dsh-boost 0.1.2 → 0.1.4

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.md CHANGED
@@ -3,12 +3,13 @@
3
3
  通过**工具回执投影**与**确定性只读替换**降低 DeepSeek Harness(DSH)的 token 消耗。
4
4
 
5
5
  > **状态:v1 已实现。** 投影、替换与控制面均已落地;`npm run build` 干净,测试套件全部通过。
6
- > 收益区间是设计阶段的事前估算(下界 3.5% / 理想上界 10.0%;净保底约 0.4%),交付物**无法复算**——见下。
6
+ > 收益区间是设计阶段的事前估算(下界 3.5% / 理想上界 10.0%;投影侧在 300 个最长会话上的
7
+ > 聚合净额约 0.4%),两端都是离线估算、不是每会话保底,交付物**无法复算**——见下。
7
8
 
8
9
  ## 它解决什么
9
10
 
10
11
  DSH 每次模型请求都会回放全部历史。本机 300 个最长会话的实测聚合(`npm run --silent stats`——不带
11
- `--silent` 时 npm 会把 `> dsh-boost@0.1.1 stats` 横幅打进 stdout,机器解析请用 `--silent` 或直接
12
+ `--silent` 时 npm 会把 `> dsh-boost@0.1.3 stats` 横幅打进 stdout,机器解析请用 `--silent` 或直接
12
13
  `node scripts/session-stats.mjs`;快照时刻 `2026-11-19T03:13:21Z`):54,141 步、54,088 个请求,合计 10,575,904,022 raw token。按步均值
13
14
  195,340 token,按请求均值 195,531、中位 187,681;97.01% 的输入是缓存读。工具回执是体积主体
14
15
  (bash 61.75%、read 22.13%、ssh 10.01%),而下一步真正会用到的部分通常远小于回执本身。
@@ -21,8 +22,9 @@ DSH 每次模型请求都会回放全部历史。本机 300 个最长会话的
21
22
  直接提交,不再向模型要一次决策;多候选时用一个单标签选择器——一次独立的辅助请求
22
23
  (`maxTokens` 512,另加其输入)。这是对原始需求 2.2 的**收窄**:原需求要 Jev 对每个工具
23
24
  结果逐条打分、判断能否交给下一个工具,v1 只做「同一回执上的多个候选里选一个」,不做
24
- 逐条打分(见[澄清记录](docs/superpowers/clarifications/2026-11-18-dsh-token-efficiency.md)
25
- 的 2.2 与「用户裁决」第 9 条)。对替换涉及的三个工具而言,计划里的 `$public` 参数绑定
25
+ 逐条打分。这条收窄是**实现者的范围决定(E2)**,不是用户裁决——澄清记录里**没有用户消息
26
+ 追认它**(见[澄清记录](docs/superpowers/clarifications/2026-11-18-dsh-token-efficiency.md)
27
+ 的 2.2 与「实现者决定」E2)。对替换涉及的三个工具而言,计划里的 `$public` 参数绑定
26
28
  (把上一步回执里的值直接搬进下一步参数)在实践中只对 `glob` 的单 token 输出有效;
27
29
  `read` 与 `grep` 的输出带行号或是裸路径,标识符投影匹配不到,这些调用会退回模型。
28
30
 
@@ -34,9 +36,13 @@ DSH 每次模型请求都会回放全部历史。本机 300 个最长会话的
34
36
 
35
37
  v1 的**事前估算**区间是 **3.5%(下界)– 10.0%(理想上界)**,按 raw `totalTokens` 计;
36
38
  **3.5% 不是保底**——它是设计阶段对一个 300 会话语料做离线估算得到的下界,其中替换账的
37
- 2.70% 是**上限**,不能算进保底;诚实的净保底只有约 **0.4%**(投影侧毛额约 0.8% 减去每请求
38
- 固定开销约 0.4%)。这个区间不是保证,也不是从交付的 `session-snapshot.json` 能复算出来的
39
- 数字(快照只存聚合计数,没有估算用的分项)——交付物里**没有任何工具能复算它**。影子周也
39
+ 2.70% 是**上限**,不能算进任何保底。投影侧在 **300 个最长会话**上的**聚合**净额约 **0.4%**
40
+ (毛额约 0.8% 减去每请求固定开销约 0.4%,即 778 / 195,531);它也不是每会话保底——长会话
41
+ 摊薄固定开销,**短会话可能倒亏**,而 `top-300` 里没有 ≤5 步的会话。3.5% 与 0.4% 两端都是
42
+ 离线估算,不是测量。这个区间不是保证,也不是从交付的 `session-snapshot.json` 能复算出来的
43
+ 数字:快照按会话存了聚合计数,也存了每个会话的 `requestTokens` / `receiptChars` 数组、
44
+ `valueTransfer` / `whitelist` 计数,以及该会话按工具族归因的 `toolChars` 字符总量,但
45
+ **没有逐回执的族别字节**,估算所需的投影分项仍然凑不出来——交付物里**没有任何工具能复算它**。影子周也
40
46
  **不能**把这个区间变成实测百分比:影子报告只输出四个比例(见「影子周」一节),没有总 token
41
47
  分母,`boost status` 也只有绝对值;区间要被实测取代,得等后续版本补上分母统计。
42
48
 
@@ -58,26 +64,29 @@ v1 的**事前估算**区间是 **3.5%(下界)– 10.0%(理想上界)**
58
64
  `dsh plugin` 要求指定 profile,剩下的参数原样转发给该 profile 目录里的 pnpm:
59
65
 
60
66
  ```bash
61
- # 从 registry 安装:npmjs 上的 latest 是 0.1.1(本仓库 .npmrc 与 lockfile
67
+ # 从 registry 安装:npmjs 上的 latest 是 0.1.3(本仓库 .npmrc 与 lockfile
62
68
  # 也已钉在 npmjs,见下)
63
- dsh plugin --profile <name> add dsh-boost@^0.1.1 --registry=https://registry.npmjs.org/
69
+ dsh plugin --profile <name> add dsh-boost@^0.1.3 --registry=https://registry.npmjs.org/
64
70
 
65
71
  # 或从本地 checkout 安装(先构建;dist/ 不入库)
66
72
  npm run build
67
73
  dsh plugin --profile <name> add /absolute/path/to/dsh-boost
68
74
  ```
69
75
 
70
- 例如 web profile:`dsh plugin --profile web add dsh-boost@^0.1.1 --registry=https://registry.npmjs.org/`。
76
+ 例如 web profile:`dsh plugin --profile web add dsh-boost@^0.1.3 --registry=https://registry.npmjs.org/`。
71
77
  `dsh plugin` 把操作转发给 pnpm,所以 pnpm 必须在 PATH 上。
72
78
 
73
- > **两个 registry 的版本不同,`^0.1.0` 不是安全的钉法。** `registry.npmjs.org` 上有三条版本记录:
74
- > `0.1.1`(当前 `latest`)、`0.1.0`,以及首次发布时 npm 自动创建的占位版本 `0.0.0-stage`。而
75
- > `registry.npmmirror.com` 目前只有 `0.1.0`(它的 `latest` 也是 0.1.0)——本仓库已把 `.npmrc`
76
- > 与 lockfile 改钉 npmjs,但你机器上的全局 npm 配置可能仍指向镜像。同一个
77
- > `^0.1.0` 在 npmjs 解析到 0.1.1、在镜像解析到 0.1.0——镜像用户会装到缺少 0.1.1 十项修复的
78
- > 构建,其中几项是静默失效修复。请用 `dsh-boost@^0.1.1`(或 `@latest`),并在意 registry 时
79
- > 显式传 `--registry=https://registry.npmjs.org/`;镜像尚未同步 0.1.1 时,不带该 flag 的
80
- > `@^0.1.1` 会解析失败。
79
+ > **两个 registry 现在都到 0.1.3,`^0.1.3` 是安全的钉法。** `registry.npmjs.org` 与
80
+ > `registry.npmmirror.com` 各有五条版本记录:`0.1.3`(两边都是当前 `latest`)、`0.1.2`、
81
+ > `0.1.1`、`0.1.0`,以及首次发布时 npm 自动创建的占位版本 `0.0.0-stage`——**不要安装
82
+ > `0.0.0-stage`**,它不是可用构建。0.1.3 修掉了「模型看到的正文被外层改写后仍按原始回执
83
+ > 提交替换」的问题,并把节省改报为上下界区间(新增 `avoided_total_tokens`),另加三个宿主
84
+ > 能力降级码与 `status.hasSpill`;0.1.2 修掉了 scope 文件被静默覆盖的问题:坏 JSON(含非对象
85
+ > 或数组)与无法识别的版本不再被默认文档覆盖。请用 `dsh-boost@^0.1.3`(或 `@latest`)——
86
+ > `^0.1.3` 表达的是「至少含 0.1.3 的修复」。本仓库已把 `.npmrc`
87
+ > 与 lockfile 钉在 npmjs,但**你机器上的全局 npm 配置**可能仍指向一个尚未同步 0.1.3 的镜像:
88
+ > 那是本机配置,不是本仓库的状态。在意 registry 时显式传
89
+ > `--registry=https://registry.npmjs.org/`;镜像滞后时,`@^0.1.3` 会在同步前解析失败。
81
90
 
82
91
  包是 ESM(`"type": "module"`),`exports` 的 `.` 条目同时映射 `require` / `default`:Node ≥ 24.9
83
92
  下 `require('dsh-boost')` 与 `import` 加载同一份代码,装好的包里**不做任何构建**(`files` 只带
@@ -97,7 +106,7 @@ bundle,patch 的 `insert` 行落在 profile root 上。**装完必须重启 DS
97
106
  ```
98
107
 
99
108
  `workspaceIds` 为空时没有可见工作区:协议段不注入,投影与替换都原样放行,但每个工具调用
100
- 仍会记一条 `skip:no-scope` 收据。`boost` 工具本身是唯一的 scope 豁免,因此没有工作区时仍然
109
+ 仍会记一条 `skip:no-scope` 收据——但 PTC 内层调用(`exec.parent` 存在)与被取消的调用在 scope 门之前就返回,两条都不记。`boost` 工具本身是唯一的 scope 豁免,因此没有工作区时仍然
101
110
  可以调用它来启用。
102
111
 
103
112
  `boost` 是**模型工具,不是 shell 命令**——这个包没有 `bin`,启用全程都要在对话里让模型调用
@@ -106,8 +115,8 @@ bundle,patch 的 `insert` 行落在 profile root 上。**装完必须重启 DS
106
115
  > 调用 boost 工具,参数 `{"cmd":"status"}`,把 JSON 结果给我。
107
116
 
108
117
  首次 `status` 应看到 `ok: true`;`data.scope.workspaceIds` 为空、`revision` 为 `0`,`shadow` 为
109
- `true`、`projection` 为 `"shadow"`,`counts` 为空(**仅限全新会话**——越界会话更早的工具调用
110
- 已经各记过一条 `skip:no-scope`)。首次 `status` 的 `degraded` 里**不会**因为 `scope.json`
118
+ `true`、`projection` 为 `"shadow"`,`counts` 为空(**仅限全新回执根**——`scan()` 读全部分片,同一 DSH home 里别的会话早先的
119
+ 越界调用已经各记过一条 `skip:no-scope`)。首次 `status` 的 `degraded` 里**不会**因为 `scope.json`
111
120
  缺失而出现 `ERR_SCOPE_READ_FAILED`:缺失是干净的默认值(`ENOENT` 不带降级码,
112
121
  `src/scope/store.ts`);全新根目录且宿主能力齐全时,`degraded` 就是空数组。在 `status` 的
113
122
  读取路径上,`ERR_SCOPE_READ_FAILED` 只表示文件**存在但读不出来**(权限、I/O、路径是目录
@@ -152,6 +161,9 @@ bundle,patch 的 `insert` 行落在 profile root 上。**装完必须重启 DS
152
161
  `@deepseek-ai/dsh-token-meter/estimate` 不可达,`fixedOverheadTokens` 会是字符串
153
162
  `"unknown"`(不是 0),`degraded` 带 `ERR_HOST_NO_ESTIMATOR`;此时 `estimate_kind` 仍可能是
154
163
  `"host"`,因为 token meter 服务还在——两件事不要混。
164
+ - `data.hasSpill` 为 `true`(宿主**提供** spill 服务的存在性)。它**不表示可用**:服务在但
165
+ 没有 `saveText` 时仍是 `true`,`degraded` 会带 `ERR_HOST_SPILL_UNUSABLE`。打开
166
+ `projection: 'on'` 前要同时看这两个字段;只看 `hasSpill` 会把一个不可用的后端当成可用。
155
167
  - `data.counts` 一开始通常为空——但**控制调用自己也计数**:可见工作区为空时,`boost`
156
168
  自己的调用同样要过 post-execute 的 scope 门(那里没有 boost 豁免,豁免只在工具注册层),
157
169
  每条记一次 `skip:no-scope`。正常工具调用后会累积,例如出现 `projection-shadow` 条目。
@@ -187,18 +199,28 @@ scope**:`boost` 工具 schema(399)只要插件装配就常驻——`boost`
187
199
  ## 影子周
188
200
 
189
201
  设计选择**影子优先**:先用一周只记账(不合成回合、不跳过调用,投影只记账不改内容),再决定
190
- 是否真的投影与替换。**「什么都不改」并不成立**:只要有可见工作区,协议段(379 token)就会
191
- 注入系统提示;多候选计划仍会**真实调用一次选择器**(一次独立的辅助模型请求)。影子周按设计
192
- 零节省,它只产出下一节的四个比例。
193
-
194
- 其中 `saveableRatio`、`byFamily`、`candidateRecall` 能决定的是**替换侧是否值得打开**:
195
- 白名单能兑现多少替换决策、命中落在哪些工具族、候选集召回多高——也就是替换打开后会不会
196
- 真的触发、主要落在哪些族。它们**不能决定发布**:v1 按正常版本发布,不把影子期收益当发布
197
- 门;这个决定是**实现者在设计阶段做的,不是用户裁决**——用户只接受了为期一周的影子期,没有
198
- 裁定影子结果是否该当发布门。它们也**不能测出节省**:报告没有总 token 分母,
199
- `retrievalUpperBound` 在影子期结构性为 `0`(它只统计 `projection:'on'` 的已应用投影取回),
200
- 连投影的取回损害都约束不了;投影的放行依据是可见性契约(原文可经页脚取回)与事后检测,
201
- 不是影子标签。
202
+ 是否真的投影与替换。**「什么都不改」并不成立**:`boost` 工具 schema(399 token)只要插件装配
203
+ 就常驻;只要有可见工作区,协议段(379 token)还会注入系统提示——推荐配置下每请求固定成本
204
+ **778**;多候选计划仍会**真实调用一次选择器**(一次独立的辅助模型请求)。影子周不省任何
205
+ token,它只产出下一节的四个比例;`selected + []` 下协议段为空,固定成本仍有 **399**。
206
+
207
+ 其中 `saveableRatio`、`byFamily`、`candidateRecall` 提供的是**替换侧的标签,不单独决定
208
+ 是否开启替换**:白名单能兑现多少替换决策、命中落在哪些工具族、提交产出率多高——也就是
209
+ 替换打开后会不会真的触发、主要落在哪些族。报告**没有总 token 分母**,所以这些标签判断不了
210
+ 净收益;它们也**不能决定发布**:v1 按正常版本发布,不把影子期收益当发布门;这个决定是
211
+ **实现者在设计阶段做的,不是用户裁决**——用户只接受了为期一周的影子期,没有裁定影子结果
212
+ 是否该当发布门。它们也**不能测出节省**:`retrievalUpperBound` 在影子期结构性为 `0`(它只
213
+ 统计 `projection:'on'` 的已应用投影取回),连投影的取回损害都约束不了。投影的放行依据只有
214
+ 可见性契约(原文可经页脚取回),不是影子标签,也**不是事后检测**:v1 没有误截检测器——
215
+ `src/admission/retrieval.ts` 只按精确 locator 统计取回次数,设计稿 §6.1 也写明损害度量未
216
+ 交付、取回计数不是损害上界。唯一的护栏是模型能取回原文;而「发生过取回」只是信号,不是
217
+ 「没有误截」的证明。
218
+
219
+ **全零周不能区分两件事。** 如果模型整周没有写 `<CHISEL_PLAN>`,就没有任何决策收据,
220
+ 四个比例全是 `0`;这与「没有可省项」在报告里长得一模一样——报告不测 plan 发射率。看到
221
+ 全零时先查收据里有没有替换决策(`kind:'shadow'` / `kind:'skip'`),不要直接读成
222
+ 「插件没有效果」。
223
+
202
224
  `scope.json` 里有两个独立开关:
203
225
 
204
226
  | 开关 | 取值 | 行为 |
@@ -218,17 +240,21 @@ scope**:`boost` 工具 schema(399)只要插件装配就常驻——`boost`
218
240
  `~/.dsh`)。这个脚本是 dev-only,不在 npm tarball 里。它输出四个标签:
219
241
  `saveableRatio`(白名单能兑现的替换占比 = `whitelisted` 影子提交 / **全部**替换决策——分母
220
242
  是每一次替换决策,不只是白名单调用;影子期全族记账,bash/ssh 的潜力看 `byFamily`)、`byFamily`(按候选工具族的命中率)、
221
- `candidateRecall`(候选集召回)、`retrievalUpperBound`(取回率上界;影子期没有真正投影,
222
- 结构上恒为 `0`)。
223
- 3. **打开投影**:投影的放行不靠影子标签(依据是可见性契约与事后检测),确认宿主 spill
224
- 后端可用后,保持 `shadow: true`,把 `projection` 改成 `'on'`:
243
+ `candidateRecall`(**提交产出率,不是候选集召回**:`commits / (commits + noCandidate)`;
244
+ 脚本从不拿候选集去比对模型实际的下一调,所以它回答「有候选的决策里多少提交了」,不回答
245
+ 「候选集漏没漏掉模型真正要做的调用」)、`retrievalUpperBound`(**已观测取回率的下界,不是
246
+ 取回损害的上界**;影子期没有真正投影,结构上恒为 `0`)。
247
+ 3. **打开投影**:投影的放行不靠影子标签(依据是可见性契约:原文可经页脚取回;v1 没有
248
+ 误截检测器)。先确认 `status.data.hasSpill` 为 `true` **且** `degraded` 不含
249
+ `ERR_HOST_SPILL_UNUSABLE`——前者只证明宿主**提供**服务,后者才说明服务可用;再保持
250
+ `shadow: true`,把 `projection` 改成 `'on'`:
225
251
 
226
252
  ```json
227
253
  { "cmd": "scope-set", "body": { "projection": "on" }, "baseRevision": 1 }
228
254
  ```
229
255
 
230
256
  `scope-set` 只覆盖你传入的字段,其余保持不变。此时回执开始真正被替换,但替换决策仍然只记账。
231
- 4. **再打开替换**:影子报告显示白名单命中与候选召回可接受时,直接把影子关掉——**先检查再关
257
+ 4. **再打开替换**:影子报告显示白名单命中与提交产出率可接受时,直接把影子关掉——**先检查再关
232
258
  是无效顺序**:影子期从不合成回合,`content[].thinking` 的 400 在结构上不可能出现,
233
259
  关影子之前检查它永远只能读到「未见」。
234
260
  把 `shadow` 设为 `false` 之后,按 [docs/RELEASE.md](docs/RELEASE.md) §4 在**第一个真正
@@ -260,7 +286,7 @@ scope**:`boost` 工具 schema(399)只要插件装配就常驻——`boost`
260
286
  | `projection.glob.*` | 700 / 400 / 100 | `glob` 窗口 |
261
287
  | `projection.bash.*` | 4000 / 2000 / 500 | `bash` 窗口 |
262
288
  | `projection.ssh.*` | 2000 / 1200 / 300 | `mcp__ssh__*`(如 `mcp__ssh__execute-command`)窗口 |
263
- | `admission.thresholdTokens` | 1024 | 每个候选进入替换所需的最小净节省;唯一候选的确定性提交豁免 |
289
+ | `admission.thresholdTokens` | 1024 | 每个候选进入替换所需的最小净节省;**单步计划豁免**(`plan.steps.length === 1`,`src/hooks/post-execute.ts` 的 `admittedFor`)——计划只有一步时没有选择器可付,阈值不适用。不是「确定性 && 唯一候选」:多步计划即使只剩一个候选,仍要过阈值(`src/admission/ledger.ts` 的 `worthSubstituting`) |
264
290
  | `selector.maxTokens` | 512 | 多候选选择器的输出预算(输入 + 输出上界从节省里扣) |
265
291
  | `stepsPerTurn` | 8 | 每个 turn 的替换步数上限 |
266
292
  | `horizonSteps` | 20 | 算不出会话历史均值时的剩余步数 horizon |
@@ -272,7 +298,7 @@ scope**:`boost` 工具 schema(399)只要插件装配就常驻——`boost`
272
298
  不变量不是 `triggerChars ≥ headChars + tailChars + 1`。真实替换串是 head line + head + 页脚 +
273
299
  tail + 3 个换行;页脚由宿主 `formatSpillNotice` 生成:68 字符 locator 加宿主固定的 66 字符
274
300
  retrieval hint 下,3 位省略字节数是 190 字符,5 位是 192 字符。grep/glob 默认 400+100 时:
275
- `400 + 100 + 50(head line) + 190(页脚) + 3 = 743 > 700`(5 位计数则是 745)。于是刚过 700、
301
+ `400 + 100 + 50(head line) + 190(页脚) + 3 = 743 > 700`(5 位计数时页脚 192、head line 里的数字也各长一位,实测 747–749)。于是刚过 700、
276
302
  约 743 以下的回执会被 `truncate` 判定“可裁”,但 `projectApply` 组装后并不短于原文,直接返回
277
303
  原文——这是死区,不是净亏。运行时的 `assembled.length >= text.length` 检查保证投影绝不会让
278
304
  回执变长;要消除死区,把 `triggerChars` 提到至少这个和(例如 grep/glob 用 800),或缩小窗口。
@@ -328,8 +354,10 @@ plugin manager 才能把运行中的 entry 认成本包的行、通过 profile p
328
354
  - `scope.json`——暴露面的唯一事实来源(version 2,带 revision)。
329
355
  - `scope.lock`——写路径的短锁,正常写入结束后删除。
330
356
  - `receipts/<encoded-session>.jsonl`——追加式收据。**收据按“决定”写,不是每次调用都写**:
331
- 只有发生投影、替换决策(含 skip)或越界 `skip:no-scope` 时才落一行;一个没有计划的
332
- `write` / `edit` 不产生任何收据,它的参数不会被记录。每行携带元数据、回执前 256 个码点的
357
+ 只有发生投影、替换决策(含 skip)、待发替换因外部改写被放弃(`kind:'reset'`,`code` 为
358
+ `pruned-reset` / `compaction-reset`)或越界 `skip:no-scope` 时才落一行;一个没有计划的
359
+ `write` / `edit` 不产生任何收据,它的参数不会被记录。除 `kind:'reset'` 与
360
+ `appendSkipNoScope` 写出的 `skip:no-scope` 外,每行携带元数据、回执前 256 个码点的
333
361
  preview(不存 stdout 全文)和该调用的绑定参数 `args`(模型所写:超过 2048 个码点时以
334
362
  `args_truncated` 标记的截断 JSON 落盘;嵌套超过 64 层时以 `args_depth_truncated` 标记,
335
363
  并把更深的子树换成 `{ "truncated_depth": 64 }`)。**只有替换类收据**另外携带计划 goal
@@ -343,7 +371,9 @@ plugin manager 才能把运行中的 entry 认成本包的行、通过 profile p
343
371
  (`kind:'projection'`、`code:'projection-retrieval'`)带 `locator` 与
344
372
  `retrieval_call_tokens` / `retrieval_content_tokens` / `retrieval_tokens`;三个取回字段
345
373
  只在这次取回被定价时写入,未定价时 `estimate` 为 `'unknown'`、字段省略。`skip` 收据只有
346
- preview 与 args(`skip:no-scope` 连这两个都没有,只记工具名)。
374
+ preview 与 args(`skip:no-scope` 分两条路径:走 `appendSkipNoScope` 的分支——无 agent、
375
+ 无 session id、会话已不活跃——只记工具名;运行中途可见性翻转的 `ledgerEntry` 分支仍带
376
+ preview 与 args)。
347
377
 
348
378
  当前分片超过 8 MiB 或 20,000 行时,下一次写入前轮转为 `<encoded-session>.1.jsonl`;只保留
349
379
  当前分片和它的前一份(旧的 `.1` 被覆盖)。`boost status` 先读 `.1` 再读当前分片。256 分片
@@ -366,11 +396,19 @@ horizon 重放,并计入 `projection_horizon_reestimated`;`projection_horizo
366
396
  - `projection_unknown_families`:带 `mcp__` 前缀、进入投影阶段但没有匹配到工具族的调用数;
367
397
  `projection_unknown_tools` 是其中保留的未映射工具名及次数(最多 32 个),用来发现 mapper
368
398
  缺口。
369
- - `hasWorkspaceRegistry`:宿主当前是否提供 `workspaceRegistry`;没有探测到时该键**省略**,
370
- 不是 `false`。
371
- - `saved`:兼容旧消费者的 camelCase 账目对象(`substitution` / `projectionGross` /
372
- `projectionNet` / `retrievals`),与顶层 snake_case 字段由同一次聚合派生。旧投影收据
373
- (pre-T23b)没有 `saved_projection_tokens` 时,按收据里的 legacy `saved` 字段回退计价。
399
+ - `hasWorkspaceRegistry`:宿主是否**提供** `workspaceRegistry`(同样是存在性)。生产装配总是传入
400
+ 这个键,所以它**总是布尔**:宿主没有该服务是 `false` + `ERR_HOST_NO_WORKSPACE_REGISTRY`;服务在但
401
+ `list()` 抛错是 `true` + `ERR_HOST_WORKSPACE_REGISTRY_BROKEN`——两种都让每个会话被判不可见,但
402
+ 修法不同。只有直接构造 `boost` 依赖、完全不给宿主事实时该键才省略(测试场景)。
403
+ - `hasSpill`:宿主是否**提供** spill 后端(存在性,不是可用性)。服务缺失是 `false` +
404
+ `ERR_HOST_NO_SPILL`;服务在但不提供 `saveText` 时它**仍是 `true`**,同时 `degraded` 带
405
+ `ERR_HOST_SPILL_UNUSABLE`——能力事实在 `degraded` 里,不在这个布尔里。
406
+ - `saved`:兼容旧消费者的 camelCase 账目对象(`substitution` / `substitutionAvoided` /
407
+ `projectionGross` / `projectionNet` / `retrievals`),与顶层 snake_case 字段由同一次聚合派生。
408
+ 旧投影收据(pre-T23b)没有 `saved_projection_tokens` 时,按收据里的 legacy `saved` 字段回退计价。
409
+ **两个替换数是一对区间,不是同一个量**:`substitution` 取被跳过请求的**下一**个真实请求的输入
410
+ (含被替换调用自己的结果,所以是**上界**);`substitutionAvoided` 取计划那一次请求的
411
+ `input + cacheRead + output`(不含被替换调用的结果,所以是**下界**)。真实节省落在两者之间。
374
412
 
375
413
  `projection: 'on'` 时,完整原文在替换发生**之前**写入宿主的 spill 后端,页脚 locator 可以用
376
414
  `read` / `grep` 取回。投影不会丢掉唯一副本;spill 写入失败就不替换(收据记
@@ -407,7 +445,7 @@ horizon 重放,并计入 `projection_horizon_reestimated`;`projection_horizo
407
445
 
408
446
  ## 宿主依赖
409
447
 
410
- `inject` 是硬依赖:`tools`、`systemPrompt`——缺任一,插件加载失败。`llm` 是软依赖(只有
448
+ `inject` 是硬依赖:`tools`、`systemPrompt`——缺任一,cordis 让插件停在 pending、不 apply(不是抛错,但对使用者而言效果相同:插件不工作)。`llm` 是软依赖(只有
411
449
  选择器用),缺失时选择器以 `selector-unavailable` 退回,投影与替换的其余部分照常。
412
450
 
413
451
  | 依赖 | 形态 | 缺失时 |
@@ -419,7 +457,7 @@ horizon 重放,并计入 `projection_horizon_reestimated`;`projection_horizo
419
457
  | (spill 后端存在但写失败) | — | 每次 `saveText` 被拒:收据 `projection-skipped:spill-failed`,`status.degraded` 带 **`ERR_HOST_SPILL_FAILING`**。这是**第三种**状态,既不是「没有后端」也不是「没有页脚渲染器」——让操作者去「恢复 spill 包」会把一个已装好却报错的包当成没装 |
420
458
  | `@deepseek-ai/dsh-token-meter/estimate` | 软(动态 import) | 固定开销无法测量,`fixedOverheadTokens` 为 `'unknown'`;`status.degraded` 带 `ERR_HOST_NO_ESTIMATOR` |
421
459
  | `win32` 平台 | 运行时检查 `isPosixOnly()` | 拒绝替换,投影照常;`status.degraded` 带 `ERR_HOST_PLATFORM_UNSUPPORTED` |
422
- | 宿主版本线 | 启动时读 `@deepseek-ai/dsh-app-boot` 的版本 | 不是 `0.2.2-rc.4` 时日志警告 `ERR_HOST_VERSION_MISMATCH`,插件照常加载(advisory,不是 `status.degraded` 码);版本读不到时只记 info,不发码 |
460
+ | 宿主版本线 | 启动时读 `@deepseek-ai/dsh-app-boot` 的版本 | 版本**落在 `engines.dsh` 区间外**(`>=0.2.2-rc.4 <0.2.3-0`)时日志警告 `ERR_HOST_VERSION_MISMATCH`,插件照常加载(advisory,不是 `status.degraded` 码);区间内但不是验证过的 `0.2.2-rc.4`(如 `rc.5` / `0.2.2`)只记 info、不发码;版本读不到或区间无法解析时也只记 info |
423
461
  | 收据分片可读性 | `boost status` 全量扫描(非依赖) | 至少一个收据分片读不出来(EACCES、名为 `x.jsonl` 的目录等)时 `status.degraded` 带 `ERR_RECEIPTS_UNREADABLE`;`status` 仍是**全量聚合**——健康分片照常计数——所以数字可能不完整。查 `<dshHome>/boost/receipts/` 的权限与异常条目,修复后重跑并对比计数 |
424
462
  | 收据分片数量 | `boost status` 全量扫描(非依赖) | 分片超过 256 个时 `status` 只统计按编码名排序的前 256 个,`status.degraded` 带 `ERR_RECEIPTS_TRUNCATED`,所有计数因此是**下界**;分片永不自动删除,可归档/移走旧会话分片后重跑 `status` |
425
463
  | 提示段装配瀑布 | 出站请求探测(非依赖) | 宿主的 `complete: true` 提示段在装配瀑布之后替换了整个系统提示、协议段没有到达请求时,`status.degraded` 带 `ERR_HOST_COMPLETE_SECTION`;受影响请求上替换与投影 fail-closed(工作区明明可见插件却不动作)。找出宿主里覆盖瀑布的 complete 段(通常属于另一个插件)并移除,或接受这些请求上不动作 |
@@ -450,17 +488,31 @@ spill,报它只会制造噪音);但**收据通道**不看当前模式—
450
488
  ## v1 的边界
451
489
 
452
490
  - 只做两件事:**就地替换工具回执**,以及**替换只读调用**(`read` / `grep` / `glob`)。
453
- - **不批量执行工具调用**(没有 PTC / `run_code`):这不是 v1 自行划定的范围,而是原始需求
454
- 2.1 被**收窄**后的结果——原需求要一次调用多个工具,裁决为显式排除、二期再议(见
455
- [澄清记录](docs/superpowers/clarifications/2026-11-18-dsh-token-efficiency.md) 的 2.1 与
456
- 「用户裁决」第 9 条;设计 N1)。
491
+ - **不批量执行工具调用**(没有 PTC / `run_code`):这是原始需求 2.1 的**收窄**,也是**实现者
492
+ 的范围决定(E2)**,不是用户裁决——**没有用户消息追认这条收窄**。收窄的理由是范围,不是
493
+ 「批量派发已被证明没有价值」:每步恰好 1 个工具占 79.8%,但 **20.2% 的步不是单工具步**——
494
+ 16.9% 带 ≥2 个调用、3.3% 零调用(`clarifications:17`);用户明确要求批量派发,非单工具步
495
+ 正是它的作用面。PTC 留二期,重启条件是影子期拿到批量步的真实占比与收益标签,而不是
496
+ 「79.8% 已证明不需要批量」(见[澄清记录](docs/superpowers/clarifications/2026-11-18-dsh-token-efficiency.md)
497
+ 的 2.1 与 E2;设计 N1)。
498
+ - **不回答「工具调用顺序由谁定」**:原始需求 2.3 要求调研组合工具的顺序(Jev 决策还是主模型
499
+ 一开始定好),v1 **没有交付这项调研**——这是开放缺口,**不被 PTC 的推迟覆盖**。v1 的实现是
500
+ 主模型逐步决定下一次调用,Jev 只在已声明候选里选一个、无权加步骤或改序;研究里
501
+ ReWOO / LLMCompiler 的「先声明计划、步骤间不再问模型」证据没有应用到定序权威上,也没有
502
+ 对比实验(`clarifications:19`、设计 §9)。
457
503
  - **不去重、不合并工具调用**(设计 N5)——这条完全没开工,且 v1 **没有任何工具能测出重复
458
504
  调用率**:设计稿里用来触发重启判定的「影子周重复率统计」没有交付,`shadow-report.mjs`
459
505
  不产出它。
460
- - **影子周按设计零节省**:只记账(协议段照注入、选择器照调用),它的产出是四个比例,
461
- 不是省下的 token。
462
- - **v1 不评判「结果更好」**:只有 token 账目和一套**人工**的 20 任务回退流程(任务集不随包发布,见 `docs/RELEASE.md` §3),没有任何质量指标;「替换后
463
- 结果质量」在 v1 是不可判的。
506
+ - **HarnessMM 只移植了四件**:扁平候选银行、GDR 守卫、CCS 单候选提交、闭集选择器(Jev)。
507
+ **EDG 的图/链(`predecessor_id`)没有移植**——本插件的计划是扁平、每回执一次性的候选列表,
508
+ 源码里没有 `predecessor_id`;**RSI 循环也没有移植**——v1 是固定策略插件,没有训练/选择
509
+ 生命周期(`clarifications:16`)。
510
+ - **影子周不省 token**:只记账(协议段照注入、选择器照调用),推荐配置下每请求仍固定花
511
+ 778(`selected + []` 为 399);它的产出是四个比例,不是省下的 token。
512
+ - **v1 不评判「结果更好」**:只有 token 账目和一套**人工**的 20 任务回退流程(任务集不随包发布,
513
+ 见 `docs/RELEASE.md` §3),没有任何质量指标;「替换后结果质量」在 v1 是不可判的。这套流程
514
+ 本身也没交付完整:冒烟 runner(`test/regression/run.mjs`)与同一节的取回完整性检查都未实现,
515
+ `test/regression/` 只有 `.gitkeep`,因此 pass 谓词里的「无数据丢失」不变量在 v1 **未经核实**。
464
516
  - **投影是截断,不是精炼**:它保留头尾、丢掉中段;账本里的 before/after token 差量的是
465
517
  「变短」,不是「变相关」。被丢掉的中段可能正是下一步决策要用的内容——`projection: 'on'`
466
518
  下原文可经页脚 locator 取回,但取回要花一次工具调用,且 v1 没有指标区分「精炼」与
@@ -471,10 +523,11 @@ spill,报它只会制造噪音);但**收据通道**不看当前模式—
471
523
  - 不替换、也不接管 DSH 的压缩、剪枝与 spill 决策(设计 N3);投影只改模型可见 content,
472
524
  原文仍借宿主 spill 存放。
473
525
  - 不做模型训练或权重改动(N2);不追求论文里的 87.93%(N4)。
474
- - 不承诺 10%:3.5% 是事前估算的**下界**,不是保底;10% 是全程存活的理想上界。净保底约
475
- 0.4%(投影侧毛额约 0.8% 减去每请求固定开销约 0.4%)。影子周只回答替换侧是否值得打开
476
- (候选覆盖与命中),不决定发布,也不能把区间换成实测值(`shadow-report.mjs` 只有四个
477
- 比例,没有总 token 分母)。
526
+ - 不承诺 10%:3.5% 是事前估算的**下界**,不是保底;10% 是全程存活的理想上界。投影侧在
527
+ 300 个最长会话上的聚合净额约 0.4%(毛额约 0.8% 减去每请求固定开销约 0.4%),同样是
528
+ 离线估算,**不是每会话保底**(短会话可能倒亏)。影子周只给替换侧的标签(候选覆盖与提交
529
+ 产出率),不单独决定是否开启替换、也不决定发布,更不能把区间换成实测值
530
+ (`shadow-report.mjs` 只有四个比例,没有总 token 分母)。
478
531
 
479
532
  ## 文档
480
533
 
@@ -490,9 +543,10 @@ spill,报它只会制造噪音);但**收据通道**不看当前模式—
490
543
  | [设计稿](docs/superpowers/specs/2026-11-18-dsh-token-efficiency-design.md) | 目标、证据、架构、契约、度量、风险、发布形态 |
491
544
  | [宿主契约附录](docs/superpowers/plans/2026-11-18-host-contracts.md) | 逐条抄自宿主源码的接口准绳 |
492
545
  | [三层委派研究](docs/research/2026-11-18-three-tier-delegation.md) | 缓存、路由阈值、压缩、校验的 25 条一手来源 |
493
- | [发布验收](docs/RELEASE.md) | `npm run verify:package` 一条命令验收、零 peerDependencies 现状与安装规格、降级码矩阵、20 任务回退流程(人工,任务集不随包发布)、影子周与统计复算 |
546
+ | [发布验收](docs/RELEASE.md) | `npm run verify:package` 一条命令验收、零 peerDependencies 现状与安装规格、降级码矩阵、20 任务回退流程(人工;任务集、runner 与取回完整性检查均未交付)、影子周与统计复算 |
494
547
 
495
548
  ## 许可证
496
549
 
497
- Apache-2.0。机制移植自 [HarnessMM](https://github.com/YuhuaJiang2002/HarnessMM)(Apache-2.0),
498
- 随包分发 `NOTICE`。
550
+ Apache-2.0。机制移植自 [HarnessMM](https://github.com/YuhuaJiang2002/HarnessMM)(Apache-2.0):
551
+ 扁平候选银行、GDR 守卫、CCS 单候选提交与闭集选择器;**EDG 的图/链(`predecessor_id`)与
552
+ RSI 循环没有移植**。随包分发 `NOTICE`。
@@ -9,6 +9,14 @@
9
9
  * next request is `'unknown'`; an interpolated number would be indistinguishable
10
10
  * from a measurement once written to a receipt.
11
11
  *
12
+ * That next request is not the avoided request: it also carries the executed
13
+ * call and its result, which the avoided request would not have seen. So
14
+ * `saved_input_tokens` is an **upper** estimate. `settle()` therefore also
15
+ * reports `avoided_total_tokens = before.input + before.cacheRead +
16
+ * before.output` — the whole request that produced the plan, which the avoided
17
+ * request would have carried (plus the plan) — as a **lower** estimate. Each
18
+ * side is `'unknown'` from its own sample, never a copy of the other's.
19
+ *
12
20
  * The ledger keeps two request slots plus a mark: `latest`, the first request
13
21
  * after the mark, and the mark itself — which holds the request that preceded
14
22
  * it and the candidate id. No whole-history table (YAGNI). Pure arithmetic: no
@@ -91,12 +99,25 @@ export class UsageLedger {
91
99
  /**
92
100
  * Consume the mark and report the substitution's measured cost.
93
101
  *
94
- * `saved_input_tokens` is the first after-mark request's `input + cacheRead`;
95
- * `output_tokens` is that request's `output`, a third count that is never
96
- * folded into input. Both are `'unknown'` when no usable request arrived after
97
- * the mark — never a copy of the previous request's numbers. `cache_hit_delta`
98
- * is the after-mark hit rate minus the pre-mark hit rate, `null` when either
99
- * side cannot be told (a `null` delta means "cannot tell", not zero).
102
+ * Two estimates of the avoided request, from the same pair of samples:
103
+ *
104
+ * - `saved_input_tokens` is the first after-mark request's `input +
105
+ * cacheRead`. That request is the next real one, so its input also carries
106
+ * the executed call and its result — tokens the avoided request would never
107
+ * have seen. It is therefore the **upper** estimate of the avoided input,
108
+ * and the plugin's headline number.
109
+ * - `avoided_total_tokens` is the pre-mark request's `input + cacheRead +
110
+ * output`: the whole request that produced the plan. The avoided request
111
+ * would have carried that request's context plus the plan, so this is a
112
+ * **lower** estimate of the avoided total. It includes output, hence
113
+ * "total", never "input".
114
+ *
115
+ * Each side is `'unknown'` when its own sample is missing or unusable —
116
+ * never a copy of the other request's numbers. `output_tokens` is the
117
+ * after-mark request's `output`, a third count never folded into either
118
+ * estimate. `cache_hit_delta` is the after-mark hit rate minus the pre-mark
119
+ * hit rate, `null` when either side cannot be told (a `null` delta means
120
+ * "cannot tell", not zero).
100
121
  *
101
122
  * A second `settle()` has nothing left to consume and reports the same
102
123
  * `'unknown'` / `null`.
@@ -108,14 +129,37 @@ export class UsageLedger {
108
129
  this.beforeMark = undefined;
109
130
  this.afterMark = undefined;
110
131
  this.candidateId = undefined;
132
+ // The lower estimate depends only on the pre-mark sample: a settlement
133
+ // with no after-mark request still knows how much that request would have
134
+ // had to replay, and reporting it cannot overstate anything.
135
+ const avoided = before !== undefined && usable(before)
136
+ ? before.input + before.cacheRead + before.output
137
+ : undefined;
138
+ const avoidedTotal = avoided !== undefined && Number.isFinite(avoided) ? avoided : 'unknown';
111
139
  if (after === undefined || !usable(after)) {
112
- return { saved_input_tokens: 'unknown', cache_hit_delta: null, output_tokens: 'unknown' };
140
+ return {
141
+ // No after-sample means no ceiling; the floor stands alone and the
142
+ // status sum ignores it unless a ceiling exists for the same receipt.
143
+ saved_input_tokens: 'unknown',
144
+ avoided_total_tokens: avoidedTotal,
145
+ cache_hit_delta: null,
146
+ output_tokens: 'unknown',
147
+ };
113
148
  }
114
149
  const afterRate = hitRate(after);
115
150
  const beforeRate = hitRate(before);
116
151
  const delta = afterRate !== null && beforeRate !== null ? afterRate - beforeRate : null;
152
+ // The two figures bound different quantities (the skipped step's total vs
153
+ // the next request's input), so a context that *shrank* between the samples
154
+ // — a compaction, a rebuilt request, an adapter that does not replay the
155
+ // whole turn — can push the lower above the upper. A range whose floor is
156
+ // above its ceiling is not a range: drop the floor rather than print it
157
+ // (review cod#1).
158
+ const upper = after.input + after.cacheRead;
159
+ const bounded = avoidedTotal === 'unknown' || avoidedTotal <= upper ? avoidedTotal : 'unknown';
117
160
  return {
118
- saved_input_tokens: after.input + after.cacheRead,
161
+ saved_input_tokens: upper,
162
+ avoided_total_tokens: bounded,
119
163
  cache_hit_delta: delta !== null && Number.isFinite(delta) ? delta : null,
120
164
  output_tokens: after.output,
121
165
  };
@@ -1 +1 @@
1
- {"version":3,"file":"usage.js","sourceRoot":"","sources":["../../src/admission/usage.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AASH;;;;;;;GAOG;AACH,SAAS,MAAM,CAAC,CAAQ;IACtB,OAAO,CACL,CAAC,CAAC,CAAC,KAAK,EAAE,CAAC,CAAC,SAAS,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QAC3E,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAC,KAAK,GAAG,CAAC,CAAC,SAA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,MAAM;QAKJ,MAAM,KAAK,GAAG,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,SAAS,CAAA;QACvD,MAAM,MAAM,GAAG,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,CAAC,SAAS,CAAA;QACzD,IAAI,CAAC,OAAO,GAAG,KAAK,CAAA;QACpB,IAAI,CAAC,UAAU,GAAG,SAAS,CAAA;QAC3B,IAAI,CAAC,SAAS,GAAG,SAAS,CAAA;QAC1B,IAAI,CAAC,WAAW,GAAG,SAAS,CAAA;QAE5B,IAAI,KAAK,KAAK,SAAS,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC;YAC1C,OAAO,EAAE,kBAAkB,EAAE,SAAS,EAAE,eAAe,EAAE,IAAI,EAAE,aAAa,EAAE,SAAS,EAAE,CAAA;QAC3F,CAAC;QAED,MAAM,SAAS,GAAG,OAAO,CAAC,KAAK,CAAC,CAAA;QAChC,MAAM,UAAU,GAAG,OAAO,CAAC,MAAM,CAAC,CAAA;QAClC,MAAM,KAAK,GAAG,SAAS,KAAK,IAAI,IAAI,UAAU,KAAK,IAAI,CAAC,CAAC,CAAC,SAAS,GAAG,UAAU,CAAC,CAAC,CAAC,IAAI,CAAA;QAEvF,OAAO;YACL,kBAAkB,EAAE,KAAK,CAAC,KAAK,GAAG,KAAK,CAAC,SAAS;YACjD,eAAe,EAAE,KAAK,KAAK,IAAI,IAAI,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI;YACxE,aAAa,EAAE,KAAK,CAAC,MAAM;SAC5B,CAAA;IACH,CAAC;CACF","sourcesContent":["/**\n * Usage pairing: turn two consecutive model requests into the measured saving\n * of one substitution (design §5.3).\n *\n * When the plugin substitutes a call, the model is not asked for that step, so\n * the next real request replays a shorter history. The saving is therefore\n * measured as the size of that next request — `input + cacheRead`, because the\n * host reports `inputTokens` excluding cache reads — never estimated. A missing\n * next request is `'unknown'`; an interpolated number would be indistinguishable\n * from a measurement once written to a receipt.\n *\n * The ledger keeps two request slots plus a mark: `latest`, the first request\n * after the mark, and the mark itself — which holds the request that preceded\n * it and the candidate id. No whole-history table (YAGNI). Pure arithmetic: no\n * timers, no I/O, no host calls.\n *\n * @module dsh-boost/admission/usage\n */\n\n/** One model request's raw counts, mapped from the `llm/stream` usage chunk. */\nexport interface Usage {\n input: number\n cacheRead: number\n output: number\n}\n\n/**\n * A sample is usable only when all three counts are finite and non-negative\n * and their input total does not overflow. A negative or non-finite count is a\n * protocol violation, and any arithmetic on it would invent `NaN` or\n * `Infinity` — a bogus number no receipt reader could tell from a measurement.\n * An unusable after-mark sample makes the whole settlement unusable; an\n * unusable pre-mark sample only loses the delta.\n */\nfunction usable(u: Usage): boolean {\n return (\n [u.input, u.cacheRead, u.output].every((n) => Number.isFinite(n) && n >= 0) &&\n Number.isFinite(u.input + u.cacheRead)\n )\n}\n\n/**\n * Cache hit rate of one request, `cacheRead / (input + cacheRead)`. `null`\n * when the rate cannot be told: no sample, an unusable sample, or a\n * non-positive denominator. Both sides of the delta go through this one\n * helper so they cannot drift.\n */\nfunction hitRate(u: Usage | undefined): number | null {\n if (u === undefined || !usable(u)) return null\n const denominator = u.input + u.cacheRead\n if (denominator <= 0) return null\n const rate = u.cacheRead / denominator\n return Number.isFinite(rate) ? rate : null\n}\n\n/**\n * Pairs two consecutive model requests around one substitution.\n *\n * The pairing target is the FIRST request after the mark, never the latest:\n * when a caller forgets to settle, a later unrelated request must not be\n * attributed to the substitution. `settle()` consumes the mark and clears the\n * pairing slots; `last()` is a pure reader and survives it.\n */\nexport class UsageLedger {\n private latest: Usage | undefined\n private hasMark = false\n private beforeMark: Usage | undefined\n private afterMark: Usage | undefined\n private candidateId: string | undefined\n\n /**\n * Record one real request. The first request after a mark claims the pairing\n * slot and keeps it; later requests only advance `last()`.\n */\n request(u: Usage): void {\n this.latest = u\n if (this.hasMark && this.afterMark === undefined) this.afterMark = u\n }\n\n /** Most recent request, or `undefined` before the first one. Never consumes. */\n last(): Usage | undefined {\n return this.latest\n }\n\n /**\n * Record that a substitution just happened.\n *\n * `candidateId` is kept only so the caller can pair `settle()` with the right\n * substitution receipt (`pendingCandidateId()`); it never changes the\n * arithmetic. A new mark discards any unconsumed pairing and starts over from\n * the current latest request.\n */\n markSubstituted(candidateId: string): void {\n this.hasMark = true\n this.beforeMark = this.latest\n this.afterMark = undefined\n this.candidateId = candidateId\n }\n\n /** Id of the pending mark, or `undefined` before a mark and after `settle()`. */\n pendingCandidateId(): string | undefined {\n return this.candidateId\n }\n\n /**\n * Consume the mark and report the substitution's measured cost.\n *\n * `saved_input_tokens` is the first after-mark request's `input + cacheRead`;\n * `output_tokens` is that request's `output`, a third count that is never\n * folded into input. Both are `'unknown'` when no usable request arrived after\n * the mark — never a copy of the previous request's numbers. `cache_hit_delta`\n * is the after-mark hit rate minus the pre-mark hit rate, `null` when either\n * side cannot be told (a `null` delta means \"cannot tell\", not zero).\n *\n * A second `settle()` has nothing left to consume and reports the same\n * `'unknown'` / `null`.\n */\n settle(): {\n saved_input_tokens: number | 'unknown'\n cache_hit_delta: number | null\n output_tokens: number | 'unknown'\n } {\n const after = this.hasMark ? this.afterMark : undefined\n const before = this.hasMark ? this.beforeMark : undefined\n this.hasMark = false\n this.beforeMark = undefined\n this.afterMark = undefined\n this.candidateId = undefined\n\n if (after === undefined || !usable(after)) {\n return { saved_input_tokens: 'unknown', cache_hit_delta: null, output_tokens: 'unknown' }\n }\n\n const afterRate = hitRate(after)\n const beforeRate = hitRate(before)\n const delta = afterRate !== null && beforeRate !== null ? afterRate - beforeRate : null\n\n return {\n saved_input_tokens: after.input + after.cacheRead,\n cache_hit_delta: delta !== null && Number.isFinite(delta) ? delta : null,\n output_tokens: after.output,\n }\n }\n}"]}
1
+ {"version":3,"file":"usage.js","sourceRoot":"","sources":["../../src/admission/usage.ts"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,CAAC,EAAE,CAAC;YAC1C,OAAO;gBACL,mEAAmE;gBACnE,sEAAsE;gBACtE,kBAAkB,EAAE,SAAS;gBAC7B,oBAAoB,EAAE,YAAY;gBAClC,eAAe,EAAE,IAAI;gBACrB,aAAa,EAAE,SAAS;aACzB,CAAA;QACH,CAAC;QAED,MAAM,SAAS,GAAG,OAAO,CAAC,KAAK,CAAC,CAAA;QAChC,MAAM,UAAU,GAAG,OAAO,CAAC,MAAM,CAAC,CAAA;QAClC,MAAM,KAAK,GAAG,SAAS,KAAK,IAAI,IAAI,UAAU,KAAK,IAAI,CAAC,CAAC,CAAC,SAAS,GAAG,UAAU,CAAC,CAAC,CAAC,IAAI,CAAA;QAEvF,0EAA0E;QAC1E,4EAA4E;QAC5E,yEAAyE;QACzE,0EAA0E;QAC1E,wEAAwE;QACxE,kBAAkB;QAClB,MAAM,KAAK,GAAG,KAAK,CAAC,KAAK,GAAG,KAAK,CAAC,SAAS,CAAA;QAC3C,MAAM,OAAO,GAAG,YAAY,KAAK,SAAS,IAAI,YAAY,IAAI,KAAK,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC,CAAE,SAAmB,CAAA;QAEzG,OAAO;YACL,kBAAkB,EAAE,KAAK;YACzB,oBAAoB,EAAE,OAAO;YAC7B,eAAe,EAAE,KAAK,KAAK,IAAI,IAAI,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI;YACxE,aAAa,EAAE,KAAK,CAAC,MAAM;SAC5B,CAAA;IACH,CAAC;CACF","sourcesContent":["/**\n * Usage pairing: turn two consecutive model requests into the measured saving\n * of one substitution (design §5.3).\n *\n * When the plugin substitutes a call, the model is not asked for that step, so\n * the next real request replays a shorter history. The saving is therefore\n * measured as the size of that next request — `input + cacheRead`, because the\n * host reports `inputTokens` excluding cache reads — never estimated. A missing\n * next request is `'unknown'`; an interpolated number would be indistinguishable\n * from a measurement once written to a receipt.\n *\n * That next request is not the avoided request: it also carries the executed\n * call and its result, which the avoided request would not have seen. So\n * `saved_input_tokens` is an **upper** estimate. `settle()` therefore also\n * reports `avoided_total_tokens = before.input + before.cacheRead +\n * before.output` — the whole request that produced the plan, which the avoided\n * request would have carried (plus the plan) — as a **lower** estimate. Each\n * side is `'unknown'` from its own sample, never a copy of the other's.\n *\n * The ledger keeps two request slots plus a mark: `latest`, the first request\n * after the mark, and the mark itself — which holds the request that preceded\n * it and the candidate id. No whole-history table (YAGNI). Pure arithmetic: no\n * timers, no I/O, no host calls.\n *\n * @module dsh-boost/admission/usage\n */\n\n/** One model request's raw counts, mapped from the `llm/stream` usage chunk. */\nexport interface Usage {\n input: number\n cacheRead: number\n output: number\n}\n\n/**\n * A sample is usable only when all three counts are finite and non-negative\n * and their input total does not overflow. A negative or non-finite count is a\n * protocol violation, and any arithmetic on it would invent `NaN` or\n * `Infinity` — a bogus number no receipt reader could tell from a measurement.\n * An unusable after-mark sample makes the whole settlement unusable; an\n * unusable pre-mark sample only loses the delta.\n */\nfunction usable(u: Usage): boolean {\n return (\n [u.input, u.cacheRead, u.output].every((n) => Number.isFinite(n) && n >= 0) &&\n Number.isFinite(u.input + u.cacheRead)\n )\n}\n\n/**\n * Cache hit rate of one request, `cacheRead / (input + cacheRead)`. `null`\n * when the rate cannot be told: no sample, an unusable sample, or a\n * non-positive denominator. Both sides of the delta go through this one\n * helper so they cannot drift.\n */\nfunction hitRate(u: Usage | undefined): number | null {\n if (u === undefined || !usable(u)) return null\n const denominator = u.input + u.cacheRead\n if (denominator <= 0) return null\n const rate = u.cacheRead / denominator\n return Number.isFinite(rate) ? rate : null\n}\n\n/**\n * Pairs two consecutive model requests around one substitution.\n *\n * The pairing target is the FIRST request after the mark, never the latest:\n * when a caller forgets to settle, a later unrelated request must not be\n * attributed to the substitution. `settle()` consumes the mark and clears the\n * pairing slots; `last()` is a pure reader and survives it.\n */\nexport class UsageLedger {\n private latest: Usage | undefined\n private hasMark = false\n private beforeMark: Usage | undefined\n private afterMark: Usage | undefined\n private candidateId: string | undefined\n\n /**\n * Record one real request. The first request after a mark claims the pairing\n * slot and keeps it; later requests only advance `last()`.\n */\n request(u: Usage): void {\n this.latest = u\n if (this.hasMark && this.afterMark === undefined) this.afterMark = u\n }\n\n /** Most recent request, or `undefined` before the first one. Never consumes. */\n last(): Usage | undefined {\n return this.latest\n }\n\n /**\n * Record that a substitution just happened.\n *\n * `candidateId` is kept only so the caller can pair `settle()` with the right\n * substitution receipt (`pendingCandidateId()`); it never changes the\n * arithmetic. A new mark discards any unconsumed pairing and starts over from\n * the current latest request.\n */\n markSubstituted(candidateId: string): void {\n this.hasMark = true\n this.beforeMark = this.latest\n this.afterMark = undefined\n this.candidateId = candidateId\n }\n\n /** Id of the pending mark, or `undefined` before a mark and after `settle()`. */\n pendingCandidateId(): string | undefined {\n return this.candidateId\n }\n\n /**\n * Consume the mark and report the substitution's measured cost.\n *\n * Two estimates of the avoided request, from the same pair of samples:\n *\n * - `saved_input_tokens` is the first after-mark request's `input +\n * cacheRead`. That request is the next real one, so its input also carries\n * the executed call and its result — tokens the avoided request would never\n * have seen. It is therefore the **upper** estimate of the avoided input,\n * and the plugin's headline number.\n * - `avoided_total_tokens` is the pre-mark request's `input + cacheRead +\n * output`: the whole request that produced the plan. The avoided request\n * would have carried that request's context plus the plan, so this is a\n * **lower** estimate of the avoided total. It includes output, hence\n * \"total\", never \"input\".\n *\n * Each side is `'unknown'` when its own sample is missing or unusable —\n * never a copy of the other request's numbers. `output_tokens` is the\n * after-mark request's `output`, a third count never folded into either\n * estimate. `cache_hit_delta` is the after-mark hit rate minus the pre-mark\n * hit rate, `null` when either side cannot be told (a `null` delta means\n * \"cannot tell\", not zero).\n *\n * A second `settle()` has nothing left to consume and reports the same\n * `'unknown'` / `null`.\n */\n settle(): {\n saved_input_tokens: number | 'unknown'\n avoided_total_tokens: number | 'unknown'\n cache_hit_delta: number | null\n output_tokens: number | 'unknown'\n } {\n const after = this.hasMark ? this.afterMark : undefined\n const before = this.hasMark ? this.beforeMark : undefined\n this.hasMark = false\n this.beforeMark = undefined\n this.afterMark = undefined\n this.candidateId = undefined\n\n // The lower estimate depends only on the pre-mark sample: a settlement\n // with no after-mark request still knows how much that request would have\n // had to replay, and reporting it cannot overstate anything.\n const avoided =\n before !== undefined && usable(before)\n ? before.input + before.cacheRead + before.output\n : undefined\n const avoidedTotal =\n avoided !== undefined && Number.isFinite(avoided) ? avoided : ('unknown' as const)\n\n if (after === undefined || !usable(after)) {\n return {\n // No after-sample means no ceiling; the floor stands alone and the\n // status sum ignores it unless a ceiling exists for the same receipt.\n saved_input_tokens: 'unknown',\n avoided_total_tokens: avoidedTotal,\n cache_hit_delta: null,\n output_tokens: 'unknown',\n }\n }\n\n const afterRate = hitRate(after)\n const beforeRate = hitRate(before)\n const delta = afterRate !== null && beforeRate !== null ? afterRate - beforeRate : null\n\n // The two figures bound different quantities (the skipped step's total vs\n // the next request's input), so a context that *shrank* between the samples\n // — a compaction, a rebuilt request, an adapter that does not replay the\n // whole turn — can push the lower above the upper. A range whose floor is\n // above its ceiling is not a range: drop the floor rather than print it\n // (review cod#1).\n const upper = after.input + after.cacheRead\n const bounded = avoidedTotal === 'unknown' || avoidedTotal <= upper ? avoidedTotal : ('unknown' as const)\n\n return {\n saved_input_tokens: upper,\n avoided_total_tokens: bounded,\n cache_hit_delta: delta !== null && Number.isFinite(delta) ? delta : null,\n output_tokens: after.output,\n }\n }\n}"]}