logicsrc/packages/opencontext/src/ids.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

140 lines
5.3 KiB
TypeScript

/**
* Object ids, references, and the pattern language used by scopes and
* permissions.
*
* Everything here is exact-match-first: a wildcard only ever matches whole
* dotted segments, so `products.*` can never reach `products-internal`. That
* matters because these functions decide what an agent is allowed to read.
*/
const ID_PATTERN = /^[a-z0-9][a-z0-9_-]*(\.[a-z0-9][a-z0-9_-]*)*$/;
const REF_PATTERN = /^([a-z0-9][a-z0-9_-]*(?:\.[a-z0-9][a-z0-9_-]*)*)(?:@(\d+))?$/;
const SCOPE_PATTERN = /^([a-z0-9][a-z0-9_-]*|\*)(\.([a-z0-9][a-z0-9_-]*|\*))*$/;
export function isValidId(id: string): boolean {
return ID_PATTERN.test(id);
}
export function isValidScopePattern(pattern: string): boolean {
return SCOPE_PATTERN.test(pattern);
}
export interface ObjectRef {
id: string;
version?: number;
}
/** Parse `policy.refunds` or `policy.refunds@2`. Returns null when malformed. */
export function parseRef(ref: string): ObjectRef | null {
const match = REF_PATTERN.exec(ref.trim());
if (!match) return null;
const version = match[2] === undefined ? undefined : Number.parseInt(match[2], 10);
return version === undefined ? { id: match[1]! } : { id: match[1]!, version };
}
export function formatRef(ref: ObjectRef): string {
return ref.version === undefined ? ref.id : `${ref.id}@${ref.version}`;
}
/**
* Match an id against one scope pattern.
*
* Wildcards are always whole segments, never substrings, so a pattern can never
* reach a sibling id that merely starts with the same characters —
* `products.*` covers `products.enterprise` and never `products-internal`.
*
* `*` everything
* `policies.support.*` a trailing wildcard: the prefix itself, plus any
* depth beneath it (`policies.support`,
* `policies.support.refund`, and deeper)
* `customers.*.churn-risk` an interior wildcard: exactly one segment, so it
* matches `customers.acme.churn-risk` but not
* `customers.acme.eu.churn-risk`
*
* The asymmetry is deliberate. A trailing wildcard is how people express "this
* subtree", and an interior one is how they express "this field, whichever
* record it belongs to" — collapsing them into one rule would make the second
* silently grant the first.
*/
export function matchPattern(pattern: string, id: string): boolean {
if (pattern === "*") return true;
const idSegments = id.split(".");
if (pattern.endsWith(".*")) {
const prefix = pattern.slice(0, -2).split(".");
if (idSegments.length < prefix.length) return false;
return prefix.every((segment, index) => segmentMatches(segment, idSegments[index]!));
}
const patternSegments = pattern.split(".");
if (patternSegments.length !== idSegments.length) return false;
return patternSegments.every((segment, index) => segmentMatches(segment, idSegments[index]!));
}
function segmentMatches(patternSegment: string, idSegment: string): boolean {
return patternSegment === "*" || patternSegment === idSegment;
}
export function matchesAny(patterns: readonly string[] | undefined, id: string): boolean {
if (!patterns || patterns.length === 0) return false;
return patterns.some((pattern) => matchPattern(pattern, id));
}
/** The pattern that matched, for reporting *why* something was excluded. */
export function firstMatch(patterns: readonly string[] | undefined, id: string): string | undefined {
return patterns?.find((pattern) => matchPattern(pattern, id));
}
/**
* Match a principal list (an object's `permissions.read`, `write`, or `deny`)
* against the consumer's identity and roles. Supports `*` and a trailing `.*`.
*/
export function matchesPrincipal(list: readonly string[] | undefined, principals: readonly string[]): boolean {
if (!list || list.length === 0) return false;
return list.some((entry) => {
if (entry === "*") return true;
if (entry.endsWith(".*")) {
const prefix = entry.slice(0, -2);
return principals.some((p) => p === prefix || p.startsWith(`${prefix}.`));
}
return principals.includes(entry);
});
}
/**
* Derive an id from a file path inside a collection, used when a document does
* not declare its own.
*
* `policies` + `support/refund.md` becomes `policies.support.refund`. Segments
* are lowercased and non-id characters collapse to dashes so a real-world
* filename such as `Refund Policy (v2).md` still produces a usable id.
*/
export function deriveId(collectionKey: string, relativePath: string): string {
const withoutExt = relativePath.replace(/\.(md|markdown|ya?ml|json)$/i, "");
const segments = withoutExt
.split(/[/\\]/)
.filter((segment) => segment.length > 0 && segment !== ".")
.map(slugSegment)
.filter((segment) => segment.length > 0);
// `policies/index.md` is the collection root, not `policies.index`.
if (segments.length > 0 && (segments.at(-1) === "index" || segments.at(-1) === "readme")) {
segments.pop();
}
return [collectionKey, ...segments].join(".");
}
function slugSegment(segment: string): string {
return segment
.toLowerCase()
.replace(/[^a-z0-9_-]+/g, "-")
.replace(/^-+|-+$/g, "")
.replace(/-{2,}/g, "-");
}
/** Sort ids the way bundles and reports order them: stable and locale-independent. */
export function compareIds(a: string, b: string): number {
return a < b ? -1 : a > b ? 1 : 0;
}