@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,1218 @@
|
|
|
1
|
+
// WP4b · apply nine-step write protocol (DESIGN §5.3a, F29/D31, K4/K8/K19/L-05).
|
|
2
|
+
//
|
|
3
|
+
// Steps (each numbered below in apply()):
|
|
4
|
+
// 1. acquire writer lease (fail → state "queued", not "busy")
|
|
5
|
+
// 2. re-read proposal from disk; it must still be approved
|
|
6
|
+
// 3. re-read target sha; it must equal baseSha, else conflict with zero writes
|
|
7
|
+
// 4. WAL apply.begin(baseSha, afterSha, snapshot) + fsync
|
|
8
|
+
// 5. snapshot original bytes to disk; verify sha == baseSha
|
|
9
|
+
// 6. write <target>.tmp-<proposalId>, fsync, close — no rename yet
|
|
10
|
+
// 7. last recheck: third target sha read + tmp complete; mismatch → delete tmp,
|
|
11
|
+
// WAL apply.abort(owner-write-race), conflict, zero writes
|
|
12
|
+
// 8. rename + fsync(dir); readback must equal afterSha; else conflict +
|
|
13
|
+
// RESTORE_REQUIRED (record actual sha, never auto-rollback, D31)
|
|
14
|
+
// 9. release lease, advance queue, audit
|
|
15
|
+
//
|
|
16
|
+
// Writers never "repair" conflicting targets. A snapshot is evidence, not a
|
|
17
|
+
// rollback trigger.
|
|
18
|
+
|
|
19
|
+
import crypto from 'node:crypto';
|
|
20
|
+
import fs from 'node:fs';
|
|
21
|
+
import path from 'node:path';
|
|
22
|
+
|
|
23
|
+
import {
|
|
24
|
+
appendJsonLineDurable,
|
|
25
|
+
readProposal,
|
|
26
|
+
readTargetSnapshot,
|
|
27
|
+
scanProposalDir,
|
|
28
|
+
updateProposalStrict,
|
|
29
|
+
StoreError,
|
|
30
|
+
} from './store.mjs';import { ensureDir } from './paths.mjs';
|
|
31
|
+
import { sortQueueEntries } from './queue.mjs';
|
|
32
|
+
import { isSubagentCaller } from './caller.mjs';
|
|
33
|
+
|
|
34
|
+
const SNAPSHOT_KEEP_MS = 30 * 24 * 60 * 60 * 1000;
|
|
35
|
+
const TMP_MAX_AGE_MS = 60 * 60 * 1000;
|
|
36
|
+
|
|
37
|
+
class TestCrash extends Error {
|
|
38
|
+
constructor(phase) {
|
|
39
|
+
super(`test crash at ${phase}`);
|
|
40
|
+
this.code = 'E_TEST_CRASH';
|
|
41
|
+
this.phase = phase;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function isoNow(date) {
|
|
46
|
+
return date.toISOString();
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function sha256Buffer(buffer) {
|
|
50
|
+
// Bare lowercase hex: the public contract compares it to the file digest the
|
|
51
|
+
// host reports (N-01), and the `sha256:` prefix on persisted proposal content
|
|
52
|
+
// is a different field (contentSha), not a target digest.
|
|
53
|
+
return crypto.createHash('sha256').update(buffer).digest('hex');
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function ensureTrailingNewline(text) {
|
|
57
|
+
if (text === '') return '';
|
|
58
|
+
return text.endsWith('\n') ? text : `${text}\n`;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function trimTrailingBlank(text) {
|
|
62
|
+
return text.replace(/\n+$/u, '');
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Deterministic content transforms for the five proposal ops. DESIGN §7.2 fixes
|
|
67
|
+
* the targets but not the byte layout; this is the single documented layout.
|
|
68
|
+
* - journal.append / topic.append: keep the file, add one blank line, append the
|
|
69
|
+
* content block at EOF (missing file gets a `# <basename>` header).
|
|
70
|
+
* - state.section: replace the body of `## <title>` up to the next `## ` heading.
|
|
71
|
+
* - index.row: append exactly one row line at EOF.
|
|
72
|
+
* - handover.create: new file containing the content block.
|
|
73
|
+
*/
|
|
74
|
+
export function buildAfterContent(proposal, beforeText) {
|
|
75
|
+
const op = proposal.op;
|
|
76
|
+
const content = ensureTrailingNewline(String(proposal.content ?? ''));
|
|
77
|
+
const before = String(beforeText ?? '');
|
|
78
|
+
if (op === 'journal.append' || op === 'topic.append') {
|
|
79
|
+
if (before.trim() === '') {
|
|
80
|
+
const base = path.basename(proposal.target, '.md');
|
|
81
|
+
return `# ${base}\n\n${content}`;
|
|
82
|
+
}
|
|
83
|
+
return `${trimTrailingBlank(before)}\n\n${content}`;
|
|
84
|
+
}
|
|
85
|
+
if (op === 'state.section') {
|
|
86
|
+
const title = String(proposal.title ?? '').trim();
|
|
87
|
+
if (!title) throw new StoreError('E_BAD_CONTENT', 'state.section is missing its section title');
|
|
88
|
+
const lines = before.split('\n');
|
|
89
|
+
const start = lines.findIndex((line) => line.trim() === `## ${title}`.trim());
|
|
90
|
+
if (start === -1) throw new StoreError('E_BAD_CONTENT', `section not found: ${title}`);
|
|
91
|
+
let end = lines.length;
|
|
92
|
+
for (let index = start + 1; index < lines.length; index += 1) {
|
|
93
|
+
if (/^##\s+/u.test(lines[index])) { end = index; break; }
|
|
94
|
+
}
|
|
95
|
+
const head = lines.slice(0, start + 1);
|
|
96
|
+
const tail = lines.slice(end);
|
|
97
|
+
const bodyLines = content.replace(/\n$/u, '').split('\n');
|
|
98
|
+
const next = [...head, '', ...bodyLines, '', ...tail];
|
|
99
|
+
return ensureTrailingNewline(next.join('\n').replace(/\n{3,}/gu, '\n\n'));
|
|
100
|
+
}
|
|
101
|
+
if (op === 'index.row') {
|
|
102
|
+
const row = content.trim();
|
|
103
|
+
if (!row.startsWith('|')) throw new StoreError('E_BAD_CONTENT', 'index.row content must be a table row');
|
|
104
|
+
return `${trimTrailingBlank(before)}\n${row}\n`;
|
|
105
|
+
}
|
|
106
|
+
if (op === 'handover.create') {
|
|
107
|
+
return content;
|
|
108
|
+
}
|
|
109
|
+
throw new StoreError('E_BAD_CONTENT', `unsupported op: ${op}`);
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
export class Applier {
|
|
113
|
+
constructor({
|
|
114
|
+
paths = null,
|
|
115
|
+
vaultDir = paths?.vaultDir,
|
|
116
|
+
memoryRoot = null,
|
|
117
|
+
config = {},
|
|
118
|
+
lease = null,
|
|
119
|
+
wal = null,
|
|
120
|
+
queue = null,
|
|
121
|
+
wake = null,
|
|
122
|
+
audit = null,
|
|
123
|
+
now = () => new Date(),
|
|
124
|
+
logger = null,
|
|
125
|
+
testHooks = null,
|
|
126
|
+
caller = {},
|
|
127
|
+
onWarning = null,
|
|
128
|
+
} = {}) {
|
|
129
|
+
this.paths = paths;
|
|
130
|
+
this.vaultDir = vaultDir;
|
|
131
|
+
this.memoryRoot = memoryRoot ?? paths?.liveRoot ?? null;
|
|
132
|
+
this.proposalsDir = paths?.proposalsDir ?? path.join(this.vaultDir, 'proposals');
|
|
133
|
+
this.snapshotsDir = path.join(this.vaultDir, 'snapshots');
|
|
134
|
+
this.snapshotManifest = path.join(this.snapshotsDir, 'manifest.jsonl');
|
|
135
|
+
this.config = config;
|
|
136
|
+
this.audit = audit;
|
|
137
|
+
this.now = typeof now === 'function' ? now : () => new Date();
|
|
138
|
+
this.logger = logger;
|
|
139
|
+
this.testHooks = testHooks && typeof testHooks === 'object' ? testHooks : null;
|
|
140
|
+
this.caller = caller ?? {};
|
|
141
|
+
this.onWarning = typeof onWarning === 'function' ? onWarning : null;
|
|
142
|
+
this.runId = `apply-${process.pid}-${crypto.randomBytes(4).toString('hex')}`;
|
|
143
|
+
this.holder = {
|
|
144
|
+
sessionId: this.caller.sessionId ?? 'owner-cli',
|
|
145
|
+
runId: this.runId,
|
|
146
|
+
pid: process.pid,
|
|
147
|
+
host: 'local',
|
|
148
|
+
};
|
|
149
|
+
this.lease = lease;
|
|
150
|
+
this.wal = wal;
|
|
151
|
+
this.queue = queue;
|
|
152
|
+
this.wake = wake;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
#auditSafe(kind, data) {
|
|
156
|
+
try { this.audit?.(kind, data); } catch { /* ignore */ }
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
#warn(code) {
|
|
160
|
+
this.#auditSafe('warn', { code });
|
|
161
|
+
// D-CR17: warnings must reach the service status, not only the audit log.
|
|
162
|
+
try { this.onWarning?.(code); } catch { /* a warning sink must never break a write */ }
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
#scan() {
|
|
166
|
+
return scanProposalDir(this.proposalsDir);
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
#injected(name) {
|
|
170
|
+
const hooks = this.testHooks;
|
|
171
|
+
if (!hooks) return false;
|
|
172
|
+
const value = hooks[name];
|
|
173
|
+
if (value === true) {
|
|
174
|
+
hooks[name] = false;
|
|
175
|
+
return true;
|
|
176
|
+
}
|
|
177
|
+
if (typeof value === 'function') return value() === true;
|
|
178
|
+
return false;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
#updateProposal(id, mutate, { expectRev = null } = {}) {
|
|
182
|
+
return updateProposalStrict(this.proposalsDir, id, expectRev, (current) => {
|
|
183
|
+
const next = mutate(current) ?? current;
|
|
184
|
+
const { __file, ...clean } = next;
|
|
185
|
+
return clean;
|
|
186
|
+
}, { now: () => this.now() });
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
#readTarget(proposal) {
|
|
190
|
+
const absolute = path.resolve(this.memoryRoot ?? path.dirname(this.proposalsDir), proposal.target);
|
|
191
|
+
const snapshot = readTargetSnapshot(absolute);
|
|
192
|
+
if (!snapshot.ok) return { ok: false, code: snapshot.code, message: snapshot.message ?? null };
|
|
193
|
+
if (!snapshot.exists) return { ok: true, exists: false, sha256: null, bytes: 0, buffer: Buffer.alloc(0), text: '', absolute };
|
|
194
|
+
const buffer = fs.readFileSync(absolute);
|
|
195
|
+
return {
|
|
196
|
+
ok: true,
|
|
197
|
+
exists: true,
|
|
198
|
+
sha256: sha256Buffer(buffer),
|
|
199
|
+
bytes: buffer.length,
|
|
200
|
+
buffer,
|
|
201
|
+
text: buffer.toString('utf8'),
|
|
202
|
+
absolute,
|
|
203
|
+
};
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
#conflict(proposal, { code = 'E_BASE_MOVED', reason = 'base-moved', note = null, phase = null, extra = null } = {}) {
|
|
207
|
+
const next = this.#updateProposal(proposal.id, (current) => ({
|
|
208
|
+
...current,
|
|
209
|
+
status: 'conflict',
|
|
210
|
+
queue: { ...current.queue, lease: null, blockedReason: null },
|
|
211
|
+
conflict: { code, reason, phase, at: isoNow(this.now()), ...(extra ?? {}) },
|
|
212
|
+
result: current.result ?? null,
|
|
213
|
+
stateLog: [...(current.stateLog ?? []), {
|
|
214
|
+
at: isoNow(this.now()),
|
|
215
|
+
from: current.status,
|
|
216
|
+
to: 'conflict',
|
|
217
|
+
by: 'router',
|
|
218
|
+
note: note ?? reason,
|
|
219
|
+
}],
|
|
220
|
+
}), { expectRev: proposal.rev });
|
|
221
|
+
return next;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
#tmpPath(absolute, proposalId) {
|
|
225
|
+
return `${absolute}.tmp-${proposalId}`;
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
#fsyncDir(dir) {
|
|
229
|
+
try {
|
|
230
|
+
const fd = fs.openSync(dir, 'r');
|
|
231
|
+
try { fs.fsyncSync(fd); } finally { fs.closeSync(fd); }
|
|
232
|
+
} catch { /* directory fsync is best effort on Windows */ }
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
#snapshotName(proposal, target) {
|
|
236
|
+
const stamp = isoNow(this.now()).replace(/[:.]/gu, '-');
|
|
237
|
+
return path.join('snapshots', `${stamp}-${proposal.id}-${path.basename(target)}.bak`);
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
#writeSnapshot(proposal, target, buffer, baseSha, relative) {
|
|
241
|
+
ensureDir(this.snapshotsDir);
|
|
242
|
+
const file = path.join(this.vaultDir, relative);
|
|
243
|
+
const fd = fs.openSync(file, 'w', 0o600);
|
|
244
|
+
try {
|
|
245
|
+
fs.writeFileSync(fd, buffer);
|
|
246
|
+
fs.fsyncSync(fd);
|
|
247
|
+
} finally {
|
|
248
|
+
fs.closeSync(fd);
|
|
249
|
+
}
|
|
250
|
+
const back = fs.readFileSync(file);
|
|
251
|
+
const actual = sha256Buffer(back);
|
|
252
|
+
if (actual !== baseSha) throw new StoreError('E_SNAPSHOT', 'snapshot read-back sha mismatch', { expected: baseSha, actual });
|
|
253
|
+
appendJsonLineDurable(this.snapshotManifest, {
|
|
254
|
+
proposalId: proposal.id,
|
|
255
|
+
target: proposal.target,
|
|
256
|
+
beforeSha: baseSha,
|
|
257
|
+
bytes: buffer.length,
|
|
258
|
+
snapshot: relative,
|
|
259
|
+
at: isoNow(this.now()),
|
|
260
|
+
});
|
|
261
|
+
return { file, relative };
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
#releaseLease() {
|
|
265
|
+
try {
|
|
266
|
+
return this.lease?.release?.() ?? { ok: true };
|
|
267
|
+
} catch (error) {
|
|
268
|
+
this.#auditSafe('lease.release_failed', { error: String(error?.message ?? error) });
|
|
269
|
+
return { ok: false };
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
#headApproved(proposals) {
|
|
274
|
+
const approved = sortQueueEntries(proposals
|
|
275
|
+
.filter((proposal) => proposal.status === 'approved')
|
|
276
|
+
.map((proposal) => ({
|
|
277
|
+
ticket: proposal.queue?.ticket ?? null,
|
|
278
|
+
effectivePriority: proposal.queue?.effectivePriority ?? proposal.queue?.priority ?? 'P3',
|
|
279
|
+
queuedAt: proposal.queue?.queuedAt ?? proposal.createdAt,
|
|
280
|
+
proposal,
|
|
281
|
+
})));
|
|
282
|
+
return approved[0]?.proposal ?? null;
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
/**
|
|
286
|
+
* Public read-only view of the queue head. Used by
|
|
287
|
+
* service.requestApply to resolve a no-id apply/rollback before the
|
|
288
|
+
* confirm check (D-CR3); the selection matches the one apply() uses.
|
|
289
|
+
*/
|
|
290
|
+
headApproved() {
|
|
291
|
+
return this.#headApproved(this.#scan().proposals);
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/**
|
|
295
|
+
* Apply exactly one approved proposal — only the queue head, never preempt.
|
|
296
|
+
* Returns ok:false with a stable code on failure; a "queued" result is NOT an
|
|
297
|
+
* error (design deletes the old E_LEASE_HELD outward code).
|
|
298
|
+
*/
|
|
299
|
+
async apply(args = {}, options = {}) {
|
|
300
|
+
// Guard: applying is an owner-level operation. The gate must look at the
|
|
301
|
+
// per-call caller (D-CR2); the instance caller is only a fallback.
|
|
302
|
+
if (this.config.applyEnabled !== true) return { ok: false, code: 'E_APPLY_DISABLED' };
|
|
303
|
+
const caller = options?.caller ?? this.caller;
|
|
304
|
+
if (isSubagentCaller(caller)) return { ok: false, code: 'E_NOT_MAIN_SESSION' };
|
|
305
|
+
|
|
306
|
+
const scan = this.#scan();
|
|
307
|
+
let proposal = null;
|
|
308
|
+
if (args.id) {
|
|
309
|
+
proposal = scan.proposals.find((candidate) => candidate.id === args.id) ?? null;
|
|
310
|
+
if (!proposal) return { ok: false, code: 'E_TICKET_UNKNOWN', ticket: args.ticket ?? null };
|
|
311
|
+
if (proposal.status !== 'approved') return { ok: false, code: 'E_BAD_STATE', id: proposal.id, state: proposal.status };
|
|
312
|
+
const head = this.#headApproved(scan.proposals);
|
|
313
|
+
if (head && head.id !== proposal.id) {
|
|
314
|
+
return { ok: true, state: 'queued', id: proposal.id, ticket: proposal.queue?.ticket ?? null, position: null, message: 'waiting behind the queue head' };
|
|
315
|
+
}
|
|
316
|
+
} else {
|
|
317
|
+
proposal = this.#headApproved(scan.proposals);
|
|
318
|
+
if (!proposal) return { ok: true, state: 'idle', message: 'no approved proposal' };
|
|
319
|
+
if (args.ticket && args.ticket !== proposal.queue?.ticket) {
|
|
320
|
+
return { ok: false, code: 'E_TICKET_UNKNOWN', ticket: args.ticket };
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
const ticket = proposal.queue?.ticket ?? null;
|
|
325
|
+
const proposalId = proposal.id;
|
|
326
|
+
|
|
327
|
+
// STEP 1 — acquire the writer lease. Failure is "still queued", never a busy
|
|
328
|
+
// error. §5.6: wait at most the configured window, then degrade to
|
|
329
|
+
// blocked-on-user/LEASE_TIMEOUT with the single timeout code E_WAIT_TIMEOUT.
|
|
330
|
+
// Cap the in-process wait (a CLI apply must not hang for a five-minute lease
|
|
331
|
+
// window); queue maintain still owns the long-window transition.
|
|
332
|
+
let acquired = this.lease.acquire({ ticket, proposalId });
|
|
333
|
+
// A short configured window (?5000ms) is an explicit caller request for the
|
|
334
|
+
// bounded E_WAIT_TIMEOUT contract (L-04). The default long window keeps the
|
|
335
|
+
// legacy non-blocking "queued" reply; queue.maintain owns that transition.
|
|
336
|
+
const configuredWait = Number(this.config.leaseWaitTimeoutMs);
|
|
337
|
+
const fastTimeout = Number.isFinite(configuredWait) && configuredWait > 0 && configuredWait <= 5000;
|
|
338
|
+
if (!acquired.ok && fastTimeout) {
|
|
339
|
+
const waitMs = Math.min(configuredWait, 1500);
|
|
340
|
+
const deadline = Date.now() + waitMs;
|
|
341
|
+
while (!acquired.ok && Date.now() < deadline) {
|
|
342
|
+
await new Promise((resolve) => setTimeout(resolve, 25));
|
|
343
|
+
acquired = this.lease.acquire({ ticket, proposalId });
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
if (!acquired.ok && !fastTimeout) {
|
|
347
|
+
return { ok: true, state: 'queued', id: proposalId, ticket, holder: acquired.holder ?? null };
|
|
348
|
+
}
|
|
349
|
+
if (!acquired.ok) {
|
|
350
|
+
const blockedTtlMs = Number(this.config.blockedOnUserTtlMs) || 86_400_000;
|
|
351
|
+
const at = isoNow(this.now());
|
|
352
|
+
const next = this.#updateProposal(proposalId, (current) => ({
|
|
353
|
+
...current,
|
|
354
|
+
status: 'blocked-on-user',
|
|
355
|
+
queue: {
|
|
356
|
+
...current.queue,
|
|
357
|
+
lease: null,
|
|
358
|
+
blockedReason: 'LEASE_TIMEOUT',
|
|
359
|
+
deadlineAt: isoNow(new Date(this.now().getTime() + blockedTtlMs)),
|
|
360
|
+
},
|
|
361
|
+
reason: 'LEASE_TIMEOUT',
|
|
362
|
+
stateLog: [...(current.stateLog ?? []), { at, from: 'approved', to: 'blocked-on-user', by: 'router', note: 'LEASE_TIMEOUT' }],
|
|
363
|
+
}));
|
|
364
|
+
this.#auditSafe('proposal.blocked', { proposalId, ticket, reason: 'LEASE_TIMEOUT' });
|
|
365
|
+
return {
|
|
366
|
+
ok: false,
|
|
367
|
+
code: 'E_WAIT_TIMEOUT',
|
|
368
|
+
state: 'blocked-on-user',
|
|
369
|
+
reason: 'LEASE_TIMEOUT',
|
|
370
|
+
id: proposalId,
|
|
371
|
+
ticket,
|
|
372
|
+
holder: acquired.holder ?? null,
|
|
373
|
+
message: 'writer lease wait timed out; owner adjudication required',
|
|
374
|
+
deadlineAt: next?.queue?.deadlineAt ?? null,
|
|
375
|
+
};
|
|
376
|
+
}
|
|
377
|
+
this.wal.append('lease.acquire', { ticket, proposalId, runId: this.runId, pid: process.pid });
|
|
378
|
+
|
|
379
|
+
let phase = 'validate';
|
|
380
|
+
try {
|
|
381
|
+
// STEP 2 — re-read from disk; it must still be approved (and not a stale rev).
|
|
382
|
+
const fresh = readProposal(this.proposalsDir, proposalId);
|
|
383
|
+
if (!fresh || fresh.status !== 'approved') {
|
|
384
|
+
this.#releaseLease();
|
|
385
|
+
return { ok: false, code: 'E_BAD_STATE', id: proposalId, state: fresh?.status ?? 'missing' };
|
|
386
|
+
}
|
|
387
|
+
proposal = fresh;
|
|
388
|
+
|
|
389
|
+
// STEP 3 — target sha must equal baseSha. Any mismatch is a conflict with
|
|
390
|
+
// zero writes (no snapshot, no tmp, no canonical touch).
|
|
391
|
+
const target = this.#readTarget(proposal);
|
|
392
|
+
if (!target.ok) {
|
|
393
|
+
this.#conflict(proposal, { code: target.code, reason: 'target-unreadable', phase: 'validate' });
|
|
394
|
+
this.#releaseLease();
|
|
395
|
+
return { ok: false, code: target.code, id: proposalId, ticket, state: 'conflict' };
|
|
396
|
+
}
|
|
397
|
+
// Proposal digests are bare lowercase hex in 1.1.1; accept a legacy
|
|
398
|
+
// `sha256:`-prefixed baseSha from a 1.1.0 vault without re-writing it.
|
|
399
|
+
const baseSha = typeof proposal.baseSha === 'string'
|
|
400
|
+
? proposal.baseSha.replace(/^sha256:/u, '').toLowerCase()
|
|
401
|
+
: (proposal.baseSha ?? null);
|
|
402
|
+
if (target.exists) {
|
|
403
|
+
if (!baseSha || target.sha256 !== baseSha) {
|
|
404
|
+
this.#conflict(proposal, {
|
|
405
|
+
code: 'E_BASE_MOVED',
|
|
406
|
+
reason: 'base-moved',
|
|
407
|
+
phase: 'validate',
|
|
408
|
+
extra: { expectedSha: baseSha, actualSha: target.sha256 },
|
|
409
|
+
});
|
|
410
|
+
this.#auditSafe('apply.conflict', { proposalId, ticket, reason: 'base-moved', phase: 'validate', expectedSha: baseSha, actualSha: target.sha256 });
|
|
411
|
+
this.#releaseLease();
|
|
412
|
+
return { ok: false, code: 'E_BASE_MOVED', id: proposalId, ticket, state: 'conflict' };
|
|
413
|
+
}
|
|
414
|
+
} else if (baseSha) {
|
|
415
|
+
this.#conflict(proposal, { code: 'E_TARGET_MISSING', reason: 'target-missing', phase: 'validate', extra: { expectedSha: baseSha, actualSha: null } });
|
|
416
|
+
this.#releaseLease();
|
|
417
|
+
return { ok: false, code: 'E_TARGET_MISSING', id: proposalId, ticket, state: 'conflict' };
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
let afterText;
|
|
421
|
+
try {
|
|
422
|
+
afterText = buildAfterContent(proposal, target.text);
|
|
423
|
+
} catch (error) {
|
|
424
|
+
this.#conflict(proposal, { code: 'E_BAD_CONTENT', reason: 'content-transform', phase: 'validate' });
|
|
425
|
+
this.#releaseLease();
|
|
426
|
+
return { ok: false, code: 'E_BAD_CONTENT', id: proposalId, ticket, state: 'conflict' };
|
|
427
|
+
}
|
|
428
|
+
const afterBuffer = Buffer.from(afterText, 'utf8');
|
|
429
|
+
const afterSha = sha256Buffer(afterBuffer);
|
|
430
|
+
const snapshotRelative = this.#snapshotName(proposal, target.absolute);
|
|
431
|
+
|
|
432
|
+
const holderCheck = this.lease.check({ phase: 'pre-begin' });
|
|
433
|
+
if (!holderCheck.ok) {
|
|
434
|
+
this.#releaseLease();
|
|
435
|
+
return { ok: false, code: holderCheck.code, id: proposalId, ticket, state: 'queued' };
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
// STEP 4 — WAL apply.begin + fsync BEFORE any canonical/dir side effect.
|
|
439
|
+
this.wal.append('apply.begin', {
|
|
440
|
+
ticket,
|
|
441
|
+
proposalId,
|
|
442
|
+
op: proposal.op,
|
|
443
|
+
target: proposal.target,
|
|
444
|
+
baseSha,
|
|
445
|
+
afterSha,
|
|
446
|
+
snapshot: snapshotRelative,
|
|
447
|
+
bytesAfter: afterBuffer.length,
|
|
448
|
+
});
|
|
449
|
+
phase = 'begin';
|
|
450
|
+
proposal = this.#updateProposal(proposalId, (current) => ({
|
|
451
|
+
...current,
|
|
452
|
+
status: 'applying',
|
|
453
|
+
queue: {
|
|
454
|
+
...current.queue,
|
|
455
|
+
lease: {
|
|
456
|
+
holder: this.holder.sessionId,
|
|
457
|
+
pid: this.holder.pid,
|
|
458
|
+
host: this.holder.host,
|
|
459
|
+
runId: this.runId,
|
|
460
|
+
acquiredAt: acquired.lease?.acquiredAt ?? isoNow(this.now()),
|
|
461
|
+
expiresAt: acquired.lease?.expiresAt ?? null,
|
|
462
|
+
renewals: 0,
|
|
463
|
+
},
|
|
464
|
+
},
|
|
465
|
+
stateLog: [...(current.stateLog ?? []), {
|
|
466
|
+
at: isoNow(this.now()),
|
|
467
|
+
from: 'approved',
|
|
468
|
+
to: 'applying',
|
|
469
|
+
by: 'router',
|
|
470
|
+
note: 'apply.begin',
|
|
471
|
+
}],
|
|
472
|
+
}), { expectRev: proposal.rev });
|
|
473
|
+
|
|
474
|
+
// STEP 5 — snapshot original bytes and verify sha == baseSha.
|
|
475
|
+
phase = 'snapshot';
|
|
476
|
+
let snapshot = null;
|
|
477
|
+
try {
|
|
478
|
+
if (this.#injected('failSnapshot')) throw new StoreError('E_SNAPSHOT', 'injected snapshot failure');
|
|
479
|
+
snapshot = this.#writeSnapshot(proposal, target.absolute, target.buffer, baseSha ?? sha256Buffer(Buffer.alloc(0)), snapshotRelative);
|
|
480
|
+
} catch (error) {
|
|
481
|
+
this.wal.append('apply.abort', { ticket, proposalId, reason: 'snapshot-failed', phase: 'snapshot' });
|
|
482
|
+
this.#auditSafe('snapshot_failed', { proposalId, ticket, error: String(error?.message ?? error) });
|
|
483
|
+
this.#auditSafe('apply.abort', { proposalId, ticket, reason: 'snapshot-failed', phase: 'snapshot' });
|
|
484
|
+
this.#conflict(proposal, { code: 'E_SNAPSHOT_FAILED', reason: 'snapshot-failed', phase: 'snapshot' });
|
|
485
|
+
this.#releaseLease();
|
|
486
|
+
return { ok: false, code: 'E_SNAPSHOT_FAILED', id: proposalId, ticket, state: 'conflict' };
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
// STEP 6 — write tmp in the same directory, fsync + close. No rename yet.
|
|
490
|
+
phase = 'tmp';
|
|
491
|
+
const tmpFile = this.#tmpPath(target.absolute, proposalId);
|
|
492
|
+
try {
|
|
493
|
+
fs.mkdirSync(path.dirname(target.absolute), { recursive: true });
|
|
494
|
+
const fd = fs.openSync(tmpFile, 'w', 0o600);
|
|
495
|
+
try {
|
|
496
|
+
fs.writeFileSync(fd, afterBuffer);
|
|
497
|
+
if (this.#injected('failFsync')) throw new StoreError('E_IO', 'injected fsync failure');
|
|
498
|
+
fs.fsyncSync(fd);
|
|
499
|
+
} finally {
|
|
500
|
+
fs.closeSync(fd);
|
|
501
|
+
}
|
|
502
|
+
if (this.#injected('failWriteAfter')) throw new TestCrash('after-tmp-write');
|
|
503
|
+
} catch (error) {
|
|
504
|
+
if (error instanceof TestCrash) throw error;
|
|
505
|
+
try { fs.unlinkSync(tmpFile); } catch { /* no tmp */ }
|
|
506
|
+
this.wal.append('apply.abort', { ticket, proposalId, reason: 'write-failed', phase: 'tmp-write' });
|
|
507
|
+
this.#auditSafe('apply.abort', { proposalId, ticket, reason: 'write-failed', phase: 'tmp-write' });
|
|
508
|
+
this.#conflict(proposal, { code: 'E_IO', reason: 'tmp-write-failed', phase: 'tmp-write' });
|
|
509
|
+
this.#releaseLease();
|
|
510
|
+
return { ok: false, code: 'E_IO', id: proposalId, ticket, state: 'conflict' };
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
// STEP 7 — final recheck: third target read + complete tmp. Any change means
|
|
514
|
+
// an owner wrote during our window: delete tmp, zero canonical bytes.
|
|
515
|
+
phase = 'recheck';
|
|
516
|
+
const holderCheck2 = this.lease.check({ phase: 'pre-rename' });
|
|
517
|
+
if (!holderCheck2.ok) {
|
|
518
|
+
try { fs.unlinkSync(tmpFile); } catch { /* ignore */ }
|
|
519
|
+
this.wal.append('apply.abort', { ticket, proposalId, reason: 'lease-lost', phase: 'pre-rename' });
|
|
520
|
+
this.#conflict(proposal, { code: holderCheck2.code, reason: 'lease-lost', phase: 'pre-rename' });
|
|
521
|
+
return { ok: false, code: holderCheck2.code, id: proposalId, ticket, state: 'conflict' };
|
|
522
|
+
}
|
|
523
|
+
const finalTarget = this.#readTarget(proposal);
|
|
524
|
+
const tmpBytes = (() => {
|
|
525
|
+
try { return fs.statSync(tmpFile).size; } catch { return null; }
|
|
526
|
+
})();
|
|
527
|
+
// Consume the "skip one injection" hook without changing the outcome —
|
|
528
|
+
// it exists so tests can prove the next apply is unaffected by a pending
|
|
529
|
+
// force. forceInjection deliberately fails this recheck.
|
|
530
|
+
this.#injected('skipInjectionOnce');
|
|
531
|
+
const recheckOk = finalTarget.ok
|
|
532
|
+
&& ((!finalTarget.exists && !baseSha) || (finalTarget.exists && finalTarget.sha256 === baseSha))
|
|
533
|
+
&& tmpBytes === afterBuffer.length
|
|
534
|
+
&& !this.#injected('forceInjection');
|
|
535
|
+
if (!recheckOk) {
|
|
536
|
+
try { fs.unlinkSync(tmpFile); } catch { /* ignore */ }
|
|
537
|
+
this.wal.append('apply.abort', { ticket, proposalId, reason: 'owner-write-race', phase: 'pre-rename' });
|
|
538
|
+
this.#auditSafe('apply.abort', { proposalId, ticket, reason: 'owner-write-race', phase: 'pre-rename' });
|
|
539
|
+
this.#conflict(proposal, { code: 'E_BASE_MOVED', reason: 'owner-write-race', phase: 'pre-rename', extra: { expectedSha: baseSha, actualSha: finalTarget.ok ? finalTarget.sha256 : null } });
|
|
540
|
+
this.#warn('OWNER_WRITE_RACE');
|
|
541
|
+
this.#releaseLease();
|
|
542
|
+
return { ok: false, code: 'E_BASE_MOVED', id: proposalId, ticket, state: 'conflict', reason: 'owner-write-race' };
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
// STEP 8 — rename into place, fsync dir, read back.
|
|
546
|
+
phase = 'rename';
|
|
547
|
+
let renameError = null;
|
|
548
|
+
try {
|
|
549
|
+
fs.renameSync(tmpFile, target.absolute);
|
|
550
|
+
this.#fsyncDir(path.dirname(target.absolute));
|
|
551
|
+
} catch (error) {
|
|
552
|
+
renameError = error;
|
|
553
|
+
}
|
|
554
|
+
if (renameError) {
|
|
555
|
+
try { fs.unlinkSync(tmpFile); } catch { /* ignore */ }
|
|
556
|
+
this.wal.append('apply.abort', { ticket, proposalId, reason: 'rename-failed', phase: 'rename' });
|
|
557
|
+
this.#conflict(proposal, { code: 'E_IO', reason: 'rename-failed', phase: 'rename' });
|
|
558
|
+
this.#releaseLease();
|
|
559
|
+
return { ok: false, code: 'E_IO', id: proposalId, ticket, state: 'conflict' };
|
|
560
|
+
}
|
|
561
|
+
phase = 'readback';
|
|
562
|
+
let actual = null;
|
|
563
|
+
try {
|
|
564
|
+
actual = sha256Buffer(fs.readFileSync(target.absolute));
|
|
565
|
+
} catch {
|
|
566
|
+
actual = null;
|
|
567
|
+
}
|
|
568
|
+
const readbackOk = !this.#injected('failReadback') && actual === afterSha;
|
|
569
|
+
if (!readbackOk) {
|
|
570
|
+
this.wal.append('apply.conflict', {
|
|
571
|
+
ticket,
|
|
572
|
+
proposalId,
|
|
573
|
+
reason: 'readback-mismatch',
|
|
574
|
+
phase: 'after-rename',
|
|
575
|
+
expectedSha: afterSha,
|
|
576
|
+
actualSha: actual,
|
|
577
|
+
});
|
|
578
|
+
this.wal.append('restore.required', {
|
|
579
|
+
ticket,
|
|
580
|
+
proposalId,
|
|
581
|
+
reason: 'readback-mismatch',
|
|
582
|
+
expectedSha: afterSha,
|
|
583
|
+
actualSha: actual,
|
|
584
|
+
snapshot: snapshot?.relative ?? snapshotRelative,
|
|
585
|
+
});
|
|
586
|
+
this.#auditSafe('apply.conflict', { proposalId, ticket, reason: 'readback-mismatch', phase: 'after-rename', expectedSha: afterSha, actualSha: actual });
|
|
587
|
+
this.#warn('RESTORE_REQUIRED');
|
|
588
|
+
const conflicted = this.#conflict(proposal, {
|
|
589
|
+
code: 'RESTORE_REQUIRED',
|
|
590
|
+
reason: 'readback-mismatch',
|
|
591
|
+
phase: 'after-rename',
|
|
592
|
+
extra: { expectedSha: afterSha, actualSha: actual, restoreRequired: true, snapshot: snapshot?.relative ?? snapshotRelative },
|
|
593
|
+
});
|
|
594
|
+
// Restore_required is recorded on the proposal; never auto-rollback (B-04).
|
|
595
|
+
this.#updateProposal(proposalId, (current) => ({
|
|
596
|
+
...current,
|
|
597
|
+
result: {
|
|
598
|
+
appliedAt: null,
|
|
599
|
+
beforeSha: baseSha,
|
|
600
|
+
afterSha,
|
|
601
|
+
bytesAdded: afterBuffer.length - (target.bytes ?? 0),
|
|
602
|
+
snapshot: snapshot?.relative ?? snapshotRelative,
|
|
603
|
+
restoreRequired: true,
|
|
604
|
+
actualSha: actual,
|
|
605
|
+
},
|
|
606
|
+
}), { expectRev: conflicted.rev });
|
|
607
|
+
this.#releaseLease();
|
|
608
|
+
return { ok: false, code: 'E_RESTORE_REQUIRED', id: proposalId, ticket, state: 'conflict', restoreRequired: true, actualSha: actual };
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
// STEP 9 — WAL apply.done, proposal done, lease release, queue advance, audit.
|
|
612
|
+
const result = {
|
|
613
|
+
appliedAt: isoNow(this.now()),
|
|
614
|
+
beforeSha: baseSha,
|
|
615
|
+
afterSha,
|
|
616
|
+
bytesAdded: afterBuffer.length - (target.bytes ?? 0),
|
|
617
|
+
snapshot: snapshot.relative,
|
|
618
|
+
};
|
|
619
|
+
this.wal.append('apply.done', { ticket, proposalId, beforeSha: baseSha, afterSha, snapshot: snapshot.relative });
|
|
620
|
+
this.#updateProposal(proposalId, (current) => ({
|
|
621
|
+
...current,
|
|
622
|
+
status: 'done',
|
|
623
|
+
queue: { ...current.queue, lease: null, blockedReason: null },
|
|
624
|
+
result,
|
|
625
|
+
conflict: null,
|
|
626
|
+
stateLog: [...(current.stateLog ?? []), {
|
|
627
|
+
at: isoNow(this.now()),
|
|
628
|
+
from: 'applying',
|
|
629
|
+
to: 'done',
|
|
630
|
+
by: 'router',
|
|
631
|
+
note: 'apply.done',
|
|
632
|
+
}],
|
|
633
|
+
}), { expectRev: proposal.rev });
|
|
634
|
+
this.#auditSafe('apply.done', { proposalId, ticket, beforeSha: baseSha, afterSha, bytesAdded: result.bytesAdded });
|
|
635
|
+
this.#releaseLease();
|
|
636
|
+
this.queue?.rebuild?.();
|
|
637
|
+
return { ok: true, state: 'done', id: proposalId, ticket, result };
|
|
638
|
+
} catch (error) {
|
|
639
|
+
if (error instanceof TestCrash) {
|
|
640
|
+
// Simulated kill: leave tmp + applying + lease for restart recovery (K8).
|
|
641
|
+
this.#auditSafe('apply.crash_simulated', { proposalId, ticket, phase: error.phase });
|
|
642
|
+
throw error;
|
|
643
|
+
}
|
|
644
|
+
this.#auditSafe('apply.error', { proposalId, ticket, phase, error: String(error?.message ?? error) });
|
|
645
|
+
try { this.#releaseLease(); } catch { /* ignore */ }
|
|
646
|
+
throw error;
|
|
647
|
+
}
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
/**
|
|
651
|
+
* Owner rollback (DESIGN §5.9): only a done proposal whose target still equals
|
|
652
|
+
* result.afterSha may be restored from its snapshot. Never auto-triggered.
|
|
653
|
+
*/
|
|
654
|
+
async rollback(args = {}, options = {}) {
|
|
655
|
+
if (this.config.applyEnabled !== true) return { ok: false, code: 'E_APPLY_DISABLED' };
|
|
656
|
+
const caller = options?.caller ?? this.caller;
|
|
657
|
+
if (isSubagentCaller(caller)) return { ok: false, code: 'E_NOT_MAIN_SESSION' };
|
|
658
|
+
const id = typeof args.id === 'string' ? args.id.trim() : '';
|
|
659
|
+
let proposal = id ? readProposal(this.proposalsDir, id) : null;
|
|
660
|
+
if (!proposal) return { ok: false, code: 'E_TICKET_UNKNOWN', ticket: args.ticket ?? null };
|
|
661
|
+
if (proposal.status !== 'done') return { ok: false, code: 'E_BAD_STATE', id: proposal.id, state: proposal.status };
|
|
662
|
+
const ticket = proposal.queue?.ticket ?? null;
|
|
663
|
+
const result = proposal.result ?? {};
|
|
664
|
+
// R-06: an apply that created a new file records beforeSha/baseSha = null.
|
|
665
|
+
// Rolling it back means removing the file, not restoring empty bytes.
|
|
666
|
+
const newFileApply = (result.baseSha ?? result.beforeSha ?? null) === null;
|
|
667
|
+
|
|
668
|
+
// Side-effect-free first look: the target must still be exactly the bytes
|
|
669
|
+
// this apply wrote, and the restore snapshot must be readable.
|
|
670
|
+
const initial = this.#readTarget(proposal);
|
|
671
|
+
if (!initial.ok || !initial.exists || initial.sha256 !== result.afterSha) {
|
|
672
|
+
this.#auditSafe('rollback.base_moved', { proposalId: proposal.id, expectedSha: result.afterSha ?? null, actualSha: initial.ok ? initial.sha256 : null });
|
|
673
|
+
return { ok: false, code: 'E_BASE_MOVED', id: proposal.id, ticket };
|
|
674
|
+
}
|
|
675
|
+
if (!result.snapshot) return { ok: false, code: 'E_SNAPSHOT_FAILED', id: proposal.id, ticket };
|
|
676
|
+
const snapshotFile = path.join(this.vaultDir, result.snapshot);
|
|
677
|
+
let before = null;
|
|
678
|
+
try { before = fs.readFileSync(snapshotFile); } catch { before = null; }
|
|
679
|
+
if (!before) return { ok: false, code: 'E_SNAPSHOT_FAILED', id: proposal.id, ticket };
|
|
680
|
+
const beforeSha = sha256Buffer(before);
|
|
681
|
+
const acquired = this.lease.acquire({ ticket, proposalId: proposal.id });
|
|
682
|
+
if (!acquired.ok) return { ok: true, state: 'queued', id: proposal.id, ticket, holder: acquired.holder ?? null };
|
|
683
|
+
|
|
684
|
+
try {
|
|
685
|
+
// D-CR8: enter "applying" with rollback:true BEFORE rollback.begin, so a
|
|
686
|
+
// crash at any later point is visible to recoverApplying().
|
|
687
|
+
proposal = this.#updateProposal(proposal.id, (current) => ({
|
|
688
|
+
...current,
|
|
689
|
+
status: 'applying',
|
|
690
|
+
rollback: {
|
|
691
|
+
active: true,
|
|
692
|
+
runId: this.runId,
|
|
693
|
+
startedAt: isoNow(this.now()),
|
|
694
|
+
beforeSha,
|
|
695
|
+
afterSha: result.afterSha ?? null,
|
|
696
|
+
snapshot: result.snapshot,
|
|
697
|
+
removeTarget: newFileApply,
|
|
698
|
+
},
|
|
699
|
+
queue: {
|
|
700
|
+
...current.queue,
|
|
701
|
+
lease: {
|
|
702
|
+
holder: this.holder.sessionId,
|
|
703
|
+
pid: this.holder.pid,
|
|
704
|
+
host: this.holder.host,
|
|
705
|
+
runId: this.runId,
|
|
706
|
+
acquiredAt: acquired.lease?.acquiredAt ?? isoNow(this.now()),
|
|
707
|
+
expiresAt: acquired.lease?.expiresAt ?? null,
|
|
708
|
+
renewals: 0,
|
|
709
|
+
},
|
|
710
|
+
},
|
|
711
|
+
stateLog: [...(current.stateLog ?? []), {
|
|
712
|
+
at: isoNow(this.now()),
|
|
713
|
+
from: 'done',
|
|
714
|
+
to: 'applying',
|
|
715
|
+
by: 'router',
|
|
716
|
+
note: 'rollback.begin',
|
|
717
|
+
}],
|
|
718
|
+
}), { expectRev: proposal.rev });
|
|
719
|
+
|
|
720
|
+
this.wal.append('rollback.begin', {
|
|
721
|
+
ticket,
|
|
722
|
+
proposalId: proposal.id,
|
|
723
|
+
beforeSha,
|
|
724
|
+
afterSha: result.afterSha ?? null,
|
|
725
|
+
snapshot: result.snapshot,
|
|
726
|
+
removeTarget: newFileApply,
|
|
727
|
+
});
|
|
728
|
+
|
|
729
|
+
const absolute = initial.absolute;
|
|
730
|
+
const tmp = this.#tmpPath(absolute, `rollback-${proposal.id}`);
|
|
731
|
+
fs.mkdirSync(path.dirname(absolute), { recursive: true });
|
|
732
|
+
if (!newFileApply) {
|
|
733
|
+
const fd = fs.openSync(tmp, 'w', 0o600);
|
|
734
|
+
try {
|
|
735
|
+
fs.writeFileSync(fd, before);
|
|
736
|
+
fs.fsyncSync(fd);
|
|
737
|
+
} finally {
|
|
738
|
+
fs.closeSync(fd);
|
|
739
|
+
}
|
|
740
|
+
}
|
|
741
|
+
|
|
742
|
+
// Final check after the tmp is durable, immediately before any canonical
|
|
743
|
+
// write: lease still ours + target still afterSha. Zero bytes on failure.
|
|
744
|
+
const holderCheck = this.lease.check({ phase: 'pre-rename' });
|
|
745
|
+
if (!holderCheck.ok) {
|
|
746
|
+
try { fs.unlinkSync(tmp); } catch { /* ignore */ }
|
|
747
|
+
this.wal.append('apply.abort', { ticket, proposalId: proposal.id, reason: 'lease-lost', phase: 'rollback-pre-rename' });
|
|
748
|
+
this.#conflict(proposal, { code: holderCheck.code, reason: 'lease-lost', phase: 'rollback-pre-rename' });
|
|
749
|
+
this.#releaseLease();
|
|
750
|
+
return { ok: false, code: holderCheck.code, id: proposal.id, ticket, state: 'conflict' };
|
|
751
|
+
}
|
|
752
|
+
if (typeof this.testHooks?.onRollbackRecheck === 'function') {
|
|
753
|
+
try { this.testHooks.onRollbackRecheck(); } catch { /* test seam only */ }
|
|
754
|
+
}
|
|
755
|
+
const finalTarget = this.#readTarget(proposal);
|
|
756
|
+
const recheckOk = finalTarget.ok
|
|
757
|
+
&& finalTarget.exists
|
|
758
|
+
&& finalTarget.sha256 === result.afterSha
|
|
759
|
+
&& !this.#injected('forceRollbackInjection');
|
|
760
|
+
if (!recheckOk) {
|
|
761
|
+
try { fs.unlinkSync(tmp); } catch { /* ignore */ }
|
|
762
|
+
this.wal.append('apply.abort', { ticket, proposalId: proposal.id, reason: 'owner-write-race', phase: 'rollback-pre-rename' });
|
|
763
|
+
this.#auditSafe('apply.abort', { proposalId: proposal.id, ticket, reason: 'owner-write-race', phase: 'rollback-pre-rename' });
|
|
764
|
+
this.#conflict(proposal, {
|
|
765
|
+
code: 'E_BASE_MOVED',
|
|
766
|
+
reason: 'owner-write-race',
|
|
767
|
+
phase: 'rollback-pre-rename',
|
|
768
|
+
extra: { expectedSha: result.afterSha ?? null, actualSha: finalTarget.ok ? finalTarget.sha256 : null },
|
|
769
|
+
});
|
|
770
|
+
this.#warn('OWNER_WRITE_RACE');
|
|
771
|
+
this.#releaseLease();
|
|
772
|
+
return { ok: false, code: 'E_BASE_MOVED', id: proposal.id, ticket, state: 'conflict', reason: 'owner-write-race' };
|
|
773
|
+
}
|
|
774
|
+
|
|
775
|
+
// Evidence: snapshot the bytes being overwritten (still afterSha).
|
|
776
|
+
const stamp = isoNow(this.now()).replace(/[:.]/gu, '-');
|
|
777
|
+
const evidence = path.join('snapshots', `rollback-${stamp}-${proposal.id}-${path.basename(absolute)}.bak`);
|
|
778
|
+
this.#writeSnapshot(proposal, absolute, finalTarget.buffer, result.afterSha, evidence);
|
|
779
|
+
|
|
780
|
+
if (newFileApply) {
|
|
781
|
+
// R-06 residual: the final sha recheck happens immediately before the
|
|
782
|
+
// unlink too — a third-party write between recheck and removal must not
|
|
783
|
+
// be silently deleted.
|
|
784
|
+
let current = null;
|
|
785
|
+
try { current = sha256Buffer(fs.readFileSync(absolute)); } catch { current = null; }
|
|
786
|
+
if (current !== null && current !== result.afterSha) {
|
|
787
|
+
this.#auditSafe('rollback.base_moved', { proposalId: proposal.id, expectedSha: result.afterSha ?? null, actualSha: current, phase: 'pre-unlink' });
|
|
788
|
+
this.wal.append('apply.abort', { ticket, proposalId: proposal.id, reason: 'owner-write-race', phase: 'rollback-pre-unlink' });
|
|
789
|
+
this.#conflict(proposal, { code: 'E_BASE_MOVED', reason: 'owner-write-race', phase: 'rollback-pre-unlink', extra: { expectedSha: result.afterSha ?? null, actualSha: current } });
|
|
790
|
+
this.#releaseLease();
|
|
791
|
+
return { ok: false, code: 'E_BASE_MOVED', id: proposal.id, ticket, state: 'conflict', reason: 'owner-write-race' };
|
|
792
|
+
}
|
|
793
|
+
// R-06: the apply created this file; rollback removes it. ENOENT already
|
|
794
|
+
// satisfies the contract (someone else removed it).
|
|
795
|
+
let removeError = null;
|
|
796
|
+
try {
|
|
797
|
+
fs.unlinkSync(absolute);
|
|
798
|
+
} catch (error) {
|
|
799
|
+
if (error?.code !== 'ENOENT') removeError = error;
|
|
800
|
+
}
|
|
801
|
+
this.#fsyncDir(path.dirname(absolute));
|
|
802
|
+
if (this.#injected('failRollbackAfterRename')) throw new TestCrash('after-rollback-remove');
|
|
803
|
+
|
|
804
|
+
let actual = null;
|
|
805
|
+
let stillExists = false;
|
|
806
|
+
try {
|
|
807
|
+
actual = sha256Buffer(fs.readFileSync(absolute));
|
|
808
|
+
stillExists = true;
|
|
809
|
+
} catch {
|
|
810
|
+
stillExists = false;
|
|
811
|
+
}
|
|
812
|
+
if (removeError && stillExists) {
|
|
813
|
+
this.wal.append('apply.conflict', { ticket, proposalId: proposal.id, reason: 'rollback-remove-failed', expectedSha: null, actualSha: actual });
|
|
814
|
+
this.#conflict(proposal, { code: 'RESTORE_REQUIRED', reason: 'rollback-remove-failed', phase: 'rollback', extra: { expectedSha: null, actualSha: actual, error: removeError?.code ?? null } });
|
|
815
|
+
this.#warn('RESTORE_REQUIRED');
|
|
816
|
+
this.#releaseLease();
|
|
817
|
+
return { ok: false, code: 'E_RESTORE_REQUIRED', id: proposal.id, ticket, actualSha: actual };
|
|
818
|
+
}
|
|
819
|
+
if (stillExists) {
|
|
820
|
+
this.wal.append('apply.conflict', { ticket, proposalId: proposal.id, reason: 'rollback-readback-mismatch', expectedSha: null, actualSha: actual });
|
|
821
|
+
this.#conflict(proposal, { code: 'RESTORE_REQUIRED', reason: 'rollback-readback-mismatch', phase: 'rollback', extra: { expectedSha: null, actualSha: actual } });
|
|
822
|
+
this.#warn('RESTORE_REQUIRED');
|
|
823
|
+
this.#releaseLease();
|
|
824
|
+
return { ok: false, code: 'E_RESTORE_REQUIRED', id: proposal.id, ticket, actualSha: actual };
|
|
825
|
+
}
|
|
826
|
+
} else {
|
|
827
|
+
fs.renameSync(tmp, absolute);
|
|
828
|
+
this.#fsyncDir(path.dirname(absolute));
|
|
829
|
+
if (this.#injected('failRollbackAfterRename')) throw new TestCrash('after-rollback-rename');
|
|
830
|
+
|
|
831
|
+
let actual = null;
|
|
832
|
+
try { actual = sha256Buffer(fs.readFileSync(absolute)); } catch { actual = null; }
|
|
833
|
+
if (actual !== beforeSha) {
|
|
834
|
+
this.wal.append('apply.conflict', { ticket, proposalId: proposal.id, reason: 'rollback-readback-mismatch', expectedSha: beforeSha, actualSha: actual });
|
|
835
|
+
this.#conflict(proposal, { code: 'RESTORE_REQUIRED', reason: 'rollback-readback-mismatch', phase: 'rollback', extra: { expectedSha: beforeSha, actualSha: actual } });
|
|
836
|
+
this.#warn('RESTORE_REQUIRED');
|
|
837
|
+
this.#releaseLease();
|
|
838
|
+
return { ok: false, code: 'E_RESTORE_REQUIRED', id: proposal.id, ticket, actualSha: actual };
|
|
839
|
+
}
|
|
840
|
+
}
|
|
841
|
+
|
|
842
|
+
// WAL first: a crash between WAL and the state flip is recovered from
|
|
843
|
+
// rollback.begin (actual == beforeSha / target absent) without losing it.
|
|
844
|
+
this.wal.append('rollback.done', newFileApply
|
|
845
|
+
? { ticket, proposalId: proposal.id, removed: true, restoredSha: null, snapshot: evidence }
|
|
846
|
+
: { ticket, proposalId: proposal.id, restoredSha: beforeSha, snapshot: evidence });
|
|
847
|
+
const updated = this.#updateProposal(proposal.id, (current) => ({
|
|
848
|
+
...current,
|
|
849
|
+
status: 'rolled_back',
|
|
850
|
+
rollback: {
|
|
851
|
+
...(current.rollback ?? {}),
|
|
852
|
+
active: false,
|
|
853
|
+
finishedAt: isoNow(this.now()),
|
|
854
|
+
evidence,
|
|
855
|
+
...(newFileApply ? { removed: true } : {}),
|
|
856
|
+
},
|
|
857
|
+
queue: { ...current.queue, lease: null },
|
|
858
|
+
result: {
|
|
859
|
+
...(current.result ?? {}),
|
|
860
|
+
rolledBackAt: isoNow(this.now()),
|
|
861
|
+
...(newFileApply ? { removed: true, restoredSha: null } : { restoredSha: beforeSha }),
|
|
862
|
+
rollbackSnapshot: evidence,
|
|
863
|
+
},
|
|
864
|
+
stateLog: [...(current.stateLog ?? []), {
|
|
865
|
+
at: isoNow(this.now()),
|
|
866
|
+
from: 'applying',
|
|
867
|
+
to: 'rolled_back',
|
|
868
|
+
by: caller?.kind === 'owner-cli' ? 'owner:cli' : (caller?.sessionId ?? 'router'),
|
|
869
|
+
note: 'rollback.done',
|
|
870
|
+
}],
|
|
871
|
+
}), { expectRev: proposal.rev });
|
|
872
|
+
this.#auditSafe('rollback.done', {
|
|
873
|
+
proposalId: updated.id,
|
|
874
|
+
ticket,
|
|
875
|
+
...(newFileApply ? { removed: true, restoredSha: null } : { restoredSha: beforeSha }),
|
|
876
|
+
evidence,
|
|
877
|
+
});
|
|
878
|
+
this.#releaseLease();
|
|
879
|
+
this.queue?.rebuild?.();
|
|
880
|
+
return {
|
|
881
|
+
ok: true,
|
|
882
|
+
state: 'rolled_back',
|
|
883
|
+
id: updated.id,
|
|
884
|
+
ticket,
|
|
885
|
+
...(newFileApply ? { removed: true, restoredSha: null } : { restoredSha: beforeSha }),
|
|
886
|
+
snapshot: evidence,
|
|
887
|
+
};
|
|
888
|
+
} catch (error) {
|
|
889
|
+
if (error instanceof TestCrash) {
|
|
890
|
+
this.#auditSafe('rollback.crash_simulated', { proposalId: proposal.id, ticket, phase: error.phase });
|
|
891
|
+
throw error;
|
|
892
|
+
}
|
|
893
|
+
this.#releaseLease();
|
|
894
|
+
throw error;
|
|
895
|
+
}
|
|
896
|
+
}
|
|
897
|
+
|
|
898
|
+
/**
|
|
899
|
+
* DESIGN §5.4 restart reconciliation for proposals stuck in "applying":
|
|
900
|
+
* sha==baseSha → approved (attempts+1); sha==afterSha → done; otherwise
|
|
901
|
+
* conflict + RESTORE_REQUIRED. Never auto-rollback.
|
|
902
|
+
*/
|
|
903
|
+
recoverApplying() {
|
|
904
|
+
const scan = this.#scan();
|
|
905
|
+
const summary = { recovered: [], done: [], conflicts: [], rolledBack: [] };
|
|
906
|
+
for (const proposal of scan.proposals) {
|
|
907
|
+
if (proposal.status !== 'applying') continue;
|
|
908
|
+
// A rotation may have folded apply.begin into wal.snapshot.json; fall
|
|
909
|
+
// back to the snapshot's per-proposal begin record (DESIGN §3.5).
|
|
910
|
+
const begin = this.wal.last((line) => (line.ev === 'apply.begin' || line.ev === 'rollback.begin')
|
|
911
|
+
&& line.proposalId === proposal.id)
|
|
912
|
+
?? this.wal.snapshotBegin?.(proposal.id)
|
|
913
|
+
?? null;
|
|
914
|
+
const target = this.#readTarget(proposal);
|
|
915
|
+
const actual = target.ok ? target.sha256 : null;
|
|
916
|
+
if (!begin) {
|
|
917
|
+
this.#updateProposal(proposal.id, (current) => ({
|
|
918
|
+
...current,
|
|
919
|
+
status: 'approved',
|
|
920
|
+
queue: { ...current.queue, lease: null, attempts: (current.queue?.attempts ?? 0) + 1 },
|
|
921
|
+
stateLog: [...(current.stateLog ?? []), { at: isoNow(this.now()), from: 'applying', to: 'approved', by: 'router', note: 'recover: no apply.begin' }],
|
|
922
|
+
}));
|
|
923
|
+
this.wal.append('apply.abort', { ticket: proposal.queue?.ticket ?? null, proposalId: proposal.id, reason: 'recovered-no-begin', phase: 'recovery' });
|
|
924
|
+
this.#auditSafe('proposal.recovered', { proposalId: proposal.id, outcome: 'approved', reason: 'no-begin' });
|
|
925
|
+
summary.recovered.push(proposal.id);
|
|
926
|
+
continue;
|
|
927
|
+
}
|
|
928
|
+
if (begin.ev === 'rollback.begin') {
|
|
929
|
+
const beginBefore = begin.beforeSha ?? null;
|
|
930
|
+
const beginAfter = begin.afterSha ?? null;
|
|
931
|
+
if (beginBefore && actual === beginBefore) {
|
|
932
|
+
// The rename landed, but the state flip did not: finish the rollback.
|
|
933
|
+
this.#updateProposal(proposal.id, (current) => ({
|
|
934
|
+
...current,
|
|
935
|
+
status: 'rolled_back',
|
|
936
|
+
rollback: { ...(current.rollback ?? {}), active: false, finishedAt: isoNow(this.now()) },
|
|
937
|
+
queue: { ...current.queue, lease: null },
|
|
938
|
+
result: {
|
|
939
|
+
...(current.result ?? {}),
|
|
940
|
+
rolledBackAt: isoNow(this.now()),
|
|
941
|
+
restoredSha: beginBefore,
|
|
942
|
+
recovered: true,
|
|
943
|
+
},
|
|
944
|
+
stateLog: [...(current.stateLog ?? []), { at: isoNow(this.now()), from: 'applying', to: 'rolled_back', by: 'router', note: 'recover: rollback applied' }],
|
|
945
|
+
}));
|
|
946
|
+
this.wal.append('rollback.done', { ticket: proposal.queue?.ticket ?? null, proposalId: proposal.id, restoredSha: beginBefore, recovered: true });
|
|
947
|
+
this.#auditSafe('proposal.recovered', { proposalId: proposal.id, outcome: 'rolled_back', reason: 'rollback-applied' });
|
|
948
|
+
summary.rolledBack.push(proposal.id);
|
|
949
|
+
continue;
|
|
950
|
+
}
|
|
951
|
+
if (begin.removeTarget === true && actual === null) {
|
|
952
|
+
// R-06: the new-file rollback removed the target but the state flip
|
|
953
|
+
// did not land; finish it as a removal, not as an empty restore.
|
|
954
|
+
this.#updateProposal(proposal.id, (current) => ({
|
|
955
|
+
...current,
|
|
956
|
+
status: 'rolled_back',
|
|
957
|
+
rollback: { ...(current.rollback ?? {}), active: false, removed: true, finishedAt: isoNow(this.now()) },
|
|
958
|
+
queue: { ...current.queue, lease: null },
|
|
959
|
+
result: {
|
|
960
|
+
...(current.result ?? {}),
|
|
961
|
+
rolledBackAt: isoNow(this.now()),
|
|
962
|
+
restoredSha: null,
|
|
963
|
+
removed: true,
|
|
964
|
+
recovered: true,
|
|
965
|
+
},
|
|
966
|
+
stateLog: [...(current.stateLog ?? []), { at: isoNow(this.now()), from: 'applying', to: 'rolled_back', by: 'router', note: 'recover: rollback removed target' }],
|
|
967
|
+
}));
|
|
968
|
+
this.wal.append('rollback.done', { ticket: proposal.queue?.ticket ?? null, proposalId: proposal.id, removed: true, restoredSha: null, recovered: true });
|
|
969
|
+
this.#auditSafe('proposal.recovered', { proposalId: proposal.id, outcome: 'rolled_back', reason: 'rollback-removed' });
|
|
970
|
+
summary.rolledBack.push(proposal.id);
|
|
971
|
+
continue;
|
|
972
|
+
}
|
|
973
|
+
if (beginAfter && actual === beginAfter) {
|
|
974
|
+
// The rename never happened: the proposal is still exactly as applied.
|
|
975
|
+
this.#updateProposal(proposal.id, (current) => ({
|
|
976
|
+
...current,
|
|
977
|
+
status: 'done',
|
|
978
|
+
rollback: { ...(current.rollback ?? {}), active: false, aborted: true, finishedAt: isoNow(this.now()) },
|
|
979
|
+
queue: { ...current.queue, lease: null },
|
|
980
|
+
stateLog: [...(current.stateLog ?? []), { at: isoNow(this.now()), from: 'applying', to: 'done', by: 'router', note: 'recover: rollback did not land' }],
|
|
981
|
+
}));
|
|
982
|
+
this.wal.append('apply.abort', { ticket: proposal.queue?.ticket ?? null, proposalId: proposal.id, reason: 'rollback-target-unchanged', phase: 'recovery' });
|
|
983
|
+
this.#auditSafe('proposal.recovered', { proposalId: proposal.id, outcome: 'done', reason: 'rollback-not-applied' });
|
|
984
|
+
summary.done.push(proposal.id);
|
|
985
|
+
continue;
|
|
986
|
+
}
|
|
987
|
+
this.wal.append('apply.conflict', {
|
|
988
|
+
ticket: proposal.queue?.ticket ?? null,
|
|
989
|
+
proposalId: proposal.id,
|
|
990
|
+
reason: 'rollback-recovery-sha-mismatch',
|
|
991
|
+
phase: 'recovery',
|
|
992
|
+
expectedSha: begin.removeTarget === true ? null : (beginBefore ?? beginAfter ?? null),
|
|
993
|
+
actualSha: actual,
|
|
994
|
+
});
|
|
995
|
+
this.wal.append('restore.required', {
|
|
996
|
+
ticket: proposal.queue?.ticket ?? null,
|
|
997
|
+
proposalId: proposal.id,
|
|
998
|
+
reason: 'rollback-recovery-sha-mismatch',
|
|
999
|
+
expectedSha: begin.removeTarget === true ? null : (beginBefore ?? beginAfter ?? null),
|
|
1000
|
+
actualSha: actual,
|
|
1001
|
+
snapshot: begin.snapshot ?? null,
|
|
1002
|
+
});
|
|
1003
|
+
this.#conflict(proposal, {
|
|
1004
|
+
code: 'RESTORE_REQUIRED',
|
|
1005
|
+
reason: 'rollback-recovery-sha-mismatch',
|
|
1006
|
+
phase: 'recovery',
|
|
1007
|
+
extra: { expectedSha: beginBefore ?? beginAfter ?? null, actualSha: actual, restoreRequired: true, snapshot: begin.snapshot ?? null, rollback: true },
|
|
1008
|
+
});
|
|
1009
|
+
this.#warn('RESTORE_REQUIRED');
|
|
1010
|
+
summary.conflicts.push(proposal.id);
|
|
1011
|
+
continue;
|
|
1012
|
+
}
|
|
1013
|
+
if (begin.afterSha && actual === begin.afterSha) {
|
|
1014
|
+
this.#updateProposal(proposal.id, (current) => ({
|
|
1015
|
+
...current,
|
|
1016
|
+
status: 'done',
|
|
1017
|
+
queue: { ...current.queue, lease: null },
|
|
1018
|
+
result: {
|
|
1019
|
+
appliedAt: isoNow(this.now()),
|
|
1020
|
+
beforeSha: begin.baseSha ?? null,
|
|
1021
|
+
afterSha: begin.afterSha,
|
|
1022
|
+
bytesAdded: null,
|
|
1023
|
+
snapshot: begin.snapshot ?? null,
|
|
1024
|
+
recovered: true,
|
|
1025
|
+
},
|
|
1026
|
+
stateLog: [...(current.stateLog ?? []), { at: isoNow(this.now()), from: 'applying', to: 'done', by: 'router', note: 'recover: afterSha present' }],
|
|
1027
|
+
}));
|
|
1028
|
+
this.wal.append('apply.done', { ticket: proposal.queue?.ticket ?? null, proposalId: proposal.id, beforeSha: begin.baseSha ?? null, afterSha: begin.afterSha, recovered: true });
|
|
1029
|
+
this.#auditSafe('proposal.recovered', { proposalId: proposal.id, outcome: 'done' });
|
|
1030
|
+
summary.done.push(proposal.id);
|
|
1031
|
+
continue;
|
|
1032
|
+
}
|
|
1033
|
+
if ((begin.baseSha ?? null) === actual) {
|
|
1034
|
+
this.#updateProposal(proposal.id, (current) => ({
|
|
1035
|
+
...current,
|
|
1036
|
+
status: 'approved',
|
|
1037
|
+
queue: { ...current.queue, lease: null, attempts: (current.queue?.attempts ?? 0) + 1 },
|
|
1038
|
+
stateLog: [...(current.stateLog ?? []), { at: isoNow(this.now()), from: 'applying', to: 'approved', by: 'router', note: 'recover: baseSha intact' }],
|
|
1039
|
+
}));
|
|
1040
|
+
this.wal.append('apply.abort', { ticket: proposal.queue?.ticket ?? null, proposalId: proposal.id, reason: 'recovered-base-intact', phase: 'recovery' });
|
|
1041
|
+
this.#auditSafe('proposal.recovered', { proposalId: proposal.id, outcome: 'approved', reason: 'base-intact' });
|
|
1042
|
+
summary.recovered.push(proposal.id);
|
|
1043
|
+
continue;
|
|
1044
|
+
}
|
|
1045
|
+
this.wal.append('apply.conflict', {
|
|
1046
|
+
ticket: proposal.queue?.ticket ?? null,
|
|
1047
|
+
proposalId: proposal.id,
|
|
1048
|
+
reason: 'recovery-sha-mismatch',
|
|
1049
|
+
phase: 'recovery',
|
|
1050
|
+
expectedSha: begin.afterSha ?? null,
|
|
1051
|
+
actualSha: actual,
|
|
1052
|
+
});
|
|
1053
|
+
this.wal.append('restore.required', {
|
|
1054
|
+
ticket: proposal.queue?.ticket ?? null,
|
|
1055
|
+
proposalId: proposal.id,
|
|
1056
|
+
reason: 'recovery-sha-mismatch',
|
|
1057
|
+
expectedSha: begin.afterSha ?? null,
|
|
1058
|
+
actualSha: actual,
|
|
1059
|
+
snapshot: begin.snapshot ?? null,
|
|
1060
|
+
});
|
|
1061
|
+
this.#conflict(proposal, {
|
|
1062
|
+
code: 'RESTORE_REQUIRED',
|
|
1063
|
+
reason: 'recovery-sha-mismatch',
|
|
1064
|
+
phase: 'recovery',
|
|
1065
|
+
extra: { expectedSha: begin.afterSha ?? null, actualSha: actual, restoreRequired: true, snapshot: begin.snapshot ?? null },
|
|
1066
|
+
});
|
|
1067
|
+
this.#warn('RESTORE_REQUIRED');
|
|
1068
|
+
summary.conflicts.push(proposal.id);
|
|
1069
|
+
}
|
|
1070
|
+
// A same-process recovery (test/restart seam) may still own the lease that
|
|
1071
|
+
// the crashed attempt acquired. Release it only when it is provably ours.
|
|
1072
|
+
const held = this.lease?.read?.() ?? null;
|
|
1073
|
+
if (held && held.holder?.runId === this.lease?.holder?.runId
|
|
1074
|
+
&& (summary.recovered.length + summary.done.length + summary.conflicts.length + summary.rolledBack.length) > 0) {
|
|
1075
|
+
this.#releaseLease();
|
|
1076
|
+
}
|
|
1077
|
+
return summary;
|
|
1078
|
+
}
|
|
1079
|
+
|
|
1080
|
+
/** Remove abandoned tmp files older than one hour (DESIGN §5.4). */
|
|
1081
|
+
cleanStaleTmp() {
|
|
1082
|
+
const scan = this.#scan();
|
|
1083
|
+
const removed = [];
|
|
1084
|
+
// Orphan proposal writes (`<id>.json.tmp-<pid>`) live in proposalsDir and
|
|
1085
|
+
// are invisible to the proposal scanner; L-02 requires them gone.
|
|
1086
|
+
try {
|
|
1087
|
+
for (const name of fs.readdirSync(this.proposalsDir)) {
|
|
1088
|
+
if (!name.includes('.tmp-')) continue;
|
|
1089
|
+
const file = path.join(this.proposalsDir, name);
|
|
1090
|
+
try {
|
|
1091
|
+
if (this.now().getTime() - fs.statSync(file).mtimeMs > TMP_MAX_AGE_MS) {
|
|
1092
|
+
fs.unlinkSync(file);
|
|
1093
|
+
removed.push(file);
|
|
1094
|
+
}
|
|
1095
|
+
} catch { /* raced */ }
|
|
1096
|
+
}
|
|
1097
|
+
} catch { /* no proposals dir yet */ }
|
|
1098
|
+
for (const proposal of scan.proposals) {
|
|
1099
|
+
const absolute = path.resolve(this.memoryRoot ?? path.dirname(this.proposalsDir), proposal.target);
|
|
1100
|
+
// Both the apply tmp and the rollback tmp live next to the target (D-CR8).
|
|
1101
|
+
for (const tmp of [this.#tmpPath(absolute, proposal.id), this.#tmpPath(absolute, `rollback-${proposal.id}`)]) {
|
|
1102
|
+
try {
|
|
1103
|
+
const stat = fs.statSync(tmp);
|
|
1104
|
+
if (this.now().getTime() - stat.mtimeMs > TMP_MAX_AGE_MS) {
|
|
1105
|
+
fs.unlinkSync(tmp);
|
|
1106
|
+
removed.push(tmp);
|
|
1107
|
+
}
|
|
1108
|
+
} catch { /* no tmp */ }
|
|
1109
|
+
}
|
|
1110
|
+
}
|
|
1111
|
+
return removed;
|
|
1112
|
+
}
|
|
1113
|
+
|
|
1114
|
+
/** Remove evidence snapshots older than 30 days (kept as evidence before that). */
|
|
1115
|
+
cleanSnapshots() {
|
|
1116
|
+
let names = [];
|
|
1117
|
+
try { names = fs.readdirSync(this.snapshotsDir); } catch { return 0; }
|
|
1118
|
+
let removed = 0;
|
|
1119
|
+
for (const name of names) {
|
|
1120
|
+
if (!name.endsWith('.bak')) continue;
|
|
1121
|
+
const file = path.join(this.snapshotsDir, name);
|
|
1122
|
+
try {
|
|
1123
|
+
if (this.now().getTime() - fs.statSync(file).mtimeMs > SNAPSHOT_KEEP_MS) {
|
|
1124
|
+
fs.unlinkSync(file);
|
|
1125
|
+
removed += 1;
|
|
1126
|
+
}
|
|
1127
|
+
} catch { /* ignore */ }
|
|
1128
|
+
}
|
|
1129
|
+
return removed;
|
|
1130
|
+
}
|
|
1131
|
+
|
|
1132
|
+
/**
|
|
1133
|
+
* One maintenance pass. Called while the caller holds tick.lock, so no other
|
|
1134
|
+
* Router tick can interleave. allowApply is decided by the service.
|
|
1135
|
+
*/
|
|
1136
|
+
async maintain({ allowApply = false } = {}) {
|
|
1137
|
+
const summary = { lease: null, recovered: null, queue: null, apply: null, cleaned: 0, snapshotsRemoved: 0, walBroken: false };
|
|
1138
|
+
try {
|
|
1139
|
+
summary.lease = this.lease.reclaimIfNeeded();
|
|
1140
|
+
} catch (error) {
|
|
1141
|
+
this.#auditSafe('lease.reclaim_failed', { error: String(error?.message ?? error) });
|
|
1142
|
+
}
|
|
1143
|
+
try {
|
|
1144
|
+
summary.recovered = this.recoverApplying();
|
|
1145
|
+
} catch (error) {
|
|
1146
|
+
this.#auditSafe('apply.recover_failed', { error: String(error?.message ?? error) });
|
|
1147
|
+
}
|
|
1148
|
+
summary.cleaned = this.cleanStaleTmp().length;
|
|
1149
|
+
summary.snapshotsRemoved = this.cleanSnapshots();
|
|
1150
|
+
for (let attempt = 0; attempt < 3; attempt += 1) {
|
|
1151
|
+
try {
|
|
1152
|
+
summary.queue = this.queue.maintain();
|
|
1153
|
+
break;
|
|
1154
|
+
} catch (error) {
|
|
1155
|
+
if (error?.code !== 'E_STATE_RACE' || attempt === 2) {
|
|
1156
|
+
this.#auditSafe('queue.maintain_failed', { error: String(error?.message ?? error) });
|
|
1157
|
+
break;
|
|
1158
|
+
}
|
|
1159
|
+
}
|
|
1160
|
+
}
|
|
1161
|
+
// Surface a chain break to service.mjs so it can raise WAL_BROKEN (§3.7).
|
|
1162
|
+
summary.walBroken = summary.queue?.walBroken === true
|
|
1163
|
+
|| this.wal?.status?.().broken === true;
|
|
1164
|
+
if (allowApply && this.config.applyEnabled === true) {
|
|
1165
|
+
const approved = this.#scan().proposals.some((proposal) => proposal.status === 'approved');
|
|
1166
|
+
if (approved && !this.lease.read()) {
|
|
1167
|
+
for (let attempt = 0; attempt < 3; attempt += 1) {
|
|
1168
|
+
try {
|
|
1169
|
+
summary.apply = await this.apply({});
|
|
1170
|
+
break;
|
|
1171
|
+
} catch (error) {
|
|
1172
|
+
if (error?.code === 'E_TEST_CRASH') break;
|
|
1173
|
+
if (error?.code !== 'E_STATE_RACE' || attempt === 2) throw error;
|
|
1174
|
+
}
|
|
1175
|
+
}
|
|
1176
|
+
}
|
|
1177
|
+
}
|
|
1178
|
+
return summary;
|
|
1179
|
+
}
|
|
1180
|
+
|
|
1181
|
+
/** Queue/lease/WAL snapshot for status.json (never includes proposal bodies). */
|
|
1182
|
+
status() {
|
|
1183
|
+
const scan = this.#scan();
|
|
1184
|
+
const counts = { pending: 0, queued: 0, applying: 0, blockedOnUser: 0, expired: 0 };
|
|
1185
|
+
let doneToday = 0;
|
|
1186
|
+
let conflicts = 0;
|
|
1187
|
+
let superseded = 0;
|
|
1188
|
+
const today = isoNow(this.now()).slice(0, 10);
|
|
1189
|
+
for (const proposal of scan.proposals) {
|
|
1190
|
+
if (proposal.status === 'pending') counts.pending += 1;
|
|
1191
|
+
else if (proposal.status === 'approved') counts.queued += 1;
|
|
1192
|
+
else if (proposal.status === 'applying') counts.applying += 1;
|
|
1193
|
+
else if (proposal.status === 'blocked-on-user') counts.blockedOnUser += 1;
|
|
1194
|
+
else if (proposal.status === 'expired') counts.expired += 1;
|
|
1195
|
+
if (proposal.status === 'conflict') conflicts += 1;
|
|
1196
|
+
if (proposal.status === 'superseded') superseded += 1;
|
|
1197
|
+
if (proposal.status === 'done' && String(proposal.result?.appliedAt ?? '').startsWith(today)) doneToday += 1;
|
|
1198
|
+
}
|
|
1199
|
+
const view = this.queue?.view?.() ?? { entries: [], blocked: [], seqCounter: 1, etaMs: 0, writer: null };
|
|
1200
|
+
return {
|
|
1201
|
+
proposals: { doneToday, conflicts, superseded, counts },
|
|
1202
|
+
queue: {
|
|
1203
|
+
seqCounter: view.seqCounter ?? 1,
|
|
1204
|
+
depth: view.entries?.length ?? 0,
|
|
1205
|
+
etaMs: view.etaMs ?? 0,
|
|
1206
|
+
starvation: false,
|
|
1207
|
+
writer: view.writer ?? null,
|
|
1208
|
+
blocked: (view.blocked ?? []).slice(0, 8),
|
|
1209
|
+
},
|
|
1210
|
+
lease: this.lease.status(),
|
|
1211
|
+
wal: this.wal.status(),
|
|
1212
|
+
};
|
|
1213
|
+
}
|
|
1214
|
+
}
|
|
1215
|
+
|
|
1216
|
+
export function createApplier(options) {
|
|
1217
|
+
return new Applier(options);
|
|
1218
|
+
}
|