@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
@@ -13,26 +13,34 @@ export const GOAL_BUDGET_WARN_RATIO = 0.75
13
13
  // 设计轮轮数注入阈值(AGENT-LOOP.md §6.6「设计轮轮数注入」· 台账 #1661):
14
14
  // 5 = 在 persona 判定点(过 7 轮未落盘 ⇒ 降级)之前 3 轮给出计数;8 = 与 persona 同一判定点;
15
15
  // 15 = persona 的首版预算(注入串里的 15 一律由它插值——改常量即改注入文本,不另留字面)。
16
+ // 2 = 每条链的注入帽(两档各一条:5 轮计数条 + 8 轮骨架判定条)——到帽即静默;
17
+ // 无帽时判据只有下界,长链逐轮重发同形句(实测 600+ 轮 ⇒ 600+ 条)。
16
18
  export const DESIGN_TURN_NOTICE_AT = 5
17
19
  export const DESIGN_TURN_SKELETON_AT = 8
18
20
  export const DESIGN_FIRST_VERSION_TURNS = 15
21
+ export const DESIGN_TURN_NOTICE_MAX = 2
19
22
 
20
23
  /**
21
- * 设计轮轮数提醒(纯函数——注入串 | `null`;判据源 = 链内累计轮号 + 本设计轮是否落过盘)。
24
+ * 设计轮轮数提醒(纯函数——注入串 | `null`;判据源 = 链内累计轮号 + 本设计轮是否落过盘 + 本链已注入条数)。
22
25
  * 逐字注入形 = `AGENT-LOOP.md` §6.6「注入形逐字」;角色表当前一行(`eng-designer`),
23
26
  * `eng-coder` 零注入(其零落笔面另由零落笔看门狗兜)。
24
- * @param {{role?:string|null, turn?:number, wrote?:boolean}} o `turn` = 链内累计轮号(1 起)
27
+ * **何时发(有上限、有去重)**:每条链两档各一条——`notices` 0 ⇒ 5 轮起常行;1 ⇒ 8 轮起降级行(未落盘)∥ 常行(已落盘);
28
+ * 到帽(`DESIGN_TURN_NOTICE_MAX`)⇒ 静默。注入的唯一作用是让模型看见「已用轮次 + 是否落过盘」,该信息只在 5 轮与 8 轮各改一次判断。
29
+ * @param {{role?:string|null, turn?:number, wrote?:boolean, notices?:number}} o `turn` = 链内累计轮号(1 起)· `notices` = 本链已注入条数
25
30
  * @returns {string|null}
26
31
  */
27
- export function designTurnReminder({ role, turn, wrote } = {}) {
32
+ export function designTurnReminder({ role, turn, wrote, notices } = {}) {
28
33
  if (role !== "eng-designer") return null
29
34
  const used = Number(turn ?? 0)
30
35
  if (!Number.isFinite(used) || used < DESIGN_TURN_NOTICE_AT) return null
36
+ const sent = Number(notices ?? 0)
37
+ if (!Number.isFinite(sent) || sent >= DESIGN_TURN_NOTICE_MAX) return null
31
38
  const budget = DESIGN_FIRST_VERSION_TURNS
32
- if (used >= DESIGN_TURN_SKELETON_AT && !wrote) {
33
- return `[System reminder: design round turn ${used}/${budget} — nothing has been written to disk yet. The 7-turn mark has passed with nothing landed: degrade the delivery NOW — write the skeleton (design doc + batch record §2) plus an unresolved list, then refine in place.]`
34
- }
35
- return `[System reminder: design round turn ${used}/${budget} — ${wrote ? "something has been written to disk" : "nothing has been written to disk yet"}. First version budget is ${budget} turns; past 7 turns with nothing landed the rule is a skeleton + unresolved list.]`
39
+ const normal = `[System reminder: design round turn ${used}/${budget} — ${wrote ? "something has been written to disk" : "nothing has been written to disk yet"}. First version budget is ${budget} turns; past 7 turns with nothing landed the rule is a skeleton + unresolved list.]`
40
+ if (sent === 0) return normal
41
+ if (used < DESIGN_TURN_SKELETON_AT) return null
42
+ if (wrote) return normal
43
+ return `[System reminder: design round turn ${used}/${budget} — nothing has been written to disk yet. The 7-turn mark has passed with nothing landed: degrade the delivery NOW — write the skeleton (design doc + batch record §2) plus an unresolved list, then refine in place.]`
36
44
  }
37
45
 
38
46
  /**
@@ -92,13 +100,19 @@ export function injectPostTurn(agent, results, recentCallSigs, callbacks, turn,
92
100
  }
93
101
 
94
102
  // 设计轮轮数注入(AGENT-LOOP.md §6.6 · 台账 #1661):轮号取 `_currentTurn`(链内累计、续跑不重置),
95
- // 写入痕迹取 `_touchedFiles`(在 resume 保留集内 ⇒ 续跑段沿用前段痕迹);段内 `turn` 形参不参与判据。
103
+ // 写入痕迹取 `_touchedFiles`(六件写工具)∥ `_batchWrites`(batch 成功写盘计数)——两者与注入帽计数
104
+ // `_designTurnNotices` 都在 resume 保留集内 ⇒ 续跑段沿用前段痕迹;段内 `turn` 形参不参与判据。
105
+ // 注入帽计数与注入同址自增(判据与自增一处,不写第二份)。
96
106
  const designReminder = designTurnReminder({
97
107
  role: agent._role,
98
108
  turn: agent._currentTurn ?? 0,
99
- wrote: (agent._touchedFiles ?? []).length > 0,
109
+ wrote: (agent._touchedFiles ?? []).length > 0 || (agent._batchWrites ?? 0) > 0,
110
+ notices: agent._designTurnNotices ?? 0,
100
111
  })
101
- if (designReminder) agent.history.push({ role: "user", content: designReminder })
112
+ if (designReminder) {
113
+ agent.history.push({ role: "user", content: designReminder })
114
+ agent._designTurnNotices = (agent._designTurnNotices ?? 0) + 1
115
+ }
102
116
 
103
117
  callbacks.onTurnEnd?.(agent, turn)
104
118
  }
@@ -34,6 +34,11 @@ import { looksLikeReviewOutput, advisorIncompleteMarker } from "../advisor/run.m
34
34
  import { noteReviewDelivered } from "../agent-tools/review-facts.mjs"
35
35
  // #1178:动作级只读分类(settings get ∥ manifest read 类)不失效 verify——谓词单源 = dispatch-gates。
36
36
  import { isReadonlyAction } from "./dispatch-gates.mjs"
37
+ // 跨轮投影的**账本采集点**(CONTEXT-COMPACTION.md §1.1 · 台账 #2395):每一条工具结果入史的同时记一笔
38
+ // 运行记账(验证命令与结果摘要);变更文件面仍走 `_touchedFiles` 既有归集(不另立第二份清单)。
39
+ import { noteTurnToolFacts } from "./turn-projection.mjs"
40
+ // 归属表(收口取材的判据一):记账的同时写下「这笔写服务哪一批」——`_touchedFiles` 形状一字不动。
41
+ import { recordAttribution } from "./batch-attribution.mjs"
37
42
 
38
43
  let _reindexFile = null
39
44
 
@@ -51,6 +56,8 @@ export async function recordToolResults(agent, toolByName, results) {
51
56
 
52
57
  for (const { toolCall, result, ok } of results) {
53
58
  const tool = toolByName.get(toolCall.name)
59
+ // 运行记账先于三条入史分支(多模态 ∥ 普通 ∥ 非视觉提醒)——一条结果只记一次。
60
+ noteTurnToolFacts(agent._turnLedger, { toolCall, result, ok })
54
61
  // Multimodal tools return JSON { text, images } — inject as multimodal user message
55
62
  if (tool?.multimodal && ok) {
56
63
  try {
@@ -134,7 +141,13 @@ export async function recordToolResults(agent, toolByName, results) {
134
141
  // (含类型不可判——run 缺失的 legacy 直调)⇒ 不置「已覆盖」(与 settle 面
135
142
  // 逐条 parity;设计评审保持计入——无代码面)。
136
143
  const incomplete = advisorIncompleteMarker(String(result))
137
- if (!(incomplete && run?.reviewType !== "design")) agent._calledAdvisorThisRun = true
144
+ if (!(incomplete && run?.reviewType !== "design")) {
145
+ agent._calledAdvisorThisRun = true
146
+ // ADVISOR-CONVERGENCE.md §6.4 B 复位点 2(同步面):评审覆盖成立 ⇒ 本未评审周期结束,
147
+ // 下一周期起于完整预算(未完成尾不计——与覆盖标记同一判据分摊)。
148
+ agent._advisorReminders = 0
149
+ agent._advisorHonestySent = false
150
+ }
138
151
  if (reviewId !== undefined) {
139
152
  if (run) {
140
153
  run.round++
@@ -163,10 +176,12 @@ export async function recordToolResults(agent, toolByName, results) {
163
176
  try {
164
177
  const args = JSON.parse(toolCall.arguments)
165
178
  const paths = toolTouchPaths(tool, args)
179
+ const touched = []
166
180
  for (const p of paths) {
167
181
  if (typeof p !== "string" || !p) continue // 非字符串项不拖累合法路径(与 dispatch / VSC 消费面同口径)
168
182
  const abs = resolve(agent.cwd, p)
169
183
  if (!agent._touchedFiles.includes(abs)) agent._touchedFiles.push(abs)
184
+ touched.push(abs)
170
185
  if (agent.memory) {
171
186
  // Fire-and-forget: don't block the agent loop on indexing.
172
187
  // Reuses a single cached import; errors surface as pending reminders on next turn.
@@ -179,6 +194,8 @@ export async function recordToolResults(agent, toolByName, results) {
179
194
  })
180
195
  }
181
196
  }
197
+ // 归属与路径同一笔记(`agent._batchDoc` 由 spawn 绑定;未绑定 ⇒ 不入表,收口按本批判)。
198
+ recordAttribution(agent, touched, agent._batchDoc)
182
199
  } catch { /* #327:畸形 args(含 null)/ 畸形路径不再裸抛——touchedFiles 尽力而为 */ }
183
200
  }
184
201
  }
@@ -8,11 +8,11 @@
8
8
  * agent.mjs 迁入,agent.mjs 内无其他引用)。verbatim 迁移 + 签名化,语义零变。
9
9
  */
10
10
 
11
- import { compressIfNeeded, compressFallback, COMPRESS_FAILURE_LIMIT } from "../context.mjs"
12
- // §6.17/D-CC32 溢出守卫(兜底,非主修):预算面单源 requestBudget ∥ 再估面 contextUsage(与压缩判定同一函数)
13
- import { requestBudget } from "../config.mjs"
11
+ import { compressIfNeeded } from "../context.mjs"
12
+ // §6.17/D-CC32 溢出守卫(兜底,非主修):预算面单源 `policyBudget`(有效窗口)∥ 再估面 contextUsage(与压缩判定同一函数)
13
+ import { policyBudget, resolveWorkMode } from "../config.mjs"
14
14
  import { contextUsage } from "../token-window.mjs"
15
- import { contextOverflowError } from "../provider/errors.mjs"
15
+ import { contextOverflowError, overheadOverflowError } from "../provider/errors.mjs"
16
16
  import { ensureAutoReminder, injectEngineeringReminder, ContinueError, snapshotGuard } from "./helpers.mjs"
17
17
  import { pushManifestStateReminder } from "./setup-reminders.mjs"
18
18
  import { cleanupConsultSessions } from "../agent-tools/consult.mjs"
@@ -27,6 +27,9 @@ import { discardAbortedPool, discardAbortedAdvisors, discardAbortedBgTasks, disc
27
27
  // R10 L3 (MULTI-INSTANCE-COLLAB §2a.5 D-L3a):回合末域登记 flush(写工具钩子累积 →
28
28
  // 整写一次本实例 peers 文件——无写入跳过;失败容忍不抛)
29
29
  import { flushPeerDomains } from "../peer-domains.mjs"
30
+ // 投递面名册(MULTI-INSTANCE-COLLAB §5.2 · D-MI28):回合收尾刷新 `updatedAt`(与足迹 flush 同点;
31
+ // 不在册 ⇒ 零动作——入册只发生在取件面装配处)
32
+ import { refreshInstance } from "../instance-registry.mjs"
30
33
  // 第 30 批 D1(Stop 钩子——AGENT-LOOP.md §6.13):主会话 run 终止事件(触发块见 finalizeAgentTurn)
31
34
  import { runHooks } from "../hooks.mjs"
32
35
 
@@ -74,7 +77,7 @@ export function injectResponseReminders(agent, response) {
74
77
  }
75
78
  }
76
79
 
77
- // ─── 压缩记账三件(§6.17 阈值面 ∥ 守卫面 ∥ §6.17.1 链三自适应面共用同一段,零复制)───
80
+ // ─── 压缩记账两件(§6.17 阈值面 ∥ 守卫面 ∥ §6.17.1 链三自适应面共用同一段,零复制)───
78
81
 
79
82
  /** 压缩成功记账:失败计数清零 / 计划提醒 cadence 复位 / 停滞检测计数复位 / 完成事件 / AUTO 提醒重注入。 */
80
83
  function bookkeepCompaction(agent, ctx) {
@@ -87,28 +90,22 @@ function bookkeepCompaction(agent, ctx) {
87
90
  ensureAutoReminder(agent)
88
91
  }
89
92
 
90
- /** 压缩失败记账——AbortError 必须透传(用户中止不得被当成压缩失败吞掉)。 */
93
+ /** 压缩失败记账——AbortError 必须透传(用户中止不得被当成压缩失败吞掉)。
94
+ * 计数只为面板与 stats 读(§5.1 之后它不再触发任何降级:摘要失败一次当场走丢弃)。 */
91
95
  function noteCompressFailure(agent, ctx, compressError) {
92
96
  if (compressError?.name === "AbortError" || ctx.signal?.aborted) throw compressError
93
97
  agent._compressFailures = (agent._compressFailures ?? 0) + 1
94
- // Q3 (CONTEXT-COMPACTION §7 D-C1): a failed compression is surfaced to the panel;
95
- // COMPRESS_FAILURE_LIMIT consecutive failures still degrade to compressFallback.
98
+ // Q3 (CONTEXT-COMPACTION §7 D-C1): a failed compression is surfaced to the panel.
99
+ // 降级不再由「连续失败 N 次」触发:`compressIfNeeded` 的 ⑥ 步在失败当次就丢弃(§5.1)。
96
100
  ctx.callbacks?.onCompressFail?.(compressError)
97
101
  }
98
102
 
99
- /** 三连败降级(确定性截断——零网络,§6.5 D6)。 */
100
- function degradeIfCompressExhausted(agent, ctx) {
101
- if (agent._compressFailures < COMPRESS_FAILURE_LIMIT) return
102
- agent._compressFailures = 0
103
- if (compressFallback(agent)) ctx.callbacks?.onCompress?.(agent._lastCompressInfo ?? {})
104
- }
105
-
106
103
  /**
107
104
  * 回合压缩检查(2026-09-05 实践轮——自 runAgent 主循环提取):仅安全点(history 以
108
105
  * 完整交换结尾——user/tool 位)。成功:失败计数清零/计划提醒 cadence 复位/停滞检测
109
106
  * 计数复位(recentCallSigs——runAgent 回合级局部——经 ctx 传对象引用)/压缩完成事件
110
- * /AUTO 提醒重注入。失败:AbortError 透传;计数 + Q3 onCompressFail;
111
- * COMPRESS_FAILURE_LIMIT 连续失败降级 compressFallback(确定性截断——不发 LLM)。
107
+ * /AUTO 提醒重注入。失败:AbortError 透传;计数 + Q3 onCompressFail——降级不由「连续失败 N 次」
108
+ * 触发:`compressIfNeeded` 的 ⑥ 步在摘要失败当次就丢弃(§5.1)。
112
109
  * 模型主动压缩(`context` 工具)由本点消费(§6.16.2——取用即清槽;no-op 与失败各落一行注记)。
113
110
  */
114
111
  export async function runCompactionCheck(agent, ctx) {
@@ -125,9 +122,15 @@ export async function runCompactionCheck(agent, ctx) {
125
122
  signal,
126
123
  )
127
124
  if (!compacted && pending) {
128
- // 强制面无可压(短历史无中段)⇒ 记 no-op 注记后**照常**跑阈值面(阈值面不因模型请求让位)
129
- const { compactNoopNote } = await import("../agent-tools/context.mjs")
130
- agent.history.push({ role: "user", content: compactNoopNote(), transient: true })
125
+ // 强制面无可压:固定开销单独越线 ⇒ 回执报与守卫同一个原因(`CONTEXT-COMPACTION.md` §5),
126
+ // 否则 = 短历史无中段。两种 no-op 的处置不同,回执不能同一句。
127
+ const { compactNoopNote, compactOverheadNote } = await import("../agent-tools/context.mjs")
128
+ const forced = contextUsage(agent, compactionOverhead)
129
+ const budget = policyBudget(agent.provider, undefined, resolveWorkMode(agent.config?.agent))
130
+ const note = forced.fixedFloor > budget.limit
131
+ ? compactOverheadNote(forced.fixedFloor, budget.limit, budget.window)
132
+ : compactNoopNote()
133
+ agent.history.push({ role: "user", content: note, transient: true })
131
134
  compacted = await compressIfNeeded(agent, threshold, callbacks, compactionOverhead, signal)
132
135
  }
133
136
  if (compacted) bookkeepCompaction(agent, ctx)
@@ -138,7 +141,6 @@ export async function runCompactionCheck(agent, ctx) {
138
141
  const { compactFailureNote } = await import("../agent-tools/context.mjs")
139
142
  agent.history.push({ role: "user", content: compactFailureNote(errText(compressError), agent._compressFailures), transient: true })
140
143
  }
141
- degradeIfCompressExhausted(agent, ctx)
142
144
  }
143
145
 
144
146
  // 溢出守卫(CONTEXT-COMPACTION.md §6.17 / D-CC32——兜底,非主修;本缝 = catch 闭合后、返回前)。
@@ -148,7 +150,7 @@ export async function runCompactionCheck(agent, ctx) {
148
150
 
149
151
  /**
150
152
  * 越窗守卫 / 自适应共用原子(CONTEXT-COMPACTION.md §6.17 守卫 ∥ §6.17.1 链三自适应):
151
- * `requestBudget` 判 → 强压一次(`force`)→ 再判 → 抛三实数(不截断、不静默削输出)。
153
+ * `policyBudget` 判 → 强压一次(`force`)→ 再判 → 抛三实数(不截断、不静默削输出)。
152
154
  *
153
155
  * `opts.forceCompact`(链三面):**跳过前置估算判据**、直接强压——服务端已判越窗时估算准不准不再作门
154
156
  * (本批要治的就是估算低估:死锁现场估 491K < limit 606,784,按估算开门会压 0 次、重试同一请求再吃 400)。
@@ -157,13 +159,18 @@ export async function runCompactionCheck(agent, ctx) {
157
159
  */
158
160
  export async function enforceContextFit(agent, ctx, { forceCompact = false } = {}) {
159
161
  const { threshold, callbacks, compactionOverhead, signal } = ctx
160
- // 判据 = prompt 估算 > `budget.limit`(**无档次门**——absent 档 limit 取地板 max(window − reserve, threshold),
161
- // 恒为正数、恒可判)。**判据不用 maxTokens**:未发时为 undefined ⇒ NaN ⇒ 守卫静默失效(§6.17)。
162
- const budget = requestBudget(agent.provider)
162
+ // 判据 = prompt 估算 > `budget.limit`(**无档次门**——`limit = window − reserve`,恒为正数、恒可判;
163
+ // 派生不成立的配置在装载期已被拒,见 §2.4)。**判据不用 maxTokens**:未发时为 undefined ⇒ NaN ⇒ 守卫静默失效(§6.17)。
164
+ // 预算取**有效窗口**(`CONTEXT-COMPACTION.md` §2.2「stats、守卫和压缩使用同一预算对象」):tiny 档下
165
+ // 守卫与压缩线同一把尺,否则只降阈值不动 limit = 「早压缩但仍放行到模型窗口」,与上界相反。
166
+ const budget = policyBudget(agent.provider, undefined, resolveWorkMode(agent.config?.agent))
163
167
  let usage = contextUsage(agent, compactionOverhead)
168
+ // 固定开销单独越线(#2398 · `CONTEXT-COMPACTION.md` §5):history 归零后 `total` 仍等于固定开销 ⇒ 压缩无解,
169
+ // 在强压**之前**抛 typed error(`forceCompact` 同样拦:强制压缩跳得过阈值,跳不过这条)。
170
+ if (usage.fixedFloor > budget.limit) throw overheadOverflowError(agent.provider, budget, usage.fixedFloor)
164
171
  if (!forceCompact && !(usage.total > budget.limit)) return false
165
- // 强压一次:失败走与阈值面同一条记账 / 降级链(不把摘要错误当回合错误直抛——
166
- // 记账后仍按「压后仍超」判:降级截断可能已把上下文压到线下)。
172
+ // 强压一次:失败走与阈值面同一条记账链(不把摘要错误当回合错误直抛——
173
+ // 记账后仍按「压后仍超」判:⑥ 的丢弃可能已把上下文压到线下)。
167
174
  try {
168
175
  const compacted = await compressIfNeeded(
169
176
  agent, threshold, callbacks, { ...compactionOverhead, force: true }, signal,
@@ -171,18 +178,53 @@ export async function enforceContextFit(agent, ctx, { forceCompact = false } = {
171
178
  if (compacted) bookkeepCompaction(agent, ctx)
172
179
  } catch (compressError) {
173
180
  noteCompressFailure(agent, ctx, compressError)
174
- degradeIfCompressExhausted(agent, ctx)
175
181
  }
176
182
  usage = contextUsage(agent, compactionOverhead)
177
183
  if (usage.total > budget.limit) {
178
- const remedy = budget.limit < 0
179
- ? `max_tokens ${budget.maxTokens} alone exceeds the window — lower provider.maxTokens or switch to a larger-window model`
180
- : "forced compaction ran but the prompt still exceeds the window; reduce the conversation (/compact or prune) before retrying"
184
+ const remedy = "forced compaction ran but the prompt still exceeds the window; reduce the conversation (/compact or prune) before retrying"
181
185
  throw contextOverflowError(agent.provider, usage.total, budget, remedy)
182
186
  }
183
187
  return true
184
188
  }
185
189
 
190
+ /**
191
+ * 切换预判(`CONTEXT-COMPACTION.md` §5.2):run 装配之后、第一个回合之前,比一次实测优先的
192
+ * `contextUsage.total` 与 `policyBudget(...).limit`。
193
+ *
194
+ * 存量历史可能超过新窗口:用户从 1M 模型切到 256K 模型、把 `providers[].context` 调小,或改
195
+ * `reasoningEffort`(`max` 档把 `reserve` 抬到 131,072)——这几种变更都让 `limit` 变小,而 `agent.history`
196
+ * 一条没少。不预判就得等下一次请求撞上守卫:报文说 `context_overflow`,用户读到的是「上下文太大」,
197
+ * 真实原因(刚换的配置装不下已有历史)被报文挡在后面。
198
+ *
199
+ * 超了就**跑 §5.1 的同一条处置链**(force 面:prune → 摘要 → 丢弃),不另立第二条路径;跑完仍超 `limit`
200
+ * ⇒ 守卫照 §5 抛三实数,报文点明切换后的模型装不下存量历史。
201
+ * 判据用实测优先的 `contextUsage`:切换前的最后一次响应给过真值,它比估算更接近服务端会看到的量。
202
+ * 返回是否越线(未越线 = 零动作)。
203
+ */
204
+ export async function preflightWindowFit(agent, ctx) {
205
+ const { threshold, callbacks, compactionOverhead, signal } = ctx
206
+ const budget = policyBudget(agent.provider, undefined, resolveWorkMode(agent.config?.agent))
207
+ let usage = contextUsage(agent, compactionOverhead)
208
+ if (!(usage.total > budget.limit)) return false
209
+ if (usage.fixedFloor > budget.limit) throw overheadOverflowError(agent.provider, budget, usage.fixedFloor)
210
+ try {
211
+ const compacted = await compressIfNeeded(
212
+ agent, threshold, callbacks, { ...compactionOverhead, force: true }, signal,
213
+ )
214
+ if (compacted) bookkeepCompaction(agent, ctx)
215
+ } catch (compressError) {
216
+ noteCompressFailure(agent, ctx, compressError)
217
+ }
218
+ usage = contextUsage(agent, compactionOverhead)
219
+ if (usage.total > budget.limit) {
220
+ throw contextOverflowError(
221
+ agent.provider, usage.total, budget,
222
+ "the stored history does not fit the configuration this run started with (model switch, smaller providers[].context or a larger reasoningEffort reservation); /compact or start a fresh session, or switch back to a larger-window model",
223
+ )
224
+ }
225
+ return true
226
+ }
227
+
186
228
  /**
187
229
  * 回合注入组(2026-09-05 实践轮——自 runAgent 主循环提取):plan-mode 提醒 cadence
188
230
  * (稀疏 2 轮/满 5 轮/新用户消息重置——限制不淡化)+ 工程模式状态注入(depth-0 每新
@@ -228,6 +270,9 @@ export async function finalizeAgentTurn(agent, ctx) {
228
270
  // R10 L3(MULTI-INSTANCE-COLLAB §2a.5 D-L3a):回合末登记 flush——本回合写足迹整写
229
271
  // 一次(首行执行:收尾链后续任何异常都不吞登记);无写入 → 跳过(hot 窗口自然衰减)。
230
272
  flushPeerDomains(agent)
273
+ // 投递面名册走时(MULTI-INSTANCE-COLLAB §5.2 · D-MI28:回合收尾刷新 `updatedAt`,与足迹 flush 同点)——
274
+ // 只刷新已在册条目;失败容忍(吞掉——名册写失败不得影响收尾链后续任何一步)。
275
+ try { refreshInstance({ cwd: agent?.cwd }) } catch { /* NF2:失败容忍 */ }
231
276
  // 第 30 批 D1(Stop 钩子):主会话 run 终止 → fire-and-forget(非阻塞;失败静默——与 PostToolUse 同语义)。
232
277
  // 排除用户中止(Ctrl+C / Ctrl+I——中止后 TUI 重建 controller 续跑或已显式停回合)与 AbortError 展开。
233
278
  if (depth === 0 && !signal?.aborted && thrownError?.name !== "AbortError") {
@@ -247,7 +292,7 @@ export async function finalizeAgentTurn(agent, ctx) {
247
292
  // resumes); the Ctrl+C abort branch below is the only path that aborts them
248
293
  // (cleanupConsultSessions — marked stopped → no digest), and the suspension
249
294
  // driver aborts them on its own abort unwind.
250
- // Async subagent turn-end handling (AGENT-LOOP-SUBAGENT.md §6.7.3 D-A3 + AGENT-LOOP-ASYNC-POOL.md §6.8 D-S1). Lifecycle:
295
+ // Async subagent turn-end handling (AGENT-LOOP-SUBAGENT.md §6.7.3 + AGENT-LOOP-ASYNC-POOL.md §6.8 D-S1). Lifecycle:
251
296
  // - Ctrl+C (plain abort): children were aborted with the parent signal — discard dead
252
297
  // entries (tombstone/out-of-pool/notice — AGENT-LOOP-ASYNC-POOL.md §6.20; no stale
253
298
  // errors injected — user explicitly stopped); consultation sessions are cross-turn
@@ -4,6 +4,9 @@
4
4
  * 接口 = beginRun(agent, input, callbacks, opts) → 主循环装配面(`tools` 死绑定去——KD-8)。
5
5
  */
6
6
  import { prepareRun } from "./setup.mjs"
7
+ // 跨轮机读投影(CONTEXT-COMPACTION.md §1.1 ∥ SESSION.md §2 · 台账 #2395):安全接缝 = 本档——
8
+ // 蒸馏得到之后、注入异步结果与本轮输入之前先把上一完成轮折叠掉。
9
+ import { applyTurnProjection, createTurnLedger, findTurnStartIndex } from "./turn-projection.mjs"
7
10
  import {
8
11
  restoreGuard, // digest D-S6 读侧单点(AGENT-LOOP-ASYNC-POOL.md §6.8;P2 机制层端差批 §2.18——键清单归核)
9
12
  AUTO_TURN_DIGEST_DOMAIN,
@@ -23,6 +26,20 @@ export async function beginRun(agent, input, callbacks, {
23
26
  agent._pendingDistill = null
24
27
  await p
25
28
  }
29
+ // ── 跨轮机读投影(CONTEXT-COMPACTION.md §1.1 · 台账 #2395)──
30
+ // 安全接缝三条理由(设计 §2):①上一轮已完成且已登记(`_turnPending`)⇒ 把它的原始机读过程
31
+ // 折叠为「用户请求 ∥ 最终回复 ∥ 任务状态」;②投影在 `await _pendingDistill` **之后**——蒸馏会
32
+ // 异步替换 `agent.history`,先等待才作用在最终数组上,不被后到的替换覆盖;③投影在注入异步结果
33
+ // 与本轮输入**之前**——本轮得到的工具过程原样完整(轮内第二次请求照旧看得见)。
34
+ applyTurnProjection(agent)
35
+ // 本轮原始段起点(续跑沿用链起点——链是同一轮):**用户输入消息**所在位——输入之前的运行注入
36
+ // (环境行 ∥ 文档与记忆注入 ∥ 异步结果)属于上下文,不随折叠消失。尚未推到输入(续跑)⇒ 不动。
37
+ if (!resume) agent._turnStartLen = null
38
+ // 账本:续跑沿用同一本(链内各段一笔账);新回合重开一本(中止 ∥ 异常后也不沿用旧账)。
39
+ // 自动 / 上行 / 定时轮不伪造用户请求(设计 §2;三类均无用户输入)。
40
+ if (!resume) {
41
+ agent._turnLedger = createTurnLedger({ input, autoTurn: autoTurn || upstreamTurn || timerTurn, goal: agent.goal ?? null })
42
+ }
26
43
  // AGENT-LOOP-ASYNC-POOL.md §6.8 D-S3: suspension-settled async results inject before EVERY run's prepareRun
27
44
  // (user + auto-turn); spliced = consumed. collectSettledAsync owns a different
28
45
  // container, so no double-inject across the two consumption points.
@@ -86,6 +103,9 @@ export async function beginRun(agent, input, callbacks, {
86
103
  }
87
104
  }
88
105
  agent._inAutoTurn = autoTurn // spawn gate for manual-tier digests (AGENT-LOOP-ASYNC-POOL.md §6.8 D-S6/N3;上行唤醒轮同持 autoTurn——§6.27.12.4 ①)
106
+ // 投影段起点的搜索下界(台账 #2395):本次 `prepareRun` 将要推入的区间起点——
107
+ // 只在本次推入的消息里找输入(不会误取上一轮的同文请求)。
108
+ const prePrepareLen = agent.history.length
89
109
  const { maxTurns, threshold, toolSchemas, toolByName, systemPrompt } = await prepareRun(
90
110
  // G1/G2(施工②):prompt 装配收口 prepareRun 内部(assemblePrompt——prompt-overlays.mjs
91
111
  // 槽位常量,与子代理角色常量同源——单一权威锚 D1);本调用不再携带 prompt 常量。
@@ -96,6 +116,11 @@ export async function beginRun(agent, input, callbacks, {
96
116
  // Exploration-distillation boundary (CONTEXT-COMPACTION §5): prepareRun already
97
117
  // pushed input + injections — appended from here counts as "this run's" work.
98
118
  agent._runStartHistoryLen = agent.history.length
119
+ // 跨轮机读投影的段起点(台账 #2395):本轮输入消息的下标——`prepareRun` 已把输入与其后的
120
+ // 回合注入推进历史,投影的「本轮原始段」就从那条输入开始(输入之前的运行注入留在机读线)。
121
+ if (!Number.isInteger(agent._turnStartLen)) {
122
+ agent._turnStartLen = resume ? agent.history.length : findTurnStartIndex(agent.history, input, prePrepareLen)
123
+ }
99
124
 
100
125
  // Per-run bookkeeping reset — PRESERVED on `resume` (ContinueError continuation):
101
126
  // mutation/guard continuity and the convergence budget must survive a continuation.
@@ -130,9 +155,21 @@ export async function beginRun(agent, input, callbacks, {
130
155
  agent._zeroWriteAlerted = false
131
156
  agent._verifyRetries = 0
132
157
  agent._advisorRound = 0
158
+ // ADVISOR-CONVERGENCE.md §6.4 B 复位点 1(穷举两处之一):新用户回合起点 · 无继承时——回到完整预算。
159
+ // 「非自动回合」合取:digest / timer / upstream 三类自动回合同样不带 `resume`(同样进本块),
160
+ // 但它们落在周期中间而非起点——不清零,否则「用户回合 → 自动回合 → 用户回合」每段重新拿满 5 条,
161
+ // 上限被自动回合吃掉。自动回合留下的值经 `INHERITED_GUARD_KEYS` 回填(`if (g)` 支)。
162
+ if (!(autoTurn || upstreamTurn || timerTurn)) {
163
+ agent._advisorReminders = 0
164
+ agent._advisorHonestySent = false
165
+ }
133
166
  agent._advisorSession = null // advisor session is per-run: discard when the task ends, next task starts fresh
134
167
  agent._emptyRetries = 0 // empty-response retry budget is per-run: a fresh user turn restarts from zero
135
168
  agent._compressFailures = 0 // compaction summary-failure counter is per-run: a fresh user turn restarts from zero
169
+ // §6.6(AGENT-LOOP.md)两个载体与 `_emptyRetries` 同点复位(链起点):`wrote` 判据(`_batchWrites`)与注入帽计数
170
+ // (`_designTurnNotices`)均按整流累计读——续跑不重置,否则「已落过盘」与「已告知过」的痕迹会被抹掉。
171
+ agent._batchWrites = 0
172
+ agent._designTurnNotices = 0
136
173
  // F-CC2(§6.16.2):模型主动压缩的排队槽也是回合级——上一回合末尾未被安全点消费的请求不得跨回合生效
137
174
  agent._pendingCompact = null
138
175
  }
@@ -32,7 +32,7 @@ import { resolve } from "node:path"
32
32
  import { sessionEnd } from "../session-slots.mjs"
33
33
  import { peerInstances } from "../peer-instances.mjs"
34
34
  import { specForModel } from "../config.mjs"
35
- import { manifestFilePath, readManifest, projectView } from "../manifest.mjs"
35
+ import { docRootPaths, manifestFilePath, readManifest, projectView } from "../manifest.mjs"
36
36
 
37
37
  /** env-state line builder — 对入参 + 进程端名确定(§6.20 端名缝 sessionEnd();setSessionEnd 注入 ⇒ 单元测试可用)。
38
38
  * §6.11(F1):slot 字段入行——位置在 model 后 resumed 前(N3:无绑定 → 显式 null——
@@ -52,7 +52,8 @@ export function envStateLine({ mode, model, slot, resumed }) {
52
52
  * a missing config/history never throws (T-E13).
53
53
  */
54
54
  export function pushEnvStateReminder(agent) {
55
- const mode = agent.config?.agent?.engineering ? "eng" : "normal"
55
+ const workMode = agent.config?.agent?.mode ?? (agent.config?.agent?.engineering ? "engineering" : "normal")
56
+ const mode = workMode === "engineering" ? "eng" : workMode
56
57
  const model = agent.activeModel ?? agent.provider?.model ?? "unknown"
57
58
  const slot = agent._slot ?? null
58
59
  const resumed = agent._envResumed === true
@@ -137,6 +138,12 @@ function refreshManifest(agent) {
137
138
  }
138
139
  if (!m.ok) return // 读回非法 / 缺失 ⇒ 保守(沿用旧值)
139
140
  agent.manifest = m.manifest
141
+ // 设计 ∥ 需求文档根的绝对路径表(#2400 `changedDocs` 的过滤面):manifest 就在手,同一处解析一次——
142
+ // 轮投影保持零 IO(`buildTurnTaskState` 只收 `facts.docRoots`,不自读 manifest),取走的是这条已算好的表。
143
+ agent._docRoots = [
144
+ ...docRootPaths(m.manifest?.docRoot?.design, agent.cwd),
145
+ ...docRootPaths(m.manifest?.docRoot?.requirements, agent.cwd),
146
+ ]
140
147
  agent._manifestMtime = mtimeMs
141
148
  }
142
149
 
package/agent/setup.mjs CHANGED
@@ -22,7 +22,7 @@ import { assembleFamilyTools } from "./family-tools.mjs"
22
22
  import { normalizeOrigin } from "../memory/origin.mjs"
23
23
  import { searchOrigins } from "../memory/code-search.mjs"
24
24
  import { INDEX_ORIGIN_ROW_WARN } from "../memory/schema.mjs"
25
- import { resolveCompactThreshold } from "../config.mjs"
25
+ import { policyBudget, resolveCompactThreshold, resolveWorkMode, setConfigWorkMode } from "../config.mjs"
26
26
  import { safeSliceUTF16 } from "../text-budget.mjs"
27
27
 
28
28
  const DOC_SEARCH_LIMIT = 5
@@ -41,16 +41,25 @@ export async function prepareRun(agent, input, callbacks, {
41
41
  injections = null, toolDecorate = undefined,
42
42
  } = {}) {
43
43
  const maxTurns = overrideTurns ?? agent.config?.agent?.maxTurns ?? DEFAULT_MAX_TURNS
44
+ // Read the sole mode on every run so commands and host controls affect the next request only.
45
+ const mode = resolveWorkMode(agent.config?.agent)
46
+ if (agent.config) setConfigWorkMode(agent.config, mode)
47
+ const tiny = mode === "tiny"
44
48
  // §6.17 每 run 现算:数值在场 = 显式原样;不在场 = auto 现算(按在用 provider——切模型后下一 run 跟手)。
45
- // 派生值不落 agent.compactThreshold(显式键永不被改写)。
46
- const threshold = resolveCompactThreshold(agent.config?.agent?.compactThreshold, agent.provider).value
49
+ // 派生值不落 agent.compactThreshold(显式键永不被改写)。auto 档走**有效窗口**(§2.1):tiny 把压缩线一起压下去。
50
+ const threshold = resolveCompactThreshold(agent.config?.agent?.compactThreshold, agent.provider, mode).value
51
+ // 派生不成立即拒(`CONTEXT-COMPACTION.md` §2.4):装载期的判据点 = 这里,provider 落定之后调一次,
52
+ // 用户在与该模型的第一条读数之前就听到矛盾。喂的是 `policyBudget` 那一边的**有效窗口**——用户开 tiny 时
53
+ // 的可用窗口就是他要用的那个窗(§2.2.1)。显式 `compactThreshold` 会让上面那行跳过派生,所以本行独立走一次:
54
+ // `reserve ≥ window`(`usableWindow`)与 `threshold ≤ 0`(减法链)都在这一行抛出并点三个数。
55
+ policyBudget(agent.provider, undefined, mode)
47
56
  // 注入开关(PROMPT-SYSTEM.md §6.24 · 台账 #1420):判据 `!== false`(缺省 = 现行为零变)——
48
57
  // 逐 run 现读 `agent.config` ⇒ `settings` 工具 ∕ `/config` 写入后本会话下一次组装即生效。
49
- const injectDocs = agent.config?.agent?.injectDocs !== false
58
+ const injectDocs = !tiny && agent.config?.agent?.injectDocs !== false
50
59
  // 2026-10-15(PROMPT-SYSTEM.md §6.27 · 台账 #1465):项目指令块独立开关——与 `injectDocs`
51
60
  // 完全正交(用户 05:05 裁);判点 = 下方 `projectRules` 装配支(原读 `injectDocs` ⇒ 换读本变量)。
52
61
  const injectProjectRules = agent.config?.agent?.injectProjectRules !== false
53
- const injectMemories = agent.config?.agent?.injectMemories !== false
62
+ const injectMemories = !tiny && agent.config?.agent?.injectMemories !== false
54
63
 
55
64
  agent._lastPromptTokens = null
56
65
  agent._usageAtLen = null
@@ -106,7 +115,7 @@ export async function prepareRun(agent, input, callbacks, {
106
115
  agent._processRestartPending = false
107
116
  agent.history.push({ role: "user", content: `[System reminder: process restarted at ${new Date().toISOString()}.]`, transient: true })
108
117
  }
109
- if (agent.memory && !agent.history.some((m) => typeof m.content === "string" && m.content.startsWith(OUTLINE_INJECT_PREFIX))) {
118
+ if (!tiny && agent.memory && !agent.history.some((m) => typeof m.content === "string" && m.content.startsWith(OUTLINE_INJECT_PREFIX))) {
110
119
  try {
111
120
  const { buildSummary } = await import("../tools/repomap.mjs")
112
121
  // §6.14 B4:origin 限定 + 文件数上界(越界 ⇒ 提示行 + 跳过大纲构建——见 repomap.mjs)
@@ -223,7 +232,10 @@ export async function prepareRun(agent, input, callbacks, {
223
232
  })
224
233
  // 两段式:绑定值(基础集)→ 家族段 → caller 注入面(§2.3F 不相交义务在注入方)。
225
234
  const tools = [...agent.tools, ...familyTools, ...(Array.isArray(extraTools) ? extraTools : [])]
226
- const toolSchemas = tools.map(toOpenAISchema)
235
+ // 工具描述按档装配(设计 TOOLS §1):主链取会话现读的 mode;`agent._role === "consult"` 取完整档
236
+ // ——consult 与主链共用这处装配,取会话档就等于把 requirements §9.1「独立基底不被极简装配改写」撤掉。
237
+ const toolMode = agent._role === "consult" ? "normal" : mode
238
+ const toolSchemas = tools.map((tool) => toOpenAISchema(tool, toolMode))
227
239
  const toolByName = new Map(tools.map((t) => [t.name, t]))
228
240
  agent._onTaskUpdate = callbacks.onTaskUpdate
229
241
 
@@ -245,6 +257,7 @@ export async function prepareRun(agent, input, callbacks, {
245
257
  : (depth === 0 || engChildRole) && agent.config?.agent?.engineering
246
258
  ? (engChildRole ?? "engineering")
247
259
  : (depth === 0 ? "normal" : agent._role ?? "normal"),
260
+ mode,
248
261
  )
249
262
  // D2 警告通道 = 既有 setup 警告通道(history 注入)——不新增机制。深度 0 才注入
250
263
  // (子代理警告不打扰主会话历史——旧工程警告块同款深度门)。
@@ -268,10 +281,10 @@ export async function prepareRun(agent, input, callbacks, {
268
281
  // const 声明会 TypeError: Assignment to constant variable(每次 run 必炸)。
269
282
  let systemPrompt = base
270
283
  // 派单固块(台账 #23 · AGENT-LOOP-SUBAGENT.md §6.26):spawn 级固定的机制性指令(批次档路径行 /
271
- // 审计模板)随 system 面下发——固块值在 child 生命周期内恒定 ⇒ run 内前缀逐字节稳定(前缀缓存
272
- // 不破),且不在 `agent.history` 内 ⇒ 压缩只重建 history(吞不掉)。拼接位 = 槽位装配之后、
273
- // 项目指令之前;`_spawnSystemBlock` 为 null/undefined ⇒ 分支不进(depth-0 / explore / plan /
274
- // consult 的 system 逐字节同改前)。
284
+ // 审计模板 / 写域行 / 文档坐标行)随 system 面下发——固块值在 child 生命周期内恒定 ⇒ run 内前缀
285
+ // 逐字节稳定(前缀缓存不破),且不在 `agent.history` 内 ⇒ 压缩只重建 history(吞不掉)。拼接位 =
286
+ // 槽位装配之后、项目指令之前;`_spawnSystemBlock` 为 null/undefined ⇒ 分支不进(depth-0 的 system
287
+ // 逐字节同改前——它不走 `buildSpawnChild`)。子代理可有可无该块:四块里一个都没推 ⇒ 同样不进。
275
288
  if (agent._spawnSystemBlock) systemPrompt += `\n\n${agent._spawnSystemBlock}`
276
289
 
277
290
  // Time injection deliberately does NOT live here: system prompts must be byte-identical
@@ -48,6 +48,41 @@ export { TURN_CAP_MARK, STOPPED_MARK } from "./child-marks.mjs"
48
48
  * schema 层过滤(setup.mjs 受限变体)只是给模型的参数提示——本函数是机械强制。
49
49
  */
50
50
  export const ENG_AUDIT_SPAWN_LIMIT = 6 // 允许 6 次审计 spawn;第 7 次拒绝
51
+
52
+ /** 文件域比较键(与 `agent-tools/subagent-scheduler.mjs` 的 `fileKey` 同律:win32 大小写不敏感)。
53
+ * 本档不 import 那个档(它 import 本档——成环),故这枚三字规则在此重述一次。 */
54
+ const batchKeyOf = (p) => (process.platform === "win32" ? String(p).toLowerCase() : String(p))
55
+
56
+ /** 设计席勘察预算(TOOLS.md §6.29 B7):模型面对 eng-designer 承诺「≤6 explore spawns per batch」,
57
+ * 而 `gateEngCoderSpawn` 对 designer 直接返回 null(不计数)——承诺没有实现。
58
+ *
59
+ * 三处判据都在调用点保证:**角色、同步方式、batchDoc 准入**先过完,本函数只计数
60
+ * (被拒的 spawn 不占额度);计数挂 **depth-0 根 agent 的独立 Map**(挂在一次性 designer child 上
61
+ * 会在 fix respawn 归零;复用 `_engAuditSpawns` 会把两种预算混成一本 —— K5)。
62
+ * @returns {number} 本次是第几次勘察(1 起)
63
+ */
64
+ export function chargeDesignerSurveySpawn(rootAgent, batchDoc) {
65
+ const key = batchKeyOf(batchDoc)
66
+ const map = (rootAgent._engSurveySpawns ??= new Map())
67
+ const used = map.get(key) ?? 0
68
+ if (used >= ENG_AUDIT_SPAWN_LIMIT) {
69
+ throw new Error(`explore survey budget exhausted — ${ENG_AUDIT_SPAWN_LIMIT} explore spawns per batch record, and this record has already used ${used} (${key}). Correction rounds do not reset the budget: finish the design with what these surveys returned, or state the gap in the design document instead of surveying again.`)
70
+ }
71
+ map.set(key, used + 1)
72
+ return used + 1
73
+ }
74
+
75
+ /** depth-0 根 agent(沿 `_upstream.parent` 走上:子代理面拿到的预算载体必须在根上,否则
76
+ * 每次 respawn 都是一本新账)。链断(无 `_upstream`)= 传入者即根。 */
77
+ export function rootAgentOf(agent) {
78
+ let cur = agent
79
+ for (let hop = 0; cur && hop < 8; hop++) {
80
+ const parent = cur._upstream?.parent
81
+ if (!parent) return cur
82
+ cur = parent
83
+ }
84
+ return cur ?? agent
85
+ }
51
86
  export function gateEngCoderSpawn(parent, depth, role, async) {
52
87
  const parentRole = parent?._role
53
88
  if ((depth ?? 0) <= 0 || (parentRole !== "eng-coder" && parentRole !== "eng-designer")) return null
@@ -58,6 +93,8 @@ export function gateEngCoderSpawn(parent, depth, role, async) {
58
93
  throw new Error(`${parentRole} internal spawns are sync-only — the child's report must return before the next protocol step; async spawn is only available at the top level`)
59
94
  }
60
95
  // designer 勘察路径:校验通过即返回 null(非审计——不计数、不触发审计任务书注入)
96
+ // **designer 的勘察预算不在本函数**:它按「设计席自己发起的 explore」计在批档上,
97
+ // 调用点 = `agent-tools/subagent-spawn.mjs` 的 `buildSpawnChild`(TOOLS.md §6.29 B7)。
61
98
  if (parentRole === "eng-designer") return null
62
99
  const attempt = (parent._engAuditSpawns ?? 0) + 1
63
100
  if (attempt > ENG_AUDIT_SPAWN_LIMIT) {
@@ -110,7 +147,7 @@ export function makeRelay(parent, label, emit, model) {
110
147
  // Single source for the event grammar branch lists (consult P3, 2026-08-30):
111
148
  // stripEventToken (display) and stripEventTokensForCapture (capture) shared them
112
149
  // literally — extending the event set meant touching both regexes.
113
- // "done" = AGENT-LOOP-SUBAGENT.md §6.7.3 D-A3 async-child completion event (emitted by the parent's
150
+ // "done" = AGENT-LOOP-SUBAGENT.md §6.7.3 async-child completion event (emitted by the parent's
114
151
  // turn-end collection, not by children — listed so the grammar stays honest).
115
152
  const EVENT_PHASE = "turn|approval|done"
116
153
  const EVENT_TYPE = "llm|tool|approval|done"
package/agent/timers.mjs CHANGED
@@ -94,12 +94,14 @@ export function takeExpiredTimers(agent, now = Date.now()) {
94
94
  return expired
95
95
  }
96
96
 
97
- /** 历史注入单点(逐字形态 = 既有注入单源):逐条 `[System reminder: ⏰ timer — <message>]` 落历史,
98
- * 返回注入的原文(显示面复用同一串——零第二份字面)。 */
97
+ /** 历史注入单点(逐字形态 = 既有注入单源):逐条 `[System reminder: timer — <message>]` 落历史,
98
+ * 返回注入的原文(显示面复用同一串——零第二份字面)。
99
+ * **字符面(AGENT-LOOP-ASYNC-POOL.md §6.30.3)**:前缀段全落在 `/^[\x20-\x7E]+$/`(至 `timer —` 之前)——
100
+ * 缺字形的图标字符不入本行(该行以 `C.warn` 进 CLI 会话流,用户在终端直接读到)。 */
99
101
  export function injectTimerReminders(agent, entries) {
100
102
  const lines = []
101
103
  for (const t of entries ?? []) {
102
- const line = `[System reminder: ⏰ timer — ${t.message}]`
104
+ const line = `[System reminder: timer — ${t.message}]`
103
105
  agent.history.push({ role: "user", content: line })
104
106
  lines.push(line)
105
107
  }