@cygnuxlabs/tracekit 1.7.3 → 1.8.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.
@@ -22,16 +22,18 @@
22
22
  import { StrictJSONError, canonicalize, repr as quoted, strictParseBytes } from "./jcs.js";
23
23
  import { ED25519, HYBRID, NoteError, SIGNER_LEAVES, b64decode, bytes, checkWitnesses, equal, keyAlg, leafHash, openNote, parseLeaf, parseVkey, registryOrigin, runHash, sha256hex, spkiKid, unhex, verifyConsistency, verifyInclusion, verifyV2, vkey, } from "./primitives.js";
24
24
  import { Detector } from "./detect.js";
25
+ import { Sources, byCodePoint, runLabels } from "./labels.js";
26
+ import { Budget, Spent } from "./rx.js";
25
27
  import { same, validateEvent } from "./schema.js";
26
28
  import { BadZipFile, MAX_ENTRY, Unusable, readZip } from "./zip.js";
27
29
  import VERSIONS_JSON from "./versions.json" with { type: "json" };
28
30
  export { MAX_ENTRIES, MAX_ENTRY, MAX_TOTAL, Unusable, readZip } from "./zip.js";
29
31
  export { StrictJSONError, canonicalize, strictParse, strictParseBytes } from "./jcs.js";
30
32
  /** This verifier's release (the package's). */
31
- export const VERSION = "1.7.3";
33
+ export const VERSION = "1.8.0";
32
34
  /** The newest bundle format version this verifier reads: the reference's VERSIONS' newest row (tracekit/bundle_v2.py),
33
35
  * or VERSION when later (tracekit/verify/v2.py READS); a bundle needing a later one is UNVERIFIABLE. */
34
- export const READS = "1.7.3";
36
+ export const READS = "1.8.0";
35
37
  /** The browser verifier of the latest release (docs/RELEASING.md). */
36
38
  const PAGE = "https://cygnux-labs.github.io/Tracekit/verify/";
37
39
  export const EXIT_OK = 0, EXIT_FAIL = 1, EXIT_BAD = 2, EXIT_WARN = 3;
@@ -161,15 +163,6 @@ const extend = (to, xs) => {
161
163
  for (const x of xs)
162
164
  to.push(x);
163
165
  };
164
- /** Python's order of strings, by code point (JavaScript's `<` and sort() compare UTF-16 code units, which put a
165
- * character above U+FFFF before one in U+E000..U+FFFF). */
166
- const byCodePoint = (a, b) => {
167
- const unit = (u) => u >= 0xd800 && u < 0xe000 ? u + 0x2000 : u >= 0xe000 ? u - 0x800 : u;
168
- for (let i = 0; i < Math.min(a.length, b.length); i++)
169
- if (a.charCodeAt(i) !== b.charCodeAt(i))
170
- return unit(a.charCodeAt(i)) - unit(b.charCodeAt(i));
171
- return a.length - b.length;
172
- };
173
166
  const byKey = ([a], [b]) => byCodePoint(a, b);
174
167
  const count = (xs) => {
175
168
  const m = new Map();
@@ -192,7 +185,7 @@ async function loadTrust(data, name) {
192
185
  const opt = (o, k) => Object.hasOwn(o, k) ? o[k] : [];
193
186
  const r = isObj(t) ? get(t, "rekor", {}) : null;
194
187
  const ok = isObj(t) && Object.keys(t).every((k) => ["logs", "witnesses", "algs", "witnesses_required", "rekor",
195
- "monitors", "issuers", "analyzers"].includes(k))
188
+ "monitors", "issuers", "analyzers", "policies"].includes(k))
196
189
  && isObj(r) && (!Object.keys(r).length || exactly(r, ["trusted_root", "publishing_key", "class"])
197
190
  && isObj(r.trusted_root) && typeof r.publishing_key === "string" && CLASSES.includes(r.class))
198
191
  && strings(t.logs)
@@ -204,10 +197,19 @@ async function loadTrust(data, name) {
204
197
  && Array.isArray(opt(t, "issuers")) && opt(t, "issuers").every((i) => exactly(i, ["vkey", "issuance_log_vkey"])
205
198
  && Object.values(i).every((v) => typeof v === "string"))
206
199
  && Array.isArray(opt(t, "analyzers"))
207
- && opt(t, "analyzers").every((a) => typeof a === "string" && /^[a-z0-9_]+:[^\n]+$/.test(a));
200
+ && opt(t, "analyzers").every((a) => typeof a === "string" && /^[a-z0-9_]+:[^\n]+$/.test(a))
201
+ && Array.isArray(opt(t, "policies")) && opt(t, "policies").every((x) => typeof x === "string");
208
202
  if (!ok)
209
203
  throw new ValueError(`${name}: not a v2 trust config (logs, witnesses, algs, witnesses_required, rekor, monitors, `
210
- + "issuers, analyzers)");
204
+ + "issuers, analyzers, policies)");
205
+ const known = new Map(); // `policies`: each compiled policy's text, by its policy_hash
206
+ for (const text of opt(t, "policies")) {
207
+ const bytes = new TextEncoder().encode(text);
208
+ if (/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/.test(text)
209
+ || !isObj(strictParseBytes(bytes, new WeakMap())))
210
+ throw new ValueError(`${name}: a policies entry is not a compiled policy (a JSON object's text)`);
211
+ known.set(`sha256:${await sha256hex(bytes)}`, bytes);
212
+ }
211
213
  for (const k of [...t.logs, ...opt(t, "witnesses").map((w) => w.vkey), ...opt(t, "monitors").map((m) => m.vkey),
212
214
  ...opt(t, "issuers").flatMap((i) => Object.values(i))]) {
213
215
  try {
@@ -238,6 +240,7 @@ async function loadTrust(data, name) {
238
240
  t.witnesses_required ??= 0;
239
241
  t.issuers ??= [];
240
242
  t.analyzers ??= [];
243
+ t.policies = known;
241
244
  return t;
242
245
  }
243
246
  /** `s` as one shell argument, as the reference quotes it (shlex.quote; on Windows subprocess.list2cmdline). */
@@ -273,7 +276,8 @@ export async function verify(bundle, trust, names = { bundle: "BUNDLE", trust: "
273
276
  const rep = new Report();
274
277
  let t, files, manifest, v1 = false;
275
278
  if (trust === null) {
276
- t = { logs: [], witnesses: [], algs: ["ed25519"], witnesses_required: 0, issuers: [], analyzers: [] };
279
+ t = { logs: [], witnesses: [], algs: ["ed25519"], witnesses_required: 0, issuers: [], analyzers: [],
280
+ policies: new Map() };
277
281
  rep.check("trust config", false, "none: the checkpoint's signature and its witnesses are not checked, so nothing ties "
278
282
  + "these records to a signer you trust", [], true);
279
283
  }
@@ -549,6 +553,9 @@ async function check(rep, manifest, files, trust, floats) {
549
553
  if (p === `policies/${hex}.json`)
550
554
  policies.set(`sha256:${hex}`, file(p));
551
555
  }
556
+ for (const [h, data] of trust.policies)
557
+ if (!policies.has(h))
558
+ policies.set(h, data); // and the trust config's
552
559
  const open = [...runs.values()].filter((rs) => get(rs.at(-1).event, "type") !== "run.final");
553
560
  rep.integrity = !open.length ? "VERIFIED" : only ? `VERIFIED TO HEAD ${str(get(open[0].at(-1).event, "run_seq"))} (open)`
554
561
  : `VERIFIED (${open.length} run(s) open)`;
@@ -556,6 +563,8 @@ async function check(rep, manifest, files, trust, floats) {
556
563
  // a grant the run's own user issued (intent.grant) approves the calls it releases: a self-approval too
557
564
  const selfApproved = [...typed("approval"), ...typed("ext").filter((e) => get(at(e, "data"), "name") === "intent.grant")]
558
565
  .some((e) => get(at(e, "data"), "self_approved") === true);
566
+ // a label the run's own user cleared on a dev signer: who that is can be the agent, as for a self-approval
567
+ const selfCleared = typed("run.label").some((e) => get(at(e, "data"), "self_cleared") === true);
559
568
  const gaps = (k) => typed("capture.gap").filter((e) => get(at(e, "data"), "kind") === k)
560
569
  .map((e) => `seq ${e.seq}: ${cut(str(get(e.data, "reason")), 200)}`);
561
570
  const against = gaps("executed_against_policy");
@@ -620,6 +629,7 @@ async function check(rep, manifest, files, trust, floats) {
620
629
  checkReviews(rep, runs, trust.analyzers);
621
630
  checkConstraints(rep, runs);
622
631
  checkIncidents(rep, runs, policies, floats);
632
+ checkLabels(rep, runs, policies, floats);
623
633
  const accessed = typed("content.accessed").length, erased = typed("content.erased").length;
624
634
  if (accessed || erased) // signer records of the content vault (docs/privacy.md): who read or erased retained content
625
635
  rep.check("content vault", true, `${accessed} access(es), ${erased} erasure(s) of retained content, each signed by the signer`);
@@ -682,9 +692,10 @@ async function check(rep, manifest, files, trust, floats) {
682
692
  rep.check("key assurance", true, "asserted: the log declares its record keys; none is attested");
683
693
  const algs = new Set([...every, ...keyRecords].map((r) => text(at(r, "alg"))));
684
694
  rep.assurance = !anchored ? "none: no trust config pins a log key or witness"
685
- : await assurance(origin, cosigs, witnesses, trust, algs, selfApproved, regCosigs)
695
+ : await assurance(origin, cosigs, witnesses, trust, algs, selfApproved, regCosigs, selfCleared)
686
696
  + (provenTo < relied ? "; key retirements not proven complete" : "");
687
697
  approvals(rep, runs, policies, floats);
698
+ aiApprovals(rep, runs, policies, floats);
688
699
  const glass = typed("approval").filter((e) => get(at(e, "data"), "break_glass") === true);
689
700
  if (glass.length)
690
701
  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 `
@@ -1102,13 +1113,50 @@ export async function checkGrants(rep, events, floats) {
1102
1113
  + `T2, decided and run by an executor or gateway; ${tiers.T1} at T1, on the arguments the harness reported), each `
1103
1114
  + "re-checked against its grant and its running totals", [...broken, ...bad].slice(0, 20), !broken.length);
1104
1115
  }
1116
+ /**
1117
+ * ext.approval.decision (1.8.0): each approval.consumed names a policy.decision of its own run, tool_call_id and attempt
1118
+ * that comes before it. The signer writes the decision it checked the approval's use against; the check is a warning,
1119
+ * not a failure, when the bundle doesn't hold it (an ext name is non-critical).
1120
+ */
1121
+ export function checkApprovalDecision(rep, events) {
1122
+ const decisions = new Map(), at = (v) => typeof v === "number" ? v : 0;
1123
+ const key = (e, id) => JSON.stringify([get(e, "run_id"), id]);
1124
+ for (const e of events) {
1125
+ const d = get(e, "data");
1126
+ if (get(e, "type") === "policy.decision" && isObj(d) && typeof d.decision_id === "string")
1127
+ decisions.set(key(e, d.decision_id), [...(decisions.get(key(e, d.decision_id)) ?? []), e]);
1128
+ }
1129
+ let n = 0;
1130
+ const bad = [];
1131
+ for (const e of events) {
1132
+ if (!extNames(e).includes("approval.decision"))
1133
+ continue;
1134
+ n++;
1135
+ if (get(e, "type") !== "approval.consumed") {
1136
+ bad.push(e);
1137
+ continue;
1138
+ }
1139
+ const ext = isObj(get(e, "ext")) ? e.ext : {};
1140
+ const did = ext["approval.decision"];
1141
+ const before = typeof did === "string" ? (decisions.get(key(e, did)) ?? [])
1142
+ .filter((d) => at(get(d, "run_seq")) < at(get(e, "run_seq"))) : [];
1143
+ if (typeof did !== "string" || !before.some((d) => (get(d, "tool_call_id") ?? get(get(d, "data"), "tool_use_id")) === get(e, "tool_call_id")
1144
+ && at(get(d, "attempt")) === at(get(e, "attempt"))))
1145
+ bad.push(e);
1146
+ }
1147
+ if (n)
1148
+ rep.check("approval decision", bad.length === 0, bad.length === 0 ? `${n} record(s) name a policy.decision of their run, call id and attempt before them`
1149
+ : `the record(s) at seq ${bad.slice(0, 5).map((e) => str(get(e, "seq"))).join(", ")} carry `
1150
+ + "ext.approval.decision without naming a policy.decision of their run, call id and attempt before it", [], true);
1151
+ }
1105
1152
  /**
1106
1153
  * The ext names this verifier interprets (the VERSIONS rows' "ext" in tracekit/bundle_v2.py): name -> its check, whose
1107
1154
  * lines are its own: every other line of the report reads the same without them (docs/format-v2.md §9). Names that
1108
1155
  * share a check are read together, once: a grant, its revocation and the calls it released.
1109
1156
  */
1110
1157
  const EXT_CHECKS = new Map([["amended", checkAmended], ["openshell.policy", checkOpenshellPolicy],
1111
- ["box", checkBox], ["intent.grant", checkGrants], ["intent.revoked", checkGrants], ["grant", checkGrants]]);
1158
+ ["box", checkBox], ["approval.decision", checkApprovalDecision], ["intent.grant", checkGrants],
1159
+ ["intent.revoked", checkGrants], ["grant", checkGrants]]);
1112
1160
  const MAX_UNREAD = 20; // `not interpreted` lines, one per ext name; the rest on one line
1113
1161
  /** A run's problems past which its later records go unchecked: forged records cost a verifier little. */
1114
1162
  const RUN_PROBLEMS = 20;
@@ -1179,8 +1227,10 @@ export async function checkExt(rep, events, full, floats) {
1179
1227
  ? `; tracekit >= ${full} checks it` : "";
1180
1228
  let shown = 0, more = 0;
1181
1229
  const done = new Set();
1182
- // records a check reads beside its names' own: the decisions TK-GRANT names, ext.grant or not
1183
- const also = new Map([[checkGrants, events.filter(tkGrant)]]);
1230
+ // records a check reads beside its names' own: the decisions TK-GRANT names, ext.grant or not; the decisions
1231
+ // ext.approval.decision names
1232
+ const also = new Map([[checkGrants, events.filter(tkGrant)],
1233
+ [checkApprovalDecision, events.filter((e) => get(e, "type") === "policy.decision")]]);
1184
1234
  const run = async (f) => {
1185
1235
  done.add(f);
1186
1236
  await f(rep, [...new Set([...[...carry].filter(([k]) => EXT_CHECKS.get(k) === f).flatMap(([, v]) => v),
@@ -1264,11 +1314,15 @@ function approvals(rep, runs, policies, floats) {
1264
1314
  + "bundles the policies its records cite");
1265
1315
  continue;
1266
1316
  }
1267
- let asks, flags;
1317
+ let asks, flags, listed, parseAsks;
1268
1318
  try {
1269
1319
  const pol = strictParseBytes(snap, floats);
1270
1320
  asks = new Map(list(get(pol, "ask", [])).map((r) => [at(r, "id"), r]));
1271
1321
  flags = new Set(list(get(pol, "flag", [])).map((r) => at(r, "id")));
1322
+ if (get(pol, "unknown_tools") === "flag")
1323
+ flags.add("TK-UNKNOWN-TOOL");
1324
+ listed = new Set(list(get(get(pol, "approval_agent") ?? {}, "rules") ?? []).filter((r) => APPROVER_RULES.includes(r)));
1325
+ parseAsks = get(pol, "on_parse_error", "ask") === "ask";
1272
1326
  }
1273
1327
  catch {
1274
1328
  problems.push(`${where}: the policy snapshot is not a policy`);
@@ -1276,7 +1330,10 @@ function approvals(rep, runs, policies, floats) {
1276
1330
  }
1277
1331
  for (const rid of get(dec, "rule_ids") ?? []) {
1278
1332
  const approval = get(asks.get(rid) ?? {}, "approval") ?? {};
1279
- if (!flags.has(rid) && (!isObj(approval) || !has(approval, "agent") || approval.passkey === "required"))
1333
+ // an AI approver's rule: one the policy's approval_agent lists (from the reviewed list), held as an ask there,
1334
+ // or TK-SHELL-PARSE where on_parse_error asks
1335
+ const ai = listed.has(rid) && (asks.has(rid) || rid === "TK-SHELL-PARSE" && parseAsks) && has(req, "ai");
1336
+ if (!flags.has(rid) && !ai && (!isObj(approval) || !has(approval, "agent") || approval.passkey === "required"))
1280
1337
  problems.push(`${where}: rule ${cut(str(rid), 64)} does not permit agents`);
1281
1338
  }
1282
1339
  }
@@ -1288,6 +1345,164 @@ function approvals(rep, runs, policies, floats) {
1288
1345
  + "by agents (model output); argument bounds are not checkable offline (salted commitments): audit one with "
1289
1346
  + "`tracekit signer reveal`" + (unchecked.length ? `; agent approval bounds unchecked for ${unchecked.length}` : ""), `${agents} approval(s) answered by agents`), (problems.length ? problems : unchecked).slice(0, 20), !problems.length);
1290
1347
  }
1348
+ /** The rules an operator's approval_agent may list (tracekit/policy2/compile.py APPROVER_RULES). */
1349
+ export const APPROVER_RULES = ["TK-SHELL-PARSE", "TK-A062", "TK-A025"];
1350
+ /** How long a person's answer counts as a precedent (tracekit/signer/pipeline.py PRECEDENT_S). */
1351
+ export const PRECEDENT_S = 30 * 86400;
1352
+ /**
1353
+ * The AI approver's records (docs/approvals.md#the-ai-approver), on a line of their own when the bundle has any: the
1354
+ * `ai` of approval requests, what AI answers relied on (`relied_on`), and its playbook, precedent and circuit-breaker
1355
+ * records. An AI yes that decided (an agent's `approval` that approves, of a request with `ai`) carries `relied_on`
1356
+ * with mode enforce, two answers that approve and a person's precedent, the request's policy hash, and no person's
1357
+ * rejection of a call like it; with the snapshot of the policy it names, none of the labels its run carried is one the
1358
+ * policy's approval_agent run bound names: those the signer says it read (`relied_on.labels`) and those the run's own
1359
+ * run.label records add and clear, replayed up to the yes and up to its consume. That is checked on a line of its own,
1360
+ * `AI run bound`, when any AI yes had a label either way, which also fails when the bundle has no readable snapshot of
1361
+ * the policy such a yes cites (a bundle can leave a snapshot out, never its signed records; a snapshot whose
1362
+ * approval_agent.run isn't an object can't be read). A precedent it names, when the bundle holds it, and any person's rejection the bundle holds of a call like it,
1363
+ * count as the signer counts them: a person's own answer (not a self-approval, not break-glass) to a request with the
1364
+ * same precedent key (its digest), tenant and requester, made in a run clean when asked and when answered (run_clean),
1365
+ * before the answer and at most PRECEDENT_S before it, not revoked as a precedent (precedent.revoked) before it. A
1366
+ * named precedent that doesn't count, or a rejection that does, fails the line; a named precedent the bundle doesn't
1367
+ * hold (often another run's) is counted, not checked.
1368
+ */
1369
+ /**
1370
+ * The run bound (approval_agent.run.clean) of policy snapshot `snap`: [] when the policy has no approval_agent; null
1371
+ * when there is no snapshot or it can't be read, `run` included (not an object, its `clean` not a list of strings).
1372
+ */
1373
+ function runBound(snap, floats) {
1374
+ let aa;
1375
+ try {
1376
+ if (!snap)
1377
+ return null;
1378
+ aa = get(strictParseBytes(snap, floats), "approval_agent") ?? null;
1379
+ }
1380
+ catch {
1381
+ return null;
1382
+ }
1383
+ if (aa !== null && !isObj(aa))
1384
+ return null;
1385
+ const run = aa !== null && has(aa, "run") ? aa.run : {};
1386
+ const clean = isObj(run) ? (has(run, "clean") ? run.clean : []) : null;
1387
+ return Array.isArray(clean) && clean.every((c) => typeof c === "string") ? clean : null;
1388
+ }
1389
+ function aiApprovals(rep, runs, policies, floats) {
1390
+ const events = [...runs.values()].flatMap((rs) => rs.map((r) => r.event)).sort((a, b) => a.seq - b.seq);
1391
+ const asked = new Map(), answered = new Map(), gone = new Map(), broken = [];
1392
+ const boundBroken = [];
1393
+ let yes = 0, shadow = 0, checked = 0, outside = 0, changes = 0, labelled = 0;
1394
+ const key = (tenant, id) => JSON.stringify([tenant ?? null, id ?? null]);
1395
+ // the labels each run's records add and clear, as of each record of note
1396
+ const carried = new Map(), held = new Map();
1397
+ const consumed = new Map();
1398
+ for (const e of events) {
1399
+ const d = e.data, k = key(get(e, "tenant"), get(d, "approval_id"));
1400
+ const rk = key(get(e, "tenant"), get(e, "run_id"));
1401
+ if (!carried.has(rk))
1402
+ carried.set(rk, new Set());
1403
+ const have = carried.get(rk);
1404
+ if (e.type === "run.label" && typeof get(d, "label") === "string") {
1405
+ if (get(d, "action") === "add")
1406
+ have.add(d.label);
1407
+ else
1408
+ have.delete(d.label);
1409
+ }
1410
+ else if (e.type === "approval")
1411
+ held.set(e.seq, new Set(have));
1412
+ else if (e.type === "approval.consumed" && !consumed.has(k))
1413
+ consumed.set(k, new Set(have));
1414
+ if (e.type === "approval.request" && has(d, "ai"))
1415
+ asked.set(k, e);
1416
+ else if (e.type === "approval" && get(d, "approver_kind") !== "agent")
1417
+ answered.set(k, e);
1418
+ else if (["playbook.entry", "precedent.revoked", "approver.enabled", "approver.switched"].includes(e.type)) {
1419
+ changes++;
1420
+ if (e.type === "precedent.revoked" && !gone.has(k))
1421
+ gone.set(k, e.seq);
1422
+ }
1423
+ }
1424
+ const when = (e) => Date.parse(e.ts) / 1000;
1425
+ /** Why person's answer `p` (to request `pa`) doesn't count as a precedent at AI answer `e`, or null. */
1426
+ const discounted = (p, pa, e) => p.data.self_approved ? "was self-approved"
1427
+ : p.data.break_glass ? "was a break-glass answer"
1428
+ : !(pa.data.ai.clean && p.data.run_clean === true) ? "was made in a run that wasn't clean"
1429
+ : p.seq > e.seq ? "came after the answer"
1430
+ : when(e) - when(p) > PRECEDENT_S ? `is more than ${PRECEDENT_S / 86400} days older than the answer`
1431
+ : (gone.get(key(get(e, "tenant"), p.data.approval_id)) ?? e.seq) < e.seq
1432
+ ? "was revoked as a precedent before the answer" : null;
1433
+ for (const e of events) {
1434
+ const d = e.data;
1435
+ if (e.type === "approval.suggested" && has(d, "relied_on"))
1436
+ shadow++;
1437
+ if (!(e.type === "approval" && get(d, "approver_kind") === "agent" && get(d, "decision") === "approve"))
1438
+ continue;
1439
+ const mine = asked.get(key(get(e, "tenant"), get(d, "approval_id")));
1440
+ if (mine === undefined)
1441
+ continue; // an agent approver bounded by argument fields, or a request outside the bundle
1442
+ yes++;
1443
+ const where = `seq ${e.seq}`, x = get(d, "relied_on");
1444
+ if (x === undefined || x.mode !== "enforce"
1445
+ || JSON.stringify((x.answers ?? []).map((a) => a.decision)) !== JSON.stringify(["approve", "approve"])) {
1446
+ broken.push(`${where}: an AI yes that decided without two answers that approve`);
1447
+ continue;
1448
+ }
1449
+ if (!x.precedents.approve.length || x.precedents.reject.length)
1450
+ broken.push(`${where}: an AI yes without a person's precedent, or with a person's rejection of a call like it`);
1451
+ if (x.policy_hash !== mine.data.policy_hash)
1452
+ broken.push(`${where}: an AI yes that cites policy ${x.policy_hash}, not the one its call was held under`);
1453
+ // the run bound of the policy it cites decides whether the labels the run carried let it answer: those the signer
1454
+ // read, and those the run's own records held at the yes and at its consume
1455
+ const ways = [["that carried {}", new Set(x.labels)],
1456
+ ["whose records held {} at the yes", held.get(e.seq)],
1457
+ ["whose records held {} at its consume", consumed.get(key(get(e, "tenant"), get(d, "approval_id"))) ?? new Set()]];
1458
+ if (ways.some(([, ls]) => ls.size)) {
1459
+ labelled++;
1460
+ const bound = runBound(policies.get(x.policy_hash), floats);
1461
+ if (bound === null) {
1462
+ const had = [...new Set(ways.flatMap(([, ls]) => [...ls]))].sort().join(", ");
1463
+ boundBroken.push(`${where}: an AI yes in a run that carried ${had}, under policy ${x.policy_hash}, whose `
1464
+ + "snapshot the bundle doesn't hold (or can't be read): export the run with its policy snapshots");
1465
+ }
1466
+ else {
1467
+ for (const [how, ls] of ways) {
1468
+ const met = [...ls].filter((l) => bound.includes(l)).sort();
1469
+ if (met.length)
1470
+ boundBroken.push(`${where}: an AI yes in a run ${how.replace("{}", met[0])}, which the `
1471
+ + "policy's run bound names");
1472
+ }
1473
+ }
1474
+ }
1475
+ for (const pid of x.precedents.approve) {
1476
+ const k = key(get(e, "tenant"), pid), p = answered.get(k), pa = asked.get(k);
1477
+ if (p === undefined || pa === undefined) {
1478
+ outside++;
1479
+ continue;
1480
+ }
1481
+ checked++;
1482
+ const why = p.data.decision !== "approve" ? "is no person's approval"
1483
+ : pa.data.ai.digest !== mine.data.ai.digest ? "is of another kind of call"
1484
+ : pa.data.requester !== mine.data.requester ? "is another requester's" : discounted(p, pa, e);
1485
+ if (why)
1486
+ broken.push(`${where}: precedent ${cut(str(pid), 64)} ${why}`);
1487
+ }
1488
+ for (const [k, p] of answered) { // a rejection that counted, named or not
1489
+ const pa = asked.get(k), [tenant, pid] = JSON.parse(k);
1490
+ if (tenant === (get(e, "tenant") ?? null) && pa !== undefined && p.data.decision === "reject"
1491
+ && pa.data.ai.digest === mine.data.ai.digest && pa.data.requester === mine.data.requester
1492
+ && discounted(p, pa, e) === null)
1493
+ broken.push(`${where}: a person's rejection of a call like it (${cut(str(pid), 64)}) counted when the AI said yes`);
1494
+ }
1495
+ }
1496
+ if (!asked.size && !shadow && !changes)
1497
+ return; // a bundle without the AI approver keeps the report it always had
1498
+ rep.check("AI approvals", !broken.length, `${yes} AI approval(s) that decided, each with two answers that agree and a `
1499
+ + `person's precedent (${checked} precedent(s) checked in this bundle, ${outside} in runs it doesn't hold); ${shadow} `
1500
+ + `shadow suggestion(s); ${changes} switch, playbook, precedent and circuit-breaker record(s)`, broken.slice(0, 20));
1501
+ if (labelled) {
1502
+ rep.check("AI run bound", !boundBroken.length, `${labelled} AI approval(s) in a run that carried a label, each read `
1503
+ + "against the run bound of the policy snapshot it cites", boundBroken.slice(0, 20));
1504
+ }
1505
+ }
1291
1506
  const CONTAINMENT = ["incident.opened", "incident.updated", "run.held", "run.quarantined", "run.resumed"];
1292
1507
  const FIRES = ["policy.decision", "approval.consumed", "capture.gap", "trace.tamper", "refusal.summary",
1293
1508
  "reconcile.unexplained_effect"];
@@ -1507,6 +1722,59 @@ function checkIncidents(rep, runs, policies, floats) {
1507
1722
  + "signer-asserted, not recomputed (export the run with the signer's config, which bundles the policies its "
1508
1723
  + "records cite)", [...unbundled].sort(byCodePoint).slice(0, 20), true);
1509
1724
  }
1725
+ /** The `run labels` line, as verify/v2.py's _labels: each run's labels replayed under the compiled policies of the
1726
+ * policy_hashes its decisions name (the bundle's or the trust config's), each record under its own; an inherited one
1727
+ * signer-asserted; a `label policies` warning for each policy a decision names that neither carries. */
1728
+ function checkLabels(rep, runs, policies, floats) {
1729
+ let problems = [];
1730
+ const unbundled = new Set(), inherited = [], budget = new Budget();
1731
+ const refused = new Map(); // what verify/v2.py's _labels refuses, by policy and rule
1732
+ let checked = 0, asserted = 0;
1733
+ for (const rs of runs.values()) {
1734
+ const events = rs.map((r) => r.event).filter((e) => isObj(e) && isObj(e.data));
1735
+ const marked = events.some((e) => e.type === "run.label" || e.type === "policy.decision"
1736
+ && Object.hasOwn(e.data, "run_labels"));
1737
+ const hashes = new Set(events.filter((e) => e.type === "policy.decision" && Object.hasOwn(e.data, "policy_hash"))
1738
+ .map((e) => str(e.data.policy_hash)));
1739
+ for (const h of hashes)
1740
+ if (!policies.has(h))
1741
+ unbundled.add(cut(h, 80));
1742
+ if (!hashes.size || [...hashes].some((h) => !policies.has(h))) {
1743
+ if (marked)
1744
+ asserted++;
1745
+ continue;
1746
+ }
1747
+ const srcs = new Map([...hashes].sort(byCodePoint).map((h) => [h, new Sources(strictParseBytes(policies.get(h), floats))]));
1748
+ for (const [h, src] of srcs)
1749
+ for (const rid of src.refused.keys())
1750
+ refused.set(JSON.stringify([cut(h, 80), cut(str(rid), 64)]), [cut(h, 80), cut(str(rid), 64)]);
1751
+ if (marked || [...srcs.values()].some((src) => src.tracked.size)) {
1752
+ checked++;
1753
+ try {
1754
+ extend(problems, runLabels(events, srcs, inherited, budget));
1755
+ }
1756
+ catch (e) {
1757
+ if (!(e instanceof Spent))
1758
+ throw e;
1759
+ problems.push(`${e.message}: the rest of the bundle's runs weren't replayed`);
1760
+ break;
1761
+ }
1762
+ }
1763
+ }
1764
+ problems = [...refused.values()].sort(([a, b], [c, d]) => byCodePoint(a, c) || byCodePoint(b, d))
1765
+ .map(([h, rid]) => `policy ${h}: ${rid} reads the labels with a pattern the signer would refuse (outside the RE2 `
1766
+ + "subset check_pattern accepts, or too large): not replayed").concat(problems);
1767
+ if (checked || asserted)
1768
+ rep.check("run labels", !problems.length, found(problems, `${checked} run(s) replayed under their policies, `
1769
+ + `${asserted} signer-asserted (under a policy not in the bundle)`
1770
+ + (inherited.length ? `; ${inherited.length} label(s) inherited from another run of the requester, `
1771
+ + "signer-asserted (that run's bundle shows its add)" : ""), "run labels"), problems.slice(0, 20));
1772
+ if (unbundled.size)
1773
+ rep.check("label policies", false, `${unbundled.size} policy(ies) neither in the bundle nor the trust config: the `
1774
+ + "labels of the runs decided under them are signer-asserted, not replayed, so one a signer left out wouldn't "
1775
+ + "show (export the run with the signer's config, which bundles the policies its records cite, or add the "
1776
+ + "policy's text to the trust config's `policies`)", [...unbundled].sort(byCodePoint).slice(0, 20), true);
1777
+ }
1510
1778
  /** The problems of one run's records with the holds and quarantines they record (verify/v2.py's _honoured). */
1511
1779
  function honoured(events, pointers) {
1512
1780
  const problems = [], flight = new Set(), asked = new Map(), consumed = new Set();
@@ -1768,14 +2036,14 @@ function level(cosigs, witnesses, trust) {
1768
2036
  }
1769
2037
  /** dev: no pinned witness cosigned, or a self-approval in the run; local: only operator-run ones; witnessed: enough
1770
2038
  * independent ones. A run-set's registry notes cap the level by the same rule. */
1771
- async function assurance(origin, cosigs, witnesses, trust, algs, selfApproved, registryNotes) {
2039
+ async function assurance(origin, cosigs, witnesses, trust, algs, selfApproved, registryNotes, selfCleared = false) {
1772
2040
  let hybrid = false;
1773
2041
  for (const k of trust.logs) {
1774
2042
  const p = await parseVkey(k);
1775
2043
  hybrid ||= p.name === origin && p.type === HYBRID;
1776
2044
  }
1777
2045
  const times = cosigs.filter(([k]) => witnesses.get(k) !== "operator").map(([, ts]) => ts);
1778
- let lvl = selfApproved ? "dev" : level(cosigs, witnesses, trust);
2046
+ let lvl = selfApproved || selfCleared ? "dev" : level(cosigs, witnesses, trust);
1779
2047
  let capped = registryNotes.map((c) => level(c, witnesses, trust))
1780
2048
  .reduce((a, b) => LEVELS.indexOf(b) < LEVELS.indexOf(a) ? b : a, "witnessed");
1781
2049
  if (LEVELS.indexOf(capped) < LEVELS.indexOf(lvl))
@@ -1787,7 +2055,8 @@ async function assurance(origin, cosigs, witnesses, trust, algs, selfApproved, r
1787
2055
  return `${lvl}; records ${[...algs].sort(byCodePoint).join("+")}; checkpoint ${hybrid ? "Ed25519 + SLH-DSA-SHA2-128s" : "Ed25519 only"} `
1788
2056
  + `(${origin})` + (cosigned ? `; cosigned ed25519 by ${cosigned}` : "; no witness cosignature")
1789
2057
  + (times.length ? `; earliest independent anchor ${fmt(times.reduce((a, b) => b < a ? b : a))}` : "")
1790
- + (capped ? `; capped by the run-set's registry notes (${capped})` : "") + (selfApproved ? "; approvals: self" : "");
2058
+ + (capped ? `; capped by the run-set's registry notes (${capped})` : "") + (selfApproved ? "; approvals: self" : "")
2059
+ + (selfCleared ? "; labels: self-cleared" : "");
1791
2060
  }
1792
2061
  /** `x` without control characters and the bidirectional and zero-width format characters that would reorder or hide
1793
2062
  * the text around them, as the report prints bundle-derived strings. */
@@ -0,0 +1,46 @@
1
+ /**
2
+ * tracekit/signer/labels.py's Sources and tracekit/verify/v2.py's _run_labels: which run labels a run's records set,
3
+ * replayed under its compiled policy, for the verifier's `run labels` check (docs/policy-v2.md#run-conditions). A port
4
+ * kept in step with the reference by tests/test_run_conditions.py.
5
+ */
6
+ import { Detector } from "./detect.js";
7
+ import { Budget, Pattern } from "./rx.js";
8
+ type J = any;
9
+ /** Python's order of strings, by code point (JavaScript's `<` and sort() compare UTF-16 code units, which put a
10
+ * character above U+FFFF before one in U+E000..U+FFFF). */
11
+ export declare const byCodePoint: (a: string, b: string) => number;
12
+ /** tracekit/policy2/compile.py subject_labels: {rule id: label} of the rules whose labels a rule on the labels field
13
+ * reads, each rule's non-empty label but a run condition rule's and another labels field rule's. */
14
+ export declare function subjectLabels(policy: J): Map<string, string>;
15
+ /** tracekit/policy2/compile.py labels_subject: the labels `labels` gives `ids`, each once, sorted by code point and
16
+ * joined by a space; "" when none has one. */
17
+ export declare const labelsSubject: (ids: string[], labels: Map<string, string>) => string;
18
+ export declare class Sources {
19
+ when: Map<string, Set<string>>;
20
+ tracked: Set<string>;
21
+ label: Map<string, string>;
22
+ subjectLabels: Map<string, string>;
23
+ onLabels: [string, Pattern, Pattern | null, string | null][];
24
+ refused: Map<string, string>;
25
+ untrusted: string[];
26
+ tools: Record<string, string>;
27
+ spelled: Map<string, string[]>;
28
+ classes: Detector;
29
+ constructor(policy: J);
30
+ /** The names `tools:` lists that `tool` spells, when it lists neither the tool nor a glob that takes it. */
31
+ listed(tool: string): string[];
32
+ untrustedResults(tool: string): boolean;
33
+ ofCall(tool: J, ruleIds: string[]): Set<string>;
34
+ /** The labels record `e` sets; `requested`, `decided`: {tool, rule_ids} of an approval's call and a call's latest
35
+ * decision, or undefined. */
36
+ sets(e: J, requested: (k: J) => J, decided: (k: J) => J): Set<string>;
37
+ }
38
+ /** The policies each of a run's records is replayed under (tracekit/verify/v2.py _policies_at): a decision's own; another
39
+ * record's, that of the decision before it (the first one's before any) and, between two decisions under different
40
+ * policies, the next one's too. */
41
+ export declare function policiesAt(events: J[], srcs: Map<string, Sources>): Sources[][];
42
+ /** The problems of one run's labels under `srcs` (policy_hash -> Sources), each record under its policy
43
+ * (tracekit/verify/v2.py _run_labels); each inherited add of a label its policy reads goes to `inherited` as [where,
44
+ * label, the add it cites]. */
45
+ export declare function runLabels(events: J[], srcs: Map<string, Sources>, inherited: [string, string, J][], budget?: Budget): string[];
46
+ export {};