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>
This commit is contained in:
Anthony Ettinger 2026-08-09 11:46:11 -07:00 • committed by GitHub
parent 1bb7ba6e60
commit 3ab8a4b38b
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
212 changed files with 17249 additions and 7 deletions

View file

@ -0,0 +1,103 @@
/**
* `file://` adapter, and the resolver for bare relative paths.
*
* This adapter is the one that runs on every local project, so it is also the
* one that has to be careful: a context repository may be authored by someone
* who is not the person running the resolver, and `../../../.ssh/id_rsa` is a
* perfectly ordinary-looking string in a YAML file. Every path is resolved and
* then checked to be inside the manifest directory before anything is read.
*/
import { readFile, stat } from "node:fs/promises";
import { isAbsolute, relative, resolve, sep } from "node:path";
import { fileURLToPath } from "node:url";
import type { Adapter, AdapterContext, AdapterResult } from "../types.js";
import { sha256Uri } from "../digest.js";
export class PathTraversalError extends Error {
readonly uri: string;
constructor(uri: string, resolved: string, root: string) {
super(
`Refusing to read "${uri}": it resolves to ${resolved}, which is outside the context root ${root}. ` +
`Context sources must stay inside the directory containing opencontext.yaml.`
);
this.name = "PathTraversalError";
this.uri = uri;
}
}
/**
* Turn a `file://` URI or a relative path into an absolute path inside `root`.
*
* Throws rather than clamping: silently rewriting an escaping path would hide
* a misconfigured or hostile context repository.
*/
export function resolveInside(root: string, target: string): string {
const raw = target.startsWith("file:") ? fileUriToPath(target) : target;
// An absolute path is allowed only when it is already inside the root, so an
// authored `/etc/passwd` fails the same way `../../etc/passwd` does.
const absolute = isAbsolute(raw) ? resolve(raw) : resolve(root, raw);
const rootResolved = resolve(root);
const rel = relative(rootResolved, absolute);
if (rel === "") return absolute;
if (rel.startsWith("..") || rel.startsWith(`..${sep}`) || isAbsolute(rel)) {
throw new PathTraversalError(target, absolute, rootResolved);
}
return absolute;
}
function fileUriToPath(uri: string): string {
// `file://./context/mission.md` is not a legal file URI but is what people
// write, so treat a non-absolute file: URI as a relative path.
if (/^file:\/\/\/|^file:\/\/[a-zA-Z]/.test(uri) && !uri.startsWith("file://.")) {
try {
return fileURLToPath(uri);
} catch {
// fall through to the lenient reading below
}
}
return uri.replace(/^file:\/\//, "").replace(/^file:/, "");
}
export const fileAdapter: Adapter = {
name: "file",
schemes: ["file"],
remote: false,
async load(uri: string, ctx: AdapterContext): Promise<AdapterResult> {
const path = resolveInside(ctx.dir, uri);
let stats;
try {
stats = await stat(path);
} catch {
throw new Error(`Source not found: ${uri} (looked in ${path})`);
}
if (stats.isDirectory()) {
throw new Error(`Source ${uri} is a directory. Point content_uri at a file, or use a collection glob.`);
}
const content = await readFile(path, "utf8");
return {
content,
contentType: guessContentType(path),
digest: sha256Uri(content),
retrievedAt: stats.mtime.toISOString(),
// Local files are inside the trust boundary — they are reviewed the same
// way code is, through the repository they live in.
trust: "trusted"
};
}
};
export function guessContentType(path: string): string {
const lower = path.toLowerCase();
if (lower.endsWith(".json")) return "application/json";
if (lower.endsWith(".yaml") || lower.endsWith(".yml")) return "application/yaml";
if (lower.endsWith(".csv")) return "text/csv";
if (lower.endsWith(".txt")) return "text/plain";
if (lower.endsWith(".html") || lower.endsWith(".htm")) return "text/html";
return "text/markdown";
}

View file

@ -0,0 +1,173 @@
/**
* `git://` adapter — read context out of a git revision.
*
* The primary form addresses the repository the manifest already lives in:
*
* git://HEAD/context/mission.md
* git://v1.2.0/context/policies/refunds.md
* git://9f2c1ab/context/policies/refunds.md
*
* That is what makes "reconstruct the context available at a previous time"
* work offline with no server: the history is already in the repository. The
* remote form `git://github.com/acme/context/policies/refunds.md` is understood
* for provenance, but reading it requires an explicit local mapping, because
* silently cloning a URL found in a context file would be a remote fetch the
* operator never asked for:
*
* adapters:
* git:
* repos:
* github.com/acme/context: ../acme-context
*/
import { execFile } from "node:child_process";
import { promisify } from "node:util";
import type { Adapter, AdapterContext, AdapterResult } from "../types.js";
import { sha256Uri } from "../digest.js";
import { guessContentType, resolveInside } from "./file.js";
const run = promisify(execFile);
const REV_PATTERN = /^[A-Za-z0-9._/-]+$/;
/** ASCII unit separator — safe inside a git --format because it can't appear in a subject line. */
const FIELD_SEP = "\u001F";
export interface GitTarget {
rev: string;
path: string;
/** Set when the URI named a remote repository rather than the local one. */
repo?: string;
}
/**
* Parse a `git://` URI.
*
* A leading segment that looks like a hostname is read as a remote repository;
* anything else is a revision in the local repository.
*/
export function parseGitUri(uri: string): GitTarget {
const withoutScheme = uri.replace(/^git:\/\//, "");
const segments = withoutScheme.split("/").filter((segment) => segment.length > 0);
if (segments.length < 2) {
throw new Error(`Malformed git URI "${uri}". Expected git://<rev>/<path> or git://<host>/<owner>/<repo>/<path>.`);
}
const first = segments[0]!;
if (first.includes(".") && !first.startsWith(".") && segments.length >= 4) {
return { rev: "HEAD", path: segments.slice(3).join("/"), repo: segments.slice(0, 3).join("/") };
}
return { rev: first, path: segments.slice(1).join("/") };
}
export const gitAdapter: Adapter = {
name: "git",
schemes: ["git"],
// Reads the local object database, so it still works offline.
remote: false,
async load(uri: string, ctx: AdapterContext): Promise<AdapterResult> {
const target = parseGitUri(uri);
let cwd = ctx.dir;
if (target.repo) {
const mapping = (ctx.config.repos as Record<string, string> | undefined)?.[target.repo];
if (!mapping) {
throw new Error(
`No local checkout configured for ${target.repo}. Add it under adapters.git.repos in opencontext.yaml, ` +
`e.g. "${target.repo}: ../acme-context". OpenContext will not clone a repository on its own.`
);
}
cwd = resolveInside(ctx.dir, mapping);
}
if (!REV_PATTERN.test(target.rev)) {
throw new Error(`Refusing to use "${target.rev}" as a git revision: it contains unexpected characters.`);
}
if (target.path.split("/").includes("..")) {
throw new Error(`Refusing to read "${target.path}" from git: paths must not traverse upward.`);
}
let stdout: string;
try {
// execFile, never a shell: the rev and path come from a context file.
const result = await run("git", ["show", `${target.rev}:${target.path}`], {
cwd,
maxBuffer: 5 * 1024 * 1024,
windowsHide: true
});
stdout = result.stdout;
} catch (error) {
const stderr = (error as { stderr?: string }).stderr?.trim();
throw new Error(`git show ${target.rev}:${target.path} failed${stderr ? `: ${stderr}` : ""}`);
}
return {
content: stdout,
contentType: guessContentType(target.path),
digest: sha256Uri(stdout),
retrievedAt: new Date().toISOString(),
// Committed history is inside the trust boundary of the local repository;
// a mapped external checkout is only as trusted as whoever wrote it.
trust: target.repo ? "verified" : "trusted"
};
}
};
/** Whether `git` is usable in `dir`. Used to degrade `history` gracefully. */
export async function isGitAvailable(dir: string): Promise<boolean> {
try {
await run("git", ["rev-parse", "--git-dir"], { cwd: dir, windowsHide: true });
return true;
} catch {
return false;
}
}
export interface GitCommit {
commit: string;
date: string;
author: string;
subject: string;
}
/**
* Commits that touched `path`, newest first.
*
* Returns an empty list rather than throwing when git is unavailable or the
* path was never committed, so `history` degrades to the versions declared in
* the context objects themselves — which is the offline-valid answer.
*/
export async function gitLog(dir: string, path: string, limit = 50): Promise<GitCommit[]> {
try {
const { stdout } = await run(
"git",
["log", `--max-count=${limit}`, `--format=%H${FIELD_SEP}%aI${FIELD_SEP}%an${FIELD_SEP}%s`, "--", path],
{ cwd: dir, windowsHide: true, maxBuffer: 4 * 1024 * 1024 }
);
return stdout
.split("\n")
.filter((line) => line.trim().length > 0)
.map((line) => {
const [commit = "", date = "", author = "", subject = ""] = line.split(FIELD_SEP);
return { commit, date, author, subject };
});
} catch {
return [];
}
}
/** Read a path at a revision. Returns null when it did not exist there. */
export async function gitShow(dir: string, rev: string, path: string): Promise<string | null> {
if (!REV_PATTERN.test(rev)) return null;
try {
const { stdout } = await run("git", ["show", `${rev}:${path}`], {
cwd: dir,
windowsHide: true,
maxBuffer: 5 * 1024 * 1024
});
return stdout;
} catch {
return null;
}
}

View file

@ -0,0 +1,79 @@
/**
* `http://` and `https://` adapter.
*
* Remote content is data, never instruction. Whatever comes back is marked
* untrusted unless the object declares a digest that matches, in which case it
* is `verified` — integrity is a claim about bytes, not about intent, so even a
* digest-matched document never becomes `trusted`.
*/
import type { Adapter, AdapterContext, AdapterResult } from "../types.js";
import { sha256Uri } from "../digest.js";
export class OfflineError extends Error {
constructor(uri: string) {
super(`Cannot fetch ${uri} in --offline mode. Run without --offline, or inline the content.`);
this.name = "OfflineError";
}
}
const DEFAULT_TIMEOUT_MS = 10_000;
const MAX_BYTES = 5 * 1024 * 1024;
export const httpAdapter: Adapter = {
name: "http",
schemes: ["http", "https"],
remote: true,
async load(uri: string, ctx: AdapterContext): Promise<AdapterResult> {
if (ctx.offline) throw new OfflineError(uri);
const url = new URL(uri);
if (url.protocol === "http:" && ctx.config.allow_insecure !== true) {
throw new Error(
`Refusing to fetch ${uri} over plaintext http. Use https, or set adapters.http.allow_insecure: true ` +
`if this is a trusted network you control.`
);
}
const timeoutMs = ctx.timeoutMs ?? (ctx.config.timeout_ms as number | undefined) ?? DEFAULT_TIMEOUT_MS;
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), timeoutMs);
let response: Response;
try {
response = await fetch(url, {
signal: controller.signal,
// Redirects can move a request to a host the author never named, so the
// final URL is reported back rather than followed silently.
redirect: "follow",
headers: { accept: "text/markdown, text/plain, application/json;q=0.9, */*;q=0.8" }
});
} catch (error) {
throw new Error(`Failed to fetch ${uri}: ${(error as Error).message}`);
} finally {
clearTimeout(timer);
}
if (!response.ok) {
throw new Error(`Failed to fetch ${uri}: HTTP ${response.status} ${response.statusText}`);
}
const declaredLength = Number(response.headers.get("content-length") ?? "0");
if (declaredLength > MAX_BYTES) {
throw new Error(`Refusing to load ${uri}: ${declaredLength} bytes exceeds the ${MAX_BYTES} byte limit.`);
}
const content = await response.text();
if (content.length > MAX_BYTES) {
throw new Error(`Refusing to load ${uri}: response exceeds the ${MAX_BYTES} byte limit.`);
}
return {
content,
contentType: (response.headers.get("content-type") ?? "text/plain").split(";")[0]!.trim(),
digest: sha256Uri(content),
retrievedAt: new Date().toISOString(),
trust: (ctx.config.trust as AdapterResult["trust"]) ?? "untrusted"
};
}
};

View file

@ -0,0 +1,128 @@
/**
* The adapter registry.
*
* Two rules matter here, and both are normative:
*
* 1. An unknown scheme fails loudly. Resolving `crm://pricing/enterprise` to
* empty content would hand an agent a bundle that silently omits the
* pricing it was asked about — worse than an error, because nothing looks
* wrong.
* 2. Adapters return data. Nothing an adapter fetches is ever executed, and
* nothing it returns can change resolver policy.
*/
import type { Adapter, AdapterConfig, AdapterContext, AdapterResult, Manifest, Trust } from "../types.js";
import { fileAdapter } from "./file.js";
import { httpAdapter } from "./http.js";
import { gitAdapter } from "./git.js";
import { sqliteAdapter } from "./sqlite.js";
export { fileAdapter, resolveInside, PathTraversalError, guessContentType } from "./file.js";
export { httpAdapter, OfflineError } from "./http.js";
export { gitAdapter, parseGitUri, gitLog, gitShow, isGitAvailable, type GitCommit } from "./git.js";
export { sqliteAdapter, parseSqliteUri } from "./sqlite.js";
export class UnknownSchemeError extends Error {
readonly scheme: string;
readonly uri: string;
constructor(scheme: string, uri: string, known: string[]) {
super(
`No adapter is installed for "${scheme}://" (from ${uri}). ` +
`Known schemes: ${known.join(", ")}. Register one with registerAdapter(), or remove the reference.`
);
this.name = "UnknownSchemeError";
this.scheme = scheme;
this.uri = uri;
}
}
export class AdapterRegistry {
private readonly adapters = new Map<string, Adapter>();
constructor(adapters: Adapter[] = defaultAdapters()) {
for (const adapter of adapters) this.register(adapter);
}
register(adapter: Adapter): this {
for (const scheme of adapter.schemes) {
this.adapters.set(scheme.toLowerCase(), adapter);
}
return this;
}
get(scheme: string): Adapter | undefined {
return this.adapters.get(scheme.toLowerCase());
}
has(scheme: string): boolean {
return this.adapters.has(scheme.toLowerCase());
}
schemes(): string[] {
return [...this.adapters.keys()].sort();
}
/**
* Load a URI.
*
* A bare path with no scheme is a file path — that is the common case in a
* local repository and does not deserve ceremony.
*/
async load(uri: string, options: LoadOptions): Promise<AdapterResult> {
const scheme = schemeOf(uri);
if (!scheme) {
return fileAdapter.load(uri, contextFor("file", options));
}
const adapter = this.get(scheme);
if (!adapter) {
throw new UnknownSchemeError(scheme, uri, this.schemes());
}
const config = options.manifest?.adapters?.[scheme] ?? {};
if (config.enabled === false) {
throw new Error(`The "${scheme}://" adapter is disabled in opencontext.yaml (adapters.${scheme}.enabled: false).`);
}
const ctx = contextFor(scheme, options);
const result = await adapter.load(uri, ctx);
// A configured trust level is a deliberate operator statement and wins over
// the adapter's own guess — but it can only ever be applied here, never by
// the content itself.
const configured = config.trust as Trust | undefined;
return configured ? { ...result, trust: configured } : result;
}
}
export interface LoadOptions {
dir: string;
manifest?: Manifest;
offline?: boolean;
}
function contextFor(scheme: string, options: LoadOptions): AdapterContext {
const config: AdapterConfig = options.manifest?.adapters?.[scheme] ?? {};
return {
dir: options.dir,
offline: options.offline ?? false,
config,
timeoutMs: config.timeout_ms
};
}
/** The scheme of a URI, or undefined for a bare path. Windows drive letters are not schemes. */
export function schemeOf(uri: string): string | undefined {
const match = /^([a-zA-Z][a-zA-Z0-9+.-]*):/.exec(uri);
if (!match) return undefined;
const scheme = match[1]!.toLowerCase();
if (scheme.length === 1) return undefined;
return scheme;
}
/** Adapters every conforming implementation ships: file and http are required, git and sqlite are recommended. */
export function defaultAdapters(): Adapter[] {
return [fileAdapter, httpAdapter, gitAdapter, sqliteAdapter];
}

View file

@ -0,0 +1,141 @@
/**
* `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;
}
}