From a796e43bd0fe2e028208602e6241f38b6b744d8c Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 16 Nov 2026 23:25:18 +0000 Subject: [PATCH 01/31] chore(ci): retire the frozen native diagram qualification pin (#4105) The pin let a ready PR retain browser proof from an earlier run, but the hybrid ruling moved browser proof to the squash's main run, where it is always fresh. All three pinned source files had also drifted, so the binding could no longer qualify. Its only effect left was to fail unit on every dependency change until a manual Docker requalification moved it; three requalifications produced byte-identical output. Remove the binding and its self-test, and stop the browser input closure, worker audit and inclusion inputs from carrying its identity. The container boundary and the producer's run-time checks are unchanged. A guard test keeps the retired identities from being pinned again. ci-proof.ts and visual.mjs still read the now-absent field; they are audited sources, so that dead branch goes at their next re-audit. The maintainer ruling of 2026-11-16 is recorded in ci-utility.md, superseding the 2026-11-02 and 2026-11-11 requalification rulings. Co-Authored-By: Claude Opus 5.5 --- CONTRIBUTING.md | 32 +++---- docs/decisions/ci-utility.md | 32 +++++-- docs/process/diagnostic-installs.md | 3 +- scripts/browser-input-closure.ts | 14 +-- scripts/browser-worker-audit.ts | 5 +- scripts/inclusion-inputs.ts | 4 +- scripts/native-diagram-inputs.ts | 92 ------------------- scripts/proof-inputs.ts | 6 ++ scripts/test-shard-costs.json | 1 - tests/browser-worker-audit.test.ts | 8 +- tests/native-diagram-inputs.test.ts | 127 --------------------------- tests/native-diagram-retired.test.ts | 30 +++++++ 12 files changed, 87 insertions(+), 267 deletions(-) delete mode 100644 scripts/native-diagram-inputs.ts delete mode 100644 tests/native-diagram-inputs.test.ts create mode 100644 tests/native-diagram-retired.test.ts diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index ca628ae45f..a834207ca3 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -84,30 +84,26 @@ Before instrumenting installed dependencies, follow [dependency diagnostic preparation](docs/process/diagnostic-installs.md): worktrees alone do not isolate Bun cache hardlinks. -The frozen native diagram control also requires the independently qualified -installation bytes and modes. An `installation-mismatch` with matching frozen -source is an install problem: keep its source revision, 859-file inventory and -qualification fingerprints unchanged. A frozen lockfile does not repair a -modified shared package cache, and copying that cache copies the modifications -([#1980](https://github.com/schlessera/brain-kit/issues/1980)). Recover only the -owned checkout through a fresh private cache and independent file copies, -**under umask `022`**. The installation identity includes file modes, and the -installer's umask narrows them. The qualified install was made under `022`, so -an install under any other umask, such as `0077`, never matches, even though its -package, file and byte counts are identical. The preparation script sets its own umask so -your own umask is unchanged: +The native diagram producer has no frozen qualification pin +([#4105](https://github.com/schlessera/brain-kit/issues/4105)): adding, +removing or upgrading a dependency needs no requalification, and its proof +runs fresh in the producer's Docker boundary. A frozen lockfile still does not +repair a modified shared package cache, and copying that cache copies the +modifications ([#1980](https://github.com/schlessera/brain-kit/issues/1980)). +When a check fails on installed bytes, recover only the owned checkout through +a fresh private cache and independent file copies, under umask `022`; the +preparation script sets its own umask so yours is unchanged: ```sh # Preserve evidence and move aside this owned checkout's node_modules first. sh scripts/prepare-diagnostic-install.sh -bun run test ./tests/native-diagram-inputs.test.ts ``` -Retain the failed and restored installation identities. Verify any suspected -package edits against the lockfile's archive integrity; never normalize unknown -bytes or modes to force qualification. Leave shared caches and other checkouts -alone. Use the same preparation before future dependency instrumentation; retain the -original failure evidence as described in the diagnostic guide. +Verify any suspected package edits against the lockfile's archive integrity; +never normalize unknown bytes or modes to force a pass. Leave shared caches and +other checkouts alone. Use the same preparation before future dependency +instrumentation; retain the original failure evidence as described in the +diagnostic guide. The Linux backend nonpersistence tests require `bubblewrap` and permitted user namespaces. They launch the installed Claude and pi adapters with a loopback diff --git a/docs/decisions/ci-utility.md b/docs/decisions/ci-utility.md index 530166972e..6f82a27907 100644 --- a/docs/decisions/ci-utility.md +++ b/docs/decisions/ci-utility.md @@ -1084,13 +1084,31 @@ retains the original SVG/reference zero-request replay and raster/font/PDF assertions. Different launches never share a prepared output root. The browser-side pinned font cache remains a separately owned browser input. -Qualification is tied to the exact operation, source and installed identities; -unknown readers, drift or missing inputs retain complete fresh proof. The fresh -shard independently passes its computed identity to host preparation and checks -installation/runtime identity again before emitting its existing receipt. Both -shards, independent immutable source/current validation and whole-workflow -successful eligibility retain the existing complete-domain protocol. Local proof -is not a hosted baseline, retention hit or permission to use a failed workflow. +**The frozen qualification is retired (maintainer, 2026-11-16, +[#4105](https://github.com/schlessera/brain-kit/issues/4105)).** #2293 pinned the +producer's source (`e8502b6f…`, the frozen #2293 snapshot), its installation +(a hash over every package, file, byte and mode in `node_modules`) and three +source files. That let a ready PR retain browser proof from an earlier green +run. The pin no longer protected anything live: + +- Under the [hybrid ruling](#hybrid-post-merge-heavy-proof), ready confirmation + no longer runs browser proof, and the squash's main run is always fresh. +- All three pinned source files had drifted, so the binding could not qualify + on the current tree in any case. +- Any dependency change moved the installation hash and turned `unit` red. That + needed a manual requalification run on a Docker host and a second merge + cycle. It happened three times (#3320, #3968, #4102), and the frozen + producer's SVG and PNG came out byte-identical every time. + +The binding (`scripts/native-diagram-inputs.ts`) and its self-test are +removed, and the browser input closure no longer binds the producer's reads. +The browser domain therefore always runs fresh. This supersedes the +requalification rulings of 2026-11-02 (#2509/#3320) and 2026-11-11 (#3968). +The container boundary above, the producer's own run-time identity checks and +the browser's validation of the handoff are unchanged. If browser retention +returns to ready confirmation, its qualification is designed afresh then. +Local proof is not a hosted baseline, retention hit or permission to use a +failed workflow. Two audited fixture readers consume the literal installed `axe-core/axe.min.js` asset. Its explicit resource identity records package name/version, relative diff --git a/docs/process/diagnostic-installs.md b/docs/process/diagnostic-installs.md index af12fbe708..c6a72d652c 100644 --- a/docs/process/diagnostic-installs.md +++ b/docs/process/diagnostic-installs.md @@ -35,8 +35,7 @@ copy alone proves neither provenance nor pristine package bytes. Keep the original and recovered observations separate. Do not change package versions, locks, assertions, qualification pins or file modes to force a pass. Rebuild as required and rerun the original focused check through its offline -wrapper. For the frozen native diagram fixture, retain the failed/restored -installation identities and run `bun run test ./tests/native-diagram-inputs.test.ts`. +wrapper. Once evidence is retained and no process uses it, remove only the owned old installation. Never delete or repair shared caches while others may use them. Repeat preparation before a new independent diagnostic; an installation you diff --git a/scripts/browser-input-closure.ts b/scripts/browser-input-closure.ts index 7c0a9485e6..1248e9a817 100644 --- a/scripts/browser-input-closure.ts +++ b/scripts/browser-input-closure.ts @@ -5,7 +5,6 @@ import { builtinModules } from "node:module"; import { dirname, isAbsolute, join, relative, resolve } from "node:path"; import ts from "typescript"; import { auditCommandActivation, type CommandCandidate } from "./browser-command-activation"; -import { nativeDiagramInputs, type NativeDiagramIdentity, type NativeDiagramDiagnostic } from "./native-diagram-inputs"; import { generatedThemeInputs } from "./generated-theme-inputs"; import { sourceBrowserDispatch } from "./source-browser-dispatch"; import { boundBrowserDocuments, type BrowserDocumentInputs } from "./bound-browser-documents"; @@ -27,7 +26,7 @@ export interface IndirectInput { observation?: "linux-proc-self-identity"; } export interface InputDeclaration { owner: string; inputs: IndirectInput[]; } -export interface InputClosure { files: string[]; directories?: string[]; external?: LockedBrowserAsset[]; nativeDiagram?:NativeDiagramIdentity; nativeDiagramDiagnostic?:NativeDiagramDiagnostic; unresolved: string[]; } +export interface InputClosure { files: string[]; directories?: string[]; external?: LockedBrowserAsset[]; unresolved: string[]; } const builtins = new Set(builtinModules.flatMap(name => [name, `node:${name}`])); const sourceExtension = /\.[cm]?[jt]sx?$/; const readOperations = new Set(["readFile", "readFileSync", "readdir", "readdirSync", "readlink", "readlinkSync", "createReadStream", "open", "openSync", "opendir", "opendirSync", "access", "accessSync", "existsSync", "stat", "statSync", "lstat", "lstatSync", "watch", "watchFile", "spawn", "spawnSync", "exec", "execSync", "execFile", "execFileSync", "fork"]); @@ -47,8 +46,6 @@ export function discoverInputClosure(root: string, entrypoints: readonly string[ let runtimeBindings: BrowserRuntimeBindings = new Map(); let dispatchBindings = new Map>(); let documentBindings = new Map>(); - let nativeBinding:ReturnType; - let nativeDiagramDiagnostic:NativeDiagramDiagnostic|undefined; let themeBinding: ReturnType; if (activation) { const audit = auditCommandActivation(root, activation.config, activation.selected, activation.candidates); @@ -60,7 +57,6 @@ export function discoverInputClosure(root: string, entrypoints: readonly string[ dispatchBindings = sourceBrowserDispatch(root, audit.files, importers); documentBindings = boundBrowserDocuments(root, audit.files, importers); themeBinding = generatedThemeInputs(root, audit.files, importers); - nativeBinding = nativeDiagramInputs(root, audit.files, importers,value=>{nativeDiagramDiagnostic=value;}); } if (!audit.unresolved.length) for (const candidate of audit.candidates) { const names = inactive.get(candidate.owner) ?? new Set(); @@ -98,7 +94,7 @@ export function discoverInputClosure(root: string, entrypoints: readonly string[ for (const entry of readdirSync(absolute).sort()) visit(normalized ? `${normalized}/${entry}` : entry, scanOnly, sourceOnly); return; } - if (scanOnly) return; // Byte inventories: Tailwind text or exact mount-bound native inputs. + if (scanOnly) return; // Byte inventories: Tailwind text or exact mount-bound inputs. if (file.endsWith(".css")) { const css = cssInputs(readFileSync(absolute, "utf8")); const uses = new Set(); @@ -276,8 +272,6 @@ export function discoverInputClosure(root: string, entrypoints: readonly string[ const literalPayload = /\.(?:fulfill|setContent)$/.test(originalCallee) && sourceBrowserPayload(root, normalized, expression); const boundRuntime = runtimeBindings.get(normalized)?.get(expression); const boundDispatch = dispatchBindings.get(normalized)?.has(expression) === true; - const boundNative = nativeBinding?.sites.get(normalized)?.has(expression)===true; - if(boundNative)for(const target of nativeBinding!.files)visit(target,true); const boundDocument = documentBindings.get(normalized)?.get(expression); if(boundDocument){for(const target of boundDocument.runtime)visit(target);for(const target of boundDocument.bytes)visit(target,true);} const generatedTheme = themeBinding?.owner===normalized && themeBinding.read===expression ? themeBinding : undefined; @@ -293,7 +287,7 @@ export function discoverInputClosure(root: string, entrypoints: readonly string[ } const matching = inputDeclarations(node); if (matching.some(declaration => declaration.observation && !kernelObservation(node, declaration))) unresolved.add(`Invalid runner observation ${normalized}: ${expression}`); - if (!matching.length && !generated && !locked && !literalPayload && !boundRuntime && !boundDispatch && !generatedTheme && !boundDocument && !boundNative) unresolved.add(`Undeclared input ${normalized}: ${expression}`); + if (!matching.length && !generated && !locked && !literalPayload && !boundRuntime && !boundDispatch && !generatedTheme && !boundDocument) unresolved.add(`Undeclared input ${normalized}: ${expression}`); else for (const declaration of matching) { uses.add(inputKey(declaration)); for (const target of declaration.targets) visit(target); } } } @@ -310,7 +304,7 @@ export function discoverInputClosure(root: string, entrypoints: readonly string[ }; for (const file of [...entrypoints,...executionRoots]) visit(file); for (const owner of declared.keys()) if (!files.has(owner)) unresolved.add(`Unused declaration owner: ${owner}`); - return { ...(nativeBinding?{nativeDiagram:nativeBinding.identity}:{}), ...(nativeDiagramDiagnostic?{nativeDiagramDiagnostic}:{}), files: [...files].sort(), directories: [...directories].sort(), ...(external.size ? { external: [...external.values()].sort((a,b) => `${a.package}/${a.asset}`.localeCompare(`${b.package}/${b.asset}`)) } : {}), unresolved: [...unresolved].sort() }; + return { files: [...files].sort(), directories: [...directories].sort(), ...(external.size ? { external: [...external.values()].sort((a,b) => `${a.package}/${a.asset}`.localeCompare(`${b.package}/${b.asset}`)) } : {}), unresolved: [...unresolved].sort() }; } export function closureSelects(changed: readonly string[], closure: InputClosure, broad: boolean): boolean { const inputs = new Set(closure.files); diff --git a/scripts/browser-worker-audit.ts b/scripts/browser-worker-audit.ts index 8d5db6ee5e..855c5bd2f8 100644 --- a/scripts/browser-worker-audit.ts +++ b/scripts/browser-worker-audit.ts @@ -24,7 +24,7 @@ function workerAuditMaterial(root:string,closure:InputClosure,selected:readonly return [file,stat.mode&0o777,createHash("sha256").update(readFileSync(absolute)).digest("hex")]; }).sort((a,b)=>String(a[0]).localeCompare(String(b[0]))); const inventory=selected.map(({file,project})=>({file,project})).sort((a,b)=>a.project.localeCompare(b.project)||a.file.localeCompare(b.file)); - return {version:1,files,directories:[...(closure.directories??[])].sort(),external:closure.external??[],...(closure.nativeDiagram?{nativeDiagram:closure.nativeDiagram}:{}),inventory}; + return {version:1,files,directories:[...(closure.directories??[])].sort(),external:closure.external??[],inventory}; }catch{return;} } export function workerAuditIdentity(root:string,closure:InputClosure,selected:readonly Spec[]):string|undefined{ @@ -55,8 +55,7 @@ export function inspectWorkerAudit(root:string,closure:InputClosure,selected:rea const owner=prefix?input.slice(prefix[0].length).split(":")[0]:undefined; return{code:prefix?.[1]??"unsupported-input",...(owner&&owner.length<256&&/^[A-Za-z0-9_./@-]+$/.test(owner)&&closure.files.includes(owner)?{owner}:{})}; }); - const expectedNative=Object.fromEntries(["source","installation","runtime"].flatMap(key=>typeof audit?.sourceAudit?.native?.[key]==="string"&&/^[a-f0-9]{64}$/.test(audit.sourceAudit.native[key])?[[key,audit.sourceAudit.native[key]]]:[])); - const diagnostic={version:1,expectedIdentity,actualIdentity,enforcementValid:Boolean(enforcementValid),admissionSupported:Boolean(material),selected:selected.length,files:closure.files.length,unresolvedCount:closure.unresolved.length,unresolved:labels,expectedNative,native:closure.nativeDiagramDiagnostic,material:diagnosticMaterial}; + const diagnostic={version:1,expectedIdentity,actualIdentity,enforcementValid:Boolean(enforcementValid),admissionSupported:Boolean(material),selected:selected.length,files:closure.files.length,unresolvedCount:closure.unresolved.length,unresolved:labels,material:diagnosticMaterial}; if(JSON.stringify(diagnostic).length>768*1024)return{qualified:false,diagnostic:{version:1,expectedIdentity,actualIdentity,reason:"bounded manifest exceeded"}}; return{qualified,diagnostic}; } diff --git a/scripts/inclusion-inputs.ts b/scripts/inclusion-inputs.ts index 823af8c197..9c55239790 100644 --- a/scripts/inclusion-inputs.ts +++ b/scripts/inclusion-inputs.ts @@ -117,8 +117,8 @@ export function inclusionInputs(root: string, category: Reusable, inventory: Spe const partitions = balanceBrowserSpecs(selected.map(spec => ({ key: `${spec.project}::${spec.file}`, project: spec.project })), PROOF_SHARDS[category], readBrowserCosts(join(snapshot, "scripts/browser-shard-costs.json"))).map(part => part.map(spec => spec.key)); const files = entries.filter(entry => included.has(entry.path)); - const material = { version: 2, category, runner, inventory, partitions, directories: closure.directories ?? [], external: closure.external ?? [], ...(closure.nativeDiagram?{nativeDiagram:closure.nativeDiagram}:{}), files }; - return { version: 2, category, runner, inventory, partitions, excluded: [], ...(closure.nativeDiagram?{nativeDiagram:closure.nativeDiagram}:{}), + const material = { version: 2, category, runner, inventory, partitions, directories: closure.directories ?? [], external: closure.external ?? [], files }; + return { version: 2, category, runner, inventory, partitions, excluded: [], fingerprint: createHash("sha256").update(JSON.stringify(material)).digest("hex") }; } finally { rmSync(snapshot, { recursive: true, force: true }); } } diff --git a/scripts/native-diagram-inputs.ts b/scripts/native-diagram-inputs.ts deleted file mode 100644 index 5001b073f4..0000000000 --- a/scripts/native-diagram-inputs.ts +++ /dev/null @@ -1,92 +0,0 @@ -/** One fixed mount-bound native SVG/PNG/PDF operation; drift keeps fresh proof. */ -import {createHash} from "node:crypto"; -import {existsSync,lstatSync,readFileSync,readdirSync,realpathSync} from "node:fs"; -import {resolve} from "node:path"; -import {diagramSourceDomains,diagramSourceSetup,diagramSourceIdentity} from "./diagram-export-source.mjs"; -import {diagramInstallationIdentity} from "./diagram-export-installation.mjs"; -import {diagramProducerRuntime} from "./diagram-export-producer.mjs"; -import type {BrowserImporters} from "./bound-browser-runtime-inputs"; -export interface NativeDiagramIdentity {source:string;installation:string;runtime:string;} -export interface NativeDiagramDiagnostic { - version:1;status:string;stage:string;expected:{source:string;installation:string}; - actual?:Partial;sourceInputs?:number; - installation?:{packages:number;files:number;bytes:number}; - pins?:{path:string;expected:string;actual?:string;owned:boolean}[];errorCode?:string;recovery?:string; -} - -// Candidate qualification is exact: all source/installation drift requires fresh -// execution and requalification. The separate Docker mount boundary closes -// active initialization/shared-library reads; byte hashes alone do not. -const qualified:Omit={source:"e8502b6ffb3c575f2e9a1c93dea8dbf5ceda93ece367da9d542cb10b1c9ac32b",installation:"ea866695f2a83f9da2fcf18e75e95e936668ecb28e1449845a2584aa1025b728"}; -// The installation identity includes file modes, which the installer's umask -// narrows: the qualified install was made under umask 022, and any other umask -// (such as 0077) can never match. Recovery replaces only this owned install. -const installationRecovery="Preserve evidence and move aside this owned checkout's node_modules, then run sh scripts/prepare-diagnostic-install.sh. It sets umask 022 and installs the unchanged lock through a fresh private cache and copyfile. The installation identity includes file modes, so an install under any other umask (such as 0077) never matches. See CONTRIBUTING.md; never refresh qualification pins."; -const caller="packages/ui-kit/vitest.config.ts",owner="packages/ui-react/tests/browser/diagram-export-command.ts"; -const sourcePins:Record={ - "packages/ui-kit/vitest.config.ts": "e724696a55955e9f32d396b2031214600086533c3f9b8baabcc1c6bb7311f1db", - "packages/ui-react/tests/browser/diagram-export-command.ts": "f7c3d14ccf96438bf4e28ecc1929b1208fb99520d21a9947086bb43bca933328", - "scripts/ci-proof.ts": "c58de06eba788b6b892416ddda3abb28fa1e8e908f25c0800482fbe05e0de678" -}; -/** The same complete source family the trusted host preparer enumerates. */ -export function nativeDiagramSourceInventory(root:string){ - const inputs:{path:string;mode:string;sha256:string}[]=[]; - const read=(path:string)=>{const absolute=resolve(root,path),stat=lstatSync(absolute); - if(realpathSync(absolute)!==absolute||stat.isSymbolicLink())throw Error("Unsupported native source alias"); - if(stat.isDirectory()){for(const entry of readdirSync(absolute).sort())read(`${path}/${entry}`);} - else if(stat.isFile())inputs.push({path,mode:stat.mode&0o111?"100755":"100644",sha256:createHash("sha256").update(readFileSync(absolute)).digest("hex")}); - else throw Error("Unsupported native source entry");}; - for(const file of diagramSourceSetup)read(file); - for(const domain of diagramSourceDomains)read(`packages/${domain}`); - return{inputs,sha256:diagramSourceIdentity(inputs)}; -} -/** Input identity supplements the existing complete fresh-shard receipt. */ -export function nativeDiagramInputs(root:string,files:readonly string[],importers:BrowserImporters,observe?:(value:NativeDiagramDiagnostic)=>void){ - const diagnostic:NativeDiagramDiagnostic={version:1,status:"unavailable",stage:"role",expected:{...qualified}}; - const report=()=>observe?.(diagnostic); - if(![caller,owner].every(path=>files.includes(path)))return; - if(!qualified.source||!qualified.installation||[...(importers.get(owner)??[])].some(path=>path!==caller)){diagnostic.status="unsealed-role";report();return;} - try{ - diagnostic.stage="pins"; - diagnostic.pins=Object.entries(sourcePins).map(([path,expected])=>{const absolute=resolve(root,path),owned=existsSync(absolute)&&realpathSync(absolute)===absolute;return{path,expected,owned,...(owned?{actual:createHash("sha256").update(readFileSync(absolute)).digest("hex")}:{} )};}); - if(diagnostic.pins.some(pin=>!pin.owned||pin.actual!==pin.expected)){diagnostic.status="source-pin-mismatch";report();return;} - diagnostic.stage="source";const source=nativeDiagramSourceInventory(root);diagnostic.actual={source:source.sha256};diagnostic.sourceInputs=source.inputs.length; - diagnostic.stage="installation";const installation=diagramInstallationIdentity(root);diagnostic.actual.installation=installation.sha256;diagnostic.installation={packages:installation.packages,files:installation.files,bytes:installation.bytes}; - diagnostic.stage="runtime";const runtime=diagramProducerRuntime();diagnostic.actual.runtime=runtime.sha256; - if(source.sha256!==qualified.source||installation.sha256!==qualified.installation){if(source.sha256!==qualified.source)diagnostic.status="source-mismatch";else{diagnostic.status="installation-mismatch";diagnostic.recovery=installationRecovery;}report();return;} - const sites=new Map>([ - [owner,new Set([ - "readFileSync(resolve(prepared,\"producer.json\"),\"utf8\")", - "readFileSync(resolve(prepared,name))", - "readFileSync(resolve(directory,\"release.svg\"),\"utf8\")", - "readFileSync(resolve(directory,\"release.png\"))", - "page.setContent(`${svg}`)" -])], - ["scripts/diagram-export-producer.mjs",new Set([ - "accessSync(path,constants.X_OK)", - "statSync(path)", - "readFileSync(executable)", - "readFileSync(join(repo,\"tmp/diagram-export-source.json\"),\"utf8\")", - "readdirSync(join(repo,\"node_modules\"))", - "readdirSync(join(repo,\"node_modules\",top))", - "spawnSync(\"docker\",[\"run\",\"--rm\",\"--pull=never\",\"--read-only\",\"--network=none\",\"--shm-size=256m\",\"--user\",`${process.getuid()}:${process.getgid()}`,\"--tmpfs\",\"/tmp:rw,exec,nosuid,nodev,mode=1777\",\"-v\",`${source}:${source}:ro`,\"-v\",`${modules}:${join(repo,\"node_modules\")}:ro`,\"-v\",`${executable}:/usr/local/bin/bun:ro`,\"-v\",`${output}:/proof`,\"-w\",source,\"-e\",\"HOME=/tmp/home\",runtime.image,\"/usr/local/bin/bun\",\"-e\",program],{encoding:\"utf8\",maxBuffer:4*1024*1024})", - "readFileSync(join(output,name))" -])], - ["scripts/diagram-export-source.mjs",new Set([ - 'readFileSync(archivePath(repo))','existsSync(target)','lstatSync(source)','readFileSync(source)', - 'readFileSync(join(target,"packages",name,"package.json"),"utf8")','existsSync(installed)', - 'readdirSync(join(repo,"node_modules"))','readdirSync(join(repo,"node_modules",entry))' - ])], - ["scripts/diagram-export-installation.mjs",new Set([ - 'lstatSync(absolute)','lstatSync(real)','readlinkSync(absolute)','readdirSync(absolute)','readFileSync(absolute)', - 'readdirSync(join(repo,"node_modules"))','readdirSync(join(repo,"node_modules",top))','readFileSync(join(base,"package.json"),"utf8")' - ])] - ]); - diagnostic.status="qualified";diagnostic.stage="complete";report(); - return{identity:{source:source.sha256,installation:installation.sha256,runtime:runtime.sha256},files:source.inputs.map(entry=>entry.path),sites}; - }catch(error){ - const safeMessages=["Unsupported native dependency alias","Unbounded native dependency inventory","Unsupported native dependency entry","Unbounded native dependency packages","NATIVE_DEPENDENCY_ORIGIN_CHANGED","Unsupported native dependency identity"]; - const message=error instanceof Error?error.message:""; - diagnostic.errorCode=safeMessages.includes(message)?message.replaceAll(" ","_").toUpperCase():"UNAVAILABLE";report();return; - } -} diff --git a/scripts/proof-inputs.ts b/scripts/proof-inputs.ts index b1fa7b2ee6..c4e099b9be 100644 --- a/scripts/proof-inputs.ts +++ b/scripts/proof-inputs.ts @@ -11,6 +11,12 @@ export interface Checkout { sha: string; tree: string; parents: string[]; } export interface Inputs { version: 2; category: Reusable; fingerprint: string; runner: string; inventory: Spec[]; partitions: string[][]; excluded: string[]; + /** + * Never produced since #4105 retired the frozen native diagram qualification. + * `scripts/ci-proof.ts` and `scripts/visual.mjs` still read it, and do + * nothing when it is absent; they are audited sources, so the dead branches + * go when those files next change under their own re-audit. + */ nativeDiagram?:{source:string;installation:string;runtime:string}; } export function git(root: string, ...args: string[]): string { diff --git a/scripts/test-shard-costs.json b/scripts/test-shard-costs.json index f3c0bfeece..0a2362a14b 100644 --- a/scripts/test-shard-costs.json +++ b/scripts/test-shard-costs.json @@ -1115,7 +1115,6 @@ "tests/module-hygiene-queries.test.ts": 0.785, "tests/module-public-imports.test.ts": 0.1, "tests/native-dead-root-trace.test.ts": 0.1, - "tests/native-diagram-inputs.test.ts": 18.314, "tests/native-event-log.test.ts": 0.1, "tests/offline-test-launcher.test.ts": 0.123, "tests/opportunity-cli-agreement.test.ts": 2.381, diff --git a/tests/browser-worker-audit.test.ts b/tests/browser-worker-audit.test.ts index 32de985611..0e2aa67f87 100644 --- a/tests/browser-worker-audit.test.ts +++ b/tests/browser-worker-audit.test.ts @@ -53,15 +53,13 @@ test("covered byte drift stays unavailable and the bounded manifest names only t expect(JSON.stringify(after.diagnostic).length).toBeLessThan(768*1024); }); -test("unknown native inputs expose bounded evidence without admission material",()=>{ +test("unknown inputs expose bounded evidence without admission material",()=>{ const {root,closure,selected}=fixture(); - const unknown={...closure,unresolved:[pdfWorkerInput,"Undeclared input spec.ts: readFile(secretSourceContents)"],nativeDiagramDiagnostic:{version:1 as const,status:"source-mismatch",stage:"runtime",expected:{source:"a".repeat(64),installation:"b".repeat(64)},actual:{source:"c".repeat(64),installation:"b".repeat(64),runtime:"d".repeat(64)}}}; + const unknown={...closure,unresolved:[pdfWorkerInput,"Undeclared input spec.ts: readFile(secretSourceContents)"]}; expect(workerAuditIdentity(root,unknown,selected),"UNSUPPORTED_INPUT_HAS_NO_ADMISSION_IDENTITY").toBeUndefined(); const inspected=inspectWorkerAudit(root,unknown,selected),diagnostic=inspected.diagnostic as any; - expect(inspected.qualified,"UNKNOWN_NATIVE_INPUT_ALWAYS_REQUIRES_FRESH").toBe(false); + expect(inspected.qualified,"UNKNOWN_INPUT_ALWAYS_REQUIRES_FRESH").toBe(false); expect(diagnostic.admissionSupported).toBe(false); - expect(diagnostic.native?.status,"UNKNOWN_NATIVE_DIAGNOSTIC_IS_NON_NULL").toBe("source-mismatch"); - expect(diagnostic.native.actual.source).toBe("c".repeat(64)); expect(diagnostic.material.files.some((entry:any)=>entry[0]==="data.json")).toBe(true); expect(diagnostic.unresolved).toContainEqual({code:"undeclared-input",owner:"spec.ts"}); expect(JSON.stringify(diagnostic)).not.toContain(root); diff --git a/tests/native-diagram-inputs.test.ts b/tests/native-diagram-inputs.test.ts deleted file mode 100644 index e16bae7e31..0000000000 --- a/tests/native-diagram-inputs.test.ts +++ /dev/null @@ -1,127 +0,0 @@ -import {afterEach,expect,test} from "bun:test"; -import assert from "node:assert/strict"; -import {chmodSync,cpSync,lstatSync,mkdirSync,mkdtempSync,readFileSync,readdirSync,realpathSync,rmSync,symlinkSync,writeFileSync} from "node:fs"; -import {tmpdir} from "node:os"; -import {dirname,join,resolve} from "node:path"; -import {diagramSourceSetup,diagramSourceDomains} from "../scripts/diagram-export-source.mjs"; -import {nativeDiagramInputs,nativeDiagramSourceInventory,type NativeDiagramDiagnostic} from "../scripts/native-diagram-inputs"; -const repo=resolve(import.meta.dir,".."),roots:string[]=[],owner="packages/ui-react/tests/browser/diagram-export-command.ts",caller="packages/ui-kit/vitest.config.ts"; -// Delivered #2293 owns the qualified bytes. Never substitute HEAD/worktree bytes, -// Git archive filters, or a newly computed candidate fingerprint for this control. -const frozen="0d780605fe1ea9a281cce947b1f0074f3f3e7acc"; -const qualifiedSource="e8502b6ffb3c575f2e9a1c93dea8dbf5ceda93ece367da9d542cb10b1c9ac32b"; -const qualifiedInstallation="ea866695f2a83f9da2fcf18e75e95e936668ecb28e1449845a2584aa1025b728"; -const ownedPaths=[...diagramSourceSetup,...diagramSourceDomains.map(name=>`packages/${name}`),owner,caller,"scripts/ci-proof.ts"]; -afterEach(()=>{for(const root of roots.splice(0))rmSync(root,{recursive:true,force:true});}); -function fixture(current=false,install?:(modules:string)=>void){ - const root=mkdtempSync(join(tmpdir(),"odysseus-native-inputs-"));roots.push(root); - const tree=Bun.spawnSync(["git","ls-tree","-r","-z",current?"HEAD":frozen,"--",...ownedPaths],{cwd:repo,stdout:"pipe",stderr:"pipe"}); - expect(tree.exitCode,"FROZEN_SOURCE_OWNER_MUST_BE_AVAILABLE_OFFLINE").toBe(0); - const entries=tree.stdout.toString().split("\0").filter(Boolean).map(row=>{const tab=row.indexOf("\t"),[mode,kind,oid]=row.slice(0,tab).split(" ");expect(kind).toBe("blob");expect(["100644","100755"]).toContain(mode);return{mode,oid,path:row.slice(tab+1)};}); - // Match the repository's immutable source protocol: read raw objects in one - // batch, verifying each header/length and complete output before using it. - const batch=Bun.spawnSync(["git","cat-file","--batch"],{cwd:repo,stdin:Buffer.from(entries.map(entry=>entry.oid).join("\n")+"\n"),stdout:"pipe",stderr:"pipe"}); - expect(batch.exitCode).toBe(0);const bytes=Buffer.from(batch.stdout);let offset=0; - for(const entry of entries){ - const end=bytes.indexOf(10,offset);expect(end).toBeGreaterThanOrEqual(offset); - const [oid,kind,length]=bytes.subarray(offset,end).toString("ascii").split(" "),size=Number(length); - expect(oid).toBe(entry.oid);expect(kind).toBe("blob");expect(Number.isSafeInteger(size)&&size>=0&&end+1+size`${top}/${name}`):[top];for(const name of names){if(name.startsWith("@schlessera/"))continue;const target=join(root,"node_modules",name);mkdirSync(dirname(target),{recursive:true});symlinkSync(realpathSync(join(repo,"node_modules",name)),target,"dir");}} - let diagnostic:NativeDiagramDiagnostic|undefined; - const importers=new Map([[owner,new Set([caller])]]),bind=()=>nativeDiagramInputs(root,[owner,caller],importers,value=>{diagnostic=value;}); - return{root,importers,bind,diagnostic:()=>diagnostic}; -} -function sourceRefused(control:ReturnType,name:string){ - expect(control.bind(),name).toBeUndefined();const diagnostic=control.diagnostic(); - assert(diagnostic,"UNKNOWN_NATIVE_BINDING_MUST_REPORT_DIAGNOSTIC"); - expect(diagnostic.status,"UNKNOWN_NATIVE_BINDING_HAS_REASON").toBe("source-mismatch"); - assert(diagnostic.actual?.source,"SOURCE_REFUSAL_MUST_REPORT_ACTUAL_IDENTITY"); - expect(diagnostic.expected.source).toBe(qualifiedSource); - expect(diagnostic.actual.source).not.toBe(diagnostic.expected.source); - expect(diagnostic.actual.installation).toBe(qualifiedInstallation); - expect(JSON.stringify(diagnostic)).not.toContain(control.root); -} -test("fixed native qualification binds the independently frozen complete source without Docker or image lookup",()=>{ - const control=fixture(),path=process.env.PATH,bin=join(control.root,"commands");mkdirSync(bin);symlinkSync(realpathSync(process.execPath),join(bin,"bun")); - try{ - process.env.PATH=bin;const binding=control.bind(); - expect(control.diagnostic(),"FROZEN_NATIVE_INSTALLATION_MUST_MATCH_QUALIFIED_BYTES: reinstall this owned checkout under umask 022 from a fresh private cache (CONTRIBUTING.md); never refresh qualification pins").toMatchObject({ - status:"qualified",stage:"complete",sourceInputs:859, - actual:{source:qualifiedSource,installation:qualifiedInstallation}, - installation:{packages:930,files:66881,bytes:1374331961} - }); - expect(binding?.files.length,"COMPLETE_NATIVE_QUALIFICATION_WITHOUT_DOCKER_OR_IMAGE_LOOKUP").toBe(859); - expect(binding?.files.toSorted()).toEqual(nativeDiagramSourceInventory(control.root).inputs.map(entry=>entry.path).toSorted()); - expect(binding?.identity.source).toBe(qualifiedSource);expect(binding?.identity.installation).toBe(qualifiedInstallation); - expect(control.diagnostic()?.status).toBe("qualified"); - }finally{if(path===undefined)delete process.env.PATH;else process.env.PATH=path;} -}); -test("an additional native importer requires fresh proof",()=>{ - const control=fixture();control.importers.get(owner)!.add("new-caller.ts"); - expect(control.bind(),"NATIVE_IMPORTER_REQUIRES_FRESH_PROOF").toBeUndefined();expect(control.diagnostic()?.status).toBe("unsealed-role"); -}); -test.each([owner,caller,"scripts/ci-proof.ts"])("changed pinned native input %s requires fresh proof",file=>{ - const control=fixture(),target=join(control.root,file);writeFileSync(target,readFileSync(target,"utf8")+"\n// changed native operation\n"); - expect(control.bind(),"NATIVE_PIN_REQUIRES_FRESH_PROOF").toBeUndefined();expect(control.diagnostic()?.status).toBe("source-pin-mismatch"); - const pin=control.diagnostic()?.pins?.find(pin=>pin.path===file); - assert(pin,"PIN_REFUSAL_MUST_REPORT_EXPECTED_PIN");assert(pin.actual,"PIN_REFUSAL_MUST_REPORT_ACTUAL_PIN"); - expect(pin.actual).not.toBe(pin.expected); -}); -test("added package source requires native requalification",()=>{ - const control=fixture();writeFileSync(join(control.root,"packages/core/src/unused-native-probe.ts"),"export const Odysseus=1;"); - sourceRefused(control,"NATIVE_SOURCE_ADDITION_REQUIRES_REQUALIFICATION"); -}); -test("changed package content requires native requalification",()=>{ - const control=fixture(),target=join(control.root,"packages/core/src/cli/brain.ts");writeFileSync(target,readFileSync(target,"utf8")+"\n// changed package content\n"); - sourceRefused(control,"NATIVE_SOURCE_CONTENT_REQUIRES_REQUALIFICATION"); -}); -test("changed package executable mode requires native requalification",()=>{ - const control=fixture(),target=join(control.root,"packages/core/src/cli/brain.ts");chmodSync(target,(lstatSync(target).mode&0o777)^0o111); - sourceRefused(control,"NATIVE_SOURCE_MODE_REQUIRES_REQUALIFICATION"); -}); -// An installer's umask narrows the modes it writes, and the installation identity -// includes modes. Simulate one package written under each umask. -const syntheticInstall=(mask:number)=>(modules:string)=>{ - const previous=process.umask(mask); - try{ - const base=join(modules,"odysseus-ledger");mkdirSync(join(base,"bin"),{recursive:true,mode:0o755}); - writeFileSync(join(base,"package.json"),JSON.stringify({name:"odysseus-ledger",version:"1.0.0"}),{mode:0o644}); - writeFileSync(join(base,"bin/ledger.js"),"#!/usr/bin/env bun\nconsole.log(\"Ithaca\");\n",{mode:0o755}); - }finally{process.umask(previous);} -}; -test("an install under umask 0077 is refused with the umask 022 recovery, and that recovery restores its identity",()=>{ - const restrictive=fixture(false,syntheticInstall(0o077)),reference=fixture(false,syntheticInstall(0o022)); - expect(restrictive.bind(),"RESTRICTIVE_UMASK_INSTALL_IS_REFUSED").toBeUndefined(); - const refused=restrictive.diagnostic();assert(refused,"RESTRICTIVE_UMASK_REFUSAL_MUST_REPORT_DIAGNOSTIC"); - expect(refused.status).toBe("installation-mismatch");expect(refused.actual?.source).toBe(qualifiedSource); - expect(refused.recovery,"INSTALLATION_REFUSAL_NAMES_THE_REQUIRED_UMASK").toContain("umask 022"); - expect(refused.recovery,"INSTALLATION_REFUSAL_NAMES_THE_INSTALL_COMMAND").toContain("sh scripts/prepare-diagnostic-install.sh"); - expect(JSON.stringify(refused)).not.toContain(restrictive.root); - reference.bind();const expected=reference.diagnostic();assert(expected?.actual?.installation,"REFERENCE_INSTALL_MUST_REPORT_IDENTITY"); - // Same packages, files and bytes: only the modes differ. - expect(refused.installation).toEqual(expected.installation);expect(refused.actual?.installation).not.toBe(expected.actual.installation); - // The documented recovery: replace the owned install under umask 022. - rmSync(join(restrictive.root,"node_modules/odysseus-ledger"),{recursive:true});syntheticInstall(0o022)(join(restrictive.root,"node_modules")); - restrictive.bind();expect(restrictive.diagnostic()?.actual?.installation,"UMASK_022_RECOVERY_RESTORES_THE_IDENTITY").toBe(expected.actual.installation); -}); -test("relocated installed native dependency requires fresh proof",()=>{ - const control=fixture(),clone=join(control.root,"relocated/marked");mkdirSync(dirname(clone));cpSync(realpathSync(join(control.root,"node_modules/marked")),clone,{recursive:true});rmSync(join(control.root,"node_modules/marked"));symlinkSync(clone,join(control.root,"node_modules/marked"),"dir"); - expect(control.bind(),"NATIVE_INSTALLED_ORIGIN_REQUIRES_FRESH_PROOF").toBeUndefined();expect(control.diagnostic()?.stage).toBe("installation");expect(control.diagnostic()?.errorCode,"UNKNOWN_INSTALLED_ORIGIN_HAS_BOUNDED_REASON").toBe("NATIVE_DEPENDENCY_ORIGIN_CHANGED"); -}); -test("the actual current candidate qualifies only when its complete frozen source and pins match",()=>{ - const control=fixture(true),source=nativeDiagramSourceInventory(control.root),binding=control.bind(),diagnostic=control.diagnostic(); - assert(diagnostic,"CURRENT_CANDIDATE_MUST_REPORT_DIAGNOSTIC"); - // A legitimate new file or pinned proof/caller edit is an unsupported operation, - // not a broken positive fixture. The frozen positive above must still qualify. - if(source.sha256===qualifiedSource&&diagnostic.pins?.every(pin=>pin.owned&&pin.actual===pin.expected)){ - expect(binding?.identity.source).toBe(qualifiedSource);expect(diagnostic?.status).toBe("qualified"); - }else{ - expect(binding,"CHANGED_CANDIDATE_MUST_KEEP_FRESH_NATIVE_PROOF").toBeUndefined();expect(["source-mismatch","source-pin-mismatch"]).toContain(diagnostic.status); - } -}); diff --git a/tests/native-diagram-retired.test.ts b/tests/native-diagram-retired.test.ts new file mode 100644 index 0000000000..a1bdb35f4b --- /dev/null +++ b/tests/native-diagram-retired.test.ts @@ -0,0 +1,30 @@ +// The frozen native diagram qualification is retired (#4105, maintainer ruling +// 2026-11-16). Its pins made every dependency change fail `unit` until a +// manual Docker requalification moved them. Nothing in the scripts or tests +// may pin those identities again: the producer's proof runs fresh in its +// container boundary, and its own run-time checks verify what it mounts. +import { expect, test } from "bun:test"; +import { readFileSync } from "node:fs"; +import { join, resolve } from "node:path"; + +const root = resolve(import.meta.dir, ".."); + +const RETIRED = [ + "e8502b6ffb3c575f2e9a1c93dea8dbf5ceda93ece367da9d542cb10b1c9ac32b", // frozen #2293 source + "ea866695f2a83f9da2fcf18e75e95e936668ecb28e1449845a2584aa1025b728", // last qualified installation + "e724696a55955e9f32d396b2031214600086533c3f9b8baabcc1c6bb7311f1db", // pinned ui-kit vitest config + // The diagram export command's own hash (`f7c3d14c…`) is not listed: the + // bound-browser-documents audit pins that file independently. + "c58de06eba788b6b892416ddda3abb28fa1e8e908f25c0800482fbe05e0de678", // pinned ci-proof +]; + +test("no script or test pins the retired native diagram qualification", () => { + // Two patterns: Bun's glob matches nothing when a brace alternative holds a `/`. + const files = ["{scripts,tests}/**/*.{ts,tsx,mjs,js}", "packages/*/{tests,scripts}/**/*.{ts,tsx,mjs,js}"] + .flatMap((pattern) => [...new Bun.Glob(pattern).scanSync({ cwd: root, dot: false })]) + .filter((file) => !file.includes("node_modules") && file !== "tests/native-diagram-retired.test.ts"); + // The scan must see the files the binding lived in, or an empty glob passes vacuously. + expect(files, "SCAN_COVERS_THE_PROOF_SCRIPTS").toContain("scripts/browser-input-closure.ts"); + const pinned = files.flatMap((file) => RETIRED.filter((hash) => readFileSync(join(root, file), "utf8").includes(hash)).map((hash) => `${file}: ${hash.slice(0, 8)}`)); + expect(pinned, "NATIVE_DIAGRAM_QUALIFICATION_STAYS_RETIRED").toEqual([]); +}); From 74fa6e0eb086c04c7a5057e4cd24384adabf126a Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 16 Nov 2026 23:56:46 +0000 Subject: [PATCH 02/31] chore(ci): pin workflow actions by commit SHA (#4111) Every workflow referenced its actions by a mutable major tag. Each uses: now names the full commit that tag pointed at on 2026-11-16, with the tag as a comment. scripts/action-pins.ts owns the table; the workflow lint refuses a tag, a branch, an unreviewed commit or a missing tag comment in any workflow file, and the generated heavy-feedback workflow keeps the comments its YAML rendering drops. No action moves to a newer release. Co-Authored-By: Claude Fable 5.2 --- .github/workflows/ci-timings.yml | 6 +-- .github/workflows/ci.yml | 62 ++++++++++++------------ .github/workflows/contract.yml | 4 +- .github/workflows/heavy-feedback.yml | 62 ++++++++++++------------ .github/workflows/project-sync.yml | 4 +- .github/workflows/publish-pages.yml | 12 ++--- .github/workflows/red-main-probe.yml | 6 +-- .github/workflows/red-main.yml | 6 +-- docs/decisions/github-actions-ci.md | 30 ++++++++++++ docs/process/testing.md | 23 +++++++++ scripts/action-pins.ts | 72 ++++++++++++++++++++++++++++ scripts/check-ci-workflows.ts | 7 ++- scripts/heavy-feedback-workflow.ts | 3 +- tests/ci-workflows.test.ts | 51 ++++++++++++++++++-- 14 files changed, 259 insertions(+), 89 deletions(-) create mode 100644 scripts/action-pins.ts diff --git a/.github/workflows/ci-timings.yml b/.github/workflows/ci-timings.yml index 42b62919a4..eb063a3698 100644 --- a/.github/workflows/ci-timings.yml +++ b/.github/workflows/ci-timings.yml @@ -22,13 +22,13 @@ jobs: runs-on: ubuntu-24.04 timeout-minutes: 30 steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: ref: ${{ github.event.repository.default_branch }} persist-credentials: false # Proof-policy epochs classify main's first-parent squashes locally. fetch-depth: 0 - - uses: oven-sh/setup-bun@v2 + - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 with: bun-version: "1.4.2" - name: Archive incremental two-day job and step timings @@ -41,7 +41,7 @@ jobs: bun scripts/ci-timings.ts collect --repo "$TIMING_REPO" --since "$since" --seed "$TIMING_DEFAULT_BRANCH" --request-budget 200 --reserve 500 --reservations --red-main - name: Retain normalized timing archive if: always() - uses: actions/upload-artifact@v7 + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 with: name: ci-timings path: tmp/ci-timings/ diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b17e0d5f53..2c50eb3f8b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -43,11 +43,11 @@ jobs: reuse: ${{ steps.reuse.outputs.reuse }} red_main_oid: ${{ steps.plan.outputs.red_main_oid }} steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: persist-credentials: false fetch-depth: 0 - - uses: oven-sh/setup-bun@v2 + - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 with: bun-version: "1.4.2" - run: bun install --frozen-lockfile @@ -100,7 +100,7 @@ jobs: fi - name: Retention ledger and diagnostics if: always() - uses: actions/upload-artifact@v7 + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 with: name: proof-reuse-ledger path: | @@ -116,11 +116,11 @@ jobs: runs-on: ubuntu-24.04 timeout-minutes: 7 steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: persist-credentials: false fetch-depth: 0 - - uses: oven-sh/setup-bun@v2 + - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 with: bun-version: "1.4.2" - id: verify_install @@ -160,13 +160,13 @@ jobs: GEMINI_API_KEY: "" ANTHROPIC_API_KEY: "" steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: persist-credentials: false - - uses: oven-sh/setup-bun@v2 + - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 with: bun-version: "1.4.2" - - uses: actions/setup-node@v7 + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7 with: node-version: "24" - run: bun install --frozen-lockfile @@ -191,11 +191,11 @@ jobs: matrix: shard: ${{ fromJSON(needs.changeset.outputs.unit_shards) }} steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: persist-credentials: false fetch-depth: 0 - - uses: oven-sh/setup-bun@v2 + - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 with: bun-version: "1.4.2" # Native source freezes require dependency inodes owned by this checkout. @@ -227,7 +227,7 @@ jobs: "$SETUP_OUTCOME" "$PROOF_OUTCOME" >> "$GITHUB_STEP_SUMMARY" - name: Proof receipts and failure diagnostics if: always() - uses: actions/upload-artifact@v7 + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 with: name: unit-proof-${{ matrix.shard }} path: | @@ -268,11 +268,11 @@ jobs: # 12 minutes setup + unchanged 15 minutes proof + 3 minutes for other steps (#2658). timeout-minutes: 30 steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: persist-credentials: false fetch-depth: 0 - - uses: oven-sh/setup-bun@v2 + - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 with: bun-version: "1.4.2" - run: bun install --frozen-lockfile @@ -301,7 +301,7 @@ jobs: "$SETUP_OUTCOME" "$PROOF_OUTCOME" >> "$GITHUB_STEP_SUMMARY" - name: Proof receipts and failure diagnostics if: always() - uses: actions/upload-artifact@v7 + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 with: name: runtime-proof path: | @@ -337,11 +337,11 @@ jobs: # 12 minutes setup + unchanged 15 minutes proof + 3 minutes for other steps (#2658). timeout-minutes: 30 steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: persist-credentials: false fetch-depth: 0 - - uses: oven-sh/setup-bun@v2 + - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 with: bun-version: "1.4.2" - run: bun install --frozen-lockfile @@ -389,7 +389,7 @@ jobs: "$SETUP_OUTCOME" "$PROOF_OUTCOME" >> "$GITHUB_STEP_SUMMARY" - name: Proof receipts and failure diagnostics if: always() - uses: actions/upload-artifact@v7 + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 with: name: runtime-host-proof path: | @@ -430,11 +430,11 @@ jobs: matrix: shard: [1, 2, 3] steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: persist-credentials: false fetch-depth: 0 - - uses: oven-sh/setup-bun@v2 + - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 with: bun-version: "1.4.2" - run: bun install --frozen-lockfile @@ -449,7 +449,7 @@ jobs: run: bun scripts/ci-proof.ts browser --shard=${{ matrix.shard }}/3 - name: Proof receipts and failure diagnostics if: always() - uses: actions/upload-artifact@v7 + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 with: name: browser-proof-${{ matrix.shard }} path: | @@ -495,11 +495,11 @@ jobs: matrix: shard: [1, 2] steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: persist-credentials: false fetch-depth: 0 - - uses: oven-sh/setup-bun@v2 + - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 with: bun-version: "1.4.2" - run: bun install --frozen-lockfile @@ -514,7 +514,7 @@ jobs: run: bun scripts/ci-proof.ts layout --shard=${{ matrix.shard }}/2 - name: Proof receipts and failure diagnostics if: always() - uses: actions/upload-artifact@v7 + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 with: name: layout-proof-${{ matrix.shard }} path: | @@ -550,11 +550,11 @@ jobs: runs-on: ubuntu-24.04 timeout-minutes: 20 steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: persist-credentials: false fetch-depth: 0 - - uses: oven-sh/setup-bun@v2 + - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 with: bun-version: "1.4.2" - run: bun install --frozen-lockfile @@ -569,7 +569,7 @@ jobs: run: bun scripts/ci-proof.ts captures - name: Proof receipts and failure diagnostics if: always() - uses: actions/upload-artifact@v7 + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 with: name: captures-proof path: | @@ -603,11 +603,11 @@ jobs: runs-on: ubuntu-24.04 timeout-minutes: 20 steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: persist-credentials: false fetch-depth: 0 - - uses: oven-sh/setup-bun@v2 + - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 with: bun-version: "1.4.2" - run: bun install --frozen-lockfile @@ -622,7 +622,7 @@ jobs: run: bun scripts/ci-proof.ts endurance - name: Proof receipts and failure diagnostics if: always() - uses: actions/upload-artifact@v7 + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 with: name: endurance-proof path: | @@ -659,11 +659,11 @@ jobs: runs-on: ubuntu-24.04 timeout-minutes: 3 steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: persist-credentials: false fetch-depth: 0 - - uses: oven-sh/setup-bun@v2 + - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 with: bun-version: "1.4.2" - run: bun install --frozen-lockfile diff --git a/.github/workflows/contract.yml b/.github/workflows/contract.yml index c3dcba019b..887da31f33 100644 --- a/.github/workflows/contract.yml +++ b/.github/workflows/contract.yml @@ -37,12 +37,12 @@ jobs: # The PR's head commit, not the default synthetic merge commit: the # merge commit, diffed against the base, drops a doc edit that also # landed on the base through another PR. Full history for the merge base. - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: persist-credentials: false ref: ${{ github.event.pull_request.head.sha }} fetch-depth: 0 - - uses: oven-sh/setup-bun@v2 + - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 with: bun-version: "1.4.2" - name: Match the CONTRACT title and label to the contract doc diff --git a/.github/workflows/heavy-feedback.yml b/.github/workflows/heavy-feedback.yml index 5322a51276..ffebb5177c 100644 --- a/.github/workflows/heavy-feedback.yml +++ b/.github/workflows/heavy-feedback.yml @@ -56,11 +56,11 @@ jobs: red_main_oid: "${{ steps.plan.outputs.red_main_oid }}" base_sha: "${{ steps.admit.outputs.base_sha }}" steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: persist-credentials: false fetch-depth: 1 - - uses: oven-sh/setup-bun@v2 + - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 with: bun-version: 1.4.2 - run: bun install --frozen-lockfile @@ -71,7 +71,7 @@ jobs: FEEDBACK_HEAD_SHA: "${{ inputs.head_sha }}" GH_TOKEN: "${{ github.token }}" run: bun scripts/heavy-feedback.ts admit - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: persist-credentials: false fetch-depth: 0 @@ -97,12 +97,12 @@ jobs: runs-on: ubuntu-24.04 timeout-minutes: 7 steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: persist-credentials: false fetch-depth: 0 ref: "${{ inputs.head_sha }}" - - uses: oven-sh/setup-bun@v2 + - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 with: bun-version: 1.4.2 - id: verify_install @@ -139,14 +139,14 @@ jobs: GEMINI_API_KEY: "" ANTHROPIC_API_KEY: "" steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: persist-credentials: false ref: "${{ inputs.head_sha }}" - - uses: oven-sh/setup-bun@v2 + - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 with: bun-version: 1.4.2 - - uses: actions/setup-node@v7 + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7 with: node-version: "24" - run: bun install --frozen-lockfile @@ -163,12 +163,12 @@ jobs: matrix: shard: "${{ fromJSON(needs.changeset.outputs.unit_shards) }}" steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: persist-credentials: false fetch-depth: 0 ref: "${{ inputs.head_sha }}" - - uses: oven-sh/setup-bun@v2 + - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 with: bun-version: 1.4.2 - run: bun install --frozen-lockfile --backend=copyfile @@ -196,7 +196,7 @@ jobs: run: "printf 'Environment setup (infrastructure prerequisite, 12-minute limit): %s\\nProof (30-minute limit): %s\\n' \\\n \"$SETUP_OUTCOME\" \"$PROOF_OUTCOME\" >> \"$GITHUB_STEP_SUMMARY\"\n" - name: Proof receipts and failure diagnostics if: always() - uses: actions/upload-artifact@v7 + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 with: name: "unit-proof-${{ matrix.shard }}" path: "tmp/proof-checkout.json\ntmp/proof-resources.json\ntmp/runner-disk.json\ntmp/unit-memory.jsonl\ntmp/unit-report.xml\ntmp/unit-report-summary.json\ntmp/unit-worker-*.xml\ntmp/unit-worker-*.json\ntmp/unit-worker-diagnostics/\ntmp/unit-timings.json\ntmp/measure-claude-*.json\ntmp/*-probe.json\ntmp/feature-capture-verification/\npackages/ui-kit/.vitest-attachments/\npackages/ui-react/.vitest-attachments/\n.vitest-attachments/\ntmp/diagram-renderer-proof/\ntmp/mermaid-renderer-proof/\ntmp/diagram-export-proof/\ntmp/cold-capture/\ntmp/share-review/\ntmp/svg-proof/\npackages/ui-kit/**/__screenshots__/**/*-[0-9]*.png\npackages/ui-react/**/__screenshots__/**/*-[0-9]*.png\n!packages/ui-kit/**/__screenshots__/**/*-linux.png\n!packages/ui-react/**/__screenshots__/**/*-linux.png\n" @@ -209,12 +209,12 @@ jobs: runs-on: ubuntu-24.04 timeout-minutes: 30 steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: persist-credentials: false fetch-depth: 0 ref: "${{ inputs.head_sha }}" - - uses: oven-sh/setup-bun@v2 + - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 with: bun-version: 1.4.2 - run: bun install --frozen-lockfile @@ -240,7 +240,7 @@ jobs: run: "printf 'Environment setup (infrastructure prerequisite, 12-minute limit): %s\\nProof (15-minute limit): %s\\n' \\\n \"$SETUP_OUTCOME\" \"$PROOF_OUTCOME\" >> \"$GITHUB_STEP_SUMMARY\"\n" - name: Proof receipts and failure diagnostics if: always() - uses: actions/upload-artifact@v7 + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 with: name: runtime-proof path: "tmp/native-host-proof/\ntmp/proof-checkout.json\ntmp/proof-resources.json\ntmp/unit-report.xml\ntmp/unit-timings.json\ntmp/measure-claude-*.json\ntmp/*-probe.json\ntmp/feature-capture-verification/\npackages/ui-kit/.vitest-attachments/\npackages/ui-react/.vitest-attachments/\n.vitest-attachments/\ntmp/diagram-renderer-proof/\ntmp/mermaid-renderer-proof/\ntmp/diagram-export-proof/\ntmp/cold-capture/\ntmp/share-review/\ntmp/svg-proof/\npackages/ui-kit/**/__screenshots__/**/*-[0-9]*.png\npackages/ui-react/**/__screenshots__/**/*-[0-9]*.png\n!packages/ui-kit/**/__screenshots__/**/*-linux.png\n!packages/ui-react/**/__screenshots__/**/*-linux.png\n" @@ -253,12 +253,12 @@ jobs: runs-on: ubuntu-24.04 timeout-minutes: 30 steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: persist-credentials: false fetch-depth: 0 ref: "${{ inputs.head_sha }}" - - uses: oven-sh/setup-bun@v2 + - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 with: bun-version: 1.4.2 - run: bun install --frozen-lockfile @@ -296,7 +296,7 @@ jobs: run: "printf 'Environment setup (infrastructure prerequisite, 12-minute limit): %s\\nProof (15-minute limit): %s\\n' \\\n \"$SETUP_OUTCOME\" \"$PROOF_OUTCOME\" >> \"$GITHUB_STEP_SUMMARY\"\n" - name: Proof receipts and failure diagnostics if: always() - uses: actions/upload-artifact@v7 + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 with: name: runtime-host-proof path: "tmp/native-host-proof/\ntmp/reference-pool-proof/\ntmp/worker-identity-proof/\ntmp/proof-checkout.json\ntmp/proof-resources.json\ntmp/unit-report.xml\ntmp/unit-timings.json\ntmp/measure-claude-*.json\ntmp/*-probe.json\ntmp/feature-capture-verification/\npackages/ui-kit/.vitest-attachments/\npackages/ui-react/.vitest-attachments/\n.vitest-attachments/\ntmp/diagram-renderer-proof/\ntmp/mermaid-renderer-proof/\ntmp/diagram-export-proof/\ntmp/cold-capture/\ntmp/share-review/\ntmp/svg-proof/\npackages/ui-kit/**/__screenshots__/**/*-[0-9]*.png\npackages/ui-react/**/__screenshots__/**/*-[0-9]*.png\n!packages/ui-kit/**/__screenshots__/**/*-linux.png\n!packages/ui-react/**/__screenshots__/**/*-linux.png\n" @@ -316,12 +316,12 @@ jobs: - 2 - 3 steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: persist-credentials: false fetch-depth: 0 ref: "${{ inputs.head_sha }}" - - uses: oven-sh/setup-bun@v2 + - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 with: bun-version: 1.4.2 - run: bun install --frozen-lockfile @@ -335,7 +335,7 @@ jobs: run: "bun scripts/ci-proof.ts browser --shard=${{ matrix.shard }}/3" - name: Proof receipts and failure diagnostics if: always() - uses: actions/upload-artifact@v7 + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 with: name: "browser-proof-${{ matrix.shard }}" path: "tmp/proof-checkout.json\ntmp/proof-resources.json\ntmp/proof-cases.json\ntmp/unit-report.xml\ntmp/unit-timings.json\ntmp/measure-claude-*.json\ntmp/*-probe.json\ntmp/feature-capture-verification/\npackages/ui-kit/.vitest-attachments/\npackages/ui-react/.vitest-attachments/\n.vitest-attachments/\ntmp/diagram-renderer-proof/\ntmp/mermaid-renderer-proof/\ntmp/diagram-export-proof/\ntmp/diagram-export-native-prepared/*/*/release.svg\ntmp/diagram-export-native-prepared/*/*/release.png\ntmp/diagram-export-native-prepared/*/*/release.pdf\ntmp/diagram-export-native-prepared/*/*/origin.svg\ntmp/diagram-export-native-prepared/*/*/origin.png\ntmp/diagram-export-native-prepared/*/*/origin.pdf\ntmp/diagram-export-native-prepared/*/*/producer.json\ntmp/cold-capture/\ntmp/share-review/\ntmp/svg-proof/\npackages/ui-kit/**/__screenshots__/**/*-[0-9]*.png\npackages/ui-react/**/__screenshots__/**/*-[0-9]*.png\n!packages/ui-kit/**/__screenshots__/**/*-linux.png\n!packages/ui-react/**/__screenshots__/**/*-linux.png\n" @@ -354,12 +354,12 @@ jobs: - 1 - 2 steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: persist-credentials: false fetch-depth: 0 ref: "${{ inputs.head_sha }}" - - uses: oven-sh/setup-bun@v2 + - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 with: bun-version: 1.4.2 - run: bun install --frozen-lockfile @@ -373,7 +373,7 @@ jobs: run: "bun scripts/ci-proof.ts layout --shard=${{ matrix.shard }}/2" - name: Proof receipts and failure diagnostics if: always() - uses: actions/upload-artifact@v7 + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 with: name: "layout-proof-${{ matrix.shard }}" path: "tmp/proof-checkout.json\ntmp/proof-resources.json\ntmp/proof-cases.json\ntmp/unit-report.xml\ntmp/unit-timings.json\ntmp/measure-claude-*.json\ntmp/*-probe.json\ntmp/feature-capture-verification/\npackages/ui-kit/.vitest-attachments/\npackages/ui-react/.vitest-attachments/\n.vitest-attachments/\ntmp/diagram-renderer-proof/\ntmp/mermaid-renderer-proof/\ntmp/diagram-export-proof/\ntmp/hygiene-proof/\ntmp/cold-capture/\ntmp/share-review/\ntmp/svg-proof/\npackages/ui-kit/**/__screenshots__/**/*-[0-9]*.png\npackages/ui-react/**/__screenshots__/**/*-[0-9]*.png\n!packages/ui-kit/**/__screenshots__/**/*-linux.png\n!packages/ui-react/**/__screenshots__/**/*-linux.png\n" @@ -386,12 +386,12 @@ jobs: runs-on: ubuntu-24.04 timeout-minutes: 20 steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: persist-credentials: false fetch-depth: 0 ref: "${{ inputs.head_sha }}" - - uses: oven-sh/setup-bun@v2 + - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 with: bun-version: 1.4.2 - run: bun install --frozen-lockfile @@ -405,7 +405,7 @@ jobs: run: bun scripts/ci-proof.ts captures - name: Proof receipts and failure diagnostics if: always() - uses: actions/upload-artifact@v7 + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 with: name: captures-proof path: "tmp/proof-checkout.json\ntmp/proof-resources.json\ntmp/unit-report.xml\ntmp/unit-timings.json\ntmp/measure-claude-*.json\ntmp/*-probe.json\ntmp/feature-capture-verification/\npackages/ui-kit/.vitest-attachments/\npackages/ui-react/.vitest-attachments/\n.vitest-attachments/\ntmp/diagram-renderer-proof/\ntmp/mermaid-renderer-proof/\ntmp/diagram-export-proof/\ntmp/cold-capture/\ntmp/share-review/\ntmp/svg-proof/\npackages/ui-kit/**/__screenshots__/**/*-[0-9]*.png\npackages/ui-react/**/__screenshots__/**/*-[0-9]*.png\n!packages/ui-kit/**/__screenshots__/**/*-linux.png\n!packages/ui-react/**/__screenshots__/**/*-linux.png\n" @@ -418,12 +418,12 @@ jobs: runs-on: ubuntu-24.04 timeout-minutes: 20 steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: persist-credentials: false fetch-depth: 0 ref: "${{ inputs.head_sha }}" - - uses: oven-sh/setup-bun@v2 + - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 with: bun-version: 1.4.2 - run: bun install --frozen-lockfile @@ -437,7 +437,7 @@ jobs: run: bun scripts/ci-proof.ts endurance - name: Proof receipts and failure diagnostics if: always() - uses: actions/upload-artifact@v7 + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 with: name: endurance-proof path: "tmp/proof-checkout.json\ntmp/proof-resources.json\ntmp/proof-cases.json\ntmp/unit-report.xml\ntmp/unit-timings.json\ntmp/measure-claude-*.json\ntmp/*-probe.json\ntmp/feature-capture-verification/\npackages/ui-kit/.vitest-attachments/\npackages/ui-react/.vitest-attachments/\n.vitest-attachments/\ntmp/diagram-renderer-proof/\ntmp/mermaid-renderer-proof/\ntmp/diagram-export-proof/\ntmp/cold-capture/\ntmp/share-review/\ntmp/svg-proof/\npackages/ui-kit/**/__screenshots__/**/*-[0-9]*.png\npackages/ui-react/**/__screenshots__/**/*-[0-9]*.png\n!packages/ui-kit/**/__screenshots__/**/*-linux.png\n!packages/ui-react/**/__screenshots__/**/*-linux.png\n" @@ -461,11 +461,11 @@ jobs: runs-on: ubuntu-24.04 timeout-minutes: 3 steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: persist-credentials: false fetch-depth: 0 - - uses: oven-sh/setup-bun@v2 + - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 with: bun-version: 1.4.2 - run: bun install --frozen-lockfile diff --git a/.github/workflows/project-sync.yml b/.github/workflows/project-sync.yml index c74fda1cb4..a5e5013884 100644 --- a/.github/workflows/project-sync.yml +++ b/.github/workflows/project-sync.yml @@ -48,8 +48,8 @@ jobs: runs-on: ubuntu-24.04 timeout-minutes: 15 steps: - - uses: actions/checkout@v7 - - uses: oven-sh/setup-bun@v2 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 with: bun-version: "1.4.2" - name: Sync the issue diff --git a/.github/workflows/publish-pages.yml b/.github/workflows/publish-pages.yml index 08b32c294f..72c9e63e4d 100644 --- a/.github/workflows/publish-pages.yml +++ b/.github/workflows/publish-pages.yml @@ -51,16 +51,16 @@ jobs: outputs: publish: ${{ steps.selection.outputs.publish }} steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: # Release runs pair current website main with the independently tagged product. ref: ${{ inputs.source_sha || 'main' }} fetch-depth: 0 persist-credentials: false - - uses: oven-sh/setup-bun@v2 + - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 with: bun-version: '1.4.2' - - uses: actions/setup-node@v6 + - uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6 with: node-version: '22.23.3' - name: Validate source and select the product @@ -128,7 +128,7 @@ jobs: run: bun website/scripts/verify-publication.ts - name: Save browser diagnostics and build provenance if: always() && steps.selection.outputs.publish == 'true' - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 with: name: website-proof-${{ github.run_id }}-${{ github.run_attempt }} path: | @@ -141,7 +141,7 @@ jobs: if-no-files-found: warn include-hidden-files: true retention-days: 14 - - uses: actions/upload-pages-artifact@v4 + - uses: actions/upload-pages-artifact@7b1f4a764d45c48632c6b24a0339c27f5614fb0b # v4 if: steps.selection.outputs.publish == 'true' with: path: ${{ env.PAGES_WORKSPACE }}/website/dist @@ -160,4 +160,4 @@ jobs: steps: - name: Publish the verified artifact id: deployment - uses: actions/deploy-pages@v4 + uses: actions/deploy-pages@d6db90164ac5ed86f2b6aed7e0febac5b3c0c03e # v4 \ No newline at end of file diff --git a/.github/workflows/red-main-probe.yml b/.github/workflows/red-main-probe.yml index f2c64b7151..e7c8c97751 100644 --- a/.github/workflows/red-main-probe.yml +++ b/.github/workflows/red-main-probe.yml @@ -40,18 +40,18 @@ jobs: PROBE_SHA: ${{ inputs.sha }} run: | [[ "$SOURCE_RUN" =~ ^[1-9][0-9]*$ ]] && [[ "$PROBE_SHA" =~ ^[a-f0-9]{40}$ ]] - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: ref: ${{ github.event.repository.default_branch }} path: tooling persist-credentials: false - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: ref: ${{ inputs.sha }} path: target persist-credentials: false fetch-depth: 0 - - uses: oven-sh/setup-bun@v2 + - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 with: bun-version: "1.4.2" - run: bun install --frozen-lockfile diff --git a/.github/workflows/red-main.yml b/.github/workflows/red-main.yml index a5543048a3..5929f6d1b2 100644 --- a/.github/workflows/red-main.yml +++ b/.github/workflows/red-main.yml @@ -30,11 +30,11 @@ jobs: issues: write # one incident issue per record; flake issues pull-requests: write # report squashes that landed while red steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: ref: ${{ github.event.repository.default_branch }} fetch-depth: 0 - - uses: oven-sh/setup-bun@v2 + - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 with: bun-version: "1.4.2" - run: bun install --frozen-lockfile @@ -44,7 +44,7 @@ jobs: run: bun scripts/red-main-cli.ts coordinate - name: Retain recorded incident events if: always() - uses: actions/upload-artifact@v7 + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 with: name: red-main-events path: tmp/red-main-events/ diff --git a/docs/decisions/github-actions-ci.md b/docs/decisions/github-actions-ci.md index 056937e3cd..ddcd9c499b 100644 --- a/docs/decisions/github-actions-ci.md +++ b/docs/decisions/github-actions-ci.md @@ -60,3 +60,33 @@ repository's active Depot definitions disables its configured CI workflows; the cutover records actual provider execution rather than assuming that a local YAML comparison proves event delivery. Unrelated Depot products and other repositories are outside this change. + +## Actions pinned by commit + +The maintainer ruled on 2026-11-16 +([#4111](https://github.com/schlessera/brain-kit/issues/4111)) that every +workflow references an action by the full commit its release tag named when +the pin was reviewed. A tag can be moved by whoever controls the action's +repository; a commit cannot. An action runs with the workflow's token, which +for `red-main.yml` can write the coordination ref, cancel runs and edit +issues. + +- **One table.** `ACTION_PINS` (`scripts/action-pins.ts:7-16`) maps each + `owner/name@tag` to its commit. Tests and lint rules name an action through + `pinned` (`scripts/action-pins.ts:22-24`), never a literal reference. +- **The lint refuses anything else.** `actionPinProblems` + (`scripts/action-pins.ts:44-63`) requires each reference to be its own block + line, `uses: owner/name@ # `, with the commit and tag found in + the table. It also counts the references in the parsed workflow against + those lines, so a quoted, flow-style or reusable-workflow reference is + refused instead of going unread. `checkCIWorkflows` runs it on every + workflow file. +- **The generated workflow keeps the comments.** `heavy-feedback.yml` is + rendered from `ci.yml`, and rendering drops comments; + `annotateActionPins` (`scripts/action-pins.ts:66-72`) restores them from + the table. + +This pins what was already in use: no action moved to a newer release. +[Bumping a pin](../process/testing.md#bumping-an-action-pin) is a reviewed +change to the table. + diff --git a/docs/process/testing.md b/docs/process/testing.md index bf7d70c538..06cbe77dd4 100644 --- a/docs/process/testing.md +++ b/docs/process/testing.md @@ -718,6 +718,29 @@ affected tests run. Drafts run cheap gates only. Forks use ordinary `checks: read` for bounded proof lookup), no secrets and nonpersisted checkout credentials. A fork run awaiting maintainer approval has not passed. +### Bumping an action pin + +Workflows reference each action by commit, with its release tag as a comment: +`uses: actions/checkout@<40-hex commit> # v7` +([why](../decisions/github-actions-ci.md#actions-pinned-by-commit)). +`bun run lint` refuses a tag, a branch, a commit that is not in +`scripts/action-pins.ts`, or a missing or wrong tag comment. To move a pin: + +1. Resolve the tag from the action's own repository, and dereference an + annotated tag to its commit: + + ```sh + gh api repos/actions/checkout/git/ref/tags/v7 --jq '.object.type + " " + .object.sha' + # "tag " is an annotated tag: read its commit + gh api repos/actions/checkout/git/tags/ --jq .object.sha + ``` + +2. Read what changed between the old and new commits before trusting it. +3. Change the commit in `ACTION_PINS`, replace it in every workflow, and run + `bun scripts/heavy-feedback-workflow.ts` to regenerate `heavy-feedback.yml`. +4. A new action or a new major tag is a new table row. The PR lists action, + tag and commit. + Environment setup via `scripts/ci-runtime-setup.sh` has its own 12-minute step limit in `unit`, `runtime` and `runtime_host`. Proof retains a separate 30-minute unit allowance or 15-minute runtime allowance. The job caps are diff --git a/scripts/action-pins.ts b/scripts/action-pins.ts new file mode 100644 index 0000000000..b4af1899dd --- /dev/null +++ b/scripts/action-pins.ts @@ -0,0 +1,72 @@ +/** + * Workflow actions run with the workflow's token, so each `uses:` names the + * full commit its release tag pointed at when the pin was reviewed, never the + * mutable tag itself (#4111). One table owns every pin; the workflow lint and + * the generated heavy-feedback workflow read it. + */ +export const ACTION_PINS = { + "actions/checkout@v7": "3d3c42e5aac5ba805825da76410c181273ba90b1", + "actions/deploy-pages@v4": "d6db90164ac5ed86f2b6aed7e0febac5b3c0c03e", + "actions/setup-node@v6": "249970729cb0ef3589644e2896645e5dc5ba9c38", + "actions/setup-node@v7": "949feb2413d6458794dcd2491c4babbbce0c15c1", + "actions/upload-artifact@v4": "ea165f8d65b6e75b540449e92b4886f43607fa02", + "actions/upload-artifact@v7": "cf430e030ddbb5b0abf93d22962f4752f3646cd9", + "actions/upload-pages-artifact@v4": "7b1f4a764d45c48632c6b24a0339c27f5614fb0b", + "oven-sh/setup-bun@v2": "0c5077e51419868618aeaa5fe8019c62421857d6", +} as const; +export type ActionPin = keyof typeof ACTION_PINS; + +const split = (pin: string): [string, string] => [pin.slice(0, pin.lastIndexOf("@")), pin.slice(pin.lastIndexOf("@") + 1)]; + +/** The `uses:` value for a reviewed action release: `owner/name@`. */ +export function pinned(pin: ActionPin): string { + return `${split(pin)[0]}@${ACTION_PINS[pin]}`; +} + +const REVIEWED = new Map(Object.entries(ACTION_PINS).map(([pin, sha]) => [`${split(pin)[0]}@${sha}`, split(pin)[1]])); +const USES_LINE = /^\s*(?:-\s*)?uses:\s*(.*?)\s*$/; + +/** Every `uses:` value a parsed workflow carries, wherever its YAML spells it. */ +function parsedUses(value: unknown, found: string[] = []): string[] { + if (Array.isArray(value)) for (const entry of value) parsedUses(entry, found); + else if (value && typeof value === "object") for (const [key, entry] of Object.entries(value)) { + if (key === "uses") found.push(String(entry)); else parsedUses(entry, found); + } + return found; +} + +/** + * A workflow may run only reviewed action commits. Each reference is one block + * line, `uses: owner/name@<40-hex commit> # `, whose commit and tag match + * `ACTION_PINS`. Parsed references are counted against those lines, so a quoted, + * flow-style or reusable-workflow reference cannot pass unread. + */ +export function actionPinProblems(text: string, file: string): string[] { + const problems: string[] = [], fail = (message: string) => problems.push(`${file}: ${message}`); + let parsed: unknown; + try { parsed = Bun.YAML.parse(text); } catch { return [`${file}: invalid YAML`]; } + let lines = 0; + for (const line of text.split("\n")) { + const value = USES_LINE.exec(line)?.[1]; + if (value === undefined) continue; + lines++; + const match = /^([^\s@"'#]+)@([0-9a-f]{40})\s+#\s+(\S+)$/.exec(value); + if (!match) { fail(`action reference must be a full commit followed by its tag comment, not: ${value}`); continue; } + const tag = REVIEWED.get(`${match[1]}@${match[2]}`); + if (!tag) fail(`${match[1]}@${match[2]} is not a reviewed pin in scripts/action-pins.ts`); + else if (tag !== match[3]) fail(`${match[1]}@${match[2]} is the reviewed commit of ${tag}, not ${match[3]}`); + } + const uses = parsedUses(parsed); + for (const value of uses) if (!REVIEWED.has(value)) fail(`${value} is not a reviewed action commit`); + if (uses.length !== lines) fail(`${uses.length} action references but ${lines} readable uses: lines; write each as its own block line`); + return [...new Set(problems)]; +} + +/** Restore the tag comments a YAML stringifier drops, for generated workflows. */ +export function annotateActionPins(text: string): string { + return text.split("\n").map(line => { + const match = /^(\s*(?:-\s*)?uses:\s*)["']?([^\s"'#]+@[0-9a-f]{40})["']?\s*$/.exec(line); + const tag = match && REVIEWED.get(match[2]!); + return match && tag ? `${match[1]}${match[2]} # ${tag}` : line; + }).join("\n"); +} diff --git a/scripts/check-ci-workflows.ts b/scripts/check-ci-workflows.ts index 3b50cbb7cb..681692a9f1 100644 --- a/scripts/check-ci-workflows.ts +++ b/scripts/check-ci-workflows.ts @@ -4,6 +4,7 @@ import { join, resolve } from "node:path"; import { PROOF_SHARDS, shardNumbers, type ShardedDomain } from "./proof-shards"; import { FEEDBACK_AGGREGATE } from "./heavy-feedback"; import { CATEGORY_JOBS, FEEDBACK_GROUP, renderHeavyFeedbackWorkflow, sameWorkflow } from "./heavy-feedback-workflow"; +import { actionPinProblems, pinned } from "./action-pins"; export const CI_WORKFLOWS = ["ci.yml", "contract.yml"] as const; const RUN_EXPRESSIONS = new Set(["matrix.shard", "github.event_name", "github.base_ref", "github.event.before"]); @@ -134,6 +135,8 @@ export function checkCIWorkflows(root: string): string[] { if (files.includes("ci-timings.yml")) expected.push("ci-timings.yml"); if (files.includes("heavy-feedback.yml")) expected.push("heavy-feedback.yml"); if (JSON.stringify(files) !== JSON.stringify(expected.sort())) problems.push("GitHub must contain only authoritative CI, contract, project-sync, red-main coordination and optional Pages/timing/heavy-feedback workflows"); + // Every workflow, authoritative or not, runs only reviewed action commits (#4111). + for (const file of files.filter(file => /\.ya?ml$/.test(file))) problems.push(...actionPinProblems(readFileSync(join(directory, file), "utf8"), file)); const depot = join(root, ".depot/workflows"); if (existsSync(depot) && readdirSync(depot).some(file => /\.ya?ml$/.test(file))) problems.push("Active Depot CI workflow definitions must be removed"); for (const file of CI_WORKFLOWS) { @@ -209,7 +212,7 @@ export function timingWorkflowProblems(text: string): string[] { if (!collection?.run?.includes('bun scripts/ci-timings.ts collect --repo "$TIMING_REPO" --since "$since" --seed "$TIMING_DEFAULT_BRANCH" --request-budget 200 --reserve 500 --reservations --red-main') || /--resources\b/.test(collection.run) || collection.env?.TIMING_DEFAULT_BRANCH !== "${{ github.event.repository.default_branch }}") fail("timing collection requires seeded acquisition, a hard budget/reserve and no scheduled resource logs"); for (const step of steps) if ((step.run ?? "").includes("${{") || /bun install/.test(step.run ?? "")) fail("collector scripts must not interpolate events or install candidate dependencies"); - if (!steps.some(s => s.uses === "actions/upload-artifact@v7" && s.if === "always()" && s.with?.["retention-days"] === 90 && s.with?.path === "tmp/ci-timings/")) fail("bounded always-upload timing archive missing"); + if (!steps.some(s => s.uses === pinned("actions/upload-artifact@v7") && s.if === "always()" && s.with?.["retention-days"] === 90 && s.with?.path === "tmp/ci-timings/")) fail("bounded always-upload timing archive missing"); return errors; } @@ -232,7 +235,7 @@ export function publicationWorkflowProblems(text: string): string[] { const steps = artifact?.steps ?? []; const checkouts = steps.filter(step => step.uses?.startsWith("actions/checkout@")); if (!checkouts.length || checkouts.some(step => step.with?.["persist-credentials"] !== false)) fail("checkout credentials must not persist"); - const upload = steps.findIndex(step => step.uses === "actions/upload-pages-artifact@v4"); + const upload = steps.findIndex(step => step.uses === pinned("actions/upload-pages-artifact@v4")); for (const command of ["bun website/scripts/check.ts", "bun website/scripts/verify-publication.ts"]) { const check = steps.findIndex(step => step.run === command); if (check < 0 || upload < 0 || check >= upload) fail("browser and identity checks must precede Pages artifact upload"); diff --git a/scripts/heavy-feedback-workflow.ts b/scripts/heavy-feedback-workflow.ts index c5d32b331c..e6146a680a 100644 --- a/scripts/heavy-feedback-workflow.ts +++ b/scripts/heavy-feedback-workflow.ts @@ -9,6 +9,7 @@ * bun scripts/heavy-feedback-workflow.ts --check # fail if it is stale */ import { readFileSync, writeFileSync } from "node:fs"; +import { annotateActionPins } from "./action-pins"; import { join, resolve } from "node:path"; import { FEEDBACK_AGGREGATE } from "./heavy-feedback"; @@ -103,7 +104,7 @@ export function renderHeavyFeedbackWorkflow(ciText: string): string { return "# Generated by scripts/heavy-feedback-workflow.ts from ci.yml; do not edit.\n" + "# Draft heavy feedback (#3272) runs a draft PR's affected heavy categories with\n" + "# the same jobs and pins as confirmation. It is never `proof`; request it with\n" + - "# `bun scripts/request-heavy-feedback.ts `.\n" + Bun.YAML.stringify(workflow, null, 2); + "# `bun scripts/request-heavy-feedback.ts `.\n" + annotateActionPins(Bun.YAML.stringify(workflow, null, 2)); } /** Freshness compares parsed structure: Bun's YAML stringifier whitespace differs diff --git a/tests/ci-workflows.test.ts b/tests/ci-workflows.test.ts index 5cad2fc6e9..a6d8802101 100644 --- a/tests/ci-workflows.test.ts +++ b/tests/ci-workflows.test.ts @@ -1,9 +1,10 @@ /** Preserve contribution routing, scheduling and hostile-metadata proof on GitHub Actions. */ import { afterAll, beforeAll, describe, expect, test } from "bun:test"; -import { existsSync, mkdtempSync, readFileSync, mkdirSync, rmSync, writeFileSync } from "node:fs"; +import { existsSync, mkdtempSync, readFileSync, readdirSync, mkdirSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { dirname, join, resolve } from "node:path"; import { CI_WORKFLOWS, checkCIWorkflows, publicationWorkflowProblems, workflowProblems } from "../scripts/check-ci-workflows.ts"; +import { ACTION_PINS, actionPinProblems, annotateActionPins, pinned } from "../scripts/action-pins.ts"; const ROOT = resolve(import.meta.dir, ".."); type Json = null | boolean | number | string | Json[] | { [key: string]: Json }; type Obj = { [key: string]: Json }; @@ -117,7 +118,7 @@ describe("GitHub is the sole provider for every contribution", () => { expect(publicationWorkflowProblems(Bun.YAML.stringify(elevated))).toContain("publish-pages.yml: artifact job must inherit read-only permissions"); const premature = Bun.YAML.parse(pages) as Workflow; const steps = premature.jobs.artifact!.steps; - const upload = steps.findIndex(step => step.uses === "actions/upload-pages-artifact@v4"); + const upload = steps.findIndex(step => step.uses === pinned("actions/upload-pages-artifact@v4")); expect(upload).toBeGreaterThan(0); steps.unshift(...steps.splice(upload, 1)); expect(publicationWorkflowProblems(Bun.YAML.stringify(premature))).toContain("publish-pages.yml: browser and identity checks must precede Pages artifact upload"); @@ -138,7 +139,7 @@ describe("the authoritative jobs retain their important phases", () => { expect(metadata).toContain("bun scripts/env-docs.ts --check"); expect(metadata).toContain("bun scripts/check-changeset-packages.ts"); expect(ci.jobs.verify!.steps.filter(s => s.run).map(s => s.run)).toContain("bun scripts/ci-runner.ts"); for (const [name,job] of Object.entries(ci.jobs)) { - const bun = job.steps.find(s => s.uses === "oven-sh/setup-bun@v2"); + const bun = job.steps.find(s => s.uses === pinned("oven-sh/setup-bun@v2")); expect(bun?.with?.["bun-version"]).toBe("1.4.2"); const install=name==="unit"?"bun install --frozen-lockfile --backend=copyfile":"bun install --frozen-lockfile"; expect(job.steps.some(s => s.run === install)).toBe(true); @@ -153,7 +154,7 @@ describe("the authoritative jobs retain their important phases", () => { const contract = workflows.find(w => w.file === "contract.yml")!.workflow; expect(contract.on.pull_request).toEqual({ types: ["opened", "edited", "synchronize", "reopened", "labeled", "unlabeled"] }); const job = contract.jobs.contract!; - const checkout = job.steps.find(s => s.uses === "actions/checkout@v7"); + const checkout = job.steps.find(s => s.uses === pinned("actions/checkout@v7")); expect(checkout?.with?.ref).toBe("${{ github.event.pull_request.head.sha }}"); expect(checkout?.with?.["fetch-depth"]).toBe(0); const command = job.steps.find(s => s.run)!; @@ -553,7 +554,7 @@ test("small exact inventories wire bounded planner partitions into actual unit e }); test("all unit partitions upload incremental memory diagnostics even after proof failure", () => { - const upload = ci.jobs.unit!.steps.find(s => s.uses === "actions/upload-artifact@v7")!; + const upload = ci.jobs.unit!.steps.find(s => s.uses === pinned("actions/upload-artifact@v7"))!; expect(upload.if).toBe("always()"); expect(String(upload.with!.path).split("\n"), "UNIT_MEMORY_DIAGNOSTICS_RETAINED").toContain("tmp/unit-memory.jsonl"); }); @@ -677,3 +678,43 @@ test("a main push whose metadata job fails still runs its selected proof (#2942) for (const gateStep of ["Lint, leakage and contribution workflow guards", "Env documentation matches its descriptors", "Validate all pending changeset package names", "Require a changeset for shipped package changes"]) expect(steps.indexOf(gateStep), `OUTPUTS_BEFORE_${gateStep}`).toBeGreaterThan(reuse); }); + +describe("workflow actions are pinned by commit (#4111)", () => { + const sha = ACTION_PINS["actions/checkout@v7"]; + const workflow = (uses: string) => `name: fixture\non: push\njobs:\n one:\n runs-on: ubuntu-24.04\n steps:\n - ${uses}\n - run: echo done\n`; + test("every workflow in the repository names reviewed commits with their tag comment", () => { + for (const file of readdirSync(join(ROOT, ".github/workflows")).sort()) expect({ file, problems: actionPinProblems(read(file), file) }).toEqual({ file, problems: [] }); + }); + test("a tag, a branch, an unreviewed commit and a missing or wrong tag comment are refused", () => { + expect(actionPinProblems(workflow(`uses: actions/checkout@${sha} # v7`), "fixture.yml")).toEqual([]); + for (const [uses, reason] of [ + ["uses: actions/checkout@v7", "ACTION_BY_TAG"], + ["uses: actions/checkout@main", "ACTION_BY_BRANCH"], + [`uses: actions/checkout@${"0".repeat(40)} # v7`, "UNREVIEWED_COMMIT"], + [`uses: actions/checkout@${sha}`, "MISSING_TAG_COMMENT"], + [`uses: actions/checkout@${sha} # v6`, "WRONG_TAG_COMMENT"], + [`uses: "actions/checkout@${sha}" # v7`, "QUOTED_REFERENCE"], + ["uses: ./local-action", "LOCAL_ACTION"], + ] as const) expect(actionPinProblems(workflow(uses), "fixture.yml").length, reason).toBeGreaterThan(0); + }); + test("a reusable workflow call and a flow-style step cannot carry an unpinned action past the line check", () => { + expect(actionPinProblems("name: fixture\non: push\njobs:\n call:\n uses: odysseus/ithaca/.github/workflows/sail.yml@v1\n", "fixture.yml").length).toBeGreaterThan(0); + expect(actionPinProblems("name: fixture\non: push\njobs:\n one:\n runs-on: ubuntu-24.04\n steps: [{ uses: actions/checkout@v7 }]\n", "fixture.yml").length).toBeGreaterThan(0); + }); + test("the repository lint reports an unpinned action in any workflow file", () => { + const root = mkdtempSync(join(tmpdir(), "action-pins-")); + try { + mkdirSync(join(root, ".github/workflows"), { recursive: true }); + for (const file of readdirSync(join(ROOT, ".github/workflows"))) writeFileSync(join(root, ".github/workflows", file), read(file)); + expect(checkCIWorkflows(root)).toEqual([]); + const target = join(root, ".github/workflows/project-sync.yml"); + writeFileSync(target, readFileSync(target, "utf8").replace(`${pinned("actions/checkout@v7")} # v7`, "actions/checkout@v7")); + expect(checkCIWorkflows(root).some(problem => problem.startsWith("project-sync.yml:") && problem.includes("actions/checkout@v7"))).toBe(true); + } finally { rmSync(root, { recursive: true, force: true }); } + }); + test("the generated heavy-feedback workflow keeps the tag comments its YAML rendering drops", () => { + const bare = ` - uses: ${pinned("oven-sh/setup-bun@v2")}\n - uses: "${pinned("actions/checkout@v7")}"\n`; + expect(annotateActionPins(bare)).toBe(` - uses: ${pinned("oven-sh/setup-bun@v2")} # v2\n - uses: ${pinned("actions/checkout@v7")} # v7\n`); + expect(actionPinProblems(read("heavy-feedback.yml"), "heavy-feedback.yml")).toEqual([]); + }); +}); From 93763ae8b9042eb6296d6e10600eea8fb3d84486 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 17 Nov 2026 00:03:40 +0000 Subject: [PATCH 03/31] chore(ci): run ready confirmation's unit proof in eight partitions (#4108) Ready confirmation and draft heavy feedback plan up to eight unit partitions; main pushes and exhaustive runs keep four. UNIT_PARTITIONS in scripts/proof-shards.ts is the one owner: the planner reads it by cadence, the hosted aggregate refuses a published partition set that differs from the plan, the merge path bounds the confirmed set by the confirmation cap, the weight refresh takes its job count from it, and the workflow guard refuses a literal unit matrix or divisor. Co-Authored-By: Claude Fable 5.2 --- scripts/candidate-proof.ts | 7 ++- scripts/check-ci-workflows.ts | 9 ++++ scripts/ci-plan.ts | 8 +-- scripts/integration-proof.ts | 7 +-- scripts/proof-shards.ts | 24 +++++++++ scripts/refresh-unit-costs.ts | 13 +++-- tests/ci-plan.test.ts | 84 +++++++++++++++++++++++++++++--- tests/ci-workflows.test.ts | 17 +++++++ tests/hosted-proof.test.ts | 26 +++++++++- tests/integration-proof.test.ts | 52 ++++++++++++++++++++ tests/refresh-unit-costs.test.ts | 19 ++++++-- 11 files changed, 240 insertions(+), 26 deletions(-) diff --git a/scripts/candidate-proof.ts b/scripts/candidate-proof.ts index 33cb55b403..7377595d5f 100644 --- a/scripts/candidate-proof.ts +++ b/scripts/candidate-proof.ts @@ -1,5 +1,5 @@ /** Exact merge-candidate validation; feedback never authorizes merging. */ -import { planFromEnvironment, proofCadence, proofSelections, redMainSnapshot } from "./ci-plan"; +import { planFromEnvironment, proofCadence, proofSelections, redMainSnapshot, unitShards } from "./ci-plan"; import type { RedMainRecord } from "./red-main"; import { checkout, type Checkout } from "./proof-inputs"; import { GitHubProofAPI, type API } from "./proof-reuse"; @@ -60,9 +60,12 @@ export function validateSelections(root: string, event: any, env: NodeJS.Process const plan = planFromEnvironment(root, { ...env, BASE_SHA: event.pull_request?.base?.sha, BEFORE_SHA: event.before, HEAD_SHA: event.pull_request?.head?.sha ?? env.GITHUB_SHA }, record); plan.cadence = cadence; - for (const [category, selected] of Object.entries(proofSelections(plan))) { + const selections = proofSelections(plan); + for (const [category, selected] of Object.entries(selections)) { if (outputs?.[category] !== String(selected)) throw new Error(`${category}: required candidate selection differs from actual inputs`); } + // The matrix ran the partitions the metadata job published; they must be the planned set (#4108). + if (selections.unit && outputs?.unit_shards !== JSON.stringify(unitShards(plan))) throw new Error("unit: published partition set differs from the planned one"); } export async function requireCandidate(root: string, event: any, env: NodeJS.ProcessEnv): Promise { diff --git a/scripts/check-ci-workflows.ts b/scripts/check-ci-workflows.ts index 3b50cbb7cb..a546ad7337 100644 --- a/scripts/check-ci-workflows.ts +++ b/scripts/check-ci-workflows.ts @@ -94,6 +94,15 @@ export function workflowProblems(text: string, file: string): string[] { if (JSON.stringify(job?.strategy?.matrix?.shard) !== JSON.stringify(shardNumbers(domain)) || !job?.steps?.some((step: any) => step.run === `bun scripts/ci-proof.ts ${domain} --shard=\${{ matrix.shard }}/${PROOF_SHARDS[domain]}`)) fail(`${domain}: matrix and shard divisor must match PROOF_SHARDS`); } + // The unit partition count has one owner, UNIT_PARTITIONS, read by the planner per cadence (#4108). + // A literal matrix, a second matrix dimension or a literal divisor would disagree with it. + const unit = workflow.jobs?.unit as any, changeset = workflow.jobs?.changeset as any; + const unitProof = unit?.steps?.find((step: Step) => step.run?.startsWith("bun scripts/ci-proof.ts unit")); + if (changeset?.outputs?.unit_shards !== "${{ steps.plan.outputs.unit_shards }}" || + changeset?.steps?.find((step: Step) => step.id === "plan")?.run !== "bun scripts/ci-plan.ts" || + JSON.stringify(unit?.strategy?.matrix) !== JSON.stringify({ shard: "${{ fromJSON(needs.changeset.outputs.unit_shards) }}" }) || + unitProof?.run !== 'bun scripts/ci-proof.ts unit --shard=${{ matrix.shard }}/"$UNIT_SHARDS"' || + unitProof?.env?.UNIT_SHARDS !== "${{ strategy.job-total }}") fail("unit: matrix and shard divisor must come from the planner's unit_shards output"); const proof = workflow.jobs?.proof; if (proof?.name !== "${{ github.event_name != 'pull_request' && 'integrated or exhaustive proof' || github.event.pull_request.draft && 'draft gates' || 'proof' }}") fail("proof: draft, manual or main runs must not impersonate candidate confirmation"); if (JSON.stringify(proof?.needs) !== JSON.stringify(["changeset", ...names])) fail("proof: aggregate must observe every selected category"); diff --git a/scripts/ci-plan.ts b/scripts/ci-plan.ts index d199e2c85b..f5d7e62c48 100644 --- a/scripts/ci-plan.ts +++ b/scripts/ci-plan.ts @@ -6,6 +6,7 @@ import { closureSelects, discoverBrowserClosures, type BrowserClosures } from ". import { addUnitImportConsumers, type UnitImportGraph } from "./unit-test-consumers"; import { coordinationFiles, RESERVATION_REF } from "./integration-reservation"; import { includeRedSet, isPostMerge, type Category, type IncludedRedSet, type RedMainRecord } from "./red-main"; +import { unitPartitions } from "./proof-shards"; export interface Workspace { dir: string; @@ -389,11 +390,10 @@ export function selectBrowserClosures(plan: CheckPlan, closures: BrowserClosures return { ...plan, local }; } -/** Narrow inventories use fewer nonempty partitions; ordinary proof keeps four. */ +/** Narrow inventories use fewer nonempty partitions. The cap follows the plan's + * cadence: `UNIT_PARTITIONS` (`scripts/proof-shards.ts`) is its one owner (#4108). */ export function unitShards(plan: CheckPlan): number[] { - const count = plan.unitTests?.length ?? 4; - if (!count) throw new Error("Empty selected unit inventory"); - return Array.from({length: Math.min(4, count)}, (_, i) => i + 1); + return unitPartitions(plan.cadence, plan.unitTests?.length); } export type ProofCadence = "draft" | "feedback" | "feedback-heavy" | "confirmation" | "integrated" | "exhaustive"; diff --git a/scripts/integration-proof.ts b/scripts/integration-proof.ts index 6501bbd46e..2509501c26 100644 --- a/scripts/integration-proof.ts +++ b/scripts/integration-proof.ts @@ -4,7 +4,7 @@ import { checkout, type Checkout } from "./proof-inputs"; import type { Candidate } from "./integration-reservation"; import type { API } from "./proof-reuse"; import { PROOF_JOBS, proofProblems } from "./ci-proof"; -import { shardNumbers } from "./proof-shards"; +import { MAX_UNIT_PARTITIONS, shardNumbers, unitPartitionLimit } from "./proof-shards"; import { coveredCategories } from "./check-receipt"; import type { Category } from "./red-main"; @@ -58,7 +58,7 @@ function inventoryDiagnostic(inventory: any, run: any, head: string): string { const choice = (value: unknown, choices: readonly string[]) => typeof value === "string" && choices.includes(value) ? value : "unrecognized"; const names = ["changeset", "proof", ...PROOF_JOBS, ...["browser", "layout"].flatMap(name => shardNumbers(name as "browser" | "layout").map(shard => `${name} (${shard})`)), - ...[1, 2, 3, 4].map(shard => `unit (${shard})`)]; + ...Array.from({ length: MAX_UNIT_PARTITIONS }, (_, index) => `unit (${index + 1})`)]; const fields = metadataObject(inventory) ? inventory : {}; const jobs = fields.jobs; const predicates: string[] = []; @@ -121,7 +121,8 @@ export async function verifyIntegrationProof(root: string, repository: string, c if (fresh && (name === "browser" || name === "layout")) expected.push(...shardNumbers(name).map(shard => `${name} (${shard}):success`)); else if (fresh && name === "unit") { const shards: unknown = JSON.parse(selected.unitShards ?? "null"); - if (!Array.isArray(shards) || !shards.length || shards.length > 4 || shards.some((value, index) => value !== index + 1)) throw new Error("Missing actual unit partition identity"); + // Only a ready confirmation reaches the merge path, so its cap bounds the planned set (#4108). + if (!Array.isArray(shards) || !shards.length || shards.length > unitPartitionLimit("confirmation") || shards.some((value, index) => value !== index + 1)) throw new Error("Missing actual unit partition identity"); expected.push(...shards.map(index => `unit (${index}):success`)); } else expected.push(`${name}:${fresh ? "success" : "skipped"}`); } diff --git a/scripts/proof-shards.ts b/scripts/proof-shards.ts index 8ea658395e..0631c5f082 100644 --- a/scripts/proof-shards.ts +++ b/scripts/proof-shards.ts @@ -6,3 +6,27 @@ export type ShardedDomain = keyof typeof PROOF_SHARDS; export function shardNumbers(domain: ShardedDomain): number[] { return Array.from({ length: PROOF_SHARDS[domain] }, (_, index) => index + 1); } + +/** Unit-tier partition caps (#4108). Ready confirmation holds the one merge + * lease while its unit jobs run, and draft heavy feedback runs the same jobs, + * so both use eight. Main pushes, exhaustive runs and local diagnostics keep + * the base four, so a main run needs no more runners than before. The planner, + * the merge path's partition validation, the weight refresh and the workflow + * guard read this table; the matrix and the divisor reach it through the + * planner's `unit_shards` output. */ +export const UNIT_PARTITIONS = { base: 4, cadence: { confirmation: 8, "feedback-heavy": 8 } } as const; +export const MAX_UNIT_PARTITIONS = Math.max(UNIT_PARTITIONS.base, ...Object.values(UNIT_PARTITIONS.cadence)); + +export function unitPartitionLimit(cadence: string | undefined): number { + const wide: Readonly> = UNIT_PARTITIONS.cadence; + return cadence !== undefined && Object.hasOwn(wide, cadence) ? wide[cadence]! : UNIT_PARTITIONS.base; +} + +/** Partition numbers for an inventory of `files` test files: never more + * partitions than files, so every partition is nonempty. Complete discovery + * passes no count and takes the cadence's cap. */ +export function unitPartitions(cadence: string | undefined, files?: number): number[] { + const limit = unitPartitionLimit(cadence); + if (files !== undefined && !(Number.isSafeInteger(files) && files >= 1)) throw new Error("Empty selected unit inventory"); + return Array.from({ length: Math.min(limit, files ?? limit) }, (_, index) => index + 1); +} diff --git a/scripts/refresh-unit-costs.ts b/scripts/refresh-unit-costs.ts index 5940bcfaee..9e7c679387 100644 --- a/scripts/refresh-unit-costs.ts +++ b/scripts/refresh-unit-costs.ts @@ -5,6 +5,7 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import type { API } from "./proof-reuse"; import type { Checkout } from "./proof-inputs"; +import { unitPartitionLimit } from "./proof-shards"; export interface UnitEvidenceAPI extends API { archive(id: number): Promise<{ digest: string; files: Record }>; @@ -20,7 +21,9 @@ export function assertWeightedLongFiles(milliseconds: Readonly = {}, observations = []; const jobIDs = new Set(); let identity: Checkout | undefined; - for (let shard = 1; shard <= 4; shard++) { + const total = unitPartitionLimit(info.event === "pull_request" ? "confirmation" : undefined); + if (page.jobs.filter((j: any) => /^unit \(\d+\)$/.test(j?.name)).length !== total) throw new Error(`Exactly ${total} fresh successful unit jobs required`); + for (let shard = 1; shard <= total; shard++) { const jobs = page.jobs.filter((j: any) => j.name === `unit (${shard})`), job = jobs[0]; const steps = job?.steps?.filter((s: any) => s.name === "Complete unit proof"), step = steps?.[0]; - if (jobs.length !== 1 || !Number.isSafeInteger(job.id) || jobIDs.has(job.id) || job.run_id !== run || job.head_sha !== info.head_sha || job.status !== "completed" || job.conclusion !== "success" || steps.length !== 1 || step.status !== "completed" || step.conclusion !== "success") throw new Error("Four fresh successful unit jobs required"); + if (jobs.length !== 1 || !Number.isSafeInteger(job.id) || jobIDs.has(job.id) || job.run_id !== run || job.head_sha !== info.head_sha || job.status !== "completed" || job.conclusion !== "success" || steps.length !== 1 || step.status !== "completed" || step.conclusion !== "success") throw new Error(`Exactly ${total} fresh successful unit jobs required`); jobIDs.add(job.id); const found = artifacts.artifacts.filter((a: any) => a.name === `unit-proof-${shard}`), artifact = found[0]; const created = Date.parse(artifact?.created_at); @@ -45,7 +50,7 @@ export async function refreshUnitCosts(run: number, attempt: number, api: UnitEv const receipt = JSON.parse(archive.files["proof-checkout.json"]!), timings = JSON.parse(archive.files["unit-timings.json"]!); const log = (await api.log(job.id)).replace(/\u001b\[[0-9;]*[A-Za-z]/g, ""); const checkouts = [...log.matchAll(/git log -1 --format=%H[^\n]*\n[^\n]*? ([a-f0-9]{40})\s*(?:\n|$)/g)]; - if (receipt.category !== "unit" || receipt.shard !== `${shard}/4` || !receipt.plan?.global || !receipt.plan?.local?.fullTests || + if (receipt.category !== "unit" || receipt.shard !== `${shard}/${total}` || !receipt.plan?.global || !receipt.plan?.local?.fullTests || !SHA.test(receipt.checkout?.sha) || !SHA.test(receipt.checkout?.tree) || checkouts.length !== 1 || checkouts[0]![1] !== receipt.checkout.sha || (identity && JSON.stringify(identity) !== JSON.stringify(receipt.checkout))) throw new Error("Unit checkout/source identity mismatch or nonexhaustive selection"); identity = receipt.checkout; diff --git a/tests/ci-plan.test.ts b/tests/ci-plan.test.ts index 770454f844..e98d61626e 100644 --- a/tests/ci-plan.test.ts +++ b/tests/ci-plan.test.ts @@ -31,6 +31,15 @@ function fixture() { return { dir, write, git, base: git("rev-parse", "HEAD") }; } +/** The real planner executable inside a fixture repository whose HEAD changes one core source file. */ +function plannerFixture() { + const f = fixture(); f.write("scripts/ci-plan.ts", readFileSync(join(import.meta.dir, "../scripts/ci-plan.ts"), "utf8").replace('"typescript"', JSON.stringify(import.meta.resolve("typescript")))); + for (const name of ["browser-input-closure", "unit-test-consumers", "integration-reservation", "red-main", "proof-shards"]) f.write(`scripts/${name}.ts`, `export * from ${JSON.stringify(resolve(import.meta.dir, `../scripts/${name}.ts`))};\n`); + f.write("packages/core/src/note.ts", "export const note = 2;\n"); + f.git("add", "."); f.git("commit", "-qm", "planner fixture"); + return f; +} + describe("affected CI checks", () => { test("file-read dispatch audits follow reviewed consumers and handler sources", () => { for (const path of ["packages/ui-react/src/connection.ts", "packages/ui-react/src/hooks/use-websocket.ts", @@ -77,6 +86,22 @@ describe("affected CI checks", () => { plan.unitTests = []; expect(() => unitShards(plan)).toThrow("Empty selected unit inventory"); }); + test("ready confirmation and draft heavy feedback plan eight unit partitions; main and exhaustive runs keep four (#4108)", () => { + const numbers = (length: number) => Array.from({ length }, (_, i) => i + 1); + for (const [cadence, cap] of [["confirmation", 8], ["feedback-heavy", 8], ["integrated", 4], ["exhaustive", 4], + ["draft", 4], ["feedback", 4], [undefined, 4]] as const) { + // Complete discovery names no inventory and takes the cadence's cap. + const plan = { ...planChecks(["package.json"], []), cadence }; + expect(unitShards(plan), `COMPLETE_DISCOVERY_${cadence}`).toEqual(numbers(cap)); + // Fewer files than partitions: one partition per file, never an empty one. + for (let count = 1; count <= 10; count++) { + plan.unitTests = Array.from({ length: count }, (_, i) => `tests/leaf-${i}.test.ts`); + expect(unitShards(plan), `NONEMPTY_${cadence}_${count}`).toEqual(numbers(Math.min(cap, count))); + } + plan.unitTests = []; expect(() => unitShards(plan), `EMPTY_${cadence}`).toThrow("Empty selected unit inventory"); + } + }); + test("an existing build glob consumes a test and refuses leaf selection", () => { const f = fixture(); const file = "packages/ui-sdk/tests/build-input.test.ts"; f.write(file, 'test("base", () => {});'); @@ -209,12 +234,7 @@ describe("affected CI checks", () => { }); test("the executable writes affected job outputs and keeps drafts on cheap gates", async () => { - const f = fixture(); f.write("scripts/ci-plan.ts", readFileSync(join(import.meta.dir, "../scripts/ci-plan.ts"), "utf8").replace('"typescript"', JSON.stringify(import.meta.resolve("typescript")))); - f.write("scripts/browser-input-closure.ts", `export * from ${JSON.stringify(resolve(import.meta.dir, "../scripts/browser-input-closure.ts"))};\n`); - f.write("scripts/unit-test-consumers.ts", `export * from ${JSON.stringify(resolve(import.meta.dir, "../scripts/unit-test-consumers.ts"))};\n`); - for (const name of ["integration-reservation", "red-main"]) f.write(`scripts/${name}.ts`, `export * from ${JSON.stringify(resolve(import.meta.dir, `../scripts/${name}.ts`))};\n`); - f.write("packages/core/src/note.ts", "export const note = 2;\n"); - f.git("add", "."); f.git("commit", "-qm", "planner fixture"); + const f = plannerFixture(); for (const draft of ["true", "false"]) { const output = join(f.dir, `outputs-${draft}`); const plan = join(f.dir, `plan-${draft}.json`); const eventPath = join(f.dir, "event.json"); @@ -225,7 +245,7 @@ describe("affected CI checks", () => { const [code, err] = await Promise.all([child.exited, new Response(child.stderr).text()]); expect(code, err).toBe(0); const expected = proofSelections(JSON.parse(readFileSync(plan, "utf8")), draft === "true"); - expect(readFileSync(output, "utf8")).toBe(`unit_shards=[1,2,3,4]\ncadence=${draft === "true" ? "draft" : "confirmation"}\nred_main_oid=\n` + Object.entries(expected).map(([name, value]) => `${name}=${value}\n`).join("")); + expect(readFileSync(output, "utf8")).toBe(`unit_shards=${draft === "true" ? "[1,2,3,4]" : "[1,2,3,4,5,6,7,8]"}\ncadence=${draft === "true" ? "draft" : "confirmation"}\nred_main_oid=\n` + Object.entries(expected).map(([name, value]) => `${name}=${value}\n`).join("")); expect(expected.unit).toBe(draft === "false"); // Ready confirmation leaves heavy runtime proof to the squash's main run (hybrid ruling). expect(expected.runtime, "CONFIRMATION_DEFERS_RUNTIME").toBe(false); @@ -233,6 +253,29 @@ describe("affected CI checks", () => { } }); + test("the executable plans eight unit partitions for ready confirmation and draft heavy feedback, four for main and exhaustive runs (#4108)", async () => { + const f = plannerFixture(); + for (const [label, name, event, extra, cadence, shards] of [ + ["ready confirmation", "pull_request", { action: "ready_for_review", pull_request: { draft: false } }, { BASE_SHA: f.base }, "confirmation", "[1,2,3,4,5,6,7,8]"], + ["draft heavy feedback", "workflow_dispatch", { inputs: { pr: "7", head_sha: "a".repeat(40) } }, { BASE_SHA: f.base, FEEDBACK_PR: "7" }, "feedback-heavy", "[1,2,3,4,5,6,7,8]"], + ["main push", "push", { before: f.base }, { BEFORE_SHA: f.base, RED_MAIN_OID: "none" }, "integrated", "[1,2,3,4]"], + ["manual exhaustive run", "workflow_dispatch", { inputs: null }, {}, "exhaustive", "[1,2,3,4]"], + ["scheduled exhaustive run", "schedule", { schedule: "17 3 * * *" }, {}, "exhaustive", "[1,2,3,4]"], + ] as const) { + const output = join(f.dir, `outputs-${label}`), eventPath = join(f.dir, "event.json"); + writeFileSync(eventPath, JSON.stringify(event)); + const child = Bun.spawn([process.execPath, join(f.dir, "scripts/ci-plan.ts")], { cwd: f.dir, stdout: "pipe", stderr: "pipe", + env: { ...process.env, BASE_SHA: "", BEFORE_SHA: "", FEEDBACK_PR: "", RED_MAIN_OID: "", PR_DRAFT: "", ...extra, GITHUB_EVENT_NAME: name, + HEAD_SHA: "HEAD", GITHUB_EVENT_PATH: eventPath, GITHUB_OUTPUT: output, CI_PLAN_PATH: join(f.dir, `plan-${label}.json`) } }); + const [code, err] = await Promise.all([child.exited, new Response(child.stderr).text()]); + expect(code, `${label}: ${err}`).toBe(0); + const outputs = Object.fromEntries(readFileSync(output, "utf8").trim().split("\n").map(line => line.split("="))); + expect(outputs.cadence, label).toBe(cadence); + expect(outputs.unit, `UNIT_SELECTED: ${label}`).toBe("true"); + expect(outputs.unit_shards, `PARTITIONS: ${label}`).toBe(shards); + } + }); + test("every curated test exists and no browser/endurance filename joins implicitly", () => { const root = resolve(import.meta.dir, ".."); const files = [...Object.values(FAST_TESTS).flat(), ...Object.keys(FILE_INPUT_TESTS)]; expect(files.length).toBeGreaterThan(20); @@ -507,3 +550,30 @@ describe("main aggregate re-plans with the metadata job's red-main set (#3541)", expect(() => validateSelections(f.dir, event, env, withoutSnapshot, () => record)).toThrow("missing its red-main coordination snapshot"); }); }); + +describe("hosted aggregate binds the published unit partitions to the plan (#4108)", () => { + test("a confirmation whose unit partition set is not exactly the planned one is refused", async () => { + const { validateSelections } = await import("../scripts/candidate-proof"); + const f = fixture(); f.write("packages/core/src/note.ts", "export const note = 2;\n"); f.git("add", "."); f.git("commit", "-qm", "core change"); + const head = f.git("rev-parse", "HEAD"); + const published = (cadence: "confirmation" | "integrated", env: Record, shards: string | undefined) => { + const plan = planFromEnvironment(f.dir, env); plan.cadence = cadence; + const selections = proofSelections(plan); + expect(selections.unit, "UNIT_SELECTED").toBe(true); + return { cadence, red_main_oid: "a".repeat(40), ...Object.fromEntries(Object.entries(selections).map(([k, v]) => [k, String(v)])), + ...(shards === undefined ? {} : { unit_shards: shards }) }; + }; + const refusal = "unit: published partition set differs from the planned one"; + const confirmation = { GITHUB_EVENT_NAME: "pull_request", GITHUB_SHA: head, BASE_SHA: f.base, HEAD_SHA: head }; + const ready = { action: "ready_for_review", pull_request: { draft: false, base: { sha: f.base }, head: { sha: head } } }; + expect(() => validateSelections(f.dir, ready, confirmation, published("confirmation", confirmation, "[1,2,3,4,5,6,7,8]")), "PLANNED_EIGHT").not.toThrow(); + for (const [label, shards] of [["DROPPED_PARTITION", "[1,2,3,4,5,6,7]"], ["MAIN_COUNT", "[1,2,3,4]"], ["EXTRA_PARTITION", "[1,2,3,4,5,6,7,8,9]"], + ["REORDERED", "[2,1,3,4,5,6,7,8]"], ["MISSING_OUTPUT", undefined]] as const) { + expect(() => validateSelections(f.dir, ready, confirmation, published("confirmation", confirmation, shards)), label).toThrow(refusal); + } + // A main push of the same change plans four; eight published there is refused too. + const push = { GITHUB_EVENT_NAME: "push", GITHUB_SHA: head, BEFORE_SHA: f.base, HEAD_SHA: head }, pushed = { before: f.base }; + expect(() => validateSelections(f.dir, pushed, push, published("integrated", push, "[1,2,3,4]"), () => null), "MAIN_KEEPS_FOUR").not.toThrow(); + expect(() => validateSelections(f.dir, pushed, push, published("integrated", push, "[1,2,3,4,5,6,7,8]"), () => null), "MAIN_REFUSES_EIGHT").toThrow(refusal); + }); +}); diff --git a/tests/ci-workflows.test.ts b/tests/ci-workflows.test.ts index 5cad2fc6e9..42b7ebeb90 100644 --- a/tests/ci-workflows.test.ts +++ b/tests/ci-workflows.test.ts @@ -552,6 +552,23 @@ test("small exact inventories wire bounded planner partitions into actual unit e expect(step.run).toBe('bun scripts/ci-proof.ts unit --shard=${{ matrix.shard }}/"$UNIT_SHARDS"'); }); +test("a unit matrix or divisor that disagrees with the planner's partition set is refused (#4108)", () => { + const text = read("ci.yml"), problem = "unit: matrix and shard divisor must come from the planner's unit_shards output"; + expect(workflowProblems(text, "ci.yml")).toEqual([]); + const matrix = " shard: ${{ fromJSON(needs.changeset.outputs.unit_shards) }}\n"; + for (const [label, from, to] of [ + ["LITERAL_FOUR_MATRIX", matrix, " shard: [1, 2, 3, 4]\n"], + ["LITERAL_EIGHT_MATRIX", matrix, " shard: [1, 2, 3, 4, 5, 6, 7, 8]\n"], + ["SECOND_MATRIX_DIMENSION", matrix, matrix + " worker: [1, 2]\n"], + ["LITERAL_DIVISOR", 'unit --shard=${{ matrix.shard }}/"$UNIT_SHARDS"', "unit --shard=${{ matrix.shard }}/4"], + ["LITERAL_DIVISOR_VALUE", "UNIT_SHARDS: ${{ strategy.job-total }}", "UNIT_SHARDS: 4"], + ["OUTPUT_NOT_FROM_PLANNER", "unit_shards: ${{ steps.plan.outputs.unit_shards }}", 'unit_shards: "[1,2,3,4]"'], + ] as const) { + expect(text.split(from), `ONE_SITE: ${label}`).toHaveLength(2); + expect(workflowProblems(text.replace(from, to), "ci.yml"), label).toContain(`ci.yml: ${problem}`); + } +}); + test("all unit partitions upload incremental memory diagnostics even after proof failure", () => { const upload = ci.jobs.unit!.steps.find(s => s.uses === "actions/upload-artifact@v7")!; expect(upload.if).toBe("always()"); diff --git a/tests/hosted-proof.test.ts b/tests/hosted-proof.test.ts index 1ba0d23b20..d75155b0f4 100644 --- a/tests/hosted-proof.test.ts +++ b/tests/hosted-proof.test.ts @@ -3,7 +3,7 @@ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join, resolve } from "node:path"; import { categoryCommands, proofProblems, PROOF_JOBS, unitFiles } from "../scripts/ci-proof"; -import { planChecks, proofSelections, workspaces, type Workspace } from "../scripts/ci-plan"; +import { planChecks, proofSelections, unitShards, workspaces, type ProofCadence, type Workspace } from "../scripts/ci-plan"; import { discoverTests } from "../scripts/test-shards"; import { localChecks } from "../scripts/check-pr"; import { checkout } from "../scripts/proof-inputs"; @@ -109,6 +109,30 @@ test("affected complete discovery admits new files and reverse dependencies with expect(() => unitFiles(plan, dir, "3/2")).toThrow("Invalid proof shard"); }); +test("eight confirmation partitions run the files four main partitions run, each exactly once (#4108)", () => { + const complete = planChecks(["package.json"], workspaces(ROOT)); + // Each hosted partition calls unitFiles with its own number over the matrix size. + const partitions = (cadence: ProofCadence, plan = complete) => { + const shards = unitShards({ ...plan, cadence }); + return shards.map(shard => unitFiles({ ...plan, cadence }, ROOT, `${shard}/${shards.length}`)); + }; + const discovered = discoverTests(ROOT, ["packages", "tests"]); + expect(discovered.length).toBeGreaterThan(100); + for (const [cadence, count] of [["confirmation", 8], ["feedback-heavy", 8], ["integrated", 4], ["exhaustive", 4]] as const) { + const sets = partitions(cadence); + expect(sets, `PARTITION_COUNT: ${cadence}`).toHaveLength(count); + expect(sets.every(files => files.length > 0), `NONEMPTY: ${cadence}`).toBe(true); + // Sorted equality with the duplicate-free discovery refuses an omitted, repeated or foreign file. + expect(sets.flat().sort(), `EXACTLY_ONCE: ${cadence}`).toEqual([...discovered].sort()); + } + // A selected inventory smaller than the cap gets one nonempty partition per file. + const narrow = { ...planChecks(["packages/core/src/index.ts"], workspaces(ROOT)), unitTests: discovered.slice(0, 5) }; + expect(narrow.global).toBe(false); + const few = partitions("confirmation", narrow); + expect(few.map(files => files.length), "ONE_FILE_PER_PARTITION").toEqual([1, 1, 1, 1, 1]); + expect(few.flat().sort()).toEqual(discovered.slice(0, 5).sort()); +}); + test("hosted global commands retain the full local inventory and real offline namespaces", () => { const plan = planChecks(["package.json"], workspaces(ROOT)); const selections = proofSelections(plan); diff --git a/tests/integration-proof.test.ts b/tests/integration-proof.test.ts index 236f23f13f..61d25df3d7 100644 --- a/tests/integration-proof.test.ts +++ b/tests/integration-proof.test.ts @@ -124,3 +124,55 @@ for (const [label, malformed] of [ expect(message).not.toContain("Bearer"); expect(message.length).toBeLessThan(1800); }); + +/** A ready confirmation as the merge path reads it: the aggregate's receipts plus the run's actual job inventory. */ +async function confirmationOutcome(published: unknown, ran: readonly number[]): Promise { + const categories = ["verify", "pack", "unit", "browser", "layout", "captures", "runtime", "runtime_host", "endurance"]; + const fast = (name: string) => ["verify", "pack", "unit"].includes(name); + const checkout = { sha: "d".repeat(40), tree: "e".repeat(40), parents: [candidate.base, candidate.head] }; + const selected = { selections: Object.fromEntries(categories.map(name => [name, String(fast(name))])), + results: Object.fromEntries(categories.map(name => [name, fast(name) ? "success" : "skipped"])), retained: [], + unitShards: typeof published === "string" || published === null ? published : JSON.stringify(published) }; + let id = 100; + const entry = (name: string, conclusion = "success") => ({ ...job, id: id++, name, conclusion }); + const jobs = [entry("changeset"), entry("proof"), ...categories.flatMap(name => name === "unit" ? ran.map(shard => entry(`unit (${shard})`)) + : [entry(name, fast(name) ? "success" : "skipped")])]; + const actual = `[command]/usr/bin/git log -1 --format=%H\n2026-07-12T00:00:00Z ${checkout.sha}\n`; + const proofLog = actual + `BRAIN_CANDIDATE_RECEIPT ${JSON.stringify({ event: "ready_for_review", head: candidate.head, base: candidate.base, checkout })}\n` + + `BRAIN_SELECTED_PROOF_RECEIPT ${JSON.stringify(selected)}\nAll selected hosted proof passed; remaining skips are planner-intended.\n`; + const api: API = { + async json(path) { + if (path === "actions/runs/17/attempts/2/jobs?per_page=100") return { total_count: jobs.length, jobs }; + return { workflow_runs: [{ id: 17, run_attempt: 2, event: "pull_request", head_sha: candidate.head, + repository: { html_url: candidate.repository }, head_repository: { html_url: candidate.repository }, + pull_requests: [{ number: candidate.pr }], status: "completed", conclusion: "success" }] }; + }, + async log(jobId) { return jobId === jobs[1]!.id ? proofLog : actual; }, + }; + // Reaching the checkout fetch means the inventory, partition and per-job checkout guards all accepted the run. + try { await verifyIntegrationProof("unused", "odysseus/brain-kit", candidate, api, sha => { throw new Error(`ACCEPTED_INVENTORY ${sha}`); }); } + catch (error) { return (error as Error).message; } + return "verified without fetching the checkout"; +} + +test("the merge path accepts a confirmation only with exactly its planned unit partitions (#4108)", async () => { + const eight = [1, 2, 3, 4, 5, 6, 7, 8], accepted = `ACCEPTED_INVENTORY ${"d".repeat(40)}`; + const differs = "Actual selected job inventory differs from the validated selection", identity = "Missing actual unit partition identity"; + expect(await confirmationOutcome(eight, eight), "EIGHT_PLANNED_EIGHT_RAN").toBe(accepted); + // A narrow inventory plans fewer partitions; the same exactness holds. + expect(await confirmationOutcome([1, 2, 3], [1, 2, 3]), "THREE_PLANNED_THREE_RAN").toBe(accepted); + expect(await confirmationOutcome(eight, eight.slice(0, 7)), "DROPPED_LAST_PARTITION").toBe(differs); + expect(await confirmationOutcome(eight, [1, 2, 3, 5, 6, 7, 8]), "DROPPED_MIDDLE_PARTITION").toBe(differs); + expect(await confirmationOutcome(eight, [...eight, 8]), "DUPLICATE_PARTITION").toBe(differs); + expect(await confirmationOutcome(eight.slice(0, 4), eight), "RAN_MORE_THAN_PLANNED").toBe(differs); + expect(await confirmationOutcome([...eight, 9], [...eight, 9]), "ABOVE_CONFIRMATION_CAP").toBe(identity); + expect(await confirmationOutcome([1, 2, 4, 3, 5, 6, 7, 8], eight), "REORDERED_PLAN").toBe(identity); + expect(await confirmationOutcome([2, 3, 4, 5, 6, 7, 8], [2, 3, 4, 5, 6, 7, 8]), "PLAN_WITHOUT_FIRST").toBe(identity); + expect(await confirmationOutcome([], []), "EMPTY_PLAN").toBe(identity); + expect(await confirmationOutcome(null, eight), "MISSING_PLAN").toBe(identity); +}); + +test("refusal diagnostics name every partition a confirmation can plan", async () => { + const message = await refusal({ total_count: 2, jobs: [job, { ...job, id: 20, name: "unit (8)", status: "queued" }] }); + expect(JSON.parse(message.split("inventory: ")[1]!).offending[0].job.name).toBe("unit (8)"); +}); diff --git a/tests/refresh-unit-costs.test.ts b/tests/refresh-unit-costs.test.ts index e366a52c99..a0a876fc56 100644 --- a/tests/refresh-unit-costs.test.ts +++ b/tests/refresh-unit-costs.test.ts @@ -1,18 +1,18 @@ import { expect, test } from "bun:test"; import { assertWeightedLongFiles, refreshUnitCosts, type UnitEvidenceAPI } from "../scripts/refresh-unit-costs"; const sha = "a".repeat(40), tree = "b".repeat(40), parent = "c".repeat(40), digest = `sha256:${"d".repeat(64)}`; -function fixture() { - const run = { id: 42, run_attempt: 1, status: "completed", conclusion: "success", path: ".github/workflows/ci.yml", event: "push", head_sha: sha, repository: { full_name: "schlessera/brain-kit" } }; - const jobs = [1, 2, 3, 4].map(id => ({ id, run_id: 42, head_sha: sha, name: `unit (${id})`, started_at: "2026-07-12T00:00:00Z", completed_at: "2026-07-12T00:03:00Z", status: "completed", conclusion: "success", steps: [{ name: "Complete unit proof", status: "completed", conclusion: "success", started_at: "2026-07-12T00:00:00Z", completed_at: "2026-07-12T00:02:00Z" }] })); +function fixture(event = "push", partitions = 4) { + const run = { id: 42, run_attempt: 1, status: "completed", conclusion: "success", path: ".github/workflows/ci.yml", event, head_sha: sha, repository: { full_name: "schlessera/brain-kit" } }; + const jobs = Array.from({ length: partitions }, (_, index) => index + 1).map(id => ({ id, run_id: 42, head_sha: sha, name: `unit (${id})`, started_at: "2026-07-12T00:00:00Z", completed_at: "2026-07-12T00:03:00Z", status: "completed", conclusion: "success", steps: [{ name: "Complete unit proof", status: "completed", conclusion: "success", started_at: "2026-07-12T00:00:00Z", completed_at: "2026-07-12T00:02:00Z" }] })); const artifacts = jobs.map(j => ({ id: j.id, name: `unit-proof-${j.id}`, expired: false, created_at: "2026-07-12T00:02:01Z", digest, workflow_run: { id: 42, head_sha: sha } })); const files = jobs.map(j => `tests/odysseus-${j.id}.test.ts`); const archives = jobs.map((j, i) => ({ digest, files: { - "proof-checkout.json": JSON.stringify({ category: "unit", shard: `${j.id}/4`, checkout: { sha, tree, parents: [parent] }, plan: { global: true, local: { fullTests: true } }, files: [files[i]] }), + "proof-checkout.json": JSON.stringify({ category: "unit", shard: `${j.id}/${partitions}`, checkout: { sha, tree, parents: event === "pull_request" ? [parent, sha] : [parent] }, plan: { global: true, local: { fullTests: true } }, files: [files[i]] }), "unit-timings.json": JSON.stringify({ version: 1, files: { [files[i]!]: j.id * 1000 } }), "unit-report.xml": ``, } })); const logs = jobs.map(() => `2026-07-12T00:00:00Z [command]/usr/bin/git log -1 --format=%H\n2026-07-12T00:00:00Z ${sha}\n`); - const commit = { sha, tree: { sha: tree }, parents: [{ sha: parent }] }; + const commit = { sha, tree: { sha: tree }, parents: event === "pull_request" ? [{ sha: parent }, { sha }] : [{ sha: parent }] }; const source = { sha: tree, truncated: false, tree: files.map(path => ({ path, type: "blob" })) }; const api: UnitEvidenceAPI = { json: async path => { if (path === "actions/runs/42/attempts/1") return run; @@ -55,6 +55,15 @@ for (const [name, corrupt] of [ ] satisfies [string, (f: ReturnType) => void][]) test(`unit refresh rejects ${name}`, async () => { const f = fixture(); corrupt(f); await expect(f.refresh()).rejects.toThrow(); }); +test("a ready confirmation refreshes from its eight partitions and a main run from its four (#4108)", async () => { + const confirmation = await fixture("pull_request", 8).refresh(); + expect(confirmation.measurement.jobs.map(j => j.shard)).toEqual([1, 2, 3, 4, 5, 6, 7, 8]); + expect(Object.keys(confirmation.seconds)).toHaveLength(8); + for (const event of ["push", "schedule", "workflow_dispatch"]) expect((await fixture(event, 4).refresh()).measurement.jobs).toHaveLength(4); + // The count is the cadence's cap, never whatever the run happens to contain. + await expect(fixture("pull_request", 4).refresh(), "CONFIRMATION_WITH_MAIN_COUNT").rejects.toThrow("Exactly 8 fresh successful unit jobs required"); + await expect(fixture("push", 8).refresh(), "MAIN_WITH_CONFIRMATION_COUNT").rejects.toThrow("Exactly 4 fresh successful unit jobs required"); +}); test("missing-weight guard names the unweighted 120 second file and passes after weighting", () => { const file = "tests/odysseus-long.test.ts", observations = { [file]: 120000 }; expect(() => assertWeightedLongFiles(observations, {})).toThrow(`Missing unit weight above 30s: ${file}`); From fdbb8f0a4bf7931db526d2214d21fc628bbf60d6 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 17 Nov 2026 00:03:40 +0000 Subject: [PATCH 04/31] docs(ci): record the eight-partition ruling for ready confirmation (#4108) Co-Authored-By: Claude Fable 5.2 --- docs/decisions/ci-utility.md | 68 ++++++++++++++++++++++++++++++++--- docs/decisions/test-health.md | 2 +- docs/process/ci-throughput.md | 8 +++++ docs/process/ci-timings.md | 3 +- docs/process/testing.md | 9 +++++ 5 files changed, 84 insertions(+), 6 deletions(-) diff --git a/docs/decisions/ci-utility.md b/docs/decisions/ci-utility.md index 530166972e..a6f2837a0c 100644 --- a/docs/decisions/ci-utility.md +++ b/docs/decisions/ci-utility.md @@ -509,7 +509,9 @@ one PR share a cancellable group. Different PRs never cancel one another. After cheap gates, packaging, strict verification, unit shards, runtime probes, browser shards, layout shards, a separate endurance job and captures start independently. -There are four measured-cost unit partitions, three browser and two layout partitions +There are four measured-cost unit partitions +([eight on ready confirmation and draft heavy feedback](#eight-unit-partitions-for-ready-confirmation)), +three browser and two layout partitions (`PROOF_SHARDS`, `scripts/proof-shards.ts`, which the workflow guard matches against the matrices), with full coverage assertions and original per-browser file concurrency bounds. The first two-unit-partition hosted run reached its 20-minute budgets while @@ -849,8 +851,9 @@ unavailable; process maximum RSS does not establish aggregate headroom. The measurement workflow remains an evidence vehicle and is not merged. Unit weights have the same explicit reviewed path: -`bun scripts/refresh-unit-costs.ts `. It requires all four -successful exhaustive unit jobs and binds actual checkout logs, immutable +`bun scripts/refresh-unit-costs.ts `. It requires every planned +partition of an exhaustive run as a successful unit job (four, or eight on a +ready confirmation) and binds actual checkout logs, immutable source discovery, complete JUnit/timing partitions and downloaded archive digests. `scripts/unit-shard-measurement.json` records that provenance; the refresh names any observed unweighted file exceeding 30 seconds. Timings @@ -1868,6 +1871,62 @@ pre-merge confirmation if any of these holds: - unresolved first-main failures grow by more than ten in the week; - red main blocks a release for more than 24 hours. +## Eight unit partitions for ready confirmation + +Maintainer decision, 2026-11-16 +([#4108](https://github.com/schlessera/brain-kit/issues/4108)): shorten the +merge lease hold by running ready confirmation's unit tier in more partitions. +Proof content does not change. + +- **Ready confirmation and draft heavy feedback** run the unit tier in up to + eight partitions. **Main pushes and exhaustive runs** keep four, so a main + run needs no more runners than before. +- **One owner.** One table holds both caps (`UNIT_PARTITIONS`, + `scripts/proof-shards.ts:17`). The planner reads it by cadence (`unitShards`, + `scripts/ci-plan.ts:395-397`) and publishes the partition numbers as + `unit_shards`. The `unit` matrix is that output, and each partition's divisor + is the matrix size. The hosted aggregate plans again and refuses a published + set that differs from the plan (`selections.unit`, + `scripts/candidate-proof.ts:68`). The merge path accepts only a job inventory + that matches the confirmed set, bounded by the confirmation cap + (`unitPartitionLimit("confirmation")`, `scripts/integration-proof.ts:125-126`). + `bun run lint` refuses a literal matrix, a second matrix dimension or a + literal divisor (`The unit partition count has one owner`, + `scripts/check-ci-workflows.ts:97-105`). The weight refresh takes its job + count from the same table. +- **Fewer files than partitions.** A selected inventory smaller than the cap + gets one partition per file. No partition is empty and no file runs twice + (`unitPartitions`, `scripts/proof-shards.ts:28-32`). + +**Why.** One repository-wide lease serializes ready confirmation and merge. +#4108 records that on 2026-11-16 the lease was acquired 53 times and held for +75% of the day, with a median hold of 26 minutes. That hold is the `unit` job: +over the 100 most recent successful PR runs it took a median 19.1 minutes (p90 +23.8), against 2.6 for `pack` and 1.9 for `verify`. The +[hybrid ruling](#hybrid-post-merge-heavy-proof) moved the browser categories +after merge and did not shorten the hold. + +**Four-partition baseline.** In run 43974750583 the four `Complete unit proof` +steps took 857, 862, 1,027 and 1,334 seconds, after 43 to 160 seconds of +runtime setup. The slowest `unit` job took 1,433 seconds. The reviewed weights +in `scripts/test-shard-costs.json` balance to an estimated 1,098 seconds per +partition at four and 549 at eight, and the largest single file is 350 +seconds. The estimate uses weights measured under four partitions. It is not +a measurement of eight. + +**What does not change.** Every selected file still runs exactly once. The +two-process queue inside a partition, the 12-minute setup, 30-minute proof and +45-minute job limits, every per-test deadline, the browser and layout shard +counts and the weight table are unchanged. No test leaves the pre-merge unit +tier. + +**Known costs.** A confirmation uses eight unit runners instead of four, and +each pays its own checkout, install and runtime setup. Summed runner time per +confirmation rises while the slowest job shortens. A confirmation lists up to +18 jobs, under the merge path's 30-job inventory bound. The weights were +measured at four partitions, so the balance at eight may be uneven; a weight +refresh is separate work. + ## Fast lane outside the core packages The maintainer ruled on 2026-11-16 that the fast lane allowed on 2026-11-03 @@ -1969,7 +2028,8 @@ or deleted tests, unknown inputs and unavailable scans retain ordinary selection Main pushes and exhaustive runs retain complete affected/default discovery. The exact unit inventory is validated against default Bun discovery. It includes -owning fast tests once, and uses at most the existing four partitions, reduced +owning fast tests once, and uses at most its cadence's partition cap (four, or +eight on ready confirmation and draft heavy feedback), reduced only when fewer files exist; no empty partition or duplicate execution substitutes for coverage. Selected categories remain required by the unchanged aggregate. diff --git a/docs/decisions/test-health.md b/docs/decisions/test-health.md index 16267cfc63..0b6d19bb7d 100644 --- a/docs/decisions/test-health.md +++ b/docs/decisions/test-health.md @@ -39,7 +39,7 @@ follows is in [ci-utility.md](ci-utility.md) and enumerated fields. - **A batch stays inside one group and lands as one pull request.** Hosted proof for a test edit is priced by the workspaces it touches, not by the - number of files (`const packageCode`, `scripts/ci-plan.ts:355-356`): any path + number of files (`const packageCode`, `scripts/ci-plan.ts:356-357`): any path under a package's `tests/` selects that package and its reverse dependants. One changed test in a package costs the same confirmation as thirty, so small pull requests are the most expensive way to land this work. A large diff --git a/docs/process/ci-throughput.md b/docs/process/ci-throughput.md index dd1d0a6368..d302c4d325 100644 --- a/docs/process/ci-throughput.md +++ b/docs/process/ci-throughput.md @@ -81,6 +81,14 @@ candidates as well as actual defects. Mixed policy epochs, sizes, dependency graphs and runners confound comparisons; the report includes changed-line cohorts and proof-policy epochs but does not establish causality. +A ready confirmation runs its unit tier in up to eight partitions and a main +push in up to four +([ruling](../decisions/ci-utility.md#eight-unit-partitions-for-ready-confirmation)). +Per-job `unit` durations, job counts and runner-minutes therefore differ +between the `pull_request_ready` and `push_main` cohorts by design, and +between epochs on either side of that change. Compare the slowest `unit` job +of a run, or the reservation hold, not the per-job median. + ## Proof-policy epochs Each merged proof-system change opens a new proof-policy epoch diff --git a/docs/process/ci-timings.md b/docs/process/ci-timings.md index 6c59997057..0aef0a4d0a 100644 --- a/docs/process/ci-timings.md +++ b/docs/process/ci-timings.md @@ -173,7 +173,8 @@ bun scripts/refresh-unit-costs.ts It writes `scripts/test-shard-costs.json` in seconds and `scripts/unit-shard-measurement.json` with the run, attempt, actual checkout, immutable tree/parents, job/step durations, artifact IDs and archive digests. -The command requires four successful unit jobs, one attributed archive per +The command requires every planned partition as a successful unit job (four, +or eight for a ready confirmation), one attributed archive per shard, complete matching JUnit/timing partitions, and exact source-discovery coverage. Failed, cancelled, partial or ambiguously attributed evidence is refused. A successful workflow summary alone does not qualify a run; duplicate diff --git a/docs/process/testing.md b/docs/process/testing.md index bf7d70c538..10febc2d78 100644 --- a/docs/process/testing.md +++ b/docs/process/testing.md @@ -730,6 +730,15 @@ after successful setup belongs to the proof phase. Both leave the job and selected aggregate nonpassing. Browser/layout do not call this setup script and retain their existing pinned-container proof budgets. +The unit tier runs in up to eight partitions on a ready confirmation and on +draft heavy feedback, and in up to four on main pushes and exhaustive runs. +A selected inventory with fewer files than the cap gets one partition per +file. `UNIT_PARTITIONS` in `scripts/proof-shards.ts` is the only place the +counts are written: the planner publishes the partition numbers, the `unit` +matrix and its divisor follow that output, and the aggregate and the merge +path refuse a run whose unit jobs are not exactly the planned set +([ruling](../decisions/ci-utility.md#eight-unit-partitions-for-ready-confirmation)). + Hosted unit partitions run up to two serial Bun test processes through `scripts/unit-workers.ts`. Each owns its source checkout, copied frozen install, build output and workspace lease. Full preparation now runs after From e5a1e4a39838f0d6151744900a5199744b5d0d3e Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 17 Nov 2026 00:08:58 +0000 Subject: [PATCH 05/31] chore(ci): add the review record and the core-package path predicate (#4110) scripts/review-receipt.ts writes, posts and reads the record of an independent review: one PR comment in a fixed block naming the reviewed head, the base, the reviewer as agent or human only, and each finding with exactly one disposition. It decides whether a record covers a candidate head from real Git ancestry: merges of the base keep it valid; a new commit, a rebase or an amend does not. scripts/fast-lane.ts is the single owner of the core-package path rule that the fast lane and the review requirement share. Co-Authored-By: Claude Fable 5.2 --- scripts/fast-lane.ts | 28 ++++ scripts/review-receipt.ts | 266 +++++++++++++++++++++++++++++++++ tests/review-receipt.test.ts | 278 +++++++++++++++++++++++++++++++++++ 3 files changed, 572 insertions(+) create mode 100644 scripts/fast-lane.ts create mode 100644 scripts/review-receipt.ts create mode 100644 tests/review-receipt.test.ts diff --git a/scripts/fast-lane.ts b/scripts/fast-lane.ts new file mode 100644 index 0000000000..b802d327e3 --- /dev/null +++ b/scripts/fast-lane.ts @@ -0,0 +1,28 @@ +/** + * The one definition of the core packages (#4110). A pull request whose diff + * touches none of them may take the fast lane; one that touches any of them + * keeps ready confirmation and needs a recorded independent review + * (`scripts/review-receipt.ts`). Both rules read this predicate, so the two + * lanes cannot drift apart. + * + * gh pr diff --name-only | bun scripts/fast-lane.ts + * + * prints one line of JSON: the lane and the core-package paths that decided it. + */ +export const CORE_PACKAGES = ["ui-react", "ui-kit", "ui-server", "core"] as const; + +export function isCorePackagePath(path: string): boolean { + return CORE_PACKAGES.some(name => path.startsWith(`packages/${name}/`)); +} + +/** True when any changed path lies under a core package: the full lane. */ +export function touchesCorePackages(paths: readonly string[]): boolean { + return paths.some(isCorePackagePath); +} + +if (import.meta.main) { + const paths = (await Bun.stdin.text()).split("\n").map(line => line.trim()).filter(Boolean); + if (!paths.length) { console.error("usage: gh pr diff --name-only | bun scripts/fast-lane.ts (no changed paths were read)"); process.exit(2); } + const corePaths = paths.filter(isCorePackagePath); + console.log(JSON.stringify({ lane: corePaths.length ? "full" : "fast", paths: paths.length, corePaths })); +} diff --git a/scripts/review-receipt.ts b/scripts/review-receipt.ts new file mode 100644 index 0000000000..bcb70a808f --- /dev/null +++ b/scripts/review-receipt.ts @@ -0,0 +1,266 @@ +/** + * The machine-readable record of an independent review (#4110). A pull request + * whose diff touches the core packages (`scripts/fast-lane.ts`) carries it as + * one comment, and `scripts/integrate.ts` refuses to confirm or merge such a + * candidate without a record that covers its head. + * + * bun scripts/review-receipt.ts post --reviewer agent|human --head + * (--no-findings | --findings ) [--base ] [--dry-run] + * bun scripts/review-receipt.ts check + * + * `post` writes the record and posts it; `--findings` names a JSON array of + * `{ "summary": "..." }` entries, each answered with exactly one disposition: + * `"disposition": "fixed"` with `"commit"`, `"filed"` with `"issue"` + * (`owner/repo#N`) or `"rejected"` with `"reason"`. `check` prints the merge + * path's decision for the pull request's live head without changing anything. + * The record names the reviewer only as `agent` or `human`. + */ +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { scanText } from "./check-leakage"; +import { CORE_PACKAGES, touchesCorePackages } from "./fast-lane"; +import { DEFAULT_REPO, type Gh } from "./issue-queue"; + +export const REVIEW_KIND = "brain-review-receipt"; +export const REVIEW_START = ""; +export const REVIEW_END = ""; +export const REVIEWERS = ["agent", "human"] as const; +export type Reviewer = typeof REVIEWERS[number]; + +export type ReviewFinding = + | { summary: string } + | { summary: string; disposition: "fixed"; commit: string } + | { summary: string; disposition: "filed"; issue: string } + | { summary: string; disposition: "rejected"; reason: string }; +export interface ReviewRecord { + version: 1; kind: typeof REVIEW_KIND; pr: number; head: string; base: string; reviewer: Reviewer; + outcome: "no-findings" | "findings"; findings: ReviewFinding[]; +} +/** The exact candidate the merge path is deciding: its PR, head and live base. */ +export interface ReviewCandidate { pr: number; head: string; base: string } + +const SHA = /^[a-f0-9]{40}$/; +const ISSUE = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+#[1-9]\d*$/; +const RECORD_KEYS = ["version", "kind", "pr", "head", "base", "reviewer", "outcome", "findings"]; +/** The second key each disposition requires, beside `summary` and `disposition`. */ +const DETAIL = { fixed: "commit", filed: "issue", rejected: "reason" } as const; + +/** Exactly these keys: an unknown field (a reviewer's name, a model, a session) refuses. */ +const exact = (value: object, keys: readonly string[]) => Object.keys(value).length === keys.length && keys.every(key => Object.hasOwn(value, key)); +const sha = (value: unknown): value is string => typeof value === "string" && SHA.test(value); +/** One line of prose: no line breaks or control characters, at most 500 characters. */ +const prose = (value: unknown): value is string => typeof value === "string" && value.trim().length > 0 && value.length <= 500 && !/[\u0000-\u001f\u007f]/.test(value); + +function parseFinding(value: unknown): ReviewFinding { + const finding = value as Record; + if (!finding || typeof finding !== "object" || Array.isArray(finding) || !prose(finding.summary)) throw new Error("Invalid review finding"); + if (exact(finding, ["summary"])) return finding as ReviewFinding; + const detail = Object.hasOwn(DETAIL, String(finding.disposition)) ? DETAIL[finding.disposition as keyof typeof DETAIL] : undefined; + if (!detail || !exact(finding, ["summary", "disposition", detail])) throw new Error("Invalid review finding: a disposition is fixed with a commit, filed with an issue or rejected with a reason, and nothing else"); + const answer = finding[detail]; + if (detail === "commit" ? !sha(answer) : detail === "issue" ? !(typeof answer === "string" && ISSUE.test(answer)) : !prose(answer)) throw new Error(`Invalid review finding ${detail}`); + return finding as ReviewFinding; +} + +export function parseReview(value: unknown): ReviewRecord { + const r = value as ReviewRecord; + if (!r || typeof r !== "object" || Array.isArray(r) || !exact(r, RECORD_KEYS) || r.version !== 1 || r.kind !== REVIEW_KIND || + !Number.isSafeInteger(r.pr) || r.pr < 1 || !sha(r.head) || !sha(r.base) || !REVIEWERS.includes(r.reviewer) || + !Array.isArray(r.findings) || r.findings.length > 100) throw new Error("Invalid review record"); + // A review with no findings says so; an empty list never stands in for it. + if (r.outcome !== (r.findings.length ? "findings" : "no-findings")) throw new Error("Invalid review record: the outcome is no-findings exactly when the findings list is empty"); + r.findings.forEach(parseFinding); + return r; +} + +export const undisposed = (record: ReviewRecord) => record.findings.filter(finding => !("disposition" in finding)); + +/** The fixed block the comment carries; the merge path reads nothing else. */ +export function reviewBlock(record: ReviewRecord): string { + return [REVIEW_START, "```json", JSON.stringify(record), "```", REVIEW_END].join("\n"); +} + +/** The whole comment: the same facts as prose for a reader, then the block. */ +export function reviewComment(record: ReviewRecord): string { + const line = (finding: ReviewFinding) => !("disposition" in finding) ? `**no disposition yet**: ${finding.summary}` + : finding.disposition === "fixed" ? `**fixed** in ${finding.commit}: ${finding.summary}` + : finding.disposition === "filed" ? `**filed** as ${finding.issue}: ${finding.summary}` + : `**rejected**: ${finding.summary} Reason: ${finding.reason}`; + return ["## Independent review", "", + `Reviewed head ${record.head} against base ${record.base}. Reviewer: ${record.reviewer}.`, "", + record.findings.length ? record.findings.map((finding, index) => `${index + 1}. ${line(finding)}`).join("\n") : "No findings.", "", + reviewBlock(record)].join("\n"); +} + +/** The record one comment carries: null when it has no block; an unreadable or doubled block refuses. */ +export function reviewFromBody(body: string | null | undefined): ReviewRecord | null { + const text = (body ?? "").replace(/\r\n/g, "\n"); + const blocks: string[] = []; + let at = 0; + for (;;) { + const start = text.indexOf(REVIEW_START, at); + if (start < 0) break; + const end = text.indexOf(REVIEW_END, start); + if (end < 0) throw new Error("Unterminated review record block"); + blocks.push(text.slice(start + REVIEW_START.length, end)); at = end + REVIEW_END.length; + } + if (!blocks.length) return null; + if (blocks.length > 1) throw new Error("One comment carries more than one review record"); + const json = /```json\s*\n([\s\S]*?)\n\s*```/.exec(blocks[0]!)?.[1]?.trim(); + if (!json) throw new Error("The review record block is empty"); + let parsed: unknown; + try { parsed = JSON.parse(json); } catch { throw new Error("The review record is not JSON"); } + return parseReview(parsed); +} + +/** + * The newest record among a pull request's comments, given oldest first. Only + * the newest counts: an unreadable newest record refuses and never falls back + * to an older one. + */ +export function newestReview(comments: readonly (string | null | undefined)[]): ReviewRecord | null { + for (let index = comments.length - 1; index >= 0; index--) { + if ((comments[index] ?? "").includes(REVIEW_START)) return reviewFromBody(comments[index]); + } + return null; +} + +function git(root: string, args: string[]): { code: number; out: string; err: string } { + const result = Bun.spawnSync(["git", ...args], { cwd: root, stdout: "pipe", stderr: "pipe" }); + return { code: result.exitCode ?? 1, out: new TextDecoder().decode(result.stdout), err: new TextDecoder().decode(result.stderr).trim() }; +} +function must(root: string, args: string[]): string { + const result = git(root, args); + if (result.code !== 0) throw new Error(`git ${args.slice(0, 2).join(" ")} failed: ${result.err}`); + return result.out; +} +/** A commit this repository has, fetching it on demand; false when it can be neither read nor fetched. */ +function available(root: string, commit: string): boolean { + const present = () => git(root, ["cat-file", "-e", `${commit}^{commit}`]).code === 0; + return present() || (git(root, ["fetch", "--no-tags", "origin", commit]).code === 0 && present()); +} + +/** Paths the candidate changes against its merge base, with a rename counted at both ends. */ +export function changedPaths(root: string, candidate: ReviewCandidate): string[] { + for (const commit of [candidate.base, candidate.head]) if (!available(root, commit)) throw new Error(`Cannot read candidate commit ${commit}`); + return must(root, ["diff", "--name-only", "--no-renames", "-z", `${candidate.base}...${candidate.head}`]).split("\0").filter(Boolean); +} + +/** + * Non-merge commits in the candidate head that neither the base nor the + * reviewed head contains: the work nobody reviewed. Merging the base into the + * branch adds only a merge commit and commits the base already has, so a + * refresh by merge leaves this empty; a rebase or an amend rewrites the + * reviewed commits and does not. + */ +export function unreviewedCommits(root: string, candidate: ReviewCandidate, reviewedHead: string): string[] { + return must(root, ["rev-list", "--no-merges", candidate.head, `^${candidate.base}`, `^${reviewedHead}`]).split("\n").filter(Boolean); +} + +const REMEDY = "Have a fresh agent context or a human review it, given only the pull request and its issue, then record the result with"; + +/** + * The merge decision for a core-package candidate's review; returns the + * refusal text or null. `comments` are the pull request's comment bodies, + * oldest first. + */ +export function reviewRefusal(root: string, candidate: ReviewCandidate, comments: readonly (string | null | undefined)[]): string | null { + const post = `\`bun scripts/review-receipt.ts post ${candidate.pr} --reviewer --head (--no-findings | --findings )\``; + const record = newestReview(comments); + if (!record) return `No review record on PR #${candidate.pr}, whose diff touches the core packages (${CORE_PACKAGES.map(name => `packages/${name}/`).join(", ")}). ${REMEDY} ${post}`; + if (record.pr !== candidate.pr) return `The newest review record on PR #${candidate.pr} names PR #${record.pr}. ${REMEDY} ${post}`; + const open = undisposed(record); + if (open.length) return `The newest review record (head ${record.head}) leaves ${open.length} finding${open.length === 1 ? "" : "s"} without a disposition: ${open.map(finding => JSON.stringify(finding.summary)).join("; ")}. Answer each as fixed (naming the commit), filed (naming the issue) or rejected (with the reason), and post the record again with ${post}`; + for (const finding of record.findings) { + if ("disposition" in finding && finding.disposition === "fixed" && !(available(root, finding.commit) && git(root, ["merge-base", "--is-ancestor", finding.commit, candidate.head]).code === 0)) { + return `The newest review record answers a finding as fixed in ${finding.commit}, which the candidate head ${candidate.head} does not contain. Name the commit that fixes it and post the record again with ${post}`; + } + } + if (!available(root, record.head)) return `The reviewed head ${record.head} can be neither read nor fetched, so the commits added since cannot be established. ${REMEDY} ${post}`; + const fresh = unreviewedCommits(root, candidate, record.head); + if (!fresh.length) return null; + return `The candidate head ${candidate.head} contains ${fresh.length} commit${fresh.length === 1 ? "" : "s"} the reviewed head ${record.head} does not (${fresh.slice(0, 5).map(commit => commit.slice(0, 12)).join(", ")}${fresh.length > 5 ? ", ..." : ""}). Merging the base keeps a record valid; a new commit, a rebase or an amend needs a new review of the current head. ${REMEDY} ${post}`; +} + +/** + * The whole gate: a candidate outside the core packages is never asked for a + * review, and its comments are never read. + */ +export async function reviewGate(root: string, candidate: ReviewCandidate, comments: () => Promise): Promise { + if (!touchesCorePackages(changedPaths(root, candidate))) return null; + return reviewRefusal(root, candidate, await comments()); +} + +export interface ReviewIo { gh?: Gh; out: (text: string) => void; root?: string } + +const realGh: Gh = args => { + const result = Bun.spawnSync(["gh", ...args], { stdout: "pipe", stderr: "pipe" }); + return { code: result.exitCode, stdout: result.stdout.toString(), stderr: result.stderr.toString() }; +}; +function ghMust(gh: Gh, args: string[]): string { + const result = gh(args); + if (result.code !== 0) throw new Error(`gh ${args.slice(0, 3).join(" ")}: ${result.stderr.trim() || `exit ${result.code}`}`); + return result.stdout; +} + +/** Comment bodies of one pull request, oldest first: GitHub lists issue comments by ascending id. */ +export function commentBodies(gh: Gh, repo: string, pr: number): string[] { + return ghMust(gh, ["api", `repos/${repo}/issues/${pr}/comments`, "--paginate", "--jq", ".[] | .body | @json"]) + .split("\n").filter(Boolean).map(line => String(JSON.parse(line) ?? "")); +} + +const USAGE = "usage: bun scripts/review-receipt.ts post --reviewer agent|human --head (--no-findings | --findings ) [--base ] [--dry-run] | check "; + +export async function main(argv: readonly string[], io: ReviewIo): Promise { + const gh = io.gh ?? realGh, root = io.root ?? process.cwd(); + const flags = new Map(), positional: string[] = []; + for (let index = 0; index < argv.length; index++) { + const arg = argv[index]!; + if (!arg.startsWith("--")) positional.push(arg); + else if (flags.has(arg.slice(2))) throw new Error(`${arg} given twice`); + else if (["no-findings", "dry-run"].includes(arg.slice(2))) flags.set(arg.slice(2), true); + else if (["reviewer", "head", "base", "findings", "repo"].includes(arg.slice(2))) { const value = argv[++index]; if (value === undefined || value.startsWith("--")) throw new Error(`${arg} needs a value`); flags.set(arg.slice(2), value); } + else throw new Error(`Unknown option ${arg}`); + } + const text = (name: string) => { const value = flags.get(name); return typeof value === "string" ? value : undefined; }; + const [command, target] = positional; + if (!["post", "check"].includes(command ?? "") || !/^[1-9]\d*$/.test(target ?? "") || positional.length !== 2) { io.out(USAGE); return 2; } + const pr = Number(target), repo = text("repo") ?? DEFAULT_REPO; + const live = JSON.parse(ghMust(gh, ["api", `repos/${repo}/pulls/${pr}`])) as { state: string; head: { sha: string }; base: { ref: string; sha: string } }; + + if (command === "check") { + const base = ghMust(gh, ["api", `repos/${repo}/git/ref/heads/${live.base.ref}`, "--jq", ".object.sha"]).trim(); + const candidate = { pr, head: live.head.sha, base }; + const required = touchesCorePackages(changedPaths(root, candidate)); + const comments = required ? commentBodies(gh, repo, pr) : []; + const refusal = required ? reviewRefusal(root, candidate, comments) : null, record = newestReview(comments); + io.out(JSON.stringify({ ...candidate, required, record: record && { head: record.head, reviewer: record.reviewer, findings: record.findings.length, undisposed: undisposed(record).length }, refusal })); + return refusal ? 1 : 0; + } + + if (live.state !== "open") throw new Error(`PR #${pr} is ${live.state}; a review is recorded on an open pull request`); + if (!REVIEWERS.includes(text("reviewer") as Reviewer)) throw new Error("--reviewer is agent or human; the record names no other identity"); + if (!sha(text("head"))) throw new Error("--head needs the full reviewed commit SHA: the head the reviewer read"); + if (flags.has("no-findings") === flags.has("findings")) throw new Error("Give exactly one of --no-findings and --findings : a review with no findings says so"); + const findings: unknown = flags.has("findings") ? JSON.parse(readFileSync(text("findings")!, "utf8")) : []; + if (!Array.isArray(findings) || (flags.has("findings") && !findings.length)) throw new Error("--findings needs a JSON array with at least one finding; use --no-findings for a review that found nothing"); + const record = parseReview({ version: 1, kind: REVIEW_KIND, pr, head: text("head"), base: text("base") ?? live.base.sha, reviewer: text("reviewer"), + outcome: findings.length ? "findings" : "no-findings", findings }); + const body = reviewComment(record); + // Every word of the comment is public: the leakage gate reads it before anything is posted. + if (scanText("review record", body).length) throw new Error("The review record contains text the leakage gate refuses; nothing was posted"); + if (flags.has("dry-run")) { io.out(body); return 0; } + const dir = mkdtempSync(join(tmpdir(), "review-receipt-")); + try { + writeFileSync(join(dir, "body.md"), body); + ghMust(gh, ["pr", "comment", String(pr), "--repo", repo, "--body-file", join(dir, "body.md")]); + } finally { rmSync(dir, { recursive: true, force: true }); } + io.out(JSON.stringify({ posted: true, pr, head: record.head, base: record.base, reviewer: record.reviewer, findings: record.findings.length, undisposed: undisposed(record).length })); + return 0; +} + +if (import.meta.main) { + try { process.exit(await main(process.argv.slice(2), { out: text => console.log(text) })); } + catch (error) { console.error(error instanceof Error ? error.message : String(error)); process.exit(2); } +} diff --git a/tests/review-receipt.test.ts b/tests/review-receipt.test.ts new file mode 100644 index 0000000000..bd49cabe5f --- /dev/null +++ b/tests/review-receipt.test.ts @@ -0,0 +1,278 @@ +import { afterEach, describe, expect, test } from "bun:test"; +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; +import { isCorePackagePath, touchesCorePackages } from "../scripts/fast-lane"; +import type { Gh } from "../scripts/issue-queue"; +import { main, newestReview, parseReview, reviewBlock, reviewComment, reviewFromBody, reviewGate, reviewRefusal, unreviewedCommits, + REVIEW_END, REVIEW_START, type ReviewFinding, type ReviewRecord } from "../scripts/review-receipt"; + +const dirs: string[] = []; +afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); }); + +const PR = 7, REPO = "odysseus/brain-kit"; +const record = (head: string, base: string, findings: ReviewFinding[] = [], reviewer: ReviewRecord["reviewer"] = "agent"): ReviewRecord => + ({ version: 1, kind: "brain-review-receipt", pr: PR, head, base, reviewer, outcome: findings.length ? "findings" : "no-findings", findings }); + +/** + * A real repository: `main` with one commit and a `raft` branch whose one + * commit changes a core package. That commit is the reviewed head. + */ +function voyage(path = "packages/core/src/raft.ts") { + const root = mkdtempSync(join(tmpdir(), "odysseus-review-")); dirs.push(root); + const git = (...args: string[]) => { + const result = Bun.spawnSync(["git", "-c", "commit.gpgsign=false", "-c", "user.name=Odysseus", "-c", "user.email=odysseus@example.invalid", ...args], { cwd: root, stdout: "pipe", stderr: "pipe" }); + expect(result.exitCode, `git ${args.join(" ")}: ${new TextDecoder().decode(result.stderr)}`).toBe(0); + return new TextDecoder().decode(result.stdout).trim(); + }; + const commit = (file: string, text: string, message: string) => { + mkdirSync(dirname(join(root, file)), { recursive: true }); writeFileSync(join(root, file), text); + git("add", "-A"); git("commit", "-qm", message); return git("rev-parse", "HEAD"); + }; + git("init", "-q", "-b", "main"); + const start = commit("README.md", "Odysseus sails.\n", "base"); + git("checkout", "-qb", "raft"); + const reviewed = commit(path, "export const raft = 1;\n", "build the raft"); + /** Main gains a commit, as another merged PR would add. */ + const advanceMain = (name: string) => { git("checkout", "-q", "main"); const tip = commit(`docs/${name}.md`, `${name}\n`, `main: ${name}`); git("checkout", "-q", "raft"); return tip; }; + /** The refresh used under lease contention: merge the base into the branch. */ + const mergeMain = () => { git("merge", "-q", "--no-ff", "--no-edit", "main"); return git("rev-parse", "HEAD"); }; + return { root, git, commit, start, reviewed, advanceMain, mergeMain }; +} + +describe("the record", () => { + const head = "a".repeat(40), base = "b".repeat(40), fix = "c".repeat(40); + const full = record(head, base, [{ summary: "The mast is not lashed.", disposition: "fixed", commit: fix }, + { summary: "The oars are uncounted.", disposition: "filed", issue: "odysseus/brain-kit#12" }, + { summary: "The sail is too small.", disposition: "rejected", reason: "The raft carries one man." }]); + + test("round-trips through its comment, and a review with no findings says so explicitly", () => { + expect(reviewFromBody(reviewComment(full))).toEqual(full); + expect(reviewFromBody(reviewComment(full).replace(/\n/g, "\r\n"))).toEqual(full); + const none = record(head, base); + expect(none.outcome).toBe("no-findings"); + expect(reviewComment(none)).toContain("No findings."); + expect(() => parseReview({ ...none, outcome: "findings" }), "EMPTY_LIST_IS_NOT_A_STATEMENT").toThrow("no-findings exactly when"); + expect(() => parseReview({ ...full, outcome: "no-findings" })).toThrow("no-findings exactly when"); + }); + + test("names the reviewer only as agent or human, and refuses any other identity field", () => { + expect(parseReview(record(head, base, [], "human")).reviewer).toBe("human"); + expect(() => parseReview({ ...full, reviewer: "Odysseus" }), "REVIEWER_KIND_ONLY").toThrow("Invalid review record"); + expect(() => parseReview({ ...full, reviewerName: "Odysseus" }), "NO_EXTRA_RECORD_FIELD").toThrow("Invalid review record"); + expect(() => parseReview({ ...full, findings: [{ summary: "The mast is not lashed.", author: "Odysseus" }] }), "NO_EXTRA_FINDING_FIELD").toThrow("Invalid review finding"); + expect(Object.keys(JSON.parse(/```json\n(.*)\n```/.exec(reviewBlock(full))![1]!)).sort()).toEqual(["base", "findings", "head", "kind", "outcome", "pr", "reviewer", "version"]); + }); + + test("gives each finding at most one disposition, with exactly the detail that disposition names", () => { + const bad = (finding: object) => () => parseReview({ ...full, findings: [finding] }); + expect(parseReview({ ...full, findings: [{ summary: "The mast is not lashed." }] }).findings).toHaveLength(1); + expect(bad({ summary: "x", disposition: "fixed" })).toThrow("Invalid review finding"); + expect(bad({ summary: "x", disposition: "fixed", commit: "c0ffee" })).toThrow("Invalid review finding commit"); + expect(bad({ summary: "x", disposition: "fixed", commit: fix, reason: "also rejected" })).toThrow("Invalid review finding"); + expect(bad({ summary: "x", disposition: "filed", issue: "#12" })).toThrow("Invalid review finding issue"); + expect(bad({ summary: "x", disposition: "rejected", reason: " " })).toThrow("Invalid review finding reason"); + expect(bad({ summary: "x", disposition: "wontfix", reason: "no" })).toThrow("Invalid review finding"); + expect(bad({ summary: "two\nlines" })).toThrow("Invalid review finding"); + }); + + test("only the newest record counts, and an unreadable newest record never falls back to an older one", () => { + const older = reviewComment(record(head, base)), newer = reviewComment(record(fix, base)); + expect(newestReview([])).toBeNull(); + expect(newestReview(["Odysseus builds a raft.", null])).toBeNull(); + expect(newestReview([older, "A later remark.", newer, "The last word."])?.head).toBe(fix); + expect(() => newestReview([older, `${REVIEW_START}\n\`\`\`json\n{"version":2}\n\`\`\`\n${REVIEW_END}`]), "NO_FALLBACK_TO_OLDER").toThrow("Invalid review record"); + expect(() => newestReview([older, `${REVIEW_START}\n${REVIEW_END}`])).toThrow("empty"); + expect(() => newestReview([older + "\n" + newer])).toThrow("more than one"); + expect(() => newestReview([REVIEW_START])).toThrow("Unterminated"); + }); +}); + +describe("one path predicate decides the fast lane and the review", () => { + test("only the four core packages count, by directory", () => { + for (const path of ["packages/core/src/index.ts", "packages/ui-react/tests/a.test.tsx", "packages/ui-kit/package.json", "packages/ui-server/src/routes/x.ts"]) expect(isCorePackagePath(path), path).toBe(true); + for (const path of ["packages/core-extras/src/index.ts", "packages/ui-sdk/src/index.ts", "docs/packages/core/x.md", "scripts/core/x.ts", "packages/core"]) expect(isCorePackagePath(path), path).toBe(false); + expect(touchesCorePackages(["docs/voyage.md", "packages/ui-kit/src/sail.css"])).toBe(true); + expect(touchesCorePackages(["docs/voyage.md", "scripts/integrate.ts"])).toBe(false); + }); + + test("a PR outside the four packages is never asked for a review: its comments are not even read", async () => { + const { root, reviewed, start } = voyage("packages/common/src/raft.ts"); + const asked = () => { throw new Error("NEVER_ASKED: comments were read for a PR outside the core packages"); }; + expect(await reviewGate(root, { pr: PR, head: reviewed, base: start }, asked)).toBeNull(); + }); + + test("a core-package PR with no record is refused with the command that fixes it", async () => { + const { root, reviewed, start } = voyage(); + const refusal = await reviewGate(root, { pr: PR, head: reviewed, base: start }, async () => ["Odysseus builds a raft."]); + expect(refusal, "CORE_PR_WITHOUT_RECORD_REFUSED").toContain("No review record on PR #7"); + expect(refusal).toContain("bun scripts/review-receipt.ts post 7 --reviewer --head "); + expect(refusal).toContain("a fresh agent context or a human"); + }); + + test("moving a file out of a core package still touches it", async () => { + const { root, git, reviewed } = voyage(); + git("mv", "packages/core/src/raft.ts", "raft.ts"); git("commit", "-qm", "beach the raft"); + const refusal = await reviewGate(root, { pr: PR, head: git("rev-parse", "HEAD"), base: reviewed }, async () => []); + expect(refusal, "RENAME_SOURCE_COUNTS").toContain("No review record"); + }); +}); + +describe("which commits a record covers, against real Git history", () => { + test("a record at an older head still admits a candidate whose only newer commits are merges of the base", () => { + const { root, git, reviewed, start, advanceMain, mergeMain } = voyage(); + const comments = [reviewComment(record(reviewed, start))]; + advanceMain("Scylla"); mergeMain(); + const base = advanceMain("Charybdis"), head = mergeMain(); + // The control: the head really moved, by two merge commits and main's two commits. + expect(head).not.toBe(reviewed); + expect(git("rev-list", "--merges", head, `^${base}`).split("\n")).toHaveLength(2); + expect(git("rev-list", "--count", `${reviewed}..${head}`)).toBe("4"); + expect(unreviewedCommits(root, { pr: PR, head, base }, reviewed)).toEqual([]); + expect(reviewRefusal(root, { pr: PR, head, base }, comments), "RECORD_SURVIVES_BASE_MERGE").toBeNull(); + }); + + test("a new non-merge commit after the reviewed head refuses, also behind a later merge of the base", () => { + const { root, commit, reviewed, start, advanceMain, mergeMain } = voyage(); + const comments = [reviewComment(record(reviewed, start))]; + advanceMain("Scylla"); mergeMain(); + const added = commit("packages/core/src/oar.ts", "export const oar = 1;\n", "carve an oar"); + const base = advanceMain("Charybdis"), head = mergeMain(); + expect(unreviewedCommits(root, { pr: PR, head, base }, reviewed), "NEW_COMMIT_IS_UNREVIEWED").toEqual([added]); + const refusal = reviewRefusal(root, { pr: PR, head, base }, comments)!; + expect(refusal, "NEW_COMMIT_NEEDS_REVIEW").toContain(`contains 1 commit the reviewed head ${reviewed} does not (${added.slice(0, 12)})`); + expect(refusal).toContain("bun scripts/review-receipt.ts post 7"); + // A review of the new head covers it. + expect(reviewRefusal(root, { pr: PR, head, base }, [...comments, reviewComment(record(head, base))])).toBeNull(); + }); + + test("a rebase rewrites the reviewed commits, so the old record no longer covers the branch", () => { + const { root, git, reviewed, start, advanceMain } = voyage(); + const base = advanceMain("Scylla"); + git("rebase", "-q", "main"); + const head = git("rev-parse", "HEAD"); + expect(git("diff", "--name-only", reviewed, head)).toBe("docs/Scylla.md"); + expect(reviewRefusal(root, { pr: PR, head, base }, [reviewComment(record(reviewed, start))]), "REBASE_NEEDS_REVIEW").toContain("a new commit, a rebase or an amend needs a new review"); + }); + + test("merging another branch brings its commits with it: the merge commit does not hide them", () => { + const { root, git, commit, reviewed, start } = voyage(); + git("checkout", "-qb", "sirens", start); + const song = commit("packages/ui-server/src/song.ts", "export const song = 1;\n", "the sirens sing"); + git("checkout", "-q", "raft"); git("merge", "-q", "--no-ff", "--no-edit", "sirens"); + const head = git("rev-parse", "HEAD"); + expect(reviewRefusal(root, { pr: PR, head, base: start }, [reviewComment(record(reviewed, start))]), "MERGED_BRANCH_COMMITS_COUNT").toContain(song.slice(0, 12)); + }); + + test("a reviewed head that cannot be read cannot establish what was added since", () => { + const { root, reviewed, start } = voyage(); + expect(reviewRefusal(root, { pr: PR, head: reviewed, base: start }, [reviewComment(record("d".repeat(40), start))])).toContain("can be neither read nor fetched"); + }); +}); + +describe("dispositions", () => { + test("an undisposed finding in the newest record refuses and is named", () => { + const { root, reviewed, start } = voyage(), candidate = { pr: PR, head: reviewed, base: start }; + const open = reviewComment(record(reviewed, start, [{ summary: "The mast is not lashed." }, { summary: "The sail is too small.", disposition: "rejected", reason: "The raft carries one man." }])); + const refusal = reviewRefusal(root, candidate, [open])!; + expect(refusal, "UNDISPOSED_FINDING_REFUSES").toContain('leaves 1 finding without a disposition: "The mast is not lashed."'); + expect(refusal).toContain("fixed (naming the commit), filed (naming the issue) or rejected (with the reason)"); + // An older clean record does not rescue a newer one with an open finding. + expect(reviewRefusal(root, candidate, [reviewComment(record(reviewed, start)), open])).toContain("without a disposition"); + const answered = reviewComment(record(reviewed, start, [{ summary: "The mast is not lashed.", disposition: "filed", issue: "odysseus/brain-kit#12" }, + { summary: "The sail is too small.", disposition: "rejected", reason: "The raft carries one man." }])); + expect(reviewRefusal(root, candidate, [open, answered]), "ANSWERED_RECORD_ADMITS").toBeNull(); + }); + + test("a finding answered as fixed names a commit the candidate head contains", () => { + const { root, git, commit, reviewed, start } = voyage(); + const fixed = (sha: string) => [reviewComment(record(reviewed, start, [{ summary: "The mast is not lashed.", disposition: "fixed", commit: sha }]))]; + expect(reviewRefusal(root, { pr: PR, head: reviewed, base: start }, fixed(reviewed))).toBeNull(); + expect(reviewRefusal(root, { pr: PR, head: reviewed, base: start }, fixed("e".repeat(40))), "FIX_COMMIT_MUST_EXIST").toContain("which the candidate head"); + git("checkout", "-qb", "elsewhere", start); + const stray = commit("docs/elsewhere.md", "Elsewhere.\n", "a fix on another branch"); + expect(reviewRefusal(root, { pr: PR, head: reviewed, base: start }, fixed(stray)), "FIX_COMMIT_MUST_BE_IN_HEAD").toContain("does not contain"); + }); + + test("a record written for another pull request does not count", () => { + const { root, reviewed, start } = voyage(); + expect(reviewRefusal(root, { pr: 8, head: reviewed, base: start }, [reviewComment(record(reviewed, start))])).toContain("names PR #7"); + }); +}); + +describe("the command", () => { + function github(reviewed: string, base: string, comments: string[] = []) { + const posted: string[] = [], calls: string[][] = []; + const ok = (stdout: string) => ({ code: 0, stdout, stderr: "" }); + const gh: Gh = args => { + calls.push(args); + if (args[0] === "api" && args[1] === `repos/${REPO}/pulls/7`) return ok(JSON.stringify({ state: "open", head: { sha: reviewed }, base: { ref: "main", sha: base } })); + if (args[0] === "api" && args[1] === `repos/${REPO}/git/ref/heads/main`) return ok(`${base}\n`); + if (args[0] === "api" && args[1] === `repos/${REPO}/issues/7/comments`) return ok(comments.map(body => JSON.stringify(body)).join("\n")); + if (args[0] === "pr" && args[1] === "comment" && args[2] === "7") { posted.push(readFileSync(args[args.indexOf("--body-file") + 1]!, "utf8")); return ok(""); } + return { code: 1, stdout: "", stderr: `unexpected gh ${args.join(" ")}` }; + }; + return { gh, posted, calls }; + } + async function run(gh: Gh, root: string, ...argv: string[]) { + const out: string[] = []; + const code = await main([...argv, "--repo", REPO], { gh, out: text => out.push(text), root }); + return { code, out: out.join("\n") }; + } + const findingsFile = (root: string, findings: unknown) => { const file = join(root, "findings.json"); writeFileSync(file, JSON.stringify(findings)); return file; }; + + test("post writes one comment whose block the gate accepts, and a no-findings review says so", async () => { + const { root, reviewed, start } = voyage(), { gh, posted } = github(reviewed, start); + const result = await run(gh, root, "post", "7", "--reviewer", "agent", "--head", reviewed, "--no-findings"); + expect(result.code).toBe(0); + expect(JSON.parse(result.out)).toEqual({ posted: true, pr: 7, head: reviewed, base: start, reviewer: "agent", findings: 0, undisposed: 0 }); + expect(posted).toHaveLength(1); + expect(reviewFromBody(posted[0])).toEqual(record(reviewed, start)); + expect(reviewRefusal(root, { pr: PR, head: reviewed, base: start }, posted)).toBeNull(); + }); + + test("the comment passes the leakage gate before it is posted", async () => { + const { root, reviewed, start } = voyage(), { gh, posted, calls } = github(reviewed, start); + // Assembled from parts, so this file does not carry a string the gate refuses. + const personal = ["wyv", "ern"].join(""); + const file = findingsFile(root, [{ summary: `The mast was lashed on ${personal}.`, disposition: "rejected", reason: "Out of scope." }]); + await expect(run(gh, root, "post", "7", "--reviewer", "human", "--head", reviewed, "--findings", file)).rejects.toThrow("leakage gate refuses; nothing was posted"); + expect(posted, "NOTHING_POSTED_AFTER_LEAKAGE_REFUSAL").toEqual([]); + expect(calls.some(args => args[0] === "pr"), "NO_COMMENT_CALL").toBe(false); + // The control: the same finding without the personal string is posted. + writeFileSync(file, JSON.stringify([{ summary: "The mast was lashed on Ithaca.", disposition: "rejected", reason: "Out of scope." }])); + expect((await run(gh, root, "post", "7", "--reviewer", "human", "--head", reviewed, "--findings", file)).code).toBe(0); + expect(posted).toHaveLength(1); + }); + + test("post refuses a reviewer identity, an unanswerable shape and a silent empty review; --dry-run posts nothing", async () => { + const { root, reviewed, start } = voyage(), { gh, posted } = github(reviewed, start); + await expect(run(gh, root, "post", "7", "--reviewer", "Odysseus", "--head", reviewed, "--no-findings")).rejects.toThrow("--reviewer is agent or human"); + await expect(run(gh, root, "post", "7", "--reviewer", "agent", "--head", "raft", "--no-findings")).rejects.toThrow("--head needs the full reviewed commit SHA"); + await expect(run(gh, root, "post", "7", "--reviewer", "agent", "--head", reviewed)).rejects.toThrow("exactly one of --no-findings and --findings"); + await expect(run(gh, root, "post", "7", "--reviewer", "agent", "--head", reviewed, "--findings", findingsFile(root, []))).rejects.toThrow("use --no-findings"); + await expect(run(gh, root, "post", "7", "--reviewer", "agent", "--head", reviewed, "--findings", findingsFile(root, [{ summary: "x", reviewer: "Odysseus" }]))).rejects.toThrow("Invalid review finding"); + const open = findingsFile(root, [{ summary: "The mast is not lashed." }]); + const dry = await run(gh, root, "post", "7", "--reviewer", "agent", "--head", reviewed, "--findings", open, "--dry-run"); + expect(dry.out).toContain("**no disposition yet**: The mast is not lashed."); + expect(posted).toEqual([]); + // An unanswered review can be recorded as it stands; the gate refuses it until it is answered. + const recorded = await run(gh, root, "post", "7", "--reviewer", "agent", "--head", reviewed, "--findings", open); + expect(JSON.parse(recorded.out)).toMatchObject({ posted: true, findings: 1, undisposed: 1 }); + expect(reviewRefusal(root, { pr: PR, head: reviewed, base: start }, posted)).toContain("without a disposition"); + }); + + test("check prints the gate's decision for the live head and exits 1 on a refusal", async () => { + const { root, reviewed, start } = voyage(); + const refused = await run(github(reviewed, start).gh, root, "check", "7"); + expect(refused.code).toBe(1); + expect(JSON.parse(refused.out)).toMatchObject({ pr: 7, head: reviewed, base: start, required: true, record: null, refusal: expect.stringContaining("No review record") }); + const admitted = await run(github(reviewed, start, [reviewComment(record(reviewed, start, [], "human"))]).gh, root, "check", "7"); + expect(admitted.code).toBe(0); + expect(JSON.parse(admitted.out)).toEqual({ pr: 7, head: reviewed, base: start, required: true, record: { head: reviewed, reviewer: "human", findings: 0, undisposed: 0 }, refusal: null }); + const outside = voyage("packages/common/src/raft.ts"), other = github(outside.reviewed, outside.start); + const unasked = await run(other.gh, outside.root, "check", "7"); + expect(JSON.parse(unasked.out)).toMatchObject({ required: false, record: null, refusal: null }); + expect(other.calls.some(args => args.join(" ").includes("/comments")), "COMMENTS_NOT_READ_OUTSIDE_CORE").toBe(false); + }); +}); From dc5f332a109e35a2fd1bf1ee571d6d72c26e5ff1 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 17 Nov 2026 00:08:59 +0000 Subject: [PATCH 06/31] chore(ci): refuse to confirm or merge a core-package PR without a recorded review (#4110) confirm checks before it takes the reservation or requests candidate CI, and the merge reads the record again. A PR outside the core packages is never asked and its comments are never read. An expedited red-main fix is exempt. Co-Authored-By: Claude Fable 5.2 --- scripts/integrate.ts | 26 +++++++++++++-- tests/integration-command.test.ts | 55 +++++++++++++++++++++++++++++-- 2 files changed, 76 insertions(+), 5 deletions(-) diff --git a/scripts/integrate.ts b/scripts/integrate.ts index 1a9af0bdf2..8bac1fcf3d 100644 --- a/scripts/integrate.ts +++ b/scripts/integrate.ts @@ -8,6 +8,7 @@ import { declareFix, gateDecision, recordExpedited, type RedMainRecord } from ". import { isAncestor } from "./red-main-cli"; import { expeditedProblems, expeditedTests, fixProbeTitle, probeReceipt, type FeedbackEvidence, type ProbeEvidence } from "./red-main-expedite"; import { receiptFromBody, receiptRefusal } from "./check-receipt"; +import { reviewGate } from "./review-receipt"; import type { API } from "./proof-reuse"; /** @@ -152,6 +153,20 @@ if (import.meta.main) { await Bun.sleep(RENEW_MS); } } + /** + * The recorded independent review of a core-package candidate (#4110); returns the refusal or null. + * A candidate outside the core packages is never asked, and its comments are never read. + */ + function reviewRefusal(desired: Candidate) { + return reviewGate(store!.root, desired, async () => { + const bodies: string[] = []; + for (let page = 1; ; page++) { + const batch: Array<{ body?: string | null }> = await api.json(`issues/${desired.pr}/comments?per_page=100&page=${page}`); + bodies.push(...batch.map(comment => comment.body ?? "")); + if (batch.length < 100) return bodies; + } + }); + } async function stopHeartbeat() { if (timer) clearInterval(timer); timer = undefined; await pending; } async function milestones(pr: number, issueRefs: string[]) { const live = await api.json(`pulls/${pr}`); @@ -206,6 +221,9 @@ if (import.meta.main) { const proof = await verifyIntegrationProof(store!.root, repository, desired, api, sha => { store!.git(["fetch", "origin", sha]); }); const refusal = receiptRefusal((await api.json(`pulls/${desired.pr}`)).body, proof.covered); if (refusal) throw new Error(refusal); + // Read again here: a review posted while the candidate was being proved is the newest record. + const unreviewed = await reviewRefusal(desired); + if (unreviewed) throw new Error(unreviewed); tree = proof.checkout.tree; candidateRun = proof.run; } else { expedited = await expeditedEvidence(desired, fixesRun, after); @@ -295,8 +313,12 @@ if (import.meta.main) { // Refuse a run that is not the open record's, or category-only failures, before any write. expeditedTests(store.read().redMain, fixesRun); console.log(JSON.stringify({ declared: (await changeRedMain((record, now) => declareFix(record, desired.pr, now))).open?.fixes })); - } else if (command !== "acquire" && !receiptFromBody((await api.json(`pulls/${desired.pr}`)).body)) { - throw new Error(receiptRefusal("", new Set())!); + } else if (command !== "acquire") { + if (!receiptFromBody((await api.json(`pulls/${desired.pr}`)).body)) throw new Error(receiptRefusal("", new Set())!); + // Before any lease or candidate CI, like the receipt; an expedited red-main fix is exempt from both. + // `merge --lease` checks inside the merge instead, after its lease is proved to cover this candidate. + const unreviewed = command === "confirm" ? await reviewRefusal(desired) : null; + if (unreviewed) throw new Error(unreviewed); } refuseWhileRed(desired); if (command === "merge") { diff --git a/tests/integration-command.test.ts b/tests/integration-command.test.ts index 12b4a537b4..27d52deec2 100644 --- a/tests/integration-command.test.ts +++ b/tests/integration-command.test.ts @@ -5,11 +5,12 @@ import { tmpdir } from "node:os"; import { GitReservationStore, emptyReservation, holderDigest, reservationTransition, MAX_MS } from "../scripts/integration-reservation"; import { declareFix, emptyRedMain, openRed } from "../scripts/red-main"; import { receiptBlock, type CheckReceipt } from "../scripts/check-receipt"; +import { reviewComment, type ReviewFinding } from "../scripts/review-receipt"; import { invocationChild } from "../scripts/test-invocation-child"; import { processIdentity } from "../scripts/workspace-lease.mjs"; const dirs: string[] = []; -type ScenarioResult = { code: number; out: string; err: string; dispatched: boolean; requested: boolean; reads: string[]; state: ReturnType["state"]; +type ScenarioResult = { code: number; out: string; err: string; dispatched: boolean; requested: boolean; reads: string[]; commentReads: number; state: ReturnType["state"]; redMain: ReturnType["redMain"]; events: any[] }; type Scenario = { dir?: string; child?: ReturnType; work?: Promise; settled: boolean; beforeRead?: () => Promise }; const scenarios = new Set(); @@ -69,7 +70,10 @@ async function runScenario(mode: string, owner: Scenario): Promise reviewComment({ version: 1, kind: "brain-review-receipt", pr: 7, head, base, reviewer: "agent", + outcome: findings.length ? "findings" : "no-findings", findings }); + const openReview = review([{ summary: "The mast is not lashed." }]); + // The PR's comments at each successive read; the last entry repeats. `superseded` gains an unanswered review after the first read. + const reviews = mode.endsWith("review-absent") ? [["Odysseus builds a raft."]] : mode.endsWith("review-undisposed") ? [[review(), openReview]] + : mode.endsWith("review-superseded") ? [[review()], [review(), openReview]] : [[review()]]; const probeLog = (id: number) => (id === 401 ? { sha: base, tests: ["tests/raft.test.ts"], absent: [], exitCode: mode === "expedite-base-green" ? 0 : 1 } : mode === "expedite-revert" ? { sha: head, tests: [], absent: ["tests/raft.test.ts"], exitCode: 0 } : { sha: head, tests: ["tests/raft.test.ts"], absent: [], exitCode: mode === "expedite-head-red" ? 1 : 0 }); @@ -176,6 +186,7 @@ fi`); chmodSync(shim, 0o755); else if(/actions\\/jobs\\/2[123]\\/logs$/.test(path))value=checkout; else if(path.endsWith("git/commits/"+actual.sha))value={sha:actual.sha,tree:{sha:actual.tree},parents:actual.parents.map(sha=>({sha}))}; else if(path.endsWith("git/commits/"+squash))value={sha:squash,tree:{sha:actual.tree},parents:[{sha:base}]}; + else if(/issues\\/7\\/comments\\?/.test(path)){const reviews=${JSON.stringify(reviews)};s.commentReads=(s.commentReads??0)+1;value=reviews[Math.min(s.commentReads,reviews.length)-1].map(body=>({body}));} else if(/issues\\/\\d+$/.test(path)){s.reads.push(path);value={milestone:{title:s.mode==="wrong-milestone"||s.mode==="confirm-wrong-milestone"||(s.mode.endsWith("-mismatch")&&path.endsWith("issues/30"))?"0.43.1":"0.44.0"}};} else throw new Error("Unexpected offline API "+path); } else throw new Error("Unexpected offline gh "+JSON.stringify(args)); @@ -235,7 +246,7 @@ fi`); const eventDir = join(root, "tmp/ci-timings"); const events = existsSync(eventDir) ? readdirSync(eventDir).filter(name => name.startsWith("event-")).map(name => JSON.parse(readFileSync(join(eventDir, name), "utf8"))) : []; const api = JSON.parse(readFileSync(apiState, "utf8")); - return { code, out, err, dispatched: existsSync(sentinel), requested: api.requested, reads: api.reads ?? [], state: store.read().state, redMain: store.read().redMain, events }; + return { code, out, err, dispatched: existsSync(sentinel), requested: api.requested, reads: api.reads ?? [], commentReads: api.commentReads ?? 0, state: store.read().state, redMain: store.read().redMain, events }; } finally { await child.stop("SIGTERM"); await Promise.allSettled([output]); @@ -258,6 +269,8 @@ test("shared merge executable preserves actual proof and squash identities and r const result = await scenario("valid"); expect(result.code, result.err).toBe(2); expect(result.dispatched).toBe(true); expect(result.out).toContain('"merged":true'); expect(result.out).toContain("pending; inspect actual main jobs"); + // The fixture changes no core package: it is never asked for a review, and its comments are never read (#4110). + expect(result.commentReads, "NON_CORE_CANDIDATE_NEVER_ASKED_FOR_REVIEW").toBe(0); expect(result.state.active).toBeNull(); expect(result.state.last?.action).toBe("release"); }); @@ -527,3 +540,39 @@ test("expedited fix merges only with red-on-base and green-on-head evidence, and expect(fix.events).toMatchObject([{ kind: "expedited-fix", pr: 7, run: 11, repository: "odysseus/brain-kit", evidence: "https://github.com/odysseus/brain-kit/actions/runs/302" }]); } }); + +test("confirm refuses a core-package PR with no review record before it takes the reservation, naming the command (#4110)", async () => { + const result = await scenario("confirm-review-absent"); + expect(result.err, "CORE_PR_WITHOUT_REVIEW_REFUSED_BEFORE_LEASE").toContain("No review record on PR #7"); + expect(result.err).toContain("bun scripts/review-receipt.ts post 7 --reviewer --head (--no-findings | --findings )"); + expect(result.code, result.err).toBe(1); + expect(result.out, "NOTHING_ACQUIRED").not.toContain('"acquired":'); + expect(result.state.last, "NO_RESERVATION_TAKEN").toBeNull(); + expect(result.requested, "NO_CANDIDATE_CI_SPENT").toBe(false); + expect(result.dispatched).toBe(false); + // With a record at its head the same candidate confirms and merges; the record is read before the lease and again at the merge. + const reviewed = await scenario("confirm-review-valid"); + expect(reviewed.code, `REVIEWED_CORE_PR_CONFIRMS: ${reviewed.err}`).toBe(2); + expect(reviewed.dispatched).toBe(true); + expect(reviewed.commentReads).toBe(2); +}); + +test("the merge path refuses an undisposed finding, rereads the record at the merge, and exempts an expedited red-main fix (#4110)", async () => { + const undisposed = await scenario("review-undisposed"); + expect(undisposed.err, "UNDISPOSED_FINDING_REFUSES_MERGE").toContain('leaves 1 finding without a disposition: "The mast is not lashed."'); + expect(undisposed.code, undisposed.err).toBe(1); + expect(undisposed.dispatched).toBe(false); + // A review posted while the candidate was being proved is read by the merge itself, not only before the lease. + expect(undisposed.commentReads).toBe(1); + const superseded = await scenario("confirm-review-superseded"); + expect(superseded.err, "MERGE_REREADS_THE_NEWEST_RECORD").toContain("without a disposition"); + expect(superseded.commentReads).toBe(2); + expect(superseded.requested, "FIRST_READ_ADMITTED_THE_CANDIDATE").toBe(true); + expect(superseded.dispatched, "NO_MERGE_WITH_SUPERSEDED_REVIEW").toBe(false); + expect(superseded.state.active, "REFUSAL_RELEASES_THE_LEASE").toBeNull(); + // An expedited fix for red main is exempt, as it is from the check receipt: the next main run is the backstop. + const expedited = await scenario("expedite-review-absent"); + expect(expedited.code, `EXPEDITED_FIX_EXEMPT_FROM_REVIEW: ${expedited.err}`).toBe(2); + expect(expedited.dispatched).toBe(true); + expect(expedited.commentReads).toBe(0); +}); From 192f0d9ecfffb0a5fb4f7f0038e9a9fca9585b6a Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 17 Nov 2026 00:08:59 +0000 Subject: [PATCH 07/31] chore(ci): report the newest review record in pr-status (#4110) Co-Authored-By: Claude Fable 5.2 --- scripts/pr-status.ts | 14 ++++++++++++-- scripts/skill-tests/pr-status.test.ts | 14 +++++++++++++- 2 files changed, 25 insertions(+), 3 deletions(-) diff --git a/scripts/pr-status.ts b/scripts/pr-status.ts index 341a0f3263..c9857cacb7 100644 --- a/scripts/pr-status.ts +++ b/scripts/pr-status.ts @@ -12,13 +12,17 @@ * 1 when either moved, listing the files the base gained and which of them * the pull request also changes. `--failures` names each failed job and step; * with `--logs` it saves each failed job's log and prints only its failing - * lines. This reads; it never reruns, merges or edits anything, and it does + * lines. `reviewRecord` is the newest recorded independent review among the + * comments (`scripts/review-receipt.ts`); whether the head needs one, and + * whether that record covers it, is `bun scripts/review-receipt.ts check `. + * This reads; it never reruns, merges or edits anything, and it does * not replace the proof checks of `scripts/integrate.ts`. */ import { mkdirSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { DEFAULT_REPO, type Gh } from "./issue-queue"; import { RECEIPT_START } from "./check-receipt"; +import { commentBodies, newestReview, undisposed } from "./review-receipt"; import { EXPECTED_FAILURE_PREFIX } from "./expected-failure-log"; const realGh: Gh = args => { @@ -127,9 +131,15 @@ export async function main(argv: readonly string[], io: StatusIo): Promise = { pr: number, state: pr.state, draft: pr.isDraft, head: pr.headRefOid, baseRef: pr.baseRefName, liveBase, mergeable: pr.mergeable, mergeState: pr.mergeStateStatus, review: pr.reviewDecision || null, mergeRef, - receipt: pr.body.includes(RECEIPT_START), proof, checks: { total, ...checks }, runs }; + receipt: pr.body.includes(RECEIPT_START), reviewRecord, proof, checks: { total, ...checks }, runs }; const [expectHead, expectBase] = [text("expect-head"), text("expect-base")]; let moved = false; diff --git a/scripts/skill-tests/pr-status.test.ts b/scripts/skill-tests/pr-status.test.ts index 86f83dbb33..12d68deeaf 100644 --- a/scripts/skill-tests/pr-status.test.ts +++ b/scripts/skill-tests/pr-status.test.ts @@ -5,6 +5,7 @@ import { join } from "node:path"; import type { Gh } from "../issue-queue"; import { failingLines, main, summarizeChecks } from "../pr-status"; import { RECEIPT_START } from "../check-receipt"; +import { reviewComment, REVIEW_START } from "../review-receipt"; import { EXPECTED_FAILURE_PREFIX } from "../expected-failure-log"; const REPO = "schlessera/brain-kit"; @@ -79,6 +80,7 @@ function github(overrides: Record = { "run list": { stdout: JSON.stringify([{ databaseId: 7, workflowName: "CI", event: "pull_request", attempt: 1, status: "completed", conclusion: "failure" }]) }, [`repos/${REPO}/git/ref/heads/main`]: { stdout: `${BASE}\n` }, [`repos/${REPO}/git/ref/pull/42/merge`]: { stdout: `${MERGE}\n` }, + [`repos/${REPO}/issues/42/comments`]: { stdout: `${JSON.stringify("Odysseus builds a raft.")}\n` }, [`repos/${REPO}/git/commits/${MERGE}`]: { stdout: JSON.stringify([BASE, HEAD]) }, [`repos/${REPO}/compare/${OLD_BASE}...${BASE}`]: { stdout: JSON.stringify(["packages/ithaca/tests/oars.test.ts", "packages/pylos/src/sands.ts"]) }, "run view": { stdout: JSON.stringify({ jobs: [{ databaseId: 70, name: "unit (1)", conclusion: "failure", steps: [{ name: "Set up", conclusion: "success" }, { name: "Run unit proof", conclusion: "failure" }] }, @@ -104,11 +106,21 @@ describe("one pull request's state", () => { const result = await status(github()); expect([result.code, result.lines]).toEqual([0, 1]); expect(result.json).toEqual({ pr: 42, state: "OPEN", draft: false, head: HEAD, baseRef: "main", liveBase: BASE, mergeable: "MERGEABLE", mergeState: "CLEAN", review: null, - mergeRef: { sha: MERGE, parents: [BASE, HEAD], current: true }, receipt: true, proof: "passed", + mergeRef: { sha: MERGE, parents: [BASE, HEAD], current: true }, receipt: true, reviewRecord: null, proof: "passed", checks: { total: 2, passed: 2, skipped: 0, pending: [], failed: [] }, runs: [{ id: 7, workflow: "CI", event: "pull_request", attempt: 1, status: "completed", conclusion: "failure" }] }); }); + test("the newest recorded review is summarized, and an unreadable one is reported, not hidden", async () => { + const comments = (...bodies: string[]) => ({ [`repos/${REPO}/issues/42/comments`]: { stdout: bodies.map(body => JSON.stringify(body)).join("\n") } }); + const review = (head: string, findings: Array<{ summary: string }> = []) => reviewComment({ version: 1, kind: "brain-review-receipt", pr: 42, head, base: BASE, reviewer: "agent", + outcome: findings.length ? "findings" : "no-findings", findings }); + const newest = await status(github(comments(review(OLD_BASE), "A later remark.", review(HEAD, [{ summary: "The mast is not lashed." }])))); + expect(newest.json.reviewRecord).toEqual({ head: HEAD, reviewer: "agent", findings: 1, undisposed: 1 }); + const broken = await status(github(comments(review(HEAD), `${REVIEW_START}\nno block end`))); + expect(broken.json.reviewRecord).toEqual({ unreadable: "Unterminated review record block" }); + }); + test("a merge commit that still has the old base as its parent is not current", async () => { const stale = await status(github({ [`repos/${REPO}/git/commits/${MERGE}`]: { stdout: JSON.stringify([OLD_BASE, HEAD]) } })); expect(stale.json.mergeRef).toEqual({ sha: MERGE, parents: [OLD_BASE, HEAD], current: false }); From e53070e27dee06f602f62d3d2f104d4e15af8cf5 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 17 Nov 2026 00:08:59 +0000 Subject: [PATCH 08/31] docs(process): record the independent-review ruling and write the review step (#4110) The 2026-11-16 maintainer decision gets its own section in the CI decision record, and the fast lane section cites the shared path predicate. The work-issue skill and its CI reference gain the step: when to request the review, how to start a reviewer that is given only the PR and its issue, how to answer findings and when a new review is needed. Co-Authored-By: Claude Fable 5.2 --- .agents/skills/work-issue/SKILL.md | 94 ++++++++++++++++++- .../work-issue/references/ci-and-merge.md | 28 +++++- .github/PULL_REQUEST_TEMPLATE.md | 1 + AGENTS.md | 4 +- docs/decisions/ci-utility.md | 61 +++++++++++- docs/process/github.md | 18 +++- docs/process/testing.md | 11 +++ scripts/skill-tests/skill-commands.test.ts | 18 ++++ 8 files changed, 225 insertions(+), 10 deletions(-) diff --git a/.agents/skills/work-issue/SKILL.md b/.agents/skills/work-issue/SKILL.md index 77f7180050..da896ef35a 100644 --- a/.agents/skills/work-issue/SKILL.md +++ b/.agents/skills/work-issue/SKILL.md @@ -31,14 +31,16 @@ when changing what packages ship, dependencies, versions or publishing. checks in [Select and claim](#select-and-claim). 2. `bun scripts/issue-queue.ts claim --branch /-`. 3. Read the issue and decide readiness ([Establish readiness](#establish-readiness)). - Not ready: label, comment, then step 8. + Not ready: label, comment, then step 9. 4. Create the issue checkout ([Prepare the issue checkout](#prepare-the-issue-checkout)). 5. Implement, with failing-first and mutation receipts ([Implement the scoped issue](#implement-the-scoped-issue)). 6. `bun run check:pr`, open the pull request, read its state with `bun scripts/pr-status.ts ` ([PR, CI and merge](#pr-ci-and-merge)). -7. Confirm and merge through `bun scripts/integrate.ts`. -8. Report the outcome on the issue and `bun scripts/issue-queue.ts release ` +7. If the PR touches a core package, get an independent review and record it + ([Independent review](#independent-review)). +8. Confirm and merge through `bun scripts/integrate.ts`. +9. Report the outcome on the issue and `bun scripts/issue-queue.ts release ` ([Finish or hand off](#finish-or-hand-off)). ### Spending few tokens @@ -309,7 +311,8 @@ with `bun scripts/integrate.ts confirm --issues owner/repo#N,...` before requesting expensive confirmation; it handles the draft-to-ready transition, minute renewal and shared proof-checked merge. The PR body must carry the `check:pr` receipt; skipped or timed-out local checks need exact-head hosted -coverage. A declared red-main fix may use `--fixes-main-run `. Hold competing confirmation and +coverage. A PR that touches a core package also needs its +[independent review](#independent-review) recorded first. A declared red-main fix may use `--fixes-main-run `. Hold competing confirmation and main merges while another lease is live. See the CI reference for explicit acquire/renew/release/revoke, expiry, hard cap and unsupported native candidates. After the last push, convert to draft and mark ready under that reservation to @@ -357,6 +360,89 @@ type/area/`contract` labels; do not copy readiness labels onto the PR. monitor actual completion. Do not ask again for permission included in the end-to-end request. +## Independent review + +A PR whose diff touches `packages/ui-react/`, `packages/ui-kit/`, +`packages/ui-server/` or `packages/core/` needs a recorded independent review +before `integrate.ts confirm` takes the reservation +([ruling](../../../docs/decisions/ci-utility.md#recorded-independent-review-of-core-package-prs)). +`bun scripts/review-receipt.ts check ` prints whether this PR needs one +(`required`) and, if so, why the merge path would refuse its current head +(`refusal`, or null). A PR outside those packages needs none: skip this +section. An expedited red-main fix (`--fixes-main-run`) is exempt. + +**When to request it.** After the implementation is complete, `check:pr` +passes and the branch is pushed, and before `confirm`. Requesting it earlier +wastes it, because every later commit needs another review. Draft CI and +hosted heavy feedback can run meanwhile. + +**How to start the reviewer.** The reviewer is a fresh agent context or a +human. It did not write the change, and it does not inherit the conversation +of the context that did. Give it only: + +- the PR number, so that it reads the diff, the description and the comments + itself; +- the issue the PR closes or advances; +- the head SHA to review, and a checkout it can read that head in; +- the task below. + +Never give it your summary of the change, your reasoning, a list of what to +look at or your view of the risk. If you cannot start a context that is free +of your own, ask a human to review instead. The task, with only the +placeholders filled in: + +> Review pull request #PR of schlessera/brain-kit at head SHA against issue +> #N. Read the issue's acceptance criteria and exclusions, then the whole diff +> against the base and the code around it. Report defects only: behaviour that +> misses a criterion, a missing or broken guard, a regression in a caller the +> diff did not touch, a test that cannot fail, a contract change without its +> record, a breach of the hard rules in AGENTS.md. Do not report style. Do not +> edit, push, comment or merge. Return the head SHA you read and a JSON array +> with one `{ "summary": "..." }` per finding: one line of at most 500 +> characters that names the file and line. Return an empty array if you found +> nothing. + +**Record the review as it was returned**, before answering it and without +dropping or rewording a finding you disagree with. Save the array to a file and +post it at the head the reviewer read (`--reviewer human` for a human): + +```sh +bun scripts/review-receipt.ts post --reviewer agent --head --findings +bun scripts/review-receipt.ts post --reviewer agent --head --no-findings +``` + +The command validates the record, runs it through the leakage gate and posts +it as one PR comment. It names the reviewer as `agent` or `human` and nothing +else; do not add a name, a model or a session. + +**Answer every finding.** Add exactly one disposition to each entry of the +findings file, then post the record again with the same `--head`. The newest +record is the one the merge path reads. + +- `"disposition": "fixed", "commit": ""`: the commit on this branch + that fixes it. A finding is one instance of a bug class, so grep the diff and + its file for the others before calling it fixed. +- `"disposition": "filed", "issue": "owner/repo#N"`: a real defect outside this + issue's scope. File it through the GitHub skill first. +- `"disposition": "rejected", "reason": ""`: not a defect, with + evidence a reader can check. + +**When a new review is needed.** A record covers the head the reviewer read, +plus any later merges of the base. + +- A new commit of your own, a rebase or an amend needs a review of the new + head. That includes a commit that fixes a finding. Batch your fixes into one + push, then start another fresh reviewer the same way and post its record. + The earlier record stays on the PR, so the new reviewer can see what was + found and how it was answered. +- Merging `origin/main` into the branch needs no new review. While you wait + for the lease, refresh by merge and push, never by rebase. +- Findings that are only filed or rejected add no commit, so they need no new + review. + +Run `bun scripts/review-receipt.ts check ` again before `confirm`. Never +write or edit the block by hand, and never record a review that did not happen. + ## Main is red When any command prints `main red at ` (the hosted gate, a cancelled diff --git a/.agents/skills/work-issue/references/ci-and-merge.md b/.agents/skills/work-issue/references/ci-and-merge.md index 2dd6fbe090..44a52e5338 100644 --- a/.agents/skills/work-issue/references/ci-and-merge.md +++ b/.agents/skills/work-issue/references/ci-and-merge.md @@ -101,7 +101,8 @@ synthetic merge commit has exactly that base and that head as its parents; `false` is the stale-base case described below. `checks.total` of zero means CI has not started on this head, which is not green; `proof` is `passed` only for a successful `proof` check on this head; `receipt` says whether the body -carries a `check:pr` receipt. When you need a single check's details, the +carries a `check:pr` receipt; `reviewRecord` summarizes the newest recorded +independent review, or is null. When you need a single check's details, the underlying reads are `gh pr view --json statusCheckRollup` and `gh api 'repos/schlessera/brain-kit/commits//check-runs'`. @@ -296,6 +297,25 @@ proof did not run, naming each. Rerun the check locally and paste the new receipt, or get the category selected; never edit a receipt by hand ([local check receipts](../../../../docs/decisions/ci-utility.md#local-check-receipts)). +The merge path also reads the recorded independent review of a PR that touches +`packages/ui-react/`, `packages/ui-kit/`, `packages/ui-server/` or +`packages/core/` +([ruling](../../../../docs/decisions/ci-utility.md#recorded-independent-review-of-core-package-prs)). +`confirm` refuses before it takes the reservation, and the merge checks again. +`bun scripts/review-receipt.ts check ` prints the same decision without +changing anything. Each refusal has one remedy: + +| Refusal | Remedy | +| --- | --- | +| No review record | Get the review and post its record: the skill's [Independent review](../SKILL.md#independent-review). | +| A finding without a disposition | Answer it as fixed, filed or rejected and post the record again. | +| Fixed in a commit the head does not contain | Name the commit on this branch that fixes it. | +| The head contains commits the reviewed head does not | Get a review of the current head. Merges of the base never cause this; a new commit, a rebase or an amend does. | +| The reviewed head can be neither read nor fetched | Get a review of the current head. | + +Refresh a reviewed branch by merging `origin/main` and pushing. A rebase +rewrites the reviewed commits and discards the record's coverage. + While main is red, a declared fix for the open record, forward fix or targeted revert alike, may use `bun scripts/integrate.ts confirm --fixes-main-run --issues owner/repo#N,...`. It dispatches fix probes @@ -323,10 +343,12 @@ A PR whose diff touches nothing under `packages/ui-react/`, `packages/ui-kit/`, Check the paths against the PR's actual base, not your local branch: ```sh -gh pr diff --name-only | grep -E '^packages/(ui-react|ui-kit|ui-server|core)/' && echo "full lane" +gh pr diff --name-only | bun scripts/fast-lane.ts ``` -If any path matches, use `integrate.ts confirm` as above. Otherwise: +It prints `"lane":"full"` with the core-package paths, or `"lane":"fast"`. +The same predicate decides which PRs need a recorded independent review. On +the full lane, use `integrate.ts confirm` as above. Otherwise: 1. Paste the `check:pr` receipt and set the milestones, exactly as for any other merge. diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index 217f573394..fd89186c9e 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -50,6 +50,7 @@ bun run check:pr --base origin/main - [ ] Focused local preflight/behavioral receipts and complete selected hosted proof passed; actual head/base/job checkout evidence is in Proof. - [ ] Acceptance criteria from the issue are all met, or the gap is named below. +- [ ] A PR touching `packages/ui-react/`, `packages/ui-kit/`, `packages/ui-server/` or `packages/core/` carries a recorded independent review of its head (`bun scripts/review-receipt.ts check `), or it touches none of them. - [ ] The PR and completed/advanced issues have verified release milestones under docs/process/github.md. - [ ] A changeset is included, or this changes nothing a consumer can see. - [ ] No personal data anywhere in the diff — the leakage gate covers the whole tree. diff --git a/AGENTS.md b/AGENTS.md index 5005f9797f..a963495746 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -175,7 +175,9 @@ write one, and which kind of test proves which claim: ([hybrid ruling](docs/decisions/ci-utility.md#hybrid-post-merge-heavy-proof)). A PR touching none of `ui-react`, `ui-kit`, `ui-server` or `core` under `packages/` may take the [fast lane](docs/decisions/ci-utility.md#fast-lane-outside-the-core-packages) - instead of ready confirmation. + instead of ready confirmation. A PR touching any of them needs a + [recorded independent review](docs/decisions/ci-utility.md#recorded-independent-review-of-core-package-prs) + before `integrate.ts confirm` will proceed. Subsequent pushes need a new confirmation request; every selected job must pass, and missing, cancelled or unexpectedly skipped jobs are not green. Policy: [the CI decision](docs/decisions/ci-utility.md) and diff --git a/docs/decisions/ci-utility.md b/docs/decisions/ci-utility.md index 530166972e..322c80d384 100644 --- a/docs/decisions/ci-utility.md +++ b/docs/decisions/ci-utility.md @@ -1880,7 +1880,10 @@ PRs below. `packages/ui-react/`, `packages/ui-kit/`, `packages/ui-server/` or `packages/core/`. Every other PR, and every epic landing, keeps [ready confirmation](#hybrid-post-merge-heavy-proof) through - `integrate.ts confirm`. + `integrate.ts confirm`. The path rule has one owner in code + (`touchesCorePackages`, `scripts/fast-lane.ts:19-21`), which the + [review requirement](#recorded-independent-review-of-core-package-prs) also + reads. - **What it skips.** The explicit ready-candidate run (`verify`, `pack`, `unit`). A qualifying PR merges on its exact head once these hold: - its newest CI run on that head has no failed or cancelled job, apart from @@ -1907,6 +1910,62 @@ lease, red-main refusal, main's complete affected proof and releases from a green main all still apply. A fast-lane merge is not a successful delivery until its main run is green. +## Recorded independent review of core-package PRs + +The maintainer decided on 2026-11-16 that a PR which touches the core packages +needs a recorded independent review before it is confirmed +([#4110](https://github.com/schlessera/brain-kit/issues/4110)). None of the +382 PRs merged to `main` between 2026-10-26 and 2026-11-16 carried a review. +The median PR changed 271 lines and merged 2.2 hours after it opened, and 37% +of the merged PRs were fixes. The author's own agent was the only reader of +most changes before they landed. + +- **Who.** The complement of the + [fast lane](#fast-lane-outside-the-core-packages): a PR whose diff against + its base touches `packages/ui-react/`, `packages/ui-kit/`, + `packages/ui-server/` or `packages/core/`. The same predicate decides both + (`touchesCorePackages`, `scripts/fast-lane.ts:19-21`). A fast-lane PR is + never asked, and its comments are not read + (`reviewGate`, `scripts/review-receipt.ts:190-193`). +- **What counts as independent.** A reviewer that did not write the change and + is given only the PR and its issue, never the author's summary or reasoning. + In practice that is a fresh agent context or a human. +- **The record.** One PR comment carrying a fixed block, written and posted by + `bun scripts/review-receipt.ts post`. It names the reviewed head, the base, + and the reviewer as `agent` or `human` and nothing more: an unknown field + refuses. Each finding has exactly one disposition: `fixed` naming the commit, + `filed` naming the issue or `rejected` with the reason. A review with no + findings says so explicitly. The comment passes the leakage gate before it is + posted. Only the newest record counts, and an unreadable newest record + refuses (`newestReview`, `scripts/review-receipt.ts:122-127`). +- **The gate.** `integrate.ts confirm` and `merge` refuse a core-package + candidate (`reviewRefusal`, `scripts/review-receipt.ts:168-184`) when: + - no record exists; + - the newest record has a finding without a disposition, or answers one as + `fixed` in a commit the candidate head does not contain; + - the candidate head contains a non-merge commit, not reachable from the + base, that the reviewed head does not contain + (`unreviewedCommits`, `scripts/review-receipt.ts:157-159`). + + `confirm` checks before it takes the reservation or requests candidate CI, + like the check receipt, and the merge reads the record again. +- **What keeps a record valid.** Merging the base into the branch adds only a + merge commit and commits the base already has, so a branch refreshed that + way, however often, keeps its record. A new commit, a rebase or an amend + needs a new review of the new head. That includes a commit that fixes a + finding. +- **Exempt.** An [expedited red-main fix](#expedited-red-main-fixes) + (`--fixes-main-run`), as it is from the check receipt. The next main run is + the backstop. + +**What it is not.** This is cooperative procedure, like the lease. It adds no +repository ruleset or branch protection, it does not review fast-lane PRs, and +it does not automate the reviewer. + +**Known cost.** The rule counts commits, so the content of a merge commit +itself, such as a conflict resolution made while merging the base, is not +compared with what the reviewer read. + ## Historical measurement and upstream guidance The following guidance records the paid-provider investigation which motivated diff --git a/docs/process/github.md b/docs/process/github.md index 0f6f0cf4ee..710460732f 100644 --- a/docs/process/github.md +++ b/docs/process/github.md @@ -293,7 +293,11 @@ sit in the Ready view as traps. behavioral receipts accompany complete selected hosted proof under #1326; drafts remain cheap, and failed/cancelled/missing selected jobs cannot merge. Assign and read back the PR and delivered issues' release milestones before - merging; follow [Milestones](#milestones) for release attribution. + merging; follow [Milestones](#milestones) for release attribution. A PR + that touches `packages/ui-react/`, `packages/ui-kit/`, `packages/ui-server/` + or `packages/core/` also needs a + [recorded independent review](#coordinating-confirmation-and-ordinary-merges) + before it is confirmed. 6. **Human handoff, when needed.** Once independent agent work is complete, update the body with the remaining action and its completion evidence, replace `agent-ready` with `needs: human`, and leave the issue open. Keep @@ -330,6 +334,18 @@ for the five-minute lease, sixty-minute cap, supported candidates, actual squash/main verification and direct-merge race limits. This cooperative policy changes no GitHub protection or merge permissions. +`confirm` and `merge` also refuse a PR that touches the core packages +(`packages/ui-react/`, `packages/ui-kit/`, `packages/ui-server/`, +`packages/core/`) until it carries a recorded independent review that covers +its head: one PR comment written by `bun scripts/review-receipt.ts post`, +after a fresh agent context or a human has reviewed the PR given only the PR +and its issue. Every finding in it has one disposition: fixed, filed or +rejected with a reason. Refresh a reviewed branch by merging the base, not by +rebasing, so that the record stays valid. The +[decision](../decisions/ci-utility.md#recorded-independent-review-of-core-package-prs) +has the rule; the [work-issue skill](../../.agents/skills/work-issue/SKILL.md#independent-review) +has the steps. + ## Stacked pull requests Use a stack when independently reviewable slices depend on each other. A single diff --git a/docs/process/testing.md b/docs/process/testing.md index bf7d70c538..a5cb962182 100644 --- a/docs/process/testing.md +++ b/docs/process/testing.md @@ -531,6 +531,17 @@ in the [CI and merge reference](../../.agents/skills/work-issue/references/ci-an [fast lane](../decisions/ci-utility.md#fast-lane-outside-the-core-packages): it skips ready-candidate confirmation and is proved by its `check:pr` receipt and its squash's main run. +- A PR that does touch one of those four packages needs a recorded + independent review before `integrate.ts confirm` or `merge` will proceed + ([ruling](../decisions/ci-utility.md#recorded-independent-review-of-core-package-prs)). + The reviewer is a fresh agent context or a human, given only the PR and its + issue and never the author's summary. `bun scripts/review-receipt.ts post` + records the reviewed head and every finding with one disposition (`fixed`, + `filed` or `rejected`) as a PR comment. Merging the base into the branch + keeps the record valid; a new commit, a rebase or an amend needs a new + review. `bun scripts/review-receipt.ts check ` prints the merge path's + decision. The review is proof that someone else read the change, not a + substitute for any check above. An expedited red-main fix is exempt. - Run `bun run check:pr --base origin/main` before opening or marking ready, and paste the receipt block it prints into the PR body. Record a check you cannot finish with `--check-timeout=` or `--skip ` diff --git a/scripts/skill-tests/skill-commands.test.ts b/scripts/skill-tests/skill-commands.test.ts index 7cc5e8b4b3..b9e6b96964 100644 --- a/scripts/skill-tests/skill-commands.test.ts +++ b/scripts/skill-tests/skill-commands.test.ts @@ -66,3 +66,21 @@ describe("the tracker commands the skills name", () => { expect(unread).toEqual([]); }); }); + +describe("the review commands the skills name", () => { + const source = read("scripts/review-receipt.ts"); + const named = invocations(TRACKER_SKILLS.map(read).join("\n"), "review-receipt.ts"); + + test("the review step is written down with its commands", () => { + expect(named.length).toBeGreaterThanOrEqual(4); + expect(new Set(named.map(entry => entry.sub))).toEqual(new Set(["post", "check"])); + }); + + test("every subcommand and flag is one the script reads", () => { + const subcommands = /\["([a-z]+)", "([a-z]+)"\]\.includes\(command/.exec(source)!.slice(1, 3); + expect(subcommands).toEqual(["post", "check"]); + const flags = new Set([...source.matchAll(/\[((?:"[a-z-]+"(?:, )?)+)\]\.includes\(arg\.slice\(2\)\)/g)].flatMap(match => [...match[1]!.matchAll(/"([a-z-]+)"/g)].map(flag => flag[1]!))); + expect([...flags].sort()).toEqual(["base", "dry-run", "findings", "head", "no-findings", "repo", "reviewer"]); + expect(named.flatMap(entry => entry.flags.filter(flag => !flags.has(flag)).map(flag => `review-receipt --${flag}: ${entry.line}`))).toEqual([]); + }); +}); From 7cd80eca0140965cffbba7624743d2cf1c4e476b Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 17 Nov 2026 00:14:31 +0000 Subject: [PATCH 09/31] chore(ci): keep finding text inside the record's code fence and verify the comment reads back (#4110) A finding's summary can contain a mention or an issue reference. Outside a code fence GitHub would notify or link it, so the comment now carries the findings only inside the block, pretty-printed, under one line of counts. post refuses a comment its own reader cannot parse back. The decision record's citations follow the lines this change and the gate's import moved. Co-Authored-By: Claude Fable 5.2 --- docs/decisions/ci-utility.md | 10 +++++----- scripts/review-receipt.ts | 27 ++++++++++++++++----------- tests/review-receipt.test.ts | 14 +++++++++++--- 3 files changed, 32 insertions(+), 19 deletions(-) diff --git a/docs/decisions/ci-utility.md b/docs/decisions/ci-utility.md index 322c80d384..ec1e95b7b1 100644 --- a/docs/decisions/ci-utility.md +++ b/docs/decisions/ci-utility.md @@ -1568,7 +1568,7 @@ GitHub did not record, or whose ancestry cannot be determined, is left alone. So proof for a PR against an integration or release branch forked before the bad commit keeps running. `integrate.ts` applies the same rule to the candidate's base and head before confirming or merging, and refuses when -ancestry is unknown (`refuseWhileRed`, `scripts/integrate.ts:87-91`). A non-fix squash +ancestry is unknown (`refuseWhileRed`, `scripts/integrate.ts:88-92`). A non-fix squash that lands while red is reported once on its PR and on the incident, and recorded as an `incident` event through `scripts/ci-timings.ts record` in the coordinator's `red-main-events` artifact. @@ -1926,7 +1926,7 @@ most changes before they landed. `packages/ui-server/` or `packages/core/`. The same predicate decides both (`touchesCorePackages`, `scripts/fast-lane.ts:19-21`). A fast-lane PR is never asked, and its comments are not read - (`reviewGate`, `scripts/review-receipt.ts:190-193`). + (`reviewGate`, `scripts/review-receipt.ts:191-194`). - **What counts as independent.** A reviewer that did not write the change and is given only the PR and its issue, never the author's summary or reasoning. In practice that is a fresh agent context or a human. @@ -1937,15 +1937,15 @@ most changes before they landed. `filed` naming the issue or `rejected` with the reason. A review with no findings says so explicitly. The comment passes the leakage gate before it is posted. Only the newest record counts, and an unreadable newest record - refuses (`newestReview`, `scripts/review-receipt.ts:122-127`). + refuses (`newestReview`, `scripts/review-receipt.ts:123-128`). - **The gate.** `integrate.ts confirm` and `merge` refuse a core-package - candidate (`reviewRefusal`, `scripts/review-receipt.ts:168-184`) when: + candidate (`reviewRefusal`, `scripts/review-receipt.ts:169-185`) when: - no record exists; - the newest record has a finding without a disposition, or answers one as `fixed` in a commit the candidate head does not contain; - the candidate head contains a non-merge commit, not reachable from the base, that the reviewed head does not contain - (`unreviewedCommits`, `scripts/review-receipt.ts:157-159`). + (`unreviewedCommits`, `scripts/review-receipt.ts:158-160`). `confirm` checks before it takes the reservation or requests candidate CI, like the check receipt, and the merge reads the record again. diff --git a/scripts/review-receipt.ts b/scripts/review-receipt.ts index bcb70a808f..ac5595299e 100644 --- a/scripts/review-receipt.ts +++ b/scripts/review-receipt.ts @@ -76,21 +76,22 @@ export function parseReview(value: unknown): ReviewRecord { export const undisposed = (record: ReviewRecord) => record.findings.filter(finding => !("disposition" in finding)); -/** The fixed block the comment carries; the merge path reads nothing else. */ +/** + * The fixed block the comment carries; the merge path reads nothing else. The + * findings' own words appear only here, inside a code fence, where a `@name` + * or a `#123` in a summary is text and notifies or links nobody. + */ export function reviewBlock(record: ReviewRecord): string { - return [REVIEW_START, "```json", JSON.stringify(record), "```", REVIEW_END].join("\n"); + return [REVIEW_START, "```json", JSON.stringify(record, null, 2), "```", REVIEW_END].join("\n"); } -/** The whole comment: the same facts as prose for a reader, then the block. */ +/** The whole comment: one line of counts for a reader, then the block. */ export function reviewComment(record: ReviewRecord): string { - const line = (finding: ReviewFinding) => !("disposition" in finding) ? `**no disposition yet**: ${finding.summary}` - : finding.disposition === "fixed" ? `**fixed** in ${finding.commit}: ${finding.summary}` - : finding.disposition === "filed" ? `**filed** as ${finding.issue}: ${finding.summary}` - : `**rejected**: ${finding.summary} Reason: ${finding.reason}`; - return ["## Independent review", "", - `Reviewed head ${record.head} against base ${record.base}. Reviewer: ${record.reviewer}.`, "", - record.findings.length ? record.findings.map((finding, index) => `${index + 1}. ${line(finding)}`).join("\n") : "No findings.", "", - reviewBlock(record)].join("\n"); + const count = (disposition: string) => record.findings.filter(finding => "disposition" in finding && finding.disposition === disposition).length; + const outcome = record.findings.length + ? `${record.findings.length} finding${record.findings.length === 1 ? "" : "s"}: ${count("fixed")} fixed, ${count("filed")} filed, ${count("rejected")} rejected, ${undisposed(record).length} without a disposition.` + : "No findings."; + return ["## Independent review", "", `Reviewed head ${record.head} against base ${record.base}. Reviewer: ${record.reviewer}. ${outcome}`, "", reviewBlock(record)].join("\n"); } /** The record one comment carries: null when it has no block; an unreadable or doubled block refuses. */ @@ -248,6 +249,10 @@ export async function main(argv: readonly string[], io: ReviewIo): Promise { expect(reviewFromBody(reviewComment(full).replace(/\n/g, "\r\n"))).toEqual(full); const none = record(head, base); expect(none.outcome).toBe("no-findings"); - expect(reviewComment(none)).toContain("No findings."); + expect(reviewComment(none)).toContain("Reviewer: agent. No findings."); + expect(reviewComment(full)).toContain("3 findings: 1 fixed, 1 filed, 1 rejected, 0 without a disposition."); + // A summary's own words stay inside the code fence: outside it, a mention would notify someone. + const mention = reviewComment(record(head, base, [{ summary: "@odysseus left #12 open." }])); + expect(mention.slice(0, mention.indexOf(REVIEW_START)), "FINDING_TEXT_ONLY_IN_THE_FENCE").not.toContain("@odysseus"); + expect(reviewFromBody(mention)?.findings).toEqual([{ summary: "@odysseus left #12 open." }]); expect(() => parseReview({ ...none, outcome: "findings" }), "EMPTY_LIST_IS_NOT_A_STATEMENT").toThrow("no-findings exactly when"); expect(() => parseReview({ ...full, outcome: "no-findings" })).toThrow("no-findings exactly when"); }); @@ -61,7 +66,7 @@ describe("the record", () => { expect(() => parseReview({ ...full, reviewer: "Odysseus" }), "REVIEWER_KIND_ONLY").toThrow("Invalid review record"); expect(() => parseReview({ ...full, reviewerName: "Odysseus" }), "NO_EXTRA_RECORD_FIELD").toThrow("Invalid review record"); expect(() => parseReview({ ...full, findings: [{ summary: "The mast is not lashed.", author: "Odysseus" }] }), "NO_EXTRA_FINDING_FIELD").toThrow("Invalid review finding"); - expect(Object.keys(JSON.parse(/```json\n(.*)\n```/.exec(reviewBlock(full))![1]!)).sort()).toEqual(["base", "findings", "head", "kind", "outcome", "pr", "reviewer", "version"]); + expect(Object.keys(JSON.parse(/```json\n([\s\S]*)\n```/.exec(reviewBlock(full))![1]!)).sort()).toEqual(["base", "findings", "head", "kind", "outcome", "pr", "reviewer", "version"]); }); test("gives each finding at most one disposition, with exactly the detail that disposition names", () => { @@ -253,8 +258,11 @@ describe("the command", () => { await expect(run(gh, root, "post", "7", "--reviewer", "agent", "--head", reviewed, "--findings", findingsFile(root, []))).rejects.toThrow("use --no-findings"); await expect(run(gh, root, "post", "7", "--reviewer", "agent", "--head", reviewed, "--findings", findingsFile(root, [{ summary: "x", reviewer: "Odysseus" }]))).rejects.toThrow("Invalid review finding"); const open = findingsFile(root, [{ summary: "The mast is not lashed." }]); + const outside = mkdtempSync(join(tmpdir(), "odysseus-review-findings-")); dirs.push(outside); const dry = await run(gh, root, "post", "7", "--reviewer", "agent", "--head", reviewed, "--findings", open, "--dry-run"); - expect(dry.out).toContain("**no disposition yet**: The mast is not lashed."); + expect(dry.out).toContain("1 finding: 0 fixed, 0 filed, 0 rejected, 1 without a disposition."); + await expect(run(gh, root, "post", "7", "--reviewer", "agent", "--head", reviewed, "--findings", findingsFile(outside, [{ summary: `The block ends at ${REVIEW_END} too early.` }])), + "UNREADABLE_COMMENT_NEVER_POSTED").rejects.toThrow("does not read back from its own comment"); expect(posted).toEqual([]); // An unanswered review can be recorded as it stands; the gate refuses it until it is answered. const recorded = await run(gh, root, "post", "7", "--reviewer", "agent", "--head", reviewed, "--findings", open); From cb4128588f23adc529cd6b20ee6ccb9b0ed97b02 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 17 Nov 2026 00:17:27 +0000 Subject: [PATCH 10/31] chore(ci): repeat changed Bun test files under CPU load (#4109) Add bun scripts/test-determinism.ts. It selects the Bun test files a change adds or modifies against its merge base and runs them through the offline test wrapper with --rerun-each and --bail=1 while one busy loop per CPU runs. Five repetitions by default, reduced uniformly to a floor of two when the reviewed weights exceed the 600-second budget; no selected file is skipped and the report lists each with its repetitions. Burners are killed by PID on every exit path and exit by themselves when their parent dies. The planner records the selection for pull requests and selects determinism at every pull-request cadence, drafts included, and never on main. Co-Authored-By: Claude Fable 5.2 --- scripts/ci-plan.ts | 26 ++- scripts/test-determinism.ts | 310 +++++++++++++++++++++++++++++++++ tests/candidate-proof.test.ts | 10 +- tests/ci-plan.test.ts | 46 ++++- tests/test-determinism.test.ts | 299 +++++++++++++++++++++++++++++++ 5 files changed, 683 insertions(+), 8 deletions(-) create mode 100644 scripts/test-determinism.ts create mode 100644 tests/test-determinism.test.ts diff --git a/scripts/ci-plan.ts b/scripts/ci-plan.ts index d199e2c85b..f5313502b5 100644 --- a/scripts/ci-plan.ts +++ b/scripts/ci-plan.ts @@ -149,6 +149,8 @@ export interface CheckPlan { local: { fullTests: boolean; browser: boolean; layout: boolean; captures: boolean; runtime: boolean; endurance: boolean }; /** Main pushes also prove the open red-main record's failures (#2942). */ redMain?: IncludedRedSet; + /** Bun test files a pull request adds or modifies; each repeats under CPU load before merge (#4109). */ + determinism?: string[]; } export function workspaces(root: string): Workspace[] { @@ -307,7 +309,22 @@ export function planChecks(changed: readonly string[], packages: readonly Worksp // Explicit roots identify a real harness; two-argument synthetic workspace diagnostics stay conservative. const explicitRoot = arguments.length >= 3; const plan = planBeforeBrowserClosures(changed, packages, root, enableConsumerSelection, explicitRoot); - return explicitRoot && !plan.global ? selectBrowserClosures(plan, discoverBrowserClosures(root)) : plan; + const selected = explicitRoot && !plan.global ? selectBrowserClosures(plan, discoverBrowserClosures(root)) : plan; + // Main pushes and their red-main replans pass enableConsumerSelection=false: repetition is pre-merge proof. + const determinism = explicitRoot && enableConsumerSelection ? determinismTests(root, changed) : []; + return determinism.length ? { ...selected, determinism } : selected; +} + +/** + * The Bun test files among `changed` that exist in this checkout: what a + * change adds or modifies, never what it deletes (#4109). Same roots, name + * suffixes and directory exclusions as `discoverTests` (scripts/test-shards.ts). + */ +export function determinismTests(root: string, changed: readonly string[]): string[] { + return [...new Set(changed)].filter(path => /^(?:packages|tests)\//.test(path) && + /(?:\.test|\.spec|_test|_spec)\.(?:[cm]?[jt]s|[jt]sx)$/i.test(basename(path)) && + !path.split("/").slice(0, -1).some(part => part.startsWith(".") || part.toLowerCase() === "node_modules") && + lstatSync(join(root, path), { throwIfNoEntry: false })?.isFile() === true).sort(); } /** @@ -425,11 +442,14 @@ export function proofSelections(plan: CheckPlan, draft = false): Record 0; + return { ...Object.fromEntries(Object.entries({ verify: plan.typecheck || ((feedback || !plan.local.fullTests) && plan.tests.length > 0), pack: !feedback && plan.pack, unit: !feedback && plan.local.fullTests, browser: !feedback && plan.local.browser, layout: !feedback && plan.local.layout, captures: !feedback && plan.local.captures, runtime: !feedback && plan.local.runtime, runtime_host: !feedback && plan.local.runtime, endurance: !feedback && plan.local.endurance, - }).map(([name, selected]) => [name, !draft && !(confirmation && isPostMerge(name as Category)) && selected])); + }).map(([name, selected]) => [name, !draft && !(confirmation && isPostMerge(name as Category)) && selected])), determinism }; } function git(root: string, args: string[]): string { diff --git a/scripts/test-determinism.ts b/scripts/test-determinism.ts new file mode 100644 index 0000000000..abc82d3ad3 --- /dev/null +++ b/scripts/test-determinism.ts @@ -0,0 +1,310 @@ +/** + * Repeats a change's added or modified Bun test files under CPU load (#4109). + * + * Most red-main incidents were cleared by changing only a test: a racy wait, an + * unpinned clock, a deadline a loaded shard missed. Such a test passes once and + * fails later on someone else's merge. This command runs each changed file + * several times before it merges, while busy loops occupy the CPUs. + * + * bun scripts/test-determinism.ts --base origin/main [--json] + * bun scripts/test-determinism.ts tests/a.test.ts ... # an explicit selection (hosted job) + * + * The files run in one invocation of the offline wrapper (`bun run test`, + * scripts/test.ts), so its preload, lease and single preparation build apply, + * with Bun's `--rerun-each= --bail=1`. Verified against Bun 1.4.2: each file + * runs n times in a row in one process, its module is evaluated again for each + * run, `globalThis` and process state persist between runs, and a run with + * output is headed `: (run #k)` on stderr. A file that leaks state into + * its next run therefore fails here too. + * + * Bounded: five repetitions by default, reduced uniformly to a floor of two + * when the reviewed weights (scripts/test-shard-costs.json) exceed the budget. + * No selected file is dropped; the report lists each with its repetitions. + * Policy: docs/decisions/ci-utility.md, "Changed tests repeat under load before merge". + */ +import { appendFileSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { availableParallelism, constants } from "node:os"; +import { dirname, join, resolve } from "node:path"; +import { changedFiles, determinismTests } from "./ci-plan"; +import { ensureHostAdmission } from "./host-admission.mjs"; +import { discoverTests, FILE_COST_SECONDS } from "./test-shards"; + +export const DEFAULT_REPETITIONS = 5; +export const FLOOR_REPETITIONS = 2; +/** Total reviewed-weight seconds the repetitions may cost before they are reduced. */ +export const BUDGET_SECONDS = 600; +/** A file without a reviewed weight costs the small-file default (scripts/test-shards.ts). */ +const UNWEIGHTED_SECONDS = 0.1; +/** A burner outlives its parent by one slice at most, and never this long. */ +const BURNER_LIFETIME_MS = 2 * 60 * 60_000, BURNER_SLICE_MS = 200; +export const REPORT_KIND = "brain-test-determinism"; +const JUNIT_PATH = "tmp/determinism-junit.xml"; + +export interface FileRepetitions { file: string; weightSeconds: number; weighted: boolean; repetitions: number; observed?: number; } +export interface RepetitionPlan { + requested: number; floor: number; repetitions: number; reduced: boolean; + budgetSeconds: number; weightSeconds: number; estimatedSeconds: number; overBudget: boolean; + files: FileRepetitions[]; +} +export interface Failure { file: string | null; repetition: number | null; test: string | null; reason: string; } +export interface Report extends RepetitionPlan { + kind: typeof REPORT_KIND; version: 1; base: string | null; + outcome: "passed" | "failed" | "none-selected"; + failure: Failure | null; load: { burners: number; cpus: number }; elapsedSeconds: number; exitCode: number; +} + +/** + * The same count for every file: the most repetitions that fit the budget, + * never more than requested and never fewer than the floor. A selection too + * heavy for the floor still runs at the floor and is reported over budget. + */ +export function planRepetitions(files: readonly string[], options: { repetitions?: number; floor?: number; budgetSeconds?: number; + costs?: Readonly> } = {}): RepetitionPlan { + const requested = options.repetitions ?? DEFAULT_REPETITIONS, floor = options.floor ?? FLOOR_REPETITIONS; + const budgetSeconds = options.budgetSeconds ?? BUDGET_SECONDS, costs = options.costs ?? FILE_COST_SECONDS; + if (!Number.isSafeInteger(floor) || floor < 2) throw new Error("The repetition floor is at least two: one run proves nothing about the next"); + if (!Number.isSafeInteger(requested) || requested < floor) throw new Error(`Repetitions must be an integer of at least ${floor}`); + if (!Number.isFinite(budgetSeconds) || budgetSeconds <= 0) throw new Error("The time budget must be positive seconds"); + if (new Set(files).size !== files.length) throw new Error("A test file was selected twice"); + const weights = files.map(file => { + const weighted = Object.hasOwn(costs, file), weightSeconds = weighted ? costs[file]! : UNWEIGHTED_SECONDS; + if (!Number.isFinite(weightSeconds) || weightSeconds <= 0) throw new Error(`Test file costs must be positive finite seconds: ${file}`); + return { file, weightSeconds, weighted }; + }); + const weightSeconds = weights.reduce((sum, entry) => sum + entry.weightSeconds, 0); + const fit = weightSeconds > 0 ? Math.floor(budgetSeconds / weightSeconds) : requested; + const repetitions = Math.max(floor, Math.min(requested, fit)); + const estimatedSeconds = weightSeconds * repetitions; + return { requested, floor, repetitions, reduced: repetitions < requested, budgetSeconds, weightSeconds, estimatedSeconds, + overBudget: estimatedSeconds > budgetSeconds, files: weights.map(entry => ({ ...entry, repetitions })) }; +} + +/** The wrapper's argv: one invocation, so preparation builds once for every repetition. */ +export function repetitionArgv(files: readonly string[], repetitions: number): string[] { + return [process.execPath, "run", "test", `--rerun-each=${repetitions}`, "--bail=1", + "--reporter=junit", `--reporter-outfile=${JUNIT_PATH}`, ...files.map(file => `./${file}`)]; +} + +const plain = (text: string) => text.replace(/\x1b\[[0-9;]*m/g, ""); + +/** + * The first failure in the wrapper's stderr: Bun heads a run's output with + * `: (run #k)` and reports the case as `(fail) [