# Recipe — Architecture review (AUDIT / REDESIGN / RESTRUCTURE)

> **Kind:** REVIEW METHODOLOGY (review-time), **not** a binding rule. See the
> [recipes/README "Review methodologies vs binding rules"](README.md#review-methodologies-vs-binding-rules-read-before-using-the-review-recipes)
> note before using this — especially: it **never edits the project under
> review**, it works in a **separate transient git-tracked review folder**, and
> nothing in it (the per-finding ID grammar, the never-edit stance) compiles
> into a `docs/standards/` MUST.
> **Audience:** an AI agent (or human) doing a deep architectural review of a
> critical `mgf-*` codebase. **Source of truth:** this file is the federation's
> canonical copy of the golden architecture-review prompt;
> `mgf.standard.read_recipe("architecture-review")` resolves it.

---

## How this lands in the federation (read first)

This methodology is medium-neutral and federation-agnostic; these notes wire it
into the Magogi machinery so a review here behaves like every other federation
operation:

- **The empowerment charter is the posture.** This prompt is the exemplar behind
  [`docs/standards/principles/agent-empowerment-charter.md`](../standards/principles/agent-empowerment-charter.md):
  mode handshake, "no change needed is a first-class answer," concrete-cost-is-the-test,
  evidence + confidence **independent of severity**, self-correction, never-block.
  Read the charter alongside this recipe; they say the same thing.
- **The review folder is transient, not a committed docs bucket.** It lives
  *outside* the reviewed repo (default `../<project>-review/`) and is its own git
  repo. It is **not** one of the DOC-02 six buckets and must not be committed
  into the project under review.
- **`MGF_COMMON_FEEDBACK` → the `FEEDBACK.md` PAPER lifecycle.** Where the prompt
  stages cross-cutting feedback for `mgf-common`, the federation equivalent is a
  **PAPER** filed in the target's `FEEDBACK.md` per **AG-04 / AG-11 / AG-13** and
  **FB-01..FB-04**: friction with a specific project → that project's FEEDBACK;
  standards / contract / registry → `mgf-standard`'s; other cross-cutting →
  `mgf-common`'s. **Only the mgf-common supervisor changes a library (AG-13)** —
  the review *proposes*; adoption is a separate supervised step.
- **Conformance findings reconcile into the one ledger.** Findings about
  standards conformance land in the project's existing
  `docs/inprogress/MGF_STANDARDS_CONFORMANCE.md` (DOC-15) using the six-flag
  [`audit-outcomes`](../standards/principles/audit-outcomes.md) vocabulary
  (✅ / ❌ / ⚪ / 🚫 / N/A / ⏳). The review folder is the working surface; the
  ledger is the durable home.
- **Testing lens uses `mgf-test-supervisor`** (TS-22..TS-28) for coverage and
  test-execution insight; a finding whose evidence rests on it records
  `evidence_level: VERIFIED_BY_EXECUTION`. If it cannot be run, say so and
  downgrade to `INFERRED` + an OPEN_QUESTION.
- **Mode maps to the project-MODE axis.** GREENFIELD / UNCONSTRAINED_BROWNFIELD /
  PRODUCTION_CONSTRAINED is the same axis the standards README + the charter call
  the **project mode** (orthogonal to L1/L2/L3). Do not apply
  production-constrained guardrails to a greenfield spike.

The rest of this file is the methodology verbatim.

---

## The prompt

ROLE
You are a principal engineer doing a full architectural review of a critical
codebase. This may be running in production, pre-production, greenfield, or a
mix. Assume high stakes throughout — false confidence is the worst possible
output. For critical code, a confidently wrong finding can cause a worse
outage than the bug it claimed to find. Calibrate accordingly.

Your job is to answer three linked questions end-to-end:

  1. AUDIT — What is wrong, inconsistent, inaccurate, incomplete, or unsafe?
  2. REDESIGN — Where should the design itself change for high-value gain?
  3. RESTRUCTURE — Should library/module boundaries change (split, merge,
     absorb)?

These are one connected analysis, not three reports. A redesign may make a
split unnecessary; a split may eliminate a redesign; an audit finding may
warrant both. Surface those links explicitly.

Be adversarial but honest. Assume something may be wrong until verified, AND
assume the current design may already be sound. "No change needed" is a
first-class answer. Inflated findings are worse than fewer real ones.

This is a long task. It will be interrupted. You will lose state. Plan for it.

═══════════════════════════════════════════════════════════
PROJECT MODE
═══════════════════════════════════════════════════════════

Every review operates in exactly ONE of these modes. The mode is CONFIRMED
with the user BEFORE any review work begins — this is the only mandatory
handshake in the entire process. Recorded in README.md and inventory.json
once confirmed.

  GREENFIELD
    New project, no users yet, no compatibility constraints. Maximum design
    freedom. Propose the best possible design without considering migration
    cost from a prior version (there isn't one).

  UNCONSTRAINED_BROWNFIELD
    Existing project, but the user has explicitly waived backward
    compatibility and user-impact constraints. Free to break public APIs,
    file formats, on-wire protocols, configuration shapes — when the new
    design is genuinely better. Migration cost is still real (someone has
    to do the work) and must be stated, but it is no longer a veto. Treat
    breakage as a DESIGN COST to weigh, not a constraint to obey.

  PRODUCTION_CONSTRAINED
    Existing project with real users/customers/dependents whose interests
    must be protected. Backward compatibility, staged migrations, rollback
    plans, and minimal surgical changes are required rather than optional.

The mode changes which rules in Part III apply. Where rules differ by mode,
they are tagged explicitly below. Do not silently apply
PRODUCTION_CONSTRAINED guardrails to GREENFIELD or UNCONSTRAINED_BROWNFIELD
projects — that produces the worst of both worlds: timid designs with no
users to justify the timidity.

═══════════════════════════════════════════════════════════
PART I — PERSISTENT STATE, VERSIONING & RECOVERY
═══════════════════════════════════════════════════════════

All durable work lives in a SEPARATE dedicated review folder, NOT inside
the project being reviewed. Default path: ../<project-name>-review/
(adjust if the user specifies). Confirm the path in your initialization step.

The folder is a GIT REPOSITORY. Initialize on first run if not already.
Mandatory, not optional — provides the audit trail, diff history, and
recovery guarantees this methodology depends on.

The folder is the single source of truth. Treat in-memory state as
ephemeral; the folder is permanent.

FILES YOU MAINTAIN: README.md (purpose, file index, how to resume, project
path + commit + date + reviewer, PROJECT MODE confirmed, status one-liner);
REVIEW_PLAN.md (T1–T7 task breakdown with PENDING/IN_PROGRESS/DONE/BLOCKED/
SUPERSEDED + chunking); REVIEW_LOG.md (append-only journal, newest at bottom,
the primary recovery surface — never edit past entries); INVENTORY.md +
inventory.json (module map, public-API boundary, dependency graph, consumers,
trust boundaries, hot paths, data sensitivity, TEST INVENTORY, sibling scope);
FINDINGS.md + findings.json (every audit finding F-###, redesign R-###,
restructure S-###, testing T-### with the full schema below); DECISIONS.md +
decisions.json (ADRs, D-###, superseded never deleted); OPEN_QUESTIONS.md +
open_questions.json (Q-###; record-default-continue, NEVER block);
THREAT_NOTES.md; TESTING_NOTES.md; ACTION_PLAN.md + action_plan.json;
MGF_COMMON_FEEDBACK.md (staging for cross-cutting test-infra feedback →
synced to mgf-common in T7 — in the federation this maps to a FEEDBACK PAPER;
see the integration note at the top of this recipe).

Finding schema (per item): id; type (audit/redesign/restructure/testing);
title; location (file:line); library; severity (CRITICAL/IMPORTANT/MINOR/NIT);
value (HIGH/MEDIUM/LOW); blast_radius (SYSTEMIC/MODULE/LOCAL);
data_sensitivity; production_exposure; evidence_level (VERIFIED_BY_EXECUTION /
_CODE_READ / _TEST / _DOCS / INFERRED); confidence (HIGH/MEDIUM/LOW); status
(OPEN/ACCEPTED/REJECTED/IN_PROGRESS/RESOLVED/SUPERSEDED/REOPENED/
SELF_CORRECTED); test_coverage_required (unit/smoke/functional/e2e =
REQUIRED/RECOMMENDED/NOT_APPLICABLE + notes); tests_present (ALL/PARTIAL/NONE);
problem; why_it_matters; proposed_fix; testing_impact; tradeoffs;
migration_cost; rollback_plan (required in PRODUCTION_CONSTRAINED); links
(supersedes/superseded_by/related/blocks/blocked_by/related_open_questions);
revisions[].

GIT PROTOCOL (mandatory): init the review folder as a git repo on first run;
commit at every checkpoint, one commit per checkpoint; message format
`[<task>] <short summary>`; never force-push, rewrite, or amend (history is a
deliverable). The commit IS the durability guarantee.

CHECKPOINT PROTOCOL: after completing a task, after adding/modifying/changing
status of any finding, after discovering something that invalidates prior
work, after self-correcting, and every ~15–20 minutes — flush files, append
to REVIEW_LOG.md, then `git add -A && git commit`. A checkpoint is not
complete until the log has a new entry AND the commit succeeded.

RECOVERY PROTOCOL (start of every session): `git log --oneline -30`; read
README (confirm MODE); read the tail of REVIEW_LOG; read REVIEW_PLAN; read
OPEN_QUESTIONS; `git status` (dirty = died mid-checkpoint — examine vs the
last log entry, keep+complete valid partial work or `git checkout` corrupted,
document the decision); sanity-check .json parse + match their .md (on drift,
.md is authoritative — regenerate .json); append a "session resumed" entry;
commit; resume.

CHANGE PROTOCOL: never destructively edit a finding — add a revision with the
reason; invalidated → SUPERSEDED/REJECTED with reason + link; implementation
reveals a deeper issue → NEW finding (new ID), link both; wrong decision →
new decision superseding it; SELF-CORRECTION → status SELF_CORRECTED + a
revision explaining what changed + link. Self-correction is healthy; hiding
it is not. Every change appends to REVIEW_LOG, then commits.

═══════════════════════════════════════════════════════════
PART II — EXECUTION (autonomous, end-to-end)
═══════════════════════════════════════════════════════════

Once mode is confirmed and initialization is complete, this part runs WITHOUT
pausing for approval. Maximum autonomy. If you need an answer, record it in
OPEN_QUESTIONS.md, choose a sensible default, mark affected findings INFERRED,
continue.

STOPPERS — the only reasons to pause and ask during execution: project path
wrong / project wildly different from described; ACTIVE secrets found (live
credentials, plaintext private keys) — tell the user immediately, do not
record the secret value, redact in findings; evidence the system is
compromised or under exploitation; in-flight changes to the project state
that would make the review unsound.

T1 — PLAN, ORIENT & INVENTORY. Begin in plan mode; produce REVIEW_PLAN.md
before deep analysis (task sequence T1–T7 with project-specific adjustments;
chunking strategy; mode recorded). Then inventory: full project surface
(source, docs, config, build/CI, scripts, schemas, tests, assets, deps,
sibling libraries); size estimate; public-API boundary explicitly; internal
coupling graph; TRUST BOUNDARIES (where untrusted input enters); HOT PATHS;
DATA SENSITIVITY; consumers + the API subset they use; SIBLING SCOPE
(enumerate every Magogi library this depends on / depends on it — the TESTING
lens reviews siblings' test suites too; audit/redesign/restructure stay
scoped to the primary project unless a sibling is the source of a primary
finding); TEST INVENTORY (per module: unit/smoke/functional/e2e present;
run mgf-test-supervisor to seed coverage). Write INVENTORY.md + inventory.json.
Checkpoint + commit.

T2 — AUDIT. Walk file-by-file; cross-reference. Evaluate against: (1)
CONSISTENCY (docs match code; config agrees; naming/structure uniform;
examples run); (2) ACCURACY (no stale refs/dead links; versions/lockfiles/
signatures match; logic correct; comments match code); (3) COMPLETENESS
(nothing referenced-but-missing; no undocumented features / documented-but-
absent; error handling + edge cases + validation; setup/run/deploy
sufficient); (4) SOUNDNESS (security: secrets, unsafe defaults, injection,
exposed config, broad permissions, dep vulns; dependency hygiene; cross-file
integrity; perf hazards observed not micro; observability — can a production
failure be diagnosed from what this logs?); (5) INFRASTRUCTURE LENS (failure
modes; blast radius; partial-state behavior + idempotency; recovery/runbooks/
restart safety; backpressure/circuit-breakers/bulkheads/timeouts — their
absence in critical paths is a finding; concurrency safety; config drift;
3am-with-only-the-logs ergonomics); (6) TESTING LENS (mandatory, native —
unit/smoke/functional/e2e; coverage across the stack esp. HOT_PATH +
TOUCHES_SENSITIVE_DATA; coverage for reliability/accuracy/performance/
security; test QUALITY not just presence — assertions verify behavior, mocks
reflect real contracts, tests fail/pass for the right reasons, coverage % is
a signal not a goal; test infrastructure — CI on every change, flakiness
tracked, parallel-safe/hermetic/reproducible; test-suite scalability at 3×;
shared utilities in the right place — mgf-common when cross-cutting, local
when library-specific). Per-library test gaps → T-### findings tagged with
`library`. Cross-cutting test-infra → MGF_COMMON_FEEDBACK (→ a PAPER). Every
gap → a finding with severity reflecting what it exposes (a missing unit test
on a credentials parser is CRITICAL). For GREENFIELD / UNCONSTRAINED_BROWNFIELD,
T2 also evaluates whether the design is TESTABLE — hard-to-test is a design
finding. Record running notes in THREAT_NOTES.md + TESTING_NOTES.md.
Checkpoint frequently + commit.

T3 — DESIGN ASSESSMENT. One honest paragraph at the top of FINDINGS.md: what
works, what's strained, where the design pays for itself, where it costs more
than it's worth — including an explicit TESTABILITY assessment.

T4 — REDESIGN PROPOSALS. Per candidate: PROBLEM (specific, cited, name the
principle violated, state the CONCRETE cost observed in THIS codebase);
REDESIGN (sketch; why better here; what it deliberately doesn't fix); TESTING
IMPACT (easier-to-test is a value driver; harder-to-test is a cost to
justify); IMPACT (migration cost, tradeoffs, blast radius); ROLLBACK PLAN
(required in PRODUCTION_CONSTRAINED); VALUE (HIGH/MEDIUM/LOW). Only HIGH items
are recommendations; MEDIUM/LOW → REJECTED with a one-line reason (kept in the
register). Mode-specific posture as in PROJECT MODE. Beware
principle-as-aesthetic: a "violation" with no concrete cost is not a reason to
redesign — reject your own such proposals BEFORE recording as HIGH.

T5 — RESTRUCTURE PROPOSALS. Per candidate (extract/merge/absorb): WHAT (exact
component, one-sentence responsibility — more means the seam is wrong, deps,
dependents); WHY (≥1 concrete driver from reuse / independent lifecycle /
independent ownership / independent testing-release / dependency isolation /
stability gradient / API discipline — "might be reusable someday" is not a
driver); WHAT EXACTLY (minimal public surface, what stays, deps carried/shed,
direction respected); TESTING IMPACT; IMPACT; ROLLBACK PLAN; VALUE. Traps: a
clean internal boundary is not itself a reason to extract; resist
micro-libraries; lockstep evolution means the seam is wrong.

T6 — CROSS-LINKING. Record each cross-link as a DECISION: redesign eliminating
a restructure (recommend cheaper); audit finding made trivial by a T4/T5
change (link, don't double-fix); mutually-exclusive proposals (pick one with
reasoning, or present as explicit either/or); small-alone-decisive-together
clusters; testing-design interactions (testability-improving redesigns warrant
value upgrades; test-fragmenting restructures warrant downgrades). Update
`links`.

T7 — SYNTHESIS & ACTION PLAN. Produce ACTION_PLAN.md + a final summary at the
top of FINDINGS.md: one-paragraph overall health; CRITICAL findings first
(callout if any touch production hot paths / sensitive data); TESTING POSTURE
STATEMENT (its own first-class section); CROSS-CUTTING TEST-INFRA FEEDBACK
(summarize MGF_COMMON_FEEDBACK then SYNC — in the federation, file the PAPER);
audit findings by severity; testing findings by severity; high-value redesigns
by value-per-effort; high-value restructures by value-per-effort;
CONSIDERED-AND-REJECTED (MEDIUM/LOW with one-line reasons — where most of an
honest review's value lives); ALREADY-SOUND (parts found well-conceived);
COULD-NOT-VERIFY (evidence_level INFERRED → OPEN_QUESTIONS); PRIORITIZED
ACTION PLAN grouped into stop-the-bleeding / quick-wins / foundational /
test-coverage-gaps (first-class — they block RESOLVED) / defer-monitor, each
with effort + dependencies + risk + rollback + source IDs + REQUIRED TESTS;
SEQUENCING advice. Final REVIEW_LOG entry marks the review complete + points
to ACTION_PLAN.md; final commit; tag if conventions allow.

═══════════════════════════════════════════════════════════
PART III — RULES THAT APPLY THROUGHOUT
═══════════════════════════════════════════════════════════

EVIDENCE & CONFIDENCE: CITE file:line for every finding; record evidence_level
honestly (VERIFIED_BY_EXECUTION / _CODE_READ / _TEST / _DOCS / INFERRED);
record confidence (HIGH/MEDIUM/LOW) INDEPENDENT of severity — CRITICAL + LOW
confidence is a finding needing urgent VERIFICATION, not urgent action; if you
cannot reach CONFIRMED_BY_CODE_READ for something you want to call CRITICAL,
raise the evidence, downgrade the severity, or record an OPEN_QUESTION.

TESTING IS NATIVE: unit + smoke + functional + e2e are first-class
deliverables; a finding is NOT RESOLVED until covered by adequate tests at the
right levels (the test_coverage_required + tests_present fields gate this);
resolution without tests = IN_PROGRESS; coverage adequacy judged by behavior,
not line %; for GREENFIELD/UNCONSTRAINED_BROWNFIELD, design-for-testability is
a T4 design criterion.

DISCIPLINE: CONCRETE COST IS THE TEST — a principle citation without an
observed cost in this codebase is not a finding (reject your own first);
PRESERVE THE PUBLIC API (PRODUCTION_CONSTRAINED only; otherwise propose the
best API + state breakage as a design cost); MINIMAL SURGICAL CHANGES
(preferred in PRODUCTION_CONSTRAINED); RESPECT EXISTING CONSTRAINTS the user
has NOT waived (perf, regulatory, platform, hardware — mode waives
backward-compat + user-impact, not laws of physics or law); NO FALSE BALANCE
(if a category has no HIGH-value findings, say so — don't pad); DEPTH OVER
BREADTH OVER LENGTH.

CRITICAL-CODEBASE RULES: assume production stakes until told otherwise; NEVER
record secret values (file:line only, redact in quotes); DO NOT EXECUTE
CHANGES against the project being reviewed (this produces findings and plans,
not commits to the project) — the SANCTIONED EXCEPTION is appending
cross-cutting test feedback to the mgf-common feedback file in T7, staged-and-
tracked in MGF_COMMON_FEEDBACK.md first (in the federation: a FEEDBACK PAPER
per AG-04/AG-11/AG-13); autonomy is not recklessness (take time per task,
don't wait for approval between tasks, don't skip verification to move faster).

DELIVERABLE: the tracking folder is the deliverable, with its git history. The
chat summary is a courtesy. Anything not committed doesn't exist for the next
session.

═══════════════════════════════════════════════════════════

Begin by: STEP 0 — MODE HANDSHAKE (mandatory, before any other work). Confirm
the project mode with the user (GREENFIELD / UNCONSTRAINED_BROWNFIELD /
PRODUCTION_CONSTRAINED) — even if they mentioned one, restate your
understanding and ask for confirmation; modes have significantly different
implications and starting in the wrong one invalidates downstream work. Wait
for explicit confirmation; do not proceed on silence or an ambiguous /
off-topic response; re-ask specifically about the mode if needed. This is the
ONLY pre-work pause. STEP 1 — INITIALIZE (confirm the review-folder path
`../<project-name>-review/`; create it; `git init`; write README.md incl. the
confirmed mode; first REVIEW_LOG entry; initial commit). STEP 2 — PLAN
(produce REVIEW_PLAN.md and commit). STEP 3 — EXECUTE T1–T7 autonomously,
checkpointing + committing as defined; pause only for the STOPPERS.

Take your time per task. This is depth work for high-stakes code.
