@thincoder/core 0.10.13 → 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 (366) hide show
  1. package/CHANGELOG.md +74 -1
  2. package/advisor/convergence.mjs +34 -3
  3. package/advisor/loop.mjs +42 -10
  4. package/advisor/messages.mjs +46 -27
  5. package/advisor/notice.mjs +1 -1
  6. package/advisor/project-context.mjs +253 -14
  7. package/advisor/run.mjs +7 -4
  8. package/advisor.mjs +29 -43
  9. package/agent/batch-attribution.mjs +87 -0
  10. package/agent/batch-changed-surface.mjs +129 -0
  11. package/agent/completion.mjs +57 -4
  12. package/agent/digest-account.mjs +73 -46
  13. package/agent/dispatch-gates.mjs +6 -0
  14. package/agent/dispatch-run.mjs +1 -1
  15. package/agent/dispatch.mjs +35 -22
  16. package/agent/family-tools.mjs +36 -17
  17. package/agent/helpers.mjs +123 -95
  18. package/agent/offload.mjs +84 -0
  19. package/agent/post-turn.mjs +24 -10
  20. package/agent/record-results.mjs +19 -7
  21. package/agent/run-stages.mjs +127 -61
  22. package/agent/run-start.mjs +45 -8
  23. package/agent/setup-reminders.mjs +9 -2
  24. package/agent/setup.mjs +27 -22
  25. package/agent/spawn-child.mjs +38 -1
  26. package/agent/suspension.mjs +1 -1
  27. package/agent/timers.mjs +5 -3
  28. package/agent/turn-loop.mjs +60 -6
  29. package/agent/turn-projection.mjs +386 -0
  30. package/agent/turn-task-state.mjs +274 -0
  31. package/agent/turn-tool-process.mjs +168 -0
  32. package/agent/write-face.mjs +99 -0
  33. package/agent/write-gate-ledger.mjs +569 -0
  34. package/agent/write-gate.mjs +39 -13
  35. package/agent-tools/advisor-async.mjs +29 -169
  36. package/agent-tools/advisor-launch.mjs +178 -0
  37. package/agent-tools/advisor-settle.mjs +28 -1
  38. package/agent-tools/advisor.mjs +136 -31
  39. package/agent-tools/async-settle.mjs +2 -2
  40. package/agent-tools/audit-block.mjs +6 -6
  41. package/agent-tools/bash-async.mjs +8 -2
  42. package/agent-tools/batch-closeout.mjs +444 -0
  43. package/agent-tools/batch-gate.mjs +152 -138
  44. package/agent-tools/batch-ledger-bind.mjs +392 -0
  45. package/agent-tools/batch-ledger-link.mjs +73 -0
  46. package/agent-tools/batch-ledger-view.mjs +109 -0
  47. package/agent-tools/batch-lifecycle.mjs +245 -376
  48. package/agent-tools/batch-paths.mjs +73 -47
  49. package/agent-tools/batch-read.mjs +1 -1
  50. package/agent-tools/batch-record-write.mjs +417 -0
  51. package/agent-tools/batch-regions.mjs +215 -0
  52. package/agent-tools/batch-reopen.mjs +154 -0
  53. package/agent-tools/batch-segment-vocab.mjs +379 -0
  54. package/agent-tools/batch-skeleton.mjs +344 -196
  55. package/agent-tools/batch-supersede.mjs +232 -0
  56. package/agent-tools/batch-tier-gate.mjs +297 -0
  57. package/agent-tools/batch.mjs +189 -253
  58. package/agent-tools/consult.mjs +7 -4
  59. package/agent-tools/context.mjs +47 -17
  60. package/agent-tools/design-review-record.mjs +225 -0
  61. package/agent-tools/design-slots.mjs +24 -24
  62. package/agent-tools/design-token.mjs +318 -39
  63. package/agent-tools/doc-check.mjs +55 -29
  64. package/agent-tools/doc-graph.mjs +140 -0
  65. package/agent-tools/eng.mjs +10 -9
  66. package/agent-tools/escalate-async.mjs +5 -5
  67. package/agent-tools/manifest.mjs +34 -15
  68. package/agent-tools/read-history.mjs +115 -14
  69. package/agent-tools/review-facts.mjs +40 -15
  70. package/agent-tools/settings.mjs +23 -2
  71. package/agent-tools/spawn-gates.mjs +19 -22
  72. package/agent-tools/ssh-session.mjs +120 -111
  73. package/agent-tools/ssh-text.mjs +155 -0
  74. package/agent-tools/ssh-transfer.mjs +210 -0
  75. package/agent-tools/ssh-transport.mjs +183 -81
  76. package/agent-tools/subagent-actions-query.mjs +11 -7
  77. package/agent-tools/subagent-actions.mjs +1 -1
  78. package/agent-tools/subagent-async.mjs +11 -11
  79. package/agent-tools/subagent-brief.mjs +76 -0
  80. package/agent-tools/subagent-design-token.mjs +168 -0
  81. package/agent-tools/subagent-run.mjs +1 -1
  82. package/agent-tools/subagent-scheduler.mjs +45 -11
  83. package/agent-tools/subagent-spawn.mjs +143 -104
  84. package/agent-tools/subagent.mjs +26 -23
  85. package/agent-tools/taskbook-block.mjs +94 -0
  86. package/agent-tools/timer.mjs +12 -8
  87. package/agent-tools/verify.mjs +13 -4
  88. package/agent-tools.mjs +7 -3
  89. package/agent.mjs +20 -1
  90. package/attachments.mjs +3 -3
  91. package/browser/actions.mjs +9 -3
  92. package/browser/cdp.mjs +45 -17
  93. package/browser/launch.mjs +25 -43
  94. package/browser/pool.mjs +299 -0
  95. package/browser/queue.mjs +2 -0
  96. package/browser/session-state.mjs +450 -0
  97. package/browser/session.mjs +127 -151
  98. package/browser/snapshot.mjs +89 -0
  99. package/client-identity.mjs +22 -6
  100. package/config-defaults.mjs +2 -1
  101. package/config-migrate.mjs +40 -0
  102. package/config-normalize.mjs +28 -2
  103. package/config-presets.mjs +5 -3
  104. package/config-reload.mjs +59 -0
  105. package/config.mjs +62 -98
  106. package/context-degrade.mjs +38 -10
  107. package/context-echo.mjs +11 -0
  108. package/context.mjs +165 -68
  109. package/conventions.mjs +11 -9
  110. package/declaration.mjs +33 -7
  111. package/declared-repos.mjs +94 -0
  112. package/doc-check/doc-names.mjs +73 -0
  113. package/doc-check/doc-tokens.mjs +110 -0
  114. package/doc-check/existence.mjs +160 -0
  115. package/doc-check/index.mjs +312 -163
  116. package/doc-check/line-refs.mjs +38 -0
  117. package/doc-check/paragraph.mjs +220 -91
  118. package/doc-graph/anchors.mjs +474 -0
  119. package/doc-graph/doc-batch-face.mjs +59 -0
  120. package/doc-graph/doc-suffix.mjs +27 -0
  121. package/doc-graph/graph-tokens.mjs +160 -0
  122. package/doc-graph.mjs +778 -0
  123. package/explore-distill.mjs +12 -6
  124. package/i18n.mjs +2 -2
  125. package/index-discover.mjs +4 -1
  126. package/instance-inbox-watch.mjs +272 -0
  127. package/instance-inbox.mjs +218 -0
  128. package/instance-registry.mjs +179 -0
  129. package/knowledge/README.md +3 -0
  130. package/knowledge/prompt-resources.md +6 -0
  131. package/ledger-close-proof.mjs +95 -62
  132. package/ledger-close.mjs +188 -0
  133. package/ledger-cmd.mjs +76 -244
  134. package/ledger-consistency.mjs +113 -0
  135. package/ledger-db.mjs +70 -37
  136. package/ledger-executors.mjs +1 -1
  137. package/ledger-migrate.mjs +4 -4
  138. package/ledger-read.mjs +10 -8
  139. package/ledger-surface.mjs +1 -1
  140. package/ledger-tools.mjs +83 -24
  141. package/ledger-variant-notice.mjs +1 -1
  142. package/ledger-write-ops.mjs +462 -0
  143. package/ledger.mjs +2 -2
  144. package/manifest-discovery.mjs +5 -3
  145. package/manifest-schema.mjs +28 -2
  146. package/memory/memory-tool.mjs +5 -2
  147. package/memory/schema.mjs +6 -27
  148. package/package.json +3 -1
  149. package/path-resolve.mjs +498 -0
  150. package/permission.mjs +4 -0
  151. package/prompt-files.mjs +91 -1
  152. package/prompt-overlays.mjs +14 -6
  153. package/prompts/advisor-design.md +66 -22
  154. package/prompts/advisor-round1.md +37 -3
  155. package/prompts/advisor-round2.md +44 -10
  156. package/prompts/advisor-round3.md +43 -9
  157. package/prompts/common.md +15 -375
  158. package/prompts/consult-base.md +6 -1
  159. package/prompts/discipline-engineering.md +251 -95
  160. package/prompts/discipline-normal.md +4 -250
  161. package/prompts/knowledge/business-gates.md +22 -0
  162. package/prompts/knowledge/decision-quality.md +23 -0
  163. package/prompts/knowledge/doc-lookup.md +35 -0
  164. package/prompts/knowledge/document-writing.md +51 -0
  165. package/prompts/knowledge/documentation-evaluation.md +56 -0
  166. package/prompts/knowledge/evidence-discipline.md +57 -0
  167. package/prompts/knowledge/normal-coding-workflow.md +104 -0
  168. package/prompts/knowledge/normal-delivery-collaboration.md +108 -0
  169. package/prompts/knowledge/normal-work-management.md +57 -0
  170. package/prompts/knowledge/product-security.md +23 -0
  171. package/prompts/knowledge/project-records.md +62 -0
  172. package/prompts/knowledge/tool-advisor.md +29 -0
  173. package/prompts/knowledge/tool-apply-patch.md +18 -0
  174. package/prompts/knowledge/tool-bash.md +39 -0
  175. package/prompts/knowledge/tool-batch-eng-coder.md +12 -0
  176. package/prompts/knowledge/tool-batch-eng-designer.md +12 -0
  177. package/prompts/knowledge/tool-batch-review.md +12 -0
  178. package/prompts/knowledge/tool-batch.md +80 -0
  179. package/prompts/knowledge/tool-browser.md +57 -0
  180. package/prompts/knowledge/tool-code-search.md +4 -0
  181. package/prompts/knowledge/tool-consult-start.md +12 -0
  182. package/prompts/knowledge/tool-consult-stop.md +6 -0
  183. package/prompts/knowledge/tool-context.md +6 -0
  184. package/prompts/knowledge/tool-delete.md +17 -0
  185. package/prompts/knowledge/tool-doc-check.md +70 -0
  186. package/prompts/knowledge/tool-doc-graph-read.md +20 -0
  187. package/prompts/knowledge/tool-doc-graph.md +49 -0
  188. package/prompts/knowledge/tool-doc-search.md +6 -0
  189. package/prompts/knowledge/tool-edit.md +38 -0
  190. package/prompts/knowledge/tool-eng.md +2 -0
  191. package/prompts/knowledge/tool-execute.md +16 -0
  192. package/prompts/knowledge/tool-fetch.md +12 -0
  193. package/prompts/knowledge/tool-file-ops.md +16 -0
  194. package/prompts/knowledge/tool-get-current-time.md +7 -0
  195. package/prompts/knowledge/tool-git-read.md +19 -0
  196. package/prompts/knowledge/tool-git.md +29 -0
  197. package/prompts/knowledge/tool-glob.md +15 -0
  198. package/prompts/knowledge/tool-goal.md +8 -0
  199. package/prompts/knowledge/tool-grep.md +18 -0
  200. package/prompts/knowledge/tool-hashline-edit.md +14 -0
  201. package/prompts/knowledge/tool-insert-after.md +15 -0
  202. package/prompts/knowledge/tool-instance-list.md +6 -0
  203. package/prompts/knowledge/tool-instance-send.md +10 -0
  204. package/prompts/knowledge/tool-knowledge.md +18 -0
  205. package/prompts/knowledge/tool-ledger-read.md +35 -0
  206. package/prompts/knowledge/tool-ledger.md +42 -0
  207. package/prompts/knowledge/tool-lint.md +16 -0
  208. package/prompts/knowledge/tool-ls.md +13 -0
  209. package/prompts/knowledge/tool-lsp.md +11 -0
  210. package/prompts/knowledge/tool-main-history.md +2 -0
  211. package/prompts/knowledge/tool-manifest-read.md +14 -0
  212. package/prompts/knowledge/tool-manifest.md +31 -0
  213. package/prompts/knowledge/tool-memory-read.md +20 -0
  214. package/prompts/knowledge/tool-memory.md +15 -0
  215. package/prompts/knowledge/tool-notify-parent.md +12 -0
  216. package/prompts/knowledge/tool-operations.md +114 -0
  217. package/prompts/knowledge/tool-peer-instances.md +2 -0
  218. package/prompts/knowledge/tool-plan.md +6 -0
  219. package/prompts/knowledge/tool-process-read.md +13 -0
  220. package/prompts/knowledge/tool-process.md +15 -0
  221. package/prompts/knowledge/tool-question.md +16 -0
  222. package/prompts/knowledge/tool-read-history-batch.md +22 -0
  223. package/prompts/knowledge/tool-read-history.md +36 -0
  224. package/prompts/knowledge/tool-read-image.md +11 -0
  225. package/prompts/knowledge/tool-read.md +21 -0
  226. package/prompts/knowledge/tool-recent-changes.md +6 -0
  227. package/prompts/knowledge/tool-repo-outline.md +4 -0
  228. package/prompts/knowledge/tool-settings-read.md +12 -0
  229. package/prompts/knowledge/tool-settings.md +18 -0
  230. package/prompts/knowledge/tool-skill.md +6 -0
  231. package/prompts/knowledge/tool-ssh.md +52 -0
  232. package/prompts/knowledge/tool-subagent.md +59 -0
  233. package/prompts/knowledge/tool-task.md +12 -0
  234. package/prompts/knowledge/tool-team-ledger-read.md +11 -0
  235. package/prompts/knowledge/tool-team-ledger.md +11 -0
  236. package/prompts/knowledge/tool-timer.md +23 -0
  237. package/prompts/knowledge/tool-tree.md +14 -0
  238. package/prompts/knowledge/tool-verify.md +19 -0
  239. package/prompts/knowledge/tool-wait-for.md +25 -0
  240. package/prompts/knowledge/tool-websearch.md +19 -0
  241. package/prompts/knowledge/tool-write.md +9 -0
  242. package/prompts/knowledge/upstream-protocol.md +43 -0
  243. package/prompts/persona-eng-coder.md +29 -3
  244. package/prompts/persona-eng-designer.md +131 -159
  245. package/prompts/persona-engineering.md +202 -131
  246. package/prompts/persona-explore.md +1 -1
  247. package/prompts/persona-plan.md +6 -1
  248. package/prompts/persona-tester.md +55 -0
  249. package/prompts/subagent-base.md +2 -0
  250. package/provider/anthropic.mjs +6 -4
  251. package/provider/core.mjs +5 -4
  252. package/provider/errors.mjs +29 -4
  253. package/provider/google.mjs +39 -12
  254. package/provider/rate.mjs +11 -3
  255. package/provider/responses.mjs +3 -1
  256. package/provider/sse.mjs +15 -4
  257. package/provider-flows.mjs +2 -2
  258. package/session-identity.mjs +21 -0
  259. package/session-index-build.mjs +1 -1
  260. package/session-index-pass.mjs +1 -1
  261. package/session-index-query.mjs +1 -1
  262. package/session-index.mjs +1 -1
  263. package/session-lifecycle.mjs +79 -19
  264. package/session-slot-write.mjs +37 -5
  265. package/session-slots.mjs +9 -14
  266. package/session.mjs +29 -8
  267. package/skip-dirs.mjs +48 -0
  268. package/team-ledger.mjs +17 -13
  269. package/text-budget.mjs +4 -0
  270. package/token-ttl.mjs +73 -4
  271. package/token-window.mjs +244 -34
  272. package/tool-docs/advisor.md +2 -27
  273. package/tool-docs/apply_patch.md +1 -13
  274. package/tool-docs/bash.md +2 -37
  275. package/tool-docs/batch-eng-coder.md +3 -0
  276. package/tool-docs/batch-eng-designer.md +3 -0
  277. package/tool-docs/batch-review.md +3 -0
  278. package/tool-docs/batch.md +3 -1
  279. package/tool-docs/browser.md +2 -47
  280. package/tool-docs/code_search.md +3 -1
  281. package/tool-docs/consult_start.md +2 -4
  282. package/tool-docs/consult_stop.md +2 -2
  283. package/tool-docs/context.md +1 -5
  284. package/tool-docs/delete.md +2 -14
  285. package/tool-docs/doc_check.md +2 -72
  286. package/tool-docs/doc_graph-read.md +3 -0
  287. package/tool-docs/doc_graph.md +3 -0
  288. package/tool-docs/doc_search.md +3 -1
  289. package/tool-docs/edit.md +2 -18
  290. package/tool-docs/eng.md +3 -1
  291. package/tool-docs/execute.md +2 -12
  292. package/tool-docs/fetch.md +2 -12
  293. package/tool-docs/file_ops.md +2 -16
  294. package/tool-docs/get_current_time.md +1 -6
  295. package/tool-docs/git-read.md +3 -0
  296. package/tool-docs/git.md +2 -27
  297. package/tool-docs/glob.md +2 -10
  298. package/tool-docs/goal.md +2 -5
  299. package/tool-docs/grep.md +2 -18
  300. package/tool-docs/hashline_edit.md +2 -13
  301. package/tool-docs/insert_after.md +2 -14
  302. package/tool-docs/instance_list.md +3 -0
  303. package/tool-docs/instance_send.md +3 -0
  304. package/tool-docs/knowledge.md +3 -0
  305. package/tool-docs/ledger-read.md +3 -0
  306. package/tool-docs/ledger.md +3 -8
  307. package/tool-docs/lint.md +2 -9
  308. package/tool-docs/ls.md +2 -11
  309. package/tool-docs/lsp.md +2 -9
  310. package/tool-docs/main_history.md +3 -1
  311. package/tool-docs/manifest-read.md +2 -7
  312. package/tool-docs/manifest.md +2 -28
  313. package/tool-docs/memory-read.md +3 -0
  314. package/tool-docs/memory.md +3 -11
  315. package/tool-docs/notify_parent.md +2 -13
  316. package/tool-docs/peer_instances.md +3 -1
  317. package/tool-docs/plan.md +2 -4
  318. package/tool-docs/process-read.md +3 -0
  319. package/tool-docs/process.md +2 -13
  320. package/tool-docs/question.md +3 -17
  321. package/tool-docs/read.md +2 -19
  322. package/tool-docs/read_history-batch.md +3 -0
  323. package/tool-docs/read_history.md +2 -6
  324. package/tool-docs/read_image.md +2 -7
  325. package/tool-docs/recent_changes.md +3 -1
  326. package/tool-docs/repo_outline.md +3 -1
  327. package/tool-docs/settings-read.md +3 -0
  328. package/tool-docs/settings.md +2 -5
  329. package/tool-docs/skill.md +3 -5
  330. package/tool-docs/ssh.md +2 -50
  331. package/tool-docs/subagent.md +2 -63
  332. package/tool-docs/task.md +2 -6
  333. package/tool-docs/team_ledger-read.md +3 -0
  334. package/tool-docs/team_ledger.md +3 -9
  335. package/tool-docs/timer.md +3 -13
  336. package/tool-docs/tree.md +2 -13
  337. package/tool-docs/verify.md +3 -1
  338. package/tool-docs/wait_for.md +2 -32
  339. package/tool-docs/websearch.md +2 -17
  340. package/tool-docs/write.md +2 -10
  341. package/tools/bash.mjs +12 -2
  342. package/tools/browser.mjs +52 -7
  343. package/tools/doc-write-gate.mjs +73 -0
  344. package/tools/edit-batch.mjs +176 -91
  345. package/tools/edit-diff.mjs +129 -45
  346. package/tools/edit-receipt.mjs +39 -0
  347. package/tools/execute.mjs +11 -5
  348. package/tools/file.mjs +32 -34
  349. package/tools/git.mjs +43 -2
  350. package/tools/index.mjs +6 -0
  351. package/tools/knowledge.mjs +143 -0
  352. package/tools/linter.mjs +3 -3
  353. package/tools/ops.mjs +4 -1
  354. package/tools/patch.mjs +127 -38
  355. package/tools/process-doc-mark.mjs +139 -0
  356. package/tools/search.mjs +15 -6
  357. package/tools/shared.mjs +31 -7
  358. package/tools/ssh.mjs +48 -7
  359. package/tools/tree.mjs +4 -1
  360. package/tools/write-gate-params.mjs +31 -0
  361. package/tools/write-path.mjs +79 -6
  362. package/traces/trace-store.mjs +4 -3
  363. package/window-policy.mjs +203 -0
  364. package/agent/light-round.mjs +0 -63
  365. package/agent/unbooked-pen.mjs +0 -62
  366. package/doc-check/anchors.mjs +0 -135
@@ -1,17 +1,18 @@
1
1
  /**
2
2
  * run-stages.mjs — runAgent 主循环的阶段函数族(CLI,2026-09-05 实践轮:agent.mjs
3
3
  * runAgent 383 ≥300 按骨干—细节两层提取——VS Code 端同构文件(双端 parity——拆分
4
- * 两端同步))。本文件承载:回合压缩检查(runCompactionCheck)、回合注入组
4
+ * 两端同步))。本文件承载:回合压缩检查(runCompactionCheck)、越窗守卫 / 自适应共用原子
5
+ * (enforceContextFit——§6.17 守卫与 §6.17.1 链三共用一个压缩原子)、回合注入组
5
6
  * (injectTurnReminders——plan cadence + eng 状态)、回合收尾(finalizeAgentTurn——
6
7
  * consult 清理/async 池分流/guard 继承)与其收集器(collectSettledAsync——自
7
8
  * agent.mjs 迁入,agent.mjs 内无其他引用)。verbatim 迁移 + 签名化,语义零变。
8
9
  */
9
10
 
10
- import { compressIfNeeded, compressFallback, COMPRESS_FAILURE_LIMIT } from "../context.mjs"
11
- // §6.17/D-CC32 溢出守卫(兜底,非主修):预算面单源 requestBudget ∥ 再估面 contextUsage(与压缩判定同一函数)
12
- 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"
13
14
  import { contextUsage } from "../token-window.mjs"
14
- import { contextOverflowError } from "../provider/errors.mjs"
15
+ import { contextOverflowError, overheadOverflowError } from "../provider/errors.mjs"
15
16
  import { ensureAutoReminder, injectEngineeringReminder, ContinueError, snapshotGuard } from "./helpers.mjs"
16
17
  import { pushManifestStateReminder } from "./setup-reminders.mjs"
17
18
  import { cleanupConsultSessions } from "../agent-tools/consult.mjs"
@@ -26,6 +27,9 @@ import { discardAbortedPool, discardAbortedAdvisors, discardAbortedBgTasks, disc
26
27
  // R10 L3 (MULTI-INSTANCE-COLLAB §2a.5 D-L3a):回合末域登记 flush(写工具钩子累积 →
27
28
  // 整写一次本实例 peers 文件——无写入跳过;失败容忍不抛)
28
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"
29
33
  // 第 30 批 D1(Stop 钩子——AGENT-LOOP.md §6.13):主会话 run 终止事件(触发块见 finalizeAgentTurn)
30
34
  import { runHooks } from "../hooks.mjs"
31
35
 
@@ -73,44 +77,44 @@ export function injectResponseReminders(agent, response) {
73
77
  }
74
78
  }
75
79
 
80
+ // ─── 压缩记账两件(§6.17 阈值面 ∥ 守卫面 ∥ §6.17.1 链三自适应面共用同一段,零复制)───
81
+
82
+ /** 压缩成功记账:失败计数清零 / 计划提醒 cadence 复位 / 停滞检测计数复位 / 完成事件 / AUTO 提醒重注入。 */
83
+ function bookkeepCompaction(agent, ctx) {
84
+ agent._compressFailures = 0
85
+ agent._planReminderAtLen = 0 // After compression history shrinks, reset cadence so reminders resume
86
+ ctx.recentCallSigs.length = 0 // After compression history is rebuilt, reset stall detection counter
87
+ // Completion info (CONTEXT-COMPACTION §7 D-C2): { mode, tokensFreed, elapsedMs } —
88
+ // the TUI panel renders it; callers that ignore the arg keep prior onCompress semantics.
89
+ ctx.callbacks?.onCompress?.(agent._lastCompressInfo ?? {})
90
+ ensureAutoReminder(agent)
91
+ }
92
+
93
+ /** 压缩失败记账——AbortError 必须透传(用户中止不得被当成压缩失败吞掉)。
94
+ * 计数只为面板与 stats 读(§5.1 之后它不再触发任何降级:摘要失败一次当场走丢弃)。 */
95
+ function noteCompressFailure(agent, ctx, compressError) {
96
+ if (compressError?.name === "AbortError" || ctx.signal?.aborted) throw compressError
97
+ agent._compressFailures = (agent._compressFailures ?? 0) + 1
98
+ // Q3 (CONTEXT-COMPACTION §7 D-C1): a failed compression is surfaced to the panel.
99
+ // 降级不再由「连续失败 N 次」触发:`compressIfNeeded` 的 ⑥ 步在失败当次就丢弃(§5.1)。
100
+ ctx.callbacks?.onCompressFail?.(compressError)
101
+ }
102
+
76
103
  /**
77
104
  * 回合压缩检查(2026-09-05 实践轮——自 runAgent 主循环提取):仅安全点(history 以
78
105
  * 完整交换结尾——user/tool 位)。成功:失败计数清零/计划提醒 cadence 复位/停滞检测
79
106
  * 计数复位(recentCallSigs——runAgent 回合级局部——经 ctx 传对象引用)/压缩完成事件
80
- * /AUTO 提醒重注入。失败:AbortError 透传;计数 + Q3 onCompressFail;
81
- * COMPRESS_FAILURE_LIMIT 连续失败降级 compressFallback(确定性截断——不发 LLM)。
107
+ * /AUTO 提醒重注入。失败:AbortError 透传;计数 + Q3 onCompressFail——降级不由「连续失败 N 次」
108
+ * 触发:`compressIfNeeded` 的 ⑥ 步在摘要失败当次就丢弃(§5.1)。
82
109
  * 模型主动压缩(`context` 工具)由本点消费(§6.16.2——取用即清槽;no-op 与失败各落一行注记)。
83
110
  */
84
111
  export async function runCompactionCheck(agent, ctx) {
85
- const { threshold, callbacks, compactionOverhead, signal, recentCallSigs } = ctx
112
+ const { threshold, callbacks, compactionOverhead, signal } = ctx
86
113
  // F-CC2(CONTEXT-COMPACTION.md §6.16.2):模型主动压缩(`context` 工具)在**本安全点**消费——
87
114
  // 取用即清槽(失败不重放;重发由模型再调);`force` 只跳过阈值早退(模型判定优先于阈值),
88
115
  // 其余全同(同 splitHistory / 同尾部预算 / 同摘要链 / 同回注 / 同基线失效)。
89
116
  const pending = agent._pendingCompact
90
117
  agent._pendingCompact = null
91
- // 成功记账(§6.17:成功记账段抽局部——阈值面与守卫面共用同一段,零复制)
92
- const bookkeepCompaction = () => {
93
- agent._compressFailures = 0
94
- agent._planReminderAtLen = 0 // After compression history shrinks, reset cadence so reminders resume
95
- recentCallSigs.length = 0 // After compression history is rebuilt, reset stall detection counter
96
- // Completion info (CONTEXT-COMPACTION §7 D-C2): { mode, tokensFreed, elapsedMs } —
97
- // the TUI panel renders it; callers that ignore the arg keep prior onCompress semantics.
98
- callbacks.onCompress?.(agent._lastCompressInfo ?? {})
99
- ensureAutoReminder(agent)
100
- }
101
- // 压缩失败记账(两处共用:下面的阈值面 catch ∥ 下面的守卫面强制压缩)——AbortError 必须透传。
102
- const noteCompressFailure = (compressError) => {
103
- if (compressError?.name === "AbortError" || signal?.aborted) throw compressError
104
- agent._compressFailures = (agent._compressFailures ?? 0) + 1
105
- // Q3 (CONTEXT-COMPACTION §7 D-C1): a failed compression is surfaced to the panel;
106
- // COMPRESS_FAILURE_LIMIT consecutive failures still degrade to compressFallback.
107
- callbacks?.onCompressFail?.(compressError)
108
- }
109
- const degradeIfCompressExhausted = () => {
110
- if (agent._compressFailures < COMPRESS_FAILURE_LIMIT) return
111
- agent._compressFailures = 0
112
- if (compressFallback(agent)) callbacks.onCompress?.(agent._lastCompressInfo ?? {})
113
- }
114
118
  try {
115
119
  let compacted = await compressIfNeeded(
116
120
  agent, threshold, callbacks,
@@ -118,48 +122,107 @@ export async function runCompactionCheck(agent, ctx) {
118
122
  signal,
119
123
  )
120
124
  if (!compacted && pending) {
121
- // 强制面无可压(短历史无中段)⇒ 记 no-op 注记后**照常**跑阈值面(阈值面不因模型请求让位)
122
- const { compactNoopNote } = await import("../agent-tools/context.mjs")
123
- 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 })
124
134
  compacted = await compressIfNeeded(agent, threshold, callbacks, compactionOverhead, signal)
125
135
  }
126
- if (compacted) bookkeepCompaction()
136
+ if (compacted) bookkeepCompaction(agent, ctx)
127
137
  } catch (compressError) {
128
- noteCompressFailure(compressError)
138
+ noteCompressFailure(agent, ctx, compressError)
129
139
  if (pending) {
130
140
  // 失败注记(§6.16.2 回执面②):模型面告知缺口——既有失败链 / 面板面零改,仅补一行机器注记
131
141
  const { compactFailureNote } = await import("../agent-tools/context.mjs")
132
142
  agent.history.push({ role: "user", content: compactFailureNote(errText(compressError), agent._compressFailures), transient: true })
133
143
  }
134
- degradeIfCompressExhausted()
135
144
  }
136
145
 
137
146
  // 溢出守卫(CONTEXT-COMPACTION.md §6.17 / D-CC32——兜底,非主修;本缝 = catch 闭合后、返回前)。
138
- // 判据 = prompt 估算 > `budget.limit`(**无档次门**——absent 档 limit 取地板 max(window − reserve, threshold),
139
- // 恒为正数、恒可判)。**判据不用 maxTokens**:未发时为 undefined ⇒ NaN ⇒ 守卫静默失效(§6.17)。
140
- // 真 ⇒ 以 force 强制压缩一次(先压再判);再估仍超 ⇒ 抛三实数、回合请求零发。不截断、不静默削输出。
141
- const budget = requestBudget(agent.provider)
147
+ // 判据 / 强压 / 再判 / 抛三实数 全住 `enforceContextFit`——与 §6.17.1 链三的自适应面**同一个原子**(零复制)。
148
+ await enforceContextFit(agent, ctx)
149
+ }
150
+
151
+ /**
152
+ * 越窗守卫 / 自适应共用原子(CONTEXT-COMPACTION.md §6.17 守卫 ∥ §6.17.1 链三自适应):
153
+ * `policyBudget` 判 → 强压一次(`force`)→ 再判 → 抛三实数(不截断、不静默削输出)。
154
+ *
155
+ * `opts.forceCompact`(链三面):**跳过前置估算判据**、直接强压——服务端已判越窗时估算准不准不再作门
156
+ * (本批要治的就是估算低估:死锁现场估 491K < limit 606,784,按估算开门会压 0 次、重试同一请求再吃 400)。
157
+ * 压后仍超的再判两面同判(压后仍越线说明压缩解不了,再压只是重复付费)。
158
+ * 返回是否走到了再判通过(守卫面估算未越线 ⇒ false、零动作;压后仍超⇒抛,不到达返回值)。
159
+ */
160
+ export async function enforceContextFit(agent, ctx, { forceCompact = false } = {}) {
161
+ const { threshold, callbacks, compactionOverhead, signal } = ctx
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))
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)
171
+ if (!forceCompact && !(usage.total > budget.limit)) return false
172
+ // 强压一次:失败走与阈值面同一条记账链(不把摘要错误当回合错误直抛——
173
+ // 记账后仍按「压后仍超」判:⑥ 的丢弃可能已把上下文压到线下)。
174
+ try {
175
+ const compacted = await compressIfNeeded(
176
+ agent, threshold, callbacks, { ...compactionOverhead, force: true }, signal,
177
+ )
178
+ if (compacted) bookkeepCompaction(agent, ctx)
179
+ } catch (compressError) {
180
+ noteCompressFailure(agent, ctx, compressError)
181
+ }
182
+ usage = contextUsage(agent, compactionOverhead)
183
+ if (usage.total > budget.limit) {
184
+ const remedy = "forced compaction ran but the prompt still exceeds the window; reduce the conversation (/compact or prune) before retrying"
185
+ throw contextOverflowError(agent.provider, usage.total, budget, remedy)
186
+ }
187
+ return true
188
+ }
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))
142
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)
143
219
  if (usage.total > budget.limit) {
144
- // 强压一次:失败走与阈值面同一条记账 / 降级链(不把摘要错误当回合错误直抛——
145
- // 记账后仍按「压后仍超」判:降级截断可能已把上下文压到线下)。
146
- try {
147
- const compacted = await compressIfNeeded(
148
- agent, threshold, callbacks, { ...compactionOverhead, force: true }, signal,
149
- )
150
- if (compacted) bookkeepCompaction()
151
- } catch (compressError) {
152
- noteCompressFailure(compressError)
153
- degradeIfCompressExhausted()
154
- }
155
- usage = contextUsage(agent, compactionOverhead)
156
- if (usage.total > budget.limit) {
157
- const remedy = budget.limit < 0
158
- ? `max_tokens ${budget.maxTokens} alone exceeds the window — lower provider.maxTokens or switch to a larger-window model`
159
- : "forced compaction ran but the prompt still exceeds the window; reduce the conversation (/compact or prune) before retrying"
160
- throw contextOverflowError(agent.provider, usage.total, budget, remedy)
161
- }
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
+ )
162
224
  }
225
+ return true
163
226
  }
164
227
 
165
228
  /**
@@ -207,6 +270,9 @@ export async function finalizeAgentTurn(agent, ctx) {
207
270
  // R10 L3(MULTI-INSTANCE-COLLAB §2a.5 D-L3a):回合末登记 flush——本回合写足迹整写
208
271
  // 一次(首行执行:收尾链后续任何异常都不吞登记);无写入 → 跳过(hot 窗口自然衰减)。
209
272
  flushPeerDomains(agent)
273
+ // 投递面名册走时(MULTI-INSTANCE-COLLAB §5.2 · D-MI28:回合收尾刷新 `updatedAt`,与足迹 flush 同点)——
274
+ // 只刷新已在册条目;失败容忍(吞掉——名册写失败不得影响收尾链后续任何一步)。
275
+ try { refreshInstance({ cwd: agent?.cwd }) } catch { /* NF2:失败容忍 */ }
210
276
  // 第 30 批 D1(Stop 钩子):主会话 run 终止 → fire-and-forget(非阻塞;失败静默——与 PostToolUse 同语义)。
211
277
  // 排除用户中止(Ctrl+C / Ctrl+I——中止后 TUI 重建 controller 续跑或已显式停回合)与 AbortError 展开。
212
278
  if (depth === 0 && !signal?.aborted && thrownError?.name !== "AbortError") {
@@ -226,7 +292,7 @@ export async function finalizeAgentTurn(agent, ctx) {
226
292
  // resumes); the Ctrl+C abort branch below is the only path that aborts them
227
293
  // (cleanupConsultSessions — marked stopped → no digest), and the suspension
228
294
  // driver aborts them on its own abort unwind.
229
- // 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:
230
296
  // - Ctrl+C (plain abort): children were aborted with the parent signal — discard dead
231
297
  // entries (tombstone/out-of-pool/notice — AGENT-LOOP-ASYNC-POOL.md §6.20; no stale
232
298
  // errors injected — user explicitly stopped); consultation sessions are cross-turn
@@ -282,7 +348,7 @@ export async function finalizeAgentTurn(agent, ctx) {
282
348
  // 恒达窗 = 正常 ∥ Abort-continue ∥ 异常抛三径同达;会话停止径不判(清场语义归 finishSuspension)。
283
349
  if (isDigestRound({ autoTurn, upstreamTurn, timerTurn }) && carrierField(agent, "_daSession") === true
284
350
  && !(signal?.aborted && !signal?.reason?.interrupt)) {
285
- accountDigestRound(agent)
351
+ await accountDigestRound(agent) // async(§6.31.5 升级支 ④ 终局披露复用注入器)
286
352
  }
287
353
  agent._inAutoTurn = false
288
354
  // AGENT-LOOP-ASYNC-POOL.md §6.8 D-S6: auto-turn guard marks survive into the next USER run (restored at its
@@ -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.
@@ -31,31 +48,31 @@ export async function beginRun(agent, input, callbacks, {
31
48
  // (consult → injectConsultResult;其余 → injectAsyncResult——族分支同 CONSULTATION.md §6.2 D-R17a/b)
32
49
  // ——单容器一处清,不再逐族三段。
33
50
  // §6.31 消化账务(批 digest-accounting · 2026-10-05 · 台账 #930):**投递 ≠ 销账**——
34
- // 会话态(`_daSession`)投递留容器(覆盖才离容器 / 未见账经消化轮回路重投);fallback
51
+ // 会话态(`_daSession`)投递留容器(覆盖才离容器 / 未见账计一个未签收轮、达 `DA_MISS_LIMIT` 升级——
52
+ // 投递恒一次,无重投回路:批 digest-retry-amplify · 台账 #1850);fallback
35
53
  // (headless / 直连 runAgent)缺省条逐字沿用取尽语义(先离容后注入 ∥ `releaseSettledEntry` 面;
36
54
  // 零账目动作——不销账 / 不重投),已投递未销账条同判据跳过且留容器(§6.31 出口缝② · 父侧裁定 2026-10-05)。
37
55
  const pendingAsync = agent._pendingAsyncResults
38
56
  const { carrierField, releaseChildHold, releaseSettledEntry } = await import("../agent-tools/async-settle.mjs")
39
57
  if (carrierField(agent, "_daSession") === true) {
40
58
  const { armAccountRound, isDigestRound, shouldDeliverEntry, digestAccountRequirement } = await import("./digest-account.mjs")
41
- armAccountRound(agent) // §6.31.5 落痕清位:会话态起跑即清(缺痕 ⇒ 全条未覆盖——安全方向)
59
+ armAccountRound(agent) // §6.31.5 落痕清位:会话态起跑即清(缺痕 ⇒ 该轮按未签收判一个轮次)
42
60
  if (pendingAsync?.length) {
43
61
  const { injectAsyncResult } = await import("../agent-tools/subagent.mjs")
44
62
  const { injectConsultResult } = await import("../agent-tools/consult.mjs")
45
63
  const digestRound = isDigestRound({ autoTurn, upstreamTurn, timerTurn })
46
- // 投递门控两态(§6.31.4 · §6.34 收窄):首投**仅系统轮**(`autoTurn`——用户回合零注入)∥ 重投仅消化轮;
47
- // 注入后**留容器**(不 splice)。
64
+ // 投递门控单门(§6.31.4 · 投递恒一次):首投**仅系统轮**(`autoTurn`——用户回合零注入),
65
+ // 已投递条恒跳过;注入后**留容器**(不 splice)。
48
66
  // 注入抛错 ⇒ 未投条目(`_daDelivered` 未置)留容器待下轮——收窄既有「splice 先取尽」的丢失窗。
49
67
  for (const e of [...pendingAsync]) {
50
- if (!shouldDeliverEntry(e, digestRound, autoTurn)) continue
68
+ if (!shouldDeliverEntry(e, autoTurn)) continue
51
69
  if (e.role === "consult") await injectConsultResult(agent, e)
52
70
  else await injectAsyncResult(agent, e)
53
71
  e._daDelivered = true
54
- e._daRetry = false
55
- releaseChildHold(e) // 仅释放 `childAgent`——`report` 保留至销账 / 升级(重投需原文)
72
+ releaseChildHold(e) // 仅释放 `childAgent`——`report` 保留至销账 / 升级(升级终局披露需原文)
56
73
  }
57
74
  // 账目要求行(§6.31.3):仅会话态消化轮且未销账清单非空时注入(先投递后拼清单——
58
- // 含本回合首投 / 重投);两档同发(手动 / AUTO);transient(机器线独有)。
75
+ // 含本回合首投);两档同发(手动 / AUTO);transient(机器线独有)。
59
76
  if (digestRound) {
60
77
  const ids = pendingAsync.filter((e) => e._daDelivered === true).map((e) => e.id)
61
78
  if (ids.length > 0) {
@@ -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,21 +22,11 @@ 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
+ import { safeSliceUTF16 } from "../text-budget.mjs"
26
27
 
27
28
  const DOC_SEARCH_LIMIT = 5
28
29
  const DOC_CHUNK_PREVIEW_LEN = 300
29
- /** UTF-16 安全截断(2026-09-02 deepseek 400 根因):slice(0, N) 按码元切会把 emoji 代理对切成孤立
30
- * 高代理(如 🔴=U+D83D+DD34 只剩 D83D)——deepseek 解析器严格 UTF-16 报 400
31
- * "unexpected end of hex escape"。截断点落在高代理上时向前收一个码元。 */
32
- function safeSliceUTF16(text, max) {
33
- if (text.length <= max) return text
34
- const end = max
35
- // 截断点恰在高代理(D800-DBFF)上 → 收到高代理之前(不带它)
36
- const cp = text.charCodeAt(end - 1)
37
- if (cp >= 0xd800 && cp <= 0xdbff) return text.slice(0, end - 1)
38
- return text.slice(0, end)
39
- }
40
30
  const MEMORY_SEARCH_LIMIT = 3
41
31
 
42
32
  /**
@@ -51,22 +41,33 @@ export async function prepareRun(agent, input, callbacks, {
51
41
  injections = null, toolDecorate = undefined,
52
42
  } = {}) {
53
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"
54
48
  // §6.17 每 run 现算:数值在场 = 显式原样;不在场 = auto 现算(按在用 provider——切模型后下一 run 跟手)。
55
- // 派生值不落 agent.compactThreshold(显式键永不被改写)。
56
- 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)
57
56
  // 注入开关(PROMPT-SYSTEM.md §6.24 · 台账 #1420):判据 `!== false`(缺省 = 现行为零变)——
58
57
  // 逐 run 现读 `agent.config` ⇒ `settings` 工具 ∕ `/config` 写入后本会话下一次组装即生效。
59
- const injectDocs = agent.config?.agent?.injectDocs !== false
58
+ const injectDocs = !tiny && agent.config?.agent?.injectDocs !== false
60
59
  // 2026-10-15(PROMPT-SYSTEM.md §6.27 · 台账 #1465):项目指令块独立开关——与 `injectDocs`
61
60
  // 完全正交(用户 05:05 裁);判点 = 下方 `projectRules` 装配支(原读 `injectDocs` ⇒ 换读本变量)。
62
61
  const injectProjectRules = agent.config?.agent?.injectProjectRules !== false
63
- const injectMemories = agent.config?.agent?.injectMemories !== false
62
+ const injectMemories = !tiny && agent.config?.agent?.injectMemories !== false
64
63
 
65
64
  agent._lastPromptTokens = null
66
65
  agent._usageAtLen = null
67
66
  // §6.17 估算自校准比(`_tok` / `_tokRatio`)**不在本处清**:本函数是每 run 的 pre-flight,
68
67
  // 而在每轮用户消息上归零会让池化比退化成单样本(R2 失效)。初值在 `agent.mjs` 构造字面量,
69
68
  // 清空点 = `/new`(`session-lifecycle.mjs`)∥ `key` 变自清(`token-window.mjs` `recordTokenSample`)。
69
+ // §6.17.1 链三自适应额度:run 级一次——本处复位(一次 = 全部额度;同一 run 内第二次独立越窗直接抛)。
70
+ agent._overflowRetried = false
70
71
  // Cumulative provider cache accounting (batch 2026-10-18-context-cache-visibility):
71
72
  // the service reports prompt_cache_hit/miss per response; the terminal faces each kept
72
73
  // their own tally, so the CORE had none and `context` could not report cache efficiency.
@@ -114,7 +115,7 @@ export async function prepareRun(agent, input, callbacks, {
114
115
  agent._processRestartPending = false
115
116
  agent.history.push({ role: "user", content: `[System reminder: process restarted at ${new Date().toISOString()}.]`, transient: true })
116
117
  }
117
- 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))) {
118
119
  try {
119
120
  const { buildSummary } = await import("../tools/repomap.mjs")
120
121
  // §6.14 B4:origin 限定 + 文件数上界(越界 ⇒ 提示行 + 跳过大纲构建——见 repomap.mjs)
@@ -231,7 +232,10 @@ export async function prepareRun(agent, input, callbacks, {
231
232
  })
232
233
  // 两段式:绑定值(基础集)→ 家族段 → caller 注入面(§2.3F 不相交义务在注入方)。
233
234
  const tools = [...agent.tools, ...familyTools, ...(Array.isArray(extraTools) ? extraTools : [])]
234
- 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))
235
239
  const toolByName = new Map(tools.map((t) => [t.name, t]))
236
240
  agent._onTaskUpdate = callbacks.onTaskUpdate
237
241
 
@@ -253,6 +257,7 @@ export async function prepareRun(agent, input, callbacks, {
253
257
  : (depth === 0 || engChildRole) && agent.config?.agent?.engineering
254
258
  ? (engChildRole ?? "engineering")
255
259
  : (depth === 0 ? "normal" : agent._role ?? "normal"),
260
+ mode,
256
261
  )
257
262
  // D2 警告通道 = 既有 setup 警告通道(history 注入)——不新增机制。深度 0 才注入
258
263
  // (子代理警告不打扰主会话历史——旧工程警告块同款深度门)。
@@ -276,10 +281,10 @@ export async function prepareRun(agent, input, callbacks, {
276
281
  // const 声明会 TypeError: Assignment to constant variable(每次 run 必炸)。
277
282
  let systemPrompt = base
278
283
  // 派单固块(台账 #23 · AGENT-LOOP-SUBAGENT.md §6.26):spawn 级固定的机制性指令(批次档路径行 /
279
- // 审计模板)随 system 面下发——固块值在 child 生命周期内恒定 ⇒ run 内前缀逐字节稳定(前缀缓存
280
- // 不破),且不在 `agent.history` 内 ⇒ 压缩只重建 history(吞不掉)。拼接位 = 槽位装配之后、
281
- // 项目指令之前;`_spawnSystemBlock` 为 null/undefined ⇒ 分支不进(depth-0 / explore / plan /
282
- // consult 的 system 逐字节同改前)。
284
+ // 审计模板 / 写域行 / 文档坐标行)随 system 面下发——固块值在 child 生命周期内恒定 ⇒ run 内前缀
285
+ // 逐字节稳定(前缀缓存不破),且不在 `agent.history` 内 ⇒ 压缩只重建 history(吞不掉)。拼接位 =
286
+ // 槽位装配之后、项目指令之前;`_spawnSystemBlock` 为 null/undefined ⇒ 分支不进(depth-0 的 system
287
+ // 逐字节同改前——它不走 `buildSpawnChild`)。子代理可有可无该块:四块里一个都没推 ⇒ 同样不进。
283
288
  if (agent._spawnSystemBlock) systemPrompt += `\n\n${agent._spawnSystemBlock}`
284
289
 
285
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"
@@ -240,7 +240,7 @@ export function startSuspension(ctx) {
240
240
  const done = (async () => {
241
241
  carrier._suspended = true
242
242
  // §6.31.2 会话标记(消化账务批 · 2026-10-05 · 台账 #930):挂起会话期 true——投递留容器 /
243
- // 见账 / 重投回路的唯一判据;退出(finally)置 false ⇒ 会话外回 fallback 语义。
243
+ // 见账的唯一判据;退出(finally)置 false ⇒ 会话外回 fallback 语义。
244
244
  carrier._daSession = true
245
245
  hooks.onCounts?.(backgroundCounts(carrier))
246
246
  let aborted = false
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
  }