dsh-boost 0.2.1 → 0.2.2
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/README.en.md +4 -4
- package/README.md +10 -11
- package/dist/scope/store.js +3 -1
- package/dist/scope/store.js.map +1 -1
- package/dist/tools/boost.js +2 -1
- package/dist/tools/boost.js.map +1 -1
- package/lib/client.js +25 -12
- package/locale/en.json +5 -4
- package/locale/zh.json +5 -4
- package/package.json +1 -1
package/README.en.md
CHANGED
|
@@ -12,7 +12,7 @@ read-only substitution**.
|
|
|
12
12
|
## What it does
|
|
13
13
|
|
|
14
14
|
DSH replays the whole history on every model request. Across the 300 longest sessions measured
|
|
15
|
-
locally (`npm run --silent stats` — without `--silent`, npm prints its `> dsh-boost@0.1
|
|
15
|
+
locally (`npm run --silent stats` — without `--silent`, npm prints its `> dsh-boost@0.2.1 stats`
|
|
16
16
|
banner to stdout, so use `--silent` or `node scripts/session-stats.mjs` for machine-readable
|
|
17
17
|
output; snapshot at `2026-11-19T03:13:21Z`): 54,141 steps and 54,088 requests,
|
|
18
18
|
10,575,904,022 raw tokens in total. The mean is 195,340 tokens per step and 195,531 per request
|
|
@@ -577,6 +577,9 @@ to load. `llm` is soft (only the selector uses it); when absent the selector fal
|
|
|
577
577
|
| Prompt assembly waterfall | outgoing-request probe (not a dependency) | When the host's `complete: true` prompt section replaces the assembled system prompt after the waterfall and the protocol section never reaches the request, `status.degraded` carries `ERR_HOST_COMPLETE_SECTION`; substitution and projection fail closed for the affected requests (the plugin stays inert although the workspace is visible). Find the complete section overriding the waterfall (usually another plugin's) and remove it, or accept the inaction on those requests |
|
|
578
578
|
|
|
579
579
|
`ERR_HOST_NO_STEP_WHEN` no longer exists: step-level `when` has been part of
|
|
580
|
+
`ToolRegistrationOptions` since the oldest host line this package declares, so the plugin no
|
|
581
|
+
longer probes it and registers unconditionally.
|
|
582
|
+
|
|
580
583
|
The settings page's data route has codes of its own, and they are **not** members of
|
|
581
584
|
`status.degraded` — every failure returns one in a JSON body, and the page decides what to say from it:
|
|
582
585
|
|
|
@@ -594,9 +597,6 @@ The settings page's data route has codes of its own, and they are **not** member
|
|
|
594
597
|
`ERR_BOOST_HTTP_MOUNT_FAILED` goes to the log only: mounting the route threw (`ctx.inject` missing or
|
|
595
598
|
refused), so the page has no data source. It is not `ERR_BOOST_PARTIAL_MOUNT` — that one is about hooks.
|
|
596
599
|
|
|
597
|
-
`ToolRegistrationOptions` since the oldest host line this package declares, so the plugin no
|
|
598
|
-
longer probes it and registers unconditionally.
|
|
599
|
-
|
|
600
600
|
Registration codes come in two kinds. A non-duplicate throw while registering the protocol
|
|
601
601
|
section logs `ERR_BOOST_SECTION_REGISTER_FAILED` (log only). The three event hooks
|
|
602
602
|
(`tools/post-execute`, `llm/stream`, `tools/execute`) are then mounted **independently**: a
|
package/README.md
CHANGED
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
## 它解决什么
|
|
10
10
|
|
|
11
11
|
DSH 每次模型请求都会回放全部历史。本机 300 个最长会话的实测聚合(`npm run --silent stats`——不带
|
|
12
|
-
`--silent` 时 npm 会把 `> dsh-boost@0.2.
|
|
12
|
+
`--silent` 时 npm 会把 `> dsh-boost@0.2.1 stats` 横幅打进 stdout,机器解析请用 `--silent` 或直接
|
|
13
13
|
`node scripts/session-stats.mjs`;快照时刻 `2026-11-19T03:13:21Z`):54,141 步、54,088 个请求,合计 10,575,904,022 raw token。按步均值
|
|
14
14
|
195,340 token,按请求均值 195,531、中位 187,681;97.01% 的输入是缓存读。工具回执是体积主体
|
|
15
15
|
(bash 61.75%、read 22.13%、ssh 10.01%),而下一步真正会用到的部分通常远小于回执本身。
|
|
@@ -64,26 +64,25 @@ v1 的**事前估算**区间是 **3.5%(下界)– 10.0%(理想上界)**
|
|
|
64
64
|
`dsh plugin` 要求指定 profile,剩下的参数原样转发给该 profile 目录里的 pnpm:
|
|
65
65
|
|
|
66
66
|
```bash
|
|
67
|
-
# 从 registry 安装:npmjs 上的 latest 是 0.2.
|
|
67
|
+
# 从 registry 安装:npmjs 上的 latest 是 0.2.1(本仓库 .npmrc 与 lockfile
|
|
68
68
|
# 也已钉在 npmjs,见下)
|
|
69
|
-
dsh plugin --profile <name> add dsh-boost@^0.2.
|
|
69
|
+
dsh plugin --profile <name> add dsh-boost@^0.2.1 --registry=https://registry.npmjs.org/
|
|
70
70
|
|
|
71
71
|
# 或从本地 checkout 安装(先构建;dist/ 不入库)
|
|
72
72
|
npm run build
|
|
73
73
|
dsh plugin --profile <name> add /absolute/path/to/dsh-boost
|
|
74
74
|
```
|
|
75
75
|
|
|
76
|
-
例如 web profile:`dsh plugin --profile web add dsh-boost@^0.2.
|
|
76
|
+
例如 web profile:`dsh plugin --profile web add dsh-boost@^0.2.1 --registry=https://registry.npmjs.org/`。
|
|
77
77
|
`dsh plugin` 把操作转发给 pnpm,所以 pnpm 必须在 PATH 上。
|
|
78
78
|
|
|
79
|
-
> **`^0.2.
|
|
79
|
+
> **`^0.2.1` 是当前的安全钉法。** `registry.npmjs.org` 上 `latest` 是 `0.2.1`,历史版本依次是
|
|
80
80
|
> `0.1.4`、`0.1.3`、`0.1.2`、`0.1.1`、`0.1.0`,以及首次发布时 npm 自动创建的占位版本
|
|
81
|
-
> `0.0.0-stage`——**不要安装 `0.0.0-stage`**,它不是可用构建。`0.2.0`
|
|
82
|
-
>
|
|
83
|
-
>
|
|
84
|
-
>
|
|
85
|
-
>
|
|
86
|
-
> 在意 registry 时显式传 `--registry=https://registry.npmjs.org/`;镜像滞后时 `@^0.2.0` 会在
|
|
81
|
+
> `0.0.0-stage`——**不要安装 `0.0.0-stage`**,它不是可用构建。`0.2.0` 新增了设置页(`dsh.client` 与 `./client` 出口、`/dsh-boost/api` 路由、随包发布的
|
|
82
|
+
> `lib/client.js`)与中英双语,`0.2.1` 修了页面上三处会读到错误数值或错误提示的缺陷;`0.1.4` 及更早**没有设置页**,`^0.1.4` 也不会解析到 `0.2.x`(`^` 不跨大版本),所以从
|
|
83
|
+
> `0.1.x` 升上来要显式写 `@^0.2.1`。本仓库已把 `.npmrc` 与 lockfile 钉在 npmjs,但**你机器上
|
|
84
|
+
> 的全局 npm 配置**可能仍指向一个尚未同步 `0.2.1` 的镜像:那是本机配置,不是本仓库的状态。
|
|
85
|
+
> 在意 registry 时显式传 `--registry=https://registry.npmjs.org/`;镜像滞后时 `@^0.2.1` 会在
|
|
87
86
|
> 同步前解析失败。
|
|
88
87
|
|
|
89
88
|
## 设置页
|
package/dist/scope/store.js
CHANGED
|
@@ -354,7 +354,9 @@ export class ScopeStore {
|
|
|
354
354
|
await mkdir(this.dir, { recursive: true });
|
|
355
355
|
}
|
|
356
356
|
catch (error) {
|
|
357
|
-
|
|
357
|
+
// Creating the directory is part of the write path: a failure here is a
|
|
358
|
+
// write failure, and telling the caller to re-read would be wrong.
|
|
359
|
+
throw scopeError(ERR_SCOPE_WRITE_FAILED, `cannot create ${this.dir}: ${messageOf(error)}`);
|
|
358
360
|
}
|
|
359
361
|
}
|
|
360
362
|
/**
|
package/dist/scope/store.js.map
CHANGED
|
@@ -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,q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: 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_WRITE_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 // A write failure is not a read failure: the caller still knows its\n // baseline, and telling it to re-read would discard a draft that is\n // perfectly good. Rule 8 requires a stable code on every error.\n throw scopeError(ERR_SCOPE_WRITE_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,qBA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F","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_WRITE_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 // A write failure is not a read failure: the caller still knows its\n // baseline, and telling it to re-read would discard a draft that is\n // perfectly good. Rule 8 requires a stable code on every error.\n throw scopeError(ERR_SCOPE_WRITE_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 // Creating the directory is part of the write path: a failure here is a\n // write failure, and telling the caller to re-read would be wrong.\n throw scopeError(ERR_SCOPE_WRITE_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"]}
|
package/dist/tools/boost.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { measureFixedOverhead } from '../admission/fixed-cost.js';
|
|
2
2
|
import { DEFAULT_CONFIG } from '../config.js';
|
|
3
3
|
import { isPosixOnly } from '../host/platform.js';
|
|
4
|
-
import { ERR_SCOPE_ABORTED, ERR_SCOPE_FUTURE_VERSION, ERR_SCOPE_LOCKED, ERR_SCOPE_PARSE_FAILED, ERR_SCOPE_READ_FAILED, ERR_SCOPE_REVISION_CONFLICT, ERR_SCOPE_UNKNOWN_VERSION, } from '../scope/doc.js';
|
|
4
|
+
import { ERR_SCOPE_ABORTED, ERR_SCOPE_FUTURE_VERSION, ERR_SCOPE_LOCKED, ERR_SCOPE_PARSE_FAILED, ERR_SCOPE_READ_FAILED, ERR_SCOPE_WRITE_FAILED, ERR_SCOPE_REVISION_CONFLICT, ERR_SCOPE_UNKNOWN_VERSION, } from '../scope/doc.js';
|
|
5
5
|
/** Stable failure code: `cmd` names no subcommand this tool implements. */
|
|
6
6
|
const ERR_BOOST_UNKNOWN_CMD = 'ERR_BOOST_UNKNOWN_CMD';
|
|
7
7
|
/** Stable failure code: a required argument (`baseRevision`) is missing or malformed. */
|
|
@@ -24,6 +24,7 @@ const SCOPE_CODES = new Set([
|
|
|
24
24
|
ERR_SCOPE_FUTURE_VERSION,
|
|
25
25
|
ERR_SCOPE_PARSE_FAILED,
|
|
26
26
|
ERR_SCOPE_READ_FAILED,
|
|
27
|
+
ERR_SCOPE_WRITE_FAILED,
|
|
27
28
|
ERR_SCOPE_REVISION_CONFLICT,
|
|
28
29
|
ERR_SCOPE_LOCKED,
|
|
29
30
|
ERR_SCOPE_ABORTED,
|
package/dist/tools/boost.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"boost.js","sourceRoot":"","sources":["../../src/tools/boost.ts"],"names":[],"mappings":"AAoEA,OAAO,EAAE,oBAAoB,EAAE,MAAM,4BAA4B,CAAA;AAEjE,OAAO,EAAE,cAAc,EAAE,MAAM,cAAc,CAAA;AAC7C,OAAO,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAA;AAEjD,OAAO,EACL,iBAAiB,EACjB,wBAAwB,EACxB,gBAAgB,EAChB,sBAAsB,EACtB,qBAAqB,EACrB,2BAA2B,EAC3B,yBAAyB,GAC1B,MAAM,iBAAiB,CAAA;AAKxB,2EAA2E;AAC3E,MAAM,qBAAqB,GAAG,uBAAuB,CAAA;AAErD,yFAAyF;AACzF,MAAM,CAAC,MAAM,sBAAsB,GAAG,wBAAwB,CAAA;AAE9D,wEAAwE;AACxE,MAAM,CAAC,MAAM,sBAAsB,GAAG,wBAAwB,CAAA;AAE9D,sFAAsF;AACtF,MAAM,CAAC,MAAM,k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O;QACL,IAAI,EAAE,OAAO;QACb,WAAW,EAAE,WAAW;QACxB,UAAU,EAAE,UAAU;QACtB,MAAM,EAAE,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,EAAE,YAAY,EAAE;QACvD,OAAO,EAAE,CAAC,IAAI,EAAE,IAAI,EAAE,EAAE,CAAC,QAAQ,CAAC,EAAE,IAAI,EAAE,IAAiB,EAAE,GAAG,IAAI,EAAE,MAAM,EAAE,QAAQ,CAAC,IAAI,CAAC,EAAE,CAAC;KAChG,CAAA;AACH,CAAC","sourcesContent":["/**\n * The `boost` control tool: the user's only way to see or change what the\n * plugin is doing.\n *\n * The plugin itself is invisible — it rewrites what the model sees and never\n * speaks — so this tool's output is part of the product, not a debugging aid.\n * `status` reports what the plugin has actually recorded: the scope document's\n * exposure surface, both switches (`shadow` and `projection`; \"recording but\n * not replacing\" is not \"replacing\"), per-code receipt counts over **every**\n * shard, the substitution and projection ledgers, and the stable degraded\n * codes observed. `scope-get` reads `scope.json`; `scope-set` and `shadow`\n * write it; both writes are compare-and-swap through `ScopeStore.write`, so a\n * stale caller gets `ERR_SCOPE_REVISION_CONFLICT` rather than silently\n * overwriting a concurrent change.\n *\n * ## Contracts this module keeps\n *\n * - Every failure is a stable code in a returned value; nothing throws out of\n * `runBoost`. The store's own codes are passed through unchanged.\n * - `scope-set` never lets a caller set `version` or `revision`: `revision` is\n * the store's, `version` is fixed at 2, and a body carrying either reserved\n * field is rejected **before** the mutation runs. The store persists whatever\n * `mutate` returns, so this rejection is what stops a v1-shaped document.\n * - Both ledger sides come from the receipts. This module never estimates a\n * retrieval cost: an unpriced retrieval makes the net `'unknown'` rather\n * than free, and `projection_unpriced_retrievals` says how many there were.\n * A retrieval's own projection is excluded from gross because its visible\n * window is already charged as retrieval content. The projection saving is\n * read from `saved_projection_tokens` (the design §5.3 name T23b/T26 write),\n * falling back to `saved`; a producer must write one of them, while a\n * meterless projection has neither and makes gross/net `'unknown'`. The\n * substitution saving is read only from the settled line, because the\n * synth-time line predates any measurement.\n * - `status.degraded` is a list of **stable codes only** (`ERR_HOST_*` /\n * `ERR_SCOPE_*`; the one wiring code is `ERR_BOOST_PARTIAL_MOUNT`). The scope\n * store's internal `scope-degraded` label and the\n * receipt stream's `projection-skipped:*` are inputs, not output: a receipt\n * code is mapped to `ERR_HOST_NO_SPILL` (no spill backend),\n * `ERR_HOST_SPILL_FAILING` (backend present, every write rejected) or\n * `ERR_HOST_NO_SPILL_NOTICE` (backend present, notice module cannot render\n * the footer), `ERR_HOST_SPILL_UNUSABLE` (backend present but exposes no\n * `saveText`), `ERR_HOST_WORKSPACE_REGISTRY_BROKEN` (registry present but\n * cannot list), and `ERR_HOST_SELECTOR_UNAVAILABLE` (the LLM seam is absent\n * or failing, so multi-candidate plans abstain); and a degraded scope read\n * passes its `ERR_SCOPE_*` code through. The two estimator absences are\n * separate codes:\n * `ERR_HOST_NO_TOKENMETER` is the host service probe (`apply` records whether\n * the synchronous token meter exists), while `ERR_HOST_NO_ESTIMATOR` is the\n * pure fixed-cost package being unreachable. One can exist without the other,\n * and merging them sent the operator to the wrong host.\n * `ERR_HOST_PLATFORM_UNSUPPORTED` is `isPosixOnly()` being false.\n * `ERR_BOOST_PARTIAL_MOUNT` is an `apply` wiring failure: at least one of the\n * four host mounts (prompt section, post-execute, llm/stream, execute) is\n * missing, so the plugin is loaded but not fully wired.\n * - The fixed overhead is measured **once at startup**\n * (`measureBoostFixedOverhead`: protocol section + tool schema) and awaited\n * by `status`; it is never on a request path (design §6.1).\n * - `runBoost` is pure orchestration over the two stores plus the host facts\n * `apply` hands it: no `ctx`, no host calls beyond the one measurement. The\n * tool definition is therefore testable without a host, and the host probe\n * lives in `src/index.ts`.\n *\n * The command table is deliberately a plain record, one handler per\n * subcommand, so an unknown `cmd` is a lookup miss rather than a fallthrough.\n *\n * @module dsh-boost/tools/boost\n */\nimport type { JsonSchemaNode } from '@deepseek-ai/dsh-tools'\nimport { measureFixedOverhead } from '../admission/fixed-cost.js'\nimport type { FixedOverheadMeasurement } from '../admission/fixed-cost.js'\nimport { DEFAULT_CONFIG } from '../config.js'\nimport { isPosixOnly } from '../host/platform.js'\nimport type { ProjectionMode } from '../projection/apply.js'\nimport {\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} from '../scope/doc.js'\nimport type { ScopeCode, ScopeDoc } from '../scope/doc.js'\nimport type { ScopeStore } from '../scope/store.js'\nimport type { Receipt, ReceiptStore } from '../receipts/store.js'\n\n/** Stable failure code: `cmd` names no subcommand this tool implements. */\nconst ERR_BOOST_UNKNOWN_CMD = 'ERR_BOOST_UNKNOWN_CMD'\n\n/** Stable failure code: a required argument (`baseRevision`) is missing or malformed. */\nexport const ERR_BOOST_INVALID_ARGS = 'ERR_BOOST_INVALID_ARGS'\n\n/** Stable failure code: `body` is not a valid, writable scope patch. */\nexport const ERR_BOOST_INVALID_BODY = 'ERR_BOOST_INVALID_BODY'\n\n/** Stable failure code: an unexpected internal failure, so the tool still answers. */\nexport const ERR_BOOST_INTERNAL = 'ERR_BOOST_INTERNAL'\n\n/**\n * Load-time log code: the settings page's data route could not be mounted.\n *\n * Log-only, like `ERR_BOOST_PARTIAL_MOUNT`: the plugin keeps working, the page\n * just has no data source. Emitted from the mount path itself, so it appears in\n * the host log rather than in `boost status`.\n */\nexport const ERR_BOOST_HTTP_MOUNT_FAILED = 'ERR_BOOST_HTTP_MOUNT_FAILED'\n\n/** Every scope failure code, for passing the store's codes through unchanged. */\nconst SCOPE_CODES: ReadonlySet<string> = new Set([\n ERR_SCOPE_UNKNOWN_VERSION,\n ERR_SCOPE_FUTURE_VERSION,\n ERR_SCOPE_PARSE_FAILED,\n ERR_SCOPE_READ_FAILED,\n ERR_SCOPE_REVISION_CONFLICT,\n ERR_SCOPE_LOCKED,\n ERR_SCOPE_ABORTED,\n])\n\n/** Stable host degradation codes (design §9; the frozen set `status` reports). */\nconst ERR_HOST_NO_SPILL = 'ERR_HOST_NO_SPILL'\n/**\n * Stable degradation code: at least one of the four host mounts is missing.\n *\n * `apply` mounts the prompt section, the projection hook, the synthesizer and\n * the dispatch hook. A failure in any of them used to be logged as a section\n * failure (or swallowed) while `status` reported `degraded: []`; a plugin\n * missing its projection or flush hook looks healthy in every ledger but never\n * acts. The code names that state; `partialMounts()` lists which mounts are\n * absent (review row 2).\n */\nconst ERR_BOOST_PARTIAL_MOUNT = 'ERR_BOOST_PARTIAL_MOUNT'\n/**\n * Stable degradation code: the host spill-notice module has no footer renderer.\n *\n * Apply-mode projection cannot compose its footer without `formatSpillNotice`,\n * so every receipt is left intact and recorded as\n * `projection-skipped:no-footer`. That is a host-level absence, not an ordinary\n * \"not worth it\" skip: without this code `status` reported a healthy spill path\n * while projection silently never ran. Its producer is the receipt stream\n * (there is no service probe — the module is reached by `import()` only).\n */\nconst ERR_HOST_NO_SPILL_NOTICE = 'ERR_HOST_NO_SPILL_NOTICE'\nconst ERR_HOST_SPILL_FAILING = 'ERR_HOST_SPILL_FAILING'\nconst ERR_HOST_NO_TOKENMETER = 'ERR_HOST_NO_TOKENMETER'\nconst ERR_HOST_NO_ESTIMATOR = 'ERR_HOST_NO_ESTIMATOR'\nconst ERR_HOST_PLATFORM_UNSUPPORTED = 'ERR_HOST_PLATFORM_UNSUPPORTED'\nconst ERR_HOST_NO_WORKSPACE_REGISTRY = 'ERR_HOST_NO_WORKSPACE_REGISTRY'\n/**\n * Stable degradation code: a workspace registry is present but cannot list.\n *\n * Presence alone made a throwing `list()` look healthy: the resolver swallowed\n * the throw per call (the intentional fail-closed path for one invisible\n * session), every session was judged invisible, and `status` reported a healthy\n * plugin doing nothing (review row 6). The probe calls `list()` at status time,\n * exactly as the token meter is probed, so a broken registry is named instead\n * of being indistinguishable from an absent one.\n */\nconst ERR_HOST_WORKSPACE_REGISTRY_BROKEN = 'ERR_HOST_WORKSPACE_REGISTRY_BROKEN'\n/**\n * Stable degradation code: `spillStore` is present but exposes no `saveText`.\n *\n * `hasSpill` was presence-only, so a `{}` service reported a healthy spill path\n * until the first projection failed (review row 50). The store is probed at\n * status time for the one method the projection path calls; the notice module\n * stays covered by `ERR_HOST_NO_SPILL_NOTICE` / `projection-skipped:no-footer`,\n * because it is reached by `import()` and has no service to probe.\n */\nconst ERR_HOST_SPILL_UNUSABLE = 'ERR_HOST_SPILL_UNUSABLE'\n/**\n * Stable degradation code: multi-candidate plans will abstain.\n *\n * The selector is the only consumer of the host LLM. Its absence or a failing\n * call is written as `selector-unavailable` / `selector-error`, but those are\n * receipt counts: an operator reading `degraded` saw a healthy plugin while\n * every multi-candidate plan abstained (review row 49). Single-candidate\n * substitution still works, so this is a warning, not a failure. A\n * `selector-abstain` is deliberately not mapped: the model declined an\n * ambiguous plan, which is not a host capability absence.\n */\nconst ERR_HOST_SELECTOR_UNAVAILABLE = 'ERR_HOST_SELECTOR_UNAVAILABLE'\n\n/**\n * Stable degradation code: at least one receipt shard could not be read.\n *\n * `status` scans every shard; a single unreadable file (EACCES, or a directory\n * named `x.jsonl`) must leave the healthy shards readable and the tool\n * answering. `ReceiptStore.readErrors()` is the one live source: the store\n * contains the failure per shard and the count describes its last whole-store\n * scan, so repairing the shard and re-running `status` drops the code.\n */\nconst ERR_RECEIPTS_UNREADABLE = 'ERR_RECEIPTS_UNREADABLE'\n\n/**\n * Stable degradation code: the whole-store scan hit the 256-shard cap.\n *\n * The totals then cover only the first 256 sorted shards: under-counting is\n * the safe direction, but presenting that as a total is not. The code marks\n * the figures as a lower bound; `ReceiptStore.scanTruncated()` is its source.\n */\nconst ERR_RECEIPTS_TRUNCATED = 'ERR_RECEIPTS_TRUNCATED'\n\n/**\n * Stable degradation code: the final system prompt did not carry the protocol\n * section because a `complete: true` section replaced the assembly.\n *\n * Detected on the outgoing request (`llm/stream`), not at assembly time: the\n * host restores the complete section after the waterfall, so only the request\n * shows the loss. Substitution is refused for the affected request because the\n * model was never taught the plan grammar (review row 12).\n */\nconst ERR_HOST_COMPLETE_SECTION = 'ERR_HOST_COMPLETE_SECTION'\n\n/**\n * Receipt codes that mean the host is degraded, mapped to the stable code\n * `status` reports.\n *\n * `projection-skipped:no-spill` is the code the projection path records when\n * the spill backend is absent (design §5.4), so it is the real producer behind\n * `ERR_HOST_NO_SPILL`. The same code is also derived from the host probe when\n * `projection: 'on'`; the two channels are deduplicated, not mutually exclusive.\n *\n * `projection-skipped:no-footer` is a different absence with a different fix:\n * the spill backend exists but the host spill-notice module does not render a\n * footer, so `projectApply` refuses to replace anything. Mapping it to\n * `ERR_HOST_NO_SPILL_NOTICE` is what keeps the plugin's headline feature from\n * being silently off while `status` calls the spill path healthy.\n *\n * `projection-skipped:spill-failed` and `projection-skipped:footer-failed` are\n * the same two degradations at the point of use: the backend exists but\n * `saveText` rejected, or the renderer exists but threw. Without these rows a\n * present-but-broken store skipped 100% of projections while `degraded` stayed\n * empty (review row 31).\n *\n * `spill-failed` gets its **own** code rather than reusing `ERR_HOST_NO_SPILL`:\n * a backend that rejects every write is not an absent backend, and telling an\n * operator to \"restore the spill package\" when the package is installed and\n * failing sends them to the wrong place. `footer-failed` stays with\n * `ERR_HOST_NO_SPILL_NOTICE` because both mean the same thing at the point of\n * use — the footer cannot be produced.\n *\n * `selector-unavailable` and `selector-error` are the selector's only two host\n * failures: no LLM/route, or a call that threw. Both mean \"multi-candidate\n * plans will abstain\" while single-candidate substitution keeps working, so\n * they share one warning code. `selector-abstain` is not a host fact and is not\n * mapped (review row 49).\n */\nconst RECEIPT_DEGRADATION: ReadonlyArray<{ readonly code: string; readonly degraded: string }> = [\n { code: 'projection-skipped:no-spill', degraded: ERR_HOST_NO_SPILL },\n { code: 'projection-skipped:spill-failed', degraded: ERR_HOST_SPILL_FAILING },\n { code: 'projection-skipped:no-footer', degraded: ERR_HOST_NO_SPILL_NOTICE },\n { code: 'projection-skipped:footer-failed', degraded: ERR_HOST_NO_SPILL_NOTICE },\n // The substitution refusal writes the stable code itself, so a status built\n // without host facts still reports the reason the decision path recorded.\n { code: ERR_HOST_NO_TOKENMETER, degraded: ERR_HOST_NO_TOKENMETER },\n // Only absence is a capability fact. `selector-error` is a call failure that\n // may be transient and is summed over all history, so mapping it here would\n // mark a healthy host degraded forever (review qr5#4).\n { code: 'selector-unavailable', degraded: ERR_HOST_SELECTOR_UNAVAILABLE },\n]\n\n/**\n * Host capabilities `apply` probes once and hands `status`.\n *\n * Every field is optional because `runBoost` is also usable without a host\n * (unit tests, and the control tool built before `apply` wires the probe). An\n * absent fact means \"not probed\", never \"supported\": the status code list then\n * simply omits the corresponding code rather than guessing.\n */\nexport interface BoostHostFacts {\n /** Whether `ctx.get('tokenMeter')` exposed the synchronous message estimator. */\n hasTokenMeter?: boolean\n /** Whether `ctx.get('spillStore')` exposed the projection backend. */\n hasSpill?: boolean\n /**\n * Whether the present spill store exposes the one method projection calls.\n *\n * Presence is not capability: a `{}` service resolves, so `hasSpill` is true\n * while every projection fails at the first `saveText`. The probe is a shape\n * check only — calling `saveText` would write a spill artifact — and an\n * absent store leaves this `false` (the absence itself is `hasSpill: false`).\n */\n spillUsable?: boolean\n /**\n * Whether `ctx.get('workspaceRegistry')` ever became available.\n *\n * A missing registry makes every session invisible, which presents to the\n * operator as \"nothing ever happens\" with no error anywhere. It is a host\n * fact rather than an assembly detail because that failure mode has to be\n * diagnosable from inside the product.\n */\n hasWorkspaceRegistry?: boolean\n /**\n * Whether the present registry's `list()` threw or returned a non-array.\n *\n * `hasWorkspaceRegistry` only says the service exists. A registry that\n * cannot list makes every session invisible too, and the per-call resolver\n * swallows that throw by design, so this fact is the only way the failure\n * reaches `status` (review row 6).\n */\n workspaceRegistryBroken?: boolean\n}\n\n/** The two stores `runBoost` orchestrates, plus the host facts it reports. */\nexport interface BoostDeps {\n scope: ScopeStore\n receipts: ReceiptStore\n /** Host capabilities measured by `apply`; absent when no host was probed. */\n host?: BoostHostFacts\n /**\n * The one fixed-overhead measurement, started at plugin load.\n *\n * A function rather than a promise so `status` can await it lazily; the\n * default reuses the module-level memoised measurement.\n */\n fixedOverhead?: () => Promise<FixedOverheadMeasurement | 'unknown'>\n /**\n * Which estimator priced this assembly's figures.\n *\n * `host` means the synchronous host meter; `unknown` means no token meter,\n * so no number is fabricated (design §9). There is deliberately no\n * `chars/4` arm: a characters-over-four guess is not a measurement, and a\n * receipt that says `unknown` is more useful than one that is wrong.\n */\n estimateKind?: 'host' | 'unknown'\n /**\n * The current replay horizon; defaults to the design's 20.\n *\n * Receipts carry their own `horizon_steps`, so this is only the fallback for\n * receipts written before that field existed (counted in\n * `projection_horizon_reestimated`) — not a factor applied to the whole\n * ledger.\n */\n horizonSteps?: number\n /** Locators evicted by the per-session cap; status-time read. */\n locatorEvictions?: () => number\n /**\n * Receipt shards whole-store scans had to skip since the last scan that read\n * every shard; status-time read.\n *\n * This is the **only** source of `ERR_RECEIPTS_UNREADABLE`: the store skips\n * an unreadable shard per shard and reports the count, so `status` has one\n * mechanism rather than a status-side scan flag that no production store can\n * raise. Absent means the store has no such counter (or none was skipped);\n * the count clears when a scan reads every shard.\n */\n receiptReadErrors?: () => number\n /**\n * Whether the status scan stopped at the store's 256-shard cap; status-time\n * read.\n *\n * True means every total in the answer covers only the first 256 sorted\n * shards: the figures are a lower bound, not the whole ledger. Absent means\n * the store has no such flag (or the last scan fitted), which is the\n * pre-existing \"totals are complete\" reading.\n */\n receiptsTruncated?: () => boolean\n /** Calls skipped because no family matched; status-time read. */\n unknownFamilies?: () => number\n /** Retained unmapped tool names; status-time read. */\n unknownTools?: () => Record<string, number>\n /**\n * Prompt assemblies whose protocol section was suppressed; status-time read.\n *\n * The prompt path is the one mount that acts on every request, so design\n * §5.5:378 makes it a count rather than a receipt. It is exposed because the\n * shipped default scope is *correctly* inert: with no counter, \"nothing\n * configured\" and \"assembly failed\" look identical from `status`.\n */\n protocolSuppressed?: () => number\n /** Requests whose final prompt lost the protocol to a complete section; status-time read. */\n completeSectionSuppressions?: () => number\n /**\n * Integration points `apply` could not mount; status-time read.\n *\n * A missing projection or flush hook leaves every ledger healthy-looking\n * while the plugin never acts, so the mounts are a fact `status` must\n * report. Absent means no mount failed (or the caller does not track them).\n */\n partialMounts?: () => readonly string[]\n /**\n * Cancellation for this invocation only.\n *\n * `runBoost` is also callable directly (tests, future hosts), so this is\n * optional; `boostTool.execute` fills it from the host's `exec.signal` and a\n * cancelled call leaves `scope.json` untouched.\n */\n signal?: AbortSignal\n}\n\n/** The scope document's caller-writable fields. Everything else is store-owned. */\nconst PATCH_FIELDS = ['mode', 'workspaceIds', 'shadow', 'projection'] as const\n\n/** Fields a caller must never set: the store owns one, the format fixes the other. */\nconst RESERVED_FIELDS = ['version', 'revision'] as const\n\n/** The four subcommands. */\ntype BoostCmd = 'status' | 'scope-get' | 'scope-set' | 'shadow'\n\n/** Raw tool arguments, after the model (or a test) produced them. */\ntype BoostArgs = { cmd: BoostCmd; body?: unknown; baseRevision?: number }\n\n/** Successful report or a stable failure code — never a thrown error. */\ntype BoostResult = { ok: true; data: unknown } | { ok: false; code: string }\n\n/** What `status` reports. Both switches are top-level on purpose: they differ. */\nexport interface BoostStatus {\n scope: { mode: ScopeDoc['mode']; workspaceIds: string[]; revision: number }\n shadow: boolean\n projection: ProjectionMode\n saved: {\n /**\n * **Upper** estimate: Σ numeric `saved_input_tokens` over settled\n * substitutions only.\n *\n * This is the next request's input, which overstates the avoided cost by\n * the substituted call's own result. The synth-time `substitute` line\n * predates any measurement (design §5.3 says the field is measured), so its\n * value is `'unknown'` or absent and never contributes; `counts` keeps the\n * event count.\n */\n substitution: number\n /**\n * **Lower** estimate: Σ numeric `avoided_total_tokens` over receipts that\n * carry the field.\n *\n * The producer writes the skipped request's own total (`before.input +\n * before.cacheRead + before.output`), so this is the avoided cost itself\n * rather than the next request's input. Omitted — never `0` — when no\n * receipt carries the field: a missing measurement must not read as\n * \"avoided nothing\" (review row 7).\n */\n substitution_avoided?: number\n /**\n * Σ `saved_projection_tokens` over non-retrieval projections, **replayed**\n * by each receipt's own `horizon_steps`.\n *\n * Replay-aware so this legacy object no longer mixes a one-time gross with\n * a replay net (review R2). The one-time figure is the top-level\n * `projection_gross_tokens`. A receipt that predates `horizon_steps` is\n * replayed at the current horizon; `projection_horizon_reestimated` counts\n * those, so a re-estimated figure is never mistaken for a measured one.\n */\n projectionGross: number | 'unknown'\n /**\n * Σ saved × (1 + that receipt's horizon) − Σ content × (1 + its horizon)\n * − Σ call blocks − legacy replay-aware costs.\n *\n * `'unknown'` when any retrieval in the ledger is unpriced: an unmeasured\n * cost must never silently become zero (review R3).\n */\n projectionNet: number | 'unknown'\n /** Number of `kind:'projection'` receipts marked `retrieved: true`. */\n retrievals: number\n }\n /** Receipt count per `code`, over every shard (including the empty session id). */\n counts: Record<string, number>\n /** Stable degradation codes actually observed. */\n degraded: string[]\n /**\n * Whether the host ever exposed a workspace registry.\n *\n * Reported separately from {@link degraded} because it is the single fact\n * that explains \"the plugin is installed and nothing ever happens\": with no\n * registry, no session resolves to a workspace and every path is inert.\n * Absent when no host was probed.\n */\n hasWorkspaceRegistry?: boolean\n /**\n * Whether the host exposed a spill store.\n *\n * Presence only: {@link degraded} carries `ERR_HOST_SPILL_UNUSABLE` when the\n * store exists but cannot save, and `ERR_HOST_NO_SPILL` when it is absent.\n * Absent when no host was probed.\n */\n hasSpill?: boolean\n /**\n * The measured per-request fixed cost: protocol section + tool schema.\n *\n * `'unknown'` when the host estimator is unreachable: the measurement is\n * never fabricated (design §9). Status-time only; see\n * `src/admission/fixed-cost.ts`.\n */\n fixedOverheadTokens: number | 'unknown'\n /** The two components behind {@link fixedOverheadTokens}. */\n fixedOverhead: FixedOverheadMeasurement | 'unknown'\n /**\n * Whether the ledger figures are provider-metered or estimates.\n *\n * `unknown` means no token meter: projection still clips, but its receipts\n * carry `'unknown'` rather than invented numbers, and substitution is\n * refused (design §9).\n */\n estimate_kind: 'host' | 'unknown'\n /** The current `(1 + horizon)` replay factor; the fallback for old receipts. */\n projection_horizon_steps: number\n /**\n * Projection receipts replayed at {@link projection_horizon_steps} because\n * they predate the per-receipt `horizon_steps` field.\n *\n * `0` means every replay figure in this report is the horizon its own\n * decision was made under. A non-zero value marks that part of the net is\n * re-estimated, not measured: an operator reading the shadow-week go/no-go\n * must be able to tell the two apart.\n */\n projection_horizon_reestimated: number\n /**\n * Σ one-time `saved_projection_tokens` over applied projections whose call\n * was **not** itself a retrieval.\n *\n * A retrieval's own projection is excluded: crediting it here while also\n * charging its visible window as retrieval cost would count the same tokens\n * from both sides (review I3).\n */\n projection_gross_tokens: number | 'unknown'\n /** {@link projection_gross_tokens} replayed at each receipt's own horizon. */\n projection_gross_replay_tokens: number | 'unknown'\n /** Σ one-time retrieval totals (call + content); `0` for unpriced receipts. */\n projection_retrieval_tokens: number\n /** Σ one-time retrieval content, the side that replays with the gross. */\n projection_retrieval_content_tokens: number\n /** Σ one-time retrieval call blocks; replay does not apply to these. */\n projection_retrieval_call_tokens: number\n /** Projections with no measured saving; the gross/net become `'unknown'`. */\n projection_unpriced_projections: number\n /** Retrievals with no usable token fields; their cost makes the net unknown. */\n projection_unpriced_retrievals: number\n /** Pre-schema retrievals priced through the old `retrievalCost` field. */\n projection_legacy_retrievals: number\n /**\n * The design's receipt-field spelling of `saved.retrievals`.\n *\n * Kept at the top level because the shadow-week operator reads the two\n * ledgers by the names §5.3 gives them; `saved` keeps the original camelCase\n * shape so existing consumers keep working. Both are derived from one\n * aggregation, so they cannot drift.\n */\n projection_retrievals: number\n /**\n * Σ saved × (1 + receipt horizon) − Σ retrieval content × (1 + its horizon)\n * − Σ retrieval call blocks.\n *\n * The retrieval's own projection is not in the gross, the content it made\n * visible replays at the horizon in effect when the retrieval happened, and\n * its call block is charged once. `'unknown'` when a retrieval is unpriced or\n * a meterless projection was clipped: a lower bound cannot be computed from a\n * missing measurement.\n */\n projection_net_tokens: number | 'unknown'\n /** Locators dropped by the per-session cap; a lossy ledger is visible. */\n projection_locator_evictions: number\n /** Calls skipped because no projection family matched. */\n projection_unknown_families: number\n /** Retained unmapped tool names (at most 32), for mapper-gap diagnosis. */\n projection_unknown_tools: Record<string, number>\n /**\n * Prompt assemblies whose protocol section was suppressed.\n *\n * Counted, never receipted, because assembly runs on every request (design\n * §5.5:378). A live, monotonically increasing number is the only evidence\n * that the inert-looking default is \"no workspace configured\" rather than a\n * section that failed to inject.\n */\n protocol_suppressed: number\n /**\n * Whether the receipt store stopped accepting writes (fail-closed).\n *\n * Once true, substitution is refused outright (design §5.2-3) and every\n * figure above is a stale snapshot. Reported because the alternative is an\n * operator reading frozen numbers with no warning that they froze.\n */\n receipts_stopped: boolean\n}\n\n/** A validated scope patch: only the caller-writable fields survive. */\ntype ScopePatch = Partial<Pick<ScopeDoc, (typeof PATCH_FIELDS)[number]>>\n\n/**\n * The replay horizon one projection receipt was measured under.\n *\n * The decision path writes `horizon_steps` on every projection receipt it\n * produces. A receipt from before that field existed is replayed at the\n * current horizon and flagged as re-estimated, so `status` can tell the\n * operator how much of the net is measured rather than re-valued. A malformed\n * value is treated as absent, never trusted.\n */\nfunction replayOf(\n receipt: Receipt,\n fallback: number,\n): { horizon: number; reestimated: boolean } {\n const raw = receipt.horizon_steps\n if (typeof raw === 'number' && Number.isFinite(raw) && raw >= 0) {\n return { horizon: Math.floor(raw), reestimated: false }\n }\n return { horizon: fallback, reestimated: true }\n}\n\n/**\n * The receipt aggregation behind `status`, kept separate from the document\n * read so the accounting has one home and one test surface.\n *\n * `scan()` is called with no session id on purpose: `skip:no-scope` receipts\n * are not owned by one shard. The no-agent case writes the empty session id;\n * the cold-judgement path writes the real session id, once per tool call by\n * design (design §5.5:377), which is expected in unscoped workspaces and will\n * dominate their shards — not a leak. Only a whole-store scan sees both.\n *\n * Unreadable shards are the store's concern: `scan()` skips them and\n * `readErrors()` reports the count, so `status` has exactly one source for\n * `ERR_RECEIPTS_UNREADABLE` and a throwing store is an internal failure, not a\n * second degradation channel.\n *\n * The replay sums are computed here, per receipt, from each receipt's own\n * `horizon_steps`. A receipt written before that field existed is replayed at\n * `fallbackHorizon` (the current horizon) and counted in\n * `horizonReestimated`, so the report can say how much of the net is measured\n * rather than re-estimated.\n */\nasync function aggregate(\n receipts: ReceiptStore,\n fallbackHorizon: number,\n): Promise<{\n counts: Record<string, number>\n substitution: number\n substitutionAvoided?: number\n projectionGross: number\n projectionGrossReplay: number\n retrievalContentReplay: number\n horizonReestimated: number\n unpricedProjections: number\n retrievalTokens: number\n retrievalContentTokens: number\n retrievalCallTokens: number\n retrievals: number\n unpricedRetrievals: number\n legacyRetrievals: number\n legacyRetrievalCost: number\n degraded: string[]\n}> {\n const counts: Record<string, number> = Object.create(null)\n let substitution = 0\n let substitutionAvoided = 0\n let avoidedSeen = false\n let projectionGross = 0\n let projectionGrossReplay = 0\n let retrievalContentReplay = 0\n let horizonReestimated = 0\n let unpricedProjections = 0\n let retrievalTokens = 0\n let retrievalContentTokens = 0\n let retrievalCallTokens = 0\n let retrievals = 0\n let unpricedRetrievals = 0\n let legacyRetrievals = 0\n let legacyRetrievalCost = 0\n\n for await (const receipt of receipts.scan()) {\n // A receipt is untrusted text from a file: `counts` has no prototype so a\n // code of `toString` or `__proto__` is an ordinary numeric key, never a\n // string concatenation and never a dropped assignment.\n if (typeof receipt.code === 'string') {\n counts[receipt.code] = (counts[receipt.code] ?? 0) + 1\n }\n\n // Only the settled line carries a measured saving; the synth-time line is\n // an event and is already visible in `counts`.\n if (receipt.kind === 'substitute-settled') {\n const saved = receipt.saved_input_tokens\n if (typeof saved === 'number' && Number.isFinite(saved)) substitution += saved\n }\n\n // The lower estimate is the skipped request's own total, summed over every\n // receipt that carries it (the settled line is its producer). Presence is\n // tracked separately from the value: a receipt carrying `0` is a\n // measurement, while no receipt carrying the field means \"not measured\"\n // and the key is omitted from `status` rather than reported as zero\n // (review row 7).\n // Pair the two sums on the same receipt: a rollover settlement writes a\n // numeric lower bound with `saved_input_tokens: 'unknown'`, so summing the\n // lower over a superset could report a floor above the ceiling\n // (review qr5#2). A receipt that carries only one side contributes to\n // neither.\n const avoided = receipt.avoided_total_tokens\n const upper = receipt.saved_input_tokens\n if (\n typeof avoided === 'number' &&\n Number.isFinite(avoided) &&\n typeof upper === 'number' &&\n Number.isFinite(upper)\n ) {\n substitutionAvoided += avoided\n avoidedSeen = true\n }\n\n if (receipt.kind !== 'projection') continue\n\n const replay = replayOf(receipt, fallbackHorizon)\n\n if (receipt.unit === 'raw' && receipt.call_was_retrieval !== true && receipt.retrieved !== true) {\n // T23b/T26 write `saved_projection_tokens`; `saved` is the pre-T23b\n // spelling this consumer accepted first. Never estimate a value here.\n // A retrieval's own projection is excluded from gross: its visible\n // window is charged as retrieval content instead (review I3).\n const saved = receipt.saved_projection_tokens ?? receipt.saved\n if (typeof saved === 'number' && Number.isFinite(saved)) {\n projectionGross += saved\n projectionGrossReplay += saved * (1 + replay.horizon)\n if (replay.reestimated) horizonReestimated += 1\n }\n // A meterless projection carries `estimate:'unknown'` and no saved\n // figure. Reporting the remaining numeric sum as the gross would present\n // an unmeasured effect as zero (review R4).\n else unpricedProjections += 1\n }\n\n if (receipt.retrieved !== true) continue\n retrievals += 1\n\n const total = receipt.retrieval_tokens\n const call = receipt.retrieval_call_tokens\n const content = receipt.retrieval_content_tokens\n if (\n typeof total === 'number' &&\n Number.isFinite(total) &&\n total >= 0 &&\n typeof call === 'number' &&\n Number.isFinite(call) &&\n call >= 0 &&\n typeof content === 'number' &&\n Number.isFinite(content) &&\n content >= 0 &&\n total === call + content\n ) {\n retrievalTokens += total\n retrievalCallTokens += call\n retrievalContentTokens += content\n retrievalContentReplay += content * (1 + replay.horizon)\n if (replay.reestimated) horizonReestimated += 1\n continue\n }\n\n // Pre-schema receipts (written before the split) carry only the old\n // already-replayed `retrievalCost` total. Subtracting it directly from the\n // replayed net avoids counting it as free (review R6). Its own projection,\n // if any, predates the `call_was_retrieval` marker and cannot be identified\n // from the file; that is documented in the report.\n const legacy = receipt.retrievalCost\n if (typeof legacy === 'number' && Number.isFinite(legacy) && legacy >= 0) {\n legacyRetrievals += 1\n legacyRetrievalCost += legacy\n retrievalTokens += legacy\n continue\n }\n\n // Neither schema: the cost is unknown, not zero. The net is reported as\n // `'unknown'` rather than silently treating the retrieval as free.\n unpricedRetrievals += 1\n }\n\n const degraded = RECEIPT_DEGRADATION.filter(entry => counts[entry.code] !== undefined).map(\n entry => entry.degraded,\n )\n return {\n counts,\n substitution,\n ...(avoidedSeen ? { substitutionAvoided } : {}),\n projectionGross,\n projectionGrossReplay,\n retrievalContentReplay,\n horizonReestimated,\n unpricedProjections,\n retrievalTokens,\n retrievalContentTokens,\n retrievalCallTokens,\n retrievals,\n unpricedRetrievals,\n legacyRetrievals,\n legacyRetrievalCost,\n degraded,\n }\n}\n\n/**\n * The fixed overhead measurement, never a thrown status.\n *\n * The production deps carry the promise `apply` started at load; the default\n * is the same memoised measurement, so a direct `runBoost` (a unit test or a\n * host that built the tool itself) still reports a real number. A rejection or\n * an invalid breakdown is `'unknown'`, for the same reason the estimator's own\n * failure is.\n */\nasync function fixedOverheadOf(deps: BoostDeps): Promise<FixedOverheadMeasurement | 'unknown'> {\n try {\n const value = await (deps.fixedOverhead ?? measureBoostFixedOverhead)()\n if (value === 'unknown') return 'unknown'\n const { protocolTokens, toolSchemaTokens, totalTokens } = value\n if (\n !Number.isFinite(protocolTokens) ||\n !Number.isFinite(toolSchemaTokens) ||\n !Number.isFinite(totalTokens) ||\n protocolTokens < 0 ||\n toolSchemaTokens < 0 ||\n totalTokens !== protocolTokens + toolSchemaTokens\n ) {\n return 'unknown'\n }\n return value\n } catch {\n return 'unknown'\n }\n}\n\n/** The configured replay horizon, or the design default when absent/malformed. */\nfunction horizonOf(deps: BoostDeps): number {\n const raw = deps.horizonSteps\n return typeof raw === 'number' && Number.isFinite(raw) && raw >= 0\n ? Math.floor(raw)\n : DEFAULT_CONFIG.horizonSteps\n}\n\n/** The label for the assembly's estimator; unprobed is honestly `unknown`. */\nfunction estimateKindOf(deps: BoostDeps): BoostStatus['estimate_kind'] {\n const kind = deps.estimateKind\n return kind === 'host' || kind === 'unknown' ? kind : 'unknown'\n}\n\n/**\n * Whether the receipt store has stopped writing, fail-closed.\n *\n * Mirrors `receiptsStopped` in `src/hooks/llm-stream.ts` for the control tool's\n * own store reference: a partial store is \"not stopped\", and a store that\n * throws cannot record evidence, which is what stopped means.\n */\nfunction receiptsStopped(store: BoostDeps['receipts']): boolean {\n try {\n if (store == null || typeof store.stopped !== 'function') return false\n return store.stopped() === true\n } catch {\n return true\n }\n}\n\n/** Whether the last whole-store scan stopped at the shard cap, never thrown. */\nfunction receiptsTruncatedOf(deps: BoostDeps): boolean {\n try {\n if (deps.receiptsTruncated !== undefined) return deps.receiptsTruncated() === true\n // The store owns the fact; the override exists for a fake counter. Reading\n // the store directly keeps a hand-built `runBoost` (no measured deps) from\n // silently losing the code.\n return deps.receipts.scanTruncated() === true\n } catch {\n return false\n }\n}\n\n/** Skipped shard reads, from the override or the store's own reading. */\nfunction receiptReadErrorsOf(deps: BoostDeps): number {\n if (deps.receiptReadErrors !== undefined) return counterOf(deps.receiptReadErrors)\n try {\n return counterOf(() => deps.receipts.readErrors())\n } catch {\n return 0\n }\n}\n\n/** A monotonic status counter, never a thrown status. */\nfunction counterOf(read: (() => number) | undefined): number {\n try {\n const value = read?.()\n return typeof value === 'number' && Number.isFinite(value) && value >= 0\n ? Math.floor(value)\n : 0\n } catch {\n return 0\n }\n}\n\n/** A bounded unmapped-tool map, never a thrown status. */\nfunction toolCountsOf(read: (() => Record<string, number>) | undefined): Record<string, number> {\n // Build through a Map: `counts['__proto__'] = n` on a plain object would\n // mutate its prototype, and tool names come from the host. `fromEntries` is\n // an own-property copy, so the returned object has the normal prototype and\n // deep-equality consumers see a plain record.\n const counts = new Map<string, number>()\n try {\n const value = read?.()\n if (value === null || typeof value !== 'object') return {}\n for (const [name, count] of Object.entries(value)) {\n if (typeof count === 'number' && Number.isFinite(count) && count >= 0) counts.set(name, count)\n }\n } catch {\n // A foreign counter is evidence, not a failure.\n }\n return Object.fromEntries(counts)\n}\n\n/**\n * The stable degradation codes for one status call.\n *\n * Inputs are the receipt-observed codes, the scope read's stable code, the host\n * facts, and the mount points `apply` could not wire. Receipt codes are already\n * mapped; the scope store's internal\n * `scope-degraded` label is deliberately **not** copied — the report's contract\n * is stable codes only. Order is deterministic (receipts, scope, host) and the\n * result is deduplicated, so one condition observed through two channels\n * appears once.\n *\n * Two different absences stay distinct: `ERR_HOST_NO_TOKENMETER` is the\n * **service** (`ctx.get('tokenMeter')`) being absent, which refuses\n * substitution; `ERR_HOST_NO_ESTIMATOR` is the pure estimate package being\n * unreachable, which makes the fixed-overhead figure `'unknown'`. A host with\n * the package but no service reports the latter only.\n *\n * `when` on `tools.register` has been part of `ToolRegistrationOptions` since\n * the oldest host line this plugin declares, so there is no \"host without\n * step-level `when`\" to report: probing it would evaluate every other plugin's\n * predicate against a fabricated `Agent`, and a fact that can never be true is\n * a claim, not a measurement. `apply` registers unconditionally instead.\n */\nfunction degradationCodes(\n observed: readonly string[],\n read: Awaited<ReturnType<ScopeStore['read']>>,\n host: BoostHostFacts | undefined,\n fixedOverhead: FixedOverheadMeasurement | 'unknown',\n missingMounts: readonly string[] = [],\n): string[] {\n const codes: string[] = [...observed]\n if (read.degraded !== undefined) codes.push(read.code ?? ERR_SCOPE_READ_FAILED)\n\n if (!isPosixOnly()) codes.push(ERR_HOST_PLATFORM_UNSUPPORTED)\n if (host?.hasTokenMeter === false) codes.push(ERR_HOST_NO_TOKENMETER)\n if (fixedOverhead === 'unknown') codes.push(ERR_HOST_NO_ESTIMATOR)\n // `spillStore` matters only in apply mode; shadow mode never touches it\n // (design §5.4), so reporting it while projection is `shadow` would be noise.\n // Presence and capability are separate: an absent store and a present store\n // without `saveText` need different repairs, so they get different codes.\n if (read.doc.projection === 'on') {\n if (host?.hasSpill === false) codes.push(ERR_HOST_NO_SPILL)\n else if (host?.spillUsable === false) codes.push(ERR_HOST_SPILL_UNUSABLE)\n }\n // A present registry that cannot list is not an absent one: the operator is\n // told which of the two host states to repair (review row 6).\n if (host?.hasWorkspaceRegistry === false) codes.push(ERR_HOST_NO_WORKSPACE_REGISTRY)\n else if (host?.workspaceRegistryBroken === true) codes.push(ERR_HOST_WORKSPACE_REGISTRY_BROKEN)\n // A missing mount is a wiring failure, not a capability absence: the plugin\n // is loaded but at least one of its four integration points is not, so the\n // ledgers cannot be trusted to describe what it is doing.\n if (missingMounts.length > 0) codes.push(ERR_BOOST_PARTIAL_MOUNT)\n\n return [...new Set(codes)]\n}\n\n/** `status`: the scope document plus the receipt ledgers, never a failure. */\nasync function statusCommand(deps: BoostDeps): Promise<BoostResult> {\n const read = await deps.scope.read()\n const horizon = horizonOf(deps)\n // Each receipt replays at its own horizon; `horizon` is only the fallback for\n // receipts that predate the field, and `horizonReestimated` counts them.\n const totals = await aggregate(deps.receipts, horizon)\n const fixedOverhead = await fixedOverheadOf(deps)\n const degraded = degradationCodes(\n totals.degraded,\n read,\n deps.host,\n fixedOverhead,\n deps.partialMounts?.() ?? [],\n )\n // A shard the scan could not read is evidence, not a status failure: the\n // healthy shards were counted and the operator gets a stable code saying the\n // ledger is incomplete. `readErrors()` is the only producer; it counts skips\n // since the last fully readable whole-store scan, so a repaired shard clears\n // the code.\n if (receiptReadErrorsOf(deps) > 0 && !degraded.includes(ERR_RECEIPTS_UNREADABLE)) {\n degraded.push(ERR_RECEIPTS_UNREADABLE)\n }\n // The scan cap makes every figure a lower bound over the first 256 sorted\n // shards. Under-counting is safe, but it must not be presented as a total.\n if (receiptsTruncatedOf(deps) && !degraded.includes(ERR_RECEIPTS_TRUNCATED)) {\n degraded.push(ERR_RECEIPTS_TRUNCATED)\n }\n // A complete prompt section silently removed the protocol from the request:\n // the workspace is visible but substitution cannot be taught, so the operator\n // must see why the plugin is inert.\n if (counterOf(deps.completeSectionSuppressions) > 0) degraded.push(ERR_HOST_COMPLETE_SECTION)\n const estimateKind = estimateKindOf(deps)\n\n // Meterless projections have `estimate:'unknown'` receipts with no saved\n // figure. Reporting the numeric sum of the rest as 0/0 would be\n // indistinguishable from \"projection had no effect\" (review R4).\n const meterlessEvidence = totals.unpricedProjections > 0\n const grossOneTime = meterlessEvidence ? 'unknown' : totals.projectionGross\n const grossReplay = grossOneTime === 'unknown' ? 'unknown' : totals.projectionGrossReplay\n\n // A retrieval's own projection is excluded from gross; its content replays\n // with the gross, its call block is charged once, and a legacy cost was\n // already replay-aware (review I3/R6). An unpriced retrieval makes the whole\n // net unknown rather than free (review R3).\n const netUnknown = meterlessEvidence || totals.unpricedRetrievals > 0\n const projectionNet =\n netUnknown\n ? 'unknown'\n : totals.projectionGrossReplay -\n totals.retrievalContentReplay -\n totals.retrievalCallTokens -\n totals.legacyRetrievalCost\n\n const saved: BoostStatus['saved'] = {\n substitution: totals.substitution,\n ...(totals.substitutionAvoided === undefined\n ? {}\n : { substitution_avoided: totals.substitutionAvoided }),\n projectionGross: grossReplay,\n projectionNet,\n retrievals: totals.retrievals,\n }\n const data: BoostStatus = {\n scope: {\n mode: read.doc.mode,\n workspaceIds: read.doc.workspaceIds,\n revision: read.doc.revision,\n },\n shadow: read.doc.shadow,\n projection: read.doc.projection,\n saved,\n counts: totals.counts,\n degraded,\n fixedOverheadTokens: fixedOverhead === 'unknown' ? 'unknown' : fixedOverhead.totalTokens,\n fixedOverhead,\n estimate_kind: estimateKind,\n projection_horizon_steps: horizon,\n projection_horizon_reestimated: totals.horizonReestimated,\n projection_gross_tokens: grossOneTime,\n projection_gross_replay_tokens: grossReplay,\n projection_retrieval_tokens: totals.retrievalTokens,\n projection_retrieval_content_tokens: totals.retrievalContentTokens,\n projection_retrieval_call_tokens: totals.retrievalCallTokens,\n projection_unpriced_projections: totals.unpricedProjections,\n projection_unpriced_retrievals: totals.unpricedRetrievals,\n projection_legacy_retrievals: totals.legacyRetrievals,\n projection_retrievals: totals.retrievals,\n projection_net_tokens: projectionNet,\n projection_locator_evictions: counterOf(deps.locatorEvictions),\n projection_unknown_families: counterOf(deps.unknownFamilies),\n projection_unknown_tools: toolCountsOf(deps.unknownTools),\n protocol_suppressed: counterOf(deps.protocolSuppressed),\n receipts_stopped: receiptsStopped(deps.receipts),\n // An absent host fact is \"not probed\", not `false`: `undefined` is not a\n // legal JSON value, so the key is omitted rather than handed to the host\n // boundary (review row 35).\n ...(deps.host?.hasWorkspaceRegistry === undefined\n ? {}\n : { hasWorkspaceRegistry: deps.host.hasWorkspaceRegistry }),\n ...(deps.host?.hasSpill === undefined ? {} : { hasSpill: deps.host.hasSpill }),\n }\n return { ok: true, data }\n}\n\n/** `scope-get`: a faithful read; a degraded read is a stable tool failure. */\nasync function scopeGetCommand(deps: BoostDeps): Promise<BoostResult> {\n const read = await deps.scope.read()\n if (read.degraded !== undefined) return { ok: false, code: read.code ?? ERR_SCOPE_READ_FAILED }\n return { ok: true, data: read.doc }\n}\n\n/** Whether a value can be a caller-supplied base revision. */\nfunction isRevision(value: unknown): value is number {\n return typeof value === 'number' && Number.isInteger(value) && value >= 0\n}\n\n/** Whether `value` is one of the three projection modes. */\nfunction isProjectionMode(value: unknown): value is ProjectionMode {\n return value === 'off' || value === 'shadow' || value === 'on'\n}\n\n/**\n * Validate a `scope-set` body and prune it to the writable fields.\n *\n * Reserved fields are checked **first**: the store persists whatever `mutate`\n * returns, so a body carrying `version` or `revision` must be refused before a\n * patch is built, not stripped and written as if the caller's intent were\n * merely advisory. Unknown keys are pruned; a known key with a wrong type is\n * rejected, never coerced.\n */\nfunction scopePatchOf(body: unknown): { ok: true; patch: ScopePatch } | { ok: false; code: string } {\n if (body === null || typeof body !== 'object' || Array.isArray(body)) {\n return { ok: false, code: ERR_BOOST_INVALID_BODY }\n }\n const source = body as Record<string, unknown>\n const has = (key: string): boolean => Object.prototype.hasOwnProperty.call(source, key)\n if (RESERVED_FIELDS.some(has)) return { ok: false, code: ERR_BOOST_INVALID_BODY }\n\n const patch: ScopePatch = {}\n if (has('mode')) {\n if (source.mode !== 'selected' && source.mode !== 'global') {\n return { ok: false, code: ERR_BOOST_INVALID_BODY }\n }\n patch.mode = source.mode\n }\n if (has('workspaceIds')) {\n const ids = source.workspaceIds\n if (!Array.isArray(ids) || !ids.every(id => typeof id === 'string')) {\n return { ok: false, code: ERR_BOOST_INVALID_BODY }\n }\n patch.workspaceIds = [...ids]\n }\n if (has('shadow')) {\n if (typeof source.shadow !== 'boolean') return { ok: false, code: ERR_BOOST_INVALID_BODY }\n patch.shadow = source.shadow\n }\n if (has('projection')) {\n if (!isProjectionMode(source.projection)) return { ok: false, code: ERR_BOOST_INVALID_BODY }\n patch.projection = source.projection\n }\n return { ok: true, patch }\n}\n\n/** The store's stable code, or undefined for anything else (which never escapes). */\nfunction scopeCodeOf(error: unknown): ScopeCode | undefined {\n if (typeof error !== 'object' || error === null || !('code' in error)) return undefined\n const code = (error as { code?: unknown }).code\n return typeof code === 'string' && SCOPE_CODES.has(code) ? (code as ScopeCode) : undefined\n}\n\n/**\n * One compare-and-swap write shared by `scope-set` and `shadow`.\n *\n * `version: 2` is forced even though `ScopeStore.write` bases a corrupt or\n * v1 file on `DEFAULT_SCOPE`: the invariant must hold at the mutation boundary,\n * where the store's \"persist whatever `mutate` returns\" contract makes it\n * binding. `revision` is deliberately absent — the store owns it.\n */\nasync function writeScope(\n scope: ScopeStore,\n mutate: (doc: ScopeDoc) => ScopeDoc,\n baseRevision: number,\n signal?: AbortSignal,\n): Promise<BoostResult> {\n try {\n const doc = await scope.write(mutate, baseRevision, { signal })\n return { ok: true, data: doc }\n } catch (error) {\n const code = scopeCodeOf(error)\n if (code !== undefined) return { ok: false, code }\n throw error\n }\n}\n\n/** `scope-set`: validate, prune, then write with compare-and-swap. */\nasync function scopeSetCommand(deps: BoostDeps, args: BoostArgs): Promise<BoostResult> {\n const parsed = scopePatchOf(args.body)\n if (!parsed.ok) return parsed\n if (!isRevision(args.baseRevision)) return { ok: false, code: ERR_BOOST_INVALID_ARGS }\n const patch = parsed.patch\n return writeScope(\n deps.scope,\n doc => ({ ...doc, ...patch, version: 2 }),\n args.baseRevision,\n deps.signal,\n )\n}\n\n/**\n * `shadow`: the shadow-week switch, independent of `projection`.\n *\n * A version 1 document is **not** upgraded here. The store can carry a v1\n * document through a write, but design §5.5 makes `scope-set` the explicit\n * upgrade path: the other write refuses with the degraded read's stable code so\n * the operator performs the documented upgrade instead of a blind rewrite.\n */\nasync function shadowCommand(deps: BoostDeps, args: BoostArgs): Promise<BoostResult> {\n if (typeof args.body !== 'boolean') return { ok: false, code: ERR_BOOST_INVALID_BODY }\n if (!isRevision(args.baseRevision)) return { ok: false, code: ERR_BOOST_INVALID_ARGS }\n const current = await deps.scope.read()\n if (current.code === ERR_SCOPE_UNKNOWN_VERSION) {\n return { ok: false, code: ERR_SCOPE_UNKNOWN_VERSION }\n }\n const shadow = args.body\n return writeScope(deps.scope, doc => ({ ...doc, shadow }), args.baseRevision, deps.signal)\n}\n\n/** One handler per subcommand; the table is the dispatch and the documentation. */\nconst COMMANDS: Record<BoostCmd, (deps: BoostDeps, args: BoostArgs) => Promise<BoostResult>> = {\n status: statusCommand,\n 'scope-get': scopeGetCommand,\n 'scope-set': scopeSetCommand,\n shadow: shadowCommand,\n}\n\n/**\n * Run one `boost` invocation. Pure orchestration over the two stores.\n *\n * Failures are values: an unknown command, an invalid body or a store code all\n * come back as `{ ok: false, code }`. The `try` covers the argument read as\n * well as the handler, so a null call or an argument object with a throwing\n * getter answers a stable code instead of throwing. The catch exists only so\n * an unexpected store failure cannot turn the user's only control surface into\n * a thrown tool error; it is not an expected path.\n */\nexport async function runBoost(\n input: BoostDeps & {\n args: { cmd: BoostCmd; body?: unknown; baseRevision?: number }\n },\n): Promise<{ ok: true; data: unknown } | { ok: false; code: string }> {\n try {\n const signal = (input as { signal?: AbortSignal } | null | undefined)?.signal\n if (signal?.aborted === true) return { ok: false, code: ERR_SCOPE_ABORTED }\n const args = (input as { args?: unknown } | null | undefined)?.args\n const cmd = (args as { cmd?: unknown } | null | undefined)?.cmd\n const handler =\n typeof cmd === 'string' && Object.prototype.hasOwnProperty.call(COMMANDS, cmd)\n ? COMMANDS[cmd as BoostCmd]\n : undefined\n if (handler === undefined) return { ok: false, code: ERR_BOOST_UNKNOWN_CMD }\n return await handler(input as BoostDeps, args as BoostArgs)\n } catch {\n return { ok: false, code: ERR_BOOST_INTERNAL }\n }\n}\n\n/**\n * The host's cancellation signal, or `undefined` for any other shape.\n *\n * `exec` crosses the host boundary and is untrusted here: a plain object with\n * an `aborted` boolean and an `addEventListener` function is the documented\n * `AbortSignal` contract this code relies on, and anything else is ignored\n * rather than dereferenced (a foreign host must not make `boost` throw).\n */\nfunction signalOf(exec: unknown): AbortSignal | undefined {\n const candidate = (exec as { signal?: unknown } | null | undefined)?.signal\n if (typeof candidate !== 'object' || candidate === null) return undefined\n const signal = candidate as { aborted?: unknown; addEventListener?: unknown }\n if (typeof signal.aborted !== 'boolean' || typeof signal.addEventListener !== 'function') {\n return undefined\n }\n return candidate as AbortSignal\n}\n\n/** Model-facing description: what each command does and what it returns. */\nconst DESCRIPTION = [\n 'Inspect or change dsh-boost state. Commands:',\n 'status reports the scope document, both switches, receipt counts per code, both ledgers (substitution; projection net with its retrieval count), the measured fixed overhead, and the degraded codes;',\n 'scope-get reads the full scope document;',\n 'scope-set replaces the given fields with compare-and-swap; body = { mode?, workspaceIds?, shadow?, projection? }; version and revision are store-owned and rejected;',\n 'shadow persists the shadow-week switch; body = boolean; it refuses a version 1 document with ERR_SCOPE_UNKNOWN_VERSION — run scope-set once to upgrade it.',\n 'scope-set and shadow require the baseRevision last seen via status or scope-get; a stale one fails with ERR_SCOPE_REVISION_CONFLICT. Failures are { ok:false, code } values, never thrown.',\n].join(' ')\n\n/** The argument schema shown to the model; `status`/`scope-get` need only `cmd`. */\nconst PARAMETERS: Record<string, unknown> = {\n type: 'object',\n properties: {\n cmd: {\n type: 'string',\n enum: ['status', 'scope-get', 'scope-set', 'shadow'],\n description: 'Which boost operation to run.',\n },\n body: {\n description:\n 'scope-set: the desired scope fields (unknown keys are pruned, version/revision rejected). shadow: the desired boolean.',\n oneOf: [\n {\n type: 'object',\n properties: {\n mode: { type: 'string', enum: ['selected', 'global'] },\n workspaceIds: { type: 'array', items: { type: 'string' } },\n shadow: { type: 'boolean' },\n projection: { type: 'string', enum: ['off', 'shadow', 'on'] },\n },\n },\n { type: 'boolean' },\n ],\n },\n baseRevision: {\n // `minimum` is outside the host's enforced JSON-Schema subset; the\n // runtime check in `isRevision` is the authority for `>= 0` (row 45).\n type: 'integer',\n description: 'Required by scope-set and shadow: the revision last seen (a non-negative integer).',\n },\n },\n required: ['cmd'],\n additionalProperties: false,\n}\n\n/**\n * The model-visible part of the `boost` tool definition.\n *\n * This is the second half of the fixed-overhead budget: `estimateToolsTokens`\n * prices the schema the model receives every request. `output` is a host-side\n * envelope and is not part of the request's tool list, so it is excluded.\n */\nfunction boostSchema(): { name: 'boost'; description: string; parameters: Record<string, unknown> } {\n return { name: 'boost', description: DESCRIPTION, parameters: PARAMETERS }\n}\n\n/** The one memoised protocol + schema measurement, shared by startup and status. */\nlet boostFixedOverhead: Promise<FixedOverheadMeasurement | 'unknown'> | undefined\n\n/**\n * The startup probe `apply` fires once and `status` awaits.\n *\n * Memoised per process: a status call must report the same number the startup\n * measured, and must not re-import or re-price the schema.\n */\nexport function measureBoostFixedOverhead(): Promise<FixedOverheadMeasurement | 'unknown'> {\n boostFixedOverhead ??= measureFixedOverhead(boostSchema())\n return boostFixedOverhead\n}\n\n/**\n * The canonical output envelope. The host validates every successful return\n * against this schema, and a failure is a successful call whose value is\n * `{ ok: false, code }` (the tool never throws its stable codes), so both\n * branches are declared.\n */\nconst OUTPUT_SCHEMA: JsonSchemaNode = {\n oneOf: [\n {\n type: 'object',\n properties: {\n ok: { type: 'boolean', const: true },\n data: {},\n },\n required: ['ok', 'data'],\n additionalProperties: false,\n },\n {\n type: 'object',\n properties: {\n ok: { type: 'boolean', const: false },\n code: { type: 'string' },\n },\n required: ['ok', 'code'],\n additionalProperties: false,\n },\n ],\n}\n\n/** Render the canonical envelope as one text block; `JSON.stringify` is the format. */\nfunction renderResult(_args: unknown, value: unknown): { type: 'text'; text: string }[] {\n return [{ type: 'text', text: JSON.stringify(value) ?? 'undefined' }]\n}\n\n/**\n * Build the host tool definition.\n *\n * `output: { schema, render }` is mandatory in the host's `ToolDefinition`;\n * a definition missing it is rejected at registration. `execute` reuses\n * `runBoost`, so the tool and the pure orchestration cannot drift.\n */\nexport function boostTool(deps: BoostDeps): {\n name: 'boost'\n description: string\n parameters: Record<string, unknown>\n output: {\n schema: JsonSchemaNode\n render: (args: unknown, value: unknown) => { type: 'text'; text: string }[]\n }\n execute: (args: unknown, exec: unknown) => Promise<unknown>\n} {\n return {\n name: 'boost',\n description: DESCRIPTION,\n parameters: PARAMETERS,\n output: { schema: OUTPUT_SCHEMA, render: renderResult },\n execute: (args, exec) => runBoost({ args: args as BoostArgs, ...deps, signal: signalOf(exec) }),\n }\n}"]}
|
|
1
|
+
{"version":3,"file":"boost.js","sourceRoot":"","sources":["../../src/tools/boost.ts"],"names":[],"mappings":"AAoEA,OAAO,EAAE,oBAAoB,EAAE,MAAM,4BAA4B,CAAA;AAEjE,OAAO,EAAE,cAAc,EAAE,MAAM,cAAc,CAAA;AAC7C,OAAO,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAA;AAEjD,OAAO,EACL,iBAAiB,EACjB,wBAAwB,EACxB,gBAAgB,EAChB,sBAAsB,EACtB,qBAAqB,EACrB,sBAAsB,EACtB,2BAA2B,EAC3B,yBAAyB,GAC1B,MAAM,iBAAiB,CAAA;AAKxB,2EAA2E;AAC3E,MAAM,qBAAqB,GAAG,uBAAuB,CAAA;AAErD,yFAAyF;AACzF,MAAM,CAAC,MAAM,sBAAsB,GAAG,wBAAwB,CAAA;AAE9D,wEAAwE;AACxE,MAAM,CAAC,MAAM,sBAAsB,GAAG,wBAAwB,CAAA;AAE9D,sFAAsF;AACtF,MAAM,CAAC,MAAM,kBAAkB,GAAG,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AO;QACL,IAAI,EAAE,OAAO;QACb,WAAW,EAAE,WAAW;QACxB,UAAU,EAAE,UAAU;QACtB,MAAM,EAAE,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,EAAE,YAAY,EAAE;QACvD,OAAO,EAAE,CAAC,IAAI,EAAE,IAAI,EAAE,EAAE,CAAC,QAAQ,CAAC,EAAE,IAAI,EAAE,IAAiB,EAAE,GAAG,IAAI,EAAE,MAAM,EAAE,QAAQ,CAAC,IAAI,CAAC,EAAE,CAAC;KAChG,CAAA;AACH,CAAC","sourcesContent":["/**\n * The `boost` control tool: the user's only way to see or change what the\n * plugin is doing.\n *\n * The plugin itself is invisible — it rewrites what the model sees and never\n * speaks — so this tool's output is part of the product, not a debugging aid.\n * `status` reports what the plugin has actually recorded: the scope document's\n * exposure surface, both switches (`shadow` and `projection`; \"recording but\n * not replacing\" is not \"replacing\"), per-code receipt counts over **every**\n * shard, the substitution and projection ledgers, and the stable degraded\n * codes observed. `scope-get` reads `scope.json`; `scope-set` and `shadow`\n * write it; both writes are compare-and-swap through `ScopeStore.write`, so a\n * stale caller gets `ERR_SCOPE_REVISION_CONFLICT` rather than silently\n * overwriting a concurrent change.\n *\n * ## Contracts this module keeps\n *\n * - Every failure is a stable code in a returned value; nothing throws out of\n * `runBoost`. The store's own codes are passed through unchanged.\n * - `scope-set` never lets a caller set `version` or `revision`: `revision` is\n * the store's, `version` is fixed at 2, and a body carrying either reserved\n * field is rejected **before** the mutation runs. The store persists whatever\n * `mutate` returns, so this rejection is what stops a v1-shaped document.\n * - Both ledger sides come from the receipts. This module never estimates a\n * retrieval cost: an unpriced retrieval makes the net `'unknown'` rather\n * than free, and `projection_unpriced_retrievals` says how many there were.\n * A retrieval's own projection is excluded from gross because its visible\n * window is already charged as retrieval content. The projection saving is\n * read from `saved_projection_tokens` (the design §5.3 name T23b/T26 write),\n * falling back to `saved`; a producer must write one of them, while a\n * meterless projection has neither and makes gross/net `'unknown'`. The\n * substitution saving is read only from the settled line, because the\n * synth-time line predates any measurement.\n * - `status.degraded` is a list of **stable codes only** (`ERR_HOST_*` /\n * `ERR_SCOPE_*`; the one wiring code is `ERR_BOOST_PARTIAL_MOUNT`). The scope\n * store's internal `scope-degraded` label and the\n * receipt stream's `projection-skipped:*` are inputs, not output: a receipt\n * code is mapped to `ERR_HOST_NO_SPILL` (no spill backend),\n * `ERR_HOST_SPILL_FAILING` (backend present, every write rejected) or\n * `ERR_HOST_NO_SPILL_NOTICE` (backend present, notice module cannot render\n * the footer), `ERR_HOST_SPILL_UNUSABLE` (backend present but exposes no\n * `saveText`), `ERR_HOST_WORKSPACE_REGISTRY_BROKEN` (registry present but\n * cannot list), and `ERR_HOST_SELECTOR_UNAVAILABLE` (the LLM seam is absent\n * or failing, so multi-candidate plans abstain); and a degraded scope read\n * passes its `ERR_SCOPE_*` code through. The two estimator absences are\n * separate codes:\n * `ERR_HOST_NO_TOKENMETER` is the host service probe (`apply` records whether\n * the synchronous token meter exists), while `ERR_HOST_NO_ESTIMATOR` is the\n * pure fixed-cost package being unreachable. One can exist without the other,\n * and merging them sent the operator to the wrong host.\n * `ERR_HOST_PLATFORM_UNSUPPORTED` is `isPosixOnly()` being false.\n * `ERR_BOOST_PARTIAL_MOUNT` is an `apply` wiring failure: at least one of the\n * four host mounts (prompt section, post-execute, llm/stream, execute) is\n * missing, so the plugin is loaded but not fully wired.\n * - The fixed overhead is measured **once at startup**\n * (`measureBoostFixedOverhead`: protocol section + tool schema) and awaited\n * by `status`; it is never on a request path (design §6.1).\n * - `runBoost` is pure orchestration over the two stores plus the host facts\n * `apply` hands it: no `ctx`, no host calls beyond the one measurement. The\n * tool definition is therefore testable without a host, and the host probe\n * lives in `src/index.ts`.\n *\n * The command table is deliberately a plain record, one handler per\n * subcommand, so an unknown `cmd` is a lookup miss rather than a fallthrough.\n *\n * @module dsh-boost/tools/boost\n */\nimport type { JsonSchemaNode } from '@deepseek-ai/dsh-tools'\nimport { measureFixedOverhead } from '../admission/fixed-cost.js'\nimport type { FixedOverheadMeasurement } from '../admission/fixed-cost.js'\nimport { DEFAULT_CONFIG } from '../config.js'\nimport { isPosixOnly } from '../host/platform.js'\nimport type { ProjectionMode } from '../projection/apply.js'\nimport {\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_WRITE_FAILED,\n ERR_SCOPE_REVISION_CONFLICT,\n ERR_SCOPE_UNKNOWN_VERSION,\n} from '../scope/doc.js'\nimport type { ScopeCode, ScopeDoc } from '../scope/doc.js'\nimport type { ScopeStore } from '../scope/store.js'\nimport type { Receipt, ReceiptStore } from '../receipts/store.js'\n\n/** Stable failure code: `cmd` names no subcommand this tool implements. */\nconst ERR_BOOST_UNKNOWN_CMD = 'ERR_BOOST_UNKNOWN_CMD'\n\n/** Stable failure code: a required argument (`baseRevision`) is missing or malformed. */\nexport const ERR_BOOST_INVALID_ARGS = 'ERR_BOOST_INVALID_ARGS'\n\n/** Stable failure code: `body` is not a valid, writable scope patch. */\nexport const ERR_BOOST_INVALID_BODY = 'ERR_BOOST_INVALID_BODY'\n\n/** Stable failure code: an unexpected internal failure, so the tool still answers. */\nexport const ERR_BOOST_INTERNAL = 'ERR_BOOST_INTERNAL'\n\n/**\n * Load-time log code: the settings page's data route could not be mounted.\n *\n * Log-only, like `ERR_BOOST_PARTIAL_MOUNT`: the plugin keeps working, the page\n * just has no data source. Emitted from the mount path itself, so it appears in\n * the host log rather than in `boost status`.\n */\nexport const ERR_BOOST_HTTP_MOUNT_FAILED = 'ERR_BOOST_HTTP_MOUNT_FAILED'\n\n/** Every scope failure code, for passing the store's codes through unchanged. */\nconst SCOPE_CODES: ReadonlySet<string> = new Set([\n ERR_SCOPE_UNKNOWN_VERSION,\n ERR_SCOPE_FUTURE_VERSION,\n ERR_SCOPE_PARSE_FAILED,\n ERR_SCOPE_READ_FAILED,\n ERR_SCOPE_WRITE_FAILED,\n ERR_SCOPE_REVISION_CONFLICT,\n ERR_SCOPE_LOCKED,\n ERR_SCOPE_ABORTED,\n])\n\n/** Stable host degradation codes (design §9; the frozen set `status` reports). */\nconst ERR_HOST_NO_SPILL = 'ERR_HOST_NO_SPILL'\n/**\n * Stable degradation code: at least one of the four host mounts is missing.\n *\n * `apply` mounts the prompt section, the projection hook, the synthesizer and\n * the dispatch hook. A failure in any of them used to be logged as a section\n * failure (or swallowed) while `status` reported `degraded: []`; a plugin\n * missing its projection or flush hook looks healthy in every ledger but never\n * acts. The code names that state; `partialMounts()` lists which mounts are\n * absent (review row 2).\n */\nconst ERR_BOOST_PARTIAL_MOUNT = 'ERR_BOOST_PARTIAL_MOUNT'\n/**\n * Stable degradation code: the host spill-notice module has no footer renderer.\n *\n * Apply-mode projection cannot compose its footer without `formatSpillNotice`,\n * so every receipt is left intact and recorded as\n * `projection-skipped:no-footer`. That is a host-level absence, not an ordinary\n * \"not worth it\" skip: without this code `status` reported a healthy spill path\n * while projection silently never ran. Its producer is the receipt stream\n * (there is no service probe — the module is reached by `import()` only).\n */\nconst ERR_HOST_NO_SPILL_NOTICE = 'ERR_HOST_NO_SPILL_NOTICE'\nconst ERR_HOST_SPILL_FAILING = 'ERR_HOST_SPILL_FAILING'\nconst ERR_HOST_NO_TOKENMETER = 'ERR_HOST_NO_TOKENMETER'\nconst ERR_HOST_NO_ESTIMATOR = 'ERR_HOST_NO_ESTIMATOR'\nconst ERR_HOST_PLATFORM_UNSUPPORTED = 'ERR_HOST_PLATFORM_UNSUPPORTED'\nconst ERR_HOST_NO_WORKSPACE_REGISTRY = 'ERR_HOST_NO_WORKSPACE_REGISTRY'\n/**\n * Stable degradation code: a workspace registry is present but cannot list.\n *\n * Presence alone made a throwing `list()` look healthy: the resolver swallowed\n * the throw per call (the intentional fail-closed path for one invisible\n * session), every session was judged invisible, and `status` reported a healthy\n * plugin doing nothing (review row 6). The probe calls `list()` at status time,\n * exactly as the token meter is probed, so a broken registry is named instead\n * of being indistinguishable from an absent one.\n */\nconst ERR_HOST_WORKSPACE_REGISTRY_BROKEN = 'ERR_HOST_WORKSPACE_REGISTRY_BROKEN'\n/**\n * Stable degradation code: `spillStore` is present but exposes no `saveText`.\n *\n * `hasSpill` was presence-only, so a `{}` service reported a healthy spill path\n * until the first projection failed (review row 50). The store is probed at\n * status time for the one method the projection path calls; the notice module\n * stays covered by `ERR_HOST_NO_SPILL_NOTICE` / `projection-skipped:no-footer`,\n * because it is reached by `import()` and has no service to probe.\n */\nconst ERR_HOST_SPILL_UNUSABLE = 'ERR_HOST_SPILL_UNUSABLE'\n/**\n * Stable degradation code: multi-candidate plans will abstain.\n *\n * The selector is the only consumer of the host LLM. Its absence or a failing\n * call is written as `selector-unavailable` / `selector-error`, but those are\n * receipt counts: an operator reading `degraded` saw a healthy plugin while\n * every multi-candidate plan abstained (review row 49). Single-candidate\n * substitution still works, so this is a warning, not a failure. A\n * `selector-abstain` is deliberately not mapped: the model declined an\n * ambiguous plan, which is not a host capability absence.\n */\nconst ERR_HOST_SELECTOR_UNAVAILABLE = 'ERR_HOST_SELECTOR_UNAVAILABLE'\n\n/**\n * Stable degradation code: at least one receipt shard could not be read.\n *\n * `status` scans every shard; a single unreadable file (EACCES, or a directory\n * named `x.jsonl`) must leave the healthy shards readable and the tool\n * answering. `ReceiptStore.readErrors()` is the one live source: the store\n * contains the failure per shard and the count describes its last whole-store\n * scan, so repairing the shard and re-running `status` drops the code.\n */\nconst ERR_RECEIPTS_UNREADABLE = 'ERR_RECEIPTS_UNREADABLE'\n\n/**\n * Stable degradation code: the whole-store scan hit the 256-shard cap.\n *\n * The totals then cover only the first 256 sorted shards: under-counting is\n * the safe direction, but presenting that as a total is not. The code marks\n * the figures as a lower bound; `ReceiptStore.scanTruncated()` is its source.\n */\nconst ERR_RECEIPTS_TRUNCATED = 'ERR_RECEIPTS_TRUNCATED'\n\n/**\n * Stable degradation code: the final system prompt did not carry the protocol\n * section because a `complete: true` section replaced the assembly.\n *\n * Detected on the outgoing request (`llm/stream`), not at assembly time: the\n * host restores the complete section after the waterfall, so only the request\n * shows the loss. Substitution is refused for the affected request because the\n * model was never taught the plan grammar (review row 12).\n */\nconst ERR_HOST_COMPLETE_SECTION = 'ERR_HOST_COMPLETE_SECTION'\n\n/**\n * Receipt codes that mean the host is degraded, mapped to the stable code\n * `status` reports.\n *\n * `projection-skipped:no-spill` is the code the projection path records when\n * the spill backend is absent (design §5.4), so it is the real producer behind\n * `ERR_HOST_NO_SPILL`. The same code is also derived from the host probe when\n * `projection: 'on'`; the two channels are deduplicated, not mutually exclusive.\n *\n * `projection-skipped:no-footer` is a different absence with a different fix:\n * the spill backend exists but the host spill-notice module does not render a\n * footer, so `projectApply` refuses to replace anything. Mapping it to\n * `ERR_HOST_NO_SPILL_NOTICE` is what keeps the plugin's headline feature from\n * being silently off while `status` calls the spill path healthy.\n *\n * `projection-skipped:spill-failed` and `projection-skipped:footer-failed` are\n * the same two degradations at the point of use: the backend exists but\n * `saveText` rejected, or the renderer exists but threw. Without these rows a\n * present-but-broken store skipped 100% of projections while `degraded` stayed\n * empty (review row 31).\n *\n * `spill-failed` gets its **own** code rather than reusing `ERR_HOST_NO_SPILL`:\n * a backend that rejects every write is not an absent backend, and telling an\n * operator to \"restore the spill package\" when the package is installed and\n * failing sends them to the wrong place. `footer-failed` stays with\n * `ERR_HOST_NO_SPILL_NOTICE` because both mean the same thing at the point of\n * use — the footer cannot be produced.\n *\n * `selector-unavailable` and `selector-error` are the selector's only two host\n * failures: no LLM/route, or a call that threw. Both mean \"multi-candidate\n * plans will abstain\" while single-candidate substitution keeps working, so\n * they share one warning code. `selector-abstain` is not a host fact and is not\n * mapped (review row 49).\n */\nconst RECEIPT_DEGRADATION: ReadonlyArray<{ readonly code: string; readonly degraded: string }> = [\n { code: 'projection-skipped:no-spill', degraded: ERR_HOST_NO_SPILL },\n { code: 'projection-skipped:spill-failed', degraded: ERR_HOST_SPILL_FAILING },\n { code: 'projection-skipped:no-footer', degraded: ERR_HOST_NO_SPILL_NOTICE },\n { code: 'projection-skipped:footer-failed', degraded: ERR_HOST_NO_SPILL_NOTICE },\n // The substitution refusal writes the stable code itself, so a status built\n // without host facts still reports the reason the decision path recorded.\n { code: ERR_HOST_NO_TOKENMETER, degraded: ERR_HOST_NO_TOKENMETER },\n // Only absence is a capability fact. `selector-error` is a call failure that\n // may be transient and is summed over all history, so mapping it here would\n // mark a healthy host degraded forever (review qr5#4).\n { code: 'selector-unavailable', degraded: ERR_HOST_SELECTOR_UNAVAILABLE },\n]\n\n/**\n * Host capabilities `apply` probes once and hands `status`.\n *\n * Every field is optional because `runBoost` is also usable without a host\n * (unit tests, and the control tool built before `apply` wires the probe). An\n * absent fact means \"not probed\", never \"supported\": the status code list then\n * simply omits the corresponding code rather than guessing.\n */\nexport interface BoostHostFacts {\n /** Whether `ctx.get('tokenMeter')` exposed the synchronous message estimator. */\n hasTokenMeter?: boolean\n /** Whether `ctx.get('spillStore')` exposed the projection backend. */\n hasSpill?: boolean\n /**\n * Whether the present spill store exposes the one method projection calls.\n *\n * Presence is not capability: a `{}` service resolves, so `hasSpill` is true\n * while every projection fails at the first `saveText`. The probe is a shape\n * check only — calling `saveText` would write a spill artifact — and an\n * absent store leaves this `false` (the absence itself is `hasSpill: false`).\n */\n spillUsable?: boolean\n /**\n * Whether `ctx.get('workspaceRegistry')` ever became available.\n *\n * A missing registry makes every session invisible, which presents to the\n * operator as \"nothing ever happens\" with no error anywhere. It is a host\n * fact rather than an assembly detail because that failure mode has to be\n * diagnosable from inside the product.\n */\n hasWorkspaceRegistry?: boolean\n /**\n * Whether the present registry's `list()` threw or returned a non-array.\n *\n * `hasWorkspaceRegistry` only says the service exists. A registry that\n * cannot list makes every session invisible too, and the per-call resolver\n * swallows that throw by design, so this fact is the only way the failure\n * reaches `status` (review row 6).\n */\n workspaceRegistryBroken?: boolean\n}\n\n/** The two stores `runBoost` orchestrates, plus the host facts it reports. */\nexport interface BoostDeps {\n scope: ScopeStore\n receipts: ReceiptStore\n /** Host capabilities measured by `apply`; absent when no host was probed. */\n host?: BoostHostFacts\n /**\n * The one fixed-overhead measurement, started at plugin load.\n *\n * A function rather than a promise so `status` can await it lazily; the\n * default reuses the module-level memoised measurement.\n */\n fixedOverhead?: () => Promise<FixedOverheadMeasurement | 'unknown'>\n /**\n * Which estimator priced this assembly's figures.\n *\n * `host` means the synchronous host meter; `unknown` means no token meter,\n * so no number is fabricated (design §9). There is deliberately no\n * `chars/4` arm: a characters-over-four guess is not a measurement, and a\n * receipt that says `unknown` is more useful than one that is wrong.\n */\n estimateKind?: 'host' | 'unknown'\n /**\n * The current replay horizon; defaults to the design's 20.\n *\n * Receipts carry their own `horizon_steps`, so this is only the fallback for\n * receipts written before that field existed (counted in\n * `projection_horizon_reestimated`) — not a factor applied to the whole\n * ledger.\n */\n horizonSteps?: number\n /** Locators evicted by the per-session cap; status-time read. */\n locatorEvictions?: () => number\n /**\n * Receipt shards whole-store scans had to skip since the last scan that read\n * every shard; status-time read.\n *\n * This is the **only** source of `ERR_RECEIPTS_UNREADABLE`: the store skips\n * an unreadable shard per shard and reports the count, so `status` has one\n * mechanism rather than a status-side scan flag that no production store can\n * raise. Absent means the store has no such counter (or none was skipped);\n * the count clears when a scan reads every shard.\n */\n receiptReadErrors?: () => number\n /**\n * Whether the status scan stopped at the store's 256-shard cap; status-time\n * read.\n *\n * True means every total in the answer covers only the first 256 sorted\n * shards: the figures are a lower bound, not the whole ledger. Absent means\n * the store has no such flag (or the last scan fitted), which is the\n * pre-existing \"totals are complete\" reading.\n */\n receiptsTruncated?: () => boolean\n /** Calls skipped because no family matched; status-time read. */\n unknownFamilies?: () => number\n /** Retained unmapped tool names; status-time read. */\n unknownTools?: () => Record<string, number>\n /**\n * Prompt assemblies whose protocol section was suppressed; status-time read.\n *\n * The prompt path is the one mount that acts on every request, so design\n * §5.5:378 makes it a count rather than a receipt. It is exposed because the\n * shipped default scope is *correctly* inert: with no counter, \"nothing\n * configured\" and \"assembly failed\" look identical from `status`.\n */\n protocolSuppressed?: () => number\n /** Requests whose final prompt lost the protocol to a complete section; status-time read. */\n completeSectionSuppressions?: () => number\n /**\n * Integration points `apply` could not mount; status-time read.\n *\n * A missing projection or flush hook leaves every ledger healthy-looking\n * while the plugin never acts, so the mounts are a fact `status` must\n * report. Absent means no mount failed (or the caller does not track them).\n */\n partialMounts?: () => readonly string[]\n /**\n * Cancellation for this invocation only.\n *\n * `runBoost` is also callable directly (tests, future hosts), so this is\n * optional; `boostTool.execute` fills it from the host's `exec.signal` and a\n * cancelled call leaves `scope.json` untouched.\n */\n signal?: AbortSignal\n}\n\n/** The scope document's caller-writable fields. Everything else is store-owned. */\nconst PATCH_FIELDS = ['mode', 'workspaceIds', 'shadow', 'projection'] as const\n\n/** Fields a caller must never set: the store owns one, the format fixes the other. */\nconst RESERVED_FIELDS = ['version', 'revision'] as const\n\n/** The four subcommands. */\ntype BoostCmd = 'status' | 'scope-get' | 'scope-set' | 'shadow'\n\n/** Raw tool arguments, after the model (or a test) produced them. */\ntype BoostArgs = { cmd: BoostCmd; body?: unknown; baseRevision?: number }\n\n/** Successful report or a stable failure code — never a thrown error. */\ntype BoostResult = { ok: true; data: unknown } | { ok: false; code: string }\n\n/** What `status` reports. Both switches are top-level on purpose: they differ. */\nexport interface BoostStatus {\n scope: { mode: ScopeDoc['mode']; workspaceIds: string[]; revision: number }\n shadow: boolean\n projection: ProjectionMode\n saved: {\n /**\n * **Upper** estimate: Σ numeric `saved_input_tokens` over settled\n * substitutions only.\n *\n * This is the next request's input, which overstates the avoided cost by\n * the substituted call's own result. The synth-time `substitute` line\n * predates any measurement (design §5.3 says the field is measured), so its\n * value is `'unknown'` or absent and never contributes; `counts` keeps the\n * event count.\n */\n substitution: number\n /**\n * **Lower** estimate: Σ numeric `avoided_total_tokens` over receipts that\n * carry the field.\n *\n * The producer writes the skipped request's own total (`before.input +\n * before.cacheRead + before.output`), so this is the avoided cost itself\n * rather than the next request's input. Omitted — never `0` — when no\n * receipt carries the field: a missing measurement must not read as\n * \"avoided nothing\" (review row 7).\n */\n substitution_avoided?: number\n /**\n * Σ `saved_projection_tokens` over non-retrieval projections, **replayed**\n * by each receipt's own `horizon_steps`.\n *\n * Replay-aware so this legacy object no longer mixes a one-time gross with\n * a replay net (review R2). The one-time figure is the top-level\n * `projection_gross_tokens`. A receipt that predates `horizon_steps` is\n * replayed at the current horizon; `projection_horizon_reestimated` counts\n * those, so a re-estimated figure is never mistaken for a measured one.\n */\n projectionGross: number | 'unknown'\n /**\n * Σ saved × (1 + that receipt's horizon) − Σ content × (1 + its horizon)\n * − Σ call blocks − legacy replay-aware costs.\n *\n * `'unknown'` when any retrieval in the ledger is unpriced: an unmeasured\n * cost must never silently become zero (review R3).\n */\n projectionNet: number | 'unknown'\n /** Number of `kind:'projection'` receipts marked `retrieved: true`. */\n retrievals: number\n }\n /** Receipt count per `code`, over every shard (including the empty session id). */\n counts: Record<string, number>\n /** Stable degradation codes actually observed. */\n degraded: string[]\n /**\n * Whether the host ever exposed a workspace registry.\n *\n * Reported separately from {@link degraded} because it is the single fact\n * that explains \"the plugin is installed and nothing ever happens\": with no\n * registry, no session resolves to a workspace and every path is inert.\n * Absent when no host was probed.\n */\n hasWorkspaceRegistry?: boolean\n /**\n * Whether the host exposed a spill store.\n *\n * Presence only: {@link degraded} carries `ERR_HOST_SPILL_UNUSABLE` when the\n * store exists but cannot save, and `ERR_HOST_NO_SPILL` when it is absent.\n * Absent when no host was probed.\n */\n hasSpill?: boolean\n /**\n * The measured per-request fixed cost: protocol section + tool schema.\n *\n * `'unknown'` when the host estimator is unreachable: the measurement is\n * never fabricated (design §9). Status-time only; see\n * `src/admission/fixed-cost.ts`.\n */\n fixedOverheadTokens: number | 'unknown'\n /** The two components behind {@link fixedOverheadTokens}. */\n fixedOverhead: FixedOverheadMeasurement | 'unknown'\n /**\n * Whether the ledger figures are provider-metered or estimates.\n *\n * `unknown` means no token meter: projection still clips, but its receipts\n * carry `'unknown'` rather than invented numbers, and substitution is\n * refused (design §9).\n */\n estimate_kind: 'host' | 'unknown'\n /** The current `(1 + horizon)` replay factor; the fallback for old receipts. */\n projection_horizon_steps: number\n /**\n * Projection receipts replayed at {@link projection_horizon_steps} because\n * they predate the per-receipt `horizon_steps` field.\n *\n * `0` means every replay figure in this report is the horizon its own\n * decision was made under. A non-zero value marks that part of the net is\n * re-estimated, not measured: an operator reading the shadow-week go/no-go\n * must be able to tell the two apart.\n */\n projection_horizon_reestimated: number\n /**\n * Σ one-time `saved_projection_tokens` over applied projections whose call\n * was **not** itself a retrieval.\n *\n * A retrieval's own projection is excluded: crediting it here while also\n * charging its visible window as retrieval cost would count the same tokens\n * from both sides (review I3).\n */\n projection_gross_tokens: number | 'unknown'\n /** {@link projection_gross_tokens} replayed at each receipt's own horizon. */\n projection_gross_replay_tokens: number | 'unknown'\n /** Σ one-time retrieval totals (call + content); `0` for unpriced receipts. */\n projection_retrieval_tokens: number\n /** Σ one-time retrieval content, the side that replays with the gross. */\n projection_retrieval_content_tokens: number\n /** Σ one-time retrieval call blocks; replay does not apply to these. */\n projection_retrieval_call_tokens: number\n /** Projections with no measured saving; the gross/net become `'unknown'`. */\n projection_unpriced_projections: number\n /** Retrievals with no usable token fields; their cost makes the net unknown. */\n projection_unpriced_retrievals: number\n /** Pre-schema retrievals priced through the old `retrievalCost` field. */\n projection_legacy_retrievals: number\n /**\n * The design's receipt-field spelling of `saved.retrievals`.\n *\n * Kept at the top level because the shadow-week operator reads the two\n * ledgers by the names §5.3 gives them; `saved` keeps the original camelCase\n * shape so existing consumers keep working. Both are derived from one\n * aggregation, so they cannot drift.\n */\n projection_retrievals: number\n /**\n * Σ saved × (1 + receipt horizon) − Σ retrieval content × (1 + its horizon)\n * − Σ retrieval call blocks.\n *\n * The retrieval's own projection is not in the gross, the content it made\n * visible replays at the horizon in effect when the retrieval happened, and\n * its call block is charged once. `'unknown'` when a retrieval is unpriced or\n * a meterless projection was clipped: a lower bound cannot be computed from a\n * missing measurement.\n */\n projection_net_tokens: number | 'unknown'\n /** Locators dropped by the per-session cap; a lossy ledger is visible. */\n projection_locator_evictions: number\n /** Calls skipped because no projection family matched. */\n projection_unknown_families: number\n /** Retained unmapped tool names (at most 32), for mapper-gap diagnosis. */\n projection_unknown_tools: Record<string, number>\n /**\n * Prompt assemblies whose protocol section was suppressed.\n *\n * Counted, never receipted, because assembly runs on every request (design\n * §5.5:378). A live, monotonically increasing number is the only evidence\n * that the inert-looking default is \"no workspace configured\" rather than a\n * section that failed to inject.\n */\n protocol_suppressed: number\n /**\n * Whether the receipt store stopped accepting writes (fail-closed).\n *\n * Once true, substitution is refused outright (design §5.2-3) and every\n * figure above is a stale snapshot. Reported because the alternative is an\n * operator reading frozen numbers with no warning that they froze.\n */\n receipts_stopped: boolean\n}\n\n/** A validated scope patch: only the caller-writable fields survive. */\ntype ScopePatch = Partial<Pick<ScopeDoc, (typeof PATCH_FIELDS)[number]>>\n\n/**\n * The replay horizon one projection receipt was measured under.\n *\n * The decision path writes `horizon_steps` on every projection receipt it\n * produces. A receipt from before that field existed is replayed at the\n * current horizon and flagged as re-estimated, so `status` can tell the\n * operator how much of the net is measured rather than re-valued. A malformed\n * value is treated as absent, never trusted.\n */\nfunction replayOf(\n receipt: Receipt,\n fallback: number,\n): { horizon: number; reestimated: boolean } {\n const raw = receipt.horizon_steps\n if (typeof raw === 'number' && Number.isFinite(raw) && raw >= 0) {\n return { horizon: Math.floor(raw), reestimated: false }\n }\n return { horizon: fallback, reestimated: true }\n}\n\n/**\n * The receipt aggregation behind `status`, kept separate from the document\n * read so the accounting has one home and one test surface.\n *\n * `scan()` is called with no session id on purpose: `skip:no-scope` receipts\n * are not owned by one shard. The no-agent case writes the empty session id;\n * the cold-judgement path writes the real session id, once per tool call by\n * design (design §5.5:377), which is expected in unscoped workspaces and will\n * dominate their shards — not a leak. Only a whole-store scan sees both.\n *\n * Unreadable shards are the store's concern: `scan()` skips them and\n * `readErrors()` reports the count, so `status` has exactly one source for\n * `ERR_RECEIPTS_UNREADABLE` and a throwing store is an internal failure, not a\n * second degradation channel.\n *\n * The replay sums are computed here, per receipt, from each receipt's own\n * `horizon_steps`. A receipt written before that field existed is replayed at\n * `fallbackHorizon` (the current horizon) and counted in\n * `horizonReestimated`, so the report can say how much of the net is measured\n * rather than re-estimated.\n */\nasync function aggregate(\n receipts: ReceiptStore,\n fallbackHorizon: number,\n): Promise<{\n counts: Record<string, number>\n substitution: number\n substitutionAvoided?: number\n projectionGross: number\n projectionGrossReplay: number\n retrievalContentReplay: number\n horizonReestimated: number\n unpricedProjections: number\n retrievalTokens: number\n retrievalContentTokens: number\n retrievalCallTokens: number\n retrievals: number\n unpricedRetrievals: number\n legacyRetrievals: number\n legacyRetrievalCost: number\n degraded: string[]\n}> {\n const counts: Record<string, number> = Object.create(null)\n let substitution = 0\n let substitutionAvoided = 0\n let avoidedSeen = false\n let projectionGross = 0\n let projectionGrossReplay = 0\n let retrievalContentReplay = 0\n let horizonReestimated = 0\n let unpricedProjections = 0\n let retrievalTokens = 0\n let retrievalContentTokens = 0\n let retrievalCallTokens = 0\n let retrievals = 0\n let unpricedRetrievals = 0\n let legacyRetrievals = 0\n let legacyRetrievalCost = 0\n\n for await (const receipt of receipts.scan()) {\n // A receipt is untrusted text from a file: `counts` has no prototype so a\n // code of `toString` or `__proto__` is an ordinary numeric key, never a\n // string concatenation and never a dropped assignment.\n if (typeof receipt.code === 'string') {\n counts[receipt.code] = (counts[receipt.code] ?? 0) + 1\n }\n\n // Only the settled line carries a measured saving; the synth-time line is\n // an event and is already visible in `counts`.\n if (receipt.kind === 'substitute-settled') {\n const saved = receipt.saved_input_tokens\n if (typeof saved === 'number' && Number.isFinite(saved)) substitution += saved\n }\n\n // The lower estimate is the skipped request's own total, summed over every\n // receipt that carries it (the settled line is its producer). Presence is\n // tracked separately from the value: a receipt carrying `0` is a\n // measurement, while no receipt carrying the field means \"not measured\"\n // and the key is omitted from `status` rather than reported as zero\n // (review row 7).\n // Pair the two sums on the same receipt: a rollover settlement writes a\n // numeric lower bound with `saved_input_tokens: 'unknown'`, so summing the\n // lower over a superset could report a floor above the ceiling\n // (review qr5#2). A receipt that carries only one side contributes to\n // neither.\n const avoided = receipt.avoided_total_tokens\n const upper = receipt.saved_input_tokens\n if (\n typeof avoided === 'number' &&\n Number.isFinite(avoided) &&\n typeof upper === 'number' &&\n Number.isFinite(upper)\n ) {\n substitutionAvoided += avoided\n avoidedSeen = true\n }\n\n if (receipt.kind !== 'projection') continue\n\n const replay = replayOf(receipt, fallbackHorizon)\n\n if (receipt.unit === 'raw' && receipt.call_was_retrieval !== true && receipt.retrieved !== true) {\n // T23b/T26 write `saved_projection_tokens`; `saved` is the pre-T23b\n // spelling this consumer accepted first. Never estimate a value here.\n // A retrieval's own projection is excluded from gross: its visible\n // window is charged as retrieval content instead (review I3).\n const saved = receipt.saved_projection_tokens ?? receipt.saved\n if (typeof saved === 'number' && Number.isFinite(saved)) {\n projectionGross += saved\n projectionGrossReplay += saved * (1 + replay.horizon)\n if (replay.reestimated) horizonReestimated += 1\n }\n // A meterless projection carries `estimate:'unknown'` and no saved\n // figure. Reporting the remaining numeric sum as the gross would present\n // an unmeasured effect as zero (review R4).\n else unpricedProjections += 1\n }\n\n if (receipt.retrieved !== true) continue\n retrievals += 1\n\n const total = receipt.retrieval_tokens\n const call = receipt.retrieval_call_tokens\n const content = receipt.retrieval_content_tokens\n if (\n typeof total === 'number' &&\n Number.isFinite(total) &&\n total >= 0 &&\n typeof call === 'number' &&\n Number.isFinite(call) &&\n call >= 0 &&\n typeof content === 'number' &&\n Number.isFinite(content) &&\n content >= 0 &&\n total === call + content\n ) {\n retrievalTokens += total\n retrievalCallTokens += call\n retrievalContentTokens += content\n retrievalContentReplay += content * (1 + replay.horizon)\n if (replay.reestimated) horizonReestimated += 1\n continue\n }\n\n // Pre-schema receipts (written before the split) carry only the old\n // already-replayed `retrievalCost` total. Subtracting it directly from the\n // replayed net avoids counting it as free (review R6). Its own projection,\n // if any, predates the `call_was_retrieval` marker and cannot be identified\n // from the file; that is documented in the report.\n const legacy = receipt.retrievalCost\n if (typeof legacy === 'number' && Number.isFinite(legacy) && legacy >= 0) {\n legacyRetrievals += 1\n legacyRetrievalCost += legacy\n retrievalTokens += legacy\n continue\n }\n\n // Neither schema: the cost is unknown, not zero. The net is reported as\n // `'unknown'` rather than silently treating the retrieval as free.\n unpricedRetrievals += 1\n }\n\n const degraded = RECEIPT_DEGRADATION.filter(entry => counts[entry.code] !== undefined).map(\n entry => entry.degraded,\n )\n return {\n counts,\n substitution,\n ...(avoidedSeen ? { substitutionAvoided } : {}),\n projectionGross,\n projectionGrossReplay,\n retrievalContentReplay,\n horizonReestimated,\n unpricedProjections,\n retrievalTokens,\n retrievalContentTokens,\n retrievalCallTokens,\n retrievals,\n unpricedRetrievals,\n legacyRetrievals,\n legacyRetrievalCost,\n degraded,\n }\n}\n\n/**\n * The fixed overhead measurement, never a thrown status.\n *\n * The production deps carry the promise `apply` started at load; the default\n * is the same memoised measurement, so a direct `runBoost` (a unit test or a\n * host that built the tool itself) still reports a real number. A rejection or\n * an invalid breakdown is `'unknown'`, for the same reason the estimator's own\n * failure is.\n */\nasync function fixedOverheadOf(deps: BoostDeps): Promise<FixedOverheadMeasurement | 'unknown'> {\n try {\n const value = await (deps.fixedOverhead ?? measureBoostFixedOverhead)()\n if (value === 'unknown') return 'unknown'\n const { protocolTokens, toolSchemaTokens, totalTokens } = value\n if (\n !Number.isFinite(protocolTokens) ||\n !Number.isFinite(toolSchemaTokens) ||\n !Number.isFinite(totalTokens) ||\n protocolTokens < 0 ||\n toolSchemaTokens < 0 ||\n totalTokens !== protocolTokens + toolSchemaTokens\n ) {\n return 'unknown'\n }\n return value\n } catch {\n return 'unknown'\n }\n}\n\n/** The configured replay horizon, or the design default when absent/malformed. */\nfunction horizonOf(deps: BoostDeps): number {\n const raw = deps.horizonSteps\n return typeof raw === 'number' && Number.isFinite(raw) && raw >= 0\n ? Math.floor(raw)\n : DEFAULT_CONFIG.horizonSteps\n}\n\n/** The label for the assembly's estimator; unprobed is honestly `unknown`. */\nfunction estimateKindOf(deps: BoostDeps): BoostStatus['estimate_kind'] {\n const kind = deps.estimateKind\n return kind === 'host' || kind === 'unknown' ? kind : 'unknown'\n}\n\n/**\n * Whether the receipt store has stopped writing, fail-closed.\n *\n * Mirrors `receiptsStopped` in `src/hooks/llm-stream.ts` for the control tool's\n * own store reference: a partial store is \"not stopped\", and a store that\n * throws cannot record evidence, which is what stopped means.\n */\nfunction receiptsStopped(store: BoostDeps['receipts']): boolean {\n try {\n if (store == null || typeof store.stopped !== 'function') return false\n return store.stopped() === true\n } catch {\n return true\n }\n}\n\n/** Whether the last whole-store scan stopped at the shard cap, never thrown. */\nfunction receiptsTruncatedOf(deps: BoostDeps): boolean {\n try {\n if (deps.receiptsTruncated !== undefined) return deps.receiptsTruncated() === true\n // The store owns the fact; the override exists for a fake counter. Reading\n // the store directly keeps a hand-built `runBoost` (no measured deps) from\n // silently losing the code.\n return deps.receipts.scanTruncated() === true\n } catch {\n return false\n }\n}\n\n/** Skipped shard reads, from the override or the store's own reading. */\nfunction receiptReadErrorsOf(deps: BoostDeps): number {\n if (deps.receiptReadErrors !== undefined) return counterOf(deps.receiptReadErrors)\n try {\n return counterOf(() => deps.receipts.readErrors())\n } catch {\n return 0\n }\n}\n\n/** A monotonic status counter, never a thrown status. */\nfunction counterOf(read: (() => number) | undefined): number {\n try {\n const value = read?.()\n return typeof value === 'number' && Number.isFinite(value) && value >= 0\n ? Math.floor(value)\n : 0\n } catch {\n return 0\n }\n}\n\n/** A bounded unmapped-tool map, never a thrown status. */\nfunction toolCountsOf(read: (() => Record<string, number>) | undefined): Record<string, number> {\n // Build through a Map: `counts['__proto__'] = n` on a plain object would\n // mutate its prototype, and tool names come from the host. `fromEntries` is\n // an own-property copy, so the returned object has the normal prototype and\n // deep-equality consumers see a plain record.\n const counts = new Map<string, number>()\n try {\n const value = read?.()\n if (value === null || typeof value !== 'object') return {}\n for (const [name, count] of Object.entries(value)) {\n if (typeof count === 'number' && Number.isFinite(count) && count >= 0) counts.set(name, count)\n }\n } catch {\n // A foreign counter is evidence, not a failure.\n }\n return Object.fromEntries(counts)\n}\n\n/**\n * The stable degradation codes for one status call.\n *\n * Inputs are the receipt-observed codes, the scope read's stable code, the host\n * facts, and the mount points `apply` could not wire. Receipt codes are already\n * mapped; the scope store's internal\n * `scope-degraded` label is deliberately **not** copied — the report's contract\n * is stable codes only. Order is deterministic (receipts, scope, host) and the\n * result is deduplicated, so one condition observed through two channels\n * appears once.\n *\n * Two different absences stay distinct: `ERR_HOST_NO_TOKENMETER` is the\n * **service** (`ctx.get('tokenMeter')`) being absent, which refuses\n * substitution; `ERR_HOST_NO_ESTIMATOR` is the pure estimate package being\n * unreachable, which makes the fixed-overhead figure `'unknown'`. A host with\n * the package but no service reports the latter only.\n *\n * `when` on `tools.register` has been part of `ToolRegistrationOptions` since\n * the oldest host line this plugin declares, so there is no \"host without\n * step-level `when`\" to report: probing it would evaluate every other plugin's\n * predicate against a fabricated `Agent`, and a fact that can never be true is\n * a claim, not a measurement. `apply` registers unconditionally instead.\n */\nfunction degradationCodes(\n observed: readonly string[],\n read: Awaited<ReturnType<ScopeStore['read']>>,\n host: BoostHostFacts | undefined,\n fixedOverhead: FixedOverheadMeasurement | 'unknown',\n missingMounts: readonly string[] = [],\n): string[] {\n const codes: string[] = [...observed]\n if (read.degraded !== undefined) codes.push(read.code ?? ERR_SCOPE_READ_FAILED)\n\n if (!isPosixOnly()) codes.push(ERR_HOST_PLATFORM_UNSUPPORTED)\n if (host?.hasTokenMeter === false) codes.push(ERR_HOST_NO_TOKENMETER)\n if (fixedOverhead === 'unknown') codes.push(ERR_HOST_NO_ESTIMATOR)\n // `spillStore` matters only in apply mode; shadow mode never touches it\n // (design §5.4), so reporting it while projection is `shadow` would be noise.\n // Presence and capability are separate: an absent store and a present store\n // without `saveText` need different repairs, so they get different codes.\n if (read.doc.projection === 'on') {\n if (host?.hasSpill === false) codes.push(ERR_HOST_NO_SPILL)\n else if (host?.spillUsable === false) codes.push(ERR_HOST_SPILL_UNUSABLE)\n }\n // A present registry that cannot list is not an absent one: the operator is\n // told which of the two host states to repair (review row 6).\n if (host?.hasWorkspaceRegistry === false) codes.push(ERR_HOST_NO_WORKSPACE_REGISTRY)\n else if (host?.workspaceRegistryBroken === true) codes.push(ERR_HOST_WORKSPACE_REGISTRY_BROKEN)\n // A missing mount is a wiring failure, not a capability absence: the plugin\n // is loaded but at least one of its four integration points is not, so the\n // ledgers cannot be trusted to describe what it is doing.\n if (missingMounts.length > 0) codes.push(ERR_BOOST_PARTIAL_MOUNT)\n\n return [...new Set(codes)]\n}\n\n/** `status`: the scope document plus the receipt ledgers, never a failure. */\nasync function statusCommand(deps: BoostDeps): Promise<BoostResult> {\n const read = await deps.scope.read()\n const horizon = horizonOf(deps)\n // Each receipt replays at its own horizon; `horizon` is only the fallback for\n // receipts that predate the field, and `horizonReestimated` counts them.\n const totals = await aggregate(deps.receipts, horizon)\n const fixedOverhead = await fixedOverheadOf(deps)\n const degraded = degradationCodes(\n totals.degraded,\n read,\n deps.host,\n fixedOverhead,\n deps.partialMounts?.() ?? [],\n )\n // A shard the scan could not read is evidence, not a status failure: the\n // healthy shards were counted and the operator gets a stable code saying the\n // ledger is incomplete. `readErrors()` is the only producer; it counts skips\n // since the last fully readable whole-store scan, so a repaired shard clears\n // the code.\n if (receiptReadErrorsOf(deps) > 0 && !degraded.includes(ERR_RECEIPTS_UNREADABLE)) {\n degraded.push(ERR_RECEIPTS_UNREADABLE)\n }\n // The scan cap makes every figure a lower bound over the first 256 sorted\n // shards. Under-counting is safe, but it must not be presented as a total.\n if (receiptsTruncatedOf(deps) && !degraded.includes(ERR_RECEIPTS_TRUNCATED)) {\n degraded.push(ERR_RECEIPTS_TRUNCATED)\n }\n // A complete prompt section silently removed the protocol from the request:\n // the workspace is visible but substitution cannot be taught, so the operator\n // must see why the plugin is inert.\n if (counterOf(deps.completeSectionSuppressions) > 0) degraded.push(ERR_HOST_COMPLETE_SECTION)\n const estimateKind = estimateKindOf(deps)\n\n // Meterless projections have `estimate:'unknown'` receipts with no saved\n // figure. Reporting the numeric sum of the rest as 0/0 would be\n // indistinguishable from \"projection had no effect\" (review R4).\n const meterlessEvidence = totals.unpricedProjections > 0\n const grossOneTime = meterlessEvidence ? 'unknown' : totals.projectionGross\n const grossReplay = grossOneTime === 'unknown' ? 'unknown' : totals.projectionGrossReplay\n\n // A retrieval's own projection is excluded from gross; its content replays\n // with the gross, its call block is charged once, and a legacy cost was\n // already replay-aware (review I3/R6). An unpriced retrieval makes the whole\n // net unknown rather than free (review R3).\n const netUnknown = meterlessEvidence || totals.unpricedRetrievals > 0\n const projectionNet =\n netUnknown\n ? 'unknown'\n : totals.projectionGrossReplay -\n totals.retrievalContentReplay -\n totals.retrievalCallTokens -\n totals.legacyRetrievalCost\n\n const saved: BoostStatus['saved'] = {\n substitution: totals.substitution,\n ...(totals.substitutionAvoided === undefined\n ? {}\n : { substitution_avoided: totals.substitutionAvoided }),\n projectionGross: grossReplay,\n projectionNet,\n retrievals: totals.retrievals,\n }\n const data: BoostStatus = {\n scope: {\n mode: read.doc.mode,\n workspaceIds: read.doc.workspaceIds,\n revision: read.doc.revision,\n },\n shadow: read.doc.shadow,\n projection: read.doc.projection,\n saved,\n counts: totals.counts,\n degraded,\n fixedOverheadTokens: fixedOverhead === 'unknown' ? 'unknown' : fixedOverhead.totalTokens,\n fixedOverhead,\n estimate_kind: estimateKind,\n projection_horizon_steps: horizon,\n projection_horizon_reestimated: totals.horizonReestimated,\n projection_gross_tokens: grossOneTime,\n projection_gross_replay_tokens: grossReplay,\n projection_retrieval_tokens: totals.retrievalTokens,\n projection_retrieval_content_tokens: totals.retrievalContentTokens,\n projection_retrieval_call_tokens: totals.retrievalCallTokens,\n projection_unpriced_projections: totals.unpricedProjections,\n projection_unpriced_retrievals: totals.unpricedRetrievals,\n projection_legacy_retrievals: totals.legacyRetrievals,\n projection_retrievals: totals.retrievals,\n projection_net_tokens: projectionNet,\n projection_locator_evictions: counterOf(deps.locatorEvictions),\n projection_unknown_families: counterOf(deps.unknownFamilies),\n projection_unknown_tools: toolCountsOf(deps.unknownTools),\n protocol_suppressed: counterOf(deps.protocolSuppressed),\n receipts_stopped: receiptsStopped(deps.receipts),\n // An absent host fact is \"not probed\", not `false`: `undefined` is not a\n // legal JSON value, so the key is omitted rather than handed to the host\n // boundary (review row 35).\n ...(deps.host?.hasWorkspaceRegistry === undefined\n ? {}\n : { hasWorkspaceRegistry: deps.host.hasWorkspaceRegistry }),\n ...(deps.host?.hasSpill === undefined ? {} : { hasSpill: deps.host.hasSpill }),\n }\n return { ok: true, data }\n}\n\n/** `scope-get`: a faithful read; a degraded read is a stable tool failure. */\nasync function scopeGetCommand(deps: BoostDeps): Promise<BoostResult> {\n const read = await deps.scope.read()\n if (read.degraded !== undefined) return { ok: false, code: read.code ?? ERR_SCOPE_READ_FAILED }\n return { ok: true, data: read.doc }\n}\n\n/** Whether a value can be a caller-supplied base revision. */\nfunction isRevision(value: unknown): value is number {\n return typeof value === 'number' && Number.isInteger(value) && value >= 0\n}\n\n/** Whether `value` is one of the three projection modes. */\nfunction isProjectionMode(value: unknown): value is ProjectionMode {\n return value === 'off' || value === 'shadow' || value === 'on'\n}\n\n/**\n * Validate a `scope-set` body and prune it to the writable fields.\n *\n * Reserved fields are checked **first**: the store persists whatever `mutate`\n * returns, so a body carrying `version` or `revision` must be refused before a\n * patch is built, not stripped and written as if the caller's intent were\n * merely advisory. Unknown keys are pruned; a known key with a wrong type is\n * rejected, never coerced.\n */\nfunction scopePatchOf(body: unknown): { ok: true; patch: ScopePatch } | { ok: false; code: string } {\n if (body === null || typeof body !== 'object' || Array.isArray(body)) {\n return { ok: false, code: ERR_BOOST_INVALID_BODY }\n }\n const source = body as Record<string, unknown>\n const has = (key: string): boolean => Object.prototype.hasOwnProperty.call(source, key)\n if (RESERVED_FIELDS.some(has)) return { ok: false, code: ERR_BOOST_INVALID_BODY }\n\n const patch: ScopePatch = {}\n if (has('mode')) {\n if (source.mode !== 'selected' && source.mode !== 'global') {\n return { ok: false, code: ERR_BOOST_INVALID_BODY }\n }\n patch.mode = source.mode\n }\n if (has('workspaceIds')) {\n const ids = source.workspaceIds\n if (!Array.isArray(ids) || !ids.every(id => typeof id === 'string')) {\n return { ok: false, code: ERR_BOOST_INVALID_BODY }\n }\n patch.workspaceIds = [...ids]\n }\n if (has('shadow')) {\n if (typeof source.shadow !== 'boolean') return { ok: false, code: ERR_BOOST_INVALID_BODY }\n patch.shadow = source.shadow\n }\n if (has('projection')) {\n if (!isProjectionMode(source.projection)) return { ok: false, code: ERR_BOOST_INVALID_BODY }\n patch.projection = source.projection\n }\n return { ok: true, patch }\n}\n\n/** The store's stable code, or undefined for anything else (which never escapes). */\nfunction scopeCodeOf(error: unknown): ScopeCode | undefined {\n if (typeof error !== 'object' || error === null || !('code' in error)) return undefined\n const code = (error as { code?: unknown }).code\n return typeof code === 'string' && SCOPE_CODES.has(code) ? (code as ScopeCode) : undefined\n}\n\n/**\n * One compare-and-swap write shared by `scope-set` and `shadow`.\n *\n * `version: 2` is forced even though `ScopeStore.write` bases a corrupt or\n * v1 file on `DEFAULT_SCOPE`: the invariant must hold at the mutation boundary,\n * where the store's \"persist whatever `mutate` returns\" contract makes it\n * binding. `revision` is deliberately absent — the store owns it.\n */\nasync function writeScope(\n scope: ScopeStore,\n mutate: (doc: ScopeDoc) => ScopeDoc,\n baseRevision: number,\n signal?: AbortSignal,\n): Promise<BoostResult> {\n try {\n const doc = await scope.write(mutate, baseRevision, { signal })\n return { ok: true, data: doc }\n } catch (error) {\n const code = scopeCodeOf(error)\n if (code !== undefined) return { ok: false, code }\n throw error\n }\n}\n\n/** `scope-set`: validate, prune, then write with compare-and-swap. */\nasync function scopeSetCommand(deps: BoostDeps, args: BoostArgs): Promise<BoostResult> {\n const parsed = scopePatchOf(args.body)\n if (!parsed.ok) return parsed\n if (!isRevision(args.baseRevision)) return { ok: false, code: ERR_BOOST_INVALID_ARGS }\n const patch = parsed.patch\n return writeScope(\n deps.scope,\n doc => ({ ...doc, ...patch, version: 2 }),\n args.baseRevision,\n deps.signal,\n )\n}\n\n/**\n * `shadow`: the shadow-week switch, independent of `projection`.\n *\n * A version 1 document is **not** upgraded here. The store can carry a v1\n * document through a write, but design §5.5 makes `scope-set` the explicit\n * upgrade path: the other write refuses with the degraded read's stable code so\n * the operator performs the documented upgrade instead of a blind rewrite.\n */\nasync function shadowCommand(deps: BoostDeps, args: BoostArgs): Promise<BoostResult> {\n if (typeof args.body !== 'boolean') return { ok: false, code: ERR_BOOST_INVALID_BODY }\n if (!isRevision(args.baseRevision)) return { ok: false, code: ERR_BOOST_INVALID_ARGS }\n const current = await deps.scope.read()\n if (current.code === ERR_SCOPE_UNKNOWN_VERSION) {\n return { ok: false, code: ERR_SCOPE_UNKNOWN_VERSION }\n }\n const shadow = args.body\n return writeScope(deps.scope, doc => ({ ...doc, shadow }), args.baseRevision, deps.signal)\n}\n\n/** One handler per subcommand; the table is the dispatch and the documentation. */\nconst COMMANDS: Record<BoostCmd, (deps: BoostDeps, args: BoostArgs) => Promise<BoostResult>> = {\n status: statusCommand,\n 'scope-get': scopeGetCommand,\n 'scope-set': scopeSetCommand,\n shadow: shadowCommand,\n}\n\n/**\n * Run one `boost` invocation. Pure orchestration over the two stores.\n *\n * Failures are values: an unknown command, an invalid body or a store code all\n * come back as `{ ok: false, code }`. The `try` covers the argument read as\n * well as the handler, so a null call or an argument object with a throwing\n * getter answers a stable code instead of throwing. The catch exists only so\n * an unexpected store failure cannot turn the user's only control surface into\n * a thrown tool error; it is not an expected path.\n */\nexport async function runBoost(\n input: BoostDeps & {\n args: { cmd: BoostCmd; body?: unknown; baseRevision?: number }\n },\n): Promise<{ ok: true; data: unknown } | { ok: false; code: string }> {\n try {\n const signal = (input as { signal?: AbortSignal } | null | undefined)?.signal\n if (signal?.aborted === true) return { ok: false, code: ERR_SCOPE_ABORTED }\n const args = (input as { args?: unknown } | null | undefined)?.args\n const cmd = (args as { cmd?: unknown } | null | undefined)?.cmd\n const handler =\n typeof cmd === 'string' && Object.prototype.hasOwnProperty.call(COMMANDS, cmd)\n ? COMMANDS[cmd as BoostCmd]\n : undefined\n if (handler === undefined) return { ok: false, code: ERR_BOOST_UNKNOWN_CMD }\n return await handler(input as BoostDeps, args as BoostArgs)\n } catch {\n return { ok: false, code: ERR_BOOST_INTERNAL }\n }\n}\n\n/**\n * The host's cancellation signal, or `undefined` for any other shape.\n *\n * `exec` crosses the host boundary and is untrusted here: a plain object with\n * an `aborted` boolean and an `addEventListener` function is the documented\n * `AbortSignal` contract this code relies on, and anything else is ignored\n * rather than dereferenced (a foreign host must not make `boost` throw).\n */\nfunction signalOf(exec: unknown): AbortSignal | undefined {\n const candidate = (exec as { signal?: unknown } | null | undefined)?.signal\n if (typeof candidate !== 'object' || candidate === null) return undefined\n const signal = candidate as { aborted?: unknown; addEventListener?: unknown }\n if (typeof signal.aborted !== 'boolean' || typeof signal.addEventListener !== 'function') {\n return undefined\n }\n return candidate as AbortSignal\n}\n\n/** Model-facing description: what each command does and what it returns. */\nconst DESCRIPTION = [\n 'Inspect or change dsh-boost state. Commands:',\n 'status reports the scope document, both switches, receipt counts per code, both ledgers (substitution; projection net with its retrieval count), the measured fixed overhead, and the degraded codes;',\n 'scope-get reads the full scope document;',\n 'scope-set replaces the given fields with compare-and-swap; body = { mode?, workspaceIds?, shadow?, projection? }; version and revision are store-owned and rejected;',\n 'shadow persists the shadow-week switch; body = boolean; it refuses a version 1 document with ERR_SCOPE_UNKNOWN_VERSION — run scope-set once to upgrade it.',\n 'scope-set and shadow require the baseRevision last seen via status or scope-get; a stale one fails with ERR_SCOPE_REVISION_CONFLICT. Failures are { ok:false, code } values, never thrown.',\n].join(' ')\n\n/** The argument schema shown to the model; `status`/`scope-get` need only `cmd`. */\nconst PARAMETERS: Record<string, unknown> = {\n type: 'object',\n properties: {\n cmd: {\n type: 'string',\n enum: ['status', 'scope-get', 'scope-set', 'shadow'],\n description: 'Which boost operation to run.',\n },\n body: {\n description:\n 'scope-set: the desired scope fields (unknown keys are pruned, version/revision rejected). shadow: the desired boolean.',\n oneOf: [\n {\n type: 'object',\n properties: {\n mode: { type: 'string', enum: ['selected', 'global'] },\n workspaceIds: { type: 'array', items: { type: 'string' } },\n shadow: { type: 'boolean' },\n projection: { type: 'string', enum: ['off', 'shadow', 'on'] },\n },\n },\n { type: 'boolean' },\n ],\n },\n baseRevision: {\n // `minimum` is outside the host's enforced JSON-Schema subset; the\n // runtime check in `isRevision` is the authority for `>= 0` (row 45).\n type: 'integer',\n description: 'Required by scope-set and shadow: the revision last seen (a non-negative integer).',\n },\n },\n required: ['cmd'],\n additionalProperties: false,\n}\n\n/**\n * The model-visible part of the `boost` tool definition.\n *\n * This is the second half of the fixed-overhead budget: `estimateToolsTokens`\n * prices the schema the model receives every request. `output` is a host-side\n * envelope and is not part of the request's tool list, so it is excluded.\n */\nfunction boostSchema(): { name: 'boost'; description: string; parameters: Record<string, unknown> } {\n return { name: 'boost', description: DESCRIPTION, parameters: PARAMETERS }\n}\n\n/** The one memoised protocol + schema measurement, shared by startup and status. */\nlet boostFixedOverhead: Promise<FixedOverheadMeasurement | 'unknown'> | undefined\n\n/**\n * The startup probe `apply` fires once and `status` awaits.\n *\n * Memoised per process: a status call must report the same number the startup\n * measured, and must not re-import or re-price the schema.\n */\nexport function measureBoostFixedOverhead(): Promise<FixedOverheadMeasurement | 'unknown'> {\n boostFixedOverhead ??= measureFixedOverhead(boostSchema())\n return boostFixedOverhead\n}\n\n/**\n * The canonical output envelope. The host validates every successful return\n * against this schema, and a failure is a successful call whose value is\n * `{ ok: false, code }` (the tool never throws its stable codes), so both\n * branches are declared.\n */\nconst OUTPUT_SCHEMA: JsonSchemaNode = {\n oneOf: [\n {\n type: 'object',\n properties: {\n ok: { type: 'boolean', const: true },\n data: {},\n },\n required: ['ok', 'data'],\n additionalProperties: false,\n },\n {\n type: 'object',\n properties: {\n ok: { type: 'boolean', const: false },\n code: { type: 'string' },\n },\n required: ['ok', 'code'],\n additionalProperties: false,\n },\n ],\n}\n\n/** Render the canonical envelope as one text block; `JSON.stringify` is the format. */\nfunction renderResult(_args: unknown, value: unknown): { type: 'text'; text: string }[] {\n return [{ type: 'text', text: JSON.stringify(value) ?? 'undefined' }]\n}\n\n/**\n * Build the host tool definition.\n *\n * `output: { schema, render }` is mandatory in the host's `ToolDefinition`;\n * a definition missing it is rejected at registration. `execute` reuses\n * `runBoost`, so the tool and the pure orchestration cannot drift.\n */\nexport function boostTool(deps: BoostDeps): {\n name: 'boost'\n description: string\n parameters: Record<string, unknown>\n output: {\n schema: JsonSchemaNode\n render: (args: unknown, value: unknown) => { type: 'text'; text: string }[]\n }\n execute: (args: unknown, exec: unknown) => Promise<unknown>\n} {\n return {\n name: 'boost',\n description: DESCRIPTION,\n parameters: PARAMETERS,\n output: { schema: OUTPUT_SCHEMA, render: renderResult },\n execute: (args, exec) => runBoost({ args: args as BoostArgs, ...deps, signal: signalOf(exec) }),\n }\n}"]}
|
package/lib/client.js
CHANGED
|
@@ -41,7 +41,7 @@ window.__ModuleLoader__.load({
|
|
|
41
41
|
const LABEL_PROJECTION_GROSS$1 = "投影毛额(一次性)";
|
|
42
42
|
const LABEL_PROJECTION_GROSS_REPLAY$1 = "投影毛额(按各自 horizon 重放)";
|
|
43
43
|
const LABEL_PROJECTION_NET$1 = "投影净额";
|
|
44
|
-
const LABEL_PROJECTION_ON_PRECONDITIONS$1 = "
|
|
44
|
+
const LABEL_PROJECTION_ON_PRECONDITIONS$1 = "开启投影前确认一件事";
|
|
45
45
|
const LABEL_RETRIEVALS$1 = "取回次数";
|
|
46
46
|
const LABEL_SAVED_LOWER$1 = "替换节省(下界)";
|
|
47
47
|
const LABEL_SAVED_UPPER$1 = "替换节省(上界)";
|
|
@@ -58,15 +58,16 @@ window.__ModuleLoader__.load({
|
|
|
58
58
|
const PROJECTION_ON$1 = "开启(真替换)";
|
|
59
59
|
const PROJECTION_SHADOW$1 = "影子(只记账)";
|
|
60
60
|
const RETRY$1 = "重试";
|
|
61
|
-
const SAVED$1 = "
|
|
61
|
+
const SAVED$1 = "与页面上次读到或保存时的文档一致。页面不会轮询:别处(例如让模型调用 boost)改了 scope,这里要重新读取才看得到。";
|
|
62
62
|
const SECTION_CONFIG$1 = "生效配置";
|
|
63
63
|
const SECTION_COUNTS$1 = "收据计数";
|
|
64
64
|
const SECTION_SCOPE$1 = "作用域";
|
|
65
65
|
const SECTION_STATUS$1 = "运行状态";
|
|
66
66
|
const TITLE$1 = "Token 效率";
|
|
67
67
|
const UNAVAILABLE_REGISTRY$1 = "读不到作用域文档,这一块暂时只读。";
|
|
68
|
-
const UNKNOWN$1 = "
|
|
68
|
+
const UNKNOWN$1 = "未知错误";
|
|
69
69
|
const meta$1 = { "description": "通过工具回执投影与确定性只读替换降低 DeepSeek Harness 的 token 消耗。", "title": "dsh-boost" };
|
|
70
|
+
const STATUS_UNAVAILABLE$1 = "状态读取失败,下面的数字不是「没有」,而是没读到";
|
|
70
71
|
const zh = {
|
|
71
72
|
ACTION_REREAD: ACTION_REREAD$1,
|
|
72
73
|
ACTION_SAVE: ACTION_SAVE$1,
|
|
@@ -162,7 +163,8 @@ window.__ModuleLoader__.load({
|
|
|
162
163
|
TITLE: TITLE$1,
|
|
163
164
|
UNAVAILABLE_REGISTRY: UNAVAILABLE_REGISTRY$1,
|
|
164
165
|
UNKNOWN: UNKNOWN$1,
|
|
165
|
-
meta: meta$1
|
|
166
|
+
meta: meta$1,
|
|
167
|
+
STATUS_UNAVAILABLE: STATUS_UNAVAILABLE$1
|
|
166
168
|
};
|
|
167
169
|
function copyOf(t) {
|
|
168
170
|
const resolved = {};
|
|
@@ -309,7 +311,7 @@ window.__ModuleLoader__.load({
|
|
|
309
311
|
const LABEL_PROJECTION_GROSS = "Projection gross (one-time)";
|
|
310
312
|
const LABEL_PROJECTION_GROSS_REPLAY = "Projection gross (replayed per horizon)";
|
|
311
313
|
const LABEL_PROJECTION_NET = "Projection net";
|
|
312
|
-
const LABEL_PROJECTION_ON_PRECONDITIONS = "
|
|
314
|
+
const LABEL_PROJECTION_ON_PRECONDITIONS = "One thing to check before switching projection on";
|
|
313
315
|
const LABEL_RETRIEVALS = "Retrievals";
|
|
314
316
|
const LABEL_SAVED_LOWER = "Substitution saving (lower)";
|
|
315
317
|
const LABEL_SAVED_UPPER = "Substitution saving (upper)";
|
|
@@ -326,15 +328,16 @@ window.__ModuleLoader__.load({
|
|
|
326
328
|
const PROJECTION_ON = "On (real substitution)";
|
|
327
329
|
const PROJECTION_SHADOW = "Shadow (record only)";
|
|
328
330
|
const RETRY = "Retry";
|
|
329
|
-
const SAVED = "Matches the document
|
|
331
|
+
const SAVED = "Matches the document as this page last read or saved it. The page does not poll: if something else changes the scope (say, the model runs boost), reload to see it.";
|
|
330
332
|
const SECTION_CONFIG = "Effective config";
|
|
331
333
|
const SECTION_COUNTS = "Receipt counts";
|
|
332
334
|
const SECTION_SCOPE = "Scope";
|
|
333
335
|
const SECTION_STATUS = "Status";
|
|
334
336
|
const TITLE = "Token efficiency";
|
|
335
337
|
const UNAVAILABLE_REGISTRY = "The scope document could not be read, so this section is read-only for now.";
|
|
336
|
-
const UNKNOWN = "
|
|
338
|
+
const UNKNOWN = "unknown error";
|
|
337
339
|
const meta = { "description": "Cut DeepSeek Harness token usage by projecting tool receipts and substituting deterministic read-only calls.", "title": "dsh-boost" };
|
|
340
|
+
const STATUS_UNAVAILABLE = "Status could not be read: the figures below are unread, not empty";
|
|
338
341
|
const en = {
|
|
339
342
|
ACTION_REREAD,
|
|
340
343
|
ACTION_SAVE,
|
|
@@ -430,7 +433,8 @@ window.__ModuleLoader__.load({
|
|
|
430
433
|
TITLE,
|
|
431
434
|
UNAVAILABLE_REGISTRY,
|
|
432
435
|
UNKNOWN,
|
|
433
|
-
meta
|
|
436
|
+
meta,
|
|
437
|
+
STATUS_UNAVAILABLE
|
|
434
438
|
};
|
|
435
439
|
const LOCALE_NAMESPACE = "dsh-boost";
|
|
436
440
|
function stringsOf(source) {
|
|
@@ -758,9 +762,16 @@ window.__ModuleLoader__.load({
|
|
|
758
762
|
rows ? /* @__PURE__ */ jsxRuntime.jsx("dl", { children }) : children
|
|
759
763
|
] });
|
|
760
764
|
}
|
|
761
|
-
function Degraded({ codes }) {
|
|
765
|
+
function Degraded({ codes, unavailable }) {
|
|
762
766
|
const t = useT();
|
|
763
767
|
const c = copyOf(t);
|
|
768
|
+
if (unavailable !== void 0) {
|
|
769
|
+
return /* @__PURE__ */ jsxRuntime.jsxs("p", { className: "boost-settings__warn", children: [
|
|
770
|
+
c.STATUS_UNAVAILABLE,
|
|
771
|
+
" ",
|
|
772
|
+
/* @__PURE__ */ jsxRuntime.jsx("code", { children: unavailable === "" ? c.UNKNOWN : unavailable })
|
|
773
|
+
] });
|
|
774
|
+
}
|
|
764
775
|
if (codes.length === 0) {
|
|
765
776
|
return /* @__PURE__ */ jsxRuntime.jsx("p", { className: "boost-settings__ok", children: c.NO_DEGRADED });
|
|
766
777
|
}
|
|
@@ -789,6 +800,7 @@ window.__ModuleLoader__.load({
|
|
|
789
800
|
const status = payloadOf(result?.ok === true ? result.data.status : void 0);
|
|
790
801
|
const scope = result?.ok === true ? result.data.scope : void 0;
|
|
791
802
|
const config = payloadOf(result?.ok === true ? result.data.config : void 0);
|
|
803
|
+
const statusCode = status !== null && typeof status === "object" && status.ok === false ? String(status.code ?? "") : void 0;
|
|
792
804
|
const saved = pick(status, "saved");
|
|
793
805
|
const degraded = pick(status, "degraded");
|
|
794
806
|
const codes = Array.isArray(degraded) ? degraded.filter((code) => typeof code === "string") : [];
|
|
@@ -836,8 +848,8 @@ window.__ModuleLoader__.load({
|
|
|
836
848
|
onReload: () => load()
|
|
837
849
|
}
|
|
838
850
|
) : null,
|
|
839
|
-
/* @__PURE__ */ jsxRuntime.jsx(Section, { title: c.LABEL_DEGRADED, rows: false, children: /* @__PURE__ */ jsxRuntime.jsx(Degraded, { codes }) }),
|
|
840
|
-
/* @__PURE__ */ jsxRuntime.jsx(Section, { title: c.SECTION_COUNTS, rows: false, children: countRows.length === 0 ? /* @__PURE__ */ jsxRuntime.jsx("p", { className: "boost-settings__muted", children: c.NO_RECEIPTS }) : /* @__PURE__ */ jsxRuntime.jsx("ul", { className: "boost-settings__codes", children: countRows.map(([code, count]) => /* @__PURE__ */ jsxRuntime.jsxs("li", { children: [
|
|
851
|
+
/* @__PURE__ */ jsxRuntime.jsx(Section, { title: c.LABEL_DEGRADED, rows: false, children: /* @__PURE__ */ jsxRuntime.jsx(Degraded, { codes, unavailable: statusCode }) }),
|
|
852
|
+
/* @__PURE__ */ jsxRuntime.jsx(Section, { title: c.SECTION_COUNTS, rows: false, children: countRows.length === 0 ? /* @__PURE__ */ jsxRuntime.jsx("p", { className: "boost-settings__muted", children: statusCode === void 0 ? c.NO_RECEIPTS : c.STATUS_UNAVAILABLE }) : /* @__PURE__ */ jsxRuntime.jsx("ul", { className: "boost-settings__codes", children: countRows.map(([code, count]) => /* @__PURE__ */ jsxRuntime.jsxs("li", { children: [
|
|
841
853
|
/* @__PURE__ */ jsxRuntime.jsx("code", { children: code }),
|
|
842
854
|
/* @__PURE__ */ jsxRuntime.jsx("span", { children: count.toLocaleString() })
|
|
843
855
|
] }, code)) }) }),
|
|
@@ -903,7 +915,7 @@ window.__ModuleLoader__.load({
|
|
|
903
915
|
return;
|
|
904
916
|
}
|
|
905
917
|
const slots = ctx.slots;
|
|
906
|
-
slots.inject(
|
|
918
|
+
const disposeInjection = slots.inject(
|
|
907
919
|
SETTINGS_SLOT,
|
|
908
920
|
() => slots.register(
|
|
909
921
|
{
|
|
@@ -918,6 +930,7 @@ window.__ModuleLoader__.load({
|
|
|
918
930
|
App
|
|
919
931
|
)
|
|
920
932
|
);
|
|
933
|
+
ctx.effect?.(() => disposeInjection, `${WARN_PREFIX}: settings section`);
|
|
921
934
|
}
|
|
922
935
|
exports.SETTINGS_ID = SETTINGS_ID;
|
|
923
936
|
exports.SETTINGS_SLOT = SETTINGS_SLOT;
|
package/locale/en.json
CHANGED
|
@@ -68,7 +68,7 @@
|
|
|
68
68
|
"LABEL_PROJECTION_GROSS": "Projection gross (one-time)",
|
|
69
69
|
"LABEL_PROJECTION_GROSS_REPLAY": "Projection gross (replayed per horizon)",
|
|
70
70
|
"LABEL_PROJECTION_NET": "Projection net",
|
|
71
|
-
"LABEL_PROJECTION_ON_PRECONDITIONS": "
|
|
71
|
+
"LABEL_PROJECTION_ON_PRECONDITIONS": "One thing to check before switching projection on",
|
|
72
72
|
"LABEL_RETRIEVALS": "Retrievals",
|
|
73
73
|
"LABEL_SAVED_LOWER": "Substitution saving (lower)",
|
|
74
74
|
"LABEL_SAVED_UPPER": "Substitution saving (upper)",
|
|
@@ -85,16 +85,17 @@
|
|
|
85
85
|
"PROJECTION_ON": "On (real substitution)",
|
|
86
86
|
"PROJECTION_SHADOW": "Shadow (record only)",
|
|
87
87
|
"RETRY": "Retry",
|
|
88
|
-
"SAVED": "Matches the document
|
|
88
|
+
"SAVED": "Matches the document as this page last read or saved it. The page does not poll: if something else changes the scope (say, the model runs boost), reload to see it.",
|
|
89
89
|
"SECTION_CONFIG": "Effective config",
|
|
90
90
|
"SECTION_COUNTS": "Receipt counts",
|
|
91
91
|
"SECTION_SCOPE": "Scope",
|
|
92
92
|
"SECTION_STATUS": "Status",
|
|
93
93
|
"TITLE": "Token efficiency",
|
|
94
94
|
"UNAVAILABLE_REGISTRY": "The scope document could not be read, so this section is read-only for now.",
|
|
95
|
-
"UNKNOWN": "
|
|
95
|
+
"UNKNOWN": "unknown error",
|
|
96
96
|
"meta": {
|
|
97
97
|
"description": "Cut DeepSeek Harness token usage by projecting tool receipts and substituting deterministic read-only calls.",
|
|
98
98
|
"title": "dsh-boost"
|
|
99
|
-
}
|
|
99
|
+
},
|
|
100
|
+
"STATUS_UNAVAILABLE": "Status could not be read: the figures below are unread, not empty"
|
|
100
101
|
}
|
package/locale/zh.json
CHANGED
|
@@ -68,7 +68,7 @@
|
|
|
68
68
|
"LABEL_PROJECTION_GROSS": "投影毛额(一次性)",
|
|
69
69
|
"LABEL_PROJECTION_GROSS_REPLAY": "投影毛额(按各自 horizon 重放)",
|
|
70
70
|
"LABEL_PROJECTION_NET": "投影净额",
|
|
71
|
-
"LABEL_PROJECTION_ON_PRECONDITIONS": "
|
|
71
|
+
"LABEL_PROJECTION_ON_PRECONDITIONS": "开启投影前确认一件事",
|
|
72
72
|
"LABEL_RETRIEVALS": "取回次数",
|
|
73
73
|
"LABEL_SAVED_LOWER": "替换节省(下界)",
|
|
74
74
|
"LABEL_SAVED_UPPER": "替换节省(上界)",
|
|
@@ -85,16 +85,17 @@
|
|
|
85
85
|
"PROJECTION_ON": "开启(真替换)",
|
|
86
86
|
"PROJECTION_SHADOW": "影子(只记账)",
|
|
87
87
|
"RETRY": "重试",
|
|
88
|
-
"SAVED": "
|
|
88
|
+
"SAVED": "与页面上次读到或保存时的文档一致。页面不会轮询:别处(例如让模型调用 boost)改了 scope,这里要重新读取才看得到。",
|
|
89
89
|
"SECTION_CONFIG": "生效配置",
|
|
90
90
|
"SECTION_COUNTS": "收据计数",
|
|
91
91
|
"SECTION_SCOPE": "作用域",
|
|
92
92
|
"SECTION_STATUS": "运行状态",
|
|
93
93
|
"TITLE": "Token 效率",
|
|
94
94
|
"UNAVAILABLE_REGISTRY": "读不到作用域文档,这一块暂时只读。",
|
|
95
|
-
"UNKNOWN": "
|
|
95
|
+
"UNKNOWN": "未知错误",
|
|
96
96
|
"meta": {
|
|
97
97
|
"description": "通过工具回执投影与确定性只读替换降低 DeepSeek Harness 的 token 消耗。",
|
|
98
98
|
"title": "dsh-boost"
|
|
99
|
-
}
|
|
99
|
+
},
|
|
100
|
+
"STATUS_UNAVAILABLE": "状态读取失败,下面的数字不是「没有」,而是没读到"
|
|
100
101
|
}
|