mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-04 12:50:37 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - On 8-core PR runners (`45592683902`, `45578886514`), `Verify Paperclip Runner (static checks)` was the #3 PR critical-path straggler at `192s–222s` (`142s–178s` inside `check:static`) because `check:static` ran every build, contract check, prep test, and API-authority Vitest suite serially on a single chain—rebuilding `@paperclipai/paperclip-eval-kernel` 4 times, repeating `acpx-profiles`/`protocol-types`/`tsc` twice, re-parsing Rust files uncached in `contract-fingerprints.mjs` (`26s`), running a duplicate contract test behind a serial `&&` barrier (`52s`), and running `check-api-authority.mjs` (`75s`) without `--project @paperclipai/server` or shared-PG `fsync=off`. > - This pull request eliminates every redundant rebuild/check inside `packages/paperclip-runner`, memoizes `contract-fingerprints.mjs` by content hash (`sha1`, bit-for-bit identical digest, `10x` faster), consolidates `test:typescript:prep` into one parallel `node:test` runner, wires `check-api-authority.mjs` to `--project @paperclipai/server` + disposable shared PostgreSQL while preserving standalone self-contained execution for `release-verify.yml`, and orchestrates `check:static` via a race-free 5-phase DAG (`run-check-static.mjs`) that overlaps disjoint builds and tests across available CPU cores. > - All changes stay strictly within `packages/paperclip-runner/` and preserve 100% of original static, protocol, build, prep-test, and API-authority checks. ## Linked Issues or Issue Description Refs #22804 **What existing behavior does this improve?** Execution speed of `pnpm --filter @paperclipai/paperclip-runner run check:static` (`Verify Paperclip Runner (static checks)` CI job) on multi-core runners. **Subsystem affected** packages/paperclip-runner/ — static checks, contract fingerprinting, and prep/authority test orchestration **Current behavior** `check:static` chains `check:eval-kernel && check:protocol-without-vitest && check:api-authority` serially, rebuilding `paperclip-eval-kernel` 4x, running `tsc` and protocol checks 2x, re-stripping/re-parsing Rust sources uncached in `contract-fingerprints.mjs`, running `acpx-message-boundaries-package-contract.test.mjs` twice across a serial `&&` barrier, and running `check-api-authority.mjs` without `--project @paperclipai/server` or disposable shared PG. **Proposed behavior** Memoize Rust comment-stripping/parsing in `contract-fingerprints.mjs` with bit-for-bit identical digest parity, merge `test:typescript:prep` into one deduplicated parallel runner (`run-prep-tests.mjs`), add `--project @paperclipai/server` + disposable shared PostgreSQL + `--skip-build` to `check-api-authority.mjs`, and execute `check:static` via a race-free 5-phase parallel DAG (`run-check-static.mjs`). ## What Changed - **Memoized contract fingerprinting (`packages/paperclip-runner/scripts/contracts/contract-fingerprints.mjs`, `contract-fingerprints.test.mjs`):** - Added content-addressed (`sha1`) caches for `stripRustComments`, `withoutTestModules`, `rustSerdeItems`, per-file string constants, and `#[cfg(test)] mod` declarations, plus compact `probeCache` keys (`16.23s -> 1.63s` locally = `10.0x` speedup, bit-for-bit identical digest `sha256:bacaefb049aa9a0841fe782fefb11ede1f99222d15151873e92194e2aab9c608`). - **Deduplicated parallel prep test runner (`packages/paperclip-runner/scripts/run-prep-tests.mjs`):** - Removed duplicate `test/acpx-message-boundaries-package-contract.test.mjs` and merged the 8 Copilot `node:test` files plus `run-check-static.test.mjs` into one parallel `node-test.mjs` invocation (`44` unique suites, no serial `&&` barrier). - **Optimized API-authority verification (`packages/paperclip-runner/scripts/check-api-authority.mjs`):** - Scoped Vitest to `--project @paperclipai/server`, wrapped with `scripts/ci/vitest-shared-postgres.mjs` when no external test PG URL is supplied, and added `--skip-build` / `--dry-run` while keeping standalone `pnpm run check:api-authority` (used by `release-verify.yml`) 100% self-contained. - **Race-free 5-phase parallel `check:static` orchestrator (`packages/paperclip-runner/scripts/run-check-static.mjs`, `run-check-static.test.mjs`, `packages/paperclip-runner/package.json`):** - Phase 1: `check:eval-kernel` (builds & tests `eval-kernel` once). - Phase 2 (parallel, read-only): `acpx-profiles`, `antigravity-models`, `protocol-manifest`, 6 `node --check` checks, 4 `protocol-types` checks (each once). - Phase 3 (3 disjoint parallel chains): (A) TS builds + entrypoints + copilot assets + replay goldens, (B) serialized Cargo debug then release builds (zero `target/.cargo-lock` contention), (C) `plugin-sdk ensure-build-deps`. - Phase 4: `stage-runner-binary.mjs` after A and B complete. - Phase 5 (parallel): `run-prep-tests.mjs --skip-build` alongside `check-api-authority.mjs --skip-build` with buffered per-step output and signal forwarding. ## Verification - Verified exact digest parity: `sha256:bacaefb049aa9a0841fe782fefb11ede1f99222d15151873e92194e2aab9c608` (unchanged) - `node --test packages/paperclip-runner/scripts/contracts/contract-fingerprints.test.mjs packages/paperclip-runner/scripts/run-check-static.test.mjs packages/paperclip-runner/scripts/build-inputs.test.mjs packages/paperclip-runner/scripts/stage-runner-binary.test.mjs` — **35/35 PASS** (`2.46s`) - `node packages/paperclip-runner/scripts/run-check-static.mjs --dry-run` and `node packages/paperclip-runner/scripts/check-api-authority.mjs --dry-run` — **PASS** - `node scripts/check-test-budget.mjs --base origin/master`, `node scripts/check-maps.mjs`, `node --test scripts/check-test-budget.test.mjs scripts/__tests__/run-vitest-stable-pr-mode.test.mjs scripts/__tests__/runner-release-crate-cache.test.mjs .github/scripts/tests/ci-plan.test.mjs` — **PASS** - Live Linux execution of `Verify Paperclip Runner (static checks)` (including embedded PG `check-api-authority.mjs` and Copilot asset installation) will be verified end-to-end on PR CI. ## Risks - Low risk: all changes are scoped strictly to `packages/paperclip-runner/`, Cargo builds remain serialized in one chain to avoid target lock contention, `stage-runner-binary.mjs` waits for both TS and Rust builds before touching `dist/`, and standalone `pnpm run check:api-authority` preserves full self-contained builds for `release-verify.yml`. ## Model Used - Gemini 4 Neon (High) via Antigravity agent swarm (`server-prune`, `verifier`, `ci-pipeline`). ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge
566 lines
27 KiB
JavaScript
566 lines
27 KiB
JavaScript
// Fingerprints the contracts that cross the Runner/provider-pack boundary.
|
|
// Contracts are declared as JSON (PRP and sidecar schemas, generated catalogs)
|
|
// and read structurally, with description text stripped; Rust shapes are read
|
|
// lexically (serde structs, payload keys, match literals, env keys). Comments,
|
|
// formatting and refactors do not change a fingerprint; a new field, accepted
|
|
// value or env key does. build-provider-pack.mjs records the combined digest so
|
|
// an image pack is reused only by a controller built from the same contracts.
|
|
import { createHash } from "node:crypto";
|
|
import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
|
|
import { join, relative } from "node:path";
|
|
|
|
const R = "packages/paperclip-runner";
|
|
const RUST = `${R}/runner/crates/runner-core/src`;
|
|
const DOC_KEYS = new Set(["description", "title", "$comment", "examples", "markdownDescription"]);
|
|
|
|
/** Contract registry. Each contract binds probes; a probe reads one artifact.
|
|
* Only trees present in every pack build context are read (Docker contexts
|
|
* exclude tests, fixtures and docs), so the digest is the same wherever a pack
|
|
* is built. A TypeScript contract joins the digest by moving its definition
|
|
* into a schema under protocol/ and generating the TypeScript from it. */
|
|
export const CONTRACTS = [
|
|
{ id: "prp.schemas", expand: { kind: "json-dir", dirs: [`${R}/protocol/schemas`, `${R}/protocol/provider-schemas`] } },
|
|
{ id: "generated", expand: { dirs: [`${R}/generated`], suffix: ".json", idPrefix: "generated.", probes: [{ kind: "json", stripDocs: true }] } },
|
|
// Rust file and module names are private, so the crate is one contract whose
|
|
// values are merged across files; moving code between files changes nothing.
|
|
{ id: "rust", expand: { dirs: [RUST], suffix: ".rs", aggregate: true, probes: [
|
|
{ kind: "rust-serde" }, { kind: "rust-json-keys" }, { kind: "rust-match-literals" }, { kind: "rust-env-keys" },
|
|
] } },
|
|
// Reserved and forwarded runtime env keys are const lists in Rust.
|
|
{ id: "configured-environment", probes: [{ kind: "rust-consts", path: `${RUST}/configured_environment.rs` }] },
|
|
// The Runner's ACPX patch changes the wire behaviour every ACPX harness
|
|
// shares, so it binds the pack once for all providers. Other packages may pin
|
|
// other ACPX versions; only the Runner's own version is read, and it must exist.
|
|
{ id: "acpx-patch", expand: { dirs: ["patches"], suffix: ".patch", required: true, aggregate: true, probes: [{ kind: "bytes" }],
|
|
include: readFile => {
|
|
const version = JSON.parse(readFile(`${R}/package.json`) ?? "{}").dependencies?.acpx;
|
|
return path => path === `patches/acpx@${version}.patch`;
|
|
} } },
|
|
];
|
|
|
|
/** Every hand-registered file a probe reads. */
|
|
export function probePaths() {
|
|
return CONTRACTS.flatMap(c => c.probes ?? []).map(p => p.path);
|
|
}
|
|
export function expandDirs() {
|
|
return CONTRACTS.flatMap(c => c.expand?.dirs ?? []);
|
|
}
|
|
|
|
/**
|
|
* @param {(path: string) => string | null} readFile repository-relative path
|
|
* @param {(dir: string) => string[]} listDir repository-relative file paths under dir
|
|
* @returns {Record<string, { fingerprint: string, value: unknown }>}
|
|
*/
|
|
export function fingerprintContracts(readFile, listDir) {
|
|
const out = {};
|
|
for (const contract of CONTRACTS) {
|
|
if (contract.expand?.kind === "json-dir") {
|
|
for (const path of contract.expand.dirs.flatMap(listDir).filter(p => p.endsWith(".json")).sort()) {
|
|
const value = probe({ kind: "json", path, stripDocs: true }, readFile);
|
|
out[`prp.${path.split("/").pop().replace(/\.schema\.json$|\.json$/, "")}`] = { fingerprint: digest(value), value };
|
|
}
|
|
continue;
|
|
}
|
|
if (contract.expand) {
|
|
const { dirs, suffix, include, required, exclude, idPrefix, aggregate, probes } = contract.expand;
|
|
const included = include ? include(readFile) : () => true;
|
|
const candidates = dirs.flatMap(listDir).filter(p => p.endsWith(suffix) && included(p) && !exclude?.test(p));
|
|
if (required && candidates.length === 0) throw new Error(`Registered contract source is missing: ${contract.id}`);
|
|
const testOnly = suffix === ".rs" ? rustTestOnlyFiles(candidates, readFile) : new Set();
|
|
const sources = candidates.filter(p => !testOnly.has(p)).sort();
|
|
// Env keys are often passed through `const NAME: &str = "KEY"` defined in
|
|
// another file, so resolve constant arguments crate-wide.
|
|
const constants = suffix === ".rs" ? rustStringConstants(sources, readFile) : {};
|
|
// Serde type names never reach JSON; a reference to one is replaced by the
|
|
// referenced type's shape, which may be defined in another file.
|
|
const typeShapes = suffix === ".rs" ? rustSerdeTypeShapes(sources, readFile) : {};
|
|
const constantsKey = suffix === ".rs" ? hashText(stableStringify(constants)) : "";
|
|
const typeShapesKey = suffix === ".rs" ? hashText(stableStringify(typeShapes)) : "";
|
|
const crateWide = {
|
|
"rust-env-keys": { constants, contextKey: constantsKey },
|
|
"rust-serde": { typeShapes, contextKey: typeShapesKey },
|
|
};
|
|
const values = [];
|
|
for (const path of sources) {
|
|
const value = probes.map(p => probe({ ...p, path, ...crateWide[p.kind] }, readFile));
|
|
if (isEmpty(value)) continue;
|
|
if (aggregate) { values.push(value); continue; }
|
|
const id = idPrefix + path.slice(dirs.find(d => path.startsWith(`${d}/`)).length + 1).replace(/\.[a-z]+$/, "");
|
|
out[id] = { fingerprint: digest(value), value };
|
|
}
|
|
if (aggregate) {
|
|
const value = probes.map((_, i) => union(values.map(v => v[i])));
|
|
out[contract.id] = { fingerprint: digest(value), value };
|
|
}
|
|
continue;
|
|
}
|
|
const value = contract.probes.map(p => probe(p, readFile));
|
|
// A contract whose artifacts do not exist yet has not been introduced.
|
|
if (value.every(v => v?.absent)) continue;
|
|
out[contract.id] = { fingerprint: digest(value), value };
|
|
}
|
|
return out;
|
|
}
|
|
|
|
/** Combined digest of every contract in a checkout rooted at `root`. A missing
|
|
* registered file or directory is a build-context error, never an absent
|
|
* contract, so two build contexts cannot silently disagree. */
|
|
export function packContractDigest(root, { read, list } = checkoutSources(root)) {
|
|
for (const path of probePaths()) {
|
|
if (read(path) === null) throw new Error(`Registered contract source is missing: ${path}`);
|
|
}
|
|
for (const dir of expandDirs()) {
|
|
if (list(dir).length === 0) throw new Error(`Registered contract directory is missing: ${dir}`);
|
|
}
|
|
const contracts = fingerprintContracts(read, list);
|
|
return digest(Object.fromEntries(Object.entries(contracts).map(([id, c]) => [id, c.fingerprint])));
|
|
}
|
|
|
|
/** Repository-relative readers over a checkout. */
|
|
export function checkoutSources(root) {
|
|
return {
|
|
read: path => {
|
|
const absolute = join(root, path);
|
|
return existsSync(absolute) && statSync(absolute).isFile() ? readFileSync(absolute, "utf8") : null;
|
|
},
|
|
list: dir => existsSync(join(root, dir)) ? readdirSync(join(root, dir), { recursive: true, withFileTypes: true })
|
|
.filter(entry => entry.isFile())
|
|
.map(entry => relative(root, join(entry.parentPath, entry.name)).split("\\").join("/")) : [],
|
|
};
|
|
}
|
|
|
|
/** Merges probe values from several files: lists become sorted sets and
|
|
* objects merge by key. */
|
|
function union(values) {
|
|
if (values.every(Array.isArray)) return [...new Set(values.flat())].sort();
|
|
const keys = [...new Set(values.flatMap(Object.keys))].sort();
|
|
return Object.fromEntries(keys.map(k => [k, union(values.map(v => v[k] ?? []))]));
|
|
}
|
|
/** Files that expose no contract artifacts produce no contract. */
|
|
function isEmpty(value) {
|
|
const empty = v => v == null || (Array.isArray(v) ? v.every(empty) : typeof v === "object" ? Object.values(v).every(empty) : false);
|
|
return empty(value);
|
|
}
|
|
const probeCache = new Map();
|
|
function hashText(text) {
|
|
return createHash("sha1").update(text).digest("hex");
|
|
}
|
|
function probe(spec, readFile) {
|
|
const source = readFile(spec.path);
|
|
if (source === null) return { absent: true };
|
|
const sourceHash = hashText(source);
|
|
const key = `${spec.kind}\0${spec.path}\0${spec.stripDocs ? 1 : 0}\0${spec.contextKey ?? ""}\0${sourceHash}`;
|
|
if (!probeCache.has(key)) probeCache.set(key, probeUncached(spec, source, sourceHash));
|
|
return probeCache.get(key);
|
|
}
|
|
function probeUncached(spec, source, sourceHash) {
|
|
switch (spec.kind) {
|
|
case "json": return canonicalJson(JSON.parse(source), spec);
|
|
case "bytes": return [`${spec.path.split("/").pop()}:${digest(source)}`];
|
|
case "rust-consts": return rustConsts(source, sourceHash);
|
|
case "rust-serde": return rustSerde(source, spec.typeShapes ?? {}, sourceHash);
|
|
case "rust-json-keys": return rustJsonKeys(source, sourceHash);
|
|
case "rust-match-literals": return rustMatchLiterals(source, sourceHash);
|
|
case "rust-env-keys": return rustEnvKeys(source, spec.constants ?? {}, sourceHash);
|
|
default: throw new Error(`unknown probe kind ${spec.kind}`);
|
|
}
|
|
}
|
|
|
|
// ---------- canonical values ----------
|
|
|
|
export function digest(value) {
|
|
return `sha256:${createHash("sha256").update(stableStringify(value)).digest("hex")}`;
|
|
}
|
|
function stableStringify(value) {
|
|
if (Array.isArray(value)) return `[${value.map(stableStringify).join(",")}]`;
|
|
if (value && typeof value === "object") {
|
|
return `{${Object.keys(value).sort().map(k => `${JSON.stringify(k)}:${stableStringify(value[k])}`).join(",")}}`;
|
|
}
|
|
return JSON.stringify(value ?? null);
|
|
}
|
|
/** With `stripDocs`, drops schema annotations (description, title, $comment,
|
|
* examples) by their value shape: annotations are text or example lists, while
|
|
* a property declared as `properties.description` holds a schema object and is
|
|
* kept with its constraints. */
|
|
function canonicalJson(value, { stripDocs = false } = {}) {
|
|
if (Array.isArray(value)) return value.map(v => canonicalJson(v, { stripDocs }));
|
|
if (value && typeof value === "object") {
|
|
return Object.fromEntries(Object.entries(value)
|
|
.filter(([k, v]) => !(stripDocs && isAnnotation(k, v)))
|
|
.map(([k, v]) => [k, canonicalJson(v, { stripDocs })]));
|
|
}
|
|
return value;
|
|
}
|
|
function isAnnotation(key, value) {
|
|
return DOC_KEYS.has(key) && (typeof value === "string" || (key === "examples" && Array.isArray(value)));
|
|
}
|
|
|
|
// ---------- Rust (lexical, no syn available) ----------
|
|
|
|
const strippedRustCache = new Map();
|
|
const withoutTestModulesCache = new Map();
|
|
const rustSerdeItemsCache = new Map();
|
|
const rustFileStringConstsCache = new Map();
|
|
const rustTestModDeclsCache = new Map();
|
|
|
|
function stripRustComments(source, sourceHash = hashText(source)) {
|
|
const cached = strippedRustCache.get(sourceHash);
|
|
if (cached !== undefined) return cached;
|
|
const chunks = [];
|
|
let chunkStart = 0;
|
|
let i = 0;
|
|
const len = source.length;
|
|
while (i < len) {
|
|
const c = source[i], n = source[i + 1];
|
|
if (c === "/" && n === "/") {
|
|
if (i > chunkStart) chunks.push(source.slice(chunkStart, i));
|
|
while (i < len && source[i] !== "\n") i++;
|
|
chunkStart = i;
|
|
continue;
|
|
}
|
|
if (c === "/" && n === "*") {
|
|
if (i > chunkStart) chunks.push(source.slice(chunkStart, i));
|
|
let depth = 1;
|
|
i += 2;
|
|
while (i < len && depth) {
|
|
if (source[i] === "/" && source[i + 1] === "*") { depth++; i += 2; }
|
|
else if (source[i] === "*" && source[i + 1] === "/") { depth--; i += 2; }
|
|
else i++;
|
|
}
|
|
chunkStart = i;
|
|
continue;
|
|
}
|
|
if (c === "r" && (n === '"' || n === "#") && !/[\w]/.test(source[i - 1] ?? "")) {
|
|
const raw = /^r(#*)"/.exec(source.slice(i, i + 10));
|
|
if (raw) {
|
|
const end = source.indexOf(`"${raw[1]}`, i + raw[0].length);
|
|
if (end === -1) break;
|
|
i = end + 1 + raw[1].length;
|
|
continue;
|
|
}
|
|
}
|
|
if (c === '"') {
|
|
let j = i + 1;
|
|
while (j < len && source[j] !== '"') j += source[j] === "\\" ? 2 : 1;
|
|
i = j + 1;
|
|
continue;
|
|
}
|
|
if (c === "'") {
|
|
const m = /^'(\\.|[^\\'])'/.exec(source.slice(i, i + 4));
|
|
if (m) { i += m[0].length; continue; }
|
|
}
|
|
i++;
|
|
}
|
|
if (chunkStart < len) chunks.push(source.slice(chunkStart));
|
|
const out = chunks.length === 1 ? chunks[0] : chunks.join("");
|
|
strippedRustCache.set(sourceHash, out);
|
|
return out;
|
|
}
|
|
function withoutTestModulesForSource(source, sourceHash = hashText(source)) {
|
|
const cached = withoutTestModulesCache.get(sourceHash);
|
|
if (cached !== undefined) return cached;
|
|
const out = withoutTestModules(stripRustComments(source, sourceHash));
|
|
withoutTestModulesCache.set(sourceHash, out);
|
|
return out;
|
|
}
|
|
function rustTestModDecls(source, sourceHash = hashText(source)) {
|
|
const cached = rustTestModDeclsCache.get(sourceHash);
|
|
if (cached !== undefined) return cached;
|
|
const declaration = /#\[cfg\(test\)\]\s*((?:#\[[^\]]*\]\s*)*)(?:pub(?:\([^)]*\))?\s+)?mod\s+(\w+)\s*;/g;
|
|
const decls = [];
|
|
for (const m of stripRustComments(source, sourceHash).matchAll(declaration)) {
|
|
const explicit = /#\[path\s*=\s*"([^"]+)"\s*\]/.exec(m[1])?.[1] ?? null;
|
|
decls.push({ explicit, name: m[2] });
|
|
}
|
|
rustTestModDeclsCache.set(sourceHash, decls);
|
|
return decls;
|
|
}
|
|
/** Files compiled only under `#[cfg(test)]`: modules declared as
|
|
* `#[cfg(test)] [#[path = "..."]] mod name;`, their submodules, and files under
|
|
* a test module's directory. Inline `#[cfg(test)] mod name { .. }` blocks are
|
|
* removed separately by withoutTestModules. */
|
|
function rustTestOnlyFiles(paths, readFile) {
|
|
const known = new Set(paths);
|
|
const testOnly = new Set();
|
|
const pending = [...paths];
|
|
const visit = (path) => {
|
|
const source = readFile(path);
|
|
if (source === null) return [];
|
|
const decls = rustTestModDecls(source);
|
|
if (decls.length === 0) return [];
|
|
const directory = path.slice(0, path.lastIndexOf("/"));
|
|
const file = path.slice(path.lastIndexOf("/") + 1);
|
|
const ownDirectory = /^(lib|main|mod)\.rs$/.test(file) ? directory : `${directory}/${file.replace(/\.rs$/, "")}`;
|
|
const found = [];
|
|
for (const { explicit, name } of decls) {
|
|
// A #[path] on a module declared in a non-mod.rs file resolves from the file's directory.
|
|
const targets = explicit ? [normalizePath(`${directory}/${explicit}`)]
|
|
: [`${ownDirectory}/${name}.rs`, `${ownDirectory}/${name}/mod.rs`];
|
|
for (const target of targets) {
|
|
found.push(target);
|
|
const moduleDirectory = target.endsWith("/mod.rs") ? target.slice(0, -"/mod.rs".length) : target.replace(/\.rs$/, "");
|
|
for (const other of known) if (other.startsWith(`${moduleDirectory}/`)) found.push(other);
|
|
}
|
|
}
|
|
return found.filter(target => known.has(target));
|
|
};
|
|
while (pending.length) {
|
|
for (const target of visit(pending.pop())) {
|
|
if (testOnly.has(target)) continue;
|
|
testOnly.add(target);
|
|
pending.push(target);
|
|
}
|
|
}
|
|
return testOnly;
|
|
}
|
|
function normalizePath(path) {
|
|
const parts = [];
|
|
for (const part of path.split("/")) {
|
|
if (part === "..") parts.pop();
|
|
else if (part !== "." && part !== "") parts.push(part);
|
|
}
|
|
return parts.join("/");
|
|
}
|
|
function withoutTestModules(text) {
|
|
let out = text;
|
|
for (let m; (m = /#\[cfg\(test\)\]\s*mod\s+\w+\s*\{/.exec(out));) {
|
|
let depth = 0, j = m.index + m[0].length - 1;
|
|
for (; j < out.length; j++) { if (out[j] === "{") depth++; else if (out[j] === "}" && --depth === 0) break; }
|
|
out = out.slice(0, m.index) + out.slice(j + 1);
|
|
}
|
|
return out;
|
|
}
|
|
function rustStrings(text) {
|
|
return [...text.matchAll(/"((?:\\.|[^"\\])*)"/g)].map(m => m[1]);
|
|
}
|
|
function rustConsts(source, sourceHash = hashText(source)) {
|
|
const text = stripRustComments(source, sourceHash);
|
|
const out = {};
|
|
for (const m of text.matchAll(/\b(?:pub(?:\([^)]*\))?\s+)?(?:const|static)\s+([A-Z][A-Z0-9_]*)\s*:[^=]+=/g)) {
|
|
const end = text.indexOf(";", m.index + m[0].length);
|
|
out[m[1]] = [...rustStrings(text.slice(m.index + m[0].length, end))].sort();
|
|
}
|
|
return out;
|
|
}
|
|
const SERDE_ITEM = /((?:#\[[^\]]*\]\s*)+)(?:pub(?:\([^)]*\))?\s+)?(struct|enum)\s+(\w+)(<[^>{]*>)?/g;
|
|
const isSerdeItem = attrs => /derive\([^)]*\b(Serialize|Deserialize)\b/.test(attrs);
|
|
|
|
/** Serialized shapes of a file's derive(Serialize|Deserialize) items: serde
|
|
* attributes and field/variant bodies. Rust type names never reach JSON, so
|
|
* item names are dropped and a reference to a crate serde type is replaced by
|
|
* that type's shape digest; renaming a type is not a contract change, while
|
|
* field and variant names, field types (including which shape a reference
|
|
* names) and serde attributes are. */
|
|
function rustSerde(source, typeShapes, sourceHash = hashText(source)) {
|
|
return rustSerdeItems(source, sourceHash)
|
|
.map(item => serdeShape(item, name => Object.hasOwn(typeShapes, name) ? typeShapes[name] : null))
|
|
.sort();
|
|
}
|
|
function serdeShape({ kind, serde, body }, shapeOf) {
|
|
return stableStringify({ kind, serde, body: withNormalizedTypeReferences(body, shapeOf) });
|
|
}
|
|
/** derive(Serialize|Deserialize) items with whitespace-normalized bodies. */
|
|
function rustSerdeItems(source, sourceHash = hashText(source)) {
|
|
const cached = rustSerdeItemsCache.get(sourceHash);
|
|
if (cached !== undefined) return cached;
|
|
const text = withoutTestModulesForSource(source, sourceHash);
|
|
const items = [];
|
|
for (const m of text.matchAll(SERDE_ITEM)) {
|
|
const attrs = m[1];
|
|
if (!isSerdeItem(attrs)) continue;
|
|
let i = m.index + m[0].length;
|
|
while (i < text.length && text[i] !== "{" && text[i] !== ";" && text[i] !== "(") i++;
|
|
let body = "";
|
|
if (text[i] === "{" || text[i] === "(") {
|
|
const open = text[i], close = open === "{" ? "}" : ")";
|
|
let depth = 0, j = i;
|
|
for (; j < text.length; j++) { if (text[j] === open) depth++; else if (text[j] === close && --depth === 0) break; }
|
|
body = text.slice(i, j + 1);
|
|
}
|
|
// `#[serde(skip)]` fields never reach the wire or the persisted file.
|
|
const normalized = body.replace(/#\[serde\(skip\)\]\s*(?:pub(?:\([^)]*\))?\s+)?\w+\s*:[^,{}]*(?:<[^>]*>)?[^,{}]*,?/g, "")
|
|
.replace(/\bpub(\([^)]*\))?\s+/g, "").replace(/\s+/g, " ").replace(/\s*([{}(),:<>;\[\]=])\s*/g, "$1").replace(/,([})\]])/g, "$1");
|
|
items.push({
|
|
name: m[3],
|
|
kind: m[2],
|
|
serde: (attrs.match(/#\[serde\([^\]]*\)\]/g) ?? []).map(a => a.replace(/\s+/g, "")).sort(),
|
|
body: normalized,
|
|
});
|
|
}
|
|
rustSerdeItemsCache.set(sourceHash, items);
|
|
return items;
|
|
}
|
|
/** Replaces crate serde type names in type positions (after `:`, or inside
|
|
* `(..)` and `<..>`) with `$type:<shape>`. Names directly inside `{..}` after
|
|
* `{`, `,` or an attribute are field or variant names, which serialize, and
|
|
* stay. */
|
|
function withNormalizedTypeReferences(body, shapeOf) {
|
|
const stack = [];
|
|
let previous = "";
|
|
// Quoted strings (serde renames) are wire names and pass through unchanged.
|
|
return body.replace(/"(?:\\.|[^"\\])*"|[A-Za-z_][A-Za-z0-9_]*|[^A-Za-z0-9_]/g, token => {
|
|
if (token.startsWith("\"")) { previous = "string"; return token; }
|
|
if (/^[A-Za-z_]/.test(token)) {
|
|
const namePosition = stack.at(-1) === "{" && ["{", ",", "]"].includes(previous);
|
|
previous = "ident";
|
|
const shape = namePosition ? null : shapeOf(token);
|
|
return shape === null ? token : `$type:${shape}`;
|
|
}
|
|
if ("{(<[".includes(token)) stack.push(token);
|
|
else if ("})>]".includes(token)) stack.pop();
|
|
previous = token;
|
|
return token;
|
|
});
|
|
}
|
|
/** Shape digest of every derive(Serialize|Deserialize) item across the crate,
|
|
* keyed by its Rust name. A reference inside a shape resolves to the referenced
|
|
* shape, so the digest is independent of every Rust type name. A reference back
|
|
* into the current resolution path is recorded by its depth. Items that share a
|
|
* name in different modules resolve to all of their shapes. */
|
|
function rustSerdeTypeShapes(paths, readFile) {
|
|
const byName = new Map();
|
|
for (const path of paths) {
|
|
const source = readFile(path);
|
|
if (source === null) continue;
|
|
for (const item of rustSerdeItems(source)) byName.set(item.name, [...(byName.get(item.name) ?? []), item]);
|
|
}
|
|
const resolved = new Map();
|
|
const resolve = (name, path) => {
|
|
if (resolved.has(name)) return { shape: resolved.get(name), cyclic: false };
|
|
const back = path.indexOf(name);
|
|
if (back >= 0) return { shape: `cycle:${path.length - back}`, cyclic: true };
|
|
let cyclic = false;
|
|
const shapes = byName.get(name).map(item => serdeShape(item, reference => {
|
|
if (!byName.has(reference)) return null;
|
|
const result = resolve(reference, [...path, name]);
|
|
cyclic ||= result.cyclic;
|
|
return result.shape;
|
|
})).sort();
|
|
const shape = digest(shapes).slice("sha256:".length, "sha256:".length + 16);
|
|
// A shape inside a cycle depends on where resolution entered it.
|
|
if (!cyclic) resolved.set(name, shape);
|
|
return { shape, cyclic };
|
|
};
|
|
return Object.fromEntries([...byName.keys()].sort().map(name => [name, resolve(name, []).shape]));
|
|
}
|
|
|
|
/** Payload keys built or read in code, `json!({"key": ...})`, `["key"]` and
|
|
* `.get("key")`, grouped by enclosing function. Groups carry no function name,
|
|
* so renaming or moving a function is not a contract change, while a parser
|
|
* that starts reading a different key is, even when another function already
|
|
* reads that key. */
|
|
function rustJsonKeys(source, sourceHash = hashText(source)) {
|
|
return rustScopeGroups(source, text => {
|
|
const writes = new Set(), reads = new Set();
|
|
for (const m of text.matchAll(/json!\s*\(/g)) {
|
|
const body = balanced(text, m.index + m[0].length - 1, "(", ")");
|
|
for (const k of body.matchAll(/"((?:\\.|[^"\\])*)"\s*:/g)) writes.add(k[1]);
|
|
}
|
|
for (const m of text.matchAll(/\[\s*"((?:\\.|[^"\\])*)"\s*\]|\.get\(\s*"((?:\\.|[^"\\])*)"\s*\)/g)) reads.add(m[1] ?? m[2]);
|
|
return writes.size || reads.size ? { writes: [...writes].sort(), reads: [...reads].sort() } : null;
|
|
}, sourceHash);
|
|
}
|
|
/** Inline accept-sets, string literals in `matches!(...)` and in match-arm
|
|
* patterns, grouped by enclosing function like rustJsonKeys. */
|
|
function rustMatchLiterals(source, sourceHash = hashText(source)) {
|
|
return rustScopeGroups(source, text => {
|
|
const out = new Set();
|
|
for (const m of text.matchAll(/matches!\s*\(/g)) {
|
|
for (const s of rustStrings(balanced(text, m.index + m[0].length - 1, "(", ")"))) out.add(s);
|
|
}
|
|
const lit = String.raw`"(?:\\.|[^"\\])*"`;
|
|
for (const m of text.matchAll(new RegExp(`(${lit}(?:\\s*\\|\\s*${lit})*)\\s*(?:if\\b[^=]*)?=>`, "g"))) {
|
|
for (const s of rustStrings(m[1])) out.add(s);
|
|
}
|
|
return out.size ? [...out].sort() : null;
|
|
}, sourceHash);
|
|
}
|
|
/** Applies `collect` to each outermost function body, and to the code outside
|
|
* any function, and returns the sorted set of non-empty results. */
|
|
function rustScopeGroups(source, collect, sourceHash = hashText(source)) {
|
|
const groups = rustScopes(withoutTestModulesForSource(source, sourceHash)).map(collect).filter(Boolean);
|
|
return [...new Set(groups.map(stableStringify))].sort();
|
|
}
|
|
/** Outermost `fn` bodies, then the remaining text. String contents are masked
|
|
* while locating braces, so `"{}"` format strings do not end a body early. */
|
|
function rustScopes(text) {
|
|
const masked = text.replace(/"(?:\\.|[^"\\])*"/g, m => `"${" ".repeat(m.length - 2)}"`);
|
|
const scopes = [];
|
|
let rest = "", last = 0;
|
|
const fn = /\bfn\s+\w+/g;
|
|
for (let m; (m = fn.exec(masked));) {
|
|
// A declaration without a body ends at `;` outside the signature's (..) and [..].
|
|
let i = m.index + m[0].length, depth = 0;
|
|
for (; i < masked.length; i++) {
|
|
const c = masked[i];
|
|
if (c === "(" || c === "[") depth++;
|
|
else if (c === ")" || c === "]") depth--;
|
|
else if (depth === 0 && (c === "{" || c === ";")) break;
|
|
}
|
|
if (masked[i] !== "{") continue;
|
|
const end = i + balanced(masked, i, "{", "}").length;
|
|
rest += text.slice(last, m.index);
|
|
scopes.push(text.slice(i, end));
|
|
last = end;
|
|
fn.lastIndex = end;
|
|
}
|
|
scopes.push(rest + text.slice(last));
|
|
return scopes;
|
|
}
|
|
function balanced(text, start, open, close) {
|
|
let depth = 0, j = start;
|
|
for (; j < text.length; j++) { if (text[j] === open) depth++; else if (text[j] === close && --depth === 0) break; }
|
|
return text.slice(start, j + 1);
|
|
}
|
|
/** Environment keys passed or read in code: `keys.push(K)`, `.env(K, ..)`,
|
|
* `.env_remove(K)` and `env::var(K)` / `env::var_os(K)`, where K is a string
|
|
* literal or a string constant, and key lists: `vec![..]` or `&[..]` literals
|
|
* whose elements are all key-shaped strings or constants, at least one of them
|
|
* an upper-case `NAME_WITH_UNDERSCORE`. A constant resolves to its value, so
|
|
* renaming the Rust constant is not a contract change; an unresolved constant
|
|
* keeps its name so a rename remains visible. */
|
|
function rustEnvKeys(source, constants, sourceHash = hashText(source)) {
|
|
const text = withoutTestModulesForSource(source, sourceHash);
|
|
const keys = new Set();
|
|
const constant = String.raw`(?:[a-z_][a-z0-9_]*::)*([A-Z][A-Z0-9_]*)\b`;
|
|
const resolve = (literal, name) => literal ?? constants[name] ?? `const:${name}`;
|
|
const pattern = new RegExp(String.raw`(?:keys\.push|\.env|\.env_remove|env::var|env::var_os)\(\s*(?:"([A-Z][A-Z0-9_]*)"|${constant})`, "g");
|
|
for (const m of text.matchAll(pattern)) keys.add(resolve(m[1], m[2]));
|
|
const element = new RegExp(String.raw`^\s*(?:"([A-Za-z_][A-Za-z0-9_]*)"|${constant})\s*$`);
|
|
for (const m of text.matchAll(/(?:vec!\s*|&\s*)\[/g)) {
|
|
const body = balanced(text, m.index + m[0].length - 1, "[", "]").slice(1, -1);
|
|
const parts = body.split(",").filter((part, i, all) => i < all.length - 1 || part.trim());
|
|
const matches = parts.map(part => element.exec(part));
|
|
if (!matches.length || matches.some(e => !e)) continue;
|
|
const list = matches.map(e => resolve(e[1], e[2]));
|
|
if (list.some(key => /^[A-Z][A-Z0-9]*(?:_[A-Z0-9]+)+$/.test(key))) for (const key of list) keys.add(key);
|
|
}
|
|
return [...keys].sort();
|
|
}
|
|
function rustFileStringConstants(source, sourceHash = hashText(source)) {
|
|
const cached = rustFileStringConstsCache.get(sourceHash);
|
|
if (cached !== undefined) return cached;
|
|
const text = withoutTestModulesForSource(source, sourceHash);
|
|
const entries = [];
|
|
for (const m of text.matchAll(/\b(?:pub(?:\([^)]*\))?\s+)?(?:const|static)\s+([A-Z][A-Z0-9_]*)\s*:\s*&(?:'static\s+)?str\s*=\s*"([^"\\]*)"\s*;/g)) {
|
|
entries.push([m[1], m[2]]);
|
|
}
|
|
rustFileStringConstsCache.set(sourceHash, entries);
|
|
return entries;
|
|
}
|
|
/** String constants (`const NAME: &str = "VALUE";`) across the crate's sources.
|
|
* Names defined twice with different values are ambiguous and left unresolved. */
|
|
function rustStringConstants(paths, readFile) {
|
|
const found = new Map();
|
|
for (const path of paths) {
|
|
const source = readFile(path);
|
|
if (source === null) continue;
|
|
for (const [name, value] of rustFileStringConstants(source)) {
|
|
const values = found.get(name) ?? new Set();
|
|
values.add(value);
|
|
found.set(name, values);
|
|
}
|
|
}
|
|
return Object.fromEntries([...found].filter(([, values]) => values.size === 1).map(([name, values]) => [name, [...values][0]]).sort());
|
|
}
|