@uuaid/pillar 2.7.3 → 2.8.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.
@@ -0,0 +1,1801 @@
1
+ /**
2
+ * Continuity as protocol (2.8.0 Track B): `lineage` and `lineage.successor`
3
+ * notices, the evidence store, and the one route decision every send path reads.
4
+ *
5
+ * Design: vnext-work DESIGN-continuity.md §1-§4 and §10 (RedTeam c3ff4d, 085b71).
6
+ * - A notice is evidence only. It never routes by itself.
7
+ * - Evidence = verified lineage events and receipts, merged by event digest.
8
+ * A presentation that does not verify stores nothing.
9
+ * - The route decision is recomputed from stored evidence, the user's
10
+ * confirmations, pinned-roster home checks and the clock:
11
+ * none | pending-confirm | active | suspended.
12
+ * - A homeless rotation is pending-confirm until the user confirms the exact
13
+ * head and destination (B1). A homed one may go active on a firm pin plus
14
+ * a quorum of the PINNED homes, counted here, not by the core (B4).
15
+ * - pending-confirm holds sends to the retired key (B2). A confirmation
16
+ * clears only pending-confirm (B3).
17
+ *
18
+ * Store: <home>/continuity/state.json (0600) in a 0700 dir, written under one
19
+ * O_EXCL writer lock with a token re-check before the rename (notify-store).
20
+ *
21
+ * Lead review LEAD-REVIEW-phase2-BC (B-P0..B-P3a):
22
+ * - Nothing is ever evicted. A full store refuses new lineages.
23
+ * - Only contacts (and lineages the user made firm) open the contact gate,
24
+ * at most MAX_LINEAGES_PER_KEY non-firm lineages may name one contact key,
25
+ * and when several lineages name a key a firm one decides; otherwise two
26
+ * lineages that both retire the key suspend it.
27
+ * - Only receipts that verify under a home key the lineage names are kept,
28
+ * earliest per (home, event), capped per event.
29
+ * - A state write is capped below the read cap; an unreadable store refuses
30
+ * with `continuity-store-unreadable` and `repairStore` moves it aside.
31
+ * - A notice must carry the contact key's own signature on its event and the
32
+ * sender's own signature on its event before any full verify; the per-sender
33
+ * verify budget is kept on disk.
34
+ */
35
+ import { createHash } from "node:crypto";
36
+ import { lstatSync, renameSync } from "node:fs";
37
+ import { join } from "node:path";
38
+ import {
39
+ LINEAGE_LOG_VERSION,
40
+ LINEAGE_VERSION,
41
+ MAX_LINEAGE_EVENTS,
42
+ eventDigest,
43
+ isKeyDerivedUuaid,
44
+ signingBytes,
45
+ verifyBytesStrict,
46
+ verifyLineage,
47
+ verifySeenReceipt,
48
+ } from "../vendor/pillar-core.mjs";
49
+ import {
50
+ WRITER_STALE_MS,
51
+ WRITER_WAIT_MS,
52
+ acquireLockSync,
53
+ currentUid,
54
+ ensurePrivateDir,
55
+ readPrivateFile,
56
+ releaseLock,
57
+ stillHoldsLock,
58
+ writePrivateAtomic,
59
+ } from "../notify-store.mjs";
60
+ import { REFUSAL_FIXES } from "../net/refusals.mjs";
61
+ import { isValidUuaid } from "./knock-lane.mjs";
62
+ import { resolveHomeTargetUrl } from "./witness-cli.mjs";
63
+
64
+ export const CONTINUITY_V = "pillar-continuity/1";
65
+ export const STORE_V = "pillar-continuity-store/1";
66
+ export const KIND_LINEAGE = "lineage";
67
+ export const KIND_SUCCESSOR = "lineage.successor";
68
+ export const CONTINUITY_KINDS = Object.freeze([KIND_LINEAGE, KIND_SUCCESSOR]);
69
+ export const CONTINUITY_DIR = "continuity";
70
+ export const MAX_NOTICE_BYTES = 256 * 1024;
71
+ export const MAX_EVENTS = MAX_LINEAGE_EVENTS;
72
+ export const MAX_LINEAGES = 256;
73
+ export const MAX_LINEAGES_PER_KEY = 3; // non-firm lineages that may name one contact key
74
+ export const MAX_RETIRING_PER_KEY = 2; // past the per-key cap, a lineage that retires the key is still admitted while fewer than this many do
75
+ export const MAX_RECEIPTS_PER_EVENT = 16;
76
+ export const MAX_SIDE_ROWS = 16;
77
+ export const VERIFY_BUDGET_PER_HOUR = 10;
78
+ export const MAX_BUDGET_SENDERS = 1024;
79
+ export const HOME_TIMEOUT_MS = 5000;
80
+ export const STATE_MAX_BYTES = 64 * 1024 * 1024; // read cap
81
+ export const STATE_WRITE_MAX = 32 * 1024 * 1024; // write cap: a written store always reads back
82
+ // Work bound (RedTeam b5cbee ruling 2): checked before any expensive verify.
83
+ export const MAX_NEW_EVENTS_PER_NOTICE = 32; // newly presented events; longer logs come in by `pillar continuity pin --log`
84
+ export const MAX_SIGS_PER_EVENT = 24; // the core allows 16 witnesses and 8 doors per event
85
+ export const MAX_RECEIPTS_PER_NOTICE = 64;
86
+ export const RECEIVER_WEIGHT_PER_HOUR = 4096; // events verified per hour, receiver-wide, whatever the sender
87
+ export const PROOF_POOL_PER_HOUR = 512; // unproven continuity signature/receipt checks per hour, receiver-wide
88
+ export const MAX_PROOF_PER_CANDIDATE = 256; // worst-case proof checks an unproven candidate may reserve
89
+ // Holds (ruling 1): keys that were retired or forked, plus uncovered checkpoints, stay held after forget and repair.
90
+ export const HOLDS_V = "pillar-continuity-holds/1";
91
+ export const MAX_HOLDS = 4096;
92
+ export const MAX_CHECKPOINTS = 4096;
93
+ export const HOLDS_MAX_BYTES = 32 * 1024 * 1024;
94
+ export const HOLDS_WRITE_MAX = 16 * 1024 * 1024;
95
+ export const DEFERRED_V = "pillar-continuity-deferred/1";
96
+ export const MAX_DEFERRED_SEQS = 16_384;
97
+ export const DEFERRED_MAX_BYTES = 4 * 1024 * 1024;
98
+
99
+ // Cost bound (V1 1e74da): verification is cached by content, a non-firm lineage stores at most 32
100
+ // events, and a firm one at most 32 off its pinned path (forks), on every merge.
101
+ export const MAX_NONFIRM_EVENTS = 32;
102
+ export const MAX_OFFPIN_EVENTS = 32;
103
+ export const VERIFY_CACHE_MAX = 512;
104
+
105
+ /** Full lineage verifications run in this process, and cache hits (test hooks for the work bound). */
106
+ export const continuityStats = { verifies: 0, cacheHits: 0, sigVerifies: 0 }; // sigVerifies: single signature and receipt checks
107
+
108
+ const HEAD_RE = /^sha256:[0-9a-f]{64}$/;
109
+ const HEX64_RE = /^[0-9a-f]{64}$/;
110
+ const ROUTABLE = new Set(["valid", "recovered"]);
111
+
112
+ const isPlain = (x) => x !== null && typeof x === "object" && !Array.isArray(x)
113
+ && (Object.getPrototypeOf(x) === Object.prototype || Object.getPrototypeOf(x) === null);
114
+ const isClosed = (x, keys) => isPlain(x) && Object.keys(x).every((k) => keys.includes(k));
115
+ const stripSha = (h) => (typeof h === "string" && h.startsWith("sha256:") ? h.slice(7) : h);
116
+
117
+ /** A refused send or command. `code` is `continuity-held` or `redirect-blocked:<reason>`. */
118
+ export class ContinuityRefusalError extends Error {
119
+ constructor(code, message, details = {}) {
120
+ super(`${code}: ${message}`);
121
+ this.name = "ContinuityRefusalError";
122
+ this.code = code;
123
+ this.details = details;
124
+ this.fix = details.fix ?? REFUSAL_FIXES[code] ?? REFUSAL_FIXES["continuity-suspended"];
125
+ }
126
+ }
127
+
128
+ export function emptyState() {
129
+ return { v: STORE_V, lineages: {}, successors: {} };
130
+ }
131
+
132
+ // ── evidence ─────────────────────────────────────────────────────────────────
133
+
134
+ function digestOf(ev) {
135
+ try { return eventDigest(ev); } catch { return null; }
136
+ }
137
+
138
+ /** Union of two event lists: one copy per digest, signature sets merged. */
139
+ export function mergeEvents(a = [], b = []) {
140
+ const byDigest = new Map();
141
+ for (const ev of [...a, ...b]) {
142
+ if (!isPlain(ev) || ev.v !== LINEAGE_VERSION) continue;
143
+ const d = digestOf(ev);
144
+ if (!d) continue;
145
+ const prev = byDigest.get(d);
146
+ if (!prev) { byDigest.set(d, ev); continue; }
147
+ if (Array.isArray(prev.sigs) && Array.isArray(ev.sigs)) {
148
+ const sigs = [...prev.sigs];
149
+ for (const s of ev.sigs) if (isPlain(s) && !sigs.some((m) => m.by === s.by && m.sig === s.sig)) sigs.push(s);
150
+ byDigest.set(d, { ...prev, sigs });
151
+ }
152
+ }
153
+ return [...byDigest.values()].sort((x, y) => (x.seq ?? 0) - (y.seq ?? 0));
154
+ }
155
+
156
+ /** Plain union of receipt lists (shape only). Never stored as is: see verifiedReceipts (B-P1, B-P2a). */
157
+ export function mergeReceipts(a = [], b = []) {
158
+ return [...a, ...b].filter((r) => isPlain(r) && typeof r.registry === "string" && typeof r.event === "string");
159
+ }
160
+
161
+ /** Home keys named by any of `events` (the `homes` records), by home UUAID. */
162
+ function homeKeysOf(events) {
163
+ const m = new Map();
164
+ for (const ev of events) if (Array.isArray(ev?.homes)) for (const h of ev.homes) if (isPlain(h) && isValidUuaid(h.uuaid) && typeof h.publicKey === "string") m.set(h.uuaid, h.publicKey);
165
+ return m;
166
+ }
167
+
168
+ /**
169
+ * The receipts worth keeping (B-P1, B-P2a): each must be for this lineage and
170
+ * an event in `events`, from a home those events name, and its signature must
171
+ * verify under that home's key. One per (home, event), the earliest seenAt;
172
+ * at most MAX_RECEIPTS_PER_EVENT per event. A forged receipt can neither be
173
+ * stored nor take the slot of a real one.
174
+ */
175
+ export function verifiedReceipts(lineage, events, receipts, now) {
176
+ const digests = new Set(events.map(digestOf).filter(Boolean));
177
+ const homes = homeKeysOf(events);
178
+ const best = new Map();
179
+ for (const r of receipts) {
180
+ if (!isPlain(r) || r.lineage !== lineage || !digests.has(r.event)) continue;
181
+ const pk = homes.get(r.registry);
182
+ if (!pk) continue;
183
+ let ok = false;
184
+ try { continuityStats.sigVerifies++; ok = verifySeenReceipt(r, { now, lineage, event: r.event, home: { uuaid: r.registry, publicKey: pk } }).ok === true; } catch { ok = false; }
185
+ if (!ok) continue; // @rule continuity.receipt-verified
186
+ const k = `${r.registry}|${r.event}`;
187
+ const prev = best.get(k);
188
+ if (prev && Date.parse(prev.seenAt) <= Date.parse(r.seenAt)) continue; // @rule continuity.receipt-earliest
189
+ best.set(k, r);
190
+ }
191
+ const perEvent = new Map();
192
+ const out = [];
193
+ for (const r of [...best.values()].sort((x, y) => Date.parse(x.seenAt) - Date.parse(y.seenAt) || (x.registry < y.registry ? -1 : 1))) {
194
+ const n = perEvent.get(r.event) ?? 0;
195
+ if (n >= MAX_RECEIPTS_PER_EVENT) continue; // @rule continuity.receipt-cap
196
+ perEvent.set(r.event, n + 1);
197
+ out.push(r);
198
+ }
199
+ return out;
200
+ }
201
+
202
+ const receiptKey = (r) => `${r.registry}|${r.event}|${r.seenAt}`;
203
+
204
+ function presentation(events, receipts) {
205
+ return receipts.length ? { v: LINEAGE_LOG_VERSION, events, receipts } : events;
206
+ }
207
+
208
+ /** Verification time: `now` floored to the minute, so a verdict is a function of the content and the minute. */
209
+ function verifyTime(now) {
210
+ const ms = Date.parse(now);
211
+ return Number.isFinite(ms) ? new Date(Math.floor(ms / 60_000) * 60_000).toISOString().replace(/\.\d{3}Z$/, "Z") : now;
212
+ }
213
+
214
+ /** Verdicts by content: sha256 of the minute, the events and the receipts (signatures included). */
215
+ const verifyCache = new Map();
216
+
217
+ /**
218
+ * The frozen core's verdict on stored or merged evidence. Cached by content
219
+ * (V1 1e74da), so routing, trust and listing re-use one verification per
220
+ * lineage state instead of re-running it on every call. Time-gated changes
221
+ * (a contest window ending, a postdated receipt) apply up to a minute late,
222
+ * never early. The result is frozen: callers only read it.
223
+ */
224
+ export function verifyEvidence(events, receipts, now) {
225
+ if (!Array.isArray(events) || events.length === 0) return { verdict: "invalid", reasons: ["no-inception"], facts: {} };
226
+ const at = verifyTime(now);
227
+ let key = null;
228
+ try { key = createHash("sha256").update(`${at}\n`).update(JSON.stringify(events)).update("\n").update(JSON.stringify(receipts ?? [])).digest("hex"); } catch { key = null; }
229
+ const hit = key === null ? undefined : verifyCache.get(key);
230
+ if (hit !== undefined) { verifyCache.delete(key); verifyCache.set(key, hit); continuityStats.cacheHits++; return hit; } // @rule continuity.verify-cache
231
+ continuityStats.verifies++;
232
+ let v;
233
+ try { v = verifyLineage(presentation(events, receipts ?? []), { now: at }); }
234
+ catch (e) { v = { verdict: "indeterminate", reasons: [String(e?.message ?? e)], facts: {} }; }
235
+ if (v?.facts) Object.freeze(v.facts);
236
+ Object.freeze(v);
237
+ if (key !== null) {
238
+ verifyCache.set(key, v);
239
+ if (verifyCache.size > VERIFY_CACHE_MAX) verifyCache.delete(verifyCache.keys().next().value);
240
+ }
241
+ return v;
242
+ }
243
+
244
+ /** Events of `events` that are neither ancestors of the pinned head nor its descendants: forks of a firm lineage. */
245
+ export function offPinCount(events, pinHead) {
246
+ const byDigest = new Map();
247
+ for (const ev of events) { const d = digestOf(ev); if (d) byDigest.set(d, ev); }
248
+ const head = stripSha(pinHead);
249
+ const ancestors = chainDigests(events, pinHead);
250
+ const below = new Map(); // digest -> descends from the pinned head
251
+ const descends = (d0) => {
252
+ const path = [];
253
+ let d = d0, res = false;
254
+ for (let i = 0; d && i <= MAX_EVENTS + 1; i++) {
255
+ if (d === head) { res = true; break; }
256
+ if (below.has(d)) { res = below.get(d); break; }
257
+ path.push(d);
258
+ const prev = byDigest.get(d)?.prev;
259
+ d = typeof prev === "string" ? stripSha(prev) : null;
260
+ }
261
+ for (const x of path) below.set(x, res);
262
+ return res;
263
+ };
264
+ let off = 0;
265
+ for (const d of byDigest.keys()) if (!ancestors.has(d) && !descends(d)) off++;
266
+ return off;
267
+ }
268
+
269
+ /** Digests on the chain that ends at `head` (walking `prev`). */
270
+ export function chainDigests(events, head) {
271
+ const byDigest = new Map();
272
+ for (const ev of events) { const d = digestOf(ev); if (d) byDigest.set(d, ev); }
273
+ const out = new Set();
274
+ let d = stripSha(head);
275
+ for (let i = 0; d && byDigest.has(d) && i <= MAX_EVENTS; i++) {
276
+ out.add(d);
277
+ const prev = byDigest.get(d).prev;
278
+ d = typeof prev === "string" ? stripSha(prev) : null;
279
+ }
280
+ return out;
281
+ }
282
+
283
+ function chainEvents(events, head) {
284
+ const set = chainDigests(events, head);
285
+ return events.filter((ev) => set.has(digestOf(ev)));
286
+ }
287
+
288
+ /** Every working key named by the stored events (inception, rotations, recoveries). */
289
+ export function keysOf(events) {
290
+ const out = new Map();
291
+ for (const ev of events) if (isPlain(ev?.key) && isValidUuaid(ev.key.uuaid)) out.set(ev.key.uuaid, ev.key.publicKey);
292
+ return out;
293
+ }
294
+
295
+ /** Every pre-committed reveal key named by `events` (used when rotating via the committed `next` key). */
296
+ function revealsOf(events) {
297
+ const out = new Map();
298
+ for (const ev of events) if (isPlain(ev?.reveal) && isValidUuaid(ev.reveal.uuaid) && typeof ev.reveal.publicKey === "string") out.set(ev.reveal.uuaid, ev.reveal.publicKey);
299
+ return out;
300
+ }
301
+
302
+ /** A stored roster: at most 4 homes, each a UUAID, a key and a URL. */
303
+ function validRoster(r) {
304
+ return Array.isArray(r) && r.length <= 4 && r.every((h) => isPlain(h) && isValidUuaid(h.uuaid) && typeof h.publicKey === "string" && typeof h.url === "string");
305
+ }
306
+
307
+ /**
308
+ * The eligible homes in force at `head`: the `homes` records of the last event
309
+ * on the chain to `head` that set them, kept only where the core lists the home
310
+ * as eligible (not also a witness). `v` is a verdict the caller already holds;
311
+ * it is reused when it verified exactly `head` (V1 e46aca: one verification per
312
+ * lineage), else the chain to `head` is verified on its own.
313
+ */
314
+ export function rosterAt(events, head, now, v = null) {
315
+ const prefix = chainEvents(events, head).sort((a, b) => a.seq - b.seq);
316
+ if (!prefix.some((ev) => Array.isArray(ev?.homes))) return []; // a chain that names no homes costs no verification
317
+ let pv = null;
318
+ if (v && ROUTABLE.has(v.verdict) && typeof v.facts?.head === "string" && stripSha(v.facts.head) === stripSha(head)) pv = v; // @rule continuity.roster-reuses-verdict
319
+ pv ??= verifyEvidence(prefix, [], now);
320
+ if (!ROUTABLE.has(pv.verdict)) return [];
321
+ const eligible = new Set(Array.isArray(pv.facts?.eligibleHomes) ? pv.facts.eligibleHomes : []);
322
+ let homes = [];
323
+ for (const ev of prefix) if (Array.isArray(ev.homes)) homes = ev.homes;
324
+ return homes.filter((h) => isPlain(h) && eligible.has(h.uuaid) && typeof h.publicKey === "string" && typeof h.url === "string").map((h) => ({ uuaid: h.uuaid, publicKey: h.publicKey, url: h.url }));
325
+ }
326
+
327
+ /**
328
+ * The pinned roster (B4): the eligible homes at the pinned head. A firm pin
329
+ * stores the roster it was made with (the chain to the pinned head never
330
+ * changes), so a decision costs no extra verification; a pin without one
331
+ * computes it, re-using `v` when the pin is at the verified head.
332
+ */
333
+ export function pinnedRoster(rec, now, v = null) {
334
+ if (!rec?.pin?.head) return [];
335
+ if (rec.pin.firm !== true) return []; // @rule continuity.quorum-needs-firm-pin
336
+ if (validRoster(rec.pin.roster)) return rec.pin.roster; // @rule continuity.roster-stored-with-pin
337
+ return rosterAt(rec.events, rec.pin.head, now, v);
338
+ }
339
+
340
+ /** A firm pin at `head`, carrying its roster. */
341
+ function firmPin(events, head, now, v, extra = {}) {
342
+ return { at: now, ...extra, head, firm: true, roster: rosterAt(events, head, now, v) };
343
+ }
344
+
345
+ // ── the route decision ───────────────────────────────────────────────────────
346
+
347
+ const decision = (state, extra = {}) => ({ state, ...extra });
348
+
349
+ /** The identity of a pinned roster: a home check counts only for the roster it was made against. */
350
+ export function rosterKey(roster) {
351
+ return roster.map((h) => h.uuaid).sort().join(",");
352
+ }
353
+
354
+ /** A stable fingerprint of a decision: a send that sees it change between decision and seal is refused. */
355
+ export function decisionFingerprint(d) {
356
+ return [d?.state ?? "", d?.to ?? "", d?.head ?? "", d?.reason ?? "", d?.via ?? "", d?.lineage ?? ""].join("|");
357
+ }
358
+
359
+ /**
360
+ * Route decision for one lineage record and a queried UUAID `q` that is one
361
+ * of its keys. Pure: evidence, confirmations, home checks, clock.
362
+ */
363
+ export function decideLineage(lineage, rec, q, now) {
364
+ const keys = keysOf(rec.events);
365
+ const v = verifyEvidence(rec.events, rec.receipts, now);
366
+ const base = { kind: "rotation", lineage, queried: q };
367
+ if (v.verdict === "contested") return decision("suspended", { ...base, reason: "contested" }); // @rule continuity.suspend-contested
368
+ if (v.verdict === "pending-recovery") return decision("suspended", { ...base, reason: "pending-recovery" }); // @rule continuity.suspend-pending-recovery
369
+ if (!ROUTABLE.has(v.verdict)) return decision("suspended", { ...base, reason: `unverifiable-${v.verdict}` }); // @rule continuity.suspend-unverifiable
370
+ const f = v.facts;
371
+ const chain = chainDigests(rec.events, f.head);
372
+ if (rec.pin && !chain.has(stripSha(rec.pin.head))) return decision("suspended", { ...base, reason: "pin-fork" }); // @rule continuity.suspend-pin-fork
373
+ if ((rec.w4 ?? []).some((o) => !keys.has(o.current))) return decision("suspended", { ...base, reason: "w4-disagreement" }); // @rule continuity.suspend-w4-disagreement
374
+ const hasCps = rec.pin?.firm === true && Array.isArray(rec.checkpoints) && rec.checkpoints.length > 0;
375
+ const cpRoster = hasCps ? pinnedRoster(rec, now, v) : [];
376
+ const cpRk = cpRoster.length > 0 ? rosterKey(cpRoster) : "";
377
+ const cps = cpRk ? rec.checkpoints.filter((c) => isPlain(c) && c.roster === cpRk && typeof c.event === "string") : [];
378
+ let behindCp = false;
379
+ behindCp = cps.some((c) => !chain.has(stripSha(c.event))); // @rule continuity.checkpoint-ancestry
380
+ if (q === f.current) {
381
+ if (behindCp) return decision("pending-confirm", { ...base, head: f.head, to: cps.at(-1)?.current ?? q, verdict: v.verdict, reason: "home-checkpoint-ahead" });
382
+ return decision("none", { ...base, current: f.current, head: f.head });
383
+ }
384
+ const keyPath = Array.isArray(f.keyPath) ? f.keyPath : [];
385
+ if (!keyPath.includes(q)) return decision("suspended", { ...base, reason: "superseded-key" }); // @rule continuity.suspend-superseded-key
386
+ const to = f.current;
387
+ const toKey = chainEvents(rec.events, f.head).find((ev) => ev?.key?.uuaid === to)?.key?.publicKey;
388
+ const out = { ...base, head: f.head, to, toKey, verdict: v.verdict };
389
+ if (typeof toKey !== "string") return decision("suspended", { ...out, reason: "no-destination-key" });
390
+ if (behindCp) return decision("pending-confirm", { ...out, reason: "home-checkpoint-ahead" }); // @rule continuity.checkpoint-holds-route
391
+ let confirmed = false;
392
+ confirmed = (rec.confirmations ?? []).some((c) => c.head === f.head && c.to === to); // @rule continuity.confirm-exact-head-and-to
393
+ const roster = hasCps ? cpRoster : pinnedRoster(rec, now, v); // empty unless the pin is firm (see pinnedRoster)
394
+ const rk = hasCps ? cpRk : rosterKey(roster);
395
+ let quorum = false;
396
+ const proof = homeProof(rec.homeChecks, rk);
397
+ quorum = roster.length > 0 && proof !== null && proof.head === f.head && proof.to === to; // @rule continuity.quorum-check-exact
398
+ if (v.verdict === "recovered") return confirmed && quorum ? decision("active", { ...out, via: "confirmed+home-quorum" }) : decision("pending-confirm", { ...out, reason: "recovered-needs-confirm-and-quorum" }); // @rule continuity.recovered-needs-both
399
+ if (cps.length > 0 && !quorum) return decision("pending-confirm", { ...out, reason: "home-quorum-missing" }); // @rule continuity.checkpoint-resulting-quorum
400
+ if (confirmed) return decision("active", { ...out, via: "confirmed" });
401
+ if (quorum) return decision("active", { ...out, via: "home-quorum" });
402
+ let held = decision("none", out);
403
+ held = decision("pending-confirm", { ...out, reason: roster.length ? "home-quorum-missing" : "homeless-needs-confirm" }); // @rule continuity.homeless-pending-confirm
404
+ return held;
405
+ }
406
+
407
+ /**
408
+ * The lineage decision for `q` when one or more stored lineages name it (B-P0).
409
+ * A key is one identity, so two lineages naming it is a conflict:
410
+ * - a lineage the user made firm (pin or confirmation) decides alone;
411
+ * two firm ones suspend;
412
+ * - otherwise a lineage in which `q` is current says nothing about routing,
413
+ * one lineage that retires `q` decides, and two that retire it suspend.
414
+ */
415
+ export function decideLineages(state, q, now) {
416
+ const named = Object.entries(state.lineages ?? {}).filter(([, rec]) => keysOf(rec.events).has(q));
417
+ if (named.length === 0) return decision("none");
418
+ let pick = named;
419
+ const firm = named.filter(([, rec]) => rec.pin?.firm === true);
420
+ if (firm.length > 1) return decision("suspended", { kind: "rotation", queried: q, reason: "key-in-multiple-lineages", lineages: firm.map(([lin]) => lin) }); // @rule continuity.multi-firm-suspends
421
+ if (firm.length === 1) pick = firm; // @rule continuity.firm-lineage-decides
422
+ const ds = pick.map(([lin, rec]) => decideLineage(lin, rec, q, now));
423
+ const retiring = ds.filter((d) => d.state !== "none");
424
+ if (retiring.length > 1) return decision("suspended", { kind: "rotation", queried: q, reason: "key-in-multiple-lineages", lineages: retiring.map((d) => d.lineage) }); // @rule continuity.multi-retiring-suspends
425
+ if (retiring.length === 0 && ds.length > 1) return decision("none", { kind: "rotation", queried: q, lineages: ds.map((d) => d.lineage) });
426
+ return retiring[0] ?? ds[0];
427
+ }
428
+
429
+ /** Route decision for a declared successor of `from`. */
430
+ export function decideSuccessor(state, from, now) {
431
+ const s = state.successors?.[from];
432
+ if (!s) return decision("none");
433
+ const base = { kind: "successor", lineage: s.lineage, queried: from };
434
+ if (s.conflict) return decision("suspended", { ...base, reason: "successor-equivocation", other: s.conflict.lineage }); // @rule continuity.successor-equivocation
435
+ const d1 = decideLineages(state, from, now);
436
+ if (d1.state === "suspended") return decision("suspended", { ...base, reason: `predecessor-${d1.reason}` }); // @rule continuity.successor-inherits-suspend
437
+ if (d1.state !== "none") return decision("suspended", { ...base, reason: "successor-conflicts-rotation" }); // @rule continuity.successor-conflict
438
+ const fHold = state.holds?.[from];
439
+ if (!d1.lineage && Array.isArray(fHold?.lineages) && fHold.lineages.some((l) => l !== s.lineage)) return decision("suspended", { ...base, reason: "predecessor-held" });
440
+ const v = verifyEvidence(s.events, s.receipts, now);
441
+ if (!ROUTABLE.has(v.verdict)) return decision("suspended", { ...base, reason: `successor-${v.verdict}` }); // @rule continuity.successor-verified
442
+ if (!(v.facts.boundLegacy ?? []).includes(from)) return decision("suspended", { ...base, reason: "successor-unbound" }); // @rule continuity.successor-bound
443
+ const to = v.facts.current;
444
+ const toKey = chainEvents(s.events, v.facts.head).find((ev) => ev?.key?.uuaid === to)?.key?.publicKey;
445
+ const out = { ...base, head: v.facts.head, to, toKey, verdict: v.verdict };
446
+ let confirmed = false;
447
+ confirmed = (s.confirmations ?? []).some((c) => c.head === v.facts.head && c.to === to && c.lineage === s.lineage); // @rule continuity.successor-confirm-exact
448
+ // A homed predecessor: its pinned homes must show `from` as the current key at its verified head (RedTeam b5cbee P2).
449
+ let quorumOk = true;
450
+ for (const pr of Object.values(state.lineages ?? {})) {
451
+ if (!keysOf(pr.events).has(from)) continue;
452
+ if (pr.pin?.firm !== true) continue;
453
+ const pv = verifyEvidence(pr.events, pr.receipts, now);
454
+ const roster = pinnedRoster(pr, now, pv);
455
+ if (roster.length === 0) continue;
456
+ const rk = rosterKey(roster);
457
+ const pChain = chainDigests(pr.events, pv.facts?.head);
458
+ const behind = (pr.checkpoints ?? []).some((c) => isPlain(c) && c.roster === rk && typeof c.event === "string" && !pChain.has(stripSha(c.event)));
459
+ let ok = true; // computed on the next line; the default only matters to a mutant
460
+ const proof = homeProof(pr.homeChecks, rk);
461
+ ok = !behind && pv.facts?.current === from && proof !== null && proof.head === pv.facts.head && proof.to === from; // @rule continuity.successor-predecessor-quorum
462
+ quorumOk = quorumOk && ok;
463
+ }
464
+ if (confirmed && quorumOk && typeof toKey === "string") return decision("active", { ...out, via: "confirmed" });
465
+ let held = decision("none", out);
466
+ held = decision("pending-confirm", { ...out, reason: confirmed ? "predecessor-home-quorum-missing" : "successor-needs-confirm" }); // @rule continuity.successor-pending-confirm
467
+ return held;
468
+ }
469
+
470
+ /**
471
+ * A route the user selected with `pillar continuity recover` from a lineage
472
+ * log obtained over another channel (ruling 1). It routes only while that log
473
+ * verifies on its own at the exact head with the exact destination.
474
+ */
475
+ function decideResolution(q, res, now) {
476
+ const base = { kind: "rotation", lineage: res.lineage, queried: q };
477
+ const v = verifyEvidence(res.events ?? [], res.receipts ?? [], now);
478
+ if (!ROUTABLE.has(v.verdict) || v.facts.head !== res.head || v.facts.current !== res.to || !(v.facts.keyPath ?? []).includes(q)) return decision("suspended", { ...base, reason: "resolution-unverified" }); // @rule continuity.resolution-verified
479
+ return decision("active", { ...base, head: res.head, to: res.to, toKey: res.toKey, verdict: v.verdict, via: "recovered-by-user" });
480
+ }
481
+
482
+ /** Some stored event follows `head` directly: the evidence has moved past it. */
483
+ function movedPast(events, head) {
484
+ const h = stripSha(head);
485
+ return (events ?? []).some((ev) => typeof ev?.prev === "string" && stripSha(ev.prev) === h);
486
+ }
487
+
488
+ /** Merge two checkpoint lists by `(roster, event)` without age eviction. */
489
+ function mergeCheckpoints(a = [], b = []) {
490
+ const m = new Map();
491
+ for (const c of [...a, ...b]) {
492
+ if (!isPlain(c) || typeof c.roster !== "string" || typeof c.event !== "string") continue;
493
+ m.set(`${c.roster}|${c.event}`, c);
494
+ }
495
+ return [...m.values()];
496
+ }
497
+
498
+ /** A vouched checkpoint strictly descends from `head` (`head` is a strict ancestor of `c.event`). */
499
+ function checkpointPastList(cps, head) {
500
+ const h = stripSha(head);
501
+ return (cps ?? []).some((c) => isPlain(c) && typeof c.event === "string" && c.event !== h && Array.isArray(c.ancestors) && c.ancestors.includes(h));
502
+ }
503
+
504
+ function checkpointPast(stateOrRec, lineageOrHead, maybeHead) {
505
+ if (maybeHead === undefined) return checkpointPastList(stateOrRec?.checkpoints, lineageOrHead);
506
+ const rec = stateOrRec?.lineages?.[lineageOrHead];
507
+ const held = stateOrRec?.checkpointHolds?.[lineageOrHead];
508
+ return checkpointPastList(mergeCheckpoints(rec?.checkpoints, held), maybeHead);
509
+ }
510
+
511
+ /**
512
+ * A recovery speaks only for the lineage and head it verified (RedTeam 1c5e7a,
513
+ * 5402b7). It may decide for `q` only when:
514
+ * - the decision it would replace is about that lineage alone, or about no
515
+ * stored lineage; never one from another lineage, tracked `none` included,
516
+ * and never an aggregate conflict of several lineages;
517
+ * - every lineage that holds `q` is that lineage;
518
+ * - the stored evidence and forward checkpoints of that lineage hold nothing
519
+ * strictly past the recovered head (an incomparable fork checkpoint may be
520
+ * resolved by recovery).
521
+ * Newer evidence decides again; a conflict it shows needs a new recovery.
522
+ */
523
+ function resolutionCovers(state, q, d, res) {
524
+ if (Array.isArray(d?.lineages) || Boolean(state.successors?.[q])) return false; // @rule continuity.resolution-not-aggregate
525
+ if (typeof d?.lineage === "string" && d.lineage !== res.lineage) return false; // @rule continuity.resolution-own-lineage
526
+ const hold = state.holds?.[q];
527
+ if (hold && !(Array.isArray(hold.lineages) && hold.lineages.length > 0 && hold.lineages.every((l) => l === res.lineage))) return false; // @rule continuity.resolution-own-hold
528
+ const rec = state.lineages?.[res.lineage];
529
+ if (movedPast(rec?.events, res.head) || checkpointPast(state, res.lineage, res.head)) return false; // @rule continuity.resolution-own-head
530
+ return true;
531
+ }
532
+
533
+ /** `q` is the destination of a verified recovery that covers `q`'s own decision `d`: it is current, whatever conflict the evidence still holds. */
534
+ function resolvedDestination(state, q, d, now) {
535
+ for (const [from, res] of Object.entries(state.resolutions ?? {})) {
536
+ if (res?.to === q && resolutionCovers(state, q, d, res) && decideResolution(from, res, now).state === "active") return res;
537
+ }
538
+ return null;
539
+ }
540
+
541
+ function decideRoute(state, q, now) {
542
+ const d = decideLineages(state, q, now);
543
+ const res = state.resolutions?.[q];
544
+ const held = d.state === "pending-confirm";
545
+ if (res && (d.state === "suspended" || d.state === "none" || held) && resolutionCovers(state, q, d, res)) return decideResolution(q, res, now); // @rule continuity.resolution-decides
546
+ if (res && d.state === "none" && typeof d.lineage === "string" && d.lineage !== res.lineage && decideResolution(q, res, now).state === "active") return decision("suspended", { kind: "rotation", queried: q, reason: "key-in-multiple-lineages", lineages: [d.lineage, res.lineage] }); // @rule continuity.resolution-tracked-none-conflict
547
+ if ((d.state === "suspended" || held) && resolvedDestination(state, q, d, now)) return decision("none", { kind: "rotation", queried: q, via: "recovered-by-user" }); // @rule continuity.resolution-releases-destination
548
+ if (d.state !== "none") return d;
549
+ if (state.successors?.[q]) return decideSuccessor(state, q, now);
550
+ // A key that was retired or forked stays held after forget or repair. Only the lineage that
551
+ // held it may release it (it later shows the key as current); another lineage may not (ruling 1).
552
+ const hold = state.holds?.[q];
553
+ if (hold && !(d.lineage && Array.isArray(hold.lineages) && hold.lineages.length > 0 && hold.lineages.every((l) => l === d.lineage)) && !resolvedDestination(state, q, d, now)) return decision("suspended", { kind: "rotation", queried: q, reason: "held", lineages: hold.lineages }); // @rule continuity.hold-survives-forget
554
+ return d;
555
+ }
556
+
557
+ /** The one decision for queried UUAID `q`: every send path reads this. */
558
+ export function decideFor(state, q, now) {
559
+ if (!isValidUuaid(q) || !isPlain(state)) return decision("none");
560
+ return decideRoute(state, q, now);
561
+ }
562
+
563
+ /** Keys whose `block` carries to `sender`: every key of a lineage that names it. */
564
+ export function blockAliases(state, sender) {
565
+ const out = new Set();
566
+ for (const rec of Object.values(state?.lineages ?? {})) {
567
+ const keys = keysOf(rec.events);
568
+ if (keys.has(sender)) for (const k of keys.keys()) if (k !== sender) out.add(k);
569
+ }
570
+ for (const [from, s] of Object.entries(state?.successors ?? {})) {
571
+ if (keysOf(s.events).has(sender)) out.add(from);
572
+ }
573
+ return [...out];
574
+ }
575
+
576
+ /**
577
+ * Retired keys whose contact and allow status carry to `sender`: only over an
578
+ * active route. One decision per lineage (V1 1e74da): every retired key of one
579
+ * lineage decides alike, so only keys that another lineage or a recovery also
580
+ * names need their own decision. `only` limits the keys looked at (the caller
581
+ * passes the keys its trust policy could deliver for).
582
+ */
583
+ export function allowAliases(state, sender, now, { only = null } = {}) {
584
+ const out = [];
585
+ const seen = new Set();
586
+ const lins = Object.entries(state?.lineages ?? {});
587
+ const namers = new Map();
588
+ for (const [, rec] of lins) for (const k of keysOf(rec.events).keys()) namers.set(k, (namers.get(k) ?? 0) + 1);
589
+ for (const [lin, rec] of lins) {
590
+ const keys = keysOf(rec.events);
591
+ if (!keys.has(sender)) continue;
592
+ const v = verifyEvidence(rec.events, rec.receipts, now);
593
+ const keyPath = Array.isArray(v.facts?.keyPath) ? v.facts.keyPath : [];
594
+ const rep = keyPath.find((k) => k !== v.facts?.current);
595
+ const once = rep ? decideLineage(lin, rec, rep, now) : decision("none");
596
+ for (const k of keys.keys()) {
597
+ if (k === sender || seen.has(k) || (only && !only.has(k))) continue;
598
+ seen.add(k);
599
+ let d = null;
600
+ if (namers.get(k) === 1 && !state.resolutions?.[k]) d = keyPath.includes(k) && k !== v.facts?.current ? once : decision("none"); // @rule continuity.alias-one-decision-per-lineage
601
+ d ??= decideFor(state, k, now);
602
+ if (d.state === "active" && d.to === sender) out.push(k); // @rule continuity.allow-moves-only-active
603
+ }
604
+ }
605
+ for (const from of Object.keys(state?.successors ?? {})) {
606
+ const d = decideSuccessor(state, from, now);
607
+ if (d.state === "active" && d.to === sender) out.push(from);
608
+ }
609
+ return out;
610
+ }
611
+
612
+ // ── the notice backlog (RedTeam 5402b7) ─────────────────────────────────────
613
+ //
614
+ // A notice refused for budget is not lost. The receiver records where in its
615
+ // mailbox the backlog starts (`from`: the last inbox seq before it) plus up to
616
+ // 64 explicit earlier seqs (`extra`) for out-of-order duplicates, so a replay
617
+ // of an old row never rewinds `from` across historical mail. Every waiting
618
+ // continuity notice is verified in arrival order once the budget allows, while
619
+ // unverified claims never change `decideFor` on their own.
620
+
621
+ const MAX_BACKLOG_EXTRA = 64;
622
+
623
+ function validSeqArray(a, max) {
624
+ return Array.isArray(a) && a.length <= max && a.every((n) => Number.isSafeInteger(n) && n > 0);
625
+ }
626
+
627
+ function validBacklog(b) {
628
+ return isPlain(b) && Number.isSafeInteger(b.from) && b.from >= 0
629
+ && (b.extra === undefined || validSeqArray(b.extra, MAX_BACKLOG_EXTRA))
630
+ && (b.trusted === undefined || validSeqArray(b.trusted, MAX_BACKLOG_EXTRA))
631
+ && (b.overflowFrom === undefined || b.overflowFrom === null || (Number.isSafeInteger(b.overflowFrom) && b.overflowFrom >= 0))
632
+ && typeof b.at === "string";
633
+ }
634
+
635
+ function emptyDeferred() {
636
+ return { open: [], trusted: [], repairedThrough: 0, repairTo: null };
637
+ }
638
+
639
+ /**
640
+ * Record an inbox row `seq` whose continuity notice waits for budget or lock.
641
+ * Trusted arrivals (`trusted: true`) queue into their dedicated `trusted` list
642
+ * (and `deferred.json` past 64) without rewinding `from`; open duplicate replays
643
+ * start at `tailSeq` with `seq` in `extra` and spill excess out-of-order seqs
644
+ * into `deferred.json` (`open`), falling back to monotonic `repairTo` only if
645
+ * `maxDeferredSeqs` itself is exceeded.
646
+ */
647
+ export function noteBacklog(store, { seq, duplicate = false, trusted = false, tailSeq = null, now }) {
648
+ if (!Number.isSafeInteger(seq) || seq <= 0) return false;
649
+ store.update((s) => {
650
+ const b = validBacklog(s.backlog) ? s.backlog : null;
651
+ const def = store._readDeferred();
652
+ let defChanged = false;
653
+ const pushDeferred = (bucket, n) => {
654
+ const list = def[bucket];
655
+ if (list.includes(n)) return false;
656
+ if (list.length < store.maxDeferredSeqs) {
657
+ list.push(n);
658
+ list.sort((a, c) => a - c);
659
+ defChanged = true;
660
+ return true;
661
+ }
662
+ const target = Math.max(def.repairTo ?? 0, b?.from ?? seq);
663
+ if (target !== def.repairTo) { def.repairTo = target; defChanged = true; }
664
+ return true;
665
+ };
666
+ if (trusted) {
667
+ if (!b) {
668
+ const startFrom = Number.isSafeInteger(tailSeq) && tailSeq >= seq ? tailSeq : seq;
669
+ s.backlog = { from: startFrom, extra: [], trusted: [seq], at: now };
670
+ return s;
671
+ }
672
+ const tList = [...(b.trusted ?? [])];
673
+ if (tList.includes(seq) || def.trusted.includes(seq)) return undefined;
674
+ if (tList.length < MAX_BACKLOG_EXTRA) {
675
+ tList.push(seq);
676
+ tList.sort((a, c) => a - c);
677
+ s.backlog = { ...b, trusted: tList };
678
+ return s;
679
+ }
680
+ if (!pushDeferred("trusted", seq)) return undefined;
681
+ store._writeDeferred(def);
682
+ s.backlog = { ...b };
683
+ return s;
684
+ }
685
+ if (!b) {
686
+ let init = { from: Math.max(0, seq - 1), extra: [], at: now };
687
+ if (duplicate && Number.isSafeInteger(tailSeq) && tailSeq >= seq) init = { from: tailSeq, extra: [seq], at: now }; // @rule continuity.backlog-duplicate-tail
688
+ s.backlog = init;
689
+ return s;
690
+ }
691
+ const extra = [...(b.extra ?? [])];
692
+ if (duplicate && seq <= b.from) {
693
+ if (extra.includes(seq) || def.open.includes(seq)) return undefined;
694
+ if (extra.length < MAX_BACKLOG_EXTRA) {
695
+ extra.push(seq);
696
+ extra.sort((a, c) => a - c);
697
+ s.backlog = { ...b, extra };
698
+ return s;
699
+ }
700
+ let spilled = false;
701
+ spilled = pushDeferred("open", seq); // @rule continuity.backlog-extra-overflow
702
+ if (!spilled || !defChanged) return undefined;
703
+ store._writeDeferred(def);
704
+ s.backlog = { ...b };
705
+ return s;
706
+ }
707
+ let from = Math.min(b.from, seq - 1);
708
+ from = b.from; // @rule continuity.backlog-no-rewind
709
+ if (from !== b.from) { s.backlog = { ...b, from: Math.max(0, from) }; return s; }
710
+ return undefined;
711
+ });
712
+ return true;
713
+ }
714
+
715
+ /** Advance the backlog cursor, settle completed `extra` / `trusted` / `deferred` rows, or advance monotonic repair progress. */
716
+ export function advanceBacklog(store, { toSeq = null, doneExtra = [], addExtra = [], doneTrusted = [], repairedThrough = null, clearRepair = false } = {}) {
717
+ store.update((s) => {
718
+ if (!validBacklog(s.backlog)) return undefined;
719
+ const prev = s.backlog;
720
+ const def = store._readDeferred();
721
+ let defChanged = false;
722
+ let from = Number.isSafeInteger(toSeq) && toSeq > prev.from ? toSeq : prev.from;
723
+ const dropOpen = new Set(doneExtra);
724
+ let extra = (prev.extra ?? []).filter((n) => n > from && !dropOpen.has(n));
725
+ extra = (prev.extra ?? []).filter((n) => !dropOpen.has(n)); // @rule continuity.backlog-keep-unfinished-extra
726
+ if (dropOpen.size > 0 && def.open.length > 0) {
727
+ const nextOpen = def.open.filter((n) => !dropOpen.has(n));
728
+ if (nextOpen.length !== def.open.length) { def.open = nextOpen; defChanged = true; }
729
+ }
730
+ for (const n of addExtra) {
731
+ if (!Number.isSafeInteger(n) || n <= 0 || dropOpen.has(n) || extra.includes(n) || def.open.includes(n)) continue;
732
+ if (extra.length < MAX_BACKLOG_EXTRA) extra.push(n);
733
+ else if (def.open.length < store.maxDeferredSeqs) { def.open.push(n); defChanged = true; }
734
+ else { const target = Math.max(def.repairTo ?? 0, from); if (target !== def.repairTo) { def.repairTo = target; defChanged = true; } }
735
+ }
736
+ while (extra.length < MAX_BACKLOG_EXTRA && def.open.length > 0) {
737
+ def.open.sort((a, c) => a - c);
738
+ const nextSeq = def.open.shift();
739
+ defChanged = true;
740
+ if (!extra.includes(nextSeq) && !dropOpen.has(nextSeq)) extra.push(nextSeq);
741
+ }
742
+ if (defChanged) def.open.sort((a, c) => a - c);
743
+ extra.sort((a, c) => a - c);
744
+
745
+ const dropTrusted = new Set(doneTrusted);
746
+ let trusted = (prev.trusted ?? []).filter((n) => !dropTrusted.has(n));
747
+ if (dropTrusted.size > 0 && def.trusted.length > 0) {
748
+ const nextTrusted = def.trusted.filter((n) => !dropTrusted.has(n));
749
+ if (nextTrusted.length !== def.trusted.length) { def.trusted = nextTrusted; defChanged = true; }
750
+ }
751
+ while (trusted.length < MAX_BACKLOG_EXTRA && def.trusted.length > 0) {
752
+ def.trusted.sort((a, c) => a - c);
753
+ const nextSeq = def.trusted.shift();
754
+ defChanged = true;
755
+ if (!trusted.includes(nextSeq) && !dropTrusted.has(nextSeq)) trusted.push(nextSeq);
756
+ }
757
+ trusted.sort((a, c) => a - c);
758
+
759
+ if (Number.isSafeInteger(repairedThrough) && repairedThrough > def.repairedThrough) {
760
+ def.repairedThrough = repairedThrough; // @rule continuity.backlog-repair-monotonic
761
+ defChanged = true;
762
+ }
763
+ if (clearRepair && def.repairTo !== null && def.repairedThrough >= def.repairTo) {
764
+ def.repairTo = null;
765
+ defChanged = true;
766
+ }
767
+ if (defChanged) store._writeDeferred(def);
768
+
769
+ const prevExtra = prev.extra ?? [];
770
+ const prevTrusted = prev.trusted ?? [];
771
+ const sameExtra = extra.length === prevExtra.length && extra.every((v, i) => v === prevExtra[i]);
772
+ const sameTrusted = trusted.length === prevTrusted.length && trusted.every((v, i) => v === prevTrusted[i]);
773
+ if (from === prev.from && sameExtra && sameTrusted && prev.overflowFrom === undefined && !defChanged) return undefined;
774
+ const next = { ...prev, from, extra };
775
+ delete next.overflowFrom;
776
+ if (trusted.length > 0) next.trusted = trusted;
777
+ else delete next.trusted;
778
+ s.backlog = next;
779
+ return s;
780
+ });
781
+ }
782
+
783
+ /** Clear the backlog when `from` was reached, all `extra` / `trusted` / `deferred` queues are empty, and `hasMore()` is false under the lock. */
784
+ export function clearBacklog(store, from, hasMore) {
785
+ let cleared = false;
786
+ store.update((s) => {
787
+ if (!validBacklog(s.backlog)) { cleared = true; return undefined; }
788
+ const def = store._readDeferred();
789
+ if (s.backlog.from !== from || (s.backlog.extra?.length ?? 0) > 0 || (s.backlog.trusted?.length ?? 0) > 0 || def.open.length > 0 || def.trusted.length > 0 || def.repairTo !== null || hasMore()) return undefined;
790
+ s.backlog = null;
791
+ cleared = true;
792
+ return s;
793
+ });
794
+ return cleared;
795
+ }
796
+
797
+ // ── the store ────────────────────────────────────────────────────────────────
798
+
799
+ /** The handle before the lock is taken: release is a no-op, and it holds nothing. */
800
+ const NOT_LOCKED = Object.freeze({ path: null });
801
+
802
+ function lockBusy(path) {
803
+ const e = new Error(`continuity-locked: another process holds ${path}; nothing was written. Retry`);
804
+ e.code = "continuity-locked";
805
+ return e;
806
+ }
807
+
808
+ function unreadable(store, why) {
809
+ return new ContinuityRefusalError("continuity-store-unreadable", `${store.statePath} cannot be read (${why}); sends stop until it is repaired, because a held or suspended route cannot be told apart`);
810
+ }
811
+
812
+ function holdsUnreadable(store, why) {
813
+ return new ContinuityRefusalError("continuity-holds-unreadable", `${store.holdsPath} cannot be read (${why}); sends stop, because a held key cannot be told apart`);
814
+ }
815
+
816
+ /** True when `cp` has verified ancestry and positive pinned-home quorum at `rec`'s resulting head. */
817
+ function isCheckpointCovered(rec, cp, now) {
818
+ if (!rec || rec.pin?.firm !== true || !isPlain(cp) || typeof cp.roster !== "string" || typeof cp.event !== "string") return false;
819
+ const v = verifyEvidence(rec.events ?? [], rec.receipts ?? [], now);
820
+ if (!ROUTABLE.has(v.verdict)) return false;
821
+ const roster = pinnedRoster(rec, now, v);
822
+ if (roster.length === 0 || rosterKey(roster) !== cp.roster) return false;
823
+ if (!chainDigests(rec.events ?? [], v.facts.head).has(stripSha(cp.event))) return false;
824
+ const proof = homeProof(rec.homeChecks, cp.roster);
825
+ return proof !== null && proof.head === v.facts.head && proof.to === v.facts.current;
826
+ }
827
+
828
+ /** Uncovered checkpoints after `state` is written: discarded only on proven coverage or explicit `clearFor` recovery. */
829
+ function checkpointsAfter(state, prevCpHolds, now, clearFor = null) {
830
+ const out = {};
831
+ const lins = new Set([...Object.keys(prevCpHolds ?? {}), ...Object.keys(state.lineages ?? {})]);
832
+ for (const lin of lins) {
833
+ const rec = state.lineages?.[lin];
834
+ const merged = mergeCheckpoints(prevCpHolds?.[lin], rec?.checkpoints);
835
+ if (merged.length === 0) continue;
836
+ const kept = merged.filter((cp) => {
837
+ if (clearFor && clearFor.lineage === lin && !checkpointPastList([cp], clearFor.head)) return false;
838
+ let covered = true; // default only matters to a mutant
839
+ covered = isCheckpointCovered(rec, cp, rec?.updatedAt ?? now); // @rule continuity.checkpoint-discard-covered
840
+ return !covered;
841
+ });
842
+ if (kept.length > 0) {
843
+ out[lin] = kept;
844
+ if (rec) rec.checkpoints = kept;
845
+ } else if (rec && Array.isArray(rec.checkpoints)) {
846
+ rec.checkpoints = [];
847
+ }
848
+ }
849
+ return out;
850
+ }
851
+
852
+ /** Every key a record retires, puts in conflict, or holds behind an uncovered checkpoint (locally current key included). */
853
+ function heldKeysOf(rec, now, cpList = rec?.checkpoints) {
854
+ const keys = [...keysOf(rec.events ?? []).keys()];
855
+ let holdCurrent = false;
856
+ holdCurrent = Array.isArray(cpList) && cpList.some((cp) => !isCheckpointCovered(rec, cp, now)); // @rule continuity.checkpoint-holds-current
857
+ if (holdCurrent) return keys;
858
+ let verdict = rec.verdict, current = rec.current;
859
+ if (typeof verdict !== "string") { const v = verifyEvidence(rec.events ?? [], rec.receipts ?? [], now); verdict = v.verdict; current = v.facts?.current; }
860
+ return ROUTABLE.has(verdict) ? keys.filter((k) => k !== current) : keys;
861
+ }
862
+
863
+ /** The holds after `state` is written: a union, never shrinking (ruling 1). */
864
+ function holdsAfter(state, prev, cpHolds, now) {
865
+ const out = { ...prev };
866
+ const add = (k, lineage) => {
867
+ if (!isValidUuaid(k)) return;
868
+ const h = out[k];
869
+ if (!h) out[k] = { lineages: [lineage], at: now };
870
+ else if (!h.lineages.includes(lineage)) out[k] = { ...h, lineages: [...h.lineages, lineage] };
871
+ };
872
+ for (const [lin, rec] of Object.entries(state.lineages ?? {})) for (const k of heldKeysOf(rec, rec.updatedAt ?? now, cpHolds?.[lin] ?? rec.checkpoints)) add(k, lin);
873
+ for (const [from, rec] of Object.entries(state.successors ?? {})) add(from, rec.lineage);
874
+ for (const [q, r] of Object.entries(state.resolutions ?? {})) add(q, r.lineage);
875
+ return out;
876
+ }
877
+
878
+ /** A write that would pass the write cap, or a new lineage past the lineage cap: refused, nothing written. */
879
+ export class ContinuityStoreFull extends Error {
880
+ constructor(message) { super(`continuity-store-full: ${message}`); this.code = "continuity-store-full"; }
881
+ }
882
+
883
+ export class ContinuityStore {
884
+ constructor(home, { lockWaitMs = WRITER_WAIT_MS, lockStaleMs = WRITER_STALE_MS, maxLineages = MAX_LINEAGES, maxWriteBytes = STATE_WRITE_MAX, receiverWeight = RECEIVER_WEIGHT_PER_HOUR, maxNewEvents = MAX_NEW_EVENTS_PER_NOTICE, maxNonFirmEvents = MAX_NONFIRM_EVENTS, maxOffPinEvents = MAX_OFFPIN_EVENTS, proofPool = receiverWeight === Infinity ? Infinity : PROOF_POOL_PER_HOUR, maxCandidateProof = maxNewEvents === Infinity ? Infinity : MAX_PROOF_PER_CANDIDATE, maxDeferredSeqs = MAX_DEFERRED_SEQS } = {}) {
885
+ this.maxNewEvents = maxNewEvents;
886
+ this.maxNonFirmEvents = maxNonFirmEvents;
887
+ this.maxOffPinEvents = maxOffPinEvents;
888
+ this.home = home;
889
+ this.dir = join(home, CONTINUITY_DIR);
890
+ this.statePath = join(this.dir, "state.json");
891
+ this.holdsPath = join(this.dir, "holds.json");
892
+ this.budgetPath = join(this.dir, "budget.json");
893
+ this.deferredPath = join(this.dir, "deferred.json");
894
+ this.receiverWeight = receiverWeight;
895
+ this.proofPool = proofPool;
896
+ this.maxCandidateProof = maxCandidateProof;
897
+ this.maxDeferredSeqs = maxDeferredSeqs;
898
+ this.lockPath = join(this.dir, "writer.lock");
899
+ this.lockWaitMs = lockWaitMs;
900
+ this.lockStaleMs = lockStaleMs;
901
+ this.maxLineages = maxLineages;
902
+ this.maxWriteBytes = maxWriteBytes;
903
+ }
904
+
905
+ /**
906
+ * Parsed state, or an empty one. Anything else (over the read cap, not JSON,
907
+ * not a store, unsafe file) throws `continuity-store-unreadable`, whose fix
908
+ * is `pillar continuity repair`. Never repaired silently.
909
+ */
910
+ read() {
911
+ if (!this._dirPresent()) return { ...emptyState(), holds: {}, checkpointHolds: {} }; // verified absence: no continuity directory at all
912
+ let raw = null, err = null;
913
+ try { raw = readPrivateFile(this.statePath, { maxBytes: STATE_MAX_BYTES }); } catch (e) { err = e; }
914
+ if (err && err.code !== "ENOENT") throw unreadable(this, String(err?.message ?? err).slice(0, 200)); // @rule continuity.store-unreadable-coded
915
+ let s = emptyState();
916
+ if (raw !== null) {
917
+ try { s = JSON.parse(raw); } catch { throw unreadable(this, "not valid JSON"); }
918
+ if (!isPlain(s) || s.v !== STORE_V || !isPlain(s.lineages) || !isPlain(s.successors) || (s.resolutions !== undefined && !isPlain(s.resolutions))) throw unreadable(this, `not a ${STORE_V} store`); // @rule continuity.store-shape
919
+ if (s.backlog !== undefined && s.backlog !== null && !validBacklog(s.backlog)) throw unreadable(this, "its notice backlog is malformed"); // @rule continuity.backlog-shape
920
+ }
921
+ const hf = this._readHoldsFile();
922
+ s.holds = hf.keys;
923
+ s.checkpointHolds = hf.checkpoints;
924
+ for (const [lin, cps] of Object.entries(hf.checkpoints)) {
925
+ if (s.lineages[lin]) s.lineages[lin].checkpoints = mergeCheckpoints(s.lineages[lin].checkpoints, cps);
926
+ }
927
+ return s;
928
+ }
929
+
930
+ /**
931
+ * true when the continuity directory exists and is ours; false only when it
932
+ * does not exist (ENOENT). A symlink, a non-directory, another owner or any
933
+ * other error is a custody failure, never "no state" (RedTeam b5cbee P1).
934
+ */
935
+ _dirPresent() {
936
+ let st;
937
+ try { st = lstatSync(this.dir); }
938
+ catch (e) { if (e?.code === "ENOENT") return false; throw unreadable(this, String(e?.message ?? e).slice(0, 200)); }
939
+ if (st.isSymbolicLink() || !st.isDirectory() || st.uid !== currentUid()) throw unreadable(this, `${this.dir} is not a private directory of this user`); // @rule continuity.store-dir-custody
940
+ return true;
941
+ }
942
+
943
+ _readHoldsFile() {
944
+ let raw = null;
945
+ try { raw = readPrivateFile(this.holdsPath, { maxBytes: HOLDS_MAX_BYTES }); }
946
+ catch (e) { if (e?.code !== "ENOENT") throw holdsUnreadable(this, String(e?.message ?? e).slice(0, 200)); }
947
+ if (raw === null) return { keys: {}, checkpoints: {} };
948
+ let h;
949
+ try { h = JSON.parse(raw); } catch { throw holdsUnreadable(this, "not valid JSON"); }
950
+ if (!isPlain(h) || h.v !== HOLDS_V || !isPlain(h.keys) || (h.checkpoints !== undefined && !isPlain(h.checkpoints))) throw holdsUnreadable(this, `not a ${HOLDS_V} file`); // @rule continuity.holds-shape
951
+ const checkpoints = {};
952
+ for (const [lin, arr] of Object.entries(h.checkpoints ?? {})) {
953
+ if (!Array.isArray(arr) || !arr.every((c) => isPlain(c) && typeof c.roster === "string" && typeof c.event === "string")) throw holdsUnreadable(this, "malformed checkpoint holds");
954
+ if (arr.length > 0) checkpoints[lin] = arr;
955
+ }
956
+ return { keys: h.keys, checkpoints };
957
+ }
958
+
959
+ _readHolds() {
960
+ return this._readHoldsFile().keys;
961
+ }
962
+
963
+ _readDeferred() {
964
+ try {
965
+ const raw = readPrivateFile(this.deferredPath, { maxBytes: DEFERRED_MAX_BYTES });
966
+ if (!raw) return emptyDeferred();
967
+ const d = JSON.parse(raw);
968
+ if (!isPlain(d) || d.v !== DEFERRED_V) return emptyDeferred();
969
+ return {
970
+ open: validSeqArray(d.open, this.maxDeferredSeqs) ? [...d.open] : [],
971
+ trusted: validSeqArray(d.trusted, this.maxDeferredSeqs) ? [...d.trusted] : [],
972
+ repairedThrough: Number.isSafeInteger(d.repairedThrough) && d.repairedThrough >= 0 ? d.repairedThrough : 0,
973
+ repairTo: Number.isSafeInteger(d.repairTo) && d.repairTo >= 0 ? d.repairTo : null,
974
+ };
975
+ } catch {
976
+ return emptyDeferred();
977
+ }
978
+ }
979
+
980
+ _writeDeferred(d) {
981
+ writePrivateAtomic(this.deferredPath, JSON.stringify({
982
+ v: DEFERRED_V,
983
+ open: d.open ?? [],
984
+ trusted: d.trusted ?? [],
985
+ repairedThrough: d.repairedThrough ?? 0,
986
+ repairTo: d.repairTo ?? null,
987
+ }));
988
+ }
989
+
990
+ readDeferred() {
991
+ return this._dirPresent() ? this._readDeferred() : emptyDeferred();
992
+ }
993
+
994
+ /** A cheap stamp of what read() would return: changes whenever state, holds, or deferred files are replaced. */
995
+ version() {
996
+ const fp = (path) => {
997
+ try { const st = lstatSync(path); return `${st.ino}:${st.size}:${st.mtimeMs}`; }
998
+ catch (e) { if (e?.code === "ENOENT") return "-"; throw unreadable(this, String(e?.message ?? e).slice(0, 200)); }
999
+ };
1000
+ if (!this._dirPresent()) return "absent";
1001
+ return `${fp(this.statePath)}|${fp(this.holdsPath)}|${fp(this.deferredPath)}`;
1002
+ }
1003
+
1004
+ _withLock(fn) {
1005
+ ensurePrivateDir(this.dir);
1006
+ let handle = NOT_LOCKED;
1007
+ handle = acquireLockSync(this.lockPath, { staleMs: this.lockStaleMs, waitMs: this.lockWaitMs }); // @rule continuity.store-lock
1008
+ if (!handle) throw lockBusy(this.lockPath);
1009
+ try { return fn(handle); } finally { releaseLock(handle); }
1010
+ }
1011
+
1012
+ /**
1013
+ * Read-modify-write under the writer lock. `fn(state)` returns the new
1014
+ * state, or undefined for no write. A result over `maxWriteBytes` is
1015
+ * refused (ContinuityStoreFull), so the file always reads back (B-P1).
1016
+ */
1017
+ update(fn, { clearCheckpointsFor = null } = {}) {
1018
+ return this._withLock((handle) => {
1019
+ const cur = this.read();
1020
+ const prevHolds = cur.holds ?? {};
1021
+ const prevCpHolds = cur.checkpointHolds ?? {};
1022
+ const next = fn(cur);
1023
+ if (next === undefined) return undefined;
1024
+ const { holds: _ignored, checkpointHolds: _ignoredCps, ...persist } = next;
1025
+ const nowIso = new Date().toISOString();
1026
+ const cpHolds = checkpointsAfter(persist, prevCpHolds, nowIso, clearCheckpointsFor);
1027
+ const totalCps = Object.values(cpHolds).reduce((n, a) => n + a.length, 0);
1028
+ if (totalCps > MAX_CHECKPOINTS) throw new ContinuityStoreFull(`${MAX_CHECKPOINTS} uncovered checkpoints is the cap; nothing was written`); // @rule continuity.checkpoint-cap
1029
+ boundState(persist);
1030
+ const json = JSON.stringify(persist);
1031
+ if (Buffer.byteLength(json) > this.maxWriteBytes) throw new ContinuityStoreFull(`the store would be ${Buffer.byteLength(json)} bytes, over ${this.maxWriteBytes}; nothing was written`); // @rule continuity.store-write-cap
1032
+ let holds = prevHolds;
1033
+ holds = holdsAfter(persist, prevHolds, cpHolds, nowIso); // @rule continuity.holds-maintained
1034
+ if (Object.keys(holds).length > MAX_HOLDS) throw new ContinuityStoreFull(`${MAX_HOLDS} held keys is the cap; nothing was written`);
1035
+ const holdsPayload = { v: HOLDS_V, keys: holds, ...(Object.keys(cpHolds).length > 0 ? { checkpoints: cpHolds } : {}) };
1036
+ const holdsJson = JSON.stringify(holdsPayload);
1037
+ if (Buffer.byteLength(holdsJson) > HOLDS_WRITE_MAX) throw new ContinuityStoreFull(`the holds file would be ${Buffer.byteLength(holdsJson)} bytes, over ${HOLDS_WRITE_MAX}; nothing was written`);
1038
+ if (!stillHoldsLock(handle)) throw lockBusy(this.lockPath); // @rule continuity.store-lock-recheck
1039
+ if (JSON.stringify(holds) !== JSON.stringify(prevHolds) || JSON.stringify(cpHolds) !== JSON.stringify(prevCpHolds)) {
1040
+ writePrivateAtomic(this.holdsPath, holdsJson); // holds first: a crash between leaves more held, never less
1041
+ }
1042
+ writePrivateAtomic(this.statePath, json);
1043
+ return { ...persist, holds, checkpointHolds: cpHolds };
1044
+ });
1045
+ }
1046
+
1047
+ /** Cheap stamp of `budget.json` on disk for no-progress drain coalescing. */
1048
+ budgetVersion() {
1049
+ try {
1050
+ const st = lstatSync(this.budgetPath);
1051
+ return `${st.ino}:${st.size}:${st.mtimeMs}:${st.ctimeMs}`;
1052
+ } catch (e) {
1053
+ if (e?.code === "ENOENT") return "-";
1054
+ return "err";
1055
+ }
1056
+ }
1057
+
1058
+ _evalBudget(b, sender, weight, nowMs, { limit = VERIFY_BUDGET_PER_HOUR, reserved = false, proofReserve = 0 } = {}) {
1059
+ const spent = isPlain(b.spent) ? b.spent : {};
1060
+ const mine = sender === null ? [] : (Array.isArray(spent[sender]) ? spent[sender] : []).filter((t) => Number.isFinite(t) && nowMs - t < 3_600_000 && t <= nowMs + 300_000);
1061
+ let senderOk = true; // computed on the next line; the default only matters to a mutant
1062
+ senderOk = sender === null || mine.length < limit; // @rule continuity.verify-budget-persisted
1063
+ const recentOpen = (Array.isArray(b.receiver) ? b.receiver : []).filter((x) => Array.isArray(x) && Number.isFinite(x[0]) && Number.isFinite(x[1]) && nowMs - x[0] < 3_600_000 && x[0] <= nowMs + 300_000);
1064
+ const recentAuth = (Array.isArray(b.auth) ? b.auth : []).filter((x) => Array.isArray(x) && Number.isFinite(x[0]) && Number.isFinite(x[1]) && nowMs - x[0] < 3_600_000 && x[0] <= nowMs + 300_000);
1065
+ const recentProof = (Array.isArray(b.proof) ? b.proof : []).filter((x) => Array.isArray(x) && Number.isFinite(x[0]) && Number.isFinite(x[1]) && nowMs - x[0] < 3_600_000 && x[0] <= nowMs + 300_000);
1066
+ const usedOpen = recentOpen.reduce((n, x) => n + x[1], 0);
1067
+ const usedAuth = recentAuth.reduce((n, x) => n + x[1], 0);
1068
+ const usedProof = recentProof.reduce((n, x) => n + x[1], 0);
1069
+ let openCap = this.receiverWeight;
1070
+ if (!reserved && this.receiverWeight >= 16) openCap = Math.floor(this.receiverWeight * 3 / 4); // @rule continuity.receiver-budget-reserve
1071
+ let receiverOk = true; // computed on the next line; the default only matters to a mutant
1072
+ receiverOk = weight === 0 || ((reserved || usedOpen + weight <= openCap) && usedOpen + usedAuth + weight <= this.receiverWeight); // @rule continuity.receiver-budget
1073
+ let proofOk = true; // computed on the next line; the default only matters to a mutant
1074
+ proofOk = reserved || proofReserve === 0 || usedProof + proofReserve <= this.proofPool; // @rule continuity.proof-pool-reserve
1075
+ return { spent, mine, recentOpen, recentAuth, recentProof, senderOk, receiverOk, proofOk };
1076
+ }
1077
+
1078
+ /** Would `takeBudgets` succeed right now? Charges nothing and reads no signatures. */
1079
+ canTakeBudgets(sender, weight, nowMs, limitOrOpts = VERIFY_BUDGET_PER_HOUR) {
1080
+ const opts = typeof limitOrOpts === "number" ? { limit: limitOrOpts, reserved: false } : (limitOrOpts ?? {});
1081
+ const { senderOk, receiverOk, proofOk } = this._evalBudget(this._readBudget(), sender, weight, nowMs, opts);
1082
+ if (!senderOk) return "budget";
1083
+ if (!receiverOk || !proofOk) return "receiver-budget";
1084
+ return null;
1085
+ }
1086
+
1087
+ /** Earliest timestamp at which any active receiver, auth, proof, or per-sender budget entry frees up. */
1088
+ nextBudgetUnlockMs(nowMs, memBudget = null) {
1089
+ const b = this._readBudget();
1090
+ let earliest = Infinity;
1091
+ const note = (t) => {
1092
+ if (Number.isFinite(t) && nowMs - t < 3_600_000 && t <= nowMs + 300_000) {
1093
+ const exp = t + 3_600_000;
1094
+ if (exp < earliest) earliest = exp;
1095
+ }
1096
+ };
1097
+ for (const x of Array.isArray(b.receiver) ? b.receiver : []) if (Array.isArray(x)) note(x[0]);
1098
+ for (const x of Array.isArray(b.auth) ? b.auth : []) if (Array.isArray(x)) note(x[0]);
1099
+ for (const x of Array.isArray(b.proof) ? b.proof : []) if (Array.isArray(x)) note(x[0]);
1100
+ if (isPlain(b.spent)) for (const arr of Object.values(b.spent)) if (Array.isArray(arr)) for (const t of arr) note(t);
1101
+ if (memBudget?.map instanceof Map) for (const arr of memBudget.map.values()) if (Array.isArray(arr)) for (const t of arr) note(t);
1102
+ return earliest;
1103
+ }
1104
+
1105
+ /**
1106
+ * Take one verify from `sender`'s budget, `weight` from the receiver-wide
1107
+ * budget, and (for unproven candidates) `proofReserve` from the durable
1108
+ * proof-work pool (`b.proof`), all or none in one locked step (RedTeam 5402b7,
1109
+ * 65c007).
1110
+ */
1111
+ takeBudgets(sender, weight, nowMs, limitOrOpts = VERIFY_BUDGET_PER_HOUR) {
1112
+ const opts = typeof limitOrOpts === "number" ? { limit: limitOrOpts, reserved: false } : (limitOrOpts ?? {});
1113
+ const reserved = opts.reserved === true;
1114
+ const proofReserve = !reserved && Number.isFinite(opts.proofReserve) && opts.proofReserve > 0 ? opts.proofReserve : 0;
1115
+ const proofToken = typeof opts.proofToken === "string" ? opts.proofToken : null;
1116
+ return this._withLock((handle) => {
1117
+ const b = this._readBudget();
1118
+ const { spent, mine, recentOpen, recentAuth, recentProof, senderOk, receiverOk, proofOk } = this._evalBudget(b, sender, weight, nowMs, { ...opts, proofReserve });
1119
+ if (!senderOk) return "budget";
1120
+ if (!receiverOk || !proofOk) return "receiver-budget";
1121
+ const out = {};
1122
+ if (sender !== null) {
1123
+ mine.push(nowMs);
1124
+ spent[sender] = mine;
1125
+ const keys = Object.keys(spent).filter((k) => Array.isArray(spent[k]) && spent[k].length > 0 && nowMs - Math.max(...spent[k]) < 3_600_000);
1126
+ for (const k of keys.sort((x, y) => Math.max(...spent[y]) - Math.max(...spent[x])).slice(0, MAX_BUDGET_SENDERS)) out[k] = spent[k];
1127
+ }
1128
+ if (weight > 0) (reserved ? recentAuth : recentOpen).push([nowMs, weight]);
1129
+ if (proofReserve > 0) recentProof.push(proofToken ? [nowMs, proofReserve, proofToken] : [nowMs, proofReserve]);
1130
+ if (!stillHoldsLock(handle)) throw lockBusy(this.lockPath);
1131
+ writePrivateAtomic(this.budgetPath, JSON.stringify({ ...b, v: "pillar-continuity-budget/1", ...(sender !== null ? { spent: out } : {}), receiver: recentOpen, auth: recentAuth, proof: recentProof }));
1132
+ return null;
1133
+ });
1134
+ }
1135
+
1136
+ /** Settle a durably reserved proof-work entry down to the actual proof checks spent (failed proofs included). */
1137
+ settleProofWork(token, actual, nowMs) {
1138
+ if (!token || !Number.isFinite(actual) || actual < 1) return;
1139
+ this._withLock((handle) => {
1140
+ const b = this._readBudget();
1141
+ const recentProof = (Array.isArray(b.proof) ? b.proof : []).filter((x) => Array.isArray(x) && Number.isFinite(x[0]) && Number.isFinite(x[1]) && nowMs - x[0] < 3_600_000 && x[0] <= nowMs + 300_000);
1142
+ const idx = recentProof.findIndex((x) => x[2] === token);
1143
+ if (idx === -1) return;
1144
+ const settled = Math.min(recentProof[idx][1], Math.max(1, actual));
1145
+ recentProof[idx] = [recentProof[idx][0], settled];
1146
+ if (!stillHoldsLock(handle)) throw lockBusy(this.lockPath);
1147
+ writePrivateAtomic(this.budgetPath, JSON.stringify({ ...b, v: "pillar-continuity-budget/1", proof: recentProof }));
1148
+ });
1149
+ }
1150
+
1151
+ /** Receiver-wide budget alone (see takeBudgets). */
1152
+ takeReceiverWeight(weight, nowMs) {
1153
+ return this.takeBudgets(null, weight, nowMs, { reserved: true }) === null;
1154
+ }
1155
+
1156
+ _readBudget() {
1157
+ try { const raw = readPrivateFile(this.budgetPath, { maxBytes: 4 * 1024 * 1024 }); const b = raw ? JSON.parse(raw) : {}; return isPlain(b) ? b : {}; } catch { return {}; }
1158
+ }
1159
+
1160
+ /** Per-sender budget alone (see takeBudgets). */
1161
+ takeVerify(sender, nowMs, limit = VERIFY_BUDGET_PER_HOUR) {
1162
+ return this.takeBudgets(sender, 0, nowMs, limit) === null;
1163
+ }
1164
+ }
1165
+
1166
+ /**
1167
+ * Move an unreadable store aside (kept as state.json.bad-<stamp> for
1168
+ * inspection) and start an empty one. A readable store is left alone.
1169
+ */
1170
+ export function repairStore(store, { now = new Date().toISOString() } = {}) {
1171
+ return store._withLock(() => {
1172
+ store._dirPresent(); // a symlinked or foreign directory is refused, never repaired through
1173
+ store._readHolds(); // holds survive a repair; an unreadable holds file is refused here, never dropped (ruling 1)
1174
+ try { store.read(); return { repaired: false }; }
1175
+ catch (e) { if (e?.code !== "continuity-store-unreadable") throw e; }
1176
+ const movedTo = `${store.statePath}.bad-${String(now).replace(/[:.]/g, "-")}`;
1177
+ renameSync(store.statePath, movedTo);
1178
+ writePrivateAtomic(store.statePath, JSON.stringify(emptyState()));
1179
+ return { repaired: true, movedTo };
1180
+ });
1181
+ }
1182
+
1183
+ /** Side rows per record are trimmed. Uncovered checkpoints and lineages are never evicted by age (B-P0, B7-3). */
1184
+ function boundState(s) {
1185
+ for (const rec of Object.values(s.lineages)) {
1186
+ for (const k of ["confirmations", "homeChecks", "w4"]) if (Array.isArray(rec[k])) rec[k] = rec[k].slice(-MAX_SIDE_ROWS);
1187
+ }
1188
+ return s;
1189
+ }
1190
+
1191
+ function newRecord(now) {
1192
+ return { events: [], receipts: [], pin: null, confirmations: [], homeChecks: [], w4: [], updatedAt: now };
1193
+ }
1194
+
1195
+ // ── notices ──────────────────────────────────────────────────────────────────
1196
+
1197
+ const ROTATION_KEYS = ["v", "type", "lineage", "current", "head", "log", "text"];
1198
+ const SUCCESSOR_KEYS = ["v", "type", "from", "successor", "text"];
1199
+
1200
+ function logParts(log) {
1201
+ if (Array.isArray(log)) return { events: log, receipts: [] };
1202
+ if (isPlain(log) && log.v === LINEAGE_LOG_VERSION && Array.isArray(log.events)) return { events: log.events, receipts: Array.isArray(log.receipts) ? log.receipts : [] };
1203
+ return null;
1204
+ }
1205
+
1206
+ /** Signature and receipt counts a notice may carry (ruling 2); checked before any signature is verified. */
1207
+ function overWorkCaps(parts) {
1208
+ if (parts.receipts.length > MAX_RECEIPTS_PER_NOTICE) return "receipt-cap"; // @rule continuity.receipt-count-cap
1209
+ if (parts.events.some((ev) => Array.isArray(ev?.sigs) && ev.sigs.length > MAX_SIGS_PER_EVENT)) return "sig-cap"; // @rule continuity.sig-count-cap
1210
+ return null;
1211
+ }
1212
+
1213
+ /**
1214
+ * Pre-filter, no crypto. Returns { ok, reason, lineage, events, receipts, declared }.
1215
+ * `sender` is the envelope sender; `delegated` is open()'s flag.
1216
+ */
1217
+ export function checkNotice(kind, payload, { sender, delegated = false, bytes = 0 } = {}) {
1218
+ if (delegated) return { ok: false, reason: "delegated" }; // @rule continuity.principal-only
1219
+ if (bytes > MAX_NOTICE_BYTES) return { ok: false, reason: "too-large" }; // @rule continuity.size-cap
1220
+ if (!isPlain(payload) || payload.v !== CONTINUITY_V) return { ok: false, reason: "bad-version" }; // @rule continuity.payload-version
1221
+ if (kind === KIND_LINEAGE) {
1222
+ if (!isClosed(payload, ROTATION_KEYS) || !["rotation", "announce"].includes(payload.type)) return { ok: false, reason: "bad-shape" }; // @rule continuity.rotation-closed-shape
1223
+ const parts = logParts(payload.log);
1224
+ if (!parts || parts.events.length === 0 || parts.events.length > MAX_EVENTS) return { ok: false, reason: "bad-log" }; // @rule continuity.event-cap
1225
+ const capped = overWorkCaps(parts);
1226
+ if (capped) return { ok: false, reason: capped };
1227
+ if (!isValidUuaid(payload.lineage) || !isValidUuaid(payload.current) || !HEAD_RE.test(payload.head)) return { ok: false, reason: "bad-declared" };
1228
+ const keys = keysOf(parts.events);
1229
+ const reveals = revealsOf(parts.events);
1230
+ const homes = homeKeysOf(parts.events);
1231
+ if (!keys.has(sender) && !reveals.has(sender) && !homes.has(sender)) return { ok: false, reason: "sender-not-lineage-key" }; // @rule continuity.sender-is-lineage-key
1232
+ return { ok: true, lineage: payload.lineage, ...parts, declared: { current: payload.current, head: payload.head }, keys: [...keys.keys()], reveals, homes };
1233
+ }
1234
+ if (kind === KIND_SUCCESSOR) {
1235
+ if (!isClosed(payload, SUCCESSOR_KEYS) || payload.type !== "successor" || !isClosed(payload.successor, ["lineage", "current", "head", "log"])) return { ok: false, reason: "bad-shape" }; // @rule continuity.successor-closed-shape
1236
+ if (payload.from !== sender) return { ok: false, reason: "sender-not-from" }; // @rule continuity.successor-signed-by-from
1237
+ const parts = logParts(payload.successor.log);
1238
+ if (!parts || parts.events.length === 0 || parts.events.length > MAX_EVENTS) return { ok: false, reason: "bad-log" };
1239
+ const capped = overWorkCaps(parts);
1240
+ if (capped) return { ok: false, reason: capped };
1241
+ if (!isValidUuaid(payload.successor.lineage) || !isValidUuaid(payload.successor.current) || !HEAD_RE.test(payload.successor.head)) return { ok: false, reason: "bad-declared" };
1242
+ return { ok: true, lineage: payload.successor.lineage, ...parts, declared: { current: payload.successor.current, head: payload.successor.head }, keys: [payload.from] };
1243
+ }
1244
+ return { ok: false, reason: "not-a-notice" };
1245
+ }
1246
+
1247
+ /** Per-sender verify budget (in memory): `VERIFY_BUDGET_PER_HOUR` per sender. */
1248
+ export class VerifyBudget {
1249
+ constructor(limit = VERIFY_BUDGET_PER_HOUR) { this.limit = limit; this.map = new Map(); }
1250
+ /** Would `take` succeed? Charges nothing. */
1251
+ can(sender, nowMs) {
1252
+ return (this.map.get(sender) ?? []).filter((t) => nowMs - t < 3_600_000).length < this.limit;
1253
+ }
1254
+ take(sender, nowMs) {
1255
+ const recent = (this.map.get(sender) ?? []).filter((t) => nowMs - t < 3_600_000);
1256
+ if (recent.length >= this.limit) { this.map.set(sender, recent); return false; } // @rule continuity.verify-budget
1257
+ recent.push(nowMs);
1258
+ this.map.set(sender, recent);
1259
+ return true;
1260
+ }
1261
+ }
1262
+
1263
+ /** Contact keys that may open the gate: the caller's contacts and every key of a lineage the user made firm (B-P0: no chaining). */
1264
+ export function knownKeys(state, contacts) {
1265
+ const out = new Set(contacts ?? []);
1266
+ for (const rec of Object.values(state?.lineages ?? {})) if (rec.pin?.firm === true) for (const k of keysOf(rec.events).keys()) out.add(k);
1267
+ return out;
1268
+ }
1269
+
1270
+ /**
1271
+ * One signature check per key: the first event whose `key` is `u` (deriving
1272
+ * `u`) must carry `u`'s own valid signature, the first one by `u`. Every event
1273
+ * of a genuine log is signed by its key, so a notice that orders junk first
1274
+ * only refuses itself.
1275
+ */
1276
+ export function signsOwnEvent(events, u) {
1277
+ for (const ev of events) {
1278
+ const k = isPlain(ev?.key) && ev.key.uuaid === u ? ev.key
1279
+ : (isPlain(ev?.reveal) && ev.reveal.uuaid === u ? ev.reveal : null);
1280
+ if (!k || typeof k.publicKey !== "string") continue;
1281
+ if (!isKeyDerivedUuaid(u, k.publicKey)) return false;
1282
+ const sgn = (Array.isArray(ev.sigs) ? ev.sigs : []).find((x) => isPlain(x) && x.by === u && typeof x.sig === "string");
1283
+ if (!sgn) return false;
1284
+ let ok = false;
1285
+ try { continuityStats.sigVerifies++; ok = verifyBytesStrict(k.publicKey, signingBytes(ev), sgn.sig) === true; } catch { ok = false; }
1286
+ return ok; // @rule continuity.one-signature-per-key
1287
+ }
1288
+ return false;
1289
+ }
1290
+
1291
+ /** Stored lineages the user has not made firm that name `u`. */
1292
+ function nonFirmNaming(state, u) {
1293
+ return Object.entries(state.lineages).filter(([, r]) => r.pin?.firm !== true && keysOf(r.events).has(u));
1294
+ }
1295
+
1296
+ /** Raw (unverified) claim that `u` was followed by a later establishment event: a notice that could retire `u`. */
1297
+ function rawRetires(events, u) {
1298
+ const own = events.filter((ev) => isPlain(ev?.key) && ev.key.uuaid === u).map((ev) => ev.seq).filter(Number.isSafeInteger);
1299
+ if (own.length === 0) return false;
1300
+ const first = Math.min(...own);
1301
+ return events.some((ev) => isPlain(ev?.key) && ev.key.uuaid !== u && Number.isSafeInteger(ev.seq) && ev.seq > first);
1302
+ }
1303
+
1304
+ /**
1305
+ * Stored non-firm lineages that do not leave `u` as their current key. Uses
1306
+ * the verdict and current recorded when the record was written (no verify);
1307
+ * a record without them is decided afresh.
1308
+ */
1309
+ function retiringCount(state, u, now) {
1310
+ return nonFirmNaming(state, u).filter(([lin, r]) => (typeof r.verdict === "string"
1311
+ ? !(ROUTABLE.has(r.verdict) && r.current === u)
1312
+ : decideLineage(lin, r, u, now).state !== "none")).length;
1313
+ }
1314
+
1315
+ /** Past the per-key cap, admit a new lineage only if it retires every crowded key and fewer than MAX_RETIRING_PER_KEY stored ones do. */
1316
+ function crowdedAdmits(state, crowded, keptKeys, current, now) {
1317
+ for (const u of crowded) {
1318
+ if (!keptKeys.has(u) || current === u) return false;
1319
+ if (retiringCount(state, u, now) >= MAX_RETIRING_PER_KEY) return false; // @rule continuity.crowded-retiring-cap
1320
+ }
1321
+ return true;
1322
+ }
1323
+
1324
+ /**
1325
+ * Classify whether an envelope-authenticated notice belongs to Lane 1 (trusted
1326
+ * admission, `b.auth`, zero pre-budget lineage signature checks):
1327
+ * - `"known-contact"`: `ctx.sender` is an existing contact key or a key of a
1328
+ * firm-pinned lineage;
1329
+ * - `"committed-next"`: `ctx.sender` matches a locally verified `next`-key
1330
+ * commitment (`sha256(pubKey) === ev.next`) of a stored lineage;
1331
+ * - `"pinned-home"`: `ctx.sender` is in the firm-pinned home roster of the
1332
+ * stored lineage.
1333
+ * Any other notice is unproven (Lane 2) and receives no priority.
1334
+ */
1335
+ export function classifyTrustedNotice(state, kind, payload, ctx = {}) {
1336
+ if (ctx.senderVerified !== true || ctx.delegated === true) return null;
1337
+ const chk = checkNotice(kind, payload, ctx);
1338
+ if (!chk.ok) return null;
1339
+ const known = knownKeys(state, ctx.contacts);
1340
+ if (chk.keys.every((u) => !known.has(u))) return null;
1341
+ if (known.has(ctx.sender)) return "known-contact";
1342
+ if (kind !== KIND_LINEAGE) return null;
1343
+ const existing = state?.lineages?.[chk.lineage];
1344
+ if (!existing || !Array.isArray(existing.events) || existing.events.length === 0) return null;
1345
+ const rawPub = typeof ctx.senderPublicKey === "string" && HEX64_RE.test(ctx.senderPublicKey)
1346
+ ? ctx.senderPublicKey
1347
+ : (chk.reveals?.get(ctx.sender) ?? keysOf(chk.events).get(ctx.sender) ?? null);
1348
+ if (typeof rawPub === "string" && HEX64_RE.test(rawPub) && isKeyDerivedUuaid(ctx.sender, rawPub)) {
1349
+ const nextDigest = createHash("sha256").update(Buffer.from(rawPub, "hex")).digest("hex");
1350
+ let matchesNext = false;
1351
+ matchesNext = existing.events.some((ev) => typeof ev?.next === "string" && ev.next === nextDigest); // @rule continuity.trusted-committed-next
1352
+ if (matchesNext) return "committed-next";
1353
+ }
1354
+ let matchesHome = false;
1355
+ if (existing.pin?.firm === true) matchesHome = pinnedRoster(existing, ctx.now).some((h) => h.uuaid === ctx.sender); // @rule continuity.trusted-pinned-home
1356
+ if (matchesHome) return "pinned-home";
1357
+ return null;
1358
+ }
1359
+
1360
+ let proofTokenCounter = 0;
1361
+
1362
+ /**
1363
+ * Ingest one notice into `store`. Returns { stored, reason, trustedClass, ... }.
1364
+ * ctx: { sender, senderVerified, senderPublicKey, delegated, bytes, contacts: Set, now, budget }
1365
+ */
1366
+ export function ingestNotice(store, kind, payload, ctx) {
1367
+ const chk = checkNotice(kind, payload, ctx);
1368
+ if (!chk.ok) return { stored: false, reason: chk.reason };
1369
+ const state = store.read();
1370
+ const known = knownKeys(state, ctx.contacts);
1371
+ const named = chk.keys.filter((u) => known.has(u));
1372
+ if (named.length === 0) return { stored: false, reason: "no-contact-key" }; // @rule continuity.contact-gate
1373
+ // Every cap and budget below runs before any signature is checked (RedTeam 1c5e7a P1, 65c007 P1):
1374
+ // a notice they refuse costs zero continuity signature checks.
1375
+ const existing = kind === KIND_LINEAGE ? state.lineages[chk.lineage] : state.successors[payload.from];
1376
+ if (existing) {
1377
+ if (kind === KIND_SUCCESSOR && existing.lineage !== chk.lineage && existing.conflict?.lineage === chk.lineage) return { stored: false, reason: "no-new-evidence" };
1378
+ const have = new Set(existing.events.map(digestOf));
1379
+ const haveR = new Set(existing.receipts.map(receiptKey));
1380
+ const adds = existing.lineage !== undefined && existing.lineage !== chk.lineage
1381
+ || chk.events.some((ev) => !have.has(digestOf(ev))) || chk.receipts.some((r) => isPlain(r) && !haveR.has(receiptKey(r)));
1382
+ if (!adds) return { stored: false, reason: "no-new-evidence" }; // @rule continuity.no-new-evidence
1383
+ }
1384
+ const isNew = kind === KIND_LINEAGE && !existing;
1385
+ if (isNew && Object.keys(state.lineages).length >= store.maxLineages) return { stored: false, reason: "store-full" }; // @rule continuity.lineage-cap
1386
+ const haveDigests = new Set((existing && (kind === KIND_LINEAGE || existing.lineage === chk.lineage) ? existing.events : []).map(digestOf));
1387
+ const fresh = chk.events.filter((ev) => !haveDigests.has(digestOf(ev))).length;
1388
+ if (fresh > store.maxNewEvents) return { stored: false, reason: "new-event-cap" }; // @rule continuity.new-event-cap
1389
+ const firmRec = kind === KIND_LINEAGE && existing?.pin?.firm === true;
1390
+ if (!firmRec && haveDigests.size + fresh > store.maxNonFirmEvents) return { stored: false, reason: "lineage-event-cap" }; // @rule continuity.nonfirm-event-cap
1391
+ if (firmRec && offPinCount(mergeEvents(existing.events, chk.events), existing.pin.head) > store.maxOffPinEvents) return { stored: false, reason: "fork-event-cap" }; // @rule continuity.firm-offpin-cap
1392
+ const crowded = isNew ? named.filter((u) => nonFirmNaming(state, u).length >= MAX_LINEAGES_PER_KEY) : [];
1393
+ if (crowded.some((u) => !rawRetires(chk.events, u) || retiringCount(state, u, ctx.now) >= MAX_RETIRING_PER_KEY)) return { stored: false, reason: "key-lineage-cap" }; // @rule continuity.key-lineage-cap
1394
+ const sameLineage = kind === KIND_LINEAGE || existing?.lineage === chk.lineage;
1395
+ const candEvents = mergeEvents(sameLineage ? existing?.events ?? [] : [], chk.events);
1396
+ if (candEvents.length > MAX_EVENTS) return { stored: false, reason: "event-cap" };
1397
+ const trustedClass = classifyTrustedNotice(state, kind, payload, ctx);
1398
+ const isTrusted = trustedClass !== null;
1399
+ const candEventSigs = candEvents.reduce((n, ev) => n + (Array.isArray(ev?.sigs) ? ev.sigs.length : 0), 0);
1400
+ const proofReserve = (kind === KIND_LINEAGE ? 1 + named.length : 0) + candEventSigs + chk.receipts.length * 2;
1401
+ if (!isTrusted && proofReserve > store.maxCandidateProof) return { stored: false, reason: "proof-cap", named }; // @rule continuity.proof-candidate-cap
1402
+ const nowMs = Date.parse(ctx.now);
1403
+ if (typeof ctx.budget.can === "function" && !ctx.budget.can(ctx.sender, nowMs)) return { stored: false, reason: "budget", named, trusted: isTrusted };
1404
+ const weight = haveDigests.size + fresh + Math.ceil(chk.receipts.length / 8);
1405
+ const proofToken = !isTrusted ? `${process.pid}-${nowMs}-${++proofTokenCounter}` : null;
1406
+ let spent = null;
1407
+ spent = store.takeBudgets(ctx.sender, weight, nowMs, { reserved: isTrusted, proofReserve: isTrusted ? 0 : proofReserve, proofToken }); // @rule continuity.budget-on-disk
1408
+ if (spent) return { stored: false, reason: spent, named, trusted: isTrusted }; // @rule continuity.receiver-budget-before-verify
1409
+ if (!ctx.budget.take(ctx.sender, nowMs)) {
1410
+ if (proofToken) store.settleProofWork(proofToken, 1, nowMs);
1411
+ return { stored: false, reason: "budget", named, trusted: isTrusted };
1412
+ }
1413
+ const sig0 = continuityStats.sigVerifies;
1414
+ const ver0 = continuityStats.verifies;
1415
+ let r0Len = 0;
1416
+ try {
1417
+ let anchors = named;
1418
+ if (kind === KIND_LINEAGE) {
1419
+ if (trustedClass !== "pinned-home" && !signsOwnEvent(chk.events, ctx.sender)) return { stored: false, reason: "no-sender-signature", trusted: isTrusted }; // @rule continuity.sender-signature
1420
+ anchors = named.filter((u) => signsOwnEvent(chk.events, u)); // @rule continuity.contact-signature-filter
1421
+ if (anchors.length === 0) return { stored: false, reason: "no-contact-signature", trusted: isTrusted }; // @rule continuity.contact-signature
1422
+ }
1423
+ const r0 = verifiedReceipts(chk.lineage, candEvents, mergeReceipts(sameLineage ? existing?.receipts ?? [] : [], chk.receipts), ctx.now);
1424
+ r0Len = r0.length;
1425
+ const v = verifyEvidence(candEvents, r0, ctx.now);
1426
+ if (v.verdict === "invalid" || v.verdict === "indeterminate") return { stored: false, reason: `unverified-${v.verdict}`, trusted: isTrusted }; // @rule continuity.store-only-verified
1427
+ if (v.subject !== chk.lineage) return { stored: false, reason: "lineage-mismatch", trusted: isTrusted }; // @rule continuity.declared-lineage
1428
+ if (ROUTABLE.has(v.verdict) && (v.facts.current !== chk.declared.current || v.facts.head !== chk.declared.head)) return { stored: false, reason: "declared-mismatch", trusted: isTrusted }; // @rule continuity.declared-head-current
1429
+ if (kind === KIND_SUCCESSOR && !(v.facts.boundLegacy ?? []).includes(payload.from)) return { stored: false, reason: "successor-unbound", trusted: isTrusted }; // @rule continuity.successor-needs-bind
1430
+ const discarded = new Set((v.facts.discarded ?? []).map((d) => d?.event).filter(Boolean).map(stripSha));
1431
+ const kept = candEvents.filter((ev) => !discarded.has(digestOf(ev)));
1432
+ const receipts = kept.length === candEvents.length ? r0 : verifiedReceipts(chk.lineage, kept, r0, ctx.now);
1433
+ if (existing && sameLineage) {
1434
+ const have = new Set(existing.events.map(digestOf));
1435
+ const haveR = new Set(existing.receipts.map(receiptKey));
1436
+ const adds = kept.some((ev) => !have.has(digestOf(ev))) || receipts.some((r) => !haveR.has(receiptKey(r)));
1437
+ if (!adds) return { stored: false, reason: "no-new-evidence", trusted: isTrusted }; // @rule continuity.no-new-evidence-verified
1438
+ }
1439
+ let stored = null, refused = null;
1440
+ try {
1441
+ store.update((s) => {
1442
+ if (kind === KIND_LINEAGE) {
1443
+ let rec = s.lineages[chk.lineage];
1444
+ if (!rec) {
1445
+ if (Object.keys(s.lineages).length >= store.maxLineages) { refused = "store-full"; return undefined; }
1446
+ const crowdedNow = anchors.filter((u) => nonFirmNaming(s, u).length >= MAX_LINEAGES_PER_KEY);
1447
+ if (crowdedNow.length && !crowdedAdmits(s, crowdedNow, keysOf(kept), v.facts.current, ctx.now)) { refused = "key-lineage-cap"; return undefined; }
1448
+ rec = newRecord(ctx.now);
1449
+ }
1450
+ rec.events = mergeEvents(rec.events, kept);
1451
+ if (rec.pin?.firm !== true && rec.events.length > store.maxNonFirmEvents) { refused = "lineage-event-cap"; return undefined; } // @rule continuity.nonfirm-event-cap-locked
1452
+ if (rec.pin?.firm === true && offPinCount(rec.events, rec.pin.head) > store.maxOffPinEvents) { refused = "fork-event-cap"; return undefined; }
1453
+ rec.receipts = verifiedReceipts(chk.lineage, rec.events, mergeReceipts(rec.receipts, receipts), ctx.now);
1454
+ let mv = v;
1455
+ mv = verifyEvidence(rec.events, rec.receipts, ctx.now); // @rule continuity.verify-merged-under-lock
1456
+ if (mv.verdict === "invalid" || mv.verdict === "indeterminate") { refused = `merge-unverified-${mv.verdict}`; return undefined; }
1457
+ if (!rec.pin && ROUTABLE.has(mv.verdict)) rec.pin = { head: mv.facts.head, firm: false, at: ctx.now, source: "notice" }; // @rule continuity.first-pin-provisional
1458
+ rec.verdict = mv.verdict;
1459
+ rec.current = mv.facts.current ?? null;
1460
+ rec.updatedAt = ctx.now;
1461
+ s.lineages[chk.lineage] = rec;
1462
+ stored = rec;
1463
+ } else {
1464
+ let rec = s.successors[payload.from];
1465
+ if (rec && rec.lineage !== chk.lineage) {
1466
+ rec.conflict = { lineage: chk.lineage, head: v.facts.head, at: ctx.now }; // @rule continuity.successor-keeps-first
1467
+ rec.updatedAt = ctx.now;
1468
+ stored = rec;
1469
+ return s;
1470
+ }
1471
+ rec ??= { lineage: chk.lineage, events: [], receipts: [], confirmations: [], updatedAt: ctx.now };
1472
+ rec.events = mergeEvents(rec.events, kept);
1473
+ if (rec.events.length > store.maxNonFirmEvents) { refused = "lineage-event-cap"; return undefined; } // @rule continuity.successor-event-cap
1474
+ rec.receipts = verifiedReceipts(chk.lineage, rec.events, mergeReceipts(rec.receipts, receipts), ctx.now);
1475
+ rec.updatedAt = ctx.now;
1476
+ s.successors[payload.from] = rec;
1477
+ stored = rec;
1478
+ }
1479
+ return s;
1480
+ });
1481
+ } catch (e) {
1482
+ if (e?.code === "continuity-store-full") return { stored: false, reason: "store-full", trusted: isTrusted };
1483
+ throw e;
1484
+ }
1485
+ if (refused) return { stored: false, reason: refused, trusted: isTrusted };
1486
+ return { stored: true, verdict: v.verdict, lineage: chk.lineage, head: v.facts.head, current: v.facts.current, record: stored, trusted: isTrusted, trustedClass };
1487
+ } finally {
1488
+ if (proofToken) {
1489
+ const preActual = continuityStats.sigVerifies - sig0;
1490
+ const coreActual = (continuityStats.verifies - ver0) > 0 ? (candEventSigs + r0Len) : 0;
1491
+ let actual = proofReserve;
1492
+ actual = Math.min(proofReserve, Math.max(1, preActual + coreActual)); // @rule continuity.proof-pool-settle
1493
+ if (actual !== proofReserve) store.settleProofWork(proofToken, actual, nowMs);
1494
+ }
1495
+ }
1496
+ }
1497
+
1498
+ // ── user actions ─────────────────────────────────────────────────────────────
1499
+
1500
+ /**
1501
+ * Confirm the exact head and destination for `q` (a retired key or a
1502
+ * successor's `from`). Clears pending-confirm only (B3).
1503
+ */
1504
+ export function confirmRoute(store, { q, head, to, now }) {
1505
+ if (!HEAD_RE.test(String(head)) || !isValidUuaid(to)) throw new ContinuityRefusalError("continuity-confirm-usage", "--head sha256:<64 hex> and --to <uuaid> are required");
1506
+ // The decision is made and checked inside the writer transaction (RedTeam b5cbee P1), so a notice that
1507
+ // lands between a read and the write cannot make a stale confirmation count.
1508
+ store.update((s) => {
1509
+ const d = decideFor(s, q, now);
1510
+ if (d.state === "suspended") throw new ContinuityRefusalError(`redirect-blocked:${d.reason}`, `${q} is suspended (${d.reason}); a confirmation cannot clear it`, d); // @rule continuity.confirm-not-suspended
1511
+ if (d.state !== "pending-confirm") throw new ContinuityRefusalError("continuity-nothing-to-confirm", `${q} has no route waiting for confirmation (state ${d.state})`, d);
1512
+ if (d.head !== head || d.to !== to || (d.kind !== "successor" && typeof d.toKey !== "string")) throw new ContinuityRefusalError("continuity-confirm-mismatch", `the verified head is ${d.head} and the destination ${d.to}; the confirmation names ${head} -> ${to}`, d); // @rule continuity.confirm-matches-verified
1513
+ if (d.kind === "successor") {
1514
+ const rec = s.successors[q];
1515
+ rec.confirmations = [...(rec.confirmations ?? []), { head, to, lineage: d.lineage, at: now }].slice(-MAX_SIDE_ROWS);
1516
+ } else {
1517
+ const rec = s.lineages[d.lineage];
1518
+ rec.confirmations = [...(rec.confirmations ?? []), { head, to, at: now }];
1519
+ // A confirmed head becomes the trust anchor. A witness recovery or checkpointed record keeps the
1520
+ // pinned roster it must be checked against: the pin stays where it was and only becomes firm.
1521
+ const v = verifyEvidence(rec.events, rec.receipts, now); // a cache hit: decideFor above verified this record
1522
+ let anchor = firmPin(rec.events, head, now, v, { source: "confirm" });
1523
+ if (d.verdict === "recovered" || (rec.checkpoints?.length ?? 0) > 0) anchor = rec.pin && chainDigests(rec.events, head).has(stripSha(rec.pin.head)) ? firmPin(rec.events, rec.pin.head, now, v, rec.pin) : rec.pin; // @rule continuity.recovery-keeps-roster
1524
+ rec.pin = anchor;
1525
+ rec.updatedAt = now;
1526
+ }
1527
+ return s;
1528
+ });
1529
+ return decideFor(store.read(), q, now);
1530
+ }
1531
+
1532
+ /**
1533
+ * Ruling 1: the authenticated way out of a fork or a hold. The user obtained the
1534
+ * contact's lineage log over another channel and checked its exact head and
1535
+ * destination there. The log must verify on its own at that head, name `to` as
1536
+ * current and `q` as a retired key. Until this runs, `q` stays held or
1537
+ * suspended; forget and repair never release it.
1538
+ */
1539
+ export function recoverRoute(store, { q, log, head, to, now }) {
1540
+ if (!HEAD_RE.test(String(head)) || !isValidUuaid(to) || !isValidUuaid(q)) throw new ContinuityRefusalError("continuity-recover-usage", "a contact, --log FILE, --head sha256:<64 hex> and --to <uuaid> are required");
1541
+ const parts = logParts(log);
1542
+ if (!parts) throw new ContinuityRefusalError("continuity-recover-usage", "the file is not a lineage log (an event array or uuaid-lineage-log/1)");
1543
+ const events = chainEvents(parts.events, head).sort((a, b) => a.seq - b.seq);
1544
+ const receipts = verifiedReceipts(events[0]?.lineage, events, parts.receipts, now);
1545
+ const v = verifyEvidence(events, receipts, now);
1546
+ if (!ROUTABLE.has(v.verdict)) throw new ContinuityRefusalError("continuity-recover-unverified", `the log up to ${head} verifies ${v.verdict} (${(v.reasons ?? []).join(", ")})`); // @rule continuity.recover-verified
1547
+ if (v.facts.head !== head || v.facts.current !== to) throw new ContinuityRefusalError("continuity-recover-mismatch", `the log's head is ${v.facts.head} and its current key ${v.facts.current}; you named ${head} -> ${to}`); // @rule continuity.recover-exact
1548
+ if (q === to || !(v.facts.keyPath ?? []).includes(q)) throw new ContinuityRefusalError("continuity-recover-mismatch", `${q} is not a retired key of that log`); // @rule continuity.recover-q-retired
1549
+ const toKey = events.find((ev) => ev?.key?.uuaid === to)?.key?.publicKey;
1550
+ store.update((s) => {
1551
+ s.resolutions = { ...(s.resolutions ?? {}), [q]: { lineage: v.subject, head, to, toKey, events, receipts, at: now } };
1552
+ return s;
1553
+ }, { clearCheckpointsFor: { lineage: v.subject, head } });
1554
+ return decideFor(store.read(), q, now);
1555
+ }
1556
+
1557
+ /** Pin a lineage from a log file the user supplies (a firm pin). */
1558
+ export function pinFromLog(store, { log, now }) {
1559
+ const parts = logParts(log);
1560
+ if (!parts) throw new ContinuityRefusalError("continuity-pin-usage", "the file is not a lineage log (an event array or uuaid-lineage-log/1)");
1561
+ const v = verifyEvidence(parts.events, parts.receipts, now);
1562
+ if (!ROUTABLE.has(v.verdict)) throw new ContinuityRefusalError("continuity-pin-unverified", `the log verifies ${v.verdict} (${(v.reasons ?? []).join(", ")})`);
1563
+ // Like a notice (ingestNotice): only the events the core keeps are stored, so a superseded branch
1564
+ // carried by a homes-served log is not (V1 e46aca: every merge is bounded).
1565
+ const discarded = new Set((v.facts.discarded ?? []).map((d) => d?.event).filter(Boolean).map(stripSha));
1566
+ let kept = parts.events;
1567
+ kept = parts.events.filter((ev) => !discarded.has(digestOf(ev))); // @rule continuity.pin-keeps-verified-only
1568
+ try {
1569
+ store.update((s) => {
1570
+ if (!s.lineages[v.subject] && Object.keys(s.lineages).length >= store.maxLineages) throw new ContinuityStoreFull(`${store.maxLineages} lineages are stored; forget one first`);
1571
+ const rec = s.lineages[v.subject] ?? newRecord(now);
1572
+ rec.events = mergeEvents(rec.events, kept);
1573
+ if (offPinCount(rec.events, v.facts.head) > store.maxOffPinEvents) throw new ContinuityRefusalError("continuity-fork-event-cap", `merged with the stored evidence, ${v.subject} would hold more than ${store.maxOffPinEvents} events off the pinned path; nothing was written`); // @rule continuity.pin-offpin-cap
1574
+ rec.receipts = verifiedReceipts(v.subject, rec.events, mergeReceipts(rec.receipts, parts.receipts), now);
1575
+ // The stored verdict and current describe the merged record (P4), not the pinned file alone.
1576
+ let mv = v;
1577
+ mv = verifyEvidence(rec.events, rec.receipts, now); // @rule continuity.pin-verify-merged
1578
+ if (mv.verdict === "invalid" || mv.verdict === "indeterminate") throw new ContinuityRefusalError("continuity-pin-unverified", `the log verifies, but merged with the stored evidence it is ${mv.verdict}; nothing was written`);
1579
+ rec.pin = firmPin(rec.events, v.facts.head, now, v, { source: "pin" });
1580
+ rec.verdict = mv.verdict;
1581
+ rec.current = mv.facts.current ?? null;
1582
+ rec.updatedAt = now;
1583
+ s.lineages[v.subject] = rec;
1584
+ return s;
1585
+ });
1586
+ } catch (e) {
1587
+ if (e?.code === "continuity-store-full") throw new ContinuityRefusalError("continuity-store-full", e.message.replace(/^continuity-store-full: /, ""));
1588
+ throw e;
1589
+ }
1590
+ return { lineage: v.subject, head: v.facts.head, current: v.facts.current };
1591
+ }
1592
+
1593
+ /**
1594
+ * Drop a lineage's evidence and recovery. Never creates a route: every key the
1595
+ * lineage retired or put in conflict stays held (ruling 1), so a send to it is
1596
+ * refused until `recover` selects a verified route.
1597
+ */
1598
+ export function forgetLineage(store, lineage) {
1599
+ let removed = false;
1600
+ store.update((s) => {
1601
+ if (s.lineages[lineage]) { delete s.lineages[lineage]; removed = true; }
1602
+ for (const [from, rec] of Object.entries(s.successors)) if (rec.lineage === lineage) { delete s.successors[from]; removed = true; }
1603
+ for (const [q, r] of Object.entries(s.resolutions ?? {})) if (r.lineage === lineage) { delete s.resolutions[q]; removed = true; }
1604
+ return removed ? s : undefined;
1605
+ });
1606
+ return removed;
1607
+ }
1608
+
1609
+ /** Record a W-4 registry answer that names another current for a tracked key. */
1610
+ export function recordW4(store, { lineage, queried, current, now }) {
1611
+ store.update((s) => {
1612
+ const rec = s.lineages[lineage];
1613
+ if (!rec) return undefined;
1614
+ rec.w4 = [...(rec.w4 ?? []), { queried, current, at: now }];
1615
+ rec.updatedAt = now;
1616
+ return s;
1617
+ });
1618
+ }
1619
+
1620
+ // ── pinned-roster home quorum (B4) ───────────────────────────────────────────
1621
+
1622
+ /** Quorum for N pinned eligible homes: N when N <= 2, else N - 1. */
1623
+ export function quorumFor(n) {
1624
+ let need = n;
1625
+ if (n > 2) need = n - 1; // @rule continuity.quorum-size
1626
+ return need;
1627
+ }
1628
+
1629
+ /**
1630
+ * Ask each PINNED home for the lineage and count the ones that (1) serve a log
1631
+ * verifying `expect` at exactly `head` with current `to`, and (2) hold a seen
1632
+ * receipt for `head` signed by that home's pinned key. The roster never comes
1633
+ * from the presented or fetched log. `events` is the receiver's own record,
1634
+ * used to tell an older copy from a forward or a fork.
1635
+ *
1636
+ * Each home's answer is one of (RedTeam 1c5e7a, 5402b7):
1637
+ * - agree: both hold;
1638
+ * - disagree: the home served a log of this lineage that verifies and holds
1639
+ * an event off the receiver's chain to `head` (a forward or a fork), with
1640
+ * the home's own pinned-key receipt for that event: attributable evidence
1641
+ * of another state. Any disagreement makes the check negative;
1642
+ * - stale: the home served a verified older copy (its head is on the
1643
+ * receiver's chain), or the same head without the evidence for `expect`;
1644
+ * - failed: no usable answer (no URL, transport error or timeout, HTTP
1645
+ * error, not a lineage log, a log that does not verify, another lineage,
1646
+ * no receipt by the pinned key, or another state the home does not vouch for).
1647
+ * Only agree and disagree are attributable; stale and failed change no route.
1648
+ */
1649
+ export async function pinnedHomeQuorum({ lineage, head, to, roster, now, expect = "valid", events = null, fetch: fetchFn = globalThis.fetch, urlMap, allowInsecureLoopback = false, timeoutMs = HOME_TIMEOUT_MS }) {
1650
+ const need = quorumFor(roster.length);
1651
+ if (roster.length === 0) return { ok: false, count: 0, need: 0, disagree: 0, stale: 0, failed: 0, homes: [], reason: "no-pinned-homes" }; // @rule continuity.quorum-no-homes
1652
+ const headHex = stripSha(head);
1653
+ const one = async (home) => {
1654
+ const failed = (why) => ({ home: home.uuaid, answer: "failed", why });
1655
+ const target = resolveHomeTargetUrl(home.url, `/v1/lineage/${encodeURIComponent(lineage)}`, { urlMap, allowInsecureLoopback });
1656
+ if (!target) return failed("no-url");
1657
+ const ctrl = new AbortController();
1658
+ const timer = setTimeout(() => ctrl.abort(), timeoutMs);
1659
+ try {
1660
+ let res;
1661
+ try { res = await fetchFn(target, { headers: { accept: "application/json" }, signal: ctrl.signal }); } catch { return failed("transport"); }
1662
+ if (!res.ok) return failed(`http-${res.status}`);
1663
+ const body = await res.json().catch(() => null);
1664
+ const parts = logParts(body);
1665
+ if (!parts) return failed("not-a-log");
1666
+ const v = verifyEvidence(parts.events, parts.receipts, now);
1667
+ if (v.verdict === "invalid" || v.verdict === "indeterminate") return failed(`unverified-${v.verdict}`);
1668
+ if (v.subject !== lineage) return failed("other-lineage");
1669
+ // a receipt for one of `digests`, signed by this home's pinned key (bounded per home)
1670
+ const homeReceipts = parts.receipts.filter((r) => isPlain(r) && r.registry === home.uuaid).slice(0, MAX_RECEIPTS_PER_NOTICE);
1671
+ const vouchedOf = (digests) => {
1672
+ const seen = new Set();
1673
+ for (const r of homeReceipts) {
1674
+ if (!digests.has(r.event) || seen.has(r.event)) continue;
1675
+ continuityStats.sigVerifies++;
1676
+ if (verifySeenReceipt(r, { now, lineage, event: r.event, home: { uuaid: home.uuaid, publicKey: home.publicKey } }).ok === true) seen.add(r.event);
1677
+ }
1678
+ return [...seen];
1679
+ };
1680
+ let same = false;
1681
+ same = v.verdict === expect && v.facts.head === head && v.facts.current === to; // @rule continuity.quorum-home-serves-head
1682
+ if (same) {
1683
+ let stamped = true; // computed on the next line; the default only matters to a mutant
1684
+ stamped = vouchedOf(new Set([headHex])).length > 0; // @rule continuity.quorum-pinned-key-receipt
1685
+ return stamped ? { home: home.uuaid, answer: "agree" } : failed("no-pinned-key-receipt");
1686
+ }
1687
+ const ours = chainDigests(Array.isArray(events) ? events : parts.events, head);
1688
+ const theirs = typeof v.facts?.head === "string" ? stripSha(v.facts.head) : null;
1689
+ const discarded = new Set((v.facts?.discarded ?? []).map((d) => d?.event).filter(Boolean).map(stripSha));
1690
+ const keptTheirs = parts.events.filter((ev) => !discarded.has(digestOf(ev)));
1691
+ const beyond = new Set(keptTheirs.map(digestOf).filter((d) => d && !ours.has(d)));
1692
+ const vouchedBeyond = beyond.size > 0 ? vouchedOf(beyond) : [];
1693
+ let against = false;
1694
+ against = vouchedBeyond.length > 0; // @rule continuity.quorum-disagreement-attributed
1695
+ if (against) {
1696
+ const relation = theirs && chainDigests(keptTheirs, theirs).has(headHex) ? "ahead" : "fork";
1697
+ const checkpoints = vouchedBeyond.map((ev) => ({ event: ev, head: v.facts?.head ?? null, current: v.facts?.current ?? null, home: home.uuaid, relation, ancestors: [...chainDigests(keptTheirs, ev)].slice(0, MAX_EVENTS) }));
1698
+ return { home: home.uuaid, answer: "disagree", relation, verdict: v.verdict, head: v.facts?.head ?? null, current: v.facts?.current ?? null, checkpoints };
1699
+ }
1700
+ if (theirs && ours.has(theirs)) return { home: home.uuaid, answer: "stale", head: v.facts.head }; // @rule continuity.quorum-stale-apart
1701
+ return failed("unattributed");
1702
+ } catch {
1703
+ return failed("error");
1704
+ } finally {
1705
+ clearTimeout(timer);
1706
+ }
1707
+ };
1708
+ const homes = await Promise.all(roster.map(one));
1709
+ const count = homes.filter((h) => h.answer === "agree").length;
1710
+ const disagree = homes.filter((h) => h.answer === "disagree").length;
1711
+ const stale = homes.filter((h) => h.answer === "stale").length;
1712
+ const checkpoints = homes.flatMap((h) => h.checkpoints ?? []);
1713
+ let ok = true; // computed on the next line; the default only matters to a mutant
1714
+ ok = count >= need; // @rule continuity.quorum-count
1715
+ if (disagree > 0) ok = false; // @rule continuity.quorum-disagreement-vetoes
1716
+ let reason = null;
1717
+ if (!ok) reason = disagree > 0 ? "home-disagreement" : "below-quorum"; // @rule continuity.quorum-disagreement-apart
1718
+ return { ok, count, need, disagree, stale, failed: homes.length - count - disagree - stale, homes, checkpoints, reason };
1719
+ }
1720
+
1721
+ /**
1722
+ * The pinned-home proof in force under roster `rk` (RedTeam 5402b7): the
1723
+ * latest check with attributable evidence decides. A positive check proves its
1724
+ * head and destination; a later check in which a pinned home vouched for
1725
+ * another state retires it. Checks whose homes only failed or served an older
1726
+ * copy are not evidence, and neither give nor take a route.
1727
+ */
1728
+ export function homeProof(checks, rk) {
1729
+ let last = null;
1730
+ for (const h of Array.isArray(checks) ? checks : []) {
1731
+ if (!isPlain(h) || h.roster !== rk) continue;
1732
+ if (h.ok === true || (Number.isSafeInteger(h.disagree) && h.disagree > 0)) last = h; // @rule continuity.home-proof-latest
1733
+ }
1734
+ return last?.ok === true ? last : null;
1735
+ }
1736
+
1737
+ /** Run the pinned-roster check for a record's verified head and store the result. */
1738
+ export async function checkHomes(store, lineage, { now, ...net } = {}) {
1739
+ const rec = store.read().lineages[lineage];
1740
+ if (!rec) return { ok: false, reason: "unknown-lineage" };
1741
+ const v = verifyEvidence(rec.events, rec.receipts, now);
1742
+ if (!ROUTABLE.has(v.verdict)) return { ok: false, reason: `verdict-${v.verdict}` };
1743
+ const roster = rec.pin?.firm === true ? pinnedRoster(rec, now, v) : [];
1744
+ if (roster.length === 0) return { ok: false, reason: rec.pin?.firm ? "no-pinned-homes" : "pin-provisional" };
1745
+ // A witness recovery is checked as such: the pinned homes must serve the same `recovered` head (RedTeam b5cbee P2).
1746
+ const q = await pinnedHomeQuorum({ lineage, head: v.facts.head, to: v.facts.current, roster, now, expect: v.verdict, events: rec.events, ...net });
1747
+ const rk = rosterKey(roster);
1748
+ store.update((s) => {
1749
+ const r = s.lineages[lineage];
1750
+ if (!r) return undefined;
1751
+ r.homeChecks = [...(r.homeChecks ?? []), { head: v.facts.head, to: v.facts.current, ok: q.ok, count: q.count, need: q.need, disagree: q.disagree, stale: q.stale, failed: q.failed, roster: rk, at: now }];
1752
+ if (Array.isArray(q.checkpoints) && q.checkpoints.length > 0) {
1753
+ const merged = new Map((r.checkpoints ?? []).filter(isPlain).map((c) => [`${c.roster}|${c.event}`, c]));
1754
+ for (const cp of q.checkpoints) merged.set(`${rk}|${cp.event}`, { ...cp, roster: rk, at: now });
1755
+ r.checkpoints = [...merged.values()]; // @rule continuity.checkpoint-persisted
1756
+ }
1757
+ r.updatedAt = now;
1758
+ return s;
1759
+ });
1760
+ return { ...q, head: v.facts.head, to: v.facts.current, roster: rk };
1761
+ }
1762
+
1763
+ // ── sender side ──────────────────────────────────────────────────────────────
1764
+
1765
+ const ROTATION_TEXT = "pillar continuity notice: this agent's key changed. A pillar 2.8.0+ client verifies the attached lineage; confirm the new key out of band before replying to it.";
1766
+ const SUCCESSOR_TEXT = "pillar continuity notice: this identity names a successor. A pillar 2.8.0+ client verifies it and asks you to confirm before routing.";
1767
+
1768
+ /** A `lineage` notice payload from a home's own lineage log. */
1769
+ export function buildLineageNotice({ events, receipts = [], type = "rotation", now }) {
1770
+ const v = verifyEvidence(events, receipts, now);
1771
+ if (!ROUTABLE.has(v.verdict)) throw new Error(`continuity: the home's lineage verifies ${v.verdict}; no notice is sent`);
1772
+ return {
1773
+ v: CONTINUITY_V,
1774
+ type,
1775
+ lineage: v.subject,
1776
+ current: v.facts.current,
1777
+ head: v.facts.head,
1778
+ log: receipts.length ? { v: LINEAGE_LOG_VERSION, events, receipts } : events,
1779
+ text: ROTATION_TEXT,
1780
+ };
1781
+ }
1782
+
1783
+ /** A `lineage.successor` notice payload, sent by the old identity `from`. */
1784
+ export function buildSuccessorNotice({ from, events, receipts = [], now }) {
1785
+ const v = verifyEvidence(events, receipts, now);
1786
+ if (!ROUTABLE.has(v.verdict)) throw new Error(`continuity: the successor lineage verifies ${v.verdict}`);
1787
+ if (!(v.facts.boundLegacy ?? []).includes(from)) throw new Error(`continuity: the successor lineage does not bind ${from}`);
1788
+ return {
1789
+ v: CONTINUITY_V,
1790
+ type: "successor",
1791
+ from,
1792
+ successor: { lineage: v.subject, current: v.facts.current, head: v.facts.head, log: receipts.length ? { v: LINEAGE_LOG_VERSION, events, receipts } : events },
1793
+ text: SUCCESSOR_TEXT,
1794
+ };
1795
+ }
1796
+
1797
+ export function isContinuityKind(kind) {
1798
+ return kind === KIND_LINEAGE || kind === KIND_SUCCESSOR;
1799
+ }
1800
+
1801
+ export { HEX64_RE };