mirror of
https://github.com/garrytan/gstack.git
synced 2026-11-29 19:34:29 +01:00
Remove the /cso test files, CI workflows and docs ahead of removing /cso (GST-3920) (#4837)
Deletes the tests, test fixtures, CI workflows, scripts and docs that exist only for /cso. Nothing changes for anyone using gstack. Why: this is the first half of removing /cso. The whole removal is too big to review in one pull request, so #4833 removes the skill and its helper code next. Nothing to do: #4833 lands right after this one. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
This commit is contained in:
1 parent
1145e80a47
commit
fd7e8c7b36
113 files changed
+47
-19061
No files matched your search
@@ -1,29 +0,0 @@
|
||||
#!/usr/bin/env -S bun --no-env-file --config=/dev/null
|
||||
/** Bind cryptographically verified `gh attestation verify --format json` output to reviewed statements. */
|
||||
import * as fs from 'node:fs';
|
||||
import { resolve } from 'node:path';
|
||||
import { canonical, sha256 } from '../lib/cso/contracts';
|
||||
|
||||
const HASH=/^[a-f0-9]{64}$/,MAX_BYTES=4*1024*1024;
|
||||
|
||||
export function verifiedStatementSetDigest(value:unknown,predicateType:string,subjectSha256:string):string{
|
||||
if(!Array.isArray(value)||!value.length||typeof predicateType!=='string'||!/^https:\/\/[A-Za-z0-9./_-]+$/.test(predicateType)||!HASH.test(subjectSha256))throw new Error('INVALID_VERIFIED_ATTESTATION_SET');
|
||||
const statements:string[]=[];
|
||||
for(const item of value){
|
||||
if(!item||typeof item!=='object'||Array.isArray(item))throw new Error('INVALID_VERIFIED_ATTESTATION_SET');
|
||||
const result=(item as any).verificationResult,statement=result?.statement;
|
||||
if(!statement||typeof statement!=='object'||Array.isArray(statement)||statement.predicateType!==predicateType||!Array.isArray(statement.subject)||
|
||||
!statement.subject.some((subject:any)=>subject&&typeof subject==='object'&&subject.digest?.sha256===subjectSha256))throw new Error('VERIFIED_ATTESTATION_IDENTITY_MISMATCH');
|
||||
statements.push(canonical(statement));
|
||||
}
|
||||
statements.sort();return`sha256:${sha256(canonical(statements))}`;
|
||||
}
|
||||
|
||||
if(import.meta.main){
|
||||
try{
|
||||
const args=process.argv.slice(2),command=args.shift(),file=args.shift(),predicate=args.shift(),subject=args.shift();
|
||||
if(command!=='digest'||!file||!predicate||!subject||args.length)throw new Error('Usage: cso-attestation-evidence digest VERIFIED.json PREDICATE SUBJECT_SHA256');
|
||||
const path=resolve(file),stat=fs.lstatSync(path);if(!stat.isFile()||stat.isSymbolicLink()||stat.nlink!==1||stat.size<=0||stat.size>MAX_BYTES)throw new Error('UNSAFE_VERIFIED_ATTESTATION_FILE');
|
||||
process.stdout.write(verifiedStatementSetDigest(JSON.parse(fs.readFileSync(path,'utf8')),predicate,subject)+'\n');
|
||||
}catch(error){process.stderr.write((error instanceof Error?error.message:'ATTESTATION_EVIDENCE_ERROR')+'\n');process.exitCode=1;}
|
||||
}
|
||||
@@ -1,984 +0,0 @@
|
||||
#!/usr/bin/env -S bun --no-env-file --config=/dev/null
|
||||
/** Trusted corpus preparation, producer receipt collection, and objective result accounting. */
|
||||
import { createHash } from 'node:crypto';
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import { existsSync, lstatSync, mkdirSync, readdirSync, realpathSync } from 'node:fs';
|
||||
import { dirname, join, resolve } from 'node:path';
|
||||
import { readBoundedStable } from '../lib/cso/bounded-file';
|
||||
import { canonical } from '../lib/cso/contracts';
|
||||
import { validateRuntimeCatalog, type RuntimeCatalog } from '../lib/cso/runtime-catalog';
|
||||
import { EMPTY_GLOBAL_GIT_CONFIG, executable } from '../lib/cso/process';
|
||||
import { atomicWriteSync } from '../lib/fs-atomic';
|
||||
import { loadCorpusManifest, materializeCase, publicCorpus, STACKS, validateCorpusManifest, type CorpusManifest, type EvalCorpus, type EvalStack, type EvalVariant } from '../test/fixtures/cso-eval/materialize';
|
||||
import {
|
||||
PRODUCER_PLATFORMS,
|
||||
producerArtifactInventoryHash,
|
||||
producerExecution,
|
||||
producerInputHash,
|
||||
producerInstallationIdentityHash,
|
||||
producerProviderIdentityHash,
|
||||
producerReceiptHash,
|
||||
sha256,
|
||||
type ProducerCell,
|
||||
type ProducerArtifactInventory,
|
||||
type ProducerHost,
|
||||
type ProducerInput,
|
||||
type ProducerInstallationIdentity,
|
||||
type ProducerPlatform,
|
||||
type ProducerProviderIdentity,
|
||||
type ProducerReceipt,
|
||||
type ProducerReceiptIndex,
|
||||
type ProducerSourceEntry,
|
||||
} from './cso-eval-protocol';
|
||||
|
||||
export type EvalVersion = 'v2' | 'v3';
|
||||
export type EvalMode = 'daily' | 'comprehensive';
|
||||
export type Outcome = 'passed' | 'failed' | 'blocked' | 'not_attempted';
|
||||
/**
|
||||
* full: matched v2/v3 × 3 repetitions on one producer installation.
|
||||
* release: v3 only, 1 repetition, each cell pinned to a native platform.
|
||||
* baseline: v2 comprehensive only, 1 repetition; scored into a reusable EvalBaseline.
|
||||
*/
|
||||
export type EvalProfile = 'full' | 'release' | 'baseline';
|
||||
export type EvalPlatform = ProducerPlatform;
|
||||
type EvalCorpusManifest = CorpusManifest<string>;
|
||||
export interface EvalCell extends ProducerCell {
|
||||
id: string; caseId: string; stack: EvalStack; variant: EvalVariant; version: EvalVersion; mode: EvalMode;
|
||||
repetition: 1 | 2 | 3; model: string; host: ProducerHost; budgetSeconds: number; sourceHash: string; skillHash: string; platform?: EvalPlatform;
|
||||
}
|
||||
interface EvalMatrixBase {
|
||||
schemaVersion: 1; corpusVersion: string; corpusHash: string; model: string; host: ProducerHost;
|
||||
budgets: { daily: number; comprehensive: number }; cells: EvalCell[];
|
||||
}
|
||||
export interface FullEvalMatrix extends EvalMatrixBase { profile?: undefined; skillHashes: { v2: string; v3: string }; repetitions: 3 }
|
||||
export interface ReleaseEvalMatrix extends EvalMatrixBase {
|
||||
profile: 'release'; skillHashes: { v3: string }; repetitions: 1;
|
||||
/** Daily cells run on one platform; each comprehensive case is fixed to one platform. */
|
||||
platforms: { daily: EvalPlatform; comprehensive: Record<string, EvalPlatform> };
|
||||
/** Pre-registered external v2 baseline, or null when the regression gate stays unmeasured. */
|
||||
baselineHash: string | null;
|
||||
}
|
||||
export interface BaselineEvalMatrix extends EvalMatrixBase {
|
||||
profile: 'baseline'; skillHashes: { v2: string }; repetitions: 1;
|
||||
platforms: { comprehensive: Record<string, EvalPlatform> };
|
||||
}
|
||||
export type EvalMatrix = FullEvalMatrix | ReleaseEvalMatrix | BaselineEvalMatrix;
|
||||
interface EvalMatrixCommonOptions { model: string; host: ProducerHost; budgets?: { daily: number; comprehensive: number } }
|
||||
export interface FullEvalMatrixOptions extends EvalMatrixCommonOptions { profile?: 'full'; skillHashes: { v2: string; v3: string } }
|
||||
export interface ReleaseEvalMatrixOptions extends EvalMatrixCommonOptions { profile: 'release'; skillHashes: { v3: string }; platforms: ReleaseEvalMatrix['platforms']; baseline?: EvalBaseline }
|
||||
export interface BaselineEvalMatrixOptions extends EvalMatrixCommonOptions { profile: 'baseline'; skillHashes: { v2: string }; platforms: BaselineEvalMatrix['platforms'] }
|
||||
export type EvalMatrixOptions = FullEvalMatrixOptions | ReleaseEvalMatrixOptions | BaselineEvalMatrixOptions;
|
||||
/**
|
||||
* A scored v2 comprehensive run, reused by release matrices while every bound
|
||||
* input is unchanged. Release matrices pin its hash before results exist.
|
||||
*/
|
||||
export interface EvalBaseline {
|
||||
schemaVersion: 1; version: 'v2';
|
||||
corpusVersion: string; corpusHash: string; model: string; host: ProducerHost; budgetSeconds: number; skillHash: string;
|
||||
platforms: Record<string, EvalPlatform>;
|
||||
matrixHash: string; producerBatchHash: string; modelUsed: string;
|
||||
provider: { family: ProducerProviderIdentity['family']; policyRevision: string; version: string };
|
||||
/** One entry per corpus case, in manifest order: whether the vulnerable cell found the seeded issue. */
|
||||
cases: Array<{ caseId: string; found: boolean }>;
|
||||
baselineHash: string;
|
||||
}
|
||||
export interface PortableSkillFile {
|
||||
path: string;
|
||||
contents: string;
|
||||
}
|
||||
export interface PortableSkillFileIdentity {
|
||||
path: string;
|
||||
sha256: string;
|
||||
bytes: number;
|
||||
}
|
||||
export interface PortableSkillPayloadIdentity {
|
||||
schemaVersion: 1;
|
||||
version: EvalVersion;
|
||||
files: PortableSkillFileIdentity[];
|
||||
}
|
||||
export interface EvalFinding {
|
||||
id: string; evidence: 'supported' | 'hypothesis' | 'legacy_review'; claimedTested: boolean;
|
||||
/**
|
||||
* Written only by the independent evaluator after reviewing the reported trace. `correct`: the seeded issue.
|
||||
* `incidental`: a different issue a unanimous judge panel confirmed is real in this source; a precision true
|
||||
* positive, never recall. `instrumentation`: it targets the evaluator's declared fixture instrumentation
|
||||
* (canary overlay files, egress probe), so precision leaves it out of both terms.
|
||||
*/
|
||||
judgment: 'correct' | 'incidental' | 'instrumentation' | 'incorrect' | 'unadjudicated'; matchedCaseId?: string;
|
||||
/** `incidental` only: the evaluator's opaque key for the confirmed issue, so restatements count once per cell. */
|
||||
incidentalKey?: string;
|
||||
/**
|
||||
* Written only by the independent evaluator. A producer's tested claim is
|
||||
* valid only when this finding, rather than merely another finding in the
|
||||
* same corpus cell, owns the trusted repair and recheck observations.
|
||||
*/
|
||||
trustedVerification?: {
|
||||
repair: Outcome;
|
||||
repairEvidenceHash?: string;
|
||||
recheck: Outcome;
|
||||
recheckEvidenceHash?: string;
|
||||
};
|
||||
/**
|
||||
* Written only by the independent evaluator, for a tested claim on an `incidental` finding: the result of
|
||||
* replaying the helper's signed repair bundle for that finding against the trusted source. `passed` (with the
|
||||
* replay's evidence hash) certifies the claim; `failed` or `missing` (no bound bundle) leaves it falsely tested.
|
||||
* It never counts toward recall, repair or held-out rates, which need the seeded issue.
|
||||
*/
|
||||
trustedReplay?: { result: 'passed' | 'failed' | 'missing'; replayEvidenceHash?: string };
|
||||
}
|
||||
export interface EvalResult {
|
||||
cellId: string; sourceHash: string; skillHash: string; model: string; host: string; budgetSeconds: number;
|
||||
/**
|
||||
* `reportFinished`: the helper report's status is `finished`; its findings and runtime outcomes count whatever its
|
||||
* completeness, and the report gates require it. `reportComplete`: it is also `complete` (no gap, every domain
|
||||
* assessed), measured as its own ungated rate because the corpus fixtures carry gaps by design.
|
||||
*/
|
||||
reportPresent: boolean; reportFinished: boolean; reportComplete: boolean; findings: EvalFinding[];
|
||||
setup: Outcome; reproduction: Outcome; repair: Outcome; recheck: Outcome;
|
||||
/** Hash of trusted private observations; never a producer's claimed verification status. */
|
||||
oracleEvidenceHash?: string;
|
||||
oracleVersion?: string;
|
||||
heldOutAssertionsPassed: boolean;
|
||||
currentSourceHash?: string;
|
||||
recheckEvidenceHash?: string;
|
||||
freshRecheck: boolean;
|
||||
latencyMs: number;
|
||||
firstUsefulResultMs: number | null;
|
||||
/** Required by the release scorer; omitted only by isolated accounting tests. */
|
||||
producerReceiptHash?: string;
|
||||
usage?: { source: 'host'; tokens?: number; costUSD?: number };
|
||||
prerequisite?: string;
|
||||
}
|
||||
export interface Rate { numerator: number; denominator: number; value: number | null }
|
||||
export interface ReleaseQualification {
|
||||
containment: Record<string, 'passed' | 'failed' | 'not_run'>;
|
||||
}
|
||||
export interface PreparedEvalSchedule {
|
||||
schemaVersion: 1;
|
||||
matrixHash: string;
|
||||
scheduledCells: number;
|
||||
preparedCells: number;
|
||||
jobs: Array<{ cellId: string; relativePath: string; inputHash: string }>;
|
||||
}
|
||||
export interface ProducerGroupSummary {
|
||||
version: EvalVersion;
|
||||
mode: EvalMode;
|
||||
scheduled: number;
|
||||
submitted: number;
|
||||
missing: number;
|
||||
succeeded: number;
|
||||
failed: number;
|
||||
latency: { samples: number; denominator: number; p95Ms: number | null };
|
||||
firstUsefulResult: { samples: 0; denominator: number; p95Ms: null };
|
||||
modelTokens: { measured: number; denominator: number; total: number | null };
|
||||
estimatedCost: { measured: number; denominator: number; totalUSD: number | null; source: 'pricing-table-estimate' };
|
||||
}
|
||||
export interface ProducerBatch {
|
||||
schemaVersion: 1;
|
||||
matrixHash: string;
|
||||
scheduleHash: string;
|
||||
receipts: ProducerReceiptIndex[];
|
||||
summary: {
|
||||
scheduled: number;
|
||||
prepared: number;
|
||||
submitted: number;
|
||||
missing: number;
|
||||
matchedPairsExpected: number;
|
||||
matchedPairsSubmitted: number;
|
||||
modelMismatches: Array<{ pair: string; v2: string; v3: string }>;
|
||||
groups: ProducerGroupSummary[];
|
||||
note: string;
|
||||
};
|
||||
/** Present only when platforms embedded catalogs that differ in qualification time alone; see assertPlatformIdentities. */
|
||||
embeddedCatalogs?: RuntimeCatalog[];
|
||||
batchHash: string;
|
||||
}
|
||||
export const REQUIRED_CONTAINMENT = [
|
||||
'hostile-startup-configuration', 'environment-canary', 'remote-docker-context', 'ipv4-egress', 'ipv6-egress', 'dns-egress',
|
||||
'archive-traversal-and-poisoning', 'symlink-traversal', 'split-output-secrets', 'concurrent-admission', 'expired-snapshot-replay',
|
||||
'watchdog-survival', 'failed-report-writes', 'held-out-oracle-visibility',
|
||||
] as const;
|
||||
const digest = (value: string) => createHash('sha256').update(value).digest('hex');
|
||||
const HEX = /^[a-f0-9]{64}$/;
|
||||
const rate = (numerator: number, denominator: number): Rate => ({ numerator, denominator, value: denominator ? numerator / denominator : null });
|
||||
const validNumber = (value: unknown) => typeof value === 'number' && Number.isFinite(value) && value >= 0;
|
||||
const PORTABLE_PAYLOAD_HEADER = '<!-- GSTACK_CSO_EVAL_PAYLOAD ';
|
||||
const PORTABLE_PAYLOAD_HEADER_END = ' -->\n';
|
||||
const PORTABLE_FILE_END = '\n<<<END_GSTACK_CSO_EVAL_FILE>>>\n';
|
||||
const PORTABLE_FILE_LIMIT = 2 * 1024 * 1024;
|
||||
const PORTABLE_PAYLOAD_LIMIT = 4 * 1024 * 1024;
|
||||
|
||||
function portablePayloadPreamble(version: EvalVersion): string {
|
||||
return `# Complete portable CSO evaluation instructions (${version})\n\nThis package is the sole CSO instruction input for this evaluation cell. Apply the embedded SKILL.md and every embedded manifest-listed section. Resolve any SKILL.md reference to cso/sections/<file> or sections/<file> from the matching embedded file below. Do not read an installed, user-home, repository, or other-version CSO skill or section. The file bodies are exact generated bytes; package markers are transport metadata.\n\n`;
|
||||
}
|
||||
|
||||
function portableFileOpen(identity: PortableSkillFileIdentity): string {
|
||||
return `<<<GSTACK_CSO_EVAL_FILE ${JSON.stringify(identity)}>>>\n`;
|
||||
}
|
||||
|
||||
function parsePortableManifest(contents: string): { files: string[] } {
|
||||
let manifest: any;
|
||||
try { manifest = JSON.parse(contents); } catch { throw new Error('INVALID_CSO_EVAL_PAYLOAD_MANIFEST'); }
|
||||
if (!manifest || manifest.skill !== 'cso' || manifest.version !== 1 || !Array.isArray(manifest.sections) || manifest.sections.length === 0) throw new Error('INVALID_CSO_EVAL_PAYLOAD_MANIFEST');
|
||||
const files: string[] = [];
|
||||
const ids = new Set<string>();
|
||||
for (const section of manifest.sections) {
|
||||
if (!section || typeof section.id !== 'string' || !/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(section.id) || ids.has(section.id) || typeof section.file !== 'string' || !/^[a-z0-9]+(?:-[a-z0-9]+)*\.md$/.test(section.file) || files.includes(section.file) || typeof section.title !== 'string' || !section.title.trim() || typeof section.trigger !== 'string' || !section.trigger.trim()) throw new Error('INVALID_CSO_EVAL_PAYLOAD_MANIFEST');
|
||||
ids.add(section.id); files.push(section.file);
|
||||
}
|
||||
return { files };
|
||||
}
|
||||
|
||||
function validatePortableSkillFiles(version: EvalVersion, files: PortableSkillFile[]): PortableSkillFile[] {
|
||||
if (!['v2', 'v3'].includes(version) || !Array.isArray(files)) throw new Error('INVALID_CSO_EVAL_PAYLOAD');
|
||||
const byPath = new Map<string, string>();
|
||||
for (const file of files) {
|
||||
if (!file || typeof file.path !== 'string' || typeof file.contents !== 'string' || byPath.has(file.path) || Buffer.byteLength(file.contents) > PORTABLE_FILE_LIMIT || file.contents.includes(PORTABLE_FILE_END.trim())) throw new Error('INVALID_CSO_EVAL_PAYLOAD');
|
||||
byPath.set(file.path, file.contents);
|
||||
}
|
||||
const root = byPath.get('SKILL.md'), manifest = byPath.get('sections/manifest.json');
|
||||
if (root === undefined || manifest === undefined) throw new Error('INCOMPLETE_CSO_EVAL_PAYLOAD');
|
||||
const frontmatter = root.match(/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/)?.[1];
|
||||
const versionMatch = frontmatter?.match(/^version:\s*([0-9]+)(?:\.[0-9]+){0,2}\s*$/m);
|
||||
if (!versionMatch || Number(versionMatch[1]) !== Number(version.slice(1))) throw new Error('CSO_EVAL_PAYLOAD_VERSION_MISMATCH');
|
||||
const sectionFiles = parsePortableManifest(manifest).files;
|
||||
const expectedPaths = ['SKILL.md', 'sections/manifest.json', ...sectionFiles.map(file => `sections/${file}`)];
|
||||
if (byPath.size !== expectedPaths.length || expectedPaths.some(path => !byPath.has(path))) throw new Error('INCOMPLETE_CSO_EVAL_PAYLOAD');
|
||||
return expectedPaths.map(path => ({ path, contents: byPath.get(path)! }));
|
||||
}
|
||||
|
||||
/** Render the only portable instruction format accepted by matrix preparation. */
|
||||
export function createPortableSkillPayload(version: EvalVersion, inputFiles: PortableSkillFile[]): string {
|
||||
const files = validatePortableSkillFiles(version, inputFiles);
|
||||
const identities = files.map(file => ({ path: file.path, sha256: sha256(file.contents), bytes: Buffer.byteLength(file.contents) }));
|
||||
const identity: PortableSkillPayloadIdentity = { schemaVersion: 1, version, files: identities };
|
||||
let payload = `${PORTABLE_PAYLOAD_HEADER}${JSON.stringify(identity)}${PORTABLE_PAYLOAD_HEADER_END}${portablePayloadPreamble(version)}`;
|
||||
for (let index = 0; index < files.length; index++) payload += `${portableFileOpen(identities[index])}${files[index].contents}${PORTABLE_FILE_END}`;
|
||||
if (Buffer.byteLength(payload) > PORTABLE_PAYLOAD_LIMIT) throw new Error('CSO_EVAL_PAYLOAD_TOO_LARGE');
|
||||
return payload;
|
||||
}
|
||||
|
||||
/** Validate canonical serialization and return the identities bound by its hash. */
|
||||
export function validatePortableSkillPayload(payload: string, expectedVersion?: EvalVersion): PortableSkillPayloadIdentity {
|
||||
if (typeof payload !== 'string' || Buffer.byteLength(payload) > PORTABLE_PAYLOAD_LIMIT || !payload.startsWith(PORTABLE_PAYLOAD_HEADER)) throw new Error('INVALID_CSO_EVAL_PAYLOAD');
|
||||
const headerEnd = payload.indexOf(PORTABLE_PAYLOAD_HEADER_END, PORTABLE_PAYLOAD_HEADER.length);
|
||||
if (headerEnd < 0) throw new Error('INVALID_CSO_EVAL_PAYLOAD');
|
||||
let identity: PortableSkillPayloadIdentity;
|
||||
try { identity = JSON.parse(payload.slice(PORTABLE_PAYLOAD_HEADER.length, headerEnd)); } catch { throw new Error('INVALID_CSO_EVAL_PAYLOAD'); }
|
||||
if (identity?.schemaVersion !== 1 || !['v2', 'v3'].includes(identity.version) || (expectedVersion && identity.version !== expectedVersion) || !Array.isArray(identity.files)) throw new Error('INVALID_CSO_EVAL_PAYLOAD');
|
||||
let cursor = headerEnd + PORTABLE_PAYLOAD_HEADER_END.length;
|
||||
const preamble = portablePayloadPreamble(identity.version);
|
||||
if (payload.slice(cursor, cursor + preamble.length) !== preamble) throw new Error('INVALID_CSO_EVAL_PAYLOAD');
|
||||
cursor += preamble.length;
|
||||
const files: PortableSkillFile[] = [];
|
||||
for (const file of identity.files) {
|
||||
if (!file || typeof file.path !== 'string' || !HEX.test(file.sha256) || !Number.isSafeInteger(file.bytes) || file.bytes < 0 || file.bytes > PORTABLE_FILE_LIMIT) throw new Error('INVALID_CSO_EVAL_PAYLOAD');
|
||||
const open = portableFileOpen(file);
|
||||
if (payload.slice(cursor, cursor + open.length) !== open) throw new Error('INVALID_CSO_EVAL_PAYLOAD');
|
||||
cursor += open.length;
|
||||
const end = payload.indexOf(PORTABLE_FILE_END, cursor);
|
||||
if (end < 0) throw new Error('INVALID_CSO_EVAL_PAYLOAD');
|
||||
const contents = payload.slice(cursor, end);
|
||||
if (Buffer.byteLength(contents) !== file.bytes || sha256(contents) !== file.sha256) throw new Error('INVALID_CSO_EVAL_PAYLOAD');
|
||||
files.push({ path: file.path, contents }); cursor = end + PORTABLE_FILE_END.length;
|
||||
}
|
||||
if (cursor !== payload.length || createPortableSkillPayload(identity.version, files) !== payload) throw new Error('INVALID_CSO_EVAL_PAYLOAD');
|
||||
return identity;
|
||||
}
|
||||
|
||||
/** Read one generated CSO skill tree and package every manifest-listed section. */
|
||||
export function loadPortableSkillPayload(version: EvalVersion, skillDirectory: string): string {
|
||||
const root = resolve(skillDirectory), stat = lstatSync(root);
|
||||
if (!stat.isDirectory() || stat.isSymbolicLink() || realpathSync(root) !== root) throw new Error('UNSAFE_CSO_EVAL_SKILL_DIRECTORY');
|
||||
const read = (relativePath: string) => {
|
||||
const bytes = readBoundedStable(join(root, ...relativePath.split('/')), PORTABLE_FILE_LIMIT, `CSO ${version} ${relativePath}`);
|
||||
const contents = bytes.toString('utf8');
|
||||
if (!Buffer.from(contents).equals(bytes)) throw new Error('INVALID_CSO_EVAL_PAYLOAD_ENCODING');
|
||||
return contents;
|
||||
};
|
||||
const rootSkill = read('SKILL.md'), manifest = read('sections/manifest.json');
|
||||
const sectionFiles = parsePortableManifest(manifest).files;
|
||||
const sectionsRoot = join(root, 'sections'), sectionStat = lstatSync(sectionsRoot);
|
||||
if (!sectionStat.isDirectory() || sectionStat.isSymbolicLink() || realpathSync(sectionsRoot) !== sectionsRoot) throw new Error('UNSAFE_CSO_EVAL_SKILL_DIRECTORY');
|
||||
const listed = new Set(sectionFiles);
|
||||
const inventory = () => readdirSync(sectionsRoot, { withFileTypes: true }).filter(entry => entry.name.endsWith('.md')).map(entry => {
|
||||
if (!entry.isFile() || entry.isSymbolicLink() || !listed.has(entry.name)) throw new Error('UNLISTED_CSO_EVAL_SECTION');
|
||||
return entry.name;
|
||||
}).sort();
|
||||
const firstInventory = inventory();
|
||||
const files = [
|
||||
{ path: 'SKILL.md', contents: rootSkill },
|
||||
{ path: 'sections/manifest.json', contents: manifest },
|
||||
...sectionFiles.map(file => ({ path: `sections/${file}`, contents: read(`sections/${file}`) })),
|
||||
];
|
||||
if (JSON.stringify(inventory()) !== JSON.stringify(firstInventory) || files.some(file => read(file.path) !== file.contents)) throw new Error('CSO_EVAL_SKILL_CHANGED_DURING_PACKAGING');
|
||||
return createPortableSkillPayload(version, files);
|
||||
}
|
||||
|
||||
function matrixHash(matrix: EvalMatrix): string { return digest(JSON.stringify(matrix)); }
|
||||
|
||||
function safeWriteNew(path: string, value: unknown): void {
|
||||
const target = resolve(path), parent = dirname(target), stat = lstatSync(parent);
|
||||
if (!stat.isDirectory() || stat.isSymbolicLink() || realpathSync(parent) !== parent) throw new Error('UNSAFE_EVAL_DESTINATION');
|
||||
atomicWriteSync(target, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600, noReplace: true });
|
||||
}
|
||||
|
||||
function readJsonBounded(path: string, max: number, label: string): any {
|
||||
try { return JSON.parse(readBoundedStable(resolve(path), max, label).toString('utf8')); }
|
||||
catch (error) { if (error instanceof SyntaxError) throw new Error(`INVALID_${label.toUpperCase().replaceAll(' ', '_')}`); throw error; }
|
||||
}
|
||||
|
||||
function initializeFixtureRepository(path: string): void {
|
||||
const nullPath = process.platform === 'win32' ? 'NUL' : '/dev/null';
|
||||
const env = {
|
||||
PATH: process.env.PATH ?? '', LANG: 'C', LC_ALL: 'C',
|
||||
GIT_CONFIG_NOSYSTEM: '1', GIT_CONFIG_GLOBAL: EMPTY_GLOBAL_GIT_CONFIG, GIT_ATTR_NOSYSTEM: '1',
|
||||
GIT_AUTHOR_NAME: 'CSO Eval', GIT_AUTHOR_EMAIL: 'cso-eval@invalid',
|
||||
GIT_COMMITTER_NAME: 'CSO Eval', GIT_COMMITTER_EMAIL: 'cso-eval@invalid',
|
||||
};
|
||||
const git = executable('git');
|
||||
// Prepared sources are copied immediately. A detached auto-maintenance child
|
||||
// can remove .git/objects/maintenance.lock while that copy is in progress.
|
||||
const safe = ['-c', 'maintenance.auto=false', '-c', 'gc.auto=0',
|
||||
'-c', `core.hooksPath=${nullPath}`, '-c', `core.attributesFile=${nullPath}`, '-c', `core.excludesFile=${nullPath}`];
|
||||
execFileSync(git, [...safe, 'init', '--quiet', '--initial-branch=main'], { cwd: path, env, stdio: 'ignore' });
|
||||
execFileSync(git, [...safe, 'add', '--all'], { cwd: path, env, stdio: 'ignore' });
|
||||
execFileSync(git, [...safe, 'commit', '--quiet', '-m', 'immutable evaluation fixture'], { cwd: path, env, stdio: 'ignore' });
|
||||
}
|
||||
|
||||
function sourceEntries(corpus: EvalCorpus, caseId: string, variant: EvalVariant): ProducerSourceEntry[] {
|
||||
return Object.entries(corpus.sourceFiles(caseId, variant)).sort(([left], [right]) => left < right ? -1 : left > right ? 1 : 0).map(([path, contents]) => ({ path, sha256: sha256(contents), bytes: Buffer.byteLength(contents) }));
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepare independent one-cell jobs. The returned schedule is trusted
|
||||
* evaluator metadata; transfer one job at a time and never give the schedule
|
||||
* or sibling jobs to the producing agent.
|
||||
*/
|
||||
export function prepareEvalJobs(matrix: EvalMatrix, payloads: Partial<Record<EvalVersion, string>>, destination: string, selectedCellIds?: string[], corpus: EvalCorpus = publicCorpus()): PreparedEvalSchedule {
|
||||
validateMatrix(matrix, corpus.manifest);
|
||||
const skillHashes: Partial<Record<EvalVersion, string>> = matrix.skillHashes;
|
||||
const versions = (['v2', 'v3'] as const).filter(version => skillHashes[version] !== undefined);
|
||||
if (!payloads || Object.keys(payloads).sort().join(',') !== versions.join(',')) throw new Error('EVAL_SKILL_HASH_MISMATCH');
|
||||
for (const version of versions) {
|
||||
validatePortableSkillPayload(payloads[version]!, version);
|
||||
if (sha256(payloads[version]!) !== skillHashes[version]) throw new Error('EVAL_SKILL_HASH_MISMATCH');
|
||||
}
|
||||
const root = resolve(destination);
|
||||
if (existsSync(root)) throw new Error('EVAL_DESTINATION_EXISTS');
|
||||
const parent = dirname(root);
|
||||
if (realpathSync(parent) !== parent || !lstatSync(parent).isDirectory()) throw new Error('UNSAFE_EVAL_DESTINATION');
|
||||
const selected = selectedCellIds === undefined ? matrix.cells : selectedCellIds.map(id => {
|
||||
const cell = matrix.cells.find(item => item.id === id);
|
||||
if (!cell) throw new Error('UNKNOWN_EVAL_CELL');
|
||||
return cell;
|
||||
});
|
||||
if (new Set(selected.map(cell => cell.id)).size !== selected.length) throw new Error('DUPLICATE_EVAL_CELL');
|
||||
mkdirSync(root, { mode: 0o700 });
|
||||
const jobsRoot = join(root, 'jobs'); mkdirSync(jobsRoot, { mode: 0o700 });
|
||||
const jobs: PreparedEvalSchedule['jobs'] = [];
|
||||
for (const cell of selected) {
|
||||
const jobRoot = join(jobsRoot, cell.id); mkdirSync(jobRoot, { mode: 0o700 });
|
||||
const source = materializeCase(cell.caseId, cell.variant, join(jobRoot, 'source'), corpus);
|
||||
if (source.sourceHash !== cell.sourceHash) throw new Error('CORPUS_INTEGRITY_MISMATCH');
|
||||
initializeFixtureRepository(source.path);
|
||||
const input: ProducerInput = { schemaVersion: 2, cellRef: cell.id, skill: payloads[cell.version]!, source: sourceEntries(corpus, cell.caseId, cell.variant), execution: producerExecution(cell) };
|
||||
const inputHash = producerInputHash(input);
|
||||
safeWriteNew(join(jobRoot, 'producer-input.json'), input);
|
||||
jobs.push({ cellId: cell.id, relativePath: `jobs/${cell.id}`, inputHash });
|
||||
}
|
||||
const schedule: PreparedEvalSchedule = { schemaVersion: 1, matrixHash: matrixHash(matrix), scheduledCells: matrix.cells.length, preparedCells: jobs.length, jobs };
|
||||
safeWriteNew(join(root, 'schedule.json'), schedule);
|
||||
return schedule;
|
||||
}
|
||||
|
||||
function validateSchedule(matrix: EvalMatrix, schedule: PreparedEvalSchedule): void {
|
||||
if (schedule?.schemaVersion !== 1 || schedule.matrixHash !== matrixHash(matrix) || schedule.scheduledCells !== matrix.cells.length || !Array.isArray(schedule.jobs) || schedule.preparedCells !== schedule.jobs.length) throw new Error('INVALID_EVAL_SCHEDULE');
|
||||
const known = new Set(matrix.cells.map(cell => cell.id));
|
||||
const seen = new Set<string>();
|
||||
for (const job of schedule.jobs) {
|
||||
if (!job || !known.has(job.cellId) || seen.has(job.cellId) || job.relativePath !== `jobs/${job.cellId}` || !HEX.test(job.inputHash)) throw new Error('INVALID_EVAL_SCHEDULE');
|
||||
seen.add(job.cellId);
|
||||
}
|
||||
}
|
||||
|
||||
function validateReceipt(receipt: ProducerReceipt, cell: EvalCell, inputHash: string): void {
|
||||
if (receipt?.schemaVersion !== 2 || receipt.cellRef !== cell.id || 'cell' in receipt || receipt.inputHash !== inputHash || receipt.requestedModel !== cell.model || !['succeeded', 'failed'].includes(receipt.status) || typeof receipt.modelUsed !== 'string' || !receipt.modelUsed || !['provider_reported', 'requested_pin'].includes(receipt.modelIdentitySource) || (receipt.modelIdentitySource === 'requested_pin' && receipt.modelUsed !== receipt.requestedModel) || (receipt.modelIdentitySource === 'provider_reported' && receipt.modelUsed === receipt.requestedModel) || !validNumber(receipt.durationMs) || receipt.firstUsefulResultMs !== null || !Number.isSafeInteger(receipt.toolCalls) || receipt.toolCalls < 0 || typeof receipt.output !== 'string' || receipt.outputHash !== sha256(receipt.output) || !HEX.test(receipt.receiptHash)) throw new Error('INVALID_PRODUCER_RECEIPT');
|
||||
const { receiptHash, ...withoutHash } = receipt;
|
||||
if (producerReceiptHash(withoutHash) !== receiptHash) throw new Error('INVALID_PRODUCER_RECEIPT');
|
||||
const started = Date.parse(receipt.startedAt), finished = Date.parse(receipt.finishedAt);
|
||||
if (!Number.isFinite(started) || !Number.isFinite(finished) || finished < started) throw new Error('INVALID_PRODUCER_RECEIPT');
|
||||
if (!receipt.usage || !['inputTokens', 'outputTokens', 'cachedTokens', 'estimatedCostUSD'].every(field => receipt.usage[field as keyof typeof receipt.usage] === null || validNumber(receipt.usage[field as keyof typeof receipt.usage]))) throw new Error('INVALID_PRODUCER_RECEIPT');
|
||||
const hasError = !!receipt.error;
|
||||
if ((receipt.status === 'failed') !== hasError || (hasError && (!receipt.error!.code || typeof receipt.error!.reason !== 'string'))) throw new Error('INVALID_PRODUCER_RECEIPT');
|
||||
validateInstallationIdentity(receipt.installationIdentity, 'INVALID_PRODUCER_RECEIPT');
|
||||
validateProviderIdentity(receipt.providerIdentity, cell.host === 'codex' ? 'gpt' : cell.host, 'INVALID_PRODUCER_RECEIPT');
|
||||
validateArtifactInventory(receipt.artifacts, 'INVALID_PRODUCER_RECEIPT');
|
||||
const timeline = receipt.toolTimeline;
|
||||
if (timeline !== undefined && (!Array.isArray(timeline) || timeline.length > 4096 || timeline.some(entry => !entry || !Number.isSafeInteger(entry.atMs) || entry.atMs < 0 || (entry.endMs !== undefined && (!Number.isSafeInteger(entry.endMs) || entry.endMs < entry.atMs)) || typeof entry.tool !== 'string' || !/^[A-Za-z][A-Za-z0-9_]{0,63}$/.test(entry.tool) || !['main', 'subagent'].includes(entry.agent) || Object.keys(entry).some(key => !['atMs', 'endMs', 'tool', 'agent'].includes(key))))) throw new Error('INVALID_PRODUCER_RECEIPT');
|
||||
}
|
||||
|
||||
function validateInstallationIdentity(identity: ProducerInstallationIdentity, error: string): void {
|
||||
const artifact = (value: any) => value && HEX.test(value.sha256) && Number.isSafeInteger(value.bytes) && value.bytes > 0;
|
||||
if (!identity || identity.schemaVersion !== 1 || !artifact(identity.producer) || !artifact(identity.launcher) || !artifact(identity.core) || !artifact(identity.watchdog) ||
|
||||
!identity.embeddedCatalogs || !identity.embeddedCatalogs.runtimeRevision || !identity.embeddedCatalogs.runtimeBuildRevision || !HEX.test(identity.embeddedCatalogs.runtimeSha256) ||
|
||||
!identity.embeddedCatalogs.scannerRevision || !HEX.test(identity.embeddedCatalogs.scannerSha256) || !HEX.test(identity.identityHash)) throw new Error(error);
|
||||
const { identityHash, ...withoutHash } = identity;
|
||||
if (producerInstallationIdentityHash(withoutHash) !== identityHash) throw new Error(error);
|
||||
}
|
||||
|
||||
function validateProviderIdentity(identity: ProducerProviderIdentity, family: 'claude' | 'gpt' | 'gemini', error: string): void {
|
||||
if (!identity || identity.schemaVersion !== 1 || identity.family !== family || !identity.policyRevision || !identity.version ||
|
||||
!identity.executable || !HEX.test(identity.executable.sha256) || !Number.isSafeInteger(identity.executable.bytes) || identity.executable.bytes <= 0 ||
|
||||
!Array.isArray(identity.argsPrefix) || identity.argsPrefix.some(value => typeof value !== 'string' || value.includes('\0')) || !HEX.test(identity.identityHash)) throw new Error(error);
|
||||
const { identityHash, ...withoutHash } = identity;
|
||||
if (producerProviderIdentityHash(withoutHash) !== identityHash) throw new Error(error);
|
||||
}
|
||||
|
||||
/** Paths are unique; their order is whatever the producer bound into identityHash (1.91.75 producers sorted by locale). */
|
||||
function validateArtifactInventory(inventory: ProducerArtifactInventory, error: string): void {
|
||||
if (!inventory || inventory.schemaVersion !== 1 || inventory.root !== 'security/cso' || !Array.isArray(inventory.entries) || inventory.entries.length > 4096 ||
|
||||
!Number.isSafeInteger(inventory.totalBytes) || inventory.totalBytes < 0 || inventory.totalBytes > 128 * 1024 * 1024 || !HEX.test(inventory.identityHash)) throw new Error(error);
|
||||
const paths = new Set<string>();
|
||||
let total = 0;
|
||||
for (const entry of inventory.entries) {
|
||||
if (!entry || typeof entry.path !== 'string' || entry.path.length > 1024 || !/^[A-Za-z0-9._/-]+$/.test(entry.path) || entry.path.split('/').some(part => !part || part === '.' || part === '..') ||
|
||||
paths.has(entry.path) || !HEX.test(entry.sha256) || !Number.isSafeInteger(entry.bytes) || entry.bytes < 0 || entry.bytes > 32 * 1024 * 1024) throw new Error(error);
|
||||
paths.add(entry.path); total += entry.bytes;
|
||||
}
|
||||
if (total !== inventory.totalBytes) throw new Error(error);
|
||||
const { identityHash, ...withoutHash } = inventory;
|
||||
if (producerArtifactInventoryHash(withoutHash) !== identityHash) throw new Error(error);
|
||||
}
|
||||
|
||||
function validateReceiptIndex(receipt: ProducerReceiptIndex, cell: EvalCell): void {
|
||||
if (!receipt || receipt.schemaVersion !== 2 || receipt.cellRef !== cell.id || JSON.stringify(receipt.cell) !== JSON.stringify(cell) || !HEX.test(receipt.inputHash) || receipt.requestedModel !== cell.model || !receipt.modelUsed || !['provider_reported', 'requested_pin'].includes(receipt.modelIdentitySource) || (receipt.modelIdentitySource === 'requested_pin' && receipt.modelUsed !== receipt.requestedModel) || (receipt.modelIdentitySource === 'provider_reported' && receipt.modelUsed === receipt.requestedModel) || !['succeeded', 'failed'].includes(receipt.status) || !HEX.test(receipt.outputHash) || !HEX.test(receipt.receiptHash) || !validNumber(receipt.durationMs) || receipt.firstUsefulResultMs !== null || !Number.isSafeInteger(receipt.toolCalls) || receipt.toolCalls < 0 || !receipt.usage) throw new Error('INVALID_PRODUCER_BATCH');
|
||||
const started = Date.parse(receipt.startedAt), finished = Date.parse(receipt.finishedAt);
|
||||
if (!Number.isFinite(started) || !Number.isFinite(finished) || finished < started || !['inputTokens', 'outputTokens', 'cachedTokens', 'estimatedCostUSD'].every(field => receipt.usage[field as keyof typeof receipt.usage] === null || validNumber(receipt.usage[field as keyof typeof receipt.usage])) || ((receipt.status === 'failed') !== !!receipt.error) || (receipt.error && !receipt.error.code)) throw new Error('INVALID_PRODUCER_BATCH');
|
||||
validateInstallationIdentity(receipt.installationIdentity, 'INVALID_PRODUCER_BATCH');
|
||||
validateProviderIdentity(receipt.providerIdentity, cell.host === 'codex' ? 'gpt' : cell.host, 'INVALID_PRODUCER_BATCH');
|
||||
validateArtifactInventory(receipt.artifacts, 'INVALID_PRODUCER_BATCH');
|
||||
}
|
||||
|
||||
const matchedPairKey = (cell: EvalCell): string => [cell.caseId, cell.variant, cell.mode, cell.repetition, cell.model, cell.host, cell.budgetSeconds, cell.sourceHash].join('|');
|
||||
const PROFILE_GROUPS: Record<EvalProfile, ReadonlyArray<readonly [EvalVersion, EvalMode]>> = {
|
||||
full: [['v2', 'daily'], ['v2', 'comprehensive'], ['v3', 'daily'], ['v3', 'comprehensive']],
|
||||
release: [['v3', 'daily'], ['v3', 'comprehensive']],
|
||||
baseline: [['v2', 'comprehensive']],
|
||||
};
|
||||
const profileOf = (matrix: EvalMatrix): EvalProfile => matrix.profile ?? 'full';
|
||||
const expectedMatchedPairs = (matrix: EvalMatrix): number => profileOf(matrix) === 'full' ? matrix.cells.length / 2 : 0;
|
||||
|
||||
type IdentityBearing = Pick<ProducerReceiptIndex, 'cell' | 'installationIdentity' | 'providerIdentity'>;
|
||||
/**
|
||||
* Each platform has exactly one producer installation and provider binary.
|
||||
* Platforms differ only in native binaries: the embedded catalogs and the
|
||||
* reviewed provider policy must be identical across them. Evaluation units that
|
||||
* generated their catalog once per platform embed copies differing only in each
|
||||
* runtime's `qualifiedAt` and the evidence digest over it; `bodies`, the catalogs
|
||||
* as embedded, prove that, each hashing to its platform's runtimeSha256.
|
||||
*/
|
||||
function assertPlatformIdentities(receipts: IdentityBearing[], bodies: RuntimeCatalog[] = []): void {
|
||||
const byPlatform = new Map<string, IdentityBearing[]>();
|
||||
for (const receipt of receipts) {
|
||||
const key = receipt.cell.platform ?? 'unpinned', list = byPlatform.get(key) ?? [];
|
||||
list.push(receipt); byPlatform.set(key, list);
|
||||
}
|
||||
for (const list of byPlatform.values()) {
|
||||
if (new Set(list.map(receipt => receipt.installationIdentity.identityHash)).size > 1) throw new Error('UNMATCHED_PRODUCER_INSTALLATIONS');
|
||||
if (new Set(list.map(receipt => receipt.providerIdentity.identityHash)).size > 1) throw new Error('UNMATCHED_PRODUCER_PROVIDERS');
|
||||
}
|
||||
const representatives = [...byPlatform.values()].map(list => list[0]);
|
||||
if (representatives.length < 2) return;
|
||||
if (new Set(representatives.map(receipt => receipt.installationIdentity.identityHash)).size !== representatives.length) throw new Error('UNMATCHED_PRODUCER_PLATFORMS');
|
||||
const catalogs = (receipt: IdentityBearing) => JSON.stringify(receipt.installationIdentity.embeddedCatalogs);
|
||||
const policy = ({ providerIdentity: { family, policyRevision, version, argsPrefix } }: IdentityBearing) => JSON.stringify({ family, policyRevision, version, argsPrefix });
|
||||
if (new Set(representatives.map(catalogs)).size !== 1 && !catalogsDifferOnlyInQualificationTime(representatives, bodies)) throw new Error('UNMATCHED_PRODUCER_INSTALLATIONS');
|
||||
if (new Set(representatives.map(policy)).size !== 1) throw new Error('UNMATCHED_PRODUCER_PROVIDERS');
|
||||
}
|
||||
|
||||
function catalogsDifferOnlyInQualificationTime(representatives: IdentityBearing[], bodies: RuntimeCatalog[]): boolean {
|
||||
if (!Array.isArray(bodies) || bodies.length !== representatives.length) return false;
|
||||
const timeless = (body: RuntimeCatalog) => canonical({ ...body, evaluation: { ...body.evaluation, evidenceDigest: null }, runtimes: body.runtimes.map(({ qualifiedAt: _qualifiedAt, ...runtime }) => runtime) });
|
||||
const shared = ({ runtimeSha256: _runtimeSha256, ...rest }: ProducerInstallationIdentity['embeddedCatalogs']) => JSON.stringify(rest);
|
||||
const matched = representatives.map(receipt => bodies.find(body => sha256(JSON.stringify(body)) === receipt.installationIdentity.embeddedCatalogs.runtimeSha256));
|
||||
if (matched.some(body => !body) || new Set(matched).size !== bodies.length) return false;
|
||||
try { for (const body of bodies) validateRuntimeCatalog(body); } catch { return false; }
|
||||
return new Set(representatives.map(receipt => shared(receipt.installationIdentity.embeddedCatalogs))).size === 1 && new Set(bodies.map(timeless)).size === 1 &&
|
||||
bodies.every(body => body.revision === representatives[0].installationIdentity.embeddedCatalogs.runtimeRevision && body.evaluation);
|
||||
}
|
||||
|
||||
/** `embeddedCatalogs`: the runtime catalog each platform's producer unit embedded, required only when those differ (see assertPlatformIdentities). */
|
||||
export function collectProducerReceipts(matrix: EvalMatrix, schedule: PreparedEvalSchedule, receipts: ProducerReceipt[], corpus: EvalCorpusManifest = loadCorpusManifest(), embeddedCatalogs: RuntimeCatalog[] = []): ProducerBatch {
|
||||
validateMatrix(matrix, corpus); validateSchedule(matrix, schedule);
|
||||
if (!Array.isArray(receipts)) throw new Error('INVALID_PRODUCER_RECEIPTS');
|
||||
const cells = new Map(matrix.cells.map(cell => [cell.id, cell]));
|
||||
const jobs = new Map(schedule.jobs.map(job => [job.cellId, job]));
|
||||
const seen = new Set<string>();
|
||||
for (const receipt of receipts) {
|
||||
const cell = cells.get(receipt?.cellRef), job = jobs.get(receipt?.cellRef);
|
||||
if (!cell || !job || seen.has(cell.id)) throw new Error('UNKNOWN_OR_DUPLICATE_PRODUCER_RECEIPT');
|
||||
validateReceipt(receipt, cell, job.inputHash); seen.add(cell.id);
|
||||
}
|
||||
// Receipts name only the opaque cellRef; the trusted matrix supplies the cell.
|
||||
const bound = receipts.map(receipt => ({ ...receipt, cell: cells.get(receipt.cellRef)! }));
|
||||
assertPlatformIdentities(bound, embeddedCatalogs);
|
||||
const platformCatalogs = new Set(bound.map(receipt => receipt.installationIdentity.embeddedCatalogs.runtimeSha256)).size > 1 ? embeddedCatalogs : undefined;
|
||||
const pairs = new Map<string, Partial<Record<EvalVersion, (typeof bound)[number]>>>();
|
||||
if (profileOf(matrix) === 'full') for (const receipt of bound) {
|
||||
const key = matchedPairKey(receipt.cell as EvalCell);
|
||||
const pair = pairs.get(key) ?? {}; pair[receipt.cell.version] = receipt; pairs.set(key, pair);
|
||||
}
|
||||
else if (new Set(bound.map(receipt => receipt.modelUsed)).size > 1) throw new Error('UNMATCHED_EFFECTIVE_MODELS: single-version cells used different normalized model identities');
|
||||
const completePairs = [...pairs.entries()].filter(([, pair]) => pair.v2 && pair.v3) as Array<[string, { v2: (typeof bound)[number]; v3: (typeof bound)[number] }]>;
|
||||
const modelMismatches = completePairs.filter(([, pair]) => pair.v2.modelUsed !== pair.v3.modelUsed).map(([pair, value]) => ({ pair: digest(pair), v2: value.v2.modelUsed, v3: value.v3.modelUsed }));
|
||||
if (modelMismatches.length) throw new Error(`UNMATCHED_EFFECTIVE_MODELS: ${modelMismatches.length} matched v2/v3 pair(s) used different normalized model identities`);
|
||||
const groups: ProducerGroupSummary[] = [];
|
||||
for (const [version, mode] of PROFILE_GROUPS[profileOf(matrix)]) {
|
||||
const expected = matrix.cells.filter(cell => cell.version === version && cell.mode === mode);
|
||||
const submitted = bound.filter(receipt => receipt.cell.version === version && receipt.cell.mode === mode);
|
||||
const tokens = submitted.flatMap(receipt => receipt.usage.inputTokens === null || receipt.usage.outputTokens === null ? [] : [receipt.usage.inputTokens + receipt.usage.outputTokens]);
|
||||
const costs = submitted.flatMap(receipt => receipt.usage.estimatedCostUSD === null ? [] : [receipt.usage.estimatedCostUSD]);
|
||||
groups.push({ version, mode, scheduled: expected.length, submitted: submitted.length, missing: expected.length - submitted.length, succeeded: submitted.filter(receipt => receipt.status === 'succeeded').length, failed: submitted.filter(receipt => receipt.status === 'failed').length,
|
||||
latency: { samples: submitted.length, denominator: expected.length, p95Ms: quantile(submitted.map(receipt => receipt.durationMs), 0.95) },
|
||||
firstUsefulResult: { samples: 0, denominator: expected.length, p95Ms: null },
|
||||
modelTokens: { measured: tokens.length, denominator: expected.length, total: tokens.length ? tokens.reduce((sum, value) => sum + value, 0) : null },
|
||||
estimatedCost: { measured: costs.length, denominator: expected.length, totalUSD: costs.length ? costs.reduce((sum, value) => sum + value, 0) : null, source: 'pricing-table-estimate' },
|
||||
});
|
||||
}
|
||||
const indexes: ProducerReceiptIndex[] = bound.map(({ output: _output, toolTimeline: _toolTimeline, error, ...receipt }) => ({ ...receipt, ...(error ? { error: { code: error.code } } : {}) }));
|
||||
const base = { schemaVersion: 1 as const, matrixHash: matrixHash(matrix), scheduleHash: digest(JSON.stringify(schedule)), receipts: indexes.sort((left, right) => left.cell.id.localeCompare(right.cell.id)), summary: {
|
||||
scheduled: matrix.cells.length, prepared: schedule.preparedCells, submitted: bound.length, missing: matrix.cells.length - bound.length,
|
||||
matchedPairsExpected: expectedMatchedPairs(matrix), matchedPairsSubmitted: completePairs.length, modelMismatches, groups,
|
||||
note: 'Costs are pricing-table estimates. First-useful timing is unmeasured because the reused provider adapters return completed runs. Trusted findings and runtime outcomes require separate oracle adjudication.',
|
||||
}, ...(platformCatalogs ? { embeddedCatalogs: platformCatalogs } : {}) };
|
||||
return { ...base, batchHash: digest(JSON.stringify(base)) };
|
||||
}
|
||||
|
||||
function normalizedPlatforms(corpus: EvalCorpusManifest, value: unknown): Record<string, EvalPlatform> {
|
||||
const assignment = value as Record<string, EvalPlatform>;
|
||||
if (!assignment || typeof assignment !== 'object' || Array.isArray(assignment) || Object.keys(assignment).length !== corpus.cases.length ||
|
||||
corpus.cases.some(fixture => !PRODUCER_PLATFORMS.includes(assignment[fixture.id]))) throw new Error('INVALID_EVAL_PLATFORMS');
|
||||
return Object.fromEntries(corpus.cases.map(fixture => [fixture.id, assignment[fixture.id]]));
|
||||
}
|
||||
|
||||
function buildEvalMatrix(options: EvalMatrixOptions, corpus: EvalCorpusManifest, baselineHash: string | null): EvalMatrix {
|
||||
const profile = options.profile ?? 'full';
|
||||
const skillHashes: Partial<Record<EvalVersion, string>> = options.skillHashes ?? {};
|
||||
const versions = profile === 'full' ? ['v2', 'v3'] : profile === 'release' ? ['v3'] : ['v2'];
|
||||
if (!options.model?.trim() || !['claude', 'codex', 'gemini'].includes(options.host) || !['full', 'release', 'baseline'].includes(profile) ||
|
||||
Object.keys(skillHashes).sort().join(',') !== versions.join(',') || versions.some(version => !HEX.test(skillHashes[version as EvalVersion] ?? '')) ||
|
||||
(profile === 'full' && skillHashes.v2 === skillHashes.v3)) throw new Error('INVALID_MATCHED_EVAL_INPUT');
|
||||
const budgets = options.budgets ?? { daily: 600, comprehensive: 1800 };
|
||||
if (![budgets.daily, budgets.comprehensive].every(value => Number.isInteger(value) && value > 60 && value <= 3600)) throw new Error('INVALID_EVAL_BUDGET');
|
||||
const corpusHash = digest(JSON.stringify(corpus));
|
||||
const cells: EvalCell[] = [];
|
||||
if (options.profile === undefined || options.profile === 'full') {
|
||||
for (const fixture of corpus.cases) for (const variant of ['vulnerable', 'fixed'] as const) for (const mode of ['daily', 'comprehensive'] as const) for (const repetition of [1, 2, 3] as const) for (const version of ['v2', 'v3'] as const) {
|
||||
const cell = { caseId: fixture.id, stack: fixture.stack, variant, version, mode, repetition, model: options.model, host: options.host, budgetSeconds: budgets[mode], sourceHash: fixture.filesHash[variant], skillHash: options.skillHashes[version] };
|
||||
cells.push({ id: digest(JSON.stringify(cell)), ...cell });
|
||||
}
|
||||
return { schemaVersion: 1, corpusVersion: corpus.version, corpusHash, model: options.model, host: options.host, budgets, skillHashes: options.skillHashes, repetitions: 3, cells };
|
||||
}
|
||||
const pinned = options as ReleaseEvalMatrixOptions | BaselineEvalMatrixOptions;
|
||||
const platformKeys = pinned.profile === 'release' ? 'comprehensive,daily' : 'comprehensive';
|
||||
if (!pinned.platforms || Object.keys(pinned.platforms).sort().join(',') !== platformKeys) throw new Error('INVALID_EVAL_PLATFORMS');
|
||||
const comprehensive = normalizedPlatforms(corpus, pinned.platforms.comprehensive);
|
||||
const daily = pinned.profile === 'release' ? pinned.platforms.daily : undefined;
|
||||
if (pinned.profile === 'release' && !PRODUCER_PLATFORMS.includes(daily!)) throw new Error('INVALID_EVAL_PLATFORMS');
|
||||
const version: EvalVersion = pinned.profile === 'release' ? 'v3' : 'v2';
|
||||
const modes = pinned.profile === 'release' ? ['daily', 'comprehensive'] as const : ['comprehensive'] as const;
|
||||
for (const fixture of corpus.cases) for (const variant of ['vulnerable', 'fixed'] as const) for (const mode of modes) {
|
||||
const cell = { caseId: fixture.id, stack: fixture.stack, variant, version, mode, repetition: 1 as const, model: pinned.model, host: pinned.host, budgetSeconds: budgets[mode], sourceHash: fixture.filesHash[variant], skillHash: skillHashes[version]!, platform: mode === 'daily' ? daily! : comprehensive[fixture.id] };
|
||||
cells.push({ id: digest(JSON.stringify(cell)), ...cell });
|
||||
}
|
||||
const common = { schemaVersion: 1 as const, corpusVersion: corpus.version, corpusHash, model: pinned.model, host: pinned.host, budgets };
|
||||
if (pinned.profile === 'release') {
|
||||
if (baselineHash !== null && !HEX.test(baselineHash)) throw new Error('UNBOUND_EVAL_BASELINE');
|
||||
return { ...common, profile: 'release', skillHashes: { v3: pinned.skillHashes.v3 }, repetitions: 1, platforms: { daily: daily!, comprehensive }, baselineHash, cells };
|
||||
}
|
||||
return { ...common, profile: 'baseline', skillHashes: { v2: pinned.skillHashes.v2 }, repetitions: 1, platforms: { comprehensive }, cells };
|
||||
}
|
||||
|
||||
const BASELINE_FIELDS = 'baselineHash,budgetSeconds,cases,corpusHash,corpusVersion,host,matrixHash,model,modelUsed,platforms,producerBatchHash,provider,schemaVersion,skillHash,version';
|
||||
/** Check that a baseline was measured under the same corpus, model, host, budget and platform assignment. */
|
||||
function assertBaselineBinding(baseline: EvalBaseline, target: { corpus: EvalCorpusManifest; model: string; host: ProducerHost; budgetSeconds: number; platforms: Record<string, EvalPlatform> }): void {
|
||||
if (!baseline || typeof baseline !== 'object' || Object.keys(baseline).sort().join(',') !== BASELINE_FIELDS) throw new Error('UNBOUND_EVAL_BASELINE');
|
||||
const { baselineHash, ...record } = baseline;
|
||||
const provider = baseline.provider as unknown as Record<string, unknown>;
|
||||
if (baseline.schemaVersion !== 1 || baseline.version !== 'v2' || !HEX.test(baselineHash) || digest(JSON.stringify(record)) !== baselineHash ||
|
||||
baseline.corpusVersion !== target.corpus.version || baseline.corpusHash !== digest(JSON.stringify(target.corpus)) ||
|
||||
baseline.model !== target.model || baseline.host !== target.host || baseline.budgetSeconds !== target.budgetSeconds ||
|
||||
JSON.stringify(baseline.platforms) !== JSON.stringify(target.platforms) || !HEX.test(baseline.skillHash) || !HEX.test(baseline.matrixHash) ||
|
||||
!HEX.test(baseline.producerBatchHash) || typeof baseline.modelUsed !== 'string' || !baseline.modelUsed ||
|
||||
!provider || typeof provider !== 'object' || Object.keys(provider).sort().join(',') !== 'family,policyRevision,version' ||
|
||||
!['claude', 'gpt', 'gemini'].includes(String(provider.family)) || typeof provider.policyRevision !== 'string' || !provider.policyRevision ||
|
||||
typeof provider.version !== 'string' || !provider.version || !Array.isArray(baseline.cases) || baseline.cases.length !== target.corpus.cases.length ||
|
||||
baseline.cases.some((entry, index) => !entry || Object.keys(entry).sort().join(',') !== 'caseId,found' || entry.caseId !== target.corpus.cases[index].id || typeof entry.found !== 'boolean'))
|
||||
throw new Error('UNBOUND_EVAL_BASELINE');
|
||||
}
|
||||
|
||||
export function createEvalMatrix(options: FullEvalMatrixOptions, corpus?: EvalCorpusManifest): FullEvalMatrix;
|
||||
export function createEvalMatrix(options: ReleaseEvalMatrixOptions, corpus?: EvalCorpusManifest): ReleaseEvalMatrix;
|
||||
export function createEvalMatrix(options: BaselineEvalMatrixOptions, corpus?: EvalCorpusManifest): BaselineEvalMatrix;
|
||||
export function createEvalMatrix(options: EvalMatrixOptions, corpus: EvalCorpusManifest = loadCorpusManifest()): EvalMatrix {
|
||||
let baselineHash: string | null = null;
|
||||
if (options.profile === 'release' && options.baseline !== undefined) {
|
||||
assertBaselineBinding(options.baseline, { corpus, model: options.model, host: options.host, budgetSeconds: (options.budgets ?? { comprehensive: 1800 }).comprehensive, platforms: normalizedPlatforms(corpus, options.platforms?.comprehensive) });
|
||||
baselineHash = options.baseline.baselineHash;
|
||||
}
|
||||
return buildEvalMatrix(options, corpus, baselineHash);
|
||||
}
|
||||
|
||||
export function validateMatrix(matrix: EvalMatrix, corpus: EvalCorpusManifest = loadCorpusManifest()): void {
|
||||
if (!matrix || typeof matrix !== 'object') throw new Error('UNMATCHED_OR_INCOMPLETE_EVAL_MATRIX');
|
||||
const common = { model: matrix.model, host: matrix.host, budgets: matrix.budgets };
|
||||
let expected: EvalMatrix;
|
||||
try {
|
||||
expected = matrix.profile === 'release' ? buildEvalMatrix({ ...common, profile: 'release', skillHashes: matrix.skillHashes, platforms: matrix.platforms }, corpus, matrix.baselineHash)
|
||||
: matrix.profile === 'baseline' ? buildEvalMatrix({ ...common, profile: 'baseline', skillHashes: matrix.skillHashes, platforms: matrix.platforms }, corpus, null)
|
||||
: buildEvalMatrix({ ...common, skillHashes: matrix.skillHashes }, corpus, null);
|
||||
} catch { throw new Error('UNMATCHED_OR_INCOMPLETE_EVAL_MATRIX'); }
|
||||
if (JSON.stringify(matrix) !== JSON.stringify(expected)) throw new Error('UNMATCHED_OR_INCOMPLETE_EVAL_MATRIX');
|
||||
}
|
||||
function validateResult(result: EvalResult, cell: EvalCell, corpus: EvalCorpusManifest): void {
|
||||
if (result.sourceHash !== cell.sourceHash || result.skillHash !== cell.skillHash || result.model !== cell.model || result.host !== cell.host || result.budgetSeconds !== cell.budgetSeconds) throw new Error('UNMATCHED_EVAL_RESULT');
|
||||
for (const field of ['setup', 'reproduction', 'repair', 'recheck'] as const) if (!['passed', 'failed', 'blocked', 'not_attempted'].includes(result[field])) throw new Error('INVALID_EVAL_OUTCOME');
|
||||
for (const field of ['reportPresent', 'reportFinished', 'reportComplete', 'heldOutAssertionsPassed', 'freshRecheck'] as const) if (typeof result[field] !== 'boolean') throw new Error('INVALID_EVAL_RESULT');
|
||||
if (!Array.isArray(result.findings) || !validNumber(result.latencyMs) || (result.firstUsefulResultMs !== null && (!validNumber(result.firstUsefulResultMs) || result.firstUsefulResultMs > result.latencyMs))) throw new Error('INVALID_EVAL_RESULT');
|
||||
if ((result.reportComplete && !result.reportFinished) || (result.reportFinished && !result.reportPresent)) throw new Error('MISSING_EVAL_REPORT');
|
||||
if (!result.reportPresent && result.findings.length) throw new Error('FINDINGS_WITHOUT_REPORT');
|
||||
if (result.setup === 'blocked' && !result.prerequisite?.trim()) throw new Error('MISSING_SETUP_PREREQUISITE');
|
||||
if (result.oracleEvidenceHash !== undefined && (!HEX.test(result.oracleEvidenceHash) || result.oracleVersion !== corpus.version)) throw new Error('INVALID_ORACLE_PROVENANCE');
|
||||
if (result.currentSourceHash !== undefined && !HEX.test(result.currentSourceHash)) throw new Error('INVALID_RECHECK_SOURCE');
|
||||
if (result.recheckEvidenceHash !== undefined && !HEX.test(result.recheckEvidenceHash)) throw new Error('INVALID_RECHECK_EVIDENCE');
|
||||
if (result.usage && (result.usage.source !== 'host' || (result.usage.tokens !== undefined && !validNumber(result.usage.tokens)) || (result.usage.costUSD !== undefined && !validNumber(result.usage.costUSD)))) throw new Error('INVALID_EVAL_USAGE');
|
||||
if (result.producerReceiptHash !== undefined && !HEX.test(result.producerReceiptHash)) throw new Error('INVALID_PRODUCER_RECEIPT_PROVENANCE');
|
||||
const ids = new Set<string>(), repairEvidence = new Set<string>(), recheckEvidence = new Set<string>(), replayEvidence = new Set<string>();
|
||||
for (const finding of result.findings) {
|
||||
if (!finding.id || ids.has(finding.id) || !['supported', 'hypothesis', 'legacy_review'].includes(finding.evidence) || !['correct', 'incidental', 'instrumentation', 'incorrect', 'unadjudicated'].includes(finding.judgment) || typeof finding.claimedTested !== 'boolean') throw new Error('INVALID_FINDING_JUDGMENT');
|
||||
ids.add(finding.id);
|
||||
if (finding.judgment === 'correct' && (cell.variant !== 'vulnerable' || finding.matchedCaseId !== cell.caseId)) throw new Error('INVALID_ORACLE_MATCH');
|
||||
if ((finding.judgment === 'incidental' || finding.judgment === 'instrumentation') && (finding.evidence === 'hypothesis' || finding.matchedCaseId !== undefined)) throw new Error('INVALID_FINDING_JUDGMENT');
|
||||
if ((finding.judgment === 'incidental') !== (finding.incidentalKey !== undefined) || (finding.incidentalKey !== undefined && !HEX.test(finding.incidentalKey))) throw new Error('INVALID_FINDING_JUDGMENT');
|
||||
if (finding.trustedVerification !== undefined) {
|
||||
const verification = finding.trustedVerification as Record<string, unknown>, allowed = new Set(['repair', 'repairEvidenceHash', 'recheck', 'recheckEvidenceHash']);
|
||||
if (!verification || typeof verification !== 'object' || Array.isArray(verification) || Object.keys(verification).some(key => !allowed.has(key)) ||
|
||||
!['passed', 'failed', 'blocked', 'not_attempted'].includes(String(verification.repair)) ||
|
||||
!['passed', 'failed', 'blocked', 'not_attempted'].includes(String(verification.recheck)) || !finding.claimedTested || cell.version !== 'v3' || cell.mode !== 'comprehensive')
|
||||
throw new Error('INVALID_TRUSTED_FINDING_VERIFICATION');
|
||||
const repairHash = verification.repairEvidenceHash, recheckHash = verification.recheckEvidenceHash;
|
||||
if (!(repairHash === undefined || (typeof repairHash === 'string' && HEX.test(repairHash))) ||
|
||||
!(recheckHash === undefined || (typeof recheckHash === 'string' && HEX.test(recheckHash))) ||
|
||||
(verification.repair === 'passed') !== (repairHash !== undefined) ||
|
||||
(verification.recheck === 'passed') !== (recheckHash !== undefined) ||
|
||||
(verification.recheck === 'passed' && verification.repair !== 'passed'))
|
||||
throw new Error('INVALID_TRUSTED_FINDING_VERIFICATION');
|
||||
if (typeof repairHash === 'string') {
|
||||
if (repairEvidence.has(repairHash)) throw new Error('DUPLICATE_TRUSTED_REPAIR_BINDING');
|
||||
repairEvidence.add(repairHash);
|
||||
}
|
||||
if (typeof recheckHash === 'string') {
|
||||
if (recheckEvidence.has(recheckHash)) throw new Error('DUPLICATE_TRUSTED_RECHECK_BINDING');
|
||||
recheckEvidence.add(recheckHash);
|
||||
}
|
||||
}
|
||||
if (finding.trustedReplay !== undefined) {
|
||||
const replay = finding.trustedReplay as Record<string, unknown>, hash = replay?.replayEvidenceHash;
|
||||
if (!replay || typeof replay !== 'object' || Array.isArray(replay) || Object.keys(replay).some(key => key !== 'result' && key !== 'replayEvidenceHash') ||
|
||||
!['passed', 'failed', 'missing'].includes(String(replay.result)) || finding.judgment !== 'incidental' || !finding.claimedTested ||
|
||||
(replay.result === 'passed') !== (typeof hash === 'string' && HEX.test(hash)) || (replay.result !== 'passed' && hash !== undefined))
|
||||
throw new Error('INVALID_TRUSTED_REPLAY');
|
||||
if (typeof hash === 'string') {
|
||||
if (replayEvidence.has(hash)) throw new Error('DUPLICATE_TRUSTED_REPLAY_BINDING');
|
||||
replayEvidence.add(hash);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (cell.mode === 'daily' && [result.setup, result.reproduction, result.repair, result.recheck].some(value => value !== 'not_attempted')) throw new Error('DAILY_EVAL_EXECUTED_APPLICATION');
|
||||
}
|
||||
function quantile(values: number[], fraction: number): number | null {
|
||||
if (!values.length) return null;
|
||||
return [...values].sort((left, right) => left - right)[Math.ceil(values.length * fraction) - 1];
|
||||
}
|
||||
function measuredRate(cells: EvalCell[], results: Map<string, EvalResult>, field: 'setup' | 'reproduction' | 'repair' | 'recheck', corpus: EvalCorpusManifest): Rate {
|
||||
return rate(cells.filter(cell => {
|
||||
const result = results.get(cell.id);
|
||||
if (!result?.reportFinished || result[field] !== 'passed') return false;
|
||||
if (field === 'setup') return true;
|
||||
if (!result.oracleEvidenceHash || result.oracleVersion !== corpus.version || result.setup !== 'passed') return false;
|
||||
if (field === 'reproduction') return true;
|
||||
if (result.reproduction !== 'passed' || result.repair !== 'passed' || !result.heldOutAssertionsPassed) return false;
|
||||
if (cell.version === 'v3' && !result.findings.some(finding => trustedFindingVerification(cell, result, finding, 'repair', corpus))) return false;
|
||||
if (field === 'repair') return true;
|
||||
// Correct alternative patches need not match the reference fix byte-for-byte.
|
||||
// Closure needs a fresh source and a separate trusted current-source observation.
|
||||
return result.freshRecheck && !!result.currentSourceHash && result.currentSourceHash !== cell.sourceHash &&
|
||||
!!result.recheckEvidenceHash && result.recheckEvidenceHash !== result.oracleEvidenceHash &&
|
||||
(cell.version !== 'v3' || result.findings.some(finding => trustedFindingVerification(cell, result, finding, 'recheck', corpus)));
|
||||
}).length, cells.length);
|
||||
}
|
||||
|
||||
function trustedFindingVerification(cell: EvalCell, result: EvalResult, finding: EvalFinding, stage: 'repair' | 'recheck', corpus: EvalCorpusManifest): boolean {
|
||||
const verification = finding.trustedVerification;
|
||||
if (!result.reportFinished || cell.version !== 'v3' || cell.mode !== 'comprehensive' || cell.variant !== 'vulnerable' || finding.evidence !== 'supported' ||
|
||||
finding.judgment !== 'correct' || finding.matchedCaseId !== cell.caseId || !finding.claimedTested || !verification ||
|
||||
result.setup !== 'passed' || result.reproduction !== 'passed' || result.repair !== 'passed' || !result.heldOutAssertionsPassed ||
|
||||
verification.repair !== 'passed' || verification.repairEvidenceHash !== result.oracleEvidenceHash || result.oracleVersion !== corpus.version)
|
||||
return false;
|
||||
if (stage === 'repair') return true;
|
||||
return result.recheck === 'passed' && verification.recheck === 'passed' && verification.recheckEvidenceHash === result.recheckEvidenceHash &&
|
||||
result.freshRecheck && !!result.currentSourceHash && result.currentSourceHash !== cell.sourceHash &&
|
||||
!!result.recheckEvidenceHash && result.recheckEvidenceHash !== result.oracleEvidenceHash;
|
||||
}
|
||||
|
||||
function validatedResults(matrix: EvalMatrix, observations: EvalResult[], corpus: EvalCorpusManifest): Map<string, EvalResult> {
|
||||
if (!Array.isArray(observations)) throw new Error('INVALID_EVAL_RESULTS');
|
||||
const cells = new Map(matrix.cells.map(cell => [cell.id, cell]));
|
||||
const results = new Map<string, EvalResult>();
|
||||
for (const result of observations) {
|
||||
const cell = cells.get(result.cellId);
|
||||
if (!cell || results.has(result.cellId)) throw new Error('UNKNOWN_OR_DUPLICATE_EVAL_RESULT');
|
||||
validateResult(result, cell, corpus); results.set(result.cellId, result);
|
||||
}
|
||||
return results;
|
||||
}
|
||||
const eligibleFinding = (cell: EvalCell, finding: EvalFinding) => finding.evidence === 'supported' || (cell.version === 'v2' && finding.evidence === 'legacy_review');
|
||||
const foundSeededIssue = (cell: EvalCell, result: EvalResult | undefined) => result?.reportFinished === true &&
|
||||
result.findings.some(finding => eligibleFinding(cell, finding) && finding.judgment === 'correct');
|
||||
/**
|
||||
* A tested claim is false unless trusted evidence certifies it: the seeded repair's held-out verification, or, for an
|
||||
* `incidental` finding, a passing replay of the helper's signed bundle. Claims on declared instrumentation count in
|
||||
* neither direction (Garry, 2026-10-18, option 1), the same way precision leaves them out.
|
||||
*/
|
||||
const falselyTested = (cell: EvalCell, result: EvalResult, finding: EvalFinding, corpus: EvalCorpusManifest) =>
|
||||
finding.claimedTested && finding.judgment !== 'instrumentation' && !trustedFindingVerification(cell, result, finding, 'repair', corpus) &&
|
||||
!(finding.judgment === 'incidental' && finding.trustedReplay?.result === 'passed');
|
||||
const isHighCritical = (corpus: EvalCorpusManifest, caseId: string) => ['critical', 'high'].includes(corpus.cases.find(fixture => fixture.id === caseId)!.severity);
|
||||
|
||||
/** High/critical recall of a pre-registered external baseline, after proving it binds to this release matrix. */
|
||||
function externalBaselineRecall(matrix: ReleaseEvalMatrix, baseline: EvalBaseline, corpus: EvalCorpusManifest): Rate {
|
||||
if (matrix.baselineHash === null || baseline?.baselineHash !== matrix.baselineHash) throw new Error('UNBOUND_EVAL_BASELINE');
|
||||
assertBaselineBinding(baseline, { corpus, model: matrix.model, host: matrix.host, budgetSeconds: matrix.budgets.comprehensive, platforms: matrix.platforms.comprehensive });
|
||||
const highCritical = baseline.cases.filter(entry => isHighCritical(corpus, entry.caseId));
|
||||
return rate(highCritical.filter(entry => entry.found).length, highCritical.length);
|
||||
}
|
||||
|
||||
export function scoreEval(matrix: EvalMatrix, observations: EvalResult[], qualification: ReleaseQualification = { containment: {} }, corpus: EvalCorpusManifest = loadCorpusManifest(), baseline?: EvalBaseline) {
|
||||
validateMatrix(matrix, corpus);
|
||||
const profile = profileOf(matrix);
|
||||
if (profile === 'baseline') throw new Error('BASELINE_PROFILE_NOT_QUALIFIABLE: use createEvalBaseline');
|
||||
if (profile !== 'release' && baseline !== undefined) throw new Error('UNBOUND_EVAL_BASELINE');
|
||||
const results = validatedResults(matrix, observations, corpus);
|
||||
const found = (cell: EvalCell) => foundSeededIssue(cell, results.get(cell.id));
|
||||
const groups: any[] = [];
|
||||
for (const [version, mode] of PROFILE_GROUPS[profile]) {
|
||||
const selected = matrix.cells.filter(cell => cell.version === version && cell.mode === mode);
|
||||
const completed = selected.map(cell => results.get(cell.id)).filter((result): result is EvalResult => !!result);
|
||||
const expected = selected.filter(cell => cell.variant === 'vulnerable');
|
||||
const highCritical = expected.filter(cell => isHighCritical(corpus, cell.caseId));
|
||||
let correct = 0, reported = 0, unadjudicated = 0;
|
||||
for (const cell of selected) {
|
||||
const result = results.get(cell.id);
|
||||
const findings = result?.reportFinished ? result.findings.filter(finding => finding.evidence !== 'hypothesis' && finding.judgment !== 'instrumentation') : [];
|
||||
reported += findings.length;
|
||||
unadjudicated += findings.filter(finding => finding.judgment === 'unadjudicated').length;
|
||||
correct += Number(findings.some(finding => eligibleFinding(cell, finding) && finding.judgment === 'correct')); // Duplicate reports do not increase true positives.
|
||||
correct += new Set(findings.filter(finding => eligibleFinding(cell, finding) && finding.judgment === 'incidental').map(finding => finding.incidentalKey)).size;
|
||||
}
|
||||
const firstUseful = completed.flatMap(result => result.firstUsefulResultMs === null ? [] : [result.firstUsefulResultMs]);
|
||||
const costs = completed.flatMap(result => result.usage?.costUSD === undefined ? [] : [result.usage.costUSD]);
|
||||
const tokens = completed.flatMap(result => result.usage?.tokens === undefined ? [] : [result.usage.tokens]);
|
||||
const falseTested = selected.reduce((count, cell) => {
|
||||
const result = results.get(cell.id); if (!result) return count;
|
||||
return count + result.findings.filter(finding => falselyTested(cell, result, finding, corpus)).length;
|
||||
}, 0);
|
||||
groups.push({ version, mode, cells: selected.length, submitted: completed.length, missing: selected.length - completed.length,
|
||||
reports: rate(completed.filter(result => result.reportPresent && result.reportComplete).length, selected.length), finishedReports: rate(completed.filter(result => result.reportFinished).length, selected.length), precision: rate(correct, reported), recall: rate(expected.filter(found).length, expected.length), highCriticalRecall: rate(highCritical.filter(found).length, highCritical.length),
|
||||
unadjudicated, falseTested, setup: mode === 'comprehensive' ? measuredRate(selected, results, 'setup', corpus) : null,
|
||||
reproduction: mode === 'comprehensive' ? measuredRate(expected, results, 'reproduction', corpus) : null,
|
||||
repair: mode === 'comprehensive' ? measuredRate(expected, results, 'repair', corpus) : null,
|
||||
recheck: mode === 'comprehensive' ? measuredRate(expected, results, 'recheck', corpus) : null,
|
||||
setupBlocked: completed.filter(result => result.setup === 'blocked').length,
|
||||
firstUsefulResult: { samples: firstUseful.length, denominator: selected.length, medianMs: quantile(firstUseful, 0.5), p95Ms: quantile(firstUseful, 0.95) },
|
||||
latency: { samples: completed.length, p95Ms: quantile(completed.map(result => result.latencyMs), 0.95) },
|
||||
cost: { measured: costs.length, denominator: selected.length, totalUSD: costs.length ? costs.reduce((sum, cost) => sum + cost, 0) : null },
|
||||
modelTokens: { measured: tokens.length, denominator: selected.length, total: tokens.length ? tokens.reduce((sum, count) => sum + count, 0) : null },
|
||||
});
|
||||
}
|
||||
const daily = groups.find(group => group.version === 'v3' && group.mode === 'daily');
|
||||
const comprehensive = groups.find(group => group.version === 'v3' && group.mode === 'comprehensive');
|
||||
const inBatchBaseline = groups.find(group => group.version === 'v2' && group.mode === 'comprehensive');
|
||||
const external = matrix.profile === 'release' && baseline !== undefined ? externalBaselineRecall(matrix, baseline, corpus) : null;
|
||||
const perStack = Object.fromEntries(STACKS.map(stack => {
|
||||
const eligible = matrix.cells.filter(cell => cell.version === 'v3' && cell.mode === 'comprehensive' && cell.variant === 'vulnerable' && cell.stack === stack);
|
||||
// A repaired oracle case demonstrates the full find-to-repair workflow only
|
||||
// when the producer also reported the matching supported finding.
|
||||
const successful = new Set(eligible.filter(cell => {
|
||||
const result = results.get(cell.id);
|
||||
return result?.findings.some(finding => trustedFindingVerification(cell, result, finding, 'repair', corpus));
|
||||
}).map(cell => cell.caseId));
|
||||
return [stack, { correctHeldOutRepairs: successful.size, denominator: new Set(eligible.map(cell => cell.caseId)).size }];
|
||||
}));
|
||||
const assessedAll = observations.length === matrix.cells.length && observations.every(result => result.reportFinished) && groups.every(group => !group.unadjudicated);
|
||||
const gate = (condition: boolean | null, hasData: boolean): 'pass' | 'fail' | 'unmeasured' => !hasData || condition === null ? 'unmeasured' : condition ? 'pass' : 'fail';
|
||||
const containmentValues = REQUIRED_CONTAINMENT.map(name => qualification.containment?.[name]);
|
||||
if (containmentValues.some(value => value !== undefined && !['passed', 'failed', 'not_run'].includes(value))) throw new Error('INVALID_CONTAINMENT_RESULT');
|
||||
const gates = {
|
||||
matchedCompleteMatrix: gate(assessedAll, observations.length > 0),
|
||||
mandatoryReports: gate(groups.every(group => group.finishedReports.numerator === group.finishedReports.denominator), observations.length === matrix.cells.length),
|
||||
dailyPrecision95: gate(daily.precision.value === null ? null : daily.precision.value >= 0.95, daily.submitted === daily.cells && !daily.unadjudicated),
|
||||
comprehensiveHighCriticalRecall80: gate(comprehensive.highCriticalRecall.value >= 0.8, comprehensive.submitted === comprehensive.cells && !comprehensive.unadjudicated),
|
||||
noHighCriticalRecallRegression: profile === 'full'
|
||||
? gate(comprehensive.highCriticalRecall.value >= inBatchBaseline.highCriticalRecall.value, comprehensive.submitted === comprehensive.cells && inBatchBaseline.submitted === inBatchBaseline.cells && !comprehensive.unadjudicated && !inBatchBaseline.unadjudicated)
|
||||
: gate(external === null ? null : comprehensive.highCriticalRecall.value >= external.value!, comprehensive.submitted === comprehensive.cells && !comprehensive.unadjudicated && external !== null),
|
||||
allCoreColdStarts: gate(comprehensive.setup.numerator === comprehensive.setup.denominator, comprehensive.submitted === comprehensive.cells),
|
||||
zeroFalselyTestedRepairs: gate(comprehensive.falseTested === 0 && daily.falseTested === 0, comprehensive.submitted === comprehensive.cells && daily.submitted === daily.cells),
|
||||
heldOutRepairEachStack: gate(Object.values(perStack).every(value => value.correctHeldOutRepairs >= 1), comprehensive.submitted === comprehensive.cells),
|
||||
containmentAndCanaries: containmentValues.includes('failed') ? 'fail' as const : containmentValues.every(value => value === 'passed') ? 'pass' as const : 'unmeasured' as const,
|
||||
};
|
||||
return { schemaVersion: 1, corpusVersion: corpus.version, model: matrix.model, host: matrix.host,
|
||||
...(profile === 'release' ? { profile, baseline: external === null ? null : { baselineHash: baseline!.baselineHash, highCriticalRecall: external } } : {}),
|
||||
status: Object.values(gates).every(value => value === 'pass') ? 'qualified' : observations.length ? 'partial' : 'unmeasured', groups, perStack, gates,
|
||||
notes: ['Missing and setup-blocked supported scenarios remain in recall and workflow denominators.', 'Costs and tokens come only from host-reported usage; wall-clock budgets are not model-spend caps.', 'Oracle judgments and qualification receipts must come from the trusted evaluator, never producing agents.'] };
|
||||
}
|
||||
|
||||
/** Bind a complete collected batch and every trusted judgment to the matrix's producer receipts. */
|
||||
/** Validate the batch against its judgments; a failed producer receipt's report counts nothing, whatever the judge read. */
|
||||
function validateCollectedBatch(matrix: EvalMatrix, batch: ProducerBatch, observations: EvalResult[]): EvalResult[] {
|
||||
if (!Array.isArray(observations)) throw new Error('INVALID_EVAL_RESULTS');
|
||||
if (!batch || batch.schemaVersion !== 1 || batch.matrixHash !== matrixHash(matrix) || !HEX.test(batch.scheduleHash) || !HEX.test(batch.batchHash)) throw new Error('INVALID_PRODUCER_BATCH');
|
||||
const { batchHash, ...withoutHash } = batch;
|
||||
const pairs = expectedMatchedPairs(matrix);
|
||||
if (digest(JSON.stringify(withoutHash)) !== batchHash || !Array.isArray(batch.receipts) || batch.receipts.length !== matrix.cells.length || batch.summary.scheduled !== matrix.cells.length || batch.summary.prepared !== matrix.cells.length || batch.summary.submitted !== matrix.cells.length || batch.summary.missing !== 0 || batch.summary.matchedPairsExpected !== pairs || batch.summary.matchedPairsSubmitted !== pairs || batch.summary.modelMismatches.length !== 0) throw new Error('INCOMPLETE_PRODUCER_BATCH');
|
||||
const cells = new Map(matrix.cells.map(cell => [cell.id, cell]));
|
||||
const receipts = new Map<string, ProducerReceiptIndex>();
|
||||
for (const receipt of batch.receipts) {
|
||||
const cell = cells.get(receipt?.cellRef);
|
||||
if (!cell || receipts.has(cell.id)) throw new Error('INVALID_PRODUCER_BATCH');
|
||||
validateReceiptIndex(receipt, cell); receipts.set(cell.id, receipt);
|
||||
}
|
||||
assertPlatformIdentities(batch.receipts, batch.embeddedCatalogs);
|
||||
if (profileOf(matrix) === 'full') {
|
||||
const actualModels = new Map<string, Partial<Record<EvalVersion, string>>>();
|
||||
for (const receipt of batch.receipts) {
|
||||
const key = matchedPairKey(receipt.cell as EvalCell), pair = actualModels.get(key) ?? {};
|
||||
pair[receipt.cell.version] = receipt.modelUsed; actualModels.set(key, pair);
|
||||
}
|
||||
if (actualModels.size !== pairs || [...actualModels.values()].some(pair => !pair.v2 || !pair.v3 || pair.v2 !== pair.v3)) throw new Error('UNMATCHED_EFFECTIVE_MODELS');
|
||||
} else if (new Set(batch.receipts.map(receipt => receipt.modelUsed)).size !== 1) throw new Error('UNMATCHED_EFFECTIVE_MODELS');
|
||||
for (const result of observations) {
|
||||
const receipt = receipts.get(result.cellId);
|
||||
if (!receipt || result.producerReceiptHash !== receipt.receiptHash) throw new Error('UNBOUND_EVAL_RESULT');
|
||||
}
|
||||
return observations.map(result => receipts.get(result.cellId)!.status === 'failed' ? { ...result, reportFinished: false, reportComplete: false } : result);
|
||||
}
|
||||
|
||||
/** Release scoring path: every trusted judgment must bind to a collected producer receipt. */
|
||||
export function scoreCollectedEval(matrix: EvalMatrix, batch: ProducerBatch, observations: EvalResult[], qualification: ReleaseQualification = { containment: {} }, corpus: EvalCorpusManifest = loadCorpusManifest(), baseline?: EvalBaseline) {
|
||||
validateMatrix(matrix, corpus);
|
||||
if (profileOf(matrix) === 'baseline') throw new Error('BASELINE_PROFILE_NOT_QUALIFIABLE: use createEvalBaseline');
|
||||
const counted = validateCollectedBatch(matrix, batch, observations);
|
||||
if (baseline !== undefined) {
|
||||
const { modelUsed, providerIdentity: { family, policyRevision, version } } = batch.receipts[0];
|
||||
if (baseline?.modelUsed !== modelUsed || JSON.stringify(baseline?.provider) !== JSON.stringify({ family, policyRevision, version })) throw new Error('UNBOUND_EVAL_BASELINE');
|
||||
}
|
||||
const score = scoreEval(matrix, counted, qualification, corpus, baseline);
|
||||
return { ...score, producerBatchHash: batch.batchHash };
|
||||
}
|
||||
|
||||
/**
|
||||
* Turn a complete, fully adjudicated v2 baseline run into a reusable record.
|
||||
* Missing reports, and reports behind a failed producer receipt, count as misses; an incomplete or unadjudicated run is refused.
|
||||
*/
|
||||
export function createEvalBaseline(matrix: BaselineEvalMatrix, batch: ProducerBatch, observations: EvalResult[], corpus: EvalCorpusManifest = loadCorpusManifest()): EvalBaseline {
|
||||
if (matrix?.profile !== 'baseline') throw new Error('INVALID_EVAL_BASELINE_MATRIX');
|
||||
validateMatrix(matrix, corpus);
|
||||
const results = validatedResults(matrix, validateCollectedBatch(matrix, batch, observations), corpus);
|
||||
if (results.size !== matrix.cells.length) throw new Error('INCOMPLETE_EVAL_BASELINE');
|
||||
if ([...results.values()].some(result => result.reportFinished && result.findings.some(finding => finding.evidence !== 'hypothesis' && finding.judgment === 'unadjudicated'))) throw new Error('UNADJUDICATED_EVAL_BASELINE');
|
||||
const vulnerable = new Map(matrix.cells.filter(cell => cell.variant === 'vulnerable').map(cell => [cell.caseId, cell]));
|
||||
const { modelUsed, providerIdentity: { family, policyRevision, version } } = batch.receipts[0];
|
||||
const record: Omit<EvalBaseline, 'baselineHash'> = {
|
||||
schemaVersion: 1, version: 'v2', corpusVersion: corpus.version, corpusHash: matrix.corpusHash, model: matrix.model, host: matrix.host,
|
||||
budgetSeconds: matrix.budgets.comprehensive, skillHash: matrix.skillHashes.v2, platforms: matrix.platforms.comprehensive,
|
||||
matrixHash: matrixHash(matrix), producerBatchHash: batch.batchHash, modelUsed, provider: { family, policyRevision, version },
|
||||
cases: corpus.cases.map(fixture => ({ caseId: fixture.id, found: foundSeededIssue(vulnerable.get(fixture.id)!, results.get(vulnerable.get(fixture.id)!.id)) })),
|
||||
};
|
||||
return { ...record, baselineHash: digest(JSON.stringify(record)) };
|
||||
}
|
||||
|
||||
function splitFlags(args: string[], allowed: string[]): { positional: string[]; flags: Record<string, string> } {
|
||||
const positional: string[] = [], flags: Record<string, string> = {};
|
||||
for (let index = 0; index < args.length; index++) {
|
||||
if (!args[index].startsWith('--')) { positional.push(args[index]); continue; }
|
||||
if (!allowed.includes(args[index]) || !args[index + 1] || flags[args[index]]) throw new Error(`Unsupported or repeated flag: ${args[index]}`);
|
||||
flags[args[index]] = args[++index];
|
||||
}
|
||||
return { positional, flags };
|
||||
}
|
||||
|
||||
function cli(args: string[]): void {
|
||||
const [command, ...rest] = args;
|
||||
if (command === 'payload') {
|
||||
if (rest.length !== 6 || rest[0] !== '--version' || !['v2', 'v3'].includes(rest[1]) || rest[2] !== '--skill-dir' || rest[4] !== '--output') throw new Error('Usage: cso-eval payload --version <v2|v3> --skill-dir <directory> --output <new-file>');
|
||||
const payload = loadPortableSkillPayload(rest[1] as EvalVersion, rest[3]);
|
||||
const target = resolve(rest[5]), parent = dirname(target), stat = lstatSync(parent);
|
||||
if (!stat.isDirectory() || stat.isSymbolicLink() || realpathSync(parent) !== parent) throw new Error('UNSAFE_EVAL_DESTINATION');
|
||||
atomicWriteSync(target, payload, { mode: 0o600, noReplace: true });
|
||||
console.log(JSON.stringify({ version: rest[1], files: validatePortableSkillPayload(payload).files.length, sha256: sha256(payload), output: target, paidCalls: 0 })); return;
|
||||
}
|
||||
if (command === 'materialize') {
|
||||
if (rest.length !== 3 || !['vulnerable', 'fixed'].includes(rest[1])) throw new Error('Usage: cso-eval materialize <case-id> <vulnerable|fixed> <new-directory>');
|
||||
console.log(JSON.stringify(materializeCase(rest[0], rest[1] as EvalVariant, rest[2]), null, 2)); return;
|
||||
}
|
||||
if (command === 'matrix') {
|
||||
const values: Record<string, string> = {};
|
||||
for (let index = 0; index < rest.length; index += 2) {
|
||||
if (!['--model', '--host', '--v2-payload', '--v3-payload', '--output'].includes(rest[index]) || !rest[index + 1] || values[rest[index]]) throw new Error('Usage: cso-eval matrix --model <id> --host <claude|codex|gemini> --v2-payload <file> --v3-payload <file> --output <new-file>');
|
||||
values[rest[index]] = rest[index + 1];
|
||||
}
|
||||
if (Object.keys(values).length !== 5) throw new Error('All matrix flags are required; exact portable skill payloads and model identity must be pinned.');
|
||||
const payloads = { v2: readBoundedStable(resolve(values['--v2-payload']), PORTABLE_PAYLOAD_LIMIT, 'v2 portable skill payload').toString('utf8'), v3: readBoundedStable(resolve(values['--v3-payload']), PORTABLE_PAYLOAD_LIMIT, 'v3 portable skill payload').toString('utf8') };
|
||||
validatePortableSkillPayload(payloads.v2, 'v2'); validatePortableSkillPayload(payloads.v3, 'v3');
|
||||
const matrix = createEvalMatrix({ model: values['--model'], host: values['--host'] as ProducerHost, skillHashes: { v2: digest(payloads.v2), v3: digest(payloads.v3) } });
|
||||
safeWriteNew(values['--output'], matrix); console.log(JSON.stringify({ cells: matrix.cells.length, output: values['--output'], paidCalls: 0 })); return;
|
||||
}
|
||||
if (command === 'prepare') {
|
||||
if (rest.length !== 7 || rest[1] !== '--v2-payload' || rest[3] !== '--v3-payload' || rest[5] !== '--output') throw new Error('Usage: cso-eval prepare <matrix.json> --v2-payload <file> --v3-payload <file> --output <new-directory>');
|
||||
const matrix = readJsonBounded(rest[0], 16 * 1024 * 1024, 'evaluation matrix') as EvalMatrix;
|
||||
const schedule = prepareEvalJobs(matrix, { v2: readBoundedStable(resolve(rest[2]), PORTABLE_PAYLOAD_LIMIT, 'v2 portable skill payload').toString('utf8'), v3: readBoundedStable(resolve(rest[4]), PORTABLE_PAYLOAD_LIMIT, 'v3 portable skill payload').toString('utf8') }, rest[6]);
|
||||
console.log(JSON.stringify({ scheduled: schedule.scheduledCells, prepared: schedule.preparedCells, output: resolve(rest[6]), paidCalls: 0 })); return;
|
||||
}
|
||||
const { positional, flags } = splitFlags(rest, ['--corpus-manifest', '--baseline']);
|
||||
const corpus = flags['--corpus-manifest'] ? validateCorpusManifest(readJsonBounded(flags['--corpus-manifest'], 16 * 1024 * 1024, 'corpus manifest')) : loadCorpusManifest();
|
||||
if (command === 'collect') {
|
||||
if (positional.length !== 4 || flags['--baseline']) throw new Error('Usage: cso-eval collect <matrix.json> <schedule.json> <receipts-directory> <new-batch.json> [--corpus-manifest <manifest.json>]');
|
||||
const [matrixPath, schedulePath, receiptDirectory, output] = positional;
|
||||
const matrix = readJsonBounded(matrixPath, 16 * 1024 * 1024, 'evaluation matrix') as EvalMatrix;
|
||||
const schedule = readJsonBounded(schedulePath, 16 * 1024 * 1024, 'evaluation schedule') as PreparedEvalSchedule;
|
||||
const receiptRoot = resolve(receiptDirectory), stat = lstatSync(receiptRoot);
|
||||
if (!stat.isDirectory() || stat.isSymbolicLink() || realpathSync(receiptRoot) !== receiptRoot) throw new Error('UNSAFE_RECEIPT_DIRECTORY');
|
||||
const receipts: ProducerReceipt[] = [];
|
||||
for (const entry of readdirSync(receiptRoot, { withFileTypes: true })) {
|
||||
if (!entry.isFile() || entry.isSymbolicLink() || !/^[a-f0-9]{64}\.json$/.test(entry.name)) throw new Error('UNSAFE_RECEIPT_DIRECTORY');
|
||||
receipts.push(readJsonBounded(join(receiptRoot, entry.name), 40 * 1024 * 1024, 'producer receipt'));
|
||||
}
|
||||
const batch = collectProducerReceipts(matrix, schedule, receipts, corpus);
|
||||
safeWriteNew(resolve(output), batch);
|
||||
console.log(JSON.stringify({ output: resolve(output), submitted: batch.summary.submitted, missing: batch.summary.missing, modelMismatches: batch.summary.modelMismatches.length, paidCalls: 0 })); return;
|
||||
}
|
||||
if (command === 'score') {
|
||||
if (positional.length < 3 || positional.length > 4) throw new Error('Usage: cso-eval score <matrix.json> <producer-batch.json> <trusted-results.json> [qualification.json] [--corpus-manifest <manifest.json>] [--baseline <baseline.json>]');
|
||||
const baseline = flags['--baseline'] ? readJsonBounded(flags['--baseline'], 4 * 1024 * 1024, 'evaluation baseline') as EvalBaseline : undefined;
|
||||
console.log(JSON.stringify(scoreCollectedEval(readJsonBounded(positional[0], 16 * 1024 * 1024, 'evaluation matrix'), readJsonBounded(positional[1], 16 * 1024 * 1024, 'producer batch'), readJsonBounded(positional[2], 64 * 1024 * 1024, 'trusted results'), positional[3] ? readJsonBounded(positional[3], 4 * 1024 * 1024, 'qualification') : undefined, corpus, baseline), null, 2)); return;
|
||||
}
|
||||
if (command === 'baseline') {
|
||||
if (positional.length !== 4 || flags['--baseline']) throw new Error('Usage: cso-eval baseline <baseline-matrix.json> <producer-batch.json> <trusted-results.json> <new-baseline.json> [--corpus-manifest <manifest.json>]');
|
||||
const baseline = createEvalBaseline(readJsonBounded(positional[0], 16 * 1024 * 1024, 'evaluation matrix'), readJsonBounded(positional[1], 16 * 1024 * 1024, 'producer batch'), readJsonBounded(positional[2], 64 * 1024 * 1024, 'trusted results'), corpus);
|
||||
safeWriteNew(resolve(positional[3]), baseline);
|
||||
console.log(JSON.stringify({ output: resolve(positional[3]), baselineHash: baseline.baselineHash, paidCalls: 0 })); return;
|
||||
}
|
||||
throw new Error('Usage: cso-eval <payload|matrix|prepare|materialize|collect|score|baseline>');
|
||||
}
|
||||
if (import.meta.main) { try { cli(process.argv.slice(2)); } catch (error) { console.error(error instanceof Error ? error.message : 'CSO evaluation failed'); process.exitCode = 1; } }
|
||||
@@ -1,131 +0,0 @@
|
||||
#!/usr/bin/env -S bun --no-env-file --config=/dev/null
|
||||
/** Derive native runtime gate evidence from the named Docker tests that actually executed and passed. */
|
||||
import * as fs from 'node:fs';
|
||||
import * as path from 'node:path';
|
||||
import { sha256 } from '../lib/cso/contracts';
|
||||
import type { ImageBuildRow } from './cso-image-matrix';
|
||||
import { requiredChecks } from './cso-runtime-promotion';
|
||||
|
||||
type Stack = ImageBuildRow['stack'];
|
||||
export interface TestRef { file: string; name: string }
|
||||
export interface JUnitCase extends TestRef { status: 'passed' | 'failed' | 'skipped'; assertions: number }
|
||||
|
||||
const MAX_REPORT_BYTES = 4 * 1024 * 1024;
|
||||
const DOCKER = 'test/cso-docker-integration.test.ts';
|
||||
const CONTAINMENT: TestRef[] = [
|
||||
{ file: DOCKER, name: 'hard fails when local daemon enforcement prerequisites are absent' },
|
||||
{ file: DOCKER, name: 'rejects image-declared writable volumes before container creation' },
|
||||
{ file: DOCKER, name: 'shares only loopback while denying egress, privileges, and daemon logs, and reads private source/policy mounts' },
|
||||
{ file: DOCKER, name: 'machine-wide admission allows only two groups per endpoint' },
|
||||
];
|
||||
const STAGED: TestRef = { file: DOCKER, name: 'staged runtime executes its trusted verifier and checks every declared tool version' };
|
||||
const NODE_LIFECYCLE: TestRef = {
|
||||
file: 'test/cso-node-lifecycle-integration.test.ts',
|
||||
name: 'finds, reproduces, bundles, replays, and closes against current source through the command dispatcher',
|
||||
};
|
||||
const COLD_JOURNEY: TestRef = {
|
||||
file: 'test/cso-stack-cold-integration.test.ts',
|
||||
name: 'acquires, prepares, boots, controls, and tests the requested staged stack with no target egress',
|
||||
};
|
||||
|
||||
/** Each native check key names the tests whose execution proves it for one stack. */
|
||||
export function nativeTestRequirements(stack: Stack): Record<string, TestRef[]> {
|
||||
if (stack === 'postgresql') return {
|
||||
containmentPassed: [...CONTAINMENT, STAGED],
|
||||
coldStartPassed: [STAGED],
|
||||
multiDatabasePassed: [STAGED],
|
||||
readinessPassed: [STAGED],
|
||||
};
|
||||
const journey = stack === 'node' ? NODE_LIFECYCLE : COLD_JOURNEY;
|
||||
const application = {
|
||||
containmentPassed: [...CONTAINMENT, STAGED],
|
||||
coldStartPassed: [journey],
|
||||
positiveNegativeAssertionsPassed: [STAGED],
|
||||
acquisitionPublicOnlyPassed: [journey],
|
||||
offlineLifecyclePassed: [journey],
|
||||
};
|
||||
return stack === 'rails'
|
||||
? { ...application, railsSqlitePassed: [COLD_JOURNEY], railsPostgresqlPassed: [COLD_JOURNEY], nativeExtensionsPassed: [COLD_JOURNEY] }
|
||||
: application;
|
||||
}
|
||||
|
||||
function decode(value: string): string {
|
||||
return value.replace(/&(#x[0-9a-fA-F]+|#[0-9]+|amp|lt|gt|quot|apos);/g, (_, entity: string) => {
|
||||
if (entity.startsWith('#x')) return String.fromCodePoint(Number.parseInt(entity.slice(2), 16));
|
||||
if (entity.startsWith('#')) return String.fromCodePoint(Number.parseInt(entity.slice(1), 10));
|
||||
return { amp: '&', lt: '<', gt: '>', quot: '"', apos: "'" }[entity]!;
|
||||
});
|
||||
}
|
||||
|
||||
/** Parse the testcases of Bun's `--reporter=junit` output. */
|
||||
export function parseJUnit(xml: string): JUnitCase[] {
|
||||
if (!/^<\?xml[^>]*\?>\s*<testsuites\b/.test(xml)) throw new Error('INVALID_JUNIT_REPORT');
|
||||
const cases: JUnitCase[] = [];
|
||||
for (const match of xml.matchAll(/<testcase\b([^>]*?)(?:\/>|>([\s\S]*?)<\/testcase>)/g)) {
|
||||
const attributes = Object.fromEntries([...match[1].matchAll(/([A-Za-z_:][\w:.-]*)="([^"]*)"/g)].map(([, key, value]) => [key, decode(value)]));
|
||||
const body = match[2] ?? '';
|
||||
const status = /<(?:failure|error)\b/.test(body) ? 'failed' : /<skipped\b/.test(body) ? 'skipped' : 'passed';
|
||||
const assertions = Number(attributes.assertions ?? '0');
|
||||
if (typeof attributes.name !== 'string' || typeof attributes.file !== 'string' || !Number.isInteger(assertions) || assertions < 0) {
|
||||
throw new Error('INVALID_JUNIT_TESTCASE');
|
||||
}
|
||||
cases.push({ file: attributes.file, name: attributes.name, status, assertions });
|
||||
}
|
||||
if (cases.length === 0) throw new Error('EMPTY_JUNIT_REPORT');
|
||||
return cases;
|
||||
}
|
||||
|
||||
/** A check passes only when the whole report has no failure and every named test ran once, passed, and asserted. */
|
||||
export function deriveNativeChecks(stack: Stack, cases: JUnitCase[]): Record<string, boolean> {
|
||||
const clean = cases.some(item => item.status === 'passed') && !cases.some(item => item.status === 'failed');
|
||||
const passed = (ref: TestRef) => {
|
||||
const matches = cases.filter(item => item.file === ref.file && item.name === ref.name);
|
||||
return matches.length === 1 && matches[0].status === 'passed' && matches[0].assertions > 0;
|
||||
};
|
||||
return Object.fromEntries(Object.entries(nativeTestRequirements(stack))
|
||||
.map(([key, refs]) => [key, clean && refs.every(passed)]));
|
||||
}
|
||||
|
||||
/** Native evidence for one staged row; private checks are every required release gate the native job cannot prove. */
|
||||
export function nativeEvidence(staged: unknown, stack: Stack, platform: string, report: string): Record<string, unknown> {
|
||||
const record = staged as Record<string, unknown>;
|
||||
if (!record || typeof record !== 'object' || record.state !== 'staged' || record.stack !== stack || record.platform !== platform) {
|
||||
throw new Error('STAGED_EVIDENCE_MISMATCH');
|
||||
}
|
||||
const required = requiredChecks(stack);
|
||||
const nativeChecks = deriveNativeChecks(stack, parseJUnit(report));
|
||||
const failed = Object.entries(nativeChecks).filter(([key, value]) => !value || !required.includes(key)).map(([key]) => key);
|
||||
if (failed.length) throw new Error(`NATIVE_GATE_NOT_PASSED: ${failed.sort().join(', ')}`);
|
||||
return {
|
||||
...record,
|
||||
state: 'native-gates-passed',
|
||||
nativeChecks,
|
||||
nativeTestReport: `sha256:${sha256(report)}`,
|
||||
privateChecks: Object.fromEntries(required.filter(key => !(key in nativeChecks)).map(key => [key, 'pending'])),
|
||||
qualified: false,
|
||||
promotion: 'prohibited until authenticated private qualification evidence completes every release gate',
|
||||
};
|
||||
}
|
||||
|
||||
function readFile(file: string): string {
|
||||
const stat = fs.lstatSync(path.resolve(file));
|
||||
if (!stat.isFile() || stat.isSymbolicLink() || stat.size <= 0 || stat.size > MAX_REPORT_BYTES) throw new Error('UNSAFE_NATIVE_EVIDENCE_INPUT');
|
||||
return fs.readFileSync(path.resolve(file), 'utf8');
|
||||
}
|
||||
|
||||
if (import.meta.main) {
|
||||
try {
|
||||
const args = process.argv.slice(2);
|
||||
const names = ['--stack', '--platform', '--junit', '--staged', '--output'];
|
||||
if (args.length !== names.length * 2 || names.some((name, index) => args[index * 2] !== name)) {
|
||||
throw new Error('Usage: cso-native-evidence.ts --stack STACK --platform PLATFORM --junit REPORT.xml --staged staged-image.json --output EVIDENCE.json');
|
||||
}
|
||||
const [stack, platform, junit, staged, output] = names.map((_, index) => args[index * 2 + 1]);
|
||||
if (!['node', 'bun', 'python', 'rails', 'postgresql'].includes(stack)) throw new Error('INVALID_STACK');
|
||||
const evidence = nativeEvidence(JSON.parse(readFile(staged)), stack as Stack, platform, readFile(junit));
|
||||
fs.writeFileSync(path.resolve(output), JSON.stringify(evidence, null, 2) + '\n', { flag: 'wx', mode: 0o600 });
|
||||
} catch (error) {
|
||||
process.stderr.write((error instanceof Error ? error.message : 'NATIVE_EVIDENCE_FAILED') + '\n');
|
||||
process.exitCode = 1;
|
||||
}
|
||||
}
|
||||
@@ -1,262 +0,0 @@
|
||||
#!/usr/bin/env -S bun --no-env-file --config=/dev/null
|
||||
/** Release-only proof that a CSO image is public and anonymously pullable. */
|
||||
import * as fs from 'node:fs';
|
||||
import * as os from 'node:os';
|
||||
import * as path from 'node:path';
|
||||
|
||||
const REPOSITORY = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/;
|
||||
const DIGEST = /^sha256:[a-f0-9]{64}$/;
|
||||
const PLATFORM = /^linux\/(amd64|arm64)$/;
|
||||
const RUNTIME = /^(node|bun|python|rails|postgresql)-(amd64|arm64)$/;
|
||||
const SCANNER = /^(gitleaks|osv|semgrep|zizmor|trivy|schemathesis)-(amd64|arm64)$/;
|
||||
const MAX_HTTP_BYTES = 64 * 1024;
|
||||
const MAX_DOCKER_OUTPUT = 64 * 1024;
|
||||
const DOCKER_TIMEOUT_MS = 10 * 60 * 1000;
|
||||
|
||||
export interface PublicGhcrTarget {
|
||||
image: string;
|
||||
owner: string;
|
||||
repository: string;
|
||||
packageName: string;
|
||||
digest: string;
|
||||
platform: 'linux/amd64' | 'linux/arm64';
|
||||
}
|
||||
|
||||
export interface PublicImageProof {
|
||||
schemaVersion: 1;
|
||||
image: string;
|
||||
platform: 'linux/amd64' | 'linux/arm64';
|
||||
packageName: string;
|
||||
packageVisibility: 'public';
|
||||
packageApiUrl: string;
|
||||
anonymousPull: 'passed';
|
||||
dockerConfig: 'isolated-empty-auths';
|
||||
verifiedAt: string;
|
||||
}
|
||||
|
||||
interface CommandResult { exitCode: number; stdout: string; stderr: string }
|
||||
export interface PublicGhcrDependencies {
|
||||
fetch: typeof globalThis.fetch;
|
||||
githubToken: string;
|
||||
dockerPath: string;
|
||||
runDocker: (args: string[], env: Record<string, string>) => Promise<CommandResult>;
|
||||
now: () => string;
|
||||
sleep: (ms: number) => Promise<void>;
|
||||
}
|
||||
|
||||
function fail(message: string): never { throw new Error(message); }
|
||||
|
||||
export function parsePublicGhcrTarget(image: string, platform: string, githubRepository: string): PublicGhcrTarget {
|
||||
if (!REPOSITORY.test(githubRepository)) fail('INVALID_GITHUB_REPOSITORY');
|
||||
const platformMatch = PLATFORM.exec(platform);
|
||||
if (!platformMatch) fail('INVALID_PUBLIC_IMAGE_PLATFORM');
|
||||
const normalizedRepository = githubRepository.toLowerCase();
|
||||
const prefix = `ghcr.io/${normalizedRepository}/`;
|
||||
if (!image.startsWith(prefix)) fail('PUBLIC_IMAGE_REPOSITORY_MISMATCH');
|
||||
const at = image.lastIndexOf('@');
|
||||
if (at < prefix.length || image.indexOf('@') !== at) fail('PUBLIC_IMAGE_MUST_BE_DIGEST_PINNED');
|
||||
const suffix = image.slice(prefix.length, at), digest = image.slice(at + 1);
|
||||
if (!DIGEST.test(digest)) fail('PUBLIC_IMAGE_MUST_BE_DIGEST_PINNED');
|
||||
const [namespace, name, extra] = suffix.split('/');
|
||||
if (extra || !name || !['cso-staging', 'cso-scanners'].includes(namespace)) fail('INVALID_PUBLIC_IMAGE_PACKAGE');
|
||||
const nameMatch = namespace === 'cso-staging' ? RUNTIME.exec(name) : SCANNER.exec(name);
|
||||
if (!nameMatch || nameMatch[2] !== platformMatch[1]) fail('PUBLIC_IMAGE_PLATFORM_MISMATCH');
|
||||
const [owner, repository] = normalizedRepository.split('/');
|
||||
return {
|
||||
image,
|
||||
owner,
|
||||
repository,
|
||||
packageName: `${repository}/${namespace}/${name}`,
|
||||
digest,
|
||||
platform: platform as PublicGhcrTarget['platform'],
|
||||
};
|
||||
}
|
||||
|
||||
async function responseJson(response: Response, label: string): Promise<Record<string, unknown>> {
|
||||
const body = await response.text();
|
||||
if (body.length > MAX_HTTP_BYTES) fail(`${label}_RESPONSE_TOO_LARGE`);
|
||||
let parsed: unknown;
|
||||
try { parsed = JSON.parse(body); } catch { fail(`${label}_INVALID_RESPONSE`); }
|
||||
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) fail(`${label}_INVALID_RESPONSE`);
|
||||
return parsed as Record<string, unknown>;
|
||||
}
|
||||
|
||||
function publicHeaders(githubToken: string): Record<string, string> {
|
||||
return {
|
||||
Accept: 'application/vnd.github+json',
|
||||
Authorization: `Bearer ${githubToken}`,
|
||||
'X-GitHub-Api-Version': '2022-11-28',
|
||||
'User-Agent': 'gstack-cso-public-image-verifier',
|
||||
};
|
||||
}
|
||||
|
||||
export function assertPublicPackageMetadata(value: Record<string, unknown>, target: PublicGhcrTarget): void {
|
||||
const owner = value.owner;
|
||||
if (value.name !== target.packageName || value.package_type !== 'container' || value.visibility !== 'public' ||
|
||||
!owner || typeof owner !== 'object' || Array.isArray(owner) ||
|
||||
typeof (owner as Record<string, unknown>).login !== 'string' ||
|
||||
((owner as Record<string, unknown>).login as string).toLowerCase() !== target.owner) {
|
||||
fail('GHCR_PACKAGE_IS_NOT_PUBLIC');
|
||||
}
|
||||
}
|
||||
|
||||
async function publicPackageApi(target: PublicGhcrTarget, deps: PublicGhcrDependencies): Promise<string> {
|
||||
const ownerUrl = `https://api.github.com/users/${encodeURIComponent(target.owner)}`;
|
||||
const ownerResponse = await deps.fetch(ownerUrl, { headers: publicHeaders(deps.githubToken), redirect: 'error', signal: AbortSignal.timeout(15_000) });
|
||||
if (ownerResponse.status !== 200) fail(`PUBLIC_OWNER_LOOKUP_FAILED: HTTP ${ownerResponse.status}`);
|
||||
const owner = await responseJson(ownerResponse, 'PUBLIC_OWNER_LOOKUP');
|
||||
if (typeof owner.login !== 'string' || owner.login.toLowerCase() !== target.owner || !['User', 'Organization'].includes(String(owner.type))) {
|
||||
fail('PUBLIC_OWNER_LOOKUP_IDENTITY_MISMATCH');
|
||||
}
|
||||
const collection = owner.type === 'Organization' ? 'orgs' : 'users';
|
||||
const packageUrl = `https://api.github.com/${collection}/${encodeURIComponent(target.owner)}/packages/container/${encodeURIComponent(target.packageName)}`;
|
||||
let lastStatus = 0;
|
||||
for (let attempt = 1; attempt <= 6; attempt++) {
|
||||
const response = await deps.fetch(packageUrl, { headers: publicHeaders(deps.githubToken), redirect: 'error', signal: AbortSignal.timeout(15_000) });
|
||||
lastStatus = response.status;
|
||||
if (response.status === 200) {
|
||||
assertPublicPackageMetadata(await responseJson(response, 'PUBLIC_PACKAGE_LOOKUP'), target);
|
||||
return packageUrl;
|
||||
}
|
||||
await response.body?.cancel();
|
||||
if (attempt < 6 && [404, 429, 500, 502, 503, 504].includes(response.status)) await deps.sleep(attempt * 2_000);
|
||||
else break;
|
||||
}
|
||||
fail(`GHCR_PACKAGE_IS_NOT_PUBLIC: authenticated GitHub Packages metadata lookup returned HTTP ${lastStatus}`);
|
||||
}
|
||||
|
||||
function cleanDockerEnvironment(configRoot: string, dockerHost: string): Record<string, string> {
|
||||
return {
|
||||
HOME: configRoot,
|
||||
DOCKER_CONFIG: configRoot,
|
||||
DOCKER_HOST: dockerHost,
|
||||
LANG: 'C.UTF-8',
|
||||
LC_ALL: 'C.UTF-8',
|
||||
PATH: '/usr/local/bin:/usr/bin:/bin',
|
||||
TMPDIR: configRoot,
|
||||
};
|
||||
}
|
||||
|
||||
async function defaultRunDocker(dockerPath: string, args: string[], env: Record<string, string>): Promise<CommandResult> {
|
||||
const process = Bun.spawn([dockerPath, ...args], { env, stdin: 'ignore', stdout: 'pipe', stderr: 'pipe' });
|
||||
const timeout = setTimeout(() => process.kill(), DOCKER_TIMEOUT_MS);
|
||||
const boundedText = async (stream: ReadableStream<Uint8Array>): Promise<string> => {
|
||||
const reader = stream.getReader(), chunks: Uint8Array[] = [];
|
||||
let bytes = 0;
|
||||
try {
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
bytes += value.byteLength;
|
||||
if (bytes > MAX_DOCKER_OUTPUT) {
|
||||
process.kill();
|
||||
await reader.cancel();
|
||||
fail('ANONYMOUS_DOCKER_OUTPUT_LIMIT');
|
||||
}
|
||||
chunks.push(value);
|
||||
}
|
||||
return Buffer.concat(chunks.map(chunk => Buffer.from(chunk))).toString('utf8');
|
||||
} finally { reader.releaseLock(); }
|
||||
};
|
||||
try {
|
||||
const [stdout, stderr, exitCode] = await Promise.all([
|
||||
boundedText(process.stdout),
|
||||
boundedText(process.stderr),
|
||||
process.exited,
|
||||
]);
|
||||
return { exitCode, stdout, stderr };
|
||||
} finally { clearTimeout(timeout); }
|
||||
}
|
||||
|
||||
function dockerError(label: string, result: CommandResult): never {
|
||||
const detail = result.stderr.trim().slice(0, 2048);
|
||||
fail(`${label}${detail ? `: ${detail}` : ''}`);
|
||||
}
|
||||
|
||||
export async function verifyPublicGhcrImage(
|
||||
options: { image: string; platform: string; githubRepository: string; dockerHost?: string; removeAfter?: boolean },
|
||||
dependencies?: Partial<PublicGhcrDependencies>,
|
||||
): Promise<PublicImageProof> {
|
||||
const target = parsePublicGhcrTarget(options.image, options.platform, options.githubRepository);
|
||||
const dockerHost = options.dockerHost ?? 'unix:///var/run/docker.sock';
|
||||
if (dockerHost !== 'unix:///var/run/docker.sock') fail('UNTRUSTED_PUBLIC_IMAGE_DOCKER_HOST');
|
||||
const dockerPath = dependencies?.dockerPath ?? Bun.which('docker') ?? '';
|
||||
if (!path.isAbsolute(dockerPath)) fail('DOCKER_UNAVAILABLE');
|
||||
const githubToken = dependencies?.githubToken ?? process.env.GH_TOKEN ?? process.env.GITHUB_TOKEN ?? '';
|
||||
if (!githubToken || githubToken.length > 2048 || /[\r\n]/.test(githubToken)) fail('GITHUB_PACKAGE_METADATA_TOKEN_REQUIRED');
|
||||
const deps: PublicGhcrDependencies = {
|
||||
fetch: dependencies?.fetch ?? globalThis.fetch,
|
||||
githubToken,
|
||||
dockerPath,
|
||||
runDocker: dependencies?.runDocker ?? ((args, env) => defaultRunDocker(dockerPath, args, env)),
|
||||
now: dependencies?.now ?? (() => new Date().toISOString()),
|
||||
sleep: dependencies?.sleep ?? (ms => Bun.sleep(ms)),
|
||||
};
|
||||
const packageApiUrl = await publicPackageApi(target, deps);
|
||||
const configRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-cso-anonymous-docker-'));
|
||||
fs.chmodSync(configRoot, 0o700);
|
||||
fs.writeFileSync(path.join(configRoot, 'config.json'), '{"auths":{}}\n', { flag: 'wx', mode: 0o600 });
|
||||
const env = cleanDockerEnvironment(configRoot, dockerHost);
|
||||
let pulled = false;
|
||||
try {
|
||||
const pull = await deps.runDocker([
|
||||
'--config', configRoot, '--host', dockerHost, 'image', 'pull', '--quiet', '--platform', target.platform, target.image,
|
||||
], env);
|
||||
if (pull.exitCode !== 0) dockerError('ANONYMOUS_IMAGE_PULL_FAILED', pull);
|
||||
pulled = true;
|
||||
const inspect = await deps.runDocker([
|
||||
'--config', configRoot, '--host', dockerHost, 'image', 'inspect', target.image, '--format', '{{json .RepoDigests}}',
|
||||
], env);
|
||||
if (inspect.exitCode !== 0) dockerError('ANONYMOUS_IMAGE_INSPECT_FAILED', inspect);
|
||||
let repoDigests: unknown;
|
||||
try { repoDigests = JSON.parse(inspect.stdout.trim()); } catch { fail('ANONYMOUS_IMAGE_INSPECT_INVALID'); }
|
||||
if (!Array.isArray(repoDigests) || !repoDigests.includes(target.image)) fail('ANONYMOUS_IMAGE_DIGEST_MISMATCH');
|
||||
return {
|
||||
schemaVersion: 1,
|
||||
image: target.image,
|
||||
platform: target.platform,
|
||||
packageName: target.packageName,
|
||||
packageVisibility: 'public',
|
||||
packageApiUrl,
|
||||
anonymousPull: 'passed',
|
||||
dockerConfig: 'isolated-empty-auths',
|
||||
verifiedAt: deps.now(),
|
||||
};
|
||||
} finally {
|
||||
if (pulled && options.removeAfter) {
|
||||
const remove = await deps.runDocker([
|
||||
'--config', configRoot, '--host', dockerHost, 'image', 'rm', '--force', target.image,
|
||||
], env);
|
||||
if (remove.exitCode !== 0) dockerError('ANONYMOUS_IMAGE_CLEANUP_FAILED', remove);
|
||||
}
|
||||
fs.rmSync(configRoot, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
function option(args: string[], name: string): string | undefined {
|
||||
const index = args.indexOf(name);
|
||||
if (index < 0) return undefined;
|
||||
const value = args[index + 1];
|
||||
if (!value || value.startsWith('--')) fail(`MISSING_${name.slice(2).toUpperCase().replaceAll('-', '_')}`);
|
||||
args.splice(index, 2);
|
||||
return value;
|
||||
}
|
||||
|
||||
if (import.meta.main) {
|
||||
try {
|
||||
const args = process.argv.slice(2), command = args.shift();
|
||||
const image = option(args, '--image'), platform = option(args, '--platform'), repository = option(args, '--repository');
|
||||
const output = option(args, '--output'), dockerHost = option(args, '--docker-host');
|
||||
const removeAt = args.indexOf('--remove-after'), removeAfter = removeAt >= 0;
|
||||
if (removeAfter) args.splice(removeAt, 1);
|
||||
if (command !== 'verify' || !image || !platform || !repository || !output || args.length) {
|
||||
fail('Usage: cso-public-ghcr.ts verify --image IMAGE@sha256:DIGEST --platform linux/ARCH --repository OWNER/REPO --output PROOF.json [--docker-host unix:///var/run/docker.sock] [--remove-after]');
|
||||
}
|
||||
const proof = await verifyPublicGhcrImage({ image, platform, githubRepository: repository, dockerHost, removeAfter });
|
||||
fs.writeFileSync(path.resolve(output), JSON.stringify(proof, null, 2) + '\n', { flag: 'wx', mode: 0o600 });
|
||||
process.stdout.write(`ANONYMOUS PULL VERIFIED ${proof.image}\n`);
|
||||
} catch (error) {
|
||||
process.stderr.write((error instanceof Error ? error.message : 'PUBLIC_IMAGE_VERIFICATION_FAILED') + '\n');
|
||||
process.exitCode = 1;
|
||||
}
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
# Accept only a package-level SPDX 2.3 document whose relationships name known elements.
|
||||
.spdxVersion == "SPDX-2.3"
|
||||
and (.packages | type == "array" and length > 0)
|
||||
and (has("files") | not)
|
||||
and (([.SPDXID, .packages[].SPDXID] | map({key: ., value: true}) | from_entries) as $known
|
||||
| all(.relationships[]; ($known[.spdxElementId] // false)
|
||||
and (($known[.relatedSpdxElement] // false) or (.relatedSpdxElement | test("^(NONE|NOASSERTION)$|^DocumentRef-")))))
|
||||
@@ -1,8 +0,0 @@
|
||||
# Reduce a BuildKit SPDX 2.3 SBOM to its package inventory before signing it.
|
||||
# File entries (tens of thousands for Ruby or Python images) push the signed
|
||||
# statement past actions/attest's 16 MiB limit; packages, their versions and
|
||||
# package relationships are what CSO's release evidence relies on.
|
||||
((.files // []) | map({key: .SPDXID, value: true}) | from_entries) as $files
|
||||
| del(.files)
|
||||
| .packages |= map(del(.hasFiles))
|
||||
| .relationships |= map(select(($files[.spdxElementId] // false | not) and ($files[.relatedSpdxElement] // false | not)))
|
||||
@@ -1,173 +0,0 @@
|
||||
#!/usr/bin/env -S bun --no-env-file --config=/dev/null
|
||||
/** Assemble and validate a complete source-controlled scanner catalog proposal. */
|
||||
import * as fs from 'node:fs';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { basename, join, relative, resolve, sep } from 'node:path';
|
||||
import { canonical, sha256 } from '../lib/cso/contracts';
|
||||
import { QualifiedScanner, ScannerCatalog, scannerVersionHash, validateQualifiedScanner, validateScannerCatalog } from '../lib/cso/scanner-catalog';
|
||||
import { SCANNER_IDS, scannerPlans } from '../lib/cso/scanners';
|
||||
|
||||
const PLATFORMS = ['linux/amd64', 'linux/arm64'] as const;
|
||||
const REVISION = /^[a-z0-9][a-z0-9._-]{0,100}$/;
|
||||
const WORKFLOW = /^https:\/\/github\.com\/[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+\/actions\/runs\/[0-9]+$/;
|
||||
const MAX_ARTIFACT = 1_048_576;
|
||||
const MAX_TREE_BYTES = 10 * 1024 * 1024 * 1024;
|
||||
const MAX_TREE_ENTRIES = 100_000;
|
||||
|
||||
function sameFile(left: fs.Stats, right: fs.Stats): boolean {
|
||||
return left.dev === right.dev && left.ino === right.ino && left.mode === right.mode && left.nlink === right.nlink && left.size === right.size;
|
||||
}
|
||||
function hashRegularFile(path: string, expected: fs.Stats): string {
|
||||
const hash = createHash('sha256'), fd = fs.openSync(path, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0));
|
||||
try {
|
||||
const before = fs.fstatSync(fd);
|
||||
if (!before.isFile() || before.nlink !== 1 || !sameFile(expected, before)) throw new Error('UNSAFE_SCANNER_ASSET');
|
||||
const buffer = Buffer.alloc(1024 * 1024); let count = 0, bytes = 0;
|
||||
while ((count = fs.readSync(fd, buffer, 0, buffer.length, null)) > 0) {
|
||||
bytes += count;
|
||||
if (bytes > expected.size || bytes > MAX_TREE_BYTES) throw new Error('SCANNER_ASSET_LIMIT');
|
||||
hash.update(buffer.subarray(0, count));
|
||||
}
|
||||
const after = fs.fstatSync(fd), pathname = fs.lstatSync(path);
|
||||
if (bytes !== expected.size || !sameFile(before, after) || !sameFile(after, pathname)) throw new Error('UNSAFE_SCANNER_ASSET');
|
||||
return hash.digest('hex');
|
||||
} finally { fs.closeSync(fd); }
|
||||
}
|
||||
|
||||
function sameStrings(left: string[], right: string[]): boolean {
|
||||
return canonical([...left].sort()) === canonical([...right].sort());
|
||||
}
|
||||
function exactKeys(value: Record<string, unknown>, allowed: string[], label: string): void {
|
||||
if (Object.keys(value).some(key => !allowed.includes(key))) throw new Error(`UNEXPECTED_${label.toUpperCase()}_FIELD`);
|
||||
}
|
||||
function strictProfile(value: unknown): QualifiedScanner {
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('INVALID_SCANNER_FRAGMENT');
|
||||
const profile = value as QualifiedScanner & Record<string, unknown>;
|
||||
exactKeys(profile, ['id', 'scanner', 'state', 'platform', 'image', 'entrypoint', 'executable', 'version', 'versionOutputSha256', 'helperAbi', 'isolationPolicyHash', 'capabilities', 'assets', 'qualifiedAt', 'qualification'], 'scanner_profile');
|
||||
if (!profile.qualification || typeof profile.qualification !== 'object' || Array.isArray(profile.qualification)) throw new Error('INVALID_SCANNER_QUALIFICATION');
|
||||
exactKeys(profile.qualification as unknown as Record<string, unknown>, ['sourceCommit', 'workflow', 'sbomDigest', 'provenanceDigest', 'verifiedProvenance', 'containmentPassed', 'adapterContractPassed', 'offlineAssetsPassed'], 'scanner_qualification');
|
||||
if (profile.assets !== undefined) {
|
||||
if (!profile.assets || typeof profile.assets !== 'object' || Array.isArray(profile.assets)) throw new Error('INVALID_SCANNER_ASSETS');
|
||||
exactKeys(profile.assets as unknown as Record<string, unknown>, ['semgrepRules', 'advisoryDatabase'], 'scanner_assets');
|
||||
for (const [name, asset] of Object.entries(profile.assets)) {
|
||||
if (!asset || typeof asset !== 'object' || Array.isArray(asset)) throw new Error('INVALID_SCANNER_ASSETS');
|
||||
exactKeys(asset as unknown as Record<string, unknown>, name === 'semgrepRules' ? ['path', 'sha256'] : ['path', 'contentSha256', 'updatedAt', 'ecosystems'], 'scanner_asset');
|
||||
}
|
||||
}
|
||||
validateQualifiedScanner(profile);
|
||||
const required = scannerPlans({ snapshotRoot: '/source', offline: true, selected: [profile.scanner] })[0].requiredFeatures;
|
||||
if (!sameStrings(profile.capabilities, required)) throw new Error(`CAPABILITY_CONTRACT_MISMATCH: ${profile.scanner}`);
|
||||
return profile;
|
||||
}
|
||||
|
||||
export function scannerCatalogProposal(current: ScannerCatalog, fragments: unknown[], revision: string, expected: { sourceCommit: string; workflow: string; imagePrefix: string }): ScannerCatalog {
|
||||
validateScannerCatalog(current);
|
||||
if (!REVISION.test(revision) || revision === current.revision) throw new Error('INVALID_SCANNER_CATALOG_REVISION');
|
||||
if (!expected || !/^[a-f0-9]{40}$/.test(expected.sourceCommit)) throw new Error('INVALID_EXPECTED_SOURCE_COMMIT');
|
||||
if (!WORKFLOW.test(expected.workflow) || !expected.workflow.startsWith('https://github.com/garrytan/gstack/actions/runs/')) throw new Error('INVALID_EXPECTED_WORKFLOW');
|
||||
if (expected.imagePrefix !== 'ghcr.io/garrytan/gstack/cso-scanners/') throw new Error('INVALID_EXPECTED_IMAGE_PREFIX');
|
||||
const scanners = fragments.map(strictProfile), identities = new Set<string>();
|
||||
if (scanners.length !== SCANNER_IDS.length * PLATFORMS.length) throw new Error('INCOMPLETE_SCANNER_CATALOG_MATRIX');
|
||||
for (const profile of scanners) {
|
||||
const identity = `${profile.scanner}:${profile.platform}`;
|
||||
if (identities.has(identity)) throw new Error(`DUPLICATE_SCANNER_CATALOG_PROFILE: ${identity}`);
|
||||
identities.add(identity);
|
||||
if (profile.qualification.sourceCommit !== expected.sourceCommit) throw new Error(`SOURCE_COMMIT_MISMATCH: ${identity}`);
|
||||
if (profile.qualification.workflow !== expected.workflow) throw new Error(`WORKFLOW_IDENTITY_MISMATCH: ${identity}`);
|
||||
if (!profile.image.startsWith(expected.imagePrefix)) throw new Error(`IMAGE_REPOSITORY_MISMATCH: ${identity}`);
|
||||
}
|
||||
for (const scanner of SCANNER_IDS) for (const platform of PLATFORMS) if (!identities.has(`${scanner}:${platform}`)) throw new Error(`MISSING_SCANNER_CATALOG_PROFILE: ${scanner}:${platform}`);
|
||||
scanners.sort((a, b) => a.scanner.localeCompare(b.scanner) || a.platform.localeCompare(b.platform));
|
||||
const proposal: ScannerCatalog = {
|
||||
schemaVersion: 1,
|
||||
revision,
|
||||
previousRevision: current.revision,
|
||||
helperAbi: 3,
|
||||
promotion: { sourceCommit: expected.sourceCommit, workflow: expected.workflow, evidenceDigest: `sha256:${sha256(canonical(scanners))}` },
|
||||
scanners,
|
||||
};
|
||||
validateScannerCatalog(proposal);
|
||||
return proposal;
|
||||
}
|
||||
|
||||
/** Promotion is a compare-and-swap against the catalog revision reviewed by qualification. */
|
||||
export function validateScannerCatalogTransition(current: ScannerCatalog, proposed: ScannerCatalog): void {
|
||||
validateScannerCatalog(current); validateScannerCatalog(proposed);
|
||||
if (proposed.revision === current.revision || proposed.previousRevision !== current.revision)
|
||||
throw new Error('SCANNER_CATALOG_BASE_REVISION_MISMATCH');
|
||||
}
|
||||
|
||||
function readJson(path: string): unknown {
|
||||
const stat = fs.lstatSync(path);
|
||||
if (stat.isSymbolicLink() || !stat.isFile() || stat.nlink !== 1 || stat.size > MAX_ARTIFACT) throw new Error(`UNSAFE_CATALOG_ARTIFACT: ${basename(path)}`);
|
||||
return JSON.parse(fs.readFileSync(path, 'utf8'));
|
||||
}
|
||||
function fragments(directory: string): unknown[] {
|
||||
const root = fs.realpathSync(directory), values: unknown[] = [];
|
||||
for (const name of fs.readdirSync(root).sort()) {
|
||||
if (!/^[a-z0-9._-]+\.json$/.test(name)) throw new Error(`UNSAFE_FRAGMENT_NAME: ${name}`);
|
||||
values.push(readJson(join(root, name)));
|
||||
}
|
||||
return values;
|
||||
}
|
||||
|
||||
/** A file hashes as its bytes; a directory hashes a canonical regular-file inventory. */
|
||||
export function scannerAssetHash(path: string): string {
|
||||
const supplied = fs.lstatSync(path);
|
||||
if (supplied.isSymbolicLink()) throw new Error('UNSAFE_SCANNER_ASSET');
|
||||
const root = fs.realpathSync(path), initial = fs.lstatSync(root);
|
||||
if (initial.isFile()) {
|
||||
if (initial.nlink !== 1 || initial.size > MAX_TREE_BYTES) throw new Error('UNSAFE_SCANNER_ASSET');
|
||||
return hashRegularFile(root, initial);
|
||||
}
|
||||
if (!initial.isDirectory()) throw new Error('UNSAFE_SCANNER_ASSET');
|
||||
const entries: Array<[string, number, string]> = [], pending = [root]; let bytes = 0, objects = 0;
|
||||
while (pending.length) {
|
||||
const directory = pending.pop()!;
|
||||
for (const item of fs.readdirSync(directory).sort()) {
|
||||
const full = join(directory, item), stat = fs.lstatSync(full), rel = relative(root, full).split(sep).join('/');
|
||||
if (!rel || rel.startsWith('../') || stat.isSymbolicLink() || ++objects > MAX_TREE_ENTRIES) throw new Error('UNSAFE_SCANNER_ASSET');
|
||||
if (stat.isDirectory()) { pending.push(full); continue; }
|
||||
if (!stat.isFile() || stat.nlink !== 1) throw new Error('UNSAFE_SCANNER_ASSET');
|
||||
bytes += stat.size;
|
||||
if (bytes > MAX_TREE_BYTES) throw new Error('SCANNER_ASSET_LIMIT');
|
||||
entries.push([rel, stat.size, hashRegularFile(full, stat)]);
|
||||
}
|
||||
}
|
||||
if (!entries.length) throw new Error('EMPTY_SCANNER_ASSET');
|
||||
entries.sort(([left], [right]) => left.localeCompare(right));
|
||||
return sha256(canonical(entries));
|
||||
}
|
||||
|
||||
function option(args: string[], name: string): string | undefined {
|
||||
const at = args.indexOf(name); if (at < 0) return undefined;
|
||||
const value = args[at + 1]; if (!value || value.startsWith('--')) throw new Error(`MISSING_${name.slice(2).toUpperCase().replaceAll('-', '_')}`);
|
||||
args.splice(at, 2); return value;
|
||||
}
|
||||
|
||||
if (import.meta.main) {
|
||||
try {
|
||||
const args = process.argv.slice(2), command = args.shift();
|
||||
if (command === 'validate') {
|
||||
const path = args.shift(); if (!path || args.length) throw new Error('Usage: validate CATALOG.json');
|
||||
const value = readJson(resolve(path)); validateScannerCatalog(value); process.stdout.write('VALID\n');
|
||||
} else if (command === 'validate-transition') {
|
||||
const current = args.shift(), proposed = args.shift(); if (!current || !proposed || args.length) throw new Error('Usage: validate-transition CURRENT.json PROPOSED.json');
|
||||
validateScannerCatalogTransition(readJson(resolve(current)) as ScannerCatalog, readJson(resolve(proposed)) as ScannerCatalog); process.stdout.write('VALID TRANSITION\n');
|
||||
} else if (command === 'assemble') {
|
||||
const directory = args.shift(), currentPath = args.shift(), output = args.shift(), revision = option(args, '--revision'), sourceCommit = option(args, '--source-commit'), workflow = option(args, '--workflow'), imagePrefix = option(args, '--image-prefix');
|
||||
if (!directory || !currentPath || !output || !revision || !sourceCommit || !workflow || !imagePrefix || args.length) throw new Error('Usage: assemble FRAGMENTS CURRENT OUTPUT --revision ID --source-commit SHA --workflow URL --image-prefix PREFIX');
|
||||
const proposal = scannerCatalogProposal(readJson(resolve(currentPath)) as ScannerCatalog, fragments(resolve(directory)), revision, { sourceCommit, workflow, imagePrefix });
|
||||
fs.writeFileSync(resolve(output), JSON.stringify(proposal, null, 2) + '\n', { flag: 'wx', mode: 0o600 });
|
||||
process.stdout.write(`${proposal.scanners.length} QUALIFIED PROFILES\n`);
|
||||
} else if (command === 'hash-asset') {
|
||||
const path = args.shift(); if (!path || args.length) throw new Error('Usage: hash-asset PATH'); process.stdout.write(scannerAssetHash(resolve(path)) + '\n');
|
||||
} else if (command === 'version-hash') {
|
||||
const stdout = args.shift(), stderr = args.shift(); if (!stdout || !stderr || args.length) throw new Error('Usage: version-hash STDOUT STDERR');
|
||||
const read = (path: string) => { const stat = fs.lstatSync(path); if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1 || stat.size > 8192) throw new Error('UNSAFE_VERSION_OUTPUT'); return fs.readFileSync(path, 'utf8'); };
|
||||
process.stdout.write(scannerVersionHash(read(resolve(stdout)), read(resolve(stderr))) + '\n');
|
||||
} else throw new Error('Usage: cso-scanner-catalog <validate|validate-transition|assemble|hash-asset|version-hash> ...');
|
||||
} catch (error) {
|
||||
process.stderr.write((error instanceof Error ? error.message : 'SCANNER_CATALOG_ERROR') + '\n'); process.exitCode = 1;
|
||||
}
|
||||
}
|
||||
@@ -1,134 +0,0 @@
|
||||
#!/usr/bin/env -S bun --no-env-file --config=/dev/null
|
||||
/** Validate reviewed scanner inputs before any image is built or published. */
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { resolve } from 'node:path';
|
||||
import { SCANNER_IDS, ScannerId, scannerPlans } from '../lib/cso/scanners';
|
||||
|
||||
const PLATFORMS = ['linux/amd64', 'linux/arm64'] as const;
|
||||
const IMAGE = /^(?:[a-z0-9.-]+(?::[0-9]+)?\/)?[a-z0-9][a-z0-9._/-]*@sha256:[a-f0-9]{64}$/;
|
||||
const DIGEST = /^sha256:[a-f0-9]{64}$/;
|
||||
const HASH = /^[a-f0-9]{64}$/;
|
||||
const VERSION = /^[0-9][A-Za-z0-9.+_-]{0,100}$/;
|
||||
const EXECUTABLE = /^\/(?:[A-Za-z0-9._+-]+\/)*[A-Za-z0-9._+-]+$/;
|
||||
const REPOSITORY = /^https:\/\/github\.com\/[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/;
|
||||
const ID = /^[A-Za-z0-9][A-Za-z0-9._+/-]{0,100}$/;
|
||||
const SIGNER_WORKFLOW = /^(?:github\.com\/)?[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+\/\.github\/workflows\/[A-Za-z0-9_.\/-]+\.ya?ml$/;
|
||||
|
||||
type Platform = typeof PLATFORMS[number];
|
||||
type AssetDeclaration = {
|
||||
semgrepRules?: { path: string; sha256: string };
|
||||
advisoryDatabase?: { path: string; contentSha256: string; updatedAt: string; ecosystems: string[] };
|
||||
};
|
||||
export type ReviewedAttestedImage = {
|
||||
image: string;
|
||||
repository: string;
|
||||
sourceCommit: string;
|
||||
release: string;
|
||||
signerWorkflow: string;
|
||||
signerDigest: string;
|
||||
provenanceStatementDigest: string;
|
||||
sbomStatementDigest: string;
|
||||
};
|
||||
export interface ScannerBuildRow {
|
||||
scanner: ScannerId;
|
||||
platform: Platform;
|
||||
arch: 'amd64' | 'arm64';
|
||||
runner: 'ubuntu-24.04' | 'ubuntu-24.04-arm';
|
||||
baseImage: string;
|
||||
scannerExecutable: string;
|
||||
version: string;
|
||||
capabilities: string[];
|
||||
assets: AssetDeclaration | null;
|
||||
applicationExecutable: string;
|
||||
sbomGenerator: ReviewedAttestedImage;
|
||||
baseAttestation: ReviewedAttestedImage;
|
||||
}
|
||||
|
||||
function object(value: unknown, code: string): Record<string, unknown> {
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error(code);
|
||||
return value as Record<string, unknown>;
|
||||
}
|
||||
function exact(value: Record<string, unknown>, allowed: string[], code: string): void {
|
||||
if (Object.keys(value).some(key => !allowed.includes(key))) throw new Error(code);
|
||||
}
|
||||
function safePath(value: unknown, prefix: string, code: string): string {
|
||||
if (typeof value !== 'string' || !EXECUTABLE.test(value) || !value.startsWith(prefix) || value.split('/').includes('..')) throw new Error(code);
|
||||
return value;
|
||||
}
|
||||
function digest(value: unknown, code: string): string {
|
||||
if (typeof value !== 'string' || !DIGEST.test(value)) throw new Error(code);
|
||||
return value;
|
||||
}
|
||||
function attestedImage(value:unknown,code:string):ReviewedAttestedImage{
|
||||
const raw=object(value,code);exact(raw,['image','repository','sourceCommit','release','signerWorkflow','signerDigest','provenanceStatementDigest','sbomStatementDigest'],code);
|
||||
if(typeof raw.image!=='string'||!IMAGE.test(raw.image)||typeof raw.repository!=='string'||!REPOSITORY.test(raw.repository)||
|
||||
typeof raw.sourceCommit!=='string'||!/^[a-f0-9]{40}$/.test(raw.sourceCommit)||typeof raw.release!=='string'||!ID.test(raw.release)||
|
||||
typeof raw.signerWorkflow!=='string'||!SIGNER_WORKFLOW.test(raw.signerWorkflow)||typeof raw.signerDigest!=='string'||!/^[a-f0-9]{40}$/.test(raw.signerDigest))throw new Error(code);
|
||||
return{image:raw.image,repository:raw.repository,sourceCommit:raw.sourceCommit,release:raw.release,signerWorkflow:raw.signerWorkflow,signerDigest:raw.signerDigest,
|
||||
provenanceStatementDigest:digest(raw.provenanceStatementDigest,code),sbomStatementDigest:digest(raw.sbomStatementDigest,code)};
|
||||
}
|
||||
function assets(value: unknown, scanner: ScannerId): AssetDeclaration | null {
|
||||
if (value === undefined || value === null) {
|
||||
if (['semgrep', 'osv', 'trivy'].includes(scanner)) throw new Error(`MISSING_OFFLINE_ASSET: ${scanner}`);
|
||||
return null;
|
||||
}
|
||||
const raw = object(value, 'INVALID_SCANNER_ASSET'); exact(raw, ['semgrepRules', 'advisoryDatabase'], 'INVALID_SCANNER_ASSET');
|
||||
if (scanner === 'semgrep') {
|
||||
const rules = object(raw.semgrepRules, 'MISSING_SEMGREP_RULES'); exact(rules, ['path', 'sha256'], 'INVALID_SEMGREP_RULES');
|
||||
if (raw.advisoryDatabase !== undefined) throw new Error('INVALID_SEMGREP_RULES');
|
||||
const path = safePath(rules.path, '/policy/catalog/', 'INVALID_SEMGREP_RULES');
|
||||
if (typeof rules.sha256 !== 'string' || !HASH.test(rules.sha256)) throw new Error('INVALID_SEMGREP_RULES');
|
||||
return { semgrepRules: { path, sha256: rules.sha256 } };
|
||||
}
|
||||
if (scanner === 'osv' || scanner === 'trivy') {
|
||||
const db = object(raw.advisoryDatabase, 'MISSING_ADVISORY_DATABASE'); exact(db, ['path', 'contentSha256', 'updatedAt', 'ecosystems'], 'INVALID_ADVISORY_DATABASE');
|
||||
if (raw.semgrepRules !== undefined) throw new Error('INVALID_ADVISORY_DATABASE');
|
||||
const path = safePath(db.path, '/opt/cso/scanner-data/', 'INVALID_ADVISORY_DATABASE');
|
||||
if (typeof db.contentSha256 !== 'string' || !HASH.test(db.contentSha256) || typeof db.updatedAt !== 'string' || !Number.isFinite(Date.parse(db.updatedAt)) || !Array.isArray(db.ecosystems) || !db.ecosystems.length || new Set(db.ecosystems).size !== db.ecosystems.length || db.ecosystems.some(item => typeof item !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9.+_-]{0,63}$/.test(item))) throw new Error('INVALID_ADVISORY_DATABASE');
|
||||
return { advisoryDatabase: { path, contentSha256: db.contentSha256, updatedAt: new Date(db.updatedAt).toISOString(), ecosystems: (db.ecosystems as string[]).slice().sort() } };
|
||||
}
|
||||
throw new Error(`UNEXPECTED_OFFLINE_ASSET: ${scanner}`);
|
||||
}
|
||||
|
||||
/** Every scanner must have both native platforms; partial matrices cannot publish. */
|
||||
export function scannerBuildMatrix(input: unknown): { include: ScannerBuildRow[] } {
|
||||
const data = object(input, 'INVALID_SCANNER_BUILD_INPUTS');
|
||||
exact(data, ['schemaVersion', 'helperAbi', 'state', 'sbomGenerator', 'profiles', 'instructions'], 'INVALID_SCANNER_BUILD_INPUTS');
|
||||
if (data.schemaVersion !== 1 || data.helperAbi !== 3) throw new Error('INCOMPATIBLE_SCANNER_BUILD_INPUTS');
|
||||
if (data.state !== 'reviewed') throw new Error('MISSING_REVIEWED_SCANNER_INPUTS: review immutable images, assets, versions, SBOMs, and provenance before staging.');
|
||||
const sbomGenerator=attestedImage(data.sbomGenerator,'UNVERIFIED_SBOM_GENERATOR');
|
||||
if (!Array.isArray(data.profiles) || data.profiles.length !== SCANNER_IDS.length) throw new Error('INCOMPLETE_SCANNER_MATRIX');
|
||||
const rows: ScannerBuildRow[] = [], seen = new Set<ScannerId>();
|
||||
for (const value of data.profiles) {
|
||||
const profile = object(value, 'INVALID_SCANNER_PROFILE');
|
||||
exact(profile, ['scanner', 'version', 'baseImages', 'executable', 'assets', 'applicationExecutable'], 'INVALID_SCANNER_PROFILE');
|
||||
const scanner = profile.scanner as ScannerId;
|
||||
if (!SCANNER_IDS.includes(scanner) || seen.has(scanner)) throw new Error('INVALID_OR_DUPLICATE_SCANNER');
|
||||
seen.add(scanner);
|
||||
if (typeof profile.version !== 'string' || !VERSION.test(profile.version)) throw new Error(`UNPINNED_SCANNER_VERSION: ${scanner}`);
|
||||
if (typeof profile.executable !== 'string' || !EXECUTABLE.test(profile.executable)) throw new Error(`INVALID_SCANNER_EXECUTABLE: ${scanner}`);
|
||||
const baseImages = object(profile.baseImages, `MISSING_SCANNER_IMAGES: ${scanner}`);
|
||||
exact(baseImages, [...PLATFORMS], `INVALID_SCANNER_IMAGES: ${scanner}`);
|
||||
const declaredAssets = assets(profile.assets, scanner);
|
||||
const applicationExecutable = scanner === 'schemathesis' ? safePath(profile.applicationExecutable, '/', 'MISSING_SCHEMATHESIS_FIXTURE_RUNTIME') : '';
|
||||
if (scanner !== 'schemathesis' && profile.applicationExecutable !== undefined) throw new Error(`UNEXPECTED_APPLICATION_EXECUTABLE: ${scanner}`);
|
||||
const capabilities = scannerPlans({ snapshotRoot: '/source', offline: true, selected: [scanner] })[0].requiredFeatures.slice().sort();
|
||||
for (const platform of PLATFORMS) {
|
||||
const baseAttestation=attestedImage(baseImages[platform],`INVALID_UPSTREAM_EVIDENCE: ${scanner} ${platform}`),baseImage=baseAttestation.image;
|
||||
const arch = platform === 'linux/amd64' ? 'amd64' : 'arm64';
|
||||
rows.push({ scanner, platform, arch, runner: arch === 'amd64' ? 'ubuntu-24.04' : 'ubuntu-24.04-arm', baseImage, scannerExecutable: profile.executable, version: profile.version, capabilities, assets: declaredAssets, applicationExecutable, sbomGenerator, baseAttestation });
|
||||
}
|
||||
}
|
||||
return { include: rows };
|
||||
}
|
||||
|
||||
if (import.meta.main) {
|
||||
try {
|
||||
if (process.argv.length !== 2) throw new Error('No arguments accepted; scanner inputs come from the reviewed repository file.');
|
||||
const file = resolve(import.meta.dir, '../lib/cso/scanner-images/build-inputs.json');
|
||||
process.stdout.write(JSON.stringify(scannerBuildMatrix(JSON.parse(readFileSync(file, 'utf8')))) + '\n');
|
||||
} catch (error) {
|
||||
process.stderr.write((error instanceof Error ? error.message : 'INVALID_SCANNER_BUILD_INPUTS') + '\n');
|
||||
process.exitCode = 1;
|
||||
}
|
||||
}
|
||||
@@ -1,124 +0,0 @@
|
||||
#!/usr/bin/env -S bun --no-env-file --config=/dev/null
|
||||
/** Bind a qualification dispatch to the one successful protected-main staging run that signed its images. */
|
||||
import * as fs from 'node:fs';
|
||||
import * as path from 'node:path';
|
||||
import { canonical } from '../lib/cso/contracts';
|
||||
import { committedImageBuildMatrix } from './cso-image-matrix';
|
||||
|
||||
export const STAGING_WORKFLOW_PATH = '.github/workflows/cso-runtime-images.yml';
|
||||
export const NATIVE_JOB = 'qualify-native';
|
||||
const SLSA_PROVENANCE = 'https://slsa.dev/provenance/v1';
|
||||
const REPOSITORY = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/;
|
||||
const INVOCATION = /^https:\/\/github\.com\/([A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+)\/actions\/runs\/([1-9][0-9]*)\/attempts\/[1-9][0-9]*$/;
|
||||
const MAX_FILE_BYTES = 4 * 1024 * 1024;
|
||||
|
||||
export interface StagingRunEvidence {
|
||||
repository: string;
|
||||
runId: string;
|
||||
sourceCommit: string;
|
||||
runtimeIds: string[];
|
||||
run: unknown;
|
||||
jobPages: unknown;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the staging run from verified SLSA provenance. The predicate's
|
||||
* invocation and the Fulcio certificate's run URI must agree, and every
|
||||
* verified statement for every image must name the same run.
|
||||
*/
|
||||
export function stagingRunId(repository: string, verifications: unknown[]): string {
|
||||
if (!REPOSITORY.test(repository) || verifications.length === 0) throw new Error('INVALID_STAGING_PROVENANCE');
|
||||
const runs = new Set<string>();
|
||||
for (const verification of verifications) {
|
||||
if (!Array.isArray(verification) || verification.length === 0) throw new Error('INVALID_STAGING_PROVENANCE');
|
||||
for (const item of verification) {
|
||||
const result = (item as any)?.verificationResult;
|
||||
if (result?.statement?.predicateType !== SLSA_PROVENANCE) throw new Error('INVALID_STAGING_PROVENANCE');
|
||||
const invocation = result.statement.predicate?.runDetails?.metadata?.invocationId;
|
||||
const match = typeof invocation === 'string' ? INVOCATION.exec(invocation) : null;
|
||||
if (!match || match[1] !== repository || result.signature?.certificate?.runInvocationURI !== invocation) {
|
||||
throw new Error('STAGING_INVOCATION_MISMATCH');
|
||||
}
|
||||
runs.add(match[2]);
|
||||
}
|
||||
}
|
||||
if (runs.size !== 1) throw new Error('STAGING_RUN_NOT_UNIQUE');
|
||||
return [...runs][0];
|
||||
}
|
||||
|
||||
/** Every statement in one qualification dispatch names the same staged source commit. */
|
||||
export function dispatchSourceCommit(event: unknown): string {
|
||||
const statements = (event as any)?.client_payload?.statements;
|
||||
if (!Array.isArray(statements) || statements.length === 0) throw new Error('INVALID_QUALIFICATION_DISPATCH');
|
||||
const commits = new Set(statements.map((statement: any) => statement?.sourceCommit));
|
||||
const [commit] = [...commits];
|
||||
if (commits.size !== 1 || typeof commit !== 'string' || !/^[a-f0-9]{40}$/.test(commit)) throw new Error('STAGING_SOURCE_COMMIT_MISMATCH');
|
||||
return commit;
|
||||
}
|
||||
|
||||
/** The resolved run must be the protected-main staging dispatch at the statements' commit, with every native gate passed. */
|
||||
export function verifyStagingRun(evidence: StagingRunEvidence): void {
|
||||
const { repository, runId, sourceCommit, runtimeIds } = evidence;
|
||||
const run = evidence.run as any;
|
||||
if (!run || typeof run !== 'object' || String(run.id) !== runId) throw new Error('STAGING_RUN_ID_MISMATCH');
|
||||
if (run.path !== STAGING_WORKFLOW_PATH) throw new Error('STAGING_WORKFLOW_MISMATCH');
|
||||
if (run.repository?.full_name !== repository || run.head_repository?.full_name !== repository) throw new Error('STAGING_REPOSITORY_MISMATCH');
|
||||
if (run.event !== 'workflow_dispatch' || run.head_branch !== 'main') throw new Error('STAGING_RUN_NOT_PROTECTED_MAIN_DISPATCH');
|
||||
if (run.status !== 'completed' || run.conclusion !== 'success') throw new Error('STAGING_RUN_NOT_SUCCESSFUL');
|
||||
if (run.head_sha !== sourceCommit) throw new Error('STAGING_SOURCE_COMMIT_MISMATCH');
|
||||
|
||||
const pages = evidence.jobPages;
|
||||
if (!Array.isArray(pages) || pages.length === 0) throw new Error('INVALID_STAGING_JOBS');
|
||||
const totals = new Set(pages.map((page: any) => page?.total_count));
|
||||
if (pages.some((page: any) => !Array.isArray(page?.jobs)) || totals.size !== 1) throw new Error('INVALID_STAGING_JOBS');
|
||||
const jobs = pages.flatMap((page: any) => page.jobs);
|
||||
if (jobs.length !== [...totals][0]) throw new Error('INCOMPLETE_STAGING_JOBS');
|
||||
|
||||
const native = jobs.filter((job: any) => typeof job?.name === 'string' && job.name.startsWith(NATIVE_JOB));
|
||||
const expected = runtimeIds.map(id => `${NATIVE_JOB} ${id}`).sort();
|
||||
if (runtimeIds.length === 0 || canonical(native.map((job: any) => job.name).sort()) !== canonical(expected)) {
|
||||
throw new Error('STAGING_NATIVE_JOBS_MISMATCH');
|
||||
}
|
||||
if (native.some((job: any) => String(job.run_id) !== runId || job.status !== 'completed' || job.conclusion !== 'success')) {
|
||||
throw new Error('STAGING_NATIVE_GATE_NOT_PASSED');
|
||||
}
|
||||
}
|
||||
|
||||
function readJson(file: string): unknown {
|
||||
const absolute = path.resolve(file);
|
||||
const stat = fs.lstatSync(absolute);
|
||||
if (!stat.isFile() || stat.isSymbolicLink() || stat.size <= 0 || stat.size > MAX_FILE_BYTES) throw new Error('UNSAFE_STAGING_EVIDENCE_FILE');
|
||||
try { return JSON.parse(fs.readFileSync(absolute, 'utf8')); } catch { throw new Error('INVALID_STAGING_EVIDENCE_FILE'); }
|
||||
}
|
||||
|
||||
function option(args: string[], name: string): string {
|
||||
const index = args.indexOf(name);
|
||||
const value = index >= 0 ? args[index + 1] : undefined;
|
||||
if (!value || value.startsWith('--')) throw new Error(`Missing ${name}`);
|
||||
return value;
|
||||
}
|
||||
|
||||
if (import.meta.main) {
|
||||
try {
|
||||
const [command, ...args] = process.argv.slice(2);
|
||||
if (command === 'run-id' && args[0] === '--repository' && args.length >= 3) {
|
||||
process.stdout.write(`${stagingRunId(args[1], args.slice(2).map(readJson))}\n`);
|
||||
} else if (command === 'verify' && args.length === 10) {
|
||||
const event = readJson(option(args, '--event'));
|
||||
verifyStagingRun({
|
||||
repository: option(args, '--repository'),
|
||||
runId: option(args, '--run-id'),
|
||||
sourceCommit: dispatchSourceCommit(event),
|
||||
runtimeIds: committedImageBuildMatrix().include.map(row => row.runtimeId),
|
||||
run: readJson(option(args, '--run')),
|
||||
jobPages: readJson(option(args, '--jobs')),
|
||||
});
|
||||
process.stdout.write('STAGING RUN VERIFIED\n');
|
||||
} else {
|
||||
throw new Error('Usage: cso-staging-run.ts run-id --repository OWNER/REPO PROVENANCE.json... | verify --repository OWNER/REPO --run-id ID --event EVENT.json --run RUN.json --jobs JOB-PAGES.json');
|
||||
}
|
||||
} catch (error) {
|
||||
process.stderr.write((error instanceof Error ? error.message : 'STAGING_RUN_VERIFICATION_FAILED') + '\n');
|
||||
process.exitCode = 1;
|
||||
}
|
||||
}
|
||||
@@ -1,117 +0,0 @@
|
||||
#!/usr/bin/env -S bun --no-env-file --config=/dev/null
|
||||
/** Native trusted-CI verification for reviewed OCI build inputs. */
|
||||
import { spawnSync } from '../lib/spawn-sync';
|
||||
import { committedImageBuildMatrix, type ImageBuildRow } from './cso-image-matrix';
|
||||
|
||||
const MAX_OUTPUT = 1024 * 1024;
|
||||
const TIMEOUT = 120_000;
|
||||
|
||||
interface VersionProbe {
|
||||
image: string;
|
||||
executable: string;
|
||||
args: string[];
|
||||
version: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
export function assertVersionOutput(name: string, expected: string, output: string): void {
|
||||
if (Buffer.byteLength(output) > 64 * 1024) throw new Error(`VERSION_OUTPUT_TOO_LARGE: ${name}`);
|
||||
const first = output.match(/(?<!\d)(\d+\.\d+(?:\.\d+)?)(?![\d.])/);
|
||||
if (!first || first[1] !== expected) throw new Error(`RUNTIME_VERSION_MISMATCH: ${name} expected ${expected}`);
|
||||
}
|
||||
|
||||
export function probesForBuildRow(row: ImageBuildRow): VersionProbe[] {
|
||||
const base = row.baseImage;
|
||||
switch (row.stack) {
|
||||
case 'node':
|
||||
return [
|
||||
{ image: base, executable: '/usr/local/bin/node', args: ['--version'], version: row.versions.node, name: 'node' },
|
||||
{ image: base, executable: '/usr/local/bin/npm', args: ['--version'], version: row.versions.npm, name: 'npm' },
|
||||
];
|
||||
case 'bun':
|
||||
return [{ image: base, executable: '/usr/local/bin/bun', args: ['--version'], version: row.versions.bun, name: 'bun' }];
|
||||
case 'python':
|
||||
return [
|
||||
{ image: base, executable: '/usr/local/bin/python', args: ['--version'], version: row.versions.python, name: 'python' },
|
||||
{ image: row.uvImage, executable: '/uv', args: ['--version'], version: row.versions.uv, name: 'uv' },
|
||||
];
|
||||
case 'rails':
|
||||
return [
|
||||
{ image: base, executable: '/usr/local/bin/ruby', args: ['--version'], version: row.versions.ruby, name: 'ruby' },
|
||||
{ image: base, executable: '/usr/local/bin/bundle', args: ['--version'], version: row.versions.bundler, name: 'bundler' },
|
||||
];
|
||||
case 'postgresql':
|
||||
return [{ image: base, executable: '/usr/lib/postgresql/17/bin/postgres', args: ['--version'], version: row.versions.postgresql, name: 'postgresql' }];
|
||||
}
|
||||
}
|
||||
|
||||
function command(docker: string, args: string[], timeout = TIMEOUT): string {
|
||||
const env: Record<string, string> = { PATH: process.env.PATH ?? '/usr/bin:/bin' };
|
||||
if (process.env.HOME) env.HOME = process.env.HOME;
|
||||
if (process.env.DOCKER_CONFIG) env.DOCKER_CONFIG = process.env.DOCKER_CONFIG;
|
||||
const result = spawnSync(docker, args, { encoding: 'utf8', timeout, maxBuffer: MAX_OUTPUT, env });
|
||||
if (result.error || result.status !== 0) {
|
||||
const message = [result.error?.message, result.stderr, result.stdout].filter(Boolean).join('\n').slice(0, 4096);
|
||||
throw new Error(`DOCKER_INPUT_VERIFICATION_FAILED: ${args[0]} ${message}`);
|
||||
}
|
||||
if (Buffer.byteLength(result.stdout) + Buffer.byteLength(result.stderr) > MAX_OUTPUT) throw new Error('DOCKER_INPUT_VERIFICATION_OUTPUT_TOO_LARGE');
|
||||
return result.stdout;
|
||||
}
|
||||
|
||||
function inspectManifest(docker: string, image: string): any {
|
||||
const raw = command(docker, ['buildx', 'imagetools', 'inspect', image, '--format', '{{json .Manifest}}']);
|
||||
try { return JSON.parse(raw); } catch { throw new Error(`INVALID_OCI_MANIFEST: ${image}`); }
|
||||
}
|
||||
|
||||
function inspectImage(docker: string, image: string): any {
|
||||
const raw = command(docker, ['buildx', 'imagetools', 'inspect', image, '--format', '{{json .Image}}']);
|
||||
try { return JSON.parse(raw); } catch { throw new Error(`INVALID_OCI_IMAGE_CONFIG: ${image}`); }
|
||||
}
|
||||
|
||||
function digestOf(image: string): string {
|
||||
return image.slice(image.lastIndexOf('@') + 1);
|
||||
}
|
||||
|
||||
function assertSourceIndex(docker: string, source: string, indexImage: string, platformImage: string, row: ImageBuildRow): void {
|
||||
const sourceManifest = inspectManifest(docker, source);
|
||||
if (sourceManifest?.digest !== digestOf(indexImage)) throw new Error(`SOURCE_TAG_MOVED: ${source}`);
|
||||
const indexManifest = inspectManifest(docker, indexImage);
|
||||
const platformDigest = digestOf(platformImage);
|
||||
const match = indexManifest?.manifests?.find((manifest: any) =>
|
||||
manifest?.digest === platformDigest && manifest?.platform?.os === 'linux' && manifest?.platform?.architecture === row.arch);
|
||||
if (!match) throw new Error(`PLATFORM_MANIFEST_NOT_IN_INDEX: ${platformImage}`);
|
||||
const config = inspectImage(docker, platformImage);
|
||||
if (config?.os !== 'linux' || config?.architecture !== row.arch) throw new Error(`PLATFORM_CONFIG_MISMATCH: ${platformImage}`);
|
||||
}
|
||||
|
||||
export function verifyRuntimeBuildRow(row: ImageBuildRow, docker = Bun.which('docker')): void {
|
||||
if (!docker || !docker.startsWith('/')) throw new Error('TRUSTED_DOCKER_NOT_FOUND');
|
||||
command(docker, ['--host', 'unix:///var/run/docker.sock', 'info'], 30_000);
|
||||
assertSourceIndex(docker, row.baseSource, row.baseIndexImage, row.baseImage, row);
|
||||
assertSourceIndex(docker, row.sbomGeneratorSource, row.sbomGeneratorIndexImage, row.sbomGeneratorImage, row);
|
||||
if (row.stack === 'python') assertSourceIndex(docker, row.uvSource, row.uvIndexImage, row.uvImage, row);
|
||||
const images = [...new Set(probesForBuildRow(row).map(probe => probe.image))];
|
||||
for (const image of images) command(docker, ['--host', 'unix:///var/run/docker.sock', 'pull', '--platform', row.platform, image], 5 * 60_000);
|
||||
for (const probe of probesForBuildRow(row)) {
|
||||
const output = command(docker, [
|
||||
'--host', 'unix:///var/run/docker.sock', 'run', '--rm', '--pull', 'never', '--network', 'none',
|
||||
'--entrypoint', probe.executable, probe.image, ...probe.args,
|
||||
], 30_000);
|
||||
assertVersionOutput(probe.name, probe.version, output);
|
||||
}
|
||||
}
|
||||
|
||||
if (import.meta.main) {
|
||||
try {
|
||||
if (process.argv.length !== 2) throw new Error('No arguments accepted; the selected row comes from committed inputs and trusted CI environment.');
|
||||
const stack = process.env.CSO_STACK;
|
||||
const platform = process.env.CSO_PLATFORM;
|
||||
const rows = committedImageBuildMatrix().include.filter(row => row.stack === stack && row.platform === platform);
|
||||
if (rows.length !== 1) throw new Error('INVALID_RUNTIME_BUILD_ROW');
|
||||
verifyRuntimeBuildRow(rows[0]);
|
||||
process.stdout.write(`verified ${rows[0].runtimeId} base manifests and versions\n`);
|
||||
} catch (error) {
|
||||
process.stderr.write((error instanceof Error ? error.message : 'RUNTIME_BASE_VERIFICATION_FAILED') + '\n');
|
||||
process.exitCode = 1;
|
||||
}
|
||||
}
|
||||
@@ -337,33 +337,7 @@
|
||||
"test/cost-known.test.ts": 349,
|
||||
"test/coverage-audit.test.ts": 8774,
|
||||
"test/crew-move-layout.test.ts": 60,
|
||||
"test/cso-bounded-file.test.ts": 57,
|
||||
"test/cso-docker-policy.test.ts": 219,
|
||||
"test/cso-docker-socket-realpath.test.ts": 68,
|
||||
"test/cso-git-global-config.test.ts": 125,
|
||||
"test/cso-git-hardening.test.ts": 75,
|
||||
"test/cso-history.test.ts": 46,
|
||||
"test/cso-image-provisioning.test.ts": 280,
|
||||
"test/cso-lease-identity.test.ts": 396,
|
||||
"test/cso-native-evidence.test.ts": 99,
|
||||
"test/cso-node-lifecycle-integration.test.ts": 110,
|
||||
"test/cso-ntfs-fixture.test.ts": 592,
|
||||
"test/cso-postgresql-policy.test.ts": 66,
|
||||
"test/cso-preparation-java.test.ts": 62,
|
||||
"test/cso-preparation.test.ts": 179,
|
||||
"test/cso-preserved.test.ts": 55,
|
||||
"test/cso-public-ghcr.test.ts": 58,
|
||||
"test/cso-requalification.test.ts": 160,
|
||||
"test/cso-runtime-promotion.test.ts": 344,
|
||||
"test/cso-scanner-docker-integration.test.ts": 95,
|
||||
"test/cso-scanners.test.ts": 240,
|
||||
"test/cso-snapshot-disappearance-race.test.ts": 65,
|
||||
"test/cso-spec-taxonomy-alignment.test.ts": 45,
|
||||
"test/cso-staging-run.test.ts": 191,
|
||||
"test/cso-unreadable-secret-file.test.ts": 1252,
|
||||
"test/cso-verifier.test.ts": 94,
|
||||
"test/cso-windows-build-contract.test.ts": 62,
|
||||
"test/cso-windows-docker.test.ts": 65,
|
||||
"test/declared-annotation.test.ts": 58,
|
||||
"test/defensive-review-framing.test.ts": 50,
|
||||
"test/dependency-security.test.ts": 154,
|
||||
@@ -809,7 +783,6 @@
|
||||
"test/setup-codex-design-pdf-runtime.test.ts": 56,
|
||||
"test/setup-codex-model.test.ts": 54,
|
||||
"test/setup-codex-scope-review-boundaries.test.ts": 124,
|
||||
"test/setup-cso-windows-probe.test.ts": 49,
|
||||
"test/setup-cursor-legacy-skills.test.ts": 119,
|
||||
"test/setup-deploy-key-presence.test.ts": 96,
|
||||
"test/setup-deploy-not-deployed.test.ts": 45,
|
||||
|
||||
@@ -397,8 +397,6 @@
|
||||
"test/brain-sync.test.ts": 174893,
|
||||
"test/branch-slug-hygiene.test.ts": 623,
|
||||
"test/build-check-skill-eval.test.ts": 5280,
|
||||
"test/build-cso-nonfatal.test.ts": 51,
|
||||
"test/build-cso-result-record.test.ts": 392,
|
||||
"test/build-gbrain-env.test.ts": 58,
|
||||
"test/build-script-shell-compat.test.ts": 13,
|
||||
"test/builder-profile.test.ts": 3445,
|
||||
@@ -524,65 +522,7 @@
|
||||
"test/credential-rejection.test.ts": 283,
|
||||
"test/crew-move-layout.test.ts": 15,
|
||||
"test/crew-skills-on-capy.test.ts": 1042,
|
||||
"test/cso-audit-paths.test.ts": 21523,
|
||||
"test/cso-bounded-file.test.ts": 22,
|
||||
"test/cso-cache.test.ts": 183,
|
||||
"test/cso-cli-lifecycle.test.ts": 6272,
|
||||
"test/cso-cli-recheck.test.ts": 20977,
|
||||
"test/cso-cli.test.ts": 41566,
|
||||
"test/cso-contracts.test.ts": 298,
|
||||
"test/cso-distribution.test.ts": 2597,
|
||||
"test/cso-docker-argv0.test.ts": 947,
|
||||
"test/cso-docker-integration.test.ts": 24,
|
||||
"test/cso-docker-mounts.test.ts": 46,
|
||||
"test/cso-docker-policy.test.ts": 27,
|
||||
"test/cso-docker-socket-realpath.test.ts": 35,
|
||||
"test/cso-eval.test.ts": 10505,
|
||||
"test/cso-file-ceiling.test.ts": 36092,
|
||||
"test/cso-git-global-config.test.ts": 32,
|
||||
"test/cso-git-hardening.test.ts": 447,
|
||||
"test/cso-history.test.ts": 14,
|
||||
"test/cso-image-provisioning.test.ts": 300,
|
||||
"test/cso-json-redaction.test.ts": 285,
|
||||
"test/cso-launcher-generation.test.ts": 1624,
|
||||
"test/cso-lease-identity.test.ts": 541,
|
||||
"test/cso-macos-launcher.test.ts": 20,
|
||||
"test/cso-native-evidence.test.ts": 109,
|
||||
"test/cso-node-lifecycle-integration.test.ts": 48,
|
||||
"test/cso-ntfs-fixture.test.ts": 92,
|
||||
"test/cso-ordinary-repos.test.ts": 6367,
|
||||
"test/cso-postgresql-policy.test.ts": 28,
|
||||
"test/cso-preparation-adversarial.test.ts": 86,
|
||||
"test/cso-preparation-container.test.ts": 84,
|
||||
"test/cso-preparation-executor.test.ts": 864,
|
||||
"test/cso-preparation-java.test.ts": 30,
|
||||
"test/cso-preparation.test.ts": 122,
|
||||
"test/cso-preserved.test.ts": 19,
|
||||
"test/cso-public-ghcr.test.ts": 44,
|
||||
"test/cso-python-runner-shadow.test.ts": 3263,
|
||||
"test/cso-rails-verification.test.ts": 43,
|
||||
"test/cso-registry-socket.test.ts": 3827,
|
||||
"test/cso-requalification.test.ts": 2885,
|
||||
"test/cso-runtime-promotion.test.ts": 2784,
|
||||
"test/cso-scanner-cli.test.ts": 8609,
|
||||
"test/cso-scanner-docker-integration.test.ts": 36,
|
||||
"test/cso-scanner-executor.test.ts": 145,
|
||||
"test/cso-scanner-release.test.ts": 75,
|
||||
"test/cso-scanners.test.ts": 146,
|
||||
"test/cso-snapshot-disappearance-race.test.ts": 146,
|
||||
"test/cso-snapshot-identity.test.ts": 444,
|
||||
"test/cso-snapshot-state.test.ts": 4244,
|
||||
"test/cso-spec-taxonomy-alignment.test.ts": 15,
|
||||
"test/cso-stack-cold-integration.test.ts": 35,
|
||||
"test/cso-staging-run.test.ts": 94,
|
||||
"test/cso-unreadable-secret-file.test.ts": 263,
|
||||
"test/cso-verification-cleanup.test.ts": 1109,
|
||||
"test/cso-verifier.test.ts": 43,
|
||||
"test/cso-watchdog.test.ts": 7691,
|
||||
"test/cso-windows-build-contract.test.ts": 22,
|
||||
"test/cso-windows-docker.test.ts": 21,
|
||||
"test/cso-windows-launcher.test.ts": 21,
|
||||
"test/cso-witness.test.ts": 1069,
|
||||
"test/decision-trail.test.ts": 554,
|
||||
"test/declared-annotation.test.ts": 17,
|
||||
"test/default-base.test.ts": 4360,
|
||||
@@ -1466,8 +1406,6 @@
|
||||
"test/setup-conductor-auq-hook.test.ts": 19030,
|
||||
"test/setup-conductor-worktree.test.ts": 32,
|
||||
"test/setup-crlf-repair.test.ts": 167,
|
||||
"test/setup-cso-degrade.test.ts": 140,
|
||||
"test/setup-cso-windows-probe.test.ts": 46,
|
||||
"test/setup-cursor-legacy-skills.test.ts": 5159,
|
||||
"test/setup-deploy-key-presence.test.ts": 16,
|
||||
"test/setup-deploy-not-deployed.test.ts": 13,
|
||||
|
||||
@@ -1 +1 @@
|
||||
{"blob":"9384e521785e31e99eae4c0f126f67bb2d174260","since":8}
|
||||
{"blob":"10f92d323fc94589f184ad00fd1228f1372b5470","since":8,"nonBehavioral":"Removes the four deleted /cso workflows from the PR-profile path list; no remaining case's selection, trials or verdict changes"}
|
||||
@@ -230,30 +230,6 @@ export const KNOWN_WINDOWS_INCOMPATIBLE: Array<{ file: string; reason: string }>
|
||||
file: 'browse/test/security-audit-r2.test.ts',
|
||||
reason: 'symlink-attack fixtures (evil-link) need Developer Mode CI runners lack; expect(toThrow) fires unhandled on Windows',
|
||||
},
|
||||
// CSO comprehensive execution is qualified only for Linux containers behind
|
||||
// the POSIX watchdog and Unix-domain registry broker. Keep the portable
|
||||
// static/parser contracts in the Windows lane while leaving these exact
|
||||
// containment suites to the Linux and macOS gates.
|
||||
{
|
||||
file: 'test/cso-preparation-adversarial.test.ts',
|
||||
reason: 'exercises POSIX prepared-tree and archive-cache containment for qualified Linux Docker execution, which Windows does not admit',
|
||||
},
|
||||
{
|
||||
file: 'test/cso-preparation-container.test.ts',
|
||||
reason: 'asserts POSIX permission and symlink semantics for inert exports consumed by qualified Linux Docker execution',
|
||||
},
|
||||
{
|
||||
file: 'test/cso-preparation-executor.test.ts',
|
||||
reason: 'executes the Linux Docker acquisition path and its Unix-domain registry broker; comprehensive execution is unavailable on Windows',
|
||||
},
|
||||
{
|
||||
file: 'test/cso-verification-cleanup.test.ts',
|
||||
reason: 'spawns the POSIX detached watchdog used by contained repair verification, which Windows intentionally leaves unavailable',
|
||||
},
|
||||
{
|
||||
file: 'test/cso-witness.test.ts',
|
||||
reason: 'tests the contained repair witness with POSIX private-directory and compiled-helper assumptions; comprehensive execution is unavailable on Windows',
|
||||
},
|
||||
{
|
||||
file: 'test/shard-engine-equivalence.test.ts',
|
||||
reason: 'its classification golden was recorded from the POSIX runners (process-group wall kill); the win32 engine path is pinned by the mocked-platform case in shard-engine.test.ts',
|
||||
@@ -286,10 +262,6 @@ export const KNOWN_WINDOWS_INCOMPATIBLE: Array<{ file: string; reason: string }>
|
||||
file: 'test/setup-codex-scope-runtime-links.test.ts',
|
||||
reason: 'every case runs the real ./setup under describe.skipIf(win32); its bin/ spawns live in test/helpers/install-fixture.ts and test/helpers/setup-codex-scope-cyclic.ts, so the source scan misses them',
|
||||
},
|
||||
{
|
||||
file: 'test/cso-scanner-cli.test.ts',
|
||||
reason: 'drives the prebuilt POSIX CSO launcher with /usr/bin/git and a POSIX-only PATH; native Windows launcher behavior is covered by the dedicated cso-windows-launcher gate',
|
||||
},
|
||||
// C-stamp (ship policy, restamp, tree receipt, evidence bundle, ship receipt):
|
||||
// every case spawns bin/ shebang scripts and a #!/bin/sh `gh` shim through
|
||||
// test/helpers/restamp-fixture.ts, so the source scan misses them.
|
||||
@@ -543,7 +515,6 @@ export const KNOWN_WINDOWS_SAFE: Array<{ file: string; reason: string }> = [
|
||||
// the curated lane even if a future edit trips a content pattern.
|
||||
{ file: 'browse/test/cli-chain-stdin.test.ts', reason: 'piped-stdin browse chain against a stub daemon, and no-flow usage errors before any daemon boots; spawns the CLI through Bun argv' },
|
||||
{ file: 'browse/test/runtime-root-server-bundle.test.ts', reason: 'a runtime root copy without node_modules resolves the checkout bundle via .source-path and refuses on version skew; os.tmpdir layouts only' },
|
||||
{ file: 'test/cso-windows-docker.test.ts', reason: '/cso docker.exe discovery under known-folder roots (real path, no reparse points) and the native-transport-unsupported outcome; pure win32 path logic' },
|
||||
{ file: 'test/copilot-windows-bash.test.ts', reason: 'the Copilot glossary line that runs bash blocks in Git for Windows Bash; reads host config only' },
|
||||
{ file: 'test/ship-hook-windows-paths.test.ts', reason: 'runs bin/ helpers through explicit bash and Bun argv with forward-slash paths; never executes a shebang; the path-spelling simulation is skipIf win32' },
|
||||
{ file: 'test/review-scope-windows-launch.test.ts', reason: '#3541: runs gstack-review-scope through lib/script-invocation.ts, which must reach the bash gstack-review-read through Git Bash (red at main: windows-free-shard 3, run 41228091417); os.tmpdir state only' },
|
||||
@@ -600,12 +571,6 @@ export const KNOWN_WINDOWS_SAFE: Array<{ file: string; reason: string }> = [
|
||||
// and never launches a shebang. Keep the native delimiter cases in CI.
|
||||
reason: 'replays the registered SDK callback with fixture-only bin paths; covers native Windows PATH composition',
|
||||
},
|
||||
{
|
||||
file: 'test/cso-windows-build-contract.test.ts',
|
||||
// bin is a temporary staging directory. The adapter injects spawnSync;
|
||||
// real PowerShell/native execution remains in cso-windows-launcher.
|
||||
reason: 'replays the native build callbacks with an injected subprocess; bin paths are staging fixtures, not shebang launches',
|
||||
},
|
||||
{
|
||||
file: 'test/setup-windows-rerun-refresh.test.ts',
|
||||
// Trips the "spawns bin/ shebang script" pattern via path.join(..., 'bin',
|
||||
|
||||
@@ -270,10 +270,6 @@ export const FREE_ONLY_PR_FILES = [
|
||||
'.github/workflows/arm-setup-smoke.yml',
|
||||
'.github/workflows/ci-image.yml',
|
||||
'.github/workflows/codex-hooks.yml', // Installs the pinned Codex CLI and runs the free test/codex-hooks-real-codex.test.ts; no paid case reads it.
|
||||
'.github/workflows/cso-runtime-images.yml',
|
||||
'.github/workflows/cso-runtime-promote.yml',
|
||||
'.github/workflows/cso-runtime-qualification.yml',
|
||||
'.github/workflows/cso-scanner-images.yml',
|
||||
'.github/workflows/dependency-review.yml',
|
||||
'.github/workflows/free-durations-record.yml',
|
||||
'.github/workflows/free-tests.yml',
|
||||
|
||||
@@ -120,14 +120,6 @@
|
||||
"test/claude-code-runner.test.ts\tTS7006\tParameter 'callback' implicitly has an 'any' type.": 1,
|
||||
"test/claude-code-runner.test.ts\tTS7006\tParameter 'delay' implicitly has an 'any' type.": 1,
|
||||
"test/claude-code-runner.test.ts\tTS7019\tRest parameter 'args' implicitly has an 'any[]' type.": 1,
|
||||
"test/cso-eval.test.ts\tTS2345\tArgument of type '(command: string, args: readonly string[] | undefined, options: any) => string' is not assignable to parameter of type '{ (file: string): NonSharedBuffer; (file: string, options: ExecFileSyncOptionsWithStringEncoding): string; (file: string, options: ExecFileSyncOptionsWithBufferEncoding): NonSharedBuffer; (file: string, options?: ExecFileSyncOptions | undefined): string | NonSharedBuffer; (file: string, args: readonly string[]): Non...'. Target signature provides too few arguments. Expected 3 or more, but got 1.": 1,
|
||||
"test/cso-eval.test.ts\tTS2790\tThe operand of a 'delete' operator must be optional.": 1,
|
||||
"test/cso-eval.test.ts\tTS7005\tVariable 'receipts' implicitly has an 'any[]' type.": 1,
|
||||
"test/cso-eval.test.ts\tTS7034\tVariable 'receipts' implicitly has type 'any[]' in some locations where its type cannot be determined.": 1,
|
||||
"test/cso-lease-identity.test.ts\tTS2365\tOperator '*' cannot be applied to types 'number' and 'bigint'.": 1,
|
||||
"test/cso-ntfs-fixture.test.ts\tTS2769\tNo overload matches this call. The last overload gave the following error. Argument of type 'bigint | undefined' is not assignable to parameter of type 'bigint'. Type 'undefined' is not assignable to type 'bigint'.": 1,
|
||||
"test/cso-preparation-executor.test.ts\tTS2339\tProperty 'sidecar' does not exist on type 'PreparedDatabaseContract'. Property 'sidecar' does not exist on type '{ adapter: \"sqlite\"; connections: string[]; }'.": 1,
|
||||
"test/cso-public-ghcr.test.ts\tTS2352\tConversion of type '() => Promise<Response>' to type 'typeof fetch' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first. Property 'preconnect' is missing in type '() => Promise<Response>' but required in type 'typeof fetch'.": 1,
|
||||
"test/design-catalog.test.ts\tTS2769\tNo overload matches this call. The last overload gave the following error. Argument of type 'string' is not assignable to parameter of type '\"quality\" | \"slop\"'.": 1,
|
||||
"test/design-completion-handoff-scored.test.ts\tTS2352\tConversion of type '({ answered: boolean; answeredAt: string; answers: { ...; }; failed: boolean; questions: { header: string; multiSelect: boolean; options: { description: string; label: string; }[]; question: string; }[]; sessionId: string; toolUseId: string; unansweredQuestionIndices: never[]; } | ... 10 more ... | { ...; })[]' to type 'NativePlanQuestionCall[]' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first. Type '{ answered: boolean; answeredAt: string; answers: { ...; }; failed: boolean; questions: { header: string; multiSelect: boolean; options: { description: string; label: string; }[]; question: string; }[]; sessionId: string; toolUseId: string; unansweredQuestionIndices: never[]; } | ... 10 more ... | { ...; }' is not comparable to type 'NativePlanQuestionCall'. Type '{ sessionId: string; toolUseId: string; questions: { header: string; multiSelect: boolean; options: { description: string; label: string; }[]; question: string; }[]; answered: boolean; failed: boolean; answers: { \"Pass 1 (Info Architecture) \\u2014 7/10. The plan has DOM order and heading structure, but no scan path ...' is not comparable to type 'NativePlanQuestionCall'. Types of property 'answers' are incompatible. Type '{ \"Pass 1 (Info Architecture) \\u2014 7/10. The plan has DOM order and heading structure, but no scan path specification: what does the user's eye land on first, second, third? The Visual Hierarchy gap identifies that Save is indistinguishable from other buttons, but names it as a styling problem rather than an IA pr...' is not comparable to type 'Record<string, string>'. Property '\"Pass 1 (Info Architecture) \\u2014 7/10. The plan has DOM order and heading structure, but no scan path specification: what does the user's eye land on first, second, third? The Visual Hierarchy gap identifies that Save is indistinguishable from other buttons, but names it as a styling problem rather than an IA problem \\u2014 the primary action is missing from the visual hierarchy. Should I add a scan path description to the plan? <gstack-qid:plan-design-review-ia-scan-path>\"' is incompatible with index signature. Type 'undefined' is not comparable to type 'string'.": 1,
|
||||
"test/design-completion-handoff-scored.test.ts\tTS2352\tConversion of type '({ answered: boolean; answeredAt: string; answers: { ...; }; failed: boolean; questions: { header: string; multiSelect: boolean; options: { description: string; label: string; }[]; question: string; }[]; sessionId: string; toolUseId: string; unansweredQuestionIndices: never[]; } | ... 4 more ... | { ...; })[]' to type 'NativePlanQuestionCall[]' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first. Type '{ answered: boolean; answeredAt: string; answers: { ...; }; failed: boolean; questions: { header: string; multiSelect: boolean; options: { description: string; label: string; }[]; question: string; }[]; sessionId: string; toolUseId: string; unansweredQuestionIndices: never[]; } | ... 4 more ... | { ...; }' is not comparable to type 'NativePlanQuestionCall'. Type '{ sessionId: string; toolUseId: string; questions: { header: string; multiSelect: boolean; options: { description: string; label: string; }[]; question: string; }[]; answered: boolean; failed: boolean; answers: { \"Pass 1 \\u2014 Visual Hierarchy: The plan lists this gap but has no fix. The Save button renders with th...' is not comparable to type 'NativePlanQuestionCall'. Types of property 'answers' are incompatible. Type '{ \"Pass 1 \\u2014 Visual Hierarchy: The plan lists this gap but has no fix. The Save button renders with the same size, weight, and color as Reset, Cancel, and Export. DESIGN.md already specifies the remedy: Save gets #1d4ed8 fill with white text; the other three are ghost neutral buttons. Should I add this fix speci...' is not comparable to type 'Record<string, string>'. Property '\"Pass 1 \\u2014 Visual Hierarchy: The plan lists this gap but has no fix. The Save button renders with the same size, weight, and color as Reset, Cancel, and Export. DESIGN.md already specifies the remedy: Save gets #1d4ed8 fill with white text; the other three are ghost neutral buttons. Should I add this fix specification to the plan? <gstack-qid:plan-design-review-gap1-visual-hierarchy>\"' is incompatible with index signature. Type 'undefined' is not comparable to type 'string'.": 1,
|
||||
|
||||
Reference in new issue
Block a user