@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
@@ -0,0 +1,274 @@
1
+ /**
2
+ * agent/turn-task-state.mjs — 本轮运行记账与任务状态取形(设计 = `docs/core/design/CONTEXT-COMPACTION.md` §1.1;
3
+ * 台账 #2395 落的「一轮三条消息」里,任务状态那一条在本档成形。本批从 `thincoder-core/agent/turn-projection.mjs` 拆出)。
4
+ *
5
+ * 本档四块:
6
+ * - 账本 `createTurnLedger` ∥ `noteTurnToolFacts` ∥ `noteTurnRunError`:本轮运行记账(工具调用、验证命令与结果摘要);
7
+ * - 事实 `buildTurnTaskState`:状态由记账与真实落盘面组装,不由模型最终回复反推;
8
+ * - 状态串 `taskStateText` ∥ `TASK_STATE_MARK`:状态对象 → 线上文本;
9
+ * - 成败取形 `VERIFICATION_TOOLS` ∥ `verdictOf` ∥ `parseArgs` ∥ `resultSummary`:结果里的真实退出码与单行摘要。
10
+ *
11
+ * 与 `turn-projection.mjs` 的分工:那边是折叠 ∥ 投影 ∥ 恢复三面同尺(同一份投影函数),本档是记账与取形。
12
+ * 为什么要拆:四块同住一档时内容行越过 500 的档位线(`docs/core/standards/CODE-TIER.md` §3),而「一轮 → 三条消息」
13
+ * 的投影判据仍只在 `turn-projection.mjs` 一处——拆档只动文件归属,不动那条判据。
14
+ * 依赖方向单向:`turn-projection.mjs` → 本档;本档不 import 投影面(否则两档成环,拆了等于没拆)。
15
+ * 对外契约:搬走的符号在 `turn-projection.mjs` 原路径 re-export,既有 import 一字不改。
16
+ *
17
+ * 纪律:纯函数面零 IO、零抛、零全局态;不改写传入的账本对象与工具参数对象。
18
+ */
19
+ import { isAbsolute, relative } from "node:path"
20
+ import { safeSliceUTF16 } from "../text-budget.mjs"
21
+
22
+ /** 任务状态消息的机器标记(标准 `role:"user"` + 文本行;Provider 面零未知字段)。 */
23
+ export const TASK_STATE_MARK = "[Task state]"
24
+ /** 摘要 ∥ 命令 ∥ 结果摘要的单行上限(用户请求与最终回复不在此列,原样入库)。 */
25
+ const SUMMARY_CAP = 240
26
+ const COMMAND_CAP = 200
27
+ const MAX_VERIFICATION = 6
28
+ const MAX_CHANGED_FILES = 40
29
+ const MAX_EVIDENCE = 8
30
+ const MAX_REMAINING = 8
31
+
32
+ export const str = (v) => (typeof v === "string" ? v : "")
33
+
34
+ /** 单行摘要(折叠空白——用于命令 ∥ 结果摘要)。 */
35
+ export function line(v, limit = SUMMARY_CAP) {
36
+ const t = str(v).replace(/\s+/g, " ").trim()
37
+ return t.length <= limit ? t : `${safeSliceUTF16(t, limit)}…`
38
+ }
39
+
40
+ /** 本轮验证面工具(CONTEXT-COMPACTION §1.1「verification 面只收真正执行过命令的工具」)。
41
+ * 成员与「命令取形」在**这一处**定义:再加一份名单就是第二条判据,加成员时不会跟。
42
+ * `verify` 不在内:它不执行命令,只转述模型自述,不得冒充真实执行结果。 */
43
+ const VERIFICATION_TOOLS = {
44
+ /** bash = 命令原文。 */
45
+ bash: (args) => line(args.command, COMMAND_CAP),
46
+ /** execute = 脚本 / 内联代码首行。 */
47
+ execute: (args) => {
48
+ const parts = []
49
+ if (str(args.scriptFile)) parts.push(`node ${args.scriptFile}`)
50
+ if (str(args.code)) parts.push(str(args.code).split("\n")[0])
51
+ return line(parts.join(" · ") || "(inline execute)", COMMAND_CAP)
52
+ },
53
+ }
54
+
55
+ /** 长文本不再截断:用户请求与最终回复原样入库(容量靠轮投影控制,不靠丢失原文)。 */
56
+ export function capText(v) {
57
+ return str(v)
58
+ }
59
+
60
+ function parseArgs(raw) {
61
+ if (raw && typeof raw === "object") return raw
62
+ try {
63
+ const v = JSON.parse(str(raw) || "{}")
64
+ return v && typeof v === "object" ? v : {}
65
+ } catch {
66
+ return {}
67
+ }
68
+ }
69
+
70
+ /** 结果摘要(首段 + 上限:「通过/失败/跳过及结果摘要」)。 */
71
+ function resultSummary(result) {
72
+ const raw = str(result)
73
+ if (!raw) return ""
74
+ return line(raw)
75
+ }
76
+
77
+ /**
78
+ * 验证结论:验证面成员都是会执行命令的工具,成败先读**结果里的真实退出码**——一条 `(exit code 1)` 的命令
79
+ * 仍然「工具执行成功」,工具调用本身没错,是命令失败了;被杀的进程一律算失败。
80
+ * 结果里没有退出码(输出被截断 / 不是该形)才回落到工具调用的成败。
81
+ */
82
+ function verdictOf(result, ok) {
83
+ const text = str(result)
84
+ const exit = /\(exit code (-?\d+)\)/.exec(text)
85
+ if (exit) return Number(exit[1]) === 0
86
+ if (/\(killed: /.test(text)) return false
87
+ return ok === true
88
+ }
89
+
90
+ // ────────────────────────────── 账本(运行记账) ──────────────────────────────
91
+
92
+ /**
93
+ * 建立本轮事实账本。`autoTurn`(含上行 / 定时唤醒轮)不伪造用户请求——设计 §1.1:系统轮没有
94
+ * 用户请求,机读线不得凭空多出一条。
95
+ * @param {{ input?: unknown, autoTurn?: boolean, goal?: object|null }} spec
96
+ */
97
+ export function createTurnLedger({ input, autoTurn = false, goal = null } = {}) {
98
+ const request = capText(input) || null
99
+ return {
100
+ userRequest: autoTurn === true ? null : request,
101
+ autoTurn: autoTurn === true,
102
+ objective: request || capText(goal?.objective) || null,
103
+ verification: [],
104
+ toolCalls: 0,
105
+ /** 本轮内被观察到的异常原因(续跑链保留;异常轮不登记,故只作 blockedBy 的次选来源)。 */
106
+ error: null,
107
+ }
108
+ }
109
+
110
+ /**
111
+ * 记一条工具事实(`recordToolResults` 的唯一调用点)。只记**运行记账**面:
112
+ * 验证类工具的调用参数与结果摘要——变更文件面取 `agent._touchedFiles`(真实落盘归集,
113
+ * 含子代理 `mergeChildMutations` 合入项),不在此另立第二份清单。
114
+ */
115
+ export function noteTurnToolFacts(ledger, { toolCall, result, ok } = {}) {
116
+ if (!ledger || typeof ledger !== "object") return ledger
117
+ ledger.toolCalls = (ledger.toolCalls ?? 0) + 1
118
+ const name = str(toolCall?.name)
119
+ if (!Object.hasOwn(VERIFICATION_TOOLS, name)) return ledger
120
+ ledger.verification.push({
121
+ tool: name,
122
+ command: VERIFICATION_TOOLS[name](parseArgs(toolCall?.arguments)),
123
+ ok: verdictOf(result, ok),
124
+ summary: resultSummary(result),
125
+ })
126
+ if (ledger.verification.length > MAX_VERIFICATION) ledger.verification.shift()
127
+ return ledger
128
+ }
129
+
130
+ /** 异常面记账(`runAgent` 的 catch):本轮异常原因留给同一账本(续跑沿用)。 */
131
+ export function noteTurnRunError(ledger, error) {
132
+ if (!ledger || typeof ledger !== "object") return ledger
133
+ const message = line(error?.message ?? error, SUMMARY_CAP)
134
+ if (message) ledger.error = message
135
+ return ledger
136
+ }
137
+
138
+ // ────────────────────────────── 事实(taskState) ──────────────────────────────
139
+
140
+ /** 文档面:`_touchedFiles` 里落在调用方声明的文档根下的那些(设计 §1.1 表行「同一落盘面按调用方声明的
141
+ * 文档根过滤;只给位置,不摘录理由」)。`null` = 未声明文档根 ⇒ 该字段不出现——空数组与「本轮没改文档」
142
+ * 同形,读的人分不出是没改还是没声明根,所以缺省不写字段。文档根本身由调用方解析(本档零 IO,不自读 manifest)。 */
143
+ function changedDocsOf(touchedFiles, docRoots, cwd) {
144
+ // 分隔符归一再比(`_touchedFiles` 是平台原生绝对路径,manifest 的根也经 `resolve` 归一);win32 再折大小写
145
+ // ——同族判据同口径(`agent/write-face.mjs` 的 `faceKey`、`doc-check/existence.mjs` 的 `pathKey`):
146
+ // 磁盘不区分大小写,拍定字符串区分会静默漏项。
147
+ const norm = (p) => {
148
+ const s = p.split("\\").join("/")
149
+ return process.platform === "win32" ? s.toLowerCase() : s
150
+ }
151
+ const roots = (Array.isArray(docRoots) ? docRoots : [])
152
+ .filter((p) => typeof p === "string" && p)
153
+ .map((p) => norm(p).replace(/\/+$/, ""))
154
+ if (roots.length === 0) return null
155
+ const out = []
156
+ for (const p of Array.isArray(touchedFiles) ? touchedFiles : []) {
157
+ if (typeof p !== "string" || !p) continue
158
+ const shown = norm(p)
159
+ if (!roots.some((root) => shown === root || shown.startsWith(`${root}/`))) continue
160
+ const rel = changedPathsOf([p], cwd)[0]
161
+ if (rel && !out.includes(rel)) out.push(rel)
162
+ if (out.length >= MAX_CHANGED_FILES) break
163
+ }
164
+ return out
165
+ }
166
+
167
+ /** 真实落盘面:绝对路径 → cwd 相对(分隔符归一 `/`);cwd 外保留绝对路径。 */
168
+ function changedPathsOf(touchedFiles, cwd) {
169
+ const out = []
170
+ for (const p of Array.isArray(touchedFiles) ? touchedFiles : []) {
171
+ if (typeof p !== "string" || !p) continue
172
+ const shown = cwd ? relative(cwd, p) : p
173
+ const value = (shown && !shown.startsWith("..") && !isAbsolute(shown)) ? shown.split("\\").join("/") : p.split("\\").join("/")
174
+ if (!out.includes(value)) out.push(value)
175
+ if (out.length >= MAX_CHANGED_FILES) break
176
+ }
177
+ return out
178
+ }
179
+
180
+ function remainingOf(tasks, goal) {
181
+ const out = []
182
+ for (const t of Array.isArray(tasks) ? tasks : []) {
183
+ const status = str(t?.status) || "pending"
184
+ if (status === "done") continue
185
+ const title = line(t?.title ?? t?.content ?? t, 120)
186
+ if (title) out.push(`${title} (${status})`)
187
+ if (out.length >= MAX_REMAINING) break
188
+ }
189
+ if (goal && goal.status === "active" && str(goal.objective)) {
190
+ const objective = line(goal.objective, 120)
191
+ if (objective && !out.includes(objective)) out.push(`goal (active): ${objective}`)
192
+ }
193
+ return out.slice(0, MAX_REMAINING)
194
+ }
195
+
196
+ function blockedOf(goal, ledger) {
197
+ if (goal && goal.status === "blocked") {
198
+ const reason = line(goal._blockTally?.reason ?? goal.blockedReason ?? "", SUMMARY_CAP)
199
+ return reason ? `goal blocked: ${reason}` : "goal marked blocked"
200
+ }
201
+ // 异常轮不登记(设计 §2)——账本里的异常只在同一链后续正常收尾时充作阻塞来源。
202
+ return ledger?.error ? `run error: ${ledger.error}` : null
203
+ }
204
+
205
+ function evidenceOf({ slotFile, batchDoc, logsPath, changedFiles }) {
206
+ const out = []
207
+ const push = (v) => {
208
+ const value = str(v)
209
+ if (value && !out.includes(value) && out.length < MAX_EVIDENCE) out.push(value)
210
+ }
211
+ push(slotFile)
212
+ push(batchDoc)
213
+ push(logsPath)
214
+ for (const f of changedFiles) push(f)
215
+ return out
216
+ }
217
+
218
+ /**
219
+ * 组装本轮任务状态(设计 §1.1 表逐字段;事实来自运行记账,不由最终回复反推)。
220
+ * 无工具活动的简单问答 ⇒ `null`(设计:「没有工具活动的简单问答允许 taskState 为空」)——
221
+ * 但真的折掉了东西时不空:`folded` 那一行是给人看的交代,没有别的面装它。
222
+ *
223
+ * @param {object} ledger — `createTurnLedger` 产物
224
+ * @param {object} facts — `{ status, goal, tasks, touchedFiles, docRoots, cwd, slotFile, batchDoc, logsPath, folded }`
225
+ * @returns {object|null}
226
+ */
227
+ export function buildTurnTaskState(ledger, {
228
+ status = "completed", goal = null, tasks = [], touchedFiles = [], docRoots = [], cwd = null,
229
+ slotFile = null, batchDoc = null, logsPath = null, folded = null,
230
+ } = {}) {
231
+ if (!ledger || typeof ledger !== "object") return null
232
+ const changedFiles = changedPathsOf(touchedFiles, cwd)
233
+ const toolCalls = ledger.toolCalls ?? 0
234
+ const foldedHint = folded && typeof folded === "object" ? folded : null
235
+ if (toolCalls === 0 && changedFiles.length === 0 && (ledger.verification?.length ?? 0) === 0 && !foldedHint) return null
236
+ const changedDocs = changedDocsOf(touchedFiles, docRoots, cwd)
237
+ const state = {
238
+ objective: ledger.objective ? ledger.objective : null,
239
+ status,
240
+ changedFiles,
241
+ verification: (ledger.verification ?? []).map((v) => ({ ...v })),
242
+ evidence: evidenceOf({ slotFile, batchDoc, logsPath, changedFiles }),
243
+ remaining: remainingOf(tasks, goal),
244
+ blockedBy: blockedOf(goal, ledger),
245
+ }
246
+ if (changedDocs) state.changedDocs = changedDocs
247
+ // `folded`(§1.1 表末行 ∥ §1.2):本回合真的离开机读线的工具过程量——阈值门在取形处(`turn-projection.mjs`)
248
+ if (foldedHint) state.folded = foldedHint
249
+ return state
250
+ }
251
+
252
+ /** 任务状态的线上文本(标准 role/content 的 content 面;空状态 ⇒ `null` 不产消息)。 */
253
+ export function taskStateText(taskState) {
254
+ if (!taskState || typeof taskState !== "object") return null
255
+ const rows = []
256
+ if (taskState.objective) rows.push(`objective: ${taskState.objective}`)
257
+ if (taskState.status) rows.push(`status: ${taskState.status}`)
258
+ if (taskState.changedFiles?.length) rows.push(`changedFiles: ${taskState.changedFiles.join(", ")}`)
259
+ if (taskState.changedDocs?.length) rows.push(`changedDocs: ${taskState.changedDocs.join(", ")}`)
260
+ for (const v of taskState.verification ?? []) {
261
+ const verdict = v.ok ? "ok" : "failed"
262
+ rows.push(`verification: ${v.tool} \`${v.command}\` → ${verdict}${v.summary ? ` — ${v.summary}` : ""}`)
263
+ }
264
+ if (taskState.evidence?.length) rows.push(`evidence: ${taskState.evidence.join(" · ")}`)
265
+ if (taskState.remaining?.length) rows.push(`remaining: ${taskState.remaining.join("; ")}`)
266
+ if (taskState.blockedBy) rows.push(`blockedBy: ${taskState.blockedBy}`)
267
+ // 只报量,不指回查位置(§1.2:落盘只留 slim 后的前段,「全文可取」是一句兑现不了的话)
268
+ if (taskState.folded) {
269
+ const f = taskState.folded
270
+ rows.push(`folded: ${f.results} tool result(s) ~${f.tokens} tokens (${f.turns} turn(s), ${f.groups} call group(s))`)
271
+ }
272
+ if (rows.length === 0) return null
273
+ return `${TASK_STATE_MARK}\n${rows.join("\n")}`
274
+ }
@@ -0,0 +1,168 @@
1
+ /**
2
+ * agent/turn-tool-process.mjs — 工具过程保留族(设计 = `docs/core/design/CONTEXT-COMPACTION.md` §1.1 ∥ §1.2;
3
+ * 批次 = `docs/batches/2026-11-14-tool-output-retention.md`;台账 #2431)。五个常量 ∥ 九个函数:保留窗口与两道
4
+ * 预算、切片与整组移出、折叠提示的记账、窗口裁切的摘除、保留窗起点。
5
+ *
6
+ * 为什么单出一档:这一族与「折叠 ∥ 投影 ∥ 恢复」三面不同,同住 `turn-projection.mjs` 会把那档推过 500 内容行的
7
+ * 档位线(标准 `docs/core/standards/CODE-TIER.md` §2.1)。拆档只动文件归属,不动一条判据——五个常量值、九个函数体、
8
+ * 注释语义逐字照搬。先例 = `turn-task-state.mjs` 拆出时同形。
9
+ *
10
+ * 依赖方向单向:`turn-projection.mjs` → 本档。本档只依赖 `buildDualEndPreview`(`./offload.mjs`)与
11
+ * `estimateTokens`(`../token-window.mjs`),不 import 投影面——否则两档成环,拆了等于没拆。
12
+ *
13
+ * 对外契约:搬走的符号在 `turn-projection.mjs` 原路径 re-export,既有 import 一字不改(三个导入方 =
14
+ * `context.mjs` ∥ `context-degrade.mjs` ∥ `agent-tools/context.mjs`)。
15
+ */
16
+
17
+ // 工具段的单条缺口:双端预览复用 64K 面那一个构造器(`buildDualEndPreview`,本批给它加了必填 `budget`),
18
+ // 不另写一份切法——同一形状两份实现迟早分叉(§1.2)。
19
+ import { buildDualEndPreview } from "./offload.mjs"
20
+ // 预算与 `folded` 同一把尺:`estimateTokens` 是压缩面的计量尺(§1.2「预算用共享估算器,不另立尺」)。
21
+ import { estimateTokens } from "../token-window.mjs"
22
+
23
+ // ────────────────────── 保留窗与工具段预算(CONTEXT-COMPACTION.md §1.1 ∥ §1.2) ──────────────────────
24
+
25
+ /** 保留窗口 = 最近 2 轮(§1.1:常量,不是配置项——用户可调的是预算,这是保留边界)。 */
26
+ export const TOOL_PROCESS_WINDOW = 2
27
+ /** 单条工具内容的字符预算(§1.2):越限取双端——头 + 省略数注记 + 尾。 */
28
+ export const TOOL_PROCESS_MSG_CHARS = 4000
29
+ /** 单轮工具段的 token 预算(§1.2):越限从最旧调用组起整组移出。 */
30
+ export const TOOL_PROCESS_TURN_TOKENS = 8000
31
+ /** 折叠提示行的噪声门(§1.2):真的丢掉量低于它,`folded` 整行不出现。 */
32
+ export const FOLD_HINT_TOKENS = 1000
33
+ /** 段首移出说明的标记(§1.2 载体):`role: "user"` 不需要配对——`assistant` 文本会被 §6 的相邻归并吃掉,
34
+ * `tool` 会成为没有调用的孤儿结果、首个请求必 400。这一行给模型读,故不受 `FOLD_HINT_TOKENS` 门。 */
35
+ export const TOOL_PROCESS_DROP_MARK = "[Tool process trimmed]"
36
+
37
+ /** 一条调用组的起点:`assistant(tool_calls)`——整组进出机读线的原子单位(§1.1)。 */
38
+ export function isCallGroupStart(m) {
39
+ return m?.role === "assistant" && Array.isArray(m.tool_calls) && m.tool_calls.length > 0
40
+ }
41
+
42
+ /** 单条预算(§1.2):只量 `tool` 结果内容。`tool_calls.arguments` 不进这一档——截过的参数会让这次调用
43
+ * 看起来是以别的参数发出的,等于造一条伪的执行事实;assistant 文本同不在「工具内容」这一档。
44
+ * copy-on-write:不碰传入的消息对象(`pushReal` 的双线共享对象只读)。 */
45
+ export function clampToolMessage(m) {
46
+ if (m.role !== "tool" || typeof m.content !== "string" || m.content.length <= TOOL_PROCESS_MSG_CHARS) return m
47
+ return { ...m, content: buildDualEndPreview(m.content, TOOL_PROCESS_MSG_CHARS) }
48
+ }
49
+
50
+ /** 本轮工具段切片(§1.1):「第一次 `assistant(tool_calls)` 起、到最后一个 `tool` 结果止」的连续切片,
51
+ * 含其间的 assistant 文本;`transient` 注入不进机读线副本。这一轮没有调用 ⇒ `null`(记录不带该键)。 */
52
+ export function toolSliceOf(segment) {
53
+ let from = -1
54
+ let to = -1
55
+ for (let i = 0; i < segment.length; i++) {
56
+ const m = segment[i]
57
+ if (!m || typeof m !== "object" || m.transient === true) continue
58
+ if (from < 0 && isCallGroupStart(m)) from = i
59
+ if (m.role === "tool") to = i
60
+ }
61
+ if (from < 0 || to < from) return null
62
+ const out = []
63
+ for (let i = from; i <= to; i++) {
64
+ const m = segment[i]
65
+ if (!m || typeof m !== "object" || m.transient === true) continue
66
+ out.push(clampToolMessage(m))
67
+ }
68
+ return out.length > 0 ? out : null
69
+ }
70
+
71
+ /** 整段预算(§1.2):越 `TOOL_PROCESS_TURN_TOKENS` 就从最旧调用组起整组移出——一条 `assistant(tool_calls)`
72
+ * 与其全部 `tool` 结果同进同出(只动一边留下孤立配对,首个请求必 400)。
73
+ * 终止规则:只剩最新一组仍超限即停手——那一组保留完整、键仍在、段首那行报「已移出其余全部调用组」。
74
+ * 预算量的是**留下的调用组**:段首那行说明(含它报的组数 ∥ 条数 ∥ token)在预算之外,它约几十 token,
75
+ * 是这次移出的说明本身,不拿它去逼掉一整组真实结果。
76
+ * `lost` = 真的丢掉量(条数 · token · 组数),没移出则为零。 */
77
+ export function trimToolProcess(slice) {
78
+ const lost = { groups: 0, results: 0, tokens: 0 }
79
+ let kept = slice
80
+ if (slice.length > 0 && estimateTokens(slice) > TOOL_PROCESS_TURN_TOKENS) {
81
+ const starts = []
82
+ for (let i = 0; i < slice.length; i++) if (isCallGroupStart(slice[i])) starts.push(i)
83
+ let cursor = 0
84
+ for (let g = 0; g + 1 < starts.length; g++) {
85
+ if (estimateTokens(kept) <= TOOL_PROCESS_TURN_TOKENS) break
86
+ const gone = slice.slice(cursor, starts[g + 1])
87
+ lost.groups += 1
88
+ lost.tokens += estimateTokens(gone)
89
+ for (const m of gone) if (m.role === "tool") lost.results += 1
90
+ cursor = starts[g + 1]
91
+ kept = slice.slice(cursor)
92
+ }
93
+ }
94
+ if (lost.groups === 0) return { messages: slice, lost }
95
+ const remaining = kept.filter(isCallGroupStart).length
96
+ const only = remaining <= 1 ? " Only the most recent call group is kept here." : ""
97
+ const content = `${TOOL_PROCESS_DROP_MARK} ${lost.groups} earlier call group(s) with ${lost.results} tool result(s)` +
98
+ ` (~${lost.tokens} tokens) left this context line to stay within the turn budget.${only}`
99
+ return { messages: [{ role: "user", content }, ...kept], lost }
100
+ }
101
+
102
+ /** 本轮工具段(切片 + 两道预算,§1.2):裁剪在这里做一次,三面读同一份。 */
103
+ export function toolProcessOf(segment) {
104
+ const slice = toolSliceOf(segment)
105
+ if (!slice) return { messages: null, lost: { groups: 0, results: 0, tokens: 0 } }
106
+ return trimToolProcess(slice)
107
+ }
108
+
109
+ /** 一段工具过程的「真的丢掉量」(`folded:` 的记账面):折掉几条 `tool` 结果、估算多少 token、几组调用。 */
110
+ export function toolProcessLostOf(record) {
111
+ const lost = { groups: 0, results: 0, tokens: 0 }
112
+ const tp = Array.isArray(record?.toolProcess) ? record.toolProcess : []
113
+ if (tp.length === 0) return lost
114
+ lost.tokens = estimateTokens(tp)
115
+ for (const m of tp) {
116
+ if (m?.role === "tool") lost.results += 1
117
+ else if (isCallGroupStart(m)) lost.groups += 1
118
+ }
119
+ return lost
120
+ }
121
+
122
+ /** 折叠提示行的取形(§1.2):两个来处相加——本轮工具段被预算裁掉 ∥ 旧轮工具段逾期离开机读线。
123
+ * 低于 `FOLD_HINT_TOKENS` ⇒ `null`(整行不出现:一行常态噪声,读的人第二次起就不看了)。
124
+ * 只报量,不带任何回查位置——落盘的工具结果只留 slim 后的前段,写「全文可取回」是一句兑现不了的话。 */
125
+ export function foldHintOf(...sources) {
126
+ const total = { groups: 0, results: 0, tokens: 0, turns: 0 }
127
+ for (const s of sources) {
128
+ if (!s || (s.groups === 0 && s.results === 0)) continue
129
+ total.groups += s.groups
130
+ total.results += s.results
131
+ total.tokens += s.tokens
132
+ total.turns += 1
133
+ }
134
+ return total.tokens < FOLD_HINT_TOKENS ? null : total
135
+ }
136
+
137
+ /** 窗口裁切的上机读线部分(§1.1):把挤出去那一轮的工具段消息按**身份**摘除——压缩重建数组后下标会漂、
138
+ * 身份不漂。身份账就是那条轮记录自己的 `toolProcess`(折叠时插进机读线的正是这几个对象),不另立账。 */
139
+ export function dropToolProcessFromLine(agent, record) {
140
+ const gone = new Set(Array.isArray(record?.toolProcess) ? record.toolProcess : [])
141
+ if (gone.size === 0) return
142
+ const history = Array.isArray(agent?.history) ? agent.history : []
143
+ for (let i = history.length - 1; i >= 0; i--) if (gone.has(history[i])) history.splice(i, 1)
144
+ }
145
+
146
+ /**
147
+ * 保留窗起点(§1.2 结构保护):`turns` 里带 `toolProcess` 的轮记录,到 `agent._turnFoldMarks`
148
+ * 取它登记的那批消息对象,按身份在当刻的 `history` 上查出下标——与在途段起点同一条重定规则。
149
+ * 取全部保留轮里的**最小编号**:单个锚点被替换(压缩的归并支重写 `tail[0]`、`shrinkOversized`
150
+ * 重建条目)就会漏掉它后面的真起点,一个不留就整个窗都不受保护。
151
+ * 无保留窗(或那批消息已不在线上)⇒ `history.length`,等价于不收紧。
152
+ * 消费面 = `splitHistory` 的第四参:压缩的中段 ∥ prune 的合格集 ∥ 尾部预算三处同源受益。
153
+ */
154
+ export function retentionWindowStart(agent) {
155
+ const history = Array.isArray(agent?.history) ? agent.history : []
156
+ const turns = Array.isArray(agent?._turns) ? agent._turns : []
157
+ const marks = Array.isArray(agent?._turnFoldMarks) ? agent._turnFoldMarks : []
158
+ let earliest = -1
159
+ for (let i = 0; i < turns.length; i++) {
160
+ const tp = turns[i]?.toolProcess
161
+ if (!Array.isArray(tp) || tp.length === 0) continue
162
+ for (const m of Array.isArray(marks[i]) ? marks[i] : []) {
163
+ const k = history.indexOf(m)
164
+ if (k >= 0 && (earliest < 0 || k < earliest)) earliest = k
165
+ }
166
+ }
167
+ return earliest >= 0 ? earliest : history.length
168
+ }
@@ -0,0 +1,99 @@
1
+ /**
2
+ * agent/write-face.mjs — 面判定单源(写锁与设计门共用的判据底座)。
3
+ *
4
+ * 权威规格 = `docs/core/design/BATCH-LEDGER-REVIEW-UNIFY.md` §2.1 / §2.10;面分类的原文正源 =
5
+ * `docs/core/requirements/ENGINEERING-MODE-V2.md` §13.5。本档只做一件事:给一个绝对路径判「产品代码面
6
+ * / 文档面」,判据逐步骤对应 §2.10 的两值表。
7
+ *
8
+ * 面**只有两值**:文档面(放行)∥ 产品面(拦)——设计门按它拦;写锁 2026-11-03 起不分面(设计档 §2.3),
9
+ * 面在那里只选拒文变体。四格先命中先定:
10
+ * 1 出辖(祖先链无 manifest)⇒ 放行(`out-of-jurisdiction`)——辖界,不是面
11
+ * 2 manifest `docRoot` 前缀命中 ⇒ 放行(`doc-root`,D1 写权矩阵在写面上的机判投影)
12
+ * 3 文件 = `PROJECT-MANIFEST.json`(项目状态档)⇒ 放行(`manifest-state`)
13
+ * 4 其余一切 ⇒ 产品面(`product`,fail-closed——判不出面就按产品面走全链)
14
+ *
15
+ * 为什么不再复用 `classifyPath`:旧形把「构建产物 / 仓根 `scripts` ∥ `test` ∥ `.thincoder` ∥ `.github`
16
+ * / 锁文件 / `classifyPath` 的 temp·aux·state」当放行桶——每多一个放行桶,就多一条「这一步要不要走流程」
17
+ * 的自判口子(用户 2026-11-02 裁定退役)。两值之后没有第三桶、没有豁免、没有待裁格;`classifyPath` /
18
+ * `isCodePath` **本体零改**,它们仍是索引 / 检索 / verify 那一族的判据(七个生产消费面)。
19
+ *
20
+ * `test` 标记与面值**分离**:路径含 `test` / `tests` 段 ⇒ `test: true`,只决定写锁用测试变体拒文,
21
+ * 不改 `face`。
22
+ */
23
+ import { isAbsolute, relative, resolve } from "node:path"
24
+
25
+ import { declarationForTarget } from "../conventions.mjs"
26
+ import { docRootPaths, manifestFilePath, readManifest } from "../manifest.mjs"
27
+ // 文档面键集**不另持字面**(单源 = `agent-tools/review-facts.mjs` 的 `REVIEW_ROOT_KEYS`——同一组 docRoot 子键,
28
+ // 两份清单漂移就是「评审面放的 / 写面拦的」各说各话)。
29
+ import { REVIEW_ROOT_KEYS } from "../agent-tools/review-facts.mjs"
30
+
31
+ /** 比较键(绝对化 + 分隔符归一 `/` + win32 大小写归一——同 `write-gate.mjs` 的 `gateKey` 口径)。 */
32
+ const faceKey = (p) => {
33
+ const s = resolve(String(p)).replace(/\\/g, "/")
34
+ return process.platform === "win32" ? s.toLowerCase() : s
35
+ }
36
+
37
+ /** 该路径所属项目根的文档面根集(绝对比较键)。manifest 读不到 ⇒ 空集(兜底 = 产品代码面)。 */
38
+ function docRootKeys(root, manifest) {
39
+ let man = manifest
40
+ if (!man || typeof man !== "object" || !man.docRoot) {
41
+ try { man = readManifest(root).manifest } catch { man = null }
42
+ }
43
+ if (!man || typeof man !== "object") return []
44
+ const out = []
45
+ for (const key of REVIEW_ROOT_KEYS) {
46
+ for (const abs of docRootPaths(man.docRoot?.[key], root)) out.push(faceKey(abs))
47
+ }
48
+ return out
49
+ }
50
+
51
+ /** 路径段里有没有 `test` / `tests`(拒文变体句的判据,与面值无关)。 */
52
+ function hasTestSegment(relOrAbs) {
53
+ return String(relOrAbs).split(/[\\/]+/).filter(Boolean).some((s) => {
54
+ const low = s.toLowerCase()
55
+ return low === "test" || low === "tests"
56
+ })
57
+ }
58
+
59
+ /**
60
+ * 面判定(判据本体)。返回 `{face, reason, test}`:
61
+ * - `face` = `"product"`(产品面 ⇒ 设计门拦;写锁里只选拒文变体)∥ `"pass"`(放行面);
62
+ * - `reason` = 命中的那一格——**只有四值**:`out-of-jurisdiction` / `doc-root` / `manifest-state` /
63
+ * `product`(回执与用例的定位面);
64
+ * - `test` = 路径含 `test` / `tests` 段(产品测试面 ⇒ 写锁换测试变体那句拒文;不改 `face`)。
65
+ * @param {string} absPath — 目标绝对路径(相对形由调用方先 resolve;本档不猜会话锚)
66
+ * @param {object|null} [manifest] — 所属项目的 manifest(缺省 ⇒ 按项目根读;读不到 ⇒ 文档面空集)
67
+ * @returns {{face: "product"|"pass", reason: "out-of-jurisdiction"|"doc-root"|"manifest-state"|"product", test: boolean}}
68
+ */
69
+ export function faceDetail(absPath, manifest = null) {
70
+ const abs = resolve(String(absPath ?? ""))
71
+ const conv = declarationForTarget(abs) // 出辖 ⇒ null(祖先链无 manifest)
72
+ if (!conv) return { face: "pass", reason: "out-of-jurisdiction", test: hasTestSegment(abs) }
73
+ const root = conv.root
74
+ const rel = relative(root, abs)
75
+ const inRoot = rel === "" || (!rel.startsWith("..") && !isAbsolute(rel))
76
+ const test = hasTestSegment(inRoot ? rel : abs)
77
+ if (inRoot) {
78
+ const key = faceKey(abs)
79
+ // 2 文档面(manifest docRoot)
80
+ if (docRootKeys(root, manifest).some((d) => key === d || key.startsWith(`${d}/`))) {
81
+ return { face: "pass", reason: "doc-root", test }
82
+ }
83
+ // 3 项目状态档(主 agent 的声明面——D1 写权矩阵同源)
84
+ if (key === faceKey(manifestFilePath(root))) return { face: "pass", reason: "manifest-state", test }
85
+ }
86
+ // 4 其余一切 = 产品面(fail-closed)
87
+ return { face: "product", reason: "product", test }
88
+ }
89
+
90
+ /**
91
+ * 面判定(§2.1 契约形):`"product"` = 产品面(设计门按它拦;写锁里只选拒文变体——台账在途行才是判据),
92
+ * `"pass"` = 放行面(文档面 / 出辖)。
93
+ * @param {string} absPath — 目标绝对路径
94
+ * @param {object|null} [manifest] — 所属项目 manifest(缺省 ⇒ 按项目根读)
95
+ * @returns {"product"|"pass"}
96
+ */
97
+ export function faceOf(absPath, manifest = null) {
98
+ return faceDetail(absPath, manifest).face
99
+ }