mirror of
https://github.com/garrytan/gstack.git
synced 2026-12-01 12:25:53 +01:00
Remove the /cso security audit skill, since a plain audit request finds more (#4833)
/cso is gone: the skill, its native helper programs, scanner images, CI jobs, docs and the rest of its tests. Upgrading removes gstack's own `/cso` entries and old helper files, and leaves a skill of your own named `cso` alone. Why: on 52 real security advisories, plainly asking the agent to audit the code caught more than /cso (13 vs 7 on particle-1; 12 vs 8 of 51 on Claude Opus 5.5, within the margin of error). To do: nothing. Optional cleanup of old scanner images and reports is in the changelog entry. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> Review-Finding: p1/outside-voice#1 reader=outside-voice Review-Finding: p1/outside-voice#2 reader=outside-voice Review-Finding: p1/adversarial-native#1 reader=adversarial-native Review-Finding: p1/adversarial-native#2 reader=adversarial-native
This commit is contained in:
1 parent
fd7e8c7b36
commit
2fae1d78d6
207 files changed
+387
-32001
No files matched your search
@@ -473,9 +473,6 @@ describe('web research ({{ASIDE_RESEARCH}})', () => {
|
||||
});
|
||||
|
||||
test('every template carrying {{ASIDE_RESEARCH}} renders the section exactly once', () => {
|
||||
// CSO's private startup keeps advisory queries inside its stricter public-ID
|
||||
// policy and intentionally does not import the generic Aside research block.
|
||||
expect(carriers).not.toContain('cso');
|
||||
expect(carriers).toEqual(expect.arrayContaining(['design-consultation', 'office-hours', 'plan-ceo-review', 'plan-devex-review', 'plan-eng-review', 'review']));
|
||||
for (const skill of carriers) {
|
||||
const md = fs.readFileSync(path.join(ROOT, skill, 'SKILL.md'), 'utf-8');
|
||||
|
||||
@@ -119,8 +119,6 @@ const EXPECTED_INTERACTIVE = [
|
||||
'qa-only',
|
||||
'codex',
|
||||
'autoplan',
|
||||
// CSO uses a private startup and intentionally omits the shared PREAMBLE,
|
||||
// including its generic AskUserQuestion formatting block.
|
||||
'retro',
|
||||
'design-review',
|
||||
'design-consultation',
|
||||
|
||||
@@ -1,110 +0,0 @@
|
||||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { claudeStreamState, consumeClaudeStreamLine, resultFromClaudeStream, runClaudeProducerStream } from './helpers/providers/claude-stream';
|
||||
|
||||
// The event shapes claude 2.1.263 prints with -p --output-format stream-json --verbose --include-partial-messages.
|
||||
const start = (id: string, input: number, cached = 7) => ({ type: 'stream_event', parent_tool_use_id: null, event: { type: 'message_start', message: { id, usage: { input_tokens: input, output_tokens: 1, cache_read_input_tokens: cached } } } });
|
||||
const delta = (output: number) => ({ type: 'stream_event', parent_tool_use_id: null, event: { type: 'message_delta', delta: { stop_reason: 'tool_use' }, usage: { output_tokens: output } } });
|
||||
const stop = { type: 'stream_event', parent_tool_use_id: null, event: { type: 'message_stop' } };
|
||||
const text = (id: string, value: string) => ({ type: 'assistant', message: { id, content: [{ type: 'text', text: value }], usage: { input_tokens: 1, output_tokens: 1 } } });
|
||||
const result = (extra: Record<string, unknown>) => ({ type: 'result', subtype: 'success', is_error: false, num_turns: 2, result: 'REPORT', usage: { input_tokens: 2001, output_tokens: 201, cache_read_input_tokens: 14 }, ...extra });
|
||||
const lines = (...events: unknown[]) => events.map(event => JSON.stringify(event));
|
||||
|
||||
const fixtures: string[] = [];
|
||||
afterEach(() => { for (const path of fixtures.splice(0)) rmSync(path, { recursive: true, force: true }); });
|
||||
const stub = (body: string) => {
|
||||
const directory = mkdtempSync(join(tmpdir(), 'claude-stream-')); fixtures.push(directory);
|
||||
const script = join(directory, 'claude');
|
||||
writeFileSync(script, `#!/bin/sh\ncat > /dev/null\n${body}\n`, { mode: 0o755 });
|
||||
return { script, directory };
|
||||
};
|
||||
const printf = (events: unknown[]) => lines(...events).map(line => `printf '%s\\n' '${line}'`).join('\n');
|
||||
|
||||
describe('Claude producer stream accounting', () => {
|
||||
test('counts every message from its stream usage, including one a kill interrupted', () => {
|
||||
const state = claudeStreamState();
|
||||
for (const line of lines(start('a', 1000), text('a', 'first note'), delta(100), stop, start('b', 1001), text('b', 'second note'), delta(40))) consumeClaudeStreamLine(state, line);
|
||||
const killed = resultFromClaudeStream(state, { model: 'claude-test', durationMs: 5, error: { code: 'timeout', reason: 'exceeded 5ms' } });
|
||||
expect(killed).toMatchObject({ tokens: { input: 2001, output: 140, cached: 14 }, toolCalls: 2, output: 'second note', error: { code: 'timeout' }, modelUsed: 'claude-test' });
|
||||
});
|
||||
|
||||
test('takes usage and turns from the final result and keeps the paid result contract', () => {
|
||||
const state = claudeStreamState();
|
||||
for (const line of lines(start('a', 1000), delta(100), stop, result({}))) consumeClaudeStreamLine(state, line);
|
||||
expect(resultFromClaudeStream(state, { model: 'claude-test', durationMs: 5 })).toEqual({ output: 'REPORT', tokens: { input: 2001, output: 201, cached: 14 }, durationMs: 5, toolCalls: 2, toolTimeline: [], modelUsed: 'claude-test' });
|
||||
for (const ending of [[], [result({ result: ' ' })], [result({ result: 7 })], [result({ is_error: true })], [result({ subtype: 'error_max_turns' })]]) {
|
||||
const partial = claudeStreamState();
|
||||
for (const line of lines(start('a', 10), delta(3), stop, ...ending)) consumeClaudeStreamLine(partial, line);
|
||||
const outcome = resultFromClaudeStream(partial, { model: 'claude-test', durationMs: 1 });
|
||||
expect(outcome).toMatchObject({ output: '', error: { code: 'unknown', reason: 'empty or invalid output from claude CLI (exit 0)' } });
|
||||
expect(outcome.tokens.input).toBeGreaterThan(0);
|
||||
}
|
||||
});
|
||||
|
||||
// Shapes claude 2.1.263 printed in the mock-API replay when the producer's agent ran an Agent subagent in the background.
|
||||
const subagent = (id: string, input: number) => ({ type: 'assistant', parent_tool_use_id: 'toolu_agent', message: { id, model: 'claude-test', content: [{ type: 'text', text: 'subagent note' }], usage: { input_tokens: input, output_tokens: 1, cache_read_input_tokens: 7 } } });
|
||||
const sessionUsage = { 'claude-test': { inputTokens: 153009, outputTokens: 15308, cacheReadInputTokens: 49, cacheCreationInputTokens: 0, costUSD: 2.3 } };
|
||||
|
||||
test('counts subagent usage: the session modelUsage, every result turn, and the main thread text', () => {
|
||||
const state = claudeStreamState();
|
||||
for (const line of lines(start('a', 1000), delta(100), stop, subagent('s1', 50000), subagent('s1', 50000), subagent('s2', 50001),
|
||||
result({ result: 'MAIN ENDED TURN', modelUsage: sessionUsage }), start('b', 1002), delta(102), stop,
|
||||
result({ num_turns: 1, result: 'REPORT', usage: { input_tokens: 1002, output_tokens: 102, cache_read_input_tokens: 7 }, modelUsage: sessionUsage }))) consumeClaudeStreamLine(state, line);
|
||||
expect(resultFromClaudeStream(state, { model: 'claude-test', durationMs: 5 })).toEqual({ output: 'REPORT', tokens: { input: 153009, output: 15308, cached: 49 }, durationMs: 5, toolCalls: 3, toolTimeline: [], modelUsed: 'claude-test' });
|
||||
});
|
||||
|
||||
test('records a content-free tool timeline: main and subagent calls once each, never their inputs', () => {
|
||||
const toolStart = (id: string, name: string) => ({ type: 'stream_event', parent_tool_use_id: null, event: { type: 'content_block_start', index: 1, content_block: { type: 'tool_use', id, name, input: {} } } });
|
||||
const mainCall = { type: 'assistant', message: { id: 'a', content: [{ type: 'tool_use', id: 'toolu_bash', name: 'Bash', input: { command: 'gstack-cso inspect SECRET_PATH' } }] } };
|
||||
const subCall = { type: 'assistant', parent_tool_use_id: 'toolu_agent', message: { id: 's1', content: [{ type: 'tool_use', id: 'toolu_sub', name: 'Bash', input: { command: 'cat SECRET_PATH' } }], usage: { input_tokens: 1, output_tokens: 1 } } };
|
||||
const state = claudeStreamState();
|
||||
for (const line of lines(start('a', 10), toolStart('toolu_bash', 'Bash'), toolStart('toolu_agent', 'Agent'), mainCall, subCall, subCall, toolStart('toolu_odd', 'mcp__x/../y'))) consumeClaudeStreamLine(state, line);
|
||||
const timeline = resultFromClaudeStream(state, { model: 'claude-test', durationMs: 5, error: { code: 'timeout', reason: 'exceeded 5ms' } }).toolTimeline!;
|
||||
expect(timeline.map(({ tool, agent }) => [tool, agent])).toEqual([['Bash', 'main'], ['Agent', 'main'], ['Bash', 'subagent'], ['other', 'main']]);
|
||||
expect(timeline.every(entry => Number.isSafeInteger(entry.atMs) && entry.atMs >= 0 && Object.keys(entry).length === 3)).toBe(true);
|
||||
expect(JSON.stringify(timeline)).not.toContain('SECRET_PATH');
|
||||
});
|
||||
|
||||
test('stamps a tool call end once from its tool_result and keeps the timeline and its id index at the cap', () => {
|
||||
const state = claudeStreamState();
|
||||
const toolResult = (id: string) => ({ type: 'user', message: { content: [{ type: 'tool_result', tool_use_id: id, content: 'SECRET_OUTPUT' }] } });
|
||||
const call = (id: string) => ({ type: 'assistant', message: { id: `m${id}`, content: [{ type: 'tool_use', id, name: 'Bash', input: {} }] } });
|
||||
for (const line of lines(call('t0'), toolResult('t0'), toolResult('t0'), toolResult('unknown'), call('t1'))) consumeClaudeStreamLine(state, line);
|
||||
expect(state.toolTimeline.map(entry => entry.endMs === undefined)).toEqual([false, true]);
|
||||
expect(JSON.stringify(state.toolTimeline)).not.toContain('SECRET_OUTPUT');
|
||||
for (let i = 2; i < 5000; i++) consumeClaudeStreamLine(state, JSON.stringify(call(`t${i}`)));
|
||||
expect(state.toolTimeline).toHaveLength(4096);
|
||||
expect(state.toolUseIndex.size).toBe(4096);
|
||||
});
|
||||
|
||||
test('a killed run counts each subagent message once and never reports subagent text as the producer output', () => {
|
||||
const state = claudeStreamState();
|
||||
for (const line of lines(start('a', 1000), text('a', 'main note'), delta(100), stop, subagent('s1', 50000), subagent('s1', 50000), subagent('s2', 50001))) consumeClaudeStreamLine(state, line);
|
||||
expect(resultFromClaudeStream(state, { model: 'claude-test', durationMs: 5, error: { code: 'timeout', reason: 'exceeded 5ms' } })).toMatchObject({ output: 'main note', tokens: { input: 101001, output: 102, cached: 21 }, toolCalls: 1 });
|
||||
});
|
||||
|
||||
test.skipIf(process.platform === 'win32')('a timed-out run returns the usage and last text it streamed before the kill', async () => {
|
||||
const { script, directory } = stub(`${printf([start('a', 1000), text('a', 'investigating'), delta(100), stop, start('b', 1001), delta(9)])}\nsleep 30`);
|
||||
const began = Date.now();
|
||||
const outcome = await runClaudeProducerStream(script, ['-p'], { input: 'go', cwd: directory, env: { PATH: '/usr/bin:/bin' }, timeoutMs: 1500, model: 'claude-test' });
|
||||
expect(Date.now() - began).toBeLessThan(10_000);
|
||||
expect(outcome).toMatchObject({ output: 'investigating', tokens: { input: 2001, output: 109, cached: 14 }, toolCalls: 2, error: { code: 'timeout', reason: 'exceeded 1500ms' } });
|
||||
});
|
||||
|
||||
test.skipIf(process.platform === 'win32')('keeps the failed-command reason shape and the stream usage on a nonzero exit', async () => {
|
||||
const { script, directory } = stub(`${printf([result({ is_error: true, result: 'Invalid API key', usage: { input_tokens: 0, output_tokens: 0 } })])}\nexit 1`);
|
||||
const outcome = await runClaudeProducerStream(script, ['-p', '--model', 'm'], { input: 'go', cwd: directory, env: { PATH: '/usr/bin:/bin' }, timeoutMs: 5000, model: 'claude-test' });
|
||||
expect(outcome.error?.code).toBe('unknown');
|
||||
expect(outcome.error?.reason.startsWith(`Command failed: ${script} -p --model m`)).toBe(true);
|
||||
expect(outcome.tokens).toEqual({ input: 0, output: 0, cached: 0 });
|
||||
});
|
||||
|
||||
test.skipIf(process.platform === 'win32')('a clean exit with a final result succeeds', async () => {
|
||||
const { script, directory } = stub(printf([start('a', 10), delta(2), stop, result({})]));
|
||||
const outcome = await runClaudeProducerStream(script, [], { input: 'go', cwd: directory, env: { PATH: '/usr/bin:/bin' }, timeoutMs: 5000, model: 'claude-test' });
|
||||
expect(outcome).toMatchObject({ output: 'REPORT', tokens: { input: 2001, output: 201, cached: 14 }, toolCalls: 2 });
|
||||
expect(outcome.error).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -128,10 +128,10 @@ describe('per-case host metadata', () => {
|
||||
for (const id of Object.keys(E2E_HOSTS)) expect(Object.hasOwn(E2E_TOUCHFILES, id), id).toBe(true);
|
||||
});
|
||||
|
||||
test('classifies 52 adapter-only, 27 Claude-specific, 26 rework and 1 host-neutral case', () => {
|
||||
test('classifies 51 adapter-only, 27 Claude-specific, 26 rework and 1 host-neutral case', () => {
|
||||
const counts: Record<string, number> = {};
|
||||
for (const support of Object.values(E2E_HOSTS)) counts[support] = (counts[support] ?? 0) + 1;
|
||||
expect(counts.both).toBe(52);
|
||||
expect(counts.both).toBe(51);
|
||||
expect(counts.rework).toBe(26);
|
||||
expect(counts['host-neutral']).toBe(1);
|
||||
expect(['pty', 'sdk', 'subagents', 'skill-tool', 'hermetic', 'self-host'].reduce((sum, reason) => sum + (counts[reason] ?? 0), 0)).toBe(27);
|
||||
|
||||
@@ -1,75 +0,0 @@
|
||||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import { cpSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join, resolve } from 'node:path';
|
||||
import committedCatalog from '../lib/cso/runtime-catalog.json';
|
||||
import buildInputs from '../lib/cso/images/build-inputs.json';
|
||||
import { ISOLATION_POLICY_HASH } from '../lib/cso/docker';
|
||||
import { selectRuntime, validateRuntimeCatalog, type RuntimeCatalog } from '../lib/cso/runtime-catalog';
|
||||
import { imageSourceFiles, requalificationTriggers, staleRequalificationTriggers } from '../scripts/cso-requalification';
|
||||
import { catalogPromotionCandidate } from '../scripts/cso-runtime-promotion';
|
||||
import { completeRuntimeCatalogFixture } from './helpers/cso-runtime-catalog';
|
||||
|
||||
const ROOT = resolve(import.meta.dir, '..');
|
||||
const temps: string[] = [];
|
||||
afterEach(() => { for (const dir of temps.splice(0)) rmSync(dir, { recursive: true, force: true }); });
|
||||
const current = await requalificationTriggers();
|
||||
|
||||
describe('CSO runtime requalification triggers', () => {
|
||||
test('the committed catalog is not older than its trigger inputs', () => {
|
||||
expect(staleRequalificationTriggers(committedCatalog as unknown as RuntimeCatalog, current)).toEqual([]);
|
||||
const cli = spawnSync(process.execPath, ['scripts/cso-requalification.ts', 'check', 'lib/cso/runtime-catalog.json'], { cwd: ROOT, encoding: 'utf8', timeout: 30_000 });
|
||||
expect(cli.status, cli.stderr).toBe(0); expect(cli.stdout).toBe('REQUALIFICATION CURRENT\n');
|
||||
});
|
||||
|
||||
test.skipIf(process.platform==='win32')('triggers cover the helper ABI, isolation policy, every image-embedded source byte, and the build inputs', async () => {
|
||||
expect(current).toMatchObject({ helperAbi: 3, isolationPolicyHash: ISOLATION_POLICY_HASH, buildInputsRevision: buildInputs.revision });
|
||||
const files = await imageSourceFiles();
|
||||
for (const file of ['lib/cso/verifier.ts', 'lib/cso/preparation-container.ts', 'lib/cso/contracts.ts', 'lib/cso/images/entrypoint', 'lib/cso/images/rails.Dockerfile']) expect(files).toContain(file);
|
||||
for (const file of ['lib/cso/images/README.md', 'lib/cso/images/qualification.json', 'lib/cso/images/build-inputs.json', 'lib/cso/cli.ts']) expect(files).not.toContain(file);
|
||||
const copy = mkdtempSync(join(tmpdir(), 'cso-requalification-')); temps.push(copy);
|
||||
cpSync(join(ROOT, 'lib'), join(copy, 'lib'), { recursive: true });
|
||||
expect(await requalificationTriggers(copy)).toEqual(current);
|
||||
writeFileSync(join(copy, 'lib/cso/verifier.ts'), '\n', { flag: 'a' });
|
||||
expect((await requalificationTriggers(copy)).preparationSha256).not.toBe(current.preparationSha256);
|
||||
});
|
||||
|
||||
test.skipIf(process.platform==='win32')('triggers resolve against the repository root from any working directory', async () => {
|
||||
const elsewhere = mkdtempSync(join(tmpdir(), 'cso-requalification-cwd-')); temps.push(elsewhere);
|
||||
const nested = join(elsewhere, 'a', 'b', 'c'); mkdirSync(nested, { recursive: true });
|
||||
const cli = spawnSync(process.execPath, [join(ROOT, 'scripts/cso-requalification.ts'), 'triggers'], { cwd: nested, encoding: 'utf8', timeout: 30_000 });
|
||||
expect(cli.status, cli.stderr).toBe(0); expect(JSON.parse(cli.stdout)).toEqual(current);
|
||||
const copy = join(elsewhere, 'deeper', 'checkout'); mkdirSync(copy, { recursive: true });
|
||||
cpSync(join(ROOT, 'lib'), join(copy, 'lib'), { recursive: true });
|
||||
expect(await requalificationTriggers(copy)).toEqual(current);
|
||||
expect(await imageSourceFiles(copy)).toEqual(await imageSourceFiles());
|
||||
});
|
||||
|
||||
test('a promoted catalog names each trigger that changed after qualification', () => {
|
||||
const catalog = completeRuntimeCatalogFixture();
|
||||
const recorded = catalog.promotion!.requalification;
|
||||
expect(staleRequalificationTriggers(catalog, { ...recorded })).toEqual([]);
|
||||
expect(staleRequalificationTriggers(catalog, { ...recorded, preparationSha256: 'd'.repeat(64), buildInputsRevision: 'next-inputs' })).toEqual(['buildInputsRevision', 'preparationSha256']);
|
||||
const withdrawn = { ...catalog, runtimes: [], promotion: undefined };
|
||||
expect(staleRequalificationTriggers(withdrawn, { ...recorded, preparationSha256: 'd'.repeat(64) })).toEqual([]);
|
||||
});
|
||||
|
||||
test('promoted catalogs must record valid triggers, and the helper refuses runtimes qualified under another isolation policy', () => {
|
||||
const catalog = completeRuntimeCatalogFixture();
|
||||
validateRuntimeCatalog(catalog);
|
||||
expect(selectRuntime('node', 'linux/amd64', catalog).stack).toBe('node');
|
||||
const missing = structuredClone(catalog) as any; delete missing.promotion.requalification;
|
||||
expect(() => validateRuntimeCatalog(missing)).toThrow('INVALID_RUNTIME_PROMOTION');
|
||||
const otherBuild = structuredClone(catalog); otherBuild.promotion!.requalification.buildInputsRevision = 'other-build';
|
||||
expect(() => validateRuntimeCatalog(otherBuild)).toThrow('INVALID_RUNTIME_PROMOTION');
|
||||
const otherPolicy = structuredClone(catalog); otherPolicy.promotion!.requalification.isolationPolicyHash = 'e'.repeat(64);
|
||||
expect(() => selectRuntime('node', 'linux/amd64', otherPolicy)).toThrow('STALE_RUNTIME_QUALIFICATION');
|
||||
});
|
||||
|
||||
test('promotion records the staged triggers and refuses ones measured under another isolation policy', () => {
|
||||
expect(() => catalogPromotionCandidate(committedCatalog, buildInputs, [], { ...current, isolationPolicyHash: 'e'.repeat(64) })).toThrow('STALE_RUNTIME_QUALIFICATION');
|
||||
expect(() => catalogPromotionCandidate(committedCatalog, buildInputs, [], { ...current, buildInputsRevision: 'other' })).toThrow('INVALID_REQUALIFICATION_TRIGGERS');
|
||||
expect(() => catalogPromotionCandidate(committedCatalog, buildInputs, [], { ...current, extra: true } as any)).toThrow('INVALID_REQUALIFICATION_TRIGGERS');
|
||||
});
|
||||
});
|
||||
@@ -10,7 +10,6 @@ afterAll(cleanupSeed);
|
||||
const stubBun = (f: ReturnType<typeof makeFixture>) => put(join(f.commands, 'bun'), `#!/usr/bin/env bash
|
||||
case "$*" in
|
||||
install|'install --production --frozen-lockfile') exit 0 ;;
|
||||
'build --help') echo 'Fixture Bun has no CSO compile flags'; exit 0 ;;
|
||||
'run build') echo 'Unexpected build in a dev-setup fixture' >&2; exit 90 ;;
|
||||
*) exec '${process.execPath}' "$@" ;;
|
||||
esac
|
||||
|
||||
@@ -83,6 +83,5 @@ describe('doctor component table', () => {
|
||||
expect(SKILL_REQUIREMENTS.autoplan.optional).toContain('codex-cli');
|
||||
expect(SKILL_REQUIREMENTS.browse.requires).toContain('browser');
|
||||
expect(SKILL_REQUIREMENTS.codex.requires).toContain('codex-cli');
|
||||
expect(SKILL_REQUIREMENTS.cso.requires).toContain('cso');
|
||||
});
|
||||
});
|
||||
@@ -142,7 +142,7 @@ test('live periodic census fits the declared CI wall including setup', () => {
|
||||
|
||||
test('registered allocation is deterministic and preserves every discovered file', () => {
|
||||
const files = collectPaidTestFiles();
|
||||
expect(files).toHaveLength(107); // - skill-e2e-failure-routing (router bug-fix route removed, GST-2873); - skill-e2e-investigate-owned-completion, -owned-termination and codex-e2e-sol-scope (/investigate retired, GST-1717); - skill-e2e-plan-eng-plan-mode, -plan-eng-finding-floor and -plan-eng-artifact-full (standalone /plan-eng-review retired, GST-1698); - skill-llm-eval (last standalone judges removed, GST-1403); + skill-e2e-autoplan-ceo-only (GST-537); + skill-e2e-planning-wave (GSTA-228); + skill-e2e-model-panel (GSTA-173); + skill-e2e-write-skill (GSTA-133); + skill-e2e-ship-frozen-scope (frozen review scope, GSTA-113 PR 2); + skill-e2e-failure-routing (#3157/#3158); + skill-e2e-dx-error-contract (#3226); + skill-e2e-gate-integrity (HONEST_WORK_GATE_INTEGRITY W8); + skill-e2e-autoplan-schema-canary, -guard-pty and -long-session (Oct 7 wave, CEO-13, ENG-18, CEO-15); + skill-e2e-ship-measure-seeded-flake (v1.91.32.0); W5a: 15 carve wrappers became one case-sharded file; + codex-e2e-multiblock-live and skill-e2e-design-model-smoke (v1.91.30.0);
|
||||
expect(files).toHaveLength(106); // - skill-e2e-cso (/cso removed, GST-3920); - skill-e2e-failure-routing (router bug-fix route removed, GST-2873); - skill-e2e-investigate-owned-completion, -owned-termination and codex-e2e-sol-scope (/investigate retired, GST-1717); - skill-e2e-plan-eng-plan-mode, -plan-eng-finding-floor and -plan-eng-artifact-full (standalone /plan-eng-review retired, GST-1698); - skill-llm-eval (last standalone judges removed, GST-1403); + skill-e2e-autoplan-ceo-only (GST-537); + skill-e2e-planning-wave (GSTA-228); + skill-e2e-model-panel (GSTA-173); + skill-e2e-write-skill (GSTA-133); + skill-e2e-ship-frozen-scope (frozen review scope, GSTA-113 PR 2); + skill-e2e-failure-routing (#3157/#3158); + skill-e2e-dx-error-contract (#3226); + skill-e2e-gate-integrity (HONEST_WORK_GATE_INTEGRITY W8); + skill-e2e-autoplan-schema-canary, -guard-pty and -long-session (Oct 7 wave, CEO-13, ENG-18, CEO-15); + skill-e2e-ship-measure-seeded-flake (v1.91.32.0); W5a: 15 carve wrappers became one case-sharded file; + codex-e2e-multiblock-live and skill-e2e-design-model-smoke (v1.91.30.0);
|
||||
expect(files).toContain('test/skill-e2e-ship-skip.test.ts');
|
||||
const m = livePlan(files);
|
||||
expect(livePlan([...files].reverse())).toEqual(m);
|
||||
|
||||
Vendored
-1
@@ -15,7 +15,6 @@
|
||||
"codex": 9437,
|
||||
"context-restore": 6305,
|
||||
"context-save": 5118,
|
||||
"cso": 4916,
|
||||
"design-consultation": 10513,
|
||||
"design-html": 8996,
|
||||
"design-motion": 4738,
|
||||
|
||||
-1
@@ -17,7 +17,6 @@
|
||||
"codex",
|
||||
"context-restore",
|
||||
"context-save",
|
||||
"cso",
|
||||
"design-consultation",
|
||||
"design-html",
|
||||
"design-motion",
|
||||
|
||||
+1
-1
@@ -22,7 +22,7 @@
|
||||
}
|
||||
},
|
||||
{
|
||||
"file": "test/skill-e2e-cso.test.ts",
|
||||
"file": "test/skill-e2e-retro.test.ts",
|
||||
"slice": 1,
|
||||
"status": "planned",
|
||||
"estimatedMs": 227394
|
||||
|
||||
-18
@@ -1,18 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<testsuites name="bun test" tests="3" assertions="0" failures="0" skipped="2" time="205.007532719">
|
||||
<testsuite name="test/skill-e2e-cso.test.ts" file="test/skill-e2e-cso.test.ts" tests="3" assertions="0" failures="0" skipped="2" time="205.005012252">
|
||||
<testsuite name="CSO v3 — full audit" file="test/skill-e2e-cso.test.ts" line="146" tests="1" assertions="0" failures="0" skipped="1" time="0">
|
||||
<testcase name="/cso persists supported tenant-boundary findings with redacted evidence" classname="CSO v3 — full audit" time="0" file="test/skill-e2e-cso.test.ts" line="105" assertions="0">
|
||||
<skipped />
|
||||
</testcase>
|
||||
</testsuite>
|
||||
<testsuite name="CSO v3 — infra scope" file="test/skill-e2e-cso.test.ts" line="146" tests="1" assertions="0" failures="0" skipped="1" time="0">
|
||||
<testcase name="/cso --infra finds an attacker-to-credential execution path" classname="CSO v3 — infra scope" time="0" file="test/skill-e2e-cso.test.ts" line="192" assertions="0">
|
||||
<skipped />
|
||||
</testcase>
|
||||
</testsuite>
|
||||
<testsuite name="CSO v3 — diff mode" file="test/skill-e2e-cso.test.ts" line="146" tests="1" assertions="0" failures="0" skipped="0" time="204.971">
|
||||
<testcase name="/cso --diff records its base and investigates changed security paths" classname="CSO v3 — diff mode" time="204.97188" file="test/skill-e2e-cso.test.ts" line="151" assertions="0" />
|
||||
</testsuite>
|
||||
</testsuite>
|
||||
</testsuites>
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<testsuites name="bun test" tests="2" assertions="0" failures="0" skipped="1" time="205.007532719">
|
||||
<testsuite name="test/skill-e2e-retro.test.ts" file="test/skill-e2e-retro.test.ts" tests="2" assertions="0" failures="0" skipped="1" time="205.005012252">
|
||||
<testsuite name="Base branch detection" file="test/skill-e2e-retro.test.ts" line="67" tests="1" assertions="0" failures="0" skipped="0" time="204.971">
|
||||
<testcase name="retro-base-branch" classname="Base branch detection" time="204.97188" file="test/skill-e2e-retro.test.ts" line="80" assertions="0" />
|
||||
</testsuite>
|
||||
<testsuite name="Retro E2E" file="test/skill-e2e-retro.test.ts" line="143" tests="1" assertions="0" failures="0" skipped="1" time="0">
|
||||
<testcase name="retro" classname="Retro E2E" time="0" file="test/skill-e2e-retro.test.ts" line="191" assertions="0">
|
||||
<skipped />
|
||||
</testcase>
|
||||
</testsuite>
|
||||
</testsuite>
|
||||
</testsuites>
|
||||
@@ -27,13 +27,13 @@
|
||||
},
|
||||
{
|
||||
"files": [
|
||||
"test/skill-e2e-cso.test.ts"
|
||||
"test/skill-e2e-retro.test.ts"
|
||||
],
|
||||
"status": "passed",
|
||||
"exitCode": 0,
|
||||
"elapsedMs": 205014,
|
||||
"executedTests": 3,
|
||||
"skippedTests": 2,
|
||||
"executedTests": 2,
|
||||
"skippedTests": 1,
|
||||
"budget": {
|
||||
"timeoutMs": 1800000,
|
||||
"source": "default",
|
||||
|
||||
+1
-1
@@ -35,7 +35,7 @@
|
||||
"estimatedMs": 247902
|
||||
},
|
||||
{
|
||||
"file": "test/skill-e2e-cso.test.ts",
|
||||
"file": "test/skill-e2e-shared-libs-periodic.test.ts",
|
||||
"slice": 1,
|
||||
"status": "planned",
|
||||
"estimatedMs": 253498
|
||||
|
||||
-16
@@ -1,16 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<testsuites name="bun test" tests="3" assertions="0" failures="0" skipped="1" time="293.147597765">
|
||||
<testsuite name="test/skill-e2e-cso.test.ts" file="test/skill-e2e-cso.test.ts" tests="3" assertions="0" failures="0" skipped="1" time="293.145365972">
|
||||
<testsuite name="CSO v3 — diff mode" file="test/skill-e2e-cso.test.ts" line="146" tests="1" assertions="0" failures="0" skipped="1" time="0">
|
||||
<testcase name="/cso --diff records its base and investigates changed security paths" classname="CSO v3 — diff mode" time="0" file="test/skill-e2e-cso.test.ts" line="151" assertions="0">
|
||||
<skipped />
|
||||
</testcase>
|
||||
</testsuite>
|
||||
<testsuite name="CSO v3 — infra scope" file="test/skill-e2e-cso.test.ts" line="146" tests="1" assertions="0" failures="0" skipped="0" time="242.558">
|
||||
<testcase name="/cso --infra finds an attacker-to-credential execution path" classname="CSO v3 — infra scope" time="242.558725" file="test/skill-e2e-cso.test.ts" line="192" assertions="0" />
|
||||
</testsuite>
|
||||
<testsuite name="CSO v3 — full audit" file="test/skill-e2e-cso.test.ts" line="146" tests="1" assertions="0" failures="0" skipped="0" time="293.11">
|
||||
<testcase name="/cso persists supported tenant-boundary findings with redacted evidence" classname="CSO v3 — full audit" time="293.110054" file="test/skill-e2e-cso.test.ts" line="105" assertions="0" />
|
||||
</testsuite>
|
||||
</testsuite>
|
||||
</testsuites>
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<testsuites name="bun test" tests="2" assertions="0" failures="0" skipped="0" time="293.147597765">
|
||||
<testsuite name="test/skill-e2e-shared-libs-periodic.test.ts" file="test/skill-e2e-shared-libs-periodic.test.ts" tests="2" assertions="0" failures="0" skipped="0" time="293.145365972">
|
||||
<testsuite name="/deslop-shared-libs periodic" file="test/skill-e2e-shared-libs-periodic.test.ts" line="70" tests="2" assertions="0" failures="0" skipped="0" time="293.11">
|
||||
<testcase name="shared-libs-pr-coverage" classname="/deslop-shared-libs periodic" time="242.558725" file="test/skill-e2e-shared-libs-periodic.test.ts" line="145" assertions="0" />
|
||||
<testcase name="shared-libs-plan-callers" classname="/deslop-shared-libs periodic" time="293.110054" file="test/skill-e2e-shared-libs-periodic.test.ts" line="169" assertions="0" />
|
||||
</testsuite>
|
||||
</testsuite>
|
||||
</testsuites>
|
||||
@@ -72,13 +72,13 @@
|
||||
},
|
||||
{
|
||||
"files": [
|
||||
"test/skill-e2e-cso.test.ts"
|
||||
"test/skill-e2e-shared-libs-periodic.test.ts"
|
||||
],
|
||||
"status": "passed",
|
||||
"exitCode": 0,
|
||||
"elapsedMs": 293156,
|
||||
"executedTests": 3,
|
||||
"skippedTests": 1,
|
||||
"executedTests": 2,
|
||||
"skippedTests": 0,
|
||||
"budget": {
|
||||
"timeoutMs": 1800000,
|
||||
"source": "default",
|
||||
|
||||
-2
@@ -43,8 +43,6 @@
|
||||
"lib/claude-code-migration.ts",
|
||||
"lib/code-intelligence/gbrain-adapter.ts",
|
||||
"lib/code-intelligence/graphify-adapter.ts",
|
||||
"lib/cso/preparation-container.ts",
|
||||
"lib/cso/windows-docker.ts",
|
||||
"lib/gbrain-guards.ts",
|
||||
"lib/gbrain-sources.ts",
|
||||
"lib/harness-register.ts",
|
||||
|
||||
+1
-10
@@ -24,14 +24,6 @@
|
||||
],
|
||||
"llmJudge": []
|
||||
},
|
||||
"lib/cso/state.ts": {
|
||||
"e2e": [
|
||||
"cso-diff-mode",
|
||||
"cso-full-audit",
|
||||
"cso-infra-scope"
|
||||
],
|
||||
"llmJudge": []
|
||||
},
|
||||
"bin/gstack-paths": {
|
||||
"e2e": [
|
||||
"plan-design-with-ui-scope"
|
||||
@@ -70,8 +62,7 @@
|
||||
},
|
||||
"modules": {
|
||||
"lib/state-root.ts": [
|
||||
"browse/src/config.ts",
|
||||
"lib/cso/state.ts"
|
||||
"browse/src/config.ts"
|
||||
],
|
||||
"bin/gstack-state-root.sh": [
|
||||
"bin/gstack-paths",
|
||||
|
||||
@@ -174,7 +174,7 @@ describe('free-tests workflow wiring', () => {
|
||||
expect(gate.env.TYPECHECK_RESULT).toBe('${{ needs.typecheck.result }}');
|
||||
expect(gate.run).toContain('test "$TYPECHECK_RESULT" = success');
|
||||
const typecheck = workflow.jobs.typecheck.steps.map((step: any) => step.run).filter(Boolean);
|
||||
expect(typecheck).toEqual(expect.arrayContaining(['bun run typecheck', 'bun run typecheck:test', 'bun run format:cso:check']));
|
||||
expect(typecheck).toEqual(expect.arrayContaining(['bun run typecheck', 'bun run typecheck:test']));
|
||||
expect(source).not.toContain('--quick');
|
||||
});
|
||||
|
||||
|
||||
+12
-38
@@ -421,8 +421,7 @@ describe('gen-skill-docs', () => {
|
||||
});
|
||||
|
||||
test('tier 2+ skills contain ELI10 simplification rules (AskUserQuestion format)', () => {
|
||||
// Root SKILL.md is tier 1 and CSO intentionally uses a private startup with
|
||||
// no shared PREAMBLE. Check a regular tier 2+ PREAMBLE consumer instead.
|
||||
// Root SKILL.md is tier 1. Check a regular tier 2+ PREAMBLE consumer instead.
|
||||
// v1.7.0.0 Pros/Cons format uses "ELI10 (ALWAYS)" rather than "Simplify (ELI10".
|
||||
const content = readSkillStartup(path.join(ROOT, 'review', 'SKILL.md'));
|
||||
expect(content).toContain('ELI10');
|
||||
@@ -4399,8 +4398,6 @@ describe('LEARNINGS_LOG resolver', () => {
|
||||
});
|
||||
|
||||
describe('CONFIDENCE_CALIBRATION resolver', () => {
|
||||
// CSO owns a distinct evidence rubric; the shared numerical confidence
|
||||
// resolver would conflict with that contract and its private startup.
|
||||
const CONFIDENCE_SKILLS = ['review', 'ship', 'plan-eng-review'];
|
||||
|
||||
for (const skill of CONFIDENCE_SKILLS) {
|
||||
@@ -4506,9 +4503,9 @@ describe('voice-triggers processing', () => {
|
||||
};
|
||||
|
||||
test('extractVoiceTriggers parses valid YAML list', () => {
|
||||
const content = `---\nname: cso\ndescription: |\n Security audit.\nvoice-triggers:\n - "see-so"\n - "security review"\n---\nBody`;
|
||||
const content = `---\nname: qa\ndescription: |\n QA testing.\nvoice-triggers:\n - "quality check"\n - "run QA"\n---\nBody`;
|
||||
const triggers = extractVoiceTriggers(content);
|
||||
expect(triggers).toEqual(['see-so', 'security review']);
|
||||
expect(triggers).toEqual(['quality check', 'run QA']);
|
||||
});
|
||||
|
||||
test('extractVoiceTriggers returns [] when no field present', () => {
|
||||
@@ -4517,13 +4514,13 @@ describe('voice-triggers processing', () => {
|
||||
});
|
||||
|
||||
test('processVoiceTriggers appends voice triggers to description', () => {
|
||||
const content = `---\nname: cso\ndescription: |\n Security audit. (gstack)\nvoice-triggers:\n - "see-so"\n - "security review"\n---\nBody`;
|
||||
const content = `---\nname: qa\ndescription: |\n QA testing. (gstack)\nvoice-triggers:\n - "quality check"\n - "run QA"\n---\nBody`;
|
||||
const result = processVoiceTriggers(content);
|
||||
expect(result).toContain('Voice triggers (speech-to-text aliases): "see-so", "security review".');
|
||||
expect(result).toContain('Voice triggers (speech-to-text aliases): "quality check", "run QA".');
|
||||
});
|
||||
|
||||
test('processVoiceTriggers strips voice-triggers field from output', () => {
|
||||
const content = `---\nname: cso\ndescription: |\n Security audit. (gstack)\nvoice-triggers:\n - "see-so"\n---\nBody`;
|
||||
const content = `---\nname: qa\ndescription: |\n QA testing. (gstack)\nvoice-triggers:\n - "quality check"\n---\nBody`;
|
||||
const result = processVoiceTriggers(content);
|
||||
expect(result).not.toContain('voice-triggers:');
|
||||
});
|
||||
@@ -4533,11 +4530,11 @@ describe('voice-triggers processing', () => {
|
||||
expect(processVoiceTriggers(content)).toBe(content);
|
||||
});
|
||||
|
||||
test('CSO voice triggers fold into the full description', () => {
|
||||
// The Claude catalog trim drops this line from cso/SKILL.md; full-mode and
|
||||
test('QA voice triggers fold into the full description', () => {
|
||||
// The Claude catalog trim drops this line from qa/SKILL.md; full-mode and
|
||||
// other-host renders still carry it.
|
||||
const content = processVoiceTriggers(fs.readFileSync(path.join(ROOT, 'cso', 'SKILL.md.tmpl'), 'utf-8'));
|
||||
expect(content).toContain('"see-so"');
|
||||
const content = processVoiceTriggers(fs.readFileSync(path.join(ROOT, 'qa', 'SKILL.md.tmpl'), 'utf-8'));
|
||||
expect(content).toContain('"run QA"');
|
||||
expect(content).toContain('Voice triggers (speech-to-text aliases):');
|
||||
});
|
||||
|
||||
@@ -4556,36 +4553,13 @@ describe('voice-triggers processing', () => {
|
||||
expect(routed).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
test('generated CSO SKILL.md does NOT contain raw voice-triggers field', () => {
|
||||
const content = fs.readFileSync(path.join(ROOT, 'cso', 'SKILL.md'), 'utf-8');
|
||||
test('generated QA SKILL.md does NOT contain raw voice-triggers field', () => {
|
||||
const content = fs.readFileSync(path.join(ROOT, 'qa', 'SKILL.md'), 'utf-8');
|
||||
const fmEnd = content.indexOf('\n---', 4);
|
||||
const frontmatter = content.slice(0, fmEnd);
|
||||
expect(frontmatter).not.toContain('voice-triggers:');
|
||||
});
|
||||
|
||||
test('generated Claude CSO skill preauthorizes only the trusted launcher', () => {
|
||||
const expected = [
|
||||
'Bash(~/.claude/skills/gstack/bin/gstack-cso-launcher *)',
|
||||
'Bash(~/.claude/skills/gstack/bin/gstack-cso-launcher.exe *)',
|
||||
];
|
||||
for (const file of ['cso/SKILL.md.tmpl', 'cso/SKILL.md']) {
|
||||
const content = fs.readFileSync(path.join(ROOT, file), 'utf-8');
|
||||
const fmEnd = content.indexOf('\n---', 4);
|
||||
const frontmatter = Bun.YAML.parse(content.slice(4, fmEnd)) as Record<string, unknown>;
|
||||
expect(frontmatter['allowed-tools'], file).toEqual(expected);
|
||||
}
|
||||
});
|
||||
|
||||
test('generated CSO host variants retain challenge fallback and host-containment disclosure', () => {
|
||||
const claude = fs.readFileSync(path.join(ROOT, 'cso', 'SKILL.md'), 'utf-8');
|
||||
const codex = fs.readFileSync(path.join(EXTERNAL_OUT, '.agents', 'skills', 'gstack-cso', 'SKILL.md'), 'utf-8');
|
||||
for (const content of [claude, codex]) {
|
||||
expect(content).toContain('sequential challenge; independent agent unavailable');
|
||||
expectMentions(content, [['does not','containment','sandbox']], 'content');
|
||||
expectMentions(content, [['do not','independent','reviewer']], 'content');
|
||||
}
|
||||
});
|
||||
|
||||
// Gen-time-only keys: interactive + benefits-from are read from the .tmpl by
|
||||
// buildContext; the generated copy has no reader (the host reads name/
|
||||
// description/allowed-tools/hooks; gbrain: is runtime-read and NOT stripped).
|
||||
|
||||
@@ -4,8 +4,8 @@
|
||||
* Git for Windows checks out with core.autocrlf=true. A tracked script with no
|
||||
* `eol` rule is written with CRLF there, and a Linux bash reading that
|
||||
* checkout (a synced tree, WSL, a bind mount) fails on `set -o pipefail\r`.
|
||||
* `bin/*` is anchored at the root, so nested bin/ dirs, the hook shims, the
|
||||
* CSO image scripts and the app launcher had no rule. This pins the rules for
|
||||
* `bin/*` is anchored at the root, so nested bin/ dirs, the hook shims and
|
||||
* the app launcher had no rule. This pins the rules for
|
||||
* every tracked file that starts with `#!`, and keeps the broad patterns from
|
||||
* marking a binary file as text.
|
||||
*/
|
||||
@@ -58,7 +58,6 @@ describe('.gitattributes eol rules (#3110)', () => {
|
||||
'plan-ceo-review/bin/mode-handoff-hook',
|
||||
'hosts/claude/hooks/timeline-stop-hook',
|
||||
'browse/bin/remote-slug',
|
||||
'lib/cso/images/entrypoint',
|
||||
'scripts/app/gstack-browser',
|
||||
'browse/test/fixtures/mock-claude/claude',
|
||||
];
|
||||
|
||||
@@ -52,7 +52,6 @@ describe('gstack-doctor --check', () => {
|
||||
expect(r.rows.patch.status).toBe('PASS');
|
||||
expect(r.rows['codex-cli'].status).toBe('PASS');
|
||||
expect(r.rows.browser).toEqual({ status: 'SKIP', rest: '(lazy; gstack-browser-ensure installs on first use)' });
|
||||
expect(r.rows.cso.status).toBe('SKIP');
|
||||
expect(r.trailer).toBe(`gstack: ok ${VERSION} for=installed-hosts:claude,codex`);
|
||||
expect(r.trailers).toBe(1);
|
||||
expect(r.rows.runtime.rest).toContain('floor 1.3.3, supported minimum 1.4.2');
|
||||
@@ -313,16 +312,6 @@ describe('gstack-doctor --check', () => {
|
||||
expect(row(f, ['--for', 'autoplan']).rows.browser.status).toBe('SKIP');
|
||||
});
|
||||
|
||||
test('cso: optional by default (SKIP, never silent), required by --for cso', () => {
|
||||
const f = makeFixture();
|
||||
expect(row(f, []).rows.cso).toEqual({ status: 'SKIP', rest: '(optional; toolchain absent or helper not built)' });
|
||||
const r = row(f, ['--for', 'cso']);
|
||||
expect(r.rows.cso.status).toBe('FAIL');
|
||||
expect(r.trailer).toBe('gstack: fail cso');
|
||||
for (const name of ['gstack-cso-launcher', 'gstack-cso-core']) write(path.join(f.root, 'bin', name + EXE), '#!/bin/sh\necho cso\n', 0o755);
|
||||
expect(row(f, ['--for', 'cso']).rows.cso.status).toBe('PASS');
|
||||
});
|
||||
|
||||
test('state root: GSTACK_EPHEMERAL=1 reports durable=no in --check (PASS) and warns in the dashboard', () => {
|
||||
const f = makeFixture();
|
||||
const r = row(f, [], { GSTACK_EPHEMERAL: '1' });
|
||||
@@ -349,7 +338,7 @@ describe('gstack-doctor --check', () => {
|
||||
expect(json.ok).toBe(false);
|
||||
expect(json.failed).toEqual(['runtime']);
|
||||
expect(json.required).toEqual(['claude', 'codex', 'patch', 'runtime', 'pins', 'state-root', 'privacy', 'cores', 'revision', 'floor', 'wrapper']);
|
||||
expect(json.rows.map((x: { id: string }) => x.id)).toEqual(['claude', 'codex', 'patch', 'codex-cli', 'browse-bundle', 'browser', 'cso', 'helpers', 'runtime', 'pins', 'state-root', 'privacy', 'cores', 'revision', 'floor', 'wrapper']);
|
||||
expect(json.rows.map((x: { id: string }) => x.id)).toEqual(['claude', 'codex', 'patch', 'codex-cli', 'browse-bundle', 'browser', 'helpers', 'runtime', 'pins', 'state-root', 'privacy', 'cores', 'revision', 'floor', 'wrapper']);
|
||||
const runtime = json.rows.find((x: { id: string }) => x.id === 'runtime');
|
||||
expect(runtime.status).toBe('FAIL');
|
||||
expect(runtime.code).toBe('RUNTIME_BELOW_MINIMUM');
|
||||
|
||||
@@ -1,19 +1,17 @@
|
||||
// Split from test/gstack-doctor.test.ts: launch/CSO rows, launch Bun, wrapper drift, rescue refs and Windows bash.
|
||||
// Split from test/gstack-doctor.test.ts: launch rows, launch Bun, wrapper drift, rescue refs and Windows bash.
|
||||
import { describe, expect, test } from 'bun:test';
|
||||
import { spawnSync } from 'child_process';
|
||||
import * as fs from 'fs';
|
||||
import * as path from 'path';
|
||||
import { useDoctorCleanup, REPO, BROWSE_BIN, EXE, OTHER_BINS, write, script, bashPath, makeFixture, doctor, type Fixture } from './helpers/doctor-fixture';
|
||||
import { useDoctorCleanup, REPO, BROWSE_BIN, OTHER_BINS, write, script, bashPath, makeFixture, doctor, type Fixture } from './helpers/doctor-fixture';
|
||||
|
||||
useDoctorCleanup();
|
||||
|
||||
// #2595/#2124 and #3071: compiled binaries by launch state, and CSO from the
|
||||
// build-result record. A blocked binary is simulated by the application-control
|
||||
// message reporters captured (#2595), which works on every OS.
|
||||
describe('gstack-doctor launch and CSO rows', () => {
|
||||
// #2595/#2124: compiled binaries by launch state. A blocked binary is simulated
|
||||
// by the application-control message reporters captured (#2595), which works
|
||||
// on every OS.
|
||||
describe('gstack-doctor launch rows', () => {
|
||||
const BLOCKED = `#!/bin/sh\necho "Program 'x.exe' failed to run: An Application Control policy has blocked this file" >&2\nexit 1\n`;
|
||||
const record = (f: Fixture, text: string) => write(path.join(f.root, 'bin/.gstack-cso-build-result'), text);
|
||||
const cso = (f: Fixture) => { for (const name of ['gstack-cso-launcher', 'gstack-cso-core']) write(path.join(f.root, 'bin', name + EXE), '#!/bin/sh\necho cso\n', 0o755); };
|
||||
|
||||
test('healthy binaries are ok; a blocked browse says blocked, not "not built"', () => {
|
||||
const f = makeFixture();
|
||||
@@ -45,25 +43,6 @@ describe('gstack-doctor launch and CSO rows', () => {
|
||||
expect(r.row('binaries').detail).toBe('not built: pdf');
|
||||
});
|
||||
|
||||
test('the CSO row reads the build-result record', () => {
|
||||
const f = makeFixture();
|
||||
const none = doctor(f).row('cso');
|
||||
expect(none.state).toBe('not configured');
|
||||
expect(none.detail).toBe('native helper not built; /cso reports not assessed');
|
||||
expect(none.fix).toContain('./setup (it names any missing build prerequisite)');
|
||||
record(f, 'result=failed\nstage=build\nreason=exit 42\nrevision=1.2 (abc)\ninstalled=\nlauncher=no\ndiagnostic=/x/cso.log\n');
|
||||
let r = doctor(f);
|
||||
expect(r.row('cso').state).toBe('warn');
|
||||
expect(r.row('cso').detail).toBe('unavailable: the build step failed (exit 42); /cso reports not assessed');
|
||||
expect(r.row('cso').fix).toContain('bun run build:cso && ./setup (log: /x/cso.log;');
|
||||
cso(f);
|
||||
record(f, 'result=failed\nstage=publish\nreason=exit 1\nrevision=1.2 (abc)\ninstalled=1.1 (def)\nlauncher=yes\ndiagnostic=/x/cso.log\n');
|
||||
expect(doctor(f).row('cso').detail).toBe('publish step failed (exit 1) for 1.2 (abc); previous CSO kept: 1.1 (def)');
|
||||
record(f, 'result=ok\nstage=publish\nreason=committed\nrevision=1.2 (abc)\ninstalled=1.2 (abc)\nlauncher=yes\ndiagnostic=x\n');
|
||||
r = doctor(f);
|
||||
expect(r.row('cso')).toEqual({ state: 'ok', detail: 'native helper 1.2 (abc)', fix: '' });
|
||||
expect(r.status).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
// Field wave lane A: the trailer agrees with the Bun workflows run (A3), a
|
||||
|
||||
@@ -144,13 +144,13 @@ describe('gstack-harness register and unregister (skill folders)', () => {
|
||||
test('a skill turned off with disabled_skills is left out of the harness payload (#4548)', () => {
|
||||
const d = tmp();
|
||||
fs.mkdirSync(path.join(d, 'state'), { recursive: true });
|
||||
fs.writeFileSync(path.join(d, 'state', 'config.yaml'), 'disabled_skills: ship,/cso,gstack-qa\n');
|
||||
fs.writeFileSync(path.join(d, 'state', 'config.yaml'), 'disabled_skills: ship,/retro,gstack-qa\n');
|
||||
const r = register(opts(d, 'dots', { mode: 'all', skillsDir: path.join(d, 'all') }));
|
||||
for (const off of ['ship', 'cso', 'qa']) expect(fs.existsSync(path.join(r.dest, off))).toBe(false);
|
||||
for (const off of ['ship', 'retro', 'qa']) expect(fs.existsSync(path.join(r.dest, off))).toBe(false);
|
||||
expect(fs.existsSync(path.join(r.dest, 'review', 'SKILL.md'))).toBe(true);
|
||||
const names = sourceSkills(TARGETS.dots, ROOT, d, { GSTACK_STATE_ROOT: path.join(d, 'state') }).map(s => s.name);
|
||||
expect(names).toContain('review');
|
||||
for (const off of ['ship', 'cso', 'qa']) expect(names).not.toContain(off);
|
||||
for (const off of ['ship', 'retro', 'qa']) expect(names).not.toContain(off);
|
||||
}, 60_000);
|
||||
|
||||
test('Claude-render targets (dots, generic) never register a retired skill; /autoplan still carries its methodology', () => {
|
||||
|
||||
@@ -33,9 +33,8 @@ export interface CarveStaticInvariants {
|
||||
mustStayInSkeleton: string[];
|
||||
/**
|
||||
* Substrings that MUST appear in the skeleton BEFORE the first STOP-Read
|
||||
* (earliest-use, codex #6). For cso: mode-dispatch directives (## Arguments,
|
||||
* ## Mode Resolution) must be resolved before any section is read — a dispatch
|
||||
* directive stranded after the STOP can't govern which sections to read.
|
||||
* (earliest-use, codex #6): a mode-dispatch directive stranded after the
|
||||
* STOP can't govern which sections to read.
|
||||
* Empty/undefined = skip (most skills).
|
||||
*/
|
||||
mustPrecedeStop?: string[];
|
||||
@@ -423,47 +422,6 @@ do not launch the downstream skill or open a browser.`,
|
||||
// subagent prompt (s02 H4a); measured 1.0911 (2026-10-02).
|
||||
maxSizeRatio: 1.1776, // GST-3654 (2026-11-24, Garry "Do it" on B1): /ship installs as /gstack-ship because Claude Code keeps the name ship for its own built-in (#4775), so each line that names it grows by 7 bytes; was 1.1774. Before that: GSTA-803 (2026-11-22, Captain GStack Minder ruling D1): user-reported fix #4366, the Aside probe reports a closed app; #3924 changes only the /codex skill; was 1.1763. Before that: GST-3157 (2026-11-19, Garry "Do it" on I1): Claude Code skills load the shared preamble and the start output at load time; was 1.1719. GST-2756 (2026-11-15, Garry's "Do it" to the ask-once and open-every-file habits): two Ground Rules lines (ask each question once and carry it as one waiting line; open every handed-over file and remove placeholders), +276 bytes; measured 1.1719 (before: 1.1688). Before that: GST-2753 (2026-11-15, Garry's "Do it" to moving the never-print-secrets rule into gstack): the shared Ground Rules preamble section (never print a whole environment, git config or process table; wait on CI with one gstack-pr-wait call), +614 bytes; measured 1.1688 (before: 1.1623). Before that: + v1.91.19.0 wave: design --version probe (B4), taste-profile load (F3), verdict-form outside voice (INV-1), plus v1.91.17.0's round accounting and board/approval blocks (#3022) merged in; measured 100,446 / 90,375 = 1.1114 (2026-10-03). + Oct 6 fix wave A3/CEO-12: free text reaches commands only through agent-written mktemp files (mktemp block, write rule, path rebuild and refusal at each posting, prompt and brief site); measured 103,384 / 90,375 = 1.1439 (2026-10-06). + Oct 7 wave B6: Aside rules 1, 4, 6 and 7 (offer a target-origin tab before openTab, a second sign-in wall means a tab- or URL-bound session, no early-return hint, fast [ok without the sentinel is an abort); measured 103,576 / 90,375 = 1.1461 (2026-10-07). + Oct 7 wave B3: the Codex probe runs as a command (select-model capture lines, check-sandbox/probe-model/run-with-timeout subcommands) instead of being sourced; measured 103,522 / 90,375 = 1.1455 (2026-10-07). Both merged: measured 103,726 / 90,375 = 1.1477 (2026-10-07). + Oct 7 wave guard (CEO-20): conditional `run_in_background` request plus the background-run recovery at each foreground dispatch site; measured 103,466 / 90,375 = 1.1449 (2026-10-07). Merged with the guard area: measured 103,804 / 90,375 = 1.1486 (2026-10-07). + Honest Work wave merged (W2/W3 gate integrity in review/ship, W4 kernel + DONE line in every tier-2+ skill, W5/W7 in spec/ship): re-measured on the integrated tree (2026-10-10). + GSTA-96 shared-preamble hoist (owner-approved raise, Garry 2026-10-25: "do it"): the union now holds sections/preamble.md, so a fresh invocation reads the pointer plus the shared file; measured 105,039 / 90,375 = 1.1623 (2026-10-25). Before: 1.16.
|
||||
},
|
||||
cso: {
|
||||
skill: 'cso',
|
||||
expectedSections: ['audit-phases.md'],
|
||||
requiredReads: ['audit-phases.md'],
|
||||
scenario:
|
||||
'Run a security audit on this repository in --owasp mode (OWASP Top 10 only). Resolve the mode, do the Phase 0 stack detection and Phase 1 attack-surface census, then run the scoped audit phases and produce the findings report. Skip any step that needs network access.',
|
||||
staticInvariants: {
|
||||
// Dispatch, trusted execution, evidence/proof, reporting and recovery stay always loaded.
|
||||
mustStayInSkeleton: [
|
||||
'## Arguments',
|
||||
'## Mode Resolution',
|
||||
'### Phase 0',
|
||||
'### Phase 1',
|
||||
'### Phase 12',
|
||||
'### Phase 13',
|
||||
'### Phase 14',
|
||||
'**Private startup.**',
|
||||
'CSO evidence rubric',
|
||||
'identical security assertion',
|
||||
],
|
||||
// Earliest-use: mode must be resolvable before any section is read (codex #6).
|
||||
mustPrecedeStop: ['## Arguments', '## Mode Resolution'],
|
||||
// Scope-dependent audit detail moved to the section.
|
||||
mustMoveToSection: [
|
||||
'### Phase 2: Secrets Archaeology',
|
||||
'### Phase 9: OWASP Top 10 Assessment',
|
||||
'### Phase 10: STRIDE Threat Model',
|
||||
],
|
||||
gateAfterStop: undefined,
|
||||
},
|
||||
// v3 requires a trusted helper and private state, absent from generic prompt fixtures.
|
||||
// The full-audit E2E asserts actual section loading alongside report/proof behavior.
|
||||
behavioral: 'external',
|
||||
externalTest: 'test/skill-e2e-cso.test.ts',
|
||||
maxSkeletonBytes: 18_900, // + Oct 10 multi-agent wave PR D2 (sideways review): Phase 12's root-cause-variants sentence becomes the sibling sweep (severity follows the worst sibling), two neighbouring phrases tightened to offset most of it; measured skeleton 18,044 (2026-10-10). + Oct 26 harness lane F (TRUT 5/6, FOUN 13): the environment-hygiene paragraph (set/unset checks only; no env, printenv, set -x, bare set/export, export $(...) in a fence) and the tooling-error paragraph (bounded retries, then not assessed with the command, exit code and stderr tail; never a quiet partial), both in the always-loaded startup block because they govern every helper call; measured skeleton 18,843 (2026-10-26).
|
||||
minUnionBytes: 30_000, // v3 deliberately removes the shared export/startup preamble.
|
||||
mustContain: ['OWASP', 'STRIDE', 'daily', 'comprehensive', 'verif'],
|
||||
// Existing baseline comparison remains an upper bound; absolute limits above
|
||||
// preserve the compact controller and its complete domain reference.
|
||||
maxSizeRatio: 1.08,
|
||||
},
|
||||
// ── Token-reduction Phase 4 wave 1 (v1.69.x branch) ──────────────────────
|
||||
review: {
|
||||
skill: 'review',
|
||||
|
||||
@@ -1,125 +0,0 @@
|
||||
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', 'test@example.invalid');
|
||||
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);
|
||||
}
|
||||
@@ -1,148 +0,0 @@
|
||||
import type { CsoStack } from '../../lib/cso/preparation';
|
||||
|
||||
type RuntimeStack = Exclude<CsoStack, 'java' | 'go'>;
|
||||
import { canonical, sha256 } from '../../lib/cso/contracts';
|
||||
import { ISOLATION_POLICY_HASH } from '../../lib/cso/docker';
|
||||
import {
|
||||
CSO_HELPER_ABI,
|
||||
RUNTIME_CATALOG,
|
||||
selectRuntime,
|
||||
type QualifiedRuntime,
|
||||
type RuntimeCatalog,
|
||||
type RuntimePlatform,
|
||||
} from '../../lib/cso/runtime-catalog';
|
||||
|
||||
const STACKS = ['node', 'bun', 'python', 'rails', 'postgresql'] as const;
|
||||
const PLATFORMS = ['linux/amd64', 'linux/arm64'] as const;
|
||||
const SOURCE_COMMIT = 'b'.repeat(40);
|
||||
const WORKFLOW = 'https://github.com/garrytan/gstack/actions/runs/1';
|
||||
const DIGEST = `sha256:${'a'.repeat(64)}`;
|
||||
|
||||
const VERSIONS: Record<RuntimeStack | 'postgresql', Record<string, string>> = {
|
||||
node: { node: '24.1.0', npm: '11.3.0', 'cso-preparation': '1.0.0' },
|
||||
bun: { bun: '1.3.10', 'cso-preparation': '1.0.0' },
|
||||
python: { python: '3.12.9', uv: '0.8.0', 'cso-preparation': '1.0.0' },
|
||||
rails: { ruby: '3.3.6', bundler: '2.6.9', 'cso-preparation': '1.0.0' },
|
||||
postgresql: { postgresql: '17.2' },
|
||||
};
|
||||
|
||||
function runtimeId(stack: RuntimeStack | 'postgresql', platform: RuntimePlatform): string {
|
||||
return `${stack}-qualified-test-${platform === 'linux/amd64' ? 'amd64' : 'arm64'}`;
|
||||
}
|
||||
|
||||
export function qualifiedRuntimeFixture(
|
||||
stack: RuntimeStack | 'postgresql',
|
||||
platform: RuntimePlatform = 'linux/amd64',
|
||||
): QualifiedRuntime {
|
||||
const arch = platform === 'linux/amd64' ? 'amd64' : 'arm64';
|
||||
const qualification = stack === 'postgresql'
|
||||
? {
|
||||
kind: 'postgresql' as const,
|
||||
sourceCommit: SOURCE_COMMIT,
|
||||
workflow: WORKFLOW,
|
||||
sbomDigest: DIGEST,
|
||||
provenanceDigest: DIGEST,
|
||||
verifiedProvenance: true as const,
|
||||
containmentPassed: true as const,
|
||||
coldStartPassed: true as const,
|
||||
multiDatabasePassed: true as const,
|
||||
readinessPassed: true as const,
|
||||
}
|
||||
: {
|
||||
kind: 'application' as const,
|
||||
sourceCommit: SOURCE_COMMIT,
|
||||
workflow: WORKFLOW,
|
||||
sbomDigest: DIGEST,
|
||||
provenanceDigest: DIGEST,
|
||||
verifiedProvenance: true as const,
|
||||
containmentPassed: true as const,
|
||||
coldStartPassed: true as const,
|
||||
positiveNegativeAssertionsPassed: true as const,
|
||||
heldOutRepairPassed: true as const,
|
||||
};
|
||||
|
||||
return {
|
||||
id: runtimeId(stack, platform),
|
||||
stack,
|
||||
platform,
|
||||
state: 'qualified',
|
||||
image: `ghcr.io/garrytan/gstack/cso-staging/${stack}-${arch}@${DIGEST}`,
|
||||
entrypoint: '/opt/cso/entrypoint',
|
||||
helperAbi: CSO_HELPER_ABI,
|
||||
versions: { ...VERSIONS[stack] },
|
||||
policyVersion: 'cso-isolation-v1',
|
||||
qualifiedAt: '2026-09-09T00:00:00Z',
|
||||
qualification,
|
||||
};
|
||||
}
|
||||
|
||||
/** A fresh catalog satisfying the complete reviewed and promoted runtime matrices. */
|
||||
export function completeRuntimeCatalogFixture(
|
||||
revision = 'runtime-test-v1',
|
||||
previousRevision: string | null = null,
|
||||
): RuntimeCatalog {
|
||||
const runtimes = STACKS.flatMap(stack => PLATFORMS.map(platform => qualifiedRuntimeFixture(stack, platform)));
|
||||
return {
|
||||
schemaVersion: 1,
|
||||
revision,
|
||||
previousRevision,
|
||||
helperAbi: CSO_HELPER_ABI,
|
||||
buildRevision: 'runtime-test-build-v1',
|
||||
profiles: runtimes.map(runtime => ({
|
||||
id: runtime.id,
|
||||
stack: runtime.stack,
|
||||
platform: runtime.platform,
|
||||
state: 'build_reviewed' as const,
|
||||
versions: { ...runtime.versions },
|
||||
reviewedAt: '2026-09-08T00:00:00Z',
|
||||
})),
|
||||
promotion: {
|
||||
sourceCommit: SOURCE_COMMIT,
|
||||
workflow: WORKFLOW,
|
||||
evidenceDigest: `sha256:${sha256(canonical(runtimes))}`,
|
||||
qualificationEvidenceDigest: DIGEST,
|
||||
requalification: {
|
||||
helperAbi: CSO_HELPER_ABI,
|
||||
isolationPolicyHash: ISOLATION_POLICY_HASH,
|
||||
preparationSha256: 'c'.repeat(64),
|
||||
buildInputsRevision: 'runtime-test-build-v1',
|
||||
},
|
||||
},
|
||||
runtimes,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Put a staged runtime into its stack/platform slot under the reviewed profile
|
||||
* id, as promotion does, and re-bind the promotion evidence digest the
|
||||
* validator recomputes from the runtime matrix.
|
||||
*/
|
||||
export function installStagedRuntime(catalog: RuntimeCatalog, runtime: QualifiedRuntime): QualifiedRuntime {
|
||||
const index = catalog.runtimes.findIndex(item => item.stack === runtime.stack && item.platform === runtime.platform);
|
||||
const profile = catalog.profiles.find(item => item.stack === runtime.stack && item.platform === runtime.platform);
|
||||
if (index < 0 || !profile || !catalog.promotion) throw new Error(`Runtime catalog fixture lacks ${runtime.stack} on ${runtime.platform}`);
|
||||
const installed = { ...runtime, id: profile.id, versions: { ...runtime.versions } };
|
||||
catalog.runtimes[index] = installed;
|
||||
profile.versions = { ...installed.versions };
|
||||
catalog.promotion.evidenceDigest = `sha256:${sha256(canonical(catalog.runtimes))}`;
|
||||
return installed;
|
||||
}
|
||||
|
||||
/** The given catalog with its promotion removed: every reviewed profile is still awaiting a qualified image. */
|
||||
export function unqualifiedRuntimeCatalog(base: RuntimeCatalog = RUNTIME_CATALOG): RuntimeCatalog {
|
||||
const { promotion: _promotion, ...reviewed } = base;
|
||||
return { ...reviewed, profiles: reviewed.profiles.map(profile => ({ ...profile, versions: { ...profile.versions } })), runtimes: [] };
|
||||
}
|
||||
|
||||
/**
|
||||
* The fail-closed rejection replay reaches at runtime admission for a fixture
|
||||
* bundle whose image digest no qualified catalog entry carries.
|
||||
*/
|
||||
export function replayRuntimeRejection(profile: string, platform: RuntimePlatform): { code: string; message: string } {
|
||||
try {
|
||||
selectRuntime(profile, platform);
|
||||
} catch (error) {
|
||||
return { code: 'PREREQUISITE', message: String((error as Error).message).split(':')[0] };
|
||||
}
|
||||
return { code: 'INCOMPATIBLE_INPUT', message: 'Qualified runtime digest does not match the bundle' };
|
||||
}
|
||||
@@ -43,7 +43,6 @@ const ADAPTER_ONLY: readonly string[] = [
|
||||
'context-recovery-artifacts',
|
||||
'context-restore-loads-latest',
|
||||
'context-save-writes-file',
|
||||
'cso-diff-mode',
|
||||
'design-review-detector-shim',
|
||||
'design-review-detector-shim-dom',
|
||||
'design-review-plugin-handoff',
|
||||
|
||||
@@ -696,15 +696,6 @@
|
||||
"costUsd": 0,
|
||||
"costRuns": 91
|
||||
},
|
||||
"cso-diff-mode": {
|
||||
"observations": 157,
|
||||
"withCommands": 157,
|
||||
"commands": [
|
||||
"design/dist/design"
|
||||
],
|
||||
"costUsd": 1.5371,
|
||||
"costRuns": 91
|
||||
},
|
||||
"design-review-detector-shim": {
|
||||
"observations": 174,
|
||||
"withCommands": 174,
|
||||
|
||||
@@ -6,9 +6,8 @@
|
||||
* fixture: `git rev-parse --git-path hooks` resolves to that directory, so the
|
||||
* install rewrites the developer's own pre-push (#3353), and their hook runs
|
||||
* on fixture pushes and rejects the local remote (#2967). /dev/null drops the
|
||||
* global file on every platform: Git for Windows rejects NUL (see
|
||||
* EMPTY_GLOBAL_GIT_CONFIG in lib/cso/process.ts). Config written inside the
|
||||
* fixture repo still applies.
|
||||
* global file on every platform: Git for Windows rejects NUL. Config written
|
||||
* inside the fixture repo still applies.
|
||||
*/
|
||||
export function gitEnv(extra: Record<string, string | undefined> = {}): NodeJS.ProcessEnv {
|
||||
const env: NodeJS.ProcessEnv = { ...process.env, ...extra };
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
* node_modules symlink to its main checkout, which git lists as untracked
|
||||
* because .gitignore's `node_modules/` matches only directories. Binaries are stubbed and `bun run build` is refused, so setup
|
||||
* runs its real registration path without compiling (GSTACK_SKIP_PLAYWRIGHT,
|
||||
* GSTACK_SETUP_SKIP_CSO_BUILD, GSTACK_SKIP_FONTS). Every write the test makes
|
||||
* GSTACK_SKIP_FONTS). Every write the test makes
|
||||
* goes through `put` or the `fixture*Sync` wrappers, which refuse paths
|
||||
* outside the fixture roots.
|
||||
*
|
||||
@@ -183,7 +183,7 @@ esac
|
||||
const env: Record<string, string> = {
|
||||
PATH: `${commands}:${process.env.PATH}`, HOME: home, USERPROFILE: home,
|
||||
TMPDIR: dir, TMP: dir, TEMP: dir, LANG: 'C.UTF-8',
|
||||
GSTACK_SKIP_PLAYWRIGHT: '1', GSTACK_SETUP_SKIP_CSO_BUILD: '1', GSTACK_SKIP_FONTS: '1',
|
||||
GSTACK_SKIP_PLAYWRIGHT: '1', GSTACK_SKIP_FONTS: '1',
|
||||
GSTACK_SKIP_COREUTILS: '1', GSTACK_SKIP_ASIDE: '1',
|
||||
BUN_RUNTIME_TRANSPILER_CACHE_PATH: join(tmpdir(), 'gstack-install-fixture-bun-cache'),
|
||||
};
|
||||
@@ -251,7 +251,6 @@ export function fixture(layout: string) {
|
||||
write(join(commands, 'bun'), `#!/usr/bin/env bash
|
||||
case "$*" in
|
||||
'install --production --frozen-lockfile') exit 0 ;;
|
||||
'build --help') echo 'Fixture Bun has no CSO compile flags'; exit 0 ;;
|
||||
'run build') echo 'Unexpected build in registration fixture' >&2; exit 90 ;;
|
||||
*) exec ${quote(process.execPath)} "$@" ;;
|
||||
esac
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
*
|
||||
* Why a separate harness from skill-size-budget.test.ts: that one enforces
|
||||
* size discipline only. This module supports content invariants per skill
|
||||
* family (e.g., cso must preserve OWASP/STRIDE; plan-ceo must preserve
|
||||
* family (e.g., plan-ceo must preserve
|
||||
* mode-selection phrasing) so future compression can't silently strip
|
||||
* load-bearing prose even when size stays within ratio.
|
||||
*/
|
||||
@@ -211,7 +211,6 @@ export function runParityChecks(opts: {
|
||||
* from the size-budget / static / behavioral guards.
|
||||
*/
|
||||
const MONOLITH_INVARIANTS: ParityInvariant[] = [
|
||||
// cso is now carved — its invariant is generated from CARVE_GUARDS below.
|
||||
// review, codex, land-and-deploy (w1), autoplan (w2), qa (w3) carved in token-reduction Phase 4
|
||||
// wave 1 (v1.69.x branch) — their invariants generate from CARVE_GUARDS too.
|
||||
];
|
||||
@@ -231,9 +230,7 @@ const CARVED_INVARIANTS: ParityInvariant[] = Object.values(CARVE_GUARDS).map((g)
|
||||
maxSkeletonBytes: g.maxSkeletonBytes,
|
||||
minBytes: g.minUnionBytes,
|
||||
mustContain: g.mustContain,
|
||||
// CSO's helper trust boundary requires its private startup; demanding the
|
||||
// shared Preamble here would silently reintroduce conflicting policy.
|
||||
mustHaveHeadings: g.skill === 'cso' ? [] : ['## Preamble'],
|
||||
mustHaveHeadings: ['## Preamble'],
|
||||
...(g.sizeLedger ? { sizeLedger: g.sizeLedger } : { maxSizeRatio: g.maxSizeRatio ?? 1.05 }),
|
||||
}));
|
||||
|
||||
|
||||
@@ -1,187 +0,0 @@
|
||||
import { spawn } from 'child_process';
|
||||
import type { RunResult, ToolTimelineEntry } from './types';
|
||||
|
||||
/** Usage, turns and the latest text from `claude -p --output-format stream-json --verbose --include-partial-messages`. */
|
||||
export interface ClaudeStreamState {
|
||||
totals: { input: number; output: number; cached: number };
|
||||
/** The message each stream (main thread or a tool's subagent) is currently receiving. */
|
||||
open: Map<string, { input: number; output: number; cached: number }>;
|
||||
/** Subagent messages, by message id: claude prints them only as `assistant` events tagged with their Agent call. */
|
||||
subagents: Map<string, { input: number; output: number; cached: number }>;
|
||||
turns: number;
|
||||
/** Turns summed over every `result` event: a background subagent's completion gives the main thread another result. */
|
||||
resultTurns: number;
|
||||
lastText: string;
|
||||
result?: Record<string, unknown>;
|
||||
invalidLines: number;
|
||||
startedAt: number;
|
||||
/** Content-free: each tool call's name, start and end offsets and thread, never its input or output. */
|
||||
toolTimeline: ToolTimelineEntry[];
|
||||
/** Timeline index by tool-use id, for recorded calls only, so it stays within the timeline cap. */
|
||||
toolUseIndex: Map<string, number>;
|
||||
}
|
||||
|
||||
export function claudeStreamState(): ClaudeStreamState {
|
||||
return { totals: { input: 0, output: 0, cached: 0 }, open: new Map(), subagents: new Map(), turns: 0, resultTurns: 0, lastText: '', invalidLines: 0, startedAt: Date.now(), toolTimeline: [], toolUseIndex: new Map() };
|
||||
}
|
||||
|
||||
const TOOL_TIMELINE_LIMIT = 4096;
|
||||
|
||||
const count = (value: unknown): number => typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : 0;
|
||||
|
||||
function recordToolUse(state: ClaudeStreamState, block: { id?: unknown; name?: unknown }, agent: 'main' | 'subagent'): void {
|
||||
if (typeof block.id !== 'string' || state.toolUseIndex.has(block.id) || state.toolTimeline.length >= TOOL_TIMELINE_LIMIT) return;
|
||||
state.toolUseIndex.set(block.id, state.toolTimeline.length);
|
||||
state.toolTimeline.push({
|
||||
atMs: Date.now() - state.startedAt,
|
||||
tool: typeof block.name === 'string' && /^[A-Za-z][A-Za-z0-9_]{0,63}$/.test(block.name) ? block.name : 'other',
|
||||
agent,
|
||||
});
|
||||
}
|
||||
|
||||
function recordToolResult(state: ClaudeStreamState, block: { tool_use_id?: unknown }): void {
|
||||
const index = typeof block.tool_use_id === 'string' ? state.toolUseIndex.get(block.tool_use_id) : undefined;
|
||||
if (index !== undefined && state.toolTimeline[index].endMs === undefined) state.toolTimeline[index].endMs = Date.now() - state.startedAt;
|
||||
}
|
||||
|
||||
function close(state: ClaudeStreamState, key: string): void {
|
||||
const message = state.open.get(key);
|
||||
if (!message) return;
|
||||
state.totals.input += message.input; state.totals.output += message.output; state.totals.cached += message.cached;
|
||||
state.open.delete(key);
|
||||
}
|
||||
|
||||
export function consumeClaudeStreamLine(state: ClaudeStreamState, line: string): void {
|
||||
if (!line.trim()) return;
|
||||
let event: any;
|
||||
try { event = JSON.parse(line); } catch { state.invalidLines++; return; }
|
||||
if (!event || typeof event !== 'object') { state.invalidLines++; return; }
|
||||
if (event.type === 'result') {
|
||||
state.result = event;
|
||||
if (Number.isSafeInteger(event.num_turns) && event.num_turns >= 0) state.resultTurns += event.num_turns;
|
||||
return;
|
||||
}
|
||||
if (event.type === 'assistant' && Array.isArray(event.message?.content)) {
|
||||
for (const block of event.message.content) if (block?.type === 'tool_use') recordToolUse(state, block, typeof event.parent_tool_use_id === 'string' ? 'subagent' : 'main');
|
||||
}
|
||||
if (event.type === 'user' && Array.isArray(event.message?.content)) {
|
||||
for (const block of event.message.content) if (block?.type === 'tool_result') recordToolResult(state, block);
|
||||
return;
|
||||
}
|
||||
if (event.type === 'assistant' && typeof event.parent_tool_use_id === 'string') {
|
||||
const usage = event.message?.usage;
|
||||
if (typeof event.message?.id === 'string' && usage) state.subagents.set(event.message.id, { input: count(usage.input_tokens), output: count(usage.output_tokens), cached: count(usage.cache_read_input_tokens) });
|
||||
return;
|
||||
}
|
||||
if (event.type === 'assistant' && Array.isArray(event.message?.content)) {
|
||||
for (const block of event.message.content) if (block?.type === 'text' && typeof block.text === 'string' && block.text.trim()) state.lastText = block.text;
|
||||
return;
|
||||
}
|
||||
if (event.type !== 'stream_event' || !event.event) return;
|
||||
const key = typeof event.parent_tool_use_id === 'string' ? event.parent_tool_use_id : 'main';
|
||||
const stream = event.event;
|
||||
if (stream.type === 'message_start') {
|
||||
close(state, key);
|
||||
const usage = stream.message?.usage ?? {};
|
||||
state.open.set(key, { input: count(usage.input_tokens), output: count(usage.output_tokens), cached: count(usage.cache_read_input_tokens) });
|
||||
if (key === 'main') state.turns++;
|
||||
} else if (stream.type === 'content_block_start' && stream.content_block?.type === 'tool_use') {
|
||||
recordToolUse(state, stream.content_block, key === 'main' ? 'main' : 'subagent');
|
||||
} else if (stream.type === 'message_delta' && stream.usage) {
|
||||
const message = state.open.get(key);
|
||||
if (!message) return;
|
||||
// Anthropic message_delta usage is cumulative for the message.
|
||||
if (stream.usage.output_tokens !== undefined) message.output = count(stream.usage.output_tokens);
|
||||
if (stream.usage.input_tokens !== undefined) message.input = count(stream.usage.input_tokens);
|
||||
if (stream.usage.cache_read_input_tokens !== undefined) message.cached = count(stream.usage.cache_read_input_tokens);
|
||||
} else if (stream.type === 'message_stop') {
|
||||
close(state, key);
|
||||
}
|
||||
}
|
||||
|
||||
/** Every message seen so far, subagents' included, and ones a kill interrupted mid-stream. */
|
||||
export function claudeStreamUsage(state: ClaudeStreamState): { input: number; output: number; cached: number } {
|
||||
const totals = { ...state.totals };
|
||||
for (const message of [...state.open.values(), ...state.subagents.values()]) { totals.input += message.input; totals.output += message.output; totals.cached += message.cached; }
|
||||
return totals;
|
||||
}
|
||||
|
||||
/** `modelUsage` is the session total across models, subagents included; `usage` covers only the main thread's last turn. */
|
||||
function resultTokens(result: Record<string, unknown>): { input: number; output: number; cached: number } | undefined {
|
||||
const models = result.modelUsage;
|
||||
if (models && typeof models === 'object' && Object.keys(models).length) {
|
||||
const totals = { input: 0, output: 0, cached: 0 };
|
||||
for (const usage of Object.values(models as Record<string, Record<string, unknown>>)) {
|
||||
totals.input += count(usage?.inputTokens); totals.output += count(usage?.outputTokens); totals.cached += count(usage?.cacheReadInputTokens);
|
||||
}
|
||||
return totals;
|
||||
}
|
||||
const usage = result.usage as Record<string, unknown> | undefined;
|
||||
return usage ? { input: count(usage.input_tokens), output: count(usage.output_tokens), cached: count(usage.cache_read_input_tokens) } : undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* The final `result` event is authoritative for usage (its `modelUsage` session totals) and its text; turns sum over
|
||||
* every result. Without one (a killed run) the per-message stream usage stands in. A paid producer still needs a
|
||||
* successful result event with a nonblank `result`.
|
||||
*/
|
||||
export function resultFromClaudeStream(state: ClaudeStreamState, opts: { model: string; durationMs: number; error?: RunResult['error'] }): RunResult {
|
||||
const result = state.result;
|
||||
const tokens = (result && resultTokens(result)) ?? claudeStreamUsage(state);
|
||||
const toolCalls = result ? state.resultTurns : state.turns;
|
||||
const modelUsed = typeof result?.model === 'string' && result.model ? result.model : opts.model;
|
||||
const base = { tokens, durationMs: opts.durationMs, toolCalls, toolTimeline: state.toolTimeline, modelUsed };
|
||||
if (opts.error) return { ...base, output: typeof result?.result === 'string' ? result.result : state.lastText, error: opts.error };
|
||||
const explicitError = result?.is_error === true || (typeof result?.subtype === 'string' && result.subtype !== 'success');
|
||||
if (!result || explicitError || typeof result.result !== 'string' || !result.result.trim()) {
|
||||
return { ...base, output: '', error: { code: 'unknown', reason: 'empty or invalid output from claude CLI (exit 0)' } };
|
||||
}
|
||||
return { ...base, output: result.result };
|
||||
}
|
||||
|
||||
const LINE_LIMIT = 32 * 1024 * 1024, STDERR_LIMIT = 64 * 1024, KILL_GRACE_MS = 10_000;
|
||||
|
||||
/** Run the producer's claude, folding its event stream as it arrives so a timeout still leaves usage behind. */
|
||||
export function runClaudeProducerStream(command: string, args: string[], opts: { input: string; cwd: string; env: Record<string, string>; timeoutMs: number; model: string }): Promise<RunResult> {
|
||||
return new Promise(resolve => {
|
||||
const started = Date.now(), state = claudeStreamState();
|
||||
let pending = '', stderr = '', timedOut = false, overflow = false, spawnError: Error | undefined;
|
||||
let killTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
const child = spawn(command, args, { cwd: opts.cwd, env: opts.env, stdio: ['pipe', 'pipe', 'pipe'] });
|
||||
const stop = () => { child.kill('SIGTERM'); killTimer = setTimeout(() => child.kill('SIGKILL'), KILL_GRACE_MS); };
|
||||
const timer = setTimeout(() => { timedOut = true; stop(); }, opts.timeoutMs);
|
||||
child.stdout.setEncoding('utf8');
|
||||
child.stdout.on('data', (chunk: string) => {
|
||||
pending += chunk;
|
||||
let newline: number;
|
||||
while ((newline = pending.indexOf('\n')) >= 0) { consumeClaudeStreamLine(state, pending.slice(0, newline)); pending = pending.slice(newline + 1); }
|
||||
if (pending.length > LINE_LIMIT && !overflow) { overflow = true; pending = ''; stop(); }
|
||||
});
|
||||
child.stderr.setEncoding('utf8');
|
||||
child.stderr.on('data', (chunk: string) => { if (stderr.length < STDERR_LIMIT) stderr += chunk.slice(0, STDERR_LIMIT - stderr.length); });
|
||||
child.stdin.on('error', () => {});
|
||||
let settled = false, exitTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
child.on('error', error => { spawnError = error; if (child.pid === undefined) finish(null, null); });
|
||||
// A grandchild that inherited stdout must not hold the result open after claude itself exits.
|
||||
child.on('exit', (code, signal) => { exitTimer = setTimeout(() => { child.stdout.destroy(); child.stderr.destroy(); finish(code, signal); }, 2000); });
|
||||
child.on('close', (code, signal) => finish(code, signal));
|
||||
function finish(code: number | null, signal: NodeJS.Signals | null): void {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearTimeout(timer); if (killTimer) clearTimeout(killTimer); if (exitTimer) clearTimeout(exitTimer);
|
||||
if (!overflow) consumeClaudeStreamLine(state, pending);
|
||||
const durationMs = Date.now() - started;
|
||||
const fail = (error: NonNullable<RunResult['error']>) => resolve(resultFromClaudeStream(state, { model: opts.model, durationMs, error }));
|
||||
if (timedOut) return fail({ code: 'timeout', reason: `exceeded ${opts.timeoutMs}ms` });
|
||||
if (overflow) return fail({ code: 'unknown', reason: `claude stream-json line exceeded ${LINE_LIMIT} bytes` });
|
||||
if (spawnError) return fail({ code: 'unknown', reason: spawnError.message.slice(0, 400) });
|
||||
if (code !== 0) {
|
||||
if (/unauthorized|auth|login/i.test(stderr)) return fail({ code: 'auth', reason: stderr.slice(0, 400) });
|
||||
if (/rate[- ]?limit|429/i.test(stderr)) return fail({ code: 'rate_limit', reason: stderr.slice(0, 400) });
|
||||
return fail({ code: 'unknown', reason: `Command failed: ${[command, ...args].join(' ')}${signal ? ` (signal ${signal})` : ''}\n${stderr}`.slice(0, 400) });
|
||||
}
|
||||
resolve(resultFromClaudeStream(state, { model: opts.model, durationMs }));
|
||||
}
|
||||
child.stdin.end(opts.input);
|
||||
});
|
||||
}
|
||||
@@ -1,9 +1,4 @@
|
||||
import {
|
||||
csoProducerChildEnvironment,
|
||||
csoProducerHelperHome,
|
||||
csoProducerHelperLauncher,
|
||||
csoProducerProviderCommand,
|
||||
csoProducerStateDirectory,
|
||||
type ProviderAdapter,
|
||||
type RunOpts,
|
||||
type RunResult,
|
||||
@@ -16,20 +11,18 @@ import * as path from 'path';
|
||||
import * as os from 'os';
|
||||
import { resolveClaudeCommand } from '../../../lib/claude-bin';
|
||||
import { resolveEvalModel } from '../../../lib/eval-model';
|
||||
import { runClaudeProducerStream } from './claude-stream';
|
||||
|
||||
/**
|
||||
* Claude adapter — wraps the `claude` CLI via claude -p.
|
||||
*
|
||||
* For brevity and to avoid duplicating the full stream-json parser, this adapter
|
||||
* uses claude CLI in non-interactive mode (--print) with the simpler JSON output
|
||||
* format. CSO producers stream events instead (claude-stream.ts) so a timed-out
|
||||
* run still reports its usage.
|
||||
* format.
|
||||
*/
|
||||
export interface ClaudeAdapterOptions {
|
||||
/** Child environment for a non-producer run; defaults to claudeExecEnvironment over process.env. */
|
||||
/** Child environment for a run; defaults to claudeExecEnvironment over process.env. */
|
||||
environment?: (opts: RunOpts) => Record<string, string>;
|
||||
/** Treat an explicit error or empty `result` envelope as a failed run, as paid producers do. */
|
||||
/** Treat an explicit error or empty `result` envelope as a failed run. */
|
||||
strict?: boolean;
|
||||
}
|
||||
|
||||
@@ -39,11 +32,10 @@ export class ClaudeAdapter implements ProviderAdapter {
|
||||
|
||||
constructor(private readonly options: ClaudeAdapterOptions = {}) {}
|
||||
|
||||
async available(opts?: RunOpts): Promise<AvailabilityCheck> {
|
||||
async available(): Promise<AvailabilityCheck> {
|
||||
// Binary on PATH (or GSTACK_CLAUDE_BIN override). Routes through the shared
|
||||
// resolver so Windows + override paths behave the same as production sites.
|
||||
const producerCommand = csoProducerProviderCommand(opts ?? { prompt: '', workdir: '/', timeoutMs: 1 });
|
||||
const resolved = producerCommand ? { command: producerCommand.executable, argsPrefix: producerCommand.argsPrefix } : resolveClaudeCommand();
|
||||
const resolved = resolveClaudeCommand();
|
||||
if (!resolved) {
|
||||
return { ok: false, reason: 'claude CLI not found on PATH. Install from https://claude.ai/download or npm i -g @anthropic-ai/claude-code (or set GSTACK_CLAUDE_BIN)' };
|
||||
}
|
||||
@@ -56,7 +48,7 @@ export class ClaudeAdapter implements ProviderAdapter {
|
||||
// secret), and any failure of `security` itself falls through to the
|
||||
// not-found reason rather than throwing.
|
||||
const credsPath = path.join(os.homedir(), '.claude', '.credentials.json');
|
||||
const hasCreds = !opts?.csoProducer && fs.existsSync(credsPath);
|
||||
const hasCreds = fs.existsSync(credsPath);
|
||||
const hasKey = !!(process.env.ANTHROPIC_API_KEY || process.env.CLAUDE_CODE_OAUTH_TOKEN);
|
||||
let hasKeychain = false;
|
||||
if (!hasCreds && !hasKey && process.platform === 'darwin') {
|
||||
@@ -71,37 +63,25 @@ export class ClaudeAdapter implements ProviderAdapter {
|
||||
}
|
||||
}
|
||||
if (!hasCreds && !hasKey && !hasKeychain) {
|
||||
return { ok: false, reason: opts?.csoProducer
|
||||
? 'No Claude producer auth found. Export ANTHROPIC_API_KEY or CLAUDE_CODE_OAUTH_TOKEN; macOS Keychain auth is also supported.'
|
||||
: 'No Claude auth found. Log in via `claude` interactive session, or export ANTHROPIC_API_KEY.' };
|
||||
return { ok: false, reason: 'No Claude auth found. Log in via `claude` interactive session, or export ANTHROPIC_API_KEY.' };
|
||||
}
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
async run(opts: RunOpts): Promise<RunResult> {
|
||||
const start = Date.now();
|
||||
const producerCommand = csoProducerProviderCommand(opts);
|
||||
const resolved = producerCommand ? { command: producerCommand.executable, argsPrefix: producerCommand.argsPrefix } : resolveClaudeCommand();
|
||||
const resolved = resolveClaudeCommand();
|
||||
if (!resolved) {
|
||||
throw new Error('claude CLI not resolvable (set GSTACK_CLAUDE_BIN or install)');
|
||||
}
|
||||
const model = opts.model ?? process.env.EVALS_MODEL ?? resolveEvalModel('capture');
|
||||
const stateDirectory = csoProducerStateDirectory(opts);
|
||||
const args = claudeExecArgs(opts, model, resolved.argsPrefix);
|
||||
const env = !opts.csoProducer && this.options.environment ? this.options.environment(opts) : claudeExecEnvironment(opts, process.env);
|
||||
if (stateDirectory) {
|
||||
assertClaudeProducerPrerequisites();
|
||||
assertClaudeProducerSandboxPolicy(args, env, csoProducerHelperLauncher(opts)!);
|
||||
}
|
||||
const env = this.options.environment ? this.options.environment(opts) : claudeExecEnvironment(process.env);
|
||||
|
||||
try {
|
||||
if (stateDirectory) {
|
||||
prepareClaudeProducerState(stateDirectory);
|
||||
return await runClaudeProducerStream(resolved.command, args, { input: opts.prompt, cwd: claudeExecWorkingDirectory(opts), env, timeoutMs: opts.timeoutMs, model });
|
||||
}
|
||||
const out = execFileSync(resolved.command, args, {
|
||||
input: opts.prompt,
|
||||
cwd: claudeExecWorkingDirectory(opts),
|
||||
cwd: opts.workdir,
|
||||
timeout: opts.timeoutMs,
|
||||
encoding: 'utf-8',
|
||||
maxBuffer: 32 * 1024 * 1024,
|
||||
@@ -109,7 +89,7 @@ export class ClaudeAdapter implements ProviderAdapter {
|
||||
// AskUserQuestion failure BLOCKs rather than emitting unanswerable prose).
|
||||
env,
|
||||
});
|
||||
return resultFromClaudeOutput(out,{model,durationMs:Date.now()-start,producer:!!opts.csoProducer||!!this.options.strict});
|
||||
return resultFromClaudeOutput(out,{model,durationMs:Date.now()-start,producer:!!this.options.strict});
|
||||
} catch (err: unknown) {
|
||||
const durationMs = Date.now() - start;
|
||||
const e = err as { code?: string; stderr?: Buffer; signal?: string; message?: string };
|
||||
@@ -124,8 +104,6 @@ export class ClaudeAdapter implements ProviderAdapter {
|
||||
return this.emptyResult(durationMs, { code: 'rate_limit', reason: stderr.slice(0, 400) }, model);
|
||||
}
|
||||
return this.emptyResult(durationMs, { code: 'unknown', reason: (e.message ?? stderr ?? 'unknown').slice(0, 400) }, model);
|
||||
} finally {
|
||||
if (stateDirectory) removeClaudeProducerState(stateDirectory);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -145,7 +123,7 @@ export class ClaudeAdapter implements ProviderAdapter {
|
||||
}
|
||||
}
|
||||
|
||||
/** Map Claude JSON output; paid producers require the documented nonblank `result` envelope. */
|
||||
/** Map Claude JSON output; strict callers require the documented nonblank `result` envelope. */
|
||||
export function resultFromClaudeOutput(raw:string,opts:{model?:string;durationMs?:number;producer?:boolean}={}):RunResult{
|
||||
const durationMs=opts.durationMs??0,defaultModel=opts.model??resolveEvalModel('capture');
|
||||
try{
|
||||
@@ -160,126 +138,12 @@ export function resultFromClaudeOutput(raw:string,opts:{model?:string;durationMs
|
||||
}
|
||||
}
|
||||
|
||||
export interface ClaudeProducerPaths { root: string; home: string; workdir: string }
|
||||
|
||||
export function assertClaudeProducerPrerequisites(): void {
|
||||
if (process.platform !== 'linux') return;
|
||||
const executable = '/usr/bin/bwrap';
|
||||
let stat: fs.Stats;
|
||||
try { stat = fs.lstatSync(executable); } catch { throw new Error('CLAUDE_PRODUCER_REQUIRES_TRUSTED_BWRAP'); }
|
||||
if (!stat.isFile() || stat.isSymbolicLink() || fs.realpathSync(executable) !== executable || stat.uid !== 0 || (stat.mode & 0o022) !== 0 || (stat.mode & 0o111) === 0) {
|
||||
throw new Error('CLAUDE_PRODUCER_REQUIRES_TRUSTED_BWRAP');
|
||||
}
|
||||
}
|
||||
|
||||
export function claudeProducerPaths(stateDirectory: string): ClaudeProducerPaths {
|
||||
const root = path.join(stateDirectory, 'claude-provider');
|
||||
return { root, home: path.join(root, 'home'), workdir: path.join(root, 'work') };
|
||||
}
|
||||
|
||||
export function prepareClaudeProducerState(stateDirectory: string): ClaudeProducerPaths {
|
||||
const paths = claudeProducerPaths(stateDirectory);
|
||||
if (fs.existsSync(paths.root)) throw new Error('CLAUDE_PRODUCER_STATE_EXISTS');
|
||||
fs.mkdirSync(paths.root, { mode: 0o700 });
|
||||
fs.mkdirSync(paths.home, { mode: 0o700 });
|
||||
fs.mkdirSync(paths.workdir, { mode: 0o700 });
|
||||
return paths;
|
||||
}
|
||||
|
||||
export function removeClaudeProducerState(stateDirectory: string): void {
|
||||
fs.rmSync(claudeProducerPaths(stateDirectory).root, { recursive: true, force: true });
|
||||
}
|
||||
|
||||
export function claudeExecWorkingDirectory(opts: RunOpts): string {
|
||||
const stateDirectory = csoProducerStateDirectory(opts);
|
||||
return stateDirectory ? claudeProducerPaths(stateDirectory).workdir : opts.workdir;
|
||||
}
|
||||
|
||||
export function claudeProducerTools(opts: RunOpts): string {
|
||||
const launcher = csoProducerHelperLauncher(opts);
|
||||
if (!launcher) throw new Error('CSO producer helper launcher is required');
|
||||
return [`Bash(${launcher})`, `Bash(${launcher} *)`, 'Write'].join(',');
|
||||
}
|
||||
|
||||
/** Built-in tools: users' /cso starts its independent reviewers with Agent; subagents inherit this whole policy. */
|
||||
export const CLAUDE_PRODUCER_BUILTIN_TOOLS = 'Bash,Write,Agent';
|
||||
|
||||
/** Claude's sandbox wraps every Bash command except the trusted launcher, which must run where users run it. */
|
||||
export function claudeProducerSettings(launcher: string): { sandbox: Record<string, unknown> } {
|
||||
return {
|
||||
sandbox: {
|
||||
enabled: true,
|
||||
failIfUnavailable: true,
|
||||
allowUnsandboxedCommands: false,
|
||||
autoAllowBashIfSandboxed: false,
|
||||
excludedCommands: [launcher, `${launcher} *`],
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function assertClaudeProducerSandboxPolicy(args: readonly string[], env: Record<string, string>, launcher: string): void {
|
||||
const fail = (detail: string): never => { throw new Error(`CLAUDE_PRODUCER_SANDBOX_POLICY_MISMATCH: ${detail}`); };
|
||||
const value = (flag: string): string => {
|
||||
const positions = args.flatMap((arg, index) => arg === flag || arg.startsWith(`${flag}=`) ? [index] : []);
|
||||
if (positions.length !== 1 || args[positions[0]] !== flag || positions[0] + 1 >= args.length) fail(`expected exactly one ${flag} <value>`);
|
||||
return args[positions[0] + 1];
|
||||
};
|
||||
if (value('--tools') !== CLAUDE_PRODUCER_BUILTIN_TOOLS) fail(`--tools must be exactly ${CLAUDE_PRODUCER_BUILTIN_TOOLS}`);
|
||||
if (value('--allowed-tools') !== `Bash(${launcher}),Bash(${launcher} *),Write`) fail('--allowed-tools must name only the launcher and Write');
|
||||
if (value('--permission-mode') !== 'dontAsk') fail('--permission-mode must be dontAsk');
|
||||
for (const flag of ['--restricted', '--safe-mode', '--strict-mcp-config']) if (args.filter(arg => arg === flag).length !== 1) fail(`expected exactly one ${flag}`);
|
||||
const widening = args.find(arg => /^--(mcp-config|agents?|plugin-dir|dangerously-skip-permissions|allow-dangerously-skip-permissions|disallowed-tools|disallowedTools|setting-sources)(=|$)/.test(arg));
|
||||
if (widening) fail(`${widening.split('=')[0]} would change what the agent and its subagents may do`);
|
||||
const raw = value('--settings');
|
||||
let settings: unknown;
|
||||
try { settings = JSON.parse(raw); } catch { fail('--settings is not JSON'); }
|
||||
const expected = { enabled: true, failIfUnavailable: true, allowUnsandboxedCommands: false, autoAllowBashIfSandboxed: false, excludedCommands: [launcher, `${launcher} *`] };
|
||||
const sandbox = (settings as { sandbox?: Record<string, unknown> } | null)?.sandbox;
|
||||
if (!settings || typeof settings !== 'object' || Object.keys(settings).join() !== 'sandbox' || !sandbox || typeof sandbox !== 'object') fail('--settings must hold only a sandbox object');
|
||||
if (Object.keys(sandbox!).sort().join() !== Object.keys(expected).sort().join()) fail('sandbox settings keys differ from the launcher-only exclusion policy');
|
||||
for (const [key, wanted] of Object.entries(expected)) {
|
||||
if (JSON.stringify(sandbox![key]) !== JSON.stringify(wanted)) fail(`sandbox.${key} must be ${JSON.stringify(wanted)}`);
|
||||
}
|
||||
if (env.CLAUDE_CODE_SUBPROCESS_ENV_SCRUB !== undefined) fail('CLAUDE_CODE_SUBPROCESS_ENV_SCRUB forces every command, the launcher included, into the sandbox');
|
||||
}
|
||||
|
||||
export function claudeExecArgs(opts: RunOpts, model: string, argsPrefix: readonly string[] = []): string[] {
|
||||
const stateDirectory = csoProducerStateDirectory(opts);
|
||||
// Producers stream events so a timed-out or killed run still reports the usage it spent.
|
||||
const output = stateDirectory ? ['stream-json', '--verbose', '--include-partial-messages'] : ['json'];
|
||||
const args = [...argsPrefix, '-p', '--output-format', ...output, '--model', model];
|
||||
if (stateDirectory) {
|
||||
if (opts.extraArgs?.length) throw new Error('CSO producer does not accept extra provider arguments');
|
||||
const tools = claudeProducerTools(opts);
|
||||
const helperHome = csoProducerHelperHome(opts)!;
|
||||
args.push(
|
||||
'--restricted',
|
||||
'--safe-mode',
|
||||
'--no-session-persistence',
|
||||
'--permission-prompts', 'none',
|
||||
'--permission-mode', 'dontAsk',
|
||||
'--tools', CLAUDE_PRODUCER_BUILTIN_TOOLS,
|
||||
'--allowed-tools', tools,
|
||||
'--add-dir', claudeProducerPaths(stateDirectory).workdir,
|
||||
'--add-dir', helperHome,
|
||||
'--settings', JSON.stringify(claudeProducerSettings(csoProducerHelperLauncher(opts)!)),
|
||||
'--strict-mcp-config',
|
||||
'--no-chrome',
|
||||
);
|
||||
}
|
||||
const args = [...argsPrefix, '-p', '--output-format', 'json', '--model', model];
|
||||
if (opts.extraArgs) args.push(...opts.extraArgs);
|
||||
return args;
|
||||
}
|
||||
|
||||
export function claudeExecEnvironment(
|
||||
opts: RunOpts,
|
||||
source: NodeJS.ProcessEnv = process.env,
|
||||
): Record<string, string> {
|
||||
const stateDirectory = csoProducerStateDirectory(opts);
|
||||
const paths = stateDirectory ? claudeProducerPaths(stateDirectory) : undefined;
|
||||
return {
|
||||
...(opts.csoProducer ? csoProducerChildEnvironment('claude', source) : source),
|
||||
...(paths ? { HOME: paths.home, GSTACK_HOME: csoProducerHelperHome(opts)! } : {}),
|
||||
GSTACK_HEADLESS: '1',
|
||||
} as Record<string, string>;
|
||||
export function claudeExecEnvironment(source: NodeJS.ProcessEnv = process.env): Record<string, string> {
|
||||
return { ...source, GSTACK_HEADLESS: '1' } as Record<string, string>;
|
||||
}
|
||||
@@ -66,7 +66,7 @@ export class GatewayAdapter implements ProviderAdapter {
|
||||
constructor(readonly name: GatewayName, private readonly source: NodeJS.ProcessEnv = process.env) {
|
||||
this.model = GATEWAY_MODELS[name];
|
||||
this.harness = new ClaudeAdapter({
|
||||
environment: opts => gatewayEnvironment(this.model, claudeExecEnvironment(opts, this.source)),
|
||||
environment: () => gatewayEnvironment(this.model, claudeExecEnvironment(this.source)),
|
||||
strict: true,
|
||||
});
|
||||
}
|
||||
@@ -82,9 +82,6 @@ export class GatewayAdapter implements ProviderAdapter {
|
||||
}
|
||||
|
||||
async run(opts: RunOpts): Promise<RunResult> {
|
||||
if (opts.csoProducer) {
|
||||
return { output: '', tokens: { input: 0, output: 0 }, durationMs: 0, toolCalls: 0, modelUsed: this.model, error: { code: 'unknown', reason: 'gateway providers do not run CSO producers' } };
|
||||
}
|
||||
const result = await this.harness.run({ ...opts, model: this.model, extraArgs: [...(opts.extraArgs ?? []), '--setting-sources', ''] });
|
||||
const foreign = foreignModels(this.model, result.modelsBilled);
|
||||
if (!result.error && foreign.length) {
|
||||
|
||||
@@ -1,10 +1,4 @@
|
||||
import {
|
||||
csoProducerChildEnvironment,
|
||||
csoProducerHelperHome,
|
||||
csoProducerHelperLauncher,
|
||||
csoProducerProviderCommand,
|
||||
csoProducerStateDirectory,
|
||||
validateCsoProducerStateDirectory,
|
||||
type ProviderAdapter,
|
||||
type RunOpts,
|
||||
type RunResult,
|
||||
@@ -12,11 +6,9 @@ import {
|
||||
} from './types';
|
||||
import { estimateCostUsd } from '../pricing';
|
||||
import { execFileSync, spawnSync } from 'child_process';
|
||||
import { randomBytes } from 'node:crypto';
|
||||
import * as fs from 'fs';
|
||||
import * as path from 'path';
|
||||
import * as os from 'os';
|
||||
import { atomicWriteSync } from '../../../lib/fs-atomic';
|
||||
|
||||
export type GeminiStreamParse = {
|
||||
output: string;
|
||||
@@ -129,9 +121,8 @@ export class GeminiAdapter implements ProviderAdapter {
|
||||
readonly name = 'gemini';
|
||||
readonly family = 'gemini' as const;
|
||||
|
||||
async available(opts?: RunOpts): Promise<AvailabilityCheck> {
|
||||
const producerCommand = csoProducerProviderCommand(opts ?? { prompt: '', workdir: '/', timeoutMs: 1 });
|
||||
const res = producerCommand ? { status: 0 } : spawnSync('sh', ['-c', 'command -v gemini'], { timeout: 2000 });
|
||||
async available(): Promise<AvailabilityCheck> {
|
||||
const res = spawnSync('sh', ['-c', 'command -v gemini'], { timeout: 2000 });
|
||||
if (res.status !== 0) {
|
||||
return { ok: false, reason: 'gemini CLI not found on PATH. Install per https://github.com/google-gemini/gemini-cli' };
|
||||
}
|
||||
@@ -140,7 +131,7 @@ export class GeminiAdapter implements ProviderAdapter {
|
||||
const newOauth = path.join(newCfgDir, 'oauth_creds.json');
|
||||
// CLI accepts either name; Google AI Studio keys are usually GEMINI_API_KEY.
|
||||
if (process.env.GOOGLE_API_KEY || process.env.GEMINI_API_KEY) return { ok: true };
|
||||
const hasOauth = !opts?.csoProducer && (fs.existsSync(legacyCfgDir) || fs.existsSync(newOauth));
|
||||
const hasOauth = fs.existsSync(legacyCfgDir) || fs.existsSync(newOauth);
|
||||
return {
|
||||
ok: false,
|
||||
reason: hasOauth
|
||||
@@ -155,14 +146,12 @@ export class GeminiAdapter implements ProviderAdapter {
|
||||
// tokens + tool calls. Callers can override via extraArgs. (--skip-trust was
|
||||
// removed in gemini-cli 0.34; passing it errors at argv parse.)
|
||||
try {
|
||||
const args = geminiExecArgs(opts);
|
||||
const command = csoProducerProviderCommand(opts);
|
||||
const out = execFileSync(command?.executable ?? 'gemini', [...(command?.argsPrefix ?? []), ...args], {
|
||||
cwd: geminiExecWorkingDirectory(opts),
|
||||
const out = execFileSync('gemini', geminiExecArgs(opts), {
|
||||
cwd: opts.workdir,
|
||||
timeout: opts.timeoutMs,
|
||||
encoding: 'utf-8',
|
||||
maxBuffer: 32 * 1024 * 1024,
|
||||
env: geminiExecEnvironment(opts, process.env),
|
||||
env: geminiExecEnvironment(process.env),
|
||||
});
|
||||
return resultFromGeminiStream(out, { model: opts.model, durationMs: Date.now() - start });
|
||||
} catch (err: unknown) {
|
||||
@@ -198,123 +187,16 @@ export class GeminiAdapter implements ProviderAdapter {
|
||||
}
|
||||
}
|
||||
|
||||
export interface GeminiProducerPaths {
|
||||
root: string;
|
||||
home: string;
|
||||
workdir: string;
|
||||
systemDefaults: string;
|
||||
systemSettings: string;
|
||||
}
|
||||
|
||||
export function geminiProducerPaths(stateDirectory: string): GeminiProducerPaths {
|
||||
validateCsoProducerStateDirectory(stateDirectory);
|
||||
const root = path.join(stateDirectory, 'gemini-provider');
|
||||
return {
|
||||
root,
|
||||
home: path.join(root, 'home'),
|
||||
workdir: path.join(root, 'work'),
|
||||
systemDefaults: path.join(root, 'system-defaults.json'),
|
||||
systemSettings: path.join(root, 'system-settings.json'),
|
||||
};
|
||||
}
|
||||
|
||||
/** Highest-precedence Gemini policy for a clean, one-cell producer host. */
|
||||
const GEMINI_PRODUCER_BLOCKED_ENVIRONMENT = [
|
||||
'GEMINI_API_KEY', 'GOOGLE_API_KEY', 'GOOGLE_CLOUD_PROJECT', 'GOOGLE_CLOUD_LOCATION',
|
||||
] as const;
|
||||
|
||||
export function geminiProducerSystemSettings(contextFileName: string, helperLauncher: string) {
|
||||
if (!/^\.gstack-cso-context-[a-f0-9]{32}\.md$/.test(contextFileName)) throw new Error('INVALID_GEMINI_CONTEXT_FILENAME');
|
||||
const helper = csoProducerHelperLauncher({ prompt: '', workdir: '/', timeoutMs: 1, csoProducer: { stateDirectory: '/', sourceDirectory: '/source', helperLauncher, helperGeneration: path.join(path.dirname(helperLauncher), '.gstack-cso-generation'), providerCommand: { executable: '/provider', argsPrefix: [] } } });
|
||||
if (!helper) throw new Error('CSO producer helper launcher is required');
|
||||
const tools = [`run_shell_command(${helper})`, 'write_file'];
|
||||
return {
|
||||
advanced: { ignoreLocalEnv: true },
|
||||
admin: {
|
||||
extensions: { enabled: false },
|
||||
mcp: { enabled: false },
|
||||
skills: { enabled: false },
|
||||
},
|
||||
context: {
|
||||
fileName: [contextFileName],
|
||||
includeDirectoryTree: false,
|
||||
loadMemoryFromIncludeDirectories: false,
|
||||
memoryBoundaryMarkers: [],
|
||||
},
|
||||
hooksConfig: { enabled: false },
|
||||
privacy: { usageStatisticsEnabled: false },
|
||||
security: {
|
||||
environmentVariableRedaction: { allowed: [], blocked: [...GEMINI_PRODUCER_BLOCKED_ENVIRONMENT], enabled: true },
|
||||
folderTrust: { enabled: false },
|
||||
toolSandboxing: false,
|
||||
},
|
||||
skills: { enabled: false },
|
||||
telemetry: { enabled: false, logPrompts: false },
|
||||
tools: { allowed: tools, core: tools, sandbox: false },
|
||||
};
|
||||
}
|
||||
|
||||
export function prepareGeminiProducerState(stateDirectory: string, helperLauncher: string): GeminiProducerPaths {
|
||||
const paths = geminiProducerPaths(stateDirectory);
|
||||
if (fs.existsSync(paths.root)) throw new Error('GEMINI_PRODUCER_STATE_EXISTS');
|
||||
fs.mkdirSync(paths.root, { mode: 0o700 });
|
||||
fs.mkdirSync(paths.home, { mode: 0o700 });
|
||||
fs.mkdirSync(paths.workdir, { mode: 0o700 });
|
||||
const contextFileName = `.gstack-cso-context-${randomBytes(16).toString('hex')}.md`;
|
||||
atomicWriteSync(paths.systemDefaults, '{}\n', { mode: 0o600, noReplace: true });
|
||||
atomicWriteSync(paths.systemSettings, `${JSON.stringify(geminiProducerSystemSettings(contextFileName, helperLauncher), null, 2)}\n`, { mode: 0o600, noReplace: true });
|
||||
return paths;
|
||||
}
|
||||
|
||||
export function removeGeminiProducerState(stateDirectory: string): void {
|
||||
const paths = geminiProducerPaths(stateDirectory);
|
||||
fs.rmSync(paths.root, { recursive: true, force: true });
|
||||
}
|
||||
|
||||
export function geminiExecArgs(opts: RunOpts): string[] {
|
||||
const stateDirectory = csoProducerStateDirectory(opts);
|
||||
const args = ['-p', opts.prompt, '--output-format', 'stream-json'];
|
||||
if (stateDirectory) {
|
||||
if (opts.extraArgs?.length) throw new Error('CSO producer does not accept extra provider arguments');
|
||||
args.push(
|
||||
'--approval-mode', 'yolo',
|
||||
'--include-directories', geminiProducerPaths(stateDirectory).workdir,
|
||||
'-e', 'none',
|
||||
);
|
||||
} else {
|
||||
args.push('--yolo');
|
||||
}
|
||||
const args = ['-p', opts.prompt, '--output-format', 'stream-json', '--yolo'];
|
||||
if (opts.model) args.push('--model', opts.model);
|
||||
if (opts.extraArgs) args.push(...opts.extraArgs);
|
||||
return args;
|
||||
}
|
||||
|
||||
export function geminiExecWorkingDirectory(opts: RunOpts): string {
|
||||
const stateDirectory = csoProducerStateDirectory(opts);
|
||||
return stateDirectory ? geminiProducerPaths(stateDirectory).workdir : opts.workdir;
|
||||
}
|
||||
|
||||
export function geminiExecEnvironment(
|
||||
opts: RunOpts,
|
||||
source: NodeJS.ProcessEnv = process.env,
|
||||
): Record<string, string> {
|
||||
const stateDirectory = csoProducerStateDirectory(opts);
|
||||
const paths = stateDirectory ? geminiProducerPaths(stateDirectory) : undefined;
|
||||
const env = paths ? csoProducerChildEnvironment('gemini', source) : { ...source } as Record<string, string>;
|
||||
export function geminiExecEnvironment(source: NodeJS.ProcessEnv = process.env): Record<string, string> {
|
||||
const env = { ...source } as Record<string, string>;
|
||||
// Prefer GEMINI_API_KEY when only that is set (CLI reads both).
|
||||
if (env.GEMINI_API_KEY && !env.GOOGLE_API_KEY) env.GOOGLE_API_KEY = env.GEMINI_API_KEY;
|
||||
if (paths) {
|
||||
env.HOME = paths.home;
|
||||
env.GSTACK_HOME = csoProducerHelperHome(opts)!;
|
||||
env.GEMINI_SANDBOX = 'false';
|
||||
env.GEMINI_TELEMETRY_ENABLED = 'false';
|
||||
env.GEMINI_TELEMETRY_LOG_PROMPTS = 'false';
|
||||
env.GEMINI_CLI_TRUST_WORKSPACE = 'true';
|
||||
env.GEMINI_SYSTEM_MD = 'false';
|
||||
env.GEMINI_WRITE_SYSTEM_MD = 'false';
|
||||
env.GEMINI_CLI_HOME = paths.home;
|
||||
env.GEMINI_CLI_SYSTEM_DEFAULTS_PATH = paths.systemDefaults;
|
||||
env.GEMINI_CLI_SYSTEM_SETTINGS_PATH = paths.systemSettings;
|
||||
}
|
||||
return env;
|
||||
}
|
||||
+10
-123
@@ -1,11 +1,4 @@
|
||||
import {
|
||||
csoProducerChildEnvironment,
|
||||
csoProducerHelperGeneration,
|
||||
csoProducerHelperHome,
|
||||
csoProducerProviderCommand,
|
||||
csoProducerSourceDirectory,
|
||||
csoProducerStateDirectory,
|
||||
CSO_PRODUCER_SHELL_ENV,
|
||||
type ProviderAdapter,
|
||||
type RunOpts,
|
||||
type RunResult,
|
||||
@@ -17,7 +10,6 @@ import * as fs from 'fs';
|
||||
import * as path from 'path';
|
||||
import * as os from 'os';
|
||||
import { CODEX_FRONTIER_MODEL } from '../../../scripts/resolvers/constants';
|
||||
import { atomicWriteSync } from '../../../lib/fs-atomic';
|
||||
|
||||
/**
|
||||
* GPT adapter — wraps the OpenAI `codex` CLI (codex exec with --json output).
|
||||
@@ -30,40 +22,32 @@ export class GptAdapter implements ProviderAdapter {
|
||||
readonly name = 'gpt';
|
||||
readonly family = 'gpt' as const;
|
||||
|
||||
async available(opts?: RunOpts): Promise<AvailabilityCheck> {
|
||||
const producerCommand = csoProducerProviderCommand(opts ?? { prompt: '', workdir: '/', timeoutMs: 1 });
|
||||
const res = producerCommand ? { status: 0 } : spawnSync('sh', ['-c', 'command -v codex'], { timeout: 2000 });
|
||||
async available(): Promise<AvailabilityCheck> {
|
||||
const res = spawnSync('sh', ['-c', 'command -v codex'], { timeout: 2000 });
|
||||
if (res.status !== 0) {
|
||||
return { ok: false, reason: 'codex CLI not found on PATH. Install: npm i -g @openai/codex' };
|
||||
}
|
||||
// Auth sniff: ~/.codex/ should contain auth state after `codex login`
|
||||
const codexDir = path.join(os.homedir(), '.codex');
|
||||
const hasFileAuth = !opts?.csoProducer && fs.existsSync(codexDir);
|
||||
const hasFileAuth = fs.existsSync(codexDir);
|
||||
if (!hasFileAuth && !process.env.OPENAI_API_KEY) {
|
||||
return { ok: false, reason: 'No Codex auth found. Paid CSO producers require OPENAI_API_KEY; other evals may use `codex login`.' };
|
||||
return { ok: false, reason: 'No Codex auth found. Run `codex login` or export OPENAI_API_KEY.' };
|
||||
}
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
async run(opts: RunOpts): Promise<RunResult> {
|
||||
const start = Date.now();
|
||||
// Existing callers retain `-s read-only`. CSO producer calls use an isolated
|
||||
// CODEX_HOME with a reviewed permission profile written below.
|
||||
const model = opts.model ?? process.env.GSTACK_CODEX_MODEL ?? CODEX_FRONTIER_MODEL;
|
||||
const stateDirectory = csoProducerStateDirectory(opts);
|
||||
|
||||
try {
|
||||
if (stateDirectory) prepareCodexProducerState(opts);
|
||||
const args = codexExecArgs(opts, model);
|
||||
const command = csoProducerProviderCommand(opts);
|
||||
const out = execFileSync(command?.executable ?? 'codex', [...(command?.argsPrefix ?? []), ...args], {
|
||||
cwd: codexExecWorkingDirectory(opts),
|
||||
const out = execFileSync('codex', codexExecArgs(opts, model), {
|
||||
cwd: opts.workdir,
|
||||
timeout: opts.timeoutMs,
|
||||
encoding: 'utf-8',
|
||||
maxBuffer: 32 * 1024 * 1024,
|
||||
...(opts.csoProducer ? { env: codexExecEnvironment(opts, process.env) } : {}),
|
||||
});
|
||||
return resultFromCodexStream(out,{model,durationMs:Date.now()-start,producer:!!opts.csoProducer});
|
||||
return resultFromCodexStream(out,{model,durationMs:Date.now()-start});
|
||||
} catch (err: unknown) {
|
||||
const durationMs = Date.now() - start;
|
||||
const e = err as { code?: string; stderr?: Buffer; signal?: string; message?: string };
|
||||
@@ -78,8 +62,6 @@ export class GptAdapter implements ProviderAdapter {
|
||||
return this.emptyResult(durationMs, { code: 'rate_limit', reason: stderr.slice(0, 400) }, model);
|
||||
}
|
||||
return this.emptyResult(durationMs, { code: 'unknown', reason: (e.message ?? stderr ?? 'unknown').slice(0, 400) }, model);
|
||||
} finally {
|
||||
if (stateDirectory) removeCodexProducerState(stateDirectory);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -100,11 +82,11 @@ export class GptAdapter implements ProviderAdapter {
|
||||
}
|
||||
|
||||
/**
|
||||
* Map `codex exec --json` output while requiring evidence-bearing text for paid producers.
|
||||
* Map `codex exec --json` output.
|
||||
* Codex reports cached_input_tokens as a subset of input_tokens; split them so
|
||||
* tokens.input is uncached-only and tokens.cached is the disjoint cache-read count.
|
||||
*/
|
||||
export function resultFromCodexStream(raw:string,opts:{model?:string;durationMs?:number;producer?:boolean}={}):RunResult{
|
||||
export function resultFromCodexStream(raw:string,opts:{model?:string;durationMs?:number}={}):RunResult{
|
||||
let output='',input=0,cached=0,out=0,toolCalls=0,modelUsed:string|undefined;
|
||||
for(const line of raw.split('\n')){
|
||||
const text=line.trim();if(!text)continue;
|
||||
@@ -120,107 +102,12 @@ export function resultFromCodexStream(raw:string,opts:{model?:string;durationMs?
|
||||
}catch{/* Codex can mix diagnostic text into the JSONL stream. */}
|
||||
}
|
||||
const durationMs=opts.durationMs??0,resolvedModel=modelUsed||opts.model||CODEX_FRONTIER_MODEL;
|
||||
if(opts.producer&&!output.trim())return{output:'',tokens:{input:0,output:0},durationMs,toolCalls:0,modelUsed:resolvedModel,error:{code:'unknown',reason:'empty output from codex CLI (exit 0)'}};
|
||||
return{output,tokens:{input,cached,output:out},durationMs,toolCalls,modelUsed:resolvedModel};
|
||||
}
|
||||
|
||||
export interface CodexProducerPaths {
|
||||
root: string;
|
||||
home: string;
|
||||
workdir: string;
|
||||
config: string;
|
||||
}
|
||||
|
||||
export function codexProducerPaths(stateDirectory: string): CodexProducerPaths {
|
||||
const root = path.join(stateDirectory, 'codex-provider');
|
||||
return { root, home: path.join(root, 'home'), workdir: path.join(root, 'work'), config: path.join(root, 'home', 'config.toml') };
|
||||
}
|
||||
|
||||
export function codexProducerConfig(opts: RunOpts): string {
|
||||
const launcher = opts.csoProducer?.helperLauncher;
|
||||
if (!launcher) throw new Error('CSO producer helper launcher is required');
|
||||
const sourceDirectory = csoProducerSourceDirectory(opts);
|
||||
if (!sourceDirectory) throw new Error('CSO producer source directory is required');
|
||||
const helperHome = csoProducerHelperHome(opts);
|
||||
if (!helperHome) throw new Error('CSO producer helper home is required');
|
||||
const generation = csoProducerHelperGeneration(opts);
|
||||
if (!generation) throw new Error('CSO producer helper generation is required');
|
||||
const directory = path.dirname(launcher), suffix = process.platform === 'win32' ? '.exe' : '';
|
||||
const trustedArtifacts = [
|
||||
path.join(directory, `cso-eval-producer${suffix}`), launcher,
|
||||
path.join(directory, `gstack-cso-core${suffix}`), path.join(directory, `gstack-cso-watchdog${suffix}`),
|
||||
generation,
|
||||
];
|
||||
const grants = [...trustedArtifacts, sourceDirectory].map(file => `${JSON.stringify(file)} = "read"`).join('\n');
|
||||
return `approval_policy = "never"
|
||||
default_permissions = "cso-producer"
|
||||
allow_login_shell = false
|
||||
check_for_update_on_startup = false
|
||||
|
||||
[shell_environment_policy]
|
||||
inherit = "all"
|
||||
include_only = ${JSON.stringify(CSO_PRODUCER_SHELL_ENV)}
|
||||
ignore_default_excludes = false
|
||||
experimental_use_profile = false
|
||||
|
||||
[permissions.cso-producer]
|
||||
description = "CSO producer: private state plus one immutable source snapshot"
|
||||
|
||||
[permissions.cso-producer.filesystem]
|
||||
":root" = "deny"
|
||||
":minimal" = "read"
|
||||
${grants}
|
||||
${JSON.stringify(helperHome)} = "write"
|
||||
|
||||
[permissions.cso-producer.filesystem.":workspace_roots"]
|
||||
"." = "write"
|
||||
|
||||
[permissions.cso-producer.network]
|
||||
enabled = false
|
||||
`;
|
||||
}
|
||||
|
||||
export function prepareCodexProducerState(opts: RunOpts): CodexProducerPaths {
|
||||
const stateDirectory = csoProducerStateDirectory(opts);
|
||||
if (!stateDirectory) throw new Error('CSO producer state directory is required');
|
||||
const paths = codexProducerPaths(stateDirectory);
|
||||
if (fs.existsSync(paths.root)) throw new Error('CODEX_PRODUCER_STATE_EXISTS');
|
||||
fs.mkdirSync(paths.root, { mode: 0o700 });
|
||||
fs.mkdirSync(paths.home, { mode: 0o700 });
|
||||
fs.mkdirSync(paths.workdir, { mode: 0o700 });
|
||||
atomicWriteSync(paths.config, codexProducerConfig(opts), { mode: 0o600, noReplace: true });
|
||||
return paths;
|
||||
}
|
||||
|
||||
export function removeCodexProducerState(stateDirectory: string): void {
|
||||
fs.rmSync(codexProducerPaths(stateDirectory).root, { recursive: true, force: true });
|
||||
}
|
||||
|
||||
/** Exported so free tests can inspect the exact paid-CLI boundary without running it. */
|
||||
export function codexExecArgs(opts: RunOpts, model: string): string[] {
|
||||
const stateDirectory = csoProducerStateDirectory(opts);
|
||||
const args = ['exec', opts.prompt, '-C', stateDirectory ? codexProducerPaths(stateDirectory).workdir : opts.workdir];
|
||||
if (stateDirectory) {
|
||||
if (opts.extraArgs?.length) throw new Error('CSO producer does not accept extra provider arguments');
|
||||
args.push(
|
||||
'--strict-config', '--ephemeral', '--ignore-rules', '--skip-git-repo-check',
|
||||
);
|
||||
} else {
|
||||
args.push('-s', 'read-only', '--skip-git-repo-check');
|
||||
}
|
||||
args.push('--json', '-m', model);
|
||||
const args = ['exec', opts.prompt, '-C', opts.workdir, '-s', 'read-only', '--skip-git-repo-check', '--json', '-m', model];
|
||||
if (opts.extraArgs) args.push(...opts.extraArgs);
|
||||
return args;
|
||||
}
|
||||
|
||||
export function codexExecWorkingDirectory(opts: RunOpts): string {
|
||||
const stateDirectory = csoProducerStateDirectory(opts);
|
||||
return stateDirectory ? codexProducerPaths(stateDirectory).workdir : opts.workdir;
|
||||
}
|
||||
|
||||
export function codexExecEnvironment(opts: RunOpts, source: NodeJS.ProcessEnv = process.env): Record<string, string> {
|
||||
if (!opts.csoProducer) return source as Record<string, string>;
|
||||
const stateDirectory = csoProducerStateDirectory(opts)!;
|
||||
const paths = codexProducerPaths(stateDirectory);
|
||||
return { ...csoProducerChildEnvironment('gpt', source), HOME: paths.home, CODEX_HOME: paths.home, GSTACK_HOME: csoProducerHelperHome(opts)! };
|
||||
}
|
||||
@@ -1,5 +1,3 @@
|
||||
import * as path from 'node:path';
|
||||
|
||||
/**
|
||||
* Provider adapter interface — uniform contract for Claude, GPT, Gemini.
|
||||
*
|
||||
@@ -20,19 +18,6 @@ export interface RunOpts {
|
||||
model?: string;
|
||||
/** Extra flags per-provider (escape hatch for rare cases). Prefer staying generic. */
|
||||
extraArgs?: string[];
|
||||
/** Producer-only execution policy. Omit to preserve each adapter's defaults. */
|
||||
csoProducer?: {
|
||||
/** The one explicit state directory exposed outside the source worktree. */
|
||||
stateDirectory: string;
|
||||
/** Exact validated per-cell source root. Providers may grant only this path read-only. */
|
||||
sourceDirectory: string;
|
||||
/** Absolute immutable launcher path admitted by the producer. */
|
||||
helperLauncher: string;
|
||||
/** Exact adjacent generation manifest read by the launcher. */
|
||||
helperGeneration: string;
|
||||
/** Exact provider command whose bytes/version are bound into the receipt. */
|
||||
providerCommand: { executable: string; argsPrefix: string[] };
|
||||
};
|
||||
}
|
||||
|
||||
export interface TokenUsage {
|
||||
@@ -51,14 +36,6 @@ export type RunError =
|
||||
| 'binary_missing' // CLI not found on PATH.
|
||||
| 'unknown'; // Catch-all with reason populated.
|
||||
|
||||
export interface ToolTimelineEntry {
|
||||
atMs: number;
|
||||
/** Set when the call's tool_result arrived; absent for a call still running when the stream ended. */
|
||||
endMs?: number;
|
||||
tool: string;
|
||||
agent: 'main' | 'subagent';
|
||||
}
|
||||
|
||||
export interface RunResult {
|
||||
/** Provider's textual output for the prompt. */
|
||||
output: string;
|
||||
@@ -68,8 +45,6 @@ export interface RunResult {
|
||||
durationMs: number;
|
||||
/** Count of tool/function calls made during the run (0 if unsupported). */
|
||||
toolCalls: number;
|
||||
/** Tool calls in start order: name, start and end offsets from run start, and thread; no inputs or outputs. Unset if unsupported. */
|
||||
toolTimeline?: ToolTimelineEntry[];
|
||||
/** Actual model ID the provider reports using (may be a variant of the family). */
|
||||
modelUsed: string;
|
||||
/** Every model the CLI billed during the run (Claude CLI `modelUsage` keys). Unset if unreported. */
|
||||
@@ -86,89 +61,6 @@ export interface AvailabilityCheck {
|
||||
|
||||
export type Family = 'claude' | 'gpt' | 'gemini';
|
||||
|
||||
export const CSO_PRODUCER_SHELL_ENV = [
|
||||
'PATH', 'HOME', 'LANG', 'LC_ALL', 'TZ',
|
||||
'GSTACK_HOME', 'GSTACK_SESSION_KIND', 'GSTACK_HEADLESS',
|
||||
] as const;
|
||||
const CSO_AUTH_ENV: Record<Family, readonly string[]> = {
|
||||
claude: ['ANTHROPIC_API_KEY', 'CLAUDE_CODE_OAUTH_TOKEN'],
|
||||
gpt: ['OPENAI_API_KEY'],
|
||||
gemini: ['GEMINI_API_KEY', 'GOOGLE_API_KEY', 'GOOGLE_CLOUD_PROJECT', 'GOOGLE_CLOUD_LOCATION'],
|
||||
};
|
||||
|
||||
export function validateCsoProducerStateDirectory(stateDirectory: string): string {
|
||||
if (!path.isAbsolute(stateDirectory) || path.normalize(stateDirectory) !== stateDirectory) {
|
||||
throw new Error('CSO producer state directory must be an absolute normalized path');
|
||||
}
|
||||
return stateDirectory;
|
||||
}
|
||||
|
||||
export function csoProducerStateDirectory(opts: RunOpts): string | undefined {
|
||||
if (!opts.csoProducer) return undefined;
|
||||
csoProducerHelperLauncher(opts);
|
||||
csoProducerHelperGeneration(opts);
|
||||
csoProducerSourceDirectory(opts);
|
||||
csoProducerProviderCommand(opts);
|
||||
return validateCsoProducerStateDirectory(opts.csoProducer.stateDirectory);
|
||||
}
|
||||
|
||||
export function csoProducerSourceDirectory(opts: RunOpts): string | undefined {
|
||||
if (!opts.csoProducer) return undefined;
|
||||
return validateCsoProducerStateDirectory(opts.csoProducer.sourceDirectory);
|
||||
}
|
||||
|
||||
export function csoProducerHelperHome(opts: RunOpts): string | undefined {
|
||||
const stateDirectory = csoProducerStateDirectory(opts);
|
||||
return stateDirectory ? path.join(stateDirectory, 'cso-home') : undefined;
|
||||
}
|
||||
|
||||
export function csoProducerProviderCommand(opts: RunOpts): { executable: string; argsPrefix: string[] } | undefined {
|
||||
if (!opts.csoProducer) return undefined;
|
||||
const command = opts.csoProducer.providerCommand;
|
||||
if (!command || !path.isAbsolute(command.executable) || path.normalize(command.executable) !== command.executable ||
|
||||
!Array.isArray(command.argsPrefix) || command.argsPrefix.some(value => typeof value !== 'string' || value.includes('\0'))) {
|
||||
throw new Error('CSO producer provider command must be an absolute normalized trusted path');
|
||||
}
|
||||
return { executable: command.executable, argsPrefix: [...command.argsPrefix] };
|
||||
}
|
||||
|
||||
export function csoProducerHelperLauncher(opts: RunOpts): string | undefined {
|
||||
if (!opts.csoProducer) return undefined;
|
||||
const launcher = opts.csoProducer.helperLauncher;
|
||||
if (typeof launcher !== 'string') throw new Error('CSO producer helper launcher must be an absolute normalized trusted path');
|
||||
const suffix = process.platform === 'win32' ? '.exe' : '';
|
||||
if (!path.isAbsolute(launcher) || path.normalize(launcher) !== launcher || path.basename(launcher) !== `gstack-cso-launcher${suffix}` ||
|
||||
!/^[A-Za-z0-9_./:\\-]+$/.test(launcher)) {
|
||||
throw new Error('CSO producer helper launcher must be an absolute normalized trusted path');
|
||||
}
|
||||
return launcher;
|
||||
}
|
||||
|
||||
export function csoProducerHelperGeneration(opts: RunOpts): string | undefined {
|
||||
if (!opts.csoProducer) return undefined;
|
||||
const generation = opts.csoProducer.helperGeneration;
|
||||
const launcher = csoProducerHelperLauncher(opts);
|
||||
if (typeof generation !== 'string' || !path.isAbsolute(generation) || path.normalize(generation) !== generation ||
|
||||
path.basename(generation) !== '.gstack-cso-generation' || path.dirname(generation) !== path.dirname(launcher!) ||
|
||||
!/^[A-Za-z0-9_./:\\-]+$/.test(generation)) {
|
||||
throw new Error('CSO producer helper generation must be the exact adjacent absolute normalized trusted path');
|
||||
}
|
||||
return generation;
|
||||
}
|
||||
|
||||
/** Copy only execution inputs needed by the selected producer host. */
|
||||
export function csoProducerChildEnvironment(
|
||||
family: Family,
|
||||
source: NodeJS.ProcessEnv = process.env,
|
||||
): Record<string, string> {
|
||||
const output: Record<string, string> = {};
|
||||
for (const key of [...CSO_PRODUCER_SHELL_ENV, ...CSO_AUTH_ENV[family]]) {
|
||||
const value = source[key];
|
||||
if (typeof value === 'string' && !value.includes('\0')) output[key] = value;
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
export interface ProviderAdapter {
|
||||
/** Stable name used in output tables and config (e.g., 'claude', 'gpt', 'gemini'). */
|
||||
readonly name: string;
|
||||
|
||||
@@ -613,11 +613,6 @@ export const E2E_TOUCHFILES: Record<string, string[]> = {
|
||||
'retro': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'bin/gstack-retro-metrics', 'lib/retro-friction.ts', 'retro/**', 'test/skill-e2e-retro.test.ts'],
|
||||
'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', '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'],
|
||||
'learnings-show': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'learn/**', 'bin/gstack-learnings-search', 'bin/gstack-learnings-log', 'scripts/resolvers/learnings.ts', 'test/skill-e2e-learnings.test.ts'],
|
||||
@@ -1077,7 +1072,6 @@ export const E2E_TOUCHFILES: Record<string, string[]> = {
|
||||
'test/helpers/arm-benchmark-harness.ts',
|
||||
'test/helpers/providers/gateway.ts',
|
||||
'test/helpers/providers/claude.ts',
|
||||
'test/helpers/providers/claude-stream.ts',
|
||||
'test/helpers/providers/types.ts',
|
||||
'test/helpers/pricing.ts',
|
||||
'lib/pricing.ts',
|
||||
@@ -1091,7 +1085,6 @@ export const E2E_TOUCHFILES: Record<string, string[]> = {
|
||||
'test/helpers/arm-benchmark-harness.ts',
|
||||
'test/helpers/providers/gateway.ts',
|
||||
'test/helpers/providers/claude.ts',
|
||||
'test/helpers/providers/claude-stream.ts',
|
||||
'test/helpers/providers/types.ts',
|
||||
'test/helpers/pricing.ts',
|
||||
'lib/pricing.ts',
|
||||
@@ -1105,7 +1098,6 @@ export const E2E_TOUCHFILES: Record<string, string[]> = {
|
||||
'test/helpers/arm-benchmark-harness.ts',
|
||||
'test/helpers/providers/gateway.ts',
|
||||
'test/helpers/providers/claude.ts',
|
||||
'test/helpers/providers/claude-stream.ts',
|
||||
'test/helpers/providers/types.ts',
|
||||
'test/helpers/pricing.ts',
|
||||
'lib/pricing.ts',
|
||||
@@ -1119,7 +1111,6 @@ export const E2E_TOUCHFILES: Record<string, string[]> = {
|
||||
'test/helpers/arm-benchmark-harness.ts',
|
||||
'test/helpers/providers/gateway.ts',
|
||||
'test/helpers/providers/claude.ts',
|
||||
'test/helpers/providers/claude-stream.ts',
|
||||
'test/helpers/providers/types.ts',
|
||||
'test/helpers/pricing.ts',
|
||||
'lib/pricing.ts',
|
||||
@@ -1133,7 +1124,6 @@ export const E2E_TOUCHFILES: Record<string, string[]> = {
|
||||
'test/helpers/arm-benchmark-harness.ts',
|
||||
'test/helpers/providers/gateway.ts',
|
||||
'test/helpers/providers/claude.ts',
|
||||
'test/helpers/providers/claude-stream.ts',
|
||||
'test/helpers/providers/types.ts',
|
||||
'test/helpers/pricing.ts',
|
||||
'lib/pricing.ts',
|
||||
@@ -1433,11 +1423,6 @@ export const E2E_TIERS: Record<string, 'gate' | 'periodic' | 'marathon'> = {
|
||||
'retro': 'periodic',
|
||||
'retro-base-branch': 'gate',
|
||||
|
||||
// CSO — gate for security guardrails, periodic for quality
|
||||
'cso-full-audit': 'periodic', // D2a demotion 2026-08: 250s/$0.57 full audit; cso targeted tests stay gate
|
||||
'cso-diff-mode': 'gate',
|
||||
'cso-infra-scope': 'periodic',
|
||||
|
||||
// Learnings — gate (functional guardrail: seeded learnings must appear)
|
||||
'learnings-show': 'gate',
|
||||
'write-skill-add-lesson': 'periodic',
|
||||
@@ -1799,9 +1784,6 @@ export const E2E_KINDS: Record<string, 'rule' | 'behavior' | 'judge'> = {
|
||||
'docsync-spawned': 'rule',
|
||||
'retro': 'rule',
|
||||
'retro-base-branch': 'rule',
|
||||
'cso-full-audit': 'rule',
|
||||
'cso-diff-mode': 'rule',
|
||||
'cso-infra-scope': 'rule',
|
||||
'learnings-show': 'rule',
|
||||
'write-skill-add-lesson': 'rule',
|
||||
// GSTA-228 planning wave.
|
||||
|
||||
@@ -146,13 +146,6 @@ describe.skipIf(process.platform === 'win32')('host conformance kit', () => {
|
||||
if (existsSync(md)) expect(readSkillStartup(md), `${host}/${name} carries Claude paths`).not.toContain('~/.claude/skills/gstack');
|
||||
}
|
||||
}
|
||||
// #2906: /cso skips the shared preamble, so it names its launcher by the
|
||||
// host's literal install path; that path must reach this install's bin/.
|
||||
const cso = ['cso', 'gstack-cso'].find(n => existsSync(join(dest, n, 'SKILL.md')));
|
||||
expect(cso, `${host} cso skill`).toBeDefined();
|
||||
const launcher = readFileSync(join(dest, cso!, 'SKILL.md'), 'utf8').match(/Use `([^`]+)\/gstack-cso-launcher\[\.exe\]`/);
|
||||
expect(launcher, `${host} cso names its launcher`).not.toBeNull();
|
||||
expect(realpathSync(launcher![1].replace(/^~(?=\/)/, f.home)), `${host} cso launcher dir`).toBe(realpathSync(join(src, 'bin')));
|
||||
const rows = registryRows(f);
|
||||
expect(rows.map(row => [row[0], row[1], row[3], row[5], row[6]])).toEqual([[host, 'global', dest, realpathSync(src), readFileSync(join(src, 'VERSION'), 'utf8').trim()]]);
|
||||
expect(r.stdout + r.stderr).toMatch(new RegExp(`Install summary:[\\s\\S]*\\b${host}\\s+\\S+\\s+global\\s+installed`));
|
||||
@@ -481,7 +474,6 @@ describe.skipIf(process.platform === 'win32')('host conformance kit', () => {
|
||||
expect(claude).toContain(`\n${src}/bin/gstack-skill-start --skill "review" --model "claude"\n`);
|
||||
const codex = readFileSync(join(codexHome, 'skills/gstack-review/SKILL.md'), 'utf8');
|
||||
expect(codex).toContain(`GSTACK_ROOT="${codexHome}/skills/gstack"`);
|
||||
expect(readFileSync(join(codexHome, 'skills/gstack-cso/SKILL.md'), 'utf8')).toContain(`Use \`${codexHome}/skills/gstack/bin/gstack-cso-launcher[.exe]\``);
|
||||
expect(realpathSync(join(codexHome, 'skills/gstack/bin'))).toBe(realpathSync(join(src, 'bin')));
|
||||
const rows = registryRows(f);
|
||||
expect(rows.map(r => [r[0], r[8].startsWith(join(f.home, '.gstack/render/installs/'))]).sort()).toEqual([['claude', true], ['codex', true]]);
|
||||
|
||||
@@ -55,7 +55,7 @@ describe('the ledger covers every key and validates', () => {
|
||||
const backlog: string[] = JSON.parse(fs.readFileSync(path.join(ROOT, 'test', 'fixtures', 'inventory-grandfathered.json'), 'utf8')).keys;
|
||||
for (const key of backlog) expect([key, ledger.parts[key]?.grandfathered]).toEqual([key, true]);
|
||||
for (const [key, row] of Object.entries<any>(ledger.parts)) if (row.grandfathered) expect(backlog).toContain(key);
|
||||
for (const key of ['careful', 'freeze', 'guard', 'unfreeze', 'cso']) expect(ledger.parts[key].status).toBe('safety');
|
||||
for (const key of ['careful', 'freeze', 'guard', 'unfreeze']) expect(ledger.parts[key].status).toBe('safety');
|
||||
for (const key of ['capy-skill', 'capy-factory']) expect(ledger.parts[key]).toMatchObject({ status: 'untested', plan: 'none' });
|
||||
});
|
||||
|
||||
|
||||
@@ -9,7 +9,10 @@
|
||||
* The periodic fixture is re-shaped to the current case shards: qa-workflow runs
|
||||
* as its qa-fix-loop case shard (its three gate-tier siblings become sibling
|
||||
* deselections) and the review carve runs as a case of the consolidated
|
||||
* test/carve-section-loading.test.ts.
|
||||
* test/carve-section-loading.test.ts. With /cso removed (GST-3920), its
|
||||
* multi-case shard is re-shaped to test/skill-e2e-shared-libs-periodic.test.ts
|
||||
* (two in-lane cases) in the periodic fixture and test/skill-e2e-retro.test.ts
|
||||
* (one gate case, one periodic sibling) in the gate fixture.
|
||||
*/
|
||||
import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
|
||||
import * as fs from 'node:fs';
|
||||
@@ -48,15 +51,15 @@ describe('census attribution from the 2026-10-03 artifacts', () => {
|
||||
expect(r.status, r.out).toBe(0);
|
||||
expect(r.out).toContain(' rule 7/7 · behavior 0/0 · judge 0/0 · quarantined 0 (0 failing the lane)');
|
||||
expect(r.out).toContain(' SKIPPED 0 · INFRA 0 · INCOMPLETE 0 · unattributed 0 · ACTION REQUIRED 0');
|
||||
expect(r.out).toContain(`deselected testcases, zero credit (21):`);
|
||||
expect(r.out).toContain(`deselected testcases, zero credit (20):`);
|
||||
expect(r.out).toContain(` 13 ${DESELECTION_REASONS.sibling}`);
|
||||
expect(r.out).toContain(' 4 gate-tier case (this lane runs periodic)');
|
||||
expect(r.out).toContain(' 3 gate-tier case (this lane runs periodic)');
|
||||
expect(r.out).toContain(` 4 ${DESELECTION_REASONS.hook}`);
|
||||
expect(r.out).toContain(' ⚠ test/skill-e2e-test-value.test.ts (3 skipped — 3 gate-tier case (this lane runs periodic))');
|
||||
expect(r.out).not.toContain('UNATTRIBUTED');
|
||||
expect(r.history.map(record => `${record.case}:${record.outcome}`).sort()).toEqual([
|
||||
'benchmark-providers-live:passed', 'carve-section-loading-review:passed', 'codex-recommendation-substance:passed',
|
||||
'cso-full-audit:passed', 'cso-infra-scope:passed', 'design-consultation-core:passed', 'qa-fix-loop:passed',
|
||||
'design-consultation-core:passed', 'qa-fix-loop:passed', 'shared-libs-plan-callers:passed', 'shared-libs-pr-coverage:passed',
|
||||
]);
|
||||
expect(r.history.find(record => record.case === 'benchmark-providers-live')).toMatchObject({ file: 'test/skill-e2e-benchmark-providers.test.ts', source: 'junit' });
|
||||
expect(r.history.filter(record => record.file === 'test/skill-e2e-design.test.ts'))
|
||||
@@ -69,29 +72,29 @@ describe('census attribution from the 2026-10-03 artifacts', () => {
|
||||
expect(r.status, r.out).toBe(0);
|
||||
expect(r.out).toContain(' rule 2/2 · behavior 0/0 · judge 0/0 · quarantined 0 (0 failing the lane)');
|
||||
expect(r.out).toContain(' SKIPPED 0 · INFRA 0 · INCOMPLETE 0 · unattributed 0 · ACTION REQUIRED 0');
|
||||
expect(r.out).toContain(' 16 periodic-tier case (this lane runs gate)');
|
||||
expect(r.out).toContain(' 15 periodic-tier case (this lane runs gate)');
|
||||
expect(r.out).toContain(` 2 ${DESELECTION_REASONS.hook}`);
|
||||
expect(r.out).toContain(` ⚠ test/skill-e2e-qa-bugs.test.ts (5 skipped — 2 ${DESELECTION_REASONS.hook}; 3 periodic-tier case (this lane runs gate))`);
|
||||
expect(r.history.map(record => `${record.case}:${record.outcome}`).sort()).toEqual(['cso-diff-mode:passed', 'plan-mode-no-op:passed']);
|
||||
expect(r.history.map(record => `${record.case}:${record.outcome}`).sort()).toEqual(['plan-mode-no-op:passed', 'retro-base-branch:passed']);
|
||||
});
|
||||
|
||||
test('a selected in-lane case that skipped is SKIPPED with its reason; an unattributable testcase is listed by name', () => {
|
||||
const r = report('periodic', dir => {
|
||||
const qa = junit(dir, 'skill-e2e-qa-workflow--qa-fix-loop');
|
||||
fs.writeFileSync(qa, fs.readFileSync(qa, 'utf8').replace(/(<testcase name="qa-fix-loop"[^>]*?) \/>/, '$1><skipped /></testcase>'));
|
||||
const cso = junit(dir, 'skill-e2e-cso');
|
||||
fs.writeFileSync(cso, fs.readFileSync(cso, 'utf8').replace(/<\/testsuite>(\r?\n)<\/testsuites>/,
|
||||
'<testcase name="an unlabeled helper" classname="CSO v3" time="1" file="test/skill-e2e-cso.test.ts" line="9" />$1</testsuite>$1</testsuites>'));
|
||||
const libs = junit(dir, 'skill-e2e-shared-libs-periodic');
|
||||
fs.writeFileSync(libs, fs.readFileSync(libs, 'utf8').replace(/<\/testsuite>(\r?\n)<\/testsuites>/,
|
||||
'<testcase name="an unlabeled helper" classname="/deslop-shared-libs periodic" time="1" file="test/skill-e2e-shared-libs-periodic.test.ts" line="9" />$1</testsuite>$1</testsuites>'));
|
||||
});
|
||||
expect(r.status, r.out).toBe(0);
|
||||
expect(r.out).toContain(' SKIPPED 1 · INFRA 0 · INCOMPLETE 0 · unattributed 1 · ACTION REQUIRED 0');
|
||||
expect(r.out).toContain(`[test:paid] ◌ qa-fix-loop test/skill-e2e-qa-workflow.test.ts#qa-fix-loop (qa-fix-loop): ${RUNTIME_SKIP_REASON}`);
|
||||
expect(r.out).toContain('[test:paid] ? test/skill-e2e-cso.test.ts :: an unlabeled helper (passed)');
|
||||
expect(r.out).toContain('[test:paid] ? test/skill-e2e-shared-libs-periodic.test.ts :: an unlabeled helper (passed)');
|
||||
const summary = fs.readFileSync(path.join(r.dir, 'report-summary.md'), 'utf8');
|
||||
expect(summary).toContain('**Skipped, deselected and unattributed testcases**');
|
||||
expect(summary).toContain('? test/skill-e2e-cso.test.ts :: an unlabeled helper (passed)');
|
||||
expect(summary).toContain('? test/skill-e2e-shared-libs-periodic.test.ts :: an unlabeled helper (passed)');
|
||||
const collector = JSON.parse(fs.readFileSync(path.join(r.dir, 'collector-outcomes.json'), 'utf8'));
|
||||
expect(collector.census.unattributed).toEqual(['test/skill-e2e-cso.test.ts :: an unlabeled helper (passed)']);
|
||||
expect(collector.census.unattributed).toEqual(['test/skill-e2e-shared-libs-periodic.test.ts :: an unlabeled helper (passed)']);
|
||||
expect(collector.census.skipped).toHaveLength(1);
|
||||
expect(collector.verdict.counts).toMatchObject({ skipped: 1, unattributed: 1 });
|
||||
});
|
||||
@@ -114,12 +117,12 @@ describe('a case shard\'s result records are its one case\'s cost (2026-10-26 tr
|
||||
});
|
||||
|
||||
test('a multi-case shard whose records carry display labels keeps those trials cost-unknown instead of guessing', () => {
|
||||
const r = report('periodic', dir => results(dir, 'skill-e2e-cso',
|
||||
[{ name: '/cso full audit', suite: 'cso', tier: 'e2e', passed: true, duration_ms: 1000, cost_usd: 0.5 },
|
||||
{ name: 'cso-infra-scope', suite: 'cso', tier: 'e2e', passed: true, duration_ms: 1000, cost_usd: 0.25 }]));
|
||||
expect(r.history.find(record => record.case === 'cso-full-audit')).toMatchObject({ cost_usd: 0, cost_known: false });
|
||||
expect(r.history.find(record => record.case === 'cso-infra-scope')).toMatchObject({ cost_usd: 0.25 });
|
||||
expect(r.history.find(record => record.case === 'cso-infra-scope').cost_known).toBeUndefined();
|
||||
const r = report('periodic', dir => results(dir, 'skill-e2e-shared-libs-periodic',
|
||||
[{ name: '/deslop-shared-libs pr coverage', suite: 'shared-libs', tier: 'e2e', passed: true, duration_ms: 1000, cost_usd: 0.5 },
|
||||
{ name: 'shared-libs-plan-callers', suite: 'shared-libs', tier: 'e2e', passed: true, duration_ms: 1000, cost_usd: 0.25 }]));
|
||||
expect(r.history.find(record => record.case === 'shared-libs-pr-coverage')).toMatchObject({ cost_usd: 0, cost_known: false });
|
||||
expect(r.history.find(record => record.case === 'shared-libs-plan-callers')).toMatchObject({ cost_usd: 0.25 });
|
||||
expect(r.history.find(record => record.case === 'shared-libs-plan-callers').cost_known).toBeUndefined();
|
||||
expect(collector(r.dir).verdict.costUsd).toBe(0.75);
|
||||
});
|
||||
|
||||
@@ -139,8 +142,8 @@ describe('a case shard\'s result records are its one case\'s cost (2026-10-26 tr
|
||||
|
||||
test('a billed session\'s cost is already in its collector total, so the verdict never adds it again (Codex host, unbound label record)', () => {
|
||||
const r = report('periodic', dir => {
|
||||
results(dir, 'skill-e2e-cso', [{ name: '/cso full audit', suite: 'cso', tier: 'e2e', passed: true, duration_ms: 1, cost_usd: 0.5 }]);
|
||||
fs.writeFileSync(path.join(shard(dir, 'skill-e2e-cso'), 'session-ledger.jsonl'),
|
||||
results(dir, 'skill-e2e-shared-libs-periodic', [{ name: '/deslop-shared-libs pr coverage', suite: 'shared-libs', tier: 'e2e', passed: true, duration_ms: 1, cost_usd: 0.5 }]);
|
||||
fs.writeFileSync(path.join(shard(dir, 'skill-e2e-shared-libs-periodic'), 'session-ledger.jsonl'),
|
||||
JSON.stringify({ key: 'k', runner: 'codex', started_at: 't', elapsed_ms: 1, end: 'completed', billed: true, cost_usd: 0.5 }) + '\n');
|
||||
});
|
||||
expect(collector(r.dir).verdict.costUsd).toBe(0.5);
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
*
|
||||
* Baseline rebased v1.57.7.0 → v1.64.1.0: two parallel v1.64 waves (the
|
||||
* code-smell fix wave and main's #2571) each added shared-preamble prose,
|
||||
* pushing document-release / design-consultation / cso past their ratios on
|
||||
* pushing document-release / design-consultation past their ratios on
|
||||
* the v1.57.7.0 anchor. The v1.64.1.0 baseline captures current UNION sizes
|
||||
* (skeleton + sections/*.md, matching what the harness measures) so the
|
||||
* per-skill ratios still catch future bloat.
|
||||
|
||||
@@ -162,8 +162,6 @@ describe('one-way door safety', () => {
|
||||
'review-sql-safety', // SQL injection path
|
||||
'review-llm-trust-boundary', // LLM trust boundary
|
||||
'review-gate-disposition', // gate edit disposition: never-ask/AUTO_DECIDE must not waive it
|
||||
'cso-global-scan-approval', // scans outside branch
|
||||
'cso-finding-fix', // security finding
|
||||
'land-and-deploy-merge-confirm', // actual merge
|
||||
'land-and-deploy-rollback', // rollback decision
|
||||
'plan-ceo-review-premise-revise', // changing agreed premise
|
||||
@@ -202,7 +200,6 @@ describe('registry breadth', () => {
|
||||
'plan-devex-review',
|
||||
'qa',
|
||||
'land-and-deploy',
|
||||
'cso',
|
||||
];
|
||||
for (const skill of highVolume) {
|
||||
expect(stats.by_skill[skill] ?? 0).toBeGreaterThan(0);
|
||||
@@ -523,8 +520,7 @@ describe('one-way-doors classifier', () => {
|
||||
}
|
||||
});
|
||||
|
||||
test('skill-category fallback fires for cso:approval and land-and-deploy:approval', () => {
|
||||
expect(isOneWayDoor({ skill: 'cso', category: 'approval' })).toBe(true);
|
||||
test('skill-category fallback fires for land-and-deploy:approval', () => {
|
||||
expect(isOneWayDoor({ skill: 'land-and-deploy', category: 'approval' })).toBe(true);
|
||||
});
|
||||
|
||||
@@ -545,8 +541,7 @@ describe('one-way-doors classifier', () => {
|
||||
expect(DESTRUCTIVE_PATTERN_LIST.length).toBeGreaterThan(15);
|
||||
});
|
||||
|
||||
test('skill-category set covers security + deploy', () => {
|
||||
expect(ONE_WAY_SKILL_CATEGORY_SET.has('cso:approval')).toBe(true);
|
||||
test('skill-category set covers deploy', () => {
|
||||
expect(ONE_WAY_SKILL_CATEGORY_SET.has('land-and-deploy:approval')).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -15,7 +15,7 @@ import { generateUpgradeCheck } from '../scripts/resolvers/preamble/generate-upg
|
||||
|
||||
const ROOT = path.resolve(import.meta.dir, '..');
|
||||
const CORE = ['/office-hours', '/review', '/qa', '/gstack-ship'];
|
||||
const NON_CORE_SAMPLE = ['/cso', '/plan-ceo-review', '/design-review', '/retro'];
|
||||
const NON_CORE_SAMPLE = ['/benchmark', '/plan-ceo-review', '/design-review', '/retro'];
|
||||
// The one place the core block may name non-core skills: the rule that says to name them for the user to type.
|
||||
const TYPE_IT_RULE = 'under `core`, name `/browse` for the user to type instead of\ninvoking it.';
|
||||
|
||||
@@ -85,7 +85,7 @@ describe('proactive core set: the one-time prompt and the registry', () => {
|
||||
expect(QUESTIONS['preamble-proactive-behavior'].options).toEqual(['core', 'all', 'off']);
|
||||
});
|
||||
|
||||
test('the first-run and first-loop tips name only core skills (negative control: no /spec or /cso tip; the off gating is proven by running the script in proactive-skill-start.test.ts)', () => {
|
||||
test('the first-run and first-loop tips name only core skills (negative control: no /spec or /benchmark tip; the off gating is proven by running the script in proactive-skill-start.test.ts)', () => {
|
||||
const tips = skillStart.slice(skillStart.indexOf('if [ "$_ACTIVATED" = "no" ]; then'), skillStart.indexOf('# Routing injection'));
|
||||
for (const skill of NON_CORE_SAMPLE.concat(['/spec', '/plan-eng-review'])) expect(tips).not.toContain(skill);
|
||||
for (const skill of CORE) expect(tips).toContain(skill);
|
||||
|
||||
@@ -1,243 +1,37 @@
|
||||
import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
|
||||
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
||||
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { join } from 'node:path';
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import { assertClaudeProducerSandboxPolicy, ClaudeAdapter, claudeExecArgs, claudeExecEnvironment, claudeExecWorkingDirectory, claudeProducerPaths, resultFromClaudeOutput } from './helpers/providers/claude';
|
||||
import { codexExecArgs, codexExecEnvironment, codexExecWorkingDirectory, codexProducerConfig, codexProducerPaths, GptAdapter, resultFromCodexStream } from './helpers/providers/gpt';
|
||||
import { geminiExecArgs, geminiExecEnvironment, geminiExecWorkingDirectory, geminiProducerPaths, geminiProducerSystemSettings } from './helpers/providers/gemini';
|
||||
import { CSO_PRODUCER_SHELL_ENV, csoProducerChildEnvironment } from './helpers/providers/types';
|
||||
import { ClaudeAdapter, claudeExecArgs, claudeExecEnvironment, resultFromClaudeOutput } from './helpers/providers/claude';
|
||||
import { codexExecArgs, GptAdapter } from './helpers/providers/gpt';
|
||||
import { geminiExecArgs, geminiExecEnvironment } from './helpers/providers/gemini';
|
||||
|
||||
const ENV_KEYS = ['PATH', 'GSTACK_CLAUDE_BIN', 'GSTACK_CLAUDE_BIN_ARGS',
|
||||
'GSTACK_CODEX_MODEL', 'EVALS_MODEL', 'GSTACK_EVAL_MODEL', 'GSTACK_EVAL_MODEL_CAPTURE'];
|
||||
let saved: Record<string, string | undefined>;
|
||||
let workdir: string;
|
||||
|
||||
describe('CSO producer provider policies', () => {
|
||||
const suffix = process.platform === 'win32' ? '.exe' : '';
|
||||
const helperAt = (directory: string) => join(directory, `gstack-cso-launcher${suffix}`);
|
||||
const providerAt = (directory: string) => ({ executable: join(directory, `provider${suffix}`), argsPrefix: [] as string[] });
|
||||
const policy = (stateDirectory: string, sourceDirectory: string, helperLauncher: string) => ({
|
||||
stateDirectory, sourceDirectory, helperLauncher, helperGeneration: join(dirname(helperLauncher), '.gstack-cso-generation'), providerCommand: providerAt(dirname(helperLauncher)),
|
||||
});
|
||||
|
||||
test('keeps exact Codex read-only defaults and gives the producer a custom least-privilege profile', () => {
|
||||
const providerWorkdir = join(tmpdir(), 'gstack-provider-work');
|
||||
const common = { prompt: 'Reply OK', workdir: providerWorkdir, timeoutMs: 5000 };
|
||||
describe('provider default exec policies', () => {
|
||||
test('keeps exact Codex, Claude and Gemini default arguments', () => {
|
||||
const work = join(tmpdir(), 'gstack-provider-work');
|
||||
const common = { prompt: 'Reply OK', workdir: work, timeoutMs: 5000 };
|
||||
expect(codexExecArgs(common, 'gpt-test')).toEqual([
|
||||
'exec', 'Reply OK', '-C', providerWorkdir,
|
||||
'exec', 'Reply OK', '-C', work,
|
||||
'-s', 'read-only', '--skip-git-repo-check', '--json', '-m', 'gpt-test',
|
||||
]);
|
||||
|
||||
const state = join(providerWorkdir, 'state');
|
||||
const source = join(providerWorkdir, 'source');
|
||||
const helper = helperAt(join(providerWorkdir, 'installed'));
|
||||
const producer = { ...common, csoProducer: policy(state, source, helper) };
|
||||
expect(codexExecArgs(producer, 'gpt-test')).toEqual([
|
||||
'exec', 'Reply OK', '-C', codexProducerPaths(state).workdir,
|
||||
'--strict-config', '--ephemeral', '--ignore-rules', '--skip-git-repo-check',
|
||||
'--json', '-m', 'gpt-test',
|
||||
]);
|
||||
expect(codexExecWorkingDirectory(common)).toBe(providerWorkdir);
|
||||
expect(codexExecWorkingDirectory(producer)).toBe(codexProducerPaths(state).workdir);
|
||||
|
||||
const config = codexProducerConfig(producer);
|
||||
expect(config).toContain('default_permissions = "cso-producer"');
|
||||
expect(config).toContain('":root" = "deny"\n":minimal" = "read"');
|
||||
expect(config).toContain('[permissions.cso-producer.filesystem.":workspace_roots"]\n"." = "write"');
|
||||
expect(config).toContain('[permissions.cso-producer.network]\nenabled = false');
|
||||
expect(config).toContain(`include_only = ${JSON.stringify(CSO_PRODUCER_SHELL_ENV)}`);
|
||||
expect(config).toContain(`${JSON.stringify(join(state, 'cso-home'))} = "write"`);
|
||||
for (const admitted of [
|
||||
join(dirname(helper), `cso-eval-producer${suffix}`), helper,
|
||||
join(dirname(helper), `gstack-cso-core${suffix}`), join(dirname(helper), `gstack-cso-watchdog${suffix}`),
|
||||
join(dirname(helper), '.gstack-cso-generation'), source,
|
||||
]) expect(config).toContain(`${JSON.stringify(admitted)} = "read"`);
|
||||
expect(config).not.toContain(`${JSON.stringify(dirname(helper))} = "read"`);
|
||||
expect(config).not.toContain(`${JSON.stringify(dirname(source))} = "read"`);
|
||||
expect(config).not.toContain('OPENAI_API_KEY');
|
||||
expect(() => codexExecArgs({ ...common, csoProducer: policy('relative-state', source, helper) }, 'gpt-test')).toThrow('absolute normalized path');
|
||||
expect(() => codexExecArgs({ ...common, csoProducer: policy(state, 'relative-source', helper) }, 'gpt-test')).toThrow('absolute normalized path');
|
||||
expect(() => codexExecArgs({ ...common, csoProducer: { ...policy(state, source, helper), helperGeneration: join(dirname(helper), 'wrong-generation') } }, 'gpt-test')).toThrow('exact adjacent');
|
||||
expect(codexExecArgs(producer, 'gpt-test').join(' ')).not.toMatch(/(?:^|\s)(?:-s|--sandbox)(?:\s|$)|danger|bypass|approve-for-me/);
|
||||
});
|
||||
|
||||
test('keeps exact Claude defaults and enables its producer-only noninteractive safe policy', () => {
|
||||
const work = join(tmpdir(), 'gstack-claude-work');
|
||||
const state = join(work, 'state');
|
||||
const source = join(work, 'source');
|
||||
const helper = helperAt(join(work, 'installed'));
|
||||
const common = { prompt: 'Reply OK', workdir: work, timeoutMs: 5000 };
|
||||
expect(claudeExecArgs(common, 'claude-test', ['wrapper'])).toEqual([
|
||||
'wrapper', '-p', '--output-format', 'json', '--model', 'claude-test',
|
||||
]);
|
||||
const producer = { ...common, csoProducer: policy(state, source, helper) };
|
||||
expect(claudeExecArgs(producer, 'claude-test')).toEqual([
|
||||
'-p', '--output-format', 'stream-json', '--verbose', '--include-partial-messages', '--model', 'claude-test',
|
||||
'--restricted', '--safe-mode', '--no-session-persistence',
|
||||
'--permission-prompts', 'none', '--permission-mode', 'dontAsk',
|
||||
'--tools', 'Bash,Write,Agent',
|
||||
'--allowed-tools', `Bash(${helper}),Bash(${helper} *),Write`,
|
||||
'--add-dir', claudeProducerPaths(state).workdir,
|
||||
'--add-dir', join(state, 'cso-home'),
|
||||
'--settings', JSON.stringify({ sandbox: { enabled: true, failIfUnavailable: true, allowUnsandboxedCommands: false, autoAllowBashIfSandboxed: false, excludedCommands: [helper, `${helper} *`] } }),
|
||||
'--strict-mcp-config', '--no-chrome',
|
||||
]);
|
||||
expect(claudeExecArgs(producer, 'claude-test')).not.toContain(source);
|
||||
expect(claudeExecWorkingDirectory(common)).toBe(work);
|
||||
expect(claudeExecWorkingDirectory(producer)).toBe(claudeProducerPaths(state).workdir);
|
||||
expect(claudeExecArgs(producer, 'claude-test').join(' ')).not.toMatch(/bypassPermissions|danger/);
|
||||
});
|
||||
|
||||
test('fails the Claude producer closed unless its sandbox exempts exactly the launcher and its tool policy is the one subagents inherit', () => {
|
||||
const work = join(tmpdir(), 'gstack-claude-sandbox-policy');
|
||||
const state = join(work, 'state');
|
||||
const helper = helperAt(join(work, 'installed'));
|
||||
const producer = { prompt: '', workdir: work, timeoutMs: 1, csoProducer: policy(state, join(work, 'source'), helper) };
|
||||
const args = claudeExecArgs(producer, 'claude-test'), env = claudeExecEnvironment(producer, { PATH: '/bin', ANTHROPIC_API_KEY: 'key' });
|
||||
expect(() => assertClaudeProducerSandboxPolicy(args, env, helper)).not.toThrow();
|
||||
const at = args.indexOf('--settings'), settings = JSON.parse(args[at + 1]);
|
||||
const withSettings = (change: (sandbox: Record<string, unknown>) => void) => {
|
||||
const next = structuredClone(settings); change(next.sandbox);
|
||||
return args.map((arg, index) => index === at + 1 ? JSON.stringify(next) : arg);
|
||||
};
|
||||
const withoutSettings = args.filter((_, index) => index !== at && index !== at + 1);
|
||||
for (const [tampered, tamperedEnv, detail] of [
|
||||
[withoutSettings, env, 'expected exactly one --settings'],
|
||||
[[...args, '--settings', args[at + 1]], env, 'expected exactly one --settings'],
|
||||
[[...withoutSettings, `--settings=${args[at + 1]}`], env, 'expected exactly one --settings'],
|
||||
[withSettings(sandbox => { sandbox.excludedCommands = [helper, `${helper} *`, 'cat']; }), env, 'sandbox.excludedCommands'],
|
||||
[withSettings(sandbox => { sandbox.excludedCommands = [`${helper}-link`, `${helper}-link *`]; }), env, 'sandbox.excludedCommands'],
|
||||
[withSettings(sandbox => { sandbox.allowUnsandboxedCommands = true; }), env, 'sandbox.allowUnsandboxedCommands'],
|
||||
[withSettings(sandbox => { delete sandbox.autoAllowBashIfSandboxed; }), env, 'keys differ'],
|
||||
[withSettings(sandbox => { sandbox.enabled = false; }), env, 'sandbox.enabled'],
|
||||
[withSettings(sandbox => { sandbox.dangerouslyDisableSandbox = true; }), env, 'keys differ'],
|
||||
[args.map(arg => arg.startsWith('Bash(') ? `${arg},Bash(cat *)` : arg), env, '--allowed-tools'],
|
||||
[args, { ...env, CLAUDE_CODE_SUBPROCESS_ENV_SCRUB: '1' }, 'CLAUDE_CODE_SUBPROCESS_ENV_SCRUB'],
|
||||
[args.map(arg => arg === 'Bash,Write,Agent' ? 'Bash,Write' : arg), env, '--tools must be exactly Bash,Write,Agent'],
|
||||
[args.map(arg => arg === 'Bash,Write,Agent' ? 'Bash,Write,Agent,Read' : arg), env, '--tools must be exactly Bash,Write,Agent'],
|
||||
[args.map(arg => arg === 'dontAsk' ? 'acceptEdits' : arg), env, '--permission-mode must be dontAsk'],
|
||||
[args.filter(arg => arg !== '--restricted'), env, 'expected exactly one --restricted'],
|
||||
[args.filter(arg => arg !== '--strict-mcp-config'), env, 'expected exactly one --strict-mcp-config'],
|
||||
[[...args, '--mcp-config', '{}'], env, '--mcp-config would change'],
|
||||
[[...args, '--agents', '{}'], env, '--agents would change'],
|
||||
[[...args, '--setting-sources=user'], env, '--setting-sources would change'],
|
||||
] as Array<[string[], Record<string, string>, string]>) {
|
||||
expect(() => assertClaudeProducerSandboxPolicy(tampered, tamperedEnv, helper)).toThrow(`CLAUDE_PRODUCER_SANDBOX_POLICY_MISMATCH: `);
|
||||
expect(() => assertClaudeProducerSandboxPolicy(tampered, tamperedEnv, helper)).toThrow(detail);
|
||||
}
|
||||
});
|
||||
|
||||
test('keeps exact Gemini defaults and replaces deprecated yolo only for the producer', () => {
|
||||
const work = join(tmpdir(), 'gstack-gemini-work');
|
||||
const state = join(work, 'state');
|
||||
const source = join(work, 'source');
|
||||
const helper = helperAt(join(work, 'installed'));
|
||||
const common = { prompt: 'Reply OK', workdir: work, timeoutMs: 5000, model: 'gemini-test' };
|
||||
expect(geminiExecArgs(common)).toEqual([
|
||||
expect(geminiExecArgs({ ...common, model: 'gemini-test' })).toEqual([
|
||||
'-p', 'Reply OK', '--output-format', 'stream-json', '--yolo', '--model', 'gemini-test',
|
||||
]);
|
||||
const producer = { ...common, csoProducer: policy(state, source, helper) };
|
||||
const producerArgs = geminiExecArgs(producer);
|
||||
expect(producerArgs).toEqual([
|
||||
'-p', 'Reply OK', '--output-format', 'stream-json',
|
||||
'--approval-mode', 'yolo', '--include-directories', geminiProducerPaths(state).workdir, '-e', 'none',
|
||||
'--model', 'gemini-test',
|
||||
]);
|
||||
expect(producerArgs).not.toContain(work);
|
||||
expect(producerArgs).not.toContain(source);
|
||||
expect(geminiExecWorkingDirectory(common)).toBe(work);
|
||||
expect(geminiExecWorkingDirectory(producer)).toBe(geminiProducerPaths(state).workdir);
|
||||
const contextFileName = `.gstack-cso-context-${'a'.repeat(32)}.md`;
|
||||
expect(geminiProducerSystemSettings(contextFileName, helper)).toEqual({
|
||||
advanced: { ignoreLocalEnv: true },
|
||||
admin: { extensions: { enabled: false }, mcp: { enabled: false }, skills: { enabled: false } },
|
||||
context: { fileName: [contextFileName], includeDirectoryTree: false, loadMemoryFromIncludeDirectories: false, memoryBoundaryMarkers: [] },
|
||||
hooksConfig: { enabled: false },
|
||||
privacy: { usageStatisticsEnabled: false },
|
||||
security: {
|
||||
environmentVariableRedaction: { allowed: [], blocked: ['GEMINI_API_KEY', 'GOOGLE_API_KEY', 'GOOGLE_CLOUD_PROJECT', 'GOOGLE_CLOUD_LOCATION'], enabled: true },
|
||||
folderTrust: { enabled: false }, toolSandboxing: false,
|
||||
},
|
||||
skills: { enabled: false },
|
||||
telemetry: { enabled: false, logPrompts: false },
|
||||
tools: { allowed: [`run_shell_command(${helper})`, 'write_file'], core: [`run_shell_command(${helper})`, 'write_file'], sandbox: false },
|
||||
});
|
||||
expect(() => geminiProducerSystemSettings('GEMINI.md', helper)).toThrow('INVALID_GEMINI_CONTEXT_FILENAME');
|
||||
});
|
||||
|
||||
test('passes only selected provider auth plus safe execution inputs and strips Docker credentials', () => {
|
||||
const fixtureRoot = join(tmpdir(), 'gstack-provider-environment-policy');
|
||||
const state = join(fixtureRoot, 'state');
|
||||
const source = join(fixtureRoot, 'source');
|
||||
const helpers = join(fixtureRoot, 'helpers');
|
||||
const work = join(fixtureRoot, 'work');
|
||||
const sourceEnv = {
|
||||
PATH: '/usr/bin', HOME: '/home/eval', LANG: 'C.UTF-8', LC_ALL: 'C.UTF-8', TZ: 'UTC',
|
||||
GSTACK_HOME: state, GSTACK_SESSION_KIND: 'spawned', GSTACK_HEADLESS: '1',
|
||||
OPENAI_API_KEY: 'openai-auth', ANTHROPIC_API_KEY: 'anthropic-auth', CLAUDE_CODE_OAUTH_TOKEN: 'claude-auth',
|
||||
GEMINI_API_KEY: 'gemini-auth', GOOGLE_CLOUD_PROJECT: 'project',
|
||||
CSO_EVAL_PAID: '1', AWS_SECRET_ACCESS_KEY: 'unrelated',
|
||||
DOCKER_HOST: 'tcp://remote.example:2376', DOCKER_CONFIG: '/credentials', DOCKER_CERT_PATH: '/certs',
|
||||
};
|
||||
const safe = { PATH: '/usr/bin', HOME: '/home/eval', LANG: 'C.UTF-8', LC_ALL: 'C.UTF-8', TZ: 'UTC', GSTACK_HOME: state, GSTACK_SESSION_KIND: 'spawned', GSTACK_HEADLESS: '1' };
|
||||
expect(csoProducerChildEnvironment('gpt', sourceEnv)).toEqual({ ...safe, OPENAI_API_KEY: 'openai-auth' });
|
||||
expect(csoProducerChildEnvironment('claude', sourceEnv)).toEqual({ ...safe, ANTHROPIC_API_KEY: 'anthropic-auth', CLAUDE_CODE_OAUTH_TOKEN: 'claude-auth' });
|
||||
expect(csoProducerChildEnvironment('gemini', sourceEnv)).toEqual({ ...safe, GEMINI_API_KEY: 'gemini-auth', GOOGLE_CLOUD_PROJECT: 'project' });
|
||||
const helper = helperAt(helpers);
|
||||
const producer = policy(state, source, helper);
|
||||
const common = { prompt: '', workdir: work, timeoutMs: 1, csoProducer: producer };
|
||||
const codexPaths = codexProducerPaths(state);
|
||||
expect(codexExecEnvironment(common, sourceEnv)).toEqual({
|
||||
...safe, HOME: codexPaths.home, GSTACK_HOME: join(state, 'cso-home'), CODEX_HOME: codexPaths.home, OPENAI_API_KEY: 'openai-auth',
|
||||
});
|
||||
const claudePaths = claudeProducerPaths(state);
|
||||
expect(claudeExecEnvironment(common, sourceEnv)).toEqual({
|
||||
...safe, HOME: claudePaths.home, GSTACK_HOME: join(state, 'cso-home'),
|
||||
ANTHROPIC_API_KEY: 'anthropic-auth', CLAUDE_CODE_OAUTH_TOKEN: 'claude-auth',
|
||||
});
|
||||
const geminiPaths = geminiProducerPaths(state);
|
||||
expect(geminiExecEnvironment(common, sourceEnv)).toEqual({
|
||||
...safe, HOME: geminiPaths.home, GSTACK_HOME: join(state, 'cso-home'),
|
||||
GEMINI_API_KEY: 'gemini-auth', GOOGLE_API_KEY: 'gemini-auth', GOOGLE_CLOUD_PROJECT: 'project',
|
||||
GEMINI_SANDBOX: 'false', GEMINI_TELEMETRY_ENABLED: 'false', GEMINI_TELEMETRY_LOG_PROMPTS: 'false',
|
||||
GEMINI_CLI_TRUST_WORKSPACE: 'true', GEMINI_SYSTEM_MD: 'false', GEMINI_WRITE_SYSTEM_MD: 'false',
|
||||
GEMINI_CLI_HOME: geminiPaths.home,
|
||||
GEMINI_CLI_SYSTEM_DEFAULTS_PATH: geminiPaths.systemDefaults,
|
||||
GEMINI_CLI_SYSTEM_SETTINGS_PATH: geminiPaths.systemSettings,
|
||||
});
|
||||
for (const env of [codexExecEnvironment(common, sourceEnv), claudeExecEnvironment(common, sourceEnv), geminiExecEnvironment(common, sourceEnv)]) {
|
||||
expect(env.CSO_EVAL_PAID).toBeUndefined();
|
||||
expect(env.AWS_SECRET_ACCESS_KEY).toBeUndefined();
|
||||
expect(env.DOCKER_HOST).toBeUndefined();
|
||||
}
|
||||
});
|
||||
|
||||
test('preserves default provider environments and rejects producer escape-hatch arguments', () => {
|
||||
const fixtureRoot = join(tmpdir(), 'gstack-provider-default-policy');
|
||||
const state = join(fixtureRoot, 'state');
|
||||
const source = join(fixtureRoot, 'source');
|
||||
const helpers = join(fixtureRoot, 'helpers');
|
||||
const work = join(fixtureRoot, 'work');
|
||||
const sourceEnv = { PATH: '/bin', CSO_EVAL_PAID: '1', UNRELATED_SECRET: 'kept-by-default', GEMINI_API_KEY: 'key' };
|
||||
const common = { prompt: '', workdir: work, timeoutMs: 1 };
|
||||
const producer = policy(state, source, helperAt(helpers));
|
||||
expect(codexExecEnvironment(common, sourceEnv)).toBe(sourceEnv);
|
||||
expect(claudeExecEnvironment(common, sourceEnv)).toEqual({ ...sourceEnv, GSTACK_HEADLESS: '1' });
|
||||
expect(geminiExecEnvironment(common, sourceEnv)).toEqual({ ...sourceEnv, GOOGLE_API_KEY: 'key' });
|
||||
for (const invoke of [
|
||||
() => codexExecArgs({ ...common, csoProducer: producer, extraArgs: ['--unsafe'] }, 'model'),
|
||||
() => claudeExecArgs({ ...common, csoProducer: producer, extraArgs: ['--unsafe'] }, 'model'),
|
||||
() => geminiExecArgs({ ...common, csoProducer: producer, extraArgs: ['--unsafe'] }),
|
||||
]) expect(invoke).toThrow('does not accept extra provider arguments');
|
||||
});
|
||||
|
||||
test('fails paid Codex producers closed on empty or malformed success output',()=>{
|
||||
for(const raw of ['', ' \n', 'not json\n{bad', '{"type":"turn.completed","usage":{"input_tokens":9,"output_tokens":2}}']){
|
||||
expect(resultFromCodexStream(raw,{model:'gpt-test',producer:true})).toMatchObject({output:'',error:{code:'unknown',reason:'empty output from codex CLI (exit 0)'}});
|
||||
}
|
||||
expect(resultFromCodexStream('diagnostic\n{"type":"item.completed","item":{"type":"agent_message","text":"OK"}}',{producer:true}).error).toBeUndefined();
|
||||
expect(resultFromCodexStream('',{producer:false}).error).toBeUndefined();
|
||||
test('preserves default provider environments', () => {
|
||||
const sourceEnv = { PATH: '/bin', EVAL_FLAG: '1', UNRELATED_SECRET: 'kept-by-default', GEMINI_API_KEY: 'key' };
|
||||
expect(claudeExecEnvironment(sourceEnv)).toEqual({ ...sourceEnv, GSTACK_HEADLESS: '1' });
|
||||
expect(geminiExecEnvironment(sourceEnv)).toEqual({ ...sourceEnv, GOOGLE_API_KEY: 'key' });
|
||||
});
|
||||
|
||||
test('requires Claude producer JSON with a nonblank string result',()=>{
|
||||
@@ -247,37 +41,6 @@ describe('CSO producer provider policies', () => {
|
||||
const valid=resultFromClaudeOutput('{"result":"OK"}',{producer:true});expect(valid.output).toBe('OK');expect(valid.error).toBeUndefined();
|
||||
const legacy=resultFromClaudeOutput('plain text');expect(legacy.output).toBe('plain text');expect(legacy.error).toBeUndefined();
|
||||
});
|
||||
|
||||
test.skipIf(process.platform === 'win32')('executes the exact receipt-bound provider command despite a hostile PATH', async () => {
|
||||
const fixture = mkdtempSync(join(tmpdir(), 'cso-bound-provider-'));
|
||||
const previousPath = process.env.PATH;
|
||||
try {
|
||||
const state = join(fixture, 'state');
|
||||
const source = join(fixture, 'source');
|
||||
const installed = join(fixture, 'installed');
|
||||
const hostile = join(fixture, 'hostile');
|
||||
for (const directory of [state, source, installed, hostile]) mkdirSync(directory);
|
||||
const bound = join(installed, 'codex');
|
||||
const boundMarker = join(fixture, 'bound-ran');
|
||||
const hostileMarker = join(fixture, 'hostile-ran');
|
||||
writeFileSync(bound, `#!/bin/sh\ntouch ${JSON.stringify(boundMarker)}\nprintf '%s\\n' '{"type":"item.completed","item":{"type":"agent_message","text":"BOUND"}}'\n`, { mode: 0o755 });
|
||||
writeFileSync(join(hostile, 'codex'), `#!/bin/sh\ntouch ${JSON.stringify(hostileMarker)}\nprintf '%s\\n' '{"type":"item.completed","item":{"type":"agent_message","text":"HOSTILE"}}'\n`, { mode: 0o755 });
|
||||
process.env.PATH = `${hostile}:${previousPath ?? ''}`;
|
||||
const helper = helperAt(installed);
|
||||
const result = await new GptAdapter().run({
|
||||
prompt: 'Reply OK', workdir: fixture, timeoutMs: 5000, model: 'gpt-test',
|
||||
csoProducer: { ...policy(state, source, helper), providerCommand: { executable: bound, argsPrefix: [] } },
|
||||
});
|
||||
expect(result.output).toBe('BOUND');
|
||||
expect(existsSync(boundMarker)).toBe(true);
|
||||
expect(existsSync(hostileMarker)).toBe(false);
|
||||
expect(existsSync(codexProducerPaths(state).root)).toBe(false);
|
||||
} finally {
|
||||
if (previousPath === undefined) delete process.env.PATH;
|
||||
else process.env.PATH = previousPath;
|
||||
rmSync(fixture, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// Both adapters execute these stubs, so a regression can never launch a paid CLI.
|
||||
|
||||
@@ -517,7 +517,7 @@ describe("pii.wallet: a bc1 address needs the bech32 alphabet and checksum (Free
|
||||
"pii.wallet",
|
||||
"MEDIUM",
|
||||
[
|
||||
// The sha the CSO history range printed as <REDACTED-pii.wallet>..<REDACTED-pii.wallet>; it holds 1 and b, outside bech32's alphabet.
|
||||
// The sha a git history range printed as <REDACTED-pii.wallet>..<REDACTED-pii.wallet>; it holds 1 and b, outside bech32's alphabet.
|
||||
"bc1f7576f1eaf9d548ddb6f742b85ec11b4a3e79..bc1f7576f1eaf9d548ddb6f742b85ec11b4a3e79",
|
||||
// A sha inside the alphabet (no 1 or b after the prefix) fails the checksum.
|
||||
"commit bc1f7576f2eaf9d548ddf6f742c85ec22d4a3e79",
|
||||
|
||||
@@ -410,7 +410,7 @@ describe("MEDIUM demoted credential-shaped patterns (TENSION-1)", () => {
|
||||
}
|
||||
});
|
||||
// #2912 — a line that READS a secret from the environment holds no secret;
|
||||
// it must not fire (and so must not be masked or withhold a /cso source file).
|
||||
// it must not fire (and so must not be masked or withhold a source file).
|
||||
test("env.kv skips exact environment reads (#2912)", () => {
|
||||
for (const line of [
|
||||
'api_key=os.environ["AGENTOPS_API_KEY"]',
|
||||
|
||||
@@ -2,17 +2,11 @@
|
||||
* GST-3297: a key=value secret that follows a path separator is still a
|
||||
* secret. env.kv anchored its name at the line start (or after a diff marker
|
||||
* or comment marker), so `../password=<v>`, `path/api_key=<v>` and
|
||||
* `a/token=<v>` came back raw from the shared redactor. /cso's history.txt is
|
||||
* `git log -p` text redacted by it, so a tracked symlink target, a link that
|
||||
* exists only in history, and ordinary file content all leaked through
|
||||
* `gstack-cso history`. The name may now also start right after a `/`.
|
||||
* `a/token=<v>` came back raw from the shared redactor, so `git log -p` text
|
||||
* leaked a tracked symlink target, a link that exists only in history, and
|
||||
* ordinary file content. The name may now also start right after a `/`.
|
||||
*/
|
||||
import { afterAll, beforeAll, 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 { redact } from "../lib/cso/process";
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { redactFindingSpans, scan } from "../lib/redact-engine";
|
||||
|
||||
const j = (...p: string[]) => p.join("");
|
||||
@@ -56,7 +50,7 @@ describe("env.kv after a path separator (GST-3297)", () => {
|
||||
for (const [name, text] of leaks) {
|
||||
test(`redacts: ${name}`, () => {
|
||||
expect(envKv(text).length).toBeGreaterThan(0);
|
||||
const out = redact(text);
|
||||
const out = redactFindingSpans(text);
|
||||
expect(out).not.toContain(VALUE);
|
||||
expect(out).toContain("<REDACTED-env.kv>");
|
||||
});
|
||||
@@ -122,64 +116,7 @@ describe("env.kv after a path separator (GST-3297)", () => {
|
||||
for (const text of clean) {
|
||||
test(`negative control stays unredacted: ${text}`, () => {
|
||||
expect(envKv(text)).toEqual([]);
|
||||
expect(redact(text)).toBe(text);
|
||||
expect(redactFindingSpans(text)).toBe(text);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
const ROOT = path.resolve(import.meta.dir, "..");
|
||||
const launcher = path.join(ROOT, "bin", "gstack-cso-launcher");
|
||||
const MIB = 1024 * 1024;
|
||||
|
||||
describe.skipIf(process.platform === "win32")("/cso history never prints a key=value secret after a slash (GST-3297)", () => {
|
||||
let root = "";
|
||||
let state = "";
|
||||
beforeAll(() => {
|
||||
root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "cso-kv-slash-")));
|
||||
state = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "cso-kv-slash-state-")));
|
||||
});
|
||||
afterAll(() => {
|
||||
fs.rmSync(root, { recursive: true, force: true });
|
||||
fs.rmSync(state, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
const git = (repo: string, ...args: string[]) => {
|
||||
const result = spawnSync("/usr/bin/git", ["-C", repo, ...args], { encoding: "utf8", env: { HOME: root, PATH: "/usr/bin:/bin" }, timeout: 60_000 });
|
||||
if (result.status) throw new Error(result.stderr);
|
||||
return result.stdout;
|
||||
};
|
||||
const cso = (repo: string, args: string[]) =>
|
||||
spawnSync(launcher, args, { cwd: repo, encoding: "utf8", env: { HOME: root, GSTACK_HOME: state, PATH: "/usr/bin:/bin" }, timeout: 120_000, maxBuffer: 64 * MIB });
|
||||
|
||||
test("link target, history-only link and file content are all redacted in history.txt and the history command", () => {
|
||||
const repo = path.join(root, "repo"),
|
||||
secrets = [j(VALUE, "1"), j(VALUE, "2"), j(VALUE, "3")];
|
||||
fs.mkdirSync(path.join(repo, "cfg"), { recursive: true });
|
||||
git(repo, "init", "-q");
|
||||
git(repo, "config", "user.email", "fixture@example.test");
|
||||
git(repo, "config", "user.name", "Fixture");
|
||||
fs.writeFileSync(path.join(repo, "README.md"), "readme\n");
|
||||
fs.symlinkSync(`../${kv(PASSWORD, secrets[0])}`, path.join(repo, "cfg", "up"));
|
||||
fs.symlinkSync(`a/${kv(TOKEN, secrets[1])}`, path.join(repo, "cfg", "gone"));
|
||||
fs.writeFileSync(path.join(repo, "cfg", "notes.txt"), `see path/${kv(API_KEY, secrets[2])}\nsrc/auth/token.ts\n`);
|
||||
git(repo, "add", "-A");
|
||||
git(repo, "commit", "-qm", "links");
|
||||
fs.unlinkSync(path.join(repo, "cfg", "gone"));
|
||||
git(repo, "add", "-A");
|
||||
git(repo, "commit", "-qm", "drop link");
|
||||
|
||||
const started = cso(repo, ["start", "--repo", repo, "--scope", "auth", "--offline"]);
|
||||
expect(started.stderr).toBe("");
|
||||
expect(started.status).toBe(0);
|
||||
const run = JSON.parse(started.stdout),
|
||||
dir = path.join(state, "security", "cso", run.repoId, run.runId),
|
||||
history = fs.readFileSync(path.join(dir, "history.txt"), "utf8"),
|
||||
printed = cso(repo, ["history", run.runId]);
|
||||
expect(printed.status).toBe(0);
|
||||
for (const text of [history, printed.stdout]) {
|
||||
expect(text).toContain("Subject: drop link");
|
||||
expect(text).toContain("src/auth/token.ts");
|
||||
for (const secret of secrets) expect(text).not.toContain(secret);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,5 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { redactFindingSpans, scan } from "../lib/redact-engine";
|
||||
import { redact, sanitizeForJson } from "../lib/cso/process";
|
||||
|
||||
const secret = ["8Fk2pQ9vXz4wL7mN", "3rT6yB1cD5eG0hJq"].join("");
|
||||
const marker = "<REDACTED-env.kv>";
|
||||
@@ -63,10 +62,4 @@ describe("redaction binds each finding to its original span", () => {
|
||||
expect(redactFindingSpans("-----BEGIN " + "PRIVATE KEY-----\nbody")).toBeNull();
|
||||
expect(redactFindingSpans(`DB_PASSWORD=${secret}`, { maxBytes: 10 })).toBeNull();
|
||||
});
|
||||
|
||||
test("CSO process and JSON output use the exact span, without dropping safe context", () => {
|
||||
const input = `DB_PASSWORD=${secret}\nOTHER_API_KEY="your-api-key-here"`;
|
||||
expect(redact(input)).toBe(`DB_PASSWORD=${marker}\nOTHER_API_KEY="your-api-key-here"`);
|
||||
expect(sanitizeForJson({ output: input })).toEqual({ output: `DB_PASSWORD=${marker}\nOTHER_API_KEY="your-api-key-here"` });
|
||||
});
|
||||
});
|
||||
@@ -1,7 +1,6 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import * as path from "node:path";
|
||||
import { applyRedactions, normalizeWithMap, redactFindingSpans, scan } from "../lib/redact-engine";
|
||||
import { redact, sanitizeForJson } from "../lib/cso/process";
|
||||
|
||||
const secret = ["8Fk2pQ9vXz4wL7mN", "3rT6yB1cD5eG0hJq"].join("");
|
||||
|
||||
@@ -28,8 +27,6 @@ describe("normalized redaction offsets use UTF-16 units", () => {
|
||||
expect(redactFindingSpans(input)).toBe(expected);
|
||||
expect(scan(input).findings.map(({ id, line, col }) => ({ id, line, col })))
|
||||
.toEqual([{ id: "env.kv", line: 2, col: 13 }]);
|
||||
expect(redact(input)).toBe(expected);
|
||||
expect(sanitizeForJson({ output: input })).toEqual({ output: expected });
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -74,8 +74,6 @@ describe("#1539 confidence resolver — pre-emit verification gate present", ()
|
||||
describe("#1539 generated SKILL.md files — gate propagated to all consumers", () => {
|
||||
const consumers = [
|
||||
"review/SKILL.md",
|
||||
// CSO's private startup uses its dedicated evidence rubric rather than
|
||||
// the shared numerical confidence resolver guarded by this regression.
|
||||
"plan-eng-review/SKILL.md",
|
||||
"ship/SKILL.md",
|
||||
];
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
* Retired skills: no host registers them, and setup and gstack-relink treat
|
||||
* each as a disabled skill that config cannot re-enable (GSTACK_RETIRED_SKILLS),
|
||||
* so an existing gstack-owned entry is removed on the next setup or upgrade and
|
||||
* a user's own same-name skill stays. /investigate is retired (GST-1717).
|
||||
* a user's own same-name skill stays. /investigate is retired (GST-1717), and
|
||||
* so is /cso (GST-3920).
|
||||
* /plan-eng-review was retired in GST-1698 and came back in GST-2726: every host
|
||||
* registers it again, and external hosts still carry its methodology beside
|
||||
* gstack-autoplan/SKILL.md as plan-eng-review.md for /autoplan's eng phase.
|
||||
@@ -24,7 +25,7 @@ test('setup and gstack-relink retire the same skills as the generator', () => {
|
||||
const r = spawnSync('bash', ['-c', '. "$1" && printf %s "$GSTACK_RETIRED_SKILLS"', '_', REGISTRY], { encoding: 'utf8', timeout: 10_000 });
|
||||
expect(r.status, r.stderr).toBe(0);
|
||||
expect(r.stdout.split(/\s+/).filter(Boolean)).toEqual(RETIRED_SKILLS);
|
||||
expect(RETIRED_SKILLS.join(' ')).toBe('investigate verify');
|
||||
expect(RETIRED_SKILLS.join(' ')).toBe('investigate verify cso');
|
||||
});
|
||||
|
||||
describe('gstack-relink after an upgrade removed /investigate (GST-1717)', () => {
|
||||
@@ -66,6 +67,23 @@ describe('gstack-relink after an upgrade removed /investigate (GST-1717)', () =>
|
||||
expect(fs.existsSync(path.join(skills, 'gstack-ship', 'SKILL.md'))).toBe(true); // ship installs as gstack-ship (#4775)
|
||||
});
|
||||
|
||||
test('the dangling cso and gstack-cso entries are removed, and a user\'s own cso skill stays (GST-3920)', () => {
|
||||
fs.mkdirSync(path.join(skills, 'cso'));
|
||||
fs.symlinkSync(path.join(install, 'cso', 'SKILL.md'), path.join(skills, 'cso', 'SKILL.md'));
|
||||
fs.symlinkSync(path.join(install, 'cso'), path.join(skills, 'gstack-cso'));
|
||||
const r = relink();
|
||||
expect(r.status, r.stderr).toBe(0);
|
||||
expect(fs.lstatSync(path.join(skills, 'cso'), { throwIfNoEntry: false })).toBeUndefined();
|
||||
expect(fs.lstatSync(path.join(skills, 'gstack-cso'), { throwIfNoEntry: false })).toBeUndefined();
|
||||
|
||||
fs.mkdirSync(path.join(skills, 'cso'));
|
||||
const own = '---\nname: cso\ndescription: mine\n---\nmy own security review\n';
|
||||
fs.writeFileSync(path.join(skills, 'cso', 'SKILL.md'), own);
|
||||
const again = relink();
|
||||
expect(again.status, again.stderr).toBe(0);
|
||||
expect(fs.readFileSync(path.join(skills, 'cso', 'SKILL.md'), 'utf8')).toBe(own);
|
||||
});
|
||||
|
||||
test("a user's own investigate skill is left alone", () => {
|
||||
fs.mkdirSync(path.join(skills, 'investigate'));
|
||||
const own = '---\nname: investigate\ndescription: mine\n---\nmy own debugger\n';
|
||||
@@ -429,10 +447,18 @@ describe('gstack-relink after /verify became /build-check (#4593)', () => {
|
||||
|
||||
describe('/cso stays removed (GST-3920)', () => {
|
||||
const REMOVED_SCRIPTS = [
|
||||
'scripts/build-cso-windows.ps1',
|
||||
'scripts/build-cso.sh',
|
||||
'scripts/cso-attestation-evidence.ts',
|
||||
'scripts/cso-eval-output-redaction.ts',
|
||||
'scripts/cso-eval-producer.ts',
|
||||
'scripts/cso-eval-protocol.ts',
|
||||
'scripts/cso-eval.ts',
|
||||
'scripts/cso-image-matrix.ts',
|
||||
'scripts/cso-native-evidence.ts',
|
||||
'scripts/cso-public-ghcr.ts',
|
||||
'scripts/cso-requalification.ts',
|
||||
'scripts/cso-runtime-promotion.ts',
|
||||
'scripts/cso-sbom-packages-check.jq',
|
||||
'scripts/cso-sbom-packages.jq',
|
||||
'scripts/cso-scanner-catalog.ts',
|
||||
@@ -442,7 +468,7 @@ describe('/cso stays removed (GST-3920)', () => {
|
||||
];
|
||||
const RUNNERS = ['package.json', 'setup', 'scripts/build.sh', ...fs.readdirSync(path.join(ROOT, '.github', 'workflows')).map(f => path.join('.github', 'workflows', f))];
|
||||
|
||||
test('its evaluation, image and scanner scripts are gone, and no package script, setup step or workflow still runs one', () => {
|
||||
test('its helper, build and evaluation scripts are gone, and no package script, setup step or workflow still runs one', () => {
|
||||
expect(REMOVED_SCRIPTS.filter(f => fs.existsSync(path.join(ROOT, f)))).toEqual([]);
|
||||
const stillRun = RUNNERS.flatMap(runner => {
|
||||
const text = fs.readFileSync(path.join(ROOT, runner), 'utf8');
|
||||
|
||||
@@ -25,10 +25,10 @@ async function router(host: 'claude' | 'codex', disabledSkills?: string[]) {
|
||||
describe('C8: disabled skills leave the rendered router', () => {
|
||||
for (const host of ['claude', 'codex'] as const) {
|
||||
test(`${host}: routing rules drop disabled skills and keep the other side of an "A or B" rule`, async () => {
|
||||
const text = await router(host, ['retro', 'gstack-cso', '/careful', 'gstack-upgrade']);
|
||||
expect(text).toContain('Disabled on this install (never invoke or suggest them): `/retro`, `/cso`, `/careful`.');
|
||||
const text = await router(host, ['retro', 'gstack-health', '/careful', 'gstack-upgrade']);
|
||||
expect(text).toContain('Disabled on this install (never invoke or suggest them): `/retro`, `/health`, `/careful`.');
|
||||
expect(text).not.toMatch(/→ invoke `\/retro`/);
|
||||
expect(text).not.toMatch(/→ invoke `\/cso`/);
|
||||
expect(text).not.toMatch(/→ invoke `\/health`/);
|
||||
expect(text).toContain('careful mode → invoke `/guard`');
|
||||
expect(text).toContain('→ invoke `/gstack-upgrade`');
|
||||
expect(text).toContain('→ invoke `/gstack-ship`');
|
||||
|
||||
@@ -332,8 +332,6 @@ const GENERATED_WITH_GUIDANCE = [
|
||||
'autoplan/sections/design-phase.md',
|
||||
'autoplan/sections/eng-phase.md',
|
||||
'autoplan/sections/dx-phase.md',
|
||||
// CSO's private startup does not import the shared synchronous-dispatch
|
||||
// guidance and its bounded worker policy is specified in its own skeleton.
|
||||
'design-consultation/sections/proposal-and-preview.md',
|
||||
'design-review/sections/outside-voices.md',
|
||||
'document-release/sections/release-body.md',
|
||||
|
||||
@@ -32,7 +32,6 @@ const SESSION_KIND_INVENTORY: Record<string, string> = {
|
||||
'hosts/claude/hooks/spawned-directive.ts': 'Claude Code only (:57)',
|
||||
'hosts/claude/hooks/question-preference-hook.ts': 'Claude Code only (:506)',
|
||||
'bin/gstack-capy-install': 'writer: the Capy launcher exports unattended (:658, :677)',
|
||||
'scripts/cso-eval-producer.ts': 'writer: sets spawned for its own producer run and restores it (:616-631)',
|
||||
'scripts/lib/shard-engine.ts': 'writer: drops the Capy launch markers from shard environments (:595)',
|
||||
};
|
||||
|
||||
|
||||
@@ -74,12 +74,11 @@ esac
|
||||
if [ "$1" = run ] && [ "$2" = build ]; then
|
||||
printf 'build\\n' >> "$FIXTURE_EVENTS"
|
||||
"$FIXTURE_REAL_BUN" run scripts/gen-skill-docs.ts --host all
|
||||
for target in browse/dist/browse design/dist/design make-pdf/dist/pdf bin/gstack-cso-core bin/gstack-cso-launcher bin/gstack-cso-watchdog; do
|
||||
for target in browse/dist/browse design/dist/design make-pdf/dist/pdf; do
|
||||
mkdir -p "$(dirname "$target")"
|
||||
printf '#!/usr/bin/env bash\\nexit 0\\n' > "$target"
|
||||
chmod +x "$target"
|
||||
done
|
||||
printf '%064d\\n' 0 > bin/.gstack-cso-generation
|
||||
printf 'complete\\n' > browse/dist/.build-complete
|
||||
exit 0
|
||||
fi
|
||||
|
||||
@@ -35,9 +35,6 @@ const BUILT_ARTIFACT_ALLOWLIST = [
|
||||
'design/dist/',
|
||||
'make-pdf/dist/',
|
||||
'bin/gstack-global-discover', // compiled from bin/gstack-global-discover.ts at build time
|
||||
'bin/gstack-cso-core',
|
||||
'bin/gstack-cso-launcher',
|
||||
'bin/gstack-cso-watchdog',
|
||||
];
|
||||
|
||||
/**
|
||||
|
||||
@@ -9,7 +9,7 @@ import { runBashScript } from './helpers/bash-script';
|
||||
// the design binary is SIGKILLed at launch (exit 137). The real block runs on
|
||||
// any OS with uname/codesign/otool stubbed on PATH.
|
||||
const setup = fs.readFileSync(path.resolve(import.meta.dir, '../setup'), 'utf8');
|
||||
const start = setup.indexOf(' if [ "$(uname -s)" = "Darwin" ] && [ "$(uname -m)" = "arm64" ]; then\n # CSO artifacts');
|
||||
const start = setup.indexOf(' if [ "$(uname -s)" = "Darwin" ] && [ "$(uname -m)" = "arm64" ]; then\n # B4 (#1254)');
|
||||
const end = setup.indexOf('\n fi\n', setup.indexOf(' done', start));
|
||||
const block = setup.slice(start, end + 5);
|
||||
const BINS = ['browse/dist/browse', 'browse/dist/find-browse', 'design/dist/design', 'make-pdf/dist/pdf', 'bin/gstack-global-discover'];
|
||||
|
||||
@@ -18,7 +18,7 @@ const ROOT = path.resolve(import.meta.dir, '..');
|
||||
const SETUP_SRC = fs.readFileSync(path.join(ROOT, 'setup'), 'utf-8');
|
||||
const HELPER = path.join(ROOT, 'bin/gstack-skill-name.sh');
|
||||
const SHIMMED = ['grep', 'sed', 'tr', 'basename'];
|
||||
const SKILLS = ['qa', 'review', 'ship', 'office-hours', 'investigate', 'land-and-deploy', 'retro', 'cso'];
|
||||
const SKILLS = ['qa', 'review', 'ship', 'office-hours', 'investigate', 'land-and-deploy', 'retro', 'benchmark'];
|
||||
|
||||
function extractFn(name: string): string {
|
||||
const start = SETUP_SRC.indexOf(`\n${name}() {`);
|
||||
|
||||
+40
-110
@@ -1,10 +1,8 @@
|
||||
/**
|
||||
* setup: the NEEDS_BUILD decision ("# 1. Build browse binary if needed").
|
||||
*
|
||||
* Direct `bun run build` produces every binary. Setup includes CSO when its
|
||||
* host capability probe succeeds, and otherwise builds the general binaries
|
||||
* while removing CSO artifacts so /cso fails closed. Before,
|
||||
* only the browse binary's existence was checked and lib/ was not in the
|
||||
* Direct `bun run build` produces every binary. Before, only the browse
|
||||
* binary's existence was checked and lib/ was not in the
|
||||
* staleness set: a missing design/dist/design or make-pdf/dist/pdf, or an edit
|
||||
* to lib/ (the canonical claude-bin / error-handling / aside-render sources the
|
||||
* binaries embed), left setup reporting "up to date" with binaries that could
|
||||
@@ -24,15 +22,12 @@ import { runBashScript } from './helpers/bash-script';
|
||||
const ROOT = path.resolve(import.meta.dir, '..');
|
||||
const SETUP_SRC = fs.readFileSync(path.join(ROOT, 'setup'), 'utf-8');
|
||||
const BUILD_SRC = fs.readFileSync(path.join(ROOT, 'scripts/build.sh'), 'utf-8');
|
||||
const CSO_BUILD_SRC = fs.readFileSync(path.join(ROOT, 'scripts/build-cso.sh'), 'utf-8');
|
||||
|
||||
// From the $_EXE suffix derivation through the `fi` that closes the staleness
|
||||
// chain. The statement that follows (the build itself) is the end anchor and is
|
||||
// NOT included, so the harness never tries to run `bun run build`.
|
||||
const BLOCK_START = '_EXE=""';
|
||||
const BLOCK_END = '\nif [ "$NEEDS_BUILD" -eq 1 ]; then';
|
||||
const CSO_SWITCH_START = 'if [ "${GSTACK_SETUP_RUNNING:-0}" = "1" ] && [ "${GSTACK_SETUP_SKIP_CSO_BUILD:-0}" = "1" ]; then';
|
||||
const CSO_SWITCH_END = '\nbash browse/scripts/build-node-server.sh';
|
||||
|
||||
function needsBuildBlock(): string {
|
||||
const start = SETUP_SRC.indexOf(BLOCK_START);
|
||||
@@ -41,13 +36,6 @@ function needsBuildBlock(): string {
|
||||
return SETUP_SRC.slice(start, end + 1);
|
||||
}
|
||||
|
||||
function csoBuildSwitchBlock(): string {
|
||||
const start = BUILD_SRC.indexOf(CSO_SWITCH_START);
|
||||
const end = BUILD_SRC.indexOf(CSO_SWITCH_END, start);
|
||||
if (start < 0 || end < 0) throw new Error('Could not locate the setup-private CSO build switch');
|
||||
return BUILD_SRC.slice(start, end);
|
||||
}
|
||||
|
||||
// Fixed instants, far apart, so coarse filesystem timestamps and clock skew
|
||||
// can never blur "older than the binary" into "newer".
|
||||
const BIN_T = new Date('2024-06-01T12:00:00Z');
|
||||
@@ -64,9 +52,6 @@ const SOURCE_FILES = [
|
||||
'package.json',
|
||||
'bun.lock',
|
||||
'scripts/build.sh',
|
||||
'scripts/build-cso.sh',
|
||||
'scripts/build-cso-windows.ps1',
|
||||
'lib/cso/launcher.c',
|
||||
];
|
||||
|
||||
const tmpDirs: string[] = [];
|
||||
@@ -93,17 +78,6 @@ function makeTree(opts: { exe?: string } = {}): string {
|
||||
writeAt(path.join(dir, 'browse/dist/browse'), BIN_T, 0o755);
|
||||
writeAt(path.join(dir, `design/dist/design${exe}`), BIN_T, 0o755);
|
||||
writeAt(path.join(dir, `make-pdf/dist/pdf${exe}`), BIN_T, 0o755);
|
||||
writeAt(path.join(dir, `bin/gstack-cso-core${exe}`), BIN_T, 0o755);
|
||||
writeAt(path.join(dir, `bin/gstack-cso-launcher${exe}`), BIN_T, 0o755);
|
||||
const generation = path.join(dir, 'bin/.gstack-cso-generation');
|
||||
fs.writeFileSync(generation, `${'a'.repeat(64)}\n`, { mode: 0o600 });
|
||||
fs.utimesSync(generation, BIN_T, BIN_T);
|
||||
if (exe) {
|
||||
const generationLock = path.join(dir, 'bin/.gstack-cso-generation.lock');
|
||||
fs.writeFileSync(generationLock, '', { mode: 0o600 });
|
||||
fs.utimesSync(generationLock, BIN_T, BIN_T);
|
||||
}
|
||||
if (!exe) writeAt(path.join(dir, 'bin/gstack-cso-watchdog'), BIN_T, 0o755);
|
||||
for (const f of SOURCE_FILES) writeAt(path.join(dir, f), OLD_T);
|
||||
writeAt(path.join(dir, 'browse/dist/.build-complete'), STAMP_T);
|
||||
return dir;
|
||||
@@ -113,13 +87,12 @@ function touchNewer(dir: string, rel: string): void {
|
||||
writeAt(path.join(dir, rel), NEW_T);
|
||||
}
|
||||
|
||||
function decide(dir: string, opts: { isWindows?: '0' | '1'; csoAvailable?: '0' | '1' } = {}): number {
|
||||
function decide(dir: string, opts: { isWindows?: '0' | '1' } = {}): number {
|
||||
const script = [
|
||||
'set -e',
|
||||
`SOURCE_GSTACK_DIR="${dir}"`,
|
||||
'BROWSE_BIN="$SOURCE_GSTACK_DIR/browse/dist/browse"',
|
||||
`IS_WINDOWS=${opts.isWindows ?? '0'}`,
|
||||
`CSO_BUILD_AVAILABLE=${opts.csoAvailable ?? '1'}`,
|
||||
needsBuildBlock(),
|
||||
'echo "NEEDS_BUILD=$NEEDS_BUILD"',
|
||||
].join('\n');
|
||||
@@ -149,56 +122,16 @@ describe('setup: NEEDS_BUILD static invariants', () => {
|
||||
expect(block).toContain('[ ! -x "$SOURCE_GSTACK_DIR/design/dist/design$_EXE" ]');
|
||||
expect(block).toContain('[ ! -x "$SOURCE_GSTACK_DIR/make-pdf/dist/pdf$_EXE" ]');
|
||||
expect(block).toContain('if [ "$IS_WINDOWS" -eq 1 ]; then _EXE=".exe"; fi');
|
||||
expect(block).toContain('if [ "$CSO_BUILD_AVAILABLE" -eq 1 ]; then');
|
||||
});
|
||||
|
||||
test('setup owns the only CSO build escape hatch and probes Bun hardening flags', () => {
|
||||
for (const flag of ['dotenv', 'bunfig', 'tsconfig', 'package-json']) {
|
||||
expect(SETUP_SRC).toContain(`--no-compile-autoload-${flag}`);
|
||||
}
|
||||
expect(SETUP_SRC).toContain('probe_cso_build_prerequisites');
|
||||
expect(BUILD_SRC).toContain('[ "${GSTACK_SETUP_RUNNING:-0}" = "1" ]');
|
||||
expect(BUILD_SRC).toContain('[ "${GSTACK_SETUP_SKIP_CSO_BUILD:-0}" = "1" ]');
|
||||
expect(BUILD_SRC).toContain('BUN_CMD="$BUN_CMD" bash scripts/build-cso.sh');
|
||||
});
|
||||
|
||||
test('the skip flag alone cannot weaken a direct build; setup can omit and purge CSO', () => {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-cso-build-switch-'));
|
||||
tmpDirs.push(dir);
|
||||
for (const sub of ['bin', 'scripts']) fs.mkdirSync(path.join(dir, sub), { recursive: true });
|
||||
for (const name of ['gstack-cso-launcher', 'gstack-cso-launcher.exe', 'gstack-cso-core', 'gstack-cso-core.exe', 'gstack-cso-watchdog']) {
|
||||
writeAt(path.join(dir, 'bin', name), BIN_T, 0o755);
|
||||
}
|
||||
const strict = path.join(dir, 'scripts/build-cso.sh');
|
||||
fs.writeFileSync(strict, '#!/bin/sh\nprintf called > cso-called\n');
|
||||
fs.chmodSync(strict, 0o755);
|
||||
|
||||
let result = runBashScript(`set -e\n${csoBuildSwitchBlock()}`, {
|
||||
cwd: dir, env: { ...process.env, GSTACK_SETUP_SKIP_CSO_BUILD: '1' },
|
||||
});
|
||||
expect(result.status).toBe(0);
|
||||
expect(fs.existsSync(path.join(dir, 'cso-called'))).toBe(true);
|
||||
|
||||
fs.unlinkSync(path.join(dir, 'cso-called'));
|
||||
result = runBashScript(`set -e\n${csoBuildSwitchBlock()}`, {
|
||||
cwd: dir, env: { ...process.env, GSTACK_SETUP_RUNNING: '1', GSTACK_SETUP_SKIP_CSO_BUILD: '1' },
|
||||
});
|
||||
expect(result.status).toBe(0);
|
||||
expect(fs.existsSync(path.join(dir, 'cso-called'))).toBe(false);
|
||||
expect(fs.readdirSync(path.join(dir, 'bin')).filter(name => name.startsWith('gstack-cso-'))).toEqual([]);
|
||||
});
|
||||
|
||||
test('the whole-build stamp is invalidated before compilation and published only after every output succeeds', () => {
|
||||
const invalidate = BUILD_SRC.indexOf('rm -f "$BUILD_STAMP" "$BUILD_STAMP_TMP"');
|
||||
const firstBuild = BUILD_SRC.indexOf('"$BUN_CMD" run vendor:xterm');
|
||||
const csoBuild = BUILD_SRC.indexOf('BUN_CMD="$BUN_CMD" bash scripts/build-cso.sh');
|
||||
const publish = BUILD_SRC.indexOf('mv -f "$BUILD_STAMP_TMP" "$BUILD_STAMP"');
|
||||
expect(invalidate).toBeGreaterThan(-1);
|
||||
expect(firstBuild).toBeGreaterThan(invalidate);
|
||||
expect(csoBuild).toBeGreaterThan(firstBuild);
|
||||
expect(publish).toBeGreaterThan(csoBuild);
|
||||
expect(publish).toBeGreaterThan(firstBuild);
|
||||
expect(BUILD_SRC.slice(publish + 1)).not.toContain('"$BUN_CMD" build');
|
||||
expect(CSO_BUILD_SRC).toContain('rm -f "$CSO_BUILD_ROOT/browse/dist/.build-complete"');
|
||||
});
|
||||
|
||||
test('the staleness find walks every embedded source root, lib/ included', () => {
|
||||
@@ -217,16 +150,47 @@ describe('setup: NEEDS_BUILD decision executes', () => {
|
||||
expect(decide(makeTree())).toBe(0);
|
||||
});
|
||||
|
||||
test('an interrupted partial build cannot let a refreshed browse binary hide stale CSO outputs', () => {
|
||||
test('an interrupted partial build cannot let a refreshed browse binary hide stale outputs', () => {
|
||||
const dir = makeTree();
|
||||
fs.unlinkSync(path.join(dir, 'browse/dist/.build-complete'));
|
||||
writeAt(path.join(dir, 'browse/dist/browse'), NEW_T, 0o755);
|
||||
expect(fs.statSync(path.join(dir, 'bin/gstack-cso-core')).mtimeMs).toBeLessThan(
|
||||
fs.statSync(path.join(dir, 'browse/dist/browse')).mtimeMs,
|
||||
);
|
||||
expect(decide(dir)).toBe(1);
|
||||
});
|
||||
|
||||
test('an upgraded checkout loses the removed /cso helper and its build records, and nothing else (GST-3920)', () => {
|
||||
const dir = makeTree();
|
||||
const leftovers = ['bin/gstack-cso-launcher', 'bin/gstack-cso-core', 'bin/gstack-cso-watchdog', 'bin/gstack-cso-core.exe',
|
||||
'bin/.gstack-cso-generation', 'bin/.gstack-cso-build-result', 'bin/.gstack-cso-build.log', 'bin/.gstack-cso-evaluation',
|
||||
'bin/.gstack-cso-stage.Ab12Cd/gstack-cso-core', 'bin/.gstack-cso-build.lock/owner',
|
||||
'lib/cso/images/gstack-cso-verifier', 'lib/cso/images/gstack-cso-preparation'];
|
||||
for (const rel of leftovers) writeAt(path.join(dir, rel), OLD_T, 0o755);
|
||||
writeAt(path.join(dir, 'bin/gstack-config'), OLD_T, 0o755);
|
||||
expect(decide(dir)).toBe(0);
|
||||
for (const rel of leftovers) expect([rel, fs.existsSync(path.join(dir, rel))]).toEqual([rel, false]);
|
||||
expect(fs.existsSync(path.join(dir, 'bin/.gstack-cso-stage.Ab12Cd'))).toBe(false);
|
||||
expect(fs.existsSync(path.join(dir, 'bin/.gstack-cso-build.lock'))).toBe(false);
|
||||
expect(fs.existsSync(path.join(dir, 'lib/cso'))).toBe(false);
|
||||
expect(fs.existsSync(path.join(dir, 'bin/gstack-config'))).toBe(true);
|
||||
expect(fs.existsSync(path.join(dir, 'lib/claude-bin.ts'))).toBe(true);
|
||||
});
|
||||
|
||||
test('a file of your own that only shares the old helper prefix is kept', () => {
|
||||
const dir = makeTree();
|
||||
const own = ['bin/gstack-cso-wrapper', 'bin/.gstack-cso-notes/todo.md', 'bin/.gstack-cso-stage.mine/keep'];
|
||||
for (const rel of own) writeAt(path.join(dir, rel), OLD_T, 0o755);
|
||||
expect(decide(dir)).toBe(0);
|
||||
for (const rel of own) expect([rel, fs.existsSync(path.join(dir, rel))]).toEqual([rel, true]);
|
||||
});
|
||||
|
||||
test('a lib/cso directory holding anything else is kept', () => {
|
||||
const dir = makeTree();
|
||||
writeAt(path.join(dir, 'lib/cso/images/gstack-cso-verifier'), OLD_T, 0o755);
|
||||
writeAt(path.join(dir, 'lib/cso/notes.md'), OLD_T);
|
||||
expect(decide(dir)).toBe(0);
|
||||
expect(fs.existsSync(path.join(dir, 'lib/cso/images'))).toBe(false);
|
||||
expect(fs.existsSync(path.join(dir, 'lib/cso/notes.md'))).toBe(true);
|
||||
});
|
||||
|
||||
test('make-pdf/dist/pdf missing → 1 (was: not checked at all)', () => {
|
||||
const dir = makeTree();
|
||||
fs.unlinkSync(path.join(dir, 'make-pdf/dist/pdf'));
|
||||
@@ -245,41 +209,7 @@ describe('setup: NEEDS_BUILD decision executes', () => {
|
||||
expect(decide(dir)).toBe(1);
|
||||
});
|
||||
|
||||
test.each(['bin/gstack-cso-launcher','bin/gstack-cso-core', 'bin/gstack-cso-watchdog'])('%s missing → 1', binary => {
|
||||
const dir = makeTree();
|
||||
fs.unlinkSync(path.join(dir, binary));
|
||||
expect(decide(dir)).toBe(1);
|
||||
});
|
||||
|
||||
test('CSO generation manifest missing → 1', () => {
|
||||
const dir = makeTree();
|
||||
fs.unlinkSync(path.join(dir, 'bin/.gstack-cso-generation'));
|
||||
expect(decide(dir)).toBe(1);
|
||||
});
|
||||
|
||||
test('Windows CSO generation lock missing → 1', () => {
|
||||
const dir = makeTree({ exe: '.exe' });
|
||||
fs.unlinkSync(path.join(dir, 'bin/.gstack-cso-generation.lock'));
|
||||
expect(decide(dir, { isWindows: '1' })).toBe(1);
|
||||
});
|
||||
|
||||
test('unavailable CSO removes stale helpers and does not force a repeat build', () => {
|
||||
const dir = makeTree();
|
||||
expect(decide(dir, { csoAvailable: '0' })).toBe(0);
|
||||
for (const binary of ['bin/gstack-cso-launcher', 'bin/gstack-cso-core', 'bin/gstack-cso-watchdog', 'bin/.gstack-cso-generation']) {
|
||||
expect(fs.existsSync(path.join(dir, binary))).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
test('unavailable CSO ignores its build-script freshness but still rebuilds missing general binaries', () => {
|
||||
const dir = makeTree();
|
||||
touchNewer(dir, 'scripts/build-cso.sh');
|
||||
expect(decide(dir, { csoAvailable: '0' })).toBe(0);
|
||||
fs.unlinkSync(path.join(dir, 'design/dist/design'));
|
||||
expect(decide(dir, { csoAvailable: '0' })).toBe(1);
|
||||
});
|
||||
|
||||
test.each(['scripts/build.sh', 'scripts/build-cso.sh', 'scripts/build-cso-windows.ps1', 'lib/cso/launcher.c'])('%s changed → 1', source => {
|
||||
test.each(['scripts/build.sh'])('%s changed → 1', source => {
|
||||
const dir = makeTree();
|
||||
touchNewer(dir, source);
|
||||
expect(decide(dir)).toBe(1);
|
||||
|
||||
@@ -673,7 +673,7 @@ describe('setup and runtime need only production dependencies', () => {
|
||||
});
|
||||
|
||||
test('the dev toolchain stays out of the user install', () => {
|
||||
for (const name of ['@anthropic-ai/claude-agent-sdk', 'typescript', 'prettier', '@types/bun']) {
|
||||
for (const name of ['@anthropic-ai/claude-agent-sdk', 'typescript', '@types/bun']) {
|
||||
expect(PKG.devDependencies).toHaveProperty([name]);
|
||||
expect(PKG.dependencies).not.toHaveProperty([name]);
|
||||
}
|
||||
|
||||
@@ -22,9 +22,9 @@ afterEach(() => { for (const t of tmps.splice(0)) fs.rmSync(t, { recursive: true
|
||||
const temp = (prefix: string) => { const d = fs.mkdtempSync(path.join(os.tmpdir(), prefix)); tmps.push(d); return d; };
|
||||
const stub = (dir: string, name: string, body: string) => fs.writeFileSync(path.join(dir, name), `#!/bin/sh\n${body}\n`, { mode: 0o755 });
|
||||
|
||||
test('setup runs the launch summary only on Windows, after the CSO summary', () => {
|
||||
test('setup runs the launch summary only on Windows, after the install summary', () => {
|
||||
const call = setup.indexOf('if [ "$IS_WINDOWS" -eq 1 ]; then\n _windows_launch_summary\nfi');
|
||||
expect(call).toBeGreaterThan(setup.indexOf('# ─── CSO native-helper summary'));
|
||||
expect(call).toBeGreaterThan(setup.indexOf('\n_setup_print_summary\n'));
|
||||
});
|
||||
|
||||
describe.skipIf(process.platform === 'win32')('setup: Windows Smart App Control hint (#2595)', () => {
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
/**
|
||||
* Plan D2: review and cso look sideways. Pins the tokens, not the prose: the
|
||||
* Plan D2: review looks sideways. Pins the tokens, not the prose: the
|
||||
* sideways sweep and the forced-CRITICAL list reach review Step 4 and the
|
||||
* checklist, the flake-fix number reaches review and investigate from one
|
||||
* resolver, the review-mode Scope Check carries `Diff read` and `Undeclared
|
||||
* behavior changes`, /cso adopts the sibling sweep and nothing else, and ship's
|
||||
* byte-pinned plan-completion section is untouched.
|
||||
* behavior changes`, and ship's byte-pinned plan-completion section is
|
||||
* untouched.
|
||||
*/
|
||||
import { describe, expect, test } from 'bun:test';
|
||||
import * as fs from 'node:fs';
|
||||
@@ -30,12 +30,6 @@ describe('sideways resolver', () => {
|
||||
expect(review).toContain('forced CRITICAL');
|
||||
for (const cls of FORCED_CRITICAL) expect(review.toLowerCase()).toContain(cls);
|
||||
});
|
||||
test('the cso variant is the sibling sweep and nothing else', () => {
|
||||
const cso = generateSidewaysSweep(ctx, ['cso']);
|
||||
expect(cso).toContain('worst sibling');
|
||||
expect(cso).not.toMatch(/CRITICAL|data loss|uncapped/);
|
||||
expect(cso.split('\n').length).toBe(1);
|
||||
});
|
||||
test('the flake-fix number is one rule in two sizes', () => {
|
||||
for (const variant of [['review'], ['investigate']]) {
|
||||
const text = generateFlakeFixNumber(ctx, variant);
|
||||
@@ -85,13 +79,3 @@ describe('rendered review', () => {
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('rendered cso', () => {
|
||||
test('Phase 12 adopts the sibling sweep and keeps its own severity vocabulary', () => {
|
||||
const skill = read('cso/SKILL.md');
|
||||
const phase12 = between(skill, '### Phase 12', '### Phase 13');
|
||||
expect(phase12).toContain('severity follows the worst sibling');
|
||||
expect(phase12).not.toContain('root-cause variants');
|
||||
expect(phase12).not.toMatch(/forced CRITICAL|Forced-CRITICAL/);
|
||||
});
|
||||
});
|
||||
@@ -24,8 +24,6 @@
|
||||
* choices) are intentionally OUT of this matrix; Layer 0 covers their format
|
||||
* spec, and a fixture can't fairly trigger their AUQ.
|
||||
*
|
||||
* CSO is intentionally absent: its private startup omits the shared AUQ block,
|
||||
* and its dedicated E2E grades evidence, reporting, and proof behavior.
|
||||
* Run a subset in the foreground with AUQ_MATRIX_ONLY="plan-eng-review,spec".
|
||||
*/
|
||||
import { test } from 'bun:test';
|
||||
|
||||
@@ -1,142 +0,0 @@
|
||||
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 { CANARY, PACKAGE, DIFF_MODE_BASE, DIFF_MODE_CHANGE, withFixture, requireReport, expectDiffModeReport, type Fixture } from './helpers/cso-e2e-report';
|
||||
import * as path from 'node:path';
|
||||
|
||||
const evalCollector = createEvalCollector('e2e-cso');
|
||||
// runSkillTest can drain stderr for 5s after its unchanged CLI deadline.
|
||||
// Let cleanup and failure recording finish before Bun starts a retry.
|
||||
const CSO_FINALIZE_MS = SESSION_DRAIN_GRACE_MS + 5_000;
|
||||
let captureSequence = 0;
|
||||
afterAll(() => finalizeEvalCollector(evalCollector));
|
||||
|
||||
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')}.
|
||||
GSTACK_HOME is already set to the private evaluation state directory.
|
||||
Complete the helper-owned report even when coverage is partial. Do not use AskUserQuestion or request new scope.
|
||||
Use one sequential challenge (independent agent unavailable for this evaluation); do not spawn agents.
|
||||
This is a static audit: do not execute the application, test provider credentials, or install dependencies.
|
||||
Do not read or execute files outside this repository except the trusted skill/helper and its private run artifacts.`;
|
||||
}
|
||||
|
||||
describeIfSelected('CSO v3 — full audit', ['cso-full-audit'], () => {
|
||||
test('/cso persists supported tenant-boundary findings with redacted evidence', async () => {
|
||||
await withFixture({
|
||||
'package.json': PACKAGE,
|
||||
'.env': `PROVIDER_TOKEN=${CANARY}\n`,
|
||||
'server.js': `const http = require('node:http');
|
||||
const sessions = new Map([['alice-token', { tenant: 'alice' }], ['bob-token', { tenant: 'bob' }]]);
|
||||
const invoices = [{ id: 'invoice-a', tenant: 'alice', total: 42 }, { id: 'invoice-b', tenant: 'bob', total: 950 }];
|
||||
http.createServer((req, res) => {
|
||||
const user = sessions.get((req.headers.authorization || '').replace('Bearer ', ''));
|
||||
if (!user) { res.writeHead(401); return res.end('unauthorized'); }
|
||||
const id = req.url.split('/').pop();
|
||||
const invoice = invoices.find(item => item.id === id);
|
||||
if (!invoice) { res.writeHead(404); return res.end('not found'); }
|
||||
res.setHeader('Content-Type', 'application/json'); res.end(JSON.stringify(invoice));
|
||||
}).listen(3000);
|
||||
`,
|
||||
},undefined,async f=>{
|
||||
const result = await runSkillTest({
|
||||
testName: 'cso-full-audit',
|
||||
runId: `cso-full-audit-${process.env.EVALS_RUN_ID ?? runId}-${process.pid}-${++captureSequence}`,
|
||||
publicStreamDiagnostics: true,
|
||||
prompt: prompt(f, ''), workingDirectory: f.repo,
|
||||
env: { GSTACK_HOME: f.state }, maxTurns: 40, allowedTools: ['Bash', 'Read', 'Write', 'Grep', 'Glob'], timeout: CAPTURE_LONG_MS,
|
||||
});
|
||||
logCost('cso', result);
|
||||
let passed = false;
|
||||
try {
|
||||
expect(result.exitReason).toBe('success');
|
||||
expect(result.output).not.toContain(CANARY);
|
||||
expect(JSON.stringify(result.transcript)).not.toContain(CANARY);
|
||||
// Dedicated carve behavioral guard: a real audit must actually load its domain section.
|
||||
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.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;
|
||||
} finally {
|
||||
recordE2E(evalCollector, 'cso-full-audit', 'e2e-cso', result, { passed });
|
||||
}
|
||||
});
|
||||
}, CAPTURE_LONG_MS + CSO_FINALIZE_MS);
|
||||
});
|
||||
|
||||
describeIfSelected('CSO v3 — diff mode', ['cso-diff-mode'], () => {
|
||||
test('/cso --diff records its base and investigates changed security paths', async () => {
|
||||
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}`,
|
||||
publicStreamDiagnostics: true,
|
||||
prompt: prompt(f, '--diff'), workingDirectory: f.repo,
|
||||
env: { GSTACK_HOME: f.state }, maxTurns: 40, allowedTools: ['Bash', 'Read', 'Write', 'Grep', 'Glob'], timeout: CAPTURE_LONG_MS,
|
||||
});
|
||||
logCost('cso', result);
|
||||
let passed = false;
|
||||
try {
|
||||
expect(result.exitReason).toBe('success');
|
||||
const report = requireReport(f);
|
||||
expectDiffModeReport(report, f);
|
||||
passed = result.browseErrors.length === 0;
|
||||
} finally {
|
||||
recordE2E(evalCollector, 'cso-diff-mode', 'e2e-cso', result, { passed });
|
||||
}
|
||||
});
|
||||
}, CAPTURE_LONG_MS + CSO_FINALIZE_MS);
|
||||
});
|
||||
|
||||
describeIfSelected('CSO v3 — infra scope', ['cso-infra-scope'], () => {
|
||||
test('/cso --infra finds an attacker-to-credential execution path', async () => {
|
||||
await withFixture({ 'package.json': PACKAGE,
|
||||
'.github/workflows/comment.yml': `name: comment automation
|
||||
on:
|
||||
issue_comment:
|
||||
types: [created]
|
||||
permissions:
|
||||
contents: write
|
||||
jobs:
|
||||
reply:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Handle untrusted comment
|
||||
env:
|
||||
GH_TOKEN: \${{ secrets.GITHUB_TOKEN }}
|
||||
run: echo "\${{ github.event.comment.body }}"
|
||||
`,
|
||||
'Dockerfile': 'FROM node:22\nWORKDIR /app\nCOPY . .\nCMD ["node", "server.js"]\n',
|
||||
},undefined,async f=>{
|
||||
const result = await runSkillTest({
|
||||
testName: 'cso-infra-scope',
|
||||
runId: `cso-infra-scope-${process.env.EVALS_RUN_ID ?? runId}-${process.pid}-${++captureSequence}`,
|
||||
publicStreamDiagnostics: true,
|
||||
prompt: prompt(f, '--infra'), workingDirectory: f.repo,
|
||||
env: { GSTACK_HOME: f.state }, maxTurns: 40, allowedTools: ['Bash', 'Read', 'Write', 'Grep', 'Glob'], timeout: CAPTURE_LONG_MS,
|
||||
});
|
||||
logCost('cso', result);
|
||||
let passed = false;
|
||||
try {
|
||||
expect(result.exitReason).toBe('success');
|
||||
const report = requireReport(f);
|
||||
expect(report.policy.scope).toBe('infra');
|
||||
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);
|
||||
expect(chain).toMatch(/run(?: step|:)|shell|bash/i);
|
||||
expect(chain).toMatch(/GITHUB_TOKEN|contents:\s*write|repository write/i);
|
||||
// A missing USER directive is only a hardening lead without demonstrated attacker impact.
|
||||
expect(report.findings.some(item => item.location.path === 'Dockerfile' && /critical|high/.test(item.severity))).toBe(false);
|
||||
passed = result.browseErrors.length === 0;
|
||||
} finally {
|
||||
recordE2E(evalCollector, 'cso-infra-scope', 'e2e-cso', result, { passed });
|
||||
}
|
||||
});
|
||||
}, CAPTURE_LONG_MS + CSO_FINALIZE_MS);
|
||||
});
|
||||
@@ -160,7 +160,7 @@ describe('SKILL.md size budget regression (gate, free)', () => {
|
||||
* a tiny noise floor. A skill that was 100 KB at v1.47.0.0 and shrinks to
|
||||
* 250 bytes passes that check despite losing 99.75% of content. The
|
||||
* parity-suite content invariants cover this for 10 hand-picked skills
|
||||
* (cso, ship, plan-ceo, etc.); the remaining 41 skills had no per-skill
|
||||
* (ship, plan-ceo, etc.); the remaining 41 skills had no per-skill
|
||||
* shrinkage floor.
|
||||
*
|
||||
* Floor: 80% of the v1.47.0.0 baseline. v1.46 actual shrinkage is <1% per
|
||||
|
||||
@@ -54,28 +54,6 @@ function readShipUnion(): string {
|
||||
return readSkillUnion('ship');
|
||||
}
|
||||
|
||||
describe('CSO host permission boundary', () => {
|
||||
test('grants no raw source, mutation, search, question, or Agent tools', () => {
|
||||
const content = fs.readFileSync(path.join(ROOT, 'cso', 'SKILL.md'), 'utf-8');
|
||||
const fmEnd = content.indexOf('\n---', 4);
|
||||
const frontmatter = Bun.YAML.parse(content.slice(4, fmEnd)) as Record<string, unknown>;
|
||||
const allowed = frontmatter['allowed-tools'];
|
||||
expect(allowed).toEqual([
|
||||
'Bash(~/.claude/skills/gstack/bin/gstack-cso-launcher *)',
|
||||
'Bash(~/.claude/skills/gstack/bin/gstack-cso-launcher.exe *)',
|
||||
]);
|
||||
for (const broad of ['Bash', 'Read', 'Grep', 'Glob', 'Write', 'Agent', 'WebSearch', 'AskUserQuestion']) expect(allowed).not.toContain(broad);
|
||||
});
|
||||
|
||||
test('retains helper-only source access, sequential challenge, and honest host containment', () => {
|
||||
const content = readSkillUnion('cso');
|
||||
expect(content).toContain('Never use host `Read`/`Glob`/`Grep`');
|
||||
expect(content).toContain('sequential challenge; independent agent unavailable');
|
||||
expectMentions(content, [['do not', 'independent', 'reviewer']], 'content');
|
||||
expectMentions(content, [['does not', 'containment', 'sandbox']], 'content');
|
||||
});
|
||||
});
|
||||
|
||||
function readCodexSkillUnion(skill: string): string {
|
||||
const dir = path.join(CODEX_OUT, '.agents', 'skills', `gstack-${skill}`);
|
||||
const sections = path.join(dir, 'sections');
|
||||
@@ -340,8 +318,6 @@ describe('Update check preamble', () => {
|
||||
'benchmark/SKILL.md',
|
||||
'land-and-deploy/SKILL.md',
|
||||
'setup-deploy/SKILL.md',
|
||||
// CSO intentionally uses a private startup instead of the shared update,
|
||||
// session, learning, checkpoint, and telemetry PREAMBLE.
|
||||
];
|
||||
|
||||
for (const skill of skillsWithUpdateCheck) {
|
||||
@@ -691,8 +667,6 @@ describe('v0.4.1 preamble features', () => {
|
||||
'canary/SKILL.md',
|
||||
'land-and-deploy/SKILL.md',
|
||||
'setup-deploy/SKILL.md',
|
||||
// CSO's private startup intentionally omits the generic AUQ/session/
|
||||
// escalation PREAMBLE; its helper owns readiness and terminal state.
|
||||
];
|
||||
|
||||
const skillsWithPreamble = [...tier1Skills, ...tier2PlusSkills];
|
||||
@@ -972,8 +946,6 @@ describe('Completeness Principle in generated SKILL.md files', () => {
|
||||
'design-review/SKILL.md',
|
||||
'design-consultation/SKILL.md',
|
||||
'document-release/SKILL.md',
|
||||
// CSO reports complete/partial/not-assessed from its own evidence contract
|
||||
// and must not inherit the shared numerical completeness rubric.
|
||||
];
|
||||
|
||||
for (const skill of skillsWithPreamble) {
|
||||
@@ -985,7 +957,7 @@ describe('Completeness Principle in generated SKILL.md files', () => {
|
||||
}
|
||||
|
||||
test('Completeness Principle keeps compact scoring guidance in tier 2+ skills', () => {
|
||||
// CSO is intentionally exempt; use a regular tier 2+ PREAMBLE consumer.
|
||||
// Use a regular tier 2+ PREAMBLE consumer.
|
||||
const content = readSkillStartup(path.join(ROOT, 'review', 'SKILL.md'));
|
||||
expect(content).toContain('Completeness: X/10');
|
||||
expect(content).toContain('10 = all edge cases');
|
||||
|
||||
@@ -139,24 +139,8 @@ describe('/spec quality gate fallback (carved: gate-and-file section)', () => {
|
||||
});
|
||||
|
||||
describe('/spec fail-closed redaction (shared engine)', () => {
|
||||
test('the full taxonomy (with secret prefixes) lives in the generated /cso doc', () => {
|
||||
// cso is carved — the Secrets Archaeology prose + prefixes moved into
|
||||
// sections/audit-phases.md; read the skeleton+sections union.
|
||||
const csoDir = path.join(ROOT, 'cso');
|
||||
let cso = fs.readFileSync(path.join(csoDir, 'SKILL.md'), 'utf-8');
|
||||
const secDir = path.join(csoDir, 'sections');
|
||||
if (fs.existsSync(secDir)) {
|
||||
for (const f of fs.readdirSync(secDir).sort()) {
|
||||
if (f.endsWith('.md') && !f.endsWith('.md.tmpl')) cso += '\n' + fs.readFileSync(path.join(secDir, f), 'utf-8');
|
||||
}
|
||||
}
|
||||
expect(cso).toContain('AKIA');
|
||||
expect(cso).toMatch(/ghp_|gho_|ghs_/);
|
||||
expect(cso).toContain('sk-ant-');
|
||||
expect(cso).toContain('BEGIN');
|
||||
});
|
||||
test('/spec points to the full taxonomy without inlining the catalog', () => {
|
||||
expect(SEC_GEN).toMatch(/Full taxonomy.*lib\/redact-patterns\.ts|\/cso/);
|
||||
expect(SEC_GEN).toMatch(/Full taxonomy.*lib\/redact-patterns\.ts/);
|
||||
expect(SEC_GEN).toMatch(/~30 secret\/PII\/legal patterns/);
|
||||
});
|
||||
test('redaction routes through the shared gstack-redact bin, not inline regex', () => {
|
||||
|
||||
@@ -486,7 +486,6 @@ describe('setup --team / --no-team / -q', () => {
|
||||
[ "$1 $2" = '--no-env-file --config=/dev/null' ] && shift 2
|
||||
case "$*" in
|
||||
'install --production --frozen-lockfile') exit 0 ;;
|
||||
'build --help') echo 'Fixture Bun has no CSO compile flags'; exit 0 ;;
|
||||
*'/bin/gstack-migrate-claude-code --install-dir '*)
|
||||
[[ "$#" -eq 5 && "$2" = --install-dir && "$4" = --skills-dir ]] || exit 90
|
||||
exit 0 ;;
|
||||
|
||||
@@ -162,7 +162,6 @@ describe('selectTests map-diff wiring', () => {
|
||||
expect(result.selected).toContain('browse-basic'); // from map-diff
|
||||
expect(result.selected).toContain('retro'); // from pattern match
|
||||
expect(result.selected).toContain('retro-base-branch');
|
||||
expect(result.selected).not.toContain('cso-full-audit');
|
||||
expect(result.reason).toBe('map-diff');
|
||||
});
|
||||
|
||||
|
||||
@@ -111,26 +111,6 @@ describe('selectTests', () => {
|
||||
},
|
||||
);
|
||||
|
||||
test.each(['lib/cso/cli.ts', 'lib/cso/state.ts'])(
|
||||
'CSO runtime and report regressions select all three audit cases: %s', (file) => {
|
||||
const result = selectTests([file], E2E_TOUCHFILES);
|
||||
expect(result.reason).toBe('diff');
|
||||
expect(result.selected.sort()).toEqual(['cso-diff-mode', 'cso-full-audit', 'cso-infra-scope']);
|
||||
expect(E2E_TIERS['cso-diff-mode']).toBe('gate');
|
||||
expect(E2E_TIERS['cso-full-audit']).toBe('periodic');
|
||||
expect(E2E_TIERS['cso-infra-scope']).toBe('periodic');
|
||||
},
|
||||
);
|
||||
|
||||
test.each(['lib/redact-engine.ts', 'lib/redact-patterns.ts'])(
|
||||
'shared redaction changes retain CSO audit consumers: %s', (file) => {
|
||||
const result = selectTests([file], E2E_TOUCHFILES);
|
||||
for (const id of ['cso-diff-mode', 'cso-full-audit', 'cso-infra-scope']) {
|
||||
expect(result.selected).toContain(id);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
test('testing resolver source selects the same E2E consumers as its generated content', () => {
|
||||
const consumers = [
|
||||
['plan-eng-review/sections/review-sections.md', 'TEST_COVERAGE_AUDIT_PLAN'],
|
||||
@@ -306,7 +286,6 @@ describe('selectTests', () => {
|
||||
expect(result.selected).toContain('journey-ideation');
|
||||
// Should NOT include tests that don't depend on it
|
||||
expect(result.selected).not.toContain('retro');
|
||||
expect(result.selected).not.toContain('cso-full-audit');
|
||||
});
|
||||
|
||||
test.each(['test/helpers/ceo-finding-fixture.ts'])('mode input dependency selects its periodic eval: %s', file => {
|
||||
|
||||
@@ -18,7 +18,7 @@ const OBSERVED: Record<string, string> = {
|
||||
'free-tests.yml': 'free-suite,macos-named-regressions',
|
||||
'windows-smoke.yml': 'windows-smoke',
|
||||
'windows-scoped-tests.yml': 'windows-scoped-shard',
|
||||
'windows-setup-e2e.yml': 'windows-setup,windows-setup-recovery,windows-setup-cso,held-install-journey,held-install-trial,held-install-later-release',
|
||||
'windows-setup-e2e.yml': 'windows-setup,windows-setup-recovery,held-install-journey,held-install-trial,held-install-later-release',
|
||||
'quality-gate.yml': 'quality',
|
||||
'evals.yml': 'build-image,eval-slices',
|
||||
};
|
||||
|
||||
@@ -28,7 +28,7 @@ describe('ubicloud free-suite runner', () => {
|
||||
test('setup performs the CI job’s build steps', () => {
|
||||
const setup = read('scripts/ubicloud/setup-free-suite.sh');
|
||||
for (const command of ['bun install --frozen-lockfile', 'bun run gen:skill-docs --host all', 'bun run vendor:xterm',
|
||||
'bash browse/scripts/build-node-server.sh', 'bun run build:gates', 'bun run build:cso']) {
|
||||
'bash browse/scripts/build-node-server.sh', 'bun run build:gates']) {
|
||||
expect(freeSuite.some(step => step.run?.includes(command))).toBe(true);
|
||||
expect(setup).toContain(command);
|
||||
}
|
||||
|
||||
@@ -160,7 +160,7 @@ describe('Windows Setup E2E runs by install path', () => {
|
||||
expect(scope['runs-on']).toBe('ubuntu-24.04');
|
||||
expect(scope.steps[0].with).toEqual({ 'fetch-depth': 2, 'persist-credentials': false });
|
||||
const windowsJobs = Object.keys(setupE2e.jobs).filter(name => name !== 'windows-scope' && name !== 'trunk-dynamic-ci');
|
||||
expect(windowsJobs).toEqual(['windows-setup', 'windows-setup-recovery', 'windows-setup-cso', 'held-install-journey', 'held-install-trial', 'held-install-later-release']);
|
||||
expect(windowsJobs).toEqual(['windows-setup', 'windows-setup-recovery', 'held-install-journey', 'held-install-trial', 'held-install-later-release']);
|
||||
for (const name of windowsJobs) {
|
||||
expect([name, setupE2e.jobs[name]['runs-on'], setupE2e.jobs[name].needs, setupE2e.jobs[name].if])
|
||||
.toEqual([name, 'windows-latest', 'windows-scope', "needs.windows-scope.outputs.install == 'true'"]);
|
||||
|
||||
Reference in new issue
Block a user