unify: merge the GitHub line into Gitea, settled against real service contracts #6
+122
-28
@@ -1,38 +1,64 @@
|
||||
# =============================================================================
|
||||
# 0pt web console -- example environment
|
||||
# 0pt (edge plane) -- environment inventory / example environment
|
||||
# =============================================================================
|
||||
# Copy to `.env` (gitignored) and fill in real values. Every key below is
|
||||
# actually referenced by the code (derived from `process.env.*` usage); nothing
|
||||
# here is invented. All secrets are placeholders -- do NOT commit real values.
|
||||
# Copy to `.env` (gitignored) and fill in real values. Never commit real values.
|
||||
# Vercel env for the edge app; VPS .env (git-ignored) for infra/docker-compose.yml.
|
||||
# See docs/08-infrastructure.md for the canonical description of each integration.
|
||||
#
|
||||
# The app is designed to build and boot with these UNSET: lib/db.ts and
|
||||
# lib/stripe.ts are lazy + env-guarded, and the storage/payment/doc routes
|
||||
# return HTTP 501 ("not configured") until the relevant keys are provided.
|
||||
# Two provenance markers are used below and they mean different things:
|
||||
# * "wired in code today" -- read via a `process.env.*` somewhere in
|
||||
# this repo right now (grep-verified).
|
||||
# * "documented target, not yet read" -- named in docs/08-infrastructure.md /
|
||||
# docs/02-architecture.md but with no
|
||||
# `process.env.*` read yet. Filling it in
|
||||
# unblocks the integration; it does not by
|
||||
# itself change behaviour.
|
||||
#
|
||||
# The app is designed to build and boot with all of these UNSET: lib/db.ts and
|
||||
# lib/stripe.ts are lazy + env-guarded, and the storage/payment/doc routes return
|
||||
# HTTP 501 ("not configured") until the relevant keys are provided.
|
||||
|
||||
# ---- Core -------------------------------------------------------------------
|
||||
# ---------------------------------------------------------------------------
|
||||
# Core / public
|
||||
# ---------------------------------------------------------------------------
|
||||
# Public base URL of this app (used for absolute links / callbacks).
|
||||
NEXT_PUBLIC_APP_URL=http://localhost:3000
|
||||
# Documented target (docs/08); no call site found reading it in this pass.
|
||||
NEXT_PUBLIC_API_URL=https://api.0pt.app
|
||||
|
||||
# ---- Database (Postgres) ----------------------------------------------------
|
||||
# First one set wins: DATABASE_URL -> POSTGRES_URL -> POSTGRES_PRISMA_URL.
|
||||
# ---------------------------------------------------------------------------
|
||||
# Database (Postgres) -- wired in code today: lib/db.ts, app/api/health
|
||||
# ---------------------------------------------------------------------------
|
||||
# Vercel Postgres sets POSTGRES_URL / POSTGRES_PRISMA_URL automatically when the
|
||||
# integration is attached. First one set wins, in this order (lib/db.ts):
|
||||
# DATABASE_URL -> POSTGRES_URL -> POSTGRES_PRISMA_URL.
|
||||
DATABASE_URL=postgres://user:password@localhost:5432/opt
|
||||
POSTGRES_URL=
|
||||
POSTGRES_PRISMA_URL=
|
||||
|
||||
# ---- Queue / cache (Redis) --------------------------------------------------
|
||||
# ---------------------------------------------------------------------------
|
||||
# Cache / queue (Redis) -- app/api/health only checks presence; no other call
|
||||
# site found reading it in this pass (worker queue usage, if any, lives in
|
||||
# services/api, outside this repo's scope).
|
||||
# ---------------------------------------------------------------------------
|
||||
REDIS_URL=redis://localhost:6379
|
||||
|
||||
# ---- Auth -------------------------------------------------------------------
|
||||
# ---------------------------------------------------------------------------
|
||||
# Auth -- session / dev-login / service-token secrets (wired in code today)
|
||||
# ---------------------------------------------------------------------------
|
||||
# Session-signing secret (generate a long random string).
|
||||
AUTH_SECRET=change-me-long-random-string
|
||||
# Optional dev-only login shortcut key (leave unset in production).
|
||||
# AUTH_URL is documented (docs/08) but not yet read by any route in this pass.
|
||||
AUTH_URL=https://0pt.app
|
||||
# Optional dev-only login shortcut key (leave UNSET in production).
|
||||
DEV_LOGIN_KEY=
|
||||
# Encryption key for stored DB-connection grants (/api/connections/db-grant).
|
||||
GRANT_ENC_KEY=change-me-32-byte-key
|
||||
# Shared token for internal/service-to-service calls.
|
||||
# Shared token for internal/service-to-service calls; sent as X-Internal-Token
|
||||
# on every engineFetch() call (lib/engine.ts).
|
||||
INTERNAL_TOKEN=change-me-internal-token
|
||||
|
||||
# ---- Zitadel / OIDC Bearer verification (Wave 2 hardening) ------------------
|
||||
# ---------------------------------------------------------------------------
|
||||
# Zitadel / OIDC Bearer verification (Wave 2 hardening) -- wired in code today
|
||||
# ---------------------------------------------------------------------------
|
||||
# 0pt verifies inbound Bearer tokens against the fleet Zitadel IdP
|
||||
# (src/auth/zitadel.ts, wired via middleware.ts). JWKS are discovered from
|
||||
# <issuer>/.well-known/openid-configuration, falling back to <issuer>/oauth/v2/keys.
|
||||
@@ -51,30 +77,98 @@ AUTH_ENFORCE=true
|
||||
# urn:zitadel:iam:org:id -> urn:zitadel:iam:user:resourceowner:id -> tenant_id -> tenant.
|
||||
ZITADEL_TENANT_CLAIM=
|
||||
|
||||
# ---- Payments (Stripe) ------------------------------------------------------
|
||||
# ---------------------------------------------------------------------------
|
||||
# Data engine bridge -- wired in code today: lib/engine.ts
|
||||
# ---------------------------------------------------------------------------
|
||||
# When set, edge route handlers defer to the FastAPI engine (services/api) as the
|
||||
# single source of truth (orders/estimates/catalog/ai-parse). When unset, the edge
|
||||
# computes locally / falls back to an honest heuristic -- see lib/engine.ts and
|
||||
# app/api/ai/parse.
|
||||
ENGINE_URL=http://localhost:8000
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# SIAX platform clients
|
||||
# ---------------------------------------------------------------------------
|
||||
# src/clients/{cl0ud,n0d,aud0}-client.ts currently only accept an optional
|
||||
# constructor baseUrl and fall back to an in-memory mock / no-op -- none of these
|
||||
# three vars is read via process.env yet (grep-verified). Setting them does
|
||||
# nothing until those clients are wired to read them; a future pass should add
|
||||
# that. See docs/ICEBERG_WRITE_BOUNDARY.md.
|
||||
CL0UD_URL=
|
||||
N0D_URL=
|
||||
AUD0_URL=
|
||||
# ST0RE_URL is the convention name for src/clients/st0re-client.ts /
|
||||
# st0re-lakehouse-client.ts and is read by the real-infra test suite
|
||||
# (tests/p0/*.realinfra.test.ts). The lakehouse write path was live-verified
|
||||
# against ST0RE on 2026-07-13 with this set; unset, the clients fall back to
|
||||
# their deterministic in-memory mocks.
|
||||
ST0RE_URL=
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Payments (Stripe) -- wired in code today: app/api/payments/*,
|
||||
# app/api/webhooks/stripe
|
||||
# ---------------------------------------------------------------------------
|
||||
STRIPE_SECRET_KEY=sk_test_xxx
|
||||
STRIPE_WEBHOOK_SECRET=whsec_xxx
|
||||
# Documented target (docs/08); not yet read by any route in this pass.
|
||||
NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=
|
||||
|
||||
# ---- Object storage (Cloudflare R2 / S3-compatible) -------------------------
|
||||
# All three required to enable /api/uploads; otherwise it returns 501.
|
||||
# ---------------------------------------------------------------------------
|
||||
# Object storage -- Cloudflare R2 / S3-compatible
|
||||
# ---------------------------------------------------------------------------
|
||||
# R2_ENDPOINT / R2_BUCKET / R2_ACCESS_KEY_ID are read in code today; all three
|
||||
# are required to enable /api/uploads, otherwise it returns 501.
|
||||
# R2_ACCOUNT_ID and R2_SECRET_ACCESS_KEY are documented in docs/08 but were NOT
|
||||
# found via a process.env.* read in this pass -- verify before assuming the R2
|
||||
# client is fully wired.
|
||||
R2_ENDPOINT=https://<accountid>.r2.cloudflarestorage.com
|
||||
R2_BUCKET=opt-uploads
|
||||
R2_ACCESS_KEY_ID=change-me
|
||||
# Optional local blob dir fallback used when R2 is not configured.
|
||||
R2_ACCOUNT_ID=
|
||||
R2_SECRET_ACCESS_KEY=
|
||||
# Fallback local artifact store used when no object storage is configured
|
||||
# (src/adapters/local-blob-store.ts). Leave unset in production.
|
||||
OPT_LOCAL_BLOB_DIR=./.opt-blobs
|
||||
|
||||
# ---- Document intelligence (Azure) ------------------------------------------
|
||||
# Powers document extraction routes; unset => extraction "not configured".
|
||||
# ---------------------------------------------------------------------------
|
||||
# Document intelligence / OCR (Azure) -- wired in code today:
|
||||
# src/services/document-extraction-service.ts. Unset => extraction
|
||||
# "not configured".
|
||||
# ---------------------------------------------------------------------------
|
||||
DOC_INTELLIGENCE_ENDPOINT=https://<resource>.cognitiveservices.azure.com
|
||||
DOC_INTELLIGENCE_KEY=change-me
|
||||
DOC_INTELLIGENCE_API_VERSION=2024-11-30
|
||||
|
||||
# ---- Engine / integrations --------------------------------------------------
|
||||
# URL of the 0pt data engine (services/api orchestrator).
|
||||
ENGINE_URL=http://localhost:8000
|
||||
# ---------------------------------------------------------------------------
|
||||
# Customer DB-grant encryption -- wired in code today:
|
||||
# /api/connections/db-grant
|
||||
# ---------------------------------------------------------------------------
|
||||
# 32-byte key, AES-GCM. Encrypts customer-supplied read-only connection strings
|
||||
# at rest.
|
||||
GRANT_ENC_KEY=change-me-32-byte-key
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# External write-back targets
|
||||
# ---------------------------------------------------------------------------
|
||||
# Odoo base URL for the bills/write-back adapter.
|
||||
ODOO_BASE_URL=https://<your-odoo-host>
|
||||
|
||||
# ---- Test-only (tests/p0 real-infra suite; not needed to run the app) --------
|
||||
# ST0RE_URL=
|
||||
# ---------------------------------------------------------------------------
|
||||
# Email -- Resend (documented target, docs/08; no Resend call site found in
|
||||
# this pass -- treat as not-yet-implemented, not just unconfigured)
|
||||
# ---------------------------------------------------------------------------
|
||||
RESEND_API_KEY=
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Embedded analytics (documented target, docs/08; no call site found in this
|
||||
# pass)
|
||||
# ---------------------------------------------------------------------------
|
||||
METABASE_SITE_URL=
|
||||
METABASE_SECRET_KEY=
|
||||
NOCODB_BASE_URL=
|
||||
NOCODB_API_TOKEN=
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Test-only (tests/p0 real-infra suite; not needed to run the app)
|
||||
# ---------------------------------------------------------------------------
|
||||
# ST0RE_TEST_TENANT_ID=
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
name: CI
|
||||
|
||||
# Quality gate: typecheck + test on every PR and non-main push.
|
||||
# 0pt previously relied solely on the Vercel build with no pre-merge gate.
|
||||
# Build is intentionally NOT run here because it needs runtime secrets
|
||||
# (POSTGRES_URL, ENGINE_URL, STRIPE, RESEND) — Vercel owns the build; CI owns
|
||||
# the static gate.
|
||||
#
|
||||
# Updated by the GitHub<->Gitea unification merge (2026-07-28). The note that
|
||||
# used to sit here — "lint is not a step because this repo has no eslint
|
||||
# dependency or config wired" — is no longer true: the Gitea line's Wave 2
|
||||
# hardening added eslint + typescript-eslint + a flat config and repointed the
|
||||
# "lint" script at `eslint src tests`. Lint now runs, ADVISORY
|
||||
# (continue-on-error), matching .gitea/workflows/ci.yml: the v0-generated
|
||||
# legacy tree carries pre-existing lint noise, so it must not block merges.
|
||||
#
|
||||
# `typecheck` (BLOCKING) is tsc over tsconfig.check.json = src/ + tests/.
|
||||
# `typecheck:app` (ADVISORY) is the whole-repo tsc this workflow used to run as
|
||||
# its blocking step. It was green on the GitHub line alone but reports 9
|
||||
# pre-existing errors on the unified tree (app/api/0pt/* route handlers, where
|
||||
# the Wave 2 Zod schemas type fields as plain `string` while the services want
|
||||
# narrower unions). It is kept running, and kept visible, rather than deleted —
|
||||
# see package.json's "//scripts" note. Flip it back to blocking once those 9
|
||||
# are cleared.
|
||||
#
|
||||
# Python engine (services/api) is gated separately if/when a Python workflow
|
||||
# is added.
|
||||
on:
|
||||
pull_request:
|
||||
push:
|
||||
branches-ignore: [main]
|
||||
|
||||
concurrency:
|
||||
group: ci-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
gate:
|
||||
name: Typecheck + test
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '22'
|
||||
- name: Enable corepack (pnpm)
|
||||
run: corepack enable
|
||||
- name: Install (frozen lockfile)
|
||||
run: pnpm install --frozen-lockfile
|
||||
- name: Typecheck (tsc over src/ + tests/ -- blocking)
|
||||
run: pnpm run typecheck
|
||||
- name: Test (vitest -- blocking)
|
||||
run: pnpm run test
|
||||
- name: Typecheck whole repo (advisory -- 9 pre-existing app/ errors)
|
||||
continue-on-error: true
|
||||
run: pnpm run typecheck:app
|
||||
- name: Lint (eslint -- advisory; legacy tree has pre-existing noise)
|
||||
continue-on-error: true
|
||||
run: pnpm run lint
|
||||
@@ -18,6 +18,7 @@ yarn-error.log*
|
||||
|
||||
# env files
|
||||
.env*
|
||||
!.env.example
|
||||
|
||||
# vercel
|
||||
.vercel
|
||||
|
||||
+31
-3
@@ -42,9 +42,37 @@ Out of scope:
|
||||
- Automated scanning that generates excessive load against production
|
||||
systems without prior coordination.
|
||||
|
||||
Some known findings (for example authentication gaps on specific internal
|
||||
API routes) are already tracked internally and pending an intentional,
|
||||
reviewed fix; reporting them is still welcome and helps confirm priority.
|
||||
Note: `github.com/sax3l/0pt` (this checkout's `origin`) and
|
||||
`git.siax.io/sax3l/0pt` (Gitea) are two diverged remotes that share part of
|
||||
this codebase's history — see README "Known issues" for what's known and
|
||||
what isn't about the relationship between them. Which one is deployed to
|
||||
0pt.app is currently unconfirmed; if your finding is remote-specific, say
|
||||
which remote/branch you tested against.
|
||||
|
||||
## Known, already-tracked gaps
|
||||
|
||||
The following are **not** news to us — they are open, named gaps as of this
|
||||
pass, not secrets, and reporting them again mainly helps confirm priority
|
||||
rather than surfacing something new:
|
||||
|
||||
- **No authentication or tenant-isolation system exists in this repo yet.**
|
||||
The only gate in front of any route is a `DEV_LOGIN_KEY` dev-login scaffold
|
||||
(`app/api/auth/login/route.ts`) — there is no session-to-tenant binding.
|
||||
`app/api/orders/route.ts`'s `GET` handler carries the literal comment
|
||||
`// GET /api/orders — list (org scoping added with auth).`, confirming this
|
||||
directly. As a consequence, the P0 data-platform routes under `/api/0pt/*`
|
||||
(`lakehouse/mappings`, `sources/rate-policies`, `sources/[sourceId]/query`)
|
||||
and `src/services/document-capture-service.ts` accept `tenant_id`/
|
||||
`project_id` **from the client-supplied request body or query string**
|
||||
rather than from a server-bound session — a violation of this platform's
|
||||
own tenant-isolation rule (tenant_id must never be trusted from client
|
||||
input). This is an open, prioritized gap pending real auth (Phase 3,
|
||||
`docs/09-build-plan.md`), not an intentional design. Do not treat this repo
|
||||
as tenant-isolated until that lands.
|
||||
- Beyond that specific item, other authentication gaps on internal API
|
||||
routes may still exist and are tracked internally pending an intentional,
|
||||
reviewed fix; reporting any you find is still welcome and helps confirm
|
||||
priority.
|
||||
|
||||
## Disclosure
|
||||
|
||||
|
||||
+6
-3
@@ -42,10 +42,13 @@ export default function AdminPage() {
|
||||
const load = useCallback(async () => {
|
||||
setError(false);
|
||||
try {
|
||||
const [o, m] = await Promise.all([
|
||||
fetch("/api/orders", { cache: "no-store" }).then((r) => r.json()),
|
||||
fetch("/api/admin/metrics", { cache: "no-store" }).then((r) => r.json()),
|
||||
const [oRes, mRes] = await Promise.all([
|
||||
fetch("/api/orders", { cache: "no-store" }),
|
||||
fetch("/api/admin/metrics", { cache: "no-store" }),
|
||||
]);
|
||||
if (!oRes.ok || !mRes.ok) throw new Error("fetch failed");
|
||||
const [o, m] = await Promise.all([oRes.json(), mRes.json()]);
|
||||
if (!m || typeof m.total !== "number") throw new Error("bad metrics shape");
|
||||
setOrders(mergeOrders(Array.isArray(o) ? o : []) as Order[]);
|
||||
setMetrics(m);
|
||||
} catch {
|
||||
|
||||
@@ -21,7 +21,17 @@ export async function POST(request: NextRequest, { params }: { params: Promise<{
|
||||
return NextResponse.json(result, { status: 201 });
|
||||
} catch (error: unknown) {
|
||||
const message = error instanceof Error ? error.message : "Unknown error";
|
||||
return NextResponse.json({ error: message }, { status: 400 });
|
||||
if (/not configured/i.test(message)) {
|
||||
return NextResponse.json({ error: message }, { status: 501 });
|
||||
}
|
||||
if (/^Policy denied/i.test(message)) {
|
||||
return NextResponse.json({ error: message }, { status: 403 });
|
||||
}
|
||||
if (/^Policy requires approval/i.test(message)) {
|
||||
return NextResponse.json({ error: message }, { status: 409 });
|
||||
}
|
||||
const status = /not found/i.test(message) ? 404 : 400;
|
||||
return NextResponse.json({ error: message }, { status });
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { DatasetIcebergMappingService } from "@/src/services/dataset-iceberg-mapping-service";
|
||||
|
||||
const mappingService = new DatasetIcebergMappingService();
|
||||
import { mappingService } from "@/src/services/lakehouse-mapping-registry";
|
||||
|
||||
export async function GET(_request: Request, { params }: { params: Promise<{ mappingId: string }> }) {
|
||||
try {
|
||||
|
||||
@@ -1,11 +1,18 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { parseBody, requestIcebergWriteSchema } from "@/src/validation/0pt-schemas";
|
||||
import { IcebergWriteService } from "@/src/services/iceberg-write-service";
|
||||
|
||||
const writeService = new IcebergWriteService();
|
||||
import { writeService } from "@/src/services/lakehouse-mapping-registry";
|
||||
|
||||
// Registers a new Iceberg snapshot (a write) through ST0RE's table registry
|
||||
// for an already-mapped dataset. See docs/ICEBERG_WRITE_BOUNDARY.md.
|
||||
//
|
||||
// `writeService` is the SHARED instance from
|
||||
// src/services/lakehouse-mapping-registry.ts -- this route used to construct
|
||||
// its own `new IcebergWriteService()`, which held a private in-memory mapping
|
||||
// registry, so a mapping created via POST /lakehouse/mappings was never
|
||||
// visible here and every write failed with "mapping not found".
|
||||
//
|
||||
// The body is validated against requestIcebergWriteSchema before it reaches
|
||||
// the service (Wave 2 hardening).
|
||||
export async function POST(request: NextRequest, { params }: { params: Promise<{ mappingId: string }> }) {
|
||||
try {
|
||||
const { mappingId } = await params;
|
||||
|
||||
@@ -1,20 +1,25 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { parseBody, mapDatasetToIcebergTableSchema } from "@/src/validation/0pt-schemas";
|
||||
import { IcebergWriteService } from "@/src/services/iceberg-write-service";
|
||||
import { DatasetIcebergMappingService } from "@/src/services/dataset-iceberg-mapping-service";
|
||||
import { mappingService, writeService } from "@/src/services/lakehouse-mapping-registry";
|
||||
|
||||
// Shared instances so a mapping created via POST is visible to a later GET
|
||||
// within the same server process, matching the in-memory-per-module
|
||||
// convention already used by app/api/0pt/datasets and app/api/0pt/quality
|
||||
// (Postgres persistence exists in sql/ but is not wired into route handlers
|
||||
// in this pass -- same limitation those routes already have).
|
||||
const mappingService = new DatasetIcebergMappingService();
|
||||
const writeService = new IcebergWriteService({ mappingService });
|
||||
// Shared instances come from src/services/lakehouse-mapping-registry.ts so a
|
||||
// mapping created via POST is visible to a later GET, AND to the sibling
|
||||
// /{mappingId}/writes route, within the same server process. (Each route file
|
||||
// previously constructed its own DatasetIcebergMappingService/
|
||||
// IcebergWriteService, so a mapping created here was invisible to the writes
|
||||
// route -- every write failed with "mapping not found".) This still matches the
|
||||
// in-memory-per-module convention app/api/0pt/datasets and app/api/0pt/quality
|
||||
// use; Postgres persistence exists in sql/ but is not wired into route handlers
|
||||
// in this pass -- same limitation those routes already have.
|
||||
|
||||
// POST registers a NEW Iceberg table in ST0RE's table registry (via
|
||||
// IcebergWriteService.mapDatasetToIcebergTable) and records the
|
||||
// dataset_iceberg_mapping row that points at it -- this is 0pt's write-path
|
||||
// entrypoint, see docs/ICEBERG_WRITE_BOUNDARY.md.
|
||||
//
|
||||
// The body is validated against mapDatasetToIcebergTableSchema BEFORE it
|
||||
// reaches the service (Wave 2 hardening): an unvalidated request body used to
|
||||
// be passed straight into the capability call.
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const __raw = await request.json();
|
||||
|
||||
@@ -10,8 +10,13 @@
|
||||
* is not shared across route modules yet — see the "Singleton note" in
|
||||
* src/services/document-capture-service.ts for prior art on this same repo
|
||||
* limitation). A source registered via POST /api/0pt/sources will not be
|
||||
* resolvable here until SourceService is backed by shared persistence
|
||||
* (sql/002_p0_dataset_quality.sql already defines `opt_sources` for that).
|
||||
* resolvable here until SourceService is backed by shared persistence.
|
||||
* Correction: this comment previously claimed `sql/002_p0_dataset_quality.sql`
|
||||
* already defined an `opt_sources` table for that. That file does not exist
|
||||
* and never has (git log --all: zero commits, any branch, ever). sql/ today
|
||||
* has only 001_init.sql and 004_iceberg_write_boundary.sql. The real fix —
|
||||
* backing SourceService with real persistence — is still open; no migration
|
||||
* for it exists yet.
|
||||
* Details: docs/P0_QUERY_SOURCE_FLOW.md.
|
||||
*/
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
|
||||
@@ -24,7 +24,9 @@ const DEST: [RegExp, string][] = [
|
||||
];
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
const { text } = await req.json().catch(() => ({ text: "" }));
|
||||
const parsed = await req.json().catch(() => ({ text: "" }));
|
||||
const body = parsed && typeof parsed === "object" ? parsed : { text: "" };
|
||||
const { text } = body as { text?: string };
|
||||
if (!text) return NextResponse.json({ error: { code: "bad_request", message: "text krävs" } }, { status: 400 });
|
||||
|
||||
const eng = await engineFetch("/ai/parse", { method: "POST", body: JSON.stringify({ text }) });
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { timingSafeEqual } from "node:crypto";
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { signSession, SESSION_COOKIE } from "@/lib/auth";
|
||||
|
||||
@@ -9,7 +10,13 @@ export async function POST(req: NextRequest) {
|
||||
return NextResponse.json({ error: { code: "auth_not_configured", message: "AUTH_SECRET saknas" } }, { status: 501 });
|
||||
}
|
||||
const devKey = process.env.DEV_LOGIN_KEY;
|
||||
if (!devKey || key !== devKey) {
|
||||
// Constant-time compare: a plain !== leaks the number of matching leading
|
||||
// bytes via response timing, letting an attacker recover DEV_LOGIN_KEY
|
||||
// byte-by-byte instead of it being an all-or-nothing guess.
|
||||
const keyBuf = Buffer.from(typeof key === "string" ? key : "");
|
||||
const devKeyBuf = Buffer.from(devKey ?? "");
|
||||
const keysMatch = Boolean(devKey) && keyBuf.length === devKeyBuf.length && timingSafeEqual(keyBuf, devKeyBuf);
|
||||
if (!keysMatch) {
|
||||
return NextResponse.json({ error: { code: "forbidden", message: "Dev-login kräver giltig nyckel" } }, { status: 403 });
|
||||
}
|
||||
if (!email) {
|
||||
|
||||
@@ -11,6 +11,9 @@ export async function POST(req: NextRequest) {
|
||||
} catch {
|
||||
return NextResponse.json({ error: { code: "bad_json", message: "Invalid JSON body" } }, { status: 400 });
|
||||
}
|
||||
if (!body || typeof body !== "object") {
|
||||
return NextResponse.json({ error: { code: "bad_json", message: "Invalid JSON body" } }, { status: 400 });
|
||||
}
|
||||
|
||||
// Defer to the FastAPI data engine when it's running; fall back to local math.
|
||||
const eng = await engineFetch("/estimates", { method: "POST", body: JSON.stringify(body) });
|
||||
|
||||
@@ -19,6 +19,9 @@ export async function PATCH(req: NextRequest, ctx: { params: Promise<{ id: strin
|
||||
} catch {
|
||||
return NextResponse.json({ error: { code: "bad_json", message: "Invalid JSON" } }, { status: 400 });
|
||||
}
|
||||
if (!body || typeof body !== "object") {
|
||||
return NextResponse.json({ error: { code: "bad_json", message: "Invalid JSON body" } }, { status: 400 });
|
||||
}
|
||||
const allowed = ["draft", "quoted", "deposit_pending", "in_production", "review", "revision", "accepted", "delivered"];
|
||||
if (!body.status || !allowed.includes(body.status)) {
|
||||
return NextResponse.json({ error: { code: "bad_status", message: "Ogiltig status" } }, { status: 400 });
|
||||
|
||||
@@ -9,6 +9,9 @@ export async function POST(req: NextRequest) {
|
||||
} catch {
|
||||
return NextResponse.json({ error: { code: "bad_json", message: "Invalid JSON" } }, { status: 400 });
|
||||
}
|
||||
if (!body || typeof body !== "object") {
|
||||
return NextResponse.json({ error: { code: "bad_json", message: "Invalid JSON body" } }, { status: 400 });
|
||||
}
|
||||
const flow = body.flow || "custom";
|
||||
const config = body.config || {};
|
||||
const order = await createOrder(flow, config);
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { getOrder } from "@/lib/orders-store";
|
||||
|
||||
// POST /api/payments/[order_id]/deposit
|
||||
// Returns { url } for Stripe Checkout. Returns 501 when STRIPE_SECRET_KEY is absent.
|
||||
@@ -13,19 +14,15 @@ export async function POST(
|
||||
return NextResponse.json({ error: "payment_not_configured" }, { status: 501 });
|
||||
}
|
||||
|
||||
const origin =
|
||||
request.headers.get("origin") ??
|
||||
process.env.NEXT_PUBLIC_APP_URL ??
|
||||
"http://localhost:3000";
|
||||
// Never derive from the client-supplied Origin header (SSRF + open-redirect vector) —
|
||||
// request.nextUrl.origin reflects the actual request URL, not attacker-controlled input.
|
||||
const origin = request.nextUrl.origin;
|
||||
|
||||
let depositOre = 44750;
|
||||
try {
|
||||
const orderRes = await fetch(`${origin}/api/orders/${order_id}`);
|
||||
if (orderRes.ok) {
|
||||
const order = (await orderRes.json()) as { deposit_ore?: number; total_ore?: number };
|
||||
depositOre = order.deposit_ore ?? Math.round((order.total_ore ?? 89500) / 2);
|
||||
}
|
||||
} catch {}
|
||||
const order = await getOrder(order_id);
|
||||
if (!order) {
|
||||
return NextResponse.json({ error: { code: "not_found", message: "Order saknas" } }, { status: 404 });
|
||||
}
|
||||
const depositOre = order.deposit_ore ?? Math.round((order.total_ore ?? 89500) / 2);
|
||||
|
||||
const body = new URLSearchParams({
|
||||
"payment_method_types[0]": "card",
|
||||
|
||||
@@ -7,7 +7,8 @@ export async function GET() {
|
||||
}
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
const body = await req.json().catch(() => ({}));
|
||||
const parsed = await req.json().catch(() => ({}));
|
||||
const body = parsed && typeof parsed === "object" ? parsed : {};
|
||||
if (!body.order_id) {
|
||||
return NextResponse.json({ error: { code: "bad_request", message: "order_id krävs" } }, { status: 400 });
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
// GET /api/uploads — list uploaded files. Returns 501 until storage is configured.
|
||||
export async function GET() {
|
||||
@@ -10,9 +10,10 @@ export async function GET() {
|
||||
}
|
||||
|
||||
// POST /api/uploads (docs/04) — issue a presigned R2 PUT URL. Env-guarded:
|
||||
// returns 501 until R2 storage is configured. Client then PUTs the file directly.
|
||||
export async function POST(req: NextRequest) {
|
||||
const body = await req.json().catch(() => ({}));
|
||||
// returns 501 until R2 storage is configured, and until presign generation
|
||||
// is implemented — a configured-but-unimplemented state must not report
|
||||
// success. Client then PUTs the file directly.
|
||||
export async function POST() {
|
||||
const haveR2 = process.env.R2_ACCESS_KEY_ID && process.env.R2_BUCKET && process.env.R2_ENDPOINT;
|
||||
if (!haveR2) {
|
||||
return NextResponse.json(
|
||||
@@ -20,6 +21,10 @@ export async function POST(req: NextRequest) {
|
||||
{ status: 501 },
|
||||
);
|
||||
}
|
||||
// With R2 configured: build a presigned PUT (S3-compatible) and return it.
|
||||
return NextResponse.json({ file_id: crypto.randomUUID(), put_url: null, name: body?.name ?? null });
|
||||
// TODO: presigned PUT generation not implemented yet — keep returning 501
|
||||
// instead of a fake 200/null success shape until real R2 presign wiring exists.
|
||||
return NextResponse.json(
|
||||
{ error: { code: "storage_not_configured", message: "Presignerad uppladdning är inte implementerad än" } },
|
||||
{ status: 501 },
|
||||
);
|
||||
}
|
||||
|
||||
@@ -4,14 +4,14 @@ import { engineFetch } from "@/lib/engine";
|
||||
// GET /api/vehicles?plate=XX-99-YY — RDW (NL) open vehicle data (technical/fleet
|
||||
// only, no owner PII). Defers to the engine when running; else calls RDW directly.
|
||||
export async function GET(req: NextRequest) {
|
||||
const plate = (req.nextUrl.searchParams.get("plate") ?? "").toUpperCase().replace(/[-\s]/g, "");
|
||||
const plate = (req.nextUrl.searchParams.get("plate") ?? "").toUpperCase().replace(/[-\s]/g, "").replace(/[^A-Z0-9]/g, "");
|
||||
if (!plate) return NextResponse.json({ error: { code: "bad_request", message: "plate krävs" } }, { status: 400 });
|
||||
|
||||
const eng = await engineFetch(`/vehicles/${plate}`);
|
||||
if (eng && eng.ok) return NextResponse.json(await eng.json());
|
||||
|
||||
try {
|
||||
const r = await fetch(`https://opendata.rdw.nl/resource/m9d7-ebf2.json?kenteken=${plate}`, {
|
||||
const r = await fetch(`https://opendata.rdw.nl/resource/m9d7-ebf2.json?kenteken=${encodeURIComponent(plate)}`, {
|
||||
headers: { "User-Agent": "0pt/0.1 (+https://0pt.app; SIAX)" },
|
||||
cache: "no-store",
|
||||
});
|
||||
|
||||
@@ -65,6 +65,10 @@ export default function ProductionPage() {
|
||||
}, [id]);
|
||||
|
||||
const finish = () => {
|
||||
if (timer.current) {
|
||||
clearInterval(timer.current);
|
||||
timer.current = null;
|
||||
}
|
||||
setProgress([100, 100, 100, 100, 100]);
|
||||
setMarkets([100, 100, 100, 100]);
|
||||
setConf(94);
|
||||
|
||||
+7
-3
File diff suppressed because one or more lines are too long
+122
-20
File diff suppressed because one or more lines are too long
+74
-4
File diff suppressed because one or more lines are too long
+80
-18
File diff suppressed because one or more lines are too long
+83
-39
File diff suppressed because one or more lines are too long
+166
-23
@@ -1,6 +1,25 @@
|
||||
# 06 · Data engine
|
||||
|
||||
The engine turns sources into delivered, provenance-tagged data. It is the legal motor — the whole product positioning depends on it. Build on existing `src/workers/` (`adaptive_router`, `browser_worker`, `ocr_worker`, `db`) but enforce the sourcing boundary below.
|
||||
The engine turns sources into delivered, provenance-tagged data. It is the legal motor — the whole product positioning depends on it. The real code lives in `services/api/` (FastAPI orchestrator + workers), **not** at the `src/workers/` path this doc used to point to — the "Pipeline stages" section below states plainly, stage by stage, what's built vs. still spec.
|
||||
|
||||
> ### Known issue — two diverged git remotes for this repo (unresolved, Simon's call)
|
||||
> This doc describes the compliant-only sourcing chain as *the law*. That law was briefly violated on one
|
||||
> of this repo's two remotes, so anyone reading this doc needs to know both exist:
|
||||
> - `github.com/sax3l/0pt` (this session's `origin`) — the remote this documentation pass was verified against.
|
||||
> - `git.siax.io/sax3l/0pt` (Gitea) — a **separate, diverged** remote that shares origin history with GitHub for
|
||||
> at least part of the codebase (`services/api/workers/adaptive_router.py` is byte-for-byte identical between
|
||||
> GitHub's current `main` and Gitea's post-fix PR branch, so they were once the same commit lineage).
|
||||
>
|
||||
> Gitea's `main` independently accumulated three commits on 2026-07-13 that added a real WAF-bypass /
|
||||
> proxy-rotation / fake-identity scraper stack (`services/scrapers/*`) — exactly the category of code
|
||||
> §"Prohibited" below and CLAUDE.md §1 forbid. Those commits never touched GitHub's `main`. The stack was
|
||||
> since removed on Gitea via PR #1, but:
|
||||
> - **Which remote is authoritative / deployed to `0pt.app` is unknown** — not resolved this session.
|
||||
> - **Whether the two remotes are supposed to be kept in sync is unknown** — not resolved this session.
|
||||
>
|
||||
> This pass does not resolve either question. Simon: decide which remote is canonical, confirm the other has
|
||||
> no lingering bypass code, and either merge or retire the loser before treating "the 0pt repo" as singular
|
||||
> in any future doc pass.
|
||||
|
||||
## Sourcing chain (strict priority — this is the law)
|
||||
|
||||
@@ -11,10 +30,25 @@ For each field × market, acquire in this order; stop at the first that works:
|
||||
3. **Licensed partner data** — contractually obtained.
|
||||
4. **Otherwise → "not available / licensed only"** — delivered honestly as level 0. **Never guessed.**
|
||||
|
||||
**Current implementation covers tier 1 only.** All five working connectors in `services/api/sources/connectors.py`
|
||||
(`gleif_by_lei`, `brreg_by_orgnr`, `companies_house_by_number`, `prh_by_businessid`, `cvr_by_number`) call
|
||||
official JSON APIs over `httpx`, nothing else. There is no HTML-scraping/parsing library anywhere in
|
||||
`services/api` (no `bs4`/`lxml`/`selectolax`, no `playwright`, no `scrapy`/`crawlee` — checked against
|
||||
`requirements.txt` and the source tree), so tier 2 (authorized public web) has no code path yet. Tier 3
|
||||
(licensed partner) also has no connector — `sources.yaml`'s `bolagsverket` entry is `access: licensed` with
|
||||
no matching function in `connectors.py`; it correctly falls through to level 0 today. Both tiers remain
|
||||
target design, not built.
|
||||
|
||||
### Prohibited (do not build, keep, or extend)
|
||||
- WAF/bot-detection bypass — **including FlareSolverr**, "stealth"/patched browsers, undetected-* used to defeat detection.
|
||||
- Proxy/fingerprint rotation to evade bans; scraping behind login walls; automated fake-account creation (Apollo etc.).
|
||||
- **Reconciliation:** if `browser_worker.py` has an `HTTP → FlareSolverr → Playwright` chain, **drop the FlareSolverr stage** and keep only: polite HTTP fetch (identifies itself, obeys robots + rate limits) → optional Playwright for genuinely public JS-rendered pages (same politeness). The `adaptive_router` then chooses among **compliant** methods only (API > bulk > authorized fetch), not bypass tiers.
|
||||
- **Reconciliation note (stale — kept for history):** this section used to say "if `browser_worker.py` has an
|
||||
`HTTP → FlareSolverr → Playwright` chain, drop the FlareSolverr stage." **`browser_worker.py` does not exist
|
||||
anywhere in this repository** (verified this pass — no file of that name on GitHub's `main`). There is
|
||||
nothing to reconcile in the current Python engine. The bypass code that *did* exist, briefly, lived in
|
||||
`services/scrapers/*` on the Gitea remote only (see the Known Issue callout above) and has since been
|
||||
removed there via PR #1. `adaptive_router.py` (below) has never contained a bypass tier on either remote —
|
||||
it chooses among **compliant** methods only (API > bulk > authorized fetch > licensed), by design.
|
||||
|
||||
## Pipeline stages (per job)
|
||||
|
||||
@@ -22,19 +56,93 @@ For each field × market, acquire in this order; stop at the first that works:
|
||||
sourcing → extraction/OCR → structuring → enrichment/fusion → QA
|
||||
```
|
||||
|
||||
1. **Sourcing** — `adaptive_router` picks the compliant method per source; "source-racing" = query several *authorized* sources and take the fastest/freshest. Writes raw payloads + which source answered.
|
||||
2. **Extraction / OCR** — API JSON parsed directly; documents (PDF/HTML/images) via **Unstructured** + OCR cascade (PaddleOCR → Tesseract → LLM fallback) in `ocr_worker`. Output: candidate fields.
|
||||
3. **Structuring** — NER + entity resolution (spaCy / transformers, sv/no/da/fi/de/fr), normalize to schema, link entities across markets via **LEI** (GLEIF golden key). Dedup with **RapidFuzz**.
|
||||
4. **Enrichment / fusion** — combine fields from multiple sources; compute **multi-source agreement** → confidence + level; append optional enrichment (NACE/SNI, sanctions/PEP flag from official lists, website/tech).
|
||||
5. **QA** — quality checks (**Great Expectations** or equivalent, run inside the worker): validity (format/range), completeness, freshness, uniqueness (post-dedup), corroboration. Drop rows below the order's `confidence_target` (deliver fewer, never fabricate). Emit the quality report stored on `deliveries`.
|
||||
The stage names below are the target architecture. `services/api/workers/pipeline.py::run_job` is the one
|
||||
function that actually runs today, and it implements a much smaller slice of this than the stage list
|
||||
implies — see the "built vs. not built" status called out under each stage below.
|
||||
|
||||
Each stage updates `jobs` (`stage`, `pct`, `metrics` incl. per-market progress, running counts, climbing confidence) so the production tracker / SSE can render it live.
|
||||
1. **Sourcing** — `adaptive_router.plan_for_market(market)` returns a hardcoded, ordered list of compliant
|
||||
`source_id`s per market (see table below); `pipeline.py` tries each in order for a given key and **stops at
|
||||
the first one that returns a result** (`break` after first hit). This is sequential fallback, not
|
||||
concurrent racing — the phrase "source-racing = query several authorized sources and take the
|
||||
fastest/freshest" describes a target behavior that isn't implemented; today only one source is ever queried
|
||||
per key unless the first fails. Writes raw payload fields directly into the record dict (no separate
|
||||
raw-payload store).
|
||||
2. **Extraction / OCR — not built.** There is no `ocr_worker`, no `unstructured`, no `paddleocr`/`pytesseract`
|
||||
anywhere in this repo (checked `services/api/requirements.txt` and the full source tree — none present).
|
||||
"Extraction" today is just each connector in `connectors.py` parsing the JSON response of its own API call
|
||||
into a `CompanyResult`. Document/PDF/image ingestion and the OCR cascade described here are spec only.
|
||||
3. **Structuring — partially built.** `services/api/workers/resolve.py::resolve()` does real, deterministic
|
||||
entity resolution: block by `(market, name[:1].upper())`, then `rapidfuzz.fuzz.token_sort_ratio(...) >= 92`
|
||||
to merge duplicates, bumping `confidence` by +0.1 per corroborating match (capped 0.99) and incrementing
|
||||
`agreed_sources`. That part is real and unit-testable. What's **not** built: no spaCy/transformers, no NER,
|
||||
no multilingual normalization (`sv/no/da/fi/de/fr` from the original text), and no explicit LEI-based
|
||||
cross-market entity linking — matching is name-string-similarity only, within the same market. `spacy` and
|
||||
`transformers` are not in `requirements.txt`.
|
||||
4. **Enrichment / fusion — partially built, not fully wired into the job.** The confidence/agreement bump
|
||||
described above happens inside `resolve()`. Separately, `opensanctions_screen()` (sanctions/PEP) and
|
||||
`rdw_vehicle()` (NL vehicle data) are real, working connectors in `connectors.py` — but `pipeline.py` never
|
||||
imports or calls either one. They're only reachable as their own standalone endpoints
|
||||
(`GET /screen`, `GET /vehicles/{plate}` in `orchestrator/main.py`), not as an automatic enrichment step on
|
||||
an order's records. NACE/SNI classification and "website/tech" enrichment have no code anywhere.
|
||||
5. **QA — not built beyond a single threshold filter.** The entire QA stage in `pipeline.py` is:
|
||||
`delivered = [r for r in deduped if r["confidence"] >= threshold]`. That's real and does drop
|
||||
below-threshold rows (deliver fewer, never fabricate — that principle holds). But there is no
|
||||
Great Expectations (not in `requirements.txt`, not imported anywhere), no separate validity/format,
|
||||
completeness, freshness, or post-dedup-uniqueness checks beyond the confidence number already computed in
|
||||
structuring, and no quality-report object emitted or stored anywhere — `deliveries` (the SQL table defined
|
||||
in `sql/001_init.sql`) is never written to by this service. This mirrors a confirmed, broader finding this
|
||||
session: 0pt's data-quality/QA layer was at one point documented elsewhere (TypeScript side,
|
||||
`src/services/quality-check-service.ts` etc.) as if built and tested, but those files **do not exist** in
|
||||
this repo's history at all (zero commits, any branch — see `docs/07-dependencies.md` note). `docs/ICEBERG_WRITE_BOUNDARY.md`,
|
||||
`docs/11-lakehouse-write-plan.md`, and `docs/P0_QUERY_SOURCE_FLOW.md` have all since been corrected — each
|
||||
now carries its own explicit "fabricated, not built" callout rather than asserting those files as real —
|
||||
and `docs/P0_DATASET_QUALITY_FLOW.md` documents this gap as target-spec-only. The Python engine
|
||||
independently confirms the same gap: **no real quality-check enforcement exists in this codebase today**,
|
||||
in either language.
|
||||
|
||||
**"Each stage updates `jobs` ... so the production tracker / SSE can render it live" is not what happens.**
|
||||
`run_job` runs synchronously start-to-finish and returns one final dict (`stage: "qa", pct: 100, state: "done",
|
||||
metrics, records`). `orchestrator/main.py`'s `POST /orders/{oid}/run` awaits the whole thing and stores that one
|
||||
result in an in-memory `_JOBS` dict; `GET /orders/{oid}/status` just returns whatever's there, or a static
|
||||
`{"stage": "queued", "pct": 0, "state": "queued"}` placeholder before it's run. There is no per-stage
|
||||
incremental progress, no `pct` that climbs, and **no SSE endpoint exists anywhere in `orchestrator/main.py`**
|
||||
(grepped — none). Live progress rendering is target design, not current behavior.
|
||||
|
||||
### `adaptive_router` — actual market coverage (verified against `services/api/workers/adaptive_router.py`)
|
||||
|
||||
`MARKET_SOURCES` currently has real entries for exactly five markets, each a short compliant list — not the
|
||||
"elaborate multi-source lists" an earlier version of this router may have implied:
|
||||
|
||||
| Market | Ordered plan | Note |
|
||||
|---|---|---|
|
||||
| NO | `brreg`, `gleif` | |
|
||||
| GB | `companies_house`, `gleif` | |
|
||||
| FI | `prh`, `gleif` | |
|
||||
| DK | `cvr`, `gleif` | |
|
||||
| SE | `gleif` only | Bolagsverket bulk is licensed (see above); SE company core relies on GLEIF + a not-yet-built licensed/partner route |
|
||||
| anything else | `["gleif"]` | fallback in `plan_for_market()` |
|
||||
|
||||
`ACCESS_RANK` (`api=0, bulk=1, authorized_web=2, licensed=3`) is defined in the same file but is **not
|
||||
actually used** by `plan_for_market()` to sort anything — the lists above are hand-ordered constants already
|
||||
in the desired priority, and the rank dict is currently dead code (documentation-as-code, not logic).
|
||||
|
||||
## Confidence & provenance scoring
|
||||
|
||||
- Per field, write a `bridge_provenance` row: `source_id`, `freshness`, `confidence` (0–1), `level` (0–3), `agreed_sources`.
|
||||
- Per field, `connectors.py`'s `Provenance` dataclass carries: `field_name`, `source_id`, `confidence` (0–1),
|
||||
`level` (0–3), `freshness`. **`agreed_sources` is not a field on `Provenance`** — it's tracked separately, at
|
||||
the merged-record level, by `resolve()` (`match["agreed_sources"] = ... + 1`). If a doc or downstream
|
||||
consumer expects `agreed_sources` inside each `bridge_provenance` row, that's a mismatch to reconcile against
|
||||
the actual dataclass shape, not a fact to assume.
|
||||
- Level: 0 = unavailable/licensed; 1 = single source; 2 = partial corroboration; 3 = ≥2 independent sources agree.
|
||||
- `est_confidence` on the order = aggregate target; delivered `avg_confidence` = actual.
|
||||
- `est_confidence` on the order = aggregate target (computed in `orchestrator/main.py::compute_estimate`);
|
||||
delivered `avg_confidence` = actual, computed in `pipeline.py` as the mean confidence of delivered rows.
|
||||
- **None of this is persisted to Postgres by the current service.** `sql/001_init.sql` defines the
|
||||
`bridge_provenance` table (plus `dim_company`, `dim_source`, `fact_financials`, `deliveries`, etc.), and
|
||||
`asyncpg` is a listed dependency — but nothing in `services/api` actually calls `asyncpg` or issues a query.
|
||||
`DATABASE_URL` is read exactly once, in `orchestrator/main.py`'s `/health` handler, purely to report a
|
||||
boolean (`"db": bool(os.getenv("DATABASE_URL"))`). `orchestrator/main.py` stores orders and jobs in
|
||||
in-memory dicts (`_ORDERS`, `_JOBS`) that reset on every restart. The schema exists; the wiring from
|
||||
pipeline output → Postgres rows does not yet.
|
||||
|
||||
### Network-layer provenance: `1p` (not yet in use)
|
||||
|
||||
@@ -69,7 +177,10 @@ provenance 0pt writes. Adopting it is a later, separate step.
|
||||
|
||||
## `sources.yaml` (machine-readable registry)
|
||||
|
||||
Single registry that drives the router, the `/sources` API, and the public sourcing-map page. Schema per entry:
|
||||
Single registry that drives the router, the `/sources` API, and the (still-to-be-built) public sourcing-map
|
||||
page. `services/api/sources/sources.yaml` currently has **8 entries**: `gleif`, `brreg`, `companies_house`,
|
||||
`prh`, `cvr`, `bolagsverket`, `rdw`, `opensanctions`. Schema per entry (as actually used, confirmed against the
|
||||
file — no `entities`/`fields` mismatch found):
|
||||
|
||||
```yaml
|
||||
- source_id: gleif
|
||||
@@ -79,23 +190,55 @@ Single registry that drives the router, the `/sources` API, and the public sourc
|
||||
cadence: daily
|
||||
licence: "open (CC0) — VERIFY current terms"
|
||||
entities: [company]
|
||||
fields: [lei, legal_name, address]
|
||||
fields: [lei, legal_name, address, status]
|
||||
base_url: https://api.gleif.org
|
||||
robots_ok: true # for authorized_web only; must be honored
|
||||
rate_limit: "per provider terms"
|
||||
notes: "cross-border key"
|
||||
```
|
||||
|
||||
### Starter set (VERIFY current access/licence per source before relying — terms change)
|
||||
- **GLEIF / LEI** — typically open; cross-border key. *(verify)*
|
||||
- **Brønnøysund (Brreg, NO)** — typically open API. *(verify)*
|
||||
- **Companies House (UK)** — free API (key required). *(verify)*
|
||||
- **CVR / Virk (DK)** — API access with terms. *(verify)*
|
||||
- **PRH (FI)** — varies. *(verify)*
|
||||
- **Bolagsverket (SE)** — more restricted for bulk; plan licensed/partner route. *(verify)*
|
||||
- Vehicle: **RDW (NL)** open-ish, **Traficom (FI)**, **Transportstyrelsen (SE)**, **DVLA (UK)** — *(verify each; vehicle/PII rules differ)*
|
||||
`orchestrator/main.py` loads this file once at import time (`yaml.safe_load(...)`) and serves it through
|
||||
`GET /sources` (id/name/market/access/licence/cadence only) and `GET /sources/{market}`. It is genuinely the
|
||||
live registry behind those two endpoints — that part of the doc's original claim holds.
|
||||
|
||||
> Do not hardcode access terms as fact. When building each connector, confirm the current API/licence/robots status and record it in `sources.yaml`. If unclear or disallowed for bulk, route to licensed/partner or mark fields level 0.
|
||||
### Starter set (VERIFY current access/licence per source before relying — terms change)
|
||||
- **GLEIF / LEI** — typically open; cross-border key. Connector: `gleif_by_lei` — real, working.
|
||||
- **Brønnøysund (Brreg, NO)** — typically open API. Connector: `brreg_by_orgnr` — real, working.
|
||||
- **Companies House (UK)** — free API (key required, `COMPANIES_HOUSE_API_KEY`). Connector:
|
||||
`companies_house_by_number` — real; degrades honestly to level-0 unavailable if the key is unset (does not
|
||||
fabricate).
|
||||
- **PRH (FI)** — Connector: `prh_by_businessid` — real, working.
|
||||
- **CVR / Virk (DK)** — connector actually calls `cvrapi.dk` (a third-party aggregator), **not** Virk's own API
|
||||
directly, despite the registry entry's `base_url: https://datacvr.virk.dk`. `sources.yaml`'s `base_url` for
|
||||
`cvr` does not match what `connectors.py::cvr_by_number` actually calls — flag for reconciliation (either
|
||||
update `base_url` to `cvrapi.dk` or switch the connector to call Virk directly; not resolved this pass).
|
||||
- **Bolagsverket (SE)** — restricted for bulk; `sources.yaml` marks it `access: licensed`; **no connector
|
||||
exists** for it in `connectors.py`. Consistent with the doc's own "plan licensed/partner route" framing —
|
||||
not a false claim, just confirming it's still unbuilt.
|
||||
- **RDW (NL)** vehicle data — open, Socrata-backed. Connector: `rdw_vehicle` — real, working, but **not called
|
||||
by the job pipeline** (only reachable via `GET /vehicles/{plate}`).
|
||||
- **OpenSanctions** — global sanctions/PEP screening. Connector: `opensanctions_screen` — real, working, same
|
||||
caveat: reachable only via `GET /screen`, not part of `run_job`.
|
||||
- Vehicle beyond RDW (**Traficom FI**, **Transportstyrelsen SE**, **DVLA UK**) — no connectors exist yet;
|
||||
*(verify each before building; vehicle/PII rules differ)*.
|
||||
|
||||
> Do not hardcode access terms as fact. When building each connector, confirm the current API/licence/robots
|
||||
> status and record it in `sources.yaml`. If unclear or disallowed for bulk, route to licensed/partner or mark
|
||||
> fields level 0.
|
||||
|
||||
## Structured financials (XBRL) — real but unwired
|
||||
|
||||
`services/api/sources/financials.py::companies_house_filings()` is a real, working function: given a
|
||||
Companies House number and `COMPANIES_HOUSE_API_KEY`, it fetches the accounts filing history and returns up to
|
||||
10 filings. It is **not imported or called anywhere else in the codebase** (grepped `services/api` — only
|
||||
`financials.py` itself references the function name). The file's closing comment describes a further XBRL
|
||||
extraction step ("with `arelle` installed, download each accounts filing's iXBRL document and pull tagged
|
||||
facts...") that has no code at all — `arelle` is not in `requirements.txt`. Treat the whole file as a real but
|
||||
disconnected building block, not a wired pipeline stage.
|
||||
|
||||
## Libraries used here
|
||||
Crawlee or Scrapy (orchestration of **authorized** fetches) · Playwright (public JS pages, politely) · Unstructured (document parsing) · PaddleOCR/Tesseract (OCR) · spaCy / HF transformers (NER, multilingual) · Polars (fast tabular) · RapidFuzz (dedup/matching) · Great Expectations (quality) · dbt (optional transform layer). Versions/install: `docs/07-dependencies.md`.
|
||||
|
||||
Target list only — see `docs/07-dependencies.md` for what's actually installed today vs. still to be added,
|
||||
with an explicit install-status callout per package. As of this pass, the *only* Python packages installed for
|
||||
this engine are `fastapi`, `uvicorn`, `pydantic`, `httpx`, `asyncpg` (unused), `python-dotenv`, `pyyaml`,
|
||||
`rapidfuzz`, `tenacity` — i.e. the API-only tier 1 sourcing + structuring-by-fuzzy-match slice described above,
|
||||
nothing from the extraction/OCR/NER/quality layers this section used to list as if already in place.
|
||||
|
||||
+57
-43
File diff suppressed because one or more lines are too long
+230
-70
@@ -1,118 +1,278 @@
|
||||
# 08 · Infrastructure
|
||||
|
||||
## Repo structure (monorepo)
|
||||
> Verified against actual repo state 2026-07-19 (branch `main`, plus `.env.example` read from
|
||||
> `feature/0pt-env-example`). Where this doc previously described a target that doesn't match
|
||||
> what's committed, that's called out explicitly rather than silently corrected — see the repo's
|
||||
> honesty convention in `docs/ICEBERG_WRITE_BOUNDARY.md`.
|
||||
|
||||
## Repo structure (actual, not the original `apps/web` sketch)
|
||||
|
||||
The monorepo did **not** converge on the `apps/web/` + `packages/shared/` layout this doc originally
|
||||
sketched. What's actually on `main` today:
|
||||
|
||||
```
|
||||
0pt/
|
||||
├─ CLAUDE.md
|
||||
├─ README.md · SECURITY.md
|
||||
├─ docs/ # this documentation set
|
||||
├─ apps/
|
||||
│ └─ web/ # Next.js (Vercel): marketing, catalog, portal, admin
|
||||
├─ services/
|
||||
│ └─ api/ # FastAPI orchestrator + workers (existing src/* migrates here)
|
||||
│ ├─ orchestrator/ # main.py + routers (docs/04-api.md)
|
||||
│ ├─ workers/ # adaptive_router, fetch_worker, ocr_worker, pipeline, db
|
||||
│ └─ sources/ # sources.yaml + connectors (docs/06)
|
||||
├─ packages/
|
||||
│ └─ shared/ # shared TS types (mirror API contract), design tokens
|
||||
├─ sql/ (or services/api/alembic/) # migrations (docs/03)
|
||||
├─ app/ # Next.js App Router (Vercel) — the "edge" plane, AT THE REPO ROOT
|
||||
│ ├─ api/ # route handlers: orders, auth, admin, catalog, connections,
|
||||
│ │ # vehicles, subscriptions, sources, estimates, health, uploads,
|
||||
│ │ # payments, 0pt/*, screen, webhooks, ai
|
||||
│ ├─ bestall/ katalog/ kallor/ order/ portal/ admin/ tjanster/ # pages
|
||||
├─ lib/ # edge-side helpers: db.ts, engine.ts, auth.ts, stripe.ts,
|
||||
│ │ # orders-store.ts, subscriptions-store.ts, data.ts, services.ts
|
||||
├─ src/ # SIAX-platform-facing TS layer (NOT under app/ or lib/)
|
||||
│ ├─ clients/ # cl0ud-, n0d-, aud0-, st0re-, st0re-lakehouse-client.ts
|
||||
│ ├─ services/ # dataset-, source-, source-query-, iceberg-write-,
|
||||
│ │ # document-capture-, document-extraction-, external-writeback-,
|
||||
│ │ # source-rate-policy-, dataset-iceberg-mapping-service.ts
|
||||
│ ├─ adapters/ # local-blob-store.ts, odoo-bills-adapter.ts, graph-mailbox-adapter, ...
|
||||
│ └─ types/
|
||||
├─ components/ hooks/ styles/ # design system in code (docs/05) — data-artifact.tsx,
|
||||
│ │ # provenance-badge.tsx, embed.tsx, use-reveal.ts, globals.css
|
||||
├─ packages/schemas/ # JSON Schemas for 0pt.* event/entity contracts (not a pnpm workspace
|
||||
│ │ # package today — pnpm-workspace.yaml has no `packages:` list)
|
||||
├─ services/api/ # FastAPI orchestrator + workers (the "engine" plane, on a VPS)
|
||||
│ ├─ orchestrator/main.py
|
||||
│ ├─ workers/ # adaptive_router.py, pipeline.py, resolve.py, queue.py, run.py
|
||||
│ ├─ sources/ # sources.yaml + connectors.py (docs/06)
|
||||
│ └─ Dockerfile · requirements.txt
|
||||
├─ sql/ # migrations — see "Schema state" below
|
||||
├─ infra/
|
||||
│ ├─ docker-compose.yml # VPS always-on services
|
||||
│ └─ Caddyfile # reverse proxy + TLS
|
||||
└─ .github/workflows/ # CI/CD
|
||||
│ ├─ docker-compose.yml # real, committed (not a sketch — see below)
|
||||
│ └─ Caddyfile # real, committed
|
||||
├─ tests/p0/ # vitest, TS-side (services/clients/adapters)
|
||||
└─ (no .github/workflows/ directory exists — see "CI/CD" below)
|
||||
```
|
||||
|
||||
**Known open question (not resolved this pass, Simon's call):** `CLAUDE.md` and `README.md` both
|
||||
now note that `github.com/sax3l/0pt` (this checkout's `origin`) and `git.siax.io/sax3l/0pt` (Gitea)
|
||||
are two remotes that share part of the same history but have independently diverged — Gitea's `main`
|
||||
picked up a WAF-bypass/proxy-rotation scraper stack (since removed via a Gitea PR) that never touched
|
||||
GitHub's `main`. Which remote is authoritative/deployed, and whether they should be kept in sync, is
|
||||
undecided. This doc describes what's on **this** checkout's `main` only.
|
||||
|
||||
### Schema state (sql/)
|
||||
|
||||
Only two migration files exist in the repo's history, on any branch: `sql/001_init.sql` (the core
|
||||
schema — `dim_company`, `dim_contact`, `fact_financials`, `orders`, etc., per `docs/03-data-model.md`)
|
||||
and `sql/004_iceberg_write_boundary.sql` (`opt_dataset_iceberg_mappings` + source-rate-policy tables,
|
||||
per `docs/ICEBERG_WRITE_BOUNDARY.md`). **There is no `sql/002_*` or `sql/003_*` anywhere in this
|
||||
repo's git history** (`git log --all` for those paths returns zero commits) — despite
|
||||
`docs/ICEBERG_WRITE_BOUNDARY.md`, `docs/11-lakehouse-write-plan.md`, and `docs/P0_QUERY_SOURCE_FLOW.md`
|
||||
citing `sql/002_p0_dataset_quality.sql` and a `sql/003_*` as if they were already-applied migrations.
|
||||
They are not real. See "Security & compliance" below for what this means for QA/quality-check claims.
|
||||
|
||||
## Hosting topology
|
||||
|
||||
- **Vercel** — `apps/web` → `0pt.app`. Free Hobby until paying customers.
|
||||
- **One VPS** (Hetzner ~€5/mo) — `docker-compose`: FastAPI, workers, NocoDB, Metabase, Postgres (or Neon), Redis (if Celery), Caddy. Caddy terminates TLS and proxies `api.0pt.app`, `data.0pt.app` (NocoDB), `dash.0pt.app` (Metabase).
|
||||
- **Cloudflare R2** — files.
|
||||
- **Postgres** — on VPS (`pgvector/pgvector:pg16`) or **Neon** managed.
|
||||
- **Vercel** — `app/` (this repo's root, not a separate `apps/web`) → `0pt.app`. **Verified this pass**
|
||||
(network check performed): `https://0pt.app` returns HTTP 200, serves a Next.js/Turbopack app titled
|
||||
"0pt — your data" with SIAX branding, and `GET https://0pt.app/api/health` returns
|
||||
`{"ok":true,"service":"0pt-web","db":"not_configured","queue":"not_configured",...}` — an exact shape
|
||||
match for this repo's own `app/api/health/route.ts`. So README's "Live: https://0pt.app" is confirmed
|
||||
accurate, and the live deployment confirms `DATABASE_URL`/`REDIS_URL` are **not** set in production —
|
||||
i.e. the live site is running on the in-memory order/subscription stores described throughout this
|
||||
doc, not against a real Postgres. This does not confirm which git remote/commit is deployed, or that
|
||||
every route behaves as documented — only that the deployment exists and matches this repo's shape.
|
||||
- **One VPS** (Hetzner, per `docs/02`) — `infra/docker-compose.yml` (see below) runs FastAPI, worker,
|
||||
NocoDB, Metabase, Postgres, Redis, Caddy. This compose file and its `Caddyfile` are real, committed
|
||||
files — not a sketch — but this pass found no evidence (no CI/CD, no deploy log, no accessible host)
|
||||
that they have ever actually been run against a live VPS. Treat as "written, unexecuted."
|
||||
- **Cloudflare R2** — documented target for file storage. `app/api/uploads/route.ts` checks for
|
||||
`R2_ACCESS_KEY_ID`/`R2_BUCKET`/`R2_ENDPOINT` and returns `501 storage_not_configured` when absent;
|
||||
when "present" it still returns a **hardcoded `put_url: null`** — there is no actual presigned-URL
|
||||
generation implemented yet. R2 upload is an env-guarded stub, not a working integration.
|
||||
- **Postgres** — `lib/db.ts` resolves `DATABASE_URL || POSTGRES_URL || POSTGRES_PRISMA_URL` (Vercel
|
||||
Postgres integration sets the latter two automatically) and falls back to `null` (in-memory stores)
|
||||
when none is set. This part is real and wired.
|
||||
|
||||
## docker-compose (infra/docker-compose.yml — sketch)
|
||||
## docker-compose (`infra/docker-compose.yml` — real file, reproduced here for reference)
|
||||
|
||||
```yaml
|
||||
services:
|
||||
postgres:
|
||||
image: pgvector/pgvector:pg16
|
||||
environment: { POSTGRES_USER: opt, POSTGRES_PASSWORD: ${PG_PASSWORD}, POSTGRES_DB: opt }
|
||||
volumes: ["pgdata:/var/lib/postgresql/data"]
|
||||
volumes: ["pgdata:/var/lib/postgresql/data", "../sql:/docker-entrypoint-initdb.d:ro"]
|
||||
redis:
|
||||
image: redis:7
|
||||
api:
|
||||
build: ../services/api
|
||||
command: uvicorn orchestrator.main:app --host 0.0.0.0 --port 8000
|
||||
environment: [DATABASE_URL, R2_*, STRIPE_*, RESEND_API_KEY, INTERNAL_TOKEN]
|
||||
environment: { DATABASE_URL: "postgres://opt:${PG_PASSWORD}@postgres:5432/opt", COMPANIES_HOUSE_API_KEY: "${COMPANIES_HOUSE_API_KEY:-}", INTERNAL_TOKEN: "${INTERNAL_TOKEN}" }
|
||||
depends_on: [postgres, redis]
|
||||
worker:
|
||||
build: ../services/api
|
||||
command: python -m workers.run # or celery -A workers worker
|
||||
environment: [DATABASE_URL, R2_*]
|
||||
command: python -m workers.run
|
||||
environment: { DATABASE_URL: "postgres://opt:${PG_PASSWORD}@postgres:5432/opt", COMPANIES_HOUSE_API_KEY: "${COMPANIES_HOUSE_API_KEY:-}" }
|
||||
depends_on: [postgres, redis]
|
||||
nocodb:
|
||||
image: nocodb/nocodb
|
||||
image: nocodb/nocodb:latest
|
||||
environment: { NC_DB: "pg://postgres:5432?u=opt&p=${PG_PASSWORD}&d=opt", NC_PUBLIC_URL: "https://data.0pt.app" }
|
||||
depends_on: [postgres]
|
||||
metabase:
|
||||
image: metabase/metabase
|
||||
environment: { MB_DB_TYPE: postgres, MB_DB_HOST: postgres, MB_DB_USER: opt, MB_DB_PASS: ${PG_PASSWORD}, MB_DB_DBNAME: opt }
|
||||
image: metabase/metabase:latest
|
||||
environment: { MB_DB_TYPE: postgres, MB_DB_HOST: postgres, MB_DB_PORT: "5432", MB_DB_USER: opt, MB_DB_PASS: "${PG_PASSWORD}", MB_DB_DBNAME: opt }
|
||||
depends_on: [postgres]
|
||||
caddy:
|
||||
image: caddy:2
|
||||
ports: ["80:80","443:443"]
|
||||
ports: ["80:80", "443:443"]
|
||||
volumes: ["./Caddyfile:/etc/caddy/Caddyfile", "caddydata:/data"]
|
||||
depends_on: [api, nocodb, metabase]
|
||||
volumes: { pgdata: {}, caddydata: {} }
|
||||
```
|
||||
|
||||
## Environment variables (full inventory)
|
||||
Note vs. an earlier draft of this doc: the `api`/`worker` containers here only receive
|
||||
`DATABASE_URL`, `COMPANIES_HOUSE_API_KEY`, and `INTERNAL_TOKEN` — **not** `STRIPE_*`, `RESEND_API_KEY`,
|
||||
or `R2_*`. That's correct as written: Stripe, R2, and (a documented but unbuilt) Resend integration
|
||||
are all called from `app/api/*` route handlers, which run on Vercel, not inside this compose stack.
|
||||
|
||||
**`Caddyfile` (real, committed):**
|
||||
```
|
||||
# Postgres
|
||||
DATABASE_URL=postgres://opt:***@host:5432/opt
|
||||
PG_PASSWORD=***
|
||||
# Internal auth (Next ↔ FastAPI)
|
||||
INTERNAL_TOKEN=*** # sent as X-Internal-Token
|
||||
# Auth.js
|
||||
AUTH_SECRET=***
|
||||
AUTH_URL=https://0pt.app
|
||||
# Stripe
|
||||
STRIPE_SECRET_KEY=sk_***
|
||||
STRIPE_WEBHOOK_SECRET=whsec_***
|
||||
NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=pk_***
|
||||
# Cloudflare R2 (S3-compatible)
|
||||
R2_ACCOUNT_ID=*** R2_ACCESS_KEY_ID=*** R2_SECRET_ACCESS_KEY=*** R2_BUCKET=opt-files R2_ENDPOINT=https://<acct>.r2.cloudflarestorage.com
|
||||
# Email
|
||||
RESEND_API_KEY=re_***
|
||||
# Embeds (signed URLs)
|
||||
METABASE_SITE_URL=https://dash.0pt.app METABASE_SECRET_KEY=***
|
||||
NOCODB_BASE_URL=https://data.0pt.app NOCODB_API_TOKEN=***
|
||||
# Encryption for db_grants
|
||||
GRANT_ENC_KEY=*** # 32-byte key, AES-GCM
|
||||
# App
|
||||
NEXT_PUBLIC_API_URL=https://api.0pt.app
|
||||
api.0pt.app { reverse_proxy api:8000 }
|
||||
data.0pt.app { reverse_proxy nocodb:8080 }
|
||||
dash.0pt.app { reverse_proxy metabase:3000 }
|
||||
```
|
||||
|
||||
Never hardcode. Vercel env for `apps/web`; VPS `.env` (git-ignored) for compose. Provide `.env.example` with empty values.
|
||||
## Environment variables
|
||||
|
||||
## Security & compliance (build in, not bolt on)
|
||||
**`.env.example` now exists** — added on branch `feature/0pt-env-example`
|
||||
(`github.com/sax3l/0pt/pull/3`, **not yet merged to `main`** as of this pass). It was previously
|
||||
impossible to commit: `.gitignore`'s blanket `.env*` rule silently matched `.env.example` too, so it
|
||||
was never added despite `docs/09-build-plan.md` Phase 0 requiring it since day one. The same PR adds
|
||||
`!.env.example` to `.gitignore` to fix that. README's "Env inventory: `.env.example`" link is
|
||||
therefore currently a broken/future reference on `main` until that PR merges.
|
||||
|
||||
- **Customer DB grants**: customer creates a read-only, table-scoped, time-boxed DB role; we store the connection string **AES-GCM encrypted** (`GRANT_ENC_KEY`), validate it's read-only, and **delete after the job**. IP-allowlist; prefer a replica. Log access in `audit_log`.
|
||||
- **File delivery**: short-lived **presigned R2 URLs**; never public buckets.
|
||||
- **Isolation**: API filters by `org_id`; Postgres **RLS** where practical; NocoDB/Metabase exposed only via **signed embed URLs** scoped per customer/order (no separate login surfaced).
|
||||
- **PII (contacts/UBO)**: lawful basis recorded per delivery; honor deletion; minimize retention.
|
||||
- **DPA**: ship a Data Processing Agreement; provenance log + audit log are part of the offering.
|
||||
- **Secrets**: rotate; least privilege; no secrets in client bundles (only `NEXT_PUBLIC_*`).
|
||||
The table below is grep-verified against `main` this pass, not transcribed from `.env.example`'s own
|
||||
comments — in one case (`ST0RE_URL`, see note) that turned up a discrepancy worth flagging.
|
||||
|
||||
## Embedding NocoDB / Metabase (so it feels like one app)
|
||||
- Generate a **signed embed URL** server-side (Metabase signed embedding with `METABASE_SECRET_KEY`; NocoDB shared/locked view + token) scoped to the customer's data, and render it in an iframe inside the mono chrome. The customer never sees a NocoDB/Metabase login.
|
||||
| Var | Status on `main` | Where |
|
||||
|---|---|---|
|
||||
| `DATABASE_URL` / `POSTGRES_URL` / `POSTGRES_PRISMA_URL` | **Wired** — priority-ordered fallback | `lib/db.ts` |
|
||||
| `ENGINE_URL` | **Wired** — edge defers to FastAPI engine when set, else computes locally | `lib/engine.ts` |
|
||||
| `INTERNAL_TOKEN` | **Wired** — sent as `X-Internal-Token` on every `engineFetch()` call | `lib/engine.ts` |
|
||||
| `AUTH_SECRET` | **Wired**, but only for a lightweight HMAC session scaffold — **not Auth.js**. `lib/auth.ts`'s own comment: "Production auth = Auth.js + Postgres adapter... wired once the database is provisioned" | `lib/auth.ts`, `app/api/auth/login/route.ts` |
|
||||
| `DEV_LOGIN_KEY` | **Wired** — gates the dev-only login route (403 without a match); not a real auth system | `app/api/auth/login/route.ts` |
|
||||
| `AUTH_URL` | Documented target — no read found | — |
|
||||
| `STRIPE_SECRET_KEY` | **Wired** — real Stripe Checkout session creation (test or live key both work; not test-mode-locked in code) | `app/api/payments/[order_id]/deposit/route.ts` |
|
||||
| `STRIPE_WEBHOOK_SECRET` | **Wired** — real signature verification, advances order status | `app/api/webhooks/stripe/route.ts` |
|
||||
| `NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY` | Documented target — no read found | — |
|
||||
| `R2_ACCESS_KEY_ID`, `R2_BUCKET`, `R2_ENDPOINT` | **Presence-checked only** — gates a `501` vs stub `200`; no actual R2 client/presign call exists yet | `app/api/uploads/route.ts` |
|
||||
| `R2_ACCOUNT_ID`, `R2_SECRET_ACCESS_KEY` | Documented target — no read found (even the stub above doesn't check these) | — |
|
||||
| `OPT_LOCAL_BLOB_DIR` | **Wired** — local-disk fallback artifact store, used when no object storage is configured | `src/adapters/local-blob-store.ts` |
|
||||
| `RESEND_API_KEY` | Documented target — **no Resend call site anywhere in this repo**; not "unconfigured", genuinely not implemented | — |
|
||||
| `METABASE_SITE_URL`, `METABASE_SECRET_KEY`, `NOCODB_BASE_URL`, `NOCODB_API_TOKEN` | Documented target — no read found. `components/embed.tsx` renders an iframe from a `src` prop the *caller* must supply; no server-side signed-URL generator exists to produce that `src` | — |
|
||||
| `DOC_INTELLIGENCE_ENDPOINT`, `DOC_INTELLIGENCE_KEY`, `DOC_INTELLIGENCE_API_VERSION` | **Wired** | `src/services/document-extraction-service.ts` |
|
||||
| `GRANT_ENC_KEY` | **Presence-checked only** — gates `501` vs a stub `201` that returns `{ grant_id, status: "pending" }`. No AES-GCM encryption, no read-only validation, no actual storage happens yet despite the route's own comment describing that flow | `app/api/connections/db-grant/route.ts` |
|
||||
| `NEXT_PUBLIC_APP_URL` | **Wired** — used as a fallback origin for building Stripe redirect URLs | `app/api/payments/[order_id]/deposit/route.ts` |
|
||||
| `NEXT_PUBLIC_API_URL` | Documented target — no read found | — |
|
||||
| `REDIS_URL` | **Presence-checked only**, in `/api/health` — no queue code in this repo reads it (Celery/queue usage, if any, is `services/api`'s own concern, out of this repo's TS surface) | `app/api/health/route.ts` |
|
||||
| `COMPANIES_HOUSE_API_KEY` | Real key referenced by `services/api` (Python engine, `sources.yaml`/`connectors.py`) and passed through by `infra/docker-compose.yml` — not part of the Next.js edge app's own env surface | `services/api/` |
|
||||
|
||||
## CI/CD (.github/workflows)
|
||||
- **web**: lint + typecheck + build → deploy to Vercel on push to `main` (Vercel Git integration).
|
||||
- **api**: lint (ruff) + tests (pytest) → build Docker image → deploy to VPS (SSH `docker compose pull && up -d`, or a small runner).
|
||||
- Run DB migrations as a deploy step.
|
||||
### Platform-client URLs — corrected from a stronger claim
|
||||
|
||||
## Monitoring (cheap)
|
||||
- Vercel Analytics + Speed Insights (web).
|
||||
- **Sentry** free tier (web + api).
|
||||
- Uptime ping on `/health`.
|
||||
- Worker/job health visible in admin (reads `jobs`).
|
||||
`CL0UD_URL`, `N0D_URL`, `AUD0_URL`, and **`ST0RE_URL`** are all **documented targets only — none of
|
||||
the four is read via `process.env.*` anywhere in this repo's committed code**, grep-verified this
|
||||
pass (`grep -rn "process\.env\.\(ST0RE_URL\|CL0UD_URL\|N0D_URL\|AUD0_URL\)"` returns zero matches
|
||||
outside comments and one `it.todo(...)` placeholder in `tests/p0/iceberg-write-service.test.ts`).
|
||||
|
||||
This corrects a claim that appears in `.env.example` itself (on `feature/0pt-env-example`) and was
|
||||
carried into an earlier version of this doc: that comment states "`ST0RE_URL` **IS** read
|
||||
(`src/clients/st0re-client.ts`, `src/clients/st0re-lakehouse-client.ts`)". That is not accurate as of
|
||||
this verification. Both of those client files — like `cl0ud-client.ts`, `n0d-client.ts`, and
|
||||
`aud0-client.ts` — only export a `create*Client(baseUrl?: string)` factory that falls back to an
|
||||
in-memory mock when no `baseUrl` argument is passed. Every call site in this repo (`app/api/0pt/**`
|
||||
routes, `src/services/*.ts`) either passes no `baseUrl` at all or forwards an `opts?.st0reBaseUrl`-style
|
||||
constructor option that nothing upstream ever populates from `process.env.ST0RE_URL`. This matches
|
||||
`docs/ICEBERG_WRITE_BOUNDARY.md`'s own "Verification status" section, which lists wiring
|
||||
`ST0RE_URL` → `IcebergWriteService({ st0reBaseUrl: process.env.ST0RE_URL })` as **future work**, not
|
||||
something already done.
|
||||
|
||||
**Net effect:** setting any of `CL0UD_URL`/`N0D_URL`/`AUD0_URL`/`ST0RE_URL` in a deployed environment
|
||||
today does nothing by itself. A future pass has to wire each route/service to actually read its
|
||||
corresponding env var before the value has any effect. Until then, every 0pt→platform call in this
|
||||
repo runs against the deterministic in-memory mock built into each client file — real, tested TS, but
|
||||
never exercised against a live CL0UD/N0D/AUD0/ST0RE instance from this codebase.
|
||||
|
||||
## Security & compliance — corrected against actual code, not the target design
|
||||
|
||||
The items below were previously described as already-built behavior. Grep/read-verified this pass,
|
||||
several are **env-guarded stubs that return a plausible-shaped response without doing the described
|
||||
work**. Stating this plainly, per this repo's own honesty convention:
|
||||
|
||||
- **Customer DB grants** — `app/api/connections/db-grant/route.ts` returns `501` when `GRANT_ENC_KEY`
|
||||
is unset, and a stub `201 { grant_id, status: "pending" }` when it is set. **There is no AES-GCM
|
||||
encryption, no read-only-role validation, and no persistence implemented yet** — the route's own
|
||||
comment describes the target behavior ("validate read-only, AES-GCM encrypt conn_string, store,
|
||||
audit") but the code doesn't do it. This is a real gap, not a doc typo.
|
||||
- **File delivery / presigned R2 URLs** — same pattern: `app/api/uploads/route.ts` is a `501` stub
|
||||
with a hardcoded `put_url: null`. No presigned URL is ever actually generated in this repo today.
|
||||
- **Tenant/org isolation — OPEN SECURITY GAP, not a deliberate two-tier design.** Several `app/api/0pt/*`
|
||||
routes read `tenant_id`/`project_id` directly from the request body instead of from a server-bound
|
||||
session:
|
||||
- `app/api/0pt/lakehouse/mappings/route.ts`
|
||||
- `app/api/0pt/lakehouse/mappings/[mappingId]/writes/route.ts`
|
||||
- `app/api/0pt/sources/rate-policies/route.ts`
|
||||
- `app/api/0pt/sources/[sourceId]/query/route.ts`
|
||||
- `src/services/document-capture-service.ts`
|
||||
|
||||
This is not a defensible internal-vs-external boundary — **it's because no auth/session system
|
||||
exists anywhere in this repo yet.** `app/api/orders/route.ts`'s own `GET` handler carries the
|
||||
literal comment `// org scoping added with auth` — i.e., not yet. `lib/auth.ts` is a lightweight
|
||||
HMAC session scaffold gated by a dev-only login key, unconnected to any of the `0pt/*` routes above.
|
||||
Any caller can currently claim any `tenant_id` for these endpoints. Fixing this is Phase 3 of
|
||||
`docs/09-build-plan.md` (Auth & portal shell) — it is Simon's call how that auth design binds
|
||||
`tenant_id` server-side; it is not built anywhere in this repo today.
|
||||
- **PII (contacts/UBO) / DPA** — no code found in this pass implementing lawful-basis recording,
|
||||
deletion-on-request, or a published DPA. Treat as target design, per `CLAUDE.md` §5, not shipped.
|
||||
- **Secrets rotation / least privilege** — no rotation tooling found in this repo (expected — that's
|
||||
an operational practice, not application code — but noting it's unverified either way).
|
||||
- **Quality/QA gate on delivered data** — `src/services/quality-check-service.ts`,
|
||||
`src/services/quality-report-service.ts`, `src/types/quality-check.ts`, `src/types/quality-report.ts`,
|
||||
`src/data-platform/services/catalog-service.ts`, and `sql/002_p0_dataset_quality.sql`/`sql/003_*.sql`
|
||||
were at one point referenced in `docs/ICEBERG_WRITE_BOUNDARY.md`, `docs/11-lakehouse-write-plan.md`,
|
||||
and `docs/P0_QUERY_SOURCE_FLOW.md` as if built and tested. **None of these files has ever existed in
|
||||
this repo's git history, on any branch** (`git log --all` confirms zero commits for every one of
|
||||
those paths). **All three of those docs have since been corrected** (verified this pass) — each now
|
||||
carries its own "fabricated, not built" callout and none currently asserts those files as real; this
|
||||
section restates the underlying fact because it directly bears on the "Security & compliance" claims
|
||||
below: **there is no lakehouse-side data-quality/QA enforcement built in this repo today**. (The
|
||||
Python engine's `services/api/workers/pipeline.py` does have a real, working confidence-threshold
|
||||
drop — `delivered = [r for r in deduped if r["confidence"] >= threshold]` — but that's a separate,
|
||||
narrower mechanism inside the FastAPI pipeline, not the TS/lakehouse quality-check layer those three
|
||||
docs describe.)
|
||||
|
||||
## Embedding NocoDB / Metabase
|
||||
|
||||
`components/embed.tsx` (`EmbeddedView`) is real, committed code — a sandboxed `<iframe>` that renders
|
||||
whatever `src` URL its caller passes, with a placeholder state when `src` is `null`. **What's missing:
|
||||
the server-side code that generates a signed Metabase/NocoDB embed URL from `METABASE_SECRET_KEY` /
|
||||
`NOCODB_API_TOKEN`.** No such generator was found in this pass. So the embed *shell* exists; the
|
||||
signed-URL *plumbing* that would make it show real customer data does not yet.
|
||||
|
||||
## CI/CD
|
||||
|
||||
**There is no `.github/workflows/` directory anywhere in this repo.** No lint/typecheck/build/test
|
||||
pipeline runs in CI today. On the TS side, `pnpm lint`, `pnpm typecheck`, and `pnpm test` (vitest,
|
||||
`tests/p0/*.test.ts`) exist as local scripts in `package.json`, but nothing invokes them automatically
|
||||
on push/PR. **On the Python side there is no lint/test tooling at all** — grep-verified this pass:
|
||||
`ruff` and `pytest` appear nowhere in `services/api/requirements.txt` or anywhere else in this repo
|
||||
(no `pyproject.toml`, no `pytest.ini`, no test files). `services/api/README.md`'s own "Run locally"
|
||||
section only lists `pip install -r requirements.txt` + `uvicorn`/`python -m workers.run` — no lint or
|
||||
test step. An earlier version of this doc claimed `ruff`/`pytest` "exist as local scripts" for
|
||||
`services/api`; that was unverified and is corrected here. This is a real gap against
|
||||
`docs/09-build-plan.md` Phase 0's "CI skeleton" deliverable — not yet built, not a doc omission.
|
||||
|
||||
## Monitoring
|
||||
|
||||
- **Vercel Analytics** — genuinely wired: `app/layout.tsx` imports and renders `<Analytics />` from
|
||||
`@vercel/analytics/next` (`package.json` dependency `@vercel/[email protected]`).
|
||||
- **Sentry** — not found. No `sentry` package in `package.json`, no Sentry init/config file anywhere
|
||||
in the repo. This is a documented target only, not shipped.
|
||||
- **Uptime ping on `/health`** — `app/api/health/route.ts` exists and returns `{ ok, db, queue, ts }`
|
||||
based on env presence checks; no external uptime monitor wired to it was found in this repo (that
|
||||
would live outside this codebase regardless, e.g. an external pinger — unverified either way).
|
||||
- **Worker/job health in admin** — `app/admin/jobs/page.tsx` exists as a page; this pass did not trace
|
||||
whether it reads real job state or placeholder data (out of this doc's grounding scope — flagged for
|
||||
whoever owns `docs/01-product.md`/admin-portal docs to verify).
|
||||
|
||||
+171
-1
@@ -2,28 +2,103 @@
|
||||
|
||||
Phased, in dependency order. **Finish a phase to its acceptance criteria before the next.** Each phase = small, reviewable commits. Reconcile with existing code rather than rewriting wholesale.
|
||||
|
||||
> **Status callouts added 2026-07-19.** Each phase below now carries a `Status:` line, grep/read-verified
|
||||
> against `main` this pass. These are conservative on purpose: a phase is only called **Done** when this
|
||||
> pass found real, working code satisfying its Accept criteria; anything else is **Partial** (with the
|
||||
> specific evidence and gap named) or **Not started**. No phase is upgraded to Done without a code
|
||||
> citation. Where a referenced doc (e.g. `docs/design/...`) doesn't exist, that's flagged rather than
|
||||
> silently worked around. See `docs/08-infrastructure.md` for the full env/security grounding these
|
||||
> statuses draw on.
|
||||
|
||||
## Phase 0 — Foundation & repo
|
||||
- Monorepo structure (`docs/08`). Migrate existing `src/orchestrator` + `src/workers` into `services/api`.
|
||||
- Postgres schema + migrations (`docs/03`); `pgvector` enabled. `.env.example`.
|
||||
- `docker-compose` up (postgres, redis, api, worker, nocodb, metabase, caddy). `/health` green.
|
||||
- CI skeleton (lint/typecheck/build).
|
||||
- **Accept:** `docker compose up` runs the whole stack locally; migrations apply; `/health` returns ok for db + queue.
|
||||
- **Status: Partial.**
|
||||
- Repo structure exists but diverged from the `apps/web`/`packages/shared` layout `docs/08` originally
|
||||
sketched — it settled on `app/` (Next.js, repo root), `lib/`, `src/` (platform clients/services), and
|
||||
`services/api/` (FastAPI). `docs/08-infrastructure.md` now documents the structure as-built.
|
||||
- Migration to `services/api/orchestrator` + `services/api/workers` is **done** (verified: those
|
||||
directories exist and contain `main.py`/`adaptive_router.py`/`pipeline.py`/etc.; no `src/orchestrator`
|
||||
or `src/workers` remain at the old paths).
|
||||
- Postgres schema is real: `sql/001_init.sql` (`CREATE EXTENSION vector`, `CREATE EXTENSION pgcrypto`,
|
||||
17 tables incl. `orgs`, `users`, `orders`, `jobs`, `audit_log`, `bridge_provenance`, `db_grants`,
|
||||
`payments`) + `sql/004_iceberg_write_boundary.sql`.
|
||||
**No `sql/002_*` or `sql/003_*` exists anywhere in this repo's history** — some other docs
|
||||
(`docs/ICEBERG_WRITE_BOUNDARY.md` etc.) cite a `sql/002_p0_dataset_quality.sql` that was never built;
|
||||
see `docs/08-infrastructure.md`'s "Schema state" section.
|
||||
- `.env.example` — **now exists**, on branch `feature/0pt-env-example`
|
||||
(`github.com/sax3l/0pt/pull/3`), **not yet merged to `main`**. It was blocked for the life of this
|
||||
project by `.gitignore`'s blanket `.env*` rule silently matching it too; the same PR fixes that
|
||||
with `!.env.example`. Until that PR merges, `main` still has no `.env.example`.
|
||||
- `infra/docker-compose.yml` and `infra/Caddyfile` are real, committed files (not sketches) covering
|
||||
exactly the services listed. **This pass found no evidence they've ever actually been run** — no
|
||||
CI, no deploy log, no reachable host checked. "File exists and looks correct" ≠ "verified to run";
|
||||
treat the Accept criterion ("docker compose up runs... /health returns ok") as unverified.
|
||||
- CI skeleton — **not built.** There is no `.github/workflows/` directory in this repo at all. `pnpm
|
||||
lint`/`typecheck`/`test` exist as local scripts only.
|
||||
|
||||
## Phase 1 — Design system in code
|
||||
- Tailwind + shadcn; `globals.css` (grain + reveal keyframes) and `useReveal` verbatim (`docs/05`).
|
||||
- Build **DataArtifact** primitive (table/map/schema/chart/grid) and **ProvenanceBadge** (`docs/design` prompts 5.1, 2.11).
|
||||
- **Accept:** a sample page renders mono tokens, a DataArtifact animates on scroll, reduced-motion respected, focus rings visible.
|
||||
- **Status: Partial — real components exist; scroll-motion/reduced-motion/focus-ring behavior not
|
||||
independently exercised this pass.**
|
||||
- Tailwind + shadcn/radix stack: confirmed real in `package.json` (`tailwindcss`, `@radix-ui/*`,
|
||||
`class-variance-authority`, `tailwind-merge`, `tailwindcss-animate`).
|
||||
- `hooks/use-reveal.ts`, `components/data-artifact.tsx`, `components/provenance-badge.tsx` all exist
|
||||
and are used across `app/katalog`, `app/kallor`, `app/bestall`, `app/order/[id]`, and most
|
||||
`components/sections/*` files (grep-confirmed).
|
||||
- `docs/design/0pt-v0-build-brief.md` and `docs/design/0pt-design-coverage-and-visuals.md` (the
|
||||
"prompts 5.1, 2.11" this bullet references) **do not exist anywhere in this repo** — confirmed via
|
||||
full-repo search; there is no `docs/design/` directory at all. `CLAUDE.md`'s own doc index has
|
||||
already been corrected to flag this as a gap rather than list them as real. Treat any reference to
|
||||
specific numbered "build-brief prompts" in this build plan as pointing at a doc that was never
|
||||
written — not this file's scope to author that content.
|
||||
- Reduced-motion handling, focus-ring visibility, and actual scroll-triggered animation behavior were
|
||||
not executed/verified in this pass (no browser run performed) — code presence is confirmed, runtime
|
||||
behavior is not.
|
||||
|
||||
## Phase 2 — Marketing + catalog (placeholder data)
|
||||
- Landing components top-to-bottom (build-brief 2.1–2.10): Header, Hero, Philosophy, Catalog teaser, Engine, Visualisation gallery, Coverage, Editorial, Proof, Footer.
|
||||
- Full **Catalog** page + **Dataset detail** + **Sourcing-map** page (coverage doc 5.4). Postgres full-text search.
|
||||
- All with loading/empty/error states + mobile.
|
||||
- **Accept:** marketing site + catalog browse work end-to-end on placeholder catalog rows; one continuous scroll reads well; DoD met per screen.
|
||||
- **Status: Partial.**
|
||||
- Landing section components are real: `components/sections/{hero,philosophy,gallery,editorial,
|
||||
pricing,technology,testimonials,footer,featured-products,collection}-section.tsx` all exist.
|
||||
- `app/katalog/page.tsx`, `app/katalog/[id]/page.tsx`, `app/kallor/page.tsx` all exist.
|
||||
- **Postgres full-text search was not found** — grepped for `to_tsvector`/`websearch_to_tsquery`
|
||||
across the whole repo, zero matches. Catalog browsing today reads from `lib/data.ts` placeholder
|
||||
data, not a full-text query against Postgres. This Accept criterion's "catalog browse... on
|
||||
placeholder catalog rows" half is plausible; the Postgres full-text search half is not built.
|
||||
- Loading/empty/error states + mobile + DoD-per-screen were not independently audited screen-by-screen
|
||||
this pass — `components/states.tsx` (`LoadingSkeleton`, `ErrorState`) exists and is imported widely,
|
||||
which is evidence toward this but not a full verification.
|
||||
|
||||
## Phase 3 — Auth & portal shell
|
||||
- Auth.js + Postgres adapter; sign in/up/verify/forgot. `orgs`/`users`.
|
||||
- Portal shell + Dashboard ("Mina beställningar") with empty state.
|
||||
- **Accept:** a user can sign up, land in an empty dashboard, sign out; routes protected.
|
||||
- **Status: Not done — this is the most consequential gap in the whole repo, not a minor loose end.**
|
||||
- **There is no Auth.js integration.** `lib/auth.ts` is a from-scratch, ~40-line HMAC-SHA256 session
|
||||
scaffold (Web Crypto, no dependency) whose own comment states: "Production auth = Auth.js + Postgres
|
||||
adapter + OAuth (docs/02) — wired once the database is provisioned." `app/api/auth/login/route.ts`
|
||||
is a **dev-only** login gated by a shared `DEV_LOGIN_KEY`, not sign-up/verify/forgot.
|
||||
- `orgs` and `users` tables exist in `sql/001_init.sql` (schema is ready), but nothing in the app
|
||||
reads/writes them for real session-bound identity today.
|
||||
- `app/portal/page.tsx` and sibling portal pages exist (shell is real), but routes are **not**
|
||||
protected by any real session check tied to that schema.
|
||||
- **Concretely, this means the tenant/org isolation several `0pt.*` API routes assume does not exist
|
||||
yet.** `app/api/0pt/lakehouse/mappings/route.ts`, `.../writes/route.ts`,
|
||||
`app/api/0pt/sources/rate-policies/route.ts`, `app/api/0pt/sources/[sourceId]/query/route.ts`, and
|
||||
`src/services/document-capture-service.ts` all read `tenant_id`/`project_id` straight from the
|
||||
request body — anyone can claim any tenant. `app/api/orders/route.ts`'s own `GET` handler carries
|
||||
the literal comment `// org scoping added with auth`. This is an open security gap, not a
|
||||
two-tier design choice — see `docs/08-infrastructure.md`'s "Security & compliance" section for the
|
||||
full list. **Do not build any doc or feature that assumes tenant-scoped auth already exists.**
|
||||
|
||||
## Phase 4 — Order lifecycle end-to-end (test mode)
|
||||
- **Configurator** (2.12) wired to `POST /estimates` (real estimate math in FastAPI).
|
||||
@@ -32,12 +107,53 @@ Phased, in dependency order. **Finish a phase to its acceptance criteria before
|
||||
- **Validation & delivery** (2.15): tabs render from a sample delivery; **accept** → `POST /payments/release` (test) → `DELIVERED`; **revise** leaves escrow untouched.
|
||||
- AI-assist (`POST /ai/parse`) prefilling the configurator.
|
||||
- **Accept:** a full custom order can be configured, deposit paid (test), watched, validated, accepted, and "delivered" — state machine in `docs/01` traversed; escrow split correct.
|
||||
- **Status: Partial — the payment/escrow spine is genuinely real; the SSE tracker is not.**
|
||||
- `app/api/estimates/route.ts` exists.
|
||||
- Deposit checkout is **real, working code**: `app/api/payments/[order_id]/deposit/route.ts` calls
|
||||
Stripe's Checkout Sessions API directly (not a stub) and `app/api/webhooks/stripe/route.ts` verifies
|
||||
the webhook signature and advances order status via `setStatus`.
|
||||
- `app/api/payments/[order_id]/release/route.ts` is also real: it enforces the escrow rule in code —
|
||||
balance release is rejected with `409 not_accepted` unless `order.status === "accepted"` — matching
|
||||
the "escrow split correct" accept criterion's intent.
|
||||
- **`GET /api/orders/{id}/events` (SSE) does not exist.** Only `GET`/`PATCH /api/orders/{id}` were
|
||||
found (`app/api/orders/[id]/route.ts`); no `/events` sub-route, and no `EventSource`/
|
||||
`text/event-stream`/`ReadableStream` usage anywhere in `app/` (grep-verified). If a production
|
||||
tracker is live today, it's polling `GET /api/orders/{id}`, not the SSE stream this bullet describes
|
||||
— or it hasn't been built. Either way, the SSE contract as written is not implemented.
|
||||
- `app/api/ai/parse/route.ts` is real: a genuine (non-fabricated) keyword/regex heuristic that
|
||||
prefills a config object, with a documented fallback to `engineFetch("/ai/parse", ...)` when
|
||||
`ENGINE_URL` is set. This one holds up as described.
|
||||
|
||||
## Phase 5 — Real data engine (Nordic slice)
|
||||
- Compliant connectors first: **GLEIF + Brreg + Companies House** (verify access terms; record in `sources.yaml`). Remove any FlareSolverr/bypass path (`docs/06`).
|
||||
- Pipeline stages produce real `dim_company` + `fact_financials` with `bridge_provenance`; QA threshold drops low-confidence rows.
|
||||
- Production tracker now reflects **real** job metrics.
|
||||
- **Accept:** a Nordic company dataset is produced for a real order, every field has provenance, quality report generated, level-0 fields shown honestly (not fabricated).
|
||||
- **Status: Partial.**
|
||||
- `services/api/sources/sources.yaml` and `connectors.py` are real: GLEIF, Brreg, Companies House,
|
||||
PRH, and CVR are all registered, each with an explicit `licence: "... — VERIFY"` tag rather than an
|
||||
assumed-clean claim — matches the "verify access terms" instruction.
|
||||
- `services/api/workers/adaptive_router.py`'s own comment confirms: "There are NO bypass/stealth/
|
||||
proxy-rotation tiers here, by design (CLAUDE.md §1)" — the FlareSolverr/bypass removal is done, at
|
||||
least on this repo's `main` (see `docs/08-infrastructure.md`'s "Known open question" about the
|
||||
diverged Gitea remote, which independently added such a stack on its own `main` — unresolved which
|
||||
remote is canonical).
|
||||
- `services/api/workers/pipeline.py` has a real, working confidence-threshold QA drop: `delivered =
|
||||
[r for r in deduped if r["confidence"] >= threshold]`, plus an `avg_confidence` figure in its output.
|
||||
This is a genuine, narrow QA mechanism inside the Python engine.
|
||||
- **This is not the same thing as the "quality report" / quality-check layer once described in
|
||||
`docs/ICEBERG_WRITE_BOUNDARY.md`, `docs/11-lakehouse-write-plan.md`, and
|
||||
`docs/P0_QUERY_SOURCE_FLOW.md`.** Those three docs used to cite `src/services/quality-check-service.ts`,
|
||||
`src/services/quality-report-service.ts`, `src/types/quality-{check,report}.ts`, and
|
||||
`src/data-platform/services/catalog-service.ts` as already-built and tested. **None of those files
|
||||
has ever existed in this repo's git history, on any branch** — and all three docs have since been
|
||||
corrected to say so explicitly (verified this pass), rather than repeating the original claim. So:
|
||||
the narrow Python-side confidence filter is real; the broader TS/lakehouse "quality report" this
|
||||
Accept criterion likely also intends is not built (see `docs/P0_DATASET_QUALITY_FLOW.md` for the
|
||||
honest target spec). Whether `pipeline.py`'s `avg_confidence` output satisfies "quality report
|
||||
generated" is a judgment call for whoever runs this phase — flagging rather than deciding it here.
|
||||
- Whether an actual Nordic dataset has been produced end-to-end for a real order was not verified
|
||||
this pass (would require running the stack).
|
||||
|
||||
## Phase 6 — Delivery surfaces & integrations
|
||||
- Exports: CSV / Parquet / JSON via R2 presigned URLs.
|
||||
@@ -45,11 +161,34 @@ Phased, in dependency order. **Finish a phase to its acceptance criteria before
|
||||
- Integrations: **FiveCRM push**, webhooks, Google Sheets.
|
||||
- File **uploads** (Uppy → R2) for matching/enrichment.
|
||||
- **Accept:** a delivered dataset is downloadable, viewable in embedded NocoDB + Metabase (no separate login), and pushable to FiveCRM; uploads work.
|
||||
- **Status: Not done — this phase is UI-shell-only today.**
|
||||
- CSV/Parquet/JSON exports via R2 presigned URLs: not found. `app/api/uploads/route.ts` (the closest
|
||||
R2-touching code) is a `501` stub with a hardcoded `put_url: null` — no presign logic exists yet,
|
||||
for uploads or exports.
|
||||
- `components/embed.tsx` (`EmbeddedView`) is real — a sandboxed iframe shell — but the server-side
|
||||
signed-URL generator for Metabase/NocoDB (`METABASE_SECRET_KEY`/`NOCODB_API_TOKEN`) that would feed
|
||||
it a real `src` was not found anywhere in this pass.
|
||||
- "FiveCRM" appears only as a **destination label string** in `lib/data.ts`, `lib/services.ts`,
|
||||
`app/portal/integrationer/page.tsx` (explicitly described in that file's own comment as
|
||||
"presentationella toggles" — i.e. presentational, not wired), and as one of several regex-matched
|
||||
destination names in `app/api/ai/parse/route.ts`'s heuristic. **No actual FiveCRM API push exists.**
|
||||
- `uppy` is not a dependency in `package.json` (checked directly) — the Uppy → R2 upload flow this
|
||||
bullet describes has no corresponding package installed, let alone implemented.
|
||||
|
||||
## Phase 7 — Subscriptions / feeds
|
||||
- `subscriptions`; recurring jobs (weekly/daily) delivering **deltas**; webhooks on change.
|
||||
- Freshness monitoring; Resend emails (confirmation, "din data är klar", feedback).
|
||||
- **Accept:** an order converts to a feed; a scheduled run produces a delta + fires a webhook + email.
|
||||
- **Status: Partial — data layer real, scheduling and email are not.**
|
||||
- `lib/subscriptions-store.ts` is real CRUD against the `subscriptions` table (with an in-memory
|
||||
fallback when no DB is configured) — `createSubscription`/`listSubscriptions` genuinely insert/read.
|
||||
- No recurring-job scheduler (cron, queue consumer producing deltas, etc.) was found on the TS side of
|
||||
this repo. `services/api/workers/queue.py` exists on the Python side but this pass did not trace
|
||||
whether it implements actual delta-producing scheduled runs — flagged as unverified rather than
|
||||
assumed either way.
|
||||
- **Resend is not wired at all** — grepped for `resend`/`Resend` across the whole repo, zero matches
|
||||
outside `RESEND_API_KEY` being listed as an env var. No confirmation/"din data är klar"/feedback
|
||||
email has been implemented.
|
||||
|
||||
## Phase 8 — Admin, hardening, compliance
|
||||
- Admin: order queue + scope/quote + escrow release; **source registry & freshness** monitoring; worker/job monitoring; customer + catalog management.
|
||||
@@ -57,19 +196,50 @@ Phased, in dependency order. **Finish a phase to its acceptance criteria before
|
||||
- Security pass: RLS, presigned-only files, signed embeds, secret rotation, `audit_log` everywhere; **DPA** published; legal pages.
|
||||
- Finalize all loading/empty/error states + mobile across the app.
|
||||
- **Accept:** admin can run the business; DB-grant flow works and self-revokes; security checklist passes; DoD met app-wide.
|
||||
- **Status: Partial — UI shell real, the security substance is not.**
|
||||
- Admin pages exist: `app/admin/{page,jobs/page,sources/page,customers/page,verktyg/page}.tsx`. This
|
||||
pass did not verify whether they read real backend data or placeholders.
|
||||
- `sql/001_init.sql` defines `audit_log`, `db_grants`, and `payments` tables — schema is ready.
|
||||
- **The DB-access grant flow is a stub, not a working feature.**
|
||||
`app/api/connections/db-grant/route.ts` returns `501` without `GRANT_ENC_KEY`, and with it set
|
||||
returns a hardcoded `201 { grant_id, status: "pending" }` — **no AES-GCM encryption, no read-only
|
||||
validation, and no self-revoke logic exist in code today**, despite the route's own comment
|
||||
describing that target behavior. See `docs/08-infrastructure.md`'s "Security & compliance" section.
|
||||
- RLS enforcement, presigned-only files (blocked on the Phase 6 R2 gap above), signed embeds (blocked
|
||||
on the Phase 6 NocoDB/Metabase gap above), and a published DPA were not found as implemented in this
|
||||
pass. Treat the "security checklist passes" accept criterion as not met.
|
||||
|
||||
## Phase 9 — Launch
|
||||
- Domain `0pt.app` (Vercel) + subdomains (api/data/dash via Caddy). Sentry + uptime live.
|
||||
- Soft launch: Protosell internally + a handful of existing dealer relationships.
|
||||
- **Accept:** a real external customer completes an order start→delivery in production; feedback loop running.
|
||||
- **Status: Domain is live; soft-launch/customer criterion not verified.**
|
||||
- **Verified this pass** (network check performed): `https://0pt.app` returns HTTP 200 and serves this
|
||||
repo's own Next.js app (title "0pt — your data", SIAX branding); `GET /api/health` returns
|
||||
`{"ok":true,"service":"0pt-web","db":"not_configured","queue":"not_configured",...}`, an exact shape
|
||||
match for `app/api/health/route.ts`. README's "Live: https://0pt.app" is confirmed, and the response
|
||||
confirms the live deployment has no `DATABASE_URL`/`REDIS_URL` set — see `docs/08-infrastructure.md`'s
|
||||
"Hosting topology" section. This does not confirm which git remote/commit is deployed (see the
|
||||
diverged-remotes note elsewhere in this doc), or that api/data/dash subdomains or Caddy are live —
|
||||
only the root Vercel deployment was checked.
|
||||
- **Sentry is not wired** — no `sentry` package in `package.json`, no Sentry config file anywhere in
|
||||
the repo (grep-confirmed). `@vercel/analytics` **is** genuinely wired (`app/layout.tsx` renders
|
||||
`<Analytics />`), which is a real but much smaller piece of the "Sentry + uptime live" bullet.
|
||||
- No evidence either way on the soft-launch/external-customer criterion — out of this doc's ability to
|
||||
verify from code alone.
|
||||
|
||||
---
|
||||
|
||||
## Working conventions (for Claude Code)
|
||||
- Tech docs + identifiers **English**; UI copy **Swedish**.
|
||||
- Conventional Commits; one concern per PR; keep diffs reviewable.
|
||||
- No secrets in code; update `.env.example` when adding env.
|
||||
- No secrets in code; update `.env.example` when adding env. (`.env.example` itself currently lives on
|
||||
`feature/0pt-env-example` / PR #3 — merge that first, or this instruction has nothing to update yet.)
|
||||
- Add/extend tests for engine logic (estimate math, fusion/confidence, dedup) and API contract.
|
||||
- When a source's access/licence is unclear, **verify and record in `sources.yaml`** before relying; if disallowed for bulk, route to licensed/partner or mark level 0 — never bypass, never fabricate.
|
||||
- Touch the design tokens/motion only via `docs/05`; keep red ≤ once per screen; no photography.
|
||||
- If anything here conflicts with existing code, **flag it** in the PR description and propose the reconciliation rather than guessing.
|
||||
- **Two git remotes claim to be this repo** (`github.com/sax3l/0pt` and `git.siax.io/sax3l/0pt`), and
|
||||
they have independently diverged (see `CLAUDE.md`, `README.md`). Don't assume the checkout you're in
|
||||
is the only copy, and don't silently pick one as canonical — that's Simon's decision, flag it if it
|
||||
becomes relevant to the phase you're working on.
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user