@jjh32456/longlive 0.0.0-stage → 1.8.12
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 +205 -0
- package/LICENSE +21 -0
- package/QUICKSTART.md +363 -0
- package/README.en.md +55 -0
- package/README.md +225 -2
- package/SPEC.md +211 -0
- package/build-info.json +1555 -0
- package/cordis.patch.yml +177 -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 +807 -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 +46 -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 +160 -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-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/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 +146 -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 +824 -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 +912 -0
- package/src/handoff/index.js +944 -0
- package/src/handoff/model.js +1010 -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 +657 -0
- package/src/identity/index.js +337 -0
- package/src/identity/inject-position.js +131 -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 +124 -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/audit-records.js +222 -0
- package/src/memory/auto-cards.js +441 -0
- package/src/memory/capture-host.js +228 -0
- package/src/memory/capture.js +457 -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/conclusion-distill.js +332 -0
- package/src/memory/conclusion-drafts.js +239 -0
- package/src/memory/conflicts.js +147 -0
- package/src/memory/consolidate.js +815 -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 +410 -0
- package/src/memory/forget.js +512 -0
- package/src/memory/frames-activation.js +247 -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 +362 -0
- package/src/memory/l2-gate.js +169 -0
- package/src/memory/lifecycle.js +107 -0
- package/src/memory/lock.js +121 -0
- package/src/memory/maintenance.js +785 -0
- package/src/memory/manifest.js +245 -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.js +963 -0
- package/src/memory/provenance.js +119 -0
- package/src/memory/recall-v2.js +206 -0
- package/src/memory/recall.js +256 -0
- package/src/memory/reconcile.js +265 -0
- package/src/memory/records.js +433 -0
- package/src/memory/reinforce.js +145 -0
- package/src/memory/retention.js +128 -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/version-chain.js +264 -0
- package/src/memory/wal.js +137 -0
- package/src/memory/working-frame.js +516 -0
- package/src/metrics/classify.mjs +189 -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-fallback.mjs +235 -0
- package/src/recall/archive-search.mjs +425 -0
- package/src/recall/cards.mjs +202 -0
- package/src/recall/edges.js +379 -0
- package/src/recall/embedding.mjs +698 -0
- package/src/recall/entities.mjs +112 -0
- package/src/recall/explain.mjs +433 -0
- package/src/recall/force-policy.mjs +138 -0
- package/src/recall/index.js +1036 -0
- package/src/recall/inject-order.mjs +277 -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 +765 -0
- package/src/recall/shared-visibility.js +302 -0
- package/src/recall/time-normalizer.mjs +196 -0
- package/src/retention/config.js +106 -0
- package/src/retention/index.js +643 -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 +3146 -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,685 @@
|
|
|
1
|
+
// WP4a · proposal WAL (DESIGN §3.5/§5.4/§5.10/§3.7).
|
|
2
|
+
//
|
|
3
|
+
// One append-only line per state transition, fsync'd before canonical or the
|
|
4
|
+
// proposal file is touched. Replay verifies the prev/hash chain and stops at
|
|
5
|
+
// the first broken line: it never guesses what came after a break.
|
|
6
|
+
//
|
|
7
|
+
// Segmentation (DESIGN §3.5): the active file rotates to
|
|
8
|
+
// `wal.<firstSeq>.jsonl` when it reaches 2 MB or 5,000 lines, and the newest
|
|
9
|
+
// three archived segments are kept. Before rotating, non-terminal proposals,
|
|
10
|
+
// their queue.assign summaries, seqCounter, the queue head and the latest
|
|
11
|
+
// apply.begin are folded into `wal.snapshot.json` (atomic tmp+fsync+rename+
|
|
12
|
+
// read-back). Replay starts from that snapshot and continues through the
|
|
13
|
+
// archived segments by seq, then the active file, verifying prev/hash across
|
|
14
|
+
// every segment boundary.
|
|
15
|
+
//
|
|
16
|
+
// Pruning only runs after a successful snapshot: a line may be dropped when it
|
|
17
|
+
// is older than seven days AND terminal (its event type or its proposal is
|
|
18
|
+
// terminal). lease.expired / apply.conflict / restore.required / rollback.*
|
|
19
|
+
// are never dropped. Every dropped line is first written to the audit archive;
|
|
20
|
+
// without an audit callback nothing is pruned (no silent loss of incident
|
|
21
|
+
// evidence).
|
|
22
|
+
//
|
|
23
|
+
// WAL is the source of truth for assignment/apply decisions. This module never
|
|
24
|
+
// edits proposal files and never writes canonical memory.
|
|
25
|
+
|
|
26
|
+
import fs from 'node:fs';
|
|
27
|
+
import path from 'node:path';
|
|
28
|
+
|
|
29
|
+
import {
|
|
30
|
+
appendJsonLineDurable,
|
|
31
|
+
isTerminalProposalStatus,
|
|
32
|
+
readQueueFile,
|
|
33
|
+
readWalLines,
|
|
34
|
+
scanProposalDir,
|
|
35
|
+
StoreError,
|
|
36
|
+
writeJsonStrict,
|
|
37
|
+
} from './store.mjs';
|
|
38
|
+
import { OwnerLock, RECLAIM_STALE_MIN_MS } from './lock.mjs';
|
|
39
|
+
import { sha256Hex, writeTextAtomic } from './paths.mjs';
|
|
40
|
+
|
|
41
|
+
export const WAL_EVENT_TYPES = Object.freeze([
|
|
42
|
+
'queue.assign',
|
|
43
|
+
'queue.assign.recovered',
|
|
44
|
+
'queue.approve',
|
|
45
|
+
'queue.cancel',
|
|
46
|
+
'queue.reconcile',
|
|
47
|
+
'lease.acquire',
|
|
48
|
+
'lease.renew',
|
|
49
|
+
'lease.release',
|
|
50
|
+
'lease.expired',
|
|
51
|
+
'apply.begin',
|
|
52
|
+
'apply.abort',
|
|
53
|
+
'apply.done',
|
|
54
|
+
'apply.conflict',
|
|
55
|
+
'restore.required',
|
|
56
|
+
'rollback.begin',
|
|
57
|
+
'rollback.done',
|
|
58
|
+
]);
|
|
59
|
+
|
|
60
|
+
/** DESIGN §3.5: rotate at 2 MB (configurable lower bound 256 KB) or 5,000 lines. */
|
|
61
|
+
export const WAL_MAX_LINES = 5000;
|
|
62
|
+
/** DESIGN §3.5: keep the newest three archived segments (active + 3 = 2 MB×4). */
|
|
63
|
+
export const WAL_KEEP_SEGMENTS = 3;
|
|
64
|
+
/** DESIGN §3.5: terminal events older than seven days may be folded away. */
|
|
65
|
+
export const WAL_PRUNE_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000;
|
|
66
|
+
export const WAL_SNAPSHOT_VERSION = 1;
|
|
67
|
+
|
|
68
|
+
/** Incident records that are never pruned, regardless of age. */
|
|
69
|
+
export const WAL_NEVER_PRUNE_EVENTS = Object.freeze([
|
|
70
|
+
'lease.expired',
|
|
71
|
+
'apply.conflict',
|
|
72
|
+
'restore.required',
|
|
73
|
+
'rollback.begin',
|
|
74
|
+
'rollback.done',
|
|
75
|
+
]);
|
|
76
|
+
|
|
77
|
+
/** Events that terminate their own audit row (safe to prune when old). */
|
|
78
|
+
const WAL_TERMINAL_EVENTS = new Set([
|
|
79
|
+
'queue.cancel',
|
|
80
|
+
'lease.release',
|
|
81
|
+
'apply.done',
|
|
82
|
+
'apply.abort',
|
|
83
|
+
]);
|
|
84
|
+
|
|
85
|
+
const SEGMENT_RE = /^wal\.(\d+)\.jsonl$/u;
|
|
86
|
+
const QUEUE_ASSIGN_EVENTS = new Set([
|
|
87
|
+
'queue.assign',
|
|
88
|
+
'queue.assign.recovered',
|
|
89
|
+
'queue.approve',
|
|
90
|
+
]);
|
|
91
|
+
const APPLY_BEGIN_EVENTS = new Set(['apply.begin', 'rollback.begin']);
|
|
92
|
+
|
|
93
|
+
function ticketNumber(ticket) {
|
|
94
|
+
const match = /^q-(\d{4,})$/u.exec(String(ticket ?? ''));
|
|
95
|
+
return match ? Number(match[1]) : 0;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** Recompute the line hash exactly as proposals.mjs writes it. */
|
|
99
|
+
export function walLineHash(line) {
|
|
100
|
+
const { prev = '', hash, ...body } = line ?? {};
|
|
101
|
+
return `sha256:${sha256Hex(`${prev}\n${JSON.stringify(body)}`)}`;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export class Wal {
|
|
105
|
+
constructor({
|
|
106
|
+
file,
|
|
107
|
+
audit = null,
|
|
108
|
+
logger = null,
|
|
109
|
+
maxBytes = 2097152,
|
|
110
|
+
maxLines = WAL_MAX_LINES,
|
|
111
|
+
keepSegments = WAL_KEEP_SEGMENTS,
|
|
112
|
+
pruneAgeMs = WAL_PRUNE_MAX_AGE_MS,
|
|
113
|
+
lockFile = null,
|
|
114
|
+
lockWaitMs = 5000,
|
|
115
|
+
lockStaleMs = RECLAIM_STALE_MIN_MS,
|
|
116
|
+
now = () => new Date(),
|
|
117
|
+
} = {}) {
|
|
118
|
+
this.file = file;
|
|
119
|
+
this.audit = audit;
|
|
120
|
+
this.logger = logger;
|
|
121
|
+
this.dir = path.dirname(file);
|
|
122
|
+
this.snapshotFile = path.join(this.dir, 'wal.snapshot.json');
|
|
123
|
+
// D-CR6: one cross-process lock covers "read lastSeq/lastHash -> append" and
|
|
124
|
+
// rotation. proposals/ lives under <vault>/proposals, so the lock lives at
|
|
125
|
+
// <vault>/locks/wal.lock (custom layouts keep it next to the WAL dir).
|
|
126
|
+
const lockParent = path.basename(this.dir) === 'proposals' ? path.dirname(this.dir) : this.dir;
|
|
127
|
+
this.lockFile = lockFile ?? path.join(lockParent, 'locks', 'wal.lock');
|
|
128
|
+
this.lockWaitMs = Number.isFinite(lockWaitMs) && lockWaitMs >= 0 ? Math.trunc(lockWaitMs) : 5000;
|
|
129
|
+
this.lock = new OwnerLock({
|
|
130
|
+
file: this.lockFile,
|
|
131
|
+
evidencePrefix: 'wal.lock.reclaimed-',
|
|
132
|
+
staleMs: lockStaleMs,
|
|
133
|
+
now,
|
|
134
|
+
label: 'wal.lock',
|
|
135
|
+
audit: (kind, data) => this.#auditSafe(kind, data),
|
|
136
|
+
logger,
|
|
137
|
+
});
|
|
138
|
+
this.maxBytes = Number.isInteger(maxBytes) && maxBytes > 0 ? maxBytes : 2097152;
|
|
139
|
+
this.maxLines = Number.isInteger(maxLines) && maxLines > 0 ? maxLines : WAL_MAX_LINES;
|
|
140
|
+
this.keepSegments = Number.isInteger(keepSegments) && keepSegments >= 0 ? keepSegments : WAL_KEEP_SEGMENTS;
|
|
141
|
+
this.pruneAgeMs = Number.isFinite(pruneAgeMs) && pruneAgeMs >= 0 ? pruneAgeMs : WAL_PRUNE_MAX_AGE_MS;
|
|
142
|
+
this.now = typeof now === 'function' ? now : () => new Date();
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
#auditSafe(kind, data) {
|
|
146
|
+
try { this.audit?.(kind, data); } catch { /* audit never blocks the WAL */ }
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** Archived segments, ascending by their first seq. */
|
|
150
|
+
listSegments() {
|
|
151
|
+
let names = [];
|
|
152
|
+
try { names = fs.readdirSync(this.dir); } catch { return []; }
|
|
153
|
+
const segments = [];
|
|
154
|
+
for (const name of names) {
|
|
155
|
+
const match = SEGMENT_RE.exec(name);
|
|
156
|
+
if (!match) continue;
|
|
157
|
+
segments.push({ name, file: path.join(this.dir, name), firstSeq: Number(match[1]) });
|
|
158
|
+
}
|
|
159
|
+
segments.sort((a, b) => a.firstSeq - b.firstSeq || a.name.localeCompare(b.name));
|
|
160
|
+
return segments;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
#rawLineCount(file) {
|
|
164
|
+
try {
|
|
165
|
+
return fs.readFileSync(file, 'utf8').split('\n').filter((line) => line.trim() !== '').length;
|
|
166
|
+
} catch {
|
|
167
|
+
return 0;
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** Parsed snapshot, or null. A corrupt snapshot is audited, never repaired. */
|
|
172
|
+
readSnapshot() {
|
|
173
|
+
let text = null;
|
|
174
|
+
try {
|
|
175
|
+
text = fs.readFileSync(this.snapshotFile, 'utf8');
|
|
176
|
+
} catch (error) {
|
|
177
|
+
if (error?.code !== 'ENOENT') this.#auditSafe('wal.snapshot_unreadable', { error: error?.code ?? 'E_READ' });
|
|
178
|
+
return null;
|
|
179
|
+
}
|
|
180
|
+
try {
|
|
181
|
+
const value = JSON.parse(text);
|
|
182
|
+
if (!value || typeof value !== 'object' || value.v !== WAL_SNAPSHOT_VERSION
|
|
183
|
+
|| !Number.isInteger(value.upToSeq) || value.upToSeq < 0
|
|
184
|
+
|| typeof value.lastHash !== 'string'
|
|
185
|
+
|| !Array.isArray(value.proposals) || !Array.isArray(value.assignments)) {
|
|
186
|
+
throw new Error('invalid snapshot shape');
|
|
187
|
+
}
|
|
188
|
+
return value;
|
|
189
|
+
} catch (error) {
|
|
190
|
+
if (!this.snapshotCorruptionAudited) {
|
|
191
|
+
this.snapshotCorruptionAudited = true;
|
|
192
|
+
this.#auditSafe('wal.snapshot_corrupt', { error: String(error?.message ?? error) });
|
|
193
|
+
}
|
|
194
|
+
return null;
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
#segmentFiles() {
|
|
199
|
+
return this.listSegments().map((segment) => segment.file);
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/**
|
|
203
|
+
* Read snapshot base + archived segments + active file. Folded lines
|
|
204
|
+
* (seq <= snapshot.upToSeq) are evidence, not replay input: only their own
|
|
205
|
+
* hash is verified (pruning may leave gaps inside a folded segment). Lines
|
|
206
|
+
* after the boundary are replayed strictly by seq/prev/hash, continuously
|
|
207
|
+
* across segment boundaries.
|
|
208
|
+
*/
|
|
209
|
+
read() {
|
|
210
|
+
const snapshot = this.readSnapshot();
|
|
211
|
+
const boundary = snapshot ? snapshot.upToSeq : 0;
|
|
212
|
+
const files = [...this.#segmentFiles(), this.file];
|
|
213
|
+
const lines = [];
|
|
214
|
+
let lastSeq = boundary;
|
|
215
|
+
let lastHash = snapshot ? snapshot.lastHash : '';
|
|
216
|
+
let broken = false;
|
|
217
|
+
let brokenAt = null;
|
|
218
|
+
let error = null;
|
|
219
|
+
let rawLines = 0;
|
|
220
|
+
let parsedLines = 0;
|
|
221
|
+
let boundaryLineSeen = false;
|
|
222
|
+
let boundaryHashOk = true;
|
|
223
|
+
let foldedBad = null;
|
|
224
|
+
let readFailure = null;
|
|
225
|
+
|
|
226
|
+
outer:
|
|
227
|
+
for (const file of files) {
|
|
228
|
+
rawLines += this.#rawLineCount(file);
|
|
229
|
+
const read = readWalLines(file);
|
|
230
|
+
if (read.error && read.error !== 'ENOENT') readFailure = read.error;
|
|
231
|
+
parsedLines += read.lines.length;
|
|
232
|
+
for (const line of read.lines) {
|
|
233
|
+
if (boundary > 0 && Number.isInteger(line.seq) && line.seq <= boundary) {
|
|
234
|
+
if (!Number.isInteger(line.seq) || typeof line.hash !== 'string' || line.hash !== walLineHash(line)) {
|
|
235
|
+
foldedBad = foldedBad ?? { file: path.basename(file), seq: line.seq ?? null };
|
|
236
|
+
}
|
|
237
|
+
if (line.seq === boundary) {
|
|
238
|
+
boundaryLineSeen = true;
|
|
239
|
+
if (line.hash !== snapshot.lastHash) boundaryHashOk = false;
|
|
240
|
+
}
|
|
241
|
+
continue;
|
|
242
|
+
}
|
|
243
|
+
const expectedSeq = lastSeq + 1;
|
|
244
|
+
if (!Number.isInteger(line.seq) || line.seq !== expectedSeq
|
|
245
|
+
|| String(line.prev ?? '') !== lastHash
|
|
246
|
+
|| typeof line.hash !== 'string' || line.hash !== walLineHash(line)) {
|
|
247
|
+
broken = true;
|
|
248
|
+
brokenAt = lines.length;
|
|
249
|
+
break outer;
|
|
250
|
+
}
|
|
251
|
+
lines.push(line);
|
|
252
|
+
lastSeq = line.seq;
|
|
253
|
+
lastHash = line.hash;
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
if (!broken && boundary > 0 && (!boundaryHashOk || foldedBad)) {
|
|
258
|
+
broken = true;
|
|
259
|
+
brokenAt = 0;
|
|
260
|
+
error = foldedBad ? 'E_FOLDED_LINE' : 'E_SNAPSHOT_BOUNDARY';
|
|
261
|
+
}
|
|
262
|
+
// D-CR16: a failed read is itself a broken chain. Appending would restart
|
|
263
|
+
// seq at 1 and destroy the remaining chain, so append/rotate must refuse.
|
|
264
|
+
if (!broken && readFailure) {
|
|
265
|
+
broken = true;
|
|
266
|
+
brokenAt = lines.length;
|
|
267
|
+
error = readFailure;
|
|
268
|
+
}
|
|
269
|
+
const skipped = Math.max(0, rawLines - parsedLines);
|
|
270
|
+
if (skipped > 0 && !this.corruptionAudited) {
|
|
271
|
+
// A half-written tail is dropped, not "repaired" (DESIGN §3.7/§5.4).
|
|
272
|
+
this.corruptionAudited = true;
|
|
273
|
+
this.#auditSafe('wal.corrupt', { skipped, file: path.basename(this.file) });
|
|
274
|
+
}
|
|
275
|
+
return {
|
|
276
|
+
lines,
|
|
277
|
+
broken,
|
|
278
|
+
brokenAt,
|
|
279
|
+
lastSeq,
|
|
280
|
+
lastHash,
|
|
281
|
+
error: error ?? readFailure ?? null,
|
|
282
|
+
snapshot,
|
|
283
|
+
segments: files.filter((file) => file !== this.file).map((file) => path.basename(file)),
|
|
284
|
+
boundaryLineSeen,
|
|
285
|
+
};
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
#activeStats() {
|
|
289
|
+
let bytes = 0;
|
|
290
|
+
try { bytes = fs.statSync(this.file).size; } catch { /* no file yet */ }
|
|
291
|
+
const parsed = readWalLines(this.file).lines;
|
|
292
|
+
return { bytes, lines: parsed.length, parsed };
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
#shouldRotate() {
|
|
296
|
+
const stats = this.#activeStats();
|
|
297
|
+
if (stats.lines === 0) return false;
|
|
298
|
+
return stats.bytes >= this.maxBytes || stats.lines >= this.maxLines;
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/**
|
|
302
|
+
* Fold the replayable suffix into wal.snapshot.json.
|
|
303
|
+
* Caller has verified the chain and is rotating the active file.
|
|
304
|
+
*/
|
|
305
|
+
#buildSnapshot(state) {
|
|
306
|
+
const old = state.snapshot;
|
|
307
|
+
const proposals = scanProposalDir(this.dir).proposals;
|
|
308
|
+
const nonTerminal = proposals.filter((proposal) => !isTerminalProposalStatus(proposal.status));
|
|
309
|
+
const activeIds = new Set(nonTerminal.map((proposal) => proposal.id));
|
|
310
|
+
|
|
311
|
+
const assignmentById = new Map();
|
|
312
|
+
for (const assignment of old?.assignments ?? []) {
|
|
313
|
+
if (assignment && typeof assignment.proposalId === 'string' && activeIds.has(assignment.proposalId)) {
|
|
314
|
+
assignmentById.set(assignment.proposalId, assignment);
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
const applyById = new Map();
|
|
318
|
+
for (const proposal of old?.proposals ?? []) {
|
|
319
|
+
if (proposal && activeIds.has(proposal.id) && proposal.apply) applyById.set(proposal.id, proposal.apply);
|
|
320
|
+
}
|
|
321
|
+
for (const line of state.lines) {
|
|
322
|
+
if (typeof line.proposalId !== 'string' || !activeIds.has(line.proposalId)) continue;
|
|
323
|
+
if (QUEUE_ASSIGN_EVENTS.has(line.ev)) {
|
|
324
|
+
assignmentById.set(line.proposalId, {
|
|
325
|
+
proposalId: line.proposalId,
|
|
326
|
+
ticket: line.ticket ?? null,
|
|
327
|
+
seq: ticketNumber(line.ticket),
|
|
328
|
+
});
|
|
329
|
+
}
|
|
330
|
+
if (APPLY_BEGIN_EVENTS.has(line.ev)) {
|
|
331
|
+
applyById.set(line.proposalId, {
|
|
332
|
+
ev: line.ev,
|
|
333
|
+
seq: line.seq,
|
|
334
|
+
at: line.at ?? null,
|
|
335
|
+
ticket: line.ticket ?? null,
|
|
336
|
+
proposalId: line.proposalId,
|
|
337
|
+
baseSha: line.baseSha ?? null,
|
|
338
|
+
afterSha: line.afterSha ?? null,
|
|
339
|
+
snapshot: line.snapshot ?? null,
|
|
340
|
+
});
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
const queue = readQueueFile(path.join(this.dir, 'queue.json'));
|
|
345
|
+
let seqCounter = Math.max(
|
|
346
|
+
1,
|
|
347
|
+
Number.isInteger(old?.seqCounter) ? old.seqCounter : 1,
|
|
348
|
+
Number.isInteger(queue?.seqCounter) ? queue.seqCounter : 1,
|
|
349
|
+
...state.lines.map((line) => ticketNumber(line.ticket) + 1),
|
|
350
|
+
...nonTerminal.map((proposal) => ticketNumber(proposal.queue?.ticket) + 1),
|
|
351
|
+
);
|
|
352
|
+
|
|
353
|
+
const head = queueHead(queue, nonTerminal);
|
|
354
|
+
const snapshot = {
|
|
355
|
+
v: WAL_SNAPSHOT_VERSION,
|
|
356
|
+
at: this.now().toISOString(),
|
|
357
|
+
upToSeq: state.lastSeq,
|
|
358
|
+
lastSeq: state.lastSeq,
|
|
359
|
+
lastHash: state.lastHash,
|
|
360
|
+
lastAt: state.lines.at(-1)?.at ?? old?.lastAt ?? null,
|
|
361
|
+
seqCounter,
|
|
362
|
+
head,
|
|
363
|
+
proposals: nonTerminal.map((proposal) => ({
|
|
364
|
+
id: proposal.id,
|
|
365
|
+
status: proposal.status,
|
|
366
|
+
ticket: proposal.queue?.ticket ?? null,
|
|
367
|
+
seq: proposal.queue?.seq ?? null,
|
|
368
|
+
queuedAt: proposal.queue?.queuedAt ?? proposal.createdAt ?? null,
|
|
369
|
+
priority: proposal.queue?.priority ?? null,
|
|
370
|
+
effectivePriority: proposal.queue?.effectivePriority ?? proposal.queue?.priority ?? null,
|
|
371
|
+
op: proposal.op ?? null,
|
|
372
|
+
target: proposal.target ?? null,
|
|
373
|
+
originSessionId: proposal.origin?.sessionId ?? null,
|
|
374
|
+
updatedAt: proposal.updatedAt ?? proposal.createdAt ?? null,
|
|
375
|
+
attempts: Number.isInteger(proposal.queue?.attempts) ? proposal.queue.attempts : 0,
|
|
376
|
+
apply: applyById.get(proposal.id) ?? null,
|
|
377
|
+
})),
|
|
378
|
+
assignments: nonTerminal
|
|
379
|
+
.filter((proposal) => assignmentById.has(proposal.id))
|
|
380
|
+
.map((proposal) => {
|
|
381
|
+
const assignment = assignmentById.get(proposal.id);
|
|
382
|
+
return {
|
|
383
|
+
proposalId: proposal.id,
|
|
384
|
+
ticket: assignment.ticket ?? null,
|
|
385
|
+
seq: assignment.seq ?? ticketNumber(assignment.ticket),
|
|
386
|
+
};
|
|
387
|
+
}),
|
|
388
|
+
segments: this.#segmentFiles().map((file) => path.basename(file)),
|
|
389
|
+
};
|
|
390
|
+
return snapshot;
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
/**
|
|
394
|
+
* D-CR6: cross-process mutual exclusion for the read-lastSeq -> append (and
|
|
395
|
+
* rotate) window. The lock is held for the whole operation and released in
|
|
396
|
+
* finally; a foreign/stale holder is only replaced through OwnerLock's
|
|
397
|
+
* five-step controlled takeover.
|
|
398
|
+
*/
|
|
399
|
+
#withWalLock(fn) {
|
|
400
|
+
const acquired = this.lock.acquire({ waitMs: this.lockWaitMs });
|
|
401
|
+
if (!acquired.ok) {
|
|
402
|
+
this.#auditSafe('wal.lock_busy', {
|
|
403
|
+
reason: acquired.reason,
|
|
404
|
+
holderPid: acquired.holder?.pid ?? null,
|
|
405
|
+
});
|
|
406
|
+
throw new StoreError('E_WAL_BUSY', 'WAL lock is held by another writer', { reason: acquired.reason });
|
|
407
|
+
}
|
|
408
|
+
try {
|
|
409
|
+
return fn();
|
|
410
|
+
} finally {
|
|
411
|
+
this.lock.release();
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
/**
|
|
416
|
+
* Rotate the active file, then fold before pruning. Order is crash-safe:
|
|
417
|
+
* rename -> (snapshot) -> prune. A crash after rename but before snapshot
|
|
418
|
+
* simply replays the archived segment on top of the old snapshot.
|
|
419
|
+
*/
|
|
420
|
+
rotate(options = {}) {
|
|
421
|
+
return this.#withWalLock(() => this.#rotateLocked(options));
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
#rotateLocked({ force = false } = {}) {
|
|
425
|
+
const state = this.read();
|
|
426
|
+
if (state.broken) {
|
|
427
|
+
throw new StoreError('E_WAL_BROKEN', 'cannot rotate a broken WAL', { brokenAt: state.brokenAt });
|
|
428
|
+
}
|
|
429
|
+
const stats = this.#activeStats();
|
|
430
|
+
if (stats.lines === 0) return { rotated: false, reason: 'empty', snapshot: null, pruned: [] };
|
|
431
|
+
if (!force && stats.bytes < this.maxBytes && stats.lines < this.maxLines) {
|
|
432
|
+
return { rotated: false, reason: 'below-threshold', snapshot: null, pruned: [] };
|
|
433
|
+
}
|
|
434
|
+
const firstSeq = stats.parsed[0].seq;
|
|
435
|
+
const lastLine = state.lines.at(-1) ?? stats.parsed.at(-1);
|
|
436
|
+
if (!Number.isInteger(firstSeq) || !lastLine) return { rotated: false, reason: 'empty', snapshot: null, pruned: [] };
|
|
437
|
+
|
|
438
|
+
const target = path.join(this.dir, `wal.${firstSeq}.jsonl`);
|
|
439
|
+
if (fs.existsSync(target)) {
|
|
440
|
+
// Two segments with the same first seq mean the file state was already
|
|
441
|
+
// inconsistent; do not overwrite evidence.
|
|
442
|
+
const error = new StoreError('E_WAL_SEGMENT_EXISTS', `segment ${path.basename(target)} already exists`, { segment: target });
|
|
443
|
+
this.#auditSafe('wal.rotate_failed', { segment: path.basename(target), error: error.message });
|
|
444
|
+
throw error;
|
|
445
|
+
}
|
|
446
|
+
try {
|
|
447
|
+
fs.renameSync(this.file, target);
|
|
448
|
+
} catch (error) {
|
|
449
|
+
if (error?.code === 'ENOENT') {
|
|
450
|
+
// Another writer rotated first; re-read and continue on the new active.
|
|
451
|
+
const reread = this.read();
|
|
452
|
+
return { rotated: false, reason: 'raced', snapshot: reread.snapshot, pruned: [] };
|
|
453
|
+
}
|
|
454
|
+
this.#auditSafe('wal.rotate_failed', { error: error?.code ?? 'E_RENAME' });
|
|
455
|
+
throw new StoreError(error?.code ?? 'E_RENAME', error?.message ?? 'WAL rotate failed', { segment: target });
|
|
456
|
+
}
|
|
457
|
+
// Make the active path exist again even before the next append.
|
|
458
|
+
try { fs.closeSync(fs.openSync(this.file, 'a')); } catch { /* append recreates it */ }
|
|
459
|
+
|
|
460
|
+
let snapshot = null;
|
|
461
|
+
let snapshotError = null;
|
|
462
|
+
try {
|
|
463
|
+
snapshot = this.#buildSnapshot(state);
|
|
464
|
+
writeJsonStrict(this.snapshotFile, snapshot);
|
|
465
|
+
this.#auditSafe('wal.snapshot', {
|
|
466
|
+
upToSeq: snapshot.upToSeq,
|
|
467
|
+
seqCounter: snapshot.seqCounter,
|
|
468
|
+
proposals: snapshot.proposals.length,
|
|
469
|
+
});
|
|
470
|
+
} catch (error) {
|
|
471
|
+
snapshotError = error;
|
|
472
|
+
// Old snapshot + archived segment still replay without loss; keep every
|
|
473
|
+
// segment (no pruning) and retry the fold on the next rotation.
|
|
474
|
+
this.#auditSafe('wal.snapshot_failed', { error: error?.code ?? 'E_SNAPSHOT', message: String(error?.message ?? error) });
|
|
475
|
+
}
|
|
476
|
+
const pruned = snapshotError ? [] : this.pruneSegments();
|
|
477
|
+
this.#auditSafe('wal.rotate', {
|
|
478
|
+
segment: path.basename(target),
|
|
479
|
+
upToSeq: stats.parsed.at(-1).seq,
|
|
480
|
+
snapshot: snapshot ? snapshot.upToSeq : null,
|
|
481
|
+
pruned: pruned.length,
|
|
482
|
+
});
|
|
483
|
+
return {
|
|
484
|
+
rotated: true,
|
|
485
|
+
segment: path.basename(target),
|
|
486
|
+
upToSeq: snapshot?.upToSeq ?? null,
|
|
487
|
+
snapshot,
|
|
488
|
+
snapshotError: snapshotError ? (snapshotError.code ?? 'E_SNAPSHOT') : null,
|
|
489
|
+
pruned,
|
|
490
|
+
};
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
/**
|
|
494
|
+
* Drop older-than-seven-days terminal lines from segments beyond the newest
|
|
495
|
+
* `keepSegments`. Never runs without a snapshot. Each dropped line is written
|
|
496
|
+
* to the audit archive first; if the audit call fails the line stays.
|
|
497
|
+
*/
|
|
498
|
+
pruneSegments() {
|
|
499
|
+
if (!this.readSnapshot()) return [];
|
|
500
|
+
const segments = this.listSegments();
|
|
501
|
+
const excess = segments.length - this.keepSegments;
|
|
502
|
+
if (excess <= 0) return [];
|
|
503
|
+
const proposals = scanProposalDir(this.dir).proposals;
|
|
504
|
+
const proposalsById = new Map(proposals.map((proposal) => [proposal.id, proposal]));
|
|
505
|
+
const cutoff = this.now().getTime() - this.pruneAgeMs;
|
|
506
|
+
const pruned = [];
|
|
507
|
+
for (const segment of segments.slice(0, excess)) {
|
|
508
|
+
let text = null;
|
|
509
|
+
try { text = fs.readFileSync(segment.file, 'utf8'); } catch { continue; }
|
|
510
|
+
const kept = [];
|
|
511
|
+
const dropped = [];
|
|
512
|
+
for (const raw of text.split('\n')) {
|
|
513
|
+
if (raw.trim() === '') continue;
|
|
514
|
+
let line = null;
|
|
515
|
+
try { line = JSON.parse(raw); } catch { kept.push(raw); continue; }
|
|
516
|
+
if (!this.#prunable(line, proposalsById, cutoff)) {
|
|
517
|
+
kept.push(raw);
|
|
518
|
+
continue;
|
|
519
|
+
}
|
|
520
|
+
if (!this.#archivePrunedEvent(line)) {
|
|
521
|
+
// No audit archive: keeping the line is the only way not to lose an
|
|
522
|
+
// incident record silently.
|
|
523
|
+
kept.push(raw);
|
|
524
|
+
continue;
|
|
525
|
+
}
|
|
526
|
+
dropped.push(line);
|
|
527
|
+
}
|
|
528
|
+
if (dropped.length === 0) continue;
|
|
529
|
+
if (kept.length === 0) {
|
|
530
|
+
try {
|
|
531
|
+
fs.unlinkSync(segment.file);
|
|
532
|
+
pruned.push({ segment: segment.name, dropped: dropped.length, removed: true });
|
|
533
|
+
} catch {
|
|
534
|
+
continue;
|
|
535
|
+
}
|
|
536
|
+
} else {
|
|
537
|
+
const written = writeTextAtomic(segment.file, `${kept.join('\n')}\n`);
|
|
538
|
+
if (!written.ok) {
|
|
539
|
+
this.#auditSafe('wal.prune_failed', { segment: segment.name, error: written.error ?? 'E_WRITE' });
|
|
540
|
+
continue;
|
|
541
|
+
}
|
|
542
|
+
pruned.push({ segment: segment.name, dropped: dropped.length, removed: false });
|
|
543
|
+
}
|
|
544
|
+
this.#auditSafe('wal.pruned', {
|
|
545
|
+
segment: segment.name,
|
|
546
|
+
dropped: dropped.length,
|
|
547
|
+
events: dropped.map((line) => line.ev),
|
|
548
|
+
removed: kept.length === 0,
|
|
549
|
+
});
|
|
550
|
+
}
|
|
551
|
+
return pruned;
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
#prunable(line, proposalsById, cutoff) {
|
|
555
|
+
if (!line || typeof line !== 'object') return false;
|
|
556
|
+
const ev = String(line.ev ?? '');
|
|
557
|
+
if (WAL_NEVER_PRUNE_EVENTS.includes(ev) || ev.startsWith('rollback.')) return false;
|
|
558
|
+
const at = Date.parse(line.at ?? '');
|
|
559
|
+
if (!Number.isFinite(at) || at >= cutoff) return false;
|
|
560
|
+
const proposal = typeof line.proposalId === 'string' ? proposalsById.get(line.proposalId) : null;
|
|
561
|
+
if (proposal) return isTerminalProposalStatus(proposal.status);
|
|
562
|
+
return WAL_TERMINAL_EVENTS.has(ev);
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
#archivePrunedEvent(line) {
|
|
566
|
+
if (typeof this.audit !== 'function') return false;
|
|
567
|
+
try {
|
|
568
|
+
this.audit('wal.pruned_event', { event: line });
|
|
569
|
+
return true;
|
|
570
|
+
} catch {
|
|
571
|
+
return false;
|
|
572
|
+
}
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
/**
|
|
576
|
+
* Append one event. Refuses to append onto a broken chain: a line after a
|
|
577
|
+
* break would make the break permanent and un-replayable (DESIGN §5.4).
|
|
578
|
+
*/
|
|
579
|
+
append(ev, payload = {}) {
|
|
580
|
+
if (typeof ev !== 'string' || ev === '') throw new StoreError('E_BAD_EVENT', 'WAL event name is required');
|
|
581
|
+
// D-CR6: everything from the length/read check through fsync is one
|
|
582
|
+
// cross-process critical section, so two writers can never both claim
|
|
583
|
+
// seq N (the 20/20 duplicate-seq repro).
|
|
584
|
+
return this.#withWalLock(() => {
|
|
585
|
+
// A crash can leave a half-written tail with no newline. Cut it back to the
|
|
586
|
+
// last complete line before appending; never let a new valid line concatenate
|
|
587
|
+
// onto the corrupt fragment (DESIGN §3.7/§5.4).
|
|
588
|
+
try {
|
|
589
|
+
const raw = fs.readFileSync(this.file, 'utf8');
|
|
590
|
+
if (raw.length > 0 && !raw.endsWith('\n')) {
|
|
591
|
+
const cut = raw.lastIndexOf('\n');
|
|
592
|
+
fs.truncateSync(this.file, cut >= 0 ? Buffer.byteLength(raw.slice(0, cut + 1), 'utf8') : 0);
|
|
593
|
+
this.#auditSafe('wal.truncated', { bytes: Buffer.byteLength(raw, 'utf8') - (cut >= 0 ? Buffer.byteLength(raw.slice(0, cut + 1), 'utf8') : 0) });
|
|
594
|
+
}
|
|
595
|
+
} catch { /* no file yet */ }
|
|
596
|
+
let state = this.read();
|
|
597
|
+
if (state.broken) {
|
|
598
|
+
this.#auditSafe('wal.broken', { brokenAt: state.brokenAt, lastSeq: state.lastSeq, error: state.error ?? null });
|
|
599
|
+
throw new StoreError('E_WAL_BROKEN', 'WAL chain is broken; replay/rebuild required before appending', {
|
|
600
|
+
brokenAt: state.brokenAt,
|
|
601
|
+
error: state.error ?? null,
|
|
602
|
+
});
|
|
603
|
+
}
|
|
604
|
+
// Rotate BEFORE writing, so a full active segment never receives another
|
|
605
|
+
// line (DESIGN §3.5 limits are per segment). Already inside the lock.
|
|
606
|
+
if (this.#shouldRotate()) {
|
|
607
|
+
this.#rotateLocked();
|
|
608
|
+
state = this.read();
|
|
609
|
+
if (state.broken) {
|
|
610
|
+
this.#auditSafe('wal.broken', { brokenAt: state.brokenAt, lastSeq: state.lastSeq });
|
|
611
|
+
throw new StoreError('E_WAL_BROKEN', 'WAL chain is broken after rotation', { brokenAt: state.brokenAt });
|
|
612
|
+
}
|
|
613
|
+
}
|
|
614
|
+
const body = { seq: state.lastSeq + 1, at: new Date().toISOString(), ev, ...payload };
|
|
615
|
+
const prev = state.lastHash;
|
|
616
|
+
const hash = `sha256:${sha256Hex(`${prev}\n${JSON.stringify(body)}`)}`;
|
|
617
|
+
const line = { ...body, prev, hash };
|
|
618
|
+
appendJsonLineDurable(this.file, line);
|
|
619
|
+
return line;
|
|
620
|
+
});
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
/** Find the last event matching a predicate in the replayable suffix. */
|
|
624
|
+
last(predicate) {
|
|
625
|
+
const state = this.read();
|
|
626
|
+
for (let index = state.lines.length - 1; index >= 0; index -= 1) {
|
|
627
|
+
if (predicate(state.lines[index])) return state.lines[index];
|
|
628
|
+
}
|
|
629
|
+
return null;
|
|
630
|
+
}
|
|
631
|
+
|
|
632
|
+
/** Folded apply.begin/rollback.begin for one proposal (survives rotation). */
|
|
633
|
+
snapshotBegin(proposalId) {
|
|
634
|
+
const snapshot = this.readSnapshot();
|
|
635
|
+
const proposal = (snapshot?.proposals ?? []).find((candidate) => candidate.id === proposalId);
|
|
636
|
+
return proposal?.apply ?? null;
|
|
637
|
+
}
|
|
638
|
+
|
|
639
|
+
status() {
|
|
640
|
+
let bytes = 0;
|
|
641
|
+
let segments = 0;
|
|
642
|
+
try {
|
|
643
|
+
bytes = fs.statSync(this.file).size;
|
|
644
|
+
} catch { /* no file yet */ }
|
|
645
|
+
try {
|
|
646
|
+
segments = fs.readdirSync(this.dir).filter((name) => /^wal(\.\d+)?\.jsonl$/u.test(name)).length;
|
|
647
|
+
} catch { /* no dir yet */ }
|
|
648
|
+
const state = this.read();
|
|
649
|
+
return {
|
|
650
|
+
lastSeq: state.lastSeq,
|
|
651
|
+
lastAt: state.lines.at(-1)?.at ?? state.snapshot?.lastAt ?? null,
|
|
652
|
+
bytes,
|
|
653
|
+
segments,
|
|
654
|
+
broken: state.broken,
|
|
655
|
+
};
|
|
656
|
+
}
|
|
657
|
+
}
|
|
658
|
+
|
|
659
|
+
function queueHead(queue, proposals) {
|
|
660
|
+
const entry = Array.isArray(queue?.entries) ? queue.entries[0] : null;
|
|
661
|
+
if (entry && typeof entry.ticket === 'string') {
|
|
662
|
+
return { ticket: entry.ticket, proposalId: entry.proposalId ?? null };
|
|
663
|
+
}
|
|
664
|
+
const ordered = [...proposals].sort((a, b) => {
|
|
665
|
+
const pa = priorityIndex(a.queue?.effectivePriority ?? a.queue?.priority);
|
|
666
|
+
const pb = priorityIndex(b.queue?.effectivePriority ?? b.queue?.priority);
|
|
667
|
+
if (pa !== pb) return pa - pb;
|
|
668
|
+
const at = Date.parse(a.queue?.queuedAt ?? a.createdAt ?? '');
|
|
669
|
+
const bt = Date.parse(b.queue?.queuedAt ?? b.createdAt ?? '');
|
|
670
|
+
if (Number.isFinite(at) && Number.isFinite(bt) && at !== bt) return at - bt;
|
|
671
|
+
return ticketNumber(a.queue?.ticket) - ticketNumber(b.queue?.ticket);
|
|
672
|
+
});
|
|
673
|
+
const first = ordered[0];
|
|
674
|
+
return first ? { ticket: first.queue?.ticket ?? null, proposalId: first.id } : null;
|
|
675
|
+
}
|
|
676
|
+
|
|
677
|
+
function priorityIndex(priority) {
|
|
678
|
+
const order = ['P0', 'P1', 'P2', 'P3', 'P4'];
|
|
679
|
+
const index = order.indexOf(String(priority ?? 'P3'));
|
|
680
|
+
return index < 0 ? 3 : index;
|
|
681
|
+
}
|
|
682
|
+
|
|
683
|
+
export function createWal(options) {
|
|
684
|
+
return new Wal(options);
|
|
685
|
+
}
|