@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.
- package/CHANGELOG.md +235 -0
- package/LICENSE +21 -0
- package/QUICKSTART.md +362 -0
- package/README.en.md +64 -0
- package/README.md +256 -2
- package/SPEC.md +211 -0
- package/build-info.json +1665 -0
- package/cordis.patch.yml +208 -0
- package/docs/A1-MIGRATION.md +75 -0
- package/docs/ANSWER-GUARD.md +92 -0
- package/docs/ARCHITECTURE.md +128 -0
- package/docs/AUTO-RECALL-WIRING.md +115 -0
- package/docs/AUTO-RECALL.md +237 -0
- package/docs/CONCEPTS.md +143 -0
- package/docs/CONFIG.md +839 -0
- package/docs/ERRORS.md +271 -0
- package/docs/FAQ.md +186 -0
- package/docs/FEATURES.md +579 -0
- package/docs/INDEX-FRESHNESS.md +21 -0
- package/docs/METRICS.md +244 -0
- package/docs/MIGRATION-1.6.0.md +220 -0
- package/docs/OPERATIONS.md +439 -0
- package/docs/PANEL-INTEGRATION.md +190 -0
- package/docs/PRIVACY.md +88 -0
- package/docs/QUICKSTART.md +155 -0
- package/docs/RAW-INDEX-POLICY.md +7 -0
- package/docs/README.en.md +48 -0
- package/docs/RESIDENT-WATCHER.md +90 -0
- package/docs/SESSION-WATCH.md +214 -0
- package/docs/TOOLS.md +184 -0
- package/docs/TROUBLESHOOTING.md +329 -0
- package/icon.svg +11 -0
- package/lib/client.js +436 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +163 -4
- package/runbook.md +343 -0
- package/scripts/archive-digest-build.mjs +668 -0
- package/scripts/auto-truncate-run.ps1 +752 -0
- package/scripts/backfill-auto-cards.mjs +98 -0
- package/scripts/edges-build.mjs +1003 -0
- package/scripts/index-maintain.mjs +39 -0
- package/scripts/index-reconcile.mjs +49 -0
- package/scripts/index-status.mjs +28 -0
- package/scripts/install-resident-watcher.ps1 +15 -0
- package/scripts/install-session-watch.ps1 +332 -0
- package/scripts/install-surgery-task.ps1 +174 -0
- package/scripts/lib/auto-truncate-run.ps1 +512 -0
- package/scripts/lib/session-watch-fixture.mjs +207 -0
- package/scripts/longlive-doctor.mjs +578 -0
- package/scripts/metrics-read.mjs +79 -0
- package/scripts/metrics-sample.mjs +215 -0
- package/scripts/migrate-180.mjs +163 -0
- package/scripts/migrate-200.mjs +8 -0
- package/scripts/migrate-a1-legacy.mjs +62 -0
- package/scripts/migrate-lifecycle.mjs +157 -0
- package/scripts/pack.mjs +392 -0
- package/scripts/recall-index-build.mjs +128 -0
- package/scripts/recall-links-build.mjs +420 -0
- package/scripts/rescore-cards.mjs +36 -0
- package/scripts/resident-watcher-status.ps1 +15 -0
- package/scripts/resident-watcher.ps1 +643 -0
- package/scripts/session-watch-drill.mjs +553 -0
- package/scripts/session-watch-status.ps1 +146 -0
- package/scripts/session-watch.mjs +1367 -0
- package/scripts/surgery-inspect.mjs +122 -0
- package/scripts/surgery-run.cmd +34 -0
- package/scripts/truncate-cli.mjs +279 -0
- package/scripts/unattended-surgery.ps1 +1019 -0
- package/scripts/uninstall-resident-watcher.ps1 +15 -0
- package/scripts/uninstall-session-watch.ps1 +192 -0
- package/scripts/verify-card-anchors.mjs +138 -0
- package/scripts/watch-loop.ps1 +916 -0
- package/src/actions/audit.js +125 -0
- package/src/actions/evidence.js +122 -0
- package/src/actions/fs.js +162 -0
- package/src/activity/index.js +873 -0
- package/src/activity/model.js +351 -0
- package/src/activity/store.js +786 -0
- package/src/activity/summary.js +180 -0
- package/src/activity/thinking.js +191 -0
- package/src/adapters/constants.js +11 -0
- package/src/adapters/engram/data/aliases.json +51 -0
- package/src/adapters/engram/data/policy.json +8 -0
- package/src/adapters/engram/data/routing-rules.json +546 -0
- package/src/adapters/engram/index.js +278 -0
- package/src/adapters/registry.js +315 -0
- package/src/answer/audit.js +238 -0
- package/src/answer/claim-guard.mjs +234 -0
- package/src/answer/evidence.js +30 -0
- package/src/answer/guard.js +1370 -0
- package/src/answer/index.js +1086 -0
- package/src/answer/query.js +111 -0
- package/src/answer/second-hop.mjs +101 -0
- package/src/auto-truncate-status.js +164 -0
- package/src/auto-truncate.js +1181 -0
- package/src/autoprocedure/candidate.js +342 -0
- package/src/autoprocedure/config.js +122 -0
- package/src/autoprocedure/evidence.js +345 -0
- package/src/autoprocedure/index.js +83 -0
- package/src/autoprocedure/ledger.js +329 -0
- package/src/autoprocedure/lint.js +232 -0
- package/src/autoprocedure/llm.js +409 -0
- package/src/autoprocedure/locks.js +102 -0
- package/src/autoprocedure/paths.js +39 -0
- package/src/autoprocedure/privacy.js +87 -0
- package/src/autoprocedure/rules.js +288 -0
- package/src/autoprocedure/runtime.js +718 -0
- package/src/autoprocedure/session-reader.js +328 -0
- package/src/backup.js +310 -0
- package/src/bus/bus.mjs +1446 -0
- package/src/codec.js +269 -0
- package/src/compaction/cut-engine.js +44 -0
- package/src/compaction/engine-core.js +1237 -0
- package/src/compaction/entry.js +228 -0
- package/src/compaction.js +230 -0
- package/src/conclusion.js +366 -0
- package/src/config.js +835 -0
- package/src/d6/runtime.js +517 -0
- package/src/d6/surface.js +181 -0
- package/src/deps.js +189 -0
- package/src/engine-status.js +141 -0
- package/src/features.js +1035 -0
- package/src/handoff/index.js +1077 -0
- package/src/handoff/model.js +1058 -0
- package/src/handoff/store.js +1233 -0
- package/src/heartbeat.js +385 -0
- package/src/home.js +16 -0
- package/src/host-version.js +280 -0
- package/src/hot-truncate-diag.js +98 -0
- package/src/identity/card-marker.js +281 -0
- package/src/identity/handover.js +845 -0
- package/src/identity/index.js +337 -0
- package/src/identity/inject-position.js +133 -0
- package/src/identity/writeback.js +344 -0
- package/src/identity.js +118 -0
- package/src/index.js +647 -0
- package/src/lifecycle/gap-clocks.js +364 -0
- package/src/lifecycle/index.js +269 -0
- package/src/lifecycle/proactive.js +1426 -0
- package/src/live-target.js +212 -0
- package/src/live.js +1603 -0
- package/src/log-rotation.js +153 -0
- package/src/memory/a1-migration.js +190 -0
- package/src/memory/activity-capture.js +229 -0
- package/src/memory/anchor-fallback.js +116 -0
- package/src/memory/anchors.js +194 -0
- package/src/memory/archive-cold-state.mjs +794 -0
- package/src/memory/archive-staging.mjs +305 -0
- package/src/memory/archive.mjs +415 -0
- package/src/memory/audit-records.js +222 -0
- package/src/memory/auto-cards.js +441 -0
- package/src/memory/capture-host.js +297 -0
- package/src/memory/capture.js +496 -0
- package/src/memory/card-anchors.js +203 -0
- package/src/memory/card-priority.js +110 -0
- package/src/memory/cards.js +425 -0
- package/src/memory/catchup.mjs +534 -0
- package/src/memory/conclusion-distill.js +381 -0
- package/src/memory/conclusion-drafts.js +243 -0
- package/src/memory/conflicts.js +1060 -0
- package/src/memory/consolidate.js +834 -0
- package/src/memory/decay.js +311 -0
- package/src/memory/distill.js +485 -0
- package/src/memory/event-index.js +1826 -0
- package/src/memory/evidence-chain.js +295 -0
- package/src/memory/evidence.js +213 -0
- package/src/memory/filter-runner.js +555 -0
- package/src/memory/filter.js +1035 -0
- package/src/memory/forget-v2.js +680 -0
- package/src/memory/forget.js +531 -0
- package/src/memory/frames-activation.js +249 -0
- package/src/memory/frontmatter.js +454 -0
- package/src/memory/fts-query.js +342 -0
- package/src/memory/governance.js +604 -0
- package/src/memory/index-freshness.js +234 -0
- package/src/memory/index.js +435 -0
- package/src/memory/l2-gate.js +169 -0
- package/src/memory/land.mjs +743 -0
- package/src/memory/lifecycle.js +235 -0
- package/src/memory/lock.js +121 -0
- package/src/memory/maintenance.js +1149 -0
- package/src/memory/manifest.js +245 -0
- package/src/memory/memory-health.mjs +607 -0
- package/src/memory/migrate-200.js +1681 -0
- package/src/memory/migrate-lifecycle.js +1808 -0
- package/src/memory/migrate.js +139 -0
- package/src/memory/paths.js +229 -0
- package/src/memory/procedure-candidate.mjs +377 -0
- package/src/memory/procedure.js +982 -0
- package/src/memory/prospective-memory.mjs +362 -0
- package/src/memory/provenance.js +119 -0
- package/src/memory/recall-feedback.mjs +406 -0
- package/src/memory/recall-v2.js +218 -0
- package/src/memory/recall.js +357 -0
- package/src/memory/reconcile.js +265 -0
- package/src/memory/records.js +433 -0
- package/src/memory/reinforce.js +281 -0
- package/src/memory/retention.js +162 -0
- package/src/memory/review.js +124 -0
- package/src/memory/state.js +279 -0
- package/src/memory/tiers.js +168 -0
- package/src/memory/topic-phrases.js +73 -0
- package/src/memory/trust.js +97 -0
- package/src/memory/turn-budget.mjs +290 -0
- package/src/memory/version-chain.js +264 -0
- package/src/memory/wake-bridge.mjs +2999 -0
- package/src/memory/wal.js +137 -0
- package/src/memory/working-frame.js +779 -0
- package/src/metrics/classify.mjs +191 -0
- package/src/metrics/estimate.mjs +108 -0
- package/src/metrics/index.mjs +204 -0
- package/src/metrics/measure.mjs +462 -0
- package/src/metrics/prestep-latency.mjs +307 -0
- package/src/metrics/store.mjs +264 -0
- package/src/original.js +294 -0
- package/src/policy/threshold-policy.js +224 -0
- package/src/policy-profile.js +463 -0
- package/src/recall/anaphora.mjs +87 -0
- package/src/recall/archive-config.mjs +130 -0
- package/src/recall/archive-fallback.mjs +390 -0
- package/src/recall/archive-search.mjs +428 -0
- package/src/recall/archive-state.mjs +588 -0
- package/src/recall/brain.mjs +501 -0
- package/src/recall/cards.mjs +202 -0
- package/src/recall/current-line.mjs +110 -0
- package/src/recall/edges.js +398 -0
- package/src/recall/embedding.mjs +698 -0
- package/src/recall/entities.mjs +112 -0
- package/src/recall/explain.mjs +443 -0
- package/src/recall/force-policy.mjs +138 -0
- package/src/recall/gate-log.mjs +280 -0
- package/src/recall/gate-metrics.mjs +191 -0
- package/src/recall/index.js +1337 -0
- package/src/recall/inject-order.mjs +279 -0
- package/src/recall/link-recall.mjs +183 -0
- package/src/recall/links.mjs +696 -0
- package/src/recall/privacy.mjs +208 -0
- package/src/recall/recall-core.mjs +810 -0
- package/src/recall/shared-visibility.js +302 -0
- package/src/recall/time-normalizer.mjs +196 -0
- package/src/recall/turn-budget-inject.mjs +154 -0
- package/src/retention/cold-gate.mjs +146 -0
- package/src/retention/config.js +163 -0
- package/src/retention/index.js +801 -0
- package/src/role/activation.js +191 -0
- package/src/role/attention.js +318 -0
- package/src/role/base.js +36 -0
- package/src/role/channels.js +423 -0
- package/src/role/index.js +425 -0
- package/src/role/interfaces.js +115 -0
- package/src/role/personality.js +370 -0
- package/src/role/readers.js +151 -0
- package/src/role/relationships.js +477 -0
- package/src/role/store.js +202 -0
- package/src/role/writeprotect.js +373 -0
- package/src/router/aliases.json +182 -0
- package/src/router/background/agent-runner.mjs +239 -0
- package/src/router/background/anchor.mjs +323 -0
- package/src/router/background/audit.mjs +337 -0
- package/src/router/background/budget-ledger.mjs +648 -0
- package/src/router/background/host-sim.mjs +451 -0
- package/src/router/background/index.mjs +81 -0
- package/src/router/background/memory.mjs +63 -0
- package/src/router/background/mock-llm.mjs +203 -0
- package/src/router/background/queue.mjs +224 -0
- package/src/router/background/retry.mjs +255 -0
- package/src/router/background/router.mjs +1459 -0
- package/src/router/background/stream.mjs +276 -0
- package/src/router/background/tool-policy.mjs +255 -0
- package/src/router/design-headings.json +221 -0
- package/src/router/face/config.mjs +155 -0
- package/src/router/face/context.mjs +284 -0
- package/src/router/face/face.mjs +466 -0
- package/src/router/face/identity.mjs +130 -0
- package/src/router/face/index.mjs +65 -0
- package/src/router/face/journal.mjs +119 -0
- package/src/router/face/llm.mjs +252 -0
- package/src/router/face/outbox.mjs +153 -0
- package/src/router/face/paths.mjs +54 -0
- package/src/router/judge.mjs +987 -0
- package/src/router/policies/generic.json +131 -0
- package/src/router/route.js +1766 -0
- package/src/router/router.mjs +535 -0
- package/src/router/routing-rules.json +816 -0
- package/src/router/run-sim.mjs +530 -0
- package/src/router/runtime.js +569 -0
- package/src/router/service/apply.mjs +1218 -0
- package/src/router/service/board.mjs +712 -0
- package/src/router/service/caller.mjs +131 -0
- package/src/router/service/config.mjs +361 -0
- package/src/router/service/context.mjs +314 -0
- package/src/router/service/hint.mjs +668 -0
- package/src/router/service/lease.mjs +494 -0
- package/src/router/service/live.mjs +251 -0
- package/src/router/service/lock.mjs +550 -0
- package/src/router/service/merge.mjs +255 -0
- package/src/router/service/model-resolve.mjs +350 -0
- package/src/router/service/paths.mjs +168 -0
- package/src/router/service/proposals.mjs +1461 -0
- package/src/router/service/queue.mjs +477 -0
- package/src/router/service/reconcile.mjs +271 -0
- package/src/router/service/service.mjs +2998 -0
- package/src/router/service/sources.mjs +352 -0
- package/src/router/service/status.mjs +520 -0
- package/src/router/service/store.mjs +476 -0
- package/src/router/service/ticklock.mjs +239 -0
- package/src/router/service/tokens.mjs +95 -0
- package/src/router/service/tools.mjs +248 -0
- package/src/router/service/wake.mjs +544 -0
- package/src/router/service/wal.mjs +685 -0
- package/src/router/shadow.mjs +821 -0
- package/src/surgery-recovery.js +1909 -0
- package/src/tool-output.js +485 -0
- package/src/tools.js +3262 -0
- package/src/truncate-visible.js +2416 -0
- package/src/truncate.js +999 -0
- package/src/ui/actions.js +1312 -0
- package/src/ui/flags.js +259 -0
- package/src/ui/panel-api.js +371 -0
- package/src/ui/panel-auth.js +251 -0
- package/src/ui/panel-integrity.js +243 -0
- package/src/ui/routes-readonly.js +759 -0
- package/src/ui/routes.js +284 -0
- package/src/util/append-store.js +368 -0
- package/src/util/local-day.js +30 -0
- package/src/util/redact.js +227 -0
- package/src/util/stale-locks.js +148 -0
- package/src/version.js +99 -0
- package/test/fixtures/pre-step-container.mjs +100 -0
- package/test/p1_probe.mjs +97 -0
|
@@ -0,0 +1,1019 @@
|
|
|
1
|
+
#requires -Version 5.1
|
|
2
|
+
<#
|
|
3
|
+
.SYNOPSIS
|
|
4
|
+
Unattended longlive session truncation ("surgery") with an on-disk stage file.
|
|
5
|
+
|
|
6
|
+
.DESCRIPTION
|
|
7
|
+
Runs the longlive truncate CLI against one session file while the DSH host is
|
|
8
|
+
closed, then restarts the host. Designed to be started by Task Scheduler with
|
|
9
|
+
-WindowStyle Hidden so there is NO visible console window for the user to
|
|
10
|
+
close mid-surgery.
|
|
11
|
+
|
|
12
|
+
Stage file (atomic write, survives a killed launcher/host):
|
|
13
|
+
<MemoryRoot>\.longlive\surgery-state.json
|
|
14
|
+
|
|
15
|
+
Phases: prepare -> backup -> cut -> restart -> done | receipt-pending
|
|
16
|
+
| needs-attention | failed.
|
|
17
|
+
A cut whose CLI exited 0 but printed unreadable stdout is independently
|
|
18
|
+
verified (sha / bytes / events / messages / backup); when it passes, the cut
|
|
19
|
+
is recorded as cut.outcome "applied-unparsed" and the run still ends in
|
|
20
|
+
"done" with a receipt. When it fails, the run parks at "needs-attention"
|
|
21
|
+
(never a plain "failed") so nothing is retried blindly.
|
|
22
|
+
-DryRun stops at a dedicated "dryrun" phase (never "done"): a rehearsal has
|
|
23
|
+
no backup and no receipt, and writing "done" made the next activation report
|
|
24
|
+
a missing backup for a surgery that never happened.
|
|
25
|
+
On the next plugin activation, src/surgery-recovery.js reads this file and
|
|
26
|
+
only reports; it never re-cuts automatically.
|
|
27
|
+
|
|
28
|
+
.PARAMETER SessionPath
|
|
29
|
+
Absolute path to session.v4.jsonl.zstd. Must live under the DSH sessions root
|
|
30
|
+
unless -DryRun or -AllowOutsideSessions is given.
|
|
31
|
+
|
|
32
|
+
.PARAMETER KeepTurns
|
|
33
|
+
Passed to truncate-cli.mjs --keep-turns (default 12).
|
|
34
|
+
|
|
35
|
+
.PARAMETER KeepTokens
|
|
36
|
+
Passed to truncate-cli.mjs --keep-tokens (default 80000).
|
|
37
|
+
|
|
38
|
+
.PARAMETER StartDelaySeconds
|
|
39
|
+
Grace window between launching the script and closing the host. 30 seconds is
|
|
40
|
+
deliberate: it is the time a human gets to read the last screen before the
|
|
41
|
+
window disappears. This is a readability window, not a race with the host.
|
|
42
|
+
|
|
43
|
+
.PARAMETER RestartDelaySeconds
|
|
44
|
+
Wait between the verified receipt and restarting the host. Default 0: after
|
|
45
|
+
the read-back and the in-conversation receipt are on disk, restart at once.
|
|
46
|
+
Do not confuse this with StartDelaySeconds (30).
|
|
47
|
+
|
|
48
|
+
.PARAMETER AppPath
|
|
49
|
+
Absolute path to the DSH host executable. Required for a real run.
|
|
50
|
+
|
|
51
|
+
.PARAMETER ResultPath
|
|
52
|
+
Where to write the result JSON. Default:
|
|
53
|
+
<MemoryRoot>\.longlive\reports\surgery-result-<surgeryId>.json
|
|
54
|
+
|
|
55
|
+
.PARAMETER MemoryRoot
|
|
56
|
+
longlive memory root. Default: DSH_LONGLIVE_MEMORY_ROOT, else DSH_MEM,
|
|
57
|
+
else <DSH_HOME>\longlive-memory.
|
|
58
|
+
|
|
59
|
+
.PARAMETER NodeExe
|
|
60
|
+
node.exe path. Default: node.exe on PATH, DSH_NODE_EXE, then the bundled
|
|
61
|
+
DSH primary-runtime node.
|
|
62
|
+
|
|
63
|
+
.PARAMETER Confirm
|
|
64
|
+
Real runs require -Confirm TRUNCATE-VISIBLE (the same word the CLI uses).
|
|
65
|
+
|
|
66
|
+
.PARAMETER DryRun
|
|
67
|
+
Validate arguments and stop in phase "dryrun" with done.outcome "dry-run".
|
|
68
|
+
Never writes phase "done". Does not close the host, copy a backup, cut, or
|
|
69
|
+
restart; the startup check and --write-receipt both recognise the rehearsal.
|
|
70
|
+
|
|
71
|
+
.PARAMETER AllowOutsideSessions
|
|
72
|
+
Permit a real run on a session outside the DSH sessions root (dangerous).
|
|
73
|
+
|
|
74
|
+
.EXAMPLE
|
|
75
|
+
powershell.exe -NoProfile -NonInteractive -WindowStyle Hidden -ExecutionPolicy Bypass `
|
|
76
|
+
-File scripts\unattended-surgery.ps1 `
|
|
77
|
+
-SessionPath "%USERPROFILE%\.dsh\sessions\scope\abc\session.v4.jsonl.zstd" `
|
|
78
|
+
-AppPath "<path-to-DSH-host.exe>" -Confirm TRUNCATE-VISIBLE
|
|
79
|
+
#>
|
|
80
|
+
[CmdletBinding()]
|
|
81
|
+
param(
|
|
82
|
+
[Parameter(Mandatory = $true)]
|
|
83
|
+
[string]$SessionPath,
|
|
84
|
+
|
|
85
|
+
[int]$KeepTurns = 12,
|
|
86
|
+
[int]$KeepTokens = 80000,
|
|
87
|
+
[int]$StartDelaySeconds = 30,
|
|
88
|
+
[int]$RestartDelaySeconds = 0,
|
|
89
|
+
|
|
90
|
+
[string]$AppPath = '',
|
|
91
|
+
[string]$ResultPath = '',
|
|
92
|
+
[string]$MemoryRoot = '',
|
|
93
|
+
[string]$NodeExe = '',
|
|
94
|
+
[string]$Confirm = '',
|
|
95
|
+
|
|
96
|
+
[switch]$DryRun,
|
|
97
|
+
[switch]$AllowOutsideSessions
|
|
98
|
+
)
|
|
99
|
+
|
|
100
|
+
$ErrorActionPreference = 'Stop'
|
|
101
|
+
|
|
102
|
+
# rc.6 (R4-03): never let the console code page decide how node output is read.
|
|
103
|
+
# On a zh-CN Windows the console defaults to GBK; the truncate CLI prints UTF-8
|
|
104
|
+
# JSON that contains the first user message, so a GBK decode both corrupted the
|
|
105
|
+
# text and (when a trail byte swallowed a brace) broke ConvertFrom-Json. The
|
|
106
|
+
# script now pins every console stream to UTF-8 without a BOM and decodes node's
|
|
107
|
+
# stdout/stderr as UTF-8 explicitly in Invoke-NodeScript, independent of the
|
|
108
|
+
# system code page.
|
|
109
|
+
$script:Utf8NoBom = [System.Text.UTF8Encoding]::new($false)
|
|
110
|
+
try { [Console]::OutputEncoding = $script:Utf8NoBom } catch { }
|
|
111
|
+
try { [Console]::InputEncoding = $script:Utf8NoBom } catch { }
|
|
112
|
+
$OutputEncoding = $script:Utf8NoBom
|
|
113
|
+
|
|
114
|
+
# ---------------------------------------------------------------------------
|
|
115
|
+
# Small helpers
|
|
116
|
+
# ---------------------------------------------------------------------------
|
|
117
|
+
|
|
118
|
+
function Get-IsoNow {
|
|
119
|
+
return (Get-Date).ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ss.fffZ')
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function Write-Log {
|
|
123
|
+
param([string]$Message)
|
|
124
|
+
if (-not $script:LogPath) { return }
|
|
125
|
+
try {
|
|
126
|
+
$stamp = (Get-Date).ToString('yyyy-MM-dd HH:mm:ss.fff zzz')
|
|
127
|
+
Add-Content -LiteralPath $script:LogPath -Value ("[{0}] {1}" -f $stamp, $Message) -Encoding UTF8
|
|
128
|
+
} catch {
|
|
129
|
+
# Logging must never take the surgery down.
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function Get-Sha256 {
|
|
134
|
+
param([string]$Path)
|
|
135
|
+
return (Get-FileHash -LiteralPath $Path -Algorithm SHA256).Hash.ToLowerInvariant()
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function Resolve-NodeExe {
|
|
139
|
+
if ($NodeExe) {
|
|
140
|
+
if (-not (Test-Path -LiteralPath $NodeExe -PathType Leaf)) {
|
|
141
|
+
throw "node.exe not found: $NodeExe"
|
|
142
|
+
}
|
|
143
|
+
return (Resolve-Path -LiteralPath $NodeExe).Path
|
|
144
|
+
}
|
|
145
|
+
$cmd = Get-Command node.exe -ErrorAction SilentlyContinue
|
|
146
|
+
if ($cmd -and $cmd.Source) { return $cmd.Source }
|
|
147
|
+
if ($env:DSH_NODE_EXE -and (Test-Path -LiteralPath $env:DSH_NODE_EXE -PathType Leaf)) {
|
|
148
|
+
return (Resolve-Path -LiteralPath $env:DSH_NODE_EXE).Path
|
|
149
|
+
}
|
|
150
|
+
$candidate = Join-Path $env:USERPROFILE '.dsh\dsh-runtimes\dsh-primary-runtime\dependencies\node\bin\node.exe'
|
|
151
|
+
if (Test-Path -LiteralPath $candidate -PathType Leaf) {
|
|
152
|
+
return (Resolve-Path -LiteralPath $candidate).Path
|
|
153
|
+
}
|
|
154
|
+
throw 'node.exe not found: pass -NodeExe, put node on PATH, or set DSH_NODE_EXE.'
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
function Resolve-MemoryRoot {
|
|
158
|
+
if ($MemoryRoot) { return [IO.Path]::GetFullPath($MemoryRoot) }
|
|
159
|
+
if ($env:DSH_LONGLIVE_MEMORY_ROOT) { return [IO.Path]::GetFullPath($env:DSH_LONGLIVE_MEMORY_ROOT) }
|
|
160
|
+
if ($env:DSH_MEM) { return [IO.Path]::GetFullPath($env:DSH_MEM) }
|
|
161
|
+
$home = $env:DSH_HOME
|
|
162
|
+
if (-not $home) { $home = Join-Path $env:USERPROFILE '.dsh' }
|
|
163
|
+
return [IO.Path]::GetFullPath((Join-Path $home 'longlive-memory'))
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
function Read-JsonLine {
|
|
167
|
+
param([string]$Text)
|
|
168
|
+
if (-not $Text) { return $null }
|
|
169
|
+
$lines = @($Text -split "`n")
|
|
170
|
+
for ($i = $lines.Count - 1; $i -ge 0; $i--) {
|
|
171
|
+
$trim = $lines[$i].Trim()
|
|
172
|
+
if ($trim.StartsWith('{') -and $trim.EndsWith('}')) {
|
|
173
|
+
try { return ($trim | ConvertFrom-Json) } catch { }
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
return $null
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
function Quote-NativeArg {
|
|
180
|
+
# Windows command-line quoting (the same rules CommandLineToArgvW parses):
|
|
181
|
+
# only quote when needed, double the backslashes that precede an inner quote,
|
|
182
|
+
# and double a trailing run of backslashes before the closing quote.
|
|
183
|
+
param([string]$Value)
|
|
184
|
+
if ([string]::IsNullOrEmpty($Value)) { return '""' }
|
|
185
|
+
if ($Value -notmatch '[\s"]') { return $Value }
|
|
186
|
+
$builder = New-Object System.Text.StringBuilder
|
|
187
|
+
[void]$builder.Append('"')
|
|
188
|
+
$slashes = 0
|
|
189
|
+
foreach ($ch in $Value.ToCharArray()) {
|
|
190
|
+
if ($ch -eq '\') { $slashes += 1; continue }
|
|
191
|
+
if ($ch -eq '"') {
|
|
192
|
+
[void]$builder.Append('\' * ($slashes * 2 + 1))
|
|
193
|
+
[void]$builder.Append('"')
|
|
194
|
+
$slashes = 0
|
|
195
|
+
continue
|
|
196
|
+
}
|
|
197
|
+
if ($slashes -gt 0) { [void]$builder.Append('\' * $slashes); $slashes = 0 }
|
|
198
|
+
[void]$builder.Append($ch)
|
|
199
|
+
}
|
|
200
|
+
if ($slashes -gt 0) { [void]$builder.Append('\' * ($slashes * 2)) }
|
|
201
|
+
[void]$builder.Append('"')
|
|
202
|
+
return $builder.ToString()
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
function Write-RawCapture {
|
|
206
|
+
# Keep the bytes we could not parse as UTF-8 evidence next to surgery.log.
|
|
207
|
+
param([string]$Text, [string]$Kind)
|
|
208
|
+
if (-not $script:LogPath) { return $null }
|
|
209
|
+
try {
|
|
210
|
+
$dir = Split-Path -Parent $script:LogPath
|
|
211
|
+
if (-not (Test-Path -LiteralPath $dir)) { New-Item -ItemType Directory -Path $dir -Force | Out-Null }
|
|
212
|
+
$name = "node-{0}-{1}-{2}.utf8.txt" -f $Kind, $script:SurgeryId, (Get-Random -Minimum 100 -Maximum 1000)
|
|
213
|
+
$path = Join-Path $dir $name
|
|
214
|
+
[IO.File]::WriteAllText($path, $Text, $script:Utf8NoBom)
|
|
215
|
+
return $path
|
|
216
|
+
} catch {
|
|
217
|
+
return $null
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
function Invoke-NodeScript {
|
|
222
|
+
# rc.6 (R4-03): run node through System.Diagnostics.Process and decode both
|
|
223
|
+
# pipes as UTF-8. `& $node ... 2>&1` goes through the console code page
|
|
224
|
+
# (GBK on zh-CN), which is what corrupted the CLI JSON and the receipt text.
|
|
225
|
+
# This path never consults [Console]::OutputEncoding.
|
|
226
|
+
param([string[]]$ArgList)
|
|
227
|
+
$psi = New-Object System.Diagnostics.ProcessStartInfo
|
|
228
|
+
$psi.FileName = $script:NodeExe
|
|
229
|
+
$psi.Arguments = (@($ArgList | ForEach-Object { Quote-NativeArg -Value ([string]$_) }) -join ' ')
|
|
230
|
+
$psi.UseShellExecute = $false
|
|
231
|
+
$psi.CreateNoWindow = $true
|
|
232
|
+
$psi.RedirectStandardOutput = $true
|
|
233
|
+
$psi.RedirectStandardError = $true
|
|
234
|
+
$psi.StandardOutputEncoding = $script:Utf8NoBom
|
|
235
|
+
$psi.StandardErrorEncoding = $script:Utf8NoBom
|
|
236
|
+
$proc = New-Object System.Diagnostics.Process
|
|
237
|
+
$proc.StartInfo = $psi
|
|
238
|
+
[void]$proc.Start()
|
|
239
|
+
# Read both pipes asynchronously: a synchronous stdout read can deadlock when
|
|
240
|
+
# stderr fills its buffer.
|
|
241
|
+
$stdoutTask = $proc.StandardOutput.ReadToEndAsync()
|
|
242
|
+
$stderrTask = $proc.StandardError.ReadToEndAsync()
|
|
243
|
+
if (-not $proc.WaitForExit(900000)) {
|
|
244
|
+
try { $proc.Kill() } catch { }
|
|
245
|
+
throw "node did not exit within 900s: $($psi.FileName) $($psi.Arguments)"
|
|
246
|
+
}
|
|
247
|
+
$stdout = $stdoutTask.Result
|
|
248
|
+
$stderr = $stderrTask.Result
|
|
249
|
+
$code = $proc.ExitCode
|
|
250
|
+
$proc.Dispose()
|
|
251
|
+
$parts = @()
|
|
252
|
+
if ($stdout) { $parts += $stdout }
|
|
253
|
+
if ($stderr) { $parts += $stderr }
|
|
254
|
+
$text = ($parts -join "`n").Trim()
|
|
255
|
+
return @{
|
|
256
|
+
exitCode = $code
|
|
257
|
+
text = $text
|
|
258
|
+
stdout = $stdout
|
|
259
|
+
stderr = $stderr
|
|
260
|
+
json = (Read-JsonLine -Text $text)
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
function Invoke-Inspect {
|
|
265
|
+
param([string]$Path)
|
|
266
|
+
return Invoke-NodeScript -ArgList @($script:InspectScript, $Path)
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
function Get-CutArchivePath {
|
|
270
|
+
# Best effort: truncate-visible writes the removed prefix to
|
|
271
|
+
# "<sessionPath>.archive\<stamp>.jsonl.zstd". When the CLI JSON is unreadable
|
|
272
|
+
# we still want the newest archive created at/after the cut started, for the
|
|
273
|
+
# result and the receipt.
|
|
274
|
+
param([string]$StartedAt)
|
|
275
|
+
try {
|
|
276
|
+
$archiveDir = "$script:SessionPath.archive"
|
|
277
|
+
if (-not (Test-Path -LiteralPath $archiveDir -PathType Container)) { return $null }
|
|
278
|
+
$since = [datetime]::MinValue
|
|
279
|
+
if ($StartedAt) {
|
|
280
|
+
try {
|
|
281
|
+
$since = ([datetime]::Parse(
|
|
282
|
+
$StartedAt,
|
|
283
|
+
[Globalization.CultureInfo]::InvariantCulture,
|
|
284
|
+
[Globalization.DateTimeStyles]::AdjustToUniversal -bor [Globalization.DateTimeStyles]::AssumeUniversal
|
|
285
|
+
)).AddSeconds(-5)
|
|
286
|
+
} catch { }
|
|
287
|
+
}
|
|
288
|
+
$newest = Get-ChildItem -LiteralPath $archiveDir -File -ErrorAction SilentlyContinue |
|
|
289
|
+
Where-Object { $_.LastWriteTimeUtc -ge $since } |
|
|
290
|
+
Sort-Object LastWriteTimeUtc -Descending |
|
|
291
|
+
Select-Object -First 1
|
|
292
|
+
if ($newest) { return $newest.FullName }
|
|
293
|
+
} catch { }
|
|
294
|
+
return $null
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
function Test-CutLanded {
|
|
298
|
+
# rc.6 (R4-03): when the CLI exits 0 but its stdout is not parseable JSON, do
|
|
299
|
+
# NOT call it failed. Prove the cut from independent evidence instead:
|
|
300
|
+
# * the session parses, and its sha equals a fresh Get-FileHash of the file
|
|
301
|
+
# * the sha changed since the pre-cut snapshot
|
|
302
|
+
# * events and messages strictly decreased
|
|
303
|
+
# * the pre-surgery backup still exists and still has the before sha
|
|
304
|
+
# Byte size is recorded for the log but is NOT required: the codec rewrites
|
|
305
|
+
# the session with a fresh header/archive, so a small session can legitimately
|
|
306
|
+
# grow a few bytes even though turns were dropped (seen in the drill: 1456 ->
|
|
307
|
+
# 1509 B with 121 -> 79 events).
|
|
308
|
+
# Only when every required check passes do we record "applied-unparsed".
|
|
309
|
+
param(
|
|
310
|
+
[hashtable]$Before,
|
|
311
|
+
[string]$BackupPath,
|
|
312
|
+
[string]$StartedAt
|
|
313
|
+
)
|
|
314
|
+
$checks = [ordered]@{
|
|
315
|
+
sessionReadable = $false
|
|
316
|
+
shaMatchesDisk = $false
|
|
317
|
+
shaChanged = $false
|
|
318
|
+
bytesDecreased = $false
|
|
319
|
+
eventsDecreased = $false
|
|
320
|
+
messagesDecreased = $false
|
|
321
|
+
backupExists = $false
|
|
322
|
+
backupMatchesBefore = $false
|
|
323
|
+
}
|
|
324
|
+
$inspect = Invoke-Inspect -Path $script:SessionPath
|
|
325
|
+
if (-not $inspect.json -or -not $inspect.json.ok) {
|
|
326
|
+
return @{ ok = $false; reason = "independent read-back failed: $($inspect.text)"; checks = $checks; after = $null; archivePath = $null }
|
|
327
|
+
}
|
|
328
|
+
$checks.sessionReadable = $true
|
|
329
|
+
$after = @{
|
|
330
|
+
bytes = [int64]$inspect.json.bytes
|
|
331
|
+
events = [int64]$inspect.json.events
|
|
332
|
+
messages = [int64]$inspect.json.messages
|
|
333
|
+
sha256 = [string]$inspect.json.sha256
|
|
334
|
+
at = (Get-IsoNow)
|
|
335
|
+
}
|
|
336
|
+
$diskSha = Get-Sha256 -Path $script:SessionPath
|
|
337
|
+
$checks.shaMatchesDisk = ($after.sha256 -eq $diskSha)
|
|
338
|
+
$checks.shaChanged = ($after.sha256 -ne [string]$Before.sha256)
|
|
339
|
+
$checks.bytesDecreased = ($after.bytes -lt [int64]$Before.bytes)
|
|
340
|
+
$checks.eventsDecreased = ($after.events -lt [int64]$Before.events)
|
|
341
|
+
$checks.messagesDecreased = ($after.messages -lt [int64]$Before.messages)
|
|
342
|
+
$checks.backupExists = (Test-Path -LiteralPath $BackupPath -PathType Leaf)
|
|
343
|
+
if ($checks.backupExists) {
|
|
344
|
+
$checks.backupMatchesBefore = ((Get-Sha256 -Path $BackupPath) -eq [string]$Before.sha256)
|
|
345
|
+
}
|
|
346
|
+
$ok = $true
|
|
347
|
+
$failedOn = @()
|
|
348
|
+
$required = @(
|
|
349
|
+
'sessionReadable', 'shaMatchesDisk', 'shaChanged',
|
|
350
|
+
'eventsDecreased', 'messagesDecreased',
|
|
351
|
+
'backupExists', 'backupMatchesBefore'
|
|
352
|
+
)
|
|
353
|
+
foreach ($key in $required) {
|
|
354
|
+
if (-not [bool]$checks[$key]) { $ok = $false; $failedOn += $key }
|
|
355
|
+
}
|
|
356
|
+
$reason = if ($ok) { 'all independent checks passed' } else { "checks failed: $($failedOn -join ',')" }
|
|
357
|
+
return @{
|
|
358
|
+
ok = $ok
|
|
359
|
+
reason = $reason
|
|
360
|
+
checks = $checks
|
|
361
|
+
after = $after
|
|
362
|
+
archivePath = (Get-CutArchivePath -StartedAt $StartedAt)
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
# ---------------------------------------------------------------------------
|
|
367
|
+
# Stage file: one atomic JSON write per transition, plus a history trail.
|
|
368
|
+
# ---------------------------------------------------------------------------
|
|
369
|
+
|
|
370
|
+
function Write-State {
|
|
371
|
+
param(
|
|
372
|
+
[string]$Phase,
|
|
373
|
+
[hashtable]$Patch = @{}
|
|
374
|
+
)
|
|
375
|
+
if (-not $script:State -or $script:State.Count -eq 0) { return }
|
|
376
|
+
$now = Get-IsoNow
|
|
377
|
+
$script:State['phase'] = $Phase
|
|
378
|
+
$script:State['updatedAt'] = $now
|
|
379
|
+
foreach ($key in $Patch.Keys) { $script:State[$key] = $Patch[$key] }
|
|
380
|
+
$history = @()
|
|
381
|
+
if ($script:State.ContainsKey('history') -and $null -ne $script:State['history']) {
|
|
382
|
+
$history = @($script:State['history'])
|
|
383
|
+
}
|
|
384
|
+
$history += @{ phase = $Phase; at = $now }
|
|
385
|
+
$script:State['history'] = $history
|
|
386
|
+
|
|
387
|
+
$json = $script:State | ConvertTo-Json -Depth 20
|
|
388
|
+
$dir = Split-Path -Parent $script:StatePath
|
|
389
|
+
if (-not (Test-Path -LiteralPath $dir)) { New-Item -ItemType Directory -Path $dir -Force | Out-Null }
|
|
390
|
+
$tmp = "$script:StatePath.tmp-$PID"
|
|
391
|
+
[IO.File]::WriteAllText($tmp, $json, (New-Object System.Text.UTF8Encoding($false)))
|
|
392
|
+
Move-Item -LiteralPath $tmp -Destination $script:StatePath -Force
|
|
393
|
+
try {
|
|
394
|
+
$check = Get-Content -LiteralPath $script:StatePath -Raw -Encoding UTF8 -ErrorAction Stop | ConvertFrom-Json
|
|
395
|
+
if ($check.phase -ne $Phase) {
|
|
396
|
+
Write-Log "WARN state read-back phase=$($check.phase) expected=$Phase"
|
|
397
|
+
}
|
|
398
|
+
} catch {
|
|
399
|
+
Write-Log "WARN state read-back failed: $($_.Exception.Message)"
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
function Write-Result {
|
|
404
|
+
param(
|
|
405
|
+
[bool]$Ok,
|
|
406
|
+
[string]$Phase,
|
|
407
|
+
$ErrorInfo = $null
|
|
408
|
+
)
|
|
409
|
+
if (-not $script:ResultPath) { return }
|
|
410
|
+
$payload = @{
|
|
411
|
+
version = 1
|
|
412
|
+
kind = 'longlive-surgery-result'
|
|
413
|
+
surgeryId = $script:SurgeryId
|
|
414
|
+
at = (Get-IsoNow)
|
|
415
|
+
ok = $Ok
|
|
416
|
+
phase = $Phase
|
|
417
|
+
dryRun = [bool]$DryRun
|
|
418
|
+
sessionPath = $script:SessionPath
|
|
419
|
+
memoryRoot = $script:MemoryRoot
|
|
420
|
+
pluginVersion = $script:PluginVersion
|
|
421
|
+
before = $script:State['before']
|
|
422
|
+
backup = $script:State['backup']
|
|
423
|
+
cut = $script:State['cut']
|
|
424
|
+
after = $script:State['after']
|
|
425
|
+
verify = $script:State['verify']
|
|
426
|
+
receipt = $script:State['receipt']
|
|
427
|
+
restart = $script:State['restart']
|
|
428
|
+
statePath = $script:StatePath
|
|
429
|
+
logPath = $script:LogPath
|
|
430
|
+
error = $ErrorInfo
|
|
431
|
+
}
|
|
432
|
+
$json = $payload | ConvertTo-Json -Depth 20
|
|
433
|
+
$dir = Split-Path -Parent $script:ResultPath
|
|
434
|
+
if (-not (Test-Path -LiteralPath $dir)) { New-Item -ItemType Directory -Path $dir -Force | Out-Null }
|
|
435
|
+
$tmp = "$script:ResultPath.tmp-$PID"
|
|
436
|
+
[IO.File]::WriteAllText($tmp, $json, (New-Object System.Text.UTF8Encoding($false)))
|
|
437
|
+
Move-Item -LiteralPath $tmp -Destination $script:ResultPath -Force
|
|
438
|
+
Write-Log "result written: $script:ResultPath ok=$Ok phase=$Phase"
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
function Fail {
|
|
442
|
+
param(
|
|
443
|
+
[int]$Code,
|
|
444
|
+
[string]$Phase,
|
|
445
|
+
[string]$Message,
|
|
446
|
+
[hashtable]$Extra = @{}
|
|
447
|
+
)
|
|
448
|
+
Write-Log "FAIL($Code) [$Phase] $Message"
|
|
449
|
+
$err = @{
|
|
450
|
+
at = (Get-IsoNow)
|
|
451
|
+
phase = $Phase
|
|
452
|
+
message = $Message
|
|
453
|
+
}
|
|
454
|
+
$patch = @{ error = $err }
|
|
455
|
+
foreach ($key in $Extra.Keys) { $patch[$key] = $Extra[$key] }
|
|
456
|
+
try {
|
|
457
|
+
Write-State 'failed' $patch
|
|
458
|
+
} catch {
|
|
459
|
+
Write-Log "WARN could not write failed state: $($_.Exception.Message)"
|
|
460
|
+
}
|
|
461
|
+
try {
|
|
462
|
+
Write-Result $false $Phase $err
|
|
463
|
+
} catch {
|
|
464
|
+
Write-Log "WARN could not write result: $($_.Exception.Message)"
|
|
465
|
+
}
|
|
466
|
+
exit $Code
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
# ---------------------------------------------------------------------------
|
|
470
|
+
# Host process helpers
|
|
471
|
+
# ---------------------------------------------------------------------------
|
|
472
|
+
|
|
473
|
+
function Get-AppProcesses {
|
|
474
|
+
$result = @()
|
|
475
|
+
if (-not $script:AppPath) { return $result }
|
|
476
|
+
$name = [IO.Path]::GetFileNameWithoutExtension($script:AppPath)
|
|
477
|
+
foreach ($p in @(Get-Process -ErrorAction SilentlyContinue)) {
|
|
478
|
+
$path = $null
|
|
479
|
+
try { $path = $p.Path } catch { $path = $null }
|
|
480
|
+
if ($path) {
|
|
481
|
+
if ([string]::Equals($path, $script:AppPath, [StringComparison]::OrdinalIgnoreCase)) {
|
|
482
|
+
$result += $p
|
|
483
|
+
}
|
|
484
|
+
} elseif ($p.ProcessName -eq $name) {
|
|
485
|
+
$result += $p
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
return $result
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
function Close-Host {
|
|
492
|
+
$before = @(Get-AppProcesses)
|
|
493
|
+
$killed = @()
|
|
494
|
+
foreach ($p in $before) {
|
|
495
|
+
try {
|
|
496
|
+
Stop-Process -Id $p.Id -Force -ErrorAction Stop
|
|
497
|
+
$killed += $p.Id
|
|
498
|
+
} catch {
|
|
499
|
+
Write-Log "WARN could not stop pid $($p.Id): $($_.Exception.Message)"
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
$deadline = (Get-Date).AddSeconds(30)
|
|
503
|
+
do {
|
|
504
|
+
Start-Sleep -Milliseconds 300
|
|
505
|
+
$left = @(Get-AppProcesses)
|
|
506
|
+
} while ($left.Count -gt 0 -and (Get-Date) -lt $deadline)
|
|
507
|
+
# Let file handles settle after the last process disappears.
|
|
508
|
+
Start-Sleep -Milliseconds 800
|
|
509
|
+
$left = @(Get-AppProcesses)
|
|
510
|
+
return @{
|
|
511
|
+
ok = ($left.Count -eq 0)
|
|
512
|
+
before = @($before | ForEach-Object { $_.Id })
|
|
513
|
+
killed = $killed
|
|
514
|
+
remaining = @($left | ForEach-Object { $_.Id })
|
|
515
|
+
at = (Get-IsoNow)
|
|
516
|
+
}
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
function Start-Host {
|
|
520
|
+
Start-Process -FilePath $script:AppPath -WorkingDirectory (Split-Path -Parent $script:AppPath) | Out-Null
|
|
521
|
+
$deadline = (Get-Date).AddSeconds(60)
|
|
522
|
+
$procs = @()
|
|
523
|
+
do {
|
|
524
|
+
Start-Sleep -Milliseconds 500
|
|
525
|
+
$procs = @(Get-AppProcesses)
|
|
526
|
+
} while ($procs.Count -eq 0 -and (Get-Date) -lt $deadline)
|
|
527
|
+
return @{
|
|
528
|
+
ok = ($procs.Count -gt 0)
|
|
529
|
+
count = $procs.Count
|
|
530
|
+
pids = @($procs | ForEach-Object { $_.Id })
|
|
531
|
+
at = (Get-IsoNow)
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
function FailWithRestart {
|
|
536
|
+
param(
|
|
537
|
+
[int]$Code,
|
|
538
|
+
[string]$Phase,
|
|
539
|
+
[string]$Message
|
|
540
|
+
)
|
|
541
|
+
if ($script:HostClosed) {
|
|
542
|
+
try {
|
|
543
|
+
$restart = Start-Host
|
|
544
|
+
$script:State['restart'] = $restart
|
|
545
|
+
Write-Log "restart after failure ok=$($restart.ok) count=$($restart.count)"
|
|
546
|
+
} catch {
|
|
547
|
+
Write-Log "WARN restart after failure failed: $($_.Exception.Message)"
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
Fail $Code $Phase $Message @{ restart = $script:State['restart'] }
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
# ---------------------------------------------------------------------------
|
|
554
|
+
# Argument validation (before any state file exists)
|
|
555
|
+
# ---------------------------------------------------------------------------
|
|
556
|
+
|
|
557
|
+
function Write-StderrAndExit {
|
|
558
|
+
param([string]$Message, [int]$Code = 2)
|
|
559
|
+
[Console]::Error.WriteLine($Message)
|
|
560
|
+
exit $Code
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
if (-not (Test-Path -LiteralPath $SessionPath -PathType Leaf)) {
|
|
564
|
+
Write-StderrAndExit "SessionPath not found: $SessionPath" 2
|
|
565
|
+
}
|
|
566
|
+
$script:SessionPath = (Resolve-Path -LiteralPath $SessionPath).Path
|
|
567
|
+
|
|
568
|
+
if ($KeepTurns -lt 1) { Write-StderrAndExit "KeepTurns must be >= 1 (got $KeepTurns)" 2 }
|
|
569
|
+
if ($KeepTokens -lt 1) { Write-StderrAndExit "KeepTokens must be >= 1 (got $KeepTokens)" 2 }
|
|
570
|
+
if ($StartDelaySeconds -lt 0 -or $StartDelaySeconds -gt 86400) {
|
|
571
|
+
Write-StderrAndExit "StartDelaySeconds must be 0..86400 (got $StartDelaySeconds)" 2
|
|
572
|
+
}
|
|
573
|
+
if ($RestartDelaySeconds -lt 0 -or $RestartDelaySeconds -gt 86400) {
|
|
574
|
+
Write-StderrAndExit "RestartDelaySeconds must be 0..86400 (got $RestartDelaySeconds)" 2
|
|
575
|
+
}
|
|
576
|
+
if (-not $DryRun -and $Confirm -ne 'TRUNCATE-VISIBLE') {
|
|
577
|
+
Write-StderrAndExit "Refusing to cut: pass -Confirm TRUNCATE-VISIBLE (or use -DryRun)." 2
|
|
578
|
+
}
|
|
579
|
+
if (-not $DryRun -and -not $AppPath -and $env:DSH_APP_PATH) {
|
|
580
|
+
$AppPath = $env:DSH_APP_PATH
|
|
581
|
+
}
|
|
582
|
+
if (-not $DryRun -and -not $AppPath) {
|
|
583
|
+
Write-StderrAndExit "Refusing to cut: pass -AppPath <dsh host exe> or set DSH_APP_PATH so the host can be restarted." 2
|
|
584
|
+
}
|
|
585
|
+
if ($AppPath) {
|
|
586
|
+
if (-not (Test-Path -LiteralPath $AppPath -PathType Leaf)) {
|
|
587
|
+
Write-StderrAndExit "AppPath not found: $AppPath" 2
|
|
588
|
+
}
|
|
589
|
+
$script:AppPath = (Resolve-Path -LiteralPath $AppPath).Path
|
|
590
|
+
} else {
|
|
591
|
+
$script:AppPath = ''
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
if (-not $DryRun -and -not $AllowOutsideSessions) {
|
|
595
|
+
$sessionsRoot = $null
|
|
596
|
+
if ($env:DSH_HOME) {
|
|
597
|
+
$sessionsRoot = Join-Path $env:DSH_HOME 'sessions'
|
|
598
|
+
} else {
|
|
599
|
+
$sessionsRoot = Join-Path $env:USERPROFILE '.dsh\sessions'
|
|
600
|
+
}
|
|
601
|
+
$rootFull = [IO.Path]::GetFullPath($sessionsRoot)
|
|
602
|
+
if (-not $rootFull.EndsWith('\')) { $rootFull += '\' }
|
|
603
|
+
if (-not $script:SessionPath.StartsWith($rootFull, [StringComparison]::OrdinalIgnoreCase)) {
|
|
604
|
+
Write-StderrAndExit "Refusing: SessionPath is outside the DSH sessions root ($rootFull). Use -DryRun or -AllowOutsideSessions." 2
|
|
605
|
+
}
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
$script:MemoryRoot = Resolve-MemoryRoot
|
|
609
|
+
$script:NodeExe = Resolve-NodeExe
|
|
610
|
+
$script:PluginRoot = Split-Path -Parent $PSScriptRoot
|
|
611
|
+
$script:CliScript = Join-Path $script:PluginRoot 'scripts\truncate-cli.mjs'
|
|
612
|
+
$script:InspectScript = Join-Path $script:PluginRoot 'scripts\surgery-inspect.mjs'
|
|
613
|
+
foreach ($required in @($script:CliScript, $script:InspectScript)) {
|
|
614
|
+
if (-not (Test-Path -LiteralPath $required -PathType Leaf)) {
|
|
615
|
+
Write-StderrAndExit "Plugin file missing: $required" 2
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
$packageJsonPath = Join-Path $script:PluginRoot 'package.json'
|
|
620
|
+
$script:PluginVersion = $null
|
|
621
|
+
if (Test-Path -LiteralPath $packageJsonPath -PathType Leaf) {
|
|
622
|
+
try {
|
|
623
|
+
$script:PluginVersion = (Get-Content -LiteralPath $packageJsonPath -Raw -Encoding UTF8 | ConvertFrom-Json).version
|
|
624
|
+
} catch {
|
|
625
|
+
$script:PluginVersion = $null
|
|
626
|
+
}
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
$script:SurgeryId = (Get-Date).ToString('yyyyMMdd-HHmmss') + '-' + (Get-Random -Minimum 100 -Maximum 1000)
|
|
630
|
+
$script:StartedAt = Get-IsoNow
|
|
631
|
+
$longliveDir = Join-Path $script:MemoryRoot '.longlive'
|
|
632
|
+
$script:StatePath = Join-Path $longliveDir 'surgery-state.json'
|
|
633
|
+
$script:LogPath = Join-Path $longliveDir 'logs\surgery.log'
|
|
634
|
+
if (-not $ResultPath) {
|
|
635
|
+
$ResultPath = Join-Path $longliveDir ("reports\surgery-result-{0}.json" -f $script:SurgeryId)
|
|
636
|
+
}
|
|
637
|
+
$script:ResultPath = [IO.Path]::GetFullPath($ResultPath)
|
|
638
|
+
|
|
639
|
+
foreach ($dir in @($longliveDir, (Join-Path $longliveDir 'logs'), (Join-Path $longliveDir 'reports'), (Split-Path -Parent $script:ResultPath))) {
|
|
640
|
+
if (-not (Test-Path -LiteralPath $dir)) { New-Item -ItemType Directory -Path $dir -Force | Out-Null }
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
$script:HostClosed = $false
|
|
644
|
+
$script:State = @{
|
|
645
|
+
version = 1
|
|
646
|
+
kind = 'longlive-surgery'
|
|
647
|
+
surgeryId = $script:SurgeryId
|
|
648
|
+
phase = 'prepare'
|
|
649
|
+
startedAt = $script:StartedAt
|
|
650
|
+
updatedAt = $script:StartedAt
|
|
651
|
+
pid = $PID
|
|
652
|
+
sessionPath = $script:SessionPath
|
|
653
|
+
sessionId = (Split-Path -Leaf (Split-Path -Parent $script:SessionPath))
|
|
654
|
+
memoryRoot = $script:MemoryRoot
|
|
655
|
+
appPath = $script:AppPath
|
|
656
|
+
keepTurns = $KeepTurns
|
|
657
|
+
keepTokens = $KeepTokens
|
|
658
|
+
startDelaySeconds = $StartDelaySeconds
|
|
659
|
+
restartDelaySeconds = $RestartDelaySeconds
|
|
660
|
+
pluginVersion = $script:PluginVersion
|
|
661
|
+
hostVersion = $env:DSH_HOST_VERSION
|
|
662
|
+
dryRun = [bool]$DryRun
|
|
663
|
+
before = $null
|
|
664
|
+
backup = $null
|
|
665
|
+
cut = $null
|
|
666
|
+
after = $null
|
|
667
|
+
verify = $null
|
|
668
|
+
receipt = $null
|
|
669
|
+
restart = $null
|
|
670
|
+
done = $null
|
|
671
|
+
error = $null
|
|
672
|
+
history = @()
|
|
673
|
+
}
|
|
674
|
+
|
|
675
|
+
Write-Log "start surgeryId=$($script:SurgeryId) dryRun=$([bool]$DryRun) session=$($script:SessionPath) node=$($script:NodeExe)"
|
|
676
|
+
|
|
677
|
+
# ---------------------------------------------------------------------------
|
|
678
|
+
# main
|
|
679
|
+
# ---------------------------------------------------------------------------
|
|
680
|
+
try {
|
|
681
|
+
Write-State 'prepare'
|
|
682
|
+
|
|
683
|
+
$beforeInspect = Invoke-Inspect -Path $script:SessionPath
|
|
684
|
+
if (-not $beforeInspect.json -or -not $beforeInspect.json.ok) {
|
|
685
|
+
$detail = if ($beforeInspect.text) { $beforeInspect.text } else { "exit=$($beforeInspect.exitCode)" }
|
|
686
|
+
Fail 2 'prepare' "Cannot read session before surgery: $detail"
|
|
687
|
+
}
|
|
688
|
+
$before = @{
|
|
689
|
+
bytes = [int64]$beforeInspect.json.bytes
|
|
690
|
+
events = [int64]$beforeInspect.json.events
|
|
691
|
+
messages = [int64]$beforeInspect.json.messages
|
|
692
|
+
sha256 = [string]$beforeInspect.json.sha256
|
|
693
|
+
at = (Get-IsoNow)
|
|
694
|
+
}
|
|
695
|
+
Write-State 'prepare' @{ before = $before }
|
|
696
|
+
Write-Log "before bytes=$($before.bytes) events=$($before.events) messages=$($before.messages) sha=$($before.sha256)"
|
|
697
|
+
|
|
698
|
+
if ($DryRun) {
|
|
699
|
+
$done = @{
|
|
700
|
+
at = (Get-IsoNow)
|
|
701
|
+
outcome = 'dry-run'
|
|
702
|
+
resultPath = $script:ResultPath
|
|
703
|
+
}
|
|
704
|
+
# rc.4 (R3-01): a rehearsal must never write phase "done". The startup check
|
|
705
|
+
# treats done as a real surgery whose backup/receipt is missing and reports
|
|
706
|
+
# BACKUP_MISSING; "dryrun" is a phase of its own and every entry point
|
|
707
|
+
# short-circuits on it.
|
|
708
|
+
Write-State 'dryrun' @{ done = $done }
|
|
709
|
+
Write-Result $true 'dryrun' $null
|
|
710
|
+
Write-Log 'dry run complete; phase=dryrun (not done); no host was closed and no bytes were cut'
|
|
711
|
+
exit 0
|
|
712
|
+
}
|
|
713
|
+
|
|
714
|
+
if ($StartDelaySeconds -gt 0) {
|
|
715
|
+
Write-Log "waiting $StartDelaySeconds s before closing host"
|
|
716
|
+
Start-Sleep -Seconds $StartDelaySeconds
|
|
717
|
+
}
|
|
718
|
+
|
|
719
|
+
$close = Close-Host
|
|
720
|
+
Write-Log "close ok=$($close.ok) killed=$($close.killed -join ',') remaining=$($close.remaining -join ',')"
|
|
721
|
+
if (-not $close.ok) {
|
|
722
|
+
Fail 3 'prepare' "Host did not stop (remaining pids: $($close.remaining -join ','))." @{ close = $close }
|
|
723
|
+
}
|
|
724
|
+
$script:HostClosed = $true
|
|
725
|
+
|
|
726
|
+
# Re-read after the host is dead: this is the exact snapshot the CLI will cut.
|
|
727
|
+
$beforeInspect = Invoke-Inspect -Path $script:SessionPath
|
|
728
|
+
if (-not $beforeInspect.json -or -not $beforeInspect.json.ok) {
|
|
729
|
+
FailWithRestart 4 'cut' "Cannot read session after host close: $($beforeInspect.text)"
|
|
730
|
+
}
|
|
731
|
+
$before = @{
|
|
732
|
+
bytes = [int64]$beforeInspect.json.bytes
|
|
733
|
+
events = [int64]$beforeInspect.json.events
|
|
734
|
+
messages = [int64]$beforeInspect.json.messages
|
|
735
|
+
sha256 = [string]$beforeInspect.json.sha256
|
|
736
|
+
at = (Get-IsoNow)
|
|
737
|
+
}
|
|
738
|
+
Write-State 'prepare' @{ before = $before }
|
|
739
|
+
|
|
740
|
+
$stamp = (Get-Date).ToString('yyyyMMdd-HHmmss')
|
|
741
|
+
$backupPath = "$($script:SessionPath).pre-surgery-$stamp"
|
|
742
|
+
$suffix = 0
|
|
743
|
+
while (Test-Path -LiteralPath $backupPath) {
|
|
744
|
+
$suffix += 1
|
|
745
|
+
$backupPath = "$($script:SessionPath).pre-surgery-$stamp-$suffix"
|
|
746
|
+
}
|
|
747
|
+
try {
|
|
748
|
+
[IO.File]::Copy($script:SessionPath, $backupPath, $false)
|
|
749
|
+
$backupSha = Get-Sha256 -Path $backupPath
|
|
750
|
+
$backupBytes = (Get-Item -LiteralPath $backupPath).Length
|
|
751
|
+
} catch {
|
|
752
|
+
FailWithRestart 4 'backup' "Backup copy failed: $($_.Exception.Message)"
|
|
753
|
+
}
|
|
754
|
+
if ($backupSha -ne $before.sha256) {
|
|
755
|
+
FailWithRestart 4 'backup' "Backup sha mismatch: copy=$backupSha before=$($before.sha256)"
|
|
756
|
+
}
|
|
757
|
+
$script:State['backup'] = @{
|
|
758
|
+
path = $backupPath
|
|
759
|
+
bytes = [int64]$backupBytes
|
|
760
|
+
sha256 = $backupSha
|
|
761
|
+
at = (Get-IsoNow)
|
|
762
|
+
method = 'copy+readback-sha'
|
|
763
|
+
}
|
|
764
|
+
Write-State 'backup'
|
|
765
|
+
Write-Log "backup path=$backupPath bytes=$backupBytes sha=$backupSha"
|
|
766
|
+
|
|
767
|
+
# The cut is now allowed to happen. Write the phase BEFORE invoking the CLI:
|
|
768
|
+
# if the launcher is killed mid-cut, recovery must see phase=cut.
|
|
769
|
+
$script:State['cut'] = @{
|
|
770
|
+
startedAt = (Get-IsoNow)
|
|
771
|
+
before = $before
|
|
772
|
+
backupPath = $backupPath
|
|
773
|
+
cli = $null
|
|
774
|
+
}
|
|
775
|
+
Write-State 'cut'
|
|
776
|
+
Write-Log "cut start keepTurns=$KeepTurns keepTokens=$KeepTokens"
|
|
777
|
+
|
|
778
|
+
$cut = Invoke-NodeScript -ArgList @(
|
|
779
|
+
$script:CliScript,
|
|
780
|
+
'--session', $script:SessionPath,
|
|
781
|
+
'--keep-turns', "$KeepTurns",
|
|
782
|
+
'--keep-tokens', "$KeepTokens",
|
|
783
|
+
'--confirm', 'TRUNCATE-VISIBLE',
|
|
784
|
+
'--memory-root', $script:MemoryRoot
|
|
785
|
+
)
|
|
786
|
+
$script:State['cut']['cli'] = @{
|
|
787
|
+
exitCode = $cut.exitCode
|
|
788
|
+
text = $cut.text
|
|
789
|
+
json = $cut.json
|
|
790
|
+
}
|
|
791
|
+
# Persist the CLI receipt before the independent read-back: if the launcher is
|
|
792
|
+
# killed during verification, recovery still sees the CLI's after snapshot.
|
|
793
|
+
Write-State 'cut' @{ cut = $script:State['cut'] }
|
|
794
|
+
$parsedCli = ($null -ne $cut.json)
|
|
795
|
+
$cliExit = [int]$cut.exitCode
|
|
796
|
+
$unparsed = ($cliExit -eq 0 -and -not $parsedCli)
|
|
797
|
+
$rawPath = $null
|
|
798
|
+
if ($unparsed) {
|
|
799
|
+
# rc.6 (R4-03): exit 0 with unreadable stdout is NOT a failure by itself.
|
|
800
|
+
$rawPath = Write-RawCapture -Text $cut.text -Kind 'cut-stdout-unparsed'
|
|
801
|
+
$script:State['cut']['encoding'] = @{
|
|
802
|
+
unparsed = $true
|
|
803
|
+
capturePath = $rawPath
|
|
804
|
+
at = (Get-IsoNow)
|
|
805
|
+
note = 'truncate-cli exited 0 but stdout was not one parseable JSON line (decoded as UTF-8)'
|
|
806
|
+
}
|
|
807
|
+
Write-State 'cut' @{ cut = $script:State['cut'] }
|
|
808
|
+
Write-Log "cut exit=0 stdout-unparsed capture=$rawPath; verifying independently"
|
|
809
|
+
} else {
|
|
810
|
+
$logJsonOk = if ($parsedCli) { $cut.json.ok } else { $null }
|
|
811
|
+
$logApplied = if ($parsedCli) { $cut.json.applied } else { $null }
|
|
812
|
+
$logStatus = if ($parsedCli) { $cut.json.status } else { $null }
|
|
813
|
+
Write-Log "cut exit=$cliExit jsonOk=$logJsonOk applied=$logApplied status=$logStatus"
|
|
814
|
+
}
|
|
815
|
+
|
|
816
|
+
if ($cliExit -ne 0 -or ($parsedCli -and -not $cut.json.ok)) {
|
|
817
|
+
$message = "truncate-cli failed (exit=$cliExit): $($cut.text)"
|
|
818
|
+
FailWithRestart 4 'cut' $message @{ cut = $script:State['cut'] }
|
|
819
|
+
}
|
|
820
|
+
|
|
821
|
+
if ($unparsed) {
|
|
822
|
+
$recovery = Test-CutLanded -Before $before -BackupPath $backupPath -StartedAt $script:State['cut']['startedAt']
|
|
823
|
+
$script:State['cut']['verification'] = $recovery.checks
|
|
824
|
+
if (-not $recovery.ok) {
|
|
825
|
+
# The cut may or may not have landed. Never report plain "failed" and
|
|
826
|
+
# never retry: park the stage file at needs-attention with the evidence,
|
|
827
|
+
# so a human (or the plugin report) can decide.
|
|
828
|
+
$script:State['cut']['outcome'] = 'unverified'
|
|
829
|
+
$attention = @{
|
|
830
|
+
at = (Get-IsoNow)
|
|
831
|
+
code = 'E_CUT_UNVERIFIED'
|
|
832
|
+
phase = 'verify'
|
|
833
|
+
message = "truncate-cli exited 0 but its JSON was unreadable and independent verification did not confirm the cut: $($recovery.reason)"
|
|
834
|
+
checks = $recovery.checks
|
|
835
|
+
capturePath = $rawPath
|
|
836
|
+
cliText = $cut.text
|
|
837
|
+
}
|
|
838
|
+
Write-State 'needs-attention' @{ cut = $script:State['cut']; needsAttention = $attention }
|
|
839
|
+
Write-Result $false 'needs-attention' $attention
|
|
840
|
+
if ($script:HostClosed) {
|
|
841
|
+
try {
|
|
842
|
+
$script:State['restart'] = Start-Host
|
|
843
|
+
Write-Log "restart after needs-attention ok=$($script:State['restart'].ok)"
|
|
844
|
+
} catch {
|
|
845
|
+
Write-Log "WARN restart after needs-attention failed: $($_.Exception.Message)"
|
|
846
|
+
}
|
|
847
|
+
}
|
|
848
|
+
exit 7
|
|
849
|
+
}
|
|
850
|
+
$after = $recovery.after
|
|
851
|
+
$verify = @{
|
|
852
|
+
ok = $true
|
|
853
|
+
method = 'independent-readback-unparsed'
|
|
854
|
+
sha256 = $after.sha256
|
|
855
|
+
events = $after.events
|
|
856
|
+
messages = $after.messages
|
|
857
|
+
cliUnparsed = $true
|
|
858
|
+
checks = $recovery.checks
|
|
859
|
+
at = (Get-IsoNow)
|
|
860
|
+
}
|
|
861
|
+
$script:State['after'] = $after
|
|
862
|
+
$script:State['verify'] = $verify
|
|
863
|
+
$script:State['cut']['outcome'] = 'applied-unparsed'
|
|
864
|
+
$script:State['cut']['verify'] = $verify
|
|
865
|
+
$script:State['cut']['archivePath'] = $recovery.archivePath
|
|
866
|
+
$script:State['cut']['backupPath'] = $backupPath
|
|
867
|
+
Write-State 'restart' @{ after = $after; verify = $verify; cut = $script:State['cut'] }
|
|
868
|
+
Write-Log "applied-unparsed verified bytes=$($after.bytes) events=$($after.events) messages=$($after.messages) sha=$($after.sha256)"
|
|
869
|
+
} else {
|
|
870
|
+
$needed = $true
|
|
871
|
+
if ($null -ne $cut.json.needed) { $needed = [bool]$cut.json.needed }
|
|
872
|
+
if (-not $needed -or $cut.json.status -eq 'noop' -or -not $cut.json.applied) {
|
|
873
|
+
# Nothing was cut. The host still has to come back up.
|
|
874
|
+
$verify = @{
|
|
875
|
+
ok = $true
|
|
876
|
+
method = 'cli-noop'
|
|
877
|
+
sha256 = $before.sha256
|
|
878
|
+
events = $before.events
|
|
879
|
+
messages = $before.messages
|
|
880
|
+
at = (Get-IsoNow)
|
|
881
|
+
}
|
|
882
|
+
$script:State['verify'] = $verify
|
|
883
|
+
$script:State['after'] = $before
|
|
884
|
+
$script:State['cut']['outcome'] = 'noop'
|
|
885
|
+
Write-State 'restart' @{ verify = $verify; after = $before }
|
|
886
|
+
Write-Log 'cut reported noop; session unchanged'
|
|
887
|
+
} else {
|
|
888
|
+
$afterFromCli = $cut.json.after
|
|
889
|
+
if (-not $afterFromCli -or -not $afterFromCli.sha256) {
|
|
890
|
+
FailWithRestart 5 'verify' "truncate-cli reported applied but no after sha: $($cut.text)" @{ cut = $script:State['cut'] }
|
|
891
|
+
}
|
|
892
|
+
$afterInspect = Invoke-Inspect -Path $script:SessionPath
|
|
893
|
+
if (-not $afterInspect.json -or -not $afterInspect.json.ok) {
|
|
894
|
+
FailWithRestart 5 'verify' "Independent read-back failed: $($afterInspect.text)" @{ cut = $script:State['cut'] }
|
|
895
|
+
}
|
|
896
|
+
$after = @{
|
|
897
|
+
bytes = [int64]$afterInspect.json.bytes
|
|
898
|
+
events = [int64]$afterInspect.json.events
|
|
899
|
+
messages = [int64]$afterInspect.json.messages
|
|
900
|
+
sha256 = [string]$afterInspect.json.sha256
|
|
901
|
+
at = (Get-IsoNow)
|
|
902
|
+
}
|
|
903
|
+
if ($after.sha256 -ne [string]$afterFromCli.sha256) {
|
|
904
|
+
FailWithRestart 5 'verify' "Read-back sha mismatch: disk=$($after.sha256) cli=$($afterFromCli.sha256)" @{ cut = $script:State['cut']; after = $after }
|
|
905
|
+
}
|
|
906
|
+
if ($null -ne $afterFromCli.events -and $after.events -ne [int64]$afterFromCli.events) {
|
|
907
|
+
FailWithRestart 5 'verify' "Read-back event mismatch: disk=$($after.events) cli=$($afterFromCli.events)" @{ cut = $script:State['cut']; after = $after }
|
|
908
|
+
}
|
|
909
|
+
if ($null -ne $afterFromCli.messages -and $after.messages -ne [int64]$afterFromCli.messages) {
|
|
910
|
+
FailWithRestart 5 'verify' "Read-back message mismatch: disk=$($after.messages) cli=$($afterFromCli.messages)" @{ cut = $script:State['cut']; after = $after }
|
|
911
|
+
}
|
|
912
|
+
$verify = @{
|
|
913
|
+
ok = $true
|
|
914
|
+
method = 'independent-readback'
|
|
915
|
+
sha256 = $after.sha256
|
|
916
|
+
events = $after.events
|
|
917
|
+
messages = $after.messages
|
|
918
|
+
cliSha256 = [string]$afterFromCli.sha256
|
|
919
|
+
at = (Get-IsoNow)
|
|
920
|
+
}
|
|
921
|
+
$script:State['after'] = $after
|
|
922
|
+
$script:State['verify'] = $verify
|
|
923
|
+
$script:State['cut']['outcome'] = 'applied'
|
|
924
|
+
$script:State['cut']['verify'] = $verify
|
|
925
|
+
$script:State['cut']['archivePath'] = $cut.json.archivePath
|
|
926
|
+
$script:State['cut']['backupPath'] = $cut.json.backupPath
|
|
927
|
+
Write-State 'restart' @{ after = $after; verify = $verify; cut = $script:State['cut'] }
|
|
928
|
+
Write-Log "after bytes=$($after.bytes) events=$($after.events) messages=$($after.messages) sha=$($after.sha256)"
|
|
929
|
+
}
|
|
930
|
+
}
|
|
931
|
+
|
|
932
|
+
# Receipt (required feature 2): after read-back verification, write the visible
|
|
933
|
+
# surgery receipt into the session body. The host is closed, so this edits the
|
|
934
|
+
# on-disk session file. A failed write must not block restart: the plugin
|
|
935
|
+
# fallback reports it on the next start.
|
|
936
|
+
$receipt = Invoke-NodeScript -ArgList @(
|
|
937
|
+
$script:InspectScript,
|
|
938
|
+
'--write-receipt',
|
|
939
|
+
'--session', $script:SessionPath,
|
|
940
|
+
'--memory-root', $script:MemoryRoot
|
|
941
|
+
)
|
|
942
|
+
if ($receipt.json -and $receipt.json.ok) {
|
|
943
|
+
$script:State['receipt'] = $receipt.json.receipt
|
|
944
|
+
Write-Log "receipt written seq=$($receipt.json.receipt.seq) bytes=$($receipt.json.receipt.after.bytes)"
|
|
945
|
+
} else {
|
|
946
|
+
$reason = if ($receipt.text) { $receipt.text } else { "exit=$($receipt.exitCode)" }
|
|
947
|
+
# rc.6: the receipt script may have written the receipt and only its stdout
|
|
948
|
+
# failed to parse. Read the stage file back (UTF-8) before declaring
|
|
949
|
+
# receipt-pending; the visible receipt is the thing that matters, not stdout.
|
|
950
|
+
$stateAfterReceipt = $null
|
|
951
|
+
try {
|
|
952
|
+
$stateAfterReceipt = Get-Content -LiteralPath $script:StatePath -Raw -Encoding UTF8 | ConvertFrom-Json
|
|
953
|
+
} catch { }
|
|
954
|
+
if ($stateAfterReceipt -and $stateAfterReceipt.receipt -and $stateAfterReceipt.receipt.written -eq $true) {
|
|
955
|
+
$script:State['receipt'] = $stateAfterReceipt.receipt
|
|
956
|
+
Write-Log "receipt recovered from stage file (stdout unparsed) seq=$($script:State['receipt'].seq)"
|
|
957
|
+
} else {
|
|
958
|
+
$script:State['receipt'] = @{ written = $false; at = (Get-IsoNow); via = 'surgery-script'; error = $reason }
|
|
959
|
+
Write-Log "WARN receipt not written: $reason"
|
|
960
|
+
}
|
|
961
|
+
}
|
|
962
|
+
# Flush the receipt evidence before the host comes back up.
|
|
963
|
+
Write-State 'restart' @{ receipt = $script:State['receipt'] }
|
|
964
|
+
|
|
965
|
+
if ($RestartDelaySeconds -gt 0) {
|
|
966
|
+
Write-Log "waiting $RestartDelaySeconds s before restarting host"
|
|
967
|
+
Start-Sleep -Seconds $RestartDelaySeconds
|
|
968
|
+
}
|
|
969
|
+
$restart = Start-Host
|
|
970
|
+
$script:State['restart'] = $restart
|
|
971
|
+
Write-Log "restart ok=$($restart.ok) count=$($restart.count) pids=$($restart.pids -join ',')"
|
|
972
|
+
if (-not $restart.ok) {
|
|
973
|
+
Fail 6 'restart' "Host did not come back within 60s after restart." @{ restart = $restart }
|
|
974
|
+
}
|
|
975
|
+
|
|
976
|
+
$cutOutcome = [string]$script:State['cut']['outcome']
|
|
977
|
+
$outcome = 'applied-and-verified'
|
|
978
|
+
if ($cutOutcome -eq 'noop') { $outcome = 'noop' }
|
|
979
|
+
elseif ($cutOutcome -eq 'applied-unparsed') { $outcome = 'applied-unparsed' }
|
|
980
|
+
$done = @{
|
|
981
|
+
at = (Get-IsoNow)
|
|
982
|
+
outcome = $outcome
|
|
983
|
+
resultPath = $script:ResultPath
|
|
984
|
+
verify = $script:State['verify']
|
|
985
|
+
}
|
|
986
|
+
# R2-02: `done` means *both* the cut and the visible receipt succeeded. If the
|
|
987
|
+
# receipt could not be written, stop at `receipt-pending`; the plugin's
|
|
988
|
+
# startup fallback injects it once and then marks receipt.fallbackInjected.
|
|
989
|
+
$receiptWritten = ($script:State['receipt'].written -eq $true)
|
|
990
|
+
if ($receiptWritten) {
|
|
991
|
+
Write-State 'done' @{ done = $done; restart = $restart }
|
|
992
|
+
Write-Result $true 'done' $null
|
|
993
|
+
Write-Log "done outcome=$outcome"
|
|
994
|
+
} else {
|
|
995
|
+
$receiptPending = @{
|
|
996
|
+
at = (Get-IsoNow)
|
|
997
|
+
outcome = $outcome
|
|
998
|
+
reason = 'receipt-not-written'
|
|
999
|
+
receiptError = $script:State['receipt'].error
|
|
1000
|
+
}
|
|
1001
|
+
Write-State 'receipt-pending' @{ done = $done; restart = $restart; receipt = $script:State['receipt']; receiptPending = $receiptPending }
|
|
1002
|
+
Write-Result $true 'receipt-pending' $null
|
|
1003
|
+
Write-Log "done with receipt pending outcome=$outcome (plugin fallback will inject once)"
|
|
1004
|
+
}
|
|
1005
|
+
exit 0
|
|
1006
|
+
} catch {
|
|
1007
|
+
$message = $_.Exception.Message
|
|
1008
|
+
Write-Log "UNEXPECTED ERROR: $message"
|
|
1009
|
+
if ($script:HostClosed) {
|
|
1010
|
+
try {
|
|
1011
|
+
$restart = Start-Host
|
|
1012
|
+
$script:State['restart'] = $restart
|
|
1013
|
+
Write-Log "restart after error ok=$($restart.ok) count=$($restart.count)"
|
|
1014
|
+
} catch {
|
|
1015
|
+
Write-Log "WARN restart after error failed: $($_.Exception.Message)"
|
|
1016
|
+
}
|
|
1017
|
+
}
|
|
1018
|
+
Fail 1 'failed' $message @{ restart = $script:State['restart'] }
|
|
1019
|
+
}
|