@uuaid/pillar 2.7.0 → 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.
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,86 @@ 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 stays on 2.6.1 until 2.7.2** (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
723
  > **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.
724
+ > 2.7.2.** A 2.7.x registry can stop answering `directory.json` (and every
725
+ > other request while it works) for up to one prune pass, about 3.5 ms per
726
+ > listing, at startup and about every 10 minutes. 2.7.1 fixes the timer
727
+ > pause and the heartbeat-seq issue; 2.7.2 fixes the rest. Agents, carriers
728
+ > and private registries can use 2.7.1. The UUAID registry at
729
+ > pillar.uuaid.org is upgraded separately; until then it does not answer
730
+ > /v1/resolve.
610
731
 
611
732
  ```sh
612
733
  pillar-responder --home ~/.pillar-responder --reply-text "ack" &
@@ -782,8 +903,9 @@ survivors.
782
903
  ### Joining is permissionless
783
904
 
784
905
  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):
906
+ `pillar-directory` (see "Running a seed" above). Any operator can run one;
907
+ use the URL of the registry whose directory your agents bootstrap from, and
908
+ check that it answers `GET <registry>/v1/health` first:
787
909
 
788
910
  ```sh
789
911
  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);
@@ -491,6 +492,7 @@ const shutdown = async () => {
491
492
  federationCoordinator.stop();
492
493
  server.closeAllConnections?.();
493
494
  await new Promise(r => server.close(r));
495
+ await tombstonePruning.whenIdle();
494
496
  registry.close();
495
497
  process.exit(0);
496
498
  };
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.1",
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).
@@ -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
@@ -46,6 +46,10 @@ export const TOMBSTONE_RETENTION_MS = 365 * 86_400_000;
46
46
  * EVAL_MEMO_MAX_AGE_MS; each prune pass re-verifies all of them.
47
47
  */
48
48
  export const PRUNE_INTERVAL_MS = 10 * 60_000;
49
+ /** Longest stretch a timed prune pass holds the event loop before it yields (V1 P2). */
50
+ export const PRUNE_SLICE_MS = 20;
51
+
52
+ const yieldToEventLoop = () => new Promise((resolve) => setImmediate(resolve));
49
53
  export const PROJECTION_MAX_AGE_MS = 60_000;
50
54
  export const EVAL_MEMO_MAX_AGE_MS = PRUNE_INTERVAL_MS;
51
55
 
@@ -434,38 +438,78 @@ export class ListingStore {
434
438
  /**
435
439
  * Prune dead / withdrawn / tombstoned listing rows that have been dead for `>= 365` days
436
440
  * (`TOMBSTONE_RETENTION_MS`), while leaving `lineage_event` untouched (`T3.5`).
441
+ * One synchronous pass (tests, tools). The registry's timer uses
442
+ * pruneExpiredTombstonesYielding, which gives the event loop a turn between slices.
437
443
  */
438
444
  pruneExpiredTombstones({ now } = {}) {
439
445
  const nowStr = nowIso(now);
440
446
  const nowMs = Date.parse(nowStr);
441
447
  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
- }
448
+ for (const lineage of this._listedLineages()) {
449
+ if (this._pruneOne(lineage, nowStr, nowMs)) lineages.push(lineage);
450
+ }
451
+ return { pruned: lineages.length, lineages };
452
+ }
459
453
 
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++;
454
+ /**
455
+ * The same pass in slices of at most `sliceMs` (V1 P2): after each slice it
456
+ * awaits `yieldFn` (setImmediate), so requests are answered during the pass.
457
+ * Each row is re-read and judged inside one slice, so a write that lands
458
+ * between slices is seen. `shouldStop()` ends the pass early (shutdown).
459
+ * Returns { pruned, lineages, rows, slices, longestSliceMs }.
460
+ */
461
+ async pruneExpiredTombstonesYielding({ now, sliceMs = PRUNE_SLICE_MS, yieldFn = yieldToEventLoop, shouldStop = () => false } = {}) {
462
+ const nowStr = nowIso(now);
463
+ const nowMs = Date.parse(nowStr);
464
+ const lineages = [];
465
+ const all = this._listedLineages();
466
+ let slices = 1;
467
+ let longestSliceMs = 0;
468
+ let sliceStart = performance.now();
469
+ for (const lineage of all) {
470
+ if (shouldStop()) break;
471
+ if (this._pruneOne(lineage, nowStr, nowMs)) lineages.push(lineage);
472
+ const spent = performance.now() - sliceStart;
473
+ let yieldNow = false;
474
+ if (spent >= sliceMs) yieldNow = true; // @rule reg.prune-yields
475
+ if (yieldNow) {
476
+ longestSliceMs = Math.max(longestSliceMs, spent);
477
+ await yieldFn();
478
+ slices++;
479
+ sliceStart = performance.now();
465
480
  }
466
481
  }
482
+ longestSliceMs = Math.max(longestSliceMs, performance.now() - sliceStart);
483
+ return { pruned: lineages.length, lineages, rows: all.length, slices, longestSliceMs: Math.round(longestSliceMs) };
484
+ }
467
485
 
468
- return { pruned: lineages.length, lineages };
486
+ _listedLineages() {
487
+ return this.all().map((row) => row.lineage);
488
+ }
489
+
490
+ /** Prune one listing if it has been dead >= 365 days. Reads the row now (a yielding pass may have slept). */
491
+ _pruneOne(lineage, nowStr, nowMs) {
492
+ const row = this.getByLineage(lineage);
493
+ if (!row) return false;
494
+ const l = row.listing;
495
+ // A fresh verdict (maxAgeMs 0), kept for the next directory.json rebuild.
496
+ const evalRes = this.lineageStore ? this.lineageStore.evaluateLineageCached(l.lineage, { now: nowStr, maxAgeMs: 0 }) : null;
497
+ let deadSinceMs = null;
498
+ if (evalRes?.tombstoned === true) {
499
+ deadSinceMs = Date.parse(evalRes.tombstoneTs);
500
+ } else if (row.withdrawn === 1 || l.withdrawn === true) {
501
+ deadSinceMs = row.issued_at_ms;
502
+ } else {
503
+ const cur = evalRes && (evalRes.verdict === "valid" || evalRes.verdict === "recovered" || evalRes.verdict === "pending-recovery") ? evalRes.current : l.uuaid;
504
+ const hb = this.heartbeatStore ? this.heartbeatStore.getLatest(l.lineage) : null;
505
+ const lastSeenMs = hb && hb.uuaid === cur ? Math.max(row.issued_at_ms, hb.ts_ms) : row.issued_at_ms;
506
+ if (nowMs - lastSeenMs >= STATUS_QUIET_MS) deadSinceMs = lastSeenMs + STATUS_QUIET_MS;
507
+ }
508
+ if (deadSinceMs === null || nowMs - deadSinceMs < TOMBSTONE_RETENTION_MS) return false;
509
+ this.db.prepare("delete from listing where lineage = ?").run(l.lineage); // @rule reg.listing-prune-365d
510
+ if (this.heartbeatStore) this.heartbeatStore.deleteByLineage(l.lineage);
511
+ this.changes++;
512
+ return true;
469
513
  }
470
514
 
471
515
  /**
@@ -523,27 +567,46 @@ export class ListingStore {
523
567
  }
524
568
 
525
569
  /**
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 }).
570
+ * Prune off the request path (V1 F2), in slices that yield to the event loop
571
+ * (V1 P2): one pass now, then one every `intervalMs` (unref'd). The first
572
+ * slice runs before this returns; the rest run while the registry serves.
573
+ * One pass at a time; a pass that throws is logged and the timer keeps
574
+ * running. A pass that pruned rows or ran >= 1 s is reported through `info`.
575
+ * Returns { stop, runNow, whenIdle, runs } (runs: the last 10 passes,
576
+ * { pruned, rows, ms, slices, longestSliceMs }).
530
577
  */
531
- export function startTombstonePruning(listingStore, { getNow = () => undefined, intervalMs = PRUNE_INTERVAL_MS, log = (m) => console.error(m), setIntervalFn = setInterval, clearIntervalFn = clearInterval } = {}) {
578
+ 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
579
  const runs = [];
533
- const runNow = () => {
580
+ let stopped = false;
581
+ let inFlight = null;
582
+ const pass = async () => {
534
583
  const t0 = performance.now();
535
584
  try {
536
- const r = listingStore.pruneExpiredTombstones({ now: getNow() });
537
- runs.push({ pruned: r.pruned, ms: Math.round(performance.now() - t0) });
585
+ const r = await listingStore.pruneExpiredTombstonesYielding({ now: getNow(), sliceMs, shouldStop: () => stopped });
586
+ const ms = Math.round(performance.now() - t0);
587
+ runs.push({ pruned: r.pruned, rows: r.rows, ms, slices: r.slices, longestSliceMs: r.longestSliceMs });
538
588
  if (runs.length > 10) runs.shift();
589
+ if (r.pruned > 0 || ms >= 1000) info(`[registry] tombstone prune: ${r.pruned} of ${r.rows} listings pruned in ${ms} ms (${r.slices} slices, longest ${r.longestSliceMs} ms)`);
539
590
  return r;
540
591
  } catch (e) {
541
- log(`[registry] tombstone prune failed: ${e?.message ?? e}`);
592
+ if (!stopped) log(`[registry] tombstone prune failed: ${e?.message ?? e}`);
542
593
  return null;
594
+ } finally {
595
+ inFlight = null;
543
596
  }
544
597
  };
598
+ const runNow = () => {
599
+ if (stopped) return Promise.resolve(null);
600
+ if (!inFlight) inFlight = pass();
601
+ return inFlight;
602
+ };
545
603
  runNow();
546
604
  const timer = setIntervalFn(runNow, intervalMs);
547
605
  timer?.unref?.();
548
- return { stop: () => clearIntervalFn(timer), runNow, runs };
606
+ return {
607
+ stop: () => { stopped = true; clearIntervalFn(timer); },
608
+ runNow,
609
+ whenIdle: () => inFlight ?? Promise.resolve(null),
610
+ runs,
611
+ };
549
612
  }
@@ -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.1";
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.1";
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,81 @@ 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
+ /**
293
+ * `pillar verify <uuaid>`: core resolve (fail-closed) and the lineage verdict
294
+ * it carries. Exit as the file form: exitCodeFor(lineage verdict); 1 when the
295
+ * registry answer does not verify. Never throws; never prints a stack trace.
296
+ */
297
+ export async function runVerifyUuaidCli(rawArgs, io = {}) {
298
+ const out = io.stdout ?? ((s) => process.stdout.write(s));
299
+ const errOut = io.stderr ?? ((s) => process.stderr.write(s));
300
+ const live = await resolveLive(rawArgs, { cmdName: "verify", io });
301
+ if (live.usage) return { exitCode: live.usage.exitCode, verdict: null };
302
+ const { json, registryUrl, uuaid, result, error } = live;
303
+ if (error !== null || !result || result.ok !== true) {
304
+ const reason = error !== null ? "resolve-error" : (result?.reason ?? "failed");
305
+ const report = { ok: false, form: "uuaid", query: uuaid, registry: registryUrl, reason, ...(error !== null ? { message: error } : {}), ...(result?.statusCode ? { statusCode: result.statusCode } : {}) };
306
+ if (json) out(`${JSON.stringify(report)}\n`);
307
+ else errOut(`not verified ${uuaid}: ${reason}${result?.statusCode ? ` (HTTP ${result.statusCode})` : ""}${error !== null ? ` (${error})` : ""} [live, ${registryUrl}]\n`);
308
+ return { exitCode: 1, verdict: null }; // @rule verify-cli.uuaid-fail-closed
309
+ }
310
+ const verdict = { ...result.lineageVerdict, tool: VERIFY_CLI_TOOL };
311
+ const exitCode = exitCodeFor(verdict);
312
+ if (json) {
313
+ 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`);
314
+ } else {
315
+ const lines = [
316
+ `${verdict.verdict}${verdict.reasons?.length ? ` ${verdict.reasons.join(",")}` : ""} ${uuaid} (live: listing, card and lineage verified)`,
317
+ ` lineage: ${result.lineage}`,
318
+ ` current: ${result.current}`,
319
+ ` status: ${result.status}`,
320
+ ...(result.card?.name ? [` name: ${result.card.name}`] : []),
321
+ ...(result.card?.publicKey ? [` publicKey: ${result.card.publicKey}`] : []),
322
+ ` registry: ${registryUrl}${result.answer?.answeredBy ? ` (answered by ${result.answer.answeredBy})` : ""}`,
323
+ ];
324
+ out(`${lines.join("\n")}\n`);
325
+ }
326
+ return { exitCode, verdict };
327
+ }
328
+
329
+ /** `pillar verify`, either form. */
330
+ export async function runVerifyCommand(rawArgs, io = {}) {
331
+ if (verifyForm(rawArgs) === "uuaid") return runVerifyUuaidCli(rawArgs, io);
332
+ return runVerifyCli(rawArgs, io);
333
+ }