dsh-memu-memory 1.4.2 → 1.4.4

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 (389) hide show
  1. package/AGENTS.md +108 -110
  2. package/CHANGELOG.md +173 -868
  3. package/LICENSE +21 -21
  4. package/README.md +368 -374
  5. package/README.zh.md +354 -360
  6. package/assets/icon.svg +7 -7
  7. package/cordis.patch.yml +8 -8
  8. package/docs/active-memory-ab.md +279 -385
  9. package/docs/binding-lifecycle.md +99 -99
  10. package/docs/client-conventions.md +75 -75
  11. package/docs/contributing.md +217 -217
  12. package/docs/emotion-model-spec.md +247 -281
  13. package/docs/env-and-commands.md +149 -152
  14. package/docs/host-adaptation.md +339 -360
  15. package/docs/host-api.md +131 -137
  16. package/docs/host-versions.md +117 -120
  17. package/docs/mcp-porting.md +146 -146
  18. package/docs/memory-semantics.md +271 -259
  19. package/docs/pending-work.md +44 -51
  20. package/docs/troubleshooting.md +909 -854
  21. package/lib/active-memory.js +160 -165
  22. package/lib/activity-log.js +207 -207
  23. package/lib/auto-link/apply.js +248 -249
  24. package/lib/auto-link/candidates.js +163 -163
  25. package/lib/auto-link/decide.js +300 -300
  26. package/lib/auto-link/normalize.js +99 -99
  27. package/lib/auto-link/policy.js +42 -42
  28. package/lib/auto-link/suppression.js +101 -101
  29. package/lib/auto-link/terminology.js +311 -311
  30. package/lib/backup.js +1254 -1254
  31. package/lib/binding-diagnostics.js +634 -634
  32. package/lib/budget.js +118 -118
  33. package/lib/client.js +9820 -9751
  34. package/lib/commitment.js +178 -138
  35. package/lib/consolidation-ledger.js +434 -438
  36. package/lib/consolidation-receipt.js +386 -387
  37. package/lib/consolidation-snapshot.js +420 -405
  38. package/lib/consolidation-worker.js +240 -241
  39. package/lib/context.js +33 -33
  40. package/lib/curator-evidence.js +131 -131
  41. package/lib/curator-policy.js +198 -202
  42. package/lib/curator.js +1813 -1811
  43. package/lib/cycle.js +524 -513
  44. package/lib/diagnostics.js +524 -524
  45. package/lib/embedding-catalog.js +1051 -1055
  46. package/lib/embedding-download.js +637 -607
  47. package/lib/embedding-runtime.js +946 -946
  48. package/lib/engine.js +1103 -1103
  49. package/lib/entity-repair.js +285 -285
  50. package/lib/environment-check.js +394 -394
  51. package/lib/fork-model.js +312 -312
  52. package/lib/freshness.js +128 -121
  53. package/lib/global-graph.js +389 -389
  54. package/lib/graph.js +1193 -1193
  55. package/lib/host-surface.js +30 -30
  56. package/lib/inbound.js +284 -281
  57. package/lib/index.js +506 -511
  58. package/lib/inject.js +2639 -2619
  59. package/lib/lexicon-scope.js +143 -143
  60. package/lib/lexicon.js +1183 -1192
  61. package/lib/lifecycle-audit.js +37 -0
  62. package/lib/local-embedding-entry.js +145 -145
  63. package/lib/local-embedding-manager.js +306 -306
  64. package/lib/local-embedding-protocol.js +210 -210
  65. package/lib/local-embedding-worker.js +682 -682
  66. package/lib/local-vector-service.js +506 -453
  67. package/lib/maintenance-ledger.js +138 -0
  68. package/lib/maintenance-review.js +103 -0
  69. package/lib/maintenance-runner.js +267 -0
  70. package/lib/managed-runtime.js +118 -118
  71. package/lib/media.js +607 -513
  72. package/lib/memory.js +5035 -4941
  73. package/lib/memu-config.js +213 -213
  74. package/lib/memu.js +565 -565
  75. package/lib/migrate.js +200 -200
  76. package/lib/mood.js +300 -300
  77. package/lib/paths.js +453 -457
  78. package/lib/port-surface.js +82 -82
  79. package/lib/preset-mount.js +85 -0
  80. package/lib/preset-scope.js +126 -126
  81. package/lib/private-links.js +567 -567
  82. package/lib/private.js +2198 -2209
  83. package/lib/prompts/global-curator.md +135 -135
  84. package/lib/prompts/image-caption.md +1 -1
  85. package/lib/prompts/private-consolidation.coding.md +39 -39
  86. package/lib/prompts/private-consolidation.md +32 -32
  87. package/lib/prompts/private-consolidation.mixed.md +37 -37
  88. package/lib/prompts/private-consolidation.rp.md +47 -47
  89. package/lib/prompts/private-policy.coding.md +35 -35
  90. package/lib/prompts/private-policy.md +36 -36
  91. package/lib/prompts/private-policy.mixed.md +29 -29
  92. package/lib/prompts/private-policy.rp.md +43 -43
  93. package/lib/prompts/system-guide.coding.md +20 -20
  94. package/lib/prompts/system-guide.md +25 -25
  95. package/lib/prompts/system-guide.mixed.md +22 -22
  96. package/lib/prompts/system-guide.rp.md +23 -23
  97. package/lib/prompts.js +331 -331
  98. package/lib/recall-cache.js +212 -212
  99. package/lib/remote-summary.js +123 -123
  100. package/lib/rpc.js +2531 -2532
  101. package/lib/salient-wake.js +438 -438
  102. package/lib/snippet.js +125 -125
  103. package/lib/state.js +1948 -1928
  104. package/lib/stats.js +236 -236
  105. package/lib/temporal.js +345 -348
  106. package/lib/text-retrieval.js +992 -1001
  107. package/lib/text-similarity.js +305 -305
  108. package/lib/tokenizer-v2.js +271 -271
  109. package/lib/tools.js +1098 -1091
  110. package/lib/turn-log.js +545 -545
  111. package/lib/vector-migration.js +928 -930
  112. package/lib/vector-profile.js +1353 -1359
  113. package/lib/visibility.js +59 -59
  114. package/lib/webui/graph-LICENSE.txt +1 -1
  115. package/lib/webui/graph-view.bundle.js +2 -2
  116. package/lib/webui/graph-view.js +1171 -1175
  117. package/lib/webui/mark.svg +7 -7
  118. package/lib/webui/standalone.css +1178 -1178
  119. package/lib/webui/standalone.js +238 -238
  120. package/lib/webui.js +136 -136
  121. package/lib/worker-pool.js +1020 -979
  122. package/package.json +153 -153
  123. package/requirements.lock +34 -34
  124. package/scripts/acceptance-local.mjs +946 -946
  125. package/scripts/active-memory-ab-live.mjs +653 -655
  126. package/scripts/active-memory-ab.mjs +1302 -1302
  127. package/scripts/audit-memory-lifecycle.mjs +55 -0
  128. package/scripts/bench-recall.mjs +142 -142
  129. package/scripts/build-graph.mjs +44 -45
  130. package/scripts/chain-matrix.mjs +541 -541
  131. package/scripts/check-all.mjs +68 -74
  132. package/scripts/check-doc-drift.mjs +547 -547
  133. package/scripts/check-graph-browser.mjs +261 -261
  134. package/scripts/check-i18n.mjs +81 -83
  135. package/scripts/check-idle-compositing.mjs +61 -61
  136. package/scripts/check-seed-compat.mjs +115 -118
  137. package/scripts/check-text-format.mjs +55 -0
  138. package/scripts/curator-pair-calibrate.mjs +259 -259
  139. package/scripts/diagnose-bindings.mjs +176 -176
  140. package/scripts/drive-session.mjs +863 -864
  141. package/scripts/engine-smoke.mjs +69 -69
  142. package/scripts/entity-dedupe.mjs +110 -110
  143. package/scripts/lexicon-calibrate.mjs +230 -230
  144. package/scripts/lexicon-dedupe.mjs +318 -318
  145. package/scripts/local-runtime-install.mjs +142 -142
  146. package/scripts/local-runtime-verify.mjs +56 -56
  147. package/scripts/local-vector-verify.mjs +93 -93
  148. package/scripts/make-readme-shots.mjs +59 -59
  149. package/scripts/migrate-visibility.mjs +94 -94
  150. package/scripts/mock-llm.mjs +938 -903
  151. package/scripts/preview.mjs +58 -58
  152. package/scripts/prune-sessions.mjs +31 -34
  153. package/scripts/prune-turnlogs.mjs +29 -30
  154. package/scripts/prune-vectors.mjs +24 -24
  155. package/scripts/rebuild-auto-links.mjs +252 -252
  156. package/scripts/recall-bench.mjs +820 -820
  157. package/scripts/repetition-ab-scenarios.mjs +93 -93
  158. package/scripts/repetition-detector-snapshot.mjs +314 -314
  159. package/scripts/repetition-eval-live.mjs +360 -360
  160. package/scripts/repetition-eval.mjs +702 -702
  161. package/scripts/replay.mjs +705 -575
  162. package/scripts/setup.mjs +46 -46
  163. package/scripts/simulate-injection.mjs +299 -301
  164. package/tests/absorb-review.test.mjs +354 -354
  165. package/tests/activation.test.mjs +89 -89
  166. package/tests/active-memory-ab.test.mjs +745 -745
  167. package/tests/active-memory.test.mjs +129 -129
  168. package/tests/activity-log.test.mjs +126 -126
  169. package/tests/activity-wiring.test.mjs +155 -155
  170. package/tests/appendix-b.test.mjs +217 -217
  171. package/tests/appendix-b2.test.mjs +166 -166
  172. package/tests/audit-batch3.test.mjs +247 -247
  173. package/tests/audit-regression.test.mjs +275 -275
  174. package/tests/audit-safety.test.mjs +227 -227
  175. package/tests/auto-link-candidates.test.mjs +245 -245
  176. package/tests/auto-link-decide.test.mjs +512 -512
  177. package/tests/auto-link-migration.test.mjs +133 -133
  178. package/tests/backend-compensation.test.mjs +272 -272
  179. package/tests/backup.test.mjs +793 -793
  180. package/tests/binding-diagnostics.test.mjs +720 -720
  181. package/tests/browser.test.mjs +476 -476
  182. package/tests/client-export.test.mjs +521 -521
  183. package/tests/client-render.test.mjs +2008 -1728
  184. package/tests/coalesce.test.mjs +113 -113
  185. package/tests/commitment.test.mjs +243 -144
  186. package/tests/config.test.mjs +159 -159
  187. package/tests/consolidation-credential.test.mjs +330 -330
  188. package/tests/consolidation-feed.test.mjs +122 -122
  189. package/tests/consolidation-fork.test.mjs +1587 -1539
  190. package/tests/consolidation-ledger.test.mjs +389 -389
  191. package/tests/consolidation-snapshot.test.mjs +567 -505
  192. package/tests/consolidation-value.test.mjs +89 -89
  193. package/tests/context-scope.test.mjs +40 -40
  194. package/tests/cross-library-recall.test.mjs +269 -269
  195. package/tests/cue.test.mjs +58 -58
  196. package/tests/curator-absorb.test.mjs +444 -444
  197. package/tests/curator-calibrate.test.mjs +173 -173
  198. package/tests/curator-clusters.test.mjs +306 -306
  199. package/tests/curator-commit.test.mjs +325 -325
  200. package/tests/curator-contract.test.mjs +191 -191
  201. package/tests/curator-evidence.test.mjs +102 -102
  202. package/tests/curator-link.test.mjs +317 -317
  203. package/tests/curator-pairing.test.mjs +339 -339
  204. package/tests/curator-probe.test.mjs +490 -490
  205. package/tests/curator-review-mode.test.mjs +315 -315
  206. package/tests/curator.test.mjs +152 -152
  207. package/tests/cycle.test.mjs +567 -568
  208. package/tests/diagnostics.test.mjs +278 -278
  209. package/tests/disclosure.test.mjs +249 -249
  210. package/tests/doc-drift.test.mjs +342 -342
  211. package/tests/drive-session.test.mjs +152 -152
  212. package/tests/dynamic-rrf.test.mjs +182 -182
  213. package/tests/dynamic-threshold.test.mjs +52 -52
  214. package/tests/embedding-catalog.test.mjs +374 -374
  215. package/tests/embedding-download.test.mjs +529 -486
  216. package/tests/embedding-runtime.test.mjs +449 -449
  217. package/tests/emotion-chain.test.mjs +84 -84
  218. package/tests/emotion-contract.test.mjs +445 -445
  219. package/tests/engine.test.mjs +108 -108
  220. package/tests/entity-merge.test.mjs +278 -278
  221. package/tests/environment-check.test.mjs +187 -187
  222. package/tests/fact-version.test.mjs +146 -146
  223. package/tests/fixtures/active-memory-ab/README.md +56 -56
  224. package/tests/fixtures/active-memory-ab/cases/01-clean-dense-turn.json +351 -351
  225. package/tests/fixtures/active-memory-ab/cases/02-clean-thin-turn.json +122 -122
  226. package/tests/fixtures/active-memory-ab/cases/03-clean-starved-small.json +125 -125
  227. package/tests/fixtures/active-memory-ab/cases/04-clean-large-thin.json +137 -137
  228. package/tests/fixtures/active-memory-ab/cases/05-clean-half-step.json +166 -166
  229. package/tests/fixtures/active-memory-ab/cases/06-clean-duplicate-reread.json +197 -197
  230. package/tests/fixtures/active-memory-ab/cases/07-clean-recent-recall.json +125 -125
  231. package/tests/fixtures/active-memory-ab/cases/08-global-relevant.json +111 -111
  232. package/tests/fixtures/active-memory-ab/cases/09-global-irrelevant-conflict.json +158 -158
  233. package/tests/fixtures/active-memory-ab/cases/10-no-human-turn.json +97 -97
  234. package/tests/fixtures/active-memory-ab/cases/11-clean-scale-100.json +137 -137
  235. package/tests/fixtures/active-memory-ab/cases/12-clean-scale-1000.json +137 -137
  236. package/tests/fixtures/active-memory-ab/cases/13-clean-scale-5000.json +137 -137
  237. package/tests/fixtures/active-memory-ab/cases/14-clean-scale-20000.json +137 -137
  238. package/tests/fixtures/active-memory-ab/lead-ai-reviewed-reference.json +191 -191
  239. package/tests/fixtures/active-memory-ab/manifest.json +199 -199
  240. package/tests/fixtures/curator-pairs/labeled.v1.jsonl +90 -90
  241. package/tests/fixtures/lexicon-stub-hooks.mjs +15 -15
  242. package/tests/fixtures/lexicon-stub.mjs +284 -284
  243. package/tests/fixtures/mock-llm/reply.txt +1 -1
  244. package/tests/fixtures/recall-bench/01-paraphrase.json +183 -183
  245. package/tests/fixtures/recall-bench/02-exact.json +152 -152
  246. package/tests/fixtures/recall-bench/03-negation.json +172 -172
  247. package/tests/fixtures/recall-bench/04-no-answer.json +161 -161
  248. package/tests/fixtures/recall-bench/05-conflict.json +193 -193
  249. package/tests/fixtures/recall-bench/06-boundary.json +272 -272
  250. package/tests/fixtures/recall-bench/07-secret.json +190 -190
  251. package/tests/fixtures/recall-bench/08-coding.json +163 -163
  252. package/tests/fixtures/recall-bench-gold-candidates/01-paraphrase.json +193 -193
  253. package/tests/fixtures/recall-bench-gold-candidates/02-exact.json +197 -197
  254. package/tests/fixtures/recall-bench-gold-candidates/03-negation.json +244 -244
  255. package/tests/fixtures/recall-bench-gold-candidates/04-no-answer.json +189 -189
  256. package/tests/fixtures/recall-bench-gold-candidates/05-conflict.json +245 -245
  257. package/tests/fixtures/recall-bench-gold-candidates/06-boundary.json +279 -279
  258. package/tests/fixtures/recall-bench-gold-candidates/07-secret.json +224 -224
  259. package/tests/fixtures/recall-bench-gold-candidates/08-coding.json +218 -218
  260. package/tests/fixtures/repetition-eval/01-zh-rp.json +92 -92
  261. package/tests/fixtures/repetition-eval/02-en.json +96 -96
  262. package/tests/fixtures/repetition-eval/03-code.json +90 -90
  263. package/tests/fixtures/repetition-eval/04-names.json +115 -115
  264. package/tests/fixtures/repetition-eval/05-user-quote.json +95 -95
  265. package/tests/fixtures/repetition-eval/06-agreement.json +85 -85
  266. package/tests/fixtures/tokenizer-cases.mjs +27 -27
  267. package/tests/fork-model.test.mjs +345 -345
  268. package/tests/freshness.test.mjs +140 -140
  269. package/tests/global-graph.test.mjs +106 -106
  270. package/tests/global-lifecycle.test.mjs +149 -149
  271. package/tests/graph-cascade.test.mjs +363 -363
  272. package/tests/graph-view.test.mjs +414 -414
  273. package/tests/graph.test.mjs +371 -371
  274. package/tests/help-page.test.mjs +416 -416
  275. package/tests/hook-order.test.mjs +72 -72
  276. package/tests/humanlike.test.mjs +232 -232
  277. package/tests/hybrid-recall.test.mjs +610 -610
  278. package/tests/inbound.test.mjs +441 -441
  279. package/tests/inject-conflict.test.mjs +173 -173
  280. package/tests/inject-guide.test.mjs +513 -513
  281. package/tests/inject.test.mjs +384 -384
  282. package/tests/injection-budget-settings.test.mjs +35 -35
  283. package/tests/injection-budget.test.mjs +165 -165
  284. package/tests/injection-chain.test.mjs +442 -442
  285. package/tests/injection-intent-budget.test.mjs +92 -92
  286. package/tests/injection-rollback.test.mjs +428 -428
  287. package/tests/issue2-chain.test.mjs +169 -169
  288. package/tests/lexical-bm25.test.mjs +171 -171
  289. package/tests/lexicon-calibrate.test.mjs +48 -48
  290. package/tests/lexicon-dedupe.test.mjs +171 -171
  291. package/tests/lexicon-frequency.test.mjs +195 -195
  292. package/tests/lexicon-inject.test.mjs +459 -459
  293. package/tests/lexicon-perf.test.mjs +464 -464
  294. package/tests/lexicon-scope.test.mjs +256 -256
  295. package/tests/lexicon-ui.test.mjs +667 -667
  296. package/tests/lexicon.test.mjs +922 -922
  297. package/tests/lifecycle-audit.test.mjs +56 -0
  298. package/tests/loader-register.mjs +3 -3
  299. package/tests/loader.mjs +17 -17
  300. package/tests/local-embedding-entry.test.mjs +95 -95
  301. package/tests/local-embedding-env.test.mjs +51 -51
  302. package/tests/local-embedding-manager.test.mjs +494 -494
  303. package/tests/local-embedding-protocol.test.mjs +121 -121
  304. package/tests/local-embedding-worker.test.mjs +440 -440
  305. package/tests/local-vector-service.test.mjs +41 -0
  306. package/tests/maintenance-status.test.mjs +77 -0
  307. package/tests/maintenance.test.mjs +438 -0
  308. package/tests/managed-memory.test.mjs +1234 -1234
  309. package/tests/managed-runtime.test.mjs +72 -72
  310. package/tests/media-injection.test.mjs +225 -0
  311. package/tests/media.test.mjs +135 -135
  312. package/tests/memory-chain.test.mjs +169 -169
  313. package/tests/memory-fields.test.mjs +134 -134
  314. package/tests/memu-resident-route.test.mjs +130 -130
  315. package/tests/memu-resident.test.mjs +33 -33
  316. package/tests/migration-payload.test.mjs +40 -42
  317. package/tests/mock-llm.test.mjs +263 -225
  318. package/tests/mood.test.mjs +109 -109
  319. package/tests/multiprocess.test.mjs +29 -29
  320. package/tests/negation-polarity.test.mjs +135 -135
  321. package/tests/new-session-gate.test.mjs +617 -617
  322. package/tests/open-loop-date.test.mjs +416 -416
  323. package/tests/ops-hardening.test.mjs +209 -209
  324. package/tests/package-shipping.test.mjs +88 -88
  325. package/tests/pending-injection.test.mjs +107 -107
  326. package/tests/port-surface.test.mjs +138 -138
  327. package/tests/preset-mount.test.mjs +132 -0
  328. package/tests/preset-scope.test.mjs +212 -212
  329. package/tests/private-links.test.mjs +493 -493
  330. package/tests/prompt-semantics.test.mjs +51 -51
  331. package/tests/prompts.test.mjs +315 -315
  332. package/tests/query-decompose.test.mjs +62 -62
  333. package/tests/react-snapshot.test.mjs +24 -24
  334. package/tests/recall-bench.test.mjs +317 -317
  335. package/tests/recall-cache.test.mjs +292 -292
  336. package/tests/recall-corpus-eligibility.test.mjs +51 -51
  337. package/tests/recall-dedup.test.mjs +446 -446
  338. package/tests/recall-intent.test.mjs +172 -172
  339. package/tests/regression-sweep.test.mjs +311 -311
  340. package/tests/reminder-fairness.test.mjs +55 -0
  341. package/tests/remote.test.mjs +140 -140
  342. package/tests/rename.test.mjs +30 -30
  343. package/tests/repetition-detector-snapshot.test.mjs +231 -231
  344. package/tests/repetition-eval-live.test.mjs +177 -177
  345. package/tests/repetition-eval.test.mjs +373 -373
  346. package/tests/salience-domain.test.mjs +173 -173
  347. package/tests/salient-date.test.mjs +142 -142
  348. package/tests/salient-wake.test.mjs +389 -389
  349. package/tests/settings-beat.test.mjs +222 -222
  350. package/tests/settings-coverage.test.mjs +97 -97
  351. package/tests/settings-plumbing.test.mjs +79 -79
  352. package/tests/short-term.test.mjs +182 -166
  353. package/tests/sidebar-beat.test.mjs +213 -213
  354. package/tests/sidebar-refresh.test.mjs +123 -123
  355. package/tests/sidebar.test.mjs +102 -74
  356. package/tests/simulate-injection.test.mjs +76 -76
  357. package/tests/slot-similarity.test.mjs +153 -153
  358. package/tests/snippet.test.mjs +79 -79
  359. package/tests/source-kind.test.mjs +52 -52
  360. package/tests/speaker-provenance.test.mjs +120 -120
  361. package/tests/stale-maintenance.test.mjs +206 -131
  362. package/tests/state-gc.test.mjs +34 -34
  363. package/tests/state.test.mjs +155 -155
  364. package/tests/stats.test.mjs +112 -112
  365. package/tests/storage.test.mjs +125 -125
  366. package/tests/stubs/child-process-spy.mjs +14 -14
  367. package/tests/stubs/dsh-llm-pi-ai.js +13 -13
  368. package/tests/stubs/dsh-llm.js +5 -5
  369. package/tests/stubs/dsh-schedule.js +140 -140
  370. package/tests/stubs/dsh-session-query.js +26 -26
  371. package/tests/stubs/dsh-session.js +7 -7
  372. package/tests/stubs/dsh-tools.js +101 -101
  373. package/tests/temporal-repair.test.mjs +78 -0
  374. package/tests/temporal.test.mjs +124 -124
  375. package/tests/text-format.test.mjs +24 -0
  376. package/tests/tokenizer-v2.test.mjs +142 -142
  377. package/tests/tool-schema.test.mjs +126 -126
  378. package/tests/tools.test.mjs +810 -810
  379. package/tests/turn-log.test.mjs +487 -487
  380. package/tests/ui-defaults.test.mjs +57 -57
  381. package/tests/update-fields.test.mjs +138 -138
  382. package/tests/vector-gc.test.mjs +37 -37
  383. package/tests/vector-migration.test.mjs +810 -810
  384. package/tests/vector-profile.test.mjs +449 -449
  385. package/tests/visibility-migration.test.mjs +152 -152
  386. package/tests/webui-auth.test.mjs +963 -963
  387. package/tests/webui.test.mjs +421 -421
  388. package/tests/windows-env.test.mjs +89 -89
  389. package/tests/worker-lifecycle.test.mjs +1522 -1429
package/lib/turn-log.js CHANGED
@@ -1,545 +1,545 @@
1
- import fs from 'node:fs'
2
- import path from 'node:path'
3
- import crypto from 'node:crypto'
4
- import { dataDir, ensureDir, warn, redactSecrets, isSafeId, shortHash, stamp } from './paths.js'
5
- import { getSettings, getSessionBinding } from './state.js'
6
-
7
- // T0 构件 1(设计文档 §3):增量回合日志。
8
- //
9
- // 定位是纯旁路缓存,不是账本(§0 铁律 1):每行一个宿主 turn/end 的 seq 区间,
10
- // 记录规则与 condenseEvents 同口径(§3.1,不发明新规则)。任何失败只 warn,
11
- // 绝不影响主会话;正确性永远由宿主转录 + 缺口重建兜底(§3.3)。
12
- //
13
- // 三层 caps(§3.1):user/model 各 2000 字全保;工具行 160 字;整条记录 4000 字
14
- // 总闸——超预算只砍 tools 行(按序装、砍尾并标注省略数),user/model 不动。
15
-
16
- export const TURNLOG_USER_MODEL_CHARS = 2000
17
- export const TURNLOG_TOOL_LINE_CHARS = 160
18
- export const TURNLOG_TOOL_ARGS_CHARS = 120
19
- export const TURNLOG_RECORD_CHARS = 4000
20
- export const TURNLOG_KEEP_CHARS = 200_000
21
- export const TURNLOG_GC_DAYS = 30
22
-
23
- // 编码域的「修改重点」几乎全在工具行里(命令、错误签名、diff 参数),160 字只留得下
24
- // 开头。给编码域更宽的单项额度,整条记录仍受 4000 字总闸约束(先砍 tools 尾)。
25
- export const TURNLOG_TOOL_LINE_CHARS_CODING = 600
26
- export const TURNLOG_TOOL_ARGS_CHARS_CODING = 400
27
-
28
- const DEFAULT_TOOL_LIMITS = Object.freeze({
29
- toolLineChars: TURNLOG_TOOL_LINE_CHARS,
30
- toolArgsChars: TURNLOG_TOOL_ARGS_CHARS,
31
- })
32
-
33
- export function turnLogLimits(domain) {
34
- return String(domain) === 'coding'
35
- ? { toolLineChars: TURNLOG_TOOL_LINE_CHARS_CODING, toolArgsChars: TURNLOG_TOOL_ARGS_CHARS_CODING }
36
- : DEFAULT_TOOL_LIMITS
37
- }
38
-
39
- const TURNLOG_SUFFIX = '.turnlog.jsonl'
40
-
41
- function truncate(text, max) {
42
- const s = String(text || '')
43
- return s.length > max ? `${s.slice(0, max)}…` : s
44
- }
45
-
46
- function firstLine(text) {
47
- const s = String(text || '').replace(/\r/g, '')
48
- const nl = s.indexOf('\n')
49
- return (nl >= 0 ? s.slice(0, nl) : s).trim()
50
- }
51
-
52
- function textOfBlocks(blocks) {
53
- if (typeof blocks === 'string') return blocks.trim()
54
- if (!Array.isArray(blocks)) return ''
55
- return blocks
56
- .filter((b) => b?.type === 'text' && typeof b.text === 'string')
57
- .map((b) => b.text)
58
- .join('')
59
- .trim()
60
- }
61
-
62
- function argsText(value) {
63
- if (value == null) return ''
64
- return typeof value === 'string' ? value : JSON.stringify(value)
65
- }
66
-
67
- /**
68
- * 会话 id 直接拼进文件名。宿主 id 是安全字符集;防御性兜底把任何奇怪 id 哈希成
69
- * 固定名(缓存可重建,哈希碰撞的最坏结果是两段日志混在一个文件里,可接受)。
70
- */
71
- function logFileName(sessionId) {
72
- const raw = String(sessionId || '')
73
- return (isSafeId(raw) ? raw : `sid-${shortHash(raw)}`) + TURNLOG_SUFFIX
74
- }
75
-
76
- export function turnLogPath(sessionId) {
77
- return path.join(ensureDir(path.join(dataDir(), 'sessions')), logFileName(sessionId))
78
- }
79
-
80
- function safeSeqRange(record) {
81
- const seq = record?.seq
82
- if (!Array.isArray(seq) || seq.length !== 2) return null
83
- const start = Number(seq[0])
84
- const end = Number(seq[1])
85
- if (!Number.isSafeInteger(start) || !Number.isSafeInteger(end) || start < 0 || end < start) return null
86
- return [start, end]
87
- }
88
-
89
- // —— 记录规则(§3.1,与 condenseEvents 同口径) ————————————————
90
-
91
- function toolCallIdOfResult(event) {
92
- const message = event?.data?.message
93
- return [message?.callId, message?.toolCallId, message?.source?.callId]
94
- .find((value) => typeof value === 'string' && value) || null
95
- }
96
-
97
- function toolLine(name, args, status, errorText, limits = DEFAULT_TOOL_LIMITS) {
98
- const lineChars = limits.toolLineChars ?? TURNLOG_TOOL_LINE_CHARS
99
- const argsChars = limits.toolArgsChars ?? TURNLOG_TOOL_ARGS_CHARS
100
- const head = `${name || '?'}${args ? `(${truncate(args, argsChars)})` : ''}`
101
- const tail = status === 'ok' ? ' → 成功'
102
- : status === 'error' ? ` → 失败: ${firstLine(errorText)}`
103
- : ' → 无结果'
104
- // 工具行与对话文本同一待遇:先脱敏再截断(§3.1「记录时应用 redactSecrets」)。
105
- return truncate(redactSecrets(head + tail), lineChars)
106
- }
107
-
108
- /**
109
- * 'summary' 档工具行:调用 + 结果按 callId 配对。tool/call 事件是权威侧
110
- * (assistant 消息里的 tool-call 块是同一次调用的双写,不单独成行——condenseEvents C2 同款)。
111
- */
112
- function summaryToolLines(events, limits = DEFAULT_TOOL_LIMITS) {
113
- const lines = []
114
- const calls = new Map() // callId -> line entry
115
- for (const event of events) {
116
- if (event?.type !== 'tool/call') continue
117
- const id = typeof event?.data?.callId === 'string' && event.data.callId ? event.data.callId : null
118
- if (id && calls.has(id)) continue // 同一 callId 双写去重
119
- const entry = { name: event?.data?.name || '?', args: argsText(event?.data?.arguments), status: 'pending', errorText: '' }
120
- if (id) calls.set(id, entry)
121
- lines.push(entry)
122
- }
123
- for (const event of events) {
124
- if (event?.type !== 'tool/result') continue
125
- const id = toolCallIdOfResult(event)
126
- const entry = id ? calls.get(id) : null
127
- const isError = event?.data?.message?.isError === true
128
- const text = textOfBlocks(event?.data?.message?.content)
129
- if (entry && !entry.done) {
130
- entry.status = isError ? 'error' : 'ok'
131
- entry.errorText = text
132
- entry.done = true
133
- } else if (!entry) {
134
- // 结果先于调用可见(乱序/旧 fixture):结果行自己成行,错误结果在 errors 档也要可见。
135
- lines.push({ name: '?', args: '', status: isError ? 'error' : 'ok', errorText: text, done: true })
136
- }
137
- }
138
- return lines.map((entry) => toolLine(entry.name, entry.args, entry.status === 'pending' ? 'none' : entry.status, entry.errorText, limits))
139
- }
140
-
141
- /** 'errors' 档:只收 isError 的工具结果行——失败尝试是漏网事实的最廉价来源(§3.1)。 */
142
- function errorToolLines(events, limits = DEFAULT_TOOL_LIMITS) {
143
- const names = new Map()
144
- for (const event of events) {
145
- if (event?.type !== 'tool/call') continue
146
- const id = typeof event?.data?.callId === 'string' && event.data.callId ? event.data.callId : null
147
- if (id && !names.has(id)) names.set(id, event?.data?.name || '?')
148
- }
149
- const lines = []
150
- for (const event of events) {
151
- if (event?.type !== 'tool/result' || event?.data?.message?.isError !== true) continue
152
- const id = toolCallIdOfResult(event)
153
- const name = (id && names.get(id)) || '?'
154
- lines.push(toolLine(name, '', 'error', textOfBlocks(event?.data?.message?.content), limits))
155
- }
156
- return lines
157
- }
158
-
159
- function joinParts(parts, max) {
160
- return truncate(redactSecrets(parts.join('\n')), max)
161
- }
162
-
163
- /**
164
- * 把一段宿主事件流转成回合记录数组(纯函数:同输入同输出)。
165
- *
166
- * 分组与 candidateSeedEvents 同款:turn/start 开组(或流中途无组时首个事件开组),
167
- * turn/end 封组;尾部没有 turn/end 的半回合不产出记录(未结算)。
168
- * options.tools 覆盖设置档(测试用),默认读 consolidationTurnLogTools。
169
- */
170
- export function buildTurnRecords(events, options = {}) {
171
- let toolsMode = options.tools
172
- if (toolsMode === undefined) {
173
- try { toolsMode = getSettings().consolidationTurnLogTools } catch { toolsMode = undefined }
174
- }
175
- if (toolsMode !== 'errors' && toolsMode !== 'summary') toolsMode = 'none'
176
- const limits = {
177
- toolLineChars: Number(options.toolLineChars) > 0 ? Number(options.toolLineChars) : TURNLOG_TOOL_LINE_CHARS,
178
- toolArgsChars: Number(options.toolArgsChars) > 0 ? Number(options.toolArgsChars) : TURNLOG_TOOL_ARGS_CHARS,
179
- }
180
-
181
- const groups = []
182
- let current = null
183
- for (const event of Array.isArray(events) ? events : []) {
184
- if (!event || typeof event.type !== 'string') continue
185
- if (event.type === 'turn/start' || current === null) {
186
- current = []
187
- groups.push(current)
188
- }
189
- current.push(event)
190
- if (event.type === 'turn/end') current = null
191
- }
192
-
193
- const records = []
194
- for (const group of groups) {
195
- const end = group[group.length - 1]
196
- if (end?.type !== 'turn/end') continue // 未闭合的半回合留给下一窗对账重建
197
- const startSeq = Number(group[0]?.seq)
198
- const endSeq = Number(end?.seq)
199
- if (!Number.isSafeInteger(startSeq) || !Number.isSafeInteger(endSeq) || startSeq < 0 || endSeq < startSeq) continue
200
-
201
- const userParts = []
202
- const modelParts = []
203
- let scene = null
204
- for (const event of group) {
205
- if (event.type === 'user/message') {
206
- // 只收真人消息:插件注入 / 调度 / 心跳一律不记(§3.1 过滤口径)。
207
- if (event?.data?.source?.kind !== 'user') continue
208
- const text = textOfBlocks(event?.data?.content)
209
- if (text) userParts.push(text)
210
- const sceneTime = event?.data?.sceneTime
211
- if (typeof sceneTime === 'string' && sceneTime.trim()) scene = sceneTime
212
- } else if (event.type === 'assistant/message') {
213
- // assistant 只收 text 块:reasoning / tool-call 块不进对话记录。
214
- const text = textOfBlocks(event?.data?.message?.content)
215
- if (text) modelParts.push(text)
216
- }
217
- }
218
-
219
- const record = {
220
- seq: [startSeq, endSeq],
221
- at: Number.isFinite(end?.time) ? new Date(end.time).toISOString() : null,
222
- scene,
223
- user: joinParts(userParts, TURNLOG_USER_MODEL_CHARS),
224
- model: joinParts(modelParts, TURNLOG_USER_MODEL_CHARS),
225
- }
226
- const kind = end?.data?.reason?.kind
227
- if (kind && kind !== 'completed') record.interrupted = true
228
-
229
- let toolLines = []
230
- if (toolsMode === 'summary') toolLines = summaryToolLines(group, limits)
231
- else if (toolsMode === 'errors') toolLines = errorToolLines(group, limits)
232
- if (toolLines.length > 0) record.tools = toolLines
233
-
234
- // 空回合(纯注入/心跳/无对话无工具)不落行。
235
- if (!record.user && !record.model && !(record.tools && record.tools.length > 0)) continue
236
-
237
- applyRecordCap(record)
238
- records.push(record)
239
- }
240
- return records
241
- }
242
-
243
- /** 4000 字总闸:超预算只砍 tools 尾部(user/model 在各自 2000 内全保)。 */
244
- function applyRecordCap(record) {
245
- const tools = record.tools
246
- if (!Array.isArray(tools) || tools.length === 0) return
247
- if (JSON.stringify(record).length <= TURNLOG_RECORD_CHARS) return
248
- const marker = (n) => `…[另有 ${n} 条工具调用已省略]`
249
- let kept = tools.length
250
- while (kept >= 0) {
251
- record.tools = tools.slice(0, kept)
252
- if (kept < tools.length) record.tools.push(marker(tools.length - kept))
253
- if (JSON.stringify(record).length <= TURNLOG_RECORD_CHARS || kept === 0) return
254
- kept -= 1
255
- }
256
- }
257
-
258
- // —— 落盘与读取 ————————————————————————————————————————————
259
-
260
- function scanTurnLog(sessionId) {
261
- const file = turnLogPath(sessionId)
262
- let raw
263
- try {
264
- raw = fs.readFileSync(file, 'utf8')
265
- } catch (error) {
266
- // ENOENT = 空日志(正常);其他读失败当作不可读:绝不在没读到的地方重写。
267
- if (error?.code !== 'ENOENT') warn(`turn-log read failed for ${logFileName(sessionId)}: ${error?.message || error}`)
268
- return { file, entries: [], badLines: 0, unreadable: error?.code !== 'ENOENT' }
269
- }
270
- const entries = []
271
- let badLines = 0
272
- for (const line of raw.split('\n')) {
273
- const trimmed = line.trim()
274
- if (!trimmed) continue
275
- let record = null
276
- try { record = JSON.parse(trimmed) } catch { badLines += 1 }
277
- entries.push({ raw: trimmed, record })
278
- }
279
- return { file, entries, badLines, unreadable: false }
280
- }
281
-
282
- /** 坏行原样保留地原子重写(Windows 上 rename 的 EPERM/EBUSY 重试用 paths.js 同款节奏)。 */
283
- function rewriteTurnLog(file, lines) {
284
- ensureDir(path.dirname(file))
285
- const tmp = `${file}.tmp-${process.pid}-${crypto.randomUUID()}`
286
- try {
287
- fs.writeFileSync(tmp, lines.length > 0 ? lines.join('\n') + '\n' : '', 'utf8')
288
- for (let attempt = 0; ; attempt++) {
289
- try { fs.renameSync(tmp, file); break } catch (error) {
290
- if (!['EPERM', 'EBUSY', 'EACCES'].includes(error?.code) || attempt >= 5) throw error
291
- Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 8 * (attempt + 1))
292
- }
293
- }
294
- } catch (error) {
295
- try { fs.rmSync(tmp, { force: true }) } catch {}
296
- throw error
297
- }
298
- }
299
-
300
- /**
301
- * 重建补洞会把旧回合追加到文件尾部,打乱"文件序 = 时间序"的不变量(读取侧
302
- * readIncrement/tailSlice/pruneHead 都按文件序工作)。这里把有效记录按 seq 排回
303
- * 升序;坏行 seq 未知,原样保留在尾部。仅在确实乱序时重写,append-only 常态零开销。
304
- */
305
- function sortTurnLogBySeq(sessionId) {
306
- const scan = scanTurnLog(sessionId)
307
- if (scan.unreadable || scan.entries.length === 0) return
308
- const valid = []
309
- const bad = []
310
- for (const entry of scan.entries) {
311
- if (safeSeqRange(entry.record)) valid.push(entry)
312
- else bad.push(entry)
313
- }
314
- let ordered = true
315
- for (let i = 1; i < valid.length; i += 1) {
316
- if (valid[i].record.seq[0] < valid[i - 1].record.seq[0]) { ordered = false; break }
317
- }
318
- if (ordered) return
319
- valid.sort((a, b) => a.record.seq[0] - b.record.seq[0] || a.record.seq[1] - b.record.seq[1])
320
- try {
321
- rewriteTurnLog(scan.file, [...valid, ...bad].map((entry) => entry.raw))
322
- } catch (error) {
323
- warn(`turn-log sort failed for ${logFileName(sessionId)}: ${error?.message || error}`)
324
- }
325
- }
326
-
327
- /**
328
- * 追加一行回合记录。记录器是旁路:任何失败只 warn,绝不抛给主会话(§3.2)。
329
- * 落盘后顺带做一次头部裁剪(§3.4:只裁已结算段)。
330
- */
331
- export function recordTurn(sessionId, record) {
332
- try {
333
- if (!safeSeqRange(record)) {
334
- warn(`turn-log record rejected for ${logFileName(sessionId)}: missing a valid seq range`)
335
- return null
336
- }
337
- const line = JSON.stringify({ ...record, at: record.at || stamp() })
338
- fs.appendFileSync(turnLogPath(sessionId), line + '\n', 'utf8')
339
- try {
340
- let lastSleepSeq = null
341
- try { lastSleepSeq = getSessionBinding(String(sessionId))?.lastSleepSeq ?? null } catch {}
342
- pruneHead(String(sessionId), TURNLOG_KEEP_CHARS, lastSleepSeq)
343
- } catch {}
344
- return line
345
- } catch (error) {
346
- warn(`turn-log append failed for ${logFileName(String(sessionId))}: ${error?.message || error}`)
347
- return null
348
- }
349
- }
350
-
351
- /**
352
- * 自 afterSeq 之后的增量回合。回合是不可分单位(§3.3):记录天然整回合,
353
- * 所以按 seqStart > afterSeq 过滤即可,不存在半回合重复读。
354
- * 注意:worker 增量入口 loadWorkerIncrement 用 readIncrement(-1) 读全量后自行按
355
- * seqEnd > lastSleepSeq 过滤(跨骑回合整条收),本函数的 afterSeq 过滤只服务直接调用方。
356
- */
357
- export function readIncrement(sessionId, afterSeq) {
358
- const scan = scanTurnLog(sessionId)
359
- const after = Number(afterSeq)
360
- const from = Number.isSafeInteger(after) ? after : -1
361
- const records = scan.entries
362
- .map((entry) => entry.record)
363
- .filter((record) => {
364
- const range = safeSeqRange(record)
365
- return range && range[0] > from
366
- })
367
- return { records, badLines: scan.badLines }
368
- }
369
-
370
- /**
371
- * 校验 [fromSeq, throughSeq] 的日志覆盖与连续性(§3.3)。
372
- * missingRanges 是窗口内没有被任何记录盖住的 seq 子区间(含记录之间的空洞)。
373
- */
374
- export function verifyGap(sessionId, fromSeq, throughSeq) {
375
- const scan = scanTurnLog(sessionId)
376
- const from = Number(fromSeq)
377
- const through = Number(throughSeq)
378
- if (!Number.isSafeInteger(from) || !Number.isSafeInteger(through) || from > through) {
379
- return { ok: true, missingRanges: [], badLines: scan.badLines }
380
- }
381
- const covered = scan.entries
382
- .map((entry) => entry.record)
383
- .map((record) => safeSeqRange(record))
384
- .filter((range) => range && range[1] >= from && range[0] <= through)
385
- .sort((a, b) => a[0] - b[0])
386
- const missingRanges = []
387
- let cursor = from
388
- for (const [start, end] of covered) {
389
- if (start > cursor) missingRanges.push([cursor, start - 1])
390
- if (end + 1 > cursor) cursor = end + 1
391
- }
392
- if (cursor <= through) missingRanges.push([cursor, through])
393
- return { ok: missingRanges.length === 0, missingRanges, badLines: scan.badLines }
394
- }
395
-
396
- /**
397
- * 用宿主事件重建 [fromSeq, throughSeq] 的缺失回合(§3.3:绝不假设日志完整)。
398
- * 只补洞:与现有记录重叠的区间跳过,重复调用幂等。
399
- */
400
- export function rebuildRange(sessionId, fromSeq, throughSeq, events, options = {}) {
401
- const from = Number(fromSeq)
402
- const through = Number(throughSeq)
403
- if (!Number.isSafeInteger(from) || !Number.isSafeInteger(through) || from > through) {
404
- return { ok: false, rebuilt: 0, reason: 'invalid range' }
405
- }
406
- const slice = (Array.isArray(events) ? events : []).filter((event) => {
407
- const seq = Number(event?.seq)
408
- return Number.isSafeInteger(seq) && seq >= from && seq <= through
409
- })
410
- const candidates = buildTurnRecords(slice, options).filter((record) => {
411
- const [start, end] = safeSeqRange(record) || [NaN, NaN]
412
- return start >= from && end <= through
413
- })
414
- const scan = scanTurnLog(sessionId)
415
- const existing = scan.entries.map((entry) => safeSeqRange(entry.record)).filter(Boolean)
416
- let rebuilt = 0
417
- for (const record of candidates) {
418
- const [start, end] = record.seq
419
- if (existing.some(([s, e]) => start <= e && end >= s)) continue
420
- if (recordTurn(sessionId, record)) rebuilt += 1
421
- }
422
- // 补洞追加的旧回合可能落在文件尾部,排回时间序,保证增量/尾部/裁剪口径一致。
423
- if (rebuilt > 0) sortTurnLogBySeq(sessionId)
424
- return { ok: true, rebuilt, requested: [from, through], records: candidates }
425
- }
426
-
427
- /**
428
- * 取尾部整回合,总量(序列化后)≤ maxChars。回合不可分:最新一回合即使超预算
429
- * 也整条返回(截了就不是完整证据);再往前按预算装。
430
- */
431
- export function tailSlice(sessionId, maxChars) {
432
- const scan = scanTurnLog(sessionId)
433
- const budget = Math.max(0, Number(maxChars) || 0)
434
- const records = []
435
- let used = 0
436
- for (let i = scan.entries.length - 1; i >= 0; i--) {
437
- const record = scan.entries[i].record
438
- const range = record ? safeSeqRange(record) : null
439
- if (!range) continue
440
- const len = JSON.stringify(record).length
441
- if (records.length > 0 && used + len > budget) break
442
- records.unshift(record)
443
- used += len
444
- }
445
- return { records, text: records.map((record) => JSON.stringify(record)).join('\n'), chars: used, badLines: scan.badLines }
446
- }
447
-
448
- /**
449
- * 头部裁剪(§3.4):只裁 seqEnd ≤ lastSleepSeq 的**已结算**记录。未结算段超上限
450
- * 就让文件暂超——裁进未结算区间等于把缺口推进需要重建的地方,绝不这么干。
451
- * 坏行 seq 未知、无法证明已结算,同样保留。
452
- */
453
- export function pruneHead(sessionId, keepChars = TURNLOG_KEEP_CHARS, lastSleepSeq = null) {
454
- const scan = scanTurnLog(sessionId)
455
- const charsOf = (entry) => entry.raw.length + 1
456
- const total = scan.entries.reduce((sum, entry) => sum + charsOf(entry), 0)
457
- const budget = Number(keepChars) > 0 ? Number(keepChars) : TURNLOG_KEEP_CHARS
458
- const settledThrough = Number.isSafeInteger(Number(lastSleepSeq)) ? Number(lastSleepSeq) : null
459
- if (scan.unreadable || total <= budget || settledThrough === null) {
460
- // 读失败绝不重写;没超预算不用动;没有结算游标时整份日志都是未结算段,暂超就暂超。
461
- return { pruned: 0, charsBefore: total, charsAfter: total, unreadable: scan.unreadable }
462
- }
463
- const keep = [...scan.entries]
464
- let keptTotal = total
465
- let pruned = 0
466
- while (keep.length > 0 && keptTotal > budget) {
467
- const range = keep[0].record ? safeSeqRange(keep[0].record) : null
468
- if (!range || range[1] > settledThrough) break // 未结算/坏行:到此为止
469
- keptTotal -= charsOf(keep[0])
470
- keep.shift()
471
- pruned += 1
472
- }
473
- if (pruned === 0) return { pruned: 0, charsBefore: total, charsAfter: total }
474
- try {
475
- rewriteTurnLog(scan.file, keep.map((entry) => entry.raw))
476
- } catch (error) {
477
- warn(`turn-log head prune failed for ${logFileName(sessionId)}: ${error?.message || error}`)
478
- return { pruned: 0, charsBefore: total, charsAfter: total, error: String(error?.message || error) }
479
- }
480
- const charsAfter = keep.reduce((sum, entry) => sum + charsOf(entry), 0)
481
- return { pruned, charsBefore: total, charsAfter }
482
- }
483
-
484
- /**
485
- * 休眠 GC(§3.4):日志无未结算增量(max seqEnd ≤ lastSleepSeq)且会话 ≥30 天
486
- * 无活动 → 删文件。缓存级操作;复活后交接尾部/增量走重建路径自动补。
487
- * 两个条件都满足才删:有未结算增量(整理没做完)的日志是增量来源,保留。
488
- */
489
- export function gcTurnLogs(bindings, { now = Date.now(), olderThanDays = TURNLOG_GC_DAYS, dryRun = false } = {}) {
490
- const deleted = []
491
- const kept = []
492
- const days = Number(olderThanDays) > 0 ? Number(olderThanDays) : TURNLOG_GC_DAYS
493
- for (const binding of Array.isArray(bindings) ? bindings : []) {
494
- const sessionId = binding?.sessionId
495
- if (!sessionId) continue
496
- let stat = null
497
- try { stat = fs.statSync(turnLogPath(sessionId)) } catch { continue } // 没有日志,无事可做
498
- const lastTurnAt = Date.parse(binding.lastTurnAt || '') || 0
499
- if (!(lastTurnAt > 0) || now - lastTurnAt < days * 86_400_000) {
500
- kept.push({ sessionId, reason: 'recent-activity', lastTurnAt: binding.lastTurnAt || null })
501
- continue
502
- }
503
- const lastSleepSeq = Number(binding.lastSleepSeq)
504
- if (!Number.isSafeInteger(lastSleepSeq) || lastSleepSeq < 0) {
505
- kept.push({ sessionId, reason: 'never-settled', size: stat.size })
506
- continue
507
- }
508
- const scan = scanTurnLog(sessionId)
509
- if (scan.unreadable) {
510
- kept.push({ sessionId, reason: 'unreadable' })
511
- continue
512
- }
513
- let maxSeqEnd = -1
514
- for (const entry of scan.entries) {
515
- const range = entry.record ? safeSeqRange(entry.record) : null
516
- if (range && range[1] > maxSeqEnd) maxSeqEnd = range[1]
517
- }
518
- if (maxSeqEnd > lastSleepSeq) {
519
- kept.push({ sessionId, reason: 'unsettled-increment', maxSeqEnd, lastSleepSeq })
520
- continue
521
- }
522
- if (dryRun) {
523
- deleted.push(sessionId)
524
- continue
525
- }
526
- try {
527
- fs.rmSync(scan.file, { force: true })
528
- deleted.push(sessionId)
529
- } catch (error) {
530
- kept.push({ sessionId, reason: `delete-failed: ${error?.code || error}` })
531
- }
532
- }
533
- return { deleted, kept }
534
- }
535
-
536
- export function deleteTurnLog(sessionId) {
537
- try {
538
- const file = turnLogPath(sessionId)
539
- fs.rmSync(file, { force: true })
540
- return { ok: true, file }
541
- } catch (error) {
542
- warn(`turn-log delete failed for ${logFileName(String(sessionId))}: ${error?.message || error}`)
543
- return { ok: false, error: String(error?.message || error) }
544
- }
545
- }
1
+ import fs from 'node:fs'
2
+ import path from 'node:path'
3
+ import crypto from 'node:crypto'
4
+ import { dataDir, ensureDir, warn, redactSecrets, isSafeId, shortHash, stamp } from './paths.js'
5
+ import { getSettings, getSessionBinding } from './state.js'
6
+
7
+ // 增量回合日志。
8
+ //
9
+ // 定位是纯旁路缓存,不是账本(§0 铁律 1):每行一个宿主 turn/end 的 seq 区间,
10
+ // 记录规则与 condenseEvents 同口径(§3.1,不发明新规则)。任何失败只 warn,
11
+ // 绝不影响主会话;正确性永远由宿主转录 + 缺口重建兜底(§3.3)。
12
+ //
13
+ // 三层 caps(§3.1):user/model 各 2000 字全保;工具行 160 字;整条记录 4000 字
14
+ // 总闸——超预算只砍 tools 行(按序装、砍尾并标注省略数),user/model 不动。
15
+
16
+ export const TURNLOG_USER_MODEL_CHARS = 2000
17
+ export const TURNLOG_TOOL_LINE_CHARS = 160
18
+ export const TURNLOG_TOOL_ARGS_CHARS = 120
19
+ export const TURNLOG_RECORD_CHARS = 4000
20
+ export const TURNLOG_KEEP_CHARS = 200_000
21
+ export const TURNLOG_GC_DAYS = 30
22
+
23
+ // 编码域的「修改重点」几乎全在工具行里(命令、错误签名、diff 参数),160 字只留得下
24
+ // 开头。给编码域更宽的单项额度,整条记录仍受 4000 字总闸约束(先砍 tools 尾)。
25
+ export const TURNLOG_TOOL_LINE_CHARS_CODING = 600
26
+ export const TURNLOG_TOOL_ARGS_CHARS_CODING = 400
27
+
28
+ const DEFAULT_TOOL_LIMITS = Object.freeze({
29
+ toolLineChars: TURNLOG_TOOL_LINE_CHARS,
30
+ toolArgsChars: TURNLOG_TOOL_ARGS_CHARS,
31
+ })
32
+
33
+ export function turnLogLimits(domain) {
34
+ return String(domain) === 'coding'
35
+ ? { toolLineChars: TURNLOG_TOOL_LINE_CHARS_CODING, toolArgsChars: TURNLOG_TOOL_ARGS_CHARS_CODING }
36
+ : DEFAULT_TOOL_LIMITS
37
+ }
38
+
39
+ const TURNLOG_SUFFIX = '.turnlog.jsonl'
40
+
41
+ function truncate(text, max) {
42
+ const s = String(text || '')
43
+ return s.length > max ? `${s.slice(0, max)}…` : s
44
+ }
45
+
46
+ function firstLine(text) {
47
+ const s = String(text || '').replace(/\r/g, '')
48
+ const nl = s.indexOf('\n')
49
+ return (nl >= 0 ? s.slice(0, nl) : s).trim()
50
+ }
51
+
52
+ function textOfBlocks(blocks) {
53
+ if (typeof blocks === 'string') return blocks.trim()
54
+ if (!Array.isArray(blocks)) return ''
55
+ return blocks
56
+ .filter((b) => b?.type === 'text' && typeof b.text === 'string')
57
+ .map((b) => b.text)
58
+ .join('')
59
+ .trim()
60
+ }
61
+
62
+ function argsText(value) {
63
+ if (value == null) return ''
64
+ return typeof value === 'string' ? value : JSON.stringify(value)
65
+ }
66
+
67
+ /**
68
+ * 会话 id 直接拼进文件名。宿主 id 是安全字符集;防御性兜底把任何奇怪 id 哈希成
69
+ * 固定名(缓存可重建,哈希碰撞的最坏结果是两段日志混在一个文件里,可接受)。
70
+ */
71
+ function logFileName(sessionId) {
72
+ const raw = String(sessionId || '')
73
+ return (isSafeId(raw) ? raw : `sid-${shortHash(raw)}`) + TURNLOG_SUFFIX
74
+ }
75
+
76
+ export function turnLogPath(sessionId) {
77
+ return path.join(ensureDir(path.join(dataDir(), 'sessions')), logFileName(sessionId))
78
+ }
79
+
80
+ function safeSeqRange(record) {
81
+ const seq = record?.seq
82
+ if (!Array.isArray(seq) || seq.length !== 2) return null
83
+ const start = Number(seq[0])
84
+ const end = Number(seq[1])
85
+ if (!Number.isSafeInteger(start) || !Number.isSafeInteger(end) || start < 0 || end < start) return null
86
+ return [start, end]
87
+ }
88
+
89
+ // —— 记录规则(§3.1,与 condenseEvents 同口径) ————————————————
90
+
91
+ function toolCallIdOfResult(event) {
92
+ const message = event?.data?.message
93
+ return [message?.callId, message?.toolCallId, message?.source?.callId]
94
+ .find((value) => typeof value === 'string' && value) || null
95
+ }
96
+
97
+ function toolLine(name, args, status, errorText, limits = DEFAULT_TOOL_LIMITS) {
98
+ const lineChars = limits.toolLineChars ?? TURNLOG_TOOL_LINE_CHARS
99
+ const argsChars = limits.toolArgsChars ?? TURNLOG_TOOL_ARGS_CHARS
100
+ const head = `${name || '?'}${args ? `(${truncate(args, argsChars)})` : ''}`
101
+ const tail = status === 'ok' ? ' → 成功'
102
+ : status === 'error' ? ` → 失败: ${firstLine(errorText)}`
103
+ : ' → 无结果'
104
+ // 工具行与对话文本同一待遇:先脱敏再截断(§3.1「记录时应用 redactSecrets」)。
105
+ return truncate(redactSecrets(head + tail), lineChars)
106
+ }
107
+
108
+ /**
109
+ * 'summary' 档工具行:调用 + 结果按 callId 配对。tool/call 事件是权威侧
110
+ * (assistant 消息里的 tool-call 块是同一次调用的副本,与 condenseEvents 一致,不单独成行)。
111
+ */
112
+ function summaryToolLines(events, limits = DEFAULT_TOOL_LIMITS) {
113
+ const lines = []
114
+ const calls = new Map() // callId -> line entry
115
+ for (const event of events) {
116
+ if (event?.type !== 'tool/call') continue
117
+ const id = typeof event?.data?.callId === 'string' && event.data.callId ? event.data.callId : null
118
+ if (id && calls.has(id)) continue // 同一 callId 双写去重
119
+ const entry = { name: event?.data?.name || '?', args: argsText(event?.data?.arguments), status: 'pending', errorText: '' }
120
+ if (id) calls.set(id, entry)
121
+ lines.push(entry)
122
+ }
123
+ for (const event of events) {
124
+ if (event?.type !== 'tool/result') continue
125
+ const id = toolCallIdOfResult(event)
126
+ const entry = id ? calls.get(id) : null
127
+ const isError = event?.data?.message?.isError === true
128
+ const text = textOfBlocks(event?.data?.message?.content)
129
+ if (entry && !entry.done) {
130
+ entry.status = isError ? 'error' : 'ok'
131
+ entry.errorText = text
132
+ entry.done = true
133
+ } else if (!entry) {
134
+ // 结果先于调用可见(乱序/旧 fixture):结果行自己成行,错误结果在 errors 档也要可见。
135
+ lines.push({ name: '?', args: '', status: isError ? 'error' : 'ok', errorText: text, done: true })
136
+ }
137
+ }
138
+ return lines.map((entry) => toolLine(entry.name, entry.args, entry.status === 'pending' ? 'none' : entry.status, entry.errorText, limits))
139
+ }
140
+
141
+ /** 'errors' 档:只收 isError 的工具结果行——失败尝试是漏网事实的最廉价来源(§3.1)。 */
142
+ function errorToolLines(events, limits = DEFAULT_TOOL_LIMITS) {
143
+ const names = new Map()
144
+ for (const event of events) {
145
+ if (event?.type !== 'tool/call') continue
146
+ const id = typeof event?.data?.callId === 'string' && event.data.callId ? event.data.callId : null
147
+ if (id && !names.has(id)) names.set(id, event?.data?.name || '?')
148
+ }
149
+ const lines = []
150
+ for (const event of events) {
151
+ if (event?.type !== 'tool/result' || event?.data?.message?.isError !== true) continue
152
+ const id = toolCallIdOfResult(event)
153
+ const name = (id && names.get(id)) || '?'
154
+ lines.push(toolLine(name, '', 'error', textOfBlocks(event?.data?.message?.content), limits))
155
+ }
156
+ return lines
157
+ }
158
+
159
+ function joinParts(parts, max) {
160
+ return truncate(redactSecrets(parts.join('\n')), max)
161
+ }
162
+
163
+ /**
164
+ * 把一段宿主事件流转成回合记录数组(纯函数:同输入同输出)。
165
+ *
166
+ * 分组与 candidateSeedEvents 同款:turn/start 开组(或流中途无组时首个事件开组),
167
+ * turn/end 封组;尾部没有 turn/end 的半回合不产出记录(未结算)。
168
+ * options.tools 覆盖设置档(测试用),默认读 consolidationTurnLogTools。
169
+ */
170
+ export function buildTurnRecords(events, options = {}) {
171
+ let toolsMode = options.tools
172
+ if (toolsMode === undefined) {
173
+ try { toolsMode = getSettings().consolidationTurnLogTools } catch { toolsMode = undefined }
174
+ }
175
+ if (toolsMode !== 'errors' && toolsMode !== 'summary') toolsMode = 'none'
176
+ const limits = {
177
+ toolLineChars: Number(options.toolLineChars) > 0 ? Number(options.toolLineChars) : TURNLOG_TOOL_LINE_CHARS,
178
+ toolArgsChars: Number(options.toolArgsChars) > 0 ? Number(options.toolArgsChars) : TURNLOG_TOOL_ARGS_CHARS,
179
+ }
180
+
181
+ const groups = []
182
+ let current = null
183
+ for (const event of Array.isArray(events) ? events : []) {
184
+ if (!event || typeof event.type !== 'string') continue
185
+ if (event.type === 'turn/start' || current === null) {
186
+ current = []
187
+ groups.push(current)
188
+ }
189
+ current.push(event)
190
+ if (event.type === 'turn/end') current = null
191
+ }
192
+
193
+ const records = []
194
+ for (const group of groups) {
195
+ const end = group[group.length - 1]
196
+ if (end?.type !== 'turn/end') continue // 未闭合的半回合留给下一窗对账重建
197
+ const startSeq = Number(group[0]?.seq)
198
+ const endSeq = Number(end?.seq)
199
+ if (!Number.isSafeInteger(startSeq) || !Number.isSafeInteger(endSeq) || startSeq < 0 || endSeq < startSeq) continue
200
+
201
+ const userParts = []
202
+ const modelParts = []
203
+ let scene = null
204
+ for (const event of group) {
205
+ if (event.type === 'user/message') {
206
+ // 只收真人消息:插件注入 / 调度 / 心跳一律不记(§3.1 过滤口径)。
207
+ if (event?.data?.source?.kind !== 'user') continue
208
+ const text = textOfBlocks(event?.data?.content)
209
+ if (text) userParts.push(text)
210
+ const sceneTime = event?.data?.sceneTime
211
+ if (typeof sceneTime === 'string' && sceneTime.trim()) scene = sceneTime
212
+ } else if (event.type === 'assistant/message') {
213
+ // assistant 只收 text 块:reasoning / tool-call 块不进对话记录。
214
+ const text = textOfBlocks(event?.data?.message?.content)
215
+ if (text) modelParts.push(text)
216
+ }
217
+ }
218
+
219
+ const record = {
220
+ seq: [startSeq, endSeq],
221
+ at: Number.isFinite(end?.time) ? new Date(end.time).toISOString() : null,
222
+ scene,
223
+ user: joinParts(userParts, TURNLOG_USER_MODEL_CHARS),
224
+ model: joinParts(modelParts, TURNLOG_USER_MODEL_CHARS),
225
+ }
226
+ const kind = end?.data?.reason?.kind
227
+ if (kind && kind !== 'completed') record.interrupted = true
228
+
229
+ let toolLines = []
230
+ if (toolsMode === 'summary') toolLines = summaryToolLines(group, limits)
231
+ else if (toolsMode === 'errors') toolLines = errorToolLines(group, limits)
232
+ if (toolLines.length > 0) record.tools = toolLines
233
+
234
+ // 空回合(纯注入/心跳/无对话无工具)不落行。
235
+ if (!record.user && !record.model && !(record.tools && record.tools.length > 0)) continue
236
+
237
+ applyRecordCap(record)
238
+ records.push(record)
239
+ }
240
+ return records
241
+ }
242
+
243
+ /** 4000 字总闸:超预算只砍 tools 尾部(user/model 在各自 2000 内全保)。 */
244
+ function applyRecordCap(record) {
245
+ const tools = record.tools
246
+ if (!Array.isArray(tools) || tools.length === 0) return
247
+ if (JSON.stringify(record).length <= TURNLOG_RECORD_CHARS) return
248
+ const marker = (n) => `…[另有 ${n} 条工具调用已省略]`
249
+ let kept = tools.length
250
+ while (kept >= 0) {
251
+ record.tools = tools.slice(0, kept)
252
+ if (kept < tools.length) record.tools.push(marker(tools.length - kept))
253
+ if (JSON.stringify(record).length <= TURNLOG_RECORD_CHARS || kept === 0) return
254
+ kept -= 1
255
+ }
256
+ }
257
+
258
+ // —— 落盘与读取 ————————————————————————————————————————————
259
+
260
+ function scanTurnLog(sessionId) {
261
+ const file = turnLogPath(sessionId)
262
+ let raw
263
+ try {
264
+ raw = fs.readFileSync(file, 'utf8')
265
+ } catch (error) {
266
+ // ENOENT = 空日志(正常);其他读失败当作不可读:绝不在没读到的地方重写。
267
+ if (error?.code !== 'ENOENT') warn(`turn-log read failed for ${logFileName(sessionId)}: ${error?.message || error}`)
268
+ return { file, entries: [], badLines: 0, unreadable: error?.code !== 'ENOENT' }
269
+ }
270
+ const entries = []
271
+ let badLines = 0
272
+ for (const line of raw.split('\n')) {
273
+ const trimmed = line.trim()
274
+ if (!trimmed) continue
275
+ let record = null
276
+ try { record = JSON.parse(trimmed) } catch { badLines += 1 }
277
+ entries.push({ raw: trimmed, record })
278
+ }
279
+ return { file, entries, badLines, unreadable: false }
280
+ }
281
+
282
+ /** 坏行原样保留地原子重写(Windows 上 rename 的 EPERM/EBUSY 重试用 paths.js 同款节奏)。 */
283
+ function rewriteTurnLog(file, lines) {
284
+ ensureDir(path.dirname(file))
285
+ const tmp = `${file}.tmp-${process.pid}-${crypto.randomUUID()}`
286
+ try {
287
+ fs.writeFileSync(tmp, lines.length > 0 ? lines.join('\n') + '\n' : '', 'utf8')
288
+ for (let attempt = 0; ; attempt++) {
289
+ try { fs.renameSync(tmp, file); break } catch (error) {
290
+ if (!['EPERM', 'EBUSY', 'EACCES'].includes(error?.code) || attempt >= 5) throw error
291
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 8 * (attempt + 1))
292
+ }
293
+ }
294
+ } catch (error) {
295
+ try { fs.rmSync(tmp, { force: true }) } catch {}
296
+ throw error
297
+ }
298
+ }
299
+
300
+ /**
301
+ * 重建补洞会把旧回合追加到文件尾部,打乱"文件序 = 时间序"的不变量(读取侧
302
+ * readIncrement/tailSlice/pruneHead 都按文件序工作)。这里把有效记录按 seq 排回
303
+ * 升序;坏行 seq 未知,原样保留在尾部。仅在确实乱序时重写,append-only 常态零开销。
304
+ */
305
+ function sortTurnLogBySeq(sessionId) {
306
+ const scan = scanTurnLog(sessionId)
307
+ if (scan.unreadable || scan.entries.length === 0) return
308
+ const valid = []
309
+ const bad = []
310
+ for (const entry of scan.entries) {
311
+ if (safeSeqRange(entry.record)) valid.push(entry)
312
+ else bad.push(entry)
313
+ }
314
+ let ordered = true
315
+ for (let i = 1; i < valid.length; i += 1) {
316
+ if (valid[i].record.seq[0] < valid[i - 1].record.seq[0]) { ordered = false; break }
317
+ }
318
+ if (ordered) return
319
+ valid.sort((a, b) => a.record.seq[0] - b.record.seq[0] || a.record.seq[1] - b.record.seq[1])
320
+ try {
321
+ rewriteTurnLog(scan.file, [...valid, ...bad].map((entry) => entry.raw))
322
+ } catch (error) {
323
+ warn(`turn-log sort failed for ${logFileName(sessionId)}: ${error?.message || error}`)
324
+ }
325
+ }
326
+
327
+ /**
328
+ * 追加一行回合记录。记录器是旁路:任何失败只 warn,绝不抛给主会话(§3.2)。
329
+ * 落盘后顺带做一次头部裁剪(§3.4:只裁已结算段)。
330
+ */
331
+ export function recordTurn(sessionId, record) {
332
+ try {
333
+ if (!safeSeqRange(record)) {
334
+ warn(`turn-log record rejected for ${logFileName(sessionId)}: missing a valid seq range`)
335
+ return null
336
+ }
337
+ const line = JSON.stringify({ ...record, at: record.at || stamp() })
338
+ fs.appendFileSync(turnLogPath(sessionId), line + '\n', 'utf8')
339
+ try {
340
+ let lastSleepSeq = null
341
+ try { lastSleepSeq = getSessionBinding(String(sessionId))?.lastSleepSeq ?? null } catch {}
342
+ pruneHead(String(sessionId), TURNLOG_KEEP_CHARS, lastSleepSeq)
343
+ } catch {}
344
+ return line
345
+ } catch (error) {
346
+ warn(`turn-log append failed for ${logFileName(String(sessionId))}: ${error?.message || error}`)
347
+ return null
348
+ }
349
+ }
350
+
351
+ /**
352
+ * 自 afterSeq 之后的增量回合。回合是不可分单位(§3.3):记录天然整回合,
353
+ * 所以按 seqStart > afterSeq 过滤即可,不存在半回合重复读。
354
+ * 注意:worker 增量入口 loadWorkerIncrement 用 readIncrement(-1) 读全量后自行按
355
+ * seqEnd > lastSleepSeq 过滤(跨骑回合整条收),本函数的 afterSeq 过滤只服务直接调用方。
356
+ */
357
+ export function readIncrement(sessionId, afterSeq) {
358
+ const scan = scanTurnLog(sessionId)
359
+ const after = Number(afterSeq)
360
+ const from = Number.isSafeInteger(after) ? after : -1
361
+ const records = scan.entries
362
+ .map((entry) => entry.record)
363
+ .filter((record) => {
364
+ const range = safeSeqRange(record)
365
+ return range && range[0] > from
366
+ })
367
+ return { records, badLines: scan.badLines }
368
+ }
369
+
370
+ /**
371
+ * 校验 [fromSeq, throughSeq] 的日志覆盖与连续性(§3.3)。
372
+ * missingRanges 是窗口内没有被任何记录盖住的 seq 子区间(含记录之间的空洞)。
373
+ */
374
+ export function verifyGap(sessionId, fromSeq, throughSeq) {
375
+ const scan = scanTurnLog(sessionId)
376
+ const from = Number(fromSeq)
377
+ const through = Number(throughSeq)
378
+ if (!Number.isSafeInteger(from) || !Number.isSafeInteger(through) || from > through) {
379
+ return { ok: true, missingRanges: [], badLines: scan.badLines }
380
+ }
381
+ const covered = scan.entries
382
+ .map((entry) => entry.record)
383
+ .map((record) => safeSeqRange(record))
384
+ .filter((range) => range && range[1] >= from && range[0] <= through)
385
+ .sort((a, b) => a[0] - b[0])
386
+ const missingRanges = []
387
+ let cursor = from
388
+ for (const [start, end] of covered) {
389
+ if (start > cursor) missingRanges.push([cursor, start - 1])
390
+ if (end + 1 > cursor) cursor = end + 1
391
+ }
392
+ if (cursor <= through) missingRanges.push([cursor, through])
393
+ return { ok: missingRanges.length === 0, missingRanges, badLines: scan.badLines }
394
+ }
395
+
396
+ /**
397
+ * 用宿主事件重建 [fromSeq, throughSeq] 的缺失回合(§3.3:绝不假设日志完整)。
398
+ * 只补洞:与现有记录重叠的区间跳过,重复调用幂等。
399
+ */
400
+ export function rebuildRange(sessionId, fromSeq, throughSeq, events, options = {}) {
401
+ const from = Number(fromSeq)
402
+ const through = Number(throughSeq)
403
+ if (!Number.isSafeInteger(from) || !Number.isSafeInteger(through) || from > through) {
404
+ return { ok: false, rebuilt: 0, reason: 'invalid range' }
405
+ }
406
+ const slice = (Array.isArray(events) ? events : []).filter((event) => {
407
+ const seq = Number(event?.seq)
408
+ return Number.isSafeInteger(seq) && seq >= from && seq <= through
409
+ })
410
+ const candidates = buildTurnRecords(slice, options).filter((record) => {
411
+ const [start, end] = safeSeqRange(record) || [NaN, NaN]
412
+ return start >= from && end <= through
413
+ })
414
+ const scan = scanTurnLog(sessionId)
415
+ const existing = scan.entries.map((entry) => safeSeqRange(entry.record)).filter(Boolean)
416
+ let rebuilt = 0
417
+ for (const record of candidates) {
418
+ const [start, end] = record.seq
419
+ if (existing.some(([s, e]) => start <= e && end >= s)) continue
420
+ if (recordTurn(sessionId, record)) rebuilt += 1
421
+ }
422
+ // 补洞追加的旧回合可能落在文件尾部,排回时间序,保证增量/尾部/裁剪口径一致。
423
+ if (rebuilt > 0) sortTurnLogBySeq(sessionId)
424
+ return { ok: true, rebuilt, requested: [from, through], records: candidates }
425
+ }
426
+
427
+ /**
428
+ * 取尾部整回合,总量(序列化后)≤ maxChars。回合不可分:最新一回合即使超预算
429
+ * 也整条返回(截了就不是完整证据);再往前按预算装。
430
+ */
431
+ export function tailSlice(sessionId, maxChars) {
432
+ const scan = scanTurnLog(sessionId)
433
+ const budget = Math.max(0, Number(maxChars) || 0)
434
+ const records = []
435
+ let used = 0
436
+ for (let i = scan.entries.length - 1; i >= 0; i--) {
437
+ const record = scan.entries[i].record
438
+ const range = record ? safeSeqRange(record) : null
439
+ if (!range) continue
440
+ const len = JSON.stringify(record).length
441
+ if (records.length > 0 && used + len > budget) break
442
+ records.unshift(record)
443
+ used += len
444
+ }
445
+ return { records, text: records.map((record) => JSON.stringify(record)).join('\n'), chars: used, badLines: scan.badLines }
446
+ }
447
+
448
+ /**
449
+ * 头部裁剪(§3.4):只裁 seqEnd ≤ lastSleepSeq 的**已结算**记录。未结算段超上限
450
+ * 就让文件暂超——裁进未结算区间等于把缺口推进需要重建的地方,绝不这么干。
451
+ * 坏行 seq 未知、无法证明已结算,同样保留。
452
+ */
453
+ export function pruneHead(sessionId, keepChars = TURNLOG_KEEP_CHARS, lastSleepSeq = null) {
454
+ const scan = scanTurnLog(sessionId)
455
+ const charsOf = (entry) => entry.raw.length + 1
456
+ const total = scan.entries.reduce((sum, entry) => sum + charsOf(entry), 0)
457
+ const budget = Number(keepChars) > 0 ? Number(keepChars) : TURNLOG_KEEP_CHARS
458
+ const settledThrough = Number.isSafeInteger(Number(lastSleepSeq)) ? Number(lastSleepSeq) : null
459
+ if (scan.unreadable || total <= budget || settledThrough === null) {
460
+ // 读失败绝不重写;没超预算不用动;没有结算游标时整份日志都是未结算段,暂超就暂超。
461
+ return { pruned: 0, charsBefore: total, charsAfter: total, unreadable: scan.unreadable }
462
+ }
463
+ const keep = [...scan.entries]
464
+ let keptTotal = total
465
+ let pruned = 0
466
+ while (keep.length > 0 && keptTotal > budget) {
467
+ const range = keep[0].record ? safeSeqRange(keep[0].record) : null
468
+ if (!range || range[1] > settledThrough) break // 未结算/坏行:到此为止
469
+ keptTotal -= charsOf(keep[0])
470
+ keep.shift()
471
+ pruned += 1
472
+ }
473
+ if (pruned === 0) return { pruned: 0, charsBefore: total, charsAfter: total }
474
+ try {
475
+ rewriteTurnLog(scan.file, keep.map((entry) => entry.raw))
476
+ } catch (error) {
477
+ warn(`turn-log head prune failed for ${logFileName(sessionId)}: ${error?.message || error}`)
478
+ return { pruned: 0, charsBefore: total, charsAfter: total, error: String(error?.message || error) }
479
+ }
480
+ const charsAfter = keep.reduce((sum, entry) => sum + charsOf(entry), 0)
481
+ return { pruned, charsBefore: total, charsAfter }
482
+ }
483
+
484
+ /**
485
+ * 休眠 GC(§3.4):日志无未结算增量(max seqEnd ≤ lastSleepSeq)且会话 ≥30 天
486
+ * 无活动 → 删文件。缓存级操作;复活后交接尾部/增量走重建路径自动补。
487
+ * 两个条件都满足才删:有未结算增量(整理没做完)的日志是增量来源,保留。
488
+ */
489
+ export function gcTurnLogs(bindings, { now = Date.now(), olderThanDays = TURNLOG_GC_DAYS, dryRun = false } = {}) {
490
+ const deleted = []
491
+ const kept = []
492
+ const days = Number(olderThanDays) > 0 ? Number(olderThanDays) : TURNLOG_GC_DAYS
493
+ for (const binding of Array.isArray(bindings) ? bindings : []) {
494
+ const sessionId = binding?.sessionId
495
+ if (!sessionId) continue
496
+ let stat = null
497
+ try { stat = fs.statSync(turnLogPath(sessionId)) } catch { continue } // 没有日志,无事可做
498
+ const lastTurnAt = Date.parse(binding.lastTurnAt || '') || 0
499
+ if (!(lastTurnAt > 0) || now - lastTurnAt < days * 86_400_000) {
500
+ kept.push({ sessionId, reason: 'recent-activity', lastTurnAt: binding.lastTurnAt || null })
501
+ continue
502
+ }
503
+ const lastSleepSeq = Number(binding.lastSleepSeq)
504
+ if (!Number.isSafeInteger(lastSleepSeq) || lastSleepSeq < 0) {
505
+ kept.push({ sessionId, reason: 'never-settled', size: stat.size })
506
+ continue
507
+ }
508
+ const scan = scanTurnLog(sessionId)
509
+ if (scan.unreadable) {
510
+ kept.push({ sessionId, reason: 'unreadable' })
511
+ continue
512
+ }
513
+ let maxSeqEnd = -1
514
+ for (const entry of scan.entries) {
515
+ const range = entry.record ? safeSeqRange(entry.record) : null
516
+ if (range && range[1] > maxSeqEnd) maxSeqEnd = range[1]
517
+ }
518
+ if (maxSeqEnd > lastSleepSeq) {
519
+ kept.push({ sessionId, reason: 'unsettled-increment', maxSeqEnd, lastSleepSeq })
520
+ continue
521
+ }
522
+ if (dryRun) {
523
+ deleted.push(sessionId)
524
+ continue
525
+ }
526
+ try {
527
+ fs.rmSync(scan.file, { force: true })
528
+ deleted.push(sessionId)
529
+ } catch (error) {
530
+ kept.push({ sessionId, reason: `delete-failed: ${error?.code || error}` })
531
+ }
532
+ }
533
+ return { deleted, kept }
534
+ }
535
+
536
+ export function deleteTurnLog(sessionId) {
537
+ try {
538
+ const file = turnLogPath(sessionId)
539
+ fs.rmSync(file, { force: true })
540
+ return { ok: true, file }
541
+ } catch (error) {
542
+ warn(`turn-log delete failed for ${logFileName(String(sessionId))}: ${error?.message || error}`)
543
+ return { ok: false, error: String(error?.message || error) }
544
+ }
545
+ }