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

316 lines
12 KiB
TypeScript
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* Supersession, authority precedence, and conflicts.
*
* The rule this module exists to enforce: the resolver never quietly guesses.
* When two canonical objects contradict each other, both survive into the
* bundle's warnings and the run fails a strict validate — because the failure
* mode of silently picking one is an agent confidently acting on a policy that
* half the organization believes was replaced.
*/
import type {
Authority,
ContextObject,
Diagnostic,
LoadedObject,
Manifest,
TieBreaker
} from "./types.js";
import { parseRef } from "./ids.js";
import { parseTimestamp } from "./time.js";
import { precedenceOf, tieBreakersOf } from "./manifest.js";
export interface SupersessionResult {
/** Ids of objects replaced by something else. */
superseded: Set<string>;
/** Keyed by superseded id -> the id that replaced it, for `--explain`. */
supersededBy: Map<string, string>;
diagnostics: Diagnostic[];
}
/**
* Work out what has been replaced.
*
* Both directions are honoured: `supersedes` on the newer object, and
* `superseded_by` on the older one. A reference to something that does not
* exist is an error rather than a no-op, because a broken chain silently
* resurrects retired policy.
*/
export function resolveSupersession(objects: LoadedObject[], byId: Map<string, LoadedObject[]>): SupersessionResult {
const superseded = new Set<string>();
const supersededBy = new Map<string, string>();
const diagnostics: Diagnostic[] = [];
const markSuperseded = (targetId: string, replacementId: string): void => {
superseded.add(targetId);
if (!supersededBy.has(targetId)) supersededBy.set(targetId, replacementId);
};
for (const entry of objects) {
const object = entry.object;
for (const ref of object.supersedes ?? []) {
const parsed = parseRef(ref);
if (!parsed) {
diagnostics.push({
code: "broken-supersession",
severity: "error",
message: `${object.id} supersedes "${ref}", which is not a valid object reference.`,
id: object.id,
file: entry.file,
field: "supersedes",
remediation: "Use an id, or id@version."
});
continue;
}
if (parsed.id === object.id && parsed.version === undefined) {
diagnostics.push({
code: "supersession-cycle",
severity: "error",
message: `${object.id} supersedes itself. Pin the version it replaces, e.g. ${object.id}@${(object.version ?? 2) - 1}.`,
id: object.id,
file: entry.file,
field: "supersedes"
});
continue;
}
const targets = byId.get(parsed.id);
if (!targets || targets.length === 0) {
diagnostics.push({
code: "broken-supersession",
severity: "error",
message: `${object.id} supersedes "${ref}", which does not exist.`,
id: object.id,
ids: [object.id, parsed.id],
file: entry.file,
field: "supersedes",
remediation: `Keep the superseded object in the repository — supersession preserves history, deletion destroys it.`
});
continue;
}
for (const target of targets) {
if (target === entry) continue;
if (parsed.version !== undefined && (target.object.version ?? 1) !== parsed.version) continue;
markSuperseded(keyOf(target.object), object.id);
}
}
if (object.superseded_by) {
const parsed = parseRef(object.superseded_by);
if (!parsed || !byId.has(parsed.id)) {
diagnostics.push({
code: "broken-supersession",
severity: "error",
message: `${object.id} declares superseded_by "${object.superseded_by}", which does not exist.`,
id: object.id,
file: entry.file,
field: "superseded_by"
});
} else {
markSuperseded(keyOf(object), parsed.id);
}
}
}
// Deliberately *not* done here: implicitly superseding older versions of the
// same id because a higher-numbered one exists.
//
// It would be convenient, and it would be the resolver quietly guessing. Two
// active canonical versions of one policy is a real governance failure — a
// rewrite landed without anyone declaring what it replaced — and inferring
// the supersession would hide it, making `multiple-active-versions` and
// `duplicate-canonical` impossible to ever detect. Instead resolution still
// returns one winner (the version tie breaker), the loser is reported as
// outranked, and validation raises the missing link. Supersession is
// something an author states, not something a tool assumes.
return { superseded, supersededBy, diagnostics };
}
/**
* The key a superseded object is tracked by.
*
* Always `id@version`, and an object that declares no version is version 1 —
* the same assumption the version tie breaker makes. Emitting a bare id here
* would be ambiguous with the "supersede every version" marker that
* `isSuperseded` looks for, so superseding an unversioned object would also
* hide every later version of it.
*/
export function keyOf(object: ContextObject): string {
return `${object.id}@${object.version ?? 1}`;
}
/**
* True when this specific version has been superseded, or when every version of
* the id has been (which a bare id in the set signifies).
*/
export function isSuperseded(object: ContextObject, superseded: ReadonlySet<string>): boolean {
return superseded.has(keyOf(object)) || superseded.has(object.id);
}
export function authorityRank(authority: Authority | undefined, precedence: Authority[]): number {
const index = precedence.indexOf(authority ?? "reference");
// Anything unranked sorts last rather than first: an unknown level must never
// outrank a known one.
return index === -1 ? precedence.length : index;
}
/**
* Order two candidates: authority first, then the configured tie breakers.
*
* Returns a negative number when `a` wins. Ordering is total because `id` is
* always appended as the final tie breaker, so resolution is reproducible.
*/
export function compareCandidates(a: ContextObject, b: ContextObject, manifest: Manifest): number {
const precedence = precedenceOf(manifest);
const byAuthority = authorityRank(a.authority, precedence) - authorityRank(b.authority, precedence);
if (byAuthority !== 0) return byAuthority;
for (const breaker of tieBreakersOf(manifest)) {
const result = compareBy(breaker, a, b);
if (result !== 0) return result;
}
return 0;
}
function compareBy(breaker: TieBreaker, a: ContextObject, b: ContextObject): number {
switch (breaker) {
case "version":
return (b.version ?? 1) - (a.version ?? 1);
case "updated":
return timeOf(b.updated) - timeOf(a.updated);
case "created":
return timeOf(b.created) - timeOf(a.created);
case "confidence":
return (b.confidence ?? 1) - (a.confidence ?? 1);
case "id":
return a.id < b.id ? -1 : a.id > b.id ? 1 : 0;
default:
return 0;
}
}
function timeOf(value: string | undefined): number {
return parseTimestamp(value)?.getTime() ?? 0;
}
export interface ConflictResult {
diagnostics: Diagnostic[];
/** Ids involved in a conflict that authority could not settle. */
unresolved: Set<string>;
}
/**
* Detect conflicts among active objects.
*
* Three kinds are reported:
* - a declared `conflicts_with` between equal-authority objects, which the
* resolver cannot settle and must surface (`conflict-ambiguous`);
* - a declared conflict that authority *does* settle, still reported so the
* losing side is visible (`conflict-declared`);
* - more than one active canonical object for the same id, which means two
* files both claim to be the organization's single source of truth
* (`duplicate-canonical`).
*/
export function detectConflicts(
active: LoadedObject[],
manifest: Manifest
): ConflictResult {
const diagnostics: Diagnostic[] = [];
const unresolved = new Set<string>();
const byId = new Map<string, LoadedObject[]>();
for (const entry of active) {
const list = byId.get(entry.object.id);
if (list) list.push(entry);
else byId.set(entry.object.id, [entry]);
}
for (const [id, entries] of byId) {
if (entries.length < 2) continue;
const canonical = entries.filter((entry) => entry.object.authority === "canonical");
if (canonical.length > 1) {
diagnostics.push({
code: "duplicate-canonical",
severity: "error",
message: `${canonical.length} active canonical objects share the id "${id}" (${canonical
.map((entry) => entry.file ?? "inline")
.join(", ")}). Canonical means exactly one source of truth.`,
id,
ids: canonical.map((entry) => entry.file ?? id),
file: canonical[0]?.file,
remediation: "Supersede the older one, or lower its authority to reference."
});
unresolved.add(id);
}
diagnostics.push({
code: "multiple-active-versions",
severity: canonical.length > 1 ? "error" : "warning",
message: `${entries.length} active versions of "${id}" (versions ${entries
.map((entry) => entry.object.version ?? 1)
.join(", ")}). Default resolution will use one and exclude the rest.`,
id,
file: entries[0]?.file,
remediation: `Add supersedes: [${id}@${entries[0]?.object.version ?? 1}] to the newer object.`
});
}
const activeIds = new Set(active.map((entry) => entry.object.id));
// Deduplicate by the unordered pair, not by id ordering. A conflict is very
// often declared on one side only, so skipping whenever the declaring id
// sorts later would silently drop it — a canonical conflict disappearing on
// alphabetical luck is exactly the failure this check exists to prevent.
const reportedPairs = new Set<string>();
for (const entry of active) {
for (const ref of entry.object.conflicts_with ?? []) {
const parsed = parseRef(ref);
if (!parsed) continue;
if (!activeIds.has(parsed.id)) continue;
if (parsed.id === entry.object.id) continue;
const pairKey = [entry.object.id, parsed.id].sort().join("");
if (reportedPairs.has(pairKey)) continue;
reportedPairs.add(pairKey);
const other = active.find((candidate) => candidate.object.id === parsed.id);
if (!other) continue;
const order = compareCandidates(entry.object, other.object, manifest);
const sameAuthority = entry.object.authority === other.object.authority;
if (sameAuthority) {
diagnostics.push({
code: "conflict-ambiguous",
severity: "error",
message: `${entry.object.id} and ${other.object.id} declare a conflict and both are ${entry.object.authority}. Authority cannot settle it.`,
id: entry.object.id,
ids: [entry.object.id, other.object.id],
file: entry.file,
remediation: "Raise one object's authority, supersede one of them, or reconcile the two."
});
unresolved.add(entry.object.id);
unresolved.add(other.object.id);
} else {
const winner = order < 0 ? entry.object : other.object;
const loser = order < 0 ? other.object : entry.object;
diagnostics.push({
code: "conflict-declared",
severity: "warning",
message: `${entry.object.id} conflicts with ${other.object.id}; ${winner.id} (${winner.authority}) outranks ${loser.id} (${loser.authority}).`,
id: entry.object.id,
ids: [entry.object.id, other.object.id],
file: entry.file,
remediation: `Supersede ${loser.id} if it is genuinely obsolete.`
});
}
}
}
return { diagnostics, unresolved };
}