logicsrc/packages/openontology/src/canonical.ts
Anthony Ettinger 58c942c67f
Some checks failed
CI / build (push) Has been cancelled
test / test (push) Has been cancelled
feat(openontology): implement OpenOntology Phase 0 + local engine and CLI (#99)
Implements OpenPRD 0001 through Phase 0 (specification, schemas, example,
docs surface) and Phase 1 (local engine, CLI, conformance tests).

Schemas (17 contracts, JSON Schema Draft 2020-12, additionalProperties:false)
  manifest, namespace, entity-type, property, relationship-type, constraint,
  query, action, entity, claim, source, evidence, changeset, review, approval,
  event, package — registered in @logicsrc/validators and exported from
  @logicsrc/schemas under https://logicsrc.com/schemas/openontology/.

@logicsrc/openontology
  - canonical JSON + sha256 package digests; YAML, JSON, NDJSON, and inline
    authoring all compile to the same bytes, so digests are authoring-agnostic
  - id profile: compact / IRI / urn with one canonicalization rule, prefix
    bound by a Namespace object so IRIs reverse unambiguously
  - validation: schema, graph (domain/range, datatypes, dangling refs),
    provenance (source-or-firstParty, agent runId, derivation inputs), policy
    (excerpt limits, licensing, visibility, staleness) and declared
    constraints; four severities, stable codes, text/json/yaml/markdown
  - portable triple-pattern query AST: multi-hop, 14 operators, asOf and
    recordedAsOf, per-status filtering, distinct/order/limit, explanation
    mode, and enforced depth/binding/row limits
  - append-only store: claims are immutable; dispute/retract/supersede append
    status transitions and the effective status is the latest one
  - change sets: 9 operations, atomic pre-flight, conflict detection on stale
    base revisions, semantic diff with duplicate-identity warnings and
    affected-query deltas, per-operation reviewer decisions
  - policy: agents propose but can never apply — the denial keys on actor
    type, so every scope plus high confidence plus --yolo still cannot apply;
    merges need approval, bulk retractions need two, undeclared action side
    effects are denied
  - JSON-LD 1.1 export/import with PROV-O aliases and lossy-field reporting
  - pluggable signature envelope with a jws-ed25519 reference profile and a
    fail-closed trust policy

CLI: logicsrc ontology init|validate|lint|build|inspect, entity, claim, query,
changeset, import, export, audit. Reads take --format, writes default to a
proposal, exit codes are stable for CI.

Example: examples/openontology/ethereum-ecosystem — 12 entity types, 17
relationship types, 63 entities, 169 claims, 25 sources, 31 evidence records,
5 saved queries, every claim lifecycle state, and a pending merge proposal.
All data is fictional; the directory is removable without affecting any core
test.

Docs: docs/openontology{,-governance,-interoperability}.md, a real
/openontology route, homepage + nav + sitemap entries, and a root README
section.

Verification: 112 new tests; full monorepo build and every workspace test
pass; conformance bundle (18 valid + 13 invalid fixtures) runs against the
published schemas alone; Node.js 25 and Bun 1.3 produce byte-identical
digests, revisions, event trails, and query results.

Not included (later PRD phases): MCP resources, REST/SSE, Turso adapter, TUI
and PWA surfaces, RDF/SHACL mappings, source adapters, governed actions.

Refs: prd/0001-add-logicsrc-openontology-spec.md

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-26 02:10:13 -07:00

68 lines
2.5 KiB
TypeScript

import { createHash } from "node:crypto";
/**
* Deterministic canonical JSON.
*
* Authoring formats (YAML, NDJSON, inline manifest arrays) are compiled into
* this form before anything is hashed, signed, diffed, or published, so two
* implementations that agree on the model agree on the bytes.
*
* Rules: object keys sorted by code unit, `undefined` members dropped,
* array order preserved, no insignificant whitespace, JSON string escaping.
*/
export function canonicalize(value: unknown): string {
return stringify(value);
}
function stringify(value: unknown): string {
if (value === null) return "null";
const type = typeof value;
if (type === "number") {
if (!Number.isFinite(value as number)) {
throw new Error(`Cannot canonicalize non-finite number: ${String(value)}`);
}
// -0 and 0 must not produce different bytes.
return JSON.stringify(value === 0 ? 0 : value);
}
if (type === "boolean" || type === "string") return JSON.stringify(value);
if (type === "bigint") throw new Error("Cannot canonicalize bigint");
if (type === "undefined" || type === "function" || type === "symbol") {
throw new Error(`Cannot canonicalize ${type} at the top level`);
}
if (Array.isArray(value)) {
return `[${value.map((item) => stringify(item === undefined ? null : item)).join(",")}]`;
}
const entries = Object.entries(value as Record<string, unknown>)
.filter(([, v]) => v !== undefined)
.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${stringify(v)}`).join(",")}}`;
}
/** Strip `undefined` members so a value round-trips through canonical JSON unchanged. */
export function canonicalObject<T>(value: T): T {
return JSON.parse(canonicalize(value)) as T;
}
/** `sha256:<hex>` over the canonical JSON of a value, or over a raw string. */
export function digest(value: unknown): string {
const input = typeof value === "string" ? value : canonicalize(value);
return `sha256:${createHash("sha256").update(input, "utf8").digest("hex")}`;
}
/**
* Package digest: covers the canonical manifest plus the sorted per-file
* digest table, so any change to any declared file changes the package digest.
*/
export function packageDigest(
manifest: unknown,
files: Array<{ path: string; digest: string }>
): string {
const table = [...files]
.map((f) => ({ path: f.path, digest: f.digest }))
.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
return digest({ manifest, files: table });
}