@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,512 @@
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
+ Exit codes:
10
+ 0 success (or -DryRun validation only)
11
+ 2 bad-request
12
+ 3 close-failed
13
+ 4 cut-failed (backup restored when available)
14
+ 5 verify-failed (backup restored)
15
+ 6 restart-failed (cut kept, request kept)
16
+
17
+ The script body is ASCII. Paths and log lines may contain any Unicode text.
18
+ #>
19
+ param(
20
+ [Parameter(Mandatory = $true)][string]$MemoryRoot,
21
+ [string]$RequestFile = '',
22
+ [string]$AppExe = '',
23
+ [string]$Profile = 'desktop',
24
+ [string]$LogDir = '',
25
+ # Vendored by resident-watcher: relaunch the app with the same arguments it
26
+ # had before (e.g. --remote-debugging-port=9333 for the VM E2E harness).
27
+ [string]$AppArgs = '',
28
+ [switch]$DryRun
29
+ )
30
+
31
+ $ErrorActionPreference = 'Stop'
32
+ $script:ExeName = ''
33
+
34
+ # rc.6 (R4-03): native node output is decoded as UTF-8 explicitly; the console
35
+ # code page (GBK on a Chinese Windows) must never touch it. Keep this file ASCII
36
+ # only: PS 5.1 reads UTF-8-without-BOM scripts as ANSI.
37
+ $script:Utf8NoBom = [System.Text.UTF8Encoding]::new($false)
38
+ try { [Console]::OutputEncoding = $script:Utf8NoBom } catch { }
39
+ try { [Console]::InputEncoding = $script:Utf8NoBom } catch { }
40
+ try { $OutputEncoding = $script:Utf8NoBom } catch { }
41
+
42
+ function Quote-NativeArg([string]$Value) {
43
+ if ($null -eq $Value) { return '""' }
44
+ if ($Value -notmatch '[\s"]') { return $Value }
45
+ $sb = [System.Text.StringBuilder]::new()
46
+ [void]$sb.Append('"')
47
+ $backslashes = 0
48
+ foreach ($ch in $Value.ToCharArray()) {
49
+ if ($ch -eq '\') { $backslashes++; continue }
50
+ if ($ch -eq '"') {
51
+ [void]$sb.Append('\' * (($backslashes * 2) + 1))
52
+ [void]$sb.Append('"')
53
+ $backslashes = 0
54
+ continue
55
+ }
56
+ if ($backslashes -gt 0) { [void]$sb.Append('\' * $backslashes); $backslashes = 0 }
57
+ [void]$sb.Append($ch)
58
+ }
59
+ if ($backslashes -gt 0) { [void]$sb.Append('\' * ($backslashes * 2)) }
60
+ [void]$sb.Append('"')
61
+ return $sb.ToString()
62
+ }
63
+
64
+ function Write-Run([string]$Message) {
65
+ $ts = (Get-Date).ToString('yyyy-MM-ddTHH:mm:ss.fffzzz')
66
+ $line = "[$ts] $Message"
67
+ Add-Content -LiteralPath $script:RunLog -Value $line -Encoding UTF8
68
+ Write-Host $line
69
+ }
70
+
71
+ function Write-Result($Value) {
72
+ $json = $Value | ConvertTo-Json -Compress -Depth 10
73
+ Add-Content -LiteralPath $script:ResultLog -Value $json -Encoding UTF8
74
+ # Per-run sidecar: the watcher sets DSH_TRUNCATE_RESULT_FILE so it can read
75
+ # exactly this run's verdict even when the shared log is noisy or rotated.
76
+ if ($script:ResultFile) {
77
+ try {
78
+ [System.IO.File]::WriteAllText($script:ResultFile, $json, (New-Object System.Text.UTF8Encoding($false)))
79
+ } catch {
80
+ Write-Run "warn: cannot write result file $($script:ResultFile): $($_.Exception.Message)"
81
+ }
82
+ }
83
+ Write-Run "RESULT $json"
84
+ }
85
+
86
+ function Invoke-Native([string]$FilePath, [string[]]$Arguments) {
87
+ # Explicit UTF-8 decoders; `& $exe @args 2>&1 | Out-String` decodes through
88
+ # the console code page and corrupts non-ASCII JSON (R4-03).
89
+ $argLine = (@($Arguments) | ForEach-Object { Quote-NativeArg ([string]$_) }) -join ' '
90
+ $psi = [System.Diagnostics.ProcessStartInfo]::new()
91
+ $psi.FileName = $FilePath
92
+ $psi.Arguments = $argLine
93
+ $psi.UseShellExecute = $false
94
+ $psi.CreateNoWindow = $true
95
+ $psi.RedirectStandardOutput = $true
96
+ $psi.RedirectStandardError = $true
97
+ $psi.StandardOutputEncoding = $script:Utf8NoBom
98
+ $psi.StandardErrorEncoding = $script:Utf8NoBom
99
+ $proc = [System.Diagnostics.Process]::new()
100
+ $proc.StartInfo = $psi
101
+ [void]$proc.Start()
102
+ $outTask = $proc.StandardOutput.ReadToEndAsync()
103
+ $errTask = $proc.StandardError.ReadToEndAsync()
104
+ if (-not $proc.WaitForExit(900000)) {
105
+ try { $proc.Kill() } catch { }
106
+ throw "native process timed out after 900s: $FilePath"
107
+ }
108
+ $stdout = $outTask.Result
109
+ $stderr = $errTask.Result
110
+ $code = $proc.ExitCode
111
+ $proc.Dispose()
112
+ $text = (@($stdout, $stderr) | Where-Object { $_ }) -join "`n"
113
+ return [pscustomobject]@{ Output = $text.Trim(); Stdout = $stdout; Stderr = $stderr; ExitCode = $code }
114
+ }
115
+
116
+ function Get-AppProcs {
117
+ $names = @($script:ExeName, 'DEEPSE~1', "$($script:ExeName) Helper")
118
+ return @(Get-Process -ErrorAction SilentlyContinue | Where-Object {
119
+ $p = $_.ProcessName
120
+ $names -contains $p -or $p -like "$($script:ExeName)*"
121
+ })
122
+ }
123
+
124
+ function Resolve-NodeExe([string]$Exe) {
125
+ $dir = Split-Path -Parent $Exe
126
+ $candidates = @()
127
+ if ($env:DSH_NODE) { $candidates += $env:DSH_NODE }
128
+ $candidates += @(
129
+ (Join-Path $dir 'resources\runtime\primary-runtime\dependencies\node\bin\node.exe'),
130
+ (Join-Path $dir 'resources\runtime\node\bin\node.exe'),
131
+ (Join-Path $dir 'resources\node\node.exe')
132
+ )
133
+ foreach ($candidate in $candidates) {
134
+ if ($candidate -and (Test-Path -LiteralPath $candidate -PathType Leaf)) { return $candidate }
135
+ }
136
+ $command = Get-Command node.exe -ErrorAction SilentlyContinue
137
+ if ($command) { return $command.Source }
138
+ return ''
139
+ }
140
+
141
+ function Restore-Backup([string]$BackupPath, [string]$TargetPath, [string]$ExpectedSha) {
142
+ if (-not $BackupPath -or -not (Test-Path -LiteralPath $BackupPath -PathType Leaf)) {
143
+ Write-Run "restore: no usable backup path ($BackupPath)"
144
+ return $false
145
+ }
146
+ Copy-Item -LiteralPath $BackupPath -Destination $TargetPath -Force
147
+ $got = (Get-FileHash -LiteralPath $TargetPath -Algorithm SHA256).Hash.ToLowerInvariant()
148
+ $want = ''
149
+ if ($ExpectedSha) { $want = $ExpectedSha.ToLowerInvariant() }
150
+ $ok = ($want -eq '') -or ($got -eq $want)
151
+ Write-Run "restore: $BackupPath -> $TargetPath sha256=$got expected=$want ok=$ok"
152
+ return $ok
153
+ }
154
+
155
+ function Start-App {
156
+ try {
157
+ if ($AppArgs) {
158
+ Start-Process -FilePath $script:AppPath -ArgumentList $AppArgs | Out-Null
159
+ Write-Run "restart: launched direct with args [$AppArgs] $($script:AppPath)"
160
+ } else {
161
+ Start-Process -FilePath (Join-Path $env:WINDIR 'explorer.exe') -ArgumentList ('"' + $script:AppPath + '"') | Out-Null
162
+ Write-Run "restart: launched via explorer $($script:AppPath)"
163
+ }
164
+ } catch {
165
+ Write-Run "restart: launch failed: $($_.Exception.Message)"
166
+ return $false
167
+ }
168
+ Start-Sleep -Seconds 20
169
+ $procs = Get-AppProcs
170
+ $ok = $procs.Count -gt 0
171
+ Write-Run "restart: running=$ok count=$($procs.Count)"
172
+ return $ok
173
+ }
174
+
175
+ function Close-App {
176
+ $procs = Get-AppProcs
177
+ if ($procs.Count -eq 0) {
178
+ Write-Run 'close: app is not running'
179
+ return $true
180
+ }
181
+ Write-Run "close: running=$($procs.Count) names=$((($procs | ForEach-Object { $_.ProcessName }) -join ','))"
182
+ foreach ($image in @("$($script:ExeName).exe", 'DEEPSE~1.EXE')) {
183
+ $result = Invoke-Native 'taskkill' @('/IM', $image)
184
+ Write-Run "close: taskkill /IM $image exit=$($result.ExitCode) out=$($result.Output.Trim())"
185
+ }
186
+ $deadline = (Get-Date).AddSeconds(60)
187
+ while ((Get-Date) -lt $deadline) {
188
+ if ((Get-AppProcs).Count -eq 0) {
189
+ Write-Run 'close: graceful close confirmed'
190
+ return $true
191
+ }
192
+ Start-Sleep -Seconds 2
193
+ }
194
+ Write-Run 'close: still running after 60s, forcing'
195
+ foreach ($image in @("$($script:ExeName).exe", 'DEEPSE~1.EXE')) {
196
+ $result = Invoke-Native 'taskkill' @('/F', '/IM', $image)
197
+ Write-Run "close: taskkill /F /IM $image exit=$($result.ExitCode) out=$($result.Output.Trim())"
198
+ }
199
+ $deadline = (Get-Date).AddSeconds(30)
200
+ while ((Get-Date) -lt $deadline) {
201
+ if ((Get-AppProcs).Count -eq 0) {
202
+ Write-Run 'close: forced close confirmed'
203
+ return $true
204
+ }
205
+ Start-Sleep -Seconds 2
206
+ }
207
+ $left = Get-AppProcs
208
+ Write-Run "close: still running after force: $((($left | ForEach-Object { $_.ProcessName }) -join ','))"
209
+ return $false
210
+ }
211
+
212
+ # ---------------------------------------------------------------------------
213
+ # setup and request validation
214
+ # ---------------------------------------------------------------------------
215
+ if (-not $RequestFile) {
216
+ $RequestFile = Join-Path $MemoryRoot '.longlive\logs\auto-truncate.request.json'
217
+ }
218
+ if (-not $LogDir) {
219
+ $LogDir = Join-Path $MemoryRoot '.longlive\logs'
220
+ }
221
+ if (-not (Test-Path -LiteralPath $LogDir -PathType Container)) {
222
+ New-Item -ItemType Directory -Path $LogDir -Force | Out-Null
223
+ }
224
+ $script:RunLog = Join-Path $LogDir 'auto-truncate-run.log'
225
+ $script:ResultLog = Join-Path $LogDir 'auto-truncate.log'
226
+ $script:ResultFile = ''
227
+ if ($env:DSH_TRUNCATE_RESULT_FILE) { $script:ResultFile = [string]$env:DSH_TRUNCATE_RESULT_FILE }
228
+
229
+ Write-Run "start: request=$RequestFile app=$AppExe profile=$Profile dryRun=$($DryRun.IsPresent)"
230
+
231
+ if (-not (Test-Path -LiteralPath $RequestFile -PathType Leaf)) {
232
+ Write-Run 'bad-request: request file does not exist'
233
+ exit 2
234
+ }
235
+ try {
236
+ $raw = Get-Content -LiteralPath $RequestFile -Raw -Encoding UTF8
237
+ $request = $raw | ConvertFrom-Json
238
+ } catch {
239
+ Write-Run "bad-request: cannot parse JSON: $($_.Exception.Message)"
240
+ exit 2
241
+ }
242
+
243
+ $missing = @()
244
+ foreach ($name in @('version', 'requestId', 'at', 'sessionPath', 'sessionId', 'reason', 'estimate', 'plan', 'app', 'pluginDir')) {
245
+ if ($null -eq $request.PSObject.Properties[$name]) { $missing += $name }
246
+ }
247
+ if ($missing.Count -gt 0) {
248
+ Write-Run "bad-request: missing fields: $($missing -join ',')"
249
+ exit 2
250
+ }
251
+ if ($request.version -ne 1) {
252
+ Write-Run "bad-request: unsupported version $($request.version)"
253
+ exit 2
254
+ }
255
+ if (-not (Test-Path -LiteralPath $request.sessionPath -PathType Leaf)) {
256
+ Write-Run "bad-request: session file not found: $($request.sessionPath)"
257
+ exit 2
258
+ }
259
+ if (-not (Test-Path -LiteralPath $request.pluginDir -PathType Container)) {
260
+ Write-Run "bad-request: plugin dir not found: $($request.pluginDir)"
261
+ exit 2
262
+ }
263
+ $cli = Join-Path $request.pluginDir 'scripts\truncate-cli.mjs'
264
+ if (-not (Test-Path -LiteralPath $cli -PathType Leaf)) {
265
+ Write-Run "bad-request: truncate-cli.mjs not found: $cli"
266
+ exit 2
267
+ }
268
+ $keepTurns = 12
269
+ $keepTokens = 80000
270
+ if ($null -ne $request.plan.PSObject.Properties['keepTurns']) { $keepTurns = [int]$request.plan.keepTurns }
271
+ if ($null -ne $request.plan.PSObject.Properties['keepTokens']) { $keepTokens = [int]$request.plan.keepTokens }
272
+ if ($keepTurns -lt 1 -or $keepTokens -lt 1) {
273
+ Write-Run "bad-request: invalid keepTurns=$keepTurns keepTokens=$keepTokens"
274
+ exit 2
275
+ }
276
+
277
+ $script:AppPath = $AppExe
278
+ if (-not $script:AppPath -and $null -ne $request.app.PSObject.Properties['exe']) { $script:AppPath = [string]$request.app.exe }
279
+ if (-not $script:AppPath -or -not (Test-Path -LiteralPath $script:AppPath -PathType Leaf)) {
280
+ Write-Run "bad-request: app executable not found: $script:AppPath"
281
+ exit 2
282
+ }
283
+ $script:ExeName = [System.IO.Path]::GetFileNameWithoutExtension($script:AppPath)
284
+ Write-Run "request ok: id=$($request.requestId) session=$($request.sessionPath) keepTurns=$keepTurns keepTokens=$keepTokens"
285
+
286
+ if ($DryRun) {
287
+ $plan = [ordered]@{
288
+ ok = $true
289
+ dryRun = $true
290
+ requestId = $request.requestId
291
+ sessionPath = $request.sessionPath
292
+ app = $script:AppPath
293
+ keepTurns = $keepTurns
294
+ keepTokens = $keepTokens
295
+ requestedPlan = $request.plan
296
+ running = ((Get-AppProcs).Count -gt 0)
297
+ }
298
+ $plan | ConvertTo-Json -Depth 8
299
+ Write-Run 'dry-run: validation passed, nothing closed or cut'
300
+ exit 0
301
+ }
302
+
303
+ # ---------------------------------------------------------------------------
304
+ # close - cut - verify - restart
305
+ # ---------------------------------------------------------------------------
306
+ if (-not (Close-App)) {
307
+ Write-Run 'RESULT close-failed'
308
+ # Keep the plain line above for log compatibility, but also emit a JSON
309
+ # result so the watcher's double-insurance check sees ok=false here too.
310
+ Write-Result ([ordered]@{
311
+ ok = $false; status = 'close-failed'; requestId = $request.requestId
312
+ time = (Get-Date).ToString('o'); code = 'CLOSE_FAILED'
313
+ before = $null; after = $null; archivePath = $null; backupPath = $null
314
+ verify = $null; restored = $false; restart = $false
315
+ })
316
+ exit 3
317
+ }
318
+ Start-Sleep -Seconds 5
319
+
320
+ $nodeExe = Resolve-NodeExe $script:AppPath
321
+ if (-not $nodeExe) {
322
+ Write-Run 'cut-failed: node executable not found'
323
+ $restarted = Start-App
324
+ Write-Result ([ordered]@{
325
+ ok = $false; status = 'cut-failed'; requestId = $request.requestId
326
+ time = (Get-Date).ToString('o'); code = 'NODE_NOT_FOUND'
327
+ before = $null; after = $null; archivePath = $null; backupPath = $null
328
+ verify = $null; restored = $false; restart = $restarted
329
+ })
330
+ exit 4
331
+ }
332
+ Write-Run "cut: node=$nodeExe cli=$cli"
333
+
334
+ $cliArgs = @($cli, '--session', $request.sessionPath, '--keep-turns', [string]$keepTurns,
335
+ '--keep-tokens', [string]$keepTokens, '--confirm', 'TRUNCATE-VISIBLE')
336
+ $cliRun = Invoke-Native $nodeExe $cliArgs
337
+ $cliOutput = $cliRun.Output
338
+ $cliExit = $cliRun.ExitCode
339
+ Write-Run "cut: cli exit=$cliExit raw=$($cliOutput.Trim())"
340
+
341
+ $cliJson = $null
342
+ foreach ($line in ($cliOutput -split "`r?`n")) {
343
+ $trimmed = $line.Trim()
344
+ if ($trimmed.StartsWith('{')) {
345
+ try { $cliJson = $trimmed | ConvertFrom-Json } catch { $cliJson = $null }
346
+ }
347
+ }
348
+
349
+ # rc.6 (R4-03): exit 0 with unparseable stdout is not failure by itself. Verify
350
+ # the cut independently (event count from surgery-inspect) before restoring.
351
+ $unparsedStdout = ($cliExit -eq 0 -and $null -eq $cliJson)
352
+ $unparsedVerification = $null
353
+ if ($unparsedStdout) {
354
+ $inspectScript = Join-Path (Split-Path -Parent $PSScriptRoot) 'surgery-inspect.mjs'
355
+ $probeJson = $null
356
+ if (Test-Path -LiteralPath $inspectScript -PathType Leaf) {
357
+ $probeRun = Invoke-Native $nodeExe @($inspectScript, $request.sessionPath)
358
+ foreach ($line in ($probeRun.Output -split "`r?`n")) {
359
+ $trimmed = $line.Trim()
360
+ if (-not $trimmed.StartsWith('{')) { continue }
361
+ try { $probeJson = $trimmed | ConvertFrom-Json } catch { $probeJson = $null }
362
+ }
363
+ }
364
+ $planned = $null
365
+ if ($null -ne $request.plan -and $null -ne $request.plan.PSObject.Properties['snapshotEvents']) {
366
+ $planned = [int]$request.plan.snapshotEvents
367
+ }
368
+ $afterEvents = $null
369
+ if ($null -ne $probeJson -and $probeJson.ok) { $afterEvents = [int]$probeJson.events }
370
+ $proven = ($null -ne $planned) -and ($null -ne $afterEvents) -and ($afterEvents -lt $planned)
371
+ $unparsedVerification = [ordered]@{
372
+ ok = $proven; plannedEvents = $planned; afterEvents = $afterEvents
373
+ checkedAt = (Get-Date).ToString('o')
374
+ }
375
+ if ($proven) {
376
+ Write-Run "cut: cli stdout unparsed; read-back proves the cut (events -> $afterEvents, planned $planned)"
377
+ $cliJson = [pscustomobject]@{
378
+ ok = $true; applied = $true; needed = $true; status = 'applied-unparsed'
379
+ encoding = 'unparsed'; sessionPath = $request.sessionPath
380
+ before = [pscustomobject]@{ events = $planned; source = 'plan.snapshotEvents' }
381
+ after = $probeJson; backupPath = $null; archivePath = $null
382
+ }
383
+ } else {
384
+ Write-Run 'cut: cli stdout unparsed and read-back did not prove a cut; falling back to restore'
385
+ }
386
+ }
387
+
388
+ $backupPath = $null
389
+ $beforeSha = $null
390
+ if ($null -ne $cliJson) {
391
+ if ($null -ne $cliJson.PSObject.Properties['backupPath']) { $backupPath = [string]$cliJson.backupPath }
392
+ if ($null -ne $cliJson.PSObject.Properties['before'] -and $null -ne $cliJson.before) {
393
+ if ($null -ne $cliJson.before.PSObject.Properties['sha256']) { $beforeSha = [string]$cliJson.before.sha256 }
394
+ }
395
+ }
396
+
397
+ if ($cliExit -ne 0 -or $null -eq $cliJson -or -not $cliJson.ok) {
398
+ $code = 'CLI_FAILED'
399
+ if ($null -ne $cliJson -and $null -ne $cliJson.PSObject.Properties['code']) { $code = [string]$cliJson.code }
400
+ Write-Run "cut-failed: code=$code"
401
+ $restored = Restore-Backup $backupPath $request.sessionPath $beforeSha
402
+ $restarted = Start-App
403
+ Write-Result ([ordered]@{
404
+ ok = $false; status = 'cut-failed'; requestId = $request.requestId
405
+ time = (Get-Date).ToString('o'); code = $code
406
+ before = $(if ($null -ne $cliJson) { $cliJson.before } else { $null })
407
+ after = $(if ($null -ne $cliJson) { $cliJson.after } else { $null })
408
+ archivePath = $(if ($null -ne $cliJson) { $cliJson.archivePath } else { $null })
409
+ backupPath = $backupPath; verify = $null; restored = $restored; restart = $restarted
410
+ })
411
+ exit 4
412
+ }
413
+
414
+ $sessionPath = [string]$cliJson.sessionPath
415
+ $expectedMessages = 0
416
+ if ($null -ne $cliJson.after -and $null -ne $cliJson.after.PSObject.Properties['messages']) {
417
+ $expectedMessages = [int]$cliJson.after.messages
418
+ }
419
+ Write-Run "cut: ok needed=$($cliJson.needed) applied=$($cliJson.applied) afterMessages=$expectedMessages archive=$($cliJson.archivePath)"
420
+
421
+ $appAsar = Join-Path (Split-Path -Parent $script:AppPath) 'resources\app.asar'
422
+ $asar = Join-Path $appAsar 'dsh\node_modules'
423
+ if (-not (Test-Path -LiteralPath $appAsar -PathType Leaf)) {
424
+ Write-Run "verify-failed: app.asar not found: $appAsar"
425
+ $restored = Restore-Backup $backupPath $sessionPath $beforeSha
426
+ $restarted = Start-App
427
+ Write-Result ([ordered]@{
428
+ ok = $false; status = 'verify-failed'; requestId = $request.requestId; time = (Get-Date).ToString('o')
429
+ code = 'ASAR_NOT_FOUND'; before = $cliJson.before; after = $cliJson.after
430
+ archivePath = $cliJson.archivePath; backupPath = $backupPath; verify = $null
431
+ restored = $restored; restart = $restarted
432
+ })
433
+ exit 5
434
+ }
435
+
436
+ $verifyScript = Join-Path $LogDir 'verify-load.cjs'
437
+ $verifyCode = @'
438
+ const path = require('node:path');
439
+ const file = process.argv[2];
440
+ const expected = Number(process.argv[3]);
441
+ const asar = process.argv[4];
442
+ (async () => {
443
+ const cordis = require(path.join(asar, '@deepseek-ai/cordis'));
444
+ const persistence = require(path.join(asar, '@deepseek-ai/dsh-session-persistence-jsonl'));
445
+ const sessionMod = require(path.join(asar, '@deepseek-ai/dsh-session'));
446
+ const ctx = new cordis.Context();
447
+ await ctx.plugin(persistence, { root: path.dirname(path.dirname(path.dirname(file))), compression: 'zstd' });
448
+ const id = path.basename(path.dirname(file));
449
+ const stored = await ctx.sessionPersistence.readStoredLog(file, id);
450
+ const session = sessionMod.Session.fromRestore(
451
+ stored.meta.id, stored.events, stored.meta, stored.inheritedEventCount, stored.eventState, [],
452
+ );
453
+ const messages = session.deriveMessages();
454
+ const ok = messages.length === expected;
455
+ console.log(JSON.stringify({ ok: ok, status: stored.status, events: stored.events.length, messages: messages.length, expected: expected }));
456
+ process.exitCode = ok ? 0 : 1;
457
+ })().catch((error) => {
458
+ console.log(JSON.stringify({ ok: false, error: String((error && error.stack) || error) }));
459
+ process.exitCode = 1;
460
+ });
461
+ '@
462
+ Set-Content -LiteralPath $verifyScript -Value $verifyCode -Encoding ASCII
463
+
464
+ $env:ELECTRON_RUN_AS_NODE = '1'
465
+ $verifyRun = Invoke-Native $script:AppPath @('--expose-internals', $verifyScript, $sessionPath, ([string]$expectedMessages), $asar)
466
+ $verifyOutput = $verifyRun.Output
467
+ $verifyExit = $verifyRun.ExitCode
468
+ Remove-Item Env:\ELECTRON_RUN_AS_NODE -ErrorAction SilentlyContinue
469
+ Write-Run "verify: exit=$verifyExit raw=$($verifyOutput.Trim())"
470
+
471
+ $verifyJson = $null
472
+ foreach ($line in ($verifyOutput -split "`r?`n")) {
473
+ $trimmed = $line.Trim()
474
+ if ($trimmed.StartsWith('{')) {
475
+ try { $verifyJson = $trimmed | ConvertFrom-Json } catch { $verifyJson = $null }
476
+ }
477
+ }
478
+ $verifyOk = ($verifyExit -eq 0) -and ($null -ne $verifyJson) -and $verifyJson.ok
479
+ if (-not $verifyOk) {
480
+ Write-Run 'verify-failed: load check did not confirm the rewritten log'
481
+ $restored = Restore-Backup $backupPath $sessionPath $beforeSha
482
+ $restarted = Start-App
483
+ Write-Result ([ordered]@{
484
+ ok = $false; status = 'verify-failed'; requestId = $request.requestId; time = (Get-Date).ToString('o')
485
+ code = 'LOAD_VERIFY_FAILED'; before = $cliJson.before; after = $cliJson.after
486
+ archivePath = $cliJson.archivePath; backupPath = $backupPath
487
+ verify = $verifyJson; restored = $restored; restart = $restarted
488
+ })
489
+ exit 5
490
+ }
491
+
492
+ $restarted = Start-App
493
+ if (-not $restarted) {
494
+ Write-Run 'restart-failed: app did not come back'
495
+ Write-Result ([ordered]@{
496
+ ok = $false; status = 'restart-failed'; requestId = $request.requestId; time = (Get-Date).ToString('o')
497
+ before = $cliJson.before; after = $cliJson.after
498
+ archivePath = $cliJson.archivePath; backupPath = $backupPath
499
+ verify = $verifyJson; restart = $false
500
+ })
501
+ exit 6
502
+ }
503
+
504
+ Write-Result ([ordered]@{
505
+ ok = $true; status = 'done'; requestId = $request.requestId; time = (Get-Date).ToString('o')
506
+ before = $cliJson.before; after = $cliJson.after
507
+ archivePath = $cliJson.archivePath; backupPath = $backupPath
508
+ verify = $verifyJson; restart = $true
509
+ })
510
+ Remove-Item -LiteralPath $RequestFile -Force
511
+ Write-Run "done: request removed ($RequestFile)"
512
+ exit 0