@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,140 @@
1
+ /**
2
+ * agent-tools/doc-graph.mjs — `doc_graph` 工具面:入参校验 ∥ 动作分派 ∥ 文本回执。
3
+ *
4
+ * 设计单源 = `docs/core/design/DOC-GRAPH.md` §2.5(工具面)∥ §2.5.5(两变体契约)∥ §3(登记面);机制单源 =
5
+ * `../doc-graph.mjs`。工具形与同族(`ledger` ∥ `team_ledger` ∥ `doc_check`)同构:**一个工具 + `action` 枚举**
6
+ * 四种问法(`scan` 扫 ∥ `forward` 正向 ∥ `reverse` 反向 ∥ `chain` 链路)——`doc_check` 那边是「判决」的两种问法,
7
+ * 两者判的东西不同,故不并成一个工具(KD-2)。
8
+ *
9
+ * **两变体同体、动作集一处字面**(构造单源 = `docs/core/design/AGENT-LOOP-SUBAGENT.md` §6.60.2 ②):参数化工厂
10
+ * `makeDocGraphTool(actions, { readonly, docName, unscanned })` 产出两形——全量 `docGraphTool`(四动作,depth-0 主 agent 段)
11
+ * ∥ 只读 `docGraphReadTool`(三动作、无 `scan`,全部 depth>0 角色段与 advisor 面)。动作集一处字面 `ALL_ACTIONS`、
12
+ * 只读集由它派生 ⇒ schema 的 `enum` ∥ execute 的护栏 ∥ 拒文里的取值集三处取同一个 `actions` 参数,变体不写第二份
13
+ * 字面对象(先例 = `../ledger-tools.mjs` 的 `makeLedgerTool`)。描述从同一 `actions` 生成(`ACTION_CLAUSES`)、
14
+ * 各自一份描述档;未建图策略(`unscanned`)由只读变体传 `readonly-empty`(TOOLS.md §6.29 ③)。
15
+ *
16
+ * **子代理段为什么不给 `scan`**:`scan` 把边落进台账库(`doc_edges` 表)——一次显式动作,没有常驻进程、没有 watch
17
+ * (需求 §3);而 depth>0 段拿到的台账是**只读**变体 ⇒ 同一段里没有可依的写面,多个子代理并发扫还会重写同一张共享
18
+ * 边表(D-DT1)。父侧扫一次、子代理查同一份库。只读性按 action 判(`isReadonlyAction`,与 `ledger` 同形):三个
19
+ * 查询走只读句柄、免审批;`scan` 走写面。
20
+ *
21
+ * **参数零默认**(设计 §2.5):`target` 恒必填;`forward` ∥ `reverse` ∥ `chain` 的 `node`、`chain` 的 `depth` 缺一即拒
22
+ * 并**点名**那一个——给默认值就是替调用方做决定。两个可选参数(`scan` 的 `scope` ∥ 三个读动作的 `kind`)缺席的含义
23
+ * 都由回执首行印出来(`全仓` / `范围 K 档` ∥ 本次生效的 kind 集合),不靠调用方记。
24
+ * `kind` 的**闭集校验住在核里**(`doc-graph.mjs` 的 `kindFilterOf`,闭集单源 = `ledger-db.mjs` 的 `DOC_EDGE_KINDS`):
25
+ * 本档只判形(必为字符串),闭集外拒并点名那个值由核做——一处校验,两个入口(工具 ∥ 直调核)。
26
+ *
27
+ * W8 契约②:本档只**动态** import `../doc-graph.mjs`(它自己再动态 import 台账库)——端壳静态闭包零 `node:sqlite`。
28
+ * 描述外置:模型可见文本单点 = `tool-docs/{doc_graph,doc_graph-read}.md`(`DESC` 单一解析面)——
29
+ * 两变体各一份描述档(TOOLS.md §6.29「描述面也分两份」:只读变体的字面里没有它执行不到的 `scan` 段)。
30
+ */
31
+ import { isAbsolute, resolve } from "node:path"
32
+ import { DESC } from "../tools/shared.mjs"
33
+
34
+ /** `target` 归一:相对路径按会话锚解析(锚缺位 + 相对形 ⇒ 拒、点名锚——不落 `process.cwd()`)。 */
35
+ function targetOf(args, ctx) {
36
+ const anchor = ctx?.agent?.cwd ?? ctx?.cwd
37
+ const given = args?.target
38
+ if (typeof given !== "string" || given.trim() === "") {
39
+ throw new Error("doc_graph:target 缺失(必填)——请给项目根(带 PROJECT-MANIFEST.json 的那个目录)")
40
+ }
41
+ if (!isAbsolute(given) && !anchor) {
42
+ throw new Error("doc_graph:会话锚不可用(`ctx.agent.cwd` / `ctx.cwd` 都空)——请把 target 写成绝对路径;相对 target 没有基根,本工具不落 `process.cwd()`")
43
+ }
44
+ return resolve(anchor ?? ".", given)
45
+ }
46
+
47
+ /** 全量动作集——本档唯一字面。 */
48
+ const ALL_ACTIONS = ["scan", "forward", "reverse", "chain"]
49
+ /** 只读动作集——由上一行派生,不写第二份字面(`scan` 归主 agent,见文件头)。 */
50
+ const READ_ACTIONS = ALL_ACTIONS.filter((a) => a !== "scan")
51
+
52
+ /** 逐动作的一句话(`action` 参数描述的唯一措辞来源:描述从**本变体的动作集**生成——只读变体的字面
53
+ * 因此不含 `scan`,而两变体的措辞只有这一份,漂移由「同一张表同时派生动作与描述」挡住)。 */
54
+ const ACTION_CLAUSES = {
55
+ scan: "collects the edges into the ledger database (one explicit pass, no background index)",
56
+ forward: "lists the edges leaving a node",
57
+ reverse: "lists the edges pointing at a node",
58
+ chain: "walks outward from a node layer by layer, one layer per edge count",
59
+ }
60
+ /** `action` 参数描述(按本变体动作集生成;全量四个动作时与旧字面逐字相同)。 */
61
+ const actionDescOf = (actions) => `The question to ask: ${actions.map((a) => `\`${a}\` ${ACTION_CLAUSES[a]}`).join(" · ")}.`
62
+
63
+ /**
64
+ * 工具工厂:两个装配面同体,只有 `actions` ∥ `readonly` ∥ `docName` ∥ `unscanned` 四个参数不同。
65
+ * @param {string[]} actions — 本变体的 action 闭集(schema `enum` ∥ execute 护栏 ∥ 拒文取值集三处同取本参数)。
66
+ * @param {{readonly?: boolean, docName?: string, unscanned?: 'throw'|'readonly-empty'}} [opts] — `readonly` 缺省 false
67
+ * (全量);`docName` = 该变体的描述档名(`tool-docs/<docName>.md`);`unscanned` = 未建图策略(B5:
68
+ * 只读变体传 `readonly-empty`,全量保持抛既有指引)。
69
+ */
70
+ function makeDocGraphTool(actions, { readonly = false, docName = "doc_graph", unscanned = "throw" } = {}) {
71
+ const readOnlyVariant = readonly
72
+ return {
73
+ name: "doc_graph",
74
+ description: DESC(docName),
75
+ parameters: {
76
+ type: "object",
77
+ required: ["action"],
78
+ properties: {
79
+ action: { type: "string", enum: actions, description: actionDescOf(actions) },
80
+ target: {
81
+ type: "string",
82
+ description: "The project root this call is about (the directory carrying PROJECT-MANIFEST.json; a relative path resolves against the session anchor). Required for every action — there is no default: the session anchor is the base for a relative path, never a substitute for `target`.",
83
+ },
84
+ node: {
85
+ type: "string",
86
+ description: "The node to start from, written in the identity form: `req:F16` · `doc:<path>` · `doc:<path>#<section>` · `case:CLI 41-1` · `symbol:editTool` · `ledger:#2236`. Required for forward / reverse / chain — a missing node is refused by name, never answered with an empty result.",
87
+ },
88
+ depth: {
89
+ type: "number",
90
+ description: "How many edge steps to walk (`chain` only, required there): depth 1 = the immediate neighbours, depth 2 = their neighbours, and so on. Hops are counted in edges, not nodes. There is no default — a missing depth is refused by name.",
91
+ },
92
+ // `scope` 只服务 `scan` ⇒ 只存在全量 schema(B6:只读角色面不出现它执行不了的参数)
93
+ ...(readOnlyVariant ? {} : {
94
+ scope: {
95
+ type: "array",
96
+ items: { type: "string" },
97
+ description: "`scan` only, optional: re-scan just these documents (project-root-relative or absolute). Their edges are deleted and rebuilt; every other document's edges stay untouched. Omit it to scan the whole repository — the receipt's first field always says which of the two it did (`全仓` / `范围 K 档`).",
98
+ },
99
+ }),
100
+ kind: {
101
+ type: "string",
102
+ description: "`forward` / `reverse` / `chain` only, optional: a comma-separated subset of edge kinds to read — `cites`, `cites-req`, `mentions-case`, `case-file`, `cites-symbol`, `imports`. The edges are filtered before sorting and layering, so a narrowed run is a complete run, not a few lines pulled out of a big receipt. Omit it to read every kind (ledger projections included); the receipt's first line always prints the set in force. A value outside that closed set is refused by name — it is never treated as an empty set.",
103
+ },
104
+ },
105
+ additionalProperties: false,
106
+ },
107
+ readonly,
108
+ /** 只读性按 action(先例 = `ledger` 的 `isReadonlyAction`):三查询免审批,`scan` 走侧效门。
109
+ * 只读变体的动作集不含 `scan` ⇒ 它恒为真,与 `readonly: true` 同向,不需要第二份实现。 */
110
+ isReadonlyAction(args) { return args?.action !== "scan" },
111
+ async execute(args, ctx) {
112
+ const action = args?.action
113
+ // schema 的 enum 是建议性的(provider 不强制)——枚举外的值必须由入口拒,且只印本变体的取值集。
114
+ if (!actions.includes(action)) {
115
+ throw new Error(`doc_graph:action 非法(${JSON.stringify(action ?? null)})——取值 ∈ {${actions.join(", ")}}`)
116
+ }
117
+ const target = targetOf(args, ctx)
118
+ const boundary = ctx?.agent?.cwd ?? ctx?.cwd
119
+ const kindArg = args?.kind
120
+ if (kindArg !== undefined && typeof kindArg !== "string") {
121
+ throw new Error(`doc_graph:kind 须为逗号分隔的字符串(收到 ${typeof kindArg})——如 "cites,imports";闭集外拒并点名那一个值(由核校验)`)
122
+ }
123
+ const mod = await import("../doc-graph.mjs")
124
+ if (action === "scan") {
125
+ const scope = args?.scope
126
+ if (scope !== undefined && !Array.isArray(scope)) {
127
+ throw new Error(`doc_graph:scope 须为路径数组(收到 ${typeof scope})——只重扫几档就给 ["<path>"];给空数组等号于全仓`)
128
+ }
129
+ return mod.scanDocGraph({ target, scope, boundary })
130
+ }
131
+ return mod.queryDocGraph({ action, target, node: args?.node, depth: args?.depth, kind: kindArg, boundary, unscanned })
132
+ },
133
+ }
134
+ }
135
+
136
+ /** 全量变体(depth-0 主 agent 段):四动作,含 `scan`;未建图仍抛既有指引(逐字不变)。 */
137
+ export const docGraphTool = makeDocGraphTool(ALL_ACTIONS, { readonly: false })
138
+ /** 只读变体(全部 depth>0 角色段与 advisor 面):三动作、无 `scan`;同名不塌缩——两变体互斥装配。
139
+ * 未建图返可读空态(不要求父代跑 scan、不隐式写共享边表)。 */
140
+ export const docGraphReadTool = makeDocGraphTool(READ_ACTIONS, { readonly: true, docName: "doc_graph-read", unscanned: "readonly-empty" })
@@ -19,6 +19,7 @@ import { ENG_ON_REMINDER, ENG_OFF_REMINDER } from "../agent.mjs"
19
19
  import { clearPlanMode } from "./plan.mjs"
20
20
  import { purgeExpiredDesignTokens } from "../token-ttl.mjs"
21
21
  import { resolveEngineeringManifest } from "../manifest.mjs"
22
+ import { resolveWorkMode, setConfigWorkMode } from "../config.mjs"
22
23
  // 描述面 = `tool-docs/eng.md`(#15 描述外置统一——DESC 单一解析面,与内置工具族同径)
23
24
  import { DESC } from "../tools/shared.mjs"
24
25
 
@@ -26,7 +27,7 @@ import { DESC } from "../tools/shared.mjs"
26
27
  /**
27
28
  * 工程模式切换通知注入位(**缺省不覆盖** = no-op——CLI 语义(只进会话),零行为变;端装配层
28
29
  * 可覆盖为本端镜像写盘 / 面板提示)。核内零端名分支(契约 5——本档只认 `onToggle` 函数名)。
29
- * 契约:`onToggle(enabled, ctx) → string | null | undefined | Promise<同>`——非空字符串 =
30
+ * 契约:`onToggle(mode, ctx) → string | null | undefined | Promise<同>`——非空字符串 =
30
31
  * 追加到结果文案尾(如镜像写入碰撞提示);其余值 = 无提示。调用时机 = 状态翻转后(观察新态)。
31
32
  */
32
33
  let injectedMirror = null
@@ -37,8 +38,8 @@ export function configureEngMirror(impl) {
37
38
  export function resetEngMirror() { injectedMirror = null }
38
39
 
39
40
  /** 镜像通知串(缺省空串;仅非空字符串追加)。 */
40
- async function mirrorNotice(enabled, ctx) {
41
- const out = await injectedMirror?.onToggle(enabled, ctx)
41
+ async function mirrorNotice(mode, ctx) {
42
+ const out = await injectedMirror?.onToggle(mode, ctx)
42
43
  return typeof out === "string" && out.length > 0 ? ` ${out}` : ""
43
44
  }
44
45
 
@@ -56,7 +57,7 @@ export const engTool = {
56
57
  async execute(args, ctx) {
57
58
  ctx.agent.config.agent ??= {}
58
59
  if (args.action === "exit") {
59
- ctx.agent.config.agent.engineering = false
60
+ setConfigWorkMode(ctx.agent.config, "normal")
60
61
  // R16 (F-R16a): OFF 不清 token——有效 token 跨模式存活(设计评审过的产物不因
61
62
  // 开关重复烧)。过期清理跑在另外三处(恢复过滤 / 开模式 / spawn 门禁拒)。
62
63
  ctx.agent._advisorRound = 0 // reset convergence budget
@@ -65,13 +66,13 @@ export const engTool = {
65
66
  ctx.agent._lastEngState = false
66
67
  ctx.agent._pendingReminders = ctx.agent._pendingReminders ?? []
67
68
  ctx.agent._pendingReminders.push(ENG_OFF_REMINDER)
68
- return "Engineering mode exited. Standard discipline now applies. You may edit files directly." + await mirrorNotice(false, ctx)
69
+ return "Engineering mode exited. Standard discipline now applies. You may edit files directly." + await mirrorNotice(ctx.agent.config.agent.mode, ctx)
69
70
  }
70
71
  if (args.action === "enter") {
71
72
  // Idempotent enter (v2 2026-08-25): already in engineering mode → pure no-op
72
73
  // (cleanup only runs on a real off→on transition — T-R16c precondition: first
73
74
  // exit/OFF, then enter; an already-on enter must not touch tokens at all).
74
- if (ctx.agent.config.agent.engineering) {
75
+ if (resolveWorkMode(ctx.agent.config.agent) === "engineering") {
75
76
  return "Engineering mode already active. Existing design tokens stay valid."
76
77
  }
77
78
  // #41 先判后翻(MANIFEST.md §2.8 F2 / KD-M1-21):判据 = 入口决策树**单源**
@@ -85,7 +86,7 @@ export const engTool = {
85
86
  return `Error: cannot enter engineering mode — ${r.message} (mode unchanged)`
86
87
  }
87
88
  ctx.agent.manifest = r.ok ? r.manifest : null // 工作区放行 ⇒ 零附着(显式置 null——§2.8 F2 放行行)
88
- ctx.agent.config.agent.engineering = true
89
+ setConfigWorkMode(ctx.agent.config, "engineering")
89
90
  // FR31 ③ / KD10(翻转点①):工程模式 ⇒ planMode 恒 false——中途开模式时清残留
90
91
  //(planMode 位 + reminder 计数 + 未注入的 plan 提示语),半状态(工程纪律 × plan 只读)不产生。
91
92
  clearPlanMode(ctx.agent)
@@ -100,7 +101,7 @@ export const engTool = {
100
101
  if (cleared > 0) {
101
102
  msg += ` Cleared ${cleared} expired design token${cleared === 1 ? "" : "s"} — 清 ${cleared} 个过期 token,有效 token 保留(TTL 内不重评)。`
102
103
  }
103
- msg += await mirrorNotice(true, ctx)
104
+ msg += await mirrorNotice(ctx.agent.config.agent.mode, ctx)
104
105
  return msg
105
106
  }
106
107
  return "Invalid action: expected 'enter' or 'exit'"
@@ -152,7 +152,7 @@ export function launchEscalateAsync(parent, ctx, launch) {
152
152
  const { task, provider, tag, effortNote } = launch
153
153
  parent._asyncSubagents ??= new Map()
154
154
  parent._asyncQueue ??= []
155
- // Async id allocation (AGENT-LOOP-SUBAGENT.md §6.7.3 D-A1 precedent): reserve the relay
155
+ // Async id allocation (AGENT-LOOP-SUBAGENT.md §6.7.3 precedent): reserve the relay
156
156
  // counter at launch — the returned id stays stable while the entry sits queued.
157
157
  // The [model] token (TUI block creation) is DEFERRED to actual start so queued
158
158
  // flights don't paint an empty panel block (subagent-parity).
@@ -228,7 +228,7 @@ export function launchEscalateAsync(parent, ctx, launch) {
228
228
  signal: entry.controller.signal,
229
229
  // §2.5 #78 并入:escalate 子代理输出流式(VSC subagent-escalate-async 同款豁免)。
230
230
  streamOutput: true,
231
- // SUBAGENT-OBSERVE-SEND 缺口补配(TURN-CAP-CONTINUE.md §3.1 :85):send 注入队列
231
+ // SUBAGENT-OBSERVE-SEND 缺口补配(`docs/core/design/TURN-CAP-CONTINUE.md` §3.1「兑现后的消费路径」):send 注入队列
232
232
  // 回合边界消费(否则续段文本静默丢弃)。空队列 no-op。
233
233
  consumeInjected: (ag) => { drainInjectedQueue(entry, ag ?? child) },
234
234
  }
@@ -11,8 +11,8 @@
11
11
  * - `write` ⇒ **点改**:读现档 → 设节点 → 落盘(`writeManifest` 内先 `validateManifest`——
12
12
  * 编辑结果非法 ⇒ 拒 + 盘零变);**缺档 ⇒ 拒** + 引导 `init`(写不建档)。
13
13
  *
14
- * 写面白名单(判据单源 = `MANIFEST_SCHEMA`——钉死谓词):**13 个可写节点** = `keys` 中**非** `nestedKeys`
15
- * 父键者(`version` / `phase` / `codePaths` 整键)+ `nestedKeys` 子键(`docRoot.*` 六子键 / `index.*` 四子键);
14
+ * 写面白名单(判据单源 = `MANIFEST_SCHEMA`——钉死谓词):**16 个可写节点** = `keys` 中**非** `nestedKeys`
15
+ * 父键者(`version` / `phase` / `codePaths` 整键)+ `nestedKeys` 子键(`docRoot.*` 六子键 / `index.*` 七子键);
16
16
  * **两族整键写(传整个对象)⇒ 拒**;白名单外 ⇒ 拒(拼写保护——未知键写盘 = 静默死键,KD-M1-36 问题本体)。
17
17
  * `value` 解析 = 同款口径 `settings.mjs` 的 `parseValue`(先 `JSON.parse`,失败取字面串;`"null"` ⇒ `null`
18
18
  * ——`docRoot.*` 的「本面无」,KD-M1-37)。
@@ -22,7 +22,14 @@
22
22
  * 工作区塌缩 `null`(**回落发生在调用方 `writeRoot`,非本函数**)⇒ 写 / 建两动作**不得**直用。
23
23
  *
24
24
  * 写路径复用(零新写路径):落盘恒经 `writeManifest` / `initManifest`——`writer` 恒显式 `'main'`
25
- * (缺省 `'subagent'` = 写门 fail-closed 缺省,KD-M1-3 / AC-M1-5 零改)。
25
+ * (缺省 `'subagent'` = 写门 fail-closed 缺省,KD-M1-3 / AC-M1-5 零改)。**这里的「写门」= `writer` 身份闸**,
26
+ * 与下面那道不是同一道。
27
+ *
28
+ * **不在笔-账绑定写锁的入口集**(2026-11-10 整把出集批 · 决策 44):`read` ∥ `init` ∥ `write` 三动作一律不要
29
+ * 台账号、不要项目声明——本工具写的这份档正是写锁的输入(取根 ∥ 读 `index.writableRepos` 判跨仓),把写它
30
+ * 也放在门后就成环(档缺失建不出项目、档坏修不回来)。机制与理由单源 = `docs/core/design/BATCH-LEDGER-REVIEW-UNIFY.md`
31
+ * §2.3「`manifest` 不进写门」;该出口因此不在 `thincoder-core/agent/write-gate-ledger.mjs` 的入口集里,
32
+ * `ledger` ∥ `project` 两格也不在本工具的 `parameters.properties`(名字只为被读的地方存在)。
26
33
  *
27
34
  * 报告面随动(KD-M1-40):本工具**不写** `agent.manifest`(第二值源否——工具目标可为非锚项目)——
28
35
  * 写盘 = 盘面变化,情境行经既有 ③b mtime 门控于下回合采纳(`agent/setup-reminders.mjs`)。
@@ -37,9 +44,9 @@
37
44
  * (`readonly: false` = 动作级分类面,只读性归 `dispatch-gates` 的 `read` 判定)。
38
45
  */
39
46
  import { existsSync } from "node:fs"
40
- import { join, resolve } from "node:path"
47
+ import { isAbsolute, join, resolve } from "node:path"
41
48
  import { MANIFEST_REL, MANIFEST_SCHEMA, initManifest, projectRootView, projectView, readManifest, writeManifest } from "../manifest.mjs"
42
- import { DESC, LEDGER_PARAM_DESC_MANIFEST, PROJECT_PARAM_DESC } from "../tools/shared.mjs"
49
+ import { DESC } from "../tools/shared.mjs"
43
50
  import { clearDeclarationCache } from "../conventions.mjs" // #1367 面⑦:写档成功 ⇒ 缓存失效(fix 轮接线)
44
51
 
45
52
  /** 拒面统一前缀(设计 §2.10:`manifest <action>: refused — …`)——盘零变类拒绝一律经此抛错。 */
@@ -47,11 +54,23 @@ function refuse(action, reason) {
47
54
  return new Error(`manifest ${action}: refused — ${reason}`)
48
55
  }
49
56
 
50
- /** `target` 解析(先例 `eng.mjs` 的 `resolveEngineeringManifest` 缺省会话锚 ∥ `git.mjs` 的 `resolveBaseDir` 相对形归一):缺省 = 会话锚
51
- * (`ctx.agent.cwd ?? ctx.cwd`);显式相对形按会话锚归一(绝对形原样)。 */
52
- function resolveTarget(args, ctx) {
57
+ /** `target` 解析:`target` 必填;`base` 只作相对形基根。缺 ∥ 空串 ∥ `null` ⇒ 抛、报文点名 `target`,零判定
58
+ * (不拿锚替调用方选根)。`base` = `ctx.agent.cwd ?? ctx.cwd`(KD-9);绝对形原样。 */
59
+ function resolveTarget(action, args, ctx) {
53
60
  const base = ctx?.agent?.cwd ?? ctx?.cwd
54
- return args?.target ? resolve(base, String(args.target)) : resolve(base)
61
+ const given = args?.target
62
+ if (typeof given !== "string" || given.trim() === "") {
63
+ throw new Error(`manifest ${action}: target is required — pass the project root or directory you mean (an absolute path, or a path relative to the session anchor); there is no default.`)
64
+ }
65
+ // 锚只作**相对形**的基根(KD-9):锚缺位 + 相对形 ⇒ 拒、点名锚——不许落 `process.cwd()`
66
+ // (同 `thincoder-core/agent-tools/doc-check.mjs` 的同支,全批共用契约)。
67
+ if (!base) {
68
+ if (!isAbsolute(given)) {
69
+ throw new Error(`manifest ${action}: target is required as an absolute path — no session anchor is available (\`ctx.agent.cwd\` / \`ctx.cwd\` both empty), so a relative \`target\` has no base to resolve against.`)
70
+ }
71
+ return resolve(given)
72
+ }
73
+ return resolve(base, given)
55
74
  }
56
75
 
57
76
  /** 写面白名单谓词(**钉死**——设计 §2.10):点分路径恰两形——
@@ -131,14 +150,11 @@ export const manifestTool = {
131
150
  type: "object",
132
151
  properties: {
133
152
  action: { type: "string", enum: ["read", "init", "write"], description: "read — current manifest + validation state (five-state anchor, never throws); init — create the default manifest when missing (refused when one already exists); write — point-edit one node (key + value) of an existing manifest" },
134
- target: { type: "string", description: "Explicit target directory — defaults to the session anchor; relative paths resolve against it. A workspace target (several projects below it) is refused with the full project list — pass the project root you mean." },
153
+ target: { type: "string", description: "Required — pass the project root or directory you mean (relative paths resolve against the session anchor; a workspace target is reported with its project list)" },
135
154
  key: { type: "string", description: "(write) Dot path of the node to set — version / phase / codePaths, or a sub-key of docRoot / index (e.g. docRoot.design / index.publicRepos); whole-object writes of those two families are refused", },
136
155
  value: { type: "string", description: "(write) New value — parsed as JSON first (null / true / 5 / [\"a\"]), otherwise kept as a literal string; \"null\" is the explicit no-such-face for docRoot.<key>" },
137
- ledger: { type: "string", description: LEDGER_PARAM_DESC_MANIFEST },
138
- // 项目声明面(决策 40):`target` 缺位时才被读(定位参数优先);纯声明,不改查/建的目标目录。
139
- project: { type: "string", description: PROJECT_PARAM_DESC },
140
156
  },
141
- required: ["action"],
157
+ required: ["action", "target"],
142
158
  },
143
159
  readonly: false, // 动作级分类(dispatch-gates `isReadonlyAction`):read = 只读类;init / write 保持侧效门
144
160
  async execute(args, ctx) {
@@ -146,7 +162,7 @@ export const manifestTool = {
146
162
  if (!["read", "init", "write"].includes(action)) {
147
163
  throw new Error(`manifest: action must be one of read/init/write — got ${JSON.stringify(action)}`)
148
164
  }
149
- const target = resolveTarget(args, ctx)
165
+ const target = resolveTarget(action, args, ctx)
150
166
 
151
167
  if (action === "read") return readAction(target)
152
168
 
@@ -220,15 +236,15 @@ export const manifestReadTool = {
220
236
  type: "object",
221
237
  properties: {
222
238
  action: { type: "string", enum: ["read"], description: "read — current manifest + validation state (five-state anchor, never throws)" },
223
- target: { type: "string", description: "Explicit target directory — defaults to the session anchor; relative paths resolve against it. A workspace target (several projects below it) is reported with the full project list — pass the project root you mean." },
239
+ target: { type: "string", description: "Required — pass the project root or directory you mean (relative paths resolve against the session anchor; a workspace target is reported with its project list)" },
224
240
  },
225
- required: ["action"],
241
+ required: ["action", "target"],
226
242
  },
227
243
  readonly: true,
228
244
  async execute(args, ctx) {
229
245
  if (args?.action !== "read") {
230
246
  throw new Error(`manifest read: refused — this read-only variant exposes only action=read (got ${JSON.stringify(args?.action)})`)
231
247
  }
232
- return readAction(resolveTarget(args, ctx), { canInit: false })
248
+ return readAction(resolveTarget("read", args, ctx), { canInit: false })
233
249
  },
234
250
  }
@@ -19,9 +19,11 @@
19
19
  *
20
20
  * Returns a JSON array in chronological order. Every message without ts comes
21
21
  * back as ts:null and can never match a time window (legacy sessions). Content
22
- * is truncated to ~500 chars with an explicit marker — full text lives in the
23
- * session file. assistant tool_calls come back as [{name, arguments}] with the
24
- * stored argument string capped at 300 chars (matches the stored precision).
22
+ * is truncated to ~500 chars with an explicit marker that states what is actually
23
+ * retrievable: for `tool` results the session file stores only those first 500
24
+ * chars (re-run the tool for more), for `user` / `assistant` text the full text
25
+ * is in the session file. assistant tool_calls come back as [{name, arguments}]
26
+ * with the stored argument string capped at 300 chars (matches the stored precision).
25
27
  *
26
28
  * Cross-session (SESSION.md §6.13 D-R19a + §6.19 D-SE47 — 索引优先 + 主存回落):
27
29
  * path = a session file path (absolute, or relative to the project cwd) → when the derived
@@ -78,16 +80,21 @@ function messageText(m) {
78
80
  return ""
79
81
  }
80
82
 
81
- /** Truncate long content (~500 chars) with an explicit marker. The cut never splits a UTF-16
82
- * surrogate pair (emoji etc.) — a lone high surrogate in tool output would be an eyesore at
83
- * minimum; the send layer sanitizes it anyway, but clean output costs nothing
84
- * (thincoder-core/text-budget.mjs `safeSliceUTF16` same rule). */
85
- function truncateContent(text) {
83
+ /** Truncate long content (~500 chars) with an explicit marker whose wording is **true for the role**
84
+ * (`SESSION.md` §5 取回面标记条): on the human line a `tool` result is stored as the first 500 chars
85
+ * (`slimForDisplay`), so the session file holds no more than what already came back — “full text is in
86
+ * the session file” would be a promise nobody can keep, and a model that believes it stops re-running
87
+ * the tool. `user` / `assistant` bodies are never slimmed, so that promise still holds there.
88
+ * The cut never splits a UTF-16 surrogate pair (emoji etc.) — `text-budget.mjs` `safeSliceUTF16` same rule. */
89
+ function truncateContent(text, role) {
86
90
  const t = String(text ?? "")
87
91
  if (t.length <= CONTENT_CAP) return t
88
92
  let end = CONTENT_CAP
89
93
  if (t.charCodeAt(end - 1) >= 0xd800 && t.charCodeAt(end - 1) <= 0xdbff) end-- // high surrogate at the cut → step back
90
- return t.slice(0, end) + `\n… (truncated: ${t.length - end} chars — full text is in the session file)`
94
+ const where = role === "tool"
95
+ ? "the session file keeps only the first 500 chars of a tool result — re-run the tool if you need it"
96
+ : "full text is in the session file"
97
+ return t.slice(0, end) + `\n… (truncated: ${t.length - end} chars — ${where})`
91
98
  }
92
99
 
93
100
  /** Tool name across both stored shapes ({function:{name}} and flat {name}). */
@@ -124,7 +131,7 @@ function toEntry(m) {
124
131
  }
125
132
  if (m.name !== undefined) entry.name = m.name
126
133
  if (m.tool_call_id !== undefined) entry.tool_call_id = m.tool_call_id
127
- entry.content = truncateContent(messageText(m))
134
+ entry.content = truncateContent(messageText(m), m.role)
128
135
  if (Array.isArray(m.tool_calls) && m.tool_calls.length > 0) {
129
136
  const calls = toolCallEntries(m.tool_calls)
130
137
  if (calls.length > 0) entry.tool_calls = calls
@@ -259,7 +266,7 @@ function indexEntry(r) {
259
266
  const entry = { ts: typeof r.ts === "number" ? r.ts : null, role: r.role ?? null }
260
267
  if (r.name !== undefined && r.name !== null) entry.name = r.name
261
268
  if (r.tool_call_id !== undefined && r.tool_call_id !== null) entry.tool_call_id = r.tool_call_id
262
- entry.content = truncateContent(r.content ?? "")
269
+ entry.content = truncateContent(r.content ?? "", r.role)
263
270
  if (Array.isArray(r.tool_calls) && r.tool_calls.length > 0) entry.tool_calls = r.tool_calls
264
271
  return entry
265
272
  }
@@ -308,6 +315,100 @@ async function queryAllSessions(filters, current = null) {
308
315
  } finally { if (db) db.close() }
309
316
  }
310
317
 
318
+ // ─── 受限父历史(TOOLS.md §6.29 ④ · B8)─────────────────────────────────────────
319
+ /** 变体 `limit` 上限(设计档:必传且上限 50——读的是父会话的一个批窗口,不是整本历史)。 */
320
+ export const BATCH_HISTORY_LIMIT_MAX = 50
321
+
322
+ /** 批档比较键(win32 大小写不敏感——与 `agent-tools/subagent-scheduler.mjs` 的 fileKey 同律)。 */
323
+ const batchKeyOf = (p) => (process.platform === "win32" ? String(p).toLowerCase() : String(p))
324
+
325
+ /**
326
+ * 记录一批的父会话起点(`depth-0 根 agent` 上按规范化 batchDoc 存):批创建成功时记一次;
327
+ * 旧批没有起点时由首次绑定 spawn 记一次(`subagent-spawn.mjs` 的 `buildSpawnChild`)——
328
+ * **已记过的不动**(不回填一个虚构的历史范围)。
329
+ * @param {object} rootAgent — depth-0 根 agent(历史与窗口都属于它那一本账)
330
+ * @param {string} batchDoc — 批次档绝对路径
331
+ * @param {number} [ts] — 起点时刻(epoch ms;缺省 = 现在)
332
+ */
333
+ export function recordBatchHistoryStart(rootAgent, batchDoc, ts = Date.now()) {
334
+ if (!rootAgent || !batchDoc) return
335
+ const map = (rootAgent._batchHistoryStart ??= new Map())
336
+ const key = batchKeyOf(batchDoc)
337
+ if (!map.has(key)) map.set(key, ts)
338
+ }
339
+
340
+ /** 本批的父会话窗口:`[起点, 下一批起点)`;没有下一批 ⇒ 终点开放到查询时刻。
341
+ * 起点不在账上 ⇒ null(fail-closed:不拿一个猜出来的下界去读)。 */
342
+ function historyWindowOf(rootAgent, batchDoc) {
343
+ const map = rootAgent?._batchHistoryStart
344
+ const key = batchKeyOf(batchDoc)
345
+ const start = map instanceof Map ? map.get(key) : undefined
346
+ if (typeof start !== "number") return null
347
+ let end = null
348
+ for (const [k, v] of map) {
349
+ if (k === key || typeof v !== "number" || v <= start) continue
350
+ if (end === null || v < end) end = v
351
+ }
352
+ return { start, end }
353
+ }
354
+
355
+ /**
356
+ * 绑定父 agent 的受限 `read_history`(同名工具,只在 eng 子代理的 `childRunOpts.extraTools` 注入):
357
+ * 读的是**父会话**里本批起点之后、下一批起点之前的消息,限量 50,禁止 `path` / 跨会话
358
+ * (`ctx.agent` 固定为闭包里的父 agent ⇒ 读不到 child 自己,也不能反向写父状态)。
359
+ * 无时间戳消息按原工具规则不进入时间窗——所需无日期事实由任务书 `knownFacts` 携带(K6)。
360
+ * @param {object} parentAgent — depth-0 根 agent(父会话 + 窗口账本)
361
+ * @param {string} batchDoc — 本批批次档绝对路径(窗口键)
362
+ */
363
+ export function makeBatchHistoryTool(parentAgent, batchDoc) {
364
+ return {
365
+ name: "read_history",
366
+ description: DESC("read_history-batch"),
367
+ parameters: {
368
+ type: "object",
369
+ required: ["limit"],
370
+ properties: {
371
+ role: { type: "string", enum: ["user", "assistant", "tool"], description: "Only messages with this role." },
372
+ keyword: { type: "string", description: "Case-insensitive substring of the message text (multimodal matches on text parts)." },
373
+ tool: { type: "string", description: "Only messages for this tool: role=tool messages with name=tool, plus assistant messages that declared a call to it." },
374
+ since: { type: "integer", description: "Earliest ts to match, epoch ms, INCLUSIVE — this batch window's start applies too (the later of the two wins); messages without ts never match." },
375
+ until: { type: "integer", description: "Latest ts to match, epoch ms, INCLUSIVE — the next batch's start (or now) applies too (the earlier of the two wins)." },
376
+ limit: { type: "integer", description: "REQUIRED — how many messages to return (1–50). No default: the window is decided by the caller, never supplied for it." },
377
+ direction: { type: "string", enum: ["oldest", "newest"], description: "Take the limit window from the oldest or newest end of the matched set (default newest)." },
378
+ },
379
+ },
380
+ readonly: true,
381
+ execute(args, ctx) {
382
+ const a = args ?? {}
383
+ // `path` 不在本变体 schema 里;直接调进来的一笔同样拒(schema 是提示,不是门)
384
+ if (Object.hasOwn(a, "path")) {
385
+ throw new Error("read_history: `path` is not available here — this bounded face reads the parent session's window for THIS batch only (no other session, no other batch). Drop `path`. Nothing was read.")
386
+ }
387
+ if (a.limit === undefined || a.limit === null) {
388
+ throw new Error(`read_history: limit is required and has no default — pass how many messages you need (1–${BATCH_HISTORY_LIMIT_MAX}). Nothing was read.`)
389
+ }
390
+ const limit = Math.floor(Number(a.limit))
391
+ if (!Number.isFinite(limit) || limit < 1) {
392
+ throw new Error(`read_history: limit ${JSON.stringify(a.limit)} is not a positive integer — pass 1–${BATCH_HISTORY_LIMIT_MAX}. Nothing was read.`)
393
+ }
394
+ if (limit > BATCH_HISTORY_LIMIT_MAX) {
395
+ throw new Error(`read_history: limit ${limit} exceeds the cap of ${BATCH_HISTORY_LIMIT_MAX} for this bounded face — narrow it by keyword / since / until and ask again. Nothing was read.`)
396
+ }
397
+ const window = historyWindowOf(parentAgent, batchDoc)
398
+ if (window === null) {
399
+ throw new Error(`read_history: no history window is recorded for this batch record (${batchDoc}) — the window is recorded when the batch is created or when its first spawn binds it. Nothing was read; carry the fact you need in the task book instead.`)
400
+ }
401
+ const asNumber = (v) => (v === undefined || v === null ? null : Number(v))
402
+ const sinceGiven = asNumber(a.since)
403
+ const untilGiven = asNumber(a.until)
404
+ const since = sinceGiven === null || !Number.isFinite(sinceGiven) ? window.start : Math.max(sinceGiven, window.start)
405
+ const end = window.end ?? Date.now()
406
+ const until = untilGiven === null || !Number.isFinite(untilGiven) ? end : Math.min(untilGiven, end)
407
+ // ctx.agent 固定为父 agent:读到的是父会话,读不到 child 自己,也写不回父状态
408
+ return readHistoryTool.execute({ ...a, limit, since, until }, { ...ctx, agent: parentAgent })
409
+ },
410
+ }
411
+ }
311
412
  export const readHistoryTool = {
312
413
  name: "read_history",
313
414
  description: DESC("read_history"),
@@ -35,8 +35,12 @@ export function docSetKey(documents, cwd) {
35
35
 
36
36
  /** **写门面**评审根的 docRoot 键集(`agent/write-gate.mjs` 的 `resolveReviewTargetPaths` 消费)——
37
37
  * 设计评审**受理面不再消费**本键集(受理 = 项目内现存 `.md`,判据单源 = `ADVISOR-GUARDS.md` §12)。
38
- * 2026-10-04 自 `agent/write-gate.mjs` 迁入(键集本体零变;write-gate 同名再出口)。 */
39
- export const REVIEW_ROOT_KEYS = ["requirements", "specs", "design", "modules", "batches"]
38
+ * 2026-10-04 自 `agent/write-gate.mjs` 迁入(键集本体零变;write-gate 同名再出口)。
39
+ *
40
+ * **六层**(`docs/core/design/MANIFEST.md` §2.5「键集」条):末位 `standards` = 标准层(目录语义,
41
+ * 见同档 §2.12)。键集只在本处改——写面 `agent/write-face.mjs`、评审候选扫描、文档锚点图
42
+ * `doc-graph.mjs` 三处共用这一份,不各持字面(KD-M1-64)。 */
43
+ export const REVIEW_ROOT_KEYS = ["requirements", "specs", "design", "modules", "batches", "standards"]
40
44
 
41
45
  /**
42
46
  * 写门评审根解析单点(按用点形——2026-09-21 收口 · 台账 #828;2026-10-04 自 `agent/write-gate.mjs`
@@ -93,7 +97,7 @@ export function resolveReviewDocPaths(documents, cwd) {
93
97
  for (const doc of (documents ?? [])) {
94
98
  if (typeof doc !== "string" || !doc.trim()) continue
95
99
  const abs = /^[a-zA-Z]:[\\/]/.test(doc) || doc.startsWith("/") || doc.startsWith("\\\\")
96
- const r = resolvePathTarget(cwd, doc, { kind: "file", order: "root-first", crossRepo: "dangling", scanBases })
100
+ const r = resolvePathTarget(cwd, doc, { kind: "file", order: "root-first", scanBases })
97
101
  if (r.state === "ambiguous") { invalid.push({ doc, resolved: null, reason: "ambiguous-path", candidates: r.candidates }); continue }
98
102
  // 相对形 ∧ 锚无项目根 ⇒ 无基可挂(受理判据「必须在项目内」)——**与盘上有没有那档无关**:
99
103
  // 同一锚态同一个词(KD-8),否则拒因词成了磁盘状态的函数。
@@ -103,6 +107,9 @@ export function resolveReviewDocPaths(documents, cwd) {
103
107
  invalid.push({ doc, resolved: r.tried?.[0] ?? null, reason: "not-doc-file", sameName: r.sameName })
104
108
  continue
105
109
  }
110
+ // 其余非 `resolved` 态(`unverified` ∥ `outOfDomain`):本面不传 `declaredRepos` / `domainRoots`,两者今天都不会出现,
111
+ // 但消费面必须**总覆盖**——拿不到 `abs` 的态一律按「解析无果」拒(fail-closed),不让 undefined 流进 `isInside`。
112
+ if (r.state !== "resolved") { invalid.push({ doc, resolved: null, reason: "dangling-path" }); continue }
106
113
  const p = r.abs
107
114
  if (!abs && !isInside(p, view.root)) { invalid.push({ doc, resolved: p, reason: "outside-project" }); continue }
108
115
  if (abs && !owningProject(p, cwd)) { invalid.push({ doc, resolved: p, reason: "outside-project" }); continue }
@@ -12,7 +12,7 @@
12
12
  * 走显式形状表(_NULL_LEAF_SHAPES 相等面 / _SIBLING_SHAPES 存在性面——按各自真实消费形态
13
13
  * 校验,完备性机械锁 + 一次性警告;SETTINGS-TOOL.md §8);set 侧效走审批门(dispatch 动作级分类)。
14
14
  */
15
- import { DEFAULTS, configPath, promoteAgentViews, writeConfigAtomic } from "../config.mjs"
15
+ import { DEFAULTS, WORK_MODES, configPath, promoteAgentViews, resolveWorkMode, setConfigWorkMode, writeConfigAtomic } from "../config.mjs"
16
16
  import { DESC } from "../tools/shared.mjs" // #15 描述外置:文本单点 = tool-docs/settings.md
17
17
 
18
18
  /** 敏感键段判定(完整点分路径的段级匹配——两句取或:词表段 ∨ 开口键族段;SETTINGS-TOOL.md §2.4)。
@@ -164,6 +164,20 @@ function _checkAdvisorTimeout(value) {
164
164
  * ③ 未知键 → 原样通过(全量域)。
165
165
  */
166
166
  function _checkKnownKeyValue(path, value) {
167
+ if (path === "agent.engineering") {
168
+ throw new Error("settings set: agent.engineering is derived from agent.mode and cannot be written directly")
169
+ }
170
+ if (path === "agent.mode" && !WORK_MODES.includes(value)) {
171
+ throw new Error(`settings set: agent.mode expects one of ${WORK_MODES.join(", ")} — got ${_shownValue(path, value)}`)
172
+ }
173
+ if (path === "agent" && value !== null && typeof value === "object" && !Array.isArray(value)) {
174
+ if (Object.hasOwn(value, "engineering")) {
175
+ throw new Error("settings set: agent.engineering is derived from agent.mode and cannot be written through an agent object")
176
+ }
177
+ if (Object.hasOwn(value, "mode") && !WORK_MODES.includes(value.mode)) {
178
+ throw new Error(`settings set: agent.mode expects one of ${WORK_MODES.join(", ")} — got ${_shownValue("agent.mode", value.mode)}`)
179
+ }
180
+ }
167
181
  if (path === "agent.advisor.timeoutMs" || path === "advisor.timeoutMs") return _checkAdvisorTimeout(value)
168
182
  if ((path === "agent.advisor" || path === "advisor") && value !== null && typeof value === "object" && !Array.isArray(value) && "timeoutMs" in value) {
169
183
  _checkAdvisorTimeout(value.timeoutMs) // 整段赋值腿(两个段名):对象内该键同规则校验(§2.6)
@@ -307,6 +321,7 @@ export function settingsTool(opts = {}) {
307
321
  // set
308
322
  if (!args.key || args.value === undefined) throw new Error("settings set: key and value are required")
309
323
  const value = parseValue(args.value)
324
+ const sessionMode = resolveWorkMode(config.agent)
310
325
  // 已知键校验(形状表两表都查 + 派生类型表——SETTINGS-TOOL.md §8.3;未知键 JSON 原样)
311
326
  _checkKnownKeyValue(String(args.key), value)
312
327
  // 写盘(D-F5b:磁盘真相最小化——默认不固化;冲突/畸形抛错,内存不热应用(零虚假成功))+
@@ -340,11 +355,17 @@ export function settingsTool(opts = {}) {
340
355
  setKeyPath(config, promotedPath, value) // 子键 set:键级同步(与 null 腿同一种「同一子键」口径)
341
356
  }
342
357
  }
358
+ // agent.mode persisted here is the new-session default. Keep the existing session's sole
359
+ // mode and its derived boolean unchanged; session commands and host controls switch slots.
360
+ const modeDefaultWrite = args.key === "agent.mode" || args.key === "agent"
361
+ if (modeDefaultWrite) setConfigWorkMode(config, sessionMode)
343
362
  const sensitive = isSensitiveKey(String(args.key))
344
363
  const shown = sensitive ? MASKED : value
345
364
  const suffix = value === null
346
365
  ? " — key removed(键已删除——回退默认)"
347
- : sensitive ? " — stored(值不回显)" : " — persisted + hot-applied(运行中已生效)"
366
+ : sensitive ? " — stored(值不回显)"
367
+ : modeDefaultWrite ? " — persisted as the new-session default(当前会话不变)"
368
+ : " — persisted + hot-applied(运行中已生效)"
348
369
  return `settings set: ${args.key} = ${shown} (${_kindOf(value)})${suffix}`
349
370
  },
350
371
  }