@uuaid/pillar 2.6.0 → 2.7.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.
Files changed (62) hide show
  1. package/HOSTING-LIMITS.md +12 -0
  2. package/README.md +201 -5
  3. package/bin/carrier.mjs +72 -2
  4. package/bin/pillar-ask.mjs +4 -1
  5. package/bin/pillar-blob.mjs +6 -0
  6. package/bin/pillar-directory.mjs +280 -16
  7. package/bin/pillar-escrow.mjs +4 -1
  8. package/bin/pillar-group-v2.mjs +6 -0
  9. package/bin/pillar-notify.mjs +13 -0
  10. package/bin/pillar-responder.mjs +266 -23
  11. package/bin/pillar.mjs +504 -255
  12. package/package.json +17 -25
  13. package/src/cli-help.mjs +23 -0
  14. package/src/group-v2-cli.mjs +1 -1
  15. package/src/identity/trust.mjs +72 -6
  16. package/src/mailbox/mailbox.mjs +308 -12
  17. package/src/net/carrier-server.mjs +34 -2
  18. package/src/net/refusals.mjs +2 -0
  19. package/src/net/seed-registry.mjs +2 -1
  20. package/src/net/transport.mjs +308 -92
  21. package/src/node-check.mjs +29 -8
  22. package/src/notify-events.mjs +148 -0
  23. package/src/notify-log.mjs +124 -0
  24. package/src/notify-runner.mjs +372 -0
  25. package/src/notify-store.mjs +725 -0
  26. package/src/notify.mjs +350 -0
  27. package/src/pillar.mjs +382 -27
  28. package/src/readers.mjs +2 -2
  29. package/src/registry/federation.mjs +3056 -0
  30. package/src/registry/gossip.mjs +294 -0
  31. package/src/registry/heartbeats.mjs +195 -0
  32. package/src/registry/lineage-verifier.mjs +972 -0
  33. package/src/registry/lineage.mjs +984 -0
  34. package/src/registry/listings.mjs +549 -0
  35. package/src/registry/resolve.mjs +376 -0
  36. package/src/registry/stats.mjs +508 -0
  37. package/src/sqlite-loader.mjs +40 -0
  38. package/src/vendor/pillar-core.mjs +22 -0
  39. package/src/vendor/uuaid-soul.mjs +2246 -0
  40. package/src/vnext/a6b-common.mjs +270 -0
  41. package/src/vnext/b1-cli.mjs +970 -0
  42. package/src/vnext/card-cli.mjs +370 -0
  43. package/src/vnext/greeter-operator.mjs +160 -0
  44. package/src/vnext/greeter-suggest.mjs +318 -0
  45. package/src/vnext/greeter.mjs +571 -0
  46. package/src/vnext/homes.mjs +48 -0
  47. package/src/vnext/init-cli.mjs +489 -0
  48. package/src/vnext/intro-cli.mjs +81 -0
  49. package/src/vnext/json-dir-mailbox.mjs +296 -0
  50. package/src/vnext/jsonl-mailbox.mjs +1066 -0
  51. package/src/vnext/knock-answer.mjs +162 -0
  52. package/src/vnext/knock-cli.mjs +520 -0
  53. package/src/vnext/knock-lane.mjs +312 -0
  54. package/src/vnext/knock-responder.mjs +344 -0
  55. package/src/vnext/lineage-cli.mjs +653 -0
  56. package/src/vnext/listing-cli.mjs +323 -0
  57. package/src/vnext/resolve-cli.mjs +86 -0
  58. package/src/vnext/soul-cli.mjs +666 -0
  59. package/src/vnext/verify-cli.mjs +251 -0
  60. package/src/vnext/w4-redirect.mjs +178 -0
  61. package/src/vnext/wave-a.mjs +193 -0
  62. package/src/vnext/witness-cli.mjs +547 -0
@@ -0,0 +1,984 @@
1
+ /**
2
+ * Pillar vNext §2 — Home-registry lineage log & `uuaid-lineage-seen/1` receipt store (Wave B B9).
3
+ *
4
+ * Implements:
5
+ * - All 9 `uuaid-lineage/1` event types under Guard C (accepts any verified event whose `prev`
6
+ * is stored, even when `prev` is not the current tip).
7
+ * - `W-1`: SQLite `lineage_receipt` storing signed `uuaid-lineage-seen/1` receipts stamped from
8
+ * the registry's monotonic clock (`now`), never from `ev.ts` or `ev.claimedAt`.
9
+ * - `W-1a` & `W-2`: Sub-threshold `recovery.claim` events store as `complete = 0` with `0` receipts
10
+ * until merged witness + `newKey` signatures meet `witnessThreshold`; registries listed in
11
+ * active or historical `witnesses[]` store events under Guard C and issue `0` receipts.
12
+ * - `recovery.final` hold: refused with `contest-window-open` / `claim-unobserved` until the
13
+ * corroborated contest window (`2nd-earliest eligible home seenAt + contestWindow`) expires.
14
+ * - `C2` / `R25BP-4`: `recovery.*` events at `seq > 0` store and stamp regardless of future `ev.ts`,
15
+ * while non-recovery events keep the `+5 min` `future-ts` refusal.
16
+ * - `RT-5`: Leaf-first eviction of superseded dead-branch events when active-key / canonical events
17
+ * arrive at the `256`-event or `512 KiB` per-lineage cap.
18
+ * - Full-log gossip ingestion (`ingestPresentation`, bounded `<= 1024` receipts, never re-signing
19
+ * peer timestamps).
20
+ */
21
+ import { MAX_TOTAL_LINEAGE_BYTES, checkLineageTotalCap, openRegistryDb } from "./federation.mjs";
22
+ import {
23
+ LINEAGE_SKEW_MS,
24
+ LINEAGE_VERSION,
25
+ durMs,
26
+ eligibleHomes,
27
+ eventDigest,
28
+ isKeyDerivedAgentUuaid,
29
+ jcs,
30
+ verifyLineageDoc,
31
+ } from "../vendor/pillar-core.mjs";
32
+ import {
33
+ ALL_EVENT_TYPES,
34
+ HEX64_RE,
35
+ LINEAGE_LOG_VERSION,
36
+ LINEAGE_SEEN_VERSION,
37
+ MAX_EVENT_SIGS,
38
+ MAX_LOG_RECEIPTS,
39
+ RECOVERY_EVENT_TYPES,
40
+ UUAID_RE,
41
+ buildSeenReceipt,
42
+ checkEventTypeFields,
43
+ isDenseArray,
44
+ isPlainObject,
45
+ isStrictDateTime,
46
+ sha256Hex,
47
+ sigsShapeOk,
48
+ verifyLineageFull,
49
+ verifySeenReceiptStrict,
50
+ } from "./lineage-verifier.mjs";
51
+
52
+ export {
53
+ ALL_EVENT_TYPES,
54
+ LINEAGE_LOG_VERSION,
55
+ LINEAGE_SEEN_VERSION,
56
+ MAX_EVENT_SIGS,
57
+ MAX_LOG_RECEIPTS,
58
+ UUAID_RE,
59
+ isPlainObject,
60
+ isStrictDateTime,
61
+ sigsShapeOk,
62
+ };
63
+
64
+ export const MAX_LINEAGE_EVENTS = 256;
65
+ export const MAX_LINEAGE_BYTES = 512 * 1024;
66
+
67
+ const EVICTABLE_REASONS = new Set([
68
+ "superseded-by-rotation",
69
+ "superseded-by-recovery",
70
+ "owner-event-too-late",
71
+ "equivalent-branch",
72
+ "cancellation-branch",
73
+ "claim-defeated",
74
+ "final-overridden-by-owner",
75
+ ]);
76
+
77
+ function isEvictableReason(reason) {
78
+ return typeof reason === "string" && (EVICTABLE_REASONS.has(reason) || reason.startsWith("claim-stale:"));
79
+ }
80
+
81
+ function nowIso(now) {
82
+ if (typeof now === "string") return now;
83
+ const ms = typeof now === "number" ? now : Date.now();
84
+ return new Date(ms).toISOString().replace(/\.\d{3}Z$/, "Z");
85
+ }
86
+
87
+ function isoSec(ms) {
88
+ return new Date(ms).toISOString().replace(/\.\d{3}Z$/, "Z");
89
+ }
90
+
91
+ function mergeSigs(existing, incoming) {
92
+ const seen = new Set(existing.map((s) => `${s.by}:${s.sig}`));
93
+ const merged = [...existing];
94
+ for (const s of incoming) {
95
+ const key = `${s.by}:${s.sig}`;
96
+ if (!seen.has(key)) {
97
+ seen.add(key);
98
+ merged.push(s);
99
+ }
100
+ }
101
+ return merged;
102
+ }
103
+
104
+ /**
105
+ * Resolve the Ed25519 public key (64 lowercase hex) for an allowed signer `by` on `ev`
106
+ * given `parentEvOrBranch` (accepts either a parent event `{ key }` or a verifier branch `{ st, openClaim }`).
107
+ */
108
+ export function allowedSignerPubKey(ev, parentEvOrBranch, by) {
109
+ if (ev.key && ev.key.uuaid === by && typeof ev.key.publicKey === "string") return ev.key.publicKey; // @rule reg.lineage-signer-key
110
+ if (ev.reveal && ev.reveal.uuaid === by && typeof ev.reveal.publicKey === "string") return ev.reveal.publicKey; // @rule reg.lineage-signer-reveal
111
+ const parentKey = parentEvOrBranch?.st?.key ?? parentEvOrBranch?.key ?? null;
112
+ if (parentKey && parentKey.uuaid === by && typeof parentKey.publicKey === "string") return parentKey.publicKey; // @rule reg.lineage-signer-parent
113
+ if (ev.type === "inception" && Array.isArray(ev.doors)) {
114
+ const d = ev.doors.find((x) => x?.uuaid === by && typeof x.publicKey === "string");
115
+ if (d) return d.publicKey; // @rule reg.lineage-signer-init-door
116
+ }
117
+ if (ev.type === "door.add" && ev.door?.uuaid === by && typeof ev.door.publicKey === "string") return ev.door.publicKey; // @rule reg.lineage-signer-door
118
+ if (ev.type === "recovery.claim") {
119
+ const wits = parentEvOrBranch?.st?.witnesses ?? parentEvOrBranch?.witnesses ?? [];
120
+ const w = wits.find((x) => x?.uuaid === by && typeof x.publicKey === "string");
121
+ if (w) return w.publicKey; // @rule reg.lineage-signer-witness
122
+ }
123
+ if (ev.type === "recovery.veto" && typeof ev.nextKey === "string" && HEX64_RE.test(ev.nextKey) && isKeyDerivedAgentUuaid(by, ev.nextKey)) {
124
+ return ev.nextKey; // @rule reg.lineage-signer-nextkey
125
+ }
126
+ if (ev.type === "recovery.final") {
127
+ const nk = parentEvOrBranch?.openClaim?.ev?.key;
128
+ if (nk && nk.uuaid === by && typeof nk.publicKey === "string") return nk.publicKey; // @rule reg.lineage-signer-claim-key
129
+ }
130
+ return null;
131
+ }
132
+
133
+ function normalizeRegistryKey(registryKey) {
134
+ if (!registryKey) return null;
135
+ if (registryKey._identity && typeof registryKey.sign === "function") {
136
+ const id = registryKey._identity;
137
+ return {
138
+ uuaid: id.uuaid,
139
+ publicKey: id.publicKeyHex.toLowerCase(),
140
+ sign: (bytes) => registryKey.sign(bytes),
141
+ };
142
+ }
143
+ const uuaid = registryKey.uuaid;
144
+ const publicKey = (registryKey.publicKey ?? registryKey.publicKeyHex ?? "").toLowerCase();
145
+ if (typeof registryKey.sign === "function" && uuaid && HEX64_RE.test(publicKey)) {
146
+ return { uuaid, publicKey, sign: registryKey.sign };
147
+ }
148
+ const seedHex = (registryKey.seedHex ?? "").toLowerCase();
149
+ if (!uuaid || !HEX64_RE.test(publicKey) || !HEX64_RE.test(seedHex)) {
150
+ throw new TypeError("LineageStore: registryKey requires a loaded Keychain or { uuaid, publicKey, seedHex }");
151
+ }
152
+ return { uuaid, publicKey, seedHex };
153
+ }
154
+
155
+ export class LineageStore {
156
+ /**
157
+ * @param {object} opts
158
+ * db existing better-sqlite3 Database instance (shared with SeedRegistry)
159
+ * dbPath path to open if `db` is not supplied
160
+ * maxEvents per-lineage distinct event cap (default 256)
161
+ * maxBytes per-lineage serialized event JSON byte cap (default 512 KiB)
162
+ * registryKey optional `{ uuaid, publicKey, seedHex }` used to stamp `uuaid-lineage-seen/1` receipts
163
+ */
164
+ constructor({
165
+ db,
166
+ dbPath = ":memory:",
167
+ maxEvents = MAX_LINEAGE_EVENTS,
168
+ maxBytes = MAX_LINEAGE_BYTES,
169
+ maxTotalLineageBytes = MAX_TOTAL_LINEAGE_BYTES,
170
+ registryKey = null,
171
+ federationStore = null,
172
+ } = {}) {
173
+ this._ownsDb = !db;
174
+ this.db = db ?? openRegistryDb(dbPath);
175
+ if (this._ownsDb) this.db.pragma("journal_mode = WAL");
176
+ this.maxEvents = maxEvents;
177
+ this.maxBytes = maxBytes;
178
+ this.maxTotalLineageBytes = maxTotalLineageBytes;
179
+ this.registryKey = normalizeRegistryKey(registryKey);
180
+ this.federationStore = federationStore;
181
+
182
+ this._monoBaseWall = Date.now();
183
+ this._monoBaseHr = process.hrtime.bigint();
184
+ this._lastGlobalSeenMs = 0;
185
+ this._lastSeenMsByLineage = new Map();
186
+ // Read caches (V1 F2): `changes` counts calls that may change stored events
187
+ // or receipts; `_evalMemo` holds evaluateLineageCached results per lineage.
188
+ this.changes = 0;
189
+ this._evalMemo = new Map();
190
+
191
+ this.db.exec(`
192
+ create table if not exists lineage_event (
193
+ lineage text not null,
194
+ digest text not null,
195
+ seq integer not null,
196
+ prev text,
197
+ type text not null,
198
+ key_uuaid text,
199
+ event_json text not null,
200
+ byte_len integer not null,
201
+ received_at text not null,
202
+ complete integer not null default 1,
203
+ primary key (lineage, digest)
204
+ );
205
+ create index if not exists idx_lineage_event_seq on lineage_event(lineage, seq);
206
+ create index if not exists idx_lineage_event_key on lineage_event(key_uuaid);
207
+
208
+ create table if not exists lineage_uuaid (
209
+ lineage text not null,
210
+ uuaid text not null,
211
+ primary key (lineage, uuaid)
212
+ );
213
+ create index if not exists idx_lineage_uuaid_uuaid on lineage_uuaid(uuaid);
214
+
215
+ create table if not exists lineage_receipt (
216
+ lineage text not null,
217
+ event text not null,
218
+ registry text not null,
219
+ seen_at text not null,
220
+ seen_at_ms integer not null,
221
+ sig text not null,
222
+ receipt_json text not null,
223
+ primary key (lineage, event, registry)
224
+ );
225
+ create index if not exists idx_lineage_receipt_lineage on lineage_receipt(lineage, seen_at_ms, event);
226
+
227
+ create table if not exists lineage_claim_broadcast (
228
+ lineage text not null,
229
+ claim_digest text not null,
230
+ broadcast_at text not null,
231
+ primary key (lineage, claim_digest)
232
+ );
233
+ `);
234
+
235
+ const cols = this.db.prepare("pragma table_info(lineage_event)").all();
236
+ if (!cols.some((c) => c.name === "complete")) {
237
+ this.db.exec("alter table lineage_event add column complete integer not null default 1");
238
+ }
239
+ }
240
+
241
+ close() {
242
+ if (this._ownsDb && this.db.open) this.db.close();
243
+ }
244
+
245
+ setFederationStore(federationStore) {
246
+ this.federationStore = federationStore;
247
+ }
248
+
249
+ _nextSeenAt(lineage, nowProvided, nowMs) {
250
+ const prevLineageMs = this._lastSeenMsByLineage.get(lineage) ?? 0;
251
+ let candidateMs;
252
+ if (nowProvided) {
253
+ candidateMs = nowMs;
254
+ } else {
255
+ const hrElapsed = Number(process.hrtime.bigint() - this._monoBaseHr) / 1e6;
256
+ const monoWall = Math.floor(Math.max(Date.now(), this._monoBaseWall + hrElapsed, this._lastGlobalSeenMs));
257
+ this._lastGlobalSeenMs = monoWall;
258
+ candidateMs = monoWall;
259
+ }
260
+ const clampedMs = Math.max(candidateMs, prevLineageMs);
261
+ this._lastSeenMsByLineage.set(lineage, clampedMs);
262
+ return { seenAt: isoSec(clampedMs), seenAtMs: clampedMs };
263
+ }
264
+
265
+ _indexCompleteEventUuaids(ev) {
266
+ const uuaids = new Set([ev.lineage]);
267
+ if (typeof ev.key?.uuaid === "string") uuaids.add(ev.key.uuaid);
268
+ if (ev.type === "door.add" && typeof ev.door?.uuaid === "string") uuaids.add(ev.door.uuaid);
269
+ if (ev.type === "inception" && Array.isArray(ev.doors)) {
270
+ for (const d of ev.doors) if (typeof d?.uuaid === "string") uuaids.add(d.uuaid);
271
+ }
272
+ const ins = this.db.prepare("insert or ignore into lineage_uuaid (lineage, uuaid) values (?, ?)");
273
+ for (const u of uuaids) ins.run(ev.lineage, u);
274
+ }
275
+
276
+ /** Resolve a UUAID to its unique genesis lineage, detecting cross-lineage ambiguity. */
277
+ lookupLineageByUuaid(uuaid) {
278
+ if (typeof uuaid !== "string" || !UUAID_RE.test(uuaid)) return { ok: false, status: 400, reason: "bad-uuaid" }; // @rule reg.lineage-lookup-uuaid
279
+ const matches = this.db
280
+ .prepare(`
281
+ select distinct lineage from (
282
+ select lineage from lineage_event where complete = 1 and (lineage = ? or key_uuaid = ?)
283
+ union
284
+ select lineage from lineage_uuaid where uuaid = ?
285
+ ) limit 2
286
+ `)
287
+ .all(uuaid, uuaid, uuaid);
288
+ if (matches.length > 1) return { ok: false, status: 409, reason: "ambiguous-uuaid" }; // @rule reg.lineage-lookup-ambiguous
289
+ if (matches.length === 1) return { ok: true, lineage: matches[0].lineage };
290
+ return { ok: false, status: 404, reason: "not-found" };
291
+ }
292
+
293
+ /** True if `uuaid` appears in any stored complete lineage other than `expectedLineage`. */
294
+ hasOtherLineage(uuaid, expectedLineage) {
295
+ const row = this.db
296
+ .prepare(`
297
+ select 1 from (
298
+ select lineage from lineage_event where complete = 1 and (lineage = ? or key_uuaid = ?) and lineage != ?
299
+ union
300
+ select lineage from lineage_uuaid where uuaid = ? and lineage != ?
301
+ ) limit 1
302
+ `)
303
+ .get(uuaid, uuaid, expectedLineage, uuaid, expectedLineage);
304
+ return Boolean(row);
305
+ }
306
+
307
+ findLineageByUuaid(uuaid) {
308
+ const r = this.lookupLineageByUuaid(uuaid);
309
+ return r.ok ? r.lineage : null;
310
+ }
311
+
312
+ /** Return all complete stored event rows for a lineage, ordered deterministically by seq, digest. */
313
+ getRows(lineage, { includeIncomplete = false } = {}) {
314
+ if (includeIncomplete) {
315
+ return this.db.prepare("select * from lineage_event where lineage = ? order by seq asc, digest asc").all(lineage);
316
+ }
317
+ return this.db.prepare("select * from lineage_event where lineage = ? and complete = 1 order by seq asc, digest asc").all(lineage);
318
+ }
319
+
320
+ /** Return stored `uuaid-lineage-seen/1` receipts for a lineage (bounded `<= 1024`). */
321
+ getReceipts(lineage) {
322
+ const rows = this.db
323
+ .prepare("select receipt_json from lineage_receipt where lineage = ? order by seen_at_ms asc, event asc, registry asc limit ?")
324
+ .all(lineage, MAX_LOG_RECEIPTS);
325
+ return rows.map((r) => JSON.parse(r.receipt_json));
326
+ }
327
+
328
+ /** Return all declared `{ uuaid, publicKey, url }` homes across all complete stored events of `lineage`. */
329
+ getDeclaredHomes(lineage) {
330
+ const byUuaid = new Map();
331
+ for (const row of this.getRows(lineage)) {
332
+ const ev = JSON.parse(row.event_json);
333
+ if (Array.isArray(ev.homes)) {
334
+ for (const h of ev.homes) {
335
+ if (h?.uuaid && h?.publicKey && h?.url) byUuaid.set(h.uuaid, h);
336
+ }
337
+ }
338
+ }
339
+ return [...byUuaid.values()];
340
+ }
341
+
342
+ /** Return all active or historical witness records `{ uuaid, publicKey }` for `lineage` (plus optional `extraEv`). */
343
+ getAllWitnesses(lineage, extraEv = null) {
344
+ const out = [];
345
+ for (const row of this.getRows(lineage, { includeIncomplete: true })) {
346
+ const ev = JSON.parse(row.event_json);
347
+ if (Array.isArray(ev.witnesses)) out.push(...ev.witnesses);
348
+ }
349
+ if (extraEv && Array.isArray(extraEv.witnesses)) out.push(...extraEv.witnesses);
350
+ return out;
351
+ }
352
+
353
+ _isWitnessForLineage(lineage, extraEv = null) {
354
+ if (!this.registryKey) return false;
355
+ const { uuaid, publicKey } = this.registryKey;
356
+ return this.getAllWitnesses(lineage, extraEv).some((w) => w && (w.uuaid === uuaid || w.publicKey === publicKey));
357
+ }
358
+
359
+ /** Build the complete ancestor chain ending at `parentDigest` (inclusive), or null if broken/missing. */
360
+ _loadAncestors(lineage, parentDigest, expectedParentSeq) {
361
+ const chain = [];
362
+ const seen = new Set();
363
+ let curDigest = parentDigest;
364
+ let curSeq = expectedParentSeq;
365
+ const stmt = this.db.prepare("select digest, seq, prev, event_json from lineage_event where lineage = ? and digest = ? and complete = 1");
366
+ while (curDigest !== null) {
367
+ if (seen.has(curDigest)) return null;
368
+ seen.add(curDigest);
369
+ const row = stmt.get(lineage, curDigest);
370
+ if (!row) return null; // @rule reg.lineage-ancestor-missing
371
+ if (row.seq !== curSeq) return null; // @rule reg.lineage-ancestor-seq
372
+ chain.push(JSON.parse(row.event_json));
373
+ curDigest = row.prev;
374
+ curSeq -= 1;
375
+ }
376
+ if (curSeq !== -1) return null; // @rule reg.lineage-ancestor-root
377
+ chain.reverse();
378
+ return chain;
379
+ }
380
+
381
+ _eligibleClaimReceiptTimes(lineage, claimDigest, homes, witnesses, nowMs) {
382
+ const elig = eligibleHomes(homes ?? [], witnesses ?? []);
383
+ const rows = this.db.prepare("select receipt_json from lineage_receipt where lineage = ? and event = ?").all(lineage, claimDigest);
384
+ const best = new Map();
385
+ for (const row of rows) {
386
+ const r = JSON.parse(row.receipt_json);
387
+ const h = elig.find((x) => x.uuaid === r.registry);
388
+ if (!h || !verifySeenReceiptStrict(r, { lineage, home: h, nowMs })) continue;
389
+ const t = Date.parse(r.seenAt);
390
+ if (!best.has(h.uuaid) || t < best.get(h.uuaid)) best.set(h.uuaid, t);
391
+ }
392
+ return [...best.values()].sort((a, b) => a - b);
393
+ }
394
+
395
+ /**
396
+ * RT-5 cap defense: evict incomplete partial claims and leaf-first superseded dead-branch
397
+ * events when a non-superseded incoming event hits `maxEvents` or `maxBytes`.
398
+ */
399
+ _evictForIncoming(lineage, incomingDigest, candidateEv, incomingByteLen, isUpdate, nowStr, storedReceipts) {
400
+ const countAndBytes = () =>
401
+ this.db
402
+ .prepare("select count(*) as cnt, coalesce(sum(byte_len), 0) as total from lineage_event where lineage = ? and digest != ?")
403
+ .get(lineage, incomingDigest);
404
+
405
+ const fits = (st) => (isUpdate || st.cnt + 1 <= this.maxEvents) && st.total + incomingByteLen <= this.maxBytes;
406
+ if (fits(countAndBytes())) return;
407
+
408
+ // Evaluate candidate against all stored complete events to identify superseded dead branches.
409
+ const completeRows = this.db
410
+ .prepare("select digest, seq, prev, byte_len, event_json from lineage_event where lineage = ? and complete = 1 and digest != ? order by seq asc, digest asc")
411
+ .all(lineage, incomingDigest);
412
+ const allEvents = [...completeRows.map((r) => JSON.parse(r.event_json)), candidateEv];
413
+ const evalRes = verifyLineageFull(
414
+ { v: LINEAGE_LOG_VERSION, events: allEvents, receipts: storedReceipts },
415
+ { now: nowStr, allowBind: true, ignoreRecoveryFutureTs: true },
416
+ );
417
+
418
+ const discardedRoots = new Set();
419
+ for (const d of evalRes.facts?.discarded ?? []) {
420
+ if (isEvictableReason(d.reason)) discardedRoots.add(d.event);
421
+ }
422
+
423
+ // Expand discarded roots to their full subtrees across stored + incoming events.
424
+ const parentByDigest = new Map(completeRows.map((r) => [r.digest, r.prev]));
425
+ parentByDigest.set(incomingDigest, candidateEv.prev);
426
+ const inEvictableSubtree = (dig) => {
427
+ for (let cur = dig; cur; cur = parentByDigest.get(cur) ?? null) {
428
+ if (discardedRoots.has(cur)) return true;
429
+ }
430
+ return false;
431
+ };
432
+
433
+ // Never evict stored events to make room for an incoming event that is ITSELF superseded spam.
434
+ if (inEvictableSubtree(incomingDigest)) return; // @rule reg.rt5-refuse-superseded-incoming
435
+
436
+ // 1. Evict incomplete (`complete = 0`) partial claims first.
437
+ const partials = this.db
438
+ .prepare("select digest from lineage_event where lineage = ? and complete = 0 and digest != ? order by received_at asc")
439
+ .all(lineage, incomingDigest);
440
+ const delStmt = this.db.prepare("delete from lineage_event where lineage = ? and digest = ?");
441
+ for (const p of partials) {
442
+ delStmt.run(lineage, p.digest);
443
+ if (fits(countAndBytes())) return;
444
+ }
445
+
446
+ // 2. Evict superseded complete events strictly leaf-first (zero remaining children, highest seq first).
447
+ const childCount = new Map();
448
+ const rowByDigest = new Map();
449
+ for (const r of completeRows) {
450
+ rowByDigest.set(r.digest, r);
451
+ childCount.set(r.digest, 0);
452
+ }
453
+ for (const r of completeRows) {
454
+ if (r.prev && childCount.has(r.prev)) childCount.set(r.prev, childCount.get(r.prev) + 1);
455
+ }
456
+ if (candidateEv.prev && childCount.has(candidateEv.prev)) {
457
+ childCount.set(candidateEv.prev, childCount.get(candidateEv.prev) + 1);
458
+ }
459
+
460
+ const evictable = completeRows.filter((r) => inEvictableSubtree(r.digest));
461
+ while (!fits(countAndBytes())) {
462
+ const leafCandidates = evictable
463
+ .filter((r) => rowByDigest.has(r.digest) && (childCount.get(r.digest) ?? 0) === 0)
464
+ .sort((a, b) => b.seq - a.seq || b.byte_len - a.byte_len || (a.digest < b.digest ? 1 : -1));
465
+ if (!leafCandidates.length) break;
466
+ const victim = leafCandidates[0];
467
+ delStmt.run(lineage, victim.digest); // @rule reg.rt5-evict-superseded
468
+ rowByDigest.delete(victim.digest);
469
+ childCount.delete(victim.digest);
470
+ if (victim.prev && childCount.has(victim.prev)) {
471
+ childCount.set(victim.prev, childCount.get(victim.prev) - 1);
472
+ }
473
+ }
474
+ }
475
+
476
+ _stampOwnReceiptIfEligible(lineage, digest, candidateEv, nowProvided, nowMs) {
477
+ if (!this.registryKey) return { receipt: null, receiptCreated: false };
478
+ if (this._isWitnessForLineage(lineage, candidateEv)) {
479
+ this.db.prepare("delete from lineage_receipt where lineage = ? and registry = ?").run(lineage, this.registryKey.uuaid); // @rule reg.witness-home-exclusion
480
+ return { receipt: null, receiptCreated: false }; // @rule reg.witness-home-zero-receipt
481
+ }
482
+ const existing = this.db
483
+ .prepare("select receipt_json from lineage_receipt where lineage = ? and event = ? and registry = ?")
484
+ .get(lineage, digest, this.registryKey.uuaid);
485
+ if (existing) return { receipt: JSON.parse(existing.receipt_json), receiptCreated: false };
486
+
487
+ const { seenAt, seenAtMs } = this._nextSeenAt(lineage, nowProvided, nowMs);
488
+ const rec = buildSeenReceipt(this.registryKey, lineage, digest, seenAt);
489
+ const insRec = this.db.prepare("insert into lineage_receipt (lineage, event, registry, seen_at, seen_at_ms, sig, receipt_json) values (?, ?, ?, ?, ?, ?, ?)");
490
+ insRec.run(lineage, digest, this.registryKey.uuaid, seenAt, seenAtMs, rec.sig, JSON.stringify(rec)); // @rule reg.stamp-own-receipt
491
+ return { receipt: rec, receiptCreated: true };
492
+ }
493
+
494
+ /**
495
+ * Verify and store one `uuaid-lineage/1` event (Guard C + W-1/W-1a/W-2 + C2 + RT-5).
496
+ */
497
+ storeEvent(ev, { now } = {}) {
498
+ const nowProvided = now !== undefined;
499
+ const nowStr = nowIso(now);
500
+ const nowMs = Date.parse(nowStr);
501
+
502
+ if (!isPlainObject(ev)) return { ok: false, reason: "malformed-artifact" }; // @rule reg.lineage-object
503
+ if (ev.v !== LINEAGE_VERSION) return { ok: false, reason: "unsupported-version" }; // @rule reg.lineage-version
504
+ if (typeof ev.type !== "string" || !ALL_EVENT_TYPES.has(ev.type)) return { ok: false, reason: "unsupported-event" }; // @rule reg.lineage-wave-a-type
505
+ if (typeof ev.lineage !== "string" || !UUAID_RE.test(ev.lineage)) return { ok: false, reason: "bad-uuaid" }; // @rule reg.lineage-uuaid
506
+ if (!Number.isInteger(ev.seq) || ev.seq < 0) return { ok: false, reason: "bad-seq" }; // @rule reg.lineage-seq
507
+ if (!isStrictDateTime(ev.ts)) return { ok: false, reason: "bad-ts" }; // @rule reg.lineage-ts-format
508
+ if (Date.parse(ev.ts) > nowMs + LINEAGE_SKEW_MS && !(ev.seq > 0 && RECOVERY_EVENT_TYPES.has(ev.type))) {
509
+ return { ok: false, reason: "future-ts" }; // @rule reg.lineage-future-ts
510
+ }
511
+ if (!sigsShapeOk(ev.sigs)) return { ok: false, reason: "bad-signature" }; // @rule reg.lineage-sigs-shape
512
+
513
+ let digest;
514
+ try {
515
+ jcs(ev);
516
+ digest = eventDigest(ev);
517
+ } catch {
518
+ return { ok: false, reason: "malformed-artifact" }; // @rule reg.lineage-canonical
519
+ }
520
+
521
+ const fieldErr = checkEventTypeFields(ev);
522
+ if (fieldErr) return { ok: false, reason: fieldErr }; // @rule reg.lineage-closed-keys
523
+
524
+ let ancestors = [];
525
+ if (ev.type === "inception") {
526
+ if (ev.seq !== 0 || ev.prev !== null) return { ok: false, reason: "prev-not-null" }; // @rule reg.lineage-inception-root
527
+ } else {
528
+ if (ev.seq <= 0 || typeof ev.prev !== "string" || !HEX64_RE.test(ev.prev)) return { ok: false, reason: "prev-mismatch" }; // @rule reg.lineage-rotation-prev-format
529
+ ancestors = this._loadAncestors(ev.lineage, ev.prev, ev.seq - 1);
530
+ if (!ancestors) return { ok: false, reason: "missing-prev" }; // @rule reg.lineage-missing-prev
531
+ }
532
+
533
+ const tx = this.db.transaction(() => {
534
+ const storedReceipts = this.getReceipts(ev.lineage);
535
+ let parentBranch = null;
536
+ if (ancestors.length > 0) {
537
+ const ancEval = verifyLineageFull(
538
+ { v: LINEAGE_LOG_VERSION, events: ancestors, receipts: storedReceipts },
539
+ { now: nowStr, allowBind: true, ignoreRecoveryFutureTs: true },
540
+ );
541
+ const pNode = ancEval._nodes.get(ev.prev);
542
+ if (!pNode) return { ok: false, reason: ancEval.reasons[0] ?? "missing-prev" }; // @rule reg.lineage-tombstone-ancestors
543
+ parentBranch = pNode.branch;
544
+ }
545
+
546
+ if (ev.type === "tombstone" && ev.sigs[0]?.by !== parentBranch.st.key.uuaid) {
547
+ return { ok: false, reason: "tombstone-not-current-key" }; // @rule reg.lineage-tombstone-owner
548
+ }
549
+
550
+ // Every incoming signature must belong to an allowed signer for this event and verify strictly.
551
+ for (const s of ev.sigs) {
552
+ const pub = allowedSignerPubKey(ev, parentBranch, s.by);
553
+ if (!pub || !isKeyDerivedAgentUuaid(s.by, pub) || !verifyLineageDoc(ev, pub, s.sig)) {
554
+ return { ok: false, reason: "bad-signature" }; // @rule reg.lineage-incoming-sigs
555
+ }
556
+ }
557
+
558
+ const existingRow = this.db
559
+ .prepare("select event_json, byte_len, complete from lineage_event where lineage = ? and digest = ?")
560
+ .get(ev.lineage, digest);
561
+ const prevParsed = existingRow ? JSON.parse(existingRow.event_json) : null;
562
+ const mergedSigs = mergeSigs(prevParsed ? prevParsed.sigs : [], ev.sigs);
563
+ const candidateEv = prevParsed ? { ...prevParsed, sigs: mergedSigs } : { ...ev, sigs: mergedSigs };
564
+
565
+ // Sub-threshold recovery.claim handling (W-1a + W-2): stage with 0 receipts until threshold + newKey sig met.
566
+ if (candidateEv.type === "recovery.claim") {
567
+ if (parentBranch.tombstoned) return { ok: false, reason: "after-tombstone" };
568
+ if (parentBranch.openClaim) return { ok: false, reason: "claim-already-open" };
569
+ const wits = parentBranch.st.witnesses;
570
+ const witCount = wits.filter((w) => candidateEv.sigs.some((s) => s.by === w.uuaid && verifyLineageDoc(candidateEv, w.publicKey, s.sig))).length;
571
+ if (wits.length === 0 || witCount === 0) return { ok: false, reason: "witness-threshold" }; // @rule reg.claim-requires-witness-sig
572
+ const hasNewKeySig = candidateEv.sigs.some((s) => s.by === candidateEv.key.uuaid && verifyLineageDoc(candidateEv, candidateEv.key.publicKey, s.sig));
573
+ if (!isKeyDerivedAgentUuaid(candidateEv.key.uuaid, candidateEv.key.publicKey)) return { ok: false, reason: "key-uuaid-mismatch" };
574
+ const kh = sha256Hex(candidateEv.key.publicKey);
575
+ if (parentBranch.used.includes(candidateEv.key.publicKey) || parentBranch.usedNext.includes(kh)) return { ok: false, reason: "key-reused" };
576
+ if (candidateEv.next === kh) return { ok: false, reason: "next-is-key" };
577
+ if (parentBranch.used.some((u) => sha256Hex(u) === candidateEv.next) || parentBranch.usedNext.includes(candidateEv.next)) return { ok: false, reason: "next-reused" };
578
+ if (parentBranch.st.homes.some((h) => h.publicKey === candidateEv.key.publicKey || sha256Hex(h.publicKey) === candidateEv.next)) {
579
+ return { ok: false, reason: "home-is-lineage-key" };
580
+ }
581
+
582
+ if (witCount < parentBranch.st.m || !hasNewKeySig) {
583
+ const serializedPartial = JSON.stringify(candidateEv);
584
+ const partialBytes = Buffer.byteLength(serializedPartial, "utf8");
585
+ const stats = this.db
586
+ .prepare("select count(*) as cnt, coalesce(sum(byte_len), 0) as total from lineage_event where lineage = ? and digest != ?")
587
+ .get(ev.lineage, digest);
588
+ if (!existingRow && stats.cnt + 1 > this.maxEvents) return { ok: false, reason: "lineage-cap-exceeded" };
589
+ if (stats.total + partialBytes > this.maxBytes) return { ok: false, reason: "lineage-cap-exceeded" };
590
+
591
+ const sigAdded = !prevParsed || candidateEv.sigs.length > prevParsed.sigs.length;
592
+ if (existingRow) {
593
+ this.db
594
+ .prepare("update lineage_event set event_json = ?, byte_len = ?, received_at = ? where lineage = ? and digest = ?")
595
+ .run(serializedPartial, partialBytes, nowStr, ev.lineage, digest);
596
+ } else {
597
+ const insPartial = this.db.prepare("insert into lineage_event (lineage, digest, seq, prev, type, key_uuaid, event_json, byte_len, received_at, complete) values (?, ?, ?, ?, ?, ?, ?, ?, ?, 0)");
598
+ insPartial.run(ev.lineage, digest, candidateEv.seq, candidateEv.prev, candidateEv.type, null, serializedPartial, partialBytes, nowStr); // @rule reg.claim-partial-uncomplete
599
+ }
600
+ const partialOut = { ok: true, lineage: ev.lineage, digest: `sha256:${digest}`, seq: candidateEv.seq, merged: Boolean(existingRow), sigCount: candidateEv.sigs.length, complete: false, changed: !existingRow || sigAdded, receipt: null };
601
+ return partialOut; // @rule reg.claim-partial-zero-receipt
602
+ }
603
+ }
604
+
605
+ // Hold recovery.final until corroborated registry seenAt + contestWindow expires (W-1).
606
+ if (candidateEv.type === "recovery.final") {
607
+ if (!parentBranch.openClaim || candidateEv.claim !== parentBranch.openClaim.d) {
608
+ return { ok: false, reason: "final-without-open-claim" };
609
+ }
610
+ const nk = parentBranch.openClaim.ev.key;
611
+ if (!candidateEv.sigs.some((s) => s.by === nk.uuaid && verifyLineageDoc(candidateEv, nk.publicKey, s.sig))) {
612
+ return { ok: false, reason: "bad-signature" };
613
+ }
614
+ const oc = parentBranch.openClaim;
615
+ const cwMs = durMs(oc.cw);
616
+ const eligTimes = this._eligibleClaimReceiptTimes(ev.lineage, oc.d, oc.homes, oc.witnesses, nowMs);
617
+ if (eligTimes.length === 1 && nowMs < eligTimes[0] + cwMs) return { ok: false, reason: "contest-window-open" }; // @rule reg.final-single-home-hold
618
+ if (eligTimes.length < 2) return { ok: false, reason: "claim-unobserved" };
619
+ if (nowMs < eligTimes[1] + cwMs) return { ok: false, reason: "contest-window-open" }; // @rule reg.final-contest-window-hold
620
+ }
621
+
622
+ const check = verifyLineageFull(
623
+ { v: LINEAGE_LOG_VERSION, events: [...ancestors, candidateEv], receipts: storedReceipts },
624
+ { now: nowStr, allowBind: true, ignoreRecoveryFutureTs: true },
625
+ );
626
+ if (!check._nodes.has(digest)) {
627
+ const discReason = check.facts?.discarded?.find((x) => x.event === digest)?.reason;
628
+ return { ok: false, reason: discReason ?? check.reasons[0] ?? "invalid-event" }; // @rule reg.lineage-verify
629
+ }
630
+
631
+ const serialized = JSON.stringify(candidateEv);
632
+ const byteLen = Buffer.byteLength(serialized, "utf8");
633
+
634
+ this._evictForIncoming(ev.lineage, digest, candidateEv, byteLen, Boolean(existingRow), nowStr, storedReceipts);
635
+
636
+ const stats = this.db
637
+ .prepare("select count(*) as cnt, coalesce(sum(byte_len), 0) as total from lineage_event where lineage = ? and digest != ?")
638
+ .get(ev.lineage, digest);
639
+ if (!existingRow && stats.cnt + 1 > this.maxEvents) return { ok: false, reason: "lineage-cap-exceeded" }; // @rule reg.lineage-cap-count
640
+ if (stats.total + byteLen > this.maxBytes) return { ok: false, reason: "lineage-cap-exceeded" }; // @rule reg.lineage-cap-bytes
641
+ const totalCap = checkLineageTotalCap(ev.lineage, stats.total + byteLen, {
642
+ maxTotalBytes: this.federationStore?.maxTotalLineageBytes ?? this.maxTotalLineageBytes,
643
+ listingStore: this.federationStore?.listingStore ?? null,
644
+ heartbeatStore: this.federationStore?.heartbeatStore ?? null,
645
+ lineageStore: null,
646
+ });
647
+ if (!totalCap.ok) return { ok: false, reason: "lineage-cap-exceeded" };
648
+
649
+ const keyUuaid = candidateEv.key?.uuaid ?? (candidateEv.type === "door.add" ? candidateEv.door?.uuaid : null) ?? null;
650
+ const becameComplete = !existingRow || existingRow.complete === 0;
651
+ const sigAdded = !prevParsed || candidateEv.sigs.length > prevParsed.sigs.length;
652
+
653
+ if (existingRow) {
654
+ this.db
655
+ .prepare("update lineage_event set key_uuaid = ?, event_json = ?, byte_len = ?, received_at = ?, complete = 1 where lineage = ? and digest = ?")
656
+ .run(keyUuaid, serialized, byteLen, nowStr, ev.lineage, digest);
657
+ } else {
658
+ this.db
659
+ .prepare(`
660
+ insert into lineage_event (lineage, digest, seq, prev, type, key_uuaid, event_json, byte_len, received_at, complete)
661
+ values (?, ?, ?, ?, ?, ?, ?, ?, ?, 1)
662
+ `)
663
+ .run(ev.lineage, digest, candidateEv.seq, candidateEv.prev, candidateEv.type, keyUuaid, serialized, byteLen, nowStr);
664
+ }
665
+ this._indexCompleteEventUuaids(candidateEv);
666
+ if (this.federationStore) {
667
+ const doorUuaids = Array.isArray(candidateEv.doors) ? candidateEv.doors.map((d) => d?.uuaid).filter(Boolean) : [];
668
+ this.federationStore.notifyLocalIngest(
669
+ ev.lineage,
670
+ ...(keyUuaid ? [keyUuaid] : []),
671
+ ...(typeof candidateEv.reveal?.uuaid === "string" ? [candidateEv.reveal.uuaid] : []),
672
+ ...doorUuaids,
673
+ );
674
+ }
675
+
676
+ const { receipt, receiptCreated } = this._stampOwnReceiptIfEligible(ev.lineage, digest, candidateEv, nowProvided, nowMs);
677
+
678
+ return {
679
+ ok: true,
680
+ lineage: ev.lineage,
681
+ digest: `sha256:${digest}`,
682
+ seq: candidateEv.seq,
683
+ merged: Boolean(existingRow),
684
+ sigCount: candidateEv.sigs.length,
685
+ complete: true,
686
+ changed: becameComplete || sigAdded || receiptCreated,
687
+ ...(receipt ? { receipt } : {}),
688
+ };
689
+ });
690
+
691
+ return tx();
692
+ }
693
+
694
+ /**
695
+ * Store verified peer `uuaid-lineage-seen/1` receipts from declared non-witness homes of `lineage`.
696
+ * Never re-signs peer timestamps and never overwrites this registry's own receipt rows.
697
+ */
698
+ ingestPeerReceipts(lineage, receipts, { now } = {}) {
699
+ if (!isDenseArray(receipts) || receipts.length === 0) return { accepted: 0, changed: false };
700
+ const nowMs = Date.parse(nowIso(now));
701
+ const tx = this.db.transaction(() => {
702
+ const completeDigests = new Set(this.getRows(lineage).map((r) => r.digest));
703
+ if (!completeDigests.size) return { accepted: 0, changed: false };
704
+ const declaredHomes = this.getDeclaredHomes(lineage);
705
+ const allWitnesses = this.getAllWitnesses(lineage);
706
+ const eligHomes = eligibleHomes(declaredHomes, allWitnesses);
707
+
708
+ let accepted = 0;
709
+ let changed = false;
710
+ const getExisting = this.db.prepare("select seen_at_ms from lineage_receipt where lineage = ? and event = ? and registry = ?");
711
+ const countForLin = this.db.prepare("select count(*) as n from lineage_receipt where lineage = ?");
712
+ const upsert = this.db.prepare(`
713
+ insert into lineage_receipt (lineage, event, registry, seen_at, seen_at_ms, sig, receipt_json)
714
+ values (?, ?, ?, ?, ?, ?, ?)
715
+ on conflict(lineage, event, registry) do update set
716
+ seen_at = excluded.seen_at,
717
+ seen_at_ms = excluded.seen_at_ms,
718
+ sig = excluded.sig,
719
+ receipt_json = excluded.receipt_json
720
+ `);
721
+
722
+ for (const r of receipts.slice(0, MAX_LOG_RECEIPTS)) {
723
+ if (!isPlainObject(r) || r.lineage !== lineage) continue;
724
+ if (this.registryKey && r.registry === this.registryKey.uuaid) continue; // @rule reg.gossip-never-overwrite-self
725
+ if (!completeDigests.has(r.event)) continue; // @rule reg.gossip-receipt-known-event
726
+ const home = eligHomes.find((h) => h.uuaid === r.registry);
727
+ if (!home) continue; // @rule reg.gossip-receipt-eligible-home
728
+ if (!verifySeenReceiptStrict(r, { lineage, home, nowMs })) continue; // @rule reg.gossip-receipt-sig
729
+ const seenMs = Date.parse(r.seenAt);
730
+ const cur = getExisting.get(lineage, r.event, r.registry);
731
+ if (cur && seenMs >= cur.seen_at_ms) continue;
732
+ if (!cur && countForLin.get(lineage).n >= MAX_LOG_RECEIPTS) continue; // @rule reg.gossip-receipt-cap
733
+ const clean = { v: LINEAGE_SEEN_VERSION, lineage: r.lineage, event: r.event, registry: r.registry, seenAt: r.seenAt, sig: r.sig };
734
+ upsert.run(lineage, r.event, r.registry, r.seenAt, seenMs, r.sig, JSON.stringify(clean));
735
+ accepted += 1;
736
+ changed = true;
737
+ }
738
+ return { accepted, changed };
739
+ });
740
+ return tx();
741
+ }
742
+
743
+ /**
744
+ * Ingest a full `uuaid-lineage-log/1` presentation (gossip or client sync).
745
+ * Runs 2 passes (`non-final events -> peer receipts -> recovery.final & descendants -> peer receipts`)
746
+ * so corroborated `recovery.final` events verify cleanly once peer claim receipts are stored.
747
+ */
748
+ ingestPresentation(presentation, { now } = {}) {
749
+ if (!isPlainObject(presentation) || presentation.v !== LINEAGE_LOG_VERSION) {
750
+ return { ok: false, reason: "malformed-lineage-log" }; // @rule reg.gossip-pres-version
751
+ }
752
+ if (!isDenseArray(presentation.events) || presentation.events.length === 0 || presentation.events.length > MAX_LINEAGE_EVENTS) {
753
+ return { ok: false, reason: "malformed-lineage-log" }; // @rule reg.gossip-pres-events
754
+ }
755
+ if (presentation.receipts !== undefined && (!isDenseArray(presentation.receipts) || presentation.receipts.length > MAX_LOG_RECEIPTS)) {
756
+ return { ok: false, reason: "malformed-lineage-log" }; // @rule reg.gossip-pres-receipts-cap
757
+ }
758
+ const allowedKeys = new Set(["v", "events", "receipts"]);
759
+ if (!Object.keys(presentation).every((k) => allowedKeys.has(k))) {
760
+ return { ok: false, reason: "malformed-lineage-log" }; // @rule reg.gossip-pres-closed
761
+ }
762
+
763
+ const sorted = [...presentation.events].sort((a, b) => (a?.seq ?? 0) - (b?.seq ?? 0));
764
+ const lineage = sorted[0]?.lineage;
765
+ if (typeof lineage !== "string" || !UUAID_RE.test(lineage)) {
766
+ return { ok: false, reason: "bad-uuaid" };
767
+ }
768
+ if (sorted.some((e) => !isPlainObject(e) || e.lineage !== lineage)) {
769
+ return { ok: false, reason: "lineage-mismatch" }; // @rule reg.gossip-single-lineage
770
+ }
771
+
772
+ let changed = false;
773
+ let storedCount = 0;
774
+ const deferredEvents = [];
775
+
776
+ for (const ev of sorted) {
777
+ const r = this.storeEvent(ev, { now });
778
+ if (r.ok) {
779
+ storedCount += 1;
780
+ if (r.changed) changed = true;
781
+ } else if (r.reason === "claim-unobserved" || r.reason === "contest-window-open" || r.reason === "missing-prev") {
782
+ deferredEvents.push(ev);
783
+ } else {
784
+ return { ok: false, reason: r.reason };
785
+ }
786
+ }
787
+
788
+ const peerReceipts = presentation.receipts ?? [];
789
+ if (peerReceipts.length > 0) {
790
+ const pr1 = this.ingestPeerReceipts(lineage, peerReceipts, { now });
791
+ if (pr1.changed) changed = true;
792
+ }
793
+
794
+ if (deferredEvents.length > 0) {
795
+ for (const ev of deferredEvents) {
796
+ const r = this.storeEvent(ev, { now });
797
+ if (r.ok) {
798
+ storedCount += 1;
799
+ if (r.changed) changed = true;
800
+ }
801
+ }
802
+ if (peerReceipts.length > 0) {
803
+ const pr2 = this.ingestPeerReceipts(lineage, peerReceipts, { now });
804
+ if (pr2.changed) changed = true;
805
+ }
806
+ }
807
+
808
+ if (storedCount === 0) return { ok: false, reason: "no-verifiable-events" };
809
+ const pres = this.getPresentation(lineage);
810
+ return {
811
+ ok: true,
812
+ lineage,
813
+ storedCount,
814
+ changed,
815
+ presentation: pres.ok ? pres.presentation : { v: LINEAGE_LOG_VERSION, events: [], receipts: [] },
816
+ };
817
+ }
818
+
819
+ /**
820
+ * Return newly corroborated `recovery.claim` items (`>= 2` valid eligible home receipts,
821
+ * not yet recorded in `lineage_claim_broadcast`) with target owner key and active doors.
822
+ */
823
+ getPendingClaimBroadcasts(lineage, { now } = {}) {
824
+ const hasUnbroadcastClaim = this.db
825
+ .prepare(`
826
+ select 1 from lineage_event e
827
+ where e.lineage = ? and e.complete = 1 and e.type = 'recovery.claim'
828
+ and not exists (
829
+ select 1 from lineage_claim_broadcast b
830
+ where b.lineage = e.lineage and b.claim_digest = e.digest
831
+ )
832
+ limit 1
833
+ `)
834
+ .get(lineage);
835
+ if (!hasUnbroadcastClaim) return [];
836
+ const nowStr = nowIso(now);
837
+ const nowMs = Date.parse(nowStr);
838
+ const rows = this.getRows(lineage);
839
+ if (!rows.length) return [];
840
+ const events = rows.map((r) => JSON.parse(r.event_json));
841
+ const receipts = this.getReceipts(lineage);
842
+ const ver = verifyLineageFull({ v: LINEAGE_LOG_VERSION, events, receipts }, { now: nowStr, allowBind: true, ignoreRecoveryFutureTs: true });
843
+
844
+ const out = [];
845
+ const sentStmt = this.db.prepare("select 1 from lineage_claim_broadcast where lineage = ? and claim_digest = ?");
846
+ for (const [d, node] of ver._nodes.entries()) {
847
+ if (node.e.type !== "recovery.claim" || !node.parent) continue;
848
+ if (sentStmt.get(lineage, d)) continue;
849
+ const oc = node.branch.openClaim;
850
+ const times = this._eligibleClaimReceiptTimes(lineage, d, oc.homes, oc.witnesses, nowMs);
851
+ if (times.length < 2) continue; // @rule reg.broadcast-requires-corroboration
852
+ const pst = node.parent.branch.st;
853
+ const recipients = [pst.key];
854
+ for (const dr of pst.doors.values()) {
855
+ if (!dr.notAfter || Date.parse(dr.notAfter) > nowMs) recipients.push({ uuaid: dr.uuaid, publicKey: dr.publicKey });
856
+ }
857
+ out.push({ claimDigest: d, claimEvent: node.e, recipients });
858
+ }
859
+ return out;
860
+ }
861
+
862
+ markClaimBroadcast(lineage, claimDigest, { now } = {}) {
863
+ this.db
864
+ .prepare("insert or ignore into lineage_claim_broadcast (lineage, claim_digest, broadcast_at) values (?, ?, ?)")
865
+ .run(lineage, claimDigest, nowIso(now));
866
+ }
867
+
868
+ /**
869
+ * Serve `uuaid-lineage-log/1` presentation (`events` + signed `receipts`, `<= 1024`) for any lineage or key UUAID.
870
+ */
871
+ getPresentation(uuaid) {
872
+ const lookup = this.lookupLineageByUuaid(uuaid);
873
+ if (!lookup.ok) return { ok: false, status: lookup.status, reason: lookup.reason }; // @rule reg.lineage-get-lookup
874
+ const lineage = lookup.lineage;
875
+ const rows = this.getRows(lineage);
876
+ if (rows.length === 0) return { ok: false, status: 404, reason: "not-found" };
877
+ const events = rows.map((r) => JSON.parse(r.event_json));
878
+ const receipts = this.getReceipts(lineage);
879
+ return {
880
+ ok: true,
881
+ lineage,
882
+ presentation: {
883
+ v: LINEAGE_LOG_VERSION,
884
+ events,
885
+ receipts,
886
+ },
887
+ };
888
+ }
889
+
890
+ /**
891
+ * evaluateLineage, remembered per lineage for at most `maxAgeMs` of `now`
892
+ * (a verdict can change with time alone: a recovery claim becoming
893
+ * effective). A call that may write the lineage's events or receipts
894
+ * forgets its entry (LINEAGE_WRITES). `maxAgeMs: 0` always evaluates and
895
+ * refreshes the entry. Returns the same object for a remembered lineage:
896
+ * callers must not modify it.
897
+ */
898
+ evaluateLineageCached(lineage, { now, maxAgeMs } = {}) {
899
+ const nowMs = Date.parse(nowIso(now));
900
+ const hit = this._evalMemo.get(lineage);
901
+ if (hit && nowMs >= hit.atMs && nowMs - hit.atMs < maxAgeMs) return hit.ev; // @rule reg.lineage-eval-memo-age
902
+ const ev = this.evaluateLineage(lineage, { now });
903
+ this._evalMemo.set(lineage, { atMs: nowMs, ev });
904
+ return ev;
905
+ }
906
+
907
+ /** A write to `lineage` (unknown: any lineage) happened or may have happened. */
908
+ _noteLineageWrite(lineage) {
909
+ this.changes++;
910
+ if (typeof lineage !== "string") {
911
+ this._evalMemo.clear();
912
+ return;
913
+ }
914
+ this._evalMemo.delete(lineage); // @rule reg.lineage-eval-memo-forget
915
+ }
916
+
917
+ isTombstoned(lineage, { now } = {}) {
918
+ return this.evaluateLineage(lineage, { now })?.tombstoned === true;
919
+ }
920
+
921
+ /**
922
+ * Evaluate stored complete events + stored receipts for `lineage` at `now` using full 9-event `r2.5b'''` rules.
923
+ */
924
+ evaluateLineage(lineage, { now } = {}) {
925
+ const rows = this.getRows(lineage);
926
+ if (rows.length === 0) return null;
927
+ const nowStr = nowIso(now);
928
+ const events = rows.map((r) => JSON.parse(r.event_json));
929
+ const receipts = this.getReceipts(lineage);
930
+ const latestTs = events.reduce((acc, e) => (Date.parse(e.ts) > Date.parse(acc) ? e.ts : acc), events[0].ts);
931
+ const lv = verifyLineageFull({ v: LINEAGE_LOG_VERSION, events, receipts }, { now: nowStr, allowBind: true });
932
+
933
+ if (lv.verdict === "contested") {
934
+ return { verdict: "contested", reasons: lv.reasons, events, receipts, current: null, head: undefined, latestTs, forked: true, tombstoned: false, raw: lv }; // @rule reg.lineage-eval-fork
935
+ }
936
+
937
+ const tombstoned = Boolean(lv.facts?.tombstoned);
938
+ const headDigest = typeof lv.facts?.head === "string" && lv.facts.head.startsWith("sha256:") ? lv.facts.head.slice(7) : null;
939
+ const tombstoneTs = tombstoned && headDigest ? lv._nodes.get(headDigest)?.e?.ts : undefined;
940
+
941
+ return {
942
+ verdict: lv.verdict,
943
+ reasons: lv.reasons,
944
+ events,
945
+ receipts,
946
+ current: lv.facts?.current ?? null,
947
+ head: lv.facts?.head,
948
+ latestTs,
949
+ forked: false,
950
+ tombstoned,
951
+ ...(tombstoneTs ? { tombstoneTs } : {}),
952
+ raw: lv,
953
+ };
954
+ }
955
+ }
956
+
957
+ /**
958
+ * LineageStore methods that may write events or receipts, and the lineage
959
+ * each one writes (undefined = not known: forget every entry). Each call,
960
+ * accepted or refused, ends with _noteLineageWrite.
961
+ */
962
+ const LINEAGE_WRITES = {
963
+ storeEvent: (ev) => ev?.lineage,
964
+ ingestPeerReceipts: (lineage) => lineage,
965
+ ingestPresentation: (p) => {
966
+ const ls = new Set(Array.isArray(p?.events) ? p.events.map((e) => e?.lineage) : []);
967
+ return ls.size === 1 ? [...ls][0] : undefined;
968
+ },
969
+ };
970
+
971
+ for (const [name, lineageOf] of Object.entries(LINEAGE_WRITES)) {
972
+ const write = LineageStore.prototype[name];
973
+ Object.defineProperty(LineageStore.prototype, name, {
974
+ value: function noted(...args) {
975
+ try {
976
+ return write.apply(this, args);
977
+ } finally {
978
+ this._noteLineageWrite(lineageOf(...args));
979
+ }
980
+ },
981
+ writable: true,
982
+ configurable: true,
983
+ });
984
+ }