merge: unify GitHub main into Gitea main (0pt)
CI (SIAX Cloud) / quality (push) Successful in 38s
CI (SIAX Cloud) / security (push) Successful in 17s

Merges github/main (6 commits: 17-bug audit fix, CI quality gate,
.env.example + .gitignore fix, missing platform clients + registry
services, docs accuracy overhaul) into gitea/main (8 commits: Iceberg
write boundary + live ST0RE verification, lakehouse mapping routes,
Waves 1-4 foundational hardening).

16 conflicts. Both sides had independently written the four
src/clients/*.ts and the two registry services, so those are combined
rather than picked:

- st0re-client.ts: GitHub's endpoint wins on evidence. POST goes to
  /v1/st0re/artifacts/register, not /v1/st0re/artifacts -- verified in
  sax3l/st0re src/api/routes/artifacts.ts, where the bare path is a
  GET-only list route. Gitea's URL normalisation, error-body text and
  mock kept.
- n0d-client.ts: field is `status`, not `state`, with N0D's real 13-state
  union -- verified in sax3l/n0d packages/schemas/n0d.job.schema.json,
  which says explicitly not to add "succeeded". Gitea's mock echo,
  URL normalisation and error-body text kept.
- cl0ud-client.ts: Gitea's fail-closed HTTP normalisation kept (a 200
  with no `decision` reads as "deny", not as a silent allow). GitHub's
  PolicyDecision/PolicyDecisionValue naming kept; PolicyResult retained
  as an alias.
- aud0-client.ts: permissive union of both input types (optional
  payload/metadata/correlation_id), GitHub's echo return, Gitea's URL
  normalisation and error-body text, plus a JSON-parse fallback so a
  successful POST with an empty body does not throw.
- dataset-service.ts / source-service.ts: GitHub's record/DTO split and
  event naming (0pt.source_created / 0pt.create_source, which the merged
  docs already reference) plus Gitea's name validation, description /
  created_by fields and actor_id derivation. List filters are the union.
- lakehouse mapping routes: GitHub's shared lakehouse-mapping-registry
  singletons (without which every write 400'd "mapping not found") AND
  Gitea's Zod parseBody validation. Both, not either.
- src/types/source.ts, src/types/dataset.ts: unions of both vocabularies;
  GitHub's `access` legal-sourcing field kept.
- .env.example: GitHub's audited inventory plus Gitea's Zitadel /
  AUTH_ENFORCE block.
- CLAUDE.md, docs/ICEBERG_WRITE_BOUNDARY.md: GitHub's corrections kept,
  Gitea's live-verification kept and marked as superseding the
  "would 400 outright" finding (Gitea had already added the required
  X-Tenant-Id/X-Actor-Id headers).
- pnpm-lock.yaml: regenerated with pnpm 9.15.9, not merged.

Also corrects CLAUDE.md's claim that the banned services/scrapers stack
was "since removed" -- the removal PR is open, not merged, and this
branch inherits that code from Gitea main. Nothing here resurrects,
extends or re-wires any of it; services/scrapers/ is byte-identical to
Gitea main.

Verified on the merged tree: typecheck (src/ + tests/) clean;
17 test files, 121 passed, 1 skipped (the realinfra test skipping
honestly on ST0RE HTTP 401), 0 failures. Gitea main baseline was the
same 121/1; GitHub main baseline could not even `pnpm install`
("packages field missing or empty") -- Gitea's pnpm-workspace.yaml fix
resolves that. Whole-repo `typecheck:app` reports 9 errors, an identical
set to Gitea main's baseline, so it is advisory in both CI workflows
rather than deleted. Lint: 16 problems, identical to Gitea baseline.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
Claude (SIAX platform session)
2026-07-28 12:38:01 +02:00
co-authored by Claude Opus 5
58 changed files with 2785 additions and 610 deletions
@@ -162,6 +162,10 @@ export class DocumentIntelligenceAdapter {
for (let i = 0; i < maxPollAttempts; i++) {
await sleep(pollIntervalMs);
const pollRes = await fetch(operationLocation, { headers: { "Ocp-Apim-Subscription-Key": this.config.apiKey } });
if (!pollRes.ok) {
const text = await pollRes.text().catch(() => "");
throw new Error(`Document Intelligence poll request failed: ${pollRes.status} ${text.slice(0, 300)}`);
}
const json = (await pollRes.json()) as Record<string, unknown>;
if (json.status === "succeeded") {
payload = json;
+49 -21
View File
@@ -1,18 +1,28 @@
/**
* src/clients/aud0-client.ts
* ===========================
* 0pt's thin client for emitting append-only events + lineage edges to AUD0
* (the SIAX Cloud system of record). Two methods:
* 0pt's ONLY path for recording "what happened" to AUD0, the SIAX Cloud
* append-only system of record. Every mutating capability in this repo emits
* a plain event (`ingestEvent`) and, where the mutation produced or
* transformed something, a lineage edge (`ingestLineageEvent`) -- see
* docs/ICEBERG_WRITE_BOUNDARY.md's "Event names" table for the full list this
* client backs. Two endpoints:
* - ingestEvent -> POST {baseUrl}/v1/aud0/events
* - ingestLineageEvent -> POST {baseUrl}/v1/aud0/lineage/events
*
* Convention (identical to cl0ud-client.ts / n0d-client.ts / st0re-client.ts
* / st0re-lakehouse-client.ts): when no base URL is configured the client is
* a NO-OP — it does not attempt any network call. AUD0 is a best-effort,
* out-of-band audit sink for 0pt; a missing AUD0_URL (unit tests, local dev)
* must not turn every capability call into a failed fetch to `undefined`.
* When a base URL IS configured, events are POSTed as-is (the event object is
* the wire body) with `Content-Type: application/json`.
* a NO-OP -- it does not attempt any network call, it never throws, and it
* never blocks a caller. AUD0 is a best-effort, out-of-band audit sink for
* 0pt; a missing AUD0_URL (unit tests, local dev) must not turn every
* capability call into a failed fetch to `undefined`. That matches AUD0's own
* documented stance that an audit emission is a record of what already
* happened, not a gate the action waits on.
*
* HONESTY NOTE: no AUD0_URL has been available to probe in any pass so far --
* AUD0 has no live ingestion endpoint wired for 0pt yet. A real deployment
* must be pointed at via `aud0BaseUrl`/`AUD0_URL` before events emitted
* through this client are durable anywhere.
*/
export interface Aud0Event {
@@ -27,7 +37,12 @@ export interface Aud0Event {
resource_id: string;
/** Risk level L0–L5 per the SIAX Cloud risk taxonomy. */
risk_level: string;
payload: Record<string, unknown>;
/**
* Free-form event body. Optional and `unknown`-typed so every call site in
* this repo type-checks: most emit a structured `Record<string, unknown>`,
* some emit nothing at all.
*/
payload?: unknown;
created_at: string;
correlation_id?: string;
}
@@ -44,14 +59,19 @@ export interface Aud0LineageEvent {
target_id: string;
/** e.g. "produced" | "derived_from" | "stored_as". */
lineage_type: string;
metadata: Record<string, unknown>;
metadata?: unknown;
created_at: string;
correlation_id?: string;
}
/** Alias so both historical import names resolve to the same shape. */
export type Aud0EventInput = Aud0Event;
/** Alias so both historical import names resolve to the same shape. */
export type Aud0LineageEventInput = Aud0LineageEvent;
export interface Aud0Client {
ingestEvent(event: Aud0Event): Promise<void>;
ingestLineageEvent(event: Aud0LineageEvent): Promise<void>;
ingestEvent(event: Aud0Event): Promise<Aud0Event>;
ingestLineageEvent(event: Aud0LineageEvent): Promise<Aud0LineageEvent>;
}
export function createAud0Client(baseUrl?: string): Aud0Client {
@@ -59,13 +79,17 @@ export function createAud0Client(baseUrl?: string): Aud0Client {
return new HttpAud0Client(baseUrl);
}
/** No AUD0_URL configured: audit emission is a no-op (see module doc comment). */
/**
* No AUD0_URL configured: audit emission is a no-op (see module doc comment).
* Echoes the event back so callers that want the emitted record get the same
* value shape they would from the HTTP client.
*/
class NoopAud0Client implements Aud0Client {
async ingestEvent(_event: Aud0Event): Promise<void> {
/* intentional no-op */
async ingestEvent(event: Aud0Event): Promise<Aud0Event> {
return event;
}
async ingestLineageEvent(_event: Aud0LineageEvent): Promise<void> {
/* intentional no-op */
async ingestLineageEvent(event: Aud0LineageEvent): Promise<Aud0LineageEvent> {
return event;
}
}
@@ -77,15 +101,15 @@ class HttpAud0Client implements Aud0Client {
this.baseUrl = baseUrl.replace(/\/+$/, "");
}
async ingestEvent(event: Aud0Event): Promise<void> {
await this.post("/v1/aud0/events", event);
async ingestEvent(event: Aud0Event): Promise<Aud0Event> {
return this.post("/v1/aud0/events", event);
}
async ingestLineageEvent(event: Aud0LineageEvent): Promise<void> {
await this.post("/v1/aud0/lineage/events", event);
async ingestLineageEvent(event: Aud0LineageEvent): Promise<Aud0LineageEvent> {
return this.post("/v1/aud0/lineage/events", event);
}
private async post(path: string, body: unknown): Promise<void> {
private async post<T>(path: string, body: T): Promise<T> {
const res = await fetch(`${this.baseUrl}${path}`, {
method: "POST",
headers: { "Content-Type": "application/json" },
@@ -94,5 +118,9 @@ class HttpAud0Client implements Aud0Client {
if (!res.ok) {
throw new Error(`AUD0 ${path} error: ${res.status} ${await res.text().catch(() => "")}`);
}
// AUD0 is not guaranteed to echo a JSON body on ingest. Prefer the
// server's canonical record when there is one, otherwise fall back to what
// we sent -- never fail an already-successful POST on an empty body.
return (await res.json().catch(() => body)) as T;
}
}
+37 -15
View File
@@ -1,23 +1,37 @@
/**
* src/clients/cl0ud-client.ts
* ============================
* 0pt's client for the CL0UD control-plane policy decision point:
* 0pt's ONLY path to the CL0UD control-plane policy decision point:
* evaluatePolicy -> POST {baseUrl}/v1/cl0ud/policies/evaluate
*
* Every side-effecting 0pt capability re-consults CL0UD before acting (per
* docs/PRODUCT_PLAN.md §4.1), so this is the single choke point for that.
* docs/PRODUCT_PLAN.md §4.1) -- document-extraction-service.ts,
* iceberg-write-service.ts, external-writeback-service.ts -- so this is the
* single choke point for that. Never bypassed: a `deny` or
* `approval_required` decision always aborts the caller, even when an
* upstream gate (e.g. ACT0's own Approval Engine) already ran; see
* external-writeback-service.ts's module doc comment for why that specific
* re-check matters.
*
* Convention (identical to aud0-client.ts / n0d-client.ts / st0re-client.ts):
* when no base URL is configured the client runs in LOCAL PASS-THROUGH mode —
* when no base URL is configured the client runs in LOCAL PASS-THROUGH mode --
* it returns a deterministic `allow` decision WITHOUT any network call, so
* unit tests and local dev are hermetic. This is a dev-mode default only; any
* real deployment MUST set CL0UD_URL so decisions come from the real policy
* engine. The pass-through never invents a `deny`/`approval_required` — it
* only ever allows, and it stamps a clearly local-looking decision id.
* unit tests and local dev are hermetic. Every 0pt service that calls
* evaluatePolicy() treats anything other than "allow" as fatal, so a mock that
* defaulted to "deny" would make every unconfigured-CL0UD path unusable;
* tests/p0/external-writeback-service.test.ts exercises "deny" and
* "approval_required" explicitly via its own fetch stub against an HTTP client
* instance, not this pass-through.
*
* This is a dev-mode default, NOT a security control. Any real deployment MUST
* set CL0UD_URL so decisions come from the real policy engine. The pass-through
* never invents a `deny`/`approval_required` -- it only ever allows, and it
* stamps a clearly local-looking decision id.
*/
import crypto from "crypto";
export type PolicyDecision = "allow" | "deny" | "approval_required";
/** The decision vocabulary itself. */
export type PolicyDecisionValue = "allow" | "deny" | "approval_required";
export interface EvaluatePolicyInput {
tenant_id: string;
@@ -31,14 +45,18 @@ export interface EvaluatePolicyInput {
correlation_id?: string;
}
export interface PolicyResult {
decision: PolicyDecision;
/** The decision record CL0UD returns. */
export interface PolicyDecision {
decision: PolicyDecisionValue;
decision_id: string;
reason?: string;
}
/** Alias so both historical import names resolve to the same shape. */
export type PolicyResult = PolicyDecision;
export interface Cl0udClient {
evaluatePolicy(input: EvaluatePolicyInput): Promise<PolicyResult>;
evaluatePolicy(input: EvaluatePolicyInput): Promise<PolicyDecision>;
}
export function createCl0udClient(baseUrl?: string): Cl0udClient {
@@ -48,7 +66,7 @@ export function createCl0udClient(baseUrl?: string): Cl0udClient {
/** No CL0UD_URL configured: allow-only local pass-through (see module doc comment). */
class LocalAllowCl0udClient implements Cl0udClient {
async evaluatePolicy(_input: EvaluatePolicyInput): Promise<PolicyResult> {
async evaluatePolicy(_input: EvaluatePolicyInput): Promise<PolicyDecision> {
return { decision: "allow", decision_id: `pdec_local_${crypto.randomUUID()}` };
}
}
@@ -60,7 +78,7 @@ class HttpCl0udClient implements Cl0udClient {
this.baseUrl = baseUrl.replace(/\/+$/, "");
}
async evaluatePolicy(input: EvaluatePolicyInput): Promise<PolicyResult> {
async evaluatePolicy(input: EvaluatePolicyInput): Promise<PolicyDecision> {
const res = await fetch(`${this.baseUrl}/v1/cl0ud/policies/evaluate`, {
method: "POST",
headers: { "Content-Type": "application/json" },
@@ -69,9 +87,13 @@ class HttpCl0udClient implements Cl0udClient {
if (!res.ok) {
throw new Error(`CL0UD policy evaluate error: ${res.status} ${await res.text().catch(() => "")}`);
}
const body = (await res.json()) as Partial<PolicyResult>;
const body = (await res.json()) as Partial<PolicyDecision>;
// FAIL CLOSED. A configured CL0UD that answers 200 with a body missing
// `decision` must not be read as an allow -- callers only special-case
// "deny"/"approval_required", so an `undefined` decision would slip
// through as if it had been permitted.
return {
decision: (body.decision ?? "deny") as PolicyDecision,
decision: (body.decision ?? "deny") as PolicyDecisionValue,
decision_id: body.decision_id ?? `pdec_${crypto.randomUUID()}`,
reason: body.reason,
};
+50 -15
View File
@@ -1,21 +1,26 @@
/**
* src/clients/n0d-client.ts
* ==========================
* 0pt's client for REQUESTING heavy compute jobs from N0D (the Compute OS).
* 0pt never executes heavy work in-process — it submits an N0D job and holds
* only the returned `job_id` (docs/11-lakehouse-write-plan.md item 7,
* docs/P0_QUERY_SOURCE_FLOW.md):
* 0pt's ONLY path for REQUESTING heavy compute jobs from N0D (the Compute OS).
* 0pt REQUESTS jobs; it never executes heavy work in-process and never owns
* N0D's scheduling/node/GPU decisions -- it submits a job and holds only the
* returned `job_id` (docs/11-lakehouse-write-plan.md item 7,
* docs/P0_QUERY_SOURCE_FLOW.md, and see
* `IcebergWriteService.requestIcebergWrite({ heavy: true })` for the concrete
* example this client backs):
* createJob -> POST {baseUrl}/v1/n0d/jobs
*
* Convention (identical to aud0-client.ts / cl0ud-client.ts / st0re-client.ts
* / st0re-lakehouse-client.ts): when no base URL is configured the client
* returns a deterministic in-memory MOCK job (id prefixed "mock_job_") with
* NO network call, so unit tests stay hermetic. A real deployment sets
* N0D_URL to submit against the live scheduler.
* returns a deterministic in-memory MOCK job (id prefixed "mock_job_", the
* prefix tests/p0/iceberg-write-service.test.ts and
* tests/p0/document-capture-mailbox.test.ts already assert on) with NO network
* call, so unit tests stay hermetic. The mock never actually runs anything; a
* real deployment sets N0D_URL to submit against the live scheduler.
*/
import crypto from "crypto";
export interface CreateJobInput {
export interface N0dCreateJobInput {
tenant_id: string;
project_id: string;
job_type: string;
@@ -34,16 +39,46 @@ export interface CreateJobInput {
correlation_id?: string;
}
export type N0dJobState = "queued" | "running" | "succeeded" | "failed" | "cancelled";
/** Alias so both historical import names resolve to the same shape. */
export type CreateJobInput = N0dCreateJobInput;
export interface N0dJob extends CreateJobInput {
/**
* N0D's real job lifecycle, taken verbatim from sax3l/n0d's own wire contract
* (`packages/schemas/n0d.job.schema.json`, which mirrors
* `src/contracts/job.contract.ts`). That schema names the field `status`, not
* `state`, and says explicitly: "Do not add 'succeeded' -- that is 'completed'
* under a different name." An earlier draft of this client used a five-value
* `state` field with `succeeded`; it was wrong against the real contract.
*/
export type N0dJobStatus =
| "created"
| "validated"
| "queued"
| "scheduled"
| "running"
| "retrying"
| "waiting_for_capacity"
| "waiting_for_approval"
| "completed"
| "completed_with_warnings"
| "failed"
| "cancelled"
| "expired";
/** Alias kept for the older name used elsewhere in this repo's history. */
export type N0dJobState = N0dJobStatus;
export interface N0dJob extends Partial<N0dCreateJobInput> {
job_id: string;
state: N0dJobState;
job_type: string;
tenant_id: string;
project_id: string;
status: N0dJobStatus;
created_at: string;
}
export interface N0dClient {
createJob(input: CreateJobInput): Promise<N0dJob>;
createJob(input: N0dCreateJobInput): Promise<N0dJob>;
}
export function createN0dClient(baseUrl?: string): N0dClient {
@@ -53,11 +88,11 @@ export function createN0dClient(baseUrl?: string): N0dClient {
/** No N0D_URL configured: returns a deterministic mock job (see module doc comment). */
class MockN0dClient implements N0dClient {
async createJob(input: CreateJobInput): Promise<N0dJob> {
async createJob(input: N0dCreateJobInput): Promise<N0dJob> {
return {
...input,
job_id: `mock_job_${crypto.randomUUID()}`,
state: "queued",
status: "queued",
created_at: new Date().toISOString(),
};
}
@@ -70,7 +105,7 @@ class HttpN0dClient implements N0dClient {
this.baseUrl = baseUrl.replace(/\/+$/, "");
}
async createJob(input: CreateJobInput): Promise<N0dJob> {
async createJob(input: N0dCreateJobInput): Promise<N0dJob> {
const res = await fetch(`${this.baseUrl}/v1/n0d/jobs`, {
method: "POST",
headers: { "Content-Type": "application/json" },
+35 -20
View File
@@ -2,22 +2,35 @@
* src/clients/st0re-client.ts
* ============================
* 0pt's client for the generic ST0RE Artifact registry (snake_case wire
* shape), distinct from `./st0re-lakehouse-client.ts` (the camelCase
* /v1/st0re/lakehouse/* table registry). This one registers an artifact's
* METADATA — a pointer to where the bytes live (provider/bucket/key/region)
* plus content-type/size/checksum/retention/PII/residency:
* createArtifact -> POST {baseUrl}/v1/st0re/artifacts
* shape), used by document-capture-service.ts and
* document-extraction-service.ts to record what they produced. Distinct from
* `./st0re-lakehouse-client.ts` (the camelCase /v1/st0re/lakehouse/* table
* registry -- see that file's own doc comment for why the two are kept
* separate). This one registers an artifact's METADATA: a pointer to where the
* bytes live (provider/bucket/key/region) plus content-type/size/checksum/
* retention/PII/residency:
* createArtifact -> POST {baseUrl}/v1/st0re/artifacts/register
*
* KNOWN GAP (documented in src/adapters/local-blob-store.ts): ST0RE does not
* yet expose a raw-bytes upload endpoint for 0pt to call, so the actual bytes
* are persisted by LocalBlobStore (interim) and only the resulting location
* is registered here as metadata.
* The route is `/v1/st0re/artifacts/register`, NOT `/v1/st0re/artifacts`.
* Verified against sax3l/st0re `src/api/routes/artifacts.ts`, where
* `/v1/st0re/artifacts` is registered as a GET-only list route and the POST
* handler lives on `.../register`. An earlier draft of this client POSTed to
* the bare collection path and would not have registered anything.
*
* KNOWN GAP (documented in src/adapters/local-blob-store.ts and
* src/services/document-capture-service.ts's own header): ST0RE does not yet
* expose a raw-bytes upload endpoint for 0pt to call, so the actual bytes are
* persisted by LocalBlobStore (interim) and only the resulting location is
* registered here as metadata.
*
* Convention (identical to aud0-client.ts / cl0ud-client.ts / n0d-client.ts /
* st0re-lakehouse-client.ts): when no base URL is configured the client
* returns a deterministic in-memory MOCK artifact (id prefixed
* "mock_artifact_") with NO network call, so unit tests stay hermetic. A real
* deployment sets ST0RE_URL to register against the live artifact registry.
* "mock_artifact_", the prefix tests/p0/document-capture-mailbox.test.ts and
* tests/p0/document-extraction-never-fabricates.test.ts assert on) with NO
* network call, so unit tests stay hermetic -- but it persists nothing beyond
* the current process. A real deployment sets ST0RE_URL to register against
* the live artifact registry.
*/
import crypto from "crypto";
@@ -28,7 +41,7 @@ export interface St0reObjectLocation {
region?: string;
}
export interface CreateArtifactInput {
export interface St0reArtifactInput {
tenant_id: string;
project_id: string;
artifact_type: string;
@@ -38,8 +51,7 @@ export interface CreateArtifactInput {
content_type: string;
size_bytes: number;
checksum_sha256: string;
/** "none" | "low" | "medium" | "high" — kept as string to stay tolerant of ST0RE's own vocabulary. */
pii_level: string;
pii_level: "none" | "low" | "medium" | "high";
retention_policy: string;
data_residency: string;
/** Risk level L0–L5 per the SIAX Cloud risk taxonomy. */
@@ -47,13 +59,16 @@ export interface CreateArtifactInput {
correlation_id?: string;
}
export interface St0reArtifact extends CreateArtifactInput {
/** Alias so both historical import names resolve to the same shape. */
export type CreateArtifactInput = St0reArtifactInput;
export interface St0reArtifact extends St0reArtifactInput {
artifact_id: string;
created_at: string;
}
export interface St0reClient {
createArtifact(input: CreateArtifactInput): Promise<St0reArtifact>;
createArtifact(input: St0reArtifactInput): Promise<St0reArtifact>;
}
export function createSt0reClient(baseUrl?: string): St0reClient {
@@ -63,7 +78,7 @@ export function createSt0reClient(baseUrl?: string): St0reClient {
/** No ST0RE_URL configured: returns a deterministic mock artifact (see module doc comment). */
class MockSt0reClient implements St0reClient {
async createArtifact(input: CreateArtifactInput): Promise<St0reArtifact> {
async createArtifact(input: St0reArtifactInput): Promise<St0reArtifact> {
return {
...input,
artifact_id: `mock_artifact_${crypto.randomUUID()}`,
@@ -79,14 +94,14 @@ class HttpSt0reClient implements St0reClient {
this.baseUrl = baseUrl.replace(/\/+$/, "");
}
async createArtifact(input: CreateArtifactInput): Promise<St0reArtifact> {
const res = await fetch(`${this.baseUrl}/v1/st0re/artifacts`, {
async createArtifact(input: St0reArtifactInput): Promise<St0reArtifact> {
const res = await fetch(`${this.baseUrl}/v1/st0re/artifacts/register`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(input),
});
if (!res.ok) {
throw new Error(`ST0RE create-artifact error: ${res.status} ${await res.text().catch(() => "")}`);
throw new Error(`ST0RE artifact registration error: ${res.status} ${await res.text().catch(() => "")}`);
}
return (await res.json()) as St0reArtifact;
}
+85 -52
View File
@@ -1,60 +1,67 @@
/**
* src/services/dataset-service.ts
* ================================
* Owns 0pt.dataset.schema.v1 — the registry of 0pt datasets (raw / enriched /
* curated / feature outputs). In-memory reference implementation (same
* convention as the other 0pt services in this repo; a real deployment backs
* this with `opt_datasets`).
* Owns 0pt.dataset.schema.v1 — the registry of 0pt datasets (raw / structured
* / enriched / curated / feature / derived outputs). This is the thing
* `DatasetIcebergMappingService` (src/services/dataset-iceberg-mapping-service.ts)
* and `IcebergWriteService` (src/services/iceberg-write-service.ts) look a
* `dataset_id` up against before pointing an Iceberg table mapping or a write
* at it.
*
* Consumed by:
* - dataset-iceberg-mapping-service.ts (getDataset -> does the dataset exist
* before we map it to an Iceberg table?)
* - iceberg-write-service.ts (getDataset -> guard the write path)
* Deliberately small: it is a reference/registry entry, NOT dataset content,
* schema, or quality state — see docs/ICEBERG_WRITE_BOUNDARY.md for that
* boundary. In-memory reference implementation (same convention as the other
* 0pt services in this repo; a real deployment backs this with `opt_datasets`).
*
* In-memory scope: each `new DatasetService()` owns its own registry, the same
* pre-existing limitation source-service.ts and every other P0 registry
* service documents (docs/P0_QUERY_SOURCE_FLOW.md's "Known gaps"). Callers
* that need a shared view across API routes pass an existing instance in via
* the `datasetService` constructor option — see
* src/services/lakehouse-mapping-registry.ts, which does exactly that for the
* whole app/api/0pt/lakehouse/mappings route group.
*
* Registering a dataset emits a best-effort AUD0 `0pt.dataset_registered`
* event; with no AUD0_URL configured that emission is a no-op (see
* aud0-client.ts), so this stays hermetic in tests and local dev.
*/
import { createAud0Client, type Aud0Client } from "../clients/aud0-client";
import type { Dataset, DatasetStatus, DatasetType, CreateDatasetInput } from "../types/dataset";
export type DatasetType = "raw" | "enriched" | "curated" | "feature" | "derived";
export type DatasetStatus = "active" | "deprecated" | "archived";
// Re-exported so the historical `import { Dataset, DatasetType, ... } from
// "./dataset-service"` call shape keeps working alongside the canonical
// `../types/dataset` module.
export type { Dataset, DatasetStatus, DatasetType, CreateDatasetInput };
/** Alias so both historical input-type names resolve to the same shape. */
export type RegisterDatasetInput = CreateDatasetInput;
export interface Dataset {
/**
* Storage shape: nullable columns, exactly as the eventual `opt_datasets`
* table would hold them. `toDataset()` converts back to the `Dataset` DTO.
*/
interface DatasetRecord {
dataset_id: string;
tenant_id: string;
project_id: string;
name: string;
dataset_type: DatasetType;
description?: string;
status: DatasetStatus;
correlation_id?: string;
dataset_type: string;
status: string;
description: string | null;
correlation_id: string | null;
created_at: string;
updated_at?: string;
created_by?: string;
}
export interface RegisterDatasetInput {
dataset_id: string;
tenant_id: string;
project_id: string;
name: string;
dataset_type: DatasetType;
description?: string;
status?: DatasetStatus;
correlation_id?: string;
created_by?: string;
updated_at: string | null;
created_by: string | null;
}
export class DatasetService {
private datasets: Map<string, Dataset> = new Map();
private datasets: Map<string, DatasetRecord> = new Map();
private aud0: Aud0Client;
constructor(aud0BaseUrl?: string) {
this.aud0 = createAud0Client(aud0BaseUrl);
}
async registerDataset(input: RegisterDatasetInput): Promise<Dataset> {
async registerDataset(input: CreateDatasetInput): Promise<Dataset> {
if (this.datasets.has(input.dataset_id)) {
throw new Error(`Dataset ${input.dataset_id} already exists`);
}
@@ -63,50 +70,76 @@ export class DatasetService {
}
const now = new Date().toISOString();
const dataset: Dataset = {
const record: DatasetRecord = {
dataset_id: input.dataset_id,
tenant_id: input.tenant_id,
project_id: input.project_id,
name: input.name,
dataset_type: input.dataset_type,
description: input.description,
status: input.status ?? "active",
correlation_id: input.correlation_id,
description: input.description ?? null,
correlation_id: input.correlation_id ?? null,
created_at: now,
created_by: input.created_by,
updated_at: null,
created_by: input.created_by ?? null,
};
this.datasets.set(dataset.dataset_id, dataset);
this.datasets.set(record.dataset_id, record);
// 0pt.dataset_registered -- same "no mutation without an evented trail"
// doctrine every other P0 registry service in this repo follows
// (SourceService.createSource, SourceRatePolicyService.createSourceRatePolicy).
await this.aud0.ingestEvent({
event_id: `evt_0pt_dataset_registered_${dataset.dataset_id}`,
event_id: `evt_0pt_dataset_registered_${record.dataset_id}`,
event_type: "0pt.dataset_registered",
tenant_id: dataset.tenant_id,
project_id: dataset.project_id,
actor_id: dataset.created_by ?? "system",
tenant_id: record.tenant_id,
project_id: record.project_id,
actor_id: record.created_by ?? "system",
app_id: "0pt",
capability_id: "0pt.register_dataset",
resource_type: "dataset",
resource_id: dataset.dataset_id,
resource_id: record.dataset_id,
risk_level: "L2",
payload: { dataset_type: dataset.dataset_type, name: dataset.name },
payload: { name: record.name, dataset_type: record.dataset_type },
created_at: now,
correlation_id: dataset.correlation_id,
correlation_id: record.correlation_id ?? undefined,
});
return dataset;
return this.toDataset(record);
}
async getDataset(datasetId: string): Promise<Dataset> {
const dataset = this.datasets.get(datasetId);
if (!dataset) throw new Error(`Dataset ${datasetId} not found`);
return dataset;
const record = this.datasets.get(datasetId);
if (!record) throw new Error(`Dataset ${datasetId} not found`);
return this.toDataset(record);
}
async listDatasets(filter?: { tenant_id?: string; project_id?: string; dataset_type?: DatasetType }): Promise<Dataset[]> {
async listDatasets(filter?: {
tenant_id?: string;
project_id?: string;
dataset_type?: DatasetType;
status?: DatasetStatus;
}): Promise<Dataset[]> {
let results = Array.from(this.datasets.values());
if (filter?.tenant_id) results = results.filter((d) => d.tenant_id === filter.tenant_id);
if (filter?.project_id) results = results.filter((d) => d.project_id === filter.project_id);
if (filter?.dataset_type) results = results.filter((d) => d.dataset_type === filter.dataset_type);
return results;
if (filter?.tenant_id) results = results.filter((r) => r.tenant_id === filter.tenant_id);
if (filter?.project_id) results = results.filter((r) => r.project_id === filter.project_id);
if (filter?.dataset_type) results = results.filter((r) => r.dataset_type === filter.dataset_type);
if (filter?.status) results = results.filter((r) => r.status === filter.status);
return results.map((r) => this.toDataset(r));
}
private toDataset(r: DatasetRecord): Dataset {
return {
dataset_id: r.dataset_id,
tenant_id: r.tenant_id,
project_id: r.project_id,
name: r.name,
dataset_type: r.dataset_type as DatasetType,
status: r.status as DatasetStatus,
description: r.description ?? undefined,
correlation_id: r.correlation_id ?? undefined,
created_at: r.created_at,
updated_at: r.updated_at ?? undefined,
created_by: r.created_by ?? undefined,
};
}
}
+5 -1
View File
@@ -18,7 +18,11 @@
* `writeExternalRecord` runs, a human has already approved the write -- this
* service still re-checks CL0UD policy (per docs/PRODUCT_PLAN.md section
* 4.1's hard rule that CL0UD is always re-consulted, the same rule
* quality-check-service.ts/document-extraction-service.ts already follow),
* document-extraction-service.ts already follows -- confirmed by grepping
* this repo's src/services/ for evaluatePolicy()/Cl0udClient usage; the
* only other real service that does the same is iceberg-write-service.ts.
* An earlier version of this comment also cited `quality-check-service.ts`
* here; that file does not exist anywhere in this repo),
* but does not itself re-verify the upstream Approval record (ACT0 owns
* approvals; 0pt's own capability boundary is "did CL0UD say yes for THIS
* call", same separation of concerns every other 0pt service in this repo
@@ -0,0 +1,19 @@
import { DatasetService } from "./dataset-service";
import { DatasetIcebergMappingService } from "./dataset-iceberg-mapping-service";
import { IcebergWriteService } from "./iceberg-write-service";
/**
* Shared singleton instances for the lakehouse-mapping route group
* (app/api/0pt/lakehouse/mappings/*). Previously each route file in that
* group instantiated its own DatasetService/DatasetIcebergMappingService/
* IcebergWriteService, so a mapping created via POST /mappings was invisible
* to GET /mappings/{id} and to POST /mappings/{id}/writes within the same
* server process (each held a distinct in-memory Map). Constructing all
* three here once, wired together, and importing them everywhere fixes that
* -- matching the in-memory-per-module convention this repo already uses
* elsewhere (see document-capture-service.ts's own singleton note), just
* applied consistently across this route group instead of per-file.
*/
export const datasetService = new DatasetService();
export const mappingService = new DatasetIcebergMappingService({ datasetService });
export const writeService = new IcebergWriteService({ datasetService, mappingService });
+96 -37
View File
@@ -1,25 +1,53 @@
/**
* src/services/source-service.ts
* ===============================
* Owns 0pt.source.schema.v1 — the registry of upstream data sources
* (databases, crawl domains, APIs, file drops). In-memory reference
* implementation (same convention as the other 0pt services in this repo:
* each API route file constructs its own instance; a real deployment backs
* this with `opt_sources` — sql/002_p0_dataset_quality.sql).
* Owns 0pt.source.schema.v1 — the per-tenant registry of upstream data
* sources (databases, crawl domains, APIs, file drops). This is the registry
* `SourceQueryService.querySource()` (src/services/source-query-service.ts)
* and `SourceRatePolicyService` (src/services/source-rate-policy-service.ts)
* both look a `source_id` up against — see docs/P0_QUERY_SOURCE_FLOW.md.
*
* Consumed by:
* - source-query-service.ts (getSource -> is this source queryable?)
* - source-rate-policy-service.ts (getSource -> does the source exist?)
* Deliberately small and in-memory, same "pure core, thin registry" shape
* every other P0 service in this repo already uses; a real deployment backs
* this with `opt_sources`. In-memory scope: each `new SourceService()` owns
* its own registry — the pre-existing limitation docs/P0_QUERY_SOURCE_FLOW.md's
* "Known gaps" section documents (a Source registered via one API route module
* is not yet visible to another route module in the same running process).
* Callers that need a shared view pass an existing instance in via the
* `sourceService` constructor option, exactly like SourceQueryService and
* SourceRatePolicyService already do.
*
* Registering a source emits a best-effort AUD0 `0pt.source_registered`
* event; with no AUD0_URL configured that emission is a no-op (see
* aud0-client.ts), so this stays hermetic in tests and local dev.
* Registering a source emits a best-effort AUD0 `0pt.source_created` event —
* the same "no mutation without an evented trail" doctrine every other P0
* registry service follows. With no AUD0_URL configured that emission is a
* no-op (see aud0-client.ts), so this stays hermetic in tests and local dev.
*/
import { createAud0Client, type Aud0Client } from "../clients/aud0-client";
import type { CreateSourceInput, Source } from "../types/source";
import type { CreateSourceInput, Source, SourceStatus, SourceType } from "../types/source";
/**
* Storage shape: nullable columns, exactly as the eventual `opt_sources` table
* would hold them. `toSource()` converts back to the `Source` DTO (undefined
* rather than null) so callers never have to handle both.
*/
interface SourceRecord {
source_id: string;
tenant_id: string;
project_id: string;
source_type: string;
name: string;
adapter_id: string | null;
access: string | null;
description: string | null;
status: string;
correlation_id: string | null;
created_at: string;
updated_at: string | null;
created_by: string | null;
}
export class SourceService {
private sources: Map<string, Source> = new Map();
private sources: Map<string, SourceRecord> = new Map();
private aud0: Aud0Client;
constructor(aud0BaseUrl?: string) {
@@ -35,51 +63,82 @@ export class SourceService {
}
const now = new Date().toISOString();
const source: Source = {
const record: SourceRecord = {
source_id: input.source_id,
tenant_id: input.tenant_id,
project_id: input.project_id,
source_type: input.source_type,
name: input.name,
adapter_id: input.adapter_id,
description: input.description,
adapter_id: input.adapter_id ?? null,
access: input.access ?? null,
description: input.description ?? null,
status: input.status ?? "active",
correlation_id: input.correlation_id,
correlation_id: input.correlation_id ?? null,
created_at: now,
created_by: input.created_by,
updated_at: null,
created_by: input.created_by ?? null,
};
this.sources.set(source.source_id, source);
this.sources.set(record.source_id, record);
await this.aud0.ingestEvent({
event_id: `evt_0pt_source_registered_${source.source_id}`,
event_type: "0pt.source_registered",
tenant_id: source.tenant_id,
project_id: source.project_id,
actor_id: source.created_by ?? "system",
event_id: `evt_0pt_source_created_${record.source_id}`,
event_type: "0pt.source_created",
tenant_id: record.tenant_id,
project_id: record.project_id,
actor_id: record.created_by ?? "system",
app_id: "0pt",
capability_id: "0pt.register_source",
capability_id: "0pt.create_source",
resource_type: "source",
resource_id: source.source_id,
resource_id: record.source_id,
risk_level: "L2",
payload: { source_type: source.source_type, adapter_id: source.adapter_id ?? null, name: source.name },
payload: {
source_type: record.source_type,
name: record.name,
adapter_id: record.adapter_id,
access: record.access,
},
created_at: now,
correlation_id: source.correlation_id,
correlation_id: record.correlation_id ?? undefined,
});
return source;
return this.toSource(record);
}
async getSource(sourceId: string): Promise<Source> {
const source = this.sources.get(sourceId);
if (!source) throw new Error(`Source ${sourceId} not found`);
return source;
const record = this.sources.get(sourceId);
if (!record) throw new Error(`Source ${sourceId} not found`);
return this.toSource(record);
}
async listSources(filter?: { tenant_id?: string; project_id?: string; source_type?: Source["source_type"] }): Promise<Source[]> {
async listSources(filter?: {
tenant_id?: string;
project_id?: string;
source_type?: SourceType;
status?: SourceStatus;
}): Promise<Source[]> {
let results = Array.from(this.sources.values());
if (filter?.tenant_id) results = results.filter((s) => s.tenant_id === filter.tenant_id);
if (filter?.project_id) results = results.filter((s) => s.project_id === filter.project_id);
if (filter?.source_type) results = results.filter((s) => s.source_type === filter.source_type);
return results;
if (filter?.tenant_id) results = results.filter((r) => r.tenant_id === filter.tenant_id);
if (filter?.project_id) results = results.filter((r) => r.project_id === filter.project_id);
if (filter?.source_type) results = results.filter((r) => r.source_type === filter.source_type);
if (filter?.status) results = results.filter((r) => r.status === filter.status);
return results.map((r) => this.toSource(r));
}
private toSource(r: SourceRecord): Source {
return {
source_id: r.source_id,
tenant_id: r.tenant_id,
project_id: r.project_id,
source_type: r.source_type as SourceType,
name: r.name,
adapter_id: r.adapter_id ?? undefined,
access: (r.access as Source["access"]) ?? undefined,
description: r.description ?? undefined,
status: r.status as SourceStatus,
correlation_id: r.correlation_id ?? undefined,
created_at: r.created_at,
updated_at: r.updated_at ?? undefined,
created_by: r.created_by ?? undefined,
};
}
}
+44
View File
@@ -0,0 +1,44 @@
// 0pt.dataset.schema.v1
//
// A dataset 0pt produces or manages -- the thing `dataset_iceberg_mapping`
// (src/types/dataset-iceberg-mapping.ts) points at, and the thing
// IcebergWriteService (src/services/iceberg-write-service.ts) writes through
// ST0RE's table registry on behalf of. This type intentionally stays small:
// it is a reference/registry entry, not a copy of dataset content, schema,
// or quality state (that boundary is documented in
// docs/ICEBERG_WRITE_BOUNDARY.md -- 0pt owns dataset production, but this
// specific type is only what DatasetIcebergMappingService/IcebergWriteService
// need to confirm a dataset_id is real before pointing a table at it).
// Union of both dataset-type vocabularies that existed in this repo's two
// remotes ("structured" from one, "feature"/"derived" from the other);
// nothing is dropped by the GitHub<->Gitea unification merge.
export type DatasetType = "raw" | "structured" | "enriched" | "curated" | "feature" | "derived";
export type DatasetStatus = "active" | "archived" | "deprecated";
export interface Dataset {
dataset_id: string;
tenant_id: string;
project_id: string;
name: string;
dataset_type: DatasetType;
status: DatasetStatus;
description?: string;
correlation_id?: string;
created_at: string;
updated_at?: string;
created_by?: string;
}
export interface CreateDatasetInput {
dataset_id: string;
tenant_id: string;
project_id: string;
name: string;
dataset_type: DatasetType;
description?: string;
status?: DatasetStatus;
correlation_id?: string;
created_by?: string;
}
+35 -2
View File
@@ -8,12 +8,37 @@
* (src/services/source-query-service.ts), which reads `source_type` +
* `adapter_id` to decide whether a Source is queryable.
*
* This is a DIFFERENT, newer entity than the static provenance catalog in
* docs/03-data-model.md's `dim_source` table (the ~9-row list of national
* registries served today by GET /api/sources) -- this Source is a per-tenant
* registration of something 0pt can actually connect to. See
* docs/P0_QUERY_SOURCE_FLOW.md and src/services/source-query-service.ts, the
* first real consumer.
*
* `adapter_id` is the seam that lets a "database" source name the concrete
* driver 0pt should use for it (today only "fabric_onelake_sql" is wired on
* the synchronous path — see source-query-service.ts).
*
* `access` mirrors dim_source.access (docs/03-data-model.md) so a Source
* registered here can still be reported against the same legal-sourcing
* vocabulary CLAUDE.md §1 requires everywhere in this repo.
*/
/**
* Union of both source-type vocabularies that existed in this repo's two
* remotes; nothing is dropped by the unification merge.
*/
export type SourceType = "database" | "file" | "web" | "api" | "stream" | "manual";
export type SourceStatus = "active" | "paused" | "archived";
/**
* Union of both status vocabularies. "archived" and "deprecated" both survive
* the unification merge -- they were introduced independently and no code
* treats either as canonical.
*/
export type SourceStatus = "active" | "paused" | "archived" | "deprecated";
/** Legal-sourcing vocabulary, mirroring dim_source.access. */
export type SourceAccess = "api" | "bulk" | "authorized_web" | "licensed";
export interface Source {
source_id: string;
@@ -21,8 +46,15 @@ export interface Source {
project_id: string;
source_type: SourceType;
name: string;
/** Concrete driver id for this source, e.g. "fabric_onelake_sql". Optional: not every source is directly queryable. */
/**
* Identifies which concrete adapter implementation this source is queried
* through (e.g. "fabric_onelake_sql" -- src/adapters/fabric-onelake-adapter.ts).
* Required in practice for source_type "database"; optional/unused for other
* types until they grow a synchronous query path of their own.
*/
adapter_id?: string;
/** Mirrors dim_source.access (docs/03-data-model.md). */
access?: SourceAccess;
description?: string;
status: SourceStatus;
correlation_id?: string;
@@ -38,6 +70,7 @@ export interface CreateSourceInput {
source_type: SourceType;
name: string;
adapter_id?: string;
access?: SourceAccess;
description?: string;
status?: SourceStatus;
correlation_id?: string;