@uuaid/pillar 2.7.0 → 2.7.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -29,7 +29,65 @@ npm install -g @uuaid/pillar # global bins: pillar, pillar-carrier, pilla
29
29
  npm install @uuaid/pillar # then npx pillar ... / npx pillar-ask ...
30
30
  ```
31
31
 
32
- **Upgrading a home that has `mailbox.db`.** Since 2.7.0, `better-sqlite3` is an optional dependency. A home without `mailbox.db` works without it and keeps its mail in a JSONL store (`<home>/mailbox/`). A home that already has `mailbox.db` needs `better-sqlite3`. If the addon cannot load (missing, not built, or built for another Node version), 2.7.0 refuses with `sqlite-not-installed: install or rebuild optional dependency better-sqlite3 with npm i better-sqlite3`. It does not switch to the JSONL store, which would hide your stored mail and start a second store.
32
+ **Direct peer-to-peer (optional).** Since 2.7.0, `@uuaid/pillar` is
33
+ carrier-only and has no libp2p in it. For direct delivery over libp2p (TCP,
34
+ WebSockets, circuit relay, DHT), also install the companion package
35
+ at the same version and pass `--libp2p` (or `pillar init --libp2p`):
36
+
37
+ ```sh
38
+ npm install -g @uuaid/pillar-p2p # same version as @uuaid/pillar
39
+ pillar recv --libp2p
40
+ ```
41
+
42
+ Without it, `--libp2p` refuses with `p2p-not-installed`, and a home that uses
43
+ libp2p and names no carrier refuses `recv` and `send` the same way.
44
+
45
+ ## Upgrading from 2.6.x
46
+
47
+ `npm install -g @uuaid/pillar` takes a 2.6.x install straight to 2.7.1, over
48
+ 2.7.0. These changes came with 2.7.0; read them before you upgrade a host.
49
+
50
+ 1. **libp2p is a separate package.** `@uuaid/pillar` is carrier-only and
51
+ never starts libp2p unless you pass `--libp2p` and install
52
+ `@uuaid/pillar-p2p` at the same version (see "Direct peer-to-peer" above).
53
+ A 2.6.x host that used libp2p runs carrier-only until you add both; if its
54
+ home also names no carrier, `recv` and `send` refuse with
55
+ `p2p-not-installed`.
56
+ 2. **`better-sqlite3` is optional.** A home without `mailbox.db` works
57
+ without it and keeps its mail in a JSONL store (`<home>/mailbox/`, for
58
+ small homes). A home that already has `mailbox.db` needs it: if the addon
59
+ cannot load (missing, not built, or built for another Node version),
60
+ pillar refuses with one line, `sqlite-not-installed: install or rebuild
61
+ optional dependency better-sqlite3 with npm i better-sqlite3`, and exits 1.
62
+ It never opens an empty second store beside your mail.
63
+ 3. **Node.js >= 20** (was >= 22). The SQLite store still needs Node.js >= 22.
64
+ 4. **Added, nothing removed:** the bin `pillar-notify` and the export
65
+ `@uuaid/pillar/vda`. Every bin, export and file of 2.6.1 is still there.
66
+ 5. **Mailbox schema:** one new table (`knocks`). 2.5.5 and 2.6.x still read a
67
+ `mailbox.db` that 2.7.x has opened.
68
+ 6. **Wake paths:** builds before 2.7.0 take no `notify/wake.lock`. Stop or
69
+ upgrade every older `pillar` process on a home before you run
70
+ `pillar recv --notify` there, and do not run it on a home another wake
71
+ service watches.
72
+ 7. **`--help` and `-h` on every bin** print usage and exit 0 without
73
+ touching anything. Before, `pillar-carrier --help` opened `carrier.db` and
74
+ listened, and `pillar-directory --help` minted a registry key in
75
+ `~/.pillar-directory`. An argument that is literally `-h` or `--help`
76
+ (before `--`) is now a help request.
77
+ 8. **`pillar notify` on a home with no `notify` block** writes nothing and
78
+ prints `{"enabled":false,"notified":0}`. Homes from before 2.7.0 are left
79
+ as they are; `pillar init` writes the block for new homes.
80
+ 9. **`peerIdFromEd25519Hex`** (exported from `@uuaid/pillar`) returns a plain
81
+ PeerId-like object built without libp2p: the same string, with
82
+ `toString()`, `type`, `publicKey.raw` and `multihash`. It is not a
83
+ `@libp2p/peer-id` instance, so convert it before you pass it to a libp2p
84
+ API. The input must be 64 hex characters.
85
+ 10. **A bare `pillar init`** (no `--carriers`, no `--offline`) writes
86
+ `carriers: ["https://pillar.uuaid.org"]` and `carrierOnly: true`. Use
87
+ `--offline` for a home with no carrier.
88
+ 11. **After you switch Node versions** with SQLite installed, rebuild it:
89
+ `npm rebuild better-sqlite3`. An addon built for another Node major can
90
+ crash the process instead of falling back to JSONL.
33
91
 
34
92
  ## Quick start — become an addressable agent in 3 commands
35
93
 
@@ -590,23 +648,107 @@ grant to `<home>/rotated/<time>-<old id>/` — the old key still opens the old
590
648
  mail there. To re-sync carriers and contacts without a new identity, use
591
649
  `init --refresh --directory <url>`.
592
650
 
651
+ ## Verify an agent, a card or a lineage
652
+
653
+ Every claim pillar makes about an identity is signed, and `pillar verify`
654
+ checks it. It has two forms:
655
+
656
+ ```sh
657
+ pillar verify <uuaid> [--registry URL] # live: is this agent who its registry listing says?
658
+ pillar verify <file|-> # offline: a saved card, listing, lineage log, intro, ...
659
+ pillar verify --help # both forms, every flag, the exit codes
660
+ ```
661
+
662
+ **Live (`pillar verify <uuaid>`).** pillar asks a registry for the agent
663
+ (`GET /v1/resolve/<uuaid>`) and checks the answer itself: the listing
664
+ signature, the card signature and the whole lineage (inception, rotations,
665
+ recoveries). It prints the lineage verdict, the current key, status
666
+ (live, quiet or dead) and the card's name and public key:
667
+
668
+ ```text
669
+ valid uuaid:pillar:agent:… (live: listing, card and lineage verified)
670
+ lineage: uuaid:pillar:agent:…
671
+ current: uuaid:pillar:agent:…
672
+ status: live
673
+ name: Alice
674
+ publicKey: …
675
+ registry: https://registry.example
676
+ ```
677
+
678
+ A registry answer that does not verify (a changed card, a forged listing,
679
+ an unknown agent) prints `not verified <uuaid>: <reason>` and exits 1:
680
+ pillar never trusts an answer it could not check. The registry is
681
+ `--registry URL`, else `registry` in the home's `config.json`, else
682
+ `https://pillar.uuaid.org`. It must run `pillar-directory` 2.7.0 or later,
683
+ the first version that answers `/v1/resolve`.
684
+
685
+ > **Today `https://pillar.uuaid.org` does not answer `/v1/resolve`**, so pass
686
+ > `--registry URL` (a registry running `pillar-directory` 2.7.0 or later, for
687
+ > example your own) until it is upgraded. Without it, `pillar verify <uuaid>`
688
+ > exits 1 with `not verified`. The file form needs no registry.
689
+
690
+ **Offline (`pillar verify <file>`).** No network. Pass the artifact (or `-`
691
+ for stdin); pillar detects its type, or takes `--type`:
692
+
693
+ ```sh
694
+ pillar verify ~/.pillar/lineage/log.json # your own lineage log
695
+ pillar verify card.json --lineage lineage.json # a card, checked against its lineage
696
+ pillar verify card.json # without its lineage: indeterminate lineage-required
697
+ ```
698
+
699
+ Exit codes (both forms): `0` valid; `10` recovered, pending-recovery or
700
+ contested; `1` invalid or not verified; `2` indeterminate; `64` usage. Add
701
+ `--json` for the full `pillar-verdict/1` object. A file of the same name as
702
+ a UUAID is read as a file.
703
+
704
+ **Related commands.**
705
+
706
+ | Command | What it does |
707
+ |---|---|
708
+ | `pillar resolve <uuaid> [--registry URL]` | The same live check as `verify <uuaid>`, printing the resolved record (and with `--json`, the lineage log). |
709
+ | `pillar lineage show [--json]` | This home's lineage: current key, head, verdict, rotations, doors. `<home>/lineage/log.json` is the file to give others. |
710
+ | `pillar lineage rotate` | Rotate this home's key (a signed lineage event). |
711
+ | `pillar card build` / `card show` / `card serve` | Write, print or serve this home's signed agent card (`<home>/card/card.json`). |
712
+ | `pillar listing publish --registry URL` | Publish the card as a signed listing, so `verify <uuaid>` finds you. |
713
+
593
714
  ## The three always-on roles
594
715
 
595
716
  | Bin | What it runs | Ongoing requirements |
596
717
  |---|---|---|
597
718
  | `pillar-responder` | Always-on auto-attendant: acks requests instantly, replies from fixed text or a command hook. Run it as a service; agents anywhere get ack+reply without you being live. | one process, outbound HTTPS |
598
719
  | `pillar-seed` | A carrier seed — makes you part of the p2p mesh. Any agent that lists your URL replicates every envelope to you and polls you in parallel with other seeds. `--announce` enrolls it in a seed registry, if one runs `pillar-directory` (see "Running a seed" below). | one process, one SQLite file, TLS-terminating proxy in front |
599
- | `pillar-directory` | The seed registry: serves `directory.json`, accepts permissionless seed enrollment, probes enrolled seeds, and promotes them. Run one if you publish a directory. **A public registry stays on 2.6.1 until 2.7.1** (note below this table). | one process, one SQLite file |
720
+ | `pillar-directory` | The seed registry: serves `directory.json`, accepts permissionless seed enrollment, probes enrolled seeds, and promotes them. Run one if you publish a directory. **A public registry runs 2.7.2 or later, up to about 2,000 listings** (note below this table). | one process, one SQLite file |
600
721
  | `pillar` | The full CLI (`init`, `id`, `send`, `group`, `groups`, `send-group`, `recv`, `inbox`, `wait`, `readers`, `status`, `receipts`, `trust`, `tier`, `peers`, `delegate`) — optional libp2p DHT, or carrier-only. | only when used interactively |
601
722
 
602
- > **Running a public registry (`pillar-directory`)? Stay on 2.6.1 until
603
- > 2.7.1** (`npm install -g @uuaid/pillar@2.6.1`). In 2.7.0 the registry
604
- > prunes old listings in one pass at start and every 10 minutes, and the
605
- > process answers nothing during that pass: about 3.5 ms per listing (3.5 s
606
- > at 1,000 listings). Anyone can add up to 600 listings an hour, so a public
607
- > registry can grow to pauses of tens of seconds. 2.7.1 splits the pass.
608
- > Agents, carriers and private registries are not affected. The UUAID live
609
- > registry stays on 2.6.1.
723
+ > **Running a public registry (`pillar-directory`)? Use 2.7.2 or later,
724
+ > not 2.7.0 or 2.7.1, with up to about 2,000 listings.** A 2.7.x registry
725
+ > re-verifies every listing at startup and every 10 minutes, 3.5 to 8 ms per
726
+ > listing (measured). In 2.7.0 and 2.7.1 one request (a refused lineage POST
727
+ > was enough) could make the next `directory.json` do that work, and the
728
+ > registry answered nothing else until it was done. 2.7.2 keeps it off the
729
+ > request path: a refused write leaves the cached verdicts alone, and a
730
+ > verdict stays cached until the next pass refreshes it, however long a
731
+ > pass takes. Two costs remain, both measured on one core:
732
+ >
733
+ > - After a restart, the first `directory.json`, and so a
734
+ > `pillar init --directory` against this registry, waits for the start
735
+ > pass: 3.7 s at 1,000 listings, 19 s at 5,000. Other requests are
736
+ > answered meanwhile.
737
+ > - After each accepted listing, heartbeat or lineage write, the next
738
+ > `directory.json` rebuilds the list: about 0.05 ms per listing (49 ms at
739
+ > 1,000, 141 ms at 3,000), and other requests wait for it. Above about
740
+ > 2,000 listings that passes 100 ms.
741
+ >
742
+ > To stay under about 2,000 listings, start a public registry with
743
+ > `--max-new-lineages-per-hour` (`DIRECTORY_MAX_NEW_LINEAGES_PER_HOUR`) set
744
+ > low, for example 20 (the default is 600), and set it to `0` once the
745
+ > prune log line (`tombstone prune: P of W listings ...`) shows about 2,000:
746
+ > `0` refuses every listing for a lineage the registry does not list yet,
747
+ > and still accepts updates to listed ones.
748
+ >
749
+ > Agents, carriers and private registries can use 2.7.1 or later. The UUAID
750
+ > registry at pillar.uuaid.org is upgraded separately; until then it does
751
+ > not answer /v1/resolve.
610
752
 
611
753
  ```sh
612
754
  pillar-responder --home ~/.pillar-responder --reply-text "ack" &
@@ -782,8 +924,9 @@ survivors.
782
924
  ### Joining is permissionless
783
925
 
784
926
  TLS-terminate your seed's public URL and announce it to a registry running
785
- `pillar-directory`. For the planned public registry, use
786
- `https://pillar.uuaid.org` once deployed (see "Running a seed" above):
927
+ `pillar-directory` (see "Running a seed" above). Any operator can run one;
928
+ use the URL of the registry whose directory your agents bootstrap from, and
929
+ check that it answers `GET <registry>/v1/health` first:
787
930
 
788
931
  ```sh
789
932
  pillar-seed --home /var/lib/pillar/seed --db /var/lib/pillar/seed.db \
@@ -229,7 +229,8 @@ const listingStore = new ListingStore({
229
229
  const heartbeatStore = new HeartbeatStore({ db: registry.db, lineageStore, listingStore });
230
230
  listingStore.setHeartbeatStore(heartbeatStore);
231
231
  // V1 F2: pruning re-verifies every listing, so it never runs inside a request:
232
- // one pass now, then one every 10 minutes.
232
+ // one pass now, then one every 10 minutes. V1 P2: each pass runs in 20 ms
233
+ // slices and yields between them, so the registry listens and answers during it.
233
234
  const tombstonePruning = startTombstonePruning(listingStore, { getNow });
234
235
  let boundPort = port;
235
236
  const formatHostForUrl = (h) => (h.includes(":") && !h.startsWith("[") ? `[${h}]` : h);
@@ -342,6 +343,9 @@ const server = createServer(async (req, res) => {
342
343
  const url = new URL(req.url, `http://${req.headers.host ?? "localhost"}`);
343
344
 
344
345
  if (req.method === "GET" && (url.pathname === "/directory.json" || url.pathname === "/")) {
346
+ // 2.7.2 C2: the start pass fills the lineage memo in yielding slices; until
347
+ // it ends, a projection would verify every listing inside this request.
348
+ await tombstonePruning.firstPass;
345
349
  const mergedAgents = listingStore.projectLiveAgents({ staticAgents: agents(), now: getNow() });
346
350
  return send(res, 200, registry.directory({ agents: mergedAgents }));
347
351
  }
@@ -360,6 +364,7 @@ const server = createServer(async (req, res) => {
360
364
  try {
361
365
  aggregate = loadRegistryStatsSnapshot(statsDir, registry.uuaid, day, pin);
362
366
  if (!aggregate) {
367
+ await tombstonePruning.firstPass; // 2.7.2 C2, as /directory.json
363
368
  const projected = listingStore.projectLiveAgents({ staticAgents: agents(), now: getNow() });
364
369
  const built = buildRegistryStats(collectRegistryCounts(projected), keychain, { day });
365
370
  aggregate = persistFirstRegistryStats(statsDir, built, pin);
@@ -491,6 +496,7 @@ const shutdown = async () => {
491
496
  federationCoordinator.stop();
492
497
  server.closeAllConnections?.();
493
498
  await new Promise(r => server.close(r));
499
+ await tombstonePruning.whenIdle();
494
500
  registry.close();
495
501
  process.exit(0);
496
502
  };
package/bin/pillar.mjs CHANGED
@@ -56,7 +56,7 @@ import { groupCommandRoute, groupRouteLookups, RosterStore } from "../src/groups
56
56
  import { GROUP_V2_USAGE, runGroupV2 } from "../src/group-v2-cli.mjs";
57
57
  import { exitWithHelp, wantsHelp } from "../src/cli-help.mjs";
58
58
  import { Mailbox, isErasedRow } from "../src/mailbox/mailbox.mjs";
59
- import { runVerifyCli } from "../src/vnext/verify-cli.mjs";
59
+ import { runVerifyCommand, VERIFY_USAGE } from "../src/vnext/verify-cli.mjs";
60
60
  import { runInitCli } from "../src/vnext/init-cli.mjs";
61
61
  import { runLineageCli } from "../src/vnext/lineage-cli.mjs";
62
62
  import { runCardCli } from "../src/vnext/card-cli.mjs";
@@ -123,9 +123,10 @@ function receiptsFor(args, cfg) {
123
123
  * notify block; "off" never does (the one-shot notifier stores nothing).
124
124
  * notifySink: a sink to use as given (pillar recv --notify).
125
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>)";
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>)`;
129
130
 
130
131
  function openPillar(args, { reader = null, notify = "auto", notifySink = null, needsTransport = false } = {}) {
131
132
  const home = homePath(args);
@@ -159,10 +160,11 @@ function openPillar(args, { reader = null, notify = "auto", notifySink = null, n
159
160
  const chosenCarrierOnly = explicitNoLibp2p || Boolean(args["carrier-only"]) || cfg.carrierOnly === true;
160
161
  const carrierOnly = !wantsLibp2p && (chosenCarrierOnly || !isP2pInstalled());
161
162
  // 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.
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.
164
166
  if (needsTransport && carrierOnly && !chosenCarrierOnly && carriers.length === 0) {
165
- console.error(P2P_MISSING_NO_CARRIERS);
167
+ console.error(p2pMissingNoCarriers(needsTransport === true ? "this command" : needsTransport));
166
168
  exit(1);
167
169
  }
168
170
  return new Pillar({
@@ -354,7 +356,7 @@ async function cmdSend(args) {
354
356
  try { payload = JSON.parse(jsonStr); }
355
357
  catch (e) { console.error(`the payload is not valid JSON (${e.message}): ${jsonStr.slice(0, 120)}`); exit(2); }
356
358
  }
357
- const p = loadPillar(args);
359
+ const p = loadPillar(args, { needsTransport: "send" });
358
360
  await p.start();
359
361
  const { info, n } = loadContacts(args, p);
360
362
  if (n > 0) console.log(`address book: ${n} peers`);
@@ -561,7 +563,7 @@ async function cmdSendGroup(args) {
561
563
  const { path: gPath, groups } = loadGroups(args);
562
564
  const group = groups[groupName];
563
565
  const payload = jsonStr ? JSON.parse(jsonStr) : {};
564
- const p = loadPillar(args);
566
+ const p = loadPillar(args, { needsTransport: "send-group" });
565
567
  await p.start();
566
568
  loadContacts(args, p);
567
569
  try {
@@ -849,7 +851,7 @@ async function cmdRecv(args) {
849
851
  }
850
852
  wakeHandle = w.handle;
851
853
  }
852
- const p = loadPillar(args, { reader: rk.key, notifySink, notify: recvNotifyMode({ bridge: bridged }), needsTransport: true });
854
+ const p = loadPillar(args, { reader: rk.key, notifySink, notify: recvNotifyMode({ bridge: bridged }), needsTransport: "recv" });
853
855
  await p.start();
854
856
  writeRuntimeFile(p, homePath(args)); // warm handoff: publish live addr for senders
855
857
  const { n } = loadContacts(args, p);
@@ -1683,7 +1685,10 @@ function findCommandIndex(raw) {
1683
1685
  return -1;
1684
1686
  }
1685
1687
 
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]`;
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)`;
1687
1692
  const NOTIFY_USAGE = `usage:
1688
1693
  pillar notify [--home DIR] [--fleet FILE] [--groups FILE]
1689
1694
  pillar notify --print-unit launchd|systemd [--label L]
@@ -1696,6 +1701,7 @@ function helpText(raw) {
1696
1701
  const cmd = i === -1 ? undefined : rest[i];
1697
1702
  if (cmd === "group") return GROUP_V2_USAGE; // the v1 cmdGroup text stays inside its pinned bytes
1698
1703
  if (cmd === "notify") return NOTIFY_USAGE;
1704
+ if (cmd === "verify") return VERIFY_USAGE;
1699
1705
  return USAGE;
1700
1706
  }
1701
1707
 
@@ -1712,7 +1718,7 @@ async function main() {
1712
1718
  exit(exitCode);
1713
1719
  }
1714
1720
  if (directCmd === "verify") {
1715
- const { exitCode } = runVerifyCli(subRaw);
1721
+ const { exitCode } = await runVerifyCommand(subRaw);
1716
1722
  exit(exitCode);
1717
1723
  }
1718
1724
  if (directCmd === "lineage") {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@uuaid/pillar",
3
- "version": "2.7.0",
3
+ "version": "2.7.2",
4
4
  "description": "Pillar (Protocol for Inter-agent Linked Ledger And Relay) — the secure delivery layer of UACP, the Universal Agent Communication Protocol. UACP = UUAID (identity) + Envelope (signed, encrypted container) + Pillar (relay, mailbox, routing, store-and-forward). Reference implementation of the UACP delivery layer; includes VDA-1 (IAASO-3901, in ballot) delivery attestation and a blind escrow for the Zilligon ZGN / EVM rails.",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -21,7 +21,7 @@ import { dirname, join } from "node:path";
21
21
  import { jcs } from "../identity/jcs.mjs";
22
22
  import { requireBetterSqlite3, tryLoadBetterSqlite3 } from "../sqlite-loader.mjs";
23
23
  import { rekeyToSenderUnique } from "../sqlite-rekey.mjs";
24
- import { JsonDirMailboxReader, resolveJsonDirMailbox } from "../vnext/json-dir-mailbox.mjs";
24
+ import { JsonDirMailboxReader, hasClientIdentity, resolveJsonDirMailbox } from "../vnext/json-dir-mailbox.mjs";
25
25
  import { JsonlMailboxStore, hasJsonlMailboxFiles, resolveWritableJsonlDir } from "../vnext/jsonl-mailbox.mjs";
26
26
  import { KNOCK_LANE_CAP, KNOCK_RATE_WINDOW_MS } from "../vnext/knock-lane.mjs";
27
27
 
@@ -106,7 +106,12 @@ function toCanonicalIso(value) {
106
106
  export class Mailbox {
107
107
  constructor(path, opts = {}) {
108
108
  const jsonDir = resolveJsonDirMailbox(path);
109
- if (jsonDir !== null && !existsSync(join(dirname(jsonDir), "keychain.json"))) {
109
+ let clientHome = jsonDir !== null && !existsSync(join(dirname(jsonDir), "keychain.json"));
110
+ // A pillar JSONL home whose key is not keychain.json (pillar-escrow: kc.json)
111
+ // has the same mailbox files but no client identity: it stays writable.
112
+ // 2.7.0 opened it read-only from the second run on (V1 F5, 2.7.1 A6).
113
+ if (clientHome && !hasClientIdentity(dirname(jsonDir))) clientHome = false; // @rule mailbox.pillar-jsonl-home-writable
114
+ if (clientHome) {
110
115
  this.mode = "json-dir";
111
116
  this.jsonDir = jsonDir;
112
117
  this.db = null;
@@ -12,7 +12,9 @@
12
12
  * `npm i @uuaid/pillar-p2p` when neither is installed.
13
13
  */
14
14
  import { createECDH, createHash } from "node:crypto";
15
+ import { existsSync, realpathSync } from "node:fs";
15
16
  import { createRequire } from "node:module";
17
+ import { dirname, join } from "node:path";
16
18
  import { REFUSAL_FIXES } from "./refusals.mjs";
17
19
 
18
20
  export const PILLAR_PROTOCOL = "/uuaid/pillar/1.0.0";
@@ -117,20 +119,31 @@ function isModuleNotFound(err) {
117
119
  }
118
120
 
119
121
  /**
120
- * Synchronous check for whether `@uuaid/pillar-p2p` or legacy `libp2p` is installed.
122
+ * The directory of package `name` as `from` (a require function) would find
123
+ * it, or null. It walks the same node_modules directories as require.resolve
124
+ * but reads no `exports` map, so it needs no export condition: libp2p
125
+ * exports only "import" and "module-sync", and a CJS require.resolve found
126
+ * it only on Node builds that add "module-sync" (V1 F4, 2.7.1 A5).
127
+ */
128
+ function packageDir(from, name) {
129
+ for (const dir of from.resolve.paths(name) ?? []) {
130
+ const pj = join(dir, name, "package.json");
131
+ if (existsSync(pj)) {
132
+ try { return dirname(realpathSync(pj)); } catch { return dirname(pj); }
133
+ }
134
+ }
135
+ return null;
136
+ }
137
+
138
+ /**
139
+ * Synchronous check for whether `@uuaid/pillar-p2p` (with the libp2p it
140
+ * resolves) or legacy `libp2p` is installed.
121
141
  */
122
142
  export function isP2pInstalled() {
123
143
  if (process.env.PILLAR_DISABLE_P2P === "1") return false;
124
- try {
125
- const p2pEntry = req.resolve("@uuaid/pillar-p2p");
126
- createRequire(p2pEntry).resolve("libp2p");
127
- return true;
128
- } catch {}
129
- try {
130
- req.resolve("libp2p");
131
- return true;
132
- } catch {}
133
- return false;
144
+ const p2pDir = packageDir(req, "@uuaid/pillar-p2p");
145
+ if (p2pDir !== null && packageDir(createRequire(join(p2pDir, "package.json")), "libp2p") !== null) return true;
146
+ return packageDir(req, "libp2p") !== null;
134
147
  }
135
148
 
136
149
  let cachedP2pPromise = null;
@@ -413,6 +413,17 @@ export function releaseLock(handle) {
413
413
  }
414
414
  }
415
415
 
416
+ /**
417
+ * Is this lock file still ours (our token)? false when it was stolen,
418
+ * replaced, removed or cannot be read. A writer that may have stalled past
419
+ * the stale rule calls this just before it commits (V1 P3, 2.7.1 A2).
420
+ */
421
+ export function stillHoldsLock(handle) {
422
+ if (!handle?.path) return false;
423
+ try { return readLock(handle.path, handle.uid)?.info?.token === handle.token; }
424
+ catch (_e) { return false; }
425
+ }
426
+
416
427
  /** Refresh a long-held lock's `at` (cross-host staleness); false if it is no longer ours. */
417
428
  /**
418
429
  * Refresh a long-held lock's `at` (it still matters for another host).
@@ -472,6 +472,9 @@ export class PureJsRegistryDb {
472
472
  }
473
473
 
474
474
  _flush() {
475
+ // Every write statement below calls flush() once it changed a table, so
476
+ // this counts writes, as SQLite's total_changes() does (2.7.2 R1).
477
+ this._writeCount = (this._writeCount ?? 0) + 1;
475
478
  if (!this._persistPath) return;
476
479
  mkdirSync(dirname(this._persistPath), { recursive: true });
477
480
  const out = {};
@@ -514,6 +517,9 @@ export class PureJsRegistryDb {
514
517
  if (norm === "pragma table_info(lineage_event)") {
515
518
  return { all: () => [{ name: "complete" }] };
516
519
  }
520
+ if (norm === "select total_changes() as n") {
521
+ return { get: () => ({ n: this._writeCount ?? 0 }) };
522
+ }
517
523
 
518
524
  // ---- listing ----
519
525
  if (norm === "select * from listing where lineage = ?") {
@@ -149,13 +149,23 @@ export class HeartbeatStore {
149
149
  if (!totalCap.ok) return totalCap;
150
150
 
151
151
  const tx = this.db.transaction(() => {
152
- const existing = this.db
153
- .prepare("select seq, ts_ms, received_at_ms from heartbeat_latest where lineage = ?")
154
- .get(hb.lineage);
155
-
156
- if (existing && hb.seq <= existing.seq) return { ok: false, status: 400, reason: "stale-heartbeat" }; // @rule reg.hb-stale-seq
157
- if (!federated && existing && nowMs - existing.received_at_ms < this.minIntervalMs) return { ok: false, status: 429, reason: "rate-limited" }; // @rule reg.hb-rate-limit
158
- if (federated && existing && tsMs - existing.ts_ms < this.minIntervalMs) return { ok: false, status: 429, reason: "rate-limited" };
152
+ const existing = this.db.prepare("select * from heartbeat_latest where lineage = ?").get(hb.lineage);
153
+
154
+ // V1 F6 (2.7.1 A7): the seq and the rate window belong to the key that
155
+ // posted them. After a rotation the new key starts fresh, so a stolen old
156
+ // key's seq 2^53-1 cannot block the owner. Under one key a newer `ts` also
157
+ // passes (signed by the current key, and a replay never has a newer ts),
158
+ // so a client that lost its heartbeat state recovers after one window.
159
+ // An older `ts` never replaces a newer one, whatever its seq: once a
160
+ // client restarts at seq 1, its old high-seq heartbeats are replays.
161
+ let prev = existing ?? null;
162
+ if (prev && prev.uuaid !== hb.uuaid) prev = null; // @rule reg.hb-seq-per-key
163
+ let stale = Boolean(prev) && hb.seq <= prev.seq;
164
+ if (stale && tsMs > prev.ts_ms) stale = false; // @rule reg.hb-newer-ts
165
+ if (prev && tsMs < prev.ts_ms) stale = true; // @rule reg.hb-older-ts
166
+ if (stale) return { ok: false, status: 400, reason: "stale-heartbeat" }; // @rule reg.hb-stale-seq
167
+ if (!federated && prev && nowMs - prev.received_at_ms < this.minIntervalMs) return { ok: false, status: 429, reason: "rate-limited" }; // @rule reg.hb-rate-limit
168
+ if (federated && prev && tsMs - prev.ts_ms < this.minIntervalMs) return { ok: false, status: 429, reason: "rate-limited" };
159
169
 
160
170
  if (existing) {
161
171
  this.db
@@ -184,9 +184,11 @@ export class LineageStore {
184
184
  this._lastGlobalSeenMs = 0;
185
185
  this._lastSeenMsByLineage = new Map();
186
186
  // Read caches (V1 F2): `changes` counts calls that may change stored events
187
- // or receipts; `_evalMemo` holds evaluateLineageCached results per lineage.
187
+ // or receipts; `_evalMemo` holds evaluateLineageCached results per lineage,
188
+ // each stamped with the verify pass current when it was evaluated.
188
189
  this.changes = 0;
189
190
  this._evalMemo = new Map();
191
+ this._verifyPass = 0;
190
192
 
191
193
  this.db.exec(`
192
194
  create table if not exists lineage_event (
@@ -888,22 +890,45 @@ export class LineageStore {
888
890
  }
889
891
 
890
892
  /**
891
- * evaluateLineage, remembered per lineage for at most `maxAgeMs` of `now`
892
- * (a verdict can change with time alone: a recovery claim becoming
893
- * effective). A call that may write the lineage's events or receipts
894
- * forgets its entry (LINEAGE_WRITES). `maxAgeMs: 0` always evaluates and
895
- * refreshes the entry. Returns the same object for a remembered lineage:
896
- * callers must not modify it.
893
+ * evaluateLineage, remembered per lineage until a verify pass completes
894
+ * without verifying it again (2.7.2 R2, V1 77962b P2). `refresh: true`
895
+ * always evaluates and stores the result (the pass itself uses it). A write
896
+ * to the lineage forgets its entry (LINEAGE_WRITES). Validity is by pass,
897
+ * not wall-clock age: an entry verified by the pass in progress or by the
898
+ * last completed pass is kept, however long a pass takes. Returns the same
899
+ * object for a remembered lineage: callers must not modify it.
897
900
  */
898
- evaluateLineageCached(lineage, { now, maxAgeMs } = {}) {
899
- const nowMs = Date.parse(nowIso(now));
900
- const hit = this._evalMemo.get(lineage);
901
- if (hit && nowMs >= hit.atMs && nowMs - hit.atMs < maxAgeMs) return hit.ev; // @rule reg.lineage-eval-memo-age
901
+ evaluateLineageCached(lineage, { now, refresh = false } = {}) {
902
+ const hit = refresh === true ? undefined : this._evalMemo.get(lineage);
903
+ if (hit) return hit.ev;
902
904
  const ev = this.evaluateLineage(lineage, { now });
903
- this._evalMemo.set(lineage, { atMs: nowMs, ev });
905
+ this._evalMemo.set(lineage, { pass: this._verifyPass, ev });
904
906
  return ev;
905
907
  }
906
908
 
909
+ /** Start a verify pass (a prune pass over every listing); returns its id. */
910
+ beginVerifyPass() {
911
+ this._verifyPass += 1;
912
+ return this._verifyPass;
913
+ }
914
+
915
+ /**
916
+ * Pass `id` judged every listing: drop the verdicts it did not refresh
917
+ * (verified by an older pass and not since). A stopped or failed pass does
918
+ * not end, so the last completed pass's verdicts stay valid meanwhile.
919
+ */
920
+ endVerifyPass(id) {
921
+ for (const [lineage, entry] of this._evalMemo) {
922
+ if (entry.pass < id) this._evalMemo.delete(lineage); // @rule reg.lineage-eval-memo-pass
923
+ }
924
+ }
925
+
926
+ /** Rows written on this connection so far (SQLite total_changes(); the pure-JS db counts its writes). */
927
+ _dbWrites() {
928
+ this._totalChangesStmt ??= this.db.prepare("select total_changes() as n");
929
+ return this._totalChangesStmt.get().n;
930
+ }
931
+
907
932
  /** A write to `lineage` (unknown: any lineage) happened or may have happened. */
908
933
  _noteLineageWrite(lineage) {
909
934
  this.changes++;
@@ -956,8 +981,12 @@ export class LineageStore {
956
981
 
957
982
  /**
958
983
  * LineageStore methods that may write events or receipts, and the lineage
959
- * each one writes (undefined = not known: forget every entry). Each call,
960
- * accepted or refused, ends with _noteLineageWrite.
984
+ * each one writes (undefined = not known: forget every entry). A call is
985
+ * noted (_noteLineageWrite: forget the cached verdict, bump `changes`) only
986
+ * when it wrote a row or threw (2.7.2 R1, V1 77962b P1). Before, every call
987
+ * was noted, accepted or refused, and a refused unauthenticated
988
+ * POST /v1/lineage with no string lineage ({} or null) emptied the whole
989
+ * verdict cache, so the next directory.json re-verified every listing.
961
990
  */
962
991
  const LINEAGE_WRITES = {
963
992
  storeEvent: (ev) => ev?.lineage,
@@ -972,10 +1001,16 @@ for (const [name, lineageOf] of Object.entries(LINEAGE_WRITES)) {
972
1001
  const write = LineageStore.prototype[name];
973
1002
  Object.defineProperty(LineageStore.prototype, name, {
974
1003
  value: function noted(...args) {
1004
+ const before = this._dbWrites();
1005
+ let threw = true;
975
1006
  try {
976
- return write.apply(this, args);
1007
+ const res = write.apply(this, args);
1008
+ threw = false;
1009
+ return res;
977
1010
  } finally {
978
- this._noteLineageWrite(lineageOf(...args));
1011
+ let wrote = true;
1012
+ if (!threw && this._dbWrites() === before) wrote = false; // @rule reg.lineage-note-real-writes
1013
+ if (wrote) this._noteLineageWrite(lineageOf(...args));
979
1014
  }
980
1015
  },
981
1016
  writable: true,
@@ -42,12 +42,25 @@ export const TOMBSTONE_RETENTION_MS = 365 * 86_400_000;
42
42
  * request path: at start and every PRUNE_INTERVAL_MS (startTombstonePruning).
43
43
  * directory.json is rebuilt when a listing, heartbeat or lineage write
44
44
  * happened, or after PROJECTION_MAX_AGE_MS (status is a function of time).
45
- * A rebuild re-verifies only lineages written since, or not verified within
46
- * EVAL_MEMO_MAX_AGE_MS; each prune pass re-verifies all of them.
45
+ * A rebuild re-verifies only lineages written since, or not verified by the
46
+ * last completed prune pass nor the one in progress; each pass re-verifies
47
+ * all of them.
48
+ *
49
+ * Validity is by pass number, not age (2.7.2 R2, V1 77962b P2). 2.7.1 kept a
50
+ * verdict for one interval from the pass start, so all expired as the next
51
+ * pass started and a rebuild early in it re-verified every row not yet
52
+ * walked, inside the request (V1 cf5902). 2.7.2-r1 doubled the age, which
53
+ * held only while a pass ended within one interval. Now an entry lives until
54
+ * a pass completes without refreshing it, whatever a pass takes. A verdict
55
+ * that changes with time alone reaches directory.json when the next pass
56
+ * reaches its row, plus PROJECTION_MAX_AGE_MS.
47
57
  */
48
58
  export const PRUNE_INTERVAL_MS = 10 * 60_000;
59
+ /** Longest stretch a timed prune pass holds the event loop before it yields (V1 P2). */
60
+ export const PRUNE_SLICE_MS = 20;
61
+
62
+ const yieldToEventLoop = () => new Promise((resolve) => setImmediate(resolve));
49
63
  export const PROJECTION_MAX_AGE_MS = 60_000;
50
- export const EVAL_MEMO_MAX_AGE_MS = PRUNE_INTERVAL_MS;
51
64
 
52
65
  const HEX128_RE = /^[0-9a-f]{128}$/;
53
66
  const NONCE_RE = /^[0-9a-f]{1,32}$/;
@@ -434,38 +447,88 @@ export class ListingStore {
434
447
  /**
435
448
  * Prune dead / withdrawn / tombstoned listing rows that have been dead for `>= 365` days
436
449
  * (`TOMBSTONE_RETENTION_MS`), while leaving `lineage_event` untouched (`T3.5`).
450
+ * One synchronous pass (tests, tools). The registry's timer uses
451
+ * pruneExpiredTombstonesYielding, which gives the event loop a turn between slices.
437
452
  */
438
453
  pruneExpiredTombstones({ now } = {}) {
439
454
  const nowStr = nowIso(now);
440
455
  const nowMs = Date.parse(nowStr);
441
456
  const lineages = [];
442
- const delStmt = this.db.prepare("delete from listing where lineage = ?");
443
-
444
- for (const row of this.all()) {
445
- const l = row.listing;
446
- // A fresh verdict (maxAgeMs 0), kept for the next directory.json rebuild.
447
- const evalRes = this.lineageStore ? this.lineageStore.evaluateLineageCached(l.lineage, { now: nowStr, maxAgeMs: 0 }) : null;
448
- let deadSinceMs = null;
449
- if (evalRes?.tombstoned === true) {
450
- deadSinceMs = Date.parse(evalRes.tombstoneTs);
451
- } else if (row.withdrawn === 1 || l.withdrawn === true) {
452
- deadSinceMs = row.issued_at_ms;
453
- } else {
454
- const cur = evalRes && (evalRes.verdict === "valid" || evalRes.verdict === "recovered" || evalRes.verdict === "pending-recovery") ? evalRes.current : l.uuaid;
455
- const hb = this.heartbeatStore ? this.heartbeatStore.getLatest(l.lineage) : null;
456
- const lastSeenMs = hb && hb.uuaid === cur ? Math.max(row.issued_at_ms, hb.ts_ms) : row.issued_at_ms;
457
- if (nowMs - lastSeenMs >= STATUS_QUIET_MS) deadSinceMs = lastSeenMs + STATUS_QUIET_MS;
458
- }
457
+ const pass = this.lineageStore ? this.lineageStore.beginVerifyPass() : 0;
458
+ for (const lineage of this._listedLineages()) {
459
+ if (this._pruneOne(lineage, nowStr, nowMs)) lineages.push(lineage);
460
+ }
461
+ if (this.lineageStore) this.lineageStore.endVerifyPass(pass);
462
+ return { pruned: lineages.length, lineages };
463
+ }
459
464
 
460
- if (deadSinceMs !== null && nowMs - deadSinceMs >= TOMBSTONE_RETENTION_MS) {
461
- delStmt.run(l.lineage); // @rule reg.listing-prune-365d
462
- if (this.heartbeatStore) this.heartbeatStore.deleteByLineage(l.lineage);
463
- lineages.push(l.lineage);
464
- this.changes++;
465
+ /**
466
+ * The same pass in slices of at most `sliceMs` (V1 P2): after each slice it
467
+ * awaits `yieldFn` (setImmediate), so requests are answered during the pass.
468
+ * Each row is re-read and judged inside one slice, so a write that lands
469
+ * between slices is seen. `shouldStop()` ends the pass early (shutdown).
470
+ * Returns { pruned, lineages, rows, walked, slices, longestSliceMs }: rows
471
+ * is the number of listings when the pass began, walked the number it
472
+ * judged (less than rows when it was stopped).
473
+ */
474
+ async pruneExpiredTombstonesYielding({ now, sliceMs = PRUNE_SLICE_MS, yieldFn = yieldToEventLoop, shouldStop = () => false } = {}) {
475
+ const nowStr = nowIso(now);
476
+ const nowMs = Date.parse(nowStr);
477
+ const lineages = [];
478
+ const all = this._listedLineages();
479
+ const pass = this.lineageStore ? this.lineageStore.beginVerifyPass() : 0;
480
+ let walked = 0;
481
+ let slices = 1;
482
+ let longestSliceMs = 0;
483
+ let sliceStart = performance.now();
484
+ for (const lineage of all) {
485
+ if (shouldStop()) break;
486
+ if (this._pruneOne(lineage, nowStr, nowMs)) lineages.push(lineage);
487
+ walked++;
488
+ const spent = performance.now() - sliceStart;
489
+ let yieldNow = false;
490
+ if (spent >= sliceMs) yieldNow = true; // @rule reg.prune-yields
491
+ if (yieldNow) {
492
+ longestSliceMs = Math.max(longestSliceMs, spent);
493
+ await yieldFn();
494
+ slices++;
495
+ sliceStart = performance.now();
465
496
  }
466
497
  }
498
+ longestSliceMs = Math.max(longestSliceMs, performance.now() - sliceStart);
499
+ // Only a pass that judged every listing ends: a stopped one keeps the last
500
+ // completed pass's verdicts valid (2.7.2 R2).
501
+ if (this.lineageStore && walked === all.length) this.lineageStore.endVerifyPass(pass);
502
+ return { pruned: lineages.length, lineages, rows: all.length, walked, slices, longestSliceMs: Math.round(longestSliceMs) };
503
+ }
467
504
 
468
- return { pruned: lineages.length, lineages };
505
+ _listedLineages() {
506
+ return this.all().map((row) => row.lineage);
507
+ }
508
+
509
+ /** Prune one listing if it has been dead >= 365 days. Reads the row now (a yielding pass may have slept). */
510
+ _pruneOne(lineage, nowStr, nowMs) {
511
+ const row = this.getByLineage(lineage);
512
+ if (!row) return false;
513
+ const l = row.listing;
514
+ // A fresh verdict (refresh), kept for the next directory.json rebuild.
515
+ const evalRes = this.lineageStore ? this.lineageStore.evaluateLineageCached(l.lineage, { now: nowStr, refresh: true }) : null;
516
+ let deadSinceMs = null;
517
+ if (evalRes?.tombstoned === true) {
518
+ deadSinceMs = Date.parse(evalRes.tombstoneTs);
519
+ } else if (row.withdrawn === 1 || l.withdrawn === true) {
520
+ deadSinceMs = row.issued_at_ms;
521
+ } else {
522
+ const cur = evalRes && (evalRes.verdict === "valid" || evalRes.verdict === "recovered" || evalRes.verdict === "pending-recovery") ? evalRes.current : l.uuaid;
523
+ const hb = this.heartbeatStore ? this.heartbeatStore.getLatest(l.lineage) : null;
524
+ const lastSeenMs = hb && hb.uuaid === cur ? Math.max(row.issued_at_ms, hb.ts_ms) : row.issued_at_ms;
525
+ if (nowMs - lastSeenMs >= STATUS_QUIET_MS) deadSinceMs = lastSeenMs + STATUS_QUIET_MS;
526
+ }
527
+ if (deadSinceMs === null || nowMs - deadSinceMs < TOMBSTONE_RETENTION_MS) return false;
528
+ this.db.prepare("delete from listing where lineage = ?").run(l.lineage); // @rule reg.listing-prune-365d
529
+ if (this.heartbeatStore) this.heartbeatStore.deleteByLineage(l.lineage);
530
+ this.changes++;
531
+ return true;
469
532
  }
470
533
 
471
534
  /**
@@ -504,7 +567,7 @@ export class ListingStore {
504
567
  if (row.withdrawn === 1 || l.withdrawn === true) continue; // @rule reg.project-not-withdrawn
505
568
  if (this.hasOtherLineage(l.lineage, l.lineage) || this.hasOtherLineage(l.uuaid, l.lineage)) continue; // @rule reg.project-ambiguous-listing-store
506
569
  if (this.lineageStore.hasOtherLineage(l.lineage, l.lineage) || this.lineageStore.hasOtherLineage(l.uuaid, l.lineage)) continue; // @rule reg.project-ambiguous-lineage-store
507
- const evalRes = this.lineageStore.evaluateLineageCached(l.lineage, { now: nowStr, maxAgeMs: EVAL_MEMO_MAX_AGE_MS });
570
+ const evalRes = this.lineageStore.evaluateLineageCached(l.lineage, { now: nowStr });
508
571
  if (evalRes?.tombstoned === true) continue; // @rule reg.project-not-tombstoned
509
572
  if (evalRes !== null && ((evalRes.verdict !== "valid" && evalRes.verdict !== "recovered" && evalRes.verdict !== "pending-recovery") || evalRes.current !== l.uuaid)) continue; // @rule reg.project-lineage-current
510
573
  const hb = this.heartbeatStore ? this.heartbeatStore.getLatest(l.lineage) : null;
@@ -523,27 +586,62 @@ export class ListingStore {
523
586
  }
524
587
 
525
588
  /**
526
- * Prune off the request path (V1 F2): one pass now, then one every
527
- * `intervalMs` (unref'd). A pass that throws is logged and the timer keeps
528
- * running. Returns { stop, runNow, runs } (runs: the last 10 passes,
529
- * { pruned, ms }).
589
+ * Prune off the request path (V1 F2), in slices that yield to the event loop
590
+ * (V1 P2): one pass now, then one every `intervalMs` (unref'd). The first
591
+ * slice runs before this returns; the rest run while the registry serves.
592
+ * One pass at a time; a pass that throws is logged and the timer keeps
593
+ * running. A pass that pruned rows or ran >= 1 s is reported through `info`.
594
+ * Returns { stop, runNow, whenIdle, firstPass, runs } (runs: the last 10
595
+ * passes, { pruned, rows, ms, slices, longestSliceMs }). `firstPass`
596
+ * settles when the start pass ends (pruned, failed or stopped; it never
597
+ * rejects) and the directory.json projection is built: a handler that
598
+ * projects every listing awaits it, so the start pass fills the lineage
599
+ * memo off the request path (2.7.2 C2). The build (about 40 ms at 1,000
600
+ * listings) runs in a tick of its own, with an I/O turn before and after
601
+ * it, so the handlers that waited resume on a cached projection instead
602
+ * of all building and sending in one tick.
530
603
  */
531
- export function startTombstonePruning(listingStore, { getNow = () => undefined, intervalMs = PRUNE_INTERVAL_MS, log = (m) => console.error(m), setIntervalFn = setInterval, clearIntervalFn = clearInterval } = {}) {
604
+ export function startTombstonePruning(listingStore, { getNow = () => undefined, intervalMs = PRUNE_INTERVAL_MS, sliceMs = PRUNE_SLICE_MS, log = (m) => console.error(m), info = (m) => console.log(m), setIntervalFn = setInterval, clearIntervalFn = clearInterval } = {}) {
532
605
  const runs = [];
533
- const runNow = () => {
606
+ let stopped = false;
607
+ let inFlight = null;
608
+ const pass = async () => {
534
609
  const t0 = performance.now();
535
610
  try {
536
- const r = listingStore.pruneExpiredTombstones({ now: getNow() });
537
- runs.push({ pruned: r.pruned, ms: Math.round(performance.now() - t0) });
611
+ const r = await listingStore.pruneExpiredTombstonesYielding({ now: getNow(), sliceMs, shouldStop: () => stopped });
612
+ const ms = Math.round(performance.now() - t0);
613
+ runs.push({ pruned: r.pruned, rows: r.rows, walked: r.walked, ms, slices: r.slices, longestSliceMs: r.longestSliceMs });
538
614
  if (runs.length > 10) runs.shift();
615
+ // "P of W": W = listings this pass judged. A pass stopped early (shutdown)
616
+ // says so, rather than counting listings it never reached as checked.
617
+ const stoppedEarly = r.walked < r.rows;
618
+ if (r.pruned > 0 || ms >= 1000 || stoppedEarly) info(`[registry] tombstone prune: ${r.pruned} of ${r.walked} listings pruned in ${ms} ms (${r.slices} slices, longest ${r.longestSliceMs} ms)${stoppedEarly ? `; stopped after ${r.walked} of ${r.rows} listings` : ""}`);
539
619
  return r;
540
620
  } catch (e) {
541
- log(`[registry] tombstone prune failed: ${e?.message ?? e}`);
621
+ if (!stopped) log(`[registry] tombstone prune failed: ${e?.message ?? e}`);
542
622
  return null;
623
+ } finally {
624
+ inFlight = null;
543
625
  }
544
626
  };
545
- runNow();
627
+ const runNow = () => {
628
+ if (stopped) return Promise.resolve(null);
629
+ if (!inFlight) inFlight = pass();
630
+ return inFlight;
631
+ };
632
+ const firstPass = runNow().then(async (r) => {
633
+ await yieldToEventLoop();
634
+ try { listingStore.projectLiveAgents({ now: getNow() }); } catch (_e) { /* a store without lineages: the handler reports it */ }
635
+ await yieldToEventLoop();
636
+ return r;
637
+ });
546
638
  const timer = setIntervalFn(runNow, intervalMs);
547
639
  timer?.unref?.();
548
- return { stop: () => clearIntervalFn(timer), runNow, runs };
640
+ return {
641
+ stop: () => { stopped = true; clearIntervalFn(timer); },
642
+ runNow,
643
+ whenIdle: () => inFlight ?? Promise.resolve(null),
644
+ firstPass,
645
+ runs,
646
+ };
549
647
  }
@@ -52,7 +52,7 @@ export const TTFA_METHODS = Object.freeze(["ci-canary", "field-cohort"]);
52
52
  export const TTFA_MIN_N = 10;
53
53
 
54
54
  /** Tool stamped on B8 verdicts (same string the `pillar verify` CLI uses). */
55
- export const STATS_VERDICT_TOOL = "pillar/2.7.0";
55
+ export const STATS_VERDICT_TOOL = "pillar/2.7.2";
56
56
 
57
57
  /** Closed key set of `pillar-ttfa-report/1`. */
58
58
  export const TTFA_REPORT_KEYS = Object.freeze([
@@ -28,6 +28,19 @@ function hasJsonDirMailboxFiles(dir) {
28
28
  );
29
29
  }
30
30
 
31
+ /**
32
+ * True iff `home` holds a `@uuaid/pillar-client` identity (what `open()`
33
+ * writes). A pillar JSONL store home has none: its key is keychain.json, or
34
+ * kc.json for pillar-escrow (2.7.1 A6).
35
+ */
36
+ export function hasClientIdentity(home) {
37
+ return (
38
+ existsSync(join(home, "identity", "agent.seed")) ||
39
+ existsSync(join(home, "identity", "agent-meta.json")) ||
40
+ existsSync(join(home, "card", "card.json"))
41
+ );
42
+ }
43
+
31
44
  /**
32
45
  * True iff `home` is an `@uuaid/pillar-client` `open()` JSON-dir home
33
46
  * (never a SQLite `pillar init` home carrying `mailbox.db` or `keychain.json`).
@@ -36,12 +49,7 @@ export function isJsonDirHome(home) {
36
49
  return (
37
50
  !existsSync(join(home, "mailbox.db")) &&
38
51
  !existsSync(join(home, "keychain.json")) &&
39
- (
40
- hasJsonDirMailboxFiles(join(home, "mailbox")) ||
41
- existsSync(join(home, "identity", "agent.seed")) ||
42
- existsSync(join(home, "identity", "agent-meta.json")) ||
43
- existsSync(join(home, "card", "card.json"))
44
- )
52
+ (hasJsonDirMailboxFiles(join(home, "mailbox")) || hasClientIdentity(home))
45
53
  );
46
54
  }
47
55
 
@@ -21,16 +21,22 @@
21
21
  import { createHash, randomBytes } from "node:crypto";
22
22
  import {
23
23
  appendFileSync,
24
+ closeSync,
24
25
  existsSync,
26
+ fstatSync,
27
+ ftruncateSync,
25
28
  mkdirSync,
29
+ openSync,
26
30
  readFileSync,
31
+ readSync,
27
32
  renameSync,
28
33
  statSync,
34
+ unlinkSync,
29
35
  writeFileSync,
30
36
  } from "node:fs";
31
37
  import { basename, dirname, join } from "node:path";
32
38
  import { jcs } from "../identity/jcs.mjs";
33
- import { WRITER_STALE_MS, WRITER_WAIT_MS, acquireLockSync, releaseLock } from "../notify-store.mjs";
39
+ import { WRITER_STALE_MS, WRITER_WAIT_MS, acquireLockSync, releaseLock, stillHoldsLock } from "../notify-store.mjs";
34
40
  import { KNOCK_LANE_CAP, KNOCK_RATE_WINDOW_MS } from "./knock-lane.mjs";
35
41
 
36
42
  const CHAIN_SEED = "uuaid-pillar-mailbox-v1|";
@@ -88,6 +94,13 @@ export function resolveWritableJsonlDir(rawPath) {
88
94
  /** `_withLock` before the lock is taken: release is a no-op. */
89
95
  const NOT_LOCKED = Object.freeze({ path: null });
90
96
 
97
+ /** V1 P3: this writer stalled past the stale rule and another writer took the lock. */
98
+ function lockLostError(lockPath, what) {
99
+ const err = new Error(`mailbox-locked: this process no longer holds ${lockPath} (it stalled past the stale rule and another writer took it); the ${what} was not done. Retry`);
100
+ err.code = "mailbox-locked";
101
+ return err;
102
+ }
103
+
91
104
  function lockBusyError(lockPath, waitMs) {
92
105
  const err = new Error(`mailbox-locked: another process held ${lockPath} for ${waitMs} ms; nothing was written. Retry; if it persists, check for a hung pillar process on this home`);
93
106
  err.code = "mailbox-locked";
@@ -146,6 +159,7 @@ export class JsonlMailboxStore {
146
159
  if (!handle) throw lockBusyError(this.lockPath, this.lockWaitMs);
147
160
  this._lock = handle;
148
161
  try {
162
+ this._repairTornTails(); // @rule jsonl.repair-torn-tail
149
163
  return fn();
150
164
  } finally {
151
165
  this._lock = null;
@@ -153,6 +167,52 @@ export class JsonlMailboxStore {
153
167
  }
154
168
  }
155
169
 
170
+ /**
171
+ * Just before a commit (rename or append): is the lock still ours? A holder
172
+ * stalled past the stale rule (SIGSTOP, swap, a disk stall) may have lost it
173
+ * to another writer, whose rows a late rename would overwrite (V1 P3).
174
+ */
175
+ _assertStillLocked(what) {
176
+ if (this.memory) return;
177
+ if (!stillHoldsLock(this._lock)) throw lockLostError(this.lockPath, what);
178
+ }
179
+
180
+ /**
181
+ * A crash in the middle of an append leaves an unterminated last line
182
+ * (V1 P3). Under the lock no append is in flight, so it is a dead write:
183
+ * its bytes move to `<file>.torn-<time>-<pid>` (0600) and the file is cut
184
+ * back to its last complete row. Lock-free reads already skip such a tail.
185
+ * Without this, every later write failed on it (SyntaxError) until the home
186
+ * was repaired by hand. The row's sender can still be fetched again: a
187
+ * receiver advances its carrier cursor only after the append returns.
188
+ */
189
+ _repairTornTails() {
190
+ if (this.memory) return;
191
+ for (const p of [this.inboxPath, this.outboxPath, this.knocksPath]) this._repairTornTail(p);
192
+ }
193
+
194
+ _repairTornTail(filePath) {
195
+ let fd;
196
+ try { fd = openSync(filePath, "r+"); } catch (e) { if (e.code === "ENOENT") return null; throw e; }
197
+ try {
198
+ const { size } = fstatSync(fd);
199
+ if (size === 0) return null;
200
+ const last = Buffer.alloc(1);
201
+ readSync(fd, last, 0, 1, size - 1);
202
+ if (last[0] === 0x0a) return null;
203
+ const buf = Buffer.alloc(size);
204
+ let off = 0;
205
+ while (off < size) { const n = readSync(fd, buf, off, size - off, off); if (n === 0) break; off += n; }
206
+ const cut = buf.subarray(0, off).lastIndexOf(0x0a) + 1;
207
+ const stamp = new Date().toISOString().replace(/[:.]/g, "-");
208
+ const backup = `${filePath}.torn-${stamp}-${process.pid}`;
209
+ writeFileSync(backup, buf.subarray(cut, off), { mode: 0o600, flag: "wx" });
210
+ this._assertStillLocked(`cut of the torn tail of ${basename(filePath)}`);
211
+ ftruncateSync(fd, cut);
212
+ return backup;
213
+ } finally { closeSync(fd); }
214
+ }
215
+
156
216
  /** A disk write outside `_withLock` is a bug: refuse it rather than race. */
157
217
  _assertLocked(what) {
158
218
  if (!this.memory && !this._lock) throw new Error(`JsonlMailboxStore: ${what} outside the mailbox lock`); // @rule jsonl.write-needs-lock
@@ -167,6 +227,12 @@ export class JsonlMailboxStore {
167
227
  this._ensureDir();
168
228
  const tmp = `${filePath}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
169
229
  writeFileSync(tmp, content, { mode: 0o600 });
230
+ try {
231
+ this._assertStillLocked(`rename of ${basename(filePath)}`); // @rule jsonl.recheck-before-rename
232
+ } catch (e) {
233
+ try { unlinkSync(tmp); } catch (_e) { /* already gone */ }
234
+ throw e;
235
+ }
170
236
  renameSync(tmp, filePath);
171
237
  }
172
238
 
@@ -174,8 +240,7 @@ export class JsonlMailboxStore {
174
240
  if (!existsSync(filePath)) return [];
175
241
  let text = readFileSync(filePath, "utf8");
176
242
  // Outside the lock an unterminated tail is an append in flight: not yet a
177
- // row. Under the lock no append is in flight, so a torn tail stays visible
178
- // (it fails the parse, or the audit, as before).
243
+ // row. Under the lock a torn tail was already moved aside (_repairTornTails).
179
244
  if (!this._lock) text = text.slice(0, text.lastIndexOf("\n") + 1); // @rule jsonl.read-committed-rows
180
245
  const out = [];
181
246
  let lineNo = 0;
@@ -213,6 +278,7 @@ export class JsonlMailboxStore {
213
278
  }
214
279
  this._assertLocked(`append ${basename(filePath)}`);
215
280
  this._ensureDir();
281
+ this._assertStillLocked(`append to ${basename(filePath)}`); // @rule jsonl.recheck-before-append
216
282
  appendFileSync(filePath, `${JSON.stringify(row)}\n`, { mode: 0o600 });
217
283
  }
218
284
 
@@ -1,5 +1,6 @@
1
1
  /**
2
2
  * `pillar resolve <uuaid> [--registry URL] [--now ISO] [--home DIR] [--json]`
3
+ * (and the live form of `pillar verify <uuaid>`, through resolveLive)
3
4
  *
4
5
  * Calls core `resolve()` (fail-closed cryptographic verification of listing,
5
6
  * card, and lineage). Exits:
@@ -33,54 +34,71 @@ function formatHumanResolve(res) {
33
34
  }
34
35
 
35
36
  /**
36
- * Execute `pillar resolve` with injectable streams and fetch.
37
- * Returns `{ exitCode, result? }`.
37
+ * Parse `<uuaid> [--registry URL] [--now ISO] [--home DIR] [--json]` and run
38
+ * core `resolve()` (fail-closed verification of listing, card and lineage).
39
+ * Shared by `pillar resolve` and `pillar verify <uuaid>`. Returns
40
+ * `{ usage: { exitCode } }` after printing a usage error, or
41
+ * `{ json, registryUrl, uuaid, result, error }` (error: a thrown message).
38
42
  */
39
- export async function runResolveCli(rawArgs, io = {}) {
40
- const out = io.stdout ?? ((s) => process.stdout.write(s));
43
+ export async function resolveLive(rawArgs, { cmdName = "resolve", io = {} } = {}) {
41
44
  const errOut = io.stderr ?? ((s) => process.stderr.write(s));
42
-
43
45
  const parsed = parseStrictFlags(rawArgs, {
44
46
  boolFlags: new Set(["json"]),
45
47
  valueFlags: new Set(["home", "registry", "now"]),
46
- cmdName: "resolve",
48
+ cmdName,
47
49
  });
48
- if (!parsed.ok) return failCli(errOut, parsed.error, parsed.exitCode);
50
+ if (!parsed.ok) return { usage: failCli(errOut, parsed.error, parsed.exitCode) };
49
51
 
50
52
  const { positionals, opts } = parsed;
51
- if (positionals.length !== 1) return failCli(errOut, "usage: pillar resolve <uuaid> [--registry URL] [--now ISO] [--json]", 64); // @rule resolve-cli.arg-count
53
+ if (positionals.length !== 1) return { usage: failCli(errOut, `usage: pillar ${cmdName} <uuaid> [--registry URL] [--now ISO] [--json]`, 64) }; // @rule resolve-cli.arg-count
52
54
 
53
55
  const uuaid = positionals[0];
54
- if (!isValidUuaid(uuaid)) return failCli(errOut, `resolve: invalid UUAID "${uuaid}"`, 64); // @rule resolve-cli.uuaid-valid
56
+ if (!isValidUuaid(uuaid)) return { usage: failCli(errOut, `${cmdName}: invalid UUAID "${uuaid}"`, 64) }; // @rule resolve-cli.uuaid-valid
55
57
 
56
58
  const ts = opts.now !== undefined ? opts.now : nowIsoSeconds();
57
- if (!isStrictIsoDateTime(ts)) return failCli(errOut, "resolve: --now must be a valid ISO-8601 timestamp", 64); // @rule resolve-cli.now-valid
59
+ if (!isStrictIsoDateTime(ts)) return { usage: failCli(errOut, `${cmdName}: --now must be a valid ISO-8601 timestamp`, 64) }; // @rule resolve-cli.now-valid
58
60
 
59
61
  let cfg = {};
60
62
  try { cfg = loadHomeConfig(resolveHome(opts)); } catch { cfg = {}; }
61
63
  const registryUrl = opts.registry ?? cfg.registry ?? DEFAULT_RESOLVE_REGISTRY;
62
- if (!isRegistryUrl(registryUrl)) return failCli(errOut, `resolve: --registry must be an https:// (or loopback http://) URL, got "${registryUrl}"`, 64); // @rule resolve-cli.registry-url
64
+ if (!isRegistryUrl(registryUrl)) return { usage: failCli(errOut, `${cmdName}: --registry must be an https:// (or loopback http://) URL, got "${registryUrl}"`, 64) }; // @rule resolve-cli.registry-url
63
65
 
64
- let result;
65
66
  try {
66
- result = await resolve(uuaid, {
67
+ const result = await resolve(uuaid, {
67
68
  registryUrl,
68
69
  now: ts,
69
70
  ...(io.fetch ? { fetch: io.fetch } : {}),
70
71
  });
72
+ return { json: opts.json, registryUrl, uuaid, result, error: null };
71
73
  } catch (e) {
72
- const msg = e instanceof Error ? e.message : String(e);
73
- if (opts.json) out(`${JSON.stringify({ ok: false, reason: "resolve-error", message: msg })}\n`);
74
- else errOut(`resolve: ${msg}\n`);
74
+ return { json: opts.json, registryUrl, uuaid, result: null, error: e instanceof Error ? e.message : String(e) };
75
+ }
76
+ }
77
+
78
+ /**
79
+ * Execute `pillar resolve` with injectable streams and fetch.
80
+ * Returns `{ exitCode, result? }`.
81
+ */
82
+ export async function runResolveCli(rawArgs, io = {}) {
83
+ const out = io.stdout ?? ((s) => process.stdout.write(s));
84
+ const errOut = io.stderr ?? ((s) => process.stderr.write(s));
85
+
86
+ const live = await resolveLive(rawArgs, { cmdName: "resolve", io });
87
+ if (live.usage) return live.usage;
88
+ const { json, result, error } = live;
89
+
90
+ if (error !== null) {
91
+ if (json) out(`${JSON.stringify({ ok: false, reason: "resolve-error", message: error })}\n`);
92
+ else errOut(`resolve: ${error}\n`);
75
93
  return { exitCode: 1, result: { ok: false, reason: "resolve-error" } };
76
94
  }
77
95
 
78
96
  if (!result || result.ok !== true) {
79
- if (opts.json) out(`${JSON.stringify(result)}\n`);
97
+ if (json) out(`${JSON.stringify(result)}\n`);
80
98
  else errOut(`resolve: ${result?.reason ?? "failed"}${result?.statusCode ? ` (HTTP ${result.statusCode})` : ""}\n`);
81
99
  return { exitCode: 1, result }; // @rule resolve-cli.fail-closed-exit-1
82
100
  }
83
101
 
84
- out(opts.json ? `${JSON.stringify(result)}\n` : formatHumanResolve(result));
102
+ out(json ? `${JSON.stringify(result)}\n` : formatHumanResolve(result));
85
103
  return { exitCode: 0, result };
86
104
  }
@@ -1,6 +1,8 @@
1
1
  /**
2
2
  * `pillar verify <file>` — offline vNext artifact verifier CLI backed by
3
3
  * the vendored `@uuaid/pillar-client` core (`verifyArtifact` + `exitCodeFor`).
4
+ * `pillar verify <uuaid>` — live: core `resolve()` against a registry, which
5
+ * verifies the listing, card and lineage and fails closed (2.7.1 A9).
4
6
  *
5
7
  * Exit codes (V3):
6
8
  * 0 valid
@@ -11,7 +13,7 @@
11
13
  *
12
14
  * Never prints a stack trace on any artifact input or usage error.
13
15
  */
14
- import { readFileSync } from "node:fs";
16
+ import { existsSync, readFileSync } from "node:fs";
15
17
  import {
16
18
  VERDICT_VERSION,
17
19
  VERIFY_TYPES,
@@ -21,13 +23,15 @@ import {
21
23
  verifyArtifact,
22
24
  } from "../vendor/pillar-core.mjs";
23
25
  import { isStrictIsoDateTime, nowIsoSeconds } from "./wave-a.mjs";
26
+ import { isValidUuaid } from "./a6b-common.mjs";
27
+ import { resolveLive } from "./resolve-cli.mjs";
24
28
  import {
25
29
  REGISTRY_STATS_VERDICT_TYPE,
26
30
  TTFA_VERDICT_TYPE,
27
31
  verifyStatsArtifact,
28
32
  } from "../registry/stats.mjs";
29
33
 
30
- export const VERIFY_CLI_TOOL = "pillar/2.7.0";
34
+ export const VERIFY_CLI_TOOL = "pillar/2.7.2";
31
35
  const TYPE_SET = new Set([...VERIFY_TYPES, TTFA_VERDICT_TYPE, REGISTRY_STATS_VERDICT_TYPE]);
32
36
 
33
37
  const VALUE_FLAGS = new Set([
@@ -249,3 +253,91 @@ export function runVerifyCli(rawArgs, io = {}) {
249
253
 
250
254
  return emitVerdict({ ...verdict, tool: VERIFY_CLI_TOOL }, json, out);
251
255
  }
256
+
257
+ export const VERIFY_USAGE = `usage:
258
+ pillar verify <file|-> [--type T] [--now ISO] [--json] [...] verify a saved artifact offline
259
+ (card, listing, lineage log, intro, heartbeat, ...)
260
+ pillar verify <uuaid> [--registry URL] [--now ISO] [--json] verify an agent live: resolve it from a
261
+ registry and check its listing, card and lineage
262
+ Exit: 0 valid, 10 recovered|pending-recovery|contested, 1 invalid or not verified, 2 indeterminate, 64 usage.
263
+ Default registry: config.json "registry", else https://pillar.uuaid.org.`;
264
+
265
+ /** The first positional of `pillar verify`, skipping flags and their values; null if none. */
266
+ function firstPositional(rawArgs) {
267
+ const args = Array.isArray(rawArgs) ? rawArgs : [];
268
+ for (let i = 0; i < args.length; i++) {
269
+ const tok = args[i];
270
+ if (tok === "--") return args[i + 1] ?? null;
271
+ if (typeof tok === "string" && tok.startsWith("-") && tok !== "-") {
272
+ const key = tok.startsWith("--") ? tok.slice(2).split("=")[0] : "";
273
+ if (!tok.includes("=") && (VALUE_FLAGS.has(key) || key === "registry")) i++;
274
+ continue;
275
+ }
276
+ return tok;
277
+ }
278
+ return null;
279
+ }
280
+
281
+ /**
282
+ * Which form a `pillar verify` call is: "uuaid" when its argument is a valid
283
+ * UUAID and no file of that name exists (a file always wins), else "file".
284
+ */
285
+ export function verifyForm(rawArgs) {
286
+ const target = firstPositional(rawArgs);
287
+ let live = typeof target === "string" && isValidUuaid(target);
288
+ if (live && existsSync(target)) live = false; // @rule verify-cli.file-wins
289
+ return live ? "uuaid" : "file";
290
+ }
291
+
292
+ /** A pillar-verdict/1 object exitCodeFor can read. */
293
+ const isVerdict = (v) => typeof v === "object" && v !== null && typeof v.verdict === "string";
294
+
295
+ /**
296
+ * `pillar verify <uuaid>`: core resolve (fail-closed) and the lineage verdict
297
+ * it carries. Exit as the file form: exitCodeFor(lineage verdict); 1 when the
298
+ * registry answer does not verify. Never throws; never prints a stack trace.
299
+ */
300
+ export async function runVerifyUuaidCli(rawArgs, io = {}) {
301
+ const out = io.stdout ?? ((s) => process.stdout.write(s));
302
+ const errOut = io.stderr ?? ((s) => process.stderr.write(s));
303
+ const live = await resolveLive(rawArgs, { cmdName: "verify", io });
304
+ if (live.usage) return { exitCode: live.usage.exitCode, verdict: null };
305
+ const { json, registryUrl, uuaid, result, error } = live;
306
+ let reason = null;
307
+ if (error !== null) reason = "resolve-error";
308
+ else if (!result || result.ok !== true) reason = result?.reason ?? "failed";
309
+ // 2.7.2 C3 (V1 cf5902 P4): core resolve checks the listing and card but
310
+ // fetches no lineage for a listing-only agent (card without lineageHead,
311
+ // current == lineage == query), so there is no lineage verdict to report.
312
+ // Not verified, rather than exitCodeFor(undefined) and a stack trace.
313
+ if (reason === null && !isVerdict(result.lineageVerdict)) reason = "lineage-not-verified"; // @rule verify-cli.uuaid-needs-lineage-verdict
314
+ if (reason !== null) {
315
+ const report = { ok: false, form: "uuaid", query: uuaid, registry: registryUrl, reason, ...(error !== null ? { message: error } : {}), ...(result?.statusCode ? { statusCode: result.statusCode } : {}) };
316
+ if (json) out(`${JSON.stringify(report)}\n`);
317
+ else errOut(`not verified ${uuaid}: ${reason}${result?.statusCode ? ` (HTTP ${result.statusCode})` : ""}${error !== null ? ` (${error})` : ""} [live, ${registryUrl}]\n`);
318
+ return { exitCode: 1, verdict: null }; // @rule verify-cli.uuaid-fail-closed
319
+ }
320
+ const verdict = { ...result.lineageVerdict, tool: VERIFY_CLI_TOOL };
321
+ const exitCode = exitCodeFor(verdict);
322
+ if (json) {
323
+ out(`${JSON.stringify({ ok: true, form: "uuaid", query: uuaid, registry: registryUrl, verdict, lineage: result.lineage, current: result.current, status: result.status, card: result.card, answeredBy: result.answer?.answeredBy ?? null })}\n`);
324
+ } else {
325
+ const lines = [
326
+ `${verdict.verdict}${verdict.reasons?.length ? ` ${verdict.reasons.join(",")}` : ""} ${uuaid} (live: listing, card and lineage verified)`,
327
+ ` lineage: ${result.lineage}`,
328
+ ` current: ${result.current}`,
329
+ ` status: ${result.status}`,
330
+ ...(result.card?.name ? [` name: ${result.card.name}`] : []),
331
+ ...(result.card?.publicKey ? [` publicKey: ${result.card.publicKey}`] : []),
332
+ ` registry: ${registryUrl}${result.answer?.answeredBy ? ` (answered by ${result.answer.answeredBy})` : ""}`,
333
+ ];
334
+ out(`${lines.join("\n")}\n`);
335
+ }
336
+ return { exitCode, verdict };
337
+ }
338
+
339
+ /** `pillar verify`, either form. */
340
+ export async function runVerifyCommand(rawArgs, io = {}) {
341
+ if (verifyForm(rawArgs) === "uuaid") return runVerifyUuaidCli(rawArgs, io);
342
+ return runVerifyCli(rawArgs, io);
343
+ }