@rightkit/release 0.6.51 → 0.6.54

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/README.md +1 -1
  2. package/adapter-env.mjs +16 -105
  3. package/admission-host.mjs +14 -1
  4. package/bin/darwin/rightkit-swap +0 -0
  5. package/bin/rightkit-gate.mjs +609 -404
  6. package/broker-admission.mjs +122 -2
  7. package/build-launch.mjs +52 -58
  8. package/build-release.mjs +2 -2
  9. package/cargo-ledger.mjs +24 -5
  10. package/cargo-target-shim.mjs +54 -23
  11. package/cargo-target.mjs +2 -2
  12. package/carried-adapter-run.mjs +7 -8
  13. package/carried-cargo-run.mjs +1 -1
  14. package/ci-compile-admission.mjs +1 -1
  15. package/clippy-route.mjs +65 -18
  16. package/compile-inputs.mjs +91 -15
  17. package/cross-targets.mjs +5 -3
  18. package/deps-cargo-lock.mjs +1 -1
  19. package/deterministic-scans.mjs +789 -259
  20. package/development.mjs +33 -7
  21. package/direct-receipt.mjs +3 -5
  22. package/feature-coverage.mjs +45 -9
  23. package/feature-partition.mjs +204 -0
  24. package/feature-sets.mjs +113 -0
  25. package/gate-acceptance.mjs +187 -115
  26. package/gate-seam.mjs +352 -0
  27. package/gate-serve.mjs +34 -2
  28. package/gate-stages.mjs +6 -2
  29. package/ghsa-audit.mjs +19 -4
  30. package/heavy-command.mjs +5 -4
  31. package/install-tauri-authenticode.mjs +73 -4
  32. package/ios-dev.mjs +3 -3
  33. package/ios-package-recipe.mjs +6 -6
  34. package/linux-setup.mjs +3 -2
  35. package/local-publish.mjs +113 -17
  36. package/lock-identity.mjs +24 -100
  37. package/managed-cargo.mjs +3 -3
  38. package/managed-root-guard.mjs +2 -2
  39. package/managed-roots.mjs +3 -3
  40. package/native-adapters.mjs +41 -244
  41. package/native-helpers.mjs +1 -1
  42. package/pack-digest.mjs +1 -1
  43. package/package-recipe-targets.mjs +3 -3
  44. package/package.json +2 -2
  45. package/publication-gate.mjs +29 -6
  46. package/publish-cargo.mjs +4 -5
  47. package/publish-local-cargo.mjs +77 -1
  48. package/qualification-verify.mjs +76 -49
  49. package/receipt-signature.mjs +104 -0
  50. package/release-switch-registry.json +4 -0
  51. package/release-switch-scan.mjs +13 -10
  52. package/rightkit-versions.json +126 -113
  53. package/scan-digest.mjs +43 -14
  54. package/seam-broker.mjs +168 -0
  55. package/snapshot-check.mjs +4 -1
  56. package/snapshot-dependency-reuse.mjs +1 -1
  57. package/snapshot-metadata.mjs +24 -35
  58. package/snapshot.mjs +328 -49
  59. package/stage-commands.mjs +59 -5
  60. package/stage-ledger.mjs +2 -2
  61. package/{carried-cargo.mjs → stage-seam.mjs} +118 -70
  62. package/stage-sidecar.mjs +3 -3
  63. package/tauri-bundle-marker.mjs +5 -2
  64. package/tauri-locked.mjs +1 -1
  65. package/tool-build.mjs +8 -6
  66. package/unit-gate.mjs +40 -10
  67. package/web-build.mjs +6 -0
  68. package/broker-handshake.mjs +0 -160
  69. package/broker-wire.mjs +0 -278
  70. package/build-ownership.mjs +0 -1578
  71. package/cargo-shapes.mjs +0 -332
  72. package/cargo-width.mjs +0 -49
  73. package/carrier-census.mjs +0 -124
  74. package/clippy-equivalence.mjs +0 -202
  75. package/freshness-census.mjs +0 -405
  76. package/handle-revocation.mjs +0 -100
  77. package/handle-revocation.rust-vector.json +0 -1
  78. package/handle-revocation.vectors.json +0 -53
  79. package/legion-freeze-consumer.mjs +0 -241
  80. package/linux-qualifier.mjs +0 -83
  81. package/native-tool-planning.mjs +0 -94
  82. package/owner-process-proof.mjs +0 -14
  83. package/ownership-mark.mjs +0 -191
  84. package/ownership-recover.mjs +0 -78
  85. package/pnpm-adapter-grammar.mjs +0 -226
  86. package/provenance-verify.mjs +0 -413
  87. package/snapshot-broker.mjs +0 -808
  88. package/snapshot-request.mjs +0 -722
  89. package/unit-list-compile.mjs +0 -356
@@ -1,202 +0,0 @@
1
- // Batch equivalence for the Clippy route (GATE-CONTRACT §1 "Batching", E14; item 8 rows 8.7 and 8.16). A batched Clippy invocation
2
- // replaces the per-crate ones only when it is shown to say the same thing: the same diagnostics (package, target, code, span), the
3
- // same resolved features for what it compiled (feature unification across the selected packages can change what compiles), and the
4
- // same engine and toolchain. This module is the comparison; `run` below drives real cargo over a checkout (a gate-owned export, a
5
- // Linux host) and writes the recorded comparison.
6
- //
7
- // node clippy-equivalence.mjs --repo <dir> --out <dir> [--units a,b,...] [--target-dir <dir>] [--cargo cargo]
8
- //
9
- // Exit 0 when every batch is equivalent to its per-crate runs (after any unified crate was split out and the split re-run), 1 when not.
10
- import crypto from "node:crypto";
11
- import fs from "node:fs";
12
- import path from "node:path";
13
- import { spawnSync } from "./background-process.mjs";
14
- import { fileURLToPath } from "node:url";
15
- import { clippyArgs, clippyBatchPlan, sidecarBoundCrate } from "./deterministic-scans.mjs";
16
- import { rustCratePlan } from "./scan-digest.mjs";
17
- import { parseCargoMessages, summarizeMessages, toolchainIdentity } from "./clippy-route.mjs";
18
-
19
- export const EQUIVALENCE_SCHEMA = "rightkit.clippy-batch-equivalence/1";
20
- const sha256 = (v) => crypto.createHash("sha256").update(v).digest("hex");
21
-
22
- /** One diagnostic's identity for the comparison: package, target, level, code (else its first line) and primary span. */
23
- export const diagnosticKey = (d) => JSON.stringify([d.package, d.kind, d.target, d.level, d.code ?? String(d.message).split("\n")[0], d.span ? [d.span.file, d.span.line, d.span.column, d.span.lineEnd, d.span.columnEnd] : null]);
24
- const artifactKey = (a) => JSON.stringify([a.package, a.kind, a.target, a.test === true]);
25
- const multiset = (keys) => { const m = new Map(); for (const k of keys) m.set(k, (m.get(k) ?? 0) + 1); return m; };
26
- const diff = (a, b) => { const out = []; for (const [k, n] of a) { const d = n - (b.get(k) ?? 0); for (let i = 0; i < d; i += 1) out.push(k); } return out.sort(); };
27
-
28
- /**
29
- * Compares each batch with the per-crate runs of its members. `groups`: `[{ id, units, batch: { messages, toolchain }, perCrate:
30
- * [{ unit, crate, messages, toolchain }] }]` (`messages` are parsed cargo JSON objects; `units` the batch's unit names, which
31
- * `perCrate` covers one for one). Returns `{ equivalent, groups, separate, failures }`: `separate` maps each unit whose batched
32
- * compile differed (a different feature set for itself, or a dependency built with features no per-crate run built it with) to the
33
- * reason, for the planner to keep it as its own invocation; any difference in diagnostics, or a missing or unequal toolchain
34
- * identity, is a failure of the run (row 8.16).
35
- */
36
- export function compareEquivalence({ groups }) {
37
- const failures = []; const separate = new Map(); const rows = [];
38
- for (const g of groups) {
39
- const members = new Set(g.perCrate.map((p) => p.crate));
40
- const batch = summarizeMessages(g.batch.messages);
41
- const per = g.perCrate.map((p) => ({ ...p, run: summarizeMessages(p.messages) }));
42
- const row = { id: g.id, units: g.units, crates: [...members].sort() };
43
- // A member the batch never built (no artifact, no diagnostic) while another member of the batch failed is BLOCKED in the batch: with
44
- // `-D warnings` a lint is a build failure, so a dependent of a failing member builds nothing under --keep-going where its own per-crate
45
- // run (which lints only itself) would have run. That is the route's reported `blocked` state (row 8.4), not a clean result, and it is
46
- // excluded from the comparison; a member the batch did not build while nothing in it failed is a difference.
47
- const failedInBatch = new Set(batch.diagnostics.filter((d) => members.has(d.package) && d.level.startsWith("error")).map((d) => d.package));
48
- const builtInBatch = new Set([...batch.artifacts.map((a) => a.package), ...batch.diagnostics.map((d) => d.package)]);
49
- const blocked = [...members].filter((m) => !builtInBatch.has(m)).sort();
50
- // Not built in the batch, nothing in it failed, and the member's own per-crate run did build it: a difference. A member neither run
51
- // builds (a build script that fails on this host, a missing system library) is the same in both.
52
- const builtOnItsOwn = (m) => per.some((p) => p.crate === m && p.run.artifacts.some((a) => a.package === m));
53
- const unbuilt = failedInBatch.size === 0 ? blocked.filter(builtOnItsOwn) : [];
54
- row.blockedInBatch = failedInBatch.size ? blocked : [];
55
- const compared = (pkg) => members.has(pkg) && !row.blockedInBatch.includes(pkg);
56
- // Diagnostics: the batch's, for its members, against each per-crate run's, for that crate.
57
- const batchKeys = multiset(batch.diagnostics.filter((d) => compared(d.package)).map(diagnosticKey));
58
- const perKeys = multiset(per.flatMap((p) => p.run.diagnostics.filter((d) => d.package === p.crate && compared(p.crate)).map(diagnosticKey)));
59
- row.diagnostics = { batch: [...batchKeys.values()].reduce((a, n) => a + n, 0), perCrate: [...perKeys.values()].reduce((a, n) => a + n, 0), onlyInBatch: diff(batchKeys, perKeys), onlyInPerCrate: diff(perKeys, batchKeys) };
60
- row.diagnosticsOfBlockedMembers = per.filter((p) => row.blockedInBatch.includes(p.crate)).reduce((n, p) => n + p.run.diagnostics.filter((d) => d.package === p.crate).length, 0);
61
- if (row.diagnostics.onlyInBatch.length || row.diagnostics.onlyInPerCrate.length) failures.push(`${g.id}: the batch's diagnostics differ from its per-crate runs (${row.diagnostics.onlyInBatch.length} only in the batch, ${row.diagnostics.onlyInPerCrate.length} only per crate)`);
62
- const unitOf = new Map(per.map((p) => [p.crate, p.unit]));
63
- const byDiagnostics = new Set([...row.diagnostics.onlyInBatch, ...row.diagnostics.onlyInPerCrate].map((k) => JSON.parse(k)[0]));
64
- for (const pkg of byDiagnostics) if (unitOf.has(pkg)) separate.set(unitOf.get(pkg), `batching changed the diagnostics of ${pkg} (item 8 row 8.7): kept as its own invocation`);
65
- for (const pkg of unbuilt) if (unitOf.has(pkg)) separate.set(unitOf.get(pkg), `the batch never built ${pkg} although nothing in it failed (item 8 row 8.7)`);
66
- // Resolved features: what each member was built with, in the batch against its own per-crate run, for every unit both built.
67
- const unified = [];
68
- for (const p of per) {
69
- if (!compared(p.crate)) continue;
70
- const own = (a) => a.package === p.crate;
71
- const batchOf = new Map(); for (const a of batch.artifacts.filter(own)) batchOf.set(artifactKey(a), a.features);
72
- const ownOf = new Map(); for (const a of p.run.artifacts.filter(own)) ownOf.set(artifactKey(a), a.features);
73
- for (const [key, w] of ownOf) {
74
- const b = batchOf.get(key);
75
- if (b !== undefined && JSON.stringify(b) !== JSON.stringify(w)) unified.push({ unit: p.unit, crate: p.crate, unitKey: JSON.parse(key), batchFeatures: b, perCrateFeatures: w });
76
- }
77
- }
78
- const seen = new Map();
79
- for (const p of per) for (const a of p.run.artifacts.filter((x) => !members.has(x.package))) { const k = `${a.packageId}\0${artifactKey(a)}`; if (!seen.has(k)) seen.set(k, new Set()); seen.get(k).add(JSON.stringify(a.features)); }
80
- const dependencies = [];
81
- for (const a of batch.artifacts.filter((x) => !members.has(x.package))) {
82
- const k = `${a.packageId}\0${artifactKey(a)}`;
83
- const known = seen.get(k);
84
- if (known && !known.has(JSON.stringify(a.features))) dependencies.push({ package: a.package, packageId: a.packageId, batchFeatures: a.features, perCrateFeatures: [...known].map((s) => JSON.parse(s)) });
85
- }
86
- // Third-party packages built with a union of the batch's features are recorded, not judged: cargo's features are additive, and the
87
- // linted code is the members'. A member built with other features than its own run is what changes what compiles.
88
- row.features = { unified, dependenciesBuiltWithOtherFeatures: dependencies.length };
89
- row.dependenciesBuiltWithOtherFeatures = dependencies.map((d) => d.packageId).sort();
90
- for (const u of unified) separate.set(u.unit, `batching changed the features ${u.crate} compiles with (${u.batchFeatures.join(",") || "none"} in the batch, ${u.perCrateFeatures.join(",") || "none"} on its own): feature unification (item 8 row 8.7)`);
91
- // A batch that fails to build where every per-crate run builds, and whose failure no diagnostic of a member explains (a build script, a
92
- // feature conflict): the unified features cannot all be on together (mutually exclusive ones). A failure a member's diagnostic explains
93
- // is judged by the diagnostics and the unified-feature comparison above.
94
- const exits = { batch: g.batch.exit ?? null, perCrate: per.map((p) => p.exit ?? null) };
95
- row.exits = exits;
96
- const exitDiffers = exits.batch !== null && exits.batch !== 0 && per.length > 0 && per.every((p) => p.exit === 0) && failedInBatch.size === 0;
97
- if (exitDiffers) for (const p of per) separate.set(p.unit, "the batch fails to build where every per-crate run builds: its features cannot all be on together (item 8 row 8.7)");
98
- // Toolchain identity (row 8.16): present and equal for the batch and every per-crate run.
99
- const toolchains = [g.batch.toolchain, ...per.map((p) => p.toolchain)];
100
- const equal = toolchains.every((t) => typeof t === "string" && t.trim() !== "") && new Set(toolchains).size === 1;
101
- row.toolchain = { equal, batch: g.batch.toolchain ?? null, perCrate: [...new Set(per.map((p) => p.toolchain ?? null))] };
102
- if (!equal) failures.push(`${g.id}: the toolchain identity of the batch and its per-crate runs is not one equal, present string (batch ${g.batch.toolchain ?? "missing"}; per crate ${row.toolchain.perCrate.join(", ")})`);
103
- row.equivalent = !row.diagnostics.onlyInBatch.length && !row.diagnostics.onlyInPerCrate.length && !unified.length && !exitDiffers && !unbuilt.length && equal;
104
- rows.push(row);
105
- }
106
- if (separate.size) failures.push(`${separate.size} unit(s) are kept separate: ${[...separate.keys()].sort().join(", ")}`);
107
- return { schema: EQUIVALENCE_SCHEMA, equivalent: failures.length === 0, groups: rows, separate, failures };
108
- }
109
-
110
- // ---- the run over a checkout (real cargo) ---------------------------------------------------------------------------------------------
111
-
112
- function cargoRun({ cargo, args, cwd, env, messagesFile, clean = [] }) {
113
- // Each run lints its packages afresh: cargo replays the cached diagnostics of a fresh unit, and what it cached depends on which run
114
- // compiled the unit first, so a comparison over a shared target directory would compare cache history. Cleaning only the packages
115
- // the run selects keeps the dependencies' compiled outputs warm.
116
- if (clean.length) {
117
- const c = spawnSync(cargo, ["clean", ...clean.flatMap((n) => ["-p", n])], { cwd, env, encoding: "utf8" });
118
- if (c.status !== 0) throw new Error(`clean of ${clean.join(", ")} failed: ${String(c.stderr).slice(-300)}`);
119
- }
120
- const fd = fs.openSync(messagesFile, "w");
121
- const t = Date.now();
122
- let r;
123
- try { r = spawnSync(cargo, args, { cwd, env, stdio: ["ignore", fd, "pipe"], encoding: "utf8", maxBuffer: 256 * 1024 * 1024 }); } finally { fs.closeSync(fd); }
124
- const body = fs.readFileSync(messagesFile, "utf8");
125
- return { status: r.status, signal: r.signal, stderr: String(r.stderr ?? "").slice(-4000), messages: parseCargoMessages(body).messages, ms: Date.now() - t, bytes: Buffer.byteLength(body), error: r.error?.message ?? null };
126
- }
127
- const withKeepGoing = (args) => { const i = args.indexOf("--"); return [...args.slice(0, i < 0 ? undefined : i), "--keep-going", ...(i < 0 ? [] : args.slice(i))]; };
128
-
129
- /**
130
- * Runs the per-crate and the batched Clippy invocations of `units` (default: every workspace member) over `repo` with the same
131
- * toolchain and one shared target directory, compares them, and when a batch is not equivalent because of feature unification
132
- * splits the affected units out and runs and compares again. Writes `<out>/equivalence.json` (without raw messages) and returns it.
133
- */
134
- export function run({ repo, out, units = null, targetDir = path.join(out, "target"), cargo = "cargo", env = process.env, log = (m) => process.stderr.write(`${m}\n`) }) {
135
- fs.mkdirSync(out, { recursive: true });
136
- const runEnv = { ...env, CARGO_TARGET_DIR: targetDir };
137
- const meta = spawnSync(cargo, ["metadata", "--no-deps", "--format-version", "1", "--locked"], { cwd: repo, env: runEnv, encoding: "utf8", maxBuffer: 256 * 1024 * 1024 });
138
- if (meta.status !== 0) throw new Error(`cargo metadata failed: ${String(meta.stderr).slice(-400)}`);
139
- const metadata = JSON.parse(meta.stdout);
140
- const byId = new Map(metadata.packages.map((p) => [p.id, p]));
141
- const members = metadata.workspace_members.map((id) => byId.get(id)).filter(Boolean).sort((a, b) => (a.name < b.name ? -1 : 1));
142
- const config = JSON.parse(fs.readFileSync(path.join(repo, "ci", "gate.config.json"), "utf8")).rust ?? {};
143
- let solo = []; try { solo = JSON.parse(fs.readFileSync(path.join(repo, "ci", "shards.json"), "utf8")).solo ?? []; } catch { solo = []; }
144
- const wanted = units ? new Set(units) : null;
145
- const entries = [];
146
- for (const p of members) {
147
- if (wanted && !wanted.has(p.name)) continue;
148
- const { lintSets } = rustCratePlan(config[p.name] ?? {});
149
- for (const set of lintSets) entries.push({ name: p.name, crate: p.name, ws: ".", set, count: lintSets.length, env: null });
150
- }
151
- const sidecarBound = new Set(entries.filter((e) => sidecarBoundCrate({ dir: path.dirname(byId.get(members.find((m) => m.name === e.name).id).manifest_path) }).bound).map((e) => e.name));
152
- const toolchainNow = () => toolchainIdentity({ spawn: (c, a, o) => spawnSync(c, a, { ...o, encoding: "utf8" }), env: runEnv, cwd: repo });
153
- const toolchain = toolchainNow();
154
- log(`equivalence: ${entries.length} crate configuration(s) of ${members.length} workspace member(s); toolchain ${toolchain}`);
155
-
156
- const perCrateRuns = new Map();
157
- const perCrate = (entry) => {
158
- const key = `${entry.name}\0${entry.set.join(" ")}`;
159
- if (!perCrateRuns.has(key)) {
160
- const args = withKeepGoing(clippyArgs(entry.crate, { features: entry.set, messageFormat: "json", locked: true }));
161
- const r = { toolchain: toolchainNow(), ...cargoRun({ cargo, args, cwd: repo, env: runEnv, clean: [entry.crate], messagesFile: path.join(out, `percrate-${sha256(key).slice(0, 10)}.jsonl`) }) };
162
- log(`per-crate ${entry.name} [${entry.set.join(" ") || "default"}]: exit ${r.status} ${r.ms} ms ${r.bytes} bytes`);
163
- perCrateRuns.set(key, { ...r, argv: args });
164
- }
165
- return perCrateRuns.get(key);
166
- };
167
- const runPass = (separate) => {
168
- const plan = clippyBatchPlan(entries, { solo, separate, sidecarBound, toolchain: cargo });
169
- const groups = [];
170
- for (const b of plan.batches) {
171
- const args = withKeepGoing(clippyArgs(b.crates, { features: b.set, messageFormat: "json", locked: true }));
172
- const r = { toolchain: toolchainNow(), ...cargoRun({ cargo, args, cwd: repo, env: runEnv, clean: b.crates, messagesFile: path.join(out, `batch-${sha256(b.key).slice(0, 10)}.jsonl`) }) };
173
- log(`batch ${b.id} (${b.crates.length} crate(s), ${b.set.join(" ") || "default"}): exit ${r.status} ${r.ms} ms ${r.bytes} bytes`);
174
- const own = entries.filter((e) => b.units.includes(e.name) && e.set.join(" ") === b.set.join(" "));
175
- groups.push({ id: b.id, units: b.units, reason: b.reason, argv: args, exit: r.status, batch: { messages: r.messages, toolchain: r.toolchain, exit: r.status }, perCrate: own.map((e) => { const p = perCrate(e); return { unit: e.name, crate: e.crate, messages: p.messages, toolchain: p.toolchain, exit: p.status, argv: p.argv }; }) });
176
- }
177
- return { plan, groups, result: compareEquivalence({ groups }) };
178
- };
179
- const strip = (pass) => ({ batches: pass.plan.batches.map((b) => ({ id: b.id, crates: b.crates, set: b.set, reason: b.reason, order: b.order })), notes: pass.plan.notes, groups: pass.result.groups, failures: pass.result.failures, exits: pass.groups.map((g) => ({ id: g.id, batchExit: g.exit, perCrateExits: g.perCrate.map((p) => [p.unit, p.exit]) })) });
180
- const first = runPass(new Map());
181
- let final = first; let second = null;
182
- if (first.result.separate.size) { second = runPass(first.result.separate); final = second; }
183
- const report = {
184
- schema: EQUIVALENCE_SCHEMA, at: new Date().toISOString(), repo, toolchain, cargo,
185
- coverage: { workspaceMembers: members.length, crateConfigurations: entries.length, units: [...new Set(entries.map((e) => e.name))].sort(), sidecarBound: [...sidecarBound], perCrateRuns: perCrateRuns.size, firstPassBatches: first.plan.batches.length },
186
- equivalent: final.result.failures.filter((f) => !/are kept separate/.test(f)).length === 0 && final.result.separate.size === 0,
187
- firstPass: strip(first), firstPassSeparate: Object.fromEntries(first.result.separate),
188
- afterSplit: second ? strip(second) : null,
189
- };
190
- fs.writeFileSync(path.join(out, "equivalence.json"), `${JSON.stringify(report, null, 2)}\n`);
191
- return report;
192
- }
193
-
194
- const invokedDirectly = (() => { try { return fs.realpathSync(process.argv[1]) === fs.realpathSync(fileURLToPath(import.meta.url)); } catch { return false; } })();
195
- if (invokedDirectly) {
196
- const args = process.argv.slice(2);
197
- const opt = (name) => { const i = args.indexOf(name); return i < 0 ? null : args[i + 1]; };
198
- if (!opt("--repo") || !opt("--out")) { process.stderr.write("usage: clippy-equivalence.mjs --repo <dir> --out <dir> [--units a,b] [--target-dir <dir>] [--cargo cargo]\n"); process.exit(2); }
199
- const report = run({ repo: path.resolve(opt("--repo")), out: path.resolve(opt("--out")), units: opt("--units") ? opt("--units").split(",") : null, ...(opt("--target-dir") ? { targetDir: path.resolve(opt("--target-dir")) } : {}), ...(opt("--cargo") ? { cargo: opt("--cargo") } : {}) });
200
- process.stdout.write(`${JSON.stringify({ equivalent: report.equivalent, coverage: report.coverage, firstPassFailures: report.firstPass.failures, afterSplitFailures: report.afterSplit?.failures ?? null })}\n`);
201
- process.exit(report.equivalent ? 0 : 1);
202
- }
@@ -1,405 +0,0 @@
1
- // The freshness census of a direct (Linux) snapshot compile (item 7 row 7.19; GATE-CONTRACT "Returned evidence", `freshness`:
2
- // `{ unitsAtStart, fresh, notFresh, invalidationReasons }`, the census the measured-cache rule is judged from; E16: "the second
3
- // build's census shows reuse").
4
- //
5
- // Cargo keeps no invalidation reason on disk: a fingerprint file holds the current hash only. The reason exists only in Cargo's own
6
- // fingerprint log (`CARGO_LOG=cargo::core::compiler::fingerprint=info`: a `fingerprint dirty for <unit>` line, then `dirty: <reason>`),
7
- // the same source the RustRight broker reads for its receipt (rustright-broker job_service/cargo_evidence.rs; attested-runs.md).
8
- // The gate turns that log on for the cargo processes that compile a workspace, on THAT process only (never in the scan environment
9
- // the repository's own tests and scripts inherit), reads it from the process's standard error, and keeps the lines out of the output
10
- // unless the caller set CARGO_LOG itself (a caller's own CARGO_LOG is read the same way and left visible).
11
- //
12
- // Counts come from the target directory the way the broker takes them (rustright-policy cargo_freshness.rs): a unit is one directory
13
- // of a `.fingerprint`; a unit whose newest file is at or after the census start was rebuilt (`notFresh`, a new unit included), the
14
- // others were reused (`fresh`). Judging unexplained rebuilds belongs to item 11; this module only measures and records.
15
- //
16
- // GB-68 (BROKER-CONTRACT section 16; the shared vector test-support/vectors/freshness-evidence-vectors.v1.json, held by freshness-vectors.test.mjs):
17
- // - the log reader reads only the ROOT's lines: those before Cargo's first execution status word (`Compiling`, `Checking`, ... `Finished`); nested
18
- // Cargo chatter after it is neither counted nor stripped; a `failed to read ...fingerprint...` reason followed by a `Caused by:` not-found cause
19
- // (Unix `os error 2`, Windows `os error 3`) is `FingerprintMissing`, any other cause stays `unexplained`; every reason carries its `cause`;
20
- // - the census reads the SELECTED scope only: `<target>/<profile>/.fingerprint` and, for a `--target` triple, `<target>/<triple>/<profile>/.fingerprint`
21
- // (never every profile or triple, never `doc` or `package`), taken from the compiling process's own arguments and environment;
22
- // - a fingerprint directory or unit that exists and cannot be read is `fingerprint-census-read-failed`: unavailable, never an empty census and never a
23
- // first build. Only an absent directory is empty.
24
- import fs from "node:fs";
25
- import path from "node:path";
26
-
27
- /** The `CARGO_LOG` filter the gate sets for a compiling cargo process (the broker's FINGERPRINT_LOG_FILTER). */
28
- export const FINGERPRINT_LOG_FILTER = "cargo::core::compiler::fingerprint=info";
29
- const FINGERPRINT_TARGET = "cargo::core::compiler::fingerprint";
30
- export const FRESHNESS_SOURCE = "cargo-fingerprint-log+fingerprint-mtime";
31
- /** Reasons kept in the receipt; the rest are counted. */
32
- export const REASONS_CAP = 10_000;
33
- /** Characters kept of one reason (Cargo prints it with `Debug`, paths and mtimes included). */
34
- export const REASON_TEXT_CAP = 512;
35
- /** Unit directories and files visited before the census is declared unavailable rather than partial. */
36
- export const CENSUS_ENTRY_CAP = 250_000;
37
- // A held partial line longer than this is not a log line.
38
- const PARTIAL_CAP = 64 * 1024;
39
-
40
- /** Cargo's execution-phase status words: the first one ends the window in which fingerprint lines are the root's (pre-resolution words do not). */
41
- export const EXECUTION_STATUS = Object.freeze(["Compiling", "Checking", "Documenting", "Fresh", "Dirty", "Running", "Finished", "Scraping"]);
42
- const EXECUTION_WORDS = new Set(EXECUTION_STATUS);
43
-
44
- const SOURCE_OR_DEPENDENCY = new Set(["FsStatusOutdated", "PathToSourceChanged", "NumberOfDependenciesChanged", "UnitDependencyNameChanged", "UnitDependencyInfoChanged", "LocalLengthsChanged", "PrecalculatedComponentsChanged", "DepInfoOutputChanged", "RerunIfChangedOutputFileChanged", "RerunIfChangedOutputPathsChanged"]);
45
- const ENV_RUSTFLAGS_PROFILE_FEATURES_TARGET = new Set(["EnvVarChanged", "EnvVarsChanged", "RustflagsChanged", "ProfileConfigurationChanged", "FeaturesChanged", "DeclaredFeaturesChanged", "TargetConfigurationChanged", "CompileKindChanged", "LocalFingerprintTypeChanged", "FingerprintMethodChanged", "ConfigSettingsChanged"]);
46
-
47
- /**
48
- * The cause a reason's `kind` explains (RustRight cargo_evidence.rs `cause_of`; the vector's `causes`): the first build, a missing fingerprint (named apart, and still unexplained
49
- * by itself), a toolchain change, a source or dependency change, an environment, rustflags, profile, features or target change. Any other kind, one Cargo adds later included, is `unexplained`.
50
- */
51
- export function causeOf(kind) {
52
- if (kind === "FreshBuild") return "first-build";
53
- if (kind === "FingerprintMissing") return "fingerprint-missing";
54
- if (kind === "RustcChanged") return "toolchain-changed";
55
- if (SOURCE_OR_DEPENDENCY.has(kind)) return "source-or-dependency-changed";
56
- if (ENV_RUSTFLAGS_PROFILE_FEATURES_TARGET.has(kind)) return "env-rustflags-profile-features-or-target-changed";
57
- return "unexplained";
58
- }
59
-
60
- /** Whether a `Caused by:` line says the fingerprint file was absent: `No such file or directory (os error 2)` on Unix, `... (os error 2)` or `... path specified. (os error 3)` on Windows. */
61
- const missingFingerprint = (cause) => cause.endsWith("(os error 2)") || cause.endsWith("(os error 3)");
62
-
63
- /** The profile directory a command line selects (RustRight `cargo_profile_directory`): `--release`/`-r`, `--profile X` (`dev` and `test` are `debug`, `bench` is `release`, a custom name is itself); nothing after `--`. */
64
- export function cargoProfileDirectory(argv) {
65
- let profile = null; let release = false;
66
- const words = Array.isArray(argv) ? argv.map(String) : [];
67
- for (let i = 0; i < words.length && words[i] !== "--"; i += 1) {
68
- const item = words[i];
69
- if (item === "--release" || item === "-r") release = true;
70
- else if (item === "--profile") profile = words[i + 1] ?? null;
71
- else if (item.startsWith("--profile=")) profile = item.slice("--profile=".length);
72
- }
73
- if (profile === "dev" || profile === "test") return "debug";
74
- if (profile === "bench") return "release";
75
- if (profile !== null) return profile;
76
- return release ? "release" : "debug";
77
- }
78
-
79
- /** Whether a command line asks for JSON messages (`--message-format json*` in any spelling, before `--`). */
80
- export function wantsCargoJson(argv) {
81
- const words = Array.isArray(argv) ? argv.map(String) : [];
82
- for (let i = 0; i < words.length; i += 1) {
83
- const item = words[i];
84
- if (item === "--") break;
85
- const value = item === "--message-format" ? words[i + 1] : item.startsWith("--message-format=") ? item.slice("--message-format=".length) : undefined;
86
- if (value !== undefined && value.split(",").some((segment) => segment.startsWith("json"))) return true;
87
- }
88
- return false;
89
- }
90
-
91
- /** The triples a command line names with `--target` (before `--`), then `CARGO_BUILD_TARGET` when the line names none. */
92
- export function cargoTargetTriples(argv, env = {}) {
93
- const words = Array.isArray(argv) ? argv.map(String) : [];
94
- const found = [];
95
- for (let i = 0; i < words.length && words[i] !== "--"; i += 1) {
96
- const item = words[i];
97
- const value = item === "--target" ? words[i + 1] : item.startsWith("--target=") ? item.slice("--target=".length) : undefined;
98
- if (typeof value === "string" && value !== "" && !found.includes(value)) found.push(value);
99
- }
100
- if (found.length === 0) {
101
- const named = Object.entries(env ?? {}).find(([key]) => key.toUpperCase() === "CARGO_BUILD_TARGET");
102
- if (named && typeof named[1] === "string" && named[1].trim() !== "") for (const t of named[1].trim().split(/\s+/)) if (!found.includes(t)) found.push(t);
103
- }
104
- return found;
105
- }
106
-
107
- /**
108
- * The `.fingerprint` directories one compile selects in a target directory: `<target>/<triple>/<profile>/.fingerprint` for each selected triple, then `<target>/<profile>/.fingerprint`
109
- * (RustRight `fingerprint_census_start`). Never every profile or triple, never `doc` or `package`.
110
- */
111
- export function selectedFingerprintDirectories(targetDir, { argv = [], triples = [] } = {}) {
112
- const profile = cargoProfileDirectory(argv);
113
- const found = [];
114
- for (const triple of triples) { const dir = path.join(targetDir, triple, profile, ".fingerprint"); if (!found.includes(dir)) found.push(dir); }
115
- const plain = path.join(targetDir, profile, ".fingerprint");
116
- if (!found.includes(plain)) found.push(plain);
117
- return found;
118
- }
119
-
120
- const stripAnsi = (text) => text.replace(/\u001b\[[^A-Za-z]*[A-Za-z]/g, "");
121
- const afterPrefix = (message, prefixes) => {
122
- for (const prefix of prefixes) if (message.startsWith(prefix)) return message.slice(prefix.length);
123
- return null;
124
- };
125
-
126
- /** `name version` and the target of the unit a dirty line names (the span carries `target="..."`; the message `<name> v<ver> (<src>)/<mode>/...`). */
127
- function unitOf(prefix, rest) {
128
- let target = null;
129
- const at = prefix.indexOf('target="');
130
- if (at >= 0) {
131
- const value = prefix.slice(at + 8);
132
- const end = value.indexOf('"');
133
- if (end >= 0) target = value.slice(0, end);
134
- }
135
- const head = rest.split("/")[0] ?? rest;
136
- const unit = (head.split(" (")[0] ?? head).trim();
137
- return { unit, target };
138
- }
139
-
140
- /** The reason's variant name (`FsStatusOutdated`, `RustflagsChanged`, ...): what a summary groups by. */
141
- const reasonKind = (reason) => {
142
- const kind = reason.split(/[^\p{L}\p{N}_]/u)[0];
143
- return kind ? kind : "unknown";
144
- };
145
-
146
- /** Reads Cargo's fingerprint log from a process's standard error; `strip` keeps its lines out of what the caller sees. */
147
- export class FingerprintLog {
148
- constructor({ strip = false } = {}) {
149
- this.strip = strip;
150
- this.partial = "";
151
- this.current = null;
152
- this.dirtyUnits = 0;
153
- this.reasons = [];
154
- this.truncated = 0;
155
- // Cargo printed its first execution-phase status line: later fingerprint lines are not the root's (a nested Cargo's).
156
- this.executing = false;
157
- // The reason just recorded was Cargo's `failed to read` of a `.fingerprint` file: its `Caused by:` chain follows on the next lines and says whether the file was simply absent.
158
- this.awaitingCause = null;
159
- }
160
-
161
- /** One chunk of standard error in; what the caller sees out. Without stripping that is the chunk itself. */
162
- feed(chunk) {
163
- this.partial += String(chunk);
164
- let shown = "";
165
- for (let at = this.partial.indexOf("\n"); at >= 0; at = this.partial.indexOf("\n")) {
166
- const line = this.partial.slice(0, at + 1);
167
- this.partial = this.partial.slice(at + 1);
168
- const isLog = this.#line(line);
169
- if (!isLog || !this.strip) shown += line;
170
- }
171
- if (this.partial.length > PARTIAL_CAP) {
172
- const rest = this.partial;
173
- this.partial = "";
174
- if (this.strip) shown += rest;
175
- }
176
- return this.strip ? shown : String(chunk);
177
- }
178
-
179
- /** The end of the stream: a held partial line is judged and, when stripping and it is not a log line, returned. */
180
- finish() {
181
- const rest = this.partial;
182
- this.partial = "";
183
- if (rest === "" || this.#line(rest) || !this.strip) return "";
184
- return rest;
185
- }
186
-
187
- /** Whether `raw` is one of the ROOT's fingerprint lines (counted, and stripped when stripping). */
188
- #line(raw) {
189
- const line = stripAnsi(raw.replace(/\s+$/, ""));
190
- // GB-68: after the first execution status word nothing is the root's: nested Cargo chatter is neither counted nor stripped.
191
- if (this.executing) { this.awaitingCause = null; return false; }
192
- const first = line.trim().split(/\s+/)[0];
193
- if (EXECUTION_WORDS.has(first)) { this.executing = true; return false; }
194
- // The `Caused by:` chain of a `failed to read` reason: the heading, then the cause, indented. Blank lines inside the chain belong to it.
195
- if (this.awaitingCause !== null) {
196
- const text = line.trim();
197
- if (text === "") return true;
198
- if (!this.awaitingCause.headingSeen && text === "Caused by:") { this.awaitingCause.headingSeen = true; return true; }
199
- const { index, headingSeen } = this.awaitingCause;
200
- this.awaitingCause = null;
201
- if (headingSeen && /^\s/.test(line)) {
202
- if (missingFingerprint(text) && this.reasons[index]) { this.reasons[index].kind = "FingerprintMissing"; this.reasons[index].cause = causeOf("FingerprintMissing"); }
203
- return true;
204
- }
205
- }
206
- const at = line.indexOf(FINGERPRINT_TARGET);
207
- if (at < 0) return false;
208
- const message = line.slice(at + FINGERPRINT_TARGET.length).replace(/^:+/, "").trim();
209
- const unitLine = afterPrefix(message, ["fingerprint dirty for ", "fingerprint error for "]);
210
- if (unitLine !== null) {
211
- this.dirtyUnits += 1;
212
- this.current = unitOf(line.slice(0, at), unitLine);
213
- return true;
214
- }
215
- const reason = afterPrefix(message, ["dirty:", "err:"]);
216
- if (reason !== null) this.#record(reason.trim());
217
- return true;
218
- }
219
-
220
- #record(reason) {
221
- if (this.reasons.length >= REASONS_CAP) { this.truncated += 1; return; }
222
- const { unit, target } = this.current ?? { unit: "unknown", target: null };
223
- const chars = Array.from(reason);
224
- const text = chars.length > REASON_TEXT_CAP ? `${chars.slice(0, REASON_TEXT_CAP).join("")}\u2026` : reason;
225
- const kind = reasonKind(reason);
226
- this.reasons.push({ unit, target, kind, cause: causeOf(kind), reason: text });
227
- const readsFingerprint = reason.startsWith("failed to read `") && (reason.includes("/.fingerprint/") || reason.includes("\\.fingerprint\\"));
228
- this.awaitingCause = readsFingerprint ? { index: this.reasons.length - 1, headingSeen: false } : null;
229
- }
230
-
231
- /** What another log's reading adds to this one (the census keeps one aggregate over every compiling process). */
232
- merge(other) {
233
- this.dirtyUnits += other.dirtyUnits;
234
- this.truncated += other.truncated;
235
- for (const reason of other.reasons) {
236
- if (this.reasons.length >= REASONS_CAP) this.truncated += 1;
237
- else this.reasons.push(reason);
238
- }
239
- }
240
- }
241
-
242
- // Cargo subcommands that compile a workspace's units (the wrapper's COMPILE set without metadata and package, which the census
243
- // does not count). `--` ends cargo's own arguments; `--color` and `--explain` take a value.
244
- const COMPILING = new Set(["build", "b", "check", "c", "test", "t", "bench", "run", "r", "doc", "d", "rustc", "rustdoc", "clippy"]);
245
- const GLOBAL_VALUE = new Set(["--color", "--explain"]);
246
-
247
- /** True when `command args` is a cargo process that compiles a workspace's units (its fingerprint log is the census's). */
248
- export function compilesWorkspace(command, args) {
249
- if (path.basename(String(command)).replace(/\.exe$/i, "") !== "cargo") return false;
250
- const words = Array.isArray(args) ? args : [];
251
- let i = typeof words[0] === "string" && words[0].startsWith("+") ? 1 : 0;
252
- for (; i < words.length; i += 1) {
253
- const w = String(words[i]);
254
- if (w === "--") return false;
255
- if (GLOBAL_VALUE.has(w)) { i += 1; continue; }
256
- if (w.startsWith("-")) continue;
257
- return COMPILING.has(w);
258
- }
259
- return false;
260
- }
261
-
262
- /** An error that says the path is not there (an empty profile), as opposed to being there and unreadable. */
263
- const isAbsent = (error) => error?.code === "ENOENT";
264
-
265
- /** The fingerprint directory's entries: `{ names }`, `{ names: [] }` when it is absent, or `{ error }` when it exists and cannot be read (a file, permission, I/O: never read as empty). */
266
- function readFingerprintDirectory(dir, fsApi) {
267
- try { return { names: fsApi.readdirSync(dir) }; } catch (error) { return isAbsent(error) ? { names: [] } : { error: `${dir}: ${error?.code ?? error?.message ?? "unreadable"}` }; }
268
- }
269
-
270
- /**
271
- * The `build.target` triples `.cargo/config.toml` / `.cargo/config` name for a compile run from `cwd` (the process's own directory upward, then `$CARGO_HOME`): the compile's output then
272
- * sits under `<target>/<triple>/<profile>`, so the selected scope must name it as `--target` would. A simple reader of the `[build]` table's `target` string or string list.
273
- */
274
- export function configuredBuildTargets(cwd, { env = {}, fsApi = fs } = {}) {
275
- const files = [];
276
- if (typeof cwd === "string" && cwd) for (let dir = path.resolve(cwd); ; dir = path.dirname(dir)) { files.push(path.join(dir, ".cargo", "config.toml"), path.join(dir, ".cargo", "config")); if (path.dirname(dir) === dir) break; }
277
- const home = Object.entries(env ?? {}).find(([key]) => key.toUpperCase() === "CARGO_HOME")?.[1];
278
- if (typeof home === "string" && home) files.push(path.join(home, "config.toml"), path.join(home, "config"));
279
- for (const file of files) {
280
- let text;
281
- try { text = fsApi.readFileSync(file, "utf8"); } catch { continue; }
282
- let inBuild = false;
283
- for (const raw of String(text).split(/\r?\n/)) {
284
- const line = raw.replace(/#.*$/, "").trim();
285
- const table = /^\[\s*([^\]]+?)\s*\]$/.exec(line);
286
- if (table) { inBuild = table[1] === "build"; continue; }
287
- const dotted = /^build\.target\s*=\s*(.+)$/.exec(line);
288
- const plain = inBuild ? /^target\s*=\s*(.+)$/.exec(line) : null;
289
- const value = (dotted ?? plain)?.[1];
290
- if (value !== undefined) return [...value.matchAll(/["']([^"']+)["']/g)].map((m) => m[1]);
291
- }
292
- }
293
- return [];
294
- }
295
-
296
- /**
297
- * One census for one stage of a direct compile: `start()` before the scans, `wrapSpawn(spawn)` around the scan runner's spawner (it selects each compiling cargo process's scope and
298
- * turns the fingerprint log on for it only), `finish()` after them. `start({ argv, triples, env })` selects a scope itself (a caller that knows the command).
299
- *
300
- * The scope is what the compiling processes SELECT (cargoProfileDirectory, cargoTargetTriples), not every profile directory of the target: each selected directory's baseline is read
301
- * before the first process that selects it, and `since` is the census start. A directory that exists and cannot be read, at the baseline or in the walk, makes the census
302
- * unavailable (`fingerprint-census-read-failed`); with no compiling process there is no scope and the census is unavailable (`fingerprint-census-no-compiling-process`).
303
- */
304
- export function createFreshnessCensus({ targetDirs, now = Date.now, fsApi = fs, cap = CENSUS_ENTRY_CAP } = {}) {
305
- const dirs = [...new Set(Object.values(targetDirs ?? {}).filter((d) => typeof d === "string" && d))];
306
- const log = new FingerprintLog({ strip: false });
307
- let since = null; let processes = 0; let outputCut = false;
308
- const baselines = new Map(); // fingerprint directory -> { count } | { error }
309
- let unitsAtStart = 0; let capped = false; let readError = null; let selected = false;
310
-
311
- const select = ({ argv = [], triples = null, env = {}, cwd = null } = {}) => {
312
- const named = triples ?? [...cargoTargetTriples(argv, env), ...(cargoTargetTriples(argv, env).length === 0 ? configuredBuildTargets(cwd, { env, fsApi }) : [])];
313
- for (const targetDir of dirs) {
314
- for (const dir of selectedFingerprintDirectories(targetDir, { argv, triples: [...new Set(named)] })) {
315
- selected = true;
316
- if (baselines.has(dir)) continue;
317
- const read = readFingerprintDirectory(dir, fsApi);
318
- if (read.error !== undefined) { baselines.set(dir, { error: read.error }); readError ??= read.error; continue; }
319
- baselines.set(dir, { count: read.names.length });
320
- unitsAtStart += read.names.length;
321
- if (unitsAtStart > cap) capped = true;
322
- }
323
- }
324
- };
325
-
326
- /** Walks the selected directories: the units' newest file times, or why the walk cannot be trusted. */
327
- const walk = () => {
328
- const units = new Map();
329
- let visited = 0;
330
- for (const dir of baselines.keys()) {
331
- const read = readFingerprintDirectory(dir, fsApi);
332
- if (read.error !== undefined) return { reason: "fingerprint-census-read-failed" };
333
- for (const name of read.names) {
334
- visited += 1;
335
- if (visited > cap) return { reason: "fingerprint-census-entry-cap-exceeded" };
336
- const unitDir = path.join(dir, name);
337
- let newest = 0;
338
- let files = [];
339
- try { files = fsApi.readdirSync(unitDir); } catch (error) {
340
- // A unit that vanished meanwhile, or is a plain file, holds no files; any other failure means its freshness was never read.
341
- if (!isAbsent(error) && error?.code !== "ENOTDIR") return { reason: "fingerprint-census-read-failed" };
342
- }
343
- for (const file of files) {
344
- visited += 1;
345
- if (visited > cap) return { reason: "fingerprint-census-entry-cap-exceeded" };
346
- try { newest = Math.max(newest, fsApi.statSync(path.join(unitDir, file)).mtimeMs); } catch { /* vanished: it holds no time */ }
347
- }
348
- units.set(unitDir, newest);
349
- }
350
- }
351
- return { units };
352
- };
353
-
354
- return {
355
- start(selection) { since = now(); if (selection) select(selection); },
356
- select,
357
- /** What the selection reads at the start: the directories, the units counted there, whether the entry cap was passed and the first read error. */
358
- scope() { return { directories: [...baselines.keys()], unitsAtStart, capped, readError }; },
359
- wrapSpawn(spawn) {
360
- return async (command, args, options = {}) => {
361
- if (!compilesWorkspace(command, args)) return spawn(command, args, options);
362
- const env = options.env ?? process.env;
363
- if (since !== null) select({ argv: Array.isArray(args) ? args : [], env, cwd: options.cwd ?? process.cwd() });
364
- // A caller's own CARGO_LOG stands and stays visible; the gate's own is kept out of the output.
365
- const ours = !Object.keys(env).some((k) => k.toUpperCase() === "CARGO_LOG");
366
- const result = await spawn(command, args, ours ? { ...options, env: { ...env, CARGO_LOG: FINGERPRINT_LOG_FILTER } } : options);
367
- processes += 1;
368
- if (!result || typeof result.stderr !== "string") return result;
369
- if (result.truncated) outputCut = true;
370
- const reading = new FingerprintLog({ strip: ours });
371
- const shown = reading.feed(result.stderr) + reading.finish();
372
- log.merge(reading);
373
- return { ...result, stderr: shown };
374
- };
375
- },
376
- finish() {
377
- const base = { source: FRESHNESS_SOURCE, cargoProcesses: processes, dirtyUnits: log.dirtyUnits, truncated: log.truncated, ...(outputCut ? { outputCut: true } : {}) };
378
- const unavailable = (reason) => ({ unitsAtStart: 0, fresh: 0, notFresh: 0, invalidationReasons: log.reasons, available: false, reason, ...base });
379
- if (since === null) return unavailable("fingerprint-census-not-started");
380
- if (!selected) return unavailable("fingerprint-census-no-compiling-process");
381
- if (capped) return unavailable("fingerprint-census-entry-cap-exceeded");
382
- if (readError !== null) return unavailable("fingerprint-census-read-failed");
383
- const end = walk();
384
- if (end.reason) return unavailable(end.reason);
385
- if (end.units.size === 0) return unavailable("no-fingerprint-units-found");
386
- let notFresh = 0;
387
- for (const newest of end.units.values()) if (newest >= since) notFresh += 1;
388
- return { unitsAtStart, fresh: end.units.size - notFresh, notFresh, invalidationReasons: log.reasons, available: true, ...base };
389
- },
390
- };
391
- }
392
-
393
- const isCount = (n) => Number.isInteger(n) && n >= 0;
394
-
395
- /** What is wrong with a `freshness` object (an empty list: it is the census the contract names, well formed). */
396
- export function validateFreshness(freshness) {
397
- const problems = [];
398
- if (!freshness || typeof freshness !== "object" || Array.isArray(freshness)) return ["freshness is absent"];
399
- for (const key of ["unitsAtStart", "fresh", "notFresh"]) if (!isCount(freshness[key])) problems.push(`freshness.${key} is not a count`);
400
- if (!Array.isArray(freshness.invalidationReasons)) problems.push("freshness.invalidationReasons is not a list");
401
- else freshness.invalidationReasons.forEach((r, i) => { if (!r || typeof r.unit !== "string" || typeof r.kind !== "string" || typeof r.reason !== "string") problems.push(`freshness.invalidationReasons[${i}] has no unit, kind and reason`); else if (r.cause !== undefined && typeof r.cause !== "string") problems.push(`freshness.invalidationReasons[${i}].cause is not a string`); });
402
- if (freshness.available !== undefined && typeof freshness.available !== "boolean") problems.push("freshness.available is not a boolean");
403
- if (freshness.available === false && typeof freshness.reason !== "string") problems.push("an unavailable census names no reason");
404
- return problems;
405
- }