@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
@@ -3,12 +3,13 @@
3
3
  * 单一工具三操作(用户定形 F-CC5):`stats`(感知 F-CC1)· `prune`(噪声清理 F-CC3)· `compact`(主动压缩 F-CC2,携 focus + 自动附任务/目标 + 可回查锚——裁令 A/D)。
4
4
  * 描述外置(tool-docs/context.md——#15 统一面:文本单点 = tool-docs,DESC 加载);装配面 = 登记册 `agent-tools.mjs`(#83)+ `agent/family-tools.mjs` 的 depth-0 段(`depthOnly`)——两端自动同表;**depth>0 不给**(§6.16.6)。
5
5
  * 本档同时是**注记文案 / 轻推行 / 回执文案的单源**(核与 VSC 的 run-stages 消费点经动态 import 取用——零新增静态边)。
6
- * 机械面:`stats` 不新增第三口径(首行主口径 = 可填量占用 total / `limit`,窗口与压缩线各以具名数值呈现;状态行行(第 6 行)走核 `historyReading`——与 CLI ∥ VSC 同源:一个实现点,端侧零自算式);`prune` = 合格集(`token-window.mjs` 单源)+「原位换内容」应用面(`context-degrade.mjs`);`compact` **当次零执行**(只登记 `agent._pendingCompact`,由下一安全点消费——§6.16.2)。
6
+ * 机械面:`stats` 不新增第三口径(首行主口径 = 可填量占用 total / `limit`,窗口与压缩线各以具名数值呈现;状态行行(第 6 行)走核 `contextReading`——与 CLI ∥ VSC 同源:一个实现点,端侧零自算式);`prune` = 合格集(`token-window.mjs` 单源)+「原位换内容」应用面(`context-degrade.mjs`);`compact` **当次零执行**(只登记 `agent._pendingCompact`,由下一安全点消费——§6.16.2)。
7
7
  */
8
- import { contextUsage, estimateTokens, collectStaleToolOutputs, historyReading, tokenRatioOf, PRUNE_MIN_TOKENS } from "../token-window.mjs"
8
+ import { contextUsage, estimateTokens, collectStaleToolOutputs, contextReading, overheadSegments, tokenRatioOf, PRUNE_MIN_TOKENS } from "../token-window.mjs"
9
9
  // 预算面 = **有效窗口**(`CONTEXT-COMPACTION.md` §2.2:stats ∥ 守卫 ∥ 压缩同一个预算对象)
10
- import { policyBudget, resolveWorkMode } from "../config.mjs"
10
+ import { policyBudget } from "../config.mjs"
11
11
  import { pruneStaleToolOutputs } from "../context.mjs"
12
+ import { flattenHistory, flatIndexOf, pushInject } from "../context.mjs"
12
13
  // 保留窗起点(#2431):stats 的 prunable 读数与 prune 本体同一个合格集——两处传同一值,不自成第二套(§1.2)。
13
14
  import { retentionWindowStart } from "../agent/turn-projection.mjs"
14
15
  import { slotPath } from "../session-slots.mjs"
@@ -26,13 +27,33 @@ export function compactNoopNote() {
26
27
  return `${CONTEXT_NOTE_PREFIX} did nothing right now (no middle section — the history is too short to summarize). The context is unchanged.]`
27
28
  }
28
29
 
29
- /** 压缩 no-op 注记——固定开销单独越线(`CONTEXT-COMPACTION.md` §5):与守卫抛出的 typed error **同一个原因**,
30
- * 回执里带 `reason`、固定开销、limit 与 window 三数,并说清压缩解不了——不把方向指到会话内容上。 */
31
- export function compactOverheadNote(fixedFloor, limit, window) {
32
- return `${CONTEXT_NOTE_PREFIX} did nothing right now: the fixed overhead (system + tools) ~${fixedFloor} tokens alone` +
30
+ /** 压缩 no-op 注记——非对话面单独越线(`CONTEXT-COMPACTION.md` §5):与守卫抛出的 typed error **同一个原因**,
31
+ * 回执里带 `reason`、六项分段(`systemPrompt` ∥ `tools` ∥ `_retained` ∥ `_inject` ∥ `_sessionHead` ∥ `_pendingInject`,并点名最大那一段)、
32
+ * `fixedFloor`、limit 与 window,并说清压缩解不了——不把方向指到会话内容上。
33
+ * `usage` = `contextUsage(...)` 的返回面(六项与 `fixedFloor` 都从它取,本函数不自己累加)。
34
+ */
35
+ export function compactOverheadNote(usage, limit, window) {
36
+ const segments = overheadSegments(usage)
37
+ const listed = segments.map(([name, tokens]) => `${name} ${tokens}`).join(" · ")
38
+ const [largest, largestTokens] = segments.reduce((a, b) => (b[1] > a[1] ? b : a))
39
+ return `${CONTEXT_NOTE_PREFIX} did nothing right now: the non-conversation face alone ~${usage.fixedFloor} tokens` +
33
40
  ` exceeds the limit ${limit} (window ${window}) — reason: overhead_exceeds_limit.` +
34
- ` Compaction cannot help (the overhead stays after the history is summarized): lower max_tokens,` +
35
- ` switch to a larger-window model, or trim the system prompt / tools declaration.]`
41
+ ` Segments ~: ${listed} — largest is ${largest} (${largestTokens}).` +
42
+ ` Compaction cannot help (that face stays after the history is summarized): lower max_tokens,` +
43
+ ` switch to a larger-window model, or trim ${largest}.]`
44
+ }
45
+
46
+ /** 压缩 no-op 注记——配置矛盾(`CONTEXT-COMPACTION.md` §2.4):与守卫抛出的 typed error **同一个原因**,
47
+ * 回执带 `reason: budget_contradiction` 与矛盾三数(window ∥ reserve ∥ 差值),并把方向指到配置上(不指向会话内容——那个方向是错的)。
48
+ * `contradiction` = 预算对象上的 `{ window, reserve, usable }`(`window-policy.mjs` 的 `budgetOf` 夹点时算出的三个数)。
49
+ */
50
+ export function compactContradictionNote(contradiction) {
51
+ const c = contradiction ?? {}
52
+ const numbers = `window ${c.window} · reserve ${c.reserve} · difference ${c.usable}`
53
+ return `${CONTEXT_NOTE_PREFIX} did nothing right now: this channel's configuration has no solution — ${numbers} —` +
54
+ ` reason: budget_contradiction. Compaction cannot help: no request can be sent until the configuration changes` +
55
+ ` (raise the window via providers[].modelContext / a larger-context model, lower provider.maxTokens,` +
56
+ ` or use a model whose maxOutput is smaller than its window). The context is unchanged.]`
36
57
  }
37
58
 
38
59
  /** 压缩失败注记(§6.16.2 回执面②——模型面告知缺口)。§5.1 之后**没有「第 N 次 / 共 3 次」**:摘要在失败当次
@@ -55,46 +76,40 @@ function nudgeAnchor(agent) {
55
76
 
56
77
  /**
57
78
  * 方向转换轻推(F-CC4 · §6.16.5):task/goal 变更后直推**一行**机器行(`transient: true`,非命令)。
58
- * 去重 = **单活体行**:同前缀旧行先滤再推一行 ⇒ 任意次数变更后恒**恰一行**(in-place splice 保
59
- * 数组引用——VSC 面板持同一数组:`agent.history = <新数组>` 会让端侧局部引用失效,先例 = D-CC24
60
- * 同一顾虑)。压缩重建时该行无特殊处理(一次建议——落入中段即随摘要退场、落入 tail 则保留,良性)。
79
+ * 去重 = **单活体行**:同前缀旧条先从待发队(B 段)摘掉再推一行 ⇒ 任意次数变更后恒**恰一行**。
61
80
  * 深度门由调用方落(`ctx.depth === 0`——子代理拿不到 `context`,提示它拿不到的工具即噪音)。
62
81
  */
63
82
  export function pushContextNudge(agent) {
64
- const history = agent.history
65
- for (let i = history.length - 1; i >= 0; i--) {
66
- const m = history[i]
67
- if (m?.role === "user" && typeof m.content === "string" && m.content.startsWith(CONTEXT_NUDGE_PREFIX)) {
68
- history.splice(i, 1)
69
- }
70
- }
71
- history.push({
83
+ const queue = Array.isArray(agent._pendingInject) ? agent._pendingInject : []
84
+ agent._pendingInject = queue.filter(
85
+ (m) => !(m?.role === "user" && typeof m.content === "string" && m.content.startsWith(CONTEXT_NUDGE_PREFIX)),
86
+ )
87
+ pushInject(agent, {
72
88
  role: "user",
73
89
  content: `${CONTEXT_NUDGE_PREFIX} current objective: ${nudgeAnchor(agent)}. ` +
74
90
  `If the earlier context no longer serves this direction, you may compact it (context tool, action="compact" with a focus) — the decision is yours.]`,
75
- transient: true,
76
91
  })
77
92
  }
78
93
 
79
94
  /** stats 报面(§6.16.4 逐行定稿——机判可解析;三段 / 工具输出小计 / 状态行百分比 / 压缩履历)。 */
80
95
  function statsReport(agent) {
81
- // 档位自 agent 现取(§2.3 握有 agent 的面自取):本档三处读数(有效窗口预算 ∥ 保护尾 ∥ 状态行分母)同取它。
82
- const workMode = resolveWorkMode(agent?.config?.agent)
83
96
  const usage = contextUsage(agent, agent?._ctxBasis?.overhead ?? {})
97
+ const flat = flattenHistory(agent?.history ?? [])
98
+ const protectFrom = retentionWindowStart(agent)
84
99
  // 合格集与 prune 本体同一组实参(§2.3 表):`fixedOverhead` ∥ `ratio` 都当场现算,没有一处落盘。
85
100
  const stale = collectStaleToolOutputs(
86
- agent?.history ?? [], agent?.provider, workMode, retentionWindowStart(agent),
87
- usage.overhead, tokenRatioOf(agent),
101
+ flat, agent?.provider, protectFrom ? flatIndexOf(agent.history, protectFrom) : flat.length,
102
+ usage.fixed - usage.compactionSummary, tokenRatioOf(agent),
88
103
  )
89
104
  let toolOut = 0
90
105
  let toolCount = 0
91
- for (const m of agent?.history ?? []) {
106
+ for (const m of flat) {
92
107
  if (m?.role !== "tool") continue
93
108
  toolCount++
94
109
  toolOut += estimateTokens([m])
95
110
  }
96
111
  // 预算取一次,全行共用(§7.1「从同一 contextUsage ∥ policyBudget ∥ historyReading 取数,各自具名,不混用分母」)。
97
- const budget = policyBudget(agent?.provider, undefined, workMode)
112
+ const budget = policyBudget(agent?.provider)
98
113
  // 分母 = `limit`(用户实际可填的量,§2.5 / §7.1):与状态行第 6 行同一个数,`window` 只作具名读数出现。
99
114
  const pct = Math.round((usage.total / budget.limit) * 100)
100
115
  const toGo = Math.max(0, usage.threshold - usage.total) // 已越阈值 ⇒ 0(自动压缩将在下一安全点接手)
@@ -112,9 +127,10 @@ function statsReport(agent) {
112
127
  const cacheLine = cacheTurns === 0
113
128
  ? "Cache: no provider usage readings yet (hit/miss arrive with the first response)"
114
129
  : `Cache: hit ${cacheHit} · miss ${cacheMiss} tokens (${Math.round((cacheHit / cacheTotal) * 100)}% hit) across ${cacheTurns} response(s)`
115
- // 第 6 行 = 核读数投影(§6.16.4):`pct` 与括号内的 `calibratedHistory` 是同一次调用的两个返回值——同屏两值同尺;
116
- // 标记 `calibrated history estimate` 把它与 `Segments ≈` 行的裸估算 `history`(核 `estimateTokens`,未乘比)分名。
117
- const statusReading = historyReading(agent?.history ?? [], agent?.provider, tokenRatioOf(agent), workMode)
130
+ // 第 6 行 = 核整量读数的投影(§7.1):与状态行同一个 `contextReading`——同屏两值同尺;
131
+ // 括号内的口径词按 `basis` 取(`measured` / `estimated`),`calibrated history estimate` 随之退场——
132
+ // 声称「状态行的投影」却报另一个量,就是一句不实的话。
133
+ const statusReading = contextReading(agent, agent?._ctxBasis?.overhead ?? {})
118
134
  return [
119
135
  `Context ≈${usage.total} tokens (${pct}% of ${budget.limit} fillable limit; window ${usage.window}, compaction line ${usage.threshold} (${toGo} to the line))`,
120
136
  // §6.16.4 字面单源(该行为唯一字面,逐字;预算面同源 policyBudget——不自算第二套):
@@ -131,7 +147,7 @@ function statsReport(agent) {
131
147
  `Segments ≈: system ${usage.system} · tools ${usage.tools} · history ${usage.history} (basis: ${usage.basis})`,
132
148
  `History: tool outputs ${toolOut} tokens in ${toolCount} msgs · prunable stale ${stale.tokens} tokens in ${stale.indexes.length} msgs · protected tail ${stale.tailCount} msgs`,
133
149
  cacheLine,
134
- `Status line: context ${statusReading.pct}% (${statusReading.tokens} calibrated history estimate / ${statusReading.limit} fillable limit, compaction line ${statusReading.threshold})`,
150
+ `Status line: context ${statusReading.pct}% (${statusReading.tokens} ${statusReading.basis === "measured" ? "measured" : "estimated"} prompt tokens / ${statusReading.limit} fillable limit, compaction line ${statusReading.threshold})`,
135
151
  `Compaction so far: ${compaction} · failed attempts ${agent?._compressFailures ?? 0}`,
136
152
  ].join("\n")
137
153
  }
@@ -1,5 +1,5 @@
1
1
  /**
2
- * digest-budget.mjs — digest 注入批量预算单源(群 B 批 B5——AGENT-LOOP.md §6.14 语义源)。
2
+ * digest-budget.mjs — digest 注入批量预算单源(群 B 批 B5——AGENT-LOOP.md §9 语义源)。
3
3
  * 原预算块居 subagent-async.mjs(只覆盖经 injectAsyncResult 的三族:subagent / advisor /
4
4
  * escalate),consult 族注入器(injectConsultResult)绕过 ⇒ 多族条目同轮合并注入时可累计
5
5
  * 超限(BATCH-3-STRUCTURE F-2 原始事故面 1.3MB 请求体)。本档把常量 / 判超 / 记账 / 落盘
@@ -9,8 +9,8 @@
9
9
  * - `DIGEST_INJECT_BUDGET`(64×1024——与 offload 单条预览同量级);
10
10
  * - `digestBudgetOver(agent, size)`——判超 + 记账:`used > 0 && used + size > BUDGET`
11
11
  * 首条豁免保留(单条大报告 >64K 走 offload 预览照旧——预算只约束轮累计);轮界定
12
- * `agent.history.length !== r.len + 1` 语义逐字迁入(相邻注入间 history 无其他落史 = 同轮;
13
- * 每次注入 pushReal 恰 +1——他人落史 = 新请求窗口 → 预算复位);键 = agent(会话级复用
12
+ * 改读线尾位置 `{ turn, msg }`:注入不在线上(B 段待发队),所以线尾没变 = 同一请求窗口;
13
+ * 真有对话落线(任一层长度变了)= 新请求窗口 → 预算复位);键 = agent(会话级复用
14
14
  * ——Map 常驻一两项)。
15
15
  * - `persistOverflowReport(raw, { tag })`——超限条目全量落盘(`configDir/tool-results` +
16
16
  * `cleanupOldToolResults` 轮转;落盘名 `<ts>-<tag>.log`(tag = 溯源标签:写入族 + 条目 id
@@ -33,17 +33,18 @@ import { configDir } from "../config.mjs"
33
33
 
34
34
  export const DIGEST_INJECT_BUDGET = 64 * 1024 // 64K——与 offload 单条预览同量级
35
35
 
36
- // 轮记账:agent → { len, used }(逐字自 subagent-async.mjs 迁入——语义零变)。
36
+ // 轮记账:agent → { turn, msg, used }(位置形 = 线尾;注入不进线 ⇒ 线尾没变就是同一请求窗口)。
37
37
  const digestRounds = new Map()
38
38
  function digestRoundFor(agent) {
39
- const h = agent.history
39
+ const h = Array.isArray(agent.history) ? agent.history : []
40
+ const last = h.at(-1)
41
+ const pos = { turn: h.length - 1, msg: Array.isArray(last?.messages) ? last.messages.length : 0 }
40
42
  const r = digestRounds.get(agent)
41
- if (!r || h.length !== r.len + 1) {
42
- const fresh = { len: h.length, used: 0 }
43
+ if (!r || r.turn !== pos.turn || r.msg !== pos.msg) {
44
+ const fresh = { turn: pos.turn, msg: pos.msg, used: 0 }
43
45
  digestRounds.set(agent, fresh)
44
46
  return fresh
45
47
  }
46
- r.len = h.length
47
48
  return r
48
49
  }
49
50
 
@@ -58,7 +59,7 @@ export function digestBudgetOver(agent, size) {
58
59
  /** Test seam: 落盘目录重定向(单元测试沙箱——生产从不调用)。 */
59
60
  let _digestOffloadDirOverride = null
60
61
  export function _setDigestOffloadDirForTest(dir) { _digestOffloadDirOverride = dir }
61
- /** 缝的读取面(无参):生产恒 undefined ⇒ 消费方取各自默认目录。一条缝覆盖本档与 `offloadToolResult` 两族(TIMEOUT-DIGEST.md §2.2)。 */
62
+ /** 缝的读取面(无参):生产恒 undefined ⇒ 消费方取各自默认目录。一条缝覆盖本档与 `offloadToolResult` 两族(TIMEOUT-DIGEST.md §2)。 */
62
63
  export function _digestOffloadDirForTest() { return _digestOffloadDirOverride ?? undefined }
63
64
 
64
65
  /** 超限条目全量落盘(返回清单行文本;失败 null——调用方回退 inline——结果零丢失)。
@@ -20,6 +20,7 @@ import { clearPlanMode } from "./plan.mjs"
20
20
  import { purgeExpiredDesignTokens } from "../token-ttl.mjs"
21
21
  import { resolveEngineeringManifest } from "../manifest.mjs"
22
22
  import { resolveWorkMode, setConfigWorkMode } from "../config.mjs"
23
+ import { pushInject } from "../context.mjs"
23
24
  // 描述面 = `tool-docs/eng.md`(#15 描述外置统一——DESC 单一解析面,与内置工具族同径)
24
25
  import { DESC } from "../tools/shared.mjs"
25
26
 
@@ -64,8 +65,7 @@ export const engTool = {
64
65
  ctx.agent._advisorRuns = new Map() // AGENT-LOOP-ASYNC-POOL.md §6.10 D-24b: per-review instances die with the mode (fresh cycles)
65
66
  ctx.agent._touchedFiles = [] // clear mutation tracking
66
67
  ctx.agent._lastEngState = false
67
- ctx.agent._pendingReminders = ctx.agent._pendingReminders ?? []
68
- ctx.agent._pendingReminders.push(ENG_OFF_REMINDER)
68
+ pushInject(ctx.agent, { role: "user", content: ENG_OFF_REMINDER })
69
69
  return "Engineering mode exited. Standard discipline now applies. You may edit files directly." + await mirrorNotice(ctx.agent.config.agent.mode, ctx)
70
70
  }
71
71
  if (args.action === "enter") {
@@ -95,8 +95,7 @@ export const engTool = {
95
95
  const cleared = purgeExpiredDesignTokens(ctx.agent)
96
96
  ctx.agent._advisorRuns = new Map() // §6.10 D-24b: per-review instances die with the mode (fresh cycles)
97
97
  ctx.agent._lastEngState = true
98
- ctx.agent._pendingReminders = ctx.agent._pendingReminders ?? []
99
- ctx.agent._pendingReminders.push(ENG_ON_REMINDER)
98
+ pushInject(ctx.agent, { role: "user", content: ENG_ON_REMINDER })
100
99
  let msg = "Engineering mode activated. Design-before-code enforced: write a design document first (location per your project's document conventions), run advisor with type='design', get user approval, then implement via eng-coder subagents."
101
100
  if (cleared > 0) {
102
101
  msg += ` Cleared ${cleared} expired design token${cleared === 1 ? "" : "s"} — 清 ${cleared} 个过期 token,有效 token 保留(TTL 内不重评)。`
@@ -27,7 +27,7 @@
27
27
  import { relative, isAbsolute } from "node:path"
28
28
  import { runAgent, createAgent, DEFAULT_SUBAGENT_TURNS, excludeSubagentTools } from "../agent.mjs"
29
29
  import { runWithContinue, TURN_CAP_MARK, wrapChildCallbacks } from "../agent/spawn-child.mjs"
30
- // TUI-OOM-ROOTCAUSE·AGENT-LOOP.md §6.15:子代理人读线窗口常量(单源——store 零依赖)。
30
+ // TUI-OOM-ROOTCAUSE·AGENT-LOOP.md §9.2:子代理人读线窗口常量(单源——store 零依赖)。
31
31
  import { RECORD_WINDOW_MESSAGES } from "../session-store.mjs"
32
32
  import { logEvent } from "../log.mjs"
33
33
  import { deathLine } from "../abort-provenance.mjs"
@@ -106,7 +106,7 @@ function touchedFilesNote(child, cwd) {
106
106
  */
107
107
  export function classifyEscalateSettle(parent, entry) {
108
108
  if (entry.cancelled) return { cancelled: true }
109
- // AGENT-LOOP.md §6.15(TUI-OOM-ROOTCAUSE)——childAgent 语义面:settle 分类(touched 摘要/partial
109
+ // AGENT-LOOP-ASYNC-POOL.md §4(TUI-OOM-ROOTCAUSE)——childAgent 语义面:settle 分类(touched 摘要/partial
110
110
  // merge)与 status/observe 摘要的读取源;**消化注入完成后释放**(池内未消化窗口不释放——表 2 候选 2 否决);
111
111
  // fallback 面(无 `_daSession`)由 `releaseSettledEntry`(async-settle.mjs)置 null(逐字沿用);会话态
112
112
  // (`_daSession`)注入后改调 `releaseChildHold`(仅释放 `childAgent`——`report` 保留至销账 / 升级;
@@ -204,7 +204,7 @@ export function launchEscalateAsync(parent, ctx, launch) {
204
204
  role: "coder",
205
205
  })
206
206
  entry.childAgent = child // settle 分类/status touched 摘要绑定(start 时刻)
207
- child._historyWindow = RECORD_WINDOW_MESSAGES // TUI-OOM-ROOTCAUSE·AGENT-LOOP.md §6.15:子代理人读线窗口(四处创建点同置)
207
+ child._historyWindow = RECORD_WINDOW_MESSAGES // TUI-OOM-ROOTCAUSE·AGENT-LOOP.md §9.2:子代理人读线窗口(四处创建点同置)
208
208
  child._logId = relayPrefix.slice(0, -1)
209
209
  // SUBAGENT-UPSTREAM-CHANNEL(§6.27.4 W3——escalate **async**:工具返回注走异步形)。
210
210
  child._upstream = { parent, label: relayPrefix.slice(0, -1), sync: false }
@@ -1,5 +1,6 @@
1
1
  // F-CC4(CONTEXT-COMPACTION.md §6.16.5):goal 任一状态变更 ⇒ 方向转换轻推(本档只调用;文案/去重单源 = agent-tools/context.mjs)
2
2
  import { pushContextNudge } from "./context.mjs"
3
+ import { flattenHistory } from "../context.mjs"
3
4
  import { DESC } from "../tools/shared.mjs"
4
5
 
5
6
  /**
@@ -54,10 +55,12 @@ export const goalTool = {
54
55
 
55
56
  // Independent judge: verify the goal was actually achieved
56
57
  // Only applies when the agent is at depth 0 (not a subagent) and has history to review
57
- if (ctx.depth === 0 && agent.history.length > 2) {
58
+ // 机读线按轮嵌套:判据与取数都在拍平视图上(外层条数是轮数,不是消息数)。
59
+ const flat = flattenHistory(agent.history)
60
+ if (ctx.depth === 0 && flat.length > 2) {
58
61
  try {
59
62
  // Extract recent activity: last 4 assistant messages (summarizing what was done)
60
- const recent = agent.history.filter(m => m.role === "assistant").slice(-4)
63
+ const recent = flat.filter(m => m.role === "assistant").slice(-4)
61
64
  const activity = recent.map(m => (m.content ?? "").slice(0, 500)).join("\n---\n")
62
65
  const { chat } = await import("../provider/index.mjs")
63
66
  const judgeRes = await chat(agent.provider, {
@@ -0,0 +1,347 @@
1
+ /**
2
+ * agent-tools/judge-domain.mjs — 判域机检(命令行面)。
3
+ * 判据句单源 = `docs/core/design/PROMPT-SYSTEM.md` §10.8「机检入口」与「读法」。
4
+ *
5
+ * 用法:`node thincoder-core/agent-tools/judge-domain.mjs --doc <设计档> --record <批档>`
6
+ * 两个参数都必填,缺一个在边界拒绝并点名该参数,没有默认值。
7
+ * 调用面 = 验收对照表里跑本件的那些行(带 `--doc` 与 `--record`)与收口 `doc_check` gate。
8
+ *
9
+ * 首行 `JUDGE-DOMAIN: PASS`(其后零条问题行)或 `JUDGE-DOMAIN: REFUSED`(其后逐条问题行)。
10
+ * `## 验收对照` 节在、但一条含 `判法「` 的验收行都没有时,两行都不写——边界拒绝,点名 `--record` 的路径与「zero 验收行」:零行时 PASS 会把「一行都没判」读成「全过」。
11
+ * 它报三类问题,各一行,点名判据或验收行:
12
+ * 1. `判域行不成形 <判法名>` —— 缺 对象/排除/止于 之一,某字段重复或为空,某字段值含占位词(「视情况」「按需」,或以「等」收尾一份列举),
13
+ * 判域行条数与判法行条数不等,行首判法名对不上判法行。
14
+ * 2. `验收行指不到判据 <首句>` —— 验收行点名的判据首句,在 §10.4 的判据条目里找不到。
15
+ * 验收行整格没点名判据首句时,同一个类报成 `验收行指不到判据(未点名判据首句) —— 验收行 <# 格>`:没有首句可点,仍属这一类,不是第四类。
16
+ * 3. `验收尺带判据没有的数 <数字>` —— 判法名文本里的每个数(连写的数字算一个数),在判据正文(判法在内)里以同一个数出现至少一次。两侧都按整串数读:判据正文里的数也连写读,尺上的 4 不因正文有 45 就算出现过。
17
+ * 三类之外不多报一行:验收行带了一个判据没有的判法名,由收口逐条读(§10.8「两处不一致即缺陷」),不是机检的第四类。
18
+ *
19
+ * 读法(照 §10.8「读法」原文解析,不另立一套):
20
+ * - 判据 = §10.4 里以 `- ` 起头、条目正文含 `**判域**:` 行的条目;条目正文 = 该行之后以空白起首的续行。
21
+ * - 判据首句 = 该条目第一个 `:` 之前的文字。
22
+ * - 判法行 = 条目正文里以 `判法「<判法名>」:` 起头的行(去首尾空白后)。
23
+ * - 判域行 = 条目正文里以 `**判域**:<判法名> —— ` 起头的行,字段形 `对象 = …;排除 = …;止于 = …。`
24
+ * - 判据正文 = 判据句加条目正文;判法行与判域行都在里面(设计原话:该判据自己的正文,判法在内)。
25
+ * - 验收行 = 批档「验收对照」表里含 `判法「` 的行;数字比对面只取它那一格里 `判法「…」` 的判法名文本。
26
+ * - 判据首句是配对键:§10.4 两条判据同首句时无法配对,边界拒绝并点名该首句。
27
+ *
28
+ * 比对面:数字只取验收行内 `判法「…」` 的判法名文本;`#` 列标签、期望列与引用坐标 `design §10.4` 的段号都不参与。
29
+ * 边界:本件只判形、配对与数字来源,不判判据在语义上是否完备。
30
+ * 退出码:0 = PASS,1 = REFUSED,2 = 边界拒绝(缺参数、档读不到、两份档缺本条读法要的章节、零条验收行、§10.4 两条判据同首句)。
31
+ */
32
+ import { readFileSync } from "node:fs"
33
+
34
+ /** 判域行三字段的闭集与顺序。 */
35
+ const FIELD_LABELS = Object.freeze(["对象", "排除", "止于"])
36
+
37
+ /** 占位词:字段值是正文,不写「视情况」「按需」「等」。前两个按出现在值里算。 */
38
+ const PLACEHOLDER_MARKERS = Object.freeze(["视情况", "按需"])
39
+
40
+ /** 「等」只在它收尾一份列举时算占位词:整值就是它,或以它收尾而前一字不是构成「相等」「同等」的相/同。 */
41
+ const PLACEHOLDER_ETC_RE = /(?:^|[^相同])等\s*$/
42
+
43
+ /** 判法行:去首尾空白后以 `判法「<判法名>」:` 起头。 */
44
+ const JUDGE_LAW_RE = /^判法「([^」]+)」:/
45
+
46
+ /** 判域行:去首尾空白后以 `**判域**:<判法名> —— ` 起头,余下是字段正文。 */
47
+ const JUDGE_DOMAIN_RE = /^\*\*判域\*\*:([^—\s]+)\s*——\s*(.+)$/
48
+
49
+ const USAGE = "node thincoder-core/agent-tools/judge-domain.mjs --doc <设计档> --record <批档>"
50
+
51
+ /**
52
+ * 边界拒绝:点名该输入与用法,退出码 2,零判决行。
53
+ * @param {string} message 拒绝原因(须点出缺哪个参数或哪份档)。
54
+ * @returns {never}
55
+ */
56
+ function boundary(message) {
57
+ process.stderr.write(`judge-domain: ${message}\n用法:${USAGE}\n`)
58
+ process.exit(2)
59
+ }
60
+
61
+ /**
62
+ * 取 `--doc` 与 `--record` 两个路径。两形都收:`--doc <path>` 与 `--doc=<path>`。
63
+ * 缺一个即边界拒绝并点名该参数;没有默认值。
64
+ * @param {string[]} argv `process.argv.slice(2)`
65
+ * @returns {{ doc: string, record: string }}
66
+ */
67
+ function parseArgs(argv) {
68
+ const picked = { doc: null, record: null }
69
+ for (let i = 0; i < argv.length; i += 1) {
70
+ const raw = argv[i]
71
+ if (!raw.startsWith("--")) boundary(`unexpected argument "${raw}" — only --doc and --record are taken`)
72
+ const eq = raw.indexOf("=")
73
+ const flag = eq > 0 ? raw.slice(0, eq) : raw
74
+ const key = flag === "--doc" ? "doc" : flag === "--record" ? "record" : null
75
+ if (key === null) boundary(`unknown argument "${flag}" — only --doc and --record are taken`)
76
+ if (picked[key] !== null) boundary(`duplicate ${flag} — pass each of --doc and --record exactly once`)
77
+ let value = eq > 0 ? raw.slice(eq + 1) : null
78
+ if (value === null) {
79
+ const next = argv[i + 1]
80
+ if (next === undefined || next.startsWith("--")) {
81
+ boundary(`missing value for ${flag} — both --doc and --record are required and carry no default`)
82
+ }
83
+ value = next
84
+ i += 1
85
+ }
86
+ if (value.trim() === "") boundary(`empty value for ${flag} — pass the path to the document it names`)
87
+ picked[key] = value
88
+ }
89
+ if (picked.doc === null) boundary("missing --doc <设计档> — the design document carrying §10.4 and §10.8 is required; there is no default")
90
+ if (picked.record === null) boundary("missing --record <批档> — the batch record carrying the 验收对照 table is required; there is no default")
91
+ return picked
92
+ }
93
+
94
+ /**
95
+ * 读一份 UTF-8 档;读不到就在边界拒绝并点名该参数与路径。
96
+ * @param {string} flag 参数名(`--doc` ∥ `--record`)
97
+ * @param {string} path 盘上路径
98
+ * @returns {string}
99
+ */
100
+ function readUtf8(flag, path) {
101
+ try {
102
+ return readFileSync(path, "utf8")
103
+ } catch (e) {
104
+ boundary(`${flag} ${path} is unreadable (${e?.code ?? e?.message ?? "unknown"}) — pass an absolute path or a path relative to the current directory`)
105
+ }
106
+ }
107
+
108
+ /**
109
+ * 取一份档里以某行起头的一节正文:从该行之后到下一个同级或更高级标题之前。
110
+ * @param {string} text 档全文
111
+ * @param {RegExp} headingRe 起头标题的匹配式(如 `/^### 10\.4\s/`)
112
+ * @returns {{ heading: string, lines: { text: string }[] } | null}
113
+ */
114
+ function sectionOf(text, headingRe) {
115
+ const lines = String(text).split(/\r?\n/)
116
+ const start = lines.findIndex((line) => headingRe.test(line))
117
+ if (start < 0) return null
118
+ const level = (lines[start].match(/^#+/) ?? [""])[0].length
119
+ const body = []
120
+ for (let i = start + 1; i < lines.length; i += 1) {
121
+ const nested = lines[i].match(/^(#+)\s/)
122
+ if (nested && nested[1].length <= level) break
123
+ body.push({ text: lines[i] })
124
+ }
125
+ return { heading: lines[start], lines: body }
126
+ }
127
+
128
+ /**
129
+ * 把一节正文读成 §10.4 的条目。条目 = 以 `- ` 起头的行 + 其后以空白起首的续行。
130
+ * 续行之间可以隔空行;未缩进的非空行结束该条目。围栏块整块不入条目正文(示例不是判据句子)。
131
+ * @param {{ text: string }[]} lines 一节的正文行
132
+ * @returns {{ firstLine: string, body: string[] }[]}
133
+ */
134
+ function entriesOf(lines) {
135
+ const entries = []
136
+ let current = null
137
+ let fenced = false
138
+ const close = () => {
139
+ if (current) entries.push(current)
140
+ current = null
141
+ }
142
+ for (const { text } of lines) {
143
+ if (/^\s*```/.test(text)) {
144
+ fenced = !fenced
145
+ continue
146
+ }
147
+ if (fenced) continue
148
+ if (/^-\s+/.test(text)) {
149
+ close()
150
+ current = { firstLine: text.replace(/^-\s+/, "").trim(), body: [] }
151
+ continue
152
+ }
153
+ if (current === null) continue
154
+ if (text.trim() === "") continue
155
+ if (/^[ \t]+\S/.test(text)) current.body.push(text.trim())
156
+ else close()
157
+ }
158
+ close()
159
+ return entries
160
+ }
161
+
162
+ /**
163
+ * 判据首句:该条目第一个 `:` 之前的文字;整条没有 `:` 时取该行全文。
164
+ * @param {string} firstLine 条目的 `- ` 行正文
165
+ * @returns {string}
166
+ */
167
+ function firstSentenceOf(firstLine) {
168
+ const cut = firstLine.indexOf(":")
169
+ return (cut < 0 ? firstLine : firstLine.slice(0, cut)).trim()
170
+ }
171
+
172
+ /**
173
+ * 读一条判域行的三字段。
174
+ * @param {string} rest `**判域**:<判法名> —— ` 之后的字段正文
175
+ * @returns {{ ok: true, fields: Map<string, string> } | { ok: false, reason: string }}
176
+ */
177
+ function domainFields(rest) {
178
+ const body = rest.trim().replace(/[。.]$/, "")
179
+ const fields = new Map()
180
+ for (const segment of body.split(";").map((s) => s.trim()).filter(Boolean)) {
181
+ const hit = segment.match(/^(对象|排除|止于)\s*=\s*([\s\S]*)$/)
182
+ if (!hit) return { ok: false, reason: `unlabeled segment "${segment}"` }
183
+ const label = hit[1]
184
+ const value = hit[2].trim()
185
+ if (fields.has(label)) return { ok: false, reason: `duplicate field ${label}` }
186
+ if (value === "") return { ok: false, reason: `empty field ${label}` }
187
+ if (PLACEHOLDER_MARKERS.some((marker) => value.includes(marker)) || PLACEHOLDER_ETC_RE.test(value)) {
188
+ return { ok: false, reason: `placeholder value in ${label}` }
189
+ }
190
+ fields.set(label, value)
191
+ }
192
+ for (const label of FIELD_LABELS) {
193
+ if (!fields.has(label)) return { ok: false, reason: `missing field ${label}` }
194
+ }
195
+ return { ok: true, fields }
196
+ }
197
+
198
+ /**
199
+ * 读 §10.4 的判据条目:每条带首句、判法行、判域行与判据正文(判法在内)。
200
+ * @param {string} docText 设计档全文
201
+ * @returns {{ firstSentence: string, laws: { name: string }[], domains: { name: string, rest: string }[], text: string }[] | null}
202
+ */
203
+ function criteriaOf(docText) {
204
+ const section = sectionOf(docText, /^#{2,4}\s*10\.4\s/)
205
+ if (section === null) return null
206
+ return entriesOf(section.lines).map((entry) => {
207
+ const laws = []
208
+ const domains = []
209
+ for (const line of entry.body) {
210
+ const law = line.match(JUDGE_LAW_RE)
211
+ if (law) {
212
+ laws.push({ name: law[1] })
213
+ continue
214
+ }
215
+ const domain = line.match(JUDGE_DOMAIN_RE)
216
+ if (domain) domains.push({ name: domain[1], rest: domain[2] })
217
+ }
218
+ // 判据正文 = 判据句 + 条目正文:判法行与判域行都在里面(§10.8「该判据自己的正文(判法在内)」)。
219
+ return { firstSentence: firstSentenceOf(entry.firstLine), laws, domains, text: [entry.firstLine, ...entry.body].join("\n") }
220
+ })
221
+ }
222
+
223
+ /**
224
+ * 读批档「验收对照」表里含 `判法「` 的数据行。判法名文本 = 验收行那一格里每个「…」,去掉点名前的那一个判据首句(`§10.4「…」`);`#` 列标签与期望列不参与。
225
+ * @param {string} recordText 批档全文
226
+ * @returns {{ label: string, firstSentence: string | null, lawNames: string[] }[] | null}
227
+ */
228
+ function acceptanceRowsOf(recordText) {
229
+ const section = sectionOf(recordText, /^#{2,4}\s*验收对照\s*$/)
230
+ if (section === null) return null
231
+ const rows = []
232
+ for (const line of section.lines) {
233
+ const text = line.text
234
+ if (!text.startsWith("|")) continue
235
+ if (/^\|[\s|:-]+\|?\s*$/.test(text)) continue
236
+ if (!text.includes("判法「")) continue
237
+ const cells = text.split("|").map((cell) => cell.trim())
238
+ const label = (cells[1] ?? "").replace(/`/g, "")
239
+ // 数字比对面 = 验收行那一格;`#` 列标签与期望列里的引文不进比对面。
240
+ const row = cells.find((each) => each.includes("判法「")) ?? ""
241
+ const first = row.match(/§10\.4「([^」]*)」/)
242
+ // 判法名文本 = 该格里每个「…」,去掉点名前那个判据首句:A6 形「判法「按行判」与「按义务判」」两个判法名都收。
243
+ const rest = first ? row.replace(first[0], "") : row
244
+ const lawNames = [...rest.matchAll(/「([^」]+)」/g)].map((m) => m[1])
245
+ rows.push({ label, firstSentence: first ? first[1] : null, lawNames })
246
+ }
247
+ return rows
248
+ }
249
+
250
+ /**
251
+ * 判据侧:判域行与判法行配不上对即报。条数不等、行首判法名不认判法行、三字段不成形都算。§10.8「判域行不成形」。
252
+ * @param {{ laws: { name: string }[], domains: { name: string, rest: string }[] }[]} criteria §10.4 的判据条目
253
+ * @param {(line: string) => void} report 收一条问题行(同一问题行只收一次)
254
+ */
255
+ function reportDomainPairing(criteria, report) {
256
+ for (const entry of criteria) {
257
+ if (entry.laws.length === 0 && entry.domains.length === 0) continue
258
+ const lawNames = entry.laws.map((law) => law.name)
259
+ for (const name of new Set(lawNames)) {
260
+ const lawCount = lawNames.filter((each) => each === name).length
261
+ const domainCount = entry.domains.filter((each) => each.name === name).length
262
+ if (lawCount !== domainCount) report(`判域行不成形 ${name}`)
263
+ }
264
+ for (const domain of entry.domains) {
265
+ if (!lawNames.includes(domain.name)) {
266
+ report(`判域行不成形 ${domain.name}`)
267
+ continue
268
+ }
269
+ if (!domainFields(domain.rest).ok) report(`判域行不成形 ${domain.name}`)
270
+ }
271
+ }
272
+ }
273
+
274
+ /**
275
+ * 验收侧:点不到判据首句、带判据正文没有的数,各报一行。§10.8 机检入口三类,第四类不报。
276
+ * @param {{ label: string, firstSentence: string | null, lawNames: string[] }[]} rows 批档验收行
277
+ * @param {Map<string, { text: string }>} byFirstSentence 判据首句 → 判据
278
+ * @param {(line: string) => void} report 收一条问题行
279
+ */
280
+ function reportAcceptanceRows(rows, byFirstSentence, report) {
281
+ for (const row of rows) {
282
+ if (row.firstSentence === null) {
283
+ report(`验收行指不到判据(未点名判据首句) —— 验收行 ${row.label}`)
284
+ continue
285
+ }
286
+ const criterion = byFirstSentence.get(row.firstSentence)
287
+ if (criterion === undefined) {
288
+ report(`验收行指不到判据 ${row.firstSentence} —— 验收行 ${row.label}`)
289
+ continue
290
+ }
291
+ // 两侧都按一个数比:判据正文也取连写的数字串,尺上的 4 不会因正文里有 45 就算「出现过」。
292
+ const criterionNumbers = new Set(criterion.text.match(/\d+/g) ?? [])
293
+ for (const name of row.lawNames) {
294
+ for (const run of name.match(/\d+/g) ?? []) {
295
+ if (!criterionNumbers.has(run)) report(`验收尺带判据没有的数 ${run} —— 验收行 ${row.label}`)
296
+ }
297
+ }
298
+ }
299
+ }
300
+
301
+ /**
302
+ * 判定入口:两份档缺本条读法要的章节、以及一条验收行都没有,都在边界拒绝;其余交给判据侧与验收侧分别收行。
303
+ * @param {{ docText: string, recordText: string, recordPath: string }} input 两份档的全文与批档路径(拒绝句要点名它)
304
+ * @returns {string[]} 问题行(零条 ⇒ PASS)
305
+ */
306
+ function judgeDomains({ docText, recordText, recordPath }) {
307
+ const criteria = criteriaOf(docText)
308
+ if (criteria === null) boundary("--doc carries no `### 10.4` section — §10.4 is the only place 判据 and their 判法 live")
309
+ const rows = acceptanceRowsOf(recordText)
310
+ if (rows === null) boundary("--record carries no `### 验收对照` section — that table is the only place 验收行 live")
311
+ // 零条验收行 = 这一趟什么都判不到:写 PASS 会把「一行都没判」报成「全过」,写 REFUSED 又指不出一条不成立的行。
312
+ // 两个判决词都不成立时走边界拒绝(与缺参数、缺章节同一出口),点名这一份档。
313
+ if (rows.length === 0) {
314
+ boundary(`--record ${recordPath} carries zero 验收行 — the \`## 验收对照\` table has 0 rows carrying 判法「, so nothing is judged and no verdict line is written`)
315
+ }
316
+
317
+ const problems = []
318
+ const seen = new Set()
319
+ const report = (line) => {
320
+ if (seen.has(line)) return
321
+ seen.add(line)
322
+ problems.push(line)
323
+ }
324
+
325
+ // 首句查表按 §10.4 读法:判据 = 条目正文含判域行的条目。首句是配对键,两条判据同句即无法配对,边界拒绝并点名。
326
+ const byFirstSentence = new Map()
327
+ for (const entry of criteria) {
328
+ if (entry.domains.length === 0) continue
329
+ if (byFirstSentence.has(entry.firstSentence)) {
330
+ boundary(`--doc has two §10.4 criteria with the same 首句「${entry.firstSentence}」 — the first sentence is the pairing key and has to be unique`)
331
+ }
332
+ byFirstSentence.set(entry.firstSentence, entry)
333
+ }
334
+
335
+ reportDomainPairing(criteria, report)
336
+ reportAcceptanceRows(rows, byFirstSentence, report)
337
+ return problems
338
+ }
339
+
340
+ const args = parseArgs(process.argv.slice(2))
341
+ const docText = readUtf8("--doc", args.doc)
342
+ const recordText = readUtf8("--record", args.record)
343
+
344
+ const found = judgeDomains({ docText, recordText, recordPath: args.record })
345
+ const verdict = found.length === 0 ? "JUDGE-DOMAIN: PASS" : "JUDGE-DOMAIN: REFUSED"
346
+ process.stdout.write([verdict, ...found].join("\n") + "\n")
347
+ process.exitCode = found.length === 0 ? 0 : 1
@@ -11,8 +11,8 @@
11
11
  * - `write` ⇒ **点改**:读现档 → 设节点 → 落盘(`writeManifest` 内先 `validateManifest`——
12
12
  * 编辑结果非法 ⇒ 拒 + 盘零变);**缺档 ⇒ 拒** + 引导 `init`(写不建档)。
13
13
  *
14
- * 写面白名单(判据单源 = `MANIFEST_SCHEMA`——钉死谓词):**16 个可写节点** = `keys` 中**非** `nestedKeys`
15
- * 父键者(`version` / `phase` / `codePaths` 整键)+ `nestedKeys` 子键(`docRoot.*` 六子键 / `index.*` 七子键);
14
+ * 写面白名单(判据单源 = `MANIFEST_SCHEMA`——钉死谓词):**15 个可写节点** = `keys` 中**非** `nestedKeys`
15
+ * 父键者(`version` / `phase` / `codePaths` 整键)+ `nestedKeys` 子键(`docRoot.*` 六子键 / `index.*` 六子键);
16
16
  * **两族整键写(传整个对象)⇒ 拒**;白名单外 ⇒ 拒(拼写保护——未知键写盘 = 静默死键,KD-M1-36 问题本体)。
17
17
  * `value` 解析 = 同款口径 `settings.mjs` 的 `parseValue`(先 `JSON.parse`,失败取字面串;`"null"` ⇒ `null`
18
18
  * ——`docRoot.*` 的「本面无」,KD-M1-37)。