@thincoder/core 0.11.1 → 0.11.2

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 (333) hide show
  1. package/CHANGELOG.md +46 -2
  2. package/advisor/convergence.mjs +34 -3
  3. package/advisor/loop.mjs +42 -10
  4. package/advisor/messages.mjs +42 -25
  5. package/advisor/project-context.mjs +171 -42
  6. package/advisor/run.mjs +7 -4
  7. package/advisor.mjs +29 -43
  8. package/agent/batch-attribution.mjs +87 -0
  9. package/agent/batch-changed-surface.mjs +129 -0
  10. package/agent/completion.mjs +44 -3
  11. package/agent/dispatch-gates.mjs +6 -0
  12. package/agent/dispatch.mjs +8 -3
  13. package/agent/family-tools.mjs +27 -12
  14. package/agent/helpers.mjs +122 -1
  15. package/agent/offload.mjs +25 -29
  16. package/agent/post-turn.mjs +24 -10
  17. package/agent/record-results.mjs +18 -1
  18. package/agent/run-stages.mjs +77 -32
  19. package/agent/run-start.mjs +37 -0
  20. package/agent/setup-reminders.mjs +9 -2
  21. package/agent/setup.mjs +24 -11
  22. package/agent/spawn-child.mjs +38 -1
  23. package/agent/timers.mjs +5 -3
  24. package/agent/turn-loop.mjs +30 -5
  25. package/agent/turn-projection.mjs +386 -0
  26. package/agent/turn-task-state.mjs +274 -0
  27. package/agent/turn-tool-process.mjs +168 -0
  28. package/agent/write-gate-ledger.mjs +569 -0
  29. package/agent/write-gate.mjs +29 -352
  30. package/agent-tools/advisor-async.mjs +29 -169
  31. package/agent-tools/advisor-launch.mjs +178 -0
  32. package/agent-tools/advisor-settle.mjs +28 -1
  33. package/agent-tools/advisor.mjs +36 -47
  34. package/agent-tools/audit-block.mjs +6 -6
  35. package/agent-tools/batch-closeout.mjs +273 -35
  36. package/agent-tools/batch-gate.mjs +142 -342
  37. package/agent-tools/batch-ledger-bind.mjs +226 -17
  38. package/agent-tools/batch-ledger-view.mjs +109 -0
  39. package/agent-tools/batch-lifecycle.mjs +169 -46
  40. package/agent-tools/batch-paths.mjs +29 -8
  41. package/agent-tools/batch-record-write.mjs +417 -0
  42. package/agent-tools/batch-regions.mjs +215 -0
  43. package/agent-tools/batch-reopen.mjs +23 -11
  44. package/agent-tools/batch-segment-vocab.mjs +379 -0
  45. package/agent-tools/batch-skeleton.mjs +192 -239
  46. package/agent-tools/batch-supersede.mjs +232 -0
  47. package/agent-tools/batch-tier-gate.mjs +297 -0
  48. package/agent-tools/batch.mjs +182 -439
  49. package/agent-tools/consult.mjs +7 -4
  50. package/agent-tools/context.mjs +44 -17
  51. package/agent-tools/design-review-record.mjs +225 -0
  52. package/agent-tools/design-slots.mjs +1 -1
  53. package/agent-tools/design-token.mjs +279 -81
  54. package/agent-tools/doc-check.mjs +43 -33
  55. package/agent-tools/doc-graph.mjs +140 -0
  56. package/agent-tools/eng.mjs +9 -8
  57. package/agent-tools/escalate-async.mjs +2 -2
  58. package/agent-tools/manifest.mjs +34 -18
  59. package/agent-tools/read-history.mjs +112 -11
  60. package/agent-tools/review-facts.mjs +10 -3
  61. package/agent-tools/settings.mjs +23 -2
  62. package/agent-tools/spawn-gates.mjs +9 -8
  63. package/agent-tools/ssh-session.mjs +2 -2
  64. package/agent-tools/ssh-text.mjs +155 -0
  65. package/agent-tools/ssh-transport.mjs +19 -148
  66. package/agent-tools/subagent-actions-query.mjs +10 -6
  67. package/agent-tools/subagent-async.mjs +8 -9
  68. package/agent-tools/subagent-brief.mjs +76 -0
  69. package/agent-tools/subagent-design-token.mjs +168 -0
  70. package/agent-tools/subagent-run.mjs +1 -1
  71. package/agent-tools/subagent-scheduler.mjs +4 -4
  72. package/agent-tools/subagent-spawn.mjs +90 -110
  73. package/agent-tools/subagent.mjs +11 -10
  74. package/agent-tools/taskbook-block.mjs +94 -0
  75. package/agent-tools/timer.mjs +12 -8
  76. package/agent-tools/verify.mjs +13 -4
  77. package/agent-tools.mjs +7 -3
  78. package/agent.mjs +20 -1
  79. package/attachments.mjs +3 -3
  80. package/browser/actions.mjs +9 -3
  81. package/browser/cdp.mjs +45 -17
  82. package/browser/launch.mjs +25 -43
  83. package/browser/pool.mjs +299 -0
  84. package/browser/queue.mjs +2 -0
  85. package/browser/session-state.mjs +450 -0
  86. package/browser/session.mjs +127 -151
  87. package/browser/snapshot.mjs +89 -0
  88. package/client-identity.mjs +1 -1
  89. package/config-defaults.mjs +2 -1
  90. package/config-migrate.mjs +40 -0
  91. package/config-normalize.mjs +28 -2
  92. package/config-reload.mjs +59 -0
  93. package/config.mjs +62 -98
  94. package/context-degrade.mjs +38 -10
  95. package/context-echo.mjs +11 -0
  96. package/context.mjs +149 -83
  97. package/conventions.mjs +11 -9
  98. package/declaration.mjs +31 -5
  99. package/declared-repos.mjs +94 -0
  100. package/doc-check/doc-names.mjs +73 -0
  101. package/doc-check/doc-tokens.mjs +110 -0
  102. package/doc-check/existence.mjs +160 -0
  103. package/doc-check/index.mjs +309 -213
  104. package/doc-check/line-refs.mjs +27 -101
  105. package/doc-check/paragraph.mjs +218 -102
  106. package/doc-graph/anchors.mjs +474 -0
  107. package/doc-graph/doc-batch-face.mjs +59 -0
  108. package/doc-graph/doc-suffix.mjs +27 -0
  109. package/doc-graph/graph-tokens.mjs +160 -0
  110. package/doc-graph.mjs +778 -0
  111. package/explore-distill.mjs +11 -5
  112. package/i18n.mjs +1 -1
  113. package/instance-inbox-watch.mjs +272 -0
  114. package/instance-inbox.mjs +218 -0
  115. package/instance-registry.mjs +179 -0
  116. package/knowledge/README.md +3 -0
  117. package/knowledge/prompt-resources.md +6 -0
  118. package/ledger-close-proof.mjs +100 -49
  119. package/ledger-close.mjs +188 -0
  120. package/ledger-cmd.mjs +47 -91
  121. package/ledger-consistency.mjs +113 -0
  122. package/ledger-db.mjs +47 -15
  123. package/ledger-executors.mjs +1 -1
  124. package/ledger-tools.mjs +78 -19
  125. package/ledger-write-ops.mjs +130 -41
  126. package/ledger.mjs +1 -1
  127. package/manifest-discovery.mjs +3 -1
  128. package/manifest-schema.mjs +27 -5
  129. package/memory/schema.mjs +2 -2
  130. package/package.json +3 -1
  131. package/path-resolve.mjs +338 -57
  132. package/prompt-files.mjs +91 -1
  133. package/prompt-overlays.mjs +9 -6
  134. package/prompts/advisor-design.md +62 -21
  135. package/prompts/advisor-round1.md +34 -1
  136. package/prompts/advisor-round2.md +40 -7
  137. package/prompts/advisor-round3.md +39 -6
  138. package/prompts/common.md +14 -387
  139. package/prompts/consult-base.md +5 -1
  140. package/prompts/discipline-engineering.md +226 -51
  141. package/prompts/discipline-normal.md +4 -255
  142. package/prompts/knowledge/business-gates.md +22 -0
  143. package/prompts/knowledge/decision-quality.md +23 -0
  144. package/prompts/knowledge/doc-lookup.md +35 -0
  145. package/prompts/knowledge/document-writing.md +51 -0
  146. package/prompts/knowledge/documentation-evaluation.md +56 -0
  147. package/prompts/knowledge/evidence-discipline.md +57 -0
  148. package/prompts/knowledge/normal-coding-workflow.md +104 -0
  149. package/prompts/knowledge/normal-delivery-collaboration.md +108 -0
  150. package/prompts/knowledge/normal-work-management.md +57 -0
  151. package/prompts/knowledge/product-security.md +23 -0
  152. package/prompts/knowledge/project-records.md +62 -0
  153. package/prompts/knowledge/tool-advisor.md +29 -0
  154. package/prompts/knowledge/tool-apply-patch.md +18 -0
  155. package/prompts/knowledge/tool-bash.md +39 -0
  156. package/prompts/knowledge/tool-batch-eng-coder.md +12 -0
  157. package/prompts/knowledge/tool-batch-eng-designer.md +12 -0
  158. package/prompts/knowledge/tool-batch-review.md +12 -0
  159. package/prompts/knowledge/tool-batch.md +80 -0
  160. package/prompts/knowledge/tool-browser.md +57 -0
  161. package/prompts/knowledge/tool-code-search.md +4 -0
  162. package/prompts/knowledge/tool-consult-start.md +12 -0
  163. package/prompts/knowledge/tool-consult-stop.md +6 -0
  164. package/prompts/knowledge/tool-context.md +6 -0
  165. package/prompts/knowledge/tool-delete.md +17 -0
  166. package/prompts/knowledge/tool-doc-check.md +70 -0
  167. package/prompts/knowledge/tool-doc-graph-read.md +20 -0
  168. package/prompts/knowledge/tool-doc-graph.md +49 -0
  169. package/prompts/knowledge/tool-doc-search.md +6 -0
  170. package/prompts/knowledge/tool-edit.md +38 -0
  171. package/prompts/knowledge/tool-eng.md +2 -0
  172. package/prompts/knowledge/tool-execute.md +16 -0
  173. package/prompts/knowledge/tool-fetch.md +12 -0
  174. package/prompts/knowledge/tool-file-ops.md +16 -0
  175. package/prompts/knowledge/tool-get-current-time.md +7 -0
  176. package/prompts/knowledge/tool-git-read.md +19 -0
  177. package/prompts/knowledge/tool-git.md +29 -0
  178. package/prompts/knowledge/tool-glob.md +15 -0
  179. package/prompts/knowledge/tool-goal.md +8 -0
  180. package/prompts/knowledge/tool-grep.md +18 -0
  181. package/prompts/knowledge/tool-hashline-edit.md +14 -0
  182. package/prompts/knowledge/tool-insert-after.md +15 -0
  183. package/prompts/knowledge/tool-instance-list.md +6 -0
  184. package/prompts/knowledge/tool-instance-send.md +10 -0
  185. package/prompts/knowledge/tool-knowledge.md +18 -0
  186. package/prompts/knowledge/tool-ledger-read.md +35 -0
  187. package/prompts/knowledge/tool-ledger.md +42 -0
  188. package/prompts/knowledge/tool-lint.md +16 -0
  189. package/prompts/knowledge/tool-ls.md +13 -0
  190. package/prompts/knowledge/tool-lsp.md +11 -0
  191. package/prompts/knowledge/tool-main-history.md +2 -0
  192. package/prompts/knowledge/tool-manifest-read.md +14 -0
  193. package/prompts/knowledge/tool-manifest.md +31 -0
  194. package/prompts/knowledge/tool-memory-read.md +20 -0
  195. package/prompts/knowledge/tool-memory.md +15 -0
  196. package/prompts/knowledge/tool-notify-parent.md +12 -0
  197. package/prompts/knowledge/tool-operations.md +114 -0
  198. package/prompts/knowledge/tool-peer-instances.md +2 -0
  199. package/prompts/knowledge/tool-plan.md +6 -0
  200. package/prompts/knowledge/tool-process-read.md +13 -0
  201. package/prompts/knowledge/tool-process.md +15 -0
  202. package/prompts/knowledge/tool-question.md +16 -0
  203. package/prompts/knowledge/tool-read-history-batch.md +22 -0
  204. package/prompts/knowledge/tool-read-history.md +36 -0
  205. package/prompts/knowledge/tool-read-image.md +11 -0
  206. package/prompts/knowledge/tool-read.md +21 -0
  207. package/prompts/knowledge/tool-recent-changes.md +6 -0
  208. package/prompts/knowledge/tool-repo-outline.md +4 -0
  209. package/prompts/knowledge/tool-settings-read.md +12 -0
  210. package/prompts/knowledge/tool-settings.md +18 -0
  211. package/prompts/knowledge/tool-skill.md +6 -0
  212. package/prompts/knowledge/tool-ssh.md +52 -0
  213. package/prompts/knowledge/tool-subagent.md +59 -0
  214. package/prompts/knowledge/tool-task.md +12 -0
  215. package/prompts/knowledge/tool-team-ledger-read.md +11 -0
  216. package/prompts/knowledge/tool-team-ledger.md +11 -0
  217. package/prompts/knowledge/tool-timer.md +23 -0
  218. package/prompts/knowledge/tool-tree.md +14 -0
  219. package/prompts/knowledge/tool-verify.md +19 -0
  220. package/prompts/knowledge/tool-wait-for.md +25 -0
  221. package/prompts/knowledge/tool-websearch.md +19 -0
  222. package/prompts/knowledge/tool-write.md +9 -0
  223. package/prompts/knowledge/upstream-protocol.md +43 -0
  224. package/prompts/persona-eng-coder.md +21 -3
  225. package/prompts/persona-eng-designer.md +131 -169
  226. package/prompts/persona-engineering.md +142 -84
  227. package/prompts/persona-explore.md +1 -1
  228. package/prompts/persona-plan.md +5 -1
  229. package/prompts/subagent-base.md +2 -0
  230. package/provider/anthropic.mjs +6 -4
  231. package/provider/core.mjs +3 -2
  232. package/provider/errors.mjs +29 -4
  233. package/provider/google.mjs +24 -7
  234. package/provider/responses.mjs +3 -1
  235. package/provider-flows.mjs +2 -2
  236. package/session-index-build.mjs +1 -1
  237. package/session-index-pass.mjs +1 -1
  238. package/session-index-query.mjs +1 -1
  239. package/session-index.mjs +1 -1
  240. package/session-lifecycle.mjs +72 -17
  241. package/session-slot-write.mjs +37 -5
  242. package/session.mjs +24 -8
  243. package/skip-dirs.mjs +2 -2
  244. package/team-ledger.mjs +13 -9
  245. package/token-ttl.mjs +73 -4
  246. package/token-window.mjs +167 -33
  247. package/tool-docs/advisor.md +2 -27
  248. package/tool-docs/apply_patch.md +1 -15
  249. package/tool-docs/bash.md +2 -41
  250. package/tool-docs/batch-eng-coder.md +3 -0
  251. package/tool-docs/batch-eng-designer.md +3 -0
  252. package/tool-docs/batch-review.md +3 -0
  253. package/tool-docs/batch.md +2 -84
  254. package/tool-docs/browser.md +2 -49
  255. package/tool-docs/code_search.md +2 -2
  256. package/tool-docs/consult_start.md +2 -8
  257. package/tool-docs/consult_stop.md +2 -4
  258. package/tool-docs/context.md +1 -5
  259. package/tool-docs/delete.md +2 -17
  260. package/tool-docs/doc_check.md +2 -107
  261. package/tool-docs/doc_graph-read.md +3 -0
  262. package/tool-docs/doc_graph.md +3 -0
  263. package/tool-docs/doc_search.md +2 -4
  264. package/tool-docs/edit.md +1 -38
  265. package/tool-docs/eng.md +3 -1
  266. package/tool-docs/execute.md +2 -18
  267. package/tool-docs/fetch.md +2 -14
  268. package/tool-docs/file_ops.md +2 -18
  269. package/tool-docs/get_current_time.md +1 -6
  270. package/tool-docs/git-read.md +3 -0
  271. package/tool-docs/git.md +2 -35
  272. package/tool-docs/glob.md +2 -10
  273. package/tool-docs/goal.md +1 -6
  274. package/tool-docs/grep.md +2 -18
  275. package/tool-docs/hashline_edit.md +2 -15
  276. package/tool-docs/insert_after.md +2 -16
  277. package/tool-docs/instance_list.md +3 -0
  278. package/tool-docs/instance_send.md +3 -0
  279. package/tool-docs/knowledge.md +3 -0
  280. package/tool-docs/ledger-read.md +3 -0
  281. package/tool-docs/ledger.md +3 -8
  282. package/tool-docs/lint.md +2 -10
  283. package/tool-docs/ls.md +2 -11
  284. package/tool-docs/lsp.md +2 -9
  285. package/tool-docs/main_history.md +3 -1
  286. package/tool-docs/manifest-read.md +2 -8
  287. package/tool-docs/manifest.md +2 -35
  288. package/tool-docs/memory-read.md +3 -0
  289. package/tool-docs/memory.md +2 -20
  290. package/tool-docs/notify_parent.md +2 -13
  291. package/tool-docs/peer_instances.md +3 -1
  292. package/tool-docs/plan.md +1 -5
  293. package/tool-docs/process-read.md +3 -0
  294. package/tool-docs/process.md +2 -13
  295. package/tool-docs/question.md +3 -17
  296. package/tool-docs/read.md +2 -19
  297. package/tool-docs/read_history-batch.md +3 -0
  298. package/tool-docs/read_history.md +2 -18
  299. package/tool-docs/read_image.md +2 -9
  300. package/tool-docs/recent_changes.md +2 -2
  301. package/tool-docs/repo_outline.md +2 -2
  302. package/tool-docs/settings-read.md +3 -0
  303. package/tool-docs/settings.md +1 -12
  304. package/tool-docs/skill.md +2 -6
  305. package/tool-docs/ssh.md +1 -62
  306. package/tool-docs/subagent.md +2 -100
  307. package/tool-docs/task.md +1 -7
  308. package/tool-docs/team_ledger-read.md +3 -0
  309. package/tool-docs/team_ledger.md +3 -9
  310. package/tool-docs/timer.md +2 -19
  311. package/tool-docs/tree.md +2 -13
  312. package/tool-docs/verify.md +2 -12
  313. package/tool-docs/wait_for.md +2 -32
  314. package/tool-docs/websearch.md +2 -19
  315. package/tool-docs/write.md +2 -12
  316. package/tools/browser.mjs +52 -7
  317. package/tools/doc-write-gate.mjs +73 -0
  318. package/tools/edit-batch.mjs +170 -92
  319. package/tools/edit-diff.mjs +78 -62
  320. package/tools/edit-receipt.mjs +39 -0
  321. package/tools/execute.mjs +1 -1
  322. package/tools/file.mjs +16 -8
  323. package/tools/git.mjs +24 -9
  324. package/tools/index.mjs +6 -0
  325. package/tools/knowledge.mjs +143 -0
  326. package/tools/linter.mjs +3 -3
  327. package/tools/ops.mjs +3 -1
  328. package/tools/patch.mjs +123 -43
  329. package/tools/shared.mjs +28 -27
  330. package/tools/write-gate-params.mjs +31 -0
  331. package/tools/write-path.mjs +16 -4
  332. package/window-policy.mjs +203 -0
  333. package/doc-check/anchors.mjs +0 -235
@@ -0,0 +1,129 @@
1
+ /**
2
+ * agent/batch-changed-surface.mjs — 收口档位臂取材面的判据一族(从 `agent-tools/batch-closeout.mjs` 拆出):
3
+ * 比较键 `surfaceKey` ∥ 显示式 `displayRelOf` ∥ 三处判据 `selfAttributedOf` / `sessionClaimsOf` / `neighborListClaims`。
4
+ *
5
+ * 语义单源 = `docs/core/design/BATCH-RECORD.md` §4.18.1(本批改动面的取材:写时归属作判据一 ∥ 提交 diff 按认领收窄);
6
+ * 本档只实现它,不重述口径。
7
+ *
8
+ * 依赖单向:`agent-tools/batch-closeout.mjs` → 本档——入口 `changedSurface` 与回执段 `changedSurfaceReceiptLine`
9
+ * 留在那里;本档不 import 它,两档不成环。比较键随判据一族住在这里:三处判据都用它,留在入口侧就要反向 import。
10
+ *
11
+ * 本档不是无依赖那一形(同族的 `batch-attribution.mjs` 才是「零 fs、零 import」):认领的计划源本来就要读盘、
12
+ * 要问 git——`batchDirs` ∥ `machineListRowsOf` ∥ `baseShaOf` ∥ `committedDocs` 都在它的取材路径上。
13
+ */
14
+ import { readdirSync, readFileSync } from "node:fs"
15
+ import { isAbsolute, relative, resolve } from "node:path"
16
+
17
+ import { owningProject } from "../manifest.mjs"
18
+ import { batchDirs } from "../doc-check/existence.mjs"
19
+ import { baseShaOf } from "../agent-tools/batch-gate.mjs"
20
+ import { committedDocs, committedDocsUpto, lastCommitOf } from "../agent-tools/batch-regions.mjs"
21
+ import { isBatchRecord, machineListRowsOf, readBatchStatusLine } from "../agent-tools/batch-segment-vocab.mjs"
22
+ import { attributedTo } from "./batch-attribution.mjs"
23
+
24
+ /** 比较键(绝对路径归一:`/` 分隔符 + win32 折小写)——归属表、认领表与改动面条目三处共用一把尺。 */
25
+ export function surfaceKey(p) {
26
+ const s = resolve(String(p ?? "")).replace(/\\/g, "/")
27
+ return process.platform === "win32" ? s.toLowerCase() : s
28
+ }
29
+
30
+ /** 显示用的仓根相对路径(**不折大小写**:折小写是比较键的事,回执上印真名;仓外 ⇒ 照原值)。 */
31
+ export function displayRelOf(root, p) {
32
+ const raw = String(p ?? "").replace(/\\/g, "/")
33
+ if (typeof root !== "string" || root === "") return raw
34
+ const rel = relative(resolve(root), resolve(p)).replace(/\\/g, "/")
35
+ return rel === "" || rel.startsWith("../") || isAbsolute(rel) ? raw : rel
36
+ }
37
+
38
+ /** 归属表里归属**含本档**的路径集(比较键)。精确取件走叶档的 `attributedTo`,再按归一键补一遍:
39
+ * 表键与批档串在分隔符 ∥ 大小写上可能不同形,而判据一必须比认领更硬——少判的那一侧只许来自认领。 */
40
+ export function selfAttributedOf(agent, selfAbs) {
41
+ const mine = new Set(attributedTo(agent, selfAbs).map(surfaceKey))
42
+ const table = agent?._batchAttribution
43
+ if (!(table instanceof Map)) return mine
44
+ const self = surfaceKey(selfAbs)
45
+ for (const [batch, paths] of table) {
46
+ if (surfaceKey(batch) !== self) continue
47
+ for (const p of paths) mine.add(surfaceKey(p))
48
+ }
49
+ return mine
50
+ }
51
+
52
+ /** 本会话归属表里**别的批**的路径集(认领的观测源)。
53
+ * 不按批档状态筛:归属记的是「哪一批写了这一档」这件已发生的事,那一批收口之后这个事实不变——
54
+ * 同会话并行的两批,后收口的一方靠这一源减掉先收口那一方的档(正是「各自收口不为对方档要行」的实现面)。 */
55
+ export function sessionClaimsOf(agent, selfAbs) {
56
+ const table = agent?._batchAttribution
57
+ const claims = new Set()
58
+ if (!(table instanceof Map)) return claims
59
+ const self = surfaceKey(selfAbs)
60
+ for (const [batch, paths] of table) {
61
+ if (surfaceKey(batch) === self) continue
62
+ for (const p of paths) claims.add(surfaceKey(p))
63
+ }
64
+ return claims
65
+ }
66
+
67
+ /** 盘上**别的批档**已认领的路径集(认领的计划源),`Map<比较键, 批档绝对路径>`。
68
+ *
69
+ * 清单只是**计划面**——它声明打算改哪些档,不证明真改了;单凭计划认领,一条永不兑现的计划就能把一档从
70
+ * 每一批的判据里摘出去。故本源另加三条(缺一不认领):
71
+ * ① 该档确在**那份批档自己的**区间之内(`baseShaOf` 取那份批档的 sha,`committedDocs` ∥ `committedDocsUpto` 给档清单);
72
+ * ② 那份批档与本次收口**同项目根**——跨项目同名的相对路径不认领;
73
+ * ③ 那份批档**状态可读**(`readBatchStatusLine` 三值):收口不改变归属事实,所以已收口的批同样靠本源认领,
74
+ * 缺的只是上界——上界随状态定:`open` ⇒ `HEAD`(`committedDocs`,答「目前改到哪」),`closed` ⇒ 那份批档
75
+ * 自己的最后一次改动提交(`lastCommitOf` + `committedDocsUpto`),取不到上界就不认领。`unknown`(无状态行 ∥
76
+ * 两条以上 ∥ 两词皆不命中)与写锁同口按冻结处置:状态不明的一方不给认领权(不明不等于未收口)。
77
+ * 为什么 `closed` 不能也取 HEAD:收口批的区间会一直往后长,「该档在它的区间之内」对它几乎恒真 ⇒ 计划面变回
78
+ * 所有权,正是①要防的静默放过;钉死上界之后,认领面退回「那一批确实改过的档」。
79
+ * **失败面**:本函数逐条链批各算一次,那几笔读不出——`baseShaOf` 回 `null`、两函数回 `ok: false`、
80
+ * `lastCommitOf` 回 `null`——一律 `continue` 按「认领不成立」处置:那一档照本批判,本批收口照跑。
81
+ * 拒收口那一条只属 `changedSurface` 自己那一笔 diff(邻批的缺陷不得拦本批的收口)。
82
+ * 抽取面 = `machineListRowsOf`(机读清单读取)+ `batchDirs`(批档目录):按「哪一份批档列了哪一档」取,
83
+ * 不取跨批合并后的路径集(并集给不出①要的那份批档自己的批起 sha)。 */
84
+ export function neighborListClaims(root, selfAbs) {
85
+ const claims = new Map()
86
+ const self = surfaceKey(selfAbs)
87
+ const base = resolve(root)
88
+ for (const dir of batchDirs(base)) {
89
+ let names
90
+ try { names = readdirSync(dir) } catch { continue }
91
+ for (const name of names) {
92
+ if (!name.toLowerCase().endsWith(".md")) continue
93
+ const abs = resolve(dir, name)
94
+ if (surfaceKey(abs) === self) continue
95
+ let src
96
+ try { src = readFileSync(abs, "utf8") } catch { continue }
97
+ // 认领面只收**可读状态**的批档:收口批靠它自己的区间上界认领,`unknown`(无状态行 ∥ 两条以上 ∥ 两词皆不命中)
98
+ // 与写锁同口按冻结处置——状态不明的一方不给认领权(不明不等于未收口,认领是往「少判」方向倒的那一条)。
99
+ if (!isBatchRecord(src)) continue
100
+ const status = readBatchStatusLine(src)
101
+ if (status === "unknown") continue
102
+ const rows = machineListRowsOf(src)
103
+ if (rows.length === 0) continue
104
+ const owned = owningProject(abs, base)
105
+ if (!owned || surfaceKey(owned) !== surfaceKey(base)) continue // ②(取不到根 ⇒ 不认领)
106
+ const sha = baseShaOf(abs)
107
+ if (sha === null) continue // 没有它自己的批起 sha ⇒ 观测不成立
108
+ // 区间上界随状态定:未收口 ⇒ HEAD(右端继续往后长是对的,那一批还在写);
109
+ // 已收口 ⇒ 它自己的最后一次提交(钉死上界,否则「该档在它区间内」对它几乎恒真 ⇒ 计划面变所有权)。
110
+ let committed
111
+ if (status === "closed") {
112
+ const upper = lastCommitOf(base, abs)
113
+ if (upper === null) continue // 上界取不到 ⇒ 不认领(fail-closed:那一档照本批判)
114
+ committed = committedDocsUpto(base, sha, upper)
115
+ } else {
116
+ committed = committedDocs(base, sha)
117
+ }
118
+ if (!committed.ok) continue // 这一链读不出 ⇒ 不认领、本批照跑(拒收口只属本批自己的 diff 腿)
119
+ // 认领键与改动面条目同一坐标系(绝对路径归一)——两侧共用 `surfaceKey` 一把尺。
120
+ const changed = new Set()
121
+ for (const f of committed.files ?? []) changed.add(surfaceKey(resolve(committed.base, f)))
122
+ for (const row of rows) {
123
+ const key = surfaceKey(resolve(base, row.path))
124
+ if (changed.has(key)) claims.set(key, abs) // ①
125
+ }
126
+ }
127
+ }
128
+ return claims
129
+ }
@@ -13,6 +13,9 @@ import { poolLive } from "./suspension.mjs"
13
13
  const MAX_VERIFY_PUSHBACKS = 2
14
14
  const MAX_VERIFY_RETRIES = 3
15
15
  const MAX_ADVISOR_PUSHBACKS = 3
16
+ // 层 2(ADVISOR-CONVERGENCE.md §6.4 B):同一未评审周期的提醒硬上限——续跑与段重启都不回满。
17
+ // 取 5 而非 3:进展窗口预算保持原值 3,周期上限再给一次「真改了代码还是漏评审」的宽限。
18
+ const MAX_ADVISOR_REMINDERS = 5
16
19
  const MAX_EMPTY_RETRIES = 2
17
20
 
18
21
  /**
@@ -152,13 +155,51 @@ export function handleCompletion(agent, response, depth, turn, guardPushbacks, h
152
155
  const pending = advisorReviewPending(agent)
153
156
  // rounds 仅作提醒文案显示(撤 cap——轮次不是终止判据;ADVISOR-CONVERGENCE.md §3.1)。
154
157
  const rounds = effectiveAdvisorRound(agent)
155
- if (!pending && agent._mutatedThisRun && !agent._calledAdvisorThisRun && hasCodeMutations(agent)
156
- && advisorPushbacks < MAX_ADVISOR_PUSHBACKS) {
158
+ // 「未评审即收尾」的四项合取(既有判据逐字零改)+ 两支出口(推回一条 ∥ 任一层停推后的到顶诚实提醒,§6.4 A/B)。
159
+ // `!pending` 同属两支的一部分:异步评审在飞 = 未决,不是未评审——此时推「未经评审」的诚实声明
160
+ // 会与正在跑的评审自相矛盾。
161
+ const unreviewed = !pending && agent._mutatedThisRun && !agent._calledAdvisorThisRun && hasCodeMutations(agent)
162
+ // 层 1(进展窗口,§6.4 A)+ 层 2(未评审周期,§6.4 B)都还有余量 ⇒ 推一条。
163
+ // 计数落 agent:回合环那个 `advisorPushbacks` 是 `runAgent` 局部量,续跑重进即归零(上限形同没设)。
164
+ if (unreviewed && (agent._advisorReminders ?? 0) < MAX_ADVISOR_REMINDERS && advisorPushbacks < MAX_ADVISOR_PUSHBACKS) {
165
+ agent._advisorReminders = (agent._advisorReminders ?? 0) + 1
157
166
  advisorPushbacks++
158
167
  pushReal(agent, { role: "assistant", content: response.content })
159
168
  agent.history.push({
160
169
  role: "user",
161
- content: `[System reminder: you changed code in this run and MUST get an advisor review before finishing (round ${rounds + 1}). Call the \`advisor\` tool now. This is required, not optional — do not skip it even if you believe the changes are trivial — the review will be quick either way. After the review, produce a response table for every issue found (see discipline rules for format).]`,
170
+ content: `[System reminder: you changed code in this run and MUST get an advisor review before finishing (round ${rounds + 1}). Call the \`advisor\` tool now. This is required, not optional — do not skip it even if you believe the changes are trivial — the review will be quick either way. After the review, produce a response table for every issue found (see discipline rules for format).${
171
+ agent._advisorReminders >= MAX_ADVISOR_REMINDERS
172
+ ? ` This is reminder ${MAX_ADVISOR_REMINDERS} of ${MAX_ADVISOR_REMINDERS} — the last one. If you deliver without an advisor review, state explicitly in your reply to the user that this code has not been reviewed.`
173
+ : ""
174
+ }]`,
175
+ })
176
+ callbacks.onSubTurnBreak?.()
177
+ callbacks.onTurnEnd?.(agent, turn)
178
+ return { action: "continue", guardPushbacks, honestReminderInjected, advisorPushbacks }
179
+ }
180
+ // **任一层停推**(层 1 或层 2 耗尽 ⇒ 本轮推不成)⇒ 推**一条**诚实提醒,其后本轮放行收尾。
181
+ // 判据不写成「推满 5 条」:层 1 的预算只在真写了文件时回满(§6.4 A),所以「改过一次代码后只读不写」
182
+ // 是最常见形态——层 1 停在 3 条时只认 5 条的到顶条件永不成真,两支都不进 ⇒ 直接 `done`、零诚实提醒,
183
+ // 正是本机制要挡的「未评审即交付且静默」。
184
+ // 到顶静默放行 = 把「未评审即交付」这条业务失败做成静默成功,而这道 guard 存在的目的就是挡它:
185
+ // 形态照 verify 面到顶(本档上方 `// Exhausted retries — inject honesty reminder once`)——同形、
186
+ // 只换主语,不新增用户可见标记 / 字段 / 配置键。
187
+ // 一次性位的复位口径(§1 20:39 裁定):位**随新进展复位**——与推回预算同一处(`turn-loop.mjs` 的写序推进
188
+ // 点,两行手拉手),另在本周期两处复位点(新用户回合起点 ∥ 评审覆盖成立处)一并归假。故口径是
189
+ // 「每次停推且仍未评审的收尾恰得一条诚实提醒」——不存在「发过一条之后本周期彻底静默」的第二条静默途径,
190
+ // 而「本轮发过就再也不发」会让「诚实提醒 → 又改代码 → 再收尾」整段不吭声(正是本批要堵的形状)。
191
+ // 文案只陈述事实(几条已发 ∥ 代码未评审 ∥ 二选一),**不**许诺「不再推」——层 1 先耗尽的形态下,
192
+ // 后续有新进展仍会再推提醒(§1 20:39 裁定第二条)。条数取 `?? 0`:复位点 2 清零后层 1 耗尽可达,别读出 undefined。
193
+ if (
194
+ unreviewed
195
+ && ((agent._advisorReminders ?? 0) >= MAX_ADVISOR_REMINDERS || advisorPushbacks >= MAX_ADVISOR_PUSHBACKS)
196
+ && !agent._advisorHonestySent
197
+ ) {
198
+ agent._advisorHonestySent = true
199
+ pushReal(agent, { role: "assistant", content: response.content })
200
+ agent.history.push({
201
+ role: "user",
202
+ content: `[System reminder: ${agent._advisorReminders ?? 0} advisor reminders sent. You have not had this code reviewed. Either call the \`advisor\` tool now, or state explicitly in your reply that this code has not been reviewed — do not present the work as reviewed. The user needs to know it is unreviewed.]`,
162
203
  })
163
204
  callbacks.onSubTurnBreak?.()
164
205
  callbacks.onTurnEnd?.(agent, turn)
@@ -132,6 +132,12 @@ export function isSubagentEscalateAction(toolName, args) {
132
132
  export function readonlyActionOf(tool, toolName, args) {
133
133
  return tool?.isReadonlyAction?.(args) ?? isReadonlyAction(toolName, args)
134
134
  }
135
+ /** 只读变体派生面的谓词形(`(tool, args)`——`readonlyActionOf` 的单参适配,单源只此一处)。
136
+ * 消费点 = `agent/helpers.mjs` 的 `makeReadonlyToolVariant` / `deriveReadonlyTools` 注入面:
137
+ * 构造器不 import 本档(本档 import 它——成环),故由调用方把这枚函数传进去(TOOLS.md §6.29 ①)。 */
138
+ export function readonlyActionTest(tool, args) {
139
+ return readonlyActionOf(tool, tool?.name, args)
140
+ }
135
141
  export function controlActionOf(tool, toolName, args) {
136
142
  return tool?.isControlAction?.(args) ?? isSubagentControlAction(toolName, args)
137
143
  }
@@ -114,8 +114,11 @@ export async function executeToolCalls(agent, toolByName, toolCalls, callbacks,
114
114
  }
115
115
  if (blocked) {
116
116
  // Undeclared project → point at ITS declaration file (§4.3 降级可见契约; #1102).
117
+ // 文案不列段名:本支只在 `!conv.declared` 时发,而 `declared` 是值比较(`buildDeclaration`)
118
+ // ⇒ 未声明 ⇒ `codePaths` 与缺省逐项相等 = 空。默认段自 2026-11-10 起清空(KD-M1-31),
119
+ // 原先 `code paths: ${…join}` 的空集渲染会印出一句残句,故改述判据来源(兜底分类)。
117
120
  const convNote = noteConv
118
- ? ` — this path was classified as product code by the default conventions (code paths: ${noteConv.codePaths.join(", ")}); declare project conventions in ${manifestFilePath(noteConv.root)} to adjust.`
121
+ ? ` — this path fell through to product code (no code segment is declared: code paths are empty); declare project conventions in ${manifestFilePath(noteConv.root)} to adjust.`
119
122
  : ""
120
123
  prepared.push({
121
124
  toolCall, tool, denied: true,
@@ -162,8 +165,10 @@ export async function executeToolCalls(agent, toolByName, toolCalls, callbacks,
162
165
  // 写锁(第三道 · 2026-11-03 笔-账绑定批 · 设计档 §2.3):本笔报的 `ledger:"#N"` 必须是**目标所属项目**
163
166
  // 台账里一条 `status = 在途` 的行。位次 = 既有两道之后(既有拒因先报);判序 = 先判目标所属项目
164
167
  // (出辖 ⇒ 门不管),再按号查该根台账;台账读不到 ⇒ 拒(业务门)。
165
- // 入口集 = 十三把(写盘七件 + `bash` ∥ `execute` + `git` + `manifest` ∥ `memory` + `ssh`)——`bash` ∥ `execute`
166
- // 与写盘工具同一判据、不按命令内容分类(决策 36);`git` 只对写型 action 要号(决策 37);`ssh` 只对 `get` 要号。
168
+ // 入口集 = 十一把(写盘七件 + `bash` ∥ `execute` + `memory` + `ssh`)——`bash` ∥ `execute`
169
+ // 与写盘工具同一判据、不按命令内容分类(决策 36);`ssh` 只对 `get` 要号。`git` **不在集内**(决策 37 改判):
170
+ // 它不落新字节,写型与只读同为不要号 ⇒ 本门不问它的 action;`manifest` **不在集内**(决策 44):本门自己要
171
+ // 读它写的那份档(取根 ∥ 写权表),把它也放在门后即构成环 ⇒ 三动作一概不要号。
167
172
  // 只在工程模式生效(`agent.config.agent.engineering`)∥ 只在 depth 0(子代理走既有 token 门)。
168
173
  // 路径集与 `args.ledger` 由判据函数自己取(调形只传 tool + toolName + args)。
169
174
  const ledgerConflict = await ledgerBindWriteConflict(agent, depth, tool, toolCall.name, args)
@@ -2,7 +2,7 @@
2
2
  * agent/family-tools.mjs — 家族矩阵单源(`assembleFamilyTools`)。
3
3
  *
4
4
  * 批次 `docs/batches/2026-09-15-vsc-tool-table-dup.md` §2.3A:家族矩阵(哪个运行面得哪些
5
- * 家族工具)自 CLI 侧 `agent/setup.mjs` 的 `assembleFamilyTools`(as-of 迁出前坐标)整体迁出——CLI 与 VSC 同调同一份实现
5
+ * 家族工具)自 CLI 侧 `agent/setup.mjs` 的 `assembleFamilyTools` 整体迁出——CLI 与 VSC 同调同一份实现
6
6
  * (消灭「同一角色矩阵两份实现」= 本批缺陷的类根因);端差(VSC 装饰链 / settings 追加 /
7
7
  * consult 池来源)经 `decorate` 注入——**不传 = 核默认形态**(CLI = 迁出前逐字)。
8
8
  *
@@ -17,6 +17,8 @@
17
17
  * 核内先例 = 登记册头注「Loaded from agent.mjs via dynamic import to avoid ESM circular
18
18
  * dependencies」(本档先于 `agent/setup.mjs` 的调用点载入,同一语义)。
19
19
  */
20
+ import { knowledgeTool } from "../tools/knowledge.mjs"
21
+
20
22
  export async function assembleFamilyTools({
21
23
  depth, // number 0 = 主 agent;>0 = 子代理
22
24
  role = null, // string 子代理角色(eng-coder / eng-designer / coder / consult / explore / …)
@@ -26,7 +28,7 @@ export async function assembleFamilyTools({
26
28
  decorate = null, // object 端差面:{ subagent?, consultStart?, consultStop?, settings? }
27
29
  } = {}) {
28
30
  // CORE-UNIFICATION TOOLS #83:consult 家族随统一登记册自 `../agent-tools.mjs` 取用(单一来源)
29
- const { planTool, subagentTool, taskTool, skillTool, goalTool, verifyTool, recentChangesTool, timerTool, advisorTool, engTool, readHistoryTool, contextTool, batchTool, manifestTool, manifestReadTool, consultStartTool, consultStopTool, parentChannelTool, docCheckTool } = await import("../agent-tools.mjs")
31
+ const { planTool, subagentTool, taskTool, skillTool, goalTool, verifyTool, recentChangesTool, timerTool, advisorTool, engTool, readHistoryTool, contextTool, batchTool, manifestTool, manifestReadTool, consultStartTool, consultStopTool, parentChannelTool, docCheckTool, docGraphTool, docGraphReadTool } = await import("../agent-tools.mjs")
30
32
  // 台账统一入口(2026-10-05 统一入口批——台账 #923):全量变体 = depth-0 段 ∥ 只读变体 = 全部
31
33
  // depth>0 段。动态 import——ledger 链静态达 node:sqlite(W8 契约②);两变体同名单对象、schema 窄化。
32
34
  const { ledgerTool, ledgerReadTool } = await import("../ledger.mjs")
@@ -132,6 +134,9 @@ export async function assembleFamilyTools({
132
134
  ? "Spawn a read-only `explore` sub-agent to SURVEY the current state for the design: it reads code / docs / existing designs and reports evidence with file:line. BLOCKING ONLY (no async) and action:'spawn' ONLY — the survey channel is read-only; escalate/status/cancel/panel/consume-design/observe/send are not available. Survey budget: ≤6 explore spawns per batch — the main agent's survey result is reference only; do your own. The spawn carries the five task-book parameters (four core: goal / knownFacts / acceptance / reportFormat + `scope`); a task-only spawn is refused."
133
135
  : "Spawn a read-only `explore` sub-agent to AUDIT your delivery against the design: it compares the delivered code with the design for divergence — partially implemented acceptance criteria, silent simplifications, doc drift, changes outside the approved file list. BLOCKING ONLY (no async — the audit report decides your next protocol step). action:'spawn' ONLY — the audit channel is a read-only spawn; escalate/status/cancel/panel/consume-design/observe/send are not available. The audit context is appended MECHANICALLY — the batch record path (its §2 is the delivery's task book, read it before judging) plus the files you actually touched; never hand the audit a self-written file list (a self-report could omit exactly the out-of-scope file it must catch). The spawn carries the five task-book parameters (four core: goal / knownFacts / acceptance / reportFormat + `scope`); a task-only spawn is refused.",
134
136
  parameters: { ...subagentTool.parameters, properties: props },
137
+ // `async` 不在本变体 schema 里(`delete props.async`)= 这条通道**没有异步选项**。`async` 必填化后
138
+ // 由变体自己声明固定值(同步),而不是给模型留一个缺省——缺省就是替调用方拿主意,同步才是本通道的契约。
139
+ execute: (args, ctx) => subagentTool.execute({ ...args, async: false }, ctx),
135
140
  }
136
141
  })()
137
142
  : null
@@ -145,6 +150,12 @@ export async function assembleFamilyTools({
145
150
  ? [decorate?.consultStart ?? withPool(consultStartTool), decorate?.consultStop ?? consultStopTool]
146
151
  : []
147
152
 
153
+ // 文档工具面(`AGENT-LOOP-SUBAGENT.md` §6.60.1 · 需求 `docs/core/requirements/DOC-GRAPH.md` §4 AC-10):
154
+ // **一处写、五处展开**——`doc_check` 本就只读(无写 action 可收窄)⇒ 本体直挂;`doc_graph` 挂只读变体
155
+ // (三动作、无 `scan`:子代理段的台账是只读变体,扫由父侧做——D-DT1)。五段各写一遍字面就是五份会各自漂的
156
+ // 单子(D-DT4);并成一段又会抹掉各段真实差异。depth-0 段不展开本组:那边挂的是全量 `docGraphTool` + `docCheckTool`。
157
+ const docTools = [docCheckTool, docGraphReadTool]
158
+
148
159
  const depthOnly = depth === 0
149
160
  ? [decorate?.subagent ?? filteredSubagent, skillTool, goalTool, engTool, verifyTool, recentChangesTool, readHistoryTool, contextTool, advisorTool, batchTool(null),
150
161
  ...consultTools,
@@ -153,11 +164,15 @@ export async function assembleFamilyTools({
153
164
  // 团队台账全量变体(五 action——同律:子代理段只挂读变体;登录态门在工具内)
154
165
  teamLedgerTool,
155
166
  // manifest 工具(`MANIFEST.md` §2.10 · 2026-10-08 · 台账 #1098):主 agent 读写出口——
156
- // **两模式同挂**(需求未设模式门);全量变体仅 depth-0——子代理各段挂只读变体(见下 `:187-193`)。
167
+ // **两模式同挂**(需求未设模式门);全量变体仅 depth-0——子代理各角色段挂只读变体(见下 depth>0 各段)。
157
168
  manifestTool,
158
- // 文档纪律机检(`DOC-DISCIPLINE.md` §3.20 条目 S):只读报告态——depth-0 主 agent 段;
159
- // 写文档 / 设计档的角色段(eng-coder / eng-designer)另挂(见下两分支)。
169
+ // 文档纪律机检(`DOC-DISCIPLINE.md` §3.20 条目 S):只读报告态——depth-0 主 agent 段挂本体;
170
+ // 全部 depth>0 角色段由下方 `docTools` 展开供给(`AGENT-LOOP-SUBAGENT.md` §6.60)。
160
171
  docCheckTool,
172
+ // 文档锚点图(`DOC-GRAPH.md` §2.5 · 需求 F1–F6):**两变体互斥装配**——本段(depth-0)挂全量四动作;
173
+ // 全部 depth>0 角色段挂只读变体(三动作、无 `scan`,契约 = `DOC-GRAPH.md` §2.5.5,装配矩阵单源 =
174
+ // `AGENT-LOOP-SUBAGENT.md` §6.60.2)。位置与 `docCheckTool` 同段(同一族:文档纪律面)。
175
+ docGraphTool,
161
176
  // 端差(decorate.settings——VSC depth-0 主 agent 面;缺省不追加):核默认形态里
162
177
  // settings 住**基础集**(`tools/index.mjs` `assembleBuiltinTools`),端侧自持清单
163
178
  // 无该面 ⇒ 端以 decorate 补位(收敛通道 = 将来去 decorate 项即归核位)。
@@ -188,13 +203,13 @@ export async function assembleFamilyTools({
188
203
  // 团队台账只读变体(team-ledger 批)同律。
189
204
  // manifest 只读变体(MANIFEST.md §2.10.1 · 2026-10-22 · 台账 #1738):同名 `manifest`、action 枚举只剩 `read`;
190
205
  // 与上两条只读先例同律挂在全部 depth>0 角色段(全量变体仅 depth-0——两变体互斥装配,同名不塌缩)。
191
- : engChildRole === "eng-coder" ? [parentChannelTool, ledgerReadTool, teamLedgerReadTool, manifestReadTool, advisorTool, verifyTool, batchTool(batchDoc), docCheckTool,
206
+ : engChildRole === "eng-coder" ? [parentChannelTool, ledgerReadTool, teamLedgerReadTool, manifestReadTool, advisorTool, verifyTool, batchTool(batchDoc, { role: "eng-coder" }), ...docTools,
192
207
  ...(engChildSubagent ? [engChildSubagent] : [])]
193
- : engChildRole === "eng-designer" ? [parentChannelTool, ledgerReadTool, teamLedgerReadTool, manifestReadTool, batchTool(batchDoc), docCheckTool,
208
+ : engChildRole === "eng-designer" ? [parentChannelTool, ledgerReadTool, teamLedgerReadTool, manifestReadTool, batchTool(batchDoc, { role: "eng-designer" }), ...docTools,
194
209
  ...(engChildSubagent ? [engChildSubagent] : [])]
195
- : role === "coder" ? [parentChannelTool, ledgerReadTool, teamLedgerReadTool, manifestReadTool, verifyTool, advisorTool, ...(batchDoc ? [batchTool(batchDoc)] : [])]
196
- : role === "consult" ? [recentChangesTool, ledgerReadTool, teamLedgerReadTool, manifestReadTool]
197
- : [parentChannelTool, ledgerReadTool, teamLedgerReadTool, manifestReadTool]
210
+ : role === "coder" ? [parentChannelTool, ledgerReadTool, teamLedgerReadTool, manifestReadTool, verifyTool, advisorTool, ...docTools, ...(batchDoc ? [batchTool(batchDoc, { role: "coder" })] : [])]
211
+ : role === "consult" ? [recentChangesTool, ledgerReadTool, teamLedgerReadTool, manifestReadTool, ...docTools]
212
+ : [parentChannelTool, ledgerReadTool, teamLedgerReadTool, manifestReadTool, ...docTools]
198
213
 
199
214
  // 固定段(装配序 = agent.tools → 固定段 → 家族段 → extraTools):timer 全模式全深度;
200
215
  // plan 随模式位——ENG-PLAN-EXCLUSION(FR31 ① · KD8 卸载而非「注册 + 报错」· KD11 全深度两端);
@@ -204,6 +219,6 @@ export async function assembleFamilyTools({
204
219
  // 判据 = 单一模式位 `engineering`(不带深度分支——子代理面随同排除,role enum
205
220
  // `subagentRoles` + spawn 门 / task execute 门已同向)。
206
221
  return engineering
207
- ? [timerTool, ...depthOnly]
208
- : [taskTool, planTool, timerTool, ...depthOnly]
222
+ ? [timerTool, knowledgeTool, ...depthOnly]
223
+ : [taskTool, planTool, timerTool, knowledgeTool, ...depthOnly]
209
224
  }
package/agent/helpers.mjs CHANGED
@@ -6,6 +6,8 @@ import { homedir } from "node:os"
6
6
  import { join } from "node:path"
7
7
  import { execFile } from "node:child_process"
8
8
  import { promisify } from "node:util"
9
+ // 只读变体的描述取值面(§6.29 ①「描述」行:档名 → `DESC` → `loadToolDoc`,档定义期读一次)
10
+ import { DESC } from "../tools/shared.mjs"
9
11
  export { offloadToolResult, cleanupOldToolResults, TMP_RETENTION_MS } from "./offload.mjs"
10
12
 
11
13
  /** Single source for the AUTO-mode reminder (was duplicated in agent.mjs +
@@ -156,9 +158,13 @@ export class ContinueError extends Error {
156
158
  export const INHERITED_GUARD_KEYS = [
157
159
  "_mutatedThisRun", "_verifiedThisRun", "_verifyPassed", "_calledAdvisorThisRun",
158
160
  "_touchedFiles", "_verifyRetries", "_advisorRound",
161
+ // ADVISOR-CONVERGENCE.md §6.4「状态的跨段存活」:advisor 提醒计数与到顶诚实提醒的一次性位同进清单——
162
+ // 不在清单里的字段不被 `restoreGuard` 回填,而自动回合收尾留下的 guard 三态照旧回填 ⇒ 计数不随、
163
+ // 下一次用户回合从零起,B 的周期上限形同没设。
164
+ "_advisorReminders", "_advisorHonestySent",
159
165
  ]
160
166
 
161
- /** 写侧单点:快照 7 键 → 纯对象(载体形态由调用方决定——核 = agent 字段 / 端 = 宿主容器)。 */
167
+ /** 写侧单点:快照 `INHERITED_GUARD_KEYS` 全部键 → 纯对象(载体形态由调用方决定——核 = agent 字段 / 端 = 宿主容器)。 */
162
168
  export function snapshotGuard(agent) {
163
169
  const snap = {}
164
170
  for (const k of INHERITED_GUARD_KEYS) snap[k] = agent[k]
@@ -284,6 +290,121 @@ export function readonlyToolNames(tools) {
284
290
  return new Set(tools.filter((t) => t.readonly).map((t) => t.name))
285
291
  }
286
292
 
293
+ // ─── 只读角色的 action 级变体(TOOLS.md §6.29 ①)───────────────────────────────
294
+ /** 嵌套动作键闭集(§6.29「嵌套动作的配对规则」):键 → 顶层 action。schema 是平铺的,配对只在
295
+ * 「顶层 action + 这个键的一个值」这一对上判;表外的键不参与配对。 */
296
+ const NESTED_ACTION_KEYS = {
297
+ stash: "stashAction",
298
+ worktree: "worktreeAction",
299
+ tag: "tagAction",
300
+ branch: "branchAction",
301
+ remote: "remoteAction",
302
+ checkpoint: "checkpointAction",
303
+ }
304
+
305
+ /** 只读变体登记表(**单源**——核装配 `agent-tools/subagent-spawn.mjs` ∥ `agent-tools/consult.mjs`
306
+ * 与端装配 `thincoder-vscode/src/agent/tool-table.mjs` 同取本表):
307
+ * - `doc` = 该变体的描述档名(`tool-docs/<doc>.md`);**没有登记的工具不挂入只读角色**
308
+ * (§6.29「档与角色」:`browser` ∥ `ssh` 的 `isReadonlyAction` 判的是审批门,不造变体)。
309
+ * - `writeOnly` = 只有被剔掉的写动作才消费的参数名。没有通用派生法:参数名与注释都不说
310
+ * 它服务哪个 action(`git` 的 `name` 挂在 `branch` 上,而 `branch` 的只读项 `list` 并不读它),
311
+ * 所以这一列按工具声明,动作集仍只由运行期谓词裁决(K2:不另立第二份动作名单)。 */
312
+ export const READONLY_VARIANT_DOCS = {
313
+ git: { doc: "git-read", writeOnly: ["message", "name", "remoteUrl", "tags", "mode", "rebaseAction", "dryRun", "create", "dest"] },
314
+ memory: { doc: "memory-read", writeOnly: ["title", "content", "tags", "id", "confirm", "ledger", "project"] },
315
+ settings: { doc: "settings-read", writeOnly: [] },
316
+ process: { doc: "process-read", writeOnly: ["pid", "id"] },
317
+ }
318
+
319
+ /**
320
+ * 只读变体构造器(§6.29 ①「共用 action 变体」):接收**工具、谓词、描述档名**三样注入,
321
+ * 本函数不持角色名单、也不复制任何工具的动作表。
322
+ *
323
+ * 三面同时收窄(K4):schema 的 `action.enum` 与嵌套键 `enum` ∥ 描述 ∥ execute 第二道门——
324
+ * 只删 enum 会留下写参数与全文诱导,只做文本过滤又会被直接 execute 绕过(provider 不保证执行 schema)。
325
+ *
326
+ * @param {object} tool — 原工具(读它的 `parameters`;执行仍回原 `execute`)
327
+ * @param {{docName: string, writeOnly?: string[], isReadonly: (tool: object, args: object) => boolean}} opts
328
+ * `isReadonly` = 运行期动作判据(调用点一律传 `readonlyActionOf` 的单参形 `readonlyActionTest`)。
329
+ * @returns {object} 同名只读变体(`readonly: true`)
330
+ */
331
+ export function makeReadonlyToolVariant(tool, { docName, writeOnly = [], isReadonly }) {
332
+ const params = tool.parameters ?? {}
333
+ const props = params.properties ?? {}
334
+ const declared = Array.isArray(props.action?.enum) ? props.action.enum : []
335
+ const keptActions = []
336
+ const keptNested = {}
337
+ for (const action of declared) {
338
+ const nestedKey = NESTED_ACTION_KEYS[action]
339
+ if (nestedKey && Array.isArray(props[nestedKey]?.enum)) {
340
+ // 候选形 = 「顶层 action + 同 schema 里被钩子读取的嵌套键」这一对;每个枚举值各成一候选
341
+ const values = props[nestedKey].enum.filter((v) => isReadonly(tool, { action, [nestedKey]: v }))
342
+ if (values.length > 0) {
343
+ keptActions.push(action)
344
+ keptNested[nestedKey] = values
345
+ }
346
+ continue
347
+ }
348
+ if (isReadonly(tool, { action })) keptActions.push(action)
349
+ }
350
+ // 缺省空调用候选(`process` 缺省 action = list):空调用判为只读 ⇒ action 不设必填,
351
+ // 必填与否就由它自己决定,而不是替调用方补一个默认值。
352
+ const emptyCallReadonly = isReadonly(tool, {})
353
+ const variantProps = {}
354
+ for (const [key, spec] of Object.entries(props)) {
355
+ if (key === "action") {
356
+ variantProps.action = {
357
+ ...spec,
358
+ enum: keptActions,
359
+ description: `Read-only variant: ${keptActions.join(" / ")} — the only actions this tool face carries. Every one of them only reads; write actions are not part of it.`,
360
+ }
361
+ continue
362
+ }
363
+ if (writeOnly.includes(key)) continue
364
+ const owningAction = Object.keys(NESTED_ACTION_KEYS).find((a) => NESTED_ACTION_KEYS[a] === key)
365
+ if (owningAction) {
366
+ // 嵌套键的 enum = 各保留顶层下只读值的并集;其顶层不在变体里 ⇒ 本键整枚不出现
367
+ if (keptNested[key]) variantProps[key] = { ...spec, enum: keptNested[key] }
368
+ continue
369
+ }
370
+ variantProps[key] = spec
371
+ }
372
+ const required = (params.required ?? []).filter((k) => !(k === "action" && emptyCallReadonly))
373
+ return {
374
+ ...tool,
375
+ description: DESC(docName), // 档定义期取值:全量档仍服务 depth-0,两变体各一份描述
376
+ parameters: { ...params, properties: variantProps, required },
377
+ readonly: true,
378
+ isReadonlyAction(args) { return isReadonly(tool, args) },
379
+ async execute(args, ctx) {
380
+ const call = args && typeof args === "object" ? args : {}
381
+ if (!isReadonly(tool, call)) {
382
+ const named = call.action === undefined ? "(no action)" : JSON.stringify(call.action)
383
+ throw new Error(`${tool.name}: ${named} is not available to a read-only role — this tool face carries only ${keptActions.join(" / ")}; nothing was executed (zero file write, zero ledger write, zero network write).`)
384
+ }
385
+ return tool.execute(args, ctx)
386
+ },
387
+ }
388
+ }
389
+
390
+ /**
391
+ * 只读角色的工具面(§6.29 B4):整把 `readonly` 工具原样 ∪ 登记的 action 级只读变体。
392
+ * `isReadonly` 注入面同 `makeReadonlyToolVariant`;`tester` 面不消费本函数(它只用整把只读集,不顺扩)。
393
+ * @param {object[]} tools — 调用方父面工具表
394
+ * @param {(tool: object, args: object) => boolean} isReadonly
395
+ * @returns {object[]} 新数组(原表零改)
396
+ */
397
+ export function deriveReadonlyTools(tools, isReadonly) {
398
+ const out = []
399
+ for (const t of tools ?? []) {
400
+ if (t?.readonly) { out.push(t); continue }
401
+ const reg = READONLY_VARIANT_DOCS[t?.name]
402
+ if (!reg) continue // 无描述档 ⇒ 不挂入只读角色(§6.29「档与角色」)
403
+ out.push(makeReadonlyToolVariant(t, { docName: reg.doc, writeOnly: reg.writeOnly, isReadonly }))
404
+ }
405
+ return out
406
+ }
407
+
287
408
  /** Depth>0 tool exclusions — subagents never get the interactive main-session tools (`question`:
288
409
  * no user to ask; `ssh`: the credential window is a user-facing event AND the session pool
289
410
  * belongs to the main session — no UI at depth>0 and no session to hand back; the routing
package/agent/offload.mjs CHANGED
@@ -4,38 +4,34 @@
4
4
  import { configDir } from "../config.mjs"
5
5
  import { writeFile, mkdir, readdir, stat, unlink } from "node:fs/promises"
6
6
  import { join } from "node:path"
7
- import { safeSliceUTF16 } from "../text-budget.mjs"
7
+ import { safeSliceUTF16, safeSliceUTF16Tail } from "../text-budget.mjs"
8
8
 
9
9
  const TOOL_RESULT_OFFLOAD_LIMIT = 64 * 1024 // 65536 chars — offload only above 64K (2026-08-24)
10
10
  const TOOL_RESULT_PREVIEW = 64 * 1024 // total preview budget: head + middle note + tail ≤ 65536 (aligns with CLI/VS Code webview)
11
- const TOOL_RESULT_PREVIEW_HEAD = 16 * 1024 // head slice preserved (2026-09-04 §5 — dual-end preview)
12
- const TOOL_RESULT_PREVIEW_TAIL = 48 * 1024 // nominal tail slice (results/errors/stats live here — actual tail = budget remainder, see buildDualEndPreview)
13
11
 
14
- /** UTF-16 safe END slice (2026-09-04 §5 dual-end preview — review #5: both boundaries must not split
15
- * a surrogate pair). Same rule as safeSliceUTF16, mirrored: if the slice START lands on a LOW
16
- * surrogate (DC00-DFFF — the second half of a pair whose high half sits just before the boundary),
17
- * advance one code unit so the slice never begins with an orphan low surrogate. */
18
- function safeSliceUTF16End(text, max) {
19
- if (text.length <= max) return text
20
- const start = text.length - max
21
- const cp = text.charCodeAt(start)
22
- if (cp >= 0xdc00 && cp <= 0xdfff) return text.slice(start + 1)
23
- return text.slice(start)
24
- }
25
-
26
- /** Dual-end preview (design §5 D-4.1): head + middle-omitted note + tail — the tail carries
27
- * results/errors/stats that a pure-head truncation would cut off.
28
- * Budget (round1 review #2, fixed): head + note + tail ≤ TOOL_RESULT_PREVIEW (65536) — tail is
29
- * computed from constants (tail = TOOL_RESULT_PREVIEW − head − noteLen), never hardcoded.
30
- * The note length depends on the omitted digit count; text.length's digit count is an upper bound
31
- * for omitted (< text.length), so budgeting with it keeps the total ≤ 65536 while the printed
32
- * note reports the actual omitted count. Both boundaries run surrogate-safe slices (review #5). */
33
- function buildDualEndPreview(text) {
34
- const head = safeSliceUTF16(text, TOOL_RESULT_PREVIEW_HEAD)
12
+ /** Dual-end preview: head + middle-omitted note + tail — the tail carries results/errors/stats that a
13
+ * pure-head truncation would cut off (design §5 D-4.1; `docs/core/design/TOOL-OUTPUT-LIMITS.md` §2).
14
+ *
15
+ * `budget` is REQUIRED and has no default (`CONTEXT-COMPACTION.md` §1.2): a default would decide the
16
+ * caller's crop size on its behalf. head = floor(budget / 4), the note reports the ACTUAL omitted
17
+ * count, tail = budget remainder (never a hardcoded number).
18
+ * The 64K face is byte-identical to before: floor(65536 / 4) = 16384 was the old fixed head, and the
19
+ * old 48K tail nominal was only ever `budget − head − note` — the cap never bit.
20
+ *
21
+ * Both cut points run the surrogate-safe slices exported by `text-budget.mjs`. The deleted local END
22
+ * slice guarded only the slice START; `safeSliceUTF16Tail` also drops a lone high surrogate at the
23
+ * trailing end, so a result that itself ends in half a surrogate pair loses one more code unit.
24
+ * Callers only pass text LONGER than the budget (a shorter body would come out twice). */
25
+ export function buildDualEndPreview(text, budget) {
26
+ if (!(typeof budget === "number" && Number.isFinite(budget) && budget > 0)) {
27
+ throw new Error("buildDualEndPreview: `budget` is required (a positive character budget, no default) — pass the preview budget this caller needs")
28
+ }
29
+ const t = String(text ?? "")
30
+ const head = safeSliceUTF16(t, Math.floor(budget / 4))
35
31
  const noteFn = (omitted) => `\n\n… [middle omitted: ${omitted} chars] …\n\n`
36
- const tailLen = Math.min(TOOL_RESULT_PREVIEW_TAIL, TOOL_RESULT_PREVIEW - TOOL_RESULT_PREVIEW_HEAD - noteFn(text.length).length)
37
- const tail = safeSliceUTF16End(text, tailLen)
38
- return head + noteFn(Math.max(0, text.length - head.length - tail.length)) + tail
32
+ const tailLen = Math.max(0, budget - head.length - noteFn(t.length).length)
33
+ const tail = safeSliceUTF16Tail(t, tailLen)
34
+ return head + noteFn(Math.max(0, t.length - head.length - tail.length)) + tail
39
35
  }
40
36
 
41
37
  /** Offload-dir write-time self-cleanup retention window (2026-08-21): files older than 3 days are deleted on the next offload. */
@@ -77,11 +73,11 @@ export async function offloadToolResult(text, callId, dir = join(configDir, "too
77
73
  const file = join(dir, `${Date.now()}-${String(callId).replace(/[^a-zA-Z0-9_-]/g, "_")}.log`)
78
74
  await writeFile(file, text, "utf8")
79
75
  if (!overLimit) return `${text}\n\n[... full content saved to: ${file}\nPage through it with the read tool (offset/limit) if you need the full text later.]`
80
- return buildDualEndPreview(text) + `\n\n[... output too large (${text.length} chars total), full content saved to: ${file}\n` +
76
+ return buildDualEndPreview(text, TOOL_RESULT_PREVIEW) + `\n\n[... output too large (${text.length} chars total), full content saved to: ${file}\n` +
81
77
  `Page through it with the read tool (offset/limit) or sed -n 'START,ENDp' — do NOT re-run the tool blindly.]`
82
78
  } catch {
83
79
  // 写盘失败不吞报告:>LIMIT 走双端预览 + 原文案;≤LIMIT 正文整段在前(不谎称 truncated)
84
- const body = overLimit ? buildDualEndPreview(text) : text
80
+ const body = overLimit ? buildDualEndPreview(text, TOOL_RESULT_PREVIEW) : text
85
81
  return body + (overLimit ? `\n\n[... truncated: ${text.length} chars total, offload to disk failed]`
86
82
  : `\n\n[... full text kept inline above (${text.length} chars), offload to disk failed]`)
87
83
  }