Files
gstack/test/helpers/skill-fixture.ts
Garry Tanandcapy-ai[bot] 3e4240a76f v1.91.276.0 feat(preamble): tier 2+ skills load the shared preamble once per session (GSTA-96) (#3434)
* fix(preamble): completeness means complete coverage with minimal code (GSTA-96)

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

* feat(preamble): tier 2+ skills load the shared preamble once per session (GSTA-96)

Every tier 2+ SKILL.md inlined the same ~23 KB preamble. It now renders once
per host into sections/preamble.md beside each tier 2+ SKILL.md; the SKILL.md
keeps a pointer that asks for the Read only when the file's id is not already
in context. Only sections byte-identical to the shared render move, so every
skill keeps exactly its pre-hoist paragraphs (verified across all 41 skills).

Parity caps for ten skills raised to their measured unions (owner-approved,
Garry 2026-10-25: "do it"); 63 size pins lowered and 26 deleted.

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

* fix(paid-select): a generated sections/preamble.md takes its skill template's identity in the PR planner (GSTA-96)

screen-summary failed on #3434 with 'PR profile requires full validation' for nine
skills whose only paid coverage is periodic: their new sections/preamble.md had no
dependency identity, while the SKILL.md beside it inherits its template's.

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

* test(section-manifest): the shared sections/preamble.md renders from the hoist resolver, not a section template (GSTA-96)

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

* fix: pre-landing review fixes (CHANGELOG says 3 characters shorter; model-overlays guards the coverage half)

The completeness section shrank by 3 characters (5 bytes), matching the 89 pins lowered by 3. The default-copy test pinned only the minimal-code half; an expectMentions check now fails if the full-coverage or never-excuses-a-gap clause is dropped.

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

* fix: pre-landing review fixes (model-overlays binds smaller diff to equal coverage)

The default-copy check now also fails if 'on equal coverage' is dropped from the smaller-diff rule (which would tell models to prefer the smaller diff unconditionally) or if the no-impossible-state-checks clause is removed.

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

* docs: CHANGELOG lists the model-overlays coverage checks

The [Unreleased] Tests bullet now says the default-copy test checks both halves of the rule (full coverage of the requirement; smaller diff only at equal coverage; no impossible-state checks; never excuses a gap), matching 88e3cc0 and 44eacaf.

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

* fix: plan-ceo-review and ETHOS say completeness means coverage, not more code

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

* fix: pre-landing review fixes (CEO bullet bounds code by accepted scope; tests bind each completeness rule)

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

* test: cover the shared-preamble hoist (ship Step 7)

Adds test/preamble-hoist.test.ts (tier 1 unchanged; tier 2+ SKILL.md plus
sections/preamble.md reproduces the pre-hoist preamble; pointer position and id)
and two gen-skill-docs-checks cases (one shared preamble per host, beside every
pointer and named by its id; preamble artifact kind).

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

* fix: pre-landing review fixes (ship Step 9.4)

- setup: follow a symlinked sections/ dir in the carved-pointer status check
- touchfiles: select preamble-hoist.ts alongside every preamble.ts entry
- section-manifest: exempt sections/preamble.md only for skills whose SKILL.md
  carries the shared-preamble pointer
- skill-size-budget: growth ceiling measures SKILL.md plus its shared preamble
- host-conformance: tolerate a missing sections/ dir, as setup does
- skill-validation: read bin/gstack-skill-start directly
- skill-fixture: error messages and docblocks name the actual boundary
  (harness-version non-behavioral note updated)

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

* fix: describe the size-budget growth check's startup measure (ship Step 9.4, pass 2)

The growth ceiling now measures SKILL.md plus the shared preamble, the same
measure as the shrink floor; the docblock said SKILL.md only.

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

* docs: CHANGELOG says simplification.md quotes the old rule and CLAUDE.md restates the new one

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

* docs: CHANGELOG lists the hoist tests and the growth-ceiling measure (ship Step 9.4)

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

* test: cover the symlinked sections/ status check and the ETHOS house-rule quote (ship Step 7)

host-conformance: --status still finds a broken bare sections/ pointer when a
carved Claude skill's installed sections/ is a directory symlink (fails at the
pre-repair 0e5d11fd9). gen-skill-docs: the house rule review/specialists/
simplification.md quotes from ETHOS.md still appears in ETHOS.md.

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

* docs: describe the shared preamble file (ship Step 14.5 docs audit)

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

* fix: the shared-preamble skip needs the skill's own Read; digest and first-run intro say complete coverage, minimal code (GSTA-96)

The pointer skipped the shared file when any text carrying its id was in context, so a
page or file with that heading could stand in for the anti-spoofing rules (security,
red team and adversarial review, ship run 2). It now requires the skill's own earlier
Read. The digest's Boil the Ocean bullet and the first-run intro still said 'AI makes
completeness cheap, so do the complete thing' (docs audit blocker); both now carry
Garry's 'complete coverage, minimal code' (2026-10-25: '1/ yes fix this').

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

* test: pin the shared-preamble provenance skip and the new Boil the Ocean wording (ship Step 7)

preamble-hoist: on every host, tier and render option the pointer allows the
skip only when the skill's own Read is in context. agents-digest and
gstack-skill-start: the digest bullet and the lake intro say complete
coverage, minimal code, never the retired phrasing. Each fails at 9af36d010.

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

* fix: describe the provenance skip where the docs still described the id-only one (ship Step 9.4)

The preamble-hoist.ts docblock and ARCHITECTURE.md still said the shared
preamble is re-read only when its id is absent; since 2acf1a44a the pointer
requires the skill's own earlier Read of the file.

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

* docs: CHANGELOG lists the provenance-pointer and Boil the Ocean wording tests (ship Step 13)

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

* revert(digest): keep the agents digest at main's bytes; an unstamped head cannot change a release output (GSTA-96)

CI 'Check VERSION is not stale vs queue' classified #3434 as stamped because it touched
agents-digest/gstack-AGENTS.md (a release_outputs path), while regenerating only the
generator fails the digest freshness test. The first-run intro rewording stays.

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

* test: voice judge reads the hoisted preamble; register ETHOS.md on its reader cases

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

* test: refresh the claude ship golden the main merge took from main (ship Step 5 preflight)

The 1a4dcaf07 merge resolved test/fixtures/golden/claude-ship-SKILL.md to
main's pre-hoist bytes. The golden is a copy of ship/SKILL.md; regenerated
with bun scripts/gen-ship-goldens.ts (pregate regen: REGEN_STALE).

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

* test: pr-dependencies' unplaceable-file example uses SECURITY.md now that ETHOS.md is mapped

6183ca8ae registered ETHOS.md on its reader cases in touchfiles-data.ts, so a
PR touching only ETHOS.md plans in pr mode and no longer restores the full gate.
The fail-closed test and the real-unknown label check now use SECURITY.md, which
is tracked and unmapped; the assertions are unchanged. CHANGELOG names the
third test file. (CI free shard 7 at 7c21720ac; remote pregate shard 6.)

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

* test: host path-leak checks read the moved shared preamble too; name SHARED_PREAMBLE_FILE (ship review pass 2)

The external-host path-leak assertions in gen-skill-docs.test.ts (Codex,
Factory) and host-config.test.ts (Copilot, Antigravity) read SKILL.md
alone, so a Claude path that moved into sections/preamble.md with the
hoist went unchecked. They now read the skill's startup text through
readSkillStartup. workflow-judge-input and host-conformance use the
SHARED_PREAMBLE_FILE constant instead of a bare 'preamble.md' literal,
and preamble.ts's header describes the hoisted composition.

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

* docs: CHANGELOG token savings name the per-skill skip and the autoplan follow-up (ship review pass 2)

The pointer's skip is bound to the skill's own copy of sections/preamble.md,
so "every later one saves about 5,800" holds per skill, not per session, and
/autoplan's skip list and the inline /office-hours loader do not yet skip the
pointer section. The entry now says so instead of claiming the full /autoplan
saving. Adding the skip entry grows size-pinned skills, so it is a follow-up.

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

* test: corpus budget measures startup bytes; carve-safety counts shared preamble as uncarved (ship review pass 2)

skill-size-budget's growth ceiling and shrink floor already measured
SKILL.md plus sections/preamble.md, but the total-corpus check still summed
hoisted SKILL.md bytes against the pre-hoist baseline, hiding about 0.9 MB
of headroom. It now sums the same startup bytes (3,114,885 -> 2,590,484,
x0.832); the unreachable SKILL.md-missing fallback is gone.

auq-format-always-loaded's carve-safety guard treated any sections/ dir as
carved, so every skill with only the shared preamble ran it and its sanity
check passed on preamble.md. It now uses setup --status's rule: a section
other than the shared preamble. Those skills keep the per-skill checks.

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

* test: remaining SKILL.md-only negatives read the shared preamble too (ship review pass 3)

The parameterized external-host path-leak smoke test, the two Codex
.claude path checks and both vestigial-handshake negatives read SKILL.md
alone, so text that moved into sections/preamble.md went unchecked. They
now read readSkillStartup. preamble.ts's header no longer says tier 1
renders through generatePreamble().

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

* test: ratchet skeleton caps and eager context ceilings down after the hoist (ship review pass 3)

The hoist moved about 22 KB out of every tier 2+ SKILL.md, which left
each hoisted maxSkeletonBytes cap and each eagerPerInvocation ceiling
roughly 22 KB / 5-6K tokens slack. The 20 hoisted skeleton caps now sit at
the post-hoist skeleton plus their pre-hoist headroom, and 42 context-budget
ceilings take the recaptured (lower) values. Nothing was raised: the four
ceilings the recapture would have raised keep their old values.

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

* fix: preamble-hoist's section splitter closes a fence only on a bare delimiter (ship Step 11)

Inside an open fence, a line such as "```bash" is content in CommonMark,
but splitSections treated it as the closing fence, so a later "## " line in
the same block could split a section mid-code-block and hoist half of it.
A closing delimiter now needs nothing but whitespace after it. Every host's
render is unchanged (gen-skill-docs --dry-run FRESH on all twelve hosts).

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

* test: skill-startup.ts is a global, pinned harness file like skill-fixture.ts (ship review pass 3)

skill-fixture.ts is a global touchfile pinned in scripts/harness-version.json
because it reshapes the skill content most E2E suites read, and it now
builds that content through test/helpers/skill-startup.ts. That helper was
in neither list, so a later edit to it would change fixture inputs without
the harness-version guard and select only 27 keys. It is now global and
pinned, recorded non-behavioral (its fixtures are byte-identical to the
pre-hoist output). ARCHITECTURE.md and the CHANGELOG stop calling the
pointer id a content id: it hashes the shared text before host rewrites.

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

* docs: CHANGELOG matches the merged skip lists and the baseline diff (ship review, run 4)

The headline still called the autoplan and inline /office-hours skip
entries a follow-up, but the main merge added them; it now says the loaded
skills skip their shared Read. The #3451 sentence is dropped, because that
fix shipped in v1.91.237.0 and is recorded there. The typecheck baseline
line says the TS2769 entry was re-keyed for the 'preamble' artifact kind
with its count unchanged, not fixed and lowered.

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

* test: pin the pointer entry in the loader skip lists; drop a carve-safety tautology (ship review, run 4)

A new INVOKE_SKILL test checks that plan-ceo-review's inline /office-hours
skip list and autoplan's section skip list both name the shared-preamble
pointer heading, and that office-hours and the four plan reviews carry it.
The carve-safety "sanity" assertion repeated the predicate discoverSkills()
now uses to set sectionsDir, so it could never fail; it is removed.

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

* fix: gstack-doctor finds the Codex model patch in the hoisted shared preamble (ship Step 11, run 4)

The doctor's patch row grepped only the Codex review SKILL.md for the
"Model-Specific Behavioral Patch (" heading. The hoist moves that section
into sections/preamble.md, so the required row (for ship, review, the plan
reviews, office-hours, investigate and more) would fail on every correct
post-hoist Codex install and block install.sh's "gstack: ok". It now checks
the SKILL.md and then its shared preamble and names the file it found. A
new doctor test covers a hoisted render.

preamble-hoist's variantSubsections also returns null when no subsection
differs, instead of emitting a replacing heading with no subsections.
Every host's render is unchanged.

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

* test(docsync): fixtureDocs installs the generated sections/preamble.md (hunk taken from #3472)

A generated skill that loads the shared preamble names sections/preamble.md
as a required asset before skill start, and a spawned document-release child
blocks on its absence, so docsync-spawned stayed red on every #3434 screen.
fixtureDocs now copies that file when the generated skill has it.

This single hunk is taken unchanged from gstack#3472 (head 2e3f7ba1,
GSTA-107), which trains ahead of #3434, so the train merge sees identical
lines. Nothing else from #3472 is included.

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

* docs: CHANGELOG notes the docsync fixture hunk taken from #3472

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

* docs: CHANGELOG names the post-merge context-budget ratchet (captain hoisted)

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

* test(auq): planted skill fixtures resolve the shared preamble like an install (GSTA-96)

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

* test(plan-format): mode menu delivers its question without output-harvesting wording (GSTA-96)

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

* docs(changelog): record the v1.91.270.0 merge values (GSTA-96)

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

* test(auq): parallel-capture contract expects the planted skill with its sections path mapped (GSTA-96)

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

* docs(changelog): record the v1.91.273.0 merge re-measurements (GSTA-96)

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

* docs(changelog): restore the released entries the previous commit truncated (GSTA-96)

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

* docs(changelog): end two sentences the prose gate flags (GSTA-96)

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-10-27 13:28:18 +00:00

319 lines
14 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 generated preamble (tier 1:
* "## Preamble (run first)" or "## Preamble (after scope gate)" .. end of
* "## Plan Status Footer"; tier 2+: the shared-preamble pointer .. this
* skill's own preamble sections through Telemetry).
* For tests that exercise the skill's ENTIRE specific flow but never
* touch the generated 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';
import { SHARED_POINTER_HEADING, readSharedSections, readSkillEffective } from './skill-startup';
// ─── 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 = [
'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 = [
'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 = [
'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. */
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 an inline (tier 1) preamble block. extractSkillBody
* drops this range; a hoisted tier 2+ preamble is bounded by its pointer instead. */
const SHARED_PREAMBLE_FIRST = ['Preamble (run first)', 'Preamble (after scope gate)'];
const SHARED_PREAMBLE_LAST = 'Plan Status Footer';
/** Preamble sections a hoisted SKILL.md keeps inline because they name the skill. */
const INLINE_PREAMBLE = [...SHARED_PREAMBLE_FIRST, 'Question Tuning', 'Repo Ownership', 'Search Before Building', 'Telemetry (run last)'];
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.
* Standalone generated STOP-Read blocks between horizontal rules replace
* entire carved steps and end the preceding H2. Nested pointers stay inside it.
*/
function scanH2Sections(bodyLines: string[], stopAtH1 = false): 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) {
const heading = line.startsWith('## ');
const title = stopAtH1 && /^ {0,3}#(?:[ \t]|$)/.test(line);
let carvedStep = /^> \*\*STOP\.\*\* Before .+, Read `[^`]+\/sections\/[^`]+\.md` and execute it$/.test(line)
&& bodyLines[i + 1] === '> in full. Do not work from memory — that section is the source of truth for this step.';
if (carvedStep) {
let preceding = i - 1;
while (preceding >= 0 && !bodyLines[preceding].trim()) preceding--;
let following = i + 2;
while (following < bodyLines.length && !bodyLines[following].trim()) following++;
carvedStep = bodyLines[preceding] === '---' && bodyLines[following] === '---';
}
if (heading || title || carvedStep) {
const previous = sections.at(-1);
if (previous) previous.end = Math.min(previous.end, i);
if (heading) sections.push({ heading: line.slice(3).trim(), start: i, end: bodyLines.length });
}
}
}
return sections;
}
function loadSkill(skillDirOrFile: string, stopAtH1 = false, effective = false): {
file: string;
frontmatter: string;
bodyLines: string[];
sections: H2Section[];
} {
const file = resolveSkillMd(skillDirOrFile);
const raw = effective ? readSkillEffective(file) : fs.readFileSync(file, 'utf-8');
const { frontmatter, bodyLines } = splitFrontmatter(raw, file);
return { file, frontmatter, bodyLines, sections: scanH2Sections(bodyLines, stopAtH1) };
}
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, false, true);
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; in a hoisted SKILL.md, the shared-preamble pointer through the
* skill's own preamble sections ending at Telemetry). Use when a test exercises the whole skill flow: this drops the
* generated preamble and nothing else.
*/
export function extractSkillBody(skillDir: string): string {
const { file, frontmatter, bodyLines, sections: all } = loadSkill(skillDir, true);
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 pointer = all.findIndex(section => `## ${section.heading}` === SHARED_POINTER_HEADING);
let first: H2Section, last: H2Section;
if (pointer >= 0) {
// Hoisted preamble: the pointer, then this skill's own preamble sections up to Telemetry.
const shared = new Set(readSharedSections(file).map(section => section.split('\n', 1)[0]!.slice(3)));
let end = pointer;
while (end + 1 < all.length && (shared.has(all[end + 1].heading)
|| INLINE_PREAMBLE.some(name => all[end + 1].heading.startsWith(name)))) end++;
if (!all.slice(pointer, end + 1).some(section => section.heading === 'Telemetry (run last)')) {
throw new Error(`skill-fixture: no "## Telemetry (run last)" closes the preamble in ${file}.`);
}
[first, last] = [all[pointer], all[end]];
} else {
first = boundary(SHARED_PREAMBLE_FIRST);
last = boundary([SHARED_PREAMBLE_LAST]);
}
if (first.start >= last.start) {
throw new Error(`skill-fixture: "## ${last.heading}" 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 "## ${last.heading}" — `
+ '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);
}
export function extractDesignResearchContract(skill: string): string {
const setup = sliceBetween(skill, '## BROWSER SETUP', '### Rules for driving a real browser');
const probe = setup.match(/```bash\n[\s\S]*?\n```/)?.[0];
if (!probe) throw new Error('skill fixture: design research readiness probe missing');
const routing = sliceBetween(skill, '## Web research runs in Aside', '## Phase 2: Research');
const search = sliceBetween(skill, '**Step 1: Identify', '**Step 2: Visual research');
const prelude = search.match(/^_EG=.*_aside_exec\(\).*$/m)?.[0];
if (!prelude) throw new Error('skill fixture: design research egress prelude missing');
return ['Run this readiness probe once before research:', probe, routing,
'For each Aside research call, include this prelude before invoking `_aside_exec` with the requested query:',
'```bash', prelude, '```'].join('\n\n');
}