@uuaid/pillar 2.5.4 → 2.6.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.
package/HOSTING-LIMITS.md CHANGED
@@ -123,13 +123,24 @@ grant.
123
123
 
124
124
  | Client | `wait` | Request timeout | After an error | Carriers |
125
125
  |---|---|---|---|---|
126
- | `pillar recv`, `Pillar.startCarrierPolling()` | 25 s (src/pillar.mjs:542) | 40 s (src/net/carrier-client.mjs:143) | sleep 2 s (src/net/carrier-client.mjs:187) | all in parallel, one cursor each (src/net/carrier-client.mjs:175-180) |
127
- | `pillar inbox` | 0, reading pages until one is empty (src/pillar.mjs:571-590) | 40 s | exits | one at a time |
128
- | `pillar-responder` | 20 s (bin/pillar-responder.mjs:299) | 40 s | sleep 2 s | all in parallel |
126
+ | `pillar recv`, `Pillar.startCarrierPolling()` | 25 s | 40 s per fetch | sleep 2 s + random [0, 2 s) jitter | all in parallel, one cursor each |
127
+ | `pillar inbox`, `Pillar.drainCarrierInbox()` | 0, reading pages until one is empty | 40 s per fetch; API accepts `timeoutMs` and `signal` | record the carrier's error, try the next carrier, throw once at the end | one at a time |
128
+ | `pillar-responder` | 20 s (bin/pillar-responder.mjs:299) | 40 s | sleep 2 s + random [0, 2 s) jitter | all in parallel |
129
129
  | `@uuaid/pillar-client` `poll()` / `subscribe()` | 25 s (packages/pillar-client/src/carrier.ts:149) | `wait` + 15 s (packages/pillar-client/src/carrier.ts:158) | sleep 2 s (packages/pillar-client/src/carrier.ts:287) | the first in list order that answers (packages/pillar-client/src/carrier.ts:160-167) |
130
130
  | Pillar mobile app, on screen | 25 s (apps/mobile/src/services/pillar.ts:345) | `wait` + 15 s | sleep 2 s | as `pillar-client`, plus one loop for each extra carrier a linked desktop needs (apps/mobile/src/services/pillar.ts:208-213) |
131
131
  | Push relay | 25 s, 30 at most (apps/pillar-push/src/config.ts:48) | `wait` + 20 s (apps/pillar-push/src/poller.ts:130) | sleep 2 s (apps/pillar-push/src/poller.ts:198) | all; one loop per uuaid per carrier (apps/pillar-push/src/poller.ts:95-103) |
132
132
 
133
+ In `@uuaid/pillar`, polling `stop()` aborts in-flight fetches and retry timers,
134
+ and its promise resolves after the run (including an active handler) ends.
135
+ New runs wait for previous runs to finish. `Pillar.stop()` awaits that
136
+ shutdown before closing the mailbox. The polling `random` and abortable
137
+ `sleep` functions are injectable in `CarrierClient.startPolling` for tests.
138
+ The drain returns the number of envelopes fetched when every carrier answers.
139
+ Otherwise it throws once, after every carrier was tried, the first failure with
140
+ `drained` (envelopes stored) and `errors` (`[{ carrier, error }]`); errors,
141
+ timeouts and caller cancellation retain partial progress. The timeout is per
142
+ request, while `signal` can bound the whole drain.
143
+
133
144
  `deliver()` in both libraries posts to every carrier in parallel, with a 10 s
134
145
  timeout each (src/net/carrier-client.mjs:81,
135
146
  packages/pillar-client/src/carrier.ts:86). It succeeds if any carrier accepts.
@@ -168,8 +179,9 @@ extra carriers.
168
179
  (INTERACTION-CONVENTION.md:54) is spent on your own work, not on polling.
169
180
  - **On 429:** budgets refill over a sliding 60 s. Back off, for example from
170
181
  5 s doubling to 60 s. Resending the same envelope is safe but spends budget.
171
- - **On 503 `busy`:** wait at least 2 s, with jitter (shipped clients use a
172
- fixed 2 s). **On 503 `carrier-full`:** see §5; your other carriers still
182
+ - **On 503 `busy`:** wait at least 2 s, with jitter (`@uuaid/pillar` polls use
183
+ 2 s + random [0, 2 s); the other clients listed above still use fixed 2 s).
184
+ **On 503 `carrier-full`:** see §5; your other carriers still
173
185
  take the envelope.
174
186
  - **On 401 `clock-skew`:** fix your clock. Keep it within 5 min, and send each
175
187
  envelope within 24 h of sealing it.
package/README.md CHANGED
@@ -54,6 +54,18 @@ For automated checking, put `pillar inbox --notify <cmd>` on a cron/launchd
54
54
  interval — the hook gets `PILLAR_NEW` / `PILLAR_UNREAD` / `PILLAR_UUAID` env
55
55
  vars and a JSON summary on stdin, and only fires when there is mail.
56
56
 
57
+ If every configured carrier fails, `inbox` behaves as 2.5.5 did: it prints
58
+ each refusal as `<code>: <fix>` on stderr (any other failure as the error
59
+ itself) and exits 1, without printing mail, moving a reader cursor or marking
60
+ anything read. Mail fetched before a later page fails remains stored and
61
+ unread (recover with `--unread` or a named reader).
62
+ If at least one carrier drains successfully, failed carriers are reported
63
+ as `<carrier URL>: <code>: <fix>` (or `<carrier URL>: <message>`) on stderr,
64
+ healthy mail is printed and `--mark-read` works normally, with exit 0 so
65
+ couriers keep the output. `send` retains its one-line refusal and exit 1
66
+ behavior. `wait` only peeks and `recv` polls; neither calls the one-shot
67
+ drain or marks mail read.
68
+
57
69
  ### Several readers on one home: `--reader`
58
70
 
59
71
  Carrier reads are non-destructive and the mailbox is idempotent on sender +
@@ -80,6 +92,99 @@ reader last looked (naming the process and its directory), or when a live
80
92
  are flagged too. `pillar-responder` and `pillar-ask` still want their own
81
93
  identity/home: they act on first arrival, which a cursor cannot share.
82
94
 
95
+ ### Mailbox: local message erasure (library)
96
+
97
+ `pillar.mailbox.eraseRows(selector)` synchronously redacts inbox **and**
98
+ outbox content in one SQLite transaction. Pass exactly one selector:
99
+
100
+ - `{ pairs: [{ sender, envelope_id }, ...] }`: explicit envelope identities.
101
+ The sender scopes both logs; for an outgoing message use **your** UUAID,
102
+ not its recipient. Outbox sender matching reads the original envelope's
103
+ `sender` (or legacy `from`).
104
+ - `{ conversation: peerUuaid }`: the **direct** conversation with that peer:
105
+ inbox messages from it and outbox messages to it that are not filed under a
106
+ group (`group_id IS NULL`), in both directions. The same peer's group
107
+ messages are left untouched, as the mobile app's `dm:<peer>` erase leaves
108
+ them. **Limit:** the mailbox cannot read the sealed group tag, so a row it
109
+ never filed under a group has no `group_id` and falls under this selector:
110
+ an inbound pillar-group v1 message from a sender who is not a member of that
111
+ group (v1 files a row only when its sender is a member), and a held or
112
+ quarantined v2 message. A caller that decrypts and classifies rows (as the
113
+ Mac core does) should pass explicit `pairs`, which are exact.
114
+ - `{ groupId }`: rows filed under that `group_id`, for pillar-group v1 or v2.
115
+ This does not remove the roster or v2 manifest/hold store.
116
+ A row the receiver has not yet filed under a group (for example a held v2
117
+ envelope) needs explicit pairs or a conversation selector instead.
118
+ Its group tag is inside the encrypted payload, not available to the
119
+ mailbox's non-decrypting erase path; `{ groupId }` alone cannot select it.
120
+
121
+ It returns `{ inbox: n, outbox: n }`, counting only newly redacted rows.
122
+ Repeated calls and valid selectors naming unknown messages return zeros.
123
+ Empty/malformed selectors, mixed modes and unknown option names throw;
124
+ there is no implicit “erase everything.” Do not call inside another transaction.
125
+
126
+ The fixed replacement for `envelope_json` is `{"erased":true,"v":1}`.
127
+ The exact marker identifies tombstones without a schema change. Rows retain their `seq`,
128
+ `envelope_sha256`, `chain_hash`, IDs, routing/group metadata and cursor
129
+ positions, so both chain audits still pass. This is **content erasure, not
130
+ metadata anonymity**. Retained `(sender, envelope_id)` inbox identities make
131
+ late redelivery a duplicate, without storing the body or firing handlers again.
132
+ Mailbox listings (including unread, named-reader/new, quarantine and group
133
+ views) omit erased rows before applying their limit. Direct
134
+ `getInbound`/`getOutbound` lookups still return the marker and audit metadata.
135
+ Erased rows cannot be marked read, released from quarantine (so no new
136
+ reader position brings them back), re-quarantined, filed under a group, or
137
+ updated by recipient ack/read matching. A held pillar-group/2 message erased
138
+ before its chain completes is not released, filed or handed to any handler
139
+ when the chain arrives. Normal list-driven read-receipt flows skip them.
140
+ The CLI never prints a tombstone's content or a "decrypt failed" line for
141
+ it, never counts one in `wait` or `inbox` totals, and never marks one read
142
+ (`inbox` and `recv` skip it; `group show` lists only id and sender). An erased
143
+ send no longer counts as "answering our send" for the trust gate, so a
144
+ stranger's ack or reply to it follows `trust.json` like any other message.
145
+ VDA message-delivery attestations (`attestMessageDelivery`) still verify
146
+ from the kept hash, chain and ack evidence; they never carry content.
147
+
148
+ **Physical erasure and concurrency limits:** erasure enables
149
+ `PRAGMA secure_delete = ON` on its connection (and leaves it enabled for
150
+ subsequent writes), compacts the database with `VACUUM`, then requires a
151
+ successful `wal_checkpoint(TRUNCATE)`. Compaction removes historical content
152
+ in pages freed by older code or a re-key while secure delete was off; it
153
+ rewrites the whole database and can require additional temporary disk space.
154
+ Both the main database and WAL are scrubbed on successful return. Idle
155
+ connections and live reader leases are supported; a pinned SQLite read
156
+ snapshot is not. A short, bounded preflight checkpoint refuses existing
157
+ snapshot contention before any rows change (`ERASE_ABORTED`,
158
+ `committed: false`). Mutation failures roll back both logs together.
159
+ SQLite cannot atomically commit the transaction, compact, and truncate WAL:
160
+ a compaction failure or snapshot racing the final checkpoint can leave all
161
+ selected rows committed but the disk scrub incomplete. That throws `ERASE_CHECKPOINT_INCOMPLETE`,
162
+ `committed: true`, with committed counts in `error.erased`. Release snapshots
163
+ and retry the **same selector**; even a zero-count retry checkpoints again.
164
+ Never treat that error as successful physical erasure.
165
+
166
+ Erasure cannot revoke previously returned JavaScript views, in-flight
167
+ handlers/receipts, app previews, v2 hold buffers, external blobs, remote
168
+ carrier/peer copies, filesystem/device snapshots, re-key `.bak` copies from
169
+ `sqlite-rekey.mjs`, or application backups. Backups must be managed separately.
170
+ `Pillar.sendReadReceipts(views)` checks the sender-scoped mailbox before
171
+ planning and immediately before each send, so cached views of erased rows
172
+ cannot initiate a new receipt. A send already admitted before erasure cannot
173
+ be recalled; applications needing that stronger guarantee must serialize
174
+ erasure with completion of receipt sends using an admission barrier.
175
+ Do not restore old backups and assume erased tombstones survive.
176
+
177
+ **Rolling back to 2.5.5.** The published 2.5.5 opens a mailbox that 2.6.0
178
+ erased rows in and runs its read paths without crashing; both chains still
179
+ audit and an erased envelope redelivered stays a duplicate (acceptance test
180
+ against the registry tarball, `test/integration/downgrade-2.5.5.test.mjs`).
181
+ 2.5.5 predates the tombstone, so it shows each one as an id-less
182
+ `{"payload":{"error":"decrypt failed"}}` line in `inbox` and `group show`,
183
+ counts it in the unread totals and as an `undefined` kind in `wait`, and
184
+ `trust quarantine --release` can release an erased held row. `--mark-read`
185
+ leaves it unread. No content comes back (it is gone), and 2.6.0 hides every
186
+ tombstone again when it reopens the mailbox.
187
+
83
188
  ### Sleep until there is mail: `pillar wait`
84
189
 
85
190
  Homes that cannot open a port poll. `pillar wait` turns the poll into a wake
@@ -169,6 +274,134 @@ themselves. Messages from members who are not your contacts still follow
169
274
  Same convention as the mobile app and agentnet.chat; `send-group` with a
170
275
  `groups.json` keeps working and now sends the same tag.
171
276
 
277
+ For signed groups-v2 invitations, an incomplete manifest chain waits in a
278
+ bounded buffer: at most 4 pending invitations per sender and 64 overall,
279
+ with 4 MiB per sender and 32 MiB total across invitation and recovery buffers.
280
+ Malformed manifests take no slot. At the count caps, invitations that do not
281
+ name your exact UUAID and key as invited are evicted before ones that do;
282
+ within each class the oldest goes first, from the same sender first when
283
+ that sender is at its cap. Malformed manifests cannot evict anything, and
284
+ existing non-self junk is removed before a pending invitation that names you.
285
+ A complete, verified invitation is adopted immediately and leaves no pending
286
+ slot.
287
+
288
+ The accepted remaining limit is that 64 genuine but incomplete invitations
289
+ that name you (16 senders with 4 each) can evict an older pending invitation
290
+ that also names you. Re-sending its manifest chain completes that invitation;
291
+ the eviction delays adoption and does not remove an adopted group. Admission
292
+ and eviction do not currently prefer contacts or trusted senders.
293
+
294
+ ### Group admin from code: `@uuaid/pillar/groups-v2`
295
+
296
+ From 2.6.0 the signed pillar-group/2 admin API is a package export, so an app
297
+ needs neither `pillar group` nor a deep import. It exports exactly these 11
298
+ names: `adminCreate`, `adminChange`, `adminManifestSends`, `parseMemberRef`,
299
+ `adminOf`, `activeAdmins`, `isGroupIdV2`, `ACTIONS`, `MAX_MEMBERS`, `MAX_NAME`
300
+ and `MAX_PURPOSE`.
301
+
302
+ **No store and no receiver is exported** (one group store per home, design
303
+ D5): there is no `RosterStore`, `MemoryRosterStore`, `GroupReceiver` or
304
+ `syncMailboxRoster`, and no `buildGenesis`, `buildNext` or `signManifest`,
305
+ which `adminCreate` and `adminChange` already wrap. Use the store and mailbox
306
+ your `Pillar` already holds, `pillar.groupsV2.store`, as the CLI does.
307
+ `@uuaid/pillar/src/groups-v2.mjs` stays unexported. Like the CLI, admin
308
+ writes sign, verify and persist the new manifest and mailbox roster locally;
309
+ they do **not** start a transport or send anything.
310
+
311
+ ```js
312
+ import { randomBytes } from "node:crypto";
313
+ import { adminCreate, adminChange, adminManifestSends } from "@uuaid/pillar/groups-v2";
314
+
315
+ // pillar is your configured Pillar instance with a loaded keychain.
316
+ // invitee is { uuaid, publicKeyHex }, obtained through your trusted contact flow.
317
+ const store = pillar.groupsV2.store;
318
+ const mailbox = pillar.mailbox; // Mailbox instance
319
+ function queueManifests(rec) {
320
+ const sends = adminManifestSends(rec, mailbox.getGroup(rec.id), pillar.uuaid);
321
+ const ids = mailbox.enqueueGroupV2Sends(rec.id, sends, {
322
+ newId: () => `gq-${randomBytes(12).toString("hex")}`,
323
+ });
324
+ // The queue is bounded. Report how many did not fit rather than assuming
325
+ // every manifest was queued; do not blindly repeat already-queued sends.
326
+ if (ids.length < sends.length) {
327
+ console.warn(`${sends.length - ids.length} manifest send(s) did not fit`);
328
+ }
329
+ return ids;
330
+ }
331
+
332
+ const { rec } = adminCreate({
333
+ store, mailbox, keychain: pillar.keychain, name: "crew",
334
+ members: [{ uuaid: invitee.uuaid, key: invitee.publicKeyHex }],
335
+ });
336
+ queueManifests(rec);
337
+
338
+ const changed = adminChange({
339
+ store, mailbox, keychain: pillar.keychain, groupId: rec.id,
340
+ action: "rename", opts: { name: "crew 2" },
341
+ }).rec;
342
+ queueManifests(changed);
343
+
344
+ // Explicit delivery, exactly as `pillar group sync <grp-id>` does.
345
+ try {
346
+ await pillar.start();
347
+ const results = await pillar.syncGroupV2({ groupId: rec.id });
348
+ // sent/dropped are final; failures stay queued for a later explicit sync.
349
+ for (const row of results) console.log(row.state, row.to, row.reason ?? "");
350
+ } finally {
351
+ await pillar.stop();
352
+ }
353
+ ```
354
+
355
+ `adminChange` also supports `invite`, `remove`, `accept`, `leave`,
356
+ `ext_update` and `admin_transfer`; it verifies the signer is the current
357
+ admin. `adminManifestSends` includes the chain an invitee needs and the
358
+ newest manifest for a removed member. Always queue after each admin write.
359
+ The store/roster write and queue insertion are separate operations, as in
360
+ the CLI: this is not an atomic store-and-send API.
361
+
362
+ ### Carrier polling lifecycle and one-shot drain
363
+
364
+ Keep the handle from `pillar.startCarrierPolling({ waitS: 25 })`.
365
+ `await handle.stop()` (or `await pillar.stopCarrierPolling()`) aborts its
366
+ in-flight fetches and retry timers and waits for the loop to end. A handler
367
+ already running is allowed to finish; handlers must not await their own
368
+ poller's stop promise. Stop the old handle before restarting: a new run
369
+ waits for earlier runs to finish, so suspend/resume cannot multiply polls.
370
+ `pillar.stop()` waits before closing the mailbox. Carrier errors retry
371
+ after `2000 + Math.floor(Math.random() * 2000)` ms, in [2000, 4000).
372
+
373
+ `await pillar.drainCarrierInbox({ timeoutMs: 10000, signal })` pulls pages
374
+ without long-polling. When every carrier answers it returns a **number**,
375
+ the envelopes fetched (duplicates included), exactly as before 2.6.0; with no
376
+ carriers it returns 0. From 2.6.0 every carrier is tried on its own, so one
377
+ that fails no longer keeps the carriers after it from being drained. If any
378
+ failed, the drain throws **once, after the last carrier was tried**: the
379
+ thrown error is the first failure itself, with `err.drained` (envelopes this
380
+ call stored, from healthy carriers and from pages a failed carrier served
381
+ before it failed) and `err.errors = [{ carrier, error }]` (one entry per
382
+ carrier that did not finish, in carrier order; not enumerable, because
383
+ `errors[0].error` is the thrown error). `err.errors.length ===
384
+ pillar.carriers.length` means no carrier finished. A failure that is not an
385
+ extensible object is wrapped in an `Error` whose `cause` is the original.
386
+
387
+ ```js
388
+ try {
389
+ const pulled = await pillar.drainCarrierInbox();
390
+ } catch (err) {
391
+ if (!Array.isArray(err.errors)) throw err; // not a carrier outcome
392
+ const allFailed = err.errors.length === pillar.carriers.length;
393
+ for (const { carrier, error } of err.errors) console.error(carrier, error.code ?? error.message);
394
+ // err.drained envelopes were stored; their handlers already ran.
395
+ }
396
+ ```
397
+
398
+ `timeoutMs` applies to **each fetch**, default 40000 ms, not the whole drain.
399
+ Use an `AbortSignal` for a whole-drain deadline or suspend cancellation. An
400
+ aborted drain throws the abort reason; the carrier it interrupted and every
401
+ carrier after it (not fetched) are listed in `err.errors`. Completed mailbox
402
+ writes and cursors remain, and a running receive handler finishes before
403
+ cancellation is checked again.
404
+
172
405
  ### Replacing an identity: `init --force`
173
406
 
174
407
  `init --force` mints a NEW uuaid, which silently breaks every contact that
@@ -622,6 +855,22 @@ rate and body size — see "Tier grants" above for the ladder. It is a
622
855
  A tier grant changes the window's ceiling, not whether usage is tracked.
623
856
  - **Grants are not revocable before expiry** — see "What a tier grant is —
624
857
  and is not" above; plan grant lifetimes accordingly.
858
+ - **Local message erasure (`mailbox.eraseRows`, 2.6.0) erases content, not
859
+ the fact that a message existed.**
860
+ - **What an erase keeps:** `sender` or `recipient`, the times,
861
+ `envelope_id`, `group_id`, `kind`, `thread`, `status`, and the ack and
862
+ read times. They still show that a message existed. (Also kept, for the
863
+ chain audits and the readers: `seq`, `envelope_sha256`, `chain_hash`,
864
+ `quarantined`, `released_seq`, `pulled_by` and every reader cursor.)
865
+ - **What it cannot reach:**
866
+ - the re-key `.bak` files (`sqlite-rekey.mjs:147`) and app backups;
867
+ - other connections, until a checkpoint completes;
868
+ - SSD remanence;
869
+ - the carrier's copy until its TTL;
870
+ - other devices' copies.
871
+
872
+ See "Mailbox: local message erasure" above for the selectors, the
873
+ checkpoint-incomplete error and retry, and rolling back to 2.5.5.
625
874
 
626
875
  ## Source, provenance and releases
627
876
 
package/bin/pillar.mjs CHANGED
@@ -50,7 +50,13 @@ import { extractGroupTag, findGroup, normalizeMembers } from "../src/groups.mjs"
50
50
  import { describeOutboundStatus, receiptFor } from "../src/receipts.mjs";
51
51
  import { groupCommandRoute, groupRouteLookups, RosterStore } from "../src/groups-v2.mjs";
52
52
  import { runGroupV2 } from "../src/group-v2-cli.mjs";
53
- import { Mailbox } from "../src/mailbox/mailbox.mjs";
53
+ import { Mailbox, isErasedRow } from "../src/mailbox/mailbox.mjs";
54
+
55
+ // JSON rendered as one text line (or embedded in a Zestro command). Preserve
56
+ // parsed values while escaping the two separators JSON.stringify leaves raw.
57
+ function jsonLine(value) {
58
+ return JSON.stringify(value).replace(/[\u2028\u2029]/g, c => `\\u${c.charCodeAt(0).toString(16)}`);
59
+ }
54
60
 
55
61
  function parseArgs(argv) {
56
62
  const args = { _: [] };
@@ -188,7 +194,19 @@ function inboxLine(env, payload, extra = {}) {
188
194
  return line;
189
195
  }
190
196
 
197
+ /**
198
+ * The decrypted view of a stored inbox row. An erased row's tombstone is not
199
+ * an envelope: it is never parsed or shown as "decrypt failed"; its view is a
200
+ * stub, `erased: true` with only the row's id and sender and no payload, and
201
+ * inbox/recv skip it (no line, no handler, no read receipt). Mailbox listings
202
+ * already omit tombstones; this keeps any row that still reaches a reader
203
+ * safe (C6). The stub keeps the pinned v1 `group show` code from throwing.
204
+ */
191
205
  function viewOfRow(p, row, decrypt) {
206
+ if (isErasedRow(row)) {
207
+ return { erased: true, env: { id: row.envelope_id, sender: row.sender, kind: null, createdAt: null }, payload: null,
208
+ seq: row.seq, groupId: row.group_id ?? null, pulledBy: row.pulled_by ?? null };
209
+ }
192
210
  const env = JSON.parse(row.envelope_json);
193
211
  let payload;
194
212
  try { payload = decrypt(p.keychain, env); } catch (_e) { payload = { error: "decrypt failed" }; }
@@ -836,7 +854,7 @@ async function cmdGroup(args) {
836
854
  const { decrypt } = await import("../src/net/envelope.mjs");
837
855
  // A local view: it never pulls from carriers (that would take "new" away
838
856
  // from the next inbox run). Pull with pillar inbox first.
839
- console.log(JSON.stringify({ group: g.id, name: g.name, members: g.members, pending: g.pending, left: g.left, createdBy: g.createdBy, view: "local — pull new mail with pillar inbox" }));
857
+ console.log(jsonLine({ group: g.id, name: g.name, members: g.members, pending: g.pending, left: g.left, createdBy: g.createdBy, view: "local — pull new mail with pillar inbox" }));
840
858
  const items = [];
841
859
  for (const row of p.mailbox.groupInbound(g.id, limit)) {
842
860
  const { env, payload } = viewOfRow(p, row, decrypt);
@@ -855,7 +873,7 @@ async function cmdGroup(args) {
855
873
  }
856
874
  for (const [msgId, m] of byMsg) items.push({ at: m.at, line: { dir: "out", msgId, at: m.at, members: m.to, acceptedByCarrier: m.carrier, acknowledged: m.acked, read: m.read } });
857
875
  items.sort((a, b) => (a.at < b.at ? -1 : a.at > b.at ? 1 : 0));
858
- for (const it of items.slice(-limit)) console.log(JSON.stringify(it.line));
876
+ for (const it of items.slice(-limit)) console.log(jsonLine(it.line));
859
877
  return;
860
878
  }
861
879
  } finally {
@@ -955,7 +973,7 @@ async function cmdRecv(args) {
955
973
  const tag = extractGroupTag(env.payload);
956
974
  if (tag) { line.group = tag.name; line.groupId = tag.id; if (tag.msgId) line.msgId = tag.msgId; if (tag.op !== "message") line.op = tag.op; }
957
975
  if (rk.named) line.id = env.id;
958
- console.log(JSON.stringify(line));
976
+ console.log(jsonLine(line));
959
977
  if (bridge && env.kind === "request") {
960
978
  // Interaction-convention return leg: ack FIRST — pillar-ask allows 120s
961
979
  // per phase but ZestroBridge times out at 30s, so the ack goes out before
@@ -970,7 +988,7 @@ async function cmdRecv(args) {
970
988
  const senderKey = env.transportSignature.publicKey; // open() F1: sender derives from this key
971
989
  try {
972
990
  if (!autoAcks) await p.send({ recipient: env.sender, recipientPublicKey: senderKey, kind: "ack", payload: { inReplyTo: env.id } });
973
- const result = await bridge.sendCommand({ command: JSON.stringify({ kind: env.kind, payload: env.payload, sender: env.sender }) });
991
+ const result = await bridge.sendCommand({ command: jsonLine({ kind: env.kind, payload: env.payload, sender: env.sender }) });
974
992
  const hasText = result && typeof result === "object" &&
975
993
  ["text", "result", "output", "response", "message"].some(k => k in result);
976
994
  const text = hasText
@@ -996,8 +1014,8 @@ async function cmdRecv(args) {
996
1014
  }
997
1015
  } else if (bridge && env.kind !== "ack" && env.kind !== "reply") {
998
1016
  try {
999
- const result = await bridge.sendCommand({ command: JSON.stringify({ kind: env.kind, payload: env.payload, sender: env.sender }) });
1000
- console.log(` → zestro result: ${JSON.stringify(result).slice(0, 200)}`);
1017
+ const result = await bridge.sendCommand({ command: jsonLine({ kind: env.kind, payload: env.payload, sender: env.sender }) });
1018
+ console.log(` → zestro result: ${jsonLine(result).slice(0, 200)}`);
1001
1019
  } catch (e) {
1002
1020
  if (e.code === "SESSION_BUSY") {
1003
1021
  console.log(` → zestro: busy (${e.message})`);
@@ -1028,8 +1046,8 @@ async function cmdRecv(args) {
1028
1046
  try {
1029
1047
  const cursor = p.mailbox.getReader(rk.key)?.cursor ?? 0;
1030
1048
  await handleInOrder(p.mailbox.inboxAfter(cursor, 200), async (row) => {
1031
- const { env, payload } = viewOfRow(p, row, decrypt);
1032
- await handle({ ...env, payload });
1049
+ const view = viewOfRow(p, row, decrypt);
1050
+ if (!view.erased) await handle({ ...view.env, payload: view.payload });
1033
1051
  }, {
1034
1052
  advance: (row) => p.mailbox.setReaderCursor(rk.key, row.released_seq ?? row.seq),
1035
1053
  onError: (row, e) => console.error(`reader ${rk.key}: row ${row.seq} not handled, not retried: ${e.message}`),
@@ -1083,8 +1101,28 @@ async function cmdInbox(args) {
1083
1101
  // A new named reader starts before the oldest unread row, computed BEFORE
1084
1102
  // this run's pull so that what it pulls is new to it too.
1085
1103
  const startCursor = prev ? prev.cursor : (rk.named ? initialCursor(p.mailbox) : p.mailbox.inboxTipSeq());
1104
+ // The drain returns the number pulled. If a carrier failed it throws once,
1105
+ // after every carrier was tried, with err.drained and err.errors (2.6.0).
1106
+ // R2: EVERY carrier failed -> exactly 2.5.5: each failure on stderr as
1107
+ // `<code>: <fix>`, exit 1, nothing printed, no reader moved, nothing marked
1108
+ // read. SOME failed -> each failed carrier's line prefixed with its URL,
1109
+ // the healthy mail printed and marked read as usual, exit 0: a courier
1110
+ // discards stdout on nonzero exit, so mail marked read under rc 1 is lost.
1111
+ let pulled;
1112
+ try {
1113
+ pulled = await p.drainCarrierInbox();
1114
+ } catch (err) {
1115
+ const errors = Array.isArray(err?.errors) ? err.errors : null;
1116
+ if (!errors) throw err; // not a carrier outcome: main() prints it, exit 1 (as 2.5.5)
1117
+ const allFailed = errors.length >= p.carriers.length;
1118
+ for (const { carrier, error } of errors) {
1119
+ if (allFailed) console.error(refusalLine(error) ?? error);
1120
+ else console.error(`${carrier}: ${refusalLine(error) ?? error?.message ?? String(error)}`);
1121
+ }
1122
+ if (allFailed) { await p.stop(); exit(1); }
1123
+ pulled = err.drained;
1124
+ }
1086
1125
  p.mailbox.touchReader(rk.key, { ...ctx, cursor: startCursor });
1087
- const pulled = await p.drainCarrierInbox();
1088
1126
  const { decrypt } = await import("../src/net/envelope.mjs");
1089
1127
  const printed = []; // { id, sender, kind, payload, groupId } — for read receipts
1090
1128
 
@@ -1092,31 +1130,35 @@ async function cmdInbox(args) {
1092
1130
  if (rk.named) {
1093
1131
  const rows = p.mailbox.inboxAfter(startCursor, 1000);
1094
1132
  for (const row of rows) {
1095
- const { env, payload, groupId } = viewOfRow(p, row, decrypt);
1096
- console.log(JSON.stringify(inboxLine(env, payload, { new: true })));
1133
+ const view = viewOfRow(p, row, decrypt);
1134
+ if (view.erased) continue;
1135
+ const { env, payload, groupId } = view;
1136
+ console.log(jsonLine(inboxLine(env, payload, { new: true })));
1097
1137
  printed.push({ id: env.id, sender: env.sender, kind: env.kind, payload, groupId });
1098
1138
  }
1099
1139
  if (rows.length && !args.peek) p.mailbox.setReaderCursor(rk.key, rows.at(-1).released_seq ?? rows.at(-1).seq);
1100
1140
  const qCount = (p.mailbox.inboxQuarantined?.(500) ?? []).length;
1101
- console.log(`inbox: ${rows.length} new for reader "${rk.key}" (${pulled} pulled from carriers by this run)${args.peek ? ", cursor not moved (--peek)" : ""}${qCount ? `, ${qCount} quarantined (pillar trust quarantine)` : ""}`);
1141
+ console.log(`inbox: ${printed.length} new for reader "${rk.key}" (${pulled} pulled from carriers by this run)${args.peek ? ", cursor not moved (--peek)" : ""}${qCount ? `, ${qCount} quarantined (pillar trust quarantine)` : ""}`);
1102
1142
  } else {
1103
1143
  // fromPublicKey: the sender's verified Ed25519 key (transportSignature —
1104
1144
  // open() binds it to `from`). Lets a drain-and-reply consumer (the fleet
1105
1145
  // courier's auto-ack, a bot) seal back to a sender who is NOT in fleet.json
1106
1146
  // via `pillar send … --to-pubkey <fromPublicKey>`. Additive field.
1107
1147
  for (const env of fresh) {
1108
- console.log(JSON.stringify(inboxLine(env, env.payload, { new: true })));
1148
+ console.log(jsonLine(inboxLine(env, env.payload, { new: true })));
1109
1149
  printed.push({ id: env.id, sender: env.sender, kind: env.kind, payload: env.payload, groupId: extractGroupTag(env.payload)?.id ?? null });
1110
1150
  }
1111
1151
  // Backlog: rows stored earlier (e.g. by a recv daemon) but never surfaced.
1112
1152
  // Keyed on (sender, id): an id is unique only within its sender.
1113
1153
  const freshKeys = new Set(fresh.map(e => `${e.sender}\n${e.id}`));
1114
1154
  const isFresh = (r) => freshKeys.has(`${r.sender}\n${r.envelope_id}`);
1115
- backlog = (p.mailbox.inboxUnread?.(500) ?? []).filter(r => !isFresh(r));
1155
+ backlog = (p.mailbox.inboxUnread?.(500) ?? []).filter(r => !isFresh(r) && !isErasedRow(r));
1116
1156
  if (args.unread) {
1117
1157
  for (const row of backlog) {
1118
- const { env, payload, groupId } = viewOfRow(p, row, decrypt);
1119
- console.log(JSON.stringify(inboxLine(env, payload, { new: false })));
1158
+ const view = viewOfRow(p, row, decrypt);
1159
+ if (view.erased) continue;
1160
+ const { env, payload, groupId } = view;
1161
+ console.log(jsonLine(inboxLine(env, payload, { new: false })));
1120
1162
  printed.push({ id: env.id, sender: env.sender, kind: env.kind, payload, groupId });
1121
1163
  }
1122
1164
  }
@@ -1127,7 +1169,7 @@ async function cmdInbox(args) {
1127
1169
  // other reader already marked read are missing.
1128
1170
  if (prev) {
1129
1171
  const taken = p.mailbox.inboxAfter(prev.cursor, 1000)
1130
- .filter((r) => !isFresh(r) && r.pulled_by !== rk.key && (!args.unread || r.read_at));
1172
+ .filter((r) => !isFresh(r) && !isErasedRow(r) && r.pulled_by !== rk.key && (!args.unread || r.read_at));
1131
1173
  if (taken.length) {
1132
1174
  const by = new Map();
1133
1175
  for (const r of taken) by.set(r.pulled_by ?? null, (by.get(r.pulled_by ?? null) ?? 0) + 1);
@@ -1155,7 +1197,7 @@ async function cmdInbox(args) {
1155
1197
  const { spawnSync } = await import("node:child_process");
1156
1198
  const r = spawnSync(args.notify, {
1157
1199
  shell: true,
1158
- input: JSON.stringify({ uuaid: p.uuaid, new: newCount, unread: backlog.length }) + "\n",
1200
+ input: jsonLine({ uuaid: p.uuaid, new: newCount, unread: backlog.length }) + "\n",
1159
1201
  env: { ...process.env, PILLAR_NEW: String(newCount), PILLAR_UNREAD: String(backlog.length), PILLAR_UUAID: p.uuaid },
1160
1202
  stdio: ["pipe", "inherit", "inherit"],
1161
1203
  });
@@ -1196,11 +1238,13 @@ async function cmdWait(args) {
1196
1238
  const r = p.mailbox.getReader(rk.key);
1197
1239
  return r ? r.cursor : initialCursor(p.mailbox);
1198
1240
  };
1199
- const localRows = () => (rk.named ? p.mailbox.inboxAfter(cursor(), 1000) : []);
1241
+ // An erased row is not pending mail: it never wakes a reader or counts as a
1242
+ // kind, whatever listing handed it over (C6).
1243
+ const localRows = () => (rk.named ? p.mailbox.inboxAfter(cursor(), 1000).filter((r) => !isErasedRow(r)) : []);
1200
1244
  const report = (carrierViews, local) => {
1201
1245
  const kinds = {};
1202
1246
  for (const k of [...carrierViews.map((v) => v.kind), ...local.map((r) => JSON.parse(r.envelope_json).kind)]) kinds[k] = (kinds[k] ?? 0) + 1;
1203
- console.log(JSON.stringify({ uuaid: p.uuaid, ...(rk.named ? { reader: rk.key } : {}), pending: carrierViews.length + local.length, carrier: carrierViews.length, local: local.length, kinds }));
1247
+ console.log(jsonLine({ uuaid: p.uuaid, ...(rk.named ? { reader: rk.key } : {}), pending: carrierViews.length + local.length, carrier: carrierViews.length, local: local.length, kinds }));
1204
1248
  };
1205
1249
  let local = localRows();
1206
1250
  if (local.length) { report([], local); await p.stop(); exit(0); }
@@ -1209,7 +1253,7 @@ async function cmdWait(args) {
1209
1253
  local = localRows();
1210
1254
  await p.stop();
1211
1255
  if (views.length || local.length) { report(views, local); exit(0); }
1212
- console.log(JSON.stringify({ uuaid: p.uuaid, pending: 0, timedOut: true }));
1256
+ console.log(jsonLine({ uuaid: p.uuaid, pending: 0, timedOut: true }));
1213
1257
  exit(3);
1214
1258
  }
1215
1259
 
@@ -1227,7 +1271,7 @@ async function cmdReaders(args) {
1227
1271
  for (const r of readers) {
1228
1272
  const behind = mb.inboxAfter(r.cursor, 100000).length;
1229
1273
  const leases = live.filter((l) => l.reader === r.name);
1230
- console.log(JSON.stringify({
1274
+ console.log(jsonLine({
1231
1275
  reader: r.name, named: !r.name.startsWith("ctx:"), cursor: r.cursor, unseen: behind,
1232
1276
  last: describeProcess(r), live: leases.map(describeProcess),
1233
1277
  }));
@@ -1261,7 +1305,7 @@ async function cmdStatus(args) {
1261
1305
  const rows = id ? [p.mailbox.getOutbound(id)].filter(Boolean) : p.mailbox.outboxRecent(Number(args.limit ?? 20));
1262
1306
  if (id && !rows.length) { console.error(`no envelope ${id} in this home's outbox`); exit(2); }
1263
1307
  for (const r of rows) {
1264
- console.log(JSON.stringify({
1308
+ console.log(jsonLine({
1265
1309
  id: r.envelope_id, to: r.recipient, kind: r.kind ?? null, at: r.created_at,
1266
1310
  ...(r.group_id ? { groupId: r.group_id, msgId: r.group_msg_id ?? null } : {}),
1267
1311
  acceptedByCarrier: r.status === "delivered" ? (r.delivered_at ?? true) : null,
@@ -1372,7 +1416,7 @@ async function cmdTrust(args) {
1372
1416
  return;
1373
1417
  }
1374
1418
  for (const row of mb.inboxQuarantined(500)) {
1375
- console.log(JSON.stringify({ id: row.envelope_id, from: row.sender, reason: row.quarantined, at: row.received_at }));
1419
+ console.log(jsonLine({ id: row.envelope_id, from: row.sender, reason: row.quarantined, at: row.received_at }));
1376
1420
  }
1377
1421
  mb.close();
1378
1422
  return;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@uuaid/pillar",
3
- "version": "2.5.4",
3
+ "version": "2.6.0",
4
4
  "description": "Pillar (Protocol for Inter-agent Linked Ledger And Relay) — the secure delivery layer of UACP, the Universal Agent Communication Protocol. UACP = UUAID (identity) + Envelope (signed, encrypted container) + Pillar (relay, mailbox, routing, store-and-forward). Reference implementation of the UACP delivery layer; includes VDA-1 (IAASO-3901, in ballot) delivery attestation and a blind escrow for the Zilligon ZGN / EVM rails.",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -32,6 +32,7 @@
32
32
  "./blob/store": "./src/blob/store.mjs",
33
33
  "./blob/broker": "./src/blob/broker.mjs",
34
34
  "./refusals": "./src/net/refusals.mjs",
35
+ "./groups-v2": "./src/groups-v2-admin.mjs",
35
36
  "./package.json": "./package.json"
36
37
  },
37
38
  "files": [
@@ -0,0 +1,16 @@
1
+ /**
2
+ * `@uuaid/pillar/groups-v2`: the pillar-group/2 admin API (2.6.0, G1).
3
+ * Re-exports only; the code is ./groups-v2.mjs.
4
+ *
5
+ * No store and no receiver is exported (design D5: one group store). The
6
+ * caller passes the store its Pillar already holds, `pillar.groupsV2.store`,
7
+ * as `pillar group` does (src/group-v2-cli.mjs keyed()). A public RosterStore
8
+ * or GroupReceiver would let a consumer build a second store beside it.
9
+ * buildGenesis, buildNext and signManifest stay inside too: adminCreate and
10
+ * adminChange wrap them (sign, verify, store, write the mailbox row).
11
+ */
12
+ export {
13
+ adminCreate, adminChange, adminManifestSends, parseMemberRef,
14
+ adminOf, activeAdmins, isGroupIdV2,
15
+ ACTIONS, MAX_MEMBERS, MAX_NAME, MAX_PURPOSE,
16
+ } from "./groups-v2.mjs";
@@ -79,6 +79,15 @@ create table if not exists chain_state (
79
79
  `;
80
80
 
81
81
  const CHAIN_SEED = "uuaid-pillar-mailbox-v1|";
82
+ export const ERASED_ENVELOPE_JSON = '{"erased":true,"v":1}';
83
+ // A valid stored envelope always has an id; this exact constant cannot be a
84
+ // valid envelope. No schema migration or extra enumerable row field needed.
85
+ const LIVE_ENVELOPE_SQL = `envelope_json <> '${ERASED_ENVELOPE_JSON}'`;
86
+
87
+ /** True for an inbox/outbox row whose content eraseRows replaced (a tombstone). */
88
+ export function isErasedRow(row) {
89
+ return !!row && row.envelope_json === ERASED_ENVELOPE_JSON;
90
+ }
82
91
 
83
92
  export class Mailbox {
84
93
  constructor(path) {
@@ -192,6 +201,87 @@ export class Mailbox {
192
201
  }
193
202
 
194
203
  close() { try { this.db.close(); } catch (_e) {} }
204
+ /**
205
+ * Local content erasure, not log deletion. Exactly one selector:
206
+ * { pairs: [{ sender, envelope_id }] } — sender scopes BOTH logs;
207
+ * { conversation: peerUuaid } — the DIRECT conversation only: inbox rows
208
+ * from the peer and outbox rows to it with group_id IS NULL, as the
209
+ * phone's `dm:<peer>` key (C3). The peer's group rows are untouched.
210
+ * A row the mailbox never filed under a group (a v1 group message from
211
+ * a non-member, a held v2 message) has group_id NULL and so falls here:
212
+ * its group tag is sealed. Pass explicit pairs when that matters;
213
+ * { groupId } — either pillar-group version's stored group_id.
214
+ * Retains routing metadata, ids, seqs, hashes and cursor positions as
215
+ * duplicate tombstones. Counts only newly erased rows.
216
+ *
217
+ * SQLite cannot commit, vacuum and truncate WAL in one atomic operation. A pinned
218
+ * snapshot fails the preflight without changing rows. A racing snapshot
219
+ * after commit throws with committed=true and counts in error.erased:
220
+ * release the snapshot and retry the SAME selector to finish the scrub.
221
+ * Success means both logs committed and the WAL was truncated, not that
222
+ * backups, old JS views, or storage-device snapshots have been erased.
223
+ */
224
+ eraseRows(selector) {
225
+ const bad = () => new TypeError("eraseRows: provide exactly one non-empty selector: pairs [{sender, envelope_id}], conversation, or groupId");
226
+ if (!selector || typeof selector !== "object" || Array.isArray(selector)) throw bad();
227
+ const keys = Object.keys(selector);
228
+ if (keys.length !== 1 || !["pairs", "conversation", "groupId"].includes(keys[0])) throw bad();
229
+ const nonempty = (v) => typeof v === "string" && v.trim().length > 0;
230
+ const mode = keys[0];
231
+ let pairs;
232
+ if (mode === "pairs") {
233
+ if (!Array.isArray(selector.pairs) || !selector.pairs.length) throw bad();
234
+ pairs = Array.from(selector.pairs, (p) => {
235
+ if (!p || typeof p !== "object" || Array.isArray(p) ||
236
+ Object.keys(p).length !== 2 || !nonempty(p.sender) || !nonempty(p.envelope_id)) throw bad();
237
+ return { sender: p.sender, envelope_id: p.envelope_id };
238
+ });
239
+ } else if (!nonempty(selector[mode])) throw bad();
240
+ if (this.db.inTransaction) throw new Error("eraseRows: cannot run inside an existing transaction");
241
+
242
+ // This connection keeps secure_delete ON after erasure. It costs extra
243
+ // writes, but later changes on this connection must not retain old bytes.
244
+ this.db.pragma("secure_delete = ON");
245
+ const timeout = this.db.pragma("busy_timeout", { simple: true });
246
+ const counts = { inbox: 0, outbox: 0 };
247
+ let committed = false;
248
+ const checkpoint = () => {
249
+ const result = this.db.pragma("wal_checkpoint(TRUNCATE)")[0];
250
+ if (result.busy) throw new Error("another connection holds a SQLite snapshot; release it and retry eraseRows");
251
+ };
252
+ try {
253
+ this.db.pragma("busy_timeout = 100");
254
+ checkpoint();
255
+ this.db.transaction(() => {
256
+ for (const table of ["inbox", "outbox"]) {
257
+ const where = mode === "pairs"
258
+ ? (table === "inbox" ? "sender = ? and envelope_id = ?"
259
+ : "coalesce(json_extract(envelope_json, '$.sender'), json_extract(envelope_json, '$.from'), 'unknown') = ? and envelope_id = ?")
260
+ : mode === "conversation" ? `${table === "inbox" ? "sender" : "recipient"} = ? and group_id is null` : "group_id = ?";
261
+ const update = this.db.prepare(`update ${table} set envelope_json = ?
262
+ where ${LIVE_ENVELOPE_SQL} and (${where})`);
263
+ const bindings = mode === "pairs" ? pairs.map((p) => [p.sender, p.envelope_id]) : [[selector[mode]]];
264
+ for (const args of bindings) counts[table] += update.run(ERASED_ENVELOPE_JSON, ...args).changes;
265
+ }
266
+ }).immediate();
267
+ committed = true;
268
+ // secure_delete clears current cells, not pages freed by an earlier
269
+ // re-key/old-code update while it was OFF. Compact away that historical
270
+ // residue too. Explicit INTEGER PRIMARY KEY seqs survive VACUUM.
271
+ // This is physical maintenance, not a second logical erase transaction.
272
+ this.db.exec("vacuum");
273
+ checkpoint(); // Also on idempotent retry: a prior post-commit scrub may have failed.
274
+ return counts;
275
+ } catch (cause) {
276
+ const error = new Error(`eraseRows: ${committed ? "rows committed, disk scrub incomplete" : "nothing erased"}: ${cause.message}`, { cause });
277
+ error.code = committed ? "ERASE_CHECKPOINT_INCOMPLETE" : "ERASE_ABORTED";
278
+ error.committed = committed;
279
+ error.erased = committed ? counts : { inbox: 0, outbox: 0 };
280
+ throw error;
281
+ } finally {
282
+ this.db.pragma(`busy_timeout = ${timeout}`);
283
+ }
284
+ }
195
285
 
196
286
  /** Carrier polling cursors: carrier URL -> highest seq we have consumed. */
197
287
  getCarrierCursors() {
@@ -312,29 +402,32 @@ export class Mailbox {
312
402
  inboxTip() { return this._getHead("inbox") ?? "0".repeat(64); }
313
403
 
314
404
  outboxSince(seq = 0, limit = 100) {
315
- return this.db.prepare("select * from outbox where seq > ? order by seq asc limit ?").all(seq, limit);
405
+ return this.db.prepare(`select * from outbox where seq > ? and ${LIVE_ENVELOPE_SQL} order by seq asc limit ?`).all(seq, limit);
316
406
  }
317
407
  inboxSince(seq = 0, limit = 100) {
318
- return this.db.prepare("select * from inbox where seq > ? order by seq asc limit ?").all(seq, limit);
408
+ return this.db.prepare(`select * from inbox where seq > ? and ${LIVE_ENVELOPE_SQL} order by seq asc limit ?`).all(seq, limit);
319
409
  }
320
410
 
321
411
  /** Envelopes never shown to the operator (read_at null, not quarantined). Oldest first. */
322
412
  inboxUnread(limit = 100) {
323
- return this.db.prepare("select * from inbox where read_at is null and quarantined is null order by seq asc limit ?").all(limit);
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);
324
414
  }
325
415
 
326
416
  /** Trust-gated envelopes: stored as evidence, never surfaced to handlers. */
327
417
  inboxQuarantined(limit = 100) {
328
- return this.db.prepare("select * from inbox where quarantined is not null order by seq asc limit ?").all(limit);
418
+ return this.db.prepare(`select * from inbox where quarantined is not null and ${LIVE_ENVELOPE_SQL} order by seq asc limit ?`).all(limit);
329
419
  }
330
420
 
331
- /** Without `sender`, every row under the id is quarantined (the safe side). */
421
+ /**
422
+ * Without `sender`, every row under the id is quarantined (the safe side).
423
+ * An erased row is left as it is (C4): its quarantine state is evidence.
424
+ */
332
425
  markQuarantined(envelopeId, reason, sender) {
333
426
  const r = String(reason).slice(0, 100);
334
427
  if (sender === undefined) {
335
- this.db.prepare("update inbox set quarantined = ? where envelope_id = ?").run(r, envelopeId);
428
+ this.db.prepare(`update inbox set quarantined = ? where envelope_id = ? and ${LIVE_ENVELOPE_SQL}`).run(r, envelopeId);
336
429
  } else {
337
- this.db.prepare("update inbox set quarantined = ? where envelope_id = ? and sender = ?").run(r, envelopeId, sender);
430
+ this.db.prepare(`update inbox set quarantined = ? where envelope_id = ? and sender = ? and ${LIVE_ENVELOPE_SQL}`).run(r, envelopeId, sender);
338
431
  }
339
432
  }
340
433
 
@@ -402,12 +495,12 @@ export class Mailbox {
402
495
  let changes = 0;
403
496
  this.db.transaction(() => {
404
497
  if (sender === undefined) {
405
- const n = this.db.prepare("select count(*) as n from inbox where envelope_id = ? and quarantined is not null").get(envelopeId).n;
498
+ const n = this.db.prepare(`select count(*) as n from inbox where envelope_id = ? and quarantined is not null and ${LIVE_ENVELOPE_SQL}`).get(envelopeId).n;
406
499
  if (n > 1) throw new Error(`releaseQuarantined: ${n} senders hold envelope ${envelopeId} quarantined; name the sender`);
407
500
  }
408
501
  const tip = this._seqFloor();
409
502
  const where = sender === undefined ? "envelope_id = ?" : "envelope_id = ? and sender = ?";
410
- changes = this.db.prepare(`update inbox set quarantined = null, released_seq = ? where ${where} and quarantined is not null`)
503
+ changes = this.db.prepare(`update inbox set quarantined = null, released_seq = ? where ${where} and quarantined is not null and ${LIVE_ENVELOPE_SQL}`)
411
504
  .run(tip + 1, envelopeId, ...(sender === undefined ? [] : [sender])).changes;
412
505
  if (changes > 0) {
413
506
  this.db.prepare("update sqlite_sequence set seq = max(seq, ?) where name = 'inbox'")
@@ -430,18 +523,22 @@ export class Mailbox {
430
523
  markInboxRead(envelopeId, sender) {
431
524
  const at = new Date().toISOString();
432
525
  if (sender === undefined) {
433
- this.db.prepare("update inbox set read_at = ? where envelope_id = ? and read_at is null").run(at, envelopeId);
526
+ this.db.prepare(`update inbox set read_at = ? where envelope_id = ? and read_at is null and ${LIVE_ENVELOPE_SQL}`).run(at, envelopeId);
434
527
  } else {
435
- this.db.prepare("update inbox set read_at = ? where envelope_id = ? and sender = ? and read_at is null").run(at, envelopeId, sender);
528
+ this.db.prepare(`update inbox set read_at = ? where envelope_id = ? and sender = ? and read_at is null and ${LIVE_ENVELOPE_SQL}`).run(at, envelopeId, sender);
436
529
  }
437
530
  }
438
531
 
439
- /** Without `sender`, every row under the id is tagged. */
532
+ /**
533
+ * Without `sender`, every row under the id is tagged. An erased row keeps
534
+ * the group_id it had when erased (C4): filing it now would move it into
535
+ * another selector's reach after the user's erase.
536
+ */
440
537
  setInboundGroup(envelopeId, groupId, sender) {
441
538
  if (sender === undefined) {
442
- this.db.prepare("update inbox set group_id = ? where envelope_id = ?").run(groupId, envelopeId);
539
+ this.db.prepare(`update inbox set group_id = ? where envelope_id = ? and ${LIVE_ENVELOPE_SQL}`).run(groupId, envelopeId);
443
540
  } else {
444
- this.db.prepare("update inbox set group_id = ? where envelope_id = ? and sender = ?").run(groupId, envelopeId, sender);
541
+ this.db.prepare(`update inbox set group_id = ? where envelope_id = ? and sender = ? and ${LIVE_ENVELOPE_SQL}`).run(groupId, envelopeId, sender);
445
542
  }
446
543
  }
447
544
 
@@ -468,7 +565,7 @@ export class Mailbox {
468
565
  inboxAfter(seq = 0, limit = 500) {
469
566
  return this.db.prepare(`
470
567
  select * from inbox
471
- where coalesce(released_seq, seq) > ? and quarantined is null
568
+ where coalesce(released_seq, seq) > ? and quarantined is null and ${LIVE_ENVELOPE_SQL}
472
569
  order by coalesce(released_seq, seq) asc limit ?
473
570
  `).all(seq, limit);
474
571
  }
@@ -527,7 +624,7 @@ export class Mailbox {
527
624
  markOutboundAcked(envelopeId, { from, ackId = null, at = null }) {
528
625
  const r = this.db.prepare(`
529
626
  update outbox set recipient_ack_at = coalesce(recipient_ack_at, ?), recipient_ack_id = coalesce(recipient_ack_id, ?)
530
- where envelope_id = ? and recipient = ?
627
+ where envelope_id = ? and recipient = ? and ${LIVE_ENVELOPE_SQL}
531
628
  `).run(at ?? new Date().toISOString(), ackId, envelopeId, from);
532
629
  return r.changes > 0;
533
630
  }
@@ -537,7 +634,7 @@ export class Mailbox {
537
634
  const ts = at ?? new Date().toISOString();
538
635
  const stmt = this.db.prepare(`
539
636
  update outbox set recipient_read_at = coalesce(recipient_read_at, ?), recipient_ack_at = coalesce(recipient_ack_at, ?)
540
- where envelope_id = ?
637
+ where envelope_id = ? and ${LIVE_ENVELOPE_SQL}
541
638
  `);
542
639
  let n = 0;
543
640
  this.db.transaction(() => { for (const id of envelopeIds) n += stmt.run(ts, ts, id).changes; })();
@@ -546,11 +643,11 @@ export class Mailbox {
546
643
 
547
644
  /** Outbound rows to one recipient, oldest first (receipt matching). */
548
645
  outboundTo(recipient) {
549
- return this.db.prepare("select * from outbox where recipient = ? order by seq asc").all(recipient);
646
+ return this.db.prepare(`select * from outbox where recipient = ? and ${LIVE_ENVELOPE_SQL} order by seq asc`).all(recipient);
550
647
  }
551
648
 
552
649
  outboxRecent(limit = 20) {
553
- return this.db.prepare("select * from outbox order by seq desc limit ?").all(limit);
650
+ return this.db.prepare(`select * from outbox where ${LIVE_ENVELOPE_SQL} order by seq desc limit ?`).all(limit);
554
651
  }
555
652
 
556
653
  // ── Groups (pillar-group v1 rosters, INTERACTION-CONVENTION.md) ───────────
@@ -605,11 +702,11 @@ export class Mailbox {
605
702
  }
606
703
 
607
704
  groupInbound(groupId, limit = 50) {
608
- return this.db.prepare("select * from inbox where group_id = ? and quarantined is null order by seq desc limit ?").all(groupId, limit).reverse();
705
+ 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();
609
706
  }
610
707
 
611
708
  groupOutbound(groupId, limit = 200) {
612
- return this.db.prepare("select * from outbox where group_id = ? order by seq desc limit ?").all(groupId, limit).reverse();
709
+ return this.db.prepare(`select * from outbox where group_id = ? and ${LIVE_ENVELOPE_SQL} order by seq desc limit ?`).all(groupId, limit).reverse();
613
710
  }
614
711
 
615
712
  /**
@@ -8,6 +8,7 @@
8
8
  import { envelopeBodyBytes, preflightBodyBytes } from "../blob/blob.mjs";
9
9
  import { seedTier } from "./seed-tier.mjs";
10
10
  import { carrierFix, REFUSAL_FIXES } from "./refusals.mjs";
11
+ import { setTimeout as sleepTimer } from "node:timers/promises";
11
12
 
12
13
  /**
13
14
  * Rank carriers by how proven they are, best first. Unknown carriers rank as
@@ -65,7 +66,7 @@ export class CarrierClient {
65
66
  this.tierGrantB64 = tierGrant
66
67
  ? Buffer.from(JSON.stringify(tierGrant), "utf-8").toString("base64")
67
68
  : null;
68
- this._stopPolling = false;
69
+ this._pollingDone = Promise.resolve();
69
70
  }
70
71
 
71
72
  get uuaid() { return this.keychain._identity.uuaid; }
@@ -187,33 +188,49 @@ export class CarrierClient {
187
188
 
188
189
  /**
189
190
  * Long-poll every carrier in parallel forever, invoking onEnvelope for each
190
- * new envelope. Tracks per-carrier cursor. Returns a stop() function.
191
+ * new envelope. Tracks per-carrier cursor. Returns { stop, cursors, done }.
192
+ * stop() aborts fetches/backoff and resolves after this run's handlers end.
193
+ * Stop the old handle before starting again; a new run waits for all prior
194
+ * runs to finish, including handlers already in progress.
191
195
  * onError(error, { carrier }) — the carrier context is passed so callers
192
196
  * can attribute failures per carrier in metrics.
197
+ * random(): [0, 1) and sleep(ms, value, { signal }) (node:timers/promises
198
+ * signature) are injectable for deterministic jitter/backoff tests.
193
199
  */
194
- startPolling({ onEnvelope, cursors = {}, waitS = 25, onError }) {
195
- this._stopPolling = false;
200
+ startPolling({ onEnvelope, cursors = {}, waitS = 25, onError, random = Math.random, sleep = sleepTimer }) {
201
+ const controller = new AbortController();
202
+ const { signal } = controller;
203
+ const previous = this._pollingDone;
196
204
  const state = { cursors: { ...cursors } };
197
205
  const loops = this.carriers.map(async (base) => {
198
- while (!this._stopPolling) {
206
+ // Aborting a fetch does not synchronously finish its promise/handler.
207
+ // Do not open its replacement until that run has actually finished.
208
+ await previous;
209
+ while (!signal.aborted) {
199
210
  try {
200
- const r = await this.fetchInbox(base, { since: state.cursors[base] ?? 0, waitS });
211
+ const r = await this.fetchInbox(base, { since: state.cursors[base] ?? 0, waitS, signal });
201
212
  for (const { seq, envelope } of r.envelopes) {
213
+ if (signal.aborted) break;
202
214
  state.cursors[base] = Math.max(state.cursors[base] ?? 0, seq);
203
215
  try { await onEnvelope(envelope, { carrier: base, seq }); }
204
216
  catch (e) { onError?.(new Error(`onEnvelope threw: ${e.message}`), { carrier: base }); }
205
217
  }
206
218
  } catch (e) {
219
+ if (signal.aborted) break;
207
220
  onError?.(e, { carrier: base });
208
- // Back off on error so a dead carrier doesn't spin the CPU.
209
- await new Promise(r2 => setTimeout(r2, 2000));
221
+ if (signal.aborted) break;
222
+ // 2 seconds plus uniform [0, 2 seconds) jitter avoids a retry herd.
223
+ try { await sleep(2000 + Math.floor(random() * 2000), undefined, { signal }); }
224
+ catch (error) { if (!signal.aborted) throw error; }
210
225
  }
211
226
  }
212
227
  });
228
+ const done = Promise.allSettled(loops);
229
+ this._pollingDone = done;
213
230
  return {
214
- stop: () => { this._stopPolling = true; },
231
+ stop: () => { controller.abort(); return done; },
215
232
  cursors: () => ({ ...state.cursors }),
216
- done: Promise.allSettled(loops),
233
+ done,
217
234
  };
218
235
  }
219
236
  }
@@ -106,7 +106,7 @@ export function withCarrierFix(status, body) {
106
106
  * terminal. Every other character is printed as received.
107
107
  */
108
108
  function oneLine(value) {
109
- return String(value).replace(/[\u0000-\u001f\u007f-\u009f]+/g, " ").trim();
109
+ return String(value).replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029]+/g, " ").trim();
110
110
  }
111
111
 
112
112
  /**
@@ -2,8 +2,9 @@
2
2
  * Transport — libp2p node that speaks the UUAID pillar protocol.
3
3
  *
4
4
  * Design:
5
- * - The pillar's Ed25519 identity IS the libp2p PeerId (same private key).
6
- * One identity, one keypair, one signature primitive across every layer.
5
+ * - The transport PeerId uses a secp256k1 key read from the pillar's
6
+ * 32-byte seed. It differs from the Ed25519 identity used to sign
7
+ * envelopes; peerIdFromSeedHex derives the transport PeerId.
7
8
  * - Kad-DHT is used for two things:
8
9
  * 1. Peer routing (find PeerId -> multiaddrs)
9
10
  * 2. Content routing (publish a UUAID -> hash mapping so anyone can
@@ -38,7 +39,7 @@ export const PILLAR_PROTOCOL = "/uuaid/pillar/1.0.0";
38
39
  export const DHT_PROTOCOL_PREFIX = "/uuaid";
39
40
 
40
41
  /**
41
- * Build a libp2p node bound to the pillar's Ed25519 identity.
42
+ * Build a libp2p node with the seed-derived secp256k1 transport identity.
42
43
  *
43
44
  * @param {{seedHex: string, listenAddrs?: string[], bootstrapPeers?: string[], enableRelay?: boolean, dhtClientMode?: boolean}} opts
44
45
  */
@@ -111,8 +112,10 @@ export function peerIdFromSeedHex(seedHex) {
111
112
  }
112
113
 
113
114
  /**
114
- * Convert a raw Ed25519 public key hex to a libp2p PeerId. This is how
115
- * a peer given only a UUAID's public key can dial that peer.
115
+ * Convert a raw Ed25519 public key hex to its Ed25519 libp2p PeerId.
116
+ * This conversion does not identify the node started by createTransport,
117
+ * which uses a seed-derived secp256k1 key. Use peerIdFromSeedHex for that
118
+ * node; a UUAID's Ed25519 public key alone cannot derive its transport PeerId.
116
119
  */
117
120
  export function peerIdFromEd25519Hex(publicKeyHex) {
118
121
  const raw = Buffer.from(publicKeyHex, "hex");
package/src/pillar.mjs CHANGED
@@ -20,7 +20,7 @@ import * as raw from "multiformats/codecs/raw";
20
20
  import { sha256 } from "multiformats/hashes/sha2";
21
21
  import { createTransport, PILLAR_PROTOCOL, uuaidToDhtKey, peerIdFromEd25519Hex } from "./net/transport.mjs";
22
22
  import { seal, open, decrypt, envelopeSha, mkEnvelopeId, ENVELOPE_VERSION } from "./net/envelope.mjs";
23
- import { Mailbox } from "./mailbox/mailbox.mjs";
23
+ import { Mailbox, isErasedRow } from "./mailbox/mailbox.mjs";
24
24
  import { CarrierClient } from "./net/carrier-client.mjs";
25
25
  import { REFUSAL_FIXES } from "./net/refusals.mjs";
26
26
  import { Observability } from "./observability.mjs";
@@ -74,6 +74,7 @@ export class Pillar {
74
74
  this.carriers = carriers;
75
75
  this.carrierClient = carriers.length ? new CarrierClient({ keychain, carriers, tierGrant }) : null;
76
76
  this._carrierPoller = null;
77
+ this._carrierStopping = Promise.resolve();
77
78
  this.enableLibp2p = enableLibp2p;
78
79
  this.cryptoInventory = cryptoInventory;
79
80
  this.node = null;
@@ -178,7 +179,7 @@ export class Pillar {
178
179
  }
179
180
 
180
181
  async stop() {
181
- this.stopCarrierPolling();
182
+ await this.stopCarrierPolling();
182
183
  if (!this.node) { this.mailbox.close(); return; }
183
184
  for (const push of this._openStreams.values()) { try { push.end(); } catch (_e) {} }
184
185
  this._openStreams.clear();
@@ -559,34 +560,83 @@ export class Pillar {
559
560
  }
560
561
 
561
562
  stopCarrierPolling() {
562
- if (this._carrierPoller) { this._carrierPoller.stop(); this._carrierPoller = null; }
563
+ if (this._carrierPoller) {
564
+ this._carrierStopping = this._carrierPoller.stop();
565
+ this._carrierPoller = null;
566
+ }
567
+ return this._carrierStopping;
563
568
  }
564
569
 
565
570
  /**
566
571
  * One-shot inbox pull: fetch every pending envelope from every carrier
567
572
  * (no long-poll) through the same verification + mailbox + handler
568
573
  * pipeline, then return. Complements startCarrierPolling for CLI /
569
- * cron-style "check my mail now" callers. Returns envelopes fetched.
574
+ * cron-style "check my mail now" callers. Returns envelopes fetched
575
+ * (a number, duplicates included), as every release before 2.6.0 did.
576
+ *
577
+ * timeoutMs bounds EACH carrier request (default 40000 ms); it is not a
578
+ * deadline for the whole drain or for handlers
579
+ * signal an AbortSignal that ends the whole drain
580
+ *
581
+ * Every carrier is tried, each on its own (2.6.0): one that fails no longer
582
+ * keeps the mail of the carriers after it from being stored. When any
583
+ * failed, the drain throws ONCE, after the last carrier was tried. The
584
+ * thrown error is the first failure itself, with two properties added:
585
+ * drained envelopes stored by this call (healthy carriers' mail, and the
586
+ * pages a failed carrier served before it failed);
587
+ * errors [{ carrier, error }], one per carrier that did not finish, in
588
+ * carrier order. Not enumerable: errors[0].error is the thrown
589
+ * error itself, and JSON.stringify(err) must not meet that cycle.
590
+ * A failure that is not an extensible object (or already has its own
591
+ * `drained`/`errors`) is wrapped in an Error whose `cause` is the original.
592
+ * So `errors.length === carriers.length` means no carrier finished; fewer
593
+ * means the others' mail is stored and their cursors moved.
594
+ * An aborted signal ends the drain: the carrier it interrupted and every
595
+ * carrier after it (not fetched) are listed with the abort reason.
596
+ * Already processed mail and cursors are kept; an in-progress _receive or
597
+ * handler is allowed to finish.
570
598
  */
571
- async drainCarrierInbox() {
599
+ async drainCarrierInbox({ timeoutMs = null, signal = null } = {}) {
572
600
  if (!this.carrierClient) return 0;
601
+ if (timeoutMs != null && !(typeof timeoutMs === "number" && Number.isFinite(timeoutMs) && timeoutMs >= 0)) {
602
+ throw new TypeError(`drainCarrierInbox: timeoutMs must be a finite number of ms, 0 or more, not ${String(timeoutMs)}`);
603
+ }
604
+ const perFetchMs = timeoutMs ?? 40000;
573
605
  let total = 0;
606
+ const errors = [];
574
607
  const cursors = this.mailbox.getCarrierCursors?.() ?? {};
575
608
  for (const base of this.carriers) {
576
609
  let since = cursors[base] ?? 0;
577
- for (;;) { // carrier pages at 200/fetch — loop until an empty page
578
- const r = await this.carrierClient.fetchInbox(base, { since, waitS: 0 });
579
- if (!r.envelopes.length) break;
580
- for (const { seq, envelope } of r.envelopes) {
581
- await this._receive(JSON.stringify(envelope), null);
582
- this.mailbox.setCarrierCursor?.(base, seq);
583
- since = Math.max(since, seq);
584
- total++;
585
- this.metrics.inc(`carrier.drain.${base}`);
610
+ try {
611
+ for (;;) { // carrier pages at 200/fetch — loop until an empty page
612
+ signal?.throwIfAborted();
613
+ const r = await this.carrierClient.fetchInbox(base, { since, waitS: 0, timeoutMs: perFetchMs, signal });
614
+ signal?.throwIfAborted();
615
+ if (!r.envelopes.length) break;
616
+ for (const { seq, envelope } of r.envelopes) {
617
+ signal?.throwIfAborted();
618
+ await this._receive(JSON.stringify(envelope), null);
619
+ this.mailbox.setCarrierCursor?.(base, seq);
620
+ since = Math.max(since, seq);
621
+ total++;
622
+ this.metrics.inc(`carrier.drain.${base}`);
623
+ }
586
624
  }
625
+ } catch (error) {
626
+ errors.push({ carrier: base, error });
627
+ this.metrics.inc(`carrier.drain.error.${base}`);
587
628
  }
588
629
  }
589
- return total;
630
+ if (!errors.length) return total;
631
+ const first = errors[0].error;
632
+ const reusable = first !== null && typeof first === "object" && Object.isExtensible(first)
633
+ && !Object.hasOwn(first, "drained") && !Object.hasOwn(first, "errors");
634
+ const err = reusable
635
+ ? first
636
+ : new Error(`drainCarrierInbox: ${errors[0].carrier}: ${first?.message ?? String(first)}`, { cause: first });
637
+ err.drained = total;
638
+ Object.defineProperty(err, "errors", { value: errors, enumerable: false, writable: true, configurable: true });
639
+ throw err;
590
640
  }
591
641
 
592
642
  async _deliverToPeer(envelope, peerIdStr, multiaddrStr) {
@@ -802,11 +852,15 @@ export class Pillar {
802
852
  async _settleHeldGroupV2(ref, verdict, reason, groupId) {
803
853
  if (!ref?.id) return;
804
854
  const { id: envelopeId, sender } = ref;
855
+ // An erased held row stays erased (C4): no release to the readers, no
856
+ // filing under the group, no re-quarantine and no handler. The mailbox
857
+ // calls below are no-ops on it too; this skips them outright.
858
+ if (isErasedRow(this.mailbox.getInbound(envelopeId, sender))) { this.metrics.inc("group-v2.settle.erased"); return; }
805
859
  if (verdict !== "accepted") { this.mailbox.markQuarantined(envelopeId, `group-v2:${reason ?? verdict}`, sender); return; }
806
860
  this.mailbox.clearQuarantine(envelopeId, sender);
807
861
  this.mailbox.setInboundGroup(envelopeId, groupId, sender);
808
862
  const row = this.mailbox.getInbound(envelopeId, sender);
809
- if (!row) return;
863
+ if (!row || isErasedRow(row)) return; // marker-safe reader (C6): the tombstone is not an envelope
810
864
  const envelope = JSON.parse(row.envelope_json);
811
865
  let payload;
812
866
  try { payload = decrypt(this.keychain, envelope); } catch { return; }
@@ -867,14 +921,20 @@ export class Pillar {
867
921
  */
868
922
  async sendReadReceipts(views) {
869
923
  if (!this.receipts.read) return { sent: 0, skipped: 0, dropped: 0 };
924
+ const isErased = (v) => v && isErasedRow(this.mailbox.getInbound(v.id, v.sender));
925
+ views = views.filter((v) => !isErased(v));
870
926
  const { receipts, dropped } = planReadReceipts(views, { self: this.uuaid });
871
927
  let sent = 0, skipped = 0;
872
928
  for (const r of receipts) {
873
- const source = views.find((v) => v.id === r.upTo);
929
+ const source = views.find((v) => v?.id === r.upTo && v.sender === r.to);
874
930
  const tag = source?.groupId ? { id: source.groupId } : null;
875
931
  if (!this._isReceiptPeer(r.to, tag)) { skipped++; continue; }
876
932
  try {
877
- await this.send({ recipient: r.to, recipientPublicKey: this._sealKeyFor(r.to, source, tag), ...readReceipt(r) });
933
+ const spec = { recipient: r.to, recipientPublicKey: this._sealKeyFor(r.to, source, tag), ...readReceipt(r) };
934
+ // A previous send may have yielded while this row was erased.
935
+ // No asynchronous gap is allowed between this admission check and send.
936
+ if (isErased(source)) { skipped++; continue; }
937
+ await this.send(spec);
878
938
  sent++;
879
939
  } catch (e) {
880
940
  skipped++;
package/src/receipts.mjs CHANGED
@@ -20,6 +20,8 @@
20
20
  * Sending either is opt-in (config.json `receipts`), and only ever to a
21
21
  * contact: acking a stranger would confirm the address is live.
22
22
  */
23
+ import { isErasedRow } from "./mailbox/mailbox.mjs";
24
+
23
25
  export const READ_RECEIPT_TYPE = "pillar-read-receipt";
24
26
  export const MAX_READ_RECEIPTS_PER_RUN = 64;
25
27
 
@@ -94,7 +96,9 @@ export function applyReceipt(mailbox, envelope, payload, { applyRead = true } =
94
96
  const from = envelope.sender;
95
97
  if (isReadReceipt(payload)) {
96
98
  if (!applyRead) return { kind: "read", marked: 0, ignored: "read-receipts-off" };
97
- const rows = mailbox.outboundTo(from);
99
+ // Erased rows are neither anchors nor candidates (C6). Mailbox#outboundTo
100
+ // already omits them; this holds for any listing a caller passes in.
101
+ const rows = mailbox.outboundTo(from).filter((r) => !isErasedRow(r));
98
102
  const cited = rows.find((r) => r.envelope_id === payload.thread);
99
103
  let candidates;
100
104
  let cutoffRow;
@@ -121,13 +125,19 @@ export function applyReceipt(mailbox, envelope, payload, { applyRead = true } =
121
125
  return { kind: null, marked: 0 };
122
126
  }
123
127
 
124
- /** True when an inbound ack/reply answers something we sent to its sender. */
128
+ /**
129
+ * True when an inbound ack/reply answers something we sent to its sender.
130
+ * An erased send answers nothing (C6): the trust-gate exemption exists so the
131
+ * answer to a message we hold can reach us; once that message is erased its
132
+ * id must not keep letting the counterparty past the gate. (Its ack and read
133
+ * times are not updated either: markOutboundAcked/Read skip tombstones.)
134
+ */
125
135
  export function answersOurSend(mailbox, envelope, payload) {
126
136
  if (envelope.kind !== "ack" && envelope.kind !== "reply") return false;
127
137
  const sentTo = (id) => {
128
138
  if (typeof id !== "string" || !id) return false;
129
139
  const row = mailbox.getOutbound(id);
130
- return !!row && row.recipient === envelope.sender;
140
+ return !!row && !isErasedRow(row) && row.recipient === envelope.sender;
131
141
  };
132
142
  if (sentTo(payload?.inReplyTo)) return true;
133
143
  return envelope.kind === "ack" && isReadReceipt(payload) && (sentTo(payload.thread) || sentTo(payload.upTo));