@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
@@ -17,11 +17,12 @@
17
17
  * 「解析出的档在盘」,先写指针后落档必被自己的门当场拒。
18
18
  * ③ **回收只回 `待核销`**(§2.13):`已核销` 是终态,重开不回收、回执点名;其余状态一律不动。
19
19
  */
20
- import { basename, isAbsolute, resolve } from "node:path"
20
+ import { basename, isAbsolute, relative, resolve } from "node:path"
21
21
 
22
22
  import { ALLOWED_MIGRATIONS, nowIso, openLedger, PENDING_STATUSES, resolveLedgerRoot } from "./ledger-db.mjs"
23
23
  import { declaredPublicRoots, resolveDeclaredRef } from "./declaration.mjs"
24
- import { assertAnchorBatchSettleable, assertCloseOutProof, filePartOf, isReservedPointer, namesPointer } from "./ledger-close-proof.mjs"
24
+ import { batchDirs, isBatchFace } from "./doc-check/existence.mjs" // 批档根集与前缀包含判据单源(§6.4 第三支——不另造根枚举)
25
+ import { assertAnchorBatchSettleable, assertCloseOutProof, filePartOf, isReservedPointer, namesPointer, RESERVED_POINTER_MARKER } from "./ledger-close-proof.mjs"
25
26
 
26
27
  /** 解析基准(设计档 §6.1 口径 2 同一子表达式——与台账库键同源):`resolveLedgerRoot(cwd, boundary)?.root
27
28
  * ?? resolve(cwd ?? ".")`。`boundary` = 会话锚(与 `openLedger` 同一枚上界——同一笔动作的判据不能两界)。 */
@@ -70,14 +71,30 @@ export function assertEvidenceValue(fnName, evidence) {
70
71
  if (evidence != null && String(evidence).trim() === "") throw new Error(`${fnName}:evidence 为空(非空字符串)`)
71
72
  }
72
73
 
73
- /** 预定指针拒文(逐字 = `docs/core/design/LEDGER.md` §6.4 拒文表两分支)。 */
74
+ /** 预定指针拒文(三支;规则出处 = `docs/core/design/LEDGER.md` §6.4 预定指针):前两支字面沿用(第二支有集成用例逐字断言),第三支按 §6.4「落在批档根之外的指针不是预定……写入时即拒并点名该指针与合法形」点名两者。 */
74
75
  const reservedNotRelativeError = (value) => `task_book:预定指针须写项目相对路径(不带声明源前缀 / 绝对路径):${value}`
75
76
  const reservedOnDiskError = (value) => `task_book:预定指针所指的档已在盘(去掉「(预定)」标记即可):${value}`
77
+ /** 第三支的合法形 = 本项目各批档根的项目相对前缀(根集单源 = `batchDirs`);`docRoot.batches` 显式 `null`
78
+ * ⇒ 根集空 ⇒ 本项目没有批档面(§6.4 第三句),同一句拒文把这条一并说清——不另立第二条串。 */
79
+ const reservedOutsideBatchRootError = (value, base) => {
80
+ const roots = batchDirs(base).map((dir) => relative(base, dir).replace(/\\/g, "/") || ".")
81
+ const legal = roots.length
82
+ ? roots.map((dir) => `${dir}/<档名>.md${RESERVED_POINTER_MARKER}`).join(" ∥ ")
83
+ : "无——PROJECT-MANIFEST.json 的 docRoot.batches 显式为 null ⇒ 本项目没有批档面"
84
+ return `task_book:预定指针须落在本项目的批档根之下(合法形 = ${legal}):${value}`
85
+ }
86
+
87
+ /** 预定指针 → 普通形(§6.4「在途行被接手时……同笔改写成普通形式」):只剥值尾标记,`§` 段号等其余部分
88
+ * 原样保留——收编去掉的只是「档未建」这一层已失效的语义,不改这行指针的其余内容。 */
89
+ const plainPointerOf = (v) => String(v).trim().slice(0, -RESERVED_POINTER_MARKER.length).trim()
76
90
 
77
- /** 预定指针(§6.4 写门臂② 两支):两条件全成立才放过——① **项目相对**(不带声明源前缀、不是绝对路径、
91
+ /** 预定指针(§6.4 写门臂② 三支):三条件全成立才放过——① **项目相对**(不带声明源前缀、不是绝对路径、
78
92
  * 不带盘符):认领以 `batch create` 的目标路径 P 为键(P 恒项目相对),值带声明源前缀 ∥ 绝对路径时认领按 P
79
93
  * 解析、走另一个基准 ⇒ 同一行在认领里永远认不到;② **不在盘**(已在盘 ⇒ 标记多余,读数面会撒谎:
80
- * `taskBookOnDisk` 报 `false` 而档在盘)。在盘判据与普通指针同一函数(`resolveDeclaredRef`),零二写。 */
94
+ * `taskBookOnDisk` 报 `false` 而档在盘);③ **落在本项目的批档根之下**:解析基准 = 本项目的根(`baseOf`
95
+ * 给出、认领探针同基),判据 = `isBatchFace` 的前缀包含(根集单源 `batchDirs` ⇒ `docRootPaths`)。
96
+ * 根外的指针不是「档还没建」的合法态,而是一条永远认领不到的死指针:认领探针按项目根相对形解析目标,
97
+ * 这类行恒不命中 ⇒ 写入时即拒。② ③ 两判吃同一个解析结果(`resolveDeclaredRef` 的 `abs`),零二写。 */
81
98
  function assertReservedPointer(cwd, value, boundary) {
82
99
  const base = baseOf(cwd, boundary)
83
100
  const part = filePartOf(value)
@@ -86,7 +103,9 @@ function assertReservedPointer(cwd, value, boundary) {
86
103
  const declared = declaredPublicRoots(base)
87
104
  const withPrefix = declared.some((root) => segs[0] === basename(root))
88
105
  if (isAbsolute(part) || /^[a-zA-Z]:/.test(part) || withPrefix) throw new Error(reservedNotRelativeError(value))
89
- if (resolveDeclaredRef(base, part).ok) throw new Error(reservedOnDiskError(value))
106
+ const hit = resolveDeclaredRef(base, part)
107
+ if (hit.ok) throw new Error(reservedOnDiskError(value))
108
+ if (!isBatchFace(hit.abs, base)) throw new Error(reservedOutsideBatchRootError(value, base))
90
109
  }
91
110
 
92
111
  /** 写门·指针点名(设计档 §6.1 两臂 · AC-M2-10 ∥ AC-M2-29):判**本笔写入面**——两臂之外零判。
@@ -94,8 +113,8 @@ function assertReservedPointer(cwd, value, boundary) {
94
113
  * (缺 / 空串 / 全空白 ⇒ 拒「必填」);**不判在盘**(列值事实,不随盘面翻转——DDL 咬合 CHECK 为该半幅防线)。
95
114
  * 臂②(本笔新指名):本笔新写 `task_book`(非空值)∥ 本笔新写 `trigger = 归批` ⇒ 绑定指针非空 ∧ 文件部分
96
115
  * 可解析 ∧ 解析出的档**在盘**(判定单源 = `resolveDeclaredRef`,零二写)。
97
- * **预定指针一支例外**(§6.4):值尾带 `(预定)` 标记 ⇒ 臂② 改判两支(项目相对 ∥ 不在盘),
98
- * 不判在盘——未建档是它的合法态。
116
+ * **预定指针一支例外**(§6.4):值尾带 `(预定)` 标记 ⇒ 臂② 改判三支(项目相对 ∥ 不在盘 ∥ 落在本项目的
117
+ * 批档根之下),不判在盘——未建档是它的合法态。
99
118
  * **「档此刻在不在盘」不入臂①**:批档可随时整体清理 ⇒ 当结果行判据则合法账务被拒、而出路正是被拒字段
100
119
  * (死锁);存量指针失效只体现为读数 `taskBookOnDisk = false`(§7.1)。 */
101
120
  export function assertTaskBookGate(cwd, fnName, face, boundary) {
@@ -294,7 +313,7 @@ async function sameFaceScan({ cwd, boundary, face }) {
294
313
  * `BEGIN IMMEDIATE` → (新建)INSERT 一行 `待讨论`(无指针;`trigger` 不填——`trigger=归批` 与
295
314
  * `task_book` 同在下一步一笔写,否则臂① 会把无指针的行当场拒)→ `writeRecord(#N)` 写批档 →
296
315
  * `applyRowUpdateTx` 迁 `在途` + 写 `task_book`(过写门)→ `COMMIT`。接管路径同一条道理:`#N` 已知 →
297
- * `writeRecord` → `applyRowUpdateTx` → `COMMIT`。
316
+ * `writeRecord` → (指针带预定标记时同笔一次 `applyRowUpdateTx` 收编标记)→ `COMMIT`。
298
317
  *
299
318
  * 崩在窗口内(行已 INSERT ∥ 已改、`COMMIT` 未执行、档已落盘):SQLite 回滚事务 ⇒ 行回原态;档留在盘上而
300
319
  * 台账里没有它的行(写锁只问「这个项目里有没有 `在途` 行」,不读指针——设计档 §2.3)。清理只删**本笔所建**的档(`created` 由调用方按返回值判断——`wx` 撞已有
@@ -312,8 +331,9 @@ async function sameFaceScan({ cwd, boundary, face }) {
312
331
  * `newDebt` = 非空字符串(为什么这不是候选里那几条);空串 ∥ 全空白 ⇒ 按未给判;与 `ledger` 同携 ⇒ 拒。
313
332
  * @param {(id:number)=>void} writeRecord — 写批档(`wx` 独占创建;真实行号已可得)
314
333
  * @returns {Promise<{id:number, created:boolean, claimed?:boolean, tookOver:"new"|"discussed"|"designed"|"live",
315
- * sameFace:{face:string|null, n:number, m:number, declared:string|null}|null}>} `claimed` = 本笔认领了预定行
316
- * (不开新行);`sameFace` = 同面判读数(`null` = 接手 ∥ 认领路径——两支都不判同面);
334
+ * normalized:boolean, sameFace:{face:string|null, n:number, m:number, declared:string|null}|null}>} `claimed` = 本笔认领了预定行
335
+ * (不开新行);`normalized` = 接手支把带预定标记的指针同笔改写成普通形(`true` ⇒ 本笔有一次台账写;
336
+ * 普通指针接手恒 `false` = 零台账写);`sameFace` = 同面判读数(`null` = 接手 ∥ 认领路径——两支都不判同面);
317
337
  * `n` = 本面未决数 · `m` = 他面未决数(读数,不拦)· `declared` = 声明的新事理由
318
338
  */
319
339
  export async function ledgerBindBatch({ cwd, ledgerNo = null, newDebt = null, targetAbs, taskBook, title, kind = "tech_todo", board = null, boundary, executorSessionId = null, agent = {} }, writeRecord) {
@@ -368,12 +388,19 @@ export async function ledgerBindBatch({ cwd, ledgerNo = null, newDebt = null, ta
368
388
  if (row.status === "待核销") throw new Error(bindSettledError(id))
369
389
  if (row.status === "在途") {
370
390
  const part = filePartOf(row.task_book)
371
- const hit = part === "" ? { ok: false, abs: "" } : resolveDeclaredRef(base, part)
372
- if (!hit.ok || pathKey(hit.abs) !== pathKey(targetAbs)) throw new Error(bindOwnedError(id, row.task_book))
373
- // 接管(不动状态、零台账写):档可能已不在盘(残留态)——照写一次 `wx`,撞已有档时由调用方报
391
+ const abs = part === "" ? "" : resolveDeclaredRef(base, part).abs
392
+ // 接手判据只比解析结果(§6.4):`create` 里指针先写、档后落,此刻还要求「档在盘」会把一条合法接手
393
+ // 判成「另一批持有」——`hit.ok` 判的恰恰是在盘。
394
+ if (pathKey(abs) !== pathKey(targetAbs)) throw new Error(bindOwnedError(id, row.task_book))
395
+ // 接管(不动状态):档可能已不在盘(残留态)——照写一次 `wx`,撞已有档时由调用方报
374
396
  writeRecord(id)
397
+ // 接手同笔收编预定标记(§6.4):档此刻已由本批建立,标记的「档未建」语义当场失效;留着的指针还会
398
+ // 让一致性检查把它当预定行整条豁免(`ledger-consistency` 对 `isReservedPointer` 的行不判)⇒ 从此
399
+ // 不再受检。普通指针这一支零台账写——带标记才是接手支唯一的那笔 UPDATE,且档已落盘、过得了写门。
400
+ const normalized = isReservedPointer(row.task_book)
401
+ if (normalized) applyRowUpdateTx(db, cwd, row, { task_book: plainPointerOf(row.task_book) }, executorSessionId, boundary, { base, agent })
375
402
  db.exec("COMMIT")
376
- return { id, created: false, tookOver: "live", sameFace }
403
+ return { id, created: false, tookOver: "live", normalized, sameFace }
377
404
  }
378
405
  }
379
406
  // 步 3:落档——必须先于步 4(写门两形都判「解析出的档在盘」)
@@ -383,7 +410,7 @@ export async function ledgerBindBatch({ cwd, ledgerNo = null, newDebt = null, ta
383
410
  // 该行此后是普通行集成员(`filePartOf` 同址,选行判据零改)。
384
411
  applyRowUpdateTx(db, cwd, row, { status: "在途", task_book: taskBook, trigger: "归批" }, executorSessionId, boundary, { base, agent })
385
412
  db.exec("COMMIT")
386
- return { id, created, claimed: !!claim, tookOver: created ? "new" : row.status === "待设计" ? "designed" : "discussed", sameFace }
413
+ return { id, created, claimed: !!claim, normalized: false, tookOver: created ? "new" : row.status === "待设计" ? "designed" : "discussed", sameFace }
387
414
  } catch (e) {
388
415
  try { db.exec("ROLLBACK") } catch { /* 事务未开 / 已结 */ }
389
416
  throw e
package/memory/docs.mjs CHANGED
@@ -12,10 +12,11 @@ import { _upsertDocFile, yieldTick } from "./code-index.mjs"
12
12
  import { markIndexedCommit, listProjectFiles, indexExtensions, declaredRootEntries } from "./code-sync.mjs"
13
13
  import { searchOrigins } from "./code-search.mjs"
14
14
  import { createRowBudget, rowCountOfPath, sweepStaleRows } from "./sync-tail.mjs"
15
- import { loadProjectDeclaration, declaredIndexScope } from "../conventions.mjs" // 面① 谓词经 `decl` 传 `sweepStaleRows`
15
+ import { loadProjectDeclaration, declaredIndexScope, declarationForTarget, docLayerOf } from "../conventions.mjs" // 面① 谓词经 `decl` 传 `sweepStaleRows`;层判据 = `docLayerOf`(机制 = `docs/core/design/DOC-SYSTEM.md` §3.1)
16
16
  import { createReadGate } from "./read-gate.mjs" // 面⑥∪面⑦ 读面准入单源(#1372 抽件——两档原各持一份逐字相同的 rowHidden)
17
17
  import { logEvent } from "../log.mjs"
18
18
  import { safeSliceUTF16 } from "../text-budget.mjs"
19
+ import { resolve as resolvePath } from "node:path"
19
20
  import { DESC } from "../tools/shared.mjs" // #15 描述外置:文本单点 = tool-docs/*.md(DESC 单解析面,缺档抛错语义不变)
20
21
 
21
22
  const DOC_EMBED_BATCH = 64
@@ -107,9 +108,13 @@ export async function syncDocRoot(memory, dir, { onProgress, yieldFn = yieldTick
107
108
  * Falls back to pure FTS when no embedder; falls back to pure vector when ftsQuery is empty and embedder is present.
108
109
  * `origins`(可选覆盖参 · 2026-10-10 #1100):缺省 `null` ⇒ 现行为(本函数自取 `searchOrigins`)**逐字**;
109
110
  * 给定 ⇒ 以其为 origin 集(复用既有单/多 origin SQL 形);空数组 ⇒ 现「不过滤」语义(本设计调用方不产此形)。
110
- * 消费方 = `thincoder-core/agent/setup.mjs` 注入块两路分取(配额策略 = `docs/core/design/AGENT-LOOP.md` §6.3)。
111
+ * `layers`(可选层过滤):层名数组;缺省 ∥ 空数组 ⇒ **不筛**(不是筛成某几层)。筛在**候选准入处**
112
+ * (与 `rowHidden` 同一处、在各自的 `slice(0, limit)` 之前)——先截 `limit` 再筛层会产出「该层有命中却 0 条」,
113
+ * 补位遍因此永远补不到人。层判据 = `docLayerOf`(属辖声明 + 根相对最长前缀)。
114
+ * 回执每行带 `origin` · `layer` · `authority`:工具行、`doc_search` 与注入块读这三个字段,不各自再算一遍。
115
+ * 消费方 = `thincoder-core/agent/setup.mjs` 注入块两路分取(配额机制 = `docs/core/design/AGENT-LOOP.md` §4.2「注入面」)。
111
116
  */
112
- export async function docSearch(memory, query, { limit = 5, origins: originsOverride = null } = {}) {
117
+ export async function docSearch(memory, query, { limit = 5, origins: originsOverride = null, layers = null } = {}) {
113
118
  const ftsQuery = buildFtsQuery(query)
114
119
  if (!ftsQuery && !memory.embedder) return []
115
120
 
@@ -122,44 +127,75 @@ export async function docSearch(memory, query, { limit = 5, origins: originsOver
122
127
  // 存量行不删(收尾保护位);窗口欠额接受。
123
128
  const { rowHidden } = createReadGate()
124
129
  const ftsNeedOrigin = origins.length !== 1 // 单 origin 形 SQL 零改;多 origin ∥ 无过滤形补 `origin` 列(行 origin 随行可得)
130
+ // 层判定(按 `origin|path` 记忆):属辖声明沿祖先链取(`declarationForTarget`——与工具面同一把尺),
131
+ // 声明公共源里的行因此按那个仓自己的 `docRoot` 判层,不借会话项目的根。
132
+ const layerCache = new Map()
133
+ const UNLAYERED = { layer: "unlayered", authority: false }
134
+ const layerAt = (origin, path) => {
135
+ const key = `${origin}|${path}`
136
+ const hit = layerCache.get(key)
137
+ if (hit) return hit
138
+ const abs = resolvePath(String(origin ?? ""), String(path ?? ""))
139
+ const decl = declarationForTarget(abs)
140
+ const value = decl ? docLayerOf(abs, decl) : UNLAYERED
141
+ layerCache.set(key, value)
142
+ return value
143
+ }
144
+ const layerWanted = Array.isArray(layers) && layers.length > 0 ? new Set(layers) : null
145
+ const admitLayer = (origin, path) => !layerWanted || layerWanted.has(layerAt(origin, path).layer)
146
+ // 候选窗口:层判据只能在 JS 侧施加(层由路径 + 属辖声明派生,不是一列),而 SQL 的 `LIMIT` 在它之前。
147
+ // 所以单层取数(`layers` 在场——注入的保底名额走这一支)把窗口放宽:窗口取小,就会把「该层命中排在窗口外」
148
+ // 读成「该层无命中」。仍不是穷尽取数:语料大到命中落在窗口外时取不到,那不是「语料里没有这一层」。
149
+ const windowSize = layerWanted ? Math.max(limit * 40, 200) : Math.max(limit * 4, 20)
150
+ /** 回执行盖三个字段(同一行的 origin 不论从 SQL 列还是从单-origin 形得出,都走这一处)。 */
151
+ const stamp = (row, origin) => {
152
+ const l = layerAt(origin, row.path)
153
+ row.origin = origin
154
+ row.layer = l.layer
155
+ row.authority = l.authority
156
+ return row
157
+ }
158
+ const ftsRowOrigin = (r) => (origins.length === 1 ? origins[0] : r.origin)
159
+ const finish = (list) => list.slice(0, limit).map((r) => stamp(r, ftsRowOrigin(r)))
125
160
 
126
161
  const ftsList = ftsQuery ? memory.db.prepare(`
127
162
  SELECT d.rowid, d.path, d.language, d.heading, d.content, d.line_start, d.line_end, bm25(doc_chunks_fts) AS rank${ftsNeedOrigin ? ", d.origin" : ""}
128
163
  FROM doc_chunks_fts JOIN doc_chunks d ON d.rowid = doc_chunks_fts.rowid
129
164
  WHERE doc_chunks_fts MATCH ? ${ftsOriginFilter}
130
165
  ORDER BY rank LIMIT ?
131
- `).all(ftsQuery, ...originParams, Math.max(limit * 4, 20))
132
- .filter((r) => !rowHidden(origins.length === 1 ? origins[0] : r.origin, r.path)) : []
166
+ `).all(ftsQuery, ...originParams, windowSize)
167
+ .filter((r) => !rowHidden(origins.length === 1 ? origins[0] : r.origin, r.path) && admitLayer(ftsRowOrigin(r), r.path)) : []
133
168
 
134
- if (!memory.embedder) return ftsList.slice(0, limit)
169
+ if (!memory.embedder) return finish(ftsList)
135
170
 
136
171
  let docEnsured
137
172
  try { docEnsured = await ensureDocEmbeddings(memory) } catch (e) {
138
173
  console.error(`[docs] embedding ensure failed, falling back to FTS-only: ${e.message}`)
139
- return ftsList.slice(0, limit)
174
+ return finish(ftsList)
140
175
  }
141
176
  if (docEnsured?.mismatch) { // §6.14 B7 读面零写:模型键失配 ⇒ 本面向量通道降级 FTS-only(一行可见;失效执行归维护口)
142
177
  console.warn("[docs] embedding model changed — vector channel degraded to FTS-only (rebuild runs at maintenance: sync tail / reindex)")
143
- return ftsList.slice(0, limit)
178
+ return finish(ftsList)
144
179
  }
145
180
  let qvec
146
181
  try { [qvec] = await embed(memory.embedder, [query]) } catch (e) {
147
182
  console.error(`[docs] query embedding failed, falling back to FTS-only: ${e.message}`)
148
- return ftsList.slice(0, limit)
183
+ return finish(ftsList)
149
184
  }
150
185
  // TUI-OOM-ROOTCAUSE(MEMORY.md §10.3):分块扫描 + 有界 top-K(原全表 .all()——峰值 = 块 + K)
151
186
  // TUI 假死批(§6.10 修法 A1/A2):游标 = PK 去等值过滤前缀列(有 origin 过滤 ⇒ 2 元组;
152
187
  // 无过滤 ⇒ 全 PK);scanVectors = async(让出)。SELECT 须携键列(游标值源)。
153
188
  const cursorKey = origins.length > 0 ? ["path", "line_start"] : ["origin", "path", "line_start"]
154
189
  const keyCols = cursorKey.join(", ")
155
- const top = createTopK(Math.max(limit * 4, 20))
190
+ const top = createTopK(windowSize)
156
191
  // §6.15 多 origin ⇒ 逐 origin 分趟(每趟单 origin 等值 + 游标键去等值前缀列——与单 origin 快径同形)
157
192
  const vecSql = `SELECT rowid, ${keyCols}, embedding FROM doc_chunks WHERE embedding IS NOT NULL ${origins.length ? "AND origin = ?" : ""}`
158
193
  for (const origin of origins.length ? origins : [null]) {
159
194
  await scanVectors(memory.db, vecSql, origin ? [origin] : [], {
160
195
  cursorKey,
161
- onRow: (r) => { // §6.14 面⑥∪面⑦ 准入(top-K push 前;无过滤形行 origin = 游标键 `origin` 列)
162
- if (!rowHidden(origin ?? r.origin, r.path)) top.push({ id: r.rowid, rowid: r.rowid, score: cosine(qvec, fromBlob(r.embedding)) })
196
+ onRow: (r) => { // §6.14 面⑥∪面⑦ 准入(top-K push 前;无过滤形行 origin = 游标键 `origin` 列);层过滤同一处
197
+ const rowOrigin = origin ?? r.origin
198
+ if (!rowHidden(rowOrigin, r.path) && admitLayer(rowOrigin, r.path)) top.push({ id: r.rowid, rowid: r.rowid, score: cosine(qvec, fromBlob(r.embedding)) })
163
199
  },
164
200
  })
165
201
  }
@@ -171,7 +207,7 @@ export async function docSearch(memory, query, { limit = 5, origins: originsOver
171
207
  vecList.forEach((r, i) => scores.set(r.rowid, (scores.get(r.rowid) ?? 0) + 1 / (K + i + 1)))
172
208
 
173
209
  const fetchChunk = memory.db.prepare(`
174
- SELECT path, language, heading, content, line_start, line_end FROM doc_chunks WHERE rowid = ?
210
+ SELECT path, language, heading, content, line_start, line_end, origin FROM doc_chunks WHERE rowid = ?
175
211
  `)
176
212
  const sorted = [...scores.entries()]
177
213
  .sort((a, b) => b[1] - a[1])
@@ -181,7 +217,7 @@ export async function docSearch(memory, query, { limit = 5, origins: originsOver
181
217
  const chunk = fetchChunk.get(rowid)
182
218
  if (!chunk) return null
183
219
  chunk._score = Math.round(score * 100) / 100
184
- return chunk
220
+ return stamp(chunk, chunk.origin)
185
221
  })
186
222
  .filter(Boolean)
187
223
  }
@@ -234,7 +270,7 @@ export function docSearchTool(memory) {
234
270
  const results = await docSearch(memory, args.query, { limit: args.limit ?? 5 })
235
271
  if (results.length === 0) return "(no matching documentation)"
236
272
  return results.map((r) =>
237
- `${r.path}${r.heading ? ` > ${r.heading}` : ""} (L${r.line_start}-L${r.line_end}, relevance ${r._score?.toFixed(2) ?? "?"}):\n${r.content.slice(0, 2000)}`
273
+ `[${r.layer}] ${r.path}${r.heading ? ` > ${r.heading}` : ""} (L${r.line_start}-L${r.line_end}, relevance ${r._score?.toFixed(2) ?? "?"}):\n${r.content.slice(0, 2000)}`
238
274
  ).join("\n\n---\n\n")
239
275
  },
240
276
  }
@@ -3,6 +3,10 @@
3
3
  * 内容 = `indexExtensions`(内置扩展名表 ∪ 项目声明并集)∥ `listProjectFiles`(git 列面 + 非 git walk
4
4
  * 回退 + unlisted 计数;准入 = 排除(§6.14 面①∪面⑥——git 列面筛行 ∥ walk 剪枝)+ 声明范围门
5
5
  * (§6.14 面⑦——双径逐文件判 ∥ walk 不剪枝))——迁出块逐字。
6
+ *
7
+ * 本档的排除面也是「过程档不进文档索引语料」的实证:过程档在**列**面就被挡在语料外,所以
8
+ * `doc_search` 既没有可排除的行,也没有可取回的行(机制 = `docs/core/design/DOC-SYSTEM.md` §3.2)。
9
+ * 过程层内容的检索路径 = 四个浏览类工具加 `read`。
6
10
  * 原档 `memory/code-sync.mjs` 经 `export { … } from` 转口保名(消费面 / 单元测试档 import 面零改)。
7
11
  */
8
12
  import { CODE_EXTS, DOC_EXTS } from "./schema.mjs"
@@ -41,6 +45,8 @@ export function indexExtensions(dir) {
41
45
  * no pruning on the walk (a segment-sequence face may match at any depth).
42
46
  * `truncated` = the non-git walk hit its file cap (capped trees are logged, never
43
47
  * silently indexed-partial; out-of-scope files spend no budget). opts.maxFiles = the walk cap (test seam).
48
+ * 过程档(面⑥ 批次段 ∥ 面① 声明前缀)在同一道排除里被挡在**语料**外:文档索引不带 `includeProcessDocs`
49
+ * 类开关,因为这里已经没有它的行可排可收(机制 = `docs/core/design/DOC-SYSTEM.md` §3.2)。
44
50
  */
45
51
  export async function listProjectFiles(dir, exts, { maxFiles } = {}) {
46
52
  const { execFile: _execFile } = await import("node:child_process")
package/model-specs.mjs CHANGED
@@ -8,6 +8,7 @@
8
8
  */
9
9
 
10
10
  import { listedContextTokens, manualContextK, warnContextOnce } from "./model-context.mjs"
11
+ import { logEvent } from "./log.mjs"
11
12
 
12
13
  /**
13
14
  * Known model capability spec table (prefix match within the model's last "/"-segment, longer first).
@@ -111,13 +112,20 @@ const MODEL_SPECS = [
111
112
  // (6 levels), 3.8-flash adds it (7); enum order = the server's literal order, first member "none"
112
113
  // (D-5) — never re-sort by strength. context = doc/web statement (1M class, not API-measured);
113
114
  // partialMode / thinkApi / tempRange = same-family carry-over (not independently
114
- // measured on these rows); reasoningEcho stays undeclared (cross-turn echo unverified — R-4).
115
+ // measured on these rows); reasoningEcho stays undeclared(qwen3.8-max / qwen3.7-flash / qwen4-max 真机实测:带 tools 的续跑请求里,历史工具轮缺 `reasoning_content` 键照样 200——DashScope 不强制跨轮回声,故不声明 required)。
115
116
  ["qwen3.7-flash", { context: 1_000_000, maxOutput: 131_072, thinking: true, partialMode: true, multimodal: true, thinkApi: "effort", reasoningEffortEnum: ["none", "minimal", "low", "medium", "high", "xhigh"], tempRange: [0, 2] }],
116
117
  // qwen3.7-plus(2026-09-24 bench 名单批):context = **官方口径(网络转述)**(2026-09-20 qwen-flash-specs 批 AC-6 已裁允许入表——「100 万长文档」族点名);
117
118
  // maxOutput / partialMode / thinkApi / tempRange / thinking = **族沿用 qwen3.7-flash 行**;枚举 / 视觉面 = **未探**(不声明)。
118
119
  ["qwen3.7-plus", { context: 1_000_000, maxOutput: 131_072, thinking: true, partialMode: true, thinkApi: "effort", tempRange: [0, 2] }],
119
120
  ["qwen3.8-flash", { context: 1_000_000, maxOutput: 131_072, thinking: true, partialMode: true, multimodal: true, thinkApi: "effort", reasoningEffortEnum: ["none", "minimal", "low", "medium", "high", "xhigh", "max"], tempRange: [0, 2] }],
120
121
  ["qwen3.8-max", { context: 1_000_000, maxOutput: 131_072, thinking: true, partialMode: true, multimodal: true, thinkApi: "effort", reasoningEffortEnum: ["xhigh", "medium", "low"], tempRange: [0, 2] }],
122
+ // qwen4-max(2026-11-19 批)——行注即标级(`MODEL-SPECS.md` §1「逐字段记录当前一手来源或实测证据;不能从名字猜能力」):
123
+ // context 1_000_000 = **官方口径**(`https://help.aliyun.com/zh/model-studio/qwen4-max-preview` 原文「Context length,
124
+ // 1M tokens」);maxOutput 393_216 = **官方口径**(同页原文「Maximum output, 393,216 tokens, shared by thinking and
125
+ // the final answer」);thinking = 同句(thinking 与最终答案共享输出上限 ⇒ 该模型走 thinking)。
126
+ // partialMode ∥ multimodal ∥ thinkApi ∥ reasoningEffortEnum ∥ tempRange = **未探**(不声明——不拿邻行猜值);
127
+ // thinkApi 不声明 ⇒ 无 off 路径,UI 不给假 off(`MODEL-SPECS.md` §4)。
128
+ ["qwen4-max", { context: 1_000_000, maxOutput: 393_216, thinking: true }],
121
129
  // qwen3.8-omni-flash / qwen3.8-27b — parent 80-token probe (batch §1.8-①): reasoning_content
122
130
  // present, reasoning_tokens 49, `effort:"none"` removes it ⇒ thinking MEASURED; enum / maxOutput
123
131
  // / image intake measured the same way. omni-flash: context = doc/web statement (1M class, not
@@ -130,7 +138,7 @@ const MODEL_SPECS = [
130
138
  // undeclared (cross-turn echo unverified — R-4).
131
139
  ["qwen3.8-27b", { context: 262_144, maxOutput: 131_072, thinking: true, partialMode: true, multimodal: true, thinkApi: "effort", reasoningEffortEnum: ["none", "minimal", "low", "medium", "high", "xhigh", "max"], tempRange: [0, 2] }],
132
140
  // No generic "qwen" fallback row: unlisted qwen names deliberately resolve to DEFAULT_SPEC
133
- // (128K / 32K, no vision) — per-name disposition in docs/core/design/MODEL-SPECS.md §2.4.
141
+ // (256K / 32K, no vision) — per-name disposition in docs/core/design/MODEL-SPECS.md §3.
134
142
  // Do not re-add a blanket prefix row (silent inheritance is how missing rows stayed invisible).
135
143
 
136
144
  // qwen3.6 系五行(批 2026-09-20-qwen36-family-rows · 五名同形,取证叙述落此一处全量):
@@ -246,7 +254,10 @@ const MODEL_SPECS = [
246
254
  // 生效值同值);行键 = 裸名(渠道名录形 stepfun/step-3.7-flash——命名空间剥离同命中)。
247
255
  ["step-3.7-flash", { context: 262_144, maxOutput: 32_000 }],
248
256
  ]
249
- const DEFAULT_SPEC = { context: 128_000, maxOutput: 32_000 }
257
+ // 回落规格(`MODEL-SPECS.md` §3):窗口 262_144 / 输出 32_000。窗口取 256K 不取 128K 的理由不对称——
258
+ // 常见输出预留 131,072 落在 128K 窗上算出负的输入窗口(128,000 − 131,072 < 0),回落因此连一条请求都发不出;
259
+ // 256K 让同一份预留仍留出输入窗口。
260
+ const DEFAULT_SPEC = { context: 262_144, maxOutput: 32_000 }
250
261
 
251
262
  /** 查表规则(单源 = PROVIDER.md §6.9 · 用户 2026-10-23 17:34 裁定「匹配 / 拆分以后的最后一段」):
252
263
  *
@@ -279,14 +290,14 @@ function lookupSpec(model) {
279
290
  }
280
291
 
281
292
  /** Unknown model: warn ONCE (not per request) so a typo'd ID or a missing alias surfaces
282
- * instead of silently degrading to the 128K default (IK5VGJ). The dedupe set is shared by
293
+ * instead of silently degrading to the 256K default (IK5VGJ). The dedupe set is shared by
283
294
  * specForModel / specMatch (PROVIDER.md §16 M5). */
284
295
  function warnUnknownModel(model) {
285
296
  // 非串 model(脏载)归一空串 ⇒ 不警告(未登记 ≠ 拼错——不刷屏;#638 与 lookupSpec 同归一)
286
297
  const m = (typeof model === "string" ? model : "").toLowerCase()
287
298
  if (m && !warnedModels.has(m)) {
288
299
  warnedModels.add(m)
289
- console.warn(`[config] model "${model}" not found in MODEL_SPECS — using default spec (128K context, 32K output). Check the model ID or add an alias.`)
300
+ console.warn(`[config] model "${model}" not found in MODEL_SPECS — using default spec (256K context, 32K output). Check the model ID or add an alias.`)
290
301
  }
291
302
  }
292
303
 
@@ -333,13 +344,13 @@ export function formatDeclaredContextK(k) {
333
344
  * L2 `providers[].context`(旧键,K;仅未被 L1 点名的模型) → ×1024(同一乘点)
334
345
  * L3 `/models` 自报(三字段任一,token) → 不乘
335
346
  * L4 `MODEL_SPECS` 静态表(token) → 不乘
336
- * L5 `DEFAULT_SPEC`(128K,token) → 不乘
347
+ * L5 `DEFAULT_SPEC`(256K,token) → 不乘
337
348
  *
338
349
  * L2 位于 L3 之上:旧键也是人工声明(2026-10-23 17:30 裁定「人工声明 > 列表」),只是粒度不对、
339
350
  * 单位事故出过两次;`modelContext` 点名的模型一律走 L1,L2 不参与。L2 实际被用到时告警一次
340
351
  * (provider 名去重——装载期告警会在 L1 已完全覆盖时误报)。
341
352
  *
342
- * 量级守卫(R32):L1 ∥ L2 的 K 值换算后 > 静态表 ×4(表无行时 = 4 × 128K)⇒ 照用 + 告警一次,
353
+ * 量级守卫(R32):L1 ∥ L2 的 K 值换算后 > 静态表 ×4(表无行时 = 4 × 256K)⇒ 照用 + 告警一次,
343
354
  * 不截断、不拒写——与 L3 的 4× 守卫对称。守卫住在核里:值可能来自手改 JSON(不经任何界面),
344
355
  * 端上守不到;手改 ∥ CLI ∥ VSC ∥ 桌面四条来源在这里同判。
345
356
  *
@@ -352,7 +363,7 @@ export function formatDeclaredContextK(k) {
352
363
  * 与其余能力位仍取静态表 ∥ DEFAULT_SPEC(需求边界:不改 maxOutput 来源)。
353
364
  *
354
365
  * `source` 闭集五值(`windowSource` 的唯一来源,不并类):`modelContext` ∥ `provider-override` ∥
355
- * `list` ∥ `spec` ∥ `default`。`warnUnknownModel` 只在链落到 L4/L5 时触发(L1-L3 供值时 128K 告警为假)。
366
+ * `list` ∥ `spec` ∥ `default`。`warnUnknownModel` 只在链落到 L4/L5 时触发(L1-L3 供值时 256K 告警为假)。
356
367
  */
357
368
  export function providerSpecResolution(provider) {
358
369
  const model = provider?.model ?? ""
@@ -408,34 +419,89 @@ export function providerSpec(provider) {
408
419
  }
409
420
 
410
421
  /**
411
- * assistantToolCallMessage(response, spec) — the tool-round assistant message pushed onto the
422
+ * assistantEchoMessage(response, spec, thinkingMode) — the tool-round assistant message pushed onto the
412
423
  * machine line (D-CC22, #109 — live-push face of the echo-safety family; single construction
413
- * point, CONTEXT-COMPACTION.md §6.10 #9).
424
+ * point, CONTEXT-COMPACTION.md §6.10 #9). 机制正文 = `docs/core/design/AGENT-LOOP.md` §5.4。
414
425
  *
415
- * `reasoningEcho:"required"` families (deepseek / kimi / mimo) MUST carry the reasoning echo on
416
- * every tool-call assistant message: the field is NEVER omitted — an absent/non-string
417
- * `response.reasoning` is echoed as `""` (2026-09-22 re-probe: value / missing field / empty
418
- * string all 200 — the 2026-09-20 "must be passed back" 400 was NOT reproduced). `optional` /
419
- * undeclared families (incl. DEFAULT_SPEC) never get the field (behavior byte-identical).
426
+ * 取值次序固定,第三参只参与「手里没有原文」那一支:
427
+ * - `reasoningEcho:"required"` 族(deepseek / kimi / mimo)握着非空 `response.reasoning` ⇒ 逐字带上
428
+ * `reasoning_content`,其值就是那串原文,不改写——**不因 `thinkingMode === false` 省键**(关闭标记不保证
429
+ * 服务端没有思考,丢掉手里已有的原文会让带 `tools` 的下一轮缺回声);
430
+ * - 同族没有非空原文且 `thinkingMode === true` ⇒ **写空串**并写 `echo:missing` 留痕事件(provider、model、
431
+ * toolCount),不抛错(#2645 降级、#2647 改正写法)。服务端拒的是缺键,空串是合法的「没有原文」编码:
432
+ * 真机读数——同一具 39 条失败请求体只把缺失的键补成空串即 200,键缺失则 400;
433
+ * - 同族没有非空原文且 `thinkingMode === false` ⇒ 不带该键、不抛错——需求 §7「非思考模式下服务端不返回该字段,
434
+ * 此时不带它,不算缺陷」;
435
+ * - `optional` ∥ 未声明的族(含 `spec` 为 `null` 与 DEFAULT_SPEC)⇒ 不带该键。
436
+ *
437
+ * 边界(无默认值):`response` 未传 ⇒ 点名报错;`spec` 未传(`undefined`)⇒ 点名报错;`thinkingMode`
438
+ * 未传 ∥ 非布尔 ⇒ 各自点名报错。`spec` 传 `null` 是合法的「未声明族」值——服务端 live 工具轮在名字不可解
439
+ * ∥ 缺核时回落的正是它,不带该键、不抛错。`thinkingMode` 由 `isThinkingRequest(provider, spec)` 算出
440
+ * (`thincoder-core/think-off.mjs`,经 `config.mjs` 转口);本函数不重算模式。
441
+ * `response.toolCalls` 为空 ⇒ 入口报错并点名 `toolCalls`:工具轮消息必须带工具调用,不写成 `tool_calls: []`。
442
+ * 纯文本轮走同档的 `assistantTextMessage`,回声键的取值次序与边界与之逐条相同。
420
443
  *
421
444
  * 思考签名(PROVIDER.md §6.24):`tool_calls[].extra_content` 在场才带(缺 ⇒ 键不存在——无签名上游键集逐字不变)。
422
445
  *
423
- * Callers (as-of 2026-10-10): thincoder-core/agent/turn-loop.mjs (main loop) · thincoder-core/advisor/loop.mjs
424
- * (review mirror) · bench/lib/client.mjs (bench client) — each passes its own spec face; VSC 转口
425
- * (`thincoder-vscode/src/specs.mjs` 的 `providerSpec` ∕ `assistantToolCallMessage` 再导出) 零调用点(父侧收口机械笔 · 可 revert)。
446
+ * 调用点:`thincoder-core/agent/turn-loop.mjs`(主循环)· `thincoder-core/advisor/loop.mjs`(评审镜像)·
447
+ * `bench/lib/client.mjs`(bench 客户端)· `prompt-fixture/runner.mjs`(夹具跑器)——各自解析自己的 spec 面、
448
+ * 各自算好自己的模式;服务端 live 工具轮 = `thincoder-server/src/agent/chat-compact.mjs` 的 `assistantTurnOf`
449
+ * (动载后调用);VSC 转口 `thincoder-vscode/src/specs.mjs` 的 `providerSpec` ∕ `assistantEchoMessage` 再导出
450
+ * (本仓零调用点)。
426
451
  */
427
- export function assistantToolCallMessage(response, spec) {
452
+ export function assistantEchoMessage(response, spec, thinkingMode, provider = null) {
453
+ if (response === undefined || response === null) throw new Error("assistantEchoMessage: response is required — 工具轮消息由调用方手里那次响应构造,本函数不替调用方补默认")
454
+ if (spec === undefined) throw new Error("assistantEchoMessage: spec is required — 传该族的规格(未声明的族传 null),本函数不替调用方补默认")
455
+ if (thinkingMode === undefined) throw new Error("assistantEchoMessage: thinkingMode is required — 传 isThinkingRequest(provider, spec) 的结果,本函数不替调用方补默认")
456
+ if (typeof thinkingMode !== "boolean") throw new Error(`assistantEchoMessage: thinkingMode must be a boolean — 收到 ${typeof thinkingMode}`)
457
+ const toolCalls = Array.isArray(response.toolCalls) ? response.toolCalls : []
458
+ if (toolCalls.length === 0) throw new Error("assistantEchoMessage: toolCalls is empty — 工具轮消息必须带工具调用;纯文本轮不经本函数构造,也不写 tool_calls: []")
428
459
  const msg = {
429
460
  role: "assistant",
430
461
  content: response.content || null,
431
- tool_calls: response.toolCalls.map((tc) => ({
462
+ tool_calls: toolCalls.map((tc) => ({
432
463
  id: tc.id, type: "function",
433
464
  function: { name: tc.name, arguments: tc.arguments },
434
465
  ...(tc.extra_content ? { extra_content: tc.extra_content } : {}),
435
466
  })),
436
467
  }
437
468
  if (spec?.reasoningEcho === "required") {
438
- msg.reasoning_content = typeof response.reasoning === "string" ? response.reasoning : ""
469
+ const echo = response.reasoning
470
+ if (typeof echo === "string" && echo !== "") {
471
+ msg.reasoning_content = echo
472
+ } else if (thinkingMode) {
473
+ // 思考模式下服务端没给回声:写空串 + 留痕,不抛错(#2645 降级、#2647 把省键改成空串)。
474
+ // 服务端拒的是缺键;空串是合法的「没有原文」编码(真机:补键 200、缺键 400)。
475
+ msg.reasoning_content = ""
476
+ logEvent("echo:missing", { provider: provider?.name ?? undefined, model: provider?.model ?? undefined, toolCount: toolCalls.length, thinkingMode })
477
+ }
478
+ }
479
+ return msg
480
+ }
481
+
482
+ /**
483
+ * assistantTextMessage(response, spec, thinkingMode, provider) — 纯文本轮的 assistant 消息(无工具调用)。
484
+ *
485
+ * 与 `assistantEchoMessage` 同住一个取值次序:有非空 `response.reasoning` 就逐字带上;`required` 族、
486
+ * `thinkingMode` 为真而无原文时写空串并留痕;其余情形不带该键。差别只有一条——不带 `tool_calls`。
487
+ * 机制正文 = `docs/core/design/AGENT-LOOP.md` §5.4(写面是回声键的源头)。
488
+ *
489
+ * 边界同档:`response` ∥ `spec` ∥ `thinkingMode` 缺一在入口点名报错;`spec` 传 `null` 是合法的「未声明族」。
490
+ */
491
+ export function assistantTextMessage(response, spec, thinkingMode, provider = null) {
492
+ if (response === undefined || response === null) throw new Error("assistantTextMessage: response is required — 消息由调用方手里那次响应构造,本函数不替调用方补默认")
493
+ if (spec === undefined) throw new Error("assistantTextMessage: spec is required — 传该族的规格(未声明的族传 null),本函数不替调用方补默认")
494
+ if (thinkingMode === undefined) throw new Error("assistantTextMessage: thinkingMode is required — 传 isThinkingRequest(provider, spec) 的结果,本函数不替调用方补默认")
495
+ if (typeof thinkingMode !== "boolean") throw new Error(`assistantTextMessage: thinkingMode must be a boolean — 收到 ${typeof thinkingMode}`)
496
+ const msg = { role: "assistant", content: response.content || null }
497
+ if (spec?.reasoningEcho === "required") {
498
+ const echo = response.reasoning
499
+ if (typeof echo === "string" && echo !== "") {
500
+ msg.reasoning_content = echo
501
+ } else if (thinkingMode) {
502
+ msg.reasoning_content = ""
503
+ logEvent("echo:missing", { provider: provider?.name ?? undefined, model: provider?.model ?? undefined, toolCount: 0, thinkingMode })
504
+ }
439
505
  }
440
506
  return msg
441
507
  }