dsh-boost 0.1.1 → 0.1.3

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.
Files changed (52) hide show
  1. package/README.en.md +141 -51
  2. package/README.md +115 -47
  3. package/dist/admission/usage.js +41 -7
  4. package/dist/admission/usage.js.map +1 -1
  5. package/dist/gate/decide.js +33 -2
  6. package/dist/gate/decide.js.map +1 -1
  7. package/dist/hooks/llm-stream.js +232 -58
  8. package/dist/hooks/llm-stream.js.map +1 -1
  9. package/dist/hooks/post-execute.js +206 -39
  10. package/dist/hooks/post-execute.js.map +1 -1
  11. package/dist/hooks/session-state.js +18 -8
  12. package/dist/hooks/session-state.js.map +1 -1
  13. package/dist/index.js +601 -72
  14. package/dist/index.js.map +1 -1
  15. package/dist/scope/doc.js.map +1 -1
  16. package/dist/scope/store.js +24 -9
  17. package/dist/scope/store.js.map +1 -1
  18. package/dist/tools/boost.js +82 -2
  19. package/dist/tools/boost.js.map +1 -1
  20. package/package.json +9 -5
  21. package/dist/admission/fixed-cost.d.ts +0 -23
  22. package/dist/admission/ledger.d.ts +0 -113
  23. package/dist/admission/retrieval.d.ts +0 -65
  24. package/dist/admission/usage.d.ts +0 -75
  25. package/dist/config.d.ts +0 -43
  26. package/dist/gate/binding.d.ts +0 -113
  27. package/dist/gate/decide.d.ts +0 -82
  28. package/dist/gate/guard.d.ts +0 -69
  29. package/dist/gate/invalidate.d.ts +0 -112
  30. package/dist/gate/plan.d.ts +0 -86
  31. package/dist/hooks/clock.d.ts +0 -68
  32. package/dist/hooks/execute.d.ts +0 -79
  33. package/dist/hooks/llm-stream.d.ts +0 -283
  34. package/dist/hooks/pending.d.ts +0 -89
  35. package/dist/hooks/post-execute.d.ts +0 -257
  36. package/dist/hooks/session-state.d.ts +0 -158
  37. package/dist/hooks/synthesize.d.ts +0 -74
  38. package/dist/host/loader.d.ts +0 -23
  39. package/dist/host/platform.d.ts +0 -18
  40. package/dist/host/root.d.ts +0 -25
  41. package/dist/projection/apply.d.ts +0 -174
  42. package/dist/projection/canonicalise.d.ts +0 -43
  43. package/dist/projection/counters.d.ts +0 -65
  44. package/dist/projection/truncate.d.ts +0 -47
  45. package/dist/prompt/protocol.d.ts +0 -45
  46. package/dist/receipts/store.d.ts +0 -198
  47. package/dist/scope/doc.d.ts +0 -117
  48. package/dist/scope/resolve.d.ts +0 -91
  49. package/dist/scope/store.d.ts +0 -135
  50. package/dist/selector/jev.d.ts +0 -93
  51. package/dist/tools/boost.d.ts +0 -380
  52. package/dist/tools/family.d.ts +0 -26
@@ -1 +1 @@
1
- {"version":3,"file":"store.js","sourceRoot":"","sources":["../../src/scope/store.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8CG;AACH,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAA;AACxC,OAAO,EACL,SAAS,EACT,SAAS,EACT,QAAQ,EACR,YAAY,EACZ,UAAU,EACV,QAAQ,EACR,UAAU,EACV,aAAa,GACd,MAAM,SAAS,CAAA;AAChB,OAAO,EAAE,KAAK,EAAE,IAAI,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAA;AAEtE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAA;AAChC,OAAO,EACL,aAAa,EACb,iBAAiB,EACjB,wBAAwB,EACxB,gBAAgB,EAChB,sBAAsB,EACtB,qBAAqB,EACrB,2BAA2B,EAC3B,UAAU,EACV,oBAAoB,GACrB,MAAM,UAAU,CAAA;AAGjB,MAAM,UAAU,GAAG,YAAY,CAAA;AAC/B,MAAM,SAAS,GAAG,YAAY,CAAA;AAC9B,0FAA0F;AAC1F,MAAM,aAAa,GAAG,MAAM,CAAA;AAC5B;;;;;;;;GAQG;AACH,MAAM,gBAAgB,GAAG,EAAE,GAAG,aAAa,CAAA;AAC3C,qEAAqE;AACrE,MAAM,OAAO,GAAG,aAAa,CAAA;AA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AAC,CAAA;YAC/B,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,CAAA;QAC1B,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,EAAE,KAAK,SAAS,EAAE,CAAC;gBACrB,IAAI,CAAC;oBACH,SAAS,CAAC,EAAE,CAAC,CAAA;gBACf,CAAC;gBAAC,MAAM,CAAC;oBACP,oEAAoE;gBACtE,CAAC;YACH,CAAC;YACD,IAAI,CAAC;gBACH,UAAU,CAAC,QAAQ,CAAC,CAAA;YACtB,CAAC;YAAC,MAAM,CAAC;gBACP,oEAAoE;YACtE,CAAC;YACD,MAAM,KAAK,CAAA;QACb,CAAC;IACH,CAAC;CACF","sourcesContent":["/**\n * Persistent scope store: one small JSON document that says where the plugin is\n * active, plus the per-agent judgement cache the synchronous prompt provider\n * reads.\n *\n * `scope.json` is read on every tool call and written only by the `boost`\n * control tool. Reads never throw: a missing file is the clean default\n * (revision 0, no code — a fresh install has simply configured nothing yet),\n * while an unreadable, corrupt or newer-versioned file means \"nobody sees the\n * plugin\" (`DEFAULT_SCOPE`) plus a stable code for the receipt/status channel.\n * A failed read never touches the file. Writes are compare-and-swap: the caller\n * passes the revision it last saw, the store locks, verifies that revision,\n * mutates, bumps it, and renames a temporary file over `scope.json`. The rename\n * makes a crash leave either the old or the new document, never a half-written\n * one. The revision check makes a lost update require the narrow stale-lock\n * reclaim race documented at `acquireLock`; it cannot silently corrupt or merge\n * a document.\n *\n * ## Sync/async boundary\n *\n * The read path is async (`stat` + `readFile`), because it is called on the\n * hot step path of a live agent and must not block the event loop. The write\n * path is async only while acquiring the lock: everything inside the lock —\n * the disk read, the mutation, the atomic write — is synchronous, so no other\n * writer can interleave between the revision check and the write.\n *\n * ## Cache\n *\n * The cache stores the last validated parse next to the exact bytes and mtime\n * it was parsed from. A read reuses that parse only when both the mtime and the\n * exact bytes match. Byte identity implies the parsed `revision` is unchanged\n * (the invariant design §5.5 asks for), and it is strictly safer than an\n * mtime+revision key: an external edit that preserves both would otherwise be\n * served from the old parse. The cache therefore avoids re-parsing the same\n * bytes, not the read itself — the revision check requires reading\n * `scope.json`. Cache hits keep the cached document object internally and\n * every returned document is a deep copy, so a caller mutating a result cannot\n * poison the cache.\n *\n * The judgement cache is intentionally per agent key (the session id). A\n * single global value would leak one workspace's visibility into every other\n * agent (design §5.5). `remember` is the only writer; `forget` is called from\n * the plugin's `session/disposed` handler so a long-lived process does not keep\n * one entry per session forever.\n *\n * @module dsh-boost/scope/store\n */\nimport { randomUUID } from 'node:crypto'\nimport {\n closeSync,\n fsyncSync,\n openSync,\n readFileSync,\n renameSync,\n statSync,\n unlinkSync,\n writeFileSync,\n} from 'node:fs'\nimport { mkdir, open, readFile, stat, unlink } from 'node:fs/promises'\nimport type { FileHandle } from 'node:fs/promises'\nimport { join } from 'node:path'\nimport {\n DEFAULT_SCOPE,\n ERR_SCOPE_ABORTED,\n ERR_SCOPE_FUTURE_VERSION,\n ERR_SCOPE_LOCKED,\n ERR_SCOPE_PARSE_FAILED,\n ERR_SCOPE_READ_FAILED,\n ERR_SCOPE_REVISION_CONFLICT,\n parseScope,\n parseVersionOneScope,\n} from './doc.js'\nimport type { ScopeCode, ScopeDoc } from './doc.js'\n\nconst SCOPE_FILE = 'scope.json'\nconst LOCK_FILE = 'scope.lock'\n/** A lock older than this is a reclaim candidate when its pid is dead (or unrecorded). */\nconst LOCK_STALE_MS = 60_000\n/**\n * After this much time a lock is taken over even when its recorded pid is alive.\n *\n * `startedAt` (not `mtime`) is the age source when present. The write section\n * inside the lock is synchronous and tiny, so a ten-minute hold means a crashed\n * writer whose pid the OS reused; without this bound such a lock wedges every\n * `boost scope` write until it is deleted by hand. Ten times the dead-pid\n * timeout keeps a genuinely slow writer safe.\n */\nconst LOCK_TAKEOVER_MS = 10 * LOCK_STALE_MS\n/** Largest value `process.kill` accepts as a pid (signed 32-bit). */\nconst MAX_PID = 2_147_483_647\n/** Stable code logged when a live-pid lock is reclaimed on age alone. */\nexport const ERR_SCOPE_LOCK_TAKEOVER = 'ERR_SCOPE_LOCK_TAKEOVER'\n/** Per-process identity in the lock file: distinguishes a reused pid from this boot. */\nconst BOOT_NONCE = randomUUID()\n\n/**\n * One disk read.\n *\n * A missing file is its own arm, not a failure: it still carries the strict\n * default to serve, but no code and no degraded flag, because \"nothing has\n * been configured yet\" is the clean state a fresh install starts in. Both read\n * paths and the write path use `missing` to tell a first write from an I/O\n * error; only genuine failures carry a stable `code` and `cause`.\n */\ntype DiskRead =\n | { ok: true; doc: ScopeDoc; mtimeMs: number; text: string }\n | { ok: false; missing: true; doc: ScopeDoc }\n | {\n ok: false\n missing: false\n doc: ScopeDoc\n code: ScopeCode\n cause?: unknown\n /** The v1 field values an explicit upgrade must carry (see `parseVersionOneScope`). */\n upgrade?: ScopeDoc\n }\n\n/** A write-path failure: the stable code is on `.code` and in the message. */\nfunction scopeError(code: ScopeCode, detail: string): Error & { code: ScopeCode } {\n return Object.assign(new Error(`${code}: ${detail}`), { code })\n}\n\n/** The stable cancellation error; the file has not been touched yet. */\nfunction abortedError(): Error & { code: ScopeCode } {\n return scopeError(ERR_SCOPE_ABORTED, 'the scope write was cancelled')\n}\n\n/** Stop before the next side effect when the caller has cancelled. */\nfunction checkAbort(signal: AbortSignal | undefined): void {\n if (signal?.aborted === true) throw abortedError()\n}\n\n/** The errno string of a Node filesystem error, if it has one. */\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\n/** A human-readable detail for a wrapped error. */\nfunction messageOf(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n\n/**\n * Liveness probe for lock reclamation.\n *\n * `EPERM` means the process exists but belongs to another user, so it counts as\n * alive; only `ESRCH` proves the recorded writer is gone. Any other outcome is\n * treated as alive too: reclamation must never evict a writer on a guess.\n * `readLockPid` bounds the pid to the range `process.kill` accepts, so the\n * impossible-pid `ERR_INVALID_ARG_TYPE` path is never reached.\n */\nfunction isProcessAlive(pid: number): boolean {\n try {\n process.kill(pid, 0)\n return true\n } catch (error) {\n return errorCode(error) !== 'ESRCH'\n }\n}\n\n/** A deep copy: cached and returned documents never share mutable state. */\nfunction cloneDoc(doc: ScopeDoc): ScopeDoc {\n return structuredClone(doc)\n}\n\n/**\n * Classify a failed disk read.\n *\n * `ENOENT` is the clean default: the document does not exist yet, so nobody\n * has been configured in and there is nothing to report. Every other failure\n * (permissions, I/O, a directory where a file is expected) is a genuine\n * degraded read and keeps `ERR_SCOPE_READ_FAILED`.\n */\nfunction readFailed(error: unknown): DiskRead {\n if (errorCode(error) === 'ENOENT') {\n return { ok: false, missing: true, doc: cloneDoc(DEFAULT_SCOPE) }\n }\n return {\n ok: false,\n missing: false,\n doc: cloneDoc(DEFAULT_SCOPE),\n code: ERR_SCOPE_READ_FAILED,\n cause: error,\n }\n}\n\n/** Decode one already-read `scope.json`; JSON errors are parse failures too. */\nfunction decode(text: string, mtimeMs: number): DiskRead {\n let raw: unknown\n try {\n raw = JSON.parse(text)\n } catch (error) {\n return {\n ok: false,\n doc: cloneDoc(DEFAULT_SCOPE),\n code: ERR_SCOPE_PARSE_FAILED,\n missing: false,\n cause: error,\n }\n }\n const parsed = parseScope(raw)\n if (parsed.code !== undefined) {\n // A v1 document is read-only-degraded, but the explicit upgrade rewrites\n // its recognised fields rather than resetting them to DEFAULT_SCOPE\n // (review row 38). `parseVersionOneScope` is deliberately not applied to\n // the read path.\n const upgrade = parseVersionOneScope(raw)\n return {\n ok: false,\n doc: parsed.doc,\n code: parsed.code,\n missing: false,\n ...(upgrade === undefined ? {} : { upgrade }),\n }\n }\n return { ok: true, doc: parsed.doc, mtimeMs, text }\n}\n\n/** Test seam and operator hook for the lock's time-based takeover. */\nexport interface ScopeStoreOptions {\n /** Age after which a live-pid lock is ignored (defaults to ten dead-pid timeouts). */\n lockTakeoverMs?: number\n /** Age after which a dead-pid lock is reclaimable (defaults to 60 s). */\n lockStaleMs?: number\n /** Clock, injectable so tests do not sleep. */\n now?: () => number\n /** Sink for the takeover warning; defaults to a process warning. */\n warn?: (message: string) => void\n}\n\nexport class ScopeStore {\n private readonly file: string\n private readonly lockFile: string\n private readonly lockStaleMs: number\n private readonly lockTakeoverMs: number\n private readonly now: () => number\n private readonly warn: (message: string) => void\n private cached?: { mtimeMs: number; text: string; doc: ScopeDoc }\n private lockOwner?: string\n private readonly judgements = new Map<string, boolean>()\n\n constructor(private readonly dir: string, options: ScopeStoreOptions = {}) {\n this.file = join(dir, SCOPE_FILE)\n this.lockFile = join(dir, LOCK_FILE)\n this.lockStaleMs = options.lockStaleMs ?? LOCK_STALE_MS\n this.lockTakeoverMs = options.lockTakeoverMs ?? LOCK_TAKEOVER_MS\n this.now = options.now ?? Date.now\n this.warn = options.warn ?? ((message: string) => process.emitWarning(message))\n }\n\n /**\n * Read the current document. Never throws and never writes: every stat,\n * read, JSON or shape failure comes back as a fresh `DEFAULT_SCOPE` plus\n * `degraded: 'scope-degraded'` and the stable code.\n */\n async read(): Promise<{ doc: ScopeDoc; degraded?: 'scope-degraded'; code?: ScopeCode }> {\n const result = await this.readDisk()\n if (!result.ok) {\n // Ruling 1: a degraded document is never a cache entry. The next call\n // must retry the disk instead of serving the strict default forever.\n this.cached = undefined\n // A missing file is the clean default (revision 0, no degraded code);\n // a genuine failure keeps its stable code.\n if (result.missing) return { doc: cloneDoc(result.doc) }\n return { doc: cloneDoc(result.doc), degraded: 'scope-degraded', code: result.code }\n }\n\n // On a cache hit `result.doc` is the cached object (identical bytes);\n // either way the caller gets a copy, so a mutation cannot poison it.\n this.cached = { mtimeMs: result.mtimeMs, text: result.text, doc: result.doc }\n return { doc: cloneDoc(result.doc) }\n }\n\n /**\n * Compare-and-swap write. Returns the new document (revision `baseRevision + 1`,\n * `updatedAt` now) and leaves it cached.\n *\n * A missing file is a first write: the base is `DEFAULT_SCOPE` at revision 0,\n * so it succeeds only when the caller passes 0. A corrupt or version 1 file\n * is also based on the strict default, which is how `boost scope set`\n * explicitly upgrades a version 1 document. A **future** version (a numeric\n * version greater than 2) is refused with `ERR_SCOPE_FUTURE_VERSION` before\n * the mutation: the newer field set cannot be represented here, so rewriting\n * it would silently drop configuration. An existing file that cannot be read\n * at all is `ERR_SCOPE_READ_FAILED` — never overwritten blindly.\n */\n async write(\n mutate: (doc: ScopeDoc) => ScopeDoc,\n baseRevision: number,\n options: { signal?: AbortSignal } = {},\n ): Promise<ScopeDoc> {\n const signal = options.signal\n checkAbort(signal)\n await this.ensureDirectory()\n checkAbort(signal)\n await this.acquireLock(signal)\n try {\n checkAbort(signal)\n const current = this.readDiskSync()\n checkAbort(signal)\n let base: ScopeDoc\n if (current.ok) {\n base = current.doc\n } else if (current.missing) {\n // A first write starts from the strict default at revision 0.\n base = current.doc\n } else {\n if (current.code === ERR_SCOPE_FUTURE_VERSION) {\n throw scopeError(\n ERR_SCOPE_FUTURE_VERSION,\n `refusing to rewrite ${this.file}: it declares a newer scope version`,\n )\n }\n if (current.code === ERR_SCOPE_READ_FAILED) {\n const detail = current.cause === undefined ? 'unknown read error' : messageOf(current.cause)\n throw scopeError(ERR_SCOPE_READ_FAILED, `cannot read ${this.file}: ${detail}`)\n }\n // A v1 file was read as DEFAULT_SCOPE at revision 0, but its recognised\n // fields are the user's configuration: base the upgrade on those so a\n // partial `scope-set` cannot silently drop `global`/`workspaceIds`.\n base = current.upgrade ?? current.doc\n }\n if (base.revision !== baseRevision) {\n throw scopeError(\n ERR_SCOPE_REVISION_CONFLICT,\n `base revision ${baseRevision} does not match ${base.revision}`,\n )\n }\n\n const doc: ScopeDoc = {\n ...mutate(base),\n revision: baseRevision + 1,\n updatedAt: new Date().toISOString(),\n }\n checkAbort(signal)\n let written: { mtimeMs: number; text: string }\n try {\n written = this.writeAtomic(doc)\n } catch (error) {\n // Serialization and disk failures are storage failures too; rule 8\n // requires a stable code on every error the write path raises.\n throw scopeError(ERR_SCOPE_READ_FAILED, `cannot write ${this.file}: ${messageOf(error)}`)\n }\n // Clone before caching: `doc` may still share arrays with an object the\n // caller (or `mutate`) holds, and the cache must never alias those.\n this.cached = { mtimeMs: written.mtimeMs, text: written.text, doc: cloneDoc(doc) }\n return cloneDoc(doc)\n } finally {\n this.releaseLock()\n }\n }\n\n /** Cache one agent's visibility judgement; the only writer of this cache. */\n remember(key: string, visible: boolean): void {\n this.judgements.set(key, visible)\n }\n\n /**\n * Drop one session's cached judgement on session disposal.\n *\n * The judgement map is per session and otherwise lives as long as the plugin;\n * without this a process that served many sessions would retain one boolean\n * (and its string key) per session forever.\n */\n forget(key: string): void {\n this.judgements.delete(key)\n }\n\n /** Synchronous per-agent lookup: a miss is `fallback`, and fail-closed is `false`. */\n judgement(key: string, fallback?: boolean): boolean {\n return this.judgements.get(key) ?? fallback ?? false\n }\n\n /** Async read path: stat + read + decode, all failures degraded. */\n private async readDisk(): Promise<DiskRead> {\n try {\n const stats = await stat(this.file)\n const text = await readFile(this.file, 'utf8')\n return this.decodeFromCache(text, stats.mtimeMs)\n } catch (error) {\n return readFailed(error)\n }\n }\n\n /**\n * Reuse the previous parse only when the exact bytes and mtime were already\n * parsed. Byte identity is a stronger key than mtime+revision: an external\n * edit that keeps both cannot be served from the old parse.\n */\n private decodeFromCache(text: string, mtimeMs: number): DiskRead {\n const cached = this.cached\n if (cached !== undefined && cached.mtimeMs === mtimeMs && cached.text === text) {\n return { ok: true, doc: cached.doc, mtimeMs, text }\n }\n return decode(text, mtimeMs)\n }\n\n /** Sync read path, used only inside the write lock (see the module comment). */\n private readDiskSync(): DiskRead {\n try {\n const stats = statSync(this.file)\n const text = readFileSync(this.file, 'utf8')\n return decode(text, stats.mtimeMs)\n } catch (error) {\n return readFailed(error)\n }\n }\n\n /** The write path must be able to create `<root>/boost` on a fresh install. */\n private async ensureDirectory(): Promise<void> {\n try {\n await mkdir(this.dir, { recursive: true })\n } catch (error) {\n throw scopeError(ERR_SCOPE_READ_FAILED, `cannot create ${this.dir}: ${messageOf(error)}`)\n }\n }\n\n /**\n * Take the write lock, reclaiming a stale lock at most once.\n *\n * Two independent staleness rules:\n *\n * 1. dead-owner reclaim — older than `lockStaleMs` **and** the recorded pid is\n * dead (or unrecorded/unparseable/out of pid range);\n * 2. bounded takeover — the lock's `startedAt` (falling back to mtime) is\n * older than `lockTakeoverMs`, **even when its pid is alive**. A pid is\n * reused after a crash, so rule 1 alone can leave `scope.lock` held for the\n * whole process lifetime in a container. The hold window is one small\n * synchronous write, so a lock this old is a crashed writer.\n *\n * The takeover re-reads the lock immediately before unlinking and refuses if\n * its bytes or mtime changed, which narrows the cross-process race. Two\n * writers can still judge the same lock stale; `releaseLock` only removes a\n * lock whose content it wrote, and the CAS revision check still refuses to\n * merge divergent writes, so the residual race cannot corrupt the document.\n *\n * When that first read finds **no** lock there is nothing to compare against,\n * so the reclaim is refused with `ERR_SCOPE_LOCKED`. `createLock` already saw\n * the file exist; a lock created between that failure and the read is\n * indistinguishable from one a live writer still owns, and unlinking it\n * would lose that writer's update. Refusing is safe (the caller retries) and\n * the alternative is the one case the changed-lock guard cannot cover.\n */\n private async acquireLock(signal?: AbortSignal): Promise<void> {\n checkAbort(signal)\n if (await this.createLock()) {\n // `createLock` is the one await that can leave a lock behind; an abort\n // observed after it returns must release it, not strand it.\n if (signal?.aborted === true) {\n this.releaseLock()\n throw abortedError()\n }\n return\n }\n checkAbort(signal)\n const first = this.readLock()\n const decision = this.classifyLock(first)\n if (decision === 'held') {\n throw scopeError(ERR_SCOPE_LOCKED, `${this.lockFile} is held by another writer`)\n }\n if (decision === 'missing') {\n throw scopeError(\n ERR_SCOPE_LOCKED,\n `${this.lockFile} existed for createLock but vanished before it could be inspected; another writer may hold it now`,\n )\n }\n if (decision === 'takeover') {\n this.warn(\n `${ERR_SCOPE_LOCK_TAKEOVER}: taking over ${this.lockFile} from pid ${\n first?.pid ?? 'unknown'\n } after ${Math.round(this.ageOf(first) / 1000)}s; the recording process may have crashed and its pid been reused`,\n )\n }\n\n // Re-read before the unlink: a writer that replaced the lock between the\n // decision and here must not be evicted on a stale observation.\n const again = this.readLock()\n if (again !== undefined && first !== undefined) {\n if (again.text !== first.text || again.mtimeMs !== first.mtimeMs) {\n throw scopeError(ERR_SCOPE_LOCKED, `${this.lockFile} changed while being reclaimed`)\n }\n }\n try {\n unlinkSync(this.lockFile)\n } catch (error) {\n if (errorCode(error) !== 'ENOENT') {\n throw scopeError(ERR_SCOPE_LOCKED, `cannot reclaim ${this.lockFile}: ${messageOf(error)}`)\n }\n }\n if (!(await this.createLock())) {\n throw scopeError(ERR_SCOPE_LOCKED, `${this.lockFile} is held by another writer`)\n }\n if (signal?.aborted === true) {\n this.releaseLock()\n throw abortedError()\n }\n }\n\n /** `open(lock, 'wx')`; false means another writer holds it. */\n private async createLock(): Promise<boolean> {\n let handle: FileHandle\n try {\n handle = await open(this.lockFile, 'wx')\n } catch (error) {\n if (errorCode(error) === 'EEXIST') return false\n throw scopeError(ERR_SCOPE_LOCKED, `cannot create ${this.lockFile}: ${messageOf(error)}`)\n }\n\n const content = JSON.stringify({\n pid: process.pid,\n startedAt: this.now(),\n nonce: BOOT_NONCE,\n })\n let failure: unknown\n try {\n await handle.writeFile(content)\n } catch (error) {\n failure = error\n } finally {\n await handle.close().catch(() => {})\n }\n if (failure !== undefined) {\n // A lock without owner data would block for the stale timeout; remove\n // what we created.\n await unlink(this.lockFile).catch(() => {})\n throw scopeError(ERR_SCOPE_LOCKED, `cannot write ${this.lockFile}: ${messageOf(failure)}`)\n }\n this.lockOwner = content\n return true\n }\n\n /**\n * One read of the lock: bytes, mtime and the owner fields they record.\n *\n * `undefined` means absent (the `EEXIST` raced a release): the caller may\n * retry the create. An unreadable-but-present lock is returned with the mtime\n * and no owner fields, so it becomes reclaimable only after the dead-pid\n * timeout — never immediately, because an unreadable live lock must not be\n * evicted on a guess.\n */\n private readLock(): { text: string; mtimeMs: number; pid?: number; startedAt?: number } | undefined {\n let mtimeMs: number\n try {\n mtimeMs = statSync(this.lockFile).mtimeMs\n } catch {\n return undefined\n }\n let text: string\n try {\n text = readFileSync(this.lockFile, 'utf8')\n } catch {\n return { text: '', mtimeMs }\n }\n let parsed: unknown\n try {\n parsed = JSON.parse(text)\n } catch {\n return { text, mtimeMs }\n }\n const record = typeof parsed === 'object' && parsed !== null ? (parsed as Record<string, unknown>) : {}\n const pid = record.pid\n const startedAt = record.startedAt\n return {\n text,\n mtimeMs,\n ...(typeof pid === 'number' && Number.isInteger(pid) && pid > 0 && pid <= MAX_PID ? { pid } : {}),\n ...(typeof startedAt === 'number' && Number.isFinite(startedAt) && startedAt > 0 && startedAt <= this.now()\n ? { startedAt }\n : {}),\n }\n }\n\n /** Age from `startedAt` when it is usable, otherwise from the file's mtime. */\n private ageOf(lock: { mtimeMs: number; startedAt?: number } | undefined): number {\n if (lock === undefined) return 0\n return Math.max(0, this.now() - (lock.startedAt ?? lock.mtimeMs))\n }\n\n /** Whether the lock is reclaimable, and whether that decision needs a warning. */\n private classifyLock(\n lock: { mtimeMs: number; pid?: number; startedAt?: number } | undefined,\n ): 'held' | 'dead' | 'takeover' | 'missing' {\n if (lock === undefined) return 'missing'\n const age = this.ageOf(lock)\n if (age <= this.lockStaleMs) return 'held'\n if (age >= this.lockTakeoverMs) return 'takeover'\n return lock.pid === undefined || !isProcessAlive(lock.pid) ? 'dead' : 'held'\n }\n\n /**\n * Remove the lock only if it still contains exactly what this acquisition\n * wrote. An unconditional unlink would delete a replacement lock another\n * writer created after a stale-reclaim race. Every error is swallowed:\n * cleanup must never mask the causal error (rule 8), and a lock left behind\n * is reclaimable after 60 s while a masked conflict is not diagnosable.\n */\n private releaseLock(): void {\n const owner = this.lockOwner\n this.lockOwner = undefined\n if (owner === undefined) return\n try {\n if (readFileSync(this.lockFile, 'utf8') === owner) unlinkSync(this.lockFile)\n } catch {\n // See the method comment: cleanup never rethrows.\n }\n }\n\n /**\n * Serialize `doc` into a temporary file, fsync it, and rename it over\n * `scope.json`. Returns the stored file's mtime and the exact text written\n * (for the cache). A failed write removes the temporary file; the caller's\n * `finally` removes the lock.\n */\n private writeAtomic(doc: ScopeDoc): { mtimeMs: number; text: string } {\n const tempFile = join(this.dir, `.${SCOPE_FILE}.${process.pid}.${randomUUID()}.tmp`)\n const text = `${JSON.stringify(doc)}\\n`\n let fd: number | undefined\n try {\n fd = openSync(tempFile, 'w')\n writeFileSync(fd, text)\n fsyncSync(fd)\n closeSync(fd)\n fd = undefined\n // Stat before the rename: if this fails nothing has touched `scope.json`,\n // and the mtime of the inode is what `read()` will observe afterwards.\n const mtimeMs = statSync(tempFile).mtimeMs\n renameSync(tempFile, this.file)\n return { mtimeMs, text }\n } catch (error) {\n if (fd !== undefined) {\n try {\n closeSync(fd)\n } catch {\n // Already closed or never opened; the unlink below is what matters.\n }\n }\n try {\n unlinkSync(tempFile)\n } catch {\n // Best effort: the temporary file may not exist if openSync failed.\n }\n throw error\n }\n }\n}\n"]}
1
+ {"version":3,"file":"store.js","sourceRoot":"","sources":["../../src/scope/store.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8CG;AACH,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAA;AACxC,OAAO,EACL,SAAS,EACT,SAAS,EACT,QAAQ,EACR,YAAY,EACZ,UAAU,EACV,QAAQ,EACR,UAAU,EACV,aAAa,GACd,MAAM,SAAS,CAAA;AAChB,OAAO,EAAE,KAAK,EAAE,IAAI,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAA;AAEtE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAA;AAChC,OAAO,EACL,aAAa,EACb,iBAAiB,EACjB,wBAAwB,EACxB,gBAAgB,EAChB,sBAAsB,EACtB,qBAAqB,EACrB,2BAA2B,EAC3B,yBAAyB,EACzB,UAAU,EACV,oBAAoB,GACrB,MAAM,UAAU,CAAA;AAGjB,MAAM,UAAU,GAAG,YAAY,CAAA;AAC/B,MAAM,SAAS,GAAG,YAAY,CAAA;AAC9B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AC,IAAI,CAAC,GAAG,EAAE,IAAI,UAAU,IAAI,OAAO,CAAC,GAAG,IAAI,UAAU,EAAE,MAAM,CAAC,CAAA;QACpF,MAAM,IAAI,GAAG,GAAG,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,IAAI,CAAA;QACvC,IAAI,EAAsB,CAAA;QAC1B,IAAI,CAAC;YACH,EAAE,GAAG,QAAQ,CAAC,QAAQ,EAAE,GAAG,CAAC,CAAA;YAC5B,aAAa,CAAC,EAAE,EAAE,IAAI,CAAC,CAAA;YACvB,SAAS,CAAC,EAAE,CAAC,CAAA;YACb,SAAS,CAAC,EAAE,CAAC,CAAA;YACb,EAAE,GAAG,SAAS,CAAA;YACd,0EAA0E;YAC1E,uEAAuE;YACvE,MAAM,OAAO,GAAG,QAAQ,CAAC,QAAQ,CAAC,CAAC,OAAO,CAAA;YAC1C,UAAU,CAAC,QAAQ,EAAE,IAAI,CAAC,IAAI,CAAC,CAAA;YAC/B,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,CAAA;QAC1B,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,EAAE,KAAK,SAAS,EAAE,CAAC;gBACrB,IAAI,CAAC;oBACH,SAAS,CAAC,EAAE,CAAC,CAAA;gBACf,CAAC;gBAAC,MAAM,CAAC;oBACP,oEAAoE;gBACtE,CAAC;YACH,CAAC;YACD,IAAI,CAAC;gBACH,UAAU,CAAC,QAAQ,CAAC,CAAA;YACtB,CAAC;YAAC,MAAM,CAAC;gBACP,oEAAoE;YACtE,CAAC;YACD,MAAM,KAAK,CAAA;QACb,CAAC;IACH,CAAC;CACF","sourcesContent":["/**\n * Persistent scope store: one small JSON document that says where the plugin is\n * active, plus the per-agent judgement cache the synchronous prompt provider\n * reads.\n *\n * `scope.json` is read on every tool call and written only by the `boost`\n * control tool. Reads never throw: a missing file is the clean default\n * (revision 0, no code — a fresh install has simply configured nothing yet),\n * while an unreadable, corrupt or newer-versioned file means \"nobody sees the\n * plugin\" (`DEFAULT_SCOPE`) plus a stable code for the receipt/status channel.\n * A failed read never touches the file. Writes are compare-and-swap: the caller\n * passes the revision it last saw, the store locks, verifies that revision,\n * mutates, bumps it, and renames a temporary file over `scope.json`. The rename\n * makes a crash leave either the old or the new document, never a half-written\n * one. The revision check makes a lost update require the narrow stale-lock\n * reclaim race documented at `acquireLock`; it cannot silently corrupt or merge\n * a document.\n *\n * ## Sync/async boundary\n *\n * The read path is async (`stat` + `readFile`), because it is called on the\n * hot step path of a live agent and must not block the event loop. The write\n * path is async only while acquiring the lock: everything inside the lock —\n * the disk read, the mutation, the atomic write — is synchronous, so no other\n * writer can interleave between the revision check and the write.\n *\n * ## Cache\n *\n * The cache stores the last validated parse next to the exact bytes and mtime\n * it was parsed from. A read reuses that parse only when both the mtime and the\n * exact bytes match. Byte identity implies the parsed `revision` is unchanged\n * (the invariant design §5.5 asks for), and it is strictly safer than an\n * mtime+revision key: an external edit that preserves both would otherwise be\n * served from the old parse. The cache therefore avoids re-parsing the same\n * bytes, not the read itself — the revision check requires reading\n * `scope.json`. Cache hits keep the cached document object internally and\n * every returned document is a deep copy, so a caller mutating a result cannot\n * poison the cache.\n *\n * The judgement cache is intentionally per agent key (the session id). A\n * single global value would leak one workspace's visibility into every other\n * agent (design §5.5). `remember` is the only writer; `forget` is called from\n * the plugin's `session/disposed` handler so a long-lived process does not keep\n * one entry per session forever.\n *\n * @module dsh-boost/scope/store\n */\nimport { randomUUID } from 'node:crypto'\nimport {\n closeSync,\n fsyncSync,\n openSync,\n readFileSync,\n renameSync,\n statSync,\n unlinkSync,\n writeFileSync,\n} from 'node:fs'\nimport { mkdir, open, readFile, stat, unlink } from 'node:fs/promises'\nimport type { FileHandle } from 'node:fs/promises'\nimport { join } from 'node:path'\nimport {\n DEFAULT_SCOPE,\n ERR_SCOPE_ABORTED,\n ERR_SCOPE_FUTURE_VERSION,\n ERR_SCOPE_LOCKED,\n ERR_SCOPE_PARSE_FAILED,\n ERR_SCOPE_READ_FAILED,\n ERR_SCOPE_REVISION_CONFLICT,\n ERR_SCOPE_UNKNOWN_VERSION,\n parseScope,\n parseVersionOneScope,\n} from './doc.js'\nimport type { ScopeCode, ScopeDoc } from './doc.js'\n\nconst SCOPE_FILE = 'scope.json'\nconst LOCK_FILE = 'scope.lock'\n/** A lock older than this is a reclaim candidate when its pid is dead (or unrecorded). */\nconst LOCK_STALE_MS = 60_000\n/**\n * After this much time a lock is taken over even when its recorded pid is alive.\n *\n * `startedAt` (not `mtime`) is the age source when present. The write section\n * inside the lock is synchronous and tiny, so a ten-minute hold means a crashed\n * writer whose pid the OS reused; without this bound such a lock wedges every\n * `boost scope` write until it is deleted by hand. Ten times the dead-pid\n * timeout keeps a genuinely slow writer safe.\n */\nconst LOCK_TAKEOVER_MS = 10 * LOCK_STALE_MS\n/** Largest value `process.kill` accepts as a pid (signed 32-bit). */\nconst MAX_PID = 2_147_483_647\n/** Stable code logged when a live-pid lock is reclaimed on age alone. */\nexport const ERR_SCOPE_LOCK_TAKEOVER = 'ERR_SCOPE_LOCK_TAKEOVER'\n/** Per-process identity in the lock file: distinguishes a reused pid from this boot. */\nconst BOOT_NONCE = randomUUID()\n\n/**\n * One disk read.\n *\n * A missing file is its own arm, not a failure: it still carries the strict\n * default to serve, but no code and no degraded flag, because \"nothing has\n * been configured yet\" is the clean state a fresh install starts in. Both read\n * paths and the write path use `missing` to tell a first write from an I/O\n * error; only genuine failures carry a stable `code` and `cause`.\n */\ntype DiskRead =\n | { ok: true; doc: ScopeDoc; mtimeMs: number; text: string }\n | { ok: false; missing: true; doc: ScopeDoc }\n | {\n ok: false\n missing: false\n doc: ScopeDoc\n code: ScopeCode\n cause?: unknown\n /** The v1 field values an explicit upgrade must carry (see `parseVersionOneScope`). */\n upgrade?: ScopeDoc\n }\n\n/** A write-path failure: the stable code is on `.code` and in the message. */\nfunction scopeError(code: ScopeCode, detail: string): Error & { code: ScopeCode } {\n return Object.assign(new Error(`${code}: ${detail}`), { code })\n}\n\n/** The stable cancellation error; the file has not been touched yet. */\nfunction abortedError(): Error & { code: ScopeCode } {\n return scopeError(ERR_SCOPE_ABORTED, 'the scope write was cancelled')\n}\n\n/** Stop before the next side effect when the caller has cancelled. */\nfunction checkAbort(signal: AbortSignal | undefined): void {\n if (signal?.aborted === true) throw abortedError()\n}\n\n/** The errno string of a Node filesystem error, if it has one. */\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\n/** A human-readable detail for a wrapped error. */\nfunction messageOf(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n\n/**\n * Liveness probe for lock reclamation.\n *\n * `EPERM` means the process exists but belongs to another user, so it counts as\n * alive; only `ESRCH` proves the recorded writer is gone. Any other outcome is\n * treated as alive too: reclamation must never evict a writer on a guess.\n * `readLockPid` bounds the pid to the range `process.kill` accepts, so the\n * impossible-pid `ERR_INVALID_ARG_TYPE` path is never reached.\n */\nfunction isProcessAlive(pid: number): boolean {\n try {\n process.kill(pid, 0)\n return true\n } catch (error) {\n return errorCode(error) !== 'ESRCH'\n }\n}\n\n/** A deep copy: cached and returned documents never share mutable state. */\nfunction cloneDoc(doc: ScopeDoc): ScopeDoc {\n return structuredClone(doc)\n}\n\n/**\n * Classify a failed disk read.\n *\n * `ENOENT` is the clean default: the document does not exist yet, so nobody\n * has been configured in and there is nothing to report. Every other failure\n * (permissions, I/O, a directory where a file is expected) is a genuine\n * degraded read and keeps `ERR_SCOPE_READ_FAILED`.\n */\nfunction readFailed(error: unknown): DiskRead {\n if (errorCode(error) === 'ENOENT') {\n return { ok: false, missing: true, doc: cloneDoc(DEFAULT_SCOPE) }\n }\n return {\n ok: false,\n missing: false,\n doc: cloneDoc(DEFAULT_SCOPE),\n code: ERR_SCOPE_READ_FAILED,\n cause: error,\n }\n}\n\n/** Decode one already-read `scope.json`; JSON errors are parse failures too. */\nfunction decode(text: string, mtimeMs: number): DiskRead {\n let raw: unknown\n try {\n raw = JSON.parse(text)\n } catch (error) {\n return {\n ok: false,\n doc: cloneDoc(DEFAULT_SCOPE),\n code: ERR_SCOPE_PARSE_FAILED,\n missing: false,\n cause: error,\n }\n }\n const parsed = parseScope(raw)\n if (parsed.code !== undefined) {\n // A v1 document is read-only-degraded, but the explicit upgrade rewrites\n // its recognised fields rather than resetting them to DEFAULT_SCOPE\n // (review row 38). `parseVersionOneScope` is deliberately not applied to\n // the read path.\n const upgrade = parseVersionOneScope(raw)\n return {\n ok: false,\n doc: parsed.doc,\n code: parsed.code,\n missing: false,\n ...(upgrade === undefined ? {} : { upgrade }),\n }\n }\n return { ok: true, doc: parsed.doc, mtimeMs, text }\n}\n\n/** Test seam and operator hook for the lock's time-based takeover. */\nexport interface ScopeStoreOptions {\n /** Age after which a live-pid lock is ignored (defaults to ten dead-pid timeouts). */\n lockTakeoverMs?: number\n /** Age after which a dead-pid lock is reclaimable (defaults to 60 s). */\n lockStaleMs?: number\n /** Clock, injectable so tests do not sleep. */\n now?: () => number\n /** Sink for the takeover warning; defaults to a process warning. */\n warn?: (message: string) => void\n}\n\nexport class ScopeStore {\n private readonly file: string\n private readonly lockFile: string\n private readonly lockStaleMs: number\n private readonly lockTakeoverMs: number\n private readonly now: () => number\n private readonly warn: (message: string) => void\n private cached?: { mtimeMs: number; text: string; doc: ScopeDoc }\n private lockOwner?: string\n private readonly judgements = new Map<string, boolean>()\n\n constructor(private readonly dir: string, options: ScopeStoreOptions = {}) {\n this.file = join(dir, SCOPE_FILE)\n this.lockFile = join(dir, LOCK_FILE)\n this.lockStaleMs = options.lockStaleMs ?? LOCK_STALE_MS\n this.lockTakeoverMs = options.lockTakeoverMs ?? LOCK_TAKEOVER_MS\n this.now = options.now ?? Date.now\n this.warn = options.warn ?? ((message: string) => process.emitWarning(message))\n }\n\n /**\n * Read the current document. Never throws and never writes: every stat,\n * read, JSON or shape failure comes back as a fresh `DEFAULT_SCOPE` plus\n * `degraded: 'scope-degraded'` and the stable code.\n */\n async read(): Promise<{ doc: ScopeDoc; degraded?: 'scope-degraded'; code?: ScopeCode }> {\n const result = await this.readDisk()\n if (!result.ok) {\n // Ruling 1: a degraded document is never a cache entry. The next call\n // must retry the disk instead of serving the strict default forever.\n this.cached = undefined\n // A missing file is the clean default (revision 0, no degraded code);\n // a genuine failure keeps its stable code.\n if (result.missing) return { doc: cloneDoc(result.doc) }\n return { doc: cloneDoc(result.doc), degraded: 'scope-degraded', code: result.code }\n }\n\n // On a cache hit `result.doc` is the cached object (identical bytes);\n // either way the caller gets a copy, so a mutation cannot poison it.\n this.cached = { mtimeMs: result.mtimeMs, text: result.text, doc: result.doc }\n return { doc: cloneDoc(result.doc) }\n }\n\n /**\n * Compare-and-swap write. Returns the new document (revision `baseRevision + 1`,\n * `updatedAt` now) and leaves it cached.\n *\n * A missing file is a first write: the base is `DEFAULT_SCOPE` at revision 0,\n * so it succeeds only when the caller passes 0. A version 1 file is based on\n * the fields it actually carries, which is how `boost scope set` explicitly\n * upgrades it. Every other present-but-unusable document is refused before\n * the mutation: a **future** version (a numeric version greater than 2) with\n * `ERR_SCOPE_FUTURE_VERSION`, a non-document with\n * `ERR_SCOPE_PARSE_FAILED`, a missing or non-numeric version with\n * `ERR_SCOPE_UNKNOWN_VERSION`, and an unreadable file with\n * `ERR_SCOPE_READ_FAILED`. Each refusal leaves the file byte-identical.\n */\n async write(\n mutate: (doc: ScopeDoc) => ScopeDoc,\n baseRevision: number,\n options: { signal?: AbortSignal } = {},\n ): Promise<ScopeDoc> {\n const signal = options.signal\n checkAbort(signal)\n await this.ensureDirectory()\n checkAbort(signal)\n await this.acquireLock(signal)\n try {\n checkAbort(signal)\n const current = this.readDiskSync()\n checkAbort(signal)\n let base: ScopeDoc\n if (current.ok) {\n base = current.doc\n } else if (current.missing) {\n // A first write starts from the strict default at revision 0.\n base = current.doc\n } else {\n if (current.code === ERR_SCOPE_FUTURE_VERSION) {\n throw scopeError(\n ERR_SCOPE_FUTURE_VERSION,\n `refusing to rewrite ${this.file}: it declares a newer scope version`,\n )\n }\n if (current.code === ERR_SCOPE_READ_FAILED) {\n const detail = current.cause === undefined ? 'unknown read error' : messageOf(current.cause)\n throw scopeError(ERR_SCOPE_READ_FAILED, `cannot read ${this.file}: ${detail}`)\n }\n // Both remaining codes mean the bytes are present but unusable. Key on\n // the code, not on this branch: only a v1 document (whose `upgrade`\n // `decode` supplied) has recognised fields worth preserving, and only\n // its documented `scope-set` upgrade may rewrite the file. A parse\n // failure has no fields at all, and a missing or non-numeric version is\n // equally unrepresentable; basing a write on DEFAULT_SCOPE for either\n // would silently replace the user's document, which `docs/RELEASE.md`\n // promises not to do (\"写拒绝\" / \"写不盲改\").\n if (current.code === ERR_SCOPE_PARSE_FAILED) {\n throw scopeError(\n ERR_SCOPE_PARSE_FAILED,\n `refusing to rewrite ${this.file}: it is not a scope document`,\n )\n }\n if (current.upgrade === undefined) {\n throw scopeError(\n ERR_SCOPE_UNKNOWN_VERSION,\n `refusing to rewrite ${this.file}: it declares an unknown scope version`,\n )\n }\n // A v1 file was read as DEFAULT_SCOPE at revision 0, but its recognised\n // fields are the user's configuration: base the upgrade on those so a\n // partial `scope-set` cannot silently drop `global`/`workspaceIds`.\n base = current.upgrade\n }\n if (base.revision !== baseRevision) {\n throw scopeError(\n ERR_SCOPE_REVISION_CONFLICT,\n `base revision ${baseRevision} does not match ${base.revision}`,\n )\n }\n\n const doc: ScopeDoc = {\n ...mutate(base),\n revision: baseRevision + 1,\n updatedAt: new Date().toISOString(),\n }\n checkAbort(signal)\n let written: { mtimeMs: number; text: string }\n try {\n written = this.writeAtomic(doc)\n } catch (error) {\n // Serialization and disk failures are storage failures too; rule 8\n // requires a stable code on every error the write path raises.\n throw scopeError(ERR_SCOPE_READ_FAILED, `cannot write ${this.file}: ${messageOf(error)}`)\n }\n // Clone before caching: `doc` may still share arrays with an object the\n // caller (or `mutate`) holds, and the cache must never alias those.\n this.cached = { mtimeMs: written.mtimeMs, text: written.text, doc: cloneDoc(doc) }\n return cloneDoc(doc)\n } finally {\n this.releaseLock()\n }\n }\n\n /** Cache one agent's visibility judgement; the only writer of this cache. */\n remember(key: string, visible: boolean): void {\n this.judgements.set(key, visible)\n }\n\n /**\n * Drop one session's cached judgement on session disposal.\n *\n * The judgement map is per session and otherwise lives as long as the plugin;\n * without this a process that served many sessions would retain one boolean\n * (and its string key) per session forever.\n */\n forget(key: string): void {\n this.judgements.delete(key)\n }\n\n /** Synchronous per-agent lookup: a miss is `fallback`, and fail-closed is `false`. */\n judgement(key: string, fallback?: boolean): boolean {\n return this.judgements.get(key) ?? fallback ?? false\n }\n\n /** Async read path: stat + read + decode, all failures degraded. */\n private async readDisk(): Promise<DiskRead> {\n try {\n const stats = await stat(this.file)\n const text = await readFile(this.file, 'utf8')\n return this.decodeFromCache(text, stats.mtimeMs)\n } catch (error) {\n return readFailed(error)\n }\n }\n\n /**\n * Reuse the previous parse only when the exact bytes and mtime were already\n * parsed. Byte identity is a stronger key than mtime+revision: an external\n * edit that keeps both cannot be served from the old parse.\n */\n private decodeFromCache(text: string, mtimeMs: number): DiskRead {\n const cached = this.cached\n if (cached !== undefined && cached.mtimeMs === mtimeMs && cached.text === text) {\n return { ok: true, doc: cached.doc, mtimeMs, text }\n }\n return decode(text, mtimeMs)\n }\n\n /** Sync read path, used only inside the write lock (see the module comment). */\n private readDiskSync(): DiskRead {\n try {\n const stats = statSync(this.file)\n const text = readFileSync(this.file, 'utf8')\n return decode(text, stats.mtimeMs)\n } catch (error) {\n return readFailed(error)\n }\n }\n\n /** The write path must be able to create `<root>/boost` on a fresh install. */\n private async ensureDirectory(): Promise<void> {\n try {\n await mkdir(this.dir, { recursive: true })\n } catch (error) {\n throw scopeError(ERR_SCOPE_READ_FAILED, `cannot create ${this.dir}: ${messageOf(error)}`)\n }\n }\n\n /**\n * Take the write lock, reclaiming a stale lock at most once.\n *\n * Two independent staleness rules:\n *\n * 1. dead-owner reclaim — older than `lockStaleMs` **and** the recorded pid is\n * dead (or unrecorded/unparseable/out of pid range);\n * 2. bounded takeover — the lock's `startedAt` (falling back to mtime) is\n * older than `lockTakeoverMs`, **even when its pid is alive**. A pid is\n * reused after a crash, so rule 1 alone can leave `scope.lock` held for the\n * whole process lifetime in a container. The hold window is one small\n * synchronous write, so a lock this old is a crashed writer.\n *\n * The takeover re-reads the lock immediately before unlinking and refuses if\n * its bytes or mtime changed, which narrows the cross-process race. Two\n * writers can still judge the same lock stale; `releaseLock` only removes a\n * lock whose content it wrote, and the CAS revision check still refuses to\n * merge divergent writes, so the residual race cannot corrupt the document.\n *\n * When that first read finds **no** lock there is nothing to compare against,\n * so the reclaim is refused with `ERR_SCOPE_LOCKED`. `createLock` already saw\n * the file exist; a lock created between that failure and the read is\n * indistinguishable from one a live writer still owns, and unlinking it\n * would lose that writer's update. Refusing is safe (the caller retries) and\n * the alternative is the one case the changed-lock guard cannot cover.\n */\n private async acquireLock(signal?: AbortSignal): Promise<void> {\n checkAbort(signal)\n if (await this.createLock()) {\n // `createLock` is the one await that can leave a lock behind; an abort\n // observed after it returns must release it, not strand it.\n if (signal?.aborted === true) {\n this.releaseLock()\n throw abortedError()\n }\n return\n }\n checkAbort(signal)\n const first = this.readLock()\n const decision = this.classifyLock(first)\n if (decision === 'held') {\n throw scopeError(ERR_SCOPE_LOCKED, `${this.lockFile} is held by another writer`)\n }\n if (decision === 'missing') {\n throw scopeError(\n ERR_SCOPE_LOCKED,\n `${this.lockFile} existed for createLock but vanished before it could be inspected; another writer may hold it now`,\n )\n }\n if (decision === 'takeover') {\n this.warn(\n `${ERR_SCOPE_LOCK_TAKEOVER}: taking over ${this.lockFile} from pid ${\n first?.pid ?? 'unknown'\n } after ${Math.round(this.ageOf(first) / 1000)}s; the recording process may have crashed and its pid been reused`,\n )\n }\n\n // Re-read before the unlink: a writer that replaced the lock between the\n // decision and here must not be evicted on a stale observation.\n const again = this.readLock()\n if (again !== undefined && first !== undefined) {\n if (again.text !== first.text || again.mtimeMs !== first.mtimeMs) {\n throw scopeError(ERR_SCOPE_LOCKED, `${this.lockFile} changed while being reclaimed`)\n }\n }\n try {\n unlinkSync(this.lockFile)\n } catch (error) {\n if (errorCode(error) !== 'ENOENT') {\n throw scopeError(ERR_SCOPE_LOCKED, `cannot reclaim ${this.lockFile}: ${messageOf(error)}`)\n }\n }\n if (!(await this.createLock())) {\n throw scopeError(ERR_SCOPE_LOCKED, `${this.lockFile} is held by another writer`)\n }\n if (signal?.aborted === true) {\n this.releaseLock()\n throw abortedError()\n }\n }\n\n /** `open(lock, 'wx')`; false means another writer holds it. */\n private async createLock(): Promise<boolean> {\n let handle: FileHandle\n try {\n handle = await open(this.lockFile, 'wx')\n } catch (error) {\n if (errorCode(error) === 'EEXIST') return false\n throw scopeError(ERR_SCOPE_LOCKED, `cannot create ${this.lockFile}: ${messageOf(error)}`)\n }\n\n const content = JSON.stringify({\n pid: process.pid,\n startedAt: this.now(),\n nonce: BOOT_NONCE,\n })\n let failure: unknown\n try {\n await handle.writeFile(content)\n } catch (error) {\n failure = error\n } finally {\n await handle.close().catch(() => {})\n }\n if (failure !== undefined) {\n // A lock without owner data would block for the stale timeout; remove\n // what we created.\n await unlink(this.lockFile).catch(() => {})\n throw scopeError(ERR_SCOPE_LOCKED, `cannot write ${this.lockFile}: ${messageOf(failure)}`)\n }\n this.lockOwner = content\n return true\n }\n\n /**\n * One read of the lock: bytes, mtime and the owner fields they record.\n *\n * `undefined` means absent (the `EEXIST` raced a release): the caller may\n * retry the create. An unreadable-but-present lock is returned with the mtime\n * and no owner fields, so it becomes reclaimable only after the dead-pid\n * timeout — never immediately, because an unreadable live lock must not be\n * evicted on a guess.\n */\n private readLock(): { text: string; mtimeMs: number; pid?: number; startedAt?: number } | undefined {\n let mtimeMs: number\n try {\n mtimeMs = statSync(this.lockFile).mtimeMs\n } catch {\n return undefined\n }\n let text: string\n try {\n text = readFileSync(this.lockFile, 'utf8')\n } catch {\n return { text: '', mtimeMs }\n }\n let parsed: unknown\n try {\n parsed = JSON.parse(text)\n } catch {\n return { text, mtimeMs }\n }\n const record = typeof parsed === 'object' && parsed !== null ? (parsed as Record<string, unknown>) : {}\n const pid = record.pid\n const startedAt = record.startedAt\n return {\n text,\n mtimeMs,\n ...(typeof pid === 'number' && Number.isInteger(pid) && pid > 0 && pid <= MAX_PID ? { pid } : {}),\n ...(typeof startedAt === 'number' && Number.isFinite(startedAt) && startedAt > 0 && startedAt <= this.now()\n ? { startedAt }\n : {}),\n }\n }\n\n /** Age from `startedAt` when it is usable, otherwise from the file's mtime. */\n private ageOf(lock: { mtimeMs: number; startedAt?: number } | undefined): number {\n if (lock === undefined) return 0\n return Math.max(0, this.now() - (lock.startedAt ?? lock.mtimeMs))\n }\n\n /** Whether the lock is reclaimable, and whether that decision needs a warning. */\n private classifyLock(\n lock: { mtimeMs: number; pid?: number; startedAt?: number } | undefined,\n ): 'held' | 'dead' | 'takeover' | 'missing' {\n if (lock === undefined) return 'missing'\n const age = this.ageOf(lock)\n if (age <= this.lockStaleMs) return 'held'\n if (age >= this.lockTakeoverMs) return 'takeover'\n return lock.pid === undefined || !isProcessAlive(lock.pid) ? 'dead' : 'held'\n }\n\n /**\n * Remove the lock only if it still contains exactly what this acquisition\n * wrote. An unconditional unlink would delete a replacement lock another\n * writer created after a stale-reclaim race. Every error is swallowed:\n * cleanup must never mask the causal error (rule 8), and a lock left behind\n * is reclaimable after 60 s while a masked conflict is not diagnosable.\n */\n private releaseLock(): void {\n const owner = this.lockOwner\n this.lockOwner = undefined\n if (owner === undefined) return\n try {\n if (readFileSync(this.lockFile, 'utf8') === owner) unlinkSync(this.lockFile)\n } catch {\n // See the method comment: cleanup never rethrows.\n }\n }\n\n /**\n * Serialize `doc` into a temporary file, fsync it, and rename it over\n * `scope.json`. Returns the stored file's mtime and the exact text written\n * (for the cache). A failed write removes the temporary file; the caller's\n * `finally` removes the lock.\n */\n private writeAtomic(doc: ScopeDoc): { mtimeMs: number; text: string } {\n const tempFile = join(this.dir, `.${SCOPE_FILE}.${process.pid}.${randomUUID()}.tmp`)\n const text = `${JSON.stringify(doc)}\\n`\n let fd: number | undefined\n try {\n fd = openSync(tempFile, 'w')\n writeFileSync(fd, text)\n fsyncSync(fd)\n closeSync(fd)\n fd = undefined\n // Stat before the rename: if this fails nothing has touched `scope.json`,\n // and the mtime of the inode is what `read()` will observe afterwards.\n const mtimeMs = statSync(tempFile).mtimeMs\n renameSync(tempFile, this.file)\n return { mtimeMs, text }\n } catch (error) {\n if (fd !== undefined) {\n try {\n closeSync(fd)\n } catch {\n // Already closed or never opened; the unlink below is what matters.\n }\n }\n try {\n unlinkSync(tempFile)\n } catch {\n // Best effort: the temporary file may not exist if openSync failed.\n }\n throw error\n }\n }\n}\n"]}
@@ -49,6 +49,39 @@ const ERR_HOST_NO_TOKENMETER = 'ERR_HOST_NO_TOKENMETER';
49
49
  const ERR_HOST_NO_ESTIMATOR = 'ERR_HOST_NO_ESTIMATOR';
50
50
  const ERR_HOST_PLATFORM_UNSUPPORTED = 'ERR_HOST_PLATFORM_UNSUPPORTED';
51
51
  const ERR_HOST_NO_WORKSPACE_REGISTRY = 'ERR_HOST_NO_WORKSPACE_REGISTRY';
52
+ /**
53
+ * Stable degradation code: a workspace registry is present but cannot list.
54
+ *
55
+ * Presence alone made a throwing `list()` look healthy: the resolver swallowed
56
+ * the throw per call (the intentional fail-closed path for one invisible
57
+ * session), every session was judged invisible, and `status` reported a healthy
58
+ * plugin doing nothing (review row 6). The probe calls `list()` at status time,
59
+ * exactly as the token meter is probed, so a broken registry is named instead
60
+ * of being indistinguishable from an absent one.
61
+ */
62
+ const ERR_HOST_WORKSPACE_REGISTRY_BROKEN = 'ERR_HOST_WORKSPACE_REGISTRY_BROKEN';
63
+ /**
64
+ * Stable degradation code: `spillStore` is present but exposes no `saveText`.
65
+ *
66
+ * `hasSpill` was presence-only, so a `{}` service reported a healthy spill path
67
+ * until the first projection failed (review row 50). The store is probed at
68
+ * status time for the one method the projection path calls; the notice module
69
+ * stays covered by `ERR_HOST_NO_SPILL_NOTICE` / `projection-skipped:no-footer`,
70
+ * because it is reached by `import()` and has no service to probe.
71
+ */
72
+ const ERR_HOST_SPILL_UNUSABLE = 'ERR_HOST_SPILL_UNUSABLE';
73
+ /**
74
+ * Stable degradation code: multi-candidate plans will abstain.
75
+ *
76
+ * The selector is the only consumer of the host LLM. Its absence or a failing
77
+ * call is written as `selector-unavailable` / `selector-error`, but those are
78
+ * receipt counts: an operator reading `degraded` saw a healthy plugin while
79
+ * every multi-candidate plan abstained (review row 49). Single-candidate
80
+ * substitution still works, so this is a warning, not a failure. A
81
+ * `selector-abstain` is deliberately not mapped: the model declined an
82
+ * ambiguous plan, which is not a host capability absence.
83
+ */
84
+ const ERR_HOST_SELECTOR_UNAVAILABLE = 'ERR_HOST_SELECTOR_UNAVAILABLE';
52
85
  /**
53
86
  * Stable degradation code: at least one receipt shard could not be read.
54
87
  *
@@ -104,6 +137,12 @@ const ERR_HOST_COMPLETE_SECTION = 'ERR_HOST_COMPLETE_SECTION';
104
137
  * failing sends them to the wrong place. `footer-failed` stays with
105
138
  * `ERR_HOST_NO_SPILL_NOTICE` because both mean the same thing at the point of
106
139
  * use — the footer cannot be produced.
140
+ *
141
+ * `selector-unavailable` and `selector-error` are the selector's only two host
142
+ * failures: no LLM/route, or a call that threw. Both mean "multi-candidate
143
+ * plans will abstain" while single-candidate substitution keeps working, so
144
+ * they share one warning code. `selector-abstain` is not a host fact and is not
145
+ * mapped (review row 49).
107
146
  */
108
147
  const RECEIPT_DEGRADATION = [
109
148
  { code: 'projection-skipped:no-spill', degraded: ERR_HOST_NO_SPILL },
@@ -113,6 +152,10 @@ const RECEIPT_DEGRADATION = [
113
152
  // The substitution refusal writes the stable code itself, so a status built
114
153
  // without host facts still reports the reason the decision path recorded.
115
154
  { code: ERR_HOST_NO_TOKENMETER, degraded: ERR_HOST_NO_TOKENMETER },
155
+ // Only absence is a capability fact. `selector-error` is a call failure that
156
+ // may be transient and is summed over all history, so mapping it here would
157
+ // mark a healthy host degraded forever (review qr5#4).
158
+ { code: 'selector-unavailable', degraded: ERR_HOST_SELECTOR_UNAVAILABLE },
116
159
  ];
117
160
  /** The scope document's caller-writable fields. Everything else is store-owned. */
118
161
  const PATCH_FIELDS = ['mode', 'workspaceIds', 'shadow', 'projection'];
@@ -158,6 +201,8 @@ function replayOf(receipt, fallback) {
158
201
  async function aggregate(receipts, fallbackHorizon) {
159
202
  const counts = Object.create(null);
160
203
  let substitution = 0;
204
+ let substitutionAvoided = 0;
205
+ let avoidedSeen = false;
161
206
  let projectionGross = 0;
162
207
  let projectionGrossReplay = 0;
163
208
  let retrievalContentReplay = 0;
@@ -184,6 +229,26 @@ async function aggregate(receipts, fallbackHorizon) {
184
229
  if (typeof saved === 'number' && Number.isFinite(saved))
185
230
  substitution += saved;
186
231
  }
232
+ // The lower estimate is the skipped request's own total, summed over every
233
+ // receipt that carries it (the settled line is its producer). Presence is
234
+ // tracked separately from the value: a receipt carrying `0` is a
235
+ // measurement, while no receipt carrying the field means "not measured"
236
+ // and the key is omitted from `status` rather than reported as zero
237
+ // (review row 7).
238
+ // Pair the two sums on the same receipt: a rollover settlement writes a
239
+ // numeric lower bound with `saved_input_tokens: 'unknown'`, so summing the
240
+ // lower over a superset could report a floor above the ceiling
241
+ // (review qr5#2). A receipt that carries only one side contributes to
242
+ // neither.
243
+ const avoided = receipt.avoided_total_tokens;
244
+ const upper = receipt.saved_input_tokens;
245
+ if (typeof avoided === 'number' &&
246
+ Number.isFinite(avoided) &&
247
+ typeof upper === 'number' &&
248
+ Number.isFinite(upper)) {
249
+ substitutionAvoided += avoided;
250
+ avoidedSeen = true;
251
+ }
187
252
  if (receipt.kind !== 'projection')
188
253
  continue;
189
254
  const replay = replayOf(receipt, fallbackHorizon);
@@ -249,6 +314,7 @@ async function aggregate(receipts, fallbackHorizon) {
249
314
  return {
250
315
  counts,
251
316
  substitution,
317
+ ...(avoidedSeen ? { substitutionAvoided } : {}),
252
318
  projectionGross,
253
319
  projectionGrossReplay,
254
320
  retrievalContentReplay,
@@ -415,10 +481,20 @@ function degradationCodes(observed, read, host, fixedOverhead, missingMounts = [
415
481
  codes.push(ERR_HOST_NO_ESTIMATOR);
416
482
  // `spillStore` matters only in apply mode; shadow mode never touches it
417
483
  // (design §5.4), so reporting it while projection is `shadow` would be noise.
418
- if (host?.hasSpill === false && read.doc.projection === 'on')
419
- codes.push(ERR_HOST_NO_SPILL);
484
+ // Presence and capability are separate: an absent store and a present store
485
+ // without `saveText` need different repairs, so they get different codes.
486
+ if (read.doc.projection === 'on') {
487
+ if (host?.hasSpill === false)
488
+ codes.push(ERR_HOST_NO_SPILL);
489
+ else if (host?.spillUsable === false)
490
+ codes.push(ERR_HOST_SPILL_UNUSABLE);
491
+ }
492
+ // A present registry that cannot list is not an absent one: the operator is
493
+ // told which of the two host states to repair (review row 6).
420
494
  if (host?.hasWorkspaceRegistry === false)
421
495
  codes.push(ERR_HOST_NO_WORKSPACE_REGISTRY);
496
+ else if (host?.workspaceRegistryBroken === true)
497
+ codes.push(ERR_HOST_WORKSPACE_REGISTRY_BROKEN);
422
498
  // A missing mount is a wiring failure, not a capability absence: the plugin
423
499
  // is loaded but at least one of its four integration points is not, so the
424
500
  // ledgers cannot be trusted to describe what it is doing.
@@ -473,6 +549,9 @@ async function statusCommand(deps) {
473
549
  totals.legacyRetrievalCost;
474
550
  const saved = {
475
551
  substitution: totals.substitution,
552
+ ...(totals.substitutionAvoided === undefined
553
+ ? {}
554
+ : { substitution_avoided: totals.substitutionAvoided }),
476
555
  projectionGross: grossReplay,
477
556
  projectionNet,
478
557
  retrievals: totals.retrievals,
@@ -514,6 +593,7 @@ async function statusCommand(deps) {
514
593
  ...(deps.host?.hasWorkspaceRegistry === undefined
515
594
  ? {}
516
595
  : { hasWorkspaceRegistry: deps.host.hasWorkspaceRegistry }),
596
+ ...(deps.host?.hasSpill === undefined ? {} : { hasSpill: deps.host.hasSpill }),
517
597
  };
518
598
  return { ok: true, data };
519
599
  }