@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,752 @@
1
+ #requires -Version 5.1
2
+ <#
3
+ auto-truncate-run.ps1 - out-of-app visible truncation orchestrator.
4
+
5
+ The in-app plugin only writes a request; this script performs the cut while
6
+ the app is closed, verifies the rewritten log by loading it through the
7
+ app's own Electron runtime, and restarts the app.
8
+
9
+ The request's sessionPath must live under the sessions root (by default
10
+ %USERPROFILE%\.dsh\sessions, or <DSH_HOME>\sessions when DSH_HOME is set).
11
+ The path is resolved to its full form and compared case-insensitively, so a
12
+ relative path, a ..-escape, or an arbitrary file is refused before anything
13
+ is closed.
14
+
15
+ Exit codes:
16
+ 0 success (or -DryRun validation only)
17
+ 2 bad-request (including SESSION_PATH_OUTSIDE_ROOT)
18
+ 3 close-failed (CLOSE_FAILED; structured result written)
19
+ 4 cut-failed (backup restored when available)
20
+ 5 verify-failed (backup restored)
21
+ 6 restart-failed (cut kept, request kept)
22
+
23
+ Closing the app is a hard kill, because a graceful-only close proved to shut
24
+ down 3 of 5 processes and to make the run wait a full minute for nothing:
25
+ Close-App sends one polite CloseMainWindow to the processes that own a main
26
+ window, waits at most 3 seconds, then force-kills every survivor by PID with
27
+ Stop-Process -Force (never a /IM image-name sweep, which matches by image name
28
+ and both misses and overreaches), settles 2 seconds and requires zero
29
+ processes. Anything still alive after that is CLOSE_FAILED / exit 3 and no
30
+ session byte changes.
31
+
32
+ -SimulateCloseFailure exists only so the test suite can exercise the
33
+ close-failed path without touching a real process. It makes Close-App report
34
+ failure before it looks at any process.
35
+
36
+ The script body is ASCII. Paths and log lines may contain any Unicode text.
37
+ #>
38
+ param(
39
+ [Parameter(Mandatory = $true)][string]$MemoryRoot,
40
+ [string]$RequestFile = '',
41
+ [string]$AppExe = '',
42
+ [string]$Profile = 'desktop',
43
+ [string]$LogDir = '',
44
+ [string]$SessionsRoot = '',
45
+ [long]$LogMaxBytes = 8388608,
46
+ [int]$LogMaxFiles = 5,
47
+ [switch]$DryRun,
48
+ [switch]$SimulateCloseFailure
49
+ )
50
+
51
+ $ErrorActionPreference = 'Stop'
52
+ $script:ExeName = ''
53
+ $script:LogMaxBytes = [Math]::Max([long]65536, [long]$LogMaxBytes)
54
+ $script:LogMaxFiles = [Math]::Max(1, [int]$LogMaxFiles)
55
+
56
+ # rc.6 (R4-03): capture every native node process as UTF-8, independent of the
57
+ # console code page. On a Chinese Windows the host console is GBK; letting the
58
+ # runtime decode node's UTF-8 stdout through that page produced mojibake and
59
+ # made the JSON line unparseable. This file is UTF-8 without BOM and must never
60
+ # contain non-ASCII string literals (PS 5.1 reads it as ANSI).
61
+ $script:Utf8NoBom = [System.Text.UTF8Encoding]::new($false)
62
+ try { [Console]::OutputEncoding = $script:Utf8NoBom } catch { }
63
+ try { [Console]::InputEncoding = $script:Utf8NoBom } catch { }
64
+ try { $OutputEncoding = $script:Utf8NoBom } catch { }
65
+
66
+ function Quote-NativeArg([string]$Value) {
67
+ if ($null -eq $Value) { return '""' }
68
+ if ($Value -notmatch '[\s"]') { return $Value }
69
+ $sb = [System.Text.StringBuilder]::new()
70
+ [void]$sb.Append('"')
71
+ $backslashes = 0
72
+ foreach ($ch in $Value.ToCharArray()) {
73
+ if ($ch -eq '\') { $backslashes++; continue }
74
+ if ($ch -eq '"') {
75
+ [void]$sb.Append('\' * (($backslashes * 2) + 1))
76
+ [void]$sb.Append('"')
77
+ $backslashes = 0
78
+ continue
79
+ }
80
+ if ($backslashes -gt 0) { [void]$sb.Append('\' * $backslashes); $backslashes = 0 }
81
+ [void]$sb.Append($ch)
82
+ }
83
+ if ($backslashes -gt 0) { [void]$sb.Append('\' * ($backslashes * 2)) }
84
+ [void]$sb.Append('"')
85
+ return $sb.ToString()
86
+ }
87
+
88
+ function Rotate-JsonlLogIfNeeded([string]$Path) {
89
+ # 1.8.1-rc.7: the runner appends RESULT lines to auto-truncate.log directly,
90
+ # so the in-plugin rotation alone would leave this writer unbounded. Keep the
91
+ # same simple policy as src/log-rotation.js: size, local day, max files.
92
+ if (-not (Test-Path -LiteralPath $Path)) { return }
93
+ try {
94
+ $item = Get-Item -LiteralPath $Path
95
+ $today = (Get-Date).Date
96
+ $tooBig = $item.Length -ge $script:LogMaxBytes
97
+ $oldDay = $item.Length -gt 0 -and $item.LastWriteTime.Date -lt $today
98
+ if (-not $tooBig -and -not $oldDay) { return }
99
+ $dir = Split-Path -Parent $Path
100
+ $name = [System.IO.Path]::GetFileNameWithoutExtension($Path)
101
+ $ext = [System.IO.Path]::GetExtension($Path)
102
+ $stamp = (Get-Date).ToString('yyyyMMdd-HHmmss')
103
+ $target = Join-Path $dir "$name.$stamp$ext"
104
+ $n = 1
105
+ while (Test-Path -LiteralPath $target) {
106
+ $target = Join-Path $dir "$name.$stamp-$n$ext"
107
+ $n += 1
108
+ }
109
+ Move-Item -LiteralPath $Path -Destination $target
110
+ $rotated = @(Get-ChildItem -LiteralPath $dir -File -ErrorAction SilentlyContinue |
111
+ Where-Object { $_.Name -like "$name.*$ext" -and $_.FullName -ne $target } |
112
+ Sort-Object LastWriteTime -Descending)
113
+ for ($i = 0; $i -lt $rotated.Count; $i += 1) {
114
+ if ($i -ge ($script:LogMaxFiles - 1)) {
115
+ Remove-Item -LiteralPath $rotated[$i].FullName -Force -ErrorAction SilentlyContinue
116
+ }
117
+ }
118
+ } catch {
119
+ # Diagnostics must never fail the runner.
120
+ }
121
+ }
122
+
123
+ function Write-Run([string]$Message) {
124
+ $ts = (Get-Date).ToString('yyyy-MM-ddTHH:mm:ss.fffzzz')
125
+ $line = "[$ts] $Message"
126
+ Rotate-JsonlLogIfNeeded $script:RunLog
127
+ Add-Content -LiteralPath $script:RunLog -Value $line -Encoding UTF8
128
+ Write-Host $line
129
+ }
130
+
131
+ function Write-Result($Value) {
132
+ $json = $Value | ConvertTo-Json -Compress -Depth 10
133
+ Rotate-JsonlLogIfNeeded $script:ResultLog
134
+ Add-Content -LiteralPath $script:ResultLog -Value $json -Encoding UTF8
135
+ Write-Run "RESULT $json"
136
+ }
137
+
138
+ function Invoke-Native([string]$FilePath, [string[]]$Arguments) {
139
+ # stdout/stderr are read through explicit UTF-8 decoders. Do not go back to
140
+ # `& $exe @args 2>&1 | Out-String`: that path decodes via the console code
141
+ # page and corrupts non-ASCII JSON (R4-03).
142
+ $argLine = (@($Arguments) | ForEach-Object { Quote-NativeArg ([string]$_) }) -join ' '
143
+ $psi = [System.Diagnostics.ProcessStartInfo]::new()
144
+ $psi.FileName = $FilePath
145
+ $psi.Arguments = $argLine
146
+ $psi.UseShellExecute = $false
147
+ $psi.CreateNoWindow = $true
148
+ $psi.RedirectStandardOutput = $true
149
+ $psi.RedirectStandardError = $true
150
+ $psi.StandardOutputEncoding = $script:Utf8NoBom
151
+ $psi.StandardErrorEncoding = $script:Utf8NoBom
152
+ $proc = [System.Diagnostics.Process]::new()
153
+ $proc.StartInfo = $psi
154
+ [void]$proc.Start()
155
+ $outTask = $proc.StandardOutput.ReadToEndAsync()
156
+ $errTask = $proc.StandardError.ReadToEndAsync()
157
+ if (-not $proc.WaitForExit(900000)) {
158
+ try { $proc.Kill() } catch { }
159
+ throw "native process timed out after 900s: $FilePath"
160
+ }
161
+ $stdout = $outTask.Result
162
+ $stderr = $errTask.Result
163
+ $code = $proc.ExitCode
164
+ $proc.Dispose()
165
+ $text = (@($stdout, $stderr) | Where-Object { $_ }) -join "`n"
166
+ return [pscustomobject]@{ Output = $text.Trim(); Stdout = $stdout; Stderr = $stderr; ExitCode = $code }
167
+ }
168
+
169
+ function Get-AppProcs {
170
+ $names = @($script:ExeName, 'DEEPSE~1', "$($script:ExeName) Helper")
171
+ return @(Get-Process -ErrorAction SilentlyContinue | Where-Object {
172
+ $p = $_.ProcessName
173
+ $names -contains $p -or $p -like "$($script:ExeName)*"
174
+ })
175
+ }
176
+
177
+ function Resolve-NodeExe([string]$Exe) {
178
+ $dir = Split-Path -Parent $Exe
179
+ $candidates = @()
180
+ if ($env:DSH_NODE) { $candidates += $env:DSH_NODE }
181
+ $candidates += @(
182
+ (Join-Path $dir 'resources\runtime\primary-runtime\dependencies\node\bin\node.exe'),
183
+ (Join-Path $dir 'resources\runtime\node\bin\node.exe'),
184
+ (Join-Path $dir 'resources\node\node.exe')
185
+ )
186
+ foreach ($candidate in $candidates) {
187
+ if ($candidate -and (Test-Path -LiteralPath $candidate -PathType Leaf)) { return $candidate }
188
+ }
189
+ $command = Get-Command node.exe -ErrorAction SilentlyContinue
190
+ if ($command) { return $command.Source }
191
+ return ''
192
+ }
193
+
194
+ function Restore-Backup([string]$BackupPath, [string]$TargetPath, [string]$ExpectedSha) {
195
+ if (-not $BackupPath -or -not (Test-Path -LiteralPath $BackupPath -PathType Leaf)) {
196
+ Write-Run "restore: no usable backup path ($BackupPath)"
197
+ return $false
198
+ }
199
+ Copy-Item -LiteralPath $BackupPath -Destination $TargetPath -Force
200
+ $got = (Get-FileHash -LiteralPath $TargetPath -Algorithm SHA256).Hash.ToLowerInvariant()
201
+ $want = ''
202
+ if ($ExpectedSha) { $want = $ExpectedSha.ToLowerInvariant() }
203
+ $ok = ($want -eq '') -or ($got -eq $want)
204
+ Write-Run "restore: $BackupPath -> $TargetPath sha256=$got expected=$want ok=$ok"
205
+ return $ok
206
+ }
207
+
208
+ # rc.6 (R4-03): when truncate-cli exits 0 but its stdout cannot be parsed, the
209
+ # cut may still have landed (GBK decoding ate the JSON, not the write). Read the
210
+ # session back with surgery-inspect and compare its event count with the plan
211
+ # snapshot: a drop is proof the cut landed; no drop means we cannot tell and the
212
+ # old restore-and-fail path stays in charge.
213
+ function Test-CutApplied([string]$NodeExe, [string]$Path, $Request) {
214
+ $inspectScript = Join-Path $PSScriptRoot 'surgery-inspect.mjs'
215
+ if (-not (Test-Path -LiteralPath $inspectScript -PathType Leaf)) {
216
+ return [pscustomobject]@{ ok = $false; reason = 'inspect-missing'; after = $null; backupPath = $null }
217
+ }
218
+ $run = Invoke-Native $NodeExe @($inspectScript, $Path)
219
+ $json = $null
220
+ foreach ($line in ($run.Output -split "`r?`n")) {
221
+ $trimmed = $line.Trim()
222
+ if (-not $trimmed.StartsWith('{')) { continue }
223
+ try { $json = $trimmed | ConvertFrom-Json } catch { $json = $null }
224
+ }
225
+ if ($null -eq $json -or -not $json.ok) {
226
+ return [pscustomobject]@{ ok = $false; reason = 'inspect-unreadable'; after = $null; backupPath = $null }
227
+ }
228
+ $planned = $null
229
+ if ($null -ne $Request.plan -and $null -ne $Request.plan.PSObject.Properties['snapshotEvents']) {
230
+ $planned = [int]$Request.plan.snapshotEvents
231
+ }
232
+ if ($null -eq $planned) {
233
+ return [pscustomobject]@{ ok = $false; reason = 'no-plan-snapshot'; after = $json; backupPath = $null }
234
+ }
235
+ $fileName = Split-Path -Leaf $Path
236
+ $backup = Get-ChildItem -LiteralPath (Split-Path -Parent $Path) -Filter "$fileName.bak-*" -File -ErrorAction SilentlyContinue |
237
+ Sort-Object LastWriteTimeUtc -Descending | Select-Object -First 1
238
+ $backupPath = $null
239
+ if ($backup) { $backupPath = $backup.FullName }
240
+ $afterEvents = [int]$json.events
241
+ if ($afterEvents -lt $planned) {
242
+ return [pscustomobject]@{ ok = $true; reason = 'events-dropped'; after = $json; backupPath = $backupPath; planned = $planned }
243
+ }
244
+ return [pscustomobject]@{ ok = $false; reason = "events-did-not-drop ($afterEvents >= $planned)"; after = $json; backupPath = $backupPath; planned = $planned }
245
+ }
246
+
247
+ function Start-App {
248
+ try {
249
+ Start-Process -FilePath (Join-Path $env:WINDIR 'explorer.exe') -ArgumentList ('"' + $script:AppPath + '"') | Out-Null
250
+ Write-Run "restart: launched via explorer $($script:AppPath)"
251
+ } catch {
252
+ Write-Run "restart: launch failed: $($_.Exception.Message)"
253
+ return $false
254
+ }
255
+ Start-Sleep -Seconds 20
256
+ $procs = Get-AppProcs
257
+ $ok = $procs.Count -gt 0
258
+ Write-Run "restart: running=$ok count=$($procs.Count)"
259
+ return $ok
260
+ }
261
+
262
+ function Close-App {
263
+ if ($SimulateCloseFailure) {
264
+ Write-Run 'close: simulated failure (-SimulateCloseFailure), no process touched'
265
+ return $false
266
+ }
267
+ $started = Get-Date
268
+ $procs = Get-AppProcs
269
+ if ($procs.Count -eq 0) {
270
+ Write-Run 'close: app is not running'
271
+ return $true
272
+ }
273
+ Write-Run "close: running=$($procs.Count) pids=$((($procs | ForEach-Object { $_.Id }) -join ',')) names=$((($procs | ForEach-Object { $_.ProcessName }) -join ','))"
274
+
275
+ # One polite signal, only to the processes that actually own a main window.
276
+ # Helpers, renderers and crashpad have no window and are not asked; they are
277
+ # killed by PID below like everything else that is still alive.
278
+ $polite = 0
279
+ foreach ($proc in $procs) {
280
+ $hasWindow = $false
281
+ try { $hasWindow = ($proc.MainWindowHandle.ToInt64() -ne 0) } catch { $hasWindow = $false }
282
+ if (-not $hasWindow) { continue }
283
+ $sent = $false
284
+ try { $sent = $proc.CloseMainWindow() } catch { $sent = $false }
285
+ $polite += 1
286
+ Write-Run "close: polite signal pid=$($proc.Id) sent=$sent"
287
+ }
288
+ if ($polite -eq 0) {
289
+ Write-Run 'close: no process owns a main window, no polite signal sent'
290
+ }
291
+
292
+ # Three seconds is a courtesy window, not a negotiation: whatever is left is
293
+ # force-killed by PID right away (never a /IM image-name sweep, which matches
294
+ # globally by image name and leaves sibling processes behind).
295
+ $graceDeadline = (Get-Date).AddSeconds(3)
296
+ while ((Get-Date) -lt $graceDeadline) {
297
+ if ((Get-AppProcs).Count -eq 0) {
298
+ $ms = [int]((Get-Date) - $started).TotalMilliseconds
299
+ Write-Run "close: closed after the polite signal, elapsed=${ms}ms"
300
+ return $true
301
+ }
302
+ Start-Sleep -Milliseconds 100
303
+ }
304
+
305
+ $left = Get-AppProcs
306
+ Write-Run "close: force-killing $($left.Count) pid(s)"
307
+ foreach ($proc in $left) {
308
+ try {
309
+ Stop-Process -Id $proc.Id -Force -ErrorAction Stop
310
+ Write-Run "close: Stop-Process -Force pid=$($proc.Id) name=$($proc.ProcessName)"
311
+ } catch {
312
+ Write-Run "close: Stop-Process pid=$($proc.Id) failed: $($_.Exception.Message)"
313
+ }
314
+ }
315
+
316
+ Start-Sleep -Seconds 2
317
+ $still = Get-AppProcs
318
+ if ($still.Count -gt 0) {
319
+ Write-Run "close: still running after force: $((($still | ForEach-Object { $_.Id }) -join ','))"
320
+ return $false
321
+ }
322
+ $ms = [int]((Get-Date) - $started).TotalMilliseconds
323
+ Write-Run "close: forced close confirmed, elapsed=${ms}ms"
324
+ return $true
325
+ }
326
+
327
+ # ---------------------------------------------------------------------------
328
+ # setup and request validation
329
+ # ---------------------------------------------------------------------------
330
+ if (-not $RequestFile) {
331
+ $RequestFile = Join-Path $MemoryRoot '.longlive\logs\auto-truncate.request.json'
332
+ }
333
+ if (-not $LogDir) {
334
+ $LogDir = Join-Path $MemoryRoot '.longlive\logs'
335
+ }
336
+ if (-not (Test-Path -LiteralPath $LogDir -PathType Container)) {
337
+ New-Item -ItemType Directory -Path $LogDir -Force | Out-Null
338
+ }
339
+ $script:RunLog = Join-Path $LogDir 'auto-truncate-run.log'
340
+ $script:ResultLog = Join-Path $LogDir 'auto-truncate.log'
341
+
342
+ Write-Run "start: request=$RequestFile app=$AppExe profile=$Profile dryRun=$($DryRun.IsPresent)"
343
+
344
+ if (-not (Test-Path -LiteralPath $RequestFile -PathType Leaf)) {
345
+ Write-Run 'bad-request: request file does not exist'
346
+ exit 2
347
+ }
348
+ try {
349
+ $raw = Get-Content -LiteralPath $RequestFile -Raw -Encoding UTF8
350
+ $request = $raw | ConvertFrom-Json
351
+ } catch {
352
+ Write-Run "bad-request: cannot parse JSON: $($_.Exception.Message)"
353
+ exit 2
354
+ }
355
+
356
+ $missing = @()
357
+ foreach ($name in @('version', 'requestId', 'at', 'sessionPath', 'sessionId', 'reason', 'estimate', 'plan', 'app', 'pluginDir')) {
358
+ if ($null -eq $request.PSObject.Properties[$name]) { $missing += $name }
359
+ }
360
+ if ($missing.Count -gt 0) {
361
+ Write-Run "bad-request: missing fields: $($missing -join ',')"
362
+ exit 2
363
+ }
364
+ if ($request.version -ne 1) {
365
+ Write-Run "bad-request: unsupported version $($request.version)"
366
+ exit 2
367
+ }
368
+ if (-not (Test-Path -LiteralPath $request.sessionPath -PathType Leaf)) {
369
+ Write-Run "bad-request: session file not found: $($request.sessionPath)"
370
+ exit 2
371
+ }
372
+
373
+ # ---------------------------------------------------------------------------
374
+ # sessionPath containment: it must be a real file under the sessions root.
375
+ #
376
+ # Resolve-Path normalises separators and ..-segments; the comparison is a
377
+ # case-insensitive prefix on the full path plus one separator, so
378
+ # "sessions-other\x" cannot pass as "sessions\x". The root itself is resolved
379
+ # the same way, which keeps the check honest when DSH_HOME is redirected.
380
+ # ---------------------------------------------------------------------------
381
+ if (-not $SessionsRoot) {
382
+ if ($env:DSH_HOME) {
383
+ $SessionsRoot = Join-Path $env:DSH_HOME 'sessions'
384
+ } else {
385
+ $SessionsRoot = Join-Path $env:USERPROFILE '.dsh\sessions'
386
+ }
387
+ }
388
+ $sessionsRootFull = ''
389
+ try {
390
+ if (-not (Test-Path -LiteralPath $SessionsRoot -PathType Container)) {
391
+ throw "not a directory: $SessionsRoot"
392
+ }
393
+ $sessionsRootFull = [System.IO.Path]::GetFullPath(
394
+ (Resolve-Path -LiteralPath $SessionsRoot).ProviderPath
395
+ ).TrimEnd([char[]]@('\', '/'))
396
+ } catch {
397
+ $message = "sessions root is not usable: $SessionsRoot ($($_.Exception.Message))"
398
+ Write-Run "bad-request: SESSIONS_ROOT_NOT_FOUND $message"
399
+ Write-Result ([ordered]@{
400
+ ok = $false; status = 'bad-request'; requestId = $request.requestId
401
+ time = (Get-Date).ToString('o'); code = 'SESSIONS_ROOT_NOT_FOUND'; message = $message
402
+ sessionPath = [string]$request.sessionPath; sessionsRoot = $SessionsRoot
403
+ })
404
+ exit 2
405
+ }
406
+ $sessionFull = [System.IO.Path]::GetFullPath(
407
+ (Resolve-Path -LiteralPath $request.sessionPath).ProviderPath
408
+ )
409
+ $insidePrefix = $sessionsRootFull + [System.IO.Path]::DirectorySeparatorChar
410
+ $insideRoot = $sessionFull.StartsWith($insidePrefix, [System.StringComparison]::OrdinalIgnoreCase)
411
+ if (-not $insideRoot) {
412
+ $message = "sessionPath is outside the sessions root: $sessionFull (root: $sessionsRootFull)"
413
+ Write-Run "bad-request: SESSION_PATH_OUTSIDE_ROOT $message"
414
+ Write-Result ([ordered]@{
415
+ ok = $false; status = 'bad-request'; requestId = $request.requestId
416
+ time = (Get-Date).ToString('o'); code = 'SESSION_PATH_OUTSIDE_ROOT'; message = $message
417
+ sessionPath = $sessionFull; sessionsRoot = $sessionsRootFull
418
+ })
419
+ exit 2
420
+ }
421
+ Write-Run "session-path ok: $sessionFull under $sessionsRootFull"
422
+
423
+ if (-not (Test-Path -LiteralPath $request.pluginDir -PathType Container)) {
424
+ Write-Run "bad-request: plugin dir not found: $($request.pluginDir)"
425
+ exit 2
426
+ }
427
+ $cli = Join-Path $request.pluginDir 'scripts\truncate-cli.mjs'
428
+ if (-not (Test-Path -LiteralPath $cli -PathType Leaf)) {
429
+ Write-Run "bad-request: truncate-cli.mjs not found: $cli"
430
+ exit 2
431
+ }
432
+ $keepTurns = 12
433
+ $keepTokens = 80000
434
+ if ($null -ne $request.plan.PSObject.Properties['keepTurns']) { $keepTurns = [int]$request.plan.keepTurns }
435
+ if ($null -ne $request.plan.PSObject.Properties['keepTokens']) { $keepTokens = [int]$request.plan.keepTokens }
436
+ if ($keepTurns -lt 1 -or $keepTokens -lt 1) {
437
+ Write-Run "bad-request: invalid keepTurns=$keepTurns keepTokens=$keepTokens"
438
+ exit 2
439
+ }
440
+
441
+ $script:AppPath = $AppExe
442
+ if (-not $script:AppPath -and $null -ne $request.app.PSObject.Properties['exe']) { $script:AppPath = [string]$request.app.exe }
443
+ if (-not $script:AppPath -or -not (Test-Path -LiteralPath $script:AppPath -PathType Leaf)) {
444
+ Write-Run "bad-request: app executable not found: $script:AppPath"
445
+ exit 2
446
+ }
447
+ $script:ExeName = [System.IO.Path]::GetFileNameWithoutExtension($script:AppPath)
448
+ Write-Run "request ok: id=$($request.requestId) session=$($request.sessionPath) keepTurns=$keepTurns keepTokens=$keepTokens"
449
+
450
+ if ($DryRun) {
451
+ $plan = [ordered]@{
452
+ ok = $true
453
+ dryRun = $true
454
+ requestId = $request.requestId
455
+ sessionPath = $request.sessionPath
456
+ sessionsRoot = $sessionsRootFull
457
+ app = $script:AppPath
458
+ keepTurns = $keepTurns
459
+ keepTokens = $keepTokens
460
+ requestedPlan = $request.plan
461
+ running = ((Get-AppProcs).Count -gt 0)
462
+ close = [ordered]@{
463
+ policy = 'hard-kill'
464
+ signal = 'CloseMainWindow'
465
+ gracefulMs = 3000
466
+ kill = 'Stop-Process -Id -Force'
467
+ settleMs = 2000
468
+ }
469
+ }
470
+ $plan | ConvertTo-Json -Depth 8
471
+ Write-Run 'dry-run: validation passed, nothing closed or cut'
472
+ exit 0
473
+ }
474
+
475
+ # ---------------------------------------------------------------------------
476
+ # close - cut - verify - restart
477
+ # ---------------------------------------------------------------------------
478
+ if (-not (Close-App)) {
479
+ Write-Result ([ordered]@{
480
+ ok = $false; status = 'close-failed'; requestId = $request.requestId
481
+ time = (Get-Date).ToString('o'); code = 'CLOSE_FAILED'
482
+ message = 'the app could not be closed; nothing was cut and no session byte changed'
483
+ sessionPath = $sessionFull; app = $script:AppPath
484
+ before = $null; after = $null; archivePath = $null; backupPath = $null
485
+ verify = $null; restored = $false; restart = $false
486
+ })
487
+ # Kept for readers that only grep the run log.
488
+ Write-Run 'RESULT close-failed'
489
+ exit 3
490
+ }
491
+ Start-Sleep -Seconds 5
492
+
493
+ $nodeExe = Resolve-NodeExe $script:AppPath
494
+ if (-not $nodeExe) {
495
+ Write-Run 'cut-failed: node executable not found'
496
+ $restarted = Start-App
497
+ Write-Result ([ordered]@{
498
+ ok = $false; status = 'cut-failed'; requestId = $request.requestId
499
+ time = (Get-Date).ToString('o'); code = 'NODE_NOT_FOUND'
500
+ before = $null; after = $null; archivePath = $null; backupPath = $null
501
+ verify = $null; restored = $false; restart = $restarted
502
+ })
503
+ exit 4
504
+ }
505
+ Write-Run "cut: node=$nodeExe cli=$cli"
506
+
507
+ $cliArgs = @($cli, '--session', $sessionFull, '--keep-turns', [string]$keepTurns,
508
+ '--keep-tokens', [string]$keepTokens, '--confirm', 'TRUNCATE-VISIBLE',
509
+ '--memory-root', $MemoryRoot)
510
+ # m2 (rc.2): truncate-cli.mjs re-checks that --session lives under the DSH
511
+ # sessions root ($DSH_HOME/sessions). When the caller passed an explicit
512
+ # -SessionsRoot, derive the matching home for the child and restore it after.
513
+ $previousDshHome = $env:DSH_HOME
514
+ if ((Split-Path -Leaf $sessionsRootFull) -ieq 'sessions') {
515
+ $env:DSH_HOME = Split-Path -Parent $sessionsRootFull
516
+ }
517
+ $cliRun = Invoke-Native $nodeExe $cliArgs
518
+ if ($null -eq $previousDshHome) {
519
+ Remove-Item Env:\DSH_HOME -ErrorAction SilentlyContinue
520
+ } else {
521
+ $env:DSH_HOME = $previousDshHome
522
+ }
523
+ $cliOutput = $cliRun.Output
524
+ $cliExit = $cliRun.ExitCode
525
+ Write-Run "cut: cli exit=$cliExit raw=$($cliOutput.Trim())"
526
+
527
+ $cliJson = $null
528
+ foreach ($line in ($cliOutput -split "`r?`n")) {
529
+ $trimmed = $line.Trim()
530
+ if ($trimmed.StartsWith('{')) {
531
+ try { $cliJson = $trimmed | ConvertFrom-Json } catch { $cliJson = $null }
532
+ }
533
+ }
534
+
535
+ # rc.6 (R4-03): exit 0 with unparseable stdout is not proof of failure. Verify
536
+ # the write independently before restoring: a dropped event count means the cut
537
+ # really landed and the JSON line was the only casualty.
538
+ $unparsedStdout = ($cliExit -eq 0 -and $null -eq $cliJson)
539
+ $unparsedVerification = $null
540
+ if ($unparsedStdout) {
541
+ $probe = Test-CutApplied $nodeExe $sessionFull $request
542
+ $unparsedVerification = [ordered]@{
543
+ ok = $probe.ok
544
+ reason = $probe.reason
545
+ plannedEvents = $probe.planned
546
+ afterEvents = $(if ($null -ne $probe.after) { $probe.after.events } else { $null })
547
+ backupPath = $probe.backupPath
548
+ checkedAt = (Get-Date).ToString('o')
549
+ }
550
+ if ($probe.ok) {
551
+ Write-Run "cut: cli stdout unparsed; read-back proves the cut (events -> $($probe.after.events), planned $($probe.planned))"
552
+ $cliJson = [pscustomobject]@{
553
+ ok = $true
554
+ applied = $true
555
+ needed = $true
556
+ status = 'applied-unparsed'
557
+ encoding = 'unparsed'
558
+ sessionPath = $sessionFull
559
+ before = [pscustomobject]@{ events = $probe.planned; source = 'plan.snapshotEvents' }
560
+ after = $probe.after
561
+ backupPath = $probe.backupPath
562
+ archivePath = $null
563
+ }
564
+ } else {
565
+ Write-Run "cut: cli stdout unparsed and read-back did not prove a cut ($($probe.reason)); falling back to restore"
566
+ }
567
+ }
568
+
569
+ $backupPath = $null
570
+ $beforeSha = $null
571
+ if ($null -ne $cliJson) {
572
+ if ($null -ne $cliJson.PSObject.Properties['backupPath']) { $backupPath = [string]$cliJson.backupPath }
573
+ if ($null -ne $cliJson.before -and $null -ne $cliJson.before.PSObject.Properties['sha256']) {
574
+ $beforeSha = [string]$cliJson.before.sha256
575
+ }
576
+ }
577
+ if (-not $backupPath -and $null -ne $unparsedVerification) {
578
+ $backupPath = [string]$unparsedVerification.backupPath
579
+ }
580
+
581
+ if ($cliExit -ne 0 -or $null -eq $cliJson -or -not $cliJson.ok) {
582
+ $code = 'CLI_FAILED'
583
+ if ($null -ne $cliJson -and $null -ne $cliJson.PSObject.Properties['code']) { $code = [string]$cliJson.code }
584
+ Write-Run "cut-failed: code=$code"
585
+ $restored = Restore-Backup $backupPath $request.sessionPath $beforeSha
586
+ $restarted = Start-App
587
+ Write-Result ([ordered]@{
588
+ ok = $false; status = 'cut-failed'; requestId = $request.requestId
589
+ time = (Get-Date).ToString('o'); code = $code
590
+ before = $(if ($null -ne $cliJson) { $cliJson.before } else { $null })
591
+ after = $(if ($null -ne $cliJson) { $cliJson.after } else { $null })
592
+ archivePath = $(if ($null -ne $cliJson) { $cliJson.archivePath } else { $null })
593
+ backupPath = $backupPath; verify = $null; restored = $restored; restart = $restarted
594
+ })
595
+ exit 4
596
+ }
597
+
598
+ $sessionPath = [string]$cliJson.sessionPath
599
+ $expectedMessages = 0
600
+ if ($null -ne $cliJson.after -and $null -ne $cliJson.after.PSObject.Properties['messages']) {
601
+ $expectedMessages = [int]$cliJson.after.messages
602
+ }
603
+ Write-Run "cut: ok needed=$($cliJson.needed) applied=$($cliJson.applied) afterMessages=$expectedMessages archive=$($cliJson.archivePath)"
604
+
605
+ # The plan inside the request was built from a snapshot taken while the app was
606
+ # still running; the app keeps appending for a few milliseconds after turn/end,
607
+ # so the file this run cuts can be longer than the snapshot. Report the
608
+ # difference instead of pretending the plan matched: the numbers are what the
609
+ # operator audits, and a silent mismatch is exactly the bug this field removes.
610
+ $actualBefore = $null
611
+ if ($null -ne $cliJson.before -and $null -ne $cliJson.before.PSObject.Properties['events']) {
612
+ $actualBefore = [int]$cliJson.before.events
613
+ }
614
+ $actualAfter = $null
615
+ if ($null -ne $cliJson.after -and $null -ne $cliJson.after.PSObject.Properties['events']) {
616
+ $actualAfter = [int]$cliJson.after.events
617
+ }
618
+ $plannedSnapshot = $null
619
+ if ($null -ne $request.plan.PSObject.Properties['snapshotEvents']) {
620
+ $plannedSnapshot = [int]$request.plan.snapshotEvents
621
+ }
622
+ $plannedKept = $null
623
+ if ($null -ne $request.plan.PSObject.Properties['kept']) {
624
+ $plannedKept = [int]$request.plan.kept
625
+ }
626
+ $plannedDropped = $null
627
+ if ($null -ne $request.plan.PSObject.Properties['dropped']) {
628
+ $plannedDropped = [int]$request.plan.dropped
629
+ }
630
+ $eventsDelta = $null
631
+ if (($null -ne $plannedSnapshot) -and ($null -ne $actualBefore)) {
632
+ $eventsDelta = $actualBefore - $plannedSnapshot
633
+ }
634
+ $keptDelta = $null
635
+ if (($null -ne $plannedKept) -and ($null -ne $actualAfter)) {
636
+ $keptDelta = $actualAfter - $plannedKept
637
+ }
638
+ $actualDropped = $null
639
+ if (($null -ne $actualBefore) -and ($null -ne $actualAfter)) {
640
+ $actualDropped = $actualBefore - $actualAfter
641
+ }
642
+ $drifted = $false
643
+ if (($null -ne $eventsDelta) -and ($eventsDelta -ne 0)) { $drifted = $true }
644
+ if (($null -ne $keptDelta) -and ($keptDelta -ne 0)) { $drifted = $true }
645
+ $drift = [ordered]@{
646
+ planSnapshotEvents = $plannedSnapshot
647
+ actualBeforeEvents = $actualBefore
648
+ eventsDelta = $eventsDelta
649
+ plannedKept = $plannedKept
650
+ actualKept = $actualAfter
651
+ keptDelta = $keptDelta
652
+ plannedDropped = $plannedDropped
653
+ actualDropped = $actualDropped
654
+ drifted = $drifted
655
+ }
656
+ Write-Run "cut: drift snapshot=$plannedSnapshot actualBefore=$actualBefore eventsDelta=$eventsDelta keptDelta=$keptDelta drifted=$drifted"
657
+
658
+ $appAsar = Join-Path (Split-Path -Parent $script:AppPath) 'resources\app.asar'
659
+ $asar = Join-Path $appAsar 'dsh\node_modules'
660
+ if (-not (Test-Path -LiteralPath $appAsar -PathType Leaf)) {
661
+ Write-Run "verify-failed: app.asar not found: $appAsar"
662
+ $restored = Restore-Backup $backupPath $sessionPath $beforeSha
663
+ $restarted = Start-App
664
+ Write-Result ([ordered]@{
665
+ ok = $false; status = 'verify-failed'; requestId = $request.requestId; time = (Get-Date).ToString('o')
666
+ code = 'ASAR_NOT_FOUND'; before = $cliJson.before; after = $cliJson.after
667
+ archivePath = $cliJson.archivePath; backupPath = $backupPath; verify = $null
668
+ restored = $restored; restart = $restarted
669
+ })
670
+ exit 5
671
+ }
672
+
673
+ $verifyScript = Join-Path $LogDir 'verify-load.cjs'
674
+ $verifyCode = @'
675
+ const path = require('node:path');
676
+ const file = process.argv[2];
677
+ const expected = Number(process.argv[3]);
678
+ const asar = process.argv[4];
679
+ (async () => {
680
+ const cordis = require(path.join(asar, '@deepseek-ai/cordis'));
681
+ const persistence = require(path.join(asar, '@deepseek-ai/dsh-session-persistence-jsonl'));
682
+ const sessionMod = require(path.join(asar, '@deepseek-ai/dsh-session'));
683
+ const ctx = new cordis.Context();
684
+ await ctx.plugin(persistence, { root: path.dirname(path.dirname(path.dirname(file))), compression: 'zstd' });
685
+ const id = path.basename(path.dirname(file));
686
+ const stored = await ctx.sessionPersistence.readStoredLog(file, id);
687
+ const session = sessionMod.Session.fromRestore(
688
+ stored.meta.id, stored.events, stored.meta, stored.inheritedEventCount, stored.eventState, [],
689
+ );
690
+ const messages = session.deriveMessages();
691
+ const ok = messages.length === expected;
692
+ console.log(JSON.stringify({ ok: ok, status: stored.status, events: stored.events.length, messages: messages.length, expected: expected }));
693
+ process.exitCode = ok ? 0 : 1;
694
+ })().catch((error) => {
695
+ console.log(JSON.stringify({ ok: false, error: String((error && error.stack) || error) }));
696
+ process.exitCode = 1;
697
+ });
698
+ '@
699
+ Set-Content -LiteralPath $verifyScript -Value $verifyCode -Encoding ASCII
700
+
701
+ $env:ELECTRON_RUN_AS_NODE = '1'
702
+ $verifyRun = Invoke-Native $script:AppPath @('--expose-internals', $verifyScript, $sessionPath, ([string]$expectedMessages), $asar)
703
+ $verifyOutput = $verifyRun.Output
704
+ $verifyExit = $verifyRun.ExitCode
705
+ Remove-Item Env:\ELECTRON_RUN_AS_NODE -ErrorAction SilentlyContinue
706
+ Write-Run "verify: exit=$verifyExit raw=$($verifyOutput.Trim())"
707
+
708
+ $verifyJson = $null
709
+ foreach ($line in ($verifyOutput -split "`r?`n")) {
710
+ $trimmed = $line.Trim()
711
+ if ($trimmed.StartsWith('{')) {
712
+ try { $verifyJson = $trimmed | ConvertFrom-Json } catch { $verifyJson = $null }
713
+ }
714
+ }
715
+ $verifyOk = ($verifyExit -eq 0) -and ($null -ne $verifyJson) -and $verifyJson.ok
716
+ if (-not $verifyOk) {
717
+ Write-Run 'verify-failed: load check did not confirm the rewritten log'
718
+ $restored = Restore-Backup $backupPath $sessionPath $beforeSha
719
+ $restarted = Start-App
720
+ Write-Result ([ordered]@{
721
+ ok = $false; status = 'verify-failed'; requestId = $request.requestId; time = (Get-Date).ToString('o')
722
+ code = 'LOAD_VERIFY_FAILED'; before = $cliJson.before; after = $cliJson.after
723
+ archivePath = $cliJson.archivePath; backupPath = $backupPath
724
+ verify = $verifyJson; restored = $restored; restart = $restarted
725
+ })
726
+ exit 5
727
+ }
728
+
729
+ $restarted = Start-App
730
+ if (-not $restarted) {
731
+ Write-Run 'restart-failed: app did not come back'
732
+ Write-Result ([ordered]@{
733
+ ok = $false; status = 'restart-failed'; requestId = $request.requestId; time = (Get-Date).ToString('o')
734
+ before = $cliJson.before; after = $cliJson.after
735
+ archivePath = $cliJson.archivePath; backupPath = $backupPath
736
+ verify = $verifyJson; restart = $false; drift = $drift
737
+ })
738
+ exit 6
739
+ }
740
+
741
+ Write-Result ([ordered]@{
742
+ ok = $true; status = 'done'; requestId = $request.requestId; time = (Get-Date).ToString('o')
743
+ before = $cliJson.before; after = $cliJson.after
744
+ archivePath = $cliJson.archivePath; backupPath = $backupPath
745
+ verify = $verifyJson; restart = $true
746
+ drift = $drift
747
+ encoding = $(if ($unparsedStdout) { 'unparsed' } else { 'utf8-json' })
748
+ unparsedVerification = $unparsedVerification
749
+ })
750
+ Remove-Item -LiteralPath $RequestFile -Force
751
+ Write-Run "done: request removed ($RequestFile)"
752
+ exit 0