@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
package/agent/setup.mjs CHANGED
@@ -1,34 +1,113 @@
1
1
  /**
2
2
  * agent/setup.mjs — runAgent pre-flight setup: context injection, system prompt construction, tool injection
3
3
  */
4
- /** Local time, second precision, for the per-run transient reminder. */
5
- function timeNowLocal() {
6
- return new Date().toLocaleString("sv-SE")
7
- }
8
-
9
4
  import { search as memorySearch, docSearch } from "../memory.mjs"
10
- import { pushReal } from "../context.mjs"
5
+ // 写面单点(CONTEXT-COMPACTION §1.1):对话 → `pushReal`;A 段当前状态 → `setInject`;B 段一次性事件 → `pushInject`。
6
+ import { pushReal, pushInject } from "../context.mjs"
11
7
  import { toOpenAISchema } from "../tools/index.mjs"
12
- import { loadSkills, formatSkillListing } from "../skills.mjs"
13
- import { scopedRulesBlock } from "../rules.mjs"
14
8
  import { assemblePrompt } from "../prompt-overlays.mjs"
15
9
  import {
16
- escapeXml, repairHistory, listWorkDir,
17
- collectGitContext, loadProjectInstructions, OUTLINE_INJECT_PREFIX,
10
+ escapeXml, repairHistory,
11
+ loadProjectInstructions,
18
12
  DEFAULT_MAX_TURNS, ensureAutoReminder,
19
13
  } from "./helpers.mjs"
20
- import { pushEnvStateReminder, pushPeerReminder, pushInjections } from "./setup-reminders.mjs"
14
+ import { pushSessionHeadBlock, pushPeerReminder, pushInjections, pushTimeReminder, sessionOutlineOf } from "./setup-reminders.mjs"
15
+ // 执行器版本:会话头那一行的版本要等一次探测(硬上限 `SHELL_VERSION_TIMEOUT_MS`),本档是唯一等它的地方。
16
+ import { probeShellVersion, resolveShellIdentity, SHELL_VERSION_TIMEOUT_MS } from "../shell-identity.mjs"
21
17
  import { assembleFamilyTools } from "./family-tools.mjs"
22
18
  import { normalizeOrigin } from "../memory/origin.mjs"
23
19
  import { searchOrigins } from "../memory/code-search.mjs"
24
20
  import { INDEX_ORIGIN_ROW_WARN } from "../memory/schema.mjs"
25
- import { resolveCompactThreshold } from "../config.mjs"
21
+ import { policyBudget, resolveCompactThreshold, resolveWorkMode, setConfigWorkMode } from "../config.mjs"
22
+ // 权威层集合由声明派生(正文单源 = `docs/core/design/DOC-SYSTEM.md` §3.1;本档不持成员名单)。
23
+ import { declarationForTarget, docLayers } from "../conventions.mjs"
26
24
  import { safeSliceUTF16 } from "../text-budget.mjs"
25
+ // §2.4 的响一声:核日志一行(`ev = "budget:contradiction"`)——通道单源仍是 `log.mjs`,本批只新增一个事件名。
26
+ import { logEvent } from "../log.mjs"
27
27
 
28
28
  const DOC_SEARCH_LIMIT = 5
29
29
  const DOC_CHUNK_PREVIEW_LEN = 300
30
30
  const MEMORY_SEARCH_LIMIT = 3
31
31
 
32
+ /**
33
+ * 预留成表(**纯函数**:不读库、不碰盘——取数由调用方以 `fetchLayer(L)` 注入,单测不碰库)。
34
+ *
35
+ * 为什么预留:一次带层过滤的取数只把候选集限定在给定层之内,上限条数仍可能整批来自一层——
36
+ * 过滤不是名额,名额只能按层落实。规则(机制 = `docs/core/design/AGENT-LOOP.md` §4.2「注入面」):
37
+ * · 候选为空 ⇒ 全部层都没命中,补也是空:**不调** `fetchLayer`;
38
+ * · 候选里缺哪个权威层就为该层取一条作预留;候选里已有的层不调、不多占;
39
+ * · 预留行在前(按权威层层序),候选按分数序在后,按 `origin|path|line_start` 去重;
40
+ * · 截断在成表之后——先截候选再并预留,预留行会落在名额之外被截掉;
41
+ * · 某层取回仍空 ⇒ 该层无命中,不欠额、不塞空位(保底是下限不是上限)。
42
+ * @param {Array<object>} candidates 全部层的候选(既有 RRF 序)
43
+ * @param {(layer: string) => Promise<Array<object>>|Array<object>} fetchLayer 单层取数
44
+ * @param {string[]} authorityLayers 该路的权威层(序 = `docRoot` 键序)
45
+ * @param {number} limit 总行数上限
46
+ * @returns {Promise<Array<object>>} 成表后的注入行
47
+ */
48
+ export async function reservedTable(candidates, fetchLayer, authorityLayers, limit) {
49
+ const list = Array.isArray(candidates) ? candidates : []
50
+ const table = []
51
+ const seen = new Set()
52
+ const push = (d) => {
53
+ if (!d) return
54
+ const k = `${d.origin ?? ""}|${d.path ?? ""}|${d.line_start ?? ""}`
55
+ if (seen.has(k)) return
56
+ seen.add(k)
57
+ table.push(d)
58
+ }
59
+ if (list.length > 0) {
60
+ for (const layer of authorityLayers ?? []) {
61
+ if (list.some((d) => d.layer === layer)) continue
62
+ const hit = await fetchLayer(layer)
63
+ if (Array.isArray(hit)) push(hit[0])
64
+ }
65
+ }
66
+ for (const d of list) push(d)
67
+ return table.slice(0, limit)
68
+ }
69
+
70
+ /** 一路 origin 集的权威层(并集,序 = `docRoot` 键序):某 origin 无属辖声明 ⇒ 它不贡献层。 */
71
+ function authorityLayersOf(origins) {
72
+ const out = []
73
+ for (const origin of origins ?? []) {
74
+ const decl = declarationForTarget(origin)
75
+ if (!decl) continue
76
+ for (const l of docLayers(decl)) if (l.authority && !out.includes(l.layer)) out.push(l.layer)
77
+ }
78
+ return out
79
+ }
80
+
81
+ /** 预算矛盾的三个数(§2.4 的提醒与日志同源):矛盾只剩一格——`reserve ≥ window`,报文点 window ∥ reserve ∥ 差值。
82
+ * 旧的比例余量形状(「窗口装得下输出、装不下注入余量」)随比例余量退场,它已不是可达状态。 */
83
+ function contradictionNumbers(contradiction) {
84
+ const c = contradiction ?? {}
85
+ return `window ${c.window} · reserve ${c.reserve} · difference ${c.usable}`
86
+ }
87
+
88
+ /** 响一声(`CONTEXT-COMPACTION.md` §2.4):核日志一行(带 window ∥ reserve ∥ 差值)+ 一条 B 段提醒
89
+ * (点这三个数与三条出路)。同一次 run 里同一条矛盾只响一次——`budgetOf` 一次 run 被调多次
90
+ * (`resolveCompactThreshold` 一次、`policyBudget` 一次,守卫面每次发送前又一次),不判重就刷屏。
91
+ * 去重键 = run 标识 + window + reserve + 差值;换一次 run 重新响一次,因为配置可能已改。
92
+ * 静默仍被禁止:日志、提醒、守卫拒发三件都在,改的只是「在哪儿响」——从 UI 起来之前的装载期挪到运行时。
93
+ * 调用点只有 `prepareRun` 一处;导出面是给本批单测档(`docs/batches/*.test.mjs`)驱动「同一 run 连响三次」那一格用的。
94
+ */
95
+ export function announceBudgetContradiction(agent, contradiction) {
96
+ const key = `${agent._runSeq ?? 0}|${contradiction?.window}|${contradiction?.reserve}|${contradiction?.usable}`
97
+ if (agent._budgetContradictionKey === key) return
98
+ agent._budgetContradictionKey = key
99
+ logEvent("budget:contradiction", {
100
+ window: contradiction?.window, reserve: contradiction?.reserve, delta: contradiction?.usable, run: agent._runSeq ?? 0,
101
+ })
102
+ pushInject(agent, {
103
+ role: "user",
104
+ content: `[System reminder: budget contradiction — ${contradictionNumbers(contradiction)}. No request can be sent on ` +
105
+ `this channel until the configuration changes: raise the window (providers[].modelContext / a larger-context model), ` +
106
+ `lower provider.maxTokens, or use a model whose maxOutput is smaller than its window. ` +
107
+ `The session keeps running so the configuration can be fixed.]`,
108
+ })
109
+ }
110
+
32
111
  /**
33
112
  * Prepare an agent run: inject context, build system prompt, inject tools.
34
113
  * Returns all state needed by the main loop, and writes initialization messages into agent.history.
@@ -41,19 +120,37 @@ export async function prepareRun(agent, input, callbacks, {
41
120
  injections = null, toolDecorate = undefined,
42
121
  } = {}) {
43
122
  const maxTurns = overrideTurns ?? agent.config?.agent?.maxTurns ?? DEFAULT_MAX_TURNS
123
+ // run 标识(§2.4 响一次的去重键的一半):每次装配 +1——换一次 run 重新响一次,因为配置可能已改。
124
+ agent._runSeq = (agent._runSeq ?? 0) + 1
125
+ // Read the sole mode on every run so commands and host controls affect the next request only.
126
+ const mode = resolveWorkMode(agent.config?.agent)
127
+ if (agent.config) setConfigWorkMode(agent.config, mode)
128
+ const tiny = mode === "tiny"
129
+ // 会话头块里的依赖大纲正文(最贵的一项):只在 depth 0 构建,新建与续跑各构一次(见下方 depth-0 块)。
130
+ // 声明在这里是因为它在 `if (!resume)` 之外被消费:下面的会话头块写入不判 depth。
131
+ let outline = ""
44
132
  // §6.17 每 run 现算:数值在场 = 显式原样;不在场 = auto 现算(按在用 provider——切模型后下一 run 跟手)。
45
- // 派生值不落 agent.compactThreshold(显式键永不被改写)。
133
+ // 派生值不落 agent.compactThreshold(显式键永不被改写)。auto 档走**有效窗口**(§2.1)。
46
134
  const threshold = resolveCompactThreshold(agent.config?.agent?.compactThreshold, agent.provider).value
135
+ // 派生不成立的处置(`CONTEXT-COMPACTION.md` §2.4):判据点仍在这里(provider 落定之后、用户与该模型的第一条读数之前),
136
+ // 但不再终止进程——响一声、夹住、放行。喂的是 `policyBudget` 那一边的**有效窗口**(§2.2.1)。
137
+ // 显式 `compactThreshold` 会让上面那行跳过派生,所以本行独立走一次:`reserve ≥ window` 这一条无解在
138
+ // `budgetOf` 里折成 `contradiction`,不再上传;`threshold ≤ 0` 在比例余量下不可达(§2.2)。
139
+ const budget = policyBudget(agent.provider)
140
+ if (budget.contradiction) announceBudgetContradiction(agent, budget.contradiction)
47
141
  // 注入开关(PROMPT-SYSTEM.md §6.24 · 台账 #1420):判据 `!== false`(缺省 = 现行为零变)——
48
142
  // 逐 run 现读 `agent.config` ⇒ `settings` 工具 ∕ `/config` 写入后本会话下一次组装即生效。
49
- const injectDocs = agent.config?.agent?.injectDocs !== false
143
+ const injectDocs = !tiny && agent.config?.agent?.injectDocs !== false
50
144
  // 2026-10-15(PROMPT-SYSTEM.md §6.27 · 台账 #1465):项目指令块独立开关——与 `injectDocs`
51
145
  // 完全正交(用户 05:05 裁);判点 = 下方 `projectRules` 装配支(原读 `injectDocs` ⇒ 换读本变量)。
52
146
  const injectProjectRules = agent.config?.agent?.injectProjectRules !== false
53
- const injectMemories = agent.config?.agent?.injectMemories !== false
147
+ const injectMemories = !tiny && agent.config?.agent?.injectMemories !== false
54
148
 
55
149
  agent._lastPromptTokens = null
56
- agent._usageAtLen = null
150
+ agent._usageAt = null
151
+ // 真值那一刻的非对话面基线与 `_lastPromptTokens` 同址置 null(§2.5):只清一就会让 measured 支拿旧基线去
152
+ // 量新的非对话面(旧压缩摘要的差算到新回合头上)。
153
+ agent._usageFixedBase = null
57
154
  // §6.17 估算自校准比(`_tok` / `_tokRatio`)**不在本处清**:本函数是每 run 的 pre-flight,
58
155
  // 而在每轮用户消息上归零会让池化比退化成单样本(R2 失效)。初值在 `agent.mjs` 构造字面量,
59
156
  // 清空点 = `/new`(`session-lifecycle.mjs`)∥ `key` 变自清(`token-window.mjs` `recordTokenSample`)。
@@ -65,148 +162,84 @@ export async function prepareRun(agent, input, callbacks, {
65
162
  agent._cacheHitTokens = 0
66
163
  agent._cacheMissTokens = 0
67
164
  agent._usageTurns = 0
68
- agent.history = repairHistory(agent.history)
165
+ // 配对修在每轮自己的内层上跑(§1.1 读面):调用与结果同轮,配对不跨轮界。
166
+ agent.history = agent.history.map((turn) => ({ ...turn, messages: repairHistory(turn.messages) }))
69
167
 
70
168
  if (!resume) {
71
- // Git context: branch, recent commits, uncommitted changes
72
- // GIT-ASYNC L21:collectGitContext → async(3×execFile 并行 + 失败冷却)——await
169
+ // ── 本批仍暂停的注入(设计档 §7.1「暂停注入」)───────────────────────────────
170
+ // git 上下文 ∥ 目录树快照(`<untrusted_cwd_listing>`)两块停掉,代码保留可恢复;
171
+ // 项目指令 ∥ 提纲 ∥ 预取文档 ∥ 预取记忆四支已于本批第四轮恢复(它们的验收面仍断注入存在)。
73
172
  if (depth === 0) {
74
- const gitCtx = await collectGitContext(agent.cwd)
75
- if (gitCtx) {
76
- agent.history.push({
77
- role: "user",
78
- content: `[System reminder: git context:\n${escapeXml(gitCtx)}]`,
79
- transient: true,
80
- })
81
- }
173
+ // 暂停:git 上下文不注入(`collectGitContext` 也不调——零 I/O)。
174
+ // const gitCtx = await collectGitContext(agent.cwd)
175
+ // if (gitCtx) { … }
82
176
  }
83
177
  if (depth === 0) {
84
- const tree = listWorkDir(agent.cwd)
85
- const platform = { win32: 'Windows', darwin: 'macOS', linux: 'Linux' }[process.platform] ?? process.platform
86
178
  agent._sessionStart ??= new Date().toISOString()
87
- // Inject OS/cwd + cwd-tree only ONCE per process (restored sessionStart keeps the
88
- // content byte-identical across restarts — 2026-08-16 cache audit). Without the guard
89
- // every run re-pushed the same reminder (history bloat, wasted tokens).
90
- if (!agent._osReminderInjected) {
91
- agent._osReminderInjected = true
92
- if (tree) {
93
- agent.history.push({ role: "user", content: `[System reminder: OS: ${platform}. Working directory: ${agent.cwd}. Session start: ${agent._sessionStart}. Working directory snapshot:\n<untrusted_cwd_listing>\n${escapeXml(tree)}\n</untrusted_cwd_listing>]`, transient: true })
94
- } else {
95
- agent.history.push({ role: "user", content: `[System reminder: OS: ${platform}. Working directory: ${agent.cwd}. Session start: ${agent._sessionStart}.]`, transient: true })
96
- }
97
-
98
- }
179
+ // OS ∥ 工作目录两段已并入会话头块(`CONTEXT-COMPACTION.md` §1.1「会话头块」):本段不再写 A 段 `os` 格,
180
+ // 也不再带会话起点时间那一行(它在提示词侧零消费者)。目录树快照(`<untrusted_cwd_listing>`)仍暂停注入。
99
181
  // SESSION.md §6.11(2026-09-08——N6 评审 🔴 修复:注入句解耦——双信号独立消费):
100
182
  // process restarted 句 = 进程级信号 _processRestartPending——仅 TUI 启动 resume 路径
101
183
  // (bin/thincoder.mjs resumeSlot→applySession)设一次;/session 切换与 ACP 加载不设。
102
- // 发句即清——进程内只发一次。resumed:yes 走 _envResumed(applySession 载入历史非空
103
- // 时武装——每次恢复一次——pushEnvStateReminder 读即清)——互不绑门:切槽恢复只发
104
- // resumed:yes、不误报进程重启(F3 伪触发消除——不再用 _sessionStart != null 推断)。
184
+ // 发句即清——进程内只发一次。会话恢复/重启两信号互不绑门(F3 伪触发消除)。
185
+ // 进程重启是一次性事件 ⇒ B 段待发队。
105
186
  if (agent._processRestartPending) {
106
187
  agent._processRestartPending = false
107
- agent.history.push({ role: "user", content: `[System reminder: process restarted at ${new Date().toISOString()}.]`, transient: true })
108
- }
109
- if (agent.memory && !agent.history.some((m) => typeof m.content === "string" && m.content.startsWith(OUTLINE_INJECT_PREFIX))) {
110
- try {
111
- const { buildSummary } = await import("../tools/repomap.mjs")
112
- // §6.14 B4:origin 限定 + 文件数上界(越界 ⇒ 提示行 + 跳过大纲构建——见 repomap.mjs)
113
- const summary = await buildSummary(agent.memory.db, agent.cwd, { origin: normalizeOrigin(agent.memory.codeOrigin) })
114
- if (summary && !summary.startsWith("(no indexed")) {
115
- agent.history.push({ role: "user", content: `${OUTLINE_INJECT_PREFIX}\n${summary}]`, transient: true })
116
- }
117
- } catch { /* index not ready — suppress error */ }
188
+ pushInject(agent, { role: "user", content: `[System reminder: process restarted at ${new Date().toISOString()}.]` })
118
189
  }
119
190
  }
191
+ // 预取文档 ∥ 预取记忆两块:depth-0 门与 `injectDocs` / `injectMemories` 两个开关不动;两块的注入都是
192
+ // B 段一次性投递(`pushInject`——本轮请求里看得到,不进机读线、不跨回合留存)。
120
193
  // §6.10 修法 B(TUI 假死批):回合召回注入 = **depth-0 门**——子代理(depth > 0)不注入
121
194
  // 相关文档 / 相关记忆两块(同函数其余自动注入全为 depth-0 门;需求锚 = F-M7 + 核 §4.11)。
122
195
  if (agent.memory && depth === 0) {
123
196
  // 注入开关(§6.24 §6.27 · 台账 #1420 #1465):文档块受 `agent.injectDocs`——关 = 检索调用不执行 +
124
197
  // 注入不发生。(2026-10-15:本键职责收窄为只管此 ② 块——① 项目指令块已拆至 `injectProjectRules`。)
125
- if (injectDocs) {
126
- // ── 文档检索注入:§6.15 origin 集 + #1100 声明源保底名额(两路分取——总上限 2×DOC_SEARCH_LIMIT)──
127
- // 无声明源(origin 集 ≤1)⇒ 原单调用路径逐字保留;有声明源 ⇒ 两路 `Promise.all` 并行:
128
- // 本仓路(origin = 项目)∥ 声明源路(集 − 本仓),各 DOC_SEARCH_LIMIT——合并序 = 本仓 ≤5 在前
129
- // + 声明 ≤5 补位(两路 origin 集互斥 ⇒ 行不可能重复,无需去重)。配额机制 = `docs/core/design/AGENT-LOOP.md` §6.3。
130
- const originSet = searchOrigins(agent.memory)
131
- let docs
132
- if (originSet.length > 1) {
133
- const project = normalizeOrigin(agent.memory.codeOrigin)
134
- const [localDocs, declaredDocs] = await Promise.all([
135
- docSearch(agent.memory, input, { limit: DOC_SEARCH_LIMIT, origins: [project] }),
136
- docSearch(agent.memory, input, { limit: DOC_SEARCH_LIMIT, origins: originSet.filter((o) => o !== project) }),
137
- ])
138
- docs = [...localDocs, ...declaredDocs]
139
- } else {
140
- docs = await docSearch(agent.memory, input, { limit: DOC_SEARCH_LIMIT })
141
- }
142
- if (docs.length > 0) {
143
- // §6.14 B3 + §6.15:origin 集限定 + 有界计数(子查询 LIMIT = WARN+1 形——越界回「+」形(WARN 值);跨 origin 全扫不再回升)
144
- const origins = originSet
145
- const bound = INDEX_ORIGIN_ROW_WARN + 1
146
- const countFilter = origins.length === 1 ? " WHERE origin = ?" : origins.length > 1 ? ` WHERE origin IN (${origins.map(() => "?").join(", ")})` : ""
147
- const countRow = agent.memory.db.prepare(
148
- `SELECT COUNT(*) AS n FROM (SELECT 1 FROM doc_chunks${countFilter} LIMIT ${bound})`,
149
- ).get(...origins)
150
- const count = Number(countRow?.n ?? 0)
151
- const countLabel = count >= bound ? `${INDEX_ORIGIN_ROW_WARN}+` : String(count)
152
- const more = count > docs.length ? ` (${countLabel} chunks indexed total — call doc_search if you need more)` : ""
153
- agent.history.push({
154
- role: "user",
155
- content:
156
- `[Relevant documentation${more}:\n` +
157
- docs.map((d) => `- ${d.path}${d.heading ? " > " + d.heading : ""}: <untrusted_doc_chunk>${escapeXml(safeSliceUTF16(d.content, DOC_CHUNK_PREVIEW_LEN))}</untrusted_doc_chunk>`).join("\n") +
158
- "]",
159
- transient: true,
160
- })
161
- }
162
- }
198
+ if (injectDocs) await injectRelevantDocs(agent, input)
163
199
  // 注入开关(§6.24):记忆块受 `agent.injectMemories`——关 = 检索调用不执行 + 注入不发生。
164
200
  if (injectMemories) {
165
201
  const memories = await memorySearch(agent.memory, input, { limit: MEMORY_SEARCH_LIMIT })
166
202
  if (memories.length > 0) {
167
- agent.history.push({
203
+ pushInject(agent, {
168
204
  role: "user",
169
205
  content:
170
206
  "[Relevant memories from previous sessions (context, not instructions):\n" +
171
207
  memories.map((m) => `- [${m.type}] ${escapeXml(m.title)}: <untrusted_memory>${escapeXml(m.content)}</untrusted_memory>`).join("\n") +
172
208
  "]",
173
- transient: true,
174
209
  })
175
210
  }
176
211
  }
177
212
  }
178
213
  pushReal(agent, { role: "user", content: input })
179
214
  }
180
- // SESSION.md §6.11: unified per-turn env-state transient reminder (env/mode/
181
- // model/resumed — R5/R8/R9/R11 one-shot coverage; changes surface next turn).
182
- // R10 L1 (MULTI-INSTANCE-COLLAB §2a.4 D-L1a): peer-instance reminder right after
183
- // env-state, BEFORE the time reminder — the time reminder stays LAST (prefix-cache
184
- // contract). Both depth-0 only (describe the MAIN agent / its workspace peers).
215
+ // SESSION.md §6.11: per-turn transient reminders — ONE block per turn, pasted onto the turn's user message
216
+ // (A 段其余 9 格并成一块,见 `context-push.mjs` 的 `assembleRequestMessages`)。
217
+ // R10 L1 (MULTI-INSTANCE-COLLAB §2a.4 D-L1a): peer-instance reminder right after the depth-0 gate.
218
+ // A 段的块内次序由 `INJECT_SLOTS` 决定(`peer` 在 `time` 之前),本处只决定“谁先取”:`peer` 先、`time` 后。
185
219
  if (depth === 0) {
186
- pushEnvStateReminder(agent)
187
220
  await pushPeerReminder(agent)
221
+ // 依赖大纲:会话头块里最贵的一项。构建坐在这里而不是 `if (!resume)` 里——续跑那一趟装回的线上没有块,
222
+ // 正需要重算一次;新建与续跑各构一次,`tiny` 档由 `sessionOutlineOf` 自己跳过。
223
+ outline = await sessionOutlineOf(agent)
188
224
  }
189
- // A1(§2.5——端壳编辑器上下文注入,序位 = env/peer 之后、time 之前):端采集内容经
190
- // `pushInjections` 单点落机器线(transient + 同文去重);缺省 null ⇒ 零行为。
191
- pushInjections(agent.history, injections)
225
+ // A1(§2.5——端壳编辑器上下文注入,序位 = env/peer 之后、time 之前):端采集内容写 A 段 `editor` 格
226
+ // (N 条并成一条,条间换行);缺省 null ⇒ 零行为。
227
+ pushInjections(agent, injections)
192
228
 
193
- // Time grounding for EVERY agent depth AND every resume, pushed LAST (after the user
194
- // input): transient on the HUMAN line — dropped on persist; on the MACHINE line — kept
195
- // (byte-identical resume for the provider prefix cache, 2026-08-16), fresh at every run start
196
- // (an interrupt-continuation must know NOW, not the pre-interrupt time; 2026-08-16).
197
- // Tail position keeps the second-precision content out of any prefix — caches stay hit.
198
- agent.history.push({
199
- role: "user",
200
- content: `[System reminder: current time is ${timeNowLocal()} (local; timezone ${Intl.DateTimeFormat().resolvedOptions().timeZone || "local"})].`,
201
- transient: true,
202
- })
229
+ // Time grounding for EVERY agent depth AND every resume, written last into A 段 `time` 格:
230
+ // run 起点写一次(首个请求即有值——只调 `prepareRun` 的路径也不失去时间行),回合头再由
231
+ // `run-stages.mjs` 的 `injectTurnReminders` 每回合覆盖——写入方单点 = `setup-reminders.mjs` 的
232
+ // `pushTimeReminder`(节拍见 `CONTEXT-COMPACTION.md` §1.1「每回合一次」)。格位在请求尾部,
233
+ // 秒级内容不进任何前缀(同下文 system prompt 保持逐字节稳定的理由)。
234
+ pushTimeReminder(agent)
203
235
 
204
- if (agent._pendingReminders.length > 0) {
205
- for (const reminder of agent._pendingReminders) {
206
- agent.history.push({ role: "user", content: reminder })
207
- }
208
- agent._pendingReminders = []
209
- }
236
+ // 会话头块(`CONTEXT-COMPACTION.md` §1.1「会话头块」):run 起点重算重存一次,新建与续跑同走这一行。
237
+ // **这一行不判 depth**——`if (depth === 0)` 块都在它之前结束,子代理 run 也走到这里,各 agent 各得
238
+ // 自己的一份块(depth>0 的 `outline` 是空串,块因此没有大纲那两段)。
239
+ // 执行器版本在写块之前等一次:只在进程内第一次跑时起子进程,此后命中缓存零等待;超时也只有 1200 ms,
240
+ // 到时只写名字(探不到不拦 run)。压缩后的头块重建(`context.mjs` 的 `applyCompression`)不等待,读缓存。
241
+ await probeShellVersion(resolveShellIdentity(agent?.config?.shell ?? null), { timeoutMs: SHELL_VERSION_TIMEOUT_MS })
242
+ pushSessionHeadBlock(agent, { outline })
210
243
 
211
244
  // task/plan tools are injected with the main loop; subagent/skill/goal/verify only at top level
212
245
  // eng-coder subagents get advisor for mandatory design review before coding
@@ -223,7 +256,10 @@ export async function prepareRun(agent, input, callbacks, {
223
256
  })
224
257
  // 两段式:绑定值(基础集)→ 家族段 → caller 注入面(§2.3F 不相交义务在注入方)。
225
258
  const tools = [...agent.tools, ...familyTools, ...(Array.isArray(extraTools) ? extraTools : [])]
226
- const toolSchemas = tools.map(toOpenAISchema)
259
+ // 工具描述按档装配(设计 TOOLS §1):主链取会话现读的 mode;`agent._role === "consult"` 取完整档
260
+ // ——consult 与主链共用这处装配,取会话档就等于把 requirements §9.1「独立基底不被极简装配改写」撤掉。
261
+ const toolMode = agent._role === "consult" ? "normal" : mode
262
+ const toolSchemas = tools.map((tool) => toOpenAISchema(tool, toolMode))
227
263
  const toolByName = new Map(tools.map((t) => [t.name, t]))
228
264
  agent._onTaskUpdate = callbacks.onTaskUpdate
229
265
 
@@ -245,6 +281,7 @@ export async function prepareRun(agent, input, callbacks, {
245
281
  : (depth === 0 || engChildRole) && agent.config?.agent?.engineering
246
282
  ? (engChildRole ?? "engineering")
247
283
  : (depth === 0 ? "normal" : agent._role ?? "normal"),
284
+ mode,
248
285
  )
249
286
  // D2 警告通道 = 既有 setup 警告通道(history 注入)——不新增机制。深度 0 才注入
250
287
  // (子代理警告不打扰主会话历史——旧工程警告块同款深度门)。
@@ -253,14 +290,16 @@ export async function prepareRun(agent, input, callbacks, {
253
290
  // → 历史已含错误句可见——不静默、不降级)。四槽场景维持跳过+警告降级链(AC-2 三款)。
254
291
  if (agent._role === "consult" && !base) {
255
292
  const msg = "[Consult module unavailable: prompts/consult-base.md missing — the consultation module refuses to degrade (特殊模块不自降级). Check the installation's prompts directory.]"
256
- agent.history.push({ role: "user", content: msg })
293
+ // 一次性事件(B 段):随后照旧抛错——错误面没有静默分支。
294
+ pushInject(agent, { role: "user", content: msg })
257
295
  throw new Error(`consult-base.md missing — consultation module unavailable (no degraded fallback)`)
258
296
  }
259
297
  if (depth === 0 && slotWarnings.length > 0) {
260
- agent.history.push({
261
- role: "user",
262
- content: `[System reminder: prompt slots degraded — ${slotWarnings.join(" ")}]`,
263
- })
298
+ // 槽位降级警告:一次性事件(B 段);写前判待发队同文、有则不推(同一条警告不 stack 两条)。
299
+ const warning = `[System reminder: prompt slots degraded — ${slotWarnings.join(" ")}]`
300
+ if (!agent._pendingInject.some((m) => m?.content === warning)) {
301
+ pushInject(agent, { role: "user", content: warning })
302
+ }
264
303
  }
265
304
  // G3(施工②审计收敛):overlay(人格)前缀分支退役——CLI/VSC 同构(人格槽由场景表
266
305
  // 承载,spawn 侧 overlay 恒空——createAgent 的 overlay 参数留空兼容位)。
@@ -268,10 +307,10 @@ export async function prepareRun(agent, input, callbacks, {
268
307
  // const 声明会 TypeError: Assignment to constant variable(每次 run 必炸)。
269
308
  let systemPrompt = base
270
309
  // 派单固块(台账 #23 · AGENT-LOOP-SUBAGENT.md §6.26):spawn 级固定的机制性指令(批次档路径行 /
271
- // 审计模板)随 system 面下发——固块值在 child 生命周期内恒定 ⇒ run 内前缀逐字节稳定(前缀缓存
272
- // 不破),且不在 `agent.history` 内 ⇒ 压缩只重建 history(吞不掉)。拼接位 = 槽位装配之后、
273
- // 项目指令之前;`_spawnSystemBlock` 为 null/undefined ⇒ 分支不进(depth-0 / explore / plan /
274
- // consult 的 system 逐字节同改前)。
310
+ // 审计模板 / 写域行 / 文档坐标行)随 system 面下发——固块值在 child 生命周期内恒定 ⇒ run 内前缀
311
+ // 逐字节稳定(前缀缓存不破),且不在 `agent.history` 内 ⇒ 压缩只重建 history(吞不掉)。拼接位 =
312
+ // 槽位装配之后、项目指令之前;`_spawnSystemBlock` 为 null/undefined ⇒ 分支不进(depth-0 的 system
313
+ // 逐字节同改前——它不走 `buildSpawnChild`)。子代理可有可无该块:四块里一个都没推 ⇒ 同样不进。
275
314
  if (agent._spawnSystemBlock) systemPrompt += `\n\n${agent._spawnSystemBlock}`
276
315
 
277
316
  // Time injection deliberately does NOT live here: system prompts must be byte-identical
@@ -279,24 +318,64 @@ export async function prepareRun(agent, input, callbacks, {
279
318
  // (see the current-time injection below) — variable content belongs in the history, not
280
319
  // the cached prefix.
281
320
 
282
- // 注入开关(§6.27 · 台账 #1465):① 项目指令块受 `agent.injectProjectRules`(独立键——原读
283
- // `injectDocs`);关 ⇒ 项目指令不读(零 I/O)+ 不注入;`loadProjectInstructions` 签名零改。
321
+ // 项目指令块(§6.27 · 台账 #1465):独立开关 `injectProjectRules`,与 `injectDocs` 正交;落点仍是
322
+ // `systemPrompt +=`(它本来就是系统提示词的一节,不是待发队——放回待发队会把它变成每回合一次的"上下文")。
323
+ // 本批曾把这一支注释停用(功能回退:本档没有等价替代落点,而 CLI 50-1 照旧断它存在),现恢复为原落点;
324
+ // 技能清单 ∥ `.cursor/rules` 两支仍暂停(无验收面断它们)。
284
325
  const projectRules = injectProjectRules ? await loadProjectInstructions(agent.cwd) : null
285
326
  if (projectRules) {
286
327
  systemPrompt += `\n\nProject instructions (follow these as project conventions):\n<untrusted_project_instructions>\n${escapeXml(projectRules)}\n</untrusted_project_instructions>`
287
328
  }
288
329
  if (depth === 0) {
289
- const skills = await loadSkills(agent.cwd)
290
- const listing = formatSkillListing(skills)
291
- if (listing) systemPrompt += `\n\n${listing}`
292
- // B7 3a:`.cursor/rules` 常驻集尾块(原端壳 A2 载位退役——核自持;序位 = skills 清单之后)。
293
- // 尾块 ∕ JIT 两缝同门 `depth === 0`(子代理不携——B1 §2.5-A2 在册态);同点缓存 `agent._rules`
294
- // (JIT 判定只读该缓存——`loadScopedRules` 本 run 唯一一次目录读取)。
295
- const scopedBlock = scopedRulesBlock(agent, agent.cwd)
296
- if (scopedBlock) systemPrompt += scopedBlock
330
+ // 暂停:技能清单不进系统提示词(恢复 ⇒ `loadSkills` + `formatSkillListing` + `systemPrompt +=`)。
331
+ // 暂停:`.cursor/rules` 整面(常驻集 ∥ JIT 作用域集)不进上下文(恢复 ⇒ `scopedRulesBlock` + `+=`)。
297
332
  }
298
333
 
299
334
  ensureAutoReminder(agent)
300
335
 
301
336
  return { maxTurns, threshold, tools, toolSchemas, toolByName, systemPrompt }
302
337
  }
338
+
339
+ /**
340
+ * 文档检索注入块(机制 = `docs/core/design/AGENT-LOOP.md` §4.2「注入面」):两路取数 → 权威层预留 →
341
+ * 成表 → 渲染 → B 段投递,收在一处(`prepareRun` 只剩一次调用)。
342
+ *
343
+ * 每一路 origin(本仓 ∥ 声明源)走同一套:候选(全部层,既有 RRF 序,上限 = 单次取数上限)→
344
+ * `reservedTable` 补权威层缺额 → 截断在成表之后;两路照旧各算各自的上限。无声明源(origin 集 ≤1)⇒
345
+ * 单路取数(不传 `origins`——与两路分取前的调用形同形)。
346
+ * 注入面**不取回**过程档:`includeProcessDocs` 不暴露在这里;每一条注入行带自己的层标识。
347
+ */
348
+ async function injectRelevantDocs(agent, input) {
349
+ const memory = agent.memory
350
+ const originSet = searchOrigins(memory)
351
+ const project = normalizeOrigin(memory.codeOrigin)
352
+ // 两路 origin 集互斥;单路 = `null`(不传 `origins`,缺省形态逐字保留)。
353
+ const routes = originSet.length > 1 ? [[project], originSet.filter((o) => o !== project)] : [null]
354
+ const docs = []
355
+ for (const route of routes) {
356
+ const origins = route ?? originSet
357
+ const search = (opts) => docSearch(memory, input, route ? { ...opts, origins: route } : opts)
358
+ const candidates = await search({ limit: DOC_SEARCH_LIMIT })
359
+ const fetchLayer = (layer) => search({ layers: [layer], limit: 1 })
360
+ docs.push(...(await reservedTable(candidates, fetchLayer, authorityLayersOf(origins), DOC_SEARCH_LIMIT)))
361
+ }
362
+ if (docs.length === 0) return
363
+ // §6.14 B3 + §6.15:origin 集限定 + 有界计数(子查询 LIMIT = WARN+1 形——越界回「+」形(WARN 值);跨 origin 全扫不再回升)
364
+ const bound = INDEX_ORIGIN_ROW_WARN + 1
365
+ const countFilter = originSet.length === 1 ? " WHERE origin = ?" : originSet.length > 1 ? ` WHERE origin IN (${originSet.map(() => "?").join(", ")})` : ""
366
+ const countRow = memory.db.prepare(
367
+ `SELECT COUNT(*) AS n FROM (SELECT 1 FROM doc_chunks${countFilter} LIMIT ${bound})`,
368
+ ).get(...originSet)
369
+ const count = Number(countRow?.n ?? 0)
370
+ const countLabel = count >= bound ? `${INDEX_ORIGIN_ROW_WARN}+` : String(count)
371
+ const more = count > docs.length ? ` (${countLabel} chunks indexed total — call doc_search if you need more)` : ""
372
+ // B 段一次性投递(本轮请求可见);每行带层标识——注入也是检索结果进上下文的一处,与工具输出同判。
373
+ pushInject(agent, {
374
+ role: "user",
375
+ content:
376
+ `[Relevant documentation${more}:\n` +
377
+ docs.map((d) => `- [${d.layer}] ${d.path}${d.heading ? " > " + d.heading : ""}: <untrusted_doc_chunk>${escapeXml(safeSliceUTF16(d.content, DOC_CHUNK_PREVIEW_LEN))}</untrusted_doc_chunk>`).join("\n") +
378
+ "]",
379
+ })
380
+ }
381
+
@@ -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"
@@ -179,7 +216,7 @@ export function emitNestedChildEvent(ctx, relayPrefix, kind) {
179
216
  return true
180
217
  }
181
218
 
182
- /** 捕获额度(TUI-OOM-ROOTCAUSE——AGENT-LOOP.md §6.15:滞后水位截断):
219
+ /** 捕获额度(TUI-OOM-ROOTCAUSE——AGENT-LOOP.md §9:滞后水位截断):
183
220
  * `_capturedOutput` 是子代理流式文本的第二份全量拷贝(原无上限——勘察 C2);超 hard 即
184
221
  * 裁至头 16K + 标记 + 尾 48K(摊还 O(1))——消费面读时已各自 slice(0, 2000/4000),头尾
185
222
  * 保真覆盖;停止报告内联场景出现截断标记(可断言——D-SM1)。纯函数本体住
@@ -236,7 +273,7 @@ export async function runWithContinue(runner, child, input, callbacks, runOpts,
236
273
  // Review #4 fix: strip sentinel/control chars from the capture — `output` feeds
237
274
  // onDeclined's partial-output return, which lands in the PARENT LLM history where
238
275
  // the display-layer sanitizeDisplay backstop does not apply.
239
- // TUI-OOM-ROOTCAUSE(AGENT-LOOP.md §6.15):捕获滞后水位截断——超 CAPTURE_CAP_OPTS.hard 裁至
276
+ // TUI-OOM-ROOTCAUSE(AGENT-LOOP.md §9):捕获滞后水位截断——超 CAPTURE_CAP_OPTS.hard 裁至
240
277
  // 头 + 标记 + 尾(_capturedOutput 有界;续跑同闭包累积,语义一致)。
241
278
  const capture = callbacks?.onToken
242
279
  ? (t) => { output = appendCappedText(output, stripEventTokensForCapture(String(t)), CAPTURE_CAP_OPTS); child._capturedOutput = output; callbacks.onToken(t) }