@uuaid/pillar 2.6.1 → 2.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/README.md +325 -7
  2. package/bin/carrier.mjs +21 -0
  3. package/bin/pillar-ask.mjs +4 -1
  4. package/bin/pillar-blob.mjs +6 -0
  5. package/bin/pillar-directory.mjs +282 -16
  6. package/bin/pillar-escrow.mjs +4 -1
  7. package/bin/pillar-group-v2.mjs +6 -0
  8. package/bin/pillar-notify.mjs +13 -0
  9. package/bin/pillar-responder.mjs +266 -23
  10. package/bin/pillar.mjs +512 -257
  11. package/package.json +17 -25
  12. package/src/cli-help.mjs +23 -0
  13. package/src/group-v2-cli.mjs +1 -1
  14. package/src/identity/trust.mjs +72 -6
  15. package/src/mailbox/mailbox.mjs +313 -12
  16. package/src/net/carrier-server.mjs +34 -2
  17. package/src/net/refusals.mjs +2 -0
  18. package/src/net/seed-registry.mjs +2 -1
  19. package/src/net/transport.mjs +320 -91
  20. package/src/node-check.mjs +29 -8
  21. package/src/notify-events.mjs +148 -0
  22. package/src/notify-log.mjs +124 -0
  23. package/src/notify-runner.mjs +372 -0
  24. package/src/notify-store.mjs +736 -0
  25. package/src/notify.mjs +350 -0
  26. package/src/pillar.mjs +382 -27
  27. package/src/readers.mjs +2 -2
  28. package/src/registry/federation.mjs +3056 -0
  29. package/src/registry/gossip.mjs +294 -0
  30. package/src/registry/heartbeats.mjs +205 -0
  31. package/src/registry/lineage-verifier.mjs +972 -0
  32. package/src/registry/lineage.mjs +984 -0
  33. package/src/registry/listings.mjs +612 -0
  34. package/src/registry/resolve.mjs +376 -0
  35. package/src/registry/stats.mjs +508 -0
  36. package/src/sqlite-loader.mjs +40 -0
  37. package/src/vendor/pillar-core.mjs +22 -0
  38. package/src/vendor/uuaid-soul.mjs +2246 -0
  39. package/src/vnext/a6b-common.mjs +270 -0
  40. package/src/vnext/b1-cli.mjs +970 -0
  41. package/src/vnext/card-cli.mjs +370 -0
  42. package/src/vnext/greeter-operator.mjs +160 -0
  43. package/src/vnext/greeter-suggest.mjs +318 -0
  44. package/src/vnext/greeter.mjs +571 -0
  45. package/src/vnext/homes.mjs +48 -0
  46. package/src/vnext/init-cli.mjs +489 -0
  47. package/src/vnext/intro-cli.mjs +81 -0
  48. package/src/vnext/json-dir-mailbox.mjs +304 -0
  49. package/src/vnext/jsonl-mailbox.mjs +1132 -0
  50. package/src/vnext/knock-answer.mjs +162 -0
  51. package/src/vnext/knock-cli.mjs +520 -0
  52. package/src/vnext/knock-lane.mjs +312 -0
  53. package/src/vnext/knock-responder.mjs +344 -0
  54. package/src/vnext/lineage-cli.mjs +653 -0
  55. package/src/vnext/listing-cli.mjs +323 -0
  56. package/src/vnext/resolve-cli.mjs +104 -0
  57. package/src/vnext/soul-cli.mjs +666 -0
  58. package/src/vnext/verify-cli.mjs +333 -0
  59. package/src/vnext/w4-redirect.mjs +178 -0
  60. package/src/vnext/wave-a.mjs +193 -0
  61. package/src/vnext/witness-cli.mjs +547 -0
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 { runVerifyCommand, VERIFY_USAGE } 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,17 @@ 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
+ /** One line, for a command (`recv`, `send`, `send-group`) that has no transport left. */
127
+ const p2pMissingNoCarriers = (verb) =>
128
+ `p2p-not-installed: this home uses libp2p and names no carrier, and @uuaid/pillar-p2p is not installed, so ${verb} has no transport. ` +
129
+ `Install it (npm i @uuaid/pillar-p2p), or name a carrier (pillar init --refresh --carriers <url>, or ${verb} --carrier <url>)`;
130
+
131
+ function openPillar(args, { reader = null, notify = "auto", notifySink = null, needsTransport = false } = {}) {
104
132
  const home = homePath(args);
105
133
  const kcPath = join(home, "keychain.json");
106
134
  const mbPath = join(home, "mailbox.db");
@@ -127,6 +155,18 @@ function loadPillar(args, { reader = null } = {}) {
127
155
  // attached to carrier delivers — raises budgets at carriers trusting the issuer.
128
156
  const tgPath = join(home, "tier-grant.json");
129
157
  const tierGrant = existsSync(tgPath) ? JSON.parse(readFileSync(tgPath, "utf-8")) : null;
158
+ const wantsLibp2p = args.libp2p === true || args.libp2p === "true" || args.libp2p === "1";
159
+ const explicitNoLibp2p = args.libp2p === false || args.libp2p === "false" || args.libp2p === "0";
160
+ const chosenCarrierOnly = explicitNoLibp2p || Boolean(args["carrier-only"]) || cfg.carrierOnly === true;
161
+ const carrierOnly = !wantsLibp2p && (chosenCarrierOnly || !isP2pInstalled());
162
+ // V1 F3: a libp2p home (2.6.1, or init --libp2p) that names no carrier,
163
+ // upgraded without @uuaid/pillar-p2p, has no transport left. recv printed
164
+ // carrier-only and exited 0; send threw "pillar not started" (V1 P3, 2.7.1
165
+ // A8). A command that needs a transport (needsTransport = its verb) refuses.
166
+ if (needsTransport && carrierOnly && !chosenCarrierOnly && carriers.length === 0) {
167
+ console.error(p2pMissingNoCarriers(needsTransport === true ? "this command" : needsTransport));
168
+ exit(1);
169
+ }
130
170
  return new Pillar({
131
171
  keychain: kc,
132
172
  mailboxPath: mbPath,
@@ -135,14 +175,29 @@ function loadPillar(args, { reader = null } = {}) {
135
175
  enableRelay: cfg.enableRelay ?? false,
136
176
  dhtClientMode: cfg.dhtClientMode ?? true,
137
177
  carriers,
138
- enableLibp2p: !(args["carrier-only"] || cfg.carrierOnly === true),
178
+ enableLibp2p: !carrierOnly,
139
179
  trust,
140
180
  tierGrant,
141
181
  reader,
142
182
  receipts: receiptsFor(args, cfg),
183
+ notifySink: notifySink ?? notifySinkFor(home, cfg, notify),
143
184
  });
144
185
  }
145
186
 
187
+
188
+ /** The Zestro bridge is on for this run (cmdRecv starts it on exactly this condition). */
189
+ function zestroBridgeConfigured(args) {
190
+ return !!(args["zestro-bridge"] || process.env.PILLAR_ZESTRO_URL);
191
+ }
192
+
193
+ function notifySinkFor(home, cfg, notify) {
194
+ if (notify !== "auto") return null;
195
+ const ncfg = notifyConfigFrom(cfg);
196
+ return ncfg.present && ncfg.enabled ? new NotifySink({ home, cfg: ncfg }) : null;
197
+ }
198
+
199
+ const loadPillar = openPillar;
200
+
146
201
  /**
147
202
  * Load the address book into `p`, printing every problem with it on stderr
148
203
  * (once), and return the inspection so a later error can say exactly why a
@@ -233,207 +288,6 @@ function writeRuntimeFile(pillar, home) {
233
288
  writeFileSync(join(home, "runtime.json"), JSON.stringify(rt, null, 2), { mode: 0o600 });
234
289
  }
235
290
 
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
291
  /**
438
292
  * pillar id — read-only (2.5.3). It reads only the key file's public part and
439
293
  * config.json: no passphrase, no mailbox, no libp2p node. Up to 2.5.2 it ran
@@ -464,17 +318,19 @@ async function cmdId(args) {
464
318
  exit(2);
465
319
  }
466
320
  const cfg = readConfig(home);
321
+ const wantsLibp2p = args.libp2p === true || args.libp2p === "true" || args.libp2p === "1";
322
+ const carrierOnly = !wantsLibp2p && (Boolean(args["carrier-only"]) || cfg.carrierOnly === true || !isP2pInstalled());
467
323
  console.log(`uuaid: ${pub.uuaid}`);
468
324
  console.log(`publicKey: ${pub.publicKeyHex}`);
469
- if (args["carrier-only"] || cfg.carrierOnly === true) {
325
+ let peerId = null;
326
+ try {
327
+ const der = kc.load({ passphrase: process.env.PILLAR_PASSPHRASE ?? "" }).privateKey.export({ type: "pkcs8", format: "der" });
328
+ peerId = peerIdFromSeedHex(Buffer.from(der.slice(der.length - 32)).toString("hex")).toString();
329
+ } catch { /* wrong or missing passphrase: the public part above is still right */ }
330
+ console.log(`peerId: ${peerId ?? "unknown: the key did not open (set PILLAR_PASSPHRASE to show it)"}`);
331
+ if (carrierOnly) {
470
332
  console.log(`mode: carrier-only (no libp2p)`);
471
333
  } 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
334
  let rt = null;
479
335
  try { rt = JSON.parse(readFileSync(join(home, "runtime.json"), "utf-8")); } catch { /* none, or unreadable */ }
480
336
  if (rt?.uuaid === pub.uuaid && Array.isArray(rt.addrs) && rt.addrs.length) {
@@ -492,7 +348,7 @@ async function cmdId(args) {
492
348
  async function cmdSend(args) {
493
349
  const [recipientArg, kind, jsonStr] = args._.slice(1);
494
350
  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]");
351
+ 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
352
  exit(2);
497
353
  }
498
354
  let payload = {};
@@ -500,7 +356,7 @@ async function cmdSend(args) {
500
356
  try { payload = JSON.parse(jsonStr); }
501
357
  catch (e) { console.error(`the payload is not valid JSON (${e.message}): ${jsonStr.slice(0, 120)}`); exit(2); }
502
358
  }
503
- const p = loadPillar(args);
359
+ const p = loadPillar(args, { needsTransport: "send" });
504
360
  await p.start();
505
361
  const { info, n } = loadContacts(args, p);
506
362
  if (n > 0) console.log(`address book: ${n} peers`);
@@ -508,9 +364,10 @@ async function cmdSend(args) {
508
364
  try { recipient = resolveRecipient(recipientArg, info).uuaid; }
509
365
  catch (e) { await p.stop(); console.error(e.message); exit(2); }
510
366
  const toKey = typeof args["to-pubkey"] === "string" ? args["to-pubkey"] : undefined;
367
+ const regUrl = typeof args.registry === "string" ? args.registry : undefined;
511
368
  // Say WHY there is no key before the library says only that there is none
512
369
  // (a malformed contacts file used to surface as "no public key known").
513
- if (!toKey && !p.addressBook?.get(recipient)?.publicKey && !p.node) {
370
+ if (!toKey && !regUrl && !p.registryUrl && !p.addressBook?.get(recipient)?.publicKey && !p.node) {
514
371
  await p.stop();
515
372
  console.error(explainMissingKey(recipient, info));
516
373
  exit(1);
@@ -518,29 +375,39 @@ async function cmdSend(args) {
518
375
  try {
519
376
  const sent = await p.send({
520
377
  recipient, kind, payload,
521
- recipientPublicKey: toKey, // explicit key for peers outside fleet.json
378
+ recipientPublicKey: toKey,
522
379
  resolveTimeoutMs: 5000,
380
+ registryUrl: regUrl,
381
+ confirmRecovered: args["confirm-recovered"] === true || args["confirm-recovered"] === "true" || args["confirm-recovered"] === "1",
382
+ now: typeof args.now === "string" ? args.now : null,
383
+ allowInsecureLoopback: args["allow-insecure-loopback"] === true || args["allow-insecure-loopback"] === "true",
523
384
  });
524
385
  const { envelope, delivery } = sent;
386
+ const effRecipient = sent.redirectedTo ?? recipient;
525
387
  console.log(`sent envelope ${envelope.id}`);
526
- console.log(` to: ${recipient}${recipient !== recipientArg ? ` (${recipientArg})` : ""}`);
388
+ if (sent.redirectedFrom) console.log(` redirected (W-4): ${sent.redirectedFrom} -> ${sent.redirectedTo} (mapping persisted in ${join(homePath(args), "w4-redirect.json")})`);
389
+ console.log(` to: ${effRecipient}${effRecipient !== recipientArg ? ` (${recipientArg})` : ""}`);
527
390
  console.log(` kind: ${kind}`);
528
391
  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.`);
392
+ 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
393
  if (delivery?.carrier) console.log(` accepted by carrier ${delivery.carrier} (seq ${delivery.seq}) — that is the carrier's receipt, not the recipient's`);
531
394
  if (args["wait-ack"] !== undefined) {
532
395
  const secs = args["wait-ack"] === true ? 60 : Number(args["wait-ack"]);
533
396
  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);
397
+ const r = await waitForAck(p, envelope.id, effRecipient, Date.now() + secs * 1000);
535
398
  if (r.acked) {
536
- console.log(` acknowledged: signed by ${recipient} (${r.how}, ${r.at})`);
399
+ console.log(` acknowledged: signed by ${effRecipient} (${r.how}, ${r.at})`);
537
400
  } 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).`);
401
+ 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
402
  exit(4);
540
403
  }
541
404
  }
542
405
  } catch (e) {
543
406
  if (/no public key known/.test(e.message)) { console.error(explainMissingKey(recipient, info)); exit(1); }
407
+ if (e?.name === "W4RefusalError") {
408
+ console.error(`${e.code}: ${e.fix}`);
409
+ exit(e.code === "confirm-recovered-redirect" ? 3 : 1);
410
+ }
544
411
  throw e;
545
412
  } finally {
546
413
  await p.stop();
@@ -696,7 +563,7 @@ async function cmdSendGroup(args) {
696
563
  const { path: gPath, groups } = loadGroups(args);
697
564
  const group = groups[groupName];
698
565
  const payload = jsonStr ? JSON.parse(jsonStr) : {};
699
- const p = loadPillar(args);
566
+ const p = loadPillar(args, { needsTransport: "send-group" });
700
567
  await p.start();
701
568
  loadContacts(args, p);
702
569
  try {
@@ -738,7 +605,7 @@ function printGroupResults({ group, groupId, msgId, results }) {
738
605
  async function cmdGroups(args) {
739
606
  const home = homePath(args);
740
607
  const { Mailbox } = await import("../src/mailbox/mailbox.mjs");
741
- const mine = existsSync(join(home, "mailbox.db")) ? (() => {
608
+ const mine = (existsSync(join(home, "mailbox.db")) || existsSync(join(home, "mailbox"))) ? (() => {
742
609
  const mb = new Mailbox(join(home, "mailbox.db"));
743
610
  try { return mb.listGroups(); } finally { mb.close(); }
744
611
  })() : [];
@@ -887,7 +754,7 @@ async function cmdGroup(args) {
887
754
  function wantsGroupV2(args) {
888
755
  const home = homePath(args);
889
756
  const mbPath = join(home, "mailbox.db");
890
- const mb = existsSync(mbPath) ? new Mailbox(mbPath) : null;
757
+ const mb = (existsSync(mbPath) || existsSync(join(home, "mailbox"))) ? new Mailbox(mbPath) : null;
891
758
  try { return groupCommandRoute(args, groupRouteLookups(new RosterStore(home), mb)) === "v2"; }
892
759
  finally { mb?.close(); }
893
760
  }
@@ -919,7 +786,72 @@ async function cmdRecv(args) {
919
786
  // contacts file that exists but yields nothing at all stops recv instead.
920
787
  const fleetInfo = inspectFleetFile(fleetPath(args));
921
788
  if (fleetInfo.error) { console.error(`recv: ${fleetInfo.error}`); exit(1); }
922
- const p = loadPillar(args, { reader: rk.key });
789
+ // --notify: this recv is the home's resident wake path. It takes no command
790
+ // text; the hook comes from config.json notify.hook (absolute exec + args).
791
+ const wantsNotify = args.notify !== undefined;
792
+ let notifyCfg = null, notifyStore = null, notifySink = null, wakeHandle = null, notifyDeferred = false, notifyLine = null;
793
+ if (wantsNotify) {
794
+ // V1 F2: the Zestro bridge is a second wake path (unbudgeted, and it
795
+ // forwards payload text). One process never runs both.
796
+ if (zestroBridgeConfigured(args)) { console.error(NOTIFY_BRIDGE_REFUSAL); exit(64); }
797
+ 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); }
798
+ const home = homePath(args);
799
+ if (!existsSync(join(home, "keychain.json"))) { console.error(`no pillar found at ${home}. run: pillar init`); exit(2); }
800
+ notifyCfg = notifyConfigFrom(readConfig(home));
801
+ if (!notifyCfg.enabled) { console.error("recv --notify: notify.enabled is false in config.json"); exit(2); }
802
+ if (notifyCfg.invalid.length) { for (const m of notifyCfg.invalid) console.error(`recv --notify: ${m}`); exit(2); }
803
+ try { checkHook(notifyCfg.hook); } catch (e) { console.error(`recv --notify: ${e.message}`); exit(2); }
804
+ notifyStore = new NotifyStore(home);
805
+ // V1 F3: from here on, stderr in --notify mode is bounded (escaped, words
806
+ // <= 64 chars, lines <= 400), rate-limited, and copied to notify/recv.log.
807
+ const { boundedWriter, PrivateLog } = await import("../src/notify-log.mjs");
808
+ const { format } = await import("node:util");
809
+ notifyLine = boundedWriter({ log: new PrivateLog(notifyStore.dir) });
810
+ console.warn = (...a) => notifyLine(format(...a));
811
+ console.error = (...a) => notifyLine(format(...a));
812
+ process.on("uncaughtException", (e) => { notifyLine(`recv --notify: fatal: ${e?.stack ?? e}`); exit(1); });
813
+ notifySink = new NotifySink({ home, cfg: notifyCfg, store: notifyStore });
814
+ let w = null;
815
+ try { notifyStore.open(); w = await notifyStore.acquireWake("resident"); }
816
+ catch (e) {
817
+ if (e.code !== "notify-custody") throw e;
818
+ // V1 F1d: a custody problem in notify/ never stops mail intake. Receive
819
+ // without notify; retry the wake path every minute.
820
+ console.error(`recv --notify: notify-custody: ${String(e.message).slice(0, 300)}; receiving without notify, retrying every 60 s`);
821
+ notifyDeferred = true;
822
+ }
823
+ if (w && !w.handle) {
824
+ const h = w.heldBy;
825
+ const r = wakeRefusal("resident", h.kind); // V1 F2b: a bridged recv holds it -> exit 64
826
+ 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`);
827
+ exit(r.code);
828
+ }
829
+ if (w) wakeHandle = w.handle;
830
+ }
831
+ // V1 F2b: a recv with the Zestro bridge is a wake path too (one agent
832
+ // command per message). It takes notify/wake.lock as "bridge" before it
833
+ // pulls any mail, so it and a resident or fallback notifier can never run
834
+ // on one home together, whichever starts first. A plain recv takes no lock.
835
+ const bridged = zestroBridgeConfigured(args);
836
+ const bridgeHome = homePath(args);
837
+ if (recvWakeKind({ notify: wantsNotify, bridge: bridged }) === "bridge" && existsSync(join(bridgeHome, "keychain.json"))) {
838
+ const bridgeStore = new NotifyStore(bridgeHome);
839
+ let w = null;
840
+ try { bridgeStore.open(); w = await bridgeStore.acquireWake("bridge"); }
841
+ catch (e) {
842
+ if (e.code !== "notify-custody") throw e;
843
+ // Fail closed: without the lock the bridge could run beside a notifier.
844
+ 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`);
845
+ exit(2);
846
+ }
847
+ if (!w.handle) {
848
+ const r = wakeRefusal("bridge", w.heldBy.kind);
849
+ console.error(r.message);
850
+ exit(r.code);
851
+ }
852
+ wakeHandle = w.handle;
853
+ }
854
+ const p = loadPillar(args, { reader: rk.key, notifySink, notify: recvNotifyMode({ bridge: bridged }), needsTransport: "recv" });
923
855
  await p.start();
924
856
  writeRuntimeFile(p, homePath(args)); // warm handoff: publish live addr for senders
925
857
  const { n } = loadContacts(args, p);
@@ -928,7 +860,6 @@ async function cmdRecv(args) {
928
860
  const prevReader = p.mailbox.getReader(rk.key);
929
861
  // A NEW named reader of a bridged recv starts at the tip: its unread
930
862
  // backlog would otherwise reach the bridge as fresh agent turns.
931
- const bridged = !!(args["zestro-bridge"] || process.env.PILLAR_ZESTRO_URL);
932
863
  const start = bridged ? p.mailbox.inboxTipSeq() : initialCursor(p.mailbox);
933
864
  p.mailbox.touchReader(rk.key, { ...ctx, cursor: prevReader ? 0 : start });
934
865
  const lease = () => p.mailbox.holdLease(rk.key, { ...ctx, ttlMs: LEASE_TTL_MS });
@@ -942,14 +873,58 @@ async function cmdRecv(args) {
942
873
  } else {
943
874
  console.log(`(carrier-only mode: no libp2p listener)`);
944
875
  }
876
+ let notifier = null, notifyRetry = null, wakeGuard = null, bridge = null;
877
+ // Lead L2: a wake path that loses notify/wake.lock (token gone, or the lock
878
+ // unreadable) stops at once: bridge closed, notifier stopped, no hook or
879
+ // command after the loss. It exits 75 (temporary failure): a supervisor
880
+ // restart must take the lock afresh, and is refused (64) while the new
881
+ // holder lives. The lock is re-read every 2 s and before every use.
882
+ const onWakeLockLost = (reason) => {
883
+ try { if (notifier) notifier.stop(); } catch (_e) {}
884
+ try { if (bridge) bridge.close(); } catch (_e) {}
885
+ bridge = null;
886
+ const who = bridged ? "recv (Zestro bridge)" : "recv --notify";
887
+ console.error(`${who}: lost notify/wake.lock (${String(reason).slice(0, 120)}); another wake path holds this home; stopping`);
888
+ try { p.mailbox.releaseLease(rk.key, ctx); } catch (_e) {}
889
+ exit(75);
890
+ };
891
+ const holdsWakeLock = () => !!wakeGuard?.check();
892
+ if (bridged && wakeHandle) wakeGuard = guardLock(wakeHandle, { intervalMs: 2000, onLost: onWakeLockLost });
893
+ const startNotifier = async () => {
894
+ wakeGuard = guardLock(wakeHandle, { intervalMs: 2000, onLost: onWakeLockLost });
895
+ // Activate (baseline at the tip on a first run) BEFORE intake starts.
896
+ notifier = new Notifier({ home: homePath(args), store: notifyStore, cfg: notifyCfg, uuaid: p.uuaid, mailbox: p.mailbox, mode: "resident", log: notifyLine, holdCheck: holdsWakeLock });
897
+ notifySink.onEvent = () => notifier.poke(); // enqueue only; the hook runs apart from the receive path
898
+ const first = await notifier.startResident();
899
+ const how = first.error ? `waiting (${first.error})` : first.activated ? "activated (baseline at the tip)" : "resumed";
900
+ console.log(`notify: resident wake path ${how}; hook ${notifyCfg.hook ? "from notify.hook" : "none: notices go to notify/notifications.jsonl only"}`);
901
+ };
902
+ if (wantsNotify && !notifyDeferred) await startNotifier();
903
+ if (wantsNotify && notifyDeferred) {
904
+ notifyRetry = setInterval(async () => {
905
+ try {
906
+ notifyStore = new NotifyStore(homePath(args));
907
+ notifyStore.open();
908
+ const w = await notifyStore.acquireWake("resident");
909
+ if (!w.handle) { // another wake path took the home meanwhile: keep receiving, keep waiting
910
+ 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`); }
911
+ return;
912
+ }
913
+ wakeHandle = w.handle;
914
+ notifySink.store = notifyStore;
915
+ clearInterval(notifyRetry);
916
+ notifyRetry = null;
917
+ await startNotifier();
918
+ } catch (_e) { /* still unusable: stay quiet, try again in a minute */ }
919
+ }, 60_000);
920
+ }
945
921
  if (p.carrierClient) {
946
922
  p.startCarrierPolling();
947
923
  console.log(`polling carriers: ${p.carriers.join(", ")}`);
948
924
  }
949
925
  if (n > 0) console.log(`address book: ${n} peers from ${fleetPath(args)}`);
950
926
 
951
- let bridge = null;
952
- if (args["zestro-bridge"] || process.env.PILLAR_ZESTRO_URL) {
927
+ if (bridged) {
953
928
  const { ZestroBridge } = await import("../src/bridges/zestro.mjs");
954
929
  bridge = new ZestroBridge({
955
930
  url: process.env.PILLAR_ZESTRO_URL ?? args["zestro-url"],
@@ -969,11 +944,20 @@ async function cmdRecv(args) {
969
944
  // bridge must not send a second ack for a request.
970
945
  const autoAcks = p.receipts.delivered;
971
946
  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));
947
+ if (wantsNotify) {
948
+ // The notify surface is metadata only: no payload or group name on stdout,
949
+ // and id/from only when they pass the protocol checks (V1 F1a, F3).
950
+ console.log(jsonLine({ at: new Date().toISOString(), id: isSafeId(env.id) ? env.id : null, from: isSafeUuaid(env.sender) ? env.sender : null, kind: env.kind }));
951
+ } else {
952
+ const line = { at: new Date().toISOString(), from: env.sender, kind: env.kind, payload: env.payload };
953
+ const tag = extractGroupTag(env.payload);
954
+ 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; }
955
+ if (rk.named) line.id = env.id;
956
+ console.log(jsonLine(line));
957
+ }
958
+ // Lead L2: re-read the lock before forwarding anything to the agent; a
959
+ // bridge that lost it forwards nothing (onWakeLockLost exits).
960
+ if (bridge && !holdsWakeLock()) return;
977
961
  if (bridge && env.kind === "request") {
978
962
  // Interaction-convention return leg: ack FIRST — pillar-ask allows 120s
979
963
  // per phase but ZestroBridge times out at 30s, so the ack goes out before
@@ -1065,6 +1049,10 @@ async function cmdRecv(args) {
1065
1049
  const shutdown = async () => {
1066
1050
  clearInterval(heartbeat);
1067
1051
  if (tail) clearInterval(tail);
1052
+ if (notifier) notifier.stop(); // a running hook's group is killed; its run reads "ambiguous" next time
1053
+ if (wakeGuard) wakeGuard.stop();
1054
+ if (notifyRetry) clearInterval(notifyRetry);
1055
+ if (wakeHandle) { try { releaseLock(wakeHandle); } catch (_e) {} }
1068
1056
  try { p.mailbox.releaseLease(rk.key, ctx); } catch (_e) {}
1069
1057
  if (bridge) bridge.close();
1070
1058
  await p.stop();
@@ -1194,19 +1182,63 @@ async function cmdInbox(args) {
1194
1182
  }
1195
1183
  const newCount = rk.named ? printed.length : pulled;
1196
1184
  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}`);
1185
+ // Lead L5: the legacy hook is a wake path too. It runs only while this run
1186
+ // holds notify/wake.lock (kind "inbox"); a held lock (resident, fallback,
1187
+ // bridge) or an unusable notify/ skips it with one stderr line. The exit
1188
+ // code stays 0 either way: a courier drops stdout on a non-zero exit.
1189
+ const inboxStore = new NotifyStore(homePath(args));
1190
+ let lock = null;
1191
+ let skip = null;
1192
+ try { inboxStore.open(); lock = await inboxStore.acquireWake("inbox"); }
1193
+ catch (e) { skip = `notify/ is unusable (${e.code ?? "error"})`; }
1194
+ if (lock && !lock.handle) skip = `the ${lock.heldBy?.kind ?? "other"} wake path holds notify/wake.lock`;
1195
+ if (skip) {
1196
+ console.error(`inbox --notify: hook skipped: ${skip}; one wake path per home`);
1197
+ } else {
1198
+ try {
1199
+ // Lead T5: the legacy hook gets the same deadline as notify.hook: after
1200
+ // 10 s its process group gets SIGTERM, then SIGKILL, and is reaped (a
1201
+ // hanging command must not hold wake.lock). This run's exit code is
1202
+ // unchanged (0) whatever the hook does.
1203
+ const { status, timedOut } = await runLegacyInboxHook(args.notify, jsonLine({ uuaid: p.uuaid, new: newCount, unread: backlog.length }) + "\n",
1204
+ { ...process.env, PILLAR_NEW: String(newCount), PILLAR_UNREAD: String(backlog.length), PILLAR_UUAID: p.uuaid });
1205
+ if (timedOut) console.error("notify hook timed out after 10 s; its process group was killed");
1206
+ else if (status !== 0) console.error(`notify hook exited ${status}`);
1207
+ } finally {
1208
+ releaseLock(lock.handle);
1209
+ }
1210
+ }
1205
1211
  }
1206
1212
  await p.stop();
1207
1213
  exit(0);
1208
1214
  }
1209
1215
 
1216
+ /**
1217
+ * Run the legacy `inbox --notify CMD` shell command (Lead T5): own process
1218
+ * group, stdin = the summary line, stdout/stderr inherited; after 10 s the
1219
+ * group gets SIGTERM, then SIGKILL 1 s later, and is reaped. Resolves
1220
+ * { status, timedOut }.
1221
+ */
1222
+ async function runLegacyInboxHook(cmd, input, env, { timeoutMs = 10_000, graceMs = 1000 } = {}) {
1223
+ const { spawn } = await import("node:child_process");
1224
+ return new Promise((resolve) => {
1225
+ const child = spawn(cmd, { shell: true, env, detached: true, stdio: ["pipe", "inherit", "inherit"] });
1226
+ const killGroup = (sig) => { try { process.kill(-child.pid, sig); } catch (_e) { /* gone */ } };
1227
+ let timedOut = false;
1228
+ let grace = null;
1229
+ const timer = setTimeout(() => { timedOut = true; killGroup("SIGTERM"); grace = setTimeout(() => killGroup("SIGKILL"), graceMs); }, timeoutMs);
1230
+ child.stdin.on("error", () => {});
1231
+ child.stdin.end(input);
1232
+ child.on("error", () => { clearTimeout(timer); clearTimeout(grace); resolve({ status: 127, timedOut: false }); });
1233
+ child.on("exit", (code, signal) => {
1234
+ clearTimeout(timer);
1235
+ clearTimeout(grace);
1236
+ killGroup("SIGKILL"); // anything it left in its group dies with it
1237
+ resolve({ status: code ?? (signal ? 128 : 1), timedOut });
1238
+ });
1239
+ });
1240
+ }
1241
+
1210
1242
  /**
1211
1243
  * pillar wait — sleep until there is mail, then exit 0 with the count.
1212
1244
  *
@@ -1257,11 +1289,119 @@ async function cmdWait(args) {
1257
1289
  exit(3);
1258
1290
  }
1259
1291
 
1292
+ /**
1293
+ * pillar notify — one-shot new-mail notices. FALLBACK for hosts that cannot
1294
+ * keep a process; the main path is a resident `pillar recv --notify` (print a
1295
+ * unit with --print-unit launchd|systemd; nothing is installed, and the hook
1296
+ * comes from config.json notify.hook, never from the command line).
1297
+ *
1298
+ * Never pulls or stores. Holds the single wake-path lock (notify/wake.lock)
1299
+ * for the run, so it never runs beside a resident notifier. It claims
1300
+ * committed eligibility events (written by whichever reader stored the mail,
1301
+ * after final admission), under the same budget, cursor and log as the
1302
+ * resident path, and runs the hook once for them (src/notify-runner.mjs).
1303
+ * The first run baselines at the tip. A carrier peek adds an unverified
1304
+ * count only (verified: false): it cannot prove group admission, and it
1305
+ * never starts a hook.
1306
+ *
1307
+ * pillar notify [--home DIR] [--fleet FILE] [--groups FILE]
1308
+ * pillar notify --print-unit launchd|systemd [--label L]
1309
+ * pillar notify --print-unit cron [--every MIN]
1310
+ */
1311
+ async function cmdNotify(args) {
1312
+ const home = homePath(args);
1313
+ if (args["print-unit"] !== undefined) {
1314
+ const { renderUnit } = await import("../src/notify.mjs");
1315
+ 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); }
1316
+ const pillarBin = join(dirname(fileURLToPath(import.meta.url)), "pillar.mjs");
1317
+ try {
1318
+ process.stdout.write(renderUnit(String(args["print-unit"]), {
1319
+ node: process.execPath, pillarBin, home: resolvePath(home),
1320
+ label: typeof args.label === "string" ? args.label : null,
1321
+ everyMinutes: args.every !== undefined ? Number(args.every) : 5,
1322
+ }));
1323
+ } catch (e) { console.error(e.message); exit(2); }
1324
+ if (!notifyConfigFrom(existsSync(join(home, "config.json")) ? readConfig(home) : {}).hook && String(args["print-unit"]) !== "cron") {
1325
+ console.error("note: this home has no notify.hook yet; the unit runs, but notices go to notify/notifications.jsonl only");
1326
+ }
1327
+ return;
1328
+ }
1329
+ const N = await import("../src/notify.mjs");
1330
+ if (zestroBridgeConfigured(args)) { console.error(NOTIFY_BRIDGE_REFUSAL); exit(64); } // V1 F2
1331
+ if (!existsSync(join(home, "keychain.json"))) { console.error(`no pillar found at ${home}. run: pillar init`); exit(2); }
1332
+ const cfg = N.notifyConfigFrom(readConfig(home));
1333
+ if (!cfg.enabled) { console.log(jsonLine({ enabled: false, notified: 0 })); exit(0); }
1334
+ // R2 H2: no notify block = the readers of this home write no eligibility
1335
+ // events, so there is nothing to notify. Write nothing (no notify/ dir).
1336
+ if (!cfg.present) {
1337
+ 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)");
1338
+ console.log(jsonLine({ enabled: false, notified: 0 }));
1339
+ exit(0);
1340
+ }
1341
+ if (cfg.invalid.length) { for (const m of cfg.invalid) console.error(`notify: ${m}`); exit(2); }
1342
+ try { checkHook(cfg.hook); } catch (e) { console.error(`notify: ${e.message}`); exit(2); }
1343
+ const store = new NotifyStore(home);
1344
+ let wake;
1345
+ try {
1346
+ store.open();
1347
+ wake = await store.acquireWake("fallback");
1348
+ } catch (e) {
1349
+ 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); }
1350
+ throw e;
1351
+ }
1352
+ if (!wake.handle) {
1353
+ const h = wake.heldBy;
1354
+ const r = wakeRefusal("fallback", h.kind); // V1 F2b: a live bridged recv -> exit 64
1355
+ 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`);
1356
+ console.log(jsonLine({ refused: true, heldBy: h.kind ?? "unknown", notified: 0 }));
1357
+ exit(r.code);
1358
+ }
1359
+ args["carrier-only"] = true;
1360
+ const p = loadPillar(args, { reader: null, notify: "off" });
1361
+ await p.start();
1362
+ loadContacts(args, p); // a "directory" policy needs known senders for the peek
1363
+ let code = 0;
1364
+ try {
1365
+ const notifier = new Notifier({ home, store, cfg, uuaid: p.uuaid, mailbox: p.mailbox, mode: "fallback" });
1366
+ let r;
1367
+ try { r = await notifier.tick(); }
1368
+ catch (e) {
1369
+ // V1 F1d: one bounded line and a status, never a stack.
1370
+ if (e.code !== "notify-custody") throw e;
1371
+ console.error(`notify: notify-custody: ${String(e.message).slice(0, 300)}`);
1372
+ r = { error: "notify-custody" };
1373
+ code = 2;
1374
+ }
1375
+ let carrier = null;
1376
+ const pageInfo = {};
1377
+ if (p.carrierClient) {
1378
+ try { carrier = (await p.peekCarrierInbox({ deadlineMs: Date.now(), waitS: 0, match: (v) => N.qualifies(v, cfg), pageInfo })).length; }
1379
+ catch (e) { code = code || 1; console.error(`notify: ${refusalLine(e) ?? e?.message ?? String(e)}`); }
1380
+ }
1381
+ console.log(jsonLine({
1382
+ uuaid: p.uuaid, activated: !!r.activated, pending: r.pending ?? 0,
1383
+ notified: r.input?.new ?? 0, records: r.input?.records ?? [], more: r.input?.more ?? 0,
1384
+ ...(r.deferred ? { deferred: r.deferred, nextAt: Number.isFinite(r.nextAt) ? new Date(r.nextAt).toISOString() : null } : {}),
1385
+ ...(r.refusedHook ? { refusedHook: r.refusedHook } : {}),
1386
+ ...(r.busy ? { busy: r.busy } : {}), // the writer lock stayed held: nothing claimed, try again
1387
+ ...(r.error ? { error: r.error } : {}),
1388
+ hook: r.hook ? { status: r.hook.status, code: r.hook.code ?? null, ms: r.hook.ms ?? 0 } : null,
1389
+ // A peek is a count, never a notice. truncated: a carrier page was full
1390
+ // (or a carrier's answer was abandoned), so `count` is a lower bound.
1391
+ carrier: { count: carrier, verified: false, truncated: !!(pageInfo.full || pageInfo.partial) },
1392
+ }));
1393
+ } finally {
1394
+ releaseLock(wake.handle);
1395
+ await p.stop();
1396
+ }
1397
+ exit(code);
1398
+ }
1399
+
1260
1400
  /** pillar readers — every reader of this home, its cursor, and live leases. */
1261
1401
  async function cmdReaders(args) {
1262
1402
  const home = homePath(args);
1263
1403
  const { Mailbox } = await import("../src/mailbox/mailbox.mjs");
1264
- if (!existsSync(join(home, "mailbox.db"))) { console.log(`no mailbox at ${home} yet`); return; }
1404
+ if (!existsSync(join(home, "mailbox.db")) && !existsSync(join(home, "mailbox"))) { console.log(`no mailbox at ${home} yet`); return; }
1265
1405
  const mb = new Mailbox(join(home, "mailbox.db"));
1266
1406
  try {
1267
1407
  const tip = mb.inboxTipSeq();
@@ -1396,16 +1536,25 @@ async function cmdTrust(args) {
1396
1536
  const { Mailbox } = await import("../src/mailbox/mailbox.mjs");
1397
1537
  const mb = new Mailbox(join(home, "mailbox.db"));
1398
1538
  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
1539
  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(", ")}`);
1540
+ if (mb.mode !== "json-dir") {
1541
+ // An id is unique only within its sender: with two quarantined senders
1542
+ // under one id, --from picks which one to release.
1543
+ const held = mb.quarantinedSenders(args.release);
1544
+ if (!from && held.length > 1) {
1545
+ console.error(`${held.length} senders have ${args.release} quarantined; release one with --from <uuaid>: ${held.join(", ")}`);
1546
+ mb.close();
1547
+ exit(2);
1548
+ }
1549
+ }
1550
+ let changed;
1551
+ try {
1552
+ changed = mb.releaseQuarantined(args.release, from);
1553
+ } catch (e) {
1554
+ console.error(e instanceof Error ? e.message : String(e));
1405
1555
  mb.close();
1406
- exit(2);
1556
+ exit(1);
1407
1557
  }
1408
- const changed = mb.releaseQuarantined(args.release, from);
1409
1558
  if (changed === 0) {
1410
1559
  console.error(`no quarantined row with id ${args.release}${from ? ` from ${from}` : ""} — nothing released`);
1411
1560
  mb.close();
@@ -1500,17 +1649,122 @@ async function cmdTier(args) {
1500
1649
  async function cmdPeers(args) {
1501
1650
  const p = loadPillar(args);
1502
1651
  await p.start();
1652
+ if (!p.node) {
1653
+ console.log("0 connected peers (carrier-only mode)");
1654
+ await p.stop();
1655
+ return;
1656
+ }
1503
1657
  const peers = p.node.getPeers();
1504
1658
  console.log(`${peers.length} connected peers:`);
1505
1659
  for (const peer of peers) console.log(` ${peer.toString()}`);
1506
1660
  await p.stop();
1507
1661
  }
1508
1662
 
1663
+ const PRE_CMD_BOOL_FLAGS = new Set(["json", "force", "refresh", "carrier-only", "libp2p", "offline", "no-receipts", "ack", "a2a", "drain", "withdraw"]);
1664
+
1665
+ function findCommandIndex(raw) {
1666
+ for (let i = 0; i < raw.length; i++) {
1667
+ const a = raw[i];
1668
+ if (a === "--") return i + 1 < raw.length ? i + 1 : -1;
1669
+ if (a.startsWith("--")) {
1670
+ const eq = a.indexOf("=");
1671
+ const key = eq === -1 ? a.slice(2) : a.slice(2, eq);
1672
+ if (eq === -1 && !PRE_CMD_BOOL_FLAGS.has(key) && i + 1 < raw.length && !raw[i + 1].startsWith("-")) {
1673
+ i++;
1674
+ }
1675
+ continue;
1676
+ }
1677
+ if (a.startsWith("-") && a !== "-") {
1678
+ if (!a.includes("=") && i + 1 < raw.length && !raw[i + 1].startsWith("-")) {
1679
+ i++;
1680
+ }
1681
+ continue;
1682
+ }
1683
+ return i;
1684
+ }
1685
+ return -1;
1686
+ }
1687
+
1688
+ 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]
1689
+ pillar verify <file|-> verify a saved artifact offline (card, listing, lineage log, intro, ...)
1690
+ pillar verify <uuaid> verify an agent live: its registry listing, card and lineage
1691
+ pillar <command> --help usage of one command (verify, group, notify)`;
1692
+ const NOTIFY_USAGE = `usage:
1693
+ pillar notify [--home DIR] [--fleet FILE] [--groups FILE]
1694
+ pillar notify --print-unit launchd|systemd [--label L]
1695
+ pillar notify --print-unit cron [--every MIN]`;
1696
+
1697
+ /** Usage for `pillar [<command>] --help`: the command's own text where it has one, else pillar's. */
1698
+ function helpText(raw) {
1699
+ const rest = raw.filter((a) => a !== "--help" && a !== "-h");
1700
+ const i = findCommandIndex(rest);
1701
+ const cmd = i === -1 ? undefined : rest[i];
1702
+ if (cmd === "group") return GROUP_V2_USAGE; // the v1 cmdGroup text stays inside its pinned bytes
1703
+ if (cmd === "notify") return NOTIFY_USAGE;
1704
+ if (cmd === "verify") return VERIFY_USAGE;
1705
+ return USAGE;
1706
+ }
1707
+
1509
1708
  async function main() {
1510
- const args = parseArgs(argv.slice(2));
1709
+ const raw = argv.slice(2);
1710
+ if (wantsHelp(raw)) await exitWithHelp(helpText(raw)); // R2: before any home, key, file or carrier is touched
1711
+ const cmdIdx = findCommandIndex(raw);
1712
+ const directCmd = cmdIdx === -1 ? undefined : raw[cmdIdx];
1713
+ const VNEXT_DIRECT_CMDS = new Set(["verify", "lineage", "init", "card", "knock", "knocks", "answer", "intro", "resolve", "listing", "soul"]);
1714
+ if (VNEXT_DIRECT_CMDS.has(directCmd)) {
1715
+ const subRaw = [...raw.slice(0, cmdIdx), ...raw.slice(cmdIdx + 1)];
1716
+ if (directCmd === "soul") {
1717
+ const { exitCode } = await runSoulCli(subRaw);
1718
+ exit(exitCode);
1719
+ }
1720
+ if (directCmd === "verify") {
1721
+ const { exitCode } = await runVerifyCommand(subRaw);
1722
+ exit(exitCode);
1723
+ }
1724
+ if (directCmd === "lineage") {
1725
+ const { exitCode } = await runLineageCli(subRaw);
1726
+ exit(exitCode);
1727
+ }
1728
+ if (directCmd === "init") {
1729
+ const { exitCode } = await runInitCli(subRaw);
1730
+ exit(exitCode);
1731
+ }
1732
+ if (directCmd === "card") {
1733
+ const { exitCode } = await runCardCli(subRaw);
1734
+ exit(exitCode);
1735
+ }
1736
+ if (directCmd === "intro") {
1737
+ const { exitCode } = runIntroCli(subRaw);
1738
+ exit(exitCode);
1739
+ }
1740
+ if (directCmd === "resolve") {
1741
+ const { exitCode } = await runResolveCli(subRaw);
1742
+ exit(exitCode);
1743
+ }
1744
+ if (directCmd === "listing") {
1745
+ const { exitCode } = await runListingCli(subRaw);
1746
+ exit(exitCode);
1747
+ }
1748
+ if (directCmd === "knock") {
1749
+ const { exitCode } = await runKnockCli(subRaw);
1750
+ exit(exitCode);
1751
+ }
1752
+ if (directCmd === "knocks") {
1753
+ const { exitCode } = await runKnocksCli(subRaw);
1754
+ exit(exitCode);
1755
+ }
1756
+ const { exitCode } = await runAnswerCli(subRaw);
1757
+ exit(exitCode);
1758
+ }
1759
+ const args = parseArgs(raw);
1760
+ for (const bf of ["carrier-only", "libp2p", "offline", "confirm-recovered", "allow-insecure-loopback"]) {
1761
+ if (typeof args[bf] === "string" && !["true", "false", "1", "0"].includes(args[bf])) {
1762
+ args._.unshift(args[bf]);
1763
+ args[bf] = true;
1764
+ }
1765
+ }
1511
1766
  const cmd = args._[0];
1512
1767
  switch (cmd) {
1513
- case "init": return cmdInit(args);
1514
1768
  case "id": return cmdId(args);
1515
1769
  case "send": return cmdSend(args);
1516
1770
  case "send-group": return cmdSendGroup(args);
@@ -1522,6 +1776,7 @@ async function main() {
1522
1776
  case "peers": return cmdPeers(args);
1523
1777
  case "delegate": return cmdDelegate(args);
1524
1778
  case "wait": return cmdWait(args);
1779
+ case "notify": return cmdNotify(args);
1525
1780
  case "readers": return cmdReaders(args);
1526
1781
  case "status": return cmdStatus(args);
1527
1782
  case "receipts": return cmdReceipts(args);
@@ -1529,7 +1784,7 @@ async function main() {
1529
1784
  if (wantsGroupV2(args)) return cmdGroupV2(args); // @rule P-cli-dispatch-v2
1530
1785
  return cmdGroup(args);
1531
1786
  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]`);
1787
+ console.error(USAGE);
1533
1788
  exit(2);
1534
1789
  }
1535
1790
  }