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

@ -0,0 +1,40 @@
import {
handle,
apiJson,
readJson,
idempotentReplay,
rememberIdempotent
} from "@/lib/ontology-service";
export const dynamic = "force-dynamic";
export async function POST(
request: Request,
{ params }: { params: Promise<{ ontologyId: string; changeSetId: string }> }
) {
const { ontologyId, changeSetId } = await params;
const id = decodeURIComponent(changeSetId);
const replay = idempotentReplay(request);
if (replay) return replay;
const body = await readJson(request);
return handle(request, ontologyId, async (engine, serviceState) => {
const applied = engine.applyOntologyChangeSet(id, {
skipRejectedOperations: body.skipRejectedOperations === true
});
// libSQL buffers writes; make them durable before we report success.
if (serviceState.flush) await serviceState.flush();
const payload = {
changeSet: applied.changeSet.id,
revision: applied.revision,
addedEntities: applied.addedEntities,
addedClaims: applied.addedClaims,
statusChanges: applied.statusChanges,
skipped: applied.skipped,
events: applied.events.map((event) => ({ id: event.id, type: event.type }))
};
rememberIdempotent(request, payload, 200);
return apiJson(payload, { revision: applied.revision });
});
}

View file

@ -0,0 +1,29 @@
import {
handle,
apiJson,
readJson,
idempotentReplay,
rememberIdempotent
} from "@/lib/ontology-service";
export const dynamic = "force-dynamic";
export async function POST(
request: Request,
{ params }: { params: Promise<{ ontologyId: string; changeSetId: string }> }
) {
const { ontologyId, changeSetId } = await params;
const id = decodeURIComponent(changeSetId);
const replay = idempotentReplay(request);
if (replay) return replay;
const body = await readJson(request);
return handle(request, ontologyId, async (engine, serviceState) => {
const approval = engine.approveOntologyChangeSet(id, {
comment: typeof body.comment === "string" ? body.comment : undefined
});
rememberIdempotent(request, { approval }, 201);
return apiJson({ approval }, { status: 201 });
});
}

View file

@ -0,0 +1,32 @@
import {
handle,
apiJson,
readJson,
idempotentReplay,
rememberIdempotent
} from "@/lib/ontology-service";
export const dynamic = "force-dynamic";
export async function POST(
request: Request,
{ params }: { params: Promise<{ ontologyId: string; changeSetId: string }> }
) {
const { ontologyId, changeSetId } = await params;
const id = decodeURIComponent(changeSetId);
const replay = idempotentReplay(request);
if (replay) return replay;
const body = await readJson(request);
return handle(request, ontologyId, async (engine, serviceState) => {
const state = typeof body.state === "string" ? body.state : "commented";
const review = engine.reviewOntologyChangeSet(id, {
state: state as never,
comment: typeof body.comment === "string" ? body.comment : undefined,
operationDecisions: body.operationDecisions as never
});
rememberIdempotent(request, { review }, 201);
return apiJson({ review }, { status: 201 });
});
}

View file

@ -0,0 +1,23 @@
import { handle, apiJson, apiError } from "@/lib/ontology-service";
export const dynamic = "force-dynamic";
export async function GET(
request: Request,
{ params }: { params: Promise<{ ontologyId: string; changeSetId: string }> }
) {
const { ontologyId, changeSetId } = await params;
const id = decodeURIComponent(changeSetId);
return handle(request, ontologyId, (engine) => {
const changeSet = engine.store.getChangeSet(id);
if (!changeSet) return apiError("OO-A-NOT-FOUND", `Unknown change set ${id}`, 404);
return apiJson({
changeSet,
diff: engine.diffOntologyChangeSet(id),
reviews: engine.store.listReviews(id),
approvals: engine.store.listApprovals(id),
events: engine.listEvents({ changeSet: id })
});
});
}

View file

@ -0,0 +1,54 @@
import {
handle,
apiJson,
apiError,
readJson,
idempotentReplay,
rememberIdempotent
} from "@/lib/ontology-service";
export const dynamic = "force-dynamic";
export async function GET(request: Request, { params }: { params: Promise<{ ontologyId: string }> }) {
const { ontologyId } = await params;
return handle(request, ontologyId, (engine) =>
apiJson({
changeSets: engine.store.listChangeSets().map((changeSet) => ({
id: changeSet.id,
title: changeSet.title,
status: changeSet.status,
createdBy: changeSet.createdBy,
createdAt: changeSet.createdAt,
operations: changeSet.operations.length,
requiredApprovals: changeSet.requiredApprovals ?? 0,
approvals: engine.store.listApprovals(changeSet.id).length
}))
})
);
}
// POST — create a PROPOSED change set. Requires ontology:claim:propose.
export async function POST(request: Request, { params }: { params: Promise<{ ontologyId: string }> }) {
const { ontologyId } = await params;
const replay = idempotentReplay(request);
if (replay) return replay;
const body = await readJson(request);
return handle(request, ontologyId, (engine) => {
const title = typeof body.title === "string" ? body.title : null;
const operations = Array.isArray(body.operations) ? body.operations : null;
if (!title || !operations || operations.length === 0) {
return apiError("OO-E-REQUEST", "title and a non-empty operations array are required", 422);
}
const changeSet = engine.createOntologyChangeSet({
title,
rationale: typeof body.rationale === "string" ? body.rationale : undefined,
runId: typeof body.runId === "string" ? body.runId : undefined,
operations: operations as never
});
const payload = { changeSet, diff: engine.diffOntologyChangeSet(changeSet.id) };
rememberIdempotent(request, payload, 201);
return apiJson(payload, { status: 201, revision: engine.store.revision() });
});
}

View file

@ -0,0 +1,21 @@
import { handle, apiJson } from "@/lib/ontology-service";
export const dynamic = "force-dynamic";
export async function GET(
request: Request,
{ params }: { params: Promise<{ ontologyId: string; claimId: string }> }
) {
const { ontologyId, claimId } = await params;
const id = decodeURIComponent(claimId);
return handle(request, ontologyId, (engine) => {
const claim = engine.getClaim(id);
return apiJson({
claim,
history: engine.claimHistory(id),
sources: (claim.sources ?? []).map((sourceId) => engine.store.getSource(sourceId)).filter(Boolean),
evidence: (claim.evidence ?? []).map((evidenceId) => engine.store.getEvidence(evidenceId)).filter(Boolean)
});
});
}

View file

@ -0,0 +1,19 @@
import { handle, apiJson } from "@/lib/ontology-service";
export const dynamic = "force-dynamic";
export async function GET(request: Request, { params }: { params: Promise<{ ontologyId: string }> }) {
const { ontologyId } = await params;
const url = new URL(request.url);
const statusParam = url.searchParams.get("status") ?? "asserted";
const limit = Math.min(Number(url.searchParams.get("limit") ?? 100), 500);
return handle(request, ontologyId, (engine) => {
const claims = engine.store.listClaims({
subject: url.searchParams.get("subject") ?? undefined,
predicate: url.searchParams.get("predicate") ?? undefined,
status: statusParam.split(",").map((value) => value.trim()) as never
});
return apiJson({ total: claims.length, limit, claims: claims.slice(0, limit) });
});
}

View file

@ -0,0 +1,33 @@
import { handle, apiJson } from "@/lib/ontology-service";
export const dynamic = "force-dynamic";
export async function GET(
request: Request,
{ params }: { params: Promise<{ ontologyId: string; entityId: string }> }
) {
const { ontologyId, entityId } = await params;
const id = decodeURIComponent(entityId);
return handle(request, ontologyId, (engine) => {
const entity = engine.getEntity(id);
const claims = engine.store.listClaims({ subject: entity.id });
return apiJson(
{
entity,
// The old id still resolves after a merge; say so rather than 404ing.
redirectedFrom: entity.id === id ? undefined : id,
claims: claims.map((claim) => ({
id: claim.id,
predicate: claim.predicate,
object: claim.object,
status: claim.status,
confidence: claim.confidence,
validTime: claim.validTime,
sources: claim.sources ?? []
}))
},
{ revision: engine.store.revision() }
);
});
}

View file

@ -0,0 +1,46 @@
import { handle, apiJson } from "@/lib/ontology-service";
export const dynamic = "force-dynamic";
// GET /api/ontologies/{id}/entities?type=&q=&limit=&offset=
export async function GET(request: Request, { params }: { params: Promise<{ ontologyId: string }> }) {
const { ontologyId } = await params;
const url = new URL(request.url);
const type = url.searchParams.get("type") ?? undefined;
const q = url.searchParams.get("q") ?? undefined;
const limit = Math.min(Number(url.searchParams.get("limit") ?? 50), 200);
const offset = Math.max(Number(url.searchParams.get("offset") ?? 0), 0);
return handle(request, ontologyId, (engine) => {
if (q) {
const matches = engine.findEntities({ text: q, type, limit });
return apiJson({
total: matches.length,
matches: matches.map((match) => ({
id: match.entity.id,
type: match.entity.type,
canonicalName: match.entity.canonicalName,
status: match.entity.status ?? "active",
score: match.score,
matchedOn: match.matchedOn,
evidence: match.evidence
}))
});
}
const all = engine.store.listEntities({ type });
return apiJson({
total: all.length,
limit,
offset,
entities: all.slice(offset, offset + limit).map((entity) => ({
id: entity.id,
type: entity.type,
canonicalName: entity.canonicalName,
status: entity.status ?? "active",
aliases: entity.aliases ?? [],
externalIds: entity.externalIds ?? {}
}))
});
});
}

View file

@ -0,0 +1,67 @@
import { getService, apiError, apiJson, engineFor } from "@/lib/ontology-service";
export const dynamic = "force-dynamic";
/**
* GET /api/ontologies/{id}/events
*
* Returns the event log as JSON, or a live SSE stream when the client asks for
* text/event-stream. Same event objects either way — the transport does not
* change the schema.
*/
export async function GET(request: Request, { params }: { params: Promise<{ ontologyId: string }> }) {
const { ontologyId } = await params;
const bound = await engineFor(request);
if (!bound) {
const state = await getService();
return apiError("OO-E-UNAVAILABLE", state.error ?? "No ontology is loaded", 503);
}
if (bound.state.ontologyId !== ontologyId) {
return apiError("OO-A-NOT-FOUND", `Unknown ontology ${ontologyId}`, 404);
}
const url = new URL(request.url);
const wantsStream =
(request.headers.get("accept") ?? "").includes("text/event-stream") || url.searchParams.get("stream") === "1";
const engine = bound.engine;
if (!wantsStream) {
const limit = Math.min(Number(url.searchParams.get("limit") ?? 100), 500);
return apiJson({ events: engine.listEvents({ limit }) });
}
const encoder = new TextEncoder();
const stream = new ReadableStream({
start(controller) {
const send = (event: unknown, type: string) => {
controller.enqueue(encoder.encode(`event: ${type}\ndata: ${JSON.stringify(event)}\n\n`));
};
// Replay recent history so a late subscriber is not blind to it.
for (const event of engine.listEvents({ limit: 20 })) send(event, event.type);
send({ ontology: ontologyId, revision: engine.store.revision() }, "ready");
const unsubscribe = engine.subscribeOntologyEvents((event) => send(event, event.type));
const keepAlive = setInterval(() => controller.enqueue(encoder.encode(": keep-alive\n\n")), 15000);
request.signal.addEventListener("abort", () => {
clearInterval(keepAlive);
unsubscribe();
try {
controller.close();
} catch {
// already closed
}
});
}
});
return new Response(stream, {
headers: {
"content-type": "text/event-stream",
"cache-control": "no-store, no-transform",
connection: "keep-alive"
}
});
}

View file

@ -0,0 +1,14 @@
import { handle, apiJson, apiError, readJson } from "@/lib/ontology-service";
export const dynamic = "force-dynamic";
export async function POST(request: Request, { params }: { params: Promise<{ ontologyId: string }> }) {
const { ontologyId } = await params;
const body = await readJson(request);
return handle(request, ontologyId, (engine) => {
const resultId = typeof body.resultId === "string" ? body.resultId : null;
if (!resultId) return apiError("OO-E-REQUEST", "resultId is required", 422);
return apiJson(engine.explainOntologyResult(resultId, Number(body.row ?? 0)));
});
}

View file

@ -0,0 +1,10 @@
import { handle, apiJson } from "@/lib/ontology-service";
export const dynamic = "force-dynamic";
export async function GET(request: Request, { params }: { params: Promise<{ ontologyId: string }> }) {
const { ontologyId } = await params;
return handle(request, ontologyId, (engine) =>
apiJson(engine.getOntologyManifest(), { revision: engine.store.revision() })
);
}

View file

@ -0,0 +1,32 @@
import { handle, apiJson, apiError, readJson } from "@/lib/ontology-service";
export const dynamic = "force-dynamic";
// POST /api/ontologies/{id}/query — portable triple-pattern query.
export async function POST(request: Request, { params }: { params: Promise<{ ontologyId: string }> }) {
const { ontologyId } = await params;
const body = await readJson(request);
return handle(request, ontologyId, (engine) => {
const saved = typeof body.savedQuery === "string" ? body.savedQuery : null;
const query = body.query as Record<string, unknown> | undefined;
if (!saved && !query) {
return apiError("OO-E-REQUEST", "Provide savedQuery or query", 422);
}
const result = engine.queryOntology(
(saved ?? query) as never,
(body.params as Record<string, unknown>) ?? undefined
);
return apiJson(
{
resultId: result.id,
columns: result.columns,
rows: result.rows.map((row) => ({ ...row.bindings, claims: row.claims })),
explanation: result.explanation
},
{ revision: engine.store.revision() }
);
});
}

View file

@ -0,0 +1,10 @@
import { handle, apiJson } from "@/lib/ontology-service";
export const dynamic = "force-dynamic";
export async function GET(request: Request, { params }: { params: Promise<{ ontologyId: string }> }) {
const { ontologyId } = await params;
return handle(request, ontologyId, (engine) =>
apiJson(engine.getOntologySchema(), { revision: engine.store.revision() })
);
}

View file

@ -0,0 +1,12 @@
import { handle, apiJson, readJson } from "@/lib/ontology-service";
export const dynamic = "force-dynamic";
export async function POST(request: Request, { params }: { params: Promise<{ ontologyId: string }> }) {
const { ontologyId } = await params;
const body = await readJson(request);
return handle(request, ontologyId, (engine) =>
apiJson(engine.validateOntologyPackage({ strict: body.strict === true }))
);
}