@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,999 @@
1
+ // dsh-longlive — truncation core.
2
+ //
3
+ // Hard flow (SPEC §3). Every step either fully succeeds or leaves the original
4
+ // session file byte-identical:
5
+ //
6
+ // read -> split frames -> parse -> plan cut at a turn/start boundary
7
+ // -> build candidate (renumber seq, remap references, keep title,
8
+ // drop agent/inbox/* = live-inbox traffic that a resumed session
9
+ // must not inherit)
10
+ // -> prove deriveMessages digest unchanged
11
+ // -> prove inbox projection replays from an empty inbox
12
+ // -> verify backup exists with the right sha256
13
+ // -> write *.tmp -> re-read/verify tmp -> atomic rename
14
+ // -> re-read final -> ledger (or restore from backup + rollback.json)
15
+ //
16
+ // Nothing here reads message content beyond the fields needed to fold the
17
+ // Surface and hash the visible messages.
18
+
19
+ import fs from 'node:fs';
20
+ import path from 'node:path';
21
+ import { spawnSync } from 'node:child_process';
22
+ import {
23
+ parseSession,
24
+ encodeSession,
25
+ deriveMessagesDigest,
26
+ assertContiguous,
27
+ foldSurface,
28
+ sha256,
29
+ MESSAGE_TYPES,
30
+ } from './codec.js';
31
+ import { ensureBackup, verifyBackup } from './backup.js';
32
+
33
+ export const DEFAULT_KEEP_EVENTS = 20000;
34
+ export const RECENT_WRITE_WINDOW_MS = 60_000;
35
+ export const EVENTS_PER_FRAME = 2000;
36
+ export const CONFIRM_WORD = 'TRUNCATE';
37
+ export const INBOX_GUARD_WINDOW = 100;
38
+ // The session log's file name, and therefore the root of every backup name.
39
+ // Kept local so this module never imports the tool layer (tools.js imports us).
40
+ export const SESSION_FILENAME = 'session.v4.jsonl.zstd';
41
+
42
+ export const ERROR_CODES = {
43
+ NOT_FOUND: 'SESSION_NOT_FOUND',
44
+ RECENT_WRITE: 'SESSION_RECENT_WRITE',
45
+ LOCKED: 'SESSION_LOCKED',
46
+ FILE_BUSY: 'VISIBLE_FILE_BUSY',
47
+ CONFIRM_REQUIRED: 'CONFIRM_REQUIRED',
48
+ BACKUP_MISSING: 'BACKUP_MISSING',
49
+ BACKUP_MISMATCH: 'BACKUP_SHA256_MISMATCH',
50
+ NO_BOUNDARY: 'NO_TURN_BOUNDARY',
51
+ CONVERSATION_CHANGED: 'VISIBLE_CONVERSATION_CHANGED',
52
+ INBOX_INVALID: 'INBOX_PROJECTION_INVALID',
53
+ IS_BACKUP: 'IS_BACKUP',
54
+ TMP_VERIFY: 'TMP_VERIFY_FAILED',
55
+ POST_VERIFY: 'POST_WRITE_VERIFY_FAILED',
56
+ CHANGED: 'SESSION_CHANGED',
57
+ CORRUPT: 'SESSION_CORRUPT',
58
+ BAD_ARGUMENT: 'BAD_ARGUMENT',
59
+ };
60
+
61
+ export function sessionError(code, message, cause) {
62
+ const error = new Error(message);
63
+ error.code = code;
64
+ if (cause) error.cause = cause;
65
+ return error;
66
+ }
67
+
68
+ /** Types stored only for logging; dropping them cannot change the Surface. */
69
+ const LOG_ONLY_TYPES = new Set(['compaction/prune']);
70
+
71
+ /**
72
+ * Live agent-inbox traffic. A resumed session projects the inbox from an empty
73
+ * state, so splices that assumed items carried over from before the cut would
74
+ * throw `invalid persisted inbox splice at session seq N` (the 2026-10-30 bug).
75
+ * Dropping them is conservative: they are not part of the visible conversation.
76
+ */
77
+ export function isInboxEvent(event) {
78
+ return typeof event.type === 'string' && event.type.startsWith('agent/inbox/');
79
+ }
80
+
81
+ function truncationLedgerPath(sessionPath) {
82
+ return path.join(path.dirname(sessionPath), 'truncate.json');
83
+ }
84
+
85
+ function readJsonFile(file, fallback) {
86
+ if (!fs.existsSync(file)) return fallback;
87
+ try {
88
+ return JSON.parse(fs.readFileSync(file, 'utf8'));
89
+ } catch {
90
+ return fallback;
91
+ }
92
+ }
93
+
94
+ function writeJsonFile(file, value) {
95
+ fs.writeFileSync(file, JSON.stringify(value, null, 2) + '\n', 'utf8');
96
+ }
97
+
98
+ /** True when the first `window` retained events contain live inbox traffic. */
99
+ function inboxInWindow(events, index, window = INBOX_GUARD_WINDOW) {
100
+ return events.slice(index, index + window).some(isInboxEvent);
101
+ }
102
+
103
+ export function planTruncation(parsed, { keepEvents = DEFAULT_KEEP_EVENTS } = {}) {
104
+ const events = parsed.events;
105
+ if (!Number.isInteger(keepEvents) || keepEvents < 1) {
106
+ throw sessionError(ERROR_CODES.BAD_ARGUMENT, `keepEvents must be a positive integer (got ${keepEvents})`);
107
+ }
108
+ if (events.length <= keepEvents) return { needed: false, events: events.length, keepEvents };
109
+
110
+ const naive = events.length - keepEvents;
111
+ let index = naive;
112
+ while (index < events.length && events[index].type !== 'turn/start') index += 1;
113
+ if (index >= events.length) {
114
+ throw sessionError(ERROR_CODES.NO_BOUNDARY,
115
+ 'cannot find a turn/start boundary inside the keep window; refusing to cut mid-turn');
116
+ }
117
+
118
+ // Dropping an event is only safe when it is already invisible in the
119
+ // original Surface. Everything from the first visible message onward must
120
+ // survive, so the cut can never be later than that node's seq.
121
+ const visible = foldSurface(events).filter((node) => MESSAGE_TYPES.has(node.type));
122
+ const firstVisibleSeq = visible.length > 0 ? visible[0].seq : events.length;
123
+ let limitedByVisible = false;
124
+ if (index > firstVisibleSeq) {
125
+ let j = Math.min(firstVisibleSeq, events.length - 1);
126
+ while (j >= 0 && events[j].type !== 'turn/start') j -= 1;
127
+ if (j < 0) {
128
+ throw sessionError(ERROR_CODES.NO_BOUNDARY,
129
+ `no turn/start at or before the first visible message (seq ${firstVisibleSeq})`);
130
+ }
131
+ index = j;
132
+ limitedByVisible = true;
133
+ }
134
+
135
+ const cutTurn = events[index].data?.turn;
136
+ if (!Number.isInteger(cutTurn) || cutTurn < 1) {
137
+ throw sessionError(ERROR_CODES.NO_BOUNDARY, `turn/start at seq ${index} has no usable turn number`);
138
+ }
139
+ return {
140
+ needed: true,
141
+ keepEvents,
142
+ naiveCutIndex: naive,
143
+ cutIndex: index,
144
+ cutSeq: index,
145
+ cutTurn,
146
+ firstVisibleSeq,
147
+ limitedByVisible,
148
+ droppedEvents: index,
149
+ retainedEvents: events.length - index,
150
+ inboxInWindow: inboxInWindow(events, index),
151
+ };
152
+ }
153
+
154
+ function compactionGroupId(event) {
155
+ const data = event.data ?? {};
156
+ if (event.type.startsWith('compaction/')) return data.compactionId ?? null;
157
+ if (data.source && typeof data.source === 'object' && data.source.compactionId) {
158
+ return data.source.compactionId;
159
+ }
160
+ return null;
161
+ }
162
+
163
+ function assertGroupsDoNotStraddleCut(events, cutIndex) {
164
+ const groups = new Map();
165
+ events.forEach((event, index) => {
166
+ const id = compactionGroupId(event);
167
+ if (!id) return;
168
+ if (!groups.has(id)) groups.set(id, []);
169
+ groups.get(id).push(index);
170
+ });
171
+ for (const [id, members] of groups) {
172
+ const before = members.filter((i) => i < cutIndex).length;
173
+ const after = members.filter((i) => i >= cutIndex).length;
174
+ if (before > 0 && after > 0) {
175
+ throw sessionError(ERROR_CODES.NO_BOUNDARY,
176
+ `compaction block ${id} straddles the cut (${before} before, ${after} after); ` +
177
+ 'choose a keepEvents value that keeps the whole compaction block');
178
+ }
179
+ }
180
+ }
181
+
182
+ function isProtectedHead(event) {
183
+ return event.type === 'system/message' && event.surfaceOp === 'append';
184
+ }
185
+
186
+ function needsProtectedHead(retained) {
187
+ return retained.some((e) => e.type === 'system/message' && (e.surfaceOp === 'append' || e.surfaceOp === undefined))
188
+ && !retained.some(isProtectedHead);
189
+ }
190
+
191
+ /**
192
+ * Replay `agent/inbox/spliced` over the empty projection state the host uses on
193
+ * resume. Mirrors dsh-agent-loop: init {next-turn:[], next-step:[]}; a splice
194
+ * must satisfy 0 <= start <= start+removedCount <= queue.length.
195
+ */
196
+ export function checkInboxProjection(events) {
197
+ const state = { 'next-turn': [], 'next-step': [] };
198
+ let splices = 0;
199
+ for (const event of events) {
200
+ if (event.type !== 'agent/inbox/spliced') continue;
201
+ splices += 1;
202
+ const splice = event.data ?? {};
203
+ const queue = state[splice.target];
204
+ const removedCount = splice.removedCount ?? 0;
205
+ const invalid = (why) => sessionError(ERROR_CODES.INBOX_INVALID,
206
+ `invalid persisted inbox splice at session seq ${event.seq}: ${why}`);
207
+ if (!Array.isArray(queue)) throw invalid(`unknown target ${JSON.stringify(splice.target)}`);
208
+ if (!Number.isSafeInteger(splice.start) || splice.start < 0 || splice.start > queue.length) {
209
+ throw invalid(`start ${splice.start} is outside 0..${queue.length}`);
210
+ }
211
+ if (!Number.isSafeInteger(removedCount) || removedCount < 0 || splice.start + removedCount > queue.length) {
212
+ throw invalid(`start ${splice.start} + removedCount ${removedCount} > ${queue.length} projected item(s)`);
213
+ }
214
+ if (!Array.isArray(splice.inserted)) throw invalid('inserted must be an array');
215
+ queue.splice(splice.start, removedCount, ...splice.inserted);
216
+ const ids = new Set();
217
+ const merged = splice.target === 'next-turn'
218
+ ? [...queue, ...state['next-step']]
219
+ : [...state['next-turn'], ...queue];
220
+ for (const message of merged) {
221
+ const id = message && typeof message === 'object' ? message.id : undefined;
222
+ if (id === undefined) continue;
223
+ if (ids.has(id)) throw invalid(`message "${id}" is already pending`);
224
+ ids.add(id);
225
+ }
226
+ }
227
+ return { splices, ok: true };
228
+ }
229
+
230
+ /**
231
+ * One rewrite pass: number the surviving events and remap every reference
232
+ * against that numbering. Events whose references point at something that no
233
+ * longer exists are reported as dropped; the caller removes them and runs
234
+ * another pass, because dropping shifts the numbering the references were
235
+ * computed against.
236
+ */
237
+ function rewritePass(work, { cutIndex, cutTurn, hasHead, dropOldSeqs = new Set(), chainFinalOldSeq = null }) {
238
+ const map = new Map();
239
+ work.forEach((w, i) => { if (!w.inserted) map.set(w.oldSeq, i); });
240
+ const mapOne = (oldSeq) => (oldSeq < 0 ? map.get(oldSeq) : oldSeq < cutIndex ? undefined : map.get(oldSeq));
241
+ const out = [];
242
+ const droppedIndexes = new Set();
243
+
244
+ work.forEach((w, index) => {
245
+ // Prompt-chain events are folded into the carried head; their old targets
246
+ // are gone, so they must not survive as nodes of their own.
247
+ if (!w.inserted && dropOldSeqs.has(w.oldSeq)) {
248
+ droppedIndexes.add(index);
249
+ return;
250
+ }
251
+ const event = structuredClone(w.event);
252
+ if (w.inserted) {
253
+ // Only the carried system head is a Surface node that has to sit inside
254
+ // turn/step 1; the seeded-observability marker keeps its own shape.
255
+ if (event.type === 'system/message') {
256
+ event.data = { ...(event.data ?? {}), turn: 1, step: 1 };
257
+ event.__insertedHead = true;
258
+ }
259
+ }
260
+ // The chain's last rewrite is retargeted onto the carried head: it deletes
261
+ // the head node and takes the head's original position in the Surface, so
262
+ // the visible conversation keeps the order it had before the truncation.
263
+ const isChainFinal = w.oldSeq === chainFinalOldSeq;
264
+ if (isChainFinal) event.__chainFinal = true;
265
+ let lost = false;
266
+
267
+ if (!isChainFinal && event.surfaceOp && typeof event.surfaceOp === 'object') {
268
+ const start = event.surfaceOp.startSeq ?? event.surfaceOp.start;
269
+ const end = event.surfaceOp.endSeq ?? event.surfaceOp.end;
270
+ // A negative range is a carried throwaway node (see buildTruncated): it
271
+ // always survives, so it maps like any other kept reference.
272
+ if (end < cutIndex && end >= 0) {
273
+ // Every node this replacement covered is gone and nothing carried it
274
+ // across, so the replacement cannot stay legal.
275
+ lost = true;
276
+ } else {
277
+ const mappedStart = start < cutIndex && start >= 0 ? 0 : mapOne(start);
278
+ const mappedEnd = mapOne(end);
279
+ if (mappedStart === undefined || mappedEnd === undefined || mappedEnd < mappedStart) lost = true;
280
+ else event.surfaceOp = { op: 'replace', startSeq: mappedStart, endSeq: mappedEnd };
281
+ }
282
+ }
283
+
284
+ if (Array.isArray(event.sourceEventSeqs)) {
285
+ const mapped = [];
286
+ for (const ref of event.sourceEventSeqs) {
287
+ const at = mapOne(ref);
288
+ if (at !== undefined) mapped.push(at);
289
+ }
290
+ const unique = [...new Set(mapped)].sort((a, b) => a - b);
291
+ if (unique.length > 0) event.sourceEventSeqs = unique;
292
+ else delete event.sourceEventSeqs;
293
+ }
294
+
295
+ const data = event.data;
296
+ if (!lost && data && typeof data === 'object') {
297
+ if (typeof data.throughSeq === 'number') {
298
+ const at = mapOne(data.throughSeq);
299
+ if (at === undefined) lost = true;
300
+ else data.throughSeq = Math.min(at, out.length - 1);
301
+ }
302
+ if (Array.isArray(data.shadowedSeqs)) {
303
+ data.shadowedSeqs = [...new Set(data.shadowedSeqs.map((s) => mapOne(s)).filter((v) => v !== undefined))]
304
+ .sort((a, b) => a - b);
305
+ }
306
+ if (data.shadowedRange) {
307
+ const start = data.shadowedRange.start;
308
+ const end = data.shadowedRange.end;
309
+ if (end < cutIndex) {
310
+ delete data.shadowedRange;
311
+ } else {
312
+ const mappedStart = start < cutIndex ? 0 : mapOne(start);
313
+ const mappedEnd = mapOne(end);
314
+ if (mappedStart === undefined || mappedEnd === undefined || mappedEnd < mappedStart) lost = true;
315
+ else data.shadowedRange = { start: mappedStart, end: mappedEnd };
316
+ }
317
+ }
318
+ if (Array.isArray(data.messageSeqs)) {
319
+ data.messageSeqs = [...new Set(data.messageSeqs.map((s) => mapOne(s)).filter((v) => v !== undefined))]
320
+ .sort((a, b) => a - b);
321
+ }
322
+ if (typeof data.headerSeq === 'number') {
323
+ const at = mapOne(data.headerSeq);
324
+ if (at === undefined) delete data.headerSeq;
325
+ else data.headerSeq = at;
326
+ }
327
+ if (typeof data.sourceEventSeq === 'number') {
328
+ const at = mapOne(data.sourceEventSeq);
329
+ if (at === undefined) delete data.sourceEventSeq;
330
+ else data.sourceEventSeq = at;
331
+ }
332
+ if (!w.inserted && typeof data.turn === 'number') data.turn -= cutTurn - 1;
333
+ }
334
+
335
+ if (lost) droppedIndexes.add(index);
336
+ else out.push(event);
337
+ });
338
+
339
+ out.forEach((event, index) => { event.seq = index; });
340
+ const headFinal = out.findIndex((event) => event.__insertedHead === true);
341
+ for (const event of out) delete event.__insertedHead;
342
+ if (headFinal >= 0) {
343
+ for (const event of out) {
344
+ if (event.__chainFinal !== true) continue;
345
+ event.surfaceOp = { op: 'replace', startSeq: headFinal, endSeq: headFinal };
346
+ event.sourceEventSeqs = [headFinal];
347
+ delete event.__chainFinal;
348
+ }
349
+ // The host requires the very first Surface node to be the protected system
350
+ // message. A replacement whose range was clamped to 0 (because it started
351
+ // before the cut) must not swallow that head, so start it after the head.
352
+ for (const event of out) {
353
+ const op = event.surfaceOp;
354
+ if (op && typeof op === 'object' && op.startSeq < headFinal && op.endSeq > headFinal) {
355
+ event.surfaceOp = { op: 'replace', startSeq: headFinal + 1, endSeq: op.endSeq };
356
+ }
357
+ }
358
+ }
359
+
360
+ return { events: out, droppedIndexes };
361
+ }
362
+
363
+ /**
364
+ * A seeded v4 log carries its inherited cut as a marker EVENT rather than a
365
+ * header field: one `session/end-seed` row with `data.inherited === true`, and
366
+ * the decoders derive `inheritedEventCount` from the LAST such row.
367
+ *
368
+ * `@deepseek-ai/dsh-session-format-v1-to-v2` finish(): a seeded header without
369
+ * one throws "released v2 seeded Session lacks an inherited end-seed marker";
370
+ * an unseeded header that still has one throws "released v2 unseeded Session
371
+ * contains an inherited end-seed marker". v3-to-v4 repeats the rule as "format
372
+ * v4 seeded header disagrees with its last inherited end-seed marker", and
373
+ * `dsh-session`'s constructor refuses a second marker after the inherited cut.
374
+ * Truncation must therefore rewrite this metadata together with the events.
375
+ *
376
+ * (Defined here, not imported: truncate-visible.js imports this module.)
377
+ */
378
+ function isInheritedSeedMarker(event) {
379
+ return Boolean(event)
380
+ && event.type === 'session/end-seed'
381
+ && event.data !== null
382
+ && typeof event.data === 'object'
383
+ && event.data.inherited === true;
384
+ }
385
+
386
+ export function buildTruncated(parsed, plan) {
387
+ const { header, events } = parsed;
388
+ const cutIndex = plan.cutIndex;
389
+ const cutTurn = plan.cutTurn;
390
+ assertGroupsDoNotStraddleCut(events, cutIndex);
391
+
392
+ const retainedOriginal = events.slice(cutIndex);
393
+ // The host insists that the first Surface node of a log is a protected
394
+ // system message. If the cut removes the original head, carry a copy of it
395
+ // across, rewritten to the *final* prompt text: the head's replacement chain
396
+ // (2160 -> 10466 -> ...) would otherwise dangle once its target seqs are gone,
397
+ // and a rewrite retargeted onto the head would delete it.
398
+ const originalHead = events.find(isProtectedHead) ?? null;
399
+ let insertedHead = null;
400
+ let chainFinalOldSeq = null;
401
+ const dropOldSeqs = new Set();
402
+ // The head is visible only through its replacement chain: a checkpoint may
403
+ // shadow the head itself, and prompt rewrites replace it in turn. Copy the
404
+ // head across only when the chain's final node is one of the visible surface
405
+ // nodes; otherwise the copy would ADD a message to the conversation.
406
+ const originalSurfaceSeqs = new Set(foldSurface(events).map((node) => node.seq));
407
+ if (originalHead && originalHead.seq < cutIndex) {
408
+ let node = originalHead.seq;
409
+ let finalData = originalHead.data;
410
+ const chain = [];
411
+ for (const event of events) {
412
+ if (event.type !== 'system/message' && event.type !== 'developer/message') continue;
413
+ const op = event.surfaceOp;
414
+ if (!op || typeof op !== 'object') continue;
415
+ const start = op.startSeq ?? op.start;
416
+ const end = op.endSeq ?? op.end;
417
+ if (start <= node && node <= end) {
418
+ node = event.seq;
419
+ finalData = event.data;
420
+ chain.push(event.seq);
421
+ }
422
+ }
423
+ if (originalSurfaceSeqs.has(node)) {
424
+ // The last rewrite stays behind and is retargeted onto the carried head,
425
+ // so the message keeps its original position in the folded Surface.
426
+ for (const seq of chain.slice(0, -1)) dropOldSeqs.add(seq);
427
+ chainFinalOldSeq = chain.length > 0 ? chain[chain.length - 1] : null;
428
+ if (chainFinalOldSeq !== null && chainFinalOldSeq < cutIndex) {
429
+ dropOldSeqs.add(chainFinalOldSeq);
430
+ chainFinalOldSeq = null;
431
+ }
432
+ insertedHead = { ...structuredClone(originalHead), data: structuredClone(finalData ?? {}) };
433
+ }
434
+ }
435
+
436
+ // A compaction group whose whole shadowed range lies before the cut has
437
+ // nothing left to shadow: everything it replaced was cut away. Keeping the
438
+ // group would demand a surface span over nodes that no longer exist, so the
439
+ // group is dropped and its checkpoint becomes a plain user message.
440
+ const compactionIds = new Map();
441
+ for (const event of events) {
442
+ const data = event.data ?? {};
443
+ const id = data.compactionId ?? data.source?.compactionId;
444
+ if (!id) continue;
445
+ if (!compactionIds.has(id)) compactionIds.set(id, []);
446
+ compactionIds.get(id).push(event);
447
+ }
448
+ const mootCompactions = new Set();
449
+ for (const [id, group] of compactionIds) {
450
+ const targets = [];
451
+ for (const event of group) {
452
+ const data = event.data ?? {};
453
+ if (Array.isArray(data.shadowedSeqs)) targets.push(...data.shadowedSeqs);
454
+ const range = data.shadowedRange;
455
+ if (range && typeof range.start === 'number') targets.push(range.start, range.end);
456
+ }
457
+ if (targets.length > 0 && targets.every((seq) => seq < cutIndex)) mootCompactions.add(id);
458
+ }
459
+
460
+ let work = retainedOriginal
461
+ .filter((event) => !isInboxEvent(event))
462
+ // No inherited marker may survive inside the kept window: it would announce
463
+ // a cut at its own position, and the decoders insist the last such marker
464
+ // equals the header's inherited cut. The single marker written below
465
+ // replaces every one that used to live in the dropped prefix.
466
+ .filter((event) => !isInheritedSeedMarker(event))
467
+ .filter((event) => {
468
+ const id = event.data?.compactionId ?? event.data?.source?.compactionId;
469
+ return !(id !== undefined && mootCompactions.has(id) && event.type !== 'user/message');
470
+ })
471
+ .map((event) => ({ event: structuredClone(event), oldSeq: event.seq, inserted: false }));
472
+ for (const wrap of work) {
473
+ const data = wrap.event.data ?? {};
474
+ if (data.source?.kind === 'compact-checkpoint' && mootCompactions.has(data.source.compactionId)) {
475
+ wrap.event.surfaceOp = 'append';
476
+ delete wrap.event.sourceEventSeqs;
477
+ }
478
+ }
479
+ if (insertedHead) {
480
+ const pos = work.findIndex((w) => w.event.type === 'step/start');
481
+ work.splice(pos >= 0 ? pos + 1 : 0, 0, {
482
+ event: structuredClone(insertedHead),
483
+ oldSeq: insertedHead.seq,
484
+ inserted: true,
485
+ });
486
+ }
487
+ work = work.filter((w) => w.inserted || !LOG_ONLY_TYPES.has(w.event.type));
488
+
489
+ // `delivery-accepted` acknowledges a seq that must still exist afterwards.
490
+ const presentOld = new Set(work.filter((w) => !w.inserted).map((w) => w.oldSeq));
491
+ work = work.filter((w) => {
492
+ const through = w.event.data?.throughSeq;
493
+ return !(typeof through === 'number' && (through < cutIndex || !presentOld.has(through)));
494
+ });
495
+
496
+ // A pruned tool result is a `replace` whose target lies before the cut. The
497
+ // target went away with the prefix, so the replacement has nothing left to
498
+ // name; the host rejects it outright. Drop the whole event: what it showed
499
+ // was already filler left by pruning, and the log stays self-consistent.
500
+ // This is exactly the strategy that resumed cleanly on the real session.
501
+ work = work.filter((w) => {
502
+ if (w.inserted) return true;
503
+ const op = w.event.surfaceOp;
504
+ if (!op || typeof op !== 'object') return true;
505
+ const end = op.endSeq ?? op.end;
506
+ if (typeof end !== 'number' || end >= cutIndex) return true;
507
+ return w.event.type === 'system/message' || w.event.type === 'developer/message';
508
+ });
509
+
510
+ // Seeded logs: the inherited prefix is exactly what a prefix cut removes, so
511
+ // the marker that described it has to be rewritten rather than dropped with
512
+ // it. One fresh marker at index 0 declares an explicitly empty inherited
513
+ // prefix - a shape `@deepseek-ai/dsh-subagent` documents as supported and the
514
+ // decoder accepts (`inheritedEventCount === 0`). Clearing `isSeeded` instead
515
+ // would silently re-label a detached child as a fresh session, and leaving
516
+ // `isSeeded` with no marker is the 0.7.4 corruption.
517
+ const seeded = header.isSeeded === true;
518
+ let seedMarker = null;
519
+ if (seeded) {
520
+ seedMarker = { type: 'session/end-seed', inherited: true, index: 0, inheritedEventCount: 0 };
521
+ work.unshift({
522
+ event: { type: 'session/end-seed', time: Date.now(), data: { inherited: true } },
523
+ oldSeq: -1,
524
+ inserted: true,
525
+ });
526
+ }
527
+
528
+ // Rewrite until stable: a pass may drop events whose references are gone,
529
+ // and dropping shifts the numbering, so another pass is needed to check.
530
+ const ctx = { cutIndex, cutTurn, hasHead: Boolean(insertedHead), dropOldSeqs, chainFinalOldSeq };
531
+ let pass = { events: [], droppedIndexes: new Set() };
532
+ for (let round = 0; round < 5; round += 1) {
533
+ pass = rewritePass(work, ctx);
534
+ if (pass.droppedIndexes.size === 0) break;
535
+ work = work.filter((_, index) => !pass.droppedIndexes.has(index));
536
+ }
537
+ const out = pass.events;
538
+ assertContiguous(out);
539
+
540
+ // A resumed session projects its inbox from empty, so the kept window must
541
+ // not open with live inbox traffic (the 2026-10-30 `invalid persisted inbox
542
+ // splice` bug). We drop every agent/inbox/* event, so this is a guarantee.
543
+ const opening = out.slice(0, INBOX_GUARD_WINDOW).filter(isInboxEvent);
544
+ if (opening.length > 0) {
545
+ throw sessionError(ERROR_CODES.INBOX_INVALID,
546
+ `kept window still opens with ${opening.length} agent/inbox event(s); refusing to truncate`);
547
+ }
548
+
549
+ // A checkpoint whose replacement reached into the cut prefix names a range
550
+ // that no longer starts on a surface node. Clamp it to the surviving surface
551
+ // nodes it actually covers; if nothing is left to shadow, it becomes a plain
552
+ // user message (the prefix it used to summarize is gone).
553
+ {
554
+ for (let at = 0; at < out.length; at += 1) {
555
+ const event = out[at];
556
+ if (event.type !== 'user/message') continue;
557
+ if (event.data?.source?.kind !== 'compact-checkpoint') continue;
558
+ const op = event.surfaceOp;
559
+ if (!op || typeof op !== 'object') continue;
560
+ const nodes = foldSurface(out.slice(0, at)).map((node) => node.seq);
561
+ const startOk = nodes.includes(op.startSeq);
562
+ const endOk = nodes.includes(op.endSeq);
563
+ if (startOk && endOk) continue;
564
+ const inside = nodes.filter((seq) => seq >= (startOk ? op.startSeq : 0) && seq <= op.endSeq);
565
+ if (inside.length === 0) {
566
+ event.surfaceOp = 'append';
567
+ delete event.sourceEventSeqs;
568
+ continue;
569
+ }
570
+ event.surfaceOp = { op: 'replace', startSeq: inside[0], endSeq: inside[inside.length - 1] };
571
+ event.sourceEventSeqs = [...inside];
572
+ }
573
+ }
574
+
575
+ // Compaction spans must name an exact contiguous slice of the folded
576
+ // Surface. Dropping nodes inside a span leaves the mapped seq list short, and
577
+ // a checkpoint that was retargeted onto the kept window shadows a different
578
+ // span than the original summary did. Both are rebuilt here: a summary takes
579
+ // the exact span its checkpoint replaces, and any span left over is trimmed
580
+ // to the surviving nodes it still names.
581
+ {
582
+ for (let at = 0; at < out.length; at += 1) {
583
+ const checkpoint = out[at];
584
+ if (checkpoint.type !== 'user/message') continue;
585
+ const compactionId = checkpoint.data?.source?.compactionId;
586
+ if (compactionId === undefined) continue;
587
+ const op = checkpoint.surfaceOp;
588
+ if (!op || typeof op !== 'object') continue;
589
+ const nodes = foldSurface(out.slice(0, at)).map((node) => node.seq);
590
+ const startIndex = nodes.indexOf(op.startSeq);
591
+ const endIndex = nodes.indexOf(op.endSeq);
592
+ if (startIndex < 0 || endIndex < startIndex) continue;
593
+ const slice = nodes.slice(startIndex, endIndex + 1);
594
+ for (let back = 0; back < at; back += 1) {
595
+ const summary = out[back];
596
+ if (summary.type !== 'compaction/summary' && summary.type !== 'compaction/prune') continue;
597
+ if (summary.data?.compactionId !== compactionId) continue;
598
+ summary.data.shadowedSeqs = slice;
599
+ summary.data.shadowedRange = { start: slice[0], end: slice[slice.length - 1] };
600
+ }
601
+ }
602
+ const nodes = foldSurface(out).map((node) => node.seq);
603
+ const nodeSet = new Set(nodes);
604
+ const indexOf = new Map(nodes.map((seq, at) => [seq, at]));
605
+ for (const event of out) {
606
+ if (event.type !== 'compaction/summary' && event.type !== 'compaction/prune') continue;
607
+ const data = event.data ?? {};
608
+ const seqs = Array.isArray(data.shadowedSeqs) ? data.shadowedSeqs.filter((seq) => nodeSet.has(seq)) : [];
609
+ if (seqs.length === 0) continue;
610
+ const lo = Math.min(...seqs);
611
+ const hi = Math.max(...seqs);
612
+ const slice = nodes.slice(indexOf.get(lo), indexOf.get(hi) + 1);
613
+ if (slice.length !== seqs.length) continue;
614
+ data.shadowedSeqs = [...slice];
615
+ data.shadowedRange = { start: lo, end: hi };
616
+ }
617
+ }
618
+
619
+ const headerOut = structuredClone(header);
620
+ // The physical header line accepts a fixed key set (isHeaderLine in
621
+ // dsh-session-persistence-jsonl) and has no inheritedEventCount field, so the
622
+ // old `headerOut.inheritedEventCount = 0` never reached disk. The cut now
623
+ // travels on `seedMarker`; keep `isSeeded` as it was and drop any in-memory
624
+ // stray so an unknown key can never be encoded.
625
+ delete headerOut.inheritedEventCount;
626
+
627
+ return { header: headerOut, events: out, insertedHead: Boolean(insertedHead), seedMarker };
628
+ }
629
+
630
+ /** Compare the visible conversation before and after the candidate rewrite. */
631
+ export function assertSameConversation(parsed, candidate) {
632
+ const before = deriveMessagesDigest(parsed.header, parsed.events);
633
+ const after = deriveMessagesDigest(candidate.header, candidate.events);
634
+ if (before.sha256 !== after.sha256) {
635
+ throw sessionError(ERROR_CODES.CONVERSATION_CHANGED,
636
+ 'refusing to truncate: the kept window would change the visible conversation ' +
637
+ `(${before.count} messages / ${before.sha256.slice(0, 12)} -> ${after.count} messages / ${after.sha256.slice(0, 12)}). ` +
638
+ 'Raise keepEvents so every still-visible message is kept.');
639
+ }
640
+ return { before, after };
641
+ }
642
+
643
+ function ensureTitle(events, originalEvents, cutIndex, map) {
644
+ if (events.some((e) => e.type === 'session/title')) return false;
645
+ let title = null;
646
+ for (let i = originalEvents.length - 1; i >= 0; i -= 1) {
647
+ if (originalEvents[i].type === 'session/title') { title = originalEvents[i]; break; }
648
+ }
649
+ if (!title) return false;
650
+ const copy = structuredClone(title);
651
+ copy.seq = events.length;
652
+ if (Array.isArray(copy.data?.messageSeqs)) {
653
+ copy.data.messageSeqs = copy.data.messageSeqs
654
+ .filter((s) => s >= cutIndex && map.has(s))
655
+ .map((s) => map.get(s));
656
+ }
657
+ events.push(copy);
658
+ return true;
659
+ }
660
+
661
+ export function formatBytes(n) {
662
+ if (n < 1024) return `${n} B`;
663
+ if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KiB`;
664
+ return `${(n / (1024 * 1024)).toFixed(2)} MiB`;
665
+ }
666
+
667
+ /**
668
+ * Windows-only exclusive-handle probe.
669
+ *
670
+ * `fs.openSync(path, 'r+')` succeeds while another process also has the file
671
+ * open with share flags (a running DSH keeps its session log open), so it can
672
+ * never tell "idle file" from "live owner". Opening with FileShare.None fails
673
+ * when ANY other handle exists, which is the signal this guard needs. The probe
674
+ * runs in a child process so the handle is released before we rename.
675
+ *
676
+ * Returns { ok, skipped?, detail? }: `skipped` means the probe itself is
677
+ * unavailable (non-Windows, no PowerShell) and the caller falls back.
678
+ */
679
+ function exclusiveWriteProbe(sessionPath) {
680
+ if (process.platform !== 'win32') {
681
+ return {
682
+ ok: true,
683
+ skipped: `non-windows: the exclusive-handle probe needs Windows PowerShell (FileShare.None); ` +
684
+ `on ${process.platform} only the freshness window and fs.openSync('r+') guard this write`,
685
+ };
686
+ }
687
+ const script = [
688
+ "$ErrorActionPreference='Stop'",
689
+ '$handle=[System.IO.File]::Open($env:DSH_LIVE_PROBE_PATH,[System.IO.FileMode]::Open,[System.IO.FileAccess]::ReadWrite,[System.IO.FileShare]::None)',
690
+ '$handle.Dispose()',
691
+ "Write-Output 'DSH_PROBE_FREE'",
692
+ ].join('; ');
693
+ let result;
694
+ try {
695
+ result = spawnSync('powershell.exe', ['-NoLogo', '-NoProfile', '-NonInteractive', '-Command', script], {
696
+ encoding: 'utf8',
697
+ timeout: 15_000,
698
+ windowsHide: true,
699
+ env: { ...process.env, DSH_LIVE_PROBE_PATH: sessionPath },
700
+ });
701
+ } catch (error) {
702
+ return { ok: true, skipped: `probe-unavailable:${error.code ?? error.message}` };
703
+ }
704
+ if (result.error) return { ok: true, skipped: `probe-unavailable:${result.error.code ?? result.error.message}` };
705
+ if (result.status === 0) return { ok: true };
706
+ const raw = `${result.stderr ?? ''}\n${result.stdout ?? ''}`
707
+ .split(/\r?\n/)
708
+ .map((line) => line.trim())
709
+ .filter((line) => line && !line.startsWith('<Objs') && !line.startsWith('</Objs'))
710
+ .slice(-3)
711
+ .join(' ')
712
+ .slice(0, 300);
713
+ return { ok: false, detail: raw || (result.status === null ? 'probe-timeout' : `exit ${result.status}`) };
714
+ }
715
+
716
+ /**
717
+ * Refuse while the session looks live: held open, or modified recently.
718
+ *
719
+ * `onProbe` receives the raw probe result so a caller that reports on its
720
+ * checks (live-target.js) can say "unverified on this platform" instead of
721
+ * mistaking a skipped probe for proof that the handle is free.
722
+ */
723
+ export function assertNotLive(sessionPath, {
724
+ recentWriteWindowMs = RECENT_WRITE_WINDOW_MS,
725
+ now = Date.now(),
726
+ onProbe = null,
727
+ } = {}) {
728
+ // Handle-level check first: this is the one that catches a running app even
729
+ // when its last write is older than the freshness window (the 0.7.1 hole:
730
+ // idle for 60 s -> the mtime guard waved the write through and tore the log).
731
+ const probe = exclusiveWriteProbe(sessionPath);
732
+ if (typeof onProbe === 'function') {
733
+ try { onProbe(probe); } catch { /* a reporting hook must not change the verdict */ }
734
+ }
735
+ if (!probe.ok) {
736
+ throw sessionError(ERROR_CODES.FILE_BUSY,
737
+ `cannot take an exclusive write handle on the session log (${probe.detail}); ` +
738
+ 'another process — most likely the app running this session — still holds it. ' +
739
+ 'Close that app and retry; the plugin never kills a process.');
740
+ }
741
+ const stat = fs.statSync(sessionPath);
742
+ const ageMs = now - stat.mtimeMs;
743
+ // <= 0 disables the freshness guard (tests and deliberate maintenance runs).
744
+ if (recentWriteWindowMs > 0 && ageMs < recentWriteWindowMs) {
745
+ throw sessionError(ERROR_CODES.RECENT_WRITE,
746
+ `session log changed ${Math.round(ageMs / 1000)} s ago (<= ${Math.round(recentWriteWindowMs / 1000)} s); ` +
747
+ 'a running session may be writing. Stop that session first; the plugin never truncates a live log.');
748
+ }
749
+ try {
750
+ const fd = fs.openSync(sessionPath, 'r+');
751
+ fs.closeSync(fd);
752
+ } catch (error) {
753
+ throw sessionError(ERROR_CODES.LOCKED,
754
+ `cannot open the session log for writing (${error.code ?? error.message}); ` +
755
+ 'another process may hold it. Close it and retry; the plugin never kills a process.', error);
756
+ }
757
+ }
758
+
759
+ /**
760
+ * Read the log once and record the identity of exactly those bytes.
761
+ *
762
+ * The size and mtime are cheap tripwires, the sha256 is what decides: a writer
763
+ * can append and keep the size identical (a replacement, not an append), so a
764
+ * length-only check would overwrite new history without noticing.
765
+ */
766
+ function readSnapshot(abs) {
767
+ const buf = fs.readFileSync(abs);
768
+ const stat = fs.statSync(abs);
769
+ return {
770
+ buf,
771
+ size: buf.length,
772
+ statSize: stat.size,
773
+ mtimeMs: stat.mtimeMs,
774
+ sha256: sha256(buf),
775
+ };
776
+ }
777
+
778
+ /** Refuse to overwrite a log whose bytes are no longer the snapshot's bytes. */
779
+ function assertUnchanged(abs, snapshot) {
780
+ let now;
781
+ try {
782
+ const buf = fs.readFileSync(abs);
783
+ const stat = fs.statSync(abs);
784
+ now = { size: buf.length, statSize: stat.size, mtimeMs: stat.mtimeMs, sha256: sha256(buf) };
785
+ } catch (error) {
786
+ throw sessionError(ERROR_CODES.CHANGED,
787
+ `session log became unreadable while truncating (${error.code ?? error.message}); nothing was written`, error);
788
+ }
789
+ const changed = now.sha256 !== snapshot.sha256
790
+ || now.size !== snapshot.size
791
+ || now.mtimeMs !== snapshot.mtimeMs;
792
+ if (changed) {
793
+ throw sessionError(ERROR_CODES.CHANGED,
794
+ 'session log changed while truncating: ' +
795
+ `${snapshot.size} B/${snapshot.sha256.slice(0, 12)} -> ${now.size} B/${now.sha256.slice(0, 12)}. ` +
796
+ 'Another writer appended or the file was replaced; refusing to rename over it so that write is not lost. ' +
797
+ 'Nothing was written — stop the writer and retry.');
798
+ }
799
+ }
800
+
801
+ /**
802
+ * Full truncation flow. `dryRun: true` (default) performs every read and
803
+ * computation but writes nothing — no tmp, no backup, no ledger.
804
+ */
805
+ export function truncateSession(sessionPath, options = {}) {
806
+ const {
807
+ keepEvents = DEFAULT_KEEP_EVENTS,
808
+ dryRun = true,
809
+ confirm,
810
+ now = new Date(),
811
+ recentWriteWindowMs = RECENT_WRITE_WINDOW_MS,
812
+ eventsPerFrame = EVENTS_PER_FRAME,
813
+ } = options;
814
+
815
+ if (!sessionPath || typeof sessionPath !== 'string') {
816
+ throw sessionError(ERROR_CODES.BAD_ARGUMENT, 'sessionPath is required');
817
+ }
818
+ const abs = path.resolve(sessionPath);
819
+ if (!fs.existsSync(abs)) {
820
+ throw sessionError(ERROR_CODES.NOT_FOUND,
821
+ `session log not found: ${abs} — run session_health to list available sessions, ` +
822
+ 'or pass sessionId / session:"latest" instead of guessing a path. Nothing was written.');
823
+ }
824
+ // A backup is the rollback source, never a truncation target (N4). The tool
825
+ // layer refuses this before calling in; the check lives here too so a direct
826
+ // library call cannot eat the only way back.
827
+ const baseName = path.basename(abs);
828
+ if (baseName.startsWith(`${SESSION_FILENAME}.bak-`)) {
829
+ throw sessionError(ERROR_CODES.IS_BACKUP,
830
+ `refusing to truncate a backup: ${baseName} is a ${SESSION_FILENAME} backup. ` +
831
+ `Point at ${SESSION_FILENAME}; the backup is the rollback source.`);
832
+ }
833
+ assertNotLive(abs, { recentWriteWindowMs });
834
+
835
+ // One read, one snapshot: everything below is computed from these bytes, and
836
+ // the same bytes are what the backup is written from (N1).
837
+ const snapshot = readSnapshot(abs);
838
+ const originalBuf = snapshot.buf;
839
+ let parsed;
840
+ try {
841
+ parsed = parseSession(originalBuf);
842
+ } catch (error) {
843
+ throw sessionError(ERROR_CODES.CORRUPT,
844
+ `${error.message} — the log was left untouched. Check session_health first; ` +
845
+ 'if the file is still being written, stop that session and retry.', error);
846
+ }
847
+ checkInboxProjection(parsed.events);
848
+
849
+ const plan = planTruncation(parsed, { keepEvents });
850
+ if (!plan.needed) {
851
+ return {
852
+ dryRun, needed: false, sessionPath: abs,
853
+ beforeBytes: originalBuf.length, beforeEvents: parsed.events.length, keepEvents,
854
+ message: `nothing to do: ${parsed.events.length} events <= keepEvents ${keepEvents}`,
855
+ };
856
+ }
857
+
858
+ const candidate = buildTruncated(parsed, plan);
859
+ const conversation = assertSameConversation(parsed, candidate);
860
+ const map = new Map(parsed.events.slice(plan.cutIndex).map((e, i) => [e.seq, i]));
861
+ const createdTitle = ensureTitle(candidate.events, parsed.events, plan.cutIndex, map);
862
+ if (createdTitle) candidate.events.forEach((event, index) => { event.seq = index; });
863
+ assertContiguous(candidate.events);
864
+ const inbox = checkInboxProjection(candidate.events);
865
+
866
+ const buffer = encodeSession(candidate.header, candidate.events, { eventsPerFrame });
867
+
868
+ // The visibility guard can move the cut to the first turn boundary, where
869
+ // the protected head is dropped and re-inserted: the rebuilt log then has
870
+ // the same number of events as the original. Report that honestly as a
871
+ // no-op — a dry run must never promise a cut the real run cannot shrink.
872
+ if (candidate.events.length >= parsed.events.length) {
873
+ return {
874
+ dryRun, needed: false, sessionPath: abs, keepEvents,
875
+ cutSeq: plan.cutSeq, cutTurn: plan.cutTurn,
876
+ beforeBytes: originalBuf.length, afterBytes: buffer.length,
877
+ beforeEvents: parsed.events.length, afterEvents: candidate.events.length,
878
+ message: 'nothing to do: the safe cut at seq ' + plan.cutSeq +
879
+ ' keeps every visible message and would not shrink the log (' +
880
+ parsed.events.length + ' events -> ' + candidate.events.length + ' events)',
881
+ };
882
+ }
883
+
884
+ const summary = {
885
+ dryRun,
886
+ needed: true,
887
+ sessionPath: abs,
888
+ cutSeq: plan.cutSeq,
889
+ cutTurn: plan.cutTurn,
890
+ advancedForInbox: plan.inboxInWindow ? 'dropped agent/inbox traffic in the kept window' : '',
891
+ beforeBytes: originalBuf.length,
892
+ afterBytes: buffer.length,
893
+ beforeEvents: parsed.events.length,
894
+ afterEvents: candidate.events.length,
895
+ droppedEvents: parsed.events.length - candidate.events.length,
896
+ insertedProtectedHead: candidate.insertedHead,
897
+ createdTitle,
898
+ inboxSplicesAfter: inbox.splices,
899
+ beforeFirstSeq: parsed.events[0]?.seq ?? null,
900
+ afterFirstSeq: candidate.events[0]?.seq ?? null,
901
+ beforeLastType: parsed.events.at(-1)?.type ?? null,
902
+ afterLastType: candidate.events.at(-1)?.type ?? null,
903
+ deriveBefore: conversation.before,
904
+ deriveAfter: conversation.after,
905
+ message: `${formatBytes(originalBuf.length)} / ${parsed.events.length} events -> ` +
906
+ `${formatBytes(buffer.length)} / ${candidate.events.length} events`,
907
+ };
908
+
909
+ if (dryRun) return summary;
910
+ if (confirm !== CONFIRM_WORD) {
911
+ throw sessionError(ERROR_CODES.CONFIRM_REQUIRED,
912
+ `refusing to write: pass confirm:"${CONFIRM_WORD}" to actually truncate`);
913
+ }
914
+
915
+ // The backup is written from the snapshot buffer, not from a second read of
916
+ // the log: a writer that appends in the meantime must not end up inside a
917
+ // backup that claims to represent the bytes this plan was built from.
918
+ let backup;
919
+ try {
920
+ backup = ensureBackup(abs, {
921
+ date: now,
922
+ sourceBuf: originalBuf,
923
+ sha256: snapshot.sha256,
924
+ size: snapshot.size,
925
+ });
926
+ } catch (error) {
927
+ const code = error.code === 'ENOENT' ? ERROR_CODES.BACKUP_MISSING : ERROR_CODES.BACKUP_MISMATCH;
928
+ throw sessionError(code, `backup failed: ${error.message}`, error);
929
+ }
930
+ const verified = verifyBackup(backup.file, backup.sha256);
931
+ if (!verified.ok) {
932
+ const code = String(verified.reason).includes('does not exist')
933
+ ? ERROR_CODES.BACKUP_MISSING : ERROR_CODES.BACKUP_MISMATCH;
934
+ throw sessionError(code, `backup missing or invalid: ${verified.reason}`);
935
+ }
936
+
937
+ const tmp = `${abs}.tmp-${process.pid}-${Date.now()}`;
938
+ try {
939
+ fs.writeFileSync(tmp, buffer);
940
+ const tmpParsed = parseSession(fs.readFileSync(tmp));
941
+ if (tmpParsed.events.length !== candidate.events.length) {
942
+ throw sessionError(ERROR_CODES.TMP_VERIFY,
943
+ `tmp verification failed: ${tmpParsed.events.length} events != ${candidate.events.length}`);
944
+ }
945
+ const tmpDigest = deriveMessagesDigest(tmpParsed.header, tmpParsed.events).sha256;
946
+ if (tmpDigest !== conversation.before.sha256) {
947
+ throw sessionError(ERROR_CODES.TMP_VERIFY, 'tmp verification failed: visible conversation changed');
948
+ }
949
+ // Last gate before the rename: if anything changed since the snapshot, the
950
+ // append we did not plan for would be destroyed by the rename. Refuse.
951
+ assertUnchanged(abs, snapshot);
952
+ fs.renameSync(tmp, abs);
953
+ } catch (error) {
954
+ try { if (fs.existsSync(tmp)) fs.unlinkSync(tmp); } catch { /* best effort */ }
955
+ throw error;
956
+ }
957
+
958
+ // After the rename the original only exists in the verified backup.
959
+ try {
960
+ const finalParsed = parseSession(fs.readFileSync(abs));
961
+ if (finalParsed.events.length !== candidate.events.length) {
962
+ throw sessionError(ERROR_CODES.POST_VERIFY,
963
+ `post-write verification failed: ${finalParsed.events.length} events != ${candidate.events.length}`);
964
+ }
965
+ const finalDigest = deriveMessagesDigest(finalParsed.header, finalParsed.events).sha256;
966
+ if (finalDigest !== conversation.before.sha256) {
967
+ throw sessionError(ERROR_CODES.POST_VERIFY, 'post-write verification failed: visible conversation changed');
968
+ }
969
+ } catch (error) {
970
+ fs.copyFileSync(backup.file, abs);
971
+ writeJsonFile(path.join(path.dirname(abs), 'rollback.json'), {
972
+ at: new Date().toISOString(),
973
+ sessionPath: abs,
974
+ reason: error.message,
975
+ code: error.code ?? null,
976
+ restoredFrom: backup.file,
977
+ restoredSha256: backup.sha256,
978
+ });
979
+ throw sessionError(ERROR_CODES.POST_VERIFY, `${error.message}; original restored from ${backup.file}`, error);
980
+ }
981
+
982
+ const ledgerFile = truncationLedgerPath(abs);
983
+ const ledger = readJsonFile(ledgerFile, { truncations: [] });
984
+ ledger.truncations.push({
985
+ at: new Date().toISOString(),
986
+ beforeBytes: summary.beforeBytes,
987
+ afterBytes: summary.afterBytes,
988
+ beforeEvents: summary.beforeEvents,
989
+ afterEvents: summary.afterEvents,
990
+ cutSeq: summary.cutSeq,
991
+ cutTurn: summary.cutTurn,
992
+ backup: backup.file,
993
+ backupSha256: backup.sha256,
994
+ });
995
+ if (ledger.truncations.length > 20) ledger.truncations = ledger.truncations.slice(-20);
996
+ writeJsonFile(ledgerFile, ledger);
997
+
998
+ return { ...summary, dryRun: false, backupFile: backup.file, backupSha256: backup.sha256 };
999
+ }