Bootstrap AI-Docs and deep-review skill for a new repository
Use this prompt to bootstrap, in a previously undocumented codebase, a documentation + review-skill stack that captures the system's business invariants and technical premises in a form future AI agents (and humans) can load as context. The end goal is for a /deep-review slash-command in the target repo to produce findings well above a generic review.
Token spend is not a constraint here. Depth is. The output is high-leverage: one good bootstrap is read by every future session.
Operator (the human running this): paste this whole prompt into a fresh Claude Code session in the target repo. Confirm you'll be available to answer interview questions — the agent will block on you for things only you know. Once finished, the agent will have created docs/CORE_TENETS.md, docs/index.md, docs/{domain}/premises.md for each domain, .claude/skills/deep-review/SKILL.md, and updated CLAUDE.md. If the codebase owns a database schema, the agent will also create docs/schema/index.md and docs/schema/{domain}.md per domain — otherwise the schema layer is skipped. Plan for at least one full working session.
0. Mental model — what we're producing and why
The artifacts below answer different questions for different readers. Don't merge them.
File
Reader
Question it answers
docs/CORE_TENETS.md
Senior engineer new to the domain
"What business rules cannot be broken?" Conceptual entities, end-to-end flow, named invariants, edge-cases the system explicitly handles.
docs/index.md
Any reader
"Where do I find what I need?" Pure routing. No content.
docs/schema/index.md(only if repo owns DB code — see §1.4)
Anyone writing SQL
"Which table belongs to which domain, and what's the naming convention?" Plus a "common wrong guesses" table.
docs/schema/{domain}.md(only if repo owns DB code)
Anyone writing SQL against that domain
"What are the exact column names, types, enums, indexes, FKs in this domain?"
docs/{domain}/premises.md
Anyone modifying code in this domain
"What technical invariants does this domain assume? What breaks if I violate them? Which test protects each premise?"
docs/{domain}/<topic>.md
Engineers touching a specific subsystem
"How does this calculation/integration actually work, with examples?"
.claude/skills/deep-review/SKILL.md
The /deep-review agent
"How do I review changes through the lens of this codebase's domain?"
Two key distinctions to keep clean:
Business rules (CORE_TENETS) vs. technical premises ({domain}/premises.md). Business rules are facts about the world the product models ("we only transfer the regular amount; overpayment becomes store credit"). Premises are facts about the implementation that downstream code silently depends on ("entity X is never updated after creation; the audit join table requires this"). The same idea may appear in both, framed differently — that's fine.
Schema docs (docs/schema/) vs. domain knowledge (docs/{domain}/). Schema is pure table reference and only exists when the repo owns database code. Domain knowledge is calculation/integration/lifecycle prose and exists regardless.
Conditional layer — the schema docs. If this repo does not own a database schema (e.g., it's a pure-logic library, a CLI, a UI-only frontend, a thin client wrapping someone else's API, an SDK), skip the schema layer entirely. Section 4 below has an explicit gate. The CORE_TENETS / premises / deep-review skill still apply.
Why this works at all: AI agents in undocumented repos guess. Guesses about money flow are catastrophic in fintech-shaped systems and merely embarrassing elsewhere. The premises files in particular surface invariants that are invisible from reading code in isolation — the kind that only emerge when you stack multiple files together or run a flow end-to-end. Once written down, a reviewer agent can check changes against them.
1. Reconnaissance — read before you ask
Do NOT start interviewing the human until you have a working mental map. Run these in parallel where possible.
1.1 Repo shape
git ls-files | head -200 and git ls-files | wc -l — orient yourself on size and layout.
For each entity, capture: package/folder, immutability hints (updatable = false, @Immutable, readonly, frozen=True), primary key strategy, status enum values, soft-delete columns vs status-based cancellation, audit-table conventions.
Look for state machines or status transition guards: methods named canTransitionTo, validateTransition, transitionTo, decorators, enums with explicit allowed-next sets. These are premise goldmines.
1.3 Money / unit-of-value / atomicity
For any system that moves money, accounts, points, or scarce resources, find the atomic unit. Specifically look for:
Money column types (BIGINT cents vs DECIMAL vs numeric(18,2)) — fix the convention.
Ledger-style tables (entries that are append-only, with debit/credit semantics).
"Settlement" / "transaction" / "event" / "movement" tables — anything that registers an externally caused change.
Also search broadly for ORM/entity definitions (@Entity, class \w+\(Base\), models.Model, Prisma model , Diesel table!, etc.).
Decision:
Repo owns DB code (migrations, schema source, or ORM entity definitions present) → the schema layer applies. Continue reading this section.
Repo does NOT own DB code (pure library, CLI, UI, SDK, thin API client) → skip this section, skip §4 (schema drafting) entirely, and proceed with CORE_TENETS + premises + deep-review only.
Ambiguous case (e.g., reads from a shared DB owned by another service, or uses an external API as its data source) → confirm with the human. Default to not writing schema docs the human would have to keep in sync with someone else's system; instead capture the contract in a docs/{domain}/<external-system>.md knowledge doc.
If the schema layer applies, continue with the reconnaissance:
Skim the most recent ~10 migrations: those name the current concerns of the team. Anything you read in old migrations may have been renamed.
For Postgres specifically, look for: CHECK constraints, partial unique indexes (WHERE), EXCLUDE constraints, ON CONFLICT patterns, triggers. These often encode invariants the application code assumes.
Renames are dangerous. git log --diff-filter=R --follow per file and inspecting migration files that mention RENAME catches the most common "common gotchas" entries (e.g., a field everyone now calls customer_id but which used to be company_id).
1.5 Services, events, and async flow
Find the request-handling layer (controllers, handlers, resolvers, RPC endpoints).
Build an event topology: which services publish events, on which topics/queues, consumed by which listeners? Look for convertAndSend, publish, enqueue, send_message, produce. Cross-reference subscribers/handlers.
Identify fan-out outboxes (a single publish that drives multiple downstream listeners). These are premise-rich: each subscriber introduces an implicit "this event will be fired exactly once on commit" assumption.
Identify transactional boundaries: where do transactions start and end? Are there post-commit hooks? Is @Transactional used? transaction.atomic()? BEGIN/COMMIT?
1.6 Tests
Test directory structure, test types (unit / integration / e2e), what containers/fixtures are used (testcontainers, in-memory, mocks).
Existing test naming conventions (these will inform how premise **Tests:** fields cite tests).
Architecture tests (ArchUnit, dependency-cruiser, custom lint) — these are premise-protectors and a model for new ones.
1.7 What you've learned, written down
Before going to the human, summarize for yourself (don't post it):
Top 5–10 entities and how they relate (draw it on paper / a scratch file).
The "happy path" of the core use case: from input to persistence to downstream effects.
3–5 things that surprised you or you don't yet understand.
3–5 places where the code clearly assumes something the code itself doesn't enforce (these are premise candidates).
If you cannot do this after reconnaissance, you don't have enough context to interview the human productively. Do another pass.
2. Interview the human
The human is your single best source for why. Code tells you what; the human tells you why this invariant exists, what broke last quarter, what's load-bearing for the business, what's an accident of history.
Use the AskUserQuestion tool for closed-ended choices, but for open-ended questions write them as plain prose and wait for the answer. Ask in small batches (3–6 questions at a time) so the human can answer without getting overwhelmed. Iterate until you have what you need.
The order below matters. Don't shortcut it.
Batch A — Orient on the business
"In one paragraph, what does this system do for whom? Who pays whom, who owes whom, what physically or financially moves through it?"
"Who are the primary actors? (customers, operators, third parties, internal teams)"
"What is the atomic unit of value the system tracks? (a row of money, a stock unit, a credit, an event)"
"Walk me through the happy-path flow from the moment value enters the system to the moment it leaves or terminates. Name the entities."
After this, your reconnaissance map should align with the human's description. If it doesn't, ask why before moving on.
Batch B — Find the invariants
For each major entity / flow they named, ask variants of:
5. "What property of <entity> would, if violated, cause a financial/data corruption / customer-visible bug that's hard to undo?"
6. "What's something the code assumes about <entity> that's not enforced in the DB?"
7. "Are there fields that should never change after creation? Are there transitions that should never happen even if a method exists that could technically do them?"
8. "When the team debates whether a change is safe, what do you find yourself re-explaining?"
9. "What was the last incident that involved this domain? What was the invariant the broken code violated?"
10. "Are there entities you'd call insert-only or immutable? How is that enforced today?"
Capture answers verbatim in your scratchpad — direct quotes often become the Why: field of a premise.
Batch C — Edge cases the system explicitly handles
"What are the exceptional flows the team has had to handle? (overpayment, returns, cancellations, race conditions between provider and us, partial failures, retries)"
"For each: what is the rule? (e.g., 'we register the payment regardless of entity state; reconciliation happens after')"
"Are there manual / admin / 'bypass' / out-of-flow operations? How are they isolated from the main flow?"
Batch D — Cross-domain assumptions
"Is there a domain that depends on another's invariant — e.g., 'cohort math assumes settlements are write-once'? Name as many as you can."
"Are there events / messages between domains that imply contracts? ('domain A publishes E; domain B assumes E fires exactly once on commit')"
Batch E — Naming and gotchas
"Are there fields or tables whose names trip up new engineers? ('I'd guess X but it's Y')."
"Are there renames in the recent history that are still tripping people up? Legacy fields that look used but aren't?"
Batch F — Sizing the deep-review skill
"If you were reviewing a PR in this codebase, which 4–6 lenses would you wear? (e.g., 'money-flow expert', 'state-machine expert', 'adjacent-code expert who finds untouched callers that break')"
"What kind of finding is the highest-value? (e.g., 'someone added a new status value but didn't update three downstream filters')"
"Are there tests / architecture rules that are already protecting some of these invariants? Point me at the gold-standard test file."
After the interview, restate your model of the system back to the human in 8–12 bullet points and ask "is this right?" Adjust before drafting docs.
3. Draft docs/CORE_TENETS.md
Write the file in one pass, then iterate with the human.
Structure
A short prologue that names the system and its purpose.
Numbered top-level sections (## 1. <Domain>, ## 2. <Domain> …). Each section corresponds to one of the major flow stages or domain clusters the human described.
Inside each section, prose paragraphs that name entities, describe the flow they participate in, and then call out:
### Key Invariant — single declarative statement that must always hold (e.g., a sum equation, a uniqueness, a status-bound monotonicity).
### Key Rule — operational rule that flows from the invariant (e.g., "we only transfer the regular amount; everything else becomes store credit").
Edge cases as sub-sections (### Overpayment, ### Discount-before-date, ### Admin correction) — each one explains what happens in the exceptional path because of the rule above.
Voice
Conceptual, not field-by-field. Field-by-field belongs in docs/schema/.
Heavy on named entities, light on code references. A reader should be able to load this file as background context and then go read code.
Concrete amounts in examples when explaining a calculation (the human has a feel for what realistic numbers look like — ask).
Don't include implementation classes/files in normal prose; in edge-case sections where pointing to the exact class is high signal (the one place the logic lives), use backticks and a short reference. Do this sparingly.
How to draft
Sketch the section titles based on the human's flow walk-through. Run them by the human before writing prose. Use AskUserQuestion with options when there's a sensible split (e.g., "Should Payouts be its own section or part of Transfers?").
Write section by section. After each section, paste it for the human, ask "what's wrong with this?". They will catch errors that aren't in the code.
After all sections exist, ask the human: "Read it once top-to-bottom. What's missing? What would surprise a smart engineer who read this and then opened the code?"
Quality bar
A CORE_TENETS section is good if:
A senior engineer who never saw the code can read it and predict the names of the entities and the rough shape of the tables.
Every invariant is testable in principle — the file can later be paired with tests that would break if the invariant did.
Edge cases are examples of the rule, not exceptions to it. ("Overpayment is just the rule that we always register money, applied to the dual-instrument case.")
4. Draft docs/schema/(skip entirely if §1.4 determined the repo does not own DB code)
Gate: only proceed with this section if §1.4 confirmed the repo owns migrations / schema source / ORM entity definitions. If not, jump straight to §5.
4.1 docs/schema/index.md
Conventions: PK strategy, naming (snake_case vs camelCase, table prefixes), money column type, enum representation, audit conventions, soft-delete (or not), ID type uniformity.
Common gotchas table: | Wrong guess | Correct column | Why | — populate from interview batch E + reconnaissance renames.
Table-to-domain mapping — list every domain and which tables belong to it. This becomes the routing index for both humans and the deep-review agent.
4.2 docs/schema/{domain}.md (one per domain)
For each table:
Entity class name, package.
Columns table: | Column | Type | Nullable | Description |. Pull types from the migration files / schema source — don't invent.
For enum-typed columns, list the values explicitly (**Status enum:** X, Y, Z).
Indexes, named constraints, partial unique indexes — list them; they encode invariants.
Relationships: incoming and outgoing FKs in one line each.
How to draft
This is a long, mechanical task. Doing it for many tables is the kind of task you can split into parallel Agent invocations: spawn one agent per domain, give it the schema source files and the conventions doc, ask for one docs/schema/{domain}.md per agent. Sanity-check the output before saving.
Each docs/schema/{domain}.md doesn't need a long prose intro — a one-paragraph overview is enough. The value is in the column tables.
If the schema is owned outside this repo (microservice owns its DB elsewhere, or it's a managed service), say so and link out.
5. Draft docs/{domain}/premises.md
This is the highest-leverage file type and the most labor-intensive. Do it after CORE_TENETS and schema, so you have the vocabulary settled.
Per-premise format
markdown
## <Premise title — short, declarative, present tense>
<One paragraph: what is true and must remain true. Be specific
about which entity, which field, which method, which condition.>
**Why:** <The reason — what business/technical concern motivates this.
Often a past incident or a downstream system that relies on it.>
**Breaks:** <What goes wrong if violated — specific downstream
systems / specific reports / specific calculations.>
**Tests:** <Test class or method that protects this premise.
If you can't name one yet, write `none yet` and treat it as a debt.>
**Depends on:** <Cross-references to premises in other domains, by their
title, if any.>
Where to find premises (each item is a separate candidate)
Tables with no UPDATE statements anywhere in the codebase (grep proves it).
"X is never deleted" in interview notes.
Math equalities
Sum equalities in code: sum(children.amount) == parent.amount, principal + interest + fine == total, debits == credits.
Proportional distribution: where one parent value is split into N children — look for "proportion", "ratio", "split", "allocate".
Anything that's require(...) / assert ... / check(...) in a constructor or service.
Status transitions
State machines: every "X → Y transition is explicit and bounded" is a premise. Reverse transitions that exist only in a correction flow are also premises ("reverse transitions are not part of the standard state machine").
Filters that depend on status: findByStatusIn(...), where status != ..., .filter { it.status in ...}. The set of statuses being filtered IS the premise.
Idempotency and dedup
Idempotency keys, unique constraints on (entity_id, kind, timestamp), "if exists return" patterns. Each is a premise that downstream consumers may not call twice.
Eventing contracts
"Every X site MUST publish event Y." Especially when the event drives a fan-out outbox.
"Event Y fires once on AFTER_COMMIT, never inside the transaction."
"Consumer Z must be idempotent because retry → at-least-once."
Cross-entity invariants the DB doesn't enforce
The interview will surface these ("store custom attribute must reference an attribute declared by its franchisor — the DB doesn't enforce it").
Search for service-layer validation patterns — when a service does a findById + check before insert, the check is a premise.
Monetary atomicity
"Amount X always equals … in cents." "Amount Y is the bank amount; amount Z is the effective amount and they differ only when discount is honored."
Insert-only history
Audit tables (Envers / equivalents). Anything time-travel-like. Anything that says "history is never rewritten."
Time and timezone
"All timestamps are UTC at rest." "Date X is wall-clock in São Paulo for business reasons."
"Test suite runs in UTC."
Concurrency
Pessimistic locking calls (SELECT … FOR UPDATE / @Lock(PESSIMISTIC_WRITE)) protect an invariant — the invariant is the premise.
Optimistic locking (@Version) on an entity says "concurrent writers must lose; the surviving write wins" — sometimes a premise.
How to draft, mechanically
For each major domain, spawn an Agent (or open a deep work session) that:
Has the affected source files in context.
Has the interview notes for that domain.
Produces a first list of premise candidates (one bullet each, no full bodies yet) — easily 20–40 per domain on a complex system.
Run the candidate list past the human. They will:
Confirm or kill each one.
Add 3–10 they can think of that no agent would have spotted.
Refine the Why for the load-bearing ones with the story behind them.
Promote confirmed candidates to full premise entries with the format above.
For each premise, search for an existing test that would break if the premise were violated:
If found, name it in **Tests:**.
If not, write none yet and add a follow-up task. Premises with none yet are debt — list them at the end of the bootstrap.
Link related premises with [[premise-title-slug]] or by full title. Cross-domain dependencies use **Depends on:** {domain} — "Premise title".
Sizing
A premises file with fewer than ~5 entries is suspect — push harder, you probably missed invariants.
A premises file approaching ~30 entries is a signal that the domain is too broad. Ask the human if it splits cleanly.
6. Draft per-domain knowledge docs
Not every domain needs one. Create docs/{domain}/<topic>.md when:
There's a non-trivial calculation with rounding or order-of-operations subtleties → write an "examples.md" with worked examples (concrete amounts in / amounts out).
There's an integration with a quirky external API whose docs are bad → write the integration's idiosyncrasies down ("provider X expects field Y in centavos but the API docs say reais").
There's a multi-step lifecycle that's already well-covered in CORE_TENETS but worth re-stating with code references for someone deep in implementation.
Skip them on V1 if the human has limited time. They're additive.
7. Build .claude/skills/deep-review/SKILL.md
The deep-review skill is a meta-prompt that spawns parallel domain agents. You adapt the agent personas to this codebase's domain.
Phase structure (the skill must implement all five phases)
code
Phase 0: Input resolution.
Parse arguments. Determine review target:
- no arg → review current branch vs origin/main, including uncommitted
- URL with /pull/ → PR mode (extract number)
- numeric or #N → PR mode
- 7–40 hex chars → commit mode
- anything else → branch mode
Also detect a "cheaper"/"eco" flag to swap deep-thinking agents to a
smaller model. Then check out the target code (gh pr checkout / git
checkout) and capture the diff with `gh pr diff` or
`git diff origin/main...HEAD` / `git diff <SHA>~1 <SHA>` depending on
mode. Abort if the checkout fails — never let agents read the wrong
branch.
Phase 1: Context gathering.
Read CORE_TENETS.md, the schema doc for each affected domain
(if the schema layer exists), each affected domain's premises.md,
and CLAUDE.md. Identify the affected-domain list from the diff.
Pass the full diff + all of this to every agent.
Phase 2: Parallel review agents.
Spawn N agents (typically 4–6) in parallel. Each agent gets a
persona, embedded tenets, and a checklist (see "How to tailor the
agents" below).
Phase 3: Consolidation.
Dedupe findings. For every Blocker / High, re-read the actual file
to confirm the code matches what the agent described — agents
hallucinate, and a single false-positive Blocker erodes trust faster
than five misses. Never dismiss a finding because the local file
"looks different" — that means you may be on the wrong branch; recheck
Phase 0 first. Classify each surviving finding as Blocker / High /
Medium / Low.
Phase 4: Output.
Present the consolidated review. Then ask the human (via
AskUserQuestion) what to do: post to GitHub (PR mode only),
copy to clipboard (pbcopy / xclip), save to a file, or nothing.
How to tailor the agents
From interview batch F, you have the 4–6 lenses the human wants. For each, write an agent prompt section with three parts:
Persona — "You are the engineer who owns X. You know every path that does Y."
Embedded tenets — quote the relevant CORE_TENETS section verbatim inside the agent prompt, then list the testable consequences ("Therefore, verify that …"). The agent must not need to re-derive the tenet.
Checklist — explicit, numbered steps. Two checklists generalize across every codebase and you should include them in every deep-review skill regardless of domain:
Adjacent-code checklist. This is the highest-value lens and catches bugs that diff-only reviews always miss.
Step 1: Extract semantic changes from the diff: new enum values, changed method signatures, new status values or transitions, changed filter/query conditions, new entity fields, changed business logic.
Step 2: For each semantic change, run an exhaustive grep across the repo for callers, references, and pattern-matched uses of the changed element. Also always grep for the most central financial/business primitives of the system (e.g., the settlement-creation site, the proportion calculator) — these are the "always check these" anchors.
Step 3: Open every grep hit and verify the method still handles the new behavior. If not → finding (file, line, scenario, suggested fix).
Step 4: Inverse check — does the new code handle all existing scenarios it didn't before? (e.g., a new filter that doesn't cover all status values).
State-machine / lifecycle checklist. Pick the most critical lifecycle in the system and walk it stage by stage. For each stage: which methods are called, what the entity states are at that point, which filters/guards depend on those states, and whether any of them fail with the new changes. Always include an execution-order check — bugs where step N's filter runs before step M's transition, returning empty when state has already moved, are some of the most dangerous and hardest to spot.
The remaining 2–4 agents are domain-specific. Examples of strong personas:
A "money flow" / "value propagation" agent that traces a new entity through the full downstream cascade and quantifies financial impact at each stage.
A "core pipeline" agent that owns the most heavily-used producer/consumer path and checks every place that produces an event of type X handles the new shape.
A "test coverage & premises" agent that maps each premise in the affected premises.md files to a test and flags premises with Tests: none yet or unstated premises the diff implicitly relies on.
Model routing
Keep an optional "economy mode" that swaps deep-thought agents from Opus to Sonnet. This is helpful for routine PRs.
Consolidation
The consolidation phase MUST verify each Blocker against the actual file — agents hallucinate, and a single false-positive Blocker in a code review erodes trust faster than five misses.
Test the skill before declaring done
Run /deep-review on a recently merged PR you know well. Compare findings to what you'd produce by hand.
Run it on a deliberately buggy branch (introduce a status filter that misses a new enum value) — does the adjacent-code agent catch it? If not, adjust the checklist.
8. Wire CLAUDE.md
Update (or create) the top-level CLAUDE.md to reference the new structure. Sections to include:
Code Conventions — short. Things genuinely enforced (line length, naming, DI style, structured error responses).
Documentation — point at docs/index.md and explain the splits: CORE_TENETS vs premises vs domain knowledge (and schema, if it exists).
Premises — embed a short explanation of what premises files are (what they're for, the Why/Breaks/Tests/Depends-on format, when to update them, the workflow expectation for AI sessions: read the file before implementing, propose new premises before writing tests, fill in **Tests:** after writing tests). The §5 spec above is the canonical content — paraphrase it into CLAUDE.md.
Required Skills / Rules — list .claude/skills/* and .claude/rules/* you've created with one-line "when to load" descriptions.
End the bootstrap session by re-reading CLAUDE.md and confirming every link resolves to a file that exists.
9. Acceptance criteria — what "done" looks like for V1
Before declaring the bootstrap complete, verify:
docs/CORE_TENETS.md exists. Every section has a ### Key Invariant or ### Key Rule. The human has read it top-to-bottom and signed off.
docs/index.md exists and links resolve.
(Only if §1.4 said the schema layer applies)docs/schema/index.md has the conventions, the "common gotchas" table (≥3 rows on any non-toy codebase), and the table-to-domain mapping.
(Only if applicable)docs/schema/{domain}.md exists for every domain in the mapping. Each table has columns, types, enum values, named constraints, and FK relationships.
docs/{domain}/premises.md exists for every domain that has any. Each premise has Why/Breaks/Tests/Depends-on. Premises with Tests: none yet are listed at the end of the session as follow-up debt.
.claude/skills/deep-review/SKILL.md exists. The agent personas match the human's "4–6 lenses" answer. The adjacent-code agent and the lifecycle agent are present. A test run on a known PR produces sensible findings.
CLAUDE.md references everything and has no dead links.
You ran /deep-review against a recently merged PR and the findings are non-trivial and accurate. If they aren't, iterate on the skill before declaring done — the skill is the whole point of the docs.
10. Operating notes for the agent running this
The human is the oracle. When you have a choice between guessing and asking, ask. Token cost is irrelevant compared to writing a wrong premise that propagates as gospel.
Iterate in small batches. Draft one section → show the human → adjust → next section. Do not produce 800 lines of premises and ask for sign-off in one shot — the human will skim and miss errors.
Save aggressively, commit nothing. Write files into the repo so the human can read them in their editor, but don't git commit unless explicitly asked.
Use parallel agents for parallel work. Schema docs for 12 tables, premise-candidate generation for 6 domains — these parallelize cleanly. Spawn Agents and consolidate.
Don't fabricate tests. When filling in a premise's **Tests:** field, only name a test you've verified exists (grep for the class name, read the test). If none exists, write none yet — that's honest and actionable.
Distinguish 'the system today' from 'the system aspirationally'. Some premises the human wants to be true but aren't enforced yet. Mark these explicitly (**Status:** aspirational — not yet enforced; see [issue/TODO]).
Maintain a follow-up list. At session end, hand the human:
Premises with Tests: none yet.
Aspirational premises that need enforcement.
(If schema applies) Domains whose schema you didn't reach.
Knowledge docs (docs/{domain}/<topic>.md) that the human said would be useful but you skipped on V1.
End by running /deep-review against a real PR. This is the integration test for the whole bootstrap. If it doesn't produce findings a human reviewer would respect, the docs aren't done yet.
11. Reference shapes (self-contained — no external repo needed)
The shape and voice you should produce, captured inline so you don't need access to any reference repo.
docs/CORE_TENETS.md — shape
~150–300 lines on a non-trivial system.
A short prologue: what this system does, who it serves, what it MUST preserve.
Numbered top-level sections (## 1. <Domain Cluster>, ## 2. <Domain Cluster> …), typically 5–8 sections matching the major flow stages.
Each section is prose first — names the entities, describes the flow they participate in, what's exchanged, what triggers what.
Inside each section, distinct sub-headings:
### Key Invariant — a single declarative statement that must always hold (a sum equation, a uniqueness, a monotonicity, an exclusion).
### Key Rule — operational consequence of the invariant ("we always X; if Y happens, route to Z").
### <Edge case name> — overpayment, refund, cancellation, race, retry. Each one is an example of the rule applied to an exceptional path, not an exception to it.
Heavy on named entities (each named in bold the first time). Light on code references — point at the canonical class only when it's the single place the logic lives.
When showing a calculation, include a concrete worked example with realistic numbers.
docs/index.md — shape
~30–60 lines. Pure routing, no content of its own.
Tables that list (domain) → (file) → (one-line description).
One section for CORE_TENETS, one for schema (when it exists), one for domain knowledge, one for conventions.
docs/schema/index.md — shape (only if applicable)
Conventions block: PK strategy, naming (snake_case vs camelCase), money column type, enum representation, audit conventions, soft-delete approach, ID type uniformity.
A Common Gotchas table: | Wrong guess | Correct column | Why | — 3–10 rows on any non-toy codebase.
A table-to-domain mapping: one row per domain listing every table that belongs to it. This is the routing index for SQL writers and for the deep-review agent.
docs/schema/{domain}.md — shape (only if applicable)
One-paragraph overview of the domain.
Per table: entity class name + package, then a | Column | Type | Nullable | Description | table. Pull types from migrations / schema source — never invent.
For enum-typed columns: list values explicitly (**Status enum:** A, B, C).
List named constraints, indexes, partial unique indexes — they encode invariants.
One-line relationships block: incoming and outgoing FKs.
docs/{domain}/premises.md — shape (the highest-leverage file)
10–30 premises per non-trivial domain. Fewer than ~5 means you missed invariants; near ~30 means the domain probably splits.
Each premise as an ## H2 section using exactly this format:
markdown
## <Short, declarative, present-tense title>
<One paragraph: what is true and must remain true. Be specific
about which entity, which field, which method, which condition.>
**Why:** <The reason — what concern motivates this. Often a past
incident or a downstream system that silently relies on this.>
**Breaks:** <What goes wrong if violated — specific downstream
systems, reports, calculations, or user-facing flows.>
**Tests:** <Test class or method that protects this premise. If you
can't name one yet, write `none yet` and treat it as debt.>
**Depends on:** <Cross-references to premises in other domains (by
title), if any. — if none.>
The Why is where the value compounds. Make it concrete: "the audit-join table assumes settlements are write-once; rewriting them would silently corrupt the audit trail and break the X reconciliation report" beats "we don't update this entity."
A premise with Tests: none yet is incomplete. New premises introduced by current work require tests before merge; retroactively-documented premises can start with none yet and become follow-up debt.
.claude/skills/deep-review/SKILL.md — shape
Frontmatter with name: deep-review and a one-line description:.
Phase 1 context gathering (CORE_TENETS + affected schema + affected premises + CLAUDE.md, passed to every agent).
Phase 2 spawns 4–6 parallel agents. Each agent prompt has: persona, embedded tenets (quoted from CORE_TENETS), a numbered checklist. Always include the adjacent-code agent and the state-machine/lifecycle agent (see §7 above).
Phase 3 consolidation with file re-verification for every Blocker/High.
Phase 4 output handling: present, then ask the human what to do with the review (post to GitHub, copy to clipboard, save to file, nothing).
An optional "economy mode" that swaps non-critical agents to a cheaper model.
When you find yourself unsure about voice or depth at any point during the bootstrap, ask the human to read 30 lines you've just written and tell you whether the tone matches what they want — they're the calibration source, not any external reference.
Assistant
I'll bootstrap an AI-docs + /deep-review stack for MonoDreams. Since I'm in plan mode, I'll do reconnaissance first, ask a few scoping questions, then write the plan to the plan file.
Let me start by exploring the codebase in parallel to build a mental map. Three focused Explore agents covering different aspects.
Assistant
Reconnaissance done. MonoDreams is a 2D ECS game engine — clearly no database, so the schema layer (§4) is skipped. I've mapped 12 domains, ~35 premise candidates, and the deep-review skill personas this codebase needs.
A few scoping questions before I finalize the plan.
Assistant
Scope locked. Writing the plan to the plan file now.
Assistant
Plan written. Calling ExitPlanMode to request approval.
Assistant
Plan approved. Loading task tooling, then I'll start Phase 1 — Batch A of the interview.
Assistant
Starting Phase 1 — Batch A (orient on the engine). Four open-ended questions; answer in whatever shape is natural (bullets, paragraphs, one-liners).
Batch A — orient on the engine
What is the gameplay-development experience MonoDreams is trying to deliver? What kind of games is it aimed at (2D platformers, top-down, puzzle, anything that fits the ECS shape)? Is there a "north star" game or genre that drives prioritization?
Who are the intended users? Solo devs / small teams / yourself only / hobby vs. shipping commercial. Is this primarily a personal engine you happen to publish to NuGet, or do you imagine other devs adopting it?
What is the atomic unit of composition — the component? the entity? the system? Phrased differently: when someone wants to add a feature, which thing do they most often reach for first? (E.g., "a new component" vs "a new system" vs "extend an existing component".)
Walk me through the happy-path of using MonoDreams to add a feature — pick something concrete like "I want a new enemy that throws projectiles" or "I want a player that double-jumps". What does the developer touch, in what order? Where do they put the new code (Examples? a downstream game project?)? What do they learn / configure to make it appear in a level?
Take your time — the answers shape every doc that comes after.
User
11. Reference shapes (self-contained — no external repo needed)
The shape and voice you should produce, captured inline so you don't need access to any reference repo.
docs/CORE_TENETS.md — shape
~150–300 lines on a non-trivial system.
A short prologue: what this system does, who it serves, what it MUST preserve.
Numbered top-level sections (## 1. <Domain Cluster>, ## 2. <Domain Cluster> …), typically 5–8 sections matching the major flow stages.
Each section is prose first — names the entities, describes the flow they participate in, what's exchanged, what triggers what.
Inside each section, distinct sub-headings:
### Key Invariant — a single declarative statement that must always hold (a sum equation, a uniqueness, a monotonicity, an exclusion).
### Key Rule — operational consequence of the invariant ("we always X; if Y happens, route to Z").
### <Edge case name> — overpayment, refund, cancellation, race, retry. Each one is an example of the rule applied to an exceptional path, not an exception to it.
Heavy on named entities (each named in bold the first time). Light on code references — point at the canonical class only when it's the single place the logic lives.
When showing a calculation, include a concrete worked example with realistic numbers.
docs/index.md — shape
~30–60 lines. Pure routing, no content of its own.
Tables that list (domain) → (file) → (one-line description).
One section for CORE_TENETS, one for schema (when it exists), one for domain knowledge, one for conventions.
docs/schema/index.md — shape (only if applicable)
Conventions block: PK strategy, naming (snake_case vs camelCase), money column type, enum representation, audit conventions, soft-delete approach, ID type uniformity.
A Common Gotchas table: | Wrong guess | Correct column | Why | — 3–10 rows on any non-toy codebase.
A table-to-domain mapping: one row per domain listing every table that belongs to it. This is the routing index for SQL writers and for the deep-review agent.
docs/schema/{domain}.md — shape (only if applicable)
One-paragraph overview of the domain.
Per table: entity class name + package, then a table. Pull types from migrations / schema source — never invent.
User
10. Operating notes for the agent running this
The human is the oracle. When you have a choice between guessing and asking, ask. Token cost is irrelevant compared to writing a wrong premise that propagates as gospel.
Iterate in small batches. Draft one section → show the human → adjust → next section. Do not produce 800 lines of premises and ask for sign-off in one shot — the human will skim and miss errors.
Save aggressively, commit nothing. Write files into the repo so the human can read them in their editor, but don't git commit unless explicitly asked.
Use parallel agents for parallel work. Schema docs for 12 tables, premise-candidate generation for 6 domains — these parallelize cleanly. Spawn Agents and consolidate.
Don't fabricate tests. When filling in a premise's **Tests:** field, only name a test you've verified exists (grep for the class name, read the test). If none exists, write none yet — that's honest and actionable.
Distinguish 'the system today' from 'the system aspirationally'. Some premises the human wants to be true but aren't enforced yet. Mark these explicitly (**Status:** aspirational — not yet enforced; see [issue/TODO]).
Maintain a follow-up list. At session end, hand the human:
Premises with Tests: none yet.
Aspirational premises that need enforcement.
(If schema applies) Domains whose schema you didn't reach.
Knowledge docs (docs/{domain}/<topic>.md) that the human said would be useful but you skipped on V1.
End by running /deep-review against a real PR. This is the integration test for the whole bootstrap. If it doesn't produce findings a human reviewer would respect, the docs aren't done yet.
User
9. Acceptance criteria — what "done" looks like for V1
Before declaring the bootstrap complete, verify:
docs/CORE_TENETS.md exists. Every section has a ### Key Invariant or ### Key Rule. The human has read it top-to-bottom and signed off.
docs/index.md exists and links resolve.
(Only if §1.4 said the schema layer applies)docs/schema/index.md has the conventions, the "common gotchas" table (≥3 rows on any non-toy codebase), and the table-to-domain mapping.
(Only if applicable)docs/schema/{domain}.md exists for every domain in the mapping. Each table has columns, types, enum values, named constraints, and FK relationships.
docs/{domain}/premises.md exists for every domain that has any. Each premise has Why/Breaks/Tests/Depends-on. Premises with Tests: none yet are listed at the end of the session as follow-up debt.
.claude/skills/deep-review/SKILL.md exists. The agent personas match the human's "4–6 lenses" answer. The adjacent-code agent and the lifecycle agent are present. A test run on a known PR produces sensible findings.
CLAUDE.md references everything and has no dead links.
You ran /deep-review against a recently merged PR and the findings are non-trivial and accurate. If they aren't, iterate on the skill before declaring done — the skill is the whole point of the docs.
User
8. Wire CLAUDE.md
Update (or create) the top-level CLAUDE.md to reference the new structure. Sections to include:
Code Conventions — short. Things genuinely enforced (line length, naming, DI style, structured error responses).
Documentation — point at docs/index.md and explain the splits: CORE_TENETS vs premises vs domain knowledge (and schema, if it exists).
Premises — embed a short explanation of what premises files are (what they're for, the Why/Breaks/Tests/Depends-on format, when to update them, the workflow expectation for AI sessions: read the file before implementing, propose new premises before writing tests, fill in **Tests:** after writing tests). The §5 spec above is the canonical content — paraphrase it into CLAUDE.md.
Required Skills / Rules — list .claude/skills/* and .claude/rules/* you've created with one-line "when to load" descriptions.
End the bootstrap session by re-reading CLAUDE.md and confirming every link resolves to a file that exists.
User
7. Build .claude/skills/deep-review/SKILL.md
The deep-review skill is a meta-prompt that spawns parallel domain agents. You adapt the agent personas to this codebase's domain.
Phase structure (the skill must implement all five phases)
code
Phase 0: Input resolution.
Parse arguments. Determine review target:
- no arg → review current branch vs origin/main, including uncommitted
- URL with /pull/ → PR mode (extract number)
- numeric or #N → PR mode
- 7–40 hex chars → commit mode
- anything else → branch mode
Also detect a "cheaper"/"eco" flag to swap deep-thinking agents to a
smaller model. Then check out the target code (gh pr checkout / git
checkout) and capture the diff with `gh pr diff` or
`git diff origin/main...HEAD` / `git diff <SHA>~1 <SHA>` depending on
mode. Abort if the checkout fails — never let agents read the wrong
branch.
Phase 1: Context gathering.
Read CORE_TENETS.md, the schema doc for each affected domain
(if the schema layer exists), each affected domain's premises.md,
and CLAUDE.md. Identify the affected-domain list from the diff.
Pass the full diff + all of this to every agent.
Phase 2: Parallel review agents.
Spawn N agents (typically 4–6) in parallel. Each agent gets a
persona, embedded tenets, and a checklist (see "How to tailor the
agents" below).
Phase 3: Consolidation.
Dedupe findings. For every Blocker / High, re-read the actual file
to confirm the code matches what the agent described — agents
hallucinate, and a single false-positive Blocker erodes trust faster
than five misses. Never dismiss a finding because the local file
"looks different" — that means you may be on the wrong branch; recheck
Phase 0 first. Classify each surviving finding as Blocker / High /
Medium / Low.
Phase 4: Output.
Present the consolidated review. Then ask the human (via
AskUserQuestion) what to do: post to GitHub (PR mode only),
copy to clipboard (pbcopy / xclip), save to a file, or nothing.
User
6. Draft per-domain knowledge docs
Not every domain needs one. Create docs/{domain}/<topic>.md when:
There's a non-trivial calculation with rounding or order-of-operations subtleties → write an "examples.md" with worked examples (concrete amounts in / amounts out).
There's an integration with a quirky external API whose docs are bad → write the integration's idiosyncrasies down ("provider X expects field Y in centavos but the API docs say reais").
There's a multi-step lifecycle that's already well-covered in CORE_TENETS but worth re-stating with code references for someone deep in implementation.
Skip them on V1 if the human has limited time. They're additive.
User
5. Draft docs/{domain}/premises.md
This is the highest-leverage file type and the most labor-intensive. Do it after CORE_TENETS and schema, so you have the vocabulary settled.
Per-premise format
markdown
## <Premise title — short, declarative, present tense>
<One paragraph: what is true and must remain true. Be specific
about which entity, which field, which method, which condition.>
**Why:** <The reason — what business/technical concern motivates this.
Often a past incident or a downstream system that relies on it.>
**Breaks:** <What goes wrong if violated — specific downstream
systems / specific reports / specific calculations.>
**Tests:** <Test class or method that protects this premise.
If you can't name one yet, write `none yet` and treat it as a debt.>
**Depends on:** <Cross-references to premises in other domains, by their
title, if any.>
Where to find premises (each item is a separate candidate)
Tables with no UPDATE statements anywhere in the codebase (grep proves it).
"X is never deleted" in interview notes.
Math equalities
Sum equalities in code: sum(children.amount) == parent.amount, principal + interest + fine == total, debits == credits.
Proportional distribution: where one parent value is split into N children — look for "proportion", "ratio", "split", "allocate".
Anything that's require(...) / assert ... / check(...) in a constructor or service.
Status transitions
State machines: every "X → Y transition is explicit and bounded" is a premise. Reverse transitions that exist only in a correction flow are also premises ("reverse transitions are not part of the standard state machine").
User
4. Draft docs/schema/(skip entirely if §1.4 determined the repo does not own DB code)
Gate: only proceed with this section if §1.4 confirmed the repo owns migrations / schema source / ORM entity definitions. If not, jump straight to §5.
4.1 docs/schema/index.md
Conventions: PK strategy, naming (snake_case vs camelCase, table prefixes), money column type, enum representation, audit conventions, soft-delete (or not), ID type uniformity.
Common gotchas table: | Wrong guess | Correct column | Why | — populate from interview batch E + reconnaissance renames.
Table-to-domain mapping — list every domain and which tables belong to it. This becomes the routing index for both humans and the deep-review agent.
4.2 docs/schema/{domain}.md (one per domain)
For each table:
Entity class name, package.
Columns table: | Column | Type | Nullable | Description |. Pull types from the migration files / schema source — don't invent.
For enum-typed columns, list the values explicitly (**Status enum:** X, Y, Z).
Indexes, named constraints, partial unique indexes — list them; they encode invariants.
Relationships: incoming and outgoing FKs in one line each.
How to draft
This is a long, mechanical task. Doing it for many tables is the kind of task you can split into parallel Agent invocations: spawn one agent per domain, give it the schema source files and the conventions doc, ask for one docs/schema/{domain}.md per agent. Sanity-check the output before saving.
Each docs/schema/{domain}.md doesn't need a long prose intro — a one-paragraph overview is enough. The value is in the column tables.
If the schema is owned outside this repo (microservice owns its DB elsewhere, or it's a managed service), say so and link out.
User
3. Draft docs/CORE_TENETS.md
Write the file in one pass, then iterate with the human.
Structure
A short prologue that names the system and its purpose.
Numbered top-level sections (## 1. <Domain>, ## 2. <Domain> …). Each section corresponds to one of the major flow stages or domain clusters the human described.
Inside each section, prose paragraphs that name entities, describe the flow they participate in, and then call out:
### Key Invariant — single declarative statement that must always hold (e.g., a sum equation, a uniqueness, a status-bound monotonicity).
### Key Rule — operational rule that flows from the invariant (e.g., "we only transfer the regular amount; everything else becomes store credit").
Edge cases as sub-sections (### Overpayment, ### Discount-before-date, ### Admin correction) — each one explains what happens in the exceptional path because of the rule above.
Voice
Conceptual, not field-by-field. Field-by-field belongs in docs/schema/.
Heavy on named entities, light on code references. A reader should be able to load this file as background context and then go read code.
Concrete amounts in examples when explaining a calculation (the human has a feel for what realistic numbers look like — ask).
Don't include implementation classes/files in normal prose; in edge-case sections where pointing to the exact class is high signal (the one place the logic lives), use backticks and a short reference. Do this sparingly.
How to draft
Sketch the section titles based on the human's flow walk-through. Run them by the human before writing prose. Use AskUserQuestion with options when there's a sensible split (e.g., "Should Payouts be its own section or part of Transfers?").
Write section by section. After each section, paste it for the human, ask "what's wrong with this?". They will catch errors that aren't in the code.
After all sections exist, ask the human: "Read it once top-to-bottom. What's missing? What would surprise a smart engineer who read this and then opened the code?"
Quality bar
A CORE_TENETS section is good if:
A senior engineer who never saw the code can read it and predict the names of the entities and the rough shape of the tables.
Every invariant is testable in principle — the file can later be paired with tests that would break if the invariant did.
Edge cases are examples of the rule, not exceptions to it. ("Overpayment is just the rule that we always register money, applied to the dual-instrument case.")
User
2. Interview the human
The human is your single best source for why. Code tells you what; the human tells you why this invariant exists, what broke last quarter, what's load-bearing for the business, what's an accident of history.
Use the AskUserQuestion tool for closed-ended choices, but for open-ended questions write them as plain prose and wait for the answer. Ask in small batches (3–6 questions at a time) so the human can answer without getting overwhelmed. Iterate until you have what you need.
The order below matters. Don't shortcut it.
Batch A — Orient on the business
"In one paragraph, what does this system do for whom? Who pays whom, who owes whom, what physically or financially moves through it?"
"Who are the primary actors? (customers, operators, third parties, internal teams)"
"What is the atomic unit of value the system tracks? (a row of money, a stock unit, a credit, an event)"
"Walk me through the happy-path flow from the moment value enters the system to the moment it leaves or terminates. Name the entities."
After this, your reconnaissance map should align with the human's description. If it doesn't, ask why before moving on.
Batch B — Find the invariants
For each major entity / flow they named, ask variants of:
5. "What property of <entity> would, if violated, cause a financial/data corruption / customer-visible bug that's hard to undo?"
6. "What's something the code assumes about <entity> that's not enforced in the DB?"
7. "Are there fields that should never change after creation? Are there transitions that should never happen even if a method exists that could technically do them?"
8. "When the team debates whether a change is safe, what do you find yourself re-explaining?"
9. "What was the last incident that involved this domain? What was the invariant the broken code violated?"
10. "Are there entities you'd call insert-only or immutable? How is that enforced today?"
Capture answers verbatim in your scratchpad — direct quotes often become the Why: field of a premise.
Batch C — Edge cases the system explicitly handles
"What are the exceptional flows the team has had to handle? (overpayment, returns, cancellations, race conditions between provider and us, partial failures, retries)"
"For each: what is the rule? (e.g., 'we register the payment regardless of entity state; reconciliation happens after')"
"Are there manual / admin / 'bypass' / out-of-flow operations? How are they isolated from the main flow?"
User
1. Reconnaissance — read before you ask
Do NOT start interviewing the human until you have a working mental map. Run these in parallel where possible.
1.1 Repo shape
git ls-files | head -200 and git ls-files | wc -l — orient yourself on size and layout.
For each entity, capture: package/folder, immutability hints (updatable = false, @Immutable, readonly, frozen=True), primary key strategy, status enum values, soft-delete columns vs status-based cancellation, audit-table conventions.
Look for state machines or status transition guards: methods named canTransitionTo, validateTransition, transitionTo, decorators, enums with explicit allowed-next sets. These are premise goldmines.
1.3 Money / unit-of-value / atomicity
For any system that moves money, accounts, points, or scarce resources, find the atomic unit. Specifically look for:
Money column types (BIGINT cents vs DECIMAL vs numeric(18,2)) — fix the convention.
Ledger-style tables (entries that are append-only, with debit/credit semantics).
"Settlement" / "transaction" / "event" / "movement" tables — anything that registers an externally caused change.
The artifacts below answer different questions for different readers. Don't merge them.
File
Reader
Question it answers
docs/CORE_TENETS.md
Senior engineer new to the domain
"What business rules cannot be broken?" Conceptual entities, end-to-end flow, named invariants, edge-cases the system explicitly handles.
docs/index.md
Any reader
"Where do I find what I need?" Pure routing. No content.
docs/schema/index.md(only if repo owns DB code — see §1.4)
Anyone writing SQL
"Which table belongs to which domain, and what's the naming convention?" Plus a "common wrong guesses" table.
docs/schema/{domain}.md(only if repo owns DB code)
Anyone writing SQL against that domain
"What are the exact column names, types, enums, indexes, FKs in this domain?"
docs/{domain}/premises.md
Anyone modifying code in this domain
"What technical invariants does this domain assume? What breaks if I violate them? Which test protects each premise?"
docs/{domain}/<topic>.md
Engineers touching a specific subsystem
"How does this calculation/integration actually work, with examples?"
.claude/skills/deep-review/SKILL.md
The /deep-review agent
"How do I review changes through the lens of this codebase's domain?"
Two key distinctions to keep clean:
Business rules (CORE_TENETS) vs. technical premises ({domain}/premises.md). Business rules are facts about the world the product models ("we only transfer the regular amount; overpayment becomes store credit"). Premises are facts about the implementation that downstream code silently depends on ("entity X is never updated after creation; the audit join table requires this"). The same idea may appear in both, framed differently — that's fine.
Schema docs (docs/schema/) vs. domain knowledge (docs/{domain}/). Schema is pure table reference and only exists when the repo owns database code. Domain knowledge is calculation/integration/lifecycle prose and exists regardless.
Conditional layer — the schema docs. If this repo does own a database schema (e.g., it's a pure-logic library, a CLI, a UI-only frontend, a thin client wrapping someone else's API, an SDK), skip the schema layer entirely. Section 4 below has an explicit gate. The CORE_TENETS / premises / deep-review skill still apply.
User
The experience aimed is for full control via code, unlike Unity and Unreal where your code has to conform to the engine and can only be placed in restrict specific places, Monodreams aims to be the same as Spring is for web developers, you're in control but we've got you covered with most of what's common need for most games, the price is that the developer is expected to embrace ECS architecture. Today, devs wanting control only have bare MonoGame and have to do the heavy lifting themselves or use Nez or others that are more loose and don't deliver as much. This approach favors devs who like to code and those who use AI coding agents like Claude Code. Said that, since the base is MonoGame, the focus is 2D games, but I don't discard the possibility of enhancing the 3D rendering pipeline outside of MonoGame and in the future serving 3D gamedevs as well.
Solo devs for sure and small teams as well. Monodreams should empower indie devs and small studios to push way above their size. The plan currently is to grow a userbase around this opensource engine and maybe, just maybe, create an AI-powered IDE around this to also have a commercial offering in the future (but we shouldn't talk about this in this repo and stage of the project, just caring for the repo to be friendly for AI coding agents too).
I think primarily a System, but often a pair System + Component. Components hold data, so you only need them if there is need for new data, System operates behaviors on top of that data, so there'll probably be more systems than components. (entities are just IDs that groups components).
If a dev wants the player to double jump, first they have to know which systems and components are already in place, lets suppose there is already a system to control gravity and components to identify which entities are subject to gravity, then there shall be a component to identify the player, a system to map input to game commands, and a system to control the jump velocity, the airborne state may or may not be already tracked, the dev will have to keep track of this in a component and then modify the jump system to account for the conditions to allow a double jump, like being airborne and maybe having the ability unlocked in the game. Then you just have to be sure the right components are created for the player and the systems are added to the update loop and in the right order.
Assistant
Got it. Three things stand out from your answers I want to capture before continuing:
"Spring for game devs" is the meta-tenet — framework, not library; full code control via embracing ECS.
AI coding agents are a first-class user. That changes the docs voice: optimize for an agent loading the file as context, not just a human skim.
Discovery-before-creation is the developer workflow — "first know what's already in place" then decide whether you need a new component, a new system, or to modify ordering. This is exactly the gap CORE_TENETS / premises files close.
Batch B — invariants
What property of Transform would, if violated, cause the hardest-to-debug breakage? (E.g., creating a second spatial component, mutating Position without going through Transform, child entity reading WorldPosition before HierarchySystem ran for the frame.) Pick the one that scares you most.
Same question for DrawComponent / the rendering pipeline. What's the silent corruption mode? (A new render path that bypasses MasterRenderSystem? Setting Visible manually? Mutating LayerDepth after YSortSystem?)
Same for the collision stack (BoxCollider / ConvexCollider / ColliderTag). What's an assumption the code makes that nothing enforces?
What does the engine assume but not enforce in code? Free-form — anything that comes to mind. Examples to prime you: "EntitySpawnSystem silently drops unregistered factories", "the polygon buffer in TransformCollisionDetectionSystem assumes single-threaded execution", "Logger.Initialize must be called once before use".
What do you find yourself re-explaining — to a contributor, to Claude, to yourself a month later — when working on this engine? The thing you've typed three times.
Has there been a bug or surprise in the last few months caused by violating an invariant? Even a small one. The story behind a premise is often the most useful part of writing it down.
User
The dev will be free to create their own Transform custom component if they wish/need, what I fear most is inconsistency, the dev creates a MyTransform and start using both, Transform and MyTransform, this will lead to a complicated code, hard do debug problems, and a lot of duplication. Systems on the other hand should tend to be more agnostic, like if they were saying: if a component is in such conditions, I do this and that, no matter what. So you're isolated and, of course this can lead to bugs where the system doesn't care for another new condition and something odd happens, but this should be preventable by the AI agent or dev reviewing the pipeline of systems that operates on that component and should be relatively common to debug problems like this.
The rendering pipeline is a little bit more delicate because it's harder to debug bugs and a more hard expectation is that systems operating this pipeline will be last in the systems pipeline.
What is most non-obvious, and this is true for many systems, is that the collision stack depends heavily on Transform. This is not enforced and not immediatly clear when you're rapidly scanning the project. So if you switch to a custom Transform implementation, collisions won't be as plug'n play. But I think this is more an implementation flaw/gap than a constraint of the project. Ideally these modules should be relatively independant from each other and there should be a way to have the collision stack to play nicely with other implementations of Transform/Position.
I think we later can go in depth, module by module. We should take the chance to bundle and separate things so that its clear what's dependent on what, just like you can choose to use Spring Security but this is a separate pack that can be used when using Spring, but not necessarly, and not using it won't break Spring and other modules.
It's constant for AI agents to create custom components when in fact we should enhance or refactor a current existing component. I fear we end with a pletora of micro-components that just spams the dev with infinite non-obvious components. The problem is not exactly to go on creating components, there are cases where it's justifyable, maybe after defining clear packs/modules then we can make it easir to decide if we're going to create or edit a current module's components since they're be more contained and easier to reason about.
When I was experimenting with the CullingSystem and created the Visible component I then forgot to use it in another game screen and was puzzled why some entities weren't visible. But I don't know what would have made it faster to debug this problem.
Assistant
Three big shifts I'm now incorporating:
Transform invariant is "don't mix two" — not "only ours". Devs CAN write MyTransform; what hurts is mixing. Systems should be agnostic (operate on conditions, not on a specific type). Premise reframed.
Rendering systems run LAST — strong ordering rule. Will become a Key Invariant in the rendering section.
Aspirational vs current state — collision-depends-on-Transform, module decoupling, modular packs (Spring Security analog). These get Status: aspirational — not yet enforced so we don't pretend the code is what we wish it were.
The pet peeve gets a top-billing tenet — "Discover and extend before creating a new component." Reinforces what CLAUDE.md says but makes it the FIRST rule.
The Visible-not-set story is the perfect anchor case for why these premises files exist — written down, it's a 30-second check; not written down, you stare at an invisible entity.
Batch C — edge cases
Entity disposed mid-frame. What happens today if a system disposes entity X, and a later system in the same frame still queries / messages it? Is there a convention (dispose at end of frame? defer? best-effort?). Is this a real problem or theoretical?
Parent entity disposed while children exist. I see HierarchySystem cascade-disposes orphaned children. Is the rule "children always die with the parent"? Are there cases where you want a child to survive a parent's death?
Two colliders on one entity (or zero colliders + ColliderTag). Is the engine 1-collider-per-entity, or can an entity carry both a BoxCollider and a ConvexCollider? What's the answer if a level designer accidentally exports a mesh with two -collider children?
Layer-depth ties in Y-sort. Two entities at the same world Y — does the system have a stable tiebreaker (entity ID order, insertion order, undefined)? Have you ever had visible flicker from this?
Out-of-pipeline / debug operations. Are there things the engine does that bypass the normal frame loop — e.g., ScreenshotCaptureSystem, replay-driven input injection, the inspector overlay? Anything important to call out as "not part of the normal pipeline; doesn't follow the same ordering rules"?
Headless mode contract. In headless, what's still expected to work and what's deliberately skipped? (E.g., do prep systems run? does culling run? does the Logger still fire?) Anything subtle that's bitten you in headless replay tests?
User
I haven't stumbled on this problem yet, so I don't have an opinion.
I don't know, as of today, all children should be disposed alongside their parent, but nothing prevents that we add support for children outliving their parents if needed.
Good question, today the engine assumes one collider of the same type per entity. But this is just something that wasn't given too much thought about.
I haven't experienced flickering but this is a recent implementation. I remember implementing something to resolve ties, just isn't sure what it was.
I don't recall, but feel free to take a look into the code.
I think that headless implementation is doomed and not well thought out. The original idea was to enable AI agents to visually test the game but I don't think it's a stable and trustworthy implementation.
Assistant
Captured. Edge cases I'm noting:
Mid-frame dispose: no convention yet → not writing a premise; flag as open-question.
Child orphans: current behavior is "die with parent" → premise as current-state.
1-of-each-type-collider: implicit, not enforced; "wasn't given much thought" → premise with note.
Y-sort tiebreaker: I'll grep YSortSystem during drafting and write what the code actually does, then we can validate.
Headless mode: reframed to "experimental; tests built on it are best-effort", not load-bearing.
Batch D — cross-domain assumptions
This batch I want to flip the format — instead of asking open-ended questions that risk "I don't know", let me list the cross-domain dependencies I've already inferred from reconnaissance. Tell me which are correct, which are wrong, and which I missed. One-liner answers are fine.
A. Read-after-write across domains:
17. Rendering reads Transform.WorldPosition → assumes HierarchySystem ran this frame. ✓ / ✗ / nuance?
18. CullingSystem reads Camera.VirtualScreenBounds → assumes CameraFollowSystem already updated Camera this frame. ✓ / ✗ / nuance?
19. CursorPositionSystem reads Camera to do screen→world; assumes Camera is current. ✓ / ✗?
20. Collision detection reads Transform.Position and Transform.Delta → assumes movement systems wrote Position this frame AND TransformCommitSystem ran for the previous frame (so Delta is meaningful). ✓ / ✗ / nuance?
B. Message contracts:
21. LoadLevelRequest → LevelLoadRequestSystem writes CurrentLevelComponent. The parser systems (LDtk / Blender) listen on CurrentLevelComponentadded (not on LoadLevelRequest). Is that intentional — i.e., adding the component manually would also trigger parsing?
22. EntitySpawnRequest is dispatched by string identifier. Unregistered identifier → log warning + silent drop. Intentional design (game code lazily registers) or oversight (should throw)?
23. There's also PositionChangeMessage, SizeChangeMessage, RigidBodyTouchMessage. Are these all currently active contracts? What publishes / consumes each? Or are some leftover from older designs?
C. Cross-domain dependencies I might've missed:
24. Anything important the inferences above leave out — e.g., a system that depends on Visible other than the renderer, a system that reads collision-tag without producing it, a contract via EntityHierarchy resource that nobody would guess from class names?
User
nuance: the system just renders at Transform.WorldPosition, whatever it is. If you want HierarchySystem to run before rendering (most of the cases you do), then yes. But the rendering pipeline doesn't cares about HierarchySystem or whatever system, it's a little like functional programming, it performs an operation on an input, it doesn't assumes anything about the input. This is true for the concept of ECS, so to all Systems. Of course, a dev can code a System that heavily assumes other systems did something before but then it's their job to guarantee that happened, at least today, but I see a future, if we find a nice way to implement it, to provide some easy ways to declare these conditions or dependencies between systems.
Yes, if CameraFollowSystem is enabled in the pipeline. It may verywell be the case of a game with fixed camera, or another implementation of cameras, we're the framework for any game one can think of, so we have to stay flexible. There can be implementations for 4 different cameras at once, maybe it's a local multiplayer game or CCTV system.
Yes.
Yes. This is a good example where it's expected that Transform.Delta is meaningful but this is not actually enforced (I think it's not enforced, don't remember if I coded some interaction methods on Transform to guarantee Delta is meaningful and consistent, if not, maybe I should.).
Yes, the parser systems should be ignorant on how CurrentLevelComponent got there, it only matters that it has been added. This is true for most (or all?) systems.
Yeah, I think that it should throw.
I think that they might be leftovers. But do mind that this is a framework, so we expose contracts, and no necessarily use them ourselves. But a good practice from now on would be to have a test and/or example to use a contract, a message, etc. To ensure it's an actual maintained contract/API.
Not that I can think of now.
Assistant
Crucial reframe. ECS systems are functional / pure: they operate on input, assume nothing about ordering. Responsibility for ordering belongs to the pipeline assembler (the screen), not to individual systems. That changes how I write premises — premises become "if you assemble these systems, this is the order required for correct behavior in pipeline X", not "system A depends on system B". Reference assembly is LoadLevelExampleGameScreen.cs:277–331, not a contract.
Aspirational items added to V1 follow-up:
Declarative system dependencies (future API).
Transform.Delta consistency-enforcing methods.
EntitySpawn should throw on unregistered identifier (not silent drop).
Test/example for every public contract (no unmaintained leftovers).
Modular packs (Spring Security analog).
Also: parser systems subscribing on CurrentLevelComponent-added (not on message) is a deliberate pattern. Adding component manually triggers parsing. This will get its own premise.
Batch E — naming, gotchas, conventions that trip people up
Some I already know from CLAUDE.md (EntityInfo as string, MonoDreams.EntityFactory not .Entity to dodge DefaultEcs.Entity shadowing, CameraFollowTarget location, "don't create new draw components"). Let me probe a few more I noticed during reconnaissance:
Transform.Parent vs ChildOf split. Today there's Transform.Parent (the matrix link) AND a separate ChildOf component (structural relationship), and HierarchySystem syncs them. Is that split intentional or accidental? Does it confuse you / does it confuse an AI agent reading the code cold?
Component folder inconsistency. Some components live directly under Component/ (Transform.cs, EntityInfo.cs, CameraFollowTarget.cs), others under Component/<subdomain>/ (Component/Draw/..., Component/Cursor/..., Component/Collision/..., Component/Physics/...). Is there a rule, or did it grow organically? Is reorganizing in scope or out-of-scope?
Visible empty tag. Newcomer sees DrawComponent and thinks "this is everything I need". The tag is only mentioned in . Your own debugging story (#10) is the canonical case. Would you rephrase the entity stack (" + + + + ") so newcomers don't miss ?
User
Yes, it confuses me. The problema I was trying to solve is how to handle complex UI elements like a dialogue UI that has the background banner, the avatars on each end, the text, and the visual indication of line finished and dialogue in a state waiting on input to advance to the next dialogue line. I just wanted to handle that in a simple and elegant manner.
Reorganizing is in scope, it's a little bit messy. What I want actually is to have those divided into packs/modules, just like Spring have Spring Data, Spring Security, etc.
Well, yes, it can be. Or maybe we should have visibility coded as a property of DrawComponent? I don't know.
Quick hack. We should find a more elegant and organized way of managing this.
None that I can think of right now.
Assistant
A few items here look like refactoring backlog as much as engine invariants. Captured:
Transform.Parent + ChildOf is confusing even to you — the canonical use-case is hierarchical UI (dialogue banner + avatars + text + indicator). Consolidation intent noted as aspirational.
Folder layout is messy → modular packs (Spring Data / Spring Security analog) — added to aspirational direction in CORE_TENETS.
Visible as DrawComponent.Visible bool — possible refactor; current state documented, refactor flagged.
Blender_ prefix is a quick hack — premise documents current behavior + flag.
Batch F — sizing the /deep-review skill
Final batch. The skill spawns N parallel agents. I have 6 personas proposed (§5 of the plan). I want to validate them and let you reshape if needed.
Adjacent-code agent (mandatory) — extracts semantic changes from the diff, greps callers, verifies each handles the new behavior.
System-ordering / pipeline agent (mandatory) — walks the per-frame pipeline at the screen registration site for each touched system; checks the pipeline assembler still produces sensible behavior. (Reframed per Batch D: ordering is the screen's responsibility, not individual systems.)
Component-design agent — verifies new components are pure data, checks if an existing component could have been extended (= your #1 pet peeve from Batch B). Also checks namespace placement (no MonoDreams.Entity).
Cross-domain dependency agent — for each domain touched, reads other domains' premises.md looking for **Depends on:** cross-refs that point back.
Premises / test-coverage agent — maps each premise to a test; flags Tests: none yet, flags new unstated premises the diff introduces.
ECS-purity agent — checks no logic in components, no parallel render systems, no shadowing of DefaultEcs.Entity, no individual systems assuming ordering of other systems (the functional-purity rule from Batch D).
Which of these are gold? Which feel redundant or off? Anything missing — e.g., a "contract-coverage" agent that catches public messages/components without a test or example (your point from Batch D about leftover contracts)?
User
Let's go with all of your suggestions.
"Added a super specialized component/system that solves one specific pain point right now but doesn't evolve well in the framework to deliver value for more implementations and play nice with other features in MonoDreams"
No
Worth it, include this option
Assistant
Interview complete. Per the plan, here's my restated model of the engine in 12 bullets. Read this top-to-bottom and tell me what's wrong / missing / needs sharpening. Once you confirm, I move to Phase 2 (drafting CORE_TENETS section-by-section).
MonoDreams — restated model
Framework-not-library. MonoDreams is to game devs what Spring is to web devs — full code control, ECS-required, framework handles common needs. Competitive position: between bare MonoGame (too low-level) and Nez (too loose). 2D primary; 3D possible later.
Two users, equal weight. Solo devs / small indie teams who like writing code, and AI coding agents. The docs we're writing are first-class artifacts for the second user, not just supplementary material.
Atomic unit of composition.Systems (primarily), often paired with new Components. Entities are just IDs grouping components. Net result: more Systems than Components.
ECS-purity is functional. Every System is a pure function: operates on whatever input components satisfy its query, makes no assumption about other systems' presence or ordering. The pipeline assembler (the screen) owns ordering. A future API for declarative system dependencies is in the aspirational backlog.
The #1 anti-pattern to catch. A hyper-specialized component/system that solves today's feature but doesn't generalize. The /deep-review skill's primary value is flagging "framework-shaped vs game-shaped" mismatches.
Discover-before-creating. Before adding a component or system, search what's there. Prefer extending an existing component. Modular packs (Spring Security analog) is the aspirational scoping mechanism.
Reference pipeline assembly.LoadLevelExampleGameScreen.cs:277–331 is the gold-standard ordering. Roughly: input → logic → physics (movement → velocity → detection → resolution → commit) → hierarchy → cull → prep → render last. Each game's screen owns its own pipeline; the reference is a recommendation, not a contract.
Transform invariant is "don't mix two." Custom MyTransform is allowed; mixing Transform + MyTransform is the bug. Aspirational: modules become Transform-implementation-agnostic so the collision stack plays nicely with any Transform-shaped contract.
User
Right
Assistant
Confirmed. Moving to Phase 2.
Assistant
Drafting CORE_TENETS Sections 1–2 (the meta-tenets — Framework + ECS purity). I'll stop here for voice approval before writing the domain sections.
Assistant
Sections 1–2 written. Two validation questions before I continue with Sections 3–8.
Assistant
Voice approved. Let me grep one detail Rodrigo didn't remember (Y-sort tiebreaker), then write Sections 3–9 in one pass.
Assistant
Got it — Y-sort uses parent-relative bias with epsilon; same-Y entities on the same layer fall through to insertion order. I'll write that honestly. Now Sections 3–9.
Assistant
Full CORE_TENETS draft is now in docs/CORE_TENETS.md (9 sections, ~440 lines). Before I move to Phase 3 (docs/index.md) and Phase 4 (5 premises files), please read it top-to-bottom and answer two questions.
Assistant
Drafting docs/index.md.
Assistant
Drafting candidate-bullet lists for the 5 premises files. Let me first check what tests exist so I can pre-tag candidates with likely Tests: mappings.
Assistant
Now I have a test-coverage map. Drafting all 5 premises files in parallel with candidate-bullet format.
Assistant
All 5 premises drafts written as candidate bullets + open questions + aspirational items. Total ~35 candidates across the files.
Files for your review:
docs/hierarchy-transform/premises.md — 7 candidates (H1–H7) + 2 open questions
docs/rendering/premises.md — 11 candidates (R1–R11) + 3 open questions
docs/collision/premises.md — 9 candidates (C1–C9) + 3 open questions
docs/physics/premises.md — 5 candidates (P1–P5) + 3 open questions
docs/level-loading/premises.md — 7 candidates (L1–L7) + 3 open questions
Please read each file and respond per-domain. Format that works for me: either "domain X all good" or "domain X: kill C6, add 'colliders for trigger zones should not push back', fix P4 — Last is set externally by collision response, not internally". Free-form is fine.
Once you confirm, I promote the bullets to full Why / Breaks / Tests / Depends on entries (the format from CORE_TENETS that the deep-review skill consumes), file the open-question items as known-unknowns, then move to Phase 5 (the skill).
User
docs/hierarchy-transform/premises.md — all good
docs/rendering/premises.md — all good
docs/collision/premises.md — all good (Tunneling at high velocity: the only prevention is keeping the velocity and collider sizes reasonable. this is a known gap/limitation.)
docs/physics/premises.md — all good (High-speed velocity caps: no caps exist; Gravity per-entity scaling: per-entity gravity scaling; RigidBody.Mass: only that one use but nothing prevents other uses)
docs/level-loading/premises.md — all good (Multiple levels loaded simultaneously: a future implementation, but not currently supported; Hot reload: doesn't fully work, needs attetion to work reliably; Factory re-registration: never thought about this, don't know what would happen if someone do this)
Assistant
All bullets confirmed. Promoting to full Why/Breaks/Tests/Depends-on entries, folding the answered open-questions in, and tightening per your notes.
Assistant
Drafting the deep-review skill.
Assistant
Appending Documentation / Premises / Skills sections to CLAUDE.md.
Assistant
Verifying all created files exist and CLAUDE.md links resolve.
Assistant
All links resolve. Marking Phase 6 done, then doing a quick dotnet build sanity check, then on to Phase 7.
Assistant
Build clean (63 warnings, 0 errors — all pre-existing). Now Phase 7 — exercising the skill against PR #22. I can't invoke /deep-review as a slash command (it's user-triggered), but I'll simulate the skill by following its Phase 0–4 instructions myself. That's the integration test the plan asks for.
Assistant
PR #22 metadata captured. The known-findings from commit 7ef39f8 give me ground truth:
Flat-hierarchy constraint on ConvexCollider.UpdateWorldVertices
NormalToSide 45° edge case
ContactPoint SAT approximation fidelity
Static-entity dirty-flag optimization
ColliderDebugSystem dev-only intent
-collider naming convention in Blender exporter
Saving the diff and running a representative subset of the agents (4 of 6 for the verification run — adjacent-code, system-ordering, component-design, premises-coverage). If findings are weak I'll add the other two.
Assistant
Spawning 4 agents in parallel, each pointed at its checklist in SKILL.md.
Assistant
All 4 agents returned substantive findings. Let me Phase 3-verify the highest-impact claims by reading the actual files, then consolidate and compare to ground truth.
Assistant
All three spot-checked claims verified against the source files. The skill works. Marking Phase 7 done and giving you the consolidated review + ground-truth comparison.
Ran 4 of 6 agents (adjacent-code, system-ordering, component-design, premises-coverage) with the full framework context. Phase 3 re-verified 3 high-impact claims by reading source files — all confirmed.
For enum-typed columns: list values explicitly (**Status enum:** A, B, C).
List named constraints, indexes, partial unique indexes — they encode invariants.
One-line relationships block: incoming and outgoing FKs.
docs/{domain}/premises.md — shape (the highest-leverage file)
10–30 premises per non-trivial domain. Fewer than ~5 means you missed invariants; near ~30 means the domain probably splits.
Each premise as an ## H2 section using exactly this format:
markdown
## <Short, declarative, present-tense title>
<One paragraph: what is true and must remain true. Be specific
about which entity, which field, which method, which condition.>
**Why:** <The reason — what concern motivates this. Often a past
incident or a downstream system that silently relies on this.>
**Breaks:** <What goes wrong if violated — specific downstream
systems, reports, calculations, or user-facing flows.>
**Tests:** <Test class or method that protects this premise. If you
can't name one yet, write `none yet` and treat it as debt.>
**Depends on:** <Cross-references to premises in other domains (by
title), if any. — if none.>
The Why is where the value compounds. Make it concrete: "the audit-join table assumes settlements are write-once; rewriting them would silently corrupt the audit trail and break the X reconciliation report" beats "we don't update this entity."
A premise with Tests: none yet is incomplete. New premises introduced by current work require tests before merge; retroactively-documented premises can start with none yet and become follow-up debt.
.claude/skills/deep-review/SKILL.md — shape
Frontmatter with name: deep-review and a one-line description:.
Phase 1 context gathering (CORE_TENETS + affected schema + affected premises + CLAUDE.md, passed to every agent).
Phase 2 spawns 4–6 parallel agents. Each agent prompt has: persona, embedded tenets (quoted from CORE_TENETS), a numbered checklist. Always include the adjacent-code agent and the state-machine/lifecycle agent (see §7 above).
Phase 3 consolidation with file re-verification for every Blocker/High.
Phase 4 output handling: present, then ask the human what to do with the review (post to GitHub, copy to clipboard, save to file, nothing).
An optional "economy mode" that swaps non-critical agents to a cheaper model.
When you find yourself unsure about voice or depth at any point during the bootstrap, ask the human to read 30 lines you've just written and tell you whether the tone matches what they want — they're the calibration source, not any external reference.
How to tailor the agents
From interview batch F, you have the 4–6 lenses the human wants. For each, write an agent prompt section with three parts:
Persona — "You are the engineer who owns X. You know every path that does Y."
Embedded tenets — quote the relevant CORE_TENETS section verbatim inside the agent prompt, then list the testable consequences ("Therefore, verify that …"). The agent must not need to re-derive the tenet.
Checklist — explicit, numbered steps. Two checklists generalize across every codebase and you should include them in every deep-review skill regardless of domain:
Adjacent-code checklist. This is the highest-value lens and catches bugs that diff-only reviews always miss.
Step 1: Extract semantic changes from the diff: new enum values, changed method signatures, new status values or transitions, changed filter/query conditions, new entity fields, changed business logic.
Step 2: For each semantic change, run an exhaustive grep across the repo for callers, references, and pattern-matched uses of the changed element. Also always grep for the most central financial/business primitives of the system (e.g., the settlement-creation site, the proportion calculator) — these are the "always check these" anchors.
Step 3: Open every grep hit and verify the method still handles the new behavior. If not → finding (file, line, scenario, suggested fix).
Step 4: Inverse check — does the new code handle all existing scenarios it didn't before? (e.g., a new filter that doesn't cover all status values).
State-machine / lifecycle checklist. Pick the most critical lifecycle in the system and walk it stage by stage. For each stage: which methods are called, what the entity states are at that point, which filters/guards depend on those states, and whether any of them fail with the new changes. Always include an execution-order check — bugs where step N's filter runs before step M's transition, returning empty when state has already moved, are some of the most dangerous and hardest to spot.
The remaining 2–4 agents are domain-specific. Examples of strong personas:
A "money flow" / "value propagation" agent that traces a new entity through the full downstream cascade and quantifies financial impact at each stage.
A "core pipeline" agent that owns the most heavily-used producer/consumer path and checks every place that produces an event of type X handles the new shape.
A "test coverage & premises" agent that maps each premise in the affected premises.md files to a test and flags premises with Tests: none yet or unstated premises the diff implicitly relies on.
Model routing
Keep an optional "economy mode" that swaps deep-thought agents from Opus to Sonnet. This is helpful for routine PRs.
Consolidation
The consolidation phase MUST verify each Blocker against the actual file — agents hallucinate, and a single false-positive Blocker in a code review erodes trust faster than five misses.
Test the skill before declaring done
Run /deep-review on a recently merged PR you know well. Compare findings to what you'd produce by hand.
Run it on a deliberately buggy branch (introduce a status filter that misses a new enum value) — does the adjacent-code agent catch it? If not, adjust the checklist.
Filters that depend on status: findByStatusIn(...), where status != ..., .filter { it.status in ...}. The set of statuses being filtered IS the premise.
Idempotency and dedup
Idempotency keys, unique constraints on (entity_id, kind, timestamp), "if exists return" patterns. Each is a premise that downstream consumers may not call twice.
Eventing contracts
"Every X site MUST publish event Y." Especially when the event drives a fan-out outbox.
"Event Y fires once on AFTER_COMMIT, never inside the transaction."
"Consumer Z must be idempotent because retry → at-least-once."
Cross-entity invariants the DB doesn't enforce
The interview will surface these ("store custom attribute must reference an attribute declared by its franchisor — the DB doesn't enforce it").
Search for service-layer validation patterns — when a service does a findById + check before insert, the check is a premise.
Monetary atomicity
"Amount X always equals … in cents." "Amount Y is the bank amount; amount Z is the effective amount and they differ only when discount is honored."
Insert-only history
Audit tables (Envers / equivalents). Anything time-travel-like. Anything that says "history is never rewritten."
Time and timezone
"All timestamps are UTC at rest." "Date X is wall-clock in São Paulo for business reasons."
"Test suite runs in UTC."
Concurrency
Pessimistic locking calls (SELECT … FOR UPDATE / @Lock(PESSIMISTIC_WRITE)) protect an invariant — the invariant is the premise.
Optimistic locking (@Version) on an entity says "concurrent writers must lose; the surviving write wins" — sometimes a premise.
How to draft, mechanically
For each major domain, spawn an Agent (or open a deep work session) that:
Has the affected source files in context.
Has the interview notes for that domain.
Produces a first list of premise candidates (one bullet each, no full bodies yet) — easily 20–40 per domain on a complex system.
Run the candidate list past the human. They will:
Confirm or kill each one.
Add 3–10 they can think of that no agent would have spotted.
Refine the Why for the load-bearing ones with the story behind them.
Promote confirmed candidates to full premise entries with the format above.
For each premise, search for an existing test that would break if the premise were violated:
If found, name it in **Tests:**.
If not, write none yet and add a follow-up task. Premises with none yet are debt — list them at the end of the bootstrap.
Link related premises with [[premise-title-slug]] or by full title. Cross-domain dependencies use **Depends on:** {domain} — "Premise title".
Sizing
A premises file with fewer than ~5 entries is suspect — push harder, you probably missed invariants.
A premises file approaching ~30 entries is a signal that the domain is too broad. Ask the human if it splits cleanly.
Batch D — Cross-domain assumptions
"Is there a domain that depends on another's invariant — e.g., 'cohort math assumes settlements are write-once'? Name as many as you can."
"Are there events / messages between domains that imply contracts? ('domain A publishes E; domain B assumes E fires exactly once on commit')"
Batch E — Naming and gotchas
"Are there fields or tables whose names trip up new engineers? ('I'd guess X but it's Y')."
"Are there renames in the recent history that are still tripping people up? Legacy fields that look used but aren't?"
Batch F — Sizing the deep-review skill
"If you were reviewing a PR in this codebase, which 4–6 lenses would you wear? (e.g., 'money-flow expert', 'state-machine expert', 'adjacent-code expert who finds untouched callers that break')"
"What kind of finding is the highest-value? (e.g., 'someone added a new status value but didn't update three downstream filters')"
"Are there tests / architecture rules that are already protecting some of these invariants? Point me at the gold-standard test file."
After the interview, restate your model of the system back to the human in 8–12 bullet points and ask "is this right?" Adjust before drafting docs.
unique
(entity_id, kind)
Stop and write a one-paragraph "money flow" note for yourself before continuing.
1.4 Database structure — first, decide if this repo even has one
Run a quick gate to determine whether the schema layer applies:
Also search broadly for ORM/entity definitions (@Entity, class \w+\(Base\), models.Model, Prisma model , Diesel table!, etc.).
Decision:
Repo owns DB code (migrations, schema source, or ORM entity definitions present) → the schema layer applies. Continue reading this section.
Repo does NOT own DB code (pure library, CLI, UI, SDK, thin API client) → skip this section, skip §4 (schema drafting) entirely, and proceed with CORE_TENETS + premises + deep-review only.
Ambiguous case (e.g., reads from a shared DB owned by another service, or uses an external API as its data source) → confirm with the human. Default to not writing schema docs the human would have to keep in sync with someone else's system; instead capture the contract in a docs/{domain}/<external-system>.md knowledge doc.
If the schema layer applies, continue with the reconnaissance:
Skim the most recent ~10 migrations: those name the current concerns of the team. Anything you read in old migrations may have been renamed.
For Postgres specifically, look for: CHECK constraints, partial unique indexes (WHERE), EXCLUDE constraints, ON CONFLICT patterns, triggers. These often encode invariants the application code assumes.
Renames are dangerous. git log --diff-filter=R --follow per file and inspecting migration files that mention RENAME catches the most common "common gotchas" entries (e.g., a field everyone now calls customer_id but which used to be company_id).
1.5 Services, events, and async flow
Find the request-handling layer (controllers, handlers, resolvers, RPC endpoints).
Build an event topology: which services publish events, on which topics/queues, consumed by which listeners? Look for convertAndSend, publish, enqueue, send_message, produce. Cross-reference subscribers/handlers.
Identify fan-out outboxes (a single publish that drives multiple downstream listeners). These are premise-rich: each subscriber introduces an implicit "this event will be fired exactly once on commit" assumption.
Identify transactional boundaries: where do transactions start and end? Are there post-commit hooks? Is @Transactional used? transaction.atomic()? BEGIN/COMMIT?
1.6 Tests
Test directory structure, test types (unit / integration / e2e), what containers/fixtures are used (testcontainers, in-memory, mocks).
Existing test naming conventions (these will inform how premise **Tests:** fields cite tests).
Architecture tests (ArchUnit, dependency-cruiser, custom lint) — these are premise-protectors and a model for new ones.
1.7 What you've learned, written down
Before going to the human, summarize for yourself (don't post it):
Top 5–10 entities and how they relate (draw it on paper / a scratch file).
The "happy path" of the core use case: from input to persistence to downstream effects.
3–5 things that surprised you or you don't yet understand.
3–5 places where the code clearly assumes something the code itself doesn't enforce (these are premise candidates).
If you cannot do this after reconnaissance, you don't have enough context to interview the human productively. Do another pass.
not
Why this works at all: AI agents in undocumented repos guess. Guesses about money flow are catastrophic in fintech-shaped systems and merely embarrassing elsewhere. The premises files in particular surface invariants that are invisible from reading code in isolation — the kind that only emerge when you stack multiple files together or run a flow end-to-end. Once written down, a reviewer agent can check changes against them.
Visible
CullingSystem
EntityInfo
Transform
SpriteInfo
DrawComponent
Visible
Visible
Blender_ identifier prefix. Levels named with a Blender_ prefix go to the Blender parser, everything else goes to LDtk. Is this a stable convention or a quick hack? Should the prefix be in the level's content/data instead of its name?
Anything else — names, conventions, locations — where you've thought "I'd guess X but it's actually Y"? Especially anything that recently changed (the Examples → Core moves over phases 1–8).
Highest-value finding type. If /deep-review could only catch ONE class of bug in this codebase, which one? (Examples: "missed a downstream caller that doesn't handle a new enum value", "added a new component when an existing one could be extended", "broke an aspirational invariant we wrote down but didn't enforce in code", "introduced a system that silently assumes another system ran first".)
Architecture / lint rules already in place. Are there any tests or analyzers that protect invariants today? E.g., does the codebase use Roslyn analyzers, custom test helpers, anything in MonoDreams.Tests/ that asserts an architectural property (not just behavior)? I see SATCollisionTests, BlenderLevelTests, InfiniteRunnerTests and GameTestRunner — are any of these "gold standard" for the style of test the premise Tests: fields should ideally cite?
Eco / fast mode. The bootstrap prompt suggests an optional "swap deep-thought agents to Sonnet" flag. Worth it for solo-alpha? Or single-mode-Opus is fine?
Last batch — after this I'll restate the engine's model back to you in 8–12 bullets and we'll start drafting.
Rendering pipeline runs last. Three render targets (Main / UI / HUD), unified DrawComponent (Sprite/Text/NinePatch/Mesh), MasterRenderSystem is the sole renderer. Visible tag owned by CullingSystem. Refactor candidate: Visible as a DrawComponent.Visible bool.
Collision and physics coupling to Transform is implementation debt, not desired design. Aspirational: loose coupling to any Transform-shaped contract.
Component-added contracts, not message contracts. Parser systems subscribe to CurrentLevelComponent-added events; they don't care how it got there. Most/all systems follow this pattern. Every public contract (message, component, system) should have a test or example — otherwise it's suspect / leftover.
Refactor backlog (named on the record):
ChildOf vs Transform.Parent split (confusing; consolidation desired).
Blender_ identifier prefix (quick hack; needs a more elegant dispatch).
Transform.Delta consistency not enforced (no API prevents stale reads).
Headless mode is experimental, not load-bearing.
No architectural tests yet — every premise will start at Tests: none yet unless behaviorally covered by SAT/Blender/InfiniteRunnerTests.
Right / wrong / sharpen?
No (not surfaced — narrow numerical edge case, plausibly out-of-reach for static review)
#3 ContactPoint SAT approximation fidelity
Partial — Agent 1 (A1.3) caught a related issue: SAT collisions emit contactTime=0, breaking the sort order in resolution
#4 Static-entity dirty-flag optimization
No (performance optimization, not invariant violation)
#5 ColliderDebugSystem dev-only intent
Yes — Agent 2 flagged the related premise violation: debug systems add Visible outside CullingSystem
#6 -collider naming convention in Blender exporter
No (documentation-only)
Acceptance criteria from §9 of the plan: at least one of (a) adjacent-code finding from 7ef39f8, (b) collision-pipeline ordering observation, (c) BroadPhaseAABB refresh contract premise. All three met.
Bonus findings the human reviewer did not flag (all verified)
CollisionType enum embeds game-specific values (Collectible, Damage, Dialogue, NPCInteraction) in a core message — exactly the "specialized component that doesn't generalize" anti-pattern you named in Batch F as the #1 review lens.
SpriteDebugSystem debug entities never render — missing Visible tag; the system is silently broken today.
CollisionType.NPCInteraction is emitted but has no consumer — NPCInteractionSystem uses its own geometric scan instead of subscribing to the message. Wasted CPU + dead contract.
Two CollisionMessage static factories (Create, CreateSAT) are dead code — never called; the CreateCollisionMessageDelegate path supersedes them.
ColliderTag cleanup on collider removal is undefined — auto-add hooked, auto-remove missing. The collision premises file already flagged this as an open question.
ConvexCollider has a logic-shaped instance method (UpdateWorldVertices) — pure-data violation per CORE_TENETS §2.
IgnoreTransformRotation is a Blender-pipeline escape hatch on a core component — same anti-pattern, smaller scale.
Only one consumer exercises the TCollisionMessage generic — abstraction unprotected; CORE_TENETS §2 demands a use site.
Where to go from here
Consider folding the bonus findings into a follow-up PR (most are 1–5 line fixes).
The 4 proposed premises from Agent 5 (BroadPhaseAABB refresh contract, ICollisionMessage immutability, ColliderTag removal cleanup, SATCollision statelessness) are good candidates to fold into docs/collision/premises.md.
The skill ran with 4/6 agents and already hit all three acceptance criteria. Real runs with all 6 (including cross-domain + ECS-purity) will find more.
Bootstrap V1 complete. The deep-review skill recovered ground-truth findings #1, #3, #5 (in part), and surfaced 8+ additional valid findings — well above the "non-trivial and accurate" bar.