From cb670552f90b8a31714d544b9b1bf17a9b8136a4 Mon Sep 17 00:00:00 2001 From: Nir Alfasi Date: Tue, 10 Feb 2026 18:45:56 +0200 Subject: [PATCH 1/2] feat: improve architect.init output quality with team-size calibration Architect.init generated too much boilerplate for small teams and documented obvious decisions. This adds team-size awareness (auto-detected from git history) to calibrate output depth, a surprise-value heuristic to skip trivial ADRs, and a risks/gaps analysis phase as the primary valuable output. Co-Authored-By: Claude Opus 4.6 --- scripts/bash/setup-architecture.sh | 108 +++++++++-- templates/AD-template-lean.md | 135 +++++++++++++ templates/adr-template.md | 8 +- templates/commands/architect.init.md | 274 +++++++++++++++++++-------- 4 files changed, 430 insertions(+), 95 deletions(-) create mode 100644 templates/AD-template-lean.md diff --git a/scripts/bash/setup-architecture.sh b/scripts/bash/setup-architecture.sh index 6985381a8..b09ebdf53 100755 --- a/scripts/bash/setup-architecture.sh +++ b/scripts/bash/setup-architecture.sh @@ -4,6 +4,7 @@ set -e JSON_MODE=false ACTION="" +TEAM_SIZE="" ARGS=() # Parse arguments @@ -12,11 +13,25 @@ for arg in "$@"; do --json) JSON_MODE=true ;; + --team-size=*) + TEAM_SIZE="${arg#--team-size=}" + ;; + --team-size) + # Next arg will be the value, handled below + TEAM_SIZE="__NEXT__" + ;; + small|medium|large) + if [[ "$TEAM_SIZE" == "__NEXT__" ]]; then + TEAM_SIZE="$arg" + else + ARGS+=("$arg") + fi + ;; init|map|update|review|specify|implement|clarify) ACTION="$arg" ;; --help|-h) - echo "Usage: $0 [action] [context] [--json]" + echo "Usage: $0 [action] [context] [--json] [--team-size small|medium|large]" echo "" echo "Actions:" echo " specify Interactive PRD exploration to create system ADRs (greenfield)" @@ -28,13 +43,16 @@ for arg in "$@"; do echo " review Validate architecture against constitution" echo "" echo "Options:" - echo " --json Output results in JSON format" - echo " --help Show this help message" + echo " --json Output results in JSON format" + echo " --team-size Set team size tier: small (1-3), medium (4-15), large (16+)" + echo " Auto-detected from git history if not specified" + echo " --help Show this help message" echo "" echo "Examples:" echo " $0 specify \"B2B SaaS for supply chain management\"" echo " $0 clarify \"Focus on authentication and data persistence decisions\"" echo " $0 init \"Django monolith with PostgreSQL and React\"" + echo " $0 init --team-size small" echo " $0 implement \"Generate full AD.md from ADRs\"" echo " $0 update \"Added microservices and event sourcing\"" echo " $0 review \"Focus on security and performance\"" @@ -71,6 +89,36 @@ mkdir -p "$REPO_ROOT/memory" ARCHITECTURE_FILE="$REPO_ROOT/memory/architecture.md" TEMPLATE_FILE="$REPO_ROOT/.specify/templates/architecture-template.md" +# Function to detect team size from git history +detect_team_size() { + local team_size="$TEAM_SIZE" + + # If user provided --team-size, use that + if [[ -n "$team_size" && "$team_size" != "__NEXT__" ]]; then + echo "$team_size" + return + fi + + # Auto-detect from git committer count (last 6 months) + local committer_count=1 + if command -v git &> /dev/null && [[ -d "$REPO_ROOT/.git" ]]; then + committer_count=$(git -C "$REPO_ROOT" log --since="6 months ago" --format='%aE' 2>/dev/null | sort -u | wc -l | tr -d ' ') + if [[ -z "$committer_count" || "$committer_count" -eq 0 ]]; then + committer_count=1 + fi + fi + + echo "Detected $committer_count unique committer(s) in last 6 months" >&2 + + if [[ "$committer_count" -le 3 ]]; then + echo "small" + elif [[ "$committer_count" -le 15 ]]; then + echo "medium" + else + echo "large" + fi +} + # Function to detect tech stack from codebase detect_tech_stack() { local tech_stack="" @@ -454,28 +502,54 @@ action_init() { echo "Use 'update' action to modify or delete the file to reinitialize" >&2 exit 1 fi - - if [[ ! -f "$TEMPLATE_FILE" ]]; then - echo "❌ Template not found: $TEMPLATE_FILE" >&2 + + # Detect team size and select appropriate template + local detected_size + detected_size=$(detect_team_size) + echo "📊 Team size tier: $detected_size" >&2 + + local lean_template="$REPO_ROOT/.specify/templates/AD-template-lean.md" + local selected_template="$TEMPLATE_FILE" + + if [[ "$detected_size" == "small" || "$detected_size" == "medium" ]]; then + if [[ -f "$lean_template" ]]; then + selected_template="$lean_template" + echo "Using lean architecture template (for $detected_size teams)" >&2 + else + echo "⚠️ Lean template not found, falling back to full template" >&2 + fi + else + echo "Using full Rozanski & Woods template (for large teams)" >&2 + fi + + if [[ ! -f "$selected_template" ]]; then + echo "❌ Template not found: $selected_template" >&2 exit 1 fi - + echo "📐 Initializing architecture from template..." >&2 - cp "$TEMPLATE_FILE" "$ARCHITECTURE_FILE" - - # Generate diagrams based on user config - generate_and_insert_diagrams "$ARCHITECTURE_FILE" "System" - + cp "$selected_template" "$ARCHITECTURE_FILE" + + # Generate diagrams based on user config (only for full template) + if [[ "$selected_template" == "$TEMPLATE_FILE" ]]; then + generate_and_insert_diagrams "$ARCHITECTURE_FILE" "System" + fi + echo "✅ Created: $ARCHITECTURE_FILE" >&2 echo "" >&2 echo "Next steps:" >&2 echo "1. Review and customize the architecture document" >&2 - echo "2. Fill in stakeholder concerns and system scope" >&2 - echo "3. Complete each viewpoint section with your system details" >&2 - echo "4. Run '/architect.implement' to generate full AD.md" >&2 - + echo "2. Fill in system overview and context diagram" >&2 + if [[ "$detected_size" == "small" ]]; then + echo "3. Focus on Risks & Gaps section (most valuable for small teams)" >&2 + echo "4. Run '/architect.clarify' to refine ADRs" >&2 + else + echo "3. Complete each section with your system details" >&2 + echo "4. Run '/architect.implement' to generate full AD.md" >&2 + fi + if $JSON_MODE; then - echo "{\"status\":\"success\",\"action\":\"init\",\"file\":\"$ARCHITECTURE_FILE\"}" + echo "{\"status\":\"success\",\"action\":\"init\",\"file\":\"$ARCHITECTURE_FILE\",\"team_size\":\"$detected_size\",\"template\":\"$(basename "$selected_template")\"}" fi } diff --git a/templates/AD-template-lean.md b/templates/AD-template-lean.md new file mode 100644 index 000000000..1424f1def --- /dev/null +++ b/templates/AD-template-lean.md @@ -0,0 +1,135 @@ +# Architecture Description: [SYSTEM_NAME] + +**Version**: 1.0 | **Created**: [DATE] | **Last Updated**: [DATE] +**Author**: [AUTHOR/AI] | **Status**: Draft | Review | Approved +**ADR Reference**: [memory/adr.md](memory/adr.md) + +> This is a lean architecture description for small-to-medium teams. +> For the full Rozanski & Woods template, use `AD-template.md`. + +--- + +## 1. Risks, Gaps & Recommendations + +> The most actionable section — what's missing, what could break, and what to fix first. + +### Critical (Address Soon) + +| Finding | Impact | Recommendation | +|---------|--------|----------------| +| [FINDING] | [IMPACT] | [RECOMMENDATION] | + +### Important (Plan For) + +| Finding | Impact | Recommendation | +|---------|--------|----------------| +| [FINDING] | [IMPACT] | [RECOMMENDATION] | + +### Nice to Have + +| Finding | Impact | Recommendation | +|---------|--------|----------------| +| [FINDING] | [IMPACT] | [RECOMMENDATION] | + +--- + +## 2. System Overview + +[2-3 sentences: What does this system do? Who uses it? What problem does it solve?] + +--- + +## 3. Context Diagram + +**Purpose**: The system and everything it talks to + +```mermaid +graph TD + Users["Users"] + System["[SYSTEM_NAME]"] + Database["Database"] + ExternalAPI["External APIs"] + + Users -->|Requests| System + System -->|Queries| Database + System -->|Integrates| ExternalAPI + + classDef systemNode fill:#f47721,stroke:#333,stroke-width:2px,color:#fff + classDef externalNode fill:#e0e0e0,stroke:#333,stroke-width:1px + + class System systemNode + class Users,Database,ExternalAPI externalNode +``` + +### External Dependencies + +| Dependency | Purpose | Failure Impact | +|------------|---------|----------------| +| [DEPENDENCY] | [PURPOSE] | [WHAT BREAKS] | + +--- + +## 4. Key Data Flows + +Describe the 2-3 most important paths through the system in narrative form. + +### [Flow 1 Name] (e.g., "User Authentication") + +[Source] -> [Step 1] -> [Step 2] -> [Destination] + +Brief narrative: what happens, what data moves, what can go wrong. + +### [Flow 2 Name] (e.g., "Core Business Operation") + +[Source] -> [Step 1] -> [Step 2] -> [Destination] + +Brief narrative. + +--- + +## 5. Deployment Topology + +**Purpose**: How the system runs in production + +```mermaid +graph TB + subgraph "Production" + LB["Load Balancer"] + App["Application"] + DB["Database"] + end + + Internet["Internet"] -->|HTTPS| LB + LB --> App + App --> DB +``` + +| Environment | Infrastructure | Notes | +|-------------|----------------|-------| +| Production | [e.g., AWS EC2, Docker] | [e.g., Single instance] | +| Staging | [e.g., Same as prod] | [Optional] | +| Development | [e.g., Docker Compose] | [Local dev setup] | + +--- + +## 6. Tech Stack Summary + +| Category | Technology | Notes | +|----------|------------|-------| +| Language | [e.g., TypeScript] | | +| Framework | [e.g., Next.js] | | +| Database | [e.g., PostgreSQL] | | +| ORM | [e.g., Prisma] | | +| Cloud | [e.g., AWS] | | +| CI/CD | [e.g., GitHub Actions] | | +| Monitoring | [e.g., None / Datadog] | | + +--- + +## ADR Summary + +Detailed Architecture Decision Records are maintained in [memory/adr.md](memory/adr.md). + +| ID | Decision | Confidence | +|----|----------|------------| +| ADR-001 | [Title] | [HIGH/MED/LOW] | diff --git a/templates/adr-template.md b/templates/adr-template.md index 90f1d4d88..ece9bc0b2 100644 --- a/templates/adr-template.md +++ b/templates/adr-template.md @@ -62,17 +62,17 @@ State the decision that was made. Use active voice: "We will..." or "The system - [Risk 1 with mitigation strategy] - [Risk 2 with monitoring approach] -### Alternatives Considered +### Common Alternatives #### Option A: [Alternative Name] **Description:** [Brief description] -**Rejected because:** [Reason for rejection] +**Trade-offs:** [Why this option was not chosen, or how it compares] #### Option B: [Alternative Name] **Description:** [Brief description] -**Rejected because:** [Reason for rejection] +**Trade-offs:** [Why this option was not chosen, or how it compares] ### Related ADRs @@ -90,6 +90,7 @@ State the decision that was made. Use active voice: "We will..." or "The system - **Proposed**: Decision under discussion - **Accepted**: Decision approved and in effect +- **Discovered**: Inferred from existing codebase (used by `/architect.init`) - **Deprecated**: Decision no longer applicable - **Superseded**: Replaced by newer decision (reference successor ADR) @@ -101,6 +102,7 @@ State the decision that was made. Use active voice: "We will..." or "The system - Be honest about trade-offs and risks - Link related decisions for traceability - Update status when decisions evolve +- For discovered ADRs: cite evidence, mark confidence levels, never fabricate rejection rationale **Integration with Architecture:** diff --git a/templates/commands/architect.init.md b/templates/commands/architect.init.md index 6d2767b7b..c322598b0 100644 --- a/templates/commands/architect.init.md +++ b/templates/commands/architect.init.md @@ -30,6 +30,7 @@ You **MUST** consider the user input before proceeding (if not empty). - `"Django monolith with PostgreSQL, React frontend, AWS deployment"` - `"Node.js microservices with MongoDB and RabbitMQ"` - `"Legacy Java application, focus on understanding data layer"` +- `"--team-size small"` — override auto-detected team size - Empty input: Scan entire codebase and infer architecture When users provide context, use it to focus the reverse-engineering effort. @@ -39,7 +40,7 @@ When users provide context, use it to focus the reverse-engineering effort. Reverse-engineer architecture from an existing codebase to create: 1. **ADRs** documenting inferred architectural decisions in `memory/adr.md` -2. **Architecture Description** overview in `memory/architecture.md` (legacy format) +2. **Architecture Description** overview in `memory/architecture.md` This command is for **brownfield projects** where architecture exists in code but lacks documentation. @@ -49,8 +50,8 @@ You are acting as an **Architecture Archaeologist** uncovering implicit architec - **Scanning** codebase for technology choices and patterns - **Inferring** architectural decisions from code structure -- **Documenting** discovered patterns as ADRs -- **Identifying** gaps where decisions are unclear +- **Documenting** only the decisions that add value (non-obvious, surprising, or risky) +- **Identifying** gaps, risks, and technical debt ### Brownfield vs Greenfield @@ -62,10 +63,12 @@ You are acting as an **Architecture Archaeologist** uncovering implicit architec ## Outline 1. **Codebase Scan**: Analyze project structure and detect technologies -2. **Pattern Detection**: Identify architectural patterns in use -3. **ADR Generation**: Create ADRs for discovered decisions -4. **Gap Analysis**: Identify areas where decisions are unclear -5. **Output**: Write ADRs to `memory/adr.md` +2. **Context Calibration**: Estimate team size and set output depth +3. **Existing Docs Scan**: Read existing documentation to avoid duplication +4. **Pattern Detection**: Identify architectural patterns in use +5. **ADR Generation**: Create ADRs for surprising/non-obvious decisions only +6. **Risks & Gap Analysis**: Identify what's missing, broken, or risky (most valuable output) +7. **Output**: Write ADRs to `memory/adr.md` and architecture to `memory/architecture.md` ## Execution Steps @@ -112,7 +115,55 @@ You are acting as an **Architecture Archaeologist** uncovering implicit architec | ORM migrations | Relational DB | | DynamoDB SDK usage | AWS DynamoDB | -### Phase 2: Pattern Recognition +### Phase 2: Context Calibration + +**Objective**: Determine project scale to calibrate output depth + +1. **Estimate team size** using these signals (in priority order): + - **User override**: If `--team-size small|medium|large` was passed, use that directly + - **Git history**: Count unique committers in `git log` (last 6 months) + - **Project docs**: Check for `CLAUDE.md`, `AGENTS.md`, `CONTRIBUTING.md` — team references, contributor guidelines + - **Repo indicators**: Number of active branches, PR volume + +2. **Assign tier**: + + | Tier | Team Size | Characteristics | + |------|-----------|-----------------| + | **small** | 1-3 engineers | Startup, side project, solo dev. Everyone knows the codebase. | + | **medium** | 4-15 engineers | Growing team. Some specialization, onboarding matters. | + | **large** | 16+ engineers | Multiple teams. Formal processes, compliance needs. | + +3. **Output depth per tier**: + + | Aspect | Small | Medium | Large | + |--------|-------|--------|-------| + | ADRs | Only surprising/non-obvious decisions | Key decisions + framework deviations | Comprehensive (all categories) | + | Architecture doc | Lean template (AD-template-lean.md) | Lean template + optional expanded sections | Full Rozanski & Woods (AD-template.md) | + | Gap analysis | **Primary output** — lead with this | Prominent section | Standard appendix | + | Alternatives section | Skip unless genuinely informative | Brief "Common Alternatives" | Full analysis | + +### Phase 3: Existing Documentation Scan + +**Objective**: Avoid duplicating what's already documented + +1. **Check for existing docs** at repo root and common locations: + - `CLAUDE.md`, `AGENTS.md` — AI agent instructions (often contain architecture/conventions) + - `CONTRIBUTING.md`, `README.md` — project conventions and setup + - `docs/` directory — existing documentation + - `.specify/` directory — existing spec framework artifacts + +2. **Extract already-documented information**: + - Coding conventions and style rules + - Architecture patterns (e.g., "UI -> API -> Service -> Model") + - Technology choices already explained + - Deployment and infrastructure details + +3. **Set deduplication context**: Store a summary of what's already documented. In Phase 7 (Output), you will: + - **Not repeat** conventions, patterns, or decisions already documented elsewhere + - **Add a complementary note** at the top of generated output referencing existing docs + - **Focus on gaps** — document what existing docs *don't* cover + +### Phase 4: Pattern Recognition **Objective**: Identify architectural patterns from code structure @@ -144,18 +195,31 @@ You are acting as an **Architecture Archaeologist** uncovering implicit architec | **gRPC** | `.proto` files, gRPC client/server setup | | **WebSocket** | Socket.io, WebSocket handlers | -### Phase 3: ADR Generation +### Phase 5: ADR Generation + +**Objective**: Document discovered decisions as ADRs — but only the ones that add value + +#### ADR Filtering: The Surprise-Value Heuristic + +**Generate an ADR only if at least one of these is true:** -**Objective**: Document discovered decisions as ADRs +1. **A new engineer would be surprised by this choice** — it's not what you'd expect for this type of project +2. **A reasonable person might be tempted to change it** — the decision needs context to understand why it was made +3. **The decision goes against framework/ecosystem conventions** — e.g., CSR-only in Next.js, NoSQL for relational data, monorepo without a monorepo tool -For each discovered architectural decision: +**Do NOT generate ADRs for:** -1. **Identify the Decision**: - - What technology/pattern was chosen? - - What alternatives were available when this was built? - - What forces likely drove this decision? +- Standard/default technology choices that match the ecosystem norm (e.g., "PostgreSQL for relational data", "React for frontend when package.json shows React", "Winston for Node.js logging", "Nginx as reverse proxy", "Jest for testing in a Node.js project") +- Choices that are obvious from the project type (e.g., "npm for package management" in a Node.js project) +- Infrastructure defaults (e.g., "Docker for containerization" when there's a Dockerfile) -2. **Create ADR Entry**: +**For small teams**: Apply this filter aggressively. A 2-person team doesn't need an ADR explaining why they use PostgreSQL. Focus on decisions that would trip up a new hire or a future maintainer. + +**For large teams**: Be more inclusive — document more decisions for compliance and onboarding purposes, but still skip truly obvious defaults. + +#### ADR Template for Discovered Decisions + +For each ADR that passes the filter: ```markdown ## ADR-[NNN]: [Discovered Decision] @@ -190,87 +254,146 @@ Legacy/Inferred #### Risks - [Risk if this decision is not well understood] -### Alternatives (Available at Decision Time) -- [Alternative 1]: [Common alternative that wasn't chosen] -- [Alternative 2]: [Another option] +### Common Alternatives +[OPTIONAL — only include if genuinely informative] + +Other options in this space include: +- **[Alternative 1]**: [Brief factual description — what it is and when it's typically used] +- **[Alternative 2]**: [Brief factual description] + +> *For discovered ADRs, do not fabricate rejection rationale. State alternatives factually without assuming why they weren't chosen.* ### Confidence Level [HIGH/MEDIUM/LOW] - [Explanation of confidence in inference] ``` -3. **ADR Categories to Generate**: - - **ADR-001**: System Architecture Style - - **ADR-002**: Primary Database Choice - - **ADR-003**: API Style - - **ADR-004**: Frontend Framework (if applicable) - - **ADR-005**: Deployment Platform - - **ADR-006**: CI/CD Approach - - Additional ADRs for significant patterns discovered +**Important guidance for the "Common Alternatives" section:** + +- This section is **optional**. Only include it when the alternatives are genuinely worth noting. +- **Never use "Rejected because:" framing** — you are reverse-engineering, not documenting a decision that was actively debated. You don't know why alternatives weren't chosen. +- **State alternatives factually**: "Other options in this space include X, Y" — not "X was rejected because..." +- For small teams: skip this section entirely unless the alternative is commonly confused with the chosen option +- For large teams: include when it helps onboarding engineers understand the landscape + +### Phase 6: Risks, Gaps & Recommendations + +**Objective**: Identify what's missing, broken, or risky — this is the most valuable output + +**For small teams, this is the PRIMARY output.** Lead with this before ADRs. + +Analyze the codebase for: + +#### Operational Gaps +- Missing backup strategy or no evidence of backups +- No monitoring/alerting configuration found +- No health check endpoints +- No error tracking service (Sentry, Bugsnag, etc.) +- No log aggregation beyond local files +- Missing rate limiting on APIs + +#### Technical Debt +- Pinned beta/alpha/RC package versions +- Deprecated API usage +- TODO/FIXME/HACK comments in code (count and categorize) +- Dependencies with known vulnerabilities (`npm audit`, etc.) +- Outdated major version dependencies + +#### Single Points of Failure +- Single database instance without replica +- No failover configuration +- Single deployment target +- Hard-coded credentials or secrets not in a vault -### Phase 4: Gap Analysis +#### Missing Safety Nets +- No database migration rollback plan +- Missing test coverage for critical paths +- No CI/CD pipeline or incomplete pipeline +- No environment variable validation +- Missing `.env.example` or environment documentation -**Objective**: Identify areas where decisions are unclear +#### Security Concerns +- Secrets in code or config files +- Missing CORS configuration +- No input validation middleware +- Authentication/authorization gaps -After scanning, report: +Format findings as **actionable items**, not just observations: ```markdown -## 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 | - -### ADRs Generated -| ID | Decision | Confidence | -|----|----------|------------| -| ADR-001 | Monolithic Django architecture | HIGH | -| ADR-002 | PostgreSQL as primary database | HIGH | -| ADR-003 | REST API with Django REST Framework | MEDIUM | - -### 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] +## Risks, Gaps & Recommendations + +### Critical (Address Soon) +| Finding | Impact | Recommendation | +|---------|--------|----------------| +| No database backup config found | Data loss risk | Set up automated daily backups | +| Secrets in .env committed to git | Security breach risk | Move to secrets manager, add .env to .gitignore | + +### Important (Plan For) +| Finding | Impact | Recommendation | +|---------|--------|----------------| +| No monitoring/alerting setup | Silent failures | Add health checks + basic alerting | +| 15 TODO comments in payment module | Technical debt | Triage and prioritize | + +### Nice to Have +| Finding | Impact | Recommendation | +|---------|--------|----------------| +| Test coverage unclear | Regression risk | Add coverage reporting | ``` -### Phase 5: Output Generation +### Phase 7: Output Generation -**Objective**: Write discoveries to files +**Objective**: Write discoveries to files, calibrated to team size -1. **Write ADRs**: +1. **Add complementary note** if existing docs were found (Phase 3): + + ```markdown + > This document complements existing project documentation ([CLAUDE.md], [README.md], etc.). + > Conventions and coding standards documented there are not repeated here. + ``` + +2. **Write Risks & Gaps** (most valuable content): + - For **small teams**: This goes at the TOP of `memory/architecture.md`, before architectural views + - For **medium/large teams**: This goes in a prominent section (not buried as an appendix) + +3. **Write ADRs**: - Create or update `memory/adr.md` with discovered ADRs - Mark ADRs as "Discovered (Inferred)" status - Note confidence level for each - -2. **Optionally Update Architecture**: - - If `memory/architecture.md` exists, update tech stack section - - If not, suggest running `/architect.implement` after clarification - -3. **Generate Summary**: - - Technologies discovered - - ADRs created - - Gaps identified + - Only include ADRs that passed the surprise-value filter + +4. **Write Architecture Description**: + - For **small teams**: Use the lean template (`AD-template-lean.md`) — system overview, context diagram, key data flows, deployment topology, tech stack, risks & gaps + - For **medium teams**: Use the lean template with optional expanded sections as needed + - For **large teams**: Use the full template (`AD-template.md`) with all Rozanski & Woods viewpoints + +5. **Generate Summary**: + - Team size detected and tier used + - Existing documentation found and what was deduplicated + - Risks and gaps identified (highlight critical ones) + - ADRs created (with brief justification for why each passed the filter) - Recommended next steps ## Key Rules ### Evidence-Based Documentation -- **Only document what's found in code** - don't invent decisions +- **Only document what's found in code** — don't invent decisions - **Cite specific evidence** for each ADR - **Mark confidence levels** honestly - **Flag uncertainties** explicitly +- **Never fabricate rejection rationale** for alternatives in discovered ADRs + +### Surprise-Value Filter + +- **Skip obvious defaults** — don't document decisions that match ecosystem norms +- **Document what surprises** — non-obvious choices, convention violations, unusual constraints +- **Scale with team size** — small teams get fewer, more targeted ADRs + +### No Duplication + +- **Read existing docs first** — CLAUDE.md, README, CONTRIBUTING, etc. +- **Don't repeat** what's already documented elsewhere +- **Reference, don't reproduce** — link to existing docs instead of copying content ### Confidence Levels @@ -298,10 +421,11 @@ After scanning, report: Recommended next steps: -1. **Review Discoveries**: Verify inferred ADRs are accurate -2. **Run `/architect.clarify`**: Fill gaps with human knowledge -3. **Run `/architect.implement`**: Generate full AD.md from ADRs -4. **Update As Needed**: Refine documentation as you learn more +1. **Address Critical Gaps**: Fix any critical risks/gaps identified +2. **Review Discoveries**: Verify inferred ADRs are accurate +3. **Run `/architect.clarify`**: Fill gaps with human knowledge +4. **Run `/architect.implement`**: Generate full AD.md from ADRs (for medium/large teams) +5. **Update As Needed**: Refine documentation as you learn more ### When to Use This Command From b7063cb8c6e593ded91e3ce7843950d28cf84c8c Mon Sep 17 00:00:00 2001 From: Nir Alfasi Date: Tue, 10 Feb 2026 19:18:06 +0200 Subject: [PATCH 2/2] fix: resolve template paths to use SPECKIT_TEMPLATES_DIR Template references were hardcoded to .specify/templates/ which doesn't exist in release packages. Use a relative path from the script directory instead. Co-Authored-By: Claude Opus 4.6 --- memory/architecture.md | 416 +++++++++++++++++++++++++++++ scripts/bash/setup-architecture.sh | 9 +- 2 files changed, 421 insertions(+), 4 deletions(-) create mode 100644 memory/architecture.md diff --git a/memory/architecture.md b/memory/architecture.md new file mode 100644 index 000000000..dfd637b71 --- /dev/null +++ b/memory/architecture.md @@ -0,0 +1,416 @@ +# Architecture Description: [SYSTEM_NAME] + +**Version**: 1.0 | **Created**: [DATE] | **Last Updated**: [DATE] +**Architect**: [AUTHOR/AI] | **Status**: Draft | Review | Approved +**ADR Reference**: [memory/adr.md](memory/adr.md) + +--- + +## 1. Introduction + +### 1.1 Purpose + +[Describe why this system exists - the business/technical problem it solves] + +### 1.2 Scope + +**In Scope:** + +- [Feature/capability 1] +- [Feature/capability 2] + +**Out of Scope:** + +- [Explicitly excluded feature/capability 1] +- [Explicitly excluded feature/capability 2] + +### 1.3 Definitions & Acronyms + +| Term | Definition | +|------|------------| +| AD | Architecture Description - this document | +| ADR | Architecture Decision Record - documented architectural decisions | + +--- + +## 2. Stakeholders & Concerns + +| Stakeholder | Role | Key Concerns | Priority | +|-------------|------|--------------|----------| +| [STAKEHOLDER_1] | [e.g., Product Owner] | [e.g., Feature delivery, cost control] | High | +| [STAKEHOLDER_2] | [e.g., Operations Team] | [e.g., System uptime, deployability] | High | +| [STAKEHOLDER_3] | [e.g., Security Officer] | [e.g., Data protection, compliance] | Critical | +| [STAKEHOLDER_4] | [e.g., End Users] | [e.g., Performance, usability] | High | + +--- + +## 3. Architectural Views (Rozanski & Woods) + +### 3.1 Context View + +**Purpose**: Define system scope and external interactions + +#### 3.1.1 System Scope + +[High-level description of what the system does and its boundaries] + +#### 3.1.2 External Entities + +| Entity | Type | Interaction Type | Data Exchanged | Protocols | +|--------|------|------------------|----------------|-----------| +| [ENTITY_1] | User/System/API | [e.g., REST API, UI] | [e.g., User credentials] | [e.g., HTTPS] | +| [ENTITY_2] | [External System] | [Integration method] | [Data format] | [Protocol] | + +#### 3.1.3 Context Diagram + +```mermaid +graph TD + Users["Users"] + System["System
(Main Application)"] + Database["Database"] + ExternalAPI["External APIs"] + + Users -->|Requests| System + System -->|Queries| Database + System -->|Integrates| ExternalAPI + + classDef systemNode fill:#f47721,stroke:#333,stroke-width:2px,color:#fff + classDef externalNode fill:#e0e0e0,stroke:#333,stroke-width:1px + + class System systemNode + class Users,Database,ExternalAPI externalNode +``` + +#### 3.1.4 External Dependencies + +| Dependency | Purpose | SLA Expectations | Fallback Strategy | +|------------|---------|------------------|-------------------| +| [DEPENDENCY_1] | [Purpose] | [e.g., 99.9% uptime] | [e.g., Cache, degraded mode] | + +--- + +### 3.2 Functional View + +**Purpose**: Describe functional elements, their responsibilities, and interactions + +#### 3.2.1 Functional Elements + +| Element | Responsibility | Interfaces Provided | Dependencies | +|---------|----------------|---------------------|--------------| +| [COMPONENT_1] | [e.g., User authentication] | [e.g., REST /auth/*] | [e.g., Database] | +| [COMPONENT_2] | [Responsibility] | [Interfaces] | [Dependencies] | + +#### 3.2.2 Element Interactions + +```mermaid +graph TD + APIGateway["API Gateway"] + AuthService["Authentication
Service"] + BusinessLogic["Business Logic
Layer"] + DataAccess["Data Access
Layer"] + + APIGateway -->|Routes| AuthService + APIGateway -->|Routes| BusinessLogic + AuthService -->|Validates| BusinessLogic + BusinessLogic -->|Queries| DataAccess + + classDef serviceNode fill:#4a9eff,stroke:#333,stroke-width:2px,color:#fff + classDef dataNode fill:#66c2a5,stroke:#333,stroke-width:2px,color:#fff + + class APIGateway,AuthService,BusinessLogic serviceNode + class DataAccess dataNode +``` + +#### 3.2.3 Functional Boundaries + +**What this system DOES:** + +- [Functionality 1] +- [Functionality 2] + +**What this system does NOT do:** + +- [Excluded functionality 1] +- [Excluded functionality 2] + +--- + +### 3.3 Information View + +**Purpose**: Describe data storage, management, and flow + +#### 3.3.1 Data Entities + +| Entity | Storage Location | Owner Component | Lifecycle | Access Pattern | +|--------|------------------|-----------------|-----------|----------------| +| [ENTITY_1] | [e.g., PostgreSQL] | [e.g., UserService] | [e.g., Create-Update-Archive] | [e.g., Read-heavy] | + +#### 3.3.2 Data Flow + +**Key Data Flows:** + +1. **[Flow Name]**: [Source] -> [Transformation] -> [Destination] +2. **[Flow Name]**: [Description of data movement] + +#### 3.3.3 Data Quality & Integrity + +- **Consistency Model**: [e.g., Eventual, Strong, ACID] +- **Validation Rules**: [Key data validation points] +- **Retention Policy**: [Data lifecycle requirements] +- **Backup Strategy**: [Backup approach] + +--- + +### 3.4 Concurrency View + +**Purpose**: Describe runtime processes, threads, and coordination + +#### 3.4.1 Process Structure + +| Process | Purpose | Scaling Model | State Management | +|---------|---------|---------------|------------------| +| [PROCESS_1] | [e.g., API Server] | [e.g., Horizontal - stateless] | [Stateless/Stateful] | + +#### 3.4.2 Thread Model + +- **Threading Strategy**: [e.g., Thread pool, Event-driven async] +- **Async Patterns**: [e.g., Async/await, reactive streams] +- **Resource Pools**: [e.g., Database connection pool] + +#### 3.4.3 Coordination Mechanisms + +- **Synchronization**: [e.g., Distributed locks via Redis] +- **Communication**: [e.g., Message queues, event bus] +- **Deadlock Prevention**: [e.g., Lock ordering, timeouts] + +--- + +### 3.5 Development View + +**Purpose**: Constraints for developers - code organization, dependencies, CI/CD + +#### 3.5.1 Code Organization + +```text +project-root/ +├── src/ +│ ├── api/ # API endpoints +│ ├── services/ # Business logic +│ ├── models/ # Data models +│ └── repositories/ # Data access +├── tests/ +│ ├── unit/ +│ ├── integration/ +│ └── e2e/ +└── infra/ # Infrastructure as code +``` + +#### 3.5.2 Module Dependencies + +**Dependency Rules:** + +- API layer depends on Services layer (not vice versa) +- Services layer depends on Repositories layer +- No circular dependencies allowed + +#### 3.5.3 Build & CI/CD + +- **Build System**: [e.g., npm, gradle, cargo] +- **CI Pipeline**: [Key stages] +- **Deployment Strategy**: [e.g., Blue-green, rolling] + +#### 3.5.4 Development Standards + +- **Coding Standards**: [e.g., ESLint config, PEP 8] +- **Review Requirements**: [e.g., 2 approvals] +- **Testing Requirements**: [e.g., 80% coverage] + +--- + +### 3.6 Deployment View + +**Purpose**: Physical environment - nodes, networks, storage + +#### 3.6.1 Runtime Environments + +| Environment | Purpose | Infrastructure | Scale | +|-------------|---------|----------------|-------| +| Production | Live users | [e.g., AWS EKS] | [e.g., 10 nodes] | +| Staging | Pre-release | [e.g., AWS EKS] | [e.g., 3 nodes] | +| Development | Dev testing | [e.g., Docker Compose] | [e.g., 1 node] | + +#### 3.6.2 Network Topology + +```mermaid +graph TB + subgraph "Production" + LB["Load Balancer"] + + subgraph "App Tier" + Web1["Web Server 1"] + Web2["Web Server 2"] + end + + subgraph "Data Tier" + DB["Database"] + Cache["Cache"] + end + end + + Internet["Internet"] -->|HTTPS| LB + LB --> Web1 + LB --> Web2 + Web1 --> DB + Web2 --> DB + Web1 --> Cache + Web2 --> Cache +``` + +#### 3.6.3 Hardware Requirements + +| Component | CPU | Memory | Storage | +|-----------|-----|--------|---------| +| Web Server | [e.g., 2 cores] | [e.g., 4GB] | [e.g., 20GB] | +| Database | [Specs] | [Specs] | [Specs] | + +--- + +### 3.7 Operational View + +**Purpose**: Operations, support, and maintenance in production + +#### 3.7.1 Operational Responsibilities + +| Activity | Owner | Frequency | Automation | +|----------|-------|-----------|------------| +| Deployment | DevOps | On-demand | Automated | +| Backup | Operations | Daily | Automated | +| Monitoring | SRE | Continuous | Automated | + +#### 3.7.2 Monitoring & Alerting + +- **Key Metrics**: [e.g., Latency, error rate, throughput] +- **Alerting Rules**: [e.g., Error rate > 1% -> Page on-call] +- **Logging Strategy**: [e.g., ELK stack, 30-day retention] + +#### 3.7.3 Disaster Recovery + +- **RTO**: [e.g., 1 hour] +- **RPO**: [e.g., 15 minutes] +- **Backup Strategy**: [e.g., Daily snapshots] + +#### 3.7.4 Support Model + +- **Tier 1**: Help desk +- **Tier 2**: Application support +- **Tier 3**: Engineering +- **On-call**: [Rotation schedule] + +--- + +## 4. Architectural Perspectives (Cross-Cutting Concerns) + +### 4.1 Security Perspective + +**Applies to**: All views + +#### 4.1.1 Authentication & Authorization + +- **Identity Provider**: [e.g., OAuth2 via Auth0] +- **Authorization Model**: [e.g., RBAC, ABAC] +- **Session Management**: [e.g., JWT with 1-hour expiry] + +#### 4.1.2 Data Protection + +- **Encryption at Rest**: [e.g., AES-256] +- **Encryption in Transit**: [e.g., TLS 1.3] +- **Secrets Management**: [e.g., AWS Secrets Manager] +- **PII Handling**: [e.g., Data minimization] + +#### 4.1.3 Threat Model + +| Threat | View Affected | Likelihood | Impact | Mitigation | +|--------|---------------|------------|--------|------------| +| [THREAT_1] | [View] | [H/M/L] | [H/M/L] | [Mitigation] | + +--- + +### 4.2 Performance & Scalability Perspective + +**Applies to**: Functional, Concurrency, Deployment views + +#### 4.2.1 Performance Requirements + +| Metric | Target | Measurement | +|--------|--------|-------------| +| Response time (p95) | [e.g., <200ms] | [e.g., APM] | +| Throughput | [e.g., 1000 req/s] | [e.g., Load tests] | +| Concurrent users | [e.g., 10,000] | [Method] | + +#### 4.2.2 Scalability Model + +- **Horizontal Scaling**: [Approach and limits] +- **Vertical Scaling**: [Approach and limits] +- **Auto-scaling Triggers**: [e.g., CPU > 70%] + +#### 4.2.3 Capacity Planning + +- **Current Capacity**: [e.g., 5,000 concurrent users] +- **Growth Projections**: [e.g., 20% YoY] +- **Bottlenecks**: [Identified constraints] + +--- + +## 5. Global Constraints & Principles + +### 5.1 Technical Constraints + +- [CONSTRAINT_1 - e.g., "Must run on AWS"] +- [CONSTRAINT_2 - e.g., "Python 3.11+ only"] +- [CONSTRAINT_3 - e.g., "Max deployment size: 50MB"] + +### 5.2 Architectural Principles + +- [PRINCIPLE_1 - e.g., "API First"] +- [PRINCIPLE_2 - e.g., "Share-nothing architecture"] +- [PRINCIPLE_3 - e.g., "Immutable infrastructure"] +- [PRINCIPLE_4 - e.g., "Defense in depth"] + +--- + +## 6. ADR Summary + +Detailed Architecture Decision Records are maintained in [memory/adr.md](memory/adr.md). + +**Key Decisions:** + +| ID | Decision | Status | Impact | +|----|----------|--------|--------| +| ADR-001 | [Title] | Accepted | [High/Med/Low] | +| ADR-002 | [Title] | Accepted | [High/Med/Low] | + +--- + +## Appendix + +### A. Glossary + +| Term | Definition | +|------|------------| +| [TERM] | [Definition] | + +### B. References + +- [Architecture documentation] +- [External standards] +- [Relevant ADRs] + +### C. Tech Stack Summary + +**Languages**: [e.g., Python 3.11, TypeScript] +**Frameworks**: [e.g., FastAPI, React] +**Databases**: [e.g., PostgreSQL, Redis] +**Infrastructure**: [e.g., Kubernetes, Terraform] +**Cloud Platform**: [e.g., AWS] +**CI/CD**: [e.g., GitHub Actions] +**Monitoring**: [e.g., Datadog] diff --git a/scripts/bash/setup-architecture.sh b/scripts/bash/setup-architecture.sh index b09ebdf53..a5918a16e 100755 --- a/scripts/bash/setup-architecture.sh +++ b/scripts/bash/setup-architecture.sh @@ -87,7 +87,8 @@ eval "$(get_feature_paths)" mkdir -p "$REPO_ROOT/memory" ARCHITECTURE_FILE="$REPO_ROOT/memory/architecture.md" -TEMPLATE_FILE="$REPO_ROOT/.specify/templates/architecture-template.md" +SPECKIT_TEMPLATES_DIR="$SCRIPT_DIR/../../templates" +TEMPLATE_FILE="$SPECKIT_TEMPLATES_DIR/AD-template.md" # Function to detect team size from git history detect_team_size() { @@ -372,7 +373,7 @@ $diagram_code # Action: Specify (greenfield - interactive PRD exploration to create ADRs) action_specify() { local adr_file="$REPO_ROOT/memory/adr.md" - local adr_template="$REPO_ROOT/.specify/templates/adr-template.md" + local adr_template="$SPECKIT_TEMPLATES_DIR/adr-template.md" echo "📐 Setting up for interactive ADR creation..." >&2 @@ -453,7 +454,7 @@ action_clarify() { action_implement() { local adr_file="$REPO_ROOT/memory/adr.md" local ad_file="$REPO_ROOT/AD.md" - local ad_template="$REPO_ROOT/.specify/templates/AD-template.md" + local ad_template="$SPECKIT_TEMPLATES_DIR/AD-template.md" if [[ ! -f "$adr_file" ]]; then echo "❌ ADR file does not exist: $adr_file" >&2 @@ -508,7 +509,7 @@ action_init() { detected_size=$(detect_team_size) echo "📊 Team size tier: $detected_size" >&2 - local lean_template="$REPO_ROOT/.specify/templates/AD-template-lean.md" + local lean_template="$SPECKIT_TEMPLATES_DIR/AD-template-lean.md" local selected_template="$TEMPLATE_FILE" if [[ "$detected_size" == "small" || "$detected_size" == "medium" ]]; then