Skip to main content

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

PhaseNamePurposeCoreStory Role
1Setup & ScopingSelect project, create conversation, define extraction scopeSetup
2Architectural SurveyMap where business logic lives, identify rule categoriesOracle
3Deep ExtractionSystematically query each rule category, build draft inventoryOracle + Navigator
4ACode VerificationWalk local code to verify rules, find what CoreStory missed— (local code only)
4BEnforcement VerificationProve that rules claiming enforcement actually enforce at runtimeOracle + local code
4CFlow-Trace DiscoveryTrace end-to-end user flows to find behaviors missed by domain extractionOracle + local code
5Documentation & OutputProduce the structured business rules document with confidence levelsOracle (gap-filling)
6Conversation CaptureRename conversation with RESOLVED prefixKnowledge capture
The core principle is Oracle 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

ToolPhase(s)Purpose
list_projects1Find the target project
create_conversation1Create a persistent conversation for the extraction session
send_message2, 3, 5Query CoreStory for rules, architecture, and gap-filling
get_project_prd2Retrieve the PRD for rule-adjacent requirements (see note below)
get_project_techspec2Retrieve the TechSpec for data model constraints and architecture
list_conversations1Check for prior extraction sessions to build on
get_conversation1Resume a prior extraction session
rename_conversation6Mark 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 = <your project>
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 = <your project>
  title = "Business Rules Extraction — <scope description>"
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:
ScopeWhen to Use
Single moduleYou need rules for one specific area (e.g., payments, auth)
Single domainYou need rules across a domain (e.g., all e-commerce rules)
Full systemYou 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 (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.
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:
LayerTypical Rule TypesExamples by Stack
Service / business logic layerCore rules, state transitions, calculationsSpring @Service, Django service modules, Express middleware, .NET application services
Validation layerInput validation, format constraints, required fieldsBean Validation annotations, Pydantic models, Joi/Zod schemas, FluentValidation
Auth / security layerAuthentication, authorization, role checksSpring Security, Django permissions, Passport.js, ASP.NET Identity
Data / persistence layerIntegrity constraints, uniqueness, referential integrityJPA/Hibernate annotations, Django model constraints, Sequelize validations, EF Core configurations
API / controller layerRequest validation, error formattingController annotations, serializer validation, request middleware
ConfigurationEnvironment-specific behavior, feature flags, thresholdsProperties 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:
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."
This lets CoreStory surface the rules from the PRD without the agent needing to hold the entire document in context. 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 (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:
QueryQuality 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.5: Extract invariants and constraints.
Tool: send_message
Query: "What are the invariants that must always hold for [entity, e.g.,
MerchantStore, Customer, Product]? What constraints exist on its
configuration, and what happens if they're violated?"
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. 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:
SourceWhat 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 TypeDefinitionVerification 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-IDClaim TypeEnforcement PointViolation BehaviorScopeLevelStatus
(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 = <your project>
  conversation_id = <your conversation>
  title = "RESOLVED — Business Rules Extraction — <scope description>"
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:
### 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"]
- **Invariants:** [What must always be true for this rule to hold]
- **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:
# 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

Claude Code

Create a skill file at .claude/skills/business-rules-extraction/SKILL.md:
---
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"
---
# 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 — <scope>"
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: "Based on the technical specification, what are the
   key data model constraints — required fields, unique constraints, valid
   states, and relationships between entities?"
4. 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]?"
- "What invariants must hold for [entity]?"
- "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.

## 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 — <scope>"

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:
---
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."
---
# 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 — <scope>"
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: "Based on the technical specification, what are the
   key data model constraints — required fields, unique constraints, valid
   states, and relationships between entities?"
4. 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]?"
- "What invariants must hold for [entity]?"
- "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.

## 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 — <scope>"

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:
## Business Rules Extraction

When asked to extract or document business rules:
1. ALWAYS query CoreStory before searching code (Oracle 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. Verify every CoreStory finding against local source code (Phase 4A)
5. For Constraint/Validation/Authorization rules, verify enforcement:
   find the rejection point, not just the declaration (Phase 4B)
6. Trace end-to-end user flows to catch behaviors missed by domain
   extraction (Phase 4C)
7. Document using the BR-XXX format with confidence levels (Confirmed,
   Corrected, New) and enforcement metadata
8. Rename the CoreStory conversation with "RESOLVED" prefix when done

Cursor

Create .cursor/rules//playbooks/business-rules-extraction:
# 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 (Oracle 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]?"

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:
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)
  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.