@cygnuxlabs/tracekit 1.5.2 → 1.6.0

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.
@@ -12,8 +12,10 @@
12
12
  * Monitor reports, revocations and the v1 format bridge are inputs of the reference's CLI that this one doesn't take.
13
13
  * A bundle that needs a newer verifier is UNVERIFIABLE, with the commands that verify it; one whose records carry ext
14
14
  * names this verifier doesn't interpret (format 1.4's non-critical slot) verifies, with a `not interpreted` warning
15
- * per name; it interprets `amended` (the fields an LLM gateway changed in a request to show reasoning) and
16
- * `openshell.policy` (OpenShell's sandbox policy changes, from the OpenShell middleware's OCSF import).
15
+ * per name; it interprets `amended` (the fields an LLM gateway changed in a request to show reasoning),
16
+ * `openshell.policy` (OpenShell's sandbox policy changes, from the OpenShell middleware's OCSF import), `box` (a
17
+ * Tracekit Box box's run label) and `intent.grant`, `intent.revoked` and `grant` (intent grants and the calls they
18
+ * released).
17
19
  * `verify(bundle, null)` (no trust config) checks what needs no pinned key and is never VERIFIED. web.ts is this
18
20
  * verifier as a browser page (verify.html).
19
21
  */
@@ -22,10 +24,14 @@ import { HYBRID, NoteError, SIGNER_LEAVES, b64decode, bytes, checkWitnesses, equ
22
24
  import { Detector } from "./detect.js";
23
25
  import { same, validateEvent } from "./schema.js";
24
26
  import { BadZipFile, MAX_ENTRY, Unusable, readZip } from "./zip.js";
27
+ import VERSIONS_JSON from "./versions.json" with { type: "json" };
25
28
  export { MAX_ENTRIES, MAX_ENTRY, MAX_TOTAL, Unusable, readZip } from "./zip.js";
26
29
  export { StrictJSONError, canonicalize, strictParse, strictParseBytes } from "./jcs.js";
27
- /** The bundle format version this verifier implements: a bundle needing a later one is UNVERIFIABLE. */
28
- export const VERSION = "1.5.2";
30
+ /** This verifier's release (the package's). */
31
+ export const VERSION = "1.6.0";
32
+ /** The newest bundle format version this verifier reads: the reference's VERSIONS' newest row (tracekit/bundle_v2.py),
33
+ * or VERSION when later (tracekit/verify/v2.py READS); a bundle needing a later one is UNVERIFIABLE. */
34
+ export const READS = "1.6.0";
29
35
  /** The browser verifier of the latest release (docs/RELEASING.md). */
30
36
  const PAGE = "https://cygnux-labs.github.io/Tracekit/verify/";
31
37
  export const EXIT_OK = 0, EXIT_FAIL = 1, EXIT_BAD = 2, EXIT_WARN = 3;
@@ -65,6 +71,10 @@ export class Report {
65
71
  findings = null;
66
72
  /** Checks the bundle needs that this verifier does not implement. */
67
73
  unsupported = [];
74
+ /** For the box check: the pinned witnesses' cosignatures of the checkpoint, `name (class) at time`, and the seqs of
75
+ * the bundle's own runs' first records. */
76
+ anchored = [];
77
+ firsts = new Set();
68
78
  check(check, ok, detail = "", problems = [], warn = false) {
69
79
  this.checks.push({ check, status: ok ? "pass" : warn ? "warn" : "fail", detail, problems });
70
80
  if (!ok)
@@ -78,15 +88,25 @@ export class Report {
78
88
  }
79
89
  }
80
90
  const isObj = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
81
- /** The manifest check's detail: on a failure, the files that differ from the manifest (the first 5) and how. */
82
- function manifestDetail(listed, hashes, bad) {
91
+ /** The files a bundle may hold besides its manifest (format-v2.md §9): no code, no trust config; a misnamed run part or
92
+ * policy snapshot fails a line of its own (run parts, policy snapshot). */
93
+ const FILES = new RegExp("^(runs/[0-9a-f]{32}(\\.part-[0-9]+)?\\.jsonl|keys/records\\.jsonl|proofs/records\\.json"
94
+ + "|checkpoints/(registry-)?[0-9]+\\.note|rekor/[0-9]+\\.json|tsa/[0-9]+\\.tsr|policies/.+"
95
+ + "|registry/(run-set\\.json|records\\.jsonl))$");
96
+ /** The manifest check's detail: on a failure, the files that differ from the manifest (the first 5) and how, and the
97
+ * files no bundle holds (the first 5). */
98
+ function manifestDetail(listed, hashes, bad, other) {
83
99
  if (!isObj(listed))
84
100
  return "the manifest lists no files";
85
- if (bad.length === 0)
101
+ if (!bad.length && !other.length)
86
102
  return "every file is listed with its SHA-256 and nothing else is in the bundle";
87
- const how = bad.slice(0, 5).map((n) => `${n} (${Object.hasOwn(listed, n) && hashes.has(n) ? "changed"
88
- : Object.hasOwn(listed, n) ? "missing" : "not listed"})`);
89
- return "files differ from the manifest: " + how.join(", ") + (bad.length > 5 ? ` and ${bad.length - 5} more` : "");
103
+ const more = (names) => names.length > 5 ? ` and ${names.length - 5} more` : "", out = [];
104
+ if (bad.length)
105
+ out.push("files differ from the manifest: " + bad.slice(0, 5).map((n) => `${n} (${Object.hasOwn(listed, n)
106
+ && hashes.has(n) ? "changed" : Object.hasOwn(listed, n) ? "missing" : "not listed"})`).join(", ") + more(bad));
107
+ if (other.length)
108
+ out.push("files no bundle holds: " + other.slice(0, 5).join(", ") + more(other));
109
+ return out.join("; ");
90
110
  }
91
111
  /** A check's detail: what it found when it passed, else how many problems in what (its lines say which), so a failed
92
112
  * line never reads as a pass. */
@@ -275,7 +295,7 @@ export async function verify(bundle, trust, names = { bundle: "BUNDLE", trust: "
275
295
  const need = manifest.verifier_min_version;
276
296
  if (!(typeof need === "string" && /^\d{1,9}(\.\d{1,9}){0,2}$/.test(need)))
277
297
  throw new Unusable("verifier_min_version is not a version number");
278
- if (newer(need, VERSION)) {
298
+ if (newer(need, READS)) {
279
299
  rep.integrity = `UNVERIFIABLE (needs tracekit >= ${need})`;
280
300
  rep.check("bundle readable", false, rep.integrity, upgrade(need, names));
281
301
  return { report: rep, code: EXIT_BAD };
@@ -336,7 +356,8 @@ async function check(rep, manifest, files, trust, floats) {
336
356
  hashes.set(n, await sha256hex(b));
337
357
  const bad = isObj(listed) ? [...new Set([...Object.keys(listed), ...hashes.keys()])]
338
358
  .filter((n) => !(Object.hasOwn(listed, n) && hashes.get(n) === listed[n])).sort() : [];
339
- rep.check("manifest", isObj(listed) && bad.length === 0, manifestDetail(listed, hashes, bad));
359
+ const other = [...hashes.keys()].filter((n) => !FILES.test(n)).sort();
360
+ rep.check("manifest", isObj(listed) && !bad.length && !other.length, manifestDetail(listed, hashes, bad, other));
340
361
  // the checkpoint: the only thing the records' trust hangs on
341
362
  const proofs = json("proofs/records.json");
342
363
  const name = at(proofs, "checkpoint");
@@ -377,11 +398,11 @@ async function check(rep, manifest, files, trust, floats) {
377
398
  && (k.until === null || seq <= num(k.until))).map((k) => k.spki);
378
399
  /** Signature, schema and log membership of one record under `keys`, the SPKIs valid at its position. */
379
400
  const checkRecord = async (r, keys, problems) => {
380
- const err = await verifyRecord(r, keys, trust.algs);
401
+ const err = await verifyRecord(r, keys, trust.algs, floats);
381
402
  if (err) {
382
403
  const seq = err === "unknown kid" ? get(r.event, "seq") : null; // a well-formed record by then
383
404
  const retired = [...timeline.values()].filter((k) => Number.isInteger(seq) && k.until !== null && k.until < seq);
384
- if (retired.length && !await verifyRecord(r, retired.map((k) => k.spki), trust.algs))
405
+ if (retired.length && !await verifyRecord(r, retired.map((k) => k.spki), trust.algs, floats))
385
406
  problems.push(`seq ${seq}: signed by key ${cut(r.kid, 80)} after its key.retire`);
386
407
  else
387
408
  problems.push(`seq ${repr(get(get(r, "event", {}), "seq"))}: ${err}`);
@@ -411,6 +432,10 @@ async function check(rep, manifest, files, trust, floats) {
411
432
  keyProblems.push(`seq ${e.seq}: key ${cut(str(k.kid), 80)} has no certificate, and the trust config pins issuers`);
412
433
  continue;
413
434
  }
435
+ if (has(k, "cert") && !trust.issuers.length) { // §11 step 5: no pinned issuer can have signed it
436
+ keyProblems.push(`seq ${e.seq}: key ${cut(str(k.kid), 80)}: certificate not signed by a pinned issuer`);
437
+ continue;
438
+ }
414
439
  // lean: a certified key is taken as declared and the bundle left UNVERIFIABLE; port docs/issuer.md's checks
415
440
  // (issuance log notes, validity, tenants, revocations) when certified record keys are in use
416
441
  if (has(k, "cert"))
@@ -418,14 +443,14 @@ async function check(rep, manifest, files, trust, floats) {
418
443
  declared.set(k.kid, { spki: der, from: e.seq, until: null });
419
444
  }
420
445
  }
421
- await checkRecord(r, [...keysAt(e.seq), ...[...declared.values()].map((k) => k.spki)], keyProblems);
422
- if (e.type === "key.retire") {
446
+ if (e.type === "key.retire") { // first: a key.retire is a record too, valid only under a key valid at its seq
423
447
  const kid = at(at(e, "data"), "kid");
424
448
  if (!timeline.has(kid))
425
449
  keyProblems.push(`seq ${e.seq}: retires an unknown key`);
426
450
  else
427
451
  timeline.get(kid).until = at(e.data, "last_seq");
428
452
  }
453
+ await checkRecord(r, [...keysAt(e.seq), ...[...declared.values()].map((k) => k.spki)], keyProblems);
429
454
  for (const [kid, k] of declared)
430
455
  timeline.set(kid, k);
431
456
  }
@@ -436,7 +461,9 @@ async function check(rep, manifest, files, trust, floats) {
436
461
  const runSet = files.has("registry/run-set.json");
437
462
  const runs = new Map(), problems = [], chain = [], outside = [];
438
463
  const layout = [], seen = new Set();
464
+ let unchecked = 0;
439
465
  for (const [name, parts] of names) {
466
+ const marks = problems.length + chain.length;
440
467
  const pieces = parts.map(jsonl), records = pieces.flat(), whole = parts.length === 1 && parts[0] === name;
441
468
  runs.set(name, records);
442
469
  extend(layout, parted(name, parts, pieces));
@@ -448,15 +475,24 @@ async function check(rep, manifest, files, trust, floats) {
448
475
  if (seen.has(key))
449
476
  chain.push(`run ${repr(cut(runId, 200))} of tenant ${repr(cut(tenant, 64))} again in ${name}`);
450
477
  seen.add(key);
478
+ const named = await runName(tenant, runId); // §9: a run's file is named by its tenant and run_id
479
+ if (named !== name)
480
+ chain.push(`run ${repr(cut(runId, 200))} of tenant ${repr(cut(tenant, 64))} in ${name}: its file is ${named}`);
451
481
  }
452
482
  for (const [i, r] of records.entries()) {
453
- await checkRecord(r, keysAt(num(at(at(r, "event"), "seq"))), problems);
454
- const e = r.event, prev = i ? records[i - 1] : null;
483
+ if (problems.length + chain.length - marks >= RUN_PROBLEMS) {
484
+ unchecked += records.length - i;
485
+ chain.push(`run ${repr(cut(str(get(head, "run_id")), 200))}: ${records.length - i} record(s) from run_seq ${i} on `
486
+ + `not checked, after ${RUN_PROBLEMS} problems in the run`);
487
+ break;
488
+ }
489
+ const e = at(r, "event"), prev = i ? records[i - 1] : null; // its link to the one before first: it costs nothing
455
490
  if (!same(get(e, "run_seq"), i) || !same(get(e, "run_prev_hash"), prev ? at(prev, "hash") : ZERO_HASH)
456
491
  || !same([get(e, "tenant"), get(e, "run_id")], [get(head, "tenant"), get(head, "run_id")])
457
492
  || prev && (num(at(e, "seq")) <= num(at(at(prev, "event"), "seq")) || get(prev.event, "type") === "run.final"))
458
493
  chain.push(`run ${repr(cut(str(get(head, "run_id")), 200))} run_seq ${i} (seq ${repr(get(e, "seq"))}) does not `
459
494
  + "continue the run");
495
+ await checkRecord(r, keysAt(num(at(e, "seq"))), problems);
460
496
  }
461
497
  if (!(await included(records[0]) && await included(records.at(-1))))
462
498
  outside.push(`run ${repr(cut(str(get(head, "run_id")), 200))}` + (!whole && await included(records[0])
@@ -467,9 +503,9 @@ async function check(rep, manifest, files, trust, floats) {
467
503
  rep.unsupport("tracekit why findings");
468
504
  else if (runs.size !== 1 && !runSet && !aboutOne(runs))
469
505
  throw new ValueError("a v2 bundle holds exactly one run, one run with its findings and replay runs, or a run-set");
470
- let retired = [], provenTo = -1, regCosigs = [];
506
+ let retired = [], provenTo = -1, regCosigs = [], pointed = [];
471
507
  if (runSet) {
472
- [retired, provenTo, regCosigs] = await checkRunSet(rep, json("registry/run-set.json"), jsonl, file, trust, witnesses, origin, size, runs, included, (r, p) => checkRecord(r, keysAt(num(at(at(r, "event"), "seq"))), p), floats);
508
+ [retired, provenTo, regCosigs, pointed] = await checkRunSet(rep, json("registry/run-set.json"), jsonl, file, trust, witnesses, origin, size, runs, included, (r, p) => checkRecord(r, keysAt(num(at(at(r, "event"), "seq"))), p), floats);
473
509
  const keyed = new Set(keyRecords.map((r) => `${at(at(r, "event"), "seq")} ${at(r, "hash")}`));
474
510
  extend(keyProblems, retired.filter(([seq, h]) => !keyed.has(`${seq} ${h}`))
475
511
  .map(([seq]) => `seq ${seq}: key.retire withheld (the registry log has it)`));
@@ -492,7 +528,8 @@ async function check(rep, manifest, files, trust, floats) {
492
528
  if (inParts.length)
493
529
  rep.check("run parts", !layout.length, found(layout, `${inParts.length} run(s) in ${inParts.reduce((a, b) => a + b, 0)} `
494
530
  + "parts, each part continuing the one before it", `the parts of ${inParts.length} run(s)`), layout);
495
- rep.check("signatures", !problems.length, found(problems, `${every.length} record(s), keys valid at their position`, `${every.length} record(s)`), problems);
531
+ rep.check("signatures", !problems.length, found(problems, `${every.length - unchecked} record(s), keys valid at their `
532
+ + "position", `${every.length - unchecked} record(s)`), problems);
496
533
  const only = runs.size === 1 ? [...runs.values()][0][0].event : null;
497
534
  rep.check("run chain", !chain.length, found(chain, only ? `run ${repr(cut(str(get(only, "run_id")), 200))} of tenant `
498
535
  + `${repr(get(only, "tenant"))}, contiguous from run_seq 0` : `${runs.size} run(s), each contiguous from run_seq 0`, `the chain of ${runs.size} run(s)`), chain);
@@ -510,7 +547,9 @@ async function check(rep, manifest, files, trust, floats) {
510
547
  rep.integrity = !open.length ? "VERIFIED" : only ? `VERIFIED TO HEAD ${str(get(open[0].at(-1).event, "run_seq"))} (open)`
511
548
  : `VERIFIED (${open.length} run(s) open)`;
512
549
  const events = every.map((r) => r.event), typed = (t) => events.filter((e) => get(e, "type") === t);
513
- const selfApproved = typed("approval").some((e) => get(at(e, "data"), "self_approved") === true);
550
+ // a grant the run's own user issued (intent.grant) approves the calls it releases: a self-approval too
551
+ const selfApproved = [...typed("approval"), ...typed("ext").filter((e) => get(at(e, "data"), "name") === "intent.grant")]
552
+ .some((e) => get(at(e, "data"), "self_approved") === true);
514
553
  const gaps = (k) => typed("capture.gap").filter((e) => get(at(e, "data"), "kind") === k)
515
554
  .map((e) => `seq ${e.seq}: ${cut(str(get(e.data, "reason")), 200)}`);
516
555
  const against = gaps("executed_against_policy");
@@ -644,9 +683,12 @@ async function check(rep, manifest, files, trust, floats) {
644
683
  if (glass.length)
645
684
  rep.check("break-glass approvals", false, `${glass.length} approval(s) answered under the break-glass role`, glass.map((e) => `seq ${e.seq}: ${str(at(e.data, "decision"))} ${str(get(e.data, "approval_id"))} by `
646
685
  + `${cut(text(at(e.data, "approver")), 256)}: ${repr(cut(str(get(e.data, "reason")), 200))}`).slice(0, 20), true);
647
- const pointed = runSet ? jsonl("registry/records.jsonl") : []; // the records a run-set's leaves name
648
- checkExt(rep, [...new Map([...keyRecords, ...pointed, ...every].map((r) => [at(at(r, "event"), "seq"), r.event]))
649
- .values()], get(manifest, "verifier_version"));
686
+ rep.anchored = [...cosigs].sort((a, b) => a[1] < b[1] ? -1 : a[1] > b[1] ? 1 : 0)
687
+ .map(([k, ts]) => `${k.split("+")[0]} (${witnesses.get(k)}) at ${fmt(ts)}`);
688
+ rep.firsts = new Set(firsts.map((e) => at(e, "seq")));
689
+ const all = [...new Map([...keyRecords, ...pointed, ...every].map((r) => [at(at(r, "event"), "seq"), r.event])).values()];
690
+ await checkExt(rep, all, get(manifest, "verifier_version"), floats);
691
+ checkMinimum(rep, all, [...files.keys()], str(get(manifest, "verifier_min_version")));
650
692
  }
651
693
  /**
652
694
  * ext.amended: the JSON pointers of the fields an LLM gateway changed in a model request before sending it, to show the
@@ -693,21 +735,433 @@ function checkOpenshellPolicy(rep, events) {
693
735
  + `${good.length} time(s)` + (shown.length ? ` (${shown.join(", ")})` : "") + ", as OpenShell reported it", bad.map((e) => `seq ${str(get(e, "seq"))}: ext.openshell.policy is not an OpenShell policy change the signer `
694
736
  + "recorded").slice(0, 20), true);
695
737
  }
738
+ /** A Tracekit Box engine, as verify names what its box is (tracekit/signer/service.py ENGINES). */
739
+ const ENGINES = { firecracker: "micro-VM" };
740
+ const BOXED = "PROOF AGAINST THE BOXED AGENT";
741
+ const DOORS = "the box's doors (its connections and file writes)";
742
+ /**
743
+ * Whether `e` carries ext.box as the signer writes it: on run.registered only, {id, image_digest, allow, engine,
744
+ * channel?}, under a Box daemon's identity (a uid): its box run, or with parent_run a run of its box's agent channel.
745
+ */
746
+ function boxLabel(e) {
747
+ const v = isObj(get(e, "ext")) ? get(e.ext, "box") : null, d = get(e, "data");
748
+ const i = isObj(d) ? get(d, "identity") : null, keys = isObj(v) ? Object.keys(v) : [];
749
+ return get(e, "type") === "run.registered" && isObj(v) && isObj(i) && get(i, "scheme") === "uid"
750
+ && ["id", "image_digest", "allow", "engine"].every((k) => keys.includes(k))
751
+ && keys.every((k) => ["id", "image_digest", "allow", "engine", "channel"].includes(k))
752
+ && typeof v.id === "string" && /^[A-Za-z0-9._:-]{1,128}$/.test(v.id) && typeof v.image_digest === "string"
753
+ && /^sha256:[0-9a-f]{64}$/.test(v.image_digest) && Array.isArray(v.allow)
754
+ && v.allow.every((a) => typeof a === "string") && typeof v.engine === "string"
755
+ && Object.hasOwn(ENGINES, v.engine) && (!Object.hasOwn(v, "channel") || v.channel === "agent");
756
+ }
757
+ /**
758
+ * ext.box: the label of a Tracekit Box box's run (its daemon's account of the box, with the engine from the signer's
759
+ * own config) and of each run its agent channel registered (a copy, with parent_run). The signing key was outside that
760
+ * box, so the runs are proof against the agent in it, and no more: an agent run's records are its own account, the
761
+ * box's doors held it, and anything running as the daemon's or the signer's user on the host is outside the claim.
762
+ * Anywhere else, or in another shape, a warning and no claim. Only the bundle's own runs are claimed for
763
+ * (rep.firsts): a run-set's records of other runs carry their labels too.
764
+ */
765
+ function checkBox(rep, events) {
766
+ const bad = events.filter((e) => !boxLabel(e));
767
+ if (bad.length) {
768
+ rep.check("boxed agent", false, `${bad.length} record(s) carry ext.box where or how the signer never writes it: `
769
+ + "no proof against a boxed agent", bad.map((e) => `seq ${str(get(e, "seq"))}: ext.box is not a box's label on `
770
+ + "its run.registered").slice(0, 20), true);
771
+ return;
772
+ }
773
+ const good = events.filter((e) => rep.firsts.has(get(e, "seq")));
774
+ if (!good.length)
775
+ return; // labels of runs this bundle doesn't hold
776
+ const one = good.length === 1, agent = good.some((e) => Object.hasOwn(e.data, "parent_run"));
777
+ const kinds = [...new Set(good.map((e) => ENGINES[e.ext.box.engine]))].sort(byCodePoint).join(", ");
778
+ rep.check("boxed agent", true, `${BOXED} (${kinds}): the signing key was outside its box for `
779
+ + `${one ? "this run" : `these ${good.length} runs`}.`, [one && agent
780
+ ? `This run's records are the agent's own account of its calls; ${DOORS} are the record of what it could do.`
781
+ : one ? `This run's records are ${DOORS}, as the Box daemon recorded them.`
782
+ : `In these runs, the agent's records are its own account of its calls; ${DOORS} are the record of what it `
783
+ + "could do.",
784
+ "Before you run anything the box wrote, review it: code you run on this machine can reach the key.",
785
+ ...rep.anchored.map((a) => `anchored by ${a}`)]);
786
+ }
787
+ /** Whether the parser read `o[k]` as a number token with a fraction or exponent: Python's float, never an int. */
788
+ const isFloat = (floats, o, k) => !!floats.get(o)?.has(k);
789
+ const NO_FLOATS = new WeakMap(); // for values this verifier computed
790
+ /** A number as Python prints it: a float-written whole number with `.0`. */
791
+ // lean: integral floats below 1e16 only; Python's repr of others (1e+16, 1e-05) differs from JavaScript's
792
+ const pyNum = (v, float) => float && Number.isInteger(v) && Math.abs(v) < 1e16 ? `${v}.0` : JSON.stringify(v);
793
+ /** Python's json.dumps(v), as the reference's messages print values: ", " and ": " between items, and every character
794
+ * past ASCII escaped; `float`: v was written as a float. */
795
+ function dumps(v, floats = NO_FLOATS, float = false) {
796
+ if (Array.isArray(v))
797
+ return `[${v.map((x, i) => dumps(x, floats, isFloat(floats, v, i))).join(", ")}]`;
798
+ if (isObj(v))
799
+ return `{${Object.entries(v).map(([k, x]) => `${dumps(k)}: ${dumps(x, floats, isFloat(floats, v, k))}`)
800
+ .join(", ")}}`;
801
+ if (typeof v === "number")
802
+ return pyNum(v, float);
803
+ return JSON.stringify(v).replace(/[\x7f-\uffff]/g, (c) => "\\u" + c.charCodeAt(0).toString(16).padStart(4, "0"));
804
+ }
805
+ /** Python's str(v), as an f-string prints a value: a list or an object with its items' repr (`['g-1', None]`). */
806
+ function pyStr(v, floats = NO_FLOATS, float = false) {
807
+ const item = (x, f) => typeof x === "string" ? quoted(x) : pyStr(x, floats, f);
808
+ return Array.isArray(v) ? `[${v.map((x, i) => item(x, isFloat(floats, v, i))).join(", ")}]`
809
+ : isObj(v) ? `{${Object.entries(v).map(([k, x]) => `${quoted(k)}: ${item(x, isFloat(floats, v, k))}`).join(", ")}}`
810
+ : typeof v === "number" ? pyNum(v, float) : str(v);
811
+ }
812
+ // intent grants (docs/intent-grants.md), as tracekit/grants.py and tracekit/pcm read them; payments are the one intent
813
+ /** The minor units of each currency an amount is shown in (grants.DECIMALS). */
814
+ const DECIMALS = { USD: 2, EUR: 2, GBP: 2, INR: 2, CAD: 2, AUD: 2, CHF: 2, SGD: 2, JPY: 0,
815
+ USDC: 6, USDT: 6 };
816
+ /** payment.send's schema document (grants.PAYMENT): a grant's intent names its hash. */
817
+ const PAYMENT = { pcm_schema: 0, name: "payment.send", grant: true, fields: {
818
+ amount: { type: "int", min: 1, max: Number.MAX_SAFE_INTEGER },
819
+ currency: { type: "id", pattern: "[A-Z][A-Z0-9]{2,9}" },
820
+ payee: { type: "id", pattern: "[A-Za-z0-9._:@/+=-]{1,128}" }
821
+ } };
822
+ const FIELDS = PAYMENT.fields;
823
+ const CAVEAT_OPS = { int: ["==", "<=", ">=", "<", ">"], id: ["==", "in"] };
824
+ const GRANT_KEYS = ["name", "id", "grant", "tools", "limits", "used", "self_approved", "first", "description"];
825
+ const MAX_TOOLS = 16; // the tools one grant names (grants.MAX_TOOLS)
826
+ const ID_RE = /^[A-Za-z0-9._:-]{1,128}$/, NAME_RE = /^[a-z][a-z0-9_]{0,63}$/;
827
+ // rpc_schema.TS, whose \d Python's re reads as any decimal digit
828
+ const TS_RE = /^\p{Nd}{4}-\p{Nd}{2}-\p{Nd}{2}T\p{Nd}{2}:\p{Nd}{2}:\p{Nd}{2}\.\p{Nd}{6}Z$/u;
829
+ /** Whether `o` is an object with every key of `need` and no key outside `need` and `may` (a closed JSON Schema). */
830
+ const shaped = (o, need, may = []) => isObj(o) && need.every((k) => Object.hasOwn(o, k))
831
+ && Object.keys(o).every((k) => need.includes(k) || may.includes(k));
832
+ /** Whether `v` is a string of at most `n` characters, all of it matching `re`. */
833
+ const short = (v, n, re) => typeof v === "string" && [...v].length <= n && (!re || re.test(v));
834
+ const opt = (o, k, ok) => !Object.hasOwn(o, k) || ok(o[k]);
835
+ /** A PCM grant as rpc_schema.PCM_GRANT has it. */
836
+ const isPcmGrant = (g, floats) => shaped(g, ["pcm_grant", "ts", "issuer", "subject", "intent", "caveats",
837
+ "expires_at", "delegable", "parent", "sig"]) && g.pcm_grant === 0 && !isFloat(floats, g, "pcm_grant")
838
+ && short(g.ts, 27, TS_RE) && short(g.expires_at, 27, TS_RE)
839
+ && shaped(g.issuer, ["kind", "id", "run", "tenant"], ["person", "approval_id"])
840
+ && ["person", "agent"].includes(g.issuer.kind) && short(g.issuer.id, 256) && opt(g.issuer, "person", (v) => short(v, 256))
841
+ && short(g.issuer.run, 128, ID_RE) && short(g.issuer.tenant, 128, ID_RE)
842
+ && opt(g.issuer, "approval_id", (v) => short(v, 128, ID_RE)) && short(g.subject, 256, /^[a-z0-9_]+:[^\n]+$/)
843
+ && short(g.intent, 136, /^[a-z][a-z0-9_.-]{0,63}@sha256:[0-9a-f]{64}$/) && Array.isArray(g.caveats)
844
+ && g.caveats.length <= 16 && g.caveats.every((c) => shaped(c, ["field", "op", "value"]) && short(c.field, 64, NAME_RE)
845
+ && ["==", "<=", ">=", "<", ">", "in"].includes(c.op)) && typeof g.delegable === "boolean"
846
+ && (g.parent === null || short(g.parent, 71, /^sha256:[0-9a-f]{64}$/))
847
+ && shaped(g.sig, ["key", "sig"]) && short(g.sig.key, 300) && g.sig.key !== "" && short(g.sig.sig, 88);
848
+ /** A grant's limits as rpc_schema._LIMITS has them. */
849
+ const isLimits = (v, floats) => Array.isArray(v) && v.length >= 1 && v.length <= 4 && v.every((x) => shaped(x, ["op", "max"], ["field"]) && ["sum", "count"].includes(x.op) && opt(x, "field", (f) => short(f, 64, NAME_RE))
850
+ && Number.isSafeInteger(x.max) && !isFloat(floats, x, "max") && x.max >= 1);
851
+ /** pcm._FITS: whether `v` is a valid value of field `f`; `float`: v was written as a float, which is no int. */
852
+ // lean: the int and id rules, the types payment.send uses; port the rest with an intent whose fields use them
853
+ const fits = (f, v, float) => f.type === "int" ? Number.isInteger(v) && !float && f.min <= v && v <= f.max
854
+ : typeof v === "string" && [...v].length <= 128 && new RegExp(`^(?:${f.pattern})$`).test(v);
855
+ /** pcm.check_args of payment.send: what is wrong with call `fields`, an object. */
856
+ function argErrors(fields, floats) {
857
+ const out = Object.keys(fields).filter((k) => !Object.hasOwn(FIELDS, k)).map((k) => `args.${k}: not in the schema`);
858
+ for (const [k, f] of Object.entries(FIELDS)) {
859
+ if (!Object.hasOwn(fields, k))
860
+ out.push(`args.${k}: missing`);
861
+ else if (!fits(f, fields[k], isFloat(floats, fields, k)))
862
+ out.push(`args.${k}: ${dumps(fields[k], floats, isFloat(floats, fields, k)).slice(0, 64)} is not a valid ${f.type}`);
863
+ }
864
+ return out;
865
+ }
866
+ /** A grant's short id (grants.grant_id): `g-` and the first 16 hex digits of its hash. */
867
+ const grantId = async (g) => "g-" + (await sha256hex(bytes(canonicalize(g)))).slice(0, 16);
868
+ /** grants.number: minor units as the number a person reads (`200`, `0.5`); the minor units for an unknown currency. */
869
+ function number(minor, cur) {
870
+ const d = typeof cur === "string" && Object.hasOwn(DECIMALS, cur) ? DECIMALS[cur] : null;
871
+ if (d === null || !Number.isInteger(minor))
872
+ return dumps(minor).slice(0, 32);
873
+ const frac = minor % 10 ** d;
874
+ return `${(minor - frac) / 10 ** d}` + (frac ? "." + String(frac).padStart(d, "0").replace(/0+$/, "") : "");
875
+ }
876
+ /** grants.show: minor units as a person reads them (`200 USDC`), by name for an unknown currency. */
877
+ const show = (minor, cur) => `${number(minor, cur)} `
878
+ + (typeof cur === "string" && Object.hasOwn(DECIMALS, cur) && Number.isInteger(minor) ? cur : `${str(cur)} (minor units)`);
879
+ /** grants.problems for a payment grant, as a verifier asks (no ceiling), of caveats and limits already of their shape;
880
+ * `tools`: the record's, the tools whose calls the grant covers. */
881
+ function grantProblems(caveats, limits, tools, expiresAt, now, floats) {
882
+ const out = [], pinned = new Map(), seen = new Set();
883
+ for (const c of caveats) { // pcm.check_caveats
884
+ const f = Object.hasOwn(FIELDS, c.field) ? FIELDS[c.field] : null, vals = c.op === "in" ? c.value : [c.value];
885
+ const said = `${c.field} ${c.op} ${dumps(c.value, floats, isFloat(floats, c, "value")).slice(0, 64)}`;
886
+ if (!f)
887
+ out.push(`${said}: no field ${c.field} in payment.send`);
888
+ else if (!CAVEAT_OPS[f.type].includes(c.op))
889
+ out.push(`${said}: ${c.op} does not apply to a ${f.type} field`);
890
+ else if (!(Array.isArray(vals) && vals.length >= 1 && vals.length <= 64 && vals.every((x, i) => fits(f, x, c.op === "in" ? isFloat(floats, vals, i) : isFloat(floats, c, "value"))) && new Set(vals).size === vals.length))
891
+ out.push(`${said}: not a valid ${f.type} value`);
892
+ }
893
+ if (!(Array.isArray(tools) && tools.length > 0 && tools.length <= MAX_TOOLS && new Set(tools).size === tools.length
894
+ && tools.every((t) => typeof t === "string" && t !== "" && [...t].length <= 256)))
895
+ out.push(`a grant names the tools whose calls it covers: 1 to ${MAX_TOOLS} distinct tool names`);
896
+ for (const c of caveats)
897
+ if (c.op === "==" || c.op === "in")
898
+ pinned.set(c.field, c);
899
+ const cur = pinned.get("currency");
900
+ if (cur?.op !== "==")
901
+ out.push("a payment grant names its one currency (currency == USDC)");
902
+ else if (typeof cur.value === "string" && !Object.hasOwn(DECIMALS, cur.value)) // else check_caveats said it
903
+ out.push(`tracekit knows the units of ${Object.keys(DECIMALS).sort().join(", ")}; ${cur.value} isn't one of them`);
904
+ if (!pinned.has("payee"))
905
+ out.push("a payment grant names its payees (payee in [...])");
906
+ for (const x of limits) { // the rest of a limit's rule is its shape's (isLimits)
907
+ const k = JSON.stringify([x.op, x.field ?? null]);
908
+ const f = x.field ?? "amount";
909
+ if ((x.op === "sum") !== Object.hasOwn(x, "field") || !(Object.hasOwn(FIELDS, f) && FIELDS[f].type === "int"))
910
+ out.push(`limit ${dumps(x, floats).slice(0, 96)}: a limit is {op: sum, field, max} of a whole-number field (amount) `
911
+ + "or {op: count, max}, max a whole number above zero");
912
+ else if (seen.has(k))
913
+ out.push(`limit ${x.op} ${x.field ?? ""}: given twice`.replace(/ /g, " "));
914
+ seen.add(k);
915
+ }
916
+ if (!limits.some((x) => x.op === "sum" && x.field === "amount"))
917
+ out.push("a payment grant has a total (a sum limit of amount)");
918
+ const day = new Date(Date.parse(now.slice(0, 19) + "Z") + 86400_000).toISOString().slice(0, 19) + now.slice(19);
919
+ if (!(now < expiresAt && expiresAt <= day))
920
+ out.push(`expires_at ${expiresAt} is not in the next 24 h`);
921
+ return out;
922
+ }
923
+ /** grants._why: why `fields` break caveat `c`, in words. */
924
+ function brokenBy(c, fields) {
925
+ const v = get(fields, c.field), cur = get(fields, "currency");
926
+ if (c.field === "amount" && (c.op === "<=" || c.op === "<"))
927
+ return `amount ${show(v, cur)} is over ${show(c.value - Number(c.op === "<"), cur)} each`;
928
+ if (c.field === "amount" && (c.op === ">=" || c.op === ">"))
929
+ return `amount ${show(v, cur)} is under ${show(c.value + Number(c.op === ">"), cur)} each`;
930
+ const allowed = c.op === "in" ? c.value : [c.value];
931
+ return `${c.field} ${dumps(v).slice(0, 64)} is not ${allowed.length > 1 ? "one of " : ""}`
932
+ + allowed.slice(0, 8).map((x) => dumps(x).slice(0, 64)).join(", ")
933
+ + (allowed.length > 8 ? ` and ${allowed.length - 8} more` : "");
934
+ }
935
+ /**
936
+ * grants.check: [the totals after a call with `fields`, null] when grant `gid`'s entry `g` ({grant, limits, used,
937
+ * revoked}) releases it at `now`, else [null, why not]. Its caveats passed grantProblems and the fields argErrors, so
938
+ * each caveat compares values of one type (pcm.satisfies).
939
+ */
940
+ function grantCheck(gid, g, fields, now) {
941
+ if (g.revoked)
942
+ return [null, `grant ${gid} was revoked`];
943
+ if (now >= g.grant.expires_at)
944
+ return [null, `grant ${gid} expired at ${g.grant.expires_at}`];
945
+ for (const c of g.grant.caveats) {
946
+ const v = fields[c.field], w = c.value;
947
+ if (!(c.op === "in" ? w.includes(v) : c.op === "==" ? v === w : c.op === "<=" ? v <= w : c.op === "<" ? v < w
948
+ : c.op === ">=" ? v >= w : v > w))
949
+ return [null, `grant ${gid}: ${brokenBy(c, fields)}`];
950
+ }
951
+ const used = g.limits.map((x, i) => g.used[i] + (x.op === "sum" ? fields[x.field] : 1));
952
+ for (const [i, x] of g.limits.entries()) {
953
+ if (used[i] <= x.max)
954
+ continue;
955
+ const before = g.used[i], cur = fields.currency;
956
+ return [null, `grant ${gid}: ` + (x.op === "count" ? `${str(before)} of ${x.max} payments made`
957
+ : `${number(before, cur)} of ${show(x.max, cur)} used; this call needs ${show(used[i] - before, cur)}`)];
958
+ }
959
+ return [used, null];
960
+ }
961
+ /**
962
+ * Why `e` is not an intent.grant record as the signer writes one (SignerService._grant_issue), or null: a PCM grant of
963
+ * payment.send (`payment`, its schema ref), issued by a person for this very run and tenant, never passed on, its id its
964
+ * hash's; caveats, tools and limits a grant may have, an expiry within 24 h of its issue; and its totals those of no
965
+ * call, or of the held call it was issued from (`first`), which must be within it.
966
+ */
967
+ async function grantIssued(e, payment, floats) {
968
+ const d = get(e, "data");
969
+ if (get(e, "source") !== "signer" || !isObj(d) || !Object.keys(d).every((k) => GRANT_KEYS.includes(k))
970
+ || typeof get(d, "id") !== "string" || !Array.isArray(get(d, "used"))
971
+ || !d.used.every((u, i) => Number.isInteger(u) && !isFloat(floats, d.used, i)) || !isPcmGrant(get(d, "grant"), floats)
972
+ || !isLimits(get(d, "limits"), floats) || typeof get(d, "self_approved") !== "boolean")
973
+ return "an intent.grant record that is not as the signer writes one";
974
+ const g = d.grant;
975
+ if (g.intent !== payment)
976
+ return `a grant of intent ${cut(g.intent, 80)}, which this verifier doesn't know`;
977
+ const id = await grantId(g);
978
+ if (d.id !== id)
979
+ return `grant ${cut(d.id, 24)} is not its grant's id (${id})`;
980
+ if (g.issuer.kind !== "person" || g.issuer.run !== get(e, "run_id") || g.issuer.tenant !== get(e, "tenant")
981
+ || g.parent !== null || g.delegable !== false)
982
+ return `grant ${id} is not a person's, for this run and tenant, kept to its run`;
983
+ const bad = grantProblems(g.caveats, d.limits, get(d, "tools"), g.expires_at, g.ts, floats);
984
+ if (bad.length)
985
+ return `grant ${id}: ${cut(bad.join("; "), 300)}`;
986
+ let used = d.limits.map(() => 0);
987
+ const f = get(d, "first");
988
+ if (f !== null) {
989
+ const fields = isObj(f) ? get(f, "fields") : null;
990
+ if (!(isObj(fields) && !argErrors(fields, floats).length && typeof get(f, "approval_id") === "string"
991
+ && typeof get(f, "tool_call_id") === "string"))
992
+ return `grant ${id}: its first use is not a held call's`;
993
+ const [after, why] = grantCheck(id, { grant: g, limits: d.limits, used, revoked: false }, fields, g.ts);
994
+ if (why)
995
+ return `grant ${id} was issued from a held call outside it (${why})`;
996
+ used = after;
997
+ }
998
+ if (!same(d.used, used))
999
+ return `grant ${id} starts with totals ${dumps(d.used, floats).slice(0, 64)}, not ${dumps(used)}`;
1000
+ if (Object.hasOwn(d, "description") && !short(d.description, 512))
1001
+ return `grant ${id}: its description is not a string of at most 512 characters`;
1002
+ return null;
1003
+ }
1004
+ /** Whether `e` is a decision whose rule ids name TK-GRANT: one a grant released, as its ext.grant must say. */
1005
+ const tkGrant = (e) => get(e, "type") === "policy.decision" && isObj(get(e, "data"))
1006
+ && Array.isArray(get(e.data, "rule_ids")) && e.data.rule_ids.includes("TK-GRANT");
1007
+ /**
1008
+ * intent.grant, intent.revoked and ext.grant (docs/intent-grants.md): the grants people issued for a run, their
1009
+ * revocations, and the calls they released. Each grant is checked as grantIssued says; each released call against its
1010
+ * grant, as the signer decided it: a policy.decision flagged with TK-GRANT, its grant recorded earlier in the same run
1011
+ * and not revoked before it, decided before the grant expired, of a tool the grant covers, its fields those of the
1012
+ * intent (whole numbers where they count) and within every caveat, its totals the previous call's plus its own, whole
1013
+ * numbers within every limit, and its tier the record's (T2: an executor or gateway decided and ran the call; T1: the
1014
+ * arguments the harness reported). A release that breaks its grant fails the line, and so does one whose grant the
1015
+ * bundle doesn't hold earlier in its run, or holds only in a record a signer never writes, a decision flagged TK-GRANT
1016
+ * without ext.grant, and a tier that isn't the record's: the records are the signer's own word that the call was within
1017
+ * a person's grant. Any other record in a shape the signer never writes is a warning, as for every ext name. `events`
1018
+ * also holds the decisions TK-GRANT names (checkExt); `floats`: the parser's, so a number written as a float is no whole
1019
+ * number.
1020
+ */
1021
+ export async function checkGrants(rep, events, floats) {
1022
+ const payment = `payment.send@sha256:${await sha256hex(bytes(canonicalize(PAYMENT)))}`;
1023
+ const live = new Map(), invalid = new Set(), bad = [], broken = [];
1024
+ const issuers = new Set();
1025
+ const tiers = { T1: 0, T2: 0 };
1026
+ let issued = 0, selfish = 0, revoked = 0;
1027
+ const seq = (e) => Number.isInteger(get(e, "seq")) ? e.seq : -1;
1028
+ for (const e of [...events].sort((a, b) => seq(a) - seq(b))) {
1029
+ const where = `seq ${pyStr(get(e, "seq"), floats, isFloat(floats, e, "seq"))}`, d = get(e, "data");
1030
+ const key = (id) => JSON.stringify([get(e, "tenant"), get(e, "run_id"), id]); // a grant's id is a string
1031
+ const name = get(e, "type") === "ext" && isObj(d) ? get(d, "name") : null;
1032
+ if (name === "intent.grant") {
1033
+ const why = await grantIssued(e, payment, floats);
1034
+ if (why) {
1035
+ bad.push(`${where}: ${why}`);
1036
+ if (typeof get(d, "id") === "string")
1037
+ invalid.add(key(d.id)); // what it released is released under no valid grant
1038
+ continue;
1039
+ }
1040
+ live.set(key(d.id), { grant: d.grant, tools: d.tools, limits: d.limits, used: d.used, revoked: false });
1041
+ issued++;
1042
+ selfish += Number(d.self_approved);
1043
+ if (!d.self_approved)
1044
+ issuers.add(d.grant.issuer.person || d.grant.issuer.id);
1045
+ }
1046
+ else if (name === "intent.revoked") {
1047
+ const g = typeof get(d, "id") === "string" ? live.get(key(d.id)) : undefined;
1048
+ if (get(e, "source") !== "signer" || !g || g.revoked)
1049
+ bad.push(`${where}: revokes no grant still live in its run`);
1050
+ else {
1051
+ g.revoked = true;
1052
+ revoked++;
1053
+ }
1054
+ }
1055
+ if (!(isObj(get(e, "ext")) && Object.hasOwn(e.ext, "grant"))) {
1056
+ if (tkGrant(e))
1057
+ broken.push(`${where}: a decision flagged TK-GRANT carries no ext.grant: it names no grant it was released under`);
1058
+ continue;
1059
+ }
1060
+ const x = e.ext.grant, g = isObj(x) && typeof get(x, "id") === "string" ? live.get(key(x.id)) : undefined;
1061
+ if (!(tkGrant(e) && get(d, "decision") === "flag" && shaped(x, ["id", "fields", "used", "tier"]))) {
1062
+ bad.push(`${where}: ext.grant is not on a decision a grant released, as the signer writes it`);
1063
+ continue;
1064
+ }
1065
+ const errs = !g ? [] : isObj(x.fields) ? argErrors(x.fields, floats) : ["not an object"];
1066
+ if (!g && typeof x.id === "string" && invalid.has(key(x.id)))
1067
+ broken.push(`${where}: released under grant ${cut(x.id, 24)}, whose record is not as the signer writes one`);
1068
+ else if (!g)
1069
+ broken.push(`${where}: names grant ${cut(pyStr(x.id, floats, isFloat(floats, x, "id")), 24)}, which this `
1070
+ + "bundle doesn't hold earlier in the run (export the whole run to check it)");
1071
+ else if (errs.length)
1072
+ broken.push(`${where}: the fields it records are not a payment.send call's (${cut(errs[0], 120)})`);
1073
+ else if (!g.tools.includes(get(d, "tool")))
1074
+ broken.push(`${where}: released a call of ${dumps(get(d, "tool"), floats, isFloat(floats, d, "tool")).slice(0, 64)}, `
1075
+ + `a tool grant ${x.id} doesn't cover`);
1076
+ else {
1077
+ const [used, why] = grantCheck(x.id, g, x.fields, get(e, "ts") || "");
1078
+ if (why)
1079
+ broken.push(`${where}: released a call the grant holds (${why})`);
1080
+ else if (!(Array.isArray(x.used) && x.used.every((u, i) => Number.isInteger(u) && !isFloat(floats, x.used, i))
1081
+ && same(x.used, used)))
1082
+ broken.push(`${where}: records totals ${dumps(x.used, floats).slice(0, 64)}, not ${dumps(used)}`);
1083
+ else if (x.tier !== (get(e, "tier") === "T2" ? "T2" : "T1"))
1084
+ broken.push(`${where}: says tier ${cut(pyStr(x.tier, floats, isFloat(floats, x, "tier")), 8)}, the record `
1085
+ + (truthy(get(e, "tier")) ? pyStr(e.tier, floats, isFloat(floats, e, "tier")) : "T1"));
1086
+ else {
1087
+ g.used = used;
1088
+ tiers[x.tier]++;
1089
+ }
1090
+ }
1091
+ }
1092
+ rep.check("intent grants", !bad.length && !broken.length, `${issued} grant(s)`
1093
+ + (issuers.size ? ` by ${cut([...issuers].sort(byCodePoint).join(", "), 200)}` : "")
1094
+ + (selfish ? ` (${selfish} self-approved: issued by the run's own user, which the agent can be)` : "")
1095
+ + (revoked ? `, ${revoked} revoked` : "") + `; ${tiers.T1 + tiers.T2} call(s) released within them (${tiers.T2} at `
1096
+ + `T2, decided and run by an executor or gateway; ${tiers.T1} at T1, on the arguments the harness reported), each `
1097
+ + "re-checked against its grant and its running totals", [...broken, ...bad].slice(0, 20), !broken.length);
1098
+ }
696
1099
  /**
697
1100
  * The ext names this verifier interprets (the VERSIONS rows' "ext" in tracekit/bundle_v2.py): name -> its check, whose
698
- * lines are its own: every other line of the report reads the same without them (docs/format-v2.md §9).
1101
+ * lines are its own: every other line of the report reads the same without them (docs/format-v2.md §9). Names that
1102
+ * share a check are read together, once: a grant, its revocation and the calls it released.
699
1103
  */
700
- const EXT_CHECKS = new Map([["amended", checkAmended],
701
- ["openshell.policy", checkOpenshellPolicy]]);
1104
+ const EXT_CHECKS = new Map([["amended", checkAmended], ["openshell.policy", checkOpenshellPolicy],
1105
+ ["box", checkBox], ["intent.grant", checkGrants], ["intent.revoked", checkGrants], ["grant", checkGrants]]);
702
1106
  const MAX_UNREAD = 20; // `not interpreted` lines, one per ext name; the rest on one line
1107
+ /** A run's problems past which its later records go unchecked: forged records cost a verifier little. */
1108
+ const RUN_PROBLEMS = 20;
703
1109
  /** The ext names an event carries: its `ext` field's keys, and an `ext` record's name. */
704
1110
  const extNames = (e) => [...Object.keys(isObj(get(e, "ext")) ? e.ext : {}),
705
1111
  ...get(e, "type") === "ext" ? [at(at(e, "data"), "name")] : []];
1112
+ const ROWS = VERSIONS_JSON, EXT_SLOT = "1.4.0", EXT_NAME = "ext name ";
1113
+ const usesSlot = (e) => Object.hasOwn(e, "ext") || get(e, "type") === "ext";
1114
+ /** The entries of `row` that `e` uses: `type`, `type.field`, `type.field=value` (by type too) and EXT_NAME + name. */
1115
+ function entries(e, row) {
1116
+ const typ = str(get(e, "type")), data = isObj(get(e, "data")) ? e.data : {};
1117
+ return [...row.types.includes(typ) ? [typ] : [],
1118
+ ...(row.fields[typ] ?? []).filter((f) => Object.hasOwn(data, f)).map((f) => `${typ}.${f}`),
1119
+ ...Object.entries(row.values[typ] ?? {}).filter(([f, vs]) => Object.hasOwn(data, f) && vs.some((v) => v === data[f]))
1120
+ .map(([f]) => `${typ}.${f}=${str(data[f])}`),
1121
+ ...extNames(e).filter((n) => (row.ext ?? []).includes(n)).map((n) => EXT_NAME + str(n))];
1122
+ }
1123
+ /** The verifier_min_version records `events` in `layout` need: the newest row whose entries other than ext names they
1124
+ * use, EXT_SLOT at least when one uses the slot. */
1125
+ function needs(events, layout) {
1126
+ const order = ["1.0.0", ...Object.keys(ROWS)];
1127
+ let need = "1.0.0";
1128
+ for (const [version, row] of Object.entries(ROWS))
1129
+ if (layout.some((x) => (row.layout ?? []).includes(x))
1130
+ || events.some((e) => entries(e, row).some((x) => !x.startsWith(EXT_NAME))))
1131
+ need = version;
1132
+ return events.some(usesSlot) && order.indexOf(need) < order.indexOf(EXT_SLOT) ? EXT_SLOT : need;
1133
+ }
1134
+ /** What makes `events` in `layout` need `version`, with the seqs of the records (the first five). */
1135
+ function raisedBy(events, version, layout) {
1136
+ const seqs = new Map();
1137
+ for (const e of events)
1138
+ for (const x of [...entries(e, ROWS[version] ?? { types: [], fields: {}, values: {} }).filter((x) => !x.startsWith(EXT_NAME)),
1139
+ ...version === EXT_SLOT && usesSlot(e) ? ["ext"] : []]) {
1140
+ if (!seqs.has(x))
1141
+ seqs.set(x, []);
1142
+ seqs.get(x).push(get(e, "seq"));
1143
+ }
1144
+ return [...[...seqs].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([x, s]) => `${x}: seq ${s.slice(0, 5).map(str)
1145
+ .join(", ")}` + (s.length > 5 ? ` and ${s.length - 5} more` : "")),
1146
+ ...layout.filter((x) => (ROWS[version]?.layout ?? []).includes(x))];
1147
+ }
1148
+ /** `verifier minimum`, a warning only when the manifest's verifier_min_version (`said`) is below what the records and
1149
+ * the layout of `names` need: the manifest is never signed, and edited down it lets an older verifier claim more. A
1150
+ * record it can't read (no type, data or seq: other checks fail it) needs nothing. */
1151
+ function checkMinimum(rep, all, names, said) {
1152
+ const events = all.filter((e) => isObj(e) && typeof e.type === "string" && Object.hasOwn(e, "seq") && isObj(e.data)
1153
+ && (e.type !== "ext" || Object.hasOwn(e.data, "name")));
1154
+ const layout = names.some((n) => PART.test(n)) ? ["run parts"] : [], need = needs(events, layout);
1155
+ if (need !== "1.0.0" && newer(need, said)) // a row raised it (0.x bundles need the base)
1156
+ rep.check("verifier minimum", false, `the records need tracekit >= ${need}, the manifest asks for ${said}: a verifier `
1157
+ + `older than ${need} may have read this bundle and claimed more than its records show`, raisedBy(events, need, layout).slice(0, 20), true);
1158
+ }
706
1159
  /**
707
1160
  * A line per ext name the records carry: its EXT_CHECKS check, or a `not interpreted` warning. The records were checked
708
- * like every other (signature, chain, inclusion); `full`: the manifest's advisory verifier_version.
1161
+ * like every other (signature, chain, inclusion); `full`: the manifest's advisory verifier_version; `floats`: the
1162
+ * parser's.
709
1163
  */
710
- function checkExt(rep, events, full) {
1164
+ export async function checkExt(rep, events, full, floats) {
711
1165
  const carry = new Map(); // name -> the events carrying it
712
1166
  for (const e of events)
713
1167
  for (const n of new Set(extNames(e).map((x) => cut(str(x), 64)))) {
@@ -715,13 +1169,23 @@ function checkExt(rep, events, full) {
715
1169
  carry.set(n, []);
716
1170
  carry.get(n).push(e);
717
1171
  }
718
- const later = typeof full === "string" && /^\d{1,9}(\.\d{1,9}){0,2}$/.test(full) && newer(full, VERSION)
1172
+ const later = typeof full === "string" && /^\d{1,9}(\.\d{1,9}){0,2}$/.test(full) && newer(full, READS)
719
1173
  ? `; tracekit >= ${full} checks it` : "";
720
1174
  let shown = 0, more = 0;
1175
+ const done = new Set();
1176
+ // records a check reads beside its names' own: the decisions TK-GRANT names, ext.grant or not
1177
+ const also = new Map([[checkGrants, events.filter(tkGrant)]]);
1178
+ const run = async (f) => {
1179
+ done.add(f);
1180
+ await f(rep, [...new Set([...[...carry].filter(([k]) => EXT_CHECKS.get(k) === f).flatMap(([, v]) => v),
1181
+ ...also.get(f) ?? []])], floats);
1182
+ };
721
1183
  for (const [n, es] of [...carry].sort(byKey)) {
722
1184
  const interpret = EXT_CHECKS.get(n);
723
- if (interpret)
724
- interpret(rep, es);
1185
+ if (interpret) {
1186
+ if (!done.has(interpret))
1187
+ await run(interpret);
1188
+ }
725
1189
  else if (shown < MAX_UNREAD) {
726
1190
  shown++;
727
1191
  rep.check("not interpreted", false, `${es.length} record(s) carry ext.${n}: their signatures, chain and `
@@ -733,6 +1197,9 @@ function checkExt(rep, events, full) {
733
1197
  if (more)
734
1198
  rep.check("not interpreted", false, `${more} more ext name(s), on records whose signatures, chain and inclusion `
735
1199
  + `are checked above; what they mean is not checked${later}`, [], true);
1200
+ for (const [f, extra] of also) // a check whose names no record carries reads what it reads beside them
1201
+ if (extra.length && !done.has(f))
1202
+ await run(f);
736
1203
  }
737
1204
  /** Approvals by people and by agents, each on a line of its own. An agent's approval fails the line unless its run
738
1205
  * holds the approval.request and policy.decision it answered, the signer called the request agent-eligible
@@ -1093,10 +1560,11 @@ function honoured(events, pointers) {
1093
1560
  return problems;
1094
1561
  }
1095
1562
  /** §4: null when `r` is a v2 record signed by one of `keys` (SPKI DER) with an allowed algorithm that is the key's own,
1096
- * else why not. */
1097
- export async function verifyRecord(r, keys, algs) {
1563
+ * else why not. `floats`: where the parser read number tokens with a fraction or exponent (`v` is the integer 2). */
1564
+ export async function verifyRecord(r, keys, algs, floats) {
1098
1565
  if (!isObj(r) || Object.keys(r).length !== 6 || !["v", "event", "hash", "alg", "kid", "sig"].every((k) => Object.hasOwn(r, k))
1099
- || !same(r.v, 2) || !isObj(r.event) || !["hash", "alg", "kid", "sig"].every((k) => typeof r[k] === "string"))
1566
+ || !same(r.v, 2) || floats?.get(r)?.has("v") || !isObj(r.event)
1567
+ || !["hash", "alg", "kid", "sig"].every((k) => typeof r[k] === "string"))
1100
1568
  return "not a v2 record";
1101
1569
  let h;
1102
1570
  try {
@@ -1130,8 +1598,8 @@ export async function verifyRecord(r, keys, algs) {
1130
1598
  return await verifyV2(r.alg, key, bytes(message), sig) ? null : "bad signature";
1131
1599
  }
1132
1600
  /** §7: the run-set line (COMPLETE or INCOMPLETE) and the log tail line. Returns the (seq, hash) of every key.retire the
1133
- * range points to, the highest seq it points to when it starts at registry size 0 (else -1), and the pinned
1134
- * cosignatures of each registry note. */
1601
+ * range points to, the highest seq it points to when it starts at registry size 0 (else -1), the pinned cosignatures of
1602
+ * each registry note, and the records of registry/records.jsonl it checked, each the one its leaf points to. */
1135
1603
  async function checkRunSet(rep, rs, jsonl, file, trust, witnesses, origin, size, runs, included, checkRecord, floats) {
1136
1604
  const problems = [], tsalt = b64decode(at(rs, "tenant_salt"));
1137
1605
  const lo = at(rs, "from"), hi = at(rs, "to"), regOrigin = await registryOrigin(origin, tsalt);
@@ -1141,7 +1609,7 @@ async function checkRunSet(rep, rs, jsonl, file, trust, witnesses, origin, size,
1141
1609
  const span = `registry ${bound("from", lo)}..${bound("to", hi)}`;
1142
1610
  if (![lo, hi].every((n) => Number.isSafeInteger(n)) || floats.get(rs)?.has("from") || floats.get(rs)?.has("to")) {
1143
1611
  rep.check("run-set", false, `INCOMPLETE, ${span}`, ["the registry range is not two integers"]);
1144
- return [[], -1, []];
1612
+ return [[], -1, [], []];
1145
1613
  }
1146
1614
  // the registry notes are signed by the record log's own pinned key, under the registry origin
1147
1615
  const vkeys = [];
@@ -1172,14 +1640,18 @@ async function checkRunSet(rep, rs, jsonl, file, trust, witnesses, origin, size,
1172
1640
  }
1173
1641
  if (problems.length || !(0 <= lo && lo <= hi) || hi === 0) {
1174
1642
  rep.check("run-set", false, `INCOMPLETE, ${span}`, problems.length ? problems : [`bad registry range ${lo}..${hi}`]);
1175
- return [[], -1, regCosigs];
1643
+ return [[], -1, regCosigs, []];
1176
1644
  }
1177
1645
  if (0 < lo && lo < hi && !await verifyConsistency(lo, hi, roots.get(lo), roots.get(hi), list(at(rs, "consistency")).map(b64decode)))
1178
1646
  problems.push(`registry checkpoint ${lo} is not a prefix of ${hi}`);
1647
+ else if (!(0 < lo && lo < hi) && !same(at(rs, "consistency"), [])) // a range from 0, or empty, has no consistency proof
1648
+ problems.push(`a consistency proof for registry ${lo}..${hi}, which has none`);
1179
1649
  const leaves = list(at(rs, "leaves"));
1180
- const pointed = new Map(jsonl("registry/records.jsonl").map((r) => [at(at(r, "event"), "seq"), r]));
1650
+ const lines = jsonl("registry/records.jsonl"), pointed = [];
1181
1651
  if (leaves.length !== hi - lo)
1182
1652
  problems.push(`${hi - lo} leaves in ${lo}..${hi}, ${leaves.length} in the bundle: a leaf is missing`);
1653
+ if (lines.length !== leaves.length) // §9: the record each leaf points to, in leaf order, and nothing else
1654
+ problems.push(`${lines.length} record(s) in registry/records.jsonl for ${leaves.length} leaves: one per leaf, in leaf order`);
1183
1655
  const registered = new Map(), finals = new Map(), retired = [], targets = new Set();
1184
1656
  const gaps = new Map();
1185
1657
  let closed = null, tenant = null, top = -1;
@@ -1190,15 +1662,16 @@ async function checkRunSet(rep, rs, jsonl, file, trust, witnesses, origin, size,
1190
1662
  continue;
1191
1663
  }
1192
1664
  const { type, runHash: rh, logId, seq, hash } = parseLeaf(leaf);
1193
- const r = pointed.get(seq) ?? null, e = r && truthy(r) ? at(r, "event") : r;
1194
- if (r === null || at(r, "hash") !== hash || at(e, "type") !== type || at(e, "log_id") !== logId || !await included(r)
1665
+ top = Math.max(top, seq); // the registry note proves the leaf, whatever record the bundle has for it
1666
+ const r = j < lines.length ? lines[j] : null, e = r && truthy(r) ? at(r, "event") : r;
1667
+ if (r === null || !same(at(e, "seq"), seq) || at(r, "hash") !== hash || at(e, "type") !== type || at(e, "log_id") !== logId || !await included(r)
1195
1668
  || !equal(await runHash(tsalt, text(at(e, "run_id"))), rh)
1196
1669
  || !SIGNER_LEAVES.includes(type) && tenant !== null && !same(tenant, at(e, "tenant"))) {
1197
1670
  problems.push(`leaf ${i} points to a missing or different record (seq ${seq})`);
1198
1671
  continue;
1199
1672
  }
1200
1673
  await checkRecord(r, problems);
1201
- top = Math.max(top, seq);
1674
+ pointed.push(r);
1202
1675
  if (type === "run.registered" || type === "run.final")
1203
1676
  targets.add(await runName(at(e, "tenant"), e.run_id));
1204
1677
  if (type === "run.registered") {
@@ -1242,7 +1715,7 @@ async function checkRunSet(rep, rs, jsonl, file, trust, witnesses, origin, size,
1242
1715
  rep.check("tenant-level gaps", false, `${[...gaps.values()].reduce((a, b) => a + b, 0)} in the range: ${counted}`, [], true);
1243
1716
  rep.check("log tail", truthy(closed), truthy(closed) ? `none: log.closed at seq ${str(closed.seq)} is the last record`
1244
1717
  : `records after tree size ${size} are unproven (no log.closed in the range)`, [], true);
1245
- return [retired, lo === 0 ? top : -1, regCosigs];
1718
+ return [retired, lo === 0 ? top : -1, regCosigs, pointed];
1246
1719
  }
1247
1720
  /** A run's part: the run's file name, the part's number (tracekit/bundle_v2.py PART). */
1248
1721
  const PART = /^(runs\/.+)\.part-([0-9]+)\.jsonl$/;
@@ -1313,8 +1786,10 @@ async function assurance(origin, cosigs, witnesses, trust, algs, selfApproved, r
1313
1786
  /** `x` without control characters and the bidirectional and zero-width format characters that would reorder or hide
1314
1787
  * the text around them, as the report prints bundle-derived strings. */
1315
1788
  export const clean = (x) => x.replace(/[\x00-\x1f\x7f-\x9f\u061c\u200b-\u200f\u202a-\u202e\u2066-\u2069\ufeff]/g, "");
1316
- /** The Assurance line as the reports print it: an assurance level rates only evidence that verified. */
1317
- export const assuranceLine = (rep) => `Assurance: ${rep.integrity === "FAILED" ? "not rated (the bundle failed verification)" : clean(rep.assurance)}.`;
1789
+ /** A failed bundle's assurance: a level rates only evidence that verified. */
1790
+ export const NOT_RATED = "not rated (the bundle failed verification)";
1791
+ /** The Assurance line as the reports print it. */
1792
+ export const assuranceLine = (rep) => `Assurance: ${rep.integrity === "FAILED" ? NOT_RATED : clean(rep.assurance)}.`;
1318
1793
  /** The report as text, as the reference CLI prints it; `clean` drops characters from bundle-derived strings. */
1319
1794
  export function formatReport(rep) {
1320
1795
  let s = "";