@thincoder/core 0.10.13 → 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 (366) hide show
  1. package/CHANGELOG.md +74 -1
  2. package/advisor/convergence.mjs +34 -3
  3. package/advisor/loop.mjs +42 -10
  4. package/advisor/messages.mjs +46 -27
  5. package/advisor/notice.mjs +1 -1
  6. package/advisor/project-context.mjs +253 -14
  7. package/advisor/run.mjs +7 -4
  8. package/advisor.mjs +29 -43
  9. package/agent/batch-attribution.mjs +87 -0
  10. package/agent/batch-changed-surface.mjs +129 -0
  11. package/agent/completion.mjs +57 -4
  12. package/agent/digest-account.mjs +73 -46
  13. package/agent/dispatch-gates.mjs +6 -0
  14. package/agent/dispatch-run.mjs +1 -1
  15. package/agent/dispatch.mjs +35 -22
  16. package/agent/family-tools.mjs +36 -17
  17. package/agent/helpers.mjs +123 -95
  18. package/agent/offload.mjs +84 -0
  19. package/agent/post-turn.mjs +24 -10
  20. package/agent/record-results.mjs +19 -7
  21. package/agent/run-stages.mjs +127 -61
  22. package/agent/run-start.mjs +45 -8
  23. package/agent/setup-reminders.mjs +9 -2
  24. package/agent/setup.mjs +27 -22
  25. package/agent/spawn-child.mjs +38 -1
  26. package/agent/suspension.mjs +1 -1
  27. package/agent/timers.mjs +5 -3
  28. package/agent/turn-loop.mjs +60 -6
  29. package/agent/turn-projection.mjs +386 -0
  30. package/agent/turn-task-state.mjs +274 -0
  31. package/agent/turn-tool-process.mjs +168 -0
  32. package/agent/write-face.mjs +99 -0
  33. package/agent/write-gate-ledger.mjs +569 -0
  34. package/agent/write-gate.mjs +39 -13
  35. package/agent-tools/advisor-async.mjs +29 -169
  36. package/agent-tools/advisor-launch.mjs +178 -0
  37. package/agent-tools/advisor-settle.mjs +28 -1
  38. package/agent-tools/advisor.mjs +136 -31
  39. package/agent-tools/async-settle.mjs +2 -2
  40. package/agent-tools/audit-block.mjs +6 -6
  41. package/agent-tools/bash-async.mjs +8 -2
  42. package/agent-tools/batch-closeout.mjs +444 -0
  43. package/agent-tools/batch-gate.mjs +152 -138
  44. package/agent-tools/batch-ledger-bind.mjs +392 -0
  45. package/agent-tools/batch-ledger-link.mjs +73 -0
  46. package/agent-tools/batch-ledger-view.mjs +109 -0
  47. package/agent-tools/batch-lifecycle.mjs +245 -376
  48. package/agent-tools/batch-paths.mjs +73 -47
  49. package/agent-tools/batch-read.mjs +1 -1
  50. package/agent-tools/batch-record-write.mjs +417 -0
  51. package/agent-tools/batch-regions.mjs +215 -0
  52. package/agent-tools/batch-reopen.mjs +154 -0
  53. package/agent-tools/batch-segment-vocab.mjs +379 -0
  54. package/agent-tools/batch-skeleton.mjs +344 -196
  55. package/agent-tools/batch-supersede.mjs +232 -0
  56. package/agent-tools/batch-tier-gate.mjs +297 -0
  57. package/agent-tools/batch.mjs +189 -253
  58. package/agent-tools/consult.mjs +7 -4
  59. package/agent-tools/context.mjs +47 -17
  60. package/agent-tools/design-review-record.mjs +225 -0
  61. package/agent-tools/design-slots.mjs +24 -24
  62. package/agent-tools/design-token.mjs +318 -39
  63. package/agent-tools/doc-check.mjs +55 -29
  64. package/agent-tools/doc-graph.mjs +140 -0
  65. package/agent-tools/eng.mjs +10 -9
  66. package/agent-tools/escalate-async.mjs +5 -5
  67. package/agent-tools/manifest.mjs +34 -15
  68. package/agent-tools/read-history.mjs +115 -14
  69. package/agent-tools/review-facts.mjs +40 -15
  70. package/agent-tools/settings.mjs +23 -2
  71. package/agent-tools/spawn-gates.mjs +19 -22
  72. package/agent-tools/ssh-session.mjs +120 -111
  73. package/agent-tools/ssh-text.mjs +155 -0
  74. package/agent-tools/ssh-transfer.mjs +210 -0
  75. package/agent-tools/ssh-transport.mjs +183 -81
  76. package/agent-tools/subagent-actions-query.mjs +11 -7
  77. package/agent-tools/subagent-actions.mjs +1 -1
  78. package/agent-tools/subagent-async.mjs +11 -11
  79. package/agent-tools/subagent-brief.mjs +76 -0
  80. package/agent-tools/subagent-design-token.mjs +168 -0
  81. package/agent-tools/subagent-run.mjs +1 -1
  82. package/agent-tools/subagent-scheduler.mjs +45 -11
  83. package/agent-tools/subagent-spawn.mjs +143 -104
  84. package/agent-tools/subagent.mjs +26 -23
  85. package/agent-tools/taskbook-block.mjs +94 -0
  86. package/agent-tools/timer.mjs +12 -8
  87. package/agent-tools/verify.mjs +13 -4
  88. package/agent-tools.mjs +7 -3
  89. package/agent.mjs +20 -1
  90. package/attachments.mjs +3 -3
  91. package/browser/actions.mjs +9 -3
  92. package/browser/cdp.mjs +45 -17
  93. package/browser/launch.mjs +25 -43
  94. package/browser/pool.mjs +299 -0
  95. package/browser/queue.mjs +2 -0
  96. package/browser/session-state.mjs +450 -0
  97. package/browser/session.mjs +127 -151
  98. package/browser/snapshot.mjs +89 -0
  99. package/client-identity.mjs +22 -6
  100. package/config-defaults.mjs +2 -1
  101. package/config-migrate.mjs +40 -0
  102. package/config-normalize.mjs +28 -2
  103. package/config-presets.mjs +5 -3
  104. package/config-reload.mjs +59 -0
  105. package/config.mjs +62 -98
  106. package/context-degrade.mjs +38 -10
  107. package/context-echo.mjs +11 -0
  108. package/context.mjs +165 -68
  109. package/conventions.mjs +11 -9
  110. package/declaration.mjs +33 -7
  111. package/declared-repos.mjs +94 -0
  112. package/doc-check/doc-names.mjs +73 -0
  113. package/doc-check/doc-tokens.mjs +110 -0
  114. package/doc-check/existence.mjs +160 -0
  115. package/doc-check/index.mjs +312 -163
  116. package/doc-check/line-refs.mjs +38 -0
  117. package/doc-check/paragraph.mjs +220 -91
  118. package/doc-graph/anchors.mjs +474 -0
  119. package/doc-graph/doc-batch-face.mjs +59 -0
  120. package/doc-graph/doc-suffix.mjs +27 -0
  121. package/doc-graph/graph-tokens.mjs +160 -0
  122. package/doc-graph.mjs +778 -0
  123. package/explore-distill.mjs +12 -6
  124. package/i18n.mjs +2 -2
  125. package/index-discover.mjs +4 -1
  126. package/instance-inbox-watch.mjs +272 -0
  127. package/instance-inbox.mjs +218 -0
  128. package/instance-registry.mjs +179 -0
  129. package/knowledge/README.md +3 -0
  130. package/knowledge/prompt-resources.md +6 -0
  131. package/ledger-close-proof.mjs +95 -62
  132. package/ledger-close.mjs +188 -0
  133. package/ledger-cmd.mjs +76 -244
  134. package/ledger-consistency.mjs +113 -0
  135. package/ledger-db.mjs +70 -37
  136. package/ledger-executors.mjs +1 -1
  137. package/ledger-migrate.mjs +4 -4
  138. package/ledger-read.mjs +10 -8
  139. package/ledger-surface.mjs +1 -1
  140. package/ledger-tools.mjs +83 -24
  141. package/ledger-variant-notice.mjs +1 -1
  142. package/ledger-write-ops.mjs +462 -0
  143. package/ledger.mjs +2 -2
  144. package/manifest-discovery.mjs +5 -3
  145. package/manifest-schema.mjs +28 -2
  146. package/memory/memory-tool.mjs +5 -2
  147. package/memory/schema.mjs +6 -27
  148. package/package.json +3 -1
  149. package/path-resolve.mjs +498 -0
  150. package/permission.mjs +4 -0
  151. package/prompt-files.mjs +91 -1
  152. package/prompt-overlays.mjs +14 -6
  153. package/prompts/advisor-design.md +66 -22
  154. package/prompts/advisor-round1.md +37 -3
  155. package/prompts/advisor-round2.md +44 -10
  156. package/prompts/advisor-round3.md +43 -9
  157. package/prompts/common.md +15 -375
  158. package/prompts/consult-base.md +6 -1
  159. package/prompts/discipline-engineering.md +251 -95
  160. package/prompts/discipline-normal.md +4 -250
  161. package/prompts/knowledge/business-gates.md +22 -0
  162. package/prompts/knowledge/decision-quality.md +23 -0
  163. package/prompts/knowledge/doc-lookup.md +35 -0
  164. package/prompts/knowledge/document-writing.md +51 -0
  165. package/prompts/knowledge/documentation-evaluation.md +56 -0
  166. package/prompts/knowledge/evidence-discipline.md +57 -0
  167. package/prompts/knowledge/normal-coding-workflow.md +104 -0
  168. package/prompts/knowledge/normal-delivery-collaboration.md +108 -0
  169. package/prompts/knowledge/normal-work-management.md +57 -0
  170. package/prompts/knowledge/product-security.md +23 -0
  171. package/prompts/knowledge/project-records.md +62 -0
  172. package/prompts/knowledge/tool-advisor.md +29 -0
  173. package/prompts/knowledge/tool-apply-patch.md +18 -0
  174. package/prompts/knowledge/tool-bash.md +39 -0
  175. package/prompts/knowledge/tool-batch-eng-coder.md +12 -0
  176. package/prompts/knowledge/tool-batch-eng-designer.md +12 -0
  177. package/prompts/knowledge/tool-batch-review.md +12 -0
  178. package/prompts/knowledge/tool-batch.md +80 -0
  179. package/prompts/knowledge/tool-browser.md +57 -0
  180. package/prompts/knowledge/tool-code-search.md +4 -0
  181. package/prompts/knowledge/tool-consult-start.md +12 -0
  182. package/prompts/knowledge/tool-consult-stop.md +6 -0
  183. package/prompts/knowledge/tool-context.md +6 -0
  184. package/prompts/knowledge/tool-delete.md +17 -0
  185. package/prompts/knowledge/tool-doc-check.md +70 -0
  186. package/prompts/knowledge/tool-doc-graph-read.md +20 -0
  187. package/prompts/knowledge/tool-doc-graph.md +49 -0
  188. package/prompts/knowledge/tool-doc-search.md +6 -0
  189. package/prompts/knowledge/tool-edit.md +38 -0
  190. package/prompts/knowledge/tool-eng.md +2 -0
  191. package/prompts/knowledge/tool-execute.md +16 -0
  192. package/prompts/knowledge/tool-fetch.md +12 -0
  193. package/prompts/knowledge/tool-file-ops.md +16 -0
  194. package/prompts/knowledge/tool-get-current-time.md +7 -0
  195. package/prompts/knowledge/tool-git-read.md +19 -0
  196. package/prompts/knowledge/tool-git.md +29 -0
  197. package/prompts/knowledge/tool-glob.md +15 -0
  198. package/prompts/knowledge/tool-goal.md +8 -0
  199. package/prompts/knowledge/tool-grep.md +18 -0
  200. package/prompts/knowledge/tool-hashline-edit.md +14 -0
  201. package/prompts/knowledge/tool-insert-after.md +15 -0
  202. package/prompts/knowledge/tool-instance-list.md +6 -0
  203. package/prompts/knowledge/tool-instance-send.md +10 -0
  204. package/prompts/knowledge/tool-knowledge.md +18 -0
  205. package/prompts/knowledge/tool-ledger-read.md +35 -0
  206. package/prompts/knowledge/tool-ledger.md +42 -0
  207. package/prompts/knowledge/tool-lint.md +16 -0
  208. package/prompts/knowledge/tool-ls.md +13 -0
  209. package/prompts/knowledge/tool-lsp.md +11 -0
  210. package/prompts/knowledge/tool-main-history.md +2 -0
  211. package/prompts/knowledge/tool-manifest-read.md +14 -0
  212. package/prompts/knowledge/tool-manifest.md +31 -0
  213. package/prompts/knowledge/tool-memory-read.md +20 -0
  214. package/prompts/knowledge/tool-memory.md +15 -0
  215. package/prompts/knowledge/tool-notify-parent.md +12 -0
  216. package/prompts/knowledge/tool-operations.md +114 -0
  217. package/prompts/knowledge/tool-peer-instances.md +2 -0
  218. package/prompts/knowledge/tool-plan.md +6 -0
  219. package/prompts/knowledge/tool-process-read.md +13 -0
  220. package/prompts/knowledge/tool-process.md +15 -0
  221. package/prompts/knowledge/tool-question.md +16 -0
  222. package/prompts/knowledge/tool-read-history-batch.md +22 -0
  223. package/prompts/knowledge/tool-read-history.md +36 -0
  224. package/prompts/knowledge/tool-read-image.md +11 -0
  225. package/prompts/knowledge/tool-read.md +21 -0
  226. package/prompts/knowledge/tool-recent-changes.md +6 -0
  227. package/prompts/knowledge/tool-repo-outline.md +4 -0
  228. package/prompts/knowledge/tool-settings-read.md +12 -0
  229. package/prompts/knowledge/tool-settings.md +18 -0
  230. package/prompts/knowledge/tool-skill.md +6 -0
  231. package/prompts/knowledge/tool-ssh.md +52 -0
  232. package/prompts/knowledge/tool-subagent.md +59 -0
  233. package/prompts/knowledge/tool-task.md +12 -0
  234. package/prompts/knowledge/tool-team-ledger-read.md +11 -0
  235. package/prompts/knowledge/tool-team-ledger.md +11 -0
  236. package/prompts/knowledge/tool-timer.md +23 -0
  237. package/prompts/knowledge/tool-tree.md +14 -0
  238. package/prompts/knowledge/tool-verify.md +19 -0
  239. package/prompts/knowledge/tool-wait-for.md +25 -0
  240. package/prompts/knowledge/tool-websearch.md +19 -0
  241. package/prompts/knowledge/tool-write.md +9 -0
  242. package/prompts/knowledge/upstream-protocol.md +43 -0
  243. package/prompts/persona-eng-coder.md +29 -3
  244. package/prompts/persona-eng-designer.md +131 -159
  245. package/prompts/persona-engineering.md +202 -131
  246. package/prompts/persona-explore.md +1 -1
  247. package/prompts/persona-plan.md +6 -1
  248. package/prompts/persona-tester.md +55 -0
  249. package/prompts/subagent-base.md +2 -0
  250. package/provider/anthropic.mjs +6 -4
  251. package/provider/core.mjs +5 -4
  252. package/provider/errors.mjs +29 -4
  253. package/provider/google.mjs +39 -12
  254. package/provider/rate.mjs +11 -3
  255. package/provider/responses.mjs +3 -1
  256. package/provider/sse.mjs +15 -4
  257. package/provider-flows.mjs +2 -2
  258. package/session-identity.mjs +21 -0
  259. package/session-index-build.mjs +1 -1
  260. package/session-index-pass.mjs +1 -1
  261. package/session-index-query.mjs +1 -1
  262. package/session-index.mjs +1 -1
  263. package/session-lifecycle.mjs +79 -19
  264. package/session-slot-write.mjs +37 -5
  265. package/session-slots.mjs +9 -14
  266. package/session.mjs +29 -8
  267. package/skip-dirs.mjs +48 -0
  268. package/team-ledger.mjs +17 -13
  269. package/text-budget.mjs +4 -0
  270. package/token-ttl.mjs +73 -4
  271. package/token-window.mjs +244 -34
  272. package/tool-docs/advisor.md +2 -27
  273. package/tool-docs/apply_patch.md +1 -13
  274. package/tool-docs/bash.md +2 -37
  275. package/tool-docs/batch-eng-coder.md +3 -0
  276. package/tool-docs/batch-eng-designer.md +3 -0
  277. package/tool-docs/batch-review.md +3 -0
  278. package/tool-docs/batch.md +3 -1
  279. package/tool-docs/browser.md +2 -47
  280. package/tool-docs/code_search.md +3 -1
  281. package/tool-docs/consult_start.md +2 -4
  282. package/tool-docs/consult_stop.md +2 -2
  283. package/tool-docs/context.md +1 -5
  284. package/tool-docs/delete.md +2 -14
  285. package/tool-docs/doc_check.md +2 -72
  286. package/tool-docs/doc_graph-read.md +3 -0
  287. package/tool-docs/doc_graph.md +3 -0
  288. package/tool-docs/doc_search.md +3 -1
  289. package/tool-docs/edit.md +2 -18
  290. package/tool-docs/eng.md +3 -1
  291. package/tool-docs/execute.md +2 -12
  292. package/tool-docs/fetch.md +2 -12
  293. package/tool-docs/file_ops.md +2 -16
  294. package/tool-docs/get_current_time.md +1 -6
  295. package/tool-docs/git-read.md +3 -0
  296. package/tool-docs/git.md +2 -27
  297. package/tool-docs/glob.md +2 -10
  298. package/tool-docs/goal.md +2 -5
  299. package/tool-docs/grep.md +2 -18
  300. package/tool-docs/hashline_edit.md +2 -13
  301. package/tool-docs/insert_after.md +2 -14
  302. package/tool-docs/instance_list.md +3 -0
  303. package/tool-docs/instance_send.md +3 -0
  304. package/tool-docs/knowledge.md +3 -0
  305. package/tool-docs/ledger-read.md +3 -0
  306. package/tool-docs/ledger.md +3 -8
  307. package/tool-docs/lint.md +2 -9
  308. package/tool-docs/ls.md +2 -11
  309. package/tool-docs/lsp.md +2 -9
  310. package/tool-docs/main_history.md +3 -1
  311. package/tool-docs/manifest-read.md +2 -7
  312. package/tool-docs/manifest.md +2 -28
  313. package/tool-docs/memory-read.md +3 -0
  314. package/tool-docs/memory.md +3 -11
  315. package/tool-docs/notify_parent.md +2 -13
  316. package/tool-docs/peer_instances.md +3 -1
  317. package/tool-docs/plan.md +2 -4
  318. package/tool-docs/process-read.md +3 -0
  319. package/tool-docs/process.md +2 -13
  320. package/tool-docs/question.md +3 -17
  321. package/tool-docs/read.md +2 -19
  322. package/tool-docs/read_history-batch.md +3 -0
  323. package/tool-docs/read_history.md +2 -6
  324. package/tool-docs/read_image.md +2 -7
  325. package/tool-docs/recent_changes.md +3 -1
  326. package/tool-docs/repo_outline.md +3 -1
  327. package/tool-docs/settings-read.md +3 -0
  328. package/tool-docs/settings.md +2 -5
  329. package/tool-docs/skill.md +3 -5
  330. package/tool-docs/ssh.md +2 -50
  331. package/tool-docs/subagent.md +2 -63
  332. package/tool-docs/task.md +2 -6
  333. package/tool-docs/team_ledger-read.md +3 -0
  334. package/tool-docs/team_ledger.md +3 -9
  335. package/tool-docs/timer.md +3 -13
  336. package/tool-docs/tree.md +2 -13
  337. package/tool-docs/verify.md +3 -1
  338. package/tool-docs/wait_for.md +2 -32
  339. package/tool-docs/websearch.md +2 -17
  340. package/tool-docs/write.md +2 -10
  341. package/tools/bash.mjs +12 -2
  342. package/tools/browser.mjs +52 -7
  343. package/tools/doc-write-gate.mjs +73 -0
  344. package/tools/edit-batch.mjs +176 -91
  345. package/tools/edit-diff.mjs +129 -45
  346. package/tools/edit-receipt.mjs +39 -0
  347. package/tools/execute.mjs +11 -5
  348. package/tools/file.mjs +32 -34
  349. package/tools/git.mjs +43 -2
  350. package/tools/index.mjs +6 -0
  351. package/tools/knowledge.mjs +143 -0
  352. package/tools/linter.mjs +3 -3
  353. package/tools/ops.mjs +4 -1
  354. package/tools/patch.mjs +127 -38
  355. package/tools/process-doc-mark.mjs +139 -0
  356. package/tools/search.mjs +15 -6
  357. package/tools/shared.mjs +31 -7
  358. package/tools/ssh.mjs +48 -7
  359. package/tools/tree.mjs +4 -1
  360. package/tools/write-gate-params.mjs +31 -0
  361. package/tools/write-path.mjs +79 -6
  362. package/traces/trace-store.mjs +4 -3
  363. package/window-policy.mjs +203 -0
  364. package/agent/light-round.mjs +0 -63
  365. package/agent/unbooked-pen.mjs +0 -62
  366. package/doc-check/anchors.mjs +0 -135
@@ -1,34 +1,50 @@
1
1
  /**
2
- * ssh-transport.mjs — SSH 传输面单点(askpass 链 ∥ 子进程 ∥ 沉降 ∥ 遮蔽 ∥ 输出帽)。
2
+ * ssh-transport.mjs — SSH 传输面单点(askpass 链 ∥ 子进程 ∥ 沉降 ∥ 输出帽)。
3
3
  * 设计 = `docs/core/design/TOOLS.md` §6.22(D-TO17/D-TO18 · 台账 #1436)。
4
4
  *
5
- * 拆档由 = 机制档触 500 顾问线(§6.22 落点表「触 500 顾问线 ⇒ 实施轮先审拆分」)——本档收**运行面**
5
+ * 拆档由 = 设计轮判定机制档改前读数过 500(`docs/core/design/DOC-GRAPH.md` §3「行数档位口径」)——本档收**运行面**
6
6
  * (与会话语义无关的传输原语),`ssh-session.mjs` 收**会话面**(池 / 生命周期 / 动作)。条目形
7
7
  * (entry)由 `ssh-session.mjs` 定义并持有;本档只经其字段工作(`buf` / `mask` / `_waiters` /
8
8
  * `promptRe` / `state` / `child` / `logStream` / `_notify` / `lastDataAt` / `bytes`)。
9
9
  *
10
+ * 2026-11-05 拆档族再切一刀:**可见文本面**(剥离 ∥ 归一 ∥ 遮蔽 ∥ 收场注记)搬进同目录叶档
11
+ * `ssh-text.mjs`——本档只留进程、计时、四门与输出面。
12
+ *
10
13
  * - askpass 链:包装档(Win `.cmd` ∥ POSIX `.sh` 0700)→ `tools/ssh-askpass.mjs` → stdout;秘密只经
11
14
  * ssh 子进程环境 `TC_SSH_SECRET`(零入参 / 零落盘 / 零回显;环境经 `nodeChildEnv` 单点补 Electron 旗标)。
12
- * - 沉降:静默窗 800 ms ∥ 会话提示符正则命中 ⇒ 就绪;硬超时 10 s ⇒ 部分输出 + 可读句(不静默挂起)。
13
- * - 遮蔽:写入的秘密对**捕获面与日志面**做字面移除(跨 chunk 切分:保留 `len-1` 尾缓冲)。
15
+ * - 终端噪声:有状态剥离(CSI ∥ OSC ∥ 单字符控制三类 + CRLF 归一;状态跨 chunk 携带)——落点 = 传输入口,
16
+ * **先剥离后遮蔽**;日志面 = 模型面同源(D-TO23)。剥离器与遮蔽器本体住 `ssh-text.mjs`,本档 import 消费。
17
+ * - 就绪判据:四门(待答标记 ∥ 提示符 ∥ 仍在吐 ∥ 硬超时 60 s);静默窗只作去抖(D-TO21)。
18
+ * - 遮蔽:写入的秘密对**捕获面与日志面**做字面移除(比较面 = 同一归一 + 按不可见处切段 ≥ 4)——
19
+ * 实现住 `ssh-text.mjs` 的 `createMask`。
14
20
  * - 失败分类族(auth ∥ unreachable ∥ hostkey)照服务端 `src/sandbox/ssh.mjs` 同源判据。
15
- * 模块图:→ config.mjs(configDir 缺省)· tools/shared.mjs(解码 ∥ 清洗)· tools/node-child.mjs
16
- * (nodeChildEnv)——叶子向、无环(本档不 import `ssh-session.mjs`)。
21
+ * 模块图:→ config.mjs(configDir 缺省)· tools/shared.mjs(解码)· text-budget.mjs(截断本体)·
22
+ * tools/node-child.mjs(nodeChildEnv)· expand-home.mjs(`~` 展开单源——`identityFile` 用)·
23
+ * ssh-text.mjs(可见文本面)——叶子向、无环(本档不 import `ssh-session.mjs`)。
17
24
  */
18
25
  import { chmodSync, mkdirSync, unlinkSync, writeFileSync } from "node:fs"
19
26
  import { spawn } from "node:child_process"
20
- import { homedir } from "node:os"
21
27
  import { fileURLToPath } from "node:url"
22
28
  import { configDir } from "../config.mjs"
23
- import { makeDecoder, sanitizeOutput } from "../tools/shared.mjs"
29
+ import { expandHome } from "../expand-home.mjs"
30
+ import { makeDecoder } from "../tools/shared.mjs"
24
31
  import { nodeChildEnv } from "../tools/node-child.mjs"
32
+ import { capText as capBudgetText, fillMarker } from "../text-budget.mjs"
33
+ // 可见文本面(剥离 ∥ 归一 ∥ 遮蔽 ∥ 收场注记)2026-11-05 外移同目录叶档 `ssh-text.mjs`:体逐字搬家、
34
+ // 导出名零改——`ssh-session.mjs` / `ssh-transfer.mjs` / `ssh-vault.mjs` 的 import 行零改。
35
+ import { createStripper, createMask, escapeNote, normalizeText } from "./ssh-text.mjs"
36
+ export { createStripper, createMask, escapeNote, normalizeText }
25
37
 
26
- /** 静默窗(§6.22 ③):到点无新输出 ⇒ 判定就绪。 */
38
+ /** 静默窗(§6.22 ③):**只作去抖**——判尾部这半条标记到没到齐;不再单独构成「已就绪」。 */
27
39
  export const SSH_SETTLE_MS = 800
28
- /** 硬超时(§6.22 ③/⑥):到点返回部分输出 + 可读句。 */
29
- export const SSH_TIMEOUT_MS = 10_000
30
- /** 单次返回帽(§6.22 ⑥):保尾 + 截断注记;全量恒在 log。 */
40
+ /** 硬超时(§6.22 ③/⑥):`send` / `read` / `secret_input` 的本次等待;到点返回部分输出 + 可读句。 */
41
+ export const SSH_TIMEOUT_MS = 60_000
42
+ /** `connect` 首屏等待(§6.22 ③「适用范围」拆两常量——慢设备才拖不动连接)。 */
43
+ export const SSH_CONNECT_SETTLE_MS = 10_000
44
+ /** 单次返回帽(§6.22 ⑥):**返回窗口** = 保头 + 注记 + 保尾;省略中段回填未读缓冲。 */
31
45
  export const SSH_RETURN_CAP = 8000
46
+ /** 帽窗头尾比例(§6.22 ⑥:头 60% ∥ 尾 40%——头段装接口 / ACL,尾段装结束证据)。 */
47
+ const CAP_HEAD_RATIO = 0.6
32
48
  /** 保活缺省(§6.22 ④:`ServerAliveInterval=30`;测试态时间缝按 ms 传入后换算)。 */
33
49
  export const SSH_KEEPALIVE_MS = 30_000
34
50
  /** 秘密环境变量名(§6.22 ②「秘密传递」行)。 */
@@ -84,13 +100,6 @@ export function buildSshEnv({ wrapper, secret }) {
84
100
  return nodeChildEnv(env)
85
101
  }
86
102
 
87
- /** `~` 展开(`identityFile` 记录 / 参数——`~/.ssh/id_ed25519` 同式;非 `~` 开头原样)。 */
88
- function expandHome(file) {
89
- const raw = String(file ?? "")
90
- if (!/^~(?=$|[\\/])/.test(raw)) return raw
91
- return `${homedir()}${raw.slice(1)}`
92
- }
93
-
94
103
  /** 会话命令形(§6.22 ⑤):`-tt` 强制远端 PTY + 保活三件 + 单提示;`port`/`user` 未给 ⇒ 不下发。
95
104
  * `identityFile` 显式给出 / 记录有值 ⇒ `-i <路径>`(追加候选身份,不夺本机配置与 agent 的既有尝试序列)。
96
105
  * 预探 = `NumberOfPasswordPrompts=0`(password ∥ keyboard-interactive 两径同被短路——
@@ -110,50 +119,16 @@ export function buildSshArgs({ host, user, port, probe, identityFile = null, kee
110
119
  ]
111
120
  }
112
121
 
113
- // ─── 遮蔽(§6.22 ⑦)────────────────────────────────────────────────────────
114
-
115
- /** 秘密遮蔽过滤器:字面移除 + `len-1` 尾缓冲(跨 chunk 切分不泄;尾至沉降冲涮)。 */
116
- export function createMask() {
117
- const secrets = []
118
- let tail = ""
119
- let keep = 0
120
- return {
121
- add(secret) {
122
- const s = String(secret ?? "")
123
- if (!s || secrets.includes(s)) return
124
- secrets.push(s)
125
- keep = Math.max(keep, s.length - 1)
126
- },
127
- push(text) {
128
- let out = tail + String(text ?? "")
129
- for (const s of secrets) out = out.split(s).join("")
130
- if (out.length <= keep) { tail = out; return "" }
131
- const emit = out.slice(0, out.length - keep)
132
- tail = out.slice(out.length - keep)
133
- return emit
134
- },
135
- /** 沉降时冲涮尾缓冲:**只放行非秘密前缀段**(尾内最长可疑后缀一律扣下——整尾 ∥ 移位前缀
136
- * 都不出返回面;扣下的至多 `秘密长-1` 字符,代价 < 前缀外泄)。 */
137
- flush() {
138
- const t = tail
139
- tail = ""
140
- if (!t) return ""
141
- let cut = 0
142
- for (const s of secrets) {
143
- const max = Math.min(t.length, s.length - 1)
144
- for (let L = 1; L <= max; L++) if (t.endsWith(s.slice(0, L))) cut = Math.max(cut, L)
145
- }
146
- return cut ? t.slice(0, t.length - cut) : t
147
- },
148
- }
149
- }
150
-
122
+ // ─── 终端噪声 / 遮蔽(2026-11-05 拆档族已外移 `ssh-text.mjs`)──────────────────
123
+ // 剥离器(`createStripper`)、同一归一(`normalizeText`)与遮蔽过滤器(`createMask`)的体全住兄弟档
124
+ // `ssh-text.mjs`(纯「字节 → 可见文本」链,零子进程 / 零计时);本档 import 回来原样再出口。
125
+ // 收场面作两半:**半条序列的冲涮**(`flushEscapes`)留本档——它把交出的字节经 `handleChunk` 汇入
126
+ // log / 缓冲 / 等待者(运行时汇聚点住这里,搬过去就得反向 import);**注记**(`escapeNote`)随文本面走。
151
127
  // ─── 子进程(起跑 ∥ 双流汇入 ∥ 退出)────────────────────────────────────────
152
128
 
153
- /** 悬挂 chunk 双流汇入(遮蔽 → log ∥ 缓冲 ∥ 面板 → 唤醒沉降等待者)。 */
129
+ /** 悬挂 chunk 双流汇入(已剥离已遮蔽 → log ∥ 缓冲 ∥ 面板 → 唤醒沉降等待者)。 */
154
130
  function handleChunk(entry, text) {
155
131
  if (!text) return
156
- entry.bytes += text.length
157
132
  try { entry.logStream?.write(text) } catch { /* log 写失败不进语义——尽力面 */ }
158
133
  entry.buf += text
159
134
  if (entry.buf.length > BUF_KEEP_CHARS) {
@@ -165,18 +140,33 @@ function handleChunk(entry, text) {
165
140
  for (const w of [...entry._waiters]) w("data")
166
141
  }
167
142
 
168
- /** 子进程挂载(双流解码 ∥ 退出 ∥ spawn 错误——探连与会话同径)。 */
143
+ /** 子进程挂载(双流解码 ∥ 剥离 → 遮蔽 ∥ 退出 ∥ spawn 错误——探连与会话同径)。
144
+ * 顺序 = **先剥离后遮蔽**(§6.22 ③):剥离只删字节、不插入 ⇒ 切不断秘密字面;每条流一份剥离状态
145
+ * (两个流各自成序列,不共用一个半条状态)。到达计数在这之前记(§6.22 ③ 门④ 口径 = 「回了没有」,
146
+ * 不随遮蔽尾缓冲的后扣而变)。 */
169
147
  export function attachChild(entry, child) {
170
148
  entry.child = child
171
149
  const outDecoder = makeDecoder()
172
150
  const errDecoder = makeDecoder()
173
- const feed = (d) => handleChunk(entry, entry.mask.push(sanitizeOutput(d)))
151
+ const outStrip = createStripper()
152
+ const errStrip = createStripper()
153
+ entry.strippers = [outStrip, errStrip]
154
+ const route = (decoder, strip) => (d, final = false) => {
155
+ const visible = strip.feed(decoder(d, final))
156
+ if (!visible) return
157
+ entry.lastDataAt = Date.now()
158
+ entry.bytes += visible.length // 到达量(剥离后、遮蔽前)——门④ 判「回了没有」用
159
+ handleChunk(entry, entry.mask.push(visible))
160
+ }
161
+ const outRoute = route(outDecoder, outStrip)
162
+ const errRoute = route(errDecoder, errStrip)
174
163
  const flush = () => {
175
- const rest = sanitizeOutput(outDecoder(Buffer.alloc(0), true)) + sanitizeOutput(errDecoder(Buffer.alloc(0), true))
176
- if (rest) feed(Buffer.from(rest, "utf8"))
164
+ outRoute(Buffer.alloc(0), true)
165
+ errRoute(Buffer.alloc(0), true)
166
+ entry.escDropped = (entry.escDropped ?? 0) + flushEscapes(entry) // 收场:尾部半条序列丢弃并计一次
177
167
  }
178
- child.stdout.on("data", (d) => feed(outDecoder(d)))
179
- child.stderr.on("data", (d) => feed(errDecoder(d)))
168
+ child.stdout.on("data", (d) => outRoute(d))
169
+ child.stderr.on("data", (d) => errRoute(d))
180
170
  // stdin 无 error 监听 ⇒ 对端刚死时写入的异步 EPIPE 会以未处理 'error' 事件逸出(uncaughtException)。
181
171
  // 同族先例:CLI `tui/clipboard.mjs` ∥ `mcp/transport-stdio.mjs` 同式吞 EPIPE。
182
172
  child.stdin?.on("error", () => { /* 写失败由 send ∥ secret_input 的调用面回读;此处仅防未处理事件 */ })
@@ -210,17 +200,52 @@ export function spawnSession(entry, { user, port, secret, identityFile = null, k
210
200
  return child
211
201
  }
212
202
 
213
- // ─── 沉降(§6.22 ③)────────────────────────────────────────────────────────
203
+ // ─── 就绪判据(§6.22 ③ 四门 · D-TO21)─────────────────────────────────────
204
+
205
+ /** 待答标记(门①——设备正等我发键;`--More--` 走空格、确认走 y/n)。 */
206
+ const ANSWER_MARKERS = ["--More--", "(y/n)", "Password:"]
207
+ /** 缺省设备提示符形(门②——行尾 `#` `>` `$` `%`,前接非空白词)。 */
208
+ const DEVICE_PROMPT = /[^\s][#$>%]\s*$/u
214
209
 
215
- function promptHit(entry) {
216
- return Boolean(entry.promptRe && entry.promptRe.test(entry.buf))
210
+ /** 末行(门① 只看末行——陈旧标记被后续输出顶走就不命中,B18)。 */
211
+ const tailLine = (text) => {
212
+ const s = String(text ?? "")
213
+ return s.slice(s.lastIndexOf("\n") + 1)
217
214
  }
218
215
 
219
- /** 等到「就绪判据」成立:提示符命中 ∥ 静默窗到点 ∥ 硬超时 ∥ 退出 ∥ 中止(返回 reason)。 */
220
- export function waitSettled(entry, { timeoutMs = SSH_TIMEOUT_MS, signal = null } = {}) {
216
+ /** 判据面文本 = **新到字节**(`base` 之后) + 遮蔽尾缓冲(尾在 drain 时释放,门不得被它推迟)。
217
+ * `base` 撇掉本轮之前就在缓冲里的存量(回填的中段不得充当本轮判据面——§6.22 ③「四门只判新到字节」)。 */
218
+ const watchText = (entry, base = 0) => `${entry.buf.slice(base)}${entry.mask?.peek?.() ?? ""}`
219
+
220
+ /** 门① 待答标记(**末行锚定**——只看最后一个换行之后的部分;"出现"故用 `includes`:`(y/n)?` ∥ `[y/n]` 同类形都能命中)。 */
221
+ export function markerHit(entry, base = 0) {
222
+ const line = tailLine(watchText(entry, base))
223
+ return ANSWER_MARKERS.some((m) => line.includes(m))
224
+ }
225
+
226
+ /** 门② 提示符:agent 所设 `promptPattern` 命中 ∥ 缺省设备形。 */
227
+ export function promptHit(entry, base = 0) {
228
+ const text = watchText(entry, base)
229
+ if (entry.promptRe && entry.promptRe.test(text)) return true
230
+ return DEVICE_PROMPT.test(tailLine(text))
231
+ }
232
+
233
+ /** 硬超时失败标签三枚(门④——与门③ 两条子情形同文;计的是**到达字节**:剥离后、遮蔽前)。 */
234
+ function timeoutLabel(entry, startBytes) {
235
+ if (entry.bytes <= startBytes) return "not a single byte came back"
236
+ return Date.now() - entry.lastDataAt < SSH_SETTLE_MS ? "still producing output" : "no prompt detected"
237
+ }
238
+
239
+ /** 等到就绪(返回 reason):`marker` ∥ `prompt` ∥ `timeout` ∥ `exited` ∥ `aborted`(`connect` 另有 `silence`)。
240
+ * 门①② 在**每个到达 chunk** 上求值;静默窗只判「尾部这半条标记到没到齐」(去抖)——不参与求值、不推迟
241
+ * 判断时点,也不再单独构成「已就绪」(D-TO21)。`settleOnSilence` = `connect` 首屏沿用旧口径
242
+ * (§6.22 ③「适用范围」:四门只判 `send` / `read` / `secret_input`)。 */
243
+ export function waitSettled(entry, { timeoutMs = SSH_TIMEOUT_MS, signal = null, settleOnSilence = false } = {}) {
221
244
  return new Promise((resolve) => {
222
245
  let done = false
223
246
  let quietTimer = null
247
+ const startBytes = entry.bytes
248
+ const baseLen = entry.buf.length // 门①② 只判**新到字节**(存量中段不当本轮判据面)
224
249
  const deadline = Date.now() + Math.max(1, Number(timeoutMs) || SSH_TIMEOUT_MS)
225
250
  const finish = (reason) => {
226
251
  if (done) return
@@ -229,15 +254,28 @@ export function waitSettled(entry, { timeoutMs = SSH_TIMEOUT_MS, signal = null }
229
254
  clearTimeout(deadlineTimer)
230
255
  signal?.removeEventListener("abort", onAbort)
231
256
  entry._waiters.delete(onEvent)
257
+ if (reason === "timeout") {
258
+ entry.settleFailure = timeoutLabel(entry, startBytes)
259
+ entry.escDropped = (entry.escDropped ?? 0) + flushEscapes(entry) // 硬超时 = 收场边界(§6.22 ③ flush②)
260
+ }
232
261
  resolve(reason)
233
262
  }
263
+ const evaluate = () => {
264
+ if (markerHit(entry, baseLen)) { finish("marker"); return true }
265
+ if (promptHit(entry, baseLen)) { finish("prompt"); return true }
266
+ return false
267
+ }
234
268
  const arm = () => {
235
269
  clearTimeout(quietTimer)
236
- quietTimer = setTimeout(() => finish(promptHit(entry) ? "prompt" : "silence"), SSH_SETTLE_MS)
270
+ quietTimer = setTimeout(() => {
271
+ if (done) return
272
+ if (settleOnSilence) return finish(promptHit(entry, baseLen) ? "prompt" : "silence")
273
+ evaluate() // 去抖:尾部半条标记到齐后再求值一次;未命中 ⇒ 继续等到硬超时
274
+ }, SSH_SETTLE_MS)
237
275
  }
238
276
  const onEvent = (kind) => {
239
277
  if (kind === "exit") return finish("exited")
240
- if (promptHit(entry)) return finish("prompt")
278
+ if (evaluate()) return undefined
241
279
  arm()
242
280
  }
243
281
  const onAbort = () => finish("aborted")
@@ -246,15 +284,21 @@ export function waitSettled(entry, { timeoutMs = SSH_TIMEOUT_MS, signal = null }
246
284
  if (signal?.aborted) return finish("aborted")
247
285
  signal?.addEventListener("abort", onAbort, { once: true })
248
286
  entry._waiters.add(onEvent)
249
- onEvent("data") // 起点:先查提示符,否则起静默窗(「send 后 800 ms 无新输出」从本刻起算)
287
+ onEvent("data") // 起点:先查门①②,否则起去抖窗
250
288
  })
251
289
  }
252
290
 
253
- /** 就绪结论注记(§6.22 ③:静默 ∥ 提示符 ∥ 超时——超时带 id / host / 已等时长,不静默挂起)。 */
291
+ /** 就绪结论注记(§6.22 ③):提示符 ∥ 待答标记 ∥ 硬超时(**点名失败门**)∥ 中断 ∥ 退出。 */
254
292
  export function settleNote(entry, reason, waitedMs) {
255
293
  if (reason === "prompt") return "settled (prompt matched)"
294
+ if (reason === "marker") return "settled (the device is waiting for input — the marker is shown above)"
256
295
  if (reason === "silence") return "settled (silence window)"
257
- if (reason === "timeout") return `not settled after ${Math.round(waitedMs / 100) / 10}s (${idLabel(entry)} @ ${entry.host}) — partial output above (silence window or promptPattern never hit)`
296
+ if (reason === "timeout") {
297
+ const label = entry.settleFailure ?? "no prompt detected"
298
+ entry.settleFailure = null
299
+ const hint = label === "no prompt detected" ? "; pass promptPattern on connect if this device's prompt does not look like a shell prompt" : ""
300
+ return `not settled after ${Math.round(waitedMs / 100) / 10}s (${idLabel(entry)} @ ${entry.host}) — partial output above (${label}${hint})`
301
+ }
258
302
  if (reason === "aborted") return `(interrupted — partial output above; the session stays open: ${idLabel(entry)} @ ${entry.host})`
259
303
  if (reason === "exited") return `${idLabel(entry)} @ ${entry.host} ${entry.state === "ready" ? "ended (the remote closed the connection)" : "has stopped"}`
260
304
  return String(reason)
@@ -275,12 +319,70 @@ export function drain(entry) {
275
319
  return { text, dropped }
276
320
  }
277
321
 
278
- /** 返回帽(保尾 + 截断注记——§6.22 ⑥)。 */
279
- export function capText(text, max = SSH_RETURN_CAP, entry = null) {
280
- if (text.length <= max) return text
281
- const omitted = text.length - max
282
- const where = entry?.logPath ? ` — full output in the log: ${entry.logPath}` : ""
283
- return `[... first ${omitted} chars omitted (return cap ${max})${where}]\n${text.slice(text.length - max)}`
322
+ /** 回填未读缓冲(丢最旧、保住尾证据;§6.22 ⑥)。 */
323
+ function backfill(entry, middle) {
324
+ if (!middle || !entry) return
325
+ entry.buf = middle + entry.buf // 中段先于更新字节(回填顺序 = 原序)
326
+ if (entry.buf.length > BUF_KEEP_CHARS) {
327
+ entry.buf = entry.buf.slice(entry.buf.length - BUF_KEEP_CHARS)
328
+ entry.bufDropped = true
329
+ }
330
+ }
331
+
332
+ /** 返回帽窗(§6.22 ⑥ · D-TO22):**返回总长 ≤ 帽(注记计入帽内)**——头 60% ∥ 注记 ∥ 尾 40%,
333
+ * 切点按行边界取整、取整只在头段(头段可少不可多);省略中段**回填未读缓冲**(下一次 `read` 先交出)
334
+ * ⇒ 长配置按窗口连续取全,不靠翻日志。截断本体 = `text-budget.mjs` `capText`(零新截断实现)。 */
335
+ export function capWindow(entry, text, max = SSH_RETURN_CAP) {
336
+ const t = String(text ?? "")
337
+ if (!(max > 0) || t.length <= max) return t
338
+ if (max <= windowMarker(t.length, 0, 0).length) {
339
+ // 帽小到放不下注记 ⇒ 无法成窗:按帽交出前缀、余量回填缓冲(「总长 ≤ 帽」不变式先行;每次 read 都有进展)
340
+ backfill(entry, t.slice(max))
341
+ return t.slice(0, max)
342
+ }
343
+ let marker = windowMarker(t.length, 0, 0)
344
+ let head = 0
345
+ let tail = 0
346
+ for (let round = 0; round < 6; round++) {
347
+ const budget = Math.max(0, max - marker.length)
348
+ const nextHead = alignHead(t, Math.floor(budget * CAP_HEAD_RATIO))
349
+ const nextTail = Math.max(0, budget - Math.floor(budget * CAP_HEAD_RATIO))
350
+ const nextMarker = windowMarker(t.length - nextHead - nextTail, nextHead, nextTail)
351
+ const same = nextHead === head && nextTail === tail && nextMarker === marker
352
+ head = nextHead
353
+ tail = nextTail
354
+ marker = nextMarker
355
+ if (same) break
356
+ }
357
+ while (head > 0 && head + marker.length + tail > max) { // 收敛后的边角(省略数位数增长)——头段再收
358
+ head = Math.max(0, head - (head + marker.length + tail - max))
359
+ marker = windowMarker(t.length - head - tail, head, tail)
360
+ }
361
+ backfill(entry, t.slice(head, t.length - tail))
362
+ const markerOf = (omitted) => windowMarker(omitted, head, tail)
363
+ return capBudgetText(t, { max, keepHead: head, keepTail: tail, marker: markerOf })
364
+ }
365
+
366
+ /** 注记形(§6.22 ⑥):`N` 走 `text-budget.mjs` `fillMarker` 占位约定;`H` ∥ `T` = 实保头 ∥ 尾长。 */
367
+ const WINDOW_MARKER = "[… N chars omitted (head H / tail T) — the omitted middle is kept; call read again to collect it …]\n"
368
+ const windowMarker = (omitted, head, tail) =>
369
+ fillMarker(WINDOW_MARKER, omitted).replace("H", String(head)).replace("T", String(tail))
370
+
371
+ /** 头段切点按行边界取整(不切半行;找不到换行则保持原位——头段可少不可多)。 */
372
+ const alignHead = (text, n) => {
373
+ const nl = text.lastIndexOf("\n", Math.max(0, n - 1))
374
+ return nl >= 0 ? nl + 1 : n
375
+ }
376
+
377
+ /** 半条序列的收场(§6.22 ③ flush②):尾部半条丢弃并计一次;其前后的可见字节照常交出。 */
378
+ export function flushEscapes(entry) {
379
+ let dropped = 0
380
+ for (const strip of entry.strippers ?? []) {
381
+ const res = strip.end()
382
+ if (res.text) handleChunk(entry, entry.mask.push(res.text))
383
+ dropped += res.dropped
384
+ }
385
+ return dropped
284
386
  }
285
387
 
286
388
  /** 状态行冠形(§6.22 动作表末行):每返回首行。 */
@@ -30,7 +30,7 @@ import { unsettledRow, unsettledRows } from "../agent/digest-account.mjs"
30
30
  * - id omitted → { overview: { running: [...], queued: [...], done: [...],
31
31
  * unsettled: [{id, role, state, attempts, preview?}] } } — live queue positions (index in
32
32
  * _asyncQueue + 1); the unsettled section lists every entry still awaiting settlement
33
- * (awaiting-digest / retrying) plus the upgraded ledger (§6.31.6).
33
+ * (awaiting-digest / unaccounted) plus the upgraded ledger (§6.31.6).
34
34
  * AGENT-LOOP-SUBAGENT.md §6.7.2: running 条目带 touched files 摘要(touchedFiles 前 5 + touchedMore 超出
35
35
  * 计数——相对查询方 cwd;0 改动 → touched 占位);queued 条目带 touched 占位
36
36
  * "—(未启动)";done/error/取消条目无 touched 字段(round3 #9)。
@@ -217,11 +217,10 @@ function queuedPositionOf(agent, key) {
217
217
  return i >= 0 ? i + 1 : undefined
218
218
  }
219
219
 
220
- /** recent 参数钳制(默认 ~5 条摘要——可参数;钳到 1..20 防超长 N2 失控)。 */
220
+ /** recent 参数钳制(必填,1..20;不再造默认值)。值已在 `executeObserveAction` 入口判过缺 ∥ 非法,
221
+ * 本函数只钳区间;钳制到 1..20 防超长 N2 失控。 */
221
222
  function clampRecent(n) {
222
- const v = Number.parseInt(n, 10)
223
- if (!Number.isFinite(v)) return 5
224
- return Math.max(1, Math.min(20, v))
223
+ return Math.max(1, Math.min(20, n))
225
224
  }
226
225
 
227
226
  /**
@@ -242,6 +241,11 @@ export function executeObserveAction(args, ctx) {
242
241
  return JSON.stringify({ status: "error", error: "observe requires the id of the async subagent to inspect (from the async spawn return) — pass the id; omitting it observes nothing" })
243
242
  }
244
243
  const key = String(id)
244
+ // `recent` 必填(KD-4):钳制函数里的 `return 5` 是代码造的值——缺了就拒,不替调用方选条数。
245
+ const recentNum = Number.parseInt(args?.recent, 10)
246
+ if (!Number.isFinite(recentNum)) {
247
+ return JSON.stringify({ status: "error", error: `observe: recent is required — pass how many recent-turn summaries to return (1..20); got ${JSON.stringify(args?.recent ?? null)}` })
248
+ }
245
249
  const entry = getAsyncPool(agent, "subagent")?.get(key)
246
250
  if (!entry) {
247
251
  if (getAsyncPool(agent, "advisor")?.has(key)) {
@@ -259,7 +263,7 @@ export function executeObserveAction(args, ctx) {
259
263
  // 执行前后维护——LLM 生成/工具间空隙为空;子代理 await 长工具调用时父回合可见它。
260
264
  const inflight = child?._inflightTools
261
265
  if (inflight instanceof Set && inflight.size > 0) out.currentTool = [...inflight]
262
- const n = clampRecent(args?.recent)
266
+ const n = clampRecent(recentNum)
263
267
  out.recentTurns = recentTurnLines(child, n)
264
268
  out.note = `observing running ${entry.role}#${key} — recentTurns newest-first (cap ${n}); currentTool shown only while a tool is executing (stuck detection); sent directions consume at the next turn boundary`
265
269
  } else if (entry.status === "queued") {
@@ -270,7 +274,7 @@ export function executeObserveAction(args, ctx) {
270
274
  out.done = true
271
275
  out.turn = entry.turn ?? 0
272
276
  out.maxTurns = entry.maxTurns ?? 0
273
- out.recentTurns = child ? recentTurnLines(child, clampRecent(args?.recent)) : []
277
+ out.recentTurns = child ? recentTurnLines(child, clampRecent(recentNum)) : []
274
278
  out.note = "settled — the final report is delivered by the auto channel (turn-end collection or the suspension digest); observe returns the activity summary, not the full report (N2)"
275
279
  }
276
280
  return JSON.stringify(out)
@@ -245,7 +245,7 @@ function touchedFilesNote(child, cwd) {
245
245
  const touched = child?._touchedFiles ?? []
246
246
  if (touched.length === 0) return ""
247
247
  const shown = touched.map((f) => {
248
- const r = relative(cwd ?? process.cwd(), f)
248
+ const r = relative(cwd, f)
249
249
  return r && !r.startsWith("..") && !isAbsolute(r) ? r : f
250
250
  })
251
251
  return `\nTouched files: ${shown.join(", ")}`
@@ -40,6 +40,7 @@ import { noteReviewDelivered } from "./review-facts.mjs"
40
40
  import { injectBgResult } from "./bash-async.mjs"
41
41
  // 批 browser-async-fix:后台浏览器动作注入器(同族——role="browser" 分发到 browser-async.mjs)。
42
42
  import { injectBrowserResult } from "./browser-async.mjs"
43
+ import { mergeAttribution } from "../agent/batch-attribution.mjs" // 归属表合入(收口取材的判据一;子代理记在自己的 agent 上,并回父侧)
43
44
 
44
45
  // agent-tools 共享:并行子代理的审批/继续弹窗经 owner 上命名 promise 链串行——
45
46
  // 永不叠弹窗(返回链供调用方 .then 续接)。
@@ -50,7 +51,7 @@ export function enqueueAsk(owner, key, ask) {
50
51
  }
51
52
 
52
53
  // Async pool limits per role domain (AGENT-LOOP-ASYNC-POOL.md §6.10 — R14, 2026-09-06):
53
- // the old single cap (ASYNC_SUBAGENT_LIMIT = 4, AGENT-LOOP-SUBAGENT.md §6.7.3 D-A4) evolved into two
54
+ // the old single cap (ASYNC_SUBAGENT_LIMIT = 4, AGENT-LOOP-SUBAGENT.md §6.7.3) evolved into two
54
55
  // independent pools — eng-coder 4 / other roles 4 (user ruling "eng-coder 四路,
55
56
  // 其他 4 路") — a full engCoder pool never blocks an explore spawn and vice versa
56
57
  // (same-domain cap still 4, cross-domain total up to 8). The per-turn check
@@ -63,8 +64,9 @@ export const ASYNC_POOL_LIMITS = { engCoder: 4, other: 4 }
63
64
 
64
65
  /**
65
66
  * Role → pool domain (single source of truth — §6.10 修正 #8): the CLI role
66
- * whitelist is subagent.mjs's ROLES = { explore, plan, coder, eng-coder, eng-designer }
67
- * (mode-filtered: normal → explore/plan/coder, engineering → explore/eng-designer/eng-coder).
67
+ * whitelist is subagent.mjs's ROLES = { explore, plan, coder, eng-coder, eng-designer, tester }
68
+ * (mode-filtered: normal → explore/plan/coder/tester, engineering → explore/eng-designer/eng-coder/tester —
69
+ * tester is dispatchable in both modes).
68
70
  * eng-coder → engCoder pool; every other role (including unknown roles — fail-safe)
69
71
  * → other pool. escalate spawns its expert internally (role "coder" — other pool).
70
72
  */
@@ -122,7 +124,7 @@ function warnPoolFallback(what, sig) {
122
124
  console.warn(`[config] agent.poolLimits: ${what} — must be a positive integer ≥1 — falling back to default ${JSON.stringify(ASYNC_POOL_LIMITS)}`)
123
125
  }
124
126
 
125
- /** Running count within ONE pool domain (口径同 AGENT-LOOP-SUBAGENT.md §6.7.3 D-A1/T6: queued 与已完成不计入;
127
+ /** Running count within ONE pool domain (口径同 AGENT-LOOP-SUBAGENT.md §6.7.3 T6: queued 与已完成不计入;
126
128
  * 条目带 _pool 域字段——spawn 时 poolDomainOf(role) 落位;缺字段(手工/旧条目)按
127
129
  * other——既有 coder 域测试语义不变)。 */
128
130
  export function runningPoolCount(parent, pool) {
@@ -313,10 +315,10 @@ export function executeCancelAction(args, ctx) {
313
315
  }
314
316
 
315
317
  /**
316
- * 共享 post-spawn 管线(阻塞与 async 同一条——AGENT-LOOP-SUBAGENT.md §6.7.3 D-A1 "全不变"):turn-cap continue
318
+ * 共享 post-spawn 管线(阻塞与 async 同一条——AGENT-LOOP-SUBAGENT.md §6.7.3 "全不变"):turn-cap continue
317
319
  * 循环 → 拒绝降级 partial 返回 → MIN_REPORT_CHARS 扩写 → eng-coder mutation merge →
318
320
  * designId 后缀。onDeclined 在此(两路同一形态)——只有 askContinue 不同:阻塞经权限
319
- * 面板询问;async 永不弹面板(自动拒绝;engineering && AUTO 自动 resume——§6.7.3 D-A3)。
321
+ * 面板询问;async 永不弹面板(自动拒绝;撞帽即注册父侧检查点、挂起等父 `send` / `cancel`,AUTO 档亦不自动续跑——§6.7.3)。
320
322
  */
321
323
  export async function runChildPipeline(child, input, childOpts, childRunOpts, { parent, role, args, askContinue }) {
322
324
  const declined = { partial: null }
@@ -462,11 +464,9 @@ export function mergeChildMutations(parent, child) {
462
464
  // to the parent's guard state.
463
465
  if (!child._mutatedThisRun || !(child._touchedFiles?.length)) return false
464
466
  parent._mutatedThisRun = true
465
- const merged = []
466
- for (const abs of child._touchedFiles ?? []) {
467
- if (!parent._touchedFiles.includes(abs)) parent._touchedFiles.push(abs)
468
- merged.push(abs)
469
- }
467
+ const merged = [...(child._touchedFiles ?? [])]
468
+ for (const abs of merged) if (!parent._touchedFiles.includes(abs)) parent._touchedFiles.push(abs)
469
+ mergeAttribution(parent, child) // 归属表并集(判据一的取材面随 `_touchedFiles` 同笔并回)
470
470
  // §6.10: merged code mutates the parent's state — log it for the stale
471
471
  // scan of in-flight reviews (a review whose code changed under it is stale).
472
472
  noteMutations(parent, merged)
@@ -0,0 +1,76 @@
1
+ /**
2
+ * subagent-brief.mjs — **任务书与 system 固块拼装**族:任务书播报文本、写域行(S4)、文档坐标行(S5)。
3
+ *
4
+ * 机制单源 = `docs/core/design/AGENT-LOOP-SUBAGENT.md` §6.22(任务书)∥ §6.26(写域行 S4)∥ §6.61(文档坐标行 S5);
5
+ * 本档只拼文本,不判准入——三条门的判据住 `./spawn-gates.mjs` 与 `./subagent-spawn.mjs`。
6
+ * **为什么单独立档**:这三个函数是纯拼装(入参 → 一段文本),消费者只有 `subagent-spawn.mjs` 的 child 装配点;
7
+ * 把它整族搬走是分拆落点(`docs/core/design/PATH-RESOLUTION.md` §3 末条),装配面一句调用都没动。
8
+ */
9
+ import { relative } from "node:path"
10
+
11
+ import { docRootBase, docRootPaths, readManifest } from "../manifest.mjs"
12
+ import { composeTaskBookBrief } from "./spawn-gates.mjs"
13
+
14
+ /** 任务书播报文本:该角色名集拼装 + 可选 task 自由文本(拼装空 ⇒ 原 task 逐字——旧形零变)。 */
15
+ export function taskBriefOf(args, role) {
16
+ const composed = composeTaskBookBrief(args, role)
17
+ if (!composed) return args.task
18
+ const extra = typeof args.task === "string" ? args.task.trim() : ""
19
+ return extra ? `${composed}\n\n${extra}` : composed
20
+ }
21
+
22
+ /** S4 写域行(AGENT-LOOP-SUBAGENT.md §6.26「写域行(S4)」):表头 + 逐条绝对路径 + 两句语义——
23
+ * 本档局部纯函数(D23-9:不外提模块)。两句不可省:缺① 子代理读成「我只能写这些」⇒ 该写的漏掉;
24
+ * 缺② 仍把任务书 §2 全文当成自己的改动面(本块的病因)。清单不截断——截断正是本块要消除的
25
+ * 「看不见」。返回块文本(块间分隔由装配侧 `join("\n\n")` 施加)。 */
26
+ export function filesBlockOf(files) {
27
+ return `Files declared for this spawn (the write domain this task declares, for scheduling):\n` +
28
+ files.map((f) => `- ${f}`).join("\n") +
29
+ `\n\nThis list is not an authorization boundary: touching a file outside it is allowed — report every out-of-list file you changed, with its reason. It is also not the whole change surface: other spawns on this task declare their own files, and what is listed here is your share only.`
30
+ }
31
+
32
+ /** §6.61 契约 ② 的两件常量:层键固定 = 这三层(`specs` ∥ `modules` ∥ `standards` 不读——多的层每发再付
33
+ * 一次 token,KD-DC3);前缀逐字(英文——与兄弟块同语体),层串接在其后。 */
34
+ const DOCS_COORDINATE_KEYS = ["requirements", "design", "batches"]
35
+ const DOCS_COORDINATE_PREFIX = "Docs (project-root relative, declared by this project's PROJECT-MANIFEST.json docRoot):"
36
+
37
+ /** S5 文档坐标行(AGENT-LOOP-SUBAGENT.md §6.61「子代理文档坐标行」):本项目 manifest 声明的三层
38
+ * 文档坐标(`requirements` ∥ `design` ∥ `batches`),项目根相对形,一行随 system 固块下发;
39
+ * 未声明的层呈现 `(undeclared)`。
40
+ *
41
+ * **「未声明」的判别单源 = `readManifest` 同次返回的 `missingKeys`**——它在**原始档**上算得,与补默认
42
+ * 后的值分属两个事实。不能看返回的 `manifest.docRoot[键]` 判:`readManifest` 的返回值已 `fillDefaults`,
43
+ * `docs/design` 这类默认路径与一条真声明同形,打出去就是把项目从未声明的坐标当声明发给子代理
44
+ * (KD-DC2——比不发更坏,它看起来像声明)。
45
+ *
46
+ * **读不出(缺档 ∥ 坏档 ∥ 校验不过 ∥ 读抛 ∥ 项目根解析链 I/O 异常)⇒ 返回 null,调用点不推块**:不加本行
47
+ * 的结果 = 本批之前的行为,业务结果零变(KD-DC4;这不是兜底式静默——坐标取不到不该赔掉一次 spawn)。
48
+ *
49
+ * **护栏宽度 = 整段坐标计算**(读档 + 基数解析 + 路径映射 + 串拼装),不是只包读档那一句(§6.61.2 ④ ·
50
+ * AC-DC-8):基数取法 `docRootBase(cwd)` 走项目发现链,而树根那一环 `owningProject` 的 `statSync` 无护栏
51
+ * ⇒ 该链的 I/O 异常照原样上抛;只包读档那一句,「读不出不赔掉一次 spawn」就只兑现一半。
52
+ *
53
+ * 返回块文本 ∥ null。 */
54
+ export function docsCoordinatesBlockOf(cwd) {
55
+ try {
56
+ const read = readManifest(cwd)
57
+ if (!read.ok || !read.manifest) return null // 缺档 ∥ 坏 JSON ∥ 校验不过(契约 ③ 读档格)
58
+ const missing = new Set(read.missingKeys ?? [])
59
+ // 整键缺 ∥ 非对象 ⇒ 三层皆按未声明。**不另设「三层全未声明」分支**:它就是下面这条逐层判据连用三次。
60
+ const wholeUndeclared = missing.has("docRoot")
61
+ const base = docRootBase(cwd)
62
+ const layers = DOCS_COORDINATE_KEYS.map((key) => {
63
+ if (wholeUndeclared || missing.has(`docRoot.${key}`)) return `${key} = (undeclared)`
64
+ const value = read.manifest.docRoot?.[key]
65
+ // 显式「本面无」(`null`)与缺键同呈现:`docRootPaths(null) = []` 已定那一读(MANIFEST.md §2.7)。
66
+ if (value === null || value === undefined) return `${key} = (undeclared)`
67
+ // 路径一律项目根相对、`/` 分隔;解析为空(声明 = 项目根自身)呈现为 `.`。
68
+ const roots = docRootPaths(value, cwd).map((abs) => relative(base, abs).replaceAll("\\", "/") || ".")
69
+ return `${key} = ${roots.join(", ")}`
70
+ })
71
+ return `${DOCS_COORDINATE_PREFIX} ${layers.join(" · ")}`
72
+ } catch {
73
+ // 读档非 ENOENT 读错(权限 ∥ 目录等)· 项目根解析链的 I/O 异常:一律收成「读不出」(契约 ④)
74
+ return null
75
+ }
76
+ }