mirror of
https://github.com/profullstack/logicsrc.git
synced 2026-10-03 13:17:07 +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>
119 lines
4 KiB
TypeScript
119 lines
4 KiB
TypeScript
/**
|
|
* Lexical search over local context.
|
|
*
|
|
* The one rule that makes this different from grep: **results pass
|
|
* authorization before any content is returned**. A search that leaked titles
|
|
* of restricted documents would defeat the scoping model entirely, so the scope
|
|
* filter runs before scoring, not after.
|
|
*
|
|
* Semantic and vector search are legitimate adapter concerns and are explicitly
|
|
* out of core conformance — requiring an embedding model to find a refund policy
|
|
* would put a model vendor in the critical path of a specification whose point
|
|
* is that vendors are replaceable.
|
|
*/
|
|
|
|
import type { ContextStore, EffectiveScope, LoadedObject } from "./types.js";
|
|
import { authorize, unrestrictedScope } from "./permissions.js";
|
|
import { tokenize } from "./relevance.js";
|
|
|
|
export interface SearchOptions {
|
|
scope?: EffectiveScope;
|
|
limit?: number;
|
|
/** Restrict to these types, e.g. ["policy", "sop"]. */
|
|
types?: string[];
|
|
tags?: string[];
|
|
layer?: string;
|
|
}
|
|
|
|
export interface SearchHit {
|
|
id: string;
|
|
title?: string;
|
|
type: string;
|
|
layer?: string;
|
|
authority?: string;
|
|
score: number;
|
|
/** Which fields matched, so a reader can tell a title hit from a body hit. */
|
|
matched: string[];
|
|
/** A short excerpt around the first content match. Never returned for unauthorized objects. */
|
|
excerpt?: string;
|
|
file?: string;
|
|
}
|
|
|
|
export function search(store: ContextStore, query: string, options: SearchOptions = {}): SearchHit[] {
|
|
const scope = options.scope ?? unrestrictedScope();
|
|
const tokens = tokenize(query);
|
|
const phrase = query.trim().toLowerCase();
|
|
const hits: SearchHit[] = [];
|
|
|
|
for (const entry of store.objects) {
|
|
if (!authorize(entry.object, scope).allowed) continue;
|
|
if (options.types && !options.types.includes(entry.object.type)) continue;
|
|
if (options.layer && entry.object.layer !== options.layer) continue;
|
|
if (options.tags && !options.tags.some((tag) => entry.object.tags?.includes(tag))) continue;
|
|
|
|
const hit = scoreEntry(entry, tokens, phrase);
|
|
if (hit) hits.push(hit);
|
|
}
|
|
|
|
hits.sort((a, b) => (b.score !== a.score ? b.score - a.score : a.id < b.id ? -1 : 1));
|
|
return options.limit === undefined ? hits : hits.slice(0, options.limit);
|
|
}
|
|
|
|
function scoreEntry(entry: LoadedObject, tokens: string[], phrase: string): SearchHit | null {
|
|
const object = entry.object;
|
|
const content = typeof object.content === "string" ? object.content : JSON.stringify(object.content ?? "");
|
|
|
|
let score = 0;
|
|
const matched: string[] = [];
|
|
|
|
const field = (name: string, weight: number, text: string | undefined): void => {
|
|
if (!text) return;
|
|
const lower = text.toLowerCase();
|
|
let hits = 0;
|
|
for (const token of tokens) if (lower.includes(token)) hits += 1;
|
|
// An exact phrase match is worth more than the same words scattered.
|
|
if (phrase.length > 2 && lower.includes(phrase)) hits += 2;
|
|
if (hits > 0) {
|
|
score += hits * weight;
|
|
matched.push(name);
|
|
}
|
|
};
|
|
|
|
field("id", 5, object.id.replace(/[._-]/g, " "));
|
|
field("title", 5, object.title);
|
|
field("tags", 4, object.tags?.join(" "));
|
|
field("summary", 3, object.summary);
|
|
field("type", 2, object.type);
|
|
field("content", 1, content);
|
|
|
|
if (score === 0) return null;
|
|
|
|
return {
|
|
id: object.id,
|
|
title: object.title,
|
|
type: object.type,
|
|
layer: object.layer,
|
|
authority: object.authority,
|
|
score,
|
|
matched,
|
|
excerpt: matched.includes("content") ? excerptOf(content, tokens, phrase) : undefined,
|
|
file: entry.file
|
|
};
|
|
}
|
|
|
|
function excerptOf(content: string, tokens: string[], phrase: string): string | undefined {
|
|
const lower = content.toLowerCase();
|
|
let index = phrase.length > 2 ? lower.indexOf(phrase) : -1;
|
|
if (index === -1) {
|
|
for (const token of tokens) {
|
|
index = lower.indexOf(token);
|
|
if (index !== -1) break;
|
|
}
|
|
}
|
|
if (index === -1) return undefined;
|
|
|
|
const start = Math.max(0, index - 60);
|
|
const end = Math.min(content.length, index + 140);
|
|
const slice = content.slice(start, end).replace(/\s+/g, " ").trim();
|
|
return `${start > 0 ? "…" : ""}${slice}${end < content.length ? "…" : ""}`;
|
|
}
|