@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
@@ -9,11 +9,15 @@
9
9
  * 既有 import 面);`resolveReviewDocPaths` = 评审文档路径解析单源;
10
10
  * - 2026-10-25(评审文档路径收正批):该解析器收为**单规则**——相对形按会话项目根 / 绝对形
11
11
  * 照用 / 受理 = 项目内现存 `.md`;候选试探与歧义归一退场(判据正文 = `ADVISOR-GUARDS.md` §12)。
12
+ * - 2026-11-02(path-resolution-unify 批):路径判定改调统一解析层(`../path-resolve.mjs`)——
13
+ * 本面只留受理判据;拒因词 `no-project-root` 退役,拆成 `ambiguous-path`(判不出唯一基根)
14
+ * ∥ `dangling-path`(无项目根)。
12
15
  */
13
16
  import { existsSync, statSync } from "node:fs"
14
- import { isAbsolute, join, relative, resolve, sep } from "node:path"
17
+ import { isAbsolute, join, relative, sep } from "node:path"
15
18
  import { DEFAULT_MANIFEST, docRootPaths, readManifest } from "../manifest.mjs"
16
19
  import { owningProject, projectRootView } from "../manifest-discovery.mjs"
20
+ import { resolvePathTarget } from "../path-resolve.mjs"
17
21
 
18
22
  /** ABS 归一(cwd 相对 → cwd 拼接)——陈旧判定 / 冻结拦截 / 评审范围键同源(ADVISOR-GUARDS.md §5 E-4)。 */
19
23
  export function normAbs(p, cwd) {
@@ -31,8 +35,12 @@ export function docSetKey(documents, cwd) {
31
35
 
32
36
  /** **写门面**评审根的 docRoot 键集(`agent/write-gate.mjs` 的 `resolveReviewTargetPaths` 消费)——
33
37
  * 设计评审**受理面不再消费**本键集(受理 = 项目内现存 `.md`,判据单源 = `ADVISOR-GUARDS.md` §12)。
34
- * 2026-10-04 自 `agent/write-gate.mjs` 迁入(键集本体零变;write-gate 同名再出口)。 */
35
- 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"]
36
44
 
37
45
  /**
38
46
  * 写门评审根解析单点(按用点形——2026-09-21 收口 · 台账 #828;2026-10-04 自 `agent/write-gate.mjs`
@@ -66,26 +74,43 @@ function isInside(p, root) {
66
74
 
67
75
  /**
68
76
  * **评审文档路径解析单规则**(判据正文 = `docs/core/design/ADVISOR-GUARDS.md` §12)——逐文档:
69
- * ① 相对形:基面 = **会话项目根** `projectRootView(cwd).root`——`p = resolve(根, doc)`;越根 ⇒ `outside-project`;
70
- * ② 相对形 ∧ 项目根解析不出(锚 = `workspace` / `none`)⇒ `no-project-root`;
71
- * ③ 绝对形:照用(零根试探、零拼接);不住在任何项目里(`owningProject` 空)⇒ `outside-project`;
72
- * ④ 受理 = 现存普通文件 ∧ `.md`(大小写不敏感);否则 `not-doc-file`。
73
- * **零试探**:无候选项目根、无祖先链、无歧义归一——路径要求写对(用户 2026-10-25 11:41
74
- * 「为啥要试探?不能要求写对吗?」)。
77
+ * ① 路径判定全部经统一解析层(`kind:"file"` / `order:"root-first"` / `bases` = 无 /
78
+ * `scanBases` = `docRoot` 各键——只喂同名候选,不作受理基底;本面受理面零放宽);
79
+ * ② 判不出唯一基根(层判 `ambiguous`——工作区锚)⇒ `ambiguous-path` + 候选全列;
80
+ * 无项目根(层判 `dangling.level:"base"`)⇒ `dangling-path`;
81
+ * ③ 相对形 ∧ 锚无项目根 ⇒ `dangling-path`(受理判据「必须在项目内」——档层无根时相对形无基可挂);
82
+ * 相对形越根 ⇒ `outside-project`;
83
+ * ④ 绝对形照用(零根试探、零拼接);不住在任何项目里(`owningProject` 空)⇒ `outside-project`;
84
+ * ⑤ 受理 = 现存普通文件 ∧ `.md`(大小写不敏感);否则 `not-doc-file`。
85
+ * **零试探**:层判不出唯一即停(用户 2026-10-25 11:41「为啥要试探?不能要求写对吗?」)。
75
86
  * 非字符串 / 空白串项**静默跳过**(同 docSetKey 既有过滤语义——不进 resolved / invalid)。
76
- * @returns {{ resolved: Map<string,string>, invalid: Array<{doc: string, resolved: string|null, reason: string}> }}
77
- * `reason` ∈ `no-project-root` / `outside-project` / `not-doc-file`(标识行恒 `criterion=scope-not-doc`,
78
- * 三值只作 `reason=`);`resolved` 项 = 解析后绝对路径(`no-project-root` 无基面 ⇒ `null`)。
87
+ * @returns {{ resolved: Map<string,string>, invalid: Array<{doc: string, resolved: string|null, reason: string,
88
+ * candidates?: string[], sameName?: string[]}> }}
89
+ * `reason` ∈ `ambiguous-path` / `dangling-path` / `outside-project` / `not-doc-file`(标识行恒
90
+ * `criterion=scope-not-doc`,四值只作 `reason=`);`resolved` 项 = 解析后绝对路径(无基面 ⇒ `null`)。
79
91
  */
80
92
  export function resolveReviewDocPaths(documents, cwd) {
81
- const view = projectRootView(cwd ?? process.cwd())
93
+ const view = projectRootView(cwd)
94
+ const scanBases = resolveReviewRootsFor(cwd)
82
95
  const resolved = new Map()
83
96
  const invalid = []
84
97
  for (const doc of (documents ?? [])) {
85
98
  if (typeof doc !== "string" || !doc.trim()) continue
86
99
  const abs = /^[a-zA-Z]:[\\/]/.test(doc) || doc.startsWith("/") || doc.startsWith("\\\\")
87
- if (!abs && view.state !== "ok") { invalid.push({ doc, resolved: null, reason: "no-project-root" }); continue }
88
- const p = abs ? doc : resolve(view.root, doc)
100
+ const r = resolvePathTarget(cwd, doc, { kind: "file", order: "root-first", scanBases })
101
+ if (r.state === "ambiguous") { invalid.push({ doc, resolved: null, reason: "ambiguous-path", candidates: r.candidates }); continue }
102
+ // 相对形 ∧ 锚无项目根 ⇒ 无基可挂(受理判据「必须在项目内」)——**与盘上有没有那档无关**:
103
+ // 同一锚态同一个词(KD-8),否则拒因词成了磁盘状态的函数。
104
+ if (!abs && view.state !== "ok") { invalid.push({ doc, resolved: null, reason: "dangling-path" }); continue }
105
+ if (r.state === "dangling") {
106
+ if (r.level === "base") { invalid.push({ doc, resolved: null, reason: "dangling-path" }); continue }
107
+ invalid.push({ doc, resolved: r.tried?.[0] ?? null, reason: "not-doc-file", sameName: r.sameName })
108
+ continue
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 }
113
+ const p = r.abs
89
114
  if (!abs && !isInside(p, view.root)) { invalid.push({ doc, resolved: p, reason: "outside-project" }); continue }
90
115
  if (abs && !owningProject(p, cwd)) { invalid.push({ doc, resolved: p, reason: "outside-project" }); continue }
91
116
  if (!isDocFile(p)) { invalid.push({ doc, resolved: p, reason: "not-doc-file" }); 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
  }
@@ -2,9 +2,10 @@
2
2
  * spawn-gates.mjs — M5 委派与 spawn 门新门禁统一落点(ENGINEERING-MODE-V2-MODULE-DELEGATION §2.3):
3
3
  * 全部新增门禁逻辑集中于此——装配点(buildSpawnChild / normalizeFileList)只加 import 调用。
4
4
  * 已实现:F2(round 枚举 + 任务书参数门/拼装)· F6(files 声明面拦截谓词)。
5
- * 2026-10-24(AGENT-LOOP-SUBAGENT.md §6.22):任务书单通道 = 批次档 §2——工程角色
6
- * (eng-coder / eng-designer)零任务书文本参数,八个自由文本键(键在场即拒)命中即点名拒收;
7
- * 非工程角色(explore / plan / coder)保持四项核心 + `scope`。
5
+ * 2026-10-24(AGENT-LOOP-SUBAGENT.md §6.22):工程角色零任务书文本参数——八个自由文本键
6
+ * (键在场即拒)命中即点名拒收;任务书 = 绑定批档、按角色切片(2026-11-15 §8.1:eng-coder 取 §2,
7
+ * eng-designer 取 §1 + §2);
8
+ * 非工程角色(explore / plan / coder / tester)保持四项核心 + `scope`。
8
9
  * 裁撤(2026-09-17 主 agent 裁定——不落代码):
9
10
  * - F4 修复轮窄带:全量勘察散文 marker 不可机判(误拒风险不可接受)→ 由 F2 的 round 参数承载轮次语义;
10
11
  * - F5 advisor 角色:advisor 不入 spawn 通道(评审走 advisor 工具)——enum 收正为
@@ -18,7 +19,7 @@
18
19
  export const ROUND_VALUES = ["initial", "fix"]
19
20
 
20
21
  /** 任务书样例内容(供人照抄;不是门的判据——门只判存在 / 类型 / 非空):非工程角色
21
- * = 四项核心 + `scope`(工程角色无任务书文本参数——任务书 = 批次档 §2)。 */
22
+ * = 四项核心 + `scope`(工程角色无任务书文本参数——任务书 = 绑定批档,按角色切片(§8.1))。 */
22
23
  const TASK_BOOK_CORE_MIN = {
23
24
  goal: "实现批准设计(样例任务书——四项核心 + `scope` 齐备)。",
24
25
  knownFacts: "设计已评审通过、token 已签发、批次档在册。",
@@ -26,7 +27,7 @@ const TASK_BOOK_CORE_MIN = {
26
27
  reportFormat: "交付表 + 文件路径 + 验证命令与结果。",
27
28
  }
28
29
 
29
- /** 非工程角色样例(核心四项 + `scope`)——explore / plan / coder。 */
30
+ /** 非工程角色样例(核心四项 + `scope`)——explore / plan / coder / tester。 */
30
31
  export const PLAIN_TASK_BOOK_MIN = { ...TASK_BOOK_CORE_MIN, scope: "只读:相关源 / 设计档;不写任何文件、不碰 bench/。" }
31
32
 
32
33
  /**
@@ -53,7 +54,7 @@ export function validateRoundParam(args) {
53
54
  /** 工程角色名集(单一判据 = 是否有写权 ⇒ 只应有唯一任务来源——AGENT-LOOP-SUBAGENT.md §6.22)。 */
54
55
  const ENGINEERING_ROLES = new Set(["eng-coder", "eng-designer"])
55
56
 
56
- /** 角色 ∈ 工程角色(任务书 = 批次档 §2,零任务书文本参数)。 */
57
+ /** 角色 ∈ 工程角色(任务书 = 绑定批档,按角色切片(§8.1);零任务书文本参数)。 */
57
58
  export function isEngineeringRole(role) {
58
59
  return ENGINEERING_ROLES.has(role)
59
60
  }
@@ -80,14 +81,14 @@ export function rejectEngFreeTextParams(args, role) {
80
81
  if (offending.length === 0) return
81
82
  const names = offending
82
83
  .map((name) => (name === "designPoints"
83
- ? `${name} (designPoints is retired for every role — write §2, or scope for explore/plan/coder)`
84
+ ? `${name} (designPoints is retired for every role — write §2, or scope for explore/plan/coder/tester)`
84
85
  : name))
85
86
  .join(" / ")
86
87
  const required = ENG_REQUIRED_NAMES[role] ?? "role · batchDoc (readable) · round"
87
88
  throw new Error(
88
89
  `Spawn task-channel gate (role='${role}'): ${names}. ` +
89
- `An engineering spawn carries NO task-book text parameters — the task book is batch record §2 (batchDoc), read by the child itself. ` +
90
- `Put everything the child needs into §2 before spawning; a thin §2 earns a bounce, not a supplement. ` +
90
+ `An engineering spawn carries NO task-book text parameters — the task book is the bound batch record (batchDoc), sliced per role into the spawn system block (eng-coder: §2; eng-designer: §1 + §2). ` +
91
+ `Put everything the child needs into ${role === "eng-designer" ? "the record (§1 rulings bind; §2 is your pen)" : "§2"} before spawning; a thin section earns a bounce, not a supplement. ` +
91
92
  `Required for role='${role}': ${required}.`)
92
93
  }
93
94
 
@@ -103,7 +104,7 @@ export const TASK_BOOK_PARAMS = {
103
104
  }
104
105
 
105
106
  /** 角色 → 该角色的任务书名集(四项核心 + `scope`;序 = 拼装序:第五项插在 `knownFacts` 之后)。
106
- * 工程角色返回空集——它们没有任务书文本参数(任务书 = 批次档 §2)。 */
107
+ * 工程角色返回空集——它们没有任务书文本参数(任务书 = 绑定批档,按角色切片(§8.1))。 */
107
108
  export function taskBookParamsFor(role) {
108
109
  if (isEngineeringRole(role)) return []
109
110
  const core = TASK_BOOK_PARAMS.core
@@ -152,7 +153,7 @@ export function validateTaskBookParams(args, role) {
152
153
 
153
154
  /** 非工程角色任务书 → 子代理任务书文本(**非门禁**,纯拼装):按 `taskBookParamsFor(role)` 固定序
154
155
  * + 标签,空值跳过,`\n\n` 分隔。拼装单源 = 本函数——子代理 input、权限预览与探针判官同源。
155
- * 工程角色名集为空 ⇒ 返回空串(任务书 = 批次档 §2,运行时不拼装——KD-SC5)。 */
156
+ * 工程角色名集为空 ⇒ 返回空串(任务书 = 绑定批档,按角色切片(§8.1),运行时不拼装——KD-SC5)。 */
156
157
  export function composeTaskBookBrief(args, role) {
157
158
  const a = args ?? {}
158
159
  const parts = []
@@ -182,22 +183,18 @@ const PROCESS_BASENAMES = new Set(["changelog.md"])
182
183
  const MANIFEST_BASENAME = "project-manifest.json"
183
184
 
184
185
  /**
185
- * F6 files 声明面拦截谓词(ENGINEERING-MODE-V2-MODULE-DELEGATION §2.2):
186
- * scripts/*(工程工具面不入域——**层级锚定:仅仓根与直接子层**——目录名在深层不携带
187
- * face 信息(2026-10-14 收正:#1449——`deployment/<x>/scripts/*` 类交付物放行)——内容
188
- * 产物 only)与过程档(父侧职责)→ 收集全部违规后抛合并错误(fail-closed——错误即工具
189
- * 结果 JSON——无排队残留)。目录声明不在本谓词(normalizeFileList 循环内先行拒——错误
190
- * 序不变)。调用点 = normalizeFileList(subagent-scheduler.mjs——本谓词在循环后跑——
191
- * 目录错误先于过程档错误)。
186
+ * F6 files 声明面拦截谓词(ENGINEERING-MODE-V2-MODULE-DELEGATION §2.2):过程档(父侧职责)与项目状态档
187
+ * → 收集全部违规后抛合并错误(fail-closed——错误即工具结果 JSON——无排队残留)。目录声明不在本谓词
188
+ * (normalizeFileList 循环内先行拒——错误序不变)。调用点 = normalizeFileList(subagent-scheduler.mjs——
189
+ * 本谓词在循环后跑——目录错误先于过程档错误)。
190
+ * 产品面路径(含仓根 `scripts/**` · `test/**`)本就该进 `files` 声明面——工程工具面退役后不再有这一臂。
192
191
  */
193
- export function rejectEngineeringFilePaths(files) {
192
+ export function rejectProcessDocPaths(files) {
194
193
  const violations = []
195
194
  for (const f of Array.isArray(files) ? files : []) {
196
195
  const segs = String(f).replace(/\\/g, "/").split("/").filter((s) => s)
197
196
  const base = (segs[segs.length - 1] ?? "").toLowerCase()
198
- if (segs.slice(0, 2).some((s) => s.toLowerCase() === "scripts")) {
199
- violations.push(`engineering-tools face path ${f} must not be listed in files — scripts/* at the repo root or a direct child package is the engineering-tools face, not a content product (applies to every session, not engineering-mode-scoped; files carries source/test/design-doc paths only)`)
200
- } else if (PROCESS_BASENAMES.has(base)) {
197
+ if (PROCESS_BASENAMES.has(base)) {
201
198
  violations.push(`Parent-side maintained file ${f} must not be listed in files — reconciliation is the parent's duty; use the design-doc path if you need to edit a design doc`)
202
199
  } else if (base === MANIFEST_BASENAME) {
203
200
  violations.push(`Manifest file ${f} must not be listed in files — PROJECT-MANIFEST.json is the project state manifest and the main agent is its only writer (M1 write gate); this files-domain check is the second line of defense`)
@@ -2,7 +2,7 @@
2
2
  * ssh-session.mjs — SSH 会话面单点(池 ∥ 生命周期 ∥ 动作 ∥ 凭据窗 ∥ 非密预填)。
3
3
  * 设计 = `docs/core/design/TOOLS.md` §6.22(D-TO17/D-TO18 · 台账 #1436);需求 = `docs/core/requirements/TOOLS.md` §4.8。
4
4
  * 工具面 = `tools/ssh.mjs`(薄接线);传输面 = `agent-tools/ssh-transport.mjs`(askpass 链 / 沉降 / 遮蔽 / 帽
5
- * ——拆档由 = 机制档触 500 顾问线,§6.22 落点表「实施轮先审拆分」)。
5
+ * ——拆档由 = 当年机制档已过 500 行,§6.22 落点表候选拆分)。
6
6
  *
7
7
  * - 池:`_sshSessions`(照 `bash-async.mjs` 池先例——载体经 `carrierField` 吸收);帽 `SSH_SESSION_MAX = 4`
8
8
  * 条存活会话;超限**显式拒**(零静默关旧)。
@@ -30,9 +30,9 @@ import {
30
30
  } from "./async-settle.mjs"
31
31
  import { assertPoolKeyFree, consumeSubagentToken, nextSubagentId } from "./subagent-scheduler.mjs"
32
32
  import {
33
- SSH_KEEPALIVE_MS, SSH_RETURN_CAP, SSH_SETTLE_MS, SSH_TIMEOUT_MS, bodyText, capText, classifyFailure, createMask, drain,
34
- failureText, idLabel, settleNote, sshConfigDir, spawnSession, statusLine, unlinkAskpass, waitSettled,
35
- writeAskpassWrapper,
33
+ SSH_CONNECT_SETTLE_MS, SSH_KEEPALIVE_MS, SSH_RETURN_CAP, SSH_SETTLE_MS, SSH_TIMEOUT_MS, bodyText, capWindow, classifyFailure,
34
+ createMask, drain, escapeNote, failureText, idLabel, settleNote, sshConfigDir, spawnSession, statusLine, unlinkAskpass,
35
+ waitSettled, writeAskpassWrapper,
36
36
  } from "./ssh-transport.mjs"
37
37
  import { askCredential, deleteEntry, hostKey, resolveSecret, saveEntry, touchEntry, vaultAvailable } from "./ssh-vault.mjs"
38
38
 
@@ -232,10 +232,11 @@ export async function connectSsh(parent, ctx, { host, user, port, label, promptP
232
232
  entry.askpassFile = writeAskpassWrapper(id)
233
233
  entry.logStream = createWriteStream(entry.logPath, { flags: "a" })
234
234
  entry.logStream.on("error", () => { /* 尽力面 */ })
235
- /** 沉降等待(探连 ∥ 带密会话同径):返回 reason + 已等时长。 */
235
+ /** 沉降等待(探连 ∥ 带密会话同径):返回 reason + 已等时长。首屏 = `SSH_CONNECT_SETTLE_MS`(§6.22 ③
236
+ * 「适用范围」:60 s 只管 `send` / `read` / `secret_input`);`settleOnSilence` = 首屏沿用静默降级。 */
236
237
  const settle = async () => {
237
238
  const t0 = Date.now()
238
- const reason = await waitSettled(entry, { signal: ctx?.signal ?? null })
239
+ const reason = await waitSettled(entry, { timeoutMs: SSH_CONNECT_SETTLE_MS, settleOnSilence: true, signal: ctx?.signal ?? null })
239
240
  return { reason, waitedMs: Date.now() - t0 }
240
241
  }
241
242
  /** 起跑(探连 ∥ 带密会话同径;`-i` 两径同带——追加候选身份,不夺既有尝试序列)。
@@ -258,106 +259,48 @@ export async function connectSsh(parent, ctx, { host, user, port, label, promptP
258
259
  userFromRecord ? `user "${userFromRecord}" came from the local ssh-hosts record` : "",
259
260
  ...extra,
260
261
  dropped ? "in-memory buffer overflowed — full output in the log" : "",
261
- ].filter(Boolean)
262
- return { text: `${statusLine(entry)}\n${bodyText(capText(text, SSH_RETURN_CAP, entry))}\n${notes.join("; ")}` }
262
+ escapeNote(entry), // 半条序列收场注记(§6.22 ③ flush②)——报告一次即清零
263
+ ].filter(Boolean).map((s) => s.replace(/^\n— /u, ""))
264
+ return { text: `${statusLine(entry)}\n${bodyText(capWindow(entry, text, SSH_RETURN_CAP))}\n${notes.join("; ")}` }
263
265
  }
264
- /** 认证类失败分类(spawn 错误 ∥ 输出判据——两径同式)。 */
265
- const classify = () => (entry.spawnError
266
- ? { kind: "spawn", message: `ssh client not available (${entry.spawnError}) — install system OpenSSH or check PATH` }
267
- : classifyFailure(entry.buf))
268
- try {
269
- assertPoolKeyFree(pool, id, "ssh")
270
- pool.set(String(id), entry)
271
- spawn(effectiveUser, null) // 探连:全会话形 + NumberOfPasswordPrompts=0(不读保存件——铁序)
266
+ /** 一次尝试(探连 ∥ 带密会话同径):起跑 + 沉降 + 分类 ⇒ 归一判定(`ok` 假时 `failure` = 可读句)。
267
+ * `asUser` 缺省 = 本次有效 user(凭据窗可改);遮蔽先注册后写入(回显面零泄)。 */
268
+ const attempt = async (secret = null, asUser = effectiveUser) => {
269
+ entry.user = asUser ?? null
270
+ if (secret != null) entry.mask.add(secret)
271
+ spawn(entry.user, secret)
272
272
  let { reason, waitedMs } = await settle()
273
273
  // 「已就绪」判据要求进程尚在(静默窗与退出同刻的竞争面——升格一条死连接不成立)。
274
274
  if ((reason === "prompt" || reason === "silence") && entry.exitInfo) reason = "exited"
275
- if (reason === "aborted") {
276
- hardClose(entry, "closed", "consumed")
277
- return { error: `ssh connect interrupted before the session was ready (${entry.host})` }
278
- }
279
- if (reason === "timeout") {
280
- hardClose(entry, "closed", "consumed")
281
- return { error: `ssh connect did not settle within ${SSH_TIMEOUT_MS}ms (${entry.host}) — the connection is closed; retry or increase the wait` }
282
- }
283
- let auth = "key"
284
- const flowNotes = []
285
- if (reason === "exited") {
286
- const cls = classify()
287
- if (!cls || cls.kind !== "auth") {
288
- const text = failureText(entry, cls)
289
- hardClose(entry, "closed", "connect-failed") // 杀树收尾(finalize 只出池——活子进程会成无句柄悬挂)
290
- return { error: text }
291
- }
292
- // 认证类失败 ⇒ **先读保存件**(⑪;有效 user 判定序缺 ⇒ 零消费零删除——直接落窗)。
293
- let saved = null
294
- let failNote = ""
295
- if (effectiveUser) {
296
- const got = await resolveSecret(host, port, effectiveUser)
297
- if (got.state === "ok") saved = got
298
- else if (got.state === "damaged") failNote = "the saved-credential store is damaged — it was left untouched"
299
- else if (got.state === "undecryptable") failNote = "the saved credential could not be decrypted — the entry was kept"
300
- else if (got.state === "unavailable") failNote = "saved credentials are not available on this platform"
301
- // missing ⇒ 静默(正常首连态)
302
- }
303
- if (saved) {
304
- entry.user = effectiveUser
305
- entry.mask.add(saved.value) // 遮蔽先注册后写入(回显面零泄)
306
- spawn(entry.user, saved.value) // 带密会话(PP=1)——命中保存件 ⇒ 零窗
307
- ;({ reason, waitedMs } = await settle())
308
- if ((reason === "prompt" || reason === "silence") && entry.exitInfo) reason = "exited"
309
- if (reason === "prompt" || reason === "silence") {
310
- touchEntry(host, port) // lastUsedAt = 复用成功时更新(写失败 = 增益面静默)
311
- return promote(reason, waitedMs, { auth: "password", extra: ["saved credential used (no credential window)"] })
312
- }
313
- const clsSaved = classify()
314
- // 只有**本次进程正常退出且为认证类**才算「服务端拒绝」;超时 / 中断 / 不可达 ⇒ 条目保留、硬停。
315
- if (reason !== "exited" || clsSaved?.kind !== "auth") {
316
- const text = failureText(entry, clsSaved ?? { message: "authentication rejected" }, " — the session was not established")
317
- hardClose(entry, "closed", "connect-failed")
318
- return { error: text }
319
- }
320
- // 条目被服务端拒 ⇒ 删该条目(拒绝即值已失效——避免每次重试旧值)+ 回落窗;删失败时注记如实。
321
- const del = deleteEntry(host, port)
322
- failNote = del.ok
323
- ? "the saved credential was rejected by the server — the entry was deleted"
324
- : "the saved credential was rejected by the server — the store could not be updated (the entry may still be there)"
325
- }
326
- // 凭据窗(值只走回调返回路 + 子进程环境——NS4:零入参 ∥ 零入结果 ∥ 零落盘)。
327
- const input = await askCredential(ctx, { host, user: effectiveUser, port, sessionId: id, offerSave: vaultAvailable() })
328
- if (!input) {
329
- hardClose(entry, "closed", "consumed")
330
- return { error: `ssh connect to ${entry.host} cancelled — no credential was provided (no connection was attempted with one)${failNote ? ` (${failNote}; the credential window was shown)` : ""}` }
331
- }
332
- if (!String(input.password ?? "").length) {
333
- hardClose(entry, "closed", "consumed")
334
- return { error: "ssh connect cancelled — an empty password is never submitted (submit a password or cancel the window)" }
335
- }
336
- entry.user = input.user || effectiveUser || null
337
- entry.mask.add(input.password) // 遮蔽先注册后写入(回显面零泄)
338
- spawn(entry.user, input.password) // 单次带密会话(PP=1)
339
- ;({ reason, waitedMs } = await settle())
340
- if ((reason === "prompt" || reason === "silence") && entry.exitInfo) reason = "exited"
341
- if (reason !== "prompt" && reason !== "silence") {
342
- const cls2 = entry.spawnError ? { message: "ssh client not available" } : classifyFailure(entry.buf)
343
- const text = failureText(entry, cls2 ?? { message: "authentication rejected" }, " — the session was not established")
344
- // 带密会话未就绪(aborted ∥ timeout)时子进程可能仍活——必走杀树径(否则出池后无句柄可收)。
345
- hardClose(entry, "closed", "connect-failed")
346
- return { error: text }
347
- }
348
- // 认证成功后才写(opt-in——严格布尔;写失败不影响连接:增益面语义)
349
- if (input.save === true && entry.user) {
350
- const savedRes = await saveEntry(host, port, { user: entry.user, value: input.password })
351
- flowNotes.push(savedRes.ok
352
- ? "the credential was saved for this host (encrypted with this Windows user account)"
353
- : "the credential could not be saved (the connection is unaffected)")
354
- } else if (input.save === true) {
355
- flowNotes.push("the credential was not saved (no login user was given for this host)")
275
+ if (reason === "prompt" || reason === "silence") return { ok: true, reason, waitedMs }
276
+ const cls = entry.spawnError
277
+ ? { kind: "spawn", message: `ssh client not available (${entry.spawnError}) — install system OpenSSH or check PATH` }
278
+ : classifyFailure(entry.buf)
279
+ const failure = secret == null
280
+ ? failureText(entry, cls)
281
+ : failureText(entry, cls ?? { message: "authentication rejected" }, " — the session was not established")
282
+ return { ok: false, reason, waitedMs, auth: reason === "exited" && cls?.kind === "auth", failure }
283
+ }
284
+ try {
285
+ assertPoolKeyFree(pool, id, "ssh")
286
+ pool.set(String(id), entry)
287
+ // 凭据判定单源(D-TO25):探连 → 密文库 → 凭据窗。本档只提供「一次尝试」,顺序归 resolveSessionSecret。
288
+ const out = await resolveSessionSecret({
289
+ ctx, host, port, user: effectiveUser, sessionId: id, offerSave: vaultAvailable(), attempt,
290
+ })
291
+ if (out.state !== "ok") {
292
+ const r = out.r ?? {}
293
+ const stopped = out.state === "cancel" || out.state === "empty" || (out.phase === "probe" && (r.reason === "aborted" || r.reason === "timeout"))
294
+ hardClose(entry, "closed", stopped ? "consumed" : "connect-failed")
295
+ if (out.state === "cancel") {
296
+ return { error: `ssh connect to ${entry.host} cancelled — no credential was provided (no connection was attempted with one)${out.failNote ? ` (${out.failNote}; the credential window was shown)` : ""}` }
356
297
  }
357
- if (failNote) flowNotes.unshift(`${failNote}; the credential window was shown`)
358
- auth = "password"
298
+ if (out.state === "empty") return { error: "ssh connect cancelled — an empty password is never submitted (submit a password or cancel the window)" }
299
+ if (r.reason === "aborted") return { error: `ssh connect interrupted before the session was ready (${entry.host})` }
300
+ if (r.reason === "timeout") return { error: `ssh connect did not settle within ${SSH_CONNECT_SETTLE_MS}ms (${entry.host}) — the connection is closed; retry or increase the wait${escapeNote(entry)}` }
301
+ return { error: r.failure }
359
302
  }
360
- return promote(reason, waitedMs, { auth, extra: flowNotes })
303
+ return promote(out.r.reason, out.r.waitedMs, { auth: out.source === "key" ? "key" : "password", extra: out.notes })
361
304
  } catch (e) {
362
305
  hardClose(entry, "closed", "connect-failed") // 异常径同走杀树(子进程可能仍在飞)
363
306
  return { error: e?.noUi ? `Error: ${e.message}` : `ssh connect failed: ${e?.message ?? String(e)}` }
@@ -366,8 +309,8 @@ export async function connectSsh(parent, ctx, { host, user, port, label, promptP
366
309
  }
367
310
  }
368
311
 
369
- /** 缓冲溢出注记(三动作同式——丢弃面显式化;全量恒在 log)。 */
370
- const droppedNote = (dropped) => (dropped ? "\n— in-memory buffer overflowed — full output in the log" : "")
312
+ /** 丢弃面注记(三动作同式——缓冲溢出 ∥ 半条序列收场;全量恒在 log)。 */
313
+ const droppedNote = (dropped, entry) => `${dropped ? "\n— in-memory buffer overflowed — full output in the log" : ""}${entry ? escapeNote(entry) : ""}`
371
314
 
372
315
  /** `send`(§6.22 动作表):不结尾换行 ⇒ 补 `\r`(设备 Enter 语义);沉降到点返回该轮输出。 */
373
316
  export async function sendSsh(parent, ctx, { id, data, settle = true, timeoutMs } = {}) {
@@ -389,11 +332,11 @@ export async function sendSsh(parent, ctx, { id, data, settle = true, timeoutMs
389
332
  entry._notify = null
390
333
  const { text, dropped } = drain(entry)
391
334
  return {
392
- text: `${statusLine(entry)}\n${bodyText(capText(text, SSH_RETURN_CAP, entry))}\n— ${settleNote(entry, reason, Date.now() - t0)}${droppedNote(dropped)}`,
335
+ text: `${statusLine(entry)}\n${bodyText(capWindow(entry, text, SSH_RETURN_CAP))}\n— ${settleNote(entry, reason, Date.now() - t0)}${droppedNote(dropped, entry)}`,
393
336
  }
394
337
  }
395
338
 
396
- /** `read`:上次读后新增输出(存量即返;无则等至静默/超时——§6.22 ③/⑥)。 */
339
+ /** `read`:上次读后新增输出(**存量即返**、结论 = 缓冲;无存量才等到门① ∥ 门② ∥ 硬超时——§6.22 ③/⑥)。 */
397
340
  export async function readSsh(parent, ctx, { id, timeoutMs, maxChars } = {}) {
398
341
  const entry = findEntry(parent, id)
399
342
  if (!entry) return { error: missingEntry(parent, id) }
@@ -407,11 +350,11 @@ export async function readSsh(parent, ctx, { id, timeoutMs, maxChars } = {}) {
407
350
  const reason = await waitSettled(entry, { timeoutMs, signal: ctx?.signal ?? null })
408
351
  entry._notify = null
409
352
  const { text, dropped } = drain(entry)
410
- const body = text ? bodyText(capText(text, cap, entry)) : "(no new output)"
411
- return { text: `${statusLine(entry)}\n${body}\n— ${settleNote(entry, reason, Date.now() - t0)}${droppedNote(dropped)}` }
353
+ const body = text ? bodyText(capWindow(entry, text, cap)) : "(no new output)"
354
+ return { text: `${statusLine(entry)}\n${body}\n— ${settleNote(entry, reason, Date.now() - t0)}${droppedNote(dropped, entry)}` }
412
355
  }
413
356
  const { text, dropped } = drain(entry)
414
- return { text: `${statusLine(entry)}\n${bodyText(capText(text, cap, entry))}\n— buffered output since the last read${droppedNote(dropped)}` }
357
+ return { text: `${statusLine(entry)}\n${bodyText(capWindow(entry, text, cap))}\n— buffered output since the last read${droppedNote(dropped, entry)}` }
415
358
  }
416
359
 
417
360
  /** `secret_input`(§6.22 动作表 + ⑦):凭据窗 → 掩码写入 + `\r`;值永不出现于返回。 */
@@ -441,7 +384,7 @@ export async function secretInputSsh(parent, ctx, { id, label } = {}) {
441
384
  entry._notify = null
442
385
  const { text, dropped } = drain(entry)
443
386
  const tag = label ? ` (${escapeLite(label)})` : ""
444
- return { text: `${statusLine(entry)}\nsecret written${tag} — value never echoed\n${bodyText(capText(text, SSH_RETURN_CAP, entry))}\n— ${settleNote(entry, reason, Date.now() - t0)}${droppedNote(dropped)}` }
387
+ return { text: `${statusLine(entry)}\nsecret written${tag} — value never echoed\n${bodyText(capWindow(entry, text, SSH_RETURN_CAP))}\n— ${settleNote(entry, reason, Date.now() - t0)}${droppedNote(dropped, entry)}` }
445
388
  }
446
389
 
447
390
  /** `close`:stdin 结束 → 1.5 s 宽限 → 杀树;返回末段输出 + 关闭确认。 */
@@ -452,7 +395,7 @@ export async function closeSsh(parent, ctx, { id } = {}) {
452
395
  if (entry.state !== "ready") {
453
396
  const was = entry.state
454
397
  finalize(entry, { state: "closed", status: "consumed" })
455
- return { text: `${statusLine(entry)}\n${bodyText(capText(text, SSH_RETURN_CAP, entry))}\n— closed (it was already ${was})` }
398
+ return { text: `${statusLine(entry)}\n${bodyText(capWindow(entry, text, SSH_RETURN_CAP))}\n— closed (it was already ${was})${droppedNote(dropped, entry)}` }
456
399
  }
457
400
  entry.closing = true
458
401
  try { entry.child.stdin.end() } catch { /* 进程可能已退出——宽限后杀树 */ }
@@ -462,7 +405,7 @@ export async function closeSsh(parent, ctx, { id } = {}) {
462
405
  })
463
406
  if (!exited) killProcessTree(entry.child)
464
407
  finalize(entry, { state: "closed", status: "consumed" })
465
- return { text: `${statusLine(entry)}\n${bodyText(capText(text, SSH_RETURN_CAP, entry))}\n— closed${exited ? "" : " (the remote did not exit within 1.5s — the process tree was killed)"}${droppedNote(dropped)}` }
408
+ return { text: `${statusLine(entry)}\n${bodyText(capWindow(entry, text, SSH_RETURN_CAP))}\n— closed${exited ? "" : " (the remote did not exit within 1.5s — the process tree was killed)"}${droppedNote(dropped, entry)}` }
466
409
  }
467
410
 
468
411
  /** `list`:在活会话清单(id / host / user / 状态 / 空闲秒)——上下文压缩后的恢复路。 */
@@ -482,5 +425,71 @@ export { SSH_SETTLE_MS, SSH_TIMEOUT_MS, SSH_RETURN_CAP }
482
425
  export { _setSshBinaryForTest, _setSshConfigDirForTest } from "./ssh-transport.mjs"
483
426
 
484
427
  // 保存凭据管理面(§6.22 ⑫):`credentials` / `forget` 实体 = `ssh-vault.mjs`(核单点——本档只转口;
485
- // 拆档由 = 机制档触 500 顾问线,§6.22 落点表候选拆分)。
428
+ // 拆档由 = 当年机制档已过 500 行,§6.22 落点表候选拆分)。
486
429
  export { credentialsSsh, forgetSsh } from "./ssh-vault.mjs"
430
+ // ─── 凭据判定单源(D-TO25:`connect` ∥ 传输面两处共用)─────────────────────────
431
+
432
+ /**
433
+ * 凭据判定(§6.22 ⑩ / ⑪ + 裁定 A 预探路)——`connect` 与 `put` / `get` 两处共用的**顺序**:
434
+ * 探连(密钥 ∥ agent)→ 密文库 → 凭据窗。保存件**恒不先于探连**(S6 / N6 / B7——密钥可用则零读取)。
435
+ * `attempt(secret, user)` = 调方的起跑 + 沉降 + 分类,回 `{ ok:true, … }` 或 `{ ok:false, auth, failure }`
436
+ * (`auth` = 服务端拒绝认证 ⇒ 才继续往下一条来源;`failure` = 该来源失败的可读句)。
437
+ * @returns {Promise<{state:"ok", secret:string|null, user:string|null, source:"key"|"vault"|"window", r:Object, notes:string[]}
438
+ * | {state:"fail", phase:"probe"|"vault"|"window", r:Object} | {state:"cancel"|"empty", failNote?:string}>}
439
+ */
440
+ export async function resolveSessionSecret({ ctx, host, port, user, sessionId, offerSave = false, attempt }) {
441
+ const notes = []
442
+ let r = await attempt(null)
443
+ if (r.ok) return { state: "ok", secret: null, user: user ?? null, source: "key", r, notes }
444
+ if (!r.auth) return { state: "fail", phase: "probe", r }
445
+ // 认证类失败 ⇒ **先读保存件**(⑪;有效 user 缺 ⇒ 零消费零删除——直接落窗)。
446
+ let failNote = ""
447
+ if (user) {
448
+ const got = await resolveSecret(host, port, user)
449
+ if (got.state === "ok") {
450
+ r = await attempt(got.value, user)
451
+ if (r.ok) {
452
+ touchEntry(host, port) // lastUsedAt = 复用成功时更新(写失败 = 增益面静默)
453
+ return { state: "ok", secret: got.value, user, source: "vault", r, notes: ["saved credential used (no credential window)"] }
454
+ }
455
+ if (!r.auth) return { state: "fail", phase: "vault", r }
456
+ // 条目被服务端拒 ⇒ 删该条目(拒绝即值已失效——避免每次重试旧值)+ 回落窗;删失败时注记如实。
457
+ const del = deleteEntry(host, port)
458
+ failNote = del.ok
459
+ ? "the saved credential was rejected by the server — the entry was deleted"
460
+ : "the saved credential was rejected by the server — the store could not be updated (the entry may still be there)"
461
+ } else if (got.state === "damaged") failNote = "the saved-credential store is damaged — it was left untouched"
462
+ else if (got.state === "undecryptable") failNote = "the saved credential could not be decrypted — the entry was kept"
463
+ else if (got.state === "unavailable") failNote = "saved credentials are not available on this platform"
464
+ // missing ⇒ 静默(正常首连态)
465
+ }
466
+ // 凭据窗(值只走回调返回路 + 子进程环境——NS4:零入参 ∥ 零入结果 ∥ 零落盘)。
467
+ const input = await askCredential(ctx, { host, user, port, sessionId, offerSave })
468
+ if (!input) return { state: "cancel", failNote }
469
+ if (!String(input.password ?? "").length) return { state: "empty" }
470
+ const asUser = input.user || user || null
471
+ r = await attempt(input.password, asUser)
472
+ if (!r.ok) return { state: "fail", phase: "window", r }
473
+ // 认证成功后才写(opt-in——严格布尔;写失败不影响连接:增益面语义)
474
+ if (input.save === true && asUser) {
475
+ const saved = await saveEntry(host, port, { user: asUser, value: input.password })
476
+ notes.push(saved.ok
477
+ ? "the credential was saved for this host (encrypted with this Windows user account)"
478
+ : "the credential could not be saved (the connection is unaffected)")
479
+ } else if (input.save === true) {
480
+ notes.push("the credential was not saved (no login user was given for this host)")
481
+ }
482
+ if (failNote) notes.unshift(`${failNote}; the credential window was shown`)
483
+ return { state: "ok", secret: input.password, user: asUser, source: "window", r, notes }
484
+ }
485
+
486
+ /** 传输面取会话记录(§6.22 ⑬ ②:主机 / 用户 / 端口 / 身份面全取会话记录值——S10「不另填主机 / 凭据」)。
487
+ * 池查询本档单点(传输件不碰池);身份面取 ⑨ 记录的 `identityFile`(与 `connect` 同一判定序)。
488
+ * `header` = 回执首行的会话冠行(⑬ ③)——形单源仍是 `ssh-transport.mjs` 的 `statusLine`,本档只取一次快照。 */
489
+ export function sessionForTransfer(parent, id) {
490
+ const entry = findEntry(parent, id)
491
+ if (!entry) return { error: missingEntry(parent, id) }
492
+ const rec = lookupHostRecord(entry.host, entry.port)
493
+ const header = statusLine(entry)
494
+ return { host: entry.host, user: entry.user ?? null, port: entry.port ?? null, identityFile: rec?.identityFile ?? null, header }
495
+ }