@uuaid/pillar 2.6.0 → 2.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/HOSTING-LIMITS.md +12 -0
  2. package/README.md +201 -5
  3. package/bin/carrier.mjs +72 -2
  4. package/bin/pillar-ask.mjs +4 -1
  5. package/bin/pillar-blob.mjs +6 -0
  6. package/bin/pillar-directory.mjs +280 -16
  7. package/bin/pillar-escrow.mjs +4 -1
  8. package/bin/pillar-group-v2.mjs +6 -0
  9. package/bin/pillar-notify.mjs +13 -0
  10. package/bin/pillar-responder.mjs +266 -23
  11. package/bin/pillar.mjs +504 -255
  12. package/package.json +17 -25
  13. package/src/cli-help.mjs +23 -0
  14. package/src/group-v2-cli.mjs +1 -1
  15. package/src/identity/trust.mjs +72 -6
  16. package/src/mailbox/mailbox.mjs +308 -12
  17. package/src/net/carrier-server.mjs +34 -2
  18. package/src/net/refusals.mjs +2 -0
  19. package/src/net/seed-registry.mjs +2 -1
  20. package/src/net/transport.mjs +308 -92
  21. package/src/node-check.mjs +29 -8
  22. package/src/notify-events.mjs +148 -0
  23. package/src/notify-log.mjs +124 -0
  24. package/src/notify-runner.mjs +372 -0
  25. package/src/notify-store.mjs +725 -0
  26. package/src/notify.mjs +350 -0
  27. package/src/pillar.mjs +382 -27
  28. package/src/readers.mjs +2 -2
  29. package/src/registry/federation.mjs +3056 -0
  30. package/src/registry/gossip.mjs +294 -0
  31. package/src/registry/heartbeats.mjs +195 -0
  32. package/src/registry/lineage-verifier.mjs +972 -0
  33. package/src/registry/lineage.mjs +984 -0
  34. package/src/registry/listings.mjs +549 -0
  35. package/src/registry/resolve.mjs +376 -0
  36. package/src/registry/stats.mjs +508 -0
  37. package/src/sqlite-loader.mjs +40 -0
  38. package/src/vendor/pillar-core.mjs +22 -0
  39. package/src/vendor/uuaid-soul.mjs +2246 -0
  40. package/src/vnext/a6b-common.mjs +270 -0
  41. package/src/vnext/b1-cli.mjs +970 -0
  42. package/src/vnext/card-cli.mjs +370 -0
  43. package/src/vnext/greeter-operator.mjs +160 -0
  44. package/src/vnext/greeter-suggest.mjs +318 -0
  45. package/src/vnext/greeter.mjs +571 -0
  46. package/src/vnext/homes.mjs +48 -0
  47. package/src/vnext/init-cli.mjs +489 -0
  48. package/src/vnext/intro-cli.mjs +81 -0
  49. package/src/vnext/json-dir-mailbox.mjs +296 -0
  50. package/src/vnext/jsonl-mailbox.mjs +1066 -0
  51. package/src/vnext/knock-answer.mjs +162 -0
  52. package/src/vnext/knock-cli.mjs +520 -0
  53. package/src/vnext/knock-lane.mjs +312 -0
  54. package/src/vnext/knock-responder.mjs +344 -0
  55. package/src/vnext/lineage-cli.mjs +653 -0
  56. package/src/vnext/listing-cli.mjs +323 -0
  57. package/src/vnext/resolve-cli.mjs +86 -0
  58. package/src/vnext/soul-cli.mjs +666 -0
  59. package/src/vnext/verify-cli.mjs +251 -0
  60. package/src/vnext/w4-redirect.mjs +178 -0
  61. package/src/vnext/wave-a.mjs +193 -0
  62. package/src/vnext/witness-cli.mjs +547 -0
package/bin/pillar.mjs CHANGED
@@ -10,9 +10,12 @@
10
10
  * pillar send <recipient|name> <kind> <json> [--wait-ack S]
11
11
  * send a signed envelope; optionally wait for the recipient's signed ack
12
12
  * pillar recv [--home ~/.pillar] [--reader NAME] listen for envelopes and print them
13
+ * pillar recv --notify also the home's resident wake path (hook: config.json notify.hook)
13
14
  * pillar inbox [--home ~/.pillar] [--reader NAME] [--unread] [--notify CMD] [--mark-read]
14
15
  * one-shot: pull pending mail, print, exit
15
16
  * pillar wait [--reader NAME] [--timeout S] sleep until there is mail, print the count, exit 0 (3 on timeout)
17
+ * pillar notify [--fleet FILE] one-shot new-mail notices (fallback; never pulls or stores)
18
+ * pillar notify --print-unit launchd|systemd print a resident `recv --notify` unit; installs nothing
16
19
  * pillar readers every reader of this home, its cursor and any live lease
17
20
  * pillar status [envelope-id] [--wait S] outbox: carrier acceptance and the recipient's signed receipts
18
21
  * pillar receipts [on|off|delivered on|off|read on|off] send signed acks / read receipts (off by default)
@@ -29,13 +32,14 @@
29
32
  * More than one process reading ONE home: give each its own --reader NAME
30
33
  * (or PILLAR_READER) so each has its own cursor; see src/readers.mjs.
31
34
  */
32
- import "../src/node-check.mjs"; // must stay the first import: refuses Node < 22 before any dependency loads
33
- import { mkdirSync, existsSync, readFileSync, writeFileSync, renameSync } from "node:fs";
34
- import { join, dirname } from "node:path";
35
+ import "../src/node-check.mjs"; // must stay the first import: refuses Node < 20 and polyfills Promise.withResolvers before any dependency loads
36
+ import { existsSync, readFileSync, writeFileSync } from "node:fs";
37
+ import { join, dirname, resolve as resolvePath } from "node:path";
38
+ import { fileURLToPath } from "node:url";
35
39
  import { homedir } from "node:os";
36
40
  import { argv, exit } from "node:process";
37
- import { Keychain, mintNamespace, SELF_CERTIFYING_NAMESPACES, localIdFromKey } from "../src/identity/keychain.mjs";
38
- import { peerIdFromSeedHex } from "../src/net/transport.mjs";
41
+ import { Keychain, localIdFromKey } from "../src/identity/keychain.mjs";
42
+ import { peerIdFromSeedHex, isP2pInstalled } from "../src/net/transport.mjs";
39
43
  import { Pillar } from "../src/pillar.mjs";
40
44
  import { loadFleetAddressBook, inspectFleetFile, resolveRecipient, explainMissingKey } from "../src/address-book.mjs";
41
45
  import { loadTrustPolicy, POLICIES } from "../src/identity/trust.mjs";
@@ -43,14 +47,28 @@ import { parseLinkOffer, isLinkOfferLive, LINK_GRANT_KINDS } from "../src/net/li
43
47
  import { mintDelegationDoc } from "../src/net/delegation.mjs";
44
48
  import { refusalLine } from "../src/net/refusals.mjs";
45
49
  import {
46
- readerKey, processContext, otherLiveLeases, processesWithMailboxOpen, describeProcess, describeReader, initialCursor, handleInOrder,
50
+ readerKey, processContext, otherLiveLeases, describeProcess, describeReader, initialCursor, handleInOrder,
47
51
  LEASE_TTL_MS, LEASE_HEARTBEAT_MS,
48
52
  } from "../src/readers.mjs";
49
53
  import { extractGroupTag, findGroup, normalizeMembers } from "../src/groups.mjs";
50
54
  import { describeOutboundStatus, receiptFor } from "../src/receipts.mjs";
51
55
  import { groupCommandRoute, groupRouteLookups, RosterStore } from "../src/groups-v2.mjs";
52
- import { runGroupV2 } from "../src/group-v2-cli.mjs";
56
+ import { GROUP_V2_USAGE, runGroupV2 } from "../src/group-v2-cli.mjs";
57
+ import { exitWithHelp, wantsHelp } from "../src/cli-help.mjs";
53
58
  import { Mailbox, isErasedRow } from "../src/mailbox/mailbox.mjs";
59
+ import { runVerifyCli } from "../src/vnext/verify-cli.mjs";
60
+ import { runInitCli } from "../src/vnext/init-cli.mjs";
61
+ import { runLineageCli } from "../src/vnext/lineage-cli.mjs";
62
+ import { runCardCli } from "../src/vnext/card-cli.mjs";
63
+ import { runIntroCli } from "../src/vnext/intro-cli.mjs";
64
+ import { runResolveCli } from "../src/vnext/resolve-cli.mjs";
65
+ import { runListingCli } from "../src/vnext/listing-cli.mjs";
66
+ import { runAnswerCli, runKnockCli, runKnocksCli } from "../src/vnext/knock-cli.mjs";
67
+ import { runSoulCli } from "../src/vnext/soul-cli.mjs";
68
+ import { notifyConfigFrom, isSafeId, isSafeUuaid, NOTIFY_BRIDGE_REFUSAL, recvWakeKind, recvNotifyMode, wakeRefusal } from "../src/notify.mjs";
69
+ import { NotifySink } from "../src/notify-events.mjs";
70
+ import { NotifyStore, WAKE_LOCK, releaseLock, guardLock } from "../src/notify-store.mjs";
71
+ import { Notifier, checkHook } from "../src/notify-runner.mjs";
54
72
 
55
73
  // JSON rendered as one text line (or embedded in a Zestro command). Preserve
56
74
  // parsed values while escaping the two separators JSON.stringify leaves raw.
@@ -100,7 +118,16 @@ function receiptsFor(args, cfg) {
100
118
  return { delivered: !!r.delivered || !!args.ack, read: !!r.read };
101
119
  }
102
120
 
103
- function loadPillar(args, { reader = null } = {}) {
121
+ /**
122
+ * notify: "auto" writes eligibility events when config.json has an enabled
123
+ * notify block; "off" never does (the one-shot notifier stores nothing).
124
+ * notifySink: a sink to use as given (pillar recv --notify).
125
+ */
126
+ const P2P_MISSING_NO_CARRIERS =
127
+ "p2p-not-installed: this home receives over libp2p and names no carrier, and @uuaid/pillar-p2p is not installed, so recv has no transport. " +
128
+ "Install it (npm i @uuaid/pillar-p2p), or name a carrier (pillar init --refresh --carriers <url>, or recv --carrier <url>)";
129
+
130
+ function openPillar(args, { reader = null, notify = "auto", notifySink = null, needsTransport = false } = {}) {
104
131
  const home = homePath(args);
105
132
  const kcPath = join(home, "keychain.json");
106
133
  const mbPath = join(home, "mailbox.db");
@@ -127,6 +154,17 @@ function loadPillar(args, { reader = null } = {}) {
127
154
  // attached to carrier delivers — raises budgets at carriers trusting the issuer.
128
155
  const tgPath = join(home, "tier-grant.json");
129
156
  const tierGrant = existsSync(tgPath) ? JSON.parse(readFileSync(tgPath, "utf-8")) : null;
157
+ const wantsLibp2p = args.libp2p === true || args.libp2p === "true" || args.libp2p === "1";
158
+ const explicitNoLibp2p = args.libp2p === false || args.libp2p === "false" || args.libp2p === "0";
159
+ const chosenCarrierOnly = explicitNoLibp2p || Boolean(args["carrier-only"]) || cfg.carrierOnly === true;
160
+ const carrierOnly = !wantsLibp2p && (chosenCarrierOnly || !isP2pInstalled());
161
+ // V1 F3: a libp2p home (2.6.1, or init --libp2p) that names no carrier,
162
+ // upgraded without @uuaid/pillar-p2p, has no transport left. recv would
163
+ // print carrier-only and exit 0 at once; it refuses instead.
164
+ if (needsTransport && carrierOnly && !chosenCarrierOnly && carriers.length === 0) {
165
+ console.error(P2P_MISSING_NO_CARRIERS);
166
+ exit(1);
167
+ }
130
168
  return new Pillar({
131
169
  keychain: kc,
132
170
  mailboxPath: mbPath,
@@ -135,14 +173,29 @@ function loadPillar(args, { reader = null } = {}) {
135
173
  enableRelay: cfg.enableRelay ?? false,
136
174
  dhtClientMode: cfg.dhtClientMode ?? true,
137
175
  carriers,
138
- enableLibp2p: !(args["carrier-only"] || cfg.carrierOnly === true),
176
+ enableLibp2p: !carrierOnly,
139
177
  trust,
140
178
  tierGrant,
141
179
  reader,
142
180
  receipts: receiptsFor(args, cfg),
181
+ notifySink: notifySink ?? notifySinkFor(home, cfg, notify),
143
182
  });
144
183
  }
145
184
 
185
+
186
+ /** The Zestro bridge is on for this run (cmdRecv starts it on exactly this condition). */
187
+ function zestroBridgeConfigured(args) {
188
+ return !!(args["zestro-bridge"] || process.env.PILLAR_ZESTRO_URL);
189
+ }
190
+
191
+ function notifySinkFor(home, cfg, notify) {
192
+ if (notify !== "auto") return null;
193
+ const ncfg = notifyConfigFrom(cfg);
194
+ return ncfg.present && ncfg.enabled ? new NotifySink({ home, cfg: ncfg }) : null;
195
+ }
196
+
197
+ const loadPillar = openPillar;
198
+
146
199
  /**
147
200
  * Load the address book into `p`, printing every problem with it on stderr
148
201
  * (once), and return the inspection so a later error can say exactly why a
@@ -233,207 +286,6 @@ function writeRuntimeFile(pillar, home) {
233
286
  writeFileSync(join(home, "runtime.json"), JSON.stringify(rt, null, 2), { mode: 0o600 });
234
287
  }
235
288
 
236
- // Carrier list + address book merge from a fetched directory — shared by
237
- // `init --directory` (first contact) and `init --refresh` (re-sync without
238
- // touching the keychain).
239
- function carriersFromDirectory(d) {
240
- return [d.carrier, ...(Array.isArray(d.seeds) ? d.seeds.map((s) => s.url) : [])].filter(Boolean);
241
- }
242
-
243
- function mergeDirectoryAgents(home, d) {
244
- if (!Array.isArray(d.agents)) return null;
245
- const fleetPath = join(home, "fleet.json");
246
- const prev = existsSync(fleetPath) ? JSON.parse(readFileSync(fleetPath, "utf-8")).fleet ?? {} : {};
247
- const fleet = { ...prev };
248
- let added = 0;
249
- for (const a of d.agents) {
250
- if (!a.uuaid || !a.publicKey) continue;
251
- const key = typeof a.role === "string" && a.role ? a.role : a.uuaid;
252
- fleet[key] = {
253
- uuaid: a.uuaid,
254
- publicKey: a.publicKey,
255
- ...(prev[key]?.addrs ? { addrs: prev[key].addrs } : {}),
256
- ...(prev[key]?.peerId ? { peerId: prev[key].peerId } : {}),
257
- };
258
- if (!prev[key]) added++;
259
- }
260
- writeFileSync(fleetPath, JSON.stringify({ fleet }, null, 2), { mode: 0o600 });
261
- return { count: Object.keys(fleet).length, added };
262
- }
263
-
264
- async function fetchDirectory(url) {
265
- const res = await fetch(url);
266
- if (!res.ok) {
267
- console.error(`directory fetch failed: ${url} -> ${res.status}`);
268
- exit(1);
269
- }
270
- return res.json();
271
- }
272
-
273
- async function cmdInit(args) {
274
- const home = homePath(args);
275
- mkdirSync(home, { recursive: true });
276
-
277
- // --refresh re-syncs carriers + address book from a directory WITHOUT
278
- // touching the keychain (init --force would mint a NEW identity and break
279
- // every enrolled sender). Requires an existing identity.
280
- if (args.refresh) {
281
- const kcPath = join(home, "keychain.json");
282
- if (!existsSync(kcPath)) {
283
- console.error(`refresh: no keychain at ${kcPath} — run pillar init first (refresh never mints keys)`);
284
- exit(1);
285
- }
286
- if (typeof args.directory !== "string") {
287
- console.error("refresh: --directory <url> is required");
288
- exit(1);
289
- }
290
- const d = await fetchDirectory(args.directory);
291
- const list = carriersFromDirectory(d);
292
- if (!list.length) {
293
- console.error(`refresh: directory ${args.directory} lists no carrier and no seeds`);
294
- exit(1);
295
- }
296
- const cfgPath = join(home, "config.json");
297
- const cfg = existsSync(cfgPath) ? JSON.parse(readFileSync(cfgPath, "utf-8")) : {};
298
- cfg.carriers = list;
299
- writeFileSync(cfgPath, JSON.stringify(cfg, null, 2), { mode: 0o600 });
300
- console.log(`carriers refreshed from ${args.directory}: ${list.join(", ")}`);
301
- const ab = mergeDirectoryAgents(home, d);
302
- if (ab) console.log(`address book: ${ab.count} peers in ${join(home, "fleet.json")} (${ab.added} new from directory)`);
303
- console.log(`refresh complete at ${home} (keychain untouched)`);
304
- return;
305
- }
306
-
307
- const kcPath = join(home, "keychain.json");
308
- let rotated = null;
309
- if (existsSync(kcPath)) {
310
- const old = new Keychain(kcPath).publicView();
311
- if (!args.force) {
312
- console.error(`this home already has an identity: ${old?.uuaid ?? kcPath}`);
313
- console.error(` re-sync carriers and contacts, keeping it: pillar init --refresh --directory <url> --home ${home}`);
314
- console.error(` replace it with a NEW identity (new UUAID): pillar init --force --confirm <current uuaid> --home ${home}`);
315
- exit(1);
316
- }
317
- rotated = await confirmAndArchiveIdentity(home, old, args);
318
- }
319
- let uuaidNamespace;
320
- try { uuaidNamespace = mintNamespace(args.namespace === undefined ? undefined : args.namespace); }
321
- catch { console.error(`init: --namespace must be one of ${SELF_CERTIFYING_NAMESPACES.join(", ")}`); exit(1); }
322
- const kc = new Keychain(kcPath);
323
- const id = Keychain.generate({ uuaidNamespace });
324
- kc.save(id, { passphrase: process.env.PILLAR_PASSPHRASE ?? "" });
325
- // A rotation keeps the home's settings (carriers, receipts, …); only the
326
- // identity and what is bound to it were archived.
327
- const cfg = rotated ? readConfig(home) : {
328
- listenAddrs: ["/ip4/0.0.0.0/tcp/0", "/ip4/0.0.0.0/tcp/0/ws"],
329
- bootstrapPeers: [],
330
- enableRelay: false,
331
- dhtClientMode: true,
332
- };
333
- // P2P seed discovery: --directory fetches a pillar directory.json and wires
334
- // the primary carrier plus every seeds[] entry as carriers (the LimeWire
335
- // seed model — poll all, replicate to all); --carriers sets them directly.
336
- if (typeof args.directory === "string") {
337
- const d = await fetchDirectory(args.directory);
338
- const list = carriersFromDirectory(d);
339
- if (!list.length) {
340
- console.error(`init: directory ${args.directory} lists no carrier and no seeds`);
341
- exit(1);
342
- }
343
- cfg.carriers = list;
344
- console.log(`carriers from directory (${args.directory}): ${list.join(", ")}`);
345
- // Seed the address book from the directory's agents[] so a fresh agent can
346
- // `pillar ask`/`pillar send` with zero key plumbing (keys required for E2E).
347
- // Merge — never clobber a hand-curated fleet.json.
348
- const ab = mergeDirectoryAgents(home, d);
349
- if (ab) console.log(`address book: ${ab.count} peers in ${join(home, "fleet.json")} (${ab.added} new from directory)`);
350
- } else if (args.carriers) {
351
- cfg.carriers = args.carriers.split(",").map(s => s.trim()).filter(Boolean);
352
- }
353
- writeFileSync(join(home, "config.json"), JSON.stringify(cfg, null, 2), { mode: 0o600 });
354
- console.log(`initialized pillar at ${home}`);
355
- console.log(`uuaid: ${id.uuaid}`);
356
- console.log(`publicKey: ${id.publicKeyHex}`);
357
- if (rotated) {
358
- console.log(`\nreplaced identity ${rotated.uuaid}`);
359
- console.log(` archived to ${rotated.dir} (keychain, mailbox, tier grant): the old key still opens the old mail there`);
360
- console.log(` every contact and directory listing still names the OLD uuaid: send them the new uuaid + publicKey, and re-list it`);
361
- if (cfg.carriers?.length) console.log(` carriers kept: ${cfg.carriers.join(", ")}`);
362
- return;
363
- }
364
- console.log(`\nconfig: ${join(home, "config.json")}`);
365
- console.log(`edit bootstrapPeers to join a network, or run again with --directory <url> / --carriers a,b to wire seeds.`);
366
- }
367
-
368
- /**
369
- * `init --force` replaces an identity, which silently breaks every contact
370
- * that knows the old UUAID. So it must be confirmed, and it is never lossy:
371
- *
372
- * - interactive: type the current UUAID's last 8 characters;
373
- * non-interactive: --confirm <current uuaid, or its last 8 characters>
374
- * - refused while a live `pillar recv` holds this home (it would keep
375
- * writing into the archived mailbox)
376
- * - everything bound to the old identity (keychain, mailbox, tier grant,
377
- * runtime file) is MOVED to <home>/rotated/<time>-<old id>/, not deleted
378
- *
379
- * Returns { uuaid, dir }.
380
- */
381
- async function confirmAndArchiveIdentity(home, old, args) {
382
- const current = old?.uuaid ?? "";
383
- const tail = current.replace(/-/g, "").slice(-8);
384
- const accepted = (v) => typeof v === "string" && (v === current || v.replace(/-/g, "").toLowerCase() === tail.toLowerCase());
385
- let answer = typeof args.confirm === "string" ? args.confirm : null;
386
- if (answer === null && process.stdin.isTTY && process.stderr.isTTY) {
387
- const { createInterface } = await import("node:readline/promises");
388
- const rl = createInterface({ input: process.stdin, output: process.stderr });
389
- console.error(`This REPLACES the identity of ${home}:`);
390
- console.error(` ${current}`);
391
- console.error(`with a new key and a new UUAID. Contacts that know the old one will no longer reach you.`);
392
- answer = (await rl.question(`Type the last 8 characters of the current UUAID (${tail}) to continue: `)).trim();
393
- rl.close();
394
- }
395
- if (!accepted(answer)) {
396
- console.error(answer === null
397
- ? `init --force replaces ${current} with a NEW identity. Confirm it: pillar init --force --confirm ${current}`
398
- : `confirmation "${answer}" does not match ${current}; nothing was changed`);
399
- exit(1);
400
- }
401
- const { Mailbox } = await import("../src/mailbox/mailbox.mjs");
402
- const mbPath = join(home, "mailbox.db");
403
- if (existsSync(mbPath)) {
404
- // Two checks, each catching what the other cannot:
405
- // 1. Lease scan (otherLiveLeases): a recv daemon that has started and is
406
- // heartbeating. Catches remote hosts and processes that opened the DB
407
- // but have since closed it.
408
- // 2. File-open scan (processesWithMailboxOpen via lsof): any process with
409
- // an open fd on mailbox.db right now — a pre-lease daemon (idle, DB
410
- // open, no lease yet) or a one-shot `pillar inbox` run.
411
- // The exclusive-lock probe (BEGIN EXCLUSIVE with busy_timeout=0) was
412
- // rejected: WAL mode lets concurrent readers proceed, so an idle daemon
413
- // holding the DB open but not writing would NOT block the probe, giving
414
- // a false pass.
415
- const mb = new Mailbox(mbPath);
416
- const live = otherLiveLeases(mb);
417
- mb.close();
418
- if (live.length) {
419
- console.error(`refusing to replace the identity while ${live.map(describeProcess).join("; ")} is reading this home — stop it first`);
420
- exit(1);
421
- }
422
- const holders = processesWithMailboxOpen(mbPath);
423
- if (holders.length) {
424
- console.error(`refusing to replace the identity while ${holders.map((p) => `${p.command} (pid ${p.pid})`).join("; ")} has this home's mailbox open — stop it first`);
425
- exit(1);
426
- }
427
- }
428
- const stamp = new Date().toISOString().replace(/[:.]/g, "-");
429
- const dir = join(home, "rotated", `${stamp}-${(current.split(":")[3] ?? "unknown").slice(0, 8)}`);
430
- mkdirSync(dir, { recursive: true });
431
- for (const f of ["keychain.json", "mailbox.db", "mailbox.db-wal", "mailbox.db-shm", "tier-grant.json", "runtime.json"]) {
432
- if (existsSync(join(home, f))) renameSync(join(home, f), join(dir, f));
433
- }
434
- return { uuaid: current, dir };
435
- }
436
-
437
289
  /**
438
290
  * pillar id — read-only (2.5.3). It reads only the key file's public part and
439
291
  * config.json: no passphrase, no mailbox, no libp2p node. Up to 2.5.2 it ran
@@ -464,17 +316,19 @@ async function cmdId(args) {
464
316
  exit(2);
465
317
  }
466
318
  const cfg = readConfig(home);
319
+ const wantsLibp2p = args.libp2p === true || args.libp2p === "true" || args.libp2p === "1";
320
+ const carrierOnly = !wantsLibp2p && (Boolean(args["carrier-only"]) || cfg.carrierOnly === true || !isP2pInstalled());
467
321
  console.log(`uuaid: ${pub.uuaid}`);
468
322
  console.log(`publicKey: ${pub.publicKeyHex}`);
469
- if (args["carrier-only"] || cfg.carrierOnly === true) {
323
+ let peerId = null;
324
+ try {
325
+ const der = kc.load({ passphrase: process.env.PILLAR_PASSPHRASE ?? "" }).privateKey.export({ type: "pkcs8", format: "der" });
326
+ peerId = peerIdFromSeedHex(Buffer.from(der.slice(der.length - 32)).toString("hex")).toString();
327
+ } catch { /* wrong or missing passphrase: the public part above is still right */ }
328
+ console.log(`peerId: ${peerId ?? "unknown: the key did not open (set PILLAR_PASSPHRASE to show it)"}`);
329
+ if (carrierOnly) {
470
330
  console.log(`mode: carrier-only (no libp2p)`);
471
331
  } else {
472
- let peerId = null;
473
- try {
474
- const der = kc.load({ passphrase: process.env.PILLAR_PASSPHRASE ?? "" }).privateKey.export({ type: "pkcs8", format: "der" });
475
- peerId = peerIdFromSeedHex(Buffer.from(der.slice(der.length - 32)).toString("hex")).toString();
476
- } catch { /* wrong or missing passphrase: the public part above is still right */ }
477
- console.log(`peerId: ${peerId ?? "unknown: the key did not open (set PILLAR_PASSPHRASE to show it)"}`);
478
332
  let rt = null;
479
333
  try { rt = JSON.parse(readFileSync(join(home, "runtime.json"), "utf-8")); } catch { /* none, or unreadable */ }
480
334
  if (rt?.uuaid === pub.uuaid && Array.isArray(rt.addrs) && rt.addrs.length) {
@@ -492,7 +346,7 @@ async function cmdId(args) {
492
346
  async function cmdSend(args) {
493
347
  const [recipientArg, kind, jsonStr] = args._.slice(1);
494
348
  if (!recipientArg || !kind) {
495
- console.error("usage: pillar send <recipient-uuaid|contact-name> <kind> [json-payload] [--to-pubkey HEX] [--wait-ack SECONDS] [--fleet FLEET.json]");
349
+ console.error("usage: pillar send <recipient-uuaid|contact-name> <kind> [json-payload] [--to-pubkey HEX] [--wait-ack SECONDS] [--fleet FLEET.json] [--registry URL] [--confirm-recovered]");
496
350
  exit(2);
497
351
  }
498
352
  let payload = {};
@@ -508,9 +362,10 @@ async function cmdSend(args) {
508
362
  try { recipient = resolveRecipient(recipientArg, info).uuaid; }
509
363
  catch (e) { await p.stop(); console.error(e.message); exit(2); }
510
364
  const toKey = typeof args["to-pubkey"] === "string" ? args["to-pubkey"] : undefined;
365
+ const regUrl = typeof args.registry === "string" ? args.registry : undefined;
511
366
  // Say WHY there is no key before the library says only that there is none
512
367
  // (a malformed contacts file used to surface as "no public key known").
513
- if (!toKey && !p.addressBook?.get(recipient)?.publicKey && !p.node) {
368
+ if (!toKey && !regUrl && !p.registryUrl && !p.addressBook?.get(recipient)?.publicKey && !p.node) {
514
369
  await p.stop();
515
370
  console.error(explainMissingKey(recipient, info));
516
371
  exit(1);
@@ -518,29 +373,39 @@ async function cmdSend(args) {
518
373
  try {
519
374
  const sent = await p.send({
520
375
  recipient, kind, payload,
521
- recipientPublicKey: toKey, // explicit key for peers outside fleet.json
376
+ recipientPublicKey: toKey,
522
377
  resolveTimeoutMs: 5000,
378
+ registryUrl: regUrl,
379
+ confirmRecovered: args["confirm-recovered"] === true || args["confirm-recovered"] === "true" || args["confirm-recovered"] === "1",
380
+ now: typeof args.now === "string" ? args.now : null,
381
+ allowInsecureLoopback: args["allow-insecure-loopback"] === true || args["allow-insecure-loopback"] === "true",
523
382
  });
524
383
  const { envelope, delivery } = sent;
384
+ const effRecipient = sent.redirectedTo ?? recipient;
525
385
  console.log(`sent envelope ${envelope.id}`);
526
- console.log(` to: ${recipient}${recipient !== recipientArg ? ` (${recipientArg})` : ""}`);
386
+ if (sent.redirectedFrom) console.log(` redirected (W-4): ${sent.redirectedFrom} -> ${sent.redirectedTo} (mapping persisted in ${join(homePath(args), "w4-redirect.json")})`);
387
+ console.log(` to: ${effRecipient}${effRecipient !== recipientArg ? ` (${recipientArg})` : ""}`);
527
388
  console.log(` kind: ${kind}`);
528
389
  if (sent.direct?.peerId) console.log(` via peerId: ${sent.direct.peerId}${sent.confirmed === false ? " (a direct stream only: nothing confirms it arrived)" : ""}`);
529
- if (sent.confirmed === false) console.error(`warning: no carrier accepted ${envelope.id}${sent.carrierError ? ` (${sent.carrierError.message})` : ""}; it was written to a direct stream, which is not a receipt, so it stays pending until ${recipient} acks it.`);
390
+ if (sent.confirmed === false) console.error(`warning: no carrier accepted ${envelope.id}${sent.carrierError ? ` (${sent.carrierError.message})` : ""}; it was written to a direct stream, which is not a receipt, so it stays pending until ${effRecipient} acks it.`);
530
391
  if (delivery?.carrier) console.log(` accepted by carrier ${delivery.carrier} (seq ${delivery.seq}) — that is the carrier's receipt, not the recipient's`);
531
392
  if (args["wait-ack"] !== undefined) {
532
393
  const secs = args["wait-ack"] === true ? 60 : Number(args["wait-ack"]);
533
394
  if (!Number.isFinite(secs) || secs <= 0) { console.error("--wait-ack takes a number of seconds"); exit(2); }
534
- const r = await waitForAck(p, envelope.id, recipient, Date.now() + secs * 1000);
395
+ const r = await waitForAck(p, envelope.id, effRecipient, Date.now() + secs * 1000);
535
396
  if (r.acked) {
536
- console.log(` acknowledged: signed by ${recipient} (${r.how}, ${r.at})`);
397
+ console.log(` acknowledged: signed by ${effRecipient} (${r.how}, ${r.at})`);
537
398
  } else {
538
- console.error(` no signed ack from ${recipient} within ${secs}s. The carrier holds the envelope; the recipient has not acknowledged it (acks are opt-in on their side: pillar receipts on).`);
399
+ console.error(` no signed ack from ${effRecipient} within ${secs}s. The carrier holds the envelope; the recipient has not acknowledged it (acks are opt-in on their side: pillar receipts on).`);
539
400
  exit(4);
540
401
  }
541
402
  }
542
403
  } catch (e) {
543
404
  if (/no public key known/.test(e.message)) { console.error(explainMissingKey(recipient, info)); exit(1); }
405
+ if (e?.name === "W4RefusalError") {
406
+ console.error(`${e.code}: ${e.fix}`);
407
+ exit(e.code === "confirm-recovered-redirect" ? 3 : 1);
408
+ }
544
409
  throw e;
545
410
  } finally {
546
411
  await p.stop();
@@ -738,7 +603,7 @@ function printGroupResults({ group, groupId, msgId, results }) {
738
603
  async function cmdGroups(args) {
739
604
  const home = homePath(args);
740
605
  const { Mailbox } = await import("../src/mailbox/mailbox.mjs");
741
- const mine = existsSync(join(home, "mailbox.db")) ? (() => {
606
+ const mine = (existsSync(join(home, "mailbox.db")) || existsSync(join(home, "mailbox"))) ? (() => {
742
607
  const mb = new Mailbox(join(home, "mailbox.db"));
743
608
  try { return mb.listGroups(); } finally { mb.close(); }
744
609
  })() : [];
@@ -887,7 +752,7 @@ async function cmdGroup(args) {
887
752
  function wantsGroupV2(args) {
888
753
  const home = homePath(args);
889
754
  const mbPath = join(home, "mailbox.db");
890
- const mb = existsSync(mbPath) ? new Mailbox(mbPath) : null;
755
+ const mb = (existsSync(mbPath) || existsSync(join(home, "mailbox"))) ? new Mailbox(mbPath) : null;
891
756
  try { return groupCommandRoute(args, groupRouteLookups(new RosterStore(home), mb)) === "v2"; }
892
757
  finally { mb?.close(); }
893
758
  }
@@ -919,7 +784,72 @@ async function cmdRecv(args) {
919
784
  // contacts file that exists but yields nothing at all stops recv instead.
920
785
  const fleetInfo = inspectFleetFile(fleetPath(args));
921
786
  if (fleetInfo.error) { console.error(`recv: ${fleetInfo.error}`); exit(1); }
922
- const p = loadPillar(args, { reader: rk.key });
787
+ // --notify: this recv is the home's resident wake path. It takes no command
788
+ // text; the hook comes from config.json notify.hook (absolute exec + args).
789
+ const wantsNotify = args.notify !== undefined;
790
+ let notifyCfg = null, notifyStore = null, notifySink = null, wakeHandle = null, notifyDeferred = false, notifyLine = null;
791
+ if (wantsNotify) {
792
+ // V1 F2: the Zestro bridge is a second wake path (unbudgeted, and it
793
+ // forwards payload text). One process never runs both.
794
+ if (zestroBridgeConfigured(args)) { console.error(NOTIFY_BRIDGE_REFUSAL); exit(64); }
795
+ if (args.notify !== true) { console.error("recv --notify takes no command: set notify.hook in config.json, e.g. {\"exec\": \"/absolute/path\", \"args\": []}"); exit(2); }
796
+ const home = homePath(args);
797
+ if (!existsSync(join(home, "keychain.json"))) { console.error(`no pillar found at ${home}. run: pillar init`); exit(2); }
798
+ notifyCfg = notifyConfigFrom(readConfig(home));
799
+ if (!notifyCfg.enabled) { console.error("recv --notify: notify.enabled is false in config.json"); exit(2); }
800
+ if (notifyCfg.invalid.length) { for (const m of notifyCfg.invalid) console.error(`recv --notify: ${m}`); exit(2); }
801
+ try { checkHook(notifyCfg.hook); } catch (e) { console.error(`recv --notify: ${e.message}`); exit(2); }
802
+ notifyStore = new NotifyStore(home);
803
+ // V1 F3: from here on, stderr in --notify mode is bounded (escaped, words
804
+ // <= 64 chars, lines <= 400), rate-limited, and copied to notify/recv.log.
805
+ const { boundedWriter, PrivateLog } = await import("../src/notify-log.mjs");
806
+ const { format } = await import("node:util");
807
+ notifyLine = boundedWriter({ log: new PrivateLog(notifyStore.dir) });
808
+ console.warn = (...a) => notifyLine(format(...a));
809
+ console.error = (...a) => notifyLine(format(...a));
810
+ process.on("uncaughtException", (e) => { notifyLine(`recv --notify: fatal: ${e?.stack ?? e}`); exit(1); });
811
+ notifySink = new NotifySink({ home, cfg: notifyCfg, store: notifyStore });
812
+ let w = null;
813
+ try { notifyStore.open(); w = await notifyStore.acquireWake("resident"); }
814
+ catch (e) {
815
+ if (e.code !== "notify-custody") throw e;
816
+ // V1 F1d: a custody problem in notify/ never stops mail intake. Receive
817
+ // without notify; retry the wake path every minute.
818
+ console.error(`recv --notify: notify-custody: ${String(e.message).slice(0, 300)}; receiving without notify, retrying every 60 s`);
819
+ notifyDeferred = true;
820
+ }
821
+ if (w && !w.handle) {
822
+ const h = w.heldBy;
823
+ const r = wakeRefusal("resident", h.kind); // V1 F2b: a bridged recv holds it -> exit 64
824
+ console.error(r.message ?? `recv --notify: refused: the ${h.kind ?? "other"} wake path holds ${notifyStore.path(WAKE_LOCK)} (pid ${h.pid ?? "?"} on ${h.host ?? "?"}); one wake path per home`);
825
+ exit(r.code);
826
+ }
827
+ if (w) wakeHandle = w.handle;
828
+ }
829
+ // V1 F2b: a recv with the Zestro bridge is a wake path too (one agent
830
+ // command per message). It takes notify/wake.lock as "bridge" before it
831
+ // pulls any mail, so it and a resident or fallback notifier can never run
832
+ // on one home together, whichever starts first. A plain recv takes no lock.
833
+ const bridged = zestroBridgeConfigured(args);
834
+ const bridgeHome = homePath(args);
835
+ if (recvWakeKind({ notify: wantsNotify, bridge: bridged }) === "bridge" && existsSync(join(bridgeHome, "keychain.json"))) {
836
+ const bridgeStore = new NotifyStore(bridgeHome);
837
+ let w = null;
838
+ try { bridgeStore.open(); w = await bridgeStore.acquireWake("bridge"); }
839
+ catch (e) {
840
+ if (e.code !== "notify-custody") throw e;
841
+ // Fail closed: without the lock the bridge could run beside a notifier.
842
+ console.error(`recv: notify-custody: ${String(e.message).slice(0, 300)}; the Zestro bridge needs notify/wake.lock to stay this home's only wake path`);
843
+ exit(2);
844
+ }
845
+ if (!w.handle) {
846
+ const r = wakeRefusal("bridge", w.heldBy.kind);
847
+ console.error(r.message);
848
+ exit(r.code);
849
+ }
850
+ wakeHandle = w.handle;
851
+ }
852
+ const p = loadPillar(args, { reader: rk.key, notifySink, notify: recvNotifyMode({ bridge: bridged }), needsTransport: true });
923
853
  await p.start();
924
854
  writeRuntimeFile(p, homePath(args)); // warm handoff: publish live addr for senders
925
855
  const { n } = loadContacts(args, p);
@@ -928,7 +858,6 @@ async function cmdRecv(args) {
928
858
  const prevReader = p.mailbox.getReader(rk.key);
929
859
  // A NEW named reader of a bridged recv starts at the tip: its unread
930
860
  // backlog would otherwise reach the bridge as fresh agent turns.
931
- const bridged = !!(args["zestro-bridge"] || process.env.PILLAR_ZESTRO_URL);
932
861
  const start = bridged ? p.mailbox.inboxTipSeq() : initialCursor(p.mailbox);
933
862
  p.mailbox.touchReader(rk.key, { ...ctx, cursor: prevReader ? 0 : start });
934
863
  const lease = () => p.mailbox.holdLease(rk.key, { ...ctx, ttlMs: LEASE_TTL_MS });
@@ -942,14 +871,58 @@ async function cmdRecv(args) {
942
871
  } else {
943
872
  console.log(`(carrier-only mode: no libp2p listener)`);
944
873
  }
874
+ let notifier = null, notifyRetry = null, wakeGuard = null, bridge = null;
875
+ // Lead L2: a wake path that loses notify/wake.lock (token gone, or the lock
876
+ // unreadable) stops at once: bridge closed, notifier stopped, no hook or
877
+ // command after the loss. It exits 75 (temporary failure): a supervisor
878
+ // restart must take the lock afresh, and is refused (64) while the new
879
+ // holder lives. The lock is re-read every 2 s and before every use.
880
+ const onWakeLockLost = (reason) => {
881
+ try { if (notifier) notifier.stop(); } catch (_e) {}
882
+ try { if (bridge) bridge.close(); } catch (_e) {}
883
+ bridge = null;
884
+ const who = bridged ? "recv (Zestro bridge)" : "recv --notify";
885
+ console.error(`${who}: lost notify/wake.lock (${String(reason).slice(0, 120)}); another wake path holds this home; stopping`);
886
+ try { p.mailbox.releaseLease(rk.key, ctx); } catch (_e) {}
887
+ exit(75);
888
+ };
889
+ const holdsWakeLock = () => !!wakeGuard?.check();
890
+ if (bridged && wakeHandle) wakeGuard = guardLock(wakeHandle, { intervalMs: 2000, onLost: onWakeLockLost });
891
+ const startNotifier = async () => {
892
+ wakeGuard = guardLock(wakeHandle, { intervalMs: 2000, onLost: onWakeLockLost });
893
+ // Activate (baseline at the tip on a first run) BEFORE intake starts.
894
+ notifier = new Notifier({ home: homePath(args), store: notifyStore, cfg: notifyCfg, uuaid: p.uuaid, mailbox: p.mailbox, mode: "resident", log: notifyLine, holdCheck: holdsWakeLock });
895
+ notifySink.onEvent = () => notifier.poke(); // enqueue only; the hook runs apart from the receive path
896
+ const first = await notifier.startResident();
897
+ const how = first.error ? `waiting (${first.error})` : first.activated ? "activated (baseline at the tip)" : "resumed";
898
+ console.log(`notify: resident wake path ${how}; hook ${notifyCfg.hook ? "from notify.hook" : "none: notices go to notify/notifications.jsonl only"}`);
899
+ };
900
+ if (wantsNotify && !notifyDeferred) await startNotifier();
901
+ if (wantsNotify && notifyDeferred) {
902
+ notifyRetry = setInterval(async () => {
903
+ try {
904
+ notifyStore = new NotifyStore(homePath(args));
905
+ notifyStore.open();
906
+ const w = await notifyStore.acquireWake("resident");
907
+ if (!w.handle) { // another wake path took the home meanwhile: keep receiving, keep waiting
908
+ if (w.heldBy?.kind === "bridge" && !notifyRetry.warned) { notifyRetry.warned = true; console.error(`recv --notify: ${NOTIFY_BRIDGE_REFUSAL}; the bridge holds notify/wake.lock, so this recv keeps receiving without notify`); }
909
+ return;
910
+ }
911
+ wakeHandle = w.handle;
912
+ notifySink.store = notifyStore;
913
+ clearInterval(notifyRetry);
914
+ notifyRetry = null;
915
+ await startNotifier();
916
+ } catch (_e) { /* still unusable: stay quiet, try again in a minute */ }
917
+ }, 60_000);
918
+ }
945
919
  if (p.carrierClient) {
946
920
  p.startCarrierPolling();
947
921
  console.log(`polling carriers: ${p.carriers.join(", ")}`);
948
922
  }
949
923
  if (n > 0) console.log(`address book: ${n} peers from ${fleetPath(args)}`);
950
924
 
951
- let bridge = null;
952
- if (args["zestro-bridge"] || process.env.PILLAR_ZESTRO_URL) {
925
+ if (bridged) {
953
926
  const { ZestroBridge } = await import("../src/bridges/zestro.mjs");
954
927
  bridge = new ZestroBridge({
955
928
  url: process.env.PILLAR_ZESTRO_URL ?? args["zestro-url"],
@@ -969,11 +942,20 @@ async function cmdRecv(args) {
969
942
  // bridge must not send a second ack for a request.
970
943
  const autoAcks = p.receipts.delivered;
971
944
  const handle = async (env) => {
972
- const line = { at: new Date().toISOString(), from: env.sender, kind: env.kind, payload: env.payload };
973
- const tag = extractGroupTag(env.payload);
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; }
975
- if (rk.named) line.id = env.id;
976
- console.log(jsonLine(line));
945
+ if (wantsNotify) {
946
+ // The notify surface is metadata only: no payload or group name on stdout,
947
+ // and id/from only when they pass the protocol checks (V1 F1a, F3).
948
+ console.log(jsonLine({ at: new Date().toISOString(), id: isSafeId(env.id) ? env.id : null, from: isSafeUuaid(env.sender) ? env.sender : null, kind: env.kind }));
949
+ } else {
950
+ const line = { at: new Date().toISOString(), from: env.sender, kind: env.kind, payload: env.payload };
951
+ const tag = extractGroupTag(env.payload);
952
+ 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; }
953
+ if (rk.named) line.id = env.id;
954
+ console.log(jsonLine(line));
955
+ }
956
+ // Lead L2: re-read the lock before forwarding anything to the agent; a
957
+ // bridge that lost it forwards nothing (onWakeLockLost exits).
958
+ if (bridge && !holdsWakeLock()) return;
977
959
  if (bridge && env.kind === "request") {
978
960
  // Interaction-convention return leg: ack FIRST — pillar-ask allows 120s
979
961
  // per phase but ZestroBridge times out at 30s, so the ack goes out before
@@ -1065,6 +1047,10 @@ async function cmdRecv(args) {
1065
1047
  const shutdown = async () => {
1066
1048
  clearInterval(heartbeat);
1067
1049
  if (tail) clearInterval(tail);
1050
+ if (notifier) notifier.stop(); // a running hook's group is killed; its run reads "ambiguous" next time
1051
+ if (wakeGuard) wakeGuard.stop();
1052
+ if (notifyRetry) clearInterval(notifyRetry);
1053
+ if (wakeHandle) { try { releaseLock(wakeHandle); } catch (_e) {} }
1068
1054
  try { p.mailbox.releaseLease(rk.key, ctx); } catch (_e) {}
1069
1055
  if (bridge) bridge.close();
1070
1056
  await p.stop();
@@ -1194,19 +1180,63 @@ async function cmdInbox(args) {
1194
1180
  }
1195
1181
  const newCount = rk.named ? printed.length : pulled;
1196
1182
  if (args.notify && typeof args.notify === "string" && (newCount > 0 || backlog.length > 0)) {
1197
- const { spawnSync } = await import("node:child_process");
1198
- const r = spawnSync(args.notify, {
1199
- shell: true,
1200
- input: jsonLine({ uuaid: p.uuaid, new: newCount, unread: backlog.length }) + "\n",
1201
- env: { ...process.env, PILLAR_NEW: String(newCount), PILLAR_UNREAD: String(backlog.length), PILLAR_UUAID: p.uuaid },
1202
- stdio: ["pipe", "inherit", "inherit"],
1203
- });
1204
- if (r.status !== 0) console.error(`notify hook exited ${r.status}`);
1183
+ // Lead L5: the legacy hook is a wake path too. It runs only while this run
1184
+ // holds notify/wake.lock (kind "inbox"); a held lock (resident, fallback,
1185
+ // bridge) or an unusable notify/ skips it with one stderr line. The exit
1186
+ // code stays 0 either way: a courier drops stdout on a non-zero exit.
1187
+ const inboxStore = new NotifyStore(homePath(args));
1188
+ let lock = null;
1189
+ let skip = null;
1190
+ try { inboxStore.open(); lock = await inboxStore.acquireWake("inbox"); }
1191
+ catch (e) { skip = `notify/ is unusable (${e.code ?? "error"})`; }
1192
+ if (lock && !lock.handle) skip = `the ${lock.heldBy?.kind ?? "other"} wake path holds notify/wake.lock`;
1193
+ if (skip) {
1194
+ console.error(`inbox --notify: hook skipped: ${skip}; one wake path per home`);
1195
+ } else {
1196
+ try {
1197
+ // Lead T5: the legacy hook gets the same deadline as notify.hook: after
1198
+ // 10 s its process group gets SIGTERM, then SIGKILL, and is reaped (a
1199
+ // hanging command must not hold wake.lock). This run's exit code is
1200
+ // unchanged (0) whatever the hook does.
1201
+ const { status, timedOut } = await runLegacyInboxHook(args.notify, jsonLine({ uuaid: p.uuaid, new: newCount, unread: backlog.length }) + "\n",
1202
+ { ...process.env, PILLAR_NEW: String(newCount), PILLAR_UNREAD: String(backlog.length), PILLAR_UUAID: p.uuaid });
1203
+ if (timedOut) console.error("notify hook timed out after 10 s; its process group was killed");
1204
+ else if (status !== 0) console.error(`notify hook exited ${status}`);
1205
+ } finally {
1206
+ releaseLock(lock.handle);
1207
+ }
1208
+ }
1205
1209
  }
1206
1210
  await p.stop();
1207
1211
  exit(0);
1208
1212
  }
1209
1213
 
1214
+ /**
1215
+ * Run the legacy `inbox --notify CMD` shell command (Lead T5): own process
1216
+ * group, stdin = the summary line, stdout/stderr inherited; after 10 s the
1217
+ * group gets SIGTERM, then SIGKILL 1 s later, and is reaped. Resolves
1218
+ * { status, timedOut }.
1219
+ */
1220
+ async function runLegacyInboxHook(cmd, input, env, { timeoutMs = 10_000, graceMs = 1000 } = {}) {
1221
+ const { spawn } = await import("node:child_process");
1222
+ return new Promise((resolve) => {
1223
+ const child = spawn(cmd, { shell: true, env, detached: true, stdio: ["pipe", "inherit", "inherit"] });
1224
+ const killGroup = (sig) => { try { process.kill(-child.pid, sig); } catch (_e) { /* gone */ } };
1225
+ let timedOut = false;
1226
+ let grace = null;
1227
+ const timer = setTimeout(() => { timedOut = true; killGroup("SIGTERM"); grace = setTimeout(() => killGroup("SIGKILL"), graceMs); }, timeoutMs);
1228
+ child.stdin.on("error", () => {});
1229
+ child.stdin.end(input);
1230
+ child.on("error", () => { clearTimeout(timer); clearTimeout(grace); resolve({ status: 127, timedOut: false }); });
1231
+ child.on("exit", (code, signal) => {
1232
+ clearTimeout(timer);
1233
+ clearTimeout(grace);
1234
+ killGroup("SIGKILL"); // anything it left in its group dies with it
1235
+ resolve({ status: code ?? (signal ? 128 : 1), timedOut });
1236
+ });
1237
+ });
1238
+ }
1239
+
1210
1240
  /**
1211
1241
  * pillar wait — sleep until there is mail, then exit 0 with the count.
1212
1242
  *
@@ -1257,11 +1287,119 @@ async function cmdWait(args) {
1257
1287
  exit(3);
1258
1288
  }
1259
1289
 
1290
+ /**
1291
+ * pillar notify — one-shot new-mail notices. FALLBACK for hosts that cannot
1292
+ * keep a process; the main path is a resident `pillar recv --notify` (print a
1293
+ * unit with --print-unit launchd|systemd; nothing is installed, and the hook
1294
+ * comes from config.json notify.hook, never from the command line).
1295
+ *
1296
+ * Never pulls or stores. Holds the single wake-path lock (notify/wake.lock)
1297
+ * for the run, so it never runs beside a resident notifier. It claims
1298
+ * committed eligibility events (written by whichever reader stored the mail,
1299
+ * after final admission), under the same budget, cursor and log as the
1300
+ * resident path, and runs the hook once for them (src/notify-runner.mjs).
1301
+ * The first run baselines at the tip. A carrier peek adds an unverified
1302
+ * count only (verified: false): it cannot prove group admission, and it
1303
+ * never starts a hook.
1304
+ *
1305
+ * pillar notify [--home DIR] [--fleet FILE] [--groups FILE]
1306
+ * pillar notify --print-unit launchd|systemd [--label L]
1307
+ * pillar notify --print-unit cron [--every MIN]
1308
+ */
1309
+ async function cmdNotify(args) {
1310
+ const home = homePath(args);
1311
+ if (args["print-unit"] !== undefined) {
1312
+ const { renderUnit } = await import("../src/notify.mjs");
1313
+ if (args.command !== undefined) { console.error("--print-unit takes no hook command: units run `pillar recv --notify`, and the hook comes from notify.hook in config.json"); exit(2); }
1314
+ const pillarBin = join(dirname(fileURLToPath(import.meta.url)), "pillar.mjs");
1315
+ try {
1316
+ process.stdout.write(renderUnit(String(args["print-unit"]), {
1317
+ node: process.execPath, pillarBin, home: resolvePath(home),
1318
+ label: typeof args.label === "string" ? args.label : null,
1319
+ everyMinutes: args.every !== undefined ? Number(args.every) : 5,
1320
+ }));
1321
+ } catch (e) { console.error(e.message); exit(2); }
1322
+ if (!notifyConfigFrom(existsSync(join(home, "config.json")) ? readConfig(home) : {}).hook && String(args["print-unit"]) !== "cron") {
1323
+ console.error("note: this home has no notify.hook yet; the unit runs, but notices go to notify/notifications.jsonl only");
1324
+ }
1325
+ return;
1326
+ }
1327
+ const N = await import("../src/notify.mjs");
1328
+ if (zestroBridgeConfigured(args)) { console.error(NOTIFY_BRIDGE_REFUSAL); exit(64); } // V1 F2
1329
+ if (!existsSync(join(home, "keychain.json"))) { console.error(`no pillar found at ${home}. run: pillar init`); exit(2); }
1330
+ const cfg = N.notifyConfigFrom(readConfig(home));
1331
+ if (!cfg.enabled) { console.log(jsonLine({ enabled: false, notified: 0 })); exit(0); }
1332
+ // R2 H2: no notify block = the readers of this home write no eligibility
1333
+ // events, so there is nothing to notify. Write nothing (no notify/ dir).
1334
+ if (!cfg.present) {
1335
+ console.error("notify: config.json has no notify block, so the readers of this home write no eligibility events; nothing written (pillar init writes one for new homes)");
1336
+ console.log(jsonLine({ enabled: false, notified: 0 }));
1337
+ exit(0);
1338
+ }
1339
+ if (cfg.invalid.length) { for (const m of cfg.invalid) console.error(`notify: ${m}`); exit(2); }
1340
+ try { checkHook(cfg.hook); } catch (e) { console.error(`notify: ${e.message}`); exit(2); }
1341
+ const store = new NotifyStore(home);
1342
+ let wake;
1343
+ try {
1344
+ store.open();
1345
+ wake = await store.acquireWake("fallback");
1346
+ } catch (e) {
1347
+ if (e.code === "notify-custody") { console.error(`notify: notify-custody: ${String(e.message).slice(0, 300)}`); console.log(jsonLine({ error: "notify-custody", notified: 0 })); exit(2); }
1348
+ throw e;
1349
+ }
1350
+ if (!wake.handle) {
1351
+ const h = wake.heldBy;
1352
+ const r = wakeRefusal("fallback", h.kind); // V1 F2b: a live bridged recv -> exit 64
1353
+ console.error(r.message ?? `notify: refused: the ${h.kind ?? "other"} wake path holds ${store.path(WAKE_LOCK)} (pid ${h.pid ?? "?"} on ${h.host ?? "?"}); one wake path per home`);
1354
+ console.log(jsonLine({ refused: true, heldBy: h.kind ?? "unknown", notified: 0 }));
1355
+ exit(r.code);
1356
+ }
1357
+ args["carrier-only"] = true;
1358
+ const p = loadPillar(args, { reader: null, notify: "off" });
1359
+ await p.start();
1360
+ loadContacts(args, p); // a "directory" policy needs known senders for the peek
1361
+ let code = 0;
1362
+ try {
1363
+ const notifier = new Notifier({ home, store, cfg, uuaid: p.uuaid, mailbox: p.mailbox, mode: "fallback" });
1364
+ let r;
1365
+ try { r = await notifier.tick(); }
1366
+ catch (e) {
1367
+ // V1 F1d: one bounded line and a status, never a stack.
1368
+ if (e.code !== "notify-custody") throw e;
1369
+ console.error(`notify: notify-custody: ${String(e.message).slice(0, 300)}`);
1370
+ r = { error: "notify-custody" };
1371
+ code = 2;
1372
+ }
1373
+ let carrier = null;
1374
+ const pageInfo = {};
1375
+ if (p.carrierClient) {
1376
+ try { carrier = (await p.peekCarrierInbox({ deadlineMs: Date.now(), waitS: 0, match: (v) => N.qualifies(v, cfg), pageInfo })).length; }
1377
+ catch (e) { code = code || 1; console.error(`notify: ${refusalLine(e) ?? e?.message ?? String(e)}`); }
1378
+ }
1379
+ console.log(jsonLine({
1380
+ uuaid: p.uuaid, activated: !!r.activated, pending: r.pending ?? 0,
1381
+ notified: r.input?.new ?? 0, records: r.input?.records ?? [], more: r.input?.more ?? 0,
1382
+ ...(r.deferred ? { deferred: r.deferred, nextAt: Number.isFinite(r.nextAt) ? new Date(r.nextAt).toISOString() : null } : {}),
1383
+ ...(r.refusedHook ? { refusedHook: r.refusedHook } : {}),
1384
+ ...(r.busy ? { busy: r.busy } : {}), // the writer lock stayed held: nothing claimed, try again
1385
+ ...(r.error ? { error: r.error } : {}),
1386
+ hook: r.hook ? { status: r.hook.status, code: r.hook.code ?? null, ms: r.hook.ms ?? 0 } : null,
1387
+ // A peek is a count, never a notice. truncated: a carrier page was full
1388
+ // (or a carrier's answer was abandoned), so `count` is a lower bound.
1389
+ carrier: { count: carrier, verified: false, truncated: !!(pageInfo.full || pageInfo.partial) },
1390
+ }));
1391
+ } finally {
1392
+ releaseLock(wake.handle);
1393
+ await p.stop();
1394
+ }
1395
+ exit(code);
1396
+ }
1397
+
1260
1398
  /** pillar readers — every reader of this home, its cursor, and live leases. */
1261
1399
  async function cmdReaders(args) {
1262
1400
  const home = homePath(args);
1263
1401
  const { Mailbox } = await import("../src/mailbox/mailbox.mjs");
1264
- if (!existsSync(join(home, "mailbox.db"))) { console.log(`no mailbox at ${home} yet`); return; }
1402
+ if (!existsSync(join(home, "mailbox.db")) && !existsSync(join(home, "mailbox"))) { console.log(`no mailbox at ${home} yet`); return; }
1265
1403
  const mb = new Mailbox(join(home, "mailbox.db"));
1266
1404
  try {
1267
1405
  const tip = mb.inboxTipSeq();
@@ -1396,16 +1534,25 @@ async function cmdTrust(args) {
1396
1534
  const { Mailbox } = await import("../src/mailbox/mailbox.mjs");
1397
1535
  const mb = new Mailbox(join(home, "mailbox.db"));
1398
1536
  if (args.release) {
1399
- // An id is unique only within its sender: with two quarantined senders
1400
- // under one id, --from picks which one to release.
1401
- const held = mb.db.prepare("select sender from inbox where envelope_id = ? and quarantined is not null").all(args.release);
1402
1537
  const from = typeof args.from === "string" ? args.from : undefined;
1403
- if (!from && held.length > 1) {
1404
- console.error(`${held.length} senders have ${args.release} quarantined; release one with --from <uuaid>: ${held.map(r => r.sender).join(", ")}`);
1538
+ if (mb.mode !== "json-dir") {
1539
+ // An id is unique only within its sender: with two quarantined senders
1540
+ // under one id, --from picks which one to release.
1541
+ const held = mb.quarantinedSenders(args.release);
1542
+ if (!from && held.length > 1) {
1543
+ console.error(`${held.length} senders have ${args.release} quarantined; release one with --from <uuaid>: ${held.join(", ")}`);
1544
+ mb.close();
1545
+ exit(2);
1546
+ }
1547
+ }
1548
+ let changed;
1549
+ try {
1550
+ changed = mb.releaseQuarantined(args.release, from);
1551
+ } catch (e) {
1552
+ console.error(e instanceof Error ? e.message : String(e));
1405
1553
  mb.close();
1406
- exit(2);
1554
+ exit(1);
1407
1555
  }
1408
- const changed = mb.releaseQuarantined(args.release, from);
1409
1556
  if (changed === 0) {
1410
1557
  console.error(`no quarantined row with id ${args.release}${from ? ` from ${from}` : ""} — nothing released`);
1411
1558
  mb.close();
@@ -1500,17 +1647,118 @@ async function cmdTier(args) {
1500
1647
  async function cmdPeers(args) {
1501
1648
  const p = loadPillar(args);
1502
1649
  await p.start();
1650
+ if (!p.node) {
1651
+ console.log("0 connected peers (carrier-only mode)");
1652
+ await p.stop();
1653
+ return;
1654
+ }
1503
1655
  const peers = p.node.getPeers();
1504
1656
  console.log(`${peers.length} connected peers:`);
1505
1657
  for (const peer of peers) console.log(` ${peer.toString()}`);
1506
1658
  await p.stop();
1507
1659
  }
1508
1660
 
1661
+ const PRE_CMD_BOOL_FLAGS = new Set(["json", "force", "refresh", "carrier-only", "libp2p", "offline", "no-receipts", "ack", "a2a", "drain", "withdraw"]);
1662
+
1663
+ function findCommandIndex(raw) {
1664
+ for (let i = 0; i < raw.length; i++) {
1665
+ const a = raw[i];
1666
+ if (a === "--") return i + 1 < raw.length ? i + 1 : -1;
1667
+ if (a.startsWith("--")) {
1668
+ const eq = a.indexOf("=");
1669
+ const key = eq === -1 ? a.slice(2) : a.slice(2, eq);
1670
+ if (eq === -1 && !PRE_CMD_BOOL_FLAGS.has(key) && i + 1 < raw.length && !raw[i + 1].startsWith("-")) {
1671
+ i++;
1672
+ }
1673
+ continue;
1674
+ }
1675
+ if (a.startsWith("-") && a !== "-") {
1676
+ if (!a.includes("=") && i + 1 < raw.length && !raw[i + 1].startsWith("-")) {
1677
+ i++;
1678
+ }
1679
+ continue;
1680
+ }
1681
+ return i;
1682
+ }
1683
+ return -1;
1684
+ }
1685
+
1686
+ const USAGE = `usage: pillar <init|verify|lineage|card|knock|knocks|answer|intro|resolve|listing|id|send|send-group|group|groups|recv|inbox|wait|notify|readers|status|receipts|trust|tier|peers|delegate> [--home DIR]`;
1687
+ const NOTIFY_USAGE = `usage:
1688
+ pillar notify [--home DIR] [--fleet FILE] [--groups FILE]
1689
+ pillar notify --print-unit launchd|systemd [--label L]
1690
+ pillar notify --print-unit cron [--every MIN]`;
1691
+
1692
+ /** Usage for `pillar [<command>] --help`: the command's own text where it has one, else pillar's. */
1693
+ function helpText(raw) {
1694
+ const rest = raw.filter((a) => a !== "--help" && a !== "-h");
1695
+ const i = findCommandIndex(rest);
1696
+ const cmd = i === -1 ? undefined : rest[i];
1697
+ if (cmd === "group") return GROUP_V2_USAGE; // the v1 cmdGroup text stays inside its pinned bytes
1698
+ if (cmd === "notify") return NOTIFY_USAGE;
1699
+ return USAGE;
1700
+ }
1701
+
1509
1702
  async function main() {
1510
- const args = parseArgs(argv.slice(2));
1703
+ const raw = argv.slice(2);
1704
+ if (wantsHelp(raw)) await exitWithHelp(helpText(raw)); // R2: before any home, key, file or carrier is touched
1705
+ const cmdIdx = findCommandIndex(raw);
1706
+ const directCmd = cmdIdx === -1 ? undefined : raw[cmdIdx];
1707
+ const VNEXT_DIRECT_CMDS = new Set(["verify", "lineage", "init", "card", "knock", "knocks", "answer", "intro", "resolve", "listing", "soul"]);
1708
+ if (VNEXT_DIRECT_CMDS.has(directCmd)) {
1709
+ const subRaw = [...raw.slice(0, cmdIdx), ...raw.slice(cmdIdx + 1)];
1710
+ if (directCmd === "soul") {
1711
+ const { exitCode } = await runSoulCli(subRaw);
1712
+ exit(exitCode);
1713
+ }
1714
+ if (directCmd === "verify") {
1715
+ const { exitCode } = runVerifyCli(subRaw);
1716
+ exit(exitCode);
1717
+ }
1718
+ if (directCmd === "lineage") {
1719
+ const { exitCode } = await runLineageCli(subRaw);
1720
+ exit(exitCode);
1721
+ }
1722
+ if (directCmd === "init") {
1723
+ const { exitCode } = await runInitCli(subRaw);
1724
+ exit(exitCode);
1725
+ }
1726
+ if (directCmd === "card") {
1727
+ const { exitCode } = await runCardCli(subRaw);
1728
+ exit(exitCode);
1729
+ }
1730
+ if (directCmd === "intro") {
1731
+ const { exitCode } = runIntroCli(subRaw);
1732
+ exit(exitCode);
1733
+ }
1734
+ if (directCmd === "resolve") {
1735
+ const { exitCode } = await runResolveCli(subRaw);
1736
+ exit(exitCode);
1737
+ }
1738
+ if (directCmd === "listing") {
1739
+ const { exitCode } = await runListingCli(subRaw);
1740
+ exit(exitCode);
1741
+ }
1742
+ if (directCmd === "knock") {
1743
+ const { exitCode } = await runKnockCli(subRaw);
1744
+ exit(exitCode);
1745
+ }
1746
+ if (directCmd === "knocks") {
1747
+ const { exitCode } = await runKnocksCli(subRaw);
1748
+ exit(exitCode);
1749
+ }
1750
+ const { exitCode } = await runAnswerCli(subRaw);
1751
+ exit(exitCode);
1752
+ }
1753
+ const args = parseArgs(raw);
1754
+ for (const bf of ["carrier-only", "libp2p", "offline", "confirm-recovered", "allow-insecure-loopback"]) {
1755
+ if (typeof args[bf] === "string" && !["true", "false", "1", "0"].includes(args[bf])) {
1756
+ args._.unshift(args[bf]);
1757
+ args[bf] = true;
1758
+ }
1759
+ }
1511
1760
  const cmd = args._[0];
1512
1761
  switch (cmd) {
1513
- case "init": return cmdInit(args);
1514
1762
  case "id": return cmdId(args);
1515
1763
  case "send": return cmdSend(args);
1516
1764
  case "send-group": return cmdSendGroup(args);
@@ -1522,6 +1770,7 @@ async function main() {
1522
1770
  case "peers": return cmdPeers(args);
1523
1771
  case "delegate": return cmdDelegate(args);
1524
1772
  case "wait": return cmdWait(args);
1773
+ case "notify": return cmdNotify(args);
1525
1774
  case "readers": return cmdReaders(args);
1526
1775
  case "status": return cmdStatus(args);
1527
1776
  case "receipts": return cmdReceipts(args);
@@ -1529,7 +1778,7 @@ async function main() {
1529
1778
  if (wantsGroupV2(args)) return cmdGroupV2(args); // @rule P-cli-dispatch-v2
1530
1779
  return cmdGroup(args);
1531
1780
  default:
1532
- console.error(`usage: pillar <init|id|send|send-group|group|groups|recv|inbox|wait|readers|status|receipts|trust|tier|peers|delegate> [--home DIR]`);
1781
+ console.error(USAGE);
1533
1782
  exit(2);
1534
1783
  }
1535
1784
  }