@uuaid/pillar 2.7.3 → 2.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/pillar.mjs CHANGED
@@ -48,6 +48,11 @@ import { KNOCK_LANE, KNOCK_LANE_CAP, KNOCK_RATE_WINDOW_MS, validateKnockEnvelope
48
48
  import { KNOCK_ANSWER_KIND, answersOurKnock, buildKnockAnswer } from "./vnext/knock-answer.mjs";
49
49
  import { nowIsoSeconds } from "./vnext/wave-a.mjs";
50
50
  import { W4_CONFIRM_CODE, w4ApplyPolicy, w4ClassifyVerifiedTarget, recordRedirect } from "./vnext/w4-redirect.mjs";
51
+ import {
52
+ ContinuityRefusalError, ContinuityStore, MAX_NOTICE_BYTES, VerifyBudget, advanceBacklog, allowAliases, blockAliases, checkHomes, classifyTrustedNotice, clearBacklog, decideFor, decisionFingerprint, ingestNotice, isContinuityKind, keysOf, noteBacklog, recordW4,
53
+ } from "./vnext/continuity.mjs";
54
+ import { IMPORT_PERIOD_MS, importRetiredMail } from "./vnext/retired-import.mjs";
55
+ export { ContinuityRefusalError };
51
56
 
52
57
  export class W4RefusalError extends Error {
53
58
  constructor(code, fix, details = {}) {
@@ -87,6 +92,7 @@ export class Pillar {
87
92
  home = null, // agent home directory (for trust.json persistence on knock accept)
88
93
  knockConfig = null, // vNext §4 knock policy: { requiredBits?, maxBytes?, introductions?, stake?, trustedIssuers?, trustedContacts?, lineageResolver?, lineages?, selfLineage?, card?, cap?, rateWindowMs?, now? }
89
94
  registryUrl = null, // vNext §3 registry base URL; when set, sends follow W-4 sender redirect policy (B5, T2.7)
95
+ continuity = null, // 2.8.0 continuity: { passphrase?, now?, fetch?, urlMap?, allowInsecureLoopback? } (DESIGN-continuity)
90
96
  }) {
91
97
  if (!keychain?._identity) throw new Error("Pillar: keychain must be loaded before construction");
92
98
  this.keychain = keychain;
@@ -94,6 +100,11 @@ export class Pillar {
94
100
  this.home = home ?? (typeof mailboxPath === "string" ? dirname(mailboxPath) : null);
95
101
  this.knockConfig = knockConfig;
96
102
  this.registryUrl = registryUrl;
103
+ this.continuityOpts = continuity ?? {};
104
+ this._continuityHome = home ?? (typeof mailboxPath === "string" && mailboxPath !== ":memory:" ? dirname(mailboxPath) : null);
105
+ this._continuityBudget = new VerifyBudget();
106
+ this._importTimer = null;
107
+ this.lastImport = null;
97
108
  this.listenAddrs = listenAddrs;
98
109
  this.bootstrapPeers = bootstrapPeers;
99
110
  this.enableRelay = enableRelay;
@@ -314,12 +325,21 @@ export class Pillar {
314
325
  /**
315
326
  * Build and send a `pillar-knock/1` (`kind: "knock"`) envelope to `recipient`.
316
327
  */
317
- async sendKnock({ recipient, recipientPublicKey, card, intent, payment, bits, ts, resolveTimeoutMs = 5000, registryUrl = null, confirmRecovered = false, now = null, urlMap = undefined, allowInsecureLoopback = false, fetch: fetchOverride = undefined }) {
328
+ async sendKnock({ recipient, recipientPublicKey, subject = null, card, intent, payment, bits, ts, resolveTimeoutMs = 5000, registryUrl = null, confirmRecovered = false, now = null, urlMap = undefined, allowInsecureLoopback = false, fetch: fetchOverride = undefined }) {
318
329
  const senderCard = card ?? this.knockConfig?.card;
319
330
  const effTs = ts !== undefined ? ts : this._knockNow();
331
+ // The identity the caller asked for: its continuity decision comes first, before W-4 or a caller's
332
+ // own resolution rewrites the target (RedTeam b5cbee P1). Held or suspended: refused here.
333
+ const subj = subject ?? recipient;
334
+ await this._drainNoticeBacklog();
335
+ const cr = this._applyRoute(subj, recipientPublicKey); // @rule C-route-knock-subject
336
+ if (cr.fields.redirectedTo && recipient !== subj && recipient !== cr.recipient) throw new ContinuityRefusalError("redirect-blocked:route-changed", `${subj} routes to ${cr.recipient}, not to ${recipient}; nothing was sent`, { queried: subj, to: cr.recipient });
337
+ if (cr.fields.redirectedTo) ({ recipient, recipientPublicKey } = cr);
338
+ else if (recipient !== subj && this._continuityTracks(subj).length) throw new ContinuityRefusalError("redirect-blocked:w4-disagreement", `${subj} was resolved to ${recipient}, which the continuity evidence does not show; nothing was sent`, { queried: subj, to: recipient }); // @rule C-route-knock-rewrite-tracked
320
339
  let w4 = { direct: true }, effTo = recipient;
321
- w4 = await this._w4Gate(recipient, { registryUrl: registryUrl ?? this.registryUrl, recipientPublicKey, confirmRecovered, now: now ?? effTs, urlMap, allowInsecureLoopback, fetch: fetchOverride }); // @rule W-send-w4-knock-gate
340
+ if (!cr.fields.redirectedTo) w4 = await this._w4Gate(recipient, { registryUrl: registryUrl ?? this.registryUrl, recipientPublicKey, confirmRecovered, now: now ?? effTs, urlMap, allowInsecureLoopback, fetch: fetchOverride }); // @rule W-send-w4-knock-gate
322
341
  if (!w4.direct) effTo = w4.target; // @rule W-send-w4-knock-target
342
+ if (!w4.direct && this._continuityTracks(subj).length) throw new ContinuityRefusalError("redirect-blocked:w4-disagreement", `the registry redirects ${subj} to ${w4.target}, which the continuity evidence does not show; nothing was sent`, { queried: subj, to: w4.target });
323
343
  const payload = buildKnock({
324
344
  from: this.uuaid,
325
345
  to: effTo,
@@ -330,7 +350,8 @@ export class Pillar {
330
350
  ts: effTs,
331
351
  });
332
352
  const effPub = !w4.direct ? w4.publicKey : (recipientPublicKey ?? w4.publicKey);
333
- const sent = await this.send({ recipient: effTo, recipientPublicKey: effPub, kind: "knock", payload, resolveTimeoutMs, registryUrl: effPub ? null : (registryUrl ?? this.registryUrl), confirmRecovered, now: now ?? effTs, urlMap, allowInsecureLoopback, fetch: fetchOverride });
353
+ const sent = await this.send({ recipient: effTo, recipientPublicKey: effPub, subject: subj, routeFp: cr.fp, kind: "knock", payload, resolveTimeoutMs, registryUrl: effPub ? null : (registryUrl ?? this.registryUrl), confirmRecovered, now: now ?? effTs, urlMap, allowInsecureLoopback, fetch: fetchOverride });
354
+ if (cr.fields.redirectedTo) return { ...sent, ...cr.fields };
334
355
  return w4.record ? { ...sent, redirectedFrom: recipient, redirectedTo: w4.target } : sent;
335
356
  }
336
357
 
@@ -360,6 +381,10 @@ export class Pillar {
360
381
  const knockerUuaid = knockEnv.sender;
361
382
  const knockerPublicKey = knockPayload?.card?.publicKey;
362
383
  if (!knockerPublicKey) throw new Error(`answerKnock: knock ${knockId} carries no card publicKey`);
384
+ await this._drainNoticeBacklog();
385
+ let kr = { fields: {} };
386
+ kr = this._applyRoute(knockerUuaid, knockerPublicKey, now); // @rule C-route-knock-answer
387
+ if (kr.fields.redirectedTo) throw new ContinuityRefusalError("redirect-blocked:knocker-retired", `the knocker ${knockerUuaid} is a retired key of ${kr.recipient}; answer the current key`, { queried: knockerUuaid, to: kr.recipient });
363
388
 
364
389
  const answerNow = now ?? this._knockNow();
365
390
  const answerCard = card ?? this.knockConfig?.card;
@@ -390,6 +415,7 @@ export class Pillar {
390
415
 
391
416
  let sent;
392
417
  if (sealOnly || (!this.node && !this.carrierClient)) {
418
+ this._recheckRoute(knockerUuaid, kr.fp, knockerUuaid, now); // @rule C-route-knock-answer-recheck
393
419
  const envelope = seal(this.keychain, {
394
420
  recipient: knockerUuaid,
395
421
  recipientPublicKey: knockerPublicKey,
@@ -423,6 +449,435 @@ export class Pillar {
423
449
  };
424
450
  }
425
451
 
452
+ // ── continuity (2.8.0 Track B) ─────────────────────────────────────────────
453
+
454
+ _continuityNow() {
455
+ const n = this.continuityOpts.now;
456
+ return typeof n === "function" ? n() : (typeof n === "string" ? n : nowIsoSeconds());
457
+ }
458
+
459
+ /** The home's continuity store, or null when this Pillar has no home (an in-memory mailbox). */
460
+ _continuityStore() {
461
+ if (!this._continuityHome) return null;
462
+ this._cstore ??= new ContinuityStore(this._continuityHome);
463
+ return this._cstore;
464
+ }
465
+
466
+ /**
467
+ * The stored state, re-read only when the store's files change (their
468
+ * version stamp), with a per-version cache of decisions and a key index.
469
+ * A read or custody error throws: it is never taken as "no state" (RedTeam b5cbee P1).
470
+ */
471
+ _continuityView() {
472
+ const st = this._continuityStore();
473
+ if (!st) return null;
474
+ const version = st.version();
475
+ if (this._cview?.version !== version) {
476
+ const state = st.read();
477
+ const index = new Map();
478
+ for (const [lin, rec] of Object.entries(state.lineages ?? {})) for (const k of keysOf(rec.events ?? []).keys()) index.set(k, [...(index.get(k) ?? []), lin]);
479
+ for (const [from, rec] of Object.entries(state.successors ?? {})) for (const k of [from, ...keysOf(rec.events ?? []).keys()]) index.set(k, [...(index.get(k) ?? []), rec.lineage]);
480
+ this._cview = { version, state, index, cache: new Map() };
481
+ }
482
+ return this._cview;
483
+ }
484
+
485
+ /** The one route decision for `queried` (DESIGN-continuity §2.4, §3): every send path reads it. */
486
+ continuityDecision(queried, { now = null } = {}) {
487
+ const view = this._continuityView();
488
+ if (!view) return { state: "none" };
489
+ const n = now ?? this._continuityNow();
490
+ const key = `${queried}|${Math.floor(Date.parse(n) / 60_000)}`;
491
+ let d = view.cache.get(key);
492
+ if (!d) {
493
+ d = decideFor(view.state, queried, n);
494
+ if (view.cache.size < 4096) view.cache.set(key, d);
495
+ }
496
+ return d;
497
+ }
498
+
499
+ /**
500
+ * Right before sealing (RedTeam b5cbee P1): the subject's decision must be
501
+ * the one the send started from, and the key being sealed to must be
502
+ * current. Anything else is drift: refused, nothing sealed.
503
+ */
504
+ _recheckRoute(subject, fp, recipient, now = null) {
505
+ let d = this.continuityDecision(subject, { now });
506
+ if (decisionFingerprint(d) !== fp) throw new ContinuityRefusalError("redirect-blocked:route-changed", `the continuity decision for ${subject} changed while the send was being prepared (${d.state}); nothing was sent`, { queried: subject, ...d }); // @rule C-route-recheck-subject
507
+ if (recipient !== subject) {
508
+ d = this.continuityDecision(recipient, { now });
509
+ if (d.state !== "none") throw new ContinuityRefusalError(`redirect-blocked:destination-${d.state}`, `the destination ${recipient} is itself ${d.state}; nothing was sent`, { queried: recipient, ...d }); // @rule C-route-recheck-destination
510
+ }
511
+ }
512
+
513
+ /**
514
+ * Apply the decision to one send. none: unchanged. active: the destination
515
+ * and its key replace the retired key. pending-confirm: held (B2).
516
+ * suspended: refused. Throws ContinuityRefusalError.
517
+ */
518
+ _applyRoute(recipient, recipientPublicKey, now = null) {
519
+ const d = this.continuityDecision(recipient, { now });
520
+ const fp = decisionFingerprint(d);
521
+ if (d.state === "none") return { recipient, recipientPublicKey, fields: {}, fp };
522
+ if (d.state === "active") {
523
+ this.metrics.inc("continuity.route.active");
524
+ return { recipient: d.to, recipientPublicKey: d.toKey, fields: { redirectedFrom: recipient, redirectedTo: d.to, continuity: d.via }, fp };
525
+ }
526
+ this.metrics.inc(`continuity.route.${d.state}`);
527
+ if (d.state === "pending-confirm") throw new ContinuityRefusalError("continuity-held", `${recipient} retired in favour of ${d.to} (head ${d.head}); the send is held until you confirm it`, d); // @rule C-route-held
528
+ throw new ContinuityRefusalError(`redirect-blocked:${d.reason}`, `${recipient} is suspended (${d.reason}); nothing was sent`, d); // @rule C-route-suspended
529
+ }
530
+
531
+ /** Lineages whose stored evidence names `uuaid` as a key. */
532
+ _continuityTracks(uuaid) {
533
+ const view = this._continuityView();
534
+ if (!view) return [];
535
+ return Object.entries(view.state.lineages).filter(([, rec]) => keysOf(rec.events).has(uuaid)).map(([lin]) => lin);
536
+ }
537
+
538
+ /** Contacts that may make a notice worth verifying: address book, trust allow. */
539
+ _continuityContacts() {
540
+ return new Set([...(this.addressBook?.keys() ?? []), ...(this.trust?.allow ?? [])]);
541
+ }
542
+
543
+ /**
544
+ * A received `lineage` / `lineage.successor` envelope: evidence only. Never
545
+ * throws; never changes a route by itself (the decision reads the store).
546
+ * `seq` is its inbox row. When a notice backlog exists, earlier waiting rows
547
+ * that can now run are ingested first in arrival order; a notice refused for
548
+ * budget or lock is recorded in the backlog (RedTeam 5402b7), so it takes
549
+ * effect once the budget allows with no resend, while envelope-authenticated
550
+ * known contacts can still use their reserved quota immediately.
551
+ */
552
+ async _continuityIngest(envelope, payload, openVerdict, rawBytes, seq = null, { duplicate = false } = {}) {
553
+ try {
554
+ if (this.trust?.block?.includes(envelope.sender)) return null;
555
+ const st = this._continuityStore();
556
+ const state0 = st ? st.read() : null;
557
+ const b = state0?.backlog ?? null;
558
+ const def0 = st && b ? st.readDeferred() : null;
559
+ let trustedArrival = false;
560
+ if (state0) trustedArrival = classifyTrustedNotice(state0, envelope.kind, payload, this._continuityCtx(envelope, openVerdict, rawBytes, this._continuityNow())) !== null; // @rule C-trusted-bypass-open
561
+ const olderCompletedDup = Boolean(
562
+ duplicate && b && Number.isSafeInteger(seq) && seq <= b.from
563
+ && !(b.extra ?? []).includes(seq) && !(b.trusted ?? []).includes(seq)
564
+ && !(def0?.open ?? []).includes(seq) && !(def0?.trusted ?? []).includes(seq)
565
+ && (def0?.repairTo == null || seq <= (def0.repairedThrough ?? 0))
566
+ );
567
+ if (Number.isSafeInteger(seq) && b && !olderCompletedDup) {
568
+ if (trustedArrival) {
569
+ if ((b.trusted?.length ?? 0) > 0 || (def0?.trusted?.length ?? 0) > 0) await this._continuityRetry({ trustedOnly: true, preIngest: true });
570
+ } else {
571
+ await this._continuityRetry({ preIngest: true }); // @rule C-backlog-join
572
+ }
573
+ }
574
+ const r = await this._continuityIngestNow(envelope, payload, openVerdict, rawBytes);
575
+ let waitReason = r?.reason === "receiver-budget" || r?.reason === "continuity-locked";
576
+ waitReason = waitReason || r?.reason === "budget"; // @rule C-backlog-sender-budget
577
+ if (r && waitReason && Number.isSafeInteger(seq) && st) {
578
+ noteBacklog(st, { seq, duplicate, trusted: r.trusted === true || trustedArrival, tailSeq: this.mailbox.inboxTipSeq(), now: this._continuityNow() }); // @rule C-backlog-start
579
+ if (this._retryGate && r.reason !== "continuity-locked") {
580
+ this._retryGate.tipSeq = this.mailbox.inboxTipSeq();
581
+ this._retryGate.storeVersion = st.version();
582
+ this._retryGate.budgetFp = st.budgetVersion();
583
+ this._retryGate.memSenders = this._continuityBudget?.map?.size ?? 0;
584
+ }
585
+ }
586
+ return r;
587
+ } catch (e) {
588
+ this.metrics.inc("continuity.notice.error");
589
+ // eslint-disable-next-line no-console
590
+ console.warn(`pillar: continuity notice ${envelope.id} from ${envelope.sender} not processed: ${e.message}`);
591
+ return null;
592
+ }
593
+ }
594
+
595
+ _continuityCtx(envelope, openVerdict, rawBytes, now, extra = {}) {
596
+ const senderVerified = openVerdict?.ok === true && openVerdict?.delegated !== true;
597
+ return {
598
+ sender: envelope.sender,
599
+ senderVerified,
600
+ senderPublicKey: senderVerified && typeof envelope?.transportSignature?.publicKey === "string" ? envelope.transportSignature.publicKey : null,
601
+ delegated: openVerdict?.delegated === true,
602
+ bytes: rawBytes,
603
+ contacts: this._continuityContacts(),
604
+ now,
605
+ budget: this._continuityBudget,
606
+ ...extra,
607
+ };
608
+ }
609
+
610
+ /** Verify and store one notice now; home checks for a firm lineage it touched. Throws only for a store that cannot be used. */
611
+ async _continuityIngestNow(envelope, payload, openVerdict, rawBytes, ctxExtra = {}) {
612
+ const st = this._continuityStore();
613
+ const now = this._continuityNow();
614
+ let r;
615
+ try { r = ingestNotice(st, envelope.kind, payload, this._continuityCtx(envelope, openVerdict, rawBytes, now, ctxExtra)); }
616
+ catch (e) { if (e?.code === "continuity-locked") return { stored: false, reason: "continuity-locked" }; throw e; }
617
+ this.metrics.inc(r.stored ? "continuity.notice.stored" : `continuity.notice.dropped.${r.reason}`);
618
+ if (r.stored) {
619
+ // The lineage itself, or for a successor every predecessor lineage that names `from`: one home check each.
620
+ const state = st.read();
621
+ const lins = envelope.kind === "lineage" ? [r.lineage] : Object.entries(state.lineages).filter(([, rec]) => keysOf(rec.events).has(payload?.from)).map(([lin]) => lin);
622
+ const o = this.continuityOpts;
623
+ for (const lin of lins) {
624
+ if (state.lineages[lin]?.pin?.firm !== true) continue;
625
+ await checkHomes(st, lin, { now, fetch: o.fetch ?? globalThis.fetch, urlMap: o.urlMap, allowInsecureLoopback: o.allowInsecureLoopback === true });
626
+ }
627
+ }
628
+ return r;
629
+ }
630
+
631
+ /** Before any send path decides a route, drain waiting notices if the budget now allows. */
632
+ async _drainNoticeBacklog() {
633
+ if (this._continuityView()?.state?.backlog) await this._continuityRetry(); // @rule C-backlog-send
634
+ }
635
+
636
+ _canSkipRetry(st, nowMs, { ignoreTip = false } = {}) {
637
+ const g = this._retryGate;
638
+ if (!g || !Number.isFinite(nowMs)) return false;
639
+ return nowMs >= g.atMs && nowMs < g.nextFreeMs
640
+ && (ignoreTip || this.mailbox.inboxTipSeq() === g.tipSeq)
641
+ && st.version() === g.storeVersion
642
+ && st.budgetVersion() === g.budgetFp
643
+ && (this._continuityBudget?.map?.size ?? 0) === g.memSenders;
644
+ }
645
+
646
+ _armRetryGate(st, nowMs) {
647
+ const nextFreeMs = st.nextBudgetUnlockMs(nowMs, this._continuityBudget);
648
+ if (!Number.isFinite(nextFreeMs) || nextFreeMs <= nowMs) { this._retryGate = null; return; }
649
+ this._retryGate = {
650
+ atMs: nowMs,
651
+ nextFreeMs,
652
+ tipSeq: this.mailbox.inboxTipSeq(),
653
+ storeVersion: st.version(),
654
+ budgetFp: st.budgetVersion(),
655
+ memSenders: this._continuityBudget?.map?.size ?? 0,
656
+ };
657
+ }
658
+
659
+ /**
660
+ * Work through the notice backlog (RedTeam 5402b7, a97f59, 65c007):
661
+ * - Lane 1 (trusted): drains `backlog.trusted` + `deferred.trusted` first via
662
+ * direct `inboxAtSeqs` lookup, independent of the open scan;
663
+ * - Lane 2 (unproven/open): drains `extra` + `deferred.open` via batched
664
+ * `inboxAtSeqs`, runs a one-time monotonic repair scan if `deferred` ever
665
+ * overflowed, and advances `inboxSince(from)` in arrival order.
666
+ */
667
+ async _continuityRetry({ maxRows = 4096, preIngest = false, trustedOnly = false } = {}) {
668
+ if (this._continuityRetrying) return this._continuityRetrying;
669
+ const run = (async () => {
670
+ try {
671
+ const st = this._continuityStore();
672
+ if (!st) return;
673
+ const b0 = st.read().backlog;
674
+ if (!b0) { this._retryGate = null; return; }
675
+ const nowMs = Date.parse(this._continuityNow());
676
+ if (this._canSkipRetry(st, nowMs, { ignoreTip: preIngest })) return; // @rule C-backlog-coalesce
677
+ let sawLock = false, hitCap = false;
678
+
679
+ let runTrusted = false;
680
+ runTrusted = true; // @rule C-trusted-lane-drain
681
+ if (runTrusted) {
682
+ const defT = st.readDeferred();
683
+ const tSeqs = [...new Set([...(b0.trusted ?? []), ...defT.trusted])].sort((a, c) => a - c);
684
+ if (tSeqs.length > 0) {
685
+ const bySeq = new Map(this.mailbox.inboxAtSeqs(tSeqs).map((r) => [r.seq, r]));
686
+ const doneTrusted = [];
687
+ for (const s of tSeqs) {
688
+ const row = bySeq.get(s);
689
+ if (row) {
690
+ const out = await this._continuityRetryRow(row);
691
+ if (out === "wait-lock" || out === "wait-all") { if (out === "wait-lock") sawLock = true; break; }
692
+ if (out === "wait-sender") continue;
693
+ }
694
+ doneTrusted.push(s);
695
+ }
696
+ if (doneTrusted.length > 0) advanceBacklog(st, { doneTrusted });
697
+ }
698
+ }
699
+ if (trustedOnly) return;
700
+
701
+ let scanned = 0;
702
+ while (!sawLock && scanned < maxRows) {
703
+ const b1 = st.read().backlog;
704
+ const def1 = st.readDeferred();
705
+ const openSeqs = [...new Set([...(b1?.extra ?? []), ...def1.open])].sort((a, c) => a - c);
706
+ if (openSeqs.length === 0) break;
707
+ const batchSeqs = openSeqs.slice(0, Math.min(256, maxRows - scanned));
708
+ let batchRows = [];
709
+ batchRows = this.mailbox.inboxAtSeqs(batchSeqs); // @rule C-backlog-deferred-batch
710
+ const bySeq = new Map(batchRows.map((r) => [r.seq, r]));
711
+ const doneExtra = [];
712
+ let stopExtra = false;
713
+ for (const s of batchSeqs) {
714
+ scanned++;
715
+ const row = bySeq.get(s);
716
+ if (row) {
717
+ const out = await this._continuityRetryRow(row);
718
+ if (out === "wait-lock" || out === "wait-all") { if (out === "wait-lock") sawLock = true; stopExtra = true; break; }
719
+ if (out === "wait-sender") continue;
720
+ }
721
+ doneExtra.push(s);
722
+ }
723
+ if (doneExtra.length > 0) advanceBacklog(st, { doneExtra });
724
+ if (stopExtra) {
725
+ if (!sawLock && !hitCap && st.read().backlog) this._armRetryGate(st, nowMs);
726
+ return;
727
+ }
728
+ if (doneExtra.length === 0) break;
729
+ if (scanned >= maxRows && ((st.read().backlog?.extra?.length ?? 0) > 0 || st.readDeferred().open.length > 0)) hitCap = true;
730
+ }
731
+
732
+ while (!sawLock && scanned < maxRows) {
733
+ const defR = st.readDeferred();
734
+ if (defR.repairTo === null) break;
735
+ if (defR.repairedThrough >= defR.repairTo) { advanceBacklog(st, { clearRepair: true }); break; }
736
+ const rows = this.mailbox.inboxSince(defR.repairedThrough, Math.min(128, maxRows - scanned));
737
+ const inRange = rows.filter((r) => r.seq <= defR.repairTo);
738
+ if (inRange.length === 0) {
739
+ advanceBacklog(st, { repairedThrough: defR.repairTo, clearRepair: true });
740
+ break;
741
+ }
742
+ let repCursor = defR.repairedThrough;
743
+ const addExtra = [];
744
+ let stopRep = false;
745
+ for (const row of inRange) {
746
+ scanned++;
747
+ const out = await this._continuityRetryRow(row);
748
+ if (out === "wait-lock" || out === "wait-all") { if (out === "wait-lock") sawLock = true; stopRep = true; break; }
749
+ if (out === "wait-sender") addExtra.push(row.seq);
750
+ repCursor = row.seq;
751
+ }
752
+ const doneRep = !stopRep && (repCursor >= defR.repairTo || rows.length > inRange.length);
753
+ advanceBacklog(st, { repairedThrough: doneRep ? Math.max(repCursor, defR.repairTo) : repCursor, addExtra, clearRepair: doneRep });
754
+ if (stopRep) {
755
+ if (!sawLock && !hitCap && st.read().backlog) this._armRetryGate(st, nowMs);
756
+ return;
757
+ }
758
+ if (scanned >= maxRows && st.readDeferred().repairTo !== null) hitCap = true;
759
+ }
760
+
761
+ let lastFrom = -1;
762
+ while (!sawLock && scanned < maxRows) {
763
+ const b = st.read().backlog;
764
+ if (!b) { this._retryGate = null; return; }
765
+ if (b.from === lastFrom) break;
766
+ lastFrom = b.from;
767
+ const rows = this.mailbox.inboxSince(b.from, Math.min(128, maxRows - scanned));
768
+ if (rows.length === 0) {
769
+ clearBacklog(st, b.from, () => this.mailbox.inboxSince(b.from, 1).length > 0); // @rule C-backlog-clear
770
+ break;
771
+ }
772
+ let cursor = b.from;
773
+ const addExtra = [];
774
+ const doneExtra = [];
775
+ const extraSet = new Set(b.extra ?? []);
776
+ let stopped = false;
777
+ for (const row of rows) {
778
+ scanned++;
779
+ const out = await this._continuityRetryRow(row);
780
+ if (out === "wait-lock" || out === "wait-all") {
781
+ if (out === "wait-lock") sawLock = true;
782
+ stopped = true;
783
+ break;
784
+ }
785
+ if (out === "wait-sender") addExtra.push(row.seq);
786
+ else if (extraSet.has(row.seq)) doneExtra.push(row.seq);
787
+ cursor = row.seq;
788
+ }
789
+ if (cursor > b.from || addExtra.length || doneExtra.length) advanceBacklog(st, { toSeq: cursor, addExtra, doneExtra }); // @rule C-backlog-advance
790
+ if (stopped) break;
791
+ if (scanned >= maxRows && this.mailbox.inboxSince(cursor, 1).length > 0) hitCap = true;
792
+ }
793
+ const bEnd = st.read().backlog;
794
+ if (!bEnd) this._retryGate = null;
795
+ else if (!sawLock && !hitCap) this._armRetryGate(st, nowMs);
796
+ else this._retryGate = null;
797
+ } catch (_e) {
798
+ this.metrics.inc("continuity.backlog.error");
799
+ }
800
+ })();
801
+ this._continuityRetrying = run;
802
+ try {
803
+ return await run;
804
+ } finally {
805
+ if (this._continuityRetrying === run) this._continuityRetrying = null;
806
+ }
807
+ }
808
+
809
+ /** One backlog row: "wait-all" | "wait-sender" | "wait-lock" | "done". */
810
+ async _continuityRetryRow(row) {
811
+ const raw = typeof row?.envelope_json === "string" ? row.envelope_json : "";
812
+ if (!raw || raw.length > MAX_NOTICE_BYTES) return "done"; // not a notice the store could take
813
+ let envelope;
814
+ try { envelope = JSON.parse(raw); } catch { return "done"; }
815
+ if (!isContinuityKind(envelope?.kind) || envelope.recipient !== this.uuaid) return "done";
816
+ const verdict = open(envelope, { cryptoInventory: this.cryptoInventory });
817
+ if (!verdict.ok) return "done";
818
+ let payload;
819
+ try { payload = decrypt(this.keychain, envelope); } catch { return "done"; }
820
+ if (this.trust?.block?.includes(envelope.sender)) return "done";
821
+ const r = await this._continuityIngestNow(envelope, payload, verdict, Buffer.byteLength(raw));
822
+ let waitKind = null;
823
+ if (r?.reason === "continuity-locked") waitKind = "wait-lock";
824
+ else if (r?.reason === "budget") waitKind = "wait-sender";
825
+ if (r?.reason === "receiver-budget") waitKind = "wait-all"; // @rule C-backlog-wait
826
+ return waitKind ?? "done";
827
+ }
828
+
829
+ /**
830
+ * Start one import run. It stops when every caller waiting on it has aborted;
831
+ * a caller without a signal (the periodic import) waits to the end, so another
832
+ * caller's abort never stops it.
833
+ */
834
+ _startImport({ now = null, runMs } = {}) {
835
+ const ctl = new AbortController();
836
+ const run = { ctl, waiting: 0, done: null };
837
+ this._importRun = run;
838
+ run.done = (async () => {
839
+ try {
840
+ this.lastImport = await importRetiredMail(this, {
841
+ now: now ?? this._continuityNow(),
842
+ passphrase: this.continuityOpts.passphrase ?? process.env.PILLAR_PASSPHRASE ?? "",
843
+ signal: ctl.signal,
844
+ ...(runMs !== undefined ? { runMs } : {}),
845
+ });
846
+ } catch (e) {
847
+ this.metrics.inc("continuity.import.error");
848
+ this.lastImport = { imported: 0, rejected: 0, keys: 0, errors: [{ error: e.message }] };
849
+ } finally {
850
+ if (this._importRun === run) this._importRun = null;
851
+ }
852
+ return this.lastImport;
853
+ })();
854
+ return run;
855
+ }
856
+
857
+ /**
858
+ * Pull retired inboxes inside their grace window (B-1). Best effort: errors
859
+ * are counted, never thrown. One run at a time per Pillar; a run is bounded
860
+ * in pages and time and stops on `signal` (RedTeam b5cbee P2).
861
+ */
862
+ importRetired({ now = null, signal = null, runMs } = {}) {
863
+ const aborted = () => ({ imported: 0, rejected: 0, keys: 0, errors: [{ error: "aborted" }] });
864
+ if (signal?.aborted) return Promise.resolve(aborted());
865
+ let run = null;
866
+ run = this._importRun; // @rule C-import-single-flight
867
+ run ??= this._startImport({ now, runMs });
868
+ run.waiting++;
869
+ if (!signal) return run.done;
870
+ // Each caller's wait ends on its own signal (RedTeam 1c5e7a P2), whoever started the run.
871
+ return new Promise((resolve) => {
872
+ const leave = () => {
873
+ resolve(aborted());
874
+ if (--run.waiting === 0) run.ctl.abort();
875
+ };
876
+ signal.addEventListener("abort", leave, { once: true }); // @rule C-import-caller-abort
877
+ run.done.then((r) => { signal.removeEventListener("abort", leave); resolve(r); });
878
+ });
879
+ }
880
+
426
881
  /**
427
882
  * Send a signed envelope. Resolution order:
428
883
  * 1. Address book: if `this.addressBook.get(recipient)` returns {peerId, multiaddr},
@@ -460,15 +915,35 @@ export class Pillar {
460
915
  return { direct: true, publicKey: pubKey, carrier: res.card?.carriers?.[0] };
461
916
  }
462
917
 
463
- async send({ recipient, recipientPublicKey, kind = "message", payload = {}, envelopeId = null, resolveTimeoutMs = 5000, registryUrl = null, confirmRecovered = false, now = null, urlMap = undefined, allowInsecureLoopback = false, fetch: fetchOverride = undefined }) {
918
+ async send({ recipient, recipientPublicKey, subject = null, routeFp = null, kind = "message", payload = {}, envelopeId = null, resolveTimeoutMs = 5000, registryUrl = null, confirmRecovered = false, now = null, urlMap = undefined, allowInsecureLoopback = false, fetch: fetchOverride = undefined }) {
464
919
  if (!this.node && !this.carrierClient) {
465
920
  this.metrics.inc("send.error.not-started");
466
921
  throw new Error("pillar not started");
467
922
  }
468
923
  const t0 = Date.now();
469
924
  let w4 = { direct: true }, w4Fields = {};
470
- w4 = await this._w4Gate(recipient, { registryUrl: registryUrl ?? this.registryUrl, recipientPublicKey, confirmRecovered, now, urlMap, allowInsecureLoopback, fetch: fetchOverride }); // @rule W-send-w4-gate
471
- if (w4.record) w4Fields = { redirectedFrom: recipient, redirectedTo: w4.target }; // @rule W-send-w4-report
925
+ // `subject`: the identity a wrapper (sendKnock, sendBlob) was asked to reach before it chose `recipient`.
926
+ const subj = subject ?? recipient;
927
+ await this._drainNoticeBacklog();
928
+ let cr = { recipient, recipientPublicKey, fields: {}, fp: null };
929
+ cr = this._applyRoute(subj, recipientPublicKey, now); // @rule C-route-send
930
+ if (routeFp !== null && cr.fp !== routeFp) throw new ContinuityRefusalError("redirect-blocked:route-changed", `the continuity decision for ${subj} changed while the send was being prepared; nothing was sent`, { queried: subj }); // @rule C-route-wrapper-drift
931
+ if (subj !== recipient) {
932
+ if (cr.fields.redirectedTo && cr.recipient !== recipient) throw new ContinuityRefusalError("redirect-blocked:route-changed", `${subj} routes to ${cr.recipient}, not to ${recipient}; nothing was sent`, { queried: subj, to: cr.recipient });
933
+ w4Fields = cr.fields;
934
+ } else if (cr.fields.redirectedTo) {
935
+ ({ recipient, recipientPublicKey } = cr);
936
+ w4Fields = cr.fields;
937
+ } else {
938
+ const queried = recipient;
939
+ w4 = await this._w4Gate(recipient, { registryUrl: registryUrl ?? this.registryUrl, recipientPublicKey, confirmRecovered, now, urlMap, allowInsecureLoopback, fetch: fetchOverride }); // @rule W-send-w4-gate
940
+ if (w4.record) w4Fields = { redirectedFrom: recipient, redirectedTo: w4.target }; // @rule W-send-w4-report
941
+ const tracked = w4.record ? this._continuityTracks(queried) : [];
942
+ if (tracked.length) { // the registry names another current for a key our evidence holds current
943
+ for (const lineage of tracked) recordW4(this._continuityStore(), { lineage, queried, current: w4.target, now: this._continuityNow() });
944
+ throw new ContinuityRefusalError("redirect-blocked:w4-disagreement", `the registry redirects ${queried} to ${w4.target}, which the continuity evidence does not show; nothing was sent`, { queried, to: w4.target }); // @rule C-route-w4-disagreement
945
+ }
946
+ }
472
947
  if (!w4.direct) {
473
948
  recipient = w4.target; // @rule W-send-w4-redirect-target
474
949
  recipientPublicKey = w4.publicKey;
@@ -494,6 +969,7 @@ export class Pillar {
494
969
  throw new Error(`send: no public key known for ${recipient} — encryption is mandatory; register the peer (address book / fleet.json) or pass recipientPublicKey`);
495
970
  }
496
971
 
972
+ this._recheckRoute(subj, cr.fp, recipient, now); // nothing above awaited may change the route unseen
497
973
  const envelope = seal(this.keychain, { recipient, recipientPublicKey: pubkey, kind, payload, id: envelopeId ?? undefined });
498
974
  const hardCap = preflightBodyBytes(envelopeBodyBytes(envelope), { maxBodyBytes: MAX_INLINE_BODY_BYTES });
499
975
  if (!hardCap.ok) {
@@ -683,6 +1159,11 @@ export class Pillar {
683
1159
  */
684
1160
  async sendBlob({ recipient, recipientPublicKey, kind = BLOB_KIND, data, ttlMs, resolveTimeoutMs = 5000 }) {
685
1161
  if (!this.blobClient && !this.blobStore) throw new BlobError("no-store", "sendBlob: configure blobClient or blobStore on the Pillar");
1162
+ const subject = recipient;
1163
+ await this._drainNoticeBacklog();
1164
+ const route = this._applyRoute(recipient, recipientPublicKey); // @rule C-route-blob
1165
+ ({ recipient, recipientPublicKey } = route);
1166
+ this._recheckRoute(subject, route.fp, recipient); // @rule C-route-blob-recheck
686
1167
  const buf = Buffer.isBuffer(data) ? data : Buffer.from(data);
687
1168
  // Reserve an envelope id so the blob ciphertext is AAD-bound to it.
688
1169
  const envelopeId = mkEnvelopeId();
@@ -702,7 +1183,7 @@ export class Pillar {
702
1183
  store: this.blobStore, broker: this.blobBroker,
703
1184
  });
704
1185
  const r = await this.send({
705
- recipient, recipientPublicKey, kind,
1186
+ recipient, recipientPublicKey, kind, subject, routeFp: route.fp,
706
1187
  payload: { blobRef: prepared.ref }, envelopeId, resolveTimeoutMs,
707
1188
  });
708
1189
  this.metrics.inc("sendBlob.ok");
@@ -751,10 +1232,23 @@ export class Pillar {
751
1232
  this.metrics.inc(`carrier.poll.error.${meta?.carrier ?? "unknown"}`);
752
1233
  },
753
1234
  });
1235
+ // Retired inboxes (B-1) and the notice backlog: every IMPORT_PERIOD_MS, never a long-poll.
1236
+ if (!this._importTimer) {
1237
+ this._importTimer = setInterval(() => { this._periodicContinuity(); }, IMPORT_PERIOD_MS);
1238
+ this._importTimer.unref?.();
1239
+ this._periodicContinuity();
1240
+ }
754
1241
  return this._carrierPoller;
755
1242
  }
756
1243
 
1244
+ /** Each import period: retired inboxes, then the notice backlog. Never throws. */
1245
+ _periodicContinuity() {
1246
+ this.importRetired();
1247
+ this._continuityRetry(); // @rule C-backlog-periodic
1248
+ }
1249
+
757
1250
  stopCarrierPolling() {
1251
+ if (this._importTimer) { clearInterval(this._importTimer); this._importTimer = null; }
758
1252
  if (this._carrierPoller) {
759
1253
  this._carrierStopping = this._carrierPoller.stop();
760
1254
  this._carrierPoller = null;
@@ -822,6 +1316,8 @@ export class Pillar {
822
1316
  this.metrics.inc(`carrier.drain.error.${base}`);
823
1317
  }
824
1318
  }
1319
+ if (!signal?.aborted) await this.importRetired({ signal, runMs: 10_000 }); // B-1: retired inboxes in their grace window; bounded, cancellable, never throws
1320
+ if (!signal?.aborted) await this._continuityRetry(); // @rule C-backlog-drain
825
1321
  if (!errors.length) return total;
826
1322
  const first = errors[0].error;
827
1323
  const reusable = first !== null && typeof first === "object" && Object.isExtensible(first)
@@ -878,9 +1374,16 @@ export class Pillar {
878
1374
  * connection info out of band.
879
1375
  */
880
1376
  async sendDirect({ recipient, recipientPublicKey, recipientPeerIdStr, recipientMultiaddr, kind = "message", payload = {} }) {
1377
+ const subject = recipient;
1378
+ await this._drainNoticeBacklog();
1379
+ const cr = this._applyRoute(subject, recipientPublicKey); // @rule C-route-direct
1380
+ // The peer id and address name the subject's host. A rewritten destination has no coordinates this
1381
+ // call can verify, so a redirect is refused before anything is sealed (RedTeam 1c5e7a P1).
1382
+ if (cr.fields.redirectedTo) throw new ContinuityRefusalError("redirect-blocked:direct-redirect", `${subject} retired in favour of ${cr.recipient}; the peer id and address given are the retired key's, so nothing was sealed`, { queried: subject, to: cr.recipient, via: cr.fields.continuity }); // @rule C-route-direct-redirect
881
1383
  if (!this.node) throw new Error("pillar not started");
882
1384
  const pubkey = recipientPublicKey ?? this.addressBook?.get(recipient)?.publicKey;
883
1385
  if (!pubkey) throw new Error(`sendDirect: no public key for ${recipient} — encryption is mandatory`);
1386
+ this._recheckRoute(subject, cr.fp, recipient); // @rule C-route-direct-recheck
884
1387
  const envelope = seal(this.keychain, { recipient, recipientPublicKey: pubkey, kind, payload });
885
1388
  const bytes = envelopeBodyBytes(envelope);
886
1389
  if (bytes > MAX_INLINE_BODY_BYTES) {
@@ -1109,7 +1612,30 @@ export class Pillar {
1109
1612
  }
1110
1613
  if (!this.trust) return { deliver: true };
1111
1614
  if (answersOurSend(this.mailbox, envelope, payload)) return { deliver: true };
1112
- return evaluateTrust(this.trust, envelope.sender, new Set(this.addressBook?.keys() ?? []), { kind: envelope.kind });
1615
+ const known = new Set(this.addressBook?.keys() ?? []);
1616
+ let view = null;
1617
+ try { view = this._continuityView(); } catch { this.metrics.inc("continuity.store.unreadable"); } // an unreadable store moves no allow or block (2.7.1 behaviour); sends refuse with the repair hint
1618
+ // Ordinary mail from a key no stored lineage names costs one map lookup (RedTeam b5cbee ruling 2).
1619
+ if (view && !view.index.has(envelope.sender)) view = null; // a fast path only: no lineage names the sender
1620
+ let aliases = null;
1621
+ if (view) {
1622
+ const key = `aliases|${envelope.sender}|${Math.floor(Date.parse(this._continuityNow()) / 60_000)}`;
1623
+ aliases = view.cache.get(key);
1624
+ if (!aliases) {
1625
+ // Only keys this policy could deliver for (allow list, address book) can carry a sender in (V1 1e74da).
1626
+ const only = new Set([...(this.trust.allow ?? []), ...known]);
1627
+ aliases = { block: blockAliases(view.state, envelope.sender), allow: allowAliases(view.state, envelope.sender, this._continuityNow(), { only }) };
1628
+ if (view.cache.size < 4096) view.cache.set(key, aliases);
1629
+ }
1630
+ }
1631
+ if (aliases && aliases.block.some((k) => this.trust.block?.includes(k))) return { deliver: false, reason: "blocked" }; // @rule C-trust-block-moves
1632
+ const own = evaluateTrust(this.trust, envelope.sender, known, { kind: envelope.kind });
1633
+ if (own.deliver || !aliases || own.reason === "blocked") return own;
1634
+ for (const alias of aliases.allow) {
1635
+ const v = evaluateTrust(this.trust, alias, known, { kind: envelope.kind });
1636
+ if (v.deliver) return v; // @rule C-trust-allow-moves
1637
+ }
1638
+ return own;
1113
1639
  }
1114
1640
 
1115
1641
  /**
@@ -1311,7 +1837,9 @@ export class Pillar {
1311
1837
  continue;
1312
1838
  }
1313
1839
  dead.delete(base);
1314
- if (pageInfo && r.envelopes.length >= CARRIER_INBOX_PAGE) pageInfo.full = true;
1840
+ // A page is full at CARRIER_INBOX_PAGE rows, or when the carrier cut it
1841
+ // at its byte limit and says more wait (2.8.0 `more`).
1842
+ if (pageInfo && (r.more === true || r.envelopes.length >= CARRIER_INBOX_PAGE)) pageInfo.full = true;
1315
1843
  for (const { seq, envelope } of r.envelopes) {
1316
1844
  since = Math.max(since, seq);
1317
1845
  // Keyed like the inbox, on (sender, id): another sender's envelope
@@ -1416,9 +1944,13 @@ export class Pillar {
1416
1944
  }
1417
1945
  if (persisted.duplicate) {
1418
1946
  this.metrics.inc("received.duplicate");
1947
+ // A notice may have been refused for budget, or never reached continuity (a crash): its copy is
1948
+ // not dropped (RedTeam 5402b7). Stored evidence makes this a cheap no-new-evidence.
1949
+ if (isContinuityKind(envelope.kind)) await this._continuityIngest(envelope, payload, verdict, Buffer.byteLength(rawLine), persisted.seq, { duplicate: true }); // @rule C-recv-ingest-duplicate
1419
1950
  return; // replay: do not re-fire handlers
1420
1951
  }
1421
1952
  this.metrics.inc(`received.kind.${envelope.kind}`);
1953
+ if (isContinuityKind(envelope.kind)) await this._continuityIngest(envelope, payload, verdict, Buffer.byteLength(rawLine), persisted.seq); // @rule C-recv-ingest
1422
1954
  if (!verdict2.deliver) {
1423
1955
  this.metrics.inc(`received.quarantined.${verdict2.reason}`);
1424
1956
  // eslint-disable-next-line no-console