@thincoder/core 0.11.3 → 0.11.5

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 (183) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/advisor/compaction.mjs +40 -17
  3. package/advisor/loop.mjs +14 -6
  4. package/advisor/notice.mjs +1 -1
  5. package/advisor/timeline.mjs +4 -4
  6. package/agent/completion.mjs +19 -0
  7. package/agent/dispatch-gates.mjs +2 -0
  8. package/agent/dispatch.mjs +2 -2
  9. package/agent/family-tools.mjs +13 -9
  10. package/agent/helpers.mjs +10 -6
  11. package/agent/planning-step.mjs +453 -0
  12. package/agent/post-turn.mjs +70 -2
  13. package/agent/run-stages.mjs +22 -50
  14. package/agent/run-start.mjs +17 -0
  15. package/agent/setup-reminders.mjs +71 -8
  16. package/agent/setup.mjs +8 -39
  17. package/agent/spawn-child.mjs +6 -2
  18. package/agent/task-lifecycle.mjs +146 -0
  19. package/agent/turn-loop.mjs +73 -11
  20. package/agent-tools/batch-closeout.mjs +21 -34
  21. package/agent-tools/batch-gate.mjs +7 -5
  22. package/agent-tools/batch-ledger-bind.mjs +21 -1
  23. package/agent-tools/batch-lifecycle.mjs +7 -7
  24. package/agent-tools/batch-record-write.mjs +237 -280
  25. package/agent-tools/batch-supersede.mjs +3 -3
  26. package/agent-tools/batch.mjs +42 -9
  27. package/agent-tools/context.mjs +0 -13
  28. package/agent-tools/escalate-async.mjs +7 -1
  29. package/agent-tools/parent-channel.mjs +7 -6
  30. package/agent-tools/plan.mjs +103 -67
  31. package/agent-tools/review-facts.mjs +3 -3
  32. package/agent-tools/settings.mjs +2 -0
  33. package/agent-tools/spawn-gates.mjs +37 -11
  34. package/agent-tools/ssh-session.mjs +68 -25
  35. package/agent-tools/ssh-transfer.mjs +7 -2
  36. package/agent-tools/ssh-transport.mjs +2 -2
  37. package/agent-tools/ssh-vault.mjs +2 -2
  38. package/agent-tools/step.mjs +462 -0
  39. package/agent-tools/subagent-actions.mjs +6 -1
  40. package/agent-tools/subagent-run.mjs +7 -0
  41. package/agent-tools/subagent-spawn.mjs +1 -1
  42. package/agent-tools/subagent.mjs +17 -11
  43. package/agent-tools/task.mjs +178 -26
  44. package/agent-tools.mjs +1 -0
  45. package/agent.mjs +2 -0
  46. package/config-defaults.mjs +17 -1
  47. package/config-migrate.mjs +8 -5
  48. package/config.mjs +7 -0
  49. package/context.mjs +5 -4
  50. package/declaration.mjs +4 -4
  51. package/generate-title.mjs +0 -6
  52. package/i18n.mjs +4 -0
  53. package/ledger-cmd.mjs +11 -1
  54. package/ledger-tools.mjs +15 -4
  55. package/manifest-schema.mjs +1 -0
  56. package/model-context.mjs +34 -11
  57. package/model-specs.mjs +5 -2
  58. package/package.json +1 -1
  59. package/prompt-files.mjs +48 -11
  60. package/prompt-overlays.mjs +79 -8
  61. package/prompts/advisor-design.md +253 -206
  62. package/prompts/advisor-round1.md +151 -145
  63. package/prompts/advisor-round2.md +136 -130
  64. package/prompts/advisor-round3.md +140 -134
  65. package/prompts/common.md +244 -96
  66. package/prompts/consult-base.md +29 -30
  67. package/prompts/discipline-engineering.md +73 -519
  68. package/prompts/discipline-normal.md +28 -136
  69. package/prompts/knowledge/batch-before-write.md +8 -0
  70. package/prompts/knowledge/batch-cycle-register.md +15 -0
  71. package/prompts/knowledge/batch-progress-ledger.md +29 -0
  72. package/prompts/knowledge/business-gates.md +24 -24
  73. package/prompts/knowledge/decision-quality.md +8 -19
  74. package/prompts/knowledge/doc-discipline-d-rules.md +63 -0
  75. package/prompts/knowledge/doc-lookup.md +25 -24
  76. package/prompts/knowledge/document-writing.md +11 -32
  77. package/prompts/knowledge/documentation-evaluation.md +42 -42
  78. package/prompts/knowledge/eng-dispatch-ops.md +34 -0
  79. package/prompts/knowledge/eng-ledger-ops.md +26 -0
  80. package/prompts/knowledge/evidence-discipline.md +10 -32
  81. package/prompts/knowledge/normal-batch-discipline.md +13 -0
  82. package/prompts/knowledge/normal-coding-workflow.md +97 -99
  83. package/prompts/knowledge/normal-delivery-collaboration.md +107 -112
  84. package/prompts/knowledge/normal-work-management.md +44 -44
  85. package/prompts/knowledge/product-security.md +7 -26
  86. package/prompts/knowledge/project-records.md +69 -64
  87. package/prompts/knowledge/tool-advisor.md +17 -17
  88. package/prompts/knowledge/tool-apply-patch.md +14 -14
  89. package/prompts/knowledge/tool-bash.md +32 -31
  90. package/prompts/knowledge/tool-batch-eng-coder.md +19 -13
  91. package/prompts/knowledge/tool-batch-eng-designer.md +21 -14
  92. package/prompts/knowledge/tool-batch-review.md +18 -12
  93. package/prompts/knowledge/tool-batch.md +93 -85
  94. package/prompts/knowledge/tool-browser.md +59 -59
  95. package/prompts/knowledge/tool-code-search.md +2 -2
  96. package/prompts/knowledge/tool-consult-start.md +6 -6
  97. package/prompts/knowledge/tool-consult-stop.md +3 -3
  98. package/prompts/knowledge/tool-context.md +4 -4
  99. package/prompts/knowledge/tool-delete.md +16 -16
  100. package/prompts/knowledge/tool-doc-check.md +39 -39
  101. package/prompts/knowledge/tool-doc-graph-read.md +11 -11
  102. package/prompts/knowledge/tool-doc-graph.md +48 -48
  103. package/prompts/knowledge/tool-doc-search.md +3 -3
  104. package/prompts/knowledge/tool-edit.md +30 -30
  105. package/prompts/knowledge/tool-eng.md +1 -1
  106. package/prompts/knowledge/tool-execute.md +16 -16
  107. package/prompts/knowledge/tool-fetch.md +15 -15
  108. package/prompts/knowledge/tool-file-ops.md +15 -15
  109. package/prompts/knowledge/tool-get-current-time.md +3 -3
  110. package/prompts/knowledge/tool-git-read.md +15 -15
  111. package/prompts/knowledge/tool-git.md +26 -26
  112. package/prompts/knowledge/tool-glob.md +14 -14
  113. package/prompts/knowledge/tool-goal.md +5 -5
  114. package/prompts/knowledge/tool-grep.md +19 -18
  115. package/prompts/knowledge/tool-hashline-edit.md +13 -13
  116. package/prompts/knowledge/tool-insert-after.md +14 -14
  117. package/prompts/knowledge/tool-instance-list.md +3 -3
  118. package/prompts/knowledge/tool-instance-send.md +5 -5
  119. package/prompts/knowledge/tool-knowledge.md +12 -12
  120. package/prompts/knowledge/tool-ledger-read.md +20 -20
  121. package/prompts/knowledge/tool-ledger.md +44 -44
  122. package/prompts/knowledge/tool-lint.md +10 -10
  123. package/prompts/knowledge/tool-ls.md +11 -11
  124. package/prompts/knowledge/tool-lsp.md +8 -8
  125. package/prompts/knowledge/tool-main-history.md +1 -1
  126. package/prompts/knowledge/tool-manifest-read.md +7 -7
  127. package/prompts/knowledge/tool-manifest.md +43 -32
  128. package/prompts/knowledge/tool-memory-read.md +12 -12
  129. package/prompts/knowledge/tool-memory.md +14 -14
  130. package/prompts/knowledge/tool-notify-parent.md +10 -10
  131. package/prompts/knowledge/tool-operations.md +88 -88
  132. package/prompts/knowledge/tool-peek.md +10 -0
  133. package/prompts/knowledge/tool-peer-instances.md +1 -1
  134. package/prompts/knowledge/tool-plan.md +6 -3
  135. package/prompts/knowledge/tool-process-read.md +8 -8
  136. package/prompts/knowledge/tool-process.md +11 -11
  137. package/prompts/knowledge/tool-question.md +11 -13
  138. package/prompts/knowledge/tool-read-history-batch.md +13 -13
  139. package/prompts/knowledge/tool-read-history.md +19 -19
  140. package/prompts/knowledge/tool-read-image.md +8 -8
  141. package/prompts/knowledge/tool-read.md +17 -17
  142. package/prompts/knowledge/tool-recent-changes.md +4 -4
  143. package/prompts/knowledge/tool-repo-outline.md +2 -2
  144. package/prompts/knowledge/tool-settings-read.md +5 -7
  145. package/prompts/knowledge/tool-settings.md +10 -10
  146. package/prompts/knowledge/tool-skill.md +4 -4
  147. package/prompts/knowledge/tool-ssh.md +66 -66
  148. package/prompts/knowledge/tool-step.md +26 -0
  149. package/prompts/knowledge/tool-subagent.md +52 -50
  150. package/prompts/knowledge/tool-task.md +14 -11
  151. package/prompts/knowledge/tool-team-ledger-read.md +7 -7
  152. package/prompts/knowledge/tool-team-ledger.md +13 -13
  153. package/prompts/knowledge/tool-timer.md +14 -14
  154. package/prompts/knowledge/tool-tree.md +11 -11
  155. package/prompts/knowledge/tool-verify.md +11 -11
  156. package/prompts/knowledge/tool-wait-for.md +20 -20
  157. package/prompts/knowledge/tool-websearch.md +16 -14
  158. package/prompts/knowledge/tool-write.md +10 -10
  159. package/prompts/knowledge/upstream-protocol.md +37 -38
  160. package/prompts/persona-coder.md +22 -22
  161. package/prompts/persona-eng-coder.md +87 -81
  162. package/prompts/persona-eng-designer.md +173 -153
  163. package/prompts/persona-engineering.md +53 -554
  164. package/prompts/persona-explore.md +18 -15
  165. package/prompts/persona-normal.md +62 -63
  166. package/prompts/persona-plan.md +36 -32
  167. package/prompts/persona-tester.md +39 -39
  168. package/prompts/planning-next-moves.md +9 -0
  169. package/prompts/subagent-base.md +4 -16
  170. package/provider/errors.mjs +0 -24
  171. package/provider/list-models.mjs +20 -2
  172. package/session-lifecycle.mjs +4 -3
  173. package/tool-args.mjs +25 -0
  174. package/tool-docs/peek.md +3 -0
  175. package/tool-docs/plan.md +1 -1
  176. package/tool-docs/question.md +1 -1
  177. package/tool-docs/step.md +3 -0
  178. package/tools/edit-diff.mjs +4 -4
  179. package/tools/index.mjs +3 -2
  180. package/tools/peek.mjs +447 -0
  181. package/tools/question.mjs +87 -9
  182. package/tools/ssh.mjs +1 -1
  183. package/window-policy.mjs +107 -80
@@ -1,22 +1,12 @@
1
1
  /**
2
- * agent-tools/batch-record-write.mjs — 批次档**段写入执行面**(append ∥ edit 两条 action 的读写与门)。
2
+ * agent-tools/batch-record-write.mjs — 批次档**段写入执行面**(append ∥ edit ∥ update 三条写动作的读写与门)。
3
3
  *
4
4
  * 2026-11-05 拆档族从 `batch.mjs` 迁出:工具面(`batch` 的 schema 与 action 分发)留原档,执行面住本档。
5
- * 分界判据 = 「改 schema 的人不该翻过 300 行执行体」:本档全是逐 action 的段读写、拒面与文档机检门挂点。
5
+ * `appendBatchRecord`、`editBatchRecord` 与 `updateBatchRecord`(批量原子更新多节/多处)共享同一套
6
+ * 身份白名单、目标解析、冻结/占位检查、段写入纯变换(`applyAppendInMemory` / `applyEditInMemory`)与
7
+ * 文档机检门——单笔与批量语义完全一致,批量任一条目失败或过不了机检门即整体回滚(零字节落盘)。
6
8
  *
7
- * 搬家形 = **具名符号整块外移、不重写体、不改名**:`appendBatchRecord` ∥ `editBatchRecord` 两具执行体、
8
- * 共用五助手(`segmentNumber` ∥ `allowedSegment` ∥ `noSegmentError` ∥ `sanitizeText` ∥ `insertIntoSection`)、
9
- * edit 面一助手(`sectionBodySpan`)、`MAX_TEXT_CHARS` 及其私有件
10
- * (`CRED_RE` ∥ `CRED_TEST_RE`)、十一条拒串逐字随迁。原档 import 回来供分发调用 ⇒ 调用点零改、
11
- * 拒文零变——这是本批「行为零变」的机械保证。
12
- *
13
- * **记账注入缝(`injectedOnWrite` ∥ `configureBatchSegment` ∥ `resetBatchSegment`)不随迁**:缝的唯一
14
- * 读者是原档的 `batchTool.execute`(它取值后经 `onWritten` 形参递给 create / append / edit / status /
15
- * close 五条 action)——把缝搬到本档会让工具面反向 import 本档(两档互 import),或逼出新导出名;
16
- * 留原档两头都不必,且 `onWritten` 形参本就在两条执行体的签名里(零改)。
17
- *
18
- * 依赖单向:`batch-segment-vocab ← batch-skeleton ← …(gate ∥ closeout ∥ reopen ∥ lifecycle)← 本档 ← batch.mjs`
19
- * (本档不 import `batch.mjs`,两条 action 的调用者只在原档的分发里)。
9
+ * 依赖单向:`batch-segment-vocab ← batch-skeleton ← …(gate ∥ closeout ∥ reopen ∥ lifecycle)← 本档 ← batch.mjs`。
20
10
  */
21
11
  import { readFileSync, writeFileSync } from "node:fs"
22
12
  import { DEPTH0_SEGMENTS, ROUND_HEADING_RE, SEGMENT_BY_ROLE, SEGMENT_BY_ROLE_NORMAL, STATUS_LINE_RE, findPlaceholderResidue, firstZoneStatusLineRange, goAheadEndLine, goAheadReceiptLine, nextRoundNumber, placeholderResidueError, readBatchStatusLine, reviewWritableSegment, sectionHeaderRe, sectionThreeDesignTrackError, statusDonePlan, statusPassPlan, statusResetPlan, updateSectionStatusLine, verdictGapOf, zoneStatusCount } from "./batch-skeleton.mjs"
@@ -24,19 +14,17 @@ import { batchDocBases, resolveBatchDocPath } from "./batch-paths.mjs"
24
14
  import { gateReceiptLine, gateRefusalMessage, runBatchGate } from "./batch-gate.mjs"
25
15
  import { assertSectionFiveGate } from "./batch-closeout.mjs"
26
16
  import { findInFlightBatch } from "./batch-lifecycle.mjs"
27
- // 日期戳单源(`todayLocal`——重开 §1 状态行与本节留痕行同一枚,日期口径只一处)。
28
17
  import { todayLocal } from "./batch-reopen.mjs"
29
18
 
30
- /** text 单次上限(BATCH-RECORD.md §4.1——超出引导分段追加,不承诺"不新盖戳")。append 迁移域私有区常量
31
- * (随执行体自 batch-segment.mjs 迁入——骨架档只住骨架/状态行单源,lifecycle 档头枚举口径)。 */
19
+ /** text / newText 单次上限(BATCH-RECORD.md §4.1)。 */
32
20
  export const MAX_TEXT_CHARS = 20000
33
- /** 凭证形态(`BATCH-RECORD.md` §4.1——三形):`[DESIGN-TOKEN:…]` 闭括号形 ∥ `designId: …` 键形 ∥ 无标两段
34
- * token 值形 `⟨uuid⟩:⟨epoch⟩`(与单源 `design-token.mjs` 判据对表);裸 uuid 非凭证不剥(KD-7)。两字面勿
35
- * 合并:`CRED_RE` 走 `.replace()` 须 `/g` ∥ `CRED_TEST_RE` 逐行 `.test()` 须非 `/g`(lastIndex 有状态会漏剥)。 */
21
+ /** action:"update" 单次调用允许的最大条目数(覆盖六段 + 同段多处编辑,防异常巨包)。 */
22
+ export const MAX_UPDATE_ENTRIES = 20
23
+ /** 凭证形态(`BATCH-RECORD.md` §4.1——三形):两字面勿合并(`CRED_RE` 走 `.replace()` 须 `/g`,`CRED_TEST_RE` 逐行 `.test()` 须非 `/g`)。 */
36
24
  const CRED_RE = /\[DESIGN-TOKEN:[^\]]*\]|designId\s*:\s*\S+|[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}:\d{10,16}/g
37
25
  const CRED_TEST_RE = /\[DESIGN-TOKEN:[^\]]*\]|designId\s*:\s*\S+|[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}:\d{10,16}/
38
26
 
39
- // ─── append 迁移面(原 batch-segment.mjs 的 append 私有区——逐字迁移,错误串逐字保序)───
27
+ // ─── 共用校验与定位助手 ─────────────────────────────────────────────────────
40
28
 
41
29
  /** 段号解析:`§2` / `2` / `§2 批次任务` 均可;无法解析 → null。 */
42
30
  function segmentNumber(raw) {
@@ -44,30 +32,21 @@ function segmentNumber(raw) {
44
32
  return m ? Number(m[1]) : null
45
33
  }
46
34
 
47
- /** 身份 → 可写段号;无写权身份 → null。评审实例绑定优先(评审者的身份即"设计评审"),**评审轨那一维就在这里判**
48
- * (`BATCH-RECORD.md` §4.3:两张面判同一对输入——模式 × 评审轨):工程模式**设计轨** ⇒ null(`§3` 只由结算写),
49
- * 工程**代码轨**与普通模式 ⇒ 3。
50
- * depth-0 的段白名单(append——模式感知,§4.16)由 appendBatchRecord 分支,不经本表;
51
- * 普通模式分支额外合并 coder 增表(`SEGMENT_BY_ROLE_NORMAL`——**合并查只在普通模式分支**)。 */
35
+ /** 身份 → 可写段号;无写权身份 → null。工程设计轨的评审实例返回 null(§4.4 只读)。 */
52
36
  function allowedSegment(agent, review, engineering, reviewTrack) {
53
37
  if (review) return reviewWritableSegment(engineering, reviewTrack)
54
38
  const role = agent?._role
55
39
  return SEGMENT_BY_ROLE[role] ?? (engineering ? null : SEGMENT_BY_ROLE_NORMAL[role]) ?? null
56
40
  }
57
41
 
58
- /** 无写权身份拒串(`append` 与 `edit` 共用一条——两动作读同一张段白名单,同一件事不各写一份串)。 */
42
+ /** 无写权身份拒串(`append` / `edit` / `update` 共用)。 */
59
43
  function noSegmentError(engineering) {
60
44
  return engineering
61
45
  ? "batch_segment: no segment is writable by this caller — the channel exists for eng-designer (§2), eng-coder (§5) and design reviews bound to a batch record (§3); the parent agent writes §1/§4/§6 through ordinary document writes."
62
46
  : "batch_segment: no segment is writable by this caller — the channel exists for eng-designer (§2), eng-coder (§5) and design reviews bound to a batch record (§3); in normal mode the parent agent writes §1/§2/§4/§5/§6 through ordinary document writes."
63
47
  }
64
48
 
65
- /**
66
- * 凭证剥除 + 伪造轮次标题丢弃(BATCH-RECORD.md §4.1 F6/AC30/AC34)。
67
- * 逐行处理:含凭证形态的行 → 剥除该子串,剥后为空则整行丢弃(其余内容逐字保留)。
68
- * `dropStamp`(仅 §3 目标段):调用方自带的 `### 轮次 N(评审子代理)` 行被丢弃——
69
- * 工具生成才是唯一来源戳(否则伪造戳会污染 N 计数)。
70
- */
49
+ /** 凭证剥除 + 伪造轮次标题丢弃(BATCH-RECORD.md §4.1 F6/AC30/AC34)。 */
71
50
  function sanitizeText(text, dropStamp) {
72
51
  const kept = []
73
52
  for (const line of text.replace(/\r\n?/g, "\n").split("\n")) {
@@ -79,10 +58,7 @@ function sanitizeText(text, dropStamp) {
79
58
  return kept.join("\n")
80
59
  }
81
60
 
82
- /** 段尾定位 + 插入(append-only:只在段尾插入,既有字节不变;返回新全文 + 本轮 N)。
83
- * `blockLead`(仅 §3——打回重置的留痕行):落在**工具戳标题之后、评审正文之前**——与
84
- * `### 轮次 N(评审子代理)` 同属工具戳面,append-only 不变。
85
- */
61
+ /** 段尾定位 + 插入(append-only;仅 §3 盖工具轮次戳)。 */
86
62
  function insertIntoSection(src, seg, text, blockLead = "") {
87
63
  const hdr = sectionHeaderRe(seg).exec(src)
88
64
  if (!hdr) throw new Error(missingSectionError(seg))
@@ -90,8 +66,6 @@ function insertIntoSection(src, seg, text, blockLead = "") {
90
66
  nextRe.lastIndex = hdr.index + hdr[0].length
91
67
  const next = nextRe.exec(src)
92
68
  const endIdx = next ? next.index : src.length
93
- // 来源戳(仅 §3):工具生成标题 + N——调用方写不进自己的标题(sanitize 已丢弃同名行)。
94
- // N 的单源 = `nextRoundNumber`(= `countRoundBlocks + 1`)——留痕行的「第 N 轮」同取这一枚。
95
69
  const roundN = seg === 3 ? nextRoundNumber(src, 3) : 0
96
70
  const stamp = seg === 3 ? `### 轮次 ${roundN}(评审子代理)\n\n` + (blockLead ? `${blockLead}\n\n` : "") : ""
97
71
  const payload = stamp + text
@@ -99,279 +73,129 @@ function insertIntoSection(src, seg, text, blockLead = "") {
99
73
  const after = src.slice(endIdx)
100
74
  const eol = src.includes("\r\n") ? "\r\n" : "\n"
101
75
  const lead = before === "" ? "" : before.endsWith(eol + eol) ? "" : before.endsWith(eol) ? eol : eol + eol
102
- // 尾随 eol 恒加(块自成行);后面还有段标题时再补一个空行(保持模板的空行分隔)。
103
76
  const written = before + lead + payload.replaceAll("\n", eol) + eol + (after === "" ? "" : eol) + after
104
77
  return { written, roundN }
105
78
  }
106
79
 
107
- /**
108
- * append 执行体(action=append——原 batch_segment execute 迁移 + depth-0 分支):
109
- * - 段白名单(**模式感知**——§4.16):depth-0 工程 → §1/§4/§6(新错误面,"batch:" 前缀)∥
110
- * depth-0 普通 → §1/§2/§4/§5/§6(模式化新串);eng-designer → §2 · 评审 → §3(**工程设计轨除外**:
111
- * 那一路的 §3 只由结算写,本面直接拒——§4.4)· eng-coder → §5 · coder(普通模式分支增表)→ §5
112
- * (迁移错误面,"batch_segment:" 前缀**逐字保持**);
113
- * - 目标定位(D-BR21):depth-0 path 可选(缺省 = findInFlightBatch 唯一在飞批);子代理/评审
114
- * 传 path ⇒ 拒,目标 = spawn/实例绑定;
115
- * - 其余(gate / text 校验 / 剥凭证 / 骨架保护 / **状态行拒写(J3——行首形态行不得入档,§4.21.4)** /
116
- * **死占位机检(F11-C)** / 插入(候选全文成形 = 盘上现文 + 这一段 + **状态行改写(§4.12 被动写:
117
- * `§3` 随裁定行置位 ∥ 重置,`§2`/`§5` 写正文即置完成词)**) / **文档机检门
118
- * (§3.20 结构兜底 ①——**全部 append 同挂**(含 depth-0 与评审写 §3):判的是候选全文里这一笔写的行
119
- * (判面单源 = `docs/core/design/DOC-CHECK.md` §6「写时点怎么取区间」),命中 ⇒ 拒写且零字节(写盘在门之后),
120
- * ERROR ⇒ 写 + 回执明示;批档已落段不再入判)** / 写盘 / 记账 / 回执)逐字保持原语义(新增的一道 = 状态行拒写)。
121
- */
122
- export function appendBatchRecord({ args, ctx, review, reviewTrack, batchDoc, onWritten }) {
123
- const agent = ctx?.agent ?? {}
124
- const cwd = agent.cwd
125
- const depth0 = ctx?.depth === 0
126
- // 模式位执行期实读(§4.16——同款先例 = task.mjs execute 门;翻转即时生效——D-BR26)
127
- const engineering = !!agent?.config?.agent?.engineering
128
- const seg = allowedSegment(agent, review, engineering, reviewTrack)
129
- if (!depth0 && seg === null) {
130
- // 评审实例被拒时点名真因(§4.4 只读);其余无写权身份给段白名单那句。
131
- if (review) throw new Error(sectionThreeDesignTrackError("batch_segment"))
132
- throw new Error(noSegmentError(engineering))
133
- }
134
- const n = segmentNumber(args?.segment)
80
+ /** 段体字符区间(`## §N` 标题行尾之后 → 下一 `## §N` 段头之前;段头缺失 ⇒ null)。 */
81
+ function sectionBodySpan(src, seg) {
82
+ const hdr = sectionHeaderRe(seg).exec(src)
83
+ if (!hdr) return null
84
+ const nextRe = /^## §\d/gm
85
+ nextRe.lastIndex = hdr.index + hdr[0].length
86
+ const next = nextRe.exec(src)
87
+ const end = next ? next.index : src.length
88
+ const nl = src.indexOf("\n", hdr.index)
89
+ return { start: nl < 0 || nl + 1 > end ? end : nl + 1, end }
90
+ }
91
+
92
+ /** 校验调用者写权 + 解析目标段号(append / edit / update 共用,保留原有逐字错误串)。 */
93
+ function assertWritableSegment({ rawSegment, depth0, engineering, ownSeg, op }) {
94
+ const n = segmentNumber(rawSegment)
135
95
  if (n === null) {
136
96
  if (depth0) {
97
+ 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.`)
99
+ }
137
100
  throw new Error(engineering
138
- ? `batch: unknown segment ${JSON.stringify(args?.segment ?? null)} — depth-0 append writes §1/§4/§6 of the in-flight record (pass the section number you write, e.g. "§4").`
139
- : `batch: unknown segment ${JSON.stringify(args?.segment ?? 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").`)
101
+ ? `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").`)
140
103
  }
141
- throw new Error(`batch_segment: unknown segment ${JSON.stringify(args?.segment ?? null)} — pass the section number you write (e.g. "§${seg}").`)
104
+ throw new Error(`batch_segment: unknown segment ${JSON.stringify(rawSegment ?? null)} — pass the section number you write (e.g. "§${ownSeg}").`)
142
105
  }
143
106
  if (depth0) {
144
107
  const domain = engineering ? DEPTH0_SEGMENTS.append.engineering : DEPTH0_SEGMENTS.append.normal
145
108
  if (!domain.includes(n)) {
109
+ if (op === "edit") {
110
+ throw new Error(engineering
111
+ ? `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.`)
113
+ }
146
114
  throw new Error(engineering
147
115
  ? `batch: §${n} is not yours to write — depth-0 append writes §1/§4/§6 only (一段一作者: §2 = eng-designer, §3 = design review, §5 = eng-coder).`
148
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.`)
149
117
  }
150
- } else if (n !== seg) {
151
- throw new Error(`batch_segment: §${n} is not yours to write — this caller writes §${seg} only (一段一作者: eng-designer → §2, design review → §3, eng-coder → §5).`)
118
+ } else if (n !== ownSeg) {
119
+ 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).`)
152
120
  }
153
- // 目标定位(D-BR21)——path 拒面先于绑定解析(与 status 同序:段白名单 → path 门 → 取值)。
121
+ return n
122
+ }
123
+
124
+ /** 目标定位(D-BR21)——depth-0 认可选 path 或唯一在飞批;子代理/评审禁传 path、取绑定。 */
125
+ function resolveWriteTarget({ args, depth0, cwd, batchDoc }) {
154
126
  const givenPath = typeof args?.path === "string" && args.path.trim() ? args.path : null
155
- let abs
156
127
  if (givenPath) {
157
128
  if (!depth0) {
158
129
  throw new Error("batch: path is a depth-0-only parameter (D-BR21) — your target record arrives via the spawn binding / the review instance key. Nothing was written.")
159
130
  }
160
- abs = resolveBatchDocPath(cwd, givenPath)
161
- } else if (depth0) {
162
- abs = findInFlightBatch(cwd, batchDocBases(cwd)) // 歧义锚 ⇒ 基底 = 候选并集(#828——唯一在飞批照取 / ≥2 照列)
163
- } else {
164
- if (!batchDoc) {
165
- throw new Error("batch_segment: no batch record is bound to this caller — there is no path parameter by design (the target arrives via the spawn binding / the review instance key). Report the section as not written.")
166
- }
167
- abs = resolveBatchDocPath(cwd, batchDoc)
131
+ return resolveBatchDocPath(cwd, givenPath)
132
+ }
133
+ if (depth0) return findInFlightBatch(cwd, batchDocBases(cwd))
134
+ if (!batchDoc) {
135
+ throw new Error("batch_segment: no batch record is bound to this caller — there is no path parameter by design (the target arrives via the spawn binding / the review instance key). Report the section as not written.")
168
136
  }
137
+ return resolveBatchDocPath(cwd, batchDoc)
138
+ }
139
+
140
+ /** 读盘并做记录级前置守卫(冻结 / 状态行不可解析)。 */
141
+ function readOpenRecord(abs) {
169
142
  const src = readFileSync(abs, "utf8")
170
143
  const status = readBatchStatusLine(src)
171
144
  if (status === "closed") throw new Error(FROZEN_RECORD_ERROR)
172
145
  if (status === "unknown") throw new Error(UNRESOLVED_STATUS_ERROR)
173
- if (typeof args?.text !== "string") {
146
+ return src
147
+ }
148
+
149
+ // ─── 纯内存段变换(单笔 append / edit 与批量 update 共用单源)───────────────
150
+
151
+ /** 对内存中的记录文本应用一笔 `append`(含全部校验、净化、§5/§3 门与状态行被动写)。 */
152
+ function applyAppendInMemory(src, { n, text, engineering, date, checkResidues = true }) {
153
+ if (typeof text !== "string") {
174
154
  throw new Error("batch_segment: text must be a string (the markdown to append).")
175
155
  }
176
- if (args.text.length > MAX_TEXT_CHARS) {
177
- throw new Error(`batch_segment: text is ${args.text.length} characters — the limit is ${MAX_TEXT_CHARS} per call. Split it into multiple calls: each call becomes its own section and the round number N continues (分段追加——每次调用各成节、N 顺延).`)
156
+ if (text.length > MAX_TEXT_CHARS) {
157
+ throw new Error(`batch_segment: text is ${text.length} characters — the limit is ${MAX_TEXT_CHARS} per call. Split it into multiple calls: each call becomes its own section and the round number N continues (分段追加——每次调用各成节、N 顺延).`)
178
158
  }
179
- if (/^## §\d/m.test(args.text)) throw new Error(SKELETON_GUARD_ERROR)
180
- // J3(§4.21.4 写面第一道——`append` 是唯一还开着的入口:`edit` 早拒「引入状态行」,`append` 没有):
181
- // 段尾追加的正文落在段头区内时(该段还没有 `^#{2,}` 行时整个段体都是段头区),一条手写行就成了第二条。
182
- // 判定面 = 原始 `text`(剥凭证之前):「行首」即 `STATUS_LINE_RE` 的 `^\s*\*\*状态行\*\*[::]`——
183
- // 块引用 `> …` 与表格行 `| …` 天然不命中(拒串直接给这两种写法)。位次 = 骨架保护之后、剥凭证之前(拒 = 零字节)。
184
- if (args.text.split(/\r?\n/).some((line) => STATUS_LINE_RE.test(line))) throw new Error(STATUS_LINE_IN_APPEND_ERROR)
185
- const body = sanitizeText(args.text, n === 3).replace(/^\n+/, "").replace(/\s+$/, "")
159
+ if (/^## §\d/m.test(text)) throw new Error(SKELETON_GUARD_ERROR)
160
+ if (text.split(/\r?\n/).some((line) => STATUS_LINE_RE.test(line))) throw new Error(STATUS_LINE_IN_APPEND_ERROR)
161
+ const body = sanitizeText(text, n === 3).replace(/^\n+/, "").replace(/\s+$/, "")
186
162
  if (!body.trim()) {
187
163
  throw new Error("batch_segment: nothing to append — the text is empty after credential stripping (credential values never reach the record).")
188
164
  }
189
- // F11-C(挂点:gate / text 校验后 · insertIntoSection 前):档头结构行死占位残留 ⇒ 拒
190
- // (段体引用豁免——判据可辨性收正,`TOOLS.md` §6.20;骨架枚举单源 = skeleton 档 TEMPLATE_PLACEHOLDERS)。
191
- const residues = findPlaceholderResidue(src)
192
- if (residues.length) throw new Error(placeholderResidueError(residues))
193
- // §5 写入门(段序门 · 设计档 §2.6 `R-G2`):实现发生在评审通过之后,序在这里判得出真假;这一门没有旁路
194
- // (`§1` 声明 §3 不适用已随声明机制退役)。
195
- if (n === 5) assertSectionFiveGate(src)
196
- // §3 写入闸(设计档 `BATCH-LEDGER-REVIEW-UNIFY.md` §2.6.1 `R-G3`——裁定行在写的时刻就要在):
197
- // 能写 §3 的只有绑本档的评审实例,它结算后即离场 ⇒ 把错误退回**还有权补那一行的人在场的那一刻**。
198
- // 判定输入 = 净化后正文 `body`(落档的就是它;每笔 §3 自成一块 ⇒ 「写前正文 ≡ 写后末块」只对 body 成立);
199
- // 判据单源 = 骨架档 `verdictGapOf`(与 §5 门判据 2 ∥ 签发面同一个函数)。
200
- // 放行面 = **只拒两格**(`无裁定行` ∥ `两者同携`):判打回的一笔(`VERDICT: changes-required` ∥ `结论:不通过`)
201
- // 照写——§5 门判据 2 与打回重置都靠那一块自带打回裁定;拦它 = 把打回这条业务路堵死。
202
- // 位次 = 既有拒因之后、文档机检门之前(拒 = 零字节落盘、轮次号不消耗——N 在 insertIntoSection 时才取)。
165
+ if (checkResidues) {
166
+ const residues = findPlaceholderResidue(src)
167
+ if (residues.length) throw new Error(placeholderResidueError(residues))
168
+ }
169
+ if (n === 5 && engineering) assertSectionFiveGate(src)
203
170
  if (n === 3) {
204
171
  const gap = verdictGapOf(body)
205
172
  if (gap === "无裁定行" || gap === "两者同携") throw new Error(SECTION3_VERDICT_GAP_ERROR)
206
173
  }
207
- // 裁定行 → 状态行(BLRU §2.5——**工具被动写**,两个方向共用同一处判定与同一条写入路径):
208
- // 打回即重置(三合取:本笔写 §3 ∧ 本笔命中打回裁定行 ∧ 写前 §3 状态行 = 评审通过)⇒ 本轮块首留痕行
209
- // (随 `blockLead` 进插入)+ 状态行重置;通过即置位(本笔写 §3 ∧ 本笔命中 pass 裁定行且不命中打回行 ∧
210
- // 写前 §3 状态行 ≠ 评审通过)⇒ 状态行置成评审通过,无留痕行(块本身即记录)。
211
- // 两条靠各自的三合取天然互斥;`??` 的左先右后与签发面 `verdictGateFailure` 同序(先打回、后 pass)。
212
- // 状态行仍**只经 `updateSectionStatusLine` 这一个写入函数**改写(不新开第二条写路径);仍是
213
- // 一次 `writeFileSync`——块与字进的是同一个字符串(无「块已落、字未到」的窗口)。
214
- // 留痕行不经文档机检门——门位在上面(判集 = 本次评审正文 `pending.body`)。
215
- const date = todayLocal()
216
174
  const plan = statusResetPlan(src, n, body, date) ?? statusPassPlan(src, n, body, date)
217
175
  const { written: inserted, roundN } = insertIntoSection(src, n, body, plan?.traceLine ?? "")
218
- // 状态行进同一笔(`BATCH-RECORD.md` §4.12 ∥ §4.21):§3 按裁定置位 ∥ 重置(两条计划,三合取互斥);
219
- // §2/§5 按正文置完成词(`statusDonePlan`——正文只有占位行 ⇒ 段仍判空 ⇒ 零写);
220
- // §1/§4/§6 不动。仍是**一次** `writeFileSync`——块与字进的是同一个字符串(无「块已落、字未到」的窗口)。
221
176
  const done = plan ? null : statusDonePlan(inserted, n)
222
177
  const written = plan
223
178
  ? updateSectionStatusLine(inserted, n, plan.statusValue)
224
179
  : done ? updateSectionStatusLine(inserted, n, done.statusValue) : inserted
225
- // 文档机检门(§3.20「结构兜底」①——门位 = 既有拒因全部之后、写入之前):
226
- // **工程模式 append 同挂**(§1–§6,含 depth-0 与评审写 §3——规则一条,不按身份分支);普通模式跳过内容门。
227
- // `pending.body` = **候选全文**(`written`:盘上现文加上这一段及其状态行改写的整档视图)——门拿它与盘上现文两份
228
- // 求变更区,判的就是这一笔写的行(判面单源 = `docs/core/design/DOC-CHECK.md` §6「写时点怎么取区间」)。
229
- // 交半段文本就与盘上现文不同形,求出来的区间不是这一笔的行。REFUSED ⇒ throw(零字节落盘——`writeFileSync` 在门之后);
230
- // PASS ⇒ 照写;ERROR / 门自身异常 ⇒ 写 + 回执明示。
231
- const gate = ctx.agent?.config?.agent?.engineering === false ? null : runBatchGate({ abs, cwd, agent, scope: "writer", pending: { section: n, body: written } })
232
- if (gate?.state === "refused") throw new Error(gateRefusalMessage(gate, "append"))
233
- writeFileSync(abs, written)
234
- // #84:记账面按端注入(缺省 no-op = CLI 语义零行为变——端装配经 configureBatchSegment 覆盖,缝住 `batch.mjs`)。
235
- // 本条 = `AGENT-LOOP.md` §7.1 `wrote` 判据的计数面(成功写盘才增;上面各门已过)。
236
- agent._batchWrites = (agent._batchWrites ?? 0) + 1
237
- onWritten?.(agent, abs)
238
- return `batch_segment: appended ${body.length} characters to §${n} of the batch record${roundN ? ` (### 轮次 ${roundN}(评审子代理))` : ""}.${done ? ` §${n} 状态行 = ${done.statusValue}(同笔置位——不另调 status).` : ""}${n === 1 ? `${goAheadReceiptLine(written)}${goAheadEndLine(src, written)}` : ""}${gateReceiptLine(gate)}`
180
+ return { written, bodyLen: body.length, roundN, done }
239
181
  }
240
182
 
241
- // ─── 拒串单源(append / edit 共用——两动作只差写法,不差判据)───────────────
242
-
243
- /** 拒串:`§3` 写入闸(`R-G3` 逐字 = `docs/core/design/BATCH-LEDGER-REVIEW-UNIFY.md` §2.6.1)——一笔 `§3` 追加读成
244
- * 「无裁定行」∥「两者同携」⇒ 拒写(零字节落盘、轮次号不消耗)。两个裁定词**内联在同一句里,不各占独立一行**:
245
- * 各占一行时这段拒文自己就读成「两者同携」,把拒文原样引用并另写一行裁定的一笔仍被拒——想解释这道闸的人恰被
246
- * 它挡在门外;缩进 ∥ 列表符同样不取(照抄的行不命中整行锚 ⇒ 补的那行永不生效)。混形反例与「不消耗轮次号」照留。 */
247
- const SECTION3_VERDICT_GAP_ERROR = "batch_segment: §3 append refused — this round block states no readable verdict (块内裁定 = 无裁定行 | 两者同携). A §3 block must carry exactly one verdict as a line of its own; put exactly one of `VERDICT: pass` ∥ `VERDICT: changes-required` on such a line in the text you append — copying this refusal verbatim copies the words, not a verdict line.\n(本地化整行形 `结论:通过` / `结论:不通过` 同认,中文形的尾句号可省可带(`结论:通过。` 同认)。不作独立整行的写法不认——例如 `**结论** = VERDICT: pass`。) Nothing was written — no bytes landed and no round number was consumed: append the same text again with the verdict line added."
248
- /** 拒串:已收口档(§4.9 门 ②——append / edit / status 共用一条,串逐字含「已收口档不回改」)。 */
249
- const FROZEN_RECORD_ERROR = "batch_segment: 已收口档不回改 — the bound batch record's §1 status line contains 「已收口」, so the record is frozen: its body is never written to again (整档冻结;改 = 新批新档). Nothing was written. Report the section as not written."
250
- /** 拒串:§1 状态行不可解析或缺失(fail-closed 视为冻结——与冻结门同一条解析器)。 */
251
- const UNRESOLVED_STATUS_ERROR = "batch_segment: 状态行不可解析或缺失 — the bound batch record has no §1 `**状态行**:` line inside the section header zone whose value contains 已收口 or 进行中 (fail-closed: the write is refused as if frozen). If the record does carry such a line further down — in a round block or in the section body — move it up under `## §1`: a status line outside the header zone is never read. Nothing was written. Do NOT close the record after a refused append — nothing landed, and closing freezes the missing section for good (失败 ⇒ 勿 close)."
252
- /** 拒串:段标题缺失(create 是骨架唯一权威入口,append / edit 都不补骨架)。 */
253
- const missingSectionError = (seg) => `batch_segment: the bound batch record has no "## §${seg}" section header — the six-section skeleton is written by the record's creator before any segment write. Fix: ask the parent/creator to add the "## §${seg} …" heading (with the template's sub-headings) first, then call batch_segment again. Nothing was written.`
254
- /** 拒串:骨架保护(写入文本 ∥ 替换文本含 `## §N` 段头形态 ⇒ 段定位失效——append / edit 共用)。
255
- * 两个动作都不许把段头写进段体:段定位靠 `## §N` 标题,写进去就把定位面改掉(§4.1 fail-closed 行)。 */
256
- const SKELETON_GUARD_ERROR = "batch_segment: the text contains a section header line matching `^## §N` — that would break section location. Rewrite it (escape the heading, or drop the leading `## §N`), then call again (骨架保护). Nothing was written. Do NOT close the record after a refused append — nothing landed, and closing freezes the missing section for good (失败 ⇒ 勿 close)."
257
- /** 拒串:edit 的锚触及**受保护行** ∥ 替换引入一条 `**状态行**:` 行(§4.19 锚判据 + §4.21.2——保护面是段头区内
258
- * 第一个形态行〔位置义〕,不是“任何状态行”;串逐字 = `TOOLS.md` §6.24 ⑤ E5,未改)。 */
259
- const EDIT_STATUS_LINE_ERROR = "batch: edit would rewrite or introduce a **状态行** line — that line has exactly one writer: status, with a value from the section's word list. Nothing was written."
260
- /** 拒串:edit 空锚(E1——空锚的命中计数不会 ≥2,按「恰一次」会放行并插在段首)。 */
261
- const EDIT_BLANK_ANCHOR_ERROR = "batch: edit needs a non-empty oldText — a blank anchor cannot match exactly once. Nothing was written."
262
- /** 拒串:edit 的 newText 缺参 / 非串(`type: string` 的 fail-closed 面——缺参若当空串处理就是静默删区间)。 */
263
- const EDIT_NO_TEXT_ERROR = "batch: newText must be a string — pass an empty string to delete the anchored range. Nothing was written."
264
- /** 拒串:edit 的 `newText` 单次超限(§4.21.1 第二道门——上限与 `append` **同一条**:一个通道能装下的,
265
- * 另一个不能装;上限常量复用 `MAX_TEXT_CHARS`,不另立第二个数)。 */
266
- const EDIT_TEXT_OVER_LIMIT_ERROR = `batch: edit newText is over the ${MAX_TEXT_CHARS}-character single-call limit — the same cap append enforces (one write channel must not carry what the other refuses). Split it into several edits: each call replaces one anchored range. Nothing was written.`
267
- /** 拒串:edit 把一条状态行**顶进**段头区(§4.21.2 第二道——改写后区内条数不得多于改写前)。
268
- * 它堆的是「删掉隔在中间的子标题、把段体那条顶进区」:这条路一个字都不写状态行,却能让一条手写行
269
- * 变成**受保护行**(机器不读的副本一夜变成唯一可读行)。 */
270
- const EDIT_STATUS_LINE_PROMOTION_ERROR = (seg, before, after) => `batch: edit would promote a status line into the §${seg} header zone — the zone would hold ${after} \`**状态行**\` lines against ${before} before this edit, and a section's status is read only when the zone holds exactly one. This edit writes no status line: it moves one in by deleting the heading that fenced it off. Nothing was written. Keep the §${seg} header zone at one status line at most: delete the surplus line itself instead of the heading, or move the surplus line out of the zone.`
271
- /** 拒串:append 的 text 携行首状态行形态行(§4.21.4 写面第一道——J3:工具通道只能让形态行变少)。
272
- * 两个合法写法**内联在同一句**(不各占独立一行):拒文自己若以该形态起行,照抄拒文的一笔会被同一道闸再拒一次。 */
273
- const STATUS_LINE_IN_APPEND_ERROR = "batch_segment: append refused — the text carries a line that starts with the status-line form (行首 `**状态行**:…`), and that line has exactly one writer: status (J3: the tool channel may only make status-line rows fewer, never more). Nothing was written. Two legal ways: quote it instead — start the line with `> ` (块引用) — or rewrite it as prose that does not begin with that form; to change a section's own status line, call batch with action \"status\"."
274
-
275
- // ─── edit 面(段内就地改:`BATCH-RECORD.md` §4.19 的代码单源)─────────────────────
276
-
277
- /** 段体**字符区间**(`## §N` 标题行的行尾之后 → 下一 `## §N` 段头之前;段头缺失 ⇒ null)。
278
- * 段定位判据与 `batch-skeleton.mjs` 同源(`sectionHeaderRe` + `/^## §\d/gm`)——本档只取**偏移**。
279
- * 区间函数住这里而不进骨架档:骨架档当年已过 500 行,本批不带出助手函数(分批记录 2.4 贴线判)。 */
280
- function sectionBodySpan(src, seg) {
281
- const hdr = sectionHeaderRe(seg).exec(src)
282
- if (!hdr) return null
283
- const nextRe = /^## §\d/gm
284
- nextRe.lastIndex = hdr.index + hdr[0].length
285
- const next = nextRe.exec(src)
286
- const end = next ? next.index : src.length
287
- const nl = src.indexOf("\n", hdr.index) // 段头行余文(`## §N …` 的标题部分)不入段体
288
- return { start: nl < 0 || nl + 1 > end ? end : nl + 1, end }
289
- }
290
-
291
- /**
292
- * edit 执行体(action=edit——作者对自己那一段的**受认可通道**,不是唯一通道;判据单源 = `docs/core/design/BATCH-RECORD.md` §4.19):
293
- * 锚定区间替换——`oldText` 在**目标段段体**内恰一次命中(逐字节,含行尾)⇒ 换为 `newText`;`newText` 空串 = 删区间。
294
- * 判定与写盘**全部复用既有面**(零新写盘路径):段域 = 同模式 append 白名单(§4.1 一处单源,一张表两个动作)· path 门(D-BR21)·
295
- * 冻结拒写(§4.9 门 ②,串与 append 逐字同)· 剥凭证(同一条 `sanitizeText`;§3 另丢伪造轮次戳——§4.7 不变量 5)· 骨架保护 ·
296
- * `newText` 单次上限 ∥ F11-C 死占位(§4.21.1 两道门,与 append 同一批判据)·
297
- * 文档机检门(段长类判 `newText`、锚类判改后视图的本次替换区)· 状态行被动写(`§2`/`§5` 改后段内有正文 ⇒
298
- * 同笔置完成词,判据单源 = 骨架档 `statusDonePlan`,§4.12)· `onWrite` 记账 · 一次 `writeFileSync`。
299
- * **不跑 §5 段序门**(§4.19「段序门」行:edit 须有既有锚 ⇒ 写不出原本不存在的内容,造不出「先实施」;
300
- * 反过来在 §3 进行中时拒掉 §5 的旧行,正是本批要消的那种死锁)。
301
- * **不做整段替换**(段体实测两成超 `MAX_TEXT_CHARS`——重发全文 = 静默丢内容)∥ **不做模糊匹配**(一次近似改写 = 一次
302
- * 没人看见的错改;匹配 = 逐字节,`\r\n` 档上的 LF 锚零命中 ⇒ 拒,安全方向)。
303
- * 拒面(全 fail-closed,零字节落盘):空锚 E1 · 零命中 E2 · ≥2 命中(列命中行号)E3 · 锚越段界 E4 · 锚触及**受保护行** ∥
304
- * 替换**引入**一条形态行 E5 · 改写后段头区条数多于改写前 E5b(§4.21.2 第二道)· 骨架保护 ∥ 冻结 ∥ 段域(含工程**设计轨**的
305
- * `§3`——§4.4 只读)∥ newText 缺参 ∥ `newText` 超单次上限(§4.21.1)∥ 档头死占位残留(§4.21.1 F11-C)。
306
- */
307
- export function editBatchRecord({ args, ctx, review, reviewTrack, batchDoc, onWritten }) {
308
- const agent = ctx?.agent ?? {}
309
- const cwd = agent.cwd
310
- const depth0 = ctx?.depth === 0
311
- const engineering = !!agent?.config?.agent?.engineering
312
- // 段域(§4.19「段域」行):**= 同模式 append 白名单**——能 append 哪段就 edit 哪段,段域一处单源、一张表两个动作。
313
- // 子代理侧取身份段(§4.1:身份 → 段;含「模式 × 评审轨」那一维——工程设计轨的 §3 取到 null);
314
- // depth-0 侧取同模式 append 白名单(工程 §1/§4/§6 ∥ 普通 §1/§2/§4/§5/§6,§4.16)。
315
- const own = allowedSegment(agent, review, engineering, reviewTrack)
316
- if (!depth0 && own === null) {
317
- if (review) throw new Error(sectionThreeDesignTrackError("batch"))
318
- throw new Error(noSegmentError(engineering))
319
- }
320
- const n = segmentNumber(args?.segment)
321
- if (n === null) {
322
- throw new Error(depth0
323
- ? `batch: unknown segment ${JSON.stringify(args?.segment ?? 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.`
324
- : `batch_segment: unknown segment ${JSON.stringify(args?.segment ?? null)} — pass the section number you write (e.g. "§${own}").`)
325
- }
326
- if (depth0) {
327
- const domain = engineering ? DEPTH0_SEGMENTS.append.engineering : DEPTH0_SEGMENTS.append.normal
328
- if (!domain.includes(n)) {
329
- throw new Error(engineering
330
- ? `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.`
331
- : `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.`)
332
- }
333
- } else if (n !== own) {
334
- throw new Error(`batch_segment: §${n} is not yours to write — this caller writes §${own} only (一段一作者: eng-designer → §2, design review → §3, eng-coder → §5). Nothing was written.`)
335
- }
336
- // 目标定位(D-BR21)——与 append / status 同序:段域 → path 门 → 取值。
337
- const givenPath = typeof args?.path === "string" && args.path.trim() ? args.path : null
338
- let abs
339
- if (givenPath) {
340
- if (!depth0) {
341
- throw new Error("batch: path is a depth-0-only parameter (D-BR21) — your target record arrives via the spawn binding / the review instance key. Nothing was written.")
342
- }
343
- abs = resolveBatchDocPath(cwd, givenPath)
344
- } else if (depth0) {
345
- abs = findInFlightBatch(cwd, batchDocBases(cwd)) // 歧义锚 ⇒ 基底 = 候选并集(#828——唯一在飞批照取 / ≥2 照列)
346
- } else {
347
- if (!batchDoc) {
348
- throw new Error("batch_segment: no batch record is bound to this caller — there is no path parameter by design (the target arrives via the spawn binding / the review instance key). Report the section as not written.")
349
- }
350
- abs = resolveBatchDocPath(cwd, batchDoc)
351
- }
352
- const src = readFileSync(abs, "utf8")
353
- const status = readBatchStatusLine(src)
354
- if (status === "closed") throw new Error(FROZEN_RECORD_ERROR)
355
- if (status === "unknown") throw new Error(UNRESOLVED_STATUS_ERROR)
356
- const oldText = args?.oldText
183
+ /** 对内存中的记录文本应用一笔 `edit`(含全部锚判据、状态行保护、净化与状态行被动写)。 */
184
+ function applyEditInMemory(src, { n, oldText, newText, checkResidues = true }) {
357
185
  if (typeof oldText !== "string" || !oldText.trim()) throw new Error(EDIT_BLANK_ANCHOR_ERROR)
358
- if (typeof args?.newText !== "string") throw new Error(EDIT_NO_TEXT_ERROR)
359
- // 两道门(§4.21.1——J1:同一本档的两条写入通道过同一批骨架判据;位次 = `newText` 形态判据之后、锚解析之前):
360
- // ① 单次上限:上限只挂 `append` 时等于没有(`edit` 是另一条能装下同样内容的通道);
361
- // ② F11-C 死占位:档头仍带骨架占位 ⇒ 这本档还不是真档,`edit` 是唯一还能在这种档上落字的通道。
362
- // 两个挂点均复用既有单源(`MAX_TEXT_CHARS` ∥ `findPlaceholderResidue`)——零新常量、零新依赖。
363
- if (args.newText.length > MAX_TEXT_CHARS) throw new Error(EDIT_TEXT_OVER_LIMIT_ERROR)
364
- if (/^## §\d/m.test(args.newText)) throw new Error(SKELETON_GUARD_ERROR)
365
- const editResidues = findPlaceholderResidue(src)
366
- if (editResidues.length) throw new Error(placeholderResidueError(editResidues))
186
+ if (typeof newText !== "string") throw new Error(EDIT_NO_TEXT_ERROR)
187
+ if (newText.length > MAX_TEXT_CHARS) throw new Error(EDIT_TEXT_OVER_LIMIT_ERROR)
188
+ if (/^## §\d/m.test(newText)) throw new Error(SKELETON_GUARD_ERROR)
189
+ if (checkResidues) {
190
+ const editResidues = findPlaceholderResidue(src)
191
+ if (editResidues.length) throw new Error(placeholderResidueError(editResidues))
192
+ }
367
193
  const span = sectionBodySpan(src, n)
368
194
  if (!span) throw new Error(missingSectionError(n))
369
195
  const body = src.slice(span.start, span.end)
370
196
  const hits = []
371
197
  for (let at = body.indexOf(oldText); at >= 0; at = body.indexOf(oldText, at + 1)) hits.push(at)
372
198
  if (!hits.length) {
373
- // 零命中 vs 越段界:全档别处有 ⇒ 锚越出目标段段体(E4);全档无 ⇒ 真零命中(E2)。两者都 fail-closed:
374
- // 「删那行作废判据」若零命中放行,会报成功而一字未删——比不做更坏。
375
199
  throw new Error(src.includes(oldText)
376
200
  ? `batch: edit anchor crosses the §${n} section boundary — it starts outside the section body or reaches the next §N header, and rewriting across it would break section location. Nothing was written.`
377
201
  : `batch: edit anchor not found — oldText must match the §${n} body exactly once, byte for byte (line endings included). Nothing was written. Re-read the section and pass its current text verbatim.`)
@@ -381,37 +205,170 @@ export function editBatchRecord({ args, ctx, review, reviewTrack, batchDoc, onWr
381
205
  throw new Error(`batch: edit anchor is not unique — it matches ${hits.length} places inside §${n} (lines ${lines}). Extend the anchor until it matches once. Nothing was written.`)
382
206
  }
383
207
  const hit = hits[0]
384
- // 状态行只有一个写者(status):锚**触及受保护行**(§4.21.2「位置义」= 段头区内第一个形态行)⇒ 拒;
385
- // 锚触及**非受保护**的形态行 ⇒ 放行(`newText` 空串 = 删除惰性副本——机器不读的那行,删了不改变任何判据);
386
- // 替换**引入**一条 ⇒ 仍拒(既有判据,串逐字不变)。
387
208
  const guarded = firstZoneStatusLineRange(src, n)
388
209
  const hitStart = hit + span.start
389
210
  const hitEnd = hitStart + oldText.length
390
211
  if (guarded && hitStart < guarded.end && hitEnd > guarded.start) throw new Error(EDIT_STATUS_LINE_ERROR)
391
- if (args.newText.split(/\r?\n/).some((line) => STATUS_LINE_RE.test(line))) throw new Error(EDIT_STATUS_LINE_ERROR)
392
- // 替换文本落盘取目标档的 EOL 形(`sanitizeText` 逐行处理后以 LF 相连;同 append 的 `insertIntoSection` 口径)。
393
- // 来源戳只有工具能盖(§4.7 不变量 5)⇒ `edit §3` 的 `newText` 同 append 丢伪造轮次戳行;其余段无戳可丢。
212
+ if (newText.split(/\r?\n/).some((line) => STATUS_LINE_RE.test(line))) throw new Error(EDIT_STATUS_LINE_ERROR)
394
213
  const eol = src.includes("\r\n") ? "\r\n" : "\n"
395
- const replacement = sanitizeText(args.newText, n === 3).replaceAll("\n", eol)
214
+ const replacement = sanitizeText(newText, n === 3).replaceAll("\n", eol)
396
215
  const newBody = body.slice(0, hit) + replacement + body.slice(hit + oldText.length)
397
216
  const postEdit = src.slice(0, span.start) + newBody + src.slice(span.end)
398
- // 第二道(§4.21.2 E5b——J3 在 `edit` 面的机检形):改写后该段段头区内状态行条数**不得多于**改写前。
399
- // 堆的是「删掉隔在中间的子标题、把段体那条顶进段头区」:那条路一个字都不写状态行,却能让一条手写行
400
- // 变成受保护行。纯函数单源 `zoneStatusCount`(前后各取一次,不另写区界判断)。
401
217
  const zoneBefore = zoneStatusCount(src, n)
402
218
  const zoneAfter = zoneStatusCount(postEdit, n)
403
219
  if (zoneAfter > zoneBefore) throw new Error(EDIT_STATUS_LINE_PROMOTION_ERROR(n, zoneBefore, zoneAfter))
404
- // 状态行同笔(§4.12——与 append 同一条被动写,判据单源 `statusDonePlan`):`§2`/`§5` 改后段内有正文
405
- // ⇒ 该段状态行置完成词;`§3` 的置位归裁定计划(`edit` 不挂裁定行闸,也不置位——§4.4),其余段不动。
406
220
  const done = statusDonePlan(postEdit, n)
407
221
  const finalSrc = done ? updateSectionStatusLine(postEdit, n, done.statusValue) : postEdit
408
- // 文档机检门:工程模式的段长类判本次写入的 `newText`;锚类判改后视图 `recordView` 里的本次替换区;普通模式跳过。
409
- // 区外锚类不入判集、也不出行(判域 = 本次替换区),别让另一段的失效引文与本段互锁。REFUSED ⇒ 拒(零字节落盘)∥ ERROR ⇒ 写 + 回执明示。
410
- const gate = ctx.agent?.config?.agent?.engineering === false ? null : runBatchGate({ abs, cwd, agent, scope: "writer", pending: { section: n, body: replacement, recordView: finalSrc } })
222
+ return { finalSrc, replacement, oldLen: oldText.length, newLen: replacement.length, done }
223
+ }
224
+
225
+ // ─── 三条写动作执行体(append / edit / update)───────────────────────────────
226
+
227
+ /** 单段追加(action=append)。 */
228
+ export function appendBatchRecord({ args, ctx, review, reviewTrack, batchDoc, onWritten }) {
229
+ const agent = ctx?.agent ?? {}
230
+ const cwd = agent.cwd
231
+ const depth0 = ctx?.depth === 0
232
+ const engineering = !!agent?.config?.agent?.engineering
233
+ const seg = allowedSegment(agent, review, engineering, reviewTrack)
234
+ if (!depth0 && seg === null) {
235
+ if (review) throw new Error(sectionThreeDesignTrackError("batch_segment"))
236
+ throw new Error(noSegmentError(engineering))
237
+ }
238
+ const n = assertWritableSegment({ rawSegment: args?.segment, depth0, engineering, ownSeg: seg, op: "append" })
239
+ const abs = resolveWriteTarget({ args, depth0, cwd, batchDoc })
240
+ const src = readOpenRecord(abs)
241
+ const { written, bodyLen, roundN, done } = applyAppendInMemory(src, {
242
+ n, text: args?.text, engineering, date: todayLocal(),
243
+ })
244
+ const gate = engineering ? runBatchGate({ abs, cwd, agent, scope: "writer", pending: { section: n, body: written } }) : null
245
+ if (gate?.state === "refused") throw new Error(gateRefusalMessage(gate, "append"))
246
+ writeFileSync(abs, written)
247
+ agent._batchWrites = (agent._batchWrites ?? 0) + 1
248
+ 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)}`
250
+ }
251
+
252
+ /** 单段就地改(action=edit)。 */
253
+ export function editBatchRecord({ args, ctx, review, reviewTrack, batchDoc, onWritten }) {
254
+ const agent = ctx?.agent ?? {}
255
+ const cwd = agent.cwd
256
+ const depth0 = ctx?.depth === 0
257
+ const engineering = !!agent?.config?.agent?.engineering
258
+ const own = allowedSegment(agent, review, engineering, reviewTrack)
259
+ if (!depth0 && own === null) {
260
+ if (review) throw new Error(sectionThreeDesignTrackError("batch"))
261
+ throw new Error(noSegmentError(engineering))
262
+ }
263
+ const n = assertWritableSegment({ rawSegment: args?.segment, depth0, engineering, ownSeg: own, op: "edit" })
264
+ const abs = resolveWriteTarget({ args, depth0, cwd, batchDoc })
265
+ const src = readOpenRecord(abs)
266
+ const { finalSrc, replacement, oldLen, newLen, done } = applyEditInMemory(src, {
267
+ n, oldText: args?.oldText, newText: args?.newText,
268
+ })
269
+ const gate = engineering ? runBatchGate({ abs, cwd, agent, scope: "writer", pending: { section: n, body: replacement, recordView: finalSrc } }) : null
411
270
  if (gate?.state === "refused") throw new Error(gateRefusalMessage(gate, "edit"))
412
271
  writeFileSync(abs, finalSrc)
413
- // #84:记账面按端注入(与 append 同一条缝——缺省 no-op = CLI 语义零行为变)。
414
- agent._batchWrites = (agent._batchWrites ?? 0) + 1 // §7.1 `wrote` 判据:成功写盘计数(与 append 同一条面)
272
+ agent._batchWrites = (agent._batchWrites ?? 0) + 1
415
273
  onWritten?.(agent, abs)
416
- return `batch: edited §${n} of the batch record — replaced ${oldText.length} characters with ${replacement.length}.${done ? ` §${n} 状态行 = ${done.statusValue}(同笔置位——不另调 status).` : ""}${n === 1 ? `${goAheadReceiptLine(finalSrc)}${goAheadEndLine(src, finalSrc)}` : ""}${gateReceiptLine(gate)}`
417
- }
274
+ return `batch: edited §${n} of the batch record — replaced ${oldLen} characters with ${newLen}.${done ? ` §${n} 状态行 = ${done.statusValue}(同笔置位——不另调 status).` : ""}${n === 1 ? `${goAheadReceiptLine(finalSrc)}${goAheadEndLine(src, finalSrc)}` : ""}${gateReceiptLine(gate)}`
275
+ }
276
+
277
+ /** 解析批量更新单条目的动作名:显式 `op` 优先,缺省时按字段无歧义推断(否则 fail-closed)。 */
278
+ function resolveEntryOp(entry, idx) {
279
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
280
+ throw new Error(`batch: update entry #${idx + 1} must be an object ({ op: "append"|"edit", segment, ... }). Nothing was written.`)
281
+ }
282
+ if (entry.op === "append" || entry.op === "edit") return entry.op
283
+ if (entry.op !== undefined) {
284
+ throw new Error(`batch: update entry #${idx + 1} has unknown op ${JSON.stringify(entry.op)} — pass "append" or "edit". Nothing was written.`)
285
+ }
286
+ const hasText = entry.text !== undefined
287
+ const hasEdit = entry.oldText !== undefined || entry.newText !== undefined
288
+ if (hasText && !hasEdit) return "append"
289
+ if (hasEdit && !hasText) return "edit"
290
+ throw new Error(`batch: update entry #${idx + 1} must specify op ("append" or "edit") — could not infer unambiguously from its fields. Nothing was written.`)
291
+ }
292
+
293
+ /**
294
+ * 批量多段/多处原子更新(action=update——`BATCH-RECORD.md` §4.26):
295
+ * 按序在内存中对同一份批次档依次执行多条 `append` / `edit`,每条均走与单笔完全相同的
296
+ * 段白名单、凭证剥除、状态行保护、§3/§5 门;全部成功后再统一过一次工程文档机检门并单次落盘。
297
+ * 任一条目或机检门失败 ⇒ 抛出并附出错条目序号,零字节落盘(all-or-nothing)。
298
+ */
299
+ export function updateBatchRecord({ args, ctx, review, reviewTrack, batchDoc, onWritten }) {
300
+ const agent = ctx?.agent ?? {}
301
+ const cwd = agent.cwd
302
+ const depth0 = ctx?.depth === 0
303
+ const engineering = !!agent?.config?.agent?.engineering
304
+ const own = allowedSegment(agent, review, engineering, reviewTrack)
305
+ if (!depth0 && own === null) {
306
+ if (review) throw new Error(sectionThreeDesignTrackError("batch"))
307
+ throw new Error(noSegmentError(engineering))
308
+ }
309
+ const entries = args?.entries
310
+ if (!Array.isArray(entries) || entries.length === 0) {
311
+ throw new Error('batch: update requires a non-empty entries array (each item: { op: "append"|"edit", segment, text | oldText+newText }). Nothing was written.')
312
+ }
313
+ if (entries.length > MAX_UPDATE_ENTRIES) {
314
+ throw new Error(`batch: update received ${entries.length} entries — the limit is ${MAX_UPDATE_ENTRIES} per call. Split into smaller batches. Nothing was written.`)
315
+ }
316
+ const abs = resolveWriteTarget({ args, depth0, cwd, batchDoc })
317
+ const src = readOpenRecord(abs)
318
+ const residues = findPlaceholderResidue(src)
319
+ if (residues.length) throw new Error(placeholderResidueError(residues))
320
+
321
+ const date = todayLocal()
322
+ let cur = src
323
+ const summaries = []
324
+ const autoStatuses = new Map()
325
+ let touchedSection1 = false
326
+
327
+ for (let i = 0; i < entries.length; i++) {
328
+ const entry = entries[i]
329
+ const op = resolveEntryOp(entry, i)
330
+ let n
331
+ try {
332
+ n = assertWritableSegment({ rawSegment: entry.segment, depth0, engineering, ownSeg: own, op })
333
+ if (op === "append") {
334
+ const res = applyAppendInMemory(cur, { n, text: entry.text, engineering, date, checkResidues: false })
335
+ cur = res.written
336
+ summaries.push(`append §${n} +${res.bodyLen} chars${res.roundN ? ` (轮次 ${res.roundN})` : ""}`)
337
+ if (res.done) autoStatuses.set(n, res.done.statusValue)
338
+ } else {
339
+ const res = applyEditInMemory(cur, { n, oldText: entry.oldText, newText: entry.newText, checkResidues: false })
340
+ cur = res.finalSrc
341
+ summaries.push(`edit §${n} ${res.oldLen}→${res.newLen} chars`)
342
+ if (res.done) autoStatuses.set(n, res.done.statusValue)
343
+ }
344
+ if (n === 1) touchedSection1 = true
345
+ } catch (err) {
346
+ throw new Error(`batch: update failed at entry #${i + 1} (${op} ${entry?.segment ?? "?"}) — ${err.message}`)
347
+ }
348
+ }
349
+
350
+ const gate = engineering ? runBatchGate({ abs, cwd, agent, scope: "writer", pending: { body: cur, recordView: cur } }) : null
351
+ if (gate?.state === "refused") throw new Error(gateRefusalMessage(gate, "update"))
352
+ writeFileSync(abs, cur)
353
+ agent._batchWrites = (agent._batchWrites ?? 0) + 1
354
+ onWritten?.(agent, abs)
355
+
356
+ const statusNotes = [...autoStatuses.entries()]
357
+ .map(([segNum, val]) => ` §${segNum} 状态行 = ${val}(同笔置位——不另调 status).`)
358
+ .join("")
359
+ return `batch: updated ${entries.length} ${entries.length === 1 ? "entry" : "entries"} in the batch record (${summaries.join("; ")}).${statusNotes}${touchedSection1 ? `${goAheadReceiptLine(cur)}${goAheadEndLine(src, cur)}` : ""}${gateReceiptLine(gate)}`
360
+ }
361
+
362
+ // ─── 拒串单源(append / edit / update 共用)─────────────────────────────────
363
+
364
+ const SECTION3_VERDICT_GAP_ERROR = "batch_segment: §3 append refused — this round block states no readable verdict (块内裁定 = 无裁定行 | 两者同携). A §3 block must carry exactly one verdict as a line of its own; put exactly one of `VERDICT: pass` ∥ `VERDICT: changes-required` on such a line in the text you append — copying this refusal verbatim copies the words, not a verdict line.\n(本地化整行形 `结论:通过` / `结论:不通过` 同认,中文形的尾句号可省可带(`结论:通过。` 同认)。不作独立整行的写法不认——例如 `**结论** = VERDICT: pass`。) Nothing was written — no bytes landed and no round number was consumed: append the same text again with the verdict line added."
365
+ const FROZEN_RECORD_ERROR = "batch_segment: 已收口档不回改 — the bound batch record's §1 status line contains 「已收口」, so the record is frozen: its body is never written to again (整档冻结;改 = 新批新档). Nothing was written. Report the section as not written."
366
+ const UNRESOLVED_STATUS_ERROR = "batch_segment: 状态行不可解析或缺失 — the bound batch record has no §1 `**状态行**:` line inside the section header zone whose value contains 已收口 or 进行中 (fail-closed: the write is refused as if frozen). If the record does carry such a line further down — in a round block or in the section body — move it up under `## §1`: a status line outside the header zone is never read. Nothing was written. Do NOT close the record after a refused append — nothing landed, and closing freezes the missing section for good (失败 ⇒ 勿 close)."
367
+ const missingSectionError = (seg) => `batch_segment: the bound batch record has no "## §${seg}" section header — the six-section skeleton is written by the record's creator before any segment write. Fix: ask the parent/creator to add the "## §${seg} …" heading (with the template's sub-headings) first, then call batch_segment again. Nothing was written.`
368
+ const SKELETON_GUARD_ERROR = "batch_segment: the text contains a section header line matching `^## §N` — that would break section location. Rewrite it (escape the heading, or drop the leading `## §N`), then call again (骨架保护). Nothing was written. Do NOT close the record after a refused append — nothing landed, and closing freezes the missing section for good (失败 ⇒ 勿 close)."
369
+ const EDIT_STATUS_LINE_ERROR = "batch: edit would rewrite or introduce a **状态行** line — that line has exactly one writer: status, with a value from the section's word list. Nothing was written."
370
+ const EDIT_BLANK_ANCHOR_ERROR = "batch: edit needs a non-empty oldText — a blank anchor cannot match exactly once. Nothing was written."
371
+ const EDIT_NO_TEXT_ERROR = "batch: newText must be a string — pass an empty string to delete the anchored range. Nothing was written."
372
+ const EDIT_TEXT_OVER_LIMIT_ERROR = `batch: edit newText is over the ${MAX_TEXT_CHARS}-character single-call limit — the same cap append enforces (one write channel must not carry what the other refuses). Split it into several edits: each call replaces one anchored range. Nothing was written.`
373
+ const EDIT_STATUS_LINE_PROMOTION_ERROR = (seg, before, after) => `batch: edit would promote a status line into the §${seg} header zone — the zone would hold ${after} \`**状态行**\` lines against ${before} before this edit, and a section's status is read only when the zone holds exactly one. This edit writes no status line: it moves one in by deleting the heading that fenced it off. Nothing was written. Keep the §${seg} header zone at one status line at most: delete the surplus line itself instead of the heading, or move the surplus line out of the zone.`
374
+ const STATUS_LINE_IN_APPEND_ERROR = "batch_segment: append refused — the text carries a line that starts with the status-line form (行首 `**状态行**:…`), and that line has exactly one writer: status (J3: the tool channel may only make status-line rows fewer, never more). Nothing was written. Two legal ways: quote it instead — start the line with `> ` (块引用) — or rewrite it as prose that does not begin with that form; to change a section's own status line, call batch with action \"status\"."