Skip to main content

Overview

Test suites rot from the inside. Teams write tests for the features they build, skip the ones they inherit, and never go back to fill the gaps. The result is coverage that correlates with recency, not criticality — the newest code is well-tested, the most important code is not. AI coding agents can generate tests at scale, but without knowing what the system is supposed to do, they produce tests that mirror implementation: tests that pass today, break on every refactor, and verify nothing meaningful. This playbook teaches you how to use the CoreStory MCP server, combined with local source code, to systematically generate tests that verify behavioral specifications — acceptance criteria, business rules, invariants, state transitions, and authorization policies — rather than implementation details. The approach uses CoreStory as a Specification Expert: the agent queries CoreStory for what the system should do, discovers how the system actually does it, and generates tests that bridge the two. The primary deliverable is executable test code that matches the project’s existing test conventions — framework, directory structure, naming patterns, fixture approach, and assertion style. There is no intermediate documentation artifact. The behavioral inventory lives in the CoreStory conversation; the tests are the output. How this relates to other playbooks: This playbook generates tests for existing, already-implemented behavior — it doesn’t implement new features or fix bugs. If you’re implementing a new feature and want tests as part of that process, use the Feature Implementation playbook, which includes TDD as Phase 4. If you’re verifying behavioral equivalence between legacy and modernized code, use the Behavioral Verification playbook. If you need to extract and document business rules before generating tests, use the Business Rules Extraction playbook — its output feeds directly into Phase 2 of this playbook. This playbook’s unique contribution is systematic, specification-driven test generation for existing codebases that lack adequate coverage.

When to Use This Playbook

  • A codebase has significant untested business logic and you want to close coverage gaps systematically
  • You’re onboarding to an unfamiliar codebase and want to build a safety net before making changes
  • Preparing for a major refactor, migration, or dependency upgrade and need comprehensive regression tests
  • A compliance or audit requirement demands documented test coverage of specific business rules
  • You’ve completed a Business Rules Extraction and want to turn the inventory into executable tests
  • The team’s test coverage is implementation-heavy (mocking everything, testing method signatures) and you want to shift toward behavioral tests

When to Skip This Playbook

  • You’re implementing a new feature (use the Feature Implementation playbook — its TDD phase generates tests as part of implementation)
  • The codebase is trivially small (under ~5k LOC) — write the tests directly
  • No CoreStory project exists for the codebase and you can’t create one
  • You need to verify behavioral equivalence between two implementations (use the Behavioral Verification playbook)
  • The system under test has no observable behavior (pure infrastructure, configuration-only)

Prerequisites

  • CoreStory account with at least one project that has completed ingestion
  • CoreStory MCP server connected to your AI coding agent (see the CoreStory MCP Server Setup Guide)
  • A code repository the agent can read and write to locally
  • An existing test framework configured in the project (the playbook generates tests matching existing conventions — it doesn’t set up test infrastructure from scratch)
  • (Recommended) A prior Business Rules Extraction conversation — if one exists, Phase 2 can consume it directly instead of starting from scratch
  • (Recommended) Ability to run the test suite locally to verify generated tests

How It Works

The Workflow Phases

The core principle is Specification before Code: query CoreStory for behavioral specifications before examining source code or writing tests. This ensures tests verify intended behavior, not implementation accidents.

CoreStory MCP Tools Used

A note on the PRD and TechSpec: As with other playbooks, these documents are typically too large for an agent’s context window. Don’t try to read them end-to-end. Query CoreStory about their contents via send_message instead — CoreStory has already ingested them and can answer targeted questions about acceptance criteria, business rules, and constraints more efficiently than the agent can parse the raw documents.

HITL Gate

After Phase 4 (Coverage Gap Analysis): Before generating tests, a human should review the behavioral inventory and prioritized gap list. This is the checkpoint where domain knowledge matters most — the human validates that the extracted specifications are correct, that the prioritization makes sense, and that the scope is appropriate. Generating tests from incorrect specifications produces confidently wrong assertions.

Step-by-Step Walkthrough

Phase 1 — Setup & Scoping

Goal: Establish the test generation session and define what you’re generating tests for. Step 1.1: Find the project.
Identify the target project by name. Note the project_id — you’ll use it for every subsequent call. Step 1.2: Check for prior work.
Look for two types of prior conversations:
  • Business Rules Extraction conversations (titles containing “Business Rules”) — if one exists for the module you’re targeting, it contains a pre-built behavioral inventory. You can consume it in Phase 2 instead of extracting from scratch.
  • Prior Test Generation conversations (titles containing “Test Generation”) — if you’ve run this playbook before on a different module, review it for conventions and patterns that worked well.
Use get_conversation to review any relevant prior work. Step 1.3: Create a conversation.
Use a descriptive title that includes the generation scope. Examples:
  • “Test Generation — Order Processing Module”
  • “Test Generation — Full System Behavioral Coverage”
  • “Test Generation — Authentication & Authorization Rules”
Step 1.4: Define scope. Choose the generation scope before querying: For a first run, start with a single module — preferably one with known coverage gaps and high business criticality. Full-system generation should be done one domain at a time across multiple sessions.

Phase 2 — Behavioral Inventory (Expert)

Goal: Extract a comprehensive list of testable behavioral specifications for the scoped area. This is the phase that distinguishes specification-driven test generation from naive code-coverage-driven generation. You’re building an inventory of what the system should do, not what it happens to do. Each item in this inventory becomes one or more test cases. If a Business Rules Extraction conversation exists for the target scope, consume it:
Review the extracted rules. Each rule with its domain, type, enforcement layer, source files, and invariants translates directly into test cases. Skip to Step 2.6 (gap-filling) — you already have the core inventory. If no prior extraction exists, build the inventory from scratch using targeted queries. This is a lighter version of the Business Rules Extraction playbook, focused specifically on testable specifications rather than comprehensive documentation. Step 2.1: Query for acceptance criteria.
Acceptance criteria are the most directly testable specifications — they often map 1:1 to test cases. Step 2.2: Query for validation rules.
Validation rules produce highly specific tests: given this input, expect this outcome. CoreStory typically returns constraint values (e.g., “password must be 8–12 characters”), enforcement locations, and error responses. Step 2.3: Query for state transitions.
State transitions produce two categories of tests: positive tests (valid transitions succeed and produce correct postconditions) and negative tests (invalid transitions are rejected with appropriate errors). Step 2.4: Query for authorization rules.
Authorization rules produce tests for every role × operation combination: permitted users succeed, forbidden users get appropriate errors. Step 2.5: Query for invariants and edge cases.
Invariants produce assertion-style tests: after any operation, these conditions must still be true. Edge cases produce boundary tests that often catch the most subtle bugs. Step 2.6: Gap-filling — query for implicit and undocumented behavior.
This surfaces the behaviors that teams “just know” but never wrote down — and therefore never tested. These are often the highest-value test cases. Step 2.7: Query for calculation and transformation logic.
Calculation logic is where property-based and parameterized tests shine — given these inputs, the output must satisfy these properties. Expected output from Phase 2: A behavioral inventory in the CoreStory conversation, organized by category:
  • Acceptance criteria (from PRD / user stories)
  • Validation rules (per entity/operation)
  • State transitions (valid and invalid)
  • Authorization rules (per role × operation)
  • Invariants (always-true conditions)
  • Implicit behaviors (undocumented but enforced)
  • Calculations and transformations
Each item should have enough specificity to translate into a test: inputs, expected outputs, preconditions, postconditions.

Phase 3 — Test Convention Discovery (Expert + Navigator)

Goal: Understand how the project’s existing tests are structured so generated tests match perfectly. This phase ensures generated tests are indistinguishable from hand-written tests by the team. The agent must discover the testing conventions before writing any test code. Step 3.1: Query for test framework and structure.
The agent needs: framework (pytest, Jest, JUnit, xUnit, RSpec, etc.), directory layout, file naming pattern (e.g., test_*.py, *.test.ts, *Test.java), and any test configuration files. Step 3.2: Query for fixture and setup patterns.
The agent needs: fixture approach (factories vs. fixtures vs. inline setup), shared utilities, database handling (transactions, in-memory DB, mocks), and external service handling (mocks, stubs, test doubles). Step 3.3: Query for assertion and mock patterns.
Step 3.4: Verify conventions against local code. Navigate to the existing test directories in the local codebase and read 2–3 representative test files. Confirm that CoreStory’s description of conventions matches reality. Pay attention to:
  • Import patterns
  • Setup/teardown patterns
  • Assertion style (fluent, classic, custom)
  • Mock/stub conventions
  • Test naming (descriptive strings vs. method names)
  • Comment and docstring conventions
If conventions vary across the codebase (common in older projects), identify which convention applies to the module you’re generating tests for. Expected output from Phase 3: A concrete understanding of:
  • Test framework and runner
  • Directory and file naming conventions
  • Fixture and setup patterns to follow
  • Mock/stub approach
  • Assertion style
  • 2–3 reference test files to use as templates

Phase 4 — Coverage Gap Analysis (Navigator)

Goal: Map the behavioral inventory against existing tests to identify what’s missing. Prioritize the gaps. Step 4.1: Query for existing test coverage.
Step 4.2: Inspect existing tests locally. Navigate to the test files CoreStory identified. Read them to understand:
  • Which behaviors are already tested
  • Which behaviors are tested but weakly (e.g., only happy path, no edge cases)
  • Which behaviors have no test coverage at all
Step 4.3: Build the gap matrix. Cross-reference the behavioral inventory (Phase 2) against existing tests (Steps 4.1–4.2). For each behavior: Step 4.4: Prioritize gaps. Not all gaps are equal. Prioritize by:
  1. Business criticality — Rules that affect money, security, data integrity, or regulatory compliance
  2. Risk of breakage — Behaviors in frequently modified code, complex logic, or cross-component interactions
  3. Specificity of specification — Behaviors where the Phase 2 inventory has precise, testable specifications (vague specifications produce vague tests)
  4. Testability — Behaviors that can be tested in isolation without excessive infrastructure
Expected output from Phase 4: A prioritized list of behavioral specifications that need tests, categorized as “uncovered” or “partially covered,” with the specific gaps identified for each.
HITL Gate: Present the gap analysis to the human for review before proceeding. Key questions: Are the extracted specifications correct? Is the prioritization sensible? Is the scope appropriate for this session?

Phase 5 — Test Generation & Validation

Goal: Generate test code for each gap, verify tests pass, and confirm they’re meaningful. Work through the prioritized gap list from Phase 4. For each behavioral specification: Step 5.1: Generate the test. Using the behavioral specification from Phase 2, the test conventions from Phase 3, and the reference test files as templates, write the test. Each test should:
  • Follow the project’s naming conventions exactly
  • Use the project’s fixture and setup patterns
  • Assert the behavioral specification, not implementation details
  • Include a docstring or comment linking back to the specification (e.g., the acceptance criterion, business rule ID, or invariant)
  • Handle setup, action, and assertion in the project’s standard structure (AAA, Given-When-Then, etc.)
Step 5.2: Run the test. Execute the test and verify it passes against the current codebase. A generated test that fails immediately indicates one of three things: Step 5.3: Validate the test is meaningful. A test that passes is not necessarily a good test. For high-priority tests, validate that the test would fail if the behavior it verifies were broken. The simplest approach:
For critical invariants and business rules, consider a manual mutation check: temporarily alter the source code to violate the rule and confirm the test catches it. Restore the code afterward. Step 5.4: Generate edge case tests. For each core behavioral test, query CoreStory for edge cases specific to that behavior:
Generate additional tests for the most important edge cases. Step 5.5: Run the full test suite. After generating a batch of tests (typically per-module or per-domain), run the full test suite. Verify:
  • All new tests pass
  • No existing tests broke (new test files shouldn’t affect existing tests, but shared fixture changes might)
  • Test execution time is reasonable (generated tests should not significantly slow the suite)
Expected output from Phase 5: Test files matching the project’s conventions, organized in the project’s standard test directory structure, covering the gaps identified in Phase 4.

Phase 6 — Completion & Capture

Goal: Finalize generated tests, capture the session, and report coverage. Step 6.1: Review coverage against the behavioral inventory. Map the generated tests back to the Phase 2 behavioral inventory. Produce a summary:
Step 6.2: Organize test files. Ensure generated tests are in the correct directories, follow the project’s file naming conventions, and are ready to commit. If the project separates unit and integration tests, ensure each generated test is in the right category. Step 6.3: Commit the tests. Commit with a message that explains what was generated and why:
Step 6.4: Rename the conversation.
The RESOLVED prefix signals that this conversation contains a completed test generation session. Future sessions can reference it for conventions and patterns.

Tips & Best Practices

The specificity principle applies to test generation even more than to extraction. Compare: Always name the specific entity, operation, and rule types you’re asking about. Behavioral tests vs. implementation tests — how to tell the difference: A behavioral test asserts what the system does:
An implementation test asserts how the system does it:
The first test survives refactoring. The second breaks the moment anyone renames the validator. This playbook generates the first kind. How to scope generation to avoid overwhelming the agent and the reviewer:
  • Generate tests one domain at a time, completing the full cycle (inventory → conventions → gaps → generate → validate) before moving on
  • Within a domain, generate core behavioral tests first, edge case tests second
  • Target 10–30 test cases per session — enough to be meaningful, small enough for thorough human review
  • For a full-system effort, plan multiple sessions with clear domain boundaries
When generated tests fail — treat it as discovery, not failure: A generated test that fails on assertion (not on setup) is telling you something valuable: either the specification is wrong or the code is wrong. Both are important to know. Flag these for human review rather than discarding the test or adjusting the assertion to match current behavior. How to handle specifications that are too vague to test: If CoreStory returns a behavioral specification that’s too vague for a precise test (e.g., “the system should handle errors gracefully”), ask a follow-up:
If the specification remains vague after a targeted follow-up, it’s likely underdefined in the codebase itself. Note it as a gap in the coverage report rather than generating a meaningless test. When to involve a domain expert:
  • After Phase 2 (behavioral inventory) — to validate extracted specifications, especially implicit rules that exist only in code
  • After Phase 4 (gap analysis) — to confirm prioritization and scope
  • When generated tests fail on assertion — to determine whether the spec or the code is wrong
  • For low-confidence specifications (found only in code with no supporting documentation)

Advanced Patterns

Consuming a Business Rules Inventory

If the Business Rules Extraction playbook has been run for this module, the output is a structured inventory with rule IDs (BR-XXX), domains, types, enforcement layers, source files, and invariants. Each rule maps to tests as follows: Reference the BR-XXX IDs in test docstrings for traceability:

Parameterized Tests for Validation Rules

When a validation rule has multiple constraint values (e.g., field length limits, allowed formats, enum values), generate parameterized tests rather than individual test functions:
The exact parameterization syntax depends on the project’s framework — adapt to match.

Authorization Matrix Testing

When the behavioral inventory includes authorization rules across multiple roles and operations, generate the tests systematically from the matrix:
This produces a matrix that maps directly to parameterized tests:

State Transition Testing

For entities with defined lifecycles, generate tests for both valid and invalid transitions:
Generate positive tests for each valid transition and negative tests for representative invalid transitions:

Integration with CI/CD

Generated tests should be integrated into the project’s CI/CD pipeline like any other tests. No special configuration should be needed — the tests use the same framework, fixtures, and assertion patterns as existing tests. If the project has coverage reporting (e.g., pytest-cov, Istanbul, JaCoCo), the generated tests will automatically improve reported coverage. For teams running this playbook regularly, consider a periodic cadence: run test generation for one domain per sprint, rotating through the system. This gradually builds comprehensive behavioral coverage without requiring a single large effort.

Troubleshooting

CoreStory returns vague behavioral specifications. Your query is too broad. Replace “What should I test?” with “What validation rules exist for [specific entity] including [specific rule types]?” Always name the module, entity, or workflow. See the specificity principle in Tips above. Generated tests fail on setup, not on assertions. The test conventions from Phase 3 don’t match reality. Re-inspect the existing test files locally. Common causes: wrong import paths, missing fixture setup, incorrect mock targets, or framework version mismatches. Generated tests all pass but don’t feel meaningful. The tests may be asserting implementation details rather than behavioral specifications. Review against the “behavioral vs. implementation” distinction in Tips. If the test would still pass after changing the underlying business rule, it’s not testing the rule. CoreStory’s behavioral specification contradicts what the code does. This is valuable discovery. The specification (from the PRD or CoreStory’s understanding) says X; the code does Y. Flag it as a conflict rather than adjusting the test to match the code. One of two things is true: the code has a bug, or the specification is outdated. Both are worth knowing. Too many gaps to address in one session. This is normal for large, undertested codebases. Focus on one domain per session, prioritized by business criticality. Use the gap matrix from Phase 4 to plan a multi-session campaign. Each session produces value independently — you don’t need to cover everything at once. Phase 2 surfaces behaviors that are already well-tested. Skip them. The gap analysis in Phase 4 exists precisely to avoid generating redundant tests. If Phase 4 shows most behaviors are covered, the module has good existing coverage — move to a different module. Tests take too long to run. Generated behavioral tests should be fast. If they’re slow, check whether they’re accidentally hitting real databases, APIs, or file systems instead of using the project’s standard mocks and fixtures. Ensure generated tests follow the same isolation patterns as existing tests.

Agent Implementation Guides

The skill file shown below is plain markdown. The workflow it encodes works in any agentic harness — only the install location differs. Common conventions:
Want a single install that works across the most harnesses? Append the content to AGENTS.md at your repository root. The AGENTS.md spec is read by Codex, Aider, Cursor, Factory, Jules, Gemini CLI, Windsurf, GitHub Copilot’s coding agent, JetBrains Junie, Warp, and others — so a single file covers most users without harness-specific setup.
If your harness isn’t listed, the SKILL.md content itself is portable — install it wherever your harness loads workflow context and adapt the activation step (auto-trigger, slash command, explicit invocation) to your harness’s conventions. The sections below walk through end-to-end setup (skill file, version control, usage) for the four most common harnesses. If you’re on a different harness, copy the SKILL.md content from any section and install it per the conventions above.

Claude Code

Setup

1. Connect CoreStory MCP server. Run this in your terminal:
Verify the connection works:
2. (Optional) Connect a ticketing system MCP. Useful if test generation is driven by ticket requirements. See each platform’s official MCP server documentation. 3. Install the test generation skill. Create the skill directory and file:
Then create .claude/skills/generate-tests/SKILL.md with the contents from the Skill File section below. Commit it to version control so the whole team gets it:

Usage

The skill activates automatically when Claude Code detects test generation requests:

Tips

  • Skills auto-load from directories added via --add-dir, so team-shared skills work across machines.
  • Claude Code detects file changes during sessions — you can edit the skill file and it takes effect immediately.
  • Keep the SKILL.md under 500 lines for reliable loading.
  • Let it run. The workflow is designed for autonomous execution. Interrupting mid-phase breaks the chain of context.
  • Start with a focused module. A single-module run produces tests you can review in one sitting. Full-system runs produce too much to review at once.
  • The skill works with other skills. If you have a Business Rules Extraction skill, Claude Code will use its output as input to Phase 2.

Skill File

Save as .claude/skills/generate-tests/SKILL.md:

GitHub Copilot

Setup

  1. Configure the CoreStory MCP server. Add to your VS Code MCP settings (.vscode/mcp.json or user settings). Verify by asking Copilot Chat: “List my CoreStory projects.”
  2. Add project-level custom instructions. Create or update .github/copilot-instructions.md with the content from the instructions file below.
  3. Optionally add a reusable prompt file. Create .github/prompts/generate-tests.prompt.md with mode: agent frontmatter for on-demand invocation.
  4. Commit to version control:

Usage

With custom instructions active, Copilot Chat applies the workflow automatically when you ask about test generation:
If using a prompt file:

Tips

  • .github/copilot-instructions.md is always active — it’s global custom instructions for the project. Keep it focused on principles.
  • Prompt files (.github/prompts/) are invoked on demand and support mode: agent for agentic execution.
  • Copilot Chat accesses MCP tools through the VS Code MCP configuration. Ensure CoreStory tools appear in the available tools list.

Custom Instructions File

Save as .github/copilot-instructions.md (append to existing content if the file already exists):

Cursor

Setup

  1. Configure the CoreStory MCP server. Add to your Cursor MCP configuration (.cursor/mcp.json or user settings). Verify by asking Cursor Chat: “List my CoreStory projects.”
  2. Add the project rule. Cursor uses rules stored in .cursor/rules/:
Create .cursor/rules/generate-tests.mdc with the content from the rule file below.
  1. Commit to version control:

Usage

With alwaysApply: true, the rule activates automatically when Cursor detects test generation context. Or trigger it explicitly:

Tips

  • Cursor rules use .mdc extension with YAML frontmatter containing description, globs, and alwaysApply.
  • Set alwaysApply: true for rules that should always be active, or use globs to restrict to specific files.
  • Rules apply in both Composer and Chat modes.

Project Rule

Save as .cursor/rules/generate-tests.mdc:

Factory.ai

Setup

  1. Configure the CoreStory MCP server in your Factory.ai environment. Verify with the /mcp command that CoreStory tools are accessible.
  2. Add the custom droid. Factory.ai uses droids stored in .factory/droids/ (project-level) or ~/.factory/droids/ (personal):
Create .factory/droids/generate-tests.md with the content from the droid file below.
  1. Commit to version control:

Usage

Invoke the droid:
Or describe the task naturally — Factory.ai routes to the appropriate droid:

Droid File

Save as .factory/droids/generate-tests.md: