@uuaid/pillar 2.7.3 → 2.8.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.
@@ -36,6 +36,11 @@ const COUNT_MAX = 1_000_000;
36
36
  const str = (flag, env) => ({ flag, env, kind: "string" });
37
37
  const bool = (flag) => ({ flag, env: null, kind: "bool" });
38
38
  const int = (flag, env, def, min, max) => ({ flag, env, kind: "int", def, min, max });
39
+ // A numeric test hook (2.8.0): checked exactly as an int (digits, in range;
40
+ // parseDirectoryArgs reads every kind but bool and string as a whole number),
41
+ // but not a limit, so it is not on the limits line. No default: unset is
42
+ // undefined.
43
+ const hook = (flag, env, min, max) => ({ flag, env, kind: "hook", def: undefined, min, max });
39
44
 
40
45
  /** Every flag pillar-directory reads, in --help order. Numeric ones carry their default and range. */
41
46
  export const DIRECTORY_FLAGS = Object.freeze([
@@ -50,12 +55,14 @@ export const DIRECTORY_FLAGS = Object.freeze([
50
55
  str("peer", null), // older spelling of --peers
51
56
  str("trusted-proxy", "DIRECTORY_TRUSTED_PROXIES"),
52
57
  int("probe-minutes", "DIRECTORY_PROBE_MINUTES", 10, 1, Math.floor(TIMER_MAX_MS / 60_000)),
58
+ str("fleet-relays", "DIRECTORY_FLEET_RELAYS"), // 2.8.0: relays this registry pins (a file); none by default
53
59
  bool("help"),
54
60
  str("protocol", "DIRECTORY_PROTOCOL"),
55
61
  bool("allow-private-urls"),
56
62
  str("url-map", "DIRECTORY_URL_MAP"),
57
63
  str("clock-file", null),
58
64
  int("stamp-bits", "DIRECTORY_STAMP_BITS", 18, 12, 24),
65
+ hook("probe-interval-ms", "DIRECTORY_PROBE_INTERVAL_MS", 100, TIMER_MAX_MS), // 2.8.0 test hook: overrides --probe-minutes
59
66
  int("max-new-lineages-per-hour", "DIRECTORY_MAX_NEW_LINEAGES_PER_HOUR", MAX_NEW_LINEAGES_PER_HOUR, 0, COUNT_MAX),
60
67
  int("max-listings-per-ip-per-hour", "DIRECTORY_MAX_LISTINGS_PER_IP_PER_HOUR", 60, 0, COUNT_MAX),
61
68
  int("max-lineage-posts-per-ip-per-hour", "DIRECTORY_MAX_LINEAGE_POSTS_PER_IP_PER_HOUR", 300, 0, COUNT_MAX),
@@ -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.3";
55
+ export const STATS_VERDICT_TOOL = "pillar/2.8.1";
56
56
 
57
57
  /** Closed key set of `pillar-ttfa-report/1`. */
58
58
  export const TTFA_REPORT_KEYS = Object.freeze([
@@ -0,0 +1,399 @@
1
+ /**
2
+ * CLI for continuity (2.8.0 Track B, DESIGN-continuity §6, §10):
3
+ * pillar continuity list|show|confirm|pin|forget|imports|check
4
+ * pillar lineage rotate ... [--no-notify] [--retired-grace DUR] (wraps the B1 rotate)
5
+ * pillar lineage notify [--to <contact>]...
6
+ * pillar lineage successor --old-home DIR [--no-notify]
7
+ */
8
+ import { existsSync, readFileSync } from "node:fs";
9
+ import { homedir } from "node:os";
10
+ import { join } from "node:path";
11
+ import { Keychain } from "../identity/keychain.mjs";
12
+ import { Mailbox } from "../mailbox/mailbox.mjs";
13
+ import { loadTrustPolicy } from "../identity/trust.mjs";
14
+ import { inspectFleetFile, loadFleetAddressBook, resolveRecipient } from "../address-book.mjs";
15
+ import { Pillar } from "../pillar.mjs";
16
+ import { verifyLineage } from "../vendor/pillar-core.mjs";
17
+ import {
18
+ ContinuityRefusalError, ContinuityStore, KIND_LINEAGE, KIND_SUCCESSOR, buildLineageNotice, buildSuccessorNotice,
19
+ checkHomes, confirmRoute, decideFor, forgetLineage, keysOf, pinFromLog, recoverRoute, repairStore, verifyEvidence,
20
+ } from "./continuity.mjs";
21
+ import { clearRotationIntent, findArchive, finishPendingRetirement, parseGrace, readImports, readRotationIntent, writeRetiredRecord, writeRotationIntent } from "./retired-import.mjs";
22
+ import { runLineageCli } from "./lineage-cli.mjs";
23
+ import { nowIsoSeconds } from "./wave-a.mjs";
24
+
25
+ const VALUE_FLAGS = new Set(["home", "head", "to", "log", "confirm", "now", "fleet", "carrier", "retired-grace", "old-home"]);
26
+ const BOOL_FLAGS = new Set(["json", "no-notify", "allow-insecure-loopback"]);
27
+
28
+ function parse(raw) {
29
+ const opts = { to: [] };
30
+ const pos = [];
31
+ const errors = [];
32
+ for (let i = 0; i < raw.length; i++) {
33
+ const t = raw[i];
34
+ if (!t.startsWith("--")) { pos.push(t); continue; }
35
+ const eq = t.indexOf("=");
36
+ const k = eq === -1 ? t.slice(2) : t.slice(2, eq);
37
+ if (BOOL_FLAGS.has(k)) { opts[k] = true; continue; }
38
+ if (!VALUE_FLAGS.has(k)) { errors.push(`unknown flag ${t}`); continue; }
39
+ const v = eq !== -1 ? t.slice(eq + 1) : raw[++i];
40
+ if (v === undefined) { errors.push(`--${k} requires a value`); continue; }
41
+ if (k === "to") opts.to.push(v); else opts[k] = v;
42
+ }
43
+ return { pos, opts, errors };
44
+ }
45
+
46
+ const homeOf = (opts) => opts.home || process.env.PILLAR_HOME || join(homedir(), ".pillar");
47
+ const fleetOf = (opts, home) => opts.fleet || join(home, "fleet.json");
48
+
49
+ function ioOf(io) {
50
+ return {
51
+ out: io.stdout ?? ((s) => process.stdout.write(s)),
52
+ err: io.stderr ?? ((s) => process.stderr.write(s)),
53
+ passphrase: io.passphrase ?? process.env.PILLAR_PASSPHRASE ?? "",
54
+ };
55
+ }
56
+
57
+ /** A contact name or a UUAID, as a UUAID. */
58
+ function resolveQueried(arg, home, opts) {
59
+ if (!arg) throw new ContinuityRefusalError("continuity-usage", "name a contact or a uuaid");
60
+ return resolveRecipient(arg, inspectFleetFile(fleetOf(opts, home))).uuaid;
61
+ }
62
+
63
+ /** A carrier-only Pillar for a home, with its fleet contacts loaded. */
64
+ async function openHomePillar(home, opts, passphrase) {
65
+ const kc = new Keychain(join(home, "keychain.json"));
66
+ kc.load({ passphrase });
67
+ let cfg = {};
68
+ try { cfg = JSON.parse(readFileSync(join(home, "config.json"), "utf8")); } catch { cfg = {}; }
69
+ const carriers = opts.carrier ? [opts.carrier] : (process.env.PILLAR_CARRIERS ? process.env.PILLAR_CARRIERS.split(",") : (cfg.carriers ?? []));
70
+ const p = new Pillar({
71
+ keychain: kc,
72
+ mailboxPath: join(home, "mailbox.db"),
73
+ home,
74
+ carriers,
75
+ enableLibp2p: false,
76
+ trust: loadTrustPolicy(home),
77
+ continuity: { passphrase },
78
+ });
79
+ await p.start();
80
+ loadFleetAddressBook(fleetOf(opts, home), p, { onProblem: null });
81
+ return { p, carriers };
82
+ }
83
+
84
+ /** Send one notice to each contact; two retries on 429. Never throws. */
85
+ async function sendNotices(p, contacts, kind, payload) {
86
+ const out = [];
87
+ for (const c of contacts) {
88
+ let last = null;
89
+ for (let attempt = 0; attempt < 3; attempt++) {
90
+ try {
91
+ const r = await p.send({ recipient: c.uuaid, recipientPublicKey: c.publicKey, kind, payload });
92
+ out.push({ to: c.uuaid, name: c.name ?? null, ok: true, envelope: r.envelope.id });
93
+ last = null;
94
+ break;
95
+ } catch (e) {
96
+ last = e;
97
+ if (e?.status !== 429) break;
98
+ await new Promise((res) => setTimeout(res, 250 * (attempt + 1)));
99
+ }
100
+ }
101
+ if (last) out.push({ to: c.uuaid, name: c.name ?? null, ok: false, error: last.message });
102
+ }
103
+ return out;
104
+ }
105
+
106
+ function fleetContacts(home, opts, selfUuaid, only = []) {
107
+ const info = inspectFleetFile(fleetOf(opts, home));
108
+ let list = info.entries.filter((e) => e.uuaid !== selfUuaid && typeof e.publicKey === "string");
109
+ if (only.length) {
110
+ const want = new Set(only.map((t) => resolveRecipient(t, info).uuaid));
111
+ list = list.filter((e) => want.has(e.uuaid));
112
+ }
113
+ return list;
114
+ }
115
+
116
+ /** This home's current key (public view; no passphrase needed). */
117
+ function currentKeyOf(home) {
118
+ const kc = join(home, "keychain.json");
119
+ if (existsSync(kc)) { try { return new Keychain(kc).publicView()?.uuaid ?? null; } catch { return null; } }
120
+ try { return JSON.parse(readFileSync(join(home, "identity", "agent-meta.json"), "utf8")).uuaid ?? null; } catch { return null; }
121
+ }
122
+
123
+ /** The main inbox's carrier cursors now: the retired key's inbox starts there. */
124
+ function carrierCursorsOf(home) {
125
+ let mb = null;
126
+ try { mb = new Mailbox(join(home, "mailbox.db")); return mb.getCarrierCursors?.() ?? {}; }
127
+ catch { return {}; }
128
+ finally { try { mb?.close(); } catch { /* closed */ } }
129
+ }
130
+
131
+ function readOwnLog(home) {
132
+ const events = JSON.parse(readFileSync(join(home, "lineage", "log.json"), "utf8"));
133
+ let receipts = [];
134
+ const rp = join(home, "lineage", "receipts.json");
135
+ if (existsSync(rp)) { try { receipts = JSON.parse(readFileSync(rp, "utf8")); } catch { receipts = []; } }
136
+ return { events, receipts: Array.isArray(receipts) ? receipts : [] };
137
+ }
138
+
139
+ // ── pillar lineage rotate|notify|successor ───────────────────────────────────
140
+
141
+ const LINEAGE_BOOL = new Set(["--json", "--no-witnesses", "--allow-insecure-loopback", "--generate", "--no-notify"]);
142
+
143
+ /** The lineage subcommand: the first positional that is not a flag's value. */
144
+ export function lineageSubOf(raw) {
145
+ for (let i = 0; i < raw.length; i++) {
146
+ const t = raw[i];
147
+ if (t.startsWith("-")) { if (!t.includes("=") && !LINEAGE_BOOL.has(t)) i++; continue; }
148
+ return t;
149
+ }
150
+ return undefined;
151
+ }
152
+
153
+ /**
154
+ * `pillar lineage ...` subcommands that continuity adds or wraps. Returns
155
+ * null when the subcommand is not one of them (the caller runs lineage-cli).
156
+ */
157
+ export async function runLineageContinuityCli(subRaw, io = {}) {
158
+ const sub = lineageSubOf(subRaw);
159
+ if (sub === "rotate") return rotateAndNotify(subRaw, io);
160
+ if (sub === "notify") return notifyCmd(subRaw, io);
161
+ if (sub === "successor") return successorCmd(subRaw, io);
162
+ return null;
163
+ }
164
+
165
+ async function rotateAndNotify(subRaw, io) {
166
+ const { out, err, passphrase } = ioOf(io);
167
+ const pass = [];
168
+ let noNotify = false;
169
+ let grace = undefined;
170
+ for (let i = 0; i < subRaw.length; i++) {
171
+ const t = subRaw[i];
172
+ if (t === "--no-notify") { noNotify = true; continue; }
173
+ if (t === "--retired-grace") { grace = subRaw[++i]; continue; }
174
+ if (t.startsWith("--retired-grace=")) { grace = t.slice("--retired-grace=".length); continue; }
175
+ pass.push(t);
176
+ }
177
+ let graceMs;
178
+ try { graceMs = parseGrace(grace ?? undefined); } catch (e) { err(`lineage rotate: ${e.message}\n`); return { exitCode: 64 }; }
179
+ const json = pass.includes("--json");
180
+ const homeIdx = pass.indexOf("--home");
181
+ const home = homeIdx !== -1 ? pass[homeIdx + 1] : (pass.find((t) => t.startsWith("--home="))?.slice(7) ?? homeOf({}));
182
+ // The retired key's import policy is written durably BEFORE the rotation, so a crash after it cannot
183
+ // leave the archive without its record (RedTeam b5cbee P2). If it cannot be written, nothing rotates.
184
+ const previousUuaid = currentKeyOf(home);
185
+ let intentErr = null;
186
+ if (previousUuaid) {
187
+ // An earlier rotation that crashed before its retired.json keeps its own policy: its record is
188
+ // written first, so this rotation's intent cannot replace it (RedTeam 1c5e7a P2).
189
+ let pendingErr = null;
190
+ try { finishPendingRetirement(home, previousUuaid); } catch (e) { pendingErr = e; } // @rule continuity-cli.finish-pending-call
191
+ if (pendingErr) { err(`lineage rotate: the previous rotation's retired-key policy cannot be read or recorded (${pendingErr.message}); check ${home}/continuity/rotation-intent.json; nothing was rotated\n`); return { exitCode: 1 }; } // @rule continuity-cli.finish-pending-before-rotate
192
+ try { writeRotationIntent(home, { previousUuaid, graceMs, cursors: carrierCursorsOf(home), at: nowIsoSeconds() }); } catch (e) { intentErr = e; }
193
+ }
194
+ if (intentErr) { err(`lineage rotate: cannot record the retired key's import policy (${intentErr.message}); nothing was rotated\n`); return { exitCode: 1 }; } // @rule continuity-cli.intent-before-rotate
195
+ let captured = "";
196
+ const res = await runLineageCli(pass, { ...io, stdout: (s) => { captured += s; }, stderr: err, passphrase });
197
+ if (res.exitCode !== 0 || !res.result) { if (currentKeyOf(home) === previousUuaid) clearRotationIntent(home); out(captured); return res; }
198
+ const r = res.result;
199
+ const extra = { notices: [] };
200
+ let p = null;
201
+ try {
202
+ const opened = await openHomePillar(home, {}, passphrase);
203
+ p = opened.p;
204
+ const archive = findArchive(home, r.previousUuaid);
205
+ if (archive) {
206
+ const intent = readRotationIntent(home);
207
+ const old = existsSync(join(archive, "keychain.json")) ? new Keychain(join(archive, "keychain.json")).publicView() : null;
208
+ const cursors = intent && !intent.invalid && intent.previousUuaid === r.previousUuaid ? intent.cursors : {};
209
+ const rec = writeRetiredRecord(archive, { uuaid: r.previousUuaid, publicKey: old?.publicKeyHex ?? null, retiredAt: r.event.ts, graceMs, cursors });
210
+ clearRotationIntent(home);
211
+ extra.retired = { uuaid: rec.uuaid, until: rec.until };
212
+ } else {
213
+ err(`warning: lineage rotate: no archive found for ${r.previousUuaid}; its inbox is not imported\n`);
214
+ }
215
+ if (!noNotify) {
216
+ if (!opened.carriers.length) err("warning: lineage rotate: no carrier configured; no contact was notified\n");
217
+ else {
218
+ const { events, receipts } = readOwnLog(home);
219
+ const payload = buildLineageNotice({ events, receipts, type: "rotation", now: r.event.ts });
220
+ extra.notices = await sendNotices(p, fleetContacts(home, {}, r.uuaid), KIND_LINEAGE, payload);
221
+ for (const n of extra.notices) if (!n.ok) err(`warning: lineage rotate: notice to ${n.name ?? n.to} failed: ${n.error}\n`);
222
+ }
223
+ }
224
+ } catch (e) {
225
+ err(`warning: lineage rotate: the rotation is done, but continuity follow-up failed: ${e.message}\n`);
226
+ } finally {
227
+ if (p) await p.stop().catch(() => {});
228
+ }
229
+ if (json) {
230
+ let obj = null;
231
+ try { obj = JSON.parse(captured); } catch { obj = null; }
232
+ out(obj ? `${JSON.stringify({ ...obj, ...extra })}\n` : captured);
233
+ } else {
234
+ out(captured);
235
+ if (extra.retired) out(`retired key ${extra.retired.uuaid}: its inbox is imported until ${extra.retired.until}\n`);
236
+ for (const n of extra.notices) out(`notice -> ${n.name ?? n.to}: ${n.ok ? "sent" : "failed"}\n`);
237
+ }
238
+ return { exitCode: 0, result: { ...r, ...extra } };
239
+ }
240
+
241
+ async function notifyCmd(subRaw, io) {
242
+ const { out, err, passphrase } = ioOf(io);
243
+ const { opts, errors } = parse(subRaw.filter((t) => t !== "notify"));
244
+ if (errors.length) { err(`lineage notify: ${errors[0]}\n`); return { exitCode: 64 }; }
245
+ const home = homeOf(opts);
246
+ let p = null;
247
+ try {
248
+ const opened = await openHomePillar(home, opts, passphrase);
249
+ p = opened.p;
250
+ if (!opened.carriers.length) { err("lineage notify: no carrier configured\n"); return { exitCode: 1 }; }
251
+ const { events, receipts } = readOwnLog(home);
252
+ const payload = buildLineageNotice({ events, receipts, type: "announce", now: opts.now ?? nowIsoSeconds() });
253
+ const notices = await sendNotices(p, fleetContacts(home, opts, p.uuaid, opts.to), KIND_LINEAGE, payload);
254
+ out(opts.json ? `${JSON.stringify({ head: payload.head, notices })}\n` : notices.map((n) => `notice -> ${n.name ?? n.to}: ${n.ok ? "sent" : `failed (${n.error})`}\n`).join(""));
255
+ return { exitCode: notices.every((n) => n.ok) ? 0 : 1 };
256
+ } catch (e) {
257
+ err(`lineage notify: ${e.message}\n`);
258
+ return { exitCode: 1 };
259
+ } finally {
260
+ if (p) await p.stop().catch(() => {});
261
+ }
262
+ }
263
+
264
+ async function successorCmd(subRaw, io) {
265
+ const { out, err, passphrase } = ioOf(io);
266
+ const { opts, errors } = parse(subRaw.filter((t) => t !== "successor"));
267
+ if (errors.length || !opts["old-home"]) { err(`lineage successor: ${errors[0] ?? "--old-home DIR is required"}\n`); return { exitCode: 64 }; }
268
+ const home = homeOf(opts);
269
+ const oldHome = opts["old-home"];
270
+ const now = opts.now ?? nowIsoSeconds();
271
+ const oldKc = new Keychain(join(oldHome, "keychain.json"));
272
+ try { oldKc.load({ passphrase }); } catch (e) { err(`lineage successor: cannot load ${oldHome}/keychain.json (${e.message})\n`); return { exitCode: 1 }; }
273
+ const from = oldKc._identity.uuaid;
274
+ if (existsSync(join(oldHome, "lineage", "log.json"))) {
275
+ const old = readOwnLog(oldHome);
276
+ const v = verifyEvidence(old.events, old.receipts, now);
277
+ if (v.facts?.current !== from) { err(`lineage successor: ${from} is not the current key of its own lineage (${v.verdict}); a retired key cannot name a successor\n`); return { exitCode: 1 }; } // @rule continuity-cli.successor-from-current
278
+ }
279
+ let own = readOwnLog(home);
280
+ const bound = (verifyLineage(own.receipts.length ? { v: "uuaid-lineage-log/1", events: own.events, receipts: own.receipts } : own.events, { now }).facts?.boundLegacy ?? []).includes(from);
281
+ if (!bound) {
282
+ let bindOut = "";
283
+ const b = await runLineageCli(["bind", "--home", home, "--old-home", oldHome, "--now", now, "--json"], { stdout: (s) => { bindOut += s; }, stderr: err, passphrase });
284
+ if (b.exitCode !== 0) { err("lineage successor: bind failed; nothing was sent\n"); return { exitCode: b.exitCode }; }
285
+ own = readOwnLog(home);
286
+ }
287
+ const payload = buildSuccessorNotice({ from, events: own.events, receipts: own.receipts, now });
288
+ let notices = [];
289
+ if (!opts["no-notify"]) {
290
+ let p = null;
291
+ try {
292
+ const opened = await openHomePillar(oldHome, opts, passphrase);
293
+ p = opened.p;
294
+ if (!opened.carriers.length) err("warning: lineage successor: the old home has no carrier; no contact was notified\n");
295
+ else notices = await sendNotices(p, fleetContacts(oldHome, opts, from), KIND_SUCCESSOR, payload);
296
+ } finally {
297
+ if (p) await p.stop().catch(() => {});
298
+ }
299
+ }
300
+ out(opts.json ? `${JSON.stringify({ from, successor: payload.successor.current, lineage: payload.successor.lineage, head: payload.successor.head, notices })}\n`
301
+ : `successor of ${from}: ${payload.successor.current} (lineage ${payload.successor.lineage}, head ${payload.successor.head})\n${notices.map((n) => `notice -> ${n.name ?? n.to}: ${n.ok ? "sent" : `failed (${n.error})`}\n`).join("")}`);
302
+ return { exitCode: 0 };
303
+ }
304
+
305
+ // ── pillar continuity ... ────────────────────────────────────────────────────
306
+
307
+ const CONTINUITY_USAGE = "usage: pillar continuity <list|show <contact>|confirm <contact> --head sha256:... --to <uuaid>|recover <contact> --log FILE --head sha256:... --to <uuaid>|pin --log FILE|forget <lineage> --confirm <lineage>|imports|check <contact>|repair> [--home DIR] [--json]";
308
+
309
+ export async function runContinuityCli(rawArgs, io = {}) {
310
+ const { out, err, passphrase } = ioOf(io);
311
+ const { pos, opts, errors } = parse(rawArgs);
312
+ if (errors.length) { err(`continuity: ${errors[0]}\n`); return { exitCode: 64 }; }
313
+ const [sub, arg] = pos;
314
+ const home = homeOf(opts);
315
+ const now = opts.now ?? nowIsoSeconds();
316
+ const store = new ContinuityStore(home);
317
+ const show = (obj, text) => out(opts.json ? `${JSON.stringify(obj)}\n` : text);
318
+ try {
319
+ if (sub === "list") {
320
+ const s = store.read();
321
+ const rows = Object.entries(s.lineages).map(([lineage, rec]) => {
322
+ const v = verifyEvidence(rec.events, rec.receipts, now);
323
+ const keys = [...keysOf(rec.events).keys()];
324
+ return { lineage, verdict: v.verdict, current: v.facts?.current ?? null, head: v.facts?.head ?? null, pin: rec.pin, routes: keys.filter((k) => k !== v.facts?.current).map((k) => ({ key: k, ...pick(decideFor(s, k, now)) })) };
325
+ });
326
+ const succ = Object.keys(s.successors).map((from) => ({ from, ...pick(decideFor(s, from, now)) }));
327
+ show({ lineages: rows, successors: succ }, [...rows.map((r) => `${r.lineage}: ${r.verdict}, current ${r.current}, head ${r.head}, pin ${r.pin ? (r.pin.firm ? "firm" : "provisional") : "none"}\n${r.routes.map((x) => ` ${x.key} -> ${x.state}${x.reason ? ` (${x.reason})` : ""}${x.to ? ` to ${x.to}` : ""}\n`).join("")}`), ...succ.map((x) => `successor of ${x.from} -> ${x.state}${x.to ? ` to ${x.to}` : ""}\n`)].join("") || "no continuity evidence\n");
328
+ return { exitCode: 0 };
329
+ }
330
+ if (sub === "show" || sub === "check") {
331
+ const q = resolveQueried(arg, home, opts);
332
+ const checks = [];
333
+ if (sub === "check") {
334
+ for (const [lin, rec] of Object.entries(store.read().lineages)) {
335
+ if (!keysOf(rec.events).has(q)) continue;
336
+ const c = await checkHomes(store, lin, { now, allowInsecureLoopback: opts["allow-insecure-loopback"] === true });
337
+ checks.push({ lineage: lin, ok: c.ok, count: c.count ?? 0, need: c.need ?? 0, disagree: c.disagree ?? 0, stale: c.stale ?? 0, failed: c.failed ?? 0, reason: c.reason ?? null });
338
+ }
339
+ }
340
+ // A verified disagreement is evidence of another state; a failed home is only unreachable or unusable.
341
+ const homesText = checks.map((c) => `\n homes of ${c.lineage}: ${c.count}/${c.need} agree, ${c.disagree} disagree (verified, vouched by the home), ${c.stale} behind, ${c.failed} failed (no usable answer)${c.reason ? ` - ${c.reason}` : ""}`).join("");
342
+ const d = decideFor(store.read(), q, now);
343
+ const claimed = d.state === "pending-confirm" ? " (claimed by the notice; not verified)" : "";
344
+ const next = d.state === "pending-confirm"
345
+ ? `\n ask ${arg} over another channel (not pillar) for its new uuaid and lineage head. Only if they match, run:\n pillar continuity confirm ${arg} --head <head they gave you> --to <uuaid they gave you>`
346
+ : d.state === "suspended" ? "\n the evidence conflicts: get the contact's lineage log over another channel and run pillar continuity recover" : "";
347
+ show({ queried: q, ...d, ...(sub === "check" ? { homeChecks: checks } : {}) }, `${q}: ${d.state}${d.reason ? ` (${d.reason})` : ""}${d.to ? `\n to: ${d.to}${claimed}` : ""}${d.head ? `\n head: ${d.head}${claimed}` : ""}${homesText}${next}\n`);
348
+ return { exitCode: 0 };
349
+ }
350
+ if (sub === "confirm") {
351
+ const q = resolveQueried(arg, home, opts);
352
+ const d = confirmRoute(store, { q, head: opts.head, to: opts.to[0], now });
353
+ show({ queried: q, ...d }, `${q}: ${d.state}${d.to ? ` -> ${d.to}` : ""}\n`);
354
+ return { exitCode: d.state === "active" ? 0 : 1 };
355
+ }
356
+ if (sub === "pin") {
357
+ if (!opts.log) { err(`${CONTINUITY_USAGE}\n`); return { exitCode: 64 }; }
358
+ const r = pinFromLog(store, { log: JSON.parse(readFileSync(opts.log, "utf8")), now });
359
+ show(r, `pinned ${r.lineage} at ${r.head} (current ${r.current})\n`);
360
+ return { exitCode: 0 };
361
+ }
362
+ if (sub === "forget") {
363
+ if (!arg || opts.confirm !== arg) { err("continuity forget: --confirm <lineage> must repeat the lineage\n"); return { exitCode: 64 }; } // @rule continuity-cli.forget-confirm
364
+ const removed = forgetLineage(store, arg);
365
+ show({ lineage: arg, removed }, removed ? `forgot ${arg}. Its retired and forked keys stay held: a send to them is refused until pillar continuity recover selects a verified route.\n` : `nothing stored for ${arg}\n`);
366
+ return { exitCode: removed ? 0 : 1 };
367
+ }
368
+ if (sub === "recover") {
369
+ const q = resolveQueried(arg, home, opts);
370
+ if (!opts.log || !opts.head || !opts.to[0]) { err(`${CONTINUITY_USAGE}\n`); return { exitCode: 64 }; }
371
+ const d = recoverRoute(store, { q, log: JSON.parse(readFileSync(opts.log, "utf8")), head: opts.head, to: opts.to[0], now });
372
+ show({ queried: q, ...d }, `${q}: ${d.state}${d.to ? ` -> ${d.to}` : ""} (the route you checked over another channel, from ${opts.log})\n`);
373
+ return { exitCode: d.state === "active" ? 0 : 1 };
374
+ }
375
+ if (sub === "repair") {
376
+ const r = repairStore(store, { now });
377
+ show(r, r.repaired
378
+ ? `moved the unreadable store to ${r.movedTo} and started an empty one. Confirmed and recovered routes are gone; keys that were retired or forked stay held (continuity/holds.json), so a send to them is refused until pillar continuity recover. Re-pin or re-confirm your contacts.\n`
379
+ : "the continuity store reads fine; nothing to repair\n");
380
+ return { exitCode: 0 };
381
+ }
382
+ if (sub === "imports") {
383
+ const rows = readImports(home, { passphrase });
384
+ show({ imports: rows }, rows.map((r) => `${r.at ?? "?"} ${r.sender} -> retired ${r.recipient} [${r.kind}] ${r.readable ? JSON.stringify(r.payload) : "(unreadable)"}\n`).join("") || "no imported mail\n");
385
+ return { exitCode: 0 };
386
+ }
387
+ err(`${CONTINUITY_USAGE}\n`);
388
+ return { exitCode: 64 };
389
+ } catch (e) {
390
+ err(`continuity ${sub ?? ""}: ${e.code ? `${e.message}${e.fix ? ` (${e.fix})` : ""}` : e.message}\n`);
391
+ return { exitCode: 1, error: e };
392
+ }
393
+ }
394
+
395
+ function pick(d) {
396
+ return { state: d.state, ...(d.reason ? { reason: d.reason } : {}), ...(d.to ? { to: d.to } : {}), ...(d.head ? { head: d.head } : {}), ...(d.via ? { via: d.via } : {}) };
397
+ }
398
+
399
+ export { CONTINUITY_USAGE };