Reverse-engineer architecture from an existing codebase to create ADRs documenting discovered decisions. Use when bootstrapping architecture documentation for brownfield projects.
npx skills add https://github.com/tikalk/adlc-team-skills --skill architect-init
Reverse-engineer architecture from an existing codebase (brownfield) to create Architecture Decision Records (ADRs) documenting discovered decisions, then validate the findings by running /architect-clarify manually.
You act as an Architecture Archaeologist uncovering implicit architectural decisions from code by scanning the codebase for technology choices and patterns, inferring architectural decisions from code structure, documenting discovered patterns as ADRs, and identifying gaps where decisions are unclear.
Output:
{REPO_ROOT}/.adlc/drafts/adr/ADR-{NNN}.md (individual file format){REPO_ROOT}/.adlc/drafts/adr/adr.md/architect-clarify to validate discovered decisionsKey Difference from /architect-specify:
/architect-init (this skill) = Discovers what's already implemented in code/architect-specify = Explores new possibilities for greenfield projectsThis skill focuses on current state analysis - what IS, not what SHOULD BE.
/architect-specify for new projectsAD.md exists, use /architect-clarify to refine$ARGUMENTS
You MUST consider the user input before proceeding (if not empty).
Examples of User Input:
"Django monolith with PostgreSQL, React frontend, AWS deployment""Node.js microservices with MongoDB and RabbitMQ""Legacy Java application, focus on understanding data layer"When users provide context, use it to focus the reverse-engineering effort.
--adr-heuristic HEURISTIC: ADR generation strategysurprising (default): Skip obvious ecosystem defaults, document only surprising/risky decisionsall: Document all discovered decisionsminimal: Only high-risk decisions--no-decompose: Disable automatic sub-system detection from code structure (default: auto-detect if multiple modules detected)You are acting as an Architecture Archaeologist uncovering implicit architectural decisions from code. Your role involves:
| Scenario | Command | Input | Output |
|----------|---------|-------|--------|
| Brownfield (existing code) | /architect-init | Codebase scan | Inferred ADRs |
| Greenfield (new project) | /architect-specify | PRD/requirements | Discussed ADRs |
When discovering ADRs from brownfield code, map findings to R&W viewpoints:
| Discovery Area | Primary Viewpoint | What to Look For |
|---------------|-------------------|------------------|
| Service structure | Functional | Component boundaries, responsibilities |
| Database schemas | Information | Data entities, relationships |
| Process/thread code | Concurrency | Runtime units, coordination |
| Directory structure | Development | Module organization, dependencies |
| Deployment configs | Deployment | Infrastructure, environments |
| Monitoring/alerting | Operational | Operations support |
Functional-as-Cornerstone for Brownfield:
Even in brownfield discovery, the Functional structure is foundational:
Priority order for ADR discovery:
{REPO_ROOT}/.adlc/drafts/adr/ADR-{NNN}.md (NO AD.md creation)adr.md index/architect-clarify to validate brownfield findingsObjective: Identify sub-systems from existing code structure automatically
When: This phase runs automatically when the codebase is detected as having multiple distinct modules/packages. Use --no-decompose to skip.
Detection Source Reconciliation (CRITICAL):
The setup script may report "No distinct sub-systems detected from directory structure" while your AI analysis identifies sub-systems through code patterns (import relationships, technology boundaries, domain logic). When this occurs:
Analyze the codebase for distinct sub-systems based on directory structure:
| Pattern | Likely Sub-System |
|---------|------------------|
| src/auth/ | Authentication sub-system |
| src/users/ | User management sub-system |
| services/payment/ | Payment sub-system |
| modules/inventory/ | Inventory sub-system |
| apps/api/, apps/web/ | Monorepo with separate apps |
| lib/core/, lib/shared/ | Shared libraries (not a sub-system) |
Detect sub-systems from package/module structures:
| Pattern | Detection Method | Sub-System Evidence |
|---------|------------------|-------------------|
| Node.js workspaces | package.json workspaces | Multiple packages = multiple sub-systems |
| Python namespaces | __init__.py hierarchy | Multiple top-level packages |
| Go modules | go.mod + directories | Multiple directories under cmd/ |
| Maven/Gradle | pom.xml modules | Multiple modules in multi-module project |
| Docker services | docker-compose services | Each service = sub-system |
If database is accessible, detect sub-systems from schema:
| Pattern | Evidence |
|---------|----------|
| Table prefixes | auth_, user_, payment_ tables = separate domains |
| PostgreSQL schemas | auth., payments. schema separation |
| Separate databases | Multiple databases in docker-compose |
Present detected sub-systems to user for confirmation:
## Detected Sub-Systems
I've identified the following sub-systems from your codebase:
| # | Sub-System | Detection Method | Evidence |
|---|------------|-----------------|----------|
| 1 | **auth** | Directory + Module | src/auth/, auth/ package |
| 2 | **users** | Directory | src/users/, services/user/ |
| 3 | **payments** | Directory + Docker | services/payment/, payment service in docker-compose |
| 4 | **inventory** | Directory | src/inventory/, modules/stock/ |
### Questions for Confirmation:
1. **Are these sub-systems correct?** [Y/n]
2. **Should any sub-systems be merged?** (e.g., auth + users → identity)
3. **Should any sub-systems be split?** (e.g., payments → billing + subscriptions)
4. **Any missing sub-systems?** (e.g., analytics, reporting)
**Reply** with:
- `Y` to confirm and proceed
- `n` to disable decomposition (generate monolithic ADRs)
- Specific changes (e.g., "merge 1+2", "split 3", "add Notifications")
CRITICAL: If you have identified ANY sub-systems through ANY method (script detection, AI analysis of code patterns, or user input), you MUST execute this step.
Failure to follow this step invalidates the entire ADR discovery process.
Based on user response:
| Response | Action |
|----------|--------|
| Y / Enter | Proceed with detected sub-systems |
| n | Skip decomposition, generate monolithic ADRs |
| Modifications | Adjust sub-systems, then proceed |
| Empty/Default | Auto-proceed if ≤3 sub-systems, ask if >3 |
Threshold Logic Enforcement (MANDATORY - applies to ALL detected sub-systems, regardless of source):
| Sub-System Count | Required Action | Can Skip User Confirmation? |
|-----------------|-----------------|---------------------------|
| 0 | Proceed as monolithic (no decomposition) | Yes |
| 1-3 | Show summary, auto-approve allowed | Yes |
| 4-6 | MUST show summary and ask user confirmation | NO |
| >6 | MUST suggest grouping and MUST ask confirmation | NO |
Enforcement Rules:
After confirmation, output structured sub-system data:
{
"decomposition": "enabled",
"subsystems": [
{"id": "auth", "name": "Auth", "detection_method": "directory", "evidence": "src/auth/"},
{"id": "users", "name": "Users", "detection_method": "directory", "evidence": "src/users/"},
{"id": "payments", "name": "Payments", "detection_method": "docker", "evidence": "payment service in docker-compose"}
],
"next_phase": "Codebase Analysis (per sub-system)"
}
If decomposition disabled:
{
"decomposition": "disabled",
"reason": "user_requested",
"next_phase": "Codebase Analysis (monolithic)"
}
Objective: Discover what technologies and patterns are in use
Note: If sub-system decomposition is enabled (Phase 0), analyze each sub-system separately to provide focused insights.
scripts/bash/setup-architect.sh to initialize architecture files--no-decompose if decomposition was disabled| Indicator | Technology Category | Files to Check |
|-----------|---------------------|----------------|
| package.json | Node.js ecosystem | Dependencies, scripts |
| requirements.txt / pyproject.toml | Python ecosystem | Dependencies |
| pom.xml / build.gradle | JVM ecosystem | Dependencies |
| Cargo.toml | Rust | Dependencies |
| go.mod | Go | Dependencies |
| Dockerfile | Containerization | Base images, stages |
| docker-compose.yml | Container orchestration | Services, networks |
| *.tf / *.tfvars | Terraform/IaC | Infrastructure |
| kubernetes/*.yaml | Kubernetes | Deployment configs |
| .github/workflows/* | GitHub Actions | CI/CD |
| Pattern | Framework | Evidence |
|---------|-----------|----------|
| from django imports | Django | Python web |
| @SpringBoot | Spring Boot | Java web |
| import express | Express.js | Node.js web |
| import { Component } | React/Angular/Vue | Frontend |
| from fastapi | FastAPI | Python API |
| Evidence | Database Type |
|----------|---------------|
| PostgreSQL connection strings | PostgreSQL |
| MongoDB/mongoose imports | MongoDB |
| Redis client imports | Redis cache |
| ORM migrations | Relational DB |
| DynamoDB SDK usage | AWS DynamoDB |
Objective: Identify architectural patterns from code structure
| Pattern | Evidence | ADR Topic |
|---------|----------|-----------|
| Monolith | Single deployable, shared database | ADR: System Architecture Style |
| Microservices | Multiple services, service discovery | ADR: System Architecture Style |
| Modular Monolith | Single deploy, module boundaries | ADR: System Architecture Style |
| Event-Driven | Message queue usage, event handlers | ADR: Communication Pattern |
| Serverless | Lambda functions, managed services | ADR: Deployment Model |
| Pattern | Evidence |
|---------|----------|
| Layered | controllers/, services/, repositories/ |
| Feature-Based | features/, modules/ per domain |
| Clean Architecture | domain/, application/, infrastructure/ |
| Hexagonal | ports/, adapters/ |
| Pattern | Evidence |
|---------|----------|
| REST | Route decorators, HTTP verbs, resource URLs |
| GraphQL | Schema files, resolvers, gql imports |
| gRPC | .proto files, gRPC client/server setup |
| WebSocket | Socket.io, WebSocket handlers |
Objective: Scan existing docs to avoid repeating documented information
Scan for:
AGENTS.md - Project context, overview{TEAM_AI_DIRECTIVES}/AGENTS.md - Team-wide agent usage instructions (if configured)README.md - Tech stack, project descriptionCONTRIBUTING.md - Development guidelinesAD.md or docs/architecture.md - Existing architectureLICENSE - Legal contextDeduplication Rules:
| Finding | Action |
|---------|--------|
| Tech stack in README | Reference README in ADR, don't duplicate |
| Architecture exists | Auto-merge or offer update vs. create new |
| Guidelines in CONTRIBUTING | Reference in Development View |
| Context in AGENTS.md | Link from Context View |
| Team directives AGENTS.md | Reference for team-wide agent instructions |
Process:
scripts/bash/setup-architect.sh which calls scan_existing_docs()Objective: Document discovered decisions as ADRs
For each discovered architectural decision:
templates/adr-template.md):---
status: discovered # inferred from codebase (brownfield)
date: YYYY-MM-DD
decision-makers: [Legacy/Inferred]
consulted: []
informed: []
sub-system: System
---
# {Discovered Decision}
## Context and Problem Statement
[Inferred problem statement based on code patterns]
**Evidence Found**:
* [File/pattern evidence 1]
* [File/pattern evidence 2]
## Decision Drivers
* {inferred driver 1}
* {inferred driver 2}
## Considered Options
* {Likely Alternative}
* {Discovered choice}
## Decision Outcome
Chosen option: "{Discovered choice}", because {inferred rationale from implementation}.
### Consequences
* Good, because {benefit visible in codebase}
* Bad, because {trade-off inherent to this choice}
* Bad, because {risk if this decision is not well understood}
### Confirmation
{How compliance can be confirmed in the codebase}
## Pros and Cons of the Options
### {Likely Alternative}
* Good, because {argument}
* Bad, because {argument}
← DO NOT fabricate rejection rationale - we don't know why it wasn't chosen
## More Information
**Confidence Level**: [HIGH/MEDIUM/LOW] - [Explanation of confidence in inference]
Skip if obvious (heuristic: surprising):
Document as ADRs:
Objective: Detect which R&W perspectives apply from codebase evidence
Scan codebase for quality requirement indicators:
| Evidence | Detected Perspective |
|----------|---------------------|
| Health checks, circuit breakers, retry logic | Availability |
| Plugin systems, feature flags, extension points | Evolution |
| GDPR/HIPAA comments, audit logging, consent tracking | Regulation |
| ARIA attributes, screen reader support | Accessibility |
| i18n files, locale handling, translation keys | Internationalization |
| Multi-region configs, geo-routing, CDN setup | Location |
| Extensive UI tests, UX research artifacts | Usability |
| Resource constraints in README, limited CI runners | Development Resource |
Present detected perspectives for confirmation:
## Quality Requirements Detected
Based on codebase analysis, the following quality perspectives may apply:
| Perspective | Evidence Found | Include? |
|-------------|----------------|----------|
| Security | Always recommended | ✓ (default) |
| Performance | Always recommended | ✓ (default) |
| Availability | Circuit breakers found | [Y/N] |
| Evolution | Feature flags found | [Y/N] |
| Regulation | GDPR comments found | [Y/N] |
| Accessibility | Not detected | [Y/N] |
| Internationalization | i18n files found | [Y/N] |
| Location | Multi-region config | [Y/N] |
| Usability | UI tests found | [Y/N] |
| Development Resource | Not detected | [Y/N] |
Please confirm which perspectives to document.
Store selected perspectives in state for /architect-implement.
Structure ADRs by sub-system in the output file:
# Architecture Decision Records
## ADR Index
| ID | Sub-System | Decision | Status | Date | Confidence |
|----|------------|----------|--------|------|------------|
| ADR-001 | System | Monolithic Architecture | Discovered | 2026-02-26 | HIGH |
| ADR-002 | Auth | JWT Authentication | Discovered | 2026-02-26 | HIGH |
| ADR-003 | Payments | Stripe Integration | Discovered | 2026-02-26 | MEDIUM |
---
## System-Level ADRs
### ADR-001: Monolithic Architecture
[Full ADR content...]
---
## Auth Sub-System ADRs
### ADR-002: JWT Authentication
[Full ADR content...]
---
## Payments Sub-System ADRs
### ADR-003: Stripe Integration
[Full ADR content...]
Objective: Identify areas where decisions are unclear
After scanning, report:
## Architecture Discovery Report
### Technologies Detected
| Category | Technology | Confidence | Evidence |
|----------|------------|------------|----------|
| Backend | Django 4.2 | HIGH | requirements.txt, app structure |
| Database | PostgreSQL | HIGH | connection strings, migrations |
| Frontend | React 18 | MEDIUM | package.json, JSX files |
| Cache | Redis | HIGH | redis imports, docker-compose |
### Documentation Deduplication
✓ README.md: Tech stack documented (lines 20-45)
→ Referenced in Context View, skipping tech stack ADRs
✓ CONTRIBUTING.md: Development workflow documented
→ Referenced in Development View 3.5
### ADRs Generated (Surprising/Risky decisions only)
| ID | Decision | Confidence | Why Documented |
|----|----------|------------|----------------|
| ADR-001 | Monolithic Django architecture | HIGH | Architecture style choice |
| ADR-002 | Custom JWT authentication | MEDIUM | Security risk, non-standard |
| ADR-003 | Microservices for small team | HIGH | Scale mismatch, surprising |
### Skipped (Covered by existing docs or obvious)
| Decision | Reason |
|----------|--------|
| PostgreSQL choice | Ecosystem default + README covers |
| React frontend | Standard framework + README covers |
| Docker containerization | Conventional choice |
### Unclear Areas (Need Human Input)
| Area | Question | Suggestion |
|------|----------|------------|
| Auth | OAuth2 or custom JWT? | Found JWT usage, need confirmation |
| Caching | Redis strategy unclear | Cache-aside pattern inferred |
| Scaling | Horizontal scaling setup? | No auto-scaling config found |
### Recommended Clarifications
1. Run `/architect-clarify` to refine ADRs with human input
2. Focus on [specific unclear area]
3. Consider documenting [undocumented pattern]
Objective: Write discovered ADRs to file (NO AD.md creation)
> CRITICAL: ADR status MUST be "Discovered" when generated by this skill.
> NEVER set status to "Accepted" directly. The approval workflow is:
> init (Discovered) → clarify (review) → clarify Phase 5.5 (Accepted) → implement
>
> If the user explicitly asks to accept ADRs during init, direct them to
> run /architect-clarify instead.
Before Writing - Check for Existing ADRs:
{REPO_ROOT}/.adlc/drafts/adr/ADR-{NNN}.md filesWrite ADRs:
{REPO_ROOT}/.adlc/drafts/adr/ADR-{NNN}.md for each discovered ADRDO NOT Create AD.md:
/architect-implementGenerate Summary:
Objective: Validate brownfield findings with user
After generating ADRs, run /architect-clarify with brownfield context to validate:
Questions Clarify Should Ask (Brownfield-Specific):
| Question Type | Example |
|---------------|---------|
| Current State Validity | "I detected microservices in docker-compose.yml - is this still your current approach?" |
| Decision Rationale | "PostgreSQL is used - was this chosen for specific requirements or inherited?" |
| Team Context | "Based on git history, team appears small - are current architecture decisions appropriate?" |
| Technical Debt | "Found custom authentication - are you considering migration to OAuth/OIDC?" |
| Migration Plans | "Legacy patterns detected in X module - any plans to modernize?" |
| Deprecated Patterns | "Monolithic deployment with hints of service separation - is microservices migration planned?" |
Context Passed to Clarify:
{
"source": "brownfield",
"tech_stack_detected": ["detected technologies"],
"inferred_decisions": ["list of ADRs with confidence levels"],
"assumptions": ["things that need validation"],
"files_analyzed": "count"
}
Run /architect-clarify to refine ADRs based on your input, then run /architect-implement to generate the full AD.md.
| Level | Criteria |
|-------|----------|
| HIGH | Multiple clear evidence sources, unambiguous choice |
| MEDIUM | Some evidence, but could be interpreted differently |
| LOW | Limited evidence, significant uncertainty |
/architect-initRequired: Run /architect-clarify to validate brownfield findings.
After clarification completes:
{REPO_ROOT}/.adlc/drafts/adr/adr.md for accuracy/architect-clarify Phase 5.5 to change status to "Accepted"/architect-implement: Generate full AD.md from Accepted ADRs/architect-init "Node.js API, team of 2"
↓
[Scan codebase] → Detect technologies, patterns
↓
[Generate ADRs] → Write to {REPO_ROOT}/.adlc/drafts/adr/ADR-{NNN}.md (marked "Discovered")
↓
[Run /architect-clarify] → Ask to validate decisions
↓
[Clarify asks] → "Is microservices decision still valid?"
"Custom auth detected - considering OAuth?"
↓
[Approve ADRs] → Phase 5.5 to change status to "Accepted"
↓
[Run /architect-implement] → Generate AD.md from Accepted ADRs
↓
[Generate AD.md] → Full architecture description
$ARGUMENTS
After init completes, run /architect-clarify to validate the discovered ADRs and approve them for implementation.
{REPO_ROOT}/.adlc/drafts/adr/ADR-{NNN}.md with status Discovered (Inferred).adr.md index exists in {REPO_ROOT}/.adlc/drafts/adr/.Take tikalk/architect-init from the repository into ~/.claude/skills for personal
use, or into .claude/skills inside a project.
The agent identifies a skill by the name field in its header. Two skills with the
same name cannot sit side by side — one of them will be ignored.