Files
gstack/test/gen-skill-docs-checks.test.ts
T
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

400 lines
22 KiB
TypeScript

import { afterAll, beforeAll, describe, expect, spyOn, test } from 'bun:test';
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
import { createHash } from 'crypto';
import { spawnSync } from 'child_process';
import { runGeneration, type GeneratedArtifact, type GenerationResult } from '../scripts/gen-skill-docs';
import { includesSkill } from '../scripts/discover-skills';
import { getHostConfig, ALL_HOST_NAMES } from '../hosts/index';
import { checkGeneratedFreshness, validateGeneratedArtifact } from '../scripts/skill-check';
const ROOT = path.resolve(import.meta.dir, '..');
const base = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-check-contract-'));
const render = path.join(base, 'render');
let generated: GenerationResult;
/** Hashes AND mtimes catch rewriting identical files; directory entries catch
* mkdir-only side effects. Do not follow symlinks back into the checkout. */
function inventory(root: string): unknown[] {
if (!fs.existsSync(root)) return [];
return fs.readdirSync(root).sort().flatMap(name => {
const file = path.join(root, name);
const stat = fs.lstatSync(file);
return [[file, stat.mtimeMs, stat.isDirectory() ? 'directory'
: stat.isSymbolicLink() ? fs.readlinkSync(file)
: createHash('sha256').update(fs.readFileSync(file)).digest('hex')],
...(stat.isDirectory() ? inventory(file) : [])];
});
}
beforeAll(async () => {
generated = await runGeneration({ host: 'all', outputRoot: render, contentLinkRoot: null });
expect(generated.exitCode, JSON.stringify(generated.diagnostics)).toBe(0);
}, 120_000);
afterAll(() => fs.rmSync(base, { recursive: true, force: true }));
describe('generator artifact and dry-run contract', () => {
test('all host artifacts validate, with canonical links and host exclusions', () => {
expect([...new Set(generated.artifacts.filter(a => a.host).map(a => a.host))].sort()).toEqual([...ALL_HOST_NAMES].sort());
expect([...new Set(generated.artifacts.map(a => a.kind))].sort()).toEqual(['asset', 'digest', 'doctor-components', 'index', 'metadata', 'openclaw', 'preamble', 'section', 'skill']);
expect(generated.artifacts.some(a => a.relativePath === 'claude-code/SKILL.md')).toBe(false);
expect(generated.artifacts.some(a => a.relativePath === '.agents/skills/gstack-claude-code/SKILL.md')).toBe(true);
expect(generated.artifacts.some(a => a.relativePath === '.agents/skills/gstack-codex/SKILL.md')).toBe(false);
expect(fs.readFileSync(path.join(render, 'ship/SKILL.md'), 'utf-8')).toContain('~/.claude/skills/gstack/ship/sections/');
expect(generated.artifacts.flatMap(a => validateGeneratedArtifact(render, a))).toEqual([]);
expect(generated.artifacts.filter(a => a.kind === 'asset').sort((a, b) => a.relativePath.localeCompare(b.relativePath))).toEqual([
{ relativePath: 'review/design-checklist.md', kind: 'asset', host: 'claude' },
{ relativePath: 'lib/dom-dump.js', kind: 'asset', host: 'claude' },
{ relativePath: 'autoplan/DRIVER.md', kind: 'asset', host: 'claude' },
...ALL_HOST_NAMES.filter(host => includesSkill(getHostConfig(host), 'qa')).map(host => ({
relativePath: host === 'claude' ? 'qa/templates/functional-report-template.md'
: `${getHostConfig(host).hostSubdir}/skills/gstack-qa/templates/functional-report-template.md`,
kind: 'asset' as const, host,
})),
].sort((a, b) => a.relativePath.localeCompare(b.relativePath)));
});
// Generated by /ship Step 7 coverage audit (GSTA-96).
// Value: protects=on each host every tier 2+ SKILL.md pointer has a sections/preamble.md beside it, all byte-identical under one id that the pointer names;
// fails_when=a post-hash host rewrite or skill-dependent render gives two skills different shared files under one id, or a pointer or file is orphaned;
// why_new=the all-host validation above checks commands only; goldens pin ship's SKILL.md, never the shared files across skills;
// seam=none; no_claim=that installs copy the file (host-conformance checks installed pointers resolve)
test('each host renders one shared preamble, beside every pointer and named by its id', () => {
const pointerId = /^## Shared preamble \(load first\)\n\nThis skill follows gstack shared preamble `([0-9a-f]{12})`/m;
const preambles = generated.artifacts.filter(a => a.kind === 'preamble');
const skills = generated.artifacts.filter(a => a.kind === 'skill' && pointerId.test(fs.readFileSync(path.join(render, a.relativePath), 'utf-8')));
expect(skills.length).toBeGreaterThan(40 * ALL_HOST_NAMES.length);
expect(preambles.map(a => `${a.host}:${path.dirname(path.dirname(a.relativePath))}`).sort())
.toEqual(skills.map(a => `${a.host}:${path.dirname(a.relativePath)}`).sort());
for (const host of ALL_HOST_NAMES) {
const bodies = new Set(preambles.filter(a => a.host === host).map(a => fs.readFileSync(path.join(render, a.relativePath), 'utf-8')));
expect(bodies.size, host).toBe(1);
const id = /^# gstack shared preamble ([0-9a-f]{12})$/m.exec([...bodies][0])?.[1];
expect(id, host).toBeDefined();
for (const skill of skills.filter(a => a.host === host)) {
expect(pointerId.exec(fs.readFileSync(path.join(render, skill.relativePath), 'utf-8'))?.[1], skill.relativePath).toBe(id);
}
}
});
test('include-minus-skip semantics share one predicate', () => {
const host = getHostConfig('claude');
expect(includesSkill(host, 'claude-code')).toBe(false);
expect(includesSkill(host, '.')).toBe(true);
const filtered = { ...host, generation: { ...host.generation, includeSkills: ['ship', 'claude-code'] } };
expect(includesSkill(filtered, 'ship')).toBe(true);
expect(includesSkill(filtered, 'claude-code')).toBe(false);
expect(includesSkill(filtered, 'review')).toBe(false);
});
test('fresh all-host dry run does not change bytes, mtimes, or directories', async () => {
const before = inventory(render);
const result = await runGeneration({ host: 'all', outputRoot: render, dryRun: true });
expect(result.exitCode).toBe(0);
expect(result.artifacts).toEqual(generated.artifacts);
expect(inventory(render)).toEqual(before);
});
test('missing nested output root reports every artifact family without creating anything', async () => {
const parent = fs.mkdtempSync(path.join(base, 'missing-'));
const outputRoot = path.join(parent, 'not-created', 'nested');
const before = inventory(parent);
const result = await runGeneration({ host: 'all', outputRoot, dryRun: true });
expect(result.exitCode).toBe(1);
expect(result.diagnostics.filter(d => d.kind === 'stale')).toHaveLength(generated.artifacts.length);
expect(result.diagnostics.filter(d => d.kind === 'error')).toEqual([]);
expect(inventory(parent)).toEqual(before);
expect(fs.existsSync(outputRoot)).toBe(false);
});
for (const relativePath of [
'ship/SKILL.md', 'ship/sections/adversarial.md',
'.agents/skills/gstack-ship/agents/openai.yaml',
'openclaw/gstack-lite-CLAUDE.md', 'openclaw/gstack-full-CLAUDE.md', 'openclaw/gstack-plan-CLAUDE.md',
'gstack/llms.txt', 'agents-digest/gstack-AGENTS.md',
'review/design-checklist.md', 'lib/dom-dump.js',
]) {
test(`changed ${relativePath} is stale and never repaired by dry-run`, async () => {
const file = path.join(render, relativePath);
const original = fs.readFileSync(file);
try {
fs.writeFileSync(file, 'deliberately stale\n');
const before = inventory(render);
const result = await runGeneration({ host: 'all', outputRoot: render, dryRun: true });
expect(result.exitCode).toBe(1);
expect(result.diagnostics.filter(d => d.kind === 'stale').map(d => d.relativePath)).toEqual([relativePath]);
expect(inventory(render)).toEqual(before);
} finally {
fs.writeFileSync(file, original);
}
});
}
test('missing metadata directory is reported and remains absent', async () => {
const dir = path.join(render, '.agents/skills/gstack-ship/agents');
const file = path.join(dir, 'openai.yaml');
const original = fs.readFileSync(file);
try {
fs.rmSync(dir, { recursive: true });
const result = await runGeneration({ host: 'codex', outputRoot: render, dryRun: true });
expect(result.exitCode).toBe(1);
expect(result.diagnostics.some(d => d.kind === 'stale' && d.relativePath === '.agents/skills/gstack-ship/agents/openai.yaml')).toBe(true);
expect(fs.existsSync(dir)).toBe(false);
} finally {
fs.mkdirSync(dir);
fs.writeFileSync(file, original);
}
});
test('single-host filesystem errors reach the CLI exit code with actionable diagnostics', () => {
const outputRoot = fs.mkdtempSync(path.join(base, 'not-dir-'));
fs.writeFileSync(path.join(outputRoot, '.agents'), 'not a directory');
const before = inventory(outputRoot);
const result = spawnSync('bun', ['run', 'scripts/gen-skill-docs.ts', '--host', 'codex', '--dry-run', '--out-dir', outputRoot], { cwd: ROOT, encoding: 'utf-8', timeout: 120_000 });
expect(result.status).toBe(1);
expect(result.stderr).toContain('ERROR (codex)');
expect(result.stderr).toContain('ENOTDIR');
expect(inventory(outputRoot)).toEqual(before);
});
test('Windows ENOENT for a file ancestor remains an error instead of stale output', async () => {
const outputRoot = fs.mkdtempSync(path.join(base, 'windows-not-dir-'));
fs.writeFileSync(path.join(outputRoot, '.agents'), 'not a directory');
const before = inventory(outputRoot), original = fs.readFileSync;
const mock = spyOn(fs, 'readFileSync').mockImplementation(((file: fs.PathOrFileDescriptor, ...args: any[]) => {
if (String(file).startsWith(path.join(outputRoot, '.agents') + path.sep)) {
throw Object.assign(new Error('Windows: child cannot be found'), { code: 'ENOENT' });
}
return (original as any)(file, ...args);
}) as typeof fs.readFileSync);
let result: GenerationResult;
try { result = await runGeneration({ host: 'codex', dryRun: true, outputRoot }); }
finally { mock.mockRestore(); }
expect(result!.exitCode).toBe(1);
expect(result!.diagnostics).toContainEqual(expect.objectContaining({ kind: 'error', host: 'codex', message: expect.stringContaining('ENOTDIR') }));
expect(inventory(outputRoot)).toEqual(before);
});
test('all-host generation reports a partial failure and still renders subsequent hosts', async () => {
const outputRoot = fs.mkdtempSync(path.join(base, 'partial-host-error-'));
fs.writeFileSync(path.join(outputRoot, '.agents'), 'blocks only the Codex output tree');
const result = await runGeneration({ host: 'all', outputRoot });
expect(result.exitCode).toBe(1);
expect(result.diagnostics.filter(d => d.kind === 'error').map(d => d.host)).toEqual(['codex']);
for (const relativePath of [
'ship/SKILL.md', '.factory/skills/gstack-ship/SKILL.md', '.gbrain/skills/gstack-ship/SKILL.md',
'openclaw/gstack-plan-CLAUDE.md', 'gstack/llms.txt', 'agents-digest/gstack-AGENTS.md',
]) {
expect(result.artifacts.some(a => a.relativePath === relativePath)).toBe(true);
expect(fs.readFileSync(path.join(outputRoot, relativePath)).length).toBeGreaterThan(0);
}
expect(fs.readFileSync(path.join(outputRoot, '.agents'), 'utf-8')).toBe('blocks only the Codex output tree');
});
for (const relativePath of ['gstack/llms.txt', 'agents-digest/gstack-AGENTS.md', 'review/design-checklist.md', 'lib/dom-dump.js']) {
for (const dryRun of [true, false]) {
test(`shared artifact failure is awaited: ${relativePath}, dryRun=${dryRun}`, async () => {
const outputRoot = fs.mkdtempSync(path.join(base, 'shared-error-'));
fs.mkdirSync(path.join(outputRoot, relativePath), { recursive: true });
const result = await runGeneration({ host: 'claude', outputRoot, dryRun });
expect(result.exitCode).toBe(1);
expect(result.diagnostics.some(d => d.kind === 'error' && d.relativePath === relativePath)).toBe(true);
});
}
}
test.skipIf(process.platform === 'win32')('repo-root sidecar symlink skips skill and metadata without touching source', async () => {
const outputRoot = fs.mkdtempSync(path.join(base, 'sidecar-'));
const skills = path.join(outputRoot, '.agents/skills');
fs.mkdirSync(skills, { recursive: true });
fs.symlinkSync(ROOT, path.join(skills, 'gstack'), 'dir');
const source = path.join(ROOT, 'SKILL.md');
const before = fs.statSync(source).mtimeMs;
const result = await runGeneration({ host: 'codex', outputRoot });
expect(result.exitCode).toBe(0);
expect(result.diagnostics.some(d => d.kind === 'skipped' && d.relativePath === '.agents/skills/gstack/SKILL.md')).toBe(true);
expect(result.artifacts.some(a => a.relativePath.startsWith('.agents/skills/gstack/'))).toBe(false);
expect(fs.statSync(source).mtimeMs).toBe(before);
});
test('explicit content link root preserves literal dollar signs', async () => {
const outputRoot = path.join(base, 'link-render');
const contentLinkRoot = path.join(base, 'live$&');
expect((await runGeneration({ host: 'claude', outputRoot, contentLinkRoot })).exitCode).toBe(0);
const content = fs.readFileSync(path.join(outputRoot, 'ship/SKILL.md'), 'utf-8');
expect(content).toContain(`${contentLinkRoot}/ship/sections/`);
expect(content).not.toContain(`${outputRoot}/ship/sections/`);
});
});
describe('repository freshness without installed caches', () => {
const repo = path.join(base, 'fixture-repo');
function git(...args: string[]) {
const result = spawnSync('git', args, { cwd: repo, encoding: 'utf-8', timeout: 30_000 });
expect(result.status, result.stderr).toBe(0);
}
beforeAll(() => {
fs.mkdirSync(repo);
fs.copyFileSync(path.join(ROOT, '.gitignore'), path.join(repo, '.gitignore'));
for (const artifact of generated.artifacts.filter(a => !a.relativePath.startsWith('.'))) {
const file = path.join(repo, artifact.relativePath);
fs.mkdirSync(path.dirname(file), { recursive: true });
fs.copyFileSync(path.join(render, artifact.relativePath), file);
}
git('init', '--quiet');
git('add', '--all');
});
test('clean checkout passes without external host caches', () => {
expect(fs.existsSync(path.join(repo, '.agents'))).toBe(false);
const result = checkGeneratedFreshness(repo, render, generated.artifacts);
expect(result.diagnostics).toEqual([]);
expect(result.checked).toBe(generated.artifacts.filter(a => !a.relativePath.startsWith('.')).length);
});
test('ignored stale caches and unrelated dirty files do not affect freshness', () => {
fs.mkdirSync(path.join(repo, '.agents/skills/gstack-ship'), { recursive: true });
fs.writeFileSync(path.join(repo, '.agents/skills/gstack-ship/SKILL.md'), 'stale cache');
fs.writeFileSync(path.join(repo, 'unrelated-notes.txt'), 'unrelated work');
const before = inventory(repo);
expect(checkGeneratedFreshness(repo, render, generated.artifacts).diagnostics).toEqual([]);
expect(inventory(repo)).toEqual(before);
});
test.skipIf(process.platform === 'win32')('ignored symlink cache leaves foreign files and freshness unchanged', () => {
const foreign = fs.mkdtempSync(path.join(base, 'foreign-cache-'));
const foreignSkill = path.join(foreign, 'skills/gstack-ship/SKILL.md');
fs.mkdirSync(path.dirname(foreignSkill), { recursive: true });
fs.writeFileSync(foreignSkill, 'foreign sentinel: must never be rewritten');
const link = path.join(repo, '.factory');
fs.symlinkSync(foreign, link, 'dir');
try {
const beforeForeign = inventory(foreign);
const beforeRepo = inventory(repo);
expect(checkGeneratedFreshness(repo, render, generated.artifacts).diagnostics).toEqual([]);
expect(inventory(foreign)).toEqual(beforeForeign);
expect(inventory(repo)).toEqual(beforeRepo);
expect(fs.readlinkSync(link)).toBe(foreign);
} finally {
fs.unlinkSync(link);
}
});
test('scratch ignore evaluation preserves nested ignore rules and exceptions', () => {
const dir = path.join(repo, 'local-generated');
fs.mkdirSync(dir);
fs.writeFileSync(path.join(dir, '.gitignore'), '*.md\n!required.md\n');
const extra: GeneratedArtifact[] = [
{ relativePath: 'local-generated/ignored.md', kind: 'index' },
{ relativePath: 'local-generated/required.md', kind: 'index' },
];
const result = checkGeneratedFreshness(repo, render, [...generated.artifacts, ...extra]);
expect(result.diagnostics.map(d => [d.kind, d.relativePath])).toEqual([
['untracked', 'local-generated/required.md'],
]);
});
test('scratch ignore evaluation preserves configured excludes with a relative path', () => {
const excludes = path.join(repo, '.git', 'task-excludes');
fs.writeFileSync(excludes, 'global-generated/\n');
git('config', '--local', 'core.excludesFile', '.git/task-excludes');
try {
git('check-ignore', 'global-generated/SKILL.md');
const extra: GeneratedArtifact = { relativePath: 'global-generated/SKILL.md', kind: 'skill', host: 'claude' };
expect(checkGeneratedFreshness(repo, render, [...generated.artifacts, extra]).diagnostics).toEqual([]);
} finally {
git('config', '--local', '--unset', 'core.excludesFile');
}
});
test('missing tracked output fails without being recreated', () => {
const file = path.join(repo, 'ship/SKILL.md');
const original = fs.readFileSync(file);
try {
fs.unlinkSync(file);
expect(checkGeneratedFreshness(repo, render, generated.artifacts).diagnostics).toContainEqual({ kind: 'stale', relativePath: 'ship/SKILL.md', message: 'generated or tracked output is missing' });
expect(fs.existsSync(file)).toBe(false);
} finally { fs.writeFileSync(file, original); }
});
test('new nonignored output must be tracked even when bytes match', () => {
git('update-index', '--force-remove', '--', 'ship/SKILL.md');
try {
expect(checkGeneratedFreshness(repo, render, generated.artifacts).diagnostics.some(d => d.kind === 'untracked' && d.relativePath === 'ship/SKILL.md')).toBe(true);
} finally { git('add', '--', 'ship/SKILL.md'); }
});
test('tracked ignored output is still freshness-checked', () => {
const relativePath = '.agents/skills/gstack-ship/SKILL.md';
git('add', '--force', '--', relativePath);
try {
expect(checkGeneratedFreshness(repo, render, generated.artifacts).diagnostics.some(d => d.kind === 'stale' && d.relativePath === relativePath)).toBe(true);
} finally { git('update-index', '--force-remove', '--', relativePath); }
});
test('Git failures are errors rather than stale results', () => {
const empty = fs.mkdtempSync(path.join(base, 'not-a-repo-'));
const result = checkGeneratedFreshness(empty, render, generated.artifacts);
expect(result.diagnostics).toHaveLength(1);
expect(result.diagnostics[0].kind).toBe('error');
expect(result.diagnostics[0].message).toContain('git ls-files');
});
});
describe('shared content validators', () => {
const file = path.join(base, 'validation/SKILL.md');
const artifact: GeneratedArtifact = { relativePath: 'validation/SKILL.md', host: 'codex', kind: 'skill' };
const frontmatter = '---\nname: fixture\ndescription: fixture skill\n---\n';
beforeAll(() => fs.mkdirSync(path.dirname(file)));
for (const [content, message] of [
['body only', 'frontmatter'],
['---\nname: fixture\ndescription: broken: mapping\n---\nBody.', 'valid YAML'],
['---\nname: 123\ndescription: fixture skill\n---\nBody.', 'name must be a nonempty string'],
['---\nname: fixture\ndescription: [one, two]\n---\nBody.', 'description must be a nonempty string'],
['---\nname: fixture\ndescription: ""\n---\nBody.', 'description must be a nonempty string'],
[frontmatter + '```bash\n$B nonexistent-command\n```', 'unknown command'],
[frontmatter + '```bash\n$B snapshot --bogus\n```', 'Unknown snapshot flag'],
[frontmatter + 'Read ~/.claude/skills/gstack/SKILL.md', 'outside a bash block'],
]) {
test(`rejects ${message}`, () => {
fs.writeFileSync(file, content);
expect(validateGeneratedArtifact(base, artifact).some(d => d.message.includes(message))).toBe(true);
});
}
test('legitimate fallback paths in bash examples pass', () => {
fs.writeFileSync(file, frontmatter + '```bash\nROOT=~/.claude/skills/gstack\n$B snapshot -i\n```');
expect(validateGeneratedArtifact(base, artifact)).toEqual([]);
});
test('quoted names and multiline descriptions remain valid for every host', () => {
fs.writeFileSync(file, '---\nname: "custom-skill"\ndescription: |\n A legitimate multiline\n description: with a colon.\n---\nBody.');
for (const host of ALL_HOST_NAMES) {
expect(validateGeneratedArtifact(base, { ...artifact, host })).toEqual([]);
}
});
// Generated by /ship Step 7 coverage audit (GSTA-96).
// Value: protects=skill:check rejects an unknown $B command or snapshot flag in a generated sections/preamble.md;
// fails_when='preamble' is dropped from the artifact kinds whose commands validateGeneratedArtifact checks;
// why_new=the all-host run above only proves valid preamble files pass; the section row covers kind 'section' alone;
// seam=none; no_claim=none beyond protects
test('the shared preamble validates commands without requiring frontmatter', () => {
for (const [content, message] of [['```bash\n$B snapshot --bogus\n```', 'Unknown snapshot flag'], ['```bash\n$B nonexistent-command\n```', 'unknown command']]) {
fs.writeFileSync(file, content);
const diagnostics = validateGeneratedArtifact(base, { ...artifact, kind: 'preamble', host: 'claude' });
expect(diagnostics).toHaveLength(1);
expect(diagnostics[0].message).toContain(message);
}
});
test('carved sections also validate commands without requiring frontmatter', () => {
fs.writeFileSync(file, '```bash\n$B snapshot --bogus\n```');
const diagnostics = validateGeneratedArtifact(base, { ...artifact, kind: 'section', host: 'claude' });
expect(diagnostics).toHaveLength(1);
expect(diagnostics[0].message).toContain('Unknown snapshot flag');
});
});