Files
gstack/test/sdk-system-prompt-tripwire.test.ts
T
Garry Tanandcapy-ai[bot] daf661374f v1.93.10.0 wave(docs): #3590 #3591 #3819 #3618 #3824 #3828 (#3847)
* Attribute every paid trial's cost: bind label-named records by testName, price aborted SDK sessions from streamed usage, model-free cases cost $0

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix: case cost adds streamed sessions to record sums and keeps record cost_known

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix: the paid report headline counts ledger-only session cost once

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix: a cost-only record never sets the trial model

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* test: recordE2E writes cost_case_id only for a registered label-named case

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* docs: CHANGELOG for paid-report cost attribution (Unreleased)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix: the headline adds only streamed session cost; cache writes without a 5m key

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* docs: how the paid report prices a trial and what stays cost-unknown

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* Price PTY sessions from their transcripts: pin a session id, sum the session's and its subagents' usage into the ledger's streamed_cost_usd

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix: transcript pricing never throws from a PTY ledger writer

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* chore: pin transcript-cost.ts as non-behavioral at HARNESS_VERSION 6

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix: recognise --session-id= and --resume= forms

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* docs: CHANGELOG for PTY transcript pricing (Unreleased)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* docs: PTY sessions priced from their transcripts

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix: price PTY transcripts without adding a launch argument; native AUQ capture opts out

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* docs: harness notes and CHANGELOG match the transcript claim

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* feat(flaky): gstack-flaky run reruns a failed JUnit test once and ledgers the flake (GSTA-158)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix(flaky): stream output, keep unreported runner failures red, fail-closed duplicates and nonzero reruns

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix: pre-landing review fixes

gstack-flaky never greens an incomplete run: a targeted rerun needs the
runner's summary proving the first run complete, otherwise (and always for
generic runners) the rerun repeats the whole command. A rerun clears a test
only when it exits 0 and the test passes once on its first attempt. Killed
runners exit 3 (FLAKY_COMMAND_KILLED) and signals are forwarded. The first
report is restored at --junit with reruns kept beside it; ids are redacted at
every output; the ledger gets its own GSTACK_FLAKE_LEDGER_JUNIT; fixtures are
registered in FREE_FIXTURES.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix: latch cancellation and check whole-command rerun reports

A cancel forwarded to a runner that traps the signal now counts as killed for
every later attempt, so a cancelled job is never rerun or greened. A
whole-command rerun clears nothing when its report has a failed test, misses a
first-run test, or its runner counted failures outside the report.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix: whole-command rerun when coverage or runner-flaky tests can fail the run

A coverage threshold or a fail-on-flaky policy fails a run for a reason a
narrowed rerun cannot reproduce, so either forces a whole-command rerun.
--junit refuses an existing file that is not a JUnit report instead of
deleting it.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* feat(flaky): rerun the whole command by default; targeted rerun is opt-in

A rerun counts only on the runner's own full green verdict: exit 0, no failed
or missing test, nothing counted outside the report. That covers every way a
run can fail, which a narrowed rerun cannot (a coverage threshold with an lcov
reporter, a fail-on-flaky policy, a test never reached). --rerun-scope test
reruns the failed test alone, with its preconditions documented and the
complete-run checks kept as a safety net. An unreadable existing --junit file
is a usage error, not a crash.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* docs: gstack-flaky CHANGELOG entry and standalone-binaries row (GSTA-158)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* feat(flaky): quarantine registry for repeat flakes (GSTA-158 P2)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix(flaky): bound renewal dates; match non-ASCII paths in check --base

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix(flaky): reword the FLAKY_QUARANTINE_BASE hint so the egress scanner does not read it as a network op

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* test(agent-sdk): every SDK caller passes the claude_code preset or names why not

The SDK's default system prompt is a bare stub that drops the line telling the
model to run /skill through the Skill tool. runAgentSdkTest now refuses a
missing, empty or bare-string prompt; non-preset callers name a reason; a free
tripwire scans test/ and scripts/ for the same mistake.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* test: record the SDK prompt guard as a non-behavioral harness change and baseline its tripwire

harness-version: runAgentSdkTest validates systemPrompt before starting; every
live caller already passed the claude_code preset, so no verdict can change.
test-of-test ratchet: the tripwire's subject is the eval harness by design.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* docs: name the preset literal callers pass and the unnamed-prompt refusal

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* feat(eval-plan): frontier models under test (R54)

Haiku and Sonnet are not models under test. dry-run refuses a plan whose every
arm is Haiku or Sonnet unless --tier-question names what it asks about that
tier, warns on a mix, and re-costs the plan on Opus 5.5 and GPT-6.1 Sol.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix(eval-plan): trim R54 skill prose and raise the eval-plan context ceiling

The R54 paragraph and CHECK: frontier bullet were cut to the minimum; the
exemptions and verdict rule stay in docs/TESTING_INTERNALS.md. The remaining
growth is the feature, so only the eval-plan eager ceiling moves (4887 -> 5458,
the capture helper's value); other skills' ceilings are left as they were.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix(eval-plan): pilot start keeps the R54 refusal; --tier-question rejects a flag

Review pass 1 (full depth) found the frontier refusal could be skipped by
starting a pilot on Haiku or Sonnet arms behind a dry run made on other arms,
or behind a dry-run.json written before the check existed. startPilot now
refuses a pilot whose every arm is Haiku or Sonnet unless its dry run recorded
a tier question. dry-run --tier-question no longer takes the next flag as its
answer. The testing doc now says the frontier re-cost is printed for
comparison with the brief cap, not enforced.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* docs(support-tiers): Windows CI in the present tense now that windows-smoke is required (#3806)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* chore: empty commit for a clean check set at the same tree (cancelled orphan free-suite check at 97487df)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* docs(skills): /eval-plan entry names the R54 frontier check

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

---------

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
2026-11-02 17:44:00 +00:00

136 lines
8.0 KiB
TypeScript

/**
* Every Agent SDK caller hands Claude Code its real system prompt, or names
* why not. Without systemPrompt the SDK runs a bare stub that drops the "run
* /skill via Skill" line, so a skill arm never learns to load its skill and a
* null result means nothing (docs/TESTING_INTERNALS.md#agent-sdk-system-prompt).
*/
import { describe, test, expect } from 'bun:test';
import * as fs from 'fs';
import * as path from 'path';
import { CLAUDE_CODE_PRESET, sdkSystemPrompt } from './helpers/sdk-system-prompt';
import { runAgentSdkTest } from './helpers/agent-sdk-runner';
const ROOT = path.resolve(import.meta.dir, '..');
const SELF = 'test/sdk-system-prompt-tripwire.test.ts';
const DEFINERS = new Set(['test/helpers/agent-sdk-runner.ts', 'test/helpers/sdk-system-prompt.ts']);
/** Index just past the bracket that closes the one opened at text[open]. */
function closeOf(text: string, open: number): number {
const pairs: Record<string, string> = { '(': ')', '{': '}', '[': ']' };
const stack: string[] = [];
for (let i = open; i < text.length; i++) {
const c = text[i]!;
if (c === '/' && text[i + 1] === '/') { i = text.indexOf('\n', i); if (i < 0) return text.length; continue; }
if (c === '/' && text[i + 1] === '*') { i = text.indexOf('*/', i + 2) + 1; continue; }
if (c === "'" || c === '"' || c === '\x60') {
for (i++; i < text.length && text[i] !== c; i++) if (text[i] === '\\') i++;
continue;
}
if (pairs[c]) stack.push(pairs[c]!);
else if (c === stack[stack.length - 1]) { stack.pop(); if (!stack.length) return i + 1; }
}
return text.length;
}
/** Text of one property value: from after "key:" to the next top-level , } or ). */
function valueAt(text: string, start: number): string {
let i = start;
while (i < text.length && !',})'.includes(text[i]!)) {
const c = text[i]!;
if ('({['.includes(c)) { i = closeOf(text, i); continue; }
if (c === "'" || c === '"' || c === '\x60') { for (i++; i < text.length && text[i] !== c; i++) if (text[i] === '\\') i++; }
i++;
}
return text.slice(start, i).trim();
}
/** Why a systemPrompt value is refused, or null when it is the preset, names its reason, or forwards a caller's value. */
export function promptValueProblem(value: string): string | null {
if (/^['"\x60]/.test(value)) return 'a bare string prompt (empty runs the SDK stub); pass CLAUDE_CODE_PRESET or name a reason';
if (/^[\w$.?]+$/.test(value)) return null;
const objects = [...value.matchAll(/\{[^{}]*\}/g)].map(m => m[0]);
if (!objects.length) return null;
for (const o of objects) {
if (/type:\s*'preset'/.test(o) && /preset:\s*'claude_code'/.test(o)) continue;
if (/type:\s*'(sdk-default|custom)'/.test(o) && /reason:\s*(['"\x60])\s*[^'"\x60\s][^'"\x60]*\1/.test(o)) continue;
return 'a prompt that is neither the Claude Code preset nor a named sdk-default/custom reason';
}
return null;
}
/** Every refused systemPrompt and every SDK call that omits one, in one file's source. */
export function scanSource(file: string, source: string): string[] {
const problems: string[] = [];
const line = (i: number) => source.slice(0, i).split('\n').length;
if (!DEFINERS.has(file)) {
for (const m of source.matchAll(/\bsystemPrompt\s*:/g)) {
const problem = promptValueProblem(valueAt(source, m.index! + m[0].length));
if (problem) problems.push(file + ':' + line(m.index!) + ': ' + problem);
}
}
const sdk = /import\s*\{[^}]*\bquery\b[^}]*\}\s*from\s*'@anthropic-ai\/claude-agent-sdk'|\(await import\('@anthropic-ai\/claude-agent-sdk'\)\)\.query|const\s*\{\s*query\s*\}\s*=\s*await import\('@anthropic-ai\/claude-agent-sdk'\)/.test(source);
const calls = [...source.matchAll(/(?<![\w.])runAgentSdkTest\(/g)].map(m => m.index! + m[0].length - 1);
if (sdk && !DEFINERS.has(file)) calls.push(...[...source.matchAll(/(?<![\w.])query\(/g)].map(m => m.index! + m[0].length - 1));
for (const open of calls) {
if (/function\s+runAgentSdkTest\($/.test(source.slice(Math.max(0, open - 40), open + 1))) continue;
const arg = source.slice(open + 1, closeOf(source, open) - 1).trim();
if (!arg.startsWith('{')) continue;
if (/\bsystemPrompt\b|\.\.\.\s*sdkSystemPrompt\(/.test(arg)) continue;
if (/\.\.\./.test(arg)) continue;
problems.push(file + ':' + line(open) + ': SDK call without systemPrompt; pass CLAUDE_CODE_PRESET or name a reason');
}
return problems;
}
function trackedSources(): string[] {
const out: string[] = [];
const walk = (dir: string) => {
for (const entry of fs.readdirSync(path.join(ROOT, dir), { withFileTypes: true })) {
const rel = path.posix.join(dir, entry.name);
if (entry.isDirectory()) { if (entry.name !== 'node_modules' && rel !== 'test/fixtures') walk(rel); }
else if (/\.tsx?$/.test(entry.name) && rel !== SELF) out.push(rel);
}
};
walk('test'); walk('scripts');
return out;
}
describe('Agent SDK system prompt tripwire', () => {
test('every runAgentSdkTest and SDK query caller passes the preset or names its reason', () => {
const files = trackedSources();
const problems = files.flatMap(file => scanSource(file, fs.readFileSync(path.join(ROOT, file), 'utf8')));
expect(problems).toEqual([]);
const callers = files.filter(file => /(?<![\w.])runAgentSdkTest\(/.test(fs.readFileSync(path.join(ROOT, file), 'utf8')));
expect(callers).toContain('test/helpers/ship-hook-actor.ts');
expect(callers.length).toBeGreaterThan(10);
});
test('the scanner refuses a missing, empty, bare or unnamed prompt and accepts the preset, a named reason or a forward', () => {
const scan = (body: string) => scanSource('x.ts', body);
expect(scan("runAgentSdkTest({ userPrompt: 'go', workingDirectory: d })")).toHaveLength(1);
expect(scan("runAgentSdkTest({ systemPrompt: '', userPrompt: 'go' })")).toHaveLength(1);
expect(scan("runAgentSdkTest({ systemPrompt: 'be terse', userPrompt: 'go' })")).toHaveLength(1);
expect(scan("runAgentSdkTest({ systemPrompt: { type: 'sdk-default', reason: '' }, userPrompt: 'go' })")).toHaveLength(1);
expect(scan("import { query } from '@anthropic-ai/claude-agent-sdk';\nquery({ prompt: 'p', options: { tools: [] } })")).toHaveLength(1);
expect(scan("runAgentSdkTest({ systemPrompt: { type: 'preset', preset: 'claude_code' }, userPrompt: 'go' })")).toEqual([]);
expect(scan("runAgentSdkTest({ systemPrompt: a ? { type: 'preset', preset: 'claude_code', append: x } : { type: 'preset', preset: 'claude_code' } })")).toEqual([]);
expect(scan("runAgentSdkTest({ systemPrompt: { type: 'sdk-default', reason: 'stub provider' }, userPrompt: 'go' })")).toEqual([]);
expect(scan("runAgentSdkTest({ systemPrompt: CLAUDE_CODE_PRESET, userPrompt: 'go' })")).toEqual([]);
expect(scan("runAgentSdkTest({ ...options, signal })")).toEqual([]);
expect(scan("const o = { systemPrompt: options.systemPrompt };")).toEqual([]);
expect(scan("import { query } from '@anthropic-ai/claude-agent-sdk';\nquery({ prompt: 'p', options: { ...sdkSystemPrompt({ type: 'sdk-default', reason: 'probe' }) } })")).toEqual([]);
expect(scan("import { query } from '@anthropic-ai/claude-agent-sdk';\nquery({ ...args, options: { ...args.options, cwd } })")).toEqual([]);
});
test('the runner refuses a bare or unnamed prompt before it starts', async () => {
const queryProvider = (() => { throw new Error('query must not run'); }) as never;
for (const systemPrompt of ['', 'be terse', undefined, { type: 'sdk-default', reason: ' ' }, { type: 'custom', reason: 'x' }]) {
await expect(runAgentSdkTest({ systemPrompt: systemPrompt as never, userPrompt: 'go', workingDirectory: ROOT, queryProvider, maxRetries: 0 }))
.rejects.toThrow('docs/TESTING_INTERNALS.md#agent-sdk-system-prompt');
}
expect(sdkSystemPrompt(CLAUDE_CODE_PRESET)).toEqual({ systemPrompt: CLAUDE_CODE_PRESET });
expect(sdkSystemPrompt({ type: 'sdk-default', reason: 'stub provider' })).toEqual({});
expect(sdkSystemPrompt({ type: 'custom', text: 'be terse', reason: 'overlay-only arm' })).toEqual({ systemPrompt: 'be terse' });
});
});