logicsrc/packages/opencontext/src/adapters/sqlite.ts
Anthony Ettinger 3ab8a4b38b
Add the LogicSRC OpenContext specification (#132)
* Add the LogicSRC OpenContext specification

OpenContext is an open specification for durable, portable, permissioned,
provenance-aware context shared between humans and AI agents. It defines how
organizational knowledge is described, authorized, versioned, resolved,
audited, and handed between replaceable workers without losing institutional
state.

Follows the OpenPRD/OpenOntology pattern already in the repo: self-contained
JSON Schemas in @logicsrc/schemas, a reference implementation package, CLI
subcommands, docs, examples, and an OpenPRD record.

Schemas (8, all self-contained so a third party can fetch one file and
validate against it with no further resolution):
  manifest, object, bundle, role, provenance, decision, diagnostic,
  audit-event — registered in @logicsrc/validators and schemas:validate.

Reference implementation (@logicsrc/opencontext):
  loader with upward manifest discovery, the full resolution pipeline,
  authority/supersession, permissions, redaction, lifecycle, provenance,
  deterministic digests, doctor, search, graph, history/diff, guarded writes,
  audit events, and file/http/git/sqlite adapters.

CLI: all 15 specified commands, as a standalone `opencontext` binary and as
`logicsrc context`, sharing one implementation so the two cannot drift.

Design decisions worth noting:

- Supersession is declared, never inferred from version numbers. Inferring it
  would hide the governance failure it represents and make
  multiple-active-versions and duplicate-canonical impossible to detect.

- The bundle digest identifies the resolved context, not the moment it was
  computed, so generated_at/bundle_id/digest/as_of are excluded while objects,
  lifecycle states, exclusions and warnings are covered. That is what lets a
  decision record cite exactly the context that produced it.

- A role's own max_classification beats an inherited one, so a ceiling on a
  shared base role cannot silently cap a role deliberately granted more;
  requesting several roles at once still takes the lowest, so combining roles
  never escalates.

- Scope wildcards match whole dotted segments only. A trailing .* covers a
  subtree; an interior * matches exactly one segment. Substring matching here
  would be an access-control bug.

- --include narrows an existing scope and is applied after it, never merged
  into it, so a request can never widen what a role holds.

Verified: 226 tests across core primitives, permissions/redaction, the
resolution pipeline, security, the published conformance fixtures (13 valid,
35 invalid, 8 resolution scenarios), project behaviour, and the five shipped
examples — which are held to --strict and a 100% health score. Benchmarks meet
every published budget (resolve 1,000 objects in ~33ms against a 2s target).

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* Point install docs at @logicsrc/opencontext; record the npm name collision

The unscoped `opencontext` name is already published on npm by an unrelated
third party (federicodeponte/opencontext, 2.0.0), so `npx opencontext` would
install a stranger's package. Docs now use `npx @logicsrc/opencontext`; the bin
stays named `opencontext` so the command reads as the PRD specifies once
installed.

Recorded in PRD 0003 as a blocker to resolve before any publication, along with
the fact that no @logicsrc spec package has ever been published, so there is no
existing release path to slot into.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* Advance the logicsrc-mcp next-PRD-id assertion to 0004

standards.test.ts asserts prd_next_id against the live prd/ directory, so
adding PRD 0003 makes the next free id 0004. The test's own comment
anticipates this: "advances with every PRD added".

Caught by CI, not locally — the earlier verification ran per-package tests for
the packages this branch touches, and logicsrc-mcp is coupled to the PRD
directory without importing from it.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-09 11:46:11 -07:00

141 lines
4.7 KiB
TypeScript

/**
* `sqlite://` adapter — context that already lives in a table.
*
* OpenContext is a control plane, not a database: when the truth about pricing
* lives in an application table, the context object points at it rather than
* copying it. The URI names the file, the table, and which row and column hold
* the content:
*
* sqlite://./data/context.db?table=policies&id=refunds&column=body
* sqlite://./data/context.db?table=policies&id=refunds&column=body&key=slug
*
* Identifiers are validated against the database's own schema before they reach
* a statement, and the row key is always bound as a parameter — a context file
* is authored input, and authored input never becomes SQL.
*/
import { createClient, type Client } from "@libsql/client";
import type { Adapter, AdapterContext, AdapterResult } from "../types.js";
import { sha256Uri } from "../digest.js";
import { resolveInside } from "./file.js";
const IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/;
export interface SqliteTarget {
file: string;
table: string;
column: string;
key: string;
id: string;
}
export function parseSqliteUri(uri: string): SqliteTarget {
const withoutScheme = uri.replace(/^sqlite:\/\//, "");
const [pathPart, queryPart] = splitOnce(withoutScheme, "?");
if (!queryPart) {
throw new Error(
`Malformed sqlite URI "${uri}". Expected sqlite://<file>?table=<table>&id=<row>&column=<column>.`
);
}
const params = new URLSearchParams(queryPart);
const table = params.get("table");
const id = params.get("id");
const column = params.get("column") ?? "content";
const key = params.get("key") ?? "id";
if (!table || !id) {
throw new Error(`Malformed sqlite URI "${uri}": both table and id are required.`);
}
for (const [label, value] of [
["table", table],
["column", column],
["key", key]
] as const) {
if (!IDENTIFIER.test(value)) {
throw new Error(`Refusing to use "${value}" as a SQL ${label} name in ${uri}.`);
}
}
return { file: decodeURIComponent(pathPart), table, column, key, id };
}
function splitOnce(value: string, separator: string): [string, string | undefined] {
const index = value.indexOf(separator);
if (index === -1) return [value, undefined];
return [value.slice(0, index), value.slice(index + 1)];
}
export const sqliteAdapter: Adapter = {
name: "sqlite",
schemes: ["sqlite"],
remote: false,
async load(uri: string, ctx: AdapterContext): Promise<AdapterResult> {
const target = parseSqliteUri(uri);
const file = resolveInside(ctx.dir, target.file);
let client: Client | undefined;
try {
client = createClient({ url: `file:${file}` });
// Verify the table and column exist before naming them in a statement.
// Identifiers cannot be bound as parameters, so the only safe source for
// them is the database's own catalogue.
const columns = await client.execute({
sql: "SELECT name FROM pragma_table_info(?)",
args: [target.table]
});
const names = columns.rows.map((row) => String(row.name));
if (names.length === 0) {
throw new Error(`Table "${target.table}" does not exist in ${target.file}.`);
}
for (const [label, value] of [
["column", target.column],
["key", target.key]
] as const) {
if (!names.includes(value)) {
throw new Error(
`Column "${value}" (${label}) does not exist on ${target.table}. Available: ${names.join(", ")}.`
);
}
}
const result = await client.execute({
sql: `SELECT "${target.column}" AS content FROM "${target.table}" WHERE "${target.key}" = ? LIMIT 1`,
args: [target.id]
});
const row = result.rows[0];
if (!row) {
throw new Error(`No row where ${target.key} = "${target.id}" in ${target.table} (${target.file}).`);
}
const value = row.content;
const content = value === null || value === undefined ? "" : String(value);
return {
content,
contentType: looksLikeJson(content) ? "application/json" : "text/markdown",
digest: sha256Uri(content),
retrievedAt: new Date().toISOString(),
// A local database the operator controls is inside the trust boundary,
// but its rows are frequently written by applications and end users, so
// the honest default is `verified` rather than `trusted`.
trust: (ctx.config.trust as AdapterResult["trust"]) ?? "verified"
};
} finally {
client?.close();
}
}
};
function looksLikeJson(content: string): boolean {
const trimmed = content.trim();
if (!trimmed.startsWith("{") && !trimmed.startsWith("[")) return false;
try {
JSON.parse(trimmed);
return true;
} catch {
return false;
}
}