@thincoder/core 0.11.4 → 0.12.1

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 (199) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/abort-provenance.mjs +23 -0
  3. package/advisor/citations.mjs +5 -1
  4. package/advisor/compaction.mjs +13 -10
  5. package/advisor/history.mjs +6 -1
  6. package/advisor/loop.mjs +35 -10
  7. package/advisor/messages.mjs +31 -43
  8. package/advisor/project-context.mjs +49 -45
  9. package/advisor/run.mjs +82 -26
  10. package/advisor.mjs +40 -11
  11. package/agent/assemble.mjs +5 -5
  12. package/agent/chat-call.mjs +21 -1
  13. package/agent/completion.mjs +1 -20
  14. package/agent/dispatch-gates.mjs +8 -3
  15. package/agent/dispatch-run.mjs +131 -20
  16. package/agent/dispatch.mjs +23 -22
  17. package/agent/family-tools.mjs +4 -7
  18. package/agent/goal-judge.mjs +99 -0
  19. package/agent/goal-state.mjs +96 -0
  20. package/agent/helpers.mjs +13 -4
  21. package/agent/offload.mjs +1 -1
  22. package/agent/planning-graph-guardrail.mjs +224 -0
  23. package/agent/planning-prompt.mjs +179 -0
  24. package/agent/planning-step.mjs +460 -173
  25. package/agent/post-turn.mjs +23 -33
  26. package/agent/record-results.mjs +8 -5
  27. package/agent/run-stages.mjs +22 -41
  28. package/agent/run-start.mjs +26 -19
  29. package/agent/setup-reminders.mjs +16 -14
  30. package/agent/setup.mjs +3 -2
  31. package/agent/spawn-child.mjs +17 -4
  32. package/agent/suspension.mjs +42 -21
  33. package/agent/task-lifecycle.mjs +165 -52
  34. package/agent/timers.mjs +9 -1
  35. package/agent/turn-loop.mjs +160 -69
  36. package/agent/turn-projection.mjs +26 -15
  37. package/agent/turn-task-state.mjs +4 -4
  38. package/agent/write-gate-ledger.mjs +1 -1
  39. package/agent/write-gate.mjs +14 -11
  40. package/agent-tools/advisor-async.mjs +2 -0
  41. package/agent-tools/advisor-launch.mjs +27 -13
  42. package/agent-tools/advisor-settle.mjs +19 -18
  43. package/agent-tools/advisor.mjs +90 -13
  44. package/agent-tools/bash-async.mjs +3 -3
  45. package/agent-tools/batch-ledger-bind.mjs +8 -5
  46. package/agent-tools/batch-read.mjs +42 -0
  47. package/agent-tools/batch-record-write.mjs +20 -12
  48. package/agent-tools/batch-segment-vocab.mjs +6 -4
  49. package/agent-tools/batch-skeleton.mjs +43 -12
  50. package/agent-tools/consult.mjs +5 -1
  51. package/agent-tools/context.mjs +5 -4
  52. package/agent-tools/design-slots.mjs +7 -4
  53. package/agent-tools/design-token.mjs +3 -2
  54. package/agent-tools/doc-graph.mjs +257 -95
  55. package/agent-tools/escalate-async.mjs +4 -1
  56. package/agent-tools/goal.mjs +28 -95
  57. package/agent-tools/plan.mjs +1 -1
  58. package/agent-tools/review-facts.mjs +56 -7
  59. package/agent-tools/settings.mjs +35 -1
  60. package/agent-tools/ssh-transport.mjs +23 -22
  61. package/agent-tools/step.mjs +24 -4
  62. package/agent-tools/subagent-actions.mjs +6 -2
  63. package/agent-tools/subagent-async.mjs +4 -2
  64. package/agent-tools/subagent.mjs +1 -1
  65. package/agent-tools/task.mjs +73 -65
  66. package/agent-tools.mjs +3 -3
  67. package/agent.mjs +12 -3
  68. package/auto-think.mjs +16 -3
  69. package/browser/actions.mjs +5 -1
  70. package/browser/cdp.mjs +1 -1
  71. package/browser/pool.mjs +110 -17
  72. package/compaction-work-state.mjs +103 -13
  73. package/compress-form.mjs +29 -3
  74. package/config-defaults.mjs +27 -3
  75. package/config-io.mjs +3 -14
  76. package/config-normalize.mjs +24 -4
  77. package/config-presets.mjs +40 -26
  78. package/config-warn.mjs +30 -0
  79. package/config.mjs +139 -63
  80. package/context-degrade.mjs +4 -4
  81. package/context-push.mjs +20 -9
  82. package/context.mjs +65 -20
  83. package/doc-graph/anchors.mjs +39 -40
  84. package/doc-graph/clusters.mjs +49 -0
  85. package/doc-graph/code-parsers.mjs +494 -0
  86. package/doc-graph/context-pack.mjs +392 -0
  87. package/doc-graph/dir-signals.mjs +228 -0
  88. package/doc-graph/edges.mjs +231 -0
  89. package/doc-graph/format.mjs +70 -0
  90. package/doc-graph/gc-cmd.mjs +104 -0
  91. package/doc-graph/gc.mjs +112 -0
  92. package/doc-graph/glob-work-graph.mjs +307 -0
  93. package/doc-graph/golden-set.mjs +131 -0
  94. package/doc-graph/ls-work-graph.mjs +534 -0
  95. package/doc-graph/outline.mjs +377 -0
  96. package/doc-graph/output-annotations.mjs +85 -0
  97. package/doc-graph/process-docs.mjs +68 -0
  98. package/doc-graph/read-work-graph.mjs +91 -0
  99. package/doc-graph/rebuild-cmd.mjs +75 -0
  100. package/doc-graph/resolvers.mjs +322 -0
  101. package/doc-graph/roots.mjs +86 -0
  102. package/doc-graph/schema.mjs +110 -0
  103. package/doc-graph/search-augment.mjs +418 -0
  104. package/doc-graph/store.mjs +231 -0
  105. package/doc-graph/target-resolve.mjs +352 -0
  106. package/doc-graph/walk.mjs +87 -0
  107. package/doc-graph.mjs +583 -707
  108. package/explore-distill.mjs +52 -17
  109. package/generate-title.mjs +7 -4
  110. package/ledger-close.mjs +6 -6
  111. package/ledger-cmd.mjs +3 -3
  112. package/ledger-consistency.mjs +8 -6
  113. package/ledger-db.mjs +45 -10
  114. package/ledger-migrate.mjs +25 -10
  115. package/ledger-read.mjs +1 -1
  116. package/ledger-write-ops.mjs +6 -6
  117. package/ledger.mjs +2 -2
  118. package/model-context.mjs +54 -18
  119. package/model-specs.mjs +86 -67
  120. package/package.json +1 -1
  121. package/prompt-overlays.mjs +3 -3
  122. package/prompts/advisor-round1.md +6 -5
  123. package/prompts/common.md +16 -6
  124. package/prompts/consult-base.md +2 -1
  125. package/prompts/discipline-engineering.md +1 -1
  126. package/prompts/discipline-normal.md +12 -8
  127. package/prompts/knowledge/doc-lookup.md +2 -2
  128. package/prompts/knowledge/normal-batch-discipline.md +2 -2
  129. package/prompts/knowledge/normal-delivery-collaboration.md +3 -3
  130. package/prompts/knowledge/tool-advisor.md +2 -2
  131. package/prompts/knowledge/tool-apply-patch.md +1 -1
  132. package/prompts/knowledge/tool-bash.md +2 -2
  133. package/prompts/knowledge/tool-batch.md +4 -4
  134. package/prompts/knowledge/tool-glob.md +9 -2
  135. package/prompts/knowledge/tool-goal.md +9 -6
  136. package/prompts/knowledge/tool-grep.md +7 -2
  137. package/prompts/knowledge/tool-ls.md +11 -5
  138. package/prompts/knowledge/tool-lsp.md +1 -1
  139. package/prompts/knowledge/tool-operations.md +3 -2
  140. package/prompts/knowledge/tool-plan.md +1 -1
  141. package/prompts/knowledge/tool-read.md +7 -6
  142. package/prompts/knowledge/tool-repo-graph-read.md +12 -0
  143. package/prompts/knowledge/tool-repo-graph.md +12 -0
  144. package/prompts/knowledge/tool-step.md +1 -1
  145. package/prompts/knowledge/tool-subagent.md +2 -2
  146. package/prompts/knowledge/tool-task.md +10 -9
  147. package/prompts/knowledge/tool-tree.md +7 -1
  148. package/prompts/persona-eng-coder.md +1 -1
  149. package/prompts/persona-eng-designer.md +1 -1
  150. package/prompts/persona-engineering.md +2 -1
  151. package/prompts/persona-explore.md +1 -1
  152. package/prompts/persona-normal.md +7 -6
  153. package/prompts/persona-plan.md +2 -2
  154. package/prompts/planning-next-moves.md +7 -8
  155. package/provider/anthropic.mjs +53 -51
  156. package/provider/core.mjs +85 -34
  157. package/provider/errors.mjs +33 -10
  158. package/provider/google.mjs +244 -37
  159. package/provider/list-models.mjs +28 -14
  160. package/provider/responses-request.mjs +15 -9
  161. package/provider/responses.mjs +10 -8
  162. package/provider/sse.mjs +3 -6
  163. package/proxy-transport.mjs +228 -119
  164. package/rules-file.mjs +79 -0
  165. package/rules.mjs +13 -51
  166. package/session-lifecycle.mjs +32 -20
  167. package/team-ledger.mjs +7 -7
  168. package/think-off.mjs +37 -18
  169. package/token-window.mjs +48 -31
  170. package/tool-args.mjs +8 -8
  171. package/tool-docs/bash.md +1 -1
  172. package/tool-docs/glob.md +3 -1
  173. package/tool-docs/goal.md +2 -2
  174. package/tool-docs/grep.md +3 -1
  175. package/tool-docs/ls.md +7 -1
  176. package/tool-docs/read.md +1 -1
  177. package/tool-docs/repo_graph-read.md +3 -0
  178. package/tool-docs/repo_graph.md +3 -0
  179. package/tool-docs/tree.md +1 -1
  180. package/tools/bash.mjs +53 -8
  181. package/tools/browser.mjs +4 -4
  182. package/tools/file.mjs +34 -7
  183. package/tools/glob-dialect.mjs +57 -7
  184. package/tools/index.mjs +3 -7
  185. package/tools/patch.mjs +8 -7
  186. package/tools/process-doc-mark.mjs +13 -0
  187. package/tools/search.mjs +152 -37
  188. package/tools/shared.mjs +6 -0
  189. package/tools/tree.mjs +211 -8
  190. package/window-policy.mjs +205 -126
  191. package/prompts/knowledge/tool-doc-graph-read.md +0 -20
  192. package/prompts/knowledge/tool-doc-graph.md +0 -49
  193. package/prompts/knowledge/tool-peek.md +0 -10
  194. package/prompts/knowledge/tool-repo-outline.md +0 -4
  195. package/tool-docs/doc_graph-read.md +0 -3
  196. package/tool-docs/doc_graph.md +0 -3
  197. package/tool-docs/peek.md +0 -3
  198. package/tool-docs/repo_outline.md +0 -3
  199. package/tools/peek.mjs +0 -447
@@ -6,7 +6,7 @@
6
6
  * 切点 = 原档「Review-instance registry」分节起、`cancelAsyncAdvisor` 之前整段。
7
7
  * 本档对**池与队列**只读(不碰队列、不碰控制器、不写池);实例注册表按既有语义懒建与回收,故
8
8
  * `advisorRuns` ∥ `resolveAdvisorLaunch` 会写 `_advisorRuns` 与镜像字段。留下的族是「起 ∥ 停 ∥ 排 ∥ 关」写动作。
9
- * 依赖方向单一:本档只依赖 `carrierField` ∥ `getAsyncPool`(async-settle.mjs)∥ `docSetKey` ∥
9
+ * 依赖方向单一:本档只依赖 `carrierField` ∥ `getAsyncPool`(async-settle.mjs)∥ `codeReviewScopeKey` ∥ `docSetKey` ∥
10
10
  * `resolveReviewDocPaths` ∥ `scopeAdvisorMirror`(review-facts.mjs)∥ `randomUUID`(node:crypto);
11
11
  * advisor-async.mjs 反向 import 本档的判定函数——两档之间是单向边。与 async-settle.mjs 之间
12
12
  * 存在**既有的**一环(该档静态 import `refillAdvisorQueue`,本档 import `carrierField` ∥ `getAsyncPool`):
@@ -15,7 +15,7 @@
15
15
  * 既有 import 面零改:原档 re-export 本档的全部既有导出(同 design-token.mjs ∥ advisor-settle.mjs 的先例)。
16
16
  */
17
17
  import { randomUUID } from "node:crypto"
18
- import { docSetKey, resolveReviewDocPaths, scopeAdvisorMirror } from "./review-facts.mjs"
18
+ import { codeReviewScopeKey, docSetKey, resolveReviewDocPaths, scopeAdvisorMirror } from "./review-facts.mjs"
19
19
  import { carrierField, getAsyncPool } from "./async-settle.mjs"
20
20
 
21
21
  // ─────────────────────────────────────────────────────────────────────────────
@@ -43,12 +43,15 @@ export function advisorRuns(agent) {
43
43
  return holder._advisorRuns
44
44
  }
45
45
 
46
- /** The newest OPEN code instance (the thread a fix-round launch continues), or null. */
47
- export function openCodeRun(agent) {
46
+ /** The newest OPEN code instance for this review scope (the thread a fix-round launch
47
+ * continues), or null. `scopeKey` 省略 ⇒ 不限范围(`effectiveAdvisorRound` 这类无范围可言的
48
+ * 读面沿用旧语义);给了 ⇒ 只认同键实例(键不同 = 另一件活,见 `codeReviewScopeKey`)。 */
49
+ export function openCodeRun(agent, scopeKey = undefined) {
48
50
  const runs = advisorRunsRead(agent)
49
51
  if (!(runs instanceof Map) || runs.size === 0) return null
50
52
  for (const r of [...runs.values()].reverse()) {
51
- if (r.reviewType === "code" && r.open) return r
53
+ if (r.reviewType !== "code" || !r.open) continue
54
+ if (scopeKey === undefined || r.scopeKey === scopeKey) return r
52
55
  }
53
56
  return null
54
57
  }
@@ -63,19 +66,25 @@ function openDesignRun(agent, key) {
63
66
  return null
64
67
  }
65
68
 
69
+ /** 未携显式范围(`paths` / `documents` 都空)的代码评审共用的范围键。它们取的是范围**回退面**
70
+ * (`agent._touchedFiles`——逐次发起都在变):拿那张表做键会让 guard 驱动的修复轮永远开新实例、
71
+ * 丢掉收敛,所以这类发起共用一个 sentinel 键,彼此仍能续跑。 */
72
+ const IMPLICIT_CODE_SCOPE = "<implicit>"
73
+
66
74
  /**
67
75
  * Resolve the review instance a launch continues (AGENT-LOOP-ASYNC-POOL.md §5「后台评审」 ③ — per-review
68
76
  * rounds/prior; reviewId = designId for design reviews, a random id for code).
69
77
  * - design: continue the OPEN instance of the same document set (fix rounds of
70
78
  * a review thread keep its designId and its round/prior); none → new instance.
71
- * - code: continue the newest OPEN code instance (guard-driven fix loops);
72
- * none → new instance.
79
+ * - code: continue the OPEN instance of the **same scope key** (2026-12-01 — guard-driven
80
+ * fix loops of the same work keep their round/prior; a different reviewed set is a
81
+ * different piece of work and starts at round 1 with no prior); none → new instance.
73
82
  * The legacy agent._advisorRound/_lastAdvisorOutput fields are SCOPED to the
74
83
  * instance before the launch (message building + the run.mjs cap read them) —
75
84
  * prior-less continuation degrades to round 1 semantics (fresh full review).
76
85
  * @returns {{run: object, isNew: boolean, reviewId: string, designId: string|null}}
77
86
  */
78
- export function resolveAdvisorLaunch(agent, reviewType, { documents = null } = {}) {
87
+ export function resolveAdvisorLaunch(agent, reviewType, { documents = null, paths = null } = {}) {
79
88
  const runs = advisorRuns(agent)
80
89
  let run = null
81
90
  if (reviewType === "design") {
@@ -98,14 +107,18 @@ export function resolveAdvisorLaunch(agent, reviewType, { documents = null } = {
98
107
  reviewId, reviewType, designId: prior?.designId ?? reviewId,
99
108
  round: 0, priorOutput: null, stale: false, open: true, docSetKey: key,
100
109
  // 被审文档集的**受理绝对路径**(单源 = `resolveReviewDocPaths`——与受理面同一把尺):
101
- // §10.2 封印按这一组算。`docSetKey` 是实例键(`normAbs` 的 cwd 拼法),cwd 非项目根时
102
- // 它与受理路径不是同一组——拿实例键当封印清单会把封印盖到另一条路径上。
110
+ // §10.2 封印按这一组算。`docSetKey` 是实例键,形 = `canonPath` 归一形(cwd 拼接 + 分隔符 /
111
+ // 尾分隔符 / win32 大小写);cwd 非项目根时它与受理路径不是同一组——拿实例键当封印清单
112
+ // 会把封印盖到另一条路径上。
103
113
  docAbs: [...resolveReviewDocPaths(documents, agent.cwd).resolved.values()],
104
114
  }
105
115
  runs.set(reviewId, run)
106
116
  }
107
117
  } else {
108
- run = openCodeRun(agent)
118
+ // 代码轨范围键(2026-12-01):只有**显式**范围才入键;都空就走回退面,共用一个 sentinel
119
+ // (`_touchedFiles` 逐次在变——当键用会让修复轮永远开新实例)。
120
+ const scopeKey = codeReviewScopeKey(paths, documents, agent.cwd) ?? IMPLICIT_CODE_SCOPE
121
+ run = openCodeRun(agent, scopeKey)
109
122
  if (!run) {
110
123
  // #863 实例回收(AGENT-LOOP-ASYNC-POOL.md §3「分域池」):新 code 实例创建 ⇒ closed 实例清除(openCodeRun 仅取 open——零消费)。
111
124
  for (const r of [...runs.values()]) {
@@ -114,7 +127,7 @@ export function resolveAdvisorLaunch(agent, reviewType, { documents = null } = {
114
127
  const reviewId = randomUUID()
115
128
  run = {
116
129
  reviewId, reviewType, designId: null,
117
- round: 0, priorOutput: null, stale: false, open: true, docSetKey: null,
130
+ round: 0, priorOutput: null, stale: false, open: true, docSetKey: null, scopeKey,
118
131
  }
119
132
  runs.set(reviewId, run)
120
133
  }
@@ -154,7 +167,8 @@ export function advisorPoolLimitFor(agent) {
154
167
  }
155
168
  /** AGENT-LOOP-ASYNC-POOL.md §3「分域池」 同 scope 守卫(F-5——用户裁①):同 reviewType+scope 有 running 评审 → true
156
169
  * (拒——running 并行多实例歧义放大——settled 续跑语义不变)。design scope = 文档集键
157
- * (docSetKey);code = 单 code 线程(记录不记路径键——与 openCodeRun 语义一致)。
170
+ * (docSetKey);code = 单 code 线程(不论范围键——并发多代码评审仍是一线程;续跑维度另论:
171
+ * `openCodeRun` 按范围键续跑,与并发面无关)。
158
172
  * 与池容量守卫独立:容量 = 全局 ≤N——scope = 同 scope ≤1——两关都过才启动。 */
159
173
  export function runningAdvisorOfScope(agent, reviewType, docSetKey) {
160
174
  const pool = getAsyncPool(agent, "advisor")
@@ -85,19 +85,23 @@ export function reviewIsStale(agent, entry) {
85
85
  * @returns {{id: string, path: string}|null} 命中评审 id + 冲突路径(ABS),无冲突 null
86
86
  */
87
87
  export function inflightDesignReviewConflict(agent, absPaths) {
88
- const pool = agent?._asyncAdvisors
89
- if (!(pool instanceof Map) || pool.size === 0) return null
88
+ // P0-2:同步轨与异步轨同判——同步设计评审登记在 `_syncAdvisors`(同形条目),
89
+ // 冻结窗必须两池都扫,否则 `async:false` 的在途评审护不住被审档。
90
+ const pools = [agent?._asyncAdvisors, agent?._syncAdvisors]
90
91
  const wanted = (absPaths ?? [])
91
92
  .filter((p) => typeof p === "string" && p.length > 0)
92
93
  .map((p) => normAbs(p, agent?.cwd))
93
94
  if (wanted.length === 0) return null
94
- for (const entry of pool.values()) {
95
- if (!entry || entry.reviewType !== "design") continue
96
- if (entry.status !== "running" || entry.cancelled || entry.done) continue
97
- const scope = (entry.docAbs ?? []).map((p) => normAbs(p, agent?.cwd))
98
- if (scope.length === 0) continue
99
- const set = new Set(scope)
100
- for (const p of wanted) if (set.has(p)) return { id: String(entry.id), path: p }
95
+ for (const pool of pools) {
96
+ if (!(pool instanceof Map) || pool.size === 0) continue
97
+ for (const entry of pool.values()) {
98
+ if (!entry || entry.reviewType !== "design") continue
99
+ if (entry.status !== "running" || entry.cancelled || entry.done) continue
100
+ const scope = (entry.docAbs ?? []).map((p) => normAbs(p, agent?.cwd))
101
+ if (scope.length === 0) continue
102
+ const set = new Set(scope)
103
+ for (const p of wanted) if (set.has(p)) return { id: String(entry.id), path: p }
104
+ }
101
105
  }
102
106
  return null
103
107
  }
@@ -213,19 +217,15 @@ export function settleAdvisorRun(agent, entry) {
213
217
  // back for a retry (fix #2 anti-silent-skip intent; attempts still consume
214
218
  // the per-review round budget, so repeated failures stay bounded by the
215
219
  // cap). An error settle (rejection path — report null with an error) has no
216
- // verdict either — same exclusion (advisor 复评补边). Design reviews keep
217
- // the mark on any completed verdict (parity with the sync recordToolResults
218
- // mark — they have no code face to cover) — EXCEPT a launch-refusal report
219
- // (nothing was sent, no verdict at all: see launchRefused below).
220
+ // verdict either — same exclusion (advisor 复评补边).
220
221
  // 第 11 批(F16/A3):失败判定 = 单谓词六 kind(含 review_failed 字符串 resolve 形态)
221
222
  // ——旧 `^` 锚正则只认首行形态,漏「时间线 + 尾」;语义零丢(六形态全覆盖)。
223
+ // P0-3(F11/§6.2):两轨同判——不完整评审不计覆盖(design 轨不再例外;与同步面
224
+ // `record-results.mjs` 的 `!incomplete && !run?.stale` 同判)。
222
225
  // 另:设计评审的**启动拒绝报告**(未发起请求——无评审产出)同样不得计为评审覆盖
223
226
  // (异步结算面判据;与同步工具面 _advisorRefusals 同源前缀;正常链不可达=防御纵深)
224
227
  // ——判定已上移为本结算段单点(launchRefused,上方)。
225
- const failureVerdict = (run.reviewType !== "design" && (
226
- incomplete !== null ||
227
- (result == null && entry.error != null)
228
- )) || launchRefused
228
+ const failureVerdict = incomplete !== null || (result == null && entry.error != null) || launchRefused
229
229
  if (!failureVerdict) {
230
230
  agent._calledAdvisorThisRun = true
231
231
  // ADVISOR-CONVERGENCE.md §6.4 B 复位点 2(异步面):非陈旧且非失败结算 ⇒ 评审真的覆盖了这份代码
@@ -245,7 +245,8 @@ export function settleAdvisorRun(agent, entry) {
245
245
  // 结论块(下方)刻意晚于 prior 归一:prior 只承载评审正文,不携带机制文案。
246
246
  // #863 关闭点轻量化(父侧批·五裁定——§2.3 表外追加):closed 实例零消费面(续跑仅取 open)——
247
247
  // 关闭后不再写回 priorOutput(否则 settleDesignReview 关闭点的释放被覆盖)。
248
- if (run.open && report && looksLikeReviewOutput(report)) {
248
+ // P3:不完整报告不作 prior(与 run.mjs / record-results.mjs 同判)。
249
+ if (run.open && report && looksLikeReviewOutput(report) && advisorIncompleteMarker(String(report)) === null) {
249
250
  run.priorOutput = stripApprovedSuffix(report, run.approvedSuffix)
250
251
  }
251
252
  // F28/F29 失败结论(2026-09-18 顾问面治理批——**两轨共用**,ADVISOR-GUARDS.md §7 契约二):
@@ -11,16 +11,20 @@
11
11
  import { runAdvisorReview, advisorIncompleteMarker, ADVISOR_LAUNCH_REFUSAL_PREFIX } from "../advisor/run.mjs"
12
12
  import { resolveBatchDocPath } from "./batch.mjs"
13
13
  // 设计评审的文档受理面单源 = review-facts.mjs 的 resolveReviewDocPaths(判据正文 =
14
- // docs/core/design/ADVISOR-GUARDS.md §12:相对形按会话项目根 / 绝对形照用 / 受理 = 项目内现存 `.md`)。
14
+ // docs/core/design/ADVISOR-GUARDS.md §10:相对形按会话项目根 / 绝对形照用 / 受理 = 项目内现存 `.md`)。
15
15
  import { projectRootView } from "../manifest-discovery.mjs"
16
- import { resolveReviewDocPaths } from "./review-facts.mjs"
16
+ import { resolveReviewDocPaths, touchedCandidateHint } from "./review-facts.mjs"
17
17
  import {
18
18
  generateDesignToken,
19
19
  settleDesignReview,
20
20
  resolveAdvisorLaunch,
21
21
  launchAsyncAdvisor,
22
22
  stripApprovedSuffix,
23
+ mutationSeqOf,
24
+ reviewIsStale,
23
25
  } from "./advisor-async.mjs"
26
+ // P0-2:陈旧结算的 token 清洗(单源三形——与异步 settle 同一函数)。
27
+ import { stripDesignTokenEcho } from "./design-token.mjs"
24
28
  // F30/F31(2026-09-18 顾问面治理批):类型门判定 / 拒发串 / 对象标识行——单源 `advisor/notice.mjs`
25
29
  // (文案逐字 = ADVISOR-GUARDS.md §2.4 / §2.5);零计数载体(计数护栏随撤 cap 整体退场)。
26
30
  import { typeGateCriterion, buildTypeGateRefusal, identityLine, scopeSummary, withIdentityLine } from "../advisor/notice.mjs"
@@ -90,6 +94,21 @@ function buildBatchNoLedgerRefusal({ batchDocAbs, chain, scope }) {
90
94
  ].join("\n")
91
95
  }
92
96
 
97
+ /**
98
+ * 文档范围门拒文(**逐字**——判据单源 `docs/core/design/ADVISOR-GUARDS.md` §2.3 第 5 项 + 需求 F36/N2):
99
+ * 首行 = 稳定前缀 `Advisor: launch refused` + 标识行(与准入门同族形态);其后 Why + 两个期望形 + 收尾句。
100
+ * 与准入门同因:判的是「参数在不在」,用户知道怎么传不等于知道没范围时怎么办。
101
+ */
102
+ function buildDocumentsRequiredRefusal(identity) {
103
+ return [
104
+ `Advisor: launch refused — a design review must carry \`documents\`: the design documents under review. ${identity}`,
105
+ "Why: the design token is sealed to the reviewed document set — with no set there is nothing to seal, so the token would authorize edits to any design doc, and the freeze window and the staleness check would have no scope to watch. The old fallback guessed the scope from git diff; guessing is exactly what F36 forbids.",
106
+ "Expected form 1 — project-root-relative: docs/<area>/<name>.md (resolved against the session project root).",
107
+ "Expected form 2 — absolute: D:\\repo\\docs\\<area>\\<name>.md (used as-is).",
108
+ "Nothing was sent: no review instance, no round consumed, no design token minted, no LLM call.",
109
+ ].join("\n")
110
+ }
111
+
93
112
  export const advisorTool = {
94
113
  name: "advisor",
95
114
  description: DESC("advisor"),
@@ -198,6 +217,18 @@ export const advisorTool = {
198
217
  })
199
218
  }
200
219
  }
220
+ // 文档范围门(F36 / N2 / `ADVISOR-GUARDS.md` §2.3 第 5 项):设计评审必须显式给出被审文档集——缺省时旧实现
221
+ // 回退到 git diff 猜范围(N2 明禁),且 `docAbs` 为空会让封印、冻结窗、陈旧判定三面同时失效
222
+ // (token 绑不到任何档)。位置 = 账链门之后(与 §2.3 点火顺序表一致:第 4 项账链、第 5 项 documents)。
223
+ if (reviewType === "design" && !(Array.isArray(args.documents) && args.documents.some((d) => typeof d === "string" && d.trim()))) {
224
+ if (ctx._toolCallId !== undefined) (agent._advisorRefusals ??= new Set()).add(ctx._toolCallId)
225
+ return buildDocumentsRequiredRefusal(identityLine({
226
+ type: reviewType,
227
+ scope: scopeSummary(args.paths ?? null),
228
+ round: "—", // 判定先于实例解析——本次发起无轮次(§2 第 5 条字段行)
229
+ criterion: "documents-missing",
230
+ }))
231
+ }
201
232
  const documents = args.documents || null
202
233
  // Scope fallback: the runtime mutation record (zero git) covers guard-triggered
203
234
  // reviews where the model did not pass explicit paths.
@@ -213,9 +244,13 @@ export const advisorTool = {
213
244
  )
214
245
  }
215
246
 
216
- // 设计评审:受理面 = 项目内现存 `.md`——相对形按会话项目根解析(越根 ⇒ 拒)· 绝对形照用 · 解析不出 ⇒ 拒并说清期望形;零试探、零歧义归一。
217
- if (reviewType === "design" && documents) {
218
- const { invalid } = resolveReviewDocPaths(documents, agent.cwd)
247
+ // 受理面(两轨同判——P1-7):`documents` 给了就校验(项目内现存 `.md`;相对形按会话项目根解析,
248
+ // 越根 ⇒ 拒;绝对形照用;解析不出 ⇒ 拒并说清期望形)。设计轨的 `documents` 是被审对象,
249
+ // 代码轨的是验收判据上下文——两者读不到都会让评审静默少读,所以同一道门。
250
+ let designDocAbs = []
251
+ if (documents) {
252
+ const { resolved, invalid } = resolveReviewDocPaths(documents, agent.cwd)
253
+ if (reviewType === "design") designDocAbs = [...resolved.values()]
219
254
  if (invalid.length > 0) {
220
255
  if (ctx._toolCallId !== undefined) (agent._advisorRefusals ??= new Set()).add(ctx._toolCallId)
221
256
  // 拒发文案:既有稳定前缀逐字(行首)+ 逐文档「输入 → 解析后绝对路径 ∥ 拒因」+ 锚态(仅无唯一基根)+ 候选全列 + 期望形两句。
@@ -224,12 +259,16 @@ export const advisorTool = {
224
259
  const view = projectRootView(agent.cwd)
225
260
  const where = view.state === "workspace" ? `workspace (${view.candidates.join(", ")})` : "none (no PROJECT-MANIFEST.json here or above)"
226
261
  lines.push(`Session anchor is ${where} — no single project root, so a relative path has no base to resolve against.`)
262
+ // 实发相容提示(零推断):候选根里哪个是本会话真正碰过文件的那一个 —— 证据 = 运行期改动记录
263
+ // (`_touchedFiles`,本档范围回退面已消费的同一张表);零命中 ∥ 多命中 ⇒ 不加行,宁缺勿错。
264
+ const hint = touchedCandidateHint(view.candidates, agent._touchedFiles)
265
+ if (hint) lines.push(`This session has touched files under ${hint} — that is the project your work belongs to; anchor there or pass absolute paths.`)
227
266
  const cands = [...new Set(invalid.flatMap((v) => v.candidates ?? []))]
228
267
  if (cands.length > 0) lines.push(`Candidates: ${cands.join(" ∥ ")} — pass one explicitly (an absolute path is the surest form).`)
229
268
  }
230
269
  lines.push("Expected form 1 — project-root-relative: docs/<area>/<name>.md (resolved against the session project root).", "Expected form 2 — absolute: D:\\repo\\docs\\<area>\\<name>.md (used as-is).")
231
270
  return withIdentityLine(
232
- `Advisor: design review documents must be documentation files (per the project's conventions). Invalid:\n${lines.join("\n")}`,
271
+ `Advisor: ${reviewType === "design" ? "design review documents" : "documents"} must be documentation files (per the project's conventions). Invalid:\n${lines.join("\n")}`,
233
272
  { type: reviewType, scope: scopeSummary(documents), round: "—", criterion: "scope-not-doc" },
234
273
  )
235
274
  }
@@ -262,7 +301,9 @@ export const advisorTool = {
262
301
  // slot/spawn continuity; code = the newest OPEN instance). The resolution
263
302
  // scopes agent._advisorRound/_lastAdvisorOutput so the message builder and
264
303
  // the run.mjs cap read THIS instance's round/prior (multi-review isolation).
265
- const resolved = resolveAdvisorLaunch(agent, reviewType, { documents })
304
+ // 代码轨范围键只吃**显式**范围:回退值(`_touchedFiles`)逐次发起都在变,当键用会让 guard
305
+ // 驱动的修复轮永远开新实例、丢掉收敛;回退值仍照旧喂评审消息(上方 `paths` 变量)。
306
+ const resolved = resolveAdvisorLaunch(agent, reviewType, { documents, paths: args.paths ?? null })
266
307
  resolved.run.batchDoc = launchBatchDoc
267
308
  // Design token minted for EVERY design round — the reviewer echoes it only on
268
309
  // a clean pass; on pass it is slotted under the instance's designId at settle
@@ -322,12 +363,38 @@ export const advisorTool = {
322
363
  if (ctx._toolCallId !== undefined) {
323
364
  (agent._advisorSyncCalls ??= new Map()).set(ctx._toolCallId, resolved.reviewId)
324
365
  }
325
- const result = await runAdvisorReview(agent, reviewType, {
326
- onOutput: ctx.onOutput,
327
- signal: ctx.signal,
328
- // 同步路径的绑定传递 = 同一逐笔值(异步路径走条目 `batchDoc` 字段,同值同形)。
329
- batchDoc: launchBatchDoc,
330
- }, designToken, documents, paths, reviewObject, designId)
366
+ // P0-2(D5 冻结窗口 + 陈旧判定,同步轨):同步设计评审与异步同判——发起时登记一条在途条目
367
+ // (`_syncAdvisors`,与 `_asyncAdvisors` 同形),让 `inflightDesignReviewConflict` /
368
+ // `freezeWindowConflict` 看得见它;结算前用同一 `reviewIsStale` 判陈旧。覆盖场景 = 同一条
369
+ // assistant 消息里的并行工具调用(同步评审阻塞本调用,不阻塞同批其他写)。
370
+ const syncEntry = reviewType === "design"
371
+ ? {
372
+ id: `sync-${ctx._toolCallId ?? `t${Date.now()}`}`,
373
+ reviewType: "design",
374
+ status: "running",
375
+ cancelled: false,
376
+ done: false,
377
+ docAbs: designDocAbs,
378
+ batchDoc: launchBatchDoc,
379
+ launchSeq: mutationSeqOf(agent),
380
+ run: resolved.run,
381
+ }
382
+ : null
383
+ if (syncEntry) (agent._syncAdvisors ??= new Map()).set(syncEntry.id, syncEntry)
384
+ let result
385
+ try {
386
+ result = await runAdvisorReview(agent, reviewType, {
387
+ onOutput: ctx.onOutput,
388
+ signal: ctx.signal,
389
+ // 整会话 usage(docs/cli/design/TUI.md §4):本评审的模型轮也计进状态行 —— 交父会话那枚 onUsage。
390
+ // ctx.callbacks 缺 onUsage(headless / 老调用方)⇒ null,runAdvisorReview 里不交(不吞读数也不造 0)。
391
+ onUsage: ctx.callbacks?.onUsage ?? null,
392
+ // 同步路径的绑定传递 = 同一逐笔值(异步路径走条目 `batchDoc` 字段,同值同形)。
393
+ batchDoc: launchBatchDoc,
394
+ }, designToken, documents, paths, reviewObject, designId)
395
+ } finally {
396
+ if (syncEntry) agent._syncAdvisors.delete(syncEntry.id)
397
+ }
331
398
 
332
399
  // B 启动拒绝(稳定前缀):拒发登记(同池满 / cap 款——不置 called、不耗轮次),
333
400
  // 可见报错照常返回(record-results 的 REFUSED 契约)。第 33 批:判定单点——同时供设计
@@ -346,6 +413,16 @@ export const advisorTool = {
346
413
  // retired — no mirror write here; the dispatch/spawn gates read the authoritative
347
414
  // multi-slot Map (+ slot-file re-read). Slotting moved into settleDesignReview
348
415
  // (shared with the async settle — fix #2).
416
+ // P0-2:陈旧结算不签发——与异步 `settleAdvisorRun` 的 stale 分支同形(剥 token 回显 +
417
+ // 前置句),并置 `run.stale` 让 record-results 不置覆盖位。
418
+ // 双向写:非 stale 也显式置 false——`run` 是实例级对象,上一轮残留的 true 会让
419
+ // record-results 的 `!run?.stale` 误判本轮未覆盖。
420
+ const staleNow = syncEntry ? reviewIsStale(agent, syncEntry) : false
421
+ resolved.run.stale = staleNow
422
+ if (staleNow) {
423
+ const stripped = stripDesignTokenEcho(String(result), designToken).trim()
424
+ return `评审目标已变更——token 未签发 (review target changed after launch — this review judged a stale state; no design token was issued — re-run the review on the current state)\n\n${stripped}`.trim()
425
+ }
349
426
  const incomplete = advisorIncompleteMarker(result)
350
427
  const settled = settleDesignReview(agent, resolved.run, designToken, result, { incomplete })
351
428
  // 撤计数(2026-09-18 用户裁定):原同步面“分类落账”随会话级计数器整体退场(零载体——F28③);
@@ -40,7 +40,7 @@ import { makeDecoder, sanitizeOutput } from "../tools/shared.mjs"
40
40
  import { killProcessTree } from "../tools/process-tree.mjs"
41
41
  // 过程档标记(TOOLS.md §6.28):后台径的结算摘要也是输出行——解析基准 = entry 记下的 spawn 局部 `cwd`。
42
42
  import { markProcessDocLines } from "../tools/process-doc-mark.mjs"
43
- import { buildBashEnv } from "../tools/bash.mjs"
43
+ import { buildBashEnv, wrapShellCommandForUtf8 } from "../tools/bash.mjs"
44
44
  import {
45
45
  bindChildController, buildChildSignal, carrierField, getAsyncPool, parkAsyncPending,
46
46
  tombstoneOf, wakeAsyncWaiters, writeTombstone,
@@ -122,8 +122,8 @@ export async function launchBgTask(parent, ctx, { command, timeout = null, shell
122
122
  assertPoolKeyFree(pool, id, "bash")
123
123
  const logPath = join(dir, `${Date.now()}-bash-${id}.log`)
124
124
  const cwd = ctx?.cwd ?? parent.cwd
125
- // UTF-8 码页前缀 = 同步径同款(win32 + 默认 shell);解码走 `makeDecoder`(同源)。
126
- const effectiveCommand = process.platform === "win32" && !shell ? `chcp 65001 >nul && ${command}` : command
125
+ // UTF-8 命令行包装单源(同步径同款:win32 cmd / powershell 统一保 UTF-8);解码走 `makeDecoder`(同源)。
126
+ const effectiveCommand = wrapShellCommandForUtf8(command, shell)
127
127
  const child = spawn(effectiveCommand, [], {
128
128
  cwd,
129
129
  shell: shell ?? true,
@@ -215,9 +215,12 @@ export async function createBatchRecord({ args, ctx, review, cwd, bases, onWritt
215
215
  let executorSessionId = null
216
216
  try { executorSessionId = (await import("../session-slots.mjs")).getSessionId() } catch { executorSessionId = null }
217
217
  mkdirSync(dirname(abs), { recursive: true })
218
- const writeRecord = (id) => {
218
+ const written = { title: null }
219
+ const writeRecord = (id, rowTitle) => {
220
+ const title = rowTitle ?? topic
221
+ written.title = title
219
222
  try {
220
- writeFileSync(abs, batchSkeleton({ date, topic, source, prev, baseSha, ledger: `#${id}`, board, mode }), { flag: "wx" })
223
+ writeFileSync(abs, batchSkeleton({ date, topic, source, prev, baseSha, ledger: `#${id}`, ledgerTitle: title, board, mode }), { flag: "wx" })
221
224
  } catch (e) {
222
225
  if (e?.code === "EEXIST") {
223
226
  throw new Error(`batch: create target already exists — refusing to overwrite an existing batch record (fail-closed, BR-20): ${raw}`)
@@ -272,7 +275,7 @@ export async function createBatchRecord({ args, ctx, review, cwd, bases, onWritt
272
275
  // 旧批没有起点时由首次绑定 spawn 记一次(`subagent-spawn.mjs`)——那里不回填更早的消息。
273
276
  recordBatchHistoryStart(ctx?.agent, abs, Date.now())
274
277
  // 建批这一笔也是 §1 写入(§4.24 回执面):回执带当前授权行 ⇒ 新批的默认态 `未授权` 当场读得出来。
275
- return `batch: created ${abs} — six-section skeleton written (§1 status line carries the gate-legal 「进行中」 placeholder); ledger row #${result.id} ${took} in the same call (row status = 在途 · task_book = ${taskBook} · trigger = 归批). header 台账 line filled (#${result.id} · ${board ?? "—"}).${goAheadReceiptLine(readFileSync(abs, "utf8"))}${sameFaceReceiptLine(result.sameFace)}${docRootHintLine(root)}`
278
+ return `batch: created ${abs} — six-section skeleton written (§1 status line carries the gate-legal 「进行中」 placeholder); ledger row #${result.id} ${took} in the same call (row status = 在途 · task_book = ${taskBook} · trigger = 归批). header 台账 line filled (#${result.id}${written.title ? `「${written.title}」` : ""} · ${board ?? "—"}).${goAheadReceiptLine(readFileSync(abs, "utf8"))}${sameFaceReceiptLine(result.sameFace)}${docRootHintLine(root)}`
276
279
  }
277
280
 
278
281
  /** 建批回执的权威文档层即时引导(非门、只读、失败静默):把项目的需求与设计层根路径送到动手那一帧。 */
@@ -374,9 +377,9 @@ export async function attachBatchRecord({ args, ctx, review, cwd, pickTarget, on
374
377
  /** `wrote` = 本笔**落过盘**(回档不回退——口径同 `batch-lifecycle.mjs` 的记账注释);`already` ⇒ 恒 `false`。 */
375
378
  const header = { id: null, line: null, already: false, wrote: false }
376
379
  /** 步 3(回调):把真实行号补进档头 `台账` 行。已在列表 ⇒ 零写(幂等);写盘成功才记 `_batchWrites`。 */
377
- const writeHeader = (id) => {
380
+ const writeHeader = (id, rowTitle) => {
378
381
  const current = readFileSync(abs, "utf8")
379
- const edited = appendLedgerNoToHeader(current, id)
382
+ const edited = appendLedgerNoToHeader(current, id, rowTitle ?? null)
380
383
  header.id = id
381
384
  header.line = edited.line
382
385
  if (edited.already) { header.already = true; return }
@@ -148,6 +148,37 @@ export function readBatchRecord({ args, ctx, review, pickTarget }) {
148
148
  return renderWindowReceipt(src, segRaw, args?.offset)
149
149
  }
150
150
 
151
+ /** §2 机读清单的标题行(`**受影响文件(机读清单)**` 或同名标题——前导 `#`、加粗标记与行内代码标记都剥掉,
152
+ * 尾部冒号忽略;与 doc-check 的 `plannedPathsOf` 同一条判据)。 */
153
+ const CHANGE_SET_HEADING = /^\s*(?:#{1,6}\s*)?(?:\*\*)?`?受影响文件(机读清单)`?(?:\*\*)?\s*:?\s*$/
154
+
155
+ /**
156
+ * 本批变更区(F36):从 §2 的机读清单表取第一列路径。
157
+ * 判据 = `docs/core/design/ADVISOR-GUARDS.md` §2.5 与 doc-check 的 `plannedPathsOf` 同源——
158
+ * 表头 `| 档 | 分拆方案 |`,第一列一个路径;标题缺失 / 表缺失 ⇒ 空数组(不猜)。
159
+ * @param {string} src — 批档全文
160
+ * @returns {string[]} 仓根相对路径(原样,不归一——读者按批档写的形去读)
161
+ */
162
+ function batchChangeSetFromSrc(src) {
163
+ const body = sectionBodyLines(src, 2) ?? []
164
+ const at = body.findIndex((line) => CHANGE_SET_HEADING.test(line))
165
+ if (at < 0) return []
166
+ const out = []
167
+ let inTable = false
168
+ for (let i = at + 1; i < body.length; i++) {
169
+ const line = body[i].trim()
170
+ if (!line.startsWith("|")) {
171
+ if (inTable) break
172
+ continue
173
+ }
174
+ inTable = true
175
+ const first = (line.split("|")[1] ?? "").trim()
176
+ if (!first || /^[-:]+$/.test(first) || first === "档") continue
177
+ out.push(first)
178
+ }
179
+ return out
180
+ }
181
+
151
182
  /**
152
183
  * 评审消息的批档简报块(`ADVISOR-GUARDS.md` §2.5):块标题 + 三件(解析后的绝对路径 ∥ 档头区 ∥ 逐段一行)
153
184
  * + 两句指令句(过程证据不是评审对象;检索面那句真话)。**只给路径与索引,不复制正文**——正文每轮重发、
@@ -172,10 +203,21 @@ export function buildBatchBrief(batchDoc, cwd) {
172
203
  } catch (e) {
173
204
  throw new Error(`buildBatchBrief: the bound batch record could not be read at ${abs} — ${e?.message ?? e}. The brief is built from the record itself, never from memory: fix the binding or restore the record before a review is briefed on it.`)
174
205
  }
206
+ const changeSet = batchChangeSetFromSrc(src)
207
+ const changeSetBlock = changeSet.length > 0
208
+ ? [
209
+ "",
210
+ "## This batch's change set (F36)",
211
+ "The files this batch changes. For a document that is both in the review list and in this list, judge the parts this batch touched; the rest of that document is existing content, not this batch's work:",
212
+ ...changeSet.map((p) => `- ${p}`),
213
+ "",
214
+ ]
215
+ : []
175
216
  return [
176
217
  "## Batch record",
177
218
  `${abs} — read this file in full.`,
178
219
  batchRecordIndex(src),
220
+ ...changeSetBlock,
179
221
  "",
180
222
  "The batch record is process evidence, not a review target: §2 is the task book the work must satisfy, §1 is the ruling on it and §3 is the previous round's record — none of the three is a review basis. When you read it, the search face applies: `grep` / `glob` / `ls` / `tree` omit process documents unless you pass `includeProcessDocs: true`, and an empty default search does not mean the record is absent.",
181
223
  "",
@@ -58,8 +58,10 @@ function sanitizeText(text, dropStamp) {
58
58
  return kept.join("\n")
59
59
  }
60
60
 
61
- /** 段尾定位 + 插入(append-only;仅 §3 盖工具轮次戳)。 */
62
- function insertIntoSection(src, seg, text, blockLead = "") {
61
+ /** 段尾定位 + 插入(append-only;仅 §3 盖工具轮次戳)。
62
+ * `roundLabel` = 戳里的写入者身份:评审实例写 ⇒ 「评审子代理」,depth-0 主 agent 代记结论块 ⇒ 「主 agent」。
63
+ * 留着硬编码会把主 agent 写的块标成评审写的——作者身份写错比不写更坏。 */
64
+ function insertIntoSection(src, seg, text, blockLead = "", roundLabel = "评审子代理") {
63
65
  const hdr = sectionHeaderRe(seg).exec(src)
64
66
  if (!hdr) throw new Error(missingSectionError(seg))
65
67
  const nextRe = /^## §\d/gm
@@ -67,7 +69,7 @@ function insertIntoSection(src, seg, text, blockLead = "") {
67
69
  const next = nextRe.exec(src)
68
70
  const endIdx = next ? next.index : src.length
69
71
  const roundN = seg === 3 ? nextRoundNumber(src, 3) : 0
70
- const stamp = seg === 3 ? `### 轮次 ${roundN}(评审子代理)\n\n` + (blockLead ? `${blockLead}\n\n` : "") : ""
72
+ const stamp = seg === 3 ? `### 轮次 ${roundN}(${roundLabel})\n\n` + (blockLead ? `${blockLead}\n\n` : "") : ""
71
73
  const payload = stamp + text
72
74
  const before = src.slice(0, endIdx)
73
75
  const after = src.slice(endIdx)
@@ -95,11 +97,11 @@ function assertWritableSegment({ rawSegment, depth0, engineering, ownSeg, op })
95
97
  if (n === null) {
96
98
  if (depth0) {
97
99
  if (op === "edit") {
98
- throw new Error(`batch: unknown segment ${JSON.stringify(rawSegment ?? null)} — depth-0 edit rewrites a section of the in-flight record that you author (${engineering ? "§1/§4/§6" : "§1/§2/§4/§5/§6"} — pass the section number you write, e.g. "§4"). Nothing was written.`)
100
+ throw new Error(`batch: unknown segment ${JSON.stringify(rawSegment ?? null)} — depth-0 edit rewrites a section of the in-flight record that you author (${engineering ? "§1/§4/§6" : "§1/§2/§3/§4/§5/§6"} — pass the section number you write, e.g. "§4"). Nothing was written.`)
99
101
  }
100
102
  throw new Error(engineering
101
103
  ? `batch: unknown segment ${JSON.stringify(rawSegment ?? null)} — depth-0 append writes §1/§4/§6 of the in-flight record (pass the section number you write, e.g. "§4").`
102
- : `batch: unknown segment ${JSON.stringify(rawSegment ?? null)} — in normal mode depth-0 append writes §1/§2/§4/§5/§6 of the in-flight record (pass the section number you write, e.g. "§4").`)
104
+ : `batch: unknown segment ${JSON.stringify(rawSegment ?? null)} — in normal mode depth-0 append writes §1/§2/§3/§4/§5/§6 of the in-flight record (pass the section number you write, e.g. "§4").`)
103
105
  }
104
106
  throw new Error(`batch_segment: unknown segment ${JSON.stringify(rawSegment ?? null)} — pass the section number you write (e.g. "§${ownSeg}").`)
105
107
  }
@@ -109,11 +111,11 @@ function assertWritableSegment({ rawSegment, depth0, engineering, ownSeg, op })
109
111
  if (op === "edit") {
110
112
  throw new Error(engineering
111
113
  ? `batch: §${n} is not yours to write — in engineering mode depth-0 edit rewrites §1/§4/§6 (一段一作者: §2 = eng-designer, §3 = design review, §5 = eng-coder). Nothing was written.`
112
- : `batch: §${n} is not yours to write — in normal mode depth-0 edit rewrites §1/§2/§4/§5/§6 (一段一作者: §3 = design review only). Nothing was written.`)
114
+ : `batch: §${n} is not yours to write — in normal mode depth-0 edit rewrites §1/§2/§3/§4/§5/§6 (no one-section-one-author rule here; §3 = 评审结论块,主 agent 代记). Nothing was written.`)
113
115
  }
114
116
  throw new Error(engineering
115
117
  ? `batch: §${n} is not yours to write — depth-0 append writes §1/§4/§6 only (一段一作者: §2 = eng-designer, §3 = design review, §5 = eng-coder).`
116
- : `batch: §${n} is not yours to write — in normal mode depth-0 append writes §1/§2/§4/§5/§6 (一段一作者: §3 = design review only). Nothing was written.`)
118
+ : `batch: §${n} is not yours to write — in normal mode depth-0 append writes §1/§2/§3/§4/§5/§6 (no one-section-one-author rule here; §3 = 评审结论块,主 agent 代记). Nothing was written.`)
117
119
  }
118
120
  } else if (n !== ownSeg) {
119
121
  throw new Error(`batch_segment: §${n} is not yours to write — this caller writes §${ownSeg} only (一段一作者: eng-designer → §2, design review → §3, eng-coder → §5).`)
@@ -148,8 +150,13 @@ function readOpenRecord(abs) {
148
150
 
149
151
  // ─── 纯内存段变换(单笔 append / edit 与批量 update 共用单源)───────────────
150
152
 
153
+ /** §3 轮次戳里的写入者标签:depth-0 主 agent 代记 ⇒ 「主 agent」,其余(评审实例)⇒ 「评审子代理」。 */
154
+ function roundLabelFor(depth0) {
155
+ return depth0 ? "主 agent" : "评审子代理"
156
+ }
157
+
151
158
  /** 对内存中的记录文本应用一笔 `append`(含全部校验、净化、§5/§3 门与状态行被动写)。 */
152
- function applyAppendInMemory(src, { n, text, engineering, date, checkResidues = true }) {
159
+ function applyAppendInMemory(src, { n, text, engineering, date, checkResidues = true, roundLabel = "评审子代理" }) {
153
160
  if (typeof text !== "string") {
154
161
  throw new Error("batch_segment: text must be a string (the markdown to append).")
155
162
  }
@@ -172,7 +179,7 @@ function applyAppendInMemory(src, { n, text, engineering, date, checkResidues =
172
179
  if (gap === "无裁定行" || gap === "两者同携") throw new Error(SECTION3_VERDICT_GAP_ERROR)
173
180
  }
174
181
  const plan = statusResetPlan(src, n, body, date) ?? statusPassPlan(src, n, body, date)
175
- const { written: inserted, roundN } = insertIntoSection(src, n, body, plan?.traceLine ?? "")
182
+ const { written: inserted, roundN } = insertIntoSection(src, n, body, plan?.traceLine ?? "", roundLabel)
176
183
  const done = plan ? null : statusDonePlan(inserted, n)
177
184
  const written = plan
178
185
  ? updateSectionStatusLine(inserted, n, plan.statusValue)
@@ -238,15 +245,16 @@ export function appendBatchRecord({ args, ctx, review, reviewTrack, batchDoc, on
238
245
  const n = assertWritableSegment({ rawSegment: args?.segment, depth0, engineering, ownSeg: seg, op: "append" })
239
246
  const abs = resolveWriteTarget({ args, depth0, cwd, batchDoc })
240
247
  const src = readOpenRecord(abs)
248
+ const label = roundLabelFor(depth0)
241
249
  const { written, bodyLen, roundN, done } = applyAppendInMemory(src, {
242
- n, text: args?.text, engineering, date: todayLocal(),
250
+ n, text: args?.text, engineering, date: todayLocal(), roundLabel: label,
243
251
  })
244
252
  const gate = engineering ? runBatchGate({ abs, cwd, agent, scope: "writer", pending: { section: n, body: written } }) : null
245
253
  if (gate?.state === "refused") throw new Error(gateRefusalMessage(gate, "append"))
246
254
  writeFileSync(abs, written)
247
255
  agent._batchWrites = (agent._batchWrites ?? 0) + 1
248
256
  onWritten?.(agent, abs)
249
- return `batch_segment: appended ${bodyLen} characters to §${n} of the batch record${roundN ? ` (### 轮次 ${roundN}(评审子代理))` : ""}.${done ? ` §${n} 状态行 = ${done.statusValue}(同笔置位——不另调 status).` : ""}${n === 1 ? `${goAheadReceiptLine(written)}${goAheadEndLine(src, written)}` : ""}${gateReceiptLine(gate)}`
257
+ return `batch_segment: appended ${bodyLen} characters to §${n} of the batch record${roundN ? ` (### 轮次 ${roundN}(${label}))` : ""}.${done ? ` §${n} 状态行 = ${done.statusValue}(同笔置位——不另调 status).` : ""}${n === 1 ? `${goAheadReceiptLine(written)}${goAheadEndLine(src, written)}` : ""}${gateReceiptLine(gate)}`
250
258
  }
251
259
 
252
260
  /** 单段就地改(action=edit)。 */
@@ -331,7 +339,7 @@ export function updateBatchRecord({ args, ctx, review, reviewTrack, batchDoc, on
331
339
  try {
332
340
  n = assertWritableSegment({ rawSegment: entry.segment, depth0, engineering, ownSeg: own, op })
333
341
  if (op === "append") {
334
- const res = applyAppendInMemory(cur, { n, text: entry.text, engineering, date, checkResidues: false })
342
+ const res = applyAppendInMemory(cur, { n, text: entry.text, engineering, date, checkResidues: false, roundLabel: roundLabelFor(depth0) })
335
343
  cur = res.written
336
344
  summaries.push(`append §${n} +${res.bodyLen} chars${res.roundN ? ` (轮次 ${res.roundN})` : ""}`)
337
345
  if (res.done) autoStatuses.set(n, res.done.statusValue)
@@ -85,11 +85,13 @@ export function sectionThreeDesignTrackError(prefix) {
85
85
  return `${prefix}: §3 is closed to this caller — in engineering mode the design-track round block is written by the settlement: the tool stamps the round heading, adds the settlement header line and the review's report verbatim, in the same stroke that decides the token. §3 is read-only for every tool channel on that track (a block you add would sit beside the settlement's and the record would read as two rounds). The code track and normal mode keep the §3 channel. Nothing was written.`
86
86
  }
87
87
 
88
- /** depth-0 段白名单(§4.16——**模式键两集**;工程面判定字面逐字保持、普通面新增):
89
- * append:工程 = §1/§4/§6 ∥ 普通 = §1/§2/§4/§5/§6(§2 = 设计师席并入主 agent;§5 = 直做实施记录);
90
- * status:工程 = §1 ∥ 普通 = §1/§2/§5(写域仍「调用者自己段」;`segment` 缺省 = §1)。 */
88
+ /** depth-0 段白名单(§4.16——**模式键两集**;工程面「一段一作者」字面逐字保持、普通面不再受该约束):
89
+ * append:工程 = §1/§4/§6 ∥ 普通 = §1/§2/§3/§4/§5/§6(§2 = 设计师席并入主 agent;§3 = 代码/设计评审结论块由主 agent 代记;§5 = 直做实施记录);
90
+ * status:工程 = §1 ∥ 普通 = §1/§2/§5(写域仍「调用者自己段」;`segment` 缺省 = §1)。
91
+ * 普通模式纳入 §3 的理由:工程模式一句一作者是为了让设计评审的结论块只能由评审它的人写;普通模式没有设计席与实施席的硬分权,
92
+ * 评审报告回的结论块本来就由主 agent 落档,再拦一道只会逼出「把结论写进 §5」这笔歪账。*/
91
93
  export const DEPTH0_SEGMENTS = Object.freeze({
92
- append: Object.freeze({ engineering: Object.freeze([1, 4, 6]), normal: Object.freeze([1, 2, 4, 5, 6]) }),
94
+ append: Object.freeze({ engineering: Object.freeze([1, 4, 6]), normal: Object.freeze([1, 2, 3, 4, 5, 6]) }),
93
95
  status: Object.freeze({ engineering: Object.freeze([1]), normal: Object.freeze([1, 2, 5]) }),
94
96
  })
95
97