@thincoder/core 0.11.1 → 0.11.3

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 (382) hide show
  1. package/CHANGELOG.md +64 -2
  2. package/advisor/compaction.mjs +7 -5
  3. package/advisor/convergence.mjs +34 -3
  4. package/advisor/history.mjs +24 -11
  5. package/advisor/loop.mjs +49 -12
  6. package/advisor/messages.mjs +114 -33
  7. package/advisor/project-context.mjs +171 -42
  8. package/advisor/run.mjs +24 -10
  9. package/advisor.mjs +36 -46
  10. package/agent/batch-attribution.mjs +87 -0
  11. package/agent/batch-changed-surface.mjs +129 -0
  12. package/agent/chat-call.mjs +14 -9
  13. package/agent/completion.mjs +70 -41
  14. package/agent/continue-decision.mjs +14 -8
  15. package/agent/digest-account.mjs +133 -59
  16. package/agent/dispatch-gates.mjs +6 -0
  17. package/agent/dispatch-run.mjs +1 -1
  18. package/agent/dispatch.mjs +10 -4
  19. package/agent/family-tools.mjs +37 -23
  20. package/agent/helpers.mjs +139 -73
  21. package/agent/image-heal.mjs +18 -4
  22. package/agent/offload.mjs +25 -29
  23. package/agent/post-turn.mjs +36 -35
  24. package/agent/record-results.mjs +39 -7
  25. package/agent/run-stages.mjs +132 -52
  26. package/agent/run-start.mjs +150 -78
  27. package/agent/setup-reminders.mjs +194 -91
  28. package/agent/setup.mjs +219 -140
  29. package/agent/spawn-child.mjs +40 -3
  30. package/agent/suspension.mjs +43 -15
  31. package/agent/timers.mjs +9 -4
  32. package/agent/turn-domain-text.mjs +105 -0
  33. package/agent/turn-loop.mjs +84 -27
  34. package/agent/turn-projection.mjs +286 -0
  35. package/agent/turn-task-state.mjs +274 -0
  36. package/agent/turn-tool-process.mjs +163 -0
  37. package/agent/write-gate-ledger.mjs +569 -0
  38. package/agent/write-gate.mjs +29 -352
  39. package/agent-tools/advisor-async.mjs +35 -172
  40. package/agent-tools/advisor-launch.mjs +178 -0
  41. package/agent-tools/advisor-settle.mjs +28 -1
  42. package/agent-tools/advisor.mjs +37 -48
  43. package/agent-tools/async-discard.mjs +7 -2
  44. package/agent-tools/async-settle.mjs +18 -12
  45. package/agent-tools/audit-block.mjs +6 -6
  46. package/agent-tools/bash-async.mjs +5 -2
  47. package/agent-tools/batch-closeout.mjs +223 -35
  48. package/agent-tools/batch-gate.mjs +142 -342
  49. package/agent-tools/batch-ledger-bind.mjs +240 -20
  50. package/agent-tools/batch-ledger-view.mjs +109 -0
  51. package/agent-tools/batch-lifecycle.mjs +197 -48
  52. package/agent-tools/batch-paths.mjs +29 -8
  53. package/agent-tools/batch-read.mjs +151 -4
  54. package/agent-tools/batch-record-write.mjs +417 -0
  55. package/agent-tools/batch-regions.mjs +215 -0
  56. package/agent-tools/batch-reopen.mjs +23 -11
  57. package/agent-tools/batch-segment-vocab.mjs +459 -0
  58. package/agent-tools/batch-skeleton.mjs +196 -239
  59. package/agent-tools/batch-supersede.mjs +232 -0
  60. package/agent-tools/batch-tier-gate.mjs +214 -0
  61. package/agent-tools/batch.mjs +192 -439
  62. package/agent-tools/browser-async.mjs +5 -2
  63. package/agent-tools/consult.mjs +17 -11
  64. package/agent-tools/context.mjs +76 -33
  65. package/agent-tools/design-review-record.mjs +225 -0
  66. package/agent-tools/design-slots.mjs +1 -1
  67. package/agent-tools/design-token.mjs +279 -81
  68. package/agent-tools/digest-budget.mjs +10 -9
  69. package/agent-tools/doc-check.mjs +43 -33
  70. package/agent-tools/doc-graph.mjs +140 -0
  71. package/agent-tools/eng.mjs +12 -12
  72. package/agent-tools/escalate-async.mjs +5 -5
  73. package/agent-tools/goal.mjs +5 -2
  74. package/agent-tools/judge-domain.mjs +347 -0
  75. package/agent-tools/manifest.mjs +34 -18
  76. package/agent-tools/parent-channel.mjs +6 -3
  77. package/agent-tools/plan.mjs +11 -10
  78. package/agent-tools/read-history.mjs +112 -11
  79. package/agent-tools/review-facts.mjs +19 -6
  80. package/agent-tools/settings.mjs +23 -2
  81. package/agent-tools/skill.mjs +7 -8
  82. package/agent-tools/spawn-gates.mjs +14 -24
  83. package/agent-tools/ssh-session.mjs +8 -5
  84. package/agent-tools/ssh-text.mjs +155 -0
  85. package/agent-tools/ssh-transfer.mjs +1 -1
  86. package/agent-tools/ssh-transport.mjs +19 -148
  87. package/agent-tools/subagent-actions-query.mjs +10 -6
  88. package/agent-tools/subagent-actions.mjs +2 -2
  89. package/agent-tools/subagent-async.mjs +19 -17
  90. package/agent-tools/subagent-brief.mjs +76 -0
  91. package/agent-tools/subagent-design-token.mjs +168 -0
  92. package/agent-tools/subagent-run.mjs +1 -1
  93. package/agent-tools/subagent-scheduler.mjs +13 -13
  94. package/agent-tools/subagent-spawn.mjs +92 -112
  95. package/agent-tools/subagent.mjs +16 -28
  96. package/agent-tools/task.mjs +0 -8
  97. package/agent-tools/taskbook-block.mjs +94 -0
  98. package/agent-tools/timer.mjs +12 -8
  99. package/agent-tools/verify.mjs +13 -4
  100. package/agent-tools.mjs +7 -3
  101. package/agent.mjs +26 -7
  102. package/attachments.mjs +3 -3
  103. package/auto-think.mjs +5 -2
  104. package/browser/actions.mjs +9 -3
  105. package/browser/cdp.mjs +45 -17
  106. package/browser/launch.mjs +25 -43
  107. package/browser/pool.mjs +299 -0
  108. package/browser/queue.mjs +2 -0
  109. package/browser/session-state.mjs +450 -0
  110. package/browser/session.mjs +127 -151
  111. package/browser/snapshot.mjs +89 -0
  112. package/client-identity.mjs +1 -1
  113. package/compaction-work-state.mjs +230 -0
  114. package/compress-form.mjs +41 -6
  115. package/config-defaults.mjs +7 -3
  116. package/config-migrate.mjs +40 -0
  117. package/config-normalize.mjs +28 -2
  118. package/config-reload.mjs +59 -0
  119. package/config.mjs +110 -110
  120. package/context-degrade.mjs +93 -34
  121. package/context-echo.mjs +6 -15
  122. package/context-push.mjs +328 -31
  123. package/context.mjs +298 -170
  124. package/conventions.mjs +11 -9
  125. package/declaration.mjs +126 -22
  126. package/declared-repos.mjs +94 -0
  127. package/doc-check/doc-names.mjs +73 -0
  128. package/doc-check/doc-tokens.mjs +110 -0
  129. package/doc-check/existence.mjs +160 -0
  130. package/doc-check/index.mjs +309 -213
  131. package/doc-check/line-refs.mjs +27 -101
  132. package/doc-check/paragraph.mjs +218 -102
  133. package/doc-graph/anchors.mjs +474 -0
  134. package/doc-graph/doc-batch-face.mjs +59 -0
  135. package/doc-graph/doc-suffix.mjs +27 -0
  136. package/doc-graph/graph-tokens.mjs +160 -0
  137. package/doc-graph.mjs +778 -0
  138. package/escape.mjs +6 -5
  139. package/explore-distill.mjs +41 -8
  140. package/generate-title.mjs +10 -1
  141. package/i18n.mjs +1 -1
  142. package/instance-inbox-watch.mjs +272 -0
  143. package/instance-inbox.mjs +218 -0
  144. package/instance-registry.mjs +179 -0
  145. package/knowledge/README.md +3 -0
  146. package/knowledge/prompt-resources.md +10 -0
  147. package/ledger-close-proof.mjs +100 -49
  148. package/ledger-close.mjs +188 -0
  149. package/ledger-cmd.mjs +47 -91
  150. package/ledger-consistency.mjs +113 -0
  151. package/ledger-db.mjs +47 -15
  152. package/ledger-executors.mjs +1 -1
  153. package/ledger-tools.mjs +121 -62
  154. package/ledger-write-ops.mjs +162 -46
  155. package/ledger.mjs +1 -1
  156. package/manifest-discovery.mjs +3 -1
  157. package/manifest-schema.mjs +27 -5
  158. package/memory/docs.mjs +51 -15
  159. package/memory/file-list.mjs +6 -0
  160. package/memory/schema.mjs +2 -2
  161. package/model-specs.mjs +87 -21
  162. package/origin-guard.mjs +190 -0
  163. package/package.json +3 -1
  164. package/path-resolve.mjs +338 -57
  165. package/prompt-files.mjs +114 -2
  166. package/prompt-overlays.mjs +21 -11
  167. package/prompts/advisor-design.md +96 -36
  168. package/prompts/advisor-round1.md +48 -4
  169. package/prompts/advisor-round2.md +54 -10
  170. package/prompts/advisor-round3.md +53 -9
  171. package/prompts/common.md +99 -434
  172. package/prompts/consult-base.md +7 -4
  173. package/prompts/discipline-engineering.md +504 -295
  174. package/prompts/discipline-normal.md +106 -281
  175. package/prompts/knowledge/business-gates.md +30 -0
  176. package/prompts/knowledge/decision-quality.md +21 -0
  177. package/prompts/knowledge/doc-lookup.md +30 -0
  178. package/prompts/knowledge/document-writing.md +33 -0
  179. package/prompts/knowledge/documentation-evaluation.md +48 -0
  180. package/prompts/knowledge/evidence-discipline.md +38 -0
  181. package/prompts/knowledge/normal-coding-workflow.md +110 -0
  182. package/prompts/knowledge/normal-delivery-collaboration.md +124 -0
  183. package/prompts/knowledge/normal-work-management.md +60 -0
  184. package/prompts/knowledge/product-security.md +28 -0
  185. package/prompts/knowledge/project-records.md +73 -0
  186. package/prompts/knowledge/tool-advisor.md +29 -0
  187. package/prompts/knowledge/tool-apply-patch.md +17 -0
  188. package/prompts/knowledge/tool-bash.md +48 -0
  189. package/prompts/knowledge/tool-batch-eng-coder.md +19 -0
  190. package/prompts/knowledge/tool-batch-eng-designer.md +20 -0
  191. package/prompts/knowledge/tool-batch-review.md +18 -0
  192. package/prompts/knowledge/tool-batch.md +94 -0
  193. package/prompts/knowledge/tool-browser.md +68 -0
  194. package/prompts/knowledge/tool-code-search.md +4 -0
  195. package/prompts/knowledge/tool-consult-start.md +12 -0
  196. package/prompts/knowledge/tool-consult-stop.md +6 -0
  197. package/prompts/knowledge/tool-context.md +6 -0
  198. package/prompts/knowledge/tool-delete.md +21 -0
  199. package/prompts/knowledge/tool-doc-check.md +71 -0
  200. package/prompts/knowledge/tool-doc-graph-read.md +20 -0
  201. package/prompts/knowledge/tool-doc-graph.md +49 -0
  202. package/prompts/knowledge/tool-doc-search.md +6 -0
  203. package/prompts/knowledge/tool-edit.md +41 -0
  204. package/prompts/knowledge/tool-eng.md +2 -0
  205. package/prompts/knowledge/tool-execute.md +21 -0
  206. package/prompts/knowledge/tool-fetch.md +18 -0
  207. package/prompts/knowledge/tool-file-ops.md +21 -0
  208. package/prompts/knowledge/tool-get-current-time.md +7 -0
  209. package/prompts/knowledge/tool-git-read.md +21 -0
  210. package/prompts/knowledge/tool-git.md +29 -0
  211. package/prompts/knowledge/tool-glob.md +17 -0
  212. package/prompts/knowledge/tool-goal.md +8 -0
  213. package/prompts/knowledge/tool-grep.md +21 -0
  214. package/prompts/knowledge/tool-hashline-edit.md +16 -0
  215. package/prompts/knowledge/tool-insert-after.md +17 -0
  216. package/prompts/knowledge/tool-instance-list.md +6 -0
  217. package/prompts/knowledge/tool-instance-send.md +10 -0
  218. package/prompts/knowledge/tool-knowledge.md +18 -0
  219. package/prompts/knowledge/tool-ledger-read.md +28 -0
  220. package/prompts/knowledge/tool-ledger.md +46 -0
  221. package/prompts/knowledge/tool-lint.md +16 -0
  222. package/prompts/knowledge/tool-ls.md +15 -0
  223. package/prompts/knowledge/tool-lsp.md +11 -0
  224. package/prompts/knowledge/tool-main-history.md +2 -0
  225. package/prompts/knowledge/tool-manifest-read.md +14 -0
  226. package/prompts/knowledge/tool-manifest.md +34 -0
  227. package/prompts/knowledge/tool-memory-read.md +20 -0
  228. package/prompts/knowledge/tool-memory.md +19 -0
  229. package/prompts/knowledge/tool-notify-parent.md +12 -0
  230. package/prompts/knowledge/tool-operations.md +102 -0
  231. package/prompts/knowledge/tool-peer-instances.md +2 -0
  232. package/prompts/knowledge/tool-plan.md +5 -0
  233. package/prompts/knowledge/tool-process-read.md +13 -0
  234. package/prompts/knowledge/tool-process.md +15 -0
  235. package/prompts/knowledge/tool-question.md +16 -0
  236. package/prompts/knowledge/tool-read-history-batch.md +22 -0
  237. package/prompts/knowledge/tool-read-history.md +35 -0
  238. package/prompts/knowledge/tool-read-image.md +11 -0
  239. package/prompts/knowledge/tool-read.md +22 -0
  240. package/prompts/knowledge/tool-recent-changes.md +6 -0
  241. package/prompts/knowledge/tool-repo-outline.md +4 -0
  242. package/prompts/knowledge/tool-settings-read.md +12 -0
  243. package/prompts/knowledge/tool-settings.md +17 -0
  244. package/prompts/knowledge/tool-skill.md +6 -0
  245. package/prompts/knowledge/tool-ssh.md +74 -0
  246. package/prompts/knowledge/tool-subagent.md +57 -0
  247. package/prompts/knowledge/tool-task.md +14 -0
  248. package/prompts/knowledge/tool-team-ledger-read.md +11 -0
  249. package/prompts/knowledge/tool-team-ledger.md +15 -0
  250. package/prompts/knowledge/tool-timer.md +23 -0
  251. package/prompts/knowledge/tool-tree.md +16 -0
  252. package/prompts/knowledge/tool-verify.md +19 -0
  253. package/prompts/knowledge/tool-wait-for.md +25 -0
  254. package/prompts/knowledge/tool-websearch.md +19 -0
  255. package/prompts/knowledge/tool-write.md +12 -0
  256. package/prompts/knowledge/upstream-protocol.md +45 -0
  257. package/prompts/persona-coder.md +1 -3
  258. package/prompts/persona-eng-coder.md +24 -6
  259. package/prompts/persona-eng-designer.md +150 -171
  260. package/prompts/persona-engineering.md +531 -442
  261. package/prompts/persona-explore.md +1 -3
  262. package/prompts/persona-normal.md +17 -9
  263. package/prompts/persona-plan.md +5 -3
  264. package/prompts/persona-tester.md +0 -2
  265. package/prompts/subagent-base.md +2 -2
  266. package/provider/anthropic.mjs +10 -6
  267. package/provider/core.mjs +8 -5
  268. package/provider/errors.mjs +63 -4
  269. package/provider/google.mjs +29 -10
  270. package/provider/reasoning-echo.mjs +16 -0
  271. package/provider/responses.mjs +7 -3
  272. package/provider/sse.mjs +11 -6
  273. package/provider-flows.mjs +2 -2
  274. package/rules.mjs +11 -10
  275. package/session-index-build.mjs +1 -1
  276. package/session-index-pass.mjs +1 -1
  277. package/session-index-query.mjs +1 -1
  278. package/session-index.mjs +1 -1
  279. package/session-lifecycle.mjs +131 -42
  280. package/session-slot-write.mjs +38 -6
  281. package/session.mjs +30 -11
  282. package/shell-identity.mjs +129 -22
  283. package/skip-dirs.mjs +26 -2
  284. package/team-ledger.mjs +34 -30
  285. package/text-budget.mjs +1 -1
  286. package/think-off.mjs +27 -0
  287. package/token-ttl.mjs +74 -5
  288. package/token-window.mjs +371 -47
  289. package/tool-docs/advisor.md +2 -27
  290. package/tool-docs/apply_patch.md +1 -15
  291. package/tool-docs/bash.md +2 -43
  292. package/tool-docs/batch-eng-coder.md +3 -0
  293. package/tool-docs/batch-eng-designer.md +3 -0
  294. package/tool-docs/batch-review.md +3 -0
  295. package/tool-docs/batch.md +2 -84
  296. package/tool-docs/browser.md +2 -49
  297. package/tool-docs/code_search.md +2 -2
  298. package/tool-docs/consult_start.md +2 -8
  299. package/tool-docs/consult_stop.md +2 -4
  300. package/tool-docs/context.md +1 -5
  301. package/tool-docs/delete.md +2 -17
  302. package/tool-docs/doc_check.md +2 -107
  303. package/tool-docs/doc_graph-read.md +3 -0
  304. package/tool-docs/doc_graph.md +3 -0
  305. package/tool-docs/doc_search.md +2 -4
  306. package/tool-docs/edit.md +1 -38
  307. package/tool-docs/eng.md +3 -1
  308. package/tool-docs/execute.md +2 -18
  309. package/tool-docs/fetch.md +2 -14
  310. package/tool-docs/file_ops.md +2 -18
  311. package/tool-docs/get_current_time.md +1 -6
  312. package/tool-docs/git-read.md +3 -0
  313. package/tool-docs/git.md +2 -35
  314. package/tool-docs/glob.md +2 -10
  315. package/tool-docs/goal.md +1 -6
  316. package/tool-docs/grep.md +2 -18
  317. package/tool-docs/hashline_edit.md +2 -15
  318. package/tool-docs/insert_after.md +2 -16
  319. package/tool-docs/instance_list.md +3 -0
  320. package/tool-docs/instance_send.md +3 -0
  321. package/tool-docs/knowledge.md +3 -0
  322. package/tool-docs/ledger-read.md +3 -0
  323. package/tool-docs/ledger.md +3 -8
  324. package/tool-docs/lint.md +2 -10
  325. package/tool-docs/ls.md +2 -11
  326. package/tool-docs/lsp.md +2 -9
  327. package/tool-docs/main_history.md +3 -1
  328. package/tool-docs/manifest-read.md +2 -8
  329. package/tool-docs/manifest.md +2 -35
  330. package/tool-docs/memory-read.md +3 -0
  331. package/tool-docs/memory.md +2 -20
  332. package/tool-docs/notify_parent.md +2 -13
  333. package/tool-docs/peer_instances.md +3 -1
  334. package/tool-docs/plan.md +1 -5
  335. package/tool-docs/process-read.md +3 -0
  336. package/tool-docs/process.md +2 -13
  337. package/tool-docs/question.md +3 -17
  338. package/tool-docs/read.md +2 -19
  339. package/tool-docs/read_history-batch.md +3 -0
  340. package/tool-docs/read_history.md +2 -18
  341. package/tool-docs/read_image.md +2 -9
  342. package/tool-docs/recent_changes.md +2 -2
  343. package/tool-docs/repo_outline.md +2 -2
  344. package/tool-docs/settings-read.md +3 -0
  345. package/tool-docs/settings.md +1 -12
  346. package/tool-docs/skill.md +2 -6
  347. package/tool-docs/ssh.md +1 -62
  348. package/tool-docs/subagent.md +2 -100
  349. package/tool-docs/task.md +1 -7
  350. package/tool-docs/team_ledger-read.md +3 -0
  351. package/tool-docs/team_ledger.md +3 -9
  352. package/tool-docs/timer.md +2 -19
  353. package/tool-docs/tree.md +2 -13
  354. package/tool-docs/verify.md +2 -12
  355. package/tool-docs/wait_for.md +2 -32
  356. package/tool-docs/websearch.md +2 -19
  357. package/tool-docs/write.md +2 -12
  358. package/tools/browser.mjs +54 -9
  359. package/tools/doc-write-gate.mjs +73 -0
  360. package/tools/edit-batch.mjs +170 -92
  361. package/tools/edit-diff.mjs +78 -62
  362. package/tools/edit-receipt.mjs +39 -0
  363. package/tools/execute.mjs +3 -3
  364. package/tools/file.mjs +28 -14
  365. package/tools/git.mjs +36 -21
  366. package/tools/index.mjs +6 -0
  367. package/tools/knowledge.mjs +143 -0
  368. package/tools/linter.mjs +3 -3
  369. package/tools/ops.mjs +5 -3
  370. package/tools/patch.mjs +124 -44
  371. package/tools/process-doc-mark.mjs +33 -4
  372. package/tools/repomap.mjs +25 -3
  373. package/tools/search.mjs +74 -26
  374. package/tools/shared.mjs +29 -27
  375. package/tools/ssh.mjs +5 -5
  376. package/tools/tree.mjs +32 -10
  377. package/tools/web-deepseek.mjs +1 -1
  378. package/tools/web.mjs +2 -2
  379. package/tools/write-gate-params.mjs +31 -0
  380. package/tools/write-path.mjs +16 -4
  381. package/window-policy.mjs +243 -0
  382. package/doc-check/anchors.mjs +0 -235
@@ -23,7 +23,8 @@
23
23
  * (no code face — settle-side `failureVerdict` parity).
24
24
  * - Mutations feed _touchedFiles and fire-and-forget memory reindex.
25
25
  */
26
- import { pushReal } from "../context.mjs"
26
+ import { pushReal, pushInject, flattenHistory } from "../context.mjs"
27
+ import { logEvent, errText } from "../log.mjs"
27
28
  import { specForModel } from "../config.mjs"
28
29
  import { FILE_MUTATORS, toolTouchPaths } from "./helpers.mjs"
29
30
  import { capHistoryImages } from "../provider/normalize.mjs"
@@ -34,6 +35,11 @@ import { looksLikeReviewOutput, advisorIncompleteMarker } from "../advisor/run.m
34
35
  import { noteReviewDelivered } from "../agent-tools/review-facts.mjs"
35
36
  // #1178:动作级只读分类(settings get ∥ manifest read 类)不失效 verify——谓词单源 = dispatch-gates。
36
37
  import { isReadonlyAction } from "./dispatch-gates.mjs"
38
+ // 跨轮投影的**账本采集点**(CONTEXT-COMPACTION.md §1.1 · 台账 #2395):每一条工具结果入史的同时记一笔
39
+ // 运行记账(验证命令与结果摘要);变更文件面仍走 `_touchedFiles` 既有归集(不另立第二份清单)。
40
+ import { noteTurnToolFacts } from "./turn-projection.mjs"
41
+ // 归属表(收口取材的判据一):记账的同时写下「这笔写服务哪一批」——`_touchedFiles` 形状一字不动。
42
+ import { recordAttribution } from "./batch-attribution.mjs"
37
43
 
38
44
  let _reindexFile = null
39
45
 
@@ -46,11 +52,13 @@ export async function recordToolResults(agent, toolByName, results) {
46
52
  // Multimodal user messages (injected images / not-injected reminders) must NOT be pushed
47
53
  // between tool results of parallel calls — strict providers (DeepSeek) 400 when a tool
48
54
  // message does not immediately follow its assistant tool_calls. Defer to after the loop.
49
- // real: image injections are real messages (pushReal → _fullHistory); reminders stay machine-only.
55
+ // real: image injections are real messages (pushReal → _fullHistory); reminders go to the pending queue.
50
56
  const deferredUserMsgs = []
51
57
 
52
58
  for (const { toolCall, result, ok } of results) {
53
59
  const tool = toolByName.get(toolCall.name)
60
+ // 运行记账先于三条入史分支(多模态 ∥ 普通 ∥ 非视觉提醒)——一条结果只记一次。
61
+ noteTurnToolFacts(agent._turnLedger, { toolCall, result, ok })
54
62
  // Multimodal tools return JSON { text, images } — inject as multimodal user message
55
63
  if (tool?.multimodal && ok) {
56
64
  try {
@@ -134,7 +142,13 @@ export async function recordToolResults(agent, toolByName, results) {
134
142
  // (含类型不可判——run 缺失的 legacy 直调)⇒ 不置「已覆盖」(与 settle 面
135
143
  // 逐条 parity;设计评审保持计入——无代码面)。
136
144
  const incomplete = advisorIncompleteMarker(String(result))
137
- if (!(incomplete && run?.reviewType !== "design")) agent._calledAdvisorThisRun = true
145
+ if (!(incomplete && run?.reviewType !== "design")) {
146
+ agent._calledAdvisorThisRun = true
147
+ // ADVISOR-CONVERGENCE.md §6.4 B 复位点 2(同步面):评审覆盖成立 ⇒ 本未评审周期结束,
148
+ // 下一周期起于完整预算(未完成尾不计——与覆盖标记同一判据分摊)。
149
+ agent._advisorReminders = 0
150
+ agent._advisorHonestySent = false
151
+ }
138
152
  if (reviewId !== undefined) {
139
153
  if (run) {
140
154
  run.round++
@@ -163,22 +177,27 @@ export async function recordToolResults(agent, toolByName, results) {
163
177
  try {
164
178
  const args = JSON.parse(toolCall.arguments)
165
179
  const paths = toolTouchPaths(tool, args)
180
+ const touched = []
166
181
  for (const p of paths) {
167
182
  if (typeof p !== "string" || !p) continue // 非字符串项不拖累合法路径(与 dispatch / VSC 消费面同口径)
168
183
  const abs = resolve(agent.cwd, p)
169
184
  if (!agent._touchedFiles.includes(abs)) agent._touchedFiles.push(abs)
185
+ touched.push(abs)
170
186
  if (agent.memory) {
171
187
  // Fire-and-forget: don't block the agent loop on indexing.
172
- // Reuses a single cached import; errors surface as pending reminders on next turn.
188
+ // Reuses a single cached import; a failure is logged, not injected into the
189
+ // conversation (injecting it as a reminder made the model chase an indexer hiccup).
173
190
  if (!_reindexFile) {
174
191
  const mod = await import("../memory.mjs")
175
192
  _reindexFile = mod.reindexFile
176
193
  }
177
194
  _reindexFile(agent.memory, agent.cwd, abs).catch((e) => {
178
- agent._pendingReminders.push(`[System reminder: background indexing failed for ${toolCall.name} on ${abs}: ${e.message}. This does not affect your work — the code index will catch up on next reindex.]`)
195
+ logEvent("memory:reindex-failed", { tool: toolCall.name, path: abs, err: errText(e, 200) })
179
196
  })
180
197
  }
181
198
  }
199
+ // 归属与路径同一笔记(`agent._batchDoc` 由 spawn 绑定;未绑定 ⇒ 不入表,收口按本批判)。
200
+ recordAttribution(agent, touched, agent._batchDoc)
182
201
  } catch { /* #327:畸形 args(含 null)/ 畸形路径不再裸抛——touchedFiles 尽力而为 */ }
183
202
  }
184
203
  }
@@ -187,8 +206,21 @@ export async function recordToolResults(agent, toolByName, results) {
187
206
  // All tool results committed — now safe to inject deferred multimodal user messages
188
207
  for (const { real, msg } of deferredUserMsgs) {
189
208
  if (real) pushReal(agent, msg)
190
- else agent.history.push(msg)
209
+ else pushInject(agent, msg)
191
210
  }
192
211
  // #853 D-PR32:注入面同函数同预算——history 本体驱逐最老图片(防无界膨胀;发送前另有副本面同函数)。
193
- if (deferredUserMsgs.some((d) => d.real)) agent.history = capHistoryImages(agent.history)
212
+ // 机读线按轮嵌套:预算作用在拍平视图上,按各轮内层长度切片写回(未命中的消息对象仍是原引用)。
213
+ if (deferredUserMsgs.some((d) => d.real)) {
214
+ const flat = flattenHistory(agent.history)
215
+ const capped = capHistoryImages(flat)
216
+ if (capped !== flat) {
217
+ let at = 0
218
+ agent.history = (Array.isArray(agent.history) ? agent.history : []).map((t) => {
219
+ const n = Array.isArray(t?.messages) ? t.messages.length : 0
220
+ const messages = capped.slice(at, at + n)
221
+ at += n
222
+ return { ...t, messages }
223
+ })
224
+ }
225
+ }
194
226
  }
@@ -8,13 +8,23 @@
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
+ // 写面单点(CONTEXT-COMPACTION §1.1):B 段一次性事件一律 `pushInject`(不落机读线);
13
+ // 计划提醒 cadence 的跨调用水位换位置 `{ turn, msg }`。
14
+ import { pushInject, flattenHistory, flatIndexOf } from "../context.mjs"
15
+
16
+ /** 线尾位置(外层最后一个轮元素 + 它内层的长度)——跨调用水位的写法;空线 ⇒ 线头。 */
17
+ function endPositionOf(history) {
18
+ const last = Array.isArray(history) ? history.at(-1) : null
19
+ if (!last) return { turn: 0, msg: 0 }
20
+ return { turn: history.length - 1, msg: Array.isArray(last.messages) ? last.messages.length : 0 }
21
+ }
22
+ // §6.17/D-CC32 溢出守卫(兜底,非主修):预算面单源 `policyBudget`(有效窗口)∥ 再估面 contextUsage(与压缩判定同一函数)
23
+ import { policyBudget } from "../config.mjs"
14
24
  import { contextUsage } from "../token-window.mjs"
15
- import { contextOverflowError } from "../provider/errors.mjs"
25
+ import { contextOverflowError, overheadOverflowError, budgetContradictionError } from "../provider/errors.mjs"
16
26
  import { ensureAutoReminder, injectEngineeringReminder, ContinueError, snapshotGuard } from "./helpers.mjs"
17
- import { pushManifestStateReminder } from "./setup-reminders.mjs"
27
+ import { pushTimeReminder } from "./setup-reminders.mjs"
18
28
  import { cleanupConsultSessions } from "../agent-tools/consult.mjs"
19
29
  import { logEvent, errText } from "../log.mjs"
20
30
  // ASYNC-RESULT-CONTAINER.md D1:池 accessor(absorb 双池——advisor 独立池无队列)
@@ -27,7 +37,10 @@ import { discardAbortedPool, discardAbortedAdvisors, discardAbortedBgTasks, disc
27
37
  // R10 L3 (MULTI-INSTANCE-COLLAB §2a.5 D-L3a):回合末域登记 flush(写工具钩子累积 →
28
38
  // 整写一次本实例 peers 文件——无写入跳过;失败容忍不抛)
29
39
  import { flushPeerDomains } from "../peer-domains.mjs"
30
- // 第 30 批 D1(Stop 钩子——AGENT-LOOP.md §6.13):主会话 run 终止事件(触发块见 finalizeAgentTurn)
40
+ // 投递面名册(MULTI-INSTANCE-COLLAB §5.2 · D-MI28):回合收尾刷新 `updatedAt`(与足迹 flush 同点;
41
+ // 不在册 ⇒ 零动作——入册只发生在取件面装配处)
42
+ import { refreshInstance } from "../instance-registry.mjs"
43
+ // 第 30 批 D1(Stop 钩子——AGENT-LOOP.md §8 Stop 钩子):主会话 run 终止事件(触发块见 finalizeAgentTurn)
31
44
  import { runHooks } from "../hooks.mjs"
32
45
 
33
46
  /** 结束信号缺席提醒(§6.31.7 F-DA5——逐字 = 父侧定稿;与「非 stop 异常」同面)。 */
@@ -45,7 +58,7 @@ export function injectResponseReminders(agent, response) {
45
58
  // warnings so the model sees them before its next response.
46
59
  if (response._warnings?.length) {
47
60
  const deDuplicated = [...new Map(response._warnings.map(w => [w.name || w.pattern, w])).values()]
48
- agent.history.push({
61
+ pushInject(agent, {
49
62
  role: "user",
50
63
  content: `[System reminder — stream rule warnings from your last response:\n${deDuplicated.map(w => `- ${w.name || w.pattern}: ${w.message}`).join("\n")}]`,
51
64
  })
@@ -55,7 +68,7 @@ export function injectResponseReminders(agent, response) {
55
68
  // ⇒ 不得静默当正常——同面异常提醒注入 + `ev:finish-missing` 留痕;partial / interrupted /
56
69
  // ruleTriggered 径零触(网络断流既有 `_warnings` 已覆盖;ruleTriggered 在调用点之前分流)。
57
70
  if (response.finishReason == null && !response.partial && !response.interrupted) {
58
- agent.history.push({ role: "user", content: FINISH_MISSING_REMINDER })
71
+ pushInject(agent, { role: "user", content: FINISH_MISSING_REMINDER })
59
72
  logEvent("ev:finish-missing", { turn: agent._currentTurn ?? 0, auto: agent._inAutoTurn === true, child: agent._logId })
60
73
  }
61
74
 
@@ -67,19 +80,22 @@ export function injectResponseReminders(agent, response) {
67
80
  content_filter: "response blocked by provider content filtering",
68
81
  }
69
82
  const detail = reasonMap[response.finishReason] || `unknown reason "${response.finishReason}"`
70
- agent.history.push({
83
+ pushInject(agent, {
71
84
  role: "user",
72
85
  content: `[System reminder: the previous turn ended abnormally — ${detail}. The assistant response that follows may be incomplete.]`,
73
86
  })
74
87
  }
75
88
  }
76
89
 
77
- // ─── 压缩记账三件(§6.17 阈值面 ∥ 守卫面 ∥ §6.17.1 链三自适应面共用同一段,零复制)───
90
+ // ─── 压缩记账两件(§6.17 阈值面 ∥ 守卫面 ∥ §6.17.1 链三自适应面共用同一段,零复制)───
78
91
 
79
92
  /** 压缩成功记账:失败计数清零 / 计划提醒 cadence 复位 / 停滞检测计数复位 / 完成事件 / AUTO 提醒重注入。 */
80
93
  function bookkeepCompaction(agent, ctx) {
81
94
  agent._compressFailures = 0
82
- agent._planReminderAtLen = 0 // After compression history shrinks, reset cadence so reminders resume
95
+ agent._planReminderAtLen = { turn: 0, msg: 0 } // After compression the line is cut, reset cadence so reminders resume
96
+ // 投递水位(`_advisorResponseAnchor` = 线尾位置)在砍过头部之后失去参照:
97
+ // 线上留下的每条都在那次投递之后 ⇒ 起点归线头(`{ turn: 0, msg: 0 }`),前向取首表(§1.1 读面)。
98
+ if (agent._advisorResponseAnchor !== undefined) agent._advisorResponseAnchor = { turn: 0, msg: 0 }
83
99
  ctx.recentCallSigs.length = 0 // After compression history is rebuilt, reset stall detection counter
84
100
  // Completion info (CONTEXT-COMPACTION §7 D-C2): { mode, tokensFreed, elapsedMs } —
85
101
  // the TUI panel renders it; callers that ignore the arg keep prior onCompress semantics.
@@ -87,28 +103,22 @@ function bookkeepCompaction(agent, ctx) {
87
103
  ensureAutoReminder(agent)
88
104
  }
89
105
 
90
- /** 压缩失败记账——AbortError 必须透传(用户中止不得被当成压缩失败吞掉)。 */
106
+ /** 压缩失败记账——AbortError 必须透传(用户中止不得被当成压缩失败吞掉)。
107
+ * 计数只为面板与 stats 读(§5.1 之后它不再触发任何降级:摘要失败一次当场走丢弃)。 */
91
108
  function noteCompressFailure(agent, ctx, compressError) {
92
109
  if (compressError?.name === "AbortError" || ctx.signal?.aborted) throw compressError
93
110
  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.
111
+ // Q3 (CONTEXT-COMPACTION §7 D-C1): a failed compression is surfaced to the panel.
112
+ // 降级不再由「连续失败 N 次」触发:`compressIfNeeded` 的 ⑥ 步在失败当次就丢弃(§5.1)。
96
113
  ctx.callbacks?.onCompressFail?.(compressError)
97
114
  }
98
115
 
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
116
  /**
107
117
  * 回合压缩检查(2026-09-05 实践轮——自 runAgent 主循环提取):仅安全点(history 以
108
118
  * 完整交换结尾——user/tool 位)。成功:失败计数清零/计划提醒 cadence 复位/停滞检测
109
119
  * 计数复位(recentCallSigs——runAgent 回合级局部——经 ctx 传对象引用)/压缩完成事件
110
- * /AUTO 提醒重注入。失败:AbortError 透传;计数 + Q3 onCompressFail;
111
- * COMPRESS_FAILURE_LIMIT 连续失败降级 compressFallback(确定性截断——不发 LLM)。
120
+ * /AUTO 提醒重注入。失败:AbortError 透传;计数 + Q3 onCompressFail——降级不由「连续失败 N 次」
121
+ * 触发:`compressIfNeeded` 的 ⑥ 步在摘要失败当次就丢弃(§5.1)。
112
122
  * 模型主动压缩(`context` 工具)由本点消费(§6.16.2——取用即清槽;no-op 与失败各落一行注记)。
113
123
  */
114
124
  export async function runCompactionCheck(agent, ctx) {
@@ -125,9 +135,19 @@ export async function runCompactionCheck(agent, ctx) {
125
135
  signal,
126
136
  )
127
137
  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 })
138
+ // 强制面无可压:固定开销单独越线 ⇒ 回执报与守卫同一个原因(`CONTEXT-COMPACTION.md` §5),
139
+ // 否则 = 短历史无中段。两种 no-op 的处置不同,回执不能同一句。
140
+ const { compactNoopNote, compactOverheadNote, compactContradictionNote } = await import("../agent-tools/context.mjs")
141
+ const forced = contextUsage(agent, compactionOverhead)
142
+ const budget = policyBudget(agent.provider)
143
+ // 矛盾格排在非对话面越线之前(`CONTEXT-COMPACTION.md` §2.4):夹住态上 `forced.fixedFloor > budget.limit`
144
+ // 恒成立,先跑那一支会把原因报成 `overhead_exceeds_limit`(讲「压不掉非对话面」),真实原因被挡在后面。
145
+ const note = budget.contradiction
146
+ ? compactContradictionNote(budget.contradiction)
147
+ : forced.fixedFloor > budget.limit
148
+ ? compactOverheadNote(forced, budget.limit, budget.window)
149
+ : compactNoopNote()
150
+ pushInject(agent, { role: "user", content: note })
131
151
  compacted = await compressIfNeeded(agent, threshold, callbacks, compactionOverhead, signal)
132
152
  }
133
153
  if (compacted) bookkeepCompaction(agent, ctx)
@@ -136,9 +156,8 @@ export async function runCompactionCheck(agent, ctx) {
136
156
  if (pending) {
137
157
  // 失败注记(§6.16.2 回执面②):模型面告知缺口——既有失败链 / 面板面零改,仅补一行机器注记
138
158
  const { compactFailureNote } = await import("../agent-tools/context.mjs")
139
- agent.history.push({ role: "user", content: compactFailureNote(errText(compressError), agent._compressFailures), transient: true })
159
+ pushInject(agent, { role: "user", content: compactFailureNote(errText(compressError), agent._compressFailures) })
140
160
  }
141
- degradeIfCompressExhausted(agent, ctx)
142
161
  }
143
162
 
144
163
  // 溢出守卫(CONTEXT-COMPACTION.md §6.17 / D-CC32——兜底,非主修;本缝 = catch 闭合后、返回前)。
@@ -148,7 +167,7 @@ export async function runCompactionCheck(agent, ctx) {
148
167
 
149
168
  /**
150
169
  * 越窗守卫 / 自适应共用原子(CONTEXT-COMPACTION.md §6.17 守卫 ∥ §6.17.1 链三自适应):
151
- * `requestBudget` 判 → 强压一次(`force`)→ 再判 → 抛三实数(不截断、不静默削输出)。
170
+ * `policyBudget` 判 → 强压一次(`force`)→ 再判 → 抛三实数(不截断、不静默削输出)。
152
171
  *
153
172
  * `opts.forceCompact`(链三面):**跳过前置估算判据**、直接强压——服务端已判越窗时估算准不准不再作门
154
173
  * (本批要治的就是估算低估:死锁现场估 491K < limit 606,784,按估算开门会压 0 次、重试同一请求再吃 400)。
@@ -157,13 +176,21 @@ export async function runCompactionCheck(agent, ctx) {
157
176
  */
158
177
  export async function enforceContextFit(agent, ctx, { forceCompact = false } = {}) {
159
178
  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)
179
+ // 判据 = prompt 估算 > `budget.limit`(**无档次门**——`limit = window − reserve`,恒为正数、恒可判;
180
+ // 派生不成立时它已被夹到 `BUDGET_FLOOR_TOKENS`,见 §2.4)。**判据不用 maxTokens**:未发时为 undefined ⇒ NaN ⇒ 守卫静默失效(§6.17)。
181
+ // 预算取**有效窗口**(`CONTEXT-COMPACTION.md` §2.2「stats、守卫和压缩使用同一预算对象」):有效窗口恒等于
182
+ // 模型窗口,守卫与压缩线同一把尺,否则只降阈值不动 limit = 「早压缩但仍放行到模型窗口」,与上界相反。
183
+ const budget = policyBudget(agent.provider)
184
+ // 矛盾格(`CONTEXT-COMPACTION.md` §2.4):先于非对话面越线判——夹住态上 `fixedFloor > limit` 恒成立,
185
+ // 先跑那一支会把原因报成 `overhead_exceeds_limit`。矛盾预算压多少次都装不下,不进强压(零摘要请求)。
186
+ if (budget.contradiction) throw budgetContradictionError(agent.provider, budget)
163
187
  let usage = contextUsage(agent, compactionOverhead)
188
+ // 非对话面单独越线(#2398 · `CONTEXT-COMPACTION.md` §5):history 归零后 `total` 仍等于那六项 ⇒ 压缩无解,
189
+ // 在强压**之前**抛 typed error(`forceCompact` 同样拦:强制压缩跳得过阈值,跳不过这条);报文取六项分段(§5.2)。
190
+ if (usage.fixedFloor > budget.limit) throw overheadOverflowError(agent.provider, budget, usage)
164
191
  if (!forceCompact && !(usage.total > budget.limit)) return false
165
- // 强压一次:失败走与阈值面同一条记账 / 降级链(不把摘要错误当回合错误直抛——
166
- // 记账后仍按「压后仍超」判:降级截断可能已把上下文压到线下)。
192
+ // 强压一次:失败走与阈值面同一条记账链(不把摘要错误当回合错误直抛——
193
+ // 记账后仍按「压后仍超」判:⑥ 的丢弃可能已把上下文压到线下)。
167
194
  try {
168
195
  const compacted = await compressIfNeeded(
169
196
  agent, threshold, callbacks, { ...compactionOverhead, force: true }, signal,
@@ -171,18 +198,55 @@ export async function enforceContextFit(agent, ctx, { forceCompact = false } = {
171
198
  if (compacted) bookkeepCompaction(agent, ctx)
172
199
  } catch (compressError) {
173
200
  noteCompressFailure(agent, ctx, compressError)
174
- degradeIfCompressExhausted(agent, ctx)
175
201
  }
176
202
  usage = contextUsage(agent, compactionOverhead)
177
203
  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"
204
+ const remedy = "forced compaction ran but the prompt still exceeds the window; reduce the conversation (/compact or prune) before retrying"
181
205
  throw contextOverflowError(agent.provider, usage.total, budget, remedy)
182
206
  }
183
207
  return true
184
208
  }
185
209
 
210
+ /**
211
+ * 切换预判(`CONTEXT-COMPACTION.md` §5.2):run 装配之后、第一个回合之前,比一次实测优先的
212
+ * `contextUsage.total` 与 `policyBudget(...).limit`。
213
+ *
214
+ * 存量历史可能超过新窗口:用户从 1M 模型切到 256K 模型、把 `providers[].context` 调小,或改
215
+ * `reasoningEffort`(`max` 档把 `reserve` 抬到 131,072)——这几种变更都让 `limit` 变小,而 `agent.history`
216
+ * 一条没少。不预判就得等下一次请求撞上守卫:报文说 `context_overflow`,用户读到的是「上下文太大」,
217
+ * 真实原因(刚换的配置装不下已有历史)被报文挡在后面。
218
+ *
219
+ * 超了就**跑 §5.1 的同一条处置链**(force 面:prune → 摘要 → 丢弃),不另立第二条路径;跑完仍超 `limit`
220
+ * ⇒ 守卫照 §5 抛三实数,报文点明切换后的模型装不下存量历史。
221
+ * 判据用实测优先的 `contextUsage`:切换前的最后一次响应给过真值,它比估算更接近服务端会看到的量。
222
+ * 返回是否越线(未越线 = 零动作)。
223
+ */
224
+ export async function preflightWindowFit(agent, ctx) {
225
+ const { threshold, callbacks, compactionOverhead, signal } = ctx
226
+ const budget = policyBudget(agent.provider)
227
+ // 矛盾格(`CONTEXT-COMPACTION.md` §2.4):同一个 typed error,比 `fixedFloor > limit` 那一支先判。
228
+ if (budget.contradiction) throw budgetContradictionError(agent.provider, budget)
229
+ let usage = contextUsage(agent, compactionOverhead)
230
+ if (!(usage.total > budget.limit)) return false
231
+ if (usage.fixedFloor > budget.limit) throw overheadOverflowError(agent.provider, budget, usage)
232
+ try {
233
+ const compacted = await compressIfNeeded(
234
+ agent, threshold, callbacks, { ...compactionOverhead, force: true }, signal,
235
+ )
236
+ if (compacted) bookkeepCompaction(agent, ctx)
237
+ } catch (compressError) {
238
+ noteCompressFailure(agent, ctx, compressError)
239
+ }
240
+ usage = contextUsage(agent, compactionOverhead)
241
+ if (usage.total > budget.limit) {
242
+ throw contextOverflowError(
243
+ agent.provider, usage.total, budget,
244
+ "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",
245
+ )
246
+ }
247
+ return true
248
+ }
249
+
186
250
  /**
187
251
  * 回合注入组(2026-09-05 实践轮——自 runAgent 主循环提取):plan-mode 提醒 cadence
188
252
  * (稀疏 2 轮/满 5 轮/新用户消息重置——限制不淡化)+ 工程模式状态注入(depth-0 每新
@@ -193,26 +257,34 @@ export async function injectTurnReminders(agent, ctx) {
193
257
  // Plan-mode reminder cadence: re-inject constraint reminders while plan mode is active
194
258
  // (sparse every 2 turns, full every 5 / on new user message) so the restriction never fades.
195
259
  if (agent.planMode) {
196
- const lastMsg = agent.history.at(-1)
260
+ // 注入不在线上 ⇒ 「最后一条是用户输入」与改前同义(拍平视图的最后一条)。
261
+ const flat = flattenHistory(agent.history)
262
+ const lastMsg = flat.at(-1)
197
263
  const realUserMsg = lastMsg?.role === "user"
198
264
  && typeof lastMsg.content === "string"
199
265
  && !lastMsg.content.startsWith("[System reminder:")
200
266
  && !lastMsg.content.startsWith("[User interrupt:")
201
- const newUserSince = realUserMsg && agent.history.length > (agent._planReminderAtLen ?? 0)
267
+ // 水位 = 位置 `{ turn, msg }`(上一次提醒落线处);与当前线尾比拍平序。
268
+ const since = agent._planReminderAtLen ? flatIndexOf(agent.history, agent._planReminderAtLen) : 0
269
+ const newUserSince = realUserMsg && flat.length > since
202
270
  const { planReminderForTurn } = await import("../agent-tools/plan.mjs")
203
271
  const reminder = planReminderForTurn(agent, newUserSince)
204
272
  if (reminder) {
205
- agent._planReminderAtLen = agent.history.length + 1
206
- agent.history.push({ role: "user", content: reminder, transient: true })
273
+ agent._planReminderAtLen = endPositionOf(agent.history)
274
+ pushInject(agent, { role: "user", content: reminder })
207
275
  }
208
276
  }
209
277
 
210
278
  // Engineering-mode status injection on every new user message (design-before-code
211
- // vs standard discipline) — see injectEngineeringReminder.
212
- if (depth === 0) {
213
- injectEngineeringReminder(agent)
214
- pushManifestStateReminder(agent, { depth }) // M1 情境行(MANIFEST.md §2.6——同序组,eng 之后)
215
- }
279
+ // vs standard discipline) — see injectEngineeringReminder。
280
+ // 项目相位 ∥ 报明行不在这里:它随会话头块走(`CONTEXT-COMPACTION.md` §1.1「会话头块」),是会话内恒定的项,
281
+ // 在 run 起点与压缩后刷新,不再每回合重写。
282
+ if (depth === 0) injectEngineeringReminder(agent)
283
+
284
+ // `time` 格每回合覆写(`CONTEXT-COMPACTION.md` §1.1 格位表「每回合一次」):本格对每个
285
+ // 深度都写——「当前时间」对子代理同样是这一回合的事实(`prepareRun` 的 run 起点那一笔已给了首份)。
286
+ // 写入方单点 = `setup-reminders.mjs` 的 `pushTimeReminder`。
287
+ pushTimeReminder(agent)
216
288
  }
217
289
 
218
290
  /**
@@ -225,9 +297,17 @@ export async function injectTurnReminders(agent, ctx) {
225
297
  */
226
298
  export async function finalizeAgentTurn(agent, ctx) {
227
299
  const { signal, autoTurn, upstreamTurn, timerTurn, suspDriven, thrownError, depth } = ctx
300
+ // B 段清场(CONTEXT-COMPACTION §1.1「注入的三段」):一次性事件只活一个回合——清的是**投递副本**
301
+ // (`_pendingInject` 里那条消息),不动待处理账本 `agent._pendingAsyncResults`,也不动投递账
302
+ // (`_daDelivered` 维持真——内容已经给模型看过;清副本不触发任何再投递,与「投递恒一次」及
303
+ // 用例 18-1 ∥ 18-2 的条数相抵)。不在入队处清:整回合内每一次请求都要带它。
304
+ agent._pendingInject = []
228
305
  // R10 L3(MULTI-INSTANCE-COLLAB §2a.5 D-L3a):回合末登记 flush——本回合写足迹整写
229
306
  // 一次(首行执行:收尾链后续任何异常都不吞登记);无写入 → 跳过(hot 窗口自然衰减)。
230
307
  flushPeerDomains(agent)
308
+ // 投递面名册走时(MULTI-INSTANCE-COLLAB §5.2 · D-MI28:回合收尾刷新 `updatedAt`,与足迹 flush 同点)——
309
+ // 只刷新已在册条目;失败容忍(吞掉——名册写失败不得影响收尾链后续任何一步)。
310
+ try { refreshInstance({ cwd: agent?.cwd }) } catch { /* NF2:失败容忍 */ }
231
311
  // 第 30 批 D1(Stop 钩子):主会话 run 终止 → fire-and-forget(非阻塞;失败静默——与 PostToolUse 同语义)。
232
312
  // 排除用户中止(Ctrl+C / Ctrl+I——中止后 TUI 重建 controller 续跑或已显式停回合)与 AbortError 展开。
233
313
  if (depth === 0 && !signal?.aborted && thrownError?.name !== "AbortError") {
@@ -247,7 +327,7 @@ export async function finalizeAgentTurn(agent, ctx) {
247
327
  // resumes); the Ctrl+C abort branch below is the only path that aborts them
248
328
  // (cleanupConsultSessions — marked stopped → no digest), and the suspension
249
329
  // 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:
330
+ // Async subagent turn-end handling (AGENT-LOOP-SUBAGENT.md §6.7.3 + AGENT-LOOP-ASYNC-POOL.md §6.8 D-S1). Lifecycle:
251
331
  // - Ctrl+C (plain abort): children were aborted with the parent signal — discard dead
252
332
  // entries (tombstone/out-of-pool/notice — AGENT-LOOP-ASYNC-POOL.md §6.20; no stale
253
333
  // errors injected — user explicitly stopped); consultation sessions are cross-turn
@@ -287,14 +367,14 @@ export async function finalizeAgentTurn(agent, ctx) {
287
367
  // keep _asyncSubagents/_asyncAdvisors/_consultSessions — the resumed run continues them
288
368
  } else {
289
369
  const injectedAdvisor = await collectSettledAsync(agent, { suspDriven })
290
- // AGENT-LOOP-ASYNC-POOL.md §6.10 D-24b: a normally-ended USER run with no review/child activity closes
370
+ // AGENT-LOOP-ASYNC-POOL.md §5「后台评审」 D-24b: a normally-ended run with no review/child activity closes
291
371
  // the OPEN code instances — the converged/abandoned thread must not burn the
292
372
  // 5-round cap of a later task (the next code review starts a fresh round 1).
293
- // Digest auto-turns are exempt (their disposition precedes the fix round).
373
+ // 收口判据只看「本轮有没有新注入评审报告」,不含轮型(AGENT-LOOP-ASYNC-POOL.md §8.8)。
294
374
  // A run whose turn-end collection just INJECTED a settled review report
295
375
  // (headless, suspDriven=false) must NOT close: the model has not digested
296
376
  // the findings yet — the fix round that follows still continues the thread.
297
- if (!autoTurn && !injectedAdvisor) {
377
+ if (!injectedAdvisor) {
298
378
  const { closeOpenCodeAdvisorRuns } = await import("../agent-tools/advisor-async.mjs")
299
379
  closeOpenCodeAdvisorRuns(agent)
300
380
  }
@@ -346,7 +426,7 @@ async function collectSettledAsync(agent, { suspDriven = false } = {}) {
346
426
  if (!e.done) continue // still running — stays in the pool (D-S1)
347
427
  await injectAsyncResult(agent, e)
348
428
  if (e.role === "advisor") injectedAdvisor = true
349
- // TUI-OOM-ROOTCAUSE(AGENT-LOOP.md §6.15 消费点①——回合尾收集):注入完成 → 释放条目持有
429
+ // TUI-OOM-ROOTCAUSE(AGENT-LOOP.md §9 消费点①——回合尾收集):注入完成 → 释放条目持有
350
430
  releaseSettledEntry(e)
351
431
  map.delete(String(e.id))
352
432
  }