@grimoire-cc/cli 0.6.3 → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/dist/commands/logs.d.ts.map +1 -1
  2. package/dist/commands/logs.js +2 -2
  3. package/dist/commands/logs.js.map +1 -1
  4. package/dist/static/log-viewer.html +946 -690
  5. package/dist/static/static/log-viewer.html +946 -690
  6. package/package.json +1 -1
  7. package/packs/dev-pack/agents/gr.code-reviewer.md +286 -0
  8. package/packs/dev-pack/agents/gr.tdd-specialist.md +44 -0
  9. package/packs/dev-pack/grimoire.json +55 -0
  10. package/packs/dev-pack/skills/gr.tdd-specialist/SKILL.md +247 -0
  11. package/packs/dev-pack/skills/gr.tdd-specialist/reference/anti-patterns.md +166 -0
  12. package/packs/dev-pack/skills/gr.tdd-specialist/reference/language-frameworks.md +388 -0
  13. package/packs/dev-pack/skills/gr.tdd-specialist/reference/tdd-workflow-patterns.md +135 -0
  14. package/packs/docs-pack/grimoire.json +30 -0
  15. package/packs/docs-pack/skills/gr.business-logic-docs/SKILL.md +278 -0
  16. package/packs/docs-pack/skills/gr.business-logic-docs/references/audit-checklist.md +48 -0
  17. package/packs/docs-pack/skills/gr.business-logic-docs/references/tier2-template.md +129 -0
  18. package/packs/essentials-pack/agents/gr.fact-checker.md +202 -0
  19. package/packs/essentials-pack/grimoire.json +12 -0
  20. package/packs/meta-pack/grimoire.json +72 -0
  21. package/packs/meta-pack/skills/gr.context-file-guide/SKILL.md +201 -0
  22. package/packs/meta-pack/skills/gr.context-file-guide/scripts/validate-context-file.sh +29 -0
  23. package/packs/meta-pack/skills/gr.readme-guide/SKILL.md +362 -0
  24. package/packs/meta-pack/skills/gr.skill-developer/SKILL.md +321 -0
  25. package/packs/meta-pack/skills/gr.skill-developer/examples/brand-guidelines.md +94 -0
  26. package/packs/meta-pack/skills/gr.skill-developer/examples/financial-analysis.md +85 -0
  27. package/packs/meta-pack/skills/gr.skill-developer/reference/best-practices.md +410 -0
  28. package/packs/meta-pack/skills/gr.skill-developer/reference/file-organization.md +452 -0
  29. package/packs/meta-pack/skills/gr.skill-developer/reference/patterns.md +459 -0
  30. package/packs/meta-pack/skills/gr.skill-developer/reference/yaml-spec.md +214 -0
  31. package/packs/meta-pack/skills/gr.skill-developer/scripts/create-skill.sh +210 -0
  32. package/packs/meta-pack/skills/gr.skill-developer/scripts/validate-skill.py +520 -0
  33. package/packs/meta-pack/skills/gr.skill-developer/templates/basic-skill.md +94 -0
  34. package/packs/meta-pack/skills/gr.skill-developer/templates/domain-skill.md +108 -0
@@ -0,0 +1,30 @@
1
+ {
2
+ "name": "docs-pack",
3
+ "version": "1.0.0",
4
+ "agents": [],
5
+ "skills": [
6
+ {
7
+ "name": "grimoire:business-logic-docs",
8
+ "path": "skills/gr.business-logic-docs",
9
+ "description": "Create and maintain structured business logic documentation for AI assistants and developers. Use when documenting business rules, domain knowledge, invariants, workflows, state machines, entity relationships, decision logs, or building a business logic knowledge base.",
10
+ "triggers": {
11
+ "keywords": [],
12
+ "file_extensions": [],
13
+ "patterns": [
14
+ "document.*business",
15
+ "business.*logic",
16
+ "business.*rule",
17
+ "domain.*knowledge",
18
+ "knowledge.*base",
19
+ "document.*domain",
20
+ "document.*invariant",
21
+ "document.*workflow",
22
+ "decision.*log"
23
+ ],
24
+ "file_paths": [
25
+ "**/docs/business-logic/**"
26
+ ]
27
+ }
28
+ }
29
+ ]
30
+ }
@@ -0,0 +1,278 @@
1
+ ---
2
+ name: grimoire:business-logic-docs
3
+ description: "Create, update, and audit structured business logic documentation for AI assistants and developers. Use when documenting business rules, domain knowledge, invariants, workflows, state machines, entity relationships, decision logs, building a business logic knowledge base, or reviewing docs for staleness."
4
+ ---
5
+
6
+ # Business Logic Documentation
7
+
8
+ Guide Claude through creating, updating, and auditing a structured knowledge base of a project's business logic. The knowledge base serves two audiences: AI coding assistants (so they understand domain context and make better decisions) and human developers (so they can recall and reason about business rules).
9
+
10
+ All generated documentation lives in `docs/business-logic/` by default. Ask the developer if they prefer a different path before generating.
11
+
12
+ **Core principle: business rules drive code, not vice versa.** Business logic documentation captures decisions that drive code changes — not descriptions of what code does. The flow is always: business decision → documentation → code implementation.
13
+
14
+ ## Workflow 1 — Create the Initial Knowledge Base
15
+
16
+ Use this when a project has no business logic docs yet.
17
+
18
+ ### Step 1: Discover Domain Areas
19
+
20
+ Examine the codebase to identify bounded contexts:
21
+
22
+ - **Folder structure**: Top-level directories, module boundaries, feature folders
23
+ - **Entity names**: Database models, domain classes, type definitions
24
+ - **Route groupings**: API endpoints, controller organization
25
+ - **Naming patterns**: Prefixes/suffixes that suggest domain separation (e.g., `order-`, `payment-`, `inventory-`)
26
+
27
+ Produce a preliminary list of domain areas and share it with the developer for confirmation before proceeding.
28
+
29
+ ### Step 2: Interview the Developer
30
+
31
+ Surface business rules that aren't obvious from code alone. Ask focused questions in small batches (3-5 at a time) to avoid overwhelming. Prioritize:
32
+
33
+ 1. **Domain terminology** — "What terms does your team use that have precise meanings? Any terms that are commonly confused?"
34
+ 2. **User roles and permissions** — "What roles exist, and what can each role do or not do?"
35
+ 3. **Critical invariants** — "What must always be true? What must never happen?"
36
+ 4. **Hard constraints** — "What things MUST NEVER happen in the system? What would cause the most damage if violated?"
37
+ 5. **Non-obvious edge cases** — "What scenarios have caused bugs or confusion before?"
38
+ 6. **Regulatory or legal rules** — "Are any business rules driven by compliance requirements?"
39
+
40
+ After each batch of answers, ask follow-up questions if something needs clarification. Move to the next domain area once coverage feels sufficient.
41
+
42
+ ### Step 3: Generate the Documentation
43
+
44
+ Create the three-tier structure described below. For each domain area identified:
45
+
46
+ 1. Create the Tier 2 file using the template from [references/tier2-template.md](references/tier2-template.md)
47
+ 2. Fill in what you learned from the interview. For rules surfaced from code analysis (not confirmed by the developer), mark with `[SOURCE: code-audit — unconfirmed]` — these MUST be confirmed before being treated as business rules.
48
+ 3. Mark sections where information is incomplete with `<!-- TODO: clarify with team -->`
49
+
50
+ Then create the `_overview.md` (Tier 1) and `_decision-log.md` (Tier 3) files.
51
+
52
+ ### Step 4: Integrate with CLAUDE.md
53
+
54
+ Add a reference to the knowledge base in the project's `CLAUDE.md` (create one if it doesn't exist). See [CLAUDE.md Integration](#claudemd-integration) below.
55
+
56
+ ## Workflow 2 — Update the Existing Knowledge Base
57
+
58
+ Use this when business logic changes. Updates are driven by text input — user stories, change requests, discussion transcripts/summaries — not by code analysis.
59
+
60
+ ### Step 1: Understand the Change
61
+
62
+ Read the provided input (user story, change request, discussion transcript/summary). Extract:
63
+
64
+ - What business rules are being added, modified, or removed
65
+ - Which domain area(s) and Tier 2 file(s) are affected
66
+
67
+ Do NOT look at code to infer business rules — the provided input is the single source of truth. If the input is ambiguous or incomplete, ask the user for clarification before proceeding.
68
+
69
+ ### Step 2: Review Existing Documentation
70
+
71
+ Read the affected Tier 2 file(s). For each change from Step 1, check:
72
+
73
+ - Does it contradict any existing rule?
74
+ - Does it modify an existing rule or add a new one?
75
+ - Does it affect workflows, entities, or integration points?
76
+ - Does it invalidate any existing constraints, examples, or counterexamples?
77
+
78
+ Flag any conflicts or ambiguities to the user before making changes.
79
+
80
+ ### Step 3: Clarify Uncertainties
81
+
82
+ If anything from the input is unclear, contradicts existing docs, or leaves gaps, ask the user targeted questions. Examples:
83
+
84
+ - "The user story says X, but the current docs say Y — which is correct?"
85
+ - "This change implies Z — is that intended?"
86
+ - "Are there edge cases for this new rule?"
87
+ - "Does this replace the existing rule or add a new exception?"
88
+
89
+ NEVER proceed with uncertain information. NEVER fill gaps by guessing from code.
90
+
91
+ ### Step 4: Apply the Updates
92
+
93
+ Only add information you are certain about from the provided input.
94
+
95
+ - **Modified rules**: Replace the old rule with the new one. Don't annotate what changed — git tracks history.
96
+ - **New rules**: Use the template format from [references/tier2-template.md](references/tier2-template.md). Include Source marker.
97
+ - **Removed rules**: Delete them. Only keep a note about the removal if it carries business context that other rules depend on (e.g., "we no longer support gift cards" is useful if other rules reference gift cards).
98
+ - **New domain areas**: Create a new Tier 2 file and add it to the table of contents in `_overview.md`.
99
+ - **"Enforced in" fields**: Leave empty or mark with `<!-- TODO: add code location after implementation -->` — code locations are filled in after implementation, not before.
100
+ - **Diagrams and glossary**: Update as needed to reflect changes.
101
+
102
+ ### Step 5: Validate and Present
103
+
104
+ Verify:
105
+
106
+ - No contradictions introduced across files
107
+ - Diagrams reflect the changes
108
+ - Table of contents is accurate
109
+ - Terminology is consistent with the glossary
110
+ - Decision log entry added if the change involves a non-obvious decision
111
+
112
+ Present a summary to the user showing exactly what was changed and why, so they can confirm accuracy.
113
+
114
+ ## Workflow 3 — Audit Knowledge Base
115
+
116
+ Use only when the user explicitly requests an audit or review of existing documentation.
117
+
118
+ This is the one workflow where code comparison is appropriate — but only to flag potential gaps, never to infer new business rules.
119
+
120
+ ### Step 1: Review Documentation Completeness
121
+
122
+ Check for structural issues using [references/audit-checklist.md](references/audit-checklist.md):
123
+
124
+ - Unresolved `<!-- TODO -->` markers
125
+ - Empty or placeholder sections
126
+ - Rules missing "Why" explanations
127
+ - Critical rules without counterexamples
128
+ - Constraints section empty or missing
129
+
130
+ ### Step 2: Check Code Alignment
131
+
132
+ **Only when the user explicitly asks to compare docs against code.** Check:
133
+
134
+ - "Enforced in" references still point to existing code
135
+ - State diagram transitions match actual code behavior
136
+ - Entity attributes match current schema
137
+
138
+ Flag undocumented code behavior as questions, not assertions: "This code seems to enforce X, but it's not documented — is this a business rule that should be captured?" Mark any rules surfaced this way with `[SOURCE: code-audit — unconfirmed]`.
139
+
140
+ ### Step 3: Check Terminology Consistency
141
+
142
+ - Extract all glossary terms from `_overview.md`
143
+ - Search Tier 2 files for inconsistent usage (synonyms, abbreviations, variant spellings)
144
+ - Report inconsistencies in the format described in [references/audit-checklist.md](references/audit-checklist.md)
145
+
146
+ ### Step 4: Produce Audit Report
147
+
148
+ Structured output with sections:
149
+
150
+ 1. **Incomplete Items** — Missing Why, missing examples, empty sections, unresolved TODOs
151
+ 2. **Terminology Issues** — Inconsistent term usage across files
152
+ 3. **Structural Issues** — ToC mismatches, missing template sections, duplicated rules
153
+ 4. **Potential Documentation Gaps** *(only if Step 2 was performed)* — Code behavior not reflected in docs
154
+
155
+ Ask the developer to review and confirm before making any changes.
156
+
157
+ ## Three-Tier Documentation Structure
158
+
159
+ ### Tier 1 — `_overview.md`
160
+
161
+ The entry point. Contains:
162
+
163
+ - **Business summary**: 2-3 paragraphs — enough for a newcomer to orient.
164
+ - **Glossary**: Domain terms with precise definitions. This prevents AI and humans from confusing terms.
165
+ - **User roles**: Each role's capabilities and restrictions.
166
+ - **Domain area map**: High-level view of how domain areas relate to each other. Use a mermaid diagram if relationships are non-trivial.
167
+ - **Table of contents**: Links to every Tier 2 file.
168
+
169
+ ### Tier 2 — One File Per Domain Area
170
+
171
+ E.g., `orders.md`, `payments.md`, `inventory.md`. Each follows the template in [references/tier2-template.md](references/tier2-template.md). Key sections:
172
+
173
+ - **Purpose** — What this area does and why it exists.
174
+ - **Key Entities** — Core entities, attributes, relationships. Use mermaid for non-trivial relationships.
175
+ - **Constraints** — The highest-value content. MUST and MUST NOT rules with business reasons.
176
+ - **Business Rules & Invariants** — Each rule states: what the rule is, why it exists (the business reason), where it's enforced in code, a concrete example including an edge case, and for critical rules a counterexample.
177
+ - **Workflows & State Transitions** — Key processes with mermaid state diagrams for anything with 3+ states. Specify triggers and validations.
178
+ - **Decision Trees** — Sequential if-then format for multi-branch conditional logic.
179
+ - **Integration Points** — External systems, APIs, other domain areas. Note contracts and assumptions.
180
+ - **Edge Cases & Known Gotchas** — Non-obvious behaviors that have caused bugs or confusion.
181
+
182
+ ### Tier 3 — `_decision-log.md`
183
+
184
+ A chronological record of non-obvious business decisions. Append-only — new entries go at the top, old entries are never edited. If a decision is reversed, add a new entry referencing the original.
185
+
186
+ Each entry follows:
187
+
188
+ ```markdown
189
+ ## YYYY-MM-DD — [Short title]
190
+ **Context:** What situation prompted this decision.
191
+ **Decision:** [Chosen option] because [justification], to achieve [desired outcome], accepting [tradeoff].
192
+ **Alternatives considered:** What else was evaluated and why it was rejected.
193
+ **Affected areas:** Which Tier 2 files are impacted.
194
+ ```
195
+
196
+ ## Writing Principles
197
+
198
+ Follow these when writing or updating business logic docs:
199
+
200
+ 1. **Write for reasoning, not just reading.** Always include the "why" behind a rule. Instead of "Users can't delete invoices," write "Users can't delete invoices because downstream accounting reconciliation depends on invoice immutability. Soft-delete via `deleted_at` is used instead." The causal chain enables correct inferences.
201
+
202
+ 2. **Be explicit about invariants.** Things that must always or never be true are the highest-value content. Call them out prominently in the Constraints section of every domain area file.
203
+
204
+ 3. **Link business concepts to code landmarks.** Don't describe implementation details, but do say "Order state transitions are enforced in `OrderStateMachine` — never manipulate `order.status` directly." This bridges conceptual and concrete.
205
+
206
+ 4. **Use concrete examples over abstract rules.** Instead of "discounts are applied hierarchically," show: "A user with a 10% loyalty discount buying a product with a 20% sale: sale price first ($100 -> $80), then loyalty ($80 -> $72). Total discount is 28%, not 30%."
207
+
208
+ 5. **Prefer mermaid diagrams for state machines and entity relationships.** They're diffable in PRs, render in GitHub, and Claude can read and generate them.
209
+
210
+ 6. **Don't duplicate what git tracks.** No version headers, no changelogs inside docs. The decision log is the sole exception because chronological "why" context is its purpose.
211
+
212
+ 7. **Group by domain area, not by technical layer.** Everything about orders (validation, state machine, permissions, integrations) goes in `orders.md`, not split across "validations.md" and "permissions.md".
213
+
214
+ 8. **Constraints before capabilities.** Document what MUST NOT happen before documenting what should happen. Use explicit RFC-2119 language (MUST, MUST NOT, SHOULD, SHOULD NOT) for rules that carry enforcement weight.
215
+
216
+ 9. **Include counterexamples for critical rules.** For every invariant and constraint, show the wrong behavior and why it fails. Format: what the correct behavior is, what the incorrect behavior looks like, and why it matters.
217
+
218
+ 10. **Use decision trees for complex conditional logic.** Any logic with 3+ branches MUST use sequential if-then format. Mark mutually exclusive paths explicitly. No prose-only descriptions for multi-branch logic.
219
+
220
+ 11. **Mark information sources.** Tag rules with their origin: `[SOURCE: user-story]`, `[SOURCE: discussion]`, `[SOURCE: change-request]`. During audits (Workflow 3 only), rules surfaced from code analysis get `[SOURCE: code-audit — unconfirmed]` and MUST be confirmed with the user before being treated as business rules. Incorrect docs are worse than missing docs.
221
+
222
+ 12. **State machines over prose for workflows.** Any process with 3+ states MUST use a mermaid stateDiagram plus a transition table. No prose-only workflow descriptions for stateful processes.
223
+
224
+ ## Documentation Clarity
225
+
226
+ Docs describe the current state, not history:
227
+
228
+ - When a rule changes, **replace it** — don't annotate what it used to be. Git tracks history.
229
+ - No "previously was", "changed from X to Y", "before it was" language.
230
+ - Remove rules that no longer apply. Only keep a note about the removal if it carries business context other rules depend on (e.g., "we no longer support gift cards" is useful if other rules reference gift cards).
231
+ - Use `<!-- TODO -->` markers only for genuinely incomplete information that needs user input.
232
+ - Every statement in the docs should describe what IS true right now.
233
+
234
+ ## ALWAYS / NEVER
235
+
236
+ ### ALWAYS
237
+
238
+ - ALWAYS confirm the output path before generating files
239
+ - ALWAYS include "Why" for every rule and constraint
240
+ - ALWAYS ask for clarification when input is ambiguous or incomplete
241
+ - ALWAYS verify new information doesn't contradict existing rules
242
+ - ALWAYS present a summary of all changes for user confirmation
243
+ - ALWAYS update the Table of Contents when files are added or removed
244
+ - ALWAYS add a decision log entry for non-obvious changes
245
+ - ALWAYS leave "Enforced in" empty when the code location is unknown
246
+
247
+ ### NEVER
248
+
249
+ - NEVER guess or infer business rules from code — business rules drive code, not vice versa
250
+ - NEVER add information you are not certain about
251
+ - NEVER proceed when the input contradicts existing documentation — ask first
252
+ - NEVER reverse-engineer business rules from code changes unless the user explicitly requests it
253
+ - NEVER use "previously was" / "changed from X to Y" / history annotations — docs describe current state, git tracks history
254
+ - NEVER leave diagrams contradicting documented transitions
255
+ - NEVER duplicate rules across files — reference the canonical location instead
256
+
257
+ ## CLAUDE.md Integration
258
+
259
+ Add (or update) the following section in the project's `CLAUDE.md`:
260
+
261
+ ```markdown
262
+ ## Business Logic Documentation
263
+ Before modifying business logic, read the relevant file in `docs/business-logic/`.
264
+ When your changes affect business rules, update the corresponding doc in the same commit.
265
+ If no file exists for the domain area, create one following the structure of existing files.
266
+ Start with `docs/business-logic/_overview.md` for domain orientation.
267
+ Rules marked `[SOURCE: code-audit — unconfirmed]` need human confirmation before relying on them.
268
+ ```
269
+
270
+ If the developer chose a custom docs path, adjust the paths accordingly.
271
+
272
+ ## Limitations
273
+
274
+ - This skill provides guidance for creating documentation, not executable code.
275
+ - The knowledge base captures business rules at a point in time — it requires human input for rules that aren't visible in code.
276
+ - Rules inferred from code (`[SOURCE: code-audit — unconfirmed]`) require human verification before they should be treated as authoritative business rules.
277
+ - Mermaid diagrams may not render in all environments (they work in GitHub, VS Code, and most modern markdown viewers).
278
+ - The decision log is only as valuable as the team's discipline in maintaining it.
@@ -0,0 +1,48 @@
1
+ # Audit Checklist
2
+
3
+ Use this checklist with [Workflow 3 — Audit Knowledge Base](../SKILL.md#workflow-3--audit-knowledge-base).
4
+
5
+ ## Code Alignment Checks
6
+
7
+ Only perform when the user explicitly requests code comparison.
8
+
9
+ - [ ] Every "Enforced in" reference points to a file/class/function that still exists
10
+ - [ ] Mermaid state diagrams match actual state transitions in code
11
+ - [ ] Entity attributes listed in docs match the current schema/model definitions
12
+ - [ ] Integration contracts (endpoints, payloads) match actual API implementations
13
+ - [ ] Decision trees match actual conditional logic in code
14
+
15
+ Present findings as questions, not assertions. Example: "This code seems to enforce X, but it's not documented — is this a business rule that should be captured?"
16
+
17
+ ## Content Quality Checks
18
+
19
+ - [ ] Every business rule has a "Why" explanation
20
+ - [ ] Critical rules (invariants, constraints) have counterexamples
21
+ - [ ] No unconfirmed `[SOURCE: code-audit — unconfirmed]` markers older than 30 days
22
+ - [ ] Decision trees exist for multi-branch logic (3+ paths)
23
+ - [ ] Constraints section populated with MUST / MUST NOT items
24
+ - [ ] Examples use concrete values, not abstract descriptions
25
+
26
+ ## Structural Checks
27
+
28
+ - [ ] Table of Contents in `_overview.md` lists all Tier 2 files
29
+ - [ ] Each Tier 2 file has all template sections (even if marked TODO)
30
+ - [ ] Glossary terms in `_overview.md` are consistent across all files
31
+ - [ ] No business rules duplicated across multiple Tier 2 files
32
+ - [ ] All `<!-- TODO -->` markers reviewed — resolve or confirm still pending
33
+ - [ ] Decision log entries reference correct Tier 2 files in "Affected areas"
34
+
35
+ ## Terminology Consistency Check
36
+
37
+ For each term in the glossary:
38
+
39
+ 1. Search all Tier 2 files for the term
40
+ 2. Search for common synonyms or abbreviations
41
+ 3. Flag any file that uses a synonym instead of the glossary term
42
+ 4. Check that the term's definition still matches how it's used in context
43
+
44
+ Report format:
45
+
46
+ | Term | Expected | Found | File | Line |
47
+ |---|---|---|---|---|
48
+ | `[glossary term]` | `[glossary term]` | `[synonym found]` | `[file]` | `[line]` |
@@ -0,0 +1,129 @@
1
+ # [Domain Area Name]
2
+
3
+ ## Table of Contents
4
+
5
+ - [Purpose](#purpose)
6
+ - [Key Entities](#key-entities)
7
+ - [Constraints](#constraints)
8
+ - [Business Rules & Invariants](#business-rules--invariants)
9
+ - [Workflows & State Transitions](#workflows--state-transitions)
10
+ - [Decision Trees](#decision-trees)
11
+ - [Integration Points](#integration-points)
12
+ - [Edge Cases & Known Gotchas](#edge-cases--known-gotchas)
13
+
14
+ ## Purpose
15
+
16
+ One-paragraph summary of what this area does and why it exists.
17
+
18
+ ## Key Entities
19
+
20
+ List the core entities, their key attributes, and relationships. Use a mermaid diagram if relationships are non-trivial.
21
+
22
+ ```mermaid
23
+ erDiagram
24
+ ENTITY_A ||--o{ ENTITY_B : "relationship"
25
+ ENTITY_A {
26
+ string id
27
+ string name
28
+ datetime created_at
29
+ }
30
+ ENTITY_B {
31
+ string id
32
+ string entity_a_id
33
+ string status
34
+ }
35
+ ```
36
+
37
+ ## Constraints
38
+
39
+ The highest-value content — what MUST and MUST NOT happen in this domain area.
40
+
41
+ ### MUST
42
+
43
+ - **Constraint**: State what must always be true.
44
+ - **Why**: Business reason this constraint exists.
45
+ - **Enforced in**: File, class, or function name.
46
+
47
+ ### MUST NOT
48
+
49
+ - **Constraint**: State what must never happen.
50
+ - **Why**: Business reason — what goes wrong if violated.
51
+ - **Enforced in**: File, class, or function name.
52
+
53
+ ## Business Rules & Invariants
54
+
55
+ Each rule follows this pattern:
56
+
57
+ - **Rule**: State the rule clearly.
58
+ - **Why**: Explain the business reason (this enables AI to reason correctly in adjacent code).
59
+ - **Enforced in**: Point to where in the codebase this is enforced (file, class, or function name). Leave empty or use `<!-- TODO: add code location after implementation -->` if not yet implemented.
60
+ - **Example**: A concrete scenario illustrating the rule, including at least one edge case.
61
+ - **Counterexample** *(critical rules)*: Show the wrong behavior and why it fails.
62
+ - **Source**: `[SOURCE: user-story]`, `[SOURCE: discussion]`, `[SOURCE: change-request]`, or `[SOURCE: code-audit — unconfirmed]`.
63
+
64
+ ---
65
+
66
+ - **Rule**: [Example] An order cannot be modified after it enters "shipped" status.
67
+ - **Why**: Downstream logistics systems snapshot the order at shipment time; modifications would cause fulfillment mismatches.
68
+ - **Enforced in**: `OrderStateMachine.validateTransition()` rejects edits on shipped orders.
69
+ - **Example**: A customer tries to change their shipping address 5 minutes after shipment. The system returns a 409 Conflict with instructions to contact support for a redirect request instead.
70
+ - **Counterexample**: If the system allowed edits after shipment, the warehouse would ship to the old address while the customer sees the new one — causing a lost package and a support ticket.
71
+ - **Source**: `[SOURCE: user-story]`
72
+
73
+ ## Workflows & State Transitions
74
+
75
+ Describe key processes. Use mermaid state diagrams for anything with 3+ states. Specify who/what triggers each transition and what validations occur.
76
+
77
+ ```mermaid
78
+ stateDiagram-v2
79
+ [*] --> Draft
80
+ Draft --> Pending : submit (user)
81
+ Pending --> Approved : approve (admin)
82
+ Pending --> Rejected : reject (admin)
83
+ Approved --> Completed : fulfill (system)
84
+ Rejected --> [*]
85
+ Completed --> [*]
86
+ ```
87
+
88
+ | Transition | Triggered by | Validations |
89
+ |---|---|---|
90
+ | Draft -> Pending | User submits | All required fields present, passes schema validation |
91
+ | Pending -> Approved | Admin approves | Admin has `approve` permission, item passes compliance check |
92
+ | Pending -> Rejected | Admin rejects | Rejection reason is required |
93
+ | Approved -> Completed | System fulfills | External service confirms fulfillment |
94
+
95
+ ## Decision Trees
96
+
97
+ Use sequential if-then format for multi-branch conditional logic. Mark mutually exclusive paths explicitly.
98
+
99
+ ```
100
+ IF [condition A]
101
+ THEN [action/outcome 1]
102
+ ELSE IF [condition B] ← mutually exclusive with A
103
+ IF [sub-condition B1]
104
+ THEN [action/outcome 2]
105
+ ELSE
106
+ THEN [action/outcome 3]
107
+ ELSE ← default / fallback
108
+ THEN [action/outcome 4]
109
+ ```
110
+
111
+ ## Integration Points
112
+
113
+ External systems, APIs, webhooks, or other domain areas this module interacts with. Note any contracts or assumptions.
114
+
115
+ - **[System/API name]**: Brief description of the integration, what data flows in which direction, and any assumptions about availability or response format.
116
+
117
+ ## Edge Cases & Known Gotchas
118
+
119
+ Non-obvious behaviors that have caused bugs or confusion before. These are extremely high-value for AI assistants.
120
+
121
+ - **[Gotcha title]**: Description of the non-obvious behavior, why it exists, and what to watch out for when modifying related code.
122
+
123
+ <!--
124
+ Staleness markers — use these in comments to flag items for review:
125
+
126
+ <!-- TODO: clarify with team -->
127
+ <!-- TODO: add code location after implementation -->
128
+ <!-- STALE? last verified YYYY-MM-DD — needs review -->
129
+ -->