@thincoder/core 0.11.2 → 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 (198) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/advisor/compaction.mjs +7 -5
  3. package/advisor/history.mjs +24 -11
  4. package/advisor/loop.mjs +13 -8
  5. package/advisor/messages.mjs +72 -8
  6. package/advisor/run.mjs +24 -13
  7. package/advisor.mjs +7 -3
  8. package/agent/chat-call.mjs +14 -9
  9. package/agent/completion.mjs +28 -40
  10. package/agent/continue-decision.mjs +14 -8
  11. package/agent/digest-account.mjs +133 -59
  12. package/agent/dispatch-run.mjs +1 -1
  13. package/agent/dispatch.mjs +2 -1
  14. package/agent/family-tools.mjs +12 -13
  15. package/agent/helpers.mjs +17 -72
  16. package/agent/image-heal.mjs +18 -4
  17. package/agent/post-turn.mjs +13 -26
  18. package/agent/record-results.mjs +21 -6
  19. package/agent/run-stages.mjs +72 -37
  20. package/agent/run-start.mjs +148 -113
  21. package/agent/setup-reminders.mjs +187 -91
  22. package/agent/setup.mjs +204 -138
  23. package/agent/spawn-child.mjs +2 -2
  24. package/agent/suspension.mjs +43 -15
  25. package/agent/timers.mjs +4 -1
  26. package/agent/turn-domain-text.mjs +105 -0
  27. package/agent/turn-loop.mjs +54 -22
  28. package/agent/turn-projection.mjs +127 -227
  29. package/agent/turn-tool-process.mjs +32 -37
  30. package/agent-tools/advisor-async.mjs +6 -3
  31. package/agent-tools/advisor-launch.mjs +5 -5
  32. package/agent-tools/advisor.mjs +1 -1
  33. package/agent-tools/async-discard.mjs +7 -2
  34. package/agent-tools/async-settle.mjs +18 -12
  35. package/agent-tools/bash-async.mjs +5 -2
  36. package/agent-tools/batch-closeout.mjs +12 -62
  37. package/agent-tools/batch-ledger-bind.mjs +19 -8
  38. package/agent-tools/batch-lifecycle.mjs +37 -11
  39. package/agent-tools/batch-read.mjs +151 -4
  40. package/agent-tools/batch-record-write.mjs +5 -5
  41. package/agent-tools/batch-segment-vocab.mjs +84 -4
  42. package/agent-tools/batch-skeleton.mjs +18 -14
  43. package/agent-tools/batch-supersede.mjs +1 -1
  44. package/agent-tools/batch-tier-gate.mjs +36 -119
  45. package/agent-tools/batch.mjs +30 -20
  46. package/agent-tools/browser-async.mjs +5 -2
  47. package/agent-tools/consult.mjs +10 -7
  48. package/agent-tools/context.mjs +47 -31
  49. package/agent-tools/digest-budget.mjs +10 -9
  50. package/agent-tools/eng.mjs +3 -4
  51. package/agent-tools/escalate-async.mjs +3 -3
  52. package/agent-tools/goal.mjs +5 -2
  53. package/agent-tools/judge-domain.mjs +347 -0
  54. package/agent-tools/manifest.mjs +2 -2
  55. package/agent-tools/parent-channel.mjs +6 -3
  56. package/agent-tools/plan.mjs +11 -10
  57. package/agent-tools/review-facts.mjs +9 -3
  58. package/agent-tools/skill.mjs +7 -8
  59. package/agent-tools/spawn-gates.mjs +5 -16
  60. package/agent-tools/ssh-session.mjs +6 -3
  61. package/agent-tools/ssh-transfer.mjs +1 -1
  62. package/agent-tools/subagent-actions.mjs +2 -2
  63. package/agent-tools/subagent-async.mjs +11 -8
  64. package/agent-tools/subagent-scheduler.mjs +9 -9
  65. package/agent-tools/subagent-spawn.mjs +2 -2
  66. package/agent-tools/subagent.mjs +5 -18
  67. package/agent-tools/task.mjs +0 -8
  68. package/agent.mjs +15 -15
  69. package/auto-think.mjs +5 -2
  70. package/compaction-work-state.mjs +230 -0
  71. package/compress-form.mjs +41 -6
  72. package/config-defaults.mjs +5 -2
  73. package/config.mjs +53 -17
  74. package/context-degrade.mjs +79 -48
  75. package/context-echo.mjs +6 -26
  76. package/context-push.mjs +328 -31
  77. package/context.mjs +203 -141
  78. package/conventions.mjs +1 -1
  79. package/declaration.mjs +95 -17
  80. package/escape.mjs +6 -5
  81. package/explore-distill.mjs +35 -8
  82. package/generate-title.mjs +10 -1
  83. package/knowledge/prompt-resources.md +5 -1
  84. package/ledger-tools.mjs +50 -50
  85. package/ledger-write-ops.mjs +43 -16
  86. package/memory/docs.mjs +51 -15
  87. package/memory/file-list.mjs +6 -0
  88. package/model-specs.mjs +87 -21
  89. package/origin-guard.mjs +190 -0
  90. package/package.json +1 -1
  91. package/prompt-files.mjs +33 -11
  92. package/prompt-overlays.mjs +12 -5
  93. package/prompts/advisor-design.md +55 -36
  94. package/prompts/advisor-round1.md +18 -7
  95. package/prompts/advisor-round2.md +18 -7
  96. package/prompts/advisor-round3.md +18 -7
  97. package/prompts/common.md +89 -51
  98. package/prompts/consult-base.md +2 -3
  99. package/prompts/discipline-engineering.md +474 -440
  100. package/prompts/discipline-normal.md +107 -31
  101. package/prompts/knowledge/business-gates.md +23 -15
  102. package/prompts/knowledge/decision-quality.md +16 -18
  103. package/prompts/knowledge/doc-lookup.md +22 -27
  104. package/prompts/knowledge/document-writing.md +31 -49
  105. package/prompts/knowledge/documentation-evaluation.md +37 -45
  106. package/prompts/knowledge/evidence-discipline.md +36 -55
  107. package/prompts/knowledge/normal-coding-workflow.md +27 -21
  108. package/prompts/knowledge/normal-delivery-collaboration.md +33 -17
  109. package/prompts/knowledge/normal-work-management.md +10 -7
  110. package/prompts/knowledge/product-security.md +22 -17
  111. package/prompts/knowledge/project-records.md +63 -52
  112. package/prompts/knowledge/tool-apply-patch.md +12 -13
  113. package/prompts/knowledge/tool-bash.md +13 -4
  114. package/prompts/knowledge/tool-batch-eng-coder.md +13 -6
  115. package/prompts/knowledge/tool-batch-eng-designer.md +14 -6
  116. package/prompts/knowledge/tool-batch-review.md +12 -6
  117. package/prompts/knowledge/tool-batch.md +76 -62
  118. package/prompts/knowledge/tool-browser.md +45 -34
  119. package/prompts/knowledge/tool-context.md +2 -2
  120. package/prompts/knowledge/tool-delete.md +5 -1
  121. package/prompts/knowledge/tool-doc-check.md +25 -24
  122. package/prompts/knowledge/tool-doc-graph-read.md +3 -3
  123. package/prompts/knowledge/tool-doc-graph.md +15 -15
  124. package/prompts/knowledge/tool-edit.md +26 -23
  125. package/prompts/knowledge/tool-execute.md +9 -4
  126. package/prompts/knowledge/tool-fetch.md +7 -1
  127. package/prompts/knowledge/tool-file-ops.md +6 -1
  128. package/prompts/knowledge/tool-git-read.md +3 -1
  129. package/prompts/knowledge/tool-git.md +1 -1
  130. package/prompts/knowledge/tool-glob.md +3 -1
  131. package/prompts/knowledge/tool-grep.md +5 -2
  132. package/prompts/knowledge/tool-hashline-edit.md +4 -2
  133. package/prompts/knowledge/tool-insert-after.md +3 -1
  134. package/prompts/knowledge/tool-ledger-read.md +6 -13
  135. package/prompts/knowledge/tool-ledger.md +14 -10
  136. package/prompts/knowledge/tool-ls.md +2 -0
  137. package/prompts/knowledge/tool-manifest.md +10 -7
  138. package/prompts/knowledge/tool-memory.md +15 -11
  139. package/prompts/knowledge/tool-operations.md +59 -71
  140. package/prompts/knowledge/tool-plan.md +1 -2
  141. package/prompts/knowledge/tool-process.md +1 -1
  142. package/prompts/knowledge/tool-read-history.md +6 -7
  143. package/prompts/knowledge/tool-read.md +1 -0
  144. package/prompts/knowledge/tool-settings.md +6 -7
  145. package/prompts/knowledge/tool-ssh.md +37 -15
  146. package/prompts/knowledge/tool-subagent.md +37 -39
  147. package/prompts/knowledge/tool-task.md +3 -1
  148. package/prompts/knowledge/tool-team-ledger.md +5 -1
  149. package/prompts/knowledge/tool-tree.md +2 -0
  150. package/prompts/knowledge/tool-wait-for.md +16 -16
  151. package/prompts/knowledge/tool-write.md +4 -1
  152. package/prompts/knowledge/upstream-protocol.md +39 -37
  153. package/prompts/persona-coder.md +1 -3
  154. package/prompts/persona-eng-coder.md +5 -5
  155. package/prompts/persona-eng-designer.md +34 -17
  156. package/prompts/persona-engineering.md +532 -501
  157. package/prompts/persona-explore.md +0 -2
  158. package/prompts/persona-normal.md +17 -9
  159. package/prompts/persona-plan.md +0 -2
  160. package/prompts/persona-tester.md +0 -2
  161. package/prompts/subagent-base.md +0 -2
  162. package/provider/anthropic.mjs +4 -2
  163. package/provider/core.mjs +5 -3
  164. package/provider/errors.mjs +41 -7
  165. package/provider/google.mjs +5 -3
  166. package/provider/reasoning-echo.mjs +16 -0
  167. package/provider/responses.mjs +4 -2
  168. package/provider/sse.mjs +11 -6
  169. package/rules.mjs +11 -10
  170. package/session-lifecycle.mjs +115 -81
  171. package/session-slot-write.mjs +1 -1
  172. package/session.mjs +23 -20
  173. package/shell-identity.mjs +129 -22
  174. package/skip-dirs.mjs +24 -0
  175. package/team-ledger.mjs +22 -22
  176. package/text-budget.mjs +1 -1
  177. package/think-off.mjs +27 -0
  178. package/token-ttl.mjs +1 -1
  179. package/token-window.mjs +278 -88
  180. package/tool-docs/bash.md +0 -2
  181. package/tool-docs/consult_start.md +2 -2
  182. package/tool-docs/consult_stop.md +2 -2
  183. package/tools/browser.mjs +8 -8
  184. package/tools/execute.mjs +2 -2
  185. package/tools/file.mjs +17 -11
  186. package/tools/git.mjs +12 -12
  187. package/tools/ops.mjs +2 -2
  188. package/tools/patch.mjs +1 -1
  189. package/tools/process-doc-mark.mjs +33 -4
  190. package/tools/repomap.mjs +25 -3
  191. package/tools/search.mjs +74 -26
  192. package/tools/shared.mjs +4 -3
  193. package/tools/ssh.mjs +5 -5
  194. package/tools/tree.mjs +32 -10
  195. package/tools/web-deepseek.mjs +1 -1
  196. package/tools/web.mjs +2 -2
  197. package/tools/write-gate-params.mjs +3 -3
  198. package/window-policy.mjs +118 -78
@@ -64,7 +64,7 @@ function openDesignRun(agent, key) {
64
64
  }
65
65
 
66
66
  /**
67
- * Resolve the review instance a launch continues (AGENT-LOOP-ASYNC-POOL.md §6.10 ③ — per-review
67
+ * Resolve the review instance a launch continues (AGENT-LOOP-ASYNC-POOL.md §5「后台评审」 ③ — per-review
68
68
  * rounds/prior; reviewId = designId for design reviews, a random id for code).
69
69
  * - design: continue the OPEN instance of the same document set (fix rounds of
70
70
  * a review thread keep its designId and its round/prior); none → new instance.
@@ -89,7 +89,7 @@ export function resolveAdvisorLaunch(agent, reviewType, { documents = null } = {
89
89
  // the same id (no slot residue — T14: the old token is then rejected at
90
90
  // the gate); old slots die at TTL only, kept as the fail-safe fallback.
91
91
  const prior = [...runs.values()].reverse().find((r) => r.reviewType === "design" && r.docSetKey === key)
92
- // #863 实例回收(§6.10):同 docSetKey 保最新一条 closed(= prior——F2h 只取 newest,语义零变);
92
+ // #863 实例回收(AGENT-LOOP-ASYNC-POOL.md §3「分域池」):同 docSetKey 保最新一条 closed(= prior——F2h 只取 newest,语义零变);
93
93
  // 余者去重回收(实例随删释放——closed 零消费面)。
94
94
  for (const r of [...runs.values()]) {
95
95
  if (r !== prior && r.reviewType === "design" && !r.open && r.docSetKey === key) runs.delete(r.reviewId)
@@ -107,7 +107,7 @@ export function resolveAdvisorLaunch(agent, reviewType, { documents = null } = {
107
107
  } else {
108
108
  run = openCodeRun(agent)
109
109
  if (!run) {
110
- // #863 实例回收(§6.10):新 code 实例创建 ⇒ closed 实例清除(openCodeRun 仅取 open——零消费)。
110
+ // #863 实例回收(AGENT-LOOP-ASYNC-POOL.md §3「分域池」):新 code 实例创建 ⇒ closed 实例清除(openCodeRun 仅取 open——零消费)。
111
111
  for (const r of [...runs.values()]) {
112
112
  if (r.reviewType === "code" && !r.open) runs.delete(r.reviewId)
113
113
  }
@@ -139,7 +139,7 @@ export function effectiveAdvisorRound(agent) {
139
139
 
140
140
  export const ADVISOR_POOL_LIMIT = 4
141
141
 
142
- /** AGENT-LOOP-ASYNC-POOL.md §6.10 advisor 池生效上限(纯——读 agent.poolLimits.advisor——合法 ≥1 整数生效——
142
+ /** AGENT-LOOP-ASYNC-POOL.md §3「分域池」 advisor 池生效上限(纯——读 agent.poolLimits.advisor——合法 ≥1 整数生效——
143
143
  * 非法/缺省回退 ADVISOR_POOL_LIMIT——与 subagent 域 resolvePoolLimits 独立不共享
144
144
  * (subagent 两键表不含本键——键表语义不同——POOL-CONFIG-UNIFIED F-2))。 */
145
145
  export function resolveAdvisorPoolLimit(raw) {
@@ -152,7 +152,7 @@ export function resolveAdvisorPoolLimit(raw) {
152
152
  export function advisorPoolLimitFor(agent) {
153
153
  return resolveAdvisorPoolLimit(agent?.config?.agent?.poolLimits)
154
154
  }
155
- /** §6.10 同 scope 守卫(F-5——用户裁①):同 reviewType+scope 有 running 评审 → true
155
+ /** AGENT-LOOP-ASYNC-POOL.md §3「分域池」 同 scope 守卫(F-5——用户裁①):同 reviewType+scope 有 running 评审 → true
156
156
  * (拒——running 并行多实例歧义放大——settled 续跑语义不变)。design scope = 文档集键
157
157
  * (docSetKey);code = 单 code 线程(记录不记路径键——与 openCodeRun 语义一致)。
158
158
  * 与池容量守卫独立:容量 = 全局 ≤N——scope = 同 scope ≤1——两关都过才启动。 */
@@ -106,7 +106,7 @@ export const advisorTool = {
106
106
  properties: {
107
107
  type: { type: "string", description: "Review type as declared by the caller (design/code)" },
108
108
  target: { type: "string", description: "Review target — document + section, or file(s)" },
109
- status: { type: "string", description: "Object state: 待评审 / 已批准 / 已实现 (pending-review / approved / implemented)" },
109
+ status: { type: "string", description: "Object state: pending-review / approved / implemented" },
110
110
  reason: { type: "string", description: "Why this review runs: user-initiated / delivery verification" },
111
111
  exclude: { type: "string", description: "Explicit exclusion list — approved/implemented items NOT in this review" },
112
112
  },
@@ -42,7 +42,7 @@
42
42
  * `../log.mjs`——叶子向、无环。
43
43
  */
44
44
  import { carrierField, getAsyncPool, parentAborted, writeTombstone } from "./async-settle.mjs"
45
- import { pushReal } from "../context.mjs"
45
+ import { pushInject, pushRecord } from "../context.mjs"
46
46
  import { escapeXml } from "../agent/helpers.mjs"
47
47
  import { logEvent } from "../log.mjs"
48
48
  // #9(后台 bash 任务族——收尾档②):杀单点(树杀)经 `bash-async.mjs` 落面。
@@ -127,7 +127,12 @@ function discardRole(parent, spec, ctx) {
127
127
  // `pushReal`(机器 + 人读双线);**history 数组本体形**(VSC 挂起载体——池挂数组)无注入目标 ⇒
128
128
  // 跳过(与对侧 VSC copy 的 `parent?.history` 守卫同判;§6.20.1「carrier 形无注入目标」先例)
129
129
  // ——墓碑与 `ev:discarded` 照发,仅模型可见提醒缺席(数组形无人读线可达面)。
130
- if (parent?.history) pushReal(parent, { role: "user", content: spec.reminder(out.discarded.length, escapeXml(list)) })
130
+ if (parent?.history) {
131
+ const msg = { role: "user", content: spec.reminder(out.discarded.length, escapeXml(list)) }
132
+ // B 段:一次性投递走待发队,持久写入只落人读线。
133
+ pushInject(parent, msg)
134
+ pushRecord(parent, msg)
135
+ }
131
136
  logEvent("ev:discarded", { n: out.discarded.length, ids: out.discarded.map((d) => `${d.role}#${d.id}`).join(", ") })
132
137
  return out
133
138
  }
@@ -23,7 +23,7 @@
23
23
  * escalate-async/consult)单向 import 本模块;scheduler 反向 import 本模块(getAsyncPool)
24
24
  * 与既有 scheduler ↔ subagent-async 同款惰性环——无求值期依赖。
25
25
  *
26
- * S1 续轮第二批(2026-09-14——异步机械族 VSC 侧并入,AGENT-LOOP.md §2.3 载体口径):
26
+ * S1 续轮第二批(2026-09-14——异步机械族 VSC 侧并入,AGENT-LOOP.md §9.1 载体字段):
27
27
  * - #94 载体吸收:`carrierField`(父对象字段优先 / 回退 `history`——VSC 形跨 runAgent
28
28
  * 载体)+ 墓碑三函数单点(`writeTombstoneTo` / `writeTombstone` / `tombstoneOf`,
29
29
  * 原核内 3 处 inline 写全部收口);`getAsyncPool` / `parkAsyncPending` 走吸收。
@@ -31,19 +31,19 @@
31
31
  * `bindChildController` = 链结单点(原 4 处逐字同构,interrupt 不逐链中止)。
32
32
  */
33
33
  import { logEvent, errText } from "../log.mjs"
34
- import { pushReal } from "../context.mjs"
34
+ import { pushInject, pushRecord } from "../context.mjs"
35
35
  import { escapeXml } from "../agent/helpers.mjs"
36
36
  import { TURN_CAP_MARK } from "../agent/spawn-child.mjs"
37
37
  import { dependentLabels, maybeRefillAsync, refreshQueuedTokens } from "./subagent-scheduler.mjs"
38
38
  // ED-4(2026-09-16):advisor 排队补位——同 scheduler ↔ 本模块惰性环(函数声明提升——无求值期依赖)
39
39
  import { refillAdvisorQueue } from "./advisor-async.mjs"
40
40
 
41
- // ─── #94 载体吸收(VSC 侧并入——AGENT-LOOP.md §2.3 载体五字段)───────────────
41
+ // ─── #94 载体吸收(VSC 侧并入——AGENT-LOOP.md §9.1 载体字段)───────────────
42
42
 
43
43
  /**
44
44
  * 载体字段读取吸收(#94——「VSC 的跨 runAgent 存活载体面按核内结构归一」):
45
- * §2.3 载体口径 = `_asyncSubagents` · `_asyncAdvisors` · `_consultSessions` ·
46
- * `_pendingAsyncResults` · `_suspended`(AGENT-LOOP.md §2.3 seam 表);#9 后台任务池
45
+ * §9.1 载体口径 = `_asyncSubagents` · `_asyncAdvisors` · `_consultSessions` ·
46
+ * `_pendingAsyncResults` · `_suspended`(AGENT-LOOP.md §9.1);#9 后台任务池
47
47
  * `_bgTasks` 同列(写侧父字段 + 借用/别名 history——见 `bash-async.mjs` `ensureBgPool`)。
48
48
  * CLI 形:字段直接挂 agent(跨 run 存活);VSC 形:字段挂 depth-0 `history`
49
49
  * (agent per-run 重建——run 起始把 history 容器绑到 agent 字段,绑定不变式)。
@@ -171,7 +171,7 @@ export function buildChildSignal(parent, ctx) {
171
171
  // ─── D3 settle 共享 helper ───────────────────────────────────────────────────
172
172
 
173
173
  /**
174
- * AGENT-LOOP.md §6.15 消化窗口持有释放(TUI-OOM-ROOTCAUSE——D-SM2 表 2 候选 1):注入完成后置空条目
174
+ * AGENT-LOOP.md §9 消化窗口持有释放(TUI-OOM-ROOTCAUSE——D-SM2 表 2 候选 1):注入完成后置空条目
175
175
  * 对子代理对象的引用(`childAgent`/`report`——条目前此从不显式释放,挂起期 = 分钟级驻留)。
176
176
  * 幂等(重入不抛);池内/挂起未消化窗口语义零变(settle 时刻不释放——表 2 候选 2 否决:
177
177
  * status/observe 在窗口内仍读 child 摘要)。三消费点(回合尾收集 / run 起始 pending 注入 /
@@ -267,25 +267,31 @@ export function settleAsyncEntry(parent, entry, opts = {}) {
267
267
  ctx?.callbacks?.onToken?.(`${entry.relayPrefix}⟦ev⟧stopped\x1e0\x1e0\x1estopped\x1e`)
268
268
  if (role === "advisor") {
269
269
  // ②-6b:评审取消——token 未签发提醒(settleAdvisorRun 不消费预算)。
270
- pushReal(parent, {
270
+ const msg300 = {
271
271
  role: "user",
272
272
  content: `[System reminder: async advisor review #${escapeXml(String(entry.id))} cancelled — the review did not settle; token not issued (评审已取消——token 未签发)]`,
273
- })
273
+ }
274
+ pushInject(parent, msg300)
275
+ pushRecord(parent, msg300)
274
276
  } else if (role === "escalate") {
275
- pushReal(parent, {
277
+ const msg275 = {
276
278
  role: "user",
277
279
  content: `[System reminder: async escalate #${entry.id} (${entry.tag}) cancelled by user — partial changes not merged/audited]`,
278
- })
280
+ }
281
+ pushInject(parent, msg275)
282
+ pushRecord(parent, msg275)
279
283
  } else {
280
284
  // §6.9 D-SD5:running 依赖取消——提醒列出依赖者(供模型决策)。
281
285
  const dependents = dependentLabels(parent, String(entry.id))
282
286
  const autoNote = parent.autoApprove
283
287
  ? " — AUTO session: they auto-start on slot availability (round2 #3)"
284
288
  : " — they stay queued until you cancel them or an AUTO session starts them"
285
- pushReal(parent, {
289
+ const msg285 = {
286
290
  role: "user",
287
291
  content: `[System reminder: subagent ${escapeXml(role)}#${entry.id} cancelled by user — partial changes not merged/audited${dependents.length > 0 ? `; queued dependents ${dependents.join(", ")} marked "dependency cancelled"${autoNote}` : ""}]`,
288
- })
292
+ }
293
+ pushInject(parent, msg285)
294
+ pushRecord(parent, msg285)
289
295
  }
290
296
  } else if (!aborted) {
291
297
  // 族记账 hook(advisor 陈旧判定/token D1 落盘;escalate 三分类 merge 决策;subagent/
@@ -35,7 +35,7 @@ import { join } from "node:path"
35
35
  import { spawn } from "node:child_process"
36
36
  import { configDir } from "../config.mjs"
37
37
  import { cleanupOldToolResults, escapeXml } from "../agent/helpers.mjs"
38
- import { pushReal } from "../context.mjs"
38
+ import { pushInject, pushRecord } from "../context.mjs"
39
39
  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`。
@@ -247,7 +247,10 @@ export async function injectBgResult(parent, entry) {
247
247
  const { text, truncated } = renderTail(entry)
248
248
  const body = text.trim() ? escapeXml(text) : "(no output)"
249
249
  const note = truncated ? `\n[... tail truncated — the full output is in the log: ${entry.logPath}]` : ""
250
- pushReal(parent, { role: "user", content: `${head}\n${body}${note}` })
250
+ const msg = { role: "user", content: `${head}\n${body}${note}` }
251
+ // B 段:一次性投递走待发队,持久写入只落人读线(机读线零触)。
252
+ pushInject(parent, msg)
253
+ pushRecord(parent, msg)
251
254
  writeTombstone(parent, entry.id, entry.error != null ? "failed" : "consumed", "bg")
252
255
  }
253
256
 
@@ -9,10 +9,10 @@
9
9
  * 链完整性门(§2/§3/§4/§6 各段须有内容——`不适用` 声明机制已退役)→ **`§3` 状态词臂**(无条件 = `评审通过`)
10
10
  * → 本批批内单测档门(`TESTING.md` §3.5)→ 文档机检门(判据 = `docs/core/design/DOC-CHECK.md` §1–§6;
11
11
  * 调用点 = 同档 §7「落点」三处之一「批档写入与收口」)→ **档位臂**
12
- * (`batch-tier-gate.mjs` 的 `assertTierPlan`——同一臂两节,一条拒文:本批改动面里在盘的码档,§2 必须有
13
- * 它的行读数且与批起快照一致(判法 ∥ 拒文 = `docs/core/design/DOC-CHECK.md` §8);其中实测越了收口线的
14
- * 源档,§2 还必须有它的正向形分拆方案。两节判的都是**记录缺件**(越线那一节拿收口时的当前长度当触发物,
15
- * 判的仍是 §2 那一格);语义单源 = `docs/core/standards/CODE-TIER.md` §2.2,位次 = 本档的判序第 ⑤ 臂)。
12
+ * (`batch-tier-gate.mjs` 的 `assertTierPlan`——一支判据、一条拒文:本批改动面里实测越了收口线的在盘
13
+ * 码档,§2 必须有它的正向形分拆方案(判法 ∥ 拒文 = `docs/core/design/DOC-CHECK.md` §8)。判的是
14
+ * **记录缺件**(越线那一支拿收口时的当前长度当触发物,判的仍是 §2 那一格);语义单源 =
15
+ * `docs/core/standards/CODE-TIER.md` §2.2,位次 = 本档的判序第 ⑤ 臂)。
16
16
  * ② `assertSectionFiveGate` —— §5 写入门(段序门):两条合取——① `§3` 状态行 = `评审通过`;② `§3` 最近一轮
17
17
  * 轮次块自己携 pass 裁定行(块 = `lastRoundBlock`;裁定读数 = 骨架档 `verdictGapOf`,`append §3` 写入闸与
18
18
  * 签发面读同一个函数)。旧的第一条旁路(`§1` 声明 §3 不适用)已随本批删除:实现只发生在评审之后,没有例外段。
@@ -26,9 +26,8 @@
26
26
  *
27
27
  * 依赖单向(KD-4):`skeleton ← closeout ← bind ← reopen ← lifecycle`——本档不 import lifecycle。
28
28
  */
29
- import { execFileSync } from "node:child_process"
30
29
  import { readFileSync } from "node:fs"
31
- import { isAbsolute, relative, resolve } from "node:path"
30
+ import { resolve } from "node:path"
32
31
 
33
32
  import { owningProject } from "../manifest.mjs"
34
33
  import { batchProjectRoot } from "./batch-paths.mjs"
@@ -95,11 +94,9 @@ export function assertCloseoutChainComplete(src) {
95
94
  * ② **`§3` 状态词臂**:`§3` 状态行 = `评审通过`(无条件)
96
95
  * ③ 本批批内单测档门(仍在盘 ⇒ 拒——零留存的结构兜底)
97
96
  * ④ 文档机检门(REFUSED ∥ ERROR ⇒ 拒)
98
- * ⑤ **档位臂**(`batch-tier-gate.mjs` 的 `assertTierPlan`):两节一趟判完,一条拒文——
99
- * ① 读数支:本批改动面里在盘的码档,§2 机读清单那一行须带行读数且与**批起快照**一致;
100
- * ② 越线方案支:其中实测越了收口线的档,§2 须带它的正向形分拆方案。无在盘码档就两节都不启动
101
- * (**§2 缺块不是拒因**)。
102
- * 基线内容由本档交进去(`baseTextReaderOf`——门自己不读 git)。
97
+ * ⑤ **档位臂**(`batch-tier-gate.mjs` 的 `assertTierPlan`):一支判据、一条拒文——
98
+ * 本批改动面里实测越了收口线的在盘码档,§2 机读清单那一行须带它的正向形分拆方案。没有在盘码档
99
+ * 或没有越线档就不启动(**§2 缺块不是拒因**)。判域只由改动面与盘上长度定,本档不读 git。
103
100
  * 位次 = 既有拒因之后、写盘之前(任一被拒 ⇒ 档字节不变)。返回 `④` 的门结果供回执拼行(`null` = 未跑);
104
101
  * `mode === "normal"` 时同一笔把 ⑤ 的取材读数挂上 `changedSurface`,回执行从它取「只报不判」的那一半。
105
102
  * @param {{abs:string, cwd:string, agent:object, src:string, action:"close"|"status", mode?:"normal"|"repair"|"supersede"}} o
@@ -126,7 +123,7 @@ export function assertCloseoutGates({ abs, cwd, agent, src, action = "close", mo
126
123
  if (mode === "normal") {
127
124
  const root = tierRootOf(abs, cwd)
128
125
  const surface = changedSurface(abs, root, agent)
129
- assertTierPlan(src, root, surface.judged, baseTextReaderOf(abs, root))
126
+ assertTierPlan(src, root, surface.judged)
130
127
  // 只报不判的那一半随门结果交回调用面(同一笔取材,不取第二次——两次取才可能各说各的)。
131
128
  gate.changedSurface = surface
132
129
  }
@@ -169,7 +166,7 @@ export function changedSurfaceUnreadableError(root, baseSha) {
169
166
  * **基 sha 有了却读不出**(`committed.ok === false`)⇒ 抛拒(`changedSurfaceUnreadableError`),不静默少一腿:
170
167
  * 空集若被当成「本批没有提交改动」,不经记账工具写的档就一档都判不到,而收口照样冻记录。
171
168
  * 拒收口只属**本批自己的这一笔**:邻批那几笔读不出由 `neighborListClaims` 按「认领不成立」处置。
172
- * @returns {{root:string, judged:string[], reported:string[]}} `judged` = 交给档位臂判读数的档;
169
+ * @returns {{root:string, judged:string[], reported:string[]}} `judged` = 交给档位臂判方案行的档;
173
170
  * `reported` = 认领成立、只进回执行的档(绝对路径)
174
171
  */
175
172
  export function changedSurface(abs, root, agent) {
@@ -205,7 +202,7 @@ export function changedSurface(abs, root, agent) {
205
202
  }
206
203
 
207
204
  /**
208
- * `[changed surface]` 收口回执段(判据单源 = 设计档 §4.18.1「被别的批认领的档只报不判」):这些档不判读数,
205
+ * `[changed surface]` 收口回执段(判据单源 = 设计档 §4.18.1「被别的批认领的档只报不判」):这些档不判方案行,
209
206
  * 但**点名它们**,请人确认「是否本批」——判据收窄了,这件事仍然看得见。
210
207
  * 认领的来源如实写成两源(本会话归属表 ∥ 盘上批档的 §2 清单):观测源不按状态筛;计划源**状态可读即收**、
211
208
  * 上界随状态定(未收口取 HEAD、已收口取它自己的收口提交),所以串里不写「在途」那一个限定——回执说的必须是
@@ -219,7 +216,7 @@ export function changedSurfaceReceiptLine(surface) {
219
216
  const rows = surface?.reported ?? []
220
217
  if (rows.length === 0) return ""
221
218
  const items = rows.map((p) => `\n ${displayRelOf(surface.root, p)}`).join("")
222
- return `\n[changed surface] 只报不判:${rows.length} 档被别的批认领(本会话归属表 ∥ 盘上批档的 §2 清单),本批没判它们的读数——确认是否本批${items}`
219
+ return `\n[changed surface] 只报不判:${rows.length} 档被别的批认领(本会话归属表 ∥ 盘上批档的 §2 清单),本批没判它们的方案行——确认是否本批${items}`
223
220
  }
224
221
 
225
222
  /** 仓根(§2 机读清单的第一列是仓根相对路径)——解析式与文档机检门同式
@@ -230,53 +227,6 @@ function tierRootOf(abs, cwd) {
230
227
  return owningProject(resolve(abs), base) ?? batchProjectRoot(base)
231
228
  }
232
229
 
233
- // ─── 读数支的基线内容(本档读 git 的唯一一处:门自己不读,内容由这里交进去)──────────────────
234
-
235
- /** 一次 git 调用(`-C <cwd>`):失败不抛、返 `null`——分流判据在调用方(对象在不在 ∥ 路径在不在)。 */
236
- function gitRun(cwd, argv) {
237
- try {
238
- return execFileSync("git", ["-C", cwd, ...argv], {
239
- encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 8000,
240
- })
241
- } catch {
242
- return null
243
- }
244
- }
245
-
246
- /** 档在 git 树里的路径:快照的树以 **git 仓根**为基,§2 清单以**项目根**为基——项目根住大仓子目录时
247
- * 两基不同(解析式与 `committedDocs` 的 `base` 同一条)。 */
248
- function gitPathOf(top, root, relPath) {
249
- const abs = isAbsolute(relPath) ? relPath : resolve(root, relPath)
250
- const rel = relative(top, abs).replace(/\\/g, "/")
251
- return rel === "" || rel.startsWith("../") || isAbsolute(rel) ? String(relPath).replace(/\\/g, "/") : rel
252
- }
253
-
254
- /**
255
- * 读数支的基线取值函数(判法单源 = `docs/core/design/DOC-CHECK.md` §8「两个失败怎么分开」):
256
- * `git show <sha>:<档>` 对「快照里没这一档」与「对象读不到」报的错同形,照错文分流会把每个有新建档的批整批拒
257
- * (`新` 正是那条判据的地基)。故按三步问、各问一件:对象在不在 ⇒ 路径在不在 ⇒ 取内容。
258
- * **拒绝条件只有一条 = 记入行的 sha 指向的对象读不到**(`undefined`);`refs/thincoder/baseline/<批档名>`
259
- * 在不在不进判据——ref 只负责让那个对象不被回收,不是取内容的入口。
260
- * @param {string} abs — 批档绝对路径(记入行 `批起 sha` 的取法单源 = `baseShaOf`)
261
- * @param {string} root — 项目根(清单第一列的基)
262
- * @returns {(relPath:string) => string|null|undefined} 串 = 该档在快照里的内容 ∥ `null` = 快照里没有这一档 ∥
263
- * `undefined` = 基线不可判(门按整批一条拒)
264
- */
265
- function baseTextReaderOf(abs, root) {
266
- const sha = baseShaOf(abs)
267
- if (sha === null) return () => undefined
268
- const top = (gitRun(root, ["rev-parse", "--show-toplevel"]) ?? "").trim() || root
269
- let commitReadable = null // 一次收口只问一遍对象在不在
270
- return (relPath) => {
271
- if (commitReadable === null) commitReadable = gitRun(top, ["cat-file", "-e", `${sha}^{commit}`]) !== null
272
- if (!commitReadable) return undefined
273
- const gitPath = gitPathOf(top, root, relPath)
274
- if (gitRun(top, ["cat-file", "-e", `${sha}:${gitPath}`]) === null) return null
275
- const text = gitRun(top, ["show", `${sha}:${gitPath}`])
276
- return text === null ? undefined : text // 取不到内容同样按「基线不可判」,不静默读成 `新`
277
- }
278
- }
279
-
280
230
  /** 读档(本档只读一面——写盘归 lifecycle 与 bind;读错上抛不伪装)。 */
281
231
  export function readCloseoutSource(abs) { return readFileSync(abs, "utf8") }
282
232
 
@@ -33,7 +33,7 @@ import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, unl
33
33
  import { tmpdir } from "node:os"
34
34
  import { basename, dirname, join, relative, resolve } from "node:path"
35
35
 
36
- import { appendLedgerNoToHeader, batchSkeleton, readBatchStatusLine } from "./batch-skeleton.mjs"
36
+ import { appendLedgerNoToHeader, batchSkeleton, goAheadReceiptLine, readBatchStatusLine } from "./batch-skeleton.mjs"
37
37
  import { resolveBatchCreatePath } from "./batch-paths.mjs"
38
38
  // B8(TOOLS.md §6.29 ④):父会话历史窗口起点(建批成功即记一次)
39
39
  import { recordBatchHistoryStart } from "./read-history.mjs"
@@ -157,7 +157,8 @@ function baseShaForCreate(root, abs) {
157
157
  * 不传 `ledger` ⇒ 新建一行(`在途` · `kind` = `board` 给则 `requirement` 否则 `tech_todo` · `title` = `topic` ·
158
158
  * `task_book` = 本档相对指针 · `trigger` = 归批)——**同面(本笔 `board`)无未决行时如此;有则须 `newDebt:"<一句理由>"`,
159
159
  * 两者皆无 ⇒ 拒并列候选**(设计档 `docs/core/design/LEDGER.md` §6.3);传 `#N` ⇒ 接管该行(`待讨论` / `待设计` → `在途`;
160
- * `在途` 且指针指回本档 ⇒ 零台账写;其余 ⇒ 三形拒文,见 §2.4)。
160
+ * `在途` 且指针指回本档 ⇒ 接管——普通指针零台账写,指针仍带 `(预定)` 标记时同笔一次台账写把它改写成
161
+ * 普通形(§6.4);其余 ⇒ 三形拒文,见 §2.4)。
161
162
  * 档头 `台账` 行由**真实行号**填(`board` 未给 ⇒ 括注 `—`,不拒)。
162
163
  * @returns {Promise<string>} 成功消息(含落盘绝对路径、行号与同面判读数)
163
164
  */
@@ -223,7 +224,7 @@ export async function createBatchRecord({ args, ctx, review, cwd, bases, onWritt
223
224
  throw e
224
225
  }
225
226
  created.flag = true
226
- if (ctx?.agent) ctx.agent._batchWrites = (ctx.agent._batchWrites ?? 0) + 1 // §6.6 `wrote` 判据(建档写盘成功才增)
227
+ if (ctx?.agent) ctx.agent._batchWrites = (ctx.agent._batchWrites ?? 0) + 1 // §7.1 `wrote` 判据(建档写盘成功才增)
227
228
  onWritten?.(ctx?.agent ?? {}, abs)
228
229
  }
229
230
 
@@ -257,13 +258,20 @@ export async function createBatchRecord({ args, ctx, review, cwd, bases, onWritt
257
258
  if (!recordResult) throw e // 写前拒保持原串;本笔尚未落档,不另加清理结果。
258
259
  throw new Error(`${e?.message ?? e}\n(台账事务未提交:本笔未走到 COMMIT;${recordResult})`)
259
260
  }
261
+ // 接手支的两读法(§6.4):普通指针接手 = 零台账写;带预定标记的行同笔收编标记,那一次改写必须报出来——
262
+ // 「zero ledger write」在这支为假,回执不能照搬。
260
263
  const took = result.claimed
261
264
  ? "claimed (a reserved row pointing at this path is now this record's row — no new row was opened)"
262
- : result.tookOver === "new" ? "opened" : result.tookOver === "live" ? "taken over (already live — zero ledger write)" : "taken over"
265
+ : result.tookOver === "new" ? "opened"
266
+ : result.tookOver === "live" ? (result.normalized
267
+ ? "taken over (already live — the 预定 marker on its task_book was rewritten to the plain form in the same ledger write)"
268
+ : "taken over (already live — zero ledger write)")
269
+ : "taken over"
263
270
  // B8(TOOLS.md §6.29 ④):父会话历史窗口的起点 = 本批创建时刻(depth-0 根 agent 上按规范化批档存)。
264
271
  // 旧批没有起点时由首次绑定 spawn 记一次(`subagent-spawn.mjs`)——那里不回填更早的消息。
265
272
  recordBatchHistoryStart(ctx?.agent, abs, Date.now())
266
- 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 ?? "—"}).${sameFaceReceiptLine(result.sameFace)}`
273
+ // 建批这一笔也是 §1 写入(§4.24 回执面):回执带当前授权行 ⇒ 新批的默认态 `未授权` 当场读得出来。
274
+ 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)}`
267
275
  }
268
276
 
269
277
  /** 本地今天(YYYY-MM-DD)——create 的缺省 date。 */
@@ -310,7 +318,8 @@ const attachTitleError = () => "batch: attach needs title when it opens a new le
310
318
  * - **不动已核销行**(J4):只开新行或接管未决行;核销过的行没有回退边(`ledgerBindBatch` 已拒归档 / 待核销行)。
311
319
  *
312
320
  * 幂等:行号已在档头列表 ⇒ 零写 + 回执点名「已在列表」——为的是同一个回调在 `ledgerBindBatch` 的
313
- * 「行已 live、零台账写」分支上也安全(重放 `attach{ledger:"#N"}` 落到的就是那条)。
321
+ * 「行已 live」分支上也安全(重放 `attach{ledger:"#N"}` 落到的就是那条);该分支在指针仍带 `(预定)` 标记时
322
+ * 会做一次台账写(同笔改写成普通形,§6.4),回执的那一支按实报,不称零写。
314
323
  * 拒面(全 fail-closed:档零字节 / 台账零写):门态非 `进行中` · 档头 `台账` 行缺失 · 本面有未决行而无 `newDebt` ·
315
324
  * 开新行而缺 `title` · 台账库不可达 ∥ 事务失败。
316
325
  * **台账事务失败**(写档头之后那一半)⇒ 用写前全文回写档头再抛拒(第一条串);回写也失败 ⇒ 第二条串点名
@@ -353,7 +362,7 @@ export async function attachBatchRecord({ args, ctx, review, cwd, pickTarget, on
353
362
  if (edited.already) { header.already = true; return }
354
363
  writeFileSync(abs, edited.src)
355
364
  header.wrote = true
356
- if (ctx?.agent) ctx.agent._batchWrites = (ctx.agent._batchWrites ?? 0) + 1 // §6.6 `wrote` 判据(写盘成功才增)
365
+ if (ctx?.agent) ctx.agent._batchWrites = (ctx.agent._batchWrites ?? 0) + 1 // §7.1 `wrote` 判据(写盘成功才增)
357
366
  onWritten?.(ctx?.agent ?? {}, abs)
358
367
  }
359
368
  let result
@@ -386,7 +395,9 @@ export async function attachBatchRecord({ args, ctx, review, cwd, pickTarget, on
386
395
  throw new Error(attachLedgerFailedError(cause))
387
396
  }
388
397
  const head = header.already
389
- ? `batch: ledger row #${result.id} is already in the header 台账 line of ${abs} — zero write (idempotent: the row is live and already listed; nothing changed).`
398
+ ? (result.normalized
399
+ ? `batch: ledger row #${result.id} is already in the header 台账 line of ${abs} — the header was not rewritten (idempotent: the row is live and already listed), and this same call rewrote its task_book (预定) marker to the plain form in the ledger.`
400
+ : `batch: ledger row #${result.id} is already in the header 台账 line of ${abs} — zero write (idempotent: the row is live and already listed; nothing changed).`)
390
401
  : `batch: attached ledger row #${result.id} to ${abs} — header 台账 line is now \`${header.line}\` (row status = 在途 · task_book = ${taskBook} · trigger = 归批).`
391
402
  return `${head}${sameFaceReceiptLine(result.sameFace)}`
392
403
  }
@@ -51,6 +51,7 @@ import {
51
51
  DEPTH0_SEGMENTS, SEGMENT_BY_ROLE, SEGMENT_BY_ROLE_NORMAL, STATUS_WORDS, TEMPLATE_PLACEHOLDERS,
52
52
  findPlaceholderResidue, placeholderResidueError, readBatchStatusLine, reviewWritableSegment, sectionHasStatusLine,
53
53
  sectionThreeDesignTrackError, updateSectionStatusLine, zoneStatusCount,
54
+ GO_AHEAD_REASON_CLOSE, goAheadEndLine, goAheadReceiptLine, readGoAheadState,
54
55
  } from "./batch-skeleton.mjs"
55
56
  import { assertCloseoutGates, changedSurfaceReceiptLine, checkReceipt, closeHalfStateError, closeLedgerFailedError, consistencyReceiptLine, newDebtReasonOf, newDebtReasonReceiptLine, readCloseoutSource, reanchorReceiptLine, repairReceiptLine, repairTraceLine } from "./batch-closeout.mjs"
56
57
  import { assertCloseDisposition, consistencyOf, repairDecisionOf } from "./batch-ledger-view.mjs"
@@ -69,8 +70,10 @@ function isDepthZero(ctx) {
69
70
  return ctx?.depth === 0
70
71
  }
71
72
 
72
- /** 段号解析(`§2` / `2` / `§2 批次任务` 均可;无法解析 → null——与主档 append 面同型三行谓词)。 */
73
- function segmentNumber(raw) {
73
+ /** 段号解析(`§2` / `2` / `§2 批次任务` 均可;无法解析 → null——与主档 append 面同型三行谓词)。
74
+ * **导出面** = 只读 `read` 动作(`batch-read.mjs`)取用同一条判据——三行谓词已有两份副本,
75
+ * `read` 取其一而不造第三种(`BATCH-RECORD.md` §4.25「段号与 `offset` 的取法」)。 */
76
+ export function segmentNumber(raw) {
74
77
  const m = /^§?\s*(\d+)/.exec(String(raw ?? "").trim())
75
78
  return m ? Number(m[1]) : null
76
79
  }
@@ -143,6 +146,23 @@ export function assertGateOpen(src) {
143
146
  }
144
147
  }
145
148
 
149
+ /**
150
+ * **收口落行**(`BATCH-RECORD.md` §4.24;设计 `E8`「收口自己落这条行」):`status` 写 §1「已收口」∥ `close` 两条
151
+ * 收口通路**同源调本助手**,在该笔里给 §1 段尾追加一条
152
+ * `- **自动推进**:未授权 · 结束原因 = 该批收口 · 时间 = <日期>`。三条纪律:
153
+ * - 末条已是 `未授权` ⇒ 零写(幂等)。这条行**只会把授权往下压**,永远写不出 `已授权`——工具在这里只是执行
154
+ * 需求已写明的失效条件(该批收口),不是第二个授权写者;
155
+ * - 两路必须同调:不同调就会有一路收口后盘上还写着 `已授权`;
156
+ * - 落点 = §1 段尾追加一行(既有拼接面 `appendLineToSection`,既有字节零变)。
157
+ * @param {string} src — 状态行已改写的全文
158
+ * @param {string} date — 日期戳(`todayLocal()`——日期口径仍只一处)
159
+ * @returns {string} 写盘全文(零写 = 逐字原样)
160
+ */
161
+ function appendGoAheadRevokedLine(src, date) {
162
+ if (readGoAheadState(src) === "none") return src
163
+ return appendLineToSection(src, 1, `- **自动推进**:未授权 · 结束原因 = ${GO_AHEAD_REASON_CLOSE} · 时间 = ${date}`)
164
+ }
165
+
146
166
  /** 全词表去重并集(各段项——value 命中判据与 note 零命判据共用同一口径)。 */
147
167
  function statusVocabulary() {
148
168
  return [...new Set(Object.values(STATUS_WORDS).flatMap((w) => Object.values(w)))]
@@ -289,14 +309,15 @@ export async function statusBatchRecord({ args, ctx, review, reviewTrack, pickTa
289
309
  //(值非「已收口」;写后门态 = open,后续 append/status 恢复放行)。
290
310
  writeFileSync(abs, rewriteAsReopen(src, note))
291
311
  // 记账口径同 status 径(记「落过盘」,回档不回退)——见 `statusBatchRecord` 写盘处的注释。
292
- if (ctx?.agent) ctx.agent._batchWrites = (ctx.agent._batchWrites ?? 0) + 1 // §6.6 `wrote` 判据(写盘成功才增)
312
+ if (ctx?.agent) ctx.agent._batchWrites = (ctx.agent._batchWrites ?? 0) + 1 // §7.1 `wrote` 判据(写盘成功才增)
293
313
  onWritten?.(ctx?.agent ?? {}, abs)
294
314
  // ② 台账回收(§2.17 重开步序 3–4 · 写序:档先写、台账后写):失败 ⇒ 用写前全文(冻结态)补偿回滚档,
295
315
  // 然后抛拒——「档已开、行仍 待核销」的残态会让写锁拒每一笔写盘且没有任何提示,正是本批要消掉的那一形。
296
316
  const reclaim = await ledgerAfterRecordWrite({
297
317
  side: "reopen", abs, src, run: () => reclaimOnReopen(abs, ctx?.agent?.cwd),
298
318
  })
299
- return `batch: §1 reopened — status line → 「进行中(重开 ${todayLocal()})」 + reopen record appended to §1 (reason lands verbatim in the record line). Append/status are writable again (BR-64); the closeout chain gate still applies at the next close.${reopenReceiptLine(reclaim)}${consistencyReceiptLine(await consistencyOf(abs, ctx?.agent?.cwd))}`
319
+ // 回执附带当前授权行(§4.24):重开径不改授权行(它只改写状态行 + 追记行)⇒ 读写前全文同值。
320
+ return `batch: §1 reopened — status line → 「进行中(重开 ${todayLocal()})」 + reopen record appended to §1 (reason lands verbatim in the record line). Append/status are writable again (BR-64); the closeout chain gate still applies at the next close.${goAheadReceiptLine(src)}${reopenReceiptLine(reclaim)}${consistencyReceiptLine(await consistencyOf(abs, ctx?.agent?.cwd))}`
300
321
  }
301
322
  // 收口门(§2.6——链门 + §3 状态词臂 + 单测档门 + 机检门):本笔把 §1 写成「已收口」⇒ 四道同判。
302
323
  // 段号守卫只写这一次(`STATUS_WORDS[1].closed` 只属 §1 项,`assertStatusValue` 亦拒他段该值)。
@@ -317,12 +338,14 @@ export async function statusBatchRecord({ args, ctx, review, reviewTrack, pickTa
317
338
  // 补关(§4.18-C)= 冻结之外在 §1 段尾追加一行追记(一次写盘、两处落笔);正常收口只改状态行。
318
339
  // 补关只在 `closingValue` 下成立,而 `closingValue` 蕴含 `seg === 1` ⇒ 追记行恒落 §1。
319
340
  const statusWritten = updateSectionStatusLine(src, seg, lineValue)
320
- const written = repair?.repair ? appendLineToSection(statusWritten, 1, repairTraceLine(todayLocal(), repair.rows)) : statusWritten
341
+ const repairWritten = repair?.repair ? appendLineToSection(statusWritten, 1, repairTraceLine(todayLocal(), repair.rows)) : statusWritten
342
+ // 收口即失效(§4.24):写 §1「已收口」这一笔同源落 `未授权` 行——不靠谁事后记得补一笔。
343
+ const written = closingValue ? appendGoAheadRevokedLine(repairWritten, todayLocal()) : repairWritten
321
344
  writeFileSync(abs, written)
322
345
  // 记账口径(明示,不改行为):`_batchWrites` 与端侧记账记的是「本笔**落过盘**」,位次 = 写盘成功那一刻;
323
346
  // 台账失败由 `ledgerAfterRecordWrite` 把档回档后本计数不回退(档字节净变 = 零,而写盘事实发生过)。
324
- // 它不进任何判据(§6.6 `wrote` 只问「有没有写过」),故不以回档为准重算。
325
- if (ctx?.agent) ctx.agent._batchWrites = (ctx.agent._batchWrites ?? 0) + 1 // §6.6 `wrote` 判据(写盘成功才增)
347
+ // 它不进任何判据(§7.1 `wrote` 只问「有没有写过」),故不以回档为准重算。
348
+ if (ctx?.agent) ctx.agent._batchWrites = (ctx.agent._batchWrites ?? 0) + 1 // §7.1 `wrote` 判据(写盘成功才增)
326
349
  onWritten?.(ctx?.agent ?? {}, abs)
327
350
  // 收口重锚(§6.2 · C · AC-M2-30):值余核 = §1「已收口」⇒ 本 action 就是收口 ⇒ 同调单源
328
351
  // `reanchorOnClose`(不复制 close 径逻辑);次序位 = 状态行写盘之后(写序单源 = §2.17)。
@@ -332,7 +355,7 @@ export async function statusBatchRecord({ args, ctx, review, reviewTrack, pickTa
332
355
  const reanchor = closingValue && readBatchStatusLine(src) !== "closed"
333
356
  ? await ledgerAfterRecordWrite({ side: "close", abs, src, run: () => reanchorOnClose(abs, ctx?.agent?.cwd, args?.completed, args?.closeEvidence, true) })
334
357
  : null
335
- return `batch: §${seg} status line updated to ${JSON.stringify(lineValue)} — the freeze gate (§1) is a read-only domain for non-§1 writes (frozen truth stays = the §1 line).${gateReceiptLine(gate)}${changedSurfaceReceiptLine(gate?.changedSurface)}${designTokensReceiptLine(designTokens)}${repairReceiptLine(repair?.repair ? { rows: repair.rows, date: todayLocal() } : null)}${reanchorReceiptLine(reanchor)}${newDebtReasonReceiptLine(reanchor)}${consistencyReceiptLine(await consistencyOf(abs, ctx?.agent?.cwd))}`
358
+ return `batch: §${seg} status line updated to ${JSON.stringify(lineValue)} — the freeze gate (§1) is a read-only domain for non-§1 writes (frozen truth stays = the §1 line).${gateReceiptLine(gate)}${changedSurfaceReceiptLine(gate?.changedSurface)}${designTokensReceiptLine(designTokens)}${seg === 1 ? `${goAheadReceiptLine(written)}${goAheadEndLine(src, written)}` : ""}${repairReceiptLine(repair?.repair ? { rows: repair.rows, date: todayLocal() } : null)}${reanchorReceiptLine(reanchor)}${newDebtReasonReceiptLine(reanchor)}${consistencyReceiptLine(await consistencyOf(abs, ctx?.agent?.cwd))}`
336
359
  }
337
360
 
338
361
  /**
@@ -364,17 +387,20 @@ export async function closeBatchRecord({ args, ctx, review, pickTarget, onWritte
364
387
  const date = todayLocal()
365
388
  // 补关(§4.18-C)= 冻结之外在 §1 段尾追加一行追记(一次写盘、两处落笔);正常收口只改状态行。
366
389
  const statusWritten = updateSectionStatusLine(src, 1, `已收口 ${date}`)
367
- const written = repair.repair ? appendLineToSection(statusWritten, 1, repairTraceLine(date, repair.rows)) : statusWritten
390
+ const repairWritten = repair.repair ? appendLineToSection(statusWritten, 1, repairTraceLine(date, repair.rows)) : statusWritten
391
+ // 收口即失效(§4.24):与 status 收口通路同源(`appendGoAheadRevokedLine`)——两路不同调就会有一路收口后
392
+ // 盘上还写着 `已授权`。
393
+ const written = appendGoAheadRevokedLine(repairWritten, date)
368
394
  writeFileSync(abs, written)
369
395
  // 记账口径同 status 径(记「落过盘」,回档不回退)——见 `statusBatchRecord` 写盘处的注释。
370
- if (ctx?.agent) ctx.agent._batchWrites = (ctx.agent._batchWrites ?? 0) + 1 // §6.6 `wrote` 判据(写盘成功才增)
396
+ if (ctx?.agent) ctx.agent._batchWrites = (ctx.agent._batchWrites ?? 0) + 1 // §7.1 `wrote` 判据(写盘成功才增)
371
397
  onWritten?.(ctx?.agent ?? {}, abs)
372
398
  // 收口重锚(§6.2 · C · AC-M2-30):顺序位 = 全部拒因通过、§1 状态行写盘**之后**——close 被拒 ⇒ 台账零写。
373
399
  // 台账失败 ⇒ 用写前全文回滚档 + 抛拒(§2.17 写序;不可逆的一方排最后)。
374
400
  const reanchor = await ledgerAfterRecordWrite({
375
401
  side: "close", abs, src, run: () => reanchorOnClose(abs, ctx?.agent?.cwd, args?.completed, args?.closeEvidence, true),
376
402
  })
377
- return `batch: §1 status line → 「已收口 ${date}」 — the record is frozen: append is refused from now on, and status is refused except the reopen conjunction (§1 → 进行中 with a note) (整档冻结;改 = 新批新档; §6 内容与台账核销仍走既有通道).${gateReceiptLine(gate)}${changedSurfaceReceiptLine(gate?.changedSurface)}${designTokensReceiptLine(designTokens)}${repairReceiptLine(repair.repair ? { rows: repair.rows, date } : null)}${reanchorReceiptLine(reanchor)}${newDebtReasonReceiptLine(reanchor)}${consistencyReceiptLine(await consistencyOf(abs, ctx?.agent?.cwd))}`
403
+ return `batch: §1 status line → 「已收口 ${date}」 — the record is frozen: append is refused from now on, and status is refused except the reopen conjunction (§1 → 进行中 with a note) (整档冻结;改 = 新批新档; §6 内容与台账核销仍走既有通道).${gateReceiptLine(gate)}${changedSurfaceReceiptLine(gate?.changedSurface)}${designTokensReceiptLine(designTokens)}${goAheadReceiptLine(written)}${goAheadEndLine(src, written)}${repairReceiptLine(repair.repair ? { rows: repair.rows, date } : null)}${reanchorReceiptLine(reanchor)}${newDebtReasonReceiptLine(reanchor)}${consistencyReceiptLine(await consistencyOf(abs, ctx?.agent?.cwd))}`
378
404
  }
379
405
 
380
406
  // ─── 收口自动消费本批设计凭证(DESIGN-TOKEN-SETTLEMENT §10——单源,close ∥ status 两通路同调)──