@rightkit/release 0.6.45 → 0.6.47

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/local-publish.mjs CHANGED
@@ -1,4 +1,5 @@
1
1
  #!/usr/bin/env node
2
+ import { committedCargoWorkspace } from "./committed-cargo-workspace.mjs";
2
3
  // `right-release publish npm|cargo ... --local`: publish ONE @rightkit npm package or crate from the Mac (npm and
3
4
  // crates) or from Windows (crates only) under Adrian's local-build grant (2026-10-14, committed
4
5
  // .rightkit-local-build.json). It does not weaken the publication gate: it runs the unit's own CI tests
@@ -423,14 +424,21 @@ export const GATE_CONFIG_FILES = Object.freeze(["ci/gate.config.json", "ci/asset
423
424
 
424
425
  export { CROSS_TARGETS, ZIG_TARGETS, CROSS_CC_ENV, crossTargetsFor, crossCompileEnv } from "./cross-targets.mjs";
425
426
 
426
- /** The CI gate's commands for one unit (scripts/ci/gate.mjs npmGate/rustGate), mirrored exactly. */
427
+ /** Build a selected npm package and its workspace dependency closure, in dependency order. */
428
+ export function npmBuildClosureArgs(unit) {
429
+ if (typeof unit !== "string" || unit.length > 214 || !/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/.test(unit) || unit.includes("...")) throw new Error("invalid npm package name for workspace build");
430
+ // Adapter registration accepts --if-present after run, not as a leading option.
431
+ return ["-r", "--workspace-concurrency=1", "--filter", `${unit}...`, "run", "--if-present", "build"];
432
+ }
433
+
434
+ /** Local compile and test commands for one unit, aligned with CI's selected-unit coverage. */
427
435
  export function localTestPlan({ kind, unit, dir, config, manifest, batch = false, platform = "darwin" }) {
428
436
  if (kind === "npm") {
429
437
  // End-to-end tests only (Adrian, 2026-11-03): an npm unit with no test script has no test step, as a crate with no test qualifies on its other steps.
430
438
  return {
431
439
  id: `npm:${dir}`, featureLabels: ["default"],
432
440
  steps: [
433
- { command: "pnpm", args: ["-r", "--workspace-concurrency=1", "run", "build"], test: false },
441
+ { command: "pnpm", args: npmBuildClosureArgs(unit), test: false },
434
442
  ...(manifest?.scripts?.test ? [{ command: "pnpm", args: ["--dir", dir, "run", "test"], test: true }] : []),
435
443
  ],
436
444
  };
@@ -470,33 +478,77 @@ export function localTestPlan({ kind, unit, dir, config, manifest, batch = false
470
478
  return { id: `rust:${unit}`, featureLabels: featureSets.map((features) => features.join(" ") || "default"), consumerRows: consumers, steps };
471
479
  }
472
480
 
481
+ /** Publisher compile-stage obligations. Caller supplies authenticated source policy and execution environment. */
482
+ export function compileRequirements({ kind, unit, dir, config, manifest, platform = "darwin", workspace, env, assetGated = {}, allowIgnored = false, allowIgnoredUnits = [], jobs, formatProven = false }) {
483
+ if (kind !== "cargo" && kind !== "npm") throw new Error(`unsupported compile requirement kind ${kind}`);
484
+ if (kind === "cargo" && (typeof workspace !== "string" || !workspace)) throw new Error("authenticated Cargo workspace is required");
485
+ if (!env || typeof env !== "object" || Array.isArray(env)) throw new Error("publisher execution environment is required");
486
+ if (!Array.isArray(allowIgnoredUnits)) throw new Error("allowIgnoredUnits must be an array");
487
+ const plan = localTestPlan({ kind, unit, dir, config, manifest, batch: false, platform });
488
+ const gated = Object.hasOwn(assetGated[kind === "npm" ? "npm" : "crates"] ?? {}, unit);
489
+ const executionEnv = testEnv({ env }, gated);
490
+ const configReason = kind === "cargo" && typeof config?.rust?.[unit]?.allowIgnored === "string" ? config.rust[unit].allowIgnored.trim() : "";
491
+ const ignoredAllowed = Boolean(allowIgnored || allowIgnoredUnits.includes(unit) || configReason);
492
+ const steps = [...plan.steps];
493
+ // A gate run that already passed class A's rustfmt rows over every Rust file of this same snapshot passes formatProven: the crate's own
494
+ // `cargo fmt -p <crate> --check` would repeat that check, one crate at a time (a 140-crate unit list spent minutes on it, 2026-11-05).
495
+ if (kind === "cargo" && !formatProven) steps.unshift({ command: "cargo", args: qualifyFmtArgs(unit), test: false });
496
+ const requirements = [];
497
+ const add = (requirement) => requirements.push({ id: `publisher:${kind}:${unit}:${requirements.length}`, ...requirement, coverageKey: sha256(JSON.stringify(requirement)) });
498
+ if (kind === "cargo") add({ workspace, cwd: dir, executable: null, internal: "scanCrateForSecrets", argv: [dir], env: {}, phase: "check" });
499
+ for (const step of steps) {
500
+ const consumer = step.command === "cargo" && step.args.includes("--manifest-path");
501
+ const cwd = consumer || kind === "npm" ? "." : dir;
502
+ const manifestIndex = step.args.indexOf("--manifest-path");
503
+ const requirementWorkspace = consumer ? path.posix.dirname(step.args[manifestIndex + 1]) : kind === "cargo" ? workspace : ".";
504
+ const argv = step.command === "cargo" ? oneOutput(withCargoJobs(step.args, jobs), { platform }) : [...step.args];
505
+ add({ workspace: requirementWorkspace, cwd, executable: step.command, argv, env: { ...executionEnv, ...(step.env ?? {}) }, phase: step.test ? "test" : "compile" });
506
+ }
507
+ return {
508
+ unit, requirements, consumerWorkspaces: [...new Set((plan.consumerRows ?? []).map((row) => path.posix.dirname(row.manifestPath)))],
509
+ verdict: { source: "judgeUnit", allowNoTests: true, allowIgnored: ignoredAllowed, allowIgnoredReason: configReason || null, allowMissingAssets: gated, requireZeroFailed: true, rejectTruncatedTestOutput: true, brokerCompiledTestsRunOutsideBroker: true },
510
+ sourceObligations: { cleanUnitAndGateConfig: true, cleanTrackedConsumerManifestsAndLocks: true },
511
+ };
512
+ }
513
+
473
514
  /**
474
515
  * The clippy invocations that replace each crate's own `cargo clippy -p <crate> --no-deps --all-targets
475
- * <featureSets[0]> -- -D warnings`: same flags and lint level, so the same lints on the same code. Every crate is its own
476
- * Cargo workspace with its own Cargo.lock (rightkit#1285), so cargo runs in that crate's directory and one invocation never
477
- * names two crates: one `-p <crate>` run per crate and feature set, in layer order. Crates with a different
478
- * RIGHTKIT_REQUIRE_ASSETS (asset-gated) keep their own environment.
516
+ * <features> -- -D warnings`: same flags and lint level, so the same lints on the same code. RightKit is one Cargo
517
+ * workspace (GC-T24, rightkit#1505 superseding #1285's one workspace per crate), so crates whose invocation would
518
+ * differ only in `-p <crate>` share ONE invocation naming every crate, run at the workspace root. Grouping is exact:
519
+ * same feature set, same target (or none), same asset-gated environment. A feature set that names crate-specific
520
+ * features (`--features`/`-F <names>`) never groups: one invocation would apply those names to every crate in it, so
521
+ * such a crate keeps its own invocation, exactly as deterministic-scans.mjs `batchable` refuses the same sets.
522
+ * Feature unification inside one invocation is the GC-I11 caveat the scan batching already carries; the members of
523
+ * a group share the invocation's verdict through the batch receipt, and each crate's tested/check/doc steps still
524
+ * run per crate in its own publish flow.
479
525
  */
480
- export function batchClippyInvocations(layer, { featuresOf = () => [], featureSetsOf = (unit) => [featuresOf(unit)], assetGatedOf = () => false, crossTargetsOf = () => [] } = {}) {
526
+ export function batchClippyInvocations(layer, { featuresOf = () => [], featureSetsOf = (unit) => [featuresOf(unit)], assetGatedOf = () => false, crossTargetsOf = () => [], workspaceOf = () => "." } = {}) {
481
527
  const invocations = [];
528
+ const groups = new Map(); // group key -> invocation being built (its index in `invocations` stays at first sight)
529
+ const namesFeatures = (features) => features.some((f) => f === "--features" || f === "-F" || f.startsWith("--features=") || /^-F.+/.test(f));
530
+ const add = (unit, features, target) => {
531
+ const env = target ? crossCompileEnv(target) : null;
532
+ if (target && !env) throw new Error(`RK_CROSS_CC_UNPROVISIONED: the zig C toolchain for ${target} is not provisioned; run node scripts/ci/provision-zig.mjs <managed data root>/zig (or set RIGHTKIT_CROSS_CC_DIR)`);
533
+ const assetGated = assetGatedOf(unit);
534
+ const workspace = workspaceOf(unit);
535
+ const tail = ["--message-format=json-render-diagnostics", "--no-deps", "--all-targets", ...(target ? ["--target", target] : []), ...features, "--", "-D", "warnings"];
536
+ if (namesFeatures(features)) { invocations.push({ crates: [unit], workspace, assetGated, ...(env ? { env } : {}), args: ["clippy", "-p", unit, ...tail] }); return; }
537
+ const key = JSON.stringify([workspace, features, target, assetGated, env]);
538
+ const existing = groups.get(key);
539
+ if (existing) { existing.crates.push(unit); existing.args.splice(1 + 2 * (existing.crates.length - 1), 0, "-p", unit); return; }
540
+ const invocation = { crates: [unit], workspace, assetGated, ...(env ? { env } : {}), args: ["clippy", "-p", unit, ...tail] };
541
+ groups.set(key, invocation);
542
+ invocations.push(invocation);
543
+ };
482
544
  for (const unit of layer) {
483
545
  // Every tested feature set of a crate is linted, in order; identical sets of one crate collapse to one run.
484
546
  const sets = featureSetsOf(unit) ?? [[]];
485
547
  const unique = sets.filter((set, index) => sets.findIndex((other) => JSON.stringify(other ?? []) === JSON.stringify(set ?? [])) === index);
486
548
  for (const set of unique) {
487
549
  const features = set ?? [];
488
- invocations.push({
489
- crates: [unit], assetGated: assetGatedOf(unit),
490
- args: ["clippy", "-p", unit, "--message-format=json-render-diagnostics", "--no-deps", "--all-targets", ...features, "--", "-D", "warnings"],
491
- });
492
- for (const target of crossTargetsOf(unit)) {
493
- const env = crossCompileEnv(target);
494
- if (!env) throw new Error(`RK_CROSS_CC_UNPROVISIONED: the zig C toolchain for ${target} is not provisioned; run node scripts/ci/provision-zig.mjs <managed data root>/zig (or set RIGHTKIT_CROSS_CC_DIR)`);
495
- invocations.push({
496
- crates: [unit], assetGated: assetGatedOf(unit), ...(env ? { env } : {}),
497
- args: ["clippy", "-p", unit, "--message-format=json-render-diagnostics", "--no-deps", "--all-targets", "--target", target, ...features, "--", "-D", "warnings"],
498
- });
499
- }
550
+ add(unit, features, null);
551
+ for (const target of crossTargetsOf(unit)) add(unit, features, target);
500
552
  }
501
553
  }
502
554
  return invocations;
@@ -735,7 +787,6 @@ async function* publishUnitStages(parsed, deps, batch) {
735
787
  if (feed.stagedNpm?.[unit] !== version && feed.registry?.npm?.[unit] !== version) refuse(`${unit}@${version}: stage the version in ${feedPath} and commit it before qualification`);
736
788
  }
737
789
  }
738
- if (await (deps.registryHas ?? defaultRegistryHas)({ kind, name: unit, version })) refuse(`${unit}@${version} is already on the ${kind === "npm" ? "npm" : "crates.io"} registry; bump the version`);
739
790
  log(`[right-release] local publish ${kind}:${unit}@${version} at ${head.slice(0, 12)} (local-build grant, ${LOCAL_HOST_POLICIES[platform]} policy)`);
740
791
 
741
792
  // 2. The unit's own tests, exactly as the CI gate defines them.
@@ -805,6 +856,10 @@ async function* publishUnitStages(parsed, deps, batch) {
805
856
  const packageEnv = yield { stage: "compile", kind, name: unit, version, commit: head, brokerRequests: brokerRequests.splice(0) };
806
857
  if (packageEnv) Object.assign(env, testEnv({ env: packageEnv }, isAssetGated));
807
858
 
859
+ // Availability is a publication/qualification precondition, not a compile precondition.
860
+ // A gate that stops at compile never advances past the yield above and never needs a new version.
861
+ if (await (deps.registryHas ?? defaultRegistryHas)({ kind, name: unit, version })) refuse(`${unit}@${version} is already on the ${kind === "npm" ? "npm" : "crates.io"} registry; bump the version`);
862
+
808
863
  // 3. Pack the artifact and hash it.
809
864
  // An npm pack is a broker job whose --pack-destination the adapter accepts only as an empty child of the host's scratch root, so the
810
865
  // tarball goes there (the workspace rule for run output) rather than in the OS temp directory; the package itself is packed from the
@@ -994,22 +1049,43 @@ async function runLocalPublishBatch(parsed, deps) {
994
1049
  if (published.length) refuse(`already on the crates.io registry: ${published.join(", ")}; bump the version or remove them from the batch`);
995
1050
  log(`[right-release] local publish cargo batch: ${crates.length} crate(s) in ${layers.length} layer(s) at ${head.slice(0, 12)}, concurrency ${concurrency} (local-build grant, ${LOCAL_HOST_POLICIES[platform]} policy)`);
996
1051
 
997
- // 3. Batch-level checks, once, at the batch commit. Each is recorded in every crate's evidence.
1052
+ // Resolve membership independently from selected commit blobs, never from the receipt or live files.
998
1053
  const env = testEnv(deps, false);
1054
+ const workspaces = {};
1055
+ const manifests = new Map();
1056
+ const readCommittedManifest = (file) => {
1057
+ if (manifests.has(file)) return manifests.get(file);
1058
+ const entry = git(["ls-tree", "--name-only", head, "--", file], workspaceRoot);
1059
+ if (entry === null) refuse(`cannot inspect committed ${file}`);
1060
+ if (entry !== "" && entry !== file) refuse(`ambiguous committed ${file}`);
1061
+ const contents = entry === "" ? null : git(["show", `${head}:${file}`], workspaceRoot);
1062
+ if (entry !== "" && contents === null) refuse(`cannot read committed ${file}`);
1063
+ manifests.set(file, contents);
1064
+ return contents;
1065
+ };
1066
+ for (const unit of crates) {
1067
+ try { workspaces[unit] = committedCargoWorkspace({ unitDir: `crates/${unit}`, read: readCommittedManifest }); }
1068
+ catch (error) { refuse(`cannot resolve committed Cargo workspace for ${unit}: ${error.message}`); }
1069
+ }
1070
+ const workspacePaths = [...new Set(Object.values(workspaces))].flatMap((workspace) => [path.posix.join(workspace, "Cargo.toml"), path.posix.join(workspace, "Cargo.lock")]);
1071
+ const workspaceDirty = git(["status", "--porcelain", "--", ...workspacePaths], workspaceRoot);
1072
+ if (workspaceDirty === null || workspaceDirty !== "") refuse(`Cargo workspace manifests or locks are not clean: ${workspaceDirty ?? "cannot read git status"}`);
1073
+
1074
+ // Each row records the workspace and exact units covered by that invocation.
999
1075
  const stamp = { commit: head, tree };
1000
1076
  const checks = []; const commands = [];
1001
- // One recorded check; `cwds` are the crate workspaces it runs in (each crate is its own Cargo workspace, #1285), once each.
1002
- const batchCheck = async (name, command, args, crateNames, runEnv = env, cwds = [workspaceRoot]) => {
1077
+ const batchCheck = async (name, command, args, crateNames, runEnv = env, workspace = ".") => {
1003
1078
  const text = `${command} ${args.join(" ")}`;
1004
- log(`[right-release] batch ${name}: ${text}`);
1005
- for (const cwd of cwds) {
1006
- const result = await run(command, command === "cargo" ? oneOutput(args, { platform }) : args, { cwd, env: runEnv });
1007
- if (result.error || result.status !== 0) refuse(`batch ${name} failed (${result.error?.message ?? `exit ${result.status}`}): ${text}${cwd === workspaceRoot ? "" : ` (in ${path.relative(workspaceRoot, cwd)})`}\n${tail(`${result.stdout ?? ""}\n${result.stderr ?? ""}`)}`);
1008
- }
1009
- checks.push({ name, command: text, ok: true, ...stamp, ...(crateNames ? { crates: crateNames } : {}) });
1079
+ const cwd = path.resolve(workspaceRoot, workspace);
1080
+ log(`[right-release] batch ${name}: ${text} (in ${workspace})`);
1081
+ const result = await run(command, command === "cargo" ? oneOutput(args, { platform }) : args, { cwd, env: runEnv });
1082
+ if (result.error || result.status !== 0) refuse(`batch ${name} failed (${result.error?.message ?? `exit ${result.status}`}): ${text} (in ${workspace})\n${tail(`${result.stdout ?? ""}\n${result.stderr ?? ""}`)}`);
1083
+ checks.push({ name, command: text, ok: true, ...stamp, crates: crateNames, workspace });
1010
1084
  commands.push(text);
1011
1085
  };
1012
- await batchCheck("fmt", "cargo", ["fmt", "--all", "--check"], undefined, env, crates.map((unit) => path.join(workspaceRoot, "crates", unit)));
1086
+ for (const workspace of new Set(Object.values(workspaces))) {
1087
+ await batchCheck("fmt", "cargo", ["fmt", "--all", "--check"], crates.filter((unit) => workspaces[unit] === workspace), env, workspace);
1088
+ }
1013
1089
  log("[right-release] batch secret-scan: crate directories of the batch");
1014
1090
  const scan = deps.scanSecrets ?? scanCrateForSecrets;
1015
1091
  const violations = crates.flatMap((unit) => scan(path.join(workspaceRoot, "crates", unit)).map((file) => `${unit}: ${file}`));
@@ -1019,12 +1095,11 @@ async function runLocalPublishBatch(parsed, deps) {
1019
1095
  commands.push(scanText);
1020
1096
  const featureSetsOf = (unit) => gateConfig?.rust?.[unit]?.featureSets ?? [[]];
1021
1097
  for (const layer of layers) {
1022
- for (const invocation of batchClippyInvocations(layer, { featureSetsOf, assetGatedOf: isAssetGated, crossTargetsOf: (unit) => crossTargetsFor(gateConfig?.rust?.[unit], platform) })) {
1023
- // A cross-target invocation carries the zig C toolchain environment for its target (crossCompileEnv).
1024
- await batchCheck("clippy", "cargo", invocation.args, invocation.crates, { ...testEnv(deps, invocation.assetGated), ...(invocation.env ?? {}) }, invocation.crates.map((unit) => path.join(workspaceRoot, "crates", unit)));
1098
+ for (const invocation of batchClippyInvocations(layer, { featureSetsOf, assetGatedOf: isAssetGated, crossTargetsOf: (unit) => crossTargetsFor(gateConfig?.rust?.[unit], platform), workspaceOf: (unit) => workspaces[unit] })) {
1099
+ await batchCheck("clippy", "cargo", invocation.args, invocation.crates, { ...testEnv(deps, invocation.assetGated), ...(invocation.env ?? {}) }, invocation.workspace);
1025
1100
  }
1026
1101
  }
1027
- const receipt = { id: `batch-${head.slice(0, 12)}-${sha256(JSON.stringify(layers)).slice(0, 8)}`, ...stamp, crates, checks };
1102
+ const receipt = { id: `batch-${head.slice(0, 12)}-${sha256(JSON.stringify(layers)).slice(0, 8)}`, ...stamp, crates, workspaces, checks };
1028
1103
 
1029
1104
  // 4. Publish layer by layer. A crate's publish returns only after its registry readback proved the exact
1030
1105
  // checksum visible in the index, so layer N+1 starts only once every layer-N dependency is visible.
package/managed-cargo.mjs CHANGED
@@ -202,6 +202,17 @@ export function directCargoPath({ env = process.env, exists = existsSync, readHe
202
202
  return { path: kept.join(win ? ";" : ":"), dropped, cargo };
203
203
  }
204
204
 
205
+ /**
206
+ * GC-A11 (Adrian, 2026-11-02: "Class a never in the broker. Any cargo things that are cheap and non compiling are in class a, can run outside the
207
+ * broker"): the environment for a NON-COMPILING cargo call (metadata, locate-project, tree, package --no-verify) on any host: PATH with the broker's
208
+ * own toolchain first and every RustRight shim dropped, so `cargo` is the real binary. The broker refuses such a request from inside a snapshot.
209
+ */
210
+ export function nonCompilingCargoEnv(env = process.env, platform = process.platform) {
211
+ const pathKey = platform === "win32" ? (Object.keys(env).find((k) => k.toUpperCase() === "PATH") ?? "Path") : "PATH";
212
+ const direct = directCargoPath({ env: { ...env, PATH: env[pathKey] }, platform, gateWrappers: true });
213
+ return { ...env, [pathKey]: direct.path };
214
+ }
215
+
205
216
  /** `env` for a direct host: PATH without RustRight shim directories. Unchanged on Mac, Windows and a declared Linux broker route. */
206
217
  export function directCargoEnv(env = process.env, platform = process.platform, exists = existsSync) {
207
218
  if (!directHost(platform, env)) return env; // Mac, Windows, and a Linux host that declared a broker route (no direct cargo there)
@@ -0,0 +1,95 @@
1
+ // Narrow reuse identity for plain Node syntax checks. Admission still binds the
2
+ // complete raw Class A environment; the host's runtime libraries remain under
3
+ // the same trusted-host assumption as other locally executed tools.
4
+ import fs from 'node:fs';
5
+ import path from 'node:path';
6
+ import crypto from 'node:crypto';
7
+ import { fileURLToPath } from 'node:url';
8
+
9
+ const hash = (data) => crypto.createHash('sha256').update(data).digest('hex');
10
+
11
+ // Pure data transformation: no values are persisted, only the resulting hash.
12
+ export function nodeCheckFingerprint(input) {
13
+ return hash(JSON.stringify(input));
14
+ }
15
+
16
+ export function writeNodeCheckDiagnostic(dir, record) {
17
+ let temp;
18
+ try {
19
+ const hex = (s) => typeof s === 'string' && /^[0-9a-f]{64}$/.test(s);
20
+ const scalar = ['key', 'tree', 'source', 'gate', 'gatePackage', 'helper', 'node', 'executable', 'runtime', 'cwd', 'scan', 'normalizedEnvironment', 'overriddenEnvironment'];
21
+ const names = ['schema', ...scalar, 'ancestors', 'environment'];
22
+ if (!record || Object.keys(record).length !== names.length || Object.keys(record).some((k) => !names.includes(k)) || record.schema !== 'rightkit.node-check-components/1' || !scalar.every((k) => hex(record[k]))) return;
23
+ const pairs = (rows, nullable) => Array.isArray(rows) && rows.length <= 4096 && rows.every((r) => Array.isArray(r) && r.length === 2 && hex(r[0]) && (hex(r[1]) || (nullable && r[1] === null)));
24
+ if (!pairs(record.ancestors, true) || !pairs(record.environment, false) || !path.isAbsolute(dir)) return;
25
+ const scratch = fs.realpathSync(process.platform === 'win32' ? 'D:\\scratch' : '/Volumes/D/scratch');
26
+ const target = fs.realpathSync(dir);
27
+ if (!(target === scratch || target.startsWith(scratch + path.sep)) || !fs.statSync(target).isDirectory()) return;
28
+ const file = path.join(target, `node-check-${process.pid}-${crypto.randomBytes(8).toString('hex')}.json`);
29
+ temp = `${file}.tmp`;
30
+ fs.writeFileSync(temp, JSON.stringify(record), { flag: 'wx' });
31
+ fs.renameSync(temp, file);
32
+ } catch { if (temp) { try { fs.unlinkSync(temp); } catch {} } }
33
+ }
34
+
35
+ export function createNodeCheckCacheDigest({ snapshot, tree, files, gateIdentity, gatePackage = path.dirname(fileURLToPath(import.meta.url)), nodePath, onReject = () => {}, onDiagnostic = null, diagnosticScanId = null }) {
36
+ const reject = (reason, id) => { try { onReject(reason, id); } catch {} return null; };
37
+ let captured = false;
38
+ try {
39
+ const root = fs.realpathSync(snapshot);
40
+ const executable = fs.realpathSync(nodePath);
41
+ const nodeHash = hash(fs.readFileSync(executable));
42
+ const helperHash = hash(fs.readFileSync(fileURLToPath(import.meta.url)));
43
+ const walkGate = (dir) => fs.readdirSync(dir, { withFileTypes: true }).flatMap((e) => (e.name === 'node_modules' || e.name.startsWith('.') ? [] : e.isDirectory() ? walkGate(path.join(dir, e.name)) : [path.join(dir, e.name)]));
44
+ const gateFiles = walkGate(gatePackage).sort().map((f) => [path.relative(gatePackage, f), hash(fs.readFileSync(f))]);
45
+ const gatePackageHash = nodeCheckFingerprint(gateFiles);
46
+ const committed = new Set(files);
47
+ const ancestors = [];
48
+ for (let dir = path.dirname(root);;) {
49
+ const file = path.join(dir, 'package.json');
50
+ try { ancestors.push([file, hash(fs.readFileSync(file))]); }
51
+ catch (e) { if (e.code !== 'ENOENT' && e.code !== 'ENOTDIR') throw e; ancestors.push([file, null]); }
52
+ const parent = path.dirname(dir); if (parent === dir) break; dir = parent;
53
+ }
54
+ return (scan, { childEnv, cwd, command, shimProof = null }) => {
55
+ try {
56
+ const file = typeof scan.id === 'string' && scan.id.startsWith('node-check:') ? scan.id.slice(11) : null;
57
+ if (!file || !committed.has(file) || scan.class !== 'A' || scan.tool !== 'node' || scan.root !== 'content' || scan.cwd || scan.executes || scan.internal || scan.runOutside || scan.deferred || scan.requires?.length || Object.keys(scan.env ?? {}).some((name) => name !== 'RK_SNAPSHOT_TARGETS') || !Array.isArray(scan.args) || scan.args.length !== 2 || scan.args[0] !== '--check' || scan.args[1] !== file) return reject('row-shape', scan.id);
58
+ if (fs.realpathSync(cwd) !== root || fs.realpathSync(command) !== executable) return reject('runtime-path', scan.id);
59
+ const target = path.resolve(root, file);
60
+ if (!target.startsWith(root + path.sep) || fs.realpathSync(target) !== target || !fs.lstatSync(target).isFile()) return reject('source-path', scan.id);
61
+ // These two handles identify the surrounding run, not a Node syntax
62
+ // check; options and preloads remain forbidden below.
63
+ const rows = Object.entries(childEnv).filter(([k, v]) => v !== undefined && v !== null && k !== 'RIGHTKIT_BUILD_OWNERSHIP' && k !== 'CODEX_TOOL_CALL_ID').sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
64
+ // Options, preloads, and dynamic-loader overrides can read unbounded
65
+ // external files, so no cache key is issued when any are present.
66
+ const active = (pattern) => rows.some(([k, v]) => pattern.test(k) && String(v) !== '');
67
+ if (active(/^NODE_OPTIONS$/i)) return reject('node-options', scan.id);
68
+ // This host integration variable configures the computer-use REPL,
69
+ // not Node's CLI. Its value still participates in the fingerprint.
70
+ if (rows.some(([k, v]) => /^NODE_/i.test(k) && k !== 'NODE_REPL_TRUSTED_BROWSER_CLIENT_SHA256S' && String(v) !== '')) return reject('node-environment', scan.id);
71
+ if (active(/^(LD_|DYLD_)/i)) return reject('loader-environment', scan.id);
72
+ if (active(/^(OPENSSL_CONF(?:_INCLUDE)?|OPENSSL_MODULES|SSL_CERT_(?:FILE|DIR)|ICU_DATA)$/i)) return reject('runtime-config-environment', scan.id);
73
+ let environment = rows;
74
+ let overridden = [];
75
+ if (shimProof) {
76
+ const { shim, bin, sentinel, originalEnv } = shimProof;
77
+ if (!originalEnv || typeof originalEnv !== 'object' || !path.isAbsolute(shim) || !path.isAbsolute(bin) || path.dirname(shim) !== bin || !sentinel || sentinel !== path.join(path.dirname(bin), 'unbound')) return reject('shim-proof', scan.id);
78
+ const pathKey = Object.keys(originalEnv).find((k) => k.toUpperCase() === 'PATH') ?? 'PATH';
79
+ const originalPath = originalEnv[pathKey] ?? '';
80
+ const expectedSentinel = path.join(sentinel, hash(scan.id).slice(0, 16));
81
+ if (childEnv.CARGO !== shim || childEnv[pathKey] !== `${bin}${path.delimiter}${originalPath}` || childEnv.CARGO_TARGET_DIR !== expectedSentinel || childEnv.CARGO_BUILD_TARGET_DIR !== expectedSentinel) return reject('shim-proof', scan.id);
82
+ environment = rows.map(([k, v]) => k === 'CARGO' ? [k, { generated: 'cargo-wrapper' }] : k === pathKey ? [k, { generated: 'wrapper-path', original: originalPath }] : (k === 'CARGO_TARGET_DIR' || k === 'CARGO_BUILD_TARGET_DIR') ? [k, { generated: 'scan-sentinel' }] : [k, v]);
83
+ overridden = ['CARGO', 'CARGO_TARGET_DIR', 'CARGO_BUILD_TARGET_DIR'].map((k) => [k, Object.hasOwn(originalEnv, k), originalEnv[k] ?? null]);
84
+ }
85
+ const source = hash(fs.readFileSync(target));
86
+ const key = nodeCheckFingerprint({ schema: 'rightkit.node-check-cache/2', tree, root, file, source, gateIdentity, gatePackageHash, helperHash, executable, nodeHash, nodeVersion: process.version, platform: process.platform, arch: process.arch, ancestors, argv: scan.args, id: scan.id, cwd: root, environment, overridden });
87
+ if (!captured && typeof onDiagnostic === 'function' && scan.id === diagnosticScanId) {
88
+ captured = true;
89
+ try { onDiagnostic({ schema: 'rightkit.node-check-components/1', key, tree: hash(String(tree)), source, gate: hash(String(gateIdentity)), gatePackage: gatePackageHash, helper: helperHash, node: nodeHash, executable: hash(executable), runtime: nodeCheckFingerprint([process.version, process.platform, process.arch]), cwd: hash(root), scan: nodeCheckFingerprint([scan.id, scan.args]), normalizedEnvironment: nodeCheckFingerprint([environment, overridden]), overriddenEnvironment: nodeCheckFingerprint(overridden), ancestors: ancestors.map(([name, value]) => [hash(name), value === null ? null : hash(value)]), environment: rows.map(([name, value]) => [hash(name), hash(String(value))]) }); } catch {}
90
+ }
91
+ return key;
92
+ } catch { return reject('row-error', scan?.id); }
93
+ };
94
+ } catch { return (scan) => reject('setup-error', scan?.id); }
95
+ }
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env node
2
+ // rightkit#1511: prints the process-only proof of one dead owner record as JSON (build-ownership.mjs proveOwnerProcessesGone). Writes nothing.
3
+ // usage: node owner-process-proof.mjs <managed root>/build-ownership/<key>/owner.json
4
+ // exit 0 with the proof on stdout; exit 2 with the reason on stderr when a process is still live or unknown; exit 64 on bad usage.
5
+ import { proveOwnerProcessesGone } from "./build-ownership.mjs";
6
+
7
+ const file = process.argv[2];
8
+ if (!file || process.argv.length !== 3) { process.stderr.write("usage: owner-process-proof.mjs <owner.json>\n"); process.exit(64); }
9
+ try {
10
+ process.stdout.write(`${JSON.stringify(proveOwnerProcessesGone({ file }), null, 2)}\n`);
11
+ } catch (e) {
12
+ process.stderr.write(`${e.message}\n`);
13
+ process.exit(2);
14
+ }
@@ -29,6 +29,9 @@ export function holds(file, handle) {
29
29
  * while it is still this handle's, under a short lock beside the record (carried calls of parallel children, in other
30
30
  * processes, mark the same record).
31
31
  */
32
+ /** The row id a caller names, else this process's command line (no environment), cut to 240 characters. */
33
+ const carryNote = (note) => (typeof note === "string" && note ? note : process.argv.slice(1).join(" ")).slice(0, 240);
34
+
32
35
  export function markBrokerSubmit(file, handle, callHandle, options = {}) {
33
36
  if (typeof callHandle !== "string" || callHandle.length <= handle.length + 1 || !callHandle.startsWith(`${handle}#`) || !/^[A-Za-z0-9._-]+$/.test(callHandle.slice(handle.length + 1))) {
34
37
  throw new OwnershipBusy(`build ownership ${file}: a broker submit is recorded only for a carried request's sub-handle of ${handle} (<handle>#<id>), not ${JSON.stringify(callHandle ?? null)}`);
@@ -39,7 +42,10 @@ export function markBrokerSubmit(file, handle, callHandle, options = {}) {
39
42
  if (owner?.handle !== handle) throw new OwnershipBusy(`build ownership ${file} is no longer held by ${handle}; no broker request may be submitted`);
40
43
  const seen = Array.isArray(owner.broker?.handles) ? owner.broker.handles : [];
41
44
  if (owner.broker?.submitted && seen.includes(callHandle)) return owner;
42
- const next = { ...owner, broker: { ...(owner.broker ?? {}), submitted: true, at: owner.broker?.at ?? new Date().toISOString(), handles: [...seen, callHandle] } };
45
+ // rightkit#1510: which process and which row or command carried each sub-handle, so a sub-handle left UNKNOWN can be traced to its
46
+ // request. Diagnostic only: no reclaim proof reads it, and handle order never maps concurrent rows.
47
+ const sent = { ...(owner.broker?.sent ?? {}), [callHandle]: { at: new Date().toISOString(), pid: process.pid, note: carryNote(options.note) } };
48
+ const next = { ...owner, broker: { ...(owner.broker ?? {}), submitted: true, at: owner.broker?.at ?? new Date().toISOString(), handles: [...seen, callHandle], sent } };
43
49
  const tmp = `${file}.${crypto.randomUUID()}.tmp`;
44
50
  fs.writeFileSync(tmp, JSON.stringify(next), { flag: "wx", mode: 0o600 });
45
51
  try { fs.renameSync(tmp, file); } finally { fs.rmSync(tmp, { force: true }); }
@@ -102,6 +108,9 @@ export function judgeLockHolder(rec, { identity, host = os.hostname() }) {
102
108
  }
103
109
 
104
110
  /** Creates `target` holding `record` atomically and exclusively: the content is complete the moment the name exists (write a temp file, hard-link it). */
111
+ /** Whether `text` is a well-formed mark lock. A lock is published only fully written (createExclusive links a complete file), so an unreadable one is crash debris. */
112
+ export const isMarkLockText = (text) => parseLock(text ?? "") !== null;
113
+
105
114
  function createExclusive(target, record) {
106
115
  const tmp = `${target}.${record.nonce}.tmp`;
107
116
  fs.writeFileSync(tmp, JSON.stringify(record), { flag: "wx", mode: 0o600 });
@@ -0,0 +1,78 @@
1
+ #!/usr/bin/env node
2
+ // Recovery for a build-ownership record left by a gate that died or was stopped (rightkit#1513; Adrian, 2026-11-05: "have proper recovery
3
+ // tools for the fucking gate. This recovery avoidance is wrong"; "It should ideally auto recover").
4
+ // The gate's own reclaim recovers automatically (build-ownership.mjs coveredWorkGone): a sub-handle the broker answers UNKNOWN with no member
5
+ // row was never received when the same broker process has run since before the ownership was acquired and no process of the run remains.
6
+ // This tool explains a held record (processes, broker leases, every sub-handle) and, with --apply, runs that reclaim now and releases.
7
+ //
8
+ // node ownership-recover.mjs <owner.json> [--apply] [--wait-ms N]
9
+ // Dry run by default: prints the evidence and the plan, changes nothing. Exit 0 recovered (or nothing to do / plan clean), 2 refused, 64 usage.
10
+ import { spawnSync } from "node:child_process";
11
+ import fs from "node:fs";
12
+ import { fileURLToPath } from "node:url";
13
+ import { acquireBuildOwnership, brokerLeaseState, proveOwnerProcessesGone, runningBrokerProcess } from "./build-ownership.mjs";
14
+
15
+ const SETTLE_MS = 2000;
16
+
17
+ export async function recover({ file, apply = false, waitMs = 600_000, log = console.log, lease = brokerLeaseState, broker = () => runningBrokerProcess(), sleep = (ms) => new Promise((r) => setTimeout(r, ms)) }) {
18
+ const text = (() => { try { return fs.readFileSync(file, "utf8"); } catch (e) { if (e.code === "ENOENT") return null; throw e; } })();
19
+ if (text === null) { log(`recover: ${file}: no record; nothing to recover`); return 0; }
20
+ const owner = JSON.parse(text);
21
+ log(`recover: ${file}: held by ${owner.handle} (pid ${owner.pid}, ${owner.stage ?? "stage"} of ${owner.commit ?? "a commit"}) since ${owner.acquiredAt}`);
22
+
23
+ // 1. Processes: the owner and everything of its run are gone (the reclaim's own process proof, no broker judged).
24
+ let proof;
25
+ try { proof = proveOwnerProcessesGone({ file }); } catch (e) { log(`recover: REFUSED: ${e.message}`); return 2; }
26
+ for (const p of proof.proofs) log(` process: ${p}`);
27
+
28
+ // 2. Broker: every submission settled. Wait for ACTIVE work of the dead run to finish (a stopped gate leaves its last broker jobs running).
29
+ const subs = [...new Set(Array.isArray(owner.broker?.handles) ? owner.broker.handles : [])];
30
+ const unsent = owner.broker?.unsent ?? {};
31
+ const deadline = Date.now() + waitMs;
32
+ let ownerLease;
33
+ for (;;) {
34
+ ownerLease = lease({ snapshot: owner.snapshot, handle: owner.handle });
35
+ if (ownerLease.state !== "ACTIVE") break;
36
+ if (Date.now() > deadline) { log(`recover: REFUSED: broker work under ${owner.handle} is still ACTIVE after ${Math.round(waitMs / 1000)} s`); return 2; }
37
+ log(` broker: ${owner.handle} ACTIVE; waiting`); await sleep(5000);
38
+ }
39
+ log(` broker: owner lease ${ownerLease.state} (${(ownerLease.members ?? []).length} member row(s))`);
40
+ if (!subs.length || !owner.broker?.submitted) log(" broker: no carried request was recorded");
41
+
42
+ const brk = broker();
43
+ const acquiredMs = Date.parse(owner.acquiredAt);
44
+ const brokerSawAll = Boolean(brk && Number.isFinite(acquiredMs) && brk.startedMs + SETTLE_MS < acquiredMs);
45
+ log(` broker process: ${brk ? `pid ${brk.pid} up since ${new Date(brk.startedMs).toISOString()}` : "not established"}; ${brokerSawAll ? "continuously up since before this ownership" : "NOT shown up since before this ownership"}`);
46
+
47
+ const toMark = []; const refused = []; let reaped = 0;
48
+ for (const sub of subs) {
49
+ if (unsent[sub]) continue;
50
+ const one = lease({ snapshot: owner.snapshot, handle: sub });
51
+ const listed = (ownerLease.members ?? []).find((m) => m.handle === sub);
52
+ if (one.state === "REAPED") { reaped += 1; continue; }
53
+ if (one.state === "ACTIVE" || (listed && listed.state !== "REAPED")) { refused.push(`${sub}: ${one.state}${listed ? ` (listed ${listed.state})` : ""}`); continue; }
54
+ if (one.state === "UNKNOWN" && Array.isArray(one.members) && one.members.length === 0 && !listed && brokerSawAll) { toMark.push(sub); continue; }
55
+ refused.push(`${sub}: ${one.state} (${one.why ?? ""})${brokerSawAll ? "" : "; the broker was not up throughout, so UNKNOWN proves nothing"}`);
56
+ }
57
+ log(` sub-handles: ${subs.length} recorded, ${reaped} REAPED, ${Object.keys(unsent).length} already marked unsent, ${toMark.length} never received, ${refused.length} unresolved`);
58
+ if (refused.length) { for (const r of refused.slice(0, 10)) log(` unresolved: ${r}`); log("recover: REFUSED: some broker work cannot be accounted for"); return 2; }
59
+
60
+ // The reclaim itself settles a never-received sub-handle (build-ownership.mjs coveredWorkGone, rightkit#1513): the next gate run recovers this
61
+ // record automatically; --apply runs that same reclaim now and releases.
62
+ if (!apply) { log(`recover: recoverable: ${reaped} REAPED, ${toMark.length} never reached the broker. The next gate run reclaims it automatically; --apply reclaims now.`); return 0; }
63
+ let own;
64
+ try { own = acquireBuildOwnership({ file, stage: "ownership-recover", snapshot: owner.snapshot, commit: owner.commit, exportEnv: false }); }
65
+ catch (e) { log(`recover: REFUSED by the reclaim: ${e.message}`); return 2; }
66
+ for (const p of own.reclaimed?.proofs ?? []) log(` reclaim: ${p.slice(0, 200)}`);
67
+ const rel = own.release();
68
+ log(`recover: recovered ${owner.handle}; released ${rel?.released === true ? "cleanly" : JSON.stringify(rel).slice(0, 200)}`);
69
+ return 0;
70
+ }
71
+
72
+ if (process.argv[1] && fs.realpathSync(process.argv[1]) === fs.realpathSync(fileURLToPath(import.meta.url))) {
73
+ const args = process.argv.slice(2);
74
+ const file = args.find((a) => !a.startsWith("--"));
75
+ const waitAt = args.indexOf("--wait-ms");
76
+ if (!file) { console.error("usage: ownership-recover.mjs <owner.json> [--apply] [--wait-ms N]"); process.exit(64); }
77
+ recover({ file, apply: args.includes("--apply"), waitMs: waitAt >= 0 ? Number(args[waitAt + 1]) : undefined }).then((code) => process.exit(code), (e) => { console.error(`recover: ${e.stack ?? e}`); process.exit(2); });
78
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rightkit/release",
3
- "version": "0.6.45",
3
+ "version": "0.6.47",
4
4
  "description": "Portable release CLI/SDK with fail-closed public GitHub Releases and private R2 + RightApps distribution.",
5
5
  "license": "MIT OR Apache-2.0",
6
6
  "type": "module",
@@ -100,6 +100,7 @@
100
100
  "smol-toml": "1.9.1"
101
101
  },
102
102
  "scripts": {
103
+ "test": "node --test affected-units.test.mjs batch-workspace.test.mjs unit-list-compile.test.mjs snapshot-dependency-reuse.test.mjs publisher-requirement-scan.test.mjs node-check-cache.test.mjs preparation-diagnostics.test.mjs gate-coverage-timing.test.mjs failure-class.test.mjs cargo-width.test.mjs ci-compile-admission.test.mjs ownership-mark-note.test.mjs handle-revocation.test.mjs test-run-output.test.mjs ownership-auto-recover.test.mjs gate-acceptance.test.mjs stamp-relay.test.mjs",
103
104
  "test:registry-parity": "node registry-parity.mjs --allow-unpublished",
104
105
  "test:signer:windows": "node sign-release-manifest.integration.mjs",
105
106
  "verify:standalone": "node standalone-clone-verify.mjs"
@@ -0,0 +1,19 @@
1
+ // Optional bounded measurements; never part of a gate verdict or cache key.
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import crypto from 'node:crypto';
5
+
6
+ export function writePerformanceDiagnostic(dir, category, rows) {
7
+ let temp;
8
+ try {
9
+ if (!dir || !path.isAbsolute(dir) || !['preflight', 'snapshot-verify'].includes(category) || !Array.isArray(rows) || rows.length > 256) return;
10
+ if (!rows.every((r) => r && /^[a-z0-9-]{1,80}$/.test(r.label) && Number.isFinite(r.ms) && r.ms >= 0 && Number.isInteger(r.count) && r.count >= 0)) return;
11
+ const scratch = fs.realpathSync(process.platform === 'win32' ? 'D:\\scratch' : '/Volumes/D/scratch');
12
+ const target = fs.realpathSync(dir);
13
+ if (!(target === scratch || target.startsWith(scratch + path.sep)) || !fs.statSync(target).isDirectory()) return;
14
+ const file = path.join(target, `timing-${category}-${process.pid}-${crypto.randomBytes(8).toString('hex')}.json`);
15
+ temp = `${file}.tmp`;
16
+ fs.writeFileSync(temp, JSON.stringify({ schema: 'rightkit.performance-diagnostic/1', category, rows: rows.map(({ label, ms, count }) => ({ label, ms, count })) }), { flag: 'wx' });
17
+ fs.renameSync(temp, file);
18
+ } catch { if (temp) { try { fs.unlinkSync(temp); } catch {} } }
19
+ }
@@ -144,6 +144,11 @@ export function verifyReceiptCoverage(receipt, payload) {
144
144
  covered(receipt, payload, "stageEvidence", STAGE_EVIDENCE_FIELDS, "stage evidence");
145
145
  covered(receipt, payload, "resultEvidence", RESULT_EVIDENCE_FIELDS, "result evidence");
146
146
  covered(receipt, payload, "br19Evidence", BR19_EVIDENCE_FIELDS, "BR19 evidence");
147
+ const receiptClass = Object.hasOwn(receipt, "failureClass");
148
+ const signedClass = isRecord(payload.result) && Object.hasOwn(payload.result, "failureClass");
149
+ if (receiptClass !== signedClass || (receiptClass && !equalValue(receipt.failureClass, payload.result.failureClass))) refuse("evidence", "receipt failureClass differs from the signed result");
150
+ // RustRight treats a missing postChecks and null as equivalent for older receipts.
151
+ if (!equalValue(receipt.postChecks ?? null, payload.result?.postChecks ?? null)) refuse("evidence", "receipt postChecks differs from the signed result");
147
152
  for (const name of RETIRED_RESULT_FIELDS) {
148
153
  if (receipt[name] !== undefined || (isRecord(payload.resultEvidence) && payload.resultEvidence[name] !== undefined)) refuse("evidence", `receipt ${name} is a retired verdict-reuse field`);
149
154
  }
@@ -199,11 +204,41 @@ export function verifyBr19Evidence(receipt, payload) {
199
204
  if (!(typeof environment.digest === "string" && /^[0-9a-f]{64}$/.test(environment.digest) && names("forwarded") && names("dropped"))) bad("environment needs a 64-hex digest and forwarded and dropped name lists");
200
205
  }
201
206
 
207
+ export const FAILURE_CLASSES = Object.freeze(["admission", "compile", "test", "tool", "cancelled", "timeout", "broker"]);
208
+ /** Validate an optional signed failure class; verifyReceiptCoverage binds the receipt copy. */
209
+ export function verifyFailureClass(receipt, payload) {
210
+ const signed = isRecord(payload.result) && Object.hasOwn(payload.result, "failureClass");
211
+ const copy = Object.hasOwn(receipt, "failureClass");
212
+ if (signed !== copy || (signed && !equalValue(receipt.failureClass, payload.result.failureClass))) refuse("evidence", "receipt failureClass differs from the signed result");
213
+ if (signed && payload.result.failureClass !== null && !FAILURE_CLASSES.includes(payload.result.failureClass)) refuse("evidence", "signed failureClass is neither null nor a recognized class");
214
+ }
215
+
216
+ const POST_CHECK_FIELDS = Object.freeze(["schema", "ran", "failed", "inputClosure", "inputBoundary", "verified"]);
217
+ /** Validate signed post-run checks. Snapshot callers additionally require applicable, signed boundary evidence. */
218
+ export function verifyPostChecks(receipt, payload, { snapshotAttested = false } = {}) {
219
+ const checks = payload.result?.postChecks ?? null;
220
+ if (!equalValue(receipt.postChecks ?? null, checks)) refuse("evidence", "receipt postChecks differs from the signed result");
221
+ if (checks === null) return null;
222
+ const bad = () => refuse("evidence", "the signed result's postChecks is malformed");
223
+ if (!isRecord(checks) || Object.keys(checks).length !== POST_CHECK_FIELDS.length || POST_CHECK_FIELDS.some((key) => !Object.hasOwn(checks, key))) bad();
224
+ if (checks.schema !== "rustright.post-checks.v1" || typeof checks.ran !== "boolean" || typeof checks.verified !== "boolean" || !Array.isArray(checks.failed) || !checks.failed.every((name) => ["freshness", "projection", "toolchainIdentity"].includes(name))) bad();
225
+ if (!["verified", "inputs-mutated", "unverified", "not-applicable"].includes(checks.inputClosure) || !["intact", "violated", "unverified", "unrequested", "not-applicable"].includes(checks.inputBoundary)) bad();
226
+ const boundary = payload.inputBoundary?.status;
227
+ if (typeof boundary === "string" && boundary !== checks.inputBoundary) refuse("evidence", "postChecks.inputBoundary differs from the signed inputBoundary");
228
+ if (snapshotAttested && (checks.inputClosure === "not-applicable" || checks.inputBoundary === "not-applicable" || typeof boundary !== "string" || boundary !== checks.inputBoundary)) refuse("evidence", "snapshot postChecks lacks applicable signed input boundary or closure evidence");
229
+ const verified = checks.ran && checks.failed.length === 0 && ["verified", "not-applicable"].includes(checks.inputClosure) && ["intact", "unrequested", "not-applicable"].includes(checks.inputBoundary);
230
+ if (checks.verified !== verified) refuse("evidence", "the signed postChecks.verified does not follow from its checks");
231
+ if (payload.result?.failureClass === "compile" && !(checks.ran && checks.failed.length === 0)) refuse("evidence", "a signed compile failure whose post-run checks did not all run and pass");
232
+ return checks;
233
+ }
234
+
202
235
  /** `verify_receipt_strict`: `verifyReceiptLenient`, then the signed result evidence and the BR19 shape. A gate applies it to every compile receipt, never the lenient form alone. */
203
236
  export function verifyReceiptStrict(receipt, pins, expected) {
204
237
  const payload = verifyReceiptLenient(receipt, pins, expected);
205
238
  verifyResultEvidence(receipt, payload);
206
239
  verifyBr19Evidence(receipt, payload);
240
+ verifyFailureClass(receipt, payload);
241
+ verifyPostChecks(receipt, payload);
207
242
  return payload;
208
243
  }
209
244