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 oracle — 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 playbook. If you’re building specifications for new features and need to understand existing rules as constraints, the Spec-Driven Development playbook’s Ground phase covers that. If you’re evaluating a codebase for acquisition, the M&A 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 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)
- 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 | Oracle |
| 3 | Deep Extraction | Systematically query each rule category, build inventory | Oracle + Navigator |
| 4 | Code Verification | Walk local code to verify rules, find what CoreStory missed | — (local code only) |
| 5 | Documentation & Output | Produce the structured business rules document | Oracle (gap-filling) |
| 6 | Conversation Capture | Rename conversation with RESOLVED prefix | Knowledge capture |
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 |
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.project_id — you’ll use it for every subsequent call.
Step 1.2: Check for prior work.
get_conversation to review it. You may be able to build on prior work rather than starting fresh.
Step 1.3: Create a conversation.
- “Business Rules Extraction — Order Processing Module”
- “Business Rules Extraction — Full System Inventory”
- “Business Rules Extraction — Payment & Tax Rules”
| 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 |
Phase 2 — Architectural Survey (Oracle)
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.| 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 |
- 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_rulesfields.
- 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 (Oracle + 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 |
- 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)
- “Only users in the SUPERADMIN group can assign the SUPERADMIN role to others”
- “Customer operations are scoped to the authenticated user’s merchant store”
- 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)
- 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 4 — 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,@Sizeon 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 CoreHasIndex().IsUnique(), Fluent Validation rules - Ruby/Rails:
validates :field, presence: true,uniqueness: true,format:,numericality:on ActiveRecord models
- 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)
- 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
- 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)
- 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)
| 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) |
- 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)
- 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 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:Phase 6 — Conversation Capture
Goal: Preserve the extraction session for future reference.list_conversations and get_conversation.
Output Format
Each extracted business rule should be documented using this template:Agent Implementation Guides
Claude Code
Create a skill file at.claude/skills/business-rules-extraction/SKILL.md:
GitHub Copilot
GitHub Copilot supports agent skills — folders containing aSKILL.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:
.github/copilot-instructions.md:
Cursor
Create.cursor/rules//playbooks/business-rules-extraction:
Factory.ai
Configure a Droid for business rules extraction:Tips & Best Practices
Query patterns ranked by effectiveness (based on testing against real projects):- 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.
- 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.
- Excellent: Domain-scoped validation queries. “What validation rules exist for [specific entity/workflow]?” — Returns specific constraint values, file paths, and enforcement layers.
- 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.
- Good: Architectural map queries. “Where is business logic implemented — which layers enforce which rule types?” — Produces the essential orientation for targeted follow-up queries.
- 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.
- 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
- 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
- Rules that affect money (pricing, tax, payments, refunds)
- Rules that affect security (authentication, authorization, data access)
- Rules that affect data integrity (state transitions, uniqueness constraints)
- Rules that affect user experience (validation, error handling)
- Rules that affect operations (configuration, thresholds, limits)
- 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?”
- After Phase 3 (before code verification) — to validate extracted rules against business intent
- When you find conflicts between PRD intent and code reality
- For Low-confidence rules that exist only in code with no documentation
- 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 4 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 4 exists specifically to catch these gaps.
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.
Confidence levels are mostly “Low”.
This usually means the codebase has little documentation and the PRD is sparse. Low confidence doesn’t mean the rule is wrong — it means it’s only evidenced in code. Flag these for domain expert validation and consider updating project documentation as a follow-up.