Files
gstack/test/helpers/skill-fixture.ts
T
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

277 lines
11 KiB
TypeScript

/**
* Skill fixture extraction — enforces the CLAUDE.md rule "E2E test fixtures:
* extract, don't copy".
*
* Full SKILL.md files are 1000-1900 lines. When `claude -p` (or `codex exec`)
* reads a file that large, context bloat causes timeouts, flaky turn limits,
* and tests that take 5-10x longer than necessary. Every E2E fixture that
* needs skill content should extract ONLY the sections the test actually
* exercises, through one of the three helpers here:
*
* - extractSkillSections(skillDir, sections)
* frontmatter + the named `## <section>` blocks, concatenated in the
* order given. For tests that exercise specific workflow steps.
* - extractSkillBody(skillDir)
* frontmatter + intro + everything AFTER the shared generated preamble
* ("## Preamble (run first)" or "## Preamble (after scope gate)"
* .. end of "## Plan Status Footer").
* For tests that exercise the skill's ENTIRE specific flow but never
* touch the ~780-line shared preamble.
* - extractSkillHead(skillDir, bodyLineCount)
* frontmatter + the first N body lines. For ROUTING / discovery tests,
* where the agent only reads the frontmatter (name + description) to
* decide which skill to invoke.
*
* Failure polarity: every extraction failure (missing file, missing
* frontmatter, renamed section) THROWS with the offending name — a fixture is
* never silently written empty. test/skill-fixture.test.ts pins the exported
* section lists against the real generated SKILL.md files, so a section
* rename fails the FREE suite instead of a paid E2E run.
*/
import * as fs from 'fs';
import * as path from 'path';
// ─── Section lists shared by E2E fixtures and the free pin test ────────────
// Keep these verbatim against the H2 headings in the generated SKILL.md files.
// If gen-skill-docs renames a heading, test/skill-fixture.test.ts fails free.
/** /review E2E (sql-injection, enum-completeness, design-lite): the core
* review workflow without the shared preamble, Review Army, or Fix-First. */
export const REVIEW_E2E_SECTIONS = [
'When to invoke this skill',
'Step 0: Detect platform and base branch',
'Step 1: Check branch',
'Step 2: Read the checklist',
'Step 2.5: Check for Greptile review comments',
'Step 3: Get the diff',
'Step 4: Critical pass (core review)',
'Confidence Calibration',
'Important Rules',
];
/** Review Army E2E: core workflow + Scope Drift / Plan Completion Audit
* (delivery-audit test) + Step 4.5 specialist dispatch (quality score,
* JSON findings schema, MULTI-SPECIALIST consensus, Red Team). */
export const REVIEW_ARMY_E2E_SECTIONS = [
'When to invoke this skill',
'Step 0: Detect platform and base branch',
'Step 1: Check branch',
'Step 1.5: Scope Drift Detection',
'Step 2: Read the checklist',
'Step 2.5: Check for Greptile review comments',
'Step 3: Get the diff',
'Step 4: Critical pass (core review)',
'Confidence Calibration',
'Step 4.5: Review Army — Specialist Dispatch',
'Important Rules',
];
/** /retro E2E (retro, retro-base-branch): the repo-scoped retro flow
* (Steps 0-14 live under Instructions/Prior Learnings/Capture Learnings)
* + the narrative report template. Global mode and Compare mode are not
* exercised by the E2E tests and are dropped. */
export const RETRO_E2E_SECTIONS = [
'When to invoke this skill',
'Step 0: Detect platform and base branch',
'User-invocable',
'Arguments',
'Instructions',
'Prior Learnings',
'Capture Learnings',
'Engineering Retro: [date range]',
'Tone',
'Important Rules',
];
/** codex-review-findings E2E against the Codex host variant
* (.agents/skills/gstack-review/SKILL.md). Same core workflow as
* REVIEW_E2E_SECTIONS, minus "When to invoke this skill" (the Codex host
* adapter does not emit that section). */
export const CODEX_REVIEW_E2E_SECTIONS = [
'Step 0: Detect platform and base branch',
'Step 1: Check branch',
'Step 2: Read the checklist',
'Step 3: Get the diff',
'Step 4: Critical pass (core review)',
'Confidence Calibration',
'Important Rules',
];
// ─── Parsing internals ──────────────────────────────────────────────────────
/** First/last H2 headings of the shared preamble block that gen-skill-docs
* emits into every tier >= 2 skill. extractSkillBody drops this range. */
const SHARED_PREAMBLE_FIRST = ['Preamble (run first)', 'Preamble (after scope gate)'];
const SHARED_PREAMBLE_LAST = 'Plan Status Footer';
interface H2Section {
heading: string;
/** index of the heading line within bodyLines */
start: number;
/** one past the last line of the section (start of next H2, or EOF) */
end: number;
}
/** Accept either a skill directory or a direct path to a .md file. */
function resolveSkillMd(skillDirOrFile: string): string {
const file = skillDirOrFile.endsWith('.md')
? skillDirOrFile
: path.join(skillDirOrFile, 'SKILL.md');
if (!fs.existsSync(file)) {
throw new Error(`skill-fixture: no SKILL.md at ${file}`);
}
return file;
}
function splitFrontmatter(raw: string, file: string): { frontmatter: string; bodyLines: string[] } {
const lines = raw.split('\n');
if ((lines[0] ?? '').trim() !== '---') {
throw new Error(`skill-fixture: ${file} does not start with YAML frontmatter ('---')`);
}
let close = -1;
for (let i = 1; i < lines.length; i++) {
if (lines[i].trim() === '---') { close = i; break; }
}
if (close === -1) {
throw new Error(`skill-fixture: ${file} frontmatter never closes ('---' missing)`);
}
return {
frontmatter: lines.slice(0, close + 1).join('\n'),
bodyLines: lines.slice(close + 1),
};
}
/**
* Scan body lines for H2 sections, fence-aware: `## `-prefixed lines inside
* ``` / ~~~ code fences are template content (e.g. the PLAN COMPLETION AUDIT
* output format, the /context-save checkpoint template), NOT section
* boundaries. Fences close only on a matching char of >= opening length,
* per CommonMark, so 4-backtick fences embedding 3-backtick blocks work.
*/
function scanH2Sections(bodyLines: string[]): H2Section[] {
const sections: H2Section[] = [];
let fence: { ch: string; len: number } | null = null;
for (let i = 0; i < bodyLines.length; i++) {
const line = bodyLines[i];
const m = line.match(/^ {0,3}(`{3,}|~{3,})(.*)$/);
if (m) {
const ch = m[1][0];
const len = m[1].length;
if (!fence) {
fence = { ch, len };
} else if (fence.ch === ch && len >= fence.len && m[2].trim() === '') {
fence = null;
}
continue;
}
if (!fence && line.startsWith('## ')) {
sections.push({ heading: line.slice(3).trim(), start: i, end: bodyLines.length });
}
}
for (let s = 0; s < sections.length - 1; s++) {
sections[s].end = sections[s + 1].start;
}
return sections;
}
function loadSkill(skillDirOrFile: string): {
file: string;
frontmatter: string;
bodyLines: string[];
sections: H2Section[];
} {
const file = resolveSkillMd(skillDirOrFile);
const raw = fs.readFileSync(file, 'utf-8');
const { frontmatter, bodyLines } = splitFrontmatter(raw, file);
return { file, frontmatter, bodyLines, sections: scanH2Sections(bodyLines) };
}
function findSection(sections: H2Section[], name: string, file: string): H2Section {
const hit = sections.find((s) => s.heading === name)
?? sections.find((s) => s.heading.startsWith(name));
if (!hit) {
const available = sections.map((s) => ` ## ${s.heading}`).join('\n');
throw new Error(
`skill-fixture: section "## ${name}" not found in ${file}.\n`
+ 'The section may have been renamed — update the fixture section list '
+ '(see test/helpers/skill-fixture.ts).\n'
+ `Available H2 sections:\n${available}`,
);
}
return hit;
}
// ─── Public API ─────────────────────────────────────────────────────────────
/**
* Read the real SKILL.md under `skillDir` (or a direct .md path), slice each
* requested `## <section>` block, and return frontmatter + the sections
* concatenated in the order given. Throws loudly on a missing section.
*/
export function extractSkillSections(skillDir: string, sections: string[]): string {
const { file, frontmatter, bodyLines, sections: all } = loadSkill(skillDir);
const parts: string[] = [frontmatter, ''];
for (const name of sections) {
const hit = findSection(all, name, file);
parts.push(bodyLines.slice(hit.start, hit.end).join('\n').trimEnd(), '');
}
return parts.join('\n');
}
/**
* Frontmatter + intro/scope gate (everything before either exact preamble heading) + the
* full skill-specific body (everything after the "## Plan Status Footer"
* section). Use when a test exercises the whole skill flow: this drops the
* ~780-line shared generated preamble and nothing else.
*/
export function extractSkillBody(skillDir: string): string {
const { file, frontmatter, bodyLines, sections: all } = loadSkill(skillDir);
const boundary = (names: string[]): H2Section => {
const matches = all.filter(section => names.includes(section.heading));
const label = names.map(name => `"## ${name}"`).join(' or ');
if (!matches.length) throw new Error(`skill-fixture: section ${label} not found in ${file}.`);
if (matches.length !== 1) throw new Error(`skill-fixture: ambiguous section ${label} in ${file}.`);
return matches[0];
};
const first = boundary(SHARED_PREAMBLE_FIRST);
const last = boundary([SHARED_PREAMBLE_LAST]);
if (first.start >= last.start) {
throw new Error(`skill-fixture: "## ${SHARED_PREAMBLE_LAST}" precedes the preamble in ${file}.`);
}
const intro = bodyLines.slice(0, first.start).join('\n').trimEnd();
const tail = bodyLines.slice(last.end).join('\n').trimEnd();
if (!tail) {
throw new Error(
`skill-fixture: ${file} has no content after "## ${SHARED_PREAMBLE_LAST}" — `
+ 'refusing to write a preamble-only fixture.',
);
}
return [frontmatter, '', intro, '', tail, ''].join('\n');
}
/**
* Frontmatter + the first `bodyLineCount` body lines. For routing/discovery
* fixtures: skill selection reads the frontmatter name + description, so the
* body is intentionally truncated.
*/
export function extractSkillHead(skillDir: string, bodyLineCount = 30): string {
const { frontmatter, bodyLines } = loadSkill(skillDir);
const head = bodyLines.slice(0, bodyLineCount).join('\n').trimEnd();
return `${frontmatter}\n${head}\n\n<!-- body truncated by test/helpers/skill-fixture.ts — routing fixture needs frontmatter only -->\n`;
}
/**
* Slice a rendered skill between two literal markers. Both must exist: a
* missing END marker would silently hand the agent the rest of the file, which
* is exactly the "copied the whole SKILL.md" failure the E2E fixtures avoid.
*/
export function sliceBetween(text: string, start: string, end: string): string {
const i = text.indexOf(start);
if (i < 0) throw new Error(`skill fixture: start marker not found: ${start}`);
const j = text.indexOf(end, i + start.length);
if (j < 0) throw new Error(`skill fixture: end marker not found after start: ${end}`);
return text.slice(i, j);
}