@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
@@ -7,9 +7,11 @@
7
7
  */
8
8
  import { join, relative, sep } from "node:path"
9
9
  import { findReviewRepos, collectRepoSnapshots, collectChangedFiles } from "./repos.mjs"
10
- import { buildConvergenceBody, buildConvergenceInstructions } from "./convergence.mjs"
10
+ import { buildConvergenceBody, buildConvergenceInstructions, buildPriorReviewBlock } from "./convergence.mjs"
11
11
  import { loadAdvisorMd, extractConversationBackground, extractAgentResponseTable } from "./history.mjs"
12
12
  import { injectProjectGuide, injectDocumentMap, injectProjectStandards, NO_GIT_NOTICE } from "./project-context.mjs"
13
+ // 拍平投影:背景段收拍平视图(响应表由 `extractAgentResponseTable` 自己拍平)。
14
+ import { flattenHistory } from "../context-push.mjs"
13
15
 
14
16
  // Structural split (not an authority migration): the moved helpers stay reachable here.
15
17
  export { findGuideRoot, injectProjectGuide } from "./project-context.mjs"
@@ -38,6 +40,27 @@ export function buildObjectDeclarationBlock(object = null) {
38
40
  ].join("\n")
39
41
  }
40
42
 
43
+ /**
44
+ * 判轨谓词:挂载判据与 Approval Signal 措辞两面共用的那一半。
45
+ * 绑定是前置条件,与「模式 × 评审轨」写在同一句合取里——判据见 `docs/core/design/BATCH-RECORD.md` §4.3:
46
+ * 工程模式 ∧ 设计轨的轮次块由结算写,该轨的评审席没有 `batch` 工具;代码轨与普通模式照旧由绑定评审席位写。
47
+ * 假侧含「未绑定」:工具面对无 `batchDoc` 的设计评审直接拒发(`agent-tools/advisor.mjs` 的账链门),
48
+ * 故假侧在工具面可达的读者恒为工程设计轨;直接 API 调用方绕过工具面时,锁在假侧的那句话所说的结算与
49
+ * 批档都不存在——那一条路不走本谓词的两支措辞。
50
+ * 工具面的执法半句另有:`agent-tools/batch-segment-vocab.mjs` 的 `reviewWritableSegment`(判可写段号,
51
+ * 不含绑定)——改轨判据时两处都要看,它不是本谓词的射程。
52
+ * 三参都不给默认值:缺一即判不出,一个默认值等于替调用方选一条轨,而错的那条不报错。
53
+ * 消费者 = `advisor/loop.mjs` 的挂载判据(拿不拿得到)与 `advisor/run.mjs` 经本档两处出口的措辞(怎么用)。
54
+ * @param {Object} agent — 模式位载体(`agent.config.agent.engineering`)
55
+ * @param {string} reviewType — 评审轨(`"design"` ∥ `"code"`)
56
+ * @param {string|null} batchDoc — 本评审逐笔绑定的批次档(null/undefined = 未绑定)
57
+ * @returns {boolean} true = 该实例持有 `§3` 写通道
58
+ */
59
+ export function reviewHoldsBatchWrite(agent, reviewType, batchDoc) {
60
+ const engineering = !!agent?.config?.agent?.engineering
61
+ return !!batchDoc && !(engineering && reviewType !== "code")
62
+ }
63
+
41
64
  /**
42
65
  * Approval-signal block for design reviews (round 1 and round 2+ — AGENT-LOOP-ASYNC-POOL.md §6.10 D-24b:
43
66
  * an async fix-round continuation must be able to re-approve, so the token is
@@ -45,20 +68,52 @@ export function buildObjectDeclarationBlock(object = null) {
45
68
  * §29.1 F2a (2026-09-07): BOTH values are injected — the token AND the designId
46
69
  * (anchor sentence verbatim — Copy BOTH values). designId null (legacy direct
47
70
  * callers without a resolved instance) degrades to the token-only form.
71
+ *
72
+ * `writesSection3`(`reviewHoldsBatchWrite` 的取值)决定 §3 那一句指向谁:持有 `batch` 工具的轨
73
+ * 照它 `append`,落档失败要报;无写通道那一支的块由结算按报告里的 VERDICT 行写,句内只叫它把
74
+ * VERDICT 行写进报告(工具面可达的读者 = 工程设计轨,见 `reviewHoldsBatchWrite` 的假侧说明)。
75
+ * 两支持并存、各管一个读者——这一面随每一次设计评审发出,判不了读者,只能把两支写进句子本身
76
+ * (`docs/core/design/BATCH-RECORD.md` §4.5 第七面)。缺省即抛:默认值会替调用方选一条轨,
77
+ * 错的那条不报错,只把一个评审席不该看到的写口送到它手里。
78
+ * @param {string} designToken — 本次签发的设计凭证
79
+ * @param {string|null} designId — 设计槽 id(null → 只回显 token 的降级形)
80
+ * @param {boolean} writesSection3 — 该评审实例是否持有 `§3` 写通道(`reviewHoldsBatchWrite(...)` 的取值)
81
+ * @returns {string} the Approval Signal block
48
82
  */
49
- export function buildDesignApprovalBlock(designToken, designId) {
83
+ export function buildDesignApprovalBlock(designToken, designId, writesSection3) {
84
+ if (typeof writesSection3 !== "boolean") {
85
+ throw new TypeError("buildDesignApprovalBlock: writesSection3 must be a boolean from reviewHoldsBatchWrite(agent, reviewType, batchDoc) — the track decides whether this instance holds a `batch` tool, so it is never defaulted")
86
+ }
50
87
  const echo = designId
51
88
  ? `If — and ONLY if — no unresolved 🔴 (Critical) issue remains, end your reply with this exact token: [DESIGN-TOKEN:${designToken}] and this exact designId: ${designId}. Copy BOTH values verbatim — every character, including the colon and the digits after the uuid inside the token brackets; a shortened echo is flagged as truncated.`
52
89
  : `If — and ONLY if — no unresolved 🔴 (Critical) issue remains, end your reply with this exact token: [DESIGN-TOKEN:${designToken}]. Copy it verbatim — every character, including the colon and the digits after the uuid; a shortened echo is flagged as truncated.`
90
+ const section3Line = writesSection3
91
+ ? "Put that same verdict line on its own line inside the text you append to the batch record's §3 (`batch append`): the §3 write itself is checked the same way, and a §3 append that states no verdict — or states both — is refused before anything lands."
92
+ : "Put that same verdict line on a line of its own in your report: the settlement reads it and writes the round block into the batch record's §3 once the report lands, and the verdict line inside that block is the one you state here. A report that states no verdict still lands its block — the verdict line is then the constant explanation line 本轮无裁定行(评审未给出 VERDICT 行); a report that states both lands it just the same."
53
93
  return [
54
94
  "## Approval Signal",
55
95
  echo,
56
96
  "The verdict line is checked mechanically: without a `VERDICT: pass` line, or with a `VERDICT: changes-required` line, no token is issued even when the token is echoed.",
57
- "Put that same verdict line on its own line inside the text you append to the batch record's §3 (`batch append`): the §3 write itself is checked the same way, and a §3 append that states no verdict — or states both — is refused before anything lands.",
97
+ section3Line,
58
98
  "🟡 (Advisory) and 🔵 (Note) findings do NOT block approval — list them if present, but still include the token. If any 🔴 (Critical) issue remains unresolved, do NOT include the token. A reasoned non-fix accepted by the reviewer does not block (🔴 only — 🟡/🔵 never block approval); anything else stays unresolved.",
59
99
  ].join("\n")
60
100
  }
61
101
 
102
+ /**
103
+ * `batchBrief` 的形状判据(两个构建面共用一句):签名不给默认值,非字符串即抛并点名它。
104
+ * 一个默认值等于替调用方决定「没有简报」,而空串只能是调用方算出来的结果——未绑定的评审传空串,
105
+ * 块就不出现(`docs/core/design/ADVISOR-GUARDS.md` §2.5「参数面」)。
106
+ * @param {string} batchBrief — 调用方算好的一段(`buildBatchBrief(...)` 的返回值 ∥ 空串)
107
+ * @param {string} caller — 抛错点名用(两个构建函数各报自己)
108
+ * @returns {string} 原值
109
+ */
110
+ function requireBatchBrief(batchBrief, caller) {
111
+ if (typeof batchBrief !== "string") {
112
+ throw new TypeError(`${caller}: batchBrief must be a string — the caller computes it with buildBatchBrief(boundBatchDoc, cwd) and passes "" when no batch record is bound (an unbound review carries no ## Batch record block). It is never defaulted here: a default would pick that block for the caller.`)
113
+ }
114
+ return batchBrief
115
+ }
116
+
62
117
  /**
63
118
  * Build the user message for an advisor review session.
64
119
  * @param {Object} agent — the parent agent
@@ -68,6 +123,8 @@ export function buildDesignApprovalBlock(designToken, designId) {
68
123
  * @param {string[]|null} [documents] — design review only: explicit list of doc paths to review (requirements + design + referenced docs).
69
124
  * When set, the review input is built from this list ONLY — no git-diff change-set collection.
70
125
  * When absent, the legacy git-diff-based scope is kept (backward compatible).
126
+ * @param {string} batchBrief — the bound batch record's briefing block (`ADVISOR-GUARDS.md` §2.5), built by
127
+ * `buildBatchBrief`; "" when no record is bound (the block then does not appear). Required — no default.
71
128
  * @param {string[]|null} [paths] — code review only: explicit list of file/dir paths to review (deduped; shown under Review Scope)
72
129
  * @param {Object|null} [object] — review-object declaration (AGENT-LOOP-ASYNC-POOL.md §6.18 D-OA1/D-OA3):
73
130
  * { type, target, status, reason, exclude } — mechanically injected at the
@@ -75,20 +132,24 @@ export function buildDesignApprovalBlock(designToken, designId) {
75
132
  * @param {string|null} [designId] — F2a: injected next to the token in the
76
133
  * Approval Signal (both values — the reviewer copies both verbatim); null →
77
134
  * token-only degradation (legacy direct callers).
135
+ * @param {boolean} writesSection3 — 本评审实例是否持有 `§3` 写通道(`reviewHoldsBatchWrite` 的取值,由
136
+ * `run.mjs` 算一次传进来)。**不给默认值**:绑定值在本档手里没有,就地判只能写成常量。
78
137
  * @returns {string} the user message
79
138
  */
80
- export function buildAdvisorUserMessage(agent, prior, reviewType, designToken = null, documents = null, paths = null, object = null, designId = null) {
81
- const body = buildAdvisorUserMessageInner(agent, prior, reviewType, designToken, documents, paths, object, designId)
139
+ export function buildAdvisorUserMessage(agent, prior, reviewType, designToken = null, documents = null, batchBrief, paths = null, object = null, designId = null, writesSection3) {
140
+ requireBatchBrief(batchBrief, "buildAdvisorUserMessage")
141
+ const body = buildAdvisorUserMessageInner(agent, prior, reviewType, designToken, documents, batchBrief, paths, object, designId, writesSection3)
82
142
  // B 构建自愈(F12/`ADVISOR-GUARDS.md §2` #1):design + token 且输出不含逐字信号 ⇒ 尾包补齐 Approval Signal。
83
143
  // 覆盖所有出口(含 code 形态分支降级态与 legacy 收敛分支)——既有分支语义零改:已在分支内
84
144
  // 注入过的路径因 `[DESIGN-TOKEN:{token}` 逐字在场而不重复追加(幂等)。
85
145
  if (reviewType !== "design" || !designToken) return body
86
146
  if (body.includes(`[DESIGN-TOKEN:${designToken}`)) return body
87
- return `${body}\n\n${buildDesignApprovalBlock(designToken, designId)}`
147
+ return `${body}\n\n${buildDesignApprovalBlock(designToken, designId, writesSection3)}`
88
148
  }
89
149
 
90
- /** 内层构建(无自愈尾包)——出口、分支与消息形态与拆分前逐字一致。 */
91
- function buildAdvisorUserMessageInner(agent, prior, reviewType, designToken = null, documents = null, paths = null, object = null, designId = null) {
150
+ /** 内层构建(无自愈尾包)。设计评审每轮走这里:首轮无 prior 参考块,轮 2+ 带 prior 参考块,其余消息形态相同。 */
151
+ function buildAdvisorUserMessageInner(agent, prior, reviewType, designToken = null, documents = null, batchBrief, paths = null, object = null, designId = null, writesSection3) {
152
+ requireBatchBrief(batchBrief, "buildAdvisorUserMessageInner")
92
153
  // prior = the full prior review output (string) when a convergence round is
93
154
  // being built (decision 2026-08-08 — verbatim injection, model understands it).
94
155
  // Deterministic: only _advisorRound > 0 with stored output counts.
@@ -96,24 +157,32 @@ function buildAdvisorUserMessageInner(agent, prior, reviewType, designToken = nu
96
157
 
97
158
  const parts = []
98
159
  // Review-object declaration FIRST — D-OA1: at the start of the user message
99
- // (after the system prompt, before the review content). Covers round 1
100
- // design/code and the legacy convergence path; the round-2+ normal path
101
- // prepends it in buildAdvisorFollowUp (T-OA2 — every round stays anchored).
160
+ // (after the system prompt, before the review content). Covers every design
161
+ // round and code round 1 here; the code-review round-2+ path prepends it in
162
+ // buildAdvisorFollowUp (T-OA2 — every round stays anchored).
102
163
  const declaration = buildObjectDeclarationBlock(object)
103
164
  if (declaration) parts.push(declaration)
165
+ // 批档简报(`ADVISOR-GUARDS.md` §2.5):位次 = 对象声明之后、`## Design Review` ∥ `## Review Scope` 之前
166
+ // ——读者先拿到任务书与裁定的所在(§1),再读到被判的对象正文。空串 = 未绑定,块不出现。
167
+ if (batchBrief) parts.push(batchBrief)
104
168
  const docList = Array.isArray(documents) ? documents.filter((d) => typeof d === "string" && d.trim()) : []
105
169
  const pathList = Array.isArray(paths) ? [...new Set(paths.filter((p) => typeof p === "string" && p.trim()))] : []
170
+ // 评审范围项 = 指南 ∥ 标准层 ∥ 文档地图共用的**同一份操作数**(序 = 喂给 `findGuideRoot` 的那个序)。
171
+ // 只算一处:两条 base 推导同源的前提是三个调用点拿到的确实是同一份列表。
172
+ const scopeFiles = [...pathList, ...docList]
106
173
 
107
- // Project guide FIRST in EVERY review path (code AND design round 0): the map
174
+ // Project guide FIRST in EVERY review path (code AND design): the map
108
175
  // to the requirements docs is needed for design reviews too (design must fit
109
- // the requirements, not just the methodology). Design round 0 early-returns
176
+ // the requirements, not just the methodology). The design branch early-returns
110
177
  // below — the guide must be injected before that return. Project root is
111
178
  // discovered from the review scope (code paths AND design-doc paths, so a
112
179
  // documents-only design review still finds the subproject guide).
113
- const guideRoot = injectProjectGuide(agent, parts, [...pathList, ...docList])
180
+ const guideRoot = injectProjectGuide(agent, parts, scopeFiles)
114
181
 
115
- // Design review: simplified message — focus on the design doc, not code
116
- if (reviewType === "design" && (agent._advisorRound || 0) === 0) {
182
+ // Design review — EVERY round (decision 2026-11-16: no convergence decay; each
183
+ // round re-reads the whole scope against the complete criteria). Round 2+ adds
184
+ // the prior review output as a REFERENCE block below.
185
+ if (reviewType === "design") {
117
186
  const repos = findReviewRepos(agent)
118
187
  parts.push("## Design Review")
119
188
  // FR15/P8: no git → change-set context is unavailable. Say it (never silent).
@@ -126,7 +195,7 @@ function buildAdvisorUserMessageInner(agent, prior, reviewType, designToken = nu
126
195
  // doc list — the advisor reviews ONLY these. No git-diff change-set
127
196
  // collection: diff-based discovery reviewed unrelated files, and untracked
128
197
  // design docs were invisible to git diff anyway (ENGINEERING-MODE.md §2.4).
129
- parts.push("The documents below are the review scope. Review ONLY these files — do not scan git diff or read any other files.")
198
+ parts.push("The documents below are the review scope — the review target is these documents only. Do not scan git diff; reading other files is allowed where a criterion needs it (feasibility, affected-file size), but findings outside these documents are out of scope.")
130
199
  parts.push("")
131
200
  parts.push("## Documents to Review")
132
201
  parts.push(docList.map((d) => `- ${d} — Read this file in full`).join("\n"))
@@ -159,13 +228,17 @@ function buildAdvisorUserMessageInner(agent, prior, reviewType, designToken = nu
159
228
  // Engineering mode: the project standards section — read from the project's own
160
229
  // declaration (`docRoot.standards`); three states, each machine-distinguishable:
161
230
  // undeclared / declared-but-unreadable / injected. Never a probed convention name (PO-2).
231
+ // The base is derived inside the injector from this review's scope (the owning project of
232
+ // those paths) — NOT from `guideRoot`: the guide's root is the nearest AGENTS.md, which is a
233
+ // different question, and under a workspace anchor it is the anchor (no manifest ⇒ state 1).
162
234
  if (agent.config?.agent?.engineering) {
163
- injectProjectStandards(agent, parts, guideRoot)
235
+ injectProjectStandards(agent, parts, scopeFiles)
164
236
  }
165
237
 
166
238
  // Document map: derived from the manifest `docRoot` (declared roots' README, then their common
167
- // ancestor); neither → explicit degradation sentence (never a silent skip).
168
- injectDocumentMap(agent, parts, guideRoot ?? agent.cwd)
239
+ // ancestor); neither → explicit degradation sentence (never a silent skip). Same base as the
240
+ // standards face (one derivation, two consumers).
241
+ injectDocumentMap(agent, parts, scopeFiles)
169
242
 
170
243
  parts.push("## Instructions")
171
244
  if (docList.length > 0) {
@@ -177,18 +250,28 @@ function buildAdvisorUserMessageInner(agent, prior, reviewType, designToken = nu
177
250
  parts.push("3. If the ## Project Guide (AGENTS.md) section above is present, also check requirement fit: does the design match what the requirements documents it points to actually ask for?")
178
251
  parts.push("4. Do NOT run git diff or look for code changes — there are none at this stage.")
179
252
  parts.push("5. If you find issues, produce your review table with the format: | # | Category | Severity | Issue | Suggestion |. If the design passes, no table is needed.")
253
+ // Round 2+: the prior review output and the agent's fix claims travel as
254
+ // REFERENCE — they keep the reviewer from re-reporting what is already fixed,
255
+ // and they are explicitly NOT the verification list (this round is a full
256
+ // review at the same standard as the first).
257
+ if (p && (agent._advisorRound || 0) > 0) {
258
+ const response = extractAgentResponseTable(agent.history, agent._advisorResponseAnchor ?? undefined)
259
+ || "(Agent did not provide a response table — report every issue the current file state shows)"
260
+ parts.push("")
261
+ parts.push(buildPriorReviewBlock(p, response))
262
+ }
180
263
  if (designToken) {
181
264
  parts.push("")
182
- parts.push(buildDesignApprovalBlock(designToken, designId))
265
+ parts.push(buildDesignApprovalBlock(designToken, designId, writesSection3))
183
266
  }
184
267
  return parts.join("\n")
185
268
  }
186
269
 
187
- // Convergence data (round 2+). LEGACY COMPATIBILITY PATH: the normal advisor
270
+ // Convergence data (round 2+). LEGACY COMPATIBILITY PATH: the normal code-review
188
271
  // flow routes convergence rounds through buildAdvisorFollowUp (fresh session,
189
- // decision d698434); this block only fires for direct external callers of
190
- // buildAdvisorUserMessage with a stored prior review output. Kept to avoid
191
- // breaking those. Same rule as buildAdvisorFollowUp: the FULL prior review
272
+ // decision d698434); a design review never reaches here (it returns above, every round).
273
+ // This block only fires for direct external callers of buildAdvisorUserMessage
274
+ // with a stored prior review output. Kept to avoid breaking those. Same rule as buildAdvisorFollowUp: the FULL prior review
192
275
  // output is injected verbatim (decision 2026-08-08 — the model understands it;
193
276
  // no table/header/phrase parsing).
194
277
  // NOTE: this legacy path does NOT apply escapeLiteralEscapes (that lives in
@@ -218,11 +301,8 @@ function buildAdvisorUserMessageInner(agent, prior, reviewType, designToken = nu
218
301
  parts.push("")
219
302
  }
220
303
  if (docList.length > 0) {
221
- if (reviewType === "design") {
222
- parts.push("The documents below are the review scope. Review ONLY these files — do NOT scan git diff or read any other files.")
223
- } else {
224
- parts.push("The documents below define acceptance criteria and review context. Read them for context, then read the code files specified in the review scope. Judge the implementation against these documents.")
225
- }
304
+ // Code-review path only — a design review returns inside its own branch above.
305
+ parts.push("The documents below define acceptance criteria and review context. Read them for context, then read the code files specified in the review scope. Judge the implementation against these documents.")
226
306
  parts.push("")
227
307
  parts.push("## Documents to Review")
228
308
  parts.push(docList.map((d) => `- ${d} — Read this file in full`).join("\n"))
@@ -230,7 +310,7 @@ function buildAdvisorUserMessageInner(agent, prior, reviewType, designToken = nu
230
310
  }
231
311
 
232
312
  // Conversation background — recent user↔assistant exchanges for intent context
233
- const background = extractConversationBackground(agent.history)
313
+ const background = extractConversationBackground(flattenHistory(agent.history))
234
314
  if (background) {
235
315
  parts.push("## Conversation Background (recent turns)")
236
316
  parts.push(background)
@@ -250,9 +330,10 @@ function buildAdvisorUserMessageInner(agent, prior, reviewType, designToken = nu
250
330
  parts.push("")
251
331
 
252
332
  // Engineering mode: project standards (declaration-only, same helper as the
253
- // design path) — undeclared degrades visibly (PO-2).
333
+ // design path) — undeclared degrades visibly (PO-2). Base = this review's scope's owning
334
+ // project (same derivation as the document map), not `guideRoot`.
254
335
  if (agent.config?.agent?.engineering) {
255
- injectProjectStandards(agent, parts, guideRoot)
336
+ injectProjectStandards(agent, parts, scopeFiles)
256
337
  }
257
338
 
258
339
  // Instructions — round-aware: re-reviews skip convention discovery entirely.
@@ -14,14 +14,18 @@
14
14
  * and unfixable by the user). Missing pieces now say so, and the reviewer is told
15
15
  * to state the limitation in its findings. The document map is derived from the
16
16
  * manifest's `docRoot` (the one place that says where the docs live); the standards face
17
- * is the project's OWN declaration too (`docRoot.standards`) — the probe was retired, the
18
- * declaration replaced guessing — and it degrades in three machine-distinguishable states:
17
+ * is the project's OWN declaration too (`docRoot.standards` — a document LAYER: a directory
18
+ * whose `.md` files, subdirectories included, are the standards) — the probe was retired, the declaration
19
+ * replaced guessing — and it degrades in three machine-distinguishable states:
19
20
  * undeclared (no path), declared but unreadable (the declared path is named), and injected.
20
21
  */
21
- import { readFileSync, existsSync } from "node:fs"
22
+ import { readFileSync, readdirSync, existsSync, statSync } from "node:fs"
22
23
  import { resolve, join, relative, dirname, sep } from "node:path"
23
24
  import { providerSpec } from "../config.mjs"
24
- import { DEFAULT_MANIFEST, docRootPaths, manifestFilePath, readManifest } from "../manifest.mjs"
25
+ import { DEFAULT_MANIFEST, docRootPaths, manifestFilePath, projectRootView, readManifest } from "../manifest.mjs"
26
+ // 去重键的折大小写尺子(本档私有):同一目录的两种大小写写法在 win32 上是同一个目录,
27
+ // 不折就同一份档注入两次。
28
+ const pathKey = (p) => (process.platform === "win32" ? p.toLowerCase() : p)
25
29
 
26
30
  /** Project guide (AGENTS.md) injection budget — decision 2026-08-08:
27
31
  * NO fixed truncation; long-context models (1M+) get up to 5% of their context
@@ -40,10 +44,11 @@ export const NO_STANDARDS_NOTICE = "(No project standards document — nothing i
40
44
  export const NO_GIT_NOTICE = "(No git repository detected — change-set context is unavailable; read the review-scope files directly.)"
41
45
 
42
46
  /**
43
- * 态 2 —— 声明了标准档,但一份都读不到(文案单源 = `docs/core/design/MANIFEST.md` §2.12)。
47
+ * 态 2 —— 声明了标准层,但一份都读不到(文案单源 = `docs/core/design/MANIFEST.md` §2.12)。
44
48
  * 与 `NO_STANDARDS_NOTICE` **不得同形**:那句说的是「没有任何东西声明」,而这里恰好是「声明了但
45
49
  * 读不到」。同形会让作者以为自己没声明过,回头去补一个其实已经有的声明——所以本句必带声明路径;
46
- * `reason` 两因分列(`no such file` 修路径 ∥ `read failed: <code>` 修权限)。
50
+ * `reason` 五值分列,对应三类可修面(KD-M1-65):`no such directory` 改路径 ∥ `not a directory`
51
+ * 改形态 ∥ `no .md file` 往层里放档;`read failed: <code>` ∥ `manifest read failed: <code>` 修权限 / 修档。
47
52
  * @param {{path: string, reason: string}} p — 声明路径(绝对形)+ 读不到的原因
48
53
  * @returns {string}
49
54
  */
@@ -53,8 +58,9 @@ export const STANDARDS_UNREADABLE_NOTICE = ({ path, reason }) =>
53
58
  "Fix the path or the file — do NOT declare it again. State the limitation in your findings.)"
54
59
 
55
60
  /**
56
- * 半读句 —— 多份声明里有几份读不到(态 3 的下半;KD-M1-61 拒掉「只注入首份」:其余既不注入也不报
57
- * = 静默丢声明,与需求档 §5.1 验收 ③「任何一面都不得静默跳过」相抵)。
61
+ * 半读句 —— 一个层里(或声明的多个目录里)有几份读不到(态 3 的下半——零静默:余项既不注入也不报
62
+ * = 静默丢声明,与需求档 §5.1 验收 ③「任何一面都不得静默跳过」相抵;设计 = `MANIFEST.md` §2.12
63
+ * KD-M1-65 的原因分列)。
58
64
  * @param {{unreadable: string[]}} p — 逐份 `"<路径>: <原因>"`(路径绝对形)
59
65
  * @returns {string}
60
66
  */
@@ -100,6 +106,50 @@ export function findGuideRoot(cwd, scopeFiles) {
100
106
  return null
101
107
  }
102
108
 
109
+ /**
110
+ * 评审注入面的**项目根**推导(标准层与文档地图共用;判据 = `docs/core/design/MANIFEST.md`
111
+ * §2.12「判据」块的 `base` 行)。`findGuideRoot` 答的是另一问(最近的 `AGENTS.md`),不在此函数的
112
+ * 射程内。三段,按序、任一命中即止:
113
+ * ① 评审范围项的归属项目根 —— 逐项 `resolve(cwd, item)` → `projectRootView(item)`,首个 `state === "ok"` 的
114
+ * `root`;序 = 喂给 `findGuideRoot` 的同一个序(`[...pathList, ...docList]`)。判据用「数据档归属」而
115
+ * 不用「最近的 `AGENTS.md`」——本键的基数必须是项目根(`docRoot` 的值一律相对项目根解析)。
116
+ * ② 会话锚自身的归属项目根 —— `projectRootView(cwd).root`,仅 `state === "ok"` 时;`workspace` 不向下取
117
+ * 子项目(KD-M1-30),故工作区锚不会被猜成某个子项目。
118
+ * ③ 两腿皆空 ⇒ `null` —— 调用方落 `agent.cwd`(既有缺省;本函数不给项目指南的根,那仍归 `findGuideRoot`)。
119
+ * **护栏**:①② 的每一次 `projectRootView` 调用各自包 `try`(抛 ⇒ 跳过该项 / 该腿,其余照走;两腿全空 ⇒ ③)。
120
+ * 依据 `thincoder-core/manifest-discovery.mjs` 的契约行「I/O 异常照原样上抛」——`owningProject` 取根那一环
121
+ * 无护栏,同档明写调用点要自己包护栏;而注入器自己的 `try` 只包 `readManifest`,腿 ② 一抛就穿过去。
122
+ * **第三参零缺省**:`scopeFiles` 不是数组即当场拒(`undefined` 与 `null` 同拒),拒因点名该参数与收到的值;
123
+ * **不归一成 `[]`**——「忘了传」与「范围为空」语义相反(前者是调用方写错,后者是一次真空范围的评审)。
124
+ * @param {string} cwd — 会话锚(绝对路径)
125
+ * @param {string[]} scopeFiles — 评审范围路径(cwd 相对或绝对;**无缺省**,空评审传 `[]`)
126
+ * @returns {string|null} 被评审范围的归属项目根(绝对路径);无项目可指 ⇒ null
127
+ */
128
+ export function findProjectContextRoot(cwd, scopeFiles) {
129
+ if (!Array.isArray(scopeFiles)) {
130
+ const got = scopeFiles === undefined ? "undefined" : scopeFiles === null ? "null" : typeof scopeFiles
131
+ throw new TypeError(`findProjectContextRoot: scopeFiles must be an array (got ${got}) — pass the review scope as a list of paths, or [] for an empty one`)
132
+ }
133
+ for (const f of scopeFiles) {
134
+ try {
135
+ const view = projectRootView(resolve(cwd, f))
136
+ if (view.state === "ok") return view.root
137
+ } catch (e) {
138
+ // 该项解析抛(参数值异常 ∥ 权限 ∥ 链接环)⇒ 只跳过这一项,其余照走。
139
+ // 留一行告警:空吞会让「走了 ③」与「范围项本就无项目」在盘上不可分(同档另两处降级同形)。
140
+ console.warn(`[advisor] project-context root probe failed at ${String(f)} (cwd ${cwd}): ${e?.code ?? e?.message ?? "unknown"}`)
141
+ }
142
+ }
143
+ try {
144
+ const view = projectRootView(cwd)
145
+ if (view.state === "ok") return view.root
146
+ } catch (e) {
147
+ // 同 ①:护栏住推导函数,不中断评审消息组装;告警让这一步可追。
148
+ console.warn(`[advisor] project-context root probe failed at cwd ${cwd}: ${e?.code ?? e?.message ?? "unknown"}`)
149
+ }
150
+ return null
151
+ }
152
+
103
153
  /**
104
154
  * Inject the project guide (AGENTS.md) into the review message. AGENTS.md is the
105
155
  * project's doc map — it defines the structure and where requirements/design
@@ -207,10 +257,14 @@ export function findDocumentMap(base) {
207
257
  /**
208
258
  * Inject the project document map (PO-1), derived from `docRoot`. Degrades visibly: the reviewer
209
259
  * must know the Document-ownership criterion is unchecked — never a silent skip.
260
+ * @param {Object} agent — the parent agent
261
+ * @param {string[]} parts — message parts (mutated)
262
+ * @param {string[]} scopeFiles — 评审范围路径;base = 它们的归属项目根(`findProjectContextRoot`,与标准层同一条
263
+ * 推导;无根 ⇒ `agent.cwd`)。**无缺省**——非数组由该函数当场拒,拒因点名参数与收到的值。
210
264
  * @returns {string|null} the injected map path, or null when degraded
211
265
  */
212
- export function injectDocumentMap(agent, parts, root) {
213
- const base = root ?? agent.cwd
266
+ export function injectDocumentMap(agent, parts, scopeFiles) {
267
+ const base = findProjectContextRoot(agent.cwd, scopeFiles) ?? agent.cwd
214
268
  const mapPath = findDocumentMap(base)
215
269
  parts.push("## Document Map")
216
270
  let text = null
@@ -235,30 +289,111 @@ export function injectDocumentMap(agent, parts, root) {
235
289
  /** 消息里的路径书写(\ → /):与 `injectProjectGuide` 的根注记同款(`relative(...).split(sep).join("/")`),
236
290
  * 且让「声明路径字面」在消息里可 grep(`docs/nope` 而非 `docs\nope`)。读盘仍用原样路径。 */
237
291
  const displayPath = (p) => String(p).replaceAll("\\", "/")
292
+ /**
293
+ * 标准层成员收集(模块私有——遍历 ∥ 序 ∥ 去重的单源;判据 ∥ 序 = `docs/core/design/MANIFEST.md` §2.12「接口契约」)。
294
+ *
295
+ * 递归:只下潜 `ent.isDirectory()`;**符号链接一律不跟**(`ent.isSymbolicLink()` 跳过,既不判文件也不下潜)——
296
+ * 环保险只落在这条上:无深度帽(会静默漏档)、无跳过表 ∥ 无条数帽(那两者属索引面策略,搬进来同样静默漏档)。
297
+ * 成员按**名字**认 `.md`(大小写不敏);**文件侧**不按 dirent 类型预筛(目录必下潜、链接必跳):读得成 = 可读,读不成 = 不可读(带该档自己的原因)。
298
+ * 序 = 成员**收完后对整集排一次**:目录序(声明序)→ 层根相对路径(`/` 归一)码点序——不是逐层下潜各按名序
299
+ * (递归后裸文件名不再唯一;两种读法只在「子目录名是层根档名的前缀」时给出相反的序)。
300
+ * 嵌套根(一根本身在另一根之内)⇒ 同一份档按**解析后的绝对档路径**去重、保留首次出现(首次出现的层根定排序键);
301
+ * 去重键在 **win32 折小写**(尺子 = `pathKey`——同一目录的两种写法是同一个目录);折小写**只作用于去重键**,
302
+ * 排序键与定位注仍用盘上的原字符串。
303
+ * 不去重则同一份档进两次正文、吃两份预算。
304
+ * @param {string[]} dirs — 声明目录的绝对路径(声明序;`docRootPaths` 已去重)
305
+ * @returns {{readable: {path: string, text: string}[], unreadable: {path: string, reason: string}[]}}
306
+ */
307
+ function collectStandardDocs(dirs) {
308
+ const members = [] // { path, dirIndex, rel, text }——收完统一排序
309
+ const unreadable = []
310
+ dirs.forEach((dir, dirIndex) => {
311
+ // 逐目录四臂(判据 = §2.12「判据」块,逐臂对应):路径不存在 ∥ stat 抛 ∥ 不是目录 ∥ 列不出来。
312
+ if (!existsSync(dir)) { unreadable.push({ path: dir, reason: "no such directory" }); return }
313
+ let st
314
+ try {
315
+ st = statSync(dir)
316
+ } catch (e) {
317
+ unreadable.push({ path: dir, reason: `read failed: ${e?.code ?? "unknown"}` })
318
+ return
319
+ }
320
+ if (!st.isDirectory()) { unreadable.push({ path: dir, reason: "not a directory" }); return }
321
+ let mdSeen = 0 // 整棵子树见过的 `.md` 名字数(零 ⇒ `no .md file`;被去重的那份也算见过——子树不是空的)
322
+ let listFailed = false // 有目录列不出来 ⇒ 子树内容未观察完,"零 `.md`" 就是一句没人观察到的事实
323
+ const stack = [[dir, ""]] // 显式栈:深处照样走(不限深度);项 = [绝对路径, 层根相对前缀]
324
+ while (stack.length > 0) {
325
+ const [here, prefix] = stack.pop()
326
+ let entries
327
+ try {
328
+ entries = readdirSync(here, { withFileTypes: true })
329
+ } catch (e) {
330
+ // 任一下潜目录列不出来 ⇒ 该目录进不可读集、其余照走(与层根同一臂,不另立原因词)。
331
+ unreadable.push({ path: here, reason: `read failed: ${e?.code ?? "unknown"}` })
332
+ listFailed = true
333
+ continue
334
+ }
335
+ for (const ent of entries) {
336
+ if (ent.isSymbolicLink()) continue // 一律不跟:既不判文件也不下潜(环保险)
337
+ const rel = prefix ? `${prefix}/${ent.name}` : ent.name
338
+ if (ent.isDirectory()) { stack.push([join(here, ent.name), rel]); continue }
339
+ if (!/\.md$/i.test(ent.name)) continue
340
+ mdSeen++
341
+ const p = join(here, ent.name)
342
+ try {
343
+ members.push({ path: p, dirIndex, rel, text: readFileSync(p, "utf8") })
344
+ } catch (e) {
345
+ unreadable.push({ path: p, reason: `read failed: ${e?.code ?? "unknown"}` })
346
+ }
347
+ }
348
+ }
349
+ // 全子树零 `.md` ⇒ 该层根不可读(态 2 的第三因:声明对了、层里没档)。
350
+ // 但「列不出来」与「层里没档」是两类可修面(KD-M1-65):目录列不完时子树内容未知,
351
+ // 再补一句 `no .md file` 就是拿没人观察到的事实指错方向(作者会去放档,该修的是权限)。
352
+ if (mdSeen === 0 && !listFailed) unreadable.push({ path: dir, reason: "no .md file" })
353
+ })
354
+ // 整集排一次:目录序 → 层根相对路径码点序(`a < b` 比较,不用 localeCompare——跨机器同序)
355
+ members.sort((a, b) => (a.dirIndex !== b.dirIndex ? a.dirIndex - b.dirIndex : a.rel < b.rel ? -1 : a.rel > b.rel ? 1 : 0))
356
+ const seen = new Set()
357
+ const readable = []
358
+ for (const m of members) {
359
+ const key = pathKey(resolve(m.path).replaceAll("\\", "/")) // 嵌套根 ∥ 同目录大小写两种写法:同一份档(win32 折小写)
360
+ if (seen.has(key)) continue // 保留首次出现(先出现的层根排在前面 ⇒ 排序键取它的层根)
361
+ seen.add(key)
362
+ readable.push({ path: m.path, text: m.text })
363
+ }
364
+ return { readable, unreadable }
365
+ }
238
366
 
239
367
  /**
240
368
  * Inject the project standards section (PO-2 · 判据 ∥ 文案单源 = `docs/core/design/MANIFEST.md` §2.12).
241
369
  *
370
+ * 标准层(`docRoot.standards`)= 一个**文档层(目录)**,不是一份档:层内成员 = 该目录**及其全部子目录**下的 `.md`
371
+ * (大小写不敏感),按**层根相对路径**码点序;符号链接一律不跟(KD-M1-63)。
372
+ *
242
373
  * 三态(**可机判互异**,本面立身之本 = 用声明、不猜固定名):
243
- * 态 1 未声明 —— `docRoot.standards` 缺键 / `null` / 一个路径都没得来 ⇒ `NO_STANDARDS_NOTICE`
374
+ * 态 1 未声明 —— `docRoot.standards` 缺键 / `null` / 一个目录都没得来 ⇒ `NO_STANDARDS_NOTICE`
244
375
  * (零路径字面、零 `declared`)。
245
- * 态 2 声明了但读不到 —— 声明了路径、逐份都不可读 ⇒ `STANDARDS_UNREADABLE_NOTICE`(点名**声明了
246
- * 的绝对路径** + 原因)。绝不与态 1 同形。
247
- * 态 3 读到 —— 正文注入(多份 = 按声明序拼接);部分读不到时正文在前、半读句点名不可读的逐份。
376
+ * 态 2 声明了但读不到 —— 逐目录 / 逐档都不可读 ⇒ `STANDARDS_UNREADABLE_NOTICE`(点名该**目录或该档**的
377
+ * 绝对路径 + 原因)。绝不与态 1 同形。原因取值域 = `no such directory` ∥ `not a directory` ∥
378
+ * `no .md file` ∥ `read failed: <code>` ∥ `manifest read failed: <code>`——三类可修面不同
379
+ * (改路径 ∥ 改形态 ∥ 往层里放档;KD-M1-65)。
380
+ * 态 3 读到 —— 逐档「定位注 + 正文」(目录序 + 层根相对路径码点序);部分读不到时正文在前、半读句逐项点名不可读者。
248
381
  *
249
382
  * 取值源 = `read.ok && read.manifest ? read.manifest : DEFAULT_MANIFEST`(同 `declaredDocRoots` 先例,
250
- * 不另立第二套判定)⇒ 整档缺失 / 非法一律 `std === null` ⇒ 态 1;`paths.length === 0 ⇒ 态 1` 是硬不
383
+ * 不另立第二套判定)⇒ 整档缺失 / 非法一律 `std === null` ⇒ 态 1;`dirs.length === 0 ⇒ 态 1` 是硬不
251
384
  * 变量——态 2 句永不含 `undefined` 路径。数据档本身读抛(非 ENOENT)收为态 2 族,不中断消息组装。
252
385
  *
253
386
  * @param {Object} agent — the parent agent(`cwd` / provider 取上下文窗口)
254
387
  * @param {string[]} parts — message parts (mutated)
255
- * @param {string|null} [root] — project root from the guide walk(`null` ⇒ `agent.cwd`;与
256
- * `injectDocumentMap` 同一 base)
388
+ * @param {string[]} scopeFiles — 评审范围路径;base = 它们的归属项目根(`findProjectContextRoot`;无根 ⇒
389
+ * `agent.cwd`)。与 `injectDocumentMap` 同一 base、同一条推导。**无缺省**——非数组由该函数当场拒,拒因点名
390
+ * 参数与收到的值。
257
391
  * @returns {string|string[]|null} 注入的标准档绝对路径(单份 = 串,多份 = 数组);降级 ⇒ null
258
392
  */
259
- export function injectProjectStandards(agent, parts, root) {
393
+ export function injectProjectStandards(agent, parts, scopeFiles) {
394
+ // base 先算:第三参不合契约时在改动 parts 之前就抛(消息里不留半段)。
395
+ const base = findProjectContextRoot(agent.cwd, scopeFiles) ?? agent.cwd
260
396
  parts.push("## Project Standards")
261
- const base = root ?? agent.cwd
262
397
 
263
398
  // 数据档本身读抛(权限 / 目录等——`readManifest` fail-closed 上抛):收为态 2 族,不冒 `undefined`。
264
399
  let read
@@ -271,36 +406,30 @@ export function injectProjectStandards(agent, parts, root) {
271
406
  }
272
407
 
273
408
  const std = (read.ok && read.manifest ? read.manifest : DEFAULT_MANIFEST).docRoot.standards
274
- // 态 1(两入口):未声明(缺键 / null / undefined)∥ 声明了但一个合法路径都没得来。
409
+ // 态 1(两入口):未声明(缺键 / null / undefined)∥ 声明了但一个合法目录都没得来。
275
410
  // 后者是硬不变量:宁可判「未声明」,也绝不发一句带 `undefined` 的「declared at …」。
276
- const paths = std == null ? [] : docRootPaths(std, base)
277
- if (paths.length === 0) {
411
+ const dirs = std == null ? [] : docRootPaths(std, base)
412
+ if (dirs.length === 0) {
278
413
  parts.push(NO_STANDARDS_NOTICE) // degraded — visible by contract
279
414
  parts.push("")
280
415
  return null
281
416
  }
282
417
 
283
- const readable = []
284
- const unreadable = []
285
- for (const p of paths) {
286
- if (!existsSync(p)) { unreadable.push({ path: p, reason: "no such file" }); continue }
287
- try {
288
- readable.push({ path: p, text: readFileSync(p, "utf8") })
289
- } catch (e) {
290
- unreadable.push({ path: p, reason: `read failed: ${e?.code ?? "unknown"}` })
291
- }
292
- }
293
- // 态 2:声明了,一份都读不到。
418
+ // 遍历 ∥ 排序 ∥ 嵌套去重全在 `collectStandardDocs`(本函数只留三态组装与预算——可读单元不变)。
419
+ const { readable, unreadable } = collectStandardDocs(dirs)
420
+ // 态 2:声明了,一份都读不到(句中路径 = 不可读集第一项——目录项与文件项同形)。
294
421
  if (readable.length === 0) {
295
422
  parts.push(STANDARDS_UNREADABLE_NOTICE({ path: displayPath(unreadable[0].path), reason: unreadable[0].reason }))
296
423
  parts.push("")
297
424
  return null
298
425
  }
299
426
 
300
- // 态 3:正文(多份 = 按声明序拼接,共用一次注入的同一预算——一次评审注入就是一个预算单位)。
301
- parts.push("The file below is the project's standards document. Judge methodology compliance against it.")
427
+ // 态 3:正文(一个层的全部档共用一次注入的同一预算——按**注入序**(目录序 → 层根相对路径码点序)拼接后一次截断)。
428
+ // 逐档定位注先行(评审要知道读的是哪一份),多档多行、与正文同序。
429
+ parts.push("The documents below are the project's standards — the `.md` files of the declared standards layer. Judge methodology compliance against them.")
302
430
  parts.push("")
303
- const body = readable.map((r) => r.text).join("\n\n")
431
+ const blocks = readable.map((r) => ({ path: r.path, text: `<!-- standards file: ${displayPath(r.path)} -->\n${r.text}` }))
432
+ const body = blocks.map((b) => b.text).join("\n\n")
304
433
  // 预算算式复用同两条常量、**逐注入独立计算**(不与指南共享池——两面语义不同,不该互相记账)。
305
434
  // providerSpec 取值在 body 之外算:上下文规格查不到也不得伪装成「没有标准档」。
306
435
  const resolvedProvider = agent.provider ?? agent._provider
@@ -313,17 +442,17 @@ export function injectProjectStandards(agent, parts, root) {
313
442
  if (chars.length > cap) {
314
443
  // 被截断的那一份(拼接期已有逐份偏移;偏移同以码点计)——恢复指针必须指向它,否则评审拿着残缺规矩判。
315
444
  let offset = 0
316
- let cut = readable[readable.length - 1].path
317
- for (const r of readable) {
318
- const len = [...r.text].length
319
- if (cap < offset + len) { cut = r.path; break }
445
+ let cut = blocks[blocks.length - 1].path
446
+ for (const b of blocks) {
447
+ const len = [...b.text].length
448
+ if (cap < offset + len) { cut = b.path; break }
320
449
  offset += len + 2 // +2 = 拼接分隔符 "\n\n"
321
450
  }
322
- // 截断的风险不在大小,在**静默**:指南截断丢的是指针,标准档截断丢的是判据本身。
451
+ // 截断的风险不在大小,在**静默**:指南截断丢的是指针,标准层截断丢的是判据本身。
323
452
  shown = chars.slice(0, cap).join("") + `\n\n…(truncated at ${cap} of ${chars.length} chars — the standard set is PARTIAL;\nread the full file — ${displayPath(cut)} — for the rest)`
324
453
  }
325
454
  parts.push(shown)
326
- // 半读句:正文在前,缺口逐份点名(零静默——KD-M1-61)。
455
+ // 半读句:正文在前,缺口逐项点名(零静默——KD-M1-65)。
327
456
  if (unreadable.length > 0) {
328
457
  parts.push(STANDARDS_PARTIAL_NOTICE({ unreadable: unreadable.map((u) => `${displayPath(u.path)}: ${u.reason}`) }))
329
458
  }