@thincoder/core 0.11.1 → 0.11.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 (333) hide show
  1. package/CHANGELOG.md +46 -2
  2. package/advisor/convergence.mjs +34 -3
  3. package/advisor/loop.mjs +42 -10
  4. package/advisor/messages.mjs +42 -25
  5. package/advisor/project-context.mjs +171 -42
  6. package/advisor/run.mjs +7 -4
  7. package/advisor.mjs +29 -43
  8. package/agent/batch-attribution.mjs +87 -0
  9. package/agent/batch-changed-surface.mjs +129 -0
  10. package/agent/completion.mjs +44 -3
  11. package/agent/dispatch-gates.mjs +6 -0
  12. package/agent/dispatch.mjs +8 -3
  13. package/agent/family-tools.mjs +27 -12
  14. package/agent/helpers.mjs +122 -1
  15. package/agent/offload.mjs +25 -29
  16. package/agent/post-turn.mjs +24 -10
  17. package/agent/record-results.mjs +18 -1
  18. package/agent/run-stages.mjs +77 -32
  19. package/agent/run-start.mjs +37 -0
  20. package/agent/setup-reminders.mjs +9 -2
  21. package/agent/setup.mjs +24 -11
  22. package/agent/spawn-child.mjs +38 -1
  23. package/agent/timers.mjs +5 -3
  24. package/agent/turn-loop.mjs +30 -5
  25. package/agent/turn-projection.mjs +386 -0
  26. package/agent/turn-task-state.mjs +274 -0
  27. package/agent/turn-tool-process.mjs +168 -0
  28. package/agent/write-gate-ledger.mjs +569 -0
  29. package/agent/write-gate.mjs +29 -352
  30. package/agent-tools/advisor-async.mjs +29 -169
  31. package/agent-tools/advisor-launch.mjs +178 -0
  32. package/agent-tools/advisor-settle.mjs +28 -1
  33. package/agent-tools/advisor.mjs +36 -47
  34. package/agent-tools/audit-block.mjs +6 -6
  35. package/agent-tools/batch-closeout.mjs +273 -35
  36. package/agent-tools/batch-gate.mjs +142 -342
  37. package/agent-tools/batch-ledger-bind.mjs +226 -17
  38. package/agent-tools/batch-ledger-view.mjs +109 -0
  39. package/agent-tools/batch-lifecycle.mjs +169 -46
  40. package/agent-tools/batch-paths.mjs +29 -8
  41. package/agent-tools/batch-record-write.mjs +417 -0
  42. package/agent-tools/batch-regions.mjs +215 -0
  43. package/agent-tools/batch-reopen.mjs +23 -11
  44. package/agent-tools/batch-segment-vocab.mjs +379 -0
  45. package/agent-tools/batch-skeleton.mjs +192 -239
  46. package/agent-tools/batch-supersede.mjs +232 -0
  47. package/agent-tools/batch-tier-gate.mjs +297 -0
  48. package/agent-tools/batch.mjs +182 -439
  49. package/agent-tools/consult.mjs +7 -4
  50. package/agent-tools/context.mjs +44 -17
  51. package/agent-tools/design-review-record.mjs +225 -0
  52. package/agent-tools/design-slots.mjs +1 -1
  53. package/agent-tools/design-token.mjs +279 -81
  54. package/agent-tools/doc-check.mjs +43 -33
  55. package/agent-tools/doc-graph.mjs +140 -0
  56. package/agent-tools/eng.mjs +9 -8
  57. package/agent-tools/escalate-async.mjs +2 -2
  58. package/agent-tools/manifest.mjs +34 -18
  59. package/agent-tools/read-history.mjs +112 -11
  60. package/agent-tools/review-facts.mjs +10 -3
  61. package/agent-tools/settings.mjs +23 -2
  62. package/agent-tools/spawn-gates.mjs +9 -8
  63. package/agent-tools/ssh-session.mjs +2 -2
  64. package/agent-tools/ssh-text.mjs +155 -0
  65. package/agent-tools/ssh-transport.mjs +19 -148
  66. package/agent-tools/subagent-actions-query.mjs +10 -6
  67. package/agent-tools/subagent-async.mjs +8 -9
  68. package/agent-tools/subagent-brief.mjs +76 -0
  69. package/agent-tools/subagent-design-token.mjs +168 -0
  70. package/agent-tools/subagent-run.mjs +1 -1
  71. package/agent-tools/subagent-scheduler.mjs +4 -4
  72. package/agent-tools/subagent-spawn.mjs +90 -110
  73. package/agent-tools/subagent.mjs +11 -10
  74. package/agent-tools/taskbook-block.mjs +94 -0
  75. package/agent-tools/timer.mjs +12 -8
  76. package/agent-tools/verify.mjs +13 -4
  77. package/agent-tools.mjs +7 -3
  78. package/agent.mjs +20 -1
  79. package/attachments.mjs +3 -3
  80. package/browser/actions.mjs +9 -3
  81. package/browser/cdp.mjs +45 -17
  82. package/browser/launch.mjs +25 -43
  83. package/browser/pool.mjs +299 -0
  84. package/browser/queue.mjs +2 -0
  85. package/browser/session-state.mjs +450 -0
  86. package/browser/session.mjs +127 -151
  87. package/browser/snapshot.mjs +89 -0
  88. package/client-identity.mjs +1 -1
  89. package/config-defaults.mjs +2 -1
  90. package/config-migrate.mjs +40 -0
  91. package/config-normalize.mjs +28 -2
  92. package/config-reload.mjs +59 -0
  93. package/config.mjs +62 -98
  94. package/context-degrade.mjs +38 -10
  95. package/context-echo.mjs +11 -0
  96. package/context.mjs +149 -83
  97. package/conventions.mjs +11 -9
  98. package/declaration.mjs +31 -5
  99. package/declared-repos.mjs +94 -0
  100. package/doc-check/doc-names.mjs +73 -0
  101. package/doc-check/doc-tokens.mjs +110 -0
  102. package/doc-check/existence.mjs +160 -0
  103. package/doc-check/index.mjs +309 -213
  104. package/doc-check/line-refs.mjs +27 -101
  105. package/doc-check/paragraph.mjs +218 -102
  106. package/doc-graph/anchors.mjs +474 -0
  107. package/doc-graph/doc-batch-face.mjs +59 -0
  108. package/doc-graph/doc-suffix.mjs +27 -0
  109. package/doc-graph/graph-tokens.mjs +160 -0
  110. package/doc-graph.mjs +778 -0
  111. package/explore-distill.mjs +11 -5
  112. package/i18n.mjs +1 -1
  113. package/instance-inbox-watch.mjs +272 -0
  114. package/instance-inbox.mjs +218 -0
  115. package/instance-registry.mjs +179 -0
  116. package/knowledge/README.md +3 -0
  117. package/knowledge/prompt-resources.md +6 -0
  118. package/ledger-close-proof.mjs +100 -49
  119. package/ledger-close.mjs +188 -0
  120. package/ledger-cmd.mjs +47 -91
  121. package/ledger-consistency.mjs +113 -0
  122. package/ledger-db.mjs +47 -15
  123. package/ledger-executors.mjs +1 -1
  124. package/ledger-tools.mjs +78 -19
  125. package/ledger-write-ops.mjs +130 -41
  126. package/ledger.mjs +1 -1
  127. package/manifest-discovery.mjs +3 -1
  128. package/manifest-schema.mjs +27 -5
  129. package/memory/schema.mjs +2 -2
  130. package/package.json +3 -1
  131. package/path-resolve.mjs +338 -57
  132. package/prompt-files.mjs +91 -1
  133. package/prompt-overlays.mjs +9 -6
  134. package/prompts/advisor-design.md +62 -21
  135. package/prompts/advisor-round1.md +34 -1
  136. package/prompts/advisor-round2.md +40 -7
  137. package/prompts/advisor-round3.md +39 -6
  138. package/prompts/common.md +14 -387
  139. package/prompts/consult-base.md +5 -1
  140. package/prompts/discipline-engineering.md +226 -51
  141. package/prompts/discipline-normal.md +4 -255
  142. package/prompts/knowledge/business-gates.md +22 -0
  143. package/prompts/knowledge/decision-quality.md +23 -0
  144. package/prompts/knowledge/doc-lookup.md +35 -0
  145. package/prompts/knowledge/document-writing.md +51 -0
  146. package/prompts/knowledge/documentation-evaluation.md +56 -0
  147. package/prompts/knowledge/evidence-discipline.md +57 -0
  148. package/prompts/knowledge/normal-coding-workflow.md +104 -0
  149. package/prompts/knowledge/normal-delivery-collaboration.md +108 -0
  150. package/prompts/knowledge/normal-work-management.md +57 -0
  151. package/prompts/knowledge/product-security.md +23 -0
  152. package/prompts/knowledge/project-records.md +62 -0
  153. package/prompts/knowledge/tool-advisor.md +29 -0
  154. package/prompts/knowledge/tool-apply-patch.md +18 -0
  155. package/prompts/knowledge/tool-bash.md +39 -0
  156. package/prompts/knowledge/tool-batch-eng-coder.md +12 -0
  157. package/prompts/knowledge/tool-batch-eng-designer.md +12 -0
  158. package/prompts/knowledge/tool-batch-review.md +12 -0
  159. package/prompts/knowledge/tool-batch.md +80 -0
  160. package/prompts/knowledge/tool-browser.md +57 -0
  161. package/prompts/knowledge/tool-code-search.md +4 -0
  162. package/prompts/knowledge/tool-consult-start.md +12 -0
  163. package/prompts/knowledge/tool-consult-stop.md +6 -0
  164. package/prompts/knowledge/tool-context.md +6 -0
  165. package/prompts/knowledge/tool-delete.md +17 -0
  166. package/prompts/knowledge/tool-doc-check.md +70 -0
  167. package/prompts/knowledge/tool-doc-graph-read.md +20 -0
  168. package/prompts/knowledge/tool-doc-graph.md +49 -0
  169. package/prompts/knowledge/tool-doc-search.md +6 -0
  170. package/prompts/knowledge/tool-edit.md +38 -0
  171. package/prompts/knowledge/tool-eng.md +2 -0
  172. package/prompts/knowledge/tool-execute.md +16 -0
  173. package/prompts/knowledge/tool-fetch.md +12 -0
  174. package/prompts/knowledge/tool-file-ops.md +16 -0
  175. package/prompts/knowledge/tool-get-current-time.md +7 -0
  176. package/prompts/knowledge/tool-git-read.md +19 -0
  177. package/prompts/knowledge/tool-git.md +29 -0
  178. package/prompts/knowledge/tool-glob.md +15 -0
  179. package/prompts/knowledge/tool-goal.md +8 -0
  180. package/prompts/knowledge/tool-grep.md +18 -0
  181. package/prompts/knowledge/tool-hashline-edit.md +14 -0
  182. package/prompts/knowledge/tool-insert-after.md +15 -0
  183. package/prompts/knowledge/tool-instance-list.md +6 -0
  184. package/prompts/knowledge/tool-instance-send.md +10 -0
  185. package/prompts/knowledge/tool-knowledge.md +18 -0
  186. package/prompts/knowledge/tool-ledger-read.md +35 -0
  187. package/prompts/knowledge/tool-ledger.md +42 -0
  188. package/prompts/knowledge/tool-lint.md +16 -0
  189. package/prompts/knowledge/tool-ls.md +13 -0
  190. package/prompts/knowledge/tool-lsp.md +11 -0
  191. package/prompts/knowledge/tool-main-history.md +2 -0
  192. package/prompts/knowledge/tool-manifest-read.md +14 -0
  193. package/prompts/knowledge/tool-manifest.md +31 -0
  194. package/prompts/knowledge/tool-memory-read.md +20 -0
  195. package/prompts/knowledge/tool-memory.md +15 -0
  196. package/prompts/knowledge/tool-notify-parent.md +12 -0
  197. package/prompts/knowledge/tool-operations.md +114 -0
  198. package/prompts/knowledge/tool-peer-instances.md +2 -0
  199. package/prompts/knowledge/tool-plan.md +6 -0
  200. package/prompts/knowledge/tool-process-read.md +13 -0
  201. package/prompts/knowledge/tool-process.md +15 -0
  202. package/prompts/knowledge/tool-question.md +16 -0
  203. package/prompts/knowledge/tool-read-history-batch.md +22 -0
  204. package/prompts/knowledge/tool-read-history.md +36 -0
  205. package/prompts/knowledge/tool-read-image.md +11 -0
  206. package/prompts/knowledge/tool-read.md +21 -0
  207. package/prompts/knowledge/tool-recent-changes.md +6 -0
  208. package/prompts/knowledge/tool-repo-outline.md +4 -0
  209. package/prompts/knowledge/tool-settings-read.md +12 -0
  210. package/prompts/knowledge/tool-settings.md +18 -0
  211. package/prompts/knowledge/tool-skill.md +6 -0
  212. package/prompts/knowledge/tool-ssh.md +52 -0
  213. package/prompts/knowledge/tool-subagent.md +59 -0
  214. package/prompts/knowledge/tool-task.md +12 -0
  215. package/prompts/knowledge/tool-team-ledger-read.md +11 -0
  216. package/prompts/knowledge/tool-team-ledger.md +11 -0
  217. package/prompts/knowledge/tool-timer.md +23 -0
  218. package/prompts/knowledge/tool-tree.md +14 -0
  219. package/prompts/knowledge/tool-verify.md +19 -0
  220. package/prompts/knowledge/tool-wait-for.md +25 -0
  221. package/prompts/knowledge/tool-websearch.md +19 -0
  222. package/prompts/knowledge/tool-write.md +9 -0
  223. package/prompts/knowledge/upstream-protocol.md +43 -0
  224. package/prompts/persona-eng-coder.md +21 -3
  225. package/prompts/persona-eng-designer.md +131 -169
  226. package/prompts/persona-engineering.md +142 -84
  227. package/prompts/persona-explore.md +1 -1
  228. package/prompts/persona-plan.md +5 -1
  229. package/prompts/subagent-base.md +2 -0
  230. package/provider/anthropic.mjs +6 -4
  231. package/provider/core.mjs +3 -2
  232. package/provider/errors.mjs +29 -4
  233. package/provider/google.mjs +24 -7
  234. package/provider/responses.mjs +3 -1
  235. package/provider-flows.mjs +2 -2
  236. package/session-index-build.mjs +1 -1
  237. package/session-index-pass.mjs +1 -1
  238. package/session-index-query.mjs +1 -1
  239. package/session-index.mjs +1 -1
  240. package/session-lifecycle.mjs +72 -17
  241. package/session-slot-write.mjs +37 -5
  242. package/session.mjs +24 -8
  243. package/skip-dirs.mjs +2 -2
  244. package/team-ledger.mjs +13 -9
  245. package/token-ttl.mjs +73 -4
  246. package/token-window.mjs +167 -33
  247. package/tool-docs/advisor.md +2 -27
  248. package/tool-docs/apply_patch.md +1 -15
  249. package/tool-docs/bash.md +2 -41
  250. package/tool-docs/batch-eng-coder.md +3 -0
  251. package/tool-docs/batch-eng-designer.md +3 -0
  252. package/tool-docs/batch-review.md +3 -0
  253. package/tool-docs/batch.md +2 -84
  254. package/tool-docs/browser.md +2 -49
  255. package/tool-docs/code_search.md +2 -2
  256. package/tool-docs/consult_start.md +2 -8
  257. package/tool-docs/consult_stop.md +2 -4
  258. package/tool-docs/context.md +1 -5
  259. package/tool-docs/delete.md +2 -17
  260. package/tool-docs/doc_check.md +2 -107
  261. package/tool-docs/doc_graph-read.md +3 -0
  262. package/tool-docs/doc_graph.md +3 -0
  263. package/tool-docs/doc_search.md +2 -4
  264. package/tool-docs/edit.md +1 -38
  265. package/tool-docs/eng.md +3 -1
  266. package/tool-docs/execute.md +2 -18
  267. package/tool-docs/fetch.md +2 -14
  268. package/tool-docs/file_ops.md +2 -18
  269. package/tool-docs/get_current_time.md +1 -6
  270. package/tool-docs/git-read.md +3 -0
  271. package/tool-docs/git.md +2 -35
  272. package/tool-docs/glob.md +2 -10
  273. package/tool-docs/goal.md +1 -6
  274. package/tool-docs/grep.md +2 -18
  275. package/tool-docs/hashline_edit.md +2 -15
  276. package/tool-docs/insert_after.md +2 -16
  277. package/tool-docs/instance_list.md +3 -0
  278. package/tool-docs/instance_send.md +3 -0
  279. package/tool-docs/knowledge.md +3 -0
  280. package/tool-docs/ledger-read.md +3 -0
  281. package/tool-docs/ledger.md +3 -8
  282. package/tool-docs/lint.md +2 -10
  283. package/tool-docs/ls.md +2 -11
  284. package/tool-docs/lsp.md +2 -9
  285. package/tool-docs/main_history.md +3 -1
  286. package/tool-docs/manifest-read.md +2 -8
  287. package/tool-docs/manifest.md +2 -35
  288. package/tool-docs/memory-read.md +3 -0
  289. package/tool-docs/memory.md +2 -20
  290. package/tool-docs/notify_parent.md +2 -13
  291. package/tool-docs/peer_instances.md +3 -1
  292. package/tool-docs/plan.md +1 -5
  293. package/tool-docs/process-read.md +3 -0
  294. package/tool-docs/process.md +2 -13
  295. package/tool-docs/question.md +3 -17
  296. package/tool-docs/read.md +2 -19
  297. package/tool-docs/read_history-batch.md +3 -0
  298. package/tool-docs/read_history.md +2 -18
  299. package/tool-docs/read_image.md +2 -9
  300. package/tool-docs/recent_changes.md +2 -2
  301. package/tool-docs/repo_outline.md +2 -2
  302. package/tool-docs/settings-read.md +3 -0
  303. package/tool-docs/settings.md +1 -12
  304. package/tool-docs/skill.md +2 -6
  305. package/tool-docs/ssh.md +1 -62
  306. package/tool-docs/subagent.md +2 -100
  307. package/tool-docs/task.md +1 -7
  308. package/tool-docs/team_ledger-read.md +3 -0
  309. package/tool-docs/team_ledger.md +3 -9
  310. package/tool-docs/timer.md +2 -19
  311. package/tool-docs/tree.md +2 -13
  312. package/tool-docs/verify.md +2 -12
  313. package/tool-docs/wait_for.md +2 -32
  314. package/tool-docs/websearch.md +2 -19
  315. package/tool-docs/write.md +2 -12
  316. package/tools/browser.mjs +52 -7
  317. package/tools/doc-write-gate.mjs +73 -0
  318. package/tools/edit-batch.mjs +170 -92
  319. package/tools/edit-diff.mjs +78 -62
  320. package/tools/edit-receipt.mjs +39 -0
  321. package/tools/execute.mjs +1 -1
  322. package/tools/file.mjs +16 -8
  323. package/tools/git.mjs +24 -9
  324. package/tools/index.mjs +6 -0
  325. package/tools/knowledge.mjs +143 -0
  326. package/tools/linter.mjs +3 -3
  327. package/tools/ops.mjs +3 -1
  328. package/tools/patch.mjs +123 -43
  329. package/tools/shared.mjs +28 -27
  330. package/tools/write-gate-params.mjs +31 -0
  331. package/tools/write-path.mjs +16 -4
  332. package/window-policy.mjs +203 -0
  333. package/doc-check/anchors.mjs +0 -235
package/token-ttl.mjs CHANGED
@@ -22,7 +22,9 @@
22
22
  * slot 残留 engDesignToken → 迁入 Map,此后不写不读镜像)。
23
23
  * - **§10(2026-10-26)**:批次归属旁列 `engDesignTokenBatches`(designId → 批档绝对路径)与
24
24
  * 槽多槽表**同点序列化 / 同拍恢复 / 同处落盘**;轻读面 = `readEngTokenBatchesFromSlot`。
25
- * token 值形零改(仍 `<uuid>:<expiryMs>`)——旁列只承载归属,不承载授权。
25
+ * - **§10.2(2026-11-12)**:评审封印旁列 `engDesignTokenSeals`(designId → `{ hash, docs, docHashes }`)同点序列化 /
26
+ * 同拍恢复 / 同处落盘;轻读面 = `readEngTokenSealsFromSlot`(与批归属同形兄弟、同一两形读法)。
27
+ * token 值形零改(仍 `<uuid>:<expiryMs>`)——两条旁列只承载归属与版本,不承载授权。
26
28
  *
27
29
  * 依赖方向:本模块只 import 底层槽 I/O(session-slots.mjs 原语 + session-guard.mjs 轮转
28
30
  * 守卫)——session.mjs 同时 import 本模块(engTokenSlotFields/restoreEngTokens),形成
@@ -112,8 +114,9 @@ export function purgeExpiredDesignTokens(agent) {
112
114
  * NO field,不从上次 save 复活槽。
113
115
  * DESIGN-TOKEN-SETTLEMENT D3(2026-09-08):单值镜像 `engDesignToken` 退役——
114
116
  * saveSession 不再写镜像字段(AC3 零写);只产多槽表 engDesignTokens。
115
- * 批次归属旁列 `engDesignTokenBatches`(DESIGN-TOKEN-SETTLEMENT §10)同处序列化——
116
- * 与槽表并列、同空态语义(空表 ⇒ undefined ⇒ 字段不落盘);承载归属,不承载恢复。 */
117
+ * 批次归属旁列 `engDesignTokenBatches`(DESIGN-TOKEN-SETTLEMENT §10)与评审封印旁列
118
+ * `engDesignTokenSeals`(§10.2)同处序列化——与槽表并列、同空态语义(空表 ⇒ undefined ⇒
119
+ * 字段不落盘);承载归属与版本,不承载恢复。 */
117
120
  export function engTokenSlotFields(agent) {
118
121
  return {
119
122
  engDesignTokens: agent._engDesignTokens instanceof Map && agent._engDesignTokens.size > 0
@@ -122,6 +125,10 @@ export function engTokenSlotFields(agent) {
122
125
  engDesignTokenBatches: agent._engDesignTokenBatches instanceof Map && agent._engDesignTokenBatches.size > 0
123
126
  ? Object.fromEntries(agent._engDesignTokenBatches)
124
127
  : undefined,
128
+ // 评审封印旁列(§10.2)同处序列化——与槽表、批归属并列为第三个槽字段,空表 ⇒ undefined ⇒ 字段不落盘。
129
+ engDesignTokenSeals: agent._engDesignTokenSeals instanceof Map && agent._engDesignTokenSeals.size > 0
130
+ ? Object.fromEntries(agent._engDesignTokenSeals)
131
+ : undefined,
125
132
  }
126
133
  }
127
134
 
@@ -169,6 +176,26 @@ export function restoreEngTokens(agent, data) {
169
176
  }
170
177
  if (batches.size > 0) agent._engDesignTokenBatches = batches
171
178
  else delete agent._engDesignTokenBatches
179
+ // 评审封印旁列同拍读入(§10.2):值 = `{ hash, docs, docHashes }`(被审档绝对路径清单 + 组合 sha256 +
180
+ // 逐档 `[{ path, hash }]`——逐档列只服务拒文点名,旧行没有它时保留缺席,不补不猜)。
181
+ // 只收形状完整的行——缺 `hash` ∥ `docs` 不是清单 ⇒ 闸面按「无封印值」判(旧槽同层降级)。
182
+ const seals = new Map()
183
+ if (data.engDesignTokenSeals && typeof data.engDesignTokenSeals === "object" && !Array.isArray(data.engDesignTokenSeals)) {
184
+ for (const [id, s] of Object.entries(data.engDesignTokenSeals)) {
185
+ if (s && typeof s === "object" && !Array.isArray(s) && typeof s.hash === "string"
186
+ && Array.isArray(s.docs) && s.docs.every((p) => typeof p === "string")) {
187
+ const row = { hash: s.hash, docs: [...s.docs] }
188
+ // `docHashes` 不是成形判据(闸面 `hasSeal` 零改):形状不全 ⇒ 整列按「没有」处理,行照旧读入。
189
+ const docHashes = Array.isArray(s.docHashes)
190
+ ? s.docHashes.filter((d) => d && typeof d === "object" && typeof d.path === "string" && typeof d.hash === "string").map((d) => ({ path: d.path, hash: d.hash }))
191
+ : null
192
+ if (docHashes) row.docHashes = docHashes
193
+ seals.set(id, row)
194
+ }
195
+ }
196
+ }
197
+ if (seals.size > 0) agent._engDesignTokenSeals = seals
198
+ else delete agent._engDesignTokenSeals
172
199
  let droppedDesignTokens = 0
173
200
  for (const id of before) if (!map.has(id)) droppedDesignTokens++
174
201
  return { droppedDesignTokens }
@@ -246,6 +273,41 @@ export function readEngTokenBatchesFromSlot(agent, { strict = false } = {}) {
246
273
  }
247
274
  }
248
275
 
276
+ /** 读当前会话槽文件的**评审封印**旁列(DESIGN-TOKEN-SETTLEMENT §10.2——不做 TTL 过滤、不改盘)。
277
+ * 与 `readEngTokenBatchesFromSlot` 同形兄弟(同一轻读形、同一两形读法)——两者不能合成一个函数:
278
+ * 字段名硬编码是既有读者的形状,合并就得让每个读者自己再筛字段。
279
+ * **两形**:`strict:false`(缺省)读不到 ⇒ `null`;`strict:true`(闸面)读不到 ⇒ **抛**——派单侧
280
+ * 不能在「封印读不到」时落进「无封印值 ⇒ 不拦」。
281
+ * 判据 = **「没有」与「读不到」分清**:无槽号 ∥ 文件不存在(`ENOENT`)∥ 无该字段 ⇒ 空集(合法缺省,
282
+ * 两形同);其余 I/O 错 ∥ `JSON.parse` 失败 ⇒ 宽容形 `null` / 严格形抛。
283
+ * 槽号解析在 `try` 之外:manifest 层的「读不到」自带 manifest 坐标,不被重包成封印读失败。
284
+ * 返回 {designId: {hash, docs}} 对象或 null。 */
285
+ export function readEngTokenSealsFromSlot(agent, { strict = false } = {}) {
286
+ const slot = currentSlotNoReadOnly(agent, { strict })
287
+ if (slot == null) return null
288
+ let p = "(unresolved slot path)"
289
+ try {
290
+ p = slotPath(agent.cwd, slot)
291
+ let raw
292
+ try {
293
+ raw = readFileSync(p, "utf8")
294
+ } catch (e) {
295
+ if (e?.code === "ENOENT") return null // 「没有」:文件不存在——合法缺省
296
+ throw e // 「读不到」:其余 I/O 错交外层按读形处置
297
+ }
298
+ const data = JSON.parse(raw)
299
+ return (data && typeof data === "object" && !Array.isArray(data.engDesignTokenSeals)
300
+ && data.engDesignTokenSeals && typeof data.engDesignTokenSeals === "object")
301
+ ? data.engDesignTokenSeals
302
+ : null
303
+ } catch (e) {
304
+ if (strict) {
305
+ throw new Error(`readEngTokenSealsFromSlot: the session slot file's review-seal side column could NOT be read (${p}: ${e?.message ?? e}) — the eng-coder spawn cannot tell which version of the reviewed documents passed, so the spawn is refused with nothing written; fix the slot file or its permissions and retry.`)
306
+ }
307
+ return null
308
+ }
309
+ }
310
+
249
311
  /** 内存 miss 时从权威槽 reconcile(D2 spawn 门 + D3 dispatch 写门同源):把槽文件中
250
312
  * **未过期**项并进内存 Map(TTL 过滤保留——expired 不并入,fail-closed;格式/畸形串
251
313
  * 与 restoreEngTokens 同语义读回——门禁格式拒);槽无活项 → 内存原样。返回判定用 Map。
@@ -326,7 +388,7 @@ export function persistEngTokens(agent) {
326
388
  tasks: agent.tasks ?? [],
327
389
  planMode: agent.planMode ?? false,
328
390
  autoApprove: agent.autoApprove ?? false,
329
- engineering: agent.config?.agent?.engineering ?? false,
391
+ mode: agent.config?.agent?.mode ?? (agent.config?.agent?.engineering === true ? "engineering" : "normal"),
330
392
  goal: agent.goal ?? null,
331
393
  advisor: agent.config?.advisor ?? null,
332
394
  // 会话级档位(#441③ 键齐——与 `newSlotData` 规范结构 / `saveSession` 携带面同源:
@@ -339,12 +401,19 @@ export function persistEngTokens(agent) {
339
401
  createdBy: agent._slotCreatedBy ?? sessionEnd(),
340
402
  }
341
403
  }
404
+ // Migrate legacy slots at the same write: removing the old boolean without mode would lose
405
+ // the session's engineering state if the process stops before the next full saveSession.
406
+ data.mode = agent.config?.agent?.mode ?? (agent.config?.agent?.engineering === true ? "engineering" : "normal")
407
+ delete data.engineering
342
408
  const fields = engTokenSlotFields(agent)
343
409
  if (fields.engDesignTokens !== undefined) data.engDesignTokens = fields.engDesignTokens
344
410
  else delete data.engDesignTokens
345
411
  // 批次归属旁列逐字段复制同处(§10「保存 / 合并路径」第二处):空表 ⇒ 字段删(不从上次落盘复活)。
346
412
  if (fields.engDesignTokenBatches !== undefined) data.engDesignTokenBatches = fields.engDesignTokenBatches
347
413
  else delete data.engDesignTokenBatches
414
+ // 评审封印旁列同处落盘(§10.2 落点表「落盘」行):同一空态语义(空表 ⇒ 字段删)。
415
+ if (fields.engDesignTokenSeals !== undefined) data.engDesignTokenSeals = fields.engDesignTokenSeals
416
+ else delete data.engDesignTokenSeals
348
417
  // 单值镜像字段永不复写(D3 零写)——残留 engDesignToken 随本次写一并清(更快退役,
349
418
  // 杜绝 stale 镜像 + 空 Map 组合在下次 restore 二次迁移复活死 token 的边角)。
350
419
  delete data.engDesignToken
package/token-window.mjs CHANGED
@@ -2,15 +2,26 @@
2
2
  * token-window.mjs — token 计量 / 窗口 / 切割族(自 `context.mjs` **逐字迁出**)+ 上下文用量单源
3
3
  * (CONTEXT-COMPACTION.md §6.16.3 / §6.16.4 / §6.16.8 · context-tool 批 2026-09-21)。
4
4
  * 迁出三族(语义零改——原档越限在即,本批按 §6.16.8 拆出):① 计量面(IMAGE_TOKEN_ESTIMATE + `estimateTokens`);
5
- * ② 尾族(KEEP_HEAD 头注 + TAIL_BUDGET_FRACTION / SUMMARY_TOKEN_ESTIMATE / TAIL_FLOOR_MESSAGES + `keepTailSize` + `tailBudgetTokens`);
5
+ * ② 尾族(KEEP_HEAD 头注 + SUMMARY_TOKEN_ESTIMATE / TAIL_FLOOR_MESSAGES + `keepTailSize` + `tailBudgetTokens`);
6
6
  * ③ 切分与配对修复族(`splitHistory` + `repairedTailStart` + `tightenTailByBudget`)。
7
7
  * 新增族:`contextUsage`(与 `compressIfNeeded` 的 token 判定**同一函数**)· `historyReading` / `historyPercent`(状态行
8
8
  * 百分比——与 CLI ∥ VSC **同源**:一个实现点,端侧零自算式,消费面全是本档的投影)·
9
- * `collectStaleToolOutputs`(陈旧工具输出合格集)+ 门槛常量 `PRUNE_MIN_TOKENS`(**与合格集同住本档** ⇒ 消费方单向取用、零回指)。
10
- * 依赖面 = `provider/rate.mjs`(`estimateText` / `ESTIMATOR_VERSION`)+ `config.mjs`(`providerSpec` / `resolveCompactThreshold`)——**零 import 环**。
9
+ * `collectStaleToolOutputs`(陈旧工具输出合格集)+ 门槛常量 `PRUNE_MIN_TOKENS`(**与合格集同住本档** ⇒ 消费方单向取用、零回指)·
10
+ * `rebaseMeasured`(结构编辑后的实测基线重定,§3.1)。
11
+ * 窗口面(2026-11-14 · tiny 档上限批):本档一切窗口读数取**有效窗口** `effectiveWindow`(`window-policy.mjs` §2.1),
12
+ * 不再直读 `providerSpec().context`——`workMode` 无缺省(本档的窗口消费入口 `keepTailSize` ∥ `tailBudgetTokens` ∥
13
+ * `historyReading` ∥ `historyPercent` 各自拒收,`collectStaleToolOutputs` 透传同一拒绝;必填清单的单一出处 = §2.3)。
14
+ * 保留窗面(2026-11-14 · tool-output-retention 批):`splitHistory` 的第四参 `protectFrom` 必填、无缺省——尾起点不晚于
15
+ * 保留窗起点,压缩中段 ∥ prune 合格集 ∥ 尾部预算三面同源受益(`CONTEXT-COMPACTION.md` §1.2);起点由 `agent` 面的
16
+ * `retentionWindowStart` 按消息身份当刻解析,本档只收这个下标(纯函数面不读 agent 状态)。
17
+ * 尾预算面(2026-11-15 · window-reserve-and-baseline 批):`tailBudgetTokens` 由窗口比例改为**可用容量减法链**(§4)——
18
+ * 尾的宽度从压缩线倒推,不取窗口的比例。
19
+ * 依赖面 = `provider/rate.mjs`(`estimateText` / `ESTIMATOR_VERSION`)+ `config.mjs`(`resolveWorkMode` ∥ 有效窗口 ∥
20
+ * 预算族转口)+ `context-echo.mjs`(压缩注记那对固定文本,`NOTE_ESTIMATE` 量它)——**零 import 环**。
11
21
  */
12
22
  import { estimateText, ESTIMATOR_VERSION } from "./provider/rate.mjs"
13
- import { providerSpec, resolveCompactThreshold } from "./config.mjs"
23
+ import { resolveWorkMode, effectiveWindow, resolveCompactThreshold, policyBudget } from "./config.mjs"
24
+ import { COMPACTION_PREFIX, COMPACTION_PLACEHOLDER } from "./context-echo.mjs"
14
25
 
15
26
  const IMAGE_TOKEN_ESTIMATE = 2000 // rough estimate for image content tokens (CLI legacy 256 underestimated real image costs, delaying compaction)
16
27
 
@@ -37,23 +48,62 @@ const KEEP_HEAD = 0 // No dedicated head: earliest messages may be a COMPLETED e
37
48
  // sessions — keeping them verbatim anchored attention on stale work. Everything before the tail is
38
49
  // summarized (the summary itself distinguishes completed vs in-progress work; see SUMMARIZE_PROMPT).
39
50
  // Tail count formula (D4): window-adaptive (~30 msgs per 100K — old fixed 10 too thin on 1M), capped
40
- // at 40% of history; §6.4④ D-T1/D-T2 make the count only a CANDIDATE — a token budget (TAIL_BUDGET_FRACTION
41
- // × window − SUMMARY_TOKEN_ESTIMATE ≈1K, §6.9) tightens it over pair-safe boundaries when compaction runs,
42
- // never below TAIL_FLOOR_MESSAGES; ordinary sessions never reach it (D-T4: the trigger ratio lives in `config.mjs` — untouched here).
43
- const TAIL_BUDGET_FRACTION = 0.15
44
- export const SUMMARY_TOKEN_ESTIMATE = 1000 // §6.9: summary output target ~1K tokens — reserved from the 15%;§6.17 可达性门的 `note` 项同取本常量
51
+ // at 40% of history; §6.4④ D-T1/D-T2 make the count only a CANDIDATE — the token budget
52
+ // (`tailBudgetTokens`, §4) tightens it over pair-safe boundaries when compaction runs, never below
53
+ // TAIL_FLOOR_MESSAGES; ordinary sessions never reach it (D-T4: the trigger line is §2.2's).
54
+ export const SUMMARY_TOKEN_ESTIMATE = 1000 // §6.9: summary output target ~1K tokens — §6.17 可达性门的 `note` 项同取本常量
45
55
  const TAIL_FLOOR_MESSAGES = 10 // §6.4④ D-T2: the tail keeps ≥10 verbatim messages — floor beats budget
46
- export function keepTailSize(provider, historyLen) {
47
- // provider is guaranteed at every call site (runAgent always builds one); providerSpec
56
+
57
+ /** 注记 + 占位的估算(§4 减法链的末项,也是 §6.17 可达性门的 `note` 项):摘要正文取
58
+ * `SUMMARY_TOKEN_ESTIMATE`(§6.9 的 ~1K 目标),注记前缀与占位句按 §6.3 估算式——
59
+ * 零新常数、零新算式。两个固定文本的单源 = `context-echo.mjs`。 */
60
+ export const NOTE_ESTIMATE = SUMMARY_TOKEN_ESTIMATE + estimateTokens([
61
+ { role: "user", content: COMPACTION_PREFIX },
62
+ { role: "assistant", content: COMPACTION_PLACEHOLDER },
63
+ ])
64
+
65
+ /** 必填数值参数(§2.3 缺参即拒):无缺省,非法值在入口拒绝并点名参数。
66
+ * `fixedOverhead` 缺省等于把「这份 run 的固定开销」静默定成 0,尾会按一个装不下的量去切;
67
+ * `ratio` 缺省等于把校准后的阈值和未校准的估算放进同一次减法。 */
68
+ function assertTailArgs(fnName, fixedOverhead, ratio) {
69
+ if (!Number.isFinite(fixedOverhead) || fixedOverhead < 0) {
70
+ throw new Error(`${fnName}: \`fixedOverhead\` is required (system + tools token estimate, no default) — got ${JSON.stringify(fixedOverhead)}`)
71
+ }
72
+ if (!Number.isFinite(ratio) || ratio <= 0) {
73
+ throw new Error(`${fnName}: \`ratio\` is required (the calibration ratio from tokenRatioOf, no default) — got ${JSON.stringify(ratio)}`)
74
+ }
75
+ }
76
+
77
+ export function keepTailSize(provider, historyLen, workMode) {
78
+ // provider is guaranteed at every call site (runAgent always builds one); the window below
48
79
  // degrades to DEFAULT_SPEC (128K) only if provider is somehow absent — acceptable
49
80
  // because the 40% history cap still bounds the tail. providers[].context override
50
81
  // (K units) is honored here (PROVIDER.md §6.15 T-C2: tail formula follows the window).
51
- const ctxWindow = providerSpec(provider).context
82
+ // 窗口 = **有效窗口**(§2.1/§4):tiny 把窗口压小,尾部跟着变短,不另立一套尾部规则。
83
+ // 它是**条数上限**,不是预算:一条消息的体量跨三个数量级,条数推不出容量(§4)。
84
+ const ctxWindow = effectiveWindow(provider, workMode)
52
85
  return Math.min(Math.max(10, Math.floor((ctxWindow / 100_000) * 30)), Math.floor(historyLen * 0.4))
53
86
  }
54
- // §6.4④ D-T1 tail token budget: window×15% − summary ~1K — the compressed history segment (summary + placeholder + tail) lands ≈ 15% (B 口径 §6.4④).
55
- export function tailBudgetTokens(provider) {
56
- return Math.max(0, Math.floor(providerSpec(provider).context * TAIL_BUDGET_FRACTION) - SUMMARY_TOKEN_ESTIMATE)
87
+
88
+ /**
89
+ * 尾预算(§4)——可用容量倒推,不由窗口比例决定:
90
+ *
91
+ * ```text
92
+ * tailBudgetTokens(provider, workMode, fixedOverhead, ratio)
93
+ * = max(0, floor(threshold / ratio) − fixedOverhead − SUMMARY_TOKEN_ESTIMATE − 注记与占位估算)
94
+ * ```
95
+ *
96
+ * `threshold` 取 §2.2 的压缩线(有效窗口上现推),`fixedOverhead` = system + tools 的估算,
97
+ * `ratio` = 校准比(`tokenRatioOf`),末两项合并即 `NOTE_ESTIMATE`。
98
+ * 减法链把「压完之后落在 `threshold` 以下」写成构造而不是事后检查:压后的量是
99
+ * `(tail + 注记 + 固定开销) × ratio`,尾按上式取,它就落在 `threshold` 以内。
100
+ * 乘除 `ratio` 是必需的:`threshold` 是校准后的量,尾的估算要换到同一把尺上才可比。
101
+ * `fixedOverhead` ∥ `ratio` 都必填无缺省(§2.3)。
102
+ */
103
+ export function tailBudgetTokens(provider, workMode, fixedOverhead, ratio) {
104
+ assertTailArgs("tailBudgetTokens", fixedOverhead, ratio)
105
+ const threshold = policyBudget(provider, undefined, workMode).threshold
106
+ return Math.max(0, Math.floor(threshold / ratio) - fixedOverhead - SUMMARY_TOKEN_ESTIMATE - (NOTE_ESTIMATE - SUMMARY_TOKEN_ESTIMATE))
57
107
  }
58
108
 
59
109
  /**
@@ -63,8 +113,16 @@ export function tailBudgetTokens(provider) {
63
113
  * `budgetTokens` (optional, §6.4④ D-T1): when the candidate's estimate exceeds it, the boundary moves
64
114
  * forward until the tail fits — never below the D-T2 floor (10 msgs, or the candidate itself when
65
115
  * the 40% cap made it < 10 — short history).
116
+ * `protectFrom` (REQUIRED, no default — `CONTEXT-COMPACTION.md` §1.2 保留窗与保护尾): an index the tail
117
+ * must never start after, so the tool-process retention window always sits inside the protected tail.
118
+ * The relation is structural, not arithmetic — it holds for every window size and call-group count.
119
+ * No retention window ⇒ the caller passes `history.length` (== no tightening). A default here would
120
+ * decide the caller's protection amount for it, the very silent trade-off §1.2 removes.
66
121
  */
67
- export function splitHistory(history, keepTail, budgetTokens = null) {
122
+ export function splitHistory(history, keepTail, budgetTokens = null, protectFrom) {
123
+ if (!Number.isInteger(protectFrom) || protectFrom < 0) {
124
+ throw new Error(`splitHistory: \`protectFrom\` is required (a history index, no default) — pass the retention-window start, or history.length when there is no retention window; got ${JSON.stringify(protectFrom)}`)
125
+ }
68
126
  if (history.length <= KEEP_HEAD + keepTail + 1) return null
69
127
  let headEnd = KEEP_HEAD
70
128
  // head must not end with dangling tool_calls: when assistant declares tool_calls, all its tool results must stay in head.
@@ -80,6 +138,13 @@ export function splitHistory(history, keepTail, budgetTokens = null) {
80
138
  const floor = repairedTailStart(history, headEnd, history.length - TAIL_FLOOR_MESSAGES)
81
139
  if (floor > candidate) tailStart = tightenTailByBudget(history, candidate, floor, budgetTokens)
82
140
  }
141
+ // 保留窗结构保护(§1.2):切点一处收紧,压缩中段、prune 合格集与尾部预算三面同源受益。
142
+ // 收紧后仍走一遍配对修复:修得对了它会把起点**往前挪**(成组的 assistant 被拉进尾,尾变长),
143
+ // 但遇上孤立的 `tool` 消息(前面找不到 owner)时它会把起点往后跨过去——那是尾变短的方向。
144
+ // 保留窗起点落在这种位置上不可能:折叠按组成对进出,切片里不会有孤立结果(§1.1)。
145
+ tailStart = repairedTailStart(history, headEnd, Math.min(tailStart, protectFrom))
146
+ // 保护尾吃掉全部中段 ⇒ 无可压(与「历史太短」同一支:全史即保护尾,见 `collectStaleToolOutputs`)
147
+ if (tailStart <= headEnd) return null
83
148
  return { headEnd, tailStart }
84
149
  }
85
150
 
@@ -129,8 +194,11 @@ function tightenTailByBudget(history, start, floorStart, budgetTokens) {
129
194
  * 上下文用量单源(§6.16.4「取自哪里」)——与 `compressIfNeeded` 的 token 判定**同一函数**:实测优先 =
130
195
  * `_lastPromptTokens + 增量(history.slice(_usageAtLen))`;无实测 = `estimateTokens(history) + system + tools`(固定开销面经 extras 随带)。
131
196
  * `threshold` = 该回合检查所用值(`agent._ctxBasis.threshold`——核 `agent.mjs` / VSC `checkAndCompact` 各一处暂存);缺省回退 `resolveCompactThreshold`(退化面①)。
132
- * `window` = `providerSpec(agent.provider).context`。
133
- * @returns {{basis:"measured"|"estimated", total, history, system, tools, overhead, threshold, window}}
197
+ * `window` = **有效窗口** `effectiveWindow(agent.provider, 当前档)`(§2.1)——tiny 档下它就不是模型窗口了,
198
+ * 而这个值就是 stats 首行百分比 ∥ `Segments` 行的分母;模式自 `agent.config` 现取(agent 在场,不靠参数透传)。
199
+ * `fixedFloor` = 固定开销按当前估算比缩放(与 `total` 的估算支同一把尺)——固定开销单独越过 `limit` 的判据面
200
+ * (`CONTEXT-COMPACTION.md` §5),两处消费:`enforceContextFit` 抛 typed error ∥ `compressIfNeeded` 的 `force` 支 no-op。
201
+ * @returns {{basis:"measured"|"estimated", total, history, system, tools, overhead, fixedFloor, threshold, window}}
134
202
  */
135
203
  export function contextUsage(agent, extras = {}) {
136
204
  const history = Array.isArray(agent?.history) ? agent.history : []
@@ -141,6 +209,8 @@ export function contextUsage(agent, extras = {}) {
141
209
  const measured = agent?._lastPromptTokens != null
142
210
  // §6.3 / §6.17 估算自校准:估算值乘 `_tokRatio`;`_lastPromptTokens` 是服务端真值,不乘。
143
211
  const ratio = tokenRatioOf(agent) // 取比单源(同下 `historyReading` 的第三参来源)
212
+ // 档位只从 agent 现取(握有 agent 的面自己取模式,§2.3)——不存窗口位,不添第二个来源。
213
+ const workMode = resolveWorkMode(agent?.config?.agent)
144
214
  return {
145
215
  basis: measured ? "measured" : "estimated",
146
216
  total: measured
@@ -150,9 +220,11 @@ export function contextUsage(agent, extras = {}) {
150
220
  system,
151
221
  tools,
152
222
  overhead,
223
+ // 固定开销单独越线的判据值(§5):与估算支同尺——压掉全部 history 后 total 只能落到这个量级。
224
+ fixedFloor: Math.round(overhead * ratio),
153
225
  threshold: agent?._ctxBasis?.threshold
154
- ?? resolveCompactThreshold(agent?.config?.agent?.compactThreshold, agent?.provider).value,
155
- window: providerSpec(agent?.provider).context,
226
+ ?? resolveCompactThreshold(agent?.config?.agent?.compactThreshold, agent?.provider, workMode).value,
227
+ window: effectiveWindow(agent?.provider, workMode),
156
228
  }
157
229
  }
158
230
 
@@ -221,27 +293,36 @@ function validSample(sample, provider) {
221
293
  }
222
294
 
223
295
  /**
224
- * 核读数(§6.16.4「与状态行 ctx% 的单源关系」)——这个量**只有本函数一个实现点**,五处消费面全是它的投影:
225
- * stats 第 6 行 · 打开态读数 · 桌面 `ev:usage` · VSC `specs.mjs` · CLI 状态行(经 `ctxCacheOf` 缓存)。
226
- * 一点出两值:`tokens` = 校准后的历史估算 `round(estimateTokens(history) × ratio)`、`pct` = 它 ÷ 窗口、
227
- * `window` = `providerSpec(provider).context`——同屏「context X% Yk」必须同尺,两值各自算一次就是两把尺;
228
- * `window` 随读带出,消费面不再二次派生同一个量。
296
+ * 核读数(§6.16.4「与状态行 ctx% 的单源关系」· §2.5「显示与判定同基准」)——这个量**只有本函数一个实现点**,
297
+ * 五处消费面全是它的投影:stats 第 6 行 · 打开态读数 · 桌面 `ev:usage` · VSC `specs.mjs` · CLI 状态行(经 `ctxCacheOf` 缓存)。
298
+ * 一次读数出五个值(§2.5):`tokens` = 校准后的历史估算 `round(estimateTokens(history) × ratio)`;`window` / `limit` /
299
+ * `threshold` = 同一份 `policyBudget` 的三个字段(有效窗口那一边);`pct` = `round(tokens / limit × 100)`——
300
+ * **分母 = `limit`**(用户实际可填的量):`window` 含输出预留,拿它当分母时 100% 永远到不了,读数只说明「窗口有多大」。
301
+ * `threshold` 随读带出,状态行的告警判据读它(`tokens >= threshold`),端侧不各发明一档阈值。
229
302
  * `ratio` **无缺省**:忘传 ⇒ `estimateTokens × undefined` = `NaN` ⇒ `tokens` / `pct` 皆 `NaN`。三面显示门
230
303
  * 都把非正值读作「不显示」(CLI `ctxPct > 0` · VSC 分子为假回 `null` · 桌面 `usageFrameWanted` 不发帧)
231
304
  * ⇒ 读数**缺席**(不会是错数);给缺省 1 则相反——忘传处静默显示未校准读数,看着完全正常而差一整个校准比。
232
305
  * 两种形状里只有后者会被当作事实读走,所以宁可缺席。
306
+ * `workMode` **同无缺省**(§2.3):分母的取法只有一种,忘传就拒绝并点名参数——四个参数位次序 = (history, provider,
307
+ * ratio, workMode),既有三参调用面只添末位,不前移。
233
308
  * 空历史 ⇒ 0(状态行的 `ctxPct > 0` 显示门在端侧,不入本函数面)。
234
309
  */
235
- export function historyReading(history, provider, ratio) {
236
- const window = providerSpec(provider).context
310
+ export function historyReading(history, provider, ratio, workMode) {
311
+ const budget = policyBudget(provider, undefined, workMode)
237
312
  const tokens = Math.round(estimateTokens(history ?? []) * ratio)
238
- return { tokens, pct: Math.round((tokens / window) * 100), window }
313
+ return {
314
+ tokens,
315
+ pct: Math.round((tokens / budget.limit) * 100),
316
+ window: budget.window,
317
+ limit: budget.limit,
318
+ threshold: budget.threshold,
319
+ }
239
320
  }
240
321
 
241
322
  /** 状态行百分比薄转口(名面与 export 不变):`historyReading` 的 `pct`——与 stats ∥ CLI ∥ VSC **同源**
242
- * (各处全是这一实现点的投影,端侧零自算式)。第三参 `ratio` 同 `historyReading`:无缺省。 */
243
- export function historyPercent(history, provider, ratio) {
244
- return historyReading(history, provider, ratio).pct
323
+ * (各处全是这一实现点的投影,端侧零自算式)。第三参 `ratio` ∥ 第四参 `workMode` 同 `historyReading`:无缺省。 */
324
+ export function historyPercent(history, provider, ratio, workMode) {
325
+ return historyReading(history, provider, ratio, workMode).pct
245
326
  }
246
327
 
247
328
  /** 估算校准比(§6.17)——`agent._tokRatio` 的**唯一**读出点(中性值 1 的唯一出处):
@@ -265,10 +346,16 @@ export const PRUNE_MIN_TOKENS = 200
265
346
  * 陈旧工具输出合格集(§6.16.3——三条件合取,单源实现):① `role === "tool"`;② **保护尾之外**(复用 `splitHistory` 的同一 `tailStart`——不新增第二处切割判据);③ 估算 ≥ `PRUNE_MIN_TOKENS`。
266
347
  * 返回逐条计数面(prune 回执 + stats 两处消费):`indexes` 合格索引(升序)· `tokens` 合格集估算和 · `candidates` 全史 tool 结果数 · `tailKept` 保护尾内保留数 · `belowMin` 门槛下跳过数 · `tailCount` 保护尾消息数。
267
348
  * **短历史(无中段)⇒ 合格集为空**(no-op——§6.16.3 边界)。
349
+ * `workMode` 无缺省(§2.3):它向 `keepTailSize` ∥ `tailBudgetTokens` 透传——保护尾与压缩面同取有效窗口,
350
+ * 否则 tiny 档下「可以 prune 的面」会比「会被摘掉的面」大一圈。
351
+ * `protectFrom` 无缺省(`CONTEXT-COMPACTION.md` §1.2):保留窗起点,原样转给 `splitHistory` 的第四参。
352
+ * 拿不到保留窗的调用方传 `history.length`(= 不收紧);留一个缺省就是把「保留窗内该不该被清」
353
+ * 静默定给调用方——这一档正是本批要保护的格。
354
+ * `fixedOverhead` ∥ `ratio` 无缺省(§2.3):尾预算的减法链要用它们;四个消费点各自算好再传(§2.3 表)。
268
355
  */
269
- export function collectStaleToolOutputs(history, provider) {
356
+ export function collectStaleToolOutputs(history, provider, workMode, protectFrom, fixedOverhead, ratio) {
270
357
  const h = Array.isArray(history) ? history : []
271
- const split = splitHistory(h, keepTailSize(provider, h.length), tailBudgetTokens(provider))
358
+ const split = splitHistory(h, keepTailSize(provider, h.length, workMode), tailBudgetTokens(provider, workMode, fixedOverhead, ratio), protectFrom)
272
359
  // 无中段(短历史)⇒ 可摘要面为空 ⇒ **全史即保护尾**(tailStart = 0——合格集必为空,同压缩面 no-op)
273
360
  const tailStart = split ? split.tailStart : 0
274
361
  const r = { indexes: [], tokens: 0, candidates: 0, tailKept: 0, belowMin: 0, tailCount: h.length - tailStart }
@@ -283,3 +370,50 @@ export function collectStaleToolOutputs(history, provider) {
283
370
  }
284
371
  return r
285
372
  }
373
+
374
+ /**
375
+ * 结构编辑后的实测基线重定(§3.1)——prune ∥ shrink ∥ 压缩 ∥ 蒸馏四处只改动机读线的一部分,
376
+ * 前缀因此对不上旧真值:**不能沿用,也不必归零**,改掉那一段的估算差就是它在实测尺上的差。
377
+ *
378
+ * ```text
379
+ * _lastPromptTokens' = _lastPromptTokens − round((estBefore − estAfter) × ratio)
380
+ * _usageAtLen' = 剪切后仍属于旧前缀的那些消息之后的第一个下标(就地替换 ⇒ 不变)
381
+ * ```
382
+ *
383
+ * `estBefore` / `estAfter` = 旧前缀里被改动的那一段、与它在编辑后对应的那一段,各取 `estimateTokens`。
384
+ * 乘 `ratio` 与实测支对后缀的换算同一把尺:整条读数 = 「前缀的实测值」+「后缀的估算值 × ratio」。
385
+ * 减到非正 ⇒ 基线不再描述任何东西,退回 `null`(与归零同形,但只在算不出来时走)。
386
+ *
387
+ * @param {object} agent
388
+ * @param {number} estBefore 被改那一段的旧估算
389
+ * @param {number} estAfter 它在编辑后对应那一段的估算
390
+ * @param {{inPlace?: boolean, before?: object[], measuredEnd?: number}} [opts]
391
+ * `inPlace` = 数组长度与下标不变(prune ∥ shrink 的原位替换)⇒ `_usageAtLen` 原样:被替换那条仍在
392
+ * 前缀里,它的新估算已经由上面那笔减法折进基线,再进后缀就是重复计一次。
393
+ * `before` / `measuredEnd` = 编辑前的数组与它被量到的长度(剪切类编辑按身份找回旧前缀的尾巴)。
394
+ */
395
+ export function rebaseMeasured(agent, estBefore, estAfter, { inPlace = false, before = null, measuredEnd = null } = {}) {
396
+ if (agent?._lastPromptTokens == null) return
397
+ const ratio = tokenRatioOf(agent)
398
+ const next = agent._lastPromptTokens - Math.round((estBefore - estAfter) * ratio)
399
+ if (!(next > 0)) {
400
+ agent._lastPromptTokens = null
401
+ agent._usageAtLen = null
402
+ return
403
+ }
404
+ agent._lastPromptTokens = next
405
+ if (inPlace) return
406
+ const end = Number.isInteger(measuredEnd) ? measuredEnd : Array.isArray(before) ? before.length : null
407
+ if (end == null) {
408
+ agent._usageAtLen = null
409
+ return
410
+ }
411
+ // 旧前缀的成员按**身份**取:压缩重建数组后下标会漂、身份不漂(与在途段起点同一条重定规则,§1.1)。
412
+ const kept = new Set((before ?? agent.history).slice(0, end))
413
+ const history = Array.isArray(agent.history) ? agent.history : []
414
+ let at = 0
415
+ for (let i = history.length - 1; i >= 0; i--) {
416
+ if (kept.has(history[i])) { at = i + 1; break }
417
+ }
418
+ agent._usageAtLen = at
419
+ }
@@ -1,28 +1,3 @@
1
- Run an independent review of your work. `type` is REQUIRED — one of exactly two values, no default and no silent fallback.
1
+ Run an independent review of your work.
2
2
 
3
- - `type="design"` — design review: reviews design / requirement documents BEFORE implementation. Pass `documents=[...]` and `batchDoc` — the batch record this review belongs to. **`batchDoc` is required**: a design review without it is refused before launch, because the token it would mint has no batch to close it.
4
- - `type="code"` — code review: reviews the code you changed AFTER implementation. Pass `paths=[...]` to scope files/directories; `documents=[...]` adds acceptance-criteria context.
5
-
6
- `documents` — one rule: a relative path resolves against the session project root (e.g. `docs/<area>/<name>.md`); an absolute path is used as-is.
7
-
8
- The relative form needs the session anchor to be inside a project. When the anchor is a workspace root (several projects below it, no manifest of its own) there is no single project root to resolve against, and a relative path is refused with `no-project-root` — write the absolute path there.
9
-
10
- Accepted = an existing `.md` file anywhere inside a project — a doc sitting at the repo root counts. Anything else is refused with the resolved path, the reason and the two expected forms.
11
-
12
- A call without a type (or with a conflicting `object.type`) is refused.
13
-
14
- The advisor is an independent read-only sub-agent (explores the codebase, reads files, traces callers via grep/lsp).
15
-
16
- - Code review converges: round 1 full review → round 2 verifies the agent's fix claims → round 3+ re-checks only the fix claims.
17
- - Design review is a single pass against methodology and requirements.
18
- - Criteria come from `.thincoder/advisor.md` (if present) or sensible defaults.
19
- - After the review you MUST produce a response table (format = discipline rules); on all-clear, call `verify`.
20
-
21
- `object={type,target,status,reason,exclude}` optionally anchors the review target — mechanically injected at the start of the review message; absent = no injection.
22
-
23
- ASYNC (depth 0 only): the review runs in the BACKGROUND by default — ack immediately, the report arrives automatically in a digest turn.
24
-
25
- - One shared pool: `agent.poolLimits.advisor`, default 4 — configurable via `/config` 并发池 or config.json. Pool-full and same-scope launches are refused stating the current limit; launch reviews one at a time.
26
- - Inside a child (depth>0) reviews are always synchronous (`async:true` rejected).
27
-
28
- Returns the verdict: all-clear (call `verify`) or a findings list to fix.
3
+ {{knowledge:tool-advisor}}
@@ -1,17 +1,3 @@
1
1
  Apply a unified diff to one or more files, atomically: if any hunk fails to apply, nothing is written.
2
2
 
3
- **Use it for whole-file and multi-file changes:** creating MULTIPLE new files at once (`--- /dev/null` header per file), whole-file replacement, and cross-file refactors — one unified-diff call covers the whole change. A batched call is one permission ask and one turn instead of N separate calls.
4
-
5
- Parameters:
6
- - patch (required): Unified diff text. One `--- a/path` / `+++ b/path` header pair per file, then `@@ -old,count +new,count @@` hunks. Use `--- /dev/null` to create a new file. The `+++ b/path` pair may be omitted for existing files — a lone `--- a/path` (or `--- b/path`) header followed directly by hunks applies to that path (new files still need `--- /dev/null` + `+++ b/path`).
7
-
8
- Notes:
9
- - Hunk header "@@" without coordinates is accepted. Coordinate-less hunks are located by their anchor lines: context lines plus the removed (-) lines, matched as a contiguous sequence — a unique match applies. The anchor-free forms require context: a hunk with no removed (-) lines (pure additions) needs at least 2 context lines for a unique match; a zero/one-context hunk with at least one removed (-) line is located by its anchor sequence (context + removed lines, in order) and applies on a unique match.
10
- - Returns the applied-file summary (`Applied patch to N file(s)` plus per-file change lines and syntax-check notes for changed .mjs files)
11
- - Use this for multi-file changes (e.g. rename an interface + update all callers) — one call, all-or-nothing
12
- - Hunks are located by their context/removed lines, not line numbers — but the context must match the file EXACTLY. Read the files first and generate the patch from actual content
13
- - If a hunk's context matches multiple locations it is rejected — add more surrounding context lines
14
- - Deleting files is not supported — use the delete tool
15
- - For single-file edits, edit is simpler; for full rewrites, write is simpler
16
-
17
- **`ledger`** — the in-flight ledger row this call serves: `"#N"` or `"N"`. In engineering mode the parent agent must pass it — a call that does not say which row it serves is refused.
3
+ {{knowledge:tool-apply-patch}}
package/tool-docs/bash.md CHANGED
@@ -1,43 +1,4 @@
1
- Execute a shell command and return stdout+stderr. Use for running commands, builds, tests.
2
-
3
- **Route to a dedicated tool instead of bash:**
4
- - `cat file` / `head` / `tail` → `read`
5
- - `ls` / `dir` → `ls`
6
- - `find` / glob search → `glob`
7
- - `grep` / `rg` → `grep`
8
- - `echo >` / `sed` / `printf >` / `cat << EOF` → `write` / `edit` / `hashline_edit` / `apply_patch` (preferred: write tools handle encoding/EOL correctly)
9
- - `git diff` / `git status` / `git log` → `git` tool
10
-
11
- Parameters:
12
- - command (required): Shell command to execute
13
- - timeout: Timeout in milliseconds (default 120000 for synchronous runs; background runs have no default — an explicit timeout still applies; no upper bound)
14
- - filter: Optional — a regex; only output lines matching it are returned (case-insensitive). Use instead of hand-writing a pipe into `findstr`/`grep`.
15
- - async: Run in the background (default false) — returns an ack at once (bash#<id>, log path); the result arrives as a digest when the process exits. Depth-0 only.
1
+ Execute a shell command and return stdout+stderr.
16
2
  {{inject:bash-terminal-face}}
17
3
 
18
- Output format:
19
- ```
20
- [stdout]:
21
- <standard output, or "(empty)">
22
-
23
- [stderr]:
24
- <standard error, only present if non-empty>
25
-
26
- (exit code N)
27
- ```
28
-
29
- Notes:
30
- - There is NO TTY — editors, pagers (vim, less), and interactive prompts WILL hang. Always pass non-interactive flags: `git commit -m`, `git --no-pager`, `-y`/`--yes` where applicable
31
- - The environment sets GIT_PAGER=cat, PAGER=cat, EDITOR=true, TERM=dumb — but still always use non-interactive flags
32
- - Output is capped at ~200K chars; if you need more, redirect to a file and read it. Truncated output ends with a `[... truncated: N chars omitted]` marker — the missing tail may contain errors, so read the saved log file's tail before trusting success. Use `filter` to narrow instead of hand-piping.
33
- - Check `[stderr]` for error messages, warnings, and diagnostic output — it is separated from `[stdout]` so you can quickly identify problems.
34
- - Shell identity: the bash tool's shell is NOT fixed — it depends on configuration and environment. The current executor is declared in the Executor line above; write commands for THAT shell, and when a command fails read its error output to identify the actual shell.
35
- - Never use bash to read, copy, or transmit secret files (.env, keys, tokens)
36
- - Do NOT run destructive commands (rm -rf, force-push, drop table) without explicit user confirmation
37
- - After commands that change files (git checkout, npm install, etc.), repo_outline and code_search may be stale — re-run them to get current results.
38
- - Prefer read/glob/grep/ls for file operations inside the project — file tools and bash reach the same paths (no directory restriction).
39
- - NEVER use bash to write or modify files (echo/sed/printf > file, cat << EOF, etc.). Use write/edit/insert_after/apply_patch instead — they handle encoding, escaping, and EOL conventions correctly.
40
-
41
- **`ledger`** — the in-flight ledger row this call serves: `"#N"` or `"N"`. In engineering mode the parent agent must pass it — a call that does not say which row it serves is refused, and read-only commands are judged the same way (no command-line classification).
42
-
43
- **`project`** — the project this call belongs to: the absolute path of the project root (the directory carrying PROJECT-MANIFEST.json). Engineering mode: pass it together with `ledger`. Pure declaration: it does not change the execution directory.
4
+ {{knowledge:tool-bash}}
@@ -0,0 +1,3 @@
1
+ Write the batch record's implementation section (§5) — your pen on this record.
2
+
3
+ {{knowledge:tool-batch-eng-coder}}
@@ -0,0 +1,3 @@
1
+ Write the batch record's design section (§2) — your pen on this record.
2
+
3
+ {{knowledge:tool-batch-eng-designer}}
@@ -0,0 +1,3 @@
1
+ Write the batch record's design-review section (§3) — your pen on this record.
2
+
3
+ {{knowledge:tool-batch-review}}