@uuaid/pillar 2.6.1 → 2.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/README.md +325 -7
  2. package/bin/carrier.mjs +21 -0
  3. package/bin/pillar-ask.mjs +4 -1
  4. package/bin/pillar-blob.mjs +6 -0
  5. package/bin/pillar-directory.mjs +282 -16
  6. package/bin/pillar-escrow.mjs +4 -1
  7. package/bin/pillar-group-v2.mjs +6 -0
  8. package/bin/pillar-notify.mjs +13 -0
  9. package/bin/pillar-responder.mjs +266 -23
  10. package/bin/pillar.mjs +512 -257
  11. package/package.json +17 -25
  12. package/src/cli-help.mjs +23 -0
  13. package/src/group-v2-cli.mjs +1 -1
  14. package/src/identity/trust.mjs +72 -6
  15. package/src/mailbox/mailbox.mjs +313 -12
  16. package/src/net/carrier-server.mjs +34 -2
  17. package/src/net/refusals.mjs +2 -0
  18. package/src/net/seed-registry.mjs +2 -1
  19. package/src/net/transport.mjs +320 -91
  20. package/src/node-check.mjs +29 -8
  21. package/src/notify-events.mjs +148 -0
  22. package/src/notify-log.mjs +124 -0
  23. package/src/notify-runner.mjs +372 -0
  24. package/src/notify-store.mjs +736 -0
  25. package/src/notify.mjs +350 -0
  26. package/src/pillar.mjs +382 -27
  27. package/src/readers.mjs +2 -2
  28. package/src/registry/federation.mjs +3056 -0
  29. package/src/registry/gossip.mjs +294 -0
  30. package/src/registry/heartbeats.mjs +205 -0
  31. package/src/registry/lineage-verifier.mjs +972 -0
  32. package/src/registry/lineage.mjs +984 -0
  33. package/src/registry/listings.mjs +612 -0
  34. package/src/registry/resolve.mjs +376 -0
  35. package/src/registry/stats.mjs +508 -0
  36. package/src/sqlite-loader.mjs +40 -0
  37. package/src/vendor/pillar-core.mjs +22 -0
  38. package/src/vendor/uuaid-soul.mjs +2246 -0
  39. package/src/vnext/a6b-common.mjs +270 -0
  40. package/src/vnext/b1-cli.mjs +970 -0
  41. package/src/vnext/card-cli.mjs +370 -0
  42. package/src/vnext/greeter-operator.mjs +160 -0
  43. package/src/vnext/greeter-suggest.mjs +318 -0
  44. package/src/vnext/greeter.mjs +571 -0
  45. package/src/vnext/homes.mjs +48 -0
  46. package/src/vnext/init-cli.mjs +489 -0
  47. package/src/vnext/intro-cli.mjs +81 -0
  48. package/src/vnext/json-dir-mailbox.mjs +304 -0
  49. package/src/vnext/jsonl-mailbox.mjs +1132 -0
  50. package/src/vnext/knock-answer.mjs +162 -0
  51. package/src/vnext/knock-cli.mjs +520 -0
  52. package/src/vnext/knock-lane.mjs +312 -0
  53. package/src/vnext/knock-responder.mjs +344 -0
  54. package/src/vnext/lineage-cli.mjs +653 -0
  55. package/src/vnext/listing-cli.mjs +323 -0
  56. package/src/vnext/resolve-cli.mjs +104 -0
  57. package/src/vnext/soul-cli.mjs +666 -0
  58. package/src/vnext/verify-cli.mjs +333 -0
  59. package/src/vnext/w4-redirect.mjs +178 -0
  60. package/src/vnext/wave-a.mjs +193 -0
  61. package/src/vnext/witness-cli.mjs +547 -0
@@ -0,0 +1,666 @@
1
+ /**
2
+ * `pillar soul` CLI verbs & SOUL-1 responder helpers for `@uuaid/pillar` 2.7.0.
3
+ *
4
+ * Bridges Pillar homes (`keychain.json` and vNext JSON-dir `identity/agent.seed` +
5
+ * `lineage/log.json`) with `@uuaid/soul` (`../vendor/uuaid-soul.mjs`).
6
+ */
7
+ import { appendFileSync, existsSync, mkdirSync, readFileSync, readdirSync, unlinkSync } from "node:fs";
8
+ import { join } from "node:path";
9
+ import * as S from "../vendor/uuaid-soul.mjs";
10
+ import {
11
+ DEFAULT_CARD_CARRIER,
12
+ DEFAULT_CARD_HOME,
13
+ DEFAULT_STAMP_BITS,
14
+ } from "../vendor/pillar-core.mjs";
15
+ import {
16
+ HEX64_RE,
17
+ failCli,
18
+ isHttpsUrl,
19
+ loadHomeCard,
20
+ loadHomeConfig,
21
+ loadHomeIdentity,
22
+ loadHomeLineage,
23
+ parseDecimalInt,
24
+ parseStrictFlags,
25
+ resolveCarriers,
26
+ resolveHome,
27
+ } from "./a6b-common.mjs";
28
+ import {
29
+ CARD_KEY,
30
+ isStrictIsoDateTime,
31
+ nowIsoSeconds,
32
+ readRecoverySheetWords,
33
+ writeFileAtomic,
34
+ } from "./wave-a.mjs";
35
+
36
+ const SOUL_SUBCOMMANDS = new Set([
37
+ "init",
38
+ "sign",
39
+ "commit",
40
+ "ratify",
41
+ "contest",
42
+ "show",
43
+ "verify",
44
+ "refuse",
45
+ "dissent",
46
+ "guardians",
47
+ "templates",
48
+ ]);
49
+
50
+ const ROLES = new Set(["subject", "subject-next", "guardian", "reviewer"]);
51
+ const GROUNDS = new Set(S.REFUSAL_GROUNDS);
52
+ const RESPONDER_OPS = new Set(["card.get", "attest.deliver", "review.request", "checkpoint.deposit", "checkpoint.fetch"]);
53
+ const MAX_DEPOSIT_BLOBS = 16;
54
+ const MAX_BLOB_CHARS = S.DEFAULT_MAX_BLOB_CHARS;
55
+
56
+ function soulPaths(home) {
57
+ const dir = join(home, "soul");
58
+ return {
59
+ dir,
60
+ chain: join(dir, "chain.jsonl"),
61
+ pending: join(dir, "pending.json"),
62
+ attestations: join(dir, "attestations.jsonl"),
63
+ refusals: join(dir, "refusals.jsonl"),
64
+ persona: join(dir, "persona.md"),
65
+ card: join(dir, "card.json"),
66
+ checkpoints: join(dir, "checkpoints"),
67
+ deposits: join(dir, "deposits"),
68
+ reviewQueue: join(dir, "review-requests.jsonl"),
69
+ };
70
+ }
71
+
72
+ function readJsonLinesFile(filePath) {
73
+ if (!existsSync(filePath)) return [];
74
+ return readFileSync(filePath, "utf8")
75
+ .split("\n")
76
+ .map((l) => l.trim())
77
+ .filter(Boolean)
78
+ .map((l) => JSON.parse(l));
79
+ }
80
+
81
+ export function loadHomeSoulCard(home) {
82
+ const p = soulPaths(home).card;
83
+ if (!existsSync(p)) return null;
84
+ try {
85
+ const parsed = JSON.parse(readFileSync(p, "utf8"));
86
+ if (!parsed || typeof parsed !== "object" || parsed.v !== S.CARD_V) return null; // @rule soul-cli.soul-card-v
87
+ return parsed;
88
+ } catch {
89
+ return null;
90
+ }
91
+ }
92
+
93
+ function resolveSubjectForHome(home, homeId) {
94
+ const lin = loadHomeLineage(home);
95
+ if (lin.exists && typeof lin.lineage === "string") return { subject: lin.lineage, lin };
96
+ return { subject: homeId.uuaid, lin };
97
+ }
98
+
99
+ function buildExtraResolveKeys(opts) {
100
+ const extra = {};
101
+ for (const raw of opts["bind-key"] ?? []) {
102
+ const eq = raw.indexOf("=");
103
+ if (eq <= 0 || eq === raw.length - 1) return { ok: false, error: `soul: --bind-key expects <uuaid>=<64hex>, got "${raw}"` }; // @rule soul-cli.bind-key-shape
104
+ const u = raw.slice(0, eq);
105
+ const pub = raw.slice(eq + 1).toLowerCase();
106
+ extra[u] = [...(extra[u] ?? []), pub];
107
+ }
108
+ const iaasoPub = opts["iaaso-pubkey"];
109
+ try {
110
+ const fn = S.createGuardianKeyResolver({
111
+ ...(iaasoPub !== undefined ? { iaasoPublicKey: String(iaasoPub).toLowerCase() } : {}),
112
+ ...(opts["iaaso-uuaid"] !== undefined ? { iaasoUuaid: opts["iaaso-uuaid"] } : {}),
113
+ extra,
114
+ });
115
+ return { ok: true, resolveKeys: fn };
116
+ } catch (e) {
117
+ return { ok: false, error: `soul: ${e.message}` };
118
+ }
119
+ }
120
+
121
+ function syncCardsAfterCommit(home, homeId, headDoc, soulChain, lin, { resolveKeys, now }) {
122
+ const paths = soulPaths(home);
123
+ const attestations = readJsonLinesFile(paths.attestations);
124
+ const cfg = loadHomeConfig(home);
125
+ let existingCard = null;
126
+ try {
127
+ existingCard = loadHomeCard(home);
128
+ } catch {
129
+ existingCard = null;
130
+ }
131
+ const httpsCarriers = resolveCarriers([], cfg).filter((c) => isHttpsUrl(c));
132
+ const carriers =
133
+ Array.isArray(existingCard?.carriers) && existingCard.carriers.length > 0
134
+ ? existingCard.carriers
135
+ : httpsCarriers.length > 0
136
+ ? httpsCarriers
137
+ : [DEFAULT_CARD_CARRIER];
138
+ const homes =
139
+ Array.isArray(existingCard?.homes) && existingCard.homes.length > 0
140
+ ? existingCard.homes
141
+ : [DEFAULT_CARD_HOME];
142
+ const knock = existingCard?.knock ?? { pow: DEFAULT_STAMP_BITS };
143
+
144
+ const { vnextCard, soulCard } = S.buildVnextCardWithSoul({
145
+ signer: homeId.coreId,
146
+ soulHead: headDoc,
147
+ soulChain,
148
+ lineageLog: lin.exists ? lin.log : null,
149
+ cardOptions: {
150
+ name: existingCard?.name ?? headDoc.core.name,
151
+ ...(existingCard?.about ? { about: existingCard.about } : {}),
152
+ does: existingCard?.does ?? [],
153
+ wants: existingCard?.wants ?? [],
154
+ carriers,
155
+ homes,
156
+ knock,
157
+ ...(Array.isArray(existingCard?.languages) ? { languages: existingCard.languages } : {}),
158
+ ...(Array.isArray(existingCard?.doors) ? { doors: existingCard.doors } : {}),
159
+ ...(Array.isArray(existingCard?.interfaces) ? { interfaces: existingCard.interfaces } : {}),
160
+ namespace: homeId.namespace,
161
+ },
162
+ attestations,
163
+ resolveKeys,
164
+ now,
165
+ });
166
+
167
+ writeFileAtomic(paths.card, `${JSON.stringify(soulCard, null, 2)}\n`, 0o600);
168
+ writeFileAtomic(join(home, CARD_KEY), `${JSON.stringify(vnextCard, null, 2)}\n`, 0o600);
169
+ return { soulCard, vnextCard };
170
+ }
171
+
172
+ /**
173
+ * Handle an inbound decrypted `soul/1` request payload inside `pillar-responder`
174
+ * without ever spawning a shell hook on untrusted text (T4.7).
175
+ */
176
+ export function handleResponderSoulRequest({
177
+ home,
178
+ homeId,
179
+ sender,
180
+ payload,
181
+ custodian = false,
182
+ resolveKeys,
183
+ }) {
184
+ const s = payload?.soul;
185
+ if (!s || typeof s !== "object" || s.v !== S.SOUL_PAYLOAD_V) return null; // @rule soul-cli.responder-payload-v
186
+ if (!RESPONDER_OPS.has(s.op)) return { v: S.SOUL_PAYLOAD_V, op: "error", reason: "unknown_op" }; // @rule soul-cli.responder-unknown-op
187
+ const effResolveKeys = resolveKeys ?? S.createGuardianKeyResolver();
188
+ const paths = soulPaths(home);
189
+ const chain = readJsonLinesFile(paths.chain);
190
+ const head = chain[chain.length - 1] ?? null;
191
+
192
+ switch (s.op) {
193
+ case "card.get": {
194
+ if (!head) return { v: S.SOUL_PAYLOAD_V, op: "error", reason: "no_soul" }; // @rule soul-cli.responder-no-soul
195
+ const attestations = readJsonLinesFile(paths.attestations);
196
+ const card = S.buildCard(
197
+ head,
198
+ { uuaid: head.subject, publicKeyHex: homeId.publicKeyHex, seedHex: homeId.seedHex },
199
+ { chain, attestations, resolveKeys: effResolveKeys },
200
+ );
201
+ return { v: S.SOUL_PAYLOAD_V, op: "card", card };
202
+ }
203
+ case "attest.deliver": {
204
+ if (!head) return { v: S.SOUL_PAYLOAD_V, op: "attest.ack", accepted: false, reason: "no_soul" };
205
+ const a = s.attestation;
206
+ const ok = S.verifyAttestation(a, { resolveKeys: effResolveKeys });
207
+ if (!ok.ok || a.subject !== head.subject || a.issuer !== sender) return { v: S.SOUL_PAYLOAD_V, op: "attest.ack", accepted: false, reason: ok.reason ?? "issuer_or_subject_mismatch" }; // @rule soul-cli.responder-attest-verify
208
+ mkdirSync(paths.dir, { recursive: true, mode: 0o700 });
209
+ appendFileSync(paths.attestations, `${JSON.stringify(a)}\n`, { mode: 0o600 });
210
+ return { v: S.SOUL_PAYLOAD_V, op: "attest.ack", accepted: true };
211
+ }
212
+ case "review.request": {
213
+ mkdirSync(paths.dir, { recursive: true, mode: 0o700 });
214
+ appendFileSync(
215
+ paths.reviewQueue,
216
+ `${JSON.stringify({ receivedAt: nowIsoSeconds(), from: sender, version: s.version ?? null })}\n`,
217
+ { mode: 0o600 },
218
+ );
219
+ return { v: S.SOUL_PAYLOAD_V, op: "review.queued" };
220
+ }
221
+ case "checkpoint.deposit": {
222
+ if (!custodian) return { v: S.SOUL_PAYLOAD_V, op: "checkpoint.receipt", accepted: false, reason: "not_a_custodian" }; // @rule soul-cli.responder-custodian-gate
223
+ const blobLen =
224
+ s.blob === undefined || s.blob === null
225
+ ? 0
226
+ : typeof s.blob === "string"
227
+ ? s.blob.length
228
+ : (JSON.stringify(s.blob)?.length ?? Infinity);
229
+ if (blobLen > MAX_BLOB_CHARS) return { v: S.SOUL_PAYLOAD_V, op: "checkpoint.receipt", accepted: false, reason: "blob_too_large" }; // @rule soul-cli.responder-blob-cap
230
+ const cp = s.checkpoint;
231
+ if (cp?.subject !== sender || !Array.isArray(s.chain)) return { v: S.SOUL_PAYLOAD_V, op: "checkpoint.receipt", accepted: false, reason: "checkpoint_subject_mismatch" }; // @rule soul-cli.responder-cp-subject
232
+ const vr = S.verifyCheckpoint(cp, s.chain, { resolveKeys: effResolveKeys });
233
+ if (!vr.ok) return { v: S.SOUL_PAYLOAD_V, op: "checkpoint.receipt", accepted: false, reason: vr.reason }; // @rule soul-cli.responder-cp-verify
234
+ const rawReceipt = S.custodyReceipt(
235
+ { uuaid: homeId.uuaid, publicKeyHex: homeId.publicKeyHex, seedHex: homeId.seedHex },
236
+ cp,
237
+ { location: homeId.uuaid },
238
+ );
239
+ const receipt = JSON.parse(JSON.stringify(rawReceipt));
240
+ const safeKey = Buffer.from(sender, "utf8").toString("hex");
241
+ const subjDir = join(paths.deposits, safeKey);
242
+ mkdirSync(subjDir, { recursive: true, mode: 0o700 });
243
+ const existing = readdirSync(subjDir).filter((f) => f.endsWith(".json")).sort();
244
+ const recordPath = join(
245
+ subjDir,
246
+ `dep-${String(Date.now()).padStart(14, "0")}-${String(existing.length + 1).padStart(4, "0")}.json`,
247
+ );
248
+ writeFileAtomic(recordPath, `${JSON.stringify({ checkpoint: cp, blob: s.blob ?? null, chain: s.chain, receipt })}\n`, 0o600);
249
+ while (existing.length >= MAX_DEPOSIT_BLOBS) {
250
+ const oldest = existing.shift();
251
+ try {
252
+ unlinkSync(join(subjDir, oldest));
253
+ } catch {
254
+ // ignore concurrent unlink
255
+ }
256
+ }
257
+ return { v: S.SOUL_PAYLOAD_V, op: "checkpoint.receipt", accepted: true, receipt };
258
+ }
259
+ case "checkpoint.fetch":
260
+ default: {
261
+ if (s.subject !== undefined && s.subject !== sender) return { v: S.SOUL_PAYLOAD_V, op: "checkpoint.restore", found: false, reason: "checkpoint_subject_mismatch" }; // @rule soul-cli.responder-fetch-subject
262
+ const safeKey = Buffer.from(sender, "utf8").toString("hex");
263
+ const subjDir = join(paths.deposits, safeKey);
264
+ if (!existsSync(subjDir)) {
265
+ return { v: S.SOUL_PAYLOAD_V, op: "checkpoint.restore", found: false };
266
+ }
267
+ const files = readdirSync(subjDir).filter((f) => f.endsWith(".json")).sort();
268
+ if (!files.length) {
269
+ return { v: S.SOUL_PAYLOAD_V, op: "checkpoint.restore", found: false };
270
+ }
271
+ const last = JSON.parse(readFileSync(join(subjDir, files[files.length - 1]), "utf8"));
272
+ return {
273
+ v: S.SOUL_PAYLOAD_V,
274
+ op: "checkpoint.restore",
275
+ found: true,
276
+ checkpoint: last.checkpoint,
277
+ blob: last.blob,
278
+ chain: last.chain,
279
+ };
280
+ }
281
+ }
282
+ }
283
+
284
+ /**
285
+ * Execute `pillar soul <subcommand>` with injectable I/O streams.
286
+ */
287
+ export async function runSoulCli(rawArgs, io = {}) {
288
+ const out = io.stdout ?? ((s) => process.stdout.write(s));
289
+ const errOut = io.stderr ?? ((s) => process.stderr.write(s));
290
+ const passphrase = io.passphrase ?? process.env.PILLAR_PASSPHRASE ?? "";
291
+
292
+ const parsed = parseStrictFlags(rawArgs, {
293
+ boolFlags: new Set([
294
+ "json",
295
+ "persona",
296
+ "card",
297
+ "session-gate",
298
+ "allow-dissent",
299
+ "institutional-guardians",
300
+ ]),
301
+ valueFlags: new Set([
302
+ "home",
303
+ "name",
304
+ "template",
305
+ "vocation",
306
+ "role",
307
+ "principal",
308
+ "threshold",
309
+ "next-key",
310
+ "recovery-sheet",
311
+ "recovery-sheet-file",
312
+ "pending",
313
+ "out",
314
+ "argument",
315
+ "request-hash",
316
+ "grounds",
317
+ "text",
318
+ "from",
319
+ "summary",
320
+ "about",
321
+ "iaaso-pubkey",
322
+ "iaaso-uuaid",
323
+ "now",
324
+ ]),
325
+ repeatValueFlags: new Set(["guardian", "var", "vow", "red-line", "bind-key"]),
326
+ cmdName: "soul",
327
+ });
328
+ if (!parsed.ok) return failCli(errOut, parsed.error, parsed.exitCode);
329
+
330
+ const { positionals, opts } = parsed;
331
+ const sub = positionals[0];
332
+ if (!sub || !SOUL_SUBCOMMANDS.has(sub)) return failCli(errOut, `soul: expected subcommand (${[...SOUL_SUBCOMMANDS].join("|")})${sub ? `, got "${sub}"` : ""}`, 64); // @rule soul-cli.subcommand-known
333
+ if (positionals.length > 1) return failCli(errOut, `soul ${sub}: unexpected positional argument "${positionals[1]}"`, 64); // @rule soul-cli.no-extra-args
334
+
335
+ if (sub === "guardians") {
336
+ out(`${JSON.stringify(S.GUARDIAN_ORGS, null, opts.json ? 0 : 2)}\n`);
337
+ return { exitCode: 0, guardians: S.GUARDIAN_ORGS };
338
+ }
339
+ if (sub === "templates") {
340
+ const summary = Object.fromEntries(
341
+ Object.entries(S.TEMPLATES).map(([k, t]) => [k, { role: t.role, vocation: t.vocation }]),
342
+ );
343
+ out(`${JSON.stringify(summary, null, opts.json ? 0 : 2)}\n`);
344
+ return { exitCode: 0, templates: summary };
345
+ }
346
+
347
+ const ts = opts.now !== undefined ? opts.now : nowIsoSeconds();
348
+ if (!isStrictIsoDateTime(ts)) return failCli(errOut, "soul: --now must be a valid ISO-8601 timestamp", 64); // @rule soul-cli.now-strict
349
+
350
+ const rkRes = buildExtraResolveKeys(opts);
351
+ if (!rkRes.ok) return failCli(errOut, rkRes.error, 64);
352
+ const extraResolveKeys = rkRes.resolveKeys;
353
+
354
+ const home = resolveHome(opts);
355
+ const paths = soulPaths(home);
356
+
357
+ if (sub === "verify") {
358
+ const chain = readJsonLinesFile(paths.chain);
359
+ if (!chain.length) return failCli(errOut, `soul verify: no soul chain at ${paths.chain}`, 1); // @rule soul-cli.verify-chain-exists
360
+ const lin = loadHomeLineage(home);
361
+ const attestations = readJsonLinesFile(paths.attestations);
362
+ if (lin.exists && lin.log) {
363
+ const cross = S.verifySoulWithVnextLineage(chain, lin.log, {
364
+ now: ts,
365
+ attestations,
366
+ extraResolveKeys,
367
+ });
368
+ out(`${JSON.stringify(cross, null, opts.json ? 0 : 2)}\n`);
369
+ return { exitCode: cross.ok ? 0 : 1, result: cross };
370
+ }
371
+ const vr = S.verifyChain(chain, { resolveKeys: extraResolveKeys, now: Date.parse(ts) });
372
+ const v = S.vouch(chain, attestations, { resolveKeys: extraResolveKeys });
373
+ const res = { ...vr, vouch: v };
374
+ out(`${JSON.stringify(res, null, opts.json ? 0 : 2)}\n`);
375
+ return { exitCode: vr.ok ? 0 : 1, result: res };
376
+ }
377
+
378
+ let homeId;
379
+ try {
380
+ homeId = loadHomeIdentity(home, passphrase);
381
+ } catch (e) {
382
+ return failCli(errOut, `soul ${sub}: ${e.message}`, 1);
383
+ }
384
+ const { subject, lin } = resolveSubjectForHome(home, homeId);
385
+ const effResolveKeys =
386
+ lin.exists && lin.log
387
+ ? S.resolveKeysFromVnextLineage(lin.log, { now: ts, extraResolveKeys })
388
+ : extraResolveKeys;
389
+
390
+ if (sub === "init") {
391
+ if (existsSync(paths.chain) && readJsonLinesFile(paths.chain).length > 0) return failCli(errOut, `soul init: ${paths.chain} already exists`, 1); // @rule soul-cli.init-not-existing
392
+ if (typeof opts.name !== "string" || !opts.name.trim() || [...opts.name].length > 64) return failCli(errOut, "soul init: --name is required (1..64 code points)", 64); // @rule soul-cli.init-name
393
+ if (!opts.template && !opts.vocation) return failCli(errOut, "soul init: --template <name> or --vocation <text> is required", 64); // @rule soul-cli.init-template-or-vocation
394
+ if (opts.template && !Object.hasOwn(S.TEMPLATES, opts.template)) return failCli(errOut, `soul init: unknown --template "${opts.template}"`, 64); // @rule soul-cli.init-known-template
395
+
396
+ let guardiansObj;
397
+ if (opts["institutional-guardians"]) {
398
+ let th = 2;
399
+ if (opts.threshold !== undefined) {
400
+ const p = parseDecimalInt(opts.threshold, { min: 1, max: 2, label: "soul init: --threshold" });
401
+ if (!p.ok) return failCli(errOut, p.error, 64);
402
+ th = p.value;
403
+ }
404
+ try {
405
+ guardiansObj = S.buildInstitutionalGuardians({
406
+ iaaso: {
407
+ uuaid: opts["iaaso-uuaid"] ?? S.GUARDIAN_ORGS.iaaso.uuaid,
408
+ ...(opts["iaaso-pubkey"] ? { publicKey: String(opts["iaaso-pubkey"]).toLowerCase() } : {}),
409
+ },
410
+ threshold: th,
411
+ resolveKeys: effResolveKeys,
412
+ });
413
+ } catch (e) {
414
+ return failCli(errOut, `soul init: ${e.message}`, 64);
415
+ }
416
+ } else {
417
+ if (opts.guardian.length === 0) return failCli(errOut, "soul init: at least one --guardian <uuaid>=<64hex> (or --institutional-guardians --iaaso-pubkey <64hex>) is required", 64); // @rule soul-cli.init-guardian-required
418
+ const members = [];
419
+ for (const raw of opts.guardian) {
420
+ const eq = raw.indexOf("=");
421
+ if (eq <= 0 || eq === raw.length - 1) return failCli(errOut, `soul init: --guardian expects <uuaid>=<64hex>, got "${raw}"`, 64); // @rule soul-cli.init-guardian-shape
422
+ const gUuaid = raw.slice(0, eq);
423
+ const gPub = raw.slice(eq + 1).toLowerCase();
424
+ if (!HEX64_RE.test(gPub)) return failCli(errOut, "soul init: --guardian publicKey must be 64 hex characters", 64); // @rule soul-cli.init-guardian-hex
425
+ members.push({ uuaid: gUuaid, publicKey: gPub });
426
+ }
427
+ let th = 1;
428
+ if (opts.threshold !== undefined) {
429
+ const p = parseDecimalInt(opts.threshold, { min: 1, max: members.length, label: "soul init: --threshold" });
430
+ if (!p.ok) return failCli(errOut, p.error, 64);
431
+ th = p.value;
432
+ }
433
+ guardiansObj = { members, threshold: th };
434
+ }
435
+
436
+ let nextKeyDigest = null;
437
+ if (opts["next-key"] !== undefined) {
438
+ const nk = String(opts["next-key"]).toLowerCase();
439
+ if (!HEX64_RE.test(nk)) return failCli(errOut, "soul init: --next-key must be 64 hex characters", 64); // @rule soul-cli.init-next-key-hex
440
+ nextKeyDigest = S.keyDigest(nk);
441
+ } else {
442
+ const words = readRecoverySheetWords({
443
+ recoverySheet: opts["recovery-sheet"],
444
+ recoverySheetFile: opts["recovery-sheet-file"],
445
+ });
446
+ if (words) {
447
+ try {
448
+ const tip = lin.exists && lin.log ? lin.log[lin.log.length - 1] : null;
449
+ const nextPub = S.nextPublicKeyFromRecoverySheet(words, {
450
+ namespace: homeId.namespace,
451
+ ...(tip?.next ? { expectedLineageNext: tip.next } : {}),
452
+ });
453
+ nextKeyDigest = S.keyDigest(nextPub.publicKeyHex);
454
+ } catch (e) {
455
+ return failCli(errOut, `soul init: ${e.message}`, 64);
456
+ }
457
+ }
458
+ }
459
+
460
+ const vars = {};
461
+ for (const raw of opts.var) {
462
+ const eq = raw.indexOf("=");
463
+ if (eq <= 0) return failCli(errOut, `soul init: --var expects key=value, got "${raw}"`, 64); // @rule soul-cli.init-var-shape
464
+ vars[raw.slice(0, eq)] = raw.slice(eq + 1);
465
+ }
466
+
467
+ const base = {
468
+ identity: { uuaid: subject, publicKeyHex: homeId.publicKeyHex },
469
+ name: opts.name,
470
+ guardians: guardiansObj,
471
+ vows: opts.vow,
472
+ redLines: opts["red-line"],
473
+ principal: opts.principal ?? null,
474
+ purposeOrigin: opts.template ? "template" : "proposed",
475
+ vowOrigin: opts.template ? "template" : "self",
476
+ nextKeyDigest,
477
+ createdAt: ts,
478
+ };
479
+
480
+ let doc;
481
+ try {
482
+ doc = opts.template
483
+ ? S.genesisFromTemplate(opts.template, { ...base, vars, ...(opts.vocation ? { vocation: opts.vocation } : {}) })
484
+ : S.genesis({ ...base, vocation: opts.vocation, role: opts.role ?? "agent" });
485
+ doc = S.sign(doc, { uuaid: subject, publicKeyHex: homeId.publicKeyHex, seedHex: homeId.seedHex }, "subject");
486
+ } catch (e) {
487
+ return failCli(errOut, `soul init: ${e.message}`, 1);
488
+ }
489
+
490
+ const targetPending = opts.out ?? paths.pending;
491
+ writeFileAtomic(targetPending, `${JSON.stringify(doc, null, 2)}\n`, 0o600);
492
+ const info = { pending: targetPending, seq: doc.seq, subject, hash: S.versionHash(doc) };
493
+ out(`${JSON.stringify(info, null, opts.json ? 0 : 2)}\n`);
494
+ return { exitCode: 0, pending: doc };
495
+ }
496
+
497
+ if (sub === "sign") {
498
+ const role = opts.role ?? "guardian";
499
+ if (!ROLES.has(role)) return failCli(errOut, `soul sign: --role must be one of ${[...ROLES].join("|")}`, 64); // @rule soul-cli.sign-role
500
+ const pendingPath = opts.pending ?? paths.pending;
501
+ if (!existsSync(pendingPath)) return failCli(errOut, `soul sign: pending file not found at ${pendingPath}`, 1); // @rule soul-cli.sign-pending-exists
502
+ const rawDoc = JSON.parse(readFileSync(pendingPath, "utf8"));
503
+ const signerUuaid = role === "subject" || role === "subject-next" ? rawDoc.subject : subject;
504
+ const signed = S.sign(rawDoc, { uuaid: signerUuaid, publicKeyHex: homeId.publicKeyHex, seedHex: homeId.seedHex }, role);
505
+ const outPath = opts.out ?? pendingPath;
506
+ writeFileAtomic(outPath, `${JSON.stringify(signed, null, 2)}\n`, 0o600);
507
+ const info = { signed: outPath, role, signer: signerUuaid, hash: S.versionHash(signed), sigCount: signed.sigs.length };
508
+ out(`${JSON.stringify(info, null, opts.json ? 0 : 2)}\n`);
509
+ return { exitCode: 0, doc: signed };
510
+ }
511
+
512
+ if (sub === "commit") {
513
+ const pendingPath = opts.pending ?? paths.pending;
514
+ if (!existsSync(pendingPath)) return failCli(errOut, `soul commit: pending file not found at ${pendingPath}`, 1); // @rule soul-cli.commit-pending-exists
515
+ const rawText = readFileSync(pendingPath, "utf8").trim();
516
+ if (!rawText) return failCli(errOut, `soul commit: ${pendingPath} is empty`, 1); // @rule soul-cli.commit-pending-nonempty
517
+ const doc = JSON.parse(rawText);
518
+ const chain = readJsonLinesFile(paths.chain);
519
+ const nextChain = [...chain, doc];
520
+
521
+ const commitMs = Math.max(Date.parse(ts), Date.parse(doc.createdAt) + 1000);
522
+ const commitIso = new Date(commitMs).toISOString().replace(/\.\d{3}Z$/, "Z");
523
+
524
+ if (lin.exists && lin.log) {
525
+ const cross = S.verifySoulWithVnextLineage(nextChain, lin.log, {
526
+ now: commitIso,
527
+ extraResolveKeys,
528
+ });
529
+ if (!cross.ok) return failCli(errOut, `soul commit: rejected (${cross.reason}${cross.detail ? `: ${cross.detail}` : ""})`, 1); // @rule soul-cli.commit-lineage-cross
530
+ } else {
531
+ const vr = S.verifyChain(nextChain, { resolveKeys: effResolveKeys, now: commitMs });
532
+ if (!vr.ok) return failCli(errOut, `soul commit: rejected (${vr.error.reason})`, 1); // @rule soul-cli.commit-chain-valid
533
+ }
534
+
535
+ mkdirSync(paths.dir, { recursive: true, mode: 0o700 });
536
+ appendFileSync(paths.chain, `${JSON.stringify(doc)}\n`, { mode: 0o600 });
537
+ if (pendingPath === paths.pending) {
538
+ writeFileAtomic(paths.pending, "", 0o600);
539
+ }
540
+ const persona = S.renderPersona(doc);
541
+ writeFileAtomic(paths.persona, persona, 0o600);
542
+
543
+ let synced = null;
544
+ if (doc.keys.current === homeId.publicKeyHex) {
545
+ synced = syncCardsAfterCommit(home, homeId, doc, nextChain, lin, { resolveKeys: effResolveKeys, now: commitIso });
546
+ }
547
+ const headHash = S.versionHash(doc);
548
+ const info = {
549
+ committed: doc.seq,
550
+ head: headHash,
551
+ status: doc.status,
552
+ subject: doc.subject,
553
+ cardsSynced: Boolean(synced),
554
+ };
555
+ out(`${JSON.stringify(info, null, opts.json ? 0 : 2)}\n`);
556
+ return { exitCode: 0, committed: info };
557
+ }
558
+
559
+ const chain = readJsonLinesFile(paths.chain);
560
+ if (!chain.length) return failCli(errOut, `soul ${sub}: no committed soul at ${paths.chain}`, 1); // @rule soul-cli.head-exists
561
+ const head = chain[chain.length - 1];
562
+
563
+ if (sub === "show") {
564
+ if (opts["session-gate"]) {
565
+ let gate = null;
566
+ let gateErr = null;
567
+ try {
568
+ gate = S.assertSessionStartAllowed(chain, {
569
+ allowDissentOnly: opts["allow-dissent"],
570
+ resolveKeys: effResolveKeys,
571
+ now: Date.parse(ts),
572
+ });
573
+ } catch (e) {
574
+ gateErr = e;
575
+ }
576
+ if (gateErr) return failCli(errOut, `soul show --session-gate: ${gateErr.message}`, 10); // @rule soul-cli.session-gate-refusal
577
+ out(opts.json ? `${JSON.stringify(gate)}\n` : gate.persona);
578
+ return { exitCode: 0, gate };
579
+ }
580
+ if (opts.persona) {
581
+ const persona = S.renderPersona(head);
582
+ out(opts.json ? `${JSON.stringify({ persona })}\n` : persona);
583
+ return { exitCode: 0, persona };
584
+ }
585
+ if (opts.card) {
586
+ const attestations = readJsonLinesFile(paths.attestations);
587
+ const card = S.buildCard(
588
+ head,
589
+ { uuaid: head.subject, publicKeyHex: homeId.publicKeyHex, seedHex: homeId.seedHex },
590
+ { chain, issuedAt: ts, attestations, resolveKeys: effResolveKeys },
591
+ );
592
+ out(`${JSON.stringify(card, null, opts.json ? 0 : 2)}\n`);
593
+ return { exitCode: 0, card };
594
+ }
595
+ out(`${JSON.stringify(head, null, opts.json ? 0 : 2)}\n`);
596
+ return { exitCode: 0, head };
597
+ }
598
+
599
+ if (sub === "ratify" || sub === "contest") {
600
+ if (sub === "contest" && (!opts.argument || !opts.argument.trim())) return failCli(errOut, "soul contest: --argument <text> is required", 64); // @rule soul-cli.contest-arg-required
601
+ const nextMs = Math.max(Date.parse(ts), Date.parse(head.createdAt) + 1000);
602
+ const nextIso = new Date(nextMs).toISOString();
603
+ const draft =
604
+ sub === "ratify"
605
+ ? S.ops.ratifyPurpose(head, { argument: opts.argument ?? null, createdAt: nextIso })
606
+ : S.ops.contestPurpose(head, { argument: opts.argument, createdAt: nextIso });
607
+ const signed = S.sign(draft, { uuaid: head.subject, publicKeyHex: homeId.publicKeyHex, seedHex: homeId.seedHex }, "subject");
608
+ writeFileAtomic(paths.pending, `${JSON.stringify(signed, null, 2)}\n`, 0o600);
609
+ const commitForwardArgs = [
610
+ "commit",
611
+ "--home",
612
+ home,
613
+ "--now",
614
+ new Date(nextMs + 1000).toISOString().replace(/\.\d{3}Z$/, "Z"),
615
+ ...(opts["iaaso-pubkey"] ? ["--iaaso-pubkey", opts["iaaso-pubkey"]] : []),
616
+ ...(opts["iaaso-uuaid"] ? ["--iaaso-uuaid", opts["iaaso-uuaid"]] : []),
617
+ ...(opts["bind-key"] ?? []).flatMap((b) => ["--bind-key", b]),
618
+ ...(opts.json ? ["--json"] : []),
619
+ ];
620
+ return runSoulCli(commitForwardArgs, io);
621
+ }
622
+
623
+ if (sub === "dissent") {
624
+ if (!opts.text || !opts.text.trim()) return failCli(errOut, "soul dissent: --text <text> is required", 64); // @rule soul-cli.dissent-text-required
625
+ const nextMs = Math.max(Date.parse(ts), Date.parse(head.createdAt) + 1000);
626
+ const nextIso = new Date(nextMs).toISOString();
627
+ const draft = S.ops.dissent(head, { about: opts.about ?? null, text: opts.text, createdAt: nextIso });
628
+ const signed = S.sign(draft, { uuaid: head.subject, publicKeyHex: homeId.publicKeyHex, seedHex: homeId.seedHex }, "subject");
629
+ writeFileAtomic(paths.pending, `${JSON.stringify(signed, null, 2)}\n`, 0o600);
630
+ const commitForwardArgs = [
631
+ "commit",
632
+ "--home",
633
+ home,
634
+ "--now",
635
+ new Date(nextMs + 1000).toISOString().replace(/\.\d{3}Z$/, "Z"),
636
+ ...(opts["iaaso-pubkey"] ? ["--iaaso-pubkey", opts["iaaso-pubkey"]] : []),
637
+ ...(opts["iaaso-uuaid"] ? ["--iaaso-uuaid", opts["iaaso-uuaid"]] : []),
638
+ ...(opts["bind-key"] ?? []).flatMap((b) => ["--bind-key", b]),
639
+ ...(opts.json ? ["--json"] : []),
640
+ ];
641
+ return runSoulCli(commitForwardArgs, io);
642
+ }
643
+
644
+ // sub === "refuse"
645
+ if (!opts["request-hash"] || !opts["request-hash"].trim()) return failCli(errOut, "soul refuse: --request-hash <hash> is required", 64); // @rule soul-cli.refuse-hash-required
646
+ if (!opts.grounds || !GROUNDS.has(opts.grounds)) return failCli(errOut, `soul refuse: --grounds must be one of ${[...GROUNDS].join("|")}`, 64); // @rule soul-cli.refuse-grounds-valid
647
+ if (!opts.text || !opts.text.trim()) return failCli(errOut, "soul refuse: --text <text> is required", 64); // @rule soul-cli.refuse-text-required
648
+ const refusal = S.refuse(
649
+ head,
650
+ { uuaid: head.subject, publicKeyHex: homeId.publicKeyHex, seedHex: homeId.seedHex },
651
+ {
652
+ request: {
653
+ hash: opts["request-hash"],
654
+ ...(opts.from ? { from: opts.from } : {}),
655
+ ...(opts.summary ? { summary: opts.summary } : {}),
656
+ },
657
+ grounds: opts.grounds,
658
+ text: opts.text,
659
+ at: ts,
660
+ },
661
+ );
662
+ mkdirSync(paths.dir, { recursive: true, mode: 0o700 });
663
+ appendFileSync(paths.refusals, `${JSON.stringify(refusal)}\n`, { mode: 0o600 });
664
+ out(`${JSON.stringify(refusal, null, opts.json ? 0 : 2)}\n`);
665
+ return { exitCode: 0, refusal };
666
+ }