CI (SIAX Cloud) / sonar (push) Failing after 13s
Security Scan (SIAX Cloud) / security (push) Successful in 15s
CI (SIAX Cloud) / security (push) Successful in 20s
Release chain (G17, ADR-W16-003) / Build, push, G17 (SBOM/scan/attest/verify/evidence) (push) Successful in 1m54s
Deploy to Coolify / deploy (push) Successful in 2m0s
CI (SIAX Cloud) / integration (push) Successful in 9m49s
CI (SIAX Cloud) / quality (push) Successful in 10m4s
CI (SIAX Cloud) / sonar (pull_request) Skipped
masterplan-lock / check (pull_request) Successful in 7s
masterplan-lock / check (push) Successful in 7s
CI (SIAX Cloud) / security (pull_request) Successful in 20s
Security Scan (SIAX Cloud) / security (pull_request) Successful in 44s
CI (SIAX Cloud) / integration (pull_request) Successful in 1m28s
CI (SIAX Cloud) / quality (pull_request) Successful in 10m3s
166 lines
7.6 KiB
TypeScript
166 lines
7.6 KiB
TypeScript
/**
|
|
* src/services/canonical-fact-service.ts
|
|
* ======================================
|
|
* 0pt's canonical structured-observation write/read surface (sql/022).
|
|
*
|
|
* Ownership boundary: 0pt stores normalized OBSERVED facts (what a source
|
|
* said, when, from which artifact). L0RE owns epistemic propositions and
|
|
* projections and must consume these rows through this API. Nothing here
|
|
* overwrites an earlier observation: the unique key includes source_ref +
|
|
* observed_at, so conflicting sources are preserved as separate rows.
|
|
*
|
|
* Idempotency: identical re-writes hit ON CONFLICT DO NOTHING and are
|
|
* reported as `duplicates`, never duplicated.
|
|
*/
|
|
import { createAud0Client, type Aud0Client } from "../clients/aud0-client";
|
|
import { SiaxError } from "../platform/errors";
|
|
import {
|
|
createCanonicalFactRepository,
|
|
entityKey,
|
|
type CanonicalFactRepository,
|
|
} from "../repositories/canonical-fact-repository";
|
|
import type {
|
|
CanonicalEntity,
|
|
CanonicalEntityInput,
|
|
CanonicalFact,
|
|
CanonicalFactInput,
|
|
CanonicalQuery,
|
|
CanonicalRelationInput,
|
|
CanonicalWriteRequest,
|
|
CanonicalWriteResult,
|
|
FactValueType,
|
|
} from "../types/canonical-facts";
|
|
|
|
const FACT_VALUE_TYPES: FactValueType[] = ["string", "number", "boolean", "date", "json"];
|
|
|
|
function inferValueType(value: unknown): FactValueType {
|
|
if (typeof value === "string") return "string";
|
|
if (typeof value === "number") return "number";
|
|
if (typeof value === "boolean") return "boolean";
|
|
return "json";
|
|
}
|
|
|
|
function assertEntity(entity: CanonicalEntityInput, label: string): void {
|
|
if (!entity || !entity.entity_type || !entity.identity_namespace || !entity.identity_value) {
|
|
throw new SiaxError("INVALID_REQUEST", "0pt.canonical_fact", `${label} requires entity_type, identity_namespace and identity_value`);
|
|
}
|
|
}
|
|
|
|
function assertFact(fact: CanonicalFactInput, index: number): void {
|
|
assertEntity(fact.entity, `facts[${index}].entity`);
|
|
if (!fact.predicate) throw new SiaxError("INVALID_REQUEST", "0pt.canonical_fact", `facts[${index}].predicate is required`);
|
|
if (!fact.source_ref) throw new SiaxError("INVALID_REQUEST", "0pt.canonical_fact", `facts[${index}].source_ref is required`);
|
|
if (!fact.extractor_version) throw new SiaxError("INVALID_REQUEST", "0pt.canonical_fact", `facts[${index}].extractor_version is required`);
|
|
if (!fact.observed_at || Number.isNaN(Date.parse(fact.observed_at))) {
|
|
throw new SiaxError("INVALID_REQUEST", "0pt.canonical_fact", `facts[${index}].observed_at must be an ISO timestamp`);
|
|
}
|
|
if (fact.value === undefined) throw new SiaxError("INVALID_REQUEST", "0pt.canonical_fact", `facts[${index}].value is required`);
|
|
if (fact.value_type && !FACT_VALUE_TYPES.includes(fact.value_type)) {
|
|
throw new SiaxError("INVALID_REQUEST", "0pt.canonical_fact", `facts[${index}].value_type is invalid`);
|
|
}
|
|
if (fact.confidence !== undefined && (fact.confidence < 0 || fact.confidence > 1)) {
|
|
throw new SiaxError("INVALID_REQUEST", "0pt.canonical_fact", `facts[${index}].confidence must be between 0 and 1`);
|
|
}
|
|
}
|
|
|
|
function assertRelation(relation: CanonicalRelationInput, index: number): void {
|
|
assertEntity(relation.subject, `relations[${index}].subject`);
|
|
assertEntity(relation.object, `relations[${index}].object`);
|
|
if (!relation.predicate) throw new SiaxError("INVALID_REQUEST", "0pt.canonical_relation", `relations[${index}].predicate is required`);
|
|
if (!relation.source_ref) throw new SiaxError("INVALID_REQUEST", "0pt.canonical_relation", `relations[${index}].source_ref is required`);
|
|
if (!relation.extractor_version) throw new SiaxError("INVALID_REQUEST", "0pt.canonical_relation", `relations[${index}].extractor_version is required`);
|
|
if (!relation.observed_at || Number.isNaN(Date.parse(relation.observed_at))) {
|
|
throw new SiaxError("INVALID_REQUEST", "0pt.canonical_relation", `relations[${index}].observed_at must be an ISO timestamp`);
|
|
}
|
|
}
|
|
|
|
export interface CanonicalFactServiceOptions {
|
|
repository?: CanonicalFactRepository;
|
|
aud0BaseUrl?: string;
|
|
databaseUrl?: string;
|
|
}
|
|
|
|
export class CanonicalFactService {
|
|
private readonly repo: CanonicalFactRepository;
|
|
private readonly aud0: Aud0Client;
|
|
|
|
constructor(opts?: CanonicalFactServiceOptions) {
|
|
this.repo = opts?.repository ?? createCanonicalFactRepository(opts?.databaseUrl);
|
|
this.aud0 = createAud0Client(opts?.aud0BaseUrl);
|
|
}
|
|
|
|
async write(input: CanonicalWriteRequest): Promise<CanonicalWriteResult> {
|
|
if (!input.tenant_id) throw new SiaxError("INVALID_REQUEST", "0pt.canonical_fact", "tenant_id is required");
|
|
const facts = input.facts ?? [];
|
|
const relations = input.relations ?? [];
|
|
const explicit = input.entities ?? [];
|
|
if (facts.length === 0 && relations.length === 0 && explicit.length === 0) {
|
|
throw new SiaxError("INVALID_REQUEST", "0pt.canonical_fact", "at least one entity, fact or relation is required");
|
|
}
|
|
facts.forEach(assertFact);
|
|
relations.forEach(assertRelation);
|
|
|
|
// Unique entity inputs from explicit + facts + relations.
|
|
const unique = new Map<string, CanonicalEntityInput>();
|
|
for (const e of [...explicit, ...facts.map((f) => f.entity), ...relations.flatMap((r) => [r.subject, r.object])]) {
|
|
assertEntity(e, "entity");
|
|
unique.set(entityKey(e), e);
|
|
}
|
|
const entities: CanonicalEntity[] = await this.repo.upsertEntities(input.tenant_id, [...unique.values()]);
|
|
const entityIds = new Map(entities.map((e) => [entityKey(e), e.entity_id]));
|
|
|
|
const normalizedFacts = facts.map((f) => ({ ...f, value_type: f.value_type ?? inferValueType(f.value) }));
|
|
const factResult = await this.repo.insertFacts(input.tenant_id, normalizedFacts, entityIds);
|
|
const relationResult = await this.repo.insertRelations(input.tenant_id, relations, entityIds);
|
|
|
|
// AUD0: counts and provenance refs only, never fact values (PII discipline).
|
|
try {
|
|
await this.aud0.ingestEvent({
|
|
event_id: `evt_0pt_canonical_facts_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`,
|
|
event_type: "0pt.canonical_facts_written",
|
|
tenant_id: input.tenant_id,
|
|
project_id: input.project_id ?? input.tenant_id,
|
|
actor_id: "0pt",
|
|
app_id: "0pt",
|
|
capability_id: "0pt.canonical_fact_write",
|
|
resource_type: "canonical_facts",
|
|
resource_id: input.tenant_id,
|
|
risk_level: "L2",
|
|
created_at: new Date().toISOString(),
|
|
payload: {
|
|
entities: entities.length,
|
|
facts_inserted: factResult.inserted,
|
|
facts_duplicates: factResult.duplicates,
|
|
relations_inserted: relationResult.inserted,
|
|
relations_duplicates: relationResult.duplicates,
|
|
source_refs: [...new Set([...facts.map((f) => f.source_ref), ...relations.map((r) => r.source_ref)])],
|
|
run_refs: [...new Set([...facts.map((f) => f.run_ref), ...relations.map((r) => r.run_ref)].filter(Boolean))],
|
|
},
|
|
});
|
|
} catch {
|
|
// AUD0 outage must not lose the canonical write; the caller sees counts.
|
|
}
|
|
|
|
return {
|
|
entities,
|
|
facts: normalizedFacts.map((f) => ({
|
|
fact_id: "",
|
|
entity_id: entityIds.get(entityKey(f.entity)) ?? "",
|
|
predicate: f.predicate,
|
|
})),
|
|
relations: relations.map((r) => ({
|
|
relation_id: "",
|
|
subject_id: entityIds.get(entityKey(r.subject)) ?? "",
|
|
predicate: r.predicate,
|
|
object_id: entityIds.get(entityKey(r.object)) ?? "",
|
|
})),
|
|
duplicates: factResult.duplicates + relationResult.duplicates,
|
|
};
|
|
}
|
|
|
|
async query(query: CanonicalQuery): Promise<CanonicalFact[]> {
|
|
if (!query.tenant_id) throw new SiaxError("INVALID_REQUEST", "0pt.canonical_fact", "tenant_id is required");
|
|
return this.repo.queryFacts({ ...query, limit: Math.min(query.limit ?? 100, 500) });
|
|
}
|
|
}
|