dsh-boost 0.1.0 → 0.1.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.
Files changed (54) hide show
  1. package/README.en.md +184 -70
  2. package/README.md +148 -59
  3. package/dist/gate/decide.js +33 -2
  4. package/dist/gate/decide.js.map +1 -1
  5. package/dist/hooks/llm-stream.js +242 -89
  6. package/dist/hooks/llm-stream.js.map +1 -1
  7. package/dist/hooks/post-execute.js +282 -25
  8. package/dist/hooks/post-execute.js.map +1 -1
  9. package/dist/hooks/session-state.js +18 -8
  10. package/dist/hooks/session-state.js.map +1 -1
  11. package/dist/host/root.js +22 -1
  12. package/dist/host/root.js.map +1 -1
  13. package/dist/index.js +494 -72
  14. package/dist/index.js.map +1 -1
  15. package/dist/scope/doc.js.map +1 -1
  16. package/dist/scope/store.js +24 -9
  17. package/dist/scope/store.js.map +1 -1
  18. package/dist/tools/boost.js +37 -4
  19. package/dist/tools/boost.js.map +1 -1
  20. package/dist/types.d.ts +18 -1
  21. package/dist/types.js.map +1 -1
  22. package/package.json +10 -6
  23. package/dist/admission/fixed-cost.d.ts +0 -23
  24. package/dist/admission/ledger.d.ts +0 -113
  25. package/dist/admission/retrieval.d.ts +0 -65
  26. package/dist/admission/usage.d.ts +0 -75
  27. package/dist/config.d.ts +0 -43
  28. package/dist/gate/binding.d.ts +0 -113
  29. package/dist/gate/decide.d.ts +0 -82
  30. package/dist/gate/guard.d.ts +0 -69
  31. package/dist/gate/invalidate.d.ts +0 -112
  32. package/dist/gate/plan.d.ts +0 -86
  33. package/dist/hooks/clock.d.ts +0 -68
  34. package/dist/hooks/execute.d.ts +0 -79
  35. package/dist/hooks/llm-stream.d.ts +0 -276
  36. package/dist/hooks/pending.d.ts +0 -89
  37. package/dist/hooks/post-execute.d.ts +0 -247
  38. package/dist/hooks/session-state.d.ts +0 -158
  39. package/dist/hooks/synthesize.d.ts +0 -74
  40. package/dist/host/loader.d.ts +0 -23
  41. package/dist/host/platform.d.ts +0 -18
  42. package/dist/host/root.d.ts +0 -18
  43. package/dist/projection/apply.d.ts +0 -174
  44. package/dist/projection/canonicalise.d.ts +0 -43
  45. package/dist/projection/counters.d.ts +0 -65
  46. package/dist/projection/truncate.d.ts +0 -47
  47. package/dist/prompt/protocol.d.ts +0 -45
  48. package/dist/receipts/store.d.ts +0 -198
  49. package/dist/scope/doc.d.ts +0 -117
  50. package/dist/scope/resolve.d.ts +0 -91
  51. package/dist/scope/store.d.ts +0 -135
  52. package/dist/selector/jev.d.ts +0 -93
  53. package/dist/tools/boost.d.ts +0 -367
  54. package/dist/tools/family.d.ts +0 -26
package/README.md CHANGED
@@ -3,11 +3,12 @@
3
3
  通过**工具回执投影**与**确定性只读替换**降低 DeepSeek Harness(DSH)的 token 消耗。
4
4
 
5
5
  > **状态:v1 已实现。** 投影、替换与控制面均已落地;`npm run build` 干净,测试套件全部通过。
6
+ > 收益区间是设计阶段的事前估算(下界 3.5% / 理想上界 10.0%;净保底约 0.4%),交付物**无法复算**——见下。
6
7
 
7
8
  ## 它解决什么
8
9
 
9
10
  DSH 每次模型请求都会回放全部历史。本机 300 个最长会话的实测聚合(`npm run --silent stats`——不带
10
- `--silent` 时 npm 会把 `> dsh-boost@0.1.0 stats` 横幅打进 stdout,机器解析请用 `--silent` 或直接
11
+ `--silent` 时 npm 会把 `> dsh-boost@0.1.1 stats` 横幅打进 stdout,机器解析请用 `--silent` 或直接
11
12
  `node scripts/session-stats.mjs`;快照时刻 `2026-11-19T03:13:21Z`):54,141 步、54,088 个请求,合计 10,575,904,022 raw token。按步均值
12
13
  195,340 token,按请求均值 195,531、中位 187,681;97.01% 的输入是缓存读。工具回执是体积主体
13
14
  (bash 61.75%、read 22.13%、ssh 10.01%),而下一步真正会用到的部分通常远小于回执本身。
@@ -18,21 +19,33 @@ DSH 每次模型请求都会回放全部历史。本机 300 个最长会话的
18
19
  原文仍可取回,页脚给出路径。投影按固定阈值确定性执行,不产生逐次决策。
19
20
  2. **替换**——计划里重复的只读调用(`read` / `grep` / `glob`)若已有确定性证据满足守卫,
20
21
  直接提交,不再向模型要一次决策;多候选时用一个单标签选择器——一次独立的辅助请求
21
- (`maxTokens` 512,另加其输入)。对替换涉及的三个工具而言,计划里的 `$public` 参数绑定
22
+ (`maxTokens` 512,另加其输入)。这是对原始需求 2.2 的**收窄**:原需求要 Jev 对每个工具
23
+ 结果逐条打分、判断能否交给下一个工具,v1 只做「同一回执上的多个候选里选一个」,不做
24
+ 逐条打分(见[澄清记录](docs/superpowers/clarifications/2026-11-18-dsh-token-efficiency.md)
25
+ 的 2.2 与「用户裁决」第 9 条)。对替换涉及的三个工具而言,计划里的 `$public` 参数绑定
22
26
  (把上一步回执里的值直接搬进下一步参数)在实践中只对 `glob` 的单 token 输出有效;
23
27
  `read` 与 `grep` 的输出带行号或是裸路径,标识符投影匹配不到,这些调用会退回模型。
24
28
 
25
- v1 的预期收益区间是 **3.5%(保底)– 10.0%(上界)**,按 raw `totalTokens` 计。
26
- 这是设计阶段对一个 300 会话语料做**离线事前估算**得到的区间:不是保证,也不是从交付的
27
- `session-snapshot.json` 能复算出来的数字(快照只存聚合计数,没有估算用的分项)——交付物里
28
- **没有任何工具能复算它**。影子周也**不能**把这个区间变成实测百分比:影子报告只输出四个
29
- 比例(见「影子周」一节),没有总 token 分母,`boost status` 也只有绝对值;区间要被实测
30
- 取代,得等后续版本补上分母统计。
29
+ 多候选选择器**不读独立的模型配置**:它复用**边界请求**的 `provider` / `model` /
30
+ `reasoningEffort`(`src/index.ts` 的 `rememberRoute`,主来源是 `agent/pre-step` 的
31
+ `modelSelection`,`agent/request` 的解析结果只作回退),所以它不一定是廉价模型。要让它走
32
+ 别的模型,只能在边界会话上换模型(宿主按 agent 选路由),或让计划只留一个候选(单候选
33
+ 不调用选择器)。
34
+
35
+ v1 的**事前估算**区间是 **3.5%(下界)– 10.0%(理想上界)**,按 raw `totalTokens` 计;
36
+ **3.5% 不是保底**——它是设计阶段对一个 300 会话语料做离线估算得到的下界,其中替换账的
37
+ 2.70% 是**上限**,不能算进保底;诚实的净保底只有约 **0.4%**(投影侧毛额约 0.8% 减去每请求
38
+ 固定开销约 0.4%)。这个区间不是保证,也不是从交付的 `session-snapshot.json` 能复算出来的
39
+ 数字(快照只存聚合计数,没有估算用的分项)——交付物里**没有任何工具能复算它**。影子周也
40
+ **不能**把这个区间变成实测百分比:影子报告只输出四个比例(见「影子周」一节),没有总 token
41
+ 分母,`boost status` 也只有绝对值;区间要被实测取代,得等后续版本补上分母统计。
31
42
 
32
43
  ## 前置条件
33
44
 
34
- - Node.js `>=24.9.0`,DSH `0.2.2-rc.4`(精确锁定,不是区间;两者都在 `package.json` 的
35
- `engines` 里;Node 下限对齐宿主 `@deepseek-ai/dsh@0.2.2-rc.4`)。
45
+ - Node.js `>=24.9.0`,DSH `>=0.2.2-rc.4 <0.2.3-0`(**区间**,不是精确钉法;宿主按
46
+ `includePrerelease` 语义判定,不满足时会直接停用插件,而 `0.2.2-rc.5` 与本插件触及的宿主包
47
+ 逐字节相同)。两者都在 `package.json` 的 `engines` 里;Node 下限对齐宿主
48
+ `@deepseek-ai/dsh@0.2.2-rc.4`。
36
49
  - **本包不声明任何 peerDependencies**:安装它不会带出任何 `@deepseek-ai/*` 包,模块脱离它们也能
37
50
  加载;运行时能力(`tokenMeter`、`spillStore`、估算器、页脚格式化器)由 DSH 宿主进程提供,
38
51
  缺失时走降级(见「宿主依赖」)。
@@ -45,16 +58,26 @@ v1 的预期收益区间是 **3.5%(保底)– 10.0%(上界)**,按 raw
45
58
  `dsh plugin` 要求指定 profile,剩下的参数原样转发给该 profile 目录里的 pnpm:
46
59
 
47
60
  ```bash
48
- # 从 registry 安装(0.1.0 是首次发布;发布后 latest 就是它)
49
- dsh plugin --profile <name> add dsh-boost@^0.1.0
61
+ # 从 registry 安装:npmjs 上的 latest 是 0.1.1(本仓库 .npmrc 与 lockfile
62
+ # 也已钉在 npmjs,见下)
63
+ dsh plugin --profile <name> add dsh-boost@^0.1.1 --registry=https://registry.npmjs.org/
50
64
 
51
65
  # 或从本地 checkout 安装(先构建;dist/ 不入库)
52
66
  npm run build
53
67
  dsh plugin --profile <name> add /absolute/path/to/dsh-boost
54
68
  ```
55
69
 
56
- 例如 web profile:`dsh plugin --profile web add dsh-boost@^0.1.0`。`dsh plugin` 把操作转发给 pnpm,
57
- 所以 pnpm 必须在 PATH 上。
70
+ 例如 web profile:`dsh plugin --profile web add dsh-boost@^0.1.1 --registry=https://registry.npmjs.org/`。
71
+ `dsh plugin` 把操作转发给 pnpm,所以 pnpm 必须在 PATH 上。
72
+
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` 会解析失败。
58
81
 
59
82
  包是 ESM(`"type": "module"`),`exports` 的 `.` 条目同时映射 `require` / `default`:Node ≥ 24.9
60
83
  下 `require('dsh-boost')` 与 `import` 加载同一份代码,装好的包里**不做任何构建**(`files` 只带
@@ -78,15 +101,18 @@ bundle,patch 的 `insert` 行落在 profile root 上。**装完必须重启 DS
78
101
  可以调用它来启用。
79
102
 
80
103
  `boost` 是**模型工具,不是 shell 命令**——这个包没有 `bin`,启用全程都要在对话里让模型调用
81
- 它(status、scope-set、shadow 都是工具调用,没有 CLI 等价物)。例如:
104
+ 它(status、scope-get、scope-set、shadow 都是工具调用,没有 CLI 等价物)。例如:
82
105
 
83
106
  > 调用 boost 工具,参数 `{"cmd":"status"}`,把 JSON 结果给我。
84
107
 
85
108
  首次 `status` 应看到 `ok: true`;`data.scope.workspaceIds` 为空、`revision` 为 `0`,`shadow` 为
86
109
  `true`、`projection` 为 `"shadow"`,`counts` 为空(**仅限全新会话**——越界会话更早的工具调用
87
- 已经各记过一条 `skip:no-scope`)。`degraded` 里出现 `ERR_SCOPE_READ_FAILED`
88
- 是正常的:`scope.json` 还不存在,插件正落在 fail-closed 默认值上。第一次成功的 `scope-set`
89
- 会创建这个文件。
110
+ 已经各记过一条 `skip:no-scope`)。首次 `status` 的 `degraded` 里**不会**因为 `scope.json`
111
+ 缺失而出现 `ERR_SCOPE_READ_FAILED`:缺失是干净的默认值(`ENOENT` 不带降级码,
112
+ `src/scope/store.ts`);全新根目录且宿主能力齐全时,`degraded` 就是空数组。在 `status` 的
113
+ 读取路径上,`ERR_SCOPE_READ_FAILED` 只表示文件**存在但读不出来**(权限、I/O、路径是目录
114
+ 等)——那不是正常的首次状态,要先修掉。
115
+ 第一次成功的 `scope-set` 会创建这个文件。
90
116
 
91
117
  然后列出要暴露的工作区:
92
118
 
@@ -104,10 +130,13 @@ bundle,patch 的 `insert` 行落在 profile root 上。**装完必须重启 DS
104
130
  ```
105
131
 
106
132
  - `workspaceIds` 是宿主的 workspace UUID,不是路径;宿主通过 workspace registry 把 agent 的
107
- cwd 映射成这个 id。**发现 UUID 本身有摩擦**:要么问宿主/翻会话记录,要么自己读
108
- `$DSH_HOME/storages/workspace.json` 的 `tables.workspaces`(id ↔ path 的映射表)——v1 没有
109
- 任何命令替你做这件事。找不到 UUID 且是单用户机器时,可以用 `"mode": "global"` 放开到所有
110
- **已定义**的工作区;没有工作区的会话仍然不可见。
133
+ cwd 映射成这个 id。**发现 UUID 本身有摩擦**:要么问宿主/翻会话记录,要么自己读宿主的
134
+ `<hostDshHome>/storages/workspace.json` 的 `tables.workspaces`(id ↔ path 的映射表)——v1
135
+ 没有任何命令替你做这件事。宿主的 home 解析顺序是「非空 `$DSH_HOME`(`~` 会展开)→
136
+ `~/.dsh`」,所以默认安装下文件是 `~/.dsh/storages/workspace.json`,**不是**
137
+ `$DSH_HOME/storages/workspace.json`(除非 `$DSH_HOME` 真的设了)。注意 `config.dshHome`
138
+ 只移动插件的 `<dshHome>/boost`,不会移动宿主的这个文件。找不到 UUID 且是单用户机器时,
139
+ 可以用 `"mode": "global"` 放开到所有**已定义**的工作区;没有工作区的会话仍然不可见。
111
140
  - `baseRevision` 取你刚读到的 `data.scope.revision`(首次写入是 `0`)。这是 compare-and-swap:
112
141
  revision 过期会返回 `ERR_SCOPE_REVISION_CONFLICT`,重读 `status` 再试。调用被调用方的取消
113
142
  信号打断时返回 `ERR_SCOPE_ABORTED`:锁已释放、`scope.json` 原样未动,重读 `revision` 重试
@@ -160,7 +189,17 @@ scope**:`boost` 工具 schema(399)只要插件装配就常驻——`boost`
160
189
  设计选择**影子优先**:先用一周只记账(不合成回合、不跳过调用,投影只记账不改内容),再决定
161
190
  是否真的投影与替换。**「什么都不改」并不成立**:只要有可见工作区,协议段(379 token)就会
162
191
  注入系统提示;多候选计划仍会**真实调用一次选择器**(一次独立的辅助模型请求)。影子周按设计
163
- 零节省,它只产出下一节的四个比例。`scope.json` 里有两个独立开关:
192
+ 零节省,它只产出下一节的四个比例。
193
+
194
+ 其中 `saveableRatio`、`byFamily`、`candidateRecall` 能决定的是**替换侧是否值得打开**:
195
+ 白名单能兑现多少替换决策、命中落在哪些工具族、候选集召回多高——也就是替换打开后会不会
196
+ 真的触发、主要落在哪些族。它们**不能决定发布**:v1 按正常版本发布,不把影子期收益当发布
197
+ 门;这个决定是**实现者在设计阶段做的,不是用户裁决**——用户只接受了为期一周的影子期,没有
198
+ 裁定影子结果是否该当发布门。它们也**不能测出节省**:报告没有总 token 分母,
199
+ `retrievalUpperBound` 在影子期结构性为 `0`(它只统计 `projection:'on'` 的已应用投影取回),
200
+ 连投影的取回损害都约束不了;投影的放行依据是可见性契约(原文可经页脚取回)与事后检测,
201
+ 不是影子标签。
202
+ `scope.json` 里有两个独立开关:
164
203
 
165
204
  | 开关 | 取值 | 行为 |
166
205
  |---|---|---|
@@ -174,21 +213,24 @@ scope**:`boost` 工具 schema(399)只要插件装配就常驻——`boost`
174
213
 
175
214
  1. **第一周**:按上面的 `scope-set` 使用 `shadow: true`、`projection: 'shadow'`,照常工作。
176
215
  2. **读报告**:在仓库 checkout 里跑
177
- `node scripts/shadow-report.mjs --dir "${DSH_HOME:-$HOME/.dsh}/boost/receipts"`。
178
- 这个脚本是 dev-only,不在 npm tarball 里。它输出四个标签:
216
+ `node scripts/shadow-report.mjs --dir "<root>/receipts"`,其中 `<root>` 是装配日志打印的
217
+ `root=`(即 `<dshHome>/boost`;`dshHome` 配置优先于 `$DSH_HOME`,两者都未设时回退
218
+ `~/.dsh`)。这个脚本是 dev-only,不在 npm tarball 里。它输出四个标签:
179
219
  `saveableRatio`(白名单能兑现的替换占比 = `whitelisted` 影子提交 / **全部**替换决策——分母
180
220
  是每一次替换决策,不只是白名单调用;影子期全族记账,bash/ssh 的潜力看 `byFamily`)、`byFamily`(按候选工具族的命中率)、
181
221
  `candidateRecall`(候选集召回)、`retrievalUpperBound`(取回率上界;影子期没有真正投影,
182
222
  结构上恒为 `0`)。
183
- 3. **打开投影**:报告支持的话,保持 `shadow: true`,把 `projection` 改成 `'on'`:
223
+ 3. **打开投影**:投影的放行不靠影子标签(依据是可见性契约与事后检测),确认宿主 spill
224
+ 后端可用后,保持 `shadow: true`,把 `projection` 改成 `'on'`:
184
225
 
185
226
  ```json
186
227
  { "cmd": "scope-set", "body": { "projection": "on" }, "baseRevision": 1 }
187
228
  ```
188
229
 
189
230
  `scope-set` 只覆盖你传入的字段,其余保持不变。此时回执开始真正被替换,但替换决策仍然只记账。
190
- 4. **再打开替换**:直接把影子关掉——**先检查再关是无效顺序**:影子期从不合成回合,
191
- `content[].thinking` 的 400 在结构上不可能出现,关影子之前检查它永远只能读到「未见」。
231
+ 4. **再打开替换**:影子报告显示白名单命中与候选召回可接受时,直接把影子关掉——**先检查再关
232
+ 是无效顺序**:影子期从不合成回合,`content[].thinking` 的 400 在结构上不可能出现,
233
+ 关影子之前检查它永远只能读到「未见」。
192
234
  把 `shadow` 设为 `false` 之后,按 [docs/RELEASE.md](docs/RELEASE.md) §4 在**第一个真正
193
235
  被替换的回合**检查该 400,并在此后的每个替换观察窗继续记录:
194
236
 
@@ -228,13 +270,13 @@ scope**:`boost` 工具 schema(399)只要插件装配就常驻——`boost`
228
270
  字符按 Unicode 码点计。错误回执与超过 256 KiB 的回执不投影。
229
271
 
230
272
  不变量不是 `triggerChars ≥ headChars + tailChars + 1`。真实替换串是 head line + head + 页脚 +
231
- tail + 3 个换行;页脚由宿主 `formatSpillNotice` 生成,约 196 字符(68 字符 locator、5 位省略
232
- 字节数、宿主固定 retrieval hint)。grep/glob 默认 400+100 时:
233
- `400 + 100 + 50(head line) + 196(页脚) + 3 = 749 > 700`。于是刚过 700、约 749 以下的回执
234
- 会被 `truncate` 判定“可裁”,但 `projectApply` 组装后并不短于原文,直接返回原文——这是死区,
235
- 不是净亏。运行时的 `assembled.length >= text.length` 检查保证投影绝不会让回执变长;要消除
236
- 死区,把 `triggerChars` 提到至少这个和(例如 grep/glob 用 800),或缩小窗口。页脚长度会随
237
- locator 与数字位数浮动。
273
+ tail + 3 个换行;页脚由宿主 `formatSpillNotice` 生成:68 字符 locator 加宿主固定的 66 字符
274
+ retrieval hint 下,3 位省略字节数是 190 字符,5 位是 192 字符。grep/glob 默认 400+100 时:
275
+ `400 + 100 + 50(head line) + 190(页脚) + 3 = 743 > 700`(5 位计数则是 745)。于是刚过 700、
276
+ 约 743 以下的回执会被 `truncate` 判定“可裁”,但 `projectApply` 组装后并不短于原文,直接返回
277
+ 原文——这是死区,不是净亏。运行时的 `assembled.length >= text.length` 检查保证投影绝不会让
278
+ 回执变长;要消除死区,把 `triggerChars` 提到至少这个和(例如 grep/glob 用 800),或缩小窗口。
279
+ 页脚长度会随 locator 与数字位数浮动。
238
280
 
239
281
  (`projection: 'shadow'` 定价只含 `(Omitted N bytes.)` 省略句,不含 locator/页脚全文,所以
240
282
  影子账的 `after` 是下界;apply 路径在写入后还会再核对一次。)
@@ -280,27 +322,63 @@ plugin manager 才能把运行中的 entry 认成本包的行、通过 profile p
280
322
 
281
323
  ## 状态、回滚与卸载
282
324
 
283
- 状态在 `$DSH_HOME/boost/`(`$DSH_HOME` 未设置时回退 `~/.dsh`):
325
+ 状态在 `<dshHome>/boost/`:`dshHome` 配置**优先于** `$DSH_HOME`,两者都未设置时回退
326
+ `~/.dsh`;装配日志打印解析后的 `root=`(就是 `<dshHome>/boost`)。
284
327
 
285
328
  - `scope.json`——暴露面的唯一事实来源(version 2,带 revision)。
286
329
  - `scope.lock`——写路径的短锁,正常写入结束后删除。
287
- - `receipts/<encoded-session>.jsonl`——追加式收据。每行携带元数据、回执前 256 个码点的
288
- preview(不存 stdout 全文)和**绑定后的参数 `args`(模型所写,截到 2048 个码点,超长会以
289
- `args_truncated` 标记的截断 JSON 落盘——`write` / `edit` 的参数可携带整段文件内容,同样
290
- 入账)**。**只有替换类收据**(`substitute` / `substitute-settled` / `shadow`)另外携带计划
291
- goal(≤256 码点)与守卫(≤8 条,各 ≤300 码点);投影与 skip 收据只有 preview 和 args,
292
- 没有 plan 证据。
330
+ - `receipts/<encoded-session>.jsonl`——追加式收据。**收据按“决定”写,不是每次调用都写**:
331
+ 只有发生投影、替换决策(含 skip)或越界 `skip:no-scope` 时才落一行;一个没有计划的
332
+ `write` / `edit` 不产生任何收据,它的参数不会被记录。每行携带元数据、回执前 256 个码点的
333
+ preview(不存 stdout 全文)和该调用的绑定参数 `args`(模型所写:超过 2048 个码点时以
334
+ `args_truncated` 标记的截断 JSON 落盘;嵌套超过 64 层时以 `args_depth_truncated` 标记,
335
+ 并把更深的子树换成 `{ "truncated_depth": 64 }`)。**只有替换类收据**另外携带计划 goal
336
+ (≤256 码点)与守卫(≤8 条,各 ≤300 码点):`kind:'substitute'`、
337
+ `kind:'substitute-settled'`,以及 `kind:'shadow'` 且 `code:'ok'` 的影子提交。
338
+ `kind:'shadow'` 不是替换专用——投影影子也写 `kind:'shadow'`,但带
339
+ `code:'projection-shadow'`,属于投影收据,没有 plan 证据。
340
+ **投影收据**(`kind:'projection'`、`code:'projected'`,以及投影影子)带 `before` /
341
+ `after` / `saved_projection_tokens` / `unit` / `estimate` / `horizon_steps`;没有 token
342
+ meter 时只有 `estimate:'unknown'`,三个数值字段整体省略。**取回收据**
343
+ (`kind:'projection'`、`code:'projection-retrieval'`)带 `locator` 与
344
+ `retrieval_call_tokens` / `retrieval_content_tokens` / `retrieval_tokens`;三个取回字段
345
+ 只在这次取回被定价时写入,未定价时 `estimate` 为 `'unknown'`、字段省略。`skip` 收据只有
346
+ preview 与 args(`skip:no-scope` 连这两个都没有,只记工具名)。
347
+
348
+ 当前分片超过 8 MiB 或 20,000 行时,下一次写入前轮转为 `<encoded-session>.1.jsonl`;只保留
349
+ 当前分片和它的前一份(旧的 `.1` 被覆盖)。`boost status` 先读 `.1` 再读当前分片。256 分片
350
+ 上限按**编码后的会话名**计数:轮转出的 `.1.jsonl` 与当前文件同属一个名字,不额外占名额,
351
+ 但扫描会把该名字下的两份都读入。
293
352
 
294
353
  `boost status` 的投影账按每条收据自己的 `horizon_steps` 重放;没有该字段的旧收据按当前
295
354
  horizon 重放,并计入 `projection_horizon_reestimated`;`projection_horizon_steps` 报告当前
296
355
  生效的 horizon(活动会话的最小值;没有历史时回落到 `horizonSteps`)。
297
356
 
357
+ `status.data` 里还有几个不在 `degraded` 里的状态/账目字段:
358
+
359
+ - `receipts_stopped`:收据连续写失败 3 次后为 `true`。此时替换被**整体拒绝**(fail-closed,
360
+ 不再花选择器调用或预算),投影照常;所有账目是停写前的旧快照。恢复写盘并成功追加一行后
361
+ 计数清零、该字段回到 `false`。它是唯一说出「收据已停写」的地方——没有对应的 `degraded` 码。
362
+ - `protocol_suppressed`:协议段在装配时被压掉的次数(不可见工作区、没有 agent 的诊断装配,
363
+ 以及 `complete: true` 覆盖)。装配每请求都跑,所以只计数、不写收据。
364
+ - `projection_locator_evictions`:因每会话 locator 上限(512 个,最旧先丢)被丢弃的 locator
365
+ 数;大于 0 表示取回账目有损。
366
+ - `projection_unknown_families`:带 `mcp__` 前缀、进入投影阶段但没有匹配到工具族的调用数;
367
+ `projection_unknown_tools` 是其中保留的未映射工具名及次数(最多 32 个),用来发现 mapper
368
+ 缺口。
369
+ - `hasWorkspaceRegistry`:宿主当前是否提供 `workspaceRegistry`;没有探测到时该键**省略**,
370
+ 不是 `false`。
371
+ - `saved`:兼容旧消费者的 camelCase 账目对象(`substitution` / `projectionGross` /
372
+ `projectionNet` / `retrievals`),与顶层 snake_case 字段由同一次聚合派生。旧投影收据
373
+ (pre-T23b)没有 `saved_projection_tokens` 时,按收据里的 legacy `saved` 字段回退计价。
374
+
298
375
  `projection: 'on'` 时,完整原文在替换发生**之前**写入宿主的 spill 后端,页脚 locator 可以用
299
376
  `read` / `grep` 取回。投影不会丢掉唯一副本;spill 写入失败就不替换(收据记
300
377
  `projection-skipped:spill-failed`,页脚渲染失败记 `projection-skipped:footer-failed`;页脚
301
378
  渲染器加载不到则记 `projection-skipped:no-footer`,见「宿主依赖」)。
302
379
 
303
- 回滚与停用(下面的 `baseRevision` 按「启用」一节的路径走完是 `3`,第一条执行完是 `4`;
380
+ 回滚与停用(下面的 `baseRevision` 按「启用」+「影子周」的推荐顺序走完是 `3`——启用结束于
381
+ `1`,影子周的两步各加一——第一条执行完是 `4`;
304
382
  实际使用时永远取你刚从 `status` 读到的 `data.scope.revision`,不要照抄):
305
383
 
306
384
  - **关掉两个行为**(不再投影、不再替换,但仍然可见的工作区——`selected` 下已选的、`global`
@@ -311,9 +389,10 @@ horizon 重放,并计入 `projection_horizon_reestimated`;`projection_horizo
311
389
  ```
312
390
 
313
391
  - **回到真正惰性**:把 `mode` 设回 `selected` 并清空列表。**注意 `workspaceIds` 只在
314
- `selected` 模式下起作用**:`isVisible` 对 `mode:"global"` 恒为真(`src/scope/doc.ts`,
315
- `global` 分支根本不读列表),所以**先处于 `global` 时只写 `workspaceIds: []` 什么都停不
316
- 下来**——投影与替换会照常进行,而你以为已经回滚了。在 `selected` 下移除单个工作区即可;
392
+ `selected` 模式下起作用**:`isVisible` 对 `mode:"global"` 下每个**已定义**的工作区为真
393
+ (`src/scope/doc.ts`,`global` 分支不读列表;`workspaceId` 未定义的会话仍为假),所以
394
+ **先处于 `global` 时只写 `workspaceIds: []` 什么都停不下来**——投影与替换会照常进行,
395
+ 而你以为已经回滚了。在 `selected` 下移除单个工作区即可;
317
396
  在 `global` 下必须同时改 `mode`:
318
397
 
319
398
  ```json
@@ -323,7 +402,7 @@ horizon 重放,并计入 `projection_horizon_reestimated`;`projection_horizo
323
402
  `selected` + 空列表时协议段、投影、替换全部停止(只剩下 `boost` 工具 schema 的常驻开销)。
324
403
 
325
404
  - **卸载插件**:`dsh plugin --profile <name> remove dsh-boost`,然后重启 DSH。
326
- - 删除 `$DSH_HOME/boost` 会清掉 scope 与收据(回到默认),但不会删除宿主 spill 后端里已经
405
+ - 删除 `<dshHome>/boost` 会清掉 scope 与收据(回到默认),但不会删除宿主 spill 后端里已经
327
406
  写出的原文文件。
328
407
 
329
408
  ## 宿主依赖
@@ -336,22 +415,23 @@ horizon 重放,并计入 `projection_horizon_reestimated`;`projection_horizo
336
415
  | `workspaceRegistry` | 软(`ctx.get('workspaceRegistry')`) | **工作区不可见**:cwd 永远映射不到工作区 id,一切按 fail-closed 视为不可见——协议段不注入、投影与替换全部跳过,只有 `skip:no-scope` 收据在涨;`status.degraded` 带 `ERR_HOST_NO_WORKSPACE_REGISTRY`。这是**工作区本应可见却不可见**时的宿主能力解释,不是「装上了却什么都不发生」的唯一解释:默认 `selected + []` 按设计就是惰性的且不报错;缺 token meter 会拒绝真正的替换;`complete: true` 提示段会压掉协议段 |
337
416
  | `tokenMeter` | 软(`ctx.get('tokenMeter')`) | 拒绝替换;投影仍可用,投影账记 `unknown`(不伪造数字);`status.degraded` 带 `ERR_HOST_NO_TOKENMETER` |
338
417
  | `spillStore` | 软(`ctx.get('spillStore')`) | `projection: 'on'` 时超限回执不投影(保住证据),收据记 `projection-skipped:no-spill`;`status.degraded` 带 `ERR_HOST_NO_SPILL`(实时探测只在 on 模式;历史收据在任何模式下都会让它出现) |
339
- | `@deepseek-ai/dsh-spill-policy/notice` | 软(动态 import) | spill 后端在,但页脚渲染器 `formatSpillNotice` 加载不到/不存在:apply 模式无法拼页脚,逐条跳过(收据 `projection-skipped:no-footer`),`status.degraded` 带 `ERR_HOST_NO_SPILL_NOTICE`。这与「没有 spill 后端」的 `ERR_HOST_NO_SPILL` 是两件事 |
418
+ | `@deepseek-ai/dsh-spill-policy/notice` | 软(动态 import) | spill 后端在,但页脚渲染器 `formatSpillNotice` 加载不到/不存在:apply 模式无法拼页脚,逐条跳过(收据 `projection-skipped:no-footer`;页脚渲染时抛错则记 `projection-skipped:footer-failed`),`status.degraded` 带 `ERR_HOST_NO_SPILL_NOTICE`。这与「没有 spill 后端」的 `ERR_HOST_NO_SPILL` 是两件事 |
419
+ | (spill 后端存在但写失败) | — | 每次 `saveText` 被拒:收据 `projection-skipped:spill-failed`,`status.degraded` 带 **`ERR_HOST_SPILL_FAILING`**。这是**第三种**状态,既不是「没有后端」也不是「没有页脚渲染器」——让操作者去「恢复 spill 包」会把一个已装好却报错的包当成没装 |
340
420
  | `@deepseek-ai/dsh-token-meter/estimate` | 软(动态 import) | 固定开销无法测量,`fixedOverheadTokens` 为 `'unknown'`;`status.degraded` 带 `ERR_HOST_NO_ESTIMATOR` |
341
421
  | `win32` 平台 | 运行时检查 `isPosixOnly()` | 拒绝替换,投影照常;`status.degraded` 带 `ERR_HOST_PLATFORM_UNSUPPORTED` |
342
422
  | 宿主版本线 | 启动时读 `@deepseek-ai/dsh-app-boot` 的版本 | 不是 `0.2.2-rc.4` 时日志警告 `ERR_HOST_VERSION_MISMATCH`,插件照常加载(advisory,不是 `status.degraded` 码);版本读不到时只记 info,不发码 |
343
- | 收据分片可读性 | `boost status` 全量扫描(非依赖) | 至少一个收据分片读不出来(EACCES、名为 `x.jsonl` 的目录等)时 `status.degraded` 带 `ERR_RECEIPTS_UNREADABLE`;`status` 仍是**全量聚合**——健康分片照常计数——所以数字可能不完整。查 `$DSH_HOME/boost/receipts/` 的权限与异常条目,修复后重跑并对比计数 |
423
+ | 收据分片可读性 | `boost status` 全量扫描(非依赖) | 至少一个收据分片读不出来(EACCES、名为 `x.jsonl` 的目录等)时 `status.degraded` 带 `ERR_RECEIPTS_UNREADABLE`;`status` 仍是**全量聚合**——健康分片照常计数——所以数字可能不完整。查 `<dshHome>/boost/receipts/` 的权限与异常条目,修复后重跑并对比计数 |
344
424
  | 收据分片数量 | `boost status` 全量扫描(非依赖) | 分片超过 256 个时 `status` 只统计按编码名排序的前 256 个,`status.degraded` 带 `ERR_RECEIPTS_TRUNCATED`,所有计数因此是**下界**;分片永不自动删除,可归档/移走旧会话分片后重跑 `status` |
345
425
  | 提示段装配瀑布 | 出站请求探测(非依赖) | 宿主的 `complete: true` 提示段在装配瀑布之后替换了整个系统提示、协议段没有到达请求时,`status.degraded` 带 `ERR_HOST_COMPLETE_SECTION`;受影响请求上替换与投影 fail-closed(工作区明明可见插件却不动作)。找出宿主里覆盖瀑布的 complete 段(通常属于另一个插件)并移除,或接受这些请求上不动作 |
346
426
 
347
427
  `ERR_HOST_NO_STEP_WHEN` 已不存在:步骤级 `when` 从本包声明的最老宿主线起就在
348
428
  `ToolRegistrationOptions` 里,插件不再探测、无条件注册。
349
429
 
350
- 注册阶段还有几个只进日志、不进 `status.degraded` 的码:协议段注册抛出**非重复**错误时记
351
- `ERR_BOOST_SECTION_REGISTER_FAILED`;`registerHooks` 在第一个挂载处中止,后续替换/投影/
352
- execute 钩子都不会注册,请求路径实际 inert,只有 `boost` 工具与会话事件仍会尝试挂载。宿主
353
- 真正的重复注册错误记 `ERR_BOOST_ALREADY_MOUNTED` 并跳过本次挂载;`boost` 工具自身注册失败
354
- 记 `ERR_BOOST_TOOL_REGISTER_FAILED`。
430
+ 注册阶段的码分两类。协议段注册抛出**非重复**错误时记 `ERR_BOOST_SECTION_REGISTER_FAILED`
431
+ (只进日志);此后三个事件钩子(`tools/post-execute`、`llm/stream`、`tools/execute`)**逐个
432
+ 独立挂载**,任何一个失败都会被记名并通过 **`ERR_BOOST_PARTIAL_MOUNT`** 进 `status.degraded`
433
+ ——装配不全的插件不会再看起来健康。宿主真正的重复注册错误记 `ERR_BOOST_ALREADY_MOUNTED` 并
434
+ 跳过本次挂载;`boost` 工具自身注册失败记 `ERR_BOOST_TOOL_REGISTER_FAILED`(只进日志)。
355
435
 
356
436
  `ERR_HOST_NO_TOKENMETER` 与 `ERR_HOST_NO_ESTIMATOR` 是**两件不同的事**,不要合并:
357
437
  前者是宿主服务(`ctx.get('tokenMeter')`)不存在,替换被拒绝;后者是纯估算包
@@ -370,22 +450,31 @@ spill,报它只会制造噪音);但**收据通道**不看当前模式—
370
450
  ## v1 的边界
371
451
 
372
452
  - 只做两件事:**就地替换工具回执**,以及**替换只读调用**(`read` / `grep` / `glob`)。
373
- - **不批量执行工具调用**(没有 PTC / `run_code`,设计 N1)。
453
+ - **不批量执行工具调用**(没有 PTC / `run_code`):这不是 v1 自行划定的范围,而是原始需求
454
+ 2.1 被**收窄**后的结果——原需求要一次调用多个工具,裁决为显式排除、二期再议(见
455
+ [澄清记录](docs/superpowers/clarifications/2026-11-18-dsh-token-efficiency.md) 的 2.1 与
456
+ 「用户裁决」第 9 条;设计 N1)。
374
457
  - **不去重、不合并工具调用**(设计 N5)——这条完全没开工,且 v1 **没有任何工具能测出重复
375
458
  调用率**:设计稿里用来触发重启判定的「影子周重复率统计」没有交付,`shadow-report.mjs`
376
459
  不产出它。
377
460
  - **影子周按设计零节省**:只记账(协议段照注入、选择器照调用),它的产出是四个比例,
378
461
  不是省下的 token。
379
- - **v1 不评判「结果更好」**:只有 token 账目与 20 任务回退门,没有任何质量指标;「替换后
462
+ - **v1 不评判「结果更好」**:只有 token 账目和一套**人工**的 20 任务回退流程(任务集不随包发布,见 `docs/RELEASE.md` §3),没有任何质量指标;「替换后
380
463
  结果质量」在 v1 是不可判的。
464
+ - **投影是截断,不是精炼**:它保留头尾、丢掉中段;账本里的 before/after token 差量的是
465
+ 「变短」,不是「变相关」。被丢掉的中段可能正是下一步决策要用的内容——`projection: 'on'`
466
+ 下原文可经页脚 locator 取回,但取回要花一次工具调用,且 v1 没有指标区分「精炼」与
467
+ 「误截」。
381
468
  - **装上但未启用是小的净亏**:`boost` 工具只要插件装配就注册,schema 实测 399 token/请求
382
469
  常驻(见「启用」一节的分解),收益为零。
383
470
  - **不支持 desktop profile**(设计 D6)。
384
471
  - 不替换、也不接管 DSH 的压缩、剪枝与 spill 决策(设计 N3);投影只改模型可见 content,
385
472
  原文仍借宿主 spill 存放。
386
473
  - 不做模型训练或权重改动(N2);不追求论文里的 87.93%(N4)。
387
- - 不承诺 10%:3.5% 是保底线,10% 是全程存活的理想上界;影子周只告诉你是否继续,不能把
388
- 区间换成实测值(`shadow-report.mjs` 只有四个比例,没有总 token 分母)。
474
+ - 不承诺 10%:3.5% 是事前估算的**下界**,不是保底;10% 是全程存活的理想上界。净保底约
475
+ 0.4%(投影侧毛额约 0.8% 减去每请求固定开销约 0.4%)。影子周只回答替换侧是否值得打开
476
+ (候选覆盖与命中),不决定发布,也不能把区间换成实测值(`shadow-report.mjs` 只有四个
477
+ 比例,没有总 token 分母)。
389
478
 
390
479
  ## 文档
391
480
 
@@ -401,7 +490,7 @@ spill,报它只会制造噪音);但**收据通道**不看当前模式—
401
490
  | [设计稿](docs/superpowers/specs/2026-11-18-dsh-token-efficiency-design.md) | 目标、证据、架构、契约、度量、风险、发布形态 |
402
491
  | [宿主契约附录](docs/superpowers/plans/2026-11-18-host-contracts.md) | 逐条抄自宿主源码的接口准绳 |
403
492
  | [三层委派研究](docs/research/2026-11-18-three-tier-delegation.md) | 缓存、路由阈值、压缩、校验的 25 条一手来源 |
404
- | [发布验收](docs/RELEASE.md) | `npm run verify:package` 一条命令验收、零 peerDependencies 现状与安装规格、降级码矩阵、20 任务回归门、影子周与统计复算 |
493
+ | [发布验收](docs/RELEASE.md) | `npm run verify:package` 一条命令验收、零 peerDependencies 现状与安装规格、降级码矩阵、20 任务回退流程(人工,任务集不随包发布)、影子周与统计复算 |
405
494
 
406
495
  ## 许可证
407
496
 
@@ -22,7 +22,11 @@
22
22
  * 2. **Trivial candidates next.** A candidate whose guards are only `ok: true`
23
23
  * has nothing to verify, so it is not substitution potential either. If
24
24
  * every survivor is trivial (including the empty plan, vacuously), the
25
- * answer is `guard-trivial`.
25
+ * answer is `guard-trivial`. **Step admission follows (row 7).** When the
26
+ * caller supplies this step's `ResolvedToolSet` predicate, a candidate whose
27
+ * tool it does not admit is dropped before the selector is paid for: the
28
+ * host would reject its dispatch with `UNKNOWN_TOOL`. An emptied list is the
29
+ * ordinary `no-candidate`.
26
30
  * 3. **Bind, then guard, each remaining candidate in plan order.** Binding
27
31
  * failure drops the candidate (it does not abort the plan); only a bound
28
32
  * candidate has its guards evaluated. Guards read the receipt for
@@ -74,6 +78,29 @@ function whitelisted(whitelist) {
74
78
  return kept;
75
79
  };
76
80
  }
81
+ /**
82
+ * Step-admission filter (row 7).
83
+ *
84
+ * The host's `ResolvedToolSet` is this step's dispatch admission. A candidate
85
+ * whose tool it does not list would be rejected with `UNKNOWN_TOOL` after the
86
+ * plugin had already paid for the selector and taken a budget step, so it is
87
+ * dropped here, before both. An emptied list falls through to `no-candidate`:
88
+ * the plan had candidates and none survived, exactly like a failed guard.
89
+ *
90
+ * A throwing membership read drops that candidate: an unverifiable tool is not
91
+ * one this plugin may dispatch, and dropping under-reports instead of producing
92
+ * a call the host rejects.
93
+ */
94
+ function admittedBy(admitted) {
95
+ return (candidates) => candidates.filter((candidate) => {
96
+ try {
97
+ return admitted(candidate.tool);
98
+ }
99
+ catch {
100
+ return false;
101
+ }
102
+ });
103
+ }
77
104
  /**
78
105
  * Trivial-candidate filter (rule 3).
79
106
  *
@@ -154,7 +181,11 @@ function resolve(survivors) {
154
181
  export function decide(input) {
155
182
  const filters = input.shadow
156
183
  ? [nonTrivial]
157
- : [whitelisted(input.whitelist), nonTrivial];
184
+ : [
185
+ whitelisted(input.whitelist),
186
+ nonTrivial,
187
+ ...(input.admitted === undefined ? [] : [admittedBy(input.admitted)]),
188
+ ];
158
189
  const narrowed = narrow(input.plan.steps, filters);
159
190
  if (!Array.isArray(narrowed))
160
191
  return narrowed;
@@ -1 +1 @@
1
- {"version":3,"file":"decide.js","sourceRoot":"","sources":["../../src/gate/decide.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqDG;AAGH,OAAO,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAA;AACvC,OAAO,EAAE,WAAW,EAAE,MAAM,YAAY,CAAA;AACxC,OAAO,EAAE,SAAS,EAA6B,MAAM,WAAW,CAAA;AAiBhE,4EAA4E;AAC5E,SAAS,QAAQ,CAAC,IAAY;IAC5B,OAAO,EAAE,IAAI,EAAE,UAAU,EAAE,IAAI,EAAE,CAAA;AACnC,CAAC;AAED;;;;;;GAMG;AACH,SAAS,WAAW,CAAC,SAA8B;IACjD,OAAO,CAAC,UAAU,EAAE,EAAE;QACpB,MAAM,IAAI,GAAG,UAAU,CAAC,MAAM,CAAC,CAAC,SAAS,EAAE,EAAE,CAAC,SAAS,CAAC,GAAG,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,CAAA;QAC5E,IAAI,IAAI,CAAC,MAAM,KAAK,CAAC,IAAI,UAAU,CAAC,MAAM,GAAG,CAAC;YAAE,OAAO,QAAQ,CAAC,sBAAsB,CAAC,CAAA;QACvF,OAAO,IAAI,CAAA;IACb,CAAC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AO,OAAO,CAAC,aAAa,CAAC,QAAQ,EAAE,KAAK,CAAC,MAAM,EAAE,KAAK,CAAC,QAAQ,CAAC,CAAC,CAAA;AACvE,CAAC","sourcesContent":["/**\n * Substitution decision orchestration: one parsed plan in, one decision out.\n *\n * This is the point where the gate stops describing alternatives and says what\n * to do next: commit to exactly one candidate, ask the selector to choose among\n * several, or fall back to the ordinary model turn with a code saying why. It\n * is a pure function over the plan, the receipts collected so far and the\n * whitelist — no model call, no I/O, no mutation of its inputs.\n *\n * The rule that matters most: it never guesses. Zero viable candidates is a\n * fallback with a reason, never a best-effort pick, and a candidate that fails\n * binding or a guard is dropped without a reason of its own — the plan-level\n * fallback code is the only thing the caller needs.\n *\n * Order is fixed and load-bearing:\n *\n * 1. **Whitelist first.** A candidate whose tool is not whitelisted is never\n * committed and never reaches the selector (design §5.2-5). When the plan\n * had candidates and none survives, the answer is `tool-not-whitelisted`.\n * An empty plan is not a whitelist failure: it falls through and lands in\n * `guard-trivial`, because \"nothing to verify\" is what that code means.\n * 2. **Trivial candidates next.** A candidate whose guards are only `ok: true`\n * has nothing to verify, so it is not substitution potential either. If\n * every survivor is trivial (including the empty plan, vacuously), the\n * answer is `guard-trivial`.\n * 3. **Bind, then guard, each remaining candidate in plan order.** Binding\n * failure drops the candidate (it does not abort the plan); only a bound\n * candidate has its guards evaluated. Guards read the receipt for\n * `stepId` — the step that just arrived — and an absent receipt drops every\n * candidate rather than guessing one. A `$public` template naming a node\n * that does not exist is `unresolvable` inside binding, not a separate\n * existence check here: `receipts` only ever holds steps that already ran.\n * 4. **Count.** None → `no-candidate`; one → `commit` with the *bound* args;\n * several → `ask-selector` carrying each survivor as a fresh candidate whose\n * args are its bound tree. Every decision therefore hands the caller\n * executable args — the selector path and the commit path cannot diverge by\n * binding twice, and a `$public` template never leaves this module.\n *\n * Shadow mode (`shadow: true`) skips the whitelist. The shadow week records\n * substitution *potential* for every tool family (design §5.2-5: 影子期替换\n * 不设白名单,全量记账), and a whitelist-limited shadow would only ever measure\n * the read/grep/glob three. Trivial candidates are still dropped in shadow: a\n * trivial guard means there was nothing to verify, so it is not potential.\n *\n * The returned `ask-selector.candidates` is a new array of fresh candidate\n * objects: each carries the bound args and a copied `guards` array whose guard\n * objects are copied too, so neither the plan's candidate objects, their args,\n * nor their guards can be changed through the decision. (`args` is the only\n * thing that reaches the tool call; the guard copy makes the isolation claim\n * true at every depth the caller can reach.) `commit.args` is the same freshly\n * bound tree. A `$public` template never survives into a decision.\n *\n * @module dsh-boost/gate/decide\n */\n\nimport type { CanonicalReceipt } from '../projection/canonicalise.js'\nimport { bindArgs } from './binding.js'\nimport { evaluateAll } from './guard.js'\nimport { isTrivial, type Candidate, type Plan } from './plan.js'\n\n/** What the gate decided to do with the plan. */\nexport type Decision =\n | { kind: 'commit'; candidateId: string; args: Record<string, unknown> }\n | { kind: 'ask-selector'; candidates: Candidate[] }\n | { kind: 'fallback'; code: string }\n\n/** A filter narrows the candidate list, or ends the pipeline with a decision. */\ntype Filter = (candidates: Candidate[]) => Candidate[] | Decision\n\n/** One candidate that passed binding and its guards, with the args to run it. */\ninterface Viable {\n candidate: Candidate\n args: Record<string, unknown>\n}\n\n/** The one fallback constructor, so every early exit has the same shape. */\nfunction fallback(code: string): Decision {\n return { kind: 'fallback', code }\n}\n\n/**\n * Whitelist filter (rule 1).\n *\n * Fails the pipeline only when there was something to filter: an empty plan\n * must reach the trivial filter, where it is `guard-trivial`, not a whitelist\n * rejection.\n */\nfunction whitelisted(whitelist: ReadonlySet<string>): Filter {\n return (candidates) => {\n const kept = candidates.filter((candidate) => whitelist.has(candidate.tool))\n if (kept.length === 0 && candidates.length > 0) return fallback('tool-not-whitelisted')\n return kept\n }\n}\n\n/**\n * Trivial-candidate filter (rule 3).\n *\n * `isTrivial` is true for the empty guard list too, so this filter also turns\n * an empty plan into `guard-trivial`.\n */\nconst nonTrivial: Filter = (candidates) => {\n const kept = candidates.filter((candidate) => !isTrivial(candidate))\n return kept.length === 0 ? fallback('guard-trivial') : kept\n}\n\n/** Run filters left to right; the first decision ends the pipeline. */\nfunction narrow(candidates: Candidate[], filters: readonly Filter[]): Candidate[] | Decision {\n let kept = candidates\n for (const filter of filters) {\n const next = filter(kept)\n if (!Array.isArray(next)) return next\n kept = next\n }\n return kept\n}\n\n/**\n * Bind and verify each candidate (rule 4).\n *\n * Binding runs first: a candidate that cannot be bound is dropped before its\n * guards are ever evaluated, and the failure reason is intentionally discarded\n * — every dropped candidate is just one fewer choice, not a distinct fallback\n * for the whole plan. Guards are receipt-local to `stepId`; when that receipt\n * is absent nothing can be verified, so nothing survives.\n */\nfunction bindAndVerify(\n candidates: Candidate[],\n stepId: string,\n receipts: ReadonlyMap<string, CanonicalReceipt>,\n): Viable[] {\n const receipt = receipts.get(stepId)\n if (receipt === undefined) return []\n const survivors: Viable[] = []\n for (const candidate of candidates) {\n const bound = bindArgs(candidate.args, receipts)\n if (!bound.ok) continue\n if (!evaluateAll(candidate.guards, receipt).ok) continue\n survivors.push({ candidate, args: bound.args })\n }\n return survivors\n}\n\n/**\n * Turn the survivor list into the decision (rule 5).\n *\n * Both outcomes carry the bound args, so the caller never has to bind again:\n * `commit` returns them directly, `ask-selector` returns a fresh candidate per\n * survivor and leaves the plan's objects untouched. The guard copy is one\n * level deep per guard because every `Guard` form is flat — its only nested\n * value, `json_equals.value`, is a scalar.\n */\nfunction resolve(survivors: Viable[]): Decision {\n const [only] = survivors\n if (only === undefined) return fallback('no-candidate')\n if (survivors.length > 1) {\n return {\n kind: 'ask-selector',\n candidates: survivors.map((entry) => ({\n ...entry.candidate,\n args: entry.args,\n guards: entry.candidate.guards.map((guard) => ({ ...guard })),\n })),\n }\n }\n return { kind: 'commit', candidateId: only.candidate.id, args: only.args }\n}\n\n/**\n * Decide what to do with one parsed plan.\n *\n * `shadow` skips the whitelist filter (design §5.2-5) so the shadow week can\n * record substitution potential for every tool family; everything else is the\n * same path. The function is synchronous and side-effect free.\n */\nexport function decide(input: {\n plan: Plan\n stepId: string\n receipts: ReadonlyMap<string, CanonicalReceipt>\n whitelist: ReadonlySet<string>\n shadow?: boolean\n}): Decision {\n const filters: readonly Filter[] = input.shadow\n ? [nonTrivial]\n : [whitelisted(input.whitelist), nonTrivial]\n const narrowed = narrow(input.plan.steps, filters)\n if (!Array.isArray(narrowed)) return narrowed\n return resolve(bindAndVerify(narrowed, input.stepId, input.receipts))\n}\n"]}
1
+ {"version":3,"file":"decide.js","sourceRoot":"","sources":["../../src/gate/decide.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAyDG;AAGH,OAAO,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAA;AACvC,OAAO,EAAE,WAAW,EAAE,MAAM,YAAY,CAAA;AACxC,OAAO,EAAE,SAAS,EAA6B,MAAM,WAAW,CAAA;AAiBhE,4EAA4E;AAC5E,SAAS,QAAQ,CAAC,IAAY;IAC5B,OAAO,EAAE,IAAI,EAAE,UAAU,EAAE,IAAI,EAAE,CAAA;AACnC,CAAC;AAED;;;;;;GAMG;AACH,SAAS,WAAW,CAAC,SAA8B;IACjD,OAAO,CAAC,UAAU,EAAE,EAAE;QACpB,MAAM,IAAI,GAAG,UAAU,CAAC,MAAM,CAAC,CAAC,SAAS,EAAE,EAAE,CAAC,SAAS,CAAC,GAAG,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,CAAA;QAC5E,IAAI,IAAI,CAAC,MAAM,KAAK,CAAC,IAAI,UAAU,CAAC,MAAM,GAAG,CAAC;YAAE,OAAO,QAAQ,CAAC,sBAAsB,CAAC,CAAA;QACvF,OAAO,IAAI,CAAA;IACb,CAAC,CAAA;AACH,CAAC;AAED;;;;;;;;;;;;GAYG;AACH,SAAS,UAAU,CAAC,QAAmC;IACrD,OAAO,CAAC,UAAU,EAAE,EAAE,CACpB,UAAU,CAAC,MAAM,CAAC,CAAC,SAAS,EAAE,EAAE;QAC9B,IAAI,CAAC;YACH,OA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AAE,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC,CAAC;SACtE,CAAA;IACL,MAAM,QAAQ,GAAG,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,EAAE,OAAO,CAAC,CAAA;IAClD,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,QAAQ,CAAC;QAAE,OAAO,QAAQ,CAAA;IAC7C,OAAO,OAAO,CAAC,aAAa,CAAC,QAAQ,EAAE,KAAK,CAAC,MAAM,EAAE,KAAK,CAAC,QAAQ,CAAC,CAAC,CAAA;AACvE,CAAC","sourcesContent":["/**\n * Substitution decision orchestration: one parsed plan in, one decision out.\n *\n * This is the point where the gate stops describing alternatives and says what\n * to do next: commit to exactly one candidate, ask the selector to choose among\n * several, or fall back to the ordinary model turn with a code saying why. It\n * is a pure function over the plan, the receipts collected so far and the\n * whitelist — no model call, no I/O, no mutation of its inputs.\n *\n * The rule that matters most: it never guesses. Zero viable candidates is a\n * fallback with a reason, never a best-effort pick, and a candidate that fails\n * binding or a guard is dropped without a reason of its own — the plan-level\n * fallback code is the only thing the caller needs.\n *\n * Order is fixed and load-bearing:\n *\n * 1. **Whitelist first.** A candidate whose tool is not whitelisted is never\n * committed and never reaches the selector (design §5.2-5). When the plan\n * had candidates and none survives, the answer is `tool-not-whitelisted`.\n * An empty plan is not a whitelist failure: it falls through and lands in\n * `guard-trivial`, because \"nothing to verify\" is what that code means.\n * 2. **Trivial candidates next.** A candidate whose guards are only `ok: true`\n * has nothing to verify, so it is not substitution potential either. If\n * every survivor is trivial (including the empty plan, vacuously), the\n * answer is `guard-trivial`. **Step admission follows (row 7).** When the\n * caller supplies this step's `ResolvedToolSet` predicate, a candidate whose\n * tool it does not admit is dropped before the selector is paid for: the\n * host would reject its dispatch with `UNKNOWN_TOOL`. An emptied list is the\n * ordinary `no-candidate`.\n * 3. **Bind, then guard, each remaining candidate in plan order.** Binding\n * failure drops the candidate (it does not abort the plan); only a bound\n * candidate has its guards evaluated. Guards read the receipt for\n * `stepId` — the step that just arrived — and an absent receipt drops every\n * candidate rather than guessing one. A `$public` template naming a node\n * that does not exist is `unresolvable` inside binding, not a separate\n * existence check here: `receipts` only ever holds steps that already ran.\n * 4. **Count.** None → `no-candidate`; one → `commit` with the *bound* args;\n * several → `ask-selector` carrying each survivor as a fresh candidate whose\n * args are its bound tree. Every decision therefore hands the caller\n * executable args — the selector path and the commit path cannot diverge by\n * binding twice, and a `$public` template never leaves this module.\n *\n * Shadow mode (`shadow: true`) skips the whitelist. The shadow week records\n * substitution *potential* for every tool family (design §5.2-5: 影子期替换\n * 不设白名单,全量记账), and a whitelist-limited shadow would only ever measure\n * the read/grep/glob three. Trivial candidates are still dropped in shadow: a\n * trivial guard means there was nothing to verify, so it is not potential.\n *\n * The returned `ask-selector.candidates` is a new array of fresh candidate\n * objects: each carries the bound args and a copied `guards` array whose guard\n * objects are copied too, so neither the plan's candidate objects, their args,\n * nor their guards can be changed through the decision. (`args` is the only\n * thing that reaches the tool call; the guard copy makes the isolation claim\n * true at every depth the caller can reach.) `commit.args` is the same freshly\n * bound tree. A `$public` template never survives into a decision.\n *\n * @module dsh-boost/gate/decide\n */\n\nimport type { CanonicalReceipt } from '../projection/canonicalise.js'\nimport { bindArgs } from './binding.js'\nimport { evaluateAll } from './guard.js'\nimport { isTrivial, type Candidate, type Plan } from './plan.js'\n\n/** What the gate decided to do with the plan. */\nexport type Decision =\n | { kind: 'commit'; candidateId: string; args: Record<string, unknown> }\n | { kind: 'ask-selector'; candidates: Candidate[] }\n | { kind: 'fallback'; code: string }\n\n/** A filter narrows the candidate list, or ends the pipeline with a decision. */\ntype Filter = (candidates: Candidate[]) => Candidate[] | Decision\n\n/** One candidate that passed binding and its guards, with the args to run it. */\ninterface Viable {\n candidate: Candidate\n args: Record<string, unknown>\n}\n\n/** The one fallback constructor, so every early exit has the same shape. */\nfunction fallback(code: string): Decision {\n return { kind: 'fallback', code }\n}\n\n/**\n * Whitelist filter (rule 1).\n *\n * Fails the pipeline only when there was something to filter: an empty plan\n * must reach the trivial filter, where it is `guard-trivial`, not a whitelist\n * rejection.\n */\nfunction whitelisted(whitelist: ReadonlySet<string>): Filter {\n return (candidates) => {\n const kept = candidates.filter((candidate) => whitelist.has(candidate.tool))\n if (kept.length === 0 && candidates.length > 0) return fallback('tool-not-whitelisted')\n return kept\n }\n}\n\n/**\n * Step-admission filter (row 7).\n *\n * The host's `ResolvedToolSet` is this step's dispatch admission. A candidate\n * whose tool it does not list would be rejected with `UNKNOWN_TOOL` after the\n * plugin had already paid for the selector and taken a budget step, so it is\n * dropped here, before both. An emptied list falls through to `no-candidate`:\n * the plan had candidates and none survived, exactly like a failed guard.\n *\n * A throwing membership read drops that candidate: an unverifiable tool is not\n * one this plugin may dispatch, and dropping under-reports instead of producing\n * a call the host rejects.\n */\nfunction admittedBy(admitted: (tool: string) => boolean): Filter {\n return (candidates) =>\n candidates.filter((candidate) => {\n try {\n return admitted(candidate.tool)\n } catch {\n return false\n }\n })\n}\n\n/**\n * Trivial-candidate filter (rule 3).\n *\n * `isTrivial` is true for the empty guard list too, so this filter also turns\n * an empty plan into `guard-trivial`.\n */\nconst nonTrivial: Filter = (candidates) => {\n const kept = candidates.filter((candidate) => !isTrivial(candidate))\n return kept.length === 0 ? fallback('guard-trivial') : kept\n}\n\n/** Run filters left to right; the first decision ends the pipeline. */\nfunction narrow(candidates: Candidate[], filters: readonly Filter[]): Candidate[] | Decision {\n let kept = candidates\n for (const filter of filters) {\n const next = filter(kept)\n if (!Array.isArray(next)) return next\n kept = next\n }\n return kept\n}\n\n/**\n * Bind and verify each candidate (rule 4).\n *\n * Binding runs first: a candidate that cannot be bound is dropped before its\n * guards are ever evaluated, and the failure reason is intentionally discarded\n * — every dropped candidate is just one fewer choice, not a distinct fallback\n * for the whole plan. Guards are receipt-local to `stepId`; when that receipt\n * is absent nothing can be verified, so nothing survives.\n */\nfunction bindAndVerify(\n candidates: Candidate[],\n stepId: string,\n receipts: ReadonlyMap<string, CanonicalReceipt>,\n): Viable[] {\n const receipt = receipts.get(stepId)\n if (receipt === undefined) return []\n const survivors: Viable[] = []\n for (const candidate of candidates) {\n const bound = bindArgs(candidate.args, receipts)\n if (!bound.ok) continue\n if (!evaluateAll(candidate.guards, receipt).ok) continue\n survivors.push({ candidate, args: bound.args })\n }\n return survivors\n}\n\n/**\n * Turn the survivor list into the decision (rule 5).\n *\n * Both outcomes carry the bound args, so the caller never has to bind again:\n * `commit` returns them directly, `ask-selector` returns a fresh candidate per\n * survivor and leaves the plan's objects untouched. The guard copy is one\n * level deep per guard because every `Guard` form is flat — its only nested\n * value, `json_equals.value`, is a scalar.\n */\nfunction resolve(survivors: Viable[]): Decision {\n const [only] = survivors\n if (only === undefined) return fallback('no-candidate')\n if (survivors.length > 1) {\n return {\n kind: 'ask-selector',\n candidates: survivors.map((entry) => ({\n ...entry.candidate,\n args: entry.args,\n guards: entry.candidate.guards.map((guard) => ({ ...guard })),\n })),\n }\n }\n return { kind: 'commit', candidateId: only.candidate.id, args: only.args }\n}\n\n/**\n * Decide what to do with one parsed plan.\n *\n * `shadow` skips the whitelist filter (design §5.2-5) so the shadow week can\n * record substitution potential for every tool family; everything else is the\n * same path. The function is synchronous and side-effect free.\n */\nexport function decide(input: {\n plan: Plan\n stepId: string\n receipts: ReadonlyMap<string, CanonicalReceipt>\n whitelist: ReadonlySet<string>\n shadow?: boolean\n /**\n * Whether this step's `ResolvedToolSet` admits a tool (row 7).\n *\n * `undefined` means the admission evidence is unavailable (an embedded or\n * legacy call site); the caller proceeds and records the missing evidence\n * itself, because refusing on absence would silently disable substitution on\n * paths it cannot enumerate. Shadow mode ignores the predicate: shadow\n * measures potential, not dispatchability.\n */\n admitted?: (tool: string) => boolean\n}): Decision {\n const filters: readonly Filter[] = input.shadow\n ? [nonTrivial]\n : [\n whitelisted(input.whitelist),\n nonTrivial,\n ...(input.admitted === undefined ? [] : [admittedBy(input.admitted)]),\n ]\n const narrowed = narrow(input.plan.steps, filters)\n if (!Array.isArray(narrowed)) return narrowed\n return resolve(bindAndVerify(narrowed, input.stepId, input.receipts))\n}\n"]}