@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,1909 @@
|
|
|
1
|
+
// @local/dsh-longlive — unattended-surgery recovery self-check
|
|
2
|
+
//
|
|
3
|
+
// The unattended launcher (scripts/unattended-surgery.ps1) writes a small,
|
|
4
|
+
// atomic stage file before every irreversible step:
|
|
5
|
+
//
|
|
6
|
+
// <memoryRoot>/.longlive/surgery-state.json
|
|
7
|
+
//
|
|
8
|
+
// If the operator closes the window (or the host/script dies) between two
|
|
9
|
+
// stages, that file survives. On the next activation this module performs a
|
|
10
|
+
// *read-only* post-mortem:
|
|
11
|
+
//
|
|
12
|
+
// * read the state file (one existsSync probe when there is none);
|
|
13
|
+
// * re-read the session and compare its sha256 / byte size / event count /
|
|
14
|
+
// message count with the stage file;
|
|
15
|
+
// * check the pre-surgery backup still exists and its sha256 matches;
|
|
16
|
+
// * compare the plugin (and, when recorded, host) version with the running
|
|
17
|
+
// one;
|
|
18
|
+
// * write exactly one report under .longlive/reports/ and append exactly one
|
|
19
|
+
// audit line.
|
|
20
|
+
//
|
|
21
|
+
// It NEVER truncates, restores, deletes or rewrites the session, and it never
|
|
22
|
+
// edits surgery-state.json. The four verdicts are deliberately boring:
|
|
23
|
+
//
|
|
24
|
+
// applied-and-verified the cut landed and a read-back record proves it
|
|
25
|
+
// applied-unparsed the CLI exited 0 but its stdout could not be parsed
|
|
26
|
+
// (GBK console / broken pipe), and an independent
|
|
27
|
+
// read-back proved the cut landed (rc.6 / R4-03)
|
|
28
|
+
// applied-unverified the cut landed but no read-back record was written
|
|
29
|
+
// aborted-before-cut backup is intact and the session still matches before
|
|
30
|
+
// needs-attention session unreadable/changed in an unexplained way, or
|
|
31
|
+
// the backup is missing/mismatched, or the cut could not
|
|
32
|
+
// be proved after an unparseable CLI exit (rc.6)
|
|
33
|
+
//
|
|
34
|
+
// A `phase: "done"` state file with `receipt.written: true` is a completed
|
|
35
|
+
// receipt: activation does nothing at all. A done state that never recorded a
|
|
36
|
+
// written receipt (an rc.2 state, or a launcher killed after the cut) falls
|
|
37
|
+
// through to the fallback path, which reports it once and marks the injection
|
|
38
|
+
// in the state file so later starts stay quiet. `--recover-report` / `--status`
|
|
39
|
+
// can still read any state on demand.
|
|
40
|
+
//
|
|
41
|
+
// `-DryRun` never reaches any of that. rc.4 writes `phase: "dryrun"` (plus
|
|
42
|
+
// `dryRun: true`) instead of `done`, and every entry point below short-circuits
|
|
43
|
+
// on it: the startup check returns `checked: false, reason: "dryrun"` without
|
|
44
|
+
// reading the session, writing a report or appending an audit line, and
|
|
45
|
+
// `--write-receipt` answers `E_RECEIPT_DRYRUN` instead of treating the state as
|
|
46
|
+
// a broken real surgery. An rc.3 dry-run state (`phase: "done"` with
|
|
47
|
+
// `dryRun: true`) is recognised the same way.
|
|
48
|
+
|
|
49
|
+
import fs from 'node:fs';
|
|
50
|
+
import os from 'node:os';
|
|
51
|
+
import path from 'node:path';
|
|
52
|
+
|
|
53
|
+
import { MESSAGE_TYPES, encodeSession, foldSurface, parseSession, sha256 } from './codec.js';
|
|
54
|
+
import { dshHome } from './home.js';
|
|
55
|
+
import { VERSION } from './version.js';
|
|
56
|
+
import {
|
|
57
|
+
REPORTS_DIR,
|
|
58
|
+
appendAudit,
|
|
59
|
+
ensureDir,
|
|
60
|
+
longliveDir,
|
|
61
|
+
reportsDir,
|
|
62
|
+
sha256File,
|
|
63
|
+
stampToken,
|
|
64
|
+
writeFileAtomic,
|
|
65
|
+
} from './memory/state.js';
|
|
66
|
+
|
|
67
|
+
export const SURGERY_STATE_FILENAME = 'surgery-state.json';
|
|
68
|
+
export const SURGERY_STATE_VERSION = 1;
|
|
69
|
+
export const SURGERY_KIND = 'longlive-surgery';
|
|
70
|
+
|
|
71
|
+
export const CLASSIFICATIONS = Object.freeze({
|
|
72
|
+
APPLIED_VERIFIED: 'applied-and-verified',
|
|
73
|
+
APPLIED_UNPARSED: 'applied-unparsed',
|
|
74
|
+
APPLIED_UNVERIFIED: 'applied-unverified',
|
|
75
|
+
ABORTED_BEFORE_CUT: 'aborted-before-cut',
|
|
76
|
+
NEEDS_ATTENTION: 'needs-attention',
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
export const RECOVERY_REASON = Object.freeze({
|
|
80
|
+
OK_VERIFIED: 'CUT_APPLIED_AND_VERIFIED',
|
|
81
|
+
OK_UNPARSED: 'CUT_APPLIED_UNPARSED_STDOUT',
|
|
82
|
+
OK_UNVERIFIED: 'CUT_APPLIED_WITHOUT_READBACK',
|
|
83
|
+
OK_ABORTED: 'ABORTED_BEFORE_CUT',
|
|
84
|
+
OK_NOOP: 'NOOP_TRUNCATION_NOT_NEEDED',
|
|
85
|
+
OK_DRYRUN: 'DRYRUN_NOT_A_SURGERY',
|
|
86
|
+
NOOP_SESSION_CHANGED: 'NOOP_SESSION_CHANGED',
|
|
87
|
+
STATE_UNREADABLE: 'STATE_UNREADABLE',
|
|
88
|
+
STATE_INVALID: 'STATE_INVALID',
|
|
89
|
+
SESSION_MISSING: 'SESSION_MISSING',
|
|
90
|
+
SESSION_UNREADABLE: 'SESSION_UNREADABLE',
|
|
91
|
+
SESSION_SHA_MISMATCH: 'SESSION_SHA_MISMATCH',
|
|
92
|
+
SESSION_SIZE_MISMATCH: 'SESSION_SIZE_MISMATCH',
|
|
93
|
+
SESSION_COUNTS_MISMATCH: 'SESSION_COUNTS_MISMATCH',
|
|
94
|
+
CUT_RESULT_MISSING: 'CUT_RESULT_MISSING',
|
|
95
|
+
SESSION_CHANGED_BEFORE_CUT: 'SESSION_CHANGED_BEFORE_CUT',
|
|
96
|
+
BACKUP_MISSING: 'BACKUP_MISSING',
|
|
97
|
+
BACKUP_SHA_MISMATCH: 'BACKUP_SHA_MISMATCH',
|
|
98
|
+
BACKUP_UNREADABLE: 'BACKUP_UNREADABLE',
|
|
99
|
+
// rc.6: the CLI exited 0 but printed nothing parseable, and the independent
|
|
100
|
+
// read-back could not prove the cut either. This is the error code the
|
|
101
|
+
// executor writes into needsAttention.code and the report echoes back.
|
|
102
|
+
CUT_UNVERIFIED: 'E_CUT_UNVERIFIED',
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
const PHASES = new Set(['prepare', 'backup', 'cut', 'restart', 'receipt-pending', 'done', 'failed', 'dryrun', 'needs-attention']);
|
|
106
|
+
|
|
107
|
+
// R3-04: `phase` and `sessionId` come from a JSON file that an attacker (or a
|
|
108
|
+
// broken launcher) can edit, and they used to be interpolated into conversation
|
|
109
|
+
// text verbatim. Only the fixed phase enum and a [a-z0-9-] token may be echoed
|
|
110
|
+
// (a legal session id in full, per R4-02); everything else is replaced character
|
|
111
|
+
// by character, so a value like `..\..\<user-dir>\\x` can never look like a path in
|
|
112
|
+
// the receipt.
|
|
113
|
+
const SAFE_TOKEN_RE = /^[a-z0-9-]+$/;
|
|
114
|
+
|
|
115
|
+
export function sanitizePhase(value) {
|
|
116
|
+
const text = asText(value);
|
|
117
|
+
if (!text) return '-';
|
|
118
|
+
const lower = text.toLowerCase();
|
|
119
|
+
if (PHASES.has(lower)) return lower;
|
|
120
|
+
return '[invalid]';
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
export function sanitizeSessionId(value, maxLength = 8) {
|
|
124
|
+
const text = asText(value);
|
|
125
|
+
if (!text) return null;
|
|
126
|
+
const base = SAFE_TOKEN_RE.test(text) ? text : text.toLowerCase().replace(/[^a-z0-9-]/g, '?');
|
|
127
|
+
return base.slice(0, maxLength) || null;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* R4-02: the host already constrains a session id to `[a-z0-9-]`, and operators
|
|
132
|
+
* match receipts against the real id (UUIDs are 36 characters). Echo a legal id
|
|
133
|
+
* in full. Only a value that fails the whitelist is sanitised — and only that
|
|
134
|
+
* faulty value is cut to the short display budget.
|
|
135
|
+
*/
|
|
136
|
+
export function displaySessionId(value) {
|
|
137
|
+
const text = asText(value);
|
|
138
|
+
if (!text) return null;
|
|
139
|
+
if (SAFE_TOKEN_RE.test(text)) return text;
|
|
140
|
+
return sanitizeSessionId(text);
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** Keep a token safe for a file name and for one audit/log line. */
|
|
144
|
+
function sanitizeFileToken(value) {
|
|
145
|
+
const text = asText(value) ?? 'unknown';
|
|
146
|
+
const replaced = text.replace(/[^A-Za-z0-9._-]+/g, '-').replace(/^[-.]+/, '');
|
|
147
|
+
return (replaced || 'unknown').slice(0, 80);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
export function surgeryStatePath(memoryRoot) {
|
|
151
|
+
return path.join(longliveDir(memoryRoot), SURGERY_STATE_FILENAME);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
export function recoveryReportPath(memoryRoot, now = new Date()) {
|
|
155
|
+
const dir = reportsDir(memoryRoot);
|
|
156
|
+
const base = path.join(dir, `surgery-recovery-${stampToken(now)}`);
|
|
157
|
+
let file = `${base}.json`;
|
|
158
|
+
// Two activations in the same millisecond are unlikely but not impossible.
|
|
159
|
+
// Never overwrite an earlier report: each start earns its own evidence file.
|
|
160
|
+
for (let suffix = 2; fs.existsSync(file); suffix += 1) file = `${base}-${suffix}.json`;
|
|
161
|
+
return file;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
function asText(value) {
|
|
165
|
+
return typeof value === 'string' && value.trim() !== '' ? value : null;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
function versionOf(value) {
|
|
169
|
+
if (typeof value === 'string' && value.trim() !== '') return value.trim();
|
|
170
|
+
if (value && typeof value === 'object' && typeof value.version === 'string' && value.version.trim() !== '') {
|
|
171
|
+
return value.version.trim();
|
|
172
|
+
}
|
|
173
|
+
return null;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
function countOf(value) {
|
|
177
|
+
return Number.isInteger(value) && value >= 0 ? value : null;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
function messageCount(events) {
|
|
181
|
+
try {
|
|
182
|
+
return foldSurface(events).filter((node) => MESSAGE_TYPES.has(node.type)).length;
|
|
183
|
+
} catch {
|
|
184
|
+
return null;
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/** Read the stage file without throwing. Missing is a normal, zero-cost state. */
|
|
189
|
+
export function readSurgeryState(memoryRoot) {
|
|
190
|
+
const file = surgeryStatePath(memoryRoot);
|
|
191
|
+
let exists = false;
|
|
192
|
+
try {
|
|
193
|
+
exists = fs.existsSync(file);
|
|
194
|
+
} catch {
|
|
195
|
+
exists = false;
|
|
196
|
+
}
|
|
197
|
+
if (!exists) return { exists: false, path: file, state: null, error: null };
|
|
198
|
+
let text;
|
|
199
|
+
try {
|
|
200
|
+
text = fs.readFileSync(file, 'utf8');
|
|
201
|
+
} catch (error) {
|
|
202
|
+
return {
|
|
203
|
+
exists: true,
|
|
204
|
+
path: file,
|
|
205
|
+
state: null,
|
|
206
|
+
error: { code: 'SURGERY_STATE_UNREADABLE', message: `${file}: ${error?.code ?? error?.message ?? error}` },
|
|
207
|
+
};
|
|
208
|
+
}
|
|
209
|
+
let parsed;
|
|
210
|
+
try {
|
|
211
|
+
parsed = JSON.parse(text);
|
|
212
|
+
} catch (error) {
|
|
213
|
+
return {
|
|
214
|
+
exists: true,
|
|
215
|
+
path: file,
|
|
216
|
+
state: null,
|
|
217
|
+
error: { code: 'SURGERY_STATE_CORRUPT', message: `${file}: ${error?.message ?? error}` },
|
|
218
|
+
};
|
|
219
|
+
}
|
|
220
|
+
if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
|
|
221
|
+
return {
|
|
222
|
+
exists: true,
|
|
223
|
+
path: file,
|
|
224
|
+
state: null,
|
|
225
|
+
error: { code: 'SURGERY_STATE_CORRUPT', message: `${file}: state must be a JSON object` },
|
|
226
|
+
};
|
|
227
|
+
}
|
|
228
|
+
return { exists: true, path: file, state: parsed, error: null };
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
function snapshotFromState(state) {
|
|
232
|
+
// A written in-conversation receipt moves the expected snapshot forward: the
|
|
233
|
+
// session now legitimately carries one extra user/message event.
|
|
234
|
+
const receiptSnapshot = state?.receipt?.written === true ? state?.receipt?.after : null;
|
|
235
|
+
const candidates = [
|
|
236
|
+
['receipt', receiptSnapshot],
|
|
237
|
+
['after', state?.after],
|
|
238
|
+
['after', state?.cut?.after],
|
|
239
|
+
['after', state?.cut?.cli?.after],
|
|
240
|
+
['after', state?.cut?.cli?.json?.after],
|
|
241
|
+
['before', state?.before],
|
|
242
|
+
];
|
|
243
|
+
for (const [kind, value] of candidates) {
|
|
244
|
+
if (value && typeof value === 'object' && asText(value.sha256)) {
|
|
245
|
+
return { kind, snapshot: value };
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
return { kind: null, snapshot: null };
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
function readBackRecorded(state) {
|
|
252
|
+
const flags = [
|
|
253
|
+
state?.cut?.verify?.ok,
|
|
254
|
+
state?.cut?.readBack?.ok,
|
|
255
|
+
state?.verify?.ok,
|
|
256
|
+
state?.after?.verified,
|
|
257
|
+
];
|
|
258
|
+
return flags.some((value) => value === true);
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
function sessionInfo(sessionPath) {
|
|
262
|
+
const info = {
|
|
263
|
+
exists: false,
|
|
264
|
+
readable: false,
|
|
265
|
+
bytes: null,
|
|
266
|
+
sha256: null,
|
|
267
|
+
events: null,
|
|
268
|
+
messages: null,
|
|
269
|
+
error: null,
|
|
270
|
+
};
|
|
271
|
+
if (!asText(sessionPath)) {
|
|
272
|
+
info.error = { code: 'SESSION_PATH_MISSING', message: 'state 里没有 sessionPath' };
|
|
273
|
+
return info;
|
|
274
|
+
}
|
|
275
|
+
let stat;
|
|
276
|
+
try {
|
|
277
|
+
stat = fs.statSync(sessionPath);
|
|
278
|
+
} catch (error) {
|
|
279
|
+
info.error = { code: 'SESSION_MISSING', message: `${sessionPath}: ${error?.code ?? error?.message ?? error}` };
|
|
280
|
+
return info;
|
|
281
|
+
}
|
|
282
|
+
if (!stat.isFile()) {
|
|
283
|
+
info.error = { code: 'SESSION_NOT_A_FILE', message: `${sessionPath}: not a regular file` };
|
|
284
|
+
return info;
|
|
285
|
+
}
|
|
286
|
+
info.exists = true;
|
|
287
|
+
info.bytes = stat.size;
|
|
288
|
+
let buf;
|
|
289
|
+
try {
|
|
290
|
+
buf = fs.readFileSync(sessionPath);
|
|
291
|
+
} catch (error) {
|
|
292
|
+
info.error = { code: 'SESSION_UNREADABLE', message: `${sessionPath}: ${error?.code ?? error?.message ?? error}` };
|
|
293
|
+
return info;
|
|
294
|
+
}
|
|
295
|
+
info.sha256 = sha256(buf);
|
|
296
|
+
try {
|
|
297
|
+
const parsed = parseSession(buf);
|
|
298
|
+
info.readable = true;
|
|
299
|
+
info.events = parsed.events.length;
|
|
300
|
+
info.messages = messageCount(parsed.events);
|
|
301
|
+
} catch (error) {
|
|
302
|
+
info.error = { code: 'SESSION_UNREADABLE', message: `${sessionPath}: ${error?.message ?? error}` };
|
|
303
|
+
}
|
|
304
|
+
return info;
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
function backupInfo(state) {
|
|
308
|
+
const info = { path: asText(state?.backup?.path), exists: false, sha256: null, expected: null, error: null };
|
|
309
|
+
if (!info.path) {
|
|
310
|
+
info.error = { code: 'BACKUP_NOT_RECORDED', message: 'state 里没有 backup.path' };
|
|
311
|
+
return info;
|
|
312
|
+
}
|
|
313
|
+
info.expected = asText(state?.backup?.sha256);
|
|
314
|
+
try {
|
|
315
|
+
const stat = fs.statSync(info.path);
|
|
316
|
+
if (!stat.isFile()) {
|
|
317
|
+
info.error = { code: 'BACKUP_MISSING', message: `${info.path}: not a regular file` };
|
|
318
|
+
return info;
|
|
319
|
+
}
|
|
320
|
+
info.exists = true;
|
|
321
|
+
} catch (error) {
|
|
322
|
+
info.error = { code: 'BACKUP_MISSING', message: `${info.path}: ${error?.code ?? error?.message ?? error}` };
|
|
323
|
+
return info;
|
|
324
|
+
}
|
|
325
|
+
try {
|
|
326
|
+
info.sha256 = sha256File(info.path);
|
|
327
|
+
} catch (error) {
|
|
328
|
+
info.error = { code: 'BACKUP_UNREADABLE', message: `${info.path}: ${error?.code ?? error?.message ?? error}` };
|
|
329
|
+
}
|
|
330
|
+
return info;
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
function emptyReport({ memoryRoot, statePath, now, loadedVersion, loadedHostVersion, stateRead }) {
|
|
334
|
+
return {
|
|
335
|
+
version: 1,
|
|
336
|
+
kind: 'surgery-recovery',
|
|
337
|
+
at: new Date(now).toISOString(),
|
|
338
|
+
memoryRoot,
|
|
339
|
+
statePath,
|
|
340
|
+
surgeryId: null,
|
|
341
|
+
statePhase: null,
|
|
342
|
+
stateError: stateRead?.error ?? null,
|
|
343
|
+
classification: CLASSIFICATIONS.NEEDS_ATTENTION,
|
|
344
|
+
reasonCode: RECOVERY_REASON.STATE_UNREADABLE,
|
|
345
|
+
ok: false,
|
|
346
|
+
checks: {},
|
|
347
|
+
recommendation: '',
|
|
348
|
+
actions: [],
|
|
349
|
+
evidence: {},
|
|
350
|
+
loadedVersion: versionOf(loadedVersion),
|
|
351
|
+
loadedHostVersion: versionOf(loadedHostVersion),
|
|
352
|
+
};
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
function verdict(report, classification, reasonCode) {
|
|
356
|
+
report.classification = classification;
|
|
357
|
+
report.reasonCode = reasonCode;
|
|
358
|
+
report.ok = classification !== CLASSIFICATIONS.NEEDS_ATTENTION;
|
|
359
|
+
return report;
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
/**
|
|
363
|
+
* Build (but do not write) the recovery verdict for one stage file.
|
|
364
|
+
*
|
|
365
|
+
* Pure with respect to project state: it reads the session, backup and state
|
|
366
|
+
* file, and returns a report object. Writing is a separate, explicit step.
|
|
367
|
+
*/
|
|
368
|
+
export function buildRecoveryReport(options = {}) {
|
|
369
|
+
const {
|
|
370
|
+
memoryRoot,
|
|
371
|
+
now = new Date(),
|
|
372
|
+
loadedVersion = VERSION,
|
|
373
|
+
loadedHostVersion = null,
|
|
374
|
+
stateRead = readSurgeryState(memoryRoot),
|
|
375
|
+
statePath = stateRead?.path ?? surgeryStatePath(memoryRoot),
|
|
376
|
+
} = options;
|
|
377
|
+
|
|
378
|
+
const report = emptyReport({ memoryRoot, statePath, now, loadedVersion, loadedHostVersion, stateRead });
|
|
379
|
+
|
|
380
|
+
if (!stateRead?.exists) {
|
|
381
|
+
report.reasonCode = 'NO_STATE';
|
|
382
|
+
report.summary = '没有发现手术状态文件:上次没有跑过无人值守手术(或状态已被清理)。';
|
|
383
|
+
return report;
|
|
384
|
+
}
|
|
385
|
+
if (stateRead.error || !stateRead.state) {
|
|
386
|
+
report.stateError = stateRead.error ?? { code: 'SURGERY_STATE_CORRUPT', message: 'state is empty' };
|
|
387
|
+
report.recommendation =
|
|
388
|
+
'手术状态文件读不出来,无法判断上次手术停在哪一步。先看 .longlive/logs/surgery.log 的最后几行,' +
|
|
389
|
+
'再人工核对会话文件的 sha256 与旁边的备份;确认之前不要重剪。';
|
|
390
|
+
report.actions = [
|
|
391
|
+
`查看 ${report.statePath}`,
|
|
392
|
+
'查看 .longlive/logs/surgery.log 的末尾',
|
|
393
|
+
'会话文件与备份都在原位时,可把 state 移到别处后重跑手术',
|
|
394
|
+
];
|
|
395
|
+
return report;
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
const state = stateRead.state;
|
|
399
|
+
const phase = asText(state.phase);
|
|
400
|
+
const checks = {
|
|
401
|
+
stateReadable: true,
|
|
402
|
+
stateKind: state.kind ?? null,
|
|
403
|
+
stateVersion: state.version ?? null,
|
|
404
|
+
phase,
|
|
405
|
+
phaseKnown: phase != null && PHASES.has(phase),
|
|
406
|
+
sessionId: asText(state.sessionId),
|
|
407
|
+
sessionPath: asText(state.sessionPath),
|
|
408
|
+
expectedKind: null,
|
|
409
|
+
expectedSha256: null,
|
|
410
|
+
expectedBytes: null,
|
|
411
|
+
expectedEvents: null,
|
|
412
|
+
expectedMessages: null,
|
|
413
|
+
cutOutcome: asText(state?.cut?.outcome) ?? asText(state?.done?.outcome),
|
|
414
|
+
sessionExists: false,
|
|
415
|
+
sessionReadable: false,
|
|
416
|
+
sessionBytes: null,
|
|
417
|
+
sessionSha256: null,
|
|
418
|
+
sessionEvents: null,
|
|
419
|
+
sessionMessages: null,
|
|
420
|
+
shaMatch: null,
|
|
421
|
+
beforeBytes: countOf(state?.before?.bytes),
|
|
422
|
+
beforeEvents: countOf(state?.before?.events),
|
|
423
|
+
beforeMessages: countOf(state?.before?.messages),
|
|
424
|
+
beforeSha256: asText(state?.before?.sha256),
|
|
425
|
+
sizeMatch: null,
|
|
426
|
+
countsMatch: null,
|
|
427
|
+
backupPath: asText(state?.backup?.path),
|
|
428
|
+
backupExists: false,
|
|
429
|
+
backupExpectedSha256: asText(state?.backup?.sha256),
|
|
430
|
+
backupSha256: null,
|
|
431
|
+
backupShaMatch: null,
|
|
432
|
+
readBackRecorded: readBackRecorded(state),
|
|
433
|
+
receiptWritten: state?.receipt?.written === true,
|
|
434
|
+
receiptSeq: countOf(state?.receipt?.seq),
|
|
435
|
+
receiptAt: asText(state?.receipt?.at),
|
|
436
|
+
receiptEventId: asText(state?.receipt?.eventId),
|
|
437
|
+
versionRecorded: versionOf(state.pluginVersion),
|
|
438
|
+
versionLoaded: versionOf(loadedVersion),
|
|
439
|
+
versionMatch: null,
|
|
440
|
+
hostVersionRecorded: versionOf(state.hostVersion),
|
|
441
|
+
hostVersionLoaded: versionOf(loadedHostVersion),
|
|
442
|
+
hostVersionMatch: null,
|
|
443
|
+
};
|
|
444
|
+
report.checks = checks;
|
|
445
|
+
report.surgeryId = asText(state.surgeryId);
|
|
446
|
+
report.sessionId = asText(state.sessionId);
|
|
447
|
+
report.statePhase = phase;
|
|
448
|
+
report.startedAt = asText(state.startedAt);
|
|
449
|
+
report.updatedAt = asText(state.updatedAt);
|
|
450
|
+
report.dryRun = state.dryRun === true || phase === 'dryrun';
|
|
451
|
+
// R2-02: a done state is only truly finished when the receipt was written.
|
|
452
|
+
// The fallback path reports it once; the marker makes later starts silent.
|
|
453
|
+
// A dry run is not a surgery at all: it never needs a receipt.
|
|
454
|
+
report.receiptFallbackNeeded = phase === 'done' && report.dryRun !== true && checks.receiptWritten !== true;
|
|
455
|
+
report.receiptFallbackInjected = state?.receipt?.fallbackInjected === true;
|
|
456
|
+
|
|
457
|
+
// R3-01: a dry run is a rehearsal, not a surgery. It has no backup and no
|
|
458
|
+
// after-snapshot by design, so none of the real checks below may run against
|
|
459
|
+
// it — otherwise a rehearsal is reported as BACKUP_MISSING / needs-attention
|
|
460
|
+
// and the operator is told not to re-cut. Return the boring verdict instead.
|
|
461
|
+
if (report.dryRun || phase === 'dryrun') {
|
|
462
|
+
report.dryRun = true;
|
|
463
|
+
verdict(report, CLASSIFICATIONS.ABORTED_BEFORE_CUT, RECOVERY_REASON.OK_DRYRUN);
|
|
464
|
+
report.recommendation =
|
|
465
|
+
'上次是 -DryRun 演练:只校验了参数并记了手术前快照,没有关闭宿主、没有剪切任何字节,也没有手术回执。' +
|
|
466
|
+
'这不是失败,不需要处理;要真正截断时去掉 -DryRun 重跑即可。';
|
|
467
|
+
report.actions = ['无需操作', '要真正截断时去掉 -DryRun 重跑'];
|
|
468
|
+
return report;
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
// rc.6 / R4-03: the executor now has a distinct terminal state for "the CLI
|
|
472
|
+
// exited 0 but printed unparseable stdout, and the independent read-back did
|
|
473
|
+
// NOT prove the cut". It must not be mistaken for an ordinary failed run:
|
|
474
|
+
// the report answers needs-attention with the executor's own error code, and
|
|
475
|
+
// the operator is told to check the files instead of re-cutting.
|
|
476
|
+
if (phase === 'needs-attention' || (state.needsAttention && typeof state.needsAttention === 'object')) {
|
|
477
|
+
const info = state.needsAttention ?? {};
|
|
478
|
+
const code = asText(info.code) ?? RECOVERY_REASON.CUT_UNVERIFIED;
|
|
479
|
+
checks.needsAttentionCode = code;
|
|
480
|
+
checks.needsAttentionPhase = asText(info.phase);
|
|
481
|
+
checks.needsAttentionMessage = asText(info.message);
|
|
482
|
+
checks.needsAttentionChecks = info.checks ?? null;
|
|
483
|
+
verdict(report, CLASSIFICATIONS.NEEDS_ATTENTION, code);
|
|
484
|
+
report.recommendation =
|
|
485
|
+
'剪切结果没能确认:CLI 输出读不出来,独立读回核验也没有通过。先不要重剪,' +
|
|
486
|
+
'核对会话文件与手术前备份的大小和 sha256,再看日志里的原始输出。';
|
|
487
|
+
report.actions = [
|
|
488
|
+
'核对会话文件与 .pre-surgery 备份的大小、sha256',
|
|
489
|
+
'查看 .longlive/logs/surgery.log 与同目录 node-*.utf8.txt 的原始输出',
|
|
490
|
+
'确认会话完整后,把 state 里的 needsAttention 清掉再重跑',
|
|
491
|
+
];
|
|
492
|
+
return report;
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
if (checks.versionRecorded && checks.versionLoaded) {
|
|
496
|
+
checks.versionMatch = checks.versionRecorded === checks.versionLoaded;
|
|
497
|
+
}
|
|
498
|
+
if (checks.hostVersionRecorded && checks.hostVersionLoaded) {
|
|
499
|
+
checks.hostVersionMatch = checks.hostVersionRecorded === checks.hostVersionLoaded;
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
const expected = snapshotFromState(state);
|
|
503
|
+
checks.expectedKind = expected.kind;
|
|
504
|
+
if (expected.snapshot) {
|
|
505
|
+
checks.expectedSha256 = asText(expected.snapshot.sha256);
|
|
506
|
+
checks.expectedBytes = countOf(expected.snapshot.bytes);
|
|
507
|
+
checks.expectedEvents = countOf(expected.snapshot.events);
|
|
508
|
+
checks.expectedMessages = countOf(expected.snapshot.messages);
|
|
509
|
+
}
|
|
510
|
+
report.evidence = {
|
|
511
|
+
sessionPath: checks.sessionPath,
|
|
512
|
+
expectedKind: checks.expectedKind,
|
|
513
|
+
expectedSha256: checks.expectedSha256,
|
|
514
|
+
backupPath: checks.backupPath,
|
|
515
|
+
readBackRecorded: checks.readBackRecorded,
|
|
516
|
+
};
|
|
517
|
+
|
|
518
|
+
if (!checks.phaseKnown) {
|
|
519
|
+
report.reasonCode = RECOVERY_REASON.STATE_INVALID;
|
|
520
|
+
report.recommendation =
|
|
521
|
+
`手术状态文件里的 phase=${JSON.stringify(phase)} 不是已知阶段(prepare/backup/cut/restart/receipt-pending/done/failed/dryrun)。` +
|
|
522
|
+
'先人工核对会话文件的 sha256 和备份,再决定是否重跑;不要自动重剪。';
|
|
523
|
+
report.actions = ['核对 state 文件是否被手工改过', '核对会话文件与备份的 sha256'];
|
|
524
|
+
return report;
|
|
525
|
+
}
|
|
526
|
+
if (!checks.sessionPath) {
|
|
527
|
+
report.reasonCode = RECOVERY_REASON.STATE_INVALID;
|
|
528
|
+
report.recommendation = '手术状态文件里没有 sessionPath,无法核对会话;先人工确认目标是哪个会话文件。';
|
|
529
|
+
report.actions = ['补看 .longlive/logs/surgery.log 里的 session= 行'];
|
|
530
|
+
return report;
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
const session = sessionInfo(checks.sessionPath);
|
|
534
|
+
Object.assign(checks, {
|
|
535
|
+
sessionExists: session.exists,
|
|
536
|
+
sessionReadable: session.readable,
|
|
537
|
+
sessionBytes: session.bytes,
|
|
538
|
+
sessionSha256: session.sha256,
|
|
539
|
+
sessionEvents: session.events,
|
|
540
|
+
sessionMessages: session.messages,
|
|
541
|
+
});
|
|
542
|
+
report.evidence.sessionBytes = session.bytes;
|
|
543
|
+
report.evidence.sessionSha256 = session.sha256;
|
|
544
|
+
report.evidence.sessionEvents = session.events;
|
|
545
|
+
report.evidence.sessionMessages = session.messages;
|
|
546
|
+
if (session.error) report.evidence.sessionError = session.error;
|
|
547
|
+
|
|
548
|
+
if (!session.exists) {
|
|
549
|
+
report.reasonCode = RECOVERY_REASON.SESSION_MISSING;
|
|
550
|
+
report.recommendation =
|
|
551
|
+
`会话文件 ${checks.sessionPath} 不在了。手术不会删会话,这通常说明它被挪走/改名,或 state 已经过期。` +
|
|
552
|
+
'先找到会话文件和它的备份,再决定下一步;不要重剪。';
|
|
553
|
+
report.actions = [`确认 ${checks.sessionPath} 是否被移动`, `确认备份 ${checks.backupPath ?? '(未记录)'} 是否还在`];
|
|
554
|
+
return report;
|
|
555
|
+
}
|
|
556
|
+
if (!session.readable) {
|
|
557
|
+
report.reasonCode = RECOVERY_REASON.SESSION_UNREADABLE;
|
|
558
|
+
report.recommendation =
|
|
559
|
+
'会话文件存在,但解析不了(不是合法的 v4 会话日志,或写坏了)。不要再跑任何写操作;' +
|
|
560
|
+
'先用备份和旁边同名的 .bak-* 做只读比对,必要时人工恢复。';
|
|
561
|
+
report.actions = ['对会话文件做一份只读副本', '用 pre-surgery 备份比对大小与 sha256', '确认损坏前不要重剪'];
|
|
562
|
+
return report;
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
if (checks.expectedSha256) {
|
|
566
|
+
checks.shaMatch = session.sha256 === checks.expectedSha256;
|
|
567
|
+
report.evidence.expectedBytes = checks.expectedBytes;
|
|
568
|
+
report.evidence.expectedEvents = checks.expectedEvents;
|
|
569
|
+
report.evidence.expectedMessages = checks.expectedMessages;
|
|
570
|
+
}
|
|
571
|
+
if (checks.expectedBytes != null) checks.sizeMatch = session.bytes === checks.expectedBytes;
|
|
572
|
+
if (checks.expectedEvents != null) checks.eventsMatch = session.events === checks.expectedEvents;
|
|
573
|
+
if (checks.expectedMessages != null) checks.messagesMatch = session.messages === checks.expectedMessages;
|
|
574
|
+
if (checks.expectedEvents == null && checks.expectedMessages == null) {
|
|
575
|
+
checks.countsMatch = null;
|
|
576
|
+
} else {
|
|
577
|
+
checks.countsMatch =
|
|
578
|
+
(checks.expectedEvents == null || checks.eventsMatch === true) &&
|
|
579
|
+
(checks.expectedMessages == null || checks.messagesMatch === true);
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
// Backup is required from the moment the launcher starts copying it. In the
|
|
583
|
+
// `prepare` stage it may legitimately not exist yet.
|
|
584
|
+
const backup = backupInfo(state);
|
|
585
|
+
Object.assign(checks, {
|
|
586
|
+
backupExists: backup.exists,
|
|
587
|
+
backupSha256: backup.sha256,
|
|
588
|
+
});
|
|
589
|
+
if (backup.error) report.evidence.backupError = backup.error;
|
|
590
|
+
if (backup.exists && backup.expected) checks.backupShaMatch = backup.sha256 === backup.expected;
|
|
591
|
+
|
|
592
|
+
const cutRecorded = (expected.kind === 'after' || expected.kind === 'receipt') && checks.expectedSha256 != null;
|
|
593
|
+
const backupRequired = phase !== 'prepare';
|
|
594
|
+
|
|
595
|
+
// R2-06: a noop run never cut anything. It must never be reported as
|
|
596
|
+
// "cut applied" just because after === before and verify.ok was set to true.
|
|
597
|
+
if (cutRecorded && checks.cutOutcome === 'noop') {
|
|
598
|
+
if (checks.shaMatch === false || checks.sizeMatch === false || checks.countsMatch === false) {
|
|
599
|
+
report.reasonCode = RECOVERY_REASON.NOOP_SESSION_CHANGED;
|
|
600
|
+
report.recommendation =
|
|
601
|
+
'state 说这次手术判定「无需截断」,但磁盘上的会话与手术前快照不一致。' +
|
|
602
|
+
'没有执行过剪切却出现变化,通常是宿主正常写入或外部改过文件;先只读核对,不要把它当成一次成功的截断。';
|
|
603
|
+
report.actions = ['停宿主后重新跑一次 surgery-inspect.mjs --recover-report', '不要重剪'];
|
|
604
|
+
return report;
|
|
605
|
+
}
|
|
606
|
+
verdict(report, CLASSIFICATIONS.ABORTED_BEFORE_CUT, RECOVERY_REASON.OK_NOOP);
|
|
607
|
+
report.recommendation =
|
|
608
|
+
'这次手术判定无需截断:会话没有发生剪切,文件保持手术前状态。' +
|
|
609
|
+
'不需要重剪;如果之后真的需要压缩,再重新跑手术即可。';
|
|
610
|
+
report.actions = ['无需操作'];
|
|
611
|
+
return report;
|
|
612
|
+
}
|
|
613
|
+
|
|
614
|
+
if (cutRecorded) {
|
|
615
|
+
if (checks.shaMatch === false) {
|
|
616
|
+
report.reasonCode = RECOVERY_REASON.SESSION_SHA_MISMATCH;
|
|
617
|
+
report.recommendation =
|
|
618
|
+
'stage 文件说剪切已经完成,但磁盘上会话的 sha256 与记录的 after 不一致。' +
|
|
619
|
+
'这可能是宿主重启后又写了新内容,也可能是文件被替换/恢复过。先只读核对,不要重剪;' +
|
|
620
|
+
'把宿主停掉后再比对备份与当前文件。';
|
|
621
|
+
report.actions = [
|
|
622
|
+
'停宿主后重新跑一次 scripts/surgery-inspect.mjs --recover-report,排除“运行中还在写”',
|
|
623
|
+
`比对当前文件与备份 ${checks.backupPath ?? '(未记录)'}`,
|
|
624
|
+
'确认是新写入还是异常替换,再决定是否重剪',
|
|
625
|
+
];
|
|
626
|
+
return report;
|
|
627
|
+
}
|
|
628
|
+
if (checks.sizeMatch === false || checks.countsMatch === false) {
|
|
629
|
+
report.reasonCode = RECOVERY_REASON.SESSION_COUNTS_MISMATCH;
|
|
630
|
+
report.recommendation =
|
|
631
|
+
'会话 sha256 对得上,但字节数/事件数/消息数与记录不一致。先按证据文件逐项核对;' +
|
|
632
|
+
'sha 一致时通常说明 state 里的计数写错了,而不是会话被改坏。';
|
|
633
|
+
report.actions = ['打开 recovery 报告核对 checks 各字段', '不要重剪'];
|
|
634
|
+
return report;
|
|
635
|
+
}
|
|
636
|
+
if (backupRequired && !backup.exists) {
|
|
637
|
+
report.reasonCode = RECOVERY_REASON.BACKUP_MISSING;
|
|
638
|
+
report.recommendation =
|
|
639
|
+
'剪切已完成,但 prep 备份不见了。会话可能没问题,但一旦需要回滚就没有退路。' +
|
|
640
|
+
'先找回备份(旁边同名的 .pre-surgery-* / .bak-*),找不到就不要再动这个会话。';
|
|
641
|
+
report.actions = [`在会话目录里找 ${path.basename(checks.sessionPath)}.pre-surgery-*`, '找到前不要重剪'];
|
|
642
|
+
return report;
|
|
643
|
+
}
|
|
644
|
+
if (backup.exists && checks.backupShaMatch === false) {
|
|
645
|
+
report.reasonCode = RECOVERY_REASON.BACKUP_SHA_MISMATCH;
|
|
646
|
+
report.recommendation =
|
|
647
|
+
'剪切已完成,但备份文件的 sha256 与记录不一致——备份可能被改过或拷坏了。' +
|
|
648
|
+
'先只读核对备份,不要把它当回滚依据;会话本身仍以 sha 校验结果为准。';
|
|
649
|
+
report.actions = ['核对备份文件的大小与 sha256', '另找一份更早的 .bak-* 作为退路'];
|
|
650
|
+
return report;
|
|
651
|
+
}
|
|
652
|
+
if (checks.readBackRecorded) {
|
|
653
|
+
// rc.6: `applied-unparsed` is a real, verified cut whose only anomaly was
|
|
654
|
+
// the CLI's stdout; keep it visible as its own verdict so the receipt and
|
|
655
|
+
// the logs agree, instead of pretending the stdout was fine.
|
|
656
|
+
const unparsed = checks.cutOutcome === 'applied-unparsed';
|
|
657
|
+
verdict(
|
|
658
|
+
report,
|
|
659
|
+
unparsed ? CLASSIFICATIONS.APPLIED_UNPARSED : CLASSIFICATIONS.APPLIED_VERIFIED,
|
|
660
|
+
unparsed ? RECOVERY_REASON.OK_UNPARSED : RECOVERY_REASON.OK_VERIFIED,
|
|
661
|
+
);
|
|
662
|
+
report.recommendation = unparsed
|
|
663
|
+
? '上次手术的 CLI 输出编码异常(GBK 控制台读不了 UTF-8 的 JSON),但脚本用独立读回核验确认了剪切落盘:' +
|
|
664
|
+
'会话 sha256、事件数、消息数与记录一致,备份也在。不需要重剪。'
|
|
665
|
+
: '上次手术已经落盘并通过读回校验:会话 sha256、事件数、消息数与 state 记录一致,备份也在。' +
|
|
666
|
+
'不需要重剪。若要回滚,先停宿主,再用备份覆盖会话文件。';
|
|
667
|
+
report.actions = unparsed
|
|
668
|
+
? ['无需操作(applied-unparsed 已核验)', '需要回滚时先停宿主,再用备份覆盖会话文件']
|
|
669
|
+
: ['无需操作', '需要回滚时先停宿主,再用备份覆盖会话文件'];
|
|
670
|
+
} else {
|
|
671
|
+
verdict(report, CLASSIFICATIONS.APPLIED_UNVERIFIED, RECOVERY_REASON.OK_UNVERIFIED);
|
|
672
|
+
report.recommendation =
|
|
673
|
+
'会话文件已经是剪切后的样子,但 state 里没有留下读回校验记录(脚本在 cut 之后、记录 verify 之前被杀)。' +
|
|
674
|
+
'当前这次只读检查已经核对 sha256 与备份;确认宿主能正常加载后,不需要重剪。';
|
|
675
|
+
report.actions = ['确认宿主能正常打开这个会话', '保留 state 作为回执;不要重剪'];
|
|
676
|
+
}
|
|
677
|
+
if (checks.versionMatch === false) {
|
|
678
|
+
report.recommendation +=
|
|
679
|
+
` 注意:记录的手术插件版本是 ${checks.versionRecorded},当前加载的是 ${checks.versionLoaded};` +
|
|
680
|
+
'截断本身已核对,版本变化只影响回执的解释。';
|
|
681
|
+
}
|
|
682
|
+
if (checks.hostVersionMatch === false) {
|
|
683
|
+
report.recommendation +=
|
|
684
|
+
` 宿主版本也变了(记录 ${checks.hostVersionRecorded},当前 ${checks.hostVersionLoaded}),` +
|
|
685
|
+
'如果会话能正常打开就不用处理。';
|
|
686
|
+
}
|
|
687
|
+
return report;
|
|
688
|
+
}
|
|
689
|
+
|
|
690
|
+
// No after snapshot: the cut never recorded a result.
|
|
691
|
+
const beforeSha = asText(state?.before?.sha256);
|
|
692
|
+
const matchesBefore = beforeSha != null && session.sha256 === beforeSha;
|
|
693
|
+
const cutAttempted =
|
|
694
|
+
phase === 'cut' ||
|
|
695
|
+
phase === 'restart' ||
|
|
696
|
+
phase === 'receipt-pending' ||
|
|
697
|
+
(state?.cut && (state.cut.exitCode !== undefined || state.cut.startedAt != null));
|
|
698
|
+
|
|
699
|
+
if (cutAttempted || phase === 'failed') {
|
|
700
|
+
if (matchesBefore && backup.exists) {
|
|
701
|
+
verdict(report, CLASSIFICATIONS.ABORTED_BEFORE_CUT, RECOVERY_REASON.OK_ABORTED);
|
|
702
|
+
report.recommendation =
|
|
703
|
+
'上次手术在真正剪切之前就停了:会话文件仍与 before 快照一致,备份也完整。' +
|
|
704
|
+
'可以直接重跑无人值守手术;重跑前先看 surgery.log 的最后一行,弄清上次为什么断。';
|
|
705
|
+
report.actions = ['查看 .longlive/logs/surgery.log 末尾', '确认宿主已退出后重跑手术'];
|
|
706
|
+
return report;
|
|
707
|
+
}
|
|
708
|
+
if (matchesBefore && !backup.exists) {
|
|
709
|
+
report.reasonCode = RECOVERY_REASON.BACKUP_MISSING;
|
|
710
|
+
report.recommendation =
|
|
711
|
+
'会话仍是手术前状态,但这次手术应该已经做过备份却没有找到备份文件。' +
|
|
712
|
+
'先找回备份或确认这次没有真正开始,再重跑;不要在没有退路的情况下动手术。';
|
|
713
|
+
report.actions = ['在会话目录里找 .pre-surgery-* 备份', '确认后重跑'];
|
|
714
|
+
return report;
|
|
715
|
+
}
|
|
716
|
+
report.reasonCode = RECOVERY_REASON.CUT_RESULT_MISSING;
|
|
717
|
+
report.recommendation =
|
|
718
|
+
'stage 文件停在 cut/restart,但没有记录 after 结果,而磁盘上的会话已经和 before 不一样了。' +
|
|
719
|
+
'这说明剪切很可能已经执行,只是脚本在写回执前被杀。先只读核对当前 sha、备份和 archive 目录;' +
|
|
720
|
+
'不要重剪,确认后再手工把 state 的 phase 改成 done(或保留报告作回执)。';
|
|
721
|
+
report.actions = [
|
|
722
|
+
'核对会话目录下的 .bak-* 与 .archive 产物',
|
|
723
|
+
`比对当前 sha256 ${session.sha256} 与 before ${beforeSha ?? '(未记录)'}`,
|
|
724
|
+
'确认新会话能被宿主加载后,再决定是否手工收尾',
|
|
725
|
+
];
|
|
726
|
+
return report;
|
|
727
|
+
}
|
|
728
|
+
|
|
729
|
+
// prepare / backup (or failed before the cut): the safe abort case.
|
|
730
|
+
if (matchesBefore) {
|
|
731
|
+
if (!backup.exists && phase !== 'prepare') {
|
|
732
|
+
report.reasonCode = RECOVERY_REASON.BACKUP_MISSING;
|
|
733
|
+
report.recommendation =
|
|
734
|
+
'手术在剪切前停了,但阶段已经是 backup/之后,却没有找到备份文件。先找回备份再重跑。';
|
|
735
|
+
report.actions = ['在会话目录里找 .pre-surgery-* 备份'];
|
|
736
|
+
return report;
|
|
737
|
+
}
|
|
738
|
+
if (backup.exists && checks.backupShaMatch === false) {
|
|
739
|
+
report.reasonCode = RECOVERY_REASON.BACKUP_SHA_MISMATCH;
|
|
740
|
+
report.recommendation = '手术在剪切前停了,但备份文件的 sha256 与记录不一致;先核对备份再重跑。';
|
|
741
|
+
report.actions = ['核对备份 sha256'];
|
|
742
|
+
return report;
|
|
743
|
+
}
|
|
744
|
+
verdict(report, CLASSIFICATIONS.ABORTED_BEFORE_CUT, RECOVERY_REASON.OK_ABORTED);
|
|
745
|
+
report.recommendation =
|
|
746
|
+
'上次手术在剪切前中止:会话文件仍是手术前状态,备份完整。重跑前看一眼 surgery.log 的末尾即可。';
|
|
747
|
+
report.actions = ['查看 .longlive/logs/surgery.log 末尾', '确认宿主已退出后重跑手术'];
|
|
748
|
+
return report;
|
|
749
|
+
}
|
|
750
|
+
|
|
751
|
+
report.reasonCode = RECOVERY_REASON.SESSION_CHANGED_BEFORE_CUT;
|
|
752
|
+
report.recommendation =
|
|
753
|
+
phase === 'prepare'
|
|
754
|
+
? 'stage 只到 prepare,但会话文件已经与 before 快照不一致。可能是记完 before 之后宿主又写了内容(正常),' +
|
|
755
|
+
'也可能是别的进程动过文件。先只读核对;要重跑就让手术重新记一次 before。'
|
|
756
|
+
: 'stage 说还在剪切前,但会话文件已经和 before 不一致。先只读核对,不要盲目重跑。';
|
|
757
|
+
report.actions = ['停宿主后重新核对 sha256', '确认变化来自宿主正常写入还是外部替换'];
|
|
758
|
+
return report;
|
|
759
|
+
}
|
|
760
|
+
|
|
761
|
+
function oneLine(report) {
|
|
762
|
+
const parts = [
|
|
763
|
+
`classification=${report.classification}`,
|
|
764
|
+
`reason=${report.reasonCode}`,
|
|
765
|
+
`phase=${sanitizePhase(report.statePhase)}`,
|
|
766
|
+
];
|
|
767
|
+
if (report.surgeryId) parts.push(`surgery=${sanitizeFileToken(report.surgeryId)}`);
|
|
768
|
+
if (report.dryRun === true) parts.push('dryRun=true');
|
|
769
|
+
if (report.checks?.sessionSha256) parts.push(`sha=${report.checks.sessionSha256}`);
|
|
770
|
+
return parts.join(' ');
|
|
771
|
+
}
|
|
772
|
+
|
|
773
|
+
/**
|
|
774
|
+
* Write one report file and one audit line. The caller decides whether a check
|
|
775
|
+
* is due; this function only persists evidence.
|
|
776
|
+
*/
|
|
777
|
+
export function writeRecoveryReport(memoryRoot, report, { now = new Date(), audit = true } = {}) {
|
|
778
|
+
const file = recoveryReportPath(memoryRoot, now);
|
|
779
|
+
const content = `${JSON.stringify(report, null, 2)}\n`;
|
|
780
|
+
const write = writeFileAtomic(memoryRoot, file, content, { backup: false, now });
|
|
781
|
+
let auditLine = null;
|
|
782
|
+
if (audit) {
|
|
783
|
+
try {
|
|
784
|
+
const entry = appendAudit(memoryRoot, {
|
|
785
|
+
action: 'surgery-recovery',
|
|
786
|
+
object: report.surgeryId ?? report.statePath ?? '-',
|
|
787
|
+
result: `${report.classification} ${report.reasonCode}`,
|
|
788
|
+
now,
|
|
789
|
+
});
|
|
790
|
+
auditLine = entry.line;
|
|
791
|
+
} catch {
|
|
792
|
+
// The report is the primary evidence; an append failure must not hide it.
|
|
793
|
+
auditLine = null;
|
|
794
|
+
}
|
|
795
|
+
}
|
|
796
|
+
return { path: write.path, sha256: write.sha256, bytes: write.bytes, auditLine };
|
|
797
|
+
}
|
|
798
|
+
|
|
799
|
+
/**
|
|
800
|
+
* Startup entry point. Returns `checked: false` (and touches nothing beyond
|
|
801
|
+
* one existsSync) when there is no stage file, when the last surgery is
|
|
802
|
+
* `done` *and* its receipt was written, or when the fallback receipt was
|
|
803
|
+
* already injected once. A `done` state without a written receipt falls
|
|
804
|
+
* through so the caller can inject the fallback text exactly once.
|
|
805
|
+
*
|
|
806
|
+
* Never throws: activation must not fail because a post-mortem could not be
|
|
807
|
+
* written. The caller still gets a structured result for logging/tests.
|
|
808
|
+
*/
|
|
809
|
+
export function checkSurgeryOnStart(options = {}) {
|
|
810
|
+
const { memoryRoot, now = new Date(), loadedVersion = VERSION, loadedHostVersion = null } = options;
|
|
811
|
+
if (!memoryRoot) return { checked: false, reason: 'no-memory-root' };
|
|
812
|
+
const stateRead = readSurgeryState(memoryRoot);
|
|
813
|
+
if (!stateRead.exists) return { checked: false, reason: 'no-state', statePath: stateRead.path };
|
|
814
|
+
const state = stateRead.state;
|
|
815
|
+
// R3-01: a -DryRun rehearsal is not a surgery. Return before reading the
|
|
816
|
+
// session, writing a report, appending an audit line or producing receipt
|
|
817
|
+
// text: there is nothing to recover and nothing to inject.
|
|
818
|
+
if (state?.dryRun === true || asText(state?.phase) === 'dryrun') {
|
|
819
|
+
return {
|
|
820
|
+
checked: false,
|
|
821
|
+
reason: 'dryrun',
|
|
822
|
+
statePath: stateRead.path,
|
|
823
|
+
surgeryId: asText(state.surgeryId),
|
|
824
|
+
outcome: asText(state?.done?.outcome) ?? 'dry-run',
|
|
825
|
+
};
|
|
826
|
+
}
|
|
827
|
+
if (state?.phase === 'done' && state?.receipt?.written === true) {
|
|
828
|
+
return {
|
|
829
|
+
checked: false,
|
|
830
|
+
reason: 'phase-done',
|
|
831
|
+
statePath: stateRead.path,
|
|
832
|
+
surgeryId: asText(state.surgeryId),
|
|
833
|
+
outcome: asText(state?.done?.outcome) ?? null,
|
|
834
|
+
};
|
|
835
|
+
}
|
|
836
|
+
// R2-02 / minor: the fallback is injected once. The pre-step hook writes
|
|
837
|
+
// this marker atomically after a successful injection; every later start
|
|
838
|
+
// stays quiet instead of appending the same receipt again.
|
|
839
|
+
if (state?.receipt?.fallbackInjected === true) {
|
|
840
|
+
return {
|
|
841
|
+
checked: false,
|
|
842
|
+
reason: 'receipt-fallback-injected',
|
|
843
|
+
statePath: stateRead.path,
|
|
844
|
+
surgeryId: asText(state.surgeryId),
|
|
845
|
+
outcome: asText(state?.done?.outcome) ?? null,
|
|
846
|
+
};
|
|
847
|
+
}
|
|
848
|
+
const report = buildRecoveryReport({
|
|
849
|
+
memoryRoot,
|
|
850
|
+
now,
|
|
851
|
+
loadedVersion,
|
|
852
|
+
loadedHostVersion,
|
|
853
|
+
stateRead,
|
|
854
|
+
});
|
|
855
|
+
let written = null;
|
|
856
|
+
let writeError = null;
|
|
857
|
+
try {
|
|
858
|
+
written = writeRecoveryReport(memoryRoot, report, { now });
|
|
859
|
+
report.reportPath = written.path;
|
|
860
|
+
report.reportSha256 = written.sha256;
|
|
861
|
+
report.auditLine = written.auditLine;
|
|
862
|
+
} catch (error) {
|
|
863
|
+
writeError = { code: error?.code ?? 'REPORT_WRITE_FAILED', message: error?.message ?? String(error) };
|
|
864
|
+
report.reportWriteError = writeError;
|
|
865
|
+
}
|
|
866
|
+
return {
|
|
867
|
+
checked: true,
|
|
868
|
+
reason: 'recovered',
|
|
869
|
+
statePath: stateRead.path,
|
|
870
|
+
report,
|
|
871
|
+
written,
|
|
872
|
+
writeError,
|
|
873
|
+
summary: oneLine(report),
|
|
874
|
+
};
|
|
875
|
+
}
|
|
876
|
+
|
|
877
|
+
/**
|
|
878
|
+
* Read-only CLI query. Never writes a report, never appends audit, never
|
|
879
|
+
* touches the session. Returns a JSON-serialisable object with the last
|
|
880
|
+
* surgery receipt (phase `done`) or the live recovery verdict.
|
|
881
|
+
*/
|
|
882
|
+
export function statusSurgery(options = {}) {
|
|
883
|
+
const { memoryRoot, now = new Date(), loadedVersion = VERSION, loadedHostVersion = null } = options;
|
|
884
|
+
if (!memoryRoot) {
|
|
885
|
+
return { ok: false, found: false, status: 'no-memory-root', message: '没有记忆根目录,无法定位手术状态。' };
|
|
886
|
+
}
|
|
887
|
+
const stateRead = readSurgeryState(memoryRoot);
|
|
888
|
+
if (!stateRead.exists) {
|
|
889
|
+
return {
|
|
890
|
+
ok: true,
|
|
891
|
+
found: false,
|
|
892
|
+
status: 'none',
|
|
893
|
+
memoryRoot,
|
|
894
|
+
statePath: stateRead.path,
|
|
895
|
+
message: '没有发现手术状态文件:上次没有跑过无人值守手术。',
|
|
896
|
+
};
|
|
897
|
+
}
|
|
898
|
+
if (stateRead.error || !stateRead.state) {
|
|
899
|
+
const report = buildRecoveryReport({ memoryRoot, now, loadedVersion, loadedHostVersion, stateRead });
|
|
900
|
+
return {
|
|
901
|
+
ok: false,
|
|
902
|
+
found: true,
|
|
903
|
+
status: 'state-unreadable',
|
|
904
|
+
memoryRoot,
|
|
905
|
+
statePath: stateRead.path,
|
|
906
|
+
stateError: stateRead.error,
|
|
907
|
+
classification: report.classification,
|
|
908
|
+
reasonCode: report.reasonCode,
|
|
909
|
+
recommendation: report.recommendation,
|
|
910
|
+
report,
|
|
911
|
+
};
|
|
912
|
+
}
|
|
913
|
+
const state = stateRead.state;
|
|
914
|
+
const lastSurgery = {
|
|
915
|
+
surgeryId: asText(state.surgeryId),
|
|
916
|
+
phase: asText(state.phase),
|
|
917
|
+
startedAt: asText(state.startedAt),
|
|
918
|
+
updatedAt: asText(state.updatedAt),
|
|
919
|
+
sessionPath: asText(state.sessionPath),
|
|
920
|
+
before: state.before ?? null,
|
|
921
|
+
after: state.after ?? state.cut?.after ?? state.cut?.cli?.after ?? state.cut?.cli?.json?.after ?? null,
|
|
922
|
+
backup: state.backup ?? null,
|
|
923
|
+
outcome: asText(state?.done?.outcome),
|
|
924
|
+
error: state.error ?? null,
|
|
925
|
+
};
|
|
926
|
+
if (state.dryRun === true || asText(state.phase) === 'dryrun') {
|
|
927
|
+
return {
|
|
928
|
+
ok: true,
|
|
929
|
+
found: true,
|
|
930
|
+
status: 'dryrun',
|
|
931
|
+
memoryRoot,
|
|
932
|
+
statePath: stateRead.path,
|
|
933
|
+
classification: 'dry-run',
|
|
934
|
+
reasonCode: RECOVERY_REASON.OK_DRYRUN,
|
|
935
|
+
dryRun: true,
|
|
936
|
+
lastSurgery,
|
|
937
|
+
recommendation:
|
|
938
|
+
'上次是 -DryRun 演练:没有关闭宿主、没有剪切任何字节,也没有手术回执可写。' +
|
|
939
|
+
'状态正常,不需要处理;要真正截断时去掉 -DryRun 重跑。',
|
|
940
|
+
reportPath: asText(state?.done?.resultPath),
|
|
941
|
+
};
|
|
942
|
+
}
|
|
943
|
+
if (state.phase === 'done' && state?.receipt?.written === true) {
|
|
944
|
+
const outcome = asText(state?.done?.outcome);
|
|
945
|
+
const noop = outcome === 'noop';
|
|
946
|
+
return {
|
|
947
|
+
ok: true,
|
|
948
|
+
found: true,
|
|
949
|
+
status: 'done',
|
|
950
|
+
memoryRoot,
|
|
951
|
+
statePath: stateRead.path,
|
|
952
|
+
classification: noop ? CLASSIFICATIONS.ABORTED_BEFORE_CUT : outcome ?? CLASSIFICATIONS.APPLIED_VERIFIED,
|
|
953
|
+
reasonCode: noop ? RECOVERY_REASON.OK_NOOP : RECOVERY_REASON.OK_VERIFIED,
|
|
954
|
+
lastSurgery,
|
|
955
|
+
recommendation: noop
|
|
956
|
+
? `上次手术已完成(${asText(state?.done?.at) ?? asText(state.updatedAt) ?? '时间未记录'}),` +
|
|
957
|
+
'但判定为无需截断:会话没有被剪切,文件保持手术前状态。这份查询不写任何文件。'
|
|
958
|
+
: `上次手术已完成(${asText(state?.done?.at) ?? asText(state.updatedAt) ?? '时间未记录'}),` +
|
|
959
|
+
'回执已写入会话正文。启动自检不会重复写报告;这份查询也不写任何文件。',
|
|
960
|
+
reportPath: asText(state?.done?.resultPath),
|
|
961
|
+
};
|
|
962
|
+
}
|
|
963
|
+
const report = buildRecoveryReport({ memoryRoot, now, loadedVersion, loadedHostVersion, stateRead });
|
|
964
|
+
return {
|
|
965
|
+
ok: report.ok,
|
|
966
|
+
found: true,
|
|
967
|
+
status: 'needs-review',
|
|
968
|
+
memoryRoot,
|
|
969
|
+
statePath: stateRead.path,
|
|
970
|
+
classification: report.classification,
|
|
971
|
+
reasonCode: report.reasonCode,
|
|
972
|
+
recommendation: report.recommendation,
|
|
973
|
+
actions: report.actions,
|
|
974
|
+
lastSurgery,
|
|
975
|
+
report,
|
|
976
|
+
};
|
|
977
|
+
}
|
|
978
|
+
|
|
979
|
+
export function formatRecoveryReport(report) {
|
|
980
|
+
return oneLine(report);
|
|
981
|
+
}
|
|
982
|
+
|
|
983
|
+
/**
|
|
984
|
+
* Ensure the reports directory exists for a caller that is about to write a
|
|
985
|
+
* report. Kept separate so a pure build/query never creates anything.
|
|
986
|
+
*/
|
|
987
|
+
export function ensureReportsDir(memoryRoot) {
|
|
988
|
+
const dir = path.join(longliveDir(memoryRoot), REPORTS_DIR);
|
|
989
|
+
ensureDir(memoryRoot, dir);
|
|
990
|
+
return dir;
|
|
991
|
+
}
|
|
992
|
+
|
|
993
|
+
// ---------------------------------------------------------------------------
|
|
994
|
+
// In-conversation receipt (必修二)
|
|
995
|
+
//
|
|
996
|
+
// The launcher writes a visible receipt into the session log *after* the
|
|
997
|
+
// read-back passed and *before* the host is restarted, so the next time the
|
|
998
|
+
// session opens the conversation already carries the verdict as ordinary text.
|
|
999
|
+
// If that write never happened (failed/crashed run), the plugin's startup
|
|
1000
|
+
// pre-step hook injects the same text on the next turn instead.
|
|
1001
|
+
// ---------------------------------------------------------------------------
|
|
1002
|
+
|
|
1003
|
+
export const RECEIPT_PREFIX = '【手术回执】';
|
|
1004
|
+
export const RECEIPT_SOURCE_KIND = 'user';
|
|
1005
|
+
|
|
1006
|
+
function formatCount(value) {
|
|
1007
|
+
if (!Number.isFinite(value)) return '?';
|
|
1008
|
+
return String(Math.trunc(value)).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
|
|
1009
|
+
}
|
|
1010
|
+
|
|
1011
|
+
function shortSha(value) {
|
|
1012
|
+
const text = asText(value);
|
|
1013
|
+
return text ? text.slice(0, 12) : '(未记录)';
|
|
1014
|
+
}
|
|
1015
|
+
|
|
1016
|
+
// R2-01: the receipt is conversation text, never a diagnostic dump. It must
|
|
1017
|
+
// not contain an absolute path (Windows drive, UNC, or a POSIX home path).
|
|
1018
|
+
const ABSOLUTE_PATH_RE =
|
|
1019
|
+
/(?:[A-Za-z]:[\\/]|\\\\|\/(?:Users|home|tmp|var|opt|root|mnt)\/)[^\s"'<>|,。;:))】]*/g;
|
|
1020
|
+
|
|
1021
|
+
function receiptBasename(value) {
|
|
1022
|
+
const text = asText(value);
|
|
1023
|
+
if (!text) return null;
|
|
1024
|
+
const name = path.basename(text.replace(/[\\/]+$/, ''));
|
|
1025
|
+
return name || null;
|
|
1026
|
+
}
|
|
1027
|
+
|
|
1028
|
+
/**
|
|
1029
|
+
* Strip absolute paths from free-form advice. Known session/backup paths are
|
|
1030
|
+
* replaced by their file name first so the sentence keeps its meaning; any
|
|
1031
|
+
* remaining absolute path becomes a placeholder.
|
|
1032
|
+
*/
|
|
1033
|
+
function sanitizeReceiptAdvice(value, { sessionPath, backupPath } = {}) {
|
|
1034
|
+
let text = asText(value);
|
|
1035
|
+
if (!text) return null;
|
|
1036
|
+
for (const candidate of [sessionPath, backupPath]) {
|
|
1037
|
+
const full = asText(candidate);
|
|
1038
|
+
if (!full) continue;
|
|
1039
|
+
const name = receiptBasename(full) ?? '(路径已隐藏)';
|
|
1040
|
+
text = text.split(full).join(name);
|
|
1041
|
+
text = text.split(full.replace(/\\/g, '/')).join(name);
|
|
1042
|
+
}
|
|
1043
|
+
return text.replace(ABSOLUTE_PATH_RE, '(路径已隐藏)');
|
|
1044
|
+
}
|
|
1045
|
+
|
|
1046
|
+
/**
|
|
1047
|
+
* Compose the human-readable receipt. Numbers come from the recovery report:
|
|
1048
|
+
* before = state.before, after = the verified cut result (or the receipt
|
|
1049
|
+
* snapshot once it exists), so the text cannot disagree with the evidence file.
|
|
1050
|
+
*/
|
|
1051
|
+
export function receiptText(report, { appendingReceipt = false, seq = null } = {}) {
|
|
1052
|
+
const checks = report?.checks ?? {};
|
|
1053
|
+
const classification = report?.classification ?? CLASSIFICATIONS.NEEDS_ATTENTION;
|
|
1054
|
+
const reasonCode = report?.reasonCode ?? null;
|
|
1055
|
+
let verdict;
|
|
1056
|
+
if (reasonCode === RECOVERY_REASON.OK_NOOP) {
|
|
1057
|
+
verdict = '无需截断 —— 本次手术没有执行剪切,会话保持手术前状态。';
|
|
1058
|
+
} else if (classification === CLASSIFICATIONS.APPLIED_VERIFIED) {
|
|
1059
|
+
verdict = '成功 —— 剪切已落盘,读回校验通过,宿主已自动重启。';
|
|
1060
|
+
} else if (classification === CLASSIFICATIONS.APPLIED_UNPARSED) {
|
|
1061
|
+
// rc.6 / R4-03: Chinese stdout through a GBK console used to look like a
|
|
1062
|
+
// failure even though the cut was fine. Say plainly that it was verified.
|
|
1063
|
+
verdict = '成功 —— 剪切已落盘;CLI 输出编码异常(applied-unparsed),独立读回核验通过,宿主已自动重启。';
|
|
1064
|
+
} else if (classification === CLASSIFICATIONS.APPLIED_UNVERIFIED) {
|
|
1065
|
+
verdict = '已剪切,但没有留下读回校验记录(脚本在写完校验前被杀)。';
|
|
1066
|
+
} else if (classification === CLASSIFICATIONS.ABORTED_BEFORE_CUT) {
|
|
1067
|
+
verdict = '未执行 —— 在剪切前中止,会话文件仍保持原样。';
|
|
1068
|
+
} else {
|
|
1069
|
+
verdict = '需要注意 —— 没能确认剪切结果,先不要重剪。';
|
|
1070
|
+
}
|
|
1071
|
+
|
|
1072
|
+
const lines = [`${RECEIPT_PREFIX}会话截断结果(无人值守手术)`, ''];
|
|
1073
|
+
lines.push(`结果:${verdict}`);
|
|
1074
|
+
const phase = sanitizePhase(report?.statePhase ?? checks.phase);
|
|
1075
|
+
lines.push(`停在哪:phase=${phase}${reasonCode ? `(reason=${reasonCode})` : ''}`);
|
|
1076
|
+
// Filename only: never the absolute session path.
|
|
1077
|
+
const sessionName = receiptBasename(checks.sessionPath);
|
|
1078
|
+
if (sessionName) lines.push(`会话:${sessionName}`);
|
|
1079
|
+
// R3-04 / R4-02: only a [a-z0-9-] token may be echoed. A legal session id is
|
|
1080
|
+
// shown in full (operators match UUIDs, not their first 8 chars); a value
|
|
1081
|
+
// that fails the whitelist is still sanitised and shortened. `asText` alone
|
|
1082
|
+
// let a tampered state put `..\..\<user-dir>\\...` into the transcript.
|
|
1083
|
+
const sessionId = displaySessionId(asText(report?.sessionId) ?? asText(checks.sessionId));
|
|
1084
|
+
if (sessionId) lines.push(`会话 id:${sessionId}`);
|
|
1085
|
+
|
|
1086
|
+
const beforeBytes = checks.beforeBytes;
|
|
1087
|
+
const afterBytes = checks.sessionBytes;
|
|
1088
|
+
if (Number.isFinite(beforeBytes) && Number.isFinite(afterBytes)) {
|
|
1089
|
+
const pct = beforeBytes > 0 ? (afterBytes / beforeBytes - 1) * 100 : null;
|
|
1090
|
+
// rc.6: a tiny session can legitimately grow after the cut, so an increase
|
|
1091
|
+
// must read as +x.x% instead of the old "--x.x%" double sign.
|
|
1092
|
+
const pctText = pct == null ? '' : `(${pct > 0 ? '+' : ''}${pct.toFixed(1)}%)`;
|
|
1093
|
+
lines.push(`字节:${formatCount(beforeBytes)} → ${formatCount(afterBytes)}${pctText}`);
|
|
1094
|
+
} else if (Number.isFinite(afterBytes)) {
|
|
1095
|
+
lines.push(`字节:? → ${formatCount(afterBytes)}`);
|
|
1096
|
+
}
|
|
1097
|
+
if (Number.isFinite(checks.beforeEvents) && Number.isFinite(checks.sessionEvents)) {
|
|
1098
|
+
lines.push(`事件:${formatCount(checks.beforeEvents)} → ${formatCount(checks.sessionEvents)}`);
|
|
1099
|
+
}
|
|
1100
|
+
if (Number.isFinite(checks.beforeMessages) && Number.isFinite(checks.sessionMessages)) {
|
|
1101
|
+
const after = checks.sessionMessages;
|
|
1102
|
+
const suffix = appendingReceipt ? `(本条回执另计 +1,写入后 ${formatCount(after + 1)})` : '';
|
|
1103
|
+
lines.push(`消息:${formatCount(checks.beforeMessages)} → ${formatCount(after)}${suffix}`);
|
|
1104
|
+
}
|
|
1105
|
+
if (checks.shaMatch === true) {
|
|
1106
|
+
lines.push(`sha256:磁盘读回与记录一致 ✅(after ${shortSha(checks.expectedSha256)})`);
|
|
1107
|
+
} else if (checks.shaMatch === false) {
|
|
1108
|
+
lines.push(
|
|
1109
|
+
`sha256:与记录不一致 ❌(记录 ${shortSha(checks.expectedSha256)},磁盘 ${shortSha(checks.sessionSha256)})`,
|
|
1110
|
+
);
|
|
1111
|
+
} else {
|
|
1112
|
+
lines.push('sha256:没有可比的记录(无法确认)');
|
|
1113
|
+
}
|
|
1114
|
+
const backupName = receiptBasename(checks.backupPath);
|
|
1115
|
+
if (backupName) {
|
|
1116
|
+
lines.push(`备份:${backupName}${checks.backupExists === false ? '(缺失)' : '(已保留)'}`);
|
|
1117
|
+
} else {
|
|
1118
|
+
lines.push('备份:(未记录)');
|
|
1119
|
+
}
|
|
1120
|
+
if (report?.receiptFallbackNeeded === true && !appendingReceipt) {
|
|
1121
|
+
lines.push('回执:state 停在 done,但没有写成回执;本条是启动兜底,只补写一次。');
|
|
1122
|
+
}
|
|
1123
|
+
if (appendingReceipt && seq != null) {
|
|
1124
|
+
lines.push(`本条回执已写入会话正文:seq=${seq}。`);
|
|
1125
|
+
} else {
|
|
1126
|
+
lines.push('回执来源:手术脚本没有写进会话,这条由插件在会话启动时按状态文件补写。');
|
|
1127
|
+
}
|
|
1128
|
+
const advice = sanitizeReceiptAdvice(report?.recommendation, {
|
|
1129
|
+
sessionPath: checks.sessionPath,
|
|
1130
|
+
backupPath: checks.backupPath,
|
|
1131
|
+
});
|
|
1132
|
+
if (advice) {
|
|
1133
|
+
lines.push('');
|
|
1134
|
+
lines.push(`建议:${advice}`);
|
|
1135
|
+
}
|
|
1136
|
+
return `${lines.join('\n')}\n`;
|
|
1137
|
+
}
|
|
1138
|
+
|
|
1139
|
+
/** Build the durable user/message event the host renders as conversation text. */
|
|
1140
|
+
export function buildReceiptEvent({ text, seq, now = Date.now(), id }) {
|
|
1141
|
+
return {
|
|
1142
|
+
type: 'user/message',
|
|
1143
|
+
surfaceOp: 'append',
|
|
1144
|
+
seq,
|
|
1145
|
+
time: now,
|
|
1146
|
+
data: {
|
|
1147
|
+
role: 'user',
|
|
1148
|
+
id,
|
|
1149
|
+
content: [{ type: 'text', text }],
|
|
1150
|
+
// A plain `user` source is what makes the host project this as visible
|
|
1151
|
+
// conversation text (kind `session-reference` would land in the context
|
|
1152
|
+
// rail instead, which is invisible in Chat).
|
|
1153
|
+
source: { kind: RECEIPT_SOURCE_KIND },
|
|
1154
|
+
},
|
|
1155
|
+
};
|
|
1156
|
+
}
|
|
1157
|
+
|
|
1158
|
+
function writeSessionAtomic(sessionPath, buffer) {
|
|
1159
|
+
const tmp = `${sessionPath}.tmp-receipt-${process.pid}-${Date.now()}`;
|
|
1160
|
+
const fd = fs.openSync(tmp, 'wx');
|
|
1161
|
+
try {
|
|
1162
|
+
fs.writeFileSync(fd, buffer);
|
|
1163
|
+
fs.fsyncSync(fd);
|
|
1164
|
+
} finally {
|
|
1165
|
+
fs.closeSync(fd);
|
|
1166
|
+
}
|
|
1167
|
+
const staged = fs.readFileSync(tmp);
|
|
1168
|
+
if (!staged.equals(buffer)) {
|
|
1169
|
+
try {
|
|
1170
|
+
fs.unlinkSync(tmp);
|
|
1171
|
+
} catch {
|
|
1172
|
+
/* best effort */
|
|
1173
|
+
}
|
|
1174
|
+
throw new Error(`receipt temp write mismatch: ${tmp}`);
|
|
1175
|
+
}
|
|
1176
|
+
fs.renameSync(tmp, sessionPath);
|
|
1177
|
+
const back = fs.readFileSync(sessionPath);
|
|
1178
|
+
if (!back.equals(buffer)) throw new Error(`receipt read-back mismatch: ${sessionPath}`);
|
|
1179
|
+
}
|
|
1180
|
+
|
|
1181
|
+
// R2-04: one writer at a time. The lock lives next to the state file and is
|
|
1182
|
+
// deliberately short-lived; a crashed writer leaves a lock that goes stale
|
|
1183
|
+
// after two minutes and is then replaced. The session append itself is still
|
|
1184
|
+
// idempotent by scanning for the deterministic receipt event id, so a process
|
|
1185
|
+
// killed between the append and the state write repairs the state on retry.
|
|
1186
|
+
export const RECEIPT_LOCK_FILENAME = 'surgery-receipt.lock';
|
|
1187
|
+
const RECEIPT_LOCK_STALE_MS = 2 * 60 * 1000;
|
|
1188
|
+
|
|
1189
|
+
function receiptLockPath(memoryRoot) {
|
|
1190
|
+
return path.join(longliveDir(memoryRoot), RECEIPT_LOCK_FILENAME);
|
|
1191
|
+
}
|
|
1192
|
+
|
|
1193
|
+
function acquireReceiptLock(memoryRoot, now = new Date()) {
|
|
1194
|
+
if (!memoryRoot) return null;
|
|
1195
|
+
const lockPath = receiptLockPath(memoryRoot);
|
|
1196
|
+
const payload = `${JSON.stringify({ pid: process.pid, at: new Date(now).toISOString() })}\n`;
|
|
1197
|
+
for (let attempt = 0; attempt < 2; attempt += 1) {
|
|
1198
|
+
let fd = null;
|
|
1199
|
+
try {
|
|
1200
|
+
fd = fs.openSync(lockPath, 'wx');
|
|
1201
|
+
fs.writeFileSync(fd, payload);
|
|
1202
|
+
fs.fsyncSync(fd);
|
|
1203
|
+
fs.closeSync(fd);
|
|
1204
|
+
fd = null;
|
|
1205
|
+
return {
|
|
1206
|
+
path: lockPath,
|
|
1207
|
+
release() {
|
|
1208
|
+
try {
|
|
1209
|
+
const holder = JSON.parse(fs.readFileSync(lockPath, 'utf8'));
|
|
1210
|
+
if (holder?.pid === process.pid) fs.unlinkSync(lockPath);
|
|
1211
|
+
} catch {
|
|
1212
|
+
/* best effort; never delete a lock we cannot prove is ours */
|
|
1213
|
+
}
|
|
1214
|
+
},
|
|
1215
|
+
};
|
|
1216
|
+
} catch (error) {
|
|
1217
|
+
if (fd != null) {
|
|
1218
|
+
try {
|
|
1219
|
+
fs.closeSync(fd);
|
|
1220
|
+
} catch {
|
|
1221
|
+
/* ignore */
|
|
1222
|
+
}
|
|
1223
|
+
}
|
|
1224
|
+
if (error?.code !== 'EEXIST') {
|
|
1225
|
+
try {
|
|
1226
|
+
fs.unlinkSync(lockPath);
|
|
1227
|
+
} catch {
|
|
1228
|
+
/* ignore */
|
|
1229
|
+
}
|
|
1230
|
+
throw error;
|
|
1231
|
+
}
|
|
1232
|
+
let stat = null;
|
|
1233
|
+
try {
|
|
1234
|
+
stat = fs.statSync(lockPath);
|
|
1235
|
+
} catch {
|
|
1236
|
+
continue;
|
|
1237
|
+
}
|
|
1238
|
+
if (Date.now() - stat.mtimeMs <= RECEIPT_LOCK_STALE_MS) return null;
|
|
1239
|
+
try {
|
|
1240
|
+
fs.unlinkSync(lockPath);
|
|
1241
|
+
} catch {
|
|
1242
|
+
/* another process may have replaced it; try once more */
|
|
1243
|
+
}
|
|
1244
|
+
}
|
|
1245
|
+
}
|
|
1246
|
+
return null;
|
|
1247
|
+
}
|
|
1248
|
+
|
|
1249
|
+
// ---------------------------------------------------------------------------
|
|
1250
|
+
// R3-02: a durable trace when the state file itself cannot be rewritten
|
|
1251
|
+
// ---------------------------------------------------------------------------
|
|
1252
|
+
// When persistReceiptState fails after the receipt event is already inside the
|
|
1253
|
+
// session, a retry must be able to *repair* the state instead of being blocked
|
|
1254
|
+
// forever by a needs-attention report. A marker is written next to the state
|
|
1255
|
+
// (and in the OS temp dir as a fallback when the memory root is unwritable),
|
|
1256
|
+
// and the repair branch deletes it once the state carries the receipt.
|
|
1257
|
+
export const RECEIPT_PENDING_DIR = 'receipts-pending';
|
|
1258
|
+
export const RECEIPT_PENDING_TEMP_DIR = 'dsh-longlive-receipts-pending';
|
|
1259
|
+
const RECEIPT_PENDING_KIND = 'longlive-surgery-receipt-pending';
|
|
1260
|
+
|
|
1261
|
+
function markerName(eventId) {
|
|
1262
|
+
const token = asText(eventId) ?? 'unknown';
|
|
1263
|
+
return `${sha256(Buffer.from(token, 'utf8')).slice(0, 16)}.json`;
|
|
1264
|
+
}
|
|
1265
|
+
|
|
1266
|
+
export function receiptPendingMarkerPath(memoryRoot, eventId) {
|
|
1267
|
+
return path.join(longliveDir(memoryRoot), RECEIPT_PENDING_DIR, markerName(eventId));
|
|
1268
|
+
}
|
|
1269
|
+
|
|
1270
|
+
export function receiptPendingTempMarkerPath(eventId) {
|
|
1271
|
+
return path.join(os.tmpdir(), RECEIPT_PENDING_TEMP_DIR, markerName(eventId));
|
|
1272
|
+
}
|
|
1273
|
+
|
|
1274
|
+
function writeMarkerFile(file, payload) {
|
|
1275
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
1276
|
+
const text = `${JSON.stringify(payload, null, 2)}\n`;
|
|
1277
|
+
const tmp = `${file}.tmp-${process.pid}-${Date.now()}`;
|
|
1278
|
+
try {
|
|
1279
|
+
fs.writeFileSync(tmp, text, 'utf8');
|
|
1280
|
+
fs.renameSync(tmp, file);
|
|
1281
|
+
const back = fs.readFileSync(file, 'utf8');
|
|
1282
|
+
if (back !== text) throw new Error(`marker read-back mismatch: ${file}`);
|
|
1283
|
+
} catch (error) {
|
|
1284
|
+
try {
|
|
1285
|
+
fs.unlinkSync(tmp);
|
|
1286
|
+
} catch {
|
|
1287
|
+
/* ignore */
|
|
1288
|
+
}
|
|
1289
|
+
throw error;
|
|
1290
|
+
}
|
|
1291
|
+
}
|
|
1292
|
+
|
|
1293
|
+
export function writeReceiptPendingMarker({
|
|
1294
|
+
memoryRoot,
|
|
1295
|
+
eventId,
|
|
1296
|
+
sessionPath = null,
|
|
1297
|
+
receipt = null,
|
|
1298
|
+
error = null,
|
|
1299
|
+
now = new Date(),
|
|
1300
|
+
} = {}) {
|
|
1301
|
+
const id = asText(eventId);
|
|
1302
|
+
if (!id) return { ok: false, code: 'MARKER_NO_EVENT_ID', written: [] };
|
|
1303
|
+
const slim = receipt && typeof receipt === 'object' ? { ...receipt } : null;
|
|
1304
|
+
if (slim) delete slim.text;
|
|
1305
|
+
const payload = {
|
|
1306
|
+
kind: RECEIPT_PENDING_KIND,
|
|
1307
|
+
version: 1,
|
|
1308
|
+
at: new Date(now).toISOString(),
|
|
1309
|
+
eventId: id,
|
|
1310
|
+
memoryRoot: asText(memoryRoot),
|
|
1311
|
+
statePath: memoryRoot ? surgeryStatePath(memoryRoot) : null,
|
|
1312
|
+
sessionPath: asText(sessionPath),
|
|
1313
|
+
receipt: slim,
|
|
1314
|
+
error: error == null ? null : String(error?.message ?? error),
|
|
1315
|
+
};
|
|
1316
|
+
const written = [];
|
|
1317
|
+
const errors = [];
|
|
1318
|
+
if (memoryRoot) {
|
|
1319
|
+
const file = receiptPendingMarkerPath(memoryRoot, id);
|
|
1320
|
+
try {
|
|
1321
|
+
writeMarkerFile(file, payload);
|
|
1322
|
+
written.push(file);
|
|
1323
|
+
} catch (failure) {
|
|
1324
|
+
errors.push({ path: file, message: String(failure?.message ?? failure) });
|
|
1325
|
+
}
|
|
1326
|
+
}
|
|
1327
|
+
const temp = receiptPendingTempMarkerPath(id);
|
|
1328
|
+
try {
|
|
1329
|
+
writeMarkerFile(temp, payload);
|
|
1330
|
+
written.push(temp);
|
|
1331
|
+
} catch (failure) {
|
|
1332
|
+
errors.push({ path: temp, message: String(failure?.message ?? failure) });
|
|
1333
|
+
}
|
|
1334
|
+
return {
|
|
1335
|
+
ok: written.length > 0,
|
|
1336
|
+
code: written.length > 0 ? 'MARKER_WRITTEN' : 'MARKER_WRITE_FAILED',
|
|
1337
|
+
written,
|
|
1338
|
+
errors,
|
|
1339
|
+
};
|
|
1340
|
+
}
|
|
1341
|
+
|
|
1342
|
+
function readMarker(file) {
|
|
1343
|
+
try {
|
|
1344
|
+
const parsed = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
1345
|
+
return parsed && typeof parsed === 'object' && parsed.kind === RECEIPT_PENDING_KIND ? parsed : null;
|
|
1346
|
+
} catch {
|
|
1347
|
+
return null;
|
|
1348
|
+
}
|
|
1349
|
+
}
|
|
1350
|
+
|
|
1351
|
+
function listMarkerFiles(dir) {
|
|
1352
|
+
try {
|
|
1353
|
+
return fs.readdirSync(dir).filter((name) => name.endsWith('.json')).sort();
|
|
1354
|
+
} catch {
|
|
1355
|
+
return [];
|
|
1356
|
+
}
|
|
1357
|
+
}
|
|
1358
|
+
|
|
1359
|
+
export function readReceiptPendingMarkers({ memoryRoot } = {}) {
|
|
1360
|
+
const markers = [];
|
|
1361
|
+
const seen = new Set();
|
|
1362
|
+
if (memoryRoot) {
|
|
1363
|
+
const dir = path.join(longliveDir(memoryRoot), RECEIPT_PENDING_DIR);
|
|
1364
|
+
for (const name of listMarkerFiles(dir)) {
|
|
1365
|
+
const file = path.join(dir, name);
|
|
1366
|
+
const payload = readMarker(file);
|
|
1367
|
+
if (!payload || seen.has(payload.eventId)) continue;
|
|
1368
|
+
seen.add(payload.eventId);
|
|
1369
|
+
markers.push({ ...payload, path: file });
|
|
1370
|
+
}
|
|
1371
|
+
}
|
|
1372
|
+
const tempDir = path.join(os.tmpdir(), RECEIPT_PENDING_TEMP_DIR);
|
|
1373
|
+
for (const name of listMarkerFiles(tempDir)) {
|
|
1374
|
+
const file = path.join(tempDir, name);
|
|
1375
|
+
const payload = readMarker(file);
|
|
1376
|
+
if (!payload || seen.has(payload.eventId)) continue;
|
|
1377
|
+
// A temp marker belongs to exactly one memory root; never let another
|
|
1378
|
+
// profile's leftover marker repair this one.
|
|
1379
|
+
if (memoryRoot && asText(payload.memoryRoot) && !sameFilePath(payload.memoryRoot, memoryRoot)) continue;
|
|
1380
|
+
seen.add(payload.eventId);
|
|
1381
|
+
markers.push({ ...payload, path: file });
|
|
1382
|
+
}
|
|
1383
|
+
return markers.sort((left, right) => String(right.at).localeCompare(String(left.at)));
|
|
1384
|
+
}
|
|
1385
|
+
|
|
1386
|
+
export function clearReceiptPendingMarker({ memoryRoot, eventId } = {}) {
|
|
1387
|
+
const removed = [];
|
|
1388
|
+
const files = [receiptPendingTempMarkerPath(eventId)];
|
|
1389
|
+
if (memoryRoot) files.unshift(receiptPendingMarkerPath(memoryRoot, eventId));
|
|
1390
|
+
for (const file of files) {
|
|
1391
|
+
try {
|
|
1392
|
+
fs.unlinkSync(file);
|
|
1393
|
+
removed.push(file);
|
|
1394
|
+
} catch {
|
|
1395
|
+
/* absent is fine */
|
|
1396
|
+
}
|
|
1397
|
+
}
|
|
1398
|
+
return { ok: true, removed };
|
|
1399
|
+
}
|
|
1400
|
+
|
|
1401
|
+
// ---------------------------------------------------------------------------
|
|
1402
|
+
// R3-03: cross-process claim so two hosts never inject the fallback twice
|
|
1403
|
+
// ---------------------------------------------------------------------------
|
|
1404
|
+
// `agent/pre-step` runs the handler, then an async `await next()`; two hosts
|
|
1405
|
+
// loading the same memory root can both reach the append. The claim is an
|
|
1406
|
+
// exclusive-create lock carrying host + pid + timestamp, with a TTL so a
|
|
1407
|
+
// crashed holder (or another machine) cannot wedge it forever.
|
|
1408
|
+
export const FALLBACK_CLAIM_FILENAME = 'surgery-fallback-inject.lock';
|
|
1409
|
+
export const FALLBACK_CLAIM_KIND = 'longlive-surgery-fallback-inject';
|
|
1410
|
+
export const FALLBACK_CLAIM_TTL_MS = 60 * 1000;
|
|
1411
|
+
|
|
1412
|
+
function fallbackClaimPath(memoryRoot) {
|
|
1413
|
+
return path.join(longliveDir(memoryRoot), FALLBACK_CLAIM_FILENAME);
|
|
1414
|
+
}
|
|
1415
|
+
|
|
1416
|
+
function processAlive(pid) {
|
|
1417
|
+
const value = Number(pid);
|
|
1418
|
+
if (!Number.isInteger(value) || value <= 0) return false;
|
|
1419
|
+
try {
|
|
1420
|
+
process.kill(value, 0);
|
|
1421
|
+
return true;
|
|
1422
|
+
} catch (error) {
|
|
1423
|
+
return error?.code === 'EPERM';
|
|
1424
|
+
}
|
|
1425
|
+
}
|
|
1426
|
+
|
|
1427
|
+
function claimExpired(claim, now, ttlMs) {
|
|
1428
|
+
const at = Date.parse(claim?.at);
|
|
1429
|
+
if (!Number.isFinite(at)) return true;
|
|
1430
|
+
const age = new Date(now).getTime() - at;
|
|
1431
|
+
// Too old is stale; far in the future is a clock we cannot reason about.
|
|
1432
|
+
if (age > ttlMs || age < -ttlMs) return true;
|
|
1433
|
+
if (asText(claim?.host) === os.hostname() && !processAlive(claim?.pid)) return true;
|
|
1434
|
+
return false;
|
|
1435
|
+
}
|
|
1436
|
+
|
|
1437
|
+
export function claimFallbackInjection({
|
|
1438
|
+
memoryRoot,
|
|
1439
|
+
now = new Date(),
|
|
1440
|
+
host = os.hostname(),
|
|
1441
|
+
pid = process.pid,
|
|
1442
|
+
ttlMs = FALLBACK_CLAIM_TTL_MS,
|
|
1443
|
+
} = {}) {
|
|
1444
|
+
if (!memoryRoot) return { ok: false, code: 'NO_MEMORY_ROOT' };
|
|
1445
|
+
const file = fallbackClaimPath(memoryRoot);
|
|
1446
|
+
const claim = {
|
|
1447
|
+
kind: FALLBACK_CLAIM_KIND,
|
|
1448
|
+
host: String(host),
|
|
1449
|
+
pid: Number(pid),
|
|
1450
|
+
at: new Date(now).toISOString(),
|
|
1451
|
+
ttlMs: Number(ttlMs),
|
|
1452
|
+
};
|
|
1453
|
+
const payload = `${JSON.stringify(claim)}\n`;
|
|
1454
|
+
try {
|
|
1455
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
1456
|
+
} catch {
|
|
1457
|
+
/* the open below reports the real failure */
|
|
1458
|
+
}
|
|
1459
|
+
for (let attempt = 0; attempt < 2; attempt += 1) {
|
|
1460
|
+
let fd = null;
|
|
1461
|
+
try {
|
|
1462
|
+
fd = fs.openSync(file, 'wx');
|
|
1463
|
+
fs.writeFileSync(fd, payload);
|
|
1464
|
+
fs.fsyncSync(fd);
|
|
1465
|
+
fs.closeSync(fd);
|
|
1466
|
+
fd = null;
|
|
1467
|
+
return { ok: true, code: 'CLAIMED', path: file, claim };
|
|
1468
|
+
} catch (error) {
|
|
1469
|
+
if (fd != null) {
|
|
1470
|
+
try {
|
|
1471
|
+
fs.closeSync(fd);
|
|
1472
|
+
} catch {
|
|
1473
|
+
/* ignore */
|
|
1474
|
+
}
|
|
1475
|
+
}
|
|
1476
|
+
if (error?.code !== 'EEXIST') {
|
|
1477
|
+
return { ok: false, code: 'CLAIM_WRITE_FAILED', path: file, message: String(error?.message ?? error) };
|
|
1478
|
+
}
|
|
1479
|
+
let holder = null;
|
|
1480
|
+
try {
|
|
1481
|
+
holder = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
1482
|
+
} catch {
|
|
1483
|
+
holder = null;
|
|
1484
|
+
}
|
|
1485
|
+
if (holder && !claimExpired(holder, now, ttlMs)) {
|
|
1486
|
+
try {
|
|
1487
|
+
appendAudit(memoryRoot, {
|
|
1488
|
+
action: 'surgery-fallback-inject',
|
|
1489
|
+
object: `${asText(holder.host) ?? '?'}:${holder.pid ?? '?'}`,
|
|
1490
|
+
result: 'skipped-concurrent',
|
|
1491
|
+
now,
|
|
1492
|
+
});
|
|
1493
|
+
} catch {
|
|
1494
|
+
/* audit is best effort; the skip still happened */
|
|
1495
|
+
}
|
|
1496
|
+
return { ok: false, code: 'skipped-concurrent', path: file, holder };
|
|
1497
|
+
}
|
|
1498
|
+
try {
|
|
1499
|
+
fs.unlinkSync(file);
|
|
1500
|
+
} catch {
|
|
1501
|
+
/* another process replaced it; loop once more */
|
|
1502
|
+
}
|
|
1503
|
+
}
|
|
1504
|
+
}
|
|
1505
|
+
try {
|
|
1506
|
+
appendAudit(memoryRoot, { action: 'surgery-fallback-inject', object: '-', result: 'skipped-concurrent', now });
|
|
1507
|
+
} catch {
|
|
1508
|
+
/* ignore */
|
|
1509
|
+
}
|
|
1510
|
+
return { ok: false, code: 'skipped-concurrent', path: file, holder: null };
|
|
1511
|
+
}
|
|
1512
|
+
|
|
1513
|
+
export function releaseFallbackInjectionClaim({ memoryRoot, claim } = {}) {
|
|
1514
|
+
if (!memoryRoot || !claim) return { ok: false, code: 'NO_CLAIM' };
|
|
1515
|
+
const file = fallbackClaimPath(memoryRoot);
|
|
1516
|
+
let holder = null;
|
|
1517
|
+
try {
|
|
1518
|
+
holder = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
1519
|
+
} catch {
|
|
1520
|
+
return { ok: true, released: false, reason: 'absent' };
|
|
1521
|
+
}
|
|
1522
|
+
const sameHolder =
|
|
1523
|
+
asText(holder?.host) === asText(claim.host) &&
|
|
1524
|
+
Number(holder?.pid) === Number(claim.pid) &&
|
|
1525
|
+
String(holder?.at) === String(claim.at);
|
|
1526
|
+
if (!sameHolder) return { ok: false, code: 'NOT_HOLDER', path: file };
|
|
1527
|
+
try {
|
|
1528
|
+
fs.unlinkSync(file);
|
|
1529
|
+
return { ok: true, released: true, path: file };
|
|
1530
|
+
} catch (error) {
|
|
1531
|
+
return { ok: false, code: 'RELEASE_FAILED', path: file, message: String(error?.message ?? error) };
|
|
1532
|
+
}
|
|
1533
|
+
}
|
|
1534
|
+
|
|
1535
|
+
/**
|
|
1536
|
+
* R4-01: record why this host did not inject the fallback receipt after it had
|
|
1537
|
+
* already registered the hook. `skipped-concurrent` is written by the claim
|
|
1538
|
+
* itself; `skipped-already` is written here when the second state read (or the
|
|
1539
|
+
* atomic mark) shows another host/start already injected. Audit is best effort:
|
|
1540
|
+
* a broken audit log must never turn a safe skip into a failed turn.
|
|
1541
|
+
*/
|
|
1542
|
+
export function recordFallbackInjectionSkip({ memoryRoot, result = 'skipped-already', now = new Date() } = {}) {
|
|
1543
|
+
if (!memoryRoot) return { ok: false, code: 'NO_MEMORY_ROOT' };
|
|
1544
|
+
if (result !== 'skipped-concurrent' && result !== 'skipped-already') {
|
|
1545
|
+
return { ok: false, code: 'INVALID_RESULT' };
|
|
1546
|
+
}
|
|
1547
|
+
try {
|
|
1548
|
+
appendAudit(memoryRoot, { action: 'surgery-fallback-inject', object: 'state', result, now });
|
|
1549
|
+
return { ok: true, result };
|
|
1550
|
+
} catch (error) {
|
|
1551
|
+
return { ok: false, code: 'AUDIT_WRITE_FAILED', message: String(error?.message ?? error) };
|
|
1552
|
+
}
|
|
1553
|
+
}
|
|
1554
|
+
|
|
1555
|
+
function sameFilePath(left, right) {
|
|
1556
|
+
if (!left || !right) return false;
|
|
1557
|
+
const a = path.resolve(left);
|
|
1558
|
+
const b = path.resolve(right);
|
|
1559
|
+
return process.platform === 'win32' ? a.toLowerCase() === b.toLowerCase() : a === b;
|
|
1560
|
+
}
|
|
1561
|
+
|
|
1562
|
+
function isInsidePath(root, file) {
|
|
1563
|
+
if (!root || !file) return false;
|
|
1564
|
+
const relative = path.relative(path.resolve(root), path.resolve(file));
|
|
1565
|
+
return relative !== '' && !relative.startsWith('..') && !path.isAbsolute(relative);
|
|
1566
|
+
}
|
|
1567
|
+
|
|
1568
|
+
function receiptTextFromEvent(event) {
|
|
1569
|
+
const content = event?.data?.content;
|
|
1570
|
+
if (!Array.isArray(content)) return null;
|
|
1571
|
+
const block = content.find((item) => item?.type === 'text' && typeof item.text === 'string');
|
|
1572
|
+
return block?.text ?? null;
|
|
1573
|
+
}
|
|
1574
|
+
|
|
1575
|
+
function persistReceiptState(memoryRoot, state, receipt, now, event) {
|
|
1576
|
+
const at = new Date(now).toISOString();
|
|
1577
|
+
const nextState = {
|
|
1578
|
+
...state,
|
|
1579
|
+
receipt,
|
|
1580
|
+
updatedAt: at,
|
|
1581
|
+
history: [
|
|
1582
|
+
...(Array.isArray(state.history) ? state.history : []),
|
|
1583
|
+
{ phase: state.phase ?? null, at, event },
|
|
1584
|
+
],
|
|
1585
|
+
};
|
|
1586
|
+
writeFileAtomic(memoryRoot, surgeryStatePath(memoryRoot), `${JSON.stringify(nextState, null, 2)}\n`, {
|
|
1587
|
+
backup: true,
|
|
1588
|
+
now,
|
|
1589
|
+
});
|
|
1590
|
+
return nextState;
|
|
1591
|
+
}
|
|
1592
|
+
|
|
1593
|
+
/**
|
|
1594
|
+
* Record that the pre-step hook injected the fallback receipt once. Idempotent
|
|
1595
|
+
* and atomic: the second call returns `alreadyMarked` without touching the
|
|
1596
|
+
* state file. Never overwrites a real `receipt.written === true`.
|
|
1597
|
+
*/
|
|
1598
|
+
export function markReceiptFallbackInjected({ memoryRoot, now = new Date() } = {}) {
|
|
1599
|
+
if (!memoryRoot) return { ok: false, code: 'NO_MEMORY_ROOT' };
|
|
1600
|
+
const initial = readSurgeryState(memoryRoot);
|
|
1601
|
+
if (!initial.exists || !initial.state) return { ok: false, code: 'SURGERY_STATE_MISSING' };
|
|
1602
|
+
if (isDryRunState(initial.state)) return dryRunReceiptRefusal(memoryRoot);
|
|
1603
|
+
if (initial.state.receipt?.written === true) {
|
|
1604
|
+
return { ok: true, alreadyMarked: false, written: true, receipt: initial.state.receipt };
|
|
1605
|
+
}
|
|
1606
|
+
if (initial.state.receipt?.fallbackInjected === true) {
|
|
1607
|
+
return { ok: true, alreadyMarked: true, receipt: initial.state.receipt };
|
|
1608
|
+
}
|
|
1609
|
+
let lock = null;
|
|
1610
|
+
try {
|
|
1611
|
+
lock = acquireReceiptLock(memoryRoot, now);
|
|
1612
|
+
} catch (error) {
|
|
1613
|
+
return { ok: false, code: 'RECEIPT_LOCK_FAILED', message: String(error?.message ?? error) };
|
|
1614
|
+
}
|
|
1615
|
+
if (!lock) return { ok: false, code: 'RECEIPT_BUSY', message: '另一个进程正在写手术回执' };
|
|
1616
|
+
try {
|
|
1617
|
+
const stateRead = readSurgeryState(memoryRoot);
|
|
1618
|
+
if (!stateRead.exists || !stateRead.state) return { ok: false, code: 'SURGERY_STATE_MISSING' };
|
|
1619
|
+
const state = stateRead.state;
|
|
1620
|
+
if (state.receipt?.written === true) {
|
|
1621
|
+
return { ok: true, alreadyMarked: false, written: true, receipt: state.receipt };
|
|
1622
|
+
}
|
|
1623
|
+
if (state.receipt?.fallbackInjected === true) {
|
|
1624
|
+
return { ok: true, alreadyMarked: true, receipt: state.receipt };
|
|
1625
|
+
}
|
|
1626
|
+
const at = new Date(now).toISOString();
|
|
1627
|
+
const receipt = {
|
|
1628
|
+
...(state.receipt && typeof state.receipt === 'object' ? state.receipt : {}),
|
|
1629
|
+
written: false,
|
|
1630
|
+
fallbackInjected: true,
|
|
1631
|
+
fallbackVia: 'plugin-pre-step',
|
|
1632
|
+
fallbackAt: at,
|
|
1633
|
+
};
|
|
1634
|
+
persistReceiptState(memoryRoot, state, receipt, now, 'receipt-fallback');
|
|
1635
|
+
return { ok: true, alreadyMarked: false, receipt };
|
|
1636
|
+
} catch (error) {
|
|
1637
|
+
return {
|
|
1638
|
+
ok: false,
|
|
1639
|
+
code: 'RECEIPT_STATE_WRITE_FAILED',
|
|
1640
|
+
message: `${surgeryStatePath(memoryRoot)}: ${error?.message ?? error}`,
|
|
1641
|
+
};
|
|
1642
|
+
} finally {
|
|
1643
|
+
lock.release();
|
|
1644
|
+
}
|
|
1645
|
+
}
|
|
1646
|
+
|
|
1647
|
+
function isDryRunState(state) {
|
|
1648
|
+
return state?.dryRun === true || asText(state?.phase) === 'dryrun';
|
|
1649
|
+
}
|
|
1650
|
+
|
|
1651
|
+
function dryRunReceiptRefusal(memoryRoot) {
|
|
1652
|
+
return {
|
|
1653
|
+
ok: false,
|
|
1654
|
+
code: 'E_RECEIPT_DRYRUN',
|
|
1655
|
+
message:
|
|
1656
|
+
'这不是真实手术:上次是 -DryRun 演练(没有关闭宿主、没有剪切字节、没有备份)。' +
|
|
1657
|
+
'没有回执可写,状态也不需要修复;要真正截断时去掉 -DryRun 重跑即可。',
|
|
1658
|
+
statePath: surgeryStatePath(memoryRoot),
|
|
1659
|
+
dryRun: true,
|
|
1660
|
+
};
|
|
1661
|
+
}
|
|
1662
|
+
|
|
1663
|
+
/**
|
|
1664
|
+
* Append the visible receipt to the session and record it in the stage file.
|
|
1665
|
+
*
|
|
1666
|
+
* R2-04 single writer: a short-lived lock next to the state file serialises
|
|
1667
|
+
* launcher and plugin writers. Idempotent on two levels: `receipt.written`
|
|
1668
|
+
* short-circuits, and a retry after a state-write failure finds the already
|
|
1669
|
+
* appended deterministic event id and only repairs the state file.
|
|
1670
|
+
*/
|
|
1671
|
+
export function writeSurgeryReceipt({ sessionPath, memoryRoot, now = new Date(), via = 'surgery-script' } = {}) {
|
|
1672
|
+
if (!memoryRoot) return { ok: false, code: 'NO_MEMORY_ROOT', message: '缺少记忆根,无法定位 state' };
|
|
1673
|
+
const initial = readSurgeryState(memoryRoot);
|
|
1674
|
+
if (!initial.exists) {
|
|
1675
|
+
return { ok: false, code: 'SURGERY_STATE_MISSING', message: `没有 ${surgeryStatePath(memoryRoot)}` };
|
|
1676
|
+
}
|
|
1677
|
+
// R3-01: `--write-receipt` on a rehearsal is a category error, not a broken
|
|
1678
|
+
// surgery. Answer with a distinct code so scripts can tell the operator
|
|
1679
|
+
// "this was a dry run" instead of "永久拒绝 / 需要人工处理".
|
|
1680
|
+
if (isDryRunState(initial.state)) return dryRunReceiptRefusal(memoryRoot);
|
|
1681
|
+
if (initial.state?.receipt?.written === true) {
|
|
1682
|
+
return { ok: true, alreadyWritten: true, receipt: initial.state.receipt, text: asText(initial.state.receipt.text) };
|
|
1683
|
+
}
|
|
1684
|
+
|
|
1685
|
+
let lock = null;
|
|
1686
|
+
try {
|
|
1687
|
+
lock = acquireReceiptLock(memoryRoot, now);
|
|
1688
|
+
} catch (error) {
|
|
1689
|
+
return { ok: false, code: 'RECEIPT_LOCK_FAILED', message: String(error?.message ?? error) };
|
|
1690
|
+
}
|
|
1691
|
+
if (!lock) {
|
|
1692
|
+
return { ok: false, code: 'RECEIPT_BUSY', message: '另一个进程正在写手术回执,稍后重试' };
|
|
1693
|
+
}
|
|
1694
|
+
try {
|
|
1695
|
+
return writeSurgeryReceiptLocked({ sessionPath, memoryRoot, now, via });
|
|
1696
|
+
} finally {
|
|
1697
|
+
lock.release();
|
|
1698
|
+
}
|
|
1699
|
+
}
|
|
1700
|
+
|
|
1701
|
+
function writeSurgeryReceiptLocked({ sessionPath, memoryRoot, now, via }) {
|
|
1702
|
+
// Re-read under the lock: another writer may have finished between the
|
|
1703
|
+
// optimistic check above and lock acquisition.
|
|
1704
|
+
const stateRead = readSurgeryState(memoryRoot);
|
|
1705
|
+
if (!stateRead.exists || !stateRead.state) {
|
|
1706
|
+
return { ok: false, code: 'SURGERY_STATE_MISSING', message: `没有 ${surgeryStatePath(memoryRoot)}` };
|
|
1707
|
+
}
|
|
1708
|
+
const state = stateRead.state;
|
|
1709
|
+
if (isDryRunState(state)) return dryRunReceiptRefusal(memoryRoot);
|
|
1710
|
+
if (state.receipt?.written === true) {
|
|
1711
|
+
return { ok: true, alreadyWritten: true, receipt: state.receipt, text: asText(state.receipt.text) };
|
|
1712
|
+
}
|
|
1713
|
+
|
|
1714
|
+
const candidate = asText(sessionPath);
|
|
1715
|
+
const stateSession = asText(state.sessionPath);
|
|
1716
|
+
// R3-02: a state write that failed may still have lost sessionPath with it;
|
|
1717
|
+
// a pending marker written at that moment carries the path forward.
|
|
1718
|
+
const pendingMarkers = readReceiptPendingMarkers({ memoryRoot });
|
|
1719
|
+
const markerSession = pendingMarkers.map((marker) => asText(marker.sessionPath)).find(Boolean) ?? null;
|
|
1720
|
+
const file = candidate ?? stateSession ?? markerSession;
|
|
1721
|
+
const fromMarker = !candidate && !stateSession && Boolean(markerSession);
|
|
1722
|
+
if (!file) return { ok: false, code: 'SESSION_PATH_MISSING', message: 'state 与会话参数里都没有 sessionPath' };
|
|
1723
|
+
|
|
1724
|
+
// R2-05: only the current session (state.sessionPath) or another file inside
|
|
1725
|
+
// <DSH_HOME>/sessions carrying the same session id may receive a receipt.
|
|
1726
|
+
if (candidate && !sameFilePath(candidate, stateSession)) {
|
|
1727
|
+
if (!isInsidePath(path.join(dshHome(), 'sessions'), candidate)) {
|
|
1728
|
+
return {
|
|
1729
|
+
ok: false,
|
|
1730
|
+
code: 'E_RECEIPT_SESSION_OUTSIDE',
|
|
1731
|
+
message: '--write-receipt 只接受当前会话或 sessions 根内的会话文件',
|
|
1732
|
+
};
|
|
1733
|
+
}
|
|
1734
|
+
if (!stateSession) {
|
|
1735
|
+
return { ok: false, code: 'SESSION_PATH_MISSING', message: 'state 没有 sessionPath,无法确认目标会话' };
|
|
1736
|
+
}
|
|
1737
|
+
}
|
|
1738
|
+
|
|
1739
|
+
let buffer;
|
|
1740
|
+
let parsed;
|
|
1741
|
+
try {
|
|
1742
|
+
buffer = fs.readFileSync(file);
|
|
1743
|
+
parsed = parseSession(buffer);
|
|
1744
|
+
} catch (error) {
|
|
1745
|
+
return { ok: false, code: 'SESSION_UNREADABLE', message: `${file}: ${error?.message ?? error}` };
|
|
1746
|
+
}
|
|
1747
|
+
if ((candidate && !sameFilePath(candidate, stateSession)) || fromMarker) {
|
|
1748
|
+
const expectedId = asText(state.sessionId);
|
|
1749
|
+
const actualId = asText(parsed.header?.id);
|
|
1750
|
+
if (!expectedId || actualId !== expectedId) {
|
|
1751
|
+
return {
|
|
1752
|
+
ok: false,
|
|
1753
|
+
code: 'E_RECEIPT_SESSION_MISMATCH',
|
|
1754
|
+
message: '目标会话的 header.id 与 state.sessionId 不一致',
|
|
1755
|
+
};
|
|
1756
|
+
}
|
|
1757
|
+
}
|
|
1758
|
+
|
|
1759
|
+
// R3-02: scan for an already-appended receipt *before* the needs-attention
|
|
1760
|
+
// gate. When the append landed but the state write failed, the session
|
|
1761
|
+
// already holds the deterministic event and a marker sits on disk; blocking
|
|
1762
|
+
// on the report first made the repair branch unreachable and turned a
|
|
1763
|
+
// recoverable state into a permanent RECEIPT_BLOCKED_NEEDS_ATTENTION.
|
|
1764
|
+
const receiptKey =
|
|
1765
|
+
asText(state.surgeryId) ?? asText(state.startedAt) ?? asText(state.sessionId) ?? stampToken(now);
|
|
1766
|
+
const eventId = `surgery-receipt-${receiptKey}`;
|
|
1767
|
+
const existingIndex = parsed.events.findIndex(
|
|
1768
|
+
(event) => event?.type === 'user/message' && asText(event?.data?.id) === eventId,
|
|
1769
|
+
);
|
|
1770
|
+
|
|
1771
|
+
if (existingIndex >= 0) {
|
|
1772
|
+
// The append landed but the state write did not. Repair the state instead
|
|
1773
|
+
// of appending a second receipt.
|
|
1774
|
+
const text = receiptTextFromEvent(parsed.events[existingIndex]);
|
|
1775
|
+
const messages = messageCount(parsed.events);
|
|
1776
|
+
const receipt = {
|
|
1777
|
+
written: true,
|
|
1778
|
+
via,
|
|
1779
|
+
at: new Date(now).toISOString(),
|
|
1780
|
+
sessionPath: file,
|
|
1781
|
+
seq: existingIndex,
|
|
1782
|
+
eventId,
|
|
1783
|
+
backupPath: null,
|
|
1784
|
+
text,
|
|
1785
|
+
after: {
|
|
1786
|
+
bytes: buffer.length,
|
|
1787
|
+
events: parsed.events.length,
|
|
1788
|
+
messages,
|
|
1789
|
+
sha256: sha256(buffer),
|
|
1790
|
+
},
|
|
1791
|
+
repairedState: true,
|
|
1792
|
+
};
|
|
1793
|
+
try {
|
|
1794
|
+
persistReceiptState(memoryRoot, state, receipt, now, 'receipt-repaired');
|
|
1795
|
+
} catch (error) {
|
|
1796
|
+
const marker = writeReceiptPendingMarker({
|
|
1797
|
+
memoryRoot,
|
|
1798
|
+
eventId,
|
|
1799
|
+
sessionPath: file,
|
|
1800
|
+
receipt: { ...receipt, stateWritten: false },
|
|
1801
|
+
error,
|
|
1802
|
+
now,
|
|
1803
|
+
});
|
|
1804
|
+
return {
|
|
1805
|
+
ok: false,
|
|
1806
|
+
code: 'RECEIPT_STATE_WRITE_FAILED',
|
|
1807
|
+
message: `${surgeryStatePath(memoryRoot)}: ${error?.message ?? error}`,
|
|
1808
|
+
receipt: { ...receipt, stateWritten: false },
|
|
1809
|
+
pendingMarker: marker.ok ? marker.written[0] ?? null : null,
|
|
1810
|
+
pendingMarkerError: marker.ok ? null : marker.errors?.[0]?.message ?? 'marker write failed',
|
|
1811
|
+
};
|
|
1812
|
+
}
|
|
1813
|
+
clearReceiptPendingMarker({ memoryRoot, eventId });
|
|
1814
|
+
return { ok: true, alreadyWritten: true, repairedState: true, receipt, text };
|
|
1815
|
+
}
|
|
1816
|
+
|
|
1817
|
+
const report = buildRecoveryReport({ memoryRoot, now, stateRead });
|
|
1818
|
+
// R2-09: never turn a needs-attention state into a success receipt. The
|
|
1819
|
+
// state file is left untouched so the warning stays visible.
|
|
1820
|
+
if (report.classification === CLASSIFICATIONS.NEEDS_ATTENTION) {
|
|
1821
|
+
return {
|
|
1822
|
+
ok: false,
|
|
1823
|
+
code: 'RECEIPT_BLOCKED_NEEDS_ATTENTION',
|
|
1824
|
+
message: `上次手术结果异常(${report.reasonCode}),不能写成功回执;先人工核对`,
|
|
1825
|
+
classification: report.classification,
|
|
1826
|
+
reasonCode: report.reasonCode,
|
|
1827
|
+
};
|
|
1828
|
+
}
|
|
1829
|
+
|
|
1830
|
+
const seq = parsed.events.length;
|
|
1831
|
+
const text = receiptText(report, { appendingReceipt: true, seq });
|
|
1832
|
+
const event = buildReceiptEvent({ text, seq, now: now.getTime(), id: eventId });
|
|
1833
|
+
|
|
1834
|
+
let next;
|
|
1835
|
+
let verified;
|
|
1836
|
+
try {
|
|
1837
|
+
next = encodeSession(parsed.header, [...parsed.events, event]);
|
|
1838
|
+
verified = parseSession(next);
|
|
1839
|
+
} catch (error) {
|
|
1840
|
+
return { ok: false, code: 'RECEIPT_ENCODE_FAILED', message: String(error?.message ?? error) };
|
|
1841
|
+
}
|
|
1842
|
+
if (verified.events.length !== seq + 1) {
|
|
1843
|
+
return { ok: false, code: 'RECEIPT_VERIFY_FAILED', message: '回执写入后事件数不对' };
|
|
1844
|
+
}
|
|
1845
|
+
const messages = messageCount(verified.events);
|
|
1846
|
+
if (messages !== (messageCount(parsed.events) ?? 0) + 1) {
|
|
1847
|
+
return { ok: false, code: 'RECEIPT_VERIFY_FAILED', message: '回执写入后消息数不对' };
|
|
1848
|
+
}
|
|
1849
|
+
|
|
1850
|
+
const stamp = stampToken(now);
|
|
1851
|
+
const backupPath = `${file}.bak-receipt-${stamp}`;
|
|
1852
|
+
try {
|
|
1853
|
+
fs.copyFileSync(file, backupPath);
|
|
1854
|
+
} catch (error) {
|
|
1855
|
+
return { ok: false, code: 'RECEIPT_BACKUP_FAILED', message: `${backupPath}: ${error?.message ?? error}` };
|
|
1856
|
+
}
|
|
1857
|
+
try {
|
|
1858
|
+
writeSessionAtomic(file, next);
|
|
1859
|
+
} catch (error) {
|
|
1860
|
+
try {
|
|
1861
|
+
fs.copyFileSync(backupPath, file);
|
|
1862
|
+
} catch {
|
|
1863
|
+
/* the backup path is reported below either way */
|
|
1864
|
+
}
|
|
1865
|
+
return { ok: false, code: 'RECEIPT_WRITE_FAILED', message: `${file}: ${error?.message ?? error}`, backupPath };
|
|
1866
|
+
}
|
|
1867
|
+
|
|
1868
|
+
const receipt = {
|
|
1869
|
+
written: true,
|
|
1870
|
+
via,
|
|
1871
|
+
at: new Date(now).toISOString(),
|
|
1872
|
+
sessionPath: file,
|
|
1873
|
+
seq,
|
|
1874
|
+
eventId,
|
|
1875
|
+
backupPath,
|
|
1876
|
+
text,
|
|
1877
|
+
after: {
|
|
1878
|
+
bytes: next.length,
|
|
1879
|
+
events: verified.events.length,
|
|
1880
|
+
messages,
|
|
1881
|
+
sha256: sha256(next),
|
|
1882
|
+
},
|
|
1883
|
+
};
|
|
1884
|
+
try {
|
|
1885
|
+
persistReceiptState(memoryRoot, state, receipt, now, 'receipt');
|
|
1886
|
+
} catch (error) {
|
|
1887
|
+
// R3-02: leave a trace the next run can find, even though the state file
|
|
1888
|
+
// itself is unwritable right now.
|
|
1889
|
+
const marker = writeReceiptPendingMarker({
|
|
1890
|
+
memoryRoot,
|
|
1891
|
+
eventId,
|
|
1892
|
+
sessionPath: file,
|
|
1893
|
+
receipt: { ...receipt, stateWritten: false },
|
|
1894
|
+
error,
|
|
1895
|
+
now,
|
|
1896
|
+
});
|
|
1897
|
+
return {
|
|
1898
|
+
ok: false,
|
|
1899
|
+
code: 'RECEIPT_STATE_WRITE_FAILED',
|
|
1900
|
+
message: `${surgeryStatePath(memoryRoot)}: ${error?.message ?? error}`,
|
|
1901
|
+
receipt: { ...receipt, stateWritten: false },
|
|
1902
|
+
pendingMarker: marker.ok ? marker.written[0] ?? null : null,
|
|
1903
|
+
pendingMarkerError: marker.ok ? null : marker.errors?.[0]?.message ?? 'marker write failed',
|
|
1904
|
+
};
|
|
1905
|
+
}
|
|
1906
|
+
clearReceiptPendingMarker({ memoryRoot, eventId });
|
|
1907
|
+
|
|
1908
|
+
return { ok: true, alreadyWritten: false, receipt, text };
|
|
1909
|
+
}
|