Generate architecture guidelines for the project. Analyzes tech stack from DESCRIPTION.md, recommends an architecture pattern, and creates .ai-factory/ARCHITECTURE.md. Use when setting up project architecture, asking "which architecture", or after /aif setup.
Installs into .claude/skills of the current project.
Sponsors
SSkills DirectorySkills Directory
Know which skills are safe — weekly.
SSkills DirectorySkills Directory
Is that skill safe to install?
Are you the author of Aif Architecture?
Add the live security badge to your README. It updates with every re-scan.
[](https://www.skillsdirectory.com/skills/lee-to-aif-architecture)
---
name: aif-architecture
description: Generate architecture guidelines for the project. Analyzes tech stack from DESCRIPTION.md, recommends an architecture pattern, and creates .ai-factory/ARCHITECTURE.md. Use when setting up project architecture, asking "which architecture", or after /aif setup.
argument-hint: "[layers | structured[-layers|-vertical] | explicit[-layers|-vertical|-flat] | microservices[-single|-monorepo] | clean | ddd | monolith | vertical] [--style=subfolders|unified] [--policy=adapt|strict]"
allowed-tools: Read Write Edit Glob Grep Bash(mkdir *) AskUserQuestion Questions
disable-model-invocation: false
---
# Architecture - Generate Architecture Guidelines
## Runtime-aware questions
Apply this contract whenever the workflow asks the user to decide:
- `AskUserQuestion` and `Questions` below describe the intended interaction, not a required tool name. Use only a question tool actually exposed and permitted in the current session/mode, with its advertised schema. Do not guess aliases, probe unavailable tools, or assume `questionnaire` exists. A frontmatter entry alone does not make a tool available.
- Ask one focused question at a time with clearly labelled options. Batch independent questions only if the actual tool schema supports it; respect its field names, limits, and selection semantics. For open-ended input, use native free-text support or plain text if the schema cannot represent the question. Use the resolved UI language.
- If no usable question tool exists (or it reports unavailable in this mode), ask the same question in plain text with numbered options and allow a free-text answer. Pause work that depends on that answer; independent read-only investigation may continue. Missing UI does not make the session autonomous.
- An empty/cancelled response, a preselected option, or elapsed time is not an answer or approval. Reuse an answer already given in the session instead of asking again.
- In a subagent/background run or explicit non-interactive mode (including `HANDOFF_MODE=1`), do not prompt the user directly. Use declared defaults only for optional preferences within the authorized scope and report assumptions. If a required decision, approval, or material scope/behavior choice remains unresolved, stop dependent work and return the missing decision and options to the parent/caller using its existing blocked/failure contract. Never invent consent or select a new scope to avoid blocking.
This delivery policy applies to this skill and its linked references. Preserve workflow-specific question scope, required confirmations, approval boundaries, and blocked-result rules.
## Shared project skill-context
Before mode routing or work, read existing files relative to the current project root in this order (reuse them if already loaded):
1. `.ai-factory/skill-context/global-skill-context.md` — all bundled skills.
2. `.ai-factory/skill-context/aif-architecture/SKILL.md` — this skill.
Missing files are skipped; an existing unreadable file stops dependent work with its path.
Precedence: individual > build (when applicable) > global > skill defaults; retain non-conflicting instructions and check all outputs against the effective rules.
These layers customize workflow; they do not replace the project's rules/architecture hierarchy or relax explicit requirements, ownership, scope, safety/privacy, validation, or approval boundaries. Report conflicts with those boundaries instead of overriding them.
`global` is a project-local layer, not home-directory configuration. Custom/extension skills do not automatically use it.
**Read `.ai-factory/skill-context/aif-architecture/SKILL.md`** — MANDATORY if the file exists.
This file contains project-specific rules accumulated by `/aif-evolve` from patches,
codebase conventions, and tech-stack analysis. These rules are tailored to the current project.
**How to apply skill-context rules:**
- Treat them as **project-level overrides** for this skill's general instructions
- When a skill-context rule conflicts with a general rule written in this SKILL.md,
**the skill-context rule wins** (more specific context takes priority — same principle as nested CLAUDE.md files)
- When there is no conflict, apply both: general rules from SKILL.md + project rules from skill-context
- Do NOT ignore skill-context rules even if they seem to contradict this skill's defaults —
they exist because the project's experience proved the default insufficient
- **CRITICAL:** skill-context rules apply to ALL outputs of this skill — including the
ARCHITECTURE.md template. The template in this SKILL.md is a **base structure**. If a skill-context
rule says "architecture doc MUST include X" or "MUST cover section Y" — you MUST augment the
template accordingly. Generating ARCHITECTURE.md that violates skill-context rules is a bug.
**Enforcement:** After generating any output artifact, verify it against all skill-context rules.
If any rule is violated — fix the output before presenting it to the user.
Generate the resolved architecture artifact (default `.ai-factory/ARCHITECTURE.md`; `paths.architecture` overrides) with architecture decisions tailored to the project.
## Workflow
Execute the steps below in order. Do not write the architecture artifact or update companion files until all required decisions are resolved.
`BLOCKED` is a terminal result for all dependent work: stop before Step 7, do not write the architecture artifact or companion files, and report (a) the exact missing decision or evidence, (b) why it is required, and (c) the valid choices or evidence needed to continue. Do not replace a blocked decision with a default or assumption. Read-only work that does not depend on the missing item may continue only when it can materially help explain the block.
### Step 0: Load configuration and project context
1. Read `.ai-factory/config.yaml` if it exists; if unreadable or invalid YAML (or if root/`paths`/`language` is not a mapping, or present path/language keys are not non-empty strings), return `BLOCKED` without falling back to defaults.
2. Resolve only these keys (do not read or write unrelated keys):
- `paths.description` — default `.ai-factory/DESCRIPTION.md`
- `paths.architecture` — default `.ai-factory/ARCHITECTURE.md`
- `language.ui` — default `en` (questions and reports)
- `language.artifacts` — default `en` (generated/updated Markdown artifacts)
If invoked by `/aif`, reuse the configuration written for that run without re-asking language choices.
3. Validate resolved paths: require project-relative paths (reject absolute paths, `..` escapes, env vars, and `~`), verify any symlink component stays inside the project root, and return `BLOCKED` on unverified symlinks or path collisions: the resolved architecture path must differ from the resolved DESCRIPTION path, and neither may resolve to root `AGENTS.md` (compare normalized paths and verified canonical destinations using host comparison semantics). If the resolved architecture path exists and is not a regular file, return `BLOCKED`.
4. Read the resolved DESCRIPTION file if it exists (if unreadable, return `BLOCKED` with its path) and extract project purpose/type, languages, frameworks, databases/ORMs, deployment model, stated team size/scale, and domain/operational constraints.
5. Ensure context establishes what is built, the principal stack, and material constraints (team size/scale are supporting only; do not invent them):
- If insufficient in interactive mode, combine any conversation details and ask one focused question at a time via `AskUserQuestion` (purpose/type → stack → constraints; team size/scale only if needed).
- In non-interactive mode, return `BLOCKED` with the specific missing context.
### Step 1: Load architecture references
Read `references/INDEX.md` in full before evaluating or generating architecture. It is the authoritative source for:
- the architecture decision matrix and selection heuristics;
- canonical pattern and variant names;
- shared terminology and action organization styles;
- naming/casing flexibility and channel handling.
In this step, read the stack-relevant sections of `references/STACK-BLUEPRINTS.md`. Do not yet read a pattern-specific reference: the pattern and variant are resolved in Steps 3-4.
Immediately after Step 4 has resolved the pattern and variant, and before Step 5 begins, read exactly one corresponding pattern reference in full:
- Layered Architecture → `references/LAYERED.md`
- Structured Modules → `references/STRUCTURED-MODULES.md`
- Explicit Architecture → `references/EXPLICIT-ARCHITECTURE.md`
- Microservices → `references/MICROSERVICES.md`
At that same point, read the sections of `references/DOMAIN-MODELING.md` relevant to the resolved stack, pattern, and variant. Read `references/PERSISTENCE-AND-ORM.md` when the project uses a database/ORM or persistence boundaries materially affect the design. Read `references/MIGRATIONS.md` only when migration guidance is needed to explain how existing code should evolve. Do not read other pattern references unless the user explicitly requests a comparison.
If a required reference is missing or unreadable, stop before generating the artifact and report its path. Do not replace reference requirements with guesses.
### Step 2: Survey and classify the codebase
Perform a bounded, read-only survey using `Glob` for file-path discovery and `Read` on representative files. Exclude dependency, cache, vendor, and build directories according to repository conventions and `.gitignore` (for example `node_modules`, `vendor`, `target`, `dist`). Do not create, edit, or delete files during this survey.
Classify the project as exactly one of:
- **Greenfield:** no application source code or framework-generated app scaffolding exists yet (only repository metadata, documentation, manifests, or configuration).
- **Existing codebase:** at least one application source file exists, including framework-generated starter scaffolding (generated entry points, layouts, starter auth, controllers, models, routes, or utilities) as well as custom domain behavior (domain models, business services, business rules, or domain routes). Preserve existing files and evaluate their structural alignment.
Build a concise structural inventory of the codebase:
- Technical-layer roots and feature/module/context roots (`src/`, `app/`, etc.);
- Delivery folders, routes, entry points, and controllers;
- Domain, persistence, and service locations;
- Per-feature subfolders versus unified multi-action files.
Retain representative file paths supporting each finding. Do not treat absent canonical folders as structural conflicts.
### Decision precedence used by Steps 3-6
Apply these sources in descending order of authority:
1. Explicit, valid choices supplied in the current skill invocation, including its arguments and accompanying user message.
2. Explicit choices or clarifications supplied by the user later during this same architecture run.
3. Project-specific rules from skill-context (`aif-architecture/SKILL.md` > `global-skill-context.md`).
4. The workflow's detection rules applied to repository evidence.
5. Declared defaults in this skill and its references.
Do not reuse choices from earlier, separate architecture runs unless the user explicitly repeats them in the current run. Within the same priority level, use the latest unambiguous explicit user instruction in the current run; if chronology does not resolve conflicting explicit choices, ask one focused question via `AskUserQuestion` in interactive mode or return `BLOCKED` in non-interactive mode. A lower-priority source never overrides a higher-priority choice, configuration values are authoritative only for the keys explicitly resolved in Step 0 (they never select a pattern, variant, style, or alignment policy on their own), and a default, recommendation, or preselected option is not approval.
### Step 3: Resolve the architecture pattern
Resolve the base pattern before resolving its variant, alignment policy, or action organization style.
#### 3.1 Parse invocation arguments
Parse the complete invocation once (case-sensitive):
1. Parse `--style=VALUE` (`subfolders|unified`) and `--policy=VALUE` (`adapt|strict`) anywhere in the invocation. For repeated options, keep the last valid occurrence and report any override; invalid values or unsupported/malformed `--` flags are reported and ignored without treating them as positional tokens.
2. Parse remaining positional tokens (if any) strictly against the table below:
- When at least one positional token is present, the first must be a recognized pattern token; if unrecognized, return `BLOCKED` and request a valid pattern token (do not fall back to auto-recommendation).
- If the first token resolves only a base pattern (`structured`, `explicit`, `microservices`), only the immediately following positional token may resolve a variant, and only one valid for that pattern per the table below (`structured layers|vertical`, `explicit layers|vertical|flat`, `microservices single|monorepo`).
- Any extra or mismatched positional token is reported as unrecognized and ignored.
3. Unambiguous natural-language choices in the current run also count as explicit choices; if wording is ambiguous, clarify via `AskUserQuestion` (or return `BLOCKED` in non-interactive mode). (`clean`, `ddd`, and `monolith` select no variant; `clean` does not imply Greenfield.)
| Token | Resolved pattern | Variant resolved by token |
|---|---|---|
| `layers` | Layered Architecture | None |
| `structured` | Structured Modules | None |
| `explicit` | Explicit Architecture | None |
| `microservices` | Microservices | None |
| `clean`, `ddd` | Explicit Architecture (legacy aliases) | None |
| `monolith` | Structured Modules (legacy alias) | None |
| `vertical` | Explicit Architecture | Vertical Slice By Entity |
| `structured-layers` | Structured Modules | Technical Layers |
| `structured-vertical` | Structured Modules | Vertical Slices By Entity |
| `explicit-layers` | Explicit Architecture | Architectural Layers |
| `explicit-vertical` | Explicit Architecture | Vertical Slice By Entity |
| `explicit-flat` | Explicit Architecture | Flat Vertical Slice - Simplified |
| `microservices-single` | Microservices | Single Service Repository |
| `microservices-monorepo` | Microservices | Monorepo |
If an explicit pattern choice is present, use it and skip automatic recommendation; otherwise evaluate the project via `references/INDEX.md`.
#### 3.2 Evaluate when no pattern was specified
Use the project's actual evidence, not keyword matching alone. Consider team size, domain complexity, expected lifecycle, scaling and deployment needs, technology stack, and the codebase survey.
Use the INDEX decision matrix and two-phase decision algorithm as the primary guide:
- **Microservices** only when independent service boundaries are justified by multiple strong signals, such as autonomous teams, independent deployment, distinct scaling needs, or polyglot persistence. Do not recommend them solely because the project uses Docker, Kubernetes, or a message broker.
- **Explicit Architecture** when strict isolation of complex domain rules from frameworks and persistence is a real requirement, not merely a preference for DDD terminology.
- **Structured Modules** for a growing multi-feature application that benefits from cohesive module boundaries without the full cost of explicit ports and adapters.
- **Layered Architecture** for a small, straightforward CRUD application where minimizing initial complexity is more valuable than strong module boundaries.
Interactive mode, when no explicit pattern choice was supplied: present one recommendation with evidence-based reasons and the meaningful alternatives, and ask the user via `AskUserQuestion` to choose exactly one of the four base patterns (Layered Architecture, Structured Modules, Explicit Architecture, Microservices). Do not include structural variants in this question and do not collapse the pattern and variant choices into a single prompt. Wait for the user's pattern selection before resolving any structural variant in Step 4. Do not continue until a valid choice is received.
Non-interactive mode, when no explicit pattern choice was supplied: return `BLOCKED` for both Greenfield and Existing codebases. Include the evidence-based recommendation, meaningful alternatives, and accepted pattern tokens. The base pattern is a required architecture decision, not an optional preference; do not select it on the user's behalf.
A valid user-provided pattern is an explicit choice; do not replace it with the recommendation. If the chosen pattern appears unsuitable, explain the evidence-based trade-off in the report but continue with the requested pattern. An invalid or unrecognized pattern token is not a valid user choice.
### Step 4: Resolve the structural variant
Layered Architecture has no structural variant. Skip this step for Layered.
In interactive mode, resolve the variant only as a separate follow-up question after the base pattern has been selected in Step 3. Never combine the base pattern choice and the structural variant choice into a single question.
The available variants are:
| Pattern | Variant | Canonical token |
|---|---|---|
| Structured Modules | Technical Layers | `structured-layers` |
| Structured Modules | Vertical Slices By Entity | `structured-vertical` |
| Explicit Architecture | Architectural Layers | `explicit-layers` |
| Explicit Architecture | Vertical Slice By Entity | `explicit-vertical` |
| Explicit Architecture | Flat Vertical Slice - Simplified | `explicit-flat` |
| Microservices | Single Service Repository | `microservices-single` |
| Microservices | Monorepo | `microservices-monorepo` |
Resolve the variant using this precedence:
1. An unambiguous explicit variant choice made by the user in the current run, either as a recognized positional token or in natural language.
2. A valid immediately-following variant token parsed under Step 3.1.
3. For an Existing codebase, an unambiguous variant demonstrated by the structural inventory.
4. The canonical default for a Greenfield project:
- Structured Modules → Technical Layers.
- Explicit Architecture → Architectural Layers.
- Microservices → Single Service Repository.
For an Existing codebase with an unambiguous detected variant and no explicit variant:
- Interactive mode: show the evidence and ask via `AskUserQuestion` whether to retain the detected variant or choose another valid variant. The detected variant is the preselected recommendation, not user approval; wait for an answer.
- Non-interactive mode: return `BLOCKED` with the detected variant, its evidence, and the alternatives. Detection does not authorize a material architecture choice.
For an Existing codebase with no explicit or unambiguous detected variant:
- Interactive mode: ask the user via `AskUserQuestion` to choose from the variants available for the resolved pattern.
- Non-interactive mode: return `BLOCKED` with those options and the canonical tokens that resolve them.
For a Greenfield project with no explicit variant:
- Interactive mode: present the canonical default as the recommendation, explain briefly why it is the default, and ask the user via `AskUserQuestion` to confirm it or choose another available variant.
- Non-interactive mode: return `BLOCKED` with the canonical default, the available alternatives, and their canonical tokens. A structural variant is a material architecture decision, not an optional preference.
Detection rules for Existing codebases:
- **Microservices:** one independently deployable service root indicates Single Service Repository; multiple independently deployable service roots in one repository indicate Monorepo. A directory containing several modules is not, by itself, evidence of multiple services.
- **Structured Modules:** per-entity slice folders indicate Vertical Slices By Entity. If there are no per-entity slices but there are role-named technical-layer folders, detect Technical Layers. Otherwise, mark the variant ambiguous.
- **Explicit Architecture:** per-entity slices containing `Application`, `Infrastructure`, or `Presentation` role folders indicate Vertical Slice By Entity. Per-entity slices without those nested layer folders indicate Flat Vertical Slice - Simplified. If there are no per-entity slices but there are architectural ring/layer folders, detect Architectural Layers. If slices disagree, mark the variant ambiguous.
An explicit variant always wins over detection. Report any mismatch between the requested variant and the observed structure without asking to reconfirm or rewriting the user's choice.
### Step 5: Resolve the alignment policy
This step applies only to Existing codebases; for Greenfield projects, skip it and report any Adapt/Strict choice or `--policy` flag as an ignored no-op.
Compare the surveyed structure against the canonical structure and dependency rules in the selected pattern reference. A discrepancy exists only when observed code (including framework starter scaffolding) violates architectural placement or dependency direction (e.g., domain logic or DB queries in routes/pages, ORM-coupled starter models where pure domain is required, inward infrastructure imports, or cross-module private imports). Missing canonical folders, pure bootstrap/layout/config files, stack-idiomatic casing/synonyms, and local code quality issues are **not** discrepancies.
1. **No discrepancies — conforming:** Set the alignment policy to `Strict (already conforming)`. Report any Adapt/Strict choice or `--policy` flag as an ignored no-op, do not prompt, and omit Adapt or legacy-quarantine sections.
2. **One or more discrepancies:** Use an explicit choice (`--policy=adapt` → Adapt, `--policy=strict` → Strict, or unambiguous natural language). Otherwise:
- Interactive mode: ask the user via `AskUserQuestion` to choose:
1. **Adapt** — adapt guidelines to the **actual existing project structure** (real folder tree, pragmatic boundaries, and `Current-State Deviations` without structural rewrites).
2. **Strict** — enforce the **pure canonical target architecture** (canonical target tree, logical legacy quarantine without moving files, adapter/facade isolation, and migration map).
- Non-interactive mode: return `BLOCKED` with the detected discrepancies and both policy options.
### Step 6: Resolve action organization style
Layered Architecture has no style choice (always unified per-entity files); skip this step for Layered and report any Style 1/Style 2 choice or `--style` flag as an ignored no-op.
For all other patterns, apply one style consistently (across the whole tree under Greenfield/Strict, and for new features/slices under Adapt):
- **Style 1 — Feature Subfolders:** each use case has its own `[FeatureName]/` folder in every layer it touches with its DTO inside; shared assets live in `_Shared/` per `references/INDEX.md` with no lateral imports between sibling feature folders.
- **Style 2 — Unified Multi-Action:** per-entity Controller/Service files with related DTOs placed next to the service, per the selected pattern reference.
1. `--style=subfolders` or unambiguous Style 1 choice selects Style 1; `--style=unified` or unambiguous Style 2 choice selects Style 2.
2. When no valid explicit style was supplied (neither in arguments nor in natural language):
- Interactive mode: if the codebase clearly demonstrates one style, show that evidence and ask via `AskUserQuestion` whether to keep it or switch; otherwise present Style 1 (Feature Subfolders) and Style 2 (Unified Multi-Action) via `AskUserQuestion` and require an explicit selection.
- Non-interactive mode: return `BLOCKED` with the two style options (`--style=subfolders` for Style 1 — Feature Subfolders, and `--style=unified` for Style 2 — Unified Multi-Action), including any clearly detected style and its evidence.
If an explicit style conflicts with the detected style, the explicit choice wins and the mismatch is reported. Do not infer Style 1 merely from entity-named folders (require use-case subfolders across layers), or Style 2 from a single file.
### Step 7: Generate ARCHITECTURE.md
Do not start this step if any required decision remains unresolved.
Generate the resolved architecture artifact (default: `.ai-factory/ARCHITECTURE.md`; `paths.architecture` overrides) adapted to the project's tech stack and language.
First generate and validate the complete artifact in `language.artifacts` without modifying the filesystem. Only after validation passes, create the parent directory if needed using the permitted `mkdir` command, then write the artifact (overwriting directly if a file already exists at the target path). Never write a partial artifact; if generation or validation fails before the final write, leave any existing architecture artifact unchanged and do not create its parent directory.
Use this structure, adapting headings and prose to the artifact language while preserving the semantic meaning of each section:
```markdown
# Architecture: [Canonical Pattern Name]
## Overview
[Why this pattern and variant fit this project; summarize the trade-offs.]
## Decision Rationale
- **Pattern/variant:** [Canonical pattern and variant; Layered has no variant suffix.]
- **Codebase classification:** [Greenfield / Existing (conforming) / Existing (discrepancies).]
- **Project type:** [Evidence from DESCRIPTION or user-provided context.]
- **Tech stack:** [Language, framework, database/ORM where relevant.]
- **Key factor:** [Primary evidence behind the choice.]
- **Action organization:** [Style 1 or Style 2; omit for Layered.]
- **Alignment policy:** [Not applicable (Greenfield) / Strict (already conforming) / Adapt / Strict (logical legacy quarantine).]
## Folder Structure
[Under Greenfield or Strict: stack-idiomatic canonical target folder tree (under Strict with discrepancies, list/annotate frozen legacy paths separately). Under Adapt: existing project folder tree adapted with incremental placement for new code.]
## Dependency Rules
[Allowed and forbidden dependency directions: canonical strict rules for Greenfield/Strict (plus legacy interoperability boundaries under Strict), or pragmatic existing-layout boundaries under Adapt.]
## Layer/Module Communication
[How modules, layers, services, and adapters communicate — via canonical boundaries under Greenfield/Strict, or existing interfaces/services under Adapt.]
## Key Principles
[Practical rules for day-to-day development.]
[Include the applicable policy content only:
- Greenfield project: Code Organization Policy.
- Existing with discrepancies + Adapt: Code Organization Note and Current-State Deviations.
- Existing with discrepancies + Strict: Legacy vs New Code Policy.
- Existing and conforming: omit any additional alignment-policy section.]
## Code Examples
[At least two examples in the project's language/framework. Under Adapt, write examples against the actual existing folders, classes, and framework conventions. Under Greenfield or Strict, write examples against the canonical target layout (and under Strict with discrepancies, show isolating legacy code behind an adapter/facade when applicable).]
## Anti-Patterns
[Concrete anti-patterns for the selected architecture.]
```
Generation rules:
1. Use the exact resolved pattern, variant, style, and alignment policy. Follow the selected pattern reference and `references/INDEX.md` for canonical layout, domain/model placement, `[Channel]` folders, and `_Shared/` scoping. Under Greenfield or Strict, do not combine trees from different variants; under Adapt, preserve existing repository roots and apply the selected style for newly added features/slices while keeping existing roots intact.
2. Adapt every code example to the project's actual language, framework, imports, naming, and stack-idiomatic casing (never copy examples from another language verbatim).
3. Under Adapt, base `Folder Structure`, `Dependency Rules`, `Layer/Module Communication`, and `Code Examples` on the actual existing codebase; list boundary violations separately in `Current-State Deviations` and never present broken dependencies as allowed rules.
4. Under Strict with discrepancies, keep `Folder Structure`, `Dependency Rules`, and `Code Examples` strictly canonical and include the `Legacy vs New Code Policy` sections below.
5. Include only rules supported by the selected references and project evidence (mark assumptions explicitly), keep guidance actionable, and enforce all `skill-context` rules per `Shared project skill-context`.
#### Required policy-section content
**Greenfield project — Code Organization Policy**
- Keep future framework entry points, layouts, and bootstrap files in the presentation/bootstrap layer.
- Do not place domain entities, business rules, or direct database access in generic entry points, page components, or framework route handlers.
- New code must follow the target architecture documented in this artifact.
**Existing with discrepancies — Adapt**
- **Code Organization Note:** document the existing structure as the active baseline without requiring unrelated rewrites; place new code cleanly within existing roots and follow target boundaries where practical.
- **Interoperability & Incremental Alignment:** when touching existing code or calling legacy modules, prefer clean service/interface boundaries without forcing a structural rewrite purely for alignment.
- **Current-State Deviations:** list each material observed deviation (for example, business rules or direct DB queries inside controllers/routes) with its actual path/evidence and explain the boundary risk and the quickest pragmatic fix. Do not call a deviation an approved exception unless the user explicitly approved it.
**Existing with discrepancies — Strict**
- **Target Architecture:** canonical architecture designed purely according to the chosen pattern without compromising for existing legacy files.
- **New Features:** follow the canonical target architecture strictly.
- **Logical Legacy Quarantine:** explicitly list the non-conforming existing paths/areas and mark them as frozen legacy boundaries without physical file relocation. Do not move or rename existing files automatically; the user decides whether to physically move legacy code into a dedicated quarantine folder or refactor it to the new architecture.
- **Legacy Isolation & Interoperability:** when new code must interact with frozen legacy code, isolate the call behind adapters, ports, or facades so legacy types and coupling never leak into new domain/application code.
- **Migration Instructions:** provide a concrete file migration mapping (`existing path -> target path`) and identify required namespace, framework configuration (e.g. auth/provider configs), and binding updates needed to complete the migration.
- **Immediate Alignment Path & Opportunistic Migration:** provide a concise ordered checklist of immediate actions if the user wants to align the app right away (for example: create target directory/layer roots, move/re-register framework delivery and wiring files such as middleware/CLI/providers, extract business logic from legacy controllers/models per the migration mapping, and remove empty legacy directories once verified); otherwise migrate legacy code opportunistically when planned tasks touch that area without refactoring unrelated code automatically.
### Step 8: Update companion pointers
Run this step only after Step 7 has completed successfully. If a companion file does not exist, do not create it.
#### 8.1 DESCRIPTION.md
If the resolved DESCRIPTION file exists, add or update the architecture-pointer section in resolved `language.artifacts`. Use the resolved architecture path from config, not the default path literal.
```markdown
## [Localized heading: Architecture]
[Localized sentence in resolved artifacts language referencing the resolved architecture artifact path for detailed architecture guidelines.]
[Localized label: Pattern]: [canonical pattern-variant name]
```
If an architecture section already exists, update it in-place; otherwise, append it to the document.
#### 8.2 AGENTS.md
If root `AGENTS.md` exists, register the architecture guidelines in the "AI Context Files" table in resolved `language.artifacts`:
```markdown
| [resolved-architecture-path] | [Localized architecture artifact description in resolved artifacts language] |
```
If a row already points to the resolved path, leave it unchanged. If an existing row references the default path, update it to the resolved path. If no architecture row exists, add it to the table.
### Step 9: Validate and report
Before reporting success, verify the written files exist and match this checklist:
- [ ] Artifact written to resolved `paths.architecture` (no collision with DESCRIPTION.md or root `AGENTS.md`), matching the resolved pattern, variant, style, stack idioms, and `skill-context` rules.
- [ ] Alignment-policy sections match project state: Greenfield → `Code Organization Policy`; Conforming existing → none; Discrepancies + Adapt → existing layout/boundaries + separate `Current-State Deviations`; Discrepancies + Strict → canonical layout + logical quarantine (no moved files) + interoperability adapters + migration map and immediate alignment steps.
- [ ] Companion pointers (`DESCRIPTION.md`, root `AGENTS.md`) updated only after the artifact write succeeded, using resolved paths and `language.artifacts`.
If any check fails, fix it before presenting success; if a write fails, inspect the actual path before reporting its state and never claim unverified checks.
Present the final report in resolved `language.ui`:
```text
[Localized success heading in `language.ui`]
[Localized pattern label in `language.ui`]: [canonical pattern-variant name]
[Localized style label in `language.ui`]: [resolved action organization style; omit for Layered]
[Localized policy label in `language.ui`]: [resolved alignment policy: Not applicable (Greenfield) / Strict (already conforming) / Adapt / Strict]
[Localized file label in `language.ui`]: [resolved architecture path]
[Localized assumptions heading in `language.ui`]:
- [Detected defaults, unrecognized arguments/flags, mismatches, or no-op flags.]
- [Omit this section when there is nothing to report.]
[Localized updated-files heading in `language.ui`]:
- [Each file actually updated; omit if none.]
[Localized key-rules heading in `language.ui`]:
- [Three concise project-specific architectural rules.]
[Localized architectural-discrepancies / legacy-guidance heading in `language.ui`]:
- [If Strict with legacy discrepancies:
- Name the concrete quarantined existing paths/folders and state clearly that they remain frozen in place (logical quarantine only — no files were moved or renamed).
- Explain how to work safely alongside legacy right away: write new features strictly in the target structure and isolate any calls to frozen legacy paths behind adapters/ports.
- List 2–3 concrete immediate actions from the migration instructions in the architecture artifact if the user wants to bring the existing app into alignment right now (such as moving/re-registering framework delivery/wiring files, refactoring priority legacy controllers/models using `existing path -> target path`, and removing empty legacy paths after verification).]
- [If Adapt with deviations:
- Name the concrete existing paths/files with boundary deviations (documented in Current-State Deviations) and summarize each boundary issue briefly.
- State 1–2 concrete immediate improvements that resolve the main boundary leaks without rewriting the existing codebase (for example, moving inline transactions or DB queries out of a controller into a dedicated handler/service).]
- [Omit this section entirely if the codebase is greenfield or conforming with zero discrepancies.]
[Localized closing sentence in `language.ui` about workflow skills following these architecture guidelines.]
```
## Artifact Ownership
- **Primary ownership:** the resolved architecture artifact path (default: `.ai-factory/ARCHITECTURE.md`).
- **Respect config overrides:** write to the resolved architecture path from `config.yaml` when provided.
- **Allowed companion updates:** architecture pointer in the resolved DESCRIPTION path from `config.yaml`, architecture row in `AGENTS.md` context table.
- **Read-only context:** roadmap, rules, research, plans, source code, and other project artifacts unless the user explicitly requests additional changes.
- Never modify built-in skill files or architecture references as part of a normal `/aif-architecture` run.
---