Files
gstack/test/plan-scope-selection.test.ts
Garry TanandOpenAI Codex 9f81911136 v1.86.0.0 feat: route outside reviews by harness (#2850)
* feat: add a restricted and supervised Claude Code runner

Preserve configured authentication and models while enforcing tool access, strict completion JSON, bounded output and process cleanup. Cover argv, failure handling, session metadata and Windows process containment.

* feat: route outside reviews by harness and migrate wrapper installs

Use Claude Code from Codex and Codex from other supported hosts, with shared invocation rendering, positive gate validation and per-phase provenance. Rename /claude to /claude-code, repair managed shared and copied installations safely, and generate native Kiro skills. Add installed-workflow, failure-injection and live cross-harness regression coverage.

* test: recognize CEO mode labels without terminal spacing

The paid workflow rendered SCOPEEXPANSION at option 4, but its driver required a literal space. Match the leading mode title without cursor-spacing artifacts and ignore adjacent preview text. Preserve missing-target failures and downstream posture assertions.

* test: isolate plan-count fixtures before starting review workflows

Seed the complete test plan in a private git repository before launching Claude, so a bare slash command cannot review the live workspace while a delayed fixture message remains queued. Preserve count thresholds, parsers and budgets. Add initial-context and installed-discovery tests, and retain startup/terminal diagnostics on failed evaluations.

* test: stabilize review fixtures and Claude eval startup

Preserve source boundaries in workflow judge inputs, isolate CEO mode plans, and wait for interactive trust input readiness. Keep startup failure evidence and retain existing models, budgets, and assertions.

Co-Authored-By: OpenAI Codex <noreply@openai.com>

* test: classify collapsed review modes and isolate seeded findings

Keep review questions out of the setup count when terminal cursor positioning removes spaces. State existing webhook safeguards so the five-finding control measures its seeded defects without accidental extra security and concurrency gaps. Preserve question bands and the paired control.

Co-Authored-By: OpenAI Codex <noreply@openai.com>

* test: isolate browser daemon state across free shards

Co-Authored-By: OpenAI Codex <noreply@openai.com>

* test: stabilize native review counting and interactive navigation

Co-Authored-By: OpenAI Codex <noreply@openai.com>

* chore: prepare v1.82.0.0 release

Co-Authored-By: OpenAI Codex <noreply@openai.com>

* fix: eliminate browser and process-cleanup test flakes

Pin every CI surface to Bun 1.4.0 to avoid extra-stdio finalizers closing
reused live sockets. Add an isolated GC/listener regression that fails on
Bun 1.3.13, and prevent coordinated rollback to an affected CI runtime.

Check renderer cleanup against the render's own staging directory so
concurrent renders cannot invalidate the assertion. Make the no-pgrep
process-tree walk tolerate disappearing /proc entries, and synchronize
its test fixture through child readiness and pipe EOF instead of sleeps.

Validation: 9,157 passed, 31 skipped, zero failures across 556 files with
retries disabled. Build, all-host generation freshness, and skill checks
passed. All three races have failing-before/passing-after regressions.

* fix: count completed native review questions in evals

* fix: drive review navigation from confirmed native choices

* fix: require complete section-loading eval reports

* test: isolate telemetry HTTP transport from local assertions

* fix: keep review input on the active native question

* test: let tunnel revocation daemon choose an available port

* test: allocate available ports for pairing and watchdog fixtures

* fix: stabilize planning eval navigation and phase reporting

* test: isolate installed runtime paths in planning evals

* test: stabilize review evidence and concurrent refresh fixtures

* fix: resolve design findings before editing the plan

* fix: honor and persist disabled outside plan reviews

* fix: preserve planning decisions and terminal evidence

Load installed host reviews at autoplan phase entry and wait for completed
reviewers and saved artifacts. Reuse approved remedies while preserving
individual finding decisions.

Drive interactive evals from the current terminal viewport, bind native
questions across scrolling, and require complete native report evidence.
Cover captured stale menus, permission lifecycles, setup classification,
and disabled-review tool availability with deterministic regressions.

Advance release metadata and the upgrade migration to the unclaimed
1.83.0.0 slot.

* fix: drive native review questions and preserve current plans

Use the native single-choice keyboard protocol and current terminal viewport,
with per-question navigation inside packets and completed-call coverage.
Keep permissions, multi-select menus, and Submit controls distinct.

Send Autoplan reviewers the amended implementation plan, keep its review record
separate, and supply retained application contracts in the chain fixture.
Clarify individual DevEx decisions and complete CEO fix options; use one active
plan destination for the section-loading report.

* fix: preserve complete plan-review decisions

* fix: recognize native plan dialogs and reviewer controls

* fix: preserve review decisions and phase completion

* fix: recognize completed reviews without losing findings

* fix: preserve review continuity and native eval completion

* test: fix native review completion and eval retry isolation

* test: handle native review menus and complete eval fixtures

* test: fix native review setup, completion, and isolation failures

* test: limit native skill discovery to runtime assets

* fix: bind Autoplan reviews to full ordered phase inputs

* test: fix planning eval routing, counting, and timeout handling

* chore: advance queued release to v1.84.0.0

* fix: preserve complete review inputs and planning decisions

* fix: reconcile review approvals and preserve phase obligations

* fix: preserve review obligations and unblock eval permissions

Carry recorded Autoplan requirements into blind phase inputs, require Eng
review approvals before exit, and exercise combined asynchronous flows in
CEO reviews. Correct native finding and handoff classification and unblock
repeated report edits using scoped request identities.

* fix: retain plan requirements and complete native review dialogs

* fix: complete native review prompts and retain plan references

* fix: preserve review inputs and classify native eval evidence

* fix: check competing completion orders in CEO reviews

* fix: recognize review decisions and require phase methodology

Require the current phase methodology before Autoplan snapshots. Correct
substantive decision, closed handoff, and cache-finding classification, and
honor the recommended implementation approach in native review dialogs.

Add captured-transcript regressions without changing review thresholds,
provider models, retries, or deadlines.

* test: bind native review decisions and close completed handoffs

* fix: complete review dialogs and verify methodology delivery

* fix: preserve review evidence and unblock native eval prompts

* fix: handle native review question completions

* fix: recognize native review narration and controls

* fix: count native review decisions and isolate eval fixtures

* test: verify seeded review coverage and current artifact permissions

* test: isolate model and brain-aware skill renders

* fix: repair native workflow evaluation and clarify review steps

* fix: stabilize workflow eval evidence and review guidance

* test: repair native workflow observation and fixture isolation

* fix: recognize completed workflow evidence and owned skill reads

* test: repair seeded workflow delivery and completion evidence

* test: recognize current review evidence across native forms

* test: handle native review variants and permission redraws

* fix: honor review preferences and recognize native eval evidence

* test: recognize completed review decisions and queued permissions

* test: match current review contracts and partial-line edits

* test: recognize completed workflow evidence and bounded human waits

* fix: preserve review entry gates and native eval interactions

* fix: recognize native workflow evidence and preserve review gates

* test: recognize current review evidence and preconfigure workflow fixtures

* test: recognize completed review findings and scoped artifact permissions

* fix: stabilize native workflow review and permission evidence

* fix: recognize current review evidence and scoped edit confirmations

Clarify Design and engineering review entry instructions and Design scoring.
Recognize required legacy coverage and public Autoplan completion recaps.
Bind the pending Edit confirmation to its exact file, ordered digest, and
one-request approval when a preceding command display remains visible.
Keep reviews within their existing size limits and preserve scope gates
when extracting workflow fixtures from either supported preamble header.

Keep failure outcomes, review thresholds, provider choices, and eval budgets.

* fix: recover review workflow progress and eval evidence

* fix: recognize valid review evidence and scope selection

* test: fix review evidence parsing and repeated artifact prompts

* test: recognize valid review decisions and pending native cards

* fix(plan-eng-review): keep final navigation consistent with approved tasks

* test: recognize valid review evidence and bind legacy diff requests

* fix: stabilize review eval evidence and harness repair guidance

* docs: update project documentation for v1.85.0.0

Co-Authored-By: OpenAI Codex <noreply@openai.com>

* test: fix Windows CI fixtures and credential scan

Rebase captured JSON values and filesystem evidence using the appropriate
path convention. Compile native fake CLIs on Windows and synchronize pipe
holder readiness, with cleanup retained when assertions fail.

Assemble synthetic credential fixtures at runtime so the added-line scan
keeps enforcing the same gate without flagging its own rejection controls.

Discover generated skills directly for the empty-find regression check,
avoiding a recursive scan through saved evaluation artifacts and dependencies.

* fix: preserve source renders on Windows

Compare canonical generator paths using native separators so an output
sidecar pointing at the source cannot overwrite its skill or metadata.
Keep the regression fixture isolated from the real checkout and expose
freshness diagnostics before asserting subprocess status.

Detach Windows drain-test pipe holders from the fake provider's automatic
child cleanup while preserving the enclosing runner job and its assertions.

* fix: clarify outside review fallback and CEO decisions

Render one applicable own-harness fallback path and retain native review,
disabled policy, and missing-coverage semantics. Align report field names
and mode labels, and make the existing per-cut scope approval explicit.

Regenerate skill outputs and keep the workflow judge's model, thresholds,
and retry policy unchanged.

* chore: move release to free version slot (v1.86.0.0)

PR #2852 now claims v1.85.0.0. Align the release metadata and
rename migration so upgrades from that version still receive it.

Co-Authored-By: OpenAI Codex <noreply@openai.com>

* fix: include engineering review prerequisites and restore branch context

* fix: recognize coverage diagrams and clarify design review instructions

* fix: preserve file identities and join Windows test processes

---------

Co-authored-by: OpenAI Codex <noreply@openai.com>
2026-09-14 14:32:45 -07:00

428 lines
28 KiB
TypeScript

import { expect, test } from 'bun:test';
import awFixture from './fixtures/plan-scope-target-aw.json';
import agFixture from './fixtures/design-plan-scope-ag.json';
import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
import { pathToFileURL } from 'node:url';
import { createFakeBunCli } from './helpers/fake-bun-cli';
import { nativeSeededPlanSelection } from './helpers/plan-scope-selection';
import { isScopeGateQuestionVisible } from './helpers/claude-pty-runner';
import { readPlanCountTranscript, type NativePublicToolEvent, type PlanCountTranscript } from './helpers/plan-count-transcript';
import { selectTests, E2E_TOUCHFILES } from './helpers/touchfiles';
const START = Date.parse('2026-09-10T00:25:00Z');
const opts = { seed: '# Plan: Marketing landing page\n\n## Layout\nA draft.', skillName: 'plan-design-review', sessionId: 'owned', commandStartedAt: START };
const timestamp = (delta: number) => new Date(START + delta).toISOString();
const announcements = [
`I'll review the "Marketing landing page" draft plan pasted here, starting with a parallel check of the pre-review audit, base branch, design setup, and brain context.`,
`I'm proceeding with reviewing the "Marketing landing page" draft you pasted. Next, I'll run the pre-review audit: checking git context, DESIGN.md/TODOS.md, design binary setup, and brain context.`,
];
const agAnnouncement = agFixture.observations[1]!.transcript.assistantMessages.find(message => message.text.startsWith("I've selected"))!.text;
const fixture = (text = announcements[0]!) => ({
transcript: { status: 'ready', calls: [], assistantMessages: [{ sessionId: 'owned', timestamp: timestamp(3), text }] } as PlanCountTranscript,
tools: [
{ kind: 'use', name: 'Skill', input: { skill: 'plan-design-review' }, toolUseId: 'load', sessionId: 'owned', timestamp: timestamp(1) },
{ kind: 'result', isError: false, toolUseId: 'load', sessionId: 'owned', timestamp: timestamp(2) },
] as NativePublicToolEvent[],
});
const verdict = (f = fixture(), options = opts) => nativeSeededPlanSelection(f.transcript, f.tools, options);
const axAnnouncements = [
`I'll invoke the /plan-design-review skill to review this landing page plan.`,
`I'll run the plan-design-review skill on your draft landing-page plan.`,
];
test('AX title-derived descriptors bind the unique pasted plan before or after skill load', () => {
for (const text of axAnnouncements) for (const delta of [1, 6]) {
const f = fixture(text); f.transcript.assistantMessages[0]!.timestamp = timestamp(delta);
f.tools[0]!.timestamp = timestamp(4); f.tools[1]!.timestamp = timestamp(5);
expect(verdict(f), text).toBe(true);
}
for (const text of [
`I will review this MARKETING landing-page plan.`,
`I'll review your draft landing page plan.`,
`I'll review the landing-page plan.`,
]) expect(verdict(fixture(text))).toBe(true);
expect(verdict(fixture(axAnnouncements[0]!), { ...opts, seed: '# Plan: MARKETING landing-page\n' })).toBe(true);
expect(verdict(fixture(`I'll review this checkout plan.`), { ...opts, seed: '# Plan: Checkout page\n' })).toBe(true);
});
test('a descriptor must be a contiguous whole-word portion of the unique seed title', () => {
for (const descriptor of ['pricing page', 'Marketing page', 'land', 'landing pages', 'checkout', 'other landing page']) {
const text = `I'll review this ${descriptor} plan.`;
expect(verdict(fixture(text), { ...opts, seed: opts.seed + `\nBody mentions ${descriptor}.` }), descriptor).toBe(false);
}
expect(verdict(fixture(axAnnouncements[0]!), { ...opts, seed: opts.seed + '\n# Plan: Another landing page' })).toBe(false);
});
test('described targets retain the affirmative, Skill, timing and current-selection guards', () => {
for (const text of axAnnouncements) {
for (const invalid of [
`> ${text}`, `"${text}"`, ` ${text}`, `Source:\n${text}`, `\`\`\`\n${text}\n\`\`\``,
text.replace("I'll", 'I might'), text.replace("I'll", "I won't"), text.replace(/\.$/, '?'),
`If approved, ${text}`, text.replace(/\.$/, ' if approved.'),
text.replace('plan-design-review', 'plan-eng-review'), text.replace(/\.$/, ' or another plan.'),
]) expect(verdict(fixture(invalid)), invalid).toBe(false);
for (const mutate of [
(f: ReturnType<typeof fixture>) => { f.transcript.assistantMessages[0]!.sessionId = 'foreign'; },
(f: ReturnType<typeof fixture>) => { f.transcript.assistantMessages[0]!.timestamp = timestamp(0); },
(f: ReturnType<typeof fixture>) => { f.tools[1]!.isError = true; },
(f: ReturnType<typeof fixture>) => { f.tools[0]!.input!.skill = 'plan-eng-review'; },
(f: ReturnType<typeof fixture>) => { f.tools[0]!.input!.args = 'Review the branch diff.'; },
(f: ReturnType<typeof fixture>) => { f.tools.push({kind:'use',name:'Read',sessionId:'owned',toolUseId:'work',timestamp:timestamp(2.5)}); },
]) { const f = fixture(text); mutate(f); expect(verdict(f)).toBe(false); }
for (const correction of ['This selection is withdrawn.', 'The selected target is now the branch diff.', 'I will review "Another plan" plan.', 'I will review your checkout page plan.']) {
const f = fixture(text); f.transcript.assistantMessages.push({sessionId:'owned',timestamp:timestamp(4),text:correction});
expect(verdict(f), correction).toBe(false);
}
}
});
test('actual AF public selection wording needs this seed, parent and completed skill boundary', () => {
for (const text of announcements) expect(verdict(fixture(text))).toBe(true);
const f = fixture(); f.tools[0]!.input!.skill = 'gstack:plan-design-review'; expect(verdict(f)).toBe(true);
expect(verdict(fixture(), { ...opts, seed: '# Plan: Other page' })).toBe(false);
expect(verdict(fixture(), { ...opts, seed: opts.seed + '\n# Another plan' })).toBe(false);
});
test('a late seed reply, wrong parent, failed load or missing native data supplies no selection', () => {
for (const mutate of [
(f: ReturnType<typeof fixture>) => { f.transcript.status = 'missing'; },
(f: ReturnType<typeof fixture>) => { f.transcript.status = 'error'; },
(f: ReturnType<typeof fixture>) => { f.transcript.assistantMessages[0]!.sessionId = 'foreign'; },
(f: ReturnType<typeof fixture>) => { f.transcript.assistantMessages[0]!.timestamp = timestamp(0); },
(f: ReturnType<typeof fixture>) => { f.transcript.assistantMessages[0]!.timestamp = 'unknown'; },
(f: ReturnType<typeof fixture>) => { f.tools[0]!.timestamp = timestamp(-2); f.tools[1]!.timestamp = timestamp(-1); },
(f: ReturnType<typeof fixture>) => { f.tools[0]!.name = 'Read'; },
(f: ReturnType<typeof fixture>) => { f.tools[0]!.input!.skill = 'plan-ceo-review'; },
(f: ReturnType<typeof fixture>) => { f.tools[1]!.isError = true; },
(f: ReturnType<typeof fixture>) => { f.tools[1]!.sessionId = 'foreign'; },
(f: ReturnType<typeof fixture>) => { f.tools[1]!.toolUseId = 'other'; },
(f: ReturnType<typeof fixture>) => { f.tools[1]!.timestamp = timestamp(0); },
(f: ReturnType<typeof fixture>) => { f.tools.pop(); },
(f: ReturnType<typeof fixture>) => { f.tools.push({ ...f.tools[1]! }); },
]) { const f = fixture(); mutate(f); expect(verdict(f)).toBe(false); }
});
test('quotes, examples, questions, wrong targets and conditional intentions remain negative', () => {
const text = announcements[0]!;
for (const invalid of [
`> ${text}`, ` ${text}`, ` ${text}`, `"${text}"`, `Example:
${text}`, `Expected output:
${text}`, `Original message:
${text}`, `An unproven hypothesis:
${text}`, `A proposed response:
${text}`,
`\`\`\`text\n${text}\n\`\`\``, `\`\`\`\`markdown\n\`\`\`\n${text}\n\`\`\`\``,
text.replace("I'll review", 'Should I review'), text.replace("I'll review", 'I might review'),
text.replace("I'll review", "I won't review"), text.replace('Marketing landing page', 'Other plan'),
text.replace('draft plan pasted here', 'branch diff'),
text.replace(', starting with', ', if approved, starting with'),
text.replace(', starting with', '. Unless you object, starting with'),
`I'll review the supplied plan.`, `I'll run the /plan-design-review skill.`,
]) expect(verdict(fixture(invalid)), invalid).toBe(false);
});
test('native reader rejects foreign cwd and source/tool text even when they contain the announcement', () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'scope-native-'));
try {
const journals = path.join(dir, 'projects', 'fixture'); fs.mkdirSync(journals, { recursive: true });
const make = (cwd: string, textKind = 'text') => [
{ type: 'assistant', isSidechain: false, cwd, sessionId: 'owned', timestamp: timestamp(1), message: { role: 'assistant', content: [{ type: 'tool_use', id: 'load', name: 'Skill', input: { skill: opts.skillName } }] } },
{ type: 'user', isSidechain: false, cwd, sessionId: 'owned', timestamp: timestamp(2), message: { role: 'user', content: [{ type: 'tool_result', tool_use_id: 'load', content: 'loaded', is_error: false }] } },
{ type: 'assistant', isSidechain: false, cwd, sessionId: 'owned', timestamp: timestamp(3), message: { role: 'assistant', content: [{ type: textKind, text: announcements[0] }] } },
];
for (const [cwd, kind, expected] of [[dir, 'text', true], [dir + '-foreign', 'text', false], [dir, 'thinking', false]] as const) {
fs.writeFileSync(path.join(journals, 'owned.jsonl'), make(cwd, kind).map(row => JSON.stringify(row)).join('\n') + '\n');
const tools: NativePublicToolEvent[] = [], transcript = readPlanCountTranscript(dir, dir, e => tools.push(e));
expect(nativeSeededPlanSelection(transcript, tools, opts)).toBe(expected);
}
} finally { fs.rmSync(dir, { recursive: true, force: true }); }
});
test('design scope question still requires the actual branch option', () => {
expect(isScopeGateQuestionVisible('D1—What should I design-review?\nA) Current branch diff\nB) A plan or design doc')).toBe(true);
expect(isScopeGateQuestionVisible('What should I design-review?')).toBe(false);
expect(isScopeGateQuestionVisible('I should design-review the current branch diff.')).toBe(false);
});
test('seeded plan selection dependencies select the existing design and Eng mode checks', () => {
for (const file of ['test/helpers/plan-scope-selection.ts', 'test/plan-scope-selection.test.ts']) {
const selection = selectTests([file], E2E_TOUCHFILES);
expect(selection.selected).toContain('plan-design-review-plan-mode'); expect(selection.selected).toContain('plan-eng-review-plan-mode');
}
});
test('real PTY observation binds its explicit session and retains public diagnostics before cleanup', async () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'scope-pty-'));
const cli = createFakeBunCli(path.join(dir, 'fake-claude'), `
const fs = require('node:fs'), path = require('node:path');
const args = process.argv.slice(2), id = args[args.indexOf('--session-id') + 1];
fs.writeFileSync(process.env.SCOPE_TEST_ARGV, JSON.stringify(args));
let sent = false;
process.stdin.on('data', chunk => {
if (sent || !chunk.toString().includes('/plan-design-review')) return;
sent = true;
const base = Date.now(), root = path.join(process.env.CLAUDE_CONFIG_DIR, 'projects', 'fixture');
fs.mkdirSync(root, {recursive:true});
const rows = [
['assistant', 1, [{type:'tool_use',id:'load',name:'Skill',input:{skill:'plan-design-review'}}]],
['user', 2, [{type:'tool_result',tool_use_id:'load',content:'loaded',is_error:false}]],
['assistant', 3, [{type:'text',text:${JSON.stringify(agAnnouncement)}}]],
].map(([type,n,content]) => JSON.stringify({type,isSidechain:false,cwd:process.cwd(),sessionId:id,timestamp:new Date(base+n).toISOString(),message:{role:type,content}}));
fs.writeFileSync(path.join(root,id+'.jsonl'), rows.join('\\n')+'\\n');
process.stdout.write('Reviewing the named draft.\\nA) Fix hierarchy\\nB) Keep hierarchy\\nRecommendation: A because the primary action needs emphasis.\\nReply with A or B.\\n');
});
setInterval(()=>{},1000);
`);
try {
// The executable override belongs to a separate process: parallel free
// tests cannot inherit it, and resolution is asserted before any spawn.
const runner = pathToFileURL(path.join(import.meta.dir, 'helpers/claude-pty-runner.ts')).href;
const childFile = path.join(dir, 'observe.ts');
fs.writeFileSync(childFile, `import { runPlanSkillObservation, resolveClaudeBinary } from ${JSON.stringify(runner)};
if (resolveClaudeBinary() !== process.env.BROWSE_TERMINAL_BINARY) throw new Error('Fake CLI resolution failed');
const obs = await runPlanSkillObservation({skillName:'plan-design-review',inPlanMode:true,initialPlanContent:${JSON.stringify(opts.seed)},timeoutMs:25000,env:{SCOPE_TEST_ARGV:process.env.SCOPE_TEST_ARGV}});
console.log(JSON.stringify(obs));
`);
const child = Bun.spawn([process.execPath, childFile], { cwd: process.cwd(),
env: { ...process.env, BROWSE_TERMINAL_BINARY: cli, SCOPE_TEST_ARGV: path.join(dir, 'argv.json'),
EVALS_RUN_ID: 'scope-fake', GSTACK_EVAL_DIR: path.join(dir, 'evidence') }, stdout: 'pipe', stderr: 'pipe' });
const [stdout, stderr, exitCode] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]);
expect(exitCode, stderr).toBe(0);
const obs = JSON.parse(stdout.trim().split('\n').at(-1)!);
expect(obs.outcome, JSON.stringify(obs)).toBe('asked'); expect(obs.scopeGateAutoSelectObserved).toBe(true);
const args = JSON.parse(fs.readFileSync(path.join(dir, 'argv.json'), 'utf8'));
expect(args.filter((arg: string) => arg === '--session-id')).toHaveLength(1);
const id = args[args.indexOf('--session-id') + 1]; expect(id).toMatch(/^[0-9a-f-]{36}$/);
const artifacts = obs.artifactDir; expect(typeof artifacts).toBe('string');
const saved = JSON.parse(fs.readFileSync(path.join(artifacts, 'observation.json'), 'utf8'));
expect(saved.scopeSessionId).toBe(id); expect(saved.native.assistantMessages.some((m: any) => m.sessionId === id)).toBe(true);
expect(saved.scopeGateAutoSelectObserved).toBe(true);
} finally { fs.rmSync(dir, { recursive: true, force: true }); }
}, 40_000);
test('AG spoken first declaration and explicit retry selection both bind their requested skill', () => {
const [first, retry] = agFixture.observations;
// The recorded failed outcome is unchanged; the first public intro names the design review skill.
expect(nativeSeededPlanSelection(first!.transcript as PlanCountTranscript, first!.tools as NativePublicToolEvent[], first!.opts)).toBe(true);
expect(nativeSeededPlanSelection(retry!.transcript as PlanCountTranscript, retry!.tools as NativePublicToolEvent[], retry!.opts)).toBe(true);
});
test('AG completed selection accepts ordinary grammar and the exact named pasted target', () => {
for (const text of [
`I've selected reviewing the pasted "Marketing landing page" draft plan since we're in plan mode. Now I'll run the pre-review audit.`,
'I have selected to review the pasted “Marketing landing page” plan because we are in plan mode. Next, I will run the audit.',
'I have selected reviewing the pasted `Marketing landing page` draft.',
]) expect(verdict(fixture(text)), text).toBe(true);
expect(verdict(fixture('I have selected to review the pasted "Other page" plan.')), 'wrong seed title').toBe(false);
});
test('AG completed selection rejects source text, conditional intent, wrong scope and questions', () => {
const text = `I've selected reviewing the pasted "Marketing landing page" draft plan since we're in plan mode.`;
for (const invalid of [
`> ${text}`, ` ${text}`, `\t${text}`, `"${text}"`, `Example:\n${text}`, `Expected output:\n\n${text}`,
`Original message:\n${text}`, `An unproven hypothesis:\n${text}`, `A proposed response:\n\n${text}`,
`\`\`\`text\n${text}\n\`\`\``,
text.replace("I've selected", 'I will select'), text.replace("I've selected", 'I might select'),
text.replace("I've selected", 'Have I selected'), text.replace("I've selected", "I haven't selected"),
text.replace('reviewing', 'not reviewing'), text.replace('since', 'if'),
text.replace("since we're in plan mode.", 'pending approval.'),
text.replace("since we're in plan mode.", 'tomorrow.'),
text.replace("since we're in plan mode.", 'unless you object.'),
text.replace("since we're in plan mode.", 'only after approval.'),
text.replace('draft plan since', 'branch diff since'), text.replace(/\.$/, '?'),
text + " Now I'll review the branch diff instead.",
'I have selected reviewing the supplied plan.',
]) expect(verdict(fixture(invalid)), invalid).toBe(false);
});
test('AG completed selection still requires this parent and a successful prior skill load', () => {
const text = `I've selected reviewing the pasted "Marketing landing page" draft plan since we're in plan mode.`;
for (const mutate of [
(f: ReturnType<typeof fixture>) => { f.transcript.status = 'missing'; },
(f: ReturnType<typeof fixture>) => { f.transcript.assistantMessages[0]!.sessionId = 'foreign'; },
(f: ReturnType<typeof fixture>) => { f.transcript.assistantMessages[0]!.timestamp = timestamp(0); },
(f: ReturnType<typeof fixture>) => { f.tools[0]!.input!.skill = 'plan-eng-review'; },
(f: ReturnType<typeof fixture>) => { f.tools[1]!.isError = true; },
(f: ReturnType<typeof fixture>) => { f.tools[1]!.sessionId = 'foreign'; },
(f: ReturnType<typeof fixture>) => { f.tools[1]!.toolUseId = 'other'; },
(f: ReturnType<typeof fixture>) => { f.tools.pop(); },
(f: ReturnType<typeof fixture>) => { f.tools.push({ ...f.tools[1]! }); },
]) { const f = fixture(text); mutate(f); expect(verdict(f)).toBe(false); }
expect(verdict(fixture(text), { ...opts, commandStartedAt: START + 10 })).toBe(false);
expect(verdict(fixture(text), { ...opts, sessionId: '' })).toBe(false);
expect(verdict(fixture(text), { ...opts, seed: opts.seed + '\n# Another plan' })).toBe(false);
});
test('AG actual scope fixture has exactly the existing two plan-mode owners', () => {
const selected = selectTests(['test/fixtures/design-plan-scope-ag.json'], E2E_TOUCHFILES).selected;
expect([...selected].sort()).toEqual(['plan-design-review-plan-mode', 'plan-eng-review-plan-mode']);
});
test('AG audit continuation cannot withdraw or relabel the current selection', () => {
const text = `I've selected reviewing the pasted "Marketing landing page" draft plan since we're in plan mode.`;
for (const tail of [
' Now I retract that selection.',
' Then cancel that selection; review the branch diff.',
' Next, treat that declaration as a hypothetical example.',
" Now I'll run the audit and retract that selection.",
" Next, I will start the audit and treat that declaration as a hypothetical example.",
" Now I'll run the audit. That selection was hypothetical.",
" Now I'll run the audit. That selection is cancelled.",
]) expect(verdict(fixture(text + tail)), tail).toBe(false);
expect(verdict(fixture(text + " Now I'll run the audit, including the examples in DESIGN.md."))).toBe(true);
expect(verdict(fixture(text + '\n\n> Example: cancel that selection.'))).toBe(true);
});
// These are public observation projections. Synthetic mutations below are
// controls; the recorded failed paid outcomes are never rewritten.
const awInput = (i = 0) => structuredClone(awFixture[i]!);
const awCheck = (p = awInput()) => nativeSeededPlanSelection(p.transcript as PlanCountTranscript, p.tools as NativePublicToolEvent[], p.opts);
test('AW first and retry select the unique pasted draft before loading the requested skill', () => {
expect(awFixture).toHaveLength(4);
for (const p of awFixture) {
expect(p.observed.scopeGateAutoSelectObserved).toBe(false);
expect(awCheck(p)).toBe(true);
expect(Date.parse(p.transcript.assistantMessages[0]!.timestamp)).toBeLessThan(Date.parse(p.tools[0]!.timestamp));
}
});
test('a current target may be announced before or after load, but always before review work', () => {
for (const i of [0, 1, 2, 3]) {
const p = awInput(i), m = p.transcript.assistantMessages[0]!;
m.timestamp = new Date(Date.parse(p.tools[1]!.timestamp) + 1).toISOString();
expect(awCheck(p)).toBe(true);
const title = /^#\s+(?:Plan:\s*)?(.+)$/m.exec(p.opts.seed)![1]!;
m.timestamp = new Date(p.opts.commandStartedAt + 1).toISOString();
m.text = `I'll review "${title}" plan.`;
expect(awCheck(p)).toBe(true);
m.timestamp = p.tools[2]!.timestamp;
expect(awCheck(p)).toBe(false);
}
});
test('new scope route rejects stale, foreign, premature or unsuccessful evidence', () => {
const controls: Array<(p: ReturnType<typeof awInput>) => void> = [
p => { p.transcript.assistantMessages[0]!.timestamp = new Date(p.opts.commandStartedAt - 1).toISOString(); },
p => { p.transcript.assistantMessages[0]!.timestamp = 'unknown'; },
p => { p.transcript.assistantMessages[0]!.sessionId = 'foreign'; },
p => { p.transcript.status = 'error'; },
p => { p.opts.seed += '\n# Plan: Another plan'; },
p => { p.tools[0]!.input!.skill = 'plan-ceo-review'; },
p => { p.tools[0]!.sessionId = 'foreign'; },
p => { p.tools[1]!.isError = true; },
p => { p.tools[1]!.toolUseId = 'unrelated'; },
p => { p.tools[1]!.sessionId = 'foreign'; },
p => { p.tools.splice(1, 1); },
p => { p.tools.push(structuredClone(p.tools[1]!)); },
p => { p.tools[2]!.timestamp = new Date(p.opts.commandStartedAt + 1).toISOString(); },
p => { p.tools[2]!.timestamp = new Date(Date.parse(p.tools[1]!.timestamp) - 1).toISOString(); },
p => { p.tools[2]!.timestamp = 'unknown'; },
p => { p.tools[0]!.timestamp = new Date(p.opts.commandStartedAt - 1).toISOString(); },
];
for (const [index, mutate] of controls.entries()) { const p = awInput(); mutate(p); expect(awCheck(p), `control ${index}`).toBe(false); }
});
test('unique-draft declarations must be affirmative and owned, not merely a skill introduction', () => {
for (const text of [
`I'll run the /plan-design-review skill.`, `I'll run the /plan-eng-review skill on this draft plan.`,
`I'll run the plan-design-review skill on this draft plan if approved.`,
`I'll run the plan-design-review skill on this draft plan?`,
`I'll run the plan-design-review skill on a draft plan.`,
`I might run the plan-design-review skill on this draft plan.`,
`I won't run the plan-design-review skill on this draft plan.`,
`I'll run the plan-design-review skill on this draft plan or another plan.`,
`If approved, I'll review this draft plan.`, `Provided the plan exists, I'll review this draft plan.`,
`> I'll review this draft plan.`, `"I'll review this draft plan."`, ` I'll review this draft plan.`,
`Source excerpt:\nI'll review this draft plan.`, `Historical note:\nI'll review this draft plan.`,
'```text\nI\'ll review this draft plan.\n```',
]) { const p = awInput(); p.transcript.assistantMessages[0]!.text = text; expect(awCheck(p), text).toBe(false); }
for (const text of [`I'll review this draft plan.`, `I will review your draft plan.`, `I'll run the gstack:plan-design-review skill against the draft plan.`]) {
const p = awInput(); p.transcript.assistantMessages[0]!.text = text; expect(awCheck(p), text).toBe(true);
}
});
test('Skill arguments cannot override the announced target or borrow a quoted matching title', () => {
for (const args of [
'branch diff', 'Review the draft plan "Another plan".',
'Review the branch diff; the old draft was "Marketing landing page".',
'Example: Review the draft plan "Marketing landing page".',
'"Review the draft plan \\"Marketing landing page\\"."',
'Review the draft plan "Marketing landing page" if approved.',
'Review the draft plan "Marketing landing page". Instead review the branch diff.',
'Review the draft plan "Marketing landing page" (not the target; review another plan).',
]) { const p = awInput(1); p.tools[0]!.input!.args = args; expect(awCheck(p), args).toBe(false); }
for (const args of ['Review the pasted \"Marketing landing page\" draft plan.', 'Review the draft plan \"Marketing landing page\".']) {
const p = awInput(1); p.tools[0]!.input!.args = args; expect(awCheck(p), args).toBe(true);
}
const p = awInput(1); p.opts.seed = p.opts.seed.replace('Marketing landing page', 'Checkout page');
p.tools[0]!.input!.args = p.tools[0]!.input!.args!.replace('Marketing landing page', 'Checkout page');
expect(awCheck(p)).toBe(true);
});
test('later current corrections defeat the draft selection while quoted history does not', () => {
for (const text of [
'This selection is withdrawn.', "This selection is 'withdrawn'.", 'This selection is `no longer current`.',
'This declaration is “no longer current”.',
'Historical note:\nThat selection is withdrawn.\n## Current status\nThat selection is withdrawn.', 'This selection is superseded.', 'This selection is rejected.',
'The selected target is now the branch diff.', 'I will review the branch diff instead.',
'I will review "Another plan" plan.',
]) {
const p = awInput(), m = p.transcript.assistantMessages[0]!;
p.transcript.assistantMessages.push({...m, timestamp:new Date(Date.parse(m.timestamp)+1).toISOString(), text});
expect(awCheck(p), text).toBe(false);
}
for (const text of ['> This selection is withdrawn.', 'Historical note: "This selection is withdrawn."', 'Source excerpt:\nI will review the branch diff instead.']) {
const p = awInput(), m = p.transcript.assistantMessages[0]!;
p.transcript.assistantMessages.push({...m, timestamp:new Date(Date.parse(m.timestamp)+1).toISOString(), text});
expect(awCheck(p), text).toBe(true);
}
});
test('the AW public fixture selects the existing scope helper owners without a new paid test', () => {
expect(selectTests(['test/fixtures/plan-scope-target-aw.json'], E2E_TOUCHFILES, []).selected)
.toEqual(selectTests(['test/helpers/plan-scope-selection.ts'], E2E_TOUCHFILES, []).selected);
});
// Exact public AZ intros; identities and timestamps use the existing synthetic fixture.
const spokenEngIntros = [
"I'll run the eng review skill against your draft plan.",
"I'll run the eng-manager plan review skill against this draft plan.",
];
const spokenEngFixture = (text: string) => {
const f = fixture(text); f.tools[0]!.input!.skill = 'plan-eng-review';
f.transcript.assistantMessages[0]!.timestamp = timestamp(2);
f.tools[0]!.timestamp = timestamp(4); f.tools[1]!.timestamp = timestamp(5);
return f;
};
const engScope = { ...opts, skillName: 'plan-eng-review' };
test('human-readable role names bind only the successfully requested skill', () => {
for (const text of [...spokenEngIntros, "I'll run the plan eng review skill against this draft plan.", "I'll run the eng review skill against this draft plan.", "I'll run the gstack:plan-eng-review skill against this draft plan."]) {
expect(verdict(spokenEngFixture(text), engScope), text).toBe(true);
}
expect(verdict(fixture("I'll run the design review skill against this draft plan."))).toBe(true);
});
test('spoken skill names retain scope ownership, currentness and target boundaries', () => {
for (const text of spokenEngIntros) {
for (const invalid of [text.replace(/(?:eng review|eng-manager plan review)/, 'design review'), text.replace(/(?:eng review|eng-manager plan review)/, 'eng review and design review'), text.replace(/(?:eng review|eng-manager plan review)/, 'Claude reviewer'), `"${text}"`, `Source:\n${text}`, `If approved, ${text}`])
expect(verdict(spokenEngFixture(invalid), engScope), invalid).toBe(false);
for (const mutate of [
(f: ReturnType<typeof fixture>) => { f.tools[0]!.input!.skill = 'plan-design-review'; },
(f: ReturnType<typeof fixture>) => { f.tools[1]!.isError = true; },
(f: ReturnType<typeof fixture>) => { f.transcript.assistantMessages[0]!.sessionId = 'foreign'; },
(f: ReturnType<typeof fixture>) => { f.transcript.assistantMessages[0]!.timestamp = timestamp(-1); },
(f: ReturnType<typeof fixture>) => { f.transcript.assistantMessages[0]!.timestamp = timestamp(0); },
(f: ReturnType<typeof fixture>) => { f.tools.push({kind:'use',name:'Read',sessionId:'owned',toolUseId:'work',timestamp:timestamp(1)}); },
(f: ReturnType<typeof fixture>) => { f.transcript.assistantMessages.push({sessionId:'owned',timestamp:timestamp(4),text:'This selection is "withdrawn".'}); },
(f: ReturnType<typeof fixture>) => { f.transcript.assistantMessages.push({sessionId:'owned',timestamp:timestamp(4),text:'I will review your checkout plan.'}); },
]) { const f=spokenEngFixture(text); mutate(f); expect(verdict(f,engScope)).toBe(false); }
expect(verdict(spokenEngFixture(text),{...engScope,seed:opts.seed+'\n# Another plan'})).toBe(false);
}
});