feat(openontology): Phase 2 + Phase 3 — storage, REST/SSE, MCP, RDF/SHACL, adapters, TUI, explorer

Everything the two shipped PRD phases deferred, minus what is called out below.

Storage (Phase 2)
  @logicsrc/openontology gains a SQLite/Turso adapter. It hydrates the read
  model at open, serves reads synchronously — a query evaluator that awaits per
  triple pattern is unusable — and buffers mutations as SQL that flush() writes
  in one transaction. Versioned idempotent migrations; indexes over subject,
  predicate, entity-valued object, status, both time axes, aliases, and external
  ids; FTS5 for label/alias search. The append-only status log is replayed on
  open, so retractions, supersessions, and merge redirects survive a reopen.

REST + SSE + OpenAPI (Phase 2)
  16 paths under /api/ontologies in logicsrc-web, described at
  /api/ontologies/openapi and referencing the published JSON Schemas rather
  than restating them. No token is read-only; a curator token can apply; an
  agent token can propose and cannot apply. Idempotency-Key on mutations,
  revision ETags, 409 on a stale base revision, and an SSE stream that emits
  the same event objects as the JSON endpoint.

MCP (Phase 2)
  OpenOntology and OpenPRD surfaces on the standards server: spec/manifest/
  schema/queries and PRD spec/index as resources, 11 ontology tools and 6 PRD
  tools, 7 prompts. Read-only by default; OPENONTOLOGY_MCP_WRITABLE=1 buys
  proposals, never applies — the denial is the shared policy layer, not a
  second rule that could drift.

Interoperability (Phase 3)
  RDF/Turtle export and import of the reified profile, plus the plain triple
  for asserted relationships so a consumer wanting only the accepted graph gets
  one. SHACL for 5 of 7 constraint kinds; `unique` and `query` are reported as
  unmapped in both the return value and the generated Turtle, because a shape
  that quietly means something narrower is worse than no shape.

Source adapters (Phase 3)
  CSV, JSON, YAML, NDJSON, Markdown, generic JSON HTTP, and GitHub. All produce
  PROPOSED change-set operations with source, evidence selector, run id, and
  confidence attached; fetch is injected so ingestion is offline and testable.
  Each declares its capabilities, so "nothing was deleted upstream" is never
  confused with "this adapter cannot see deletions" — none of the seven can.

TUI + explorer
  Keyboard-first panels (types, entities, claims, sources, queries, change
  sets, validation, audit) as plain strings that survive SSH and 60 columns;
  status is a glyph and a word, never colour alone; the key bar wraps rather
  than truncating. Wired as `logicsrc ontology tui`. A read-only web explorer
  at /openontology/explore with entity and claim views showing status, both
  clocks, confidence, sources, evidence, and append-only history — plus an
  /openprd page for the companion standard.

Bugs found and fixed while testing
  - the API built a new engine per request, so `explain` could never find a
    resultId from a prior request; engines are now cached per role
  - the TUI status bar called engine.validateOntologyPackage(), appending a
    package.validated event on every repaint; it now uses the pure validator

Verification: 76 new tests (527 total across the monorepo, all passing); full
build green; the libSQL adapter is exercised against real files, the API
through its route handlers, and MCP over an in-memory transport.

Not included: PWA review/approval write flows (they need an auth story this
deployment does not have), OWL/RDFS mappings, SPARQL/Cypher/Datalog query
adapters, and Phase 4 governed actions. The compatibility matrix marks those
"planned", not "supported".

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

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Anthony Ettinger 2026-07-28 12:10:03 +00:00
parent 296775e003
commit 26c8110926
53 changed files with 6939 additions and 23 deletions

View file

@ -2,6 +2,7 @@ import { readFileSync, writeFileSync } from "node:fs";
import { resolve } from "node:path";
import { Command } from "commander";
import { parse as parseYaml, stringify as toYaml } from "yaml";
import { renderOntologyKeyHelp, renderOntologyTui, type OntologyPanel } from "@logicsrc/tui";
import {
buildOntologyPackage,
createOntologyEngine,
@ -687,6 +688,26 @@ export function registerOntologyCommands(program: Command): void {
);
});
actorOptions(
ontology
.command("tui")
.option("--dir <dir>", "package directory", ".")
.option("--panel <panel>", "types|entities|claims|sources|queries|changesets|violations|audit", "entities")
.option("--width <n>", "terminal width", String(process.stdout.columns || 78))
.option("--rows <n>", "detail rows", "10")
.description("Render the keyboard-first ontology panels.")
).action((options) => {
const e = openEngine(options.dir, options);
console.log(
renderOntologyTui(e, {
panel: options.panel as OntologyPanel,
width: Number.parseInt(options.width, 10),
rows: Number.parseInt(options.rows, 10)
})
);
console.log(renderOntologyKeyHelp());
});
actorOptions(
ontology
.command("audit")

View file

@ -1,7 +1,7 @@
{
"name": "@profullstack/logicsrc-mcp",
"version": "0.1.0",
"description": "MCP server for LogicSRC standards, schemas, prompts, and validators.",
"description": "MCP server for LogicSRC standards, schemas, prompts, validators, OpenOntology, and OpenPRD.",
"type": "module",
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
@ -13,6 +13,8 @@
"test": "vitest run src"
},
"dependencies": {
"@logicsrc/openontology": "file:../openontology",
"@logicsrc/openprd": "file:../openprd",
"@logicsrc/validators": "file:../validators",
"@modelcontextprotocol/sdk": "^1.29.0",
"zod": "^4.1.13"

View file

@ -0,0 +1,564 @@
import { existsSync, readFileSync } from "node:fs";
import { resolve } from "node:path";
import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { z } from "zod";
import {
createOntologyEngine,
exportJsonLd,
exportTurtle,
constraintsToShacl,
loadOntologyPackage,
readOnlyActor,
proposerActor,
renderReport,
type OntologyEngine
} from "@logicsrc/openontology";
/**
* OpenOntology surface for the MCP server.
*
* Read tools are always available. Write tools exist but are capability-scoped
* and default to *proposal* behaviour (R158): the server runs as a read-only
* actor unless OPENONTOLOGY_MCP_WRITABLE is set, and even then an agent actor
* can only propose — applying is denied by the policy layer, not by this file.
*/
const SPEC = `# LogicSRC OpenOntology
An open contract for durable, source-backed domain knowledge shared by humans
and AI agents. Five nouns: Type, Entity, Claim, Source, Change set.
- Claims are the canonical fact record and are append-only. A correction is a
dispute, retraction, or supersession — never an edit.
- Every claim carries status, confidence, valid time, recorded time, and the
sources it rests on. Confidence is metadata, never permission.
- Queries use a portable triple-pattern AST with asOf and per-status filtering,
and every answer can be traced to the claims, evidence, and sources behind it.
- Agents propose; humans apply. An agent holding every scope still cannot apply.
Full specification: https://logicsrc.com/docs/openontology`;
interface OntologyContext {
engine: OntologyEngine | null;
packageDir: string | null;
error: string | null;
writable: boolean;
}
function loadContext(): OntologyContext {
const dir = process.env.OPENONTOLOGY_PACKAGE ?? null;
const writable = process.env.OPENONTOLOGY_MCP_WRITABLE === "1";
if (!dir) {
return { engine: null, packageDir: null, writable, error: "OPENONTOLOGY_PACKAGE is not set" };
}
const path = resolve(dir);
if (!existsSync(path)) {
return { engine: null, packageDir: path, writable, error: `${path} does not exist` };
}
try {
const pkg = loadOntologyPackage(path);
const actor = writable ? proposerActor("agent:mcp") : readOnlyActor("agent:mcp");
return {
engine: createOntologyEngine({ package: pkg, actor, client: "logicsrc-mcp" }),
packageDir: path,
writable,
error: null
};
} catch (error) {
return { engine: null, packageDir: path, writable, error: (error as Error).message };
}
}
function textResult(text: string) {
return { content: [{ type: "text" as const, text }] };
}
function errorResult(text: string) {
return { content: [{ type: "text" as const, text }], isError: true };
}
export function registerOpenOntology(server: McpServer): void {
const context = loadContext();
const requireEngine = (): OntologyEngine | null => context.engine;
const notConfigured = () =>
errorResult(
`No ontology package is loaded: ${context.error ?? "unknown reason"}. ` +
"Set OPENONTOLOGY_PACKAGE to a directory containing openontology.yaml."
);
/* ── resources ─────────────────────────────────────────────────────── */
server.registerResource(
"openontology-spec",
"logicsrc://openontology/spec",
{
title: "LogicSRC OpenOntology specification",
description: "The OpenOntology model in brief: five nouns, claims, provenance, governance.",
mimeType: "text/markdown"
},
async () => ({
contents: [{ uri: "logicsrc://openontology/spec", mimeType: "text/markdown", text: SPEC }]
})
);
if (context.engine) {
const engine = context.engine;
const manifest = engine.getOntologyManifest();
server.registerResource(
"openontology-manifest",
`ontology://${manifest.id}/manifest`,
{
title: `${manifest.name} manifest`,
description: "Package identity, namespace, licence, and maintainers.",
mimeType: "application/json"
},
async () => ({
contents: [
{
uri: `ontology://${manifest.id}/manifest`,
mimeType: "application/json",
text: JSON.stringify(manifest, null, 2)
}
]
})
);
server.registerResource(
"openontology-schema",
`ontology://${manifest.id}/schema`,
{
title: `${manifest.name} schema`,
description: "Entity types, properties, relationship types, constraints, and saved queries.",
mimeType: "application/json"
},
async () => ({
contents: [
{
uri: `ontology://${manifest.id}/schema`,
mimeType: "application/json",
text: JSON.stringify(engine.getOntologySchema(), null, 2)
}
]
})
);
server.registerResource(
"openontology-queries",
`ontology://${manifest.id}/queries`,
{
title: `${manifest.name} saved queries`,
description: "The questions this ontology already knows how to answer.",
mimeType: "application/json"
},
async () => ({
contents: [
{
uri: `ontology://${manifest.id}/queries`,
mimeType: "application/json",
text: JSON.stringify(engine.getOntologySchema().queries, null, 2)
}
]
})
);
}
/* ── read tools ────────────────────────────────────────────────────── */
server.registerTool(
"ontology_status",
{
title: "OpenOntology status",
description: "Reports which ontology package this server has loaded and whether writes are enabled.",
annotations: { readOnlyHint: true, openWorldHint: false }
},
async () =>
textResult(
JSON.stringify(
{
loaded: Boolean(context.engine),
packageDir: context.packageDir,
error: context.error,
writable: context.writable,
note: "Write tools propose change sets; applying is denied to agent actors by policy."
},
null,
2
)
)
);
server.registerTool(
"ontology_validate",
{
title: "Validate the loaded ontology package",
description: "Runs schema, graph, provenance, policy, and constraint validation.",
inputSchema: { strict: z.boolean().optional().describe("Treat unknown types and predicates as errors.") },
annotations: { readOnlyHint: true, openWorldHint: false }
},
async ({ strict }) => {
const engine = requireEngine();
if (!engine) return notConfigured();
const report = engine.validateOntologyPackage({ strict: strict === true });
return textResult(renderReport(report, "markdown"));
}
);
server.registerTool(
"ontology_get_entity",
{
title: "Get an entity",
description: "Fetches one entity by id, following merge redirects.",
inputSchema: { id: z.string().describe("Entity id, e.g. eth:person:avery-lindqvist") },
annotations: { readOnlyHint: true, openWorldHint: false }
},
async ({ id }) => {
const engine = requireEngine();
if (!engine) return notConfigured();
try {
return textResult(JSON.stringify(engine.getEntity(id), null, 2));
} catch (error) {
return errorResult((error as Error).message);
}
}
);
server.registerTool(
"ontology_find_entities",
{
title: "Find entities",
description: "Ranked candidate matches with the evidence for each — never a silent single match.",
inputSchema: {
text: z.string().optional(),
type: z.string().optional(),
limit: z.number().int().positive().max(100).optional()
},
annotations: { readOnlyHint: true, openWorldHint: false }
},
async ({ text, type, limit }) => {
const engine = requireEngine();
if (!engine) return notConfigured();
const matches = engine.findEntities({ text, type, limit });
return textResult(
JSON.stringify(
matches.map((match) => ({
id: match.entity.id,
name: match.entity.canonicalName,
type: match.entity.type,
score: match.score,
matchedOn: match.matchedOn,
evidence: match.evidence
})),
null,
2
)
);
}
);
server.registerTool(
"ontology_query",
{
title: "Run a portable query",
description:
"Runs a saved query by id, or an ad-hoc triple-pattern query. Results include the claim ids behind each row.",
inputSchema: {
savedQuery: z.string().optional().describe("Saved query id."),
query: z.string().optional().describe("JSON query body with match/where/select/include."),
asOf: z.string().optional().describe("ISO instant to evaluate domain valid time against."),
limit: z.number().int().positive().max(500).optional()
},
annotations: { readOnlyHint: true, openWorldHint: false }
},
async ({ savedQuery, query, asOf, limit }) => {
const engine = requireEngine();
if (!engine) return notConfigured();
if (!savedQuery && !query) return errorResult("Provide savedQuery or query.");
try {
const body = savedQuery
? savedQuery
: ({ ...(JSON.parse(query as string) as Record<string, unknown>) } as never);
const result = engine.queryOntology(body as never);
const rows = result.rows.slice(0, limit ?? 50);
const manifest = engine.getOntologyManifest();
// R160: factual answers carry the ontology version and claim ids.
return textResult(
JSON.stringify(
{
ontology: `${manifest.id}@${manifest.version}`,
resultId: result.id,
columns: result.columns,
claimStatus: result.explanation.claimStatus,
asOf: asOf ?? result.explanation.asOf ?? null,
rows: rows.map((row) => ({ ...row.bindings, claims: row.claims })),
truncated: result.explanation.truncated || rows.length < result.rows.length
},
null,
2
)
);
} catch (error) {
return errorResult((error as Error).message);
}
}
);
server.registerTool(
"ontology_explain",
{
title: "Explain an answer",
description: "Traces one result row to its claims, evidence, sources, and status history.",
inputSchema: {
resultId: z.string().describe("resultId returned by ontology_query."),
row: z.number().int().nonnegative().optional()
},
annotations: { readOnlyHint: true, openWorldHint: false }
},
async ({ resultId, row }) => {
const engine = requireEngine();
if (!engine) return notConfigured();
try {
return textResult(JSON.stringify(engine.explainOntologyResult(resultId, row ?? 0), null, 2));
} catch (error) {
return errorResult((error as Error).message);
}
}
);
server.registerTool(
"ontology_export",
{
title: "Export the ontology",
description: "Exports as JSON-LD, RDF/Turtle, or SHACL shapes, reporting anything the format cannot carry.",
inputSchema: { format: z.enum(["jsonld", "turtle", "shacl"]) },
annotations: { readOnlyHint: true, openWorldHint: false }
},
async ({ format }) => {
const engine = requireEngine();
if (!engine) return notConfigured();
const pkg = engine.buildOntologyPackage();
if (format === "turtle") {
const exported = exportTurtle(pkg);
return textResult(
`${exported.turtle}\n# lossy: ${exported.lossy.length} object(s) carry fields Turtle cannot express`
);
}
if (format === "shacl") {
const exported = constraintsToShacl(pkg);
return textResult(exported.turtle);
}
const exported = exportJsonLd(pkg);
return textResult(
JSON.stringify({ document: exported.document, lossy: exported.lossy }, null, 2)
);
}
);
/* ── write tools (proposal-only) ───────────────────────────────────── */
server.registerTool(
"ontology_propose_claim",
{
title: "Propose a claim",
description:
"Creates a PROPOSED change set asserting one claim. Never applies it — a human with write scope does that.",
inputSchema: {
subject: z.string(),
predicate: z.string(),
objectEntity: z.string().optional(),
objectValue: z.string().optional(),
source: z.string().optional().describe("Source id backing the claim."),
confidence: z.number().min(0).max(1).optional(),
runId: z.string().optional(),
rationale: z.string().optional()
},
annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: false }
},
async (input) => {
const engine = requireEngine();
if (!engine) return notConfigured();
if (!input.objectEntity && input.objectValue === undefined) {
return errorResult("Provide objectEntity or objectValue.");
}
try {
const changeSet = engine.createOntologyChangeSet({
title: `${input.subject} ${input.predicate} ${input.objectEntity ?? input.objectValue}`,
rationale: input.rationale,
runId: input.runId,
operations: [
{
op: "assert-claim",
value: {
subject: input.subject,
predicate: input.predicate,
object: input.objectEntity ? { entity: input.objectEntity } : { value: input.objectValue },
...(input.source ? { sources: [input.source] } : {}),
...(input.confidence !== undefined ? { confidence: input.confidence } : {})
}
}
]
});
return textResult(
JSON.stringify(
{ changeSet: changeSet.id, status: changeSet.status, requiredApprovals: changeSet.requiredApprovals },
null,
2
)
);
} catch (error) {
return errorResult((error as Error).message);
}
}
);
server.registerTool(
"ontology_create_changeset",
{
title: "Create a change set",
description: "Creates a PROPOSED change set from a JSON array of operations.",
inputSchema: {
title: z.string(),
operations: z.string().describe("JSON array of change-set operations."),
rationale: z.string().optional(),
runId: z.string().optional()
},
annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: false }
},
async ({ title, operations, rationale, runId }) => {
const engine = requireEngine();
if (!engine) return notConfigured();
try {
const parsed = JSON.parse(operations) as never[];
const changeSet = engine.createOntologyChangeSet({ title, rationale, runId, operations: parsed });
const diff = engine.diffOntologyChangeSet(changeSet.id);
return textResult(JSON.stringify({ changeSet: changeSet.id, status: changeSet.status, diff }, null, 2));
} catch (error) {
return errorResult((error as Error).message);
}
}
);
server.registerTool(
"ontology_validate_changeset",
{
title: "Validate a change set",
description: "Validates the package as it would look after a change set applies.",
inputSchema: { changeSet: z.string() },
annotations: { readOnlyHint: true, openWorldHint: false }
},
async ({ changeSet }) => {
const engine = requireEngine();
if (!engine) return notConfigured();
try {
return textResult(renderReport(engine.validateOntologyChangeSet(changeSet), "markdown"));
} catch (error) {
return errorResult((error as Error).message);
}
}
);
server.registerTool(
"ontology_apply_changeset",
{
title: "Apply a change set",
description:
"Applies an approved change set. Requires write scope and approvals; agent actors are denied by policy.",
inputSchema: { changeSet: z.string() },
annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: false }
},
async ({ changeSet }) => {
const engine = requireEngine();
if (!engine) return notConfigured();
try {
const applied = engine.applyOntologyChangeSet(changeSet);
return textResult(
JSON.stringify({ changeSet: applied.changeSet.id, revision: applied.revision }, null, 2)
);
} catch (error) {
// The denial is the point: surface it verbatim.
return errorResult(`Not applied: ${(error as Error).message}`);
}
}
);
/* ── prompts ───────────────────────────────────────────────────────── */
const prompts: Array<[string, string, string]> = [
[
"design_ontology",
"Design an OpenOntology package for a domain",
`Design a LogicSRC OpenOntology package for the domain the user describes.
Produce entity types, properties, and relationship types first — nouns before facts.
For each relationship type declare from/to, cardinality, and whether it is temporal.
Do not infer transitivity, symmetry, or inverses unless you declare them.
Then propose 3-5 saved queries that answer the questions people actually ask.
Return YAML matching the OpenOntology schemas.`
],
[
"map_sources_to_claims",
"Turn source material into proposed claims",
`Read the source material and produce PROPOSED claims.
Every claim needs: subject, predicate, a typed object, a source id, and an evidence
selector pointing at the exact location it came from. Set confidence honestly — it is
metadata, not persuasion. Never invent an entity id you have not seen; propose a new
entity explicitly instead. Output change-set operations, not applied state.`
],
[
"resolve_entities",
"Decide whether two entity records are the same thing",
`Compare the candidate entity records.
List the evidence for and against them being the same thing. Weigh stable external ids
above name similarity. Recommend merge, keep-separate, or needs-more-evidence — and say
which. Remember that merging two different people is worse than keeping duplicates, and
that a merge needs curator approval.`
],
[
"review_ontology_changeset",
"Review a proposed change set",
`Review this OpenOntology change set as a curator.
Check: does each claim cite a source? Do the domain and range hold? Is the confidence
justified by the evidence? Does any add-entity duplicate something already present?
Are merges and retractions reversible and justified? Report per-operation accept/reject
with reasons, then an overall recommendation.`
],
[
"explain_ontology_answer",
"Explain why the ontology returned an answer",
`Explain this query result to someone who does not trust it yet.
Walk from the answer to the claims that produced it, then to the evidence and sources.
State the claim statuses included, the asOf time, and any filters applied. Name what is
uncertain — low confidence, a single source, a stale source, a dispute — rather than
presenting the row as settled fact.`
]
];
for (const [name, title, text] of prompts) {
server.registerPrompt(
name,
{ title, description: title },
async () => ({ messages: [{ role: "user" as const, content: { type: "text" as const, text } }] })
);
}
}
/** Read the packaged spec doc when it is available on disk. */
export function readSpecDoc(path: string): string | null {
try {
return existsSync(path) ? readFileSync(path, "utf8") : null;
} catch {
return null;
}
}

View file

@ -0,0 +1,278 @@
import { existsSync } from "node:fs";
import { resolve } from "node:path";
import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { z } from "zod";
import {
findPrd,
loadPrdCollection,
nextPrdNumber,
nextStatuses,
prdToTasks,
renderDocument,
renderIndex,
renderReport,
summarize,
validatePrdCollection,
validateTasks,
type PrdCollection
} from "@logicsrc/openprd";
/**
* OpenPRD surface for the MCP server.
*
* Everything here is read-only. Creating or moving a PRD writes to a repo, and
* that belongs to the CLI where a human sees the diff — not to a tool an agent
* can call unattended.
*/
const SPEC = `# OpenPRD
A lightweight standard for product requirements documents. A repo keeps a
numbered, committed collection under prd/, one Markdown file each.
- One file per PRD: prd/<id>-<slug>.md, four-digit ids, no gaps, 0000 reserved
for the template.
- Front-matter carries openprd, id, title, status, authors, and optional repo,
dates, discussion, implementation, tags, supersedes, superseded-by.
- The body has eight required sections in order: Problem, Goals, Non-Goals,
Users, Requirements, UX Notes, Success Metrics, Risks & Open Questions.
- Requirements are numbered R1, R2, … each tagged [P0], [P1], or [P2].
- Lifecycle: Draft → Review → Accepted → Final, or Rejected / Withdrawn /
Superseded. Status lives in front-matter and is the source of truth.
Full specification: https://logicsrc.com/docs/openprd`;
function textResult(text: string) {
return { content: [{ type: "text" as const, text }] };
}
function errorResult(text: string) {
return { content: [{ type: "text" as const, text }], isError: true };
}
function openCollection(): { collection: PrdCollection | null; dir: string | null; error: string | null } {
const dir = process.env.OPENPRD_DIR ?? "./prd";
const path = resolve(dir);
if (!existsSync(path)) {
return { collection: null, dir: path, error: `${path} does not exist; set OPENPRD_DIR` };
}
try {
return { collection: loadPrdCollection(path), dir: path, error: null };
} catch (error) {
return { collection: null, dir: path, error: (error as Error).message };
}
}
export function registerOpenPrd(server: McpServer): void {
server.registerResource(
"openprd-spec",
"logicsrc://openprd/spec",
{
title: "OpenPRD specification",
description: "Numbered PRDs: layout, front-matter, the eight sections, and the lifecycle.",
mimeType: "text/markdown"
},
async () => ({
contents: [{ uri: "logicsrc://openprd/spec", mimeType: "text/markdown", text: SPEC }]
})
);
server.registerResource(
"openprd-index",
"prd://index",
{
title: "PRD index",
description: "The current collection index, generated from the PRDs on disk.",
mimeType: "text/markdown"
},
async () => {
const { collection, error } = openCollection();
const text = collection ? renderIndex(collection) : `No PRD collection: ${error}`;
return { contents: [{ uri: "prd://index", mimeType: "text/markdown", text }] };
}
);
server.registerTool(
"prd_list",
{
title: "List PRDs",
description: "Lists the PRDs in the collection with id, title, status, tags, and requirement count.",
inputSchema: { status: z.string().optional().describe("Comma-separated statuses to include.") },
annotations: { readOnlyHint: true, openWorldHint: false }
},
async ({ status }) => {
const { collection, error } = openCollection();
if (!collection) return errorResult(error ?? "no collection");
const wanted = status?.split(",").map((value) => value.trim());
const rows = collection.documents
.map(summarize)
.filter((row) => !wanted || wanted.includes(row.status));
return textResult(JSON.stringify(rows, null, 2));
}
);
server.registerTool(
"prd_show",
{
title: "Show a PRD",
description: "Shows one PRD's front-matter, sections, and parsed requirements.",
inputSchema: {
ref: z.string().describe("Id, number, slug, or filename."),
format: z.enum(["text", "json", "markdown"]).optional()
},
annotations: { readOnlyHint: true, openWorldHint: false }
},
async ({ ref, format }) => {
const { collection, error } = openCollection();
if (!collection) return errorResult(error ?? "no collection");
const doc = findPrd(collection, ref);
if (!doc) return errorResult(`No PRD matching "${ref}"`);
return textResult(renderDocument(doc, format ?? "text"));
}
);
server.registerTool(
"prd_validate",
{
title: "Validate the PRD collection",
description:
"Checks conformance — filename, front-matter, id match, the eight sections in order — plus collection rules.",
inputSchema: { strict: z.boolean().optional() },
annotations: { readOnlyHint: true, openWorldHint: false }
},
async ({ strict }) => {
const { collection, error } = openCollection();
if (!collection) return errorResult(error ?? "no collection");
const report = validatePrdCollection(collection, {
strict: strict === true,
expectedIndex: renderIndex(collection)
});
return textResult(renderReport(report, "markdown"));
}
);
server.registerTool(
"prd_next_id",
{
title: "Next free PRD id",
description: "Returns the next four-digit id. Numbers are assigned at creation, never reserved.",
annotations: { readOnlyHint: true, openWorldHint: false }
},
async () => {
const { collection, error } = openCollection();
if (!collection) return errorResult(error ?? "no collection");
return textResult(nextPrdNumber(collection));
}
);
server.registerTool(
"prd_next_statuses",
{
title: "Allowed lifecycle moves",
description: "Given a PRD, lists the statuses it may legally move to next.",
inputSchema: { ref: z.string() },
annotations: { readOnlyHint: true, openWorldHint: false }
},
async ({ ref }) => {
const { collection, error } = openCollection();
if (!collection) return errorResult(error ?? "no collection");
const doc = findPrd(collection, ref);
if (!doc) return errorResult(`No PRD matching "${ref}"`);
const allowed = nextStatuses(doc.frontMatter.status);
return textResult(
JSON.stringify(
{
id: doc.frontMatter.id,
status: doc.frontMatter.status,
allowedNext: allowed,
terminal: allowed.length === 0
},
null,
2
)
);
}
);
server.registerTool(
"prd_tasks",
{
title: "Map requirements to LogicSRC tasks",
description: "Turns each R# into one logicsrc.task document, validated before it is returned.",
inputSchema: {
ref: z.string(),
priority: z.string().optional().describe("Comma-separated priorities, e.g. P0,P1"),
creator: z.string().optional()
},
annotations: { readOnlyHint: true, openWorldHint: false }
},
async ({ ref, priority, creator }) => {
const { collection, error } = openCollection();
if (!collection) return errorResult(error ?? "no collection");
const doc = findPrd(collection, ref);
if (!doc) return errorResult(`No PRD matching "${ref}"`);
const priorities = priority?.split(",").map((value) => value.trim()) as
| Array<"P0" | "P1" | "P2">
| undefined;
const { tasks, skipped } = prdToTasks(doc, { creator, priorities });
const problems = validateTasks(tasks);
if (problems.length > 0) {
return errorResult(`Generated tasks failed validation: ${JSON.stringify(problems, null, 2)}`);
}
return textResult(JSON.stringify({ tasks, skipped }, null, 2));
}
);
server.registerPrompt(
"write_prd",
{ title: "Draft an OpenPRD document", description: "Draft a conforming PRD for a product decision." },
async () => ({
messages: [
{
role: "user" as const,
content: {
type: "text" as const,
text: `Draft an OpenPRD document for the change the user describes.
Front-matter: openprd "0.2", a four-digit id matching the filename, an imperative
title starting with a verb, status Draft, and at least one author.
Then all eight sections, in this order, none omitted:
Problem, Goals, Non-Goals, Users, Requirements, UX Notes, Success Metrics,
Risks & Open Questions. A section may be a single line such as _None._
Requirements are numbered R1, R2, … contiguously, each tagged [P0], [P1], or [P2],
one capability per line. Goals are outcomes, not features. Non-Goals bound the work.
Risks & Open Questions must name the decisions still owed rather than pretending
they are settled.`
}
}
]
})
);
server.registerPrompt(
"review_prd",
{ title: "Review a PRD", description: "Review a PRD for shape, clarity, and honesty." },
async () => ({
messages: [
{
role: "user" as const,
content: {
type: "text" as const,
text: `Review this PRD.
Check the shape first: all eight sections present and in order, requirements numbered
contiguously with priority tags, front-matter complete.
Then the substance: are the Goals outcomes rather than features? Do the Non-Goals
actually bound the work? Is every P0 requirement testable? Do the Success Metrics
measure the Goals? Do the Risks name real decisions still owed, or is that section
decoration? Say what you would change and why.`
}
}
]
})
);
}

View file

@ -1,6 +1,8 @@
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { z } from "zod";
import { assertSchemaKind, parseDocument, schemas, validate, type SchemaKind } from "@logicsrc/validators";
import { registerOpenOntology } from "./openontology.js";
import { registerOpenPrd } from "./openprd.js";
const docs = {
"communication-accounts": `LogicSRC Communication Accounts defines shared contracts for connecting social and email identities, granting scoped human/agent/plugin access, evaluating policy gates, brokering credentials, and auditing every account action without exposing raw secrets.`,
@ -25,7 +27,7 @@ export function createLogicSrcMcpServer() {
tools: {},
prompts: {}
},
instructions: "Use this server for LogicSRC standards, schema resources, validation, and draft object generation. Treat CommandBoard.run as a reference implementation, not the standards identity."
instructions: "Use this server for LogicSRC standards, schema resources, validation, draft object generation, OpenOntology knowledge (entities, claims, provenance, governed change sets), and OpenPRD product requirements documents. Treat CommandBoard.run as a reference implementation, not the standards identity. Ontology and PRD write tools propose; they never apply."
}
);
@ -151,6 +153,9 @@ export function createLogicSrcMcpServer() {
})
);
registerOpenOntology(server);
registerOpenPrd(server);
return server;
}

View file

@ -0,0 +1,226 @@
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
import { initOntologyPackage } from "@logicsrc/openontology";
import { createLogicSrcMcpServer } from "./server.js";
const REPO = resolve(dirname(fileURLToPath(import.meta.url)), "../../..");
const dirs: string[] = [];
let ontologyDir: string;
beforeAll(() => {
ontologyDir = mkdtempSync(join(tmpdir(), "mcp-ontology-"));
dirs.push(ontologyDir);
initOntologyPackage(ontologyDir, { id: "test-ecosystem", now: "2026-07-26T00:00:00Z" });
process.env.OPENONTOLOGY_PACKAGE = ontologyDir;
process.env.OPENPRD_DIR = join(REPO, "prd");
});
afterAll(() => {
delete process.env.OPENONTOLOGY_PACKAGE;
delete process.env.OPENPRD_DIR;
for (const dir of dirs) rmSync(dir, { recursive: true, force: true });
});
async function connect() {
const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
const server = createLogicSrcMcpServer();
const client = new Client({ name: "test-client", version: "0.1.0" });
await server.connect(serverTransport);
await client.connect(clientTransport);
return client;
}
function toolText(result: unknown): string {
const content = (result as { content?: Array<{ type: string; text?: string }> }).content ?? [];
return content.map((entry) => entry.text ?? "").join("\n");
}
/** Resource contents are text-or-blob in the SDK types; these fixtures are text. */
function resourceText(contents: unknown): string {
const entry = (contents as Array<{ text?: string }>)[0];
return entry?.text ?? "";
}
function isError(result: unknown): boolean {
return (result as { isError?: boolean }).isError === true;
}
describe("MCP: OpenOntology", () => {
it("exposes the spec, manifest, schema, and saved queries as resources", async () => {
const client = await connect();
const uris = (await client.listResources()).resources.map((resource) => resource.uri);
expect(uris).toContain("logicsrc://openontology/spec");
expect(uris).toContain("ontology://test-ecosystem/manifest");
expect(uris).toContain("ontology://test-ecosystem/schema");
expect(uris).toContain("ontology://test-ecosystem/queries");
});
it("serves the ontology schema resource", async () => {
const client = await connect();
const resource = await client.readResource({ uri: "ontology://test-ecosystem/schema" });
expect(resourceText(resource.contents)).toContain("worksOn");
});
it("runs a query and returns claim ids with the ontology version (R160)", async () => {
const client = await connect();
const result = await client.callTool({ name: "ontology_query", arguments: { savedQuery: "contributors" } });
const payload = JSON.parse(toolText(result)) as {
ontology: string;
rows: Array<{ claims: string[] }>;
resultId: string;
};
expect(payload.ontology).toBe("test-ecosystem@0.1.0");
expect(payload.rows.length).toBeGreaterThan(0);
expect(payload.rows[0]!.claims.length).toBeGreaterThan(0);
});
it("explains a result down to sources", async () => {
const client = await connect();
const query = await client.callTool({ name: "ontology_query", arguments: { savedQuery: "contributors" } });
const { resultId } = JSON.parse(toolText(query)) as { resultId: string };
const explained = await client.callTool({
name: "ontology_explain",
arguments: { resultId, row: 0 }
});
const payload = JSON.parse(toolText(explained)) as { claims: Array<{ sources: unknown[] }> };
expect(payload.claims[0]!.sources.length).toBeGreaterThan(0);
});
it("validates the loaded package", async () => {
const client = await connect();
const result = await client.callTool({ name: "ontology_validate", arguments: { strict: true } });
expect(toolText(result)).toContain("Validation passed");
});
it("finds entities with ranked evidence rather than a silent match", async () => {
const client = await connect();
const result = await client.callTool({ name: "ontology_find_entities", arguments: { text: "Alice" } });
const matches = JSON.parse(toolText(result)) as Array<{ id: string; matchedOn: string; score: number }>;
expect(matches[0]!.id).toBe("test:person:alice");
expect(matches[0]!.matchedOn).toBeTruthy();
});
it("refuses to propose when the server is read-only (the default)", async () => {
const client = await connect();
const denied = await client.callTool({
name: "ontology_propose_claim",
arguments: {
subject: "test:person:alice",
predicate: "worksOn",
objectEntity: "test:project:docs-portal",
source: "test:source:repo"
}
});
expect(isError(denied)).toBe(true);
expect(toolText(denied)).toContain("ontology:claim:propose");
});
it("proposes a change set when writes are enabled — and still cannot apply it", async () => {
process.env.OPENONTOLOGY_MCP_WRITABLE = "1";
try {
const client = await connect();
const proposed = await client.callTool({
name: "ontology_propose_claim",
arguments: {
subject: "test:person:alice",
predicate: "worksOn",
objectEntity: "test:project:docs-portal",
source: "test:source:repo",
runId: "run_mcp_1"
}
});
const payload = JSON.parse(toolText(proposed)) as { changeSet: string; status: string };
expect(payload.status).toBe("proposed");
// Enabling writes buys proposals, not applies: the actor is an agent.
const applied = await client.callTool({
name: "ontology_apply_changeset",
arguments: { changeSet: payload.changeSet }
});
expect(isError(applied)).toBe(true);
expect(toolText(applied)).toMatch(/never apply directly/);
} finally {
delete process.env.OPENONTOLOGY_MCP_WRITABLE;
}
});
it("exports Turtle and SHACL", async () => {
const client = await connect();
const turtle = await client.callTool({ name: "ontology_export", arguments: { format: "turtle" } });
expect(toolText(turtle)).toContain("@prefix oo:");
const shacl = await client.callTool({ name: "ontology_export", arguments: { format: "shacl" } });
expect(toolText(shacl)).toContain("sh:NodeShape");
});
it("registers the ontology prompts", async () => {
const client = await connect();
const names = (await client.listPrompts()).prompts.map((prompt) => prompt.name);
expect(names).toEqual(
expect.arrayContaining([
"design_ontology",
"map_sources_to_claims",
"resolve_entities",
"review_ontology_changeset",
"explain_ontology_answer"
])
);
});
});
describe("MCP: OpenPRD", () => {
it("exposes the spec and the generated index", async () => {
const client = await connect();
const uris = (await client.listResources()).resources.map((resource) => resource.uri);
expect(uris).toContain("logicsrc://openprd/spec");
expect(uris).toContain("prd://index");
const index = await client.readResource({ uri: "prd://index" });
expect(resourceText(index.contents)).toContain("| ID | Title | Status | Tags |");
});
it("lists this repo's PRDs", async () => {
const client = await connect();
const result = await client.callTool({ name: "prd_list", arguments: {} });
const rows = JSON.parse(toolText(result)) as Array<{ id: string; title: string; requirements: number }>;
expect(rows[0]!.id).toBe("0001");
expect(rows[0]!.requirements).toBe(210);
});
it("validates the collection", async () => {
const client = await connect();
const result = await client.callTool({ name: "prd_validate", arguments: {} });
expect(toolText(result)).toContain("validation passed");
});
it("reports the next free id and the allowed lifecycle moves", async () => {
const client = await connect();
expect(toolText(await client.callTool({ name: "prd_next_id", arguments: {} }))).toBe("0002");
const moves = await client.callTool({ name: "prd_next_statuses", arguments: { ref: "0001" } });
const payload = JSON.parse(toolText(moves)) as { status: string; allowedNext: string[] };
expect(payload.status).toBe("Draft");
expect(payload.allowedNext).toEqual(["Review", "Withdrawn"]);
});
it("maps requirements to validated tasks", async () => {
const client = await connect();
const result = await client.callTool({ name: "prd_tasks", arguments: { ref: "0001", priority: "P0" } });
const payload = JSON.parse(toolText(result)) as { tasks: Array<{ type: string }> };
expect(payload.tasks.length).toBeGreaterThan(100);
expect(payload.tasks[0]!.type).toBe("logicsrc.task");
});
it("registers the PRD prompts", async () => {
const client = await connect();
const names = (await client.listPrompts()).prompts.map((prompt) => prompt.name);
expect(names).toEqual(expect.arrayContaining(["write_prd", "review_prd"]));
});
});

View file

@ -15,14 +15,27 @@
"directory": "packages/openontology"
},
"homepage": "https://logicsrc.com/openontology",
"keywords": ["logicsrc", "openontology", "ontology", "knowledge-graph", "provenance", "agents", "json-schema"],
"publishConfig": { "access": "public" },
"files": ["dist"],
"keywords": [
"logicsrc",
"openontology",
"ontology",
"knowledge-graph",
"provenance",
"agents",
"json-schema"
],
"publishConfig": {
"access": "public"
},
"files": [
"dist"
],
"scripts": {
"build": "tsc -p tsconfig.json",
"test": "vitest run src"
},
"dependencies": {
"@libsql/client": "^0.17.4",
"@logicsrc/validators": "file:../validators",
"yaml": "^2.8.1"
},

View file

@ -0,0 +1,272 @@
import { describe, expect, it } from "vitest";
import {
csvAdapter,
githubAdapter,
httpApiAdapter,
jsonAdapter,
listAdapters,
markdownAdapter,
ndjsonAdapter,
parseCsv,
yamlAdapter,
type FetchLike,
type IngestContext
} from "./adapters.js";
import { createOntologyEngine } from "./engine.js";
import { loadPrdFixturePackage } from "./test-helpers.js";
import { proposerActor } from "./policy.js";
const ctx: IngestContext = {
prefix: "test",
actor: "agent:importer",
runId: "run_import_1",
now: "2026-07-26T00:00:00Z",
confidence: 0.6,
license: "CC-BY-4.0"
};
const MAPPING = {
entityType: "Person",
idField: "handle",
nameField: "name",
idSegment: "person",
aliasField: "aliases",
externalIds: { github: "github" },
properties: { role: "role" },
relationships: { worksOn: { field: "projects", targetSegment: "project" } }
};
describe("adapter capabilities", () => {
it("declares what every adapter can and cannot do (R118)", () => {
const adapters = listAdapters();
expect(adapters.map((a) => a.id).sort()).toEqual([
"csv",
"github",
"http-api",
"json",
"markdown",
"ndjson",
"yaml"
]);
for (const adapter of adapters) {
expect(adapter.capabilities).toHaveProperty("publicData");
expect(adapter.capabilities).toHaveProperty("deletions");
}
// None of the shipped adapters can see upstream deletions — say so.
expect(adapters.every((a) => a.capabilities.deletions === false)).toBe(true);
});
});
describe("CSV", () => {
const csv = `handle,name,role,github,projects
alice,Alice Reyes,Protocol engineer,areyes,"zk-prover,ledger-indexer"
bob,Bob Nakamura,Indexer lead,bnak,ledger-indexer
`;
it("parses quoted fields and embedded separators", () => {
const rows = parseCsv(csv);
expect(rows).toHaveLength(2);
expect(rows[0]!.projects).toBe("zk-prover,ledger-indexer");
});
it("handles escaped quotes", () => {
const rows = parseCsv('a,b\n"say ""hi""",2\n');
expect(rows[0]!.a).toBe('say "hi"');
});
it("maps rows to entities and claims", () => {
const result = csvAdapter.ingest({ uri: "https://example.org/people.csv", content: csv, mapping: MAPPING }, ctx);
expect(result.entities.map((e) => e.id)).toEqual(["test:person:alice", "test:person:bob"]);
expect(result.entities[0]!.externalIds).toEqual({ github: "areyes" });
const worksOn = result.claims.filter((c) => c.predicate === "worksOn");
expect(worksOn).toHaveLength(3);
expect(worksOn[0]!.object).toEqual({ entity: "test:project:zk-prover" });
});
it("proposes rather than asserts, and records the run (R113/R114)", () => {
const result = csvAdapter.ingest({ uri: "https://example.org/people.csv", content: csv, mapping: MAPPING }, ctx);
expect(result.claims.every((c) => c.status === "proposed")).toBe(true);
expect(result.claims.every((c) => c.runId === "run_import_1")).toBe(true);
expect(result.claims.every((c) => c.confidence === 0.6)).toBe(true);
});
it("attaches source and evidence with a line selector", () => {
const result = csvAdapter.ingest({ uri: "https://example.org/people.csv", content: csv, mapping: MAPPING }, ctx);
expect(result.sources[0]!.contentHash).toMatch(/^sha256:/);
expect(result.sources[0]!.license).toBe("CC-BY-4.0");
expect(result.evidence[0]!.selector).toEqual({ type: "line-range", start: 2, end: 2 });
expect(result.claims[0]!.sources).toEqual([result.sources[0]!.id]);
});
it("skips a row with no id and says so", () => {
const result = csvAdapter.ingest(
{ uri: "x.csv", content: "handle,name\n,Nobody\nalice,Alice\n", mapping: MAPPING },
ctx
);
expect(result.entities).toHaveLength(1);
expect(result.warnings[0]).toMatch(/no handle/);
});
});
describe("JSON, YAML, NDJSON", () => {
const records = [{ handle: "alice", name: "Alice Reyes" }];
it("reads a JSON array", () => {
const result = jsonAdapter.ingest(
{ uri: "x.json", content: JSON.stringify(records), mapping: MAPPING },
ctx
);
expect(result.entities[0]!.canonicalName).toBe("Alice Reyes");
});
it("finds the array inside a wrapper object", () => {
const result = jsonAdapter.ingest(
{ uri: "x.json", content: JSON.stringify({ data: records }), mapping: MAPPING },
ctx
);
expect(result.entities).toHaveLength(1);
});
it("reads a YAML sequence", () => {
const result = yamlAdapter.ingest(
{ uri: "x.yaml", content: "- handle: alice\n name: Alice Reyes\n", mapping: MAPPING },
ctx
);
expect(result.entities[0]!.id).toBe("test:person:alice");
});
it("reports a bad NDJSON line instead of aborting the file", () => {
const result = ndjsonAdapter.ingest(
{ uri: "x.ndjson", content: `${JSON.stringify(records[0])}\nnot json\n`, mapping: MAPPING },
ctx
);
expect(result.entities).toHaveLength(1);
expect(result.warnings[0]).toMatch(/line 2 is not valid JSON/);
});
});
describe("Markdown", () => {
const md = `# Title
## ZK Prover
See [the repo](https://example.org/zk) and [docs](https://example.org/docs).
## Ledger Indexer
No links here.
`;
it("turns headings into entities and links into claims", () => {
const result = markdownAdapter.ingest({ uri: "x.md", content: md, entityType: "Project" }, ctx);
expect(result.entities.map((e) => e.canonicalName)).toEqual(["ZK Prover", "Ledger Indexer"]);
expect(result.claims).toHaveLength(2);
expect(result.claims[0]!.object).toEqual({ value: "https://example.org/zk" });
});
it("warns when the document has no headings at the requested level", () => {
const result = markdownAdapter.ingest({ uri: "x.md", content: "just prose\n", entityType: "Project" }, ctx);
expect(result.warnings[0]).toMatch(/no level-2 headings/);
});
});
describe("HTTP and GitHub", () => {
const fetchOk = (bodies: Record<string, unknown>): FetchLike =>
async (url) => {
const key = Object.keys(bodies).find((k) => url.includes(k));
if (!key) return { ok: false, status: 404, text: async () => "{}" };
return { ok: true, status: 200, text: async () => JSON.stringify(bodies[key]) };
};
it("reads a JSON endpoint through an injected fetch", async () => {
const result = await httpApiAdapter.ingest(
{
url: "https://example.org/api/people",
mapping: MAPPING,
path: "items",
fetch: fetchOk({ "/api/people": { items: [{ handle: "alice", name: "Alice Reyes" }] } })
},
ctx
);
expect(result.entities[0]!.id).toBe("test:person:alice");
expect(result.evidence[0]!.selector).toMatchObject({ type: "api-field" });
});
it("throws on a non-OK response rather than proposing nothing silently", async () => {
const fetchFail: FetchLike = async () => ({ ok: false, status: 503, text: async () => "" });
await expect(
httpApiAdapter.ingest({ url: "https://example.org/x", mapping: MAPPING, fetch: fetchFail }, ctx)
).rejects.toThrow(/HTTP 503/);
});
it("maps a GitHub repo and its contributors", async () => {
const result = await githubAdapter.ingest(
{
repo: "example/zk-prover",
fetch: fetchOk({
"/repos/example/zk-prover/contributors": [{ login: "areyes", contributions: 42 }],
"/repos/example/zk-prover": {
full_name: "example/zk-prover",
name: "zk-prover",
language: "Rust",
license: { spdx_id: "Apache-2.0" },
html_url: "https://example.org/zk-prover"
}
})
},
ctx
);
expect(result.entities.map((e) => e.type)).toEqual(["Codebase", "Person"]);
expect(result.sources[0]!.license).toBe("Apache-2.0");
expect(result.claims.find((c) => c.predicate === "language")?.object).toEqual({ value: "Rust" });
expect(result.claims.find((c) => c.predicate === "contributesTo")?.object).toEqual({
entity: "test:code:zk-prover"
});
});
it("warns when a repository declares no licence", async () => {
const result = await githubAdapter.ingest(
{
repo: "example/unlicensed",
fetch: fetchOk({
"/repos/example/unlicensed/contributors": [],
"/repos/example/unlicensed": { name: "unlicensed", full_name: "example/unlicensed" }
})
},
ctx
);
expect(result.warnings.some((w) => /no SPDX licence/.test(w))).toBe(true);
expect(result.sources[0]!.license).toBe("CC-BY-4.0");
});
});
describe("ingestion feeds the governed path", () => {
it("produces operations a proposer agent can turn into a change set", () => {
const engine = createOntologyEngine({
package: loadPrdFixturePackage(),
actor: proposerActor("agent:importer"),
clock: () => ctx.now
});
const result = csvAdapter.ingest(
{
uri: "https://example.org/people.csv",
content: "handle,name\ndave,Dave Okonkwo\n",
mapping: { entityType: "Person", idField: "handle", nameField: "name", idSegment: "person" }
},
ctx
);
const changeSet = engine.createOntologyChangeSet({
title: "Import people.csv",
operations: result.operations,
runId: ctx.runId
});
expect(changeSet.status).toBe("proposed");
// An imported entity does not exist until a human applies the change set.
expect(() => engine.getEntity("test:person:dave")).toThrow(/Unknown entity/);
});
});

View file

@ -0,0 +1,752 @@
import { parse as parseYaml } from "yaml";
import { digest } from "./canonical.js";
import { OPENONTOLOGY_VERSION } from "./types.js";
import type { ChangeOperation, Claim, Entity, Evidence, EvidenceSelector, Source } from "./types.js";
/**
* Source adapters turn foreign data into **proposals**.
*
* Nothing here writes to a store. Every adapter returns entities, claims,
* sources, evidence, and the change-set operations that would introduce them —
* a human or a policy decides whether they land (R113).
*
* Each adapter declares what it can and cannot do (R118), so a caller knows
* whether "no deletions" means "nothing was deleted" or "this adapter cannot
* see deletions."
*/
export interface AdapterCapabilities {
/** Can read publicly available data. */
publicData: boolean;
/** Can read private data given credentials. */
privateData: boolean;
/** Can fetch only what changed since a marker. */
incremental: boolean;
/** Can detect that a record disappeared upstream. */
deletions: boolean;
/** Reports the licence of what it ingested. */
license: boolean;
}
export interface IngestResult {
adapter: string;
sources: Source[];
entities: Entity[];
claims: Claim[];
evidence: Evidence[];
/** Ready for `createOntologyChangeSet({ operations })`. */
operations: ChangeOperation[];
warnings: string[];
capabilities: AdapterCapabilities;
}
export interface IngestContext {
/** Compact id prefix for generated ids. */
prefix: string;
/** Actor recorded on generated claims. */
actor: string;
/** Required when the actor is an agent. */
runId?: string;
now: string;
/** Confidence stamped on generated claims. */
confidence?: number;
license?: string;
}
/** How a flat record becomes an entity plus its claims. */
export interface RecordMapping {
entityType: string;
/** Field holding the stable local id. */
idField: string;
/** Field holding the display name. Defaults to `idField`. */
nameField?: string;
/** Segment used in generated ids: `<prefix>:<idSegment>:<value>`. */
idSegment?: string;
aliasField?: string;
/** External id namespace → field. */
externalIds?: Record<string, string>;
/** Property predicate → field. */
properties?: Record<string, string>;
/** Relationship predicate → field holding the target's local id. */
relationships?: Record<string, { field: string; targetSegment: string; separator?: string }>;
}
export interface SourceAdapter<Input> {
id: string;
description: string;
capabilities: AdapterCapabilities;
ingest(input: Input, ctx: IngestContext): Promise<IngestResult> | IngestResult;
}
const READ_ONLY_PUBLIC: AdapterCapabilities = {
publicData: true,
privateData: false,
incremental: false,
deletions: false,
license: true
};
/* ── shared record → proposal machinery ─────────────────────────────────── */
function slug(value: string): string {
return String(value)
.toLowerCase()
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-+|-+$/g, "")
.slice(0, 64);
}
interface BuildOptions {
records: Array<Record<string, unknown>>;
mapping: RecordMapping;
source: Source;
ctx: IngestContext;
adapter: string;
selectorFor?: (index: number) => EvidenceSelector;
}
function buildProposal(options: BuildOptions): IngestResult {
const { records, mapping, source, ctx, adapter } = options;
const entities: Entity[] = [];
const claims: Claim[] = [];
const evidence: Evidence[] = [];
const warnings: string[] = [];
const segment = mapping.idSegment ?? slug(mapping.entityType);
let claimSeq = 0;
let evidenceSeq = 0;
const nextClaimId = () => `${ctx.prefix}:claim:${adapter}-${String(++claimSeq).padStart(4, "0")}`;
records.forEach((record, index) => {
const rawId = record[mapping.idField];
if (rawId === undefined || rawId === null || String(rawId).trim() === "") {
warnings.push(`record ${index} has no ${mapping.idField}; skipped`);
return;
}
const entityId = `${ctx.prefix}:${segment}:${slug(String(rawId))}`;
const name = String(record[mapping.nameField ?? mapping.idField] ?? rawId);
const selector = options.selectorFor?.(index) ?? { type: "json-pointer", pointer: `/${index}` };
const evidenceId = `${ctx.prefix}:evidence:${adapter}-${String(++evidenceSeq).padStart(4, "0")}`;
evidence.push({
openontology: OPENONTOLOGY_VERSION,
kind: "Evidence",
id: evidenceId,
source: source.id,
selector
});
const entity: Entity = {
openontology: OPENONTOLOGY_VERSION,
kind: "Entity",
id: entityId,
type: mapping.entityType,
canonicalName: name,
createdAt: ctx.now,
createdBy: ctx.actor
};
if (mapping.aliasField && record[mapping.aliasField]) {
const raw = record[mapping.aliasField];
entity.aliases = Array.isArray(raw)
? raw.map(String)
: String(raw)
.split(",")
.map((alias) => alias.trim())
.filter(Boolean);
}
if (mapping.externalIds) {
const externalIds: Record<string, string> = {};
for (const [namespace, field] of Object.entries(mapping.externalIds)) {
const value = record[field];
if (value !== undefined && value !== null && String(value) !== "") {
externalIds[namespace] = String(value);
}
}
if (Object.keys(externalIds).length > 0) entity.externalIds = externalIds;
}
entities.push(entity);
const base = {
openontology: OPENONTOLOGY_VERSION,
kind: "Claim" as const,
status: "proposed" as const,
assertedAt: ctx.now,
assertedBy: ctx.actor,
sources: [source.id],
evidence: [evidenceId],
...(ctx.runId ? { runId: ctx.runId } : {}),
...(ctx.confidence !== undefined ? { confidence: ctx.confidence } : {})
};
for (const [predicate, field] of Object.entries(mapping.properties ?? {})) {
const value = record[field];
if (value === undefined || value === null || value === "") continue;
claims.push({ ...base, id: nextClaimId(), subject: entityId, predicate, object: { value } });
}
for (const [predicate, config] of Object.entries(mapping.relationships ?? {})) {
const raw = record[config.field];
if (raw === undefined || raw === null || String(raw) === "") continue;
const targets = Array.isArray(raw)
? raw.map(String)
: String(raw)
.split(config.separator ?? ",")
.map((value) => value.trim())
.filter(Boolean);
for (const target of targets) {
claims.push({
...base,
id: nextClaimId(),
subject: entityId,
predicate,
object: { entity: `${ctx.prefix}:${config.targetSegment}:${slug(target)}` }
});
}
}
});
const operations: ChangeOperation[] = [
...entities.map((entity) => ({ op: "add-entity" as const, value: entity as unknown as Record<string, unknown> })),
...claims.map((claim) => ({ op: "assert-claim" as const, value: claim as unknown as Record<string, unknown> }))
];
return {
adapter,
sources: [source],
entities,
claims,
evidence,
operations,
warnings,
capabilities: READ_ONLY_PUBLIC
};
}
function makeSource(
id: string,
sourceType: string,
uri: string,
ctx: IngestContext,
content: string,
extra: Partial<Source> = {}
): Source {
return {
openontology: OPENONTOLOGY_VERSION,
kind: "Source",
id,
sourceType,
uri,
retrievedAt: ctx.now,
contentHash: digest(content),
license: ctx.license ?? "unknown",
...extra
};
}
/* ── file adapters ──────────────────────────────────────────────────────── */
export interface FileInput {
/** Where the content came from, recorded on the Source. */
uri: string;
content: string;
mapping: RecordMapping;
}
export const csvAdapter: SourceAdapter<FileInput> = {
id: "csv",
description: "Rows of a CSV file become entities and claims.",
capabilities: READ_ONLY_PUBLIC,
ingest(input, ctx) {
const rows = parseCsv(input.content);
return buildProposal({
adapter: "csv",
records: rows,
mapping: input.mapping,
ctx,
source: makeSource(`${ctx.prefix}:source:csv-${digest(input.uri).slice(7, 15)}`, "csv", input.uri, ctx, input.content, {
mediaType: "text/csv"
}),
// Row 1 is the header, so record 0 lives on line 2.
selectorFor: (index) => ({ type: "line-range", start: index + 2, end: index + 2 })
});
}
};
export const jsonAdapter: SourceAdapter<FileInput> = {
id: "json",
description: "A JSON array (or an object with an array field) becomes entities and claims.",
capabilities: READ_ONLY_PUBLIC,
ingest(input, ctx) {
const parsed = JSON.parse(input.content) as unknown;
const records = toRecords(parsed);
return buildProposal({
adapter: "json",
records,
mapping: input.mapping,
ctx,
source: makeSource(
`${ctx.prefix}:source:json-${digest(input.uri).slice(7, 15)}`,
"json",
input.uri,
ctx,
input.content,
{ mediaType: "application/json" }
)
});
}
};
export const yamlAdapter: SourceAdapter<FileInput> = {
id: "yaml",
description: "A YAML sequence becomes entities and claims.",
capabilities: READ_ONLY_PUBLIC,
ingest(input, ctx) {
const records = toRecords(parseYaml(input.content) as unknown);
return buildProposal({
adapter: "yaml",
records,
mapping: input.mapping,
ctx,
source: makeSource(
`${ctx.prefix}:source:yaml-${digest(input.uri).slice(7, 15)}`,
"yaml",
input.uri,
ctx,
input.content,
{ mediaType: "application/yaml" }
)
});
}
};
export const ndjsonAdapter: SourceAdapter<FileInput> = {
id: "ndjson",
description: "Newline-delimited JSON records become entities and claims.",
capabilities: READ_ONLY_PUBLIC,
ingest(input, ctx) {
const records: Array<Record<string, unknown>> = [];
input.content.split("\n").forEach((line, index) => {
const trimmed = line.trim();
if (!trimmed) return;
try {
records.push(JSON.parse(trimmed) as Record<string, unknown>);
} catch {
// Reported below rather than aborting the whole file.
records.push({ __parseError: index + 1 });
}
});
const bad = records.filter((record) => "__parseError" in record);
const clean = records.filter((record) => !("__parseError" in record));
const result = buildProposal({
adapter: "ndjson",
records: clean,
mapping: input.mapping,
ctx,
source: makeSource(
`${ctx.prefix}:source:ndjson-${digest(input.uri).slice(7, 15)}`,
"ndjson",
input.uri,
ctx,
input.content,
{ mediaType: "application/x-ndjson" }
),
selectorFor: (index) => ({ type: "line-range", start: index + 1, end: index + 1 })
});
for (const record of bad) {
result.warnings.push(`line ${String(record.__parseError)} is not valid JSON; skipped`);
}
return result;
}
};
export interface MarkdownInput {
uri: string;
content: string;
entityType: string;
idSegment?: string;
/** Heading level that starts a new entity. Defaults to 2 (`##`). */
headingLevel?: number;
}
export const markdownAdapter: SourceAdapter<MarkdownInput> = {
id: "markdown",
description: "Each heading in a Markdown document becomes an entity; its links become claims.",
capabilities: READ_ONLY_PUBLIC,
ingest(input, ctx) {
const level = input.headingLevel ?? 2;
const marker = "#".repeat(level);
const source = makeSource(
`${ctx.prefix}:source:markdown-${digest(input.uri).slice(7, 15)}`,
"markdown",
input.uri,
ctx,
input.content,
{ mediaType: "text/markdown" }
);
const entities: Entity[] = [];
const claims: Claim[] = [];
const evidence: Evidence[] = [];
const segment = input.idSegment ?? slug(input.entityType);
let current: { id: string; line: number } | null = null;
let seq = 0;
input.content.split("\n").forEach((line, index) => {
const heading = new RegExp(`^${marker}\\s+(.+?)\\s*$`).exec(line);
if (heading && !line.startsWith(`${marker}#`)) {
const name = heading[1] as string;
const id = `${ctx.prefix}:${segment}:${slug(name)}`;
const evidenceId = `${ctx.prefix}:evidence:markdown-${String(++seq).padStart(4, "0")}`;
evidence.push({
openontology: OPENONTOLOGY_VERSION,
kind: "Evidence",
id: evidenceId,
source: source.id,
selector: { type: "line-range", start: index + 1, end: index + 1 }
});
entities.push({
openontology: OPENONTOLOGY_VERSION,
kind: "Entity",
id,
type: input.entityType,
canonicalName: name,
createdAt: ctx.now,
createdBy: ctx.actor
});
current = { id, line: index + 1 };
return;
}
if (!current) return;
for (const match of line.matchAll(/\[([^\]]+)\]\(([^)]+)\)/g)) {
const evidenceId = `${ctx.prefix}:evidence:markdown-${String(++seq).padStart(4, "0")}`;
evidence.push({
openontology: OPENONTOLOGY_VERSION,
kind: "Evidence",
id: evidenceId,
source: source.id,
selector: { type: "line-range", start: index + 1, end: index + 1 }
});
claims.push({
openontology: OPENONTOLOGY_VERSION,
kind: "Claim",
id: `${ctx.prefix}:claim:markdown-${String(seq).padStart(4, "0")}`,
subject: current.id,
predicate: "references",
object: { value: match[2] as string },
status: "proposed",
assertedAt: ctx.now,
assertedBy: ctx.actor,
sources: [source.id],
evidence: [evidenceId],
...(ctx.runId ? { runId: ctx.runId } : {}),
...(ctx.confidence !== undefined ? { confidence: ctx.confidence } : {})
});
}
});
return {
adapter: "markdown",
sources: [source],
entities,
claims,
evidence,
operations: [
...entities.map((entity) => ({ op: "add-entity" as const, value: entity as unknown as Record<string, unknown> })),
...claims.map((claim) => ({ op: "assert-claim" as const, value: claim as unknown as Record<string, unknown> }))
],
warnings: entities.length === 0 ? [`no level-${level} headings found in ${input.uri}`] : [],
capabilities: READ_ONLY_PUBLIC
};
}
};
/* ── HTTP adapters ──────────────────────────────────────────────────────── */
export type FetchLike = (url: string, init?: { headers?: Record<string, string> }) => Promise<{
ok: boolean;
status: number;
text: () => Promise<string>;
}>;
export interface HttpInput {
url: string;
mapping: RecordMapping;
headers?: Record<string, string>;
/** JSON pointer-ish path to the array in the response, e.g. "data.items". */
path?: string;
fetch: FetchLike;
}
export const httpApiAdapter: SourceAdapter<HttpInput> = {
id: "http-api",
description: "A JSON HTTP endpoint becomes entities and claims.",
capabilities: { publicData: true, privateData: true, incremental: false, deletions: false, license: false },
async ingest(input, ctx) {
const response = await input.fetch(input.url, { headers: input.headers });
if (!response.ok) {
throw new Error(`${input.url} returned HTTP ${response.status}`);
}
const body = await response.text();
const parsed = JSON.parse(body) as unknown;
const target = input.path
? input.path.split(".").reduce<unknown>((value, key) => (value as Record<string, unknown>)?.[key], parsed)
: parsed;
const result = buildProposal({
adapter: "http-api",
records: toRecords(target),
mapping: input.mapping,
ctx,
source: makeSource(
`${ctx.prefix}:source:http-${digest(input.url).slice(7, 15)}`,
"api-response",
input.url,
ctx,
body,
{ mediaType: "application/json" }
),
selectorFor: (index) => ({ type: "api-field", field: `${input.path ?? "$"}[${index}]`, endpoint: input.url })
});
result.capabilities = httpApiAdapter.capabilities;
if (!ctx.license) {
result.warnings.push("no licence declared for this endpoint; source licence recorded as unknown");
}
return result;
}
};
export interface GithubInput {
/** `owner/name`. */
repo: string;
fetch: FetchLike;
token?: string;
apiBase?: string;
}
/**
* GitHub repository → a codebase entity plus its contributors.
*
* Fetch is injected, so tests (and offline runs) never touch the network.
*/
export const githubAdapter: SourceAdapter<GithubInput> = {
id: "github",
description: "A GitHub repository and its contributors become a codebase and people.",
capabilities: { publicData: true, privateData: true, incremental: false, deletions: false, license: true },
async ingest(input, ctx) {
const base = input.apiBase ?? "https://api.github.com";
const headers = {
accept: "application/vnd.github+json",
...(input.token ? { authorization: `Bearer ${input.token}` } : {})
};
const repoResponse = await input.fetch(`${base}/repos/${input.repo}`, { headers });
if (!repoResponse.ok) throw new Error(`GitHub returned HTTP ${repoResponse.status} for ${input.repo}`);
const repoBody = await repoResponse.text();
const repo = JSON.parse(repoBody) as {
full_name?: string;
name?: string;
language?: string;
license?: { spdx_id?: string };
html_url?: string;
};
const contributorsResponse = await input.fetch(`${base}/repos/${input.repo}/contributors`, { headers });
const contributorsBody = contributorsResponse.ok ? await contributorsResponse.text() : "[]";
const contributors = JSON.parse(contributorsBody) as Array<{ login?: string; contributions?: number }>;
const source = makeSource(
`${ctx.prefix}:source:github-${slug(input.repo)}`,
"api-response",
repo.html_url ?? `${base}/repos/${input.repo}`,
ctx,
repoBody,
{ mediaType: "application/json", license: repo.license?.spdx_id ?? ctx.license ?? "unknown", publisher: "github" }
);
const codebaseId = `${ctx.prefix}:code:${slug(repo.name ?? input.repo)}`;
const entities: Entity[] = [
{
openontology: OPENONTOLOGY_VERSION,
kind: "Entity",
id: codebaseId,
type: "Codebase",
canonicalName: repo.name ?? input.repo,
externalIds: { github: repo.full_name ?? input.repo },
createdAt: ctx.now,
createdBy: ctx.actor
}
];
const claims: Claim[] = [];
let seq = 0;
const claimBase = {
openontology: OPENONTOLOGY_VERSION,
kind: "Claim" as const,
status: "proposed" as const,
assertedAt: ctx.now,
assertedBy: ctx.actor,
sources: [source.id],
...(ctx.runId ? { runId: ctx.runId } : {}),
...(ctx.confidence !== undefined ? { confidence: ctx.confidence } : {})
};
if (repo.language) {
claims.push({
...claimBase,
id: `${ctx.prefix}:claim:github-${String(++seq).padStart(4, "0")}`,
subject: codebaseId,
predicate: "language",
object: { value: repo.language }
});
}
if (repo.license?.spdx_id) {
claims.push({
...claimBase,
id: `${ctx.prefix}:claim:github-${String(++seq).padStart(4, "0")}`,
subject: codebaseId,
predicate: "license",
object: { value: repo.license.spdx_id }
});
}
for (const contributor of contributors) {
if (!contributor.login) continue;
const personId = `${ctx.prefix}:person:${slug(contributor.login)}`;
entities.push({
openontology: OPENONTOLOGY_VERSION,
kind: "Entity",
id: personId,
type: "Person",
canonicalName: contributor.login,
externalIds: { github: contributor.login },
createdAt: ctx.now,
createdBy: ctx.actor
});
claims.push({
...claimBase,
id: `${ctx.prefix}:claim:github-${String(++seq).padStart(4, "0")}`,
subject: personId,
predicate: "contributesTo",
object: { entity: codebaseId }
});
}
const warnings: string[] = [];
if (!contributorsResponse.ok) {
warnings.push(`contributors endpoint returned HTTP ${contributorsResponse.status}; only the codebase was mapped`);
}
if (!repo.license?.spdx_id) {
warnings.push("repository declares no SPDX licence; source licence recorded as unknown");
}
return {
adapter: "github",
sources: [source],
entities,
claims,
evidence: [],
operations: [
...entities.map((entity) => ({ op: "add-entity" as const, value: entity as unknown as Record<string, unknown> })),
...claims.map((claim) => ({ op: "assert-claim" as const, value: claim as unknown as Record<string, unknown> }))
],
warnings,
capabilities: githubAdapter.capabilities
};
}
};
export const ADAPTERS = {
csv: csvAdapter,
json: jsonAdapter,
yaml: yamlAdapter,
ndjson: ndjsonAdapter,
markdown: markdownAdapter,
"http-api": httpApiAdapter,
github: githubAdapter
} as const;
export type AdapterId = keyof typeof ADAPTERS;
export function listAdapters(): Array<{ id: string; description: string; capabilities: AdapterCapabilities }> {
return Object.values(ADAPTERS).map((adapter) => ({
id: adapter.id,
description: adapter.description,
capabilities: adapter.capabilities
}));
}
/* ── helpers ────────────────────────────────────────────────────────────── */
function toRecords(value: unknown): Array<Record<string, unknown>> {
if (Array.isArray(value)) return value as Array<Record<string, unknown>>;
if (value && typeof value === "object") {
const arrayField = Object.values(value as Record<string, unknown>).find((entry) => Array.isArray(entry));
if (arrayField) return arrayField as Array<Record<string, unknown>>;
return [value as Record<string, unknown>];
}
return [];
}
/** Minimal RFC-4180 CSV reader: quoted fields, escaped quotes, CRLF. */
export function parseCsv(text: string): Array<Record<string, string>> {
const rows: string[][] = [];
let row: string[] = [];
let field = "";
let quoted = false;
for (let i = 0; i < text.length; i += 1) {
const char = text[i] as string;
if (quoted) {
if (char === '"') {
if (text[i + 1] === '"') {
field += '"';
i += 1;
} else {
quoted = false;
}
} else {
field += char;
}
continue;
}
if (char === '"') {
quoted = true;
} else if (char === ",") {
row.push(field);
field = "";
} else if (char === "\n") {
row.push(field);
rows.push(row);
row = [];
field = "";
} else if (char !== "\r") {
field += char;
}
}
if (field.length > 0 || row.length > 0) {
row.push(field);
rows.push(row);
}
const [header, ...body] = rows.filter((entry) => entry.some((cell) => cell.trim() !== ""));
if (!header) return [];
return body.map((cells) =>
Object.fromEntries(header.map((name, index) => [name.trim(), (cells[index] ?? "").trim()]))
);
}

View file

@ -51,6 +51,15 @@ export {
type QueryLimits
} from "./query.js";
export {
createLibsqlStore,
migrate as migrateLibsql,
searchEntities,
MIGRATIONS,
type LibsqlStore,
type LibsqlStoreOptions
} from "./libsql.js";
export {
createMemoryStore,
type ClaimFilter,
@ -93,6 +102,30 @@ export {
type JsonLdExport
} from "./jsonld.js";
export {
ADAPTERS,
csvAdapter,
githubAdapter,
httpApiAdapter,
jsonAdapter,
listAdapters,
markdownAdapter,
ndjsonAdapter,
parseCsv,
yamlAdapter,
type AdapterCapabilities,
type AdapterId,
type FetchLike,
type IngestContext,
type IngestResult,
type RecordMapping,
type SourceAdapter
} from "./adapters.js";
export { exportTurtle, importTurtle, type TurtleExport } from "./rdf.js";
export { constraintsToShacl, type ShaclExport } from "./shacl.js";
export {
createEd25519Provider,
generateEd25519KeyPair,

View file

@ -0,0 +1,184 @@
import { createClient } from "@libsql/client";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterAll, describe, expect, it } from "vitest";
import { createOntologyEngine } from "./engine.js";
import { createLibsqlStore, migrate, searchEntities } from "./libsql.js";
import { loadPrdFixturePackage } from "./test-helpers.js";
import { localActor } from "./policy.js";
const dirs: string[] = [];
afterAll(() => {
for (const dir of dirs) rmSync(dir, { recursive: true, force: true });
});
function dbUrl(): string {
const dir = mkdtempSync(join(tmpdir(), "openontology-libsql-"));
dirs.push(dir);
return `file:${join(dir, "ontology.db")}`;
}
const NOW = "2026-07-26T00:00:00Z";
describe("libSQL adapter", () => {
it("applies migrations once and is idempotent", async () => {
const client = createClient({ url: dbUrl() });
expect(await migrate(client)).toBeGreaterThan(0);
expect(await migrate(client)).toBe(0);
const tables = await client.execute(
"SELECT name FROM sqlite_master WHERE type IN ('table','index') ORDER BY name"
);
const names = tables.rows.map((row) => String(row.name));
expect(names).toEqual(expect.arrayContaining(["claims", "entities", "status_log", "ontology_events"]));
expect(names.filter((n) => n.startsWith("idx_claims")).length).toBeGreaterThanOrEqual(5);
client.close();
});
it("seeds a package and hydrates it back identically", async () => {
const pkg = loadPrdFixturePackage();
const url = dbUrl();
const store = await createLibsqlStore({ client: createClient({ url }), seed: pkg });
expect(store.listEntities()).toHaveLength(pkg.data.entities.length);
expect(store.listClaims({ status: ["asserted"] }).length).toBeGreaterThan(0);
store.close();
// Re-open against the same file: no seed, everything comes from SQL.
const reopened = await createLibsqlStore({
client: createClient({ url }),
ontology: pkg.manifest.id
});
expect(reopened.listEntities().map((e) => e.id).sort()).toEqual(
pkg.data.entities.map((e) => e.id).sort()
);
expect(reopened.getManifest().id).toBe(pkg.manifest.id);
reopened.close();
});
it("persists an applied change set across a reopen", async () => {
const pkg = loadPrdFixturePackage();
const url = dbUrl();
const store = await createLibsqlStore({ client: createClient({ url }), seed: pkg });
let n = 0;
const engine = createOntologyEngine({
store,
actor: localActor("curator@example.org"),
clock: () => NOW,
idFactory: (kind) => `${kind}:${String(++n).padStart(4, "0")}`
});
const changeSet = engine.createOntologyChangeSet({
title: "persisted",
operations: [
{
op: "assert-claim",
value: {
subject: "test:person:alice",
predicate: "worksOn",
object: { entity: "test:project:ledger-indexer" },
sources: ["test:source:repo"]
}
}
]
});
engine.approveOntologyChangeSet(changeSet.id);
const applied = engine.applyOntologyChangeSet(changeSet.id);
expect(store.pending()).toBeGreaterThan(0);
const flushed = await store.flush();
expect(flushed.statements).toBeGreaterThan(0);
expect(store.pending()).toBe(0);
store.close();
const reopened = await createLibsqlStore({
client: createClient({ url }),
ontology: pkg.manifest.id
});
const reread = createOntologyEngine({ store: reopened, actor: localActor() });
const rows = reread.queryOntology({
match: [{ subject: "test:person:alice", predicate: "worksOn", object: "?p" }]
}).rows;
expect(rows).toHaveLength(2);
expect(reopened.getClaim(applied.addedClaims[0]!)).toBeDefined();
expect(reopened.listChangeSets()).toHaveLength(1);
expect(reopened.listEvents().length).toBeGreaterThan(0);
expect(reopened.revision()).toBe("data-000001");
reopened.close();
});
it("replays the append-only status log so retractions survive a reopen", async () => {
const pkg = loadPrdFixturePackage();
const url = dbUrl();
const store = await createLibsqlStore({ client: createClient({ url }), seed: pkg });
const engine = createOntologyEngine({ store, actor: localActor(), clock: () => NOW });
const target = engine.queryOntology({
match: [{ subject: "test:person:carol", predicate: "worksOn", object: "?p" }]
}).rows[0]!.claims[0]!;
const changeSet = engine.createOntologyChangeSet({
title: "retract",
operations: [{ op: "retract-claim", target, reason: "left the project" }]
});
engine.approveOntologyChangeSet(changeSet.id);
engine.applyOntologyChangeSet(changeSet.id);
await store.flush();
store.close();
const reopened = await createLibsqlStore({
client: createClient({ url }),
ontology: pkg.manifest.id
});
// The claim row is still there; its effective status came from the log.
expect(reopened.getClaim(target)?.status).toBe("retracted");
expect(reopened.claimHistory(target).map((h) => h.status)).toEqual(["asserted", "retracted"]);
reopened.close();
});
it("keeps merge redirects resolvable after a reopen", async () => {
const pkg = loadPrdFixturePackage();
const url = dbUrl();
const store = await createLibsqlStore({ client: createClient({ url }), seed: pkg });
const engine = createOntologyEngine({ store, actor: localActor(), clock: () => NOW });
const changeSet = engine.createOntologyChangeSet({
title: "merge",
operations: [{ op: "merge-entity", source: "test:person:carol", target: "test:person:bob" }]
});
engine.approveOntologyChangeSet(changeSet.id);
engine.applyOntologyChangeSet(changeSet.id);
await store.flush();
store.close();
const reopened = await createLibsqlStore({
client: createClient({ url }),
ontology: pkg.manifest.id
});
expect(reopened.getEntity("test:person:carol")?.id).toBe("test:person:bob");
reopened.close();
});
it("indexes entities for full-text search", async () => {
const pkg = loadPrdFixturePackage();
const url = dbUrl();
const client = createClient({ url });
const store = await createLibsqlStore({ client, seed: pkg });
const hits = await searchEntities(client, pkg.manifest.id, "Alice");
expect(hits.map((hit) => hit.id)).toContain("test:person:alice");
const none = await searchEntities(client, pkg.manifest.id, "nonexistentterm");
expect(none).toHaveLength(0);
store.close();
});
it("refuses to open an unknown ontology with no seed", async () => {
await expect(
createLibsqlStore({ client: createClient({ url: dbUrl() }), ontology: "not-there" })
).rejects.toThrow(/not in this database/);
});
});

View file

@ -0,0 +1,713 @@
import type { Client, InArgs } from "@libsql/client";
import { revisionId } from "./ids.js";
import { createMemoryStore, type OntologyStore } from "./store.js";
import type { LoadedPackage } from "./types.js";
/**
* SQLite / Turso storage adapter.
*
* The engine's store interface is synchronous by design — a query evaluator
* that awaits per triple pattern is unusable. So this adapter:
*
* 1. hydrates the whole package into the in-memory read model at open,
* 2. serves reads from it synchronously,
* 3. records every mutation as a pending SQL statement, and
* 4. writes them in one transaction when you `flush()`.
*
* Callers that mutate MUST await `flush()` for durability; the REST layer does
* so after every applied change set. Everything persisted is append-only, so a
* crash before flush loses the last change set rather than corrupting history.
*
* At the reference target (~100k claims) hydration is a handful of queries.
* Beyond that, an adapter that pushes evaluation into SQL is the right answer —
* which is exactly why the store is an interface.
*/
export const MIGRATIONS: Array<{ version: number; name: string; statements: string[] }> = [
{
version: 1,
name: "initial",
statements: [
`CREATE TABLE IF NOT EXISTS ontologies (
id TEXT PRIMARY KEY,
version TEXT NOT NULL,
manifest TEXT NOT NULL,
schema_json TEXT NOT NULL,
revision INTEGER NOT NULL DEFAULT 0,
updated_at TEXT NOT NULL
)`,
`CREATE TABLE IF NOT EXISTS entities (
ontology TEXT NOT NULL,
id TEXT NOT NULL,
type TEXT NOT NULL,
canonical_name TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'active',
superseded_by TEXT,
visibility TEXT NOT NULL DEFAULT 'public',
created_at TEXT NOT NULL,
created_by TEXT NOT NULL,
document TEXT NOT NULL,
PRIMARY KEY (ontology, id)
)`,
`CREATE TABLE IF NOT EXISTS aliases (
ontology TEXT NOT NULL,
entity_id TEXT NOT NULL,
alias TEXT NOT NULL,
PRIMARY KEY (ontology, entity_id, alias)
)`,
`CREATE TABLE IF NOT EXISTS external_ids (
ontology TEXT NOT NULL,
entity_id TEXT NOT NULL,
namespace TEXT NOT NULL,
value TEXT NOT NULL,
PRIMARY KEY (ontology, entity_id, namespace)
)`,
`CREATE TABLE IF NOT EXISTS claims (
ontology TEXT NOT NULL,
id TEXT NOT NULL,
subject TEXT NOT NULL,
predicate TEXT NOT NULL,
object_entity TEXT,
object_value TEXT,
status TEXT NOT NULL,
confidence REAL,
valid_from TEXT,
valid_to TEXT,
observed_at TEXT,
asserted_at TEXT NOT NULL,
asserted_by TEXT NOT NULL,
run_id TEXT,
change_set TEXT,
visibility TEXT NOT NULL DEFAULT 'public',
document TEXT NOT NULL,
PRIMARY KEY (ontology, id)
)`,
`CREATE TABLE IF NOT EXISTS claim_sources (
ontology TEXT NOT NULL,
claim_id TEXT NOT NULL,
source_id TEXT NOT NULL,
PRIMARY KEY (ontology, claim_id, source_id)
)`,
`CREATE TABLE IF NOT EXISTS sources (
ontology TEXT NOT NULL,
id TEXT NOT NULL,
source_type TEXT NOT NULL,
uri TEXT NOT NULL,
retrieved_at TEXT NOT NULL,
content_hash TEXT,
license TEXT,
visibility TEXT NOT NULL DEFAULT 'public',
stale INTEGER NOT NULL DEFAULT 0,
document TEXT NOT NULL,
PRIMARY KEY (ontology, id)
)`,
`CREATE TABLE IF NOT EXISTS evidence (
ontology TEXT NOT NULL,
id TEXT NOT NULL,
source_id TEXT NOT NULL,
document TEXT NOT NULL,
PRIMARY KEY (ontology, id)
)`,
// Append-only status log: claims and entities are never updated in place.
`CREATE TABLE IF NOT EXISTS status_log (
ontology TEXT NOT NULL,
kind TEXT NOT NULL,
object_id TEXT NOT NULL,
status TEXT NOT NULL,
at TEXT NOT NULL,
by TEXT NOT NULL,
change_set TEXT,
reason TEXT,
seq INTEGER PRIMARY KEY AUTOINCREMENT
)`,
`CREATE TABLE IF NOT EXISTS changesets (
ontology TEXT NOT NULL,
id TEXT NOT NULL,
title TEXT NOT NULL,
status TEXT NOT NULL,
created_at TEXT NOT NULL,
created_by TEXT NOT NULL,
base_revision TEXT,
result_revision TEXT,
document TEXT NOT NULL,
PRIMARY KEY (ontology, id)
)`,
`CREATE TABLE IF NOT EXISTS reviews (
ontology TEXT NOT NULL,
id TEXT NOT NULL,
change_set TEXT NOT NULL,
reviewer TEXT NOT NULL,
state TEXT NOT NULL,
created_at TEXT NOT NULL,
document TEXT NOT NULL,
PRIMARY KEY (ontology, id)
)`,
`CREATE TABLE IF NOT EXISTS approvals (
ontology TEXT NOT NULL,
id TEXT NOT NULL,
change_set TEXT NOT NULL,
approver TEXT NOT NULL,
created_at TEXT NOT NULL,
document TEXT NOT NULL,
PRIMARY KEY (ontology, id)
)`,
`CREATE TABLE IF NOT EXISTS ontology_events (
ontology TEXT NOT NULL,
id TEXT NOT NULL,
type TEXT NOT NULL,
at TEXT NOT NULL,
actor TEXT NOT NULL,
change_set TEXT,
subject TEXT,
revision TEXT,
document TEXT NOT NULL,
seq INTEGER PRIMARY KEY AUTOINCREMENT
)`,
// R185: the indexes the query evaluator and lookups actually need.
"CREATE INDEX IF NOT EXISTS idx_entities_type ON entities (ontology, type)",
"CREATE INDEX IF NOT EXISTS idx_entities_status ON entities (ontology, status)",
"CREATE INDEX IF NOT EXISTS idx_entities_name ON entities (ontology, canonical_name)",
"CREATE INDEX IF NOT EXISTS idx_aliases_alias ON aliases (ontology, alias)",
"CREATE INDEX IF NOT EXISTS idx_external_ids ON external_ids (ontology, namespace, value)",
"CREATE INDEX IF NOT EXISTS idx_claims_subject ON claims (ontology, subject)",
"CREATE INDEX IF NOT EXISTS idx_claims_predicate ON claims (ontology, predicate)",
"CREATE INDEX IF NOT EXISTS idx_claims_object ON claims (ontology, object_entity)",
"CREATE INDEX IF NOT EXISTS idx_claims_sp ON claims (ontology, subject, predicate)",
"CREATE INDEX IF NOT EXISTS idx_claims_status ON claims (ontology, status)",
"CREATE INDEX IF NOT EXISTS idx_claims_valid ON claims (ontology, valid_from, valid_to)",
"CREATE INDEX IF NOT EXISTS idx_claims_asserted ON claims (ontology, asserted_at)",
"CREATE INDEX IF NOT EXISTS idx_claim_sources ON claim_sources (ontology, source_id)",
"CREATE INDEX IF NOT EXISTS idx_status_log_object ON status_log (ontology, kind, object_id)",
"CREATE INDEX IF NOT EXISTS idx_events_type ON ontology_events (ontology, type)",
"CREATE INDEX IF NOT EXISTS idx_events_changeset ON ontology_events (ontology, change_set)"
]
},
{
version: 2,
name: "full-text-search",
statements: [
// R186: label, alias, and description search.
`CREATE VIRTUAL TABLE IF NOT EXISTS entity_fts USING fts5(
entity_id UNINDEXED,
ontology UNINDEXED,
canonical_name,
aliases,
description,
tokenize = 'unicode61'
)`
]
}
];
export interface LibsqlStoreOptions {
client: Client;
/** Ontology id. Defaults to the package manifest id. */
ontology?: string;
/** Seed the database from this package when it holds no rows for the id. */
seed?: LoadedPackage;
}
export interface LibsqlStore extends OntologyStore {
/** Persist everything buffered since the last flush, in one transaction. */
flush(): Promise<{ statements: number }>;
/** Pending statement count — 0 means everything is durable. */
pending(): number;
close(): void;
}
export async function migrate(client: Client): Promise<number> {
await client.execute(
"CREATE TABLE IF NOT EXISTS schema_migrations (version INTEGER PRIMARY KEY, name TEXT NOT NULL, applied_at TEXT NOT NULL)"
);
const applied = await client.execute("SELECT version FROM schema_migrations");
const have = new Set(applied.rows.map((row) => Number(row.version)));
let count = 0;
for (const migration of MIGRATIONS) {
if (have.has(migration.version)) continue;
for (const statement of migration.statements) {
await client.execute(statement);
}
await client.execute({
sql: "INSERT INTO schema_migrations (version, name, applied_at) VALUES (?, ?, ?)",
args: [migration.version, migration.name, new Date().toISOString()]
});
count += 1;
}
return count;
}
/** Open (and if needed seed) a libSQL-backed store. */
export async function createLibsqlStore(options: LibsqlStoreOptions): Promise<LibsqlStore> {
const { client, seed } = options;
await migrate(client);
const ontology = options.ontology ?? seed?.manifest.id;
if (!ontology) throw new Error("createLibsqlStore needs an ontology id or a seed package");
const existing = await client.execute({
sql: "SELECT manifest, schema_json, revision FROM ontologies WHERE id = ?",
args: [ontology]
});
if (existing.rows.length === 0) {
if (!seed) throw new Error(`Ontology ${ontology} is not in this database and no seed was given`);
await seedPackage(client, ontology, seed);
}
const hydrated = await hydrate(client, ontology);
const memory = createMemoryStore(hydrated.pkg);
// Replay the append-only status log so effective statuses match the database.
for (const transition of hydrated.transitions) {
if (transition.kind === "claim") {
try {
memory.setClaimStatus(transition.transition);
} catch {
// A transition for a claim that is no longer present is not fatal.
}
} else {
memory.setEntityStatus(transition.transition);
}
}
for (let i = 0; i < hydrated.revision; i += 1) memory.bumpRevision();
for (const changeSet of hydrated.changeSets) memory.putChangeSet(changeSet);
for (const review of hydrated.reviews) memory.putReview(review);
for (const approval of hydrated.approvals) memory.putApproval(approval);
for (const event of hydrated.events) memory.appendEvent(event);
const pendingStatements: Array<{ sql: string; args: InArgs }> = [];
const enqueue = (sql: string, args: InArgs) => pendingStatements.push({ sql, args });
const store: LibsqlStore = {
...memory,
addEntity(entity) {
memory.addEntity(entity);
enqueue(
`INSERT INTO entities (ontology, id, type, canonical_name, status, superseded_by, visibility, created_at, created_by, document)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
[
ontology,
entity.id,
entity.type,
entity.canonicalName,
entity.status ?? "active",
entity.supersededBy ?? null,
entity.visibility ?? "public",
entity.createdAt,
entity.createdBy,
JSON.stringify(entity)
]
);
for (const alias of entity.aliases ?? []) {
enqueue("INSERT OR IGNORE INTO aliases (ontology, entity_id, alias) VALUES (?, ?, ?)", [
ontology,
entity.id,
alias
]);
}
for (const [namespace, value] of Object.entries(entity.externalIds ?? {})) {
enqueue(
"INSERT OR REPLACE INTO external_ids (ontology, entity_id, namespace, value) VALUES (?, ?, ?, ?)",
[ontology, entity.id, namespace, value]
);
}
enqueue(
"INSERT INTO entity_fts (entity_id, ontology, canonical_name, aliases, description) VALUES (?, ?, ?, ?, ?)",
[entity.id, ontology, entity.canonicalName, (entity.aliases ?? []).join(" "), ""]
);
},
updateEntityMetadata(id, patch) {
const updated = memory.updateEntityMetadata(id, patch);
enqueue(
"UPDATE entities SET canonical_name = ?, status = ?, superseded_by = ?, document = ? WHERE ontology = ? AND id = ?",
[
updated.canonicalName,
updated.status ?? "active",
updated.supersededBy ?? null,
JSON.stringify(updated),
ontology,
updated.id
]
);
return updated;
},
appendClaim(claim) {
memory.appendClaim(claim);
const objectEntity = "entity" in claim.object ? claim.object.entity : null;
const objectValue = "entity" in claim.object ? null : JSON.stringify(claim.object.value);
enqueue(
`INSERT INTO claims (ontology, id, subject, predicate, object_entity, object_value, status, confidence,
valid_from, valid_to, observed_at, asserted_at, asserted_by, run_id, change_set, visibility, document)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
[
ontology,
claim.id,
claim.subject,
claim.predicate,
objectEntity,
objectValue,
claim.status,
claim.confidence ?? null,
claim.validTime?.from ?? null,
claim.validTime?.to ?? null,
claim.observedAt ?? null,
claim.assertedAt,
claim.assertedBy,
claim.runId ?? null,
claim.changeSet ?? null,
claim.visibility ?? "public",
JSON.stringify(claim)
]
);
for (const source of claim.sources ?? []) {
enqueue(
"INSERT OR IGNORE INTO claim_sources (ontology, claim_id, source_id) VALUES (?, ?, ?)",
[ontology, claim.id, source]
);
}
},
setClaimStatus(transition) {
memory.setClaimStatus(transition);
enqueue(
"INSERT INTO status_log (ontology, kind, object_id, status, at, by, change_set, reason) VALUES (?, 'claim', ?, ?, ?, ?, ?, ?)",
[
ontology,
transition.objectId,
String(transition.status),
transition.at,
transition.by,
transition.changeSet ?? null,
transition.reason ?? null
]
);
},
setEntityStatus(transition) {
memory.setEntityStatus(transition);
enqueue(
"INSERT INTO status_log (ontology, kind, object_id, status, at, by, change_set, reason) VALUES (?, 'entity', ?, ?, ?, ?, ?, ?)",
[
ontology,
transition.objectId,
String(transition.status),
transition.at,
transition.by,
transition.changeSet ?? null,
transition.reason ?? null
]
);
},
addSource(source) {
memory.addSource(source);
enqueue(
`INSERT OR REPLACE INTO sources (ontology, id, source_type, uri, retrieved_at, content_hash, license, visibility, stale, document)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
[
ontology,
source.id,
source.sourceType,
source.uri,
source.retrievedAt,
source.contentHash ?? null,
source.license ?? null,
source.visibility ?? "public",
source.stale ? 1 : 0,
JSON.stringify(source)
]
);
},
addEvidence(record) {
memory.addEvidence(record);
enqueue("INSERT OR REPLACE INTO evidence (ontology, id, source_id, document) VALUES (?, ?, ?, ?)", [
ontology,
record.id,
record.source,
JSON.stringify(record)
]);
},
putChangeSet(changeSet) {
memory.putChangeSet(changeSet);
enqueue(
`INSERT OR REPLACE INTO changesets (ontology, id, title, status, created_at, created_by, base_revision, result_revision, document)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
[
ontology,
changeSet.id,
changeSet.title,
changeSet.status,
changeSet.createdAt,
changeSet.createdBy,
changeSet.baseRevision ?? null,
changeSet.resultRevision ?? null,
JSON.stringify(changeSet)
]
);
},
putReview(review) {
memory.putReview(review);
enqueue(
`INSERT OR REPLACE INTO reviews (ontology, id, change_set, reviewer, state, created_at, document)
VALUES (?, ?, ?, ?, ?, ?, ?)`,
[ontology, review.id, review.changeSet, review.reviewer, review.state, review.createdAt, JSON.stringify(review)]
);
},
putApproval(approval) {
memory.putApproval(approval);
enqueue(
`INSERT OR REPLACE INTO approvals (ontology, id, change_set, approver, created_at, document)
VALUES (?, ?, ?, ?, ?, ?)`,
[ontology, approval.id, approval.changeSet, approval.approver, approval.createdAt, JSON.stringify(approval)]
);
},
appendEvent(event) {
memory.appendEvent(event);
enqueue(
`INSERT INTO ontology_events (ontology, id, type, at, actor, change_set, subject, revision, document)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
[
ontology,
event.id,
event.type,
event.at,
event.actor,
event.changeSet ?? null,
event.subject ?? null,
event.revision ?? null,
JSON.stringify(event)
]
);
},
bumpRevision() {
const revision = memory.bumpRevision();
enqueue("UPDATE ontologies SET revision = revision + 1, updated_at = ? WHERE id = ?", [
new Date().toISOString(),
ontology
]);
return revision;
},
pending: () => pendingStatements.length,
async flush() {
if (pendingStatements.length === 0) return { statements: 0 };
const batch = pendingStatements.splice(0, pendingStatements.length);
await client.batch(
batch.map((statement) => ({ sql: statement.sql, args: statement.args })),
"write"
);
return { statements: batch.length };
},
close() {
client.close();
}
};
return store;
}
async function seedPackage(client: Client, ontology: string, pkg: LoadedPackage): Promise<void> {
const statements: Array<{ sql: string; args: InArgs }> = [
{
sql: "INSERT INTO ontologies (id, version, manifest, schema_json, revision, updated_at) VALUES (?, ?, ?, ?, 0, ?)",
args: [
ontology,
pkg.manifest.version,
JSON.stringify(pkg.manifest),
JSON.stringify(pkg.schema),
new Date().toISOString()
]
}
];
for (const entity of pkg.data.entities) {
statements.push({
sql: `INSERT INTO entities (ontology, id, type, canonical_name, status, superseded_by, visibility, created_at, created_by, document)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
args: [
ontology,
entity.id,
entity.type,
entity.canonicalName,
entity.status ?? "active",
entity.supersededBy ?? null,
entity.visibility ?? "public",
entity.createdAt,
entity.createdBy,
JSON.stringify(entity)
]
});
statements.push({
sql: "INSERT INTO entity_fts (entity_id, ontology, canonical_name, aliases, description) VALUES (?, ?, ?, ?, ?)",
args: [entity.id, ontology, entity.canonicalName, (entity.aliases ?? []).join(" "), ""]
});
for (const alias of entity.aliases ?? []) {
statements.push({
sql: "INSERT OR IGNORE INTO aliases (ontology, entity_id, alias) VALUES (?, ?, ?)",
args: [ontology, entity.id, alias]
});
}
for (const [namespace, value] of Object.entries(entity.externalIds ?? {})) {
statements.push({
sql: "INSERT OR REPLACE INTO external_ids (ontology, entity_id, namespace, value) VALUES (?, ?, ?, ?)",
args: [ontology, entity.id, namespace, value]
});
}
}
for (const claim of pkg.data.claims) {
statements.push({
sql: `INSERT INTO claims (ontology, id, subject, predicate, object_entity, object_value, status, confidence,
valid_from, valid_to, observed_at, asserted_at, asserted_by, run_id, change_set, visibility, document)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
args: [
ontology,
claim.id,
claim.subject,
claim.predicate,
"entity" in claim.object ? claim.object.entity : null,
"entity" in claim.object ? null : JSON.stringify(claim.object.value),
claim.status,
claim.confidence ?? null,
claim.validTime?.from ?? null,
claim.validTime?.to ?? null,
claim.observedAt ?? null,
claim.assertedAt,
claim.assertedBy,
claim.runId ?? null,
claim.changeSet ?? null,
claim.visibility ?? "public",
JSON.stringify(claim)
]
});
for (const source of claim.sources ?? []) {
statements.push({
sql: "INSERT OR IGNORE INTO claim_sources (ontology, claim_id, source_id) VALUES (?, ?, ?)",
args: [ontology, claim.id, source]
});
}
}
for (const source of pkg.data.sources) {
statements.push({
sql: `INSERT INTO sources (ontology, id, source_type, uri, retrieved_at, content_hash, license, visibility, stale, document)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
args: [
ontology,
source.id,
source.sourceType,
source.uri,
source.retrievedAt,
source.contentHash ?? null,
source.license ?? null,
source.visibility ?? "public",
source.stale ? 1 : 0,
JSON.stringify(source)
]
});
}
for (const record of pkg.data.evidence) {
statements.push({
sql: "INSERT INTO evidence (ontology, id, source_id, document) VALUES (?, ?, ?, ?)",
args: [ontology, record.id, record.source, JSON.stringify(record)]
});
}
// Batched so a partial seed cannot leave a half-populated ontology behind.
for (let i = 0; i < statements.length; i += 200) {
await client.batch(statements.slice(i, i + 200), "write");
}
}
async function hydrate(client: Client, ontology: string) {
const [meta, entities, claims, sources, evidence, log, changeSets, reviews, approvals, events] =
await Promise.all([
client.execute({ sql: "SELECT manifest, schema_json, revision FROM ontologies WHERE id = ?", args: [ontology] }),
client.execute({ sql: "SELECT document FROM entities WHERE ontology = ?", args: [ontology] }),
client.execute({ sql: "SELECT document FROM claims WHERE ontology = ?", args: [ontology] }),
client.execute({ sql: "SELECT document FROM sources WHERE ontology = ?", args: [ontology] }),
client.execute({ sql: "SELECT document FROM evidence WHERE ontology = ?", args: [ontology] }),
client.execute({
sql: "SELECT kind, object_id, status, at, by, change_set, reason FROM status_log WHERE ontology = ? ORDER BY seq",
args: [ontology]
}),
client.execute({ sql: "SELECT document FROM changesets WHERE ontology = ?", args: [ontology] }),
client.execute({ sql: "SELECT document FROM reviews WHERE ontology = ?", args: [ontology] }),
client.execute({ sql: "SELECT document FROM approvals WHERE ontology = ?", args: [ontology] }),
client.execute({ sql: "SELECT document FROM ontology_events WHERE ontology = ? ORDER BY seq", args: [ontology] })
]);
const row = meta.rows[0];
if (!row) throw new Error(`Ontology ${ontology} disappeared while hydrating`);
const docs = <T>(result: { rows: Array<Record<string, unknown>> }): T[] =>
result.rows.map((r) => JSON.parse(String(r.document)) as T);
const pkg: LoadedPackage = {
manifest: JSON.parse(String(row.manifest)) as LoadedPackage["manifest"],
schema: JSON.parse(String(row.schema_json)) as LoadedPackage["schema"],
data: {
entities: docs(entities),
claims: docs(claims),
sources: docs(sources),
evidence: docs(evidence)
},
files: []
};
return {
pkg,
revision: Number(row.revision ?? 0),
transitions: log.rows.map((r) => ({
kind: String(r.kind) as "claim" | "entity",
transition: {
objectId: String(r.object_id),
status: String(r.status) as never,
at: String(r.at),
by: String(r.by),
changeSet: r.change_set ? String(r.change_set) : undefined,
reason: r.reason ? String(r.reason) : undefined
}
})),
changeSets: docs<LoadedPackage["data"]["entities"][number] & never>(changeSets) as never[],
reviews: docs(reviews) as never[],
approvals: docs(approvals) as never[],
events: docs(events) as never[]
};
}
/** Full-text entity search backed by FTS5 (R186). */
export async function searchEntities(
client: Client,
ontology: string,
query: string,
limit = 20
): Promise<Array<{ id: string; canonicalName: string; rank: number }>> {
const result = await client.execute({
sql: `SELECT entity_id, canonical_name, rank FROM entity_fts
WHERE ontology = ? AND entity_fts MATCH ?
ORDER BY rank LIMIT ?`,
args: [ontology, query, limit]
});
return result.rows.map((row) => ({
id: String(row.entity_id),
canonicalName: String(row.canonical_name),
rank: Number(row.rank ?? 0)
}));
}
export { revisionId };

View file

@ -0,0 +1,114 @@
import { describe, expect, it } from "vitest";
import { exportTurtle, importTurtle } from "./rdf.js";
import { constraintsToShacl } from "./shacl.js";
import { packagePrefix } from "./jsonld.js";
import { loadPrdFixturePackage } from "./test-helpers.js";
const pkg = loadPrdFixturePackage();
describe("RDF/Turtle", () => {
it("declares the prefixes it uses", () => {
const { turtle } = exportTurtle(pkg);
for (const prefix of ["oo:", "prov:", "rdf:", "rdfs:", "xsd:"]) {
expect(turtle).toContain(`@prefix ${prefix}`);
}
});
it("reifies claims so provenance survives the crossing", () => {
const { turtle } = exportTurtle(pkg);
expect(turtle).toContain("a oo:Claim");
expect(turtle).toContain("rdf:subject");
expect(turtle).toContain("prov:wasDerivedFrom");
expect(turtle).toContain("prov:wasAttributedTo");
});
it("also emits the plain triple for asserted relationships", () => {
const { turtle } = exportTurtle(pkg);
const worksOn = turtle.split("\n").filter((line) => line.includes("worksOn"));
// Reified (rdf:predicate) plus at least one direct triple.
expect(worksOn.some((line) => line.includes("rdf:predicate"))).toBe(true);
expect(worksOn.some((line) => !line.includes("rdf:predicate"))).toBe(true);
});
it("round-trips entities and claims through Turtle", () => {
const { turtle } = exportTurtle(pkg);
const back = importTurtle(turtle, { ...pkg.manifest, prefix: packagePrefix(pkg) });
expect(back.entities.map((e) => e.id).sort()).toEqual(pkg.data.entities.map((e) => e.id).sort());
expect(back.claims.map((c) => c.id).sort()).toEqual(pkg.data.claims.map((c) => c.id).sort());
expect(back.unsupported).toEqual([]);
const original = pkg.data.claims[0]!;
const restored = back.claims.find((c) => c.id === original.id)!;
expect(restored.subject).toBe(original.subject);
expect(restored.predicate).toBe(original.predicate);
expect(restored.object).toEqual(original.object);
expect(restored.sources).toEqual(original.sources);
expect(restored.confidence).toBe(original.confidence);
expect(restored.validTime?.from).toBe(original.validTime?.from);
});
it("preserves a scalar property claim's value and type", () => {
const { turtle } = exportTurtle(pkg);
const back = importTurtle(turtle, { ...pkg.manifest, prefix: packagePrefix(pkg) });
const homepage = back.claims.find((c) => c.predicate === "homepage")!;
expect(homepage.object).toEqual({ value: "https://example.org/zk-prover" });
});
it("reports fields the profile cannot carry", () => {
const copy = structuredClone(pkg);
copy.data.claims[0]!.tags = ["zk"];
copy.data.claims[0]!.license = "CC-BY-4.0";
const { lossy } = exportTurtle(copy);
const entry = lossy.find((l) => l.objectId === copy.data.claims[0]!.id);
expect(entry?.fields).toEqual(expect.arrayContaining(["tags", "license"]));
});
it("counts what crossed the boundary", () => {
const { counts } = exportTurtle(pkg);
expect(counts.entities).toBe(pkg.data.entities.length);
expect(counts.claims).toBe(pkg.data.claims.length);
expect(counts.triples).toBeGreaterThan(counts.claims);
});
});
describe("SHACL", () => {
it("maps a required-predicate constraint to a node shape", () => {
const { turtle, mapped } = constraintsToShacl(pkg);
expect(mapped.map((m) => m.constraint)).toContain("project-has-homepage");
expect(turtle).toContain("sh:NodeShape");
expect(turtle).toContain("sh:targetClass ns:Project");
expect(turtle).toContain("sh:minCount 1");
});
it("carries the constraint severity across", () => {
const { turtle } = constraintsToShacl(pkg);
expect(turtle).toContain("sh:Warning");
});
it("reports uniqueness and query constraints as unmappable rather than faking them", () => {
const copy = structuredClone(pkg);
copy.schema.constraints.push(
{
openontology: "0.1",
kind: "Constraint",
id: "unique-homepage",
description: "Homepages are unique.",
rule: { type: "unique", predicate: "homepage" }
},
{
openontology: "0.1",
kind: "Constraint",
id: "needs-review",
description: "No claims awaiting review.",
rule: { type: "query", query: "contributors" }
}
);
const { unmapped, turtle } = constraintsToShacl(copy);
expect(unmapped.map((u) => u.constraint)).toEqual(["unique-homepage", "needs-review"]);
expect(unmapped[0]!.reason).toMatch(/SPARQLConstraint/);
// The gap is stated in the output itself, not just in a return value.
expect(turtle).toContain("# unmapped: unique-homepage");
});
});

View file

@ -0,0 +1,355 @@
import { toIri } from "./ids.js";
import { packagePrefix, OO, PROV } from "./jsonld.js";
import { OPENONTOLOGY_VERSION } from "./types.js";
import type { BuiltPackage, Claim, Entity, LoadedPackage } from "./types.js";
/**
* RDF/Turtle export and import for the losslessly mappable core subset.
*
* Claims are reified — each is its own resource carrying subject, predicate,
* object, status, time, confidence, and provenance — because a bare triple
* cannot say "asserted by this agent, from this commit, valid since April."
* Asserted relationship claims additionally emit the plain triple, so a
* consumer that only wants the current graph gets one.
*/
const PREFIXES: Array<[string, string]> = [
["oo", OO],
["prov", PROV],
["rdf", "http://www.w3.org/1999/02/22-rdf-syntax-ns#"],
["rdfs", "http://www.w3.org/2000/01/rdf-schema#"],
["xsd", "http://www.w3.org/2001/XMLSchema#"]
];
/** Fields this profile carries. Everything else is reported as lossy. */
const LOSSLESS_CLAIM_FIELDS = new Set([
"openontology",
"kind",
"id",
"ontology",
"subject",
"predicate",
"object",
"status",
"confidence",
"validTime",
"observedAt",
"assertedAt",
"assertedBy",
"runId",
"sources",
"evidence",
"supersedes",
"disputes"
]);
const LOSSLESS_ENTITY_FIELDS = new Set([
"openontology",
"kind",
"id",
"type",
"canonicalName",
"aliases",
"externalIds",
"status",
"createdAt",
"createdBy",
"supersededBy"
]);
export interface TurtleExport {
turtle: string;
lossy: Array<{ objectId: string; fields: string[] }>;
/** Counts, so a caller can report what actually crossed the boundary. */
counts: { entities: number; claims: number; sources: number; triples: number };
}
export function exportTurtle(pkg: BuiltPackage | LoadedPackage): TurtleExport {
const manifest = pkg.manifest;
const prefix = packagePrefix(pkg);
const ns = manifest.namespace.endsWith("/") ? manifest.namespace : `${manifest.namespace}/`;
const iri = (id: string) => `<${toIri(id, { defaultNamespace: manifest.namespace })}>`;
const vocab = (term: string) => `<${ns}${encodeURIComponent(term)}>`;
const lossy: TurtleExport["lossy"] = [];
const lines: string[] = [];
let triples = 0;
const emit = (subject: string, pairs: Array<[string, string]>) => {
if (pairs.length === 0) return;
lines.push(`${subject}`);
pairs.forEach(([predicate, object], index) => {
triples += 1;
lines.push(` ${predicate} ${object}${index === pairs.length - 1 ? " ." : " ;"}`);
});
lines.push("");
};
for (const [name, uri] of PREFIXES) lines.push(`@prefix ${name}: <${uri}> .`);
lines.push(`@prefix ns: <${ns}> .`);
lines.push(`@prefix pkg: <${ns}> .`);
lines.push("");
lines.push(`# LogicSRC OpenOntology ${OPENONTOLOGY_VERSION} — ${manifest.id}@${manifest.version}`);
lines.push(`# compact id prefix: ${prefix}`);
lines.push("");
for (const entity of pkg.data.entities) {
const pairs: Array<[string, string]> = [
["a", vocab(entity.type)],
["rdfs:label", literal(entity.canonicalName)],
["oo:status", literal(entity.status ?? "active")],
["prov:generatedAtTime", typed(entity.createdAt, "xsd:dateTime")],
["prov:wasAttributedTo", literal(entity.createdBy)]
];
for (const alias of entity.aliases ?? []) pairs.push(["oo:alias", literal(alias)]);
for (const [namespace, value] of Object.entries(entity.externalIds ?? {})) {
pairs.push(["oo:externalId", literal(`${namespace}:${value}`)]);
}
if (entity.supersededBy) pairs.push(["oo:supersededBy", iri(entity.supersededBy)]);
emit(iri(entity.id), pairs);
const extra = extraFields(entity as unknown as Record<string, unknown>, LOSSLESS_ENTITY_FIELDS);
if (extra.length) lossy.push({ objectId: entity.id, fields: extra });
}
for (const claim of pkg.data.claims) {
const objectTerm =
"entity" in claim.object ? iri(claim.object.entity) : valueTerm(claim.object);
const pairs: Array<[string, string]> = [
["a", "oo:Claim"],
["rdf:subject", iri(claim.subject)],
["rdf:predicate", vocab(claim.predicate)],
["rdf:object", objectTerm],
["oo:status", literal(claim.status)],
["prov:generatedAtTime", typed(claim.assertedAt, "xsd:dateTime")],
["prov:wasAttributedTo", literal(claim.assertedBy)]
];
if (claim.confidence !== undefined) pairs.push(["oo:confidence", typed(String(claim.confidence), "xsd:double")]);
if (claim.validTime?.from) pairs.push(["oo:validFrom", typed(claim.validTime.from, "xsd:dateTime")]);
if (claim.validTime?.to) pairs.push(["oo:validTo", typed(claim.validTime.to, "xsd:dateTime")]);
if (claim.observedAt) pairs.push(["oo:observedAt", typed(claim.observedAt, "xsd:dateTime")]);
if (claim.runId) pairs.push(["prov:wasGeneratedBy", literal(claim.runId)]);
for (const source of claim.sources ?? []) pairs.push(["prov:wasDerivedFrom", iri(source)]);
for (const record of claim.evidence ?? []) pairs.push(["oo:evidence", iri(record)]);
if (claim.supersedes) pairs.push(["oo:supersedes", iri(claim.supersedes)]);
if (claim.disputes) pairs.push(["oo:disputes", iri(claim.disputes)]);
emit(iri(claim.id), pairs);
// The plain triple, for consumers that only want the accepted graph.
if (claim.status === "asserted" && "entity" in claim.object) {
emit(iri(claim.subject), [[vocab(claim.predicate), iri(claim.object.entity)]]);
}
const extra = extraFields(claim as unknown as Record<string, unknown>, LOSSLESS_CLAIM_FIELDS);
if (extra.length) lossy.push({ objectId: claim.id, fields: extra });
}
for (const source of pkg.data.sources) {
emit(iri(source.id), [
["a", "prov:Entity"],
["oo:sourceType", literal(source.sourceType)],
["oo:uri", literal(source.uri)],
["prov:generatedAtTime", typed(source.retrievedAt, "xsd:dateTime")],
...(source.license ? ([["oo:license", literal(source.license)]] as Array<[string, string]>) : []),
...(source.contentHash ? ([["oo:contentHash", literal(source.contentHash)]] as Array<[string, string]>) : [])
]);
}
return {
turtle: `${lines.join("\n").trimEnd()}\n`,
lossy,
counts: {
entities: pkg.data.entities.length,
claims: pkg.data.claims.length,
sources: pkg.data.sources.length,
triples
}
};
}
/**
* Import the profile `exportTurtle` produces.
*
* This is deliberately a parser for that profile, not a general Turtle parser:
* it reads the reified claim shape and the entity shape, and ignores plain
* triples (which are redundant with the claims). Anything it cannot interpret
* is reported rather than silently dropped.
*/
export function importTurtle(
turtle: string,
manifest: { id: string; namespace: string; prefix?: string }
): { entities: Entity[]; claims: Claim[]; unsupported: string[] } {
const base = manifest.namespace.endsWith("/") ? manifest.namespace : `${manifest.namespace}/`;
const prefix = manifest.prefix ?? manifest.id;
const compact = (value: string): string => {
const trimmed = value.replace(/^<|>$/g, "");
if (!trimmed.startsWith(base)) return trimmed;
return [prefix, ...trimmed.slice(base.length).split("/").map(decodeURIComponent)].join(":");
};
const term = (value: string): string => {
const trimmed = value.replace(/^<|>$/g, "");
if (!trimmed.startsWith(base)) return trimmed;
return decodeURIComponent(trimmed.slice(base.length));
};
const entities: Entity[] = [];
const claims: Claim[] = [];
const unsupported: string[] = [];
for (const block of splitBlocks(turtle)) {
const pairs = block.pairs;
const type = pairs.find(([p]) => p === "a" || p === "rdf:type")?.[1];
if (type === "oo:Claim") {
const objectTerm = pairs.find(([p]) => p === "rdf:object")?.[1] ?? "";
const claim: Claim = {
openontology: OPENONTOLOGY_VERSION,
kind: "Claim",
id: compact(block.subject),
subject: compact(pairs.find(([p]) => p === "rdf:subject")?.[1] ?? ""),
predicate: term(pairs.find(([p]) => p === "rdf:predicate")?.[1] ?? ""),
object: objectTerm.startsWith("<")
? { entity: compact(objectTerm) }
: { value: parseLiteral(objectTerm) },
status: (unquote(pairs.find(([p]) => p === "oo:status")?.[1] ?? '"asserted"') as Claim["status"]) ?? "asserted",
assertedAt: unquote(pairs.find(([p]) => p === "prov:generatedAtTime")?.[1] ?? '""'),
assertedBy: unquote(pairs.find(([p]) => p === "prov:wasAttributedTo")?.[1] ?? '""')
};
const confidence = pairs.find(([p]) => p === "oo:confidence")?.[1];
if (confidence) claim.confidence = Number(unquote(confidence));
const from = pairs.find(([p]) => p === "oo:validFrom")?.[1];
const to = pairs.find(([p]) => p === "oo:validTo")?.[1];
if (from || to) {
claim.validTime = {
...(from ? { from: unquote(from) } : {}),
...(to ? { to: unquote(to) } : {})
};
}
const observed = pairs.find(([p]) => p === "oo:observedAt")?.[1];
if (observed) claim.observedAt = unquote(observed);
const run = pairs.find(([p]) => p === "prov:wasGeneratedBy")?.[1];
if (run) claim.runId = unquote(run);
const sources = pairs.filter(([p]) => p === "prov:wasDerivedFrom").map(([, o]) => compact(o));
if (sources.length) claim.sources = sources;
const evidence = pairs.filter(([p]) => p === "oo:evidence").map(([, o]) => compact(o));
if (evidence.length) claim.evidence = evidence;
const supersedes = pairs.find(([p]) => p === "oo:supersedes")?.[1];
if (supersedes) claim.supersedes = compact(supersedes);
const disputes = pairs.find(([p]) => p === "oo:disputes")?.[1];
if (disputes) claim.disputes = compact(disputes);
claims.push(claim);
continue;
}
if (type === "prov:Entity" || !type) continue;
if (!type.startsWith("<")) {
unsupported.push(`${block.subject} has unrecognized type ${type}`);
continue;
}
const entity: Entity = {
openontology: OPENONTOLOGY_VERSION,
kind: "Entity",
id: compact(block.subject),
type: term(type),
canonicalName: unquote(pairs.find(([p]) => p === "rdfs:label")?.[1] ?? '""'),
createdAt: unquote(pairs.find(([p]) => p === "prov:generatedAtTime")?.[1] ?? '""'),
createdBy: unquote(pairs.find(([p]) => p === "prov:wasAttributedTo")?.[1] ?? '""')
};
const aliases = pairs.filter(([p]) => p === "oo:alias").map(([, o]) => unquote(o));
if (aliases.length) entity.aliases = aliases;
const externalIds = pairs.filter(([p]) => p === "oo:externalId").map(([, o]) => unquote(o));
if (externalIds.length) {
entity.externalIds = Object.fromEntries(
externalIds.map((pair) => {
const at = pair.indexOf(":");
return [pair.slice(0, at), pair.slice(at + 1)];
})
);
}
const status = pairs.find(([p]) => p === "oo:status")?.[1];
if (status && unquote(status) !== "active") entity.status = unquote(status) as Entity["status"];
const supersededBy = pairs.find(([p]) => p === "oo:supersededBy")?.[1];
if (supersededBy) entity.supersededBy = compact(supersededBy);
entities.push(entity);
}
return { entities, claims, unsupported };
}
interface Block {
subject: string;
pairs: Array<[string, string]>;
}
/** Split the profile's `subject\n predicate object ;\n … .` blocks. */
function splitBlocks(turtle: string): Block[] {
const blocks: Block[] = [];
let current: Block | null = null;
for (const raw of turtle.split("\n")) {
const line = raw.trim();
if (!line || line.startsWith("#") || line.startsWith("@prefix")) continue;
if (!raw.startsWith(" ")) {
if (current) blocks.push(current);
current = { subject: line.replace(/\s*[;.]$/, ""), pairs: [] };
continue;
}
if (!current) continue;
const body = line.replace(/\s*[;.]$/, "");
const space = body.indexOf(" ");
if (space < 0) continue;
current.pairs.push([body.slice(0, space), body.slice(space + 1).trim()]);
}
if (current) blocks.push(current);
// Plain triples re-state an asserted claim, so drop those single-pair blocks.
return blocks.filter((block) => block.pairs.some(([p]) => p === "a" || p === "rdf:type"));
}
function literal(value: string): string {
return JSON.stringify(String(value));
}
function typed(value: string, datatype: string): string {
return `${JSON.stringify(value)}^^${datatype}`;
}
function valueTerm(object: { value: unknown; language?: string }): string {
if (object.language) return `${JSON.stringify(String(object.value))}@${object.language}`;
if (typeof object.value === "number") return `${JSON.stringify(String(object.value))}^^xsd:double`;
if (typeof object.value === "boolean") return `${JSON.stringify(String(object.value))}^^xsd:boolean`;
return literal(String(object.value));
}
function unquote(term: string): string {
const match = /^"((?:[^"\\]|\\.)*)"/.exec(term.trim());
if (!match) return term.trim();
return JSON.parse(`"${match[1]}"`) as string;
}
function parseLiteral(term: string): unknown {
const text = unquote(term);
if (term.includes("^^xsd:double") || term.includes("^^xsd:integer")) return Number(text);
if (term.includes("^^xsd:boolean")) return text === "true";
return text;
}
function extraFields(object: Record<string, unknown>, lossless: Set<string>): string[] {
return Object.keys(object).filter((key) => !lossless.has(key) && object[key] !== undefined);
}

View file

@ -0,0 +1,209 @@
import { packagePrefix, OO } from "./jsonld.js";
import type { BuiltPackage, Constraint, LoadedPackage } from "./types.js";
/**
* SHACL mapping for the constraint kinds whose semantics genuinely match.
*
* Four of the seven map cleanly onto node/property shapes. `unique` and the
* query-based checks do not — SHACL has no portable "this value appears once
* across the graph" without SPARQL constraints, and an OpenOntology saved
* query is not a SPARQL query. Those are reported as unmapped rather than
* approximated, because a shape that silently means something else is worse
* than no shape at all.
*/
export interface ShaclExport {
turtle: string;
mapped: Array<{ constraint: string; shape: string }>;
unmapped: Array<{ constraint: string; rule: string; reason: string }>;
}
export function constraintsToShacl(pkg: BuiltPackage | LoadedPackage): ShaclExport {
const manifest = pkg.manifest;
const ns = manifest.namespace.endsWith("/") ? manifest.namespace : `${manifest.namespace}/`;
const prefix = packagePrefix(pkg);
const mapped: ShaclExport["mapped"] = [];
const unmapped: ShaclExport["unmapped"] = [];
const body: string[] = [];
const shapeName = (constraint: Constraint) =>
`ns:${toPascal(constraint.id)}Shape`;
for (const constraint of pkg.schema.constraints) {
const severity = shaclSeverity(constraint.severity ?? "error");
const shape = shapeName(constraint);
const rule = constraint.rule;
switch (rule.type) {
case "required-predicate": {
body.push(
`${shape}`,
` a sh:NodeShape ;`,
` sh:targetClass ns:${rule.entityType} ;`,
` rdfs:comment ${JSON.stringify(constraint.description)} ;`,
` sh:property [`,
` sh:path ns:${rule.predicate} ;`,
` sh:minCount 1 ;`,
` sh:severity ${severity} ;`,
` sh:message ${JSON.stringify(constraint.description)} ;`,
` ] .`,
""
);
mapped.push({ constraint: constraint.id, shape });
break;
}
case "cardinality": {
const counts = [
rule.min !== undefined ? ` sh:minCount ${rule.min} ;` : null,
rule.max !== undefined ? ` sh:maxCount ${rule.max} ;` : null
].filter(Boolean) as string[];
body.push(
`${shape}`,
` a sh:NodeShape ;`,
rule.entityType ? ` sh:targetClass ns:${rule.entityType} ;` : ` sh:targetSubjectsOf ns:${rule.predicate} ;`,
` rdfs:comment ${JSON.stringify(constraint.description)} ;`,
` sh:property [`,
` sh:path ns:${rule.predicate} ;`,
...counts,
` sh:severity ${severity} ;`,
` sh:message ${JSON.stringify(constraint.description)} ;`,
` ] .`,
""
);
mapped.push({ constraint: constraint.id, shape });
break;
}
case "allowed-values": {
body.push(
`${shape}`,
` a sh:NodeShape ;`,
` sh:targetSubjectsOf ns:${rule.predicate} ;`,
` rdfs:comment ${JSON.stringify(constraint.description)} ;`,
` sh:property [`,
` sh:path ns:${rule.predicate} ;`,
` sh:in (${rule.values.map((value) => JSON.stringify(String(value))).join(" ")}) ;`,
` sh:severity ${severity} ;`,
` sh:message ${JSON.stringify(constraint.description)} ;`,
` ] .`,
""
);
mapped.push({ constraint: constraint.id, shape });
break;
}
case "domain-range": {
const lines = [`${shape}`, ` a sh:NodeShape ;`];
lines.push(` sh:targetSubjectsOf ns:${rule.predicate} ;`);
lines.push(` rdfs:comment ${JSON.stringify(constraint.description)} ;`);
if (rule.from?.length) {
lines.push(
` sh:or (${rule.from.map((type) => `[ sh:class ns:${type} ]`).join(" ")}) ;`
);
}
if (rule.to?.length) {
lines.push(
` sh:property [`,
` sh:path ns:${rule.predicate} ;`,
` sh:or (${rule.to.map((type) => `[ sh:class ns:${type} ]`).join(" ")}) ;`,
` sh:severity ${severity} ;`,
` ] ;`
);
}
lines.push(` sh:severity ${severity} .`, "");
body.push(...lines);
mapped.push({ constraint: constraint.id, shape });
break;
}
case "temporal-bounds": {
const props: string[] = [];
if (rule.notBefore) props.push(` sh:minInclusive ${JSON.stringify(rule.notBefore)} ;`);
if (rule.notAfter) props.push(` sh:maxInclusive ${JSON.stringify(rule.notAfter)} ;`);
if (rule.requireValidFrom) props.push(` sh:minCount 1 ;`);
if (props.length === 0) {
unmapped.push({
constraint: constraint.id,
rule: rule.type,
reason: "temporal-bounds with no bounds has nothing to express"
});
break;
}
body.push(
`${shape}`,
` a sh:NodeShape ;`,
` sh:targetObjectsOf ns:${rule.predicate} ;`,
` rdfs:comment ${JSON.stringify(constraint.description)} ;`,
` sh:property [`,
` sh:path oo:validFrom ;`,
...props,
` sh:severity ${severity} ;`,
` ] .`,
""
);
mapped.push({ constraint: constraint.id, shape });
break;
}
case "unique":
unmapped.push({
constraint: constraint.id,
rule: rule.type,
reason:
"graph-wide uniqueness has no portable SHACL Core equivalent; it needs a sh:SPARQLConstraint"
});
break;
case "query":
unmapped.push({
constraint: constraint.id,
rule: rule.type,
reason: "an OpenOntology saved query is a triple-pattern AST, not SPARQL"
});
break;
default:
unmapped.push({ constraint: (constraint as Constraint).id, rule: "unknown", reason: "unrecognized rule type" });
}
}
const header = [
"@prefix sh: <http://www.w3.org/ns/shacl#> .",
"@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .",
"@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .",
`@prefix oo: <${OO}> .`,
`@prefix ns: <${ns}> .`,
"",
`# SHACL shapes generated from ${manifest.id}@${manifest.version} (compact prefix: ${prefix})`,
`# ${mapped.length} constraint(s) mapped, ${unmapped.length} not mappable to SHACL Core.`,
...unmapped.map((entry) => `# unmapped: ${entry.constraint} (${entry.rule}) — ${entry.reason}`),
""
];
return {
turtle: `${[...header, ...body].join("\n").trimEnd()}\n`,
mapped,
unmapped
};
}
function shaclSeverity(severity: string): string {
switch (severity) {
case "warning":
return "sh:Warning";
case "info":
case "policy":
return "sh:Info";
default:
return "sh:Violation";
}
}
function toPascal(id: string): string {
return id
.split(/[-_\s]+/)
.map((part) => part.charAt(0).toUpperCase() + part.slice(1))
.join("");
}

View file

@ -0,0 +1,16 @@
import { mkdtempSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { loadOntologyPackage } from "./package.js";
import { initOntologyPackage } from "./scaffold.js";
import type { LoadedPackage } from "./types.js";
/**
* A scaffolded package with a pinned timestamp, for tests that need real data
* without depending on the Ethereum example (which is removable by design).
*/
export function loadPrdFixturePackage(id = "test-ecosystem"): LoadedPackage {
const dir = mkdtempSync(join(tmpdir(), "openontology-fixture-"));
initOntologyPackage(dir, { id, now: "2026-07-26T00:00:00Z" });
return loadOntologyPackage(dir);
}

View file

@ -9,8 +9,9 @@
"build": "tsc -p tsconfig.json"
},
"dependencies": {
"@logicsrc/plugin-core": "file:../plugin-core",
"@logicsrc/openontology": "file:../openontology",
"@logicsrc/plugin-coinpay": "file:../../plugins/coinpay",
"@logicsrc/plugin-core": "file:../plugin-core",
"@logicsrc/plugin-email-accounts": "file:../../plugins/email-accounts",
"@logicsrc/plugin-social-accounts": "file:../../plugins/social-accounts",
"@logicsrc/plugin-ugig": "file:../../plugins/ugig"

View file

@ -3,6 +3,7 @@ import { coinPayPlugin } from "@logicsrc/plugin-coinpay";
import { emailAccountsPlugin } from "@logicsrc/plugin-email-accounts";
import { socialAccountsPlugin } from "@logicsrc/plugin-social-accounts";
import { uGigPlugin } from "@logicsrc/plugin-ugig";
export { renderOntologyTui, renderOntologyKeyHelp, PANEL_KEYS, type OntologyPanel, type OntologyTuiOptions } from "./openontology.js";
export { ArcadeRegistry, createDefaultArcadeRegistry, renderArcadeList, renderArcadeSnapshot, runArcadeSession } from "./arcade/index.js";
export type { ArcadeEvent, GameAction, GameContext, GameControl, KeyEvent, TaskEvent, TaskSnapshot, TerminalFrame, WaitingGame } from "./arcade/index.js";

View file

@ -0,0 +1,94 @@
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterAll, describe, expect, it } from "vitest";
import {
createOntologyEngine,
initOntologyPackage,
loadOntologyPackage,
localActor
} from "@logicsrc/openontology";
import { renderOntologyKeyHelp, renderOntologyTui, PANEL_KEYS } from "./openontology.js";
const dirs: string[] = [];
afterAll(() => {
for (const dir of dirs) rmSync(dir, { recursive: true, force: true });
});
function engine() {
const dir = mkdtempSync(join(tmpdir(), "tui-ontology-"));
dirs.push(dir);
initOntologyPackage(dir, { id: "test-ecosystem", now: "2026-07-26T00:00:00Z" });
return createOntologyEngine({
package: loadOntologyPackage(dir),
actor: localActor("curator"),
clock: () => "2026-07-26T00:00:00Z"
});
}
describe("ontology TUI", () => {
it("renders a bordered frame with the key bar and status line", () => {
const output = renderOntologyTui(engine());
const lines = output.split("\n");
expect(lines[0]!.startsWith("┌")).toBe(true);
expect(lines.at(-1)!.startsWith("└")).toBe(true);
expect(output).toContain("e entities");
expect(output).toContain("q quit");
expect(output).toContain("asserted claims");
});
it("never exceeds the requested width, and stays usable when narrow", () => {
for (const width of [60, 78, 120]) {
const lines = renderOntologyTui(engine(), { width }).split("\n");
const widths = new Set(lines.map((line) => [...line].length));
expect(widths.size).toBe(1);
expect([...widths][0]).toBe(Math.max(width, 60));
}
});
it("shows every panel", () => {
const e = engine();
expect(renderOntologyTui(e, { panel: "types" })).toContain("Person");
expect(renderOntologyTui(e, { panel: "entities" })).toContain("Alice Reyes");
expect(renderOntologyTui(e, { panel: "claims" })).toContain("worksOn");
expect(renderOntologyTui(e, { panel: "sources" })).toContain("web-page");
expect(renderOntologyTui(e, { panel: "queries" })).toContain("contributors");
expect(renderOntologyTui(e, { panel: "changesets" })).toContain("no change sets");
expect(renderOntologyTui(e, { panel: "violations" })).toContain("no errors");
expect(renderOntologyTui(e, { panel: "audit" })).toContain("no events");
// Rendering is read-only: repainting must not append to the audit log.
expect(renderOntologyTui(e, { panel: "audit" })).toContain("no events");
});
it("distinguishes claim status by glyph and word, not colour", () => {
const claims = renderOntologyTui(engine(), { panel: "claims", rows: 20 });
expect(claims).toMatch(/✓ asserted/);
// No ANSI escapes: the panel must survive a monochrome terminal.
expect(claims.includes("[")).toBe(false);
});
it("surfaces proposed change sets and disputes in the status bar", () => {
const e = engine();
e.createOntologyChangeSet({
title: "pending",
operations: [
{
op: "assert-claim",
value: {
subject: "test:person:alice",
predicate: "worksOn",
object: { entity: "test:project:docs-portal" },
sources: ["test:source:repo"]
}
}
]
});
expect(renderOntologyTui(e)).toContain("1 proposed");
expect(renderOntologyTui(e, { panel: "changesets" })).toContain("pending");
});
it("lists the keys it binds", () => {
expect(renderOntologyKeyHelp()).toContain("v: validate");
expect(PANEL_KEYS.map((entry) => entry.key)).toContain("q");
});
});

View file

@ -0,0 +1,282 @@
import { validateOntologyPackage, type OntologyEngine, type ValidationReport } from "@logicsrc/openontology";
/**
* Keyboard-first OpenOntology panels.
*
* Rendered as plain strings so they work over SSH, in tmux, in a narrow
* terminal, and in tests. Graph diagrams are optional in the standard; lists,
* trees, and paths are what this shows.
*/
export type OntologyPanel = "types" | "entities" | "claims" | "sources" | "queries" | "changesets" | "violations" | "audit";
export const PANEL_KEYS: Array<{ key: string; panel: OntologyPanel | "quit" | "search"; label: string }> = [
{ key: "/", panel: "search", label: "search" },
{ key: "t", panel: "types", label: "types" },
{ key: "e", panel: "entities", label: "entities" },
{ key: "c", panel: "claims", label: "claims" },
{ key: "s", panel: "sources", label: "sources" },
{ key: "r", panel: "queries", label: "queries" },
{ key: "g", panel: "changesets", label: "change sets" },
{ key: "v", panel: "violations", label: "validate" },
{ key: "a", panel: "audit", label: "audit" },
{ key: "q", panel: "quit", label: "quit" }
];
export interface OntologyTuiOptions {
panel?: OntologyPanel;
/** Terminal width. Clamped to a usable minimum. */
width?: number;
/** Rows of detail to show. */
rows?: number;
selected?: string;
}
const MIN_WIDTH = 60;
export function renderOntologyTui(engine: OntologyEngine, options: OntologyTuiOptions = {}): string {
const width = Math.max(options.width ?? 78, MIN_WIDTH);
const rows = options.rows ?? 8;
const panel = options.panel ?? "entities";
const manifest = engine.getOntologyManifest();
const schema = engine.getOntologySchema();
const lines: string[] = [];
const inner = width - 2;
const rule = (left: string, right: string, fill = "─") => `${left}${fill.repeat(inner)}${right}`;
const row = (text: string) => `│${clip(` ${text}`, inner)}│`;
const heading = (text: string) => `├${clip(`─ ${text} `, inner, "─")}┤`;
lines.push(rule("┌", "┐"));
lines.push(row(`OpenOntology: ${manifest.id}@${manifest.version} rev ${engine.store.revision()}`));
// The key bar wraps rather than truncating: a binding you cannot see is a
// binding you do not have.
for (const line of wrap(PANEL_KEYS.map((entry) => `${entry.key} ${entry.label}`), inner - 1)) {
lines.push(row(line));
}
lines.push(heading(panelTitle(panel)));
for (const line of panelBody(engine, panel, { rows, selected: options.selected, width: inner })) {
lines.push(row(line));
}
// Status bar: what needs a human, always visible.
const changeSets = engine.store.listChangeSets();
const proposed = changeSets.filter((entry) => entry.status === "proposed").length;
const conflicted = changeSets.filter((entry) => entry.status === "conflicted").length;
const report = validate(engine);
const disputed = engine.store.listClaims({ status: ["disputed"] }).length;
lines.push(heading("status"));
lines.push(
row(
`${proposed} proposed ${disputed} disputed ${conflicted} conflicts ` +
`${report.counts.error} errors ${report.counts.warning} warnings`
)
);
lines.push(row(`${schema.entityTypes.length} types ${engine.store.listEntities().length} entities ${engine.store.listClaims({ status: ["asserted"] }).length} asserted claims`));
lines.push(rule("└", "┘"));
return lines.join("\n");
}
/**
* Validate without emitting an event.
*
* `engine.validateOntologyPackage()` records a package.validated event, which
* is right for a CLI run and wrong for a panel that repaints on every keypress:
* rendering a read-only view must not write to the audit log.
*/
function validate(engine: OntologyEngine): ValidationReport {
return validateOntologyPackage({
manifest: engine.getOntologyManifest(),
schema: engine.getOntologySchema(),
data: {
entities: engine.store.listEntities(),
claims: engine.store.listClaims({
status: ["asserted", "proposed", "disputed", "retracted", "superseded", "derived"]
}),
sources: engine.store.listSources(),
evidence: engine.store.listEvidence()
},
files: []
});
}
function panelTitle(panel: OntologyPanel): string {
switch (panel) {
case "types":
return "Types";
case "entities":
return "Entities";
case "claims":
return "Claims";
case "sources":
return "Sources";
case "queries":
return "Saved queries";
case "changesets":
return "Change sets";
case "violations":
return "Validation";
default:
return "Audit";
}
}
function panelBody(
engine: OntologyEngine,
panel: OntologyPanel,
view: { rows: number; selected?: string; width: number }
): string[] {
const { rows } = view;
switch (panel) {
case "types": {
const counts = new Map<string, number>();
for (const entity of engine.store.listEntities()) {
counts.set(entity.type, (counts.get(entity.type) ?? 0) + 1);
}
return engine
.getOntologySchema()
.entityTypes.slice(0, rows)
.map((type) => `${pad(type.id, 20)} ${String(counts.get(type.id) ?? 0).padStart(5)} ${type.label}`);
}
case "entities": {
const entities = engine.store.listEntities({ limit: rows });
return entities.map(
(entity) =>
`${statusMark(entity.status ?? "active")} ${pad(entity.canonicalName, 26)} ${pad(entity.type, 14)} ${entity.id}`
);
}
case "claims": {
const claims = engine.store.listClaims({
status: ["asserted", "proposed", "disputed", "retracted", "superseded", "derived"],
limit: rows
});
return claims.map((claim) => {
const object = "entity" in claim.object ? claim.object.entity : JSON.stringify(claim.object.value);
const confidence = claim.confidence === undefined ? " — " : claim.confidence.toFixed(2);
const from = claim.validTime?.from?.slice(0, 10) ?? "—";
// Status is never conveyed by colour alone: a glyph and the word.
return `${statusMark(claim.status)} ${pad(claim.status, 10)} ${pad(shorten(claim.subject), 22)} ${pad(claim.predicate, 14)} ${pad(shorten(object), 22)} ${confidence} ${from} src:${claim.sources?.length ?? 0}`;
});
}
case "sources": {
return engine.store
.listSources()
.slice(0, rows)
.map(
(source) =>
`${source.stale ? "!" : "·"} ${pad(source.sourceType, 14)} ${pad(source.license ?? "unknown", 12)} ${source.uri}`
);
}
case "queries": {
return engine
.getOntologySchema()
.queries.slice(0, rows)
.map((query) => `${pad(query.id, 30)} ${query.description}`);
}
case "changesets": {
const changeSets = engine.store.listChangeSets().slice(0, rows);
if (changeSets.length === 0) return ["(no change sets in this session)"];
return changeSets.map((changeSet) => {
const approvals = engine.store.listApprovals(changeSet.id).length;
const required = changeSet.requiredApprovals ?? 0;
return `${statusMark(changeSet.status)} ${pad(changeSet.status, 10)} ${pad(changeSet.title, 34)} ops:${String(changeSet.operations.length).padStart(3)} appr:${approvals}/${required}`;
});
}
case "violations": {
const report = validate(engine);
const findings = report.findings.filter((finding) => finding.severity !== "info").slice(0, rows);
if (findings.length === 0) return ["✓ no errors, warnings, or policy findings"];
return findings.map(
(finding) => `${severityMark(finding.severity)} ${pad(finding.code, 24)} ${finding.message}`
);
}
default: {
const events = engine.listEvents({ limit: rows });
if (events.length === 0) return ["(no events in this session)"];
return events.map(
(event) => `${event.at.slice(0, 19)} ${pad(event.type, 20)} ${pad(event.actor, 20)} ${event.subject ?? ""}`
);
}
}
}
/** Glyphs, not colour, so the status survives a monochrome terminal. */
function statusMark(status: string): string {
switch (status) {
case "asserted":
case "active":
case "applied":
return "✓";
case "proposed":
return "?";
case "disputed":
case "conflicted":
return "!";
case "retracted":
case "rejected":
return "×";
case "superseded":
case "merged":
return "→";
case "derived":
return "ƒ";
case "archived":
return "▪";
default:
return "·";
}
}
function severityMark(severity: string): string {
return severity === "error" ? "✗" : severity === "warning" ? "!" : "·";
}
/** Pack items onto as many lines as the width needs. */
function wrap(items: string[], width: number): string[] {
const lines: string[] = [];
let current = "";
for (const item of items) {
const candidate = current ? `${current} ${item}` : item;
if (candidate.length > width && current) {
lines.push(current);
current = item;
} else {
current = candidate;
}
}
if (current) lines.push(current);
return lines;
}
function pad(value: string, width: number): string {
const text = String(value ?? "");
return text.length >= width ? `${text.slice(0, Math.max(width - 1, 1))}…` : text.padEnd(width);
}
function clip(value: string, width: number, fill = " "): string {
const text = value.length > width ? `${value.slice(0, width - 1)}…` : value;
return text.padEnd(width, fill);
}
/** Compact ids read better in a narrow column without their prefix. */
function shorten(id: string): string {
const parts = String(id).split(":");
return parts.length > 2 ? parts.slice(1).join(":") : String(id);
}
/** One-line help for the panel keys, for a footer or `--help`. */
export function renderOntologyKeyHelp(): string {
return PANEL_KEYS.map((entry) => `${entry.key}: ${entry.label}`).join(" ");
}