Overview
Chapter 01: AWS AI-DLC & Framework Comparative Review (BMAD vs. Spec-Kit vs. AWS AI-DLC)
From Chaotic Conversational Coding to Disciplined, Governed Software Workflows
Playbook Track: 04 – AI Coding & Software Engineering
Target Audience: Year 1 Computer Science & Software Engineering Students Prerequisites: Basic Python syntax (functions, if/else, lists, dictionaries)
Frontier Tooling Stack: AWS AI-DLC (aidlc), Gemini 2.5 Flash & Pro, Claude Code, Cursor, GitHub Copilot, Python 3.11+
Reference Repository: `awslabs/aidlc-workflows`
Delivery Status: 🔍 Ready for Review (Tier 1 Markdown)
1. The Big Picture & Real-World Analogy
The Trap of "Vibe Coding" & Chatbox Chaos
As a Year 1 computer science student, you have likely opened an AI chat window, pasted an assignment question or a project idea like "Build me a weather web app in Python", and watched the AI spit out 150 lines of code. You copy-pasted it into your editor, ran it, and felt like a wizard when it worked on the first try.
Then came Day 2.
You wanted to add user authentication. You asked the AI for more code. It gave you another code block, but when you pasted it in:
- It silently overwrote functions you wrote yesterday.
- It imported libraries you didn't have installed.
- Cryptic errors flooded your terminal (
AttributeError,ModuleNotFoundError,KeyError). - You pasted the error back to the AI. It apologized and gave you a third version of the file, breaking another feature you had working an hour ago.
This frustrating cycle is called unstructured conversational coding (or "vibe coding"). It treats programming like a casual text chat. In professional engineering, this approach fails because software is not just text—it is an interconnected, living machine governed by dependencies, interface contracts, and business logic.
The Real-World Analogy: The Rookie Carpenter vs. The Licensed General Contractor
Imagine you want to build a small garden guest house on your property:
+----------------------------------------------------------------------------------------------------+
| THE TWO WAYS TO BUILD A HOUSE |
+----------------------------------------------------------------------------------------------------+
| |
| [THE ROOKIE CARPENTER (Chatbox Coding)] [THE LICENSED CONTRACTOR (AWS AI-DLC)] |
| |
| 1. Listens to: "Build me a cozy wooden shed" 1. INCEPTION PHASE: |
| 2. Grabs a hammer and immediately starts - Draws architectural blueprints (`spec.md`). |
| nailing 2x4s together with no blueprint. - Verifies foundation zoning and permits. |
| 3. Realizes in hour 3 that the doorway has no - [GATE 1]: Client & Inspector Sign-Off. |
| frame and the roof blocks the chimney. 2. CONSTRUCTION PHASE: |
| 4. Tears down walls repeatedly, wasting lumber. - Lays foundation strictly to blueprint specs. |
| 5. Result: A crooked, unstable shack that collapses - Tests plumbing & wiring at every step. |
| during the first storm. - [GATE 2]: Quality & Safety Verification. |
| 3. OPERATIONS PHASE: |
| - Final city inspection & occupancy permit. |
| - Handover with warranty & maintenance manual. |
| |
+----------------------------------------------------------------------------------------------------+
- The Rookie Carpenter (Chatbox Coding) starts hammering wood immediately. There are no blueprints, no measurements, and no permits. When problems arise, he hacks fixes on top of hacks until the entire structure is unstable.
- The Licensed Contractor (AWS AI-DLC) follows an engineering methodology:
- Inception: Draws clear blueprints, specifies materials, and waits for your explicit sign-off before cutting any wood.
- Construction: Builds modularly, testing the electrical wiring and plumbing before sealing the drywall.
- Operations: Conducts a final inspection, hands you the keys, and leaves an audit log of all permits and materials.
AWS AI-DLC (AI-Driven Development Life Cycle) is the open-source engineering blueprint developed by AWS Labs (awslabs/aidlc-workflows). It transforms AI from a chaotic chatterbox into a disciplined, obedient collaborator that follows blueprints, waits for your approval, and runs automated tests before claiming the job is done.
2. Engineering Jargon Demystifier
Here are the key engineering terms you need to know, explained in plain English:
| Term | What It Means in Plain English | Why It Matters to You as a Student |
|---|---|---|
| AWS AI-DLC | AI-Driven Development Life Cycle. An open-source framework by AWS Labs (awslabs/aidlc-workflows) that divides AI coding into 3 disciplined phases with mandatory human approval gates. |
Prevents the AI from randomly modifying your codebase or deleting existing working code. |
| Harness | The host application that runs your AI model (e.g., Claude Code, Cursor, Kiro CLI, GitHub Copilot). | AI-DLC is "harness-neutral"—its rules work whether you code in Cursor, Claude Code, or VS Code. |
| Inception Phase | The planning phase. The AI analyzes requirements, clarifies ambiguities, and produces a formal specification (spec.md) before writing any code. |
Stops you from wasting hours writing code for a feature you didn't clearly understand. |
| Construction Phase | The building phase. The AI generates unit tests first, writes minimal code to pass them, and fixes its own syntax errors in a loop. | Ensures that code is verified by automated tests rather than your blind trust. |
| Operations Phase | The delivery phase. Code is linted, packaged, submitted as a Git Pull Request, and monitored for errors. | Teaches you the professional GitOps workflow used in major tech companies. |
| Human Approval Gate | An intentional pause where the AI stops and asks: "Here is my plan / diff. Do you approve?" | You remain in the driver's seat. The AI cannot make changes without your explicit permission. |
| Audit Trail | An automatic log recording what the AI proposed, what tests ran, and when you approved it. | Essential for coursework submissions, teamwork, debugging, and grading. |
| AST (Abstract Syntax Tree) | The mathematical tree structure that a compiler builds to understand your code syntax. | Allows tools to verify if code has valid Python syntax before saving it to disk. |
| BMAD | Business, Modeling, Architecture, Delivery. An agile methodology focused on translating complex business stakeholder rules into software. | Ideal for large projects with lots of non-technical stakeholders. |
| Spec-Kit | Specification-Driven Development. A methodology where strict contracts (JSON Schemas, Gherkin tests) are frozen before coding begins. | Best for building clean APIs and microservices with zero ambiguity. |
3. The 5-Minute Micro-Lab: The Ambiguity Gate
One of the fundamental rules of AWS AI-DLC is: Never let an AI write code if the requirement is ambiguous.
If you ask an AI for "a fast, scalable user profile system", it will guess random assumptions because words like "fast" and "scalable" are meaningless without concrete numbers.
Here is a 25-line Python script that acts as an Inception Ambiguity Gate. Run it on your computer right now!
The Code: micro_gate.py
# micro_gate.py - Zero external dependencies!
import re
VAGUE_WORDS = ["fast", "scalable", "robust", "secure", "user-friendly", "clean", "simple"]
def audit_requirement(prompt: str) -> dict:
"""Checks whether a user prompt has enough detail to safely pass to an AI coder."""
found_vague = [w for w in VAGUE_WORDS if re.search(rf"\b{w}\b", prompt, re.I)]
has_acceptance_criteria = bool(re.search(r"(given|when|then|should return|must respond)", prompt, re.I))
has_latency_or_numbers = bool(re.search(r"(\d+\s*(ms|sec|users|tokens|%)|\$?\d+)", prompt))
score = 100 - (len(found_vague) * 20)
if not has_acceptance_criteria: score -= 30
if not has_latency_or_numbers: score -= 20
score = max(0, score)
return {
"score": score,
"is_safe_to_code": score >= 70,
"vague_words_found": found_vague,
"has_criteria": has_acceptance_criteria,
"has_metrics": has_latency_or_numbers
}
# Try two different prompts:
bad_prompt = "Build a fast, scalable user login service that is simple and robust."
good_prompt = "Build a user login endpoint that responds in < 200ms. Given valid credentials, it must return a JWT token."
for label, p in [("Prompt A (Vague)", bad_prompt), ("Prompt B (Engineered)", good_prompt)]:
res = audit_requirement(p)
status = "[PASS] APPROVED FOR AI-DLC" if res["is_safe_to_code"] else "[REJECTED] REJECTED (INCEPTION GATE)"
print(f"\n{label}: \"{p}\"")
print(f" Result: {status} (Score: {res['score']}/100)")
print(f" Flags: Vague Words={res['vague_words_found']} | Measurable Metrics={res['has_metrics']}")
Try It Yourself:
- Open your terminal or VS Code.
- Run
python micro_gate.py. - Notice how Prompt A is instantly rejected by the Inception Gate because it uses empty buzzwords, while Prompt B is approved because it gives concrete numbers and expected outcomes.
4. How It Works Under the Hood
The AWS AI-DLC Architecture (awslabs/aidlc-workflows)
In modern software engineering, AWS AI-DLC replaces chaotic chats with a 3-phase state machine governed by explicit human approval gates:
flowchart TD
subgraph P1 ["Phase 1: Inception (Specification & Blueprints)"]
A["User Goal / Feature Request"] --> B["AI Requirements Analyst"]
B --> C["Ambiguity Scrubbing & Gherkin Scenarios"]
C --> D["Architecture Blueprints & Data Flow"]
D --> G1{"HUMAN APPROVAL GATE 1<br/>(You Review & Sign Off)"}
end
subgraph P2 ["Phase 2: Construction (TDD & Self-Healing Code)"]
G1 -->|Approved| E["AI Test Engineer: Synthesizes Pytest Cases"]
E --> F["AI Developer: AST Unified Diff Code"]
F --> G["Local Test Runner Execution"]
G -->|Test Fails| H["Traceback Parser & Auto-Repair Loop"]
H -->|Max 3 attempts| F
G -->|All Tests Green| G2{"HUMAN APPROVAL GATE 2<br/>(Diff & Test Review)"}
end
subgraph P3 ["Phase 3: Operations (CI/CD & Delivery)"]
G2 -->|Approved| I["Security & Secrets Linter (TruffleHog)"]
I --> J["Automated Git Pull Request Generation"]
J --> K["Audit Trail Logged & Feature Deployed"]
end
style G1 fill:#ffe082,stroke:#f57f17,stroke-width:3px;
style G2 fill:#ffe082,stroke:#f57f17,stroke-width:3px;
style P1 fill:#e8f5e9,stroke:#2e7d32,stroke-width:2px;
style P2 fill:#e1f5fe,stroke:#0277bd,stroke-width:2px;
style P3 fill:#f3e5f5,stroke:#6a1b9a,stroke-width:2px;
Phase 1: Inception
- Goal: Define what to build and how to test it before touching production files.
- The AI asks clarifying questions, creates a structured
spec.md, and drafts Gherkin scenarios (Given-When-Then). - Gate 1: You review the spec. If the spec has missing edge cases, you reject it and send it back to the AI.
Phase 2: Construction
- Goal: Write minimal, clean, test-passing code.
- Test-Driven Development (TDD): The AI generates the unit tests first. It runs the tests, sees them fail, and only then writes implementation code to make them turn green.
- Closed-Loop Self-Repair: If a syntax error or exception occurs, the AI parses the error traceback and fixes its own mistake (up to 3 controlled attempts) without you having to manually copy-paste errors!
- Gate 2: You review the git diff and verify that all unit tests pass before merging.
Phase 3: Operations
- Goal: Safe packaging, security verification, and git publication.
- Scans the code for hardcoded secrets, syntax regressions, and generates a formatted Pull Request description with an immutable audit log.
The aidlc CLI & Harness-Neutral Core
AWS open-sourced the aidlc tool so you can enforce these rules regardless of which AI assistant you prefer.
You configure your preferred harness with one command:
# Configure for Claude Code
aidlc config --harness claude
# Or configure for Cursor / Kiro / Copilot
aidlc config --harness cursor
Once configured, triggering an AI task passes through the steering rules:
/aidlc Build an in-memory session manager supporting TTL expiration and token invalidation
Instead of dumping code immediately, the AI responds:
"I have initiated the Inception Phase. Before writing code, please review the proposed specification and Gherkin scenarios in
spec.md. Respond 'Approve' to proceed to Construction."
Framework Comparative Review: BMAD vs. Spec-Kit vs. AWS AI-DLC
When you join a development team or work on course projects, you will encounter different AI delivery methodologies. Here is how the big three compare:
+----------------------------------------------------------------------------------------------------+
| FRAMEWORK SWEET SPOTS COMPARISON |
+----------------------------------------------------------------------------------------------------+
| |
| BMAD (Enterprise Alignment) SPEC-KIT (Contract-First) AWS AI-DLC (Governance) |
| "Business -> Model -> Arch" "Spec is the Single Truth" "Inception -> Build -> Ops" |
| |
| Focus: Cross-functional teams Focus: API microservices Focus: Gated AI engineering |
| Best for: Non-technical users Best for: Strict JSON/OpenAPI Best for: Multi-harness CLI |
| Human Gate: Business sign-off Human Gate: Spec schema freeze Human Gate: Formal 3-Phase |
| |
+----------------------------------------------------------------------------------------------------+
| Dimension | BMAD (BMad Method) | Spec-Kit (Spec-Driven Dev) | AWS AI-DLC (awslabs/aidlc-workflows) |
|---|---|---|---|
| Origin & Champion | BMad Open Source Community | Modern API / Frontier Coding Community | AWS Labs Open Source (awslabs) |
| Primary Philosophy | Code is a downstream artifact of domain understanding and business alignment. | If an idea cannot be defined as a testable contract, it must not be coded. | AI is a fast junior collaborator that must operate within gated Inception/Construction/Operations phases. |
| Phase Structure | Business -> Modeling -> Architecture -> Delivery | Intent -> Spec -> Schemas -> Tests -> Implementation | Inception -> Construction -> Operations |
| Human Gate Placement | At the modeling and business requirement sign-off. | At the initial spec.md and schema freeze. |
At every phase boundary (Gate 1 after Inception, Gate 2 after Construction). |
| Supported Harnesses | Standalone multi-agent frameworks | Copilot, Cursor, bespoke scripts | Harness-neutral (Claude Code, Kiro, Cursor, Copilot, Codex) |
| Ideal Project Type | Complex enterprise applications with banks, insurers, or healthcare stakeholders. | Microservice APIs, contract-first distributed systems, typed libraries. | Full-stack applications, student projects, production codebases with CI/CD. |
| Freshman Learning Curve | Medium-High (Requires understanding business domain terminology). | Low-Medium (Requires learning Gherkin and JSON schema). | Ideal (Clear 3-step mental model, explicit approval gates, immediate safety). |
5. Freshman Survival Guide: 3 Traps to Avoid When Coding with AI
As a freshman computer science student, you will easily outpace your peers if you avoid these three common pitfalls:
Trap 1: The Chatbox Copy-Paste Trap
- The Mistake: Spending 40 minutes copying code snippets back and forth between a web browser chat and your editor, accidentally pasting over old code and losing track of versions.
- How to Avoid It: Stop copying whole files manually. Use AI CLI tools (like Claude Code, Cursor, or
aidlc) that apply changes as diffs (modifying only the 5 lines you need rather than rewriting the whole 300-line file).
Trap 2: The Blind Rubber-Stamp Trap
- The Mistake: The AI generates a 50-line code patch, and you immediately hit "Enter" or "Approve" without reading it because you assume the AI is smarter than you.
- How to Avoid It: Always enforce Approval Gate 2. Read every line of the diff before accepting it. If there is a line you cannot explain, ask the AI: "Explain line 15—why did you choose this data structure?" You are the engineer; the AI is just the typing assistant.
Trap 3: The Phantom Package Trap
- The Mistake: You run the AI's code and get
ModuleNotFoundError: No module named 'jwt_super_auth'. The AI hallucinated a library that does not exist! - How to Avoid It: Check package names against your
requirements.txtor search PyPI. Under AWS AI-DLC, all external dependencies must be explicitly approved during the Inception phase before code is generated.
6. Mandatory Hands-On Lab: AWS AI-DLC Workflow Simulator & Spec Linter
Lab Objective
In this hands-on lab, you will run an AWS AI-DLC Workflow Engine & Spec Linter on your local machine.
You will:
- Feed an ambiguous feature request into the engine and watch the Inception Gate reject it.
- Provide a structured, contract-anchored specification and observe the Inception Gate approve it.
- Watch the Construction Phase simulate test-driven code generation, self-healing traceback repair, and prompt you for Gate 2 approval.
- Inspect the generated Audit Trail Log verifying the entire lifecycle.
- Run the Framework Benchmark to compare whether AWS AI-DLC, BMAD, or Spec-Kit is best suited for your project.
Step-by-Step Instructions
- Save the code below as
aidlc_engine.py. - Run it using Python 3.11+:
python aidlc_engine.py - Observe the clean console output and verified self-test assertions.
7. Mandatory Recommended Answer & Executable Solution
"""
aidlc_engine.py
Zero-dependency Python 3.11+ simulator for Chapter 01:
- Implements AWS AI-DLC 3-phase state machine (Inception -> Construction -> Operations)
- Enforces Human Approval Gates (Gate 1 & Gate 2)
- Ambiguity Linter for Inception specs
- Framework Comparative Evaluator (AWS AI-DLC vs. BMAD vs. Spec-Kit)
- 100% self-contained with built-in self-test assertions.
"""
import re
import json
import time
from dataclasses import dataclass, field, asdict
from enum import Enum
from typing import List, Dict, Any, Optional
# ============================================================================
# 1. CORE DOMAIN TYPES & ENUMS
# ============================================================================
class Phase(str, Enum):
INCEPTION = "Inception (Planning & Spec)"
CONSTRUCTION = "Construction (TDD & Self-Healing)"
OPERATIONS = "Operations (CI/CD & Delivery)"
class ApprovalStatus(str, Enum):
PENDING = "PENDING"
APPROVED = "APPROVED"
REJECTED = "REJECTED"
class FrameworkType(str, Enum):
AWS_AI_DLC = "AWS AI-DLC"
BMAD = "BMAD"
SPEC_KIT = "Spec-Kit"
@dataclass
class HumanApprovalGate:
gate_name: str
phase: Phase
status: ApprovalStatus = ApprovalStatus.PENDING
reviewer_notes: str = ""
timestamp: float = field(default_factory=time.time)
def approve(self, notes: str = "Looks good, approved.") -> None:
self.status = ApprovalStatus.APPROVED
self.reviewer_notes = notes
def reject(self, reason: str) -> None:
self.status = ApprovalStatus.REJECTED
self.reviewer_notes = reason
# ============================================================================
# 2. INCEPTION PHASE: SPEC CONFORMANCE & AMBIGUITY LINTER
# ============================================================================
VAGUE_TERMS = [
"fast", "scalable", "robust", "clean", "simple",
"flexible", "user-friendly", "efficient", "state-of-the-art"
]
@dataclass
class SpecLintReport:
is_valid: bool
ambiguity_score: float # 0.0 (perfect) to 1.0 (unusable)
found_vague_terms: List[str]
missing_sections: List[str]
has_gherkin_scenarios: bool
recommendations: List[str]
class SpecLinter:
"""Audits specifications during the AI-DLC Inception phase to stop ambiguous code generation."""
REQUIRED_SECTIONS = ["Overview", "Data Models", "Acceptance Criteria", "Error Handling"]
@classmethod
def lint(cls, spec_markdown: str) -> SpecLintReport:
found_vague = []
for word in VAGUE_TERMS:
if re.search(rf"\b{word}\b", spec_markdown, re.IGNORECASE):
found_vague.append(word)
missing = []
for sec in cls.REQUIRED_SECTIONS:
if not re.search(rf"##\s+{sec}", spec_markdown, re.IGNORECASE):
missing.append(sec)
# Check for Gherkin syntax: Given / When / Then
has_given = bool(re.search(r"\bGiven\b", spec_markdown, re.IGNORECASE))
has_when = bool(re.search(r"\bWhen\b", spec_markdown, re.IGNORECASE))
has_then = bool(re.search(r"\bThen\b", spec_markdown, re.IGNORECASE))
has_gherkin = has_given and has_when and has_then
# Calculate ambiguity score (0.0 to 1.0)
penalty = (len(found_vague) * 0.15) + (len(missing) * 0.25)
if not has_gherkin:
penalty += 0.30
ambiguity_score = min(1.0, round(penalty, 2))
recommendations = []
if found_vague:
recommendations.append(f"Replace subjective terms {found_vague} with quantifiable metrics (e.g. '< 200ms latency').")
if missing:
recommendations.append(f"Add missing mandatory sections: {missing}.")
if not has_gherkin:
recommendations.append("Formalize acceptance criteria into Given-When-Then Gherkin scenarios.")
is_valid = (ambiguity_score <= 0.25 and len(missing) == 0 and has_gherkin)
return SpecLintReport(
is_valid=is_valid,
ambiguity_score=ambiguity_score,
found_vague_terms=found_vague,
missing_sections=missing,
has_gherkin_scenarios=has_gherkin,
recommendations=recommendations
)
# ============================================================================
# 3. AWS AI-DLC WORKFLOW ENGINE (SIMULATOR)
# ============================================================================
@dataclass
class WorkflowExecutionLog:
task_name: str
current_phase: Phase
gate_1: HumanApprovalGate
gate_2: HumanApprovalGate
audit_trail: List[str] = field(default_factory=list)
class AIDLCEngine:
"""Simulates the 3-phase AWS AI-DLC execution lifecycle with mandatory gates."""
def __init__(self, task_name: str):
self.task_name = task_name
self.log = WorkflowExecutionLog(
task_name=task_name,
current_phase=Phase.INCEPTION,
gate_1=HumanApprovalGate(gate_name="Gate 1 (Spec Approval)", phase=Phase.INCEPTION),
gate_2=HumanApprovalGate(gate_name="Gate 2 (Diff & QA Approval)", phase=Phase.CONSTRUCTION)
)
self._record("Workflow initialized in Phase 1: Inception.")
def _record(self, message: str) -> None:
entry = f"[{time.strftime('%H:%M:%S')}] {message}"
self.log.audit_trail.append(entry)
def submit_spec_for_gate_1(self, spec_markdown: str, auto_approve_if_valid: bool = True) -> bool:
"""Runs the Inception Gate. Verifies spec before permitting Construction."""
self._record("Inception Phase: Running SpecLinter on proposed specification...")
report = SpecLinter.lint(spec_markdown)
if not report.is_valid:
self.log.gate_1.reject(f"Linter failed with ambiguity score {report.ambiguity_score}. Missing: {report.missing_sections}")
self._record(f"[REJECTED] Gate 1 REJECTED: {report.recommendations}")
return False
self._record("[PASS] Spec passed Inception linting (Ambiguity score <= 0.25).")
if auto_approve_if_valid:
self.log.gate_1.approve("Human engineer reviewed and approved the spec.")
self.log.current_phase = Phase.CONSTRUCTION
self._record("Gate 1 APPROVED -> Transitioning to Phase 2: Construction.")
return True
return False
def run_construction_tdd(self, tests_pass: bool = True, auto_approve_if_green: bool = True) -> bool:
"""Simulates Phase 2: Construction (TDD code generation & verification)."""
if self.log.gate_1.status != ApprovalStatus.APPROVED:
raise RuntimeError("Cannot start Construction without passing Gate 1 (Inception Approval)!")
self._record("Construction Phase: Synthesizing unit tests first (TDD)...")
time.sleep(0.01) # Simulating execution
if not tests_pass:
self._record("[WARNING] Test failure detected! Triggering closed-loop self-repair...")
self._record("Self-repair attempt 1: Parsed traceback, updated AST unified diff patch.")
self._record("Re-running unit test harness... All tests GREEN.")
self._record("Construction Phase: All tests verified. Requesting Gate 2 human sign-off.")
if auto_approve_if_green:
self.log.gate_2.approve("Code diff reviewed; all 12 unit tests passing.")
self.log.current_phase = Phase.OPERATIONS
self._record("Gate 2 APPROVED -> Transitioning to Phase 3: Operations.")
return True
return False
def run_operations_ci(self) -> Dict[str, Any]:
"""Simulates Phase 3: Operations (Security scan, Git pull request, audit trail)."""
if self.log.gate_2.status != ApprovalStatus.APPROVED:
raise RuntimeError("Cannot run Operations without passing Gate 2 (Construction Approval)!")
self._record("Operations Phase: Scanning code diff for secrets with TruffleHog...")
self._record("Operations Phase: Verified zero secrets, zero syntax errors.")
self._record("Operations Phase: Synthesized Git Pull Request with automated release notes.")
return {
"status": "SUCCESS",
"task": self.task_name,
"final_phase": self.log.current_phase.value,
"gates_passed": [self.log.gate_1.gate_name, self.log.gate_2.gate_name],
"audit_trail_entries": len(self.log.audit_trail)
}
# ============================================================================
# 4. FRAMEWORK COMPARATIVE EVALUATOR
# ============================================================================
@dataclass
class ProjectProfile:
name: str
stakeholder_diversity: int # 1 (solo student) to 10 (enterprise executive committee)
test_strictness: float # 0.0 to 1.0 (coverage expectation)
needs_multi_harness: bool # Needs Claude Code, Cursor, Copilot interoperability
api_first_contract: bool # Heavily driven by OpenAPI / JSON Schemas
class FrameworkComparator:
"""Recommends whether AWS AI-DLC, BMAD, or Spec-Kit is best for a given project."""
@staticmethod
def evaluate(p: ProjectProfile) -> Dict[str, Any]:
scores = {
FrameworkType.AWS_AI_DLC.value: 0.0,
FrameworkType.BMAD.value: 0.0,
FrameworkType.SPEC_KIT.value: 0.0
}
# BMAD scores high when business alignment & diverse stakeholders dominate
scores[FrameworkType.BMAD.value] += p.stakeholder_diversity * 1.8
# Spec-Kit scores high for strict contract-first APIs and deterministic schemas
if p.api_first_contract:
scores[FrameworkType.SPEC_KIT.value] += 8.0
scores[FrameworkType.SPEC_KIT.value] += p.test_strictness * 6.0
# AWS AI-DLC scores high for governed multi-harness workflows with human gates
scores[FrameworkType.AWS_AI_DLC.value] += 5.0
if p.needs_multi_harness:
scores[FrameworkType.AWS_AI_DLC.value] += 7.0
scores[FrameworkType.AWS_AI_DLC.value] += p.test_strictness * 4.0
recommended = max(scores, key=scores.get)
return {
"project_name": p.name,
"recommended_framework": recommended,
"scores": scores,
"rationale": (
f"Selected {recommended} based on stakeholder diversity ({p.stakeholder_diversity}/10), "
f"test strictness ({int(p.test_strictness*100)}%), and multi-harness requirement ({p.needs_multi_harness})."
)
}
# ============================================================================
# 5. SELF-TEST VERIFICATION SUITE
# ============================================================================
def run_self_tests():
print("=" * 75)
print("RUNNING CHAPTER 01 SELF-TEST VERIFICATION SUITE (AWS AI-DLC)")
print("=" * 75)
# Test 1: Flawed Spec Rejection
bad_spec = """
# Bad Feature
Build a fast, scalable user profile system that is robust and clean.
"""
report1 = SpecLinter.lint(bad_spec)
assert not report1.is_valid, "Test 1 Failed: Bad spec should be rejected!"
assert report1.ambiguity_score > 0.5, "Test 1 Failed: Ambiguity score should be high!"
print("[PASS] Test 1 Passed: Inception Gate correctly caught flawed, ambiguous spec.")
# Test 2: Compliant Spec Approval
good_spec = """
# Feature: User Authentication
## Overview
This service provides JWT-based user authentication with < 200ms latency.
## Data Models
User credentials require email (str) and password_hash (str).
## Acceptance Criteria
- Given valid credentials, When POST /login is called, Then return HTTP 200 and a valid JWT token.
- Given invalid password, When POST /login is called, Then return HTTP 401 Unauthorized.
## Error Handling
Returns standardized RFC 7807 problem details JSON payloads.
"""
report2 = SpecLinter.lint(good_spec)
assert report2.is_valid, f"Test 2 Failed: Good spec should be valid! Recs: {report2.recommendations}"
assert report2.ambiguity_score <= 0.25, "Test 2 Failed: Good spec ambiguity should be <= 0.25"
assert report2.has_gherkin_scenarios, "Test 2 Failed: Should detect Gherkin criteria!"
print("[PASS] Test 2 Passed: Inception Gate correctly approved compliant, contract-first spec.")
# Test 3: Full 3-Phase AI-DLC Workflow Simulation
engine = AIDLCEngine(task_name="Student Auth Microservice")
# Try running Construction before Gate 1 (must fail)
try:
engine.run_construction_tdd()
assert False, "Test 3 Failed: Construction ran without Gate 1 approval!"
except RuntimeError:
print("[PASS] Test 3 Passed: Construction strictly blocked until Gate 1 sign-off.")
# Pass Gate 1
passed_gate_1 = engine.submit_spec_for_gate_1(good_spec, auto_approve_if_valid=True)
assert passed_gate_1, "Test 3 Failed: Gate 1 submission failed!"
assert engine.log.gate_1.status == ApprovalStatus.APPROVED
# Pass Gate 2 (Construction)
passed_gate_2 = engine.run_construction_tdd(tests_pass=False, auto_approve_if_green=True)
assert passed_gate_2, "Test 3 Failed: Construction phase failed!"
assert engine.log.gate_2.status == ApprovalStatus.APPROVED
# Pass Operations
ops_result = engine.run_operations_ci()
assert ops_result["status"] == "SUCCESS"
assert ops_result["final_phase"] == Phase.OPERATIONS.value
assert len(ops_result["gates_passed"]) == 2
print("[PASS] Test 4 Passed: End-to-end 3-Phase AWS AI-DLC execution succeeded with audit trail.")
# Test 5: Framework Comparative Evaluator
p1 = ProjectProfile(name="University Lab Project", stakeholder_diversity=2, test_strictness=0.9, needs_multi_harness=True, api_first_contract=False)
res1 = FrameworkComparator.evaluate(p1)
assert res1["recommended_framework"] == FrameworkType.AWS_AI_DLC.value, "Test 5 Failed: Should recommend AWS AI-DLC for multi-harness lab!"
print("[PASS] Test 5 Passed: Framework Comparator correctly recommended AWS AI-DLC for student team.")
print("\n" + "=" * 75)
print("[SUCCESS] ALL 5 SELF-TEST SUITES PASSED CLEANLY (100% GREEN ASSERTIONS)")
print("=" * 75)
if __name__ == "__main__":
run_self_tests()
8. Summary & Next Step in the Curriculum
In this opening chapter, you learned:
- The Fundamental Shift: Moving from chaotic "chatbox copy-paste" coding to disciplined, governed software development.
- AWS AI-DLC (
awslabs/aidlc-workflows): The 3 formal phases—Inception, Construction, and Operations—and how Human Approval Gates keep you in complete control of your codebase. - Framework Sweet Spots: How AWS AI-DLC provides the harness-neutral governance core, while Spec-Kit offers schema precision and BMAD bridges non-technical business stakeholders.
- Freshman Survival Habits: Avoiding whole-file overwrites, never blindly rubber-stamping code, and watching out for hallucinated libraries.
Coming Up in Chapter 02:
In Chapter 02: Automated Requirements Engineering & Spec-Kit PRD Synthesis, we will dive deep into the Inception Phase: learning how to turn a messy 2-paragraph project idea into an airtight, automated spec.md with executable Gherkin acceptance tests.