mirror of
https://github.com/profullstack/logicsrc.git
synced 2026-10-02 04:43:58 +00:00
* 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>
311 lines
11 KiB
TypeScript
311 lines
11 KiB
TypeScript
/**
|
|
* OpenContext — the reference implementation.
|
|
*
|
|
* ```ts
|
|
* import { OpenContext } from "@logicsrc/opencontext";
|
|
*
|
|
* const oc = await OpenContext.load("./opencontext.yaml");
|
|
* const result = await oc.resolve({ agent: "support-agent", task: "Handle ACME refund" });
|
|
* console.log(result.bundle);
|
|
* ```
|
|
*
|
|
* The resolver core is importable without the CLI — every function the class
|
|
* wraps is also exported directly, so an agent runtime can embed resolution
|
|
* without taking a dependency on argument parsing or terminal output.
|
|
*/
|
|
|
|
import type {
|
|
Adapter,
|
|
ContextBundle,
|
|
ContextObject,
|
|
ContextStore,
|
|
Diagnostic,
|
|
DiagnosticReport,
|
|
EffectiveScope,
|
|
LoadedObject,
|
|
Manifest,
|
|
ResolveOptions
|
|
} from "./types.js";
|
|
import { AdapterRegistry } from "./adapters/index.js";
|
|
import { loadStore, type LoadStoreOptions } from "./store.js";
|
|
import { loadManifest } from "./manifest.js";
|
|
import { resolve as resolveContext, type ResolveResult } from "./resolve.js";
|
|
import { validateStore, type ValidateOptions } from "./validate.js";
|
|
import { doctor as runDoctor, type DoctorOptions } from "./doctor.js";
|
|
import { search as runSearch, type SearchHit, type SearchOptions } from "./search.js";
|
|
import { history as objectHistory, diffObjects, type ObjectDiff, type ObjectHistory } from "./history.js";
|
|
import { buildGraph, type ContextGraph, type GraphOptions } from "./graph.js";
|
|
import { authorize, resolveScope, unrestrictedScope, type ScopeRequest } from "./permissions.js";
|
|
import { addObject, supersedeObject, type SupersedeOptions, type WriteOptions, type WriteResult } from "./write.js";
|
|
import { isSuperseded, resolveSupersession } from "./authority.js";
|
|
import { computeLifecycle } from "./lifecycle.js";
|
|
import { resolveAsOf } from "./time.js";
|
|
import { parseRef } from "./ids.js";
|
|
|
|
export interface OpenContextOptions extends LoadStoreOptions {
|
|
adapters?: Adapter[];
|
|
}
|
|
|
|
export interface ListOptions {
|
|
scope?: EffectiveScope;
|
|
type?: string;
|
|
layer?: string;
|
|
authority?: string;
|
|
tag?: string;
|
|
owner?: string;
|
|
includeSuperseded?: boolean;
|
|
at?: string | Date;
|
|
}
|
|
|
|
export interface ListEntry {
|
|
id: string;
|
|
type: string;
|
|
title?: string;
|
|
layer?: string;
|
|
authority?: string;
|
|
owner?: string;
|
|
version?: number;
|
|
lifecycle: string;
|
|
classification?: string;
|
|
file?: string;
|
|
}
|
|
|
|
export class OpenContext {
|
|
readonly store: ContextStore;
|
|
readonly registry: AdapterRegistry;
|
|
|
|
private constructor(store: ContextStore, registry: AdapterRegistry) {
|
|
this.store = store;
|
|
this.registry = registry;
|
|
}
|
|
|
|
/** Load a manifest and every object it declares. Discovers upward when given a directory. */
|
|
static async load(pathOrDir: string = process.cwd(), options: OpenContextOptions = {}): Promise<OpenContext> {
|
|
const registry = options.registry ?? new AdapterRegistry();
|
|
for (const adapter of options.adapters ?? []) registry.register(adapter);
|
|
const store = await loadStore(pathOrDir, { ...options, registry });
|
|
return new OpenContext(store, registry);
|
|
}
|
|
|
|
get manifest(): Manifest {
|
|
return this.store.manifest;
|
|
}
|
|
|
|
get dir(): string {
|
|
return this.store.dir;
|
|
}
|
|
|
|
/** Register an adapter for additional URI schemes, then reload to pick up its content. */
|
|
registerAdapter(adapter: Adapter): this {
|
|
this.registry.register(adapter);
|
|
return this;
|
|
}
|
|
|
|
/** Re-read everything from disk. */
|
|
async reload(options: LoadStoreOptions = {}): Promise<OpenContext> {
|
|
const store = await loadStore(this.store.manifestPath, { ...options, registry: this.registry });
|
|
return new OpenContext(store, this.registry);
|
|
}
|
|
|
|
validate(options: ValidateOptions = {}): Diagnostic[] {
|
|
return validateStore(this.store, options);
|
|
}
|
|
|
|
doctor(options: DoctorOptions = {}): DiagnosticReport {
|
|
return runDoctor(this.store, options);
|
|
}
|
|
|
|
resolve(options: ResolveOptions = {}): ResolveResult {
|
|
return resolveContext(this.store, options);
|
|
}
|
|
|
|
/** Just the bundle, for callers that do not need the exclusion detail. */
|
|
bundle(options: ResolveOptions = {}): ContextBundle {
|
|
return resolveContext(this.store, options).bundle;
|
|
}
|
|
|
|
search(query: string, options: SearchOptions = {}): SearchHit[] {
|
|
return runSearch(this.store, query, options);
|
|
}
|
|
|
|
/**
|
|
* Fetch one object by id, or `id@version`.
|
|
*
|
|
* Returns null when the object does not exist *or* when the scope may not
|
|
* read it — an unauthorized read and a missing object are deliberately
|
|
* indistinguishable to the caller, so probing for ids reveals nothing.
|
|
*/
|
|
get(ref: string, options: { scope?: EffectiveScope } = {}): ContextObject | null {
|
|
const parsed = parseRef(ref);
|
|
if (!parsed) return null;
|
|
|
|
const versions = this.store.byId.get(parsed.id);
|
|
if (!versions || versions.length === 0) return null;
|
|
|
|
const entry =
|
|
parsed.version === undefined
|
|
? versions.at(-1)!
|
|
: versions.find((candidate) => (candidate.object.version ?? 1) === parsed.version);
|
|
if (!entry) return null;
|
|
|
|
if (options.scope) {
|
|
const bundle = this.resolve({
|
|
agent: options.scope.consumer.type === "agent" ? options.scope.consumer.id : undefined,
|
|
role: options.scope.consumer.roles,
|
|
requested: [parsed.id]
|
|
}).bundle;
|
|
const found = bundle.objects.find((object) => object.id === parsed.id);
|
|
return (found as ContextObject | undefined) ?? null;
|
|
}
|
|
|
|
return entry.object;
|
|
}
|
|
|
|
list(options: ListOptions = {}): ListEntry[] {
|
|
const asOf = resolveAsOf(options.at);
|
|
const supersession = resolveSupersession(this.store.objects, this.store.byId);
|
|
const scope = options.scope;
|
|
|
|
const entries: ListEntry[] = [];
|
|
|
|
for (const entry of this.store.objects) {
|
|
const object = entry.object;
|
|
|
|
// Listing is a read: an object the scope may not see must not appear even
|
|
// as a row of metadata.
|
|
if (scope && !authorize(object, scope).allowed) continue;
|
|
if (options.type && object.type !== options.type) continue;
|
|
if (options.layer && object.layer !== options.layer) continue;
|
|
if (options.authority && object.authority !== options.authority) continue;
|
|
if (options.owner && object.owner !== options.owner) continue;
|
|
if (options.tag && !object.tags?.includes(options.tag)) continue;
|
|
|
|
const superseded = isSuperseded(object, supersession.superseded);
|
|
if (superseded && !options.includeSuperseded) continue;
|
|
|
|
entries.push({
|
|
id: object.id,
|
|
type: object.type,
|
|
title: object.title,
|
|
layer: object.layer,
|
|
authority: object.authority,
|
|
owner: object.owner,
|
|
version: object.version,
|
|
classification: object.classification,
|
|
lifecycle: computeLifecycle(object, {
|
|
asOf,
|
|
manifest: this.store.manifest,
|
|
superseded: superseded ? new Set([object.id]) : new Set()
|
|
}),
|
|
file: entry.file
|
|
});
|
|
}
|
|
|
|
return entries.sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
|
|
}
|
|
|
|
history(id: string, options: { at?: string | Date } = {}): Promise<ObjectHistory> {
|
|
return objectHistory(this.store, id, options);
|
|
}
|
|
|
|
/** Compare two versions of one object, or two arbitrary object sets. */
|
|
diff(from: string, to: string): ObjectDiff[] {
|
|
const before = this.objectsFor(from);
|
|
const after = this.objectsFor(to);
|
|
return diffObjects(before, after);
|
|
}
|
|
|
|
graph(options: GraphOptions = {}): ContextGraph {
|
|
return buildGraph(this.store, options);
|
|
}
|
|
|
|
scope(request: ScopeRequest): EffectiveScope {
|
|
return request.agent || request.role ? resolveScope(this.store.manifest, request) : unrestrictedScope();
|
|
}
|
|
|
|
add(object: ContextObject, options: WriteOptions = {}): WriteResult {
|
|
return addObject(this.store, object, options);
|
|
}
|
|
|
|
supersede(id: string, options: SupersedeOptions = {}): WriteResult {
|
|
return supersedeObject(this.store, id, options);
|
|
}
|
|
|
|
/** Objects addressed by an id, `id@version`, or `*`. */
|
|
private objectsFor(ref: string): ContextObject[] {
|
|
if (ref === "*") return this.store.objects.map((entry) => entry.object);
|
|
|
|
const parsed = parseRef(ref);
|
|
if (!parsed) return [];
|
|
|
|
const versions = this.store.byId.get(parsed.id) ?? [];
|
|
if (parsed.version === undefined) {
|
|
const latest = versions.at(-1);
|
|
return latest ? [latest.object] : [];
|
|
}
|
|
const match = versions.find((entry) => (entry.object.version ?? 1) === parsed.version);
|
|
return match ? [match.object] : [];
|
|
}
|
|
}
|
|
|
|
export { loadManifest, discoverManifest, SPEC_VERSION, MANIFEST_FILENAMES } from "./manifest.js";
|
|
export { loadStore, loadStoreFrom, normalize, defaultTypeFor } from "./store.js";
|
|
export { resolve, type ResolveResult } from "./resolve.js";
|
|
export { validateStore, sortDiagnostics, hasFailure, type ValidateOptions } from "./validate.js";
|
|
export { doctor, renderHealth, computeScore, DEFAULT_WEIGHTS, type DoctorOptions } from "./doctor.js";
|
|
export { search, type SearchHit, type SearchOptions } from "./search.js";
|
|
export { buildGraph, renderDot, renderGraphText, subgraph, type ContextGraph, type GraphOptions } from "./graph.js";
|
|
export { history, diffObjects, renderDiff, type ObjectDiff, type ObjectHistory } from "./history.js";
|
|
export { renderBundle, renderMarkdown, renderExplanation, type BundleFormat } from "./bundle.js";
|
|
export {
|
|
authorize,
|
|
resolveScope,
|
|
unrestrictedScope,
|
|
canWrite,
|
|
hasPermission,
|
|
redactionsFor,
|
|
classificationRank,
|
|
UnknownConsumerError,
|
|
type ScopeRequest
|
|
} from "./permissions.js";
|
|
export { applyRedactions, parsePath, detectSecrets } from "./redact.js";
|
|
export { computeLifecycle, isResolvable, isApproved, isReviewOverdue } from "./lifecycle.js";
|
|
export {
|
|
resolveSupersession,
|
|
detectConflicts,
|
|
compareCandidates,
|
|
authorityRank,
|
|
isSuperseded,
|
|
keyOf
|
|
} from "./authority.js";
|
|
export { scoreRelevance, tokenize, compareForBundle } from "./relevance.js";
|
|
export { canonicalJson, digestOf, digestBundle, sha256Hex, sha256Uri, bundleIdFromDigest } from "./digest.js";
|
|
export { parseContextDocument, ContextParseError, type ParsedDocument } from "./parse.js";
|
|
export { parseDuration, parseTimestamp, resolveAsOf, formatAge } from "./time.js";
|
|
export { parseRef, formatRef, matchPattern, matchesAny, matchesPrincipal, deriveId, isValidId } from "./ids.js";
|
|
export { expandGlob, globToRegExp, CONTEXT_EXTENSIONS } from "./glob.js";
|
|
export { initProject, scaffoldFiles, slugify, type InitOptions, type InitResult } from "./scaffold.js";
|
|
export { addObject, supersedeObject, renderObject, WriteDeniedError, type WriteResult } from "./write.js";
|
|
export {
|
|
buildEvent,
|
|
recordEvent,
|
|
eventForBundle,
|
|
isAuditEnabled,
|
|
type AuditEvent,
|
|
type AuditEventName
|
|
} from "./audit.js";
|
|
export {
|
|
AdapterRegistry,
|
|
UnknownSchemeError,
|
|
defaultAdapters,
|
|
fileAdapter,
|
|
httpAdapter,
|
|
gitAdapter,
|
|
sqliteAdapter,
|
|
schemeOf,
|
|
resolveInside,
|
|
PathTraversalError,
|
|
OfflineError
|
|
} from "./adapters/index.js";
|
|
export * from "./types.js";
|
|
export type { LoadedObject };
|