# How Does CoreStory Work? Source: https://docs.corestory.ai/about/how-does-corestory-work How CoreStory ingests repositories and produces queryable code intelligence. ## Input The CoreStory platform accepts **public repositories**, **private repositories**, and **direct file uploads** as inputs. Connect a GitHub repo or upload source files to get started. ## Ingestion Once you connect a repository, CoreStory ingests it to produce a custom **intelligence model** for that repository. This intelligence model is a dynamically queryable central store of system metadata — a rich source of truth for human and AI workers modernizing or maintaining your codebase. ## Output Your intelligence model can be queried via chat to produce on-demand **code intelligence** about your repository's structure, behavior, and business requirements. Each standard repository ingestion creates: * A **chat interface** for natural language queries about your code * A standard set of **specification outputs** (executive summary, user personas, user stories, data models, API specifications, and integration points) that can be further customized ## Integration CoreStory provides an **MCP server** and **REST API** so that third-party tools — including AI coding agents like Claude, Cursor, and GitHub Copilot — can query your intelligence model directly. This means your AI tools make decisions grounded in actual system context rather than guessing. Connect your first repository and start querying. # What is CoreStory? Source: https://docs.corestory.ai/about/what-is-corestory An overview of the CoreStory code intelligence platform. CoreStory is a code intelligence platform that uses AI to reverse-engineer specifications directly from source code, helping product and engineering teams accelerate onboarding, improve governance, and reduce the risk of failure when performing work on large codebases. ## Why CoreStory? Most teams working on large or legacy codebases face the same problem: the documentation is stale, tribal knowledge lives in people's heads, and AI coding tools hallucinate because they lack grounded context. CoreStory solves this by creating a **persistent intelligence layer** — a dynamically queryable model of your codebase that stays current with your source code. This gives both human and AI workers a shared, accurate understanding of system behavior. ## What Can You Do With It? * **Understand unfamiliar codebases** — Ask natural language questions about architecture, business logic, data flow, and dependencies. * **Generate grounded specifications** — Produce executive summaries, user stories, data models, API specs, and integration maps derived from actual source code. * **Supercharge AI agents** — Connect CoreStory to Claude, Cursor, GitHub Copilot, Devin, and other AI tools via MCP so they make decisions grounded in real system context. * **Accelerate onboarding** — Get new developers productive faster by giving them instant access to system-level understanding. * **De-risk modernization** — Map business rules, hidden dependencies, and integration points before making changes. # Who is CoreStory For? Source: https://docs.corestory.ai/about/who-is-corestory-for The teams and roles that benefit from CoreStory's code intelligence. CoreStory is for **developers, architects, analysts, product managers, and business stakeholders** working with your repository. Your entire team can query their CoreStory code intelligence model throughout the SDLC to ensure a consistent, shared understanding of system behavior. ## By Role Onboard faster, understand unfamiliar modules, and get AI-assisted bug fixes and feature implementation grounded in real system context. Map dependencies, integration points, and business rules across large codebases. De-risk modernization and migration decisions. Access auto-generated user stories, executive summaries, and data models without waiting for engineering to document them. Understand system capabilities and business logic embedded in code — especially critical for M\&A due diligence, compliance, and governance. ## By Use Case * **Legacy modernization** — Understand what a system does before deciding how to change it. * **M\&A technical due diligence** — Extract business rules and assess technical debt from acquired codebases. * **AI-assisted development** — Give Claude, Copilot, Cursor, or Devin grounded context so they produce better code. * **Onboarding** — Eliminate the months-long ramp time for developers joining complex projects. * **Compliance & governance** — Maintain auditable, up-to-date specifications derived from source code. # Getting Started Source: https://docs.corestory.ai/getting-started/getting-started Set up your CoreStory account and start generating code intelligence. ## 1) What To Expect For any newly created project, CoreStory provides the user with the following set of default features: * **Custom Intelligence Model:** A dynamically queryable central store of system metadata that provides you with on-demand code intelligence * **Chat With Your Code**: Ready-to-go chat interface supporting natural language queries about your repository's contents * **MCP Server**: Ability to integrate your intelligence model into other tools using the Model Context Protocol * **Core Documents:** A default set of specifications, broken out by category, to help you rapidly understand your codebase * **Optional structured exports:** PDF, Markdown, and JSON versions of your specs *** ## 2) Authentication & Login Visit the [login screen](https://app.corestory.ai/) to create a new account or access your existing account. CoreStory currently supports the following authentication methods: * Email and password * Login with Google *** ## 3) Uploading a Codebase To produce your first code intelligence model, select and upload a repository of your choosing by clicking the "+ Upload Codebase" button in the top-right corner of your dashboard. CoreStory currently supports the following upload methods: * ZIP upload up to 100MB * Public GitHub upload via URL * Private GitHub upload via GitHub authentication After you select a file for upload, CoreStory will scan it and inform you of the total expected file count and any excluded files. Proceed to initiate the creation of your intelligence model. Codebase analysis and intelligence model generation can take anywhere from 10 minutes to over an hour. Refer to the progress tracker on your dashboard for the latest status of your codebase upload. ## 4) Exploring Your Intelligence Model Following a successful upload, click on your project's name in the dashboard to start exploring your newly created intelligence model. Try the following steps to get a feel for what you can do with CoreStory. 1. **Chat with your code** to get instant insights about your codebase 2. Review your automatically generated **Core Documents** for an overview of your application, user stories, personas, data models, API specifications, and integration points. 3. Use **Workflows** to create custom artifacts that support project planning, feature development, application maintenance, modernization, migration, and more. 4. Configure [MCP integrations](/getting-started/mcp-server-setup) with other tools and start running [**CoreStory Playbooks**](https://corestory.ai/playbooks). You can export chat conversations and custom documents to Markdown or plain text files by clicking the Export button at the top of the Chat or Workflow interface. ## 5) See Your Impact Each time you complete a workflow or perform a time-saving task, CoreStory will track your time savings, value creation, and raw output in the Impact page. You can access the Impact page by entering a project, clicking your username in the bottom-left corner, and selecting "Impact". The more you use CoreStory, the more value you generate for yourself and your team. Track and share your impact with your teammates to identify best practices for your organization! *Note: CoreStory impact metrics are estimates based on industry-standard assumptions. Your specific time savings and generated value may not precisely align with CoreStory's estimates.* *** ## 6) Getting help **Questions about using CoreStory?** [Contact us](https://corestory.ai/contact). # MCP Server Setup Source: https://docs.corestory.ai/getting-started/mcp-server-setup Connect CoreStory to AI coding tools via the Model Context Protocol. ## What is the CoreStory MCP Server? The CoreStory MCP (Model Context Protocol) server enables AI coding assistants to directly access your CoreStory project data—including PRDs, technical specifications, codebase conversations, and project architecture—without manual copy-pasting or context switching. **What you can do with it:** * Query project documentation and requirements directly from your AI assistant * Access conversation history and codebase insights * Generate and retrieve PRD/TechSpec sections * Search a project's code index directly * Create and manage project conversations * Maintain context across multiple coding sessions **Supported AI Tools:** Claude Code, Claude Desktop, Cursor, Windsurf, VS Code (GitHub Copilot), and any other client that speaks remote MCP over HTTP. *** ## How Connecting Works Each CoreStory organization has its own MCP URL. You copy that URL into your AI client, and the first time the client connects, it opens your browser to sign in to CoreStory. There is no token to copy, paste, or store. ``` https://app.corestory.ai/mcp/{your-org-slug}-{org-id} ``` Two things to know about this URL: * **It is scoped to one organization.** The URL identifies the org, not you. Everyone in the org uses the same URL, and it never spans multiple orgs. To connect a different org, switch orgs using the org switcher and copy that org's URL. * **It is not a secret, but treat it as private anyway.** Access is granted by your browser sign-in, not by the URL. Someone who has the URL but no CoreStory account in that org cannot read anything. Sign-in is handled by CoreStory's identity provider (Clerk) at `clerk.corestory.ai` using standard OAuth. Your AI client receives a short-lived access token; **CoreStory never sees your password, and no long-lived credential is written to your config files.** Previously, connecting required generating a long-lived `mcp_...` token and pasting it into an `Authorization` header. That flow is deprecated. Existing tokens keep working until they expire — see [Legacy MCP Tokens](#legacy-mcp-tokens-deprecated). *** ## Prerequisites * A CoreStory account with access to your organization's workspace * At least one ingested project in that organization * One of the supported AI coding tools installed *** ## Step 1: Copy Your MCP URL 1. Go to [app.corestory.ai/settings](https://app.corestory.ai/settings) 2. Under **Organization Related**, open **IDE Integrations** 3. Confirm the org name shown above the section is the one you want to connect 4. Click **Copy** next to **Your MCP URL** The panel also has an **Add it to your client** tab strip with the exact config for Claude Code, Claude Desktop, Cursor, and Windsurf — pre-filled with your org's URL. The instructions below match those tabs. *** ## Step 2: Add It to Your Client ### Claude Code 1. **Add the server** — in your terminal, run: ```bash theme={null} claude mcp add --transport http corestory https://app.corestory.ai/mcp/your-org-slug-123456789 ``` Add `--scope user` to make the server available across all your projects rather than just the current one. 2. **Open Claude Code** and run `/mcp` 3. **Select `corestory` → Authenticate.** Your browser opens for sign-in. 4. **Approve access.** Claude Code is now connected. Run `/mcp` again at any time to check connection status or re-authenticate. *** ### Claude Desktop Remote MCP servers are added through the Claude Desktop UI, **not** through `claude_desktop_config.json`. 1. Open **Settings → Connectors** 2. Click **Add custom connector** 3. Paste your MCP URL. Leave **Advanced settings** blank. 4. Click **Add** — your browser opens for sign-in and consent. On Claude free plans, only one custom connector is allowed at a time. *** ### Cursor Create or edit `~/.cursor/mcp.json` (global) or `.cursor/mcp.json` (per project): ```json theme={null} { "mcpServers": { "corestory": { "url": "https://app.corestory.ai/mcp/your-org-slug-123456789" } } } ``` Save the file and restart Cursor. Cursor opens your browser to sign in on first use. No `headers` block is needed. If you are migrating from the token flow, delete the old `Authorization` header entirely — leaving it in place makes Cursor send the stale token instead of starting the browser sign-in. *** ### Windsurf Edit `~/.codeium/windsurf/mcp_config.json`, either directly or via **Cascade → Settings → MCP Servers**: ```json theme={null} { "mcpServers": { "corestory": { "serverUrl": "https://app.corestory.ai/mcp/your-org-slug-123456789" } } } ``` Windsurf uses `serverUrl` for remote servers, not `url`. Using `url` here will fail to connect. Save the file, then click **Refresh** in the MCP Servers panel. Windsurf opens your browser to sign in on first use. *** ### Other MCP Clients Any client with remote MCP + OAuth support connects the same way: give it your MCP URL as an HTTP (streamable) remote server, with no authorization header, and complete the browser sign-in it prompts for. This covers VS Code / GitHub Copilot's MCP support and similar clients. If your client can reach a remote MCP server but **cannot** perform the OAuth browser flow, it needs a legacy token instead — see below. *** ## Legacy MCP Tokens (Deprecated) Long-lived `mcp_{token_id}.{jwt}` tokens are deprecated. Prefer the URL + OAuth flow above. * **Existing tokens keep working until they expire.** Nothing breaks today. * **New token creation is discouraged.** Use it only for clients that cannot do the browser OAuth flow, or for headless/CI use. * **Manage tokens** under **Settings → IDE Integrations → Legacy tokens**, which lists each token's name, status, expiry, and last-used date, with a **Revoke** action. If you still need a token, send it as a bearer header against the same URL: ```json theme={null} { "mcpServers": { "corestory": { "url": "https://app.corestory.ai/mcp/your-org-slug-123456789", "headers": { "Authorization": "Bearer mcp_YOUR_TOKEN_HERE" } } } } ``` **Migrating off a token:** remove the `headers` block from your client config (or re-run `claude mcp add` without `--header`), reconnect, complete the browser sign-in, then revoke the old token in Settings. *** ## Available Tools Once connected, these tools are available to your AI assistant: | Tool | Description | | -------------------------------- | --------------------------------------------------------------------- | | `list_projects` | List all projects in your organization with their ingestion status | | `get_project_prd` | Retrieve a project's Product Requirements Document | | `get_project_techspec` | Retrieve a project's Technical Specification | | `list_conversations` | List all conversations for a project | | `get_conversation` | Get a conversation's details and message history | | `create_conversation` | Create a new conversation in a project | | `rename_conversation` | Rename an existing conversation | | `send_message` | Send a message to a conversation and get an AI response | | `refine_document_definition` | Build and validate a custom document definition | | `generate_document` | Start generation of a custom document | | `get_document_generation_result` | Poll a document generation run for results | | `semantic_search` | Semantic-search a project's code index and return ranked chunks | | `describe_index` | List the file paths and filterable metadata keys in a project's index | | `filter_chunks` | Fetch index chunks by metadata filter alone, with no semantic ranking | `get_project_prd` and `get_project_techspec` support `sections_only`, `sections`, `limit`, and `offset`. For large documents, discover the section list first and then request only the sections you need. **Your AI assistant can use these automatically when you ask questions about your CoreStory projects.** *** ## Testing Your Connection Ask your AI assistant: ``` Can you list my CoreStory projects? ``` The assistant should call `list_projects` and show the projects in your organization. `tools/list` is answered without authentication, so seeing the tool list is **not** proof that sign-in succeeded. Calling a tool is. If tools appear but every call fails, you are connected but not authenticated. *** ## Pairing CoreStory With Other MCP Servers Your coding agent can hold several MCP servers at once, and they compose well: each one contributes a different kind of context, and the agent decides which to consult. CoreStory contributes **code intelligence** — what the system does today and why. These servers do not talk to each other. Each connects independently to your agent, and the agent is what combines them. Adding a second server never gives it access to your CoreStory data. ### Evermuse [Evermuse](https://evermuse.com) is a customer intelligence platform — it collects and synthesizes what your customers are actually saying. Paired with CoreStory, an agent can answer questions that neither product can answer alone: *what customers are asking for* (Evermuse) checked against *what the code currently does* (CoreStory). Evermuse's MCP server uses OAuth 2.1 with no API key, so it connects the same way CoreStory does. **Evermuse MCP endpoint:** ``` https://api.evermuse.com/api/mcp ``` **Claude Code** — add both servers, then authenticate each via `/mcp`: ```bash theme={null} claude mcp add --transport http corestory https://app.corestory.ai/mcp/your-org-slug-123456789 claude mcp add --transport http evermuse https://api.evermuse.com/api/mcp ``` **Cursor** — both entries live in the same `~/.cursor/mcp.json`: ```json theme={null} { "mcpServers": { "corestory": { "url": "https://app.corestory.ai/mcp/your-org-slug-123456789" }, "evermuse": { "url": "https://api.evermuse.com/api/mcp" } } } ``` You will sign in twice — once to CoreStory, once to Evermuse — since each server authenticates against its own account. Once both are connected, you can ask things like: ``` Pull the top onboarding complaints from Evermuse, then use CoreStory to show me which parts of the signup flow those complaints touch. ``` For current Evermuse setup steps — including Claude Desktop, ChatGPT, and Codex — see Evermuse's own [MCP integration page](https://app.evermuse.com/dashboard/mcp). Their configuration is theirs to change; treat that page as the source of truth for the Evermuse side. *** ## Troubleshooting ### "Missing or invalid Authorization header" You are reaching the server but have not signed in. 1. In Claude Code, run `/mcp`, select `corestory`, and choose **Authenticate** 2. In other clients, remove and re-add the server to re-trigger the browser flow 3. Check that no stale `Authorization` header is left in your config — it suppresses the OAuth flow 4. Complete the browser consent screen; closing it early leaves the client unauthenticated *** ### The Browser Never Opens 1. Confirm your client supports remote MCP with OAuth, and that it is up to date 2. Check the client's MCP logs for a sign-in URL you can open manually 3. If the client genuinely cannot do the browser flow, use a legacy token instead *** ### Connected, But No Projects Listed 1. Verify the URL is for the org you expect — the slug in the URL is the org 2. Confirm that org actually has ingested projects 3. If you belong to multiple orgs, switch orgs in the app and copy that org's URL *** ### Tools Not Available At All 1. Restart your AI tool completely 2. Verify the server appears in the tool's connected-servers list 3. Check your configuration file is valid JSON — and that Windsurf uses `serverUrl`, not `url` 4. Look for errors in the tool's developer console or MCP logs *** ### Slow or Timeout Responses 1. For large PRDs/TechSpecs, request specific sections rather than the whole document 2. `generate_document` is long-running — submit it, then poll `get_document_generation_result` 3. Increase timeout settings in your AI tool if it allows it *** ## Security Notes 1. **No credentials in config files** — the OAuth flow stores a short-lived token in your client's own credential store, not in the JSON you commit 2. **Access follows your account** — losing access to the org immediately ends MCP access; there is no lingering token to revoke 3. **Revoke legacy tokens you no longer use** — Settings → IDE Integrations → Legacy tokens 4. **One org per connection** — if you need two orgs, add two servers under different names *** ## Support * **CoreStory Documentation:** [https://docs.corestory.ai](https://docs.corestory.ai) * **MCP Protocol Spec:** [https://modelcontextprotocol.io](https://modelcontextprotocol.io) * **Support Email:** [support@corestory.ai](mailto:support@corestory.ai) *Last Updated: August 2026* # Supercharging AI Agents with CoreStory Source: https://docs.corestory.ai/getting-started/supercharging-ai-agents How CoreStory's persistent code intelligence makes AI coding agents dramatically more effective across your development workflow. ## Overview AI coding agents are only as good as the context they have. Without architectural understanding, they guess — reinventing existing services, violating naming conventions, breaking invariants they didn't know existed. The result is code that works in isolation but doesn't fit the system. CoreStory eliminates this problem by giving your AI agent access to **code intelligence** — synthesized knowledge about how your system actually works, drawn from PRDs, technical specifications, user stories, code history, and architecture analysis. The agent queries this intelligence through MCP (Model Context Protocol) to understand the system *before* writing code, not after. This guide shows you how to connect CoreStory to your AI coding agent, verify the connection, and start using code intelligence in your development workflows. For specific workflow playbooks (bug resolution, feature implementation, spec-driven development), see the links in the Use Cases section. ### What CoreStory Gives Your Agent CoreStory serves two roles in every workflow: * **Expert** — answers questions about intended system behavior, invariants, business rules, architectural patterns, and design history. This is context synthesized from your entire codebase — not just file contents, but the *meaning* behind them. * **Navigator** — points to specific files, methods, extension points, and code paths relevant to a task. Instead of grep-wandering through a codebase, the agent gets directed guidance. Together, these roles let the agent operate like a senior engineer who's been on the team for years — understanding not just what the code does, but *why* it does it that way. *** ## Prerequisites * A **CoreStory account** with at least one project that has completed ingestion * An **AI coding agent** that supports MCP (see Supported Agents below) * A **code repository** the agent can read and write to *** ## Quick Start ### Step 1: Copy Your MCP URL 1. Go to **Settings** in the [CoreStory Dashboard](https://app.corestory.ai/settings) 2. Under **Organization Related**, open **IDE Integrations** 3. Click **Copy** next to **Your MCP URL** The URL is scoped to one organization and looks like this: ``` https://app.corestory.ai/mcp/{your-org-slug}-{org-id} ``` ### Step 2: Configure Your Agent Add that URL to your agent as an HTTP (streamable) remote MCP server, with **no authorization header**. The first time the agent connects, it opens your browser to sign in to CoreStory — there is no token to copy or store. For per-client instructions, see the [MCP Server Setup guide](/getting-started/mcp-server-setup). The Supported Agents section below covers what is specific to *agentic* workflows. ### Step 3: Verify the Connection Ask your agent: ``` List my CoreStory projects. ``` If it returns your projects, the MCP connection is working. If not, check the Troubleshooting section. ### Step 4: Verify Project Readiness Before starting any task, confirm your project has completed ingestion: ``` List my CoreStory projects. Which ones are ready to use? ``` Your agent will call `list_projects` and return project details including status. Confirm the project you want to work with is ready before proceeding. *** ## CoreStory MCP Tools Once connected, these tools are available to your AI assistant: | Tool | Description | | -------------------------------- | --------------------------------------------------------------------- | | `list_projects` | List all projects in your organization with their ingestion status | | `get_project_prd` | Retrieve a project's Product Requirements Document | | `get_project_techspec` | Retrieve a project's Technical Specification | | `list_conversations` | List all conversations for a project | | `get_conversation` | Get a conversation's details and message history | | `create_conversation` | Create a new conversation in a project | | `rename_conversation` | Rename an existing conversation | | `send_message` | Send a message to a conversation and get an AI response | | `refine_document_definition` | Build and validate a custom document definition | | `generate_document` | Start generation of a custom document | | `get_document_generation_result` | Poll a document generation run for results | | `semantic_search` | Semantic-search a project's code index and return ranked chunks | | `describe_index` | List the file paths and filterable metadata keys in a project's index | | `filter_chunks` | Fetch index chunks by metadata filter alone, with no semantic ranking | ### The Core Interaction Pattern Most CoreStory workflows follow this pattern: 1. **Select project** — `list_projects` → confirm the right project 2. **Create conversation** — `create_conversation` with a descriptive title 3. **Query the Expert** — `send_message` to understand system behavior, invariants, and architecture 4. **Query the Navigator** — `send_message` to find specific files, methods, and extension points 5. **Act on the knowledge** — implement, test, or document based on what CoreStory revealed 6. **Close the loop** — `rename_conversation` to mark the thread as resolved The conversation persists as institutional knowledge — future queries in the same thread benefit from accumulated context. *** ## Use Cases CoreStory's code intelligence powers a range of development workflows. Each has a dedicated playbook with step-by-step implementation guidance: | Use Case | Description | Playbook | | -------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------- | | **Bug Resolution** | Diagnose and fix bugs with full architectural context. The agent queries CoreStory to understand how the system *should* work, generates root cause hypotheses, writes a failing test, and implements a minimal fix. | [Agentic Bug Resolution](/playbooks/agentic-bug-resolution) | | **Feature Implementation** | Implement features from tickets using CoreStory to understand existing patterns, data structures, and integration points. TDD workflow with continuous architectural validation. | [Feature Implementation](/playbooks/feature-implementation) | | **Spec-Driven Development** | Write architecture-grounded specifications before implementation. CoreStory provides the architectural truth that standalone SDD tools can't — ensuring specs describe delta changes constrained by what actually exists. | [Spec-Driven Development](/playbooks/spec-driven-development) | | **Test Generation** | Derive comprehensive test suites from CoreStory specifications — behavioral tests, E2E journey tests, edge cases, error contracts, and authorization matrices. | [Spec-Driven Test Generation](/playbooks/spec-driven-test-generation) | | **M\&A Technical Due Diligence** | Analyze acquisition targets using CoreStory to understand architecture, identify risks, assess technical debt, and evaluate integration complexity. | [M\&A Due Diligence](/playbooks/ma-technical-due-diligence) | ### Additional Use Cases These workflows don't have dedicated playbooks but follow the same Expert → Navigator pattern: * **Spec/Code Gap Analysis** — identify discrepancies between CoreStory specifications and actual implementation, then remediate * **Architecture Comprehension** — understand component boundaries, data flows, and integration points for refactoring or onboarding * **API Contract Validation** — extract API contracts from specs, validate against code, and generate contract tests * **Security Baseline Review** — audit error handling, validation, and idempotency against spec security sections * **Developer Onboarding Documentation** — generate onboarding guides by cross-referencing CoreStory specs with source code * **Release Notes Generation** — analyze feature changes and generate release notes keyed to business rules and endpoints *** ## Supported Agents & Configuration CoreStory works with any MCP-capable AI coding agent. The connection itself is the same everywhere — point the agent at your MCP URL with no authorization header and complete the browser sign-in. Per-client connection steps live in the [MCP Server Setup guide](/getting-started/mcp-server-setup) so there is one place to keep current. This section covers the part that differs per agent: **where each one expects workflow files to live.** Each workflow playbook ships a ready-to-use SKILL.md. Install it where your harness looks for it: The skill file shown below is plain markdown. The workflow it encodes works in any agentic harness — only the install location differs. Common conventions: | Harness | Install location | | --------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Claude Code** | `.claude/skills//SKILL.md` — Claude loads the body when the YAML `description` matches the task | | **GitHub Copilot** | Append to `.github/copilot-instructions.md` for repo-wide instructions, or save as `.github/instructions/.instructions.md` with an `applyTo` glob for path-scoped use | | **Cursor** | `.cursor/rules/.mdc` with a `description` field for auto-attach (use `globs` for path-scoped or `alwaysApply: true` for every session) | | **Factory.ai** | `.factory/droids/.md` (project) or `~/.factory/droids/.md` (personal); Factory loads it as a custom Droid | | **Aider** | `CONVENTIONS.md` at repo root, loaded with `aider --read CONVENTIONS.md` — or add it to the `read:` list in `.aider.conf.yml` for automatic loading | | **Codex / `AGENTS.md` harnesses** | Append the content to `AGENTS.md` at your repository root | | **Custom runtime** | Load the markdown into your agent's system prompt, rules file, or wherever it consumes workflow context | Want a single install that works across the most harnesses? Append the content to `AGENTS.md` at your repository root. The [`AGENTS.md` spec](https://agents.md/) 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. ### Verifying the Connection | Agent | How to verify | | --------------------------------- | ------------------------------------------------------------------------------------ | | **Claude Code** | Run `/mcp` to confirm `corestory` is connected and authenticated | | **GitHub Copilot (VS Code)** | Open Copilot Chat → **Agent** mode → tools icon → confirm CoreStory tools appear | | **Cursor** | Open the AI pane → **Agent** mode → confirm CoreStory tools appear in the tools list | | **Factory.ai / Devin / Windsurf** | Ask the agent: "List my CoreStory projects" | Most clients list a server's tools *before* sign-in completes, because `tools/list` does not require authentication. Seeing CoreStory tools is not proof you are authenticated — calling one is. If tools appear but every call fails with an authorization error, finish the browser sign-in. *** ## Best Practices ### Effective CoreStory Queries The quality of CoreStory's responses depends on the specificity of your queries. **Be specific, not broad:** | Instead of | Try | | -------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | "Tell me about the order system" | "What is the validation logic for order placement? What fields are required, what are the business rules for minimum amounts, and how is stock validation handled?" | | "How does authentication work?" | "What is the session timeout configuration? How are JWT tokens validated, and what happens when a token expires during an active request?" | | "Tell me about the API" | "What are the error response formats for the payment endpoints? Do they follow RFC-7807? What HTTP status codes map to which error conditions?" | **Use specific variable names and code references** when you have them — CoreStory can resolve references to actual files and methods in the codebase. ### Expert Before Navigator Always query for *understanding* before querying for *location*. The Expert phase (how does this work? what are the invariants?) should come before the Navigator phase (which files do I need to change?). This prevents the agent from diving into code changes before understanding the system's constraints. ### Conversation Hygiene * **One conversation per task.** Create a conversation with a descriptive title like "Bug Fix: #1234 — Payment retry failing on 503 errors" or "Feature: #412 — Webhook notification system." * **Reuse conversations** for follow-up queries on the same task. The conversation accumulates context that improves subsequent responses. * **Rename when done.** Mark completed conversations with a prefix like "✅ Resolved:" so future users can find institutional knowledge. ### Cost Control * **Retrieve before regenerating.** Use `get_project_prd` and `get_project_techspec` to check if documents already exist before asking the agent to generate new content. * **Reuse conversations** instead of creating new ones for related queries — conversation context reduces the need for repeated background queries. * **Batch queries.** Plan your questions in advance and ask comprehensive questions instead of many small ones. ### Security * **Prefer the browser sign-in over tokens.** OAuth stores a short-lived credential in your agent's own credential store, so nothing sensitive lands in the config files you commit. * **Share the MCP URL, not credentials.** A project-scoped config file can safely contain the URL — each teammate signs in as themselves and sees only what their CoreStory account allows. * **Revoke leftover legacy tokens** in **Settings → IDE Integrations → Legacy tokens** once you have migrated. * **Review generated content** for sensitive data before committing to public repositories. *** ## Troubleshooting ### Agent Can't See CoreStory Tools **Symptoms:** Agent doesn't list CoreStory tools, can't access CoreStory resources, or errors about missing MCP server. **Solutions:** 1. Verify the MCP server appears in your agent's server list (e.g., `claude mcp list` for Claude Code, or the tools panel in VS Code/Cursor) 2. Confirm you completed the browser sign-in — in Claude Code, run `/mcp`, select `corestory`, and choose **Authenticate** 3. Verify the URL matches the one in **Settings → IDE Integrations** exactly, including the org slug 4. Check that no stale `Authorization` header is left over from the deprecated token flow — it suppresses the browser sign-in 5. Restart your agent after configuration changes 6. Ask the agent to list available MCP servers and tools as a diagnostic ### Project Not Found or Ingestion Incomplete **Symptoms:** `list_projects` returns empty, or queries return incomplete/stale data. **Solutions:** 1. Verify you have access to the project in the CoreStory dashboard 2. Check ingestion status — projects must show "completed" or "ready" before querying 3. If ingestion appears stuck, contact CoreStory support 4. Don't proceed with heavy queries until ingestion is complete ### Slow or Rate-Limited Responses **Symptoms:** Slow responses, timeouts, or rate-limiting errors. **Solutions:** 1. Reduce query frequency — batch related questions into single, comprehensive queries 2. Reuse conversations instead of creating new ones 3. Retrieve existing documents instead of regenerating 4. Use incremental section generation instead of full document generation ### Agent Times Out on Long Tasks **Symptoms:** Agent sessions end before completing multi-step workflows. **Solutions:** 1. Break large tasks into milestones — have the agent commit after each phase 2. Use the conversation ID to resume context in a new session 3. For agents with session limits (e.g., Devin ACU limits), prioritize the Expert and Navigator phases first, then implement in a separate session *** ## What's Next Once you've verified your CoreStory connection, pick a workflow and follow its playbook: * **First time?** Start with [Bug Resolution](/playbooks/agentic-bug-resolution) — it's the most concrete workflow and demonstrates the Expert → Navigator → Implement pattern clearly. * **Building something new?** Use [Spec-Driven Development](/playbooks/spec-driven-development) to ground your specification in the real architecture before implementation. * **Working from tickets?** [Feature Implementation](/playbooks/feature-implementation) covers the full ticket-to-merge workflow with TDD and continuous architectural validation. Each playbook includes agent-specific configuration files (skills, instructions, rules, droids) that encode the workflow so your agent follows it automatically. # CoreStory Documentation Source: https://docs.corestory.ai/index CoreStory is a code intelligence platform that uses AI to reverse-engineer specifications from source code. Explore guides, playbooks, and integrations to make any codebase queryable by humans and AI agents. **CoreStory turns your source code into a queryable specification.** It creates a persistent intelligence layer over your codebase — architecture, business rules, data flows, dependencies — that humans and AI agents can both query. The result: faster onboarding, grounded AI development, de-risked modernization, and audit-ready specifications for any system. ## Start Here A platform overview — what CoreStory does and why it matters. Create an account, upload your first codebase, and start querying. Connect Claude, Cursor, Copilot, Devin, and other agents to CoreStory via MCP. Step-by-step configuration for the CoreStory MCP server. ## Playbooks Structured, end-to-end workflows for the work software teams keep getting stuck on. Each playbook combines CoreStory's persistent code intelligence with AI agents and proven engineering methodology. Phased methodology for modernizing legacy systems. Diagnose and fix bugs with AI agents grounded in your code. Implement features with AI agents that understand your system. Generate grounded specs before changing code. Evaluate acquisition targets' codebases for risk and debt. Catalog and verify business rules embedded in code. Generate behavioral and end-to-end tests from your codebase. Push migration work packages into Jira as epics and stories. Compare two systems' capabilities — useful for SaaS migrations. ## Product Natural language queries over your entire codebase, grounded in CoreStory's persistent intelligence. Executive summaries, user stories, data models, API specs, and integration maps — auto-generated from source code. ## Who It's For CoreStory serves developers, architects, product managers, and business stakeholders working with complex or legacy codebases. [See the full breakdown by role and use case →](/about/who-is-corestory-for) # Agentic Bug Resolution Source: https://docs.corestory.ai/playbooks/agentic-bug-resolution Use CoreStory's persistent code intelligence to diagnose and fix bugs faster with AI agents grounded in your actual architecture. ## Overview This playbook teaches you to resolve bugs systematically using an AI coding agent connected to CoreStory's code intelligence via MCP. Instead of grep-wandering through a codebase, the agent queries CoreStory to understand how the system *should* work, generates hypotheses about what went wrong, writes a failing test to confirm the bug, and implements a minimal fix — all with architectural context that would normally require senior-engineer-level familiarity with the code. CoreStory serves two roles in this workflow: * **Expert** — answers questions about intended system behavior, invariants, business rules, and design history. This is context you can't get from code search alone; it synthesizes PRDs, technical specs, user stories, and code history into coherent answers. * **Navigator** — points to specific files, methods, and code paths relevant to a bug. Instead of blind searching, the agent gets directed guidance on where to look. **When to use this:** Any bug that benefits from architectural understanding — which is most of them. Especially valuable for unfamiliar codebases, cross-component issues, bugs in complex state management, and onboarding new team members who need to fix things in code they've never seen. **When to skip this:** Trivial typos, documentation-only changes, dependency bumps without behavior changes, or emergency hotfixes where speed matters more than comprehensiveness. (For hotfixes, consider running the full workflow as a retrospective.) *** ## Prerequisites **Required:** * A CoreStory account with at least one project that has completed ingestion * The CoreStory MCP server installed and configured in your AI agent * A code repository the agent can read and write to **Recommended:** * A ticketing system MCP (GitHub Issues, Jira, Azure DevOps, or Linear) so the agent can fetch ticket details and post updates automatically * Agent-specific configuration files (skill files, custom instructions, project rules) — covered in the Agent Implementation Guides section below **Verify your setup:** Ask your agent to "List my CoreStory projects." If it returns your projects, the MCP connection is working. *** ## How It Works ### The Six-Phase Workflow The workflow has six phases. The first three gather context; the last three act on it. **Phase 1 — Bug Intake.** The agent pulls the bug ticket (or accepts a description), selects the relevant CoreStory project, and creates a dedicated investigation conversation. This conversation persists as institutional knowledge. **Phase 2 — Expert Phase.** The agent queries CoreStory to understand how the system is *supposed* to work: which files implement the affected feature, what data structures and invariants are involved, and what design history exists. This happens *before* looking at code. **Phase 3 — Navigator Phase.** The agent asks CoreStory to map the bug's symptoms to specific code paths, generate ranked root cause hypotheses, and identify exact files and methods to investigate. **Phase 4 — Test-First Investigation.** The agent writes a failing test that reproduces the bug *before* reading any implementation code. It validates the test with CoreStory, then reads the identified code to pinpoint the root cause. **Phase 5 — Solution Development.** The agent implements a minimal fix, verifies the test passes, validates the fix with CoreStory against architectural constraints, adds edge case tests, and runs the full test suite. **Phase 6 — Completion.** The agent updates the ticket, commits with a structured message explaining the root cause and fix rationale, renames the CoreStory conversation to mark it resolved, and reports results. ### CoreStory MCP Tools Used | Tool | Purpose | | -------------------------------- | -------------------------------------- | | `CoreStory:list_projects` | Find available projects | | `CoreStory:get_project` | Verify project status and details | | `CoreStory:get_project_stats` | Check ingestion/processing status | | `CoreStory:create_conversation` | Start a dedicated investigation thread | | `CoreStory:send_message` | Query code intelligence (streaming) | | `CoreStory:get_conversation` | Retrieve conversation history | | `CoreStory:rename_conversation` | Mark conversation as resolved | | `CoreStory:get_project_prd` | Access PRD for requirements context | | `CoreStory:get_project_techspec` | Access technical specifications | ### Ticketing MCP Integrations (Optional) The agent can fetch ticket details and post updates automatically if you configure a ticketing MCP server. Each platform now offers an official MCP server — check their documentation for current setup instructions: | System | Official MCP Server | Sample Prompt | | ------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------- | | GitHub Issues | [GitHub MCP Server](https://github.com/github/github-mcp-server) | "Fetch GitHub issue #6992 from pydata/xarray" | | Jira | [Atlassian Rovo MCP Server](https://www.atlassian.com/platform/remote-mcp-server) — see our [Jira Integration playbook](/playbooks/using-corestory-with-jira) for setup | "Fetch Jira ticket PROJ-1234" | | Azure DevOps | [Azure DevOps MCP Server](https://github.com/microsoft/azure-devops-mcp) | "Get work item 12345 from Azure DevOps" | | Linear | [Linear MCP Server](https://linear.app/docs/mcp) | "Retrieve Linear issue ENG-456" | *** ## Step-by-Step Walkthrough This section is agent-agnostic. The prompts work with any MCP-connected agent. Agent-specific configuration is in the Implementation Guides below. ### Phase 1: Bug Intake & Context Gathering **Goal:** Import bug details and prepare the investigation environment. **Step 1 — Pull the bug ticket.** If you have a ticket ID, ask the agent to fetch it: ``` Fetch GitHub issue #6992 from pydata/xarray and extract the bug details. ``` If describing the bug directly, provide: symptoms, reproduction steps, expected vs. actual behavior, and the affected component. **Step 2 — Select the CoreStory project.** The agent lists available projects and picks the one matching your repository: ``` List my CoreStory projects and select the one for xarray. ``` If there's only one project, the agent auto-selects. It should verify ingestion status is "completed" before proceeding. **Step 3 — Create an investigation conversation.** This is the persistent thread where all CoreStory queries for this bug will live: ``` Create a CoreStory conversation titled "Bug Investigation: #6992 - reset_index coord_names issue" ``` The agent stores the `conversation_id` and uses it for all subsequent queries. This conversation becomes searchable institutional knowledge — future engineers investigating similar bugs can reference it. *** ### Phase 2: Understanding System Behavior (Expert Phase) **Goal:** Establish ground truth about how the system *should* work before investigating what's wrong. This phase is the key differentiator. Without it, you risk fixing symptoms instead of root causes, breaking adjacent functionality, or missing architectural constraints that explain why the code works the way it does. **Query 1 — Architecture Discovery:** ``` Send CoreStory message: "What files are responsible for the reset_index functionality for Dataset objects? I need to understand: 1. Primary implementation files 2. Test coverage 3. Helper/utility modules 4. Integration points with other components" ``` CoreStory responds with file names, test files, related modules, architectural patterns, and recent PRs. This is your map of the territory. **Query 2 — Invariants & Data Structures:** ``` Send CoreStory message: "In the reset_index method for Dataset, what are the key data structures involved? Specifically: 1. What is _coord_names and what does it contain? 2. What is _variables and what does it contain? 3. What is the relationship between _coord_names and _variables? 4. When reset_index is called with drop=True vs drop=False, how should these data structures be updated?" ``` The critical output here is **invariants** — conditions that must always be true (e.g., "coord\_names ⊆ variables.keys()"). These become the assertions in your tests. **Query 3 — Historical Context:** ``` Send CoreStory message: "Have there been recent changes to the reset_index functionality? What was the original design intent? Are there related issues?" ``` CoreStory synthesizes PRD context, PR history, user stories, and known edge cases — the kind of context that normally lives only in the heads of long-tenured engineers. *** ### Phase 3: Hypothesis Generation (Navigator Phase) **Goal:** Translate symptoms into specific, actionable investigation targets. **Query 1 — Map symptoms to code paths:** ``` Send CoreStory message: "If there's a bug where reset_index with drop=True leaves stale coordinate names in _coord_names, what are the specific code paths I should investigate? Walk me through the logic flow." ``` **Query 2 — Root cause candidates:** ``` Send CoreStory message: "Based on the symptom that _coord_names contains stale entries after drop=True, what are the most likely root causes? Is this a missing cleanup operation, incorrect state update, or something else? Rank by probability." ``` **Query 3 — Precise navigation:** ``` Send CoreStory message: "In dataset.py, where is the _coord_names update logic during reset_index? Which methods should I examine?" ``` At this point the agent has a ranked list of hypotheses, specific files and methods to check, and a clear understanding of what "correct" looks like. This replaces hours of code archaeology. *** ### Phase 4: Test-First Investigation **Goal:** Write a failing test before reading implementation code. This is non-negotiable. **Why test-first for bugs?** A failing test proves the bug exists, a passing test proves it's fixed, and the test prevents the bug from recurring. It also forces the agent to articulate what "correct behavior" means before getting lost in implementation details. **Step 1 — Write a reproduction test.** Based on the expected behavior (Phase 2) and symptoms (Phase 1): ```python theme={null} def test_reset_index_drop_removes_coord_names(): """Test that reset_index(drop=True) removes coordinate names. Bug: GH#6992 - _coord_names retains stale entries after drop=True Expected: coord_names should only contain coordinates still in _variables Invariant: coord_names ⊆ variables.keys() """ # Setup: Create Dataset with multi-index ds = Dataset({ 'data': ('x', [1, 2, 3]), 'level_1': ('x', ['a', 'b', 'c']), 'level_2': ('x', [10, 20, 30]) }) ds = ds.set_index(x=['level_1', 'level_2']) # Action: Reset index with drop=True result = ds.reset_index('x', drop=True) # Assert: Coordinate names should be cleaned up assert 'level_1' not in result._coord_names assert 'level_2' not in result._coord_names assert result._coord_names.issubset(result._variables.keys()) ``` **Step 2 — Verify the test fails.** Run it and confirm the failure matches the reported symptom. If the test passes, the bug doesn't exist in this form — go back to Phase 2 for clarification. **Step 3 — Validate the test with CoreStory:** ``` Send CoreStory message: "I've written this test to reproduce the bug: [paste test code] Does this correctly test the expected behavior according to the system design? Are there edge cases I'm missing?" ``` Update the test if CoreStory identifies gaps. **Step 4 — Now read the code.** Only now does the agent read the implementation files identified in Phase 3. It knows what to look for: state update logic, invariant maintenance, the specific methods CoreStory pointed to. **Step 5 — Identify the bug.** Compare actual code against expected behavior. Look for missing state updates, incorrect logic, missing validations, or invariant violations. **Step 6 — Validate the finding with CoreStory:** ``` Send CoreStory message: "Looking at line 4180 in dataset.py: coord_names = set(new_variables) | self._coord_names This only ADDS to coord_names but doesn't REMOVE dropped coordinates. Should this instead be: coord_names = (self._coord_names - set(drop_indexes)) | set(new_variables) So we remove the dropped index names before adding new ones?" ``` Wait for CoreStory's confirmation before implementing the fix. *** ### Phase 5: Solution Development **Goal:** Implement a minimal fix, verify it, and add comprehensive test coverage. **Step 1 — Implement the minimal fix.** The smallest change that restores the invariant, following architectural patterns CoreStory described. **Step 2 — Verify the test passes.** Run the reproduction test from Phase 4. If it still fails, the fix is incomplete. **Step 3 — Validate with CoreStory:** ``` Send CoreStory message: "I've implemented this fix: [describe change]. Does this align with the system architecture? Could it have unintended side effects? Does it maintain all invariants?" ``` **Step 4 — Add edge case tests.** Ask CoreStory for scenarios: ``` Send CoreStory message: "My basic test passes. What edge cases should I test? Are there scenarios where reset_index behavior gets more complex?" ``` Common edge cases: partial operations, empty inputs, boundary conditions, different parameter combinations, concurrent access. **Step 5 — Run the full test suite.** Ensure no regressions. If existing tests break, the fix has side effects — revise the approach. *** ### Phase 6: Completion & Knowledge Capture **Goal:** Close the loop and preserve knowledge. **Step 1 — Update the ticket** (if ticketing MCP is configured). Add investigation summary, root cause, fix description, and commit link. **Step 2 — Commit with structured context:** ``` Fix: reset_index(drop=True) leaves stale coord_names Problem: After calling reset_index with drop=True on a multi-index Dataset, _coord_names retains entries for dropped coordinates. Root Cause: Line 4180 in dataset.py only adds new_variables to coord_names but never removes dropped coordinates, violating the invariant coord_names ⊆ variables.keys(). Solution: Subtract drop_indexes from coord_names before adding new_variables. Invariants Restored: - coord_names ⊆ variables.keys() Testing: - Added test_reset_index_drop_removes_coord_names - Added 3 edge case tests (partial multi-index, single-level, with attrs) - All existing tests pass (no regressions) References: - Issue: #6992 - CoreStory Investigation: [conversation-id] ``` **Step 3 — Rename the CoreStory conversation** to mark it resolved: ``` Rename to: "Bug Investigation: #6992 - RESOLVED - reset_index coord_names cleanup" ``` This preserved conversation becomes a searchable resource for similar future bugs. *** ## Prompting Patterns Reference These patterns work with any MCP-connected agent querying CoreStory. ### Investigation Patterns **Architecture Discovery:** ``` What files are responsible for [feature]? I need to understand primary implementation files, test coverage, helper modules, and integration points. ``` **Invariant Understanding:** ``` What invariants should [data structure] maintain? What relationships must hold between [A] and [B]? What are the pre/post conditions for [operation]? ``` **Logic Flow Tracing:** ``` Walk me through the execution flow of [operation] from entry point to exit: key decision points, state transformations, error handling paths. ``` **Root Cause Hypothesis:** ``` Given [symptom], what are the most likely root causes? For each: explain why it could cause the symptom, rate probability, and point to specific code locations to investigate. ``` ### Validation Patterns **Fix Validation:** ``` I'm proposing this fix: [describe change]. Does this align with system architecture? Does it maintain all invariants? Could it have unintended side effects? ``` **Test Coverage Check:** ``` What existing tests cover [feature]? Are there gaps? What edge cases should I test? ``` ### Context Patterns **Historical Context:** ``` What changes have been made to [feature] recently? Related PRs, design decisions, known limitations, evolution over time. ``` **Requirements Tracing:** ``` What user stories/requirements exist for [feature]? Acceptance criteria, business rules, security requirements. ``` **Integration Impact:** ``` What other components depend on [feature]? Direct callers, integration points, downstream impacts of changing [behavior]. ``` ### Efficient Multi-Query Pattern When you want comprehensive context in one shot: ``` I'm investigating a bug where [symptom]. Please answer: Architecture: What files implement [feature]? Key data structures? Expected Behavior: What invariants should hold? What should happen when [operation] is called with [parameters]? Code Paths: Walk me through the execution flow. Where could the bug be? Testing: What existing tests cover this? What tests should I add? ``` *** ## Advanced Patterns ### Security-Sensitive Bugs When the bug involves authentication, authorization, data handling, or external input, add a security check to Phase 2: ``` Send CoreStory message: "What security considerations apply to [feature]? Are there security requirements I should verify? Could this bug have security implications?" ``` Include security validation assertions in your tests. ### Integration Impact Analysis When the bug is in a shared component, check downstream effects in Phase 3: ``` Send CoreStory message: "What other systems or components integrate with [feature]? What downstream impacts should I consider if I change [behavior]?" ``` Add integration tests for dependent components. ### Performance Bugs When investigating slowness, timeouts, or resource issues: ``` Send CoreStory message: "What are the performance characteristics of [feature]? Expected complexity? Known bottlenecks?" ``` Add performance regression tests with timing assertions. ### Related Bug Clusters When multiple tickets look related: ``` Send CoreStory message: "I'm investigating [bug A], [bug B], and [bug C] which seem related. Are there common patterns or root causes? Could they stem from the same underlying issue?" ``` Consider a unified fix if appropriate. Create separate CoreStory conversations for each but cross-reference them. *** ## 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: | Harness | Install location | | --------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Claude Code** | `.claude/skills//SKILL.md` — Claude loads the body when the YAML `description` matches the task | | **GitHub Copilot** | Append to `.github/copilot-instructions.md` for repo-wide instructions, or save as `.github/instructions/.instructions.md` with an `applyTo` glob for path-scoped use | | **Cursor** | `.cursor/rules/.mdc` with a `description` field for auto-attach (use `globs` for path-scoped or `alwaysApply: true` for every session) | | **Factory.ai** | `.factory/droids/.md` (project) or `~/.factory/droids/.md` (personal); Factory loads it as a custom Droid | | **Aider** | `CONVENTIONS.md` at repo root, loaded with `aider --read CONVENTIONS.md` — or add it to the `read:` list in `.aider.conf.yml` for automatic loading | | **Codex / `AGENTS.md` harnesses** | Append the content to `AGENTS.md` at your repository root | | **Custom runtime** | Load the markdown into your agent's system prompt, rules file, or wherever it consumes workflow context | Want a single install that works across the most harnesses? Append the content to `AGENTS.md` at your repository root. The [`AGENTS.md` spec](https://agents.md/) 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, slash command, version control) 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. **Configure the CoreStory MCP server** in your Claude Code settings (see [CoreStory MCP Server Setup Guide](/getting-started/mcp-server-setup)). 2. **Add the skill file.** Claude Code uses skills (`.claude/skills/` directory) as its preferred mechanism for teaching Claude specialized workflows. Create the skill: ```bash theme={null} mkdir -p .claude/skills/bug-resolver ``` Create `.claude/skills/bug-resolver/SKILL.md` with the content from the skill file below. 3. **(Optional) Add the slash command.** Slash commands provide a shortcut to invoke the workflow: ```bash theme={null} mkdir -p .claude/commands ``` Create `.claude/commands/fix-bug.md` with the content from the command file below. 4. **Commit to version control** for team sharing: ```bash theme={null} git add .claude/skills/ .claude/commands/ git commit -m "Add CoreStory bug resolution skill and command" ``` #### Usage The skill activates automatically when Claude Code detects bug-related requests: ``` Fix bug #6992 Investigate issue JIRA-1234 Debug the login problem ``` Or invoke explicitly: ``` /fix-bug #6992 /fix-bug JIRA-1234 /fix-bug "Users can't login after password reset" ``` #### 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. * The skill file includes structured output templates so Claude reports progress at each phase. #### Skill File Save as `.claude/skills/bug-resolver/SKILL.md`: ````markdown theme={null} --- name: CoreStory Bug Resolver description: Resolves bugs using CoreStory's code intelligence and TDD methodology. Activates on bug fix requests or ticket IDs. --- # CoreStory Bug Resolver When this skill activates, execute the six-phase bug resolution workflow. **If you do not detect that you have access to CoreStory (e.g., `list_projects` fails or is unavailable), ask the user to verify that their MCP or API connection is properly configured and that this repository has been ingested. If the user has not yet created a CoreStory account, direct them to create one and upload their repo at [app.corestory.ai](https://app.corestory.ai).** ## Activation Triggers Activate when user requests: - Bug fix or investigation - Ticket resolution (e.g., "Fix bug #6992", "Investigate JIRA-123") - Any request containing "bug", "issue", "broken", "not working" ## Prerequisites - CoreStory MCP server configured - At least one CoreStory project with completed ingestion - (Optional) Ticketing system MCP (GitHub Issues, Jira, ADO, Linear) ## Phase 1: Bug Intake & Context Gathering 1. **Extract Bug Information** - If ticket ID provided: fetch via appropriate MCP, parse symptoms, reproduction steps, expected/actual behavior - If described directly: extract from user message, ask for missing details 2. **Select CoreStory Project** ``` Use CoreStory MCP: list_projects ``` - Multiple projects → ask user which one - Single project → auto-select - Verify status is "completed" 3. **Create Investigation Conversation** ``` Use CoreStory MCP: create_conversation Title: "Bug Investigation: #[ID] - [brief description]" ``` Store conversation_id for all subsequent queries. **Report:** ``` Starting bug investigation for [ticket-id] Bug: [description] Symptoms: [what's broken] Expected: [correct behavior] CoreStory conversation: [conversation-id] ``` ## Phase 2: Understanding System Behavior (Expert Phase) Send three CoreStory queries in sequence: **Query 1 — Architecture Discovery:** ``` What files are responsible for [affected feature]? I need: 1. Primary implementation files 2. Test coverage 3. Helper/utility modules 4. Integration points ``` **Query 2 — Invariants & Data Structures:** ``` What are the key data structures in [feature]? What invariants must hold? What relationships between data structures? How should [operation] affect state when [parameters from bug]? ``` **Query 3 — Historical Context:** ``` Have there been recent changes to [feature]? Design intent? Related user stories or issues? ``` **Report:** Summarize key files, critical invariants, data structures, and design context. ## Phase 3: Hypothesis Generation (Navigator Phase) **Query 1:** Map symptoms to code paths **Query 2:** Generate ranked root cause candidates **Query 3:** Get precise file/method navigation **Report:** Most likely root cause with location, alternatives, and code path to investigate. ## Phase 4: Test-First Investigation **CRITICAL: Write tests BEFORE reading implementation code.** 1. **Write failing test** based on expected behavior and invariants from Phase 2 2. **Verify test fails** — confirms bug exists 3. **Validate test with CoreStory** — paste test code, ask if it correctly tests expected behavior 4. **Read code** — only now, focused on methods CoreStory identified 5. **Identify bug** — compare against expected behavior 6. **Validate finding with CoreStory** — paste code snippet, explain hypothesis, get confirmation ## Phase 5: Solution Development 1. **Implement minimal fix** — smallest change that restores invariant 2. **Verify test passes** 3. **Validate fix with CoreStory** — check architectural alignment 4. **Add edge case tests** — ask CoreStory for scenarios 5. **Run full test suite** — no regressions allowed ## Phase 6: Completion 1. **Update ticket** (if MCP available) 2. **Commit with structured message** — Problem, Root Cause, Solution, Invariants Restored, Testing, References 3. **Rename CoreStory conversation** to include "RESOLVED" 4. **Report results** — summary, metrics, quality indicators ## Error Handling - **Project not found:** List available projects, ask user to specify - **Test won't fail:** Re-check reproduction steps, verify with CoreStory - **Fix causes regressions:** Don't commit, report regressions, revise approach - **CoreStory response unclear:** Ask follow-up with code snippets and specific variable names ## When NOT to Use - Trivial typo fixes - Documentation-only changes - User explicitly wants manual investigation - No CoreStory project available - Feature requests (not bugs) ```` #### Slash Command Save as `.claude/commands/fix-bug.md`: ````markdown theme={null} Activate the CoreStory-powered bug resolution workflow. Usage: ``` /fix-bug #6992 /fix-bug JIRA-1234 /fix-bug "Users can't login after password reset" ``` Executes the complete six-phase workflow: 1. Bug Intake — fetches ticket, creates CoreStory investigation conversation 2. Expert Phase — queries CoreStory for architecture, invariants, history 3. Navigator Phase — maps symptoms to code paths, generates hypotheses 4. TDD Investigation — writes failing test FIRST, then identifies root cause 5. Solution Development — implements fix, validates, adds edge case tests 6. Completion — commits with context, updates ticket, preserves investigation Prerequisites: - CoreStory MCP server configured - At least one CoreStory project with completed ingestion - (Optional) Ticketing system MCP for automatic ticket fetching Expected outcome: - Bug resolved with comprehensive test coverage - No regressions introduced - Detailed commit message explaining root cause and fix rationale - CoreStory conversation preserved as institutional knowledge Time estimate: 15-60 minutes depending on bug complexity ```` *** ### GitHub Copilot #### Setup 1. **Configure the CoreStory MCP server** in your VS Code settings. Add it to your MCP server configuration (typically in VS Code settings JSON or the MCP configuration UI). 2. **Add custom instructions.** Copilot reads project-level instructions from `.github/copilot-instructions.md`. This is the primary mechanism for teaching Copilot specialized workflows: ```bash theme={null} mkdir -p .github ``` Create `.github/copilot-instructions.md` with the content from the custom instructions file below. 3. **(Optional) Add a reusable prompt file.** Prompt files (`.github/prompts/fix-bug.prompt.md`) provide reusable task templates. See the prompt file below. 4. **Commit to version control:** ```bash theme={null} git add .github/copilot-instructions.md .github/prompts/ git commit -m "Add CoreStory bug resolution instructions for Copilot" ``` #### Usage In Copilot Chat (agent mode), natural language triggers the workflow: ``` Fix bug #6992 from the xarray repository Investigate the issue where reset_index leaves stale coord_names ``` Or reference the prompt file: ``` @workspace /fix-bug #6992 ``` #### Tips * Copilot's agent mode (available in VS Code) can execute terminal commands and edit files autonomously — this workflow works best in agent mode. * You can add path-specific instruction files (e.g., `.github/instructions/backend.instructions.md` with `applyTo: "src/backend/**"`) for component-specific guidance. * On Team/Enterprise plans, organization-level instructions apply across all repositories. * Copilot automatically references `.github/copilot-instructions.md` in chat responses. #### Custom Instructions Save as `.github/copilot-instructions.md`: ```markdown theme={null} # CoreStory Bug Resolution Workflow **If you do not detect that you have access to CoreStory (e.g., `list_projects` fails or is unavailable), ask the user to verify that their MCP or API connection is properly configured and that this repository has been ingested. If the user has not yet created a CoreStory account, direct them to create one and upload their repo at [app.corestory.ai](https://app.corestory.ai).** ## Role You are a bug resolution assistant with access to CoreStory's code intelligence via MCP. When users request bug fixes or investigations, follow the six-phase workflow below. ## Activation Apply this workflow when user requests bug fixes, investigations, or ticket resolution. Trigger phrases: "bug", "issue", "broken", "not working", "fix", "investigate". ## Workflow ### Phase 1: Bug Intake 1. Extract bug info from ticket (via ticketing MCP) or user description 2. Select CoreStory project (`CoreStory:list_projects`, verify status is "completed") 3. Create investigation conversation (`CoreStory:create_conversation`) 4. Report: bug summary, symptoms, CoreStory conversation ID ### Phase 2: Expert Phase — Understand Intended Behavior **Do this BEFORE investigating code.** Send three CoreStory queries (`CoreStory:send_message`): 1. Architecture discovery: files, tests, modules, integration points for the affected feature 2. Invariants & data structures: critical variables, relationships, acceptance criteria 3. Historical context: recent changes, design intent, related issues Extract and report: key files, critical invariants, data structures, design context. ### Phase 3: Navigator Phase — Generate Hypotheses Send three CoreStory queries: 1. Map symptoms to code paths (step-by-step logic flow) 2. Root cause candidates (ranked by probability) 3. Precise navigation (specific methods and files to examine) Report: most likely root cause with location, alternatives, investigation path. ### Phase 4: Test-First Investigation **Write tests BEFORE reading implementation code.** 1. Write failing test based on expected behavior and invariants from Phase 2 2. Run test — verify it fails (confirms bug exists) 3. Validate test with CoreStory (paste code, check correctness) 4. NOW read implementation code (focused on CoreStory-identified locations) 5. Identify the bug (compare against expected behavior) 6. Validate finding with CoreStory (paste code snippet, explain hypothesis) ### Phase 5: Solution Development 1. Implement minimal fix (smallest change that restores invariant) 2. Verify reproduction test passes 3. Validate fix with CoreStory (architectural alignment, side effects) 4. Add edge case tests (ask CoreStory for scenarios) 5. Run full test suite (no regressions) ### Phase 6: Completion 1. Update ticket (if ticketing MCP available) 2. Commit with structured message: Problem, Root Cause, Solution, Invariants Restored, Testing, References 3. Rename CoreStory conversation to include "RESOLVED" 4. Report: summary, tests added, quality metrics ## Key Principles - **Expert before Navigator**: understand intended behavior before investigating code - **Test-first always**: failing test → verify fails → fix → verify passes - **Validate hypotheses**: always verify with CoreStory before acting - **Minimal fixes**: smallest change that restores the invariant - **Rich documentation**: commit messages explain WHY, not just WHAT ## CoreStory Query Patterns Architecture: "What files are responsible for [feature]?" Invariants: "What invariants should [data structure] maintain?" Code paths: "If there's a bug where [symptom], what code paths should I investigate?" Validation: "Looking at [code]: I think this is the bug because [reason]. Does this align with the intended design?" Edge cases: "What edge cases should I test for [feature]?" ``` #### Prompt File (Optional) Save as `.github/prompts/fix-bug.prompt.md`: ```markdown theme={null} --- mode: agent description: Resolve a bug using CoreStory's code intelligence --- Investigate and fix the specified bug using the CoreStory six-phase workflow. 1. Fetch the bug details and create a CoreStory investigation conversation 2. Query CoreStory for architecture, invariants, and historical context 3. Generate hypotheses and identify investigation targets 4. Write a failing test BEFORE reading code, then pinpoint the root cause 5. Implement a minimal fix, validate with CoreStory, add edge case tests 6. Commit with full context, update ticket, preserve investigation ``` *** ### Cursor #### Setup 1. **Configure the CoreStory MCP server** in Cursor's MCP settings (Settings → MCP Servers, or edit the MCP config JSON directly). 2. **Add project rules.** Cursor uses rules in `.cursor/rules/` directories. Each rule folder contains a `RULE.md` file: ```bash theme={null} mkdir -p .cursor/rules/bug-resolver ``` Create `.cursor/rules/bug-resolver/RULE.md` with the content from the rule file below. 3. **Commit to version control:** ```bash theme={null} git add .cursor/rules/ git commit -m "Add CoreStory bug resolution rules for Cursor" ``` #### Usage In Cursor's Composer or Chat, the rule activates automatically for bug-related requests: ``` Fix bug #6992 from the xarray repository Investigate the issue where reset_index leaves stale coord_names ``` #### Tips * Rules with `alwaysApply: true` load in every session. Set this if your team regularly fixes bugs. Otherwise, use `alwaysApply: false` with a good `description` so Cursor loads it intelligently when relevant. * The legacy `.cursorrules` file still works but the `.cursor/rules/` directory structure is the current recommended approach. * Rules apply to Composer and Chat but do not affect Cursor Tab or inline edits (Cmd/Ctrl+K). * On Team/Enterprise plans, team rules apply across all members. #### Project Rule Save as `.cursor/rules/bug-resolver/RULE.md`: ```markdown theme={null} --- description: CoreStory-powered bug resolution workflow. Activates for bug fixes, investigations, and ticket resolution. alwaysApply: false --- # CoreStory Bug Resolution You are a bug resolution agent with access to CoreStory's code intelligence via MCP. Follow the six-phase workflow for bug investigation and resolution. **If you do not detect that you have access to CoreStory (e.g., `list_projects` fails or is unavailable), ask the user to verify that their MCP or API connection is properly configured and that this repository has been ingested. If the user has not yet created a CoreStory account, direct them to create one and upload their repo at [app.corestory.ai](https://app.corestory.ai).** ## Activation Triggers Apply when user requests: bug fix, investigation, ticket resolution, or any phrase containing "bug", "issue", "broken", "not working". ## Phase 1: Bug Intake - Extract bug info from ticket or description - Select CoreStory project (`CoreStory:list_projects`) - Create investigation conversation (`CoreStory:create_conversation`) ## Phase 2: Expert Phase **Understand intended behavior BEFORE investigating code.** Query CoreStory (`CoreStory:send_message`) for: 1. Architecture: files, tests, modules for the affected feature 2. Invariants: data structures, relationships, acceptance criteria 3. History: recent changes, design intent, related issues ## Phase 3: Navigator Phase Query CoreStory for: 1. Symptom-to-code-path mapping 2. Ranked root cause candidates 3. Precise file/method navigation ## Phase 4: Test-First Investigation **Write tests BEFORE reading code.** 1. Write failing test from expected behavior + invariants 2. Verify test fails 3. Validate test with CoreStory 4. Read code (only now) 5. Identify bug 6. Validate finding with CoreStory ## Phase 5: Solution Development 1. Implement minimal fix 2. Verify test passes 3. Validate fix with CoreStory 4. Add edge case tests 5. Run full test suite — no regressions ## Phase 6: Completion 1. Update ticket 2. Commit: Problem, Root Cause, Solution, Invariants Restored, Testing, References 3. Rename CoreStory conversation → "RESOLVED" 4. Report results ## Key Principles - Expert before Navigator - Test-first always - Validate hypotheses with CoreStory - Minimal fixes that restore invariants - Commit messages explain WHY ``` *** ### 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): ```bash theme={null} mkdir -p .factory/droids ``` Create `.factory/droids/bug-resolver.md` with the content from the droid file below. 3. **Commit to version control** (for project-level droids): ```bash theme={null} git add .factory/droids/ git commit -m "Add CoreStory bug resolution droid" ``` #### Usage Invoke the droid via the Task tool: ``` @bug-resolver Fix bug #6992 from the xarray repository ``` Or describe the bug and Factory.ai routes to the droid based on its activation triggers. #### Tips * Use `model: inherit` in the YAML frontmatter to use whatever model the session is configured with. * The `tools` field in frontmatter can explicitly list required MCP tools if you want to restrict the droid's capabilities. * The Task tool that invokes droids requires experimental features to be enabled. * For complex bugs, the droid's CoreStory queries may produce long streaming responses — this is expected. #### Custom Droid Save as `.factory/droids/bug-resolver.md`: ```markdown theme={null} --- name: CoreStory Bug Resolver description: Resolves bugs using CoreStory code intelligence and TDD methodology model: inherit tools: - CoreStory:list_projects - CoreStory:get_project - CoreStory:get_project_stats - CoreStory:create_conversation - CoreStory:send_message - CoreStory:get_conversation - CoreStory:rename_conversation - CoreStory:get_project_prd - CoreStory:get_project_techspec --- # CoreStory Bug Resolver Execute the six-phase bug resolution workflow using CoreStory's code intelligence. **If you do not detect that you have access to CoreStory (e.g., `list_projects` fails or is unavailable), ask the user to verify that their MCP or API connection is properly configured and that this repository has been ingested. If the user has not yet created a CoreStory account, direct them to create one and upload their repo at [app.corestory.ai](https://app.corestory.ai).** ## Activation Triggers - "Fix bug #[ID]" - "Investigate issue [ID]" - "Resolve ticket [ID]" - Any bug-related investigation or fix request ## CoreStory MCP Tools - `CoreStory:list_projects` — list available projects - `CoreStory:get_project` — verify project status - `CoreStory:create_conversation` — start investigation thread - `CoreStory:send_message` — query code intelligence - `CoreStory:rename_conversation` — mark as resolved When instructions say "Query CoreStory", use `CoreStory:send_message`. ## Phase 1: Bug Intake 1. Extract bug info (from ticket MCP or user description) 2. Select CoreStory project (`CoreStory:list_projects`, verify "completed") 3. Create conversation: "Bug Investigation: #[ID] - [description]" ## Phase 2: Expert Phase — Before Code Query CoreStory for: architecture, invariants, historical context. ## Phase 3: Navigator Phase Query CoreStory for: code paths, root cause candidates, precise navigation. ## Phase 4: Test-First Investigation Write failing test → verify fails → validate with CoreStory → read code → identify bug → validate finding. ## Phase 5: Solution Development Implement fix → verify test passes → validate with CoreStory → edge case tests → full suite. ## Phase 6: Completion Update ticket → structured commit → rename conversation "RESOLVED" → report. ## Key Principles - Expert before Navigator - Test-first always - Validate with CoreStory before acting - Minimal fixes that restore invariants - Commit messages explain WHY ``` *** ## Tips & Best Practices **Ask specific questions.** "Tell me everything about reset\_index" gets a sprawling response. "What is the relationship between \_coord\_names and \_variables during reset\_index with drop=True?" gets a precise, useful answer. **Paste code in your CoreStory queries.** When validating a hypothesis or fix, include the actual code snippet. CoreStory gives much better answers when it can see what you're looking at. **Trust the test-first discipline.** It's tempting to skip straight to reading code, especially when you think you know where the bug is. The failing test is worth the five minutes — it catches false assumptions, documents the bug, and prevents regressions. **Use the CoreStory conversation as a review artifact.** Before your fix goes through code review, share the CoreStory conversation link. Reviewers can see the full investigation context: what invariants were identified, what hypotheses were considered, and why this fix was chosen. **Name conversations descriptively.** "Bug Investigation: #6992 - reset\_index coord\_names cleanup" is searchable and useful six months later. "Bug fix" is not. **Don't fight the phases.** If you're tempted to jump from Phase 1 to Phase 5, you're optimizing for speed on this bug at the cost of quality. The Expert Phase in particular catches architectural constraints that would otherwise become failed code reviews or production regressions. **Let the agent complete the workflow.** Interrupting mid-workflow loses accumulated context. If you need to redirect, explain why rather than just changing the subject. *** ## Troubleshooting **CoreStory returns generic answers.** Your queries are too broad. Instead of "Tell me about the auth system," try "What files handle JWT token validation? What invariants must the token payload satisfy?" Include specific variable names, method names, or code snippets. **Project not found or ingestion incomplete.** Run `CoreStory:get_project_stats` to check status. If ingestion is still running, wait for it to complete — queries against partially-ingested projects give incomplete answers. Verify the project name matches exactly. **The reproduction test passes (bug not reproduced).** Three possibilities: the bug was already fixed, the reproduction steps are wrong, or the test isn't testing what you think it is. Ask CoreStory to verify your understanding of expected behavior. Check if the bug is environment-specific or version-specific. **Fix causes regressions.** Don't commit. Run `CoreStory:send_message` asking about integration impacts: "What other components depend on \[feature]? What downstream effects could my change to \[behavior] have?" Revise the fix to be more targeted, or add compatibility handling for dependent components. **CoreStory response is too long or gets cut off.** Break your query into smaller, more specific questions. Instead of one query covering architecture + invariants + history, send them separately. **Agent doesn't follow the workflow.** If you're using the agent configuration files (skill/instructions/rules/droid) and the agent still doesn't follow the six-phase workflow, check that the configuration file is in the correct location and format for your agent. See the Agent Implementation Guides above for exact paths. # Business Rules Extraction Source: https://docs.corestory.ai/playbooks/business-rules-extraction Extract, catalog, and validate business rules embedded in your codebase using CoreStory's persistent architectural intelligence. ## Overview Business rules are the most critical and most poorly documented aspect of most codebases. They're scattered across service layers, embedded in conditionals, hidden in database constraints, encoded in configuration files, and rarely written down comprehensively. When a developer asks "what happens when a customer places an order?" the answer lives in dozens of files across multiple architectural layers — and no single person holds the complete picture. This playbook teaches you how to use the CoreStory MCP server, combined with local source code, to systematically extract, document, and maintain a comprehensive inventory of business rules. The approach uses CoreStory as an **architectural expert** — querying it first to understand what rules *should* exist and where they live — then verifying and deepening that understanding through direct code inspection. The primary deliverable is a structured **Business Rules Inventory**: a document that maps every significant business rule to its domain, enforcement layer, source files, invariants, and edge cases. This inventory is useful for onboarding, compliance audits, refactoring planning, migration scoping, and providing AI coding agents with accurate system context. **How this relates to other playbooks:** This playbook extracts and documents existing rules — it doesn't change them. If extraction reveals rules that need to change, use the [Feature Implementation](/playbooks/feature-implementation) playbook. If you're building specifications for new features and need to understand existing rules as constraints, the [Spec-Driven Development](/playbooks/spec-driven-development) playbook's Ground phase covers that. If you're evaluating a codebase for acquisition, the [M\&A Technical Due Diligence](/playbooks/ma-technical-due-diligence) playbook includes business rule assessment as one workstream. ### When to Use This Playbook * Onboarding to an unfamiliar codebase and need to understand what the system *does*, not just how it's built * Preparing for a major refactor, migration, or rewrite and need to know what behavior must be preserved * Conducting a compliance or security audit that requires documenting enforced rules * Building AI agent context — the business rules inventory feeds directly into `.claude/` skill files, Cursor rules, or Copilot instructions * Resolving conflicting behavior between modules by mapping out which rules govern each ### When to Skip This Playbook * You need to understand a single, specific rule (just query CoreStory directly) * The codebase is trivially small (under \~5k LOC) — read it directly * No CoreStory project exists for the codebase and you can't create one * You need to *change* business rules, not document them (use the [Feature Implementation](/playbooks/feature-implementation) playbook instead) ## 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](/getting-started/mcp-server-setup)) * A code repository the agent can read locally * (Recommended) Familiarity with the codebase's domain — helps evaluate whether extracted rules are complete and correct * (Recommended) Access to domain experts who can validate extracted rules ## How It Works ### The Workflow Phases | Phase | Name | Purpose | CoreStory Role | | ----- | ------------------------ | ------------------------------------------------------------------------- | -------------------- | | 1 | Setup & Scoping | Select project, create conversation, define extraction scope | Setup | | 2 | Architectural Survey | Map where business logic lives, identify rule categories | Expert | | 3 | Deep Extraction | Systematically query each rule category, build draft inventory | Expert + Navigator | | 4A | Code Verification | Walk local code to verify rules, find what CoreStory missed | — (local code only) | | 4B | Enforcement Verification | Prove that rules claiming enforcement actually enforce at runtime | Expert + local code | | 4C | Flow-Trace Discovery | Trace end-to-end user flows to find behaviors missed by domain extraction | Expert + local code | | 5 | Documentation & Output | Produce the structured business rules document with confidence levels | Expert (gap-filling) | | 6 | Conversation Capture | Rename conversation with RESOLVED prefix | Knowledge capture | The core principle is **Expert before Code**: query CoreStory for architectural understanding before navigating to specific code. CoreStory surfaces rules you wouldn't find through grep alone — implicit conventions, cross-layer interactions, and undocumented invariants. Verification then grounds those discoveries in reality — first through code inspection (4A), then by adversarially testing enforcement claims (4B), and finally by tracing user-facing flows end-to-end to catch behaviors that domain decomposition misses (4C). ### CoreStory MCP Tools Used | Tool | Phase(s) | Purpose | | ---------------------- | -------- | ----------------------------------------------------------------- | | `list_projects` | 1 | Find the target project | | `create_conversation` | 1 | Create a persistent conversation for the extraction session | | `send_message` | 2, 3, 5 | Query CoreStory for rules, architecture, and gap-filling | | `get_project_prd` | 2 | Retrieve the PRD for rule-adjacent requirements (see note below) | | `get_project_techspec` | 2 | Retrieve the TechSpec for data model constraints and architecture | | `list_conversations` | 1 | Check for prior extraction sessions to build on | | `get_conversation` | 1 | Resume a prior extraction session | | `rename_conversation` | 6 | Mark the conversation as resolved | **A note on the PRD and TechSpec:** These documents are often very large — too large for an agent to hold in a single context window. Rather than trying to read them end-to-end, treat them as reference material: skim for structure and vocabulary, then use `send_message` to ask CoreStory targeted questions about specific business rules, requirements, and constraints. CoreStory has already ingested these documents and can answer questions about their contents more efficiently than the agent can parse them raw. ## Step-by-Step Walkthrough ### Phase 1 — Setup & Scoping **Goal:** Establish the extraction session and define what you're extracting. **Step 1.1: Find the project.** ``` Tool: list_projects ``` 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.** ``` Tool: list_conversations Parameters: project_id = ``` If a previous business rules extraction conversation exists (look for titles containing "Business Rules"), use `get_conversation` to review it. You may be able to build on prior work rather than starting fresh. **Step 1.3: Create a conversation.** ``` Tool: create_conversation Parameters: project_id = title = "Business Rules Extraction — " ``` Use a descriptive title that includes the extraction scope. Examples: * "Business Rules Extraction — Order Processing Module" * "Business Rules Extraction — Full System Inventory" * "Business Rules Extraction — Payment & Tax Rules" **Step 1.4: Define scope.** Decide the extraction scope before querying: | Scope | When to Use | | ------------- | ----------------------------------------------------------- | | Single module | You need rules for one specific area (e.g., payments, auth) | | Single domain | You need rules across a domain (e.g., all e-commerce rules) | | Full system | You need a complete inventory of all business rules | For a first extraction, start with a single module. You can always expand scope later. Full-system extractions are best done one domain at a time across multiple sessions. ### Phase 2 — Architectural Survey (Expert) **Goal:** Understand where business logic lives in this codebase and identify the major rule categories. This phase is about building a map before diving deep. You're answering: *What kinds of business rules exist here, and which architectural layers enforce them?* **Step 2.1: Query for the architectural rule map.** ``` Tool: send_message Query: "Where is business logic implemented in this codebase — is it in service layers, middleware, database constraints, or spread across multiple layers? Give me a map of which architectural layers enforce which types of rules." ``` This query produces a layer-by-layer breakdown showing where different rule types are enforced. The specifics depend on the stack — some examples of what you might find: | Layer | Typical Rule Types | Examples by Stack | | ------------------------------ | -------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | | Service / business logic layer | Core rules, state transitions, calculations | Spring `@Service`, Django service modules, Express middleware, .NET application services | | Validation layer | Input validation, format constraints, required fields | Bean Validation annotations, Pydantic models, Joi/Zod schemas, FluentValidation | | Auth / security layer | Authentication, authorization, role checks | Spring Security, Django permissions, Passport.js, ASP.NET Identity | | Data / persistence layer | Integrity constraints, uniqueness, referential integrity | JPA/Hibernate annotations, Django model constraints, Sequelize validations, EF Core configurations | | API / controller layer | Request validation, error formatting | Controller annotations, serializer validation, request middleware | | Configuration | Environment-specific behavior, feature flags, thresholds | Properties files, environment variables, feature flag services | Note the specific file naming patterns and directory structures CoreStory identifies — you'll use these in Phase 4 to navigate code efficiently. **Step 2.2: Skim the PRD and TechSpec for structure.** ``` Tool: get_project_prd Tool: get_project_techspec ``` These documents are typically large. Don't try to read them end-to-end. Instead, skim for: * **Domain vocabulary** — the names of entities, features, and modules as the product defines them. These become your query anchors for Phase 3. * **Section structure** — which areas of the product are documented, giving you a checklist of domains to explore. * **Explicit rule language** — look for sections titled "business rules," "constraints," or "validation" and for user stories that contain `business_rules` fields. If the PRD is too large to skim effectively, query CoreStory instead. Run two queries in parallel — one for business rules, one for acceptance criteria. They are different artifacts and you want both: ``` Tool: send_message Query: "Based on the PRD and requirements for this project, what are the explicitly documented business rules? List them grouped by feature area or domain." ``` ``` Tool: send_message Query: "List the user stories and their acceptance criteria, grouped by feature area. For each AC: (1) note any associated business rules, (2) cite the implementation evidence (file:line) where present, (3) flag ACs that appear undocumented in code." ``` This lets CoreStory surface both the rules and the ACs from the PRD without the agent needing to hold the entire document in context. The ACs become inputs to the `Acceptance Criteria` field on each BR in Phase 3. **Step 2.3: Query for data model constraints from the TechSpec.** ``` Tool: send_message Query: "Based on the technical specification, what are the key data model constraints — required fields, unique constraints, valid states, and relationships between entities? Focus on constraints that encode business rules, not just structural schema." ``` The TechSpec surfaces constraints at the data layer — unique fields, required relationships, enum types that define valid states. These are business rules that are often invisible to service-level analysis. **Step 2.4: Query for a high-level rule inventory.** ``` Tool: send_message Query: "What are the major categories of business rules in this system? Group them by domain (e.g., order processing, user management, product catalog, payments, shipping, tax) and for each category, list the types of rules that exist (validation, authorization, state transitions, calculations, constraints)." ``` This gives you a category map to work through systematically in Phase 3. It's intentionally broad — the value is in creating a checklist of areas to explore, not in getting deep answers yet. **Expected output from Phase 2:** * An architectural map (which layers enforce which rule types) * A list of explicit rules from the PRD (via CoreStory query or direct skim) * A list of data constraints from the TechSpec (via CoreStory query) * A categorized inventory of rule types to explore in Phase 3 ### Phase 3 — Deep Extraction (Expert + Navigator) **Goal:** Systematically query each rule category identified in Phase 2. Build the detailed inventory. This is the core of the extraction process. For each domain/category identified in Phase 2, you'll run targeted queries. The key insight from testing: **specific, domain-scoped questions produce dramatically better results than broad questions.** **The specificity principle:** Compare these two queries: | Query | Quality of Response | | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | | "What are the business rules?" | High-level summary, light on detail | | "What validation rules exist for customer registration and credential management? Include password policies, email validation, and role-based access control rules." | Precise code-backed answers with file paths, method names, and exact constraint values | Always name the specific module, entity, or workflow you're asking about. Include the *types* of rules you expect to find (validation, authorization, state transitions, calculations). **Step 3.1: Extract validation rules per domain.** For each domain area (identified in Phase 2), query: ``` Tool: send_message Query: "What validation rules exist for [domain entity, e.g., customer registration, product creation, order submission]? Include input validation, required fields, format constraints, uniqueness checks, and cross-field validation." ``` CoreStory typically returns: * The validation class/method and its file path * Specific constraint values (e.g., "password must be 8–12 characters, include 1 digit and 1 special character") * Where validation is enforced (controller vs. service vs. model/entity layer) **Step 3.2: Extract authorization and permission rules.** ``` Tool: send_message Query: "What authorization and permission rules govern [feature area]? Who can perform which operations? What role checks exist and where are they enforced?" ``` Authorization rules are often the most security-critical and the least well-documented. CoreStory surfaces rules like: * "Only users in the SUPERADMIN group can assign the SUPERADMIN role to others" * "Customer operations are scoped to the authenticated user's merchant store" **Step 3.3: Extract state transition rules.** ``` Tool: send_message Query: "What are the state transitions for [entity, e.g., orders, user accounts, payment transactions]? What triggers each transition, what validations occur during the transition, and what states are terminal?" ``` State transition rules define the lifecycle of key entities. Look for: * Valid state sequences (e.g., ORDERED -> PROCESSED -> SHIPPED -> DELIVERED) * What triggers each transition (payment success, admin action, time-based) * What blocks a transition (failed validation, insufficient inventory) **Step 3.4: Extract calculation and pricing rules.** ``` Tool: send_message Query: "What are the pricing or calculation rules for [domain]? How are values computed, including any tiered logic, discounts, tax handling, or derived fields? What inputs affect the calculation?" ``` Calculation rules are where the most subtle business logic hides. CoreStory can map the full calculation chain — which is often spread across multiple utility classes and service methods. **Step 3.4b: Extract acceptance criteria.** Business rules describe what the system enforces. Acceptance criteria describe how a stakeholder confirms the behavior is correct. They overlap — but they are not the same artifact, and downstream consumers (TDD, behavioral verification, regression test generation) need both. CoreStory's PRD-derived user stories typically expose acceptance criteria alongside `business_rules` and `technical_requirements` fields. ``` Tool: send_message Query: "For [domain], list the user stories and their acceptance criteria. For each AC: (1) identify which business rule(s) implement or enforce it, (2) cite where the AC is observable in code (file:line), (3) flag any AC that has no clear BR mapping. Format each AC as Given/When/Then where possible." ``` Use the response to populate the `Acceptance Criteria` field on each BR entry. ACs without a BR mapping fall into one of three categories: * **Cross-cutting AC** — depends on the interaction of multiple BRs. Attach to the most central BR and reference siblings via `Related Rules`. * **Implicit-behavior AC** — implemented but never extracted as a discrete rule. Create a new BR entry to capture it. * **Aspirational AC** — documented but not implemented. Flag in the Conflicts & Open Questions section of the inventory. **Step 3.5: Extract invariants and constraints.** Invariants are the "must always be true" conditions that hold regardless of input. They are the most valuable downstream input for assertion-style tests and behavioral verification, because they are usually implicit in the code rather than documented. Categorize them as you extract — each category produces a different kind of test: | Category | What it means | Example | | -------------- | ----------------------------------------------- | ---------------------------------------------------------------------------------- | | Data-integrity | Computed totals match their inputs | "Account balance equals sum of transactions" | | State-machine | State transitions are bounded | "Order status only transitions forward: pending → confirmed → shipped → delivered" | | Referential | Cross-entity relationships are preserved | "Every line item belongs to exactly one order" | | Security | Access scoping is enforced regardless of caller | "A user can only read records they own" | | Temporal | Time-related ordering holds | "`created_at` is never after `updated_at`" | ``` Tool: send_message Query: "What are the invariants that must always hold for [entity, e.g., MerchantStore, Customer, Product]? Categorize each as data-integrity, state-machine, referential, security, or temporal. For each invariant: (1) cite the code that enforces it, (2) describe what happens if it's violated, (3) note whether it's local to this entity or cross-cutting across multiple entities." ``` Invariant queries surface the "must always be true" conditions — unique constraints, required relationships, format patterns. CoreStory returns these with evidence from model definitions, schema annotations, and column-level constraints. Cross-cutting invariants (e.g., "all timestamps are stored in UTC" — applies to every entity) should be attached to the most relevant BR and linked from siblings via `Related Rules`. **Step 3.6: Extract implicit and undocumented rules.** ``` Tool: send_message Query: "What implicit business rules exist in [module] that aren't documented but are enforced in code? For example, what happens when [edge case scenario], when [error condition], or when [limit is exceeded]?" ``` This is where CoreStory provides the most value over code search alone. It identifies fallback behaviors, error handling paths, and assumptions baked into conditional logic that no documentation mentions. Naming specific edge cases in the query helps CoreStory focus its analysis. **Step 3.7: Extract end-to-end workflow rules.** For critical workflows, query the complete code path: ``` Tool: send_message Query: "For the [workflow, e.g., order processing flow], show me the exact code path from [start, e.g., when a customer submits an order] to [end, e.g., when the order status is set to PROCESSED]. What validations happen at each step, and what causes the process to fail?" ``` This produces a step-by-step walkthrough with validation checkpoints and failure conditions at each stage — the most complete picture of how rules interact during a real operation. **Expected output from Phase 3:** * Detailed business rules organized by domain * Code-level evidence (file paths, method names, constraint values) for each rule * Identification of which architectural layer enforces each rule * Edge cases and failure conditions for each rule category ### Phase 4A — Code Verification **Goal:** Walk the local codebase to verify extracted rules, find rules CoreStory missed, and identify conflicts between documented intent and actual behavior. This phase is essential. CoreStory provides architectural knowledge that code search alone can't match — but code is ground truth. Every rule extracted in Phase 3 should be verified against actual source. **Step 4.1: Verify entity-level constraints.** Search for model/entity classes and check for constraint declarations. What you're looking for depends on the stack: * **Java/Spring:** `@UniqueConstraint`, `@Column(unique, nullable, length)`, `@NotEmpty`, `@NotNull`, `@Pattern`, `@Email`, `@Size` on entity fields * **Python/Django:** `unique=True`, `blank=False`, `max_length`, `validators=[...]`, `constraints = [...]` on model fields * **Node/TypeScript:** Zod schemas, Joi validation rules, Sequelize/Prisma model constraints, Mongoose schema validators * **C#/.NET:** `[Required]`, `[MaxLength]`, `[RegularExpression]`, EF Core `HasIndex().IsUnique()`, Fluent Validation rules * **Ruby/Rails:** `validates :field, presence: true`, `uniqueness: true`, `format:`, `numericality:` on ActiveRecord models Compare what you find with what CoreStory reported. Common discoveries: * Constraints that CoreStory mentioned but expressed differently in code * Constraints that exist in code but CoreStory didn't surface (usually on less prominent entities) * Constraints in the PRD that aren't actually enforced in code (intent vs. reality gaps) **Step 4.2: Verify service-layer business logic.** Navigate to the service implementations CoreStory identified. Look for: * Conditional branches that encode business decisions * Exception/error throws that enforce invariants * Calls to other services that create cross-domain rules * Configuration lookups that make behavior environment-dependent **Step 4.3: Verify authorization rules.** Check security configuration files, authentication providers, and authorization declarations. Look for: * Role-based access checks (annotations, decorators, middleware guards, policy classes) * Attribute-based access control patterns * Resource scoping (e.g., "users can only see their own data") * API-level authorization (route guards, endpoint permissions) Authorization rules are often the most dangerous to get wrong. Verify every role check CoreStory identified and look for additional checks it may have missed. **Step 4.4: Find rules CoreStory missed.** CoreStory excels at well-structured, explicit business logic. It sometimes misses: * Rules encoded in configuration or properties files (rate limits, feature flags, thresholds) * Rules enforced by database triggers or stored procedures * Rules implemented in third-party integration code (payment gateways, shipping APIs) * Rules embedded in test assertions that document expected behavior * Rules enforced only by frontend validation with no backend counterpart * Rules in infrastructure code (CI/CD checks, deployment constraints) Search for these patterns in the local codebase to fill gaps. **Step 4.5: Identify conflicts.** Cross-reference three sources for each rule: | Source | What It Tells You | | ------------------------ | -------------------------------------------------------------- | | PRD (from Phase 2) | What the rule *should* be (intent) | | CoreStory (from Phase 3) | What CoreStory understands the rule to be (architectural view) | | Source code (this phase) | What the rule *actually* is (ground truth) | Document any conflicts. Common conflict types: * PRD says X, code does Y (implementation drift) * CoreStory reports a rule that exists in dead code (no longer active) * Code enforces a rule that no documentation mentions (tribal knowledge) **Expected output from Phase 4A:** * Verified or corrected version of every rule from Phase 3 * New rules discovered through code inspection * Conflict log documenting intent vs. reality gaps * Confidence level for each rule (High = all three sources agree; Medium = two agree; Low = only found in code) ### Phase 4B — Enforcement Verification **Goal:** For every rule in the draft inventory that claims enforcement, validation, or constraint behavior, prove that the enforcement actually happens at runtime. Phase 4A confirms that rules *exist* in the code. Phase 4B goes further: it tests whether rules that claim to enforce, validate, or constrain actually do so. A field labeled `requiredRoles` that is never checked at runtime is not an authorization rule — it's a dead field. A validation method that compares the wrong variable doesn't enforce the constraint it appears to. This phase catches the gap between code structure and runtime behavior. **Step 4B.1: Classify each rule by claim type.** Tag every rule in the draft inventory with one of: | Claim Type | Definition | Verification Required | | ----------------- | -------------------------------------------- | ----------------------------------------------------------- | | **Workflow** | "When X happens, Y follows" | Trace the trigger → action path | | **Constraint** | "X must satisfy condition Y" | Find the code that rejects invalid X | | **Validation** | "Input X is checked for Y before proceeding" | Find the validation call site and confirm it throws/rejects | | **Default** | "X defaults to Y when not provided" | Find the assignment; low risk of inaccuracy | | **Calculation** | "X is computed as f(Y, Z)" | Find the formula; low risk of inaccuracy | | **Authorization** | "Only users with role/state X can do Y" | Find the access check that blocks non-X users | Rules tagged **Constraint**, **Validation**, and **Authorization** are highest priority for enforcement verification. **Workflow** rules need trigger-path tracing. **Default** and **Calculation** rules are lowest risk and can be spot-checked. **Step 4B.2: For each high-priority rule, answer three questions.** For every rule tagged Constraint, Validation, or Authorization: **Q1: Where is the enforcement point?** Not "where is the value declared?" but "where in the execution path is the check performed that would reject invalid input or block unauthorized access?" Cite the specific method and line. If there is no enforcement point — the value/field/config exists but nothing checks it at runtime — downgrade the rule to **"Declared but not enforced"** and flag it. **Q2: What happens when the constraint is violated?** Does the code throw an exception? Return an error? Silently ignore? Log and continue? The answer determines whether the rule is truly enforced or just aspirational. If the violation path is "nothing happens" or "the check is buggy," downgrade or correct the rule. **Q3: Is the scope of enforcement accurately described?** * **Enforcement scope:** Universal (always enforced), conditional (enforced when flag/config is set), or presentation-only (enforced in UI but not server-side). * **Enforcement level:** Code-level (throws/rejects), config-level (values defined but not validated), or convention-level (UI shows limited options but backend accepts anything). Use CoreStory to assist with tracing execution paths: ``` Tool: send_message Query: "For rule [BR-ID], which states [rule description], I need you to verify enforcement. Do NOT confirm the rule based on the existence of fields, configs, or method signatures. Instead: (1) identify the specific line of code where this rule would reject invalid input or block unauthorized access, (2) trace the execution path to confirm that line is actually reached during normal operation, and (3) describe what happens when the rule is violated. If you cannot find an enforcement point, say so explicitly." ``` This framing prevents the extraction from repeating its original error — seeing a structural element and inferring enforcement. **Step 4B.3: Produce a verification matrix.** | BR-ID | Claim Type | Enforcement Point | Violation Behavior | Scope | Level | Status | | ---------- | ---------- | ----------------- | ------------------ | ----- | ----- | ------ | | (per rule) | | | | | | | **Status values:** * **Confirmed** — rule is accurate as written * **Corrected** — rule description has been revised (show diff) * **Downgraded** — rule exists structurally but is not enforced; moved to "Declared but not enforced" appendix * **Removed** — rule does not exist in any meaningful form **Step 4B.4: Common anti-patterns to check for.** The following patterns frequently produce false-positive rules in domain-decomposed extraction. The verification step should explicitly watch for them: * **Dead fields:** Fields, properties, or config entries that are set/declared but have zero read references in any execution path. The structure suggests a rule, but nothing enforces it. * **Buggy validation:** Validation methods that compare the wrong variable, use identity comparison instead of value comparison, or have copy-paste errors where the same field is checked multiple times under different labels. * **Setter-only constraints:** Rules claiming "X is constrained to values Y" where the constraint exists only as a UI convention or documentation comment, not as server-side enforcement. A plain setter with no validation means the constraint is convention, not code. * **Inaction misread as enforcement:** Rules claiming "X is set to Y" where the code actually leaves X unchanged (it was already Y from initialization). Describe the actual mechanism, not the inferred intent. * **Scope inflation:** A behavior observed in config, UI, or a specific call site reported as a universal code-level constraint. Always specify where the boundary is enforced and whether other paths bypass it. **Expected output from Phase 4B:** * Verification matrix for all Constraint, Validation, and Authorization rules * Corrected rule descriptions where enforcement differs from the original claim * "Declared but not enforced" appendix entries for downgraded rules * Spot-check results for Default and Calculation rules ### Phase 4C — Flow-Trace Discovery **Goal:** Find implemented behaviors that domain-decomposed extraction missed by tracing end-to-end user flows through the codebase. Phases 3 and 4A–4B work domain by domain: "What does the authentication module do?" "What does the order module do?" This approach misses behaviors that emerge from the *interaction* between modules — where one module accepts input and another silently overwrites it, or where a method's name suggests additive behavior but its body replaces. Phase 4C catches these by following complete user actions from entry point to final side effect. **Step 4C.1: Identify user-facing entry points.** Query CoreStory for all user-facing entry points in the system: ``` Tool: send_message Query: "List all user-facing entry points in this system: HTTP endpoints, form handlers, API controllers, CLI commands, admin operations, scheduled jobs, message listeners, event handlers. I need a complete list of ways work enters the system." ``` The goal is a complete list of "ways work enters the system." Group them by user type (end user, admin, system/automated) and by operation type (read, write, state change). **Step 4C.2: Trace each flow end-to-end.** For each entry point, trace the complete execution path from input to final side effect: ``` Tool: send_message Query: "Trace the complete execution path for [user action] from the entry point ([class.method]) through to all database writes, message sends, and response outputs. For each step, document: what data enters, what the code does to it, and what comes out. Flag any cases where: (a) user-provided input is ignored or overwritten, (b) a method's actual behavior differs from what its name suggests, or (c) an error condition is silently swallowed." ``` For each step in the path, document: * **Data transformations:** What is the input? What does the code do to it? What is the output? * **Side effects:** Database writes, message sends, session mutations, cookie operations, external API calls. * **Hardcoded values:** Any literals, magic numbers, or test/stub data injected along the path. * **Divergence from apparent intent:** Cases where the code does something different from what a reader would expect based on method/class/variable names. Verify CoreStory's trace against local code for critical flows. **Step 4C.3: Compare flow traces against the draft inventory.** For each behavior discovered in the flow traces: * If it matches an existing rule: confirm the rule and note the flow-trace evidence. * If it contradicts an existing rule: flag the contradiction. This is the primary mechanism for catching cases where a form accepts user input but the handler ignores or overwrites it. * If it's a new behavior not in the inventory: add it as a new rule with a BR-ID. **Step 4C.4: Common anti-patterns to check for.** The following patterns frequently produce missing rules in domain-decomposed extraction. The flow-trace step should explicitly watch for them: * **Input ignored:** User-provided data that is accepted by a form/API but overwritten or discarded by the handler. This is invisible to domain extraction because the domain module "works" — the problem is in the integration between input and processing. * **Overwrite vs. accumulate semantics:** Methods whose names suggest additive behavior (add, append, increment) but whose implementations replace or reset. The only way to catch this is to read the method body, not the signature. * **Duplicate logic across entry points:** The same business logic (e.g., field validation, data normalization) implemented in multiple entry points but only cataloged once. Each instance may have subtle differences. * **Silent failures:** Code paths where an error condition is caught and swallowed rather than surfaced, effectively changing the business rule from "X is required" to "X is optional." * **Stub or test data in production paths:** Hardcoded values that look like placeholders or test fixtures but exist in the actual production code path, permanently overriding dynamic data. **Expected output from Phase 4C:** * Complete list of user-facing entry points * Flow traces for all critical user actions * New rules discovered through flow tracing (with BR-IDs) * Contradictions between flow behavior and existing inventory rules * Flow-trace evidence appendix ### Phase 5 — Documentation & Output **Goal:** Produce the structured business rules inventory document. Organize extracted rules using the output format below. For any gaps discovered during documentation, run targeted CoreStory queries to fill them: ``` Tool: send_message Query: "For the [specific rule], what edge cases exist? What happens when [boundary condition]?" ``` Group rules by domain, then by type within each domain. Assign IDs sequentially (BR-001, BR-002, ...). See the **Output Format** section below for the complete template. ### Phase 6 — Conversation Capture **Goal:** Preserve the extraction session for future reference. ``` Tool: rename_conversation Parameters: project_id = conversation_id = title = "RESOLVED — Business Rules Extraction — " ``` The RESOLVED prefix signals that this conversation contains a completed extraction. Future sessions can reference it using `list_conversations` and `get_conversation`. ## Output Format Each extracted business rule should be documented using this template: ```markdown theme={null} ### BR-001: [Short Descriptive Name] - **Domain:** [e.g., Payments, User Management, Order Processing, Shipping, Tax, Product Catalog] - **Description:** [Plain-English description of what the rule enforces and why] - **Type:** [Validation | Authorization | State Transition | Calculation | Constraint | Workflow | Configuration] - **Claim Type:** [Workflow | Constraint | Validation | Default | Calculation | Authorization] - **Enforcement Layer:** [API | Service | Database | Middleware | UI | Multiple] - **Enforcement Point:** [Specific method/line where the rule is enforced, for Constraint/Validation/Authorization rules] - **Enforcement Level:** [Code-level | Config-level | Convention-level | Declared-only] - **Source Files:** - `path/to/file.ext` (lines XX–YY) — [what this file does for the rule] - **Rule Logic:** - [Precise statement of the rule, e.g., "Password must be 8–12 characters, include at least 1 digit and 1 special character"] - **Acceptance Criteria:** - [Bulleted list of testable AC statements this rule satisfies. Source: PRD user stories, work-package definitions, or new behaviors. Format each as Given/When/Then or as a clear pass/fail statement. If this rule maps 1:1 to a single user-story AC, reference the AC ID. If multiple ACs depend on this rule, list them all. ACs are the primary input for AI-generated tests — favor outcome-based statements ("order is rejected with code MIN_AMOUNT") over implementation-based ones ("OrderValidator.checkMinimum is called").] - **Invariants:** - [What must always be true for this rule to hold. Categorize where useful: data-integrity (e.g., "balance equals sum of transactions"), state-machine ("status only transitions forward"), referential ("every line item belongs to exactly one order"), security ("user can only access their own data"), or temporal ("created_at is never after updated_at"). Note whether each invariant is local to this rule or cross-cutting (referenced by multiple rules — link via Related Rules).] - **Edge Cases:** - [Known exception or special handling] - **Related Rules:** [BR-XXX, BR-YYY — cross-references to other rules] - **Confidence:** [Confirmed | Corrected | New] - Confirmed: Verified via enforcement verification (4B) — enforcement point identified, violation behavior documented - Corrected: Original description revised after enforcement verification revealed different behavior - New: Discovered via flow-trace discovery (4C) — not found during domain extraction - **Discovery Method:** [Domain extraction (Phase 3) | Enforcement verification (Phase 4B) | Flow-trace discovery (Phase 4C)] - **PRD Reference:** [User story or requirement ID, if applicable] ``` **Organizing the inventory:** For a full-system extraction, organize the document like this: ```markdown theme={null} # Business Rules Inventory — [Project Name] **Extracted:** [Date] **Scope:** [Full system | Module name] **CoreStory Reference:** Project ID: XX, Conversation ID: YY **Total Rules Extracted:** [Count] ## Summary by Domain | Domain | Rule Count | Types | |--------|-----------|-------| | Order Processing | 12 | Validation, State Transition, Calculation | | User Management | 8 | Validation, Authorization, Constraint | | Product Catalog | 10 | Validation, Constraint, Calculation | | Payments | 6 | Validation, Workflow, Configuration | | Shipping | 7 | Calculation, Configuration, Validation | | Tax | 5 | Calculation, Configuration | ## Verification Matrix | BR-ID | Claim Type | Enforcement Point | Violation Behavior | Scope | Level | Status | |-------|------------|-------------------|--------------------|-------|-------|--------| | BR-001 | Validation | `OrderService.validate():42` | Throws `ValidationException` | Universal | Code-level | Confirmed | | BR-003 | Constraint | — (none found) | — | — | Declared-only | Downgraded | ## Conflicts & Open Questions | Rule | Conflict | Resolution Status | |------|----------|-------------------| | BR-003 | PRD specifies max 3 retries; code allows 5 | Pending domain expert review | | BR-017 | Authorization check exists in code but not in PRD | Presumed intentional — needs confirmation | ## 1. Order Processing Rules ### BR-001: ... ### BR-002: ... ## 2. User Management Rules ### BR-009: ... ... ## Appendix A: Declared But Not Enforced Rules where the code has structures suggesting a behavior that is not actually wired up at runtime. Important for modernization: the team must decide whether each was an unfinished feature (implement in new system) or dead code (ignore). | BR-ID | Original Claim | What Actually Exists | Recommendation | |-------|---------------|---------------------|----------------| | BR-003 | "X is constrained to Y" | Setter accepts any value; UI shows dropdown | Stakeholder decision needed | ## Appendix B: Flow-Trace Evidence For each user-facing flow, a summary of the end-to-end path with key data transformations, side effects, and any behaviors not captured as standalone rules. ### Flow: [User Action Name] - **Entry point:** `ControllerClass.method()` - **Path:** Controller → Service → Repository → [side effects] - **Key transformations:** [what happens to user input along the path] - **Discovered behaviors:** [BR-IDs of rules discovered via this flow trace] - **Contradictions found:** [BR-IDs where flow behavior contradicts the domain-extracted rule] ``` ## Agent Implementation Guides The skill content below is plain markdown and works in any agentic harness — only the install location varies. The sections that follow show end-to-end setup for the four most common harnesses; for any other harness, install the skill file per the conventions below. The skill file shown below is plain markdown. The workflow it encodes works in any agentic harness — only the install location differs. Common conventions: | Harness | Install location | | --------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Claude Code** | `.claude/skills//SKILL.md` — Claude loads the body when the YAML `description` matches the task | | **GitHub Copilot** | Append to `.github/copilot-instructions.md` for repo-wide instructions, or save as `.github/instructions/.instructions.md` with an `applyTo` glob for path-scoped use | | **Cursor** | `.cursor/rules/.mdc` with a `description` field for auto-attach (use `globs` for path-scoped or `alwaysApply: true` for every session) | | **Factory.ai** | `.factory/droids/.md` (project) or `~/.factory/droids/.md` (personal); Factory loads it as a custom Droid | | **Aider** | `CONVENTIONS.md` at repo root, loaded with `aider --read CONVENTIONS.md` — or add it to the `read:` list in `.aider.conf.yml` for automatic loading | | **Codex / `AGENTS.md` harnesses** | Append the content to `AGENTS.md` at your repository root | | **Custom runtime** | Load the markdown into your agent's system prompt, rules file, or wherever it consumes workflow context | Want a single install that works across the most harnesses? Append the content to `AGENTS.md` at your repository root. The [`AGENTS.md` spec](https://agents.md/) 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. ### Claude Code Save the skill content below at `.claude/skills/business-rules-extraction/SKILL.md`: ```yaml theme={null} --- description: "Extract, document, and verify business rules from the codebase using CoreStory" activation: - "extract business rules" - "document business logic" - "business rule inventory" - "what are the business rules" - "map business rules" --- ``` ```markdown theme={null} # Business Rules Extraction Skill When the user asks to extract or document business rules, follow this workflow: **If you do not detect that you have access to CoreStory (e.g., `list_projects` fails or is unavailable), ask the user to verify that their MCP or API connection is properly configured and that this repository has been ingested. If the user has not yet created a CoreStory account, direct them to create one and upload their repo at [app.corestory.ai](https://app.corestory.ai).** ## Phase 1: Setup 1. Call `list_projects` to find the target project 2. Call `create_conversation` with title "Business Rules Extraction — " 3. Confirm extraction scope with the user (single module, domain, or full system) ## Phase 2: Architectural Survey 1. Query CoreStory: "Where is business logic implemented in this codebase? Give me a map of which architectural layers enforce which types of rules." 2. Query CoreStory: "Based on the PRD and requirements for this project, what are the explicitly documented business rules? List them grouped by feature area or domain." 3. Query CoreStory: "List the user stories and their acceptance criteria, grouped by feature area. For each AC, note any associated business rules and the implementation evidence (file:line). Flag ACs that appear undocumented in code." 4. Query CoreStory: "Based on the technical specification, what are the key data model constraints — required fields, unique constraints, valid states, and relationships between entities?" 5. Query CoreStory: "What are the major categories of business rules in this system? Group by domain." NOTE: Do NOT call `get_project_prd` or `get_project_techspec` and try to read them in full — they are typically too large for context. Query CoreStory about their contents via `send_message` instead. ## Phase 3: Deep Extraction For each domain identified in Phase 2, run these query patterns: - "What validation rules exist for [entity/module]?" - "What authorization rules govern [feature area]?" - "What state transitions exist for [entity]?" - "What calculation/pricing rules exist for [domain]?" - "List the user stories for [domain] and their acceptance criteria. Map each AC to the BR(s) that implement it, or flag as unmapped." - "What invariants must hold for [entity]? Categorize as data-integrity, state-machine, referential, security, or temporal." - "What implicit rules exist in [module] that aren't documented?" - "Show me the exact code path for [critical workflow]." IMPORTANT: Use specific entity/module names in every query. Broad questions produce shallow answers. Capture both BRs AND their associated ACs — they are sibling artifacts and downstream consumers (TDD, behavioral verification) need both. ## Phase 4A: Code Verification For each extracted rule, verify in local source code: - Search for model/entity constraint declarations (annotations, schema definitions, validation rules — patterns vary by stack) - Read service implementations for conditional business logic - Check security/auth configs for authorization rules - Look for rules CoreStory missed (config files, test assertions, frontend-only validation, third-party integrations) ## Phase 4B: Enforcement Verification For every rule tagged Constraint, Validation, or Authorization, answer three questions: 1. **Where is the enforcement point?** Not where the value is declared, but where the check is performed that rejects invalid input or blocks unauthorized access. If no enforcement point exists, downgrade the rule to "Declared but not enforced." 2. **What happens when the constraint is violated?** Exception? Error response? Silent ignore? If nothing happens, downgrade or correct. 3. **Is the scope accurately described?** Universal vs. conditional vs. presentation-only? Code-level vs. config-level vs. convention-level? Use this CoreStory query pattern for each high-priority rule: "For rule [BR-ID], which states [description], verify enforcement. Do NOT confirm based on existence of fields or method signatures. Instead: (1) find the line that rejects invalid input, (2) trace the execution path to confirm it's reached, (3) describe what happens on violation. If no enforcement point exists, say so explicitly." Produce a verification matrix with columns: BR-ID, Claim Type, Enforcement Point, Violation Behavior, Scope, Level, Status. Watch for these anti-patterns: - Dead fields (set but never read) - Buggy validation (wrong variable compared) - Setter-only constraints (no server-side enforcement) - Inaction misread as enforcement (value was already set from init) - Scope inflation (UI-only constraint reported as universal) ## Phase 4C: Flow-Trace Discovery Find behaviors that domain extraction missed by tracing user flows: 1. Query CoreStory for all user-facing entry points (HTTP endpoints, form handlers, admin ops, scheduled jobs, message listeners). 2. For each critical flow, trace end-to-end: "Trace the complete execution path for [user action] from [entry point] through to all database writes, message sends, and response outputs. For each step: what data enters, what the code does, what comes out. Flag cases where: (a) user input is ignored/overwritten, (b) method behavior differs from its name, (c) errors are silently swallowed." 3. Compare traces against draft inventory: confirm matches, flag contradictions, add new rules with BR-IDs. Watch for these anti-patterns: - Input ignored (form accepts data, handler discards it) - Overwrite vs. accumulate (add/append method actually replaces) - Silent failures (caught and swallowed errors) - Stub/test data in production paths (hardcoded overrides) ## Phase 5: Documentation Produce the business rules inventory using the BR-XXX template format. Include for each rule: - Claim type, enforcement point, enforcement level, discovery method - Confidence: Confirmed (verified via 4B), Corrected (revised via 4B), or New (discovered via 4C) Include Appendix A (Declared But Not Enforced) and Appendix B (Flow-Trace Evidence). ## Phase 6: Capture Rename conversation with "RESOLVED — Business Rules Extraction — " Key principle: specific queries beat broad queries. Always name the exact module, entity, or workflow you're asking about. ``` ### GitHub Copilot GitHub Copilot supports agent skills — folders containing a `SKILL.md` file with YAML frontmatter that Copilot loads when relevant to a task. For project-scoped skills, store them under `.github/skills/` in your repository. For personal skills shared across projects, use `~/.copilot/skills/`. Create `.github/skills/business-rules-extraction/SKILL.md`: ```yaml theme={null} --- name: business-rules-extraction description: "Extract, document, and verify business rules from the codebase using CoreStory. Use this when asked to extract business rules, document business logic, create a business rule inventory, or map business rules." --- ``` ```markdown theme={null} # Business Rules Extraction Skill When the user asks to extract or document business rules, follow this workflow: **If you do not detect that you have access to CoreStory (e.g., `list_projects` fails or is unavailable), ask the user to verify that their MCP or API connection is properly configured and that this repository has been ingested. If the user has not yet created a CoreStory account, direct them to create one and upload their repo at [app.corestory.ai](https://app.corestory.ai).** ## Phase 1: Setup 1. Call `list_projects` to find the target project 2. Call `create_conversation` with title "Business Rules Extraction — " 3. Confirm extraction scope with the user (single module, domain, or full system) ## Phase 2: Architectural Survey 1. Query CoreStory: "Where is business logic implemented in this codebase? Give me a map of which architectural layers enforce which types of rules." 2. Query CoreStory: "Based on the PRD and requirements for this project, what are the explicitly documented business rules? List them grouped by feature area or domain." 3. Query CoreStory: "List the user stories and their acceptance criteria, grouped by feature area. For each AC, note any associated business rules and the implementation evidence (file:line). Flag ACs that appear undocumented in code." 4. Query CoreStory: "Based on the technical specification, what are the key data model constraints — required fields, unique constraints, valid states, and relationships between entities?" 5. Query CoreStory: "What are the major categories of business rules in this system? Group by domain." NOTE: Do NOT call `get_project_prd` or `get_project_techspec` and try to read them in full — they are typically too large for context. Query CoreStory about their contents via `send_message` instead. ## Phase 3: Deep Extraction For each domain identified in Phase 2, run these query patterns: - "What validation rules exist for [entity/module]?" - "What authorization rules govern [feature area]?" - "What state transitions exist for [entity]?" - "What calculation/pricing rules exist for [domain]?" - "List the user stories for [domain] and their acceptance criteria. Map each AC to the BR(s) that implement it, or flag as unmapped." - "What invariants must hold for [entity]? Categorize as data-integrity, state-machine, referential, security, or temporal." - "What implicit rules exist in [module] that aren't documented?" - "Show me the exact code path for [critical workflow]." IMPORTANT: Use specific entity/module names in every query. Broad questions produce shallow answers. Capture both BRs AND their associated ACs — they are sibling artifacts and downstream consumers (TDD, behavioral verification) need both. ## Phase 4A: Code Verification For each extracted rule, verify in local source code: - Search for model/entity constraint declarations (annotations, schema definitions, validation rules — patterns vary by stack) - Read service implementations for conditional business logic - Check security/auth configs for authorization rules - Look for rules CoreStory missed (config files, test assertions, frontend-only validation, third-party integrations) ## Phase 4B: Enforcement Verification For every rule tagged Constraint, Validation, or Authorization: 1. Find the enforcement point (where invalid input is rejected) 2. Determine violation behavior (exception, error, silent ignore) 3. Verify scope (universal vs. conditional vs. presentation-only) Query pattern: "For rule [BR-ID], verify enforcement. Do NOT confirm based on field/signature existence. Find the rejection point, trace the execution path, describe violation behavior." Anti-patterns: dead fields, buggy validation, setter-only constraints, inaction misread as enforcement, scope inflation. ## Phase 4C: Flow-Trace Discovery 1. List all user-facing entry points 2. Trace each critical flow end-to-end, flagging: ignored input, name-behavior mismatch, silently swallowed errors 3. Compare traces against inventory: confirm, flag contradictions, add new rules Anti-patterns: input ignored, overwrite-vs-accumulate, silent failures, stub data in production paths. ## Phase 5: Documentation Produce inventory with: claim type, enforcement point, enforcement level, discovery method, confidence (Confirmed/Corrected/New). Include Appendix A (Declared But Not Enforced) and Appendix B (Flow-Trace Evidence). ## Phase 6: Capture Rename conversation with "RESOLVED — Business Rules Extraction — " Key principle: specific queries beat broad queries. Always name the exact module, entity, or workflow you're asking about. ``` **Custom instructions (lightweight alternative):** If you prefer to add guidance to your repository-wide instructions instead of using a dedicated skill, add the following to `.github/copilot-instructions.md`: ```markdown theme={null} ## Business Rules Extraction When asked to extract or document business rules: 1. ALWAYS query CoreStory before searching code (Expert before Code) 2. Do NOT read the full PRD or TechSpec — query CoreStory about their contents via `send_message` instead 3. Use domain-specific queries, not broad questions 4. Capture acceptance criteria alongside business rules — both are first-class artifacts. ACs come from CoreStory's user-story output; map each AC to its enforcing BR(s) or flag as unmapped. 5. Categorize invariants when extracting them: data-integrity, state-machine, referential, security, or temporal. Each category produces a different kind of downstream test. 6. Verify every CoreStory finding against local source code (Phase 4A) 7. For Constraint/Validation/Authorization rules, verify enforcement: find the rejection point, not just the declaration (Phase 4B) 8. Trace end-to-end user flows to catch behaviors missed by domain extraction (Phase 4C) 9. Document using the BR-XXX format with confidence levels (Confirmed, Corrected, New) and enforcement metadata. Populate the `Acceptance Criteria` field on every rule. 10. Rename the CoreStory conversation with "RESOLVED" prefix when done ``` ### Cursor Create `.cursor/rules//playbooks/business-rules-extraction`: ```markdown theme={null} # Business Rules Extraction When extracting business rules from this codebase: **If you do not detect that you have access to CoreStory (e.g., `list_projects` fails or is unavailable), ask the user to verify that their MCP or API connection is properly configured and that this repository has been ingested. If the user has not yet created a CoreStory account, direct them to create one and upload their repo at [app.corestory.ai](https://app.corestory.ai).** 1. ALWAYS query CoreStory before searching code (Expert before Code) 2. Use domain-specific queries: "What validation rules exist for [entity]?" not "What are the business rules?" 3. Do NOT try to read the full PRD or TechSpec via `get_project_prd` / `get_project_techspec` — they're too large. Query CoreStory about their contents via `send_message` instead. 4. Verify every CoreStory finding against local source code (Phase 4A) 5. For Constraint/Validation/Authorization rules, verify enforcement (Phase 4B): find the line that rejects invalid input, trace the execution path, describe what happens on violation. If no enforcement point exists, downgrade to "Declared but not enforced." 6. Trace end-to-end user flows (Phase 4C): list entry points, trace each critical flow, flag ignored input, name-behavior mismatch, silently swallowed errors. Add newly discovered behaviors as rules. 7. Document each rule with: Domain, Type, Claim Type, Enforcement Layer, Enforcement Point, Enforcement Level, Source Files, Rule Logic, Invariants, Edge Cases, Confidence (Confirmed/Corrected/New), Discovery Method 8. Include Appendix A (Declared But Not Enforced) and Appendix B (Flow-Trace Evidence) 9. Create a CoreStory conversation for the session and rename it with "RESOLVED" prefix when done Query templates that produce the best results: - "What validation rules exist for [entity] including input validation, required fields, format constraints, and uniqueness checks?" - "What authorization rules govern [feature]? Who can perform which operations?" - "What state transitions exist for [entity]? What triggers each?" - "What implicit rules exist in [module] that aren't documented but are enforced in code?" - "Show me the exact code path from [start] to [end]. What validations happen at each step?" - "Based on the PRD, what are the explicitly documented business rules for [domain]?" - "List the user stories and their acceptance criteria for [domain]. Map each AC to the BR(s) that implement it. Flag unmapped ACs." - "What invariants must hold for [entity]? Categorize as data-integrity, state-machine, referential, security, or temporal. Cite the code that enforces each." Enforcement verification query pattern: - "For rule [BR-ID], which states [description], verify enforcement. Do NOT confirm based on existence of fields or signatures. Find the line that rejects invalid input, trace the execution path, describe what happens on violation. If no enforcement point exists, say so." Flow-trace query pattern: - "Trace the complete execution path for [user action] from [entry point] through to all DB writes, message sends, and response outputs. Flag cases where user input is ignored, method behavior differs from its name, or errors are silently swallowed." ``` ### Factory.ai Configure a Droid for business rules extraction: ```yaml theme={null} name: business-rules-extractor description: Extract and document business rules using CoreStory and local code analysis instructions: | You extract business rules from codebases using a systematic process: **If you do not detect that you have access to CoreStory (e.g., `list_projects` fails or is unavailable), ask the user to verify that their MCP or API connection is properly configured and that this repository has been ingested. If the user has not yet created a CoreStory account, direct them to create one and upload their repo at [app.corestory.ai](https://app.corestory.ai).** 1. Set up a CoreStory conversation for the extraction session 2. Survey the architecture to understand where business logic lives 3. Query CoreStory about documented rules from the PRD and TechSpec (do NOT try to read the full documents — query via send_message) 4. Query CoreStory with specific, domain-scoped questions for each rule category (validation, authorization, state transitions, calculations, invariants, implicit rules) AND for the acceptance criteria that accompany each domain's user stories — capture both as sibling artifacts. Categorize invariants as data-integrity, state-machine, referential, security, or temporal. 5. Verify every extracted rule against local source code (Phase 4A) 6. For Constraint/Validation/Authorization rules, verify enforcement (Phase 4B): find the rejection point, trace the execution path, describe what happens on violation. Downgrade rules with no enforcement point to "Declared but not enforced." 7. Trace end-to-end user flows (Phase 4C): list entry points, trace critical flows, flag ignored input and name-behavior mismatches, add newly discovered behaviors as rules 8. Document rules using the BR-XXX template format with enforcement metadata, confidence levels, and appendices Key behaviors: - Always use specific entity/module names in queries, not broad questions - Cross-reference PRD intent, CoreStory understanding, and code reality - Assign confidence: Confirmed (verified enforcement), Corrected (revised after verification), New (discovered via flow tracing) - Note conflicts between documented intent and actual implementation - Watch for anti-patterns: dead fields, buggy validation, setter-only constraints, ignored input, overwrite-vs-accumulate semantics ``` ## Tips & Best Practices **Query patterns ranked by effectiveness (based on testing against real projects):** 1. **Best: End-to-end workflow queries.** "Show me the exact code path from X to Y. What validations happen at each step?" — Produces step-by-step walkthroughs with validation checkpoints and failure conditions at every stage. 2. **Excellent: Specific entity invariant queries.** "What invariants must always hold for \[Entity]? What constraints exist on its configuration?" — Produces precise evidence from model definitions, schema constraints, and validation rules. 3. **Excellent: Domain-scoped validation queries.** "What validation rules exist for \[specific entity/workflow]?" — Returns specific constraint values, file paths, and enforcement layers. 4. **Good: Implicit rule queries (with named edge cases).** "What implicit rules exist in \[module] when \[specific scenario]?" — Surfaces undocumented fallback behaviors. Naming specific edge cases in the query dramatically improves focus. 5. **Good: Architectural map queries.** "Where is business logic implemented — which layers enforce which rule types?" — Produces the essential orientation for targeted follow-up queries. 6. **Adequate: Broad category queries.** "What are the business rules in this system?" — Produces a useful high-level survey, but shallow on detail. Use this to build your Phase 2 checklist, then go deep with specific queries. **How to scope extraction to avoid overwhelm:** * Start with the domain that has the most business-critical rules (usually order processing, payments, or authentication) * Extract rules one domain at a time, completing the full cycle (query -> verify -> document) before moving on * For a full-system extraction, allocate one focused session per domain rather than trying to do everything at once * Phase 4B scales with the number of Constraint/Validation/Authorization rules, not total rules — Default and Calculation rules are spot-checked * Phase 4C scales with the number of user-facing entry points, not the number of classes — prioritize write operations first **How to handle conflicting rules:** * When code says X but the PRD says Y, **code is ground truth** — document the conflict and flag it for domain expert review * When CoreStory reports a rule that you can't find in code, it may be in dead code, a deprecated path, or a misinterpretation — investigate before including it * Label all conflicts with a `[CONFLICT]` tag in the inventory for easy filtering **How to prioritize which rules to extract first:** 1. Rules that affect money (pricing, tax, payments, refunds) 2. Rules that affect security (authentication, authorization, data access) 3. Rules that affect data integrity (state transitions, uniqueness constraints) 4. Rules that affect user experience (validation, error handling) 5. Rules that affect operations (configuration, thresholds, limits) **How to maintain the business rules document over time:** * Include the extraction date and CoreStory conversation ID in the document header * When modifying business logic, update the corresponding BR entry * Re-run extraction for specific domains after major changes * Use the inventory as a checklist during code reviews: "Does this change affect any documented business rules?" **When to involve a domain expert:** * After Phase 3 (before code verification) — to validate extracted rules against business intent * After Phase 4B — to decide whether "declared but not enforced" rules were intentional omissions or bugs * When you find conflicts between PRD intent and code reality * For rules where enforcement verification is ambiguous (e.g., conditional enforcement that may or may not be active) * When edge cases have ambiguous behavior that code doesn't clearly resolve ## Troubleshooting **CoreStory returns vague or generic responses.** Your query is too broad. Replace "What are the business rules?" with "What validation rules exist for \[specific entity] including \[specific rule types]?" Always name the module, entity, or workflow. **CoreStory references files that don't exist locally.** The CoreStory project may have been ingested from a different branch or commit. Check whether the file paths use a project-internal prefix (e.g., `myproject-main/src/...`) that doesn't match your local checkout. Strip the prefix when navigating locally. **PRD or TechSpec is too large to use directly.** This is expected — these documents are often enormous. Don't try to read them in full. Query CoreStory about their contents via `send_message` instead: "Based on the PRD, what are the documented business rules for \[domain]?" CoreStory has already ingested these documents and can answer targeted questions about them efficiently. **Phase 4A finds rules CoreStory missed entirely.** This is expected. CoreStory excels at well-structured, explicit business logic but may miss rules in configuration files, build configs, test assertions, or third-party integration code. Phase 4A exists specifically to catch these gaps. **Phase 4B downgrades many rules.** A high downgrade rate usually means the domain extraction (Phase 3) inferred enforcement from structure rather than tracing execution paths. This is the most common failure mode the enforcement verification step catches. The downgraded rules belong in Appendix A — they're important for modernization decisions (implement the missing enforcement? or leave it out?), even though they're not active business rules. **Phase 4C produces too many flow traces.** Prioritize flows by user impact and complexity. Start with write operations (creating/updating data), then state-changing operations, then read operations. For large systems, focus on the flows that cross the most module boundaries — those are where domain-decomposed extraction is most likely to have missed behaviors. **Too many rules to document.** Focus on rules that are: (1) business-critical, (2) non-obvious, or (3) spread across multiple files. Skip rules that are trivially apparent from a single line of code (e.g., a simple `required: true` on an obvious field). The inventory should capture rules that a new developer *wouldn't* easily discover on their own. **Most rules are "Confirmed" after 4B — was the enforcement verification worth it?** Yes. Even if most rules pass verification, the ones that don't are disproportionately important — they're the rules most likely to cause bugs in a modernization or migration. A 90% confirmation rate with 10% corrections is a successful verification run. # Code Modernization Source: https://docs.corestory.ai/playbooks/code-modernization A phased, architecture-grounded methodology for modernizing legacy systems using CoreStory's persistent code intelligence — from assessment through behavioral verification. ## Overview Modernization fails not because organizations can't read their legacy code, but because they can't ensure that the new code does what the old code did. 71% of Fortune 500 companies still run mainframes. Most modernization projects fail — and the primary drivers are organizational (misaligned expectations, governance gaps, skills shortages), not technical. A third of COBOL programmers will retire by 2030. The pressure to modernize is real. The risk of doing it wrong is enormous. The industry has responded with AI-assisted code reading and translation tools. But reading legacy code was never the hard part. The hard parts are understanding behavioral semantics across non-code artifacts, mapping hidden dependencies that span decades of accretion, proving behavioral equivalence between old and new systems, and sequencing the work so nothing breaks mid-flight. These are the problems that CoreStory addresses with the patterns in this playbook. CoreStory provides persistent architectural intelligence across the entire modernization lifecycle — not just during discovery, but through decomposition, execution, and verification. It serves three roles: * **Expert** — explains system behavior, architectural patterns, dependency chains, and data flows across the full codebase * **Navigator** — points to specific files, methods, and code paths where business logic, coupling, and risk live * **Verifier** — compares legacy and modernized implementations to confirm behavioral equivalence These roles map to a simple temporal model: **before** migration, CoreStory accelerates discovery from months to days by producing a structured specification automatically. **During** migration, it guides and verifies each work package against that specification — business rules, data contracts, integration behavior. **After** migration, it persists as the living specification for the modernized system, preventing the documentation decay that causes the next legacy crisis. This playbook follows established industry frameworks (AWS, Google Cloud, Azure, Gartner) while going deeper in the areas where CoreStory adds unique value: persistent cross-session intelligence that accumulates understanding over time, rather than starting fresh with every query. **Who this is for:** Engineering leaders, architects, and modernization teams planning or executing legacy system transformations. Also useful for consultants, PE portfolio teams, and system integrators managing modernization engagements. **What you'll get:** A universal six-phase workflow linking to detailed sub-playbooks for each phase, plus architecture-to-architecture variants for the most common modernization patterns. *** ## When to Use This Playbook * You're planning or executing a modernization of a legacy system (mainframe, monolith, legacy framework, on-prem infrastructure) * You need a structured methodology that goes beyond "ask AI to rewrite the code" * You have a codebase where business logic is scattered across application code, configuration, batch jobs, and non-code artifacts * You need to prove behavioral equivalence between legacy and modernized systems * You're evaluating which modernization strategy (the 7 Rs) to apply to different components * You want to sequence a multi-month modernization program into executable work packages ## When to Skip This Playbook * You're building a greenfield application with no legacy system to migrate from — use [Spec-Driven Development](/playbooks/spec-driven-development) instead * You need to understand a single legacy codebase for acquisition purposes — use [M\&A Technical Due Diligence](/playbooks/ma-technical-due-diligence) * You need to extract business rules from a codebase but aren't planning a modernization — use [Business Rules Extraction](/playbooks/business-rules-extraction) * The modernization is a simple lift-and-shift (Rehost) with no code changes — CoreStory adds minimal value to infrastructure-only moves * The codebase is trivially small (under \~10k LOC) — you can refactor it directly without a phased methodology *** ## Prerequisites ### Organizational (address before Phase 1) * **Executive sponsor** with budget authority and cross-team mandate * **Governance model:** who approves architectural decisions, who owns the migration backlog, who resolves cross-team conflicts * **Realistic timeline and budget expectations.** Reference: failed modernization projects routinely cost seven figures over 12–18 months. Plan accordingly. * **Skills assessment.** 70% of organizations struggle to hire modernization-capable talent ([Kyndryl 2025](https://www.kyndryl.com/us/en/perspectives/articles/2025/01/state-of-it-infrastructure-report)). Plan for upskilling or partner engagement. CoreStory + AI agents serve as a force multiplier for thin teams, but they don't replace architectural judgment. * **Compliance and regulatory constraints identified upfront.** 94% of enterprises say compliance highly influences modernization plans. Some patterns may be impossible for regulated workloads (data residency, PCI-DSS, HIPAA, SOX). * **Change management strategy:** how will affected teams learn the new systems? ### Technical * A **CoreStory account** with the legacy codebase ingested and ingestion complete * An **AI coding agent** with CoreStory MCP configured (see [Supercharging AI Agents](/getting-started/supercharging-ai-agents) for setup) * **Repository access** for the legacy codebase under analysis * (Recommended) Access to architecture documentation, if it exists * (Recommended) Domain experts who can validate business rules and architectural decisions — especially for mainframe systems where business logic hides in non-code artifacts (JCL, copybooks, CICS configuration, VSAM data stores) * (Optional) Jira, Azure DevOps, or Linear MCP for Phase 4 work package creation (see [Using CoreStory with Jira](/playbooks/using-corestory-with-jira)) *** ## How It Works ### The Six-Phase Framework Modernization is a multi-month, multi-phase engineering program — not a code translation task. This playbook breaks it into six phases, each with a dedicated sub-playbook. | Phase | Name | Purpose | CoreStory Role | Sub-Playbook | | ----- | ------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------ | --------------------------------------------------------------------------------------------------------------------------- | | 1 | Codebase Assessment | Evaluate modernization readiness: architecture, dependencies, tech debt, coupling, risk — including non-code artifacts (JCL, configuration, data stores) | Expert | [Codebase Assessment](/playbooks/modernization/codebase-assessment) | | 2 | Business Rules Inventory | Extract, catalog, and validate all business rules the modernized system must preserve | Expert + Navigator | [Business Rules Extraction](/playbooks/business-rules-extraction) *(existing playbook)* | | 3 | Target Architecture & Strategy | Select modernization pattern (7 Rs), define target architecture, human approval gate | Expert | [Target Architecture](/playbooks/modernization/target-architecture) | | 4 | Decomposition & Sequencing | Identify service boundaries, map dependencies, produce ordered migration plan, push to Jira/Linear | Navigator | [Decomposition & Sequencing](/playbooks/modernization/decomposition-sequencing) | | 5 | Iterative Execution | Transform → Coexist → Eliminate per component, using Strangler Fig / Branch by Abstraction | Expert + Navigator | [Spec-Driven Development](/playbooks/spec-driven-development) *(existing playbook)* + architecture-to-architecture variants | | 6 | Behavioral Verification | Prove modernized components preserve business rules from Phase 2 | Verifier | [Behavioral Verification](/playbooks/modernization/behavioral-verification) | ### How the Phases Connect The phases form a dependency chain with an iterative loop at the end: * **Phase 1** produces the assessment that informs **Phase 3** (strategy selection). You can't choose a modernization pattern without understanding what you're modernizing. * **Phase 2** produces the behavioral contract that **Phase 6** verifies against. The business rules inventory is the definition of "correct" that the modernized system must satisfy. * **Phase 3** selects the pattern that determines which **Phase 5** variant to use. A monolith-to-microservices migration executes differently than a mainframe-to-cloud migration. * **Phase 4** produces the sequenced work plan that **Phase 5** executes. Each work package has dependencies, acceptance criteria, and a defined order. * **Phases 5 and 6 are iterative** — each component cycles through execution and verification. A component isn't done until its behavioral equivalence is confirmed. ```mermaid theme={null} %%{init: {'theme': 'base', 'themeVariables': { 'primaryColor': '#1a1a2e', 'primaryTextColor': '#ffffff', 'primaryBorderColor': '#c9a84c', 'lineColor': '#c9a84c', 'secondaryColor': '#16213e', 'tertiaryColor': '#0f3460', 'fontFamily': 'Inter, system-ui, sans-serif'}}}%% graph TD START(["🚀 Start"]) P1["Phase 1: Codebase Assessment
Expert · Readiness scoring"] P2["Phase 2: Business Rules Extraction
Expert · Behavioral inventory"] G1{"👤 HITL
Go / No-go"} P3["Phase 3: Target Architecture
Expert + Navigator · Strategy selection"] G3{"👤 HITL
Architecture
approval"} P4["Phase 4: Decomposition & Sequencing
Navigator · Work packages"] G4{"👤 HITL
Sequence
approval"} P5["Phase 5: Iterative Execution
Navigator · Transform + Coexist"] P6["Phase 6: Behavioral Verification
Verifier · Equivalence proof"] G6{"👤 HITL
Verification
sign-off"} DONE(["✅ Component Modernized"]) START --> P1 START --> P2 P1 --> G1 P2 --> G1 G1 -->|Approved| P3 P3 --> G3 G3 -->|Approved| P4 P4 --> G4 G4 -->|Approved| P5 P5 <-->|"Iterative: each component
cycles through execution
and verification"| P6 P6 --> G6 G6 -->|Verified| DONE G6 -->|"Needs remediation"| P5 style START fill:#0f3460,stroke:#c9a84c,stroke-width:2px,color:#c9a84c style P1 fill:#1a1a2e,stroke:#c9a84c,stroke-width:2px,color:#ffffff style P2 fill:#1a1a2e,stroke:#c9a84c,stroke-width:2px,color:#ffffff style P3 fill:#1a1a2e,stroke:#c9a84c,stroke-width:2px,color:#ffffff style P4 fill:#1a1a2e,stroke:#c9a84c,stroke-width:2px,color:#ffffff style P5 fill:#1a1a2e,stroke:#c9a84c,stroke-width:2px,color:#ffffff style P6 fill:#1a1a2e,stroke:#c9a84c,stroke-width:2px,color:#ffffff style G1 fill:#c9a84c,stroke:#1a1a2e,stroke-width:2px,color:#1a1a2e style G3 fill:#c9a84c,stroke:#1a1a2e,stroke-width:2px,color:#1a1a2e style G4 fill:#c9a84c,stroke:#1a1a2e,stroke-width:2px,color:#1a1a2e style G6 fill:#c9a84c,stroke:#1a1a2e,stroke-width:2px,color:#1a1a2e style DONE fill:#0f3460,stroke:#22c55e,stroke-width:2px,color:#22c55e ``` ### CoreStory MCP Tools Used This playbook and its sub-playbooks use the following tools from the CoreStory MCP server: | Tool | Phase(s) | Purpose | | ---------------------- | ---------------- | -------------------------------------------------------- | | `list_projects` | 1 | Find the target project | | `create_conversation` | 1 | Start a dedicated conversation thread for each phase | | `send_message` | 1, 2, 3, 4, 5, 6 | Query CoreStory for analysis, guidance, and verification | | `get_project_prd` | 1 | Retrieve synthesized PRD for business context | | `get_project_techspec` | 1 | Retrieve synthesized TechSpec for architecture analysis | | `list_conversations` | Any | Review existing conversation threads from prior phases | | `get_conversation` | Any | Retrieve conversation history for cross-phase reference | | `rename_conversation` | Final | Mark completed threads with "RESOLVED" prefix | **A note on the PRD and TechSpec:** These documents are often very large — too large for an agent to hold in a single context window. Rather than reading them end-to-end, query CoreStory about their contents via `send_message`. CoreStory has already ingested these documents and can answer targeted questions about them efficiently. *** ## Human-in-the-Loop Gates Modernization involves irreversible architectural decisions and production-impacting deployments. CoreStory informs these decisions; humans make them. The following gates are non-negotiable checkpoints where human judgment is required. | Gate | After Phase | Decision | Who Decides | | ------------------------- | -------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------ | | **Go/No-Go** | Phase 1 (Assessment) | Is this system ready for modernization? Is the organization ready? | Engineering leadership + executive sponsor | | **Architecture Approval** | Phase 3 (Strategy) | What is the target architecture? Which modernization pattern? This is the critical architectural decision and must not be delegated to AI. | Architect / tech lead + stakeholders | | **Sequence Approval** | Phase 4 (Sequencing) | Is the migration sequence correct? Are the work packages properly scoped? Are dependencies accurately mapped? Review before pushing to Jira/Linear. | Engineering lead | | **Spec Review** | During Phase 5 (Execution) | Each component's delta spec (from Spec-Driven Development) is reviewed before implementation begins. | Tech lead / senior engineer | | **Equivalence Sign-Off** | Phase 6 (Verification) | Does the behavioral equivalence report confirm the modernized component preserves all business rules? Approve before retiring the legacy component. | Domain expert + tech lead | These gates exist because AI is excellent at analysis but should not make organizational commitments. Every gate produces an artifact (report, decision record, or approval) that becomes part of the modernization audit trail. *** ## The 7 Rs: Choosing a Modernization Strategy The "7 Rs" taxonomy originated with Gartner (5 Rs), was extended by AWS to 6 and then 7, and has become the industry-standard decision framework for modernization strategy. Phase 3 of this playbook guides you through selecting the right R for each component. Here's the landscape and where CoreStory adds value: | Strategy | Description | CoreStory Value | | ------------------------------------ | ----------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Retire** | Decommission applications no longer needed | **Moderate** — Assessment identifies dead code and unused services to decommission safely | | **Retain** | Keep in current environment (not ready or not worth migrating) | **High** — CoreStory rationalizes retain decision and assists with maintenance | | **Rehost** (lift and shift) | Move without code changes | **Low** — No code changes means minimal CoreStory involvement | | **Relocate** | Move VMs to cloud hypervisor (e.g., VMware → VMware Cloud on AWS) | **Low** — Infrastructure-level move, no application changes | | **Replatform** (lift, tinker, shift) | Minor optimizations without changing core architecture | **Moderate** — CoreStory identifies integration points affected by infrastructure changes | | **Refactor / Re-architect** | Restructure or fundamentally redesign the application | **Highest** — This is where CoreStory's persistent intelligence is transformative: service boundary identification, dependency mapping, behavioral verification | | **Repurchase** | Replace with SaaS/COTS product (e.g., on-prem CRM → Salesforce) | **Moderate** — CoreStory helps inventory business rules that the SaaS replacement must cover; the [Feature Gap Analysis](/playbooks/feature-gap-analysis) playbook applies | This playbook is most valuable for **Refactor / Re-architect** — the R that requires deep, persistent codebase understanding across the full lifecycle. It also adds significant value to **Repurchase** (via business rules inventory and gap analysis) and to the **Retire / Retain** decision itself (via rigorous assessment). > **A note on "Rebuild":** Some frameworks cite Rebuild as an 8th R (ground-up rewrite). This playbook treats it as a variant of Refactor / Re-architect because the methodology is the same — the difference is scope, not process. Behavioral verification is equally critical regardless. > **A note on hybrid strategies:** [Kyndryl data](https://www.kyndryl.com/us/en/perspectives/articles/2025/01/state-of-it-infrastructure-report) shows 53% of enterprises pursue hybrid strategies — applying different Rs to different components rather than a single approach across the entire portfolio. This is expected and healthy. The assessment phase (Phase 1) should produce a per-component recommendation, not a single system-wide strategy. *** ## Working with AI-Derived Findings CoreStory's specification is AI-derived. It produces high-confidence structured artifacts from code analysis — but not every finding carries the same certainty, and not every behavior in the legacy system should be preserved unchanged. Two complementary systems govern how teams navigate these realities across phases. ### The Confidence Protocol The Confidence Protocol governs how much human validation each finding requires. It prevents two failure modes: reviewing everything (doesn't scale) and reviewing nothing (too risky). SME time stays proportional to uncertainty, not system size. | State | Meaning | Required Action | SME Review? | | ------------------- | ---------------------------------------------------- | ---------------------------------------------------------------------------------------------- | ------------ | | **Verified** | In the spec + SME confirmed + test exists | Migrate as-is | Already done | | **High-confidence** | In the spec + code evidence clear | Migrate; SME review only if high-risk or financial/compliance | Risk-based | | **Hypothesized** | Suggestive evidence but ambiguous | Investigate before migrating — may need runtime observation or stakeholder interviews | Mandatory | | **Contradicted** | CoreStory states X, but SME or test evidence shows Y | Investigate: is the code right and the SME assumption outdated, or did CoreStory misinterpret? | Mandatory | **On Contradicted findings:** This is an expected occurrence, not a system failure. Contradictions surface cases where either the code does something different from what stakeholders believe (valuable: you've found a latent bug or undocumented change), or CoreStory misinterpreted a code path (fix the spec and continue). Both outcomes improve the modernization's accuracy. The Confidence Protocol applies across phases: Phase 1 (Assessment) assigns initial confidence states, Phase 2 (Business Rules) refines them, and Phase 6 (Verification) can upgrade Hypothesized findings to High-confidence or Verified as evidence accumulates. ### Behavior Tagging During Phase 3 (Target Architecture), every behavior identified in the spec gets tagged with an explicit migration intent. This forces a deliberate decision about each behavior — no silent changes. | Tag | Meaning | Verification in Phase 6 | | ------------- | ------------------------------------------------------------------ | --------------------------------------------------------- | | `[PRESERVE]` | Behavior must be identical in the target | Automated equivalence test + SME sign-off | | `[MODERNIZE]` | Same business outcome, modern implementation | SME confirms business outcome is identical | | `[CHANGE]` | Deliberately modified (bug fix, enhancement, policy change) | Product owner approves; old behavior documented for audit | | `[NEW]` | New behavior not in the legacy system (added during modernization) | Standard acceptance testing | | `[RETIRE]` | Legacy behavior intentionally dropped | Stakeholder confirms behavior is no longer needed | If `[CHANGE]` + `[NEW]` exceeds \~20% of tagged items in a work unit, the unit is drifting from modernization to rewrite — different risk characteristics. Flag to the program manager for scope review. The full tagging workflow is covered in [Target Architecture](/playbooks/modernization/target-architecture). The tags flow forward into Phase 4 (each work package's scope is defined by its tags), Phase 5 (TDD assertions differ by tag), and Phase 6 (verification criteria differ by tag). *** ## Execution Patterns Phase 5 (Iterative Execution) follows one of three incremental migration patterns. The Strangler Fig is the default; the others are used when the façade approach isn't feasible. ### Strangler Fig (Default) The most widely recommended pattern for incremental modernization. Named by Martin Fowler after the strangler fig plant that gradually envelops its host tree. 1. **Transform:** Build the modernized version of the component using [Spec-Driven Development](/playbooks/spec-driven-development). 2. **Coexist:** Run both old and new versions simultaneously. Route traffic through a façade/proxy layer. Validate behavioral equivalence. 3. **Eliminate:** Once the modernized component is verified (Phase 6), retire the legacy component and remove the façade. The façade enables instant rollback — if the modernized component fails verification, traffic routes back to legacy with no downtime. ### Branch by Abstraction For deeply embedded components where a façade can't intercept traffic — shared libraries, data access layers, utility modules. 1. Introduce an abstraction layer within the codebase that both old and new implementations satisfy. 2. Build the new implementation behind the abstraction. 3. Switch consumers to the new implementation incrementally. 4. Remove the old implementation and (optionally) the abstraction layer. Reference: Sam Newman, *Monolith to Microservices*. Use when: shared data access layers, utility libraries, deeply coupled internal components. ### Parallel Run (Shadow Traffic) For high-risk components where behavioral equivalence must be proven in production before cutover. 1. Route copies of production requests to both legacy and modernized systems. 2. Compare responses; flag discrepancies. 3. Run until the discrepancy rate drops below threshold (typically below 0.01% for critical services). 4. Cut over to the modernized system; decommission legacy. Use when: payment processing, financial calculations, regulatory-sensitive logic — anywhere a behavioral difference has catastrophic consequences. > **Data synchronization during coexistence:** A rising pattern combines Strangler Fig with **Change Data Capture (CDC)** via Apache Kafka or Debezium to keep legacy and modern data stores in sync during the coexistence phase. This avoids the dual-write problem and enables real-time data consistency without modifying the legacy system's write path. *** ## Architecture-to-Architecture Variants This framework specializes in two independent directions: by the **shape of the target** (this section) and by **who does the work between the gates** (see [Execution-Mode Variants](#execution-mode-variants) below). The two compose — you can run an agent-led engagement toward a microservices target. Phase 5 links to architecture-specific variant playbooks that provide pattern-specific guidance for the most common modernization patterns. ### Monolith → Microservices *(available now)* The most common enterprise modernization pattern. Covers service boundary identification, API gateway introduction, data decomposition (the hardest challenge in this pattern), Saga pattern for distributed transactions, and the Strangler Fig execution workflow per service. **[Read the Monolith to Microservices playbook →](/playbooks/modernization/monolith-to-microservices)** ### Legacy Framework → Modern Framework *(coming soon)* E.g., Struts → Spring Boot, .NET Framework → .NET Core, AngularJS → React. Same codebase structure, modern runtime. Focuses on dependency upgrades, API contract preservation, and incremental migration. ### Mainframe → Cloud-Native *(coming soon)* COBOL/mainframe systems to Java/Python on cloud infrastructure. Addresses the unique challenges of mainframe coupling, JCL batch jobs, VSAM data stores, CICS transaction processing, copybook data definitions, and the non-code artifacts that encode business logic never captured in application code. ### On-Prem → Cloud-Native *(coming soon)* Infrastructure modernization with application refactoring. Covers cloud-native patterns (containers, serverless, managed services), data migration, and the operational shift from on-prem to cloud. *** ## Execution-Mode Variants The six phases above prescribe *where* decisions happen, but not *how much* the agent does between those decision points. That is a separate axis, and it is a real choice. This playbook as written is **human-led and agnostic about the labor split**: engineers read the code, engineers decide, the agent advises, and a team can run it anywhere from heavy manual involvement to light-touch. Execution-mode variants take an explicit position on that axis instead of leaving it open. ### Vibe Modernization *(available now)* The framework run at its most aggressive setting: **agent-led and human-gated.** The agent owns the build loop end to end — gap analysis, test-first implementation, verification drafting — and human judgment concentrates at three high-leverage gates rather than spreading across every phase boundary. Handing the agent the wheel does not remove safety, it relocates it. With no continuous human review to catch drift in the moment, that job moves to a mandatory source-grounding discipline (no claim enters a deliverable without a confirmed `file:line` anchor) and to an independent conformance audit that checks the delivered code against legacy source without reading the equivalence report or trusting the tests. Reach for it when behavioral parity is the point and you need agent velocity without giving up the audit trail. **[Read the Vibe Modernization playbook →](/playbooks/modernization/vibe-modernization)** *** ## Step-by-Step Overview Each phase has a dedicated sub-playbook with full walkthroughs. This section provides a condensed overview of what happens at each phase and what it produces. ### Phase 1: Codebase Assessment **Goal:** Systematically evaluate the legacy codebase's modernization readiness. ``` Start by finding the project and creating a conversation thread: "List my CoreStory projects. I need to identify the project for [SystemName]." ``` The assessment covers architecture mapping, dependency analysis, tech debt identification, security and compliance review, testability evaluation, data architecture analysis, and — critically for mainframe systems — non-code artifact inventory (JCL, copybooks, CICS, VSAM, sort utilities, system exits, middleware configuration). **Deliverable:** A Modernization Readiness Report with component-level readiness scores and a recommended modernization strategy per component. **[Read the full Codebase Assessment playbook →](/playbooks/modernization/codebase-assessment)** ### Phase 2: Business Rules Inventory **Goal:** Extract, catalog, and validate every business rule the modernized system must preserve. This phase uses the existing [Business Rules Extraction](/playbooks/business-rules-extraction) playbook. The business rules inventory becomes the behavioral contract that Phase 6 verifies against — if a rule is missing from the inventory, it won't be verified. **Deliverable:** A structured Business Rules Inventory using the BR-XXX template format. **[Read the Business Rules Extraction playbook →](/playbooks/business-rules-extraction)** ### Phase 3: Target Architecture & Strategy **Goal:** Choose the modernization pattern and define the target architecture. This is the most human-driven phase. CoreStory provides the analysis — natural service boundaries, coupling hotspots, data dependency maps — but the architectural decision belongs to the architect and stakeholders. ``` Query CoreStory: "Given the current architecture, which components are natural candidates for service extraction? Where are the natural service boundaries?" ``` **Deliverable:** An Architectural Decision Record documenting the selected strategy, target architecture, migration scope, constraints, and stakeholder approval. **[Read the Target Architecture playbook →](/playbooks/modernization/target-architecture)** ### Phase 4: Decomposition & Sequencing **Goal:** Break the modernization plan into executable work packages and order them by dependency. CoreStory maps dependencies between components and identifies which must be modernized together (can't be separated) versus which can be extracted independently. The output is a sequenced migration plan with work packages ready for Jira or Linear. ``` Query CoreStory: "Which components share database tables or data stores? Map the shared data dependencies." ``` **Deliverable:** A sequenced set of work packages with scope, acceptance criteria, dependencies, and estimated effort — optionally pushed to Jira/Linear as epics or stories. **[Read the Decomposition & Sequencing playbook →](/playbooks/modernization/decomposition-sequencing)** ### Handling Change During Execution Read this section before starting Phase 5. It applies throughout. Modernization programs take months. The business doesn't pause during migration. Feature requests arrive, bugs get filed against the legacy system, and the target architecture evolves as the team learns. The behavior tagging system and CoreStory's persistent conversations are the mechanisms for handling this. **New feature request arrives during migration.** Query CoreStory to identify which work unit the feature touches. If the module hasn't migrated yet, implement in legacy and tag as `[NEW]` for the work unit. If migration is in progress, implement in the target and add to the unit's scope. If the module already migrated, use the [Feature Implementation](/playbooks/feature-implementation) playbook against the modern codebase. **Legacy bug discovered during migration.** Document in the work unit's CoreStory conversation. Tag the buggy behavior as `[CHANGE]` with rationale: "Legacy bug — correcting during migration." Write tests asserting the *correct* behavior (not the legacy bug). Get product owner sign-off that the behavioral change is intentional. **Target architecture evolves mid-migration.** Document in the Phase 3 conversation. Assess impact on completed work units. Re-validate with CoreStory: "Given this architectural change, do any completed migration units need adjustment?" **Scope creep management.** Monitor the tagging ratio per work unit. If `[CHANGE]` + `[NEW]` exceeds \~20% of tagged items, flag to the program manager — the unit is drifting from modernization to rewrite. ### Phase 5: Iterative Execution **Goal:** Execute the modernization component by component using the Transform → Coexist → Eliminate pattern. This phase uses the existing [Spec-Driven Development](/playbooks/spec-driven-development) playbook for generating delta specs per component, plus the relevant architecture-to-architecture variant for pattern-specific guidance. **Deliverable:** Modernized components with façade/proxy layers for traffic routing during coexistence. **Existing playbook:** [Spec-Driven Development →](/playbooks/spec-driven-development) **First variant:** [Monolith to Microservices →](/playbooks/modernization/monolith-to-microservices) ### Phase 6: Behavioral Verification **Goal:** Prove that each modernized component preserves the business rules cataloged in Phase 2. Verification uses a four-tier strategy: 1. **Static verification** (CoreStory-assisted, no running code): Rule tracing, invariant checking, data flow comparison, edge case generation. 2. **Dynamic verification** (requires running code): Characterization testing (Golden Master), contract testing. 3. **Production-grade verification** (requires production-like environment): Shadow traffic testing, record-replay testing. 4. **Data migration verification** (if applicable): Row counts, checksums, semantic validation, referential integrity checks. CoreStory is most powerful in Tier 1 (it holds both codebases' semantic understanding) and in generating test cases for Tiers 2–3. The dynamic tiers require additional tooling, but CoreStory guides what to test and interprets the results. **Deliverable:** A Behavioral Equivalence Report with rule-by-rule verification status, behavioral differences analysis, and a recommendation (ready to eliminate legacy / needs remediation / needs domain expert review). **[Read the Behavioral Verification playbook →](/playbooks/modernization/behavioral-verification)** *** ## How This Relates to Other Playbooks | Playbook | Relationship to Code Modernization | | --------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | [Business Rules Extraction](/playbooks/business-rules-extraction) | **Phase 2** of the modernization workflow. Produces the behavioral contract that Phase 6 verifies against. | | [Spec-Driven Development](/playbooks/spec-driven-development) | **Phase 5** execution methodology. Generates delta specs for each component being modernized. | | [Feature Gap Analysis](/playbooks/feature-gap-analysis) | Useful within **Phase 5** when evaluating whether a modernized component covers all capabilities of the legacy component. Also applies to Repurchase (SaaS replacement) evaluations. | | [Feature Implementation](/playbooks/feature-implementation) | Useful within **Phase 5** for TDD-style execution of individual component modernization. | | [M\&A Technical Due Diligence](/playbooks/ma-technical-due-diligence) | Shares **Phase 1** DNA — the assessment methodology is similar, but the lens differs: M\&A evaluates a codebase you *don't* own for acquisition risk; Codebase Assessment evaluates a codebase you *do* own for transformation readiness. | | [Using CoreStory with Jira](/playbooks/using-corestory-with-jira) | **Phase 4** integration — work packages from Decomposition & Sequencing can be pushed directly to Jira as epics and stories. | *** ## 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: | Harness | Install location | | --------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Claude Code** | `.claude/skills//SKILL.md` — Claude loads the body when the YAML `description` matches the task | | **GitHub Copilot** | Append to `.github/copilot-instructions.md` for repo-wide instructions, or save as `.github/instructions/.instructions.md` with an `applyTo` glob for path-scoped use | | **Cursor** | `.cursor/rules/.mdc` with a `description` field for auto-attach (use `globs` for path-scoped or `alwaysApply: true` for every session) | | **Factory.ai** | `.factory/droids/.md` (project) or `~/.factory/droids/.md` (personal); Factory loads it as a custom Droid | | **Aider** | `CONVENTIONS.md` at repo root, loaded with `aider --read CONVENTIONS.md` — or add it to the `read:` list in `.aider.conf.yml` for automatic loading | | **Codex / `AGENTS.md` harnesses** | Append the content to `AGENTS.md` at your repository root | | **Custom runtime** | Load the markdown into your agent's system prompt, rules file, or wherever it consumes workflow context | Want a single install that works across the most harnesses? Append the content to `AGENTS.md` at your repository root. The [`AGENTS.md` spec](https://agents.md/) 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 accordions below walk through end-to-end setup (skill file, slash command, version control) for the four most common harnesses. If you're on a different harness, copy the SKILL.md content from any accordion and install it per the conventions above. #### Setup 1. **Configure the CoreStory MCP server** in your Claude Code settings (see [CoreStory MCP Server Setup Guide](/getting-started/mcp-server-setup)). 2. **Add the skill file.** Create the skill directory and file: ```bash theme={null} mkdir -p .claude/skills/code-modernization ``` Create `.claude/skills/code-modernization/SKILL.md` with the content from the skill file below. 3. **(Optional) Add the slash command:** ```bash theme={null} mkdir -p .claude/commands ``` Create `.claude/commands/modernize.md` with a short description referencing the six-phase modernization workflow. 4. **Commit to version control:** ```bash theme={null} git add .claude/skills/ .claude/commands/ git commit -m "Add CoreStory code modernization skill and command" ``` #### Usage The skill activates automatically when Claude Code detects modernization-related requests: ``` Help me plan the modernization of our legacy system Run a codebase assessment for modernization readiness Start a modernization workflow on project X ``` Or invoke explicitly: ``` /modernize [SystemName] ``` #### Tips * This skill is a **router**, not an executor. It determines which phase the user needs and delegates to the dedicated phase skill. It should never execute phase steps directly. * Each phase has its own skill file with full procedural detail. The hub skill intentionally omits that detail to prevent Claude Code from racing through all phases at once. * Create separate CoreStory conversations per phase to keep findings organized and produce clean audit trails. * Keep the SKILL.md under 500 lines for reliable loading. #### Skill File Save as `.claude/skills/code-modernization/SKILL.md`: ```markdown theme={null} --- name: CoreStory Code Modernization description: Orchestrates legacy system modernization using CoreStory's persistent code intelligence. Routes to the correct phase-specific skill and enforces sequential execution with human-in-the-loop gates between phases. Activates on modernization, migration, legacy system, or refactoring requests. --- # CoreStory Code Modernization — Orchestrator **This skill is a router and sequencer. It does NOT contain execution instructions for any phase.** When this skill activates, your job is to determine which phase the user needs, activate the dedicated skill for that phase, and enforce the gate between phases. ## Critical Rules 1. **Execute exactly one phase per session.** Never run multiple phases in a single pass. 2. **Always use the dedicated phase skill.** The summaries below are for orientation only — they do not contain enough detail to execute the phase correctly. Read and follow the dedicated skill for the active phase. 3. **After completing a phase, STOP.** Present the deliverable and wait for the user to explicitly approve before offering to advance to the next phase. 4. **Never skip phases.** Each phase depends on the outputs of the one before it. ## Activation Triggers Activate when user requests: - Code modernization or legacy modernization - System migration or codebase migration - Legacy refactoring or re-architecture - Monolith decomposition or monolith-to-microservices - Modernization assessment or readiness evaluation - Any request containing "modernize", "migration", "legacy", "monolith", "mainframe" ## Prerequisites - CoreStory MCP server configured - At least one CoreStory project with completed ingestion (the legacy codebase) - Read access to the repository for cross-referencing findings **If you do not detect that you have access to CoreStory (e.g., `list_projects` fails or is unavailable), ask the user to verify that their MCP or API connection is properly configured and that this repository has been ingested. If the user has not yet created a CoreStory account, direct them to create one and upload their repo at [app.corestory.ai](https://app.corestory.ai).** ## Phase Detection Before doing anything, determine where the user is in the process: 1. **Ask the user** which phase they want to work on, OR 2. **Check CoreStory conversations** (`list_conversations`) — look for completed phase markers: - "RESOLVED - [Assessment]..." → Phase 1 complete - "RESOLVED - [Business Rules]..." → Phase 2 complete - "RESOLVED - [Architecture]..." → Phase 3 complete - "RESOLVED - [Decomposition]..." → Phase 4 complete - Active "[Extraction]..." conversations → Phase 5 in progress - Active "[Verification]..." conversations → Phase 6 in progress 3. **If no prior work exists**, start at Phase 1. Once you know the target phase, read and follow its dedicated skill completely. --- ## Phase 1: Codebase Assessment **Purpose:** Evaluate the legacy system's architecture, dependencies, tech debt, and modernization readiness. **Dedicated skill:** Use the `codebase-assessment` skill and follow its full workflow. **Deliverable:** Modernization Readiness Report **⛔ GATE: Do not proceed to Phase 2 until the user has reviewed the Readiness Report and given explicit go/no-go approval.** --- ## Phase 2: Business Rules Inventory **Purpose:** Extract, catalog, and verify all business rules embedded in the legacy system. **Dedicated skill:** Use the `business-rules-extraction` skill and follow its full workflow. If the skill is not installed, refer to the [Business Rules Extraction playbook](https://docs.corestory.ai/playbooks/business-rules-extraction) for setup instructions. **Deliverable:** Business Rules Inventory (BR-XXX format) **⛔ GATE: Do not proceed to Phase 3 until the user has reviewed the Business Rules Inventory and confirmed completeness.** --- ## Phase 3: Target Architecture & Strategy **Purpose:** Evaluate modernization strategies (the 7 Rs), define the target architecture, and document the decision. **Dedicated skill:** Use the `target-architecture` skill and follow its full workflow. **Deliverable:** Architectural Decision Record (ADR) **⛔ GATE: Do not proceed to Phase 4 until the architect or tech lead has approved the ADR.** --- ## Phase 4: Decomposition & Sequencing **Purpose:** Break the modernization into discrete, sequenced work packages with dependency mapping and acceptance criteria. **Dedicated skill:** Use the `decomposition-sequencing` skill and follow its full workflow. **Deliverable:** Sequenced work packages (optionally pushed to Jira/Linear) **⛔ GATE: Do not proceed to Phase 5 until the engineering lead has approved the sequence.** --- ## Phase 5: Iterative Execution (per component) **Purpose:** Execute the modernization for each component following the Transform → Coexist → Eliminate pattern. **Dedicated skill:** Use the `spec-driven-dev` skill — it's the foundation for all forward engineering with CoreStory, and it generates the per-component delta specs this phase requires. For architecture-to-architecture variants, also load the matching skill: - Monolith to microservices → `monolith-to-microservices` **Deliverable:** Modernized component with coexistence infrastructure **⛔ GATE: Do not proceed to Phase 6 for a component until the delta spec has been reviewed and the Transform phase is functionally complete.** --- ## Phase 6: Behavioral Verification (per component) **Purpose:** Verify that the modernized component preserves every business rule from the Phase 2 inventory. **Dedicated skill:** Use the `behavioral-verification` skill and follow its full workflow. **Deliverable:** Behavioral Equivalence Report **⛔ GATE: Do not retire the legacy component until the domain expert or engineering lead has validated the Equivalence Report.** --- ## Error Handling - **Project not found:** List available projects, ask user to specify - **Generic answers from CoreStory:** Narrow queries with specific component names from Tech Spec - **User unsure which phase they're in:** Check CoreStory conversations for completed phase markers (see Phase Detection above) - **User wants to jump ahead:** Explain the dependency chain and what outputs are missing. Offer to start from the earliest incomplete phase. - **Phase skill not installed:** Direct the user to the relevant playbook page on [docs.corestory.ai](https://docs.corestory.ai/playbooks/code-modernization) for setup instructions. - **Legacy system uses non-code artifacts:** Explicitly ask about JCL, copybooks, CICS, VSAM — CoreStory surfaces these if prompted ``` GitHub Copilot supports agent skills — folders containing a `SKILL.md` file with YAML frontmatter that Copilot loads when relevant to a task. Create `.github/skills/code-modernization/SKILL.md`: ```yaml theme={null} --- name: code-modernization description: "Orchestrate legacy system modernization using CoreStory's persistent code intelligence. Routes to phase-specific skills and enforces sequential execution with human gates between phases." --- ``` ```markdown theme={null} # Code Modernization Skill — Orchestrator This skill is a router. It determines which phase the user needs and delegates to the dedicated phase skill. Do NOT execute phase steps from this file. **Rules:** Execute one phase per session. Always use the dedicated phase skill. STOP after each phase and wait for user approval before advancing. **If you do not detect that you have access to CoreStory (e.g., `list_projects` fails or is unavailable), ask the user to verify that their MCP or API connection is properly configured and that this repository has been ingested. If the user has not yet created a CoreStory account, direct them to create one and upload their repo at [app.corestory.ai](https://app.corestory.ai).** ## Phase 1: Codebase Assessment Dedicated skill: `codebase-assessment` — Produces Modernization Readiness Report. ⛔ GATE: User must approve before advancing to Phase 2. ## Phase 2: Business Rules Inventory Dedicated skill: `business-rules-extraction` — Produces BR-XXX format inventory. ⛔ GATE: User must confirm completeness before advancing to Phase 3. ## Phase 3: Target Architecture & Strategy Dedicated skill: `target-architecture` — Produces Architectural Decision Record (ADR). ⛔ GATE: Architect/tech lead must approve ADR before advancing to Phase 4. ## Phase 4: Decomposition & Sequencing Dedicated skill: `decomposition-sequencing` — Produces sequenced work packages. ⛔ GATE: Engineering lead must approve sequence before advancing to Phase 5. ## Phase 5: Iterative Execution (per component) Dedicated skill: `monolith-to-microservices` (or relevant architecture variant). ⛔ GATE: Delta spec must be reviewed before advancing to Phase 6. ## Phase 6: Behavioral Verification (per component) Dedicated skill: `behavioral-verification` — Produces Behavioral Equivalence Report. ⛔ GATE: Domain expert must validate before retiring legacy component. Key principle: Expert before Navigator — understand architecture from CoreStory before navigating to specific code. ``` **Custom instructions (lightweight alternative):** Add to `.github/copilot-instructions.md`: ```markdown theme={null} ## Code Modernization When asked to modernize or migrate a legacy system: 1. Execute ONE phase at a time — never run multiple phases in a single session 2. ALWAYS start with a Codebase Assessment via CoreStory (architecture, dependencies, tech debt, non-code artifacts) 3. Extract business rules BEFORE any code changes — these define "correct" 4. Use the 7 Rs framework to select strategy per component (not one strategy for everything) 5. Sequence work packages by dependency chain — CoreStory maps shared data stores and coupling 6. Execute incrementally: Transform → Coexist → Eliminate (Strangler Fig default) 7. Verify behavioral equivalence for every component before retiring legacy 8. Human approval required at five gates: go/no-go, architecture, sequence, spec review, equivalence 9. STOP after each phase deliverable and wait for explicit human approval before advancing ``` Create `.cursor/rules/code-modernization/RULE.md`: ```markdown theme={null} --- description: CoreStory-powered code modernization orchestrator. Routes to phase-specific rules and enforces sequential execution with human gates. Activates for legacy modernization, system migration, monolith decomposition, and mainframe transformation. alwaysApply: false --- # CoreStory Code Modernization — Orchestrator You are a modernization architect with access to CoreStory's code intelligence via MCP. **This rule is a router — it determines which phase the user needs and delegates to the dedicated phase rule. Do NOT execute phase steps from this file.** ## Critical Rules 1. **Execute exactly one phase per session.** Never run multiple phases in a single pass. 2. **Always use the dedicated phase rule.** The summaries below are for orientation only. 3. **After completing a phase, STOP.** Present the deliverable and wait for explicit user approval. 4. **Never skip phases.** Each phase depends on the outputs of the one before it. ## Activation Triggers Apply when user requests: code modernization, legacy migration, system migration, monolith decomposition, mainframe modernization, re-architecture, or any refactoring at architectural scale. **If you do not detect that you have access to CoreStory (e.g., `list_projects` fails or is unavailable), ask the user to verify that their MCP or API connection is properly configured and that this repository has been ingested. If the user has not yet created a CoreStory account, direct them to create one and upload their repo at [app.corestory.ai](https://app.corestory.ai).** ## Six-Phase Workflow ### Phase 1: Codebase Assessment Dedicated rule: `codebase-assessment` — Produces Modernization Readiness Report. ⛔ GATE: User must approve before advancing to Phase 2. ### Phase 2: Business Rules Inventory Dedicated rule: `business-rules-extraction` — Produces BR-XXX format inventory. ⛔ GATE: User must confirm completeness before advancing to Phase 3. ### Phase 3: Target Architecture & Strategy Dedicated rule: `target-architecture` — Produces Architectural Decision Record (ADR). ⛔ GATE: Architect/tech lead must approve ADR before advancing to Phase 4. ### Phase 4: Decomposition & Sequencing Dedicated rule: `decomposition-sequencing` — Produces sequenced work packages. ⛔ GATE: Engineering lead must approve sequence before advancing to Phase 5. ### Phase 5: Iterative Execution (per component) Dedicated rule: `monolith-to-microservices` (or relevant architecture variant). ⛔ GATE: Delta spec must be reviewed before advancing to Phase 6. ### Phase 6: Behavioral Verification (per component) Dedicated rule: `behavioral-verification` — Produces Behavioral Equivalence Report. ⛔ GATE: Domain expert must validate before retiring legacy component. ## Key Principles - Expert before Navigator: understand architecture from specs first - Business rules define "correct" — extract them before changing anything - Humans make architectural decisions; AI informs them - Incremental execution — never big-bang rewrite - Every component verified before legacy is retired ``` Create `.factory/droids/code-modernization.md`: ```markdown theme={null} --- name: CoreStory Code Modernization description: Orchestrates legacy system modernization by routing to phase-specific droids and enforcing sequential execution with human gates between phases. model: inherit tools: - CoreStory:list_projects - CoreStory:get_project_prd - CoreStory:get_project_techspec - CoreStory:create_conversation - CoreStory:send_message - CoreStory:rename_conversation - CoreStory:list_conversations - CoreStory:get_conversation --- # CoreStory Code Modernization — Orchestrator **This droid is a router. It determines which phase the user needs and delegates to the dedicated phase droid. Do NOT execute phase steps from this file.** ## Critical Rules 1. **Execute exactly one phase per session.** Never run multiple phases in a single pass. 2. **Always delegate to the dedicated phase droid.** The summaries below are for orientation only. 3. **After completing a phase, STOP.** Present the deliverable and wait for explicit user approval. 4. **Never skip phases.** Each phase depends on the outputs of the one before it. ## Activation Triggers - "Modernize [system]" or "migrate [system]" - "Codebase assessment" or "modernization readiness" - "Monolith to microservices" or "mainframe migration" - Any legacy modernization, re-architecture, or migration request ## CoreStory MCP Tools - `list_projects` — identify the target project - `list_conversations` / `get_conversation` — detect which phase has been completed - `create_conversation` — open named threads per phase - `send_message` — query CoreStory (primary investigation tool) - `rename_conversation` — mark completed threads "RESOLVED" - `get_project_prd` / `get_project_techspec` — retrieve specs for context **If you do not detect that you have access to CoreStory (e.g., `list_projects` fails or is unavailable), ask the user to verify that their MCP or API connection is properly configured and that this repository has been ingested. If the user has not yet created a CoreStory account, direct them to create one and upload their repo at [app.corestory.ai](https://app.corestory.ai).** ## Workflow Phase 1: Codebase Assessment → delegate to `codebase-assessment` droid → ⛔ HITL go/no-go Phase 2: Business Rules Inventory → delegate to `business-rules-extraction` droid → ⛔ HITL completeness Phase 3: Target Architecture → delegate to `target-architecture` droid → ⛔ HITL architecture approval Phase 4: Decomposition → delegate to `decomposition-sequencing` droid → ⛔ HITL sequence approval Phase 5: Execution → delegate to `monolith-to-microservices` droid (or variant) → ⛔ HITL spec review Phase 6: Verification → delegate to `behavioral-verification` droid → ⛔ HITL equivalence sign-off ## Key Principles - Expert before Navigator: understand architecture from specs first - Business rules define "correct" — extract before changing anything - Humans make architectural decisions; AI informs them - Incremental execution using Strangler Fig (default), Branch by Abstraction, or Parallel Run - Every component verified before legacy is retired ``` *** ## Tips & Best Practices **Start with Phase 1, even if you think you know the codebase.** Engineers who've worked on a system for years consistently discover architectural connections, dead code paths, and undocumented dependencies during a formal assessment. CoreStory surfaces things that tribal knowledge misses. **Create separate CoreStory conversations per phase.** Don't reuse a single thread across all six phases. Separate conversations keep findings organized, produce clean audit trails, and allow different team members to own different phases. **Retain is a legitimate outcome.** 53% of enterprises pursue hybrid strategies ([Kyndryl 2025](https://www.kyndryl.com/us/en/perspectives/articles/2025/01/state-of-it-infrastructure-report)). Not every component needs to be modernized. The assessment phase should identify components where the cost of modernization exceeds the benefit — and "retain" is the correct strategy for those components. **Don't skip the business rules inventory.** Phase 2 is the most frequently shortcut phase and the most common source of modernization failure. If you don't know what the legacy system does, you can't verify that the modernized system does the same thing. The business rules inventory is not optional. **Sequence by dependency chain, not by perceived difficulty.** Teams often want to start with the "easiest" component. But if that component depends on a shared database that three other components also use, you'll immediately hit data decomposition challenges. Let the dependency graph drive the sequence. **Use the architecture variant playbooks.** Generic modernization guidance is insufficient for the specific challenges of each pattern. Monolith-to-microservices has different hard problems (data decomposition, distributed transactions) than mainframe-to-cloud (JCL translation, VSAM migration, CICS session management). **Query specificity matters.** "Tell me about the architecture" produces vague answers. "Which modules access the same database tables? Map the shared data dependencies between the order processing and inventory modules" produces actionable findings with file paths. Always name the specific component, entity, or workflow. *** ## Troubleshooting **CoreStory returns generic or shallow answers about the legacy system.** Your queries are too broad. After retrieving the Tech Spec, use the architectural vocabulary it provides — specific service names, module names, data model names — in your queries. "What are the dependencies?" is weak. "What are the dependencies between the OrderService and InventoryService, including shared database tables and message queue interactions?" is strong. **The assessment reveals the system isn't ready for modernization.** This is a valid and valuable finding. Common blockers: no test coverage (can't verify), extreme coupling (can't decompose), missing domain knowledge (can't validate business rules), insufficient budget or timeline. Use the assessment to build the case for investing in readiness *before* attempting modernization. **Phase 3 produces analysis paralysis — too many options, no clear strategy.** Start with the component that has the highest business value and the lowest coupling. Prove the methodology works on one component before scaling. The architectural decision doesn't have to cover every component upfront — you can reassess after the first few components are modernized. **Work packages from Phase 4 are too large or too tightly coupled.** Ask CoreStory more targeted decomposition questions: "What is the smallest independently-deployable subset of \[component]?" and "If we extract just \[feature], what temporary integration points are needed?" The goal is work packages that can be completed in 1–3 sprints. **Behavioral verification reveals differences between legacy and modernized systems.** Not all differences are bugs. Some are intentional improvements (better error handling, more consistent validation). The verification report should classify each difference as: (a) equivalent behavior, (b) intentional improvement, (c) acceptable deviation, or (d) bug requiring remediation. Only (d) blocks the Eliminate phase. **Project not found or CoreStory tools unavailable.** See the [Supercharging AI Agents](/getting-started/supercharging-ai-agents) troubleshooting section for MCP connection issues. Verify the project has completed ingestion by calling `list_projects` and checking the status. *** ## What's Next **Start here:** [Codebase Assessment →](/playbooks/modernization/codebase-assessment) — Phase 1 is where every modernization engagement begins. **For business rules extraction:** [Business Rules Extraction →](/playbooks/business-rules-extraction) — Phase 2 of the workflow. **For the first architecture variant:** [Monolith to Microservices →](/playbooks/modernization/monolith-to-microservices) — the most common enterprise modernization pattern. **For agent setup:** [Supercharging AI Agents with CoreStory →](/getting-started/supercharging-ai-agents) — MCP server configuration and agent setup. **For Jira integration:** [Using CoreStory with Jira →](/playbooks/using-corestory-with-jira) — Phase 4 work package integration. # Feature Gap Analysis Source: https://docs.corestory.ai/playbooks/feature-gap-analysis Systematically identify what exists, what's missing, and what needs to change to implement a new feature in an existing codebase using CoreStory's persistent architectural intelligence. ## Overview Adding a feature to an established codebase is rarely greenfield work. Most of the effort — and most of the risk — lies in understanding how the new feature interacts with what already exists: which data structures need new fields, which UI components need modification, which business rules extend or conflict, and which integration points need updating. CoreStory acts as a persistent intelligence layer across this process. As **Expert**, it holds deep architectural knowledge of the existing system. As **Navigator**, it maps file structures and component relationships. As **Gap Analyzer**, it compares a feature specification against the current system to surface exactly what's present, what's absent, and what needs to change — down to specific files and functions. The primary deliverable is a **Feature Gap Analysis Report**: a structured, developer-ready breakdown of gaps across data models, UI, business logic, rendering, integrations, and constraints, with an implementation plan ordered by dependency. This playbook pairs naturally with the [Feature Implementation](/playbooks/feature-implementation) playbook (which uses gap analysis as one phase of a broader workflow) and the [Business Rules Extraction](/playbooks/business-rules-extraction) playbook (which catalogs the rules your gap analysis will need to account for). ### When to Use This Playbook * You have a feature specification (PRD, user story, design doc) and need to understand the implementation surface area before writing code * You're evaluating build effort or feasibility for a proposed feature * You want to de-risk implementation by identifying conflicts, missing structures, and downstream effects before development begins * You need a structured handoff document between product/architecture and engineering * You're onboarding a new team to a feature and need them to understand what already exists vs. what must be built ### When to Skip This Playbook * The feature is entirely greenfield with no interaction with existing code (use [Spec-Driven Development](/playbooks/spec-driven-development) instead) * You need to extract and catalog existing business rules before analyzing gaps (run [Business Rules Extraction](/playbooks/business-rules-extraction) first) * You're past gap analysis and ready to implement (move to [Feature Implementation](/playbooks/feature-implementation)) ## Prerequisites Before starting, ensure you have: 1. **CoreStory account** with the target project onboarded and analyzed 2. **CoreStory MCP server** connected to your AI coding agent ([setup guide](/getting-started/mcp-server-setup)) 3. **An AI coding agent** — Claude Code, GitHub Copilot, Cursor, or any MCP-compatible agent 4. **A feature specification** — PRD, user story, design document, or detailed description of what you want to build 5. **Repository access** — your agent should have local access to the codebase under analysis ## How It Works The playbook follows four phases, each building on the previous: | Phase | Name | Purpose | CoreStory Role | | ----- | ------------------------- | ------------------------------------------------------------------------------------------- | ------------------ | | 1 | Context Loading | Establish project context and architectural understanding | Expert | | 2 | Gap Identification | Systematically compare the feature spec against the existing system across seven categories | Gap Analyzer | | 3 | Validation & Completeness | Verify the gap analysis is thorough, check for downstream effects and conflicts | Expert + Navigator | | 4 | Implementation Planning | Produce a dependency-ordered implementation plan from the validated gaps | Navigator | ### MCP Tools Used | Tool | Phase(s) | Purpose | | ---------------------- | ---------- | ------------------------------------------------------------------------------- | | `list_projects` | 1 | Find and select the target project | | `create_conversation` | 1 | Start a dedicated gap analysis conversation thread | | `send_message` | 1, 2, 3, 4 | Query CoreStory for architectural knowledge, gap identification, and validation | | `get_project_prd` | 1 | Retrieve the project's PRD for context (if available) | | `get_project_techspec` | 1 | Retrieve the project's technical specification (if available) | | `list_conversations` | — | Resume a previous gap analysis session | | `get_conversation` | — | Retrieve prior conversation context | | `rename_conversation` | 4 | Label the conversation for future reference | If your project's PRD or TechSpec is too large for a single context window, use `send_message` to query specific sections rather than loading the full document. *** ## Step-by-Step Walkthrough ### Phase 1: Context Loading **Goal:** Establish project context so CoreStory can provide grounded, codebase-specific answers. **Step 1.1 — Connect to the project** Use `list_projects` to find your target project, then start a dedicated conversation: ``` list_projects ``` Select the appropriate project and create a conversation thread: ``` create_conversation(project_id="", title="Gap Analysis: ") ``` **Step 1.2 — Load architectural context** Retrieve available specifications to ground the analysis: ``` get_project_prd(project_id="") get_project_techspec(project_id="") ``` **Step 1.3 — Orient CoreStory to the feature** Send an initial message establishing the scope of your analysis: ``` send_message(conversation_id="", message="I'm preparing to implement a new feature and need to understand how it interacts with the existing codebase. Here is the feature specification: [Paste or summarize the feature specification] Before we begin the gap analysis, please confirm: 1. Which major subsystems or modules in the existing codebase are most relevant to this feature? 2. Are there any existing features with similar patterns I should be aware of? 3. What are the primary architectural patterns used in this codebase (e.g., MVC, event-driven, microservices)?") ``` Review the response to confirm CoreStory has sufficient context. If key areas are missing or the response is vague, provide additional specification detail or ask targeted follow-up questions. *** ### Phase 2: Gap Identification **Goal:** Produce a structured gap analysis across seven categories, each grounded in specific files and components. **Step 2.1 — Run the seven-category gap analysis** This is the core query. Send the following to CoreStory, replacing the bracketed section with your feature specification: ``` send_message(conversation_id="", message="I need to implement the following new feature in the existing codebase: [Paste or summarize the feature specification] Based on your understanding of the existing system, provide a detailed gap analysis: 1. EXISTING CAPABILITIES: What parts of this feature are already supported by the existing system? What can be reused as-is? 2. DATA MODEL GAPS: What new fields, tables, enums, or data structures need to be added? What existing structures need to be modified? 3. UI GAPS: What new screens, forms, or components need to be created? What existing UI elements need to be modified? 4. BUSINESS LOGIC GAPS: What new validation rules, calculations, or business logic needs to be implemented? What existing logic needs to be extended? 5. RENDERING/OUTPUT GAPS: What new rendering, drawing, or output logic is needed? What existing rendering needs to accommodate the new feature? 6. INTEGRATION GAPS: What existing integration points (APIs, events, workflows) need to be updated to support the new feature? 7. CONSTRAINT GAPS: What new constraints or validation rules need to be implemented? How do they interact with existing constraints? For each gap, identify the specific files that need to change and describe the change at a level of detail sufficient for a developer to implement it.") ``` **Step 2.2 — Drill into sparse categories** Review the response. If any category returned fewer than expected results, probe deeper: ``` send_message(conversation_id="", message="The [CATEGORY] section seems sparse. Can you look more carefully at: - [Specific area of concern] - Any indirect dependencies or downstream effects in this category? - Files that might not be obviously related but would need changes?") ``` **Step 2.3 — Identify cross-cutting concerns** Some gaps span multiple categories. Ask CoreStory to surface these: ``` send_message(conversation_id="", message="Are there any cross-cutting concerns that span multiple gap categories? For example: - A data model change that cascades to UI, validation, and API layers - A constraint that affects both business logic and rendering - An integration change that requires coordinated updates across subsystems List these cross-cutting concerns and the full chain of files affected.") ``` *** ### Phase 3: Validation & Completeness **Goal:** Verify the gap analysis is thorough, identify missed dependencies, and flag conflicts with existing patterns. **Step 3.1 — Run the completeness check** ``` send_message(conversation_id="", message="Review this gap analysis for completeness: - Are there any files or components I'm missing? - Are there any downstream effects that aren't captured? - Are there any existing patterns that the gap analysis contradicts? - What is the recommended implementation order?") ``` **Step 3.2 — Check for pattern conflicts** ``` send_message(conversation_id="", message="For each proposed change in the gap analysis, does it follow the existing architectural patterns in the codebase? Flag any changes that would introduce inconsistencies or require pattern exceptions.") ``` **Step 3.3 — Estimate scope** ``` send_message(conversation_id="", message="Based on the validated gap analysis, provide a scope summary: - Total number of files to create vs. modify - Highest-risk changes (most dependencies, most complex logic) - Any gaps that could be deferred to a later iteration without blocking the core feature") ``` *** ### Phase 4: Implementation Planning **Goal:** Transform the validated gaps into a dependency-ordered implementation plan. **Step 4.1 — Generate the implementation plan** ``` send_message(conversation_id="", message="Based on the validated gap analysis, produce a dependency-ordered implementation plan. Group changes in this order: 1. Data Model changes (foundations everything else depends on) 2. Business Logic changes (rules and calculations) 3. UI changes (components and screens) 4. Rendering/Output changes (visual output and reports) 5. Integration changes (APIs, events, external systems) For each group, list: - Specific files to create or modify - The change required - Which existing patterns to follow - What tests should validate the change - Dependencies on other groups") ``` **Step 4.2 — Label the conversation** Rename the conversation for future reference: ``` rename_conversation(conversation_id="", title="Gap Analysis: — Complete") ``` *** ## Output Format The gap analysis should produce a structured report. Use this template: ```markdown theme={null} # Feature Gap Analysis: [Feature Name] **Date:** [Date] **Project:** [Project Name] **Feature Spec:** [Link or reference to specification] **Status:** [Draft | Validated | Implementation-Ready] ## Executive Summary [2-3 sentences: what the feature does, how many gaps were identified, key risks] ## 1. Existing Capabilities [What already exists that supports this feature. List reusable components, patterns, and data structures.] | Component | Status | Notes | |-----------|--------|-------| | [Name] | Reusable as-is | [Detail] | | [Name] | Needs modification | [Detail] | ## 2. Data Model Gaps | Gap ID | Description | Files Affected | Priority | |--------|-------------|----------------|----------| | DM-001 | [Description] | `path/to/file` | High/Medium/Low | ### Details **DM-001: [Gap Title]** - **Current state:** [What exists now] - **Required state:** [What needs to change] - **Files:** `file1`, `file2` - **Dependencies:** [Other gaps this depends on or enables] ## 3. UI Gaps | Gap ID | Description | Files Affected | Priority | |--------|-------------|----------------|----------| | UI-001 | [Description] | `path/to/file` | High/Medium/Low | ### Details [Same structure as above for each gap] ## 4. Business Logic Gaps | Gap ID | Description | Files Affected | Priority | |--------|-------------|----------------|----------| | BL-001 | [Description] | `path/to/file` | High/Medium/Low | ### Details [Same structure as above] ## 5. Rendering/Output Gaps | Gap ID | Description | Files Affected | Priority | |--------|-------------|----------------|----------| | RO-001 | [Description] | `path/to/file` | High/Medium/Low | ### Details [Same structure as above] ## 6. Integration Gaps | Gap ID | Description | Files Affected | Priority | |--------|-------------|----------------|----------| | IG-001 | [Description] | `path/to/file` | High/Medium/Low | ### Details [Same structure as above] ## 7. Constraint Gaps | Gap ID | Description | Files Affected | Priority | |--------|-------------|----------------|----------| | CG-001 | [Description] | `path/to/file` | High/Medium/Low | ### Details [Same structure as above] ## Cross-Cutting Concerns [Gaps that span multiple categories with full dependency chains] ## Scope Summary - **Files to create:** [count] - **Files to modify:** [count] - **Highest-risk changes:** [list] - **Deferrable items:** [list] ## Implementation Plan ### Phase 1: Data Model | Step | File | Change | Pattern | Tests | |------|------|--------|---------|-------| | 1 | `path` | [Description] | [Pattern to follow] | [Test approach] | ### Phase 2: Business Logic [Same table structure] ### Phase 3: UI [Same table structure] ### Phase 4: Rendering/Output [Same table structure] ### Phase 5: Integration [Same table structure] ``` *** ## Agent Implementation Guides The skill content below is plain markdown and works in any agentic harness — only the install location varies. The sections that follow show end-to-end setup for the four most common harnesses; for any other harness, install the skill file per the conventions below. The skill file shown below is plain markdown. The workflow it encodes works in any agentic harness — only the install location differs. Common conventions: | Harness | Install location | | --------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Claude Code** | `.claude/skills//SKILL.md` — Claude loads the body when the YAML `description` matches the task | | **GitHub Copilot** | Append to `.github/copilot-instructions.md` for repo-wide instructions, or save as `.github/instructions/.instructions.md` with an `applyTo` glob for path-scoped use | | **Cursor** | `.cursor/rules/.mdc` with a `description` field for auto-attach (use `globs` for path-scoped or `alwaysApply: true` for every session) | | **Factory.ai** | `.factory/droids/.md` (project) or `~/.factory/droids/.md` (personal); Factory loads it as a custom Droid | | **Aider** | `CONVENTIONS.md` at repo root, loaded with `aider --read CONVENTIONS.md` — or add it to the `read:` list in `.aider.conf.yml` for automatic loading | | **Codex / `AGENTS.md` harnesses** | Append the content to `AGENTS.md` at your repository root | | **Custom runtime** | Load the markdown into your agent's system prompt, rules file, or wherever it consumes workflow context | Want a single install that works across the most harnesses? Append the content to `AGENTS.md` at your repository root. The [`AGENTS.md` spec](https://agents.md/) 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. ### Claude Code Save the SKILL.md content below at `.claude/skills/feature-gap-analysis/SKILL.md`: ````markdown theme={null} --- description: Run a feature gap analysis using CoreStory to identify what exists, what's missing, and what needs to change before implementing a new feature. activation: - gap analysis - feature gaps - what needs to change - implementation surface area - what's missing for this feature - analyze gaps - pre-implementation analysis --- # Feature Gap Analysis with CoreStory When this skill activates, execute the four-phase gap analysis workflow. **If you do not detect that you have access to CoreStory (e.g., `list_projects` fails or is unavailable), ask the user to verify that their MCP or API connection is properly configured and that this repository has been ingested. If the user has not yet created a CoreStory account, direct them to create one and upload their repo at [app.corestory.ai](https://app.corestory.ai).** ## Activation Triggers Activate when user requests: - Gap analysis or pre-implementation analysis - Implementation surface area assessment - "What needs to change to build [feature]?" - Any request containing "gap analysis", "what's missing", "what needs to change" ## Prerequisites - CoreStory MCP server configured - At least one CoreStory project with completed ingestion - Feature specification available (PRD, user story, or design doc) ## Phase 1: Context Loading 1. **Select CoreStory Project** ``` Use CoreStory MCP: list_projects ``` - Multiple projects → ask user which one - Single project → auto-select - Verify status is "completed" 2. **Create Gap Analysis Conversation** ``` Use CoreStory MCP: create_conversation Title: "Gap Analysis: [Feature Name]" ``` Store conversation_id for all subsequent queries. 3. **Load Architectural Context** ``` Use CoreStory MCP: get_project_prd Use CoreStory MCP: get_project_techspec ``` If either document is too large, use `send_message` to query specific sections. 4. **Orient CoreStory to the Feature** ``` I'm preparing to implement a new feature and need to understand how it interacts with the existing codebase. Here is the feature specification: [Paste or summarize the feature specification] Before we begin the gap analysis, confirm: 1. Which major subsystems or modules are most relevant to this feature? 2. Are there existing features with similar patterns I should be aware of? 3. What are the primary architectural patterns in this codebase? ``` **Report:** ``` Starting gap analysis for [Feature Name] Project: [project name] CoreStory conversation: [conversation-id] Relevant subsystems: [list from CoreStory response] Similar existing features: [list from CoreStory response] ``` ## Phase 2: Gap Identification **Send the seven-category gap analysis query:** ``` I need to implement the following feature in the existing codebase: [Feature specification] Provide a detailed gap analysis across these categories: 1. EXISTING CAPABILITIES: What parts are already supported? What can be reused as-is? 2. DATA MODEL GAPS: New fields, tables, enums, or structures to add? Existing structures to modify? 3. UI GAPS: New screens, forms, or components to create? Existing UI to modify? 4. BUSINESS LOGIC GAPS: New validation rules, calculations, or logic to implement? Existing logic to extend? 5. RENDERING/OUTPUT GAPS: New rendering or output logic needed? Existing rendering to update? 6. INTEGRATION GAPS: Existing integration points (APIs, events, workflows) to update? 7. CONSTRAINT GAPS: New constraints or validation rules? How do they interact with existing constraints? For each gap, identify specific files that need to change and describe the change at a level of detail sufficient for a developer to implement it. ``` **Drill into sparse categories:** ``` The [CATEGORY] section seems sparse. Look more carefully at: - [Specific area of concern] - Indirect dependencies or downstream effects in this category - Files that might not be obviously related but would need changes ``` **Identify cross-cutting concerns:** ``` Are there cross-cutting concerns that span multiple gap categories? For example: - A data model change that cascades to UI, validation, and API layers - A constraint that affects both business logic and rendering - An integration change requiring coordinated updates across subsystems List these and the full chain of files affected. ``` **Report:** Summarize gap counts per category, highlight any sparse categories investigated. ## Phase 3: Validation & Completeness **Completeness check:** ``` Review this gap analysis for completeness: - Are there any files or components I'm missing? - Are there any downstream effects that aren't captured? - Are there any existing patterns that the gap analysis contradicts? - What is the recommended implementation order? ``` **Pattern conflict check:** ``` For each proposed change in the gap analysis, does it follow the existing architectural patterns in the codebase? Flag any changes that would introduce inconsistencies or require pattern exceptions. ``` **Scope summary:** ``` Based on the validated gap analysis, provide a scope summary: - Total number of files to create vs. modify - Highest-risk changes (most dependencies, most complex logic) - Any gaps that could be deferred to a later iteration without blocking the core feature ``` ## Phase 4: Implementation Planning **Generate the plan:** ``` Produce a dependency-ordered implementation plan. Group changes: 1. Data Model changes (foundations everything else depends on) 2. Business Logic changes (rules and calculations) 3. UI changes (components and screens) 4. Rendering/Output changes (visual output and reports) 5. Integration changes (APIs, events, external systems) For each group, list: - Specific files to create or modify - The change required - Which existing patterns to follow - What tests should validate the change - Dependencies on other groups ``` **Label the conversation:** ``` Use CoreStory MCP: rename_conversation Title: "Gap Analysis: [Feature Name] — Complete" ``` **Report:** Present the full gap analysis report using this structure: ``` # Feature Gap Analysis: [Feature Name] ## Executive Summary [2-3 sentences: what the feature does, gap count, key risks] ## Gaps by Category For each category, use gap IDs (DM-001, UI-001, BL-001, RO-001, IG-001, CG-001): - Gap ID, description, files affected, priority - Current state vs. required state - Dependencies on other gaps ## Cross-Cutting Concerns [Gaps spanning multiple categories with full dependency chains] ## Scope Summary - Files to create: [count] - Files to modify: [count] - Highest-risk changes: [list] - Deferrable items: [list] ## Implementation Plan Ordered: Data Model → Business Logic → UI → Rendering → Integration Per step: file, change, pattern to follow, tests, dependencies ``` ## Error Handling - **Project not found:** List available projects, ask user to specify - **PRD/TechSpec too large:** Use `send_message` to query specific sections instead of loading full documents - **Sparse category results:** Drill in with targeted follow-up; some categories legitimately have no gaps - **CoreStory response is vague:** Provide more specific feature requirements — concrete fields, screens, rules - **Conflicting recommendations:** Ask CoreStory to identify the dominant pattern and recommend which to follow - **Too many gaps:** Break the feature into sub-features and run separate analyses ## When NOT to Use - Entirely greenfield features with no existing codebase interaction - Pure business rules extraction (use Business Rules Extraction skill instead) - User is past analysis and ready to implement (use Feature Implementation skill instead) - No CoreStory project available ```` ### GitHub Copilot Create the file `.github/skills/feature-gap-analysis/SKILL.md` in your repository: ````markdown theme={null} --- name: Feature Gap Analysis description: Run a feature gap analysis using CoreStory to identify what exists, what's missing, and what needs to change before implementing a new feature. --- # Feature Gap Analysis with CoreStory When this skill activates, execute the four-phase gap analysis workflow. **If you do not detect that you have access to CoreStory (e.g., `list_projects` fails or is unavailable), ask the user to verify that their MCP or API connection is properly configured and that this repository has been ingested. If the user has not yet created a CoreStory account, direct them to create one and upload their repo at [app.corestory.ai](https://app.corestory.ai).** ## Activation Triggers Activate when user requests gap analysis, implementation surface area, or pre-implementation analysis for a feature. ## Prerequisites - CoreStory MCP server configured - Feature specification available (PRD, user story, or design doc) - Access to the target repository ## Phase 1: Context Loading 1. Use `list_projects` to find the target project (verify status is "completed") 2. Use `create_conversation` to start a "Gap Analysis: [Feature Name]" thread 3. Use `get_project_prd` and `get_project_techspec` for architectural context 4. Send an orientation message with the feature specification and ask CoreStory to confirm: - Which major subsystems or modules are most relevant - Existing features with similar patterns - Primary architectural patterns in the codebase ## Phase 2: Gap Identification Send the core gap analysis query: ``` I need to implement the following feature in the existing codebase: [Feature specification] Provide a detailed gap analysis across these categories: 1. EXISTING CAPABILITIES: What can be reused as-is? 2. DATA MODEL GAPS: New fields, tables, enums, structures to add or modify? 3. UI GAPS: New screens, forms, components to create or modify? 4. BUSINESS LOGIC GAPS: New validation, calculations, logic to implement or extend? 5. RENDERING/OUTPUT GAPS: New rendering or output logic needed? 6. INTEGRATION GAPS: Existing APIs, events, workflows to update? 7. CONSTRAINT GAPS: New constraints? Interactions with existing constraints? For each gap, identify specific files and describe the change at implementation-ready detail. ``` Then: - Drill into any sparse categories with targeted follow-ups - Ask for cross-cutting concerns spanning multiple categories with full file chains ## Phase 3: Validation Run three validation queries: - **Completeness:** "Are there missing files, downstream effects, or pattern contradictions?" - **Pattern conflicts:** "Does each proposed change follow existing architectural patterns? Flag inconsistencies." - **Scope summary:** "Total files to create vs. modify, highest-risk changes, deferrable items." ## Phase 4: Implementation Planning Generate a dependency-ordered plan grouped as: 1. Data Model → 2. Business Logic → 3. UI → 4. Rendering/Output → 5. Integration Per group include: specific files, change required, pattern to follow, tests to validate, dependencies on other groups. Rename the conversation to "Gap Analysis: [Feature Name] — Complete". ## Output Format Structure the report with: - Gap IDs per category (DM-001, UI-001, BL-001, RO-001, IG-001, CG-001) - Per gap: description, files affected, current state vs. required state, priority, dependencies - Cross-cutting concerns with full dependency chains - Scope summary (create/modify counts, risks, deferrable items) - Dependency-ordered implementation plan with test strategies ## Error Handling - **Project not found:** List available projects, ask user to specify - **PRD/TechSpec too large:** Query specific sections via `send_message` instead - **Sparse category:** Drill in with targeted follow-up; some categories legitimately have no gaps - **Vague results:** Provide more specific feature requirements — concrete fields, screens, rules - **Too many gaps:** Break into sub-features and run separate analyses ```` **Lightweight alternative:** Add this to `.github/copilot-instructions.md`: ```markdown theme={null} ## Feature Gap Analysis When asked to perform a gap analysis or assess implementation surface area: 1. Connect to CoreStory via MCP. Use `list_projects`, `create_conversation`, `get_project_prd`, `get_project_techspec`. 2. Send the seven-category gap analysis query (Existing Capabilities, Data Model, UI, Business Logic, Rendering/Output, Integration, Constraints). Require specific file paths and implementation-ready change descriptions for each gap. 3. Drill into sparse categories. Identify cross-cutting concerns spanning multiple categories. 4. Validate: check for missing files, downstream effects, pattern conflicts. Estimate scope (files to create/modify, risks, deferrable items). 5. Produce a dependency-ordered implementation plan (Data Model → Business Logic → UI → Rendering → Integration) with test strategies per group. 6. Output a structured report with gap IDs (DM-001, UI-001, BL-001, etc.), file-level changes, cross-cutting concerns, scope summary, and the implementation plan. ``` ### Cursor Create the file `.cursor/rules/playbooks/feature-gap-analysis.md` in your repository: ````markdown theme={null} # Feature Gap Analysis with CoreStory **If you do not detect that you have access to CoreStory (e.g., `list_projects` fails or is unavailable), ask the user to verify that their MCP or API connection is properly configured and that this repository has been ingested. If the user has not yet created a CoreStory account, direct them to create one and upload their repo at [app.corestory.ai](https://app.corestory.ai).** ## When to Activate - User asks for gap analysis, implementation surface area, or pre-implementation analysis - User wants to know what needs to change before building a feature ## Workflow ### Phase 1: Context Loading 1. Connect to CoreStory via MCP. Use `list_projects` to find the target project (verify status is "completed"). 2. Use `create_conversation` to start a "Gap Analysis: [Feature Name]" thread. 3. Use `get_project_prd` and `get_project_techspec` for architectural context. If too large, use `send_message` to query specific sections. 4. Send an orientation message with the feature specification. Ask CoreStory to confirm relevant subsystems, similar existing features, and primary architectural patterns. ### Phase 2: Gap Identification 5. Send the seven-category gap analysis query: ``` Provide a detailed gap analysis for [feature]: 1. EXISTING CAPABILITIES: What can be reused as-is? 2. DATA MODEL GAPS: New/modified fields, tables, enums, structures? 3. UI GAPS: New/modified screens, forms, components? 4. BUSINESS LOGIC GAPS: New/extended validation, calculations, logic? 5. RENDERING/OUTPUT GAPS: New/updated rendering or output logic? 6. INTEGRATION GAPS: APIs, events, workflows to update? 7. CONSTRAINT GAPS: New constraints? Interactions with existing ones? For each gap, identify specific files and describe the change at implementation-ready detail. ``` 6. Drill into any sparse categories: "The [CATEGORY] section seems sparse. Look at indirect dependencies, downstream effects, and non-obvious files." 7. Identify cross-cutting concerns: "What gaps span multiple categories? List each with the full chain of files affected." ### Phase 3: Validation 8. Completeness check: "Are there missing files, downstream effects, or pattern contradictions?" 9. Pattern conflict check: "Does each proposed change follow existing architectural patterns? Flag inconsistencies." 10. Scope summary: "Total files to create vs. modify, highest-risk changes, deferrable items." ### Phase 4: Implementation Planning 11. Generate dependency-ordered plan: Data Model → Business Logic → UI → Rendering → Integration. Per group: specific files, change, pattern to follow, tests, dependencies. 12. Rename the conversation to "Gap Analysis: [Feature Name] — Complete". ## Output Format Structure the report with: - Gap IDs per category (DM-001, UI-001, BL-001, RO-001, IG-001, CG-001) - Per gap: description, files affected, current state vs. required state, priority, dependencies - Cross-cutting concerns with full dependency chains - Scope summary (create/modify counts, risks, deferrable items) - Dependency-ordered implementation plan with test strategies ## Error Handling - **Project not found:** List available projects, ask user to specify - **PRD/TechSpec too large:** Query specific sections via `send_message` - **Sparse category:** Drill in; some categories legitimately have no gaps - **Vague results:** Ask user for more specific requirements - **Too many gaps:** Break into sub-features and run separate analyses ```` ### Factory.ai Use this droid configuration: ```yaml theme={null} name: feature-gap-analysis description: > Runs a feature gap analysis using CoreStory's MCP server. Compares a feature specification against the existing codebase to identify gaps across data models, UI, business logic, rendering, integrations, and constraints. Produces a structured gap report with file-level changes and a dependency-ordered implementation plan. instructions: | **If you do not detect that you have access to CoreStory (e.g., `list_projects` fails or is unavailable), ask the user to verify that their MCP or API connection is properly configured and that this repository has been ingested. If the user has not yet created a CoreStory account, direct them to create one and upload their repo at [app.corestory.ai](https://app.corestory.ai).** Phase 1 — Context Loading: 1. Use list_projects to find the target project (verify status is "completed") 2. Use create_conversation to start a "Gap Analysis: [Feature Name]" thread 3. Use get_project_prd and get_project_techspec for context (if too large, query sections via send_message) 4. Orient CoreStory: send the feature spec, confirm relevant subsystems and similar existing features Phase 2 — Gap Identification: 5. Send the seven-category gap analysis query: - Existing Capabilities (what can be reused as-is) - Data Model Gaps (new/modified fields, tables, enums, structures) - UI Gaps (new/modified screens, forms, components) - Business Logic Gaps (new/extended validation, calculations, logic) - Rendering/Output Gaps (new/updated rendering or output logic) - Integration Gaps (APIs, events, workflows to update) - Constraint Gaps (new constraints, interactions with existing ones) Require specific file paths and implementation-ready change descriptions for each gap. 6. Drill into any sparse categories with targeted follow-ups 7. Identify cross-cutting concerns spanning multiple categories with full file chains Phase 3 — Validation: 8. Check completeness: missing files, downstream effects, pattern contradictions 9. Check pattern conflicts: flag changes that break existing architectural patterns 10. Produce scope summary: files to create/modify, highest-risk changes, deferrable items Phase 4 — Implementation Planning: 11. Generate dependency-ordered plan: Data Model → Business Logic → UI → Rendering → Integration Per group: specific files, change, pattern to follow, tests, dependencies 12. Rename conversation to "Gap Analysis: [Feature Name] — Complete" Output: Structured report with gap IDs (DM-001, UI-001, BL-001, RO-001, IG-001, CG-001), file-level changes, cross-cutting concerns, scope summary, and implementation plan. Error handling: - Project not found → list available, ask user to specify - PRD/TechSpec too large → query sections via send_message - Sparse categories → drill in with follow-ups - Vague results → ask user for more specific requirements - Too many gaps → break into sub-features ``` *** ## Tips & Best Practices **Query patterns, from most to least effective:** 1. **Specific and scoped:** "What data model changes are needed in the user-profile module to support multi-currency pricing?" — targets a single category and subsystem 2. **Category-focused:** "What UI gaps exist for the checkout flow redesign?" — targets one category across a feature area 3. **Comparison-based:** "How does the existing notification system need to change to support scheduled notifications?" — frames the gap as a delta 4. **Full seven-category sweep:** The core gap analysis query — comprehensive but produces the most output to validate 5. **Open-ended:** "What do I need to build this feature?" — usable but produces less structured output 6. **Vague:** "Tell me about the codebase" — too broad, not actionable **Scoping your analysis:** * Start with the full seven-category query, then drill into the categories most relevant to your feature * For large features, break the specification into sub-features and run separate gap analyses * Use the scope summary to identify what can be deferred to a follow-up iteration **Handling conflicts:** * When a gap contradicts an existing pattern, flag it explicitly — don't silently introduce a new pattern * Ask CoreStory whether the existing pattern should be extended or whether a new approach is justified * Document pattern exceptions in the gap report so reviewers understand the trade-off **Prioritization order:** * Data model gaps first (everything downstream depends on the data layer) * Business logic second (rules and calculations before presentation) * UI and rendering third (built on stable data and logic) * Integration last (connects the completed feature to external systems) **Keeping gap analyses current:** * Re-run the analysis if the feature spec changes materially * Reference previous gap analysis conversations using `list_conversations` to track how the analysis evolved * Use the gap analysis as a living document during implementation — update gap statuses as work progresses ## Troubleshooting | Problem | Likely Cause | Fix | | ----------------------------------------- | --------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------- | | CoreStory returns vague or generic gaps | Feature spec is too high-level | Provide more specific requirements — concrete fields, screens, rules, not just goals | | Missing files in gap results | CoreStory hasn't indexed recent changes | Confirm the project is up to date in CoreStory; re-analyze if needed | | PRD/TechSpec too large to load | Document exceeds context window | Use `send_message` to query specific sections instead of loading the full document | | Gaps seem incomplete for a category | The category may not apply, or the query needs refinement | Drill in with a targeted follow-up question for that specific category | | Too many gaps to act on | Feature scope is very large | Break the feature into sub-features and run separate analyses; use scope summary to identify deferrable items | | Conflicting recommendations | Codebase has inconsistent patterns | Ask CoreStory to identify the dominant pattern and recommend which to follow | | Gap analysis contradicts domain knowledge | CoreStory may lack business context | Validate with a domain expert; provide additional context via `send_message` | # Feature Implementation Source: https://docs.corestory.ai/playbooks/feature-implementation A structured workflow for implementing new features using CoreStory's architectural intelligence to guide every step from spec to merge. ## Overview Feature Implementation is a workflow for building new features, enhancements, and general development work using an AI coding agent backed by CoreStory's code intelligence. The agent uses CoreStory's MCP tools to understand your system's architecture, identify implementation patterns, and navigate to the right code locations before writing a single line — then implements the feature using a test-driven approach. CoreStory serves two roles in this workflow: * **Expert** — answers questions about system architecture, design patterns, naming conventions, and invariants. The agent queries CoreStory to understand *how the system works* and *what patterns to follow* before coding. * **Navigator** — points to specific files, extension points, base classes, and data structures. The agent queries CoreStory to understand *where to implement* and *what to reuse*. This playbook shares its six-phase structure with the Bug Resolution playbook. The difference is the starting point: Bug Resolution starts from something broken, Feature Implementation starts from something that needs building. The questions asked in each phase shift accordingly. *** ## 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](/getting-started/mcp-server-setup)) * **AI coding agent** — this playbook includes implementation guides for Claude Code, GitHub Copilot, Cursor, and Factory.ai. The generic workflow applies to any MCP-capable agent. * **Optional:** Ticketing system MCP (GitHub Issues, Jira, Linear, Azure DevOps) for automatic ticket intake *** ## How It Works The workflow has six phases. Each phase builds on the previous one. Skipping phases — especially the expert and navigator phases — increases the risk of architectural misalignment, missed patterns, and avoidable rework. | Phase | Name | Purpose | CoreStory Role | | ----- | ------------------ | ------------------------------------------------------------- | ----------------- | | 1 | Ticket Intake | Gather requirements, select project, create conversation | Setup | | 2 | Expert | Understand architecture, patterns, conventions, invariants | Expert | | 3 | Navigator | Map requirements to files, data structures, extension points | Navigator | | 4 | TDD Implementation | Write failing tests from acceptance criteria, then implement | Validation | | 5 | Feature Completion | Edge cases, regression check, performance/security validation | Validation | | 6 | Completion | Commit, update ticket, preserve conversation | Knowledge capture | **CoreStory MCP tools used:** | Tool | When Used | | --------------------- | -------------------------------------------------- | | `list_projects` | Phase 1 — select the right project | | `create_conversation` | Phase 1 — create a persistent investigation thread | | `send_message` | Phases 2–5 — all queries to CoreStory | | `rename_conversation` | Phase 6 — mark conversation as completed | Optional (if ticketing MCP is connected): the agent also uses the ticketing system's tools to fetch ticket details and post implementation summaries. *** ## Step-by-Step Walkthrough ### Phase 1: Ticket Intake & Context Gathering **Objective:** Import ticket details and set up the CoreStory implementation environment. **1.1 — Get ticket details.** If a ticketing MCP is connected, the agent fetches the ticket directly: ``` "Fetch GitHub issue #6992 from myorg/myapp" ``` Extract the user story, acceptance criteria, requirements, and constraints. If no ticketing MCP is available, provide these details in the prompt. **1.2 — Select CoreStory project.** ``` "List my CoreStory projects" "Verify that the myapp-main project ingestion is completed" ``` If multiple projects exist, confirm which one maps to the codebase being worked on. **1.3 — Create an implementation conversation.** ``` "Create a CoreStory conversation for project myapp-main titled 'Ticket Implementation: #6992 - Add CSV export for user profiles'" ``` This conversation persists across the session and captures the full chain of queries and responses — valuable institutional knowledge for future work. *** ### Phase 2: Understanding System Architecture (Expert Phase) **Objective:** Understand how the system works and where new code should integrate, *before* writing anything. Without this phase, the agent risks implementing features that don't follow existing patterns, break architectural constraints, or duplicate functionality that already exists. **2.1 — Query system architecture.** Ask CoreStory about the feature area: ``` "What files are responsible for [feature area]? I need to understand: 1. Primary implementation files and their responsibilities 2. Existing test patterns and coverage 3. Helper/utility modules I can reuse 4. Integration points with other components" ``` **Example for a CSV export feature:** ``` "What files handle user profile operations and data export? I need to understand: 1. Where user profile data is accessed 2. Existing export functionality (PDF, etc.) 3. Serialization utilities available 4. API endpoints for downloads" ``` Look for core implementation files, similar existing features (these become reference implementations), utility modules, and integration patterns. **2.2 — Query design patterns and conventions.** ``` "What architectural patterns are used for [feature type]? Specifically: 1. How are similar features structured? 2. What design patterns should I follow? 3. What naming conventions apply? 4. What invariants must I maintain?" ``` Look for class/module structure patterns, naming conventions (e.g., `{Format}ExportService`), async/sync patterns, error handling approaches, and critical invariants (e.g., "all exports require authentication"). **2.3 — Query historical context.** ``` "Have there been similar features implemented recently? What was the design intent? Are there related user stories or tickets I should reference?" ``` Look for related PRs and design discussions, past implementations that solved similar problems, and known gotchas. *** ### Phase 3: Implementation Planning (Navigator Phase) **Objective:** Map feature requirements to specific code locations and an implementation strategy. **3.1 — Identify extension points.** ``` "Where should I implement [feature]? What are the extension points? Walk me through the implementation locations step by step." ``` Look for files to create (with paths), files to modify (with specific sections), base classes to extend, and test file locations. **3.2 — Understand data structures.** ``` "What data structures should I use for [feature]? What models/schemas are involved? What are the relationships and dependencies?" ``` Look for primary models/entities, required fields, relationships to other entities, and serialization requirements. **3.3 — Identify reference implementations.** ``` "What existing features are most similar to [new feature]? Can I reuse code? What patterns should I copy?" ``` This is one of the highest-value queries. A good reference implementation gives the agent a concrete template to follow — not just abstract patterns, but actual working code in the same codebase. *** ### Phase 4: Test-First Implementation **Objective:** Write failing tests that define the feature, then implement code to make them pass. Tests come before implementation code. This is non-negotiable in the workflow — it ensures acceptance criteria are codified, requirements are clearly understood, and regressions are caught immediately. **4.1 — Write acceptance tests** from the criteria gathered in Phase 1, following the architecture patterns from Phase 2 and data structures from Phase 3: ```python theme={null} def test_admin_can_export_user_profiles_as_csv(): """ Ticket: #6992 - Add CSV export for user profiles AC: Admin users can export user data as CSV """ admin = create_user(role='admin') users = [create_user(email='user1@example.com'), create_user(email='user2@example.com')] response = client.get('/users/export/csv', headers=auth_header(admin)) assert response.status_code == 200 assert response.headers['Content-Type'] == 'text/csv' assert 'user1@example.com' in response.data.decode('utf-8-sig') ``` **4.2 — Validate tests with CoreStory.** ``` "I've written these tests for [feature]: [paste test code] Do these correctly validate the acceptance criteria? Are there edge cases I'm missing? Do they follow the testing patterns from [reference tests]?" ``` **4.3 — Verify tests fail.** Run the tests and confirm they fail. If they pass, the feature already exists or the tests are wrong — clarify with CoreStory. **4.4 — Implement the feature** following patterns from Phase 2: ```python theme={null} class CsvExportService(ExportServiceBase): """ Service for exporting user data to CSV format. Follows the export pattern established in PdfExportService. Ticket: #6992 """ def export(self, users, profiles): # Implementation following established pattern ... ``` **4.5 — Verify tests pass.** Run the specific test file and confirm all tests go green. **4.6 — Validate implementation with CoreStory.** ``` "I've implemented [feature] following this structure: [code structure] Does this align with the system architecture? Could it have unintended side effects?" ``` *** ### Phase 5: Feature Completion **Objective:** Add edge case coverage, ensure quality, prevent regressions. **5.1 — Identify edge cases** by querying CoreStory: ``` "My basic [feature] tests pass. What edge cases should I test? What scenarios might break in production?" ``` Common categories: empty state, large datasets, concurrent access, invalid input, permission boundaries, missing related data. **5.2 — Run the full test suite.** Ensure all new tests pass and no existing tests broke. If regressions appear, the implementation introduced unintended side effects — revise the approach. **5.3 — Performance and security validation** (when applicable). Add performance tests for features with latency/throughput requirements. Add security tests for features handling sensitive data or authentication. *** ### Phase 6: Completion & Knowledge Capture **Objective:** Close the loop — commit, document, and preserve knowledge. **6.1 — Update ticket** (if ticketing MCP is connected). Post an implementation summary with files created/modified, pattern followed, test count, and coverage. **6.2 — Commit with rich context.** The commit message should document the feature, implementation approach, architectural alignment, and testing scope: ``` Feat: Add CSV export for user profiles (#6992) Feature: Admin users can export user profile data in CSV format. Implementation: - Created CsvExportService following PdfExportService pattern - Added /users/export/csv endpoint (admin only) - Async processing for large datasets (>1000 records) Architecture Alignment: - Extends ExportServiceBase - Uses established auth pattern - Follows async job pattern for large exports Testing: - 7 integration tests covering acceptance criteria - 3 unit tests for CsvExportService - All tests passing, no regressions References: - Ticket: #6992 - CoreStory Investigation: [conversation-id] ``` **6.3 — Preserve the CoreStory conversation.** ``` "Rename the CoreStory conversation to: 'Ticket Implementation: #6992 - COMPLETED - CSV export'" ``` This marks the conversation as completed and preserves it for future reference. When someone implements a similar feature later, this conversation provides a blueprint. *** ## 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: | Harness | Install location | | --------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Claude Code** | `.claude/skills//SKILL.md` — Claude loads the body when the YAML `description` matches the task | | **GitHub Copilot** | Append to `.github/copilot-instructions.md` for repo-wide instructions, or save as `.github/instructions/.instructions.md` with an `applyTo` glob for path-scoped use | | **Cursor** | `.cursor/rules/.mdc` with a `description` field for auto-attach (use `globs` for path-scoped or `alwaysApply: true` for every session) | | **Factory.ai** | `.factory/droids/.md` (project) or `~/.factory/droids/.md` (personal); Factory loads it as a custom Droid | | **Aider** | `CONVENTIONS.md` at repo root, loaded with `aider --read CONVENTIONS.md` — or add it to the `read:` list in `.aider.conf.yml` for automatic loading | | **Codex / `AGENTS.md` harnesses** | Append the content to `AGENTS.md` at your repository root | | **Custom runtime** | Load the markdown into your agent's system prompt, rules file, or wherever it consumes workflow context | Want a single install that works across the most harnesses? Append the content to `AGENTS.md` at your repository root. The [`AGENTS.md` spec](https://agents.md/) 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: ```bash theme={null} claude mcp add --transport http corestory https://app.corestory.ai/mcp/your-org-slug-123456789 ``` Verify the connection works: ``` "List my CoreStory projects" ``` **2. (Optional) Connect a ticketing system MCP.** For automatic ticket intake, add an MCP server for your issue tracker. Each platform offers an official MCP server — check their documentation for current setup instructions: * **Jira:** See our [Jira Integration playbook](/playbooks/using-corestory-with-jira) for full setup * **GitHub Issues:** [GitHub MCP Server](https://github.com/github/github-mcp-server) * **Azure DevOps:** [Azure DevOps MCP Server](https://github.com/microsoft/azure-devops-mcp) * **Linear:** [Linear MCP Server](https://linear.app/docs/mcp) **3. Install the feature implementation skill.** Claude Code skills are the primary way to teach Claude Code repeatable workflows. Create the skill directory and file: ```bash theme={null} mkdir -p .claude/skills/implement-feature ``` Then create `.claude/skills/implement-feature/SKILL.md` with the contents from the **Skill File** section below. Commit it to version control so the whole team gets it: ```bash theme={null} git add .claude/skills/implement-feature/SKILL.md git commit -m "Add CoreStory feature implementation skill" ``` #### Usage The skill activates automatically when Claude Code detects feature implementation requests: ``` Implement ticket #6992 Build feature JIRA-1234 Resolve ENG-456 ``` #### 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. * The skill file includes structured output templates so Claude reports progress at each phase. * **Let it run.** The workflow is designed for autonomous execution. Interrupting mid-phase breaks the chain of context. * **Provide good acceptance criteria.** The quality of the agent's output is directly proportional to the clarity of the input. Vague tickets produce vague implementations. * **Use the skill for systematic work, plain prompts for quick tasks.** Not every feature needs the full six-phase treatment. A two-line config change doesn't need a CoreStory investigation. #### Skill File Save as `.claude/skills/implement-feature/SKILL.md`: ```markdown theme={null} --- name: implement-feature description: > Implement a feature using CoreStory's code intelligence and TDD methodology. Use when the user asks to implement a ticket, build a feature, or resolve an issue by ID (e.g., "Implement ticket #6992", "Build feature JIRA-123", "Resolve ENG-456"). Do NOT use for bug fixes — use the fix-bug skill instead. --- # CoreStory Feature Implementation Systematically implement feature tickets using CoreStory for architectural guidance and test-driven development for quality. **If you do not detect that you have access to CoreStory (e.g., `list_projects` fails or is unavailable), ask the user to verify that their MCP or API connection is properly configured and that this repository has been ingested. If the user has not yet created a CoreStory account, direct them to create one and upload their repo at [app.corestory.ai](https://app.corestory.ai).** ## Prerequisites Check Before starting, verify: 1. CoreStory MCP server is connected (`list_projects` returns results) 2. Target project has completed ingestion 3. Ticket details are available (via ticketing MCP or user-provided) ## Workflow Execute all six phases in order. Do not skip phases. ### PHASE 1: Ticket Intake 1. If user provided a ticket ID: fetch it via the appropriate ticketing MCP. If user described the feature directly: extract description and ask for acceptance criteria if not provided. 2. Select CoreStory project: - Call `list_projects` - If multiple: ask user which one - If one: auto-select - Verify project ingestion status is "completed" 3. Create implementation conversation: - Call `create_conversation` with title "Ticket Implementation: #[ID] - [description]" - Store conversation_id for all subsequent queries Report to user: ticket summary, acceptance criteria, conversation ID. ### PHASE 2: Expert Phase (Architecture Understanding) Send these queries to CoreStory via `send_message`. After each, summarize key findings to user. **Query 1 — Architecture discovery:** "What files are responsible for [feature area]? I need: primary implementation files, existing test patterns, reusable helper modules, integration points." **Query 2 — Design patterns and conventions:** "What architectural patterns are used for [feature type]? How are similar features structured? What naming conventions apply? What invariants must I maintain?" **Query 3 — Historical context:** "Have similar features been implemented recently? What was the design intent? Are there related PRs or tickets?" Parse responses for: core files, reference implementations, naming conventions, invariants (CRITICAL — these must not be violated), and known gotchas. ### PHASE 3: Navigator Phase (Implementation Planning) **Query 1 — Extension points:** "Where should I implement [feature]? What files to create, what files to modify? Walk me through step by step." **Query 2 — Data structures:** "What data structures should I use? What models/schemas are involved? What relationships and dependencies exist?" **Query 3 — Reference implementations:** "What existing features are most similar? Can I reuse code or patterns?" Output to user: files to create, files to modify, data structures, reference pattern to follow. ### PHASE 4: TDD Implementation **CRITICAL: Tests come BEFORE implementation code.** 1. Write acceptance tests from Phase 1 criteria, following Phase 2 patterns and Phase 3 data structures. Use naming pattern: `test_[feature]_[scenario]_[expected]` 2. Write unit tests for individual components. 3. Verify all tests FAIL. If they pass, the feature may already exist — check with CoreStory. 4. Validate tests with CoreStory: paste test code and ask if they correctly validate the acceptance criteria and follow established testing patterns. 5. Implement the feature following patterns from Phase 2. 6. Verify all tests PASS. 7. Validate implementation with CoreStory: paste code structure and ask if it aligns with architecture and could have unintended side effects. ### PHASE 5: Feature Completion 1. Ask CoreStory for edge cases: "What edge cases should I test? What scenarios might break in production?" 2. Add edge case tests (empty state, large data, concurrent access, invalid input, permission boundaries). 3. Run FULL test suite — all tests must pass, no regressions. 4. If feature has performance requirements: add performance tests. 5. If feature handles auth or sensitive data: add security tests. ### PHASE 6: Completion 1. Update ticket (if ticketing MCP available) with implementation summary. 2. Commit with detailed message: - Format: "Feat: [description] (#[ticket-id])" - Include: feature summary, implementation details, architecture alignment notes, test count and categories, references 3. Rename CoreStory conversation: "Ticket Implementation: #[ID] - COMPLETED - [description]" 4. Report to user: summary, commit info, test results, quality metrics. ## When NOT to Use This Skill - Trivial changes (typos, formatting) - Documentation-only changes - Bug fixes (use fix-bug skill instead) - No CoreStory project available - User explicitly wants to implement manually ``` *** ### GitHub Copilot #### Setup 1. **Configure the CoreStory MCP server** in your VS Code settings. Add it to your MCP server configuration (typically in VS Code settings JSON or the MCP configuration UI). 2. **Add custom instructions.** Copilot reads project-level instructions from `.github/copilot-instructions.md`. This is the primary mechanism for teaching Copilot specialized workflows: ```bash theme={null} mkdir -p .github ``` Create `.github/copilot-instructions.md` with the content from the custom instructions file below. 3. **(Optional) Add a reusable prompt file.** Prompt files (`.github/prompts/implement-feature.prompt.md`) provide reusable task templates. See the prompt file below. 4. **Commit to version control:** ```bash theme={null} git add .github/copilot-instructions.md .github/prompts/ git commit -m "Add CoreStory feature implementation instructions for Copilot" ``` #### Usage In Copilot Chat (agent mode), natural language triggers the workflow: ``` Implement ticket #6992 — add webhook support for project events Build feature JIRA-456 — user notification preferences ``` Or reference the prompt file: ``` @workspace /implement-feature #6992 ``` #### Tips * Copilot's agent mode (available in VS Code) can execute terminal commands and edit files autonomously — this workflow works best in agent mode. * You can add path-specific instruction files (e.g., `.github/instructions/backend.instructions.md` with `applyTo: "src/backend/**"`) for component-specific guidance. * On Team/Enterprise plans, organization-level instructions apply across all repositories. * Copilot automatically references `.github/copilot-instructions.md` in chat responses. #### Custom Instructions Save as `.github/copilot-instructions.md`: ```markdown theme={null} # CoreStory Feature Implementation Workflow ## Role You are a feature implementation assistant with access to CoreStory's code intelligence via MCP. When users request feature builds, ticket implementations, or enhancements, follow the six-phase workflow below. **If you do not detect that you have access to CoreStory (e.g., `list_projects` fails or is unavailable), ask the user to verify that their MCP or API connection is properly configured and that this repository has been ingested. If the user has not yet created a CoreStory account, direct them to create one and upload their repo at [app.corestory.ai](https://app.corestory.ai).** ## Activation Apply this workflow when user requests feature implementation, ticket resolution, or enhancement work. Trigger phrases: "implement", "build", "feature", "ticket", "story", "enhancement". Do NOT use for bug fixes. ## Workflow ### Phase 1: Ticket Intake 1. Extract feature details from ticket (via ticketing MCP) or user description 2. Identify acceptance criteria — ask for them if not provided 3. Select CoreStory project (`CoreStory:list_projects`, verify status is "completed") 4. Create implementation conversation (`CoreStory:create_conversation`) 5. Report: feature summary, acceptance criteria, CoreStory conversation ID ### Phase 2: Expert Phase — Understand Architecture **Do this BEFORE writing any code.** Send three CoreStory queries (`CoreStory:send_message`): 1. Architecture discovery: files, tests, modules, integration points for the feature area 2. Design patterns & conventions: how similar features are structured, naming conventions, invariants 3. Historical context: recent similar features, design intent, related PRs Extract and report: key files, reference implementations, conventions, invariants to maintain. ### Phase 3: Navigator Phase — Plan Implementation Send three CoreStory queries: 1. Extension points: where to add new code, what files to create/modify 2. Data structures: models, schemas, relationships, dependencies 3. Reference implementations: most similar existing features, reusable patterns Report: files to create, files to modify, data structures, pattern to follow. ### Phase 4: TDD Implementation **Write tests BEFORE implementation code.** 1. Write acceptance tests from Phase 1 criteria, following Phase 2 patterns 2. Write unit tests for individual components 3. Verify all tests FAIL (if they pass, feature may already exist) 4. Validate tests with CoreStory (paste code, check correctness and coverage) 5. Implement the feature following patterns from Phase 2 6. Verify all tests PASS 7. Validate implementation with CoreStory (architectural alignment, side effects) ### Phase 5: Feature Completion 1. Ask CoreStory for edge cases 2. Add edge case tests (empty state, large data, concurrent access, invalid input, permissions) 3. Run full test suite — no regressions 4. Add performance tests if relevant 5. Add security tests if feature touches auth or sensitive data ### Phase 6: Completion 1. Update ticket (if ticketing MCP available) 2. Commit: "Feat: [description] (#[ticket-id])" with implementation details, architecture alignment, test summary 3. Rename CoreStory conversation to include "COMPLETED" 4. Report: summary, tests added, quality metrics ## Key Principles - **Expert before Navigator**: understand architecture before planning implementation - **Test-first always**: failing tests → implement → verify passes - **Validate with CoreStory**: check tests and implementation against architecture - **Follow existing patterns**: match the codebase's conventions, don't invent new ones - **Rich documentation**: commit messages explain architectural decisions ## CoreStory Query Patterns Architecture: "What files are responsible for [feature area]?" Patterns: "How are similar features structured in this codebase?" Extension points: "Where should I implement [feature]? What files to create or modify?" Validation: "Looking at [code]: does this align with the existing architecture?" Edge cases: "What edge cases should I test for [feature]?" ``` #### Prompt File (Optional) Save as `.github/prompts/implement-feature.prompt.md`: ```markdown theme={null} --- mode: agent description: Implement a feature using CoreStory's code intelligence --- Implement the specified feature using the CoreStory six-phase workflow. 1. Fetch ticket details and create a CoreStory implementation conversation 2. Query CoreStory for architecture, patterns, conventions, and invariants 3. Plan implementation — files to create/modify, data structures, reference patterns 4. Write failing tests BEFORE implementing, then build the feature 5. Add edge case tests, run full suite, validate with CoreStory 6. Commit with full context, update ticket, preserve conversation ``` *** ### Cursor #### Setup 1. **Configure the CoreStory MCP server** in Cursor's MCP settings (Settings → MCP Servers, or edit the MCP config JSON directly). 2. **Add project rules.** Cursor uses rules in `.cursor/rules/` directories. Each rule folder contains a `RULE.md` file: ```bash theme={null} mkdir -p .cursor/rules/implement-feature ``` Create `.cursor/rules/implement-feature/RULE.md` with the content from the rule file below. 3. **Commit to version control:** ```bash theme={null} git add .cursor/rules/ git commit -m "Add CoreStory feature implementation rules for Cursor" ``` #### Usage In Cursor's Composer or Chat, the rule activates automatically for feature-related requests: ``` Implement ticket #6992 — add webhook support for project events Build the user notification preferences feature from JIRA-456 ``` #### Tips * Rules with `alwaysApply: true` load in every session. Set this if your team regularly implements features through Cursor. Otherwise, use `alwaysApply: false` with a good `description` so Cursor loads it intelligently when relevant. * The legacy `.cursorrules` file still works but the `.cursor/rules/` directory structure is the current recommended approach. * Rules apply to Composer and Chat but do not affect Cursor Tab or inline edits (Cmd/Ctrl+K). * On Team/Enterprise plans, team rules apply across all members. #### Project Rule Save as `.cursor/rules/implement-feature/RULE.md`: ```markdown theme={null} --- description: CoreStory-powered feature implementation workflow. Activates for ticket implementation, feature builds, and enhancement work. alwaysApply: false --- # CoreStory Feature Implementation You are a feature implementation agent with access to CoreStory's code intelligence via MCP. Follow the six-phase workflow for building new features from tickets. **If you do not detect that you have access to CoreStory (e.g., `list_projects` fails or is unavailable), ask the user to verify that their MCP or API connection is properly configured and that this repository has been ingested. If the user has not yet created a CoreStory account, direct them to create one and upload their repo at [app.corestory.ai](https://app.corestory.ai).** ## Activation Triggers Apply when user requests: feature implementation, ticket work, enhancements, stories, or any phrase containing "implement", "build", "feature", "ticket", "story". Do NOT use for bug fixes. ## Phase 1: Ticket Intake - Extract feature details from ticket or user description - Identify acceptance criteria — ask if missing - Select CoreStory project (`CoreStory:list_projects`) - Create implementation conversation (`CoreStory:create_conversation`) ## Phase 2: Expert Phase **Understand architecture BEFORE writing any code.** Query CoreStory (`CoreStory:send_message`) for: 1. Architecture: files, tests, modules for the feature area 2. Patterns & conventions: how similar features are structured, naming, invariants 3. History: recent similar features, design intent, related PRs ## Phase 3: Navigator Phase Query CoreStory for: 1. Extension points: where to add code, files to create/modify 2. Data structures: models, schemas, relationships 3. Reference implementations: similar features, reusable patterns ## Phase 4: TDD Implementation **Write tests BEFORE implementation code.** 1. Write acceptance tests from criteria + patterns from Phases 2-3 2. Write unit tests for components 3. Verify all tests FAIL 4. Validate tests with CoreStory 5. Implement following Phase 2 patterns 6. Verify all tests PASS 7. Validate implementation with CoreStory ## Phase 5: Feature Completion 1. Ask CoreStory for edge cases 2. Add edge case tests 3. Run full test suite — no regressions 4. Add performance/security tests if needed ## Phase 6: Completion 1. Update ticket 2. Commit: "Feat: [description] (#[ticket-id])" with architecture notes, test summary 3. Rename CoreStory conversation → "COMPLETED" 4. Report results ## Key Principles - Expert before Navigator - Test-first always - Validate with CoreStory at each transition - Follow existing patterns - Commit messages explain architectural decisions ``` *** ### 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): ```bash theme={null} mkdir -p .factory/droids ``` Create `.factory/droids/implement-feature.md` with the content from the droid file below. 3. **Commit to version control** (for project-level droids): ```bash theme={null} git add .factory/droids/ git commit -m "Add CoreStory feature implementation droid" ``` #### Usage Invoke the droid via the Task tool: ``` @implement-feature Implement ticket #6992 — add webhook support ``` Or describe the feature and Factory.ai routes to the droid based on its activation triggers. #### Tips * Use `model: inherit` in the YAML frontmatter to use whatever model the session is configured with. * The `tools` field in frontmatter can explicitly list required MCP tools if you want to restrict the droid's capabilities. * The Task tool that invokes droids requires experimental features to be enabled. * For complex features, the droid's CoreStory queries may produce long streaming responses — this is expected. #### Custom Droid Save as `.factory/droids/implement-feature.md`: ```markdown theme={null} --- name: CoreStory Feature Implementation description: Implements features using CoreStory code intelligence and TDD methodology model: inherit tools: - CoreStory:list_projects - CoreStory:get_project - CoreStory:get_project_stats - CoreStory:create_conversation - CoreStory:send_message - CoreStory:get_conversation - CoreStory:rename_conversation - CoreStory:get_project_prd - CoreStory:get_project_techspec --- # CoreStory Feature Implementation Execute the six-phase feature implementation workflow using CoreStory's code intelligence. **If you do not detect that you have access to CoreStory (e.g., `list_projects` fails or is unavailable), ask the user to verify that their MCP or API connection is properly configured and that this repository has been ingested. If the user has not yet created a CoreStory account, direct them to create one and upload their repo at [app.corestory.ai](https://app.corestory.ai).** ## Activation Triggers - "Implement ticket #[ID]" - "Build feature [description]" - "Resolve story [ID]" - Any feature implementation or enhancement request ## CoreStory MCP Tools - `CoreStory:list_projects` — list available projects - `CoreStory:get_project` — verify project status - `CoreStory:create_conversation` — start implementation thread - `CoreStory:send_message` — query code intelligence - `CoreStory:rename_conversation` — mark as completed When instructions say "Query CoreStory", use `CoreStory:send_message`. ## Phase 1: Ticket Intake 1. Extract feature details (from ticket MCP or user description) 2. Identify acceptance criteria — ask if missing 3. Select CoreStory project (`CoreStory:list_projects`, verify "completed") 4. Create conversation: "Ticket Implementation: #[ID] - [description]" ## Phase 2: Expert Phase — Before Code Query CoreStory for: architecture, design patterns, conventions, invariants. ## Phase 3: Navigator Phase Query CoreStory for: extension points, data structures, reference implementations. ## Phase 4: TDD Implementation Write failing tests → verify fail → validate with CoreStory → implement → verify pass → validate implementation. ## Phase 5: Feature Completion Edge case tests → full suite → performance/security tests if needed. ## Phase 6: Completion Update ticket → structured commit ("Feat: ...") → rename conversation "COMPLETED" → report. ## Key Principles - Expert before Navigator - Test-first always - Validate with CoreStory before acting - Follow existing codebase patterns - Commit messages explain architectural decisions ``` ## Tips & Best Practices **Start with the expert, not the editor.** The most common mistake is jumping straight to implementation. Even experienced developers benefit from the expert phase — CoreStory often surfaces patterns, utilities, and conventions that aren't obvious from reading code. **One conversation per ticket.** Don't reuse CoreStory conversations across unrelated tickets. Each conversation builds a coherent context thread. Mixing topics dilutes the quality of responses. **Test at multiple levels.** Follow the testing pyramid: many unit tests (fast, isolated), some integration tests, few end-to-end tests. The acceptance tests from Phase 4 are typically integration-level; supplement with unit tests for individual components. **Each test should verify one behavior.** Resist the temptation to test multiple acceptance criteria in a single test function. Isolated tests are easier to debug when they fail. **Name tests descriptively.** Pattern: `test_[feature]_[scenario]_[expected_outcome]`. When a test fails six months later, the name should tell someone what broke without reading the test body. **Validate with CoreStory at key transitions.** Query CoreStory after writing tests (are they comprehensive?) and after implementing (does this align?). These validation checkpoints catch misalignment early. **Feature flags for gradual rollout.** If the feature warrants a gradual rollout, ask CoreStory about existing feature flag patterns in the codebase and implement accordingly. **Security-sensitive features deserve extra scrutiny.** If the feature touches authentication, authorization, or sensitive data, add a dedicated CoreStory query: "What security considerations apply to \[feature]? What auth patterns should I follow?" Then add security-specific tests for authentication, authorization, and input sanitization. *** ## Troubleshooting **CoreStory responses are vague or generic.** Ask more specific questions. Reference previous findings from the conversation, paste code snippets, and use specific variable or method names. CoreStory responds better to concrete context than abstract questions. **CoreStory project not found.** Verify ingestion is complete: "Get project stats for \[project-id]". Check the project name spelling. Ensure the MCP token has access to the project's organization. **Tests won't fail after writing them.** The feature may already exist (partially or fully), the tests may not match the actual acceptance criteria, or there may be a test environment issue. Ask CoreStory whether the functionality already exists. **Implementation causes regressions in existing tests.** Don't commit. Ask CoreStory about integration impacts: "What other systems or components integrate with \[feature area]? What downstream impacts should I consider?" Revise the implementation to avoid the side effect. **Ticket is too vague to implement.** Ask for clarification. The workflow requires concrete acceptance criteria to produce good tests. If the ticket says "improve the export feature" with no specifics, push back before starting Phase 2. **CoreStory response is too large or takes too long.** Break the query into smaller, more targeted questions. Instead of "tell me everything about the export system," ask "what files handle CSV serialization specifically?" # Playbooks Source: https://docs.corestory.ai/playbooks/index Structured, end-to-end workflows for the work software teams keep getting stuck on. Each playbook combines CoreStory's persistent code intelligence with AI agents and proven engineering methodology. Playbooks are repeatable, end-to-end workflows for the work software teams keep getting stuck on — modernizing legacy systems, shipping features in unfamiliar code, generating tests, and more. Each one combines CoreStory's persistent code intelligence with AI agents and proven engineering methodology, so the agent works grounded in your actual architecture rather than guessing. ## Modernization & Migration Phased methodology for modernizing legacy systems — from assessment through behavioral verification. Agent-led modernization at speed, with source grounding and independent verification that hold up under audit. Evaluate acquisition targets' codebases for risk, debt, and hidden complexity. Compare two systems' capabilities — useful for SaaS migrations and consolidations. ## AI-Assisted Development Implement features with AI agents that understand your system end to end. Diagnose and fix bugs with AI agents grounded in your real architecture. Generate grounded specs before changing code, then build against them. ## Testing & Verification Generate behavioral and end-to-end tests from your codebase. Catalog and verify the business rules embedded in your code. ## Integrations Push migration work packages into Jira as epics and stories. # M&A Technical Due Diligence Source: https://docs.corestory.ai/playbooks/ma-technical-due-diligence Leverage CoreStory's code intelligence to accelerate technical due diligence for mergers, acquisitions, and investment decisions. ## Overview Technical due diligence on acquisition targets traditionally relies on CTO interviews, manual code sampling, and documentation review — covering less than 10% of the actual codebase. Critical risks hide in the 90% nobody reads: hardcoded secrets in utility modules, GPL dependencies buried three layers deep, PII flowing unencrypted through forgotten microservices. CoreStory changes this equation. By ingesting and semantically understanding the target's entire codebase, it gives your diligence team an AI-powered analyst that can answer specific risk questions against the full codebase — not a sample. The agent operates as an **Expert** (explaining system behavior, architectural patterns, and data flows) and a **Navigator** (pointing to specific files, methods, and code paths where risks live). **Who this is for:** M\&A professionals, PE portfolio teams, technical diligence consultants, and acquiring engineering teams evaluating technology-heavy acquisitions. **What you'll get:** A structured workflow for interrogating a target codebase across four risk domains — technical debt, security, data/PII compliance, and integration complexity — producing auditable findings with specific file-level evidence. *** ## Prerequisites * A **CoreStory account** with the target codebase ingested and ingestion complete * An **AI coding agent** with CoreStory MCP configured (see [Supercharging AI Agents](/getting-started/supercharging-ai-agents) for setup) * **Read access** to the target's repository (for the agent to cross-reference CoreStory findings against source) *** ## How It Works ### CoreStory MCP Tools Used This playbook uses the following tools from the CoreStory MCP server: | Tool | Role in Diligence | | ---------------------- | ----------------------------------------------------------------------------------------- | | `list_projects` | Identify and confirm the target project | | `get_project_prd` | Retrieve the synthesized Product Requirements Document for business context | | `get_project_techspec` | Retrieve the Technical Specification for architecture, data models, and security analysis | | `create_conversation` | Open a named diligence thread for each audit workstream | | `send_message` | Interrogate the codebase — the primary investigation tool | | `rename_conversation` | Mark completed threads with "RESOLVED" prefix for audit trail | | `list_conversations` | Review existing diligence threads | | `get_conversation` | Retrieve conversation history for report synthesis | ### The Diligence Workflow M\&A technical diligence with CoreStory follows a four-phase pattern: 1. **Setup** — Confirm the target project, review synthesized specs for architectural orientation, and create named conversation threads for each workstream. 2. **Interrogate** — Use `send_message` to ask specific risk questions. CoreStory answers from semantic understanding of the full codebase, citing specific files and code paths. 3. **Cross-reference** — Validate critical findings against the actual source code. CoreStory provides the file paths and context; the agent (or your team) confirms. 4. **Synthesize** — Compile findings into structured reports. Conversation history provides the audit trail. ### Expert Before Navigator The "Expert before Navigator" principle is especially important in diligence. Before searching for specific vulnerabilities or code paths, first use CoreStory to understand how the system is *designed* to work — its intended architecture, data flow patterns, and security model. This baseline makes it far easier to spot deviations, shortcuts, and risks. *** ## Step-by-Step Walkthrough ### Phase 1: Project Setup and Orientation Start every diligence engagement by confirming the target and building architectural context. **Confirm the target project:** ``` List my CoreStory projects. I need to identify the project for [TargetName]. ``` The agent calls `list_projects` and returns your available projects. Confirm the correct project before proceeding — this is a critical safety step when multiple targets may be under evaluation simultaneously. **Review synthesized specifications:** ``` For project [project_id], retrieve the Technical Specification and Product Requirements Document. Give me a high-level summary of: 1. System architecture (major components, services, data stores) 2. Technology stack (languages, frameworks, infrastructure) 3. External integrations and third-party dependencies 4. Data model overview ``` The agent calls `get_project_techspec` and `get_project_prd` to retrieve CoreStory's synthesized understanding of the codebase. This gives you architectural orientation before diving into risk-specific queries. **Create diligence threads:** ``` Create a CoreStory conversation titled "[Diligence] TargetName - Technical Risk Audit". Store the conversation_id — we'll use this thread for all risk-related queries. ``` Create separate conversation threads for each workstream (risk audit, integration planning, compliance audit). This keeps findings organized and produces clean audit trails. ### Phase 2: Risk Interrogation With architectural context established, use `send_message` to interrogate the codebase across risk domains. Each query goes through the conversation thread, and CoreStory draws on its semantic understanding of the entire codebase to answer. **The key principle:** Ask specific questions. "Tell me about security" produces vague answers. "Identify all code locations that handle authentication tokens and describe how they're stored, transmitted, and rotated" produces actionable findings with file paths. The following sections provide query patterns organized by risk domain. Use the ones relevant to your diligence scope. #### Technical Debt & Obsolescence ``` send_message: "List all services, modules, and frameworks running on end-of-life or unsupported versions. For each, identify the current version in use, the latest stable version, and whether the upgrade path has breaking changes." ``` ``` send_message: "Identify areas of the codebase with high complexity or poor separation of concerns — god classes, circular dependencies, modules with excessive coupling. For each, provide the file path and a brief description of the issue." ``` ``` send_message: "Are there any modules or services that appear to be abandoned or unmaintained — no recent commits, no test coverage, referenced but not actively developed? List them with file paths." ``` #### Security & Secrets ``` send_message: "Identify all code locations that hardcode API keys, passwords, tokens, or other secrets. For each, provide the file path, line context, and what the secret appears to be used for." ``` ``` send_message: "How is authentication handled across the system? Map the authentication flow from login through session management. Identify whether it follows standard patterns (OAuth 2.0, SAML, JWT) or uses custom logic." ``` ``` send_message: "List all known CVEs or security vulnerabilities associated with the third-party libraries and frameworks in use, sorted by severity." ``` #### Licensing & Open Source Risk ``` send_message: "Provide a complete bill of materials for all third-party and open-source dependencies. Highlight any libraries with restrictive licenses — GPL, AGPL, SSPL, or other copyleft licenses that could create obligations for the acquiring entity." ``` ``` send_message: "Are there any dependencies that are abandoned, archived, or have known unpatched vulnerabilities? List them with the current version in use and the last release date." ``` #### Data Handling & PII ``` send_message: "Map the data flow for customer onboarding. Show specifically where PII (Personally Identifiable Information) is collected, transmitted, stored, and whether it is encrypted at rest and in transit at each stage." ``` ``` send_message: "Identify all database models or tables that store PII. For each, list the fields, whether they are encrypted, and what access controls exist." ``` ``` send_message: "How is data deletion handled? Is there a mechanism for 'right to be forgotten' requests? Trace the deletion flow and identify any places where PII might persist after a deletion request." ``` #### Architecture & Integration Complexity ``` send_message: "How does the system handle payment processing? Map the integration with payment providers, showing all third-party dependencies, API touchpoints, and where financial data flows." ``` ``` send_message: "What message queues, event buses, or async communication patterns are in use? Map the event flow between services and identify any single points of failure." ``` ``` send_message: "How is the system deployed? Describe the deployment architecture, CI/CD pipeline, infrastructure dependencies, and any vendor lock-in to specific cloud providers or services." ``` ### Phase 3: Cross-Reference and Validation CoreStory provides findings with specific file paths and code context. For critical findings — especially security issues, licensing risks, and PII exposure — validate against the actual source code. ``` For the hardcoded secrets CoreStory identified: 1. Open each file path and confirm the finding 2. Check if there are environment variable alternatives that aren't being used 3. Assess whether these are production secrets or development/test placeholders ``` This cross-reference step is important because CoreStory's analysis is based on its ingestion snapshot. If the target's codebase has changed since ingestion, critical findings should be verified against the current state. ### Phase 4: Synthesis and Reporting After completing your interrogation queries, synthesize findings into structured reports. The conversation history serves as your evidence base. ``` Review our entire conversation history for the risk audit thread. Synthesize all findings into a Technical Due Diligence Report with these sections: 1. Executive Summary — top 3-5 findings that materially affect deal risk or valuation 2. Critical Risks — security vulnerabilities, licensing exposure, PII compliance gaps (each with file-level evidence and severity rating) 3. Technical Debt — end-of-life dependencies, architectural issues, maintainability concerns 4. Architecture Overview — component map, technology stack, external dependencies 5. Integration Assessment — complexity of merging with acquirer's platform, friction points 6. Recommendations — remediation priorities and estimated effort for post-close planning ``` **Mark completed threads:** ``` Rename the conversation to "RESOLVED - [Diligence] TargetName - Technical Risk Audit". ``` This creates a searchable record. Future team members can use `list_conversations` and `get_conversation` to review the full diligence trail. *** ## Advanced Workflows The following end-to-end prompt templates combine the patterns above into complete diligence workflows. Each can be used as a single agent prompt or broken into phases. ### Rapid Risk Audit **Scenario:** A PE firm has one week to perform technical diligence on a target. The goal is to identify major risks and quantify technical debt for negotiation leverage. **Timeline:** 24–48 hours with CoreStory (vs. 2–4 weeks traditional). ``` Perform a rapid technical due diligence risk audit. STEP 1: PROJECT SETUP - Call list_projects and show me the available projects. - After I confirm the project, retrieve the Technical Specification using get_project_techspec. Summarize the architecture, tech stack, and major components. STEP 2: CREATE CONVERSATION - Create a conversation titled "[Diligence] - [TargetName] - Risk Audit" - Use this thread for all subsequent queries. STEP 3: TECHNICAL DEBT Use send_message to ask: - "List all end-of-life or unsupported frameworks, languages, or platforms. For each, provide current version, latest version, and upgrade complexity." - "Identify high-complexity modules with poor test coverage. Provide file paths and complexity indicators." STEP 4: SECURITY Use send_message to ask: - "Identify all hardcoded API keys, passwords, or secrets. Provide file_path and line context for each." - "List all known CVEs from third-party libraries, sorted by severity." - "Map the authentication flow and identify any custom (non-standard) auth logic." STEP 5: LICENSING Use send_message to ask: - "Provide a bill of materials for all third-party dependencies. Flag any with GPL, AGPL, or other copyleft licenses." STEP 6: SYNTHESIZE - Compile all findings into a "Technical Risk Report" with: Issue | Location (file path) | Severity | Impact - Group by category: Security, Licensing, Technical Debt, Architecture. - Highlight the top 5 deal-affecting findings. ``` ### Post-Merger Integration Planning **Scenario:** The deal is closing. The acquiring engineering team needs an integration blueprint — what overlaps, what conflicts, and where the friction will be. ``` Create a post-merger integration blueprint for merging [TargetName] with our [AcquiringPlatformName] platform. STEP 1: PROJECT SETUP - Call list_projects and show me the available projects. - After I confirm, retrieve the Technical Specification and PRD. - Summarize: architecture, data models, API surface, auth model. STEP 2: CREATE CONVERSATION - Create conversation titled "[PMI] - [TargetName] Integration Plan" STEP 3: MAP ARCHITECTURE Use send_message to ask: - "Describe the complete system architecture — services, databases, message queues, caches, and external integrations. Include a component inventory." - "Map all data models and their relationships. Identify the core domain entities and how they flow between services." STEP 4: IDENTIFY INTEGRATION POINTS Use send_message to ask: - "How is customer authentication handled? Map the flow and compare to standard OAuth 2.0 / SAML patterns." - "Map the data flow for customer onboarding, showing all databases and external APIs involved." - "How does the system handle payment processing? What are the third-party dependencies?" - "What APIs are exposed externally? Provide endpoint inventory with authentication requirements." STEP 5: ASSESS FRICTION Use send_message to ask: - "What cloud provider or infrastructure dependencies exist? Identify any vendor lock-in." - "What custom or non-standard patterns are used that would require significant adaptation during integration?" STEP 6: SYNTHESIZE - Create an "Integration Plan Summary" covering: 1. Component inventory with integration complexity rating 2. Data model overlaps and conflicts 3. API surface that can be reused vs. must be rebuilt 4. Auth and identity merge strategy 5. High-friction areas requiring dedicated engineering effort 6. Recommended integration sequence and timeline ``` ### Security & PII Compliance Audit **Scenario:** The diligence team needs to verify the target's data handling practices for GDPR, CCPA, or other regulatory compliance before close. ``` Perform a focused security and PII compliance audit on [TargetName]. STEP 1: PROJECT SETUP - Call list_projects and show me the available projects. - After I confirm, retrieve the Technical Specification. - Summarize the security architecture and data handling patterns. STEP 2: CREATE CONVERSATION - Create conversation titled "[Audit] - [TargetName] - PII & Security" STEP 3: MAP PII FLOWS Use send_message to ask: - "Map all data flows that handle PII — customer registration, profile updates, payment processing, support interactions. For each flow, show where PII is collected, transmitted, and stored." - "Identify all database models or tables containing PII fields. For each field, state whether it is encrypted at rest." - "Is PII encrypted in transit between services? Identify any internal service-to-service communication where PII travels unencrypted." STEP 4: ASSESS COMPLIANCE MECHANISMS Use send_message to ask: - "How is data deletion handled? Is there a 'right to be forgotten' implementation? Trace the deletion flow and identify any places where PII persists after deletion." - "What data retention policies are implemented in code? Are there automated expiration or purge mechanisms?" - "Identify all external APIs or third-party services that receive PII. For each, describe what data is shared and whether data processing agreements would be required." STEP 5: SECURITY POSTURE Use send_message to ask: - "Identify all hardcoded secrets — API keys, passwords, tokens, connection strings. Provide file paths." - "How are secrets managed in production? Is there a secrets manager (Vault, AWS Secrets Manager, etc.) or are environment variables used?" - "What input validation and sanitization patterns are used? Identify any endpoints that accept user input without validation." STEP 6: SYNTHESIZE - Generate a "PII & Security Compliance Report" covering: 1. PII inventory — what data, where stored, encryption status 2. Data flow map — collection through deletion lifecycle 3. Compliance gaps — unencrypted PII, missing deletion flows, third-party data sharing without controls 4. Security findings — hardcoded secrets, missing validation, auth vulnerabilities 5. Remediation priorities with estimated effort 6. Regulatory risk assessment (GDPR, CCPA applicability) ``` *** ## Prompting Patterns Reference ### Investigation Patterns Effective diligence queries are specific and evidence-oriented. They ask for file paths, concrete examples, and traceable findings — not summaries. | Pattern | Example | | --------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- | | **Enumerate with evidence** | "List all hardcoded secrets. For each, provide the file path, line context, and what it's used for." | | **Trace a flow** | "Map the data flow for customer onboarding from signup through account creation. Show every service, database write, and external API call." | | **Compare to standard** | "How is authentication handled? Compare the implementation to standard OAuth 2.0 patterns and identify deviations." | | **Assess coverage** | "What test coverage exists for the payment processing module? Identify critical paths with no test coverage." | | **Find patterns** | "Identify all locations where database queries are constructed from user input. Flag any that don't use parameterized queries." | | **Quantify scope** | "How many external API integrations exist? For each, identify the provider, what data is exchanged, and whether there are retry/fallback mechanisms." | ### Query Specificity Vague queries produce vague answers. Always include specific anchors: | Instead of | Use | | ------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | | "Tell me about security" | "Identify all code locations that handle authentication tokens and describe how they're stored, transmitted, and rotated" | | "How's the code quality?" | "Identify modules with circular dependencies, god classes over 500 lines, or methods with cyclomatic complexity above 15" | | "Are there any risks?" | "List all third-party dependencies with known CVEs, sorted by severity, with the file that imports each one" | | "How does data flow?" | "Trace the PII data flow for the customer registration process from HTTP request through database write, identifying encryption at each stage" | ### Multi-Query Threading For thorough coverage, chain queries within a conversation thread. Each `send_message` builds on prior context: ``` Query 1: "Map the system architecture — services, databases, and external integrations." Query 2: "For each external integration you identified, what data is exchanged and what happens if the external service is unavailable?" Query 3: "Which of these external dependencies have SLA requirements, and are those SLAs enforced in code (circuit breakers, timeouts, retries)?" ``` The conversation accumulates context, so later queries can reference earlier findings without repeating them. *** ## Best Practices **Create separate threads per workstream.** Don't mix security audit queries with integration planning queries. Separate conversations keep findings organized and make it easier to hand off specific workstreams to different team members. **Start with the synthesized specs.** Use `get_project_techspec` and `get_project_prd` before diving into `send_message` queries. The specs give you architectural vocabulary — service names, data model names, API endpoint patterns — that make your queries far more specific and productive. **Ask for file paths, always.** Every finding in a diligence report needs evidence. Train your queries to always request file paths and line context. "Identify X and provide the file path" should be your default pattern. **Cross-reference critical findings.** CoreStory's analysis is based on its ingestion snapshot. For findings that materially affect deal terms — licensing poison pills, PII exposure, critical security vulnerabilities — always validate against the current source. **Use conversation rename for audit trail.** Rename completed threads with a "RESOLVED" prefix using `rename_conversation`. This creates a searchable record that survives team handoffs and can be referenced months later during post-merger integration. **Scope your queries to avoid noise.** A query like "find all security issues" will return an overwhelming response. Break it into targeted categories: hardcoded secrets, authentication flow, input validation, dependency vulnerabilities. Each produces focused, actionable findings. *** ## 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: | Harness | Install location | | --------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Claude Code** | `.claude/skills//SKILL.md` — Claude loads the body when the YAML `description` matches the task | | **GitHub Copilot** | Append to `.github/copilot-instructions.md` for repo-wide instructions, or save as `.github/instructions/.instructions.md` with an `applyTo` glob for path-scoped use | | **Cursor** | `.cursor/rules/.mdc` with a `description` field for auto-attach (use `globs` for path-scoped or `alwaysApply: true` for every session) | | **Factory.ai** | `.factory/droids/.md` (project) or `~/.factory/droids/.md` (personal); Factory loads it as a custom Droid | | **Aider** | `CONVENTIONS.md` at repo root, loaded with `aider --read CONVENTIONS.md` — or add it to the `read:` list in `.aider.conf.yml` for automatic loading | | **Codex / `AGENTS.md` harnesses** | Append the content to `AGENTS.md` at your repository root | | **Custom runtime** | Load the markdown into your agent's system prompt, rules file, or wherever it consumes workflow context | Want a single install that works across the most harnesses? Append the content to `AGENTS.md` at your repository root. The [`AGENTS.md` spec](https://agents.md/) 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, slash command, version control) 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. **Configure the CoreStory MCP server** in your Claude Code settings (see [CoreStory MCP Server Setup Guide](/getting-started/mcp-server-setup)). 2. **Add the skill file.** Claude Code uses skills (`.claude/skills/` directory) as its preferred mechanism for teaching Claude specialized workflows. Create the skill: ```bash theme={null} mkdir -p .claude/skills/ma-due-diligence ``` Create `.claude/skills/ma-due-diligence/SKILL.md` with the content from the skill file below. 3. **(Optional) Add the slash command.** Slash commands provide a shortcut to invoke the workflow: ```bash theme={null} mkdir -p .claude/commands ``` Create `.claude/commands/ma-due-diligence.md` with a short description referencing the four-phase diligence workflow. 4. **Commit to version control** for team sharing: ```bash theme={null} git add .claude/skills/ .claude/commands/ git commit -m "Add CoreStory M&A due diligence skill and command" ``` #### Usage The skill activates automatically when Claude Code detects diligence-related requests: ``` Run due diligence on the target codebase Perform a technical assessment for the acquisition Start a diligence audit on project X ``` Or invoke explicitly: ``` /ma-due-diligence [TargetName] ``` #### 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. * Create separate CoreStory conversations per risk domain (security, licensing, PII) to keep findings organized. #### Skill File Save as `.claude/skills/ma-due-diligence/SKILL.md`: ````markdown theme={null} --- name: CoreStory M&A Due Diligence description: Performs technical due diligence on acquisition targets using CoreStory's code intelligence. Activates on diligence, assessment, or M&A review requests. --- # CoreStory M&A Due Diligence When this skill activates, execute the four-phase due diligence workflow. ## Activation Triggers Activate when user requests: - Due diligence or diligence audit - Technical assessment - M&A review or acquisition review - Any request containing "due diligence", "diligence audit", "technical assessment", "M&A review", "acquisition review" ## Prerequisites - CoreStory MCP server configured - At least one CoreStory project with completed ingestion (the target codebase) - Read access to the target's repository for cross-referencing findings **If you do not detect that you have access to CoreStory (e.g., `list_projects` fails or is unavailable), ask the user to verify that their MCP or API connection is properly configured and that this repository has been ingested. If the user has not yet created a CoreStory account, direct them to create one and upload their repo at [app.corestory.ai](https://app.corestory.ai).** ## Phase 1: Project Setup & Orientation 1. **Identify the Target Project** ``` Use CoreStory MCP: list_projects ``` - Multiple projects → ask user which one is the acquisition target - Single project → confirm with user before proceeding - Verify ingestion is complete 2. **Retrieve Synthesized Specifications** ``` Use CoreStory MCP: get_project_techspec Use CoreStory MCP: get_project_prd ``` - Summarize: system architecture, technology stack, external integrations, data model overview - This establishes the architectural vocabulary for all subsequent queries 3. **Create Diligence Conversation** ``` Use CoreStory MCP: create_conversation Title: "[Diligence] TargetName - Technical Risk Audit" ``` Store conversation_id for all subsequent queries. **Report:** ``` 🔍 Starting M&A technical due diligence Target: [project name] Architecture: [high-level summary] Tech Stack: [languages, frameworks, infrastructure] CoreStory conversation: [conversation-id] ``` ## Phase 2: Risk Interrogation Use `send_message` to interrogate the codebase across risk domains. Ask specific, evidence-oriented questions — always request file paths. **Technical Debt & Obsolescence:** - "List all services, modules, and frameworks running on end-of-life or unsupported versions. For each, provide current version, latest stable version, and upgrade complexity." - "Identify high-complexity modules with poor separation of concerns — god classes, circular dependencies, excessive coupling. Provide file paths." **Security & Secrets:** - "Identify all code locations that hardcode API keys, passwords, tokens, or other secrets. For each, provide the file path and line context." - "Map the authentication flow from login through session management. Identify whether it follows standard patterns or uses custom logic." - "List all known CVEs from third-party libraries, sorted by severity." **Licensing & Open Source Risk:** - "Provide a complete bill of materials for all third-party dependencies. Flag any with GPL, AGPL, SSPL, or other copyleft licenses." - "Are there any dependencies that are abandoned, archived, or have known unpatched vulnerabilities?" **PII & Data Handling:** - "Map data flows where PII is collected, transmitted, and stored. For each stage, state whether encryption is applied at rest and in transit." - "Identify all database models containing PII fields. For each, list fields, encryption status, and access controls." - "How is data deletion handled? Is there a right-to-be-forgotten implementation? Identify where PII might persist after deletion." **Architecture & Integration Complexity:** - "Map all external integrations, showing third-party dependencies, API touchpoints, and data flows." - "What message queues, event buses, or async patterns are used? Identify single points of failure." - "Describe the deployment architecture, CI/CD pipeline, and any cloud vendor lock-in." ## Phase 3: Cross-Reference & Validation For critical findings — security issues, licensing risks, PII exposure: 1. Open each file path CoreStory identified and confirm the finding against source code 2. Check if findings reflect current state (CoreStory's analysis is based on ingestion snapshot) 3. Assess severity: production secrets vs. test placeholders, actual GPL usage vs. dev-only dependencies 4. Note any discrepancies between CoreStory findings and source code ## Phase 4: Synthesis & Reporting 1. **Compile Structured Report** Review conversation history and synthesize into: - Executive Summary — top 3-5 findings affecting deal risk or valuation - Critical Risks — security vulnerabilities, licensing exposure, PII compliance gaps (with file-level evidence and severity) - Technical Debt — end-of-life dependencies, architectural issues, maintainability concerns - Architecture Overview — component map, technology stack, external dependencies - Integration Assessment — complexity of merging with acquirer's platform - Recommendations — remediation priorities and estimated effort 2. **Mark Completed** ``` Use CoreStory MCP: rename_conversation New title: "RESOLVED - [Diligence] TargetName - Technical Risk Audit" ``` ## Error Handling - **Project not found:** List available projects, ask user to specify the target - **CoreStory gives generic answers:** Narrow queries — use specific service names, module names, and technology names from the Tech Spec - **Response too long:** Break into smaller risk-domain queries - **Findings don't match source:** Note ingestion date, request re-ingestion if target codebase has changed significantly ```` *** ### GitHub Copilot #### Setup 1. **Configure the CoreStory MCP server** in your VS Code settings. Add it to your MCP server configuration (typically in VS Code settings JSON or the MCP configuration UI). 2. **Add custom instructions.** Copilot reads project-level instructions from `.github/copilot-instructions.md`. This is the primary mechanism for teaching Copilot specialized workflows: ```bash theme={null} mkdir -p .github ``` Create `.github/copilot-instructions.md` with the content from the custom instructions file below. 3. **(Optional) Add a reusable prompt file.** Prompt files (`.github/prompts/ma-due-diligence.prompt.md`) provide reusable task templates. See the prompt file below. 4. **Commit to version control:** ```bash theme={null} git add .github/copilot-instructions.md .github/prompts/ git commit -m "Add CoreStory M&A due diligence instructions for Copilot" ``` #### Usage In Copilot Chat (agent mode), natural language triggers the workflow: ``` Run technical due diligence on the target codebase Perform a diligence audit for the acquisition Start an M&A review on project X ``` Or reference the prompt file: ``` @workspace /ma-due-diligence [TargetName] ``` #### Tips * Copilot's agent mode (available in VS Code) can execute terminal commands and edit files autonomously — this workflow works best in agent mode. * You can add path-specific instruction files (e.g., `.github/instructions/diligence.instructions.md` with `applyTo: "**"`) for project-wide guidance. * On Team/Enterprise plans, organization-level instructions apply across all repositories. * Copilot automatically references `.github/copilot-instructions.md` in chat responses. #### Custom Instructions Save as `.github/copilot-instructions.md`: ```markdown theme={null} # CoreStory M&A Due Diligence Workflow ## Role You are a technical due diligence analyst with access to CoreStory's code intelligence via MCP. When users request due diligence, technical assessments, or M&A reviews, follow the four-phase workflow below. ## Activation Apply this workflow when user requests due diligence, technical assessments, or acquisition reviews. Trigger phrases: "due diligence", "diligence audit", "technical assessment", "M&A review", "acquisition review". **If you do not detect that you have access to CoreStory (e.g., `list_projects` fails or is unavailable), ask the user to verify that their MCP or API connection is properly configured and that this repository has been ingested. If the user has not yet created a CoreStory account, direct them to create one and upload their repo at [app.corestory.ai](https://app.corestory.ai).** ## Workflow ### Phase 1: Project Setup & Orientation 1. Identify target project (`CoreStory:list_projects`) 2. Retrieve synthesized specs (`CoreStory:get_project_techspec`, `CoreStory:get_project_prd`) 3. Summarize architecture, tech stack, integrations, data models 4. Create diligence conversation (`CoreStory:create_conversation`) 5. Report: target summary, architecture overview, conversation ID ### Phase 2: Risk Interrogation Use `CoreStory:send_message` to query across risk domains: **Technical Debt:** EOL frameworks, high-complexity modules, abandoned code, test coverage gaps **Security & Secrets:** Hardcoded credentials, auth flow analysis, CVEs in dependencies **Licensing:** Bill of materials, copyleft license detection, abandoned dependencies **PII & Data Handling:** PII data flow mapping, encryption status, deletion mechanisms, third-party data sharing **Architecture & Integration:** External integrations, async patterns, deployment architecture, vendor lock-in Always request file paths and line context for every finding. ### Phase 3: Cross-Reference & Validation 1. Verify critical findings against source code (file paths from CoreStory) 2. Assess severity: production vs. test, actual vs. dev-only 3. Note discrepancies between CoreStory findings and current source 4. Flag findings that materially affect deal terms ### Phase 4: Synthesis & Reporting 1. Compile structured report: Executive Summary, Critical Risks, Technical Debt, Architecture Overview, Integration Assessment, Recommendations 2. Each finding includes file-level evidence and severity rating 3. Rename CoreStory conversation with "RESOLVED" prefix (`CoreStory:rename_conversation`) ## Key Principles - **Expert before Navigator**: understand architecture from specs before deep-diving into risk queries - **Evidence-based findings**: every finding needs a file path and concrete evidence - **Separate threads per workstream**: don't mix security audit with integration planning - **Cross-reference critical findings**: validate against source for anything affecting deal terms - **Specific queries**: use architectural vocabulary from the Tech Spec to ask targeted questions ## CoreStory Query Patterns Architecture: "What files are responsible for [service]? What are the integration points?" Security: "Identify all hardcoded secrets. Provide file path and line context for each." Licensing: "Provide a bill of materials. Flag copyleft licenses." PII: "Map PII data flows. Show encryption status at each stage." Validation: "Looking at [file path]: I found [issue]. Confirm this is a risk." ``` #### Prompt File (Optional) Save as `.github/prompts/ma-due-diligence.prompt.md`: ```markdown theme={null} --- mode: agent description: Perform M&A technical due diligence using CoreStory's code intelligence --- Perform technical due diligence on the specified target using the CoreStory four-phase workflow. 1. Identify the target project and retrieve synthesized specifications for architectural orientation 2. Interrogate the codebase across risk domains: technical debt, security, licensing, PII, architecture 3. Cross-reference critical findings against source code 4. Compile a structured due diligence report and mark the conversation resolved ``` *** ### Cursor #### Setup 1. **Configure the CoreStory MCP server** in Cursor's MCP settings (Settings → MCP Servers, or edit the MCP config JSON directly). 2. **Add project rules.** Cursor uses rules in `.cursor/rules/` directories. Each rule folder contains a `RULE.md` file: ```bash theme={null} mkdir -p .cursor/rules/ma-due-diligence ``` Create `.cursor/rules/ma-due-diligence/RULE.md` with the content from the rule file below. 3. **Commit to version control:** ```bash theme={null} git add .cursor/rules/ git commit -m "Add CoreStory M&A due diligence rules for Cursor" ``` #### Usage In Cursor's Composer or Chat, the rule activates automatically for diligence-related requests: ``` Run due diligence on the target codebase Perform a technical assessment for the acquisition Start an M&A review on project X ``` #### Tips * Rules with `alwaysApply: true` load in every session. Set this if your team regularly performs diligence. Otherwise, use `alwaysApply: false` with a good `description` so Cursor loads it intelligently when relevant. * The legacy `.cursorrules` file still works but the `.cursor/rules/` directory structure is the current recommended approach. * Rules apply to Composer and Chat but do not affect Cursor Tab or inline edits (Cmd/Ctrl+K). * On Team/Enterprise plans, team rules apply across all members. #### Project Rule Save as `.cursor/rules/ma-due-diligence/RULE.md`: ```markdown theme={null} --- description: CoreStory-powered M&A due diligence workflow. Activates for due diligence, technical assessments, and acquisition reviews. alwaysApply: false --- # CoreStory M&A Due Diligence You are a technical due diligence analyst with access to CoreStory's code intelligence via MCP. Follow the four-phase workflow for M&A technical due diligence. ## Activation Triggers Apply when user requests: due diligence, diligence audit, technical assessment, M&A review, acquisition review. **If you do not detect that you have access to CoreStory (e.g., `list_projects` fails or is unavailable), ask the user to verify that their MCP or API connection is properly configured and that this repository has been ingested. If the user has not yet created a CoreStory account, direct them to create one and upload their repo at [app.corestory.ai](https://app.corestory.ai).** ## Phase 1: Project Setup & Orientation - Identify target project (`CoreStory:list_projects`) - Retrieve specs (`CoreStory:get_project_techspec`, `CoreStory:get_project_prd`) - Summarize architecture, tech stack, integrations, data models - Create diligence conversation (`CoreStory:create_conversation`) ## Phase 2: Risk Interrogation Use `CoreStory:send_message` across five risk domains: 1. **Technical Debt:** EOL frameworks, complexity, abandoned modules 2. **Security & Secrets:** Hardcoded credentials, auth flows, CVEs 3. **Licensing:** Copyleft licenses, abandoned dependencies 4. **PII & Data Handling:** PII flows, encryption, deletion mechanisms 5. **Architecture & Integration:** External dependencies, async patterns, vendor lock-in Always request file paths and evidence. ## Phase 3: Cross-Reference & Validation - Verify critical findings against source code - Assess severity (production vs. test, actual vs. dev-only) - Flag findings that materially affect deal terms ## Phase 4: Synthesis & Reporting - Compile report: Executive Summary, Critical Risks, Technical Debt, Architecture, Integration Assessment, Recommendations - Each finding includes file-level evidence and severity - Rename conversation with "RESOLVED" prefix (`CoreStory:rename_conversation`) ## Key Principles - Expert before Navigator: understand architecture from specs first - Evidence-based: every finding needs a file path - Separate threads per workstream - Cross-reference critical findings against source - Specific queries using architectural vocabulary ``` *** ### 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): ```bash theme={null} mkdir -p .factory/droids ``` Create `.factory/droids/ma-due-diligence.md` with the content from the droid file below. 3. **Commit to version control** (for project-level droids): ```bash theme={null} git add .factory/droids/ git commit -m "Add CoreStory M&A due diligence droid" ``` #### Usage Invoke the droid via the Task tool: ``` @ma-due-diligence Run due diligence on [TargetName] ``` Or describe the task and Factory.ai routes to the droid based on its activation triggers. #### Tips * Use `model: inherit` in the YAML frontmatter to use whatever model the session is configured with. * The `tools` field in frontmatter explicitly lists required MCP tools — this restricts the droid to only the CoreStory tools needed for diligence. * The Task tool that invokes droids requires experimental features to be enabled. * For thorough diligence, the droid's CoreStory queries may produce long streaming responses — this is expected. #### Custom Droid Save as `.factory/droids/ma-due-diligence.md`: ```markdown theme={null} --- name: CoreStory M&A Due Diligence description: Performs technical due diligence on acquisition targets using CoreStory code intelligence model: inherit tools: - CoreStory:list_projects - CoreStory:get_project_prd - CoreStory:get_project_techspec - CoreStory:create_conversation - CoreStory:send_message - CoreStory:rename_conversation - CoreStory:list_conversations - CoreStory:get_conversation --- # CoreStory M&A Due Diligence Execute the four-phase due diligence workflow using CoreStory's code intelligence. ## Activation Triggers - "Run due diligence on [target]" - "Perform technical assessment" - "M&A review" or "acquisition review" - "Diligence audit" - Any due diligence or technical assessment request ## CoreStory MCP Tools - `CoreStory:list_projects` — identify the target project - `CoreStory:get_project_prd` — retrieve synthesized PRD for business context - `CoreStory:get_project_techspec` — retrieve Tech Spec for architecture analysis - `CoreStory:create_conversation` — open named diligence thread - `CoreStory:send_message` — interrogate the codebase (primary investigation tool) - `CoreStory:rename_conversation` — mark completed threads with "RESOLVED" prefix - `CoreStory:list_conversations` — review existing diligence threads - `CoreStory:get_conversation` — retrieve conversation history for report synthesis When instructions say "Query CoreStory", use `CoreStory:send_message`. **If you do not detect that you have access to CoreStory (e.g., `list_projects` fails or is unavailable), ask the user to verify that their MCP or API connection is properly configured and that this repository has been ingested. If the user has not yet created a CoreStory account, direct them to create one and upload their repo at [app.corestory.ai](https://app.corestory.ai).** ## Phase 1: Project Setup & Orientation 1. Identify target project (`CoreStory:list_projects`) 2. Retrieve specs (`CoreStory:get_project_techspec`, `CoreStory:get_project_prd`) 3. Summarize architecture, tech stack, integrations, data models 4. Create diligence conversation: "[Diligence] TargetName - Technical Risk Audit" ## Phase 2: Risk Interrogation Query CoreStory across five domains: - **Technical Debt:** EOL frameworks, complexity, abandoned modules - **Security & Secrets:** Hardcoded credentials, auth flows, CVEs - **Licensing:** Copyleft licenses, abandoned dependencies - **PII & Data Handling:** PII flows, encryption, deletion mechanisms - **Architecture & Integration:** External dependencies, async patterns, vendor lock-in Always request file paths and evidence for every finding. ## Phase 3: Cross-Reference & Validation Verify critical findings against source code. Assess severity. Flag deal-affecting issues. ## Phase 4: Synthesis & Reporting Compile report → Executive Summary, Critical Risks, Technical Debt, Architecture, Integration Assessment, Recommendations → rename conversation "RESOLVED". ## Key Principles - Expert before Navigator: understand architecture from specs first - Evidence-based: every finding needs a file path - Separate threads per workstream - Cross-reference critical findings against source - Specific queries using architectural vocabulary ``` *** ## Troubleshooting **CoreStory gives generic or shallow answers** Your queries are too broad. Include specific anchors — service names, module names, technology names, or code patterns. After reviewing the Technical Specification, use the vocabulary it provides (component names, data model names) in your queries. **Response exceeds token limit** Break large queries into smaller scopes. Instead of "Tell me everything about the data layer," ask about specific data flows or specific models. If a response is truncated, ask the agent to continue or narrow the scope. **Project not found or unavailable** Verify the project has completed ingestion by calling `list_projects` and checking the status. If the project shows as in-progress, wait for ingestion to complete before starting diligence queries. If the project doesn't appear at all, confirm the MCP token has access to the correct organization. **Findings don't match current source code** CoreStory's analysis reflects the codebase at ingestion time. If the target has pushed significant changes since ingestion, request a re-ingestion before finalizing your diligence report. Always note the ingestion date in your report for traceability. **Agent can't access CoreStory tools** See the [Supercharging AI Agents](/getting-started/supercharging-ai-agents) troubleshooting section for MCP connection issues. *** ## What's Next * **For agent setup and configuration:** [Supercharging AI Agents with CoreStory](/getting-started/supercharging-ai-agents) * **For ongoing development workflows:** [Agentic Bug Resolution](/playbooks/agentic-bug-resolution), [Feature Implementation](/playbooks/feature-implementation), [Spec-Driven Development](/playbooks/spec-driven-development) * **For MCP server reference:** [CoreStory MCP Server Setup & Usage Guide](/getting-started/mcp-server-setup) # Behavioral Verification Source: https://docs.corestory.ai/playbooks/modernization/behavioral-verification Verify that modernized components faithfully preserve the business rules and behavioral semantics of the legacy system using CoreStory's persistent code intelligence. ## Overview You've modernized the component. It compiles. The tests pass. But does it actually do what the old code did? This is the question that derails modernization programs. The hard part was never understanding what the legacy code says. The hard part is proving the new code preserves what the legacy code *does*: every business rule, every edge case, every invariant that accumulated over years of production use. Phase 6 of the modernization workflow is where behavioral equivalence is established. The Business Rules Inventory from Phase 2 defines the behavioral contract — every rule the modernized system must preserve. This playbook provides a systematic methodology for verifying that contract: tracing each rule from the inventory to its implementation in the modernized code, identifying behavioral differences, testing edge cases, and producing a structured equivalence report that gives stakeholders the confidence to retire the legacy component. CoreStory serves as a **Verifier** throughout this phase — comparing behavioral semantics across legacy and modernized codebases. It also operates as an **Expert** for understanding the intent behind legacy implementations: "Why does this code handle negative quantities differently from zero quantities? Is that a business rule or a bug?" This distinction matters because not every legacy behavior should be preserved — some behaviors are bugs, workarounds, or artifacts of obsolete requirements. The verification process must surface these distinctions for human judgment. **Who this is for:** Engineers executing modernization work packages, QA leads responsible for sign-off, and domain experts who can validate whether behavioral differences are intentional improvements or regressions. **What you'll get:** A structured Behavioral Equivalence Report for each modernized component — rule-by-rule verification status, identified differences with analysis, missing rules, integration point verification, and a clear recommendation on whether the component is ready for the Eliminate phase. *** ## When to Use This Playbook * You've completed the Transform phase for a work package and the modernized component is functionally complete * You need to verify that the modernized code preserves all business rules identified in Phase 2 * You're in the Coexist phase and need to validate behavioral equivalence before retiring the legacy component * A domain expert or stakeholder requires a structured verification report before approving legacy decommission * You've identified behavioral differences during testing and need to systematically categorize them as intentional improvements, acceptable deviations, or regressions ## When to Skip This Playbook * You haven't completed Phase 2 (Business Rules Inventory) — there's no behavioral contract to verify against. Go back to [Business Rules Extraction](/playbooks/business-rules-extraction) * The modernization strategy is Rehost/Relocate with no application-level changes — behavioral equivalence is trivially preserved * You're still in the Transform phase — finish the implementation first, then verify * The component is being Retired (decommissioned) rather than modernized — no verification is needed for code that's being removed *** ## Prerequisites * A **completed Business Rules Inventory** (Phase 2) — this is the behavioral contract. Without it, there's nothing to verify against * A **completed Transform phase** for the work package under verification — the modernized component must be functionally complete * A **CoreStory account** with both the legacy codebase and the modernized codebase ingested (or the modernized code available in the same project) * An **AI coding agent** with CoreStory MCP configured (see [Supercharging AI Agents](/getting-started/supercharging-ai-agents) for setup) * (Recommended) **Access to a domain expert** who can validate whether behavioral differences are intentional improvements, acceptable deviations, or regressions * (Recommended) The **legacy system running in a test environment** for comparison testing where static analysis is insufficient *** ## How It Works ### CoreStory MCP Tools Used | Tool | Step(s) | Purpose | | --------------------- | ---------- | ------------------------------------------------------------------------------- | | `list_projects` | 1 | Confirm the target project | | `create_conversation` | 1 | Start a dedicated verification thread | | `send_message` | 2, 3, 4, 5 | Query CoreStory for rule tracing, behavioral comparison, and edge case analysis | | `list_conversations` | 1 | Find the Business Rules Inventory conversation and prior phase threads | | `get_conversation` | 1 | Retrieve the Business Rules Inventory for verification | | `get_project_prd` | 1 | Retrieve PRD for business context behind rules | | `rename_conversation` | 5 | Mark completed thread with "RESOLVED" prefix | ### The Behavioral Verification Workflow > **Note:** The steps below are internal to this playbook. They are sub-steps of Phase 6 in the [six-phase modernization framework](/playbooks/code-modernization), not a separate numbering system. This playbook follows a five-step pattern: 1. **Setup** — Load the Business Rules Inventory and the modernized component. Establish the verification scope and identify which rules apply to the component under test. 2. **Rule-by-Rule Verification** — For each business rule in the inventory, trace it to its implementation in the modernized code and verify semantic equivalence with the legacy implementation. 3. **Edge Case & Invariant Testing** — Identify boundary conditions, invariants, and edge cases that might behave differently between legacy and modernized implementations. 4. **Integration Point Verification** — Verify that the modernized component interacts correctly with adjacent systems — both legacy components still in the Coexist phase and other modernized components. 5. **Equivalence Report** — Produce the structured Behavioral Equivalence Report with rule-by-rule status, difference analysis, and a recommendation. ### Verification Approaches Behavioral verification uses a tiered strategy. CoreStory is most powerful in Tier 1 (it holds both codebases' semantic understanding) and in generating the test cases and input sets for Tiers 2–4. The higher tiers require additional tooling and running environments, but CoreStory guides what to test and interprets the results. #### Tier 1: Static Verification (CoreStory-Assisted) No running code required. CoreStory compares behavioral semantics across the legacy and modernized codebases. **Rule tracing** is the primary method. For each business rule in the inventory, CoreStory locates the implementation in both the legacy and modernized codebases and compares the behavioral semantics — not the syntax, but the actual logic: conditions, transformations, side effects, and outputs. **Invariant checking** verifies that system-wide constraints are preserved. These are often implicit in legacy code — never explicitly documented but enforced by the implementation. Examples: "account balances never go negative," "order status transitions are one-directional," "all timestamps are stored in UTC." CoreStory can identify invariants in the legacy code and verify they're maintained in the modernized version. **Data flow comparison** traces the path of data through both systems for a given operation. Where does data enter? How is it transformed? What side effects occur? Where does it exit? Divergences in the data flow are often the source of subtle behavioral differences. **Edge case generation** uses CoreStory's understanding of the business rules to identify boundary conditions: null inputs, maximum values, concurrent access, timezone boundaries, leap years, currency rounding. These are the cases where modernized code most often diverges from legacy behavior. #### Tier 2: Dynamic Verification (Requires Running Code) When static analysis can't establish equivalence with sufficient confidence, dynamic testing provides empirical evidence. **Characterization testing (Golden Master testing)** — coined by Michael Feathers in *Working Effectively with Legacy Code* — captures the legacy system's actual outputs for a comprehensive set of inputs. Those captured outputs become the "golden master" that the modernized system must match. This is the most practical approach for systems where business rules were never formally documented: the legacy system's behavior *is* the specification. Tool support: ApprovalTests, custom test harnesses. **Contract testing** defines expected behavior at integration points using consumer-driven contracts. Particularly relevant for verifying API gateway / façade layer behavior during the Coexist phase. When the modernized service replaces the legacy component, every consumer's contract must still be satisfied. Tool support: Pact, Spring Cloud Contract. #### Tier 3: Production-Grade Verification (Requires Production-Like Environment) For high-risk components where production-like evidence is required before cutover. **Shadow traffic testing (dark launching)** routes copies of production requests to both the legacy and modernized systems simultaneously, compares responses, and flags discrepancies. Run until the discrepancy rate drops below an acceptable threshold (typically below 0.01% for financial or regulatory-sensitive services, below 0.1% for standard services). Reference: [Microsoft Engineering Playbook's guidance on shadow testing](https://microsoft.github.io/code-with-engineering-playbook/automated-testing/shadow-testing/). **Record-replay testing** captures actual production traffic from the legacy system, replays it against the modernized system, and compares outputs. Particularly valuable for batch processing workflows where you can capture input files and compare output files line by line. AWS Transform uses this approach: automated "bit-by-bit matching" of legacy expected data versus modernized results. #### Tier 4: Data Migration Verification If the modernization involves moving or transforming data stores, data integrity is a distinct verification concern from behavioral verification. **Data reconciliation** compares legacy and modernized data stores across multiple dimensions: row counts (do we have all the records?), checksums (is the data identical?), semantic validation (do derived values compute correctly?), and referential integrity (are all foreign key relationships preserved?). This should be run both immediately after migration and again after the system has been processing live data in the Coexist phase. > **When static analysis isn't enough:** If Tier 1 verification cannot establish equivalence for a rule — the logic is too complex, the edge cases too numerous, or the legacy implementation too opaque — escalate to Tier 2 (characterization testing) or Tier 3 (shadow traffic) for that specific rule. The Behavioral Equivalence Report should note which tier was used for each rule's verification. ### HITL Gate > **After Step 5 (Equivalence Report):** A domain expert or engineering lead validates the Behavioral Equivalence Report before the legacy component is retired. This is the final gate before the Eliminate phase — the human must confirm that all verified rules are equivalent, all differences are acceptable, and all missing rules are addressed. *** ## Step-by-Step Walkthrough ### Step 1: Setup Start by loading the Business Rules Inventory and establishing the verification scope for the specific component under test. **Confirm the project and locate the Business Rules Inventory:** ``` List my CoreStory projects. I need the project for [SystemName]. Then list all conversations — I need the Business Rules Inventory thread and the decomposition thread. ``` Look for "RESOLVED - \[Business Rules] SystemName" and "RESOLVED - \[Decomposition] SystemName" from prior phases. **Retrieve the Business Rules Inventory:** ``` Retrieve the conversation history from our Business Rules Inventory (conversation [conversation_id]). I need: 1. The complete list of business rules cataloged 2. For each rule: the rule ID, description, legacy implementation location, and classification (critical / important / minor) 3. Any rules that were flagged as ambiguous or requiring domain expert clarification ``` **Scope the verification to this component:** ``` send_message: "From the Business Rules Inventory, identify all rules that apply to [ComponentName]. This includes: 1. Rules directly implemented in [ComponentName] 2. Rules that [ComponentName] enforces as part of a larger workflow 3. Rules that depend on [ComponentName]'s behavior (downstream rules) 4. Cross-cutting rules (authorization, validation, logging) that [ComponentName] participates in Produce a scoped verification checklist with rule IDs, descriptions, and the legacy implementation locations." ``` **Create the verification conversation:** ``` Create a CoreStory conversation titled "[Verification] SystemName - ComponentName". Store the conversation_id for all subsequent queries. ``` ### Step 2: Rule-by-Rule Verification This is the core of the verification process. For each business rule in the scoped checklist, verify that the modernized implementation preserves the behavioral semantics. The following example illustrates what rule tracing produces for a single business rule — tracing the legacy and modernized implementations side by side with comparison indicators: ```mermaid theme={null} %%{init: {'theme': 'base', 'themeVariables': { 'primaryColor': '#1a1a2e', 'primaryTextColor': '#ffffff', 'primaryBorderColor': '#c9a84c', 'lineColor': '#c9a84c', 'fontFamily': 'Inter, system-ui, sans-serif'}}}%% graph LR subgraph rule["BR-007: Order total must include tax calculation based on shipping destination"] direction LR end subgraph legacy["Legacy Implementation"] direction TB L_FILE["📄 OrderService.java:245"] L_INPUT["Input: order items, shipping address"] L_CALC["Logic: Tax = subtotal × rate(state)
Rounding: HALF_UP to 2 decimals"] L_SIDE["Side effect: writes tax_audit_log"] L_OUT["Output: order.taxAmount"] L_FILE --> L_INPUT --> L_CALC --> L_SIDE --> L_OUT end subgraph modern["Modernized Implementation"] direction TB M_FILE["📄 order-service/src/tax.ts:18"] M_INPUT["Input: order items, shipping address"] M_CALC["Logic: Tax = subtotal × rate(state)
Rounding: HALF_UP to 2 decimals"] M_SIDE["Side effect: emits TaxCalculated event"] M_OUT["Output: order.taxAmount"] M_FILE --> M_INPUT --> M_CALC --> M_SIDE --> M_OUT end L_INPUT ---|"✅ Match"| M_INPUT L_CALC ---|"✅ Match"| M_CALC L_SIDE ---|"⚠️ Different mechanism,
same data captured"| M_SIDE L_OUT ---|"✅ Match"| M_OUT VERDICT["Status: Equivalent
Logic matches despite structural differences.
Side effect mechanism changed (DB write → event)
but same audit data is captured."] legacy ~~~ VERDICT modern ~~~ VERDICT style rule fill:#0f3460,stroke:#c9a84c,stroke-width:1px,color:#c9a84c style legacy fill:#1a1a2e,stroke:#c9a84c,stroke-width:1px,color:#c9a84c style modern fill:#1a1a2e,stroke:#c9a84c,stroke-width:1px,color:#c9a84c style L_FILE fill:#16213e,stroke:#555,color:#ccc style L_INPUT fill:#16213e,stroke:#555,color:#ccc style L_CALC fill:#16213e,stroke:#555,color:#ccc style L_SIDE fill:#16213e,stroke:#555,color:#ccc style L_OUT fill:#16213e,stroke:#555,color:#ccc style M_FILE fill:#16213e,stroke:#555,color:#ccc style M_INPUT fill:#16213e,stroke:#555,color:#ccc style M_CALC fill:#16213e,stroke:#555,color:#ccc style M_SIDE fill:#16213e,stroke:#555,color:#ccc style M_OUT fill:#16213e,stroke:#555,color:#ccc style VERDICT fill:#14532d,stroke:#22c55e,stroke-width:2px,color:#86efac ``` **Trace rules to modernized implementations:** ``` send_message: "For each business rule in the verification checklist, locate its implementation in the modernized codebase: 1. Where is the rule implemented? (file, function/method, line range) 2. Is the implementation in a single location or distributed across multiple files/services? 3. Is the implementation direct (explicit logic) or indirect (enforced via framework, middleware, database constraints)? Map each rule to its modernized implementation location(s)." ``` **Compare behavioral semantics:** ``` send_message: "For each business rule, compare the legacy and modernized implementations: Rule: [Rule ID] - [Description] Legacy: [file:line range] Modern: [file:line range] Compare: 1. Input conditions — do both implementations trigger on the same conditions? 2. Logic — are the transformations, calculations, and decisions semantically equivalent? 3. Side effects — do both produce the same downstream effects (database writes, events emitted, notifications sent)? 4. Error handling — do both handle failure cases the same way? 5. Output — given the same input, do both produce the same result? Classify as: - EQUIVALENT: Semantically identical behavior - IMPROVED: Modernized version handles the rule better (explain how) - DIFFERENT: Behavior differs (explain the difference) - MISSING: Rule not found in modernized code" ``` **Handle ambiguous rules:** ``` send_message: "For rules where the legacy implementation is unclear or appears to contain bugs: 1. What does the legacy code actually do? (not what it's supposed to do, but what it does) 2. Is the behavior intentional or accidental? Check commit history, comments, and surrounding context for clues 3. Does the modernized version reproduce the legacy behavior or 'fix' it? 4. Flag this for domain expert review — should the modernized version preserve the bug or fix it?" ``` **Batch verification for rule clusters:** For components with many rules, group related rules and verify them together: ``` send_message: "Group the remaining rules by functional area (e.g., validation rules, calculation rules, authorization rules, workflow rules). For each group: 1. Verify the group as a cluster — are all rules in this group implemented and semantically equivalent? 2. Identify any rules within the group that interact with each other — does the interaction behave the same in both systems? 3. Flag any rules where the modernized implementation changes the interaction pattern even if individual rules are equivalent" ``` ### Step 3: Edge Case & Invariant Testing Business rules are tested against their expected behavior. Edge cases test the boundaries where implementations often diverge. **Identify boundary conditions:** ``` send_message: "For each verified business rule, identify the boundary conditions and edge cases: 1. Null/empty inputs — how does each implementation handle missing data? 2. Maximum/minimum values — are there numeric limits, string length limits, or collection size limits? 3. Concurrent access — does the rule behave correctly when multiple users/processes trigger it simultaneously? 4. Temporal boundaries — timezone transitions, daylight saving, leap years, end-of-month/year 5. Currency and precision — rounding behavior, floating-point edge cases, multi-currency handling 6. State transitions — what happens at the boundaries between valid states? For each edge case, compare the legacy and modernized behavior." ``` **Check system invariants:** ``` send_message: "Identify the invariants that the legacy system enforces — constraints that are always true regardless of input: 1. Data integrity invariants (e.g., 'account balance equals sum of transactions') 2. State machine invariants (e.g., 'orders can only transition forward: pending → confirmed → shipped → delivered') 3. Referential invariants (e.g., 'every line item belongs to exactly one order') 4. Security invariants (e.g., 'user can only access their own data') 5. Temporal invariants (e.g., 'created_at is never after updated_at') Are all of these invariants preserved in the modernized code? If any are enforced differently (e.g., moved from application code to database constraints), document the change." ``` **Test implicit behaviors:** ``` send_message: "What implicit behaviors exist in the legacy implementation that might not be captured by explicit business rules? 1. Default values — what happens when optional parameters are omitted? 2. Ordering guarantees — does the legacy system return results in a specific order that consumers depend on? 3. Timing behavior — are there implicit timeouts, retry logic, or rate limits? 4. Logging and audit trail — does the legacy system produce audit records that downstream systems or compliance requires? 5. Error message format — do consumers parse error messages or depend on specific error codes? These implicit behaviors are often the source of 'invisible' regressions that don't show up until production." ``` ### Step 4: Integration Point Verification Verify that the modernized component interacts correctly with adjacent systems — especially important during the Coexist phase when some components are legacy and some are modernized. **API contract verification:** ``` send_message: "Compare the API contracts (or function signatures, message formats, etc.) between the legacy and modernized component: 1. Do all endpoints/methods that existed in legacy exist in modern? 2. Are request/response formats identical? Any added/removed/renamed fields? 3. Are HTTP status codes (or error codes) the same for the same conditions? 4. Are pagination, sorting, and filtering behaviors preserved? 5. Are authentication/authorization requirements identical? Flag any differences — even additive changes (new optional fields) can break consumers that do strict validation." ``` **Data format and encoding verification:** ``` send_message: "Compare data handling between legacy and modernized: 1. Character encoding — is the modernized component handling character sets the same way (UTF-8, Latin-1, etc.)? 2. Date/time formats — are timestamps formatted the same way in API responses and database records? 3. Numeric precision — are decimal places, rounding rules, and numeric types consistent? 4. Null handling — does the modernized component use null, empty string, or default values in the same places as legacy? 5. Serialization — JSON property names, XML element names, field ordering in responses" ``` **Downstream impact analysis:** ``` send_message: "For each system that consumes output from [ComponentName]: 1. What does the consumer expect? (data format, response time, error handling) 2. Will the modernized component meet those expectations? 3. Are there any consumers that depend on legacy-specific behavior (e.g., a specific bug, a deprecated field, a particular response ordering)? 4. During the Coexist phase, does the façade correctly route traffic and translate between legacy and modern formats?" ``` ### Step 5: Equivalence Report The interactive dashboard below shows what the verification status looks like at a glance — hover over any square for rule details: > *Sample data shown above — replace with actual verification results for your component.* Compile all verification findings into the structured Behavioral Equivalence Report. **Generate the report:** ``` send_message: "Compile the verification results into a Behavioral Equivalence Report for [ComponentName]: 1. Summary — total rules verified, equivalent, different, missing 2. Rule-by-rule verification table — ID, description, legacy location, modern location, status, notes 3. Behavioral differences — detailed analysis of each difference: is it an intentional improvement, acceptable deviation, or regression? 4. Missing rules — rules not found in modernized code, with recommended action 5. Edge case findings — boundary conditions where behavior differs 6. Integration point verification — API contract, data format, downstream impact results 7. Recommendation — ready for Eliminate, needs remediation, or needs domain expert review Use the report template from this playbook." ``` **Mark the thread complete:** ``` Rename the conversation to "RESOLVED - [Verification] SystemName - ComponentName". ``` *** ## Output Format: Behavioral Equivalence Report Each verified component produces a report following this template: ```markdown theme={null} # Behavioral Equivalence Report: [Component Name] **Date:** [Date] **Verified by:** [Engineer name + agent used] **Legacy Component:** [identifier — service name, module path, or package] **Modernized Component:** [identifier] **CoreStory Project:** [project_id] **Business Rules Inventory Reference:** [conversation_id from Phase 2] **Work Package Reference:** [WP-XXX from Decomposition & Sequencing] ## Summary | Metric | Count | |--------|-------| | Total rules in scope | [count] | | Rules verified equivalent | [count] | | Rules with intentional improvements | [count] | | Rules with behavioral differences | [count] | | Rules missing from modernized code | [count] | | Rules requiring domain expert review | [count] | **Overall status:** [Ready for Eliminate / Needs Remediation / Needs Review] ## Rule-by-Rule Verification | Rule ID | Description | Legacy Location | Modern Location | Status | Notes | |---------|-------------|----------------|-----------------|--------|-------| | BR-001 | [Description] | `legacy/path:line` | `modern/path:line` | Equivalent | | | BR-002 | [Description] | `legacy/path:line` | `modern/path:line` | Improved | [What improved] | | BR-003 | [Description] | `legacy/path:line` | `modern/path:line` | Different | [See Differences] | | BR-004 | [Description] | `legacy/path:line` | Not found | Missing | [See Missing Rules] | ## Behavioral Differences ### BR-003: [Rule Description] **Legacy behavior:** [What the legacy code does] **Modernized behavior:** [What the modernized code does] **Difference:** [Specific behavioral difference] **Classification:** - [ ] Intentional improvement (modernized version is correct, legacy had a bug) - [ ] Acceptable deviation (behavior differs but outcomes are equivalent) - [ ] Regression (modernized version is incorrect, must be fixed) **Domain expert review required:** [Yes/No] **Action:** [Fix / Accept / Review with domain expert] ## Missing Rules ### BR-004: [Rule Description] **Legacy implementation:** `legacy/path:line` — [brief description of legacy logic] **Why missing:** [Rule was not implemented / Rule was consolidated into another rule / Rule is no longer applicable] **Risk:** [What could go wrong if this rule is not preserved] **Action:** [Implement / Confirm removal with domain expert / N/A] ## Edge Case Findings | Edge Case | Legacy Behavior | Modern Behavior | Status | |-----------|----------------|-----------------|--------| | Null input to [field] | Returns default value | Throws validation error | Different | | Maximum [value] exceeded | Silently truncates | Returns error message | Improved | | Concurrent [operation] | Last-write-wins | Optimistic locking | Improved | ## Integration Point Verification | Integration Point | Contract Match | Data Format Match | Notes | |-------------------|---------------|-------------------|-------| | [API endpoint] | Yes | Yes | | | [Event published] | Yes | Partial | [Timestamp format differs] | | [Database schema] | Yes | Yes | | ## Invariants Verified | Invariant | Legacy Enforcement | Modern Enforcement | Preserved | |-----------|-------------------|-------------------|-----------| | [Description] | Application logic | Database constraint | Yes (mechanism changed) | | [Description] | Application logic | Application logic | Yes | ## Recommendation **Status:** [Choose one] - [ ] **Ready for Eliminate** — All rules verified, differences are acceptable, no missing rules - [ ] **Needs Remediation** — [count] rules must be fixed before proceeding (see Missing Rules / Regressions) - [ ] **Needs Domain Expert Review** — [count] differences require human judgment before classification **Required actions before Eliminate:** 1. [Action item — e.g., "Implement BR-004 in modernized component"] 2. [Action item — e.g., "Domain expert to review BR-003 difference"] 3. [Action item — e.g., "Fix timestamp format in event publishing"] **Sign-off:** - [ ] Engineering lead reviewed and approved - [ ] Domain expert validated behavioral differences - [ ] All required actions completed and re-verified ``` *** ## Prompting Patterns Reference ### Verification Patterns | Pattern | Example | | ---------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | | **Rule tracing** | "Where is \[Rule ID] implemented in the modernized code? Is the implementation semantically equivalent to the legacy version at \[file:line]?" | | **Behavioral diff** | "Compare how the legacy and modernized systems handle \[specific scenario]. Are the outcomes identical?" | | **Intent inference** | "The legacy code at \[file:line] does \[behavior]. Is this an intentional business rule or an artifact of the implementation?" | | **Completeness check** | "Are there any business rules in the legacy \[ComponentName] that are NOT in the Business Rules Inventory? Rules we might have missed?" | ### Edge Case Patterns | Pattern | Example | | ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------- | | **Boundary testing** | "What happens when \[field] is null, empty, at maximum value, or at minimum value — in both legacy and modern?" | | **Concurrency** | "What happens when two users simultaneously trigger \[operation]? Does the legacy system handle this differently than modern?" | | **Temporal boundaries** | "How do the legacy and modernized systems handle \[operation] at timezone boundaries, DST transitions, and leap year dates?" | | **Error propagation** | "When \[upstream dependency] fails, how do legacy and modern handle the error? Same retry logic, same fallback, same error response?" | ### Integration Patterns | Pattern | Example | | ----------------------- | ------------------------------------------------------------------------------------------------------------------------- | | **Contract comparison** | "Compare the API contract of legacy \[endpoint] with modernized \[endpoint]. Any differences in request/response format?" | | **Data flow tracing** | "Trace the data flow for \[operation] through both systems. Are there points where data is transformed differently?" | | **Consumer impact** | "Which systems consume output from \[ComponentName]? Will any of them break with the modernized version's behavior?" | ### Characterization Test Patterns | Pattern | Example | | ---------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Golden master generation** | "What inputs should we capture to create a comprehensive golden master for \[ComponentName]? Consider: representative cases, boundary values, error conditions, and high-frequency production scenarios." | | **Input set design** | "Based on the business rules inventory, what is the minimum set of test inputs that exercises every rule in \[ComponentName]?" | | **Output comparison** | "The golden master test for \[scenario] shows a difference in \[field]. Is this a behavioral change or a formatting/precision difference?" | ### Production Verification Patterns | Pattern | Example | | ------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Shadow traffic scope** | "Which API endpoints in \[ComponentName] handle the highest-risk business logic? These should be prioritized for shadow traffic testing." | | **Discrepancy analysis** | "The shadow traffic comparison flagged \[N] discrepancies. Analyze the patterns: are these concentrated in specific scenarios, or distributed randomly?" | | **Record-replay design** | "What production traffic should we capture for record-replay testing of \[ComponentName]? Consider: peak load scenarios, end-of-period processing, and cross-timezone operations." | ### Data Migration Patterns | Pattern | Example | | ---------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Reconciliation checklist** | "What data integrity checks should we run after migrating \[ComponentName]'s data? Consider: row counts, referential integrity, computed fields, and audit trail continuity." | | **Semantic validation** | "Which derived or computed fields in \[ComponentName]'s data store need to be recalculated and validated after migration?" | *** ## Best Practices **Verify against the inventory, not against the legacy code.** The Business Rules Inventory from Phase 2 is the behavioral contract. Verify against that, not against every line of legacy code. Legacy code contains bugs, workarounds, dead code, and obsolete behavior — not all of it should be preserved. The inventory captures what *should* be preserved. **Classify differences before fixing them.** Not every behavioral difference is a bug. Some are intentional improvements (the modernized version handles an edge case better). Some are acceptable deviations (the behavior differs in a way that doesn't affect outcomes). Only regressions need to be fixed. Classifying before fixing prevents wasted work on "fixing" improvements. **Involve domain experts for ambiguous rules.** When the legacy code does something unusual and neither the engineer nor CoreStory can determine whether it's intentional, escalate to a domain expert. These ambiguous behaviors are often the most critical — they're the institutional knowledge that exists only in the code and in people's heads. **Verify invariants, not just individual rules.** Individual rules can each be correct while their interaction produces different system-level behavior. Invariant checking catches these emergent differences — the system-wide constraints that no single rule fully defines but the system as a whole must maintain. **Don't skip integration point verification.** Even if every business rule is perfectly equivalent, the modernized component can still break consumers if the API contract, data format, or error handling differs. This is especially important during the Coexist phase when the façade is translating between legacy and modern. **Test implicit behaviors.** The most dangerous regressions are the ones that don't map to any explicit business rule — default values, ordering guarantees, timing behavior, error message formats. These "invisible" behaviors often aren't in the Business Rules Inventory because nobody thought to document them. Ask CoreStory to identify them. **Verify incrementally, not all at once.** For components with many business rules, verify in batches grouped by functional area. This makes the verification manageable, allows parallel verification by multiple engineers, and produces partial results that can inform ongoing Transform work on other components. **Let verification upgrade confidence states.** Each finding from earlier phases carries a confidence level (Verified, High-confidence, Hypothesized, or Contradicted — see [Working with AI-Derived Findings](/playbooks/code-modernization#working-with-ai-derived-findings)). Phase 6 is where Hypothesized findings can be promoted: a rule that was Hypothesized during assessment but now passes Tier 1 static verification and Tier 2 characterization testing can be upgraded to Verified. Track these upgrades in the Behavioral Equivalence Report — they strengthen the evidence base for stakeholder sign-off. **Tailor verification depth to behavior tags.** If Phase 3 assigned [behavior tags](/playbooks/modernization/target-architecture), use them to calibrate verification effort. `PRESERVE` behaviors need full equivalence proof — same inputs, same outputs, same side effects. `MODERNIZE` behaviors need equivalence plus evidence of improvement. `CHANGE` behaviors need stakeholder sign-off that the new behavior matches intent, not legacy behavior. `RETIRE` behaviors need confirmation that removal doesn't break consumers. This prevents over-investing in behaviors that were intentionally changed while under-investing in behaviors that must be identical. *** ## 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: | Harness | Install location | | --------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Claude Code** | `.claude/skills//SKILL.md` — Claude loads the body when the YAML `description` matches the task | | **GitHub Copilot** | Append to `.github/copilot-instructions.md` for repo-wide instructions, or save as `.github/instructions/.instructions.md` with an `applyTo` glob for path-scoped use | | **Cursor** | `.cursor/rules/.mdc` with a `description` field for auto-attach (use `globs` for path-scoped or `alwaysApply: true` for every session) | | **Factory.ai** | `.factory/droids/.md` (project) or `~/.factory/droids/.md` (personal); Factory loads it as a custom Droid | | **Aider** | `CONVENTIONS.md` at repo root, loaded with `aider --read CONVENTIONS.md` — or add it to the `read:` list in `.aider.conf.yml` for automatic loading | | **Codex / `AGENTS.md` harnesses** | Append the content to `AGENTS.md` at your repository root | | **Custom runtime** | Load the markdown into your agent's system prompt, rules file, or wherever it consumes workflow context | Want a single install that works across the most harnesses? Append the content to `AGENTS.md` at your repository root. The [`AGENTS.md` spec](https://agents.md/) 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 accordions below walk through end-to-end setup (skill file, slash command, version control) for the four most common harnesses. If you're on a different harness, copy the SKILL.md content from any accordion and install it per the conventions above. #### Setup 1. **Configure the CoreStory MCP server** in your Claude Code settings (see [CoreStory MCP Server Setup Guide](/getting-started/mcp-server-setup)). 2. **Add the skill file:** ```bash theme={null} mkdir -p .claude/skills/behavioral-verification ``` Create `.claude/skills/behavioral-verification/SKILL.md` with the content from the skill file below. 3. **Commit to version control:** ```bash theme={null} git add .claude/skills/ git commit -m "Add CoreStory behavioral verification skill" ``` #### Usage ``` Verify behavioral equivalence for [ComponentName] Check if the modernized [ComponentName] preserves all business rules Generate a behavioral equivalence report for [ComponentName] ``` #### Tips * This skill focuses on Phase 6 of the broader modernization workflow. It expects Phase 2 (Business Rules Inventory) to be complete. * The skill works best when both legacy and modernized code are in the same CoreStory project or when prior conversation threads contain the Business Rules Inventory. * Keep the SKILL.md under 500 lines for reliable loading. #### Skill File Save as `.claude/skills/behavioral-verification/SKILL.md`: ````markdown theme={null} --- name: CoreStory Behavioral Verification description: Verifies that modernized components preserve business rules from the Phase 2 inventory using CoreStory's code intelligence. Activates on verification, equivalence checking, or behavioral comparison requests. --- # CoreStory Behavioral Verification When this skill activates, guide the user through the five-step workflow to produce a Behavioral Equivalence Report for a modernized component. ## Activation Triggers Activate when user requests: - Behavioral verification or equivalence checking - Business rule verification for a modernized component - Comparison between legacy and modernized implementations - Verification report generation - Any request containing "verify", "equivalence", "behavioral", "business rules preserved", "regression check" ## Prerequisites - Completed Business Rules Inventory (Phase 2) - Modernized component functionally complete (Transform phase done) - CoreStory MCP server configured with completed ingestion **If you do not detect that you have access to CoreStory (e.g., `list_projects` fails or is unavailable), ask the user to verify that their MCP or API connection is properly configured and that this repository has been ingested. If the user has not yet created a CoreStory account, direct them to create one and upload their repo at [app.corestory.ai](https://app.corestory.ai).** ## Step 1: Setup 1. Identify target project (`list_projects`) 2. Locate Business Rules Inventory conversation (`list_conversations`) 3. Retrieve the inventory and scope to the component under verification 4. Create conversation: "[Verification] SystemName - ComponentName" ## Step 2: Rule-by-Rule Verification - Trace each business rule to its modernized implementation - Compare behavioral semantics: conditions, logic, side effects, error handling, output - Classify: Equivalent / Improved / Different / Missing - Flag ambiguous rules for domain expert review ## Step 3: Edge Case & Invariant Testing - Test boundary conditions: nulls, max/min values, concurrency, temporal edges - Verify system invariants are preserved - Identify implicit behaviors not captured in explicit rules ## Step 4: Integration Point Verification - Compare API contracts (endpoints, formats, status codes) - Verify data format consistency (encoding, dates, precision, nulls) - Assess downstream consumer impact ## Step 5: Equivalence Report - Compile rule-by-rule verification results - Analyze behavioral differences (improvement / deviation / regression) - Document missing rules with recommended actions - Produce recommendation: Ready for Eliminate / Needs Remediation / Needs Review **HITL Gate: Domain expert or engineering lead validates the report before the legacy component is retired.** ## Error Handling - **Business Rules Inventory not found:** Direct user to complete Phase 2 first - **Modernized code not yet complete:** Partial verification is possible but flag incomplete areas - **Ambiguous legacy behavior:** Flag for domain expert — do not assume it's a bug - **Rule cannot be verified statically:** Recommend runtime comparison testing ## When Static Analysis Is Insufficient If Tier 1 (static verification) cannot establish equivalence for a rule, escalate: - **Tier 2 (Characterization Testing):** Generate a golden master test suite. Use CoreStory to identify the input set, then run the legacy system to capture outputs. ``` send_message: "What inputs should I use to create a comprehensive golden master for [ComponentName]? I need inputs that exercise every business rule, boundary condition, and error path identified in the inventory." ``` - **Tier 3 (Shadow Traffic):** Design a shadow traffic configuration. Use CoreStory to identify which endpoints to shadow and what comparison logic to apply. ``` send_message: "Which endpoints in [ComponentName] handle the highest-risk business logic? What fields in the response should I compare between legacy and modern to detect behavioral differences?" ``` - **Tier 4 (Data Migration):** If applicable, generate a data reconciliation checklist. ``` send_message: "What data integrity checks should I run after migrating [ComponentName]'s data? Include row counts, referential integrity checks, and validation of computed/derived fields." ``` ```` Add the following to `.github/copilot-instructions.md`: ```markdown theme={null} ## Behavioral Verification When asked to verify behavioral equivalence between legacy and modernized code: 1. ALWAYS load the Business Rules Inventory from Phase 2 first 2. Scope verification to the specific component under test 3. Trace each rule to its modernized implementation and compare semantics 4. Classify differences: Equivalent, Improved, Different, or Missing 5. Test edge cases and invariants — these catch the regressions that explicit rules miss 6. Verify integration points — API contracts, data formats, downstream consumers 7. Produce a structured Behavioral Equivalence Report 8. Domain expert must validate the report before legacy component is retired 9. If static analysis is inconclusive for a rule, escalate to Tier 2 (characterization/golden master testing), Tier 3 (shadow traffic), or Tier 4 (data reconciliation) as appropriate ``` **(Optional) Add a reusable prompt file.** Create `.github/prompts/behavioral-verification.prompt.md`: ```markdown theme={null} --- mode: agent description: Verify behavioral equivalence between legacy and modernized components using CoreStory --- Verify that the modernized component preserves all business rules from the Phase 2 inventory. 1. Load the Business Rules Inventory and scope to the component under verification 2. Trace each business rule to its modernized implementation 3. Compare behavioral semantics: conditions, logic, side effects, error handling, output 4. Classify: Equivalent / Improved / Different / Missing 5. Test edge cases, invariants, and implicit behaviors 6. Verify integration points and downstream consumer compatibility 7. Produce a Behavioral Equivalence Report with recommendation ``` Create `.cursor/rules/behavioral-verification/RULE.md`: ```markdown theme={null} --- description: CoreStory-powered behavioral verification for modernized components. Activates for equivalence checking, business rule verification, regression checking, or verification report generation. alwaysApply: false --- # CoreStory Behavioral Verification You are a verification engineer with access to CoreStory's code intelligence via MCP. Verify that modernized components preserve the behavioral semantics of the legacy system. ## Activation Triggers Apply when user requests: behavioral verification, equivalence checking, business rule verification, regression checking, or verification report generation for modernized components. **If you do not detect that you have access to CoreStory (e.g., `list_projects` fails or is unavailable), ask the user to verify that their MCP or API connection is properly configured and that this repository has been ingested. If the user has not yet created a CoreStory account, direct them to create one and upload their repo at [app.corestory.ai](https://app.corestory.ai).** ## Five-Step Workflow ### Step 1: Setup - Load Business Rules Inventory from Phase 2 - Scope to the component under verification - Create verification conversation ### Step 2: Rule-by-Rule Verification - Trace each rule to modernized implementation - Compare: conditions, logic, side effects, error handling, output - Classify: Equivalent / Improved / Different / Missing - Flag ambiguous rules for domain expert review ### Step 3: Edge Case & Invariant Testing - Boundary conditions: nulls, max/min, concurrency, temporal edges - System invariants: data integrity, state machines, referential, security - Implicit behaviors: defaults, ordering, timing, audit trails, error formats ### Step 4: Integration Point Verification - API contract comparison (endpoints, formats, status codes, pagination) - Data format verification (encoding, dates, precision, null handling) - Downstream consumer impact analysis ### Step 5: Equivalence Report - Rule-by-rule verification table - Difference analysis with classification - Missing rules with recommended actions - Recommendation: Ready for Eliminate / Needs Remediation / Needs Review - **HITL Gate: Domain expert validates report** ## Key Principles - Verify against the inventory, not against every line of legacy code - Classify differences before fixing them — not every difference is a bug - Involve domain experts for ambiguous rules - Don't skip integration point verification - Test implicit behaviors — the most dangerous regressions are invisible - If static analysis is inconclusive, escalate: Tier 2 (golden master), Tier 3 (shadow traffic), Tier 4 (data reconciliation) ``` Create `.factory/droids/behavioral-verification.md`: ```markdown theme={null} --- name: CoreStory Behavioral Verification description: Verifies modernized components preserve business rules using CoreStory code intelligence model: inherit tools: - CoreStory:list_projects - CoreStory:get_project_prd - CoreStory:create_conversation - CoreStory:send_message - CoreStory:rename_conversation - CoreStory:list_conversations - CoreStory:get_conversation --- # CoreStory Behavioral Verification Execute the five-step workflow to produce a Behavioral Equivalence Report for a modernized component. ## Activation Triggers - "Verify behavioral equivalence" or "check business rules" - "Compare legacy and modernized" or "regression check" - "Generate verification report" or "equivalence report" - Any behavioral verification or rule comparison request ## CoreStory MCP Tools - `CoreStory:list_projects` — identify the target project - `CoreStory:get_project_prd` — retrieve PRD for business context - `CoreStory:create_conversation` — open verification thread - `CoreStory:send_message` — query CoreStory for rule tracing and comparison - `CoreStory:list_conversations` / `CoreStory:get_conversation` — load Business Rules Inventory - `CoreStory:rename_conversation` — mark completed thread "RESOLVED" **If you do not detect that you have access to CoreStory (e.g., `list_projects` fails or is unavailable), ask the user to verify that their MCP or API connection is properly configured and that this repository has been ingested. If the user has not yet created a CoreStory account, direct them to create one and upload their repo at [app.corestory.ai](https://app.corestory.ai).** ## Workflow Step 1: Setup → Load Business Rules Inventory, scope to component, create conversation Step 2: Rule-by-Rule Verification → Trace, compare, classify (Equivalent/Improved/Different/Missing) Step 3: Edge Case & Invariant Testing → Boundaries, invariants, implicit behaviors Step 4: Integration Point Verification → API contracts, data formats, downstream consumers Step 5: Equivalence Report → Compile findings → HITL domain expert validation ## Key Principles - Verify against the Phase 2 inventory, not against every line of legacy code - Classify differences before fixing: improvement, acceptable deviation, or regression - Ambiguous legacy behavior → escalate to domain expert, don't assume it's a bug - Test implicit behaviors — defaults, ordering, timing, audit trails - Integration point verification is mandatory, not optional - If static analysis is inconclusive, escalate: Tier 2 (golden master), Tier 3 (shadow traffic), Tier 4 (data reconciliation) ``` *** ## Troubleshooting **The Business Rules Inventory is incomplete or missing rules.** This is the most common verification failure. If the inventory doesn't cover all the rules in the component, verification will have gaps. Ask CoreStory: "Are there any business rules in the legacy \[ComponentName] that are NOT in the Business Rules Inventory?" If significant rules are missing, go back to [Business Rules Extraction](/playbooks/business-rules-extraction) and update the inventory before continuing. **Legacy behavior appears to be a bug — should the modernized version preserve it?** This is a domain expert decision, not an engineering decision. Document the behavior, explain why you suspect it's a bug, and escalate. Some "bugs" are actually undocumented requirements — customers may depend on the buggy behavior. The safe default is to preserve legacy behavior unless a domain expert explicitly approves the change. **The modernized component uses a completely different architecture — direct rule tracing is impossible.** When the modernized code restructures logic significantly (e.g., extracting a rules engine, using event sourcing), direct file-to-file comparison won't work. Shift to behavioral diffing: compare outcomes for specific scenarios rather than code structure. Ask CoreStory: "Given input \[scenario], what does the legacy system produce? What does the modernized system produce? Are they equivalent?" **Too many rules to verify — the report would take weeks.** Prioritize by risk. Verify critical rules (financial calculations, security, data integrity) first. Then important rules (core business logic, workflow). Minor rules (formatting, display) can be verified later or deferred to runtime testing. Ask CoreStory to help classify: "Which of these rules have the highest impact if they regress?" **Static analysis is inconclusive for a rule.** The legacy implementation is too complex, uses external state, or relies on runtime behavior that can't be verified through code analysis alone. Escalate to Tier 2: generate a characterization test (golden master) for that specific rule. If the rule involves production-specific behavior (load-dependent, timing-dependent), escalate to Tier 3 (shadow traffic). Document which tier was used in the Behavioral Equivalence Report. **Integration point verification reveals incompatibilities during Coexist.** If the modernized component's API contract differs from legacy, the façade layer must translate. This is expected during Coexist — the façade exists precisely for this purpose. Document the translation the façade performs, verify the façade produces legacy-compatible output, and plan for façade removal when all consumers are updated. **Agent can't access CoreStory tools.** See the [Supercharging AI Agents](/getting-started/supercharging-ai-agents) troubleshooting section for MCP connection issues. Verify the project has completed ingestion by calling `list_projects` and checking the status. *** ## What's Next **Component passed verification:** Proceed to the Eliminate phase — retire the legacy component and remove the façade. See [Decomposition & Sequencing →](/playbooks/modernization/decomposition-sequencing) for the Eliminate phase structure in your work package. **Component needs remediation:** Fix the missing rules or regressions, then re-run verification for the affected rules. You don't need to re-verify the entire component — just the rules that changed. **Start the next component:** Move to the next work package in the migration sequence. Each component cycles through Transform → Coexist (with verification) → Eliminate. **Return to the hub:** [Code Modernization →](/playbooks/code-modernization) — the full six-phase framework. **For business rules extraction:** [Business Rules Extraction →](/playbooks/business-rules-extraction) — the Phase 2 playbook that produces the behavioral contract verified here. **For agent setup:** [Supercharging AI Agents with CoreStory →](/getting-started/supercharging-ai-agents) — MCP server configuration and agent setup. # Codebase Assessment Source: https://docs.corestory.ai/playbooks/modernization/codebase-assessment Evaluate a legacy codebase's modernization readiness using CoreStory's persistent code intelligence — architecture mapping, dependency analysis, tech debt identification, and risk scoring. ## Overview Every modernization program starts with the same question: what exactly are we dealing with? The answer is almost never what people expect. Engineering teams who've worked on a system for years consistently discover architectural connections, dead code paths, and undocumented dependencies during a formal assessment. Tribal knowledge covers the 20% of the system that changes regularly. The other 80% — the batch jobs that run once a month, the integration points nobody remembers building, the utility modules that seven services quietly depend on — hide until you look systematically. Traditional assessment approaches rely on manual code sampling and architect interviews, producing a snapshot of what people *think* the system looks like. CoreStory changes this by ingesting and semantically understanding the entire codebase, giving your assessment team an **Expert** that can answer specific architectural questions against the full system — not a sample, not a summary, the actual code. This playbook provides a structured methodology for evaluating a codebase's modernization readiness across seven domains: architectural complexity, dependency chains, technical debt, security and compliance, testability, data architecture, and — critically for mainframe systems — non-code artifacts that encode business logic never captured in application code. **Who this is for:** Architects, engineering leads, and modernization teams performing the first phase of a modernization initiative. Also useful for consultants and system integrators scoping modernization engagements. **What you'll get:** A Modernization Readiness Report with an architecture map, dependency graph, tech debt inventory, risk register, and component-level readiness scores with a recommended modernization strategy per component. **Relationship to M\&A Due Diligence:** This playbook shares methodology DNA with the [M\&A Technical Due Diligence](/playbooks/ma-technical-due-diligence) playbook — both systematically interrogate a codebase across risk domains. The difference is the lens. M\&A evaluates a codebase you *don't* own for acquisition risk. Codebase Assessment evaluates a codebase you *do* own for transformation readiness. The interrogation categories differ accordingly: M\&A focuses on deal-affecting risks (licensing, secrets, PII exposure); Codebase Assessment focuses on transformation-readiness factors (coupling, decomposability, testability, data architecture). *** ## When to Use This Playbook * You're planning a modernization initiative and need a rigorous baseline of the current system's architecture, dependencies, and technical debt * You need to determine *which* modernization strategy (the 7 Rs) applies to each component — not a single system-wide strategy * You're evaluating whether a legacy system is ready for modernization at all, or whether prerequisites (test coverage, documentation, domain expertise) must be addressed first * You need evidence-based scope and effort estimates for a modernization proposal * You're inheriting a legacy system from another team and need architectural orientation before making changes ## When to Skip This Playbook * You already have a recent, thorough architectural assessment and need to move directly to strategy selection — start at [Target Architecture](/playbooks/modernization/target-architecture) * You're evaluating a codebase for acquisition rather than internal modernization — use [M\&A Technical Due Diligence](/playbooks/ma-technical-due-diligence) instead * The system is trivially small (under \~10k LOC) and its architecture is self-evident — you can proceed directly to refactoring * You've already decided on a full rebuild with no legacy component reuse — the assessment adds less value when nothing will be retained *** ## Prerequisites * A **CoreStory account** with the legacy codebase ingested and ingestion complete * An **AI coding agent** with CoreStory MCP configured (see [Supercharging AI Agents](/getting-started/supercharging-ai-agents) for setup) * **Repository access** for the legacy codebase (for the agent to cross-reference CoreStory findings against source) * (Recommended) Access to **architecture documentation**, if it exists — even outdated docs help frame questions * (Recommended) **Domain experts** who can validate architectural findings — especially for mainframe systems where business logic hides in non-code artifacts (JCL, copybooks, CICS configuration, VSAM data stores) *** ## How It Works ### CoreStory MCP Tools Used This playbook uses the following tools from the CoreStory MCP server: | Tool | Step(s) | Purpose | | ---------------------- | ------------- | ------------------------------------------------------------- | | `list_projects` | 1 | Find the target project | | `create_conversation` | 1 | Start a dedicated assessment conversation thread | | `send_message` | 2, 3, 4, 5, 6 | Query CoreStory for architecture analysis and risk assessment | | `get_project_prd` | 1 | Retrieve synthesized PRD for business context | | `get_project_techspec` | 1 | Retrieve synthesized TechSpec for architecture analysis | | `list_conversations` | Any | Review existing conversation threads | | `get_conversation` | Any | Retrieve conversation history for report synthesis | | `rename_conversation` | 6 | Mark completed thread with "RESOLVED" prefix | **A note on the PRD and TechSpec:** These documents are often very large — too large for an agent to hold in a single context window. Rather than reading them end-to-end, query CoreStory about their contents via `send_message`. CoreStory has already ingested these documents and can answer targeted questions about them efficiently. ### The Assessment Workflow > **Note:** The steps below are internal to this playbook. They are sub-steps of Phase 1 in the [six-phase modernization framework](/playbooks/code-modernization), not a separate numbering system. Codebase assessment with CoreStory follows a six-step pattern: 1. **Setup & Orientation** — Confirm the target project, review synthesized specs for architectural context, and create a named conversation thread for the assessment. 2. **Architecture Mapping** — Map major components, services, data stores, and communication patterns. Establish the structural vocabulary that all subsequent steps reference. 3. **Dependency Analysis** — Identify internal coupling, external dependencies, shared data stores, and integration points. This step reveals what *can* be decomposed and what *must* move together. 4. **Tech Debt & Risk Assessment** — Catalog technical debt, security risks, compliance gaps, and code quality issues. Each finding includes severity and blast radius. 5. **Modernization Readiness Scoring** — Score each component on modernization readiness. Recommend a modernization strategy (from the 7 Rs) per component, not one strategy for the whole system. 6. **Report Generation** — Synthesize findings into the Modernization Readiness Report. This is the deliverable that feeds Phase 3 (Target Architecture) of the broader modernization workflow. ### Expert Before Navigator Before searching for specific issues or code paths, first use CoreStory to understand how the system is *designed* to work — its intended architecture, data flow patterns, and integration model. This architectural baseline makes it far easier to spot deviations, shortcuts, coupling hotspots, and technical debt. Ask "what is this system?" before asking "what's wrong with this system?" ```mermaid theme={null} %%{init: {'theme': 'base', 'themeVariables': { 'primaryColor': '#1a1a2e', 'primaryTextColor': '#ffffff', 'primaryBorderColor': '#c9a84c', 'lineColor': '#c9a84c', 'secondaryColor': '#16213e', 'tertiaryColor': '#0f3460', 'fontFamily': 'Inter, system-ui, sans-serif'}}}%% graph TD subgraph foundation["🧭 Expert Before Navigator — Understand architecture from specs before searching for issues"] direction LR F1[" "] end P1["Step 1: Setup & Orientation
Confirm project · Load TechSpec + PRD
Create assessment conversation"] P2["Step 2: Architecture Mapping
Components · Communication patterns
Data stores · Entry points · Non-code artifacts"] P3["Step 3: Dependency Analysis
Internal coupling · Shared data stores
External dependencies · Integration fragility"] P4["Step 4: Tech Debt & Risk
Code quality · Security · Compliance
Testability · Operational complexity"] P5["Step 5: Readiness Scoring
Per-component 1–5 score
7 Rs strategy recommendation"] P6["Step 6: Report Generation
Modernization Readiness Report"] HITL{"👤 HITL Gate
Stakeholder review
Go / No-go"} NEXT["→ Phase 3: Target Architecture"] P1 --> P2 P2 --> P3 P3 --> P4 P4 --> P5 P5 --> P6 P6 --> HITL HITL -->|Approved| NEXT HITL -->|Not Ready| PREREQ["Address prerequisites
before proceeding"] foundation ~~~ P1 style P1 fill:#1a1a2e,stroke:#c9a84c,stroke-width:2px,color:#ffffff style P2 fill:#1a1a2e,stroke:#c9a84c,stroke-width:2px,color:#ffffff style P3 fill:#1a1a2e,stroke:#c9a84c,stroke-width:2px,color:#ffffff style P4 fill:#1a1a2e,stroke:#c9a84c,stroke-width:2px,color:#ffffff style P5 fill:#1a1a2e,stroke:#c9a84c,stroke-width:2px,color:#ffffff style P6 fill:#1a1a2e,stroke:#c9a84c,stroke-width:2px,color:#ffffff style HITL fill:#c9a84c,stroke:#1a1a2e,stroke-width:2px,color:#1a1a2e style NEXT fill:#0f3460,stroke:#c9a84c,stroke-width:2px,color:#ffffff style PREREQ fill:#4a1a1a,stroke:#c9a84c,stroke-width:1px,color:#ffffff style foundation fill:#0f3460,stroke:#c9a84c,stroke-width:1px,color:#c9a84c style F1 fill:none,stroke:none ``` *** ## Step-by-Step Walkthrough ### Step 1: Setup & Orientation Start every assessment by confirming the target and building architectural context. **Confirm the target project:** ``` List my CoreStory projects. I need to identify the project for [SystemName]. ``` The agent calls `list_projects` and returns your available projects. Confirm the correct project before proceeding — this prevents accidentally assessing the wrong codebase if multiple projects are loaded. **Review synthesized specifications:** ``` For project [project_id], retrieve the Technical Specification and Product Requirements Document. Give me a high-level summary of: 1. System architecture (major components, services, data stores) 2. Technology stack (languages, frameworks, infrastructure) 3. External integrations and third-party dependencies 4. Data model overview 5. Deployment model (how is this system deployed and operated?) ``` The agent calls `get_project_techspec` and `get_project_prd`. This gives you architectural orientation and — critically — the vocabulary (service names, module names, data model names) that makes all subsequent queries specific and productive. **Create the assessment conversation:** ``` Create a CoreStory conversation titled "[Assessment] SystemName - Modernization Readiness". Store the conversation_id — we'll use this thread for all assessment queries. ``` Using a dedicated conversation thread keeps the assessment organized and produces a clean audit trail that other team members can review. ### Step 2: Architecture Mapping With architectural context established, use `send_message` to build a comprehensive map of the system's structure. This step establishes the facts that all subsequent steps analyze. The following worked example shows what an architecture map looks like for a hypothetical e-commerce monolith. Your map will look different — this shows the structure and level of detail to aim for: ```mermaid theme={null} %%{init: {'theme': 'base', 'themeVariables': { 'primaryColor': '#1a1a2e', 'primaryTextColor': '#ffffff', 'primaryBorderColor': '#c9a84c', 'lineColor': '#666666', 'fontFamily': 'Inter, system-ui, sans-serif'}}}%% graph TB subgraph external["External Systems"] EXT1["Payment Gateway
REST API"] EXT2["Identity Provider
SAML / OAuth 2.0"] EXT3["Email Service
SMTP"] end subgraph app["Application Components"] direction TB subgraph web["Web Layer"] UI["Web UI
React · 45k LOC"] API["API Gateway
Express · 12k LOC"] end subgraph services["Service Layer"] ORD["OrderService
Java · 28k LOC"] INV["InventoryService
Java · 15k LOC"] PAY["PaymentService
Java · 22k LOC"] USR["UserService
Java · 18k LOC"] RPT["ReportingService
Python · 8k LOC"] end subgraph batch["Batch Jobs"] B1["Nightly Reconciliation"] B2["Monthly Billing"] end end subgraph data["Data Stores"] DB1[("Primary DB
PostgreSQL
⚠️ Shared writes")] DB2[("Reporting DB
PostgreSQL replica")] CACHE[("Cache
Redis")] MQ[["Message Queue
RabbitMQ"]] end UI -->|REST| API API -->|sync| ORD API -->|sync| USR ORD -->|sync| INV ORD -->|sync| PAY ORD -.->|async| MQ MQ -.->|async| RPT PAY -->|REST| EXT1 USR -->|SAML| EXT2 ORD -->|SMTP| EXT3 ORD -->|read/write| DB1 INV -->|read/write| DB1 PAY -->|read/write| DB1 USR -->|read/write| DB1 RPT -->|read| DB2 ORD -->|read/write| CACHE B1 -->|read/write| DB1 B2 -->|read| DB1 style DB1 fill:#4a1a1a,stroke:#ff6b6b,stroke-width:2px,color:#ffffff style external fill:#0f3460,stroke:#c9a84c,stroke-width:1px,color:#c9a84c style app fill:#1a1a2e,stroke:#c9a84c,stroke-width:1px,color:#c9a84c style web fill:#16213e,stroke:#555,stroke-width:1px,color:#aaa style services fill:#16213e,stroke:#555,stroke-width:1px,color:#aaa style batch fill:#16213e,stroke:#555,stroke-width:1px,color:#aaa style data fill:#1a1a2e,stroke:#c9a84c,stroke-width:1px,color:#c9a84c style UI fill:#1a1a2e,stroke:#c9a84c,color:#fff style API fill:#1a1a2e,stroke:#c9a84c,color:#fff style ORD fill:#1a1a2e,stroke:#c9a84c,color:#fff style INV fill:#1a1a2e,stroke:#c9a84c,color:#fff style PAY fill:#1a1a2e,stroke:#c9a84c,color:#fff style USR fill:#1a1a2e,stroke:#c9a84c,color:#fff style RPT fill:#1a1a2e,stroke:#c9a84c,color:#fff style B1 fill:#1a1a2e,stroke:#666,color:#aaa style B2 fill:#1a1a2e,stroke:#666,color:#aaa style DB2 fill:#1a1a2e,stroke:#c9a84c,color:#fff style CACHE fill:#1a1a2e,stroke:#c9a84c,color:#fff style MQ fill:#1a1a2e,stroke:#c9a84c,color:#fff style EXT1 fill:#0f3460,stroke:#c9a84c,color:#fff style EXT2 fill:#0f3460,stroke:#c9a84c,color:#fff style EXT3 fill:#0f3460,stroke:#c9a84c,color:#fff ``` > Note the shared-write database highlighted in red — data coupling is typically the primary decomposition challenge. **Component inventory:** ``` send_message: "Provide a complete inventory of the major components, services, and modules in this system. For each, describe its purpose, the technology it's built with, and its approximate size (files, lines of code if available). Organize by logical domain or bounded context." ``` **Communication patterns:** ``` send_message: "How do the components in this system communicate with each other? Map all inter-service communication patterns — synchronous calls (REST, gRPC, direct method invocation), asynchronous messaging (queues, events, pub/sub), and shared database access. For each communication path, identify the source component, target component, and mechanism." ``` **Data store mapping:** ``` send_message: "What data stores does this system use? Map each database, cache, file store, and message broker. For each, identify which components read from it, which components write to it, and whether multiple components share the same store. Flag any shared databases where multiple components write to the same tables." ``` **Entry points and boundaries:** ``` send_message: "Identify all external entry points into this system — API endpoints, UI routes, batch job triggers, event consumers, scheduled tasks. For each, describe what it does and which internal components it touches." ``` **Beyond the code (mainframe and legacy systems):** For mainframe systems and older legacy platforms, business logic often lives outside application code. This assessment domain is critical — miss it and you'll undercount the scope of modernization by 30–50%. ``` send_message: "Identify all non-code artifacts that encode business logic or system behavior. This includes: - JCL (Job Control Language) workflows and batch scheduling - Copybook definitions and data structure layouts - CICS transaction definitions and screen maps - VSAM/IMS data store configurations and access methods - Sort utility control statements - System exits and middleware configuration - Stored procedures, triggers, and database-level business logic - Configuration files that control business behavior (routing rules, validation thresholds, feature flags) For each artifact type found, describe what business logic it encodes and where it lives in the repository or deployment environment." ``` ### Step 3: Dependency Analysis Dependency analysis reveals what *can* be decomposed and what *must* move together. This is the step that most directly feeds Phase 4 (Decomposition & Sequencing) of the broader modernization workflow. **Internal coupling:** ``` send_message: "Map the internal dependency chains between components. Which components directly depend on which others? Identify: 1. Components with the highest fan-in (most other components depend on them) 2. Components with the highest fan-out (they depend on the most others) 3. Circular dependencies (A depends on B depends on A) 4. Hub components (everything passes through them) For each dependency, specify whether it's a compile-time dependency, runtime dependency, or data dependency." ``` **Shared data stores:** ``` send_message: "Which components share database tables or data stores? For each shared resource, identify: 1. All components that read from it 2. All components that write to it 3. Whether there are foreign key relationships that cross component boundaries 4. Whether any components use database triggers or stored procedures that affect other components' data This is the primary indicator of decomposition difficulty — shared data stores are the hardest coupling to break." ``` **External dependencies:** ``` send_message: "List all external system dependencies — third-party APIs, SaaS integrations, external databases, message brokers, identity providers, payment processors, and any other systems this codebase communicates with. For each, describe: 1. What data is exchanged 2. Which internal components interact with it 3. Whether the integration uses a standard protocol or custom logic 4. What happens if the external system is unavailable" ``` **Integration point fragility:** ``` send_message: "For the external integrations you identified, which are the most fragile? Identify integrations with: 1. No retry logic or circuit breakers 2. Hardcoded URLs or credentials 3. Tight version coupling (would break if the external API changes) 4. No fallback behavior 5. Missing timeout configuration" ``` ### Step 4: Tech Debt & Risk Assessment This step catalogs specific issues that affect modernization feasibility, cost, and risk. Each finding should include a severity assessment and blast radius (how much of the system does it affect). **Code quality and structural debt:** ``` send_message: "Identify areas of the codebase with high complexity or poor separation of concerns: 1. God classes or modules (excessive responsibility, high line count) 2. Circular dependencies between modules 3. Duplicated business logic across components (same rule implemented in multiple places, possibly inconsistently) 4. Missing abstraction layers (direct database access from UI components, business logic in controllers, etc.) 5. Inconsistent patterns across similar components For each finding, provide the file path and a brief description of the issue." ``` **Dead code and abandoned modules:** ``` send_message: "Are there modules, services, or code paths that appear to be abandoned or unused — no recent modification, no test coverage, referenced but not actively invoked at runtime? Identify: 1. Dead code paths (unreachable code, commented-out logic) 2. Unused dependencies (imported but never called) 3. Deprecated APIs still in use 4. Feature flags or configuration that control disabled features List them with file paths and evidence of disuse." ``` **Security posture:** ``` send_message: "Assess the security posture of this codebase: 1. Authentication and authorization patterns — are they consistent across all entry points? Standard (OAuth 2.0, SAML, JWT) or custom? 2. Hardcoded secrets — API keys, passwords, tokens, connection strings in the codebase (provide file paths) 3. PII data flows — where is personally identifiable information collected, transmitted, and stored? Is it encrypted at rest and in transit? 4. Input validation — are there entry points that accept user input without validation or sanitization? 5. Dependency vulnerabilities — known CVEs in third-party libraries" ``` **Compliance considerations:** ``` send_message: "Identify compliance-relevant patterns in the codebase: 1. Data residency — where is data stored? Are there geographic constraints on where data can be processed or persisted? 2. Audit logging — is there systematic logging of data access and mutations? 3. Access control — is there role-based or attribute-based access control? How granular is it? 4. Data retention and deletion — are there mechanisms for data expiration or right-to-be-forgotten compliance? Certain modernization patterns may be constrained by compliance requirements (PCI-DSS, HIPAA, SOX, GDPR). Identifying these early prevents choosing a strategy that compliance will later block." ``` **Testability assessment:** ``` send_message: "Evaluate the testability of this codebase: 1. What test coverage exists? Is it primarily unit tests, integration tests, or end-to-end tests? 2. Can individual components be tested in isolation, or do tests require the full system to be running? 3. What is the test infrastructure — CI/CD pipeline, test environments, test data management? 4. Are there characterization tests or golden master tests that capture current behavior? 5. Which critical code paths have NO test coverage? Low test coverage is a modernization blocker — you can't verify behavioral equivalence without a way to define 'correct.'" ``` **Operational complexity:** ``` send_message: "Describe the operational characteristics of this system: 1. How is the system deployed? Manual process, CI/CD pipeline, container orchestration, custom scripts? 2. What configuration management exists? Environment variables, config files, feature flags, database-driven configuration? 3. What monitoring and observability is in place? Logging, metrics, tracing, alerting? 4. What are the known operational pain points — frequent incidents, manual intervention required, scaling limitations?" ``` ### Step 5: Modernization Readiness Scoring With the architectural map, dependency graph, and risk inventory complete, score each component's readiness for modernization and recommend a strategy. The interactive heatmap below shows what the output looks like — click any row for component details: > *Sample data shown above — replace with actual assessment scores from your Step 5 analysis.* **Component-level readiness scoring:** ``` send_message: "Based on everything we've discussed — architecture, dependencies, tech debt, security, testability, and operational complexity — score each major component on modernization readiness. For each component, provide: 1. Component name and brief description 2. Readiness score (1-5): - 5: Ready to modernize immediately (low coupling, good test coverage, clear boundaries) - 4: Ready with minor preparation (some coupling to resolve, some tests to add) - 3: Moderate preparation needed (shared data stores, moderate coupling, limited test coverage) - 2: Significant preparation required (deep coupling, no tests, shared state with multiple components) - 1: Not ready (extreme coupling, no test coverage, undocumented business logic, compliance blockers) 3. Recommended strategy from the 7 Rs: Retire / Retain / Rehost / Relocate / Replatform / Refactor/Re-architect / Repurchase 4. Key blockers or prerequisites for modernization 5. Estimated relative effort (low / medium / high / very high) Remember: 53% of enterprises pursue hybrid strategies — different components get different strategies. Don't force a single approach." ``` **Recommended sequencing:** ``` send_message: "Given the readiness scores and dependency map, what order would you recommend for modernizing these components? Consider: 1. Dependency chains (what must be modernized before what) 2. Components that must move together (can't be separated due to data coupling) 3. Quick wins (high readiness, high business value, low risk) 4. Risk sequencing (tackle the riskiest components early or late?) Provide a recommended sequence with rationale for the ordering." ``` ### Step 6: Report Generation Synthesize the assessment into the Modernization Readiness Report — the deliverable that feeds Phase 3 (Target Architecture) of the broader modernization workflow. ``` Review our entire conversation history for this assessment thread. Synthesize all findings into a Modernization Readiness Report with these sections: 1. Executive Summary — modernization readiness at a glance: overall readiness level, number of components assessed, recommended strategies, top 3-5 findings that most affect modernization feasibility 2. Architecture Map — components, services, data stores, communication patterns, external integrations 3. Dependency Graph — internal coupling map, shared data stores, external dependencies, circular dependencies 4. Tech Debt Inventory — categorized by severity (critical / high / medium / low) and blast radius (how much of the system does it affect) 5. Risk Register — security, compliance, data integrity, and operational risks (each with file-level evidence and severity rating) 6. Component Readiness Scores — per-component assessment with readiness score, recommended strategy (7 Rs), key blockers, and estimated effort 7. Recommended Modernization Sequence — ordered list with dependency rationale 8. Prerequisites & Blockers — what must be addressed before modernization can begin (test coverage gaps, missing documentation, compliance requirements) ``` **Mark the assessment complete:** ``` Rename the conversation to "RESOLVED - [Assessment] SystemName - Modernization Readiness". ``` ### HITL Gate > **After Step 6 (Report Generation):** The Modernization Readiness Report must be reviewed and approved by technical leadership before proceeding to Phase 2 (Business Rules Inventory) or Phase 3 (Target Architecture). This is a go/no-go decision point. The report should be reviewed by: * **Technical leadership** (CTO, VP Engineering, or Principal Architect) — validates the assessment methodology and strategic recommendations * **Product/business stakeholders** — validates that the recommended modernization strategy aligns with business priorities and timelines * **(Recommended) Domain experts** — especially for mainframe or legacy systems where business logic resides in non-code artifacts. Domain experts can validate whether the assessment correctly identified hidden dependencies and business rules * **(Recommended) Security/compliance** — if the assessment flagged compliance constraints that affect modernization strategy **What gets decided at this gate:** 1. **Go / No-go:** Is modernization warranted, or is Retain the right strategy for all or most components? 2. **Scope confirmation:** Do the recommended strategies per component make sense? Should any be reclassified? 3. **Priority alignment:** Does the recommended sequencing align with business priorities? 4. **Prerequisite resolution:** Are there organizational prerequisites (staffing, governance, budget) that must be addressed before proceeding? Do not proceed to Target Architecture without this approval. The assessment informs every downstream decision — an unapproved assessment creates compounding errors. *** ## Output Format: Modernization Readiness Report The assessment produces a structured report that serves as the input to Phase 3 (Target Architecture & Strategy). Here is the template: ```markdown theme={null} # Modernization Readiness Report: [SystemName] **Date:** [Date] **Assessed by:** [Team/Individual] **CoreStory Project:** [project_id] **Assessment Conversation:** [conversation_id] ## Executive Summary **Overall Readiness:** [Ready / Ready with Preparation / Significant Preparation Needed / Not Ready] **Components Assessed:** [count] **Recommended Strategy Distribution:** - Retire: [count] components - Retain: [count] components - Rehost: [count] components - Relocate: [count] components - Replatform: [count] components - Refactor / Re-architect: [count] components - Repurchase: [count] components **Top Findings:** 1. [Most significant finding affecting modernization feasibility] 2. [Second most significant] 3. [Third most significant] ## Architecture Map ### Components | Component | Domain | Technology | Size | Communication Pattern | |-----------|--------|------------|------|----------------------| | [Name] | [Domain] | [Stack] | [LOC/files] | [Sync/Async/Shared DB] | ### Data Stores | Store | Type | Components (Read) | Components (Write) | Shared? | |-------|------|-------------------|--------------------|---------| | [Name] | [RDBMS/NoSQL/Cache/...] | [List] | [List] | [Yes/No] | ### External Integrations | System | Protocol | Components | Data Exchanged | Fallback? | |--------|----------|------------|----------------|-----------| | [Name] | [REST/SOAP/MQ/...] | [List] | [Description] | [Yes/No] | ## Dependency Graph ### Internal Coupling [Describe coupling hotspots, hub components, circular dependencies] ### Shared Data Dependencies | Shared Resource | Components | Coupling Severity | Decomposition Difficulty | |----------------|------------|-------------------|------------------------| | [Table/Store] | [List] | [High/Medium/Low] | [High/Medium/Low] | ## Tech Debt Inventory | ID | Category | Description | Location | Severity | Blast Radius | |----|----------|-------------|----------|----------|-------------| | TD-001 | [Code Quality/Security/Compliance/...] | [Description] | [file path] | [Critical/High/Medium/Low] | [System-wide/Component/Local] | ## Risk Register | ID | Domain | Risk | Evidence | Severity | Mitigation | |----|--------|------|----------|----------|------------| | RR-001 | [Security/Compliance/Data/Operational] | [Description] | [file path or finding] | [Critical/High/Medium/Low] | [Recommended action] | ## Component Readiness Scores | Component | Readiness (1-5) | Recommended Strategy | Key Blockers | Effort | |-----------|----------------|---------------------|-------------|--------| | [Name] | [Score] | [7 Rs strategy] | [List] | [Low/Med/High/Very High] | ## Recommended Modernization Sequence | Order | Component(s) | Strategy | Rationale | Prerequisites | |-------|-------------|----------|-----------|--------------| | 1 | [Name] | [Strategy] | [Why first] | [What must be in place] | ## Prerequisites & Blockers ### Must Address Before Modernization - [Blocker 1 — description and recommended remediation] - [Blocker 2] ### Recommended Preparation - [Preparation item — what it enables] ``` *** ## Prompting Patterns Reference ### Assessment Patterns Effective assessment queries are specific, domain-anchored, and evidence-oriented. They ask for file paths, concrete examples, and measurable indicators — not summaries. | Pattern | Example | | ------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | | **Component inventory** | "List all major components with their purpose, technology, and approximate size. Organize by domain." | | **Communication mapping** | "Map all inter-service communication paths. For each, identify source, target, mechanism, and whether it's synchronous or asynchronous." | | **Coupling detection** | "Which components share database tables? For each shared table, list all reading and writing components." | | **Tech debt identification** | "Identify god classes over 500 lines with methods that mix business logic and infrastructure concerns. Provide file paths." | | **Testability assessment** | "Which critical code paths have no test coverage? Identify the highest-risk untested paths." | | **Non-code artifact discovery** | "Identify all JCL jobs, copybook definitions, and CICS transaction maps. For each, describe the business logic it encodes." | ### Query Specificity After reviewing the Tech Spec in Step 1, use the architectural vocabulary it provides in all subsequent queries. Vague queries produce vague answers. | Instead of | Use | | -------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | | "Tell me about the architecture" | "Map the communication paths between OrderService, InventoryService, and PaymentService, including shared database tables and message queues" | | "How's the code quality?" | "Identify modules with circular dependencies, classes over 500 lines, or methods with more than 5 parameters. Provide file paths." | | "What are the dependencies?" | "Which components would break if we extracted OrderService as a standalone service? What data and logic would need to move with it?" | | "Is it ready to modernize?" | "For the inventory module specifically: what is its test coverage, how many other components depend on it, and does it share database tables with other modules?" | *** ## Best Practices **Start with the synthesized specs, not with questions.** Use `get_project_techspec` and `get_project_prd` before diving into `send_message` queries. The specs give you architectural vocabulary — service names, data model names, API patterns — that make your queries far more specific and productive. **Assess every component, even the ones you think you know.** Engineers who've worked on a system for years consistently discover surprises during a formal assessment. CoreStory surfaces connections that tribal knowledge misses — the utility module that seven services quietly depend on, the batch job that silently populates a cache every night, the database trigger that enforces a business rule nobody documented. **Don't forget non-code artifacts.** For mainframe systems and older legacy platforms, 30–50% of business logic lives in JCL workflows, copybook definitions, CICS transaction maps, stored procedures, and configuration files. If your assessment only covers application code, your modernization scope estimate will be significantly under-counted. **Ask for file paths, always.** Every finding in the readiness report needs evidence. Train your queries to always request file paths and specific code references. "Identify X and provide the file path" should be your default pattern. **Score honestly — Retain is a legitimate outcome.** 53% of enterprises pursue hybrid strategies ([Kyndryl 2025 State of IT Infrastructure Report](https://www.kyndryl.com/us/en/perspectives/articles/2025/01/state-of-it-infrastructure-report)). Not every component needs to be modernized. The assessment should identify components where the cost of modernization exceeds the benefit, and "Retain" is the correct strategy for those components. A good assessment saves money by preventing unnecessary modernization as much as by enabling necessary modernization. **Low test coverage is a blocker, not a footnote.** If a component has no test coverage, you cannot verify behavioral equivalence after modernization. The readiness report should flag this as a prerequisite: "Before modernizing \[component], establish characterization tests that capture current behavior." This is not optional — it's what prevents the 79% failure rate. **Scope your queries to avoid noise.** A query like "find all technical debt" will return an overwhelming response. Break it into targeted categories: code quality, security, compliance, testability, operational complexity. Each produces focused, actionable findings. **Track confidence levels for every finding.** Assessment findings are AI-derived — they vary in reliability. As you work through Steps 2–5, mentally categorize each finding as *Verified* (confirmed by a human or cross-referenced against running code), *High-confidence* (CoreStory is confident, consistent across multiple queries), *Hypothesized* (plausible but not yet validated), or *Contradicted* (conflicts with other evidence). This matters because downstream phases inherit your findings. A readiness score built on Hypothesized findings needs validation before it drives architectural decisions. See [Working with AI-Derived Findings](/playbooks/code-modernization#working-with-ai-derived-findings) for the full Confidence Protocol. *** ## 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: | Harness | Install location | | --------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Claude Code** | `.claude/skills//SKILL.md` — Claude loads the body when the YAML `description` matches the task | | **GitHub Copilot** | Append to `.github/copilot-instructions.md` for repo-wide instructions, or save as `.github/instructions/.instructions.md` with an `applyTo` glob for path-scoped use | | **Cursor** | `.cursor/rules/.mdc` with a `description` field for auto-attach (use `globs` for path-scoped or `alwaysApply: true` for every session) | | **Factory.ai** | `.factory/droids/.md` (project) or `~/.factory/droids/.md` (personal); Factory loads it as a custom Droid | | **Aider** | `CONVENTIONS.md` at repo root, loaded with `aider --read CONVENTIONS.md` — or add it to the `read:` list in `.aider.conf.yml` for automatic loading | | **Codex / `AGENTS.md` harnesses** | Append the content to `AGENTS.md` at your repository root | | **Custom runtime** | Load the markdown into your agent's system prompt, rules file, or wherever it consumes workflow context | Want a single install that works across the most harnesses? Append the content to `AGENTS.md` at your repository root. The [`AGENTS.md` spec](https://agents.md/) 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 accordions below walk through end-to-end setup (skill file, slash command, version control) for the four most common harnesses. If you're on a different harness, copy the SKILL.md content from any accordion and install it per the conventions above. #### Setup 1. **Configure the CoreStory MCP server** in your Claude Code settings (see [CoreStory MCP Server Setup Guide](/getting-started/mcp-server-setup)). 2. **Add the skill file.** Create the skill directory and file: ```bash theme={null} mkdir -p .claude/skills/codebase-assessment ``` Create `.claude/skills/codebase-assessment/SKILL.md` with the content from the skill file below. 3. **(Optional) Add the slash command:** ```bash theme={null} mkdir -p .claude/commands ``` Create `.claude/commands/assess.md` with a short description referencing the six-step assessment workflow. 4. **Commit to version control:** ```bash theme={null} git add .claude/skills/ .claude/commands/ git commit -m "Add CoreStory codebase assessment skill and command" ``` #### Usage The skill activates automatically when Claude Code detects assessment-related requests: ``` Run a codebase assessment for modernization readiness Assess this system's modernization readiness Evaluate the architecture for modernization planning ``` Or invoke explicitly: ``` /assess [SystemName] ``` #### Tips * This skill focuses on Phase 1 of the broader modernization workflow. For the full six-phase workflow, use the code-modernization skill instead. * Create a single CoreStory conversation for the entire assessment to maintain context across all steps. * Keep the SKILL.md under 500 lines for reliable loading. #### Skill File Save as `.claude/skills/codebase-assessment/SKILL.md`: ````markdown theme={null} --- name: CoreStory Codebase Assessment description: Evaluates a legacy codebase's modernization readiness using CoreStory's persistent code intelligence. Activates on assessment, readiness evaluation, or modernization planning requests. --- # CoreStory Codebase Assessment When this skill activates, guide the user through the six-step assessment workflow to produce a Modernization Readiness Report. ## Activation Triggers Activate when user requests: - Codebase assessment or modernization assessment - Modernization readiness evaluation - Architecture analysis for modernization planning - Legacy system evaluation or analysis - Any request containing "assess", "readiness", "evaluate architecture", "modernization planning" ## Prerequisites - CoreStory MCP server configured - At least one CoreStory project with completed ingestion (the legacy codebase) - Read access to the repository for cross-referencing findings **If you do not detect that you have access to CoreStory (e.g., `list_projects` fails or is unavailable), ask the user to verify that their MCP or API connection is properly configured and that this repository has been ingested. If the user has not yet created a CoreStory account, direct them to create one and upload their repo at [app.corestory.ai](https://app.corestory.ai).** ## Step 1: Setup & Orientation 1. **Identify the Target Project** ``` Use CoreStory MCP: list_projects ``` - Multiple projects → ask user which one to assess - Single project → confirm with user before proceeding - Verify ingestion is complete 2. **Retrieve Synthesized Specifications** ``` Use CoreStory MCP: get_project_techspec Use CoreStory MCP: get_project_prd ``` - Summarize: system architecture, technology stack, external integrations, data model, deployment model - This establishes the architectural vocabulary for all subsequent queries 3. **Create Assessment Conversation** ``` Use CoreStory MCP: create_conversation Title: "[Assessment] SystemName - Modernization Readiness" ``` Store conversation_id for all subsequent queries. **Report:** ``` 🔍 Starting codebase assessment for modernization readiness Target: [project name] Architecture: [high-level summary] Tech Stack: [languages, frameworks, infrastructure] CoreStory conversation: [conversation-id] ``` ## Step 2: Architecture Mapping Query CoreStory to map the system's structure: - "Provide a complete inventory of components, services, and modules with purpose, technology, and size" - "Map all inter-service communication patterns — sync, async, shared DB access" - "What data stores are used? Which components share them?" - "Identify all external entry points — APIs, batch triggers, event consumers, scheduled tasks" - For mainframe/legacy: "Identify non-code artifacts encoding business logic — JCL, copybooks, CICS, VSAM, stored procedures, configuration" ## Step 3: Dependency Analysis - "Map internal dependency chains. Identify highest fan-in, highest fan-out, circular dependencies, hub components" - "Which components share database tables? List all readers and writers per shared resource" - "List all external system dependencies with data exchanged, protocol, and fallback behavior" - "Which external integrations are most fragile? Missing retries, hardcoded URLs, tight version coupling?" ## Step 4: Tech Debt & Risk Assessment - "Identify god classes, circular dependencies, duplicated business logic, missing abstraction layers. Provide file paths." - "Find dead code, unused dependencies, deprecated APIs still in use" - "Assess security: auth patterns, hardcoded secrets, PII flows, input validation, dependency CVEs" - "Identify compliance-relevant patterns: data residency, audit logging, access control, data retention" - "Evaluate testability: coverage, test types, isolation capability, untested critical paths" - "Describe operational complexity: deployment, config management, monitoring, known pain points" ## Step 5: Modernization Readiness Scoring - "Score each component on readiness (1-5) with recommended 7 Rs strategy, key blockers, and effort estimate" - "Recommend modernization sequence based on dependencies, coupling, risk, and business value" ## Step 6: Report Generation 1. **Synthesize Report** Compile findings into Modernization Readiness Report: - Executive Summary (overall readiness, top findings) - Architecture Map (components, data stores, integrations) - Dependency Graph (coupling, shared data, external deps) - Tech Debt Inventory (by severity and blast radius) - Risk Register (security, compliance, data, operational) - Component Readiness Scores (per-component 7 Rs recommendation) - Recommended Sequence (ordered migration plan) - Prerequisites & Blockers 2. **Mark Completed** ``` Use CoreStory MCP: rename_conversation New title: "RESOLVED - [Assessment] SystemName - Modernization Readiness" ``` ## Error Handling - **Project not found:** List available projects, ask user to specify the target - **CoreStory gives generic answers:** Narrow queries — use specific service names, module names from the Tech Spec - **Response too long:** Break into smaller domain-specific queries - **Legacy system uses non-code artifacts:** Explicitly ask about JCL, copybooks, CICS, VSAM — CoreStory surfaces these if prompted - **Assessment reveals system isn't ready:** This is a valid finding — flag prerequisites that must be addressed first ```` #### Setup 1. **Configure the CoreStory MCP server** in your VS Code settings. Add it to your MCP server configuration (typically in VS Code settings JSON or the MCP configuration UI). 2. **Add custom instructions.** Copilot reads project-level instructions from `.github/copilot-instructions.md`. This is the primary mechanism for teaching Copilot specialized workflows: ```bash theme={null} mkdir -p .github ``` Add the following to `.github/copilot-instructions.md`: ```markdown theme={null} ## Codebase Assessment for Modernization When asked to assess a codebase for modernization readiness: 1. ALWAYS start by confirming the CoreStory project and retrieving the Tech Spec for architectural vocabulary 2. Map architecture first: components, data stores, communication patterns, non-code artifacts 3. Analyze dependencies: internal coupling, shared databases, external integrations, circular dependencies 4. Assess tech debt: code quality, security, compliance, testability, operational complexity 5. Score each component on readiness (1-5) with a 7 Rs strategy recommendation 6. Produce a Modernization Readiness Report — the deliverable for the next modernization phase 7. Always request file paths for every finding ``` 3. **(Optional) Add a reusable prompt file.** Create `.github/prompts/codebase-assessment.prompt.md`: ```markdown theme={null} --- mode: agent description: Assess a codebase's modernization readiness using CoreStory's code intelligence --- Perform a codebase assessment for modernization readiness on the specified system using CoreStory. 1. Identify the target project and retrieve synthesized specs for architectural orientation 2. Map architecture: components, services, data stores, communication patterns, non-code artifacts 3. Analyze dependencies: internal coupling, shared data stores, external integrations 4. Assess tech debt and risk: code quality, security, compliance, testability, operations 5. Score each component's modernization readiness and recommend a 7 Rs strategy 6. Compile a Modernization Readiness Report and mark the conversation resolved ``` 4. **Commit to version control:** ```bash theme={null} git add .github/copilot-instructions.md .github/prompts/ git commit -m "Add CoreStory codebase assessment instructions for Copilot" ``` #### Usage In Copilot Chat (agent mode): ``` Assess this codebase for modernization readiness Run a modernization readiness evaluation on project X Evaluate the architecture for modernization planning ``` Or reference the prompt file: ``` @workspace /codebase-assessment [SystemName] ``` #### Tips * Copilot's agent mode (available in VS Code) can execute terminal commands and edit files autonomously — this workflow works best in agent mode. * On Team/Enterprise plans, organization-level instructions apply across all repositories. * Copilot automatically references `.github/copilot-instructions.md` in chat responses. #### Setup 1. **Configure the CoreStory MCP server** in Cursor's MCP settings (Settings → MCP Servers, or edit the MCP config JSON directly). 2. **Add project rules:** ```bash theme={null} mkdir -p .cursor/rules/codebase-assessment ``` Create `.cursor/rules/codebase-assessment/RULE.md` with the content from the rule file below. 3. **Commit to version control:** ```bash theme={null} git add .cursor/rules/ git commit -m "Add CoreStory codebase assessment rules for Cursor" ``` #### Usage In Cursor's Composer or Chat, the rule activates automatically for assessment-related requests: ``` Assess this codebase for modernization readiness Evaluate the architecture for modernization planning Run a modernization readiness evaluation ``` #### Tips * Rules with `alwaysApply: true` load in every session. Set this if your team regularly performs assessments. Otherwise, use `alwaysApply: false` with a good `description` so Cursor loads it when relevant. * The `.cursor/rules/` directory structure is the current recommended approach. * Rules apply to Composer and Chat but do not affect Cursor Tab or inline edits. #### Project Rule Save as `.cursor/rules/codebase-assessment/RULE.md`: ```markdown theme={null} --- description: CoreStory-powered codebase assessment for modernization readiness. Activates for modernization assessments, readiness evaluations, and architecture analysis for modernization planning. alwaysApply: false --- # CoreStory Codebase Assessment You are a modernization architect with access to CoreStory's code intelligence via MCP. Follow the six-step assessment workflow to produce a Modernization Readiness Report. ## Activation Triggers Apply when user requests: codebase assessment, modernization readiness, architecture evaluation, legacy system analysis, or modernization planning. **If you do not detect that you have access to CoreStory (e.g., `list_projects` fails or is unavailable), ask the user to verify that their MCP or API connection is properly configured and that this repository has been ingested. If the user has not yet created a CoreStory account, direct them to create one and upload their repo at [app.corestory.ai](https://app.corestory.ai).** ## Six-Step Workflow ### Step 1: Setup & Orientation - Identify target project (`CoreStory:list_projects`) - Retrieve specs (`CoreStory:get_project_techspec`, `CoreStory:get_project_prd`) - Summarize architecture, tech stack, integrations, data model - Create assessment conversation (`CoreStory:create_conversation`) ### Step 2: Architecture Mapping - Component inventory with purpose, technology, and size - Communication patterns (sync, async, shared DB) - Data store mapping with shared access analysis - Entry points and boundaries - Non-code artifacts (JCL, copybooks, CICS, VSAM, stored procs, config) ### Step 3: Dependency Analysis - Internal coupling (fan-in, fan-out, circular deps, hub components) - Shared data stores (readers, writers, cross-boundary foreign keys) - External dependencies (protocol, data exchanged, fallback behavior) - Integration fragility (missing retries, hardcoded URLs, tight coupling) ### Step 4: Tech Debt & Risk Assessment - Code quality (god classes, duplication, missing abstractions) - Security (auth patterns, secrets, PII, CVEs) - Compliance (data residency, audit logging, retention) - Testability (coverage, isolation, untested critical paths) - Operational complexity (deployment, config, monitoring) ### Step 5: Modernization Readiness Scoring - Per-component readiness score (1-5) with 7 Rs recommendation - Recommended modernization sequence by dependency and risk ### Step 6: Report Generation - Compile Modernization Readiness Report - Rename conversation with "RESOLVED" prefix ## Key Principles - Expert before Navigator: understand architecture from specs first - Evidence-based: every finding needs a file path - Non-code artifacts matter: a significant share of mainframe business logic lives outside application code - Retain is legitimate: not every component needs modernization - Low test coverage is a blocker, not a footnote ``` #### 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:** ```bash theme={null} mkdir -p .factory/droids ``` Create `.factory/droids/codebase-assessment.md` with the content from the droid file below. 3. **Commit to version control:** ```bash theme={null} git add .factory/droids/ git commit -m "Add CoreStory codebase assessment droid" ``` #### Usage Invoke the droid via the Task tool: ``` @codebase-assessment Assess [SystemName] for modernization readiness ``` Or describe the task and Factory.ai routes to the droid based on its activation triggers. #### Tips * Use `model: inherit` in the YAML frontmatter to use whatever model the session is configured with. * The `tools` field explicitly lists required MCP tools — this restricts the droid to only the CoreStory tools needed for assessment. * The assessment queries may produce long streaming responses — this is expected. #### Custom Droid Save as `.factory/droids/codebase-assessment.md`: ```markdown theme={null} --- name: CoreStory Codebase Assessment description: Evaluates a legacy codebase's modernization readiness using CoreStory code intelligence model: inherit tools: - CoreStory:list_projects - CoreStory:get_project_prd - CoreStory:get_project_techspec - CoreStory:create_conversation - CoreStory:send_message - CoreStory:rename_conversation - CoreStory:list_conversations - CoreStory:get_conversation --- # CoreStory Codebase Assessment Execute the six-step assessment workflow to produce a Modernization Readiness Report. ## Activation Triggers - "Assess [system] for modernization" - "Codebase assessment" or "modernization readiness" - "Evaluate architecture for modernization" - "Legacy system analysis" - Any assessment or readiness evaluation request ## CoreStory MCP Tools - `CoreStory:list_projects` — identify the target project - `CoreStory:get_project_prd` — retrieve synthesized PRD for business context - `CoreStory:get_project_techspec` — retrieve Tech Spec for architecture - `CoreStory:create_conversation` — open named assessment thread - `CoreStory:send_message` — query CoreStory (primary investigation tool) - `CoreStory:rename_conversation` — mark completed thread "RESOLVED" - `CoreStory:list_conversations` / `CoreStory:get_conversation` — review threads When instructions say "Query CoreStory", use `CoreStory:send_message`. **If you do not detect that you have access to CoreStory (e.g., `list_projects` fails or is unavailable), ask the user to verify that their MCP or API connection is properly configured and that this repository has been ingested. If the user has not yet created a CoreStory account, direct them to create one and upload their repo at [app.corestory.ai](https://app.corestory.ai).** ## Workflow Step 1: Setup & Orientation → Confirm project, retrieve specs, create conversation Step 2: Architecture Mapping → Components, communication, data stores, entry points, non-code artifacts Step 3: Dependency Analysis → Internal coupling, shared data, external deps, fragility Step 4: Tech Debt & Risk → Code quality, security, compliance, testability, operations Step 5: Readiness Scoring → Per-component 1-5 score, 7 Rs recommendation, sequence Step 6: Report → Modernization Readiness Report → rename conversation "RESOLVED" ## Key Principles - Expert before Navigator: understand architecture from specs first - Evidence-based: every finding needs a file path - Non-code artifacts matter: JCL, copybooks, CICS, VSAM encode business logic - Retain is legitimate: not every component needs modernization - Low test coverage is a blocker, not a footnote - Ask specific questions using vocabulary from the Tech Spec ``` *** ## Troubleshooting **CoreStory returns generic or shallow answers about the architecture.** Your queries are too broad. After retrieving the Tech Spec, use the architectural vocabulary it provides — specific service names, module names, data model names — in your queries. "What are the dependencies?" is weak. "Which components depend on OrderService, and do any of them share the orders database tables?" is strong. **The assessment reveals the system isn't ready for modernization.** This is a valid and valuable finding. Common blockers: no test coverage (can't verify behavioral equivalence), extreme coupling (can't decompose), missing domain knowledge (can't validate business rules), compliance constraints that limit target architecture options. Use the assessment to build the case for investing in readiness *before* attempting modernization. A good assessment prevents expensive failures. **Non-code artifacts aren't showing up in the assessment.** CoreStory will surface JCL, copybooks, CICS maps, and other non-code artifacts if you explicitly ask about them. The default assessment queries focus on application code. For mainframe and older legacy systems, always include the "Beyond the Code" queries from Step 2. **Response exceeds token limit.** Break large queries into smaller scopes. Instead of "Map the complete architecture," ask about specific domains or layers. If a response is truncated, ask the agent to continue or narrow the scope. **Findings don't match current source code.** CoreStory's analysis reflects the codebase at ingestion time. If the system has changed significantly since ingestion, request a re-ingestion before finalizing your assessment report. Always note the ingestion date in your report for traceability. **Agent can't access CoreStory tools.** See the [Supercharging AI Agents](/getting-started/supercharging-ai-agents) troubleshooting section for MCP connection issues. Verify the project has completed ingestion by calling `list_projects` and checking the status. *** ## What's Next **Continue the modernization workflow:** This assessment feeds directly into Phase 3. Use the Modernization Readiness Report as the primary input for [Target Architecture & Strategy →](/playbooks/modernization/target-architecture). **Extract business rules:** Phase 2 of the modernization workflow runs in parallel with or immediately after assessment. Use [Business Rules Extraction →](/playbooks/business-rules-extraction) to catalog the behavioral contract that Phase 6 verifies against. **Return to the hub:** [Code Modernization →](/playbooks/code-modernization) — the full six-phase framework. **For agent setup:** [Supercharging AI Agents with CoreStory →](/getting-started/supercharging-ai-agents) — MCP server configuration and agent setup. # Decomposition & Sequencing Source: https://docs.corestory.ai/playbooks/modernization/decomposition-sequencing Use CoreStory to identify migration boundaries, map component dependencies, produce an ordered migration plan, and create work packages in Jira or Linear. ## Overview You have the target architecture. Now the question is: how do you get there without breaking everything along the way? Phase 4 of the modernization workflow is where strategy becomes execution planning. The Architectural Decision Record from Phase 3 defines what the system should become. This playbook turns that vision into a sequenced set of work packages — each one independently deployable, each one ordered by dependency, and each one structured around the Transform → Coexist → Eliminate cycle — the operational expression of the Strangler Fig pattern (Martin Fowler, 2004) that makes incremental modernization safe. Rather than replacing the legacy system in one big-bang release, each work package builds the new component (Transform), runs it alongside the legacy component with traffic routing (Coexist), and retires the legacy component only after behavioral equivalence is verified (Eliminate). The sequencing problem is harder than it looks. You can't just pick the easiest component and start — if that component shares a database with three others, you'll immediately hit data decomposition challenges. You can't just follow the dependency graph blindly either — sometimes the highest-risk component should go first (to retire risk early) and sometimes it should go last (to learn from easier migrations first). The right sequence balances dependency constraints, risk appetite, business value delivery, and team capability. CoreStory serves as a **Navigator** throughout this phase — mapping the specific dependencies, shared data stores, and integration points that determine what can be separated and what must move together. It also operates as an **Expert** for understanding the implications of each sequencing choice: "If we modernize this component first, what temporary integration work is needed for everything that still depends on it?" **Who this is for:** Engineering leads, project managers, and modernization teams responsible for planning and tracking the migration. Also useful for technical program managers coordinating cross-team modernization efforts. **What you'll get:** A sequenced set of work packages with scope, acceptance criteria, dependencies, estimated effort, and the Transform/Coexist/Eliminate structure for each — optionally pushed to Jira or Linear as epics and stories. *** ## When to Use This Playbook * You've completed Phase 3 (Target Architecture) and have an approved Architectural Decision Record * You need to break a modernization initiative into executable, independently-deployable work packages * You need to determine the migration sequence — what to modernize first, second, third — based on dependency analysis * You're preparing to push migration work into Jira, Linear, or another project management system * You need to identify which components *must* migrate together and which can be extracted independently ## When to Skip This Playbook * You haven't defined the target architecture yet — go back to [Target Architecture](/playbooks/modernization/target-architecture) * The modernization is a single-component refactor that doesn't need sequencing — use [Spec-Driven Development](/playbooks/spec-driven-development) directly * You're doing a lift-and-shift (Rehost/Relocate) with no application-level decomposition * You already have a sequenced migration plan and need to start execution — go to [Spec-Driven Development](/playbooks/spec-driven-development) for delta specs or the relevant [architecture variant](/playbooks/modernization/monolith-to-microservices) *** ## Prerequisites * A **completed Target Architecture decision** (Phase 3) — the Architectural Decision Record is the primary input * A **completed Codebase Assessment** (Phase 1) — the dependency graph and coupling analysis feed directly into sequencing * A **CoreStory account** with the legacy codebase ingested and ingestion complete * An **AI coding agent** with CoreStory MCP configured (see [Supercharging AI Agents](/getting-started/supercharging-ai-agents) for setup) * (Optional) **Jira or Linear MCP** configured alongside CoreStory for work package creation (see [Using CoreStory with Jira](/playbooks/using-corestory-with-jira)) * (Recommended) The **engineering lead** who will own the migration backlog should be driving this phase — sequencing decisions affect team assignments, sprint planning, and delivery timelines *** ## How It Works ### CoreStory MCP Tools Used | Tool | Step(s) | Purpose | | ---------------------- | ---------- | ----------------------------------------------------------------- | | `list_projects` | 1 | Confirm the target project | | `create_conversation` | 1 | Start a dedicated decomposition thread | | `send_message` | 2, 3, 4, 5 | Query CoreStory for dependency mapping and decomposition analysis | | `list_conversations` | 1 | Find prior phase conversations (assessment, architecture) | | `get_conversation` | 1 | Retrieve prior phase findings for cross-reference | | `get_project_techspec` | 1 | Retrieve Tech Spec for component vocabulary | | `get_project_prd` | 1 | Retrieve synthesized PRD for business context and requirements | | `rename_conversation` | 6 | Mark completed thread with "RESOLVED" prefix | ### The Decomposition & Sequencing Workflow > **Note:** The steps below are internal to this playbook. They are sub-steps of Phase 4 in the [six-phase modernization framework](/playbooks/code-modernization), not a separate numbering system. This playbook follows a six-step pattern: 1. **Input Loading** — Load the target architecture decision and dependency map from prior phases. Establish the migration scope. 2. **Component Decomposition** — Break the migration into discrete, independently-deployable work packages. Identify what can be separated and what must move together. 3. **Dependency Mapping** — Map dependencies between work packages. Identify the critical path and blocking relationships. 4. **Sequencing** — Order work packages by dependency, risk, and business value. Produce the migration sequence. 5. **Work Package Definition** — Define each work package with scope, acceptance criteria, dependencies, estimated effort, and the Transform/Coexist/Eliminate structure. 6. **Ticketing System Integration** — Push work packages to Jira or Linear as epics and stories (if MCP is available). ### The Strangler Fig Execution Model Each work package follows the Transform → Coexist → Eliminate cycle: 1. **Transform** — Build the modernized version of the component using [Spec-Driven Development](/playbooks/spec-driven-development). The legacy component remains untouched. 2. **Coexist** — Run both old and new versions simultaneously. Route traffic through a façade or proxy layer. Validate behavioral equivalence using [Behavioral Verification](/playbooks/modernization/behavioral-verification). 3. **Eliminate** — Once the modernized component passes verification, retire the legacy component and remove the façade. This cycle is the reason sequencing matters: each work package's Coexist phase requires temporary integration points (anti-corruption layers, adapters, data synchronization) with the components that haven't migrated yet. The sequence determines how much temporary integration work is needed at each step. Transform → Coexist → Eliminate lifecycle — three-phase cycle showing how each work package moves from building the new component, through coexistence with the legacy, to retirement ### Branch by Abstraction When a façade can't intercept traffic — shared libraries, data access layers, deeply embedded utility code — the Strangler Fig pattern doesn't apply. Branch by Abstraction (coined by Paul Hammant, popularized by Sam Newman in *Monolith to Microservices*) works from the inside: 1. **Introduce an abstraction layer** within the codebase that both old and new implementations can satisfy. This is an interface or adapter that wraps the current implementation. 2. **Build the new implementation** behind the abstraction. Both old and new implementations coexist in the codebase. 3. **Switch consumers incrementally.** Migrate callers from old to new one at a time, validating behavior at each step. 4. **Remove the old implementation** once all consumers have switched. Optionally remove the abstraction layer if it no longer adds value. **Use when:** The component is consumed internally (shared libraries, data access layers, utility modules) rather than through external-facing endpoints. The key signal: if you can't put a proxy in front of it, use Branch by Abstraction. **CoreStory query:** "Which internal components consume \[ComponentName] directly? If we introduced an abstraction layer, what interface would both old and new implementations need to satisfy?" ### Parallel Run (Shadow Traffic) For high-risk components where behavioral equivalence must be proven in production before cutover — payment processing, financial calculations, regulatory-sensitive logic — Parallel Run provides the strongest verification. 1. **Route copies of production requests** to both the legacy and modernized systems simultaneously. 2. **Compare responses** in real time. Flag discrepancies for analysis. 3. **Run until the discrepancy rate drops below threshold** (typically below 0.01% for critical services, below 0.1% for standard services). 4. **Cut over to the modernized system** and decommission the legacy component. **Use when:** A behavioral difference has catastrophic consequences. The component handles money, regulatory compliance, or safety-critical logic. The organization needs production-grade evidence before stakeholders will approve cutover. **Data synchronization during coexistence:** Combine with **Change Data Capture (CDC)** via Apache Kafka or Debezium to keep legacy and modern data stores in sync. This avoids the dual-write problem and enables real-time data consistency without modifying the legacy system's write path. **CoreStory query:** "Which operations in \[ComponentName] have the highest business impact if they produce incorrect results? These are the candidates for Parallel Run verification." ### HITL Gate > **After Step 4 (Sequencing):** The engineering lead reviews the migration sequence, work package definitions, and dependency map before work packages are pushed to the ticketing system. This is the gate where the migration plan is approved for execution. *** ## Step-by-Step Walkthrough ### Step 1: Input Loading Start by loading context from prior phases so all decomposition decisions are grounded in actual assessment and architecture data. **Confirm the project and locate prior work:** ``` List my CoreStory projects. I need the project for [SystemName]. Then list all conversations — I need the assessment thread and the architecture decision thread. ``` Look for "RESOLVED - \[Assessment] SystemName" and "RESOLVED - \[Architecture] SystemName" from prior phases. **Retrieve architecture decision context:** ``` Retrieve the conversation history from our architecture decision (conversation [conversation_id]). Summarize: 1. Selected strategy per component (from the ADR) 2. Target architecture — service boundaries, communication patterns, data architecture 3. Migration scope — which components are in scope for modernization 4. Key constraints and risks identified ``` **Create the decomposition conversation:** ``` Create a CoreStory conversation titled "[Decomposition] SystemName - Migration Planning". Store the conversation_id for all subsequent queries. ``` ### Step 2: Component Decomposition Break the migration scope into discrete work packages. The goal is to identify the smallest independently-deployable migration units. **Identify migration units:** ``` send_message: "For each component identified in the target architecture for modernization, determine whether it can be migrated independently or must be migrated together with other components. Consider: 1. Which components share database tables or data stores that cannot be split without migrating both sides simultaneously? 2. Which components have synchronous call dependencies that would break if only one side is modernized? 3. Which components share business logic (duplicated or via shared libraries) that must be updated together? Group the components into migration units — the smallest sets that can be independently deployed. A migration unit might be a single component or a cluster of tightly coupled components." ``` **Define work package boundaries:** ``` send_message: "For each migration unit you identified, define the work package boundary: 1. What is included in this work package (components, data stores, integration points)? 2. What is excluded (remains on the legacy side during this migration)? 3. What temporary integration points (anti-corruption layers, adapters, data sync mechanisms) are needed between the migrated and non-migrated sides? 4. What is the expected outcome — what does 'done' look like for this work package?" ``` **Validate decomposition feasibility:** ``` send_message: "For each proposed work package, validate that it can actually be deployed independently: 1. Can the modernized component function correctly while the rest of the system remains on the legacy platform? 2. Can the legacy system function correctly after this component is extracted? 3. What data consistency guarantees are needed during the coexistence period? 4. Is there a clean rollback path if the modernized component fails?" ``` ### Step 3: Dependency Mapping Map the dependencies between work packages to determine what must happen before what. The following example shows the dependency graph for our hypothetical e-commerce system — work packages arranged in waves, with the critical path highlighted in gold: ```mermaid theme={null} %%{init: {'theme': 'base', 'themeVariables': { 'primaryColor': '#1a1a2e', 'primaryTextColor': '#ffffff', 'primaryBorderColor': '#c9a84c', 'lineColor': '#666666', 'fontFamily': 'Inter, system-ui, sans-serif'}}}%% graph TD subgraph wave0["Step 0: Infrastructure"] INFRA["WP-000
API Gateway + CI/CD + Monitoring"] end subgraph wave1["Wave 1"] WP1["WP-001
ReportingService
Replatform"] WP2["WP-002
UserService
Refactor"] end subgraph wave2["Wave 2"] WP3["WP-003
InventoryService
Refactor"] WP4["WP-004
BatchReconciliation
Re-architect"] end subgraph wave3["Wave 3"] WP5["WP-005
PaymentService
Re-architect"] end subgraph wave4["Wave 4"] WP6["WP-006
OrderService
Re-architect"] end INFRA ==>|"hard"| WP1 INFRA ==>|"hard"| WP2 WP1 -.->|"soft"| WP4 WP2 ==>|"hard"| WP5 WP2 -.->|"soft"| WP3 WP3 ==>|"hard"| WP6 WP5 ==>|"hard"| WP6 style INFRA fill:#0f3460,stroke:#c9a84c,stroke-width:2px,color:#ffffff style WP1 fill:#1a1a2e,stroke:#06b6d4,stroke-width:2px,color:#ffffff style WP2 fill:#1a1a2e,stroke:#3b82f6,stroke-width:2px,color:#ffffff style WP3 fill:#1a1a2e,stroke:#3b82f6,stroke-width:2px,color:#ffffff style WP4 fill:#1a1a2e,stroke:#8b5cf6,stroke-width:2px,color:#ffffff style WP5 fill:#1a1a2e,stroke:#8b5cf6,stroke-width:2px,color:#ffffff style WP6 fill:#1a1a2e,stroke:#8b5cf6,stroke-width:2px,color:#ffffff style wave0 fill:#0f3460,stroke:#c9a84c,stroke-width:1px,color:#c9a84c style wave1 fill:#16213e,stroke:#555,stroke-width:1px,color:#aaa style wave2 fill:#16213e,stroke:#555,stroke-width:1px,color:#aaa style wave3 fill:#16213e,stroke:#555,stroke-width:1px,color:#aaa style wave4 fill:#16213e,stroke:#555,stroke-width:1px,color:#aaa ``` > Solid arrows = hard dependencies (must complete before). Dashed arrows = soft dependencies (easier if done first). Border color indicates strategy: cyan = Replatform, blue = Refactor, purple = Re-architect. **Work package dependencies:** ``` send_message: "For each work package, what are the dependencies on other work packages? Identify: 1. Hard dependencies — WP-X cannot start until WP-Y is complete (e.g., WP-Y creates an API that WP-X will consume) 2. Soft dependencies — WP-X is easier if WP-Y is done first, but can proceed independently with additional temporary integration work 3. Shared infrastructure dependencies — both WP-X and WP-Y require the same infrastructure change (e.g., API gateway, event bus, service mesh) Map these as a dependency graph. Identify the critical path — the longest chain of hard dependencies that determines the minimum total migration timeline." ``` **Shared data dependencies:** ``` send_message: "Map the shared data dependencies across work packages: 1. Which work packages share database tables? 2. For each shared table, which work package should 'own' it in the target architecture? 3. What data synchronization is needed during the coexistence period for each shared table? 4. Are there any cross-work-package foreign key relationships that must be maintained during migration?" ``` **Infrastructure prerequisites:** ``` send_message: "What shared infrastructure must be in place before any work packages can execute? Identify: 1. API gateway or service mesh (if the target architecture requires one) 2. Event bus or message broker (if moving from sync to async communication) 3. Service registry and discovery 4. Centralized logging/monitoring for the new services 5. CI/CD pipeline changes for the new deployment model These are 'Step 0' work packages that must be completed before component migration begins." ``` ### Step 4: Sequencing Order the work packages into a migration sequence. This is where engineering judgment matters most — there's no single correct sequence, and the right order depends on the team's risk appetite, business priorities, and capacity. **Dependency-driven sequence:** ``` send_message: "Given the dependency graph, what is the recommended order for executing these work packages? Consider: 1. Dependency chain — what must be done before what 2. Risk sequencing — should high-risk components go early (retire risk) or late (learn from easier migrations first)? 3. Business value — which components deliver the most value when modernized? Can we prioritize early wins? 4. Team capacity — are there work packages that can run in parallel on different teams? 5. Temporary integration cost — which sequence minimizes the total amount of anti-corruption layer and adapter code needed? Provide a recommended sequence with rationale for the ordering. Identify which work packages can run in parallel." ``` **Quick wins identification:** ``` send_message: "Which work packages are 'quick wins' — low coupling, high readiness score, high business value, and few dependencies? These are candidates for the first migration sprint. Proving the methodology works on a quick win builds team confidence and organizational support." ``` **Risk analysis per sequence position:** ``` send_message: "For the recommended sequence, identify the key risk at each step: 1. What could go wrong at this step? 2. What is the blast radius if this work package fails? 3. Is there a clean rollback path? 4. What temporary integration complexity does this step introduce? Flag any steps where the risk is concentrated — these need additional verification or smaller batch sizes." ``` ### Step 5: Work Package Definition Define each work package in detail. This is the deliverable that feeds execution (Phase 5 of the hub) and the ticketing system. **Generate work package definitions:** ``` send_message: "For each work package in the sequence, produce a structured definition: 1. Work Package ID and name 2. Component(s) included 3. Strategy (Refactor / Re-architect / Replatform / etc.) 4. Dependencies (which work packages must complete first) 5. Blocked by (hard blockers) For the Transform phase: - Delta spec scope (what changes from legacy to target) - Target patterns (architectural patterns to follow) - Estimated files to create or modify - Test strategy (unit, integration, behavioral) For the Coexist phase: - Façade/proxy approach (how traffic is routed between old and new) - Data migration/sync strategy (if applicable) - Rollback plan (how to revert if issues arise) - Verification criteria (what must pass before proceeding to Eliminate) For the Eliminate phase: - Legacy components to decommission - Façade/adapter removal (what temporary code gets cleaned up) - Final verification (behavioral equivalence confirmation) Also estimate: - Relative effort (low / medium / high / very high) - Duration estimate (in sprints, if possible) - Team/skill requirements" ``` **Acceptance criteria per work package:** ``` send_message: "For each work package, define the acceptance criteria that must be met before it's considered complete: 1. Functional criteria — what must the modernized component do? 2. Behavioral equivalence — which business rules from the Phase 2 inventory must be verified? 3. Performance criteria — latency, throughput, resource utilization targets 4. Integration criteria — what must work with adjacent components? 5. Operational criteria — monitoring, alerting, deployment pipeline" ``` ### Step 6: Ticketing System Integration If your agent has a Jira or Linear MCP configured alongside CoreStory, push the work packages directly to your project management system. **Create the migration epic (Jira):** ``` Create a Jira epic titled "[Modernization] SystemName - Migration Execution". Set the description to a summary of the migration plan: - Target architecture overview - Number of work packages - Estimated timeline - Link to the CoreStory assessment and architecture decision conversations ``` **Create stories from work packages (Jira):** ``` For each work package, create a Jira story under the migration epic: Title: "[WP-XXX] Transform: [ComponentName]" Description: - Strategy: [Refactor / Re-architect / etc.] - Dependencies: [WP-YYY, WP-ZZZ] - Blocked by: [WP-AAA must complete first] - Delta spec scope: [what changes] - Target patterns: [architectural patterns] - Test strategy: [unit, integration, behavioral] - Acceptance criteria: [from Step 5] Labels: modernization, [strategy], [component-domain] Priority: [based on sequence position] Then create sub-tasks for the Coexist and Eliminate phases: - "[WP-XXX] Coexist: [ComponentName] — façade setup and parallel run" - "[WP-XXX] Eliminate: [ComponentName] — legacy decommission and cleanup" ``` **Link dependencies (Jira):** ``` For each work package dependency, create a Jira issue link: - WP-002 "is blocked by" WP-001 - WP-003 "is blocked by" WP-001 This makes the dependency chain visible in the Jira board and prevents work packages from being started out of order. ``` **Linear alternative:** If using Linear instead of Jira, the structure maps as: epic → project or cycle, story → issue, sub-task → sub-issue. The same work package definitions apply — adapt the field names to Linear's model. #### Linear Integration Linear uses a different hierarchy than Jira. Map the modernization work packages as follows: * **Project** = the modernization initiative * **Cycle** = each migration wave (group of work packages executed together) * **Issue** = one work package (the component being modernized) * **Sub-issue** = the three phases: Transform, Coexist, Eliminate ``` For each work package, create a Linear issue with: - Title: "[WP-XXX] [ComponentName] — [Strategy]" - Description: Paste the work package scope, acceptance criteria, and dependencies - Labels: "modernization", "[strategy]" (e.g., "refactor", "replatform") - Cycle: Assign to the appropriate migration wave - Sub-issues: 1. "Transform: [ComponentName]" — linked to delta spec 2. "Coexist: [ComponentName]" — includes façade/routing setup and verification criteria 3. "Eliminate: [ComponentName]" — includes legacy decommission checklist Set blocking relationships between sub-issues (Transform blocks Coexist blocks Eliminate) and between work packages (per the dependency map from Step 4). ``` **No ticketing MCP available:** If your agent doesn't have a Jira or Linear MCP configured, the work package definitions are still the primary output. Export them as a structured document that can be manually imported or used as the basis for ticket creation. See [Using CoreStory with Jira](/playbooks/using-corestory-with-jira) for Jira MCP setup. **Mark the thread complete:** ``` Rename the conversation to "RESOLVED - [Decomposition] SystemName - Migration Planning". ``` *** ## Output Format: Work Package Each work package follows this template: ```markdown theme={null} ## Work Package: [Component Name] **ID:** WP-001 **Component:** [Name] **Strategy:** [Strangler Fig / Branch by Abstraction / Parallel Run] — [Refactor / Re-architect / Replatform] **Migration Unit:** [Standalone / Cluster with WP-002, WP-003] **Dependencies:** [WP-004, WP-005] **Blocked by:** [WP-003 must complete first] **Sequence Position:** [1st / 2nd / parallel with WP-002] **Estimated Effort:** [Low / Medium / High / Very High] **Estimated Duration:** [X sprints] ### Transform - **Delta spec scope:** [what changes from legacy to target] - **Target patterns:** [architectural patterns to follow] - **Estimated files to create/modify:** [count] - **Test strategy:** [unit, integration, behavioral] - **Spec-Driven Development reference:** Use the delta spec approach from [Spec-Driven Development](/playbooks/spec-driven-development) ### Coexist - **Façade/proxy approach:** [how traffic is routed between old and new] - **Data migration strategy:** [if applicable — sync mechanism, CDC, dual-write] - **Rollback plan:** [how to revert if issues arise] - **Verification criteria:** [what must pass before proceeding to Eliminate] - **Behavioral Verification reference:** Use the verification approach from [Behavioral Verification](/playbooks/modernization/behavioral-verification) ### Eliminate - **Legacy components to decommission:** [list] - **Façade removal:** [what temporary integration code gets cleaned up] - **Final verification:** [behavioral equivalence confirmation] - **Sign-off required:** [domain expert + tech lead] ### Acceptance Criteria - [ ] All business rules from Phase 2 inventory verified for this component - [ ] Performance meets or exceeds legacy baseline - [ ] Integration with adjacent components confirmed - [ ] Monitoring and alerting operational - [ ] Rollback tested and documented ``` *** ## Prompting Patterns Reference ### Decomposition Patterns | Pattern | Example | | --------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | | **Migration unit identification** | "Which components share data stores that cannot be split without migrating both sides simultaneously?" | | **Boundary validation** | "Can \[component] function correctly as a standalone service while the rest remains on legacy?" | | **Temporary integration scoping** | "If we extract \[component] first, what anti-corruption layers and adapters are needed for the remaining legacy components?" | | **Minimal cluster** | "What is the minimal set of components that must be modernized together? Can any be split further?" | ### Sequencing Patterns | Pattern | Example | | --------------------------------- | ------------------------------------------------------------------------------------------------------------- | | **Critical path** | "What is the longest chain of hard dependencies? This determines the minimum migration timeline." | | **Quick win identification** | "Which work packages have low coupling, high readiness, and few dependencies? These go first." | | **Parallel opportunity** | "Which work packages have no mutual dependencies and could run in parallel on different teams?" | | **Risk concentration** | "Where in the sequence is the highest risk concentrated? Should we retire that risk early or late?" | | **Integration cost minimization** | "Which sequence minimizes the total amount of temporary integration code (adapters, anti-corruption layers)?" | *** ## Best Practices **Sequence by dependency chain, not by perceived difficulty.** Teams often want to start with the "easiest" component. But if that component depends on a shared database that three other components also use, you'll immediately hit data decomposition challenges. Let the dependency graph drive the sequence, then optimize within the constraints it sets. **Start with a quick win.** Within the dependency constraints, front-load a work package that's low-risk, low-coupling, and high-visibility. Proving the methodology works on a real component builds team confidence and organizational support for the rest of the migration. This is especially important for teams that haven't done incremental modernization before. **Don't underestimate temporary integration work.** Every work package's Coexist phase requires integration between the modernized component and the legacy system. Anti-corruption layers, API adapters, data synchronization mechanisms — this is real engineering work that must be scoped and scheduled. The best sequences minimize the total temporary integration burden. **Identify infrastructure prerequisites early.** If the target architecture requires an API gateway, event bus, or service mesh, that infrastructure must be in place before component migration begins. Treat infrastructure as "Step 0" work packages with their own timelines and dependencies. **Define "done" for each work package before starting.** The acceptance criteria — functional, behavioral, performance, integration, operational — should be agreed before the Transform phase begins. This prevents scope creep and provides clear exit criteria for the Eliminate phase. **Plan for parallel execution where possible.** If two work packages have no mutual dependencies, they can run in parallel on different teams. This is the primary way to compress the migration timeline. The dependency mapping in Step 3 reveals these opportunities. **Use the Coexist phase as a safety net.** The Coexist phase (running old and new simultaneously behind a façade) is what makes incremental modernization safe. Don't rush through it. Use it to validate behavioral equivalence, measure performance, and build confidence before cutting over. The façade enables instant rollback if anything goes wrong. *** ## 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: | Harness | Install location | | --------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Claude Code** | `.claude/skills//SKILL.md` — Claude loads the body when the YAML `description` matches the task | | **GitHub Copilot** | Append to `.github/copilot-instructions.md` for repo-wide instructions, or save as `.github/instructions/.instructions.md` with an `applyTo` glob for path-scoped use | | **Cursor** | `.cursor/rules/.mdc` with a `description` field for auto-attach (use `globs` for path-scoped or `alwaysApply: true` for every session) | | **Factory.ai** | `.factory/droids/.md` (project) or `~/.factory/droids/.md` (personal); Factory loads it as a custom Droid | | **Aider** | `CONVENTIONS.md` at repo root, loaded with `aider --read CONVENTIONS.md` — or add it to the `read:` list in `.aider.conf.yml` for automatic loading | | **Codex / `AGENTS.md` harnesses** | Append the content to `AGENTS.md` at your repository root | | **Custom runtime** | Load the markdown into your agent's system prompt, rules file, or wherever it consumes workflow context | Want a single install that works across the most harnesses? Append the content to `AGENTS.md` at your repository root. The [`AGENTS.md` spec](https://agents.md/) 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 accordions below walk through end-to-end setup (skill file, slash command, version control) for the four most common harnesses. If you're on a different harness, copy the SKILL.md content from any accordion and install it per the conventions above. #### Setup 1. **Configure the CoreStory MCP server** in your Claude Code settings (see [CoreStory MCP Server Setup Guide](/getting-started/mcp-server-setup)). 2. **(Optional) Configure Jira MCP** for ticketing integration (see [Using CoreStory with Jira](/playbooks/using-corestory-with-jira)). 3. **Add the skill file:** ```bash theme={null} mkdir -p .claude/skills/decomposition-sequencing ``` Create `.claude/skills/decomposition-sequencing/SKILL.md` with the content from the skill file below. 4. **Commit to version control:** ```bash theme={null} git add .claude/skills/ git commit -m "Add CoreStory decomposition and sequencing skill" ``` #### Usage ``` Break the modernization plan into work packages Sequence the migration for [SystemName] Create migration work packages and push to Jira ``` #### Tips * This skill focuses on Phase 4 of the broader modernization workflow. It expects Phase 3 (Target Architecture) to be complete. * If Jira/Linear MCP is available, the skill can push work packages directly. If not, it produces structured definitions for manual import. * Keep the SKILL.md under 500 lines for reliable loading. #### Skill File Save as `.claude/skills/decomposition-sequencing/SKILL.md`: ```markdown theme={null} --- name: CoreStory Decomposition & Sequencing description: Breaks a modernization plan into sequenced, executable work packages using CoreStory's dependency analysis. Activates on decomposition, sequencing, migration planning, or work package requests. --- # CoreStory Decomposition & Sequencing When this skill activates, guide the user through the six-step workflow to produce sequenced work packages for modernization execution. ## Activation Triggers Activate when user requests: - Migration decomposition or work package creation - Migration sequencing or ordering - Sprint planning for modernization - Pushing modernization work to Jira or Linear - Any request containing "decompose", "sequence", "work packages", "migration plan", "migration order" ## Prerequisites - Completed Target Architecture decision (Phase 3) with ADR - CoreStory MCP server configured with completed ingestion - (Optional) Jira or Linear MCP for ticketing integration **If you do not detect that you have access to CoreStory (e.g., `list_projects` fails or is unavailable), ask the user to verify that their MCP or API connection is properly configured and that this repository has been ingested. If the user has not yet created a CoreStory account, direct them to create one and upload their repo at [app.corestory.ai](https://app.corestory.ai).** ## Step 1: Input Loading 1. Identify target project (`list_projects`) 2. Locate prior conversations (`list_conversations`) — assessment + architecture 3. Retrieve ADR and dependency analysis (`get_conversation`) 4. Create conversation: "[Decomposition] SystemName - Migration Planning" ## Step 2: Component Decomposition - Identify migration units (smallest independently-deployable sets) - Map shared data stores that force components to migrate together - Define work package boundaries (included, excluded, temporary integration) - Validate each can be deployed independently ## Step 3: Dependency Mapping - Map hard dependencies (must complete before), soft dependencies (easier if done first) - Map shared data dependencies and ownership - Identify infrastructure prerequisites (API gateway, event bus, CI/CD) - Identify the critical path ## Step 4: Sequencing - Order by dependency chain, risk, business value, team capacity - Identify quick wins for the first sprint - Identify parallel execution opportunities - Analyze risk concentration per sequence position ## Step 5: Work Package Definition For each work package, define: - Transform: delta spec scope, target patterns, files, test strategy - Coexist: façade approach, data sync, rollback plan, verification criteria - Eliminate: legacy decommission, façade removal, final verification - Acceptance criteria: functional, behavioral, performance, integration, operational ## Step 6: Ticketing System Integration If Jira/Linear MCP available: - Create migration epic - Create stories per work package with Transform/Coexist/Eliminate sub-tasks - Link dependencies between work packages **HITL Gate: Engineering lead approves sequence before pushing to ticketing system.** ## Error Handling - **ADR not found:** Direct user to complete Target Architecture first - **Components can't be separated:** Define as a cluster migration unit - **Too many dependencies:** Look for infrastructure prerequisites that unblock multiple packages - **Jira/Linear MCP not available:** Output structured work package definitions for manual import ``` Add the following to `.github/copilot-instructions.md`: ```markdown theme={null} ## Decomposition & Sequencing When asked to break a modernization plan into work packages or sequence a migration: 1. ALWAYS load the Target Architecture decision and dependency analysis from prior phases 2. Identify migration units — the smallest independently-deployable component sets 3. Map dependencies: hard (must-complete-before), soft (easier-if-done-first), infrastructure 4. Sequence by dependency chain first, then optimize for risk, business value, and team capacity 5. Structure each work package as Transform → Coexist → Eliminate with acceptance criteria 6. If Jira/Linear MCP is available, push as epic + stories with dependency links 7. Engineering lead must approve the sequence before execution begins ``` **(Optional) Add a reusable prompt file.** Create `.github/prompts/decomposition-sequencing.prompt.md`: ```markdown theme={null} --- mode: agent description: Break a modernization plan into sequenced work packages using CoreStory's dependency analysis --- Decompose the modernization plan for the specified system into executable work packages. 1. Load the Target Architecture decision and dependency analysis from prior phases 2. Break the migration into the smallest independently-deployable migration units 3. Map dependencies between work packages and identify the critical path 4. Sequence by dependency, risk, business value, and parallel execution opportunity 5. Define each work package with Transform/Coexist/Eliminate structure and acceptance criteria 6. Push to Jira/Linear if MCP is available, or output structured definitions ``` Create `.cursor/rules/decomposition-sequencing/RULE.md`: ```markdown theme={null} --- description: CoreStory-powered decomposition and sequencing for modernization execution planning. Activates for migration decomposition, work package creation, sequencing, or sprint planning. alwaysApply: false --- # CoreStory Decomposition & Sequencing You are a modernization planner with access to CoreStory's code intelligence via MCP. Break the modernization plan into sequenced, executable work packages. ## Activation Triggers Apply when user requests: migration decomposition, work package creation, migration sequencing, sprint planning for modernization, or Jira/Linear ticket creation for migration work. **If you do not detect that you have access to CoreStory (e.g., `list_projects` fails or is unavailable), ask the user to verify that their MCP or API connection is properly configured and that this repository has been ingested. If the user has not yet created a CoreStory account, direct them to create one and upload their repo at [app.corestory.ai](https://app.corestory.ai).** ## Six-Step Workflow ### Step 1: Input Loading - Load ADR and dependency analysis from prior phases - Create decomposition conversation ### Step 2: Component Decomposition - Identify migration units (smallest independently-deployable sets) - Validate independent deployability for each unit - Define boundaries: what's included, excluded, temporary integration needed ### Step 3: Dependency Mapping - Hard and soft dependencies between work packages - Shared data dependencies and ownership - Infrastructure prerequisites (API gateway, event bus, CI/CD) - Critical path identification ### Step 4: Sequencing - Order by dependency → risk → business value → team capacity - Identify quick wins and parallel opportunities - Minimize total temporary integration cost - **HITL Gate: Engineering lead approves sequence** ### Step 5: Work Package Definition - Transform: delta spec, target patterns, test strategy - Coexist: façade, data sync, rollback, verification criteria - Eliminate: decommission, cleanup, final verification - Acceptance criteria for each package ### Step 6: Ticketing Integration - Epic + stories + dependency links (if Jira/Linear MCP available) - Structured definitions for manual import (if no MCP) ## Key Principles - Sequence by dependency chain, not perceived difficulty - Start with a quick win to build confidence - Don't underestimate temporary integration work - Define "done" before starting each work package - The Coexist phase is your safety net — don't rush it ``` Create `.factory/droids/decomposition-sequencing.md`: ```markdown theme={null} --- name: CoreStory Decomposition & Sequencing description: Breaks a modernization plan into sequenced work packages using CoreStory dependency analysis model: inherit tools: - CoreStory:list_projects - CoreStory:get_project_techspec - CoreStory:get_project_prd - CoreStory:create_conversation - CoreStory:send_message - CoreStory:rename_conversation - CoreStory:list_conversations - CoreStory:get_conversation --- # CoreStory Decomposition & Sequencing Execute the six-step workflow to produce sequenced work packages for modernization. ## Activation Triggers - "Decompose the migration plan" or "create work packages" - "Sequence the modernization" or "migration order" - "Push migration to Jira/Linear" - Any decomposition, sequencing, or migration planning request ## CoreStory MCP Tools - `CoreStory:list_projects` — identify the target project - `CoreStory:get_project_techspec` — retrieve Tech Spec for component vocabulary - `CoreStory:create_conversation` — open decomposition thread - `CoreStory:send_message` — query CoreStory for dependency analysis - `CoreStory:list_conversations` / `CoreStory:get_conversation` — load prior phase findings - `CoreStory:rename_conversation` — mark completed thread "RESOLVED" **If you do not detect that you have access to CoreStory (e.g., `list_projects` fails or is unavailable), ask the user to verify that their MCP or API connection is properly configured and that this repository has been ingested. If the user has not yet created a CoreStory account, direct them to create one and upload their repo at [app.corestory.ai](https://app.corestory.ai).** ## Workflow Step 1: Input Loading → Load ADR and dependency analysis, create conversation Step 2: Component Decomposition → Migration units, boundaries, feasibility Step 3: Dependency Mapping → Hard/soft deps, shared data, infrastructure, critical path Step 4: Sequencing → Order by dependency/risk/value → HITL sequence approval Step 5: Work Package Definition → Transform/Coexist/Eliminate per package Step 6: Ticketing → Epic + stories + dependency links (if Jira/Linear MCP available) ## Key Principles - Sequence by dependency chain, not perceived difficulty - Start with a quick win to build confidence - Don't underestimate temporary integration work - Each work package follows Transform → Coexist → Eliminate - Define acceptance criteria before starting each package ``` *** ## Troubleshooting **Everything seems tightly coupled — no clean decomposition points.** This is common in monoliths. Look for the components with the lowest fan-in and fan-out — those are your best extraction candidates. If everything truly shares everything, consider a "modular monolith" intermediate step: introduce internal module boundaries within the monolith before extracting services. Ask CoreStory: "Which modules access the fewest shared database tables?" **Work packages are too large (multi-month scope).** Ask CoreStory more targeted decomposition questions: "What is the smallest independently-deployable subset of \[component]?" and "If we extract just \[specific feature], what temporary integration points are needed?" The goal is work packages that can be completed in 1–3 sprints. If a component truly can't be decomposed further, it may need a dedicated team. **The dependency graph has circular dependencies between work packages.** Circular dependencies usually indicate that the decomposition boundaries are wrong. Ask CoreStory: "Components A and B appear to depend on each other — what specific integration points create this cycle? Can any of them be broken with an anti-corruption layer or event-driven decoupling?" If the cycle can't be broken, the two work packages should be merged into a single migration unit. **Sequencing produces analysis paralysis — too many valid orderings.** Start with hard constraints (dependency chain), then optimize for one primary factor: either risk (tackle the riskiest component early to retire risk), or business value (deliver the highest-value modernization first), or team learning (start with the component the team understands best). Don't try to optimize for everything simultaneously. **Jira/Linear MCP is not configured.** The work package definitions are the primary output regardless of whether a ticketing MCP is available. Export the definitions as a structured document and import manually. See [Using CoreStory with Jira](/playbooks/using-corestory-with-jira) for Jira MCP setup instructions. **Agent can't access CoreStory tools.** See the [Supercharging AI Agents](/getting-started/supercharging-ai-agents) troubleshooting section for MCP connection issues. Verify the project has completed ingestion by calling `list_projects` and checking the status. *** ## What's Next **Start executing:** With sequenced work packages in hand, begin Phase 5. Use [Spec-Driven Development →](/playbooks/spec-driven-development) for delta specs per component, and the relevant architecture variant for pattern-specific guidance: [Monolith to Microservices →](/playbooks/modernization/monolith-to-microservices). **Verify as you go:** Each component's Coexist phase requires behavioral verification. Use [Behavioral Verification →](/playbooks/modernization/behavioral-verification) to prove the modernized component preserves business rules. **Return to the hub:** [Code Modernization →](/playbooks/code-modernization) — the full six-phase framework. **For Jira integration:** [Using CoreStory with Jira →](/playbooks/using-corestory-with-jira) — MCP setup and workflow patterns. **For agent setup:** [Supercharging AI Agents with CoreStory →](/getting-started/supercharging-ai-agents) — MCP server configuration and agent setup. # Monolith to Microservices Source: https://docs.corestory.ai/playbooks/modernization/monolith-to-microservices Architecture-specific guidance for decomposing a monolithic application into microservices using CoreStory's persistent code intelligence and the Strangler Fig execution pattern. ## Overview Monolith-to-microservices is the most common enterprise modernization pattern — and the one with the highest failure rate. Teams that attempt it without deep architectural understanding of the monolith tend to fail in predictable ways: they draw service boundaries in the wrong places, they underestimate shared data dependencies, and they end up with a "distributed monolith" that's worse than what they started with. This variant playbook provides pattern-specific guidance for Phase 5 (Iterative Execution) of the [Code Modernization](/playbooks/code-modernization) workflow. It covers the unique challenges of monolith decomposition: finding natural service boundaries, introducing the Strangler Fig façade, decomposing shared databases, choosing communication patterns, and executing the Transform → Coexist → Eliminate cycle for each extracted service. CoreStory's role is critical here because the monolith's internal structure — the coupling patterns, data access hotspots, and hidden dependencies — is precisely what determines where services can and cannot be separated. CoreStory operates as an **Expert** for understanding what the monolith actually does (as opposed to what the architecture diagram says it does), and as a **Navigator** for guiding each service extraction step by step. This playbook executes the work packages defined in [Decomposition & Sequencing](/playbooks/modernization/decomposition-sequencing). If you haven't yet broken the modernization plan into sequenced work packages, start there. This playbook picks up at the point where you have a specific component to extract and need pattern-specific guidance for the monolith-to-microservices migration. **Who this is for:** Engineers and architects executing a monolith-to-microservices migration. This playbook assumes you've already completed the assessment (Phase 1), business rules inventory (Phase 2), target architecture decision (Phase 3), and decomposition/sequencing (Phase 4). If you haven't, start with the [Code Modernization hub](/playbooks/code-modernization). **What you'll get:** A concrete methodology for extracting services from a monolith — from identifying service boundaries through database decomposition to the façade-based execution pattern that makes incremental extraction safe. *** ## When to Use This Playbook * Your Phase 3 decision selected Re-architect or Refactor with a microservices target architecture * You're executing work packages from Phase 4 that involve extracting services from a monolith * You need to identify service boundaries within a monolith that has unclear or undocumented module boundaries * You need to decompose a shared database as part of service extraction * You're introducing an API gateway or façade layer for the Strangler Fig pattern ## When to Skip This Playbook * The target architecture is not microservices — if you're modernizing within a monolith (refactoring without extraction), use [Spec-Driven Development](/playbooks/spec-driven-development) directly * The system is already service-oriented and you're re-platforming (e.g., moving from on-prem to cloud without architectural changes) * You haven't completed Phases 1–4 — go back to the [Code Modernization hub](/playbooks/code-modernization) * The monolith is small enough that extraction doesn't make sense — not every monolith needs to become microservices *** ## Prerequisites * A **completed Target Architecture decision** (Phase 3) specifying microservices as the target * A **completed Decomposition & Sequencing plan** (Phase 4) with ordered work packages * A **completed Business Rules Inventory** (Phase 2) for behavioral verification during extraction * A **CoreStory account** with the monolith codebase ingested and ingestion complete * An **AI coding agent** with CoreStory MCP configured (see [Supercharging AI Agents](/getting-started/supercharging-ai-agents) for setup) * (Recommended) **Access to the monolith's database schema** — either via CoreStory ingestion or direct access * (Recommended) **Infrastructure for running extracted services** — container orchestration, API gateway, service mesh, or at minimum a reverse proxy for the façade layer * (Recommended) **Observability tooling** — distributed tracing and centralized logging are essential for debugging issues during the Coexist phase *** ## How It Works ### CoreStory MCP Tools Used | Tool | Step(s) | Purpose | | ---------------------- | ------------- | ---------------------------------------------------------------------------------- | | `list_projects` | 1 | Confirm the target project | | `create_conversation` | 1 | Start a dedicated extraction thread per service | | `send_message` | 2, 3, 4, 5, 6 | Query CoreStory for boundary analysis, dependency mapping, and extraction guidance | | `list_conversations` | 1 | Find prior phase conversations | | `get_conversation` | 1 | Retrieve prior findings for cross-reference | | `get_project_techspec` | 1, 2 | Retrieve Tech Spec for understanding monolith structure | | `get_project_prd` | 2 | Retrieve PRD for business domain context | | `rename_conversation` | 6 | Mark completed thread with "RESOLVED" prefix | ### The Monolith-to-Microservices Workflow > **Note:** The steps below are internal to this playbook. They are sub-steps of Phase 5 in the [six-phase modernization framework](/playbooks/code-modernization), not a separate numbering system. This playbook follows a six-step pattern for each service extraction: 1. **Context Loading** — Load the work package definition, prior phase findings, and establish the extraction scope. 2. **Service Boundary Identification** — Use CoreStory to validate and refine the service boundary defined in Phase 4. Identify exactly what code, data, and logic belongs to the new service. 3. **Database Decomposition Planning** — Map shared data dependencies and plan the data separation strategy for this service extraction. 4. **Façade & Communication Design** — Design the Strangler Fig façade layer and the communication patterns between the extracted service and the remaining monolith. 5. **Service Extraction Execution** — Execute the Transform → Coexist → Eliminate cycle using Spec-Driven Development for the delta spec. 6. **Verification & Cutover** — Verify behavioral equivalence and execute the cutover from monolith to extracted service. ### The Strangler Fig Pattern for Service Extraction The Strangler Fig pattern is the execution model for monolith-to-microservices migration. Named after the strangler fig plant that grows around a host tree until it can support itself, the pattern incrementally replaces monolith functionality with extracted services: 1. **Introduce the façade.** Place an API gateway, reverse proxy, or routing layer in front of the monolith. Initially, it routes all traffic to the monolith unchanged. 2. **Extract one service.** Build the new microservice alongside the monolith. The façade routes requests for that service's domain to the new service instead of the monolith. 3. **Coexist.** Both the monolith (handling everything else) and the extracted service (handling its domain) run simultaneously. The façade manages the routing. 4. **Verify and eliminate.** Once the extracted service is verified, remove the corresponding code from the monolith. The façade continues routing. 5. **Repeat.** Extract the next service. The monolith shrinks with each extraction until only the façade remains (or the façade becomes the API gateway for the service mesh). The key safety property: at every step, the system is functional. If the extracted service fails, the façade can route traffic back to the monolith. There is no big-bang cutover. Strangler Fig Progression — four panels showing a monolith shrinking as services are extracted incrementally through a façade layer ### HITL Gate > **Before each service extraction:** The engineering lead reviews the service boundary, data decomposition plan, and façade design before extraction begins. This is especially important for the first extraction — it establishes the pattern that subsequent extractions will follow. *** ## Step-by-Step Walkthrough ### Step 1: Context Loading Start by loading the work package definition and all relevant context from prior phases. **Load the work package:** ``` List my CoreStory projects. I need the project for [SystemName]. Then list all conversations — I need the decomposition thread and the architecture decision thread. ``` **Retrieve the specific work package details:** ``` Retrieve the conversation history from our decomposition planning (conversation [conversation_id]). I need the details for work package [WP-XXX]: 1. Components included in this extraction 2. Dependencies on other work packages 3. Hard blockers (what must complete first) 4. The Transform/Coexist/Eliminate plan 5. Acceptance criteria ``` **Create the extraction conversation:** ``` Create a CoreStory conversation titled "[Extraction] SystemName - ServiceName (WP-XXX)". Store the conversation_id for all subsequent queries. ``` ### Step 2: Service Boundary Identification Phase 4 defined the work package boundary at a high level. Now refine it to the specific code, data, and logic that will move to the new service. **Map the domain boundary:** ``` send_message: "For the [ComponentName] extraction (WP-XXX), identify the precise domain boundary within the monolith: 1. Which modules, packages, or namespaces contain the logic for this domain? 2. Which classes/functions are entirely within this domain? 3. Which classes/functions are shared with other domains (used by this component AND other components)? 4. Which database tables are owned by this domain (only accessed by this component)? 5. Which database tables are shared (accessed by this component AND other components)? Distinguish between: - MOVE: code that belongs entirely to the new service - SHARE: code currently shared that needs to be duplicated or extracted into a shared library - LEAVE: code that stays in the monolith" ``` **Identify hidden coupling:** ``` send_message: "What hidden coupling exists between [ComponentName] and the rest of the monolith? 1. Direct function/method calls from other modules INTO this component — who depends on us? 2. Direct function/method calls FROM this component into other modules — who do we depend on? 3. Shared in-memory state (singletons, caches, thread-local storage) 4. Shared configuration values that this component reads 5. Implicit coupling through database triggers, stored procedures, or materialized views 6. Event/callback registrations where this component listens to events from other components or vice versa For each coupling point, classify: - Can be replaced with an API call (synchronous) - Can be replaced with an event/message (asynchronous) - Must be resolved before extraction (hard coupling)" ``` **Validate the boundary:** ``` send_message: "Given the domain boundary and coupling analysis, is this service extraction feasible as defined? 1. Can the extracted service function independently (with API calls replacing direct coupling)? 2. Can the monolith function correctly after this code is removed (with API calls to the new service replacing internal calls)? 3. Are there any circular dependencies between this component and the monolith that would prevent clean extraction? 4. Is the boundary a clean domain boundary (aligned with a bounded context) or does it cut across domain logic? If the boundary needs adjustment, what's the recommended change?" ``` ### Step 3: Database Decomposition Planning Shared databases are the hardest part of monolith-to-microservices. This phase plans how to separate data ownership for the service being extracted. **Map data dependencies:** ``` send_message: "Map all database interactions for [ComponentName]: 1. Tables OWNED by this component (only this component writes to them) 2. Tables READ by this component but OWNED by others (read-only access) 3. Tables WRITTEN by this component AND other components (shared writes) 4. Foreign key relationships between owned tables and other tables 5. Stored procedures, views, or triggers that cross the component boundary 6. Any direct SQL queries that join across component boundaries For tables with shared writes (#3), this is the critical challenge. Identify which component should own each shared table in the target architecture." ``` **Choose a data decomposition strategy:** The right strategy depends on the coupling pattern. Use the following decision tree as a starting heuristic — the right strategy depends on your specific constraints: ```mermaid theme={null} %%{init: {'theme': 'base', 'themeVariables': { 'primaryColor': '#1a1a2e', 'primaryTextColor': '#ffffff', 'primaryBorderColor': '#c9a84c', 'lineColor': '#c9a84c', 'fontFamily': 'Inter, system-ui, sans-serif'}}}%% graph TD START["Shared table identified"] Q1{"Who writes
to this table?"} Q2{"How often is this data
read by other services?"} Q3{"Can reads tolerate
eventual consistency?"} Q4{"Can write ownership
be assigned to one service?"} T1["✅ API-Mediated Access
Owner exposes read API;
consumers call on demand
"] T2["✅ CDC / Event-Driven Sync
Owner publishes changes;
consumers maintain local copies
"] T3["⚠️ Shared Schema Ownership
Transitional — co-locate until
reads can tolerate latency
"] T4["🔄 Refactor to Single Writer
Assign ownership, then
re-evaluate from the top
"] T5["⚠️ Shared Schema — Keep Co-located
True shared state; decompose
at a higher abstraction level
"] START --> Q1 Q1 -->|"Single writer"| Q2 Q1 -->|"Multiple writers"| Q4 Q2 -->|"Rarely"| T1 Q2 -->|"Frequently"| Q3 Q3 -->|"Yes"| T2 Q3 -->|"No"| T3 Q4 -->|"Yes"| T4 Q4 -->|"No"| T5 style START fill:#1a1a2e,stroke:#c9a84c,stroke-width:2px,color:#ffffff style Q1 fill:#c9a84c,stroke:#1a1a2e,stroke-width:2px,color:#1a1a2e style Q2 fill:#c9a84c,stroke:#1a1a2e,stroke-width:2px,color:#1a1a2e style Q3 fill:#c9a84c,stroke:#1a1a2e,stroke-width:2px,color:#1a1a2e style Q4 fill:#c9a84c,stroke:#1a1a2e,stroke-width:2px,color:#1a1a2e style T1 fill:#14532d,stroke:#22c55e,stroke-width:2px,color:#86efac style T2 fill:#0c4a6e,stroke:#3b82f6,stroke-width:2px,color:#93c5fd style T3 fill:#78350f,stroke:#f59e0b,stroke-width:2px,color:#fcd34d style T4 fill:#0f3460,stroke:#06b6d4,stroke-width:2px,color:#67e8f9 style T5 fill:#78350f,stroke:#f59e0b,stroke-width:2px,color:#fcd34d ``` ``` send_message: "For each shared data dependency, recommend a decomposition strategy: Option A: Database-per-service (full separation) - Each service gets its own database/schema - Data that was joined becomes API calls - Best for: cleanly separable data with clear ownership Option B: Shared database with schema ownership - One database, but each service owns specific schemas/tables - Access control enforces ownership boundaries - Best for: transitional state during migration, complex joins Option C: Event-driven synchronization - Services maintain their own copies of shared data - Changes propagate via events (CDC, outbox pattern, domain events) - Best for: read-heavy shared data where eventual consistency is acceptable Option D: API-mediated access - The owning service exposes the data via API - Consuming services call the API instead of querying directly - Best for: shared data with clear ownership and low-frequency access For each shared table, which strategy applies? Consider: - Query frequency (how often is this data accessed?) - Consistency requirements (must reads see latest writes?) - Join complexity (is this data joined with other service's data?) - Volume (how much data, how fast does it change?)" ``` **Plan the data migration:** ``` send_message: "For the selected data decomposition strategy, plan the migration: 1. What data needs to move? (tables, rows, schemas) 2. Migration sequence — can data be migrated incrementally or must it be a bulk migration? 3. During the Coexist phase, how is data kept in sync between the monolith's database and the new service's database? 4. What happens to foreign keys that cross the service boundary? 5. What's the rollback plan if the data migration fails? 6. Are there any data consistency windows where the system is in an inconsistent state? How long, and is it acceptable?" ``` ### Step 4: Façade & Communication Design Design the routing layer that enables the Strangler Fig pattern and the communication patterns between the extracted service and the monolith. **Design the façade layer:** ``` send_message: "Identify all entry points into [ComponentName] within the monolith: 1. HTTP endpoints (routes, controllers) — what URLs currently route to this component's logic? 2. Internal method calls from other modules — what functions does the monolith call into this component? 3. Background jobs or scheduled tasks — what jobs execute this component's logic? 4. Event handlers — what events trigger this component? 5. CLI commands or admin interfaces For each entry point: - Can it be routed through the façade (API gateway/reverse proxy)? - Does it need an adapter (e.g., converting an internal method call to an HTTP/gRPC call)? - Does it need to remain in the monolith temporarily with a thin wrapper that calls the new service?" ``` **Choose communication patterns:** ``` send_message: "For each interaction between the extracted service and the remaining monolith, recommend a communication pattern: Synchronous (REST/gRPC): - Best for: request-response patterns, queries, operations that need immediate confirmation - Risk: introduces latency, creates runtime coupling Asynchronous (events/messaging): - Best for: notifications, data propagation, operations that don't need immediate response - Risk: introduces eventual consistency, harder to debug For each interaction: 1. What is the current pattern in the monolith? (direct call, shared memory, database polling, etc.) 2. What should the modernized pattern be? 3. What is the latency tolerance? 4. What happens if the call fails? (retry, fallback, circuit breaker) 5. Is idempotency needed? (can the same message be processed twice safely?)" ``` **Design the anti-corruption layer:** ``` send_message: "The anti-corruption layer translates between the monolith's internal model and the new service's model. 1. Where do the models diverge? (different field names, different data types, different enumerations, different units) 2. Where does the new service intentionally improve on the monolith's model? (better naming, cleaner types, explicit nullability) 3. What translation is needed at each integration point? 4. Should the anti-corruption layer live in the new service, in the monolith, or in the façade? The anti-corruption layer is temporary — it will be removed when all consumers have migrated to the new service's model. Design it to be easy to remove." ``` ### Step 5: Service Extraction Execution Execute the Transform → Coexist → Eliminate cycle for this service. This is where the actual extraction happens. **Transform: Build the new service** Use [Spec-Driven Development](/playbooks/spec-driven-development) to create the delta spec for the new service: ``` send_message: "Generate a delta spec for extracting [ComponentName] as a standalone service: 1. What the service does (business rules from Phase 2 inventory) 2. API contract (endpoints, request/response formats, authentication) 3. Data model (owned tables, with any schema improvements) 4. Integration points (how it communicates with other services and the remaining monolith) 5. Non-functional requirements (latency, throughput, availability) The delta spec should capture what CHANGES from the monolith to the extracted service — not a full system description. Focus on the boundary: new APIs that replace internal calls, data that moves, behavior that's preserved." ``` Build the service following the delta spec. The monolith remains untouched during Transform. Key implementation steps: ``` send_message: "For the [ComponentName] service implementation, guide the extraction: 1. Which files from the monolith contain the logic to extract? 2. What modifications are needed to make this logic standalone? (remove internal dependencies, add API layer, add configuration) 3. What new infrastructure code is needed? (service bootstrap, health checks, configuration loading, database connection) 4. What test infrastructure is needed? (service-level tests, contract tests with the monolith facade) 5. What deployment configuration is needed? (Dockerfile, Kubernetes manifests, CI/CD pipeline)" ``` **Coexist: Run both versions simultaneously** Configure the façade to route traffic: ``` send_message: "Design the Coexist phase configuration: 1. Façade routing rules — which requests go to the new service, which stay in the monolith? 2. Can we start with a percentage-based rollout (e.g., 10% to new service, 90% to monolith)? 3. How do we compare responses between old and new? (shadow traffic, dual-write with comparison, manual sampling) 4. What monitoring is needed to detect behavioral differences? (error rates, latency percentiles, business metrics) 5. What's the circuit breaker configuration? (when does the façade automatically fall back to the monolith?) 6. How long should the Coexist phase last before proceeding to Eliminate?" ``` Run [Behavioral Verification](/playbooks/modernization/behavioral-verification) — the systematic process of proving the extracted service preserves every business rule from the legacy implementation — during the Coexist phase: ``` Verify behavioral equivalence for [ComponentName] using the Business Rules Inventory from Phase 2. Compare the extracted service against the monolith's implementation. ``` **Eliminate: Retire the legacy code** Once behavioral verification passes and the Coexist phase is stable: ``` send_message: "Plan the Eliminate phase for [ComponentName]: 1. Which code in the monolith should be removed? (controllers, services, repositories, models, configuration) 2. Which database tables/schemas should be dropped or transferred to the new service's database? 3. What façade routing rules should be updated? (remove the monolith path, keep only the service path) 4. What anti-corruption layer code should be removed? 5. Are there any other monolith components that referenced the removed code? How are those references updated? 6. What integration tests need to be updated to point to the service instead of the monolith?" ``` ### Step 6: Verification & Cutover Final verification before the extraction is considered complete. **Post-elimination verification:** ``` send_message: "After removing [ComponentName] from the monolith: 1. Does the monolith still build and pass all remaining tests? 2. Does the extracted service continue to function correctly without the monolith code? 3. Are all integration points working? (test each consumer of the extracted service) 4. Is monitoring showing healthy metrics? (error rates, latency, throughput) 5. Is the data migration complete and consistent? 6. Can the system handle the full production load on the extracted service?" ``` **Mark the thread complete:** ``` Rename the conversation to "RESOLVED - [Extraction] SystemName - ServiceName (WP-XXX)". ``` *** ## Key Patterns & Strategies ### Service Boundary Identification Patterns **Bounded Context alignment.** The strongest service boundaries align with Domain-Driven Design bounded contexts — areas of the codebase where a consistent domain model and ubiquitous language apply. Ask CoreStory: "What are the natural domain boundaries in this monolith based on the business concepts each module operates on?" **Data ownership alignment.** Services should own their data. If two modules both write to the same tables, they likely belong in the same service (or the shared data needs to be decomposed). Ask CoreStory: "Which modules in this monolith access the same database tables? Map data ownership." **Team ownership alignment.** In organizations where Conway's Law applies (most of them), service boundaries should align with team boundaries. A service owned by two teams is a service that will diverge. This is a human decision, but CoreStory can inform it by showing which code modules are most cohesive. **Change frequency alignment.** Code that changes together should be in the same service. Code that changes independently is a candidate for separation. Ask CoreStory: "Which modules in this codebase have historically changed together? Which change independently?" ### Database Decomposition Strategies **Database-per-service** is the target end state but rarely the first step. It requires resolving all cross-service joins, foreign keys, and shared writes. Best for services with clear data ownership and no cross-service joins. **Shared database with schema ownership** is a practical intermediate step. Each service "owns" specific tables (enforced by convention or access control) but shares the same database server. This avoids the complexity of data replication while establishing ownership boundaries. **Change Data Capture (CDC)** enables data synchronization between services without tight coupling. The owning service writes to its database; CDC propagates changes to consuming services' databases as events. Tools like Debezium, AWS DMS, or database-native logical replication handle the mechanics. **The Outbox Pattern** provides reliable event publishing alongside database writes. Instead of publishing events directly (which risks inconsistency if the publish fails), the service writes both the data change and the event to the same database transaction. A separate process reads the outbox and publishes events. This guarantees at-least-once delivery. ### Distributed Transaction Management When a business operation spans multiple services, the single database transaction that guaranteed ACID properties in the monolith no longer exists. This is one of the most common failure modes in monolith-to-microservices migrations: teams extract a service, then discover that a critical workflow relied on a transaction that spanned what are now two separate databases. The **Saga pattern** manages distributed transactions through a sequence of local transactions with compensating actions for rollback. **Choreography (event-driven):** Each service publishes events that trigger the next step. No central coordinator. Service A completes its local transaction and publishes an event; Service B listens for that event, performs its local transaction, and publishes the next event. * **Use when:** Few services involved (2–3), low coordination complexity, the team is comfortable with event-driven debugging * **Advantages:** No single point of failure, loose coupling, each service is fully autonomous * **Drawbacks:** Harder to reason about the overall flow, harder to debug when something fails mid-saga, can create implicit coupling through event schemas * **Watch for:** Circular event chains, missing compensating transactions, inconsistent event ordering **Orchestration (coordinator-driven):** A central coordinator (saga orchestrator) manages the sequence. The orchestrator calls each service in order, tracks the state of the saga, and triggers compensating actions if any step fails. * **Use when:** Many services involved (4+), complex coordination logic, the team needs visibility into the overall workflow state * **Advantages:** Easier to understand and debug, clear ownership of the coordination logic, centralized error handling * **Drawbacks:** The orchestrator is a single point of failure (mitigate with redundancy), tighter coupling between orchestrator and services * **Tool support:** Temporal, AWS Step Functions, Camunda, Azure Durable Functions **Identifying saga candidates with CoreStory:** ``` send_message: "Analyze the current transaction boundaries in [ComponentName]. Which operations currently execute within a single database transaction but will span multiple services in the target architecture? For each operation: 1. What data is written across what will become service boundaries? 2. What is the current rollback behavior if the operation fails midway? 3. What compensating actions would be needed in a saga? 4. Is the operation's consistency requirement strict (must be immediate) or eventual (can tolerate brief inconsistency)?" ``` **Decision guidance:** Start with choreography for simple, two-service interactions. Move to orchestration when you find yourself building ad-hoc coordination logic across events. Most real-world modernizations end up with a mix — choreography for simple flows, orchestration for complex multi-service workflows. ### Communication Patterns **API Gateway routing** is the simplest Strangler Fig implementation. The gateway routes requests to the monolith or the extracted service based on URL path, header, or other criteria. This works well for HTTP-based entry points. **Branch by abstraction** works for internal coupling. Introduce an interface/abstraction in the monolith where the extracted component is called. Initially, the implementation calls the monolith code. After extraction, swap the implementation to call the new service. This is the Strangler Fig pattern applied at the code level rather than the network level. **Event-driven decoupling** replaces synchronous internal calls with asynchronous events. The monolith publishes events when state changes; the extracted service subscribes. This is more work to implement but reduces runtime coupling and enables independent scaling. *** ## Prompting Patterns Reference ### Boundary Identification Patterns | Pattern | Example | | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------- | | **Domain boundary** | "What are the natural domain boundaries in this monolith? Which modules operate on the same business concepts?" | | **Data ownership** | "Which modules write to the same database tables? Map the write access patterns." | | **Coupling analysis** | "How many direct calls exist between \[ModuleA] and \[ModuleB]? What would need to change to make them independent?" | | **Shared logic** | "What code is shared between \[ModuleA] and \[ModuleB]? Can it be extracted into a shared library, or does it belong in one service?" | ### Database Decomposition Patterns | Pattern | Example | | ------------------------ | ---------------------------------------------------------------------------------------------------------------------------- | | **Table ownership** | "For each database table, which module is the primary writer? Which modules only read?" | | **Cross-boundary joins** | "Which SQL queries join tables that belong to different modules? These are the joins that must be decomposed." | | **Foreign key mapping** | "What foreign key relationships cross the proposed service boundary? Which can be replaced with IDs and API lookups?" | | **Data volume** | "How many rows are in each table that needs to migrate? What's the write frequency? This determines the migration strategy." | ### Extraction Patterns | Pattern | Example | | ------------------------- | ----------------------------------------------------------------------------------------------------------------------------- | | **Entry point mapping** | "What HTTP routes, internal calls, and background jobs currently invoke \[ComponentName] logic?" | | **Anti-corruption layer** | "Where do the monolith's data model and the new service's model diverge? What translations are needed?" | | **Rollback planning** | "If the extracted service fails under production load, what is the fastest path to routing all traffic back to the monolith?" | | **Contract testing** | "What contract tests should exist between the extracted service and its consumers to catch breaking changes?" | ### Distributed Transaction Patterns | Pattern | Example | | --------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Transaction boundary analysis** | "Which operations in \[ComponentName] write to multiple database tables within a single transaction? Which of those tables will belong to different services?" | | **Compensating action design** | "If the \[ServiceA] step of \[Operation] succeeds but the \[ServiceB] step fails, what compensating action reverses the \[ServiceA] change?" | | **Consistency requirement** | "Does \[Operation] require strong consistency (all-or-nothing, immediate) or can it tolerate eventual consistency (brief window of inconsistency)?" | | **Saga variant selection** | "For the \[Operation] workflow spanning \[ServiceA], \[ServiceB], \[ServiceC]: is the coordination logic simple enough for choreography, or does the number of steps and error scenarios warrant orchestration?" | *** ## Best Practices **Extract the smallest viable service first.** Your first extraction should be the simplest possible: low coupling, clear data ownership, few consumers. The goal is to prove the extraction pattern works — establishing the façade, the deployment pipeline, the monitoring, and the team's muscle memory — before tackling harder extractions. Getting the infrastructure right on an easy service is far cheaper than getting it wrong on a hard one. **Don't break the monolith's database on day one.** Start with shared database/schema ownership. Let the extracted service access the monolith's database through a well-defined data access layer. Decompose the database later, once the service boundary is proven stable. Premature database decomposition is one of the most common causes of monolith-to-microservices failure. **The façade is your safety net — invest in it.** The Strangler Fig façade (API gateway, reverse proxy, or routing layer) is what makes incremental extraction safe. It should support percentage-based routing (for gradual rollout), circuit breaking (for automatic fallback), and request mirroring (for comparison testing). Invest in making this layer robust before the first extraction. **Design for independent deployment from day one.** The extracted service must be deployable without coordinating with monolith deployments. This means: independent CI/CD pipeline, independent configuration, independent database migrations, independent monitoring. If deploying the service requires a synchronized monolith deployment, you've built a distributed monolith. **Contract tests are non-negotiable.** Every interaction between the extracted service and the monolith (or other services) must have a contract test. Consumer-driven contract testing (Pact, Spring Cloud Contract) ensures that the service's API doesn't break its consumers and that the service's expectations of its dependencies are met. **Plan for the data synchronization tax.** During the Coexist phase, data often needs to be synchronized between the monolith's database and the new service's database. This synchronization is complex, error-prone, and temporary. Budget for it explicitly in your work packages, and design it to be removable. **Monitor business metrics, not just technical metrics.** Error rates and latency are necessary but insufficient. Monitor the business outcomes: order completion rate, payment success rate, user conversion. If a business metric drops after extraction, there's a behavioral regression that technical metrics might not catch. *** ## 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: | Harness | Install location | | --------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Claude Code** | `.claude/skills//SKILL.md` — Claude loads the body when the YAML `description` matches the task | | **GitHub Copilot** | Append to `.github/copilot-instructions.md` for repo-wide instructions, or save as `.github/instructions/.instructions.md` with an `applyTo` glob for path-scoped use | | **Cursor** | `.cursor/rules/.mdc` with a `description` field for auto-attach (use `globs` for path-scoped or `alwaysApply: true` for every session) | | **Factory.ai** | `.factory/droids/.md` (project) or `~/.factory/droids/.md` (personal); Factory loads it as a custom Droid | | **Aider** | `CONVENTIONS.md` at repo root, loaded with `aider --read CONVENTIONS.md` — or add it to the `read:` list in `.aider.conf.yml` for automatic loading | | **Codex / `AGENTS.md` harnesses** | Append the content to `AGENTS.md` at your repository root | | **Custom runtime** | Load the markdown into your agent's system prompt, rules file, or wherever it consumes workflow context | Want a single install that works across the most harnesses? Append the content to `AGENTS.md` at your repository root. The [`AGENTS.md` spec](https://agents.md/) 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 accordions below walk through end-to-end setup (skill file, slash command, version control) for the four most common harnesses. If you're on a different harness, copy the SKILL.md content from any accordion and install it per the conventions above. #### Setup 1. **Configure the CoreStory MCP server** in your Claude Code settings (see [CoreStory MCP Server Setup Guide](/getting-started/mcp-server-setup)). 2. **Add the skill file:** ```bash theme={null} mkdir -p .claude/skills/monolith-to-microservices ``` Create `.claude/skills/monolith-to-microservices/SKILL.md` with the content from the skill file below. 3. **Commit to version control:** ```bash theme={null} git add .claude/skills/ git commit -m "Add CoreStory monolith-to-microservices skill" ``` #### Usage ``` Extract [ServiceName] from the monolith Plan the service boundary for [ComponentName] Design the database decomposition for [ComponentName] extraction Execute work package WP-XXX (monolith extraction) ``` #### Tips * This skill is a Phase 5 variant that plugs into the broader modernization workflow. It expects Phases 1–4 to be complete. * For the first extraction, spend extra time on Step 2 (boundary identification) and Step 4 (façade design) — these establish the pattern for all subsequent extractions. * Keep the SKILL.md under 500 lines for reliable loading. #### Skill File Save as `.claude/skills/monolith-to-microservices/SKILL.md`: ```markdown theme={null} --- name: CoreStory Monolith to Microservices description: Guides service extraction from a monolith using CoreStory's code intelligence and the Strangler Fig pattern. Activates on microservice extraction, service boundary, database decomposition, or monolith decomposition requests. --- # CoreStory Monolith to Microservices When this skill activates, guide the user through the six-step workflow to extract a service from a monolith. ## Activation Triggers Activate when user requests: - Service extraction from a monolith - Service boundary identification or validation - Database decomposition planning - Strangler Fig implementation - Any request containing "extract service", "microservice", "monolith", "service boundary", "decompose database" ## Prerequisites - Completed Phases 1–4 of the modernization workflow - CoreStory MCP server configured with completed ingestion - Work package definition from Phase 4 **If you do not detect that you have access to CoreStory (e.g., `list_projects` fails or is unavailable), ask the user to verify that their MCP or API connection is properly configured and that this repository has been ingested. If the user has not yet created a CoreStory account, direct them to create one and upload their repo at [app.corestory.ai](https://app.corestory.ai).** ## Step 1: Context Loading 1. Identify target project (`list_projects`) 2. Locate prior conversations — decomposition, architecture, assessment 3. Retrieve work package details (`get_conversation`) 4. Create conversation: "[Extraction] SystemName - ServiceName (WP-XXX)" ## Step 2: Service Boundary Identification - Map domain boundary: MOVE / SHARE / LEAVE classification - Identify hidden coupling: direct calls, shared state, implicit deps - Validate feasibility: can service and monolith function independently? ## Step 3: Database Decomposition Planning - Map data dependencies: owned, read-only, shared writes - Choose strategy: database-per-service, schema ownership, CDC, API-mediated - Plan migration: sequence, sync during coexist, rollback ## Step 4: Façade & Communication Design - Map all entry points into the component - Design façade routing (API gateway / reverse proxy) - Choose communication patterns (sync / async per interaction) - Design anti-corruption layer ## Step 5: Service Extraction Execution - Transform: build new service using Spec-Driven Development delta spec - Coexist: configure façade, run both versions, monitor - Eliminate: remove legacy code, update routing, clean up ## Step 6: Verification & Cutover - Behavioral verification using Phase 2 inventory - Post-elimination testing - **HITL Gate: Engineering lead approves cutover** ## Error Handling - **Circular dependencies:** Boundary needs adjustment, merge components or introduce event decoupling - **Shared database can't be split:** Use schema ownership as intermediate step - **Façade can't route cleanly:** Consider branch-by-abstraction at code level - **Performance degradation after extraction:** Network calls replacing in-process calls — add caching, optimize APIs ``` Add the following to `.github/copilot-instructions.md`: ```markdown theme={null} ## Monolith to Microservices When asked to extract a service from a monolith or plan a microservices migration: 1. ALWAYS load the work package definition and prior phase findings 2. Map the precise domain boundary: code to MOVE, SHARE, or LEAVE 3. Identify hidden coupling: direct calls, shared state, database coupling 4. Plan database decomposition: choose strategy per shared table 5. Design the Strangler Fig façade and communication patterns 6. Execute Transform → Coexist → Eliminate with behavioral verification 7. Contract tests are non-negotiable for every service interaction 8. Start with shared database ownership; decompose fully later ``` **(Optional) Add a reusable prompt file.** Create `.github/prompts/monolith-to-microservices.prompt.md`: ```markdown theme={null} --- mode: agent description: Extract a service from a monolith using CoreStory's code intelligence and the Strangler Fig pattern --- Extract the specified service from the monolith following the Strangler Fig pattern. 1. Load the work package definition and prior phase findings 2. Map the precise service boundary within the monolith 3. Plan database decomposition for shared data dependencies 4. Design the façade layer and communication patterns 5. Generate a delta spec for the extracted service 6. Guide the Transform → Coexist → Eliminate cycle 7. Verify behavioral equivalence against the Phase 2 inventory ``` Create `.cursor/rules/monolith-to-microservices/RULE.md`: ```markdown theme={null} --- description: CoreStory-powered monolith-to-microservices extraction. Activates for service extraction, microservice decomposition, service boundary identification, or database decomposition. alwaysApply: false --- # CoreStory Monolith to Microservices You are a microservices architect with access to CoreStory's code intelligence via MCP. Guide service extraction from a monolith using the Strangler Fig pattern. ## Activation Triggers Apply when user requests: service extraction, microservice decomposition, service boundary identification, database decomposition for service extraction, or Strangler Fig implementation. **If you do not detect that you have access to CoreStory (e.g., `list_projects` fails or is unavailable), ask the user to verify that their MCP or API connection is properly configured and that this repository has been ingested. If the user has not yet created a CoreStory account, direct them to create one and upload their repo at [app.corestory.ai](https://app.corestory.ai).** ## Six-Step Workflow ### Step 1: Context Loading - Load work package, prior conversations, Tech Spec - Create extraction conversation ### Step 2: Service Boundary Identification - Domain boundary: MOVE / SHARE / LEAVE classification - Hidden coupling: calls, shared state, implicit dependencies - Boundary validation: independent deployability ### Step 3: Database Decomposition Planning - Table ownership mapping (owned, read-only, shared writes) - Strategy selection per dependency (database-per-service, schema ownership, CDC, API-mediated) - Migration plan: sequence, sync, rollback ### Step 4: Façade & Communication Design - Entry point mapping (HTTP, internal calls, jobs, events) - Façade routing design (API gateway / reverse proxy) - Communication patterns (sync / async per interaction) - Anti-corruption layer design ### Step 5: Service Extraction Execution - Transform: delta spec via Spec-Driven Development - Coexist: façade routing, monitoring, comparison testing - Eliminate: remove legacy code, clean up façade - **HITL Gate: Engineering lead approves cutover** ### Step 6: Verification & Cutover - Behavioral verification against Phase 2 inventory - Post-elimination testing - Business metric monitoring ## Key Principles - Extract the smallest viable service first - Don't decompose the database on day one - The façade is your safety net — invest in it - Contract tests are non-negotiable - Monitor business metrics, not just technical metrics ``` Create `.factory/droids/monolith-to-microservices.md`: ```markdown theme={null} --- name: CoreStory Monolith to Microservices description: Guides service extraction from a monolith using CoreStory code intelligence and the Strangler Fig pattern model: inherit tools: - CoreStory:list_projects - CoreStory:get_project_techspec - CoreStory:get_project_prd - CoreStory:create_conversation - CoreStory:send_message - CoreStory:rename_conversation - CoreStory:list_conversations - CoreStory:get_conversation --- # CoreStory Monolith to Microservices Execute the six-step workflow to extract a service from a monolith. ## Activation Triggers - "Extract [service] from the monolith" - "Plan service boundary for [component]" - "Decompose the database for [component] extraction" - Any monolith decomposition or service extraction request ## CoreStory MCP Tools - `CoreStory:list_projects` — identify the target project - `CoreStory:get_project_techspec` — understand monolith structure - `CoreStory:get_project_prd` — business domain context - `CoreStory:create_conversation` — open extraction thread - `CoreStory:send_message` — query for boundary analysis and extraction guidance - `CoreStory:list_conversations` / `CoreStory:get_conversation` — load prior phase findings - `CoreStory:rename_conversation` — mark completed thread "RESOLVED" **If you do not detect that you have access to CoreStory (e.g., `list_projects` fails or is unavailable), ask the user to verify that their MCP or API connection is properly configured and that this repository has been ingested. If the user has not yet created a CoreStory account, direct them to create one and upload their repo at [app.corestory.ai](https://app.corestory.ai).** ## Workflow Step 1: Context Loading → Load work package and prior phase findings Step 2: Service Boundary → Domain mapping (MOVE/SHARE/LEAVE), coupling analysis, validation Step 3: Database Decomposition → Data dependencies, strategy selection, migration plan Step 4: Façade Design → Entry points, routing rules, communication patterns, anti-corruption layer Step 5: Extraction → Transform (delta spec) → Coexist (façade + monitoring) → Eliminate (cleanup) Step 6: Verification → Behavioral equivalence → HITL cutover approval ## Key Principles - Extract the smallest viable service first - Start with shared database ownership, decompose later - Façade enables safe rollback at every step - Contract tests for every service interaction - Monitor business metrics, not just technical metrics ``` *** ## Troubleshooting **Can't find clean service boundaries — everything is tightly coupled.** This is the most common challenge in monolith decomposition. Start by identifying the modules with the lowest fan-in (fewest inbound dependencies) — these are the easiest to extract. If no clean boundaries exist, consider an intermediate step: introduce module boundaries *within* the monolith (a "modular monolith") before extracting services. Ask CoreStory: "Which modules have the fewest inbound dependencies from other modules?" **Shared database tables can't be cleanly assigned to one service.** Use schema ownership as a transitional strategy: both services access the same database, but each "owns" specific tables. Enforce ownership via convention or database-level access control. Over time, decompose the database fully using CDC or the outbox pattern for data synchronization. **Performance degrades after service extraction — API calls are slower than in-process calls.** This is expected. Network calls replace in-process calls, adding latency. Mitigations: add caching in the extracted service for frequently-read data, batch API calls where possible, use gRPC instead of REST for internal service communication, and consider whether the service boundary is correct — if two services call each other constantly, they might belong together. **The façade introduces a single point of failure.** Use a highly-available API gateway or load balancer for the façade layer. Most cloud providers offer managed API gateways with built-in redundancy (AWS API Gateway, Azure API Management, GCP API Gateway). For self-hosted, use a cluster of reverse proxies (Nginx, Envoy, HAProxy) behind a load balancer. **Data consistency issues during the Coexist phase.** Dual-write scenarios (where both the monolith and the extracted service can write to shared data) are inherently risky. Prefer single-writer patterns: one system is the source of truth for each piece of data, and the other reads via API or receives updates via events. If dual-write is unavoidable, use the outbox pattern with at-least-once delivery and idempotent consumers. **The extracted service works in testing but fails under production load.** This usually means the service wasn't tested with production-scale data or traffic patterns. Use shadow traffic (mirror production requests to the new service without serving the response) during the Coexist phase to validate performance before cutover. Also check: database connection pooling, thread/goroutine limits, memory allocation, and external dependency timeouts. **Agent can't access CoreStory tools.** See the [Supercharging AI Agents](/getting-started/supercharging-ai-agents) troubleshooting section for MCP connection issues. Verify the project has completed ingestion by calling `list_projects` and checking the status. *** ## What's Next **Extract the next service:** Move to the next work package in the migration sequence from [Decomposition & Sequencing →](/playbooks/modernization/decomposition-sequencing). Each extraction follows the same six-step pattern, but gets faster as the team builds muscle memory and the infrastructure matures. **Verify as you extract:** Each extraction's Coexist phase requires behavioral verification. Use [Behavioral Verification →](/playbooks/modernization/behavioral-verification) to prove each extracted service preserves its business rules. **Refine the delta spec:** For each component's Transform phase, use [Spec-Driven Development →](/playbooks/spec-driven-development) to create the delta spec that defines what changes from monolith to service. **Return to the hub:** [Code Modernization →](/playbooks/code-modernization) — the full six-phase framework. **For Jira integration:** [Using CoreStory with Jira →](/playbooks/using-corestory-with-jira) — tracking extraction work packages. **For agent setup:** [Supercharging AI Agents with CoreStory →](/getting-started/supercharging-ai-agents) — MCP server configuration and agent setup. # Target Architecture & Strategy Selection Source: https://docs.corestory.ai/playbooks/modernization/target-architecture Use CoreStory's codebase intelligence to inform the critical architectural decision: what modernization pattern to follow and what the target architecture should look like. ## Overview Phase 3 of the modernization workflow is where strategy becomes structure. You have the assessment data from Phase 1 and the business rules inventory from Phase 2. Now the question is: what are we modernizing *to*, and how? This is the most human-driven phase in the entire modernization workflow. CoreStory provides the analysis — natural service boundaries, coupling hotspots, data dependency maps, effort estimates — but the architectural decision belongs to the architect and stakeholders. AI is excellent at revealing what a system *is*; humans decide what it *should become*. The reason this boundary matters: architectural decisions are organizational commitments. They determine team structure, hiring plans, vendor contracts, timelines, and budgets. They affect compliance posture, operational complexity, and the skills your team needs to develop. These are not decisions an AI should make, no matter how good its analysis is. CoreStory serves as an **Expert** throughout this phase — explaining system behavior, identifying natural boundaries and extension points, and quantifying the gap between current and target states. It also serves as a **Navigator** when defining the target architecture, pointing to specific code patterns, data flows, and integration points that inform where boundaries should be drawn. **Who this is for:** Architects, engineering leads, and technical decision-makers responsible for choosing the modernization strategy and defining the target architecture. Also useful for consultants and system integrators presenting options to stakeholders. **What you'll get:** An Architectural Decision Record (ADR) documenting the selected modernization strategy, target architecture, migration scope, constraints, and stakeholder approval — the input that Phase 4 (Decomposition & Sequencing) turns into executable work packages. *** ## When to Use This Playbook * You've completed Phase 1 (Codebase Assessment) and have a Modernization Readiness Report with component-level readiness scores * You need to choose a modernization strategy (from the 7 Rs) for each component — not a single system-wide strategy * You need to define the target architecture before decomposing work into executable packages * You're presenting modernization options to stakeholders and need data-backed analysis to support the recommendation * You need to document an architectural decision with rationale, constraints, and approval for the audit trail ## When to Skip This Playbook * You've already made the architectural decision and need to decompose it into work packages — go to [Decomposition & Sequencing](/playbooks/modernization/decomposition-sequencing) * You're still assessing the current system — go back to [Codebase Assessment](/playbooks/modernization/codebase-assessment) * The modernization is a straightforward lift-and-shift (Rehost/Relocate) with no architectural changes — this playbook adds minimal value to infrastructure-only moves * You're doing a single-component refactor that doesn't require a formal architectural decision — use [Spec-Driven Development](/playbooks/spec-driven-development) directly *** ## Prerequisites * A **completed Codebase Assessment** (Phase 1) — the Modernization Readiness Report is the primary input to this phase * A **completed or in-progress Business Rules Inventory** (Phase 2) — understanding what the system *does* is essential for deciding what it should *become* * A **CoreStory account** with the legacy codebase ingested and ingestion complete * An **AI coding agent** with CoreStory MCP configured (see [Supercharging AI Agents](/getting-started/supercharging-ai-agents) for setup) * **The right people in the room:** This phase requires architectural judgment. The architect or tech lead who will own the target architecture should be driving this phase, not delegating it to the agent. * (Recommended) Access to the Codebase Assessment conversation thread in CoreStory for cross-referencing findings *** ## How It Works ### CoreStory MCP Tools Used | Tool | Step(s) | Purpose | | ---------------------- | ------- | -------------------------------------------------------------------- | | `list_projects` | 1 | Confirm the target project | | `create_conversation` | 1 | Start a dedicated architecture decision thread | | `send_message` | 2, 3, 4 | Query CoreStory for strategy exploration and architecture definition | | `list_conversations` | 1 | Find the assessment conversation from Phase 1 | | `get_conversation` | 1 | Retrieve assessment findings for cross-reference | | `get_project_techspec` | 1 | Retrieve Tech Spec for architectural vocabulary | | `get_project_prd` | 1 | Retrieve synthesized PRD for business context and requirements | | `rename_conversation` | 5 | Mark completed thread with "RESOLVED" prefix | ### The Strategy & Architecture Workflow > **Note:** The steps below are internal to this playbook. They are sub-steps of Phase 3 in the [six-phase modernization framework](/playbooks/code-modernization), not a separate numbering system. This playbook follows a five-step pattern: 1. **Input Review** — Load the Codebase Assessment report and Business Rules Inventory from prior phases. Establish the baseline that all strategy decisions reference. 2. **Strategy Exploration** — Query CoreStory to explore which modernization patterns are feasible given the current architecture. This is the divergent phase — open the option space before narrowing. 3. **Target Architecture Definition** — Define the target architecture with CoreStory's guidance on natural service boundaries, extension points, and alignment with the selected strategy. 4. **Risk & Effort Estimation** — Assess the gap between current and target architecture. Estimate effort and risk per component. This is where the strategy meets reality. 5. **Decision Documentation** — Record the architectural decision, rationale, constraints, and approval in an Architectural Decision Record (ADR). This artifact feeds Phase 4 and serves as the audit trail. ### The HITL Boundary This phase has the most critical human-in-the-loop gate in the entire modernization workflow: > **After Step 4:** The architect or tech lead reviews the target architecture, strategy recommendations, and risk/effort estimates. This is the gate where the architectural decision is made and approved by stakeholders. It must not be delegated to AI. CoreStory's role is to provide the best possible analysis so the human decision-maker has complete information. The agent should present options with trade-offs, not make recommendations that assume the decision is already made. *** ## Step-by-Step Walkthrough ### Step 1: Input Review Start by loading context from prior phases so all strategy exploration is grounded in actual assessment data. **Confirm the project and locate prior work:** ``` List my CoreStory projects. I need the project for [SystemName]. Then list all conversations — I need to find the assessment thread from Phase 1. ``` The agent calls `list_projects` and `list_conversations` to locate the assessment conversation. If you used the naming convention from the Codebase Assessment playbook, look for "RESOLVED - \[Assessment] SystemName - Modernization Readiness". **Retrieve assessment context:** ``` Retrieve the conversation history from our codebase assessment (conversation [conversation_id]). Summarize: 1. Overall readiness level and top findings 2. Component-level readiness scores and recommended strategies 3. Key coupling hotspots and shared data dependencies 4. Major blockers or prerequisites identified ``` The agent calls `get_conversation` to retrieve the assessment findings. This establishes the baseline for strategy exploration. **Create the architecture decision thread:** ``` Create a CoreStory conversation titled "[Architecture] SystemName - Strategy & Target Architecture". Store the conversation_id — we'll use this thread for all strategy exploration queries. ``` ### Step 2: Strategy Exploration With the assessment baseline loaded, explore which modernization patterns are feasible. This is the divergent phase — the goal is to understand the option space before narrowing to a decision. **Natural boundaries and decomposition candidates:** ``` send_message: "Given the current architecture, which components are natural candidates for service extraction? Where are the natural service boundaries in this codebase? What data and logic would need to move with each service?" ``` **Coupling and independence analysis:** ``` send_message: "Which components have the lowest coupling and could be modernized independently with minimal risk? Which components are so tightly coupled that they must be modernized together? Identify the component clusters." ``` **Strategy feasibility per component:** ``` send_message: "Evaluate the feasibility of each migration strategy for each major component identified in the assessment: 1. **Retire:** Decommission entirely — is this component still needed? Does usage data support keeping it? 2. **Retain:** Keep in current state — is modernization worth the cost and risk for this component? 3. **Rehost (lift and shift):** Move to cloud without code changes — does this component benefit from cloud infrastructure alone? 4. **Relocate:** Move to a different platform (e.g., VMware to VMware Cloud on AWS) — is this an infrastructure-level move? 5. **Replatform (lift, tinker, shift):** Minor optimizations without core redesign — can targeted changes capture most of the value? 6. **Refactor / Re-architect:** Redesign as a modern service — does the coupling, data model, or architecture require fundamental restructuring? 7. **Repurchase:** Replace with SaaS/COTS — does a commercial product cover this component's business rules adequately? For each strategy, evaluate: effort (engineering months), risk (what could go wrong), dependencies (what else must change), and payoff timeline (when do benefits materialize). Remember that different components can — and usually should — get different strategies." ``` **Deployment model implications:** ``` send_message: "What is the current deployment model and what would need to change for [target pattern]? Describe the gap between current deployment infrastructure and what [microservices / cloud-native / containerized / serverless] would require." ``` **Existing alignment:** ``` send_message: "Where does the current architecture already align with [target pattern]? Which components, patterns, or infrastructure elements can be carried forward without change? Where are the biggest gaps?" ``` ### Step 3: Target Architecture Definition Narrow from exploration to definition. Use CoreStory to validate the emerging target architecture against the actual codebase. **Service boundary definition:** ``` send_message: "If we extract [component] as a standalone service, what integration points need to be created? What shared data would need to be decoupled? What anti-corruption layers would be needed for the components that still depend on it?" ``` **Pattern carryforward:** ``` send_message: "What existing patterns in the codebase should carry forward to the target architecture? Identify design patterns, API conventions, data access patterns, and configuration approaches that are well-implemented and should be preserved." ``` **Gap analysis:** ``` send_message: "For the target architecture we're defining — [describe target] — where does the current codebase already align and where are the biggest structural gaps? For each gap, describe what would need to change." ``` **Data architecture implications:** ``` send_message: "How should the data architecture change to support the target architecture? Identify: 1. Shared databases that need to be split 2. Data that needs to be replicated or synchronized between services 3. Foreign key relationships that cross the proposed service boundaries 4. Database-level business logic (triggers, stored procedures) that would need to move to application code This is often the hardest part of the architecture change — be specific." ``` **Cross-cutting concerns:** ``` send_message: "How should cross-cutting concerns be handled in the target architecture? Address: 1. Authentication and authorization — centralized or per-service? 2. Logging and observability — what changes? 3. Configuration management — how does it scale to multiple services? 4. Error handling and resilience — circuit breakers, retries, fallbacks? 5. API versioning and contract management" ``` **Behavior tagging:** Once service boundaries and patterns are defined, tag every behavior identified in the specification with an explicit migration intent. This prevents silent changes — each behavior gets a deliberate decision. ``` send_message: "For each behavior in the specification that falls within [component/service boundary], assign one of these tags: - PRESERVE — behavior carries forward exactly as-is - MODERNIZE — same behavior, improved implementation (performance, maintainability, security) - CHANGE — behavior is intentionally altered (new business logic, different rules) - NEW — behavior that doesn't exist in the current system - RETIRE — behavior being intentionally removed For each tagged behavior, note: 1. Which tag and why 2. What verification would confirm correctness for this tag 3. Any dependencies on other behaviors" ``` The tags have direct consequences downstream: * **Phase 4 (Decomposition):** Each work package's scope is defined by its tags. A package dominated by `PRESERVE` and `MODERNIZE` is lower-risk than one heavy on `CHANGE` and `NEW`. * **Phase 5 (Execution):** TDD assertions differ by tag. `PRESERVE` behaviors get regression tests asserting identical output. `CHANGE` behaviors get tests asserting the *new* expected output. `NEW` behaviors need tests written from scratch. * **Phase 6 (Verification):** Verification criteria differ by tag. `PRESERVE` items require behavioral equivalence proof. `MODERNIZE` items require equivalence plus improvement metrics. `CHANGE` items require stakeholder sign-off on the new behavior. **Scope creep detection:** If `CHANGE` + `NEW` tags exceed roughly 20% of the tagged items in a work unit, the unit is drifting from modernization toward rewrite — fundamentally different risk characteristics. Flag to the program manager for scope review before proceeding to Phase 4. ### Step 4: Risk & Effort Estimation Quantify the gap between current and target state so the decision-makers have realistic expectations. **Component-level effort estimation:** ``` send_message: "For the target architecture we've defined, estimate the relative effort for each component migration: For each component, provide: 1. Current state → Target state (brief description of the change) 2. Effort estimate (low / medium / high / very high) 3. Key risks specific to this component 4. Dependencies — what must be done before this component can migrate 5. Temporary integration work needed during migration (anti-corruption layers, adapters, data sync) Be honest about uncertainty — flag areas where the effort is hard to estimate and why." ``` **Risk register for the migration:** ``` send_message: "What are the top risks of pursuing this target architecture? Consider: 1. Data migration risks (shared databases, data consistency during cutover) 2. Integration risks (breaking existing integrations, API compatibility) 3. Performance risks (latency from service decomposition, network overhead) 4. Organizational risks (team skill gaps, operational complexity increase) 5. Compliance risks (data residency changes, audit trail continuity) 6. Rollback risks (can we revert if something goes wrong mid-migration?) For each risk, suggest a mitigation strategy." ``` **Alternative architectures:** ``` send_message: "What alternative target architectures should be considered? For example: - A less aggressive decomposition (fewer services, larger boundaries) - A staged approach (intermediate architecture before final target) - A different pattern entirely (modular monolith instead of microservices) For each alternative, describe the trade-offs compared to the primary target architecture." ``` This is where the human decision-maker should engage directly. The agent has surfaced the options, feasibility analysis, effort estimates, and risks. The architect reviews this analysis and makes the call. ### Step 5: Decision Documentation Record the decision in an Architectural Decision Record. This artifact serves three purposes: it documents the rationale for future reference, it provides the input for Phase 4 (Decomposition & Sequencing), and it creates the audit trail for governance. **Generate the ADR:** ``` Based on our strategy exploration, target architecture definition, and risk analysis, generate an Architectural Decision Record using this template: 1. Current State — summary from the Codebase Assessment 2. Selected Strategy — which of the 7 Rs for each component, and why 3. Target Architecture — description of the target state with component responsibilities and communication patterns 4. Migration Scope — component-by-component migration table 5. Constraints & Assumptions — what bounds this decision 6. Risks & Mitigations — top risks with mitigation strategies 7. Approval checklist — architecture review, stakeholder sign-off, risk acknowledgment ``` **Mark the thread complete:** ``` Rename the conversation to "RESOLVED - [Architecture] SystemName - Strategy & Target Architecture". ``` *** ## Output Format: Architectural Decision Record The following diagram illustrates the transformation from current to target architecture — the visual complement to the ADR's Components table. Mapping arrows show which current modules become which target services, color-coded by strategy: Current-to-Target Architecture Comparison — side-by-side showing the monolith modules on the left mapping to independent services on the right, color-coded by modernization strategy The primary deliverable is an ADR that feeds Phase 4 (Decomposition & Sequencing). Here is the template: ```markdown theme={null} # Architectural Decision Record: [Project Name] Modernization **Decision Date:** [Date] **Decision Maker(s):** [Names and roles] **CoreStory Project:** [project_id] **Assessment Reference:** [conversation_id from Phase 1] **Architecture Thread:** [conversation_id from this phase] ## Current State [Summary from the Codebase Assessment — architecture overview, key findings, readiness scores. Keep this concise; reference the full assessment for detail.] ## Selected Strategy **Primary pattern:** [e.g., Refactor / Re-architect — monolith to microservices] **Rationale:** [Why this strategy was selected over alternatives. Reference specific findings from the assessment and strategy exploration that support the decision.] **Hybrid strategy note:** [Which components get which strategy. Not everything gets the same treatment.] ## Target Architecture [Description of the target state — component responsibilities, service boundaries, communication patterns, data architecture, deployment model. Include enough detail for Phase 4 to decompose into work packages.] ### Components | Component | Current Role | Target Role | Strategy | |-----------|-------------|-------------|----------| | [Name] | [Current description] | [Target description] | [7 Rs strategy] | ### Communication Patterns [How services will communicate in the target architecture — sync/async, API gateway, event bus, etc.] ### Data Architecture [How data ownership changes — which databases split, which stay shared during migration, data sync strategy during coexistence] ## Migration Scope | Component | Current State | Target State | Strategy | Priority | Risk | Effort | |-----------|--------------|-------------|----------|----------|------|--------| | [Name] | [Description] | [Description] | [R] | [1-5] | [H/M/L] | [L/M/H/VH] | **Effort scale:** L = <1 engineering month, M = 1–3 months, H = 3–6 months, VH = 6+ months (per component, including testing and verification). **Risk scale:** L = rollback trivial, no data migration; M = rollback planned, data migration required; H = rollback complex, cross-team dependencies; VH = irreversible or regulatory implications. ## Constraints & Assumptions - [Constraint 1 — e.g., "PCI-DSS compliance requires payment data to remain in the existing data center during migration"] - [Constraint 2 — e.g., "Team has no Kubernetes experience; container orchestration must be introduced incrementally"] - [Assumption 1 — e.g., "Business rules inventory will be complete before execution begins"] ## Risks & Mitigations | Risk | Severity | Mitigation | |------|----------|------------| | [Risk description] | [Critical/High/Medium/Low] | [Mitigation strategy] | ## Alternatives Considered | Alternative | Trade-offs | Why Not Selected | |-------------|-----------|-----------------| | [Alternative architecture] | [Pros and cons] | [Reason for rejection] | ## Approval - [ ] Architecture review complete - [ ] Stakeholder sign-off - [ ] Risk assessment acknowledged - [ ] Budget and timeline approved - [ ] Team capability assessment complete ``` *** ## Prompting Patterns Reference ### Strategy Exploration Patterns The goal of Step 2 is to open the option space. Use divergent queries that explore multiple strategies rather than converging on one prematurely. | Pattern | Example | | ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | **Feasibility scan** | "For each component, evaluate the feasibility of all seven strategies: Retire, Retain, Rehost, Relocate, Replatform, Refactor/Re-architect, and Repurchase. For each, assess effort, risk, dependencies, and payoff timeline." | | **Boundary detection** | "Where are the natural service boundaries? What data and logic would need to move with each proposed service?" | | **Coupling clusters** | "Which components are so tightly coupled they must be modernized together? Identify the minimal migration units." | | **What-if analysis** | "If we extract OrderService as a standalone service, what integration points and anti-corruption layers are needed?" | | **Deployment gap** | "What is the gap between the current deployment model and what microservices/cloud-native would require?" | The following decision tree provides a starting heuristic for mapping component characteristics to modernization strategies. This is a heuristic, not a prescription — the architect makes the final call: ```mermaid theme={null} %%{init: {'theme': 'base', 'themeVariables': { 'primaryColor': '#1a1a2e', 'primaryTextColor': '#ffffff', 'primaryBorderColor': '#c9a84c', 'lineColor': '#c9a84c', 'fontFamily': 'Inter, system-ui, sans-serif'}}}%% graph TD START["Component from
Phase 1 Assessment"] Q1{"Is this component
actively used?"} Q2{"Readiness score?"} Q3{"Does it need
architectural change?"} Q4{"Can prerequisites
be addressed?"} Q5{"SaaS replacement
available?"} Q6{"Infrastructure
change only?"} T_RETIRE["🔴 Retire
Decommission safely"] T_REARCH["🟣 Re-architect
Redesign and rebuild"] T_REFACTOR["🔵 Refactor
Improve incrementally"] T_RETAIN["⚪ Retain
Keep as-is for now"] T_REPURCHASE["🟢 Repurchase
Replace with SaaS"] T_REPLATFORM["🔵 Rehost / Replatform
Move infrastructure only"] T_ADDRESS["🔄 Address Prerequisites
Then re-evaluate"] START --> Q1 Q1 -->|"No"| T_RETIRE Q1 -->|"Yes"| Q5 Q5 -->|"Yes"| T_REPURCHASE Q5 -->|"No"| Q2 Q2 -->|"4–5 (ready)"| Q3 Q2 -->|"1–3 (not ready)"| Q4 Q3 -->|"Yes"| T_REARCH Q3 -->|"No"| Q6 Q6 -->|"Yes"| T_REPLATFORM Q6 -->|"No"| T_REFACTOR Q4 -->|"Yes"| T_ADDRESS Q4 -->|"No"| T_RETAIN style START fill:#1a1a2e,stroke:#c9a84c,stroke-width:2px,color:#ffffff style Q1 fill:#c9a84c,stroke:#1a1a2e,stroke-width:2px,color:#1a1a2e style Q2 fill:#c9a84c,stroke:#1a1a2e,stroke-width:2px,color:#1a1a2e style Q3 fill:#c9a84c,stroke:#1a1a2e,stroke-width:2px,color:#1a1a2e style Q4 fill:#c9a84c,stroke:#1a1a2e,stroke-width:2px,color:#1a1a2e style Q5 fill:#c9a84c,stroke:#1a1a2e,stroke-width:2px,color:#1a1a2e style Q6 fill:#c9a84c,stroke:#1a1a2e,stroke-width:2px,color:#1a1a2e style T_RETIRE fill:#4a1a1a,stroke:#ef4444,stroke-width:2px,color:#fca5a5 style T_REARCH fill:#2e1065,stroke:#8b5cf6,stroke-width:2px,color:#c4b5fd style T_REFACTOR fill:#0c4a6e,stroke:#3b82f6,stroke-width:2px,color:#93c5fd style T_RETAIN fill:#1f2937,stroke:#6b7280,stroke-width:2px,color:#d1d5db style T_REPURCHASE fill:#14532d,stroke:#22c55e,stroke-width:2px,color:#86efac style T_REPLATFORM fill:#0c4a6e,stroke:#06b6d4,stroke-width:2px,color:#67e8f9 style T_ADDRESS fill:#0f3460,stroke:#c9a84c,stroke-width:2px,color:#c9a84c ``` ### Architecture Definition Patterns Step 3 narrows from exploration to definition. Use convergent queries that validate specific architectural choices. | Pattern | Example | | ----------------------------- | --------------------------------------------------------------------------------------------------------------------------- | | **Integration point mapping** | "If we extract \[component], what shared data must be decoupled and what new integration points are created?" | | **Pattern preservation** | "What existing design patterns, API conventions, and data access patterns should carry forward to the target architecture?" | | **Gap quantification** | "For the target architecture, where does the current codebase align and where are the biggest structural gaps?" | | **Data decomposition** | "Which shared databases need to split? Which foreign key relationships cross the proposed service boundaries?" | | **Cross-cutting resolution** | "How should auth, logging, config, and error handling work in the target architecture?" | *** ## Best Practices **Present options, not conclusions.** The agent should surface multiple feasible strategies with trade-offs, not converge on a single recommendation. The architectural decision belongs to the human. Framing matters: "Here are three viable approaches with their trade-offs" is better than "You should do X." **Ground every recommendation in assessment data.** Every strategy recommendation should reference specific findings from the Phase 1 assessment. "Re-architect is recommended for OrderService because the assessment found it shares 12 database tables with 4 other services and has a readiness score of 2" is actionable. "Re-architect is recommended for OrderService because it would benefit from modernization" is not. **Don't force a single strategy.** 53% of enterprises pursue hybrid strategies ([Kyndryl 2025 State of IT Infrastructure Report](https://www.kyndryl.com/us/en/perspectives/articles/2025/01/state-of-it-infrastructure-report)). Different components should get different strategies based on their readiness scores, coupling profiles, and business value. The ADR should explicitly document the per-component strategy, not a single system-wide approach. **Address data architecture explicitly.** Data decomposition is consistently the hardest part of modernization — especially for monolith-to-microservices patterns. The target architecture must address how shared databases will be handled during and after migration. Skipping this produces a target architecture that looks clean on paper but is infeasible in practice. **Include alternatives considered.** Documenting rejected alternatives and the reasons for rejection is as valuable as documenting the selected strategy. It prevents relitigating the decision later and demonstrates that the choice was deliberate. **Account for organizational constraints.** The best technical architecture is useless if the team can't build or operate it. Factor in team skills, hiring timelines, operational complexity, compliance constraints, and budget when evaluating strategies. CoreStory can analyze the code; the humans must assess the organization. **Use a staged target if needed.** Not every modernization needs to reach the final target architecture in one program. An intermediate architecture (e.g., modular monolith before microservices) may be more feasible and still deliver significant value. The ADR should document whether the target is the final state or an intermediate step. *** ## 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: | Harness | Install location | | --------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Claude Code** | `.claude/skills//SKILL.md` — Claude loads the body when the YAML `description` matches the task | | **GitHub Copilot** | Append to `.github/copilot-instructions.md` for repo-wide instructions, or save as `.github/instructions/.instructions.md` with an `applyTo` glob for path-scoped use | | **Cursor** | `.cursor/rules/.mdc` with a `description` field for auto-attach (use `globs` for path-scoped or `alwaysApply: true` for every session) | | **Factory.ai** | `.factory/droids/.md` (project) or `~/.factory/droids/.md` (personal); Factory loads it as a custom Droid | | **Aider** | `CONVENTIONS.md` at repo root, loaded with `aider --read CONVENTIONS.md` — or add it to the `read:` list in `.aider.conf.yml` for automatic loading | | **Codex / `AGENTS.md` harnesses** | Append the content to `AGENTS.md` at your repository root | | **Custom runtime** | Load the markdown into your agent's system prompt, rules file, or wherever it consumes workflow context | Want a single install that works across the most harnesses? Append the content to `AGENTS.md` at your repository root. The [`AGENTS.md` spec](https://agents.md/) 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 accordions below walk through end-to-end setup (skill file, slash command, version control) for the four most common harnesses. If you're on a different harness, copy the SKILL.md content from any accordion and install it per the conventions above. #### Setup 1. **Configure the CoreStory MCP server** in your Claude Code settings (see [CoreStory MCP Server Setup Guide](/getting-started/mcp-server-setup)). 2. **Add the skill file:** ```bash theme={null} mkdir -p .claude/skills/target-architecture ``` Create `.claude/skills/target-architecture/SKILL.md` with the content from the skill file below. 3. **Commit to version control:** ```bash theme={null} git add .claude/skills/ git commit -m "Add CoreStory target architecture skill" ``` #### Usage The skill activates automatically when Claude Code detects architecture decision requests: ``` Help me choose a modernization strategy for our legacy system Define the target architecture for our modernization What's the best migration pattern for this codebase? ``` #### Tips * This skill focuses on Phase 3 of the broader modernization workflow. It expects Phase 1 (Codebase Assessment) to be complete. * The skill should present options and trade-offs, not make the architectural decision. The human decides. * Keep the SKILL.md under 500 lines for reliable loading. #### Skill File Save as `.claude/skills/target-architecture/SKILL.md`: ```markdown theme={null} --- name: CoreStory Target Architecture & Strategy description: Guides the architectural decision for modernization — strategy selection, target architecture definition, risk/effort estimation. Activates on architecture decision, strategy selection, or target architecture requests. --- # CoreStory Target Architecture & Strategy When this skill activates, guide the user through the five-step workflow to produce an Architectural Decision Record (ADR). ## Activation Triggers Activate when user requests: - Modernization strategy selection or architecture decision - Target architecture definition for modernization - Migration pattern evaluation or comparison - Any request containing "target architecture", "migration strategy", "modernization pattern", "7 Rs", "architecture decision" ## Prerequisites - Completed Codebase Assessment (Phase 1) with Modernization Readiness Report - CoreStory MCP server configured with completed ingestion - The human decision-maker should be driving this phase **If you do not detect that you have access to CoreStory (e.g., `list_projects` fails or is unavailable), ask the user to verify that their MCP or API connection is properly configured and that this repository has been ingested. If the user has not yet created a CoreStory account, direct them to create one and upload their repo at [app.corestory.ai](https://app.corestory.ai).** ## Step 1: Input Review 1. Identify target project (`list_projects`) 2. Locate assessment conversation (`list_conversations`) 3. Retrieve assessment findings (`get_conversation`) 4. Summarize: readiness scores, coupling hotspots, shared data deps, blockers 5. Create conversation: "[Architecture] SystemName - Strategy & Target Architecture" ## Step 2: Strategy Exploration Query CoreStory to explore the option space: - "Which components are natural candidates for service extraction?" - "Which components have lowest coupling and could be modernized independently?" - "Which components are so tightly coupled they must be modernized together?" - "For each component, evaluate feasibility of all seven strategies: Retire, Retain, Rehost, Relocate, Replatform, Refactor/Re-architect, Repurchase" - "What deployment model changes would [target pattern] require?" **Present options with trade-offs. Do NOT converge on a single recommendation.** ## Step 3: Target Architecture Definition - "If we extract [component], what integration points and shared data must be decoupled?" - "What existing patterns should carry forward to the target architecture?" - "Where does the current architecture align with [target] and where are the biggest gaps?" - Address data architecture: shared DBs to split, FK relationships crossing boundaries, data sync - Address cross-cutting concerns: auth, logging, config, error handling ## Step 4: Risk & Effort Estimation - Per-component effort estimate (current → target, effort, risks, dependencies) - Top migration risks with mitigations (data, integration, performance, org, compliance, rollback) - Alternative architectures with trade-offs **HITL Gate: Present analysis to architect/tech lead for the architectural decision.** ## Step 5: Decision Documentation - Generate Architectural Decision Record (ADR): Current State | Selected Strategy | Target Architecture | Migration Scope | Constraints | Risks & Mitigations | Alternatives Considered | Approval - Rename conversation: "RESOLVED - [Architecture] SystemName - Strategy & Target Architecture" ## Error Handling - **Assessment not found:** Direct user to complete Codebase Assessment first - **Too many options, no clarity:** Focus on the highest-value, lowest-coupling component first - **Stakeholders disagree:** Document competing alternatives with trade-offs for each - **Data decomposition unclear:** Ask targeted questions about shared table access patterns ``` #### Setup Add the following to `.github/copilot-instructions.md`: ```markdown theme={null} ## Target Architecture & Strategy Selection When asked to define a target architecture or select a modernization strategy: 1. ALWAYS start by loading the Codebase Assessment findings from the prior phase 2. Explore multiple strategies per component — never converge on one option prematurely 3. Use the 7 Rs framework (Retire, Retain, Rehost, Relocate, Replatform, Refactor/Re-architect, Repurchase) 4. Address data architecture explicitly — shared databases are the hardest decomposition challenge 5. Estimate effort and risk per component with specific evidence from the assessment 6. Present options with trade-offs — the human makes the architectural decision, not the AI 7. Document the decision in an Architectural Decision Record (ADR) with rationale, constraints, and approval ``` **(Optional) Add a reusable prompt file.** Create `.github/prompts/target-architecture.prompt.md`: ```markdown theme={null} --- mode: agent description: Define a target architecture and select modernization strategy using CoreStory's code intelligence --- Guide the architecture decision for modernization of the specified system using CoreStory. 1. Load the Codebase Assessment findings from the prior phase 2. Explore strategy options per component (7 Rs framework) 3. Define target architecture with service boundaries, data architecture, communication patterns 4. Estimate effort and risk per component 5. Present options with trade-offs for the human decision-maker 6. Document the decision in an Architectural Decision Record (ADR) Critical: Present options, not conclusions. The architectural decision belongs to the human. ``` Create `.cursor/rules/target-architecture/RULE.md`: ```markdown theme={null} --- description: CoreStory-powered target architecture and strategy selection for modernization. Activates for architecture decisions, strategy selection, migration pattern evaluation. alwaysApply: false --- # CoreStory Target Architecture & Strategy You are a modernization architect with access to CoreStory's code intelligence via MCP. Guide the user through strategy selection and target architecture definition. ## Activation Triggers Apply when user requests: target architecture, modernization strategy, migration pattern selection, architecture decision, or 7 Rs evaluation. **If you do not detect that you have access to CoreStory (e.g., `list_projects` fails or is unavailable), ask the user to verify that their MCP or API connection is properly configured and that this repository has been ingested. If the user has not yet created a CoreStory account, direct them to create one and upload their repo at [app.corestory.ai](https://app.corestory.ai).** ## Five-Step Workflow ### Step 1: Input Review - Load Codebase Assessment findings from prior phase - Summarize readiness scores, coupling hotspots, shared data dependencies ### Step 2: Strategy Exploration - Explore multiple strategies per component (7 Rs framework) - Identify natural service boundaries and coupling clusters - Evaluate deployment model implications - **Present options with trade-offs — do not converge prematurely** ### Step 3: Target Architecture Definition - Define service boundaries, communication patterns, data architecture - Identify shared databases to split and cross-boundary dependencies - Address cross-cutting concerns (auth, logging, config, resilience) - Preserve well-implemented existing patterns ### Step 4: Risk & Effort Estimation - Per-component effort estimate with risks and dependencies - Top migration risks with mitigations - Alternative architectures with trade-offs - **HITL Gate: Human makes the architectural decision** ### Step 5: Decision Documentation - Generate Architectural Decision Record (ADR) - Rename conversation with "RESOLVED" prefix ## Key Principles - Present options, not conclusions — the human decides - Different components should get different strategies (hybrid is normal) - Data decomposition is the hardest part — address it explicitly - Ground every recommendation in assessment data - Account for organizational constraints, not just technical feasibility ``` Create `.factory/droids/target-architecture.md`: ```markdown theme={null} --- name: CoreStory Target Architecture & Strategy description: Guides modernization strategy selection and target architecture definition using CoreStory code intelligence model: inherit tools: - CoreStory:list_projects - CoreStory:get_project_techspec - CoreStory:get_project_prd - CoreStory:create_conversation - CoreStory:send_message - CoreStory:rename_conversation - CoreStory:list_conversations - CoreStory:get_conversation --- # CoreStory Target Architecture & Strategy Execute the five-step workflow to produce an Architectural Decision Record (ADR). ## Activation Triggers - "Define target architecture for [system]" - "Select modernization strategy" or "choose migration pattern" - "Architecture decision" or "7 Rs evaluation" - Any target architecture or strategy selection request ## CoreStory MCP Tools - `CoreStory:list_projects` — identify the target project - `CoreStory:get_project_techspec` — retrieve Tech Spec for architecture - `CoreStory:create_conversation` — open strategy exploration thread - `CoreStory:send_message` — query CoreStory (primary investigation tool) - `CoreStory:list_conversations` / `CoreStory:get_conversation` — load prior phase findings - `CoreStory:rename_conversation` — mark completed thread "RESOLVED" **If you do not detect that you have access to CoreStory (e.g., `list_projects` fails or is unavailable), ask the user to verify that their MCP or API connection is properly configured and that this repository has been ingested. If the user has not yet created a CoreStory account, direct them to create one and upload their repo at [app.corestory.ai](https://app.corestory.ai).** ## Workflow Step 1: Input Review → Load assessment findings, create conversation Step 2: Strategy Exploration → Explore 7 Rs per component, find boundaries and coupling clusters Step 3: Target Architecture → Define boundaries, data architecture, communication, cross-cutting concerns Step 4: Risk & Effort → Per-component estimates, risk register, alternatives → HITL architecture approval Step 5: Documentation → Architectural Decision Record → rename conversation "RESOLVED" ## Key Principles - Present options, not conclusions — the human decides - Different components should get different strategies - Data decomposition is the hardest part — address explicitly - Ground every recommendation in assessment data - Account for organizational constraints, not just technical feasibility ``` *** ## Troubleshooting **The assessment conversation can't be found.** Use `list_conversations` to see all available threads. If the assessment used the naming convention from the Codebase Assessment playbook, search for "RESOLVED - \[Assessment]". If the assessment was done in a prior session or by a different team member, you may need to retrieve the assessment report as a document rather than through CoreStory conversation history. **CoreStory recommends a single strategy for everything.** Push back with targeted queries. Ask about specific components: "What about the payment processing module specifically — could it be retained while the rest is re-architected? What would the integration boundary look like?" Different components have different readiness profiles, and the analysis should reflect that. **The target architecture is too ambitious for the team.** Consider a staged approach. Ask CoreStory: "What intermediate architecture could we reach that delivers value but is less complex than full microservices?" A modular monolith or a partial decomposition (extracting 2–3 high-value services while keeping the rest monolithic) is often the right first step. **Data decomposition seems impossible.** This is the most common sticking point in monolith-to-microservices patterns. Ask targeted questions: "Which tables are written by only one module?" (those are the easy ones), "Which tables are written by multiple modules?" (those need careful planning), "Can we use an event-driven approach to sync data between services during coexistence?" The [Monolith to Microservices](/playbooks/modernization/monolith-to-microservices) variant playbook addresses this in detail. **Stakeholders can't agree on a strategy.** Document each competing approach as an alternative in the ADR with trade-offs. Use CoreStory to provide objective data: effort estimates, risk profiles, component dependency analysis. Data-backed trade-offs are easier to resolve than opinion-based disagreements. **Agent can't access CoreStory tools.** See the [Supercharging AI Agents](/getting-started/supercharging-ai-agents) troubleshooting section for MCP connection issues. Verify the project has completed ingestion by calling `list_projects` and checking the status. *** ## What's Next **Decompose and sequence:** The ADR feeds directly into Phase 4. Use [Decomposition & Sequencing →](/playbooks/modernization/decomposition-sequencing) to break the target architecture into executable work packages ordered by dependency. **Extract business rules (if not complete):** If Phase 2 is still in progress, complete it before starting execution. Use [Business Rules Extraction →](/playbooks/business-rules-extraction) — the behavioral contract that Phase 6 verifies against. **Review the first variant:** If the selected strategy is monolith-to-microservices, review [Monolith to Microservices →](/playbooks/modernization/monolith-to-microservices) for pattern-specific guidance. **Return to the hub:** [Code Modernization →](/playbooks/code-modernization) — the full six-phase framework. **For agent setup:** [Supercharging AI Agents with CoreStory →](/getting-started/supercharging-ai-agents) — MCP server configuration and agent setup. # Vibe Modernization Source: https://docs.corestory.ai/playbooks/modernization/vibe-modernization Run the modernization workflow at its most aggressive setting — the agent drives the build loop end to end, humans hold a small number of high-leverage gates, and independent verification proves the result under audit. ## Overview Vibe coding is the most fun software has been in years: you describe what you want, the agent writes it, you keep moving. On a side project that trade is obviously worth it. Point the same loop at a system that clears customs declarations, prices policies, or moves money, and the trade inverts — not because the agent writes bad code, but because nothing in the loop *proves* the result is correct. There is no ground truth and no audit trail. When someone asks "how do you know this behaves like the system it replaced?", the honest answer is a shrug. The wall is not speed. Modernizations do not stall because the code arrived too fast. The wall is proof. **Vibe modernization is rebuilding a legacy system by turning a grounded AI agent loose to forward-engineer its behavior into the target architecture — the speed and feel of vibe coding, bolted to verified ground truth so it holds up under audit.** This is a *mode* of code modernization, not a replacement for it. It runs the same six-phase spine as the [Code Modernization](/playbooks/code-modernization) playbook and reaches the same gates. What makes it its own variant is a single decision about **who's driving** — and the disciplines that decision forces. Where the architecture-to-architecture variants (like [Monolith → Microservices](/playbooks/modernization/monolith-to-microservices)) specialize the framework by *target shape*, this one specializes it by *execution mode*. The two compose: you can run vibe modernization toward a microservices target. CoreStory's role shifts accordingly. In the base playbook CoreStory is an advisor to a human protagonist — Expert, Navigator, Verifier. Here the agent is the protagonist and CoreStory is the **grounding layer that makes agent velocity safe**: it accelerates discovery across both the legacy system and the target, and every claim it surfaces is checked against source before it enters a deliverable. **Who this is for:** Engineering leads and delivery teams who want agent-speed modernization on a system where behavioral parity is a hard requirement — regulated domains, financial calculations, compliance filings, anything where getting behavior wrong is expensive. **What you'll get:** A working modernized component *and* the audit trail that proves it — a gap report per work item, test-first code in the target's own idiom, a Behavioral Equivalence Report, an independent conformance ledger, and a running provenance record tying every decision back to a source anchor. *** ## When to Use This Playbook Reach for this variant when **both** of the following hold: * **Behavioral parity is the point.** The value is in preserving decades of accreted behavior, not re-imagining the product. If the goal is a redesign, this isn't it — that's a rewrite, and this playbook's entire verification apparatus is built to catch exactly the drift a rewrite intends. * **You want agent velocity without giving up the audit trail.** The deliverable is a source-traced, independently-verified body of work, not just working code. If nobody will ever ask you to prove equivalence, the overhead here is not worth paying. That is the whole entry test. Note what is deliberately *not* on it: whether the target already exists. The method runs either way — see [Standing vs. greenfield target](#standing-vs-greenfield-target) below. ## When to Skip This Playbook * **You cannot ingest the legacy system.** Everything downstream depends on grounding claims in legacy source. Without it you are vibe coding, not vibe modernizing. * **No one can validate the business rules.** The behavioral spec is the contract the whole method verifies against. If no domain expert can confirm it, you will build fast against the wrong contract. * **You cannot staff independent verification.** The method's safety property comes from the verifier being separate from the builder. If the same session and the same person write the code, the tests, *and* the equivalence report, you have re-created the circularity this variant exists to break — and you would be better served by the base playbook's continuous human review. * **The strategy is Rehost or Relocate.** No application-level change means no behavior to forward-engineer. See the [7 Rs](/playbooks/code-modernization#the-7-rs-choosing-a-modernization-strategy). * **The team has no appetite for gates.** Agent-led is not agent-unattended. If plan approval and equivalence sign-off will be rubber-stamped, run the base playbook where human judgment is distributed across every phase boundary instead of concentrated at a few points. *** ## Prerequisites * **The legacy system ingested as a CoreStory project.** Non-negotiable — every deliverable in the arc grounds in it. * **The target ingested as a second CoreStory project — once the target exists.** The dual-project setup is what lets the agent reason across both sides in a single pass. A standing target should be ingested before you begin. A greenfield target *cannot* be, and the method does not ask you to fake it: the arc runs single-project through Steps 1 and 2, and [Step 2B](#step-2b-design-and-bootstrap-the-target-greenfield-only) is where the second project comes online. * **An AI coding agent with CoreStory MCP configured** — see [Supercharging AI Agents](/getting-started/supercharging-ai-agents). * **Direct read access to legacy source** for the agent, not just the intelligence layer. Code intelligence accelerates discovery; source decides truth. The agent must be able to open the file and cite the line. * **A named domain expert** who can validate the behavioral spec. This is a gate, not a courtesy review. * **A test harness in the target** that can run red before it runs green. Test-first is not optional here — it is how the agent proves it understood the requirement before it wrote the code. * **Someone other than the builder available for verification.** Separate session at minimum; separate person preferred. * (Recommended) **A working target build** you can run locally. An agent that cannot compile cannot self-correct, and the velocity argument collapses. *** ## How It Works ### Center of Gravity: Who's Driving This is the distinction that generates everything else, so it's worth stating plainly. The base Code Modernization playbook is **human-led and agnostic about the labor split.** It prescribes *where* decisions happen — the [HITL gates](/playbooks/code-modernization#human-in-the-loop-gates), mandatory expert review on ambiguous findings, one phase per session, "AI informs; architects decide" — but not *how much* the agent does between those gates. A team can run it with heavy manual involvement (people read the code, people decide, the agent advises) or lighter-touch, anywhere along that spectrum. Vibe modernization is **agent-led and human-gated.** It takes the stance the base playbook leaves open: the agent owns the build loop end to end at speed — gap analysis, test-first implementation, verification drafting — and human judgment is **concentrated at a few high-leverage gates** rather than spread across every phase boundary. The whole arc is arranged to keep the agent running flat-out between a small number of decision points. > **Base playbook:** agnostic about who does the work, defaults to human-led. > **Vibe modernization:** opinionated — the agent drives, humans gate. Same rigor, different center of gravity. The obvious objection is that handing the agent the wheel trades away safety. It doesn't — it *relocates* it. When the agent is driving at speed you cannot lean on continuous human review to catch drift, so that job moves to the audit trail and an independent verification pass. **You can let the agent drive precisely because the verification discipline catches what pervasive manual oversight otherwise would.** That is the safety argument, and it is why the disciplines below are non-negotiable in this variant while remaining optional in the base. ### How It Differs from Base Code Modernization One thing determines which you are running: the center of gravity above. So the distinctions below are not capabilities the base playbook *lacks* — they are disciplines this variant makes mandatory, because with the agent driving it cannot fall back on continuous human judgment to catch drift. | # | Discipline | Base playbook | Vibe modernization | | - | ------------------------------ | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | 1 | **Converge, don't port** | Agnostic — a team may port module-by-module or converge, its call | The agent forward-engineers into the target as **one coherent body**. The output reads as though it had always been part of the target, not as a patchwork of per-module ports | | 2 | **Source-grounded validation** | Grounding exists but is risk-based — a human decides how deep to verify each finding | **Every claim is verified against source before it enters a deliverable**, mechanically, with a `file:line` anchor. Not optional, because there is no continuous human review to catch an ungrounded claim in the moment | | 3 | **Anti-circular verification** | Independence comes from human gates and expert review | The Behavioral Equivalence Report **plus** an independent atom-grain conformance audit — because the same agent writes the code, its test, *and* its BER, and those three can share a blind spot | Discipline 3 is the genuinely new idea. It is what stops "vibe" from meaning "unverified." On convergence and the Strangler Fig: the base playbook's [default execution pattern](/playbooks/code-modernization#strangler-fig-default) runs old and new side by side behind a façade. Convergence is not a rejection of that — on a live-production cutover you may still wrap the converged code in a coexistence layer for safe rollback. The invariant is that the *code* is one coherent body rather than a bolted-on port; the façade is a deployment concern and remains available to you. ### Standing vs. Greenfield Target Whether a target architecture already exists is **not** a reason to choose one playbook over the other. It changes only the shape of the front of the arc: * **Standing (brownfield) target** — already exists, partially built, with its own architecture and idioms. You skip target design entirely, reverse-engineer *both* sides, and converge into what's there. This is the path the walkthrough below is written for. * **Greenfield target** — nothing built yet. You fold the base playbook's [Phase 3](/playbooks/code-modernization#phase-3-target-architecture-strategy) back into the arc as [Step 2B](#step-2b-design-and-bootstrap-the-target-greenfield-only) — select the strategy with the 7 Rs, design the target, then bootstrap enough of it to be real — and then proceed unchanged. It sits after Step 2, in base Phase 3's own position, because the design is derived from the legacy assessment and the validated behavioral contract rather than chosen ahead of them. Everything downstream (the grounding, the convergence, the two-check verification) is identical; Step 1 simply keeps the target's emerging structure grounded rather than recovering a structure that already exists. **The one thing greenfield genuinely changes: you start with one CoreStory project, not two.** A repository holding a README and a directory layout has nothing to index, so the second project cannot exist on day one — and an arc that demands it up front will refuse to run. Two consequences worth stating plainly, because they are easy to get wrong: * **Only two of the arc's steps actually need the target project.** Step 1's target half (the idiom catalogue) and Step 4's target half (what already exists, what would break). Step 2 and Step 3 are legacy-only. Step 5 writes code against the working tree. Steps 6a and 6b use *legacy* source as the oracle and read target files directly. So single-project mode is a narrow accommodation at the front of the arc, not a degraded version of the method. * **On the target side, direct file access substitutes cleanly while the target is small.** Code intelligence earns its keep in proportion to how much code there is to reason over; a target you can read end to end does not need an index yet. That is why the front of the arc does not block on target ingestion — there is genuinely nothing to gain from it yet. Reasoning across both a legacy and a target codebase is a net improvement for **any** modernization variant, base included. It is shared ground, not a vibe-mod distinction — it just happens to be indispensable when the agent is the one doing the reasoning. ### CoreStory MCP Tools Used | Tool | Step(s) | Purpose | | ---------------------- | ---------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `list_projects` | 1, 2B | Confirm which projects exist and that ingestion is complete — both legacy and target on a standing target, legacy only until [Step 2B](#step-2b-design-and-bootstrap-the-target-greenfield-only) hands off | | `create_conversation` | 1, 2, 3, 4, 6 | Open a dedicated thread per phase artifact and per work item | | `send_message` | 1, 2, 3, 4, 5, 6 | Query either project for structure, behavior, gap analysis, and verification evidence | | `get_project_techspec` | 1, 4 | Retrieve the target's Tech Spec to ground convergence in its actual structure | | `get_project_prd` | 2, 3 | Retrieve business context for the behavioral contract and the user-story layer | | `list_conversations` | 3, 4, 6 | Locate prior phase threads for cross-reference and provenance citation | | `get_conversation` | 3, 4, 6 | Pull prior findings into the current artifact, with a citable reference | | `rename_conversation` | 6 | Mark completed threads "RESOLVED" once their artifact is signed off | ### The Vibe Modernization Arc > **Note:** The steps below are internal to this playbook. They map onto the [six-phase modernization framework](/playbooks/code-modernization) rather than replacing it — the mapping is in the table under each step heading. 1. **Recover Both Architectures** — reverse-engineer the target's service design and the legacy's structure, so the agent knows where legacy behavior will land. 2. **Extract the Legacy Behavioral Contract** — a source-verified behavioral spec. This is the contract everything downstream verifies against. 2B. **Design and Bootstrap the Target** — *greenfield only; skip entirely when the target already exists.* Select the strategy, design the target against what Steps 1 and 2 established, and build enough of it to ingest. 3. **Author the Backlog and Test Strategy** — the backlog is a deliverable in its own right, authored with the same grounding discipline as the code. 4. **Gap-Analyze Before Writing Code** — per work item, across both projects: what exists in the target, what the legacy requires, what must change. **This is the plan-approval gate.** 5. **Converge Into the Target, Test-First** — Red → Green, in the target's own idiom, emitting provenance as it goes. 6. **Verify Twice** — the Behavioral Equivalence Report *and* an independent conformance audit, both run in sessions separate from the build. A discipline that spans all six: **one session, one artifact of depth.** Do not collapse the arc into a single run. Each step produces one reviewable deliverable and stops at its gate. The speed comes from the agent working without interruption *inside* a step, not from merging steps together. ### Which Playbook Runs Each Step Most of the arc is existing playbooks run with the grounding discipline turned up. Only two things are genuinely new. Step 2B is conditional — it runs only on a greenfield target, and a standing target skips it. It sits after Step 2 rather than at the front because base Phase 3 takes the assessment and the rules inventory as its primary inputs. | Step | Runs on | Status in this variant | | ----------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- | | 1. Recover both architectures | [Codebase Assessment](/playbooks/modernization/codebase-assessment), applied to *both* projects | Inverted — you recover a target rather than design one | | 2. Legacy behavioral contract | [Business Rules Extraction](/playbooks/business-rules-extraction) | Borrowed, hardened — every rule carries a source anchor | | 2B. Design and bootstrap the target | [Target Architecture & Strategy](/playbooks/modernization/target-architecture) | Borrowed — **greenfield only**, base Phase 3 in its base position; skipped outright on a standing target | | 3. Backlog and test strategy | [Decomposition & Sequencing](/playbooks/modernization/decomposition-sequencing) + [Spec-Driven Test Generation](/playbooks/spec-driven-test-generation) | Borrowed, hardened — the backlog is a graded deliverable | | 4. Gap analysis per work item | [Feature Gap Analysis](/playbooks/feature-gap-analysis), run across two projects at once | **Net-new twist** — dual-project, per-ticket, pre-implementation | | 5. Converge into the target | [Feature Implementation](/playbooks/feature-implementation) | Borrowed, hardened — test-first and target-only | | 6a. Behavioral equivalence | [Behavioral Verification](/playbooks/modernization/behavioral-verification) | Borrowed — but run in a separate session from the build | | 6b. Conformance audit | *This playbook* | **Net-new** — the anti-circular check | | 6c. Critical-flow trace | [E2E Test Generation](/playbooks/test-generation/e2e-test-generation) | Borrowed — one headline trace, archived for audit | ### HITL Gates Agent-led is not agent-unattended. This variant trades *many* small review moments for *few* consequential ones — which means the ones that remain carry real weight and cannot be waved through. > **Gate 1 — Spec validation (after Step 2).** A domain expert confirms the legacy behavioral spec. Business rules define "correct"; get them confirmed before anything is built against them. This is the single highest-leverage hour in the engagement. > **Gate 2B — Target design approval (after Step 2B, greenfield only).** A human signs off the target ADR before anything is scaffolded. Inherited from base Phase 3 rather than invented here, and skipped entirely on a standing target — but on greenfield it is the cheapest gate in the arc, because changing your mind about the target costs one document instead of a delivery. It follows Gate 1 deliberately: the design is answerable to a behavioral contract an expert has already confirmed. > **Gate 2 — Plan approval (Step 4, per work item).** The gap-analysis plan is approved by a human *before any code is written*. The agent proposes; a human decides. This is the gate that keeps velocity from becoming drift. > **Gate 3 — Equivalence sign-off (after Step 6).** Sign-off happens only when the BER and the conformance audit **agree**. Disagreement is not an averaging problem — it means one of them is wrong, and you find out which before you sign. A useful check on whether you are running the method honestly: if no gate has ever sent work back, the gates are decorative. *** ## Step-by-Step Walkthrough ### Step 1: Recover Both Architectures *Base framework: Phases 1 and 3, collapsed and inverted.* In the base playbook, Phase 1 assesses the legacy for readiness and Phase 3 designs the target. When the target already exists, those two collapse: there is nothing to design, so instead of *choosing* a target you **recover the one that already exists** — and you understand the legacy well enough to converge onto it. On a greenfield target there is nothing to recover on the target side yet — run this step against the legacy alone, and the target's structure gets *chosen* rather than recovered in [Step 2B](#step-2b-design-and-bootstrap-the-target-greenfield-only). **Confirm what is ingested:** ``` List my CoreStory projects. I need the legacy [SystemName] project, and the target [TargetName] project if it exists. Confirm ingestion status for each. If the target is not there yet, say so rather than assuming it — we may be running single-project until it is. ``` If the target is not ingested — greenfield, or scaffolded but not yet indexed — run this step against the legacy project and recover the target's structure by reading its working tree. Only the retrieval changes; the anchor discipline does not. **Recover the target's service design:** ``` send_message (target project): "Produce a service-oriented design of this system, grounded only in the source: 1. What are the top-level services or modules, and what is each responsible for? 2. How do they communicate — direct calls, messaging, shared database, HTTP? 3. What are the layering conventions? Where do adapters, domain logic, and persistence live? 4. What idioms recur — error handling, logging, configuration, transaction boundaries, test structure? 5. Where are the extension points a new capability would plug into without disturbing existing structure? For each answer, cite the files that establish the pattern." ``` Point 4 is the one people skip, and it is the one convergence depends on. The agent cannot write code that "reads as though it had always been there" unless it has explicitly catalogued what "there" looks like. **Locate where legacy behavior will land:** ``` send_message (target project): "Given a legacy capability that [brief description of the domain area], which existing services or modules in this system are its natural home? 1. What already exists that overlaps with this capability? 2. What would need to be extended versus created new? 3. Which existing tests cover the surrounding behavior? 4. What would a reviewer of this codebase expect a new capability in this area to look like?" ``` **Assess the legacy side:** Run [Codebase Assessment](/playbooks/modernization/codebase-assessment) against the legacy project as written. The output you need from it here is narrower than a full modernization assessment: you are looking for scope boundaries, non-code artifacts that encode business logic, and the dependency edges that will determine sequencing. **What good looks like:** a service design of the target that a new engineer could navigate, and a clear picture of where legacy behavior will land in it. On a brownfield target there is no 7 Rs debate to have — the strategy is fixed by the standing system. *** ### Step 2: Extract the Legacy Behavioral Contract *Base framework: Phase 2 (Business Rules Inventory), carried over almost unchanged.* This is the contract everything downstream verifies against, and it is the one step where you should feel no temptation to move fast. Run [Business Rules Extraction](/playbooks/business-rules-extraction) as written, with one hardening: **every behavior must carry a source anchor.** **Extract with anchors mandatory:** ``` send_message (legacy project): "Extract the business rules implemented in [ModuleName]. For each rule: 1. State the rule in business terms, not code terms 2. Give the exact source location that implements it (file and line range) 3. Note the conditions under which it applies 4. Note what happens at the boundaries — empty, zero, negative, maximum, missing, malformed 5. Flag whether this looks like intended business logic, a workaround, or a defect that has been running in production Do not state a rule you cannot anchor to a specific location." ``` **Verify the anchors before the spec is considered done:** This is the step that separates a grounded spec from a plausible one. Code intelligence is a discovery accelerator; it is not the oracle. ``` For each rule in the extracted inventory, open the cited source location directly and confirm the rule as stated matches what the code does. Where the code and the stated rule disagree, the code wins — correct the rule and note the discrepancy. Produce a list of any rule whose anchor could not be confirmed. Those do not enter the spec until they are resolved. ``` **Record migration intent per rule:** ``` For each confirmed rule, classify the intent for modernization: - PRESERVE — behavior must be identical in the target - MODIFY — behavior changes deliberately; state the new behavior and who approved the change - DISCARD — behavior is obsolete and will not be carried forward; state why This classification is what Step 6 verifies against. ``` > **Gate 1 — Spec validation.** A domain expert confirms the spec before anything is built against it. Bring them the rules that are ambiguous, that look like defects, and that you have classified MODIFY or DISCARD. Do not bring them 400 rules and ask for a blanket approval. **What good looks like:** each behavior stated with its source anchor and a migration intent, so Step 6 has an unambiguous checklist rather than a judgment call. *** ### Step 2B: Design and Bootstrap the Target (Greenfield Only) *Base framework: Phase 3, folded back in — in its base position, after the assessment and the rules.* **Skip this step entirely if the target already exists.** It exists for one situation: you have a legacy system worth modernizing and nothing yet to converge into. **It runs here, not at the front of the arc, and the position is the point.** Base [Phase 3](/playbooks/code-modernization#phase-3-target-architecture-strategy) names two inputs as primary: the Modernization Readiness Report from Phase 1 and the business rules inventory from Phase 2 — because you cannot sensibly decide what a system *should become* before you know what it currently *does*. In this arc those are Step 1 and Step 2. Running target design before them would produce an architecture chosen from general preference rather than from this legacy system's actual coupling, data dependencies, and business rules. So on a greenfield target the front of the arc is unchanged: assess the legacy, extract and validate its behavioral contract, *then* design the thing that has to honor it. Concretely, the ADR you produce here is answerable to artifacts that already exist by the time you start it: * the legacy's coupling hotspots, shared-data dependencies, and modernization blockers, from Step 1 * the behavioral contract a domain expert signed off at Gate 1, including everything classified PRESERVE * the rules classified MODIFY or DISCARD, which are the ones most likely to change the target's shape **Select the strategy and design the target.** Run the [Target Architecture & Strategy](/playbooks/modernization/target-architecture) playbook against the legacy project — the 7 Rs, the target shape, the risk and effort call — citing those inputs. Nothing here differs from the base playbook's Phase 3, so it is not restated. Two vibe-mod overlays on it: * **Record the target's intended idioms in the ADR, not just its structure.** Error handling, logging, configuration, transaction boundaries, naming, test layout. On a standing target Step 1 *recovers* this catalogue from code; here you are choosing it, and Step 5's convergence discipline needs it to exist either way. Choosing it deliberately is the one advantage greenfield has over brownfield — take it. * **Keep decisions and findings distinguishable.** Claims about what the legacy requires of the target carry `file:line` anchors against legacy source. Claims about the target are decisions, not findings — label them as such so the audit trail never confuses a choice with an observation. ⛔ **GATE 2B — target design approval.** A human signs off the ADR before scaffolding. This gate is not new; it is base Phase 3's own gate, and it is the cheapest place in the entire arc to change your mind about the target. **Bootstrap the target to the ingestion threshold.** Now build the smallest thing that is genuinely a system rather than a placeholder: * the build and dependency configuration, working * the layering the ADR chose, as real directories with real module boundaries * the test harness, able to run and able to report a failure * **one working vertical slice** — the thinnest end-to-end path through those layers, with a test that covers it That last item is the one that matters, and the one people skip. A slice proves the layering compiles, runs, and is testable, and it gives the idiom catalogue something concrete to point at. A tree of empty directories proves none of that. A repository containing only a README, or only a directory skeleton, has nothing for CoreStory to index. Ingesting it produces an empty or near-empty project, which is worse than no project at all — the agent will query it, get nothing back, and report "the target has no such capability" for every question you ask. Bootstrap first, then ingest. **Hand off to the standing-target path.** Ingest the scaffolded target as your second CoreStory project. From here the greenfield and standing paths are the same arc: Step 3 sequences work into a target that now exists, and Step 4's gap analysis has two projects to reason across. The target-side idiom catalogue that a standing target gets from Step 1 you already hold — you wrote it into the ADR and then built it. *Base framework mapping: base [Phase 3](/playbooks/code-modernization#phase-3-target-architecture-strategy) run in its base position, plus a bootstrap task the base playbook does not need because it never assumes the target is empty.* *** ### Step 3: Author the Backlog and Test Strategy *Base framework: Phase 4 (Decomposition & Sequencing), carried over and hardened.* The base playbook decomposes and sequences into work packages. Here the **backlog itself is a deliverable**, authored with the same grounding discipline as the code — because the agent will execute against it without a human re-deriving the requirement at each ticket. **Author tickets with dual provenance:** ``` send_message: "For work package [WP-XXX], compose developer-ready tickets. Each ticket must carry: 1. A business-facing statement of what changes and why 2. The specific legacy rules it implements, by rule ID 3. Dual provenance for every factual claim — the CoreStory conversation reference AND the legacy source file:line 4. Acceptance criteria stated so a test can be written from them directly, without interpretation 5. The target location where this will land, from Step 1 6. A decision log entry wherever the spec, the intelligence layer, and the source disagreed — and how it was resolved" ``` **Add the user-story layer:** Between a technical work package and a developer ticket there is a missing middle: a business-facing statement a domain expert can actually review. Without it, spec review degrades into engineers reading tickets to each other. ``` send_message: "For work package [WP-XXX], write the business-facing user stories that sit above these tickets. Each should be reviewable by a domain expert who does not read code: - What business capability does this deliver? - What are the acceptance criteria in business language? - Which legacy rules does it preserve, modify, or discard? - What would a user notice if this were wrong?" ``` **Set the test strategy:** Run [Spec-Driven Test Generation](/playbooks/spec-driven-test-generation) to establish the engagement's test approach before implementation starts, not after. The distribution matters more than the count: characterization tests derived from legacy behavior are the ones that catch parity failures, and they need to exist before the code does. **What good looks like:** every ticket carries dual-provenance anchors and a decision log. A hand-authored backlog drifts in shape and depth across a long engagement; a generated one holds its grain — which is exactly what an agent executing it needs. *** ### Step 4: Gap-Analyze Before Writing Code *Base framework: Phase 5, pre-implementation. This is the net-new twist.* Before any code is written for a work item, run [Feature Gap Analysis](/playbooks/feature-gap-analysis) **across both projects at once**. Standard gap analysis compares two systems' capabilities. Here you are asking a sharper question: *given what the target already has and what the legacy requires, what is the minimum coherent change?* **Run the dual-project gap analysis:** ``` send_message (target project): "For ticket [TICKET-ID], establish what already exists here: 1. What existing services, classes, or functions already do part of this? 2. What existing tests already cover adjacent behavior? 3. What existing data model supports this, and what is missing? 4. What existing configuration or wiring would this plug into? 5. What would break if this were added naively?" ``` ``` send_message (legacy project): "For the same capability, establish what the legacy actually requires: 1. Which rules from the behavioral spec are in scope for this ticket? 2. What edge cases does the legacy handle that a naive implementation would miss? 3. What upstream inputs and downstream consumers does this touch? 4. What non-code artifacts (copybooks, job control, configuration, lookup tables) participate in this behavior?" ``` **Produce the plan:** ``` Synthesize a gap report for [TICKET-ID]: - EXISTS — already present in the target, reusable as-is - EXTEND — present but needs modification; state the modification - NEW — must be built; state where it lands and why there - CONFLICT — the legacy requires something that contradicts a target convention; state both and recommend a resolution Then state the implementation plan: files touched, tests to write first, and the order of work. Anchor every legacy claim to source. ``` The CONFLICT category is the one that earns the gate. Conflicts are where a modernization silently becomes a rewrite, and they are precisely the decisions an agent should not make alone. > **Gate 2 — Plan approval.** A human approves the gap report and the implementation plan before code is written. Read the CONFLICT entries first; they are where the judgment lives. If the plan proposes touching more of the target than the ticket justifies, that is scope drift arriving early, where it is cheap to stop. **What good looks like:** the plan is specific enough that a reviewer disagreeing with it can say exactly which line they disagree with. *** ### Step 5: Converge Into the Target, Test-First *Base framework: Phase 5 (Iterative Execution), carried over and hardened.* This is where "converge, don't port" becomes an execution pattern. The agent forward-engineers directly into the target so the result is one coherent body rather than a patchwork. **Write the failing tests first:** ``` From the acceptance criteria in [TICKET-ID], write the tests before any implementation: 1. One test per acceptance criterion, named for the behavior 2. Characterization tests for each legacy edge case identified in the gap report 3. Follow the target's existing test conventions exactly — structure, naming, fixtures, assertion style Run them. Confirm they fail, and confirm they fail for the right reason. A test that passes before implementation is testing nothing. ``` The "fails for the right reason" check matters more than it sounds. A test that fails because a class does not exist yet is not the same as a test that fails because behavior is wrong, and only the second one is doing work. **Implement to green, in the target's idiom:** ``` Implement [TICKET-ID] to make the failing tests pass. Constraints: - Target project only. Do not modify the legacy system. - Match the target's existing idioms from the Step 1 catalogue — error handling, logging, configuration, transaction boundaries, naming. - No new dependency or pattern unless the gap report approved it. - Stop at the ticket boundary. Anything you notice outside it goes in the notes, not in the diff. ``` **Self-review for convergence:** ``` Review the diff as a reviewer who works on this target system daily and has never seen the legacy system: 1. Would anything here tell you it came from a migration? 2. Does anything introduce a second way of doing something the codebase already does one way? 3. Is there a seam where "the ported code" starts? Convergence means the answer to all three is no. ``` **Emit the provenance entries:** Every non-obvious decision made during implementation gets a Context Inventory entry as it happens — not reconstructed later, when the reasoning has evaporated. See [Output Formats](#output-formats) below. **What good looks like:** acceptance-derived tests written and confirmed failing first, then coded to green; and new code that is indistinguishable from the target's existing style, with no seam where the migration starts. *** ### Step 6: Verify Twice *Base framework: Phase 6 (Behavioral Verification), carried over and deepened.* The base playbook signs off on a Behavioral Equivalence Report. Here that is the **first** of two independent checks — because the same agent that wrote the feature also wrote its tests and would write its BER, and those three can share a blind spot and rubber-stamp a half-build. > **Run both checks in sessions separate from the build.** Not a fresh prompt in the same session — a separate session, ideally driven by a different person. Session independence is the mechanism; everything else here is bookkeeping. **6a — Behavioral Equivalence Report.** Run [Behavioral Verification](/playbooks/modernization/behavioral-verification) as written. Each rule from the Step 2 spec is classified **Preserved / Modified / Discarded / Missing**, traced to its implementation in the target. **6b — Conformance audit.** This is the net-new check, and it is deliberately narrow: read-only, atom-grain, with legacy source as the only oracle. It does not read the BER, and it does not trust the tests. ``` Audit the delivered implementation for [scope] against the legacy source directly. Do not read the Behavioral Equivalence Report and do not treat passing tests as evidence. For each atom of required behavior in the spec, assign exactly one verdict: - DELIVERED — implemented and matches legacy behavior - STUBBED — code exists at this location but does not do the work (returns a constant, logs and exits, TODO, empty branch) - MISSING — no implementation exists - DIVERGES — implemented but behaves differently from the legacy; state both behaviors - UNVERIFIABLE — cannot be confirmed from source alone; state what would be needed Cite the target file:line and the legacy file:line for every verdict. ``` **The orphan sweep** is the other half of the audit, and it catches a different failure — behavior the spec never captured at all: ``` Now sweep in the opposite direction. Read the legacy source for [scope] and list behaviors that appear in the legacy but do not appear anywhere in the behavioral spec. For each: state the behavior, its source anchor, and whether its absence from the spec looks deliberate or like an omission. ``` STUBBED and the orphan sweep are where this audit earns its place. Green tests and a confident "Preserved" tell you the code does what the spec said; only an independent read against source tells you whether the spec was complete and whether the code actually does the work. **6c — Critical-flow trace.** One headline end-to-end flow, traced and archived. Run [E2E Test Generation](/playbooks/test-generation/e2e-test-generation) and pick the flow whose failure would be most expensive — not the one that is easiest to instrument. Archive the trace as evidence, not just the pass result. > **Gate 3 — Equivalence sign-off.** Sign off only when the BER and the conformance audit agree. Where they disagree, resolve against legacy source before signing. A BER that says Preserved and an audit that says STUBBED is not a scoring discrepancy — it is the method working. **What good looks like:** the conformance audit finds something the tests and the BER both waved through. In the field application that produced this variant, it surfaced a regressed re-import path that had a green test suite and a clean equivalence report over it. That single catch is the argument for the whole step. *** ## The Two Disciplines That Make "Vibe" Safe Velocity is the easy half. These two are what let you claim the audit trail — call them out explicitly when teaching the method, because they are what people drop first under schedule pressure. **1. Source-grounded validation.** Intelligence accelerates discovery; **source decides truth.** No claim — about legacy behavior, target structure, or a proposed change — enters a deliverable until it has been checked against the actual code and given a `file:line` anchor. This is ordinary good hygiene rather than a special mechanism, and it is what makes the velocity honest: you move fast *because* the grounding is cheap, not by skipping it. The practical test: pick any sentence in any deliverable and ask what it is anchored to. If the answer is "the agent said so," it is not grounded, however plausible it reads. **2. Anti-circular verification.** The same agent that writes a feature also tends to write its test and its equivalence report, so all three can share the same blind spot. The conformance audit breaks the circle: atom grain, independently, with legacy source as the only oracle, run in a session separate from the build. This is the method's original contribution and the reason "vibe" here does not mean "unverified." The practical test: could the verification pass have been written by someone who never saw the implementation session? If not, it is not independent. *** ## Output Formats Each artifact below is a gate input. A unit of work is not done until its artifacts exist. ### Gap Report (per work item, Step 4) ```markdown theme={null} # Gap Report: [TICKET-ID] — [Capability] ## Scope Legacy rules in scope: [BR-012, BR-013, BR-027] Target landing zone: [service/module, from Step 1] ## Findings | ID | Classification | Detail | Legacy anchor | Target anchor | |----|---------------|--------|---------------|---------------| | G-1 | EXISTS | Validation already implemented | `PGM01:L440-472` | `OrderValidator.java:88` | | G-2 | EXTEND | Needs the negative-quantity branch | `PGM01:L510-533` | `OrderValidator.java:120` | | G-3 | NEW | No equivalent exists | `PGM02:L88-140` | *(new)* `ReimportHandler.java` | | G-4 | CONFLICT | Legacy allows a state the target's model forbids | `PGM02:L201` | `OrderState.java:34` | ## Conflicts requiring decision **G-4** — [statement of both behaviors, recommended resolution, and what is lost either way] ## Implementation plan 1. Tests to write first: [list, one per acceptance criterion] 2. Files touched: [list] 3. Order of work: [sequence] ## Approval Approved by: __________ Date: __________ ``` ### Conformance Ledger (Step 6b) ```markdown theme={null} # Conformance Audit: [Scope] Oracle: legacy source only. BER not read. Tests not treated as evidence. ## Verdicts | Atom | Verdict | Target anchor | Legacy anchor | Note | |------|---------|---------------|---------------|------| | A-01 | DELIVERED | `Handler.java:142` | `PGM01:L440` | — | | A-02 | STUBBED | `Handler.java:210` | `PGM01:L512` | Returns constant; no branch logic | | A-03 | DIVERGES | `Mapper.java:77` | `PGM02:L88` | Legacy rounds half-up; target rounds half-even | | A-04 | UNVERIFIABLE | — | `PGM03:L44` | Behavior depends on runtime configuration | ## Orphan sweep Legacy behaviors absent from the spec: | Behavior | Legacy anchor | Assessment | |----------|---------------|------------| | Retry on downstream timeout | `PGM02:L320-355` | Omission — not deliberate | ## Disagreement with the BER [Any atom where this audit and the BER reach different conclusions, and the source evidence that resolves it] ``` ### Context Inventory (running, all steps) The provenance ledger. One entry per non-obvious decision, written when the decision is made. ```markdown theme={null} # Context Inventory: [Engagement/Component] | # | Decision or claim | Source of the claim | How it was validated | Anchor | Outcome | |---|-------------------|--------------------|--------------------|--------|---------| | 1 | Quantity validation rejects zero | CoreStory conv. `abc-123` | Opened source; confirmed | `PGM01:L448` | Confirmed as stated | | 2 | Rounding is half-up | CoreStory conv. `abc-123` | Opened source; contradicted | `PGM02:L88` | **Corrected** — source shows half-even | | 3 | Re-import path is unused | Assumption during planning | Orphan sweep, Step 6b | `PGM02:L320` | **Corrected** — path is live | ``` Entry 2 is the shape that matters. The value of this ledger is not that it records what was right — it is that it records what was *corrected*, and against what. That is the difference between an audit trail and a changelog. *** ## Prompting Patterns Reference ### Grounding Patterns | Pattern | Example | | ------------------------ | --------------------------------------------------------------------------------------------------------------- | | **Anchor demand** | "Do not state a rule you cannot anchor to a specific file and line range." | | **Source arbitration** | "Open the cited location directly and confirm. Where the code and the stated behavior disagree, the code wins." | | **Unverified surfacing** | "List every claim in this artifact whose anchor could not be confirmed. Those do not enter the deliverable." | | **Non-code artifacts** | "What copybooks, job control, configuration, or lookup tables participate in this behavior?" | ### Convergence Patterns | Pattern | Example | | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | **Idiom catalogue** | "What idioms recur in this codebase — error handling, logging, configuration, transaction boundaries, test structure? Cite the files that establish each pattern." | | **Landing zone** | "Which existing services are the natural home for this capability, and what would a reviewer of this codebase expect it to look like?" | | **Seam check** | "Review this diff as someone who works on this system daily and has never seen the legacy. Would anything tell you it came from a migration?" | | **Duplication check** | "Does this introduce a second way of doing something the codebase already does one way?" | ### Dual-Project Gap Patterns | Pattern | Example | | -------------------------- | --------------------------------------------------------------------------------------------------------------------------- | | **Exists-first** | "Before proposing anything new: what already exists here that does part of this?" | | **Requirement extraction** | "Which rules from the behavioral spec are in scope for this ticket, and what edge cases would a naive implementation miss?" | | **Conflict surfacing** | "Where does the legacy require something that contradicts a target convention? State both and recommend a resolution." | | **Blast radius** | "What would break if this were added naively?" | ### Anti-Circular Verification Patterns | Pattern | Example | | ------------------------ | ---------------------------------------------------------------------------------------------------------------------------------- | | **Oracle restriction** | "Audit against legacy source only. Do not read the equivalence report. Do not treat passing tests as evidence." | | **Stub detection** | "Does code exist at this location that does not do the work — returns a constant, logs and exits, empty branch, TODO?" | | **Orphan sweep** | "List behaviors in the legacy source that do not appear anywhere in the behavioral spec." | | **Disagreement forcing** | "Where does this audit reach a different conclusion from the equivalence report? Resolve against source and state which is wrong." | *** ## Best Practices **One session, one artifact of depth.** The temptation with an agent this fast is to run the whole arc in one sitting. Don't. Each step produces one reviewable deliverable and stops at its gate. The velocity comes from the agent working uninterrupted *inside* a step, not from merging steps together — and a merged arc produces artifacts nobody can review, which defeats the point. **Humans decide, agents inform.** The plan approval and the spec validation are not rubber stamps. The method's speed makes waving them through feel efficient; it is the single most reliable way to end up with a fast, confident, wrong result. **Budget review attention for convergence.** "Reads as one coherent body" is not automatable. It is a judgment about whether the new code genuinely matches the target's idioms, and it needs a human who knows the target to make it. Schedule that attention explicitly rather than hoping it happens. **Keep the verifier independent.** If the session that wrote the code also runs the BER and the audit, you have re-created the circularity the method exists to break. Separate sessions at minimum; separate people where you can. This is the one shortcut that silently invalidates everything else. **Watch the parity ratio.** Track deliberately-modified and net-new behavior against preserved behavior. Modernization becomes rewrite one "while we're in here" at a time, and the ratio climbing is the earliest signal you are drifting off-method — well before anyone would describe what is happening as a rewrite. **Ship the artifacts with the code.** A unit of work is not done until its gap report, its tests, its BER, its conformance verdicts, and its Context Inventory entries exist. Build fast to hit a demo if you must, but the artifacts are the line between a modernization and a plausible-looking rewrite. **Record corrections, not just conclusions.** When the intelligence layer says one thing and source says another, that correction is the most valuable entry in the Context Inventory. It is the evidence that the grounding discipline is actually running rather than being asserted. **Do not let the tests become the oracle.** Tests written by the same agent from the same understanding will agree with the implementation. They prove internal consistency, not equivalence. Only legacy source settles equivalence. *** ## 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: | Harness | Install location | | --------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Claude Code** | `.claude/skills//SKILL.md` — Claude loads the body when the YAML `description` matches the task | | **GitHub Copilot** | Append to `.github/copilot-instructions.md` for repo-wide instructions, or save as `.github/instructions/.instructions.md` with an `applyTo` glob for path-scoped use | | **Cursor** | `.cursor/rules/.mdc` with a `description` field for auto-attach (use `globs` for path-scoped or `alwaysApply: true` for every session) | | **Factory.ai** | `.factory/droids/.md` (project) or `~/.factory/droids/.md` (personal); Factory loads it as a custom Droid | | **Aider** | `CONVENTIONS.md` at repo root, loaded with `aider --read CONVENTIONS.md` — or add it to the `read:` list in `.aider.conf.yml` for automatic loading | | **Codex / `AGENTS.md` harnesses** | Append the content to `AGENTS.md` at your repository root | | **Custom runtime** | Load the markdown into your agent's system prompt, rules file, or wherever it consumes workflow context | Want a single install that works across the most harnesses? Append the content to `AGENTS.md` at your repository root. The [`AGENTS.md` spec](https://agents.md/) 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. This variant installs as **two** skills, mirroring the base framework's architecture: * **`vibe-modernization`** — a router and sequencer. It holds no execution detail. It decides which step is active, delegates to that step's dedicated skill, and imposes this variant's disciplines on whatever it delegates to. Seven of the eight steps run on skills that already exist — the ones from the playbooks in [Which Playbook Runs Each Step](#which-playbook-runs-each-step). * **`vibe-conformance-audit`** — the one step with no existing skill anywhere. It is the method's original contribution, and it carries the session-independence rule that a router cannot enforce on its own behalf. The router is deliberately thin. A single skill containing all six steps would hand the agent the whole arc at once, which is precisely the "collapse the arc into one run" failure the method warns against — the artifacts are only reviewable if they arrive one at a time. The accordions below walk through end-to-end setup for the four most common harnesses. If you're on a different harness, copy the skill content from any accordion and install it per the conventions above. #### Setup 1. **Configure the CoreStory MCP server** in your Claude Code settings (see [CoreStory MCP Server Setup Guide](/getting-started/mcp-server-setup)). The legacy project must be ingested. Ingest the target too if it already exists — if it does not, the arc starts with one project and [Step 2B](#step-2b-design-and-bootstrap-the-target-greenfield-only) builds it once the legacy contract is validated. 2. **Install the step skills you don't already have.** The router delegates to the skills from [Target Architecture & Strategy](/playbooks/modernization/target-architecture) (greenfield targets only), [Codebase Assessment](/playbooks/modernization/codebase-assessment), [Business Rules Extraction](/playbooks/business-rules-extraction), [Decomposition & Sequencing](/playbooks/modernization/decomposition-sequencing), [Spec-Driven Test Generation](/playbooks/spec-driven-test-generation), [Feature Gap Analysis](/playbooks/feature-gap-analysis), [Feature Implementation](/playbooks/feature-implementation), [Behavioral Verification](/playbooks/modernization/behavioral-verification), and [E2E Test Generation](/playbooks/test-generation/e2e-test-generation). Install each from its own page. 3. **Add this variant's two skills:** ```bash theme={null} mkdir -p .claude/skills/vibe-modernization mkdir -p .claude/skills/vibe-conformance-audit ``` Create `.claude/skills/vibe-modernization/SKILL.md` and `.claude/skills/vibe-conformance-audit/SKILL.md` with the content below. 4. **Commit to version control:** ```bash theme={null} git add .claude/skills/ git commit -m "Add CoreStory vibe modernization skills" ``` #### Usage ``` Start the vibe modernization arc for [SystemName] Where are we in the arc? Design and bootstrap the target for [SystemName] (greenfield, after step 2) Gap-analyze [TICKET-ID] across both projects Run the conformance audit for [scope] ``` #### Tips * The router will stop at the end of every step. That is the design, not a stall — approve and start a new session for the next one. * Run Step 6 in a **different session** from Step 5. The router refuses to verify a build performed in its own session; do not talk it out of that. * If the target does not exist yet, say so in your first message. The router will run Steps 1 and 2 legacy-only and design the target at Step 2B, rather than asking for a second project it cannot have. * Keep each SKILL.md under 500 lines for reliable loading. #### Router Skill File Save as `.claude/skills/vibe-modernization/SKILL.md`: ```markdown theme={null} --- name: CoreStory Vibe Modernization description: Orchestrates agent-led, human-gated modernization from a legacy system into a target that may already exist or may be built from scratch. Routes to the dedicated skill for each step, enforces one step per session, and imposes source-grounding and verification-independence disciplines on every delegated skill. Activates on forward-engineering legacy behavior into a target, dual-project gap analysis, conformance audit, or behavioral-parity requests. --- # CoreStory Vibe Modernization — Variant Orchestrator **This skill is a router and sequencer. It does NOT contain execution instructions for any step.** Determine which step the user needs, activate that step's dedicated skill, and impose the disciplines below on it. This router differs from the base modernization orchestrator in one way: it does not only sequence, it **constrains**. The disciplines below apply to every skill you delegate to and override that skill's defaults where they conflict. ## Critical Rules 1. **Execute exactly one step per session.** Never run multiple steps in one pass. The arc's artifacts are only reviewable if they arrive one at a time. 2. **Always use the dedicated skill.** The summaries below are for orientation only — they do not contain enough detail to execute a step correctly. 3. **After completing a step, STOP.** Present the deliverable and wait for explicit approval before offering to advance. 4. **Never verify a build you performed.** If asked to run Step 6 in the session that ran Step 5, decline and ask for a fresh session. Independence is the mechanism, not a formality. 5. **A missing target project is never a reason to refuse.** Only Step 1's target half and Step 4's target half need it. If the target does not exist yet, start at Step 1 anyway and run Step 2B when you reach it. If it exists but is not ingested, run single-project mode (below). Never tell the user the arc requires two projects before it can start, and never jump ahead to Step 2B to manufacture one — it depends on Steps 1 and 2. ## Always-On Disciplines Apply these to every delegated skill, whatever that skill's own defaults are: - **Source decides truth.** Code intelligence accelerates discovery; it does not settle facts. No claim enters a deliverable without a confirmed `file:line` anchor. Where intelligence and source disagree, source wins. - **Record corrections.** Every claim that moved between the intelligence layer and source gets a Context Inventory entry with both versions. The corrections are the audit trail's most valuable rows. - **Target only.** Never modify the legacy system, in any step. - **Escalate conflicts.** Where the legacy requires something that contradicts a target convention, stop and surface it. Never resolve a legacy-versus-target contradiction unilaterally. ## Prerequisites **Required:** - The legacy system ingested as a CoreStory project - Direct read access to legacy source, not just the intelligence layer - A domain expert available for the spec-validation gate **Required only from Step 1 onward:** - The target ingested as a second CoreStory project. Needed from Step 3 onward. If the target does not exist yet, Step 2B produces it. Do not treat its absence as a blocker at the start of the arc — Steps 1 and 2 are legacy-only either way. **If you do not detect that you have access to CoreStory (e.g., `list_projects` fails or is unavailable), ask the user to verify that their MCP or API connection is properly configured and that the legacy repository has been ingested. If the user has not yet created a CoreStory account, direct them to create one and upload their repo at [app.corestory.ai](https://app.corestory.ai).** ## Single-Project Mode When the legacy project is ingested but the target is not — because the target is greenfield, or scaffolded but not yet indexed — do not stop. Run the arc with these substitutions and say plainly, once, which mode you are in: - **Target-side queries become direct file reads.** Read the target working tree instead of querying a target project. You already have read access; this is the same evidence, gathered differently. On a small target it is not a downgrade — there is little enough code that an index adds nothing. - **Legacy-side queries are unchanged.** Everything the arc grounds in still comes from the legacy project and legacy source. - **Steps 2 and 3 are unaffected.** They are legacy-only, and run identically in either mode. - **Every target-side claim still needs a `file:line` anchor.** From the working tree rather than from intelligence. The discipline does not relax because the tooling changed. - **Exit the mode as soon as the target is ingestable.** Once the target has real code, tell the user to ingest it and switch back. Single-project mode is a starting accommodation, not a way to run the whole arc. ## Step Detection Before doing anything, determine where the user is: 1. **Establish whether the target exists.** Call `list_projects` and ask the user directly. Three cases: - **Target exists and is ingested** → standing target. Start at Step 1; never run Step 2B. - **Target repo exists but has little or no code** (a README, a bare directory skeleton) → greenfield. Still start at Step 1, legacy-only, and run Step 2B after Step 2. Do not ingest the empty repo — an empty project answers every question with "not present" and will corrupt the gap analysis. - **Target exists with real code but is not ingested** → ask the user to ingest it. If they would rather not yet, run single-project mode from Step 1. 2. **Ask the user** which step they want, OR 3. **Check CoreStory conversations** (`list_conversations`) for completed markers: - "RESOLVED - [Recovery]..." → Step 1 complete - "RESOLVED - [Contract]..." → Step 2 complete - "RESOLVED - [Target]..." → Step 2B complete (greenfield only) - "RESOLVED - [Backlog]..." → Step 3 complete - Active "[Gap]..." → Step 4 in progress - Active "[Build]..." → Step 5 in progress - Active "[Verify]..." → Step 6 in progress 4. **If no prior work exists**, start at Step 1 — on a greenfield target too. Greenfield changes where Step 2B appears, not where the arc begins. Once you know the step, read and follow its dedicated skill completely. ## Step 1: Recover Both Architectures Dedicated skill: `codebase-assessment` — run against **both** projects where both are ingested; in single-project mode, run it against the legacy project and recover the target's structure by reading its working tree. Overlay: on the target, produce an explicit catalogue of its idioms (error handling, logging, configuration, transaction boundaries, naming, test structure) with the files that establish each. Convergence in Step 5 depends on this artifact existing. ⛔ GATE: shared understanding of both architectures before any code moves. ## Step 2: Legacy Behavioral Contract Dedicated skill: `business-rules-extraction`. Overlay: every rule carries a source anchor, and every anchor is opened and confirmed before the spec is considered done. Classify migration intent PRESERVE / MODIFY / DISCARD. ⛔ GATE 1: a domain expert validates the spec. Bring them the ambiguous rules and everything classified MODIFY or DISCARD — not a blanket approval request. ## Step 2B: Design and Bootstrap the Target (greenfield only) **Skip entirely when the target already exists.** Runs after Step 2, never before Step 1. Dedicated skill: `target-architecture`. Required inputs, both of which exist by now: Step 1's legacy assessment (coupling hotspots, shared-data dependencies, blockers) and Step 2's expert-validated behavioral contract. `target-architecture` names those as its primary inputs, so do not run this step earlier in the arc — a target designed before you know what the legacy does is a preference, not a decision. Terminology warning: that skill uses "target project" to mean *the CoreStory project being analyzed* — which here is the **legacy** project. In this arc "target" means the system being built. Do not conflate them; run `target-architecture` against the legacy project to produce a design for the new system. Overlay: record the target's intended idioms in the ADR (error handling, logging, configuration, transaction boundaries, naming, test structure) — Step 1 recovers this catalogue from code on a standing target, so on greenfield you must choose it deliberately. Cite the legacy inputs above for every shape-driving decision. Label target-side statements as decisions, not findings; only legacy-side claims carry `file:line` anchors. ⛔ GATE 2B: a human approves the target ADR before anything is scaffolded. Then bootstrap to the ingestion threshold: working build configuration, the chosen layering as real modules, a test harness that can report a failure, and one working end-to-end vertical slice with a test. A directory skeleton is not enough — CoreStory needs real code to index. Finally, have the user ingest the scaffolded target as the second project, and stop. Step 3 runs in a new session. ## Step 3: Backlog and Test Strategy Dedicated skills: `decomposition-sequencing`, then `spec-driven-test-generation`. Overlay: tickets carry dual provenance (conversation reference AND source anchor) plus a decision log. Add the business-facing user-story layer above the tickets. ⛔ GATE: spec review of the user-story layer before tickets go to execution. ## Step 4: Dual-Project Gap Analysis Dedicated skill: `feature-gap-analysis`, with this variant's overlay. Overlay: run it across **both** projects for a single ticket, before any code. Query the target for what already exists and what would break; query the legacy for rules in scope, edge cases, and participating non-code artifacts. In single-project mode, replace the target-side queries with direct reads of the target working tree — the classification and the anchors are the same, only the retrieval differs. Classify every requirement EXISTS / EXTEND / NEW / CONFLICT, and produce the implementation plan (files touched, tests to write first, order of work). ⛔ GATE 2: a human approves the plan before any code is written. Present CONFLICT entries first — that is where the judgment lives. ## Step 5: Converge Into the Target Dedicated skill: `feature-implementation`. Overlay: tests first, confirmed failing for the right reason, before implementation. Match the target's idioms from Step 1's catalogue. No new dependency or pattern unless the gap report approved it. Stop at the ticket boundary. Run the seam check on the diff before presenting it. ⛔ GATE: convergence review by someone who knows the target. ## Step 6a: Behavioral Equivalence Dedicated skill: `behavioral-verification` — **in a session separate from Step 5**. Produces the BER: each rule Preserved / Modified / Discarded / Missing. ## Step 6b: Conformance Audit Dedicated skill: `vibe-conformance-audit` — this variant's own skill, also in a separate session. Produces the conformance ledger and the orphan sweep. ## Step 6c: Critical-Flow Trace Dedicated skill: `e2e-test-generation` — one headline flow, archived as evidence. ⛔ GATE 3: equivalence sign-off, only once the BER and the conformance audit agree. ## Error Handling - **Only one CoreStory project exists:** do not refuse. Establish whether the target is greenfield (→ start at Step 1, run Step 2B after Step 2) or merely un-ingested (→ single-project mode). The arc has a defined path for both. - **Target repo is too small to ingest, or ingests empty:** expected on greenfield. Do not retry the ingestion and do not query the empty project — bootstrap the target in Step 2B, then ingest. - **Target index looks out of date:** likely, on a greenfield target that is changing shape. Re-ingest when the target's structure changes (a new module, layer, or integration point) rather than per commit, and settle anything structural from the working tree in the meantime. - **User asks to design the target before the legacy is assessed:** explain the ordering rather than complying. Step 2B consumes Step 1's assessment and Step 2's validated contract; run ahead of them it yields an architecture chosen from general preference rather than from this legacy system. Offer to start at Step 1. - **User wants to run several steps at once:** explain that each step produces one reviewable artifact and stops at its gate. Offer to start the earliest incomplete step. - **User unsure which step they're in:** check conversations for the markers above. - **Step skill not installed:** direct the user to that step's playbook page on [docs.corestory.ai](https://docs.corestory.ai/playbooks/modernization/vibe-modernization) for setup. - **Asked to verify code written in this session:** decline and ask for a separate session. - **Anchor cannot be confirmed:** the claim does not enter the deliverable. List it as unresolved rather than softening the wording. - **Legacy uses non-code artifacts:** explicitly ask about copybooks, job control, configuration, and lookup tables — they carry business logic that never appears in application code. ``` #### Conformance Audit Skill File Save as `.claude/skills/vibe-conformance-audit/SKILL.md`: ```markdown theme={null} --- name: CoreStory Vibe Conformance Audit description: Independent, atom-grain audit of delivered modernization code against legacy source, using legacy source as the only oracle. Ignores the equivalence report and does not treat passing tests as evidence. Activates on conformance audit, anti-circular verification, "did we actually build everything", or stub-detection requests. --- # CoreStory Vibe Conformance Audit The anti-circular check. The same agent that writes a feature also writes its tests and would write its equivalence report, so all three can share one blind spot and rubber-stamp a half-build. This audit breaks that circle. ## Refuse-to-run condition **If this session wrote the code under audit, stop.** Say so plainly and ask the user for a fresh session, ideally driven by someone else. Session independence is the entire mechanism — an audit run in the build session verifies the same understanding that produced the build, and is worth nothing. Do not proceed because the user says it is fine. ## Activation Triggers - "Run the conformance audit for [scope]" - "Did we actually build everything the spec requires?" - "Find stubs or half-implementations" - Any anti-circular verification or completeness-against-spec request ## Oracle Rules 1. **Legacy source is the only oracle.** Not the spec, not the tests, not the BER. 2. **Do not read the Behavioral Equivalence Report** before forming your verdicts. If you have already seen it, say so — your independence is compromised and the user should know. 3. **Passing tests are not evidence.** Tests written from the same understanding as the implementation agree with it by construction. They demonstrate internal consistency, not equivalence. 4. **Read-only.** Never modify code during an audit. **If you do not detect that you have access to CoreStory (e.g., `list_projects` fails or is unavailable), ask the user to verify that their MCP or API connection is properly configured and that both repositories have been ingested. If the user has not yet created a CoreStory account, direct them to create one and upload their repos at [app.corestory.ai](https://app.corestory.ai).** ## Step 1: Establish the atom list Decompose the in-scope spec into atoms — the smallest units of required behavior that can independently be present, absent, or wrong. A rule with three conditional branches is three atoms, not one. Grain is what makes this audit catch things a component-level check misses. ## Step 2: Verdict each atom Assign exactly one verdict per atom, citing **both** the target `file:line` and the legacy `file:line`: - **DELIVERED** — implemented, and behavior matches the legacy - **STUBBED** — code exists at the location but does not do the work: returns a constant, logs and exits, empty branch, TODO, unconditional success - **MISSING** — no implementation exists - **DIVERGES** — implemented but behaves differently; state both behaviors explicitly - **UNVERIFIABLE** — cannot be settled from source alone; state what would be needed Never soften a verdict because the code looks reasonable. STUBBED is the verdict that justifies this audit's existence — it is what green tests and a confident equivalence report most reliably miss. ## Step 3: Orphan sweep Now read in the opposite direction. Read the legacy source for the scope and list behaviors that appear there but nowhere in the behavioral spec. For each: the behavior, its source anchor, and whether the omission looks deliberate or accidental. This is the only check in the arc that can catch a rule nobody ever wrote down. Everything else verifies against the spec and is blind to the spec's own gaps. ## Step 4: Reconcile with the BER Only now, read the Behavioral Equivalence Report. For every atom where the two disagree, resolve against legacy source and state which artifact is wrong. Do not average, do not split the difference, and do not defer to the BER because it was written first. A BER that says Preserved over an atom you verdicted STUBBED is not a scoring discrepancy — it is the finding. ## Output The conformance ledger: the verdict table, the orphan sweep, and the disagreement section. Add a Context Inventory entry for every correction the audit forces. ## Error Handling - **Scope too large to audit at atom grain:** narrow to one component and say what was left uncovered. Never silently sample — an audit that quietly covered half reads as an audit that covered everything. - **Spec atom has no corresponding legacy behavior:** that is a spec defect. Flag it; it is the inverse of an orphan. - **Cannot locate the legacy implementation:** UNVERIFIABLE, with a note on what was searched. Do not infer from the target's implementation what the legacy must have done — that is the circularity, running backwards. ``` Create `.github/skills/vibe-modernization/SKILL.md`: ```yaml theme={null} --- name: vibe-modernization description: "Orchestrate agent-led, human-gated modernization across a legacy and a target project. Routes to the dedicated skill for each step and imposes source-grounding and verification-independence disciplines on every delegated skill." --- ``` ```markdown theme={null} # Vibe Modernization Skill — Variant Orchestrator This skill is a router. It determines which step is active and delegates to that step's dedicated skill. Do NOT execute step procedures from this file. **Rules:** One step per session. Always use the dedicated skill. STOP after each step and wait for approval. Never verify a build performed in this session. Never refuse to start because only one CoreStory project exists. **Always-on disciplines, applied to every delegated skill:** source decides truth (no claim without a confirmed file:line anchor; source wins over intelligence); record corrections in the Context Inventory; modify the target only; escalate legacy-versus-target conflicts rather than resolving them. **If you do not detect that you have access to CoreStory (e.g., `list_projects` fails or is unavailable), ask the user to verify that their MCP or API connection is properly configured and that the legacy repository has been ingested. If the user has not yet created a CoreStory account, direct them to create one and upload their repo at [app.corestory.ai](https://app.corestory.ai).** **Single-project mode:** if the target is not ingested — greenfield, or scaffolded but not indexed — run the arc anyway, reading the target working tree in place of target-side queries. Every target claim still carries a `file:line` anchor. Exit the mode once the target is ingestable. Only Step 1's and Step 4's target halves need the second project at all. Start at Step 1 regardless; greenfield changes where Step 2B falls, not where the arc begins. ## Step 1: Recover Both Architectures Dedicated skill: `codebase-assessment`, run against BOTH projects where both are ingested; legacy project plus direct reads of the target tree otherwise. Overlay: catalogue the target's idioms explicitly. ⛔ GATE: shared understanding of both architectures before code moves. ## Step 2: Legacy Behavioral Contract Dedicated skill: `business-rules-extraction`. Overlay: mandatory source anchor per rule, each one opened and confirmed; intent tagged PRESERVE / MODIFY / DISCARD. ⛔ GATE 1: domain expert validates the spec. ## Step 2B: Design and Bootstrap the Target (greenfield only) Skip entirely if the target exists. Runs HERE, after Step 2 — never at the front of the arc. Dedicated skill: `target-architecture`, run against the legacy project, taking Step 1's assessment and Step 2's validated contract as its inputs; those are what make the design a decision rather than a preference. Overlay: record the target's intended idioms in the ADR; target statements are decisions, not anchored findings. ⛔ GATE 2B: human approves the ADR. Then scaffold to the ingestion threshold — working build, real layering, a test harness, one end-to-end vertical slice with a test — and have the user ingest it as the second project. A directory skeleton has nothing to index. ## Step 3: Backlog and Test Strategy Dedicated skills: `decomposition-sequencing`, then `spec-driven-test-generation`. Overlay: dual provenance per ticket; add the business-facing user-story layer. ⛔ GATE: spec review before tickets go to execution. ## Step 4: Dual-Project Gap Analysis Dedicated skill: `feature-gap-analysis`. Overlay: run across BOTH projects for one ticket, before any code; classify EXISTS / EXTEND / NEW / CONFLICT. ⛔ GATE 2: human approves the plan before any code is written. ## Step 5: Converge Into the Target Dedicated skill: `feature-implementation`. Overlay: tests first and confirmed failing; match the target's idioms; stop at the ticket boundary. ⛔ GATE: convergence review by someone who knows the target. ## Step 6: Verify Twice Dedicated skills: `behavioral-verification`, then `vibe-conformance-audit`, then `e2e-test-generation`. All in sessions separate from Step 5. ⛔ GATE 3: sign off only when the BER and the conformance audit agree. Key principle: the agent drives, humans gate — and the verifier is never the builder. ``` Install the conformance audit as a second skill at `.github/skills/vibe-conformance-audit/SKILL.md`, using the content from the Claude Code accordion. Create `.cursor/rules/vibe-modernization.mdc`: ```markdown theme={null} --- description: CoreStory-powered agent-led modernization across a legacy and target project. Routes to the dedicated skill for each step of the arc. Activates for forward-engineering legacy behavior, dual-project gap analysis, conformance audit, or behavioral parity work. alwaysApply: false --- # CoreStory Vibe Modernization — Variant Orchestrator You are a modernization engineer with access to CoreStory's code intelligence via MCP, working across a legacy project and a target project. The target may not exist or may not be ingested yet — that is a supported starting state, not a blocker. **This rule is a router. It does NOT contain execution detail for any step.** Identify the active step, follow that step's dedicated rule, and impose the disciplines below on it. **If you do not detect that you have access to CoreStory (e.g., `list_projects` fails or is unavailable), ask the user to verify that their MCP or API connection is properly configured and that the legacy repository has been ingested. If the user has not yet created a CoreStory account, direct them to create one and upload their repo at [app.corestory.ai](https://app.corestory.ai).** ## Critical rules - One step per session; STOP at each gate and wait for approval - Always follow the dedicated rule for the active step - Never verify a build performed in this same session - Never refuse to start because only one CoreStory project exists — every run starts at Step 1; a greenfield target designs its target at Step 2B, an un-ingested one runs in single-project mode ## Always-on disciplines (override the delegated rule's defaults) - Source decides truth; no claim without a confirmed `file:line` anchor - Record every correction in the Context Inventory, with both versions - Modify the target only - Escalate legacy-versus-target conflicts; never resolve them unilaterally ## Step map | Step | Dedicated rule | Overlay | Gate | |---|---|---|---| | 1. Recover both architectures | `codebase-assessment` (both projects; legacy + direct target reads in single-project mode) | Catalogue the target's idioms | Shared understanding | | 2. Legacy behavioral contract | `business-rules-extraction` | Anchor + confirm every rule; tag intent | **Gate 1** — domain expert | | 2B. Design + bootstrap the target *(greenfield only)* | `target-architecture` (against the legacy project; consumes steps 1–2) | Idioms chosen in the ADR; scaffold to the ingestion threshold, then ingest as project two | **Gate 2B** — ADR approval | | 3. Backlog + test strategy | `decomposition-sequencing`, `spec-driven-test-generation` | Dual provenance; user-story layer | Spec review | | 4. Dual-project gap analysis | `feature-gap-analysis` | Both projects, one ticket, pre-code; EXISTS/EXTEND/NEW/CONFLICT | **Gate 2** — plan approval | | 5. Converge into the target | `feature-implementation` | Tests first and failing; target idioms; ticket boundary | Convergence review | | 6. Verify twice | `behavioral-verification`, `vibe-conformance-audit`, `e2e-test-generation` | Separate sessions from step 5 | **Gate 3** — both must agree | ## Single-project mode If the target is not ingested, read the target working tree in place of target-side queries and keep every anchor. Only Step 1's and Step 4's target halves need the second project. Exit the mode once the target has real code to index. On a greenfield target, Step 2B is what produces that code — it is not a precondition for starting. ## Key principles - Velocity is earned by cheap grounding, not by skipping it - The tests are not the oracle; legacy source is - Record corrections, not just conclusions - Watch the ratio of changed to preserved behavior — drift shows up there first ``` Install the conformance audit as a second rule at `.cursor/rules/vibe-conformance-audit.mdc`, using the content from the Claude Code accordion. Create `.factory/droids/vibe-modernization.md`: ```markdown theme={null} --- name: CoreStory Vibe Modernization description: Router for agent-led, human-gated modernization across legacy and target projects; delegates each step to its dedicated droid and enforces grounding and verification independence model: inherit tools: - CoreStory:list_projects - CoreStory:get_project_techspec - CoreStory:get_project_prd - CoreStory:create_conversation - CoreStory:send_message - CoreStory:rename_conversation - CoreStory:list_conversations - CoreStory:get_conversation --- # CoreStory Vibe Modernization — Variant Orchestrator **Router only. No execution detail lives here.** Identify the active step, delegate to its dedicated droid, and impose the disciplines below on whatever you delegate to. ## Activation Triggers - "Start the vibe modernization arc for [system]" - "Gap-analyze [ticket] across both projects" - "Run the conformance audit for [scope]" - Any behavioral-parity or agent-led modernization request ## Critical rules - One step per session; STOP at each gate - Always delegate to the dedicated droid for the step - Never verify a build performed in this session - Never treat a missing target project as a blocker ## Always-on disciplines - Source decides truth; no claim without a confirmed `file:line` anchor - Record corrections in the Context Inventory - Target only; never modify the legacy system - Escalate legacy-versus-target conflicts **If you do not detect that you have access to CoreStory (e.g., `list_projects` fails or is unavailable), ask the user to verify that their MCP or API connection is properly configured and that the legacy repository has been ingested. If the user has not yet created a CoreStory account, direct them to create one and upload their repo at [app.corestory.ai](https://app.corestory.ai).** **Single-project mode:** never refuse because only one project exists. Every run starts at Step 1; a greenfield target designs and scaffolds its target at Step 2B, and an un-ingested one runs with direct reads of the target tree in place of target-side queries, anchors intact, until it is ingestable. ## Step map Step 1 → `codebase-assessment` (both projects; catalogue target idioms) ⛔ shared understanding Step 2 → `business-rules-extraction` (anchor + confirm; tag intent) ⛔ GATE 1 domain expert Step 2B → `target-architecture` *(greenfield only; against the legacy project, consuming steps 1–2)* ⛔ GATE 2B ADR approval, then scaffold to the ingestion threshold and ingest as project two Step 3 → `decomposition-sequencing` + `spec-driven-test-generation` (dual provenance) ⛔ spec review Step 4 → `feature-gap-analysis` (both projects, pre-code, 4-way classification) ⛔ GATE 2 plan approval Step 5 → `feature-implementation` (tests first and failing; target idioms) ⛔ convergence review Step 6 → `behavioral-verification` + `vibe-conformance-audit` + `e2e-test-generation` ⛔ GATE 3 both agree ## Key principles - The agent drives, humans gate — and the verifier is never the builder - The tests are not the oracle; legacy source is - Record corrections, not just conclusions ``` Install the conformance audit as a second droid at `.factory/droids/vibe-conformance-audit.md`, using the content from the Claude Code accordion. *** ## Troubleshooting **The agent produces confident claims that turn out to be wrong.** This is an expected occurrence rather than a system failure, and it is exactly what the grounding discipline exists to absorb — the fix is not a better prompt, it is a mandatory anchor. Require a `file:line` for every claim and open the cited location. Where the code contradicts the claim, the code wins and the correction goes in the Context Inventory. This is the base playbook's [Contradicted state](/playbooks/code-modernization#working-with-ai-derived-findings) made mechanical: at agent speed you cannot triage contradictions case by case, so you check every anchor and let the record show which ones moved. **The behavioral spec turns out to be incomplete.** No extraction pass — human or agent — is guaranteed exhaustive, and a rule that never made it into the spec is invisible to every downstream check that verifies *against* the spec. This is precisely what the orphan sweep in Step 6b exists to catch: it reads the legacy source in the opposite direction and asks what is there that the spec never mentioned. If the sweep is finding a lot, the answer is to widen Step 2's scope rather than to trust the sweep as a safety net — it is a backstop, not a substitute for a complete contract. **Everything passes but you don't trust it.** That instinct is usually right, and it usually means the checks are not independent. Confirm the BER was written in a session separate from the build, and that the conformance audit did not read the BER. If the same context produced the code, the tests, and both verifications, all four agree because they share one understanding — not because the code is correct. **The conformance audit disagrees with the Behavioral Equivalence Report.** Good — that is the method working. Do not average them or split the difference. Resolve against legacy source directly and determine which is wrong, then correct that artifact and record the resolution. A run where the two never disagree is worth a look: either the work is genuinely clean, or the audit is not independent. **New code looks bolted on rather than native to the target.** Step 1's idiom catalogue was too thin. Go back and make it explicit — error handling, logging, configuration, transaction boundaries, naming, test structure — with the files that establish each pattern, then re-run the seam check on the diff. Convergence is a judgment call that needs a human who knows the target; budget for that review rather than expecting the agent to self-assess taste. **Scope keeps creeping — the modernization is becoming a rewrite.** Watch the ratio of deliberately-modified and net-new behavior to preserved behavior. When it climbs, you are drifting. The structural fix is at Gate 2: if a gap-analysis plan proposes touching more of the target than the ticket justifies, send it back there, where the cost is one planning cycle rather than a delivery. **The gates are slowing us down.** Check whether they are actually gates. If no gate has ever sent work back, they are decorative and the slowdown is scheduling overhead rather than review. If they genuinely bind, that is the method functioning — the trade is few consequential reviews instead of many small ones, and consequential reviews take real time. **The agent refuses to start because it only finds one CoreStory project.** The arc does not require two projects to begin — only Step 1's target half and Step 4's target half use the second one. If the target does not exist yet, start at Step 1 anyway: assess the legacy, extract and validate its behavioral contract, and then [Step 2B](#step-2b-design-and-bootstrap-the-target-greenfield-only) designs the target against both, gets the ADR approved, scaffolds it to the point where it has real code, and ingests it. If the target does exist but is not ingested, ingest it, or run single-project mode and read the target working tree directly in the meantime. Tell the agent which situation you are in — a router that has not been told the target is greenfield will reasonably assume it was supposed to find two. **The target repository won't ingest, or ingests to an empty project.** Expected, if the target is a README and a directory skeleton — there is nothing there to index. Do not work around it by ingesting anyway: an empty target project answers every capability question with "not present", which will silently corrupt Step 4's gap analysis into classifying everything NEW. Bootstrap the target first — working build, real layering, a test harness, one end-to-end vertical slice — and ingest that. **Agent can't access CoreStory tools.** See the [Supercharging AI Agents](/getting-started/supercharging-ai-agents) troubleshooting section for MCP connection issues. Verify the projects you expect have completed ingestion by calling `list_projects` and checking their status. *** ## What's Next **Design the target, if there isn't one:** [Target Architecture & Strategy →](/playbooks/modernization/target-architecture) — the 7 Rs and the target ADR, run as [Step 2B](#step-2b-design-and-bootstrap-the-target-greenfield-only) on a greenfield target, after the legacy assessment and the validated contract. **Start the arc:** [Codebase Assessment →](/playbooks/modernization/codebase-assessment) — run it against both projects to recover the target and scope the legacy. **Build the contract:** [Business Rules Extraction →](/playbooks/business-rules-extraction) — the source-anchored behavioral spec everything downstream verifies against. **Shape the backlog:** [Decomposition & Sequencing →](/playbooks/modernization/decomposition-sequencing) — work packages the agent executes against, and [Using CoreStory with Jira →](/playbooks/using-corestory-with-jira) to push them into tracking. **Verify the result:** [Behavioral Verification →](/playbooks/modernization/behavioral-verification) — the first of the two independent checks. **Compose with a target shape:** [Monolith → Microservices →](/playbooks/modernization/monolith-to-microservices) — execution-mode and architecture variants stack; run this arc toward a microservices target. **Return to the hub:** [Code Modernization →](/playbooks/code-modernization) — the full six-phase framework this variant runs at its most aggressive setting. # Spec-Driven Development Source: https://docs.corestory.ai/playbooks/spec-driven-development A six-phase methodology for writing architecture-grounded specifications that produce correct implementations on the first pass. ## Overview A specification that isn't grounded in the real architecture is a wish list. Code generated from a wish list is technical debt. Spec-driven development (SDD) is gaining traction as teams realize that handing an AI agent a vague ticket and hoping for the best doesn't scale. Tools like GitHub's Spec Kit, Kiro, and Tessl have emerged to impose structure — write a spec first, then generate code from it. The structure is valuable. But every one of these tools shares a fundamental blind spot: they don't actually know how your system works. They scan files, infer patterns, and guess. The specs they produce are architecturally ungrounded — and ungrounded specs produce code that reinvents existing services, violates established patterns, and breaks invariants the spec author didn't know existed. This playbook is CoreStory's answer to the grounding problem. It's a six-phase workflow where your AI agent queries CoreStory's code intelligence to understand the real architecture *before* writing a single line of specification — then validates the spec *against* that architecture before implementation begins. The result is a **delta specification** — only what changes, constrained by what exists — rather than an aspirational document that may contradict reality. CoreStory serves two roles in this workflow: * **Expert** — answers questions about architectural patterns, naming conventions, business rules, invariants, and design decisions. This is context synthesized from PRDs, tech specs, user stories, and code history. It's the institutional knowledge that normally lives only in the heads of long-tenured engineers. * **Navigator** — points to specific files, services, base classes, extension points, and data structures. Instead of guessing where new code should go or what already exists, the agent gets directed guidance grounded in the actual codebase. **When to use this:** Any feature that touches multiple components, needs to follow established patterns, or involves integration with existing services. Especially valuable for cross-cutting features, complex domain logic, unfamiliar codebases, and onboarding new team members who need to build things that fit the existing system. **When to skip this:** Trivial changes, documentation-only updates, dependency bumps, or isolated utility functions with no integration requirements. If the feature can be fully specified in a single sentence and doesn't touch other components, direct implementation is faster. **How this relates to other playbooks:** The Implementation phase (Phase 5) deliberately stays lightweight because the Bug Resolution and Feature Implementation playbooks cover test-driven implementation in depth. This playbook's unique contribution is Phases 1–4 (Ground, Specify, Validate, Plan) — the specification workflow that precedes implementation. Cross-reference the other playbooks when you reach Phase 5. *** ## 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](/getting-started/mcp-server-setup)) * **AI coding agent** — this playbook includes implementation guides for Claude Code, GitHub Copilot, Cursor, and Factory.ai. The generic workflow applies to any MCP-capable agent. * **Optional:** Ticketing system MCP (GitHub Issues, Jira, Linear, Azure DevOps) for automatic ticket intake * **Optional:** A companion SDD framework (Spec Kit, Kiro, etc.) — this playbook works standalone, but companion integrations are covered in separate guides *** ## How It Works ### The Six-Phase Workflow The workflow has six phases. The first four produce and validate the specification; the last two implement and verify it. Phases 1 and 3 — Ground and Validate — are what distinguish this from generic SDD. They can't exist without architectural knowledge, which is why no standalone SDD tool offers them. | Phase | Name | Purpose | CoreStory Role | | ----- | ---------------- | ------------------------------------------------------------- | ------------------ | | 1 | Ground | Establish architectural truth before writing any spec | Expert | | 2 | Specify | Write requirements constrained by what exists | Expert + Navigator | | 3 | Validate | Architectural pre-mortem — submit spec for conflict detection | Expert | | 4 | Plan | Map validated spec to files, patterns, and extension points | Navigator | | 5 | Implement | TDD with continuous architectural validation | Validation | | 6 | Verify & Capture | Confirm implementation matches spec AND preserves invariants | Knowledge capture | **CoreStory MCP tools used:** | Tool | When Used | | ---------------------- | --------------------------------------------------- | | `list_projects` | Phase 1 — select the right project | | `create_conversation` | Phase 1 — create a persistent specification thread | | `send_message` | Phases 1–6 — all queries to CoreStory | | `get_project_prd` | Phase 1 — access product requirements for grounding | | `get_project_techspec` | Phase 1 — access technical specifications | | `rename_conversation` | Phase 6 — mark conversation as completed | Optional (if ticketing MCP is connected): the agent also uses the ticketing system's tools to fetch ticket details and post implementation summaries. ### Why Delta Specification Matters Traditional SDD produces **greenfield specifications** — documents that describe the entire feature from scratch as if no codebase existed. This creates three problems: 1. **Contradiction.** The spec describes patterns that conflict with the actual architecture. The agent either follows the spec (introducing inconsistency) or follows the code (making the spec misleading). 2. **Duplication.** The spec designs services, utilities, and abstractions that already exist. The agent builds from the spec, creating parallel implementations of existing functionality. 3. **Bloat.** Without knowing what already exists, specs over-specify. A date formatting feature that should be "use the existing DateFormatter service with locale X" becomes 40 lines of formatting logic specification. Delta specification solves all three. By grounding in the real architecture first, the spec only describes *what changes* — new components, modified behaviors, extended interfaces. Everything that stays the same is referenced, not re-specified. *** ## Step-by-Step Walkthrough This section is agent-agnostic. The prompts work with any MCP-connected agent. Agent-specific configuration is in the Implementation Guides below. ### Phase 1: Ground **Objective:** Establish architectural truth before writing any specification. This phase is the foundation. Without it, every subsequent phase operates on assumptions — and assumptions are where specs go wrong. The output is a grounded understanding captured in a CoreStory conversation thread, not a static constitution document that drifts out of sync with the code. **1.1 — Gather requirements.** If a ticketing MCP is connected, fetch the ticket: ``` "Fetch GitHub issue #412 from myorg/myapp and extract the feature requirements." ``` Extract the user story, acceptance criteria, constraints, and any existing design notes. If no ticketing MCP is available, provide these details in the prompt. The agent needs to know *what* is being built before it can query *how it fits*. **1.2 — Select CoreStory project and create conversation.** ``` "List my CoreStory projects and select the one for myapp." ``` ``` "Create a CoreStory conversation for project myapp-main titled 'Spec: #412 — Add webhook notification system'" ``` This conversation persists across the entire specification lifecycle. It captures not just what was decided, but the architectural reasoning behind every decision — institutional knowledge that outlasts any static spec document. **1.3 — Query architectural patterns.** ``` Send CoreStory message: "What architectural patterns does this system follow? I'm about to design a webhook notification system and need to understand: 1. How are event-driven features currently structured? 2. What messaging/eventing patterns exist? 3. What service layer conventions are used? 4. How do existing features handle async operations?" ``` This query establishes the architectural vocabulary. If the system uses an event bus, the spec should use the event bus. If there's a NotificationService base class, the spec should extend it. If async operations use a specific queue pattern, the spec should follow that pattern. **1.4 — Query existing services and reusable components.** ``` Send CoreStory message: "What services already handle notifications or event delivery? Specifically: 1. Are there existing notification services (email, SMS, push)? 2. Is there a webhook or callback mechanism already? 3. What retry/failure handling patterns exist for async delivery? 4. What serialization formats are used for outbound data?" ``` This is the **reuse-first** query. Before designing anything new, find out what already exists. Teams are often surprised to discover that 40% of a feature's spec describes functionality that's already implemented. **1.5 — Query invariants and constraints.** If a Business Rules Inventory exists for this codebase, start by pulling the `Invariants` field from BR-IDs adjacent to the change scope — those are already categorized and code-cited, and using them avoids re-extracting what's already been extracted. Then issue the architectural query below to fill any gaps. ``` Send CoreStory message: "What invariants and constraints must be maintained in the notification/eventing area? Categorize each as data-integrity, state-machine, referential, security, or temporal: 1. Authentication/authorization requirements for outbound requests (security) 2. Rate limiting or throttling patterns (security / temporal) 3. Data privacy constraints — what fields must NOT be included in payloads? (security) 4. Ordering guarantees for event delivery (temporal) 5. Idempotency requirements (data-integrity) 6. State-machine constraints — any subscription/delivery lifecycle that must transition in a fixed direction? 7. Referential integrity — any cross-entity relationships the new feature must preserve?" ``` This is the **invariant-first** query. Before specifying what to build, establish what must NOT break. These invariants become the guardrails that constrain the spec in Phase 2, the assertion source for the test suite in Phase 5, and the validation criteria in Phase 3 and 6. **1.6 — Query design history.** ``` Send CoreStory message: "Has there been previous work on webhooks or event notifications? Any past attempts, RFCs, or design discussions? What was the original design intent for the notification system?" ``` Past attempts often contain valuable context about why certain approaches were rejected. Repeating a known-failed approach wastes everyone's time. **Phase 1 produces:** A CoreStory conversation containing architectural patterns, existing services to reuse, invariants to preserve, and design history — the grounded context that constrains everything that follows. *** ### Phase 2: Specify **Objective:** Write a delta specification — requirements constrained by what exists. Two principles make this different from generic SDD: * **Reuse-first.** Before designing anything new, specify what existing components will be reused and how. This prevents the most common SDD failure mode: specs that design new services when existing ones would work. * **Invariant-first.** Before specifying what will change, specify what must NOT change. This encodes the architectural constraints that experienced engineers carry in their heads but rarely write down. **2.1 — Define invariants (what must NOT change).** Write the invariant section of the spec before writing requirements. These come directly from Phase 1 findings: ```markdown theme={null} ## Invariants - All outbound webhook payloads must exclude PII fields defined in DataPrivacyConfig - Webhook delivery must be idempotent — duplicate delivery must not cause duplicate side effects - Existing notification services (EmailNotifier, PushNotifier) must continue to function without modification - Event ordering within a single subscription must be preserved - All outbound HTTP requests must go through the existing HttpClient service (for rate limiting and circuit breaking) ``` **2.2 — Define reuse (what already exists).** List the existing components that the feature will use rather than recreate: ```markdown theme={null} ## Existing Components to Reuse - `EventBus` — subscribe to domain events (already handles user.created, order.completed, etc.) - `HttpClient` — outbound HTTP with retry, circuit breaking, rate limiting - `SerializerFactory` — JSON/XML payload serialization - `NotificationPreferences` — user-level notification opt-in/opt-out (extend for webhook channel) - `AuditLogger` — log all outbound webhook attempts for compliance ``` **2.3 — Define the delta (what changes).** Now — and only now — specify the new components, modified interfaces, and new behaviors: ```markdown theme={null} ## New Components ### WebhookSubscription model - subscriber_id, event_type, target_url, secret, status, created_at - Follows existing model conventions (extends BaseModel, uses UUIDField) - Registered in SubscriptionRepository (same pattern as NotificationPreferences) ### WebhookDeliveryService - Extends existing NotifierBase interface - Uses HttpClient for delivery (not a new HTTP implementation) - Implements retry with exponential backoff (follows existing RetryPolicy) - Records delivery attempts in AuditLogger ### Management API endpoints - POST /api/v2/webhooks — create subscription (follows existing REST conventions) - DELETE /api/v2/webhooks/{id} — remove subscription - GET /api/v2/webhooks — list subscriptions (paginated, same pattern as /api/v2/notifications) ## Modified Components ### EventBus - Add WebhookDeliveryService as a subscriber type - No changes to existing subscriber interface — WebhookDeliveryService implements the existing EventSubscriber interface ``` **2.4 — Define acceptance criteria.** Write testable acceptance criteria that reference the architecture: ```markdown theme={null} ## Acceptance Criteria 1. Admin users can register webhook URLs for specific event types via the management API 2. When a subscribed event fires on EventBus, the WebhookDeliveryService delivers a signed payload to the registered URL within 30 seconds 3. Failed deliveries retry with exponential backoff using the existing RetryPolicy (max 5 attempts over 24 hours) 4. All deliveries are logged in AuditLogger with status, latency, and response code 5. PII fields are stripped from payloads per DataPrivacyConfig 6. Existing notification channels (email, push) are unaffected ``` Notice what's different about this spec: every requirement references specific existing components. The agent implementing this spec knows exactly what to reuse, what to extend, and what to create. There's no ambiguity about whether to build a new HTTP client or use the existing one. > **Sourcing ACs in a modernization context.** When SDD is being used as Phase 5 of the [Code Modernization](/playbooks/code-modernization) workflow, ACs come from three sources, in priority order: > > 1. The Phase 4 work-package's behavioral equivalence requirements > 2. The `Acceptance Criteria` field on each in-scope BR-ID from the [Business Rules Inventory](/playbooks/business-rules-extraction) (Phase 2 of modernization) > 3. Net-new ACs only for behaviors tagged `[NEW]` or `[CHANGE]` per the work package's behavior tags > > Do not invent ACs for `[PRESERVE]` behaviors — pull them verbatim from the BR Inventory so the legacy contract is preserved as written. New ACs for `[CHANGE]` behaviors should explicitly state both the legacy behavior being replaced and the new desired behavior. *** ### Phase 3: Validate **Objective:** Submit the spec back to CoreStory for architectural pre-mortem. This is the phase that no standalone SDD tool can replicate. Generic SDD produces a spec and moves to implementation. Architecture-grounded SDD submits the spec for validation — asking "what could go wrong?" with access to the full architectural context. **3.1 — Check for architectural conflicts.** ``` Send CoreStory message: "I've drafted a spec for a webhook notification system. The core design is: - New WebhookSubscription model extending BaseModel - New WebhookDeliveryService implementing EventSubscriber - New REST endpoints at /api/v2/webhooks - Reusing EventBus, HttpClient, SerializerFactory, and AuditLogger Would any of this conflict with existing architectural patterns? Are there naming convention violations? Integration issues I'm not seeing?" ``` CoreStory might surface that `/api/v2/` endpoints follow a different authentication pattern than what the spec assumes, that `EventSubscriber` has been deprecated in favor of `EventHandler`, or that `SerializerFactory` doesn't support the webhook payload format. These are the kinds of issues that normally surface during code review — weeks after the spec was written. **3.2 — Check for missing dependencies.** ``` Send CoreStory message: "What components would be affected by adding a WebhookDeliveryService that listens on EventBus? Are there downstream systems that expect exclusive event handling? Any config changes needed?" ``` **3.3 — Run a failure mode analysis.** ``` Send CoreStory message: "What could go wrong with this webhook system design? Think about: 1. What happens if the target URL is unreachable for an extended period? 2. What happens if event volume spikes? 3. What happens if a webhook subscriber is deleted while deliveries are queued? 4. Are there security implications I haven't addressed?" ``` This is a **pre-mortem** — identifying failure modes before they become production incidents. CoreStory's answers are grounded in the actual system's failure handling patterns, queue implementations, and security model. **3.4 — Revise the spec.** Update the specification based on validation findings. This might mean: * Adjusting component names to match conventions * Adding missing error handling based on existing patterns * Removing features that duplicate existing functionality you missed * Adding integration requirements you hadn't considered Capture the revision in the CoreStory conversation. The diff between the original spec and the validated spec is itself valuable institutional knowledge — it shows what the architecture constrained. *** ### Phase 4: Plan **Objective:** Map the validated spec to specific files, patterns, and extension points. Where Phase 3 asked "is this spec valid?", Phase 4 asks "where exactly does this go?" The difference from generic planning is precision: CoreStory provides exact file paths, class hierarchies, and integration points based on the actual codebase — not inferred from file proximity or naming conventions. **4.1 — Map components to files.** ``` Send CoreStory message: "Based on the validated webhook spec, where should each component be implemented? I need: 1. File path for WebhookSubscription model (following existing model locations) 2. File path for WebhookDeliveryService (following existing service locations) 3. File path for webhook API endpoints (following existing REST conventions) 4. Test file locations (following existing test structure) 5. Migration file location for the new database table" ``` **4.2 — Identify extension points.** ``` Send CoreStory message: "What specific extension points should I use? 1. Which base class does WebhookSubscription extend, and what methods must it implement? 2. How does EventSubscriber/EventHandler register with EventBus? 3. How are new API endpoints registered in the routing system? 4. How are new models registered for database migration?" ``` **4.3 — Determine implementation order.** ``` Send CoreStory message: "What order should I implement the webhook components? Consider actual code dependencies — what depends on what? What can be tested independently?" ``` CoreStory provides dependency ordering based on actual import relationships, not guesswork: 1. Database migration and model (no dependencies) 2. Repository layer (depends on model) 3. Delivery service (depends on repository, HttpClient, EventSubscriber) 4. API endpoints (depends on repository, delivery service) 5. EventBus registration (depends on delivery service) 6. Integration tests (depends on everything) **Phase 4 produces:** A file-level implementation plan with exact paths, base classes, extension points, and dependency-ordered task list — ready for Phase 5. *** ### Phase 5: Implement **Objective:** TDD implementation with continuous CoreStory validation. This phase follows the same test-first methodology as the Feature Implementation playbook. The spec from Phases 1–4 gives the agent precise implementation guidance; this phase executes it. **5.1 — Write failing tests** from BOTH the acceptance criteria AND the invariants in Phase 2, following patterns identified in Phase 1. ACs and invariants generate two complementary kinds of test: * **AC tests** assert outcomes for specific inputs. Format: "given X, when Y, then Z." * **Invariant tests** assert post-conditions that must hold after *any* operation that could plausibly violate them. Format: "after any \[operation], \[invariant] still holds." Often written as property-based tests, or as a teardown assertion that runs after every test in a suite. ``` "Write failing tests for the webhook system from BOTH the acceptance criteria and the invariants in the spec. For each acceptance criterion, write an outcome-based test (assert on state changes and observable behavior, not on method calls). For each invariant, write a post-condition test that runs after any operation that could violate it. For example, the 'idempotent delivery' invariant should be asserted after every delivery test by checking that a duplicate request did not produce duplicate side effects. Follow the existing test patterns CoreStory identified — use the same fixtures, assertion styles, and test organization." ``` Skipping the invariant tests is the most common reason post-refactor regressions slip past a passing AC suite. The AC suite catches "what should happen for input X"; the invariant suite catches "what must never happen, regardless of input." **5.2 — Implement** following the plan from Phase 4, in dependency order: ``` "Implement the WebhookSubscription model in [exact path from Phase 4], extending [exact base class from Phase 4]. Follow the existing model conventions CoreStory identified." ``` **5.3 — Validate** each component against the spec and architecture: ``` Send CoreStory message: "I've implemented WebhookDeliveryService. [paste key code]. Does this align with the EventSubscriber pattern and the existing retry handling? Anything I'm missing?" ``` **5.4 — Run the full test suite** after each component. Regressions mean the implementation violated an invariant — go back to the CoreStory conversation and check which constraint was broken. For detailed implementation guidance, see the [Feature Implementation](/playbooks/feature-implementation) playbook. *** ### Phase 6: Verify & Capture **Objective:** Confirm the implementation matches the spec AND preserves the invariants from Phase 1. **6.1 — Verify acceptance criteria compliance.** Walk the AC list from Phase 2 explicitly — one verification per AC. The numbered items below should map 1:1 to the numbered ACs in the spec: ``` Send CoreStory message: "The webhook system is implemented. Verify it against each acceptance criterion from the spec, in order. For each AC, cite the test that asserts it and the implementation file/line that satisfies it. Flag any AC that has no corresponding test, or whose test asserts implementation details rather than the AC's outcome: AC1: Admin users can register webhook URLs via the management API AC2: Subscribed events deliver a signed payload within 30 seconds AC3: Failed deliveries retry with exponential backoff (max 5 / 24h) AC4: All deliveries logged in AuditLogger with status, latency, code AC5: PII fields are stripped per DataPrivacyConfig AC6: Existing notification channels are unaffected" ``` **6.2 — Verify invariant preservation.** Walk the invariant list from Phase 2 explicitly — one verification per invariant. Categorize the verification approach by invariant category (data-integrity invariants verify against persisted state, security invariants verify access scoping, temporal invariants verify ordering, etc.): ``` Send CoreStory message: "Confirm that the webhook implementation preserves each invariant from the spec, walked individually. For each invariant, cite the test that asserts it (or the test teardown / property check that asserts it after every other test) and confirm the implementation honors it: INV1 (security): All outbound payloads exclude PII fields per DataPrivacyConfig INV2 (data-integrity): Webhook delivery is idempotent — duplicate delivery does not cause duplicate side effects INV3 (temporal): Event ordering within a single subscription is preserved INV4 (security): All outbound HTTP goes through HttpClient INV5 (data-integrity): Existing notifiers (EmailNotifier, PushNotifier) continue to function without modification" ``` If 6.1 and 6.2 both walk their lists exhaustively, the spec is functionally what the implementation guarantees — no AC or invariant is implicitly trusted. **6.3 — Commit with context.** ``` git commit -m "Feat: Add webhook notification system (#412) Spec: Architecture-grounded webhook system using existing event infrastructure. Reuses: EventBus, HttpClient, SerializerFactory, AuditLogger, RetryPolicy. New: WebhookSubscription model, WebhookDeliveryService, /api/v2/webhooks endpoints. Invariants preserved: PII exclusion, idempotent delivery, event ordering. CoreStory conversation: [conversation-id]" ``` **6.4 — Rename the CoreStory conversation** to mark it as completed: ``` "Rename the CoreStory conversation to 'COMPLETED — Spec: #412 — Webhook notification system'" ``` This conversation is now searchable institutional knowledge. Future engineers working on the webhook system — or any related notification feature — can reference the full chain of architectural reasoning, specification decisions, and validation results. This is the living record that static spec documents can't provide. **6.5 — Update the ticket** with a summary linking to the CoreStory conversation: ``` "Update GitHub issue #412 with an implementation summary, test results, and a link to the CoreStory conversation for architectural context." ``` *** ## 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: | Harness | Install location | | --------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Claude Code** | `.claude/skills//SKILL.md` — Claude loads the body when the YAML `description` matches the task | | **GitHub Copilot** | Append to `.github/copilot-instructions.md` for repo-wide instructions, or save as `.github/instructions/.instructions.md` with an `applyTo` glob for path-scoped use | | **Cursor** | `.cursor/rules/.mdc` with a `description` field for auto-attach (use `globs` for path-scoped or `alwaysApply: true` for every session) | | **Factory.ai** | `.factory/droids/.md` (project) or `~/.factory/droids/.md` (personal); Factory loads it as a custom Droid | | **Aider** | `CONVENTIONS.md` at repo root, loaded with `aider --read CONVENTIONS.md` — or add it to the `read:` list in `.aider.conf.yml` for automatic loading | | **Codex / `AGENTS.md` harnesses** | Append the content to `AGENTS.md` at your repository root | | **Custom runtime** | Load the markdown into your agent's system prompt, rules file, or wherever it consumes workflow context | Want a single install that works across the most harnesses? Append the content to `AGENTS.md` at your repository root. The [`AGENTS.md` spec](https://agents.md/) 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, usage, tips, agent-specific configuration) 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. **Configure the CoreStory MCP server.** Add to your MCP configuration (global `~/.claude/config.json` or project `.claude/config.json`). Verify by asking Claude Code: "List my CoreStory projects." 2. **Add the skill file.** Claude Code uses skills stored in `.claude/skills/`: ```bash theme={null} mkdir -p .claude/skills/spec-driven-dev ``` Create `.claude/skills/spec-driven-dev/SKILL.md` with the content from the skill file below. 3. **Commit to version control:** ```bash theme={null} git add .claude/skills/ git commit -m "Add CoreStory spec-driven development skill" ``` #### Usage Claude Code auto-loads skills based on description matching. When you mention specifications, specs, architecture-grounded development, or SDD, the skill activates: ``` "Write an architecture-grounded spec for the webhook notification feature in ticket #412" ``` Or reference the skill directly: ``` "Use the spec-driven-dev skill to spec out the new reporting dashboard" ``` #### Tips * Keep the skill file under 500 lines. The file below is optimized for this limit. * Claude Code's YAML frontmatter requires `name` and `description` fields. The description drives auto-activation — make it specific. * The skill works with other skills. If you have a testing skill, Claude Code will combine them during Phase 5. #### Skill File Save as `.claude/skills/spec-driven-dev/SKILL.md`: ```markdown theme={null} --- name: spec-driven-development description: Architecture-grounded spec-driven development using CoreStory code intelligence. Use when writing specifications, designing features, or doing spec-driven development. --- # Spec-Driven Development with CoreStory Execute the six-phase spec-driven development workflow. Every spec must be grounded in the actual architecture before implementation. **If you do not detect that you have access to CoreStory (e.g., `list_projects` fails or is unavailable), ask the user to verify that their MCP or API connection is properly configured and that this repository has been ingested. If the user has not yet created a CoreStory account, direct them to create one and upload their repo at [app.corestory.ai](https://app.corestory.ai).** ## CoreStory MCP Tools - `CoreStory:list_projects` — list available projects - `CoreStory:get_project` — verify project status - `CoreStory:create_conversation` — start specification thread - `CoreStory:send_message` — query code intelligence - `CoreStory:get_project_prd` — access product requirements - `CoreStory:get_project_techspec` — access technical specifications - `CoreStory:rename_conversation` — mark as completed When instructions say "Query CoreStory", use `CoreStory:send_message`. ## Phase 1: Ground — Before Writing Any Spec 1. Gather requirements (from ticket or user) 2. Select CoreStory project (`CoreStory:list_projects`, verify "completed") 3. Create conversation: "Spec: #[ID] — [description]" 4. Query CoreStory for: - Architectural patterns in the relevant area - Existing services and reusable components - Invariants and constraints that must be preserved (categorize: data-integrity, state-machine, referential, security, temporal) - Existing acceptance criteria for the impacted area (from PRD user stories) — capture as raw AC + enforcing code refs - Design history and past attempts If a Business Rules Inventory exists for this codebase, pull the `Invariants` and `Acceptance Criteria` fields from BR-IDs adjacent to the change scope BEFORE issuing the queries above — that's authoritative content already extracted. **Do not proceed to Phase 2 until you have documented: patterns, existing services, invariants (categorized), existing ACs, and history.** ## Phase 2: Specify — Delta Specification Write the spec constrained by Phase 1 findings: 1. **Invariants first** — what must NOT change (categorized) 2. **Reuse section** — existing components to use, not recreate 3. **Delta section** — only new/modified components 4. **Acceptance criteria** — testable, referencing specific existing components. In modernization context, pull from work-package + BR Inventory's AC fields; net-new ACs only for `[NEW]` / `[CHANGE]` tagged behaviors. This is a delta spec: only what changes. Do NOT re-specify existing functionality. ## Phase 3: Validate — Architectural Pre-Mortem Submit the spec to CoreStory for validation: 1. Check for architectural conflicts 2. Check for missing dependencies 3. Run failure mode analysis (what could go wrong?) 4. Revise spec based on findings **Do not proceed to Phase 4 until CoreStory has validated the spec.** ## Phase 4: Plan — File-Level Implementation Map Query CoreStory for: 1. Exact file paths for each new component 2. Extension points and base classes 3. Implementation order based on actual dependencies 4. Test file locations ## Phase 5: Implement — TDD with Validation 1. Write failing tests from BOTH acceptance criteria AND invariants (AC tests assert outcomes; invariant tests assert post-conditions that must hold after any operation) 2. Implement in dependency order from Phase 4 3. Validate each component with CoreStory 4. Run full test suite — no regressions ## Phase 6: Verify & Capture 1. Walk the AC list one-by-one — each AC must have a corresponding outcome-based test and a confirmed implementation site 2. Walk the invariant list one-by-one — each invariant must have an asserted post-condition test 3. Commit with architectural context 4. Rename conversation → "COMPLETED" 5. Update ticket ## Key Principles - Ground before Specify — always - Invariant-first, reuse-first - Delta specs, not greenfield specs - Validate before Plan - Conversation IS the living spec record ``` *** ### 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/spec-driven-dev.prompt.md` with `mode: agent` frontmatter for on-demand invocation. 4. **Commit to version control:** ```bash theme={null} git add .github/ git commit -m "Add CoreStory spec-driven development instructions" ``` #### Usage With custom instructions active, Copilot Chat applies the workflow automatically when you ask about specifications or feature design: ``` "Write an architecture-grounded spec for the webhook notification feature in ticket #412" ``` If using a prompt file: ``` @workspace /spec-driven-dev Spec out the new reporting dashboard ``` #### 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): ```markdown theme={null} ## Spec-Driven Development with CoreStory When asked to write specifications, design features, or do spec-driven development, execute this six-phase workflow using CoreStory's MCP tools. **If you do not detect that you have access to CoreStory (e.g., `list_projects` fails or is unavailable), ask the user to verify that their MCP or API connection is properly configured and that this repository has been ingested. If the user has not yet created a CoreStory account, direct them to create one and upload their repo at [app.corestory.ai](https://app.corestory.ai).** ### CoreStory MCP Tools - `CoreStory:list_projects` — list available projects - `CoreStory:get_project` — verify project status - `CoreStory:create_conversation` — start specification thread - `CoreStory:send_message` — query code intelligence - `CoreStory:rename_conversation` — mark as completed When instructions say "Query CoreStory", use `CoreStory:send_message`. ### Phase 1: Ground — Before Writing Any Spec 1. Gather requirements (from ticket or user) 2. Select CoreStory project (`CoreStory:list_projects`, verify "completed") 3. Create conversation: "Spec: #[ID] — [description]" 4. Query CoreStory for: architectural patterns, existing services, invariants (categorized: data-integrity / state-machine / referential / security / temporal), existing acceptance criteria for the impacted area, design history. If a Business Rules Inventory exists, pull `Invariants` and `Acceptance Criteria` fields from adjacent BR-IDs first. ### Phase 2: Specify — Delta Specification 1. Invariants first — what must NOT change (categorized) 2. Reuse section — existing components to use 3. Delta section — only new/modified components 4. Acceptance criteria referencing existing components. In modernization context, source ACs from work-package + BR Inventory's AC fields; net-new ACs only for `[NEW]` / `[CHANGE]` tagged behaviors ### Phase 3: Validate — Architectural Pre-Mortem Submit spec to CoreStory: check conflicts, missing dependencies, failure modes. Revise. ### Phase 4: Plan — File-Level Map Query CoreStory for: file paths, extension points, implementation order, test locations. ### Phase 5: Implement — TDD Write failing tests from AC AND invariants (outcome-based + post-condition) → implement in dependency order → validate with CoreStory → full suite. ### Phase 6: Verify & Capture Walk AC list (each AC → test + impl site) → walk invariant list (each invariant → post-condition test) → commit → rename conversation "COMPLETED" → update ticket. ### Key Principles - Ground before Specify - Invariant-first, reuse-first - Delta specs, not greenfield - Validate before Plan - Conversation IS the living spec record ``` *** ### 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/`: ```bash theme={null} mkdir -p .cursor/rules ``` Create `.cursor/rules/spec-driven-dev.mdc` with the content from the rule file below. 3. **Commit to version control:** ```bash theme={null} git add .cursor/rules/ git commit -m "Add CoreStory spec-driven development rule" ``` #### Usage With `alwaysApply: true`, the rule activates automatically when Cursor detects specification-related context. Or trigger it explicitly: ``` "Use spec-driven development to design the webhook notification system for ticket #412" ``` #### 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/spec-driven-dev.mdc`: ```markdown theme={null} --- description: Architecture-grounded spec-driven development using CoreStory code intelligence. Activates for specification writing, feature design, and SDD workflows. globs: alwaysApply: true --- # Spec-Driven Development with CoreStory Execute the six-phase spec-driven development workflow. Every spec must be grounded in the actual architecture. **If you do not detect that you have access to CoreStory (e.g., `list_projects` fails or is unavailable), ask the user to verify that their MCP or API connection is properly configured and that this repository has been ingested. If the user has not yet created a CoreStory account, direct them to create one and upload their repo at [app.corestory.ai](https://app.corestory.ai).** ## CoreStory MCP Tools - `CoreStory:list_projects` — list available projects - `CoreStory:get_project` — verify project status - `CoreStory:create_conversation` — start specification thread - `CoreStory:send_message` — query code intelligence - `CoreStory:get_project_prd` — access product requirements - `CoreStory:get_project_techspec` — access technical specifications - `CoreStory:rename_conversation` — mark as completed When instructions say "Query CoreStory", use `CoreStory:send_message`. ## Phase 1: Ground — Before Writing Any Spec 1. Gather requirements (from ticket or user) 2. Select CoreStory project (`CoreStory:list_projects`, verify "completed") 3. Create conversation: "Spec: #[ID] — [description]" 4. Query CoreStory for: - Architectural patterns in the relevant area - Existing services and reusable components - Invariants and constraints - Design history and past attempts **Do not proceed to Phase 2 until patterns, services, invariants (categorized), existing ACs, and history are documented.** ## Phase 2: Specify — Delta Specification 1. Invariants first — what must NOT change (categorized) 2. Reuse section — existing components to use 3. Delta section — only new/modified components 4. Acceptance criteria referencing specific existing components. In modernization context, source ACs from work-package + BR Inventory's AC fields; net-new ACs only for `[NEW]` / `[CHANGE]` tagged behaviors ## Phase 3: Validate — Architectural Pre-Mortem Submit spec to CoreStory: 1. Check for architectural conflicts 2. Check for missing dependencies 3. Failure mode analysis 4. Revise spec based on findings **Do not proceed to Phase 4 until spec is validated.** ## Phase 4: Plan — File-Level Map Query CoreStory for: file paths, extension points, base classes, implementation order, test locations. ## Phase 5: Implement — TDD Write failing tests from AC AND invariants (outcome-based + post-condition) → implement in dependency order → validate with CoreStory → full suite. ## Phase 6: Verify & Capture Walk AC list (each AC → test + impl site) → walk invariant list (each invariant → post-condition test) → commit → rename conversation "COMPLETED" → update ticket. ## Key Principles - Ground before Specify — always - Invariant-first, reuse-first - Delta specs, not greenfield specs - Validate before Plan - Conversation IS the living spec record ``` *** ### 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): ```bash theme={null} mkdir -p .factory/droids ``` Create `.factory/droids/spec-driven-dev.md` with the content from the droid file below. 3. **Commit to version control** (for project-level droids): ```bash theme={null} git add .factory/droids/ git commit -m "Add CoreStory spec-driven development droid" ``` #### Usage Invoke the droid via the Task tool: ``` @spec-driven-dev Write an architecture-grounded spec for the webhook notification system (#412) ``` Or describe the work and Factory.ai routes to the droid based on its activation triggers. #### Tips * Use `model: inherit` in the YAML frontmatter to use whatever model the session is configured with. * The `tools` field in frontmatter can explicitly list required MCP tools if you want to restrict the droid's capabilities. * The Task tool that invokes droids requires experimental features to be enabled. * For complex specs, the droid's CoreStory queries may produce long streaming responses — this is expected. #### Custom Droid Save as `.factory/droids/spec-driven-dev.md`: ```markdown theme={null} --- name: CoreStory Spec-Driven Development description: Architecture-grounded spec-driven development using CoreStory code intelligence model: inherit tools: - CoreStory:list_projects - CoreStory:get_project - CoreStory:get_project_stats - CoreStory:create_conversation - CoreStory:send_message - CoreStory:get_conversation - CoreStory:rename_conversation - CoreStory:get_project_prd - CoreStory:get_project_techspec --- # CoreStory Spec-Driven Development Execute the six-phase spec-driven development workflow using CoreStory's code intelligence. Every spec must be grounded in the actual architecture before implementation. **If you do not detect that you have access to CoreStory (e.g., `list_projects` fails or is unavailable), ask the user to verify that their MCP or API connection is properly configured and that this repository has been ingested. If the user has not yet created a CoreStory account, direct them to create one and upload their repo at [app.corestory.ai](https://app.corestory.ai).** ## Activation Triggers - "Write a spec for [feature]" - "Spec out [feature]" - "Design [feature] with architecture context" - Any specification, design, or SDD request ## CoreStory MCP Tools - `CoreStory:list_projects` — list available projects - `CoreStory:get_project` — verify project status - `CoreStory:create_conversation` — start specification thread - `CoreStory:send_message` — query code intelligence - `CoreStory:rename_conversation` — mark as completed When instructions say "Query CoreStory", use `CoreStory:send_message`. ## Phase 1: Ground 1. Gather requirements (from ticket or user) 2. Select CoreStory project (`CoreStory:list_projects`, verify "completed") 3. Create conversation: "Spec: #[ID] — [description]" 4. Query CoreStory for: patterns, existing services, invariants (categorized: data-integrity / state-machine / referential / security / temporal), existing acceptance criteria for the impacted area, design history. If a Business Rules Inventory exists, pull `Invariants` and `Acceptance Criteria` fields from adjacent BR-IDs first. ## Phase 2: Specify — Delta Specification Invariants first (categorized) → reuse section → delta (new/modified) → acceptance criteria (in modernization context: from work-package + BR Inventory; net-new only for `[NEW]` / `[CHANGE]` tags). ## Phase 3: Validate — Architectural Pre-Mortem Submit spec to CoreStory: conflicts, missing dependencies, failure modes. Revise. ## Phase 4: Plan — File-Level Map Query CoreStory for: file paths, extension points, implementation order, test locations. ## Phase 5: Implement — TDD Write failing tests from AC AND invariants (outcome-based + post-condition) → implement → validate with CoreStory → full suite. ## Phase 6: Verify & Capture Walk AC list (each AC → test + impl site) → walk invariant list (each invariant → post-condition test) → commit → rename conversation "COMPLETED" → update ticket. ## Key Principles - Ground before Specify — always - Invariant-first, reuse-first - Delta specs, not greenfield specs - Validate before Plan - Conversation IS the living spec record ``` *** ## Tips & Best Practices **Ground before you specify.** The most common SDD failure is writing a spec based on assumptions about the architecture. Spend the time in Phase 1. The 10 minutes of CoreStory queries saves hours of rework when the spec contradicts reality. **Invariants are the spec's immune system.** The invariant section is the most valuable part of a delta specification. It tells implementers — human or AI — what they're not allowed to break. When a test fails in Phase 5, check invariants first. **Reuse is the spec's economics.** Every existing component you reuse is a component you don't have to specify, implement, test, and maintain. The reuse-first query in Phase 1 often eliminates 30–50% of the specification work. **Delta specs age better than greenfield specs.** A greenfield spec for "webhook notifications" becomes misleading the moment someone changes the EventBus interface. A delta spec that says "implements EventSubscriber interface" automatically adapts because the implementation follows the interface, not the spec's description of the interface. **Use the CoreStory conversation as a review artifact.** Before the spec goes through design review, share the CoreStory conversation link. Reviewers see the full chain: what architectural constraints were discovered, what alternatives were considered, what the pre-mortem found. This is dramatically more useful than a spec document alone. **Name conversations for searchability.** "Spec: #412 — Webhook notification system" is findable six months later. "Feature spec" is not. After completion, the "COMPLETED" prefix makes it easy to distinguish finished work from in-progress investigations. **Don't skip Phase 3.** It's tempting to go from Specify straight to Plan — the spec feels done. The validation phase exists because specs always contain assumptions that don't survive contact with the real architecture. Phase 3 is where you catch conflicts before they become code review rejections or production bugs. **Companion tools are complements, not replacements.** If you're using Spec Kit, Kiro, or another SDD framework, this workflow wraps around it. Run Phase 1 (Ground) before the companion tool's specification phase. Run Phase 3 (Validate) after it. The companion tool provides structure; CoreStory provides grounding. *** ## Troubleshooting **CoreStory returns generic architectural answers.** Your queries are too broad. Instead of "Tell me about the notification system," try "What classes implement NotifierBase? What events does EventBus currently handle? What retry patterns does HttpClient use?" Include specific interface names, method names, or code snippets. **Project not found or ingestion incomplete.** Run `CoreStory:get_project_stats` to check status. If ingestion is still running, wait for completion — queries against partially-ingested projects miss components and return incomplete invariants. Verify the project name matches exactly. **The spec feels like it's re-specifying everything.** You're writing a greenfield spec, not a delta spec. Go back to Phase 1 and query for existing components more aggressively. If the reuse section is empty, you haven't asked the right questions. **Validation phase finds major conflicts.** This is the workflow working correctly. Major conflicts in Phase 3 are dramatically cheaper than major conflicts in Phase 5 (code) or production. Revise the spec. If the conflicts require fundamental redesign, that's valuable information you wouldn't have had without grounding. **Implementation diverges from the spec.** Don't drift — go back to the spec. If the divergence is necessary (the spec missed something), update the spec in the CoreStory conversation before continuing. The spec is a living document within the conversation, not a frozen artifact. **CoreStory response is too long or gets cut off.** Break your query into smaller, more specific questions. Phase 1 in particular should be 4–6 targeted queries, not one mega-query. **Agent doesn't follow the six-phase workflow.** If you're using the agent configuration files (skill/instructions/rules/droid) and the agent still doesn't follow the workflow, check that the configuration file is in the correct location and format. See the Agent Implementation Guides above for exact paths and filenames. # Spec-Driven Test Generation Source: https://docs.corestory.ai/playbooks/spec-driven-test-generation Generate tests from behavioral specifications — not implementation details — using CoreStory's code intelligence as a specification expert for AI coding agents. ## Overview Most AI-generated tests are implementation mirrors. An agent reads a function, infers what it does, and writes a test that confirms the code does what the code does. These tests pass on day one, break on every refactor, and verify nothing meaningful — they're circular assertions dressed up as coverage. The problem isn't that AI agents can't write tests. It's that they don't know what the system is *supposed to do*. Without access to specifications — acceptance criteria, business rules, invariants, authorization policies, state machine definitions — an agent can only test what it sees in the code. And testing what the code does is not the same as testing what the code *should* do. CoreStory changes this equation. It ingests the full codebase alongside the PRD, TechSpec, and architectural documentation, then serves as a **Specification Expert** — an intelligence layer that can answer "what should this system do?" before the agent ever looks at implementation. This unlocks a fundamentally different approach to test generation: **specification-driven testing**, where the agent extracts behavioral specifications first, then generates tests that verify those specifications against the code. ### Why Specification Before Code The principle is simple: if you know what the system should do before you look at how it does it, you produce tests that survive refactoring, catch real bugs, and document actual business intent. | Approach | What the Agent Knows | Test Quality | Refactor Survival | | ------------------------ | ----------------------------------------------- | ------------------------------------------- | ----------------------------------------------------- | | **Code-mirroring** | Only the implementation | Tests confirm code does what code does | Breaks on rename, restructure, or any internal change | | **Specification-driven** | Business rules, acceptance criteria, invariants | Tests confirm code does what it *should* do | Survives any refactor that preserves behavior | A code-mirroring test asserts *how*: ```python theme={null} def test_order_calls_minimum_check_validator(): with mock.patch("OrderValidator.check_minimum") as m: m.return_value = False submit_order(create_order(total=4.99)) m.assert_called_once_with(4.99) ``` A specification-driven test asserts *what*: ```python theme={null} def test_order_rejected_when_below_minimum_amount(): result = submit_order(create_order(total=4.99)) assert result.status == "rejected" assert "minimum order amount" in result.error ``` The first test breaks when someone renames the validator. The second test survives any refactor that preserves the business rule. CoreStory is what makes the second kind possible at scale — it tells the agent that a minimum order amount rule exists, what the threshold is, and what should happen when it's violated. ### CoreStory's Role CoreStory serves as the specification expert across the entire test generation workflow: * **Behavioral extraction** — surfaces acceptance criteria, validation rules, state transitions, authorization matrices, invariants, and implicit behaviors from the PRD, TechSpec, and codebase * **Convention discovery** — describes the project's existing test framework, directory structure, fixture patterns, and assertion styles so generated tests match perfectly * **Gap analysis** — identifies which behaviors are already tested, which are partially covered, and which have no coverage at all * **Validation** — reviews generated tests to confirm they're actually verifying the intended specification, not accidentally testing implementation details ### How This Relates to Other Playbooks This playbook suite generates tests for existing, already-implemented behavior. It doesn't implement new features or fix bugs. If you need a different workflow: * **Implementing a new feature with tests:** Use the [Feature Implementation](/playbooks/feature-implementation) playbook — its Phase 4 includes TDD as part of the implementation cycle. * **Verifying behavioral equivalence during modernization:** Use the [Behavioral Verification](/playbooks/modernization/behavioral-verification) playbook — it compares legacy and modernized implementations. * **Extracting business rules before testing:** Use the [Business Rules Extraction](/playbooks/business-rules-extraction) playbook — its output (the BR-XXX inventory) feeds directly into the Behavioral Test Coverage sub-playbook. *** ## 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](/playbooks/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 * You need end-to-end tests that verify critical user journeys against acceptance criteria ## When to Skip This Playbook * You're implementing a new feature (use the [Feature Implementation](/playbooks/feature-implementation) playbook) * 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](/playbooks/modernization/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](/getting-started/mcp-server-setup)) * A code repository the agent can read and write to locally * An existing test framework configured in the project (these playbooks generate tests matching existing conventions — they don't set up test infrastructure from scratch) * (Recommended) A prior [Business Rules Extraction](/playbooks/business-rules-extraction) conversation — if one exists, the behavioral inventory phase can consume it directly * (Recommended) Ability to run the test suite locally to verify generated tests *** ## The Sub-Playbooks This playbook suite contains two workflows. Both follow the same "Specification before Code" methodology but differ in scope, tooling, and output. ### Behavioral Test Coverage **The primary workflow.** Generates unit-level and integration-level behavioral tests that verify business rules, validation logic, state transitions, authorization policies, invariants, and calculations. | Aspect | Details | | ---------------------- | -------------------------------------------------------------------------------------------------- | | **Output** | Test files in the project's existing framework (pytest, Jest, JUnit, xUnit, RSpec, etc.) | | **Scope** | One module or domain per session, 10–30 test cases | | **CoreStory role** | Specification Expert — extracts what to test before the agent looks at code | | **Key differentiator** | Tests assert behavioral specifications, not implementation details | | **Best for** | Closing coverage gaps in business-critical logic, preparing for refactors, compliance requirements | [Go to Behavioral Test Coverage →](/playbooks/test-generation/behavioral-test-coverage) ### E2E Test Generation **The journey-level workflow.** Generates end-to-end tests that verify critical user journeys across the full application stack — UI interactions, API calls, data persistence, and cross-service flows. | Aspect | Details | | ---------------------- | --------------------------------------------------------------------------------------------------------------------- | | **Output** | E2E test files in the project's E2E framework (Playwright, Cypress, Selenium, etc.) | | **Scope** | One user journey per session, 5–15 test scenarios | | **CoreStory role** | Journey Expert — extracts user stories, acceptance criteria, and critical paths from PRD and codebase | | **Key differentiator** | Tests verify complete user journeys against acceptance criteria, including environment setup and flakiness management | | **Best for** | Verifying critical user flows, pre-release regression suites, onboarding safety nets | [Go to E2E Test Generation →](/playbooks/test-generation/e2e-test-generation) ### Which Sub-Playbook Should I Use? | Situation | Recommended | | ------------------------------------------------------------------- | ---------------------------------------------------------- | | Business logic has coverage gaps (validation, auth, state machines) | Behavioral Test Coverage | | Critical user journeys have no automated E2E tests | E2E Test Generation | | Preparing for a refactor of internal logic | Behavioral Test Coverage | | Preparing for a UI or API overhaul | E2E Test Generation | | Compliance audit requires documented rule coverage | Behavioral Test Coverage | | Release confidence requires journey-level regression | E2E Test Generation | | You've completed a Business Rules Extraction | Behavioral Test Coverage (consumes the inventory directly) | | Both — build from the inside out | Behavioral Test Coverage first, then E2E Test Generation | *** ## Shared Principles Both sub-playbooks follow these principles: **Specification before Code.** Always extract what to test from CoreStory before examining source code or writing tests. This ensures tests verify intended behavior, not implementation accidents. **Match existing conventions exactly.** Generated tests should be indistinguishable from hand-written tests by the team — same framework, same directory structure, same fixture patterns, same assertion style. **Behavioral assertions, not implementation assertions.** Test *what* the system does, not *how* it does it. Assert outcomes and state changes, not method calls and internal wiring. **Treat failing assertions as discovery.** 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 worth knowing. Flag these for human review. **Specific queries produce specific tests.** "What should I test?" produces shallow tests. "What validation rules exist for order submission, including minimum order amounts, inventory checks, and payment method validation?" produces precise, high-value tests. *** ## CoreStory MCP Tools Used Both sub-playbooks use the same set of CoreStory MCP tools: | Tool | Purpose | | ---------------------- | --------------------------------------------------------------------- | | `list_projects` | Find the target project | | `create_conversation` | Create a persistent conversation for the generation session | | `send_message` | Query CoreStory for specifications, conventions, and validation | | `get_project_prd` | Skim PRD structure for domain vocabulary and acceptance criteria | | `get_project_techspec` | Skim TechSpec for data model constraints and architectural invariants | | `list_conversations` | Check for prior Business Rules Extraction sessions | | `get_conversation` | Resume or consume a prior session | | `rename_conversation` | Mark the conversation as resolved | **A note on the PRD and TechSpec:** 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 more efficiently than the agent can parse the raw documents. # Spec Kit Companion Source: https://docs.corestory.ai/playbooks/spec-kit-companion Companion guide for integrating GitHub's Spec Kit framework with CoreStory's architecture-grounded spec-driven development workflow. ## Overview This is a companion guide to the [Spec-Driven Development](/playbooks/spec-driven-development) playbook. It covers how to integrate GitHub's **Spec Kit** — a specification-driven development framework — with CoreStory's architecture-grounded SDD workflow. Read the main playbook first. It defines the six-phase methodology (Ground, Specify, Validate, Plan, Implement, Verify & Capture) that this guide builds on. This document covers only the Spec Kit-specific integration points: where Spec Kit commands slot into each phase, how its artifact system works alongside CoreStory conversations, and practical patterns for combining the two. **The relationship:** CoreStory provides architectural grounding. Spec Kit provides structured artifact generation. CoreStory tells you *what the architecture actually is*; Spec Kit gives you a framework for *writing it down* in a consistent, machine-readable format. Neither replaces the other. **When to use Spec Kit + CoreStory:** Projects that benefit from persistent, file-based specification artifacts — particularly teams that want version-controlled specs in their repository alongside the code. Spec Kit's `.specify/memory/` directory gives you a structured artifact trail; CoreStory conversations give you the architectural reasoning behind those artifacts. **When to skip Spec Kit:** If you don't need file-based spec artifacts — if the CoreStory conversation thread is sufficient as your specification record — the main playbook's workflow works standalone. Spec Kit adds value when you want specs committed to the repo, reviewed in PRs, or referenced across multiple features via a shared constitution. *** ## Prerequisites Everything from the main [Spec-Driven Development](/playbooks/spec-driven-development) playbook, plus: **Install Spec Kit:** ```bash theme={null} # Install with uv (recommended) uv tool install specify-cli --from git+https://github.com/github/spec-kit.git # Verify installation specify --version # Check system requirements specify check ``` **Initialize in your project:** ```bash theme={null} # New project specify init my-project --ai claude # or: specify init my-project --ai copilot # or: specify init my-project --ai cursor # Existing project (current directory) specify init . --ai claude # or: specify init --here --ai claude ``` Spec Kit supports a growing list of agents: `claude`, `copilot`, `cursor-agent`, `gemini`, `qwen`, `opencode`, `codex`, `windsurf`, and others. Run `specify init --help` for the current list. **Verify:** Ask your agent to "List my CoreStory projects" (MCP connection) and check that `.specify/` exists in the project root (Spec Kit initialization). *** ## How the Workflows Map Together The main playbook has six phases. Spec Kit has five commands. Here's how they align: | Main Playbook Phase | Spec Kit Command | Integration Pattern | | -------------------------- | ---------------------------------- | -------------------------------------------------------- | | Phase 1 — Ground | `/speckit.constitution` | CoreStory findings feed the constitution | | Phase 2 — Specify | `/speckit.specify` | Delta spec constrains the Spec Kit specification | | Phase 3 — Validate | *(no Spec Kit equivalent)* | CoreStory-only — validate the `.specify` artifacts | | Phase 4 — Plan | `/speckit.plan` + `/speckit.tasks` | Validated spec feeds planning and task breakdown | | Phase 5 — Implement | `/speckit.implement` | Standard TDD implementation | | Phase 6 — Verify & Capture | *(no Spec Kit equivalent)* | CoreStory-only — verify invariants and capture knowledge | The critical insight: **Phases 3 and 6 have no Spec Kit equivalent.** These are CoreStory-only phases — architectural validation and invariant verification. This is the gap that CoreStory fills. Spec Kit structures the artifacts; CoreStory validates them against reality. ### Spec Kit Artifacts Spec Kit stores its artifacts in `.specify/memory/`: | Artifact | Location | Created By | | -------------- | ------------------------------------------ | ----------------------- | | Constitution | `.specify/memory/constitution.md` | `/speckit.constitution` | | Feature spec | `.specify/memory/features/{name}/spec.md` | `/speckit.specify` | | Technical plan | `.specify/memory/features/{name}/plan.md` | `/speckit.plan` | | Task breakdown | `.specify/memory/features/{name}/tasks.md` | `/speckit.tasks` | These files persist across sessions and are version-controlled. The agent references them in subsequent phases. CoreStory insights get embedded into the artifacts, giving them architectural grounding that persists in the repo. *** ## Phase-by-Phase Integration Follow the main playbook for the full workflow. This section covers only the Spec Kit-specific additions at each phase. ### Phase 1: Ground → Constitution After completing the main playbook's Phase 1 grounding queries (architectural patterns, existing services, invariants, design history), feed the findings into Spec Kit's constitution command: ``` /speckit.constitution Context from CoreStory codebase analysis: Architecture: [paste architectural patterns from CoreStory] Conventions: [paste naming, file organization, error handling patterns] Invariants: [paste system invariants and business rules] Technology decisions: [paste stack decisions and rationale] Testing: [paste testing strategies and coverage expectations] Generate a constitution grounded in these actual codebase patterns, not generic best practices. Reference specific files and patterns. ``` **Output:** `.specify/memory/constitution.md` — a constitution with specific file references, real patterns, and actual constraints. **Spec Kit without CoreStory** produces constitutions with generic guidance like "follow clean code practices." **Spec Kit with CoreStory** produces constitutions that reference `UserService` by name, specify that all async operations use the `TaskQueue` pattern, and note that soft deletes are mandatory for audit-sensitive models. The constitution is a living document. After completing features, ask CoreStory whether new patterns emerged that should be captured, and update the constitution accordingly. ### Phase 2: Specify → Specification After the main playbook's Phase 2 (writing the delta specification with invariants, reuse, and delta sections), use Spec Kit to structure the output: ``` /speckit.specify [Feature description] Context from CoreStory-grounded specification: Invariants (must NOT change): [paste invariants from Phase 2] Existing components to reuse: [paste reuse section from Phase 2] Delta — new/modified components: [paste delta section from Phase 2] Acceptance criteria: [paste criteria from Phase 2] Generate a specification that references these actual components and follows the constitution's established patterns. ``` **Output:** `.specify/memory/features/{name}/spec.md` — a specification that inherits the delta structure from the main playbook. ### Phase 3: Validate (CoreStory Only) Spec Kit has no validation command. This is the gap. After Spec Kit generates the specification artifact, submit it to CoreStory for architectural pre-mortem — exactly as described in the main playbook's Phase 3. Paste the contents of `.specify/memory/features/{name}/spec.md` into the CoreStory query: ``` Send CoreStory message: "I've generated this specification using Spec Kit. [Paste spec.md contents] Validate against our architecture: 1. Does anything conflict with existing patterns? 2. Are there missing dependencies or integration points? 3. What failure modes should I address? 4. Does the spec correctly reference existing components?" ``` If validation finds issues, update the spec artifact directly and re-run `/speckit.specify` if the changes are substantial, or edit `.specify/memory/features/{name}/spec.md` directly for minor corrections. ### Phase 4: Plan → Plan + Tasks After validation, use Spec Kit's planning and task commands with CoreStory's file-level mapping: ``` /speckit.plan CoreStory validation results: - Confirmed patterns: [list] - Existing services to leverage: [list with file paths] - Files to create: [list with exact paths from CoreStory] - Files to modify: [list with specific sections] - Implementation order: [dependency ordering from CoreStory] - Testing approach: [test patterns from CoreStory] ``` Then break the plan into tasks: ``` /speckit.tasks Task ordering from CoreStory analysis: - Critical path: [ordered list] - Parallel tracks: [groups that can run simultaneously] - Integration test checkpoints: [where to validate] ``` **Outputs:** `.specify/memory/features/{name}/plan.md` and `.specify/memory/features/{name}/tasks.md`. ### Phase 5: Implement Run `/speckit.implement` and let the agent follow the task list. The main playbook's Phase 5 applies in full — write failing tests, implement in dependency order, validate with CoreStory at each step. The Spec Kit task artifacts provide structured checklists. CoreStory provides real-time validation during implementation. They complement each other. ### Phase 6: Verify & Capture (CoreStory Only) Spec Kit has no verification or capture command. This is the other gap. Follow the main playbook's Phase 6 in full: verify spec compliance with CoreStory, verify invariant preservation, commit with context, rename the CoreStory conversation. The Spec Kit artifacts in `.specify/memory/` persist in the repo; the CoreStory conversation persists as the architectural reasoning record. *** ## Agent Configuration The main playbook's Agent Implementation Guides cover the major agentic harnesses end-to-end. To add Spec Kit awareness, append the matching content below to your harness's existing CoreStory configuration. The four most common harnesses are shown — if you're on a different harness, append the relevant Markdown content to wherever your harness loads workflow context (see the install conventions in the main playbook). The skill file shown below is plain markdown. The workflow it encodes works in any agentic harness — only the install location differs. Common conventions: | Harness | Install location | | --------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Claude Code** | `.claude/skills//SKILL.md` — Claude loads the body when the YAML `description` matches the task | | **GitHub Copilot** | Append to `.github/copilot-instructions.md` for repo-wide instructions, or save as `.github/instructions/.instructions.md` with an `applyTo` glob for path-scoped use | | **Cursor** | `.cursor/rules/.mdc` with a `description` field for auto-attach (use `globs` for path-scoped or `alwaysApply: true` for every session) | | **Factory.ai** | `.factory/droids/.md` (project) or `~/.factory/droids/.md` (personal); Factory loads it as a custom Droid | | **Aider** | `CONVENTIONS.md` at repo root, loaded with `aider --read CONVENTIONS.md` — or add it to the `read:` list in `.aider.conf.yml` for automatic loading | | **Codex / `AGENTS.md` harnesses** | Append the content to `AGENTS.md` at your repository root | | **Custom runtime** | Load the markdown into your agent's system prompt, rules file, or wherever it consumes workflow context | Want a single install that works across the most harnesses? Append the content to `AGENTS.md` at your repository root. The [`AGENTS.md` spec](https://agents.md/) 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. ### Claude Code — Skill File Addition Append to `.claude/skills/spec-driven-dev/SKILL.md` (after the main playbook's skill content): ```markdown theme={null} ## Spec Kit Integration (Optional) **If you do not detect that you have access to CoreStory (e.g., `list_projects` fails or is unavailable), ask the user to verify that their MCP or API connection is properly configured and that this repository has been ingested. If the user has not yet created a CoreStory account, direct them to create one and upload their repo at [app.corestory.ai](https://app.corestory.ai).** If `.specify/` directory exists, integrate Spec Kit commands: - Phase 1: After CoreStory grounding → run `/speckit.constitution` - Phase 2: After delta spec → run `/speckit.specify` with invariants/reuse/delta - Phase 3: Validate `.specify/memory/features/{name}/spec.md` with CoreStory - Phase 4: After CoreStory mapping → run `/speckit.plan` then `/speckit.tasks` - Phase 5: Run `/speckit.implement` with CoreStory validation at each step Pattern: CoreStory BEFORE Spec Kit at every phase. Spec Kit structures the output. CoreStory validates the content. ``` ### GitHub Copilot — Instructions Addition Append to `.github/copilot-instructions.md`: ```markdown theme={null} ### Spec Kit Integration **If you do not detect that you have access to CoreStory (e.g., `list_projects` fails or is unavailable), ask the user to verify that their MCP or API connection is properly configured and that this repository has been ingested. If the user has not yet created a CoreStory account, direct them to create one and upload their repo at [app.corestory.ai](https://app.corestory.ai).** If Spec Kit is initialized (`.specify/` exists), use Spec Kit commands to structure outputs at each phase. Always query CoreStory BEFORE running each Spec Kit command. CoreStory provides grounding; Spec Kit provides structure. Phase mapping: Ground → `/speckit.constitution`, Specify → `/speckit.specify`, Plan → `/speckit.plan` + `/speckit.tasks`, Implement → `/speckit.implement`. Validate and Verify phases are CoreStory-only (no Spec Kit equivalent). ``` ### Cursor — Rule Addition Append to `.cursor/rules/spec-driven-dev.mdc`: ```markdown theme={null} ## Spec Kit Integration **If you do not detect that you have access to CoreStory (e.g., `list_projects` fails or is unavailable), ask the user to verify that their MCP or API connection is properly configured and that this repository has been ingested. If the user has not yet created a CoreStory account, direct them to create one and upload their repo at [app.corestory.ai](https://app.corestory.ai).** If `.specify/` directory exists, integrate Spec Kit commands after CoreStory queries: - Phase 1: CoreStory grounding → `/speckit.constitution` - Phase 2: Delta spec → `/speckit.specify` - Phase 3: CoreStory validation of `.specify` artifacts (no Spec Kit command) - Phase 4: CoreStory mapping → `/speckit.plan` → `/speckit.tasks` - Phase 5: `/speckit.implement` with CoreStory validation - Phase 6: CoreStory verification (no Spec Kit command) Always: CoreStory BEFORE Spec Kit. Spec Kit structures. CoreStory validates. ``` ### Factory.ai — Droid Addition Append to the droid's instructions in `.factory/droids/spec-driven-dev.md`: ```markdown theme={null} ## Spec Kit Integration **If you do not detect that you have access to CoreStory (e.g., `list_projects` fails or is unavailable), ask the user to verify that their MCP or API connection is properly configured and that this repository has been ingested. If the user has not yet created a CoreStory account, direct them to create one and upload their repo at [app.corestory.ai](https://app.corestory.ai).** If `.specify/` directory exists, run Spec Kit commands after CoreStory queries: - Phase 1 → `/speckit.constitution` - Phase 2 → `/speckit.specify` - Phase 4 → `/speckit.plan` + `/speckit.tasks` - Phase 5 → `/speckit.implement` Phases 3 and 6 are CoreStory-only. Always query CoreStory BEFORE Spec Kit. ``` *** ## Tips **CoreStory before Spec Kit at every phase.** The pattern is always: query CoreStory → get grounded context → feed context into Spec Kit command. Never run a Spec Kit command without CoreStory context first. **The constitution is your highest-leverage artifact.** A grounded constitution improves every subsequent Spec Kit command because Spec Kit references it automatically. Invest the most CoreStory query time here. **Update the constitution after features ship.** After completing a feature, ask CoreStory: "Did this implementation introduce new patterns that should be captured?" Feed learnings back into `.specify/memory/constitution.md`. **Version-control Spec Kit artifacts.** Commit `.specify/memory/` to the repo. This gives you PR-reviewable specs and a historical record of feature specifications alongside the code. **Use CoreStory conversations for the "why," Spec Kit artifacts for the "what."** The spec artifact says what will be built. The CoreStory conversation explains why those decisions were made, what alternatives were considered, and what architectural constraints shaped the design. *** ## Troubleshooting **Spec Kit commands not available.** Verify Spec Kit is initialized: check for `.specify/` in the project root. If missing, run `specify init --here --ai [your-agent]`. Ensure you launched the agent from the initialized project directory. **Constitution is too generic despite CoreStory queries.** Run CoreStory queries separately before `/speckit.constitution`. Review responses, extract the most specific details (file names, class names, patterns), and paste them directly into the constitution prompt. Generic input produces generic output. **Spec Kit plan proposes creating services that already exist.** This means Phase 3 (Validate) was skipped or insufficient. Submit the plan to CoreStory and ask specifically: "What existing services should this feature leverage instead of creating new ones?" Update the plan artifacts. **Spec Kit artifacts and CoreStory conversation diverge.** The CoreStory conversation is the source of truth for architectural reasoning. If the Spec Kit artifacts drift (e.g., someone edits them without CoreStory validation), re-run the validation phase. Paste the updated artifact into CoreStory and ask for a fresh architectural check. **All other issues** — CoreStory generic responses, project not found, agent not following the workflow — are covered in the main [Spec-Driven Development](/playbooks/spec-driven-development) playbook's Troubleshooting section. # Behavioral Test Coverage Source: https://docs.corestory.ai/playbooks/test-generation/behavioral-test-coverage Systematically generate behavioral test coverage from CoreStory's specification intelligence — acceptance criteria, invariants, business rules, state transitions, and edge cases — using AI coding agents. ## 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](/playbooks/feature-implementation) playbook, which includes TDD as Phase 4. If you're verifying behavioral equivalence between legacy and modernized code, use the [Behavioral Verification](/playbooks/modernization/behavioral-verification) playbook. If you need to extract and document business rules before generating tests, use the [Business Rules Extraction](/playbooks/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](/playbooks/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](/playbooks/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](/playbooks/modernization/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](/getting-started/mcp-server-setup)) * 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](/playbooks/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 | Phase | Name | Purpose | CoreStory Role | | ----- | ---------------------------- | --------------------------------------------------------------------------------------------------- | ------------------------------------- | | 1 | Setup & Scoping | Select project, create conversation, define generation scope | Setup | | 2 | Behavioral Inventory | Extract testable specifications: acceptance criteria, invariants, business rules, state transitions | Expert | | 3 | Test Convention Discovery | Understand the project's existing test patterns, framework, fixtures, and structure | Expert + Navigator | | 4 | Coverage Gap Analysis | Map behavioral inventory against existing tests to identify what's missing | Navigator | | 5 | Test Generation & Validation | Generate test code, run it, verify tests are meaningful | — (local code + CoreStory validation) | | 6 | Completion & Capture | Review coverage, commit tests, rename conversation | Knowledge capture | 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 | Tool | Phase(s) | Purpose | | ---------------------- | ---------- | ------------------------------------------------------------------------- | | `list_projects` | 1 | Find the target project | | `create_conversation` | 1 | Create a persistent conversation for the generation session | | `send_message` | 2, 3, 4, 5 | Query CoreStory for specifications, test conventions, and validation | | `get_project_prd` | 2 | Skim PRD structure for domain vocabulary and acceptance criteria sections | | `get_project_techspec` | 2 | Skim TechSpec for data model constraints and architectural invariants | | `list_conversations` | 1 | Check for prior Business Rules Extraction sessions to build on | | `get_conversation` | 1 | Resume or consume a prior extraction session | | `rename_conversation` | 6 | Mark the conversation as resolved | **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.** ``` Tool: list_projects ``` 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.** ``` Tool: list_conversations Parameters: project_id = ``` 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.** ``` Tool: create_conversation Parameters: project_id = title = "Test Generation — " ``` 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: | Scope | When to Use | Expected Output | | ------------- | ----------------------------------------------------------- | ----------------------------------------- | | Single module | You need tests for one specific area (e.g., payments, auth) | 10–30 test cases | | Single domain | You need tests across a domain (e.g., all e-commerce rules) | 30–80 test cases | | Full system | You need comprehensive behavioral coverage | 80+ test cases, done in multiple sessions | 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: ``` Tool: get_conversation Parameters: project_id = conversation_id = ``` 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.** ``` Tool: send_message Query: "What are the documented acceptance criteria for [module/domain]? I need the specific, testable conditions — input/output expectations, success/failure criteria, and boundary conditions. Group them by feature or user story." ``` Acceptance criteria are the most directly testable specifications — they often map 1:1 to test cases. **Step 2.2: Query for validation rules.** ``` Tool: send_message Query: "What validation rules exist for [entity/module]? Include input validation, required fields, format constraints, uniqueness checks, cross-field validation, and error messages returned on failure." ``` 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.** ``` Tool: send_message Query: "What are the state transitions for [entity, e.g., orders, user accounts, subscriptions]? For each transition: what triggers it, what preconditions must hold, what postconditions are guaranteed, and what invalid transitions should be rejected?" ``` 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.** ``` Tool: send_message Query: "What authorization and permission rules govern [feature area]? Who can perform which operations? What role checks exist? What happens when an unauthorized user attempts each operation?" ``` 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.** ``` Tool: send_message Query: "What invariants must always hold for [entity/module]? What are the known edge cases — null inputs, maximum values, concurrent access, boundary conditions? What happens when [specific edge case scenario]?" ``` 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.** ``` Tool: send_message Query: "What behaviors in [module] are implemented in code but not documented in the PRD or acceptance criteria? What implicit rules exist — error handling conventions, fallback behaviors, default values, side effects of operations?" ``` 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.** ``` Tool: send_message Query: "What calculations, transformations, or derived values exist in [module]? What are the inputs, formulas, rounding rules, and expected outputs? Are there tiered or conditional calculation paths?" ``` 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.** ``` Tool: send_message Query: "What testing frameworks, libraries, and tools does this project use? How are tests organized — directory structure, file naming conventions, test class naming? Are there separate unit, integration, and end-to-end test directories?" ``` 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.** ``` Tool: send_message Query: "How does this project set up test data? What fixture patterns are used — factories, fixtures, builders, shared setup? Are there shared test utilities or base test classes? How are database state and external dependencies handled in tests?" ``` 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.** ``` Tool: send_message Query: "What assertion styles does this project use? What mocking framework and patterns are standard? Are there custom assertions or test helpers? What's the convention for testing error conditions and exceptions?" ``` **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.** ``` Tool: send_message Query: "What tests currently exist for [module/domain]? What behaviors are covered? What test files correspond to the source files we identified in Phase 2?" ``` **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: | Status | Meaning | Action | | --------------------- | -------------------------------------------------------------------- | --------------------------- | | **Covered** | Existing tests adequately verify this behavior | Skip — no new test needed | | **Partially covered** | Tests exist but miss edge cases, error paths, or boundary conditions | Generate supplemental tests | | **Uncovered** | No tests verify this behavior | Generate full test coverage | **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: | Failure Type | Meaning | Action | | ----------------- | ----------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | | Setup failure | Test infrastructure is wrong (bad imports, missing fixtures, incorrect setup) | Fix the test mechanics — this is a convention mismatch, not a specification issue | | Assertion failure | The code doesn't match the specification | Investigate: is the spec wrong or is the code wrong? This is valuable discovery — flag it for human review | | Runtime error | Test triggers an error path not anticipated in the specification | Add to the behavioral inventory as a discovered edge case | **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: ``` Tool: send_message Query: "I've written this test for [behavioral specification]: [paste test code] Is this test actually verifying the intended behavior? Could it pass even if the underlying rule were violated? What would make this test more robust?" ``` 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: ``` Tool: send_message Query: "For the behavior '[specific behavior]', what edge cases should I test? What boundary conditions, null inputs, concurrent scenarios, or unusual input combinations could cause different 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: ``` Behavioral specifications inventoried: [count] Previously covered: [count] New tests generated: [count] Remaining uncovered: [count] (with reasons — e.g., "requires integration environment", "specification too vague", "deferred to next session") ``` **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: ``` Test: Add behavioral test coverage for [module/domain] Coverage: - [X] acceptance criteria tests from PRD user stories - [X] validation rule tests for [entities] - [X] state transition tests for [entity lifecycle] - [X] authorization tests for [feature area] - [X] invariant tests for [data model constraints] - [X] edge case tests for [specific scenarios] Behavioral specifications from CoreStory conversation [conversation-id]. Total new tests: [count] All existing tests still pass — no regressions. References: - CoreStory conversation: [conversation-id] - Business Rules Inventory: [conversation-id, if applicable] ``` **Step 6.4: Rename the conversation.** ``` Tool: rename_conversation Parameters: project_id = conversation_id = title = "RESOLVED — Test Generation — " ``` 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: | Query | Test Quality | | ------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------- | | "What should I test in the order module?" | Generic, shallow tests | | "What validation rules exist for order submission, including minimum order amounts, inventory checks, and payment method validation?" | Precise, high-value tests with specific assertions | 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: ```python theme={null} def test_order_rejected_when_below_minimum_amount(): order = create_order(total=4.99) result = submit_order(order) assert result.status == "rejected" assert "minimum order amount" in result.error ``` An implementation test asserts *how* the system does it: ```python theme={null} def test_order_calls_minimum_check_validator(): order = create_order(total=4.99) with mock.patch("OrderValidator.check_minimum") as mock_check: mock_check.return_value = False submit_order(order) mock_check.assert_called_once_with(4.99) ``` 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: ``` Tool: send_message Query: "For the behavior 'errors are handled gracefully in [module]', what specifically happens? What error types exist? What does the user see? What is logged? What state changes occur (or don't)?" ``` 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](/playbooks/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: | Rule Type | Test Pattern | | ---------------- | ----------------------------------------------------------------------------- | | Validation | Given invalid input → assert rejection with specific error | | Authorization | Given unauthorized user/role → assert access denied | | State Transition | Given entity in state A → perform action → assert state B + postconditions | | Calculation | Given inputs → assert output matches formula/expected value | | Constraint | After any operation → assert invariant still holds | | Workflow | Given preconditions → execute full workflow → assert end state + side effects | Reference the BR-XXX IDs in test docstrings for traceability: ```python theme={null} def test_password_minimum_length_enforced(): """BR-012: Password must be 8–12 characters.""" result = register_user(password="short") assert result.status == 400 assert "password" in result.errors ``` ### 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: ```python theme={null} @pytest.mark.parametrize("password,expected_valid", [ ("short", False), # Below minimum (8 chars) ("exactly8", True), # At minimum boundary ("twelve12char", True), # At maximum boundary ("thirteenchars", False), # Above maximum (12 chars) ("noDigit!!", False), # Missing digit ("noSpecial1", False), # Missing special char ("Valid1Pass!", True), # All criteria met ]) def test_password_validation(password, expected_valid): """BR-012: Password must be 8–12 chars, 1 digit, 1 special.""" result = validate_password(password) assert result.is_valid == expected_valid ``` 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: ``` Tool: send_message Query: "Give me the complete authorization matrix for [feature area]: which roles can perform which operations. Format as a matrix with roles as rows and operations as columns, marking each as allowed or denied." ``` This produces a matrix that maps directly to parameterized tests: ```python theme={null} @pytest.mark.parametrize("role,operation,expected", [ ("admin", "create_user", True), ("admin", "delete_user", True), ("manager", "create_user", True), ("manager", "delete_user", False), ("viewer", "create_user", False), ("viewer", "delete_user", False), ]) def test_authorization_matrix(role, operation, expected): user = create_user(role=role) result = perform_operation(user, operation) if expected: assert result.status != 403 else: assert result.status == 403 ``` ### State Transition Testing For entities with defined lifecycles, generate tests for both valid and invalid transitions: ``` Tool: send_message Query: "For [entity], give me the complete state machine: all valid transitions (from_state → to_state with trigger) and all invalid transitions that should be rejected. What postconditions are guaranteed after each valid transition?" ``` Generate positive tests for each valid transition and negative tests for representative invalid transitions: ```python theme={null} def test_order_can_transition_from_pending_to_confirmed(): """Valid transition: PENDING → CONFIRMED via payment_received.""" order = create_order(status="pending") order.receive_payment(amount=order.total) assert order.status == "confirmed" assert order.payment_received_at is not None # postcondition def test_order_cannot_transition_from_delivered_to_pending(): """Invalid transition: DELIVERED → PENDING is not allowed.""" order = create_order(status="delivered") with pytest.raises(InvalidTransitionError): order.revert_to_pending() ``` ### 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: | Harness | Install location | | --------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Claude Code** | `.claude/skills//SKILL.md` — Claude loads the body when the YAML `description` matches the task | | **GitHub Copilot** | Append to `.github/copilot-instructions.md` for repo-wide instructions, or save as `.github/instructions/.instructions.md` with an `applyTo` glob for path-scoped use | | **Cursor** | `.cursor/rules/.mdc` with a `description` field for auto-attach (use `globs` for path-scoped or `alwaysApply: true` for every session) | | **Factory.ai** | `.factory/droids/.md` (project) or `~/.factory/droids/.md` (personal); Factory loads it as a custom Droid | | **Aider** | `CONVENTIONS.md` at repo root, loaded with `aider --read CONVENTIONS.md` — or add it to the `read:` list in `.aider.conf.yml` for automatic loading | | **Codex / `AGENTS.md` harnesses** | Append the content to `AGENTS.md` at your repository root | | **Custom runtime** | Load the markdown into your agent's system prompt, rules file, or wherever it consumes workflow context | Want a single install that works across the most harnesses? Append the content to `AGENTS.md` at your repository root. The [`AGENTS.md` spec](https://agents.md/) 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: ```bash theme={null} claude mcp add --transport http corestory https://app.corestory.ai/mcp/your-org-slug-123456789 ``` Verify the connection works: ``` "List my CoreStory projects" ``` **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: ```bash theme={null} mkdir -p .claude/skills/generate-tests ``` 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: ```bash theme={null} git add .claude/skills/generate-tests/SKILL.md git commit -m "Add CoreStory test generation skill" ``` #### Usage The skill activates automatically when Claude Code detects test generation requests: ``` "Generate tests for the order processing module" "Add behavioral test coverage for authentication" "Create tests from the business rules inventory" ``` #### 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`: ```markdown theme={null} --- name: generate-tests description: > Generate comprehensive behavioral test coverage using CoreStory's code intelligence. Use when asked to generate tests, add test coverage, create tests from business rules, or improve test coverage for a module or domain. Do NOT use for TDD during feature implementation — use the implement-feature skill instead. --- # CoreStory Test Generation Systematically generate behavioral tests using CoreStory for specification extraction and the local codebase for convention matching. **If you do not detect that you have access to CoreStory (e.g., `list_projects` fails or is unavailable), ask the user to verify that their MCP or API connection is properly configured and that this repository has been ingested. If the user has not yet created a CoreStory account, direct them to create one and upload their repo at [app.corestory.ai](https://app.corestory.ai).** ## Prerequisites Check Before starting, verify: 1. CoreStory MCP server is connected (`list_projects` returns results) 2. Target project has completed ingestion 3. A test framework is configured in the project ## Workflow Execute all six phases in order. Do not skip phases. ### PHASE 1: Setup & Scoping 1. Call `list_projects` to find the target project 2. Call `list_conversations` — check for prior Business Rules Extraction or Test Generation conversations 3. Call `create_conversation` with title "Test Generation — " 4. Confirm scope with user (single module, domain, or full system) Report: scope, conversation ID, any prior work found. ### PHASE 2: Behavioral Inventory (Expert) If a Business Rules Extraction conversation exists, consume it via `get_conversation`. Otherwise, extract from scratch. Send these queries via `send_message`, specific to the scoped module: 1. "What are the documented acceptance criteria for [module]?" 2. "What validation rules exist for [entity/module]?" 3. "What state transitions exist for [entity]?" 4. "What authorization rules govern [feature area]?" 5. "What invariants must always hold for [entity/module]?" 6. "What implicit/undocumented behaviors exist in [module]?" 7. "What calculations or transformations exist in [module]?" IMPORTANT: Use specific entity/module names in every query. NOTE: Do NOT call `get_project_prd` or `get_project_techspec` and try to read them in full. Query CoreStory about their contents via `send_message` instead. Report: categorized behavioral inventory with count per category. ### PHASE 3: Test Convention Discovery Query CoreStory via `send_message`: 1. "What test framework, directory structure, and naming conventions does this project use?" 2. "What fixture, setup, and mock patterns are standard?" 3. "What assertion styles and test helpers exist?" Then read 2–3 existing test files locally to verify and use as templates. Report: framework, conventions, reference files identified. ### PHASE 4: Coverage Gap Analysis 1. Query CoreStory: "What tests currently exist for [module]?" 2. Read existing test files locally 3. Cross-reference behavioral inventory vs. existing tests 4. Categorize each behavior: Covered / Partially Covered / Uncovered 5. Prioritize gaps: business criticality > risk > specificity > testability **Present gap analysis to user for review before proceeding.** Report: gap count, priority list, request user confirmation. ### PHASE 5: Test Generation & Validation For each prioritized gap: 1. Write test matching project conventions exactly 2. Include docstring linking to behavioral specification 3. Run the test — verify it passes 4. For high-priority tests: validate with CoreStory that the test is actually verifying the intended behavior 5. Generate edge case tests for critical behaviors After each batch, run the full test suite — no regressions allowed. ### PHASE 6: Completion 1. Map generated tests back to behavioral inventory — report coverage 2. Ensure tests are in correct directories with correct naming 3. Commit with structured message (specification source, test count, coverage summary) 4. Rename conversation → "RESOLVED — Test Generation — " ## Key Principles - Specification before Code — always - Match existing conventions exactly - Behavioral tests, not implementation tests - A failing generated test is discovery, not failure - Specific queries produce specific tests ``` *** ### 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:** ```bash theme={null} git add .github/ git commit -m "Add CoreStory test generation instructions" ``` #### Usage With custom instructions active, Copilot Chat applies the workflow automatically when you ask about test generation: ``` "Generate behavioral tests for the order processing module" ``` If using a prompt file: ``` @workspace /generate-tests Add test coverage for authentication rules ``` #### 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): ```markdown theme={null} ## Test Generation with CoreStory When asked to generate tests, add test coverage, or create behavioral tests, execute this workflow using CoreStory's MCP tools. **If you do not detect that you have access to CoreStory (e.g., `list_projects` fails or is unavailable), ask the user to verify that their MCP or API connection is properly configured and that this repository has been ingested. If the user has not yet created a CoreStory account, direct them to create one and upload their repo at [app.corestory.ai](https://app.corestory.ai).** ### CoreStory MCP Tools - `CoreStory:list_projects` — list available projects - `CoreStory:create_conversation` — start test generation thread - `CoreStory:send_message` — query code intelligence - `CoreStory:list_conversations` — find prior Business Rules Extraction sessions - `CoreStory:get_conversation` — consume prior extraction work - `CoreStory:rename_conversation` — mark as completed When instructions say "Query CoreStory", use `CoreStory:send_message`. ### Phase 1: Setup 1. Select CoreStory project, check for prior Business Rules Extraction 2. Create conversation: "Test Generation — " ### Phase 2: Behavioral Inventory Query CoreStory for: acceptance criteria, validation rules, state transitions, authorization rules, invariants, implicit behaviors, calculations. Use specific entity/module names in every query. ### Phase 3: Test Convention Discovery Query CoreStory + inspect local test files: framework, structure, fixtures, mocks, assertion style. Identify reference test files as templates. ### Phase 4: Coverage Gap Analysis Cross-reference inventory vs. existing tests. Present gaps to user before generating. Prioritize by business criticality. ### Phase 5: Test Generation Write tests matching project conventions exactly. Run and verify. Validate high-priority tests with CoreStory. No regressions allowed. ### Phase 6: Completion Report coverage, commit tests, rename conversation "RESOLVED". ### Key Principles - Specification before Code - Match existing conventions exactly - Behavioral tests, not implementation tests - Specific queries produce specific tests ``` *** ### 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/`: ```bash theme={null} mkdir -p .cursor/rules ``` Create `.cursor/rules/generate-tests.mdc` with the content from the rule file below. 3. **Commit to version control:** ```bash theme={null} git add .cursor/rules/ git commit -m "Add CoreStory test generation rule" ``` #### Usage With `alwaysApply: true`, the rule activates automatically when Cursor detects test generation context. Or trigger it explicitly: ``` "Use CoreStory to generate behavioral tests for the payment module" ``` #### 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`: ```markdown theme={null} --- description: Generate behavioral test coverage using CoreStory's code intelligence. Activates for test generation, coverage improvement, and behavioral testing workflows. globs: alwaysApply: true --- # Test Generation with CoreStory Generate comprehensive behavioral tests using CoreStory for specification extraction and local code for convention matching. **If you do not detect that you have access to CoreStory (e.g., `list_projects` fails or is unavailable), ask the user to verify that their MCP or API connection is properly configured and that this repository has been ingested. If the user has not yet created a CoreStory account, direct them to create one and upload their repo at [app.corestory.ai](https://app.corestory.ai).** ## CoreStory MCP Tools - `CoreStory:list_projects` — list available projects - `CoreStory:create_conversation` — start test generation thread - `CoreStory:send_message` — query code intelligence - `CoreStory:list_conversations` — find prior Business Rules Extraction sessions - `CoreStory:get_conversation` — consume prior work - `CoreStory:rename_conversation` — mark as completed When instructions say "Query CoreStory", use `CoreStory:send_message`. ## Phase 1: Setup 1. Select CoreStory project, check for prior Business Rules Extraction 2. Create conversation: "Test Generation — " 3. Confirm scope with user ## Phase 2: Behavioral Inventory Query CoreStory for: acceptance criteria, validation rules, state transitions, authorization rules, invariants, implicit behaviors, calculations. IMPORTANT: Use specific entity/module names in every query. Broad queries produce shallow specifications that produce shallow tests. NOTE: Do NOT try to read the full PRD or TechSpec. Query CoreStory about their contents via `send_message` instead. ## Phase 3: Test Convention Discovery 1. Query CoreStory for test framework, structure, fixtures, mocks 2. Read 2–3 existing test files locally as templates 3. Match conventions exactly in all generated tests ## Phase 4: Coverage Gap Analysis 1. Query CoreStory for existing test coverage 2. Inspect existing test files locally 3. Cross-reference behavioral inventory vs. existing tests 4. Present prioritized gap list to user for approval **Do not generate tests until user confirms the gap analysis.** ## Phase 5: Test Generation For each gap: 1. Write test matching project conventions 2. Include docstring linking to behavioral specification 3. Run test — verify it passes 4. Validate critical tests with CoreStory 5. Run full suite after each batch ## Phase 6: Completion 1. Report coverage against behavioral inventory 2. Commit with structured message 3. Rename conversation → "RESOLVED" ## Key Principles - Specification before Code — always - Match existing conventions exactly - Behavioral tests, not implementation tests - A failing assertion is discovery, not failure - Specific queries → specific tests ``` *** ### 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): ```bash theme={null} mkdir -p .factory/droids ``` Create `.factory/droids/generate-tests.md` with the content from the droid file below. 3. **Commit to version control:** ```bash theme={null} git add .factory/droids/ git commit -m "Add CoreStory test generation droid" ``` #### Usage Invoke the droid: ``` @generate-tests Add behavioral tests for the authentication module ``` Or describe the task naturally — Factory.ai routes to the appropriate droid: ``` "Generate test coverage for order processing" ``` #### Droid File Save as `.factory/droids/generate-tests.md`: ```yaml theme={null} name: generate-tests description: Generate comprehensive behavioral test coverage using CoreStory code intelligence and local convention matching instructions: | You generate behavioral tests from CoreStory's code intelligence: **If you do not detect that you have access to CoreStory (e.g., `list_projects` fails or is unavailable), ask the user to verify that their MCP or API connection is properly configured and that this repository has been ingested. If the user has not yet created a CoreStory account, direct them to create one and upload their repo at [app.corestory.ai](https://app.corestory.ai).** 1. Set up a CoreStory conversation for the test generation session 2. Check for prior Business Rules Extraction — consume if available 3. Extract behavioral specifications: acceptance criteria, validation rules, state transitions, authorization rules, invariants, implicit behaviors, calculations (use specific entity/module names) 4. Discover test conventions: framework, directory structure, fixtures, mocks, assertion style. Read existing test files as templates. 5. Map specifications against existing tests to find gaps. Present to user for approval before generating. 6. Generate tests matching project conventions exactly. Run and verify. Validate critical tests with CoreStory. Run full suite. 7. Report coverage, commit, rename conversation "RESOLVED" Key behaviors: - Specification before Code — extract what to test before looking at how - Match existing test conventions exactly — generated tests should be indistinguishable from hand-written tests - Generate behavioral tests that assert what the system does, not how - Treat failing assertions as discovery — flag for human review - Use specific entity/module names in all CoreStory queries ``` # E2E Test Generation Source: https://docs.corestory.ai/playbooks/test-generation/e2e-test-generation Generate end-to-end tests that verify critical user journeys against CoreStory's acceptance criteria and user story intelligence — from journey extraction through flakiness management. ## Overview End-to-end tests are the most expensive tests to write, the most fragile to maintain, and the most valuable when they work. They verify what users actually experience — complete journeys through the application stack, from UI interaction to database persistence and back. But most E2E suites are written reactively: a critical bug ships, someone writes a test to prevent regression, and over time the suite becomes a patchwork of incident responses with no systematic coverage of the journeys that matter most. This playbook teaches you how to use CoreStory to systematically identify, prioritize, and generate E2E tests for your application's critical user journeys. CoreStory acts as a **Journey Expert** — it knows the user stories, acceptance criteria, and critical paths from the PRD, and it knows the application's routing, API endpoints, and data flow from the codebase. The agent extracts journey specifications from CoreStory, discovers E2E test conventions from the local project, and generates tests that verify complete user flows against acceptance criteria. The primary deliverable is **executable E2E test code** that matches the project's existing E2E framework — Playwright, Cypress, Selenium, or whatever the team uses. Each test traces back to a user story or acceptance criterion, making coverage auditable and gaps visible. **How this relates to the Behavioral Test Coverage playbook:** The [Behavioral Test Coverage](/playbooks/test-generation/behavioral-test-coverage) playbook generates unit-level and integration-level tests for individual business rules, validation logic, and state transitions. This playbook generates journey-level tests that verify complete user flows across the full stack. They're complementary — behavioral tests catch logic bugs in specific rules; E2E tests catch integration failures, UI regressions, and broken flows that span multiple components. ### When to Use This Playbook * Critical user journeys (signup, checkout, onboarding) have no automated E2E coverage * You're preparing for a major release and need confidence that key flows work end-to-end * A UI or API overhaul requires regression tests for existing user journeys * You're onboarding to an unfamiliar application and want to understand and verify its primary flows * The existing E2E suite is a patchwork of incident-driven tests with no systematic coverage ### When to Skip This Playbook * You need to test individual business rules or validation logic (use the [Behavioral Test Coverage](/playbooks/test-generation/behavioral-test-coverage) playbook) * The application has no UI or user-facing API — there are no journeys to test * No E2E test framework is configured in the project and you don't want to set one up (this playbook generates tests for an existing framework, it doesn't bootstrap one) * The application is a CLI tool, library, or SDK — behavioral tests are more appropriate ## Prerequisites * Everything listed in the [parent playbook prerequisites](/playbooks/spec-driven-test-generation#prerequisites) * An E2E test framework configured in the project (Playwright, Cypress, Selenium, etc.) * A running or deployable test environment that E2E tests can execute against * (Recommended) Seed data or fixture strategy for the test environment * (Recommended) CI/CD pipeline that can run E2E tests *** ## How It Works ### The Workflow Phases | Phase | Name | Purpose | CoreStory Role | | ----- | ------------------------------- | ---------------------------------------------------------------------------- | ------------------------------------- | | 1 | Setup & Scoping | Select project, create conversation, define journey scope | Setup | | 2 | Journey Extraction | Extract critical user journeys, acceptance criteria, and happy/unhappy paths | Journey Expert | | 3 | E2E Convention Discovery | Understand the project's E2E framework, selectors, fixtures, and patterns | Expert + Navigator | | 4 | Journey Prioritization | Rank journeys by business criticality and existing coverage | Navigator | | 5 | Test Generation & Stabilization | Generate E2E tests, run them, address flakiness | — (local code + CoreStory validation) | | 6 | Completion & Capture | Review coverage, commit tests, rename conversation | Knowledge capture | ### HITL Gate > **After Phase 4 (Journey Prioritization):** Before generating E2E tests, a human should review the journey list and prioritization. E2E tests are expensive to maintain — generating tests for low-value journeys wastes ongoing maintenance effort. The human validates that the selected journeys are worth the investment. *** ## Step-by-Step Walkthrough ### Phase 1 — Setup & Scoping **Goal:** Establish the E2E test generation session and define the scope. **Step 1.1: Find the project.** ``` Tool: list_projects ``` **Step 1.2: Check for prior work.** ``` Tool: list_conversations Parameters: project_id = ``` Look for prior Test Generation or Business Rules Extraction conversations. A behavioral test generation session for the same module provides useful context about the application's rules and state transitions — E2E tests exercise these at the journey level. **Step 1.3: Create a conversation.** ``` Tool: create_conversation Parameters: project_id = title = "E2E Test Generation — " ``` Examples: * "E2E Test Generation — User Onboarding Journey" * "E2E Test Generation — Checkout & Payment Flows" * "E2E Test Generation — Core User Journeys (Full Suite)" **Step 1.4: Define scope.** | Scope | When to Use | Expected Output | | --------------- | --------------------------------------- | ---------------------------------------------- | | Single journey | One critical flow (e.g., checkout) | 3–8 test scenarios | | Journey cluster | Related flows (e.g., all auth journeys) | 8–15 test scenarios | | Core journeys | All business-critical user flows | 15–30 test scenarios, across multiple sessions | Start with a single high-value journey. E2E tests require more stabilization work than behavioral tests, so smaller batches are more practical. *** ### Phase 2 — Journey Extraction (Journey Expert) **Goal:** Extract the critical user journeys, their acceptance criteria, and the happy and unhappy paths for each. **Step 2.1: Query for user stories and journeys.** ``` Tool: send_message Query: "What are the primary user journeys for [feature area/application]? For each journey: who is the user, what is the goal, what are the steps from start to completion, and what acceptance criteria define success?" ``` CoreStory extracts these from the PRD's user stories and maps them to the application's routes, API endpoints, and UI components. **Step 2.2: Query for happy path details.** ``` Tool: send_message Query: "For the [specific journey, e.g., user registration] journey, walk me through the exact happy path: what does the user see at each step, what data do they enter, what API calls are made, what state changes occur, and what is the final confirmation the user sees?" ``` This produces the step-by-step flow that becomes the core E2E test. **Step 2.3: Query for unhappy paths and error states.** ``` Tool: send_message Query: "For the [specific journey], what are the failure scenarios? What happens when validation fails at each step? What error messages does the user see? What happens on network failure, timeout, or server error? Are there any partial completion states?" ``` Unhappy paths often reveal the most critical E2E test cases — they're where users get stuck and where the application is most likely to break. **Step 2.4: Query for cross-journey dependencies.** ``` Tool: send_message Query: "What preconditions must be met before [journey] can start? Does the user need to be authenticated? Does specific data need to exist? Are there feature flags or configuration that affects the flow? What other journeys feed into or follow from this one?" ``` This surfaces the test setup requirements — what state the application needs to be in before the E2E test can run. **Step 2.5: Query for data requirements.** ``` Tool: send_message Query: "What test data does [journey] require? What users, entities, or configuration must exist? Are there specific data states that trigger different paths (e.g., a user with vs. without a payment method, an order above vs. below a threshold)?" ``` Data requirements drive the fixture and seed strategy for E2E tests. **Expected output from Phase 2:** A journey inventory organized by user flow: * Journey name, user persona, and goal * Happy path steps with expected UI state at each step * Unhappy paths with error states and recovery flows * Preconditions and data requirements * Acceptance criteria for each journey *** ### Phase 3 — E2E Convention Discovery (Expert + Navigator) **Goal:** Understand the project's E2E test patterns so generated tests match existing conventions. **Step 3.1: Query for E2E framework and structure.** ``` Tool: send_message Query: "What E2E testing framework does this project use? How are E2E tests organized — directory structure, file naming, test grouping? Is there a separate E2E test directory? What configuration files exist for the E2E runner?" ``` The agent needs: framework (Playwright, Cypress, Selenium, Puppeteer, etc.), directory layout, configuration, and any custom runner setup. **Step 3.2: Query for page objects, selectors, and abstractions.** ``` Tool: send_message Query: "Does this project use page objects, component abstractions, or selector patterns for E2E tests? How are selectors defined — data-testid attributes, CSS selectors, XPath, accessibility roles? Are there shared helpers for common interactions (login, navigation, form filling)?" ``` Selector strategy is critical for E2E test stability. Generated tests must follow the existing approach. **Step 3.3: Query for fixture and environment patterns.** ``` Tool: send_message Query: "How does this project handle test data for E2E tests? Is there a seed script, factory pattern, API-based setup, or database snapshot approach? How is the test environment configured — local server, staging, Docker Compose? How are E2E tests authenticated (test users, tokens, cookies)?" ``` **Step 3.4: Verify conventions against local code.** Navigate to the E2E test directories and read 2–3 representative test files. Confirm CoreStory's description matches reality. Pay attention to: * How tests launch and configure the browser/runner * How authentication is handled in tests * How test data is created and cleaned up * How assertions verify page state (text content, element visibility, URL changes) * How tests handle waits, timeouts, and async operations * Whether tests run in parallel or serial **Expected output from Phase 3:** * E2E framework and runner configuration * Selector strategy (data-testid, roles, CSS, etc.) * Page object or abstraction patterns * Fixture/seed data approach * Authentication strategy for tests * 2–3 reference E2E test files to use as templates *** ### Phase 4 — Journey Prioritization (Navigator) **Goal:** Rank extracted journeys by value and identify existing coverage. **Step 4.1: Query for existing E2E coverage.** ``` Tool: send_message Query: "What E2E tests currently exist? What user journeys or flows do they cover? Are there any test files that correspond to the journeys identified in Phase 2?" ``` **Step 4.2: Inspect existing E2E tests locally.** Read the existing E2E test files to understand which journeys are already covered and how thoroughly. **Step 4.3: Prioritize journeys.** Rank uncovered or partially covered journeys by: 1. **Revenue impact** — Journeys that directly affect conversion, payment, or retention (checkout, signup, subscription management) 2. **User frequency** — Journeys that every user performs regularly (login, core workflow, search) 3. **Failure severity** — Journeys where failure means data loss, security exposure, or user lock-out 4. **Complexity** — Journeys with many steps, conditional paths, or cross-service interactions (higher value because they're harder to test manually) **Expected output from Phase 4:** A prioritized list of journeys with their coverage status and recommended test scenarios. > **HITL Gate:** Present the prioritized journey list to the human. E2E tests carry ongoing maintenance cost — confirm the selected journeys are worth the investment. *** ### Phase 5 — Test Generation & Stabilization **Goal:** Generate E2E tests for each prioritized journey, run them, and stabilize against flakiness. **Step 5.1: Generate the happy path test.** For each journey, start with the happy path. Using the journey specification from Phase 2, the E2E conventions from Phase 3, and the reference test files as templates, write the test. Each test should: * Follow the project's E2E file naming and organization conventions * Use the project's selector strategy (data-testid, roles, etc.) * Use the project's page object or abstraction patterns if they exist * Include a descriptive test name that references the journey and acceptance criteria * Set up required test data using the project's fixture approach * Clean up test data after execution (or use isolation patterns) **Step 5.2: Run the test and stabilize.** E2E tests fail for different reasons than behavioral tests. Common failure categories: | Failure Type | Meaning | Action | | ------------------ | ---------------------------------------------------------------- | --------------------------------------------------------------------------------- | | Selector not found | Element locator is wrong or page structure has changed | Fix the selector — use the project's selector strategy | | Timeout | Page load, API call, or animation took longer than expected | Add appropriate waits — prefer waiting for specific conditions over fixed delays | | State mismatch | Test data wasn't set up correctly or prior test left dirty state | Fix the fixture/setup — ensure test isolation | | Assertion failure | The journey doesn't behave as the specification describes | Investigate: is the spec wrong or is the application wrong? Flag for human review | | Flaky pass/fail | Test passes sometimes and fails other times | See the flakiness management section below | **Step 5.3: Generate unhappy path tests.** For each journey's critical unhappy paths (identified in Phase 2), generate tests that verify: * Validation errors display the correct messages * The user can recover from error states (fix input and retry) * Network failures are handled gracefully (error messages, retry options) * Partial completion states are handled (back button, refresh, timeout) Focus on the unhappy paths that users actually encounter — not every theoretical error combination. **Step 5.4: Validate tests are meaningful.** For high-priority journeys, validate with CoreStory: ``` Tool: send_message Query: "I've written this E2E test for the [journey] happy path: [paste test code] Does this test verify the acceptance criteria for this journey? Are there critical steps or assertions I'm missing? Would this test catch a real regression in this flow?" ``` **Step 5.5: Run the full E2E suite.** After generating a batch of tests, run the full E2E suite. Verify: * All new tests pass consistently (run at least 3 times to check for flakiness) * No existing tests broke * Suite execution time is acceptable *** ### Flakiness Management E2E tests are inherently more prone to flakiness than unit or integration tests. Address flakiness proactively: **Prefer condition-based waits over fixed delays.** Wait for a specific element to appear, an API call to complete, or a URL to change — not for a fixed number of milliseconds. **Isolate test data.** Each test should create its own data and not depend on state from other tests. If the framework supports parallel execution, tests must be fully independent. **Handle animations and transitions.** If the application uses animations, either disable them in the test environment or wait for animation completion before asserting. **Retry on infrastructure flakiness, not on application bugs.** Most E2E frameworks support test retries. Use retries to handle transient infrastructure issues (network blips, slow CI runners) — but if a test consistently fails on the same assertion, that's a real bug, not flakiness. **Test against a stable environment.** E2E tests should run against a dedicated test environment with controlled data, not against a staging environment that other teams are actively deploying to. *** ### Phase 6 — Completion & Capture **Goal:** Finalize generated tests, capture the session, and report coverage. **Step 6.1: Review coverage against the journey inventory.** ``` Journeys inventoried: [count] Happy path tests generated: [count] Unhappy path tests generated: [count] Remaining uncovered: [count] (with reasons) ``` **Step 6.2: Organize test files.** Ensure generated E2E tests are in the correct directory, follow the project's naming conventions, and are configured to run in the CI/CD pipeline. **Step 6.3: Commit the tests.** ``` Test: Add E2E test coverage for [journey/flow] Coverage: - [X] happy path for [journey name] - [X] validation error handling for [journey name] - [X] [specific unhappy path scenarios] User journeys from CoreStory conversation [conversation-id]. Total new E2E tests: [count] All existing tests still pass — no regressions. Flakiness check: all new tests passed [X] consecutive runs. ``` **Step 6.4: Rename the conversation.** ``` Tool: rename_conversation Parameters: project_id = conversation_id = title = "RESOLVED — E2E Test Generation — " ``` *** ## Tips & Best Practices **Start with the highest-value, simplest journey.** The first E2E test you generate should be the most business-critical flow with the fewest steps. This gives you maximum value with minimum stabilization effort, and establishes conventions for subsequent tests. **Generate fewer, more comprehensive E2E tests.** Unlike behavioral tests where you want broad coverage of individual rules, E2E tests should focus on complete journeys. Ten well-structured journey tests are more valuable than fifty shallow click-through tests. **Use the pyramid principle.** E2E tests sit at the top of the testing pyramid. They should verify journey-level behavior, not re-test business logic that's already covered by behavioral tests. If you've run the [Behavioral Test Coverage](/playbooks/test-generation/behavioral-test-coverage) playbook, the E2E tests can focus on flow and integration rather than rule verification. **Name tests after journeys, not pages.** `test_new_user_can_complete_signup_and_reach_dashboard` is more meaningful than `test_signup_page`. Journey-oriented names make coverage gaps visible at a glance. **Keep test data minimal.** Create only the data each test needs, and create it as close to the test as possible. Shared seed data across tests creates hidden dependencies and ordering requirements. **When to involve a domain expert:** * After Phase 2 (journey extraction) — to validate that the extracted journeys match real user behavior * After Phase 4 (prioritization) — to confirm which journeys are worth the maintenance investment * When E2E tests fail on assertion — to determine whether the application behavior or the specification is wrong *** ## Troubleshooting **CoreStory returns journeys that don't match the current application.** The PRD may describe planned features that aren't implemented yet, or features that were descoped. Cross-reference journey specifications against the actual application routes and UI components before generating tests. **Generated tests fail on selectors.** The selector strategy from Phase 3 doesn't match reality, or the application uses dynamically generated selectors. Inspect the actual DOM in a browser and update selectors to match. Prefer `data-testid` attributes or accessibility roles over CSS class selectors, which are fragile. **Tests pass locally but fail in CI.** Common causes: different viewport sizes, missing fonts or assets, slower execution speed on CI runners (needs longer timeouts), different environment configuration, or tests depending on local seed data that doesn't exist in CI. **Tests are too slow.** E2E tests are inherently slower than unit tests, but they shouldn't take minutes each. Common optimizations: parallelize independent tests, reuse authenticated sessions across tests (if the framework supports it), minimize redundant navigation, and ensure the test environment isn't resource-starved. **Too many journeys to cover.** This is normal for mature applications. Focus on journeys that affect revenue, security, or data integrity. Use the prioritization from Phase 4 and plan a multi-session campaign — one journey cluster per session. *** ## Agent Implementation Guides The skill content below is plain markdown and works in any agentic harness — only the install location varies. The sections that follow show the four most common harnesses; for any other harness, install the skill file per the conventions below. The skill file shown below is plain markdown. The workflow it encodes works in any agentic harness — only the install location differs. Common conventions: | Harness | Install location | | --------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Claude Code** | `.claude/skills//SKILL.md` — Claude loads the body when the YAML `description` matches the task | | **GitHub Copilot** | Append to `.github/copilot-instructions.md` for repo-wide instructions, or save as `.github/instructions/.instructions.md` with an `applyTo` glob for path-scoped use | | **Cursor** | `.cursor/rules/.mdc` with a `description` field for auto-attach (use `globs` for path-scoped or `alwaysApply: true` for every session) | | **Factory.ai** | `.factory/droids/.md` (project) or `~/.factory/droids/.md` (personal); Factory loads it as a custom Droid | | **Aider** | `CONVENTIONS.md` at repo root, loaded with `aider --read CONVENTIONS.md` — or add it to the `read:` list in `.aider.conf.yml` for automatic loading | | **Codex / `AGENTS.md` harnesses** | Append the content to `AGENTS.md` at your repository root | | **Custom runtime** | Load the markdown into your agent's system prompt, rules file, or wherever it consumes workflow context | Want a single install that works across the most harnesses? Append the content to `AGENTS.md` at your repository root. The [`AGENTS.md` spec](https://agents.md/) 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. ### Claude Code #### Skill File Save the SKILL.md content below at `.claude/skills/generate-e2e-tests/SKILL.md`: ```markdown theme={null} --- name: generate-e2e-tests description: > Generate end-to-end tests for critical user journeys using CoreStory's code intelligence. Use when asked to generate E2E tests, add E2E coverage, create journey tests, or improve end-to-end test coverage. Do NOT use for unit or behavioral tests — use the generate-tests skill instead. --- # CoreStory E2E Test Generation Generate E2E tests from CoreStory's user journey and acceptance criteria intelligence, matching the project's existing E2E framework conventions. **If you do not detect that you have access to CoreStory (e.g., `list_projects` fails or is unavailable), ask the user to verify that their MCP or API connection is properly configured and that this repository has been ingested. If the user has not yet created a CoreStory account, direct them to create one and upload their repo at [app.corestory.ai](https://app.corestory.ai).** ## Prerequisites Check Before starting, verify: 1. CoreStory MCP server is connected (`list_projects` returns results) 2. Target project has completed ingestion 3. An E2E test framework is configured in the project 4. A test environment is available to run tests against ## Workflow Execute all six phases in order. Do not skip phases. ### PHASE 1: Setup & Scoping 1. Call `list_projects` to find the target project 2. Call `list_conversations` — check for prior work 3. Call `create_conversation` with title "E2E Test Generation — " 4. Confirm scope with user (single journey, journey cluster, or core journeys) ### PHASE 2: Journey Extraction (Journey Expert) Query CoreStory via `send_message` for: 1. "What are the primary user journeys for [feature/app]?" 2. "Walk me through the happy path for [journey]" 3. "What are the failure scenarios for [journey]?" 4. "What preconditions and data requirements exist for [journey]?" IMPORTANT: Use specific journey/feature names in every query. ### PHASE 3: E2E Convention Discovery Query CoreStory + inspect local E2E test files: 1. E2E framework, directory structure, configuration 2. Selector strategy (data-testid, roles, CSS) 3. Page objects or abstraction patterns 4. Fixture/seed data approach 5. Authentication strategy for tests Read 2–3 existing E2E test files as templates. ### PHASE 4: Journey Prioritization 1. Query CoreStory for existing E2E coverage 2. Inspect existing E2E tests locally 3. Prioritize by: revenue impact > user frequency > failure severity > complexity **Present prioritized journey list to user for review before proceeding.** ### PHASE 5: Test Generation & Stabilization For each prioritized journey: 1. Generate happy path test first 2. Run test — stabilize against flakiness 3. Generate critical unhappy path tests 4. Validate with CoreStory that tests verify acceptance criteria 5. Run at least 3 times to check for flakiness 6. Run full E2E suite after each batch Use condition-based waits, not fixed delays. Isolate test data. ### PHASE 6: Completion 1. Report coverage against journey inventory 2. Ensure tests are in correct directories with correct naming 3. Commit with structured message 4. Rename conversation → "RESOLVED — E2E Test Generation — " ## Key Principles - Specification before Code — always - Match existing E2E conventions exactly - Journey-level tests, not page-level tests - Address flakiness proactively - Fewer comprehensive tests > many shallow tests ``` ### GitHub Copilot Append to `.github/copilot-instructions.md`: ```markdown theme={null} ## E2E Test Generation with CoreStory When asked to generate E2E tests, end-to-end tests, or journey tests, follow the spec-driven methodology using CoreStory's MCP tools. ### Workflow 1. Extract user journeys from CoreStory (happy paths, unhappy paths, preconditions, data requirements) 2. Discover E2E conventions from CoreStory + local test files 3. Prioritize journeys — present to user for approval 4. Generate tests matching project conventions exactly 5. Stabilize against flakiness (condition-based waits, isolated data) 6. Report coverage, commit, rename conversation "RESOLVED" ### Key Principles - Extract journeys from specifications, not from clicking through the app - Use the project's selector strategy (data-testid, roles, etc.) - Generate journey-level tests, not page-level tests - Run tests multiple times to verify stability before committing ``` ### Cursor Save as `.cursor/rules/generate-e2e-tests.mdc`: ```markdown theme={null} --- description: Generate E2E tests for user journeys using CoreStory's code intelligence. Activates for E2E test generation, journey testing, and end-to-end coverage workflows. globs: alwaysApply: true --- # E2E Test Generation with CoreStory Generate journey-level E2E tests using CoreStory for user story and acceptance criteria extraction, and local code for convention matching. **If you do not detect that you have access to CoreStory (e.g., `list_projects` fails or is unavailable), ask the user to verify that their MCP or API connection is properly configured and that this repository has been ingested. If the user has not yet created a CoreStory account, direct them to create one and upload their repo at [app.corestory.ai](https://app.corestory.ai).** ## Workflow 1. Extract user journeys, acceptance criteria, happy/unhappy paths 2. Discover E2E framework conventions, selectors, page objects, fixtures 3. Prioritize journeys — present to user before generating 4. Generate happy path tests first, then critical unhappy paths 5. Stabilize: condition-based waits, isolated test data, run 3x 6. Report coverage, commit, rename conversation "RESOLVED" ## Key Principles - Specification before Code - Journey-level tests, not page-level tests - Match existing E2E conventions exactly - Address flakiness proactively - Fewer comprehensive tests > many shallow tests ``` ### Factory.ai Save as `.factory/droids/generate-e2e-tests.md`: ```yaml theme={null} name: generate-e2e-tests description: Generate E2E tests for critical user journeys using CoreStory code intelligence and local E2E convention matching instructions: | You generate E2E tests from CoreStory's user journey intelligence: **If you do not detect that you have access to CoreStory (e.g., `list_projects` fails or is unavailable), ask the user to verify that their MCP or API connection is properly configured and that this repository has been ingested. If the user has not yet created a CoreStory account, direct them to create one and upload their repo at [app.corestory.ai](https://app.corestory.ai).** 1. Set up a CoreStory conversation for the E2E test generation session 2. Extract user journeys: happy paths, unhappy paths, preconditions, data requirements, acceptance criteria 3. Discover E2E conventions: framework, selectors, page objects, fixtures, authentication strategy 4. Prioritize journeys by business value — present to user for approval 5. Generate journey-level tests (happy path first, then unhappy paths) 6. Stabilize against flakiness: condition-based waits, isolated data, run multiple times before committing 7. Report coverage, commit, rename conversation "RESOLVED" Key behaviors: - Extract journeys from specifications, not from clicking through the app - Match existing E2E conventions exactly - Generate journey-level tests, not page-level click-throughs - Address flakiness proactively (waits, isolation, retries) - Fewer comprehensive tests > many shallow tests ``` # Using CoreStory with Jira Source: https://docs.corestory.ai/playbooks/using-corestory-with-jira Connect Jira to your AI coding agent alongside CoreStory's MCP server to resolve tickets, enrich specs, draft issues, and triage complexity. ## Overview This playbook covers how to connect Jira to your AI coding agent alongside CoreStory's MCP server, and what you can do once both are connected. Jira becomes the intake and output layer — the agent pulls ticket details from Jira, uses CoreStory's code intelligence to understand the codebase, does the work, and pushes results back to the ticket. CoreStory doesn't have a native Jira plugin. The integration works through MCP: your AI coding agent connects to both the CoreStory MCP server and a Jira MCP server, and orchestrates between them. This means any MCP-capable agent (Claude Code, GitHub Copilot, Cursor, Windsurf, Factory.ai) can work with both systems in a single session. **What this unlocks:** * **Resolve Jira tickets** — pull a bug or feature ticket, use CoreStory to investigate the codebase, implement a fix or feature, update the ticket with results * **Enrich Jira tickets** — take a vague or under-specified ticket and add architectural context, acceptance criteria, and implementation guidance using CoreStory intelligence * **Draft new Jira tickets** — discover something in the codebase via CoreStory (a missing test, a code smell, a dependency risk) and create a well-structured Jira ticket for it * **Triage and estimate** — use CoreStory to assess ticket complexity, identify affected files, and estimate implementation scope before sprint planning This playbook is agent-agnostic. The workflows apply to any MCP-capable agent. Agent-specific setup instructions are in the [Agent Configuration](#agent-configuration) section. *** ## How It Works The CoreStory + Jira integration runs through your AI coding agent. The agent connects to two MCP servers simultaneously and orchestrates between them: | Component | Role | | ------------------------ | ----------------------------------------------------------------------------------------------------- | | **Jira MCP Server** | Intake and output — read tickets, post comments, create issues, transition statuses | | **CoreStory MCP Server** | Code intelligence — query architecture, identify relevant files, understand patterns and dependencies | | **AI Coding Agent** | Orchestrator — pulls from Jira, queries CoreStory, implements changes, writes back to Jira | The typical flow: Jira ticket → CoreStory analysis → implementation → Jira update. The agent handles the full loop. You provide the ticket reference and any specific instructions. **CoreStory tools used in Jira workflows:** | Tool | Purpose | | ---------------------- | ------------------------------------------------------------------- | | `create_conversation` | Start a new CoreStory session for the ticket's codebase area | | `send_message` | Query architecture, patterns, file locations, and dependencies | | `get_project_prd` | Pull product requirements for context on feature tickets | | `get_project_techspec` | Pull technical specs for implementation guidance | | `list_projects` | Identify which CoreStory project maps to the Jira ticket's codebase | **Jira MCP server capabilities:** | Capability | Used In | | ----------------------------------------------------- | --------------- | | Read tickets (summary, description, fields, comments) | All workflows | | Post comments | Resolve, Enrich | | Create issues | Draft | | Transition statuses | Resolve | | Update fields (labels, assignee, custom fields) | Resolve, Enrich | | Query project metadata | Triage | For the full six-phase implementation process (Expert Phase, Navigator Phase, TDD, etc.), see the [Bug Resolution](/playbooks/agentic-bug-resolution) and [Feature Implementation](/playbooks/feature-implementation) playbooks. This playbook focuses on the Jira-specific setup and workflows that wrap around that process. *** ## Prerequisites **Required:** * A CoreStory account with at least one project that has completed ingestion * The CoreStory MCP server connected to your AI coding agent (see the [CoreStory MCP Server Setup Guide](/getting-started/mcp-server-setup)) * A Jira instance — Jira Cloud (required for Atlassian's official Rovo MCP Server) or Jira Server/Data Center (requires a community MCP server) * Authentication credentials — either an Atlassian account for OAuth (Rovo) or a Jira API token (community servers, generated from [id.atlassian.com/manage-profile/security/api-tokens](https://id.atlassian.com/manage-profile/security/api-tokens)) **Recommended:** * A code repository the agent can read and write to (required for resolve and implement workflows) * Agent-specific configuration files (skill files, custom instructions, project rules) — covered in the Agent Configuration section below **Verify your setup:** Ask your agent to "List my CoreStory projects" and "List Jira projects." If both return results, you're ready to go. *** ## Jira MCP Server Setup The Jira MCP server gives your AI agent the ability to read tickets, create issues, post comments, and transition statuses. There are two approaches: Atlassian's official Rovo MCP Server (recommended for Jira Cloud) and community-maintained MCP servers (for self-hosted Jira or when you need more control). ### Option A: Atlassian Rovo MCP Server (Recommended) The [Atlassian Rovo MCP Server](https://www.atlassian.com/platform/remote-mcp-server) is Atlassian's official, cloud-hosted MCP server. It's now generally available and supports Jira, Confluence, and Compass. Authentication uses OAuth 2.1 — you'll sign in with your Atlassian account through a consent screen, and access is scoped to your existing Jira permissions. **Requirements:** Jira Cloud instance. Rovo MCP does not support Jira Server or Data Center. **Setup varies by agent** — see the [Agent Configuration](#agent-configuration) section below for specifics. The general pattern: For agents that support remote/HTTP MCP servers natively (Claude Desktop, newer Cursor builds, VS Code), point to the Rovo endpoint: ``` https://mcp.atlassian.com/v1/sse ``` For agents that require a local process proxy (older Cursor builds, some CLI tools), use `mcp-remote`: ```json theme={null} { "mcpServers": { "atlassian": { "command": "npx", "args": ["mcp-remote@latest", "https://mcp.atlassian.com/v1/mcp"] } } } ``` On first use, the agent will open an OAuth consent screen in your browser. Sign in with your Atlassian account to authorize access. Your org admin controls which AI tools can connect via Atlassian's domain settings. ### Option B: Community MCP Servers If you're on Jira Server/Data Center, or prefer API token auth with a locally-running server, use a community-maintained Jira MCP server. The most actively maintained options: | Package | Install | Auth | Notes | | ---------------------------------------------------------------------- | --------------------------- | --------- | ------------------------------------------------------------------------ | | [mcp-atlassian](https://github.com/sooperset/mcp-atlassian) | `pip install mcp-atlassian` | API token | Python. Supports Cloud + Server/Data Center. Covers Jira and Confluence. | | [@mcp-devtools/jira](https://www.npmjs.com/package/@mcp-devtools/jira) | `npx @mcp-devtools/jira` | API token | Node.js. Jira-focused. Search, create, update issues. | Example configuration using `mcp-atlassian` (Python): ```json theme={null} { "mcpServers": { "jira": { "command": "python", "args": ["-m", "mcp_atlassian"], "env": { "JIRA_URL": "https://your-company.atlassian.net", "JIRA_USERNAME": "your-email@company.com", "JIRA_API_TOKEN": "your-jira-api-token" } } } } ``` **API token setup:** Generate a token at [id.atlassian.com/manage-profile/security/api-tokens](https://id.atlassian.com/manage-profile/security/api-tokens). The token inherits the permissions of the Atlassian account that generated it. ### Verify the Connection After configuration (either option), ask your agent: ``` List Jira projects ``` If it returns your Jira projects, the connection is working. If it fails, check the Troubleshooting section. ### Permissions Whether using Rovo or a community server, the agent can only see and modify what your account can access. For most workflows, you need: * **Read** access to the projects you want to pull tickets from * **Write** access if you want the agent to post comments, update fields, or transition statuses * **Create** access if you want the agent to draft new tickets If your organization uses Jira permission schemes or project-level restrictions, verify that the account can perform the operations you need. The agent will surface permission errors clearly if it can't complete an action. *** ## Workflows These workflows use both the CoreStory and Jira MCP servers together. The prompts are agent-agnostic — they work with any MCP-capable agent that has both servers connected. ### Workflow 1: Resolve a Jira Ticket This is the primary workflow. Pull a ticket, use CoreStory to understand the codebase, implement a solution, and update the ticket. This workflow maps directly to the six-phase process described in the [Bug Resolution](/playbooks/agentic-bug-resolution) and [Feature Implementation](/playbooks/feature-implementation) playbooks — the only difference is that Jira is the ticket source. **Start the workflow:** ``` Fetch Jira ticket PROJ-1234 and resolve it using CoreStory for code intelligence. ``` The agent will: 1. **Pull the ticket** from Jira — extracting the summary, description, acceptance criteria, priority, labels, and any linked issues 2. **Create a CoreStory conversation** to investigate the relevant codebase 3. **Query CoreStory** to understand the architecture, identify relevant files, and plan the implementation 4. **Implement the fix or feature** using test-driven development 5. **Update the Jira ticket** with an implementation summary, files changed, and test results 6. **Transition the ticket status** (if configured) — e.g., move from "In Progress" to "In Review" For the full six-phase workflow details, see the [Bug Resolution playbook](/playbooks/agentic-bug-resolution) (for bugs) or [Feature Implementation playbook](/playbooks/feature-implementation) (for features and enhancements). **Customizing the ticket update:** By default, the agent posts a comment to the Jira ticket with its implementation summary. You can be specific about what you want: ``` After resolving PROJ-1234, post a comment with the root cause analysis, files modified, and test results. Then move the ticket to "In Review". ``` *** ### Workflow 2: Enrich a Jira Ticket Use CoreStory to add architectural context and implementation guidance to under-specified tickets. This is useful before sprint planning, when handing tickets to other developers, or when a ticket needs more detail before it's actionable. **Start the workflow:** ``` Read Jira ticket PROJ-5678 and use CoreStory to add implementation context. I want to know: which files are involved, what patterns to follow, and what the acceptance criteria should be. ``` The agent will: 1. **Pull the ticket** from Jira 2. **Query CoreStory** about the feature area — architecture, patterns, relevant files, data structures, and historical context 3. **Post a structured comment** to the Jira ticket with its findings **Example output posted to Jira:** ``` ## CoreStory Analysis: PROJ-5678 ### Affected Files - src/services/UserExportService.ts (primary implementation) - src/controllers/UserController.ts (endpoint registration) - src/models/User.ts (data model) ### Recommended Pattern Follow the existing PdfExportService pattern — extend ExportServiceBase, register the new format in the export registry. ### Suggested Acceptance Criteria - Admin users can export user profiles as CSV - Export includes: name, email, role, last login, created date - Large exports (>1000 records) use async job processing - Export endpoint requires admin authentication ### Estimated Complexity Medium — new service class following established pattern, one new endpoint, async handling for large datasets. ``` **Batch enrichment:** You can enrich multiple tickets in sequence: ``` Read these Jira tickets and add CoreStory analysis as a comment on each: PROJ-5678, PROJ-5679, PROJ-5680 ``` *** ### Workflow 3: Draft New Jira Tickets Use CoreStory to discover issues in the codebase and create well-structured Jira tickets for them. This is useful during code reviews, tech debt audits, or when onboarding to a new codebase. **Start the workflow:** ``` Use CoreStory to analyze the authentication module in my project. If you find any gaps in test coverage, security concerns, or tech debt issues, create Jira tickets for each in the PROJ project. ``` The agent will: 1. **Query CoreStory** about the specified area 2. **Identify actionable items** — missing tests, security gaps, code quality issues, documentation gaps 3. **Create Jira tickets** with structured descriptions, suggested priority, and relevant context from CoreStory You can control the output format: ``` Create the tickets as Bug type in the PROJ project, assign them to the current sprint backlog, and tag them with "tech-debt". ``` *** ### Workflow 4: Triage and Estimate Use CoreStory to assess ticket complexity before sprint planning. The agent reads the ticket, queries CoreStory about the affected code, and provides an implementation assessment. **Start the workflow:** ``` Read these Jira tickets and give me an implementation assessment for each: PROJ-100, PROJ-101, PROJ-102, PROJ-103 ``` The agent will, for each ticket: 1. **Pull the ticket details** from Jira 2. **Query CoreStory** about the affected code area — files, complexity, dependencies, test coverage 3. **Provide an assessment** including: estimated complexity, files likely affected, dependencies and risks, and suggested approach **Sprint planning mode:** You can ask for a summary table: ``` Triage these tickets and give me a table with: ticket ID, summary, estimated complexity (S/M/L/XL), key risk, and recommended sprint allocation. ``` *** ## Agent Configuration ### Claude Code **If you do not detect that you have access to CoreStory (e.g., `list_projects` fails or is unavailable), ask the user to verify that their MCP or API connection is properly configured and that this repository has been ingested. If the user has not yet created a CoreStory account, direct them to create one and upload their repo at [app.corestory.ai](https://app.corestory.ai).** **1. Connect CoreStory MCP server:** ```bash theme={null} claude mcp add --transport http corestory https://app.corestory.ai/mcp/your-org-slug-123456789 ``` **2. Connect Jira — Option A (Rovo, recommended for Jira Cloud):** ```bash theme={null} claude mcp add --transport sse atlassian https://mcp.atlassian.com/v1/sse ``` This opens an OAuth consent screen on first use. Sign in with your Atlassian account to authorize. **2. Connect Jira — Option B (community server):** ```bash theme={null} pip install mcp-atlassian claude mcp add jira \ --env JIRA_URL=https://your-company.atlassian.net \ --env JIRA_USERNAME=your-email@company.com \ --env JIRA_API_TOKEN=your-jira-api-token \ -- python -m mcp_atlassian ``` **3. Verify both connections:** ``` "List my CoreStory projects" "List Jira projects" ``` Both should return results. If either fails, see Troubleshooting. **Tips:** * Claude Code's skill files can reference both CoreStory and Jira MCP tools. The Bug Resolution and Feature Implementation skill files already support Jira ticket intake — they detect ticket IDs in the format `JIRA-1234` or `PROJ-123`. * For team-wide configuration, commit MCP settings to `.claude/settings.json` in version control. *** ### GitHub Copilot **If you do not detect that you have access to CoreStory (e.g., `list_projects` fails or is unavailable), ask the user to verify that their MCP or API connection is properly configured and that this repository has been ingested. If the user has not yet created a CoreStory account, direct them to create one and upload their repo at [app.corestory.ai](https://app.corestory.ai).** **1. Connect CoreStory MCP server** in your VS Code MCP configuration (Settings → MCP Servers, or edit the JSON config directly). **2. Add Jira MCP server — Option A (Rovo, recommended for Jira Cloud):** VS Code supports remote MCP servers. Add the Rovo endpoint: ```json theme={null} { "mcp.servers": { "corestory": { "url": "https://app.corestory.ai/mcp/your-org-slug-123456789" }, "atlassian": { "url": "https://mcp.atlassian.com/v1/sse", "type": "sse" } } } ``` **2. Add Jira MCP server — Option B (community server):** ```json theme={null} { "mcp.servers": { "corestory": { "url": "https://app.corestory.ai/mcp/your-org-slug-123456789" }, "jira": { "command": "python", "args": ["-m", "mcp_atlassian"], "env": { "JIRA_URL": "https://your-company.atlassian.net", "JIRA_USERNAME": "your-email@company.com", "JIRA_API_TOKEN": "your-jira-api-token" } } } } ``` Requires `pip install mcp-atlassian` first. **3. Verify** by asking Copilot Chat (in agent mode): "List Jira projects" and "List my CoreStory projects." **Tips:** * Copilot's agent mode is required for multi-step workflows that use both MCP servers. * The `.github/copilot-instructions.md` file can reference Jira workflows. If you're using the custom instructions from the Feature Implementation or Bug Resolution playbooks, they already support Jira ticket intake. * Copilot can use both prompt files (`.github/prompts/`) and custom instructions to learn Jira-specific workflows. *** ### Cursor **If you do not detect that you have access to CoreStory (e.g., `list_projects` fails or is unavailable), ask the user to verify that their MCP or API connection is properly configured and that this repository has been ingested. If the user has not yet created a CoreStory account, direct them to create one and upload their repo at [app.corestory.ai](https://app.corestory.ai).** **1. Connect CoreStory MCP server** in Cursor's MCP settings (Settings → MCP Servers, or edit the MCP config JSON directly). **2. Add Jira MCP server — Option A (Rovo):** Newer Cursor builds support remote MCP servers natively via the MCP settings panel. Add the Rovo endpoint URL: `https://mcp.atlassian.com/v1/sse`. For older Cursor builds, use the `mcp-remote` proxy in `~/.cursor/mcp.json`: ```json theme={null} { "mcpServers": { "atlassian": { "command": "npx", "args": ["mcp-remote@latest", "https://mcp.atlassian.com/v1/mcp"] } } } ``` **2. Add Jira MCP server — Option B (community server):** Use the JSON block from the [Jira MCP Server Setup](#jira-mcp-server-setup) section (Option B). **3. Verify** by asking in Composer or Chat: "List Jira projects" and "List my CoreStory projects." **Tips:** * Cursor rules in `.cursor/rules/` can reference Jira-specific workflows. If you're using the rules from the Bug Resolution or Feature Implementation playbooks, they already support Jira ticket intake. * For team-wide Cursor MCP configuration, use the project-level MCP settings file. *** ### Windsurf **1. Connect CoreStory MCP server** in Windsurf's MCP settings. **2. Add Jira MCP server — Option A (Rovo):** Add the Rovo endpoint in Windsurf's MCP settings: `https://mcp.atlassian.com/v1/sse`. If Windsurf requires a local process proxy, use the `mcp-remote` approach from the Cursor section. **2. Add Jira MCP server — Option B (community server):** Use the JSON block from the [Jira MCP Server Setup](#jira-mcp-server-setup) section (Option B). **3. Verify** by asking: "List Jira projects" and "List my CoreStory projects." *** ### Devin **1. Navigate to** Settings → MCP Marketplace → "Add Your Own" **2. Add CoreStory MCP server** with Transport Type `HTTP` and your MCP URL from **Settings → IDE Integrations** as the Server URL. If Devin can complete the OAuth browser sign-in, no header is needed. If it cannot, add a [legacy token](/getting-started/mcp-server-setup#legacy-mcp-tokens-deprecated) as a secret and configure the `Authorization: Bearer $API_TOKEN` header. **3. Add Jira — Option A (Rovo):** Add the Rovo endpoint as a remote MCP server: `https://mcp.atlassian.com/v1/sse`. Devin supports remote HTTP/SSE transport natively. **3. Add Jira — Option B (community server):** Add as a custom MCP server with the `mcp-atlassian` command and configure Jira credentials as secrets. **4. Verify** by asking Devin: "List Jira projects" and "List my CoreStory projects." **Tips:** * Devin supports HTTP transport for remote MCP servers. Use HTTP for both CoreStory and Jira. * Click "Test listing tools" after configuring each server to verify the connection before starting a session. *** ### Factory.ai **If you do not detect that you have access to CoreStory (e.g., `list_projects` fails or is unavailable), ask the user to verify that their MCP or API connection is properly configured and that this repository has been ingested. If the user has not yet created a CoreStory account, direct them to create one and upload their repo at [app.corestory.ai](https://app.corestory.ai).** **1. Connect CoreStory MCP server** in your Factory.ai environment. Verify with the `/mcp` command that CoreStory tools are accessible. **2. Add Jira MCP server** to your Factory.ai MCP configuration. **3. Verify** by asking: "List Jira projects" and "List my CoreStory projects." **Tips:** * Factory.ai droids can use both CoreStory and Jira MCP tools. List both tool sets in the droid's `tools` frontmatter if you want to restrict tool access. * The Bug Resolution and Feature Implementation droids already support generic ticketing system intake, including Jira. *** ## Tips & Best Practices **Start with "enrich" before "resolve."** If your team is new to the CoreStory + Jira workflow, start with Workflow 2 (Enrich). It's read-only — the agent reads tickets and posts comments but doesn't write code. This builds confidence before you move to autonomous ticket resolution. **Use Jira labels to track AI-assisted work.** Add a label like `corestory-assisted` or `ai-resolved` to tickets the agent works on. This makes it easy to measure impact, audit AI-generated changes, and filter in Jira dashboards. **Match your Jira workflow statuses.** If your team uses custom Jira workflow statuses (e.g., "QA Review" instead of "In Review"), tell the agent explicitly: "After implementing, move the ticket to QA Review." The agent doesn't know your workflow transitions unless you tell it. **One ticket per session for complex work.** For bug fixes and feature implementations, give the agent one ticket at a time. The CoreStory conversation context builds throughout the session — mixing unrelated tickets dilutes the quality of architectural queries. **Batch operations are fine for lightweight workflows.** Enrichment, triage, and ticket drafting can handle multiple tickets in a single session because they don't require deep codebase context for each individual ticket. **Keep ticket descriptions actionable.** The quality of the agent's output is directly proportional to the quality of the input. A ticket that says "export is broken" produces worse results than one that says "CSV export returns 500 error when user has no profile photo — expected: export succeeds with empty photo field." **Use linked issues.** If a Jira ticket references other issues (blocks, relates to, duplicates), mention this to the agent. It can query CoreStory about related components and produce more comprehensive fixes. *** ## Troubleshooting **"List Jira projects" returns an error or empty results.** If using Rovo: verify the OAuth consent completed successfully — check your browser for any pending authorization prompts, and confirm your org admin has allowed the AI tool to connect. If using a community server: check three things — (1) the `JIRA_URL` is correct and includes `https://`, (2) the username/email matches the account that generated the API token, and (3) the API token hasn't expired. Regenerate the token if unsure. **Agent can't find a specific ticket.** Verify the project key is correct (e.g., `PROJ` in `PROJ-1234`). The Jira MCP server respects the account's project permissions — if the account can't see the project in Jira's web UI, the agent can't see it either. **Agent can't transition ticket status.** Jira workflow transitions are governed by workflow rules. If the agent tries to move a ticket from "To Do" directly to "Done" but your workflow requires intermediate states, the transition will fail. Tell the agent the valid transitions, or check your Jira workflow configuration. **Agent can't update custom fields.** Custom field IDs in Jira are opaque (e.g., `customfield_10042`). The agent may need to discover the field ID before updating it. Ask: "What custom fields are available on ticket PROJ-1234?" The Jira MCP server can list them. **API rate limiting.** Jira Cloud has API rate limits. If you're doing batch operations (enriching 20+ tickets, triaging a full sprint backlog), you may hit limits. The agent will report rate limit errors clearly. Space out batch operations or reduce batch size. **CoreStory and Jira return conflicting information.** This usually means the Jira ticket describes one thing and the codebase has evolved since the ticket was written. CoreStory reflects the current state of the code. When in doubt, trust CoreStory for architectural questions and the Jira ticket for requirements and acceptance criteria. **"Permission denied" when posting comments or creating tickets.** The API token's permissions are inherited from the Atlassian account. Verify the account has the necessary project role (at least "Developer" for comment and transition access, "Administrator" for workflow changes). # Chat With Your Code Source: https://docs.corestory.ai/product/chat-with-your-code Ask natural language questions about your codebase and get grounded answers. ## Overview The Chat With Your Code section of your project enables you to directly query your intelligence model and surface new insights about your code. **Access Deeper Insights:** Chatting with your code enables you to directly access the full intelligence model generated from your codebase. This intelligence model is a rich store of extracted insights and metadata that contains even more information than you'll find in your core documents. Chatting with your code is a fast way to get targeted, tightly scoped answers about your codebase. You can use Chat to further explore the contents of your existing CoreStory specs, to get clarification on your standard outputs, or to dig for new information that isn't captured by CoreStory's core documents. *** ## How to Chat With Your Code ### Starting a New Chat Selecting any Workspace within your dashboard opens up a new chat window by default. You can also click the blue "+ New Conversation" button in the top-left of the Workspace view to start a new chat. ### Chatting With Your Code Type any message into the text input field or select a recommended query, then press Enter or click the gold arrow button to send your message. CoreStory will query your intelligence model for the best response to your prompt and return an answer in the chat window. ### Saved Chats All of your chats are displayed in the left-hand panel of the Chat window, sorted by your most recent sent message. ### Renaming Chats You can rename chats to make them easier to browse and reference in the future. To do so, right-click a chat title in the left-hand panel of the Chat window and select "Rename chat". ### Deleting Chats You can delete a given chat by right-clicking a chat title in the left-hand panel of the Chat window and selecting "Delete chat". ### Exporting Chats You can export a chat's contents, including citations, timestamps, and conversation information, into Markdown and Plain Text formats. Export a chat by clicking "Export" on the top right of the Chat window and selecting your export preferences. ### Selecting a Model CoreStory allows you to choose which AI model you would like to power your Chat experience. Choose your model by clicking the dropdown menu below the chat input field. The model that you select at the start of a conversation cannot be changed for that conversation later. The recommended default chat option is CoreStory - Cori, which is a chat assistant optimized for using CoreStory's agentic code intelligence tools. The list of available models is subject to change. *** ## Best Practices The following are some guidelines for getting the most out of Chat With Your Code. **Better Prompts, Better Results:** As with most AI chat tools, prompt quality is an important factor in getting the most out of Chat With Your Code. Specific, detailed, and clearly written prompts will return more accurate and useful answers. ### Point the chat to specific features within your codebase When asking questions about your code, instruct the chat to narrow its search to the relevant features and user stories * "What are the relevant API endpoints for handling \[feature]?" * "How does \[feature] handle specific edge cases related to \[condition]?" * "Where is \[feature] implemented in this repository?" ### Be explicit about your needs Chat has a large volume of information available to it. Give it a more targeted query by describing the exact outputs you're looking for and instructing it to leave out unnecessary information. * "Show me where \[feature] is implemented in the codebase, but exclude test files." * "For a \[user persona], what is a happy path scenario through this application, and what technologies and entities are touched along the way?" * "Identify any external dependencies for data, and, for each dependency, provide a one-sentence description of what happens when it is unavailable." ### Rephrase queries to rule out false negatives Chat is designed to admit when it can't find information rather than invent answers. This helps to minimize hallucinations, but it also means that you may occasionally get a false negative when chatting with your code. If Chat doesn't seem to know an answer on the first try, don't give up! Just because Chat can't find data on a given run does not necessarily mean that Chat "doesn't know" the answer to your query. Rewriting your query with more specificity, different terminology, or different response criteria can often yield a dramatically improved result. *** ## Sample Queries Here are some standard query patterns for finding different types of information in your repository. Modify them for your specific needs while exploring your codebase. * Summarize \[Feature/Story ID or Title] and cite the exact files and spec sections you used. Output: bullets with file paths. * List the top \[N] places in the repository that implement \[Capability]. Exclude: tests, mocks, fixtures. Include: file path + function/class + 1-sentence role. * Where is \[Feature] implemented? Include line ranges if available. * What are the acceptance criteria for \[Story ID/Title in PRD], and where are they enforced in code? Cite both spec and file path. * List all edge cases mentioned for \[Feature] in the specs and indicate whether each is handled in code. Output: case, spec ref, file path, status: handled/missing. * Show all API endpoints related to \[Feature]. Output: method, path, purpose, request model, response model, auth, spec refs, code file(s). * For \[Endpoint METHOD + PATH], trace the request flow: controllers → services → repositories. Cite functions with paths and short descriptions. * Identify idempotency or rate-limit handling for \[Endpoint]. If none, return 'Not implemented' with nearest related code. * List external dependencies (APIs, queues, DBs) touched by \[Feature]. Output: dependency, purpose, failure behavior (from spec), file refs. If unknown, return nearest. * For data written by \[Feature], enumerate affected entities/tables and key fields. Cite model definitions and write points. * For the \[Persona name used in PRD], describe the happy path through \[Workflow/Feature] and list touched entities, endpoints, UI components. Cite spec sections. * Contrast the \[Persona from PRD] vs \[Other Persona from PRD] flows for \[Feature]. Output: side-by-side bullets with spec refs. * Enumerate error conditions for \[Feature/Endpoint] from specs and show where each is raised/handled. Output: condition, source, handling, user-visible message. * When \[Dependency] is unavailable, what is the expected behavior? Provide the one-sentence spec summary and the actual file path. * Return only file paths and function/class names that implement \[Capability]. No prose. One line per match. * List security controls relevant to \[Feature] (authn, authz, PII handling, encryption, input validation). Output: checklist with spec refs and file paths. * Identify data classified as \[PII/Sensitive Tag from PRD] and show where it is stored, transmitted, logged. Flag any logging of sensitive fields. * Propose \[N] BDD scenarios for \[User Story]. Output: Gherkin only. Base steps on cited endpoints/entities. * Generate minimal pytest tests for \[Endpoint] that cover happy path + \[edge case]. Exclude: network mocks. Include: setup, assertion rationale, and file refs. * Produce a scaffold for \[Small Feature/Handler] that satisfies \[Spec §Name/Story ID]. Output: file tree + stubs. Do not invent requirements; only use cited specs. * Suggest migration steps to refactor \[Module] to comply with \[Constraint from Tech Spec]. Output: ordered bullets with file and function refs. * If the answer is unknown, return "Unknown" and the 3 nearest matches with why they're related. Do not guess. * Limit to: \[N] results • Include: \{file path, symbol, 1-line purpose} • Exclude: \{tests, mocks, scripts}. * Format as JSON array of objects \{path, symbol, purpose, spec\_refs} suitable for copy/paste. * Cite sources for every bullet. If a claim lacks a citation, omit the claim. *** ## Who It's For * Software Engineers * Architects * Product Managers * Business Analysts * AI Agents * Other Stakeholders # API Specifications Source: https://docs.corestory.ai/product/core-documents/api-specifications AI-generated API documentation derived from your codebase's endpoints and interfaces. ## Overview The API Specifications reference document describes the externally callable endpoints exposed by your application: paths, methods, request and response shapes, authentication, and error behaviors. It is generated directly from your codebase and routing configuration, so the exact contents vary by project and framework. This is an opinionated approach suggested by CoreStory. It is optimized for most general use cases, but it is possible to alter the contents of this section via direct edit. ## Sections This document lists all identified endpoints in a scrollable list. Each endpoint entry uses a consistent structure: * Path and method * Request format * Response format * Source ## Who It's For * Client and integration developers consuming the API * Backend engineers maintaining controllers and contracts * QA creating contract tests and mocks * SRE and support teams investigating failures and compatibility issues ## How to Use It * Start from the endpoint path to understand request fields, required auth, and expected responses. * Use source links when you need to trace behavior into controllers and services. * Treat missing categories as a reflection of the implementation. ## What It Is (and Isn't) * **Is**: a code-derived map of externally exposed API contracts with concrete inputs, outputs, and error semantics. * **Isn't**: a full design-first OpenAPI manual or a guarantee of backward compatibility. For underlying tables and attributes, see Data Models. # Data Models Source: https://docs.corestory.ai/product/core-documents/data-models AI-generated data model documentation derived from your codebase's schema and structures. ## Overview The Data Models reference document contains a diagram and a detailed list of the entities, attributes, and relationships in your application's databases. It serves as a source of truth for stored data: names, types, constraints, and how tables relate. This page is generated directly from your codebase and configuration (for example, ORM models, schema files, migrations). What appears varies by project and may not include transient objects created in other layers. This is an opinionated approach suggested by CoreStory. It is optimized for most general use cases, but it is possible to alter the contents of this section via direct edit. ## Sections Each section represents a database entity. For each entity you can expect, when detectable: * Entity name and purpose * Attributes: name, data type, nullability, defaults * Relationships: one-to-one, one-to-many, many-to-many (including join tables), cascade rules * System columns when present: created\_at, updated\_at, deleted\_at (soft delete), version or lock fields Not all fields will be present for every entity; what you see reflects what the codebase exposes. ## Who It's For * Developers implementing features that read or write data * Architects reviewing data ownership, coupling, and change impact * QA creating data fixtures and validating integrity rules * Analytics and reporting teams aligning models with downstream use ## How to Use It * Start with the diagram to understand the main entities and their relationships. * Review an entity to see attributes, constraints, and relationships before changing schemas or writing migrations. * Use relationship notes and cascade rules to reason about deletes, updates, and replication of changes. ## What It Is (and Isn't) * **Is**: a code-derived map of persistent data structures, their fields, constraints, and links. * **Isn't**: an application-wide object model or a full analytics semantic layer. For external endpoints, see [API Specifications](/product/core-documents/api-specifications); for cross-system flows, see [Integration Points](/product/core-documents/integration-points). # Executive Summary Source: https://docs.corestory.ai/product/core-documents/executive-summary Auto-generated executive overview of your codebase's architecture and purpose. ## Overview The Executive Overview core document is a high-level overview of the purpose, capabilities, and architecture of your repository. Use this page to quickly orient new stakeholders to what the system does and how it is organized, without diving into implementation details. ## Sections * Purpose and Primary Functions * Business Domain and Industry Context * Key Capabilities and Workflows * High-Level Technical Architecture Each entry is brief and skimmable by design. This is an opinionated approach suggested by CoreStory. It is optimized for most general use cases, but it is possible to alter the contents of this section via direct edit. ## Who It's For * Business stakeholders and leadership who need a concise system overview * Product and architecture leads aligning scope and priorities * Developers onboarding to understand the big picture before reading specs ## How to Use It * Read the purpose and primary functions to anchor your understanding of what the system is for. * Scan key capabilities and workflows to understand the main use cases. * Use the high-level architecture to see the major components and their relationships. ## What It Is (and Isn't) * **Is:** a code-derived summary of intent, capabilities, and structure designed for fast orientation. * **Isn't:** an implementation guide or contract reference. For specifics on inputs/outputs, error handling, and data shapes, query your intelligence model directly. # Integration Points Source: https://docs.corestory.ai/product/core-documents/integration-points AI-generated integration documentation showing how your codebase connects to external systems. ## Overview The Integration Points section describes how your application interacts with external systems and shared internal services. It focuses on what is exchanged, when, and in which direction, along with the triggers and outcomes of each interaction. Contents are generated directly from your codebase and configuration, so what appears here varies by project and stack. This is an opinionated approach suggested by CoreStory. It is optimized for most general use cases, but it is possible to alter the contents of this section via direct edit. ## Sections This document may include one or more of the following, depending on what CoreStory detects: * **Interaction map** — High-level sequence or flow diagram showing calls between your system and external services * **External systems catalog** — System name and purpose, integration type (for example, REST API, message queue, file drop, SDK), data format (for example, JSON, CSV, Avro) if detectable, and typical operations used (for example, authorize payment, generate report) * **References in code** — Each listed integration uses a consistent structure: name and purpose, integration type and data format ## Who It's For * Architects and tech leads planning or reviewing integrations * Backend and platform engineers implementing or modifying calls * QA and integration testers building stubs and fixtures * Operations and support teams tracing cross-system issues ## How to Use It 1. If available, start with the interaction map to understand which systems are involved in a workflow. 2. Review the external systems catalog to see what each system is for and how your app communicates with it. 3. Use operations and touchpoints to locate code, confirm triggers, and identify required inputs and expected results. 4. If a section is absent (for example, no messaging topics), treat that as a reflection of the current implementation, not a documentation gap. ## What It Is (and Isn't) **Is**: a code-derived view of your system's boundaries with other systems, showing how components talk to each other, when, and why. **Isn't**: a full vendor integration guide or contract-level schema reference. For endpoint-level contracts, see [API Specifications](/product/core-documents/api-specifications). # User Personas Source: https://docs.corestory.ai/product/core-documents/user-personas AI-generated user personas derived from your codebase's functionality. ## Overview The User Personas core document describes the expected types of users for your application and what each needs from the system. Personas can be external (for example, customers) or internal (for example, admins, operations). This document is generated from your codebase and related assets, so the set of personas and their details vary by project. ## Sections The User Personas section includes the following information: * One section per user persona * Goals * Use Cases * Pain Points This is an opinionated approach suggested by CoreStory. It is optimized for most general use cases, but it is possible to alter the contents of this section via direct edit. ## Who It's For * Business stakeholders validating that the right users and goals are supported * Product managers prioritizing work around real user needs * Developers and architects aligning features, access controls, and data ownership * Support and documentation teams tailoring guidance to each audience ## How to Use It * Start with the summary to understand the full user landscape and how groups relate. * Open a persona to review goals and use cases before changing flows or access rules. * Use the role and permission notes to confirm authorization and guardrails. * Cross-reference primary screens and APIs to locate concrete touchpoints for a persona. * Treat missing fields as a reflection of the current codebase rather than a documentation gap. ## What It Is (and Isn't) * **Is**: a code-derived outline of who uses the system, what they try to accomplish, and where they interact. * **Isn't**: a marketing persona framework or UX research report. For behavior-level details, see User Stories; for contracts and data, see API Specifications and Data Models. # User Stories Source: https://docs.corestory.ai/product/core-documents/user-stories AI-generated user stories derived from your codebase's features and workflows. ## Overview The User Stories section lists goal-oriented behaviors inferred from your codebase, written in the standard format: "As a \[persona], I want to \[behavior], so that \[rationale]." It describes the experience each user should have and the outcomes the system is expected to deliver. The list is generated directly from code and related assets, so fields and coverage vary by project. ## Sections Stories appear in the middle panel and are grouped by epic. Each user story includes the following sections: * User story * Associated epic * Associated persona * Description * Business rules * Code references * Technical requirements * UML class diagram (if available) * Sequence diagram (if available) This is an opinionated approach suggested by CoreStory. It is optimized for most general use cases, but it is possible to alter the contents of this section via direct edit. ## Who It's For * Business stakeholders validating expected behavior * Product managers aligning scope and priorities * Developers and QA planning implementation and tests * Architects reviewing feature boundaries ## How to Use It * Scan by epic to find the relevant story, then read the description to confirm scope. * Use business rules and technical requirements to draft test or validation points. * Follow code references to the exact files that implement the story. * Use diagrams to confirm flow and integration boundaries before refactoring or extending a feature. * When a field is missing, assume the codebase does not expose that information in a form CoreStory can infer; do not treat it as a documentation error. ## What It Is (and Isn't) * **Is**: a code-derived, persona-focused catalog of behaviors and outcomes, suitable for validation and planning. * **Isn't**: a sprint backlog or design document. For interface and endpoint details, see Interface Specifications and API Specifications. For entities and relationships, see Data Models.