@uuaid/pillar 2.7.1 → 2.7.3

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
@@ -717,17 +717,47 @@ a UUAID is read as a file.
717
717
  |---|---|---|
718
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 |
719
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 |
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 |
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 |
721
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 |
722
722
 
723
- > **Running a public registry (`pillar-directory`)? Stay on 2.6.1 until
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.
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
+ > From 2.7.3, `pillar-directory` exits 2 when it cannot use a flag or a
750
+ > value: an unknown flag, a flag with no value, a number that is out of
751
+ > range or not written in digits, or an empty `DIRECTORY_*` variable.
752
+ > `--flag value` and `--flag=value` are the same. The line after
753
+ > `listening on` shows the limits in effect (`limits: ...
754
+ > --max-new-lineages-per-hour 20 ...`); check it after each start.
755
+ > 2.7.2 and earlier ignore `--max-new-lineages-per-hour=0` and use 600:
756
+ > there, write `--max-new-lineages-per-hour 0`.
757
+ >
758
+ > Agents, carriers and private registries can use 2.7.1 or later. The UUAID
759
+ > registry at pillar.uuaid.org is upgraded separately; until then it does
760
+ > not answer /v1/resolve.
731
761
 
732
762
  ```sh
733
763
  pillar-responder --home ~/.pillar-responder --reply-text "ack" &
@@ -35,21 +35,12 @@ import { SeedRegistry } from "../src/net/seed-registry.mjs";
35
35
  import { clientIpOf, parseTrustedProxies } from "../src/net/client-ip.mjs";
36
36
  import { Keychain, mintNamespace, SERVICE_IDENTITY_NAMESPACE } from "../src/identity/keychain.mjs";
37
37
  import { tryLoadBetterSqlite3 } from "../src/sqlite-loader.mjs";
38
- import {
39
- DEFAULT_MAX_RESOLVE_MISSES_PER_IP_PER_MINUTE,
40
- DEFAULT_MAX_STRIKES,
41
- DEFAULT_NEGATIVE_CACHE_TTL_MS,
42
- DEFAULT_PULL_INTERVAL_MS,
43
- DEFAULT_QUARANTINE_COOLDOWN_MS,
44
- DEFAULT_RESOLVE_TIMEOUT_MS,
45
- FederationCoordinator,
46
- makeResolveMissRateLimiter,
47
- openRegistryDb,
48
- } from "../src/registry/federation.mjs";
38
+ import { FederationCoordinator, makeResolveMissRateLimiter, openRegistryDb } from "../src/registry/federation.mjs";
39
+ import { formatDirectoryLimits, parseDirectoryArgs } from "../src/registry/directory-flags.mjs";
49
40
  import { GossipCoordinator } from "../src/registry/gossip.mjs";
50
41
  import { HeartbeatStore } from "../src/registry/heartbeats.mjs";
51
42
  import { LineageStore, isStrictDateTime } from "../src/registry/lineage.mjs";
52
- import { ListingStore, isStrictHttpsUri, MAX_NEW_LINEAGES_PER_HOUR, startTombstonePruning } from "../src/registry/listings.mjs";
43
+ import { ListingStore, isStrictHttpsUri, startTombstonePruning } from "../src/registry/listings.mjs";
53
44
  import { handleRegistryRoute } from "../src/registry/resolve.mjs";
54
45
  import {
55
46
  buildRegistryStats,
@@ -60,32 +51,6 @@ import {
60
51
  } from "../src/registry/stats.mjs";
61
52
  import { exitWithHelp, wantsHelp } from "../src/cli-help.mjs";
62
53
 
63
- function parsePeersArg(raw) {
64
- if (!raw || typeof raw !== "string") return [];
65
- const trimmed = raw.trim();
66
- if (!trimmed) return [];
67
- if (trimmed.startsWith("[")) {
68
- const parsed = JSON.parse(trimmed);
69
- return Array.isArray(parsed) ? parsed : [];
70
- }
71
- return trimmed
72
- .split(",")
73
- .map((s) => s.trim())
74
- .filter(Boolean);
75
- }
76
-
77
- function parseArgs(argv) {
78
- const args = {};
79
- for (let i = 0; i < argv.length; i++) {
80
- const a = argv[i];
81
- if (a.startsWith("--")) {
82
- const k = a.slice(2);
83
- args[k] = (argv[i + 1] && !argv[i + 1].startsWith("--")) ? argv[++i] : true;
84
- }
85
- }
86
- return args;
87
- }
88
-
89
54
  const USAGE = `usage: pillar-directory [flags]
90
55
 
91
56
  Serves directory.json and the seed registry. Listens on 127.0.0.1 by default.
@@ -108,68 +73,50 @@ More flags (limits, federation timers, test hooks): --protocol, --allow-private-
108
73
  --max-listings-per-ip-per-hour, --max-lineage-posts-per-ip-per-hour,
109
74
  --max-heartbeats-per-ip-per-hour, --pull-interval-ms, --max-strikes,
110
75
  --quarantine-cooldown-ms, --resolve-timeout-ms, --resolve-negative-ttl-ms,
111
- --max-resolve-misses-per-ip-per-minute. Routes: see the header of bin/pillar-directory.mjs.`;
76
+ --max-resolve-misses-per-ip-per-minute. Routes: see the header of bin/pillar-directory.mjs.
77
+
78
+ --flag value and --flag=value are the same. An unknown flag, a flag with no value,
79
+ a number that is not a whole number in range (digits only) or an empty DIRECTORY_*
80
+ variable exits 2 before anything is written. After "listening on" a line shows
81
+ the limits in effect.`;
112
82
  if (wantsHelp(process.argv.slice(2))) await exitWithHelp(USAGE); // R2: before the registry key is minted or the db is opened
113
- const args = parseArgs(process.argv.slice(2));
114
- const home = args.home ?? process.env.DIRECTORY_HOME ?? join(homedir(), ".pillar-directory");
115
- const port = Number(args.port ?? process.env.DIRECTORY_PORT ?? 8800);
116
- const host = args.host ?? process.env.DIRECTORY_HOST ?? "127.0.0.1";
117
- const dbPath = args.db ?? process.env.DIRECTORY_DB ?? join(home, "registry.db");
118
- const carrier = args.carrier ?? process.env.DIRECTORY_CARRIER ?? null;
119
- const agentsPath = args.agents ?? process.env.DIRECTORY_AGENTS ?? null;
120
- const protocol = args.protocol ?? process.env.DIRECTORY_PROTOCOL ?? "uacp/1.0-draft";
121
- const probeMinutes = Number(args["probe-minutes"] ?? process.env.DIRECTORY_PROBE_MINUTES ?? 10);
122
- const allowPrivateUrls = Boolean(args["allow-private-urls"]);
123
- const publicUrlArg = args["public-url"] ?? process.env.DIRECTORY_PUBLIC_URL ?? null;
124
- const rawUrlMap = args["url-map"] ?? process.env.DIRECTORY_URL_MAP ?? null;
125
- const urlMap = rawUrlMap ? JSON.parse(rawUrlMap) : null;
126
- const clockFile = typeof args["clock-file"] === "string" ? args["clock-file"] : null;
83
+ // 2.7.3 (V1 c9da71 P3): every flag and DIRECTORY_* value is checked here, before
84
+ // the registry key is minted or the db is opened; one it cannot use exits 2.
85
+ const parsed = parseDirectoryArgs(process.argv.slice(2), process.env);
86
+ if (!parsed.ok) {
87
+ console.error(`pillar-directory: ${parsed.error.replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029]/g, (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, "0")}`)}. See pillar-directory --help.`);
88
+ process.exit(2);
89
+ }
90
+ const opts = parsed.values;
91
+ const home = opts.home ?? join(homedir(), ".pillar-directory");
92
+ const port = opts.port;
93
+ const host = opts.host ?? "127.0.0.1";
94
+ const dbPath = opts.db ?? join(home, "registry.db");
95
+ const carrier = opts.carrier ?? null;
96
+ const agentsPath = opts.agents ?? null;
97
+ const protocol = opts.protocol ?? "uacp/1.0-draft";
98
+ const probeMinutes = opts["probe-minutes"];
99
+ const allowPrivateUrls = opts["allow-private-urls"];
100
+ const publicUrlArg = opts["public-url"] ?? null;
101
+ const urlMap = opts.urlMap;
102
+ const clockFile = opts["clock-file"] ?? null;
127
103
  const getNow = () => {
128
104
  if (!clockFile || !existsSync(clockFile)) return undefined;
129
105
  const raw = readFileSync(clockFile, "utf-8").trim();
130
106
  return isStrictDateTime(raw) ? raw : undefined;
131
107
  };
132
- const stampBits = Number(args["stamp-bits"] ?? process.env.DIRECTORY_STAMP_BITS ?? 18);
133
- const maxNewLineagesPerHour = Number(
134
- args["max-new-lineages-per-hour"] ?? process.env.DIRECTORY_MAX_NEW_LINEAGES_PER_HOUR ?? MAX_NEW_LINEAGES_PER_HOUR,
135
- );
136
- const DEFAULT_MAX_LISTINGS_PER_IP_PER_HOUR = 60;
137
- const DEFAULT_MAX_LINEAGE_POSTS_PER_IP_PER_HOUR = 300;
138
- const DEFAULT_MAX_HEARTBEATS_PER_IP_PER_HOUR = 120;
139
- const maxListingsPerIpPerHour = Number(
140
- args["max-listings-per-ip-per-hour"] ??
141
- process.env.DIRECTORY_MAX_LISTINGS_PER_IP_PER_HOUR ??
142
- DEFAULT_MAX_LISTINGS_PER_IP_PER_HOUR,
143
- );
144
- const maxLineagePostsPerIpPerHour = Number(
145
- args["max-lineage-posts-per-ip-per-hour"] ??
146
- process.env.DIRECTORY_MAX_LINEAGE_POSTS_PER_IP_PER_HOUR ??
147
- DEFAULT_MAX_LINEAGE_POSTS_PER_IP_PER_HOUR,
148
- );
149
- const maxHeartbeatsPerIpPerHour = Number(
150
- args["max-heartbeats-per-ip-per-hour"] ??
151
- process.env.DIRECTORY_MAX_HEARTBEATS_PER_IP_PER_HOUR ??
152
- DEFAULT_MAX_HEARTBEATS_PER_IP_PER_HOUR,
153
- );
154
- const configuredPeers = parsePeersArg(args.peers ?? args.peer ?? process.env.DIRECTORY_PEERS ?? "");
155
- const pullIntervalMs = Number(
156
- args["pull-interval-ms"] ?? process.env.DIRECTORY_PULL_INTERVAL_MS ?? DEFAULT_PULL_INTERVAL_MS,
157
- );
158
- const maxStrikes = Number(args["max-strikes"] ?? process.env.DIRECTORY_MAX_STRIKES ?? DEFAULT_MAX_STRIKES);
159
- const quarantineCooldownMs = Number(
160
- args["quarantine-cooldown-ms"] ?? process.env.DIRECTORY_QUARANTINE_COOLDOWN_MS ?? DEFAULT_QUARANTINE_COOLDOWN_MS,
161
- );
162
- const resolveTimeoutMs = Number(
163
- args["resolve-timeout-ms"] ?? process.env.DIRECTORY_RESOLVE_TIMEOUT_MS ?? DEFAULT_RESOLVE_TIMEOUT_MS,
164
- );
165
- const negativeCacheTtlMs = Number(
166
- args["resolve-negative-ttl-ms"] ?? process.env.DIRECTORY_RESOLVE_NEGATIVE_TTL_MS ?? DEFAULT_NEGATIVE_CACHE_TTL_MS,
167
- );
168
- const maxResolveMissesPerIpPerMinute = Number(
169
- args["max-resolve-misses-per-ip-per-minute"] ??
170
- process.env.DIRECTORY_MAX_RESOLVE_MISSES_PER_IP_PER_MINUTE ??
171
- DEFAULT_MAX_RESOLVE_MISSES_PER_IP_PER_MINUTE,
172
- );
108
+ const stampBits = opts["stamp-bits"];
109
+ const maxNewLineagesPerHour = opts["max-new-lineages-per-hour"];
110
+ const maxListingsPerIpPerHour = opts["max-listings-per-ip-per-hour"];
111
+ const maxLineagePostsPerIpPerHour = opts["max-lineage-posts-per-ip-per-hour"];
112
+ const maxHeartbeatsPerIpPerHour = opts["max-heartbeats-per-ip-per-hour"];
113
+ const configuredPeers = opts.peerList;
114
+ const pullIntervalMs = opts["pull-interval-ms"];
115
+ const maxStrikes = opts["max-strikes"];
116
+ const quarantineCooldownMs = opts["quarantine-cooldown-ms"];
117
+ const resolveTimeoutMs = opts["resolve-timeout-ms"];
118
+ const negativeCacheTtlMs = opts["resolve-negative-ttl-ms"];
119
+ const maxResolveMissesPerIpPerMinute = opts["max-resolve-misses-per-ip-per-minute"];
173
120
 
174
121
  const MAX_ENROLLMENTS_PER_HOUR = 10; // per client IP
175
122
  const MAX_BODY = 8 * 1024;
@@ -334,7 +281,7 @@ function readBody(req) {
334
281
 
335
282
  // X-Forwarded-For counts only from a trusted proxy (2.5.3; src/net/client-ip.mjs).
336
283
  let trustedProxies;
337
- try { trustedProxies = parseTrustedProxies(args["trusted-proxy"] ?? process.env.DIRECTORY_TRUSTED_PROXIES); }
284
+ try { trustedProxies = parseTrustedProxies(opts["trusted-proxy"]); }
338
285
  catch (e) { console.error(`pillar-directory: ${e.message}`); process.exit(2); }
339
286
  const clientIp = (req) => clientIpOf(req, trustedProxies);
340
287
 
@@ -343,6 +290,9 @@ const server = createServer(async (req, res) => {
343
290
  const url = new URL(req.url, `http://${req.headers.host ?? "localhost"}`);
344
291
 
345
292
  if (req.method === "GET" && (url.pathname === "/directory.json" || url.pathname === "/")) {
293
+ // 2.7.2 C2: the start pass fills the lineage memo in yielding slices; until
294
+ // it ends, a projection would verify every listing inside this request.
295
+ await tombstonePruning.firstPass;
346
296
  const mergedAgents = listingStore.projectLiveAgents({ staticAgents: agents(), now: getNow() });
347
297
  return send(res, 200, registry.directory({ agents: mergedAgents }));
348
298
  }
@@ -361,6 +311,7 @@ const server = createServer(async (req, res) => {
361
311
  try {
362
312
  aggregate = loadRegistryStatsSnapshot(statsDir, registry.uuaid, day, pin);
363
313
  if (!aggregate) {
314
+ await tombstonePruning.firstPass; // 2.7.2 C2, as /directory.json
364
315
  const projected = listingStore.projectLiveAgents({ staticAgents: agents(), now: getNow() });
365
316
  const built = buildRegistryStats(collectRegistryCounts(projected), keychain, { day });
366
317
  aggregate = persistFirstRegistryStats(statsDir, built, pin);
@@ -457,6 +408,7 @@ if (configuredPeers.length > 0 && pullIntervalMs > 0) {
457
408
  federationCoordinator.start();
458
409
  }
459
410
  console.log(`pillar-directory listening on http://${formatHostForUrl(host)}:${boundPort}`);
411
+ console.log(` limits: ${formatDirectoryLimits(opts)}`);
460
412
  console.log(` uuaid: ${registry.uuaid}`);
461
413
  console.log(` issuer: ${registry.issuerKey}`);
462
414
  console.log(` carrier: ${carrier ?? "(none — set --carrier)"}`);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@uuaid/pillar",
3
- "version": "2.7.1",
3
+ "version": "2.7.3",
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",
@@ -0,0 +1,182 @@
1
+ /**
2
+ * pillar-directory flags and environment (2.7.3, V1 c9da71 P3).
3
+ *
4
+ * Before 2.7.3 the bin stored `--k=v` under the key "k=v" and ignored it,
5
+ * ignored unknown flags, and read every limit with a bare Number(): a flag
6
+ * with no value gave 1, "abc" gave NaN (no registry-wide cap), an empty
7
+ * environment variable gave 0. None of it was visible. Now:
8
+ *
9
+ * - `--k=v` means the same as `--k v`; a value that starts with "-" must
10
+ * use the `=` form.
11
+ * - An unknown flag, a bare word, a boolean flag given a value, or a value
12
+ * flag given none is refused.
13
+ * - Every numeric flag and environment variable must be a whole number in
14
+ * its range, written as digits only ("0x10", "1e3", " 5", "-1" refused).
15
+ * - A DIRECTORY_* variable set to "" is refused (never a deliberate
16
+ * setting), as pillar-seed refuses its SEED_* ones.
17
+ * - --peers and --url-map must parse.
18
+ *
19
+ * parseDirectoryArgs never exits: the bin prints the error on one line and
20
+ * exits 2 before the registry key is minted or the db is opened.
21
+ */
22
+ import {
23
+ DEFAULT_MAX_RESOLVE_MISSES_PER_IP_PER_MINUTE,
24
+ DEFAULT_MAX_STRIKES,
25
+ DEFAULT_NEGATIVE_CACHE_TTL_MS,
26
+ DEFAULT_PULL_INTERVAL_MS,
27
+ DEFAULT_QUARANTINE_COOLDOWN_MS,
28
+ DEFAULT_RESOLVE_TIMEOUT_MS,
29
+ } from "./federation.mjs";
30
+ import { MAX_NEW_LINEAGES_PER_HOUR } from "./listings.mjs";
31
+
32
+ /** Node clamps a longer timer to 1 ms, so a timer setting above this would fire at once. */
33
+ export const TIMER_MAX_MS = 2 ** 31 - 1;
34
+ const COUNT_MAX = 1_000_000;
35
+
36
+ const str = (flag, env) => ({ flag, env, kind: "string" });
37
+ const bool = (flag) => ({ flag, env: null, kind: "bool" });
38
+ const int = (flag, env, def, min, max) => ({ flag, env, kind: "int", def, min, max });
39
+
40
+ /** Every flag pillar-directory reads, in --help order. Numeric ones carry their default and range. */
41
+ export const DIRECTORY_FLAGS = Object.freeze([
42
+ str("home", "DIRECTORY_HOME"),
43
+ str("db", "DIRECTORY_DB"),
44
+ int("port", "DIRECTORY_PORT", 8800, 0, 65535),
45
+ str("host", "DIRECTORY_HOST"),
46
+ str("carrier", "DIRECTORY_CARRIER"),
47
+ str("agents", "DIRECTORY_AGENTS"),
48
+ str("public-url", "DIRECTORY_PUBLIC_URL"),
49
+ str("peers", "DIRECTORY_PEERS"),
50
+ str("peer", null), // older spelling of --peers
51
+ str("trusted-proxy", "DIRECTORY_TRUSTED_PROXIES"),
52
+ int("probe-minutes", "DIRECTORY_PROBE_MINUTES", 10, 1, Math.floor(TIMER_MAX_MS / 60_000)),
53
+ bool("help"),
54
+ str("protocol", "DIRECTORY_PROTOCOL"),
55
+ bool("allow-private-urls"),
56
+ str("url-map", "DIRECTORY_URL_MAP"),
57
+ str("clock-file", null),
58
+ int("stamp-bits", "DIRECTORY_STAMP_BITS", 18, 12, 24),
59
+ int("max-new-lineages-per-hour", "DIRECTORY_MAX_NEW_LINEAGES_PER_HOUR", MAX_NEW_LINEAGES_PER_HOUR, 0, COUNT_MAX),
60
+ int("max-listings-per-ip-per-hour", "DIRECTORY_MAX_LISTINGS_PER_IP_PER_HOUR", 60, 0, COUNT_MAX),
61
+ int("max-lineage-posts-per-ip-per-hour", "DIRECTORY_MAX_LINEAGE_POSTS_PER_IP_PER_HOUR", 300, 0, COUNT_MAX),
62
+ int("max-heartbeats-per-ip-per-hour", "DIRECTORY_MAX_HEARTBEATS_PER_IP_PER_HOUR", 120, 0, COUNT_MAX),
63
+ int("max-resolve-misses-per-ip-per-minute", "DIRECTORY_MAX_RESOLVE_MISSES_PER_IP_PER_MINUTE", DEFAULT_MAX_RESOLVE_MISSES_PER_IP_PER_MINUTE, 0, COUNT_MAX),
64
+ int("pull-interval-ms", "DIRECTORY_PULL_INTERVAL_MS", DEFAULT_PULL_INTERVAL_MS, 0, TIMER_MAX_MS),
65
+ int("max-strikes", "DIRECTORY_MAX_STRIKES", DEFAULT_MAX_STRIKES, 1, 1000),
66
+ int("quarantine-cooldown-ms", "DIRECTORY_QUARANTINE_COOLDOWN_MS", DEFAULT_QUARANTINE_COOLDOWN_MS, 0, TIMER_MAX_MS),
67
+ int("resolve-timeout-ms", "DIRECTORY_RESOLVE_TIMEOUT_MS", DEFAULT_RESOLVE_TIMEOUT_MS, 0, TIMER_MAX_MS),
68
+ int("resolve-negative-ttl-ms", "DIRECTORY_RESOLVE_NEGATIVE_TTL_MS", DEFAULT_NEGATIVE_CACHE_TTL_MS, 0, TIMER_MAX_MS),
69
+ ]);
70
+
71
+ const BY_FLAG = new Map(DIRECTORY_FLAGS.map((s) => [s.flag, s]));
72
+
73
+ /**
74
+ * --peers: a comma list of http(s) URLs, or a JSON list whose entries are
75
+ * http(s) URLs or peer objects ({ uuaid, url, publicKey }; the coordinator
76
+ * checks each object). Throws on bad JSON, a non-list, or another entry.
77
+ */
78
+ export function parsePeersArg(raw) {
79
+ if (!raw || typeof raw !== "string") return [];
80
+ const trimmed = raw.trim();
81
+ if (!trimmed) return [];
82
+ if (trimmed.startsWith("[")) {
83
+ const parsed = JSON.parse(trimmed);
84
+ const entryOk = (e) => isHttpUrl(e) || (e !== null && typeof e === "object" && !Array.isArray(e));
85
+ if (!Array.isArray(parsed) || !parsed.every(entryOk)) throw new Error("a JSON list of peer URLs or peer objects");
86
+ return parsed;
87
+ }
88
+ const list = trimmed.split(",").map((s) => s.trim()).filter(Boolean);
89
+ if (!list.every(isHttpUrl)) throw new Error("a comma list of http(s) URLs");
90
+ return list;
91
+ }
92
+
93
+ /** An http: or https: URL (the coordinator checks private and mapped hosts itself). */
94
+ function isHttpUrl(u) {
95
+ if (typeof u !== "string") return false;
96
+ try { const p = new URL(u.trim()).protocol; return p === "https:" || p === "http:"; } catch { return false; }
97
+ }
98
+
99
+ /** A token as an error message shows it: as typed when plain, else JSON-quoted. */
100
+ const shown = (t) => (/^[\x21-\x7e]+$/.test(t) ? t : JSON.stringify(t));
101
+
102
+ /**
103
+ * Parse pillar-directory's argv and environment.
104
+ * Returns { ok: true, values } or { ok: false, error } (one sentence, no trailing period).
105
+ * `values` holds every flag by name (int: number with its default applied;
106
+ * string: string or undefined; bool: boolean), plus `peerList` and `urlMap`.
107
+ */
108
+ export function parseDirectoryArgs(argv, env = process.env) {
109
+ const given = {};
110
+ const unknown = [];
111
+ const valued = [];
112
+ const missing = [];
113
+ const words = [];
114
+ for (let i = 0; i < argv.length; i++) {
115
+ const a = argv[i];
116
+ if (a === "-h") { given.help = true; continue; }
117
+ if (!(a.startsWith("--") && a.length > 2)) { words.push(a); continue; }
118
+ const eq = a.indexOf("=");
119
+ const k = eq === -1 ? a.slice(2) : a.slice(2, eq);
120
+ const spec = BY_FLAG.get(k);
121
+ if (!spec) {
122
+ unknown.push(`--${k}`);
123
+ // Its value, if it has one, is part of the mistake, not a second one.
124
+ if (eq === -1 && argv[i + 1] !== undefined && !argv[i + 1].startsWith("-")) i++;
125
+ continue;
126
+ }
127
+ if (spec.kind === "bool") {
128
+ if (eq === -1) given[k] = true; else valued.push(`--${k}`);
129
+ continue;
130
+ }
131
+ let v;
132
+ if (eq !== -1) v = a.slice(eq + 1);
133
+ else if (argv[i + 1] !== undefined && !argv[i + 1].startsWith("-")) v = argv[++i];
134
+ if (v === undefined || v === "") { missing.push(`--${k}`); continue; }
135
+ given[k] = v;
136
+ }
137
+ const parts = [];
138
+ if (unknown.length) parts.push(`unknown flag${unknown.length > 1 ? "s" : ""} ${unknown.map(shown).join(", ")}`);
139
+ if (valued.length) parts.push(`${valued.join(", ")} take${valued.length > 1 ? "" : "s"} no value`);
140
+ if (missing.length) parts.push(`${missing.join(", ")} need${missing.length > 1 ? "" : "s"} a value (one that starts with "-" is written ${missing[0]}=<value>)`);
141
+ if (words.length) parts.push(`unexpected argument${words.length > 1 ? "s" : ""} ${words.map((w) => JSON.stringify(w)).join(", ")} (pillar-directory takes only flags)`);
142
+ if (parts.length) return { ok: false, error: parts.join("; ") };
143
+
144
+ const emptyEnv = DIRECTORY_FLAGS.filter((s) => s.env && env[s.env] === "").map((s) => s.env);
145
+ if (emptyEnv.length) return { ok: false, error: `${emptyEnv.join(", ")} ${emptyEnv.length > 1 ? "are" : "is"} set but empty: unset ${emptyEnv.length > 1 ? "them" : "it"} or give a value` };
146
+
147
+ const values = {};
148
+ for (const s of DIRECTORY_FLAGS) {
149
+ const fromFlag = given[s.flag];
150
+ const fromEnv = s.env ? env[s.env] : undefined;
151
+ if (s.kind === "bool") { values[s.flag] = fromFlag === true; continue; }
152
+ if (s.kind === "string") { values[s.flag] = fromFlag ?? fromEnv ?? undefined; continue; }
153
+ const raw = fromFlag ?? fromEnv;
154
+ if (raw === undefined) { values[s.flag] = s.def; continue; }
155
+ const n = Number(raw);
156
+ if (!/^[0-9]+$/.test(raw) || n < s.min || n > s.max) {
157
+ const who = fromFlag !== undefined ? `--${s.flag}` : s.env;
158
+ return { ok: false, error: `${who} must be a whole number from ${s.min} to ${s.max}, not ${JSON.stringify(raw)}` };
159
+ }
160
+ values[s.flag] = n;
161
+ }
162
+
163
+ const peersRaw = values.peers ?? values.peer ?? "";
164
+ try { values.peerList = parsePeersArg(peersRaw); }
165
+ catch (e) {
166
+ const who = given.peers !== undefined || given.peer !== undefined ? "--peers" : "DIRECTORY_PEERS";
167
+ return { ok: false, error: `${who} must be ${e instanceof SyntaxError ? "a comma list of http(s) URLs or valid JSON" : e.message}` };
168
+ }
169
+ values.urlMap = null;
170
+ if (values["url-map"] !== undefined) {
171
+ let m;
172
+ try { m = JSON.parse(values["url-map"]); } catch { m = undefined; }
173
+ if (!m || typeof m !== "object" || Array.isArray(m)) return { ok: false, error: `${given["url-map"] !== undefined ? "--url-map" : "DIRECTORY_URL_MAP"} must be a JSON object` };
174
+ values.urlMap = m;
175
+ }
176
+ return { ok: true, values };
177
+ }
178
+
179
+ /** The effective limits, one line, values only (printed after "listening on"). */
180
+ export function formatDirectoryLimits(values) {
181
+ return DIRECTORY_FLAGS.filter((s) => s.kind === "int" && s.flag !== "port").map((s) => `--${s.flag} ${values[s.flag]}`).join(" ");
182
+ }
@@ -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 = ?") {
@@ -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,8 +42,18 @@ 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;
49
59
  /** Longest stretch a timed prune pass holds the event loop before it yields (V1 P2). */
@@ -51,7 +61,6 @@ export const PRUNE_SLICE_MS = 20;
51
61
 
52
62
  const yieldToEventLoop = () => new Promise((resolve) => setImmediate(resolve));
53
63
  export const PROJECTION_MAX_AGE_MS = 60_000;
54
- export const EVAL_MEMO_MAX_AGE_MS = PRUNE_INTERVAL_MS;
55
64
 
56
65
  const HEX128_RE = /^[0-9a-f]{128}$/;
57
66
  const NONCE_RE = /^[0-9a-f]{1,32}$/;
@@ -445,9 +454,11 @@ export class ListingStore {
445
454
  const nowStr = nowIso(now);
446
455
  const nowMs = Date.parse(nowStr);
447
456
  const lineages = [];
457
+ const pass = this.lineageStore ? this.lineageStore.beginVerifyPass() : 0;
448
458
  for (const lineage of this._listedLineages()) {
449
459
  if (this._pruneOne(lineage, nowStr, nowMs)) lineages.push(lineage);
450
460
  }
461
+ if (this.lineageStore) this.lineageStore.endVerifyPass(pass);
451
462
  return { pruned: lineages.length, lineages };
452
463
  }
453
464
 
@@ -456,19 +467,24 @@ export class ListingStore {
456
467
  * awaits `yieldFn` (setImmediate), so requests are answered during the pass.
457
468
  * Each row is re-read and judged inside one slice, so a write that lands
458
469
  * between slices is seen. `shouldStop()` ends the pass early (shutdown).
459
- * Returns { pruned, lineages, rows, slices, longestSliceMs }.
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).
460
473
  */
461
474
  async pruneExpiredTombstonesYielding({ now, sliceMs = PRUNE_SLICE_MS, yieldFn = yieldToEventLoop, shouldStop = () => false } = {}) {
462
475
  const nowStr = nowIso(now);
463
476
  const nowMs = Date.parse(nowStr);
464
477
  const lineages = [];
465
478
  const all = this._listedLineages();
479
+ const pass = this.lineageStore ? this.lineageStore.beginVerifyPass() : 0;
480
+ let walked = 0;
466
481
  let slices = 1;
467
482
  let longestSliceMs = 0;
468
483
  let sliceStart = performance.now();
469
484
  for (const lineage of all) {
470
485
  if (shouldStop()) break;
471
486
  if (this._pruneOne(lineage, nowStr, nowMs)) lineages.push(lineage);
487
+ walked++;
472
488
  const spent = performance.now() - sliceStart;
473
489
  let yieldNow = false;
474
490
  if (spent >= sliceMs) yieldNow = true; // @rule reg.prune-yields
@@ -480,7 +496,10 @@ export class ListingStore {
480
496
  }
481
497
  }
482
498
  longestSliceMs = Math.max(longestSliceMs, performance.now() - sliceStart);
483
- return { pruned: lineages.length, lineages, rows: all.length, slices, longestSliceMs: Math.round(longestSliceMs) };
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) };
484
503
  }
485
504
 
486
505
  _listedLineages() {
@@ -492,8 +511,8 @@ export class ListingStore {
492
511
  const row = this.getByLineage(lineage);
493
512
  if (!row) return false;
494
513
  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;
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;
497
516
  let deadSinceMs = null;
498
517
  if (evalRes?.tombstoned === true) {
499
518
  deadSinceMs = Date.parse(evalRes.tombstoneTs);
@@ -548,7 +567,7 @@ export class ListingStore {
548
567
  if (row.withdrawn === 1 || l.withdrawn === true) continue; // @rule reg.project-not-withdrawn
549
568
  if (this.hasOtherLineage(l.lineage, l.lineage) || this.hasOtherLineage(l.uuaid, l.lineage)) continue; // @rule reg.project-ambiguous-listing-store
550
569
  if (this.lineageStore.hasOtherLineage(l.lineage, l.lineage) || this.lineageStore.hasOtherLineage(l.uuaid, l.lineage)) continue; // @rule reg.project-ambiguous-lineage-store
551
- 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 });
552
571
  if (evalRes?.tombstoned === true) continue; // @rule reg.project-not-tombstoned
553
572
  if (evalRes !== null && ((evalRes.verdict !== "valid" && evalRes.verdict !== "recovered" && evalRes.verdict !== "pending-recovery") || evalRes.current !== l.uuaid)) continue; // @rule reg.project-lineage-current
554
573
  const hb = this.heartbeatStore ? this.heartbeatStore.getLatest(l.lineage) : null;
@@ -572,8 +591,15 @@ export class ListingStore {
572
591
  * slice runs before this returns; the rest run while the registry serves.
573
592
  * One pass at a time; a pass that throws is logged and the timer keeps
574
593
  * 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 }).
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.
577
603
  */
578
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 } = {}) {
579
605
  const runs = [];
@@ -584,9 +610,12 @@ export function startTombstonePruning(listingStore, { getNow = () => undefined,
584
610
  try {
585
611
  const r = await listingStore.pruneExpiredTombstonesYielding({ now: getNow(), sliceMs, shouldStop: () => stopped });
586
612
  const ms = Math.round(performance.now() - t0);
587
- runs.push({ pruned: r.pruned, rows: r.rows, ms, slices: r.slices, longestSliceMs: r.longestSliceMs });
613
+ runs.push({ pruned: r.pruned, rows: r.rows, walked: r.walked, ms, slices: r.slices, longestSliceMs: r.longestSliceMs });
588
614
  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)`);
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` : ""}`);
590
619
  return r;
591
620
  } catch (e) {
592
621
  if (!stopped) log(`[registry] tombstone prune failed: ${e?.message ?? e}`);
@@ -600,13 +629,19 @@ export function startTombstonePruning(listingStore, { getNow = () => undefined,
600
629
  if (!inFlight) inFlight = pass();
601
630
  return inFlight;
602
631
  };
603
- runNow();
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
+ });
604
638
  const timer = setIntervalFn(runNow, intervalMs);
605
639
  timer?.unref?.();
606
640
  return {
607
641
  stop: () => { stopped = true; clearIntervalFn(timer); },
608
642
  runNow,
609
643
  whenIdle: () => inFlight ?? Promise.resolve(null),
644
+ firstPass,
610
645
  runs,
611
646
  };
612
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.1";
55
+ export const STATS_VERDICT_TOOL = "pillar/2.7.3";
56
56
 
57
57
  /** Closed key set of `pillar-ttfa-report/1`. */
58
58
  export const TTFA_REPORT_KEYS = Object.freeze([
@@ -31,7 +31,7 @@ import {
31
31
  verifyStatsArtifact,
32
32
  } from "../registry/stats.mjs";
33
33
 
34
- export const VERIFY_CLI_TOOL = "pillar/2.7.1";
34
+ export const VERIFY_CLI_TOOL = "pillar/2.7.3";
35
35
  const TYPE_SET = new Set([...VERIFY_TYPES, TTFA_VERDICT_TYPE, REGISTRY_STATS_VERDICT_TYPE]);
36
36
 
37
37
  const VALUE_FLAGS = new Set([
@@ -289,6 +289,9 @@ export function verifyForm(rawArgs) {
289
289
  return live ? "uuaid" : "file";
290
290
  }
291
291
 
292
+ /** A pillar-verdict/1 object exitCodeFor can read. */
293
+ const isVerdict = (v) => typeof v === "object" && v !== null && typeof v.verdict === "string";
294
+
292
295
  /**
293
296
  * `pillar verify <uuaid>`: core resolve (fail-closed) and the lineage verdict
294
297
  * it carries. Exit as the file form: exitCodeFor(lineage verdict); 1 when the
@@ -300,8 +303,15 @@ export async function runVerifyUuaidCli(rawArgs, io = {}) {
300
303
  const live = await resolveLive(rawArgs, { cmdName: "verify", io });
301
304
  if (live.usage) return { exitCode: live.usage.exitCode, verdict: null };
302
305
  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");
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) {
305
315
  const report = { ok: false, form: "uuaid", query: uuaid, registry: registryUrl, reason, ...(error !== null ? { message: error } : {}), ...(result?.statusCode ? { statusCode: result.statusCode } : {}) };
306
316
  if (json) out(`${JSON.stringify(report)}\n`);
307
317
  else errOut(`not verified ${uuaid}: ${reason}${result?.statusCode ? ` (HTTP ${result.statusCode})` : ""}${error !== null ? ` (${error})` : ""} [live, ${registryUrl}]\n`);