dsh-boost 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/NOTICE +29 -0
- package/README.en.md +476 -0
- package/README.md +408 -2
- package/cordis.patch.yml +40 -0
- package/dist/admission/fixed-cost.d.ts +23 -0
- package/dist/admission/fixed-cost.js +61 -0
- package/dist/admission/fixed-cost.js.map +1 -0
- package/dist/admission/ledger.d.ts +113 -0
- package/dist/admission/ledger.js +176 -0
- package/dist/admission/ledger.js.map +1 -0
- package/dist/admission/retrieval.d.ts +65 -0
- package/dist/admission/retrieval.js +162 -0
- package/dist/admission/retrieval.js.map +1 -0
- package/dist/admission/usage.d.ts +75 -0
- package/dist/admission/usage.js +124 -0
- package/dist/admission/usage.js.map +1 -0
- package/dist/config.d.ts +43 -0
- package/dist/config.js +103 -0
- package/dist/config.js.map +1 -0
- package/dist/gate/binding.d.ts +113 -0
- package/dist/gate/binding.js +297 -0
- package/dist/gate/binding.js.map +1 -0
- package/dist/gate/decide.d.ts +82 -0
- package/dist/gate/decide.js +163 -0
- package/dist/gate/decide.js.map +1 -0
- package/dist/gate/guard.d.ts +69 -0
- package/dist/gate/guard.js +195 -0
- package/dist/gate/guard.js.map +1 -0
- package/dist/gate/invalidate.d.ts +112 -0
- package/dist/gate/invalidate.js +111 -0
- package/dist/gate/invalidate.js.map +1 -0
- package/dist/gate/plan.d.ts +86 -0
- package/dist/gate/plan.js +222 -0
- package/dist/gate/plan.js.map +1 -0
- package/dist/hooks/clock.d.ts +68 -0
- package/dist/hooks/clock.js +82 -0
- package/dist/hooks/clock.js.map +1 -0
- package/dist/hooks/execute.d.ts +79 -0
- package/dist/hooks/execute.js +128 -0
- package/dist/hooks/execute.js.map +1 -0
- package/dist/hooks/llm-stream.d.ts +276 -0
- package/dist/hooks/llm-stream.js +1008 -0
- package/dist/hooks/llm-stream.js.map +1 -0
- package/dist/hooks/pending.d.ts +89 -0
- package/dist/hooks/pending.js +115 -0
- package/dist/hooks/pending.js.map +1 -0
- package/dist/hooks/post-execute.d.ts +247 -0
- package/dist/hooks/post-execute.js +1776 -0
- package/dist/hooks/post-execute.js.map +1 -0
- package/dist/hooks/session-state.d.ts +158 -0
- package/dist/hooks/session-state.js +168 -0
- package/dist/hooks/session-state.js.map +1 -0
- package/dist/hooks/synthesize.d.ts +74 -0
- package/dist/hooks/synthesize.js +100 -0
- package/dist/hooks/synthesize.js.map +1 -0
- package/dist/host/loader.d.ts +23 -0
- package/dist/host/loader.js +31 -0
- package/dist/host/loader.js.map +1 -0
- package/dist/host/platform.d.ts +18 -0
- package/dist/host/platform.js +19 -0
- package/dist/host/platform.js.map +1 -0
- package/dist/host/root.d.ts +18 -0
- package/dist/host/root.js +43 -0
- package/dist/host/root.js.map +1 -0
- package/dist/index.d.ts +13 -0
- package/dist/index.js +866 -0
- package/dist/index.js.map +1 -0
- package/dist/projection/apply.d.ts +174 -0
- package/dist/projection/apply.js +137 -0
- package/dist/projection/apply.js.map +1 -0
- package/dist/projection/canonicalise.d.ts +43 -0
- package/dist/projection/canonicalise.js +43 -0
- package/dist/projection/canonicalise.js.map +1 -0
- package/dist/projection/counters.d.ts +65 -0
- package/dist/projection/counters.js +88 -0
- package/dist/projection/counters.js.map +1 -0
- package/dist/projection/truncate.d.ts +47 -0
- package/dist/projection/truncate.js +57 -0
- package/dist/projection/truncate.js.map +1 -0
- package/dist/prompt/protocol.d.ts +45 -0
- package/dist/prompt/protocol.js +56 -0
- package/dist/prompt/protocol.js.map +1 -0
- package/dist/receipts/store.d.ts +198 -0
- package/dist/receipts/store.js +734 -0
- package/dist/receipts/store.js.map +1 -0
- package/dist/scope/doc.d.ts +117 -0
- package/dist/scope/doc.js +158 -0
- package/dist/scope/doc.js.map +1 -0
- package/dist/scope/resolve.d.ts +91 -0
- package/dist/scope/resolve.js +146 -0
- package/dist/scope/resolve.js.map +1 -0
- package/dist/scope/store.d.ts +135 -0
- package/dist/scope/store.js +573 -0
- package/dist/scope/store.js.map +1 -0
- package/dist/selector/jev.d.ts +93 -0
- package/dist/selector/jev.js +171 -0
- package/dist/selector/jev.js.map +1 -0
- package/dist/tools/boost.d.ts +367 -0
- package/dist/tools/boost.js +768 -0
- package/dist/tools/boost.js.map +1 -0
- package/dist/tools/family.d.ts +26 -0
- package/dist/tools/family.js +26 -0
- package/dist/tools/family.js.map +1 -0
- package/dist/types.d.ts +113 -0
- package/dist/types.js +21 -0
- package/dist/types.js.map +1 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +75 -4
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"store.js","sourceRoot":"","sources":["../../src/receipts/store.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAwDG;AACH,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAA;AACxC,OAAO,EAAE,UAAU,EAAE,KAAK,EAAE,IAAI,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAA;AACrG,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAA;AAkEzC,MAAM,YAAY,GAAG,UAAU,CAAA;AAC/B,MAAM,cAAc,GAAG,QAAQ,CAAA;AAC/B,MAAM,cAAc,GAAG,UAAU,CAAA;AACjC,yFAAyF;AACzF,MAAM,mBAAmB,GAAG,GAAG,CAAA;AAC/B,MAAM,yBAAyB,GAAG,GAAG,CAAA;AACrC,MAAM,iBAAiB,GAAG,CAAC,GAAG,IAAI,GAAG,IAAI,CAAA;AACzC,MAAM,iBAAiB,GAAG,MAAM,CAAA;AAChC,8FAA8F;AAC9F,MAAM,sBAAsB,GAAG,CAAC,CAAA;AAChC,iGAAiG;AACjG,MAAM,4BAA4B,GAAG,IAAI,CAAA;AACzC,qEAAqE;AACrE,MAAM,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,cAAc;QAC1B,IAAI,OAAiB,CAAA;QACrB,IAAI,CAAC;YACH,OAAO,GAAG,MAAM,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,EAAE,YAAY,CAAC,CAAC,CAAA;QACxD,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,8EAA8E;YAC9E,2EAA2E;YAC3E,gDAAgD;YAChD,MAAM,IAAI,GAAG,SAAS,CAAC,KAAK,CAAC,CAAA;YAC7B,IAAI,IAAI,KAAK,QAAQ,IAAI,IAAI,KAAK,SAAS;gBAAE,OAAO,EAAE,CAAA;YACtD,MAAM,KAAK,CAAA;QACb,CAAC;QACD,MAAM,KAAK,GAAG,IAAI,GAAG,EAAU,CAAA;QAC/B,KAAK,MAAM,IAAI,IAAI,OAAO,EAAE,CAAC;YAC3B,IAAI,IAAI,CAAC,QAAQ,CAAC,cAAc,CAAC;gBAAE,KAAK,CAAC,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,cAAc,CAAC,MAAM,CAAC,CAAC,CAAA;iBAC9E,IAAI,IAAI,CAAC,QAAQ,CAAC,cAAc,CAAC;gBAAE,KAAK,CAAC,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,cAAc,CAAC,MAAM,CAAC,CAAC,CAAA;QAC1F,CAAC;QACD,4EAA4E;QAC5E,2DAA2D;QAC3D,OAAO,CAAC,GAAG,KAAK,CAAC,CAAC,IAAI,EAAE,CAAA;IAC1B,CAAC;CACF","sourcesContent":["/**\n * Append-only receipt store.\n *\n * Every decision the plugin makes is one JSON line under\n * `<root>/receipts/<encodeSegment(sessionId)>.jsonl`: the shadow week is\n * analysed offline from these files, and the plugin is audited from them after\n * the fact. The shard name percent-encodes every character outside\n * `[A-Za-z0-9_-]` (reversibly, one `%XX` per UTF-8 byte) because a host-supplied\n * session id may contain `/` or `..` and the store must never write outside\n * `receipts/`; the receipt body keeps the original id. The store is therefore\n * append-only (a read never writes; it ignores an unfinished tail), crash-safe\n * (a line that was never finished is not a receipt), bounded (current + `.1`,\n * hard limits), and fail-closed (three consecutive write failures stop\n * substitution rather than running without an audit trail).\n *\n * ## Write path\n *\n * A receipt is serialised and appended in one `appendFile` call, rotated before\n * the write when the current shard reached `maxBytes`/`maxLines`, and fsynced\n * only every `fsyncEveryLines` lines (or on `flush()` — the assembly flushes at\n * turn end, at the host's session/flush checkpoint and before session-end\n * eviction). A write failure never rejects: the line is buffered in memory in\n * order, `failures()` counts the *consecutive* failures, and a later successful\n * append replays the buffer and resets the count. The buffer is bounded, and\n * once the fail-closed `stopped()` threshold is reached it is dropped instead\n * of growing for the duration of the outage. `disposeSession` evicts a dead\n * session's shard state and records the id in a bounded set, so a hook that\n * lands after `session/disposed` records nothing.\n *\n * ## Read path\n *\n * `.1` is read before the current shard, so `scan` yields oldest receipts\n * first. A trailing line without `\\n` is **ignored** and the shard is left\n * untouched: a read is concurrent with the writer, and truncating from a\n * snapshot can cut a line another append just completed. Only the next write\n * path repairs the shard (`stateFor` truncates to the last newline before\n * appending). A corrupt line in the middle is skipped. Rotated shards are read\n * through the same path; nothing ever appends to `.1`, so its half line simply\n * stays ignored.\n *\n * ## Retention\n *\n * Shards are an audit trail and are never pruned: one shard set per session\n * stays on disk for the life of the root. A host that never emits\n * `session/disposed` therefore leaves the per-session maps (`states`,\n * `disposed`) and `scan`'s shard list growing with the session count. The maps\n * are bounded per session and evicted by `disposeSession`; a whole-store\n * `scan` is additionally capped at {@link MAX_SCAN_SHARDS} sorted shards so\n * `boost status` cannot walk an unbounded directory, while `scan(sessionId)`\n * still addresses any one shard. The cap drops shards from that aggregate\n * scan only; nothing is deleted.\n *\n * The store imports only `node:` builtins and knows no host services: the\n * caller resolves the root (the plugin passes `$DSH_HOME/boost`).\n *\n * @module dsh-boost/receipts/store\n */\nimport { createHash } from 'node:crypto'\nimport { appendFile, mkdir, open, readdir, readFile, rename, stat, truncate } from 'node:fs/promises'\nimport { dirname, join } from 'node:path'\n\n/** Why a receipt exists. `substitute-settled` is its own line because the store is append-only. */\nexport type ReceiptKind =\n | 'substitute'\n | 'substitute-settled'\n | 'shadow'\n | 'projection'\n | 'skip'\n | 'reset'\n\n/** Fields every receipt carries, before the store fills the derived ones. */\ntype ReceiptCore = {\n ts: string\n sessionId: string\n turn: number\n stepId?: string\n kind: ReceiptKind\n code: string\n tool?: string\n [k: string]: unknown\n}\n\n/**\n * One line of the audit log.\n *\n * Invariant (plan line 581): a receipt with `kind === 'projection'` always\n * carries `unit: 'raw'` as a literal — T19/T26 filter on it, so a projection\n * receipt without it would be invisible to the counters. The plan keeps\n * `Receipt` an interface, which cannot pair `kind` with `unit`, so `buildReceipt`\n * enforces the invariant by construction: it overwrites `unit` with `'raw'` on\n * every projection receipt, ignoring any caller-supplied value, because the\n * literal is the invariant rather than a parameter. A projection receipt is\n * never rejected for shape; it must remain auditable.\n */\nexport interface Receipt extends ReceiptCore {\n version: 1\n receipt_hash: string\n preview: string\n}\n\n/** What callers hand to `append`; the store fills `version`, `receipt_hash` and `preview`. */\ntype ReceiptInput = ReceiptCore & {\n version?: 1\n preview?: string\n}\n\n/** Tuning knobs; the defaults are the design's (§5.3). */\ninterface ReceiptStoreOptions {\n fsyncEveryLines?: number\n maxBytes?: number\n maxLines?: number\n}\n\n/** Per-shard counters used to decide rotation without re-reading the file. */\ninterface ShardState {\n lines: number\n bytes: number\n}\n\n/** One serialised line waiting for the disk. */\ninterface PendingLine {\n sessionId: string\n line: string\n}\n\nconst RECEIPTS_DIR = 'receipts'\nconst CURRENT_SUFFIX = '.jsonl'\nconst ROTATED_SUFFIX = '.1.jsonl'\n/** `preview` is the first 256 code points, never the full receipt text (design §5.4). */\nconst PREVIEW_CODE_POINTS = 256\nconst DEFAULT_FSYNC_EVERY_LINES = 100\nconst DEFAULT_MAX_BYTES = 8 * 1024 * 1024\nconst DEFAULT_MAX_LINES = 20_000\n/** Fail-closed threshold: after this many *consecutive* write failures, stop substituting. */\nconst STOPPED_AFTER_FAILURES = 3\n/** `args` is model-written; cap what a receipt line carries (identity hashes the full value). */\nconst MAX_RECEIPT_ARGS_CODE_POINTS = 2048\n/** Hard cap on the in-memory replay buffer (see `recordFailure`). */\nconst MAX_PENDING_LINES = 100\n/**\n * Depth bound for model-written `args`.\n *\n * The plan parser refuses args deeper than 64 levels, but a call that did not\n * come from a plan (the host's own `exec.arguments`) can be arbitrarily deep.\n * Walking it recursively would throw a `RangeError` and lose the receipt, and\n * `JSON.stringify` would throw the same way; deeper subtrees are replaced by\n * `{ truncated_depth: 64 }` before hashing or storing. The cut is visible in\n * the receipt as `args_depth_truncated: true`.\n */\nconst MAX_RECEIPT_ARGS_DEPTH = 64\n/**\n * Shards a whole-store `scan` visits at most.\n *\n * Shards are never deleted (the audit trail is the product), so a long-lived\n * host accumulates one per session forever. `scan()` with no id is the\n * status/report path; capping it keeps that path's work and memory bounded.\n * The kept shards are the first N sorted encoded names; named scans are not\n * capped.\n */\nconst MAX_SCAN_SHARDS = 256\n/**\n * How many disposed session ids the store remembers.\n *\n * A late `post-execute` can land seconds after `session/disposed` (a selector\n * call may take 20 s) and must not write a receipt into a closed session. The\n * set is FIFO-bounded so a long-lived process cannot grow it without limit; a\n * session id is unique, so evicting the oldest is safe.\n */\nconst MAX_DISPOSED_SESSIONS = 256\nconst NEWLINE = 0x0a\n\n/**\n * `sha256(stable JSON)` of the fields that identify a call, first 16 hex chars.\n *\n * `args` is part of the payload on purpose: without it, two different calls of\n * the same tool in one turn would collide. A missing `args` hashes like `{}`,\n * and object keys are sorted recursively so insertion order cannot change the\n * hash. An own `__proto__` key is an ordinary key, not the prototype setter.\n *\n * Args deeper than {@link MAX_RECEIPT_ARGS_DEPTH} are cut with a marker before\n * hashing, exactly as they are before storing: otherwise the recursive walk or\n * `JSON.stringify` would throw and the receipt (the audit evidence) would be\n * lost. Two trees that differ only below the bound therefore hash alike; the\n * plan parser refuses such trees, and a call whose args are deeper did not come\n * from a plan.\n */\nexport function receiptHash(r: {\n sessionId: string\n turn: number\n stepId?: string\n tool?: string\n args?: unknown\n}): string {\n const payload = {\n sessionId: r.sessionId,\n turn: r.turn,\n stepId: r.stepId,\n tool: r.tool,\n args: boundArgs(r.args ?? {}).value,\n }\n return createHash('sha256').update(JSON.stringify(payload)).digest('hex').slice(0, 16)\n}\n\n/** Whether a bounded walk had to replace a subtree deeper than the cap. */\ninterface BoundState {\n depthTruncated: boolean\n}\n\n/**\n * The sorted, depth-bounded copy of `value`.\n *\n * Keys are sorted recursively so insertion order cannot change the hash;\n * `undefined` members are dropped as `JSON.stringify` would. The copy is built\n * with `defineProperty`-equivalent semantics (`Object.create(null)`) because\n * plain assignment would let an own `__proto__` key hit the prototype setter and\n * vanish, hashing two different calls alike.\n *\n * Recursion is safe because the depth is capped at\n * {@link MAX_RECEIPT_ARGS_DEPTH}: at most 65 frames regardless of the input.\n * A deeper subtree becomes `{ truncated_depth: 64 }`.\n */\nfunction sortKeys(value: unknown, state: BoundState, depth: number): unknown {\n if (depth > MAX_RECEIPT_ARGS_DEPTH) {\n state.depthTruncated = true\n return { truncated_depth: MAX_RECEIPT_ARGS_DEPTH }\n }\n if (Array.isArray(value)) return value.map((child) => sortKeys(child, state, depth + 1))\n if (value !== null && typeof value === 'object') {\n const sorted: Record<string, unknown> = Object.create(null)\n for (const key of Object.keys(value).sort()) {\n const child = (value as Record<string, unknown>)[key]\n if (child !== undefined) sorted[key] = sortKeys(child, state, depth + 1)\n }\n return sorted\n }\n return value\n}\n\n/** Bound and sort `value`, reporting whether the depth cap cut anything. */\nfunction boundArgs(value: unknown): { value: unknown; depthTruncated: boolean } {\n const state: BoundState = { depthTruncated: false }\n return { value: sortKeys(value, state, 1), depthTruncated: state.depthTruncated }\n}\n\n/** First 256 code points; never slice UTF-16 units, which would split a surrogate pair. */\nfunction previewOf(text: string | undefined): string {\n return Array.from(text ?? '').slice(0, PREVIEW_CODE_POINTS).join('')\n}\n\n/**\n * Fill the derived fields. `receipt_hash` is always computed here — a\n * caller-supplied value would let the stored hash stop covering the receipt's\n * identifying fields, which is the one property the hash exists to guarantee.\n * A projection receipt's `unit` is likewise forced: the literal is the\n * invariant T19/T26 filter on, not a caller parameter.\n */\nfunction buildReceipt(r: ReceiptInput): Receipt {\n const receipt: Receipt = {\n ...r,\n version: r.version ?? 1,\n receipt_hash: receiptHash(r),\n preview: previewOf(r.preview),\n }\n if (receipt.kind === 'projection') receipt.unit = 'raw'\n // Bound before `capArgs`: its `JSON.stringify` would throw on a tree deeper\n // than the engine's recursion limit. The stored copy is the bounded one, so\n // a reader can parse it and the depth cut is visible.\n if (receipt.args !== undefined) {\n const bounded = boundArgs(receipt.args)\n receipt.args = bounded.value\n if (bounded.depthTruncated) receipt.args_depth_truncated = true\n }\n return capArgs(receipt)\n}\n\n/**\n * Bound the `args` a receipt carries.\n *\n * The model writes the arguments, so an otherwise-valid plan can carry a\n * multi-kilobyte blob into every receipt line. The hash is computed before this\n * cap, over the depth-bounded tree `boundArgs` produced (see `receiptHash`), so\n * identity is unaffected by this display cap; the stored copy is what an\n * operator reads, and a `truncated_json` marker with `args_truncated` says so\n * plainly rather than silently shortening a command.\n */\nfunction capArgs(receipt: Receipt): Receipt {\n if (receipt.args === undefined) return receipt\n const json = JSON.stringify(receipt.args)\n if (json === undefined || Array.from(json).length <= MAX_RECEIPT_ARGS_CODE_POINTS) return receipt\n return {\n ...receipt,\n args: { truncated_json: capCodePoints(json, MAX_RECEIPT_ARGS_CODE_POINTS) },\n args_truncated: true,\n }\n}\n\n/** Cap a string by code point so a surrogate pair is never split. */\nfunction capCodePoints(value: string, cap: number): string {\n const points = Array.from(value)\n if (points.length <= cap) return value\n return `${points.slice(0, Math.max(0, cap - 1)).join('')}…`\n}\n\n/** One receipt as one newline-terminated JSON line. */\nfunction serialiseReceipt(r: ReceiptInput): string {\n return `${JSON.stringify(buildReceipt(r))}\\n`\n}\n\n/**\n * Encode a session id as one safe filesystem path segment.\n *\n * Only `[A-Za-z0-9_-]` survives; every other character becomes `%XX` (uppercase\n * hex, one per UTF-8 byte). The mapping is reversible and keeps `/`, `\\`, `:`\n * and `.` out of the name, so a host-supplied id can never escape\n * `<root>/receipts/` and always yields one writable shard. The receipt body\n * keeps the original id; only the file name is encoded.\n */\nfunction encodeSegment(sessionId: string): string {\n let encoded = ''\n for (const char of sessionId) {\n if (/^[A-Za-z0-9_-]$/.test(char)) {\n encoded += char\n continue\n }\n for (const byte of Buffer.from(char, 'utf8')) {\n encoded += `%${byte.toString(16).toUpperCase().padStart(2, '0')}`\n }\n }\n return encoded\n}\n\n/** Path of a shard from an already-encoded base name (used by scans over the directory). */\nfunction shardFile(root: string, base: string, rotated: boolean): string {\n const name = rotated ? `${base}.1.jsonl` : `${base}.jsonl`\n return join(root, RECEIPTS_DIR, name)\n}\n\n/** `stat(dir).isDirectory()`-equivalent check without recursing into Node's `mkdir` spin. */\nasync function ensureDirectory(dir: string): Promise<void> {\n try {\n await mkdir(dir)\n return\n } catch (error) {\n const code = errorCode(error)\n if (code === 'EEXIST') {\n // `mkdir` reports EEXIST for a regular file too; only a directory is usable.\n if ((await stat(dir)).isDirectory()) return\n throw error\n }\n if (code !== 'ENOENT') throw error\n }\n // Node's own recursive `mkdir` can spin forever on filesystems that answer\n // ENOENT for a child even though the parent exists (e.g. `/proc`, the\n // fail-closed fixture's root). Walking up one segment at a time fails fast.\n const parent = dirname(dir)\n if (parent === dir) throw new Error(`cannot create directory: ${dir}`)\n await ensureDirectory(parent)\n try {\n await mkdir(dir)\n } catch (error) {\n if (errorCode(error) !== 'EEXIST' || !(await stat(dir)).isDirectory()) throw error\n }\n}\n\n/**\n * The complete-line prefix of `data`, computed without touching the file.\n *\n * A trailing line without `\\n` was never finished, so it is not a receipt:\n * `size` is the byte offset just past the last newline (zero when the first\n * line is unfinished). This is pure because the read path must never write: it\n * snapshots the file while a writer may be appending, and truncating from that\n * snapshot can cut a line the writer just completed. Only `stateFor` (the write\n * path) acts on `size < data.length`.\n */\nfunction completePrefix(data: Buffer): { valid: Buffer; size: number } {\n const lastNewline = data.lastIndexOf(NEWLINE)\n const size = lastNewline + 1\n return { valid: data.subarray(0, size), size }\n}\n\n/** Read a shard, ignoring an unfinished tail line without modifying the file. */\nasync function readShard(path: string): Promise<Receipt[]> {\n let data: Buffer\n try {\n data = await readFile(path)\n } catch (error) {\n // ENOTDIR is the file-valued `$DSH_HOME` shape: the shard cannot exist.\n const code = errorCode(error)\n if (code === 'ENOENT' || code === 'ENOTDIR') return []\n throw error\n }\n\n const { valid } = completePrefix(data)\n const receipts: Receipt[] = []\n for (const line of valid.toString('utf8').split('\\n')) {\n if (line === '') continue\n let parsed: unknown\n try {\n parsed = JSON.parse(line)\n } catch {\n continue // Corrupt middle line: skip it, do not fail the whole scan.\n }\n if (isReceipt(parsed)) receipts.push(parsed)\n }\n return receipts\n}\n\nfunction isReceipt(value: unknown): value is Receipt {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nfunction errorCode(error: unknown): string | undefined {\n return typeof error === 'object' && error !== null && 'code' in error\n ? (error as NodeJS.ErrnoException).code\n : undefined\n}\n\nfunction countNewlines(data: Buffer): number {\n let lines = 0\n for (const byte of data) {\n if (byte === NEWLINE) lines += 1\n }\n return lines\n}\n\n/**\n * Append-only, crash-safe, bounded store of receipts per session.\n *\n * See the module docs for the write and read paths. Concurrent method calls on\n * one instance are safe: writes are serialised through an internal promise\n * chain. The store is single-writer per root by design — rotation counters are\n * per instance, so two instances (or processes) writing one root can exceed the\n * shard caps and lose receipts. The plugin owns exactly one store per root.\n */\nexport class ReceiptStore {\n private readonly root: string\n private readonly fsyncEveryLines: number\n private readonly maxBytes: number\n private readonly maxLines: number\n\n /** *Consecutive* write failures; reset by any successful append. */\n private failureCount = 0\n /**\n * Shard reads skipped by whole-store scans since the last scan that read\n * every shard (EACCES, EISDIR, …). A fully readable scan resets it to zero,\n * so a repaired shard drops `ERR_RECEIPTS_UNREADABLE` instead of pinning it\n * for the life of the process. Named scans neither count here nor reset it:\n * they do not cover the shard set status reports.\n */\n private readFailureCount = 0\n /** Whether the most recent whole-store scan hit {@link MAX_SCAN_SHARDS}. */\n private scanCapHit = false\n private linesSinceSync = 0\n private readonly pending: PendingLine[] = []\n private readonly states = new Map<string, ShardState>()\n private readonly dirty = new Set<string>()\n private readonly disposed = new Set<string>()\n private readonly disposedOrder: string[] = []\n private dirReady = false\n /** Writes run one at a time so rotation and buffer replay cannot interleave. */\n private chain: Promise<void> = Promise.resolve()\n\n constructor(root: string, opts: ReceiptStoreOptions = {}) {\n this.root = root\n this.fsyncEveryLines = opts.fsyncEveryLines ?? DEFAULT_FSYNC_EVERY_LINES\n this.maxBytes = opts.maxBytes ?? DEFAULT_MAX_BYTES\n this.maxLines = opts.maxLines ?? DEFAULT_MAX_LINES\n }\n\n /**\n * Append one receipt. Never rejects: a serialisation or write failure is\n * counted and buffered. The session id is encoded only for the shard name;\n * the stored receipt keeps the original id.\n */\n append(receipt: ReceiptInput): Promise<void> {\n const run = this.chain.then(() => this.appendNow(receipt))\n const safe = run.then(\n () => undefined,\n () => undefined,\n )\n this.chain = safe\n return safe\n }\n\n /** Force the buffered lines and the current shards to disk (called at turn end). */\n flush(): Promise<void> {\n // Queued like an append: a flush racing an append must not replay the same\n // buffered line twice.\n const run = this.chain.then(() => this.flushNow())\n const safe = run.then(\n () => undefined,\n () => undefined,\n )\n this.chain = safe\n return safe\n }\n\n /** Number of receipts readable for `sessionId` (`.1` plus current). */\n async count(sessionId: string): Promise<number> {\n let count = 0\n for await (const _ of this.scan(sessionId)) count += 1\n return count\n }\n\n /**\n * Shard reads that the most recent whole-store scan skipped.\n *\n * A single unreadable shard (EACCES, a directory named `x.jsonl`, …) must\n * not abort the whole scan: `boost status` would turn that into\n * `ERR_BOOST_INTERNAL` for the entire ledger. Scans skip the shard and count\n * it here so status can report a stable degraded code.\n *\n * The count describes the skipped reads **since the last whole-store scan\n * that read every shard**, not the process lifetime: a fully readable scan\n * resets it, so repairing the shard and re-running `status` drops the code,\n * as the README instructs. A named `scan(sessionId)`/`count(sessionId)`\n * neither contributes to nor clears it, because it does not cover the shard\n * set the status total claims.\n */\n readErrors(): number {\n return this.readFailureCount\n }\n\n /**\n * Whether the most recent whole-store scan stopped at {@link MAX_SCAN_SHARDS}.\n *\n * `status` reports a total over the shards it read, so a capped scan is a\n * lower bound, not a total. The flag is per scan (false on the next full\n * scan that fits), which lets the operator see the condition clear; the\n * numeric totals stay unchanged and under-count, the safe direction.\n */\n scanTruncated(): boolean {\n return this.scanCapHit\n }\n\n /**\n * Yield readable receipts, oldest first: `.1` before the current shard.\n *\n * The optional `sessionId` is encoded to its shard name; the receipts keep\n * their original `sessionId`. With no argument, every shard under `receipts/`\n * is visited (encoded shard names sorted for determinism, capped at\n * {@link MAX_SCAN_SHARDS}), and each receipt supplies its own id from its\n * body. Unparseable middle lines are skipped; an unfinished trailing line is\n * ignored by the read and only the next write repairs it.\n *\n * A whole-store scan also maintains the two status readings: a shard it\n * cannot read increments {@link readErrors} (a fully readable scan resets\n * it), and more shards than the cap sets {@link scanTruncated}. Named scans\n * touch neither, because they are not the population `status` totals.\n */\n async *scan(sessionId?: string): AsyncIterable<Receipt> {\n await this.chain\n let shards: string[]\n let readFailed = false\n const wholeStore = sessionId === undefined\n if (wholeStore) {\n this.scanCapHit = false\n try {\n const names = await this.listShardNames()\n this.scanCapHit = names.length > MAX_SCAN_SHARDS\n // Bounded status scan; named scans below still address any one shard.\n shards = names.slice(0, MAX_SCAN_SHARDS)\n } catch {\n // An unreadable receipts directory is a degraded status answer, not a\n // thrown tool error. Count it and yield nothing.\n this.readFailureCount += 1\n return\n }\n } else {\n shards = [encodeSegment(sessionId)]\n }\n for (const base of shards) {\n for (const rotated of [true, false]) {\n let receipts: Receipt[]\n try {\n receipts = await readShard(shardFile(this.root, base, rotated))\n } catch {\n this.readFailureCount += 1\n readFailed = true\n continue\n }\n for (const receipt of receipts) {\n yield receipt\n }\n }\n }\n // A completed whole-store scan that read every shard clears the reading, so\n // repairing the shard and re-running `status` drops ERR_RECEIPTS_UNREADABLE.\n if (wholeStore && !readFailed) this.readFailureCount = 0\n }\n\n /**\n * Forget one session's shard state and silence later receipts for it.\n *\n * Called from the plugin's `session/disposed` handler after `flush()`. It\n * evicts the cached counters, forgets any buffered lines for that session\n * **only when no write failure is outstanding**, and remembers the id\n * (bounded FIFO) so a hook that lands after disposal records nothing instead\n * of recreating state nothing will ever clear.\n *\n * The conditional drop is the \"flush before eviction\" promise: a successful\n * flush has already drained `pending`, so the loop is a no-op; a failed one\n * leaves the session's lines there, and they are the only copy of that\n * evidence. They stay queued for the next flush — the buffer is bounded by\n * {@link MAX_PENDING_LINES} and is emptied once {@link stopped} is reached,\n * so retaining them cannot grow without limit.\n */\n disposeSession(sessionId: string): void {\n this.states.delete(sessionId)\n this.dirty.delete(sessionId)\n if (this.failureCount === 0) {\n for (let i = this.pending.length - 1; i >= 0; i -= 1) {\n if (this.pending[i]?.sessionId === sessionId) this.pending.splice(i, 1)\n }\n }\n if (this.disposed.has(sessionId)) return\n this.disposed.add(sessionId)\n this.disposedOrder.push(sessionId)\n while (this.disposedOrder.length > MAX_DISPOSED_SESSIONS) {\n const oldest = this.disposedOrder.shift()\n if (oldest !== undefined) this.disposed.delete(oldest)\n }\n }\n\n /** Consecutive write failures; a successful append resets it to zero. */\n failures(): number {\n return this.failureCount\n }\n\n /** Fail-closed gate: true after {@link STOPPED_AFTER_FAILURES} consecutive write failures. */\n stopped(): boolean {\n return this.failureCount >= STOPPED_AFTER_FAILURES\n }\n\n private async appendNow(receipt: ReceiptInput): Promise<void> {\n // A late hook on a disposed session is expected to run; it must record\n // nothing, not buffer a line nothing will ever write.\n if (this.disposed.has(receipt.sessionId)) return\n\n let entry: PendingLine\n try {\n entry = { sessionId: receipt.sessionId, line: serialiseReceipt(receipt) }\n } catch {\n this.recordFailure()\n return\n }\n\n try {\n await this.drainPending()\n await this.writeLine(entry)\n } catch {\n // Invalidating the cached counters makes the next attempt re-read the\n // shard, which also cuts a partial line this failed write may have left.\n // Re-checking the directory lets the store recover if it disappeared.\n this.states.delete(entry.sessionId)\n this.dirReady = false\n if (!this.stopped() && this.pending.length < MAX_PENDING_LINES) this.pending.push(entry)\n this.recordFailure()\n return\n }\n\n this.failureCount = 0\n try {\n await this.syncIfDue()\n } catch {\n // The line is written, so it is not buffered again — but a failed fsync\n // still means the write path is unhealthy.\n this.failureCount += 1\n }\n }\n\n /** The serialised body of {@link flush}; a failure is counted, never thrown. */\n private async flushNow(): Promise<void> {\n try {\n await this.drainPending()\n await this.syncDirty()\n } catch {\n this.recordFailure()\n }\n }\n\n /**\n * Count one write failure and enforce the buffer bound.\n *\n * Once the store is `stopped()` (three consecutive failures) it is\n * fail-closed: appends are still attempted so a recovered disk can reset the\n * count, but the replay buffer is dropped instead of growing for as long as\n * the outage lasts. Before that point `MAX_PENDING_LINES` is the hard cap.\n */\n private recordFailure(): void {\n this.failureCount += 1\n if (this.stopped()) this.pending.length = 0\n }\n\n /** Replay buffered lines in order; the head stays queued until its write succeeds. */\n private async drainPending(): Promise<void> {\n while (this.pending.length > 0) {\n const entry = this.pending[0]\n // `length > 0` guarantees a dense head (the buffer is only appended to\n // and shifted from); the check narrows the type without a bang. Returning\n // rather than spinning keeps an impossible sparse buffer from looping.\n if (entry === undefined) return\n await this.writeLine(entry)\n this.pending.shift()\n }\n }\n\n private async writeLine(entry: PendingLine): Promise<void> {\n await this.ensureDir()\n const state = await this.stateFor(entry.sessionId)\n await this.rotateIfFull(entry.sessionId, state)\n await appendFile(this.shardPath(entry.sessionId, false), entry.line, 'utf8')\n state.lines += 1\n state.bytes += Buffer.byteLength(entry.line, 'utf8')\n this.linesSinceSync += 1\n this.dirty.add(entry.sessionId)\n }\n\n private async ensureDir(): Promise<void> {\n if (this.dirReady) return\n await ensureDirectory(join(this.root, RECEIPTS_DIR))\n this.dirReady = true\n }\n\n /** Cached line/byte counters, loaded (and repaired) from disk on first use. */\n private async stateFor(sessionId: string): Promise<ShardState> {\n const cached = this.states.get(sessionId)\n if (cached !== undefined) return cached\n\n const path = this.shardPath(sessionId, false)\n let data: Buffer\n try {\n data = await readFile(path)\n } catch (error) {\n if (errorCode(error) !== 'ENOENT') throw error\n data = Buffer.alloc(0)\n }\n\n // A crash left a partial line; appending after it would make the next\n // receipt unreadable too. The write path repairs it before counting and\n // writing, and propagates a failed repair so this append fails instead.\n const { valid, size } = completePrefix(data)\n if (size < data.length) await truncate(path, size)\n const state: ShardState = { lines: countNewlines(valid), bytes: size }\n this.states.set(sessionId, state)\n return state\n }\n\n private async rotateIfFull(sessionId: string, state: ShardState): Promise<void> {\n if (state.lines < this.maxLines && state.bytes < this.maxBytes) return\n\n if (this.dirty.has(sessionId)) {\n await this.syncSession(sessionId)\n this.dirty.delete(sessionId)\n }\n try {\n // Renaming over an existing `.1` is the whole retention policy: only the\n // current shard and its predecessor are ever kept.\n await rename(this.shardPath(sessionId, false), this.shardPath(sessionId, true))\n } catch (error) {\n if (errorCode(error) !== 'ENOENT') throw error // already gone: nothing to rotate\n }\n state.lines = 0\n state.bytes = 0\n }\n\n private async syncIfDue(): Promise<void> {\n if (this.linesSinceSync < this.fsyncEveryLines) return\n await this.syncDirty()\n }\n\n private async syncDirty(): Promise<void> {\n for (const sessionId of this.dirty) await this.syncSession(sessionId)\n this.dirty.clear()\n this.linesSinceSync = 0\n }\n\n private async syncSession(sessionId: string): Promise<void> {\n const handle = await open(this.shardPath(sessionId, false), 'a')\n try {\n await handle.sync()\n } finally {\n await handle.close()\n }\n }\n\n private shardPath(sessionId: string, rotated: boolean): string {\n return shardFile(this.root, encodeSegment(sessionId), rotated)\n }\n\n /** Encoded shard base names present under `receipts/`, sorted. */\n private async listShardNames(): Promise<string[]> {\n let entries: string[]\n try {\n entries = await readdir(join(this.root, RECEIPTS_DIR))\n } catch (error) {\n // ENOTDIR: `$DSH_HOME` (or the boost root) names a file, so `<root>/receipts`\n // cannot be a directory. That is an empty ledger, not an internal failure;\n // `boost status` must still answer (review I5).\n const code = errorCode(error)\n if (code === 'ENOENT' || code === 'ENOTDIR') return []\n throw error\n }\n const names = new Set<string>()\n for (const name of entries) {\n if (name.endsWith(ROTATED_SUFFIX)) names.add(name.slice(0, -ROTATED_SUFFIX.length))\n else if (name.endsWith(CURRENT_SUFFIX)) names.add(name.slice(0, -CURRENT_SUFFIX.length))\n }\n // The empty base is the empty sessionId's shard (`.jsonl`). Keep it: scan()\n // must yield every receipt, and `scan('')` can address it.\n return [...names].sort()\n }\n}\n"]}
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Scope document model: where the plugin is allowed to act.
|
|
3
|
+
*
|
|
4
|
+
* `scope.json` is the single source of truth for the exposure surface (design
|
|
5
|
+
* §5.5). This module only parses an already-read value; it never touches the
|
|
6
|
+
* filesystem. Task 9's store owns reading, locking and writing.
|
|
7
|
+
*
|
|
8
|
+
* The input is the JSON-decoded value `JSON.parse` produces for `scope.json`,
|
|
9
|
+
* not an arbitrary host object: exotic in-memory shapes (throwing getters,
|
|
10
|
+
* inherited fields) are outside the contract and are not defended against.
|
|
11
|
+
*
|
|
12
|
+
* Parsing is fail-closed in three ordered stages. **Type delimitation runs
|
|
13
|
+
* before the version checks**: a non-object, `null` or an array is a parse
|
|
14
|
+
* failure even when it carries a `version` property. Then a numeric `version`
|
|
15
|
+
* greater than `2` is a **future version**: it is a valid document written by a
|
|
16
|
+
* newer plugin, so reads degrade but writes must never rewrite it (the field
|
|
17
|
+
* set may be newer than this parser knows). Finally anything whose `version` is
|
|
18
|
+
* not exactly `2` — version 1, a missing or non-numeric version — is an
|
|
19
|
+
* **unknown version**; a version 1 document is the one upgradeable case, and
|
|
20
|
+
* the command decides when to upgrade it.
|
|
21
|
+
*
|
|
22
|
+
* A matching stage rejects immediately, and no failure returns a partial
|
|
23
|
+
* document: every failure comes back as a fresh deep copy of `DEFAULT_SCOPE`,
|
|
24
|
+
* the strictest exposure (`selected + []`), so a malformed or newer-versioned
|
|
25
|
+
* file degrades to "nobody sees it" rather than crashing the agent.
|
|
26
|
+
*
|
|
27
|
+
* Individual fields are guarded on the strict side too: an unknown `mode` is
|
|
28
|
+
* `'selected'`, a non-array `workspaceIds` is `[]`, non-string members are
|
|
29
|
+
* dropped, a non-boolean `shadow` is `true`, an unknown `projection` is
|
|
30
|
+
* `'shadow'`, and a non-finite `revision` is `0`. `updatedAt` is never
|
|
31
|
+
* validated beyond being a string.
|
|
32
|
+
*
|
|
33
|
+
* @module dsh-boost/scope/doc
|
|
34
|
+
*/
|
|
35
|
+
import type { ProjectionMode } from '../projection/apply.js';
|
|
36
|
+
/** Stable rejection code: the file names a version this parser does not know. */
|
|
37
|
+
export declare const ERR_SCOPE_UNKNOWN_VERSION = "ERR_SCOPE_UNKNOWN_VERSION";
|
|
38
|
+
/**
|
|
39
|
+
* Stable rejection code: the file's version is a number newer than this parser
|
|
40
|
+
* (version 3+). Reads degrade like any other failure, but the document is
|
|
41
|
+
* **read-only**: it may carry fields and workspace ids this parser would prune,
|
|
42
|
+
* so writing it back would silently lose the user's configuration.
|
|
43
|
+
*/
|
|
44
|
+
export declare const ERR_SCOPE_FUTURE_VERSION = "ERR_SCOPE_FUTURE_VERSION";
|
|
45
|
+
/** Stable rejection code: the file is not a scope document at all. */
|
|
46
|
+
export declare const ERR_SCOPE_PARSE_FAILED = "ERR_SCOPE_PARSE_FAILED";
|
|
47
|
+
/** Stable rejection code: the file exists but could not be read. */
|
|
48
|
+
export declare const ERR_SCOPE_READ_FAILED = "ERR_SCOPE_READ_FAILED";
|
|
49
|
+
/** Stable rejection code: the write's base revision is stale. */
|
|
50
|
+
export declare const ERR_SCOPE_REVISION_CONFLICT = "ERR_SCOPE_REVISION_CONFLICT";
|
|
51
|
+
/** Stable rejection code: another writer holds the scope lock. */
|
|
52
|
+
export declare const ERR_SCOPE_LOCKED = "ERR_SCOPE_LOCKED";
|
|
53
|
+
/**
|
|
54
|
+
* Stable rejection code: the write was cancelled through its `AbortSignal`.
|
|
55
|
+
*
|
|
56
|
+
* Checked at every await boundary of the write path. A cancellation is not a
|
|
57
|
+
* storage failure — the file is left exactly as it was — so the caller can
|
|
58
|
+
* report it without implying the scope is damaged.
|
|
59
|
+
*/
|
|
60
|
+
export declare const ERR_SCOPE_ABORTED = "ERR_SCOPE_ABORTED";
|
|
61
|
+
/** Every stable scope failure code (design §5.5 plus the future-version split). */
|
|
62
|
+
export type ScopeCode = typeof ERR_SCOPE_UNKNOWN_VERSION | typeof ERR_SCOPE_FUTURE_VERSION | typeof ERR_SCOPE_PARSE_FAILED | typeof ERR_SCOPE_READ_FAILED | typeof ERR_SCOPE_REVISION_CONFLICT | typeof ERR_SCOPE_LOCKED | typeof ERR_SCOPE_ABORTED;
|
|
63
|
+
/** A parsed `scope.json` document, version 2 (design §5.5). */
|
|
64
|
+
export interface ScopeDoc {
|
|
65
|
+
version: 2;
|
|
66
|
+
/** Incremented by the store on every successful write. */
|
|
67
|
+
revision: number;
|
|
68
|
+
/** Last write time, when the store recorded one; never validated further. */
|
|
69
|
+
updatedAt?: string;
|
|
70
|
+
mode: 'selected' | 'global';
|
|
71
|
+
workspaceIds: string[];
|
|
72
|
+
/** Shadow accounting switch (`boost shadow on|off`). */
|
|
73
|
+
shadow: boolean;
|
|
74
|
+
/** Projection shape: off, accounting only, or real replacement. */
|
|
75
|
+
projection: ProjectionMode;
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* The strictest exposure and the fallback for every failure: nobody sees the
|
|
79
|
+
* plugin until the user opts in.
|
|
80
|
+
*/
|
|
81
|
+
export declare const DEFAULT_SCOPE: ScopeDoc;
|
|
82
|
+
/**
|
|
83
|
+
* Read one `scope.json` value, as produced by `JSON.parse`.
|
|
84
|
+
*
|
|
85
|
+
* A value whose type or version is wrong is rejected with a stable code and a
|
|
86
|
+
* deep copy of `DEFAULT_SCOPE`; a version 2 object yields a complete document
|
|
87
|
+
* built from its fields, with every malformed field degraded to its strict
|
|
88
|
+
* value.
|
|
89
|
+
*/
|
|
90
|
+
export declare function parseScope(raw: unknown): {
|
|
91
|
+
doc: ScopeDoc;
|
|
92
|
+
code?: 'ERR_SCOPE_UNKNOWN_VERSION' | 'ERR_SCOPE_FUTURE_VERSION' | 'ERR_SCOPE_PARSE_FAILED';
|
|
93
|
+
};
|
|
94
|
+
/**
|
|
95
|
+
* The upgrade base for a version 1 document.
|
|
96
|
+
*
|
|
97
|
+
* Reading a v1 file still degrades to {@link DEFAULT_SCOPE} and reports
|
|
98
|
+
* {@link ERR_SCOPE_UNKNOWN_VERSION} (design §5.5 rule 3: unknown versions are
|
|
99
|
+
* read-only). Only the explicit `scope-set` upgrade may rewrite it, and this
|
|
100
|
+
* function answers "what did the user's v1 file actually say" for that one
|
|
101
|
+
* write: `version` becomes 2 and `revision` starts at the degraded read's 0,
|
|
102
|
+
* while every recognised field keeps its value (strict side for malformed
|
|
103
|
+
* ones). Never use this on the read path — a v1 document is not a valid v2
|
|
104
|
+
* document and must keep presenting as invisible until upgraded.
|
|
105
|
+
*
|
|
106
|
+
* `undefined` for anything that is not a plain object with `version === 1`,
|
|
107
|
+
* including v2, future versions, missing versions and non-objects.
|
|
108
|
+
*/
|
|
109
|
+
export declare function parseVersionOneScope(raw: unknown): ScopeDoc | undefined;
|
|
110
|
+
/**
|
|
111
|
+
* Whether the plugin may act for an agent in `workspaceId`.
|
|
112
|
+
*
|
|
113
|
+
* An agent with no workspace has the global view, and the plugin never injects
|
|
114
|
+
* into the global view (design §5.5), so `undefined` is always invisible.
|
|
115
|
+
* `mode: 'global'` widens to any *defined* workspace id, not to `undefined`.
|
|
116
|
+
*/
|
|
117
|
+
export declare function isVisible(doc: ScopeDoc, workspaceId: string | undefined): boolean;
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
/** Stable rejection code: the file names a version this parser does not know. */
|
|
2
|
+
export const ERR_SCOPE_UNKNOWN_VERSION = 'ERR_SCOPE_UNKNOWN_VERSION';
|
|
3
|
+
/**
|
|
4
|
+
* Stable rejection code: the file's version is a number newer than this parser
|
|
5
|
+
* (version 3+). Reads degrade like any other failure, but the document is
|
|
6
|
+
* **read-only**: it may carry fields and workspace ids this parser would prune,
|
|
7
|
+
* so writing it back would silently lose the user's configuration.
|
|
8
|
+
*/
|
|
9
|
+
export const ERR_SCOPE_FUTURE_VERSION = 'ERR_SCOPE_FUTURE_VERSION';
|
|
10
|
+
/** Stable rejection code: the file is not a scope document at all. */
|
|
11
|
+
export const ERR_SCOPE_PARSE_FAILED = 'ERR_SCOPE_PARSE_FAILED';
|
|
12
|
+
/** Stable rejection code: the file exists but could not be read. */
|
|
13
|
+
export const ERR_SCOPE_READ_FAILED = 'ERR_SCOPE_READ_FAILED';
|
|
14
|
+
/** Stable rejection code: the write's base revision is stale. */
|
|
15
|
+
export const ERR_SCOPE_REVISION_CONFLICT = 'ERR_SCOPE_REVISION_CONFLICT';
|
|
16
|
+
/** Stable rejection code: another writer holds the scope lock. */
|
|
17
|
+
export const ERR_SCOPE_LOCKED = 'ERR_SCOPE_LOCKED';
|
|
18
|
+
/**
|
|
19
|
+
* Stable rejection code: the write was cancelled through its `AbortSignal`.
|
|
20
|
+
*
|
|
21
|
+
* Checked at every await boundary of the write path. A cancellation is not a
|
|
22
|
+
* storage failure — the file is left exactly as it was — so the caller can
|
|
23
|
+
* report it without implying the scope is damaged.
|
|
24
|
+
*/
|
|
25
|
+
export const ERR_SCOPE_ABORTED = 'ERR_SCOPE_ABORTED';
|
|
26
|
+
/**
|
|
27
|
+
* The strictest exposure and the fallback for every failure: nobody sees the
|
|
28
|
+
* plugin until the user opts in.
|
|
29
|
+
*/
|
|
30
|
+
export const DEFAULT_SCOPE = {
|
|
31
|
+
version: 2,
|
|
32
|
+
revision: 0,
|
|
33
|
+
mode: 'selected',
|
|
34
|
+
workspaceIds: [],
|
|
35
|
+
shadow: true,
|
|
36
|
+
projection: 'shadow',
|
|
37
|
+
};
|
|
38
|
+
/**
|
|
39
|
+
* Type delimitation and version classification, in the order the cases must be
|
|
40
|
+
* checked.
|
|
41
|
+
*
|
|
42
|
+
* The first entry rejects everything that is not a plain object (including
|
|
43
|
+
* `null` and arrays, whatever extra properties they carry). The second marks a
|
|
44
|
+
* numeric version greater than 2 as a future version; it must run **before**
|
|
45
|
+
* the catch-all third entry, which treats every remaining non-2 version
|
|
46
|
+
* (version 1, missing, non-numeric) as unknown. A matching entry ends parsing
|
|
47
|
+
* before the remaining fields are read.
|
|
48
|
+
*/
|
|
49
|
+
const DELIMITERS = [
|
|
50
|
+
{
|
|
51
|
+
code: ERR_SCOPE_PARSE_FAILED,
|
|
52
|
+
matches: (raw) => raw === null || typeof raw !== 'object' || Array.isArray(raw),
|
|
53
|
+
},
|
|
54
|
+
{
|
|
55
|
+
code: ERR_SCOPE_FUTURE_VERSION,
|
|
56
|
+
matches: (raw) => {
|
|
57
|
+
const version = raw.version;
|
|
58
|
+
return typeof version === 'number' && version > 2;
|
|
59
|
+
},
|
|
60
|
+
},
|
|
61
|
+
{
|
|
62
|
+
code: ERR_SCOPE_UNKNOWN_VERSION,
|
|
63
|
+
matches: (raw) => raw.version !== 2,
|
|
64
|
+
},
|
|
65
|
+
];
|
|
66
|
+
/** A failed parse: always a fresh copy of the strictest document. */
|
|
67
|
+
function rejected(code) {
|
|
68
|
+
return { doc: structuredClone(DEFAULT_SCOPE), code };
|
|
69
|
+
}
|
|
70
|
+
/** Strict side for `mode`: anything but the two literals means `selected`. */
|
|
71
|
+
function parseMode(raw) {
|
|
72
|
+
return raw === 'selected' || raw === 'global' ? raw : 'selected';
|
|
73
|
+
}
|
|
74
|
+
/** Strict side for `workspaceIds`: a non-array is empty, non-strings dropped. */
|
|
75
|
+
function parseWorkspaceIds(raw) {
|
|
76
|
+
return Array.isArray(raw) ? raw.filter((id) => typeof id === 'string') : [];
|
|
77
|
+
}
|
|
78
|
+
/** Strict side for `revision`: anything but a finite number is the initial revision. */
|
|
79
|
+
function parseRevision(raw) {
|
|
80
|
+
return typeof raw === 'number' && Number.isFinite(raw) ? raw : 0;
|
|
81
|
+
}
|
|
82
|
+
/** Strict side for `shadow`: a non-boolean keeps shadow accounting on. */
|
|
83
|
+
function parseShadow(raw) {
|
|
84
|
+
return typeof raw === 'boolean' ? raw : true;
|
|
85
|
+
}
|
|
86
|
+
/** Strict side for `projection`: anything else falls back to shadow accounting. */
|
|
87
|
+
function parseProjection(raw) {
|
|
88
|
+
return raw === 'off' || raw === 'shadow' || raw === 'on' ? raw : 'shadow';
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* Read one `scope.json` value, as produced by `JSON.parse`.
|
|
92
|
+
*
|
|
93
|
+
* A value whose type or version is wrong is rejected with a stable code and a
|
|
94
|
+
* deep copy of `DEFAULT_SCOPE`; a version 2 object yields a complete document
|
|
95
|
+
* built from its fields, with every malformed field degraded to its strict
|
|
96
|
+
* value.
|
|
97
|
+
*/
|
|
98
|
+
export function parseScope(raw) {
|
|
99
|
+
const rejection = DELIMITERS.find((delimiter) => delimiter.matches(raw));
|
|
100
|
+
if (rejection)
|
|
101
|
+
return rejected(rejection.code);
|
|
102
|
+
const source = raw;
|
|
103
|
+
return {
|
|
104
|
+
doc: {
|
|
105
|
+
version: 2,
|
|
106
|
+
revision: parseRevision(source.revision),
|
|
107
|
+
...(typeof source.updatedAt === 'string' ? { updatedAt: source.updatedAt } : {}),
|
|
108
|
+
mode: parseMode(source.mode),
|
|
109
|
+
workspaceIds: parseWorkspaceIds(source.workspaceIds),
|
|
110
|
+
shadow: parseShadow(source.shadow),
|
|
111
|
+
projection: parseProjection(source.projection),
|
|
112
|
+
},
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* The upgrade base for a version 1 document.
|
|
117
|
+
*
|
|
118
|
+
* Reading a v1 file still degrades to {@link DEFAULT_SCOPE} and reports
|
|
119
|
+
* {@link ERR_SCOPE_UNKNOWN_VERSION} (design §5.5 rule 3: unknown versions are
|
|
120
|
+
* read-only). Only the explicit `scope-set` upgrade may rewrite it, and this
|
|
121
|
+
* function answers "what did the user's v1 file actually say" for that one
|
|
122
|
+
* write: `version` becomes 2 and `revision` starts at the degraded read's 0,
|
|
123
|
+
* while every recognised field keeps its value (strict side for malformed
|
|
124
|
+
* ones). Never use this on the read path — a v1 document is not a valid v2
|
|
125
|
+
* document and must keep presenting as invisible until upgraded.
|
|
126
|
+
*
|
|
127
|
+
* `undefined` for anything that is not a plain object with `version === 1`,
|
|
128
|
+
* including v2, future versions, missing versions and non-objects.
|
|
129
|
+
*/
|
|
130
|
+
export function parseVersionOneScope(raw) {
|
|
131
|
+
if (raw === null || typeof raw !== 'object' || Array.isArray(raw))
|
|
132
|
+
return undefined;
|
|
133
|
+
if (raw.version !== 1)
|
|
134
|
+
return undefined;
|
|
135
|
+
const source = raw;
|
|
136
|
+
return {
|
|
137
|
+
version: 2,
|
|
138
|
+
revision: 0,
|
|
139
|
+
...(typeof source.updatedAt === 'string' ? { updatedAt: source.updatedAt } : {}),
|
|
140
|
+
mode: parseMode(source.mode),
|
|
141
|
+
workspaceIds: parseWorkspaceIds(source.workspaceIds),
|
|
142
|
+
shadow: parseShadow(source.shadow),
|
|
143
|
+
projection: parseProjection(source.projection),
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
/**
|
|
147
|
+
* Whether the plugin may act for an agent in `workspaceId`.
|
|
148
|
+
*
|
|
149
|
+
* An agent with no workspace has the global view, and the plugin never injects
|
|
150
|
+
* into the global view (design §5.5), so `undefined` is always invisible.
|
|
151
|
+
* `mode: 'global'` widens to any *defined* workspace id, not to `undefined`.
|
|
152
|
+
*/
|
|
153
|
+
export function isVisible(doc, workspaceId) {
|
|
154
|
+
if (workspaceId === undefined)
|
|
155
|
+
return false;
|
|
156
|
+
return doc.mode === 'global' || doc.workspaceIds.includes(workspaceId);
|
|
157
|
+
}
|
|
158
|
+
//# sourceMappingURL=doc.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"doc.js","sourceRoot":"","sources":["../../src/scope/doc.ts"],"names":[],"mappings":"AAoCA,iFAAiF;AACj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,YAAY,CAAC;QACpD,MAAM,EAAE,WAAW,CAAC,MAAM,CAAC,MAAM,CAAC;QAClC,UAAU,EAAE,eAAe,CAAC,MAAM,CAAC,UAAU,CAAC;KAC/C,CAAA;AACH,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,SAAS,CAAC,GAAa,EAAE,WAA+B;IACtE,IAAI,WAAW,KAAK,SAAS;QAAE,OAAO,KAAK,CAAA;IAC3C,OAAO,GAAG,CAAC,IAAI,KAAK,QAAQ,IAAI,GAAG,CAAC,YAAY,CAAC,QAAQ,CAAC,WAAW,CAAC,CAAA;AACxE,CAAC","sourcesContent":["/**\n * Scope document model: where the plugin is allowed to act.\n *\n * `scope.json` is the single source of truth for the exposure surface (design\n * §5.5). This module only parses an already-read value; it never touches the\n * filesystem. Task 9's store owns reading, locking and writing.\n *\n * The input is the JSON-decoded value `JSON.parse` produces for `scope.json`,\n * not an arbitrary host object: exotic in-memory shapes (throwing getters,\n * inherited fields) are outside the contract and are not defended against.\n *\n * Parsing is fail-closed in three ordered stages. **Type delimitation runs\n * before the version checks**: a non-object, `null` or an array is a parse\n * failure even when it carries a `version` property. Then a numeric `version`\n * greater than `2` is a **future version**: it is a valid document written by a\n * newer plugin, so reads degrade but writes must never rewrite it (the field\n * set may be newer than this parser knows). Finally anything whose `version` is\n * not exactly `2` — version 1, a missing or non-numeric version — is an\n * **unknown version**; a version 1 document is the one upgradeable case, and\n * the command decides when to upgrade it.\n *\n * A matching stage rejects immediately, and no failure returns a partial\n * document: every failure comes back as a fresh deep copy of `DEFAULT_SCOPE`,\n * the strictest exposure (`selected + []`), so a malformed or newer-versioned\n * file degrades to \"nobody sees it\" rather than crashing the agent.\n *\n * Individual fields are guarded on the strict side too: an unknown `mode` is\n * `'selected'`, a non-array `workspaceIds` is `[]`, non-string members are\n * dropped, a non-boolean `shadow` is `true`, an unknown `projection` is\n * `'shadow'`, and a non-finite `revision` is `0`. `updatedAt` is never\n * validated beyond being a string.\n *\n * @module dsh-boost/scope/doc\n */\nimport type { ProjectionMode } from '../projection/apply.js'\n\n/** Stable rejection code: the file names a version this parser does not know. */\nexport const ERR_SCOPE_UNKNOWN_VERSION = 'ERR_SCOPE_UNKNOWN_VERSION'\n\n/**\n * Stable rejection code: the file's version is a number newer than this parser\n * (version 3+). Reads degrade like any other failure, but the document is\n * **read-only**: it may carry fields and workspace ids this parser would prune,\n * so writing it back would silently lose the user's configuration.\n */\nexport const ERR_SCOPE_FUTURE_VERSION = 'ERR_SCOPE_FUTURE_VERSION'\n\n/** Stable rejection code: the file is not a scope document at all. */\nexport const ERR_SCOPE_PARSE_FAILED = 'ERR_SCOPE_PARSE_FAILED'\n\n/** Stable rejection code: the file exists but could not be read. */\nexport const ERR_SCOPE_READ_FAILED = 'ERR_SCOPE_READ_FAILED'\n\n/** Stable rejection code: the write's base revision is stale. */\nexport const ERR_SCOPE_REVISION_CONFLICT = 'ERR_SCOPE_REVISION_CONFLICT'\n\n/** Stable rejection code: another writer holds the scope lock. */\nexport const ERR_SCOPE_LOCKED = 'ERR_SCOPE_LOCKED'\n\n/**\n * Stable rejection code: the write was cancelled through its `AbortSignal`.\n *\n * Checked at every await boundary of the write path. A cancellation is not a\n * storage failure — the file is left exactly as it was — so the caller can\n * report it without implying the scope is damaged.\n */\nexport const ERR_SCOPE_ABORTED = 'ERR_SCOPE_ABORTED'\n\n/** Every stable scope failure code (design §5.5 plus the future-version split). */\nexport type ScopeCode =\n | typeof ERR_SCOPE_UNKNOWN_VERSION\n | typeof ERR_SCOPE_FUTURE_VERSION\n | typeof ERR_SCOPE_PARSE_FAILED\n | typeof ERR_SCOPE_READ_FAILED\n | typeof ERR_SCOPE_REVISION_CONFLICT\n | typeof ERR_SCOPE_LOCKED\n | typeof ERR_SCOPE_ABORTED\n\n/** The subset `parseScope` itself can return. */\ntype ParseCode =\n | typeof ERR_SCOPE_UNKNOWN_VERSION\n | typeof ERR_SCOPE_FUTURE_VERSION\n | typeof ERR_SCOPE_PARSE_FAILED\n\n/** A parsed `scope.json` document, version 2 (design §5.5). */\nexport interface ScopeDoc {\n version: 2\n /** Incremented by the store on every successful write. */\n revision: number\n /** Last write time, when the store recorded one; never validated further. */\n updatedAt?: string\n mode: 'selected' | 'global'\n workspaceIds: string[]\n /** Shadow accounting switch (`boost shadow on|off`). */\n shadow: boolean\n /** Projection shape: off, accounting only, or real replacement. */\n projection: ProjectionMode\n}\n\n/**\n * The strictest exposure and the fallback for every failure: nobody sees the\n * plugin until the user opts in.\n */\nexport const DEFAULT_SCOPE: ScopeDoc = {\n version: 2,\n revision: 0,\n mode: 'selected',\n workspaceIds: [],\n shadow: true,\n projection: 'shadow',\n}\n\n/**\n * Type delimitation and version classification, in the order the cases must be\n * checked.\n *\n * The first entry rejects everything that is not a plain object (including\n * `null` and arrays, whatever extra properties they carry). The second marks a\n * numeric version greater than 2 as a future version; it must run **before**\n * the catch-all third entry, which treats every remaining non-2 version\n * (version 1, missing, non-numeric) as unknown. A matching entry ends parsing\n * before the remaining fields are read.\n */\nconst DELIMITERS: ReadonlyArray<{\n readonly code: ParseCode\n readonly matches: (raw: unknown) => boolean\n}> = [\n {\n code: ERR_SCOPE_PARSE_FAILED,\n matches: (raw) => raw === null || typeof raw !== 'object' || Array.isArray(raw),\n },\n {\n code: ERR_SCOPE_FUTURE_VERSION,\n matches: (raw) => {\n const version = (raw as { version?: unknown }).version\n return typeof version === 'number' && version > 2\n },\n },\n {\n code: ERR_SCOPE_UNKNOWN_VERSION,\n matches: (raw) => (raw as { version?: unknown }).version !== 2,\n },\n]\n\n/** A failed parse: always a fresh copy of the strictest document. */\nfunction rejected(code: ParseCode): { doc: ScopeDoc; code: ParseCode } {\n return { doc: structuredClone(DEFAULT_SCOPE), code }\n}\n\n/** Strict side for `mode`: anything but the two literals means `selected`. */\nfunction parseMode(raw: unknown): ScopeDoc['mode'] {\n return raw === 'selected' || raw === 'global' ? raw : 'selected'\n}\n\n/** Strict side for `workspaceIds`: a non-array is empty, non-strings dropped. */\nfunction parseWorkspaceIds(raw: unknown): string[] {\n return Array.isArray(raw) ? raw.filter((id): id is string => typeof id === 'string') : []\n}\n\n/** Strict side for `revision`: anything but a finite number is the initial revision. */\nfunction parseRevision(raw: unknown): number {\n return typeof raw === 'number' && Number.isFinite(raw) ? raw : 0\n}\n\n/** Strict side for `shadow`: a non-boolean keeps shadow accounting on. */\nfunction parseShadow(raw: unknown): boolean {\n return typeof raw === 'boolean' ? raw : true\n}\n\n/** Strict side for `projection`: anything else falls back to shadow accounting. */\nfunction parseProjection(raw: unknown): ProjectionMode {\n return raw === 'off' || raw === 'shadow' || raw === 'on' ? raw : 'shadow'\n}\n\n/**\n * Read one `scope.json` value, as produced by `JSON.parse`.\n *\n * A value whose type or version is wrong is rejected with a stable code and a\n * deep copy of `DEFAULT_SCOPE`; a version 2 object yields a complete document\n * built from its fields, with every malformed field degraded to its strict\n * value.\n */\nexport function parseScope(raw: unknown): {\n doc: ScopeDoc\n code?: 'ERR_SCOPE_UNKNOWN_VERSION' | 'ERR_SCOPE_FUTURE_VERSION' | 'ERR_SCOPE_PARSE_FAILED'\n} {\n const rejection = DELIMITERS.find((delimiter) => delimiter.matches(raw))\n if (rejection) return rejected(rejection.code)\n\n const source = raw as Record<string, unknown>\n return {\n doc: {\n version: 2,\n revision: parseRevision(source.revision),\n ...(typeof source.updatedAt === 'string' ? { updatedAt: source.updatedAt } : {}),\n mode: parseMode(source.mode),\n workspaceIds: parseWorkspaceIds(source.workspaceIds),\n shadow: parseShadow(source.shadow),\n projection: parseProjection(source.projection),\n },\n }\n}\n\n/**\n * The upgrade base for a version 1 document.\n *\n * Reading a v1 file still degrades to {@link DEFAULT_SCOPE} and reports\n * {@link ERR_SCOPE_UNKNOWN_VERSION} (design §5.5 rule 3: unknown versions are\n * read-only). Only the explicit `scope-set` upgrade may rewrite it, and this\n * function answers \"what did the user's v1 file actually say\" for that one\n * write: `version` becomes 2 and `revision` starts at the degraded read's 0,\n * while every recognised field keeps its value (strict side for malformed\n * ones). Never use this on the read path — a v1 document is not a valid v2\n * document and must keep presenting as invisible until upgraded.\n *\n * `undefined` for anything that is not a plain object with `version === 1`,\n * including v2, future versions, missing versions and non-objects.\n */\nexport function parseVersionOneScope(raw: unknown): ScopeDoc | undefined {\n if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) return undefined\n if ((raw as { version?: unknown }).version !== 1) return undefined\n const source = raw as Record<string, unknown>\n return {\n version: 2,\n revision: 0,\n ...(typeof source.updatedAt === 'string' ? { updatedAt: source.updatedAt } : {}),\n mode: parseMode(source.mode),\n workspaceIds: parseWorkspaceIds(source.workspaceIds),\n shadow: parseShadow(source.shadow),\n projection: parseProjection(source.projection),\n }\n}\n\n/**\n * Whether the plugin may act for an agent in `workspaceId`.\n *\n * An agent with no workspace has the global view, and the plugin never injects\n * into the global view (design §5.5), so `undefined` is always invisible.\n * `mode: 'global'` widens to any *defined* workspace id, not to `undefined`.\n */\nexport function isVisible(doc: ScopeDoc, workspaceId: string | undefined): boolean {\n if (workspaceId === undefined) return false\n return doc.mode === 'global' || doc.workspaceIds.includes(workspaceId)\n}\n"]}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import type { ScopeStore } from './store.js';
|
|
2
|
+
/**
|
|
3
|
+
* The host's workspace registry.
|
|
4
|
+
*
|
|
5
|
+
* The host exposes only the synchronous `list()` and the asynchronous
|
|
6
|
+
* `resolveByPath()`; there is no `byPath`. `workspaceIdOf` uses `list()`
|
|
7
|
+
* exclusively so it can stay synchronous. `resolveByPath` is optional here
|
|
8
|
+
* because a test double need not provide the pre-warm path.
|
|
9
|
+
*/
|
|
10
|
+
export interface WorkspaceRegistry {
|
|
11
|
+
list(): readonly {
|
|
12
|
+
id: string;
|
|
13
|
+
path: string;
|
|
14
|
+
}[];
|
|
15
|
+
resolveByPath?(path: string): Promise<{
|
|
16
|
+
id: string;
|
|
17
|
+
} | undefined>;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* The agent shape this module reads.
|
|
21
|
+
*
|
|
22
|
+
* Looser than `AgentLike`: the brief's tests pass agents without an `id` (and
|
|
23
|
+
* `resolveVisible` passes `unknown`), so the header is optional here.
|
|
24
|
+
*/
|
|
25
|
+
type AgentWithCwd = {
|
|
26
|
+
session?: {
|
|
27
|
+
header?: {
|
|
28
|
+
cwd?: string;
|
|
29
|
+
};
|
|
30
|
+
};
|
|
31
|
+
};
|
|
32
|
+
/**
|
|
33
|
+
* Resolve the host workspace UUID for an agent's cwd.
|
|
34
|
+
*
|
|
35
|
+
* The cwd is matched against `registry.list()` by exact `path` equality, so
|
|
36
|
+
* `/w/a` does not match a workspace at `/w/ab` (or at `/w/a/`). This is the
|
|
37
|
+
* **synchronous fallback** for a registry without `resolveByPath`; the async
|
|
38
|
+
* {@link workspaceIdFor} is the production path because `Workspace.path` is a
|
|
39
|
+
* canonical realpath while `Session.header.cwd` is only guaranteed absolute.
|
|
40
|
+
* Any missing or malformed link in the chain — no agent, no session, a
|
|
41
|
+
* non-string cwd, no registry, a `list()` that is not an array, throws, or
|
|
42
|
+
* contains non-object entries — yields `undefined`, which `isVisible` treats as
|
|
43
|
+
* invisible. This function never throws, even when called outside
|
|
44
|
+
* `resolveVisible`.
|
|
45
|
+
*/
|
|
46
|
+
export declare function workspaceIdOf(agent: AgentWithCwd | undefined, registry: WorkspaceRegistry | undefined): string | undefined;
|
|
47
|
+
/**
|
|
48
|
+
* Resolve the workspace UUID, preferring the host's canonical lookup.
|
|
49
|
+
*
|
|
50
|
+
* `Workspace.path` is the canonical realpath (`dsh-workspace/src/types.ts`),
|
|
51
|
+
* while `Session.header.cwd` is only guaranteed absolute
|
|
52
|
+
* (`dsh-session/src/index.ts`), so a symlinked cwd or one with a trailing
|
|
53
|
+
* slash never matches byte-for-byte. `resolveByPath` is the registry's
|
|
54
|
+
* canonical resolver and is used whenever it exists; its `undefined` answer is
|
|
55
|
+
* authoritative (the workspace is not registered), while a registry without it
|
|
56
|
+
* falls back to the synchronous exact match. A throwing resolver is a
|
|
57
|
+
* resolution failure and fails closed (`undefined` -> invisible), never a
|
|
58
|
+
* crash and never a silent exact-match second guess.
|
|
59
|
+
*
|
|
60
|
+
* Never throws.
|
|
61
|
+
*/
|
|
62
|
+
export declare function workspaceIdFor(agent: AgentWithCwd | undefined, registry: WorkspaceRegistry | undefined): Promise<string | undefined>;
|
|
63
|
+
/**
|
|
64
|
+
* Visibility plus the workspace id the judgement was made against.
|
|
65
|
+
*
|
|
66
|
+
* `resolveVisible` is the boolean projection of this result. `apply` also needs
|
|
67
|
+
* the id: the stream hook's `resolveSession` map must carry the same canonical
|
|
68
|
+
* workspace id the judgement used, or a symlinked cwd would be judged visible
|
|
69
|
+
* and then refused by the substitution path.
|
|
70
|
+
*/
|
|
71
|
+
export declare function resolveWorkspace(store: ScopeStore, agent: unknown, registry: WorkspaceRegistry | undefined): Promise<{
|
|
72
|
+
visible: boolean;
|
|
73
|
+
workspaceId?: string;
|
|
74
|
+
}>;
|
|
75
|
+
/**
|
|
76
|
+
* Whether the plugin may act for `agent`, caching the judgement for the
|
|
77
|
+
* synchronous prompt provider.
|
|
78
|
+
*
|
|
79
|
+
* Never throws: a degraded read, a throwing registry, or a malformed `list()`
|
|
80
|
+
* all resolve to `false`. When the agent has a session id the result (including
|
|
81
|
+
* a failure's `false`) is written with `store.remember` before returning, so a
|
|
82
|
+
* subsequent synchronous `judgement(key)` sees the same answer.
|
|
83
|
+
*
|
|
84
|
+
* A degraded store read (missing, unreadable, corrupt or newer-versioned
|
|
85
|
+
* `scope.json`) is a *definitive* `false` for this resolution, not an unknown:
|
|
86
|
+
* it is cached like any other judgement. It is not sticky — the next
|
|
87
|
+
* `resolveVisible` call re-reads the store and overwrites the same key, so a
|
|
88
|
+
* repaired scope document self-heals the cache on the following resolution.
|
|
89
|
+
*/
|
|
90
|
+
export declare function resolveVisible(store: ScopeStore, agent: unknown, registry: WorkspaceRegistry | undefined): Promise<boolean>;
|
|
91
|
+
export {};
|