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,153 @@
/**
* Reading context documents off disk.
*
* Three shapes are supported and they mean the same thing:
* - Markdown with YAML front matter metadata in the fence, prose as content
* - YAML the whole document is the object
* - JSON the whole document is the object
*
* A Markdown file with no front matter is still a valid context object: it
* becomes content with an id derived from its path. That is what keeps
* OpenContext adoptable point it at an existing `docs/` folder and it works,
* then add metadata where governance actually matters.
*/
import { parse as parseYaml } from "yaml";
import type { ContextObject } from "./types.js";
const FRONT_MATTER = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/;
export interface ParsedDocument {
/** The object as authored. Never has defaults applied. */
object: ContextObject;
/** 1-indexed line the front matter / document body starts on. */
bodyLine: number;
/** Keys present in the source, for reporting unknown-field errors precisely. */
declaredKeys: string[];
format: "markdown" | "yaml" | "json";
}
export class ContextParseError extends Error {
readonly file: string;
readonly line?: number;
constructor(message: string, file: string, line?: number) {
super(message);
this.name = "ContextParseError";
this.file = file;
this.line = line;
}
}
export function parseContextDocument(text: string, file: string): ParsedDocument {
const lower = file.toLowerCase();
if (lower.endsWith(".json")) return parseJsonDocument(text, file);
if (lower.endsWith(".yaml") || lower.endsWith(".yml")) return parseYamlDocument(text, file);
return parseMarkdownDocument(text, file);
}
function parseJsonDocument(text: string, file: string): ParsedDocument {
let data: unknown;
try {
data = JSON.parse(text);
} catch (error) {
throw new ContextParseError(`Invalid JSON: ${(error as Error).message}`, file);
}
assertObject(data, file);
return { object: data as ContextObject, bodyLine: 1, declaredKeys: Object.keys(data as object), format: "json" };
}
function parseYamlDocument(text: string, file: string): ParsedDocument {
let data: unknown;
try {
data = parseYaml(text);
} catch (error) {
throw new ContextParseError(`Invalid YAML: ${(error as Error).message}`, file, yamlErrorLine(error));
}
if (data === null || data === undefined) {
throw new ContextParseError("Document is empty.", file, 1);
}
assertObject(data, file);
return { object: data as ContextObject, bodyLine: 1, declaredKeys: Object.keys(data as object), format: "yaml" };
}
function parseMarkdownDocument(text: string, file: string): ParsedDocument {
const match = FRONT_MATTER.exec(text);
if (!match) {
// No front matter: the whole file is content. Still a valid object once the
// loader supplies an id and type from the collection it came from.
return {
object: { content: stripBom(text) } as unknown as ContextObject,
bodyLine: 1,
declaredKeys: [],
format: "markdown"
};
}
let meta: unknown;
try {
meta = parseYaml(match[1]!);
} catch (error) {
throw new ContextParseError(
`Invalid YAML front matter: ${(error as Error).message}`,
file,
1 + (yamlErrorLine(error) ?? 0)
);
}
if (meta === null || meta === undefined) meta = {};
assertObject(meta, file);
const body = text.slice(match[0].length);
const bodyLine = countLines(match[0]) + 1;
// id and type are supplied by the loader when the author omits them, so the
// parsed front matter is not yet a complete ContextObject.
const object = { ...(meta as Record<string, unknown>) } as unknown as ContextObject;
// Front matter may carry `content` explicitly; otherwise the prose is it.
// An empty body must not clobber a declared content field.
if (object.content === undefined && body.trim().length > 0) {
object.content = body.replace(/^\r?\n/, "");
}
return { object, bodyLine, declaredKeys: Object.keys(meta as object), format: "markdown" };
}
function assertObject(data: unknown, file: string): void {
if (typeof data !== "object" || data === null || Array.isArray(data)) {
throw new ContextParseError(
`Expected a context object (a mapping), got ${Array.isArray(data) ? "an array" : typeof data}.`,
file,
1
);
}
}
function stripBom(text: string): string {
return text.charCodeAt(0) === 0xfeff ? text.slice(1) : text;
}
function countLines(text: string): number {
let count = 0;
for (const char of text) if (char === "\n") count += 1;
return count;
}
function yamlErrorLine(error: unknown): number | undefined {
const pos = (error as { linePos?: Array<{ line: number }> }).linePos;
return pos?.[0]?.line;
}
/**
* Best-effort 1-indexed line of a top-level key, so diagnostics can point at the
* offending field rather than the file. Front matter is scanned from line 2,
* since line 1 is the opening fence.
*/
export function findFieldLine(text: string, field: string): number | undefined {
const escaped = field.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
const pattern = new RegExp(`^\\s*"?${escaped}"?\\s*:`, "m");
const match = pattern.exec(text);
if (!match) return undefined;
return countLines(text.slice(0, match.index)) + 1;
}