@jjh32456/longlive 0.0.0-stage → 2.0.0

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 (331) hide show
  1. package/CHANGELOG.md +235 -0
  2. package/LICENSE +21 -0
  3. package/QUICKSTART.md +362 -0
  4. package/README.en.md +64 -0
  5. package/README.md +256 -2
  6. package/SPEC.md +211 -0
  7. package/build-info.json +1665 -0
  8. package/cordis.patch.yml +208 -0
  9. package/docs/A1-MIGRATION.md +75 -0
  10. package/docs/ANSWER-GUARD.md +92 -0
  11. package/docs/ARCHITECTURE.md +128 -0
  12. package/docs/AUTO-RECALL-WIRING.md +115 -0
  13. package/docs/AUTO-RECALL.md +237 -0
  14. package/docs/CONCEPTS.md +143 -0
  15. package/docs/CONFIG.md +839 -0
  16. package/docs/ERRORS.md +271 -0
  17. package/docs/FAQ.md +186 -0
  18. package/docs/FEATURES.md +579 -0
  19. package/docs/INDEX-FRESHNESS.md +21 -0
  20. package/docs/METRICS.md +244 -0
  21. package/docs/MIGRATION-1.6.0.md +220 -0
  22. package/docs/OPERATIONS.md +439 -0
  23. package/docs/PANEL-INTEGRATION.md +190 -0
  24. package/docs/PRIVACY.md +88 -0
  25. package/docs/QUICKSTART.md +155 -0
  26. package/docs/RAW-INDEX-POLICY.md +7 -0
  27. package/docs/README.en.md +48 -0
  28. package/docs/RESIDENT-WATCHER.md +90 -0
  29. package/docs/SESSION-WATCH.md +214 -0
  30. package/docs/TOOLS.md +184 -0
  31. package/docs/TROUBLESHOOTING.md +329 -0
  32. package/icon.svg +11 -0
  33. package/lib/client.js +436 -0
  34. package/locale/en.json +6 -0
  35. package/locale/zh.json +6 -0
  36. package/package.json +163 -4
  37. package/runbook.md +343 -0
  38. package/scripts/archive-digest-build.mjs +668 -0
  39. package/scripts/auto-truncate-run.ps1 +752 -0
  40. package/scripts/backfill-auto-cards.mjs +98 -0
  41. package/scripts/edges-build.mjs +1003 -0
  42. package/scripts/index-maintain.mjs +39 -0
  43. package/scripts/index-reconcile.mjs +49 -0
  44. package/scripts/index-status.mjs +28 -0
  45. package/scripts/install-resident-watcher.ps1 +15 -0
  46. package/scripts/install-session-watch.ps1 +332 -0
  47. package/scripts/install-surgery-task.ps1 +174 -0
  48. package/scripts/lib/auto-truncate-run.ps1 +512 -0
  49. package/scripts/lib/session-watch-fixture.mjs +207 -0
  50. package/scripts/longlive-doctor.mjs +578 -0
  51. package/scripts/metrics-read.mjs +79 -0
  52. package/scripts/metrics-sample.mjs +215 -0
  53. package/scripts/migrate-180.mjs +163 -0
  54. package/scripts/migrate-200.mjs +8 -0
  55. package/scripts/migrate-a1-legacy.mjs +62 -0
  56. package/scripts/migrate-lifecycle.mjs +157 -0
  57. package/scripts/pack.mjs +392 -0
  58. package/scripts/recall-index-build.mjs +128 -0
  59. package/scripts/recall-links-build.mjs +420 -0
  60. package/scripts/rescore-cards.mjs +36 -0
  61. package/scripts/resident-watcher-status.ps1 +15 -0
  62. package/scripts/resident-watcher.ps1 +643 -0
  63. package/scripts/session-watch-drill.mjs +553 -0
  64. package/scripts/session-watch-status.ps1 +146 -0
  65. package/scripts/session-watch.mjs +1367 -0
  66. package/scripts/surgery-inspect.mjs +122 -0
  67. package/scripts/surgery-run.cmd +34 -0
  68. package/scripts/truncate-cli.mjs +279 -0
  69. package/scripts/unattended-surgery.ps1 +1019 -0
  70. package/scripts/uninstall-resident-watcher.ps1 +15 -0
  71. package/scripts/uninstall-session-watch.ps1 +192 -0
  72. package/scripts/verify-card-anchors.mjs +138 -0
  73. package/scripts/watch-loop.ps1 +916 -0
  74. package/src/actions/audit.js +125 -0
  75. package/src/actions/evidence.js +122 -0
  76. package/src/actions/fs.js +162 -0
  77. package/src/activity/index.js +873 -0
  78. package/src/activity/model.js +351 -0
  79. package/src/activity/store.js +786 -0
  80. package/src/activity/summary.js +180 -0
  81. package/src/activity/thinking.js +191 -0
  82. package/src/adapters/constants.js +11 -0
  83. package/src/adapters/engram/data/aliases.json +51 -0
  84. package/src/adapters/engram/data/policy.json +8 -0
  85. package/src/adapters/engram/data/routing-rules.json +546 -0
  86. package/src/adapters/engram/index.js +278 -0
  87. package/src/adapters/registry.js +315 -0
  88. package/src/answer/audit.js +238 -0
  89. package/src/answer/claim-guard.mjs +234 -0
  90. package/src/answer/evidence.js +30 -0
  91. package/src/answer/guard.js +1370 -0
  92. package/src/answer/index.js +1086 -0
  93. package/src/answer/query.js +111 -0
  94. package/src/answer/second-hop.mjs +101 -0
  95. package/src/auto-truncate-status.js +164 -0
  96. package/src/auto-truncate.js +1181 -0
  97. package/src/autoprocedure/candidate.js +342 -0
  98. package/src/autoprocedure/config.js +122 -0
  99. package/src/autoprocedure/evidence.js +345 -0
  100. package/src/autoprocedure/index.js +83 -0
  101. package/src/autoprocedure/ledger.js +329 -0
  102. package/src/autoprocedure/lint.js +232 -0
  103. package/src/autoprocedure/llm.js +409 -0
  104. package/src/autoprocedure/locks.js +102 -0
  105. package/src/autoprocedure/paths.js +39 -0
  106. package/src/autoprocedure/privacy.js +87 -0
  107. package/src/autoprocedure/rules.js +288 -0
  108. package/src/autoprocedure/runtime.js +718 -0
  109. package/src/autoprocedure/session-reader.js +328 -0
  110. package/src/backup.js +310 -0
  111. package/src/bus/bus.mjs +1446 -0
  112. package/src/codec.js +269 -0
  113. package/src/compaction/cut-engine.js +44 -0
  114. package/src/compaction/engine-core.js +1237 -0
  115. package/src/compaction/entry.js +228 -0
  116. package/src/compaction.js +230 -0
  117. package/src/conclusion.js +366 -0
  118. package/src/config.js +835 -0
  119. package/src/d6/runtime.js +517 -0
  120. package/src/d6/surface.js +181 -0
  121. package/src/deps.js +189 -0
  122. package/src/engine-status.js +141 -0
  123. package/src/features.js +1035 -0
  124. package/src/handoff/index.js +1077 -0
  125. package/src/handoff/model.js +1058 -0
  126. package/src/handoff/store.js +1233 -0
  127. package/src/heartbeat.js +385 -0
  128. package/src/home.js +16 -0
  129. package/src/host-version.js +280 -0
  130. package/src/hot-truncate-diag.js +98 -0
  131. package/src/identity/card-marker.js +281 -0
  132. package/src/identity/handover.js +845 -0
  133. package/src/identity/index.js +337 -0
  134. package/src/identity/inject-position.js +133 -0
  135. package/src/identity/writeback.js +344 -0
  136. package/src/identity.js +118 -0
  137. package/src/index.js +647 -0
  138. package/src/lifecycle/gap-clocks.js +364 -0
  139. package/src/lifecycle/index.js +269 -0
  140. package/src/lifecycle/proactive.js +1426 -0
  141. package/src/live-target.js +212 -0
  142. package/src/live.js +1603 -0
  143. package/src/log-rotation.js +153 -0
  144. package/src/memory/a1-migration.js +190 -0
  145. package/src/memory/activity-capture.js +229 -0
  146. package/src/memory/anchor-fallback.js +116 -0
  147. package/src/memory/anchors.js +194 -0
  148. package/src/memory/archive-cold-state.mjs +794 -0
  149. package/src/memory/archive-staging.mjs +305 -0
  150. package/src/memory/archive.mjs +415 -0
  151. package/src/memory/audit-records.js +222 -0
  152. package/src/memory/auto-cards.js +441 -0
  153. package/src/memory/capture-host.js +297 -0
  154. package/src/memory/capture.js +496 -0
  155. package/src/memory/card-anchors.js +203 -0
  156. package/src/memory/card-priority.js +110 -0
  157. package/src/memory/cards.js +425 -0
  158. package/src/memory/catchup.mjs +534 -0
  159. package/src/memory/conclusion-distill.js +381 -0
  160. package/src/memory/conclusion-drafts.js +243 -0
  161. package/src/memory/conflicts.js +1060 -0
  162. package/src/memory/consolidate.js +834 -0
  163. package/src/memory/decay.js +311 -0
  164. package/src/memory/distill.js +485 -0
  165. package/src/memory/event-index.js +1826 -0
  166. package/src/memory/evidence-chain.js +295 -0
  167. package/src/memory/evidence.js +213 -0
  168. package/src/memory/filter-runner.js +555 -0
  169. package/src/memory/filter.js +1035 -0
  170. package/src/memory/forget-v2.js +680 -0
  171. package/src/memory/forget.js +531 -0
  172. package/src/memory/frames-activation.js +249 -0
  173. package/src/memory/frontmatter.js +454 -0
  174. package/src/memory/fts-query.js +342 -0
  175. package/src/memory/governance.js +604 -0
  176. package/src/memory/index-freshness.js +234 -0
  177. package/src/memory/index.js +435 -0
  178. package/src/memory/l2-gate.js +169 -0
  179. package/src/memory/land.mjs +743 -0
  180. package/src/memory/lifecycle.js +235 -0
  181. package/src/memory/lock.js +121 -0
  182. package/src/memory/maintenance.js +1149 -0
  183. package/src/memory/manifest.js +245 -0
  184. package/src/memory/memory-health.mjs +607 -0
  185. package/src/memory/migrate-200.js +1681 -0
  186. package/src/memory/migrate-lifecycle.js +1808 -0
  187. package/src/memory/migrate.js +139 -0
  188. package/src/memory/paths.js +229 -0
  189. package/src/memory/procedure-candidate.mjs +377 -0
  190. package/src/memory/procedure.js +982 -0
  191. package/src/memory/prospective-memory.mjs +362 -0
  192. package/src/memory/provenance.js +119 -0
  193. package/src/memory/recall-feedback.mjs +406 -0
  194. package/src/memory/recall-v2.js +218 -0
  195. package/src/memory/recall.js +357 -0
  196. package/src/memory/reconcile.js +265 -0
  197. package/src/memory/records.js +433 -0
  198. package/src/memory/reinforce.js +281 -0
  199. package/src/memory/retention.js +162 -0
  200. package/src/memory/review.js +124 -0
  201. package/src/memory/state.js +279 -0
  202. package/src/memory/tiers.js +168 -0
  203. package/src/memory/topic-phrases.js +73 -0
  204. package/src/memory/trust.js +97 -0
  205. package/src/memory/turn-budget.mjs +290 -0
  206. package/src/memory/version-chain.js +264 -0
  207. package/src/memory/wake-bridge.mjs +2999 -0
  208. package/src/memory/wal.js +137 -0
  209. package/src/memory/working-frame.js +779 -0
  210. package/src/metrics/classify.mjs +191 -0
  211. package/src/metrics/estimate.mjs +108 -0
  212. package/src/metrics/index.mjs +204 -0
  213. package/src/metrics/measure.mjs +462 -0
  214. package/src/metrics/prestep-latency.mjs +307 -0
  215. package/src/metrics/store.mjs +264 -0
  216. package/src/original.js +294 -0
  217. package/src/policy/threshold-policy.js +224 -0
  218. package/src/policy-profile.js +463 -0
  219. package/src/recall/anaphora.mjs +87 -0
  220. package/src/recall/archive-config.mjs +130 -0
  221. package/src/recall/archive-fallback.mjs +390 -0
  222. package/src/recall/archive-search.mjs +428 -0
  223. package/src/recall/archive-state.mjs +588 -0
  224. package/src/recall/brain.mjs +501 -0
  225. package/src/recall/cards.mjs +202 -0
  226. package/src/recall/current-line.mjs +110 -0
  227. package/src/recall/edges.js +398 -0
  228. package/src/recall/embedding.mjs +698 -0
  229. package/src/recall/entities.mjs +112 -0
  230. package/src/recall/explain.mjs +443 -0
  231. package/src/recall/force-policy.mjs +138 -0
  232. package/src/recall/gate-log.mjs +280 -0
  233. package/src/recall/gate-metrics.mjs +191 -0
  234. package/src/recall/index.js +1337 -0
  235. package/src/recall/inject-order.mjs +279 -0
  236. package/src/recall/link-recall.mjs +183 -0
  237. package/src/recall/links.mjs +696 -0
  238. package/src/recall/privacy.mjs +208 -0
  239. package/src/recall/recall-core.mjs +810 -0
  240. package/src/recall/shared-visibility.js +302 -0
  241. package/src/recall/time-normalizer.mjs +196 -0
  242. package/src/recall/turn-budget-inject.mjs +154 -0
  243. package/src/retention/cold-gate.mjs +146 -0
  244. package/src/retention/config.js +163 -0
  245. package/src/retention/index.js +801 -0
  246. package/src/role/activation.js +191 -0
  247. package/src/role/attention.js +318 -0
  248. package/src/role/base.js +36 -0
  249. package/src/role/channels.js +423 -0
  250. package/src/role/index.js +425 -0
  251. package/src/role/interfaces.js +115 -0
  252. package/src/role/personality.js +370 -0
  253. package/src/role/readers.js +151 -0
  254. package/src/role/relationships.js +477 -0
  255. package/src/role/store.js +202 -0
  256. package/src/role/writeprotect.js +373 -0
  257. package/src/router/aliases.json +182 -0
  258. package/src/router/background/agent-runner.mjs +239 -0
  259. package/src/router/background/anchor.mjs +323 -0
  260. package/src/router/background/audit.mjs +337 -0
  261. package/src/router/background/budget-ledger.mjs +648 -0
  262. package/src/router/background/host-sim.mjs +451 -0
  263. package/src/router/background/index.mjs +81 -0
  264. package/src/router/background/memory.mjs +63 -0
  265. package/src/router/background/mock-llm.mjs +203 -0
  266. package/src/router/background/queue.mjs +224 -0
  267. package/src/router/background/retry.mjs +255 -0
  268. package/src/router/background/router.mjs +1459 -0
  269. package/src/router/background/stream.mjs +276 -0
  270. package/src/router/background/tool-policy.mjs +255 -0
  271. package/src/router/design-headings.json +221 -0
  272. package/src/router/face/config.mjs +155 -0
  273. package/src/router/face/context.mjs +284 -0
  274. package/src/router/face/face.mjs +466 -0
  275. package/src/router/face/identity.mjs +130 -0
  276. package/src/router/face/index.mjs +65 -0
  277. package/src/router/face/journal.mjs +119 -0
  278. package/src/router/face/llm.mjs +252 -0
  279. package/src/router/face/outbox.mjs +153 -0
  280. package/src/router/face/paths.mjs +54 -0
  281. package/src/router/judge.mjs +987 -0
  282. package/src/router/policies/generic.json +131 -0
  283. package/src/router/route.js +1766 -0
  284. package/src/router/router.mjs +535 -0
  285. package/src/router/routing-rules.json +816 -0
  286. package/src/router/run-sim.mjs +530 -0
  287. package/src/router/runtime.js +569 -0
  288. package/src/router/service/apply.mjs +1218 -0
  289. package/src/router/service/board.mjs +712 -0
  290. package/src/router/service/caller.mjs +131 -0
  291. package/src/router/service/config.mjs +361 -0
  292. package/src/router/service/context.mjs +314 -0
  293. package/src/router/service/hint.mjs +668 -0
  294. package/src/router/service/lease.mjs +494 -0
  295. package/src/router/service/live.mjs +251 -0
  296. package/src/router/service/lock.mjs +550 -0
  297. package/src/router/service/merge.mjs +255 -0
  298. package/src/router/service/model-resolve.mjs +350 -0
  299. package/src/router/service/paths.mjs +168 -0
  300. package/src/router/service/proposals.mjs +1461 -0
  301. package/src/router/service/queue.mjs +477 -0
  302. package/src/router/service/reconcile.mjs +271 -0
  303. package/src/router/service/service.mjs +2998 -0
  304. package/src/router/service/sources.mjs +352 -0
  305. package/src/router/service/status.mjs +520 -0
  306. package/src/router/service/store.mjs +476 -0
  307. package/src/router/service/ticklock.mjs +239 -0
  308. package/src/router/service/tokens.mjs +95 -0
  309. package/src/router/service/tools.mjs +248 -0
  310. package/src/router/service/wake.mjs +544 -0
  311. package/src/router/service/wal.mjs +685 -0
  312. package/src/router/shadow.mjs +821 -0
  313. package/src/surgery-recovery.js +1909 -0
  314. package/src/tool-output.js +485 -0
  315. package/src/tools.js +3262 -0
  316. package/src/truncate-visible.js +2416 -0
  317. package/src/truncate.js +999 -0
  318. package/src/ui/actions.js +1312 -0
  319. package/src/ui/flags.js +259 -0
  320. package/src/ui/panel-api.js +371 -0
  321. package/src/ui/panel-auth.js +251 -0
  322. package/src/ui/panel-integrity.js +243 -0
  323. package/src/ui/routes-readonly.js +759 -0
  324. package/src/ui/routes.js +284 -0
  325. package/src/util/append-store.js +368 -0
  326. package/src/util/local-day.js +30 -0
  327. package/src/util/redact.js +227 -0
  328. package/src/util/stale-locks.js +148 -0
  329. package/src/version.js +99 -0
  330. package/test/fixtures/pre-step-container.mjs +100 -0
  331. package/test/p1_probe.mjs +97 -0
@@ -0,0 +1,2416 @@
1
+ // @local/dsh-longlive — visible-conversation truncation
2
+ //
3
+ // `session_truncate` keeps the visible conversation byte-identical and only
4
+ // drops log-only rows. This module is the other tool: it deliberately removes
5
+ // whole turns from the *front* of the conversation, renumbers `seq`, and
6
+ // writes a synthetic archive card in front of the retained turns. The point is
7
+ // to make the context actually smaller (the host derives messages from the
8
+ // Surface, so removed turns stop being sent to the model).
9
+ //
10
+ // Safety rules:
11
+ // * a turn is never split (cut only at `turn/start`);
12
+ // * the first user-authored message survives (carried into the retained
13
+ // segment when its original turn is dropped);
14
+ // * the host's protected system prompt is copied to the new head;
15
+ // * bytes are written tmp -> fsync -> rename, with an inflight record that a
16
+ // later run can use to roll back a crash;
17
+ // * a seeded session (one that forked another log, header.isSeeded) keeps
18
+ // exactly one inherited `session/end-seed` marker at seq 0, because the
19
+ // host decoder derives the inherited cut from the *last* such marker and
20
+ // refuses a seeded header without one ("released v2 seeded Session lacks an
21
+ // inherited end-seed marker"); the marker event is also the only carrier of
22
+ // that number — the v4 header line has no inheritedEventCount field;
23
+ // * every failure restores the backup and throws a specific code.
24
+
25
+ import fs from 'node:fs';
26
+ import path from 'node:path';
27
+ import crypto from 'node:crypto';
28
+ import { injectedMarkerPatterns } from './adapters/registry.js';
29
+
30
+ import {
31
+ compressFrame,
32
+ parseSession,
33
+ encodeSession,
34
+ assertContiguous,
35
+ deriveMessagesDigest,
36
+ foldSurface,
37
+ MESSAGE_TYPES,
38
+ sha256,
39
+ } from './codec.js';
40
+ import { sessionError, formatBytes, isInboxEvent, assertNotLive } from './truncate.js';
41
+ import { ensureBackup, verifyBackup, sha256File } from './backup.js';
42
+ import { appendHotTruncateDiag, hotTruncateDiagOptions } from './hot-truncate-diag.js';
43
+
44
+ export const VISIBLE_CONFIRM_WORD = 'TRUNCATE-VISIBLE';
45
+ export const DEFAULT_KEEP_TURNS = 12;
46
+ export const DEFAULT_KEEP_TOKENS = 80_000;
47
+ export const INFLIGHT_FILENAME = '.truncate-visible-inflight.json';
48
+ export const LEDGER_FILENAME = 'truncate-visible.json';
49
+ export const ARCHIVE_DIR_SUFFIX = '.archive';
50
+ export const DEFAULT_EVENTS_PER_FRAME = 2000;
51
+ // 0.8.0-rc.11 (defect A): the carried first-user message is a *pointer* to the
52
+ // archive, not a second copy of it. rc.10 copied the whole text, so a
53
+ // 15,524-character prompt became a 35,738-byte synthetic card; the cut then
54
+ // still measured 8,633 tokens and the next turn wrote another request.
55
+ export const DEFAULT_FIRST_USER_CAP_CHARS = 4000;
56
+ // How many extra, earlier cuts to try when the retained window cannot be
57
+ // stabilized at the first boundary. Each retry drops one more whole turn.
58
+ export const DEFAULT_BOUNDARY_RETRIES = 3;
59
+ export const FIRST_USER_CARRY_HEADER = '[会话起点 · 已归档]';
60
+ // The rewritten log is accepted when it lands within 5% of keepTokens; the
61
+ // planner still targets keepTokens exactly and only uses this as a ceiling.
62
+ const BUDGET_SLACK = 1.05;
63
+
64
+ export const ERROR_CODES = Object.freeze({
65
+ NOT_FOUND: 'VISIBLE_NOT_FOUND',
66
+ BAD_ARGUMENT: 'VISIBLE_BAD_ARGUMENT',
67
+ IS_BACKUP: 'VISIBLE_IS_BACKUP',
68
+ CONFIRM_REQUIRED: 'VISIBLE_CONFIRM_REQUIRED',
69
+ RECENT_WRITE: 'VISIBLE_RECENT_WRITE',
70
+ LOCKED: 'VISIBLE_LOCKED',
71
+ NO_PROTECTED_HEAD: 'VISIBLE_NO_PROTECTED_HEAD',
72
+ REPLACEMENT_STRADDLES_CUT: 'VISIBLE_REPLACEMENT_STRADDLES_CUT',
73
+ NO_BOUNDARY: 'VISIBLE_NO_BOUNDARY',
74
+ TOKEN_BUDGET: 'VISIBLE_TOKEN_BUDGET',
75
+ TMP_VERIFY: 'VISIBLE_TMP_VERIFY',
76
+ POST_VERIFY: 'VISIBLE_POST_VERIFY',
77
+ CHANGED: 'VISIBLE_CHANGED',
78
+ BACKUP_MISSING: 'VISIBLE_BACKUP_MISSING',
79
+ BACKUP_MISMATCH: 'VISIBLE_BACKUP_MISMATCH',
80
+ INFLIGHT_CORRUPT: 'VISIBLE_INFLIGHT_CORRUPT',
81
+ INFLIGHT_BACKUP_MISSING: 'VISIBLE_INFLIGHT_BACKUP_MISSING',
82
+ ARCHIVE_EXISTS: 'VISIBLE_ARCHIVE_EXISTS',
83
+ FAULT_INJECTED: 'VISIBLE_FAULT_INJECTED',
84
+ ARCHIVE_VERIFY: 'VISIBLE_ARCHIVE_VERIFY',
85
+ });
86
+
87
+ function visibleError(code, message, cause) {
88
+ return sessionError(code, message, cause);
89
+ }
90
+
91
+ // ---------------------------------------------------------------------------
92
+ // small helpers
93
+ // ---------------------------------------------------------------------------
94
+
95
+ export function estimateTokensFromChars(chars) {
96
+ return Math.ceil(Math.max(0, chars) / 4);
97
+ }
98
+
99
+ function resolvePositiveInt(name, value, fallback) {
100
+ const resolved = value ?? fallback;
101
+ if (!(Number.isInteger(resolved) && resolved >= 1)) {
102
+ throw visibleError(ERROR_CODES.BAD_ARGUMENT,
103
+ `${name} must be an integer >= 1 (got ${JSON.stringify(value)})`);
104
+ }
105
+ return resolved;
106
+ }
107
+
108
+ /**
109
+ * Build the synthetic "first user message" row that survives a cut.
110
+ *
111
+ * 0.8.0-rc.11 (defect A): the row is capped at `firstUserCapChars` (default
112
+ * 4,000). Above the cap it keeps the prefix and points at the archive, because
113
+ * the archive already holds the dropped prefix byte-for-byte. rc.10 copied the
114
+ * whole text, so one 15,524-character prompt produced a 35,738-byte card and
115
+ * the cut still exceeded keepTokens, which retriggered on the very next turn.
116
+ *
117
+ * The cap counts characters of the original text (not of the marker/header).
118
+ * A surrogate pair at the boundary is never split.
119
+ */
120
+ export function capFirstUserText(original, options = {}) {
121
+ const capChars = resolvePositiveInt('firstUserCapChars',
122
+ options.firstUserCapChars, DEFAULT_FIRST_USER_CAP_CHARS);
123
+ const source = typeof original === 'string' ? original : String(original ?? '');
124
+ const archivePath = options.archivePath ?? '(归档文件)';
125
+ if (source.length <= capChars) {
126
+ return {
127
+ text: `${FIRST_USER_CARRY_HEADER}\n${source}`,
128
+ capped: false,
129
+ capChars,
130
+ originalChars: source.length,
131
+ keptChars: source.length,
132
+ note: null,
133
+ };
134
+ }
135
+ let cut = capChars;
136
+ const last = source.charCodeAt(cut - 1);
137
+ if (last >= 0xd800 && last <= 0xdbff) cut -= 1; // do not split a surrogate pair
138
+ const note = `…[首条消息过长,原文见 ${archivePath}]`;
139
+ return {
140
+ text: `${FIRST_USER_CARRY_HEADER}\n${source.slice(0, cut)}\n${note}`,
141
+ capped: true,
142
+ capChars,
143
+ originalChars: source.length,
144
+ keptChars: cut,
145
+ note,
146
+ };
147
+ }
148
+
149
+
150
+ function messageOf(event) {
151
+ if (!event || typeof event !== 'object') return null;
152
+ if (event.type === 'user/message') return event.data ?? null;
153
+ if (event.type === 'system/message' || event.type === 'developer/message'
154
+ || event.type === 'assistant/message' || event.type === 'tool/result') {
155
+ return event.data?.message ?? null;
156
+ }
157
+ return null;
158
+ }
159
+
160
+ function textOfMessage(message) {
161
+ if (!message || !Array.isArray(message.content)) return '';
162
+ const parts = [];
163
+ for (const block of message.content) {
164
+ if (block && block.type === 'text' && typeof block.text === 'string') parts.push(block.text);
165
+ }
166
+ return parts.join('\n');
167
+ }
168
+
169
+ function textOfEvent(event) {
170
+ return textOfMessage(messageOf(event));
171
+ }
172
+
173
+ // Text signatures of blocks the host *injects* as user/message rows. They are
174
+ // prompt material, not something the user typed, so they must never be quoted
175
+ // back as "the first thing the user said".
176
+ //
177
+ // This list is the fallback, not the primary rule: the host gives real
178
+ // client-originated messages a `source.clientTimeZone` field (2723/2723 across
179
+ // the 182-session survey behind 0.7.0), while programmatic splices and the
180
+ // 2026-11-01 surgical checkpoint have none. See isUserAuthoredMessage below.
181
+ export const USER_TEXT_MARKERS = Object.freeze([
182
+ /This is an automatically generated checkpoint/i,
183
+ /Current runtime context/i,
184
+ /<current_user_request\b/i,
185
+ ...injectedMarkerPatterns(),
186
+ /<system-reminder\b/i,
187
+ /\[Compressed conversation section\]/i,
188
+ /background job[\s\S]{0,200}?\bfinished\b/i,
189
+ /<available_skills\b/i,
190
+ // Adjacent host/plugin envelopes observed in real logs; kept here so a future
191
+ // wrapper cannot silently become "the user's first message" either.
192
+ /You are the Team Lead/i,
193
+ /Dream reviewed/i,
194
+ /\[bili\]/i,
195
+ ]);
196
+
197
+ /** True when `text` carries a known injected-block signature. */
198
+ export function looksLikeInjectedText(text) {
199
+ if (typeof text !== 'string' || text === '') return false;
200
+ return USER_TEXT_MARKERS.some((pattern) => pattern.test(text));
201
+ }
202
+
203
+ /**
204
+ * Decide whether one session event is a message the *user* actually authored.
205
+ *
206
+ * Order matters:
207
+ * 1. only `user/message` events qualify;
208
+ * 2. `source.kind` must be `user` (not runtime-context, skill-catalog,
209
+ * compact-checkpoint, schedule, goal, tool-jobs, ...);
210
+ * 3. positive host evidence wins: a non-empty `source.clientTimeZone` means
211
+ * the message was pushed through the client RPC and carries the client's
212
+ * zone. Every one of the 2723 real user messages in the 182-session
213
+ * survey has it; the only `kind:"user"` message with an `rpcId` but no
214
+ * zone was the 2026-11-01 surgical checkpoint;
215
+ * 4. without that field, fall back to the text blacklist — a match is proof
216
+ * of machine text;
217
+ * 5. anything still ambiguous returns false. Never carry what cannot be
218
+ * proven to be the user's own words (a missed carry is recoverable; a
219
+ * machine block presented as the user's words is not).
220
+ */
221
+ export function isUserAuthoredMessage(event) {
222
+ if (!event || event.type !== 'user/message') return false;
223
+ const data = event.data;
224
+ if (!data || typeof data !== 'object') return false;
225
+ const source = data.source;
226
+ if (!source || typeof source !== 'object' || source.kind !== 'user') return false;
227
+ if (typeof source.clientTimeZone === 'string' && source.clientTimeZone.trim() !== '') return true;
228
+ if (looksLikeInjectedText(textOfEvent(event))) return false;
229
+ // 1.8.9: the ACP bridge delivers real client messages with an rpcId but no
230
+ // clientTimeZone (source {kind:"user", rpcId:"aa.<id>"}). Treating them as
231
+ // machine text left every bridged session with no user-authored turn: the
232
+ // boundary guard walked back onto a compaction checkpoint and every cut was
233
+ // infeasible. The injected-text blacklist above still wins, so machine
234
+ // blocks that reuse a kind:"user" row stay rejected.
235
+ if (typeof source.rpcId === 'string' && source.rpcId.trim() !== '') return true;
236
+ // No structured user-origin evidence and no disqualifying text signature:
237
+ // still not provable, so it is not carried.
238
+ return false;
239
+ }
240
+
241
+ function eventChars(event) {
242
+ try {
243
+ return JSON.stringify(event?.data ?? {}).length;
244
+ } catch {
245
+ return 0;
246
+ }
247
+ }
248
+
249
+ function eventBytes(event) {
250
+ return Buffer.byteLength(JSON.stringify(event), 'utf8') + 1;
251
+ }
252
+
253
+ function messageTokens(event) {
254
+ const message = messageOf(event);
255
+ if (!message) return 0;
256
+ return estimateTokensFromChars(JSON.stringify(message).length);
257
+ }
258
+
259
+ function eventsTokens(events) {
260
+ let total = 0;
261
+ for (const event of events) if (MESSAGE_TYPES.has(event.type)) total += messageTokens(event);
262
+ return total;
263
+ }
264
+
265
+ function eventsMessages(events) {
266
+ return events.filter((event) => MESSAGE_TYPES.has(event.type)).length;
267
+ }
268
+
269
+ function eventsBytes(events) {
270
+ let total = 0;
271
+ for (const event of events) total += eventBytes(event);
272
+ return total;
273
+ }
274
+
275
+ function firstLine(text, max = 80) {
276
+ const line = String(text ?? '').replace(/\s+/g, ' ').trim();
277
+ return line.length > max ? `${line.slice(0, max - 1)}…` : line;
278
+ }
279
+
280
+ function formatTime(ms) {
281
+ if (typeof ms !== 'number' || !Number.isFinite(ms)) return '?';
282
+ return new Date(ms).toISOString().replace('T', ' ').slice(0, 16) + 'Z';
283
+ }
284
+
285
+ function stampForFile(ms) {
286
+ // 20261102-080249, UTC; a stable, sortable archive name.
287
+ return new Date(ms).toISOString().replace(/[-:]/g, '').replace('T', '-').slice(0, 15);
288
+ }
289
+
290
+ function readSnapshot(sessionPath) {
291
+ const buf = fs.readFileSync(sessionPath);
292
+ const stat = fs.statSync(sessionPath);
293
+ return {
294
+ buf,
295
+ size: buf.length,
296
+ statSize: stat.size,
297
+ mtimeMs: stat.mtimeMs,
298
+ sha256: sha256(buf),
299
+ };
300
+ }
301
+
302
+ function assertUnchanged(sessionPath, snapshot) {
303
+ const stat = fs.statSync(sessionPath);
304
+ const now = sha256File(sessionPath);
305
+ if (stat.size !== snapshot.statSize || now !== snapshot.sha256) {
306
+ throw visibleError(ERROR_CODES.CHANGED,
307
+ `session log changed while planning (size ${snapshot.statSize} -> ${stat.size}, ` +
308
+ `sha256 ${snapshot.sha256.slice(0, 12)}… -> ${now.slice(0, 12)}…); refusing to overwrite`);
309
+ }
310
+ }
311
+
312
+ function writeDurable(file, buffer) {
313
+ const fd = fs.openSync(file, 'wx');
314
+ try {
315
+ fs.writeFileSync(fd, buffer);
316
+ fs.fsyncSync(fd);
317
+ } finally {
318
+ fs.closeSync(fd);
319
+ }
320
+ }
321
+
322
+ function fsyncDirBestEffort(dir) {
323
+ // Windows cannot fsync a directory; POSIX can. The rename itself is atomic.
324
+ try {
325
+ const fd = fs.openSync(dir, 'r');
326
+ try { fs.fsyncSync(fd); } finally { fs.closeSync(fd); }
327
+ } catch {
328
+ /* best effort only */
329
+ }
330
+ }
331
+
332
+ function removeIfExists(file) {
333
+ try { fs.rmSync(file, { force: true }); } catch { /* best effort */ }
334
+ }
335
+
336
+ export function inflightPathFor(sessionPath) {
337
+ return path.join(path.dirname(sessionPath), INFLIGHT_FILENAME);
338
+ }
339
+
340
+ export function archiveDirFor(sessionPath) {
341
+ return sessionPath + ARCHIVE_DIR_SUFFIX;
342
+ }
343
+
344
+ export function nextArchivePath(sessionPath, now = Date.now()) {
345
+ const dir = archiveDirFor(sessionPath);
346
+ const base = stampForFile(now);
347
+ let candidate = path.join(dir, `${base}.jsonl.zstd`);
348
+ let n = 2;
349
+ while (fs.existsSync(candidate)) {
350
+ candidate = path.join(dir, `${base}-${n}.jsonl.zstd`);
351
+ n += 1;
352
+ }
353
+ return candidate;
354
+ }
355
+
356
+ // ---------------------------------------------------------------------------
357
+ // turn model
358
+ // ---------------------------------------------------------------------------
359
+
360
+ /**
361
+ * Split events into turns. Anything before the first `turn/start` is a
362
+ * prelude (seed/permission events); it belongs to every prefix cut.
363
+ */
364
+ export function turnsOf(events) {
365
+ const turns = [];
366
+ let current = null;
367
+ for (let i = 0; i < events.length; i += 1) {
368
+ const event = events[i];
369
+ if (event.type === 'turn/start') {
370
+ current = {
371
+ turn: typeof event.data?.turn === 'number' ? event.data.turn : turns.length + 1,
372
+ startIndex: i,
373
+ endIndex: i,
374
+ startSeq: event.seq,
375
+ endSeq: event.seq,
376
+ startTime: typeof event.time === 'number' ? event.time : null,
377
+ endTime: typeof event.time === 'number' ? event.time : null,
378
+ events: 0,
379
+ messages: 0,
380
+ chars: 0,
381
+ bytes: 0,
382
+ tokens: 0,
383
+ firstUserIndex: null,
384
+ firstMessageIndex: null,
385
+ };
386
+ turns.push(current);
387
+ }
388
+ if (!current) continue;
389
+ current.endIndex = i;
390
+ current.endSeq = event.seq;
391
+ if (typeof event.time === 'number') current.endTime = event.time;
392
+ current.events += 1;
393
+ current.chars += eventChars(event);
394
+ current.bytes += eventBytes(event);
395
+ if (MESSAGE_TYPES.has(event.type)) {
396
+ current.messages += 1;
397
+ current.tokens += messageTokens(event);
398
+ if (current.firstMessageIndex === null) current.firstMessageIndex = i;
399
+ }
400
+ if (current.firstUserIndex === null && isUserAuthoredMessage(event)) current.firstUserIndex = i;
401
+ }
402
+ return { turns, preludeEvents: turns.length ? turns[0].startIndex : events.length };
403
+ }
404
+
405
+ function firstUserMessageIndex(events) {
406
+ for (let i = 0; i < events.length; i += 1) {
407
+ if (isUserAuthoredMessage(events[i])) return i;
408
+ }
409
+ return -1;
410
+ }
411
+
412
+ const NO_USER_MESSAGE_NOTE =
413
+ '未找到真人消息(no user-authored message matched the host/user-origin check; injected blocks are never carried)';
414
+
415
+ /**
416
+ * Cheap, side-effect-free estimate of a parsed log. Used by auto-truncate to
417
+ * decide whether a session is worth planning at all.
418
+ */
419
+ export function sessionEstimate(parsed) {
420
+ const events = parsed?.events ?? [];
421
+ const { turns } = turnsOf(events);
422
+ return {
423
+ bytes: parsed?.bytes ?? 0,
424
+ events: events.length,
425
+ messages: eventsMessages(events),
426
+ tokens: eventsTokens(events),
427
+ turns: turns.length,
428
+ userMessages: events.filter((event) => isUserAuthoredMessage(event)).length,
429
+ };
430
+ }
431
+
432
+ function protectedHeadIndex(events, cutIndex) {
433
+ for (let i = 0; i < cutIndex; i += 1) {
434
+ const event = events[i];
435
+ if (event.type === 'system/message' && event.data?.message?.source?.kind === 'system-prompt') return i;
436
+ }
437
+ return -1;
438
+ }
439
+
440
+ // buildVisibleTruncated() rewrites a cut log to start with a completed
441
+ // synthetic turn 1 that carries the protected system prompt. That turn is not
442
+ // part of the conversation, so a later plan must not count it against
443
+ // keepTurns: otherwise re-running a truncation drops one more real turn every
444
+ // time while still reporting keepTurns=N.
445
+ function syntheticHeadTurnCount(events, turns) {
446
+ if (!turns.length) return 0;
447
+ const first = turns[0];
448
+ if (first.startIndex !== 0 || first.firstUserIndex !== null) return 0;
449
+ if (events[0]?.type !== 'turn/start' || events[1]?.type !== 'step/start') return 0;
450
+ if (events[2]?.type !== 'system/message') return 0;
451
+ if (events[2].data?.message?.source?.kind !== 'system-prompt') return 0;
452
+ if (events[3]?.type !== 'step/end' || events[4]?.type !== 'turn/end') return 0;
453
+ return 1;
454
+ }
455
+
456
+ function turnSummary(turns, index, events) {
457
+ const turn = turns[index];
458
+ let firstMessage = '';
459
+ // Prefer the first message the user actually authored. A turn whose only
460
+ // "user" row is an injected runtime-context block has no human first line;
461
+ // never quote the injected block into the archive card or the report.
462
+ const candidate = turn.firstUserIndex ?? turn.firstMessageIndex;
463
+ if (candidate !== null) {
464
+ const text = textOfEvent(events[candidate]);
465
+ if (!looksLikeInjectedText(text)) firstMessage = firstLine(text, 70);
466
+ }
467
+ return {
468
+ turn: turn.turn,
469
+ startSeq: turn.startSeq,
470
+ endSeq: turn.endSeq,
471
+ startTime: turn.startTime,
472
+ endTime: turn.endTime,
473
+ events: turn.events,
474
+ messages: turn.messages,
475
+ tokens: turn.tokens,
476
+ bytes: turn.bytes,
477
+ firstMessage: firstMessage || '(无可见消息)',
478
+ };
479
+ }
480
+
481
+ function findCompactionStraddle(events, cutIndex) {
482
+ // A compaction group is compaction/start ... compaction/end. If the cut
483
+ // falls inside one, move it to the turn that owns the group's start.
484
+ for (let i = 0; i < cutIndex; i += 1) {
485
+ if (events[i].type !== 'compaction/start') continue;
486
+ for (let j = i + 1; j < events.length; j += 1) {
487
+ if (events[j].type === 'compaction/end') {
488
+ if (j >= cutIndex) return i;
489
+ break;
490
+ }
491
+ }
492
+ }
493
+ return -1;
494
+ }
495
+
496
+ /**
497
+ * 1.8.9: a retained event whose surfaceOp replaces a span that starts before
498
+ * the cut cannot be remapped; the build refuses it as
499
+ * VISIBLE_REPLACEMENT_STRADDLES_CUT. Return the *last* retained straddler so
500
+ * the caller can move the cut after it - dropping the checkpoint and the span
501
+ * it replaced, which can only reduce the post-cut size.
502
+ */
503
+ function findReplacementStraddle(events, cutIndex) {
504
+ let last = -1;
505
+ for (let i = cutIndex; i < events.length; i += 1) {
506
+ const op = events[i].surfaceOp;
507
+ if (!op || typeof op !== "object") continue;
508
+ const start = op.startSeq ?? op.start;
509
+ if (typeof start === "number" && start < cutIndex) last = i;
510
+ }
511
+ return last;
512
+ }
513
+
514
+ /**
515
+ * Pick the first retained turn index from the two mirrors of the request:
516
+ * keep the last `keepTurns` turns, and keep the last turns that fit
517
+ * `keepTokens`. The later boundary wins (fewer turns kept), then it is moved
518
+ * back until it starts on a turn that carries a user-authored message and does
519
+ * not fall inside a compaction group (1.8.9: if the next candidate would
520
+ * retain a replacement checkpoint that spans the cut, the boundary moves
521
+ * *after* that checkpoint instead).
522
+ *
523
+ * `extraDroppedTurns` is the 0.8.0-rc.11 downgrade lever: one more whole turn
524
+ * is dropped, and the same guard rules are applied again. It can never return
525
+ * a cut at or before the synthetic protected-head turn.
526
+ */
527
+ function chooseBoundary({ turns, events, keepTurns, keepTokens, extraDroppedTurns = 0 }) {
528
+ const syntheticHeadTurns = syntheticHeadTurnCount(events, turns);
529
+ const keepTurnsCut = Math.max(0, turns.length - syntheticHeadTurns - keepTurns);
530
+
531
+ // Walk backwards from the last turn while the suffix still fits the budget.
532
+ // This yields the *earliest* boundary that fits; `max` below then picks the
533
+ // later of the two boundaries as requested.
534
+ let tokenCut = turns.length - 1;
535
+ let tokenTotal = turns[tokenCut].tokens;
536
+ while (tokenCut > 0 && tokenTotal + turns[tokenCut - 1].tokens <= keepTokens) {
537
+ tokenCut -= 1;
538
+ tokenTotal += turns[tokenCut].tokens;
539
+ }
540
+
541
+ // `cutTurnIndex` is the first *kept* turn, so dropping more turns moves the
542
+ // boundary later. The retry path adds turns here; it must never move the cut
543
+ // towards the head (that would keep more, not less).
544
+ let cutTurnIndex = Math.max(syntheticHeadTurns + keepTurnsCut, tokenCut) + extraDroppedTurns;
545
+ if (cutTurnIndex > turns.length - 1) cutTurnIndex = turns.length - 1;
546
+ if (cutTurnIndex < 1) cutTurnIndex = 1;
547
+ let changed = true;
548
+ let guard = 0;
549
+ while (changed && guard < 64) {
550
+ changed = false;
551
+ guard += 1;
552
+ if (cutTurnIndex <= 0) break;
553
+ if (cutTurnIndex >= turns.length) cutTurnIndex = turns.length - 1;
554
+ // 1.8.9: prefer dropping a retained replacement checkpoint over walking
555
+ // back into it. Walking back keeps more turns and can re-enter the
556
+ // checkpoint (the old deadlock: every candidate boundary sat inside the
557
+ // replaced span); moving past it drops the checkpoint and keeps less.
558
+ const replacementAt = findReplacementStraddle(events, turns[cutTurnIndex].startIndex);
559
+ if (replacementAt >= 0) {
560
+ let next = cutTurnIndex;
561
+ while (next < turns.length && turns[next].startIndex <= replacementAt) next += 1;
562
+ if (next <= turns.length - 1) {
563
+ cutTurnIndex = next;
564
+ changed = true;
565
+ continue;
566
+ }
567
+ break; // the checkpoint lives in the last turn: no boundary can drop it
568
+ }
569
+
570
+ const straddle = findCompactionStraddle(events, turns[cutTurnIndex].startIndex);
571
+ if (straddle >= 0) {
572
+ let owner = cutTurnIndex;
573
+ while (owner > 0 && turns[owner].startIndex > straddle) owner -= 1;
574
+ if (owner < cutTurnIndex) {
575
+ cutTurnIndex = owner;
576
+ changed = true;
577
+ continue;
578
+ }
579
+ }
580
+ if (turns[cutTurnIndex].firstUserIndex === null && cutTurnIndex > 0) {
581
+ const back = cutTurnIndex - 1;
582
+ // Never undo the forward step above: moving back into a replacement
583
+ // checkpoint would make the next iteration jump forward again.
584
+ if (findReplacementStraddle(events, turns[back].startIndex) < 0) {
585
+ cutTurnIndex = back;
586
+ changed = true;
587
+ }
588
+ }
589
+ }
590
+ return { cutTurnIndex, syntheticHeadTurns, keepTurnsCut, tokenCut, tokenTotal };
591
+ }
592
+
593
+ /**
594
+ * Estimate the *rewritten* log, not just the kept turns: the protected head
595
+ * message, the archive card and the capped first-user carry are all part of
596
+ * what the next turn pays for. 0.8.0-rc.11 uses this for the budget decision
597
+ * (rc.10 subtracted only `dropped.tokens` from `original.tokens`, so synthetic
598
+ * rows were free in the arithmetic and very expensive in the log).
599
+ */
600
+ function projectCutTokens({ events, turns, cutTurnIndex, archivePath, firstUserCapChars, insertArchiveCard, carryFirstUserMessage, firstUserIndex }) {
601
+ const cutIndex = turns[cutTurnIndex].startIndex;
602
+ const kept = events.slice(cutIndex);
603
+ const keptTokens = eventsTokens(kept);
604
+ const headIndex = protectedHeadIndex(events, cutIndex);
605
+ const headTokens = headIndex >= 0 ? messageTokens(events[headIndex]) : 0;
606
+
607
+ let cardTokens = 0;
608
+ if (insertArchiveCard !== false) {
609
+ const droppedTurns = [];
610
+ for (let i = 0; i < cutTurnIndex; i += 1) droppedTurns.push(turnSummary(turns, i, events));
611
+ const cardText = buildArchiveCardText({
612
+ droppedEvents: events.slice(0, cutIndex),
613
+ droppedTurns,
614
+ cutTurnIndex,
615
+ archivePath: archivePath ?? '(归档文件)',
616
+ });
617
+ cardTokens = messageTokens(syntheticUserMessage({ id: 'archive-card-projection', text: cardText, now: 0 }));
618
+ }
619
+
620
+ let carryTokens = 0;
621
+ let carry = null;
622
+ if (carryFirstUserMessage !== false && Number.isInteger(firstUserIndex) && firstUserIndex >= 0 && firstUserIndex < cutIndex) {
623
+ carry = capFirstUserText(textOfEvent(events[firstUserIndex]), { archivePath, firstUserCapChars });
624
+ carryTokens = messageTokens(syntheticUserMessage({ id: 'archive-first-user-projection', text: carry.text, now: 0 }));
625
+ }
626
+
627
+ return {
628
+ cutIndex,
629
+ tokens: keptTokens + headTokens + cardTokens + carryTokens,
630
+ keptTokens,
631
+ headTokens,
632
+ cardTokens,
633
+ carryTokens,
634
+ carry,
635
+ };
636
+ }
637
+
638
+
639
+ // ---------------------------------------------------------------------------
640
+ // planning
641
+ // ---------------------------------------------------------------------------
642
+
643
+ /**
644
+ * Pick a turn boundary. Two independent boundaries are computed and the later
645
+ * one wins (it keeps fewer turns):
646
+ * - keep the last `keepTurns` turns;
647
+ * - keep the last turns whose estimated tokens still fit `keepTokens`.
648
+ * The boundary turn must contain a user-authored message; otherwise it moves
649
+ * back one turn. `turn 1` is only pinned when it is also the first user turn —
650
+ * a session whose first turn carries 80% of the context must still be cuttable.
651
+ */
652
+ export function planVisibleTruncation(parsed, options = {}) {
653
+ const keepTurns = options.keepTurns ?? DEFAULT_KEEP_TURNS;
654
+ const keepTokens = options.keepTokens ?? DEFAULT_KEEP_TOKENS;
655
+ if (!(Number.isInteger(keepTurns) && keepTurns >= 1)) {
656
+ throw visibleError(ERROR_CODES.BAD_ARGUMENT, `keepTurns must be an integer >= 1 (got ${JSON.stringify(keepTurns)})`);
657
+ }
658
+ if (!(Number.isInteger(keepTokens) && keepTokens >= 1)) {
659
+ throw visibleError(ERROR_CODES.BAD_ARGUMENT, `keepTokens must be an integer >= 1 (got ${JSON.stringify(keepTokens)})`);
660
+ }
661
+ const firstUserCapChars = resolvePositiveInt('firstUserCapChars',
662
+ options.firstUserCapChars, DEFAULT_FIRST_USER_CAP_CHARS);
663
+ const extraDroppedTurns = options.extraDroppedTurns ?? 0;
664
+ if (!(Number.isInteger(extraDroppedTurns) && extraDroppedTurns >= 0)) {
665
+ throw visibleError(ERROR_CODES.BAD_ARGUMENT,
666
+ `extraDroppedTurns must be an integer >= 0 (got ${JSON.stringify(options.extraDroppedTurns)})`);
667
+ }
668
+ const archivePath = options.archivePath ?? null;
669
+ const insertArchiveCard = options.insertArchiveCard !== false;
670
+ const carryFirstUserMessage = options.carryFirstUserMessage !== false;
671
+ const budgetCeiling = Math.ceil(keepTokens * BUDGET_SLACK);
672
+
673
+ const events = parsed.events;
674
+ const { turns } = turnsOf(events);
675
+ const firstUserIndex = firstUserMessageIndex(events);
676
+ const firstUserMessage = firstUserIndex >= 0
677
+ ? { seq: events[firstUserIndex].seq, text: firstLine(textOfEvent(events[firstUserIndex]), 160), carried: false }
678
+ : null;
679
+ // "No human in this log" is a finding, not silence: the tool must say so
680
+ // instead of silently falling back to an injected block.
681
+ const firstUserMessageNote = firstUserIndex < 0 ? NO_USER_MESSAGE_NOTE : null;
682
+ const original = {
683
+ bytes: parsed.bytes,
684
+ events: events.length,
685
+ messages: eventsMessages(events),
686
+ tokens: eventsTokens(events),
687
+ };
688
+ if (turns.length < 2) {
689
+ return {
690
+ needed: false,
691
+ reason: `only ${turns.length} turn(s); nothing whole to drop`,
692
+ keepTurns,
693
+ keepTokens,
694
+ original,
695
+ firstUserMessage,
696
+ firstUserMessageNote,
697
+ };
698
+ }
699
+
700
+ const base = chooseBoundary({ turns, events, keepTurns, keepTokens });
701
+ const { syntheticHeadTurns, keepTurnsCut, tokenCut } = base;
702
+
703
+ if (keepTurnsCut === 0 && tokenCut <= syntheticHeadTurns) {
704
+ return {
705
+ needed: false,
706
+ reason: 'already within keepTurns and keepTokens',
707
+ keepTurns,
708
+ keepTokens,
709
+ original,
710
+ firstUserMessage,
711
+ firstUserMessageNote,
712
+ };
713
+ }
714
+
715
+ let cutTurnIndex = chooseBoundary({ turns, events, keepTurns, keepTokens, extraDroppedTurns }).cutTurnIndex;
716
+
717
+ // 0.8.0-rc.11 (defect A): budget on the rewritten log, not on the dropped
718
+ // prefix. If the head + archive card + capped carry + kept turns still exceed
719
+ // keepTokens, drop one more whole turn (move the cut later) and try again.
720
+ let projection = projectCutTokens({
721
+ events, turns, cutTurnIndex, archivePath, firstUserCapChars,
722
+ insertArchiveCard, carryFirstUserMessage, firstUserIndex,
723
+ });
724
+ let budgetTrimSteps = 0;
725
+ const projectBudgetTrims = [];
726
+ while (projection.tokens > keepTokens && budgetTrimSteps < turns.length) {
727
+ projectBudgetTrims.push({ cutTurn: turns[cutTurnIndex].turn, tokens: projection.tokens });
728
+ budgetTrimSteps += 1;
729
+ const next = chooseBoundary({
730
+ turns, events, keepTurns, keepTokens,
731
+ extraDroppedTurns: extraDroppedTurns + budgetTrimSteps,
732
+ });
733
+ if (next.cutTurnIndex <= cutTurnIndex) break;
734
+ cutTurnIndex = next.cutTurnIndex;
735
+ projection = projectCutTokens({
736
+ events, turns, cutTurnIndex, archivePath, firstUserCapChars,
737
+ insertArchiveCard, carryFirstUserMessage, firstUserIndex,
738
+ });
739
+ }
740
+
741
+ // Cutting exactly at the synthetic head turn is legal (its prompt is copied
742
+ // into the new head), so only index 0 is off-limits. Anything that still
743
+ // cannot fit at the deepest legal cut is reported as TOKEN_BUDGET below,
744
+ // never as "nothing to do" — rc.10 answered a budget failure with a noop.
745
+ if (cutTurnIndex < syntheticHeadTurns) {
746
+ return {
747
+ needed: false,
748
+ reason: 'only the synthetic protected-head turn could be dropped',
749
+ keepTurns,
750
+ keepTokens,
751
+ original,
752
+ firstUserMessage,
753
+ firstUserMessageNote,
754
+ };
755
+ }
756
+
757
+ if (cutTurnIndex <= 0) {
758
+ return {
759
+ needed: false,
760
+ reason: 'no whole turn can be dropped while keeping a user-authored message and the protected head',
761
+ keepTurns,
762
+ keepTokens,
763
+ original,
764
+ firstUserMessage,
765
+ firstUserMessageNote,
766
+ };
767
+ }
768
+
769
+ const cutIndex = turns[cutTurnIndex].startIndex;
770
+ const headIndex = protectedHeadIndex(events, cutIndex);
771
+ const firstUserDropped = firstUserIndex >= 0 && firstUserIndex < cutIndex;
772
+ const dropped = events.slice(0, cutIndex);
773
+ const kept = events.slice(cutIndex);
774
+
775
+ const droppedTurns = [];
776
+ for (let i = 0; i < cutTurnIndex; i += 1) droppedTurns.push(turnSummary(turns, i, events));
777
+ const keptTurns = [];
778
+ for (let i = cutTurnIndex; i < turns.length; i += 1) keptTurns.push(turnSummary(turns, i, events));
779
+
780
+ const firstUserText = firstUserDropped ? textOfEvent(events[firstUserIndex]) : null;
781
+ const carryPreview = projection.carry;
782
+ const fits = projection.tokens <= keepTokens;
783
+ const feasible = projection.tokens <= budgetCeiling;
784
+
785
+ return {
786
+ needed: true,
787
+ feasible,
788
+ keepTurns,
789
+ keepTokens,
790
+ firstUserCapChars,
791
+ cutIndex,
792
+ cutSeq: cutIndex,
793
+ cutTurn: turns[cutTurnIndex].turn,
794
+ cutTurnIndex,
795
+ cutTurnStartSeq: turns[cutTurnIndex].startSeq,
796
+ cutTime: turns[cutTurnIndex].startTime,
797
+ keptTurnCount: turns.length - cutTurnIndex,
798
+ droppedTurnCount: cutTurnIndex,
799
+ original,
800
+ dropped: {
801
+ bytes: eventsBytes(dropped),
802
+ events: dropped.length,
803
+ messages: eventsMessages(dropped),
804
+ tokens: eventsTokens(dropped),
805
+ },
806
+ kept: {
807
+ bytes: eventsBytes(kept),
808
+ events: kept.length,
809
+ messages: eventsMessages(kept),
810
+ tokens: eventsTokens(kept),
811
+ },
812
+ droppedTurns,
813
+ keptTurns,
814
+ headSeq: headIndex >= 0 ? events[headIndex].seq : null,
815
+ headPresent: headIndex >= 0,
816
+ firstUserMessage: firstUserMessage
817
+ ? { ...firstUserMessage, carried: firstUserDropped }
818
+ : null,
819
+ firstUserMessageNote,
820
+ firstUserText,
821
+ // What the carried row will actually say after the cap: the full text stays
822
+ // in the archive, the rewritten log keeps a bounded prefix plus the path.
823
+ firstUserCarry: carryPreview
824
+ ? {
825
+ capped: carryPreview.capped,
826
+ capChars: carryPreview.capChars,
827
+ originalChars: carryPreview.originalChars,
828
+ keptChars: carryPreview.keptChars,
829
+ text: carryPreview.text,
830
+ }
831
+ : null,
832
+ budget: {
833
+ keepTokens,
834
+ ceiling: budgetCeiling,
835
+ afterTokens: projection.tokens,
836
+ keptTokens: projection.keptTokens,
837
+ headTokens: projection.headTokens,
838
+ cardTokens: projection.cardTokens,
839
+ carryTokens: projection.carryTokens,
840
+ fits,
841
+ overBy: Math.max(0, projection.tokens - keepTokens),
842
+ trimmedTurns: budgetTrimSteps,
843
+ trims: projectBudgetTrims,
844
+ },
845
+ infeasible: feasible ? null : {
846
+ code: ERROR_CODES.TOKEN_BUDGET,
847
+ reason: `post-cut estimate ${projection.tokens} still exceeds keepTokens ${keepTokens} ` +
848
+ `(ceiling ${budgetCeiling}) after dropping ${cutTurnIndex} turn(s); ` +
849
+ 'the carried first-user message is already capped',
850
+ attempts: null,
851
+ limit: {
852
+ kind: 'deepest-legal-cut-still-over-budget',
853
+ deepestCutTurn: turns[cutTurnIndex].turn,
854
+ deepestCutSeq: cutIndex,
855
+ keptTurns: turns.length - cutTurnIndex,
856
+ afterTokens: projection.tokens,
857
+ keepTokens,
858
+ ceiling: budgetCeiling,
859
+ // A single retained turn (or the protected head + archive card) cannot
860
+ // be split by this tool. Dropping the whole conversation is not a safe
861
+ // fallback, so the caller must surface this as an explicit limit.
862
+ note: 'cannot drop the last whole turn without dropping the entire visible conversation',
863
+ },
864
+ },
865
+ carryFirstUserMessage: firstUserDropped && carryFirstUserMessage,
866
+ insertArchiveCard,
867
+ };
868
+ }
869
+
870
+ // ---------------------------------------------------------------------------
871
+ // archive card
872
+ // ---------------------------------------------------------------------------
873
+
874
+ function walkStrings(value, out = []) {
875
+ if (value == null) return out;
876
+ if (typeof value === 'string') {
877
+ out.push(value);
878
+ return out;
879
+ }
880
+ if (Array.isArray(value)) {
881
+ for (const item of value) walkStrings(item, out);
882
+ return out;
883
+ }
884
+ if (typeof value === 'object') {
885
+ for (const item of Object.values(value)) walkStrings(item, out);
886
+ }
887
+ return out;
888
+ }
889
+
890
+ // 0.7.7: the former `PATH_RE` regular expression was removed. It backtracked
891
+ // catastrophically on a long run of separators that never reaches a recognised
892
+ // extension: `/a`*30 + `/zzz` took 28.8 s, a 6,766-character Windows path string
893
+ // from a real log 10.1 s, and a base64 PNG with 956 slashes never returned —
894
+ // all inside `extractPaths` before the dry-run report was returned.
895
+ //
896
+ // The scan below recognises exactly the language the pattern accepted:
897
+ //
898
+ // prefix := [A-Za-z]:[\\/] | /
899
+ // match := prefix A+ '.' ext A = [^"'<>\s|:*?]
900
+ //
901
+ // and keeps the pattern's leftmost/greedy semantics: the match ends at the last
902
+ // dot of the maximal A run that carries a recognised extension, and extensions
903
+ // are tried in declared order (so `a.json` still ends at `a.js`).
904
+ //
905
+ // Backslash UNC paths (`\\server\share\a.js`) are deliberately NOT added: the
906
+ // old matcher never recognised them, and widening the language would change the
907
+ // path set the archive card reports. `/`-prefixed UNC paths
908
+ // (`//server/share/a.js`) were matched before and still are.
909
+ const PATH_EXTENSIONS = Object.freeze([
910
+ 'js', 'mjs', 'cjs', 'ts', 'tsx', 'jsx', 'json', 'md', 'txt', 'log',
911
+ 'ps1', 'psm1', 'py', 'yml', 'yaml', 'zst', 'html', 'css', 'toml',
912
+ 'ini', 'cfg', 'zip', 'png', 'jpg', 'jpeg', 'wav', 'mp3',
913
+ ]);
914
+
915
+ // `[^"'<>\s|:*?]` as a lookup table for ASCII, with the real class for the
916
+ // rest of Unicode (`\s` is Unicode-aware). Built once at import time.
917
+ const PATH_CHAR_ASCII = (() => {
918
+ const table = new Uint8Array(128);
919
+ const re = /[^"'<>\s|:*?]/;
920
+ for (let code = 0; code < 128; code += 1) table[code] = re.test(String.fromCharCode(code)) ? 1 : 0;
921
+ return table;
922
+ })();
923
+ const PATH_CHAR_WIDE = /[^"'<>\s|:*?]/;
924
+
925
+ function extensionLengthAt(text, dot) {
926
+ for (const ext of PATH_EXTENSIONS) {
927
+ const from = dot + 1;
928
+ if (from + ext.length > text.length) continue;
929
+ let matches = true;
930
+ for (let i = 0; i < ext.length; i += 1) {
931
+ if (text.charCodeAt(from + i) !== ext.charCodeAt(i)) { matches = false; break; }
932
+ }
933
+ if (matches) return ext.length;
934
+ }
935
+ return 0;
936
+ }
937
+
938
+ /**
939
+ * Return every path-shaped substring `extractPaths` would take from `text`,
940
+ * in order, scanning the string exactly once (O(text.length)).
941
+ *
942
+ * Exported for the regression suite; production callers go through
943
+ * `extractPaths`/`buildArchiveCardText`.
944
+ */
945
+ export function matchPathStrings(text) {
946
+ if (typeof text !== 'string' || text.length < 3) return [];
947
+ const length = text.length;
948
+ const found = [];
949
+ let cursor = 0;
950
+ // Cache for the maximal path-character run that starts at `runStart`: where it
951
+ // ends, and the last dot inside it that carries a recognised extension.
952
+ let runStart = -1;
953
+ let runEnd = -1;
954
+ let runDot = -1;
955
+
956
+ while (cursor < length) {
957
+ let start = -1;
958
+ let prefixLength = 0;
959
+ for (let i = cursor; i < length; i += 1) {
960
+ const code = text.charCodeAt(i);
961
+ if (code === 0x2f /* / */) {
962
+ start = i;
963
+ prefixLength = 1;
964
+ break;
965
+ }
966
+ if (((code >= 0x41 && code <= 0x5a) || (code >= 0x61 && code <= 0x7a))
967
+ && text.charCodeAt(i + 1) === 0x3a /* : */) {
968
+ const separator = text.charCodeAt(i + 2);
969
+ if (separator === 0x2f || separator === 0x5c /* \ */) {
970
+ start = i;
971
+ prefixLength = 3;
972
+ break;
973
+ }
974
+ }
975
+ }
976
+ if (start < 0) break;
977
+ const bodyStart = start + prefixLength;
978
+ if (bodyStart >= length) break;
979
+
980
+ let dot;
981
+ if (bodyStart >= runStart && bodyStart < runEnd) {
982
+ // Same run as the cached one: the cached last dot is still the last dot.
983
+ dot = runDot >= bodyStart + 1 ? runDot : -1;
984
+ } else {
985
+ let end = bodyStart;
986
+ while (end < length) {
987
+ const code = text.charCodeAt(end);
988
+ if (code < 128) {
989
+ if (PATH_CHAR_ASCII[code] !== 1) break;
990
+ } else if (!PATH_CHAR_WIDE.test(text[end])) {
991
+ break;
992
+ }
993
+ end += 1;
994
+ }
995
+ let last = -1;
996
+ for (let i = end - 1; i > bodyStart; i -= 1) {
997
+ if (text.charCodeAt(i) === 0x2e /* . */ && extensionLengthAt(text, i) !== 0) {
998
+ last = i;
999
+ break;
1000
+ }
1001
+ }
1002
+ runStart = bodyStart;
1003
+ runEnd = end;
1004
+ runDot = last;
1005
+ dot = last;
1006
+ }
1007
+
1008
+ if (dot < 0) {
1009
+ // No dot in this run can carry an extension: no candidate starting here
1010
+ // can match either, so resume one character in (the next prefix wins).
1011
+ cursor = start + 1;
1012
+ continue;
1013
+ }
1014
+
1015
+ const end = dot + 1 + extensionLengthAt(text, dot);
1016
+ found.push(text.slice(start, end));
1017
+ cursor = end;
1018
+ }
1019
+ return found;
1020
+ }
1021
+
1022
+ /** Paths mentioned by `droppedEvents`, most frequent first (archive card). */
1023
+ export function extractPaths(droppedEvents, max = 8) {
1024
+ const counts = new Map();
1025
+ for (const event of droppedEvents) {
1026
+ for (const text of walkStrings(event.data)) {
1027
+ const matches = matchPathStrings(text);
1028
+ for (const raw of matches) {
1029
+ const normalized = raw.replace(/\\\\/g, '\\').replace(/\\/g, '/');
1030
+ if (normalized.length < 5 || normalized.length > 180) continue;
1031
+ const key = normalized.toLowerCase();
1032
+ counts.set(key, { path: normalized, count: (counts.get(key)?.count ?? 0) + 1 });
1033
+ }
1034
+ }
1035
+ }
1036
+ return [...counts.values()]
1037
+ .sort((a, b) => b.count - a.count || a.path.localeCompare(b.path))
1038
+ .slice(0, max)
1039
+ .map((item) => item.path);
1040
+ }
1041
+
1042
+ function extractTopics({ droppedEvents, droppedTurns, cutTurnIndex }) {
1043
+ const topics = [];
1044
+ const seen = new Set();
1045
+ const push = (value) => {
1046
+ const text = firstLine(value, 72);
1047
+ if (!text || seen.has(text.toLowerCase())) return;
1048
+ seen.add(text.toLowerCase());
1049
+ topics.push(text);
1050
+ };
1051
+
1052
+ // 1. Prefer a provider-generated title over the fallback (which is often just
1053
+ // the first user message cut at 12 characters).
1054
+ let fallbackTitle = null;
1055
+ for (const event of droppedEvents) {
1056
+ if (event.type !== 'session/title' || typeof event.data?.title !== 'string') continue;
1057
+ if (event.data.source?.kind === 'provider') {
1058
+ push(`标题:${event.data.title}`);
1059
+ fallbackTitle = null;
1060
+ break;
1061
+ }
1062
+ fallbackTitle ??= event.data.title;
1063
+ }
1064
+ if (fallbackTitle) push(`标题:${fallbackTitle}`);
1065
+
1066
+ // 2. What the dropped turns actually did: the most frequent tools.
1067
+ const toolCounts = new Map();
1068
+ for (const event of droppedEvents) {
1069
+ if (event.type !== 'tool/call' || typeof event.data?.name !== 'string') continue;
1070
+ toolCounts.set(event.data.name, (toolCounts.get(event.data.name) ?? 0) + 1);
1071
+ }
1072
+ const rankedTools = [...toolCounts.entries()]
1073
+ .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))
1074
+ .slice(0, 3);
1075
+ if (rankedTools.length) {
1076
+ push(`工具:${rankedTools.map(([name, count]) => `${name} ×${count}`).join('、')}`);
1077
+ }
1078
+
1079
+ // 3. Files the dropped turns touched, as basenames.
1080
+ const bases = [];
1081
+ for (const full of extractPaths(droppedEvents, 60)) {
1082
+ const base = full.split('/').filter(Boolean).at(-1);
1083
+ if (!base || bases.some((item) => item.toLowerCase() === base.toLowerCase())) continue;
1084
+ bases.push(base);
1085
+ if (bases.length >= 3) break;
1086
+ }
1087
+ if (bases.length) push(`文件:${bases.join('、')}`);
1088
+
1089
+ // 4. Commands named by tool-call arguments (deterministic, no model).
1090
+ const knownCommands = new Set([
1091
+ 'node', 'python', 'python3', 'pwsh', 'powershell', 'cmd', 'bash', 'sh',
1092
+ 'curl', 'git', 'npm', 'pnpm', 'npx', 'deno', 'bun', 'tar',
1093
+ ]);
1094
+ const commandCounts = new Map();
1095
+ for (const event of droppedEvents) {
1096
+ if (event.type !== 'tool/call' || typeof event.data?.arguments !== 'string') continue;
1097
+ let parsed = null;
1098
+ try { parsed = JSON.parse(event.data.arguments); } catch { continue; }
1099
+ const command = parsed?.command ?? parsed?.cmd ?? parsed?.script;
1100
+ if (typeof command !== 'string') continue;
1101
+ const first = command.trim().split(/\s+/)[0]?.replace(/^["']|["']$/g, '');
1102
+ if (!first || first.startsWith('$') || first.startsWith('-')) continue;
1103
+ const base = first.split(/[\\/]/).filter(Boolean).at(-1);
1104
+ if (!base) continue;
1105
+ const lower = base.toLowerCase();
1106
+ const isExe = /\.(exe|cmd|bat|ps1|py|js|mjs|cjs)$/i.test(base);
1107
+ if (!isExe && !knownCommands.has(lower)) continue;
1108
+ commandCounts.set(base, (commandCounts.get(base) ?? 0) + 1);
1109
+ }
1110
+ const rankedCommands = [...commandCounts.entries()]
1111
+ .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))
1112
+ .slice(0, 3);
1113
+ if (rankedCommands.length) {
1114
+ push(`命令:${rankedCommands.map(([name, count]) => `${name} ×${count}`).join('、')}`);
1115
+ }
1116
+
1117
+ // 5. Only when the prefix has almost no tool activity, fall back to turn heads.
1118
+ for (const summary of droppedTurns) {
1119
+ if (topics.length >= 4) break;
1120
+ if (summary?.firstMessage && summary.firstMessage !== '(无可见消息)') push(summary.firstMessage);
1121
+ }
1122
+
1123
+ while (topics.length < 3) {
1124
+ push(topics.length === 0 ? `早期 ${cutTurnIndex} 轮对话` : `早期对话记录(${topics.length + 1})`);
1125
+ }
1126
+ return topics.slice(0, 5);
1127
+ }
1128
+
1129
+ export function buildArchiveCardText({ droppedEvents, droppedTurns, cutTurnIndex, archivePath }) {
1130
+ const start = droppedTurns[0]?.startTime;
1131
+ const end = droppedTurns.at(-1)?.endTime;
1132
+ const topics = extractTopics({ droppedEvents, droppedTurns, cutTurnIndex });
1133
+ const paths = extractPaths(droppedEvents, 8);
1134
+ const lines = [];
1135
+ lines.push(`[已归档 ${formatTime(start)} → ${formatTime(end)}]`);
1136
+ lines.push('当时在做:');
1137
+ for (const topic of topics) lines.push(`- ${topic}`);
1138
+ if (paths.length) {
1139
+ lines.push('涉及文件:');
1140
+ for (const p of paths) lines.push(`- ${p}`);
1141
+ }
1142
+ lines.push(`原文归档:${archivePath}`);
1143
+ return lines.join('\n');
1144
+ }
1145
+
1146
+ function syntheticUserMessage({ id, text, now }) {
1147
+ return {
1148
+ type: 'user/message',
1149
+ surfaceOp: 'append',
1150
+ seq: 0,
1151
+ time: now,
1152
+ data: {
1153
+ id,
1154
+ role: 'user',
1155
+ source: { kind: 'archive-card' },
1156
+ content: [{ type: 'text', text }],
1157
+ },
1158
+ };
1159
+ }
1160
+
1161
+ // ---------------------------------------------------------------------------
1162
+ // build
1163
+ // ---------------------------------------------------------------------------
1164
+
1165
+ function cloneEvent(event) {
1166
+ return structuredClone(event);
1167
+ }
1168
+
1169
+ function preFilterRetained(event) {
1170
+ if (isInboxEvent(event)) return false;
1171
+ return true;
1172
+ }
1173
+
1174
+ /**
1175
+ * A seeded v4 log carries its inherited cut as a marker EVENT, not as a header
1176
+ * field: `session/end-seed` with `data.inherited === true`. The decoders derive
1177
+ * `inheritedEventCount` from the LAST such row and then require it to equal the
1178
+ * header's cut, so the row is load-bearing metadata rather than noise.
1179
+ *
1180
+ * `@deepseek-ai/dsh-session-format-v1-to-v2` (decoder `finish()`): a seeded
1181
+ * header without such a marker throws `released v2 seeded Session lacks an
1182
+ * inherited end-seed marker`; an unseeded header that still has one throws
1183
+ * `released v2 unseeded Session contains an inherited end-seed marker`.
1184
+ * v3-to-v4 adds `format v4 seeded header disagrees with its last inherited
1185
+ * end-seed marker`. Truncation has to rewrite this metadata with the log, not
1186
+ * around it.
1187
+ */
1188
+ export function isInheritedSeedMarker(event) {
1189
+ return Boolean(event)
1190
+ && event.type === 'session/end-seed'
1191
+ && event.data !== null
1192
+ && typeof event.data === 'object'
1193
+ && event.data.inherited === true;
1194
+ }
1195
+
1196
+ function remapReferences(event, map, cutIndex) {
1197
+ const op = event.surfaceOp;
1198
+ if (op && typeof op === 'object') {
1199
+ const start = op.startSeq ?? op.start;
1200
+ const end = op.endSeq ?? op.end;
1201
+ if (typeof start !== 'number' || typeof end !== 'number') return false;
1202
+ if (start < cutIndex || end < cutIndex) return false;
1203
+ if ('startSeq' in op) op.startSeq = map.get(start); else op.start = map.get(start);
1204
+ if ('endSeq' in op) op.endSeq = map.get(end); else op.end = map.get(end);
1205
+ if (typeof (op.startSeq ?? op.start) !== 'number') return false;
1206
+ }
1207
+
1208
+ const data = event.data;
1209
+ if (!data || typeof data !== 'object' || Array.isArray(data)) return true;
1210
+
1211
+ // Surface metadata lives on the event, not in data. A tool/result names the
1212
+ // tool/call it answers here; after a prefix cut both may survive, but the
1213
+ // number still points at the old seq unless it is remapped.
1214
+ if (Array.isArray(event.sourceEventSeqs)) {
1215
+ const values = event.sourceEventSeqs;
1216
+ if (values.every((value) => typeof value === 'number')) {
1217
+ const mapped = values
1218
+ .filter((value) => value >= cutIndex)
1219
+ .map((value) => map.get(value))
1220
+ .filter((value) => typeof value === 'number');
1221
+ if (mapped.length === 0) delete event.sourceEventSeqs;
1222
+ else event.sourceEventSeqs = mapped;
1223
+ }
1224
+ }
1225
+
1226
+ for (const key of ['sourceEventSeq', 'headerSeq', 'throughSeq']) {
1227
+ if (typeof data[key] !== 'number') continue;
1228
+ if (data[key] < cutIndex) {
1229
+ if (key === 'throughSeq') return false;
1230
+ delete data[key];
1231
+ } else {
1232
+ const mapped = map.get(data[key]);
1233
+ if (typeof mapped !== 'number') return false;
1234
+ data[key] = mapped;
1235
+ }
1236
+ }
1237
+
1238
+ for (const key of ['messageSeqs', 'shadowedSeqs', 'sourceEventSeqs']) {
1239
+ if (!Array.isArray(data[key])) continue;
1240
+ const values = data[key];
1241
+ if (values.some((value) => typeof value !== 'number')) continue; // encoded ranges: leave untouched
1242
+ if (values.some((value) => value < cutIndex)) {
1243
+ if (key === 'messageSeqs') return false;
1244
+ return false;
1245
+ }
1246
+ const mapped = values.map((value) => map.get(value));
1247
+ if (mapped.some((value) => typeof value !== 'number')) return false;
1248
+ data[key] = mapped;
1249
+ }
1250
+
1251
+ const range = data.shadowedRange;
1252
+ if (range && typeof range === 'object') {
1253
+ const start = range.startSeq ?? range.start;
1254
+ const end = range.endSeq ?? range.end;
1255
+ if (typeof start === 'number' && typeof end === 'number') {
1256
+ if (start < cutIndex || end < cutIndex) return false;
1257
+ if ('startSeq' in range) range.startSeq = map.get(start); else range.start = map.get(start);
1258
+ if ('endSeq' in range) range.endSeq = map.get(end); else range.end = map.get(end);
1259
+ }
1260
+ }
1261
+ return true;
1262
+ }
1263
+
1264
+ /**
1265
+ * Build the rewritten log. Only `seq` and references that pointed into the cut
1266
+ * prefix are changed; every other field of a retained event is preserved.
1267
+ */
1268
+ export function buildVisibleTruncated(parsed, plan, options = {}) {
1269
+ const now = options.now ?? Date.now();
1270
+ const archivePath = options.archivePath;
1271
+ const events = parsed.events;
1272
+ const cutIndex = plan.cutIndex;
1273
+
1274
+ if (!(Number.isInteger(cutIndex) && cutIndex > 0 && cutIndex < events.length)) {
1275
+ throw visibleError(ERROR_CODES.NO_BOUNDARY, `invalid cut index ${cutIndex}`);
1276
+ }
1277
+
1278
+ // A replacement that starts before the cut cannot be preserved as-is; refuse
1279
+ // rather than silently changing which messages the Surface holds.
1280
+ for (let i = cutIndex; i < events.length; i += 1) {
1281
+ const event = events[i];
1282
+ const op = event.surfaceOp;
1283
+ if (op && typeof op === 'object') {
1284
+ const start = op.startSeq ?? op.start;
1285
+ if (typeof start === 'number' && start < cutIndex) {
1286
+ throw visibleError(ERROR_CODES.REPLACEMENT_STRADDLES_CUT,
1287
+ `retained event seq ${event.seq} replaces from seq ${start}, which is before the cut at ${cutIndex}`);
1288
+ }
1289
+ }
1290
+ }
1291
+
1292
+ const dropped = events.slice(0, cutIndex);
1293
+ const droppedTurns = plan.droppedTurns ?? [];
1294
+ const synthetics = [];
1295
+
1296
+ // Seeded sessions: the marker that used to sit inside the dropped prefix has
1297
+ // to be replaced, not carried. One fresh marker at index 0 declares an
1298
+ // explicitly empty inherited prefix - a shape `@deepseek-ai/dsh-subagent`
1299
+ // documents ("isSeeded - whether this child inherits a parent-log prefix,
1300
+ // including an explicitly empty one") and the decoder accepts, because the
1301
+ // derived count is simply 0.
1302
+ //
1303
+ // Keeping `isSeeded` with no marker was the 0.7.4 bug: the physical header
1304
+ // line has no inheritedEventCount field, so the decoder derived `undefined`
1305
+ // and refused the log with "released v2 seeded Session lacks an inherited
1306
+ // end-seed marker" (SessionFormatError, wrapped by the persistence layer as
1307
+ // SessionPersistenceCorruptionError). The CLI's own read-back only reparsed
1308
+ // with src/codec.js, which never looks at this metadata, so it stayed green.
1309
+ const seeded = parsed.header?.isSeeded === true;
1310
+ if (seeded) {
1311
+ synthetics.push({ type: 'session/end-seed', time: now, data: { inherited: true } });
1312
+ }
1313
+
1314
+ const headIndex = protectedHeadIndex(events, cutIndex);
1315
+ if (headIndex < 0) {
1316
+ throw visibleError(ERROR_CODES.NO_PROTECTED_HEAD,
1317
+ 'no system/message with source.kind="system-prompt" exists before the cut; ' +
1318
+ 'the host requires a protected head, so nothing was written');
1319
+ }
1320
+ const head = cloneEvent(events[headIndex]);
1321
+ delete head.__remapped;
1322
+ // V4 enforces lifecycle relationships: a system/message is only legal inside
1323
+ // an open turn+step. Preserve the original prompt as a completed synthetic
1324
+ // turn 1, and renumber the retained turns to start at 2.
1325
+ head.data = { ...head.data, turn: 1, step: 1 };
1326
+ synthetics.push({ type: 'turn/start', time: now, data: { turn: 1 } });
1327
+ synthetics.push({ type: 'step/start', time: now, data: { turn: 1, step: 1 } });
1328
+ synthetics.push(head);
1329
+ synthetics.push({ type: 'step/end', time: now, data: { turn: 1, step: 1 } });
1330
+ // Real host turns always end with a reason object; the kinds seen in this
1331
+ // machine's session logs are completed / aborted / error / interrupted. The
1332
+ // host tolerates a missing one, but third-party consumers read
1333
+ // `event.data.reason.kind` and crash on `undefined`; a synthetic turn that
1334
+ // only exists because the prefix was dropped ended because of the truncation,
1335
+ // so that is the honest kind.
1336
+ synthetics.push({
1337
+ type: 'turn/end', time: now,
1338
+ data: { turn: 1, reason: { kind: 'truncated' } },
1339
+ });
1340
+
1341
+ let cardText = null;
1342
+ if (plan.insertArchiveCard !== false) {
1343
+ cardText = buildArchiveCardText({
1344
+ droppedEvents: dropped,
1345
+ droppedTurns: droppedTurns.length ? droppedTurns : plan.droppedTurns ?? [],
1346
+ cutTurnIndex: plan.droppedTurnCount ?? 0,
1347
+ archivePath,
1348
+ });
1349
+ const cardId = `archive-card-${sha256(Buffer.from(cardText, 'utf8')).slice(0, 8)}`;
1350
+ synthetics.push(syntheticUserMessage({ id: cardId, text: cardText, now }));
1351
+ }
1352
+
1353
+ let carryText = null;
1354
+ let carryInfo = null;
1355
+ if (plan.carryFirstUserMessage) {
1356
+ const firstIndex = firstUserMessageIndex(events);
1357
+ if (firstIndex >= 0 && firstIndex < cutIndex) {
1358
+ const original = textOfEvent(events[firstIndex]);
1359
+ // 0.8.0-rc.11 (defect A): bound the synthetic row. The archive keeps the
1360
+ // bytes; the live log keeps a prefix that names it.
1361
+ const capped = capFirstUserText(original, {
1362
+ archivePath,
1363
+ firstUserCapChars: plan.firstUserCapChars ?? options.firstUserCapChars ?? DEFAULT_FIRST_USER_CAP_CHARS,
1364
+ });
1365
+ carryText = capped.text;
1366
+ carryInfo = {
1367
+ capped: capped.capped,
1368
+ capChars: capped.capChars,
1369
+ originalChars: capped.originalChars,
1370
+ keptChars: capped.keptChars,
1371
+ note: capped.note,
1372
+ };
1373
+ const id = `archive-first-user-${sha256(Buffer.from(original, 'utf8')).slice(0, 8)}`;
1374
+ synthetics.push(syntheticUserMessage({ id, text: carryText, now }));
1375
+ }
1376
+ }
1377
+
1378
+ const offset = synthetics.length;
1379
+ const turnShift = 2 - plan.cutTurn;
1380
+ const base = events.slice(cutIndex)
1381
+ // No inherited marker may survive inside the kept window: it would announce
1382
+ // a cut at its own (new) position and the decoder would refuse the log
1383
+ // ("session inherited event count must identify the final inherited
1384
+ // marker" / "format v4 seeded header disagrees with its last inherited
1385
+ // end-seed marker"). The single marker written above replaces all of them,
1386
+ // and an unseeded header may not carry one at all.
1387
+ .filter((event) => !isInheritedSeedMarker(event))
1388
+ .map((event) => {
1389
+ const clone = cloneEvent(event);
1390
+ if (clone.data && typeof clone.data === 'object' && typeof clone.data.turn === 'number') {
1391
+ clone.data.turn += turnShift;
1392
+ }
1393
+ return clone;
1394
+ });
1395
+ let dirty = base.filter(preFilterRetained);
1396
+ let result = dirty;
1397
+ let stable = false;
1398
+ let passes = 0;
1399
+ // 0.8.0-rc.11 (defect B): drops must be cumulative. rc.10 rebuilt `dirty`
1400
+ // from `base` on every pass and only remembered the current pass's drops, so
1401
+ // an event dropped in pass 1 was re-admitted in pass 2, dropped something
1402
+ // else instead, and the loop oscillated until the 8-pass cap:
1403
+ // "could not stabilize retained events (22 candidates, 21 survived)".
1404
+ // `removed` only grows, so this converges in at most base.length passes.
1405
+ const removed = new Set();
1406
+ const maxPasses = Number.isInteger(options.stabilizePasses) && options.stabilizePasses >= 1
1407
+ ? options.stabilizePasses
1408
+ : base.length + 2;
1409
+ for (; passes < maxPasses; passes += 1) {
1410
+ const map = new Map();
1411
+ dirty.forEach((event, index) => map.set(event.seq, offset + index));
1412
+ const next = [];
1413
+ const droppedSeqs = new Set();
1414
+ for (const event of dirty) {
1415
+ const candidate = cloneEvent(event);
1416
+ if (remapReferences(candidate, map, cutIndex)) next.push(candidate);
1417
+ else droppedSeqs.add(event.seq);
1418
+ }
1419
+ result = next;
1420
+ if (droppedSeqs.size === 0) {
1421
+ stable = true;
1422
+ break;
1423
+ }
1424
+ // Dropping an event shifts every later position, so the references mapped
1425
+ // in this pass are stale: rebuild the map and redo the whole pass.
1426
+ for (const seq of droppedSeqs) removed.add(seq);
1427
+ dirty = base.filter((event) => preFilterRetained(event) && !removed.has(event.seq));
1428
+ }
1429
+ if (!stable || dirty.length !== result.length) {
1430
+ const error = visibleError(ERROR_CODES.NO_BOUNDARY,
1431
+ `could not stabilize retained events (${dirty.length} candidates, ${result.length} survived) ` +
1432
+ `at cut turn ${plan.cutTurn ?? '?'} after ${passes} pass(es)`);
1433
+ error.details = {
1434
+ code: ERROR_CODES.NO_BOUNDARY,
1435
+ candidates: dirty.length,
1436
+ survived: result.length,
1437
+ passes,
1438
+ maxPasses,
1439
+ cutTurn: plan.cutTurn ?? null,
1440
+ cutTurnIndex: plan.cutTurnIndex ?? null,
1441
+ cutIndex,
1442
+ droppedDuringStabilization: removed.size,
1443
+ };
1444
+ throw error;
1445
+ }
1446
+
1447
+ const composed = [...synthetics, ...result];
1448
+ composed.forEach((event, index) => { event.seq = index; });
1449
+ assertContiguous(composed);
1450
+
1451
+ const firstSurface = foldSurface(composed)[0];
1452
+ if (!firstSurface || firstSurface.type !== 'system/message') {
1453
+ throw visibleError(ERROR_CODES.NO_PROTECTED_HEAD,
1454
+ 'the rewritten log does not start with a system/message; refusing to write it');
1455
+ }
1456
+
1457
+ const header = { ...parsed.header };
1458
+ // The physical header line accepts a fixed key set
1459
+ // (`dsh-session-persistence-jsonl` HEADER_REQUIRED_KEYS/HEADER_OPTIONAL_KEYS
1460
+ // via isHeaderLine) and has no inheritedEventCount field at all, so 0.7.4's
1461
+ // `header.inheritedEventCount = 0` was a no-op on every real log. The cut is
1462
+ // carried by the marker event above; drop any in-memory stray so an unknown
1463
+ // key can never be encoded.
1464
+ delete header.inheritedEventCount;
1465
+ const seedMarker = seeded
1466
+ ? { type: 'session/end-seed', inherited: true, index: 0, inheritedEventCount: 0 }
1467
+ : null;
1468
+ const buffer = encodeSession(header, composed, { eventsPerFrame: options.eventsPerFrame });
1469
+ const digest = deriveMessagesDigest(header, composed);
1470
+
1471
+ return {
1472
+ header,
1473
+ seedMarker,
1474
+ events: composed,
1475
+ buffer,
1476
+ bytes: buffer.length,
1477
+ sha256: sha256(buffer),
1478
+ digest,
1479
+ messages: digest.count,
1480
+ tokens: eventsTokens(composed),
1481
+ retainedEvents: result.length,
1482
+ retainedMessages: eventsMessages(result),
1483
+ cardText,
1484
+ carryText,
1485
+ carryInfo,
1486
+ stabilizePasses: passes,
1487
+ headCopied: true,
1488
+ headSourceSeq: events[headIndex].seq,
1489
+ droppedSeqs: dropped.map((event) => event.seq),
1490
+ };
1491
+ }
1492
+
1493
+ /**
1494
+ * Archive exactly the removed prefix, keeping the original JSON lines
1495
+ * byte-for-byte. The prefix already has seq 0..cut-1, so it remains a valid
1496
+ * log on its own (header + contiguous events).
1497
+ */
1498
+ export function buildArchiveBuffer(parsed, plan, options = {}) {
1499
+ const cutIndex = plan.cutIndex;
1500
+ const rawLines = parsed.texts.join('').split('\n').filter((line) => line.length > 0);
1501
+ const headerLine = rawLines[0];
1502
+ const lines = [];
1503
+ for (let i = 0; i < cutIndex; i += 1) {
1504
+ const event = parsed.events[i];
1505
+ const raw = rawLines[event.seq + 1];
1506
+ lines.push(raw ?? JSON.stringify(event));
1507
+ }
1508
+ const out = [compressFrame(headerLine + '\n')];
1509
+ const perFrame = options.eventsPerFrame ?? DEFAULT_EVENTS_PER_FRAME;
1510
+ for (let i = 0; i < lines.length; i += perFrame) {
1511
+ out.push(compressFrame(lines.slice(i, i + perFrame).map((line) => line + '\n').join('')));
1512
+ }
1513
+ const buffer = Buffer.concat(out);
1514
+ return {
1515
+ buffer,
1516
+ bytes: buffer.length,
1517
+ sha256: sha256(buffer),
1518
+ events: lines.length,
1519
+ headerLine,
1520
+ };
1521
+ }
1522
+
1523
+ // ---------------------------------------------------------------------------
1524
+ // inflight / recovery
1525
+ // ---------------------------------------------------------------------------
1526
+
1527
+ export function readInflight(sessionPath) {
1528
+ const file = inflightPathFor(sessionPath);
1529
+ if (!fs.existsSync(file)) return null;
1530
+ let info;
1531
+ try {
1532
+ info = JSON.parse(fs.readFileSync(file, 'utf8'));
1533
+ } catch (error) {
1534
+ throw visibleError(ERROR_CODES.INFLIGHT_CORRUPT,
1535
+ `inflight record ${file} is not valid JSON; refusing to guess (${error.message})`, error);
1536
+ }
1537
+ return { ...info, inflightPath: file };
1538
+ }
1539
+
1540
+ function cleanupTmp(info) {
1541
+ for (const tmp of [info.tmpPath, info.restoreTmpPath]) {
1542
+ if (typeof tmp === 'string' && tmp.length > 0) removeIfExists(tmp);
1543
+ }
1544
+ }
1545
+
1546
+ /**
1547
+ * Resolve a record left by a crash. The target's hash decides:
1548
+ * expected -> the rename landed, finish by removing the record;
1549
+ * before -> nothing landed, finish by removing the record;
1550
+ * other -> restore the backup through tmp + rename, then verify.
1551
+ */
1552
+ export function recoverInflight(sessionPath, options = {}) {
1553
+ const info = readInflight(sessionPath);
1554
+ if (!info) return { status: 'none', recovered: false };
1555
+ const target = info.target || sessionPath;
1556
+ if (!fs.existsSync(target)) {
1557
+ if (!info.backupPath || !fs.existsSync(info.backupPath)) {
1558
+ throw visibleError(ERROR_CODES.INFLIGHT_BACKUP_MISSING,
1559
+ `target ${target} is missing and the inflight backup ${info.backupPath ?? '(none)'} does not exist; ` +
1560
+ 'restore it from your own backup before retrying');
1561
+ }
1562
+ } else {
1563
+ const current = sha256File(target);
1564
+ if (current === info.expectedSha256) {
1565
+ cleanupTmp(info);
1566
+ removeIfExists(info.inflightPath);
1567
+ return { status: 'completed', recovered: false, target, sha256: current };
1568
+ }
1569
+ if (current === info.beforeSha256) {
1570
+ cleanupTmp(info);
1571
+ removeIfExists(info.inflightPath);
1572
+ return { status: 'clean', recovered: false, target, sha256: current };
1573
+ }
1574
+ }
1575
+
1576
+ if (!info.backupPath || !fs.existsSync(info.backupPath)) {
1577
+ throw visibleError(ERROR_CODES.INFLIGHT_BACKUP_MISSING,
1578
+ `cannot roll back ${target}: backup ${info.backupPath ?? '(none)'} is missing. ` +
1579
+ `Restore it manually from your own backup.`);
1580
+ }
1581
+ if (info.backupSha256) {
1582
+ const check = verifyBackup(info.backupPath, info.backupSha256);
1583
+ if (!check.ok) {
1584
+ throw visibleError(ERROR_CODES.BACKUP_MISMATCH,
1585
+ `cannot roll back ${target}: backup ${info.backupPath} failed verification (${check.reason})`);
1586
+ }
1587
+ }
1588
+ const restoreTmp = `${target}.restore-${process.pid}-${Date.now()}`;
1589
+ try {
1590
+ writeDurable(restoreTmp, fs.readFileSync(info.backupPath));
1591
+ const restoredSha = sha256File(restoreTmp);
1592
+ if (info.beforeSha256 && restoredSha !== info.beforeSha256) {
1593
+ throw visibleError(ERROR_CODES.BACKUP_MISMATCH,
1594
+ `restored bytes ${restoredSha} != before hash ${info.beforeSha256}`);
1595
+ }
1596
+ fs.renameSync(restoreTmp, target);
1597
+ fsyncDirBestEffort(path.dirname(target));
1598
+ const finalSha = sha256File(target);
1599
+ if (info.beforeSha256 && finalSha !== info.beforeSha256) {
1600
+ throw visibleError(ERROR_CODES.BACKUP_MISMATCH,
1601
+ `after restore, ${target} has sha256 ${finalSha}, expected ${info.beforeSha256}`);
1602
+ }
1603
+ cleanupTmp(info);
1604
+ removeIfExists(info.inflightPath);
1605
+ return {
1606
+ status: 'rolled-back',
1607
+ recovered: true,
1608
+ target,
1609
+ sha256: finalSha,
1610
+ backupPath: info.backupPath,
1611
+ archivePath: info.archivePath ?? null,
1612
+ startedAt: info.startedAt ?? null,
1613
+ };
1614
+ } finally {
1615
+ removeIfExists(restoreTmp);
1616
+ }
1617
+ }
1618
+
1619
+ /**
1620
+ * Scan a DSH home for inflight records and recover each. Used at plugin start.
1621
+ * One bad record never prevents the others from being checked.
1622
+ */
1623
+ export function sweepInflight(root, options = {}) {
1624
+ const results = [];
1625
+ if (!root || !fs.existsSync(root)) return results;
1626
+ const maxDepth = options.maxDepth ?? 6;
1627
+ const stack = [{ dir: root, depth: 0 }];
1628
+ while (stack.length) {
1629
+ const { dir, depth } = stack.pop();
1630
+ let entries;
1631
+ try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { continue; }
1632
+ for (const entry of entries) {
1633
+ const full = path.join(dir, entry.name);
1634
+ if (entry.isFile() && entry.name === INFLIGHT_FILENAME) {
1635
+ try {
1636
+ results.push({ file: full, ...recoverInflight(path.join(dir, 'session.v4.jsonl.zstd')) });
1637
+ } catch (error) {
1638
+ results.push({ file: full, status: 'error', code: error?.code ?? 'VISIBLE_RECOVERY_FAILED', message: error.message });
1639
+ }
1640
+ } else if (entry.isDirectory() && depth < maxDepth && !entry.name.endsWith(ARCHIVE_DIR_SUFFIX)) {
1641
+ stack.push({ dir: full, depth: depth + 1 });
1642
+ }
1643
+ }
1644
+ }
1645
+ return results;
1646
+ }
1647
+
1648
+ // ---------------------------------------------------------------------------
1649
+ // the operation
1650
+ // ---------------------------------------------------------------------------
1651
+
1652
+ /**
1653
+ * Resolve a cut that both plans and *builds*: the boundary is only accepted
1654
+ * when the rewritten log can be encoded and lands within the token budget.
1655
+ *
1656
+ * 0.8.0-rc.11 (defect B): when the first boundary cannot be stabilized, retry
1657
+ * with one more whole turn dropped (up to `boundaryRetries`, default 3). The
1658
+ * old code threw `VISIBLE_NO_BOUNDARY` straight out of the build and
1659
+ * `onTurnEnd` swallowed it, so a dry run failed silently and the next turn
1660
+ * wrote another request. Now the failure is a value: the caller either gets a
1661
+ * feasible plan/built pair or a structured `{feasible:false, code, reason,
1662
+ * attempts}` and can log it.
1663
+ *
1664
+ * @returns {{feasible:boolean, needed:boolean, plan:object|null, built:object|null,
1665
+ * attempts:Array, overBy:number, code?:string, reason?:string, error?:Error}}
1666
+ */
1667
+ export function resolveVisibleCut(parsed, options = {}) {
1668
+ const keepTurns = options.keepTurns ?? DEFAULT_KEEP_TURNS;
1669
+ const keepTokens = options.keepTokens ?? DEFAULT_KEEP_TOKENS;
1670
+ const firstUserCapChars = resolvePositiveInt('firstUserCapChars',
1671
+ options.firstUserCapChars, DEFAULT_FIRST_USER_CAP_CHARS);
1672
+ const boundaryRetries = options.boundaryRetries ?? DEFAULT_BOUNDARY_RETRIES;
1673
+ if (!(Number.isInteger(boundaryRetries) && boundaryRetries >= 0)) {
1674
+ throw visibleError(ERROR_CODES.BAD_ARGUMENT,
1675
+ `boundaryRetries must be an integer >= 0 (got ${JSON.stringify(options.boundaryRetries)})`);
1676
+ }
1677
+ const archivePath = options.archivePath ?? null;
1678
+ const now = options.now ?? Date.now();
1679
+ const ceiling = Math.ceil(keepTokens * BUDGET_SLACK);
1680
+
1681
+ const attempts = [];
1682
+ let lastPlan = null;
1683
+ let lastError = null;
1684
+ let previousCutIndex = null;
1685
+
1686
+ for (let attempt = 0; attempt <= boundaryRetries; attempt += 1) {
1687
+ const plan = planVisibleTruncation(parsed, {
1688
+ keepTurns,
1689
+ keepTokens,
1690
+ firstUserCapChars,
1691
+ extraDroppedTurns: attempt,
1692
+ carryFirstUserMessage: options.carryFirstUserMessage,
1693
+ insertArchiveCard: options.insertArchiveCard,
1694
+ archivePath,
1695
+ });
1696
+ if (!plan.needed) {
1697
+ if (attempt === 0) return { feasible: true, needed: false, plan, built: null, attempts };
1698
+ break; // trimming walked past the last droppable turn
1699
+ }
1700
+ // The guards clamped the boundary at the last turn: retrying would repeat
1701
+ // the same plan, so stop and report what actually happened.
1702
+ if (previousCutIndex !== null && plan.cutTurnIndex === previousCutIndex) break;
1703
+ previousCutIndex = plan.cutTurnIndex;
1704
+ lastPlan = plan;
1705
+
1706
+ if (plan.feasible === false) {
1707
+ lastError = visibleError(ERROR_CODES.TOKEN_BUDGET, plan.infeasible.reason);
1708
+ lastError.details = {
1709
+ code: ERROR_CODES.TOKEN_BUDGET,
1710
+ keepTokens,
1711
+ ceiling,
1712
+ tokens: plan.budget.afterTokens,
1713
+ candidates: null,
1714
+ survived: null,
1715
+ budget: plan.budget,
1716
+ limit: plan.infeasible.limit ?? null,
1717
+ };
1718
+ attempts.push({
1719
+ attempt,
1720
+ keepTurns,
1721
+ cutTurn: plan.cutTurn,
1722
+ cutIndex: plan.cutIndex,
1723
+ code: ERROR_CODES.TOKEN_BUDGET,
1724
+ tokens: plan.budget.afterTokens,
1725
+ overBy: plan.budget.overBy,
1726
+ });
1727
+ continue;
1728
+ }
1729
+
1730
+ try {
1731
+ const built = buildVisibleTruncated(parsed, plan, {
1732
+ now,
1733
+ archivePath,
1734
+ eventsPerFrame: options.eventsPerFrame,
1735
+ stabilizePasses: options.stabilizePasses,
1736
+ });
1737
+ const overBy = Math.max(0, built.tokens - keepTokens);
1738
+ const within = built.tokens <= ceiling;
1739
+ attempts.push({
1740
+ attempt,
1741
+ keepTurns,
1742
+ cutTurn: plan.cutTurn,
1743
+ cutIndex: plan.cutIndex,
1744
+ tokens: built.tokens,
1745
+ overBy,
1746
+ stabilizePasses: built.stabilizePasses,
1747
+ code: within ? null : ERROR_CODES.TOKEN_BUDGET,
1748
+ });
1749
+ if (within) {
1750
+ return { feasible: true, needed: true, plan, built, attempts, overBy };
1751
+ }
1752
+ lastError = visibleError(ERROR_CODES.TOKEN_BUDGET,
1753
+ `post-cut estimate ${built.tokens} exceeds keepTokens ${keepTokens} (ceiling ${ceiling}) ` +
1754
+ `at cut turn ${plan.cutTurn}`);
1755
+ lastError.details = {
1756
+ code: ERROR_CODES.TOKEN_BUDGET,
1757
+ keepTokens,
1758
+ ceiling,
1759
+ tokens: built.tokens,
1760
+ cutTurn: plan.cutTurn,
1761
+ candidates: built.retainedMessages,
1762
+ survived: built.retainedEvents,
1763
+ };
1764
+ } catch (error) {
1765
+ // 1.8.1-rc.7: a replacement that straddles the cut is a boundary problem,
1766
+ // not a reason to give up. The previous build threw it straight out of
1767
+ // resolveVisibleCut, so the retry ladder never got a chance; dropping one
1768
+ // more whole turn can put the cut after the replacement's start/end pair.
1769
+ // NO_BOUNDARY is the existing retryable class; keep the list explicit so
1770
+ // an unrelated write/verify error is still surfaced immediately.
1771
+ const retryable = error?.code === ERROR_CODES.NO_BOUNDARY
1772
+ || error?.code === ERROR_CODES.REPLACEMENT_STRADDLES_CUT;
1773
+ if (!retryable) throw error;
1774
+ lastError = error;
1775
+ attempts.push({
1776
+ attempt,
1777
+ keepTurns,
1778
+ cutTurn: plan.cutTurn,
1779
+ cutIndex: plan.cutIndex,
1780
+ code: error.code,
1781
+ candidates: error.details?.candidates ?? null,
1782
+ survived: error.details?.survived ?? null,
1783
+ passes: error.details?.passes ?? null,
1784
+ });
1785
+ // The next attempt drops one more whole turn and re-runs the guards.
1786
+ }
1787
+ }
1788
+
1789
+ const code = lastError?.code ?? ERROR_CODES.NO_BOUNDARY;
1790
+ const reason = lastError?.message ?? 'no cut could be stabilized';
1791
+ const error = lastError ?? visibleError(code, reason);
1792
+ error.details = {
1793
+ ...(error.details ?? {}),
1794
+ code,
1795
+ attempts,
1796
+ keepTurns,
1797
+ keepTokens,
1798
+ firstUserCapChars,
1799
+ boundaryRetries,
1800
+ };
1801
+ error.attempts = attempts;
1802
+ return {
1803
+ feasible: false,
1804
+ needed: true,
1805
+ plan: lastPlan,
1806
+ built: null,
1807
+ attempts,
1808
+ code,
1809
+ reason,
1810
+ error,
1811
+ };
1812
+ }
1813
+
1814
+ function ledgerFor(sessionPath) {
1815
+ return path.join(path.dirname(sessionPath), LEDGER_FILENAME);
1816
+ }
1817
+
1818
+ function appendLedger(sessionPath, entry) {
1819
+ const file = ledgerFor(sessionPath);
1820
+ let ledger = { version: 1, truncations: [] };
1821
+ if (fs.existsSync(file)) {
1822
+ try {
1823
+ const parsed = JSON.parse(fs.readFileSync(file, 'utf8'));
1824
+ if (Array.isArray(parsed.truncations)) ledger = { version: parsed.version ?? 1, truncations: parsed.truncations };
1825
+ } catch { /* replace a corrupt ledger, never block the write */ }
1826
+ }
1827
+ ledger.truncations.push(entry);
1828
+ if (ledger.truncations.length > 50) ledger.truncations = ledger.truncations.slice(-50);
1829
+ fs.writeFileSync(file, JSON.stringify(ledger, null, 2) + '\n', 'utf8');
1830
+ }
1831
+
1832
+ // Test-only read seam: the suite makes the post-rename read return bytes that
1833
+ // differ from what was written, so the read-back verification (and its rollback)
1834
+ // is exercised on its own instead of failing earlier in the write. The file on
1835
+ // disk keeps the bytes we wrote; only the value read here changes.
1836
+ function readBackCorrupted(sessionPath) {
1837
+ const buf = Buffer.from(fs.readFileSync(sessionPath));
1838
+ if (buf.length > 0) buf[buf.length - 1] ^= 0x01;
1839
+ return buf;
1840
+ }
1841
+
1842
+ function readbackVerify(sessionPath, expected, readFile = fs.readFileSync) {
1843
+ const buf = readFile(sessionPath);
1844
+ const actualSha = sha256(buf);
1845
+ if (actualSha !== expected.sha256) {
1846
+ throw visibleError(ERROR_CODES.POST_VERIFY,
1847
+ `read-back sha256 ${actualSha} != written ${expected.sha256}`);
1848
+ }
1849
+ const parsed = parseSession(buf);
1850
+ assertContiguous(parsed.events);
1851
+ if (parsed.events.length !== expected.events.length) {
1852
+ throw visibleError(ERROR_CODES.POST_VERIFY,
1853
+ `read-back has ${parsed.events.length} events, expected ${expected.events.length}`);
1854
+ }
1855
+ const digest = deriveMessagesDigest(parsed.header, parsed.events);
1856
+ if (digest.count !== expected.messages) {
1857
+ throw visibleError(ERROR_CODES.POST_VERIFY,
1858
+ `read-back derives ${digest.count} messages, expected ${expected.messages}`);
1859
+ }
1860
+ return { sha256: actualSha, events: parsed.events.length, messages: digest.count };
1861
+ }
1862
+
1863
+ function restoreBackup(target, backupPath, expectedSha, log) {
1864
+ const tmp = `${target}.rollback-${process.pid}-${Date.now()}`;
1865
+ try {
1866
+ writeDurable(tmp, fs.readFileSync(backupPath));
1867
+ const got = sha256File(tmp);
1868
+ if (expectedSha && got !== expectedSha) {
1869
+ throw visibleError(ERROR_CODES.BACKUP_MISMATCH,
1870
+ `rollback copy ${got} != expected ${expectedSha}`);
1871
+ }
1872
+ fs.renameSync(tmp, target);
1873
+ fsyncDirBestEffort(path.dirname(target));
1874
+ const finalSha = sha256File(target);
1875
+ if (expectedSha && finalSha !== expectedSha) {
1876
+ throw visibleError(ERROR_CODES.BACKUP_MISMATCH,
1877
+ `after rollback ${target} has sha256 ${finalSha}, expected ${expectedSha}`);
1878
+ }
1879
+ log.push({ step: 'rollback', ok: true, backupPath, sha256: finalSha });
1880
+ return { ok: true, sha256: finalSha };
1881
+ } finally {
1882
+ removeIfExists(tmp);
1883
+ }
1884
+ }
1885
+
1886
+ export function rollbackCommand(backupPath, target) {
1887
+ if (process.platform === 'win32') {
1888
+ return `Copy-Item -LiteralPath "${backupPath}" -Destination "${target}" -Force`;
1889
+ }
1890
+ return `cp -f "${backupPath}" "${target}"`;
1891
+ }
1892
+
1893
+ /**
1894
+ * Main entry point. Defaults to a dry run; writing needs
1895
+ * `confirm: "TRUNCATE-VISIBLE"`.
1896
+ */
1897
+ export function truncateVisibleSession(sessionPath, options = {}) {
1898
+ const dryRun = options.dryRun !== false;
1899
+ const keepTurns = options.keepTurns ?? DEFAULT_KEEP_TURNS;
1900
+ const keepTokens = options.keepTokens ?? DEFAULT_KEEP_TOKENS;
1901
+ const now = options.now ?? Date.now();
1902
+ const eventsPerFrame = options.eventsPerFrame ?? DEFAULT_EVENTS_PER_FRAME;
1903
+ const log = [];
1904
+ const abs = path.resolve(sessionPath);
1905
+ // 1.8.1-rc.7: one durable diagnostic row per non-dry-run truncation attempt.
1906
+ // The archive is the operation that matters; a failure after the archive is
1907
+ // still a failed truncation, and is recorded with archiveWritten:true.
1908
+ const diagStartedAt = Date.now();
1909
+ const diagRoot = typeof options.memoryRoot === 'string' && options.memoryRoot.trim() !== ''
1910
+ ? options.memoryRoot.trim()
1911
+ : null;
1912
+ const diagOptions = options.diagOptions && typeof options.diagOptions === 'object'
1913
+ ? options.diagOptions
1914
+ : hotTruncateDiagOptions(options.autoTruncate ?? {});
1915
+ let diagArchiveWritten = false;
1916
+ let diagEmitted = false;
1917
+ function emitTruncationDiag(payload) {
1918
+ if (dryRun || !diagRoot || diagEmitted) return;
1919
+ diagEmitted = true;
1920
+ const written = appendHotTruncateDiag(diagRoot, {
1921
+ sessionId: options.sessionId ?? parsed?.header?.id ?? null,
1922
+ turn: options.turn ?? payload.turn ?? null,
1923
+ sessionPath: abs,
1924
+ plannedCut: payload.plannedCut ?? null,
1925
+ retainTurns: keepTurns,
1926
+ retainTokens: keepTokens,
1927
+ tokensBefore: payload.tokensBefore ?? null,
1928
+ tokensAfter: payload.tokensAfter ?? null,
1929
+ bytesBefore: payload.bytesBefore ?? null,
1930
+ bytesAfter: payload.bytesAfter ?? null,
1931
+ archivePath: payload.archivePath ?? null,
1932
+ archiveWritten: payload.archiveWritten === true,
1933
+ archiveBytes: payload.archiveBytes ?? null,
1934
+ archiveEvents: payload.archiveEvents ?? null,
1935
+ attempts: payload.attempts ?? null,
1936
+ result: payload.result,
1937
+ degradeReason: payload.degradeReason ?? null,
1938
+ failReason: payload.failReason ?? null,
1939
+ durationMs: Math.max(0, Date.now() - diagStartedAt),
1940
+ diagnosticsVersion: 1,
1941
+ }, diagOptions);
1942
+ if (!written.ok && typeof options.logger?.warn === 'function') {
1943
+ options.logger.warn(`[truncate-visible] diag write failed: ${written.error ?? 'unknown'}`);
1944
+ }
1945
+ }
1946
+
1947
+ if (!fs.existsSync(abs)) {
1948
+ throw visibleError(ERROR_CODES.NOT_FOUND,
1949
+ `no such session log: ${abs} — run session_health to list sessions, or pass ` +
1950
+ 'sessionId / session:"latest". Nothing was written.');
1951
+ }
1952
+ if (/\.bak-/.test(path.basename(abs))) {
1953
+ throw visibleError(ERROR_CODES.IS_BACKUP, `${path.basename(abs)} is a backup; point at session.v4.jsonl.zstd`);
1954
+ }
1955
+ if (!fs.statSync(abs).isFile()) {
1956
+ throw visibleError(ERROR_CODES.BAD_ARGUMENT, `not a regular file: ${abs}`);
1957
+ }
1958
+ if (!dryRun && options.confirm !== VISIBLE_CONFIRM_WORD) {
1959
+ throw visibleError(ERROR_CODES.CONFIRM_REQUIRED,
1960
+ `refusing to write: pass confirm:"${VISIBLE_CONFIRM_WORD}" (got ${JSON.stringify(options.confirm)})`);
1961
+ }
1962
+
1963
+ if (!dryRun) {
1964
+ const stale = readInflight(abs);
1965
+ if (stale) {
1966
+ const recovered = recoverInflight(abs, { now });
1967
+ log.push({ step: 'recover-stale-inflight', ...recovered });
1968
+ }
1969
+ }
1970
+
1971
+ const snapshot = readSnapshot(abs);
1972
+ const parsed = parseSession(snapshot.buf);
1973
+ const archivePath = nextArchivePath(abs, now);
1974
+ const resolved = resolveVisibleCut(parsed, {
1975
+ keepTurns,
1976
+ keepTokens,
1977
+ firstUserCapChars: options.firstUserCapChars,
1978
+ boundaryRetries: options.boundaryRetries,
1979
+ carryFirstUserMessage: options.carryFirstUserMessage,
1980
+ insertArchiveCard: options.insertArchiveCard,
1981
+ archivePath,
1982
+ now,
1983
+ eventsPerFrame,
1984
+ stabilizePasses: options.stabilizePasses,
1985
+ });
1986
+
1987
+ if (!resolved.needed) {
1988
+ const noop = {
1989
+ ok: true,
1990
+ needed: false,
1991
+ feasible: true,
1992
+ status: 'noop',
1993
+ sessionPath: abs,
1994
+ keepTurns,
1995
+ keepTokens,
1996
+ reason: resolved.plan.reason,
1997
+ original: resolved.plan.original,
1998
+ before: { ...resolved.plan.original, sha256: snapshot.sha256 },
1999
+ firstUserMessage: resolved.plan.firstUserMessage ?? null,
2000
+ firstUserMessageNote: resolved.plan.firstUserMessageNote ?? null,
2001
+ archivePath: null,
2002
+ };
2003
+ noop.message = formatVisibleReport(noop);
2004
+ return noop;
2005
+ }
2006
+
2007
+ if (!resolved.feasible) {
2008
+ const error = resolved.error;
2009
+ error.result = {
2010
+ sessionPath: abs,
2011
+ needed: true,
2012
+ feasible: false,
2013
+ archivePath: null,
2014
+ before: { ...sessionEstimate(parsed), sha256: snapshot.sha256 },
2015
+ attempts: resolved.attempts,
2016
+ limit: resolved.plan?.infeasible?.limit ?? error?.details?.limit ?? null,
2017
+ };
2018
+ if (!dryRun) {
2019
+ // Writing mode: nothing is ever written on an infeasible cut. Record the
2020
+ // attempt (result:fail) before throwing so a future audit can tell
2021
+ // "nothing to do" from "tried and could not".
2022
+ emitTruncationDiag({
2023
+ result: 'fail',
2024
+ failReason: `${resolved.code ?? ERROR_CODES.NO_BOUNDARY}: ${resolved.reason ?? 'infeasible'}`,
2025
+ tokensBefore: sessionEstimate(parsed).tokens,
2026
+ bytesBefore: snapshot.size,
2027
+ attempts: resolved.attempts?.length ?? 0,
2028
+ plannedCut: resolved.plan
2029
+ ? { turn: resolved.plan.cutTurn ?? null, seq: resolved.plan.cutIndex ?? null }
2030
+ : null,
2031
+ archiveWritten: false,
2032
+ });
2033
+ throw error;
2034
+ }
2035
+ const infeasible = {
2036
+ ok: false,
2037
+ needed: true,
2038
+ feasible: false,
2039
+ dryRun: true,
2040
+ applied: false,
2041
+ status: 'infeasible',
2042
+ sessionPath: abs,
2043
+ keepTurns,
2044
+ keepTokens,
2045
+ firstUserCapChars: resolved.plan?.firstUserCapChars ?? options.firstUserCapChars ?? DEFAULT_FIRST_USER_CAP_CHARS,
2046
+ code: resolved.code,
2047
+ reason: resolved.reason,
2048
+ attempts: resolved.attempts,
2049
+ limit: resolved.plan?.infeasible?.limit ?? error?.details?.limit ?? null,
2050
+ cut: null,
2051
+ before: { ...sessionEstimate(parsed), sha256: snapshot.sha256 },
2052
+ // The report still needs these shapes; an empty plan is honest about it.
2053
+ droppedTurns: [],
2054
+ keptTurns: [],
2055
+ dropped: { bytes: 0, events: 0, messages: 0, tokens: 0 },
2056
+ kept: { bytes: 0, events: 0, messages: 0, tokens: 0 },
2057
+ after: null,
2058
+ archivePath: null,
2059
+ archive: null,
2060
+ log,
2061
+ };
2062
+ infeasible.message = formatVisibleReport(infeasible);
2063
+ return infeasible;
2064
+ }
2065
+
2066
+ const plan = resolved.plan;
2067
+ const built = resolved.built;
2068
+ const archive = buildArchiveBuffer(parsed, plan, { eventsPerFrame });
2069
+ const result = {
2070
+ ok: true,
2071
+ needed: true,
2072
+ dryRun,
2073
+ applied: false,
2074
+ status: dryRun ? 'planned' : 'truncated',
2075
+ feasible: true,
2076
+ sessionPath: abs,
2077
+ keepTurns,
2078
+ keepTokens,
2079
+ firstUserCapChars: plan.firstUserCapChars,
2080
+ attempts: resolved.attempts,
2081
+ cut: {
2082
+ turn: plan.cutTurn,
2083
+ index: plan.cutIndex,
2084
+ startSeq: plan.cutTurnStartSeq,
2085
+ droppedTurns: plan.droppedTurnCount,
2086
+ keptTurns: plan.keptTurnCount,
2087
+ },
2088
+ droppedTurnCount: plan.droppedTurnCount,
2089
+ keptTurnCount: plan.keptTurnCount,
2090
+ droppedTurns: plan.droppedTurns,
2091
+ keptTurns: plan.keptTurns,
2092
+ before: { ...plan.original, sha256: snapshot.sha256 },
2093
+ dropped: plan.dropped,
2094
+ kept: plan.kept,
2095
+ after: {
2096
+ bytes: built.bytes,
2097
+ events: built.events.length,
2098
+ messages: built.messages,
2099
+ tokens: built.tokens,
2100
+ sha256: built.sha256,
2101
+ },
2102
+ retainedEvents: built.retainedEvents,
2103
+ retainedMessages: built.retainedMessages,
2104
+ archivePath,
2105
+ archive: { bytes: archive.bytes, events: archive.events, sha256: archive.sha256 },
2106
+ headCopied: built.headCopied,
2107
+ headSourceSeq: built.headSourceSeq,
2108
+ // Seeded sessions: the single inherited marker now written at index 0, or
2109
+ // null when the log is unseeded. Reported so the CLI/orchestrator can prove
2110
+ // the metadata was rewritten with the events.
2111
+ seedMarker: built.seedMarker,
2112
+ archiveCard: plan.insertArchiveCard ? { inserted: true, text: built.cardText } : { inserted: false },
2113
+ budget: plan.budget,
2114
+ firstUserMessage: plan.firstUserMessage
2115
+ ? { ...plan.firstUserMessage, carried: Boolean(built.carryText), carriedText: built.carryText }
2116
+ : null,
2117
+ firstUserCarry: plan.firstUserCarry ?? null,
2118
+ firstUserMessageNote: plan.firstUserMessageNote ?? null,
2119
+ backupPath: null,
2120
+ inflightPath: inflightPathFor(abs),
2121
+ log,
2122
+ rollback: null,
2123
+ };
2124
+
2125
+ if (dryRun) {
2126
+ result.message = formatVisibleReport(result);
2127
+ return result;
2128
+ }
2129
+
2130
+ assertNotLive(abs, { recentWriteWindowMs: options.recentWriteWindowMs ?? 60_000, now });
2131
+ assertUnchanged(abs, snapshot);
2132
+
2133
+ const archiveDir = archiveDirFor(abs);
2134
+ fs.mkdirSync(archiveDir, { recursive: true });
2135
+ if (fs.existsSync(archivePath)) {
2136
+ throw visibleError(ERROR_CODES.ARCHIVE_EXISTS,
2137
+ `archive already exists: ${archivePath} — archives are never overwritten. ` +
2138
+ 'Re-run with a different session, or move/rename the existing archive after checking it.');
2139
+ }
2140
+ writeDurable(archivePath, archive.buffer);
2141
+ diagArchiveWritten = true;
2142
+ const archiveCheck = parseSession(fs.readFileSync(archivePath));
2143
+ if (archiveCheck.events.length !== archive.events) {
2144
+ throw visibleError(ERROR_CODES.ARCHIVE_VERIFY,
2145
+ `archive has ${archiveCheck.events.length} events, expected ${archive.events}`);
2146
+ }
2147
+ log.push({ step: 'archive', ok: true, file: archivePath, bytes: archive.bytes, events: archive.events });
2148
+
2149
+ const backup = ensureBackup(abs, {
2150
+ date: new Date(now),
2151
+ sourceBuf: snapshot.buf,
2152
+ sha256: snapshot.sha256,
2153
+ size: snapshot.size,
2154
+ });
2155
+ const backupCheck = verifyBackup(backup.file, snapshot.sha256);
2156
+ if (!backupCheck.ok) {
2157
+ throw visibleError(ERROR_CODES.BACKUP_MISMATCH,
2158
+ `backup ${backup.file} failed verification: ${backupCheck.reason}`);
2159
+ }
2160
+ result.backupPath = backup.file;
2161
+ result.rollback = rollbackCommand(backup.file, abs);
2162
+ log.push({ step: 'backup', ok: true, file: backup.file, created: backup.created });
2163
+
2164
+ const tmpPath = `${abs}.truncate-visible.tmp-${process.pid}-${now}`;
2165
+ const inflight = {
2166
+ version: 1,
2167
+ kind: 'session-truncate-visible',
2168
+ target: abs,
2169
+ archivePath,
2170
+ backupPath: backup.file,
2171
+ backupSha256: snapshot.sha256,
2172
+ beforeSha256: snapshot.sha256,
2173
+ beforeSize: snapshot.size,
2174
+ expectedSha256: built.sha256,
2175
+ expectedSize: built.bytes,
2176
+ expectedEvents: built.events.length,
2177
+ expectedMessages: built.messages,
2178
+ tmpPath,
2179
+ phase: 'prepared',
2180
+ startedAt: new Date(now).toISOString(),
2181
+ keepTurns,
2182
+ keepTokens,
2183
+ cutTurn: plan.cutTurn,
2184
+ cutSeq: plan.cutIndex,
2185
+ droppedEvents: plan.dropped.events,
2186
+ droppedMessages: plan.dropped.messages,
2187
+ keptEvents: built.retainedEvents,
2188
+ keptMessages: built.retainedMessages,
2189
+ platform: process.platform,
2190
+ pid: process.pid,
2191
+ };
2192
+ const inflightPath = inflightPathFor(abs);
2193
+ writeDurable(inflightPath, Buffer.from(JSON.stringify(inflight, null, 2) + '\n', 'utf8'));
2194
+ log.push({ step: 'inflight', ok: true, file: inflightPath });
2195
+
2196
+ const fault = (name) => {
2197
+ if (options.faultAt === name) {
2198
+ throw visibleError(ERROR_CODES.FAULT_INJECTED, `injected fault at ${name} (test only)`);
2199
+ }
2200
+ };
2201
+
2202
+ try {
2203
+ fault('after-backup');
2204
+
2205
+ writeDurable(tmpPath, built.buffer);
2206
+ const tmpBuf = fs.readFileSync(tmpPath);
2207
+ if (sha256(tmpBuf) !== built.sha256) {
2208
+ throw visibleError(ERROR_CODES.TMP_VERIFY, 'tmp file sha256 does not match the in-memory buffer');
2209
+ }
2210
+ const tmpParsed = parseSession(tmpBuf);
2211
+ if (tmpParsed.events.length !== built.events.length) {
2212
+ throw visibleError(ERROR_CODES.TMP_VERIFY,
2213
+ `tmp parses to ${tmpParsed.events.length} events, expected ${built.events.length}`);
2214
+ }
2215
+ const tmpDigest = deriveMessagesDigest(tmpParsed.header, tmpParsed.events);
2216
+ if (tmpDigest.count !== built.messages) {
2217
+ throw visibleError(ERROR_CODES.TMP_VERIFY,
2218
+ `tmp derives ${tmpDigest.count} messages, expected ${built.messages}`);
2219
+ }
2220
+ log.push({ step: 'tmp', ok: true, file: tmpPath, bytes: built.bytes });
2221
+ fault('after-tmp');
2222
+
2223
+ assertUnchanged(abs, snapshot);
2224
+ fault('before-rename');
2225
+
2226
+ fs.renameSync(tmpPath, abs);
2227
+ fsyncDirBestEffort(path.dirname(abs));
2228
+ log.push({ step: 'rename', ok: true, target: abs });
2229
+ fault('after-rename');
2230
+
2231
+ const readBack = options.faultAt === 'after-rename-corrupt-readback'
2232
+ ? readBackCorrupted
2233
+ : undefined;
2234
+ const verified = readbackVerify(abs, {
2235
+ sha256: built.sha256,
2236
+ events: built.events,
2237
+ messages: built.messages,
2238
+ }, readBack);
2239
+ log.push({ step: 'read-back', ok: true, ...verified });
2240
+
2241
+ removeIfExists(inflightPath);
2242
+ result.applied = true;
2243
+ result.backupPath = backup.file;
2244
+ result.rollback = rollbackCommand(backup.file, abs);
2245
+ result.readBack = verified;
2246
+ appendLedger(abs, {
2247
+ at: new Date(now).toISOString(),
2248
+ tool: 'session_truncate_visible',
2249
+ cutTurn: plan.cutTurn,
2250
+ cutSeq: plan.cutIndex,
2251
+ droppedTurns: plan.droppedTurnCount,
2252
+ keptTurns: plan.keptTurnCount,
2253
+ beforeBytes: snapshot.size,
2254
+ afterBytes: built.bytes,
2255
+ beforeMessages: plan.original.messages,
2256
+ afterMessages: built.messages,
2257
+ beforeTokens: plan.original.tokens,
2258
+ afterTokens: built.tokens,
2259
+ archivePath,
2260
+ backupPath: backup.file,
2261
+ beforeSha256: snapshot.sha256,
2262
+ afterSha256: built.sha256,
2263
+ });
2264
+ result.message = formatVisibleReport(result);
2265
+ emitTruncationDiag({
2266
+ result: (resolved.attempts?.length ?? 0) > 1 ? 'degraded' : 'ok',
2267
+ degradeReason: (resolved.attempts?.length ?? 0) > 1 ? 'boundary-retry (dropped extra turn)' : null,
2268
+ plannedCut: { turn: plan.cutTurn, seq: plan.cutIndex },
2269
+ turn: plan.cutTurn,
2270
+ tokensBefore: plan.original.tokens,
2271
+ tokensAfter: built.tokens,
2272
+ bytesBefore: snapshot.size,
2273
+ bytesAfter: built.bytes,
2274
+ archivePath,
2275
+ archiveWritten: true,
2276
+ archiveBytes: archive.bytes,
2277
+ archiveEvents: archive.events,
2278
+ attempts: resolved.attempts?.length ?? 0,
2279
+ });
2280
+ return result;
2281
+ } catch (error) {
2282
+ // The target is only touched by the rename. If the rename already landed
2283
+ // and verification failed, restore the exact bytes we snapshotted.
2284
+ let restore = null;
2285
+ if (fs.existsSync(abs) && sha256File(abs) !== snapshot.sha256) {
2286
+ try {
2287
+ restore = restoreBackup(abs, backup.file, snapshot.sha256, log);
2288
+ result.restored = true;
2289
+ removeIfExists(inflightPath);
2290
+ } catch (rollbackError) {
2291
+ result.restoreError = { code: rollbackError?.code, message: rollbackError.message };
2292
+ }
2293
+ } else {
2294
+ removeIfExists(tmpPath);
2295
+ removeIfExists(inflightPath);
2296
+ }
2297
+ if (restore?.ok) result.rollback = rollbackCommand(backup.file, abs);
2298
+ log.push({ step: 'failed', ok: false, code: error?.code ?? 'VISIBLE_TRUNCATE_FAILED', message: error.message });
2299
+ result.log = log;
2300
+ emitTruncationDiag({
2301
+ result: 'fail',
2302
+ failReason: `${error?.code ?? 'VISIBLE_TRUNCATE_FAILED'}: ${error?.message ?? String(error)}`,
2303
+ plannedCut: { turn: plan.cutTurn, seq: plan.cutIndex },
2304
+ turn: plan.cutTurn,
2305
+ tokensBefore: plan.original.tokens,
2306
+ tokensAfter: result.restored ? plan.original.tokens : built.tokens,
2307
+ bytesBefore: snapshot.size,
2308
+ bytesAfter: result.restored ? snapshot.size : built.bytes,
2309
+ archivePath,
2310
+ archiveWritten: diagArchiveWritten || fs.existsSync(archivePath),
2311
+ archiveBytes: archive.bytes,
2312
+ archiveEvents: archive.events,
2313
+ attempts: resolved.attempts?.length ?? 0,
2314
+ });
2315
+ error.result = result;
2316
+ throw error;
2317
+ }
2318
+ }
2319
+
2320
+ // ---------------------------------------------------------------------------
2321
+ // report
2322
+ // ---------------------------------------------------------------------------
2323
+
2324
+ function percentDrop(before, after) {
2325
+ if (!before) return '0.0%';
2326
+ return `${(((before - after) / before) * 100).toFixed(1)}%`;
2327
+ }
2328
+
2329
+ export function formatVisibleReport(result) {
2330
+ if (result && result.feasible === false) {
2331
+ const lines = [];
2332
+ lines.push('无法截断(infeasible,未写盘):没有可稳定保留下来的边界');
2333
+ lines.push(`目标:${result.sessionPath}`);
2334
+ lines.push(`原因(${result.code ?? 'VISIBLE_NO_BOUNDARY'}):${result.reason ?? 'unknown'}`);
2335
+ if (result.attempts?.length) {
2336
+ lines.push(`尝试:${result.attempts.length} 次(每次多删 1 轮)`);
2337
+ for (const attempt of result.attempts) {
2338
+ lines.push(` #${attempt.attempt + 1} cut turn ${attempt.cutTurn ?? '?'}` +
2339
+ `${attempt.code ? ` → ${attempt.code}` : ''}` +
2340
+ `${Number.isInteger(attempt.candidates) ? `(${attempt.candidates} candidates, ${attempt.survived} survived)` : ''}` +
2341
+ `${Number.isInteger(attempt.tokens) ? ` tokens ${attempt.tokens}` : ''}`);
2342
+ }
2343
+ }
2344
+ if (result.before) {
2345
+ lines.push(`原始:${formatBytes(result.before.bytes)} / ${result.before.events} 事件 / ` +
2346
+ `${result.before.messages} 条消息 / ≈${result.before.tokens.toLocaleString('en-US')} token`);
2347
+ }
2348
+ lines.push('没有写归档、没有写备份、没有改动会话文件。');
2349
+ return lines.join('\n');
2350
+ }
2351
+ if (!result || result.needed === false) {
2352
+ const note = result?.firstUserMessageNote ? `;${result.firstUserMessageNote}` : '';
2353
+ return `无操作:${result?.reason ?? 'nothing to drop'}(${result?.sessionPath ?? ''})${note}`;
2354
+ }
2355
+ const lines = [];
2356
+ lines.push(`${result.applied ? '已截断(宿主需重新加载)' : '预演(dry-run,未写盘)'}`);
2357
+ lines.push(`目标:${result.sessionPath}`);
2358
+ lines.push(`原始:${formatBytes(result.before.bytes)} / ${result.before.events} 事件 / ` +
2359
+ `${result.before.messages} 条消息 / ≈${result.before.tokens.toLocaleString('en-US')} token(MESSAGE_TYPES 的 data JSON/4 启发式)`);
2360
+ lines.push(`将删:turn 1–${result.cut.turn - 1}(seq 0–${result.cut.startSeq - 1}),` +
2361
+ `${result.droppedTurnCount ?? result.droppedTurns.length} 轮 / ${result.dropped.events} 事件 / ` +
2362
+ `${result.dropped.messages} 条消息 / 解压后 ${formatBytes(result.dropped.bytes)} / ` +
2363
+ `≈${result.dropped.tokens.toLocaleString('en-US')} token`);
2364
+ lines.push(`保留:turn ${result.cut.turn}–(seq ${result.cut.startSeq}–${result.before.events - 1}),` +
2365
+ `${result.keptTurnCount ?? result.keptTurns.length} 轮 / ${result.kept.events} 事件 / ` +
2366
+ `${result.kept.messages} 条消息`);
2367
+ if (result.firstUserMessage) {
2368
+ const note = result.firstUserMessage.carried
2369
+ ? '已复刻到保留段头'
2370
+ : '位于保留段内,未复刻';
2371
+ lines.push(`首条真人消息:seq ${result.firstUserMessage.seq}(${note}):${result.firstUserMessage.text}`);
2372
+ if (result.firstUserCarry) {
2373
+ const carry = result.firstUserCarry;
2374
+ lines.push(` 复刻文本:${carry.keptChars}/${carry.originalChars} 字符` +
2375
+ `${carry.capped ? `(已截断,上限 ${carry.capChars},原文见归档)` : '(未截断)'}`);
2376
+ }
2377
+ } else {
2378
+ lines.push(result.firstUserMessageNote ?? NO_USER_MESSAGE_NOTE);
2379
+ }
2380
+ if (result.budget) {
2381
+ lines.push(`预算:裁剪后 ≈${result.budget.afterTokens.toLocaleString('en-US')} token / ` +
2382
+ `keepTokens ${result.budget.keepTokens.toLocaleString('en-US')}` +
2383
+ `${result.budget.fits ? '(达标)' : `(超 ${result.budget.overBy},在 ${Math.round((result.budget.ceiling / result.budget.keepTokens - 1) * 100)}% 余量内)`}` +
2384
+ `${result.budget.trimmedTurns ? `,为达标多删 ${result.budget.trimmedTurns} 轮` : ''}`);
2385
+ }
2386
+ lines.push('切割清单:');
2387
+ for (const turn of result.droppedTurns) {
2388
+ lines.push(` turn ${turn.turn} seq ${turn.startSeq}–${turn.endSeq} ` +
2389
+ `${formatTime(turn.startTime)} → ${formatTime(turn.endTime)} ` +
2390
+ `${turn.messages} 条消息 首条:${turn.firstMessage}`);
2391
+ }
2392
+ lines.push('保留轮:');
2393
+ for (const turn of result.keptTurns) {
2394
+ lines.push(` turn ${turn.turn} seq ${turn.startSeq}–${turn.endSeq} ` +
2395
+ `${turn.messages} 条消息 首条:${turn.firstMessage}`);
2396
+ }
2397
+ lines.push(`头:${result.headCopied ? `已复制 system/message(原 seq ${result.headSourceSeq})` : '无'}`);
2398
+ lines.push(`归档卡:${result.archiveCard.inserted ? '已插入 user/message:' : '未插入'}`);
2399
+ if (result.archiveCard.inserted) {
2400
+ for (const line of result.archiveCard.text.split('\n')) lines.push(` ${line}`);
2401
+ }
2402
+ lines.push(`写后:${formatBytes(result.after.bytes)} / ${result.after.events} 事件 / ` +
2403
+ `${result.after.messages} 条消息 / ≈${result.after.tokens.toLocaleString('en-US')} token`);
2404
+ lines.push(`字节降幅:${percentDrop(result.before.bytes, result.after.bytes)};` +
2405
+ `token 降幅:${percentDrop(result.before.tokens, result.after.tokens)}`);
2406
+ lines.push(`归档:${result.archivePath}(${formatBytes(result.archive.bytes)} / ${result.archive.events} 事件)`);
2407
+ if (result.backupPath) lines.push(`备份:${result.backupPath}`);
2408
+ lines.push(`回滚:${result.rollback ?? (result.backupPath ? rollbackCommand(result.backupPath, result.sessionPath) : '(dry-run 无备份)')}`);
2409
+ if (result.log?.some((entry) => entry.step === 'failed')) {
2410
+ lines.push('日志:');
2411
+ for (const entry of result.log) {
2412
+ lines.push(` ${entry.step}: ${entry.ok === false ? 'FAILED' : 'ok'}${entry.code ? ` (${entry.code})` : ''}`);
2413
+ }
2414
+ }
2415
+ return lines.join('\n');
2416
+ }