@uuaid/pillar 2.6.1 → 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 (61) hide show
  1. package/README.md +201 -5
  2. package/bin/carrier.mjs +21 -0
  3. package/bin/pillar-ask.mjs +4 -1
  4. package/bin/pillar-blob.mjs +6 -0
  5. package/bin/pillar-directory.mjs +280 -16
  6. package/bin/pillar-escrow.mjs +4 -1
  7. package/bin/pillar-group-v2.mjs +6 -0
  8. package/bin/pillar-notify.mjs +13 -0
  9. package/bin/pillar-responder.mjs +266 -23
  10. package/bin/pillar.mjs +504 -255
  11. package/package.json +17 -25
  12. package/src/cli-help.mjs +23 -0
  13. package/src/group-v2-cli.mjs +1 -1
  14. package/src/identity/trust.mjs +72 -6
  15. package/src/mailbox/mailbox.mjs +308 -12
  16. package/src/net/carrier-server.mjs +34 -2
  17. package/src/net/refusals.mjs +2 -0
  18. package/src/net/seed-registry.mjs +2 -1
  19. package/src/net/transport.mjs +308 -92
  20. package/src/node-check.mjs +29 -8
  21. package/src/notify-events.mjs +148 -0
  22. package/src/notify-log.mjs +124 -0
  23. package/src/notify-runner.mjs +372 -0
  24. package/src/notify-store.mjs +725 -0
  25. package/src/notify.mjs +350 -0
  26. package/src/pillar.mjs +382 -27
  27. package/src/readers.mjs +2 -2
  28. package/src/registry/federation.mjs +3056 -0
  29. package/src/registry/gossip.mjs +294 -0
  30. package/src/registry/heartbeats.mjs +195 -0
  31. package/src/registry/lineage-verifier.mjs +972 -0
  32. package/src/registry/lineage.mjs +984 -0
  33. package/src/registry/listings.mjs +549 -0
  34. package/src/registry/resolve.mjs +376 -0
  35. package/src/registry/stats.mjs +508 -0
  36. package/src/sqlite-loader.mjs +40 -0
  37. package/src/vendor/pillar-core.mjs +22 -0
  38. package/src/vendor/uuaid-soul.mjs +2246 -0
  39. package/src/vnext/a6b-common.mjs +270 -0
  40. package/src/vnext/b1-cli.mjs +970 -0
  41. package/src/vnext/card-cli.mjs +370 -0
  42. package/src/vnext/greeter-operator.mjs +160 -0
  43. package/src/vnext/greeter-suggest.mjs +318 -0
  44. package/src/vnext/greeter.mjs +571 -0
  45. package/src/vnext/homes.mjs +48 -0
  46. package/src/vnext/init-cli.mjs +489 -0
  47. package/src/vnext/intro-cli.mjs +81 -0
  48. package/src/vnext/json-dir-mailbox.mjs +296 -0
  49. package/src/vnext/jsonl-mailbox.mjs +1066 -0
  50. package/src/vnext/knock-answer.mjs +162 -0
  51. package/src/vnext/knock-cli.mjs +520 -0
  52. package/src/vnext/knock-lane.mjs +312 -0
  53. package/src/vnext/knock-responder.mjs +344 -0
  54. package/src/vnext/lineage-cli.mjs +653 -0
  55. package/src/vnext/listing-cli.mjs +323 -0
  56. package/src/vnext/resolve-cli.mjs +86 -0
  57. package/src/vnext/soul-cli.mjs +666 -0
  58. package/src/vnext/verify-cli.mjs +251 -0
  59. package/src/vnext/w4-redirect.mjs +178 -0
  60. package/src/vnext/wave-a.mjs +193 -0
  61. package/src/vnext/witness-cli.mjs +547 -0
@@ -15,12 +15,17 @@
15
15
  * chain[n] = sha256(chain[n-1] + envelope_sha256[n])
16
16
  * Where envelope_sha256[i] = sha256(JCS(envelope[i])).
17
17
  */
18
- import Database from "better-sqlite3";
19
18
  import { createHash } from "node:crypto";
20
- import { mkdirSync } from "node:fs";
21
- import { dirname } from "node:path";
19
+ import { existsSync, mkdirSync, statSync } from "node:fs";
20
+ import { dirname, join } from "node:path";
22
21
  import { jcs } from "../identity/jcs.mjs";
22
+ import { requireBetterSqlite3, tryLoadBetterSqlite3 } from "../sqlite-loader.mjs";
23
23
  import { rekeyToSenderUnique } from "../sqlite-rekey.mjs";
24
+ import { JsonDirMailboxReader, resolveJsonDirMailbox } from "../vnext/json-dir-mailbox.mjs";
25
+ import { JsonlMailboxStore, hasJsonlMailboxFiles, resolveWritableJsonlDir } from "../vnext/jsonl-mailbox.mjs";
26
+ import { KNOCK_LANE_CAP, KNOCK_RATE_WINDOW_MS } from "../vnext/knock-lane.mjs";
27
+
28
+ export { JsonDirMailboxReader, JsonlMailboxStore, resolveJsonDirMailbox };
24
29
 
25
30
  // An envelope id is unique only within its sender (Annex B5(a),
26
31
  // src/sqlite-rekey.mjs). The outbox keeps UNIQUE(envelope_id): every id in it
@@ -89,10 +94,59 @@ export function isErasedRow(row) {
89
94
  return !!row && row.envelope_json === ERASED_ENVELOPE_JSON;
90
95
  }
91
96
 
97
+ function isRegularFile(p) {
98
+ try { return typeof p === "string" && p !== ":memory:" && statSync(p).isFile(); } catch { return false; }
99
+ }
100
+
101
+ function toCanonicalIso(value) {
102
+ const ms = typeof value === "number" ? value : Date.parse(value);
103
+ return Number.isFinite(ms) ? new Date(ms).toISOString() : new Date().toISOString();
104
+ }
105
+
92
106
  export class Mailbox {
93
- constructor(path) {
94
- mkdirSync(dirname(path), { recursive: true });
95
- this.db = new Database(path);
107
+ constructor(path, opts = {}) {
108
+ const jsonDir = resolveJsonDirMailbox(path);
109
+ if (jsonDir !== null && !existsSync(join(dirname(jsonDir), "keychain.json"))) {
110
+ this.mode = "json-dir";
111
+ this.jsonDir = jsonDir;
112
+ this.db = null;
113
+ this._jsonDir = new JsonDirMailboxReader(jsonDir);
114
+ return;
115
+ }
116
+ let dbPath = path;
117
+ try {
118
+ if (
119
+ typeof path === "string" &&
120
+ statSync(path).isDirectory() &&
121
+ (existsSync(join(path, "keychain.json")) || existsSync(join(path, "mailbox.db")))
122
+ ) {
123
+ dbPath = join(path, "mailbox.db");
124
+ }
125
+ } catch { /* non-existent or non-directory path: pass through to SQLite / JSONL */ }
126
+ const Database = opts?.forceJsonl ? null : tryLoadBetterSqlite3();
127
+ // A home that already has its SQLite store keeps it. Without better-sqlite3
128
+ // refuse (sqlite-not-installed); a JSONL fallback would hide the stored mail
129
+ // and start a second store beside it.
130
+ if (!Database && !opts?.forceJsonl && isRegularFile(dbPath)) requireBetterSqlite3(`Mailbox (existing store ${dbPath})`); // @rule mailbox.sqlite-missing-refuses-existing-db
131
+ const jsonlDir = resolveWritableJsonlDir(path);
132
+ const hasExistingJsonl =
133
+ typeof dbPath === "string" &&
134
+ dbPath !== ":memory:" &&
135
+ !existsSync(dbPath) &&
136
+ jsonlDir !== ":memory:" &&
137
+ hasJsonlMailboxFiles(jsonlDir);
138
+ if (!Database || hasExistingJsonl) {
139
+ this.mode = "jsonl";
140
+ this.jsonDir = jsonlDir;
141
+ this.db = null;
142
+ this._jsonDir = new JsonlMailboxStore(jsonlDir);
143
+ return;
144
+ }
145
+ this.mode = "sqlite";
146
+ this.jsonDir = null;
147
+ this._jsonDir = null;
148
+ mkdirSync(dirname(dbPath), { recursive: true });
149
+ this.db = new Database(dbPath);
96
150
  this.db.pragma("journal_mode = WAL");
97
151
  this.db.pragma("synchronous = NORMAL");
98
152
  this.db.exec(SCHEMA);
@@ -142,6 +196,25 @@ export class Mailbox {
142
196
  ["recipient_ack_at", "text"], ["recipient_ack_id", "text"], ["recipient_read_at", "text"],
143
197
  ]);
144
198
  this.db.exec(`
199
+ create table if not exists knocks (
200
+ seq integer primary key autoincrement,
201
+ envelope_id text not null,
202
+ sender text not null,
203
+ sender_lineage text not null,
204
+ recipient_lineage text not null,
205
+ payment_type text not null,
206
+ pow_stamp text,
207
+ received_at text not null,
208
+ status text not null default 'pending',
209
+ evicted_at text,
210
+ answered_at text,
211
+ answer_decision text,
212
+ answer_envelope_id text,
213
+ envelope_json text not null,
214
+ unique (sender, envelope_id)
215
+ );
216
+ create index if not exists knocks_status_seq on knocks (status, seq);
217
+ create index if not exists knocks_pair on knocks (sender_lineage, recipient_lineage, received_at);
145
218
  create table if not exists readers (
146
219
  name text primary key,
147
220
  cursor integer not null default 0,
@@ -198,9 +271,11 @@ export class Mailbox {
198
271
  // and `pillar group` verbs naming it go to v2 (Pillar._receive, groupCommandRoute),
199
272
  // and with its v2 store file gone it is cleared, not handed back to v1.
200
273
  addCols("groups", [["v2_synced_at", "text"]]);
274
+ addCols("knocks", [["pow_stamp", "text"]]);
275
+ this.db.exec("create index if not exists knocks_pow_stamp on knocks (sender_lineage, recipient_lineage, pow_stamp);");
201
276
  }
202
277
 
203
- close() { try { this.db.close(); } catch (_e) {} }
278
+ close() { if (this._jsonDir) return this._jsonDir.close(); try { this.db.close(); } catch (_e) {} }
204
279
  /**
205
280
  * Local content erasure, not log deletion. Exactly one selector:
206
281
  * { pairs: [{ sender, envelope_id }] } — sender scopes BOTH logs;
@@ -222,6 +297,7 @@ export class Mailbox {
222
297
  * backups, old JS views, or storage-device snapshots have been erased.
223
298
  */
224
299
  eraseRows(selector) {
300
+ if (this._jsonDir) return this._jsonDir.eraseRows(selector);
225
301
  const bad = () => new TypeError("eraseRows: provide exactly one non-empty selector: pairs [{sender, envelope_id}], conversation, or groupId");
226
302
  if (!selector || typeof selector !== "object" || Array.isArray(selector)) throw bad();
227
303
  const keys = Object.keys(selector);
@@ -263,6 +339,13 @@ export class Mailbox {
263
339
  const bindings = mode === "pairs" ? pairs.map((p) => [p.sender, p.envelope_id]) : [[selector[mode]]];
264
340
  for (const args of bindings) counts[table] += update.run(ERASED_ENVELOPE_JSON, ...args).changes;
265
341
  }
342
+ if (mode === "pairs" || mode === "conversation") {
343
+ const knockWhere = mode === "pairs" ? "sender = ? and envelope_id = ?" : "sender = ?";
344
+ const updateKnocks = this.db.prepare(`update knocks set envelope_json = ?
345
+ where ${LIVE_ENVELOPE_SQL} and (${knockWhere})`);
346
+ const bindings = mode === "pairs" ? pairs.map((p) => [p.sender, p.envelope_id]) : [[selector[mode]]];
347
+ for (const args of bindings) updateKnocks.run(ERASED_ENVELOPE_JSON, ...args);
348
+ }
266
349
  }).immediate();
267
350
  committed = true;
268
351
  // secure_delete clears current cells, not pages freed by an earlier
@@ -285,11 +368,13 @@ export class Mailbox {
285
368
 
286
369
  /** Carrier polling cursors: carrier URL -> highest seq we have consumed. */
287
370
  getCarrierCursors() {
371
+ if (this._jsonDir) return this._jsonDir.getCarrierCursors();
288
372
  const rows = this.db.prepare("select carrier, seq from carrier_cursors").all();
289
373
  return Object.fromEntries(rows.map(r => [r.carrier, r.seq]));
290
374
  }
291
375
 
292
376
  setCarrierCursor(carrier, seq) {
377
+ if (this._jsonDir) return this._jsonDir.setCarrierCursor(carrier, seq);
293
378
  this.db.prepare(
294
379
  "insert into carrier_cursors (carrier, seq) values (?, ?) on conflict(carrier) do update set seq = max(seq, excluded.seq)"
295
380
  ).run(carrier, seq);
@@ -313,6 +398,7 @@ export class Mailbox {
313
398
  * atomically with the insert; concurrent appends are serialized via the SQLite transaction.
314
399
  */
315
400
  appendOutbound(envelope, { thread = null, groupId = null, groupMsgId = null } = {}) {
401
+ if (this._jsonDir) return this._jsonDir.appendOutbound(envelope, { thread, groupId, groupMsgId });
316
402
  return this.db.transaction(() => {
317
403
  const envSha = Mailbox.envelopeSha(envelope);
318
404
  const prev = this._getHead("outbox");
@@ -341,6 +427,7 @@ export class Mailbox {
341
427
  * see the row unquarantined between the two.
342
428
  */
343
429
  appendInbound(envelope, { pulledBy = null, quarantined = null } = {}) {
430
+ if (this._jsonDir) return this._jsonDir.appendInbound(envelope, { pulledBy, quarantined });
344
431
  return this.db.transaction(() => {
345
432
  const sender = envelope.sender ?? envelope.from ?? "unknown";
346
433
  const envSha = Mailbox.envelopeSha(envelope);
@@ -373,11 +460,13 @@ export class Mailbox {
373
460
 
374
461
  /** True if we sent this envelope (trust gate: is a receipt answering OUR send?). */
375
462
  hasOutbound(envelopeId) {
463
+ if (this._jsonDir) return this._jsonDir.hasOutbound(envelopeId);
376
464
  return !!this.db.prepare("select 1 from outbox where envelope_id = ?").get(envelopeId);
377
465
  }
378
466
 
379
467
  /** Full outbox row by envelope id (VDA message-delivery instrument). */
380
468
  getOutbound(envelopeId) {
469
+ if (this._jsonDir) return this._jsonDir.getOutbound(envelopeId);
381
470
  return this.db.prepare("select * from outbox where envelope_id = ?").get(envelopeId) ?? null;
382
471
  }
383
472
 
@@ -387,6 +476,7 @@ export class Mailbox {
387
476
  * may be any sender's: pass the sender whenever it is known.
388
477
  */
389
478
  getInbound(envelopeId, sender) {
479
+ if (this._jsonDir) return this._jsonDir.getInbound(envelopeId, sender);
390
480
  if (sender === undefined) {
391
481
  return this.db.prepare("select * from inbox where envelope_id = ? order by seq asc limit 1").get(envelopeId) ?? null;
392
482
  }
@@ -394,35 +484,195 @@ export class Mailbox {
394
484
  }
395
485
 
396
486
  markOutboundDelivered(envelopeId, ackSha256) {
487
+ if (this._jsonDir) return this._jsonDir.markOutboundDelivered(envelopeId, ackSha256);
397
488
  this.db.prepare("update outbox set status = 'delivered', delivered_at = ?, ack_sha256 = ? where envelope_id = ?")
398
489
  .run(new Date().toISOString(), ackSha256 ?? null, envelopeId);
399
490
  }
400
491
 
401
- outboxTip() { return this._getHead("outbox") ?? "0".repeat(64); }
402
- inboxTip() { return this._getHead("inbox") ?? "0".repeat(64); }
492
+ outboxTip() { return this._jsonDir ? this._jsonDir.outboxTip() : (this._getHead("outbox") ?? "0".repeat(64)); }
493
+ inboxTip() { return this._jsonDir ? this._jsonDir.inboxTip() : (this._getHead("inbox") ?? "0".repeat(64)); }
403
494
 
404
495
  outboxSince(seq = 0, limit = 100) {
496
+ if (this._jsonDir) return this._jsonDir.outboxSince(seq, limit);
405
497
  return this.db.prepare(`select * from outbox where seq > ? and ${LIVE_ENVELOPE_SQL} order by seq asc limit ?`).all(seq, limit);
406
498
  }
407
499
  inboxSince(seq = 0, limit = 100) {
500
+ if (this._jsonDir) return this._jsonDir.inboxSince(seq, limit);
408
501
  return this.db.prepare(`select * from inbox where seq > ? and ${LIVE_ENVELOPE_SQL} order by seq asc limit ?`).all(seq, limit);
409
502
  }
410
503
 
411
- /** Envelopes never shown to the operator (read_at null, not quarantined). Oldest first. */
504
+ _regularInboxWhere() {
505
+ let clause = `quarantined is null and ${LIVE_ENVELOPE_SQL}`;
506
+ clause += " and coalesce(json_extract(envelope_json, '$.kind'), '') <> 'knock'"; // @rule mailbox.k5-sql-exclude-knocks
507
+ return clause;
508
+ }
509
+
510
+ /** Envelopes never shown to the operator (read_at null, not quarantined, never knocks). Oldest first. */
412
511
  inboxUnread(limit = 100) {
413
- return this.db.prepare(`select * from inbox where read_at is null and quarantined is null and ${LIVE_ENVELOPE_SQL} order by seq asc limit ?`).all(limit);
512
+ if (this._jsonDir) return this._jsonDir.inboxUnread(limit);
513
+ return this.db.prepare(`select * from inbox where read_at is null and ${this._regularInboxWhere()} order by seq asc limit ?`).all(limit);
414
514
  }
415
515
 
416
516
  /** Trust-gated envelopes: stored as evidence, never surfaced to handlers. */
417
517
  inboxQuarantined(limit = 100) {
518
+ if (this._jsonDir) return this._jsonDir.inboxQuarantined(limit);
418
519
  return this.db.prepare(`select * from inbox where quarantined is not null and ${LIVE_ENVELOPE_SQL} order by seq asc limit ?`).all(limit);
419
520
  }
420
521
 
522
+ /** Senders holding `envelopeId` quarantined (used by `trust quarantine --release`). */
523
+ quarantinedSenders(envelopeId) {
524
+ if (this._jsonDir) return this._jsonDir.quarantinedSenders(envelopeId);
525
+ return this.db.prepare("select sender from inbox where envelope_id = ? and quarantined is not null").all(envelopeId).map(r => r.sender);
526
+ }
527
+
528
+ /** Lowest seq of any unread, non-quarantined regular inbox row, or null when none exist. */
529
+ oldestUnreadSeq() {
530
+ if (this._jsonDir) return this._jsonDir.oldestUnreadSeq();
531
+ const row = this.db.prepare(`select min(seq) as s from inbox where read_at is null and ${this._regularInboxWhere()}`).get();
532
+ return row?.s ?? null;
533
+ }
534
+
535
+ // ── Knocks lane (vNext §4 K5, K6, T4.4, K8) ──────────────────────────────
536
+
537
+ _k6ActiveWhere() {
538
+ let clause = "answered_at is null";
539
+ clause = "(answered_at is null or coalesce(answer_decision, '') <> 'accept')"; // @rule mailbox.k6-only-accept-resets
540
+ return clause;
541
+ }
542
+
543
+ /** Read-only K6 check: true if a knock from this lineage pair (not accepted) arrived within windowMs. */
544
+ hasUnansweredRecentKnock(senderLineage, recipientLineage, { now = new Date().toISOString(), windowMs = KNOCK_RATE_WINDOW_MS } = {}) {
545
+ if (this._jsonDir) return this._jsonDir.hasUnansweredRecentKnock(senderLineage, recipientLineage, { now, windowMs });
546
+ const nowIso = toCanonicalIso(now);
547
+ const cutoff = new Date(Date.parse(nowIso) - windowMs).toISOString();
548
+ const row = this.db.prepare(
549
+ `select 1 from knocks where sender_lineage = ? and recipient_lineage = ? and ${this._k6ActiveWhere()} and received_at > ? limit 1`
550
+ ).get(senderLineage, recipientLineage, cutoff);
551
+ return !!row;
552
+ }
553
+
554
+ /** Read-only K2 check: true if another knock for this lineage pair already consumed `powStamp`. */
555
+ hasReplayedPowStamp(senderLineage, recipientLineage, powStamp, { envelopeId = null } = {}) {
556
+ if (this._jsonDir) return this._jsonDir.hasReplayedPowStamp(senderLineage, recipientLineage, powStamp, { envelopeId });
557
+ if (typeof powStamp !== "string" || powStamp.length === 0) return false;
558
+ const row = envelopeId == null
559
+ ? this.db.prepare(
560
+ "select 1 from knocks where sender_lineage = ? and recipient_lineage = ? and pow_stamp = ? limit 1"
561
+ ).get(senderLineage, recipientLineage, powStamp)
562
+ : this.db.prepare(
563
+ "select 1 from knocks where sender_lineage = ? and recipient_lineage = ? and pow_stamp = ? and envelope_id <> ? limit 1"
564
+ ).get(senderLineage, recipientLineage, powStamp, envelopeId);
565
+ return !!row;
566
+ }
567
+
568
+ /**
569
+ * Atomically enforce K6 (1 knock / pair / 24h unless accepted), K2 PoW stamp
570
+ * single-use per lineage pair, and T4.4 (cap 50 pending; evict oldest
571
+ * non-introduction first, introduction only when all 50 are introductions),
572
+ * then admit the knock into the `knocks` lane.
573
+ */
574
+ admitKnock({
575
+ envelope,
576
+ senderLineage,
577
+ recipientLineage,
578
+ paymentType,
579
+ powStamp = null,
580
+ now = new Date().toISOString(),
581
+ cap = KNOCK_LANE_CAP,
582
+ windowMs = KNOCK_RATE_WINDOW_MS,
583
+ }) {
584
+ if (this._jsonDir) return this._jsonDir.admitKnock({ envelope, senderLineage, recipientLineage, paymentType, powStamp, now, cap, windowMs });
585
+ const nowIso = toCanonicalIso(now);
586
+ const normalizedStamp = paymentType === "pow" && typeof powStamp === "string" && powStamp.length > 0 ? powStamp : null;
587
+ return this.db.transaction(() => {
588
+ const sender = envelope.sender ?? envelope.from ?? "unknown";
589
+ const existing = this.db.prepare("select seq from knocks where envelope_id = ? and sender = ?").get(envelope.id, sender);
590
+ if (existing) {
591
+ return { admitted: false, duplicate: true, rateLimited: false, stampReplayed: false, seq: existing.seq, evicted: [] };
592
+ }
593
+ const cutoff = new Date(Date.parse(nowIso) - windowMs).toISOString();
594
+ const recent = this.db.prepare(
595
+ `select seq, envelope_id from knocks where sender_lineage = ? and recipient_lineage = ? and ${this._k6ActiveWhere()} and received_at > ? limit 1`
596
+ ).get(senderLineage, recipientLineage, cutoff);
597
+ if (recent) return { admitted: false, duplicate: false, rateLimited: true, stampReplayed: false, evicted: [] }; // @rule mailbox.k6-rate-limit
598
+
599
+ if (normalizedStamp !== null) {
600
+ const replayed = this.db.prepare(
601
+ "select seq from knocks where sender_lineage = ? and recipient_lineage = ? and pow_stamp = ? and envelope_id <> ? limit 1"
602
+ ).get(senderLineage, recipientLineage, normalizedStamp, envelope.id);
603
+ if (replayed) return { admitted: false, duplicate: false, rateLimited: false, stampReplayed: true, evicted: [] }; // @rule mailbox.k2-pow-stamp-replay
604
+ }
605
+
606
+ const evicted = [];
607
+ let pending = this.db.prepare(`select count(*) as n from knocks where status = 'pending' and ${LIVE_ENVELOPE_SQL}`).get().n;
608
+ while (pending >= cap) {
609
+ let victim = null;
610
+ victim = this.db.prepare(`select seq, envelope_id, sender, payment_type from knocks where status = 'pending' and ${LIVE_ENVELOPE_SQL} and payment_type <> 'introduction' order by seq asc limit 1`).get(); // @rule mailbox.t44-evict-non-intro-first
611
+ if (!victim) victim = this.db.prepare(`select seq, envelope_id, sender, payment_type from knocks where status = 'pending' and ${LIVE_ENVELOPE_SQL} order by seq asc limit 1`).get(); // @rule mailbox.t44-evict-cap-50
612
+ if (!victim) break;
613
+ this.db.prepare("update knocks set status = 'evicted', evicted_at = ? where seq = ?").run(nowIso, victim.seq);
614
+ evicted.push(victim);
615
+ pending--;
616
+ }
617
+
618
+ const r = this.db.prepare(`
619
+ insert into knocks (envelope_id, sender, sender_lineage, recipient_lineage, payment_type, pow_stamp, received_at, status, envelope_json)
620
+ values (?, ?, ?, ?, ?, ?, ?, 'pending', ?)
621
+ `).run(envelope.id, sender, senderLineage, recipientLineage, paymentType, normalizedStamp, nowIso, JSON.stringify(envelope));
622
+ return { admitted: true, duplicate: false, rateLimited: false, stampReplayed: false, seq: Number(r.lastInsertRowid), evicted };
623
+ }).immediate();
624
+ }
625
+
626
+ /** Pending (or filtered) knocks in the knocks lane, oldest first. */
627
+ inboxKnocks(limit = KNOCK_LANE_CAP, { status = "pending" } = {}) {
628
+ if (this._jsonDir) return this._jsonDir.inboxKnocks(limit, { status });
629
+ if (status === "all") {
630
+ return this.db.prepare(`select * from knocks where ${LIVE_ENVELOPE_SQL} order by seq asc limit ?`).all(limit);
631
+ }
632
+ return this.db.prepare(`select * from knocks where status = ? and ${LIVE_ENVELOPE_SQL} order by seq asc limit ?`).all(status, limit);
633
+ }
634
+
635
+ /** Look up one knock row by envelope_id (and optional sender). */
636
+ getKnock(envelopeId, sender) {
637
+ if (this._jsonDir) return this._jsonDir.getKnock(envelopeId, sender);
638
+ if (sender === undefined) {
639
+ const rows = this.db.prepare(`select * from knocks where envelope_id = ? and ${LIVE_ENVELOPE_SQL} order by seq asc limit 2`).all(envelopeId);
640
+ if (rows.length > 1) throw new Error(`getKnock: multiple senders hold knock ${envelopeId} (ambiguous); name the sender`); // @rule mailbox.knock-get-ambiguous
641
+ return rows[0] ?? null;
642
+ }
643
+ return this.db.prepare(`select * from knocks where envelope_id = ? and sender = ? and ${LIVE_ENVELOPE_SQL}`).get(envelopeId, sender) ?? null;
644
+ }
645
+
646
+ /** Count knocks by status (default: pending). */
647
+ knockCount(status = "pending") {
648
+ if (this._jsonDir) return this._jsonDir.knockCount(status);
649
+ return this.db.prepare(`select count(*) as n from knocks where status = ? and ${LIVE_ENVELOPE_SQL}`).get(status).n;
650
+ }
651
+
652
+ /** Mark a knock answered so K6 permits a future knock from that lineage pair. */
653
+ markKnockAnswered(envelopeId, { sender, decision = null, answerEnvelopeId = null, now = new Date().toISOString() } = {}) {
654
+ if (this._jsonDir) return this._jsonDir.markKnockAnswered(envelopeId, { sender, decision, answerEnvelopeId, now });
655
+ const nowIso = toCanonicalIso(now);
656
+ return this.db.transaction(() => {
657
+ if (sender === undefined) {
658
+ const n = this.db.prepare(`select count(*) as n from knocks where envelope_id = ? and ${LIVE_ENVELOPE_SQL}`).get(envelopeId).n;
659
+ if (n > 1) throw new Error(`markKnockAnswered: ${n} senders hold knock ${envelopeId} (ambiguous); name the sender`); // @rule mailbox.knock-answer-ambiguous
660
+ const r = this.db.prepare(`update knocks set status = 'answered', answered_at = ?, answer_decision = ?, answer_envelope_id = coalesce(?, answer_envelope_id) where envelope_id = ? and ${LIVE_ENVELOPE_SQL}`)
661
+ .run(nowIso, decision, answerEnvelopeId, envelopeId);
662
+ return r.changes > 0;
663
+ }
664
+ const r = this.db.prepare(`update knocks set status = 'answered', answered_at = ?, answer_decision = ?, answer_envelope_id = coalesce(?, answer_envelope_id) where envelope_id = ? and sender = ? and ${LIVE_ENVELOPE_SQL}`)
665
+ .run(nowIso, decision, answerEnvelopeId, envelopeId, sender);
666
+ return r.changes > 0;
667
+ }).immediate();
668
+ }
669
+
421
670
  /**
422
671
  * Without `sender`, every row under the id is quarantined (the safe side).
423
672
  * An erased row is left as it is (C4): its quarantine state is evidence.
424
673
  */
425
674
  markQuarantined(envelopeId, reason, sender) {
675
+ if (this._jsonDir) return this._jsonDir.markQuarantined(envelopeId, reason, sender);
426
676
  const r = String(reason).slice(0, 100);
427
677
  if (sender === undefined) {
428
678
  this.db.prepare(`update inbox set quarantined = ? where envelope_id = ? and ${LIVE_ENVELOPE_SQL}`).run(r, envelopeId);
@@ -440,6 +690,7 @@ export class Mailbox {
440
690
 
441
691
  /** Queue sends ({ to, key?, op, mvVersion, want?, manifestHash?, conflictsWith? }). Returns the ids queued. */
442
692
  enqueueGroupV2Sends(groupId, sends, { now = new Date().toISOString(), newId }) {
693
+ if (this._jsonDir) return this._jsonDir.enqueueGroupV2Sends(groupId, sends, { now, newId });
443
694
  const ids = [];
444
695
  this.db.transaction(() => {
445
696
  let queued = this.db.prepare("select count(*) as n from group_v2_sendq where state = 'queued'").get().n;
@@ -459,6 +710,7 @@ export class Mailbox {
459
710
 
460
711
  /** Queued rows, oldest first; one group or all. */
461
712
  queuedGroupV2Sends(groupId = null) {
713
+ if (this._jsonDir) return this._jsonDir.queuedGroupV2Sends(groupId);
462
714
  return groupId
463
715
  ? this.db.prepare("select * from group_v2_sendq where state = 'queued' and group_id = ? order by queued_at, rowid").all(groupId)
464
716
  : this.db.prepare("select * from group_v2_sendq where state = 'queued' order by queued_at, rowid").all();
@@ -466,6 +718,7 @@ export class Mailbox {
466
718
 
467
719
  /** state: sent | dropped (final), or queued with a reason (a failed attempt). */
468
720
  markGroupV2Send(id, state, { envelopeId = null, reason = null } = {}) {
721
+ if (this._jsonDir) return this._jsonDir.markGroupV2Send(id, state, { envelopeId, reason });
469
722
  this.db.prepare("update group_v2_sendq set state = ?, state_at = ?, envelope_id = coalesce(?, envelope_id), reason = ? where id = ?")
470
723
  .run(state, new Date().toISOString(), envelopeId, reason ? String(reason).slice(0, 200) : null, id);
471
724
  }
@@ -492,6 +745,7 @@ export class Mailbox {
492
745
  * Returns the number of rows changed (0 = unknown id or not quarantined).
493
746
  */
494
747
  releaseQuarantined(envelopeId, sender) {
748
+ if (this._jsonDir) return this._jsonDir.releaseQuarantined(envelopeId, sender);
495
749
  let changes = 0;
496
750
  this.db.transaction(() => {
497
751
  if (sender === undefined) {
@@ -521,6 +775,7 @@ export class Mailbox {
521
775
 
522
776
  /** Without `sender`, every row under the id is marked read. */
523
777
  markInboxRead(envelopeId, sender) {
778
+ if (this._jsonDir) return this._jsonDir.markInboxRead(envelopeId, sender);
524
779
  const at = new Date().toISOString();
525
780
  if (sender === undefined) {
526
781
  this.db.prepare(`update inbox set read_at = ? where envelope_id = ? and read_at is null and ${LIVE_ENVELOPE_SQL}`).run(at, envelopeId);
@@ -535,6 +790,7 @@ export class Mailbox {
535
790
  * another selector's reach after the user's erase.
536
791
  */
537
792
  setInboundGroup(envelopeId, groupId, sender) {
793
+ if (this._jsonDir) return this._jsonDir.setInboundGroup(envelopeId, groupId, sender);
538
794
  if (sender === undefined) {
539
795
  this.db.prepare(`update inbox set group_id = ? where envelope_id = ? and ${LIVE_ENVELOPE_SQL}`).run(groupId, envelopeId);
540
796
  } else {
@@ -548,12 +804,14 @@ export class Mailbox {
548
804
  * and every explicit-seq write bumps). A new seq or released_seq is above it.
549
805
  */
550
806
  _seqFloor() {
807
+ if (this._jsonDir) return this._jsonDir.inboxTipSeq();
551
808
  return this.db.prepare(`select max(
552
809
  coalesce((select max(coalesce(released_seq, seq)) from inbox), 0),
553
810
  coalesce((select seq from sqlite_sequence where name = 'inbox'), 0)) as n`).get().n;
554
811
  }
555
812
 
556
813
  inboxTipSeq() {
814
+ if (this._jsonDir) return this._jsonDir.inboxTipSeq();
557
815
  return this.db.prepare("select coalesce(max(coalesce(released_seq, seq)), 0) as n from inbox").get().n;
558
816
  }
559
817
 
@@ -563,9 +821,10 @@ export class Mailbox {
563
821
  * original seq, so no cursor that already passed it skips it.
564
822
  */
565
823
  inboxAfter(seq = 0, limit = 500) {
824
+ if (this._jsonDir) return this._jsonDir.inboxAfter(seq, limit);
566
825
  return this.db.prepare(`
567
826
  select * from inbox
568
- where coalesce(released_seq, seq) > ? and quarantined is null and ${LIVE_ENVELOPE_SQL}
827
+ where coalesce(released_seq, seq) > ? and ${this._regularInboxWhere()}
569
828
  order by coalesce(released_seq, seq) asc limit ?
570
829
  `).all(seq, limit);
571
830
  }
@@ -577,15 +836,18 @@ export class Mailbox {
577
836
  // still sees the row after its own cursor.
578
837
 
579
838
  getReader(name) {
839
+ if (this._jsonDir) return this._jsonDir.getReader(name);
580
840
  return this.db.prepare("select * from readers where name = ?").get(name) ?? null;
581
841
  }
582
842
 
583
843
  listReaders() {
844
+ if (this._jsonDir) return this._jsonDir.listReaders();
584
845
  return this.db.prepare("select * from readers order by name").all();
585
846
  }
586
847
 
587
848
  /** Create or refresh a reader's last-run details; never moves its cursor. */
588
849
  touchReader(name, { pid = null, host = null, cwd = null, command = null, cursor = 0 } = {}) {
850
+ if (this._jsonDir) return this._jsonDir.touchReader(name, { pid, host, cwd, command, cursor });
589
851
  this.db.prepare(`
590
852
  insert into readers (name, cursor, pid, host, cwd, command, last_seen)
591
853
  values (?, ?, ?, ?, ?, ?, ?)
@@ -595,11 +857,13 @@ export class Mailbox {
595
857
  }
596
858
 
597
859
  setReaderCursor(name, seq) {
860
+ if (this._jsonDir) return this._jsonDir.setReaderCursor(name, seq);
598
861
  this.db.prepare("update readers set cursor = max(cursor, ?) where name = ?").run(seq, name);
599
862
  }
600
863
 
601
864
  /** A long-running consumer (pillar recv) holds a lease; renew it on a heartbeat. */
602
865
  holdLease(reader, { host, pid, cwd = null, command = null, ttlMs = 90_000 }) {
866
+ if (this._jsonDir) return this._jsonDir.holdLease(reader, { host, pid, cwd, command, ttlMs });
603
867
  const now = new Date();
604
868
  this.db.prepare(`
605
869
  insert into reader_leases (reader, host, pid, cwd, command, started_at, lease_until)
@@ -609,11 +873,13 @@ export class Mailbox {
609
873
  }
610
874
 
611
875
  releaseLease(reader, { host, pid }) {
876
+ if (this._jsonDir) return this._jsonDir.releaseLease(reader, { host, pid });
612
877
  this.db.prepare("delete from reader_leases where reader = ? and host = ? and pid = ?").run(reader, host, pid);
613
878
  }
614
879
 
615
880
  /** Leases not yet expired. The caller decides which are really alive (pid check). */
616
881
  unexpiredLeases() {
882
+ if (this._jsonDir) return this._jsonDir.unexpiredLeases();
617
883
  this.db.prepare("delete from reader_leases where lease_until < ?").run(new Date(Date.now() - 3600_000).toISOString());
618
884
  return this.db.prepare("select * from reader_leases where lease_until >= ? order by started_at").all(new Date().toISOString());
619
885
  }
@@ -622,6 +888,7 @@ export class Mailbox {
622
888
 
623
889
  /** Record a recipient-signed ack. Only for a row actually sent TO `from`. */
624
890
  markOutboundAcked(envelopeId, { from, ackId = null, at = null }) {
891
+ if (this._jsonDir) return this._jsonDir.markOutboundAcked(envelopeId, { from, ackId, at });
625
892
  const r = this.db.prepare(`
626
893
  update outbox set recipient_ack_at = coalesce(recipient_ack_at, ?), recipient_ack_id = coalesce(recipient_ack_id, ?)
627
894
  where envelope_id = ? and recipient = ? and ${LIVE_ENVELOPE_SQL}
@@ -629,8 +896,25 @@ export class Mailbox {
629
896
  return r.changes > 0;
630
897
  }
631
898
 
899
+ /**
900
+ * Like markOutboundAcked, but true only for the FIRST committed transition:
901
+ * the row (ours, sent to `from`, live) had no ack and now has one. A
902
+ * repeated ack, an ack for a row already marked, or the wrong sender is
903
+ * false. Notify's ack opt-in counts only this (markOutboundAcked is true
904
+ * for a row that was already acked).
905
+ */
906
+ markOutboundAckedFirst(envelopeId, { from, ackId = null, at = null }) {
907
+ if (this._jsonDir) return this._jsonDir.markOutboundAckedFirst(envelopeId, { from, ackId, at });
908
+ const r = this.db.prepare(`
909
+ update outbox set recipient_ack_at = ?, recipient_ack_id = coalesce(recipient_ack_id, ?)
910
+ where envelope_id = ? and recipient = ? and recipient_ack_at is null and ${LIVE_ENVELOPE_SQL}
911
+ `).run(at ?? new Date().toISOString(), ackId, envelopeId, from);
912
+ return r.changes > 0;
913
+ }
914
+
632
915
  /** Mark rows read (read implies acked: a missing ack is backfilled). */
633
916
  markOutboundRead(envelopeIds, { at = null } = {}) {
917
+ if (this._jsonDir) return this._jsonDir.markOutboundRead(envelopeIds, { at });
634
918
  const ts = at ?? new Date().toISOString();
635
919
  const stmt = this.db.prepare(`
636
920
  update outbox set recipient_read_at = coalesce(recipient_read_at, ?), recipient_ack_at = coalesce(recipient_ack_at, ?)
@@ -643,10 +927,12 @@ export class Mailbox {
643
927
 
644
928
  /** Outbound rows to one recipient, oldest first (receipt matching). */
645
929
  outboundTo(recipient) {
930
+ if (this._jsonDir) return this._jsonDir.outboundTo(recipient);
646
931
  return this.db.prepare(`select * from outbox where recipient = ? and ${LIVE_ENVELOPE_SQL} order by seq asc`).all(recipient);
647
932
  }
648
933
 
649
934
  outboxRecent(limit = 20) {
935
+ if (this._jsonDir) return this._jsonDir.outboxRecent(limit);
650
936
  return this.db.prepare(`select * from outbox where ${LIVE_ENVELOPE_SQL} order by seq desc limit ?`).all(limit);
651
937
  }
652
938
 
@@ -668,28 +954,34 @@ export class Mailbox {
668
954
  }
669
955
 
670
956
  getGroup(id) {
957
+ if (this._jsonDir) return this._jsonDir.getGroup(id);
671
958
  return this._groupRow(this.db.prepare("select * from groups where id = ?").get(id));
672
959
  }
673
960
 
674
961
  listGroups() {
962
+ if (this._jsonDir) return this._jsonDir.listGroups();
675
963
  return this.db.prepare("select * from groups order by updated_at desc").all().map(r => this._groupRow(r));
676
964
  }
677
965
 
678
966
  /** Mark a groups row as written by the pillar-group/2 sync (see _migrate). The row must exist. */
679
967
  markGroupV2(id, at = new Date().toISOString()) {
968
+ if (this._jsonDir) return this._jsonDir.markGroupV2(id, at);
680
969
  this.db.prepare("update groups set v2_synced_at = ? where id = ?").run(at, id);
681
970
  }
682
971
 
683
972
  isGroupV2Marked(id) {
973
+ if (this._jsonDir) return this._jsonDir.isGroupV2Marked(id);
684
974
  return !!this.db.prepare("select v2_synced_at from groups where id = ?").get(id)?.v2_synced_at;
685
975
  }
686
976
 
687
977
  /** Ids of every row the v2 sync has marked. */
688
978
  groupV2MarkedIds() {
979
+ if (this._jsonDir) return this._jsonDir.groupV2MarkedIds();
689
980
  return this.db.prepare("select id from groups where v2_synced_at is not null order by id").all().map(r => r.id);
690
981
  }
691
982
 
692
983
  putGroup(g) {
984
+ if (this._jsonDir) return this._jsonDir.putGroup(g);
693
985
  const now = new Date().toISOString();
694
986
  this.db.prepare(`
695
987
  insert into groups (id, name, members, keys, created_by, created_at, updated_at, pending, left_at)
@@ -702,10 +994,12 @@ export class Mailbox {
702
994
  }
703
995
 
704
996
  groupInbound(groupId, limit = 50) {
997
+ if (this._jsonDir) return this._jsonDir.groupInbound(groupId, limit);
705
998
  return this.db.prepare(`select * from inbox where group_id = ? and quarantined is null and ${LIVE_ENVELOPE_SQL} order by seq desc limit ?`).all(groupId, limit).reverse();
706
999
  }
707
1000
 
708
1001
  groupOutbound(groupId, limit = 200) {
1002
+ if (this._jsonDir) return this._jsonDir.groupOutbound(groupId, limit);
709
1003
  return this.db.prepare(`select * from outbox where group_id = ? and ${LIVE_ENVELOPE_SQL} order by seq desc limit ?`).all(groupId, limit).reverse();
710
1004
  }
711
1005
 
@@ -714,6 +1008,7 @@ export class Mailbox {
714
1008
  * Returns { ok, badSeq? }. Used by adversarial tests + operator-driven audits.
715
1009
  */
716
1010
  auditOutbox() {
1011
+ if (this._jsonDir) return this._jsonDir.auditOutbox();
717
1012
  const rows = this.db.prepare("select seq, envelope_sha256, chain_hash from outbox order by seq asc").all();
718
1013
  let prev = null;
719
1014
  for (const r of rows) {
@@ -725,6 +1020,7 @@ export class Mailbox {
725
1020
  return { ok: true };
726
1021
  }
727
1022
  auditInbox() {
1023
+ if (this._jsonDir) return this._jsonDir.auditInbox();
728
1024
  const rows = this.db.prepare("select seq, envelope_sha256, chain_hash from inbox order by seq asc").all();
729
1025
  let prev = null;
730
1026
  for (const r of rows) {