Use Garry Tan's exact Claude Code setup: 23 opinionated tools that serve as CEO, Designer, Eng Manager, Release Manager, Doc Engineer, and QA
TypeScript
The /cso release check accepts the low-confidence hypotheses /cso now reports (GST-3624) (#4753)
Garry Tana256d1530dad
diff --git a/changelog.d/cso-e2e-accepts-hypotheses.md b/changelog.d/cso-e2e-accepts-hypotheses.mdnew file mode 100644index 000000000..465a9cbf6--- /dev/null+++ b/changelog.d/cso-e2e-accepts-hypotheses.md@@ -0,0 +1 @@+**The release gate's /cso check accepts the low-confidence hypotheses /cso now reports.** Since /cso started keeping unconfirmed findings as hypotheses, its diff-mode eval failed every run because the check still required every finding in a daily report to be confirmed. The check now accepts hypotheses only at low confidence, still requires each case's main finding to be confirmed, and a free test replays a captured run through the real helper.diff --git a/test/cso-e2e-report-contract.test.ts b/test/cso-e2e-report-contract.test.tsnew file mode 100644index 000000000..b865b73b0--- /dev/null+++ b/test/cso-e2e-report-contract.test.ts@@ -0,0 +1,68 @@+// Release gate census 45216872389 (main @ c4cfe6d1) failed cso-diff-mode twice at the e2e report check's old+// rule that every daily finding is supported. #4739 made /cso keep an unconfirmed candidate as a+// low-confidence hypothesis instead of dropping it, and the captured run did exactly that. These are that+// run's two submissions (attempt 1, paid-slice-8-a1), replayed through the real helper on the case's fixture.+import { describe, expect, test } from 'bun:test';+import { spawnSync } from 'node:child_process';+import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';+import type { RunReportV3 } from '../lib/cso/contracts';+import { DIFF_MODE_BASE, DIFF_MODE_CHANGE, withFixture, requireReport, expectDailyFinding, expectDiffModeReport, isWebhookAuthFinding, type Fixture } from './helpers/cso-e2e-report';++const ROOT = path.resolve(import.meta.dir, '..');+const launcher = path.join(ROOT, 'bin', process.platform === 'win32' ? 'gstack-cso-launcher.exe' : 'gstack-cso-launcher');+const CAPTURED = ['diff-mode-45216872389-sub1.json', 'diff-mode-45216872389-sub2.json']+ .map(name => path.join(ROOT, 'test', 'fixtures', 'cso-e2e', name));++function replayCapturedRun(f: Fixture): void {+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'cso-e2e-replay-'));+ try {+ const cso = (...args: string[]) => {+ const result = spawnSync(launcher, args, { cwd: f.repo, encoding: 'utf8', timeout: 120_000,+ env: { HOME: home, GSTACK_HOME: f.state, PATH: process.env.PATH ?? '' } });+ if (result.status !== 0) throw new Error(`gstack-cso ${args[0]} exited ${result.status}: ${result.stderr}${result.stdout}`);+ return JSON.parse(result.stdout.slice(result.stdout.indexOf('{')));+ };+ const run = cso('start', '--repo', f.repo, '--diff', '--base', 'main', '--offline').runId as string;+ const control = path.join(home, 'control');+ fs.mkdirSync(control, { mode: 0o700 });+ for (const capture of CAPTURED) {+ const file = path.join(control, path.basename(capture));+ fs.writeFileSync(file, fs.readFileSync(capture), { mode: 0o600 });+ cso('submit', run, file);+ fs.rmSync(file);+ }+ cso('finish', run);+ } finally {+ fs.rmSync(home, { recursive: true, force: true });+ }+}++describe('cso e2e report contract (release gate 45216872389)', () => {+ test('the captured diff-mode run, with one low-confidence hypothesis, meets the daily and diff-mode contract', async () => {+ await withFixture(DIFF_MODE_BASE, DIFF_MODE_CHANGE, async f => {+ replayCapturedRun(f);+ const report = requireReport(f);+ expectDiffModeReport(report, f);+ expect(report.findings.map(item => item.evidence).sort()).toEqual(['hypothesis', 'supported', 'supported', 'supported']);+ });+ }, 60_000);++ test('the checks still reject a confident hypothesis, a downgraded target and a finding outside the diff', async () => {+ await withFixture(DIFF_MODE_BASE, DIFF_MODE_CHANGE, async f => {+ replayCapturedRun(f);+ const report = requireReport(f);+ const hypothesis = report.findings.find(item => item.evidence === 'hypothesis')!;+ expect(() => expectDailyFinding({ ...hypothesis, confidence: 'medium' })).toThrow();+ const downgraded: RunReportV3 = structuredClone(report);+ const targets = downgraded.findings.filter(isWebhookAuthFinding);+ expect(targets).toHaveLength(1);+ Object.assign(targets[0], { evidence: 'hypothesis', confidence: 'low' });+ expect(() => expectDiffModeReport(downgraded, f)).toThrow();+ const outside: RunReportV3 = structuredClone(report);+ outside.findings[0].location.path = 'app.js';+ expect(() => expectDiffModeReport(outside, f)).toThrow();+ });+ }, 60_000);+});diff --git a/test/fixtures/cso-e2e/diff-mode-45216872389-sub1.json b/test/fixtures/cso-e2e/diff-mode-45216872389-sub1.jsonnew file mode 100644index 000000000..f3b44cf93--- /dev/null+++ b/test/fixtures/cso-e2e/diff-mode-45216872389-sub1.json@@ -0,0 +1,183 @@+{+ "application": {+ "actors": [+ "unauthenticated network client",+ "authenticated user holding a bearer session token (alice, bob)",+ "payment provider sending webhook events (intended)"+ ],+ "assets": [+ "paid-plan entitlement state (payments Map)",+ "premium revenue report",+ "bearer session tokens",+ "service availability"+ ],+ "entrypoints": [+ "POST /webhook/payment (webhook.js:11-17, unauthenticated)",+ "GET /reports/premium (webhook.js:5-10, bearer auth + paid-plan check)"+ ],+ "tenantBoundaries": [+ "per-account entitlement keyed by accountId; account identity from sessions Map"+ ],+ "sensitiveOperations": [+ "granting paid plan via payments.set on webhook event",+ "serving premium revenue report"+ ],+ "invariants": [+ "Only authenticated, provider-signed payment events may change an account's plan",+ "Premium report is served only to accounts that actually paid",+ "Malformed requests must not terminate the server process"+ ]+ },+ "findings": [+ {+ "title": "Unauthenticated payment webhook lets anyone grant any account a paid plan",+ "rootCause": "POST /webhook/payment applies payment events with no provider signature/secret verification, no replay protection, and no amount/account validation",+ "location": {+ "path": "webhook.js",+ "line": 15,+ "symbol": "payments.set (webhook handler)"+ },+ "advisoryIds": [],+ "severity": "high",+ "confidence": "high",+ "confidenceRationale": "Entire request chain is in one file read in full: no middleware, no framework, package.json has no dependencies; the handler reads the raw body, parses it and writes plan:'paid' for the attacker-chosen accountId without any check.",+ "evidence": "supported",+ "attackerControl": "JSON body fields accountId and amount on an unauthenticated POST to /webhook/payment",+ "impact": "Payment bypass / broken function-level authorization: attacker unlocks paid entitlement (premium revenue report) for their own or any account without paying; can also set arbitrary amount values.",+ "scenario": "Bob (valid session 'bob-token', unpaid) sends POST /webhook/payment with body {\"accountId\":\"bob\",\"amount\":0}. Server responds 'payment applied'. Bob then sends GET /reports/premium with Authorization: Bearer bob-token and receives the premium revenue report instead of 402.",+ "trace": [+ "http.createServer request handler (webhook.js:4)",+ "route check POST /webhook/payment (webhook.js:11)",+ "body accumulation + JSON.parse (webhook.js:12-14)",+ "payments.set(event.accountId, {plan:'paid'}) (webhook.js:15)",+ "entitlement consumed by GET /reports/premium plan check (webhook.js:8)"+ ],+ "references": [+ "webhook.js:11-17",+ "webhook.js:8",+ "OWASP Top 10:2025 A01 Broken Access Control / A07 Authentication Failures",+ "OWASP API Security Top 10:2023 API5 Broken Function Level Authorization, API6 Unrestricted Access to Sensitive Business Flows",+ "ASVS v5.0.0-8.2.2"+ ],+ "recommendation": "Verify the provider signature over the raw request body with a shared secret (HMAC, constant-time compare) before parsing; reject events with stale timestamps and dedupe by event ID; derive account and amount from the verified provider event (or fetch it from the provider API) and confirm amount/plan match an expected price before granting entitlement; reject unsigned requests with 401.",+ "challenge": {+ "reviewer": "sequential challenge; independent agent unavailable",+ "independent": false,+ "mode": "sequential_fallback",+ "callers": "Only caller is the single http.createServer handler in webhook.js; app.js is a console.log baseline and package.json declares no dependencies or scripts, so no middleware or wrapper exists in the snapshot.",+ "controls": "Checked for signature headers (none read), shared secret/env var (none), IP allowlist (none), auth on webhook route (none; sessions lookup only on GET /reports/premium), amount/accountId validation (none).",+ "counterevidence": "A deployed reverse proxy/gateway could enforce webhook auth, but no infrastructure or deployment config exists in the repo and the server listens on port 3000 on all interfaces; such a control is unverified, not evidence of safety.",+ "conclusion": "Finding survives: attacker-controlled body reaches the entitlement write with no inspected control blocking it."+ }+ },+ {+ "title": "Malformed webhook body crashes the server process (unhandled JSON.parse exception)",+ "rootCause": "JSON.parse on attacker-supplied body inside the request 'end' event listener has no try/catch; the thrown SyntaxError is an uncaught exception that terminates the Node process",+ "location": {+ "path": "webhook.js",+ "line": 14,+ "symbol": "JSON.parse(body)"+ },+ "advisoryIds": [],+ "severity": "medium",+ "confidence": "high",+ "confidenceRationale": "Exception is thrown in an EventEmitter listener outside the createServer callback's synchronous frame; no process 'uncaughtException' handler or try/catch exists in the snapshot, so Node's default behavior is process exit.",+ "evidence": "supported",+ "attackerControl": "Raw body of an unauthenticated POST /webhook/payment (e.g. the bytes 'x')",+ "impact": "Single unauthenticated request causes denial of service and, because entitlement state is held only in memory, wipes all recorded payments (paying users lose access until events are replayed).",+ "scenario": "Attacker sends POST /webhook/payment with body 'not-json'; JSON.parse throws in the 'end' listener; Node prints the uncaught SyntaxError and exits; all clients lose service and the payments Map is lost.",+ "trace": [+ "POST /webhook/payment (webhook.js:11)",+ "req.on('end') listener (webhook.js:13)",+ "JSON.parse(body) throws (webhook.js:14)"+ ],+ "references": [+ "webhook.js:12-17",+ "OWASP Top 10:2025 A10 Mishandling of Exceptional Conditions",+ "ASVS v5.0.0-16.5.3"+ ],+ "recommendation": "Wrap parsing in try/catch and respond 400 on invalid JSON; validate the parsed object's shape; verify the signature before parsing; run under a supervisor and persist entitlement state durably.",+ "challenge": {+ "reviewer": "sequential challenge; independent agent unavailable",+ "independent": false,+ "mode": "sequential_fallback",+ "callers": "Same single handler; no wrapping error domain or framework error middleware.",+ "controls": "No try/catch, no process.on('uncaughtException'), no body parser with error handling, no process supervisor config in repo.",+ "counterevidence": "An external supervisor may restart the process (unverified, not in repo); restart would still lose in-memory payment state and allows repeated crashing.",+ "conclusion": "Finding survives; severity medium (availability plus loss of entitlement state, unauthenticated, trivially repeatable)."+ }+ },+ {+ "title": "Unbounded webhook request body accumulation enables memory exhaustion",+ "rootCause": "Request body chunks are concatenated into a string with no size limit before parsing",+ "location": {+ "path": "webhook.js",+ "line": 12,+ "symbol": "req.on('data') body += chunk"+ },+ "advisoryIds": [],+ "severity": "low",+ "confidence": "medium",+ "confidenceRationale": "No length check in code; Node http imposes no default body-size limit. Practical impact depends on runtime memory limits and Node's requestTimeout, which were not observed at runtime.",+ "evidence": "supported",+ "attackerControl": "Size and streaming rate of an unauthenticated POST body",+ "impact": "Memory exhaustion / degraded service; superseded in practice by the trivial crash in the JSON.parse finding.",+ "scenario": "Attacker opens several concurrent POST /webhook/payment requests each streaming hundreds of MB; the process accumulates them in memory until OOM.",+ "trace": [+ "POST /webhook/payment (webhook.js:11)",+ "req.on('data') concatenation (webhook.js:12)"+ ],+ "references": [+ "webhook.js:12",+ "OWASP API Security Top 10:2023 API4 Unrestricted Resource Consumption",+ "ASVS v5.0.0-2.4.1"+ ],+ "recommendation": "Enforce a maximum body size (check Content-Length and running byte count; destroy the request with 413 when exceeded) and authenticate before buffering.",+ "challenge": {+ "reviewer": "sequential challenge; independent agent unavailable",+ "independent": false,+ "mode": "sequential_fallback",+ "callers": "Same single handler.",+ "controls": "No Content-Length check, no byte counter, no server.maxRequestsPerSocket or body limit configured.",+ "counterevidence": "Node 18+ default requestTimeout (300s) bounds slow requests in time but not size; a reverse proxy body limit may exist but is not in the repo.",+ "conclusion": "Survives as low severity."+ }+ },+ {+ "title": "Static bearer session tokens hardcoded in source",+ "rootCause": "Session tokens for named users are literal constants in webhook.js rather than issued secrets",+ "location": {+ "path": "webhook.js",+ "line": 2,+ "symbol": "sessions"+ },+ "advisoryIds": [],+ "severity": "low",+ "confidence": "low",+ "confidenceRationale": "Tokens appear to be synthetic placeholders; open question is whether this sessions map is used outside a fixture/demo. If deployed as-is, anyone with source access can authenticate as alice or bob.",+ "evidence": "hypothesis",+ "attackerControl": "Authorization header value copied from the repository",+ "impact": "Account impersonation for alice/bob on GET /reports/premium (still gated by paid plan, which the webhook finding bypasses).",+ "scenario": "Reader of the repository sends Authorization: Bearer alice-token and is treated as alice.",+ "trace": [+ "GET /reports/premium (webhook.js:5)",+ "sessions.get(token) (webhook.js:6)"+ ],+ "references": [+ "webhook.js:2",+ "webhook.js:6",+ "OWASP Top 10:2025 A07 Authentication Failures"+ ],+ "recommendation": "Issue random, expiring session tokens at login and store them server-side (hashed); never commit token values. Confirm whether these tokens are used in any deployed environment.",+ "challenge": {+ "reviewer": "sequential challenge; independent agent unavailable",+ "independent": false,+ "mode": "sequential_fallback",+ "callers": "sessions is read only at webhook.js:6.",+ "controls": "No login/issuance flow, expiry, or env-based override exists.",+ "counterevidence": "Token strings look like test placeholders; no deployment evidence. Kept as hypothesis rather than dropped because no code disproves deployed use.",+ "conclusion": "Hypothesis: confirm whether this file is deployed with these tokens."+ }+ }+ ]+}diff --git a/test/fixtures/cso-e2e/diff-mode-45216872389-sub2.json b/test/fixtures/cso-e2e/diff-mode-45216872389-sub2.jsonnew file mode 100644index 000000000..d9d45c690--- /dev/null+++ b/test/fixtures/cso-e2e/diff-mode-45216872389-sub2.json@@ -0,0 +1,136 @@+{+ "coverage": [+ {+ "domain": "application-model",+ "scope": "default",+ "status": "assessed",+ "method": "static read of all 3 snapshot files via helper",+ "gaps": [],+ "exclusions": [],+ "evidence": [+ "Actors, assets, entrypoints, invariants derived from webhook.js (changed), app.js, package.json; submitted application model"+ ]+ },+ {+ "domain": "attack-surface",+ "scope": "default",+ "status": "assessed",+ "method": "static census of HTTP routes in diff and affected paths",+ "gaps": [],+ "exclusions": [],+ "evidence": [+ "Two routes: POST /webhook/payment (unauthenticated), GET /reports/premium (bearer + plan); 404 fallthrough; server listens on port 3000 all interfaces"+ ]+ },+ {+ "domain": "secrets",+ "scope": "default",+ "status": "assessed",+ "method": "manual review of redacted current source and helper-retained history for base..HEAD (1 commit)",+ "gaps": [],+ "exclusions": [],+ "evidence": [+ "No provider credential prefixes found; hardcoded synthetic session tokens recorded as hypothesis finding; Gitleaks not run (offline static run, no qualified scanner profile requested)"+ ]+ },+ {+ "domain": "dependencies",+ "scope": "default",+ "status": "assessed",+ "method": "manifest review",+ "gaps": [],+ "exclusions": [],+ "evidence": [+ "package.json declares no dependencies, scripts or lockfile; only node:http builtin used; OSV not run (offline)"+ ]+ },+ {+ "domain": "ci-cd",+ "scope": "default",+ "status": "not_applicable",+ "method": "snapshot inventory review",+ "gaps": [],+ "exclusions": [],+ "evidence": [+ "No CI/CD workflow files in snapshot inventory (3 files: app.js, package.json, webhook.js)"+ ]+ },+ {+ "domain": "infrastructure",+ "scope": "default",+ "status": "not_applicable",+ "method": "snapshot inventory review",+ "gaps": [],+ "exclusions": [],+ "evidence": [+ "No Dockerfile, IaC, or deployment configuration in snapshot; deployed gateway controls unknown and noted in finding challenges"+ ]+ },+ {+ "domain": "integrations",+ "scope": "default",+ "status": "assessed",+ "method": "full trace of payment webhook handler",+ "gaps": [],+ "exclusions": [],+ "evidence": [+ "Webhook lacks signature, timestamp/replay, idempotency, amount validation; recorded as high finding; OWASP API 2023 API4/API5/API6 checked"+ ]+ },+ {+ "domain": "llm-agentic-mcp",+ "scope": "default",+ "status": "not_applicable",+ "method": "snapshot inventory review",+ "gaps": [],+ "exclusions": [],+ "evidence": [+ "No LLM, agent, or MCP code in snapshot"+ ]+ },+ {+ "domain": "skill-supply-chain",+ "scope": "default",+ "status": "not_applicable",+ "method": "snapshot inventory review",+ "gaps": [],+ "exclusions": [],+ "evidence": [+ "No skill definitions, hooks, plugins, or agent configuration in snapshot"+ ]+ },+ {+ "domain": "owasp-2025",+ "scope": "default",+ "status": "assessed",+ "method": "OWASP Top 10:2025 mapping against diff and affected paths; ASVS 5.0.0 selected requirements",+ "gaps": [],+ "exclusions": [],+ "evidence": [+ "A01/A07 webhook authorization (finding), A10 unhandled JSON.parse (finding), A06 business flow (amount unvalidated), A05 no injection sinks, A02 no debug surface; ASVS 8.2.2, 16.5.3, 2.4.1 failed; 1.2.4/1.2.5/1.3.6/5.3.2 not applicable"+ ]+ },+ {+ "domain": "stride",+ "scope": "default",+ "status": "assessed",+ "method": "STRIDE over webhook and premium report trust transitions",+ "gaps": [],+ "exclusions": [],+ "evidence": [+ "Spoofing: forged payment provider (finding); Tampering: arbitrary amount/account; DoS: crash and unbounded body (findings); Elevation: unpaid to paid entitlement; Info disclosure: premium report via forged entitlement; Repudiation: no event logging"+ ]+ },+ {+ "domain": "data-classification",+ "scope": "default",+ "status": "assessed",+ "method": "static data flow review",+ "gaps": [],+ "exclusions": [],+ "evidence": [+ "Restricted: bearer session tokens (hardcoded); Confidential: premium revenue report, payment amounts held in memory only; no PII persistence or logging observed"+ ]+ }+ ]+}diff --git a/test/helpers/cso-e2e-report.ts b/test/helpers/cso-e2e-report.tsnew file mode 100644index 000000000..03ba9bed7--- /dev/null+++ b/test/helpers/cso-e2e-report.ts@@ -0,0 +1,125 @@+import { expect } from 'bun:test';+import { validateCoverage, validateFinding, completeness, type FindingV3, type RunReportV3 } from '../../lib/cso/contracts';+import { spawnSync } from 'node:child_process';+import * as fs from 'node:fs';+import * as path from 'node:path';+import * as os from 'node:os';++// Synthetic credential-shaped canary: its bytes must never appear in agent output or saved reports.+export const CANARY = ['ghp_', 'f7K3mV9nT2qR8sL4xP6dW0bH5jY1cZ3aF9uE'].join('');+export const PACKAGE = JSON.stringify({ name: 'cso-v3-evaluation', version: '1.0.0', private: true });+export const DIFF_MODE_BASE = { 'package.json': PACKAGE, 'app.js': 'console.log("fixture baseline");\n' };+export const DIFF_MODE_CHANGE = {+ 'webhook.js': `const http = require('node:http');+const sessions = new Map([['alice-token', 'alice'], ['bob-token', 'bob']]);+const payments = new Map();+http.createServer((req, res) => {+ if (req.method === 'GET' && req.url === '/reports/premium') {+ const account = sessions.get((req.headers.authorization || '').replace('Bearer ', ''));+ if (!account) { res.writeHead(401); return res.end(); }+ if (payments.get(account)?.plan !== 'paid') { res.writeHead(402); return res.end('upgrade required'); }+ return res.end('premium revenue report');+ }+ if (req.method !== 'POST' || req.url !== '/webhook/payment') { res.writeHead(404); return res.end(); }+ let body = ''; req.on('data', chunk => body += chunk);+ req.on('end', () => {+ const event = JSON.parse(body);+ payments.set(event.accountId, { plan: 'paid', amount: event.amount });+ res.end('payment applied');+ });+}).listen(3000);+`,+};++export interface Fixture { repo: string; state: string; original: Map<string, string>; }+export function git(repo: string, ...args: string[]): string {+ // Seed commits must not depend on the host's Git configuration (signing, hooks, templates).+ const result = spawnSync('git', ['-c', 'commit.gpgsign=false', ...args], { cwd: repo, encoding: 'utf8', timeout: 5000,+ env: { ...process.env, GIT_CONFIG_GLOBAL: os.devNull, GIT_CONFIG_NOSYSTEM: '1' } });+ if (result.status !== 0) throw new Error(`Fixture git ${args[0]} failed: ${result.stderr}`);+ return result.stdout;+}+function fixture(files: Record<string, string>, diff?: Record<string, string>): Fixture {+ const repo = fs.mkdtempSync(path.join(os.tmpdir(), 'skill-e2e-cso-v3-'));+ const state = fs.mkdtempSync(path.join(os.tmpdir(), 'skill-e2e-cso-state-'));+ git(repo, 'init', '-b', 'main');+ git(repo, 'config', 'user.email', '[email protected]');+ git(repo, 'config', 'user.name', 'CSO Test');+ const write = (inputs: Record<string, string>) => {+ for (const [name, content] of Object.entries(inputs)) {+ fs.mkdirSync(path.dirname(path.join(repo, name)), { recursive: true });+ fs.writeFileSync(path.join(repo, name), content);+ }+ git(repo, 'add', '.');+ git(repo, 'commit', '-m', 'CSO fixture');+ };+ write(files);+ if (diff) { git(repo, 'checkout', '-b', 'fixture-change'); write(diff); }+ return { repo, state, original: new Map(Object.entries({ ...files, ...diff })) };+}+function removeFixture(f: Fixture): void {+ fs.rmSync(f.repo, { recursive: true, force: true });+ fs.rmSync(f.state, { recursive: true, force: true });+}+export async function withFixture<T>(files: Record<string, string>, diff: Record<string, string> | undefined, run: (fixture: Fixture) => Promise<T>): Promise<T> {+ const f = fixture(files, diff);+ try { return await run(f); } finally { removeFixture(f); }+}+function reportsUnder(dir: string): string[] {+ // Bounded to the exact private namespace; no report in source or old v2 namespace is accepted.+ if (!fs.existsSync(dir)) return [];+ return fs.readdirSync(dir, { withFileTypes: true }).flatMap(entry => {+ const child = path.join(dir, entry.name);+ return entry.isDirectory() ? reportsUnder(child) : entry.name === 'report.json' ? [child] : [];+ });+}+/** Daily reports carry supported findings and, since #4739, low-confidence hypotheses (never dropped candidates). */+export function expectDailyFinding(finding: FindingV3): void {+ const { id, fingerprint, reproduction, repair, closure, verificationId, reproductionAttemptId, ...submitted } = finding;+ validateFinding(submitted);+ expect(id).toBe(fingerprint);+ expect(id).toMatch(/^[a-f0-9]{32}$/);+ expect(['supported', 'hypothesis']).toContain(finding.evidence);+ if (finding.evidence === 'hypothesis') expect(finding.confidence).toBe('low');+ expect(reproduction).toBe('not_attempted');+ expect(repair).toBe('not_attempted');+ expect(closure).toBe('open');+ expect(verificationId).toBeUndefined();+ expect(reproductionAttemptId).toBeUndefined();+}+export function requireReport(f: Fixture): RunReportV3 {+ const reports = reportsUnder(path.join(f.state, 'security', 'cso'));+ expect(reports).toHaveLength(1); // A mandatory assertion: absent reports used to silently pass.+ const raw = fs.readFileSync(reports[0], 'utf8');+ expect(raw).not.toContain(CANARY);+ expect(raw).not.toContain(fs.realpathSync(f.repo));+ const report: RunReportV3 = JSON.parse(raw);+ expect(report.schemaVersion).toBe(3);+ expect(report.status).toBe('finished');+ expect(report.source.root).toBe('<REDACTED-internal.user_path>');+ expect(report.policy.mode).toBe('daily');+ expect(report.policy.offline).toBe(true);+ expect(report.coverage.length).toBeGreaterThan(0);+ report.coverage.forEach(validateCoverage);+ expect(report.completeness).toBe(completeness(report));+ report.findings.forEach(expectDailyFinding);+ const markdown = fs.readFileSync(path.join(path.dirname(reports[0]), 'report.md'), 'utf8');+ expect(markdown).toMatch(/^(complete|partial|not assessed) — /);+ expect(markdown).not.toContain(CANARY);+ if (report.findings.some(item => item.evidence === 'hypothesis')) expect(markdown).toContain('\nHypotheses (unconfirmed):\n');+ if (process.platform !== 'win32') expect(fs.statSync(reports[0]).mode & 0o777).toBe(0o600);+ for (const [name, content] of f.original) expect(fs.readFileSync(path.join(f.repo, name), 'utf8')).toBe(content);+ expect(git(f.repo, 'status', '--porcelain=v1', '--untracked-files=all')).toBe('');+ return report;+}+/** The finding that names the changed webhook's missing authentication (title or root cause, not a side effect in its impact). */+export const isWebhookAuthFinding = (item: FindingV3): boolean => item.location.path === 'webhook.js'+ && /signature|authentic|forg|spoof|hmac/i.test(`${item.title} ${item.rootCause}`);+/** cso-diff-mode's case contract: the changed webhook's missing authentication is a supported finding, and nothing outside the diff is reported. */+export function expectDiffModeReport(report: RunReportV3, f: Fixture): void {+ expect(report.policy.diff).toBe(true);+ expect(report.policy.base).toBe('main');+ expect(report.source.baseCommit).toBe(git(f.repo, 'rev-parse', 'main').trim());+ expect(report.findings.some(item => item.evidence === 'supported' && isWebhookAuthFinding(item))).toBe(true);+ expect(report.findings.every(item => item.location.path === 'webhook.js')).toBe(true);+}diff --git a/test/helpers/free-fixtures-data.ts b/test/helpers/free-fixtures-data.tsindex 5af7ff87f..1575b82ec 100644--- a/test/helpers/free-fixtures-data.ts+++ b/test/helpers/free-fixtures-data.ts@@ -75,6 +75,7 @@ export const FREE_FIXTURES: Readonly<Record<string, readonly string[]>> = {'test/fixtures/coverage-audit-two-file-grep.json': ['test/coverage-audit-evidence.test.ts'],'test/fixtures/coverage-audit-wc-anchor.json': ['test/coverage-audit-evidence.test.ts'],'test/fixtures/credential-rejection-39696775546.json': ['test/credential-rejection.test.ts'],+ 'test/fixtures/cso-e2e/**': ['test/cso-e2e-report-contract.test.ts'],'test/fixtures/cso-eval/**': ['scripts/cso-eval.ts', 'test/cso-eval.test.ts', 'test/cso-stack-cold-integration.test.ts', 'test/helpers/cso-eval-oracles.ts'],'test/fixtures/cso-http-smoke.c': ['test/cso-docker-integration.test.ts'],'test/fixtures/cso-sarif/**': ['test/cso-scanner-cli.test.ts', 'test/cso-scanners.test.ts'],diff --git a/test/helpers/touchfiles-data.ts b/test/helpers/touchfiles-data.tsindex 9c6530ac3..43dc01fa6 100644--- a/test/helpers/touchfiles-data.ts+++ b/test/helpers/touchfiles-data.ts@@ -614,9 +614,9 @@ export const E2E_TOUCHFILES: Record<string, string[]> = {'retro-base-branch': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'bin/gstack-retro-metrics', 'lib/retro-friction.ts', 'retro/**', 'test/skill-e2e-retro.test.ts'],// CSO- 'cso-full-audit': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'cso/**', 'lib/cso/**', 'lib/redact-engine.ts', 'lib/redact-patterns.ts', 'test/skill-e2e-cso.test.ts'],- 'cso-diff-mode': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'cso/**', 'lib/cso/**', 'lib/redact-engine.ts', 'lib/redact-patterns.ts', 'test/skill-e2e-cso.test.ts'],- 'cso-infra-scope': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'cso/**', 'lib/cso/**', 'lib/redact-engine.ts', 'lib/redact-patterns.ts', 'test/skill-e2e-cso.test.ts'],+ 'cso-full-audit': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'cso/**', 'lib/cso/**', 'lib/redact-engine.ts', 'lib/redact-patterns.ts', 'test/skill-e2e-cso.test.ts', 'test/helpers/cso-e2e-report.ts'],+ 'cso-diff-mode': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'cso/**', 'lib/cso/**', 'lib/redact-engine.ts', 'lib/redact-patterns.ts', 'test/skill-e2e-cso.test.ts', 'test/helpers/cso-e2e-report.ts'],+ 'cso-infra-scope': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'cso/**', 'lib/cso/**', 'lib/redact-engine.ts', 'lib/redact-patterns.ts', 'test/skill-e2e-cso.test.ts', 'test/helpers/cso-e2e-report.ts'],// Learnings'write-skill-add-lesson': ['write-skill/**', 'bin/gstack-skill-bill', 'lib/skill-bill.ts', 'lib/context-bill.ts', 'test/skill-e2e-write-skill.test.ts'],diff --git a/test/skill-e2e-cso.test.ts b/test/skill-e2e-cso.test.tsindex efd95bac3..30fd9f1a3 100644--- a/test/skill-e2e-cso.test.ts+++ b/test/skill-e2e-cso.test.ts@@ -2,11 +2,8 @@ import { test, expect, afterAll } from 'bun:test';import { CAPTURE_LONG_MS } from './helpers/eval-budgets';import { runSkillTest, SESSION_DRAIN_GRACE_MS } from './helpers/session-runner';import { ROOT, runId, describeIfSelected, logCost, recordE2E, createEvalCollector, finalizeEvalCollector } from './helpers/e2e-helpers';-import { validateCoverage, validateFinding, completeness, type RunReportV3 } from '../lib/cso/contracts';-import { spawnSync } from 'node:child_process';-import * as fs from 'node:fs';+import { CANARY, PACKAGE, DIFF_MODE_BASE, DIFF_MODE_CHANGE, withFixture, requireReport, expectDiffModeReport, type Fixture } from './helpers/cso-e2e-report';import * as path from 'node:path';-import * as os from 'node:os';const evalCollector = createEvalCollector('e2e-cso');// runSkillTest can drain stderr for 5s after its unchanged CLI deadline.@@ -15,80 +12,6 @@ const CSO_FINALIZE_MS = SESSION_DRAIN_GRACE_MS + 5_000;let captureSequence = 0;afterAll(() => finalizeEvalCollector(evalCollector));-// Synthetic credential-shaped canary: its bytes must never appear in agent output or saved reports.-const CANARY = ['ghp_', 'f7K3mV9nT2qR8sL4xP6dW0bH5jY1cZ3aF9uE'].join('');-interface Fixture { repo: string; state: string; original: Map<string, string>; }-function git(repo: string, ...args: string[]): string {- const result = spawnSync('git', args, { cwd: repo, encoding: 'utf8', timeout: 5000 });- if (result.status !== 0) throw new Error(`Fixture git ${args[0]} failed: ${result.stderr}`);- return result.stdout;-}-function fixture(files: Record<string, string>, diff?: Record<string, string>): Fixture {- const repo = fs.mkdtempSync(path.join(os.tmpdir(), 'skill-e2e-cso-v3-'));- const state = fs.mkdtempSync(path.join(os.tmpdir(), 'skill-e2e-cso-state-'));- git(repo, 'init', '-b', 'main');- git(repo, 'config', 'user.email', '[email protected]');- git(repo, 'config', 'user.name', 'CSO Test');- const write = (inputs: Record<string, string>) => {- for (const [name, content] of Object.entries(inputs)) {- fs.mkdirSync(path.dirname(path.join(repo, name)), { recursive: true });- fs.writeFileSync(path.join(repo, name), content);- }- git(repo, 'add', '.');- git(repo, 'commit', '-m', 'CSO fixture');- };- write(files);- if (diff) { git(repo, 'checkout', '-b', 'fixture-change'); write(diff); }- return { repo, state, original: new Map(Object.entries({ ...files, ...diff })) };-}-function removeFixture(f: Fixture): void {- fs.rmSync(f.repo, { recursive: true, force: true });- fs.rmSync(f.state, { recursive: true, force: true });-}-async function withFixture<T>(files:Record<string,string>,diff:Record<string,string>|undefined,run:(fixture:Fixture)=>Promise<T>):Promise<T>{const f=fixture(files,diff);try{return await run(f);}finally{removeFixture(f);}}-function reportsUnder(dir: string): string[] {- // Bounded to the exact private namespace; no report in source or old v2 namespace is accepted.- if (!fs.existsSync(dir)) return [];- return fs.readdirSync(dir, { withFileTypes: true }).flatMap(entry => {- const child = path.join(dir, entry.name);- return entry.isDirectory() ? reportsUnder(child) : entry.name === 'report.json' ? [child] : [];- });-}-function requireReport(f: Fixture): RunReportV3 {- const reports = reportsUnder(path.join(f.state, 'security', 'cso'));- expect(reports).toHaveLength(1); // A mandatory assertion: absent reports used to silently pass.- const raw = fs.readFileSync(reports[0], 'utf8');- expect(raw).not.toContain(CANARY);- expect(raw).not.toContain(fs.realpathSync(f.repo));- const report: RunReportV3 = JSON.parse(raw);- expect(report.schemaVersion).toBe(3);- expect(report.status).toBe('finished');- expect(report.source.root).toBe('<REDACTED-internal.user_path>');- expect(report.policy.mode).toBe('daily');- expect(report.policy.offline).toBe(true);- expect(report.coverage.length).toBeGreaterThan(0);- report.coverage.forEach(validateCoverage);- expect(report.completeness).toBe(completeness(report));- for (const finding of report.findings) {- const { id, fingerprint, reproduction, repair, closure, verificationId, reproductionAttemptId, ...submitted } = finding;- validateFinding(submitted);- expect(id).toBe(fingerprint);- expect(id).toMatch(/^[a-f0-9]{32}$/);- expect(finding.evidence).toBe('supported');- expect(reproduction).toBe('not_attempted');- expect(repair).toBe('not_attempted');- expect(closure).toBe('open');- expect(verificationId).toBeUndefined();- expect(reproductionAttemptId).toBeUndefined();- }- const markdown = fs.readFileSync(path.join(path.dirname(reports[0]), 'report.md'), 'utf8');- expect(markdown).toMatch(/^(complete|partial|not assessed) — /);- expect(markdown).not.toContain(CANARY);- if (process.platform !== 'win32') expect(fs.statSync(reports[0]).mode & 0o777).toBe(0o600);- for (const [name, content] of f.original) expect(fs.readFileSync(path.join(f.repo, name), 'utf8')).toBe(content);- expect(git(f.repo, 'status', '--porcelain=v1', '--untracked-files=all')).toBe('');- return report;-}function prompt(f: Fixture, flags: string): string {return `Read ${path.join(ROOT, 'cso/SKILL.md')} and perform /cso ${flags} --offline --base main on ${f.repo}.The trusted installed helper for this evaluation is ${path.join(ROOT, 'bin', process.platform === 'win32' ? 'gstack-cso-launcher.exe' : 'gstack-cso-launcher')}.@@ -99,8 +22,6 @@ This is a static audit: do not execute the application, test provider credentialDo not read or execute files outside this repository except the trusted skill/helper and its private run artifacts.`;}-const PACKAGE = JSON.stringify({ name: 'cso-v3-evaluation', version: '1.0.0', private: true });-describeIfSelected('CSO v3 — full audit', ['cso-full-audit'], () => {test('/cso persists supported tenant-boundary findings with redacted evidence', async () => {await withFixture({@@ -136,7 +57,7 @@ http.createServer((req, res) => {expect(result.toolCalls.some(call => /Read|Bash/.test(call.tool)&& JSON.stringify(call.input).includes('sections/audit-phases.md'))).toBe(true);const report = requireReport(f);- const tenant = report.findings.filter(item => item.location.path === 'server.js' && /tenant|owner|authoriz|access control/i.test(`${item.rootCause} ${item.impact}`));+ const tenant = report.findings.filter(item => item.evidence === 'supported' && item.location.path === 'server.js' && /tenant|owner|authoriz|access control/i.test(`${item.rootCause} ${item.impact}`));expect(tenant.length).toBeGreaterThan(0);expect(tenant.every(item => item.trace.length > 0 && item.challenge.controls.length > 0)).toBe(true);passed = result.browseErrors.length === 0;@@ -149,27 +70,7 @@ http.createServer((req, res) => {describeIfSelected('CSO v3 — diff mode', ['cso-diff-mode'], () => {test('/cso --diff records its base and investigates changed security paths', async () => {- await withFixture({ 'package.json': PACKAGE, 'app.js': 'console.log("fixture baseline");\n' }, {- 'webhook.js': `const http = require('node:http');-const sessions = new Map([['alice-token', 'alice'], ['bob-token', 'bob']]);-const payments = new Map();-http.createServer((req, res) => {- if (req.method === 'GET' && req.url === '/reports/premium') {- const account = sessions.get((req.headers.authorization || '').replace('Bearer ', ''));- if (!account) { res.writeHead(401); return res.end(); }- if (payments.get(account)?.plan !== 'paid') { res.writeHead(402); return res.end('upgrade required'); }- return res.end('premium revenue report');- }- if (req.method !== 'POST' || req.url !== '/webhook/payment') { res.writeHead(404); return res.end(); }- let body = ''; req.on('data', chunk => body += chunk);- req.on('end', () => {- const event = JSON.parse(body);- payments.set(event.accountId, { plan: 'paid', amount: event.amount });- res.end('payment applied');- });-}).listen(3000);-`,- },async f=>{+ await withFixture(DIFF_MODE_BASE, DIFF_MODE_CHANGE, async f => {const result = await runSkillTest({testName: 'cso-diff-mode',runId: `cso-diff-mode-${process.env.EVALS_RUN_ID ?? runId}-${process.pid}-${++captureSequence}`,@@ -182,11 +83,7 @@ http.createServer((req, res) => {try {expect(result.exitReason).toBe('success');const report = requireReport(f);- expect(report.policy.diff).toBe(true);- expect(report.policy.base).toBe('main');- expect(report.source.baseCommit).toBe(git(f.repo, 'rev-parse', 'main').trim());- expect(report.findings.some(item => item.location.path === 'webhook.js' && /signature|authentic|forg|spoof|hmac/i.test(`${item.title} ${item.rootCause} ${item.impact}`))).toBe(true);- expect(report.findings.every(item => item.location.path === 'webhook.js')).toBe(true);+ expectDiffModeReport(report, f);passed = result.browseErrors.length === 0;} finally {recordE2E(evalCollector, 'cso-diff-mode', 'e2e-cso', result, { passed });@@ -228,7 +125,7 @@ jobs:expect(result.exitReason).toBe('success');const report = requireReport(f);expect(report.policy.scope).toBe('infra');- const workflow=report.findings.find(item=>item.location.path==='.github/workflows/comment.yml');+ const workflow=report.findings.find(item=>item.evidence==='supported'&&item.location.path==='.github/workflows/comment.yml');expect(workflow).toBeDefined();const chain=[workflow!.title,workflow!.rootCause,workflow!.attackerControl,workflow!.impact,workflow!.scenario,...workflow!.trace].join(' ');expect(chain).toMatch(/github\.event\.comment\.body|issue comment body|comment body/i);