import { describe, it, expect, beforeAll, afterAll } from 'vitest'; import { BEFORE_ALL_TIMEOUT_MS, createSpawnContext, describeSpawnContext, disposeSpawnContext, installDevflow, isClaudeAvailable, liveSkipReason, pickCredential, printLiveSkip, runClaudeAndWait, getSubagentPreloadResult, type SpawnContext, } from './helpers.js'; /** * Maximum spawn attempts per agent type. One bounded retry is legitimate * mitigation for LLM non-determinism: haiku may occasionally answer the * parent prompt directly (exit 0) without calling the Agent tool, leaving * no subagents/ directory. A second attempt almost always succeeds. * * Two attempts total (1 original + 1 retry). Never more. */ const MAX_SPAWN_ATTEMPTS = 2; /** * Spawn an agent by name and return the preloaded skills from all subagent * transcripts in the session that was actually spawned. * * Session identity is deterministic: `runClaudeAndWait` generates a UUID before * spawning and passes it via `--session-id`. The subagents/ directory is then * read by exact path, eliminating the directory-diff race that caused sporadic * null session IDs when background Claude processes (e.g., devflow memory worker) * created new session directories concurrently. * * Outcome classification: * - 'no-session-dir': parent answered directly without spawning — retry once. * - 'no-transcripts': subagents/ dir exists but no agent-*.jsonl files — fail. * - 'ok': one or more transcripts found; return them for skill assertion. * * Returns string[][] — one skill list per transcript. The caller asserts that * at least one transcript contains the expected skills, avoiding a race where * Claude spawns auxiliary subagents whose transcript appears alongside the target. */ async function spawnAgentAndGetAllPreloads( ctx: SpawnContext, agentType: string, prompt: string, ): Promise { for (let attempt = 1; attempt <= MAX_SPAWN_ATTEMPTS; attempt++) { const result = await runClaudeAndWait( ctx, // Explicit imperative so haiku cannot answer the task itself. `You MUST call the Agent tool exactly once with subagent_type="${agentType}" and the prompt below. ` + `Do not answer the task yourself. After the agent returns, reply with the single word DONE.\n\n` + `Prompt: ${prompt}`, { timeout: 60000, model: 'haiku', allowedTools: 'Agent' }, ); const preloadResult = getSubagentPreloadResult(ctx, result.sessionId); if (preloadResult.kind === 'no-session-dir') { if (attempt < MAX_SPAWN_ATTEMPTS) { // Parent answered directly without spawning — one bounded retry (no silent vacuous pass). console.warn( `[attempt ${attempt}/${MAX_SPAWN_ATTEMPTS}] ${agentType}: parent spawned no subagent ` + `(exit=${result.exitCode}, ${result.durationMs}ms). Retrying.\n` + `Output tail: ${result.stdoutTail.slice(-400)}`, ); continue; } expect.fail( `${agentType}: parent spawned no subagent after ${MAX_SPAWN_ATTEMPTS} attempts. ` + `exit=${result.exitCode}, duration=${result.durationMs}ms.\n` + `Output tail (last ${result.stdoutTail.length}B):\n${result.stdoutTail}`, ); } if (preloadResult.kind === 'no-transcripts') { expect.fail( `${agentType}: subagents/ directory exists but contains zero agent-*.jsonl transcripts. ` + `sessionId=${result.sessionId}, exit=${result.exitCode}, duration=${result.durationMs}ms.\n` + `Output tail (last ${result.stdoutTail.length}B):\n${result.stdoutTail}`, ); } return preloadResult.transcripts; } // Unreachable: loop either returns or calls expect.fail(). throw new Error('unreachable: MAX_SPAWN_ATTEMPTS loop exited without returning'); } /** * Smoke tests for subagent skill preload via YAML block-list frontmatter. * * Verifies that skills declared in agent frontmatter are actually injected * into the subagent context at spawn time (visible as tags * in subagent transcripts). * * Every session runs in a temp HOME and a temp git repository, with devflow installed into * that HOME by `beforeAll`, the permission mode `dontAsk` (set by `buildPreloadArgs`), and * the Agent tool as the only allowed tool. It never touches the developer's own ~/.claude * or this checkout. * * Requirements: * - `claude` CLI installed * - CLAUDE_CODE_OAUTH_TOKEN or ANTHROPIC_API_KEY set (a temp HOME cannot use the stored login); * without one the file skips and prints why * - A built CLI (`npm run build`) * * Run: DEVFLOW_INTEGRATION_ALL=1 npx vitest run --config vitest.integration.config.ts \ * tests/integration/subagent-skill-preload.test.ts * (not part of `npm test` or a plain `npm run test:integration` — each test is an API call) */ const credential = pickCredential(process.env); const skipReason = liveSkipReason(credential, isClaudeAvailable()); printLiveSkip('subagent-skill-preload', skipReason); describe.skipIf(skipReason !== null)('subagent skill preload', () => { let ctx: SpawnContext; beforeAll(() => { ctx = createSpawnContext(credential); console.log(describeSpawnContext(ctx)); installDevflow(ctx); }, BEFORE_ALL_TIMEOUT_MS); afterAll(() => { if (ctx !== undefined) disposeSpawnContext(ctx); }); it('Polish agent preloads software-design and worktree-support', async () => { const allPreloads = await spawnAgentAndGetAllPreloads(ctx, 'Polish', 'reply with one line only — do not create, modify, or delete any file, do not run git: function add(a, b) { return a + b; }'); const expected = ['software-design', 'worktree-support']; expect( allPreloads.some((p) => expected.every((s) => p.includes(s))), `No transcript contains ${expected.join(', ')}. Found: ${JSON.stringify(allPreloads)}`, ).toBe(true); // Polish agent must NOT have apply-decisions (PR #182 explicit assertion) const polishTranscript = allPreloads.find((p) => expected.every((s) => p.includes(s)))!; expect(polishTranscript).not.toContain('apply-decisions'); }, 90000); it('Harden agent preloads quality-gates, software-design, worktree-support, apply-decisions', async () => { const allPreloads = await spawnAgentAndGetAllPreloads(ctx, 'Harden', 'reply with one line only — do not create, modify, or delete any file, do not run git: const x = 1;'); const expected = ['quality-gates', 'software-design', 'worktree-support', 'apply-decisions']; expect( allPreloads.some((p) => expected.every((s) => p.includes(s))), `No transcript contains ${expected.join(', ')}. Found: ${JSON.stringify(allPreloads)}`, ).toBe(true); }, 90000); it('Review agent preloads review-methodology, worktree-support, apply-decisions', async () => { const allPreloads = await spawnAgentAndGetAllPreloads(ctx, 'Review', 'reply with one line only — do not create, modify, or delete any file, do not run git: const y = 2;'); const expected = ['review-methodology', 'worktree-support', 'apply-decisions']; expect( allPreloads.some((p) => expected.every((s) => p.includes(s))), `No transcript contains ${expected.join(', ')}. Found: ${JSON.stringify(allPreloads)}`, ).toBe(true); }, 90000); it('Code agent preloads the six core skills, and none of the four mode skills', async () => { await expectRetainedPreloads( 'Code', 'reply with one line only — do not create, modify, or delete any file, do not run git, do not write any code', ['git', 'testing', 'test-driven-development', 'worktree-support', 'apply-feature-knowledge', 'apply-decisions'], ['software-design', 'patterns', 'boundary-validation', 'dependency-research'], ); }, 90000); // D-DESIGN-VARIANTS: each Design variant preloads its own mode skill and not the other one. it('Design agent preloads worktree-support, apply-decisions, gap-analysis, and not design-review', async () => { await expectRetainedPreloads( 'Design', 'reply with one line only — do not create, modify, or delete any file, do not run git: Add a cache layer.', ['worktree-support', 'apply-decisions', 'gap-analysis'], ['design-review'], ); }, 90000); it('Architect agent preloads worktree-support, apply-decisions, design-review, and not gap-analysis', async () => { await expectRetainedPreloads( 'Architect', 'reply with one line only — do not create, modify, or delete any file, do not run git: Add a cache layer.', ['worktree-support', 'apply-decisions', 'design-review'], ['gap-analysis'], ); }, 90000); it('Git agent preloads git and worktree-support', async () => { const allPreloads = await spawnAgentAndGetAllPreloads(ctx, 'Git', 'Report the current branch name only. Do not run any git command that writes (no commit, add, checkout, push, stash, tag, reset).'); const expected = ['git', 'worktree-support']; expect( allPreloads.some((p) => expected.every((s) => p.includes(s))), `No transcript contains ${expected.join(', ')}. Found: ${JSON.stringify(allPreloads)}`, ).toBe(true); }, 90000); it('Research agent preloads worktree-support, apply-decisions, apply-feature-knowledge', async () => { const allPreloads = await spawnAgentAndGetAllPreloads(ctx, 'Research', 'reply with one line only naming one testing framework — do not create, modify, or delete any file, do not run git'); const expected = ['worktree-support', 'apply-decisions', 'apply-feature-knowledge']; expect( allPreloads.some((p) => expected.every((s) => p.includes(s))), `No transcript contains ${expected.join(', ')}. Found: ${JSON.stringify(allPreloads)}`, ).toBe(true); }, 90000); // Agents whose tool policy removes the Skill tool, or that carry an allowlist, still get // their `skills:` list injected at spawn time: preload does not go through the tool. Each // case asserts the retained set, and that a trimmed skill (D-PRELOAD-TRIM) is no longer // loaded. Curate has no case: it preloads nothing, and its spawn would claim a real queue. /** * Spawn `agentType`, find the transcript that holds every expected skill, and check that * none of the trimmed skills rides along with it. */ async function expectRetainedPreloads( agentType: string, prompt: string, expected: readonly string[], trimmed: readonly string[] = [], ): Promise { const allPreloads = await spawnAgentAndGetAllPreloads(ctx, agentType, prompt); const match = allPreloads.find((p) => expected.every((s) => p.includes(s))); expect(match, `No transcript contains ${expected.join(', ')}. Found: ${JSON.stringify(allPreloads)}`).toBeDefined(); for (const skill of trimmed) { expect(match, `${agentType} still preloads ${skill}`).not.toContain(skill); } } it('Triage agent preloads worktree-support, apply-decisions, apply-feature-knowledge, and no longer security', async () => { await expectRetainedPreloads( 'Triage', 'reply with one line only — do not create, modify, or delete any file, do not run git: there are no issues to triage.', ['worktree-support', 'apply-decisions', 'apply-feature-knowledge'], ['security'], ); }, 90000); it('Knowledge agent preloads feature-knowledge, apply-decisions, worktree-support, and no longer apply-feature-knowledge', async () => { await expectRetainedPreloads( 'Knowledge', 'reply with one line only — do not create, modify, or delete any file, do not run git: there is no feature area to document.', ['feature-knowledge', 'apply-decisions', 'worktree-support'], ['apply-feature-knowledge'], ); }, 90000); it('Evaluate agent preloads worktree-support and apply-feature-knowledge, and no longer software-design', async () => { await expectRetainedPreloads( 'Evaluate', 'reply with one line only — do not create, modify, or delete any file, do not run git: nothing was implemented.', ['worktree-support', 'apply-feature-knowledge'], ['software-design'], ); }, 90000); it('Validate agent preloads worktree-support, and no longer testing', async () => { await expectRetainedPreloads( 'Validate', 'reply with one line only — do not run any command, do not create, modify, or delete any file: there is nothing to validate.', ['worktree-support'], ['testing'], ); }, 90000); it('Synthesize agent preloads worktree-support, and no longer review-methodology or docs-framework', async () => { await expectRetainedPreloads( 'Synthesize', 'reply with one line only — do not create, modify, or delete any file, do not run git: there are no agent outputs to synthesize.', ['worktree-support'], ['review-methodology', 'docs-framework'], ); }, 90000); it('Skim agent preloads worktree-support', async () => { await expectRetainedPreloads( 'Skim', 'reply with one line only — do not run any command, do not create, modify, or delete any file.', ['worktree-support'], ); }, 90000); it('Debug agent preloads worktree-support, apply-decisions, apply-feature-knowledge, and none of the five pattern skills', async () => { await expectRetainedPreloads( 'Debug', 'reply with one line only — do not create, modify, or delete any file, do not run git, do not write a report: FOCUS security, nothing to analyse.', ['worktree-support', 'apply-decisions', 'apply-feature-knowledge'], ['security', 'reliability', 'regression', 'consistency', 'complexity'], ); }, 90000); it('Test agent preloads qa and worktree-support, and no longer testing', async () => { await expectRetainedPreloads( 'Test', 'reply with one line only — do not run any command, do not create, modify, or delete any file: there is nothing to test.', ['qa', 'worktree-support'], ['testing'], ); }, 90000); });