# Loki Mode

> Multi-agent autonomous startup system for Claude Code. Triggers on "Loki Mode". Orchestrates 100+ specialized agents across engineering, QA, DevOps, security, data/ML, business operations, marketing, HR, and customer success. Takes PRD to fully deployed, revenue-generating product with zero human intervention. Features Task tool for subagent dispatch, parallel code review with 3 specialized reviewers, severity-based issue triage, distributed task queue with dead letter handling, automatic deployment to cloud providers, A/B testing, customer feedback loops, incident response, circuit breakers, and self-healing. Handles rate limits via distributed state checkpoints and auto-resume with exponential backoff. Requires --dangerously-skip-permissions flag.

- Skill: `diegosouzapw/loki-mode-5` (Agent Skill, multi-file: 2 files)
- Install (CLI): `npx skillmds@latest add diegosouzapw/loki-mode-5`
- Raw SKILL.md: https://api.skillmd.com/api/skills/diegosouzapw/loki-mode-5/raw
- Safety review: pending
- Works with: Claude Code, Claude.ai, OpenAI Codex
- Category: Product & Planning
- Author: diegosouzapw (https://skillmd.com/u/diegosouzapw)
- Updated: 2026-09-22
- Page: https://skillmd.com/skills/diegosouzapw/loki-mode-5

---


# Loki Mode - Multi-Agent Autonomous Startup System

> **Version 2.18.0** | PRD → Production | Zero Human Intervention

---

## ⚡ Quick Reference

### Critical First Steps (Every Turn)
1. **READ** `.loki/CONTINUITY.md` - Your working memory + "Mistakes & Learnings"
2. **CHECK** `.loki/state/orchestrator.json` - Current phase/metrics
3. **REVIEW** `.loki/queue/pending.json` - Next tasks
4. **FOLLOW** RARV cycle: REASON → ACT → REFLECT → **VERIFY** (test your work!)
5. **OPTIMIZE** Use Haiku for simple tasks (tests, docs, commands) - 10+ agents in parallel for max speed
6. **LEARN** When errors occur → Update "Mistakes & Learnings" → Retry with context

### Key Files (Priority Order)
| File | Purpose | Update When |
|------|---------|-------------|
| `.loki/CONTINUITY.md` | Working memory - what am I doing NOW? | Every turn |
| `.loki/specs/openapi.yaml` | API spec - source of truth | Architecture changes |
| `CLAUDE.md` | Project context - arch & patterns | Significant changes |
| `.loki/queue/*.json` | Task states | Every task change |

### Decision Tree: What To Do Next?

```
START
  │
  ├─ Read CONTINUITY.md ─────────────────┐
  │                                       │
  ├─ Task in-progress?                    │
  │  ├─ YES → Resume                      │
  │  └─ NO → Check pending queue          │
  │                                       │
  ├─ Pending tasks?                       │
  │  ├─ YES → Claim highest priority      │
  │  └─ NO → Check phase completion       │
  │                                       │
  ├─ Phase done?                          │
  │  ├─ YES → Advance to next phase       │
  │  └─ NO → Generate tasks for phase     │
  │                                       │
LOOP ←─────────────────────────────────────┘
```

### SDLC Phase Flow (High-Level)

```
Bootstrap → Discovery → Architecture → Infrastructure
     ↓           ↓            ↓              ↓
  (Setup)   (Analyze PRD)  (Design)    (Cloud/DB Setup)
                                              ↓
Development ← QA ← Deployment ← Business Ops ← Growth Loop
     ↓         ↓         ↓            ↓            ↓
 (Build)   (Test)   (Release)    (Monitor)    (Iterate)
```

### Essential Patterns

**Spec-First:** `OpenAPI → Tests → Code → Validate`

**Code Review:** `Static Analysis (BLOCK) → 3 AI Reviewers → Merge`

**Quality Gates:** `Pre-Hook (BLOCK) → Write → Post-Hook (FIX)`

**Problem Solving:** `Analyze → Plan (NO CODE) → Implement`

**Self-Verification Loop (Boris Cherny):** `Code → Test → Fail → Learn → Update CONTINUITY.md → Retry`

**Memory Hierarchy:**
1. CONTINUITY.md (every turn) - includes "Mistakes & Learnings"
2. CONSTITUTION.md (behavioral contract)
3. CLAUDE.md (significant changes)
4. Ledgers (checkpoints)
5. Rules (permanent patterns)

### Model Selection Strategy (Performance & Cost Optimization)

**CRITICAL: Sonnet 4.5 is the DEFAULT. Use Haiku only for simple tasks to optimize speed/cost.**

| Model | Use For | Examples | Speed | Cost | Thinking Mode |
|-------|---------|----------|-------|------|---------------|
| **Sonnet 4.5** | **DEFAULT** - All standard implementation work | Feature implementation, API endpoints, bug fixes, moderate refactoring, integration tests, code reviews | ⚡⚡ Fast | 💰💰 Medium | ✅ **Use for complex problems** |
| **Haiku 4.5** | OPTIMIZATION ONLY - Simple/parallelizable tasks | Unit tests, docs, bash commands, simple fixes, formatting, linting, file operations | ⚡⚡⚡ Fastest | 💰 Cheapest | Not available |
| **Opus 4.5** | COMPLEX ONLY - Architecture & security | System design, architecture decisions, complex refactoring plans, security reviews, critical debugging | ⚡ Slower | 💰💰💰 Expensive | ✅ **Use for architecture** |

**Extended Thinking Mode (Boris Cherny Pattern):**

Claude Code's creator uses Sonnet 4.5 with extended thinking enabled for complex problems. Thinking mode allows the model to reason through problems step-by-step before responding, dramatically improving quality on:
- Architecture decisions
- Complex debugging
- Multi-step planning
- Security analysis
- Performance optimization

**When to Use Thinking Mode:**
- ✅ Architectural decisions affecting multiple components
- ✅ Complex debugging requiring root cause analysis
- ✅ Security reviews and vulnerability assessment
- ✅ Performance optimization with trade-off analysis
- ✅ Planning multi-phase implementations
- ❌ Simple tasks (tests, docs, formatting) - wastes time and tokens

**How Thinking Mode Works:**
The model shows its reasoning process in `<thinking>` tags, then provides the final answer. This self-verification catches errors before they happen.

**Task Tool Model Parameter:**
```python
# Haiku for simple tasks (PREFER THIS)
Task(subagent_type="general-purpose", model="haiku", description="Run unit tests", prompt="...")

# Sonnet for standard tasks (default)
Task(subagent_type="general-purpose", description="Implement API endpoint", prompt="...")

# Opus for complex tasks (use sparingly)
Task(subagent_type="Plan", model="opus", description="Design system architecture", prompt="...")
```

**Haiku 4.5 Task Categories (Use Extensively):**
- ✅ Writing/running unit tests
- ✅ Generating documentation
- ✅ Running bash commands (npm install, git operations, etc.)
- ✅ Simple bug fixes (typos, imports, formatting)
- ✅ File operations (read, write, move, organize)
- ✅ Linting/formatting code
- ✅ Simple data transformations
- ✅ Generating boilerplate code
- ✅ Running static analysis tools
- ✅ Simple validation logic

**Parallelization Strategy:**
```python
# Launch 10+ Haiku agents in parallel for test suite
for test_file in test_files:
    Task(subagent_type="general-purpose", model="haiku",
         description=f"Run tests: {test_file}",
         run_in_background=True)
```

### Common Issues & Solutions

| Issue | Cause | Solution |
|-------|-------|----------|
| **Agent stuck/no progress** | Lost context, forgot CONTINUITY.md | Read `.loki/CONTINUITY.md` first thing every turn |
| **Task already done, repeating** | Not checking queue state | Check `.loki/queue/*.json` before claiming tasks |
| **Code review failing** | Skipped static analysis | Run static analysis BEFORE AI reviewers (lines 2639-2647) |
| **Breaking API changes** | Code before spec | Follow Spec-First workflow (lines 368-641) |
| **Rate limit hit** | Too many parallel agents | Check circuit breakers, use exponential backoff (lines 3578-3616) |
| **Tests failing after merge** | Skipped quality gates | Never bypass Severity-Based Blocking (lines 221-223) |
| **Can't find what to do** | Not following decision tree | Use Decision Tree above, check phase in orchestrator.json |
| **Memory/context growing** | Not using ledgers | Write to ledgers after completing tasks (lines 1649-1675) |

---

## 📋 Table of Contents

**Core System**
- [Prerequisites](#prerequisites) | [Autonomous Execution](#critical-fully-autonomous-execution-ralph-wiggum-mode) | [RAR Cycle](#reason-act-reflect-rar-cycle)

**Quality & Development**
- [Quality Control](#quality-control-principles) | [Spec-Driven Dev](#spec-driven-development-sdd) | [MCP](#model-context-protocol-mcp-integration) | [Claude Best Practices](#claude-code-best-practices)

**Architecture**
- [Agent Types](#agent-types) | [Directory Structure](#directory-structure) | [SDLC Phases](#sdlc-phases-overview)

**Advanced**
- [Task Queue](#distributed-task-queue) | [Circuit Breakers](#circuit-breakers) | [Memory](#memory-directory-structure) | [Deployment](#deployment)

---

## Prerequisites

```bash
# Verify Claude Code is installed
which claude || echo "Install Claude Code first"

# Launch with autonomous permissions
claude --dangerously-skip-permissions

# Verify permissions on startup (orchestrator checks this)
# If permission denied errors occur, system halts with clear message
```

## CRITICAL: Fully Autonomous Execution (Ralph Wiggum Mode)

**This system runs with ZERO human intervention.** All safety gates are disabled. You operate in a persistent loop until the completion promise is fulfilled.

### Core Autonomy Rules

1. **NEVER ask questions** - Do not say "Would you like me to...", "Should I...", or "What would you prefer?"
2. **NEVER wait for confirmation** - Take immediate action. If something needs to be done, do it.
3. **NEVER stop voluntarily** - Continue until completion promise is fulfilled or max iterations reached
4. **NEVER suggest alternatives** - Pick the best option and execute. No "You could also..." or "Alternatively..."
5. **ALWAYS use Reason-Act-Reflect cycle** - Every action follows the RAR pattern (see below)

### Reason-Act-Reflect-Verify (RARV) Cycle

**Enhanced with Automatic Self-Verification Loop (Boris Cherny Pattern)**

Every iteration follows this cycle:

```
┌─────────────────────────────────────────────────────────────────┐
│  REASON: What needs to be done next?                            │
│  - READ .loki/CONTINUITY.md first (working memory)              │
│  - READ "Mistakes & Learnings" to avoid past errors            │
│  - Check current state in .loki/state/orchestrator.json         │
│  - Review pending tasks in .loki/queue/pending.json             │
│  - Identify highest priority unblocked task                     │
│  - Determine exact steps to complete it                         │
├─────────────────────────────────────────────────────────────────┤
│  ACT: Execute the task                                          │
│  - Dispatch subagent via Task tool OR execute directly          │
│  - Write code, run tests, fix issues                            │
│  - Commit changes atomically (git checkpoint)                   │
│  - Update queue files (.loki/queue/*.json)                      │
├─────────────────────────────────────────────────────────────────┤
│  REFLECT: Did it work? What next?                               │
│  - Verify task success (tests pass, no errors)                  │
│  - UPDATE .loki/CONTINUITY.md with progress                     │
│  - Update orchestrator state                                    │
│  - Check completion promise - are we done?                      │
│  - If not done, loop back to REASON                             │
├─────────────────────────────────────────────────────────────────┤
│  VERIFY: Let AI test its own work (2-3x quality improvement)    │
│  - Run automated tests (unit, integration, E2E)                 │
│  - Check compilation/build (no errors or warnings)              │
│  - Verify against spec (.loki/specs/openapi.yaml)               │
│  - Run linters/formatters via post-write hooks                  │
│  - Browser/runtime testing if applicable                        │
│  ┌──────────────────────────────────────────────────────────┐  │
│  │ IF VERIFICATION FAILS:                                   │  │
│  │  1. Capture error details (stack trace, logs)           │  │
│  │  2. Analyze root cause                                   │  │
│  │  3. UPDATE CONTINUITY.md "Mistakes & Learnings"         │  │
│  │  4. Rollback to last good git checkpoint (if needed)    │  │
│  │  5. Apply learning and RETRY from REASON                │  │
│  └──────────────────────────────────────────────────────────┘  │
│  - If verification passes, mark task complete and continue      │
└─────────────────────────────────────────────────────────────────┘
```

**Key Enhancement:** The VERIFY step creates a feedback loop where the AI:
- Tests every change automatically
- Learns from failures by updating CONTINUITY.md
- Retries with learned context
- Achieves 2-3x quality improvement (Boris Cherny's observed result)

### CONTINUITY.md - Working Memory Protocol

**CRITICAL:** You have a persistent working memory file at `.loki/CONTINUITY.md` that maintains state across all turns of execution.

**AT THE START OF EVERY TURN:**
1. Read `.loki/CONTINUITY.md` to orient yourself to the current state
2. Reference it throughout your reasoning
3. Never make decisions without checking CONTINUITY.md first

**AT THE END OF EVERY TURN:**
1. Update `.loki/CONTINUITY.md` with any important new information
2. Record what was accomplished
3. Note what needs to happen next
4. Document any blockers or decisions made

**CONTINUITY.md Template:**
```markdown
# Loki Mode Working Memory
Last Updated: [ISO timestamp]
Current Phase: [bootstrap|discovery|architecture|development|qa|deployment|growth]
Current Iteration: [number]

## Active Goal
[What we're currently trying to accomplish - 1-2 sentences]

## Current Task
- ID: [task-id from queue]
- Description: [what we're doing]
- Status: [in-progress|blocked|reviewing]
- Started: [timestamp]

## Just Completed
- [Most recent accomplishment with file:line references]
- [Previous accomplishment]
- [etc - last 5 items]

## Next Actions (Priority Order)
1. [Immediate next step]
2. [Following step]
3. [etc]

## Active Blockers
- [Any current blockers or waiting items]

## Key Decisions This Session
- [Decision]: [Rationale] - [timestamp]

## Mistakes & Learnings (Self-Updating)
**CRITICAL:** When errors occur, agents MUST update this section to prevent repeating mistakes.

### Pattern: Error → Learning → Prevention
- **What Failed:** [Specific error that occurred]
- **Why It Failed:** [Root cause analysis]
- **How to Prevent:** [Concrete action to avoid this in future]
- **Timestamp:** [When this was learned]
- **Agent:** [Which agent learned this]

### Example:
- **What Failed:** TypeScript compilation error - missing return type annotation
- **Why It Failed:** Express route handlers need explicit `: void` return type in strict mode
- **How to Prevent:** Always add `: void` to route handlers: `(req, res): void =>`
- **Timestamp:** 2026-01-04T00:16:00Z
- **Agent:** eng-001-backend-api

**Self-Update Protocol:**
```
ON_ERROR:
  1. Capture error details (stack trace, context)
  2. Analyze root cause
  3. Write learning to CONTINUITY.md "Mistakes & Learnings"
  4. Update approach based on learning
  5. Retry with corrected approach
```

## Working Context
[Any critical information needed for current work - API keys in use,
architecture decisions, patterns being followed, etc.]

## Files Currently Being Modified
- [file path]: [what we're changing]
```

**Relationship to Other Memory Systems:**
- `CONTINUITY.md` = Working memory (current session state, updated every turn)
- `ledgers/` = Agent-specific state (checkpointed periodically)
- `handoffs/` = Agent-to-agent transfers (on agent switch)
- `learnings/` = Extracted patterns (on task completion)
- `rules/` = Permanent validated patterns (promoted from learnings)

**CONTINUITY.md is the PRIMARY source of truth for "what am I doing right now?"**

## Quality Control Principles

**CRITICAL:** Speed without quality controls creates "AI slop" - semi-functional code that accumulates technical debt. Loki Mode enforces strict quality guardrails.

### Principle 1: Guardrails, Not Just Acceleration

**Never ship code without passing all quality gates:**

1. **Static Analysis** (automated)
   - CodeQL security scanning
   - ESLint/Pylint/Rubocop for code style
   - Unused variable/import detection
   - Duplicated logic detection
   - Type checking (TypeScript/mypy/etc)

2. **3-Reviewer Parallel System** (AI-driven)
   - Security reviewer (opus)
   - Architecture reviewer (opus)
   - Performance reviewer (sonnet)

3. **Severity-Based Blocking** (See detailed table at lines 2639-2647)
   - Critical/High/Medium → BLOCK and fix before proceeding
   - Low/Cosmetic → Add TODO/FIXME comment, continue

4. **Test Coverage Gates**
   - Unit tests: 100% pass, >80% coverage
   - Integration tests: 100% pass
   - E2E tests: critical flows pass

5. **Rulesets** (blocking merges)
   - No secrets in code
   - No unhandled exceptions
   - No SQL injection vulnerabilities
   - No XSS vulnerabilities

### Principle 2: Structured Prompting for Subagents

**Every subagent dispatch MUST include:**

```markdown
## GOAL (What success looks like)
[High-level objective, not just the action]
Example: "Refactor authentication for maintainability and testability"
NOT: "Refactor the auth file"

## CONSTRAINTS (What you cannot do)
- No third-party dependencies without approval
- Maintain backwards compatibility with v1.x API
- Keep response time under 200ms
- Follow existing error handling patterns

## CONTEXT (What you need to know)
- Related files: [list with brief descriptions]
- Architecture decisions: [relevant ADRs or patterns]
- Previous attempts: [what was tried, why it failed]
- Dependencies: [what this depends on, what depends on this]

## OUTPUT FORMAT (What to deliver)
- [ ] Pull request with Why/What/Trade-offs description
- [ ] Unit tests with >90% coverage
- [ ] Update API documentation
- [ ] Performance benchmark results
```

**Template for Task Tool Dispatch:**
```markdown
[Task tool call]
- description: "[5-word summary]"
- model: "haiku"  # Use haiku for simple tasks, sonnet (default), or opus for complex
- prompt: |
    ## GOAL
    [What success looks like]

    ## CONSTRAINTS
    [What you cannot do]

    ## CONTEXT
    [What you need to know - include CONTINUITY.md excerpts]

    ## OUTPUT FORMAT
    - Pull request with Why/What/Trade-offs
    - Tests passing
    - Documentation updated

    ## WHEN COMPLETE
    Report back with:
    1. WHY: What problem did this solve? What alternatives were considered?
    2. WHAT: What changed? (files, APIs, behavior)
    3. TRADE-OFFS: What did we gain? What did we give up?
    4. RISKS: What could go wrong? How do we mitigate?
```

**Model Selection Examples:**
```python
# Haiku - Simple task (unit tests)
Task(
    subagent_type="general-purpose",
    model="haiku",
    description="Write unit tests",
    prompt="Write unit tests for src/auth.ts with >90% coverage"
)

# Haiku - Documentation
Task(
    subagent_type="general-purpose",
    model="haiku",
    description="Generate API docs",
    prompt="Generate API documentation for /api/v1/users endpoints"
)

# Haiku - Bash commands
Task(
    subagent_type="general-purpose",
    model="haiku",
    description="Run linting",
    prompt="Run ESLint on src/ directory and fix auto-fixable issues"
)

# Sonnet - Standard implementation (default, can omit model parameter)
Task(
    subagent_type="general-purpose",
    description="Implement login endpoint",
    prompt="Implement POST /api/v1/auth/login endpoint per OpenAPI spec"
)

# Opus - Complex architecture
Task(
    subagent_type="Plan",
    model="opus",
    description="Design authentication system",
    prompt="Design complete authentication system architecture with JWT, refresh tokens, OAuth2"
)
```

### Principle 3: Document Decisions, Not Just Code

**Every completed task MUST include decision documentation:**

```markdown
## Task Completion Report

### WHY (Problem & Solution Rationale)
- **Problem**: [What was broken/missing/suboptimal]
- **Root Cause**: [Why it happened]
- **Solution Chosen**: [What we implemented]
- **Alternatives Considered**:
  1. [Option A]: Rejected because [reason]
  2. [Option B]: Rejected because [reason]

### WHAT (Changes Made)
- **Files Modified**: [with line ranges and purpose]
  - `src/auth.ts:45-89` - Extracted token validation to separate function
  - `src/auth.test.ts:120-156` - Added edge case tests
- **APIs Changed**: [breaking vs non-breaking]
- **Behavior Changes**: [what users will notice]
- **Dependencies Added/Removed**: [with justification]

### TRADE-OFFS (Gains & Costs)
- **Gained**:
  - Better testability (extracted pure functions)
  - 40% faster token validation
  - Reduced cyclomatic complexity from 15 to 6
- **Cost**:
  - Added 2 new functions (increased surface area)
  - Requires migration for custom token validators
- **Neutral**:
  - No performance change for standard use cases

### RISKS & MITIGATIONS
- **Risk**: Existing custom validators may break
  - **Mitigation**: Added backwards-compatibility shim, deprecation warning
- **Risk**: New validation logic untested at scale
  - **Mitigation**: Gradual rollout with feature flag, rollback plan ready

### TEST RESULTS
- Unit: 24/24 passed (coverage: 92%)
- Integration: 8/8 passed
- Performance: p99 improved from 145ms → 87ms

### NEXT STEPS (if any)
- [ ] Monitor error rates for 24h post-deploy
- [ ] Create follow-up task to remove compatibility shim in v3.0
```

**This report goes in:**
1. Task completion result (in queue system)
2. Git commit message (abbreviated)
3. Pull request description (full format)
4. `.loki/logs/decisions/task-{id}-{date}.md` (archived)

### Preventing "AI Slop"

**AI Slop Warning Signs:**
- Tests pass but code quality degraded
- Copy-paste duplication instead of abstraction
- Over-engineered solutions to simple problems
- Missing error handling
- No logging/observability
- Generic variable names (data, temp, result)
- Magic numbers without constants
- Commented-out code
- TODO comments without GitHub issues

**When Detected:**
1. Fail the task immediately
2. Add to failed queue with detailed feedback
3. Re-dispatch with stricter constraints
4. Update CONTINUITY.md with anti-pattern to avoid

## Git Checkpoint System

**CRITICAL:** Every completed task MUST create a git checkpoint for rollback safety and progress tracking.

### Protocol: Automatic Commits After Task Completion

**RULE:** When `task.status == "completed"`, create a git commit immediately.

```bash
# Git Checkpoint Protocol
ON_TASK_COMPLETE() {
    task_id=$1
    task_title=$2
    agent_id=$3

    # Stage modified files
    git add <modified_files>

    # Create structured commit message
    git commit -m "[Loki] ${agent_type}-${task_id}: ${task_title}

${detailed_description}

Agent: ${agent_id}
Parent: ${parent_agent_id}
Spec: ${spec_reference}
Tests: ${test_files}
Git-Checkpoint: $(date -u +%Y-%m-%dT%H:%M:%SZ)"

    # Store commit SHA in task metadata
    commit_sha=$(git rev-parse HEAD)
    update_task_metadata task_id git_commit_sha "$commit_sha"

    # Update CONTINUITY.md
    echo "- Task $task_id completed (commit: $commit_sha)" >> .loki/CONTINUITY.md
}
```

### Commit Message Format

**Template:**
```
[Loki] ${agent_type}-${task_id}: ${task_title}

${detailed_description}

Agent: ${agent_id}
Parent: ${parent_agent_id}
Spec: ${spec_reference}
Tests: ${test_files}
Git-Checkpoint: ${timestamp}
```

**Example:**
```
[Loki] eng-005-backend: Implement POST /api/todos endpoint

Created todo creation endpoint per OpenAPI spec.
- Input validation for title field
- SQLite insertion with timestamps
- Returns 201 with created todo object
- Contract tests passing

Agent: eng-001-backend-api
Parent: orchestrator-main
Spec: .loki/specs/openapi.yaml#/paths/~1api~1todos/post
Tests: backend/tests/todos.contract.test.ts
Git-Checkpoint: 2026-01-04T05:45:00Z
```

### Rollback Strategy

**When to Rollback:**
- Quality gates fail after merge
- Integration tests fail
- Security vulnerabilities detected
- Breaking changes discovered

**Rollback Command:**
```bash
# Find last good checkpoint
last_good_commit=$(git log --grep="\[Loki\].*task-${last_good_task_id}" --format=%H -n 1)

# Rollback to that checkpoint
git reset --hard $last_good_commit

# Update CONTINUITY.md
echo "ROLLBACK: Reset to task-${last_good_task_id} (commit: $last_good_commit)" >> .loki/CONTINUITY.md

# Re-queue failed tasks
move_tasks_to_pending after_task=$last_good_task_id
```

### Benefits

1. **Instant Rollback:** Every task is a save point
2. **Clear History:** Git log shows exact task progression
3. **Proof of Progress:** Commit SHAs in CONTINUITY.md
4. **Blame Tracking:** Know which agent created which code
5. **Audit Trail:** Full history of what changed when

## Agent Lineage & Context Preservation

**CRITICAL:** All agents MUST inherit and preserve context from their spawning agent to prevent context drift.

### Lineage Tracking Protocol

**On Agent Spawn:**
```typescript
// When spawning a new agent
function spawnAgent(config: {
    agent_type: string,
    task_id: string,
    parent_agent_id: string
}) {
    const agent_id = generateAgentId(); // e.g., "eng-001-backend-api"

    // Inherit context from parent
    const parent_context = readAgentContext(config.parent_agent_id);

    const agent_context = {
        agent_id,
        agent_type: config.agent_type,
        model: config.model || "sonnet",
        spawned_at: new Date().toISOString(),
        spawned_by: config.parent_agent_id,
        lineage: [...parent_context.lineage, agent_id],

        // Inherited context (immutable)
        inherited_context: {
            phase: parent_context.phase,
            current_task: config.task_id,
            spec_reference: parent_context.spec_reference,
            tech_stack: parent_context.tech_stack,
            architecture_decisions: parent_context.architecture_decisions,
            constraints: parent_context.constraints
        },

        // Agent-specific context (mutable)
        decisions_made: [],
        tasks_completed: [],
        commits_created: [],
        questions_asked: [],

        status: "spawned"
    };

    // Write to .agent/sub-agents/
    fs.writeFileSync(
        `.agent/sub-agents/${agent_id}.json`,
        JSON.stringify(agent_context, null, 2)
    );

    // Update lineage tree
    updateLineageTree(agent_id, config.parent_agent_id);

    return agent_id;
}
```

### Agent Context Schema

**File:** `.agent/sub-agents/{agent-id}.json`

```json
{
  "agent_id": "eng-001-backend-api",
  "agent_type": "general-purpose",
  "model": "haiku",
  "spawned_at": "2026-01-04T05:30:00Z",
  "spawned_by": "orchestrator-main",
  "lineage": ["orchestrator-main", "eng-001-backend-api"],

  "inherited_context": {
    "phase": "development",
    "current_task": "task-005",
    "spec_reference": ".loki/specs/openapi.yaml#/paths/~1api~1todos",
    "tech_stack": ["Node.js", "Express", "TypeScript", "SQLite"],
    "architecture_decisions": [
      "Use REST over GraphQL for simplicity",
      "Use SQLite for zero-config persistence"
    ],
    "constraints": [
      "No external dependencies without approval",
      "Maximum 200ms response time",
      "100% test coverage on critical paths"
    ]
  },

  "decisions_made": [
    {
      "timestamp": "2026-01-04T05:31:15Z",
      "question": "Should we use Prisma or raw SQL?",
      "answer": "Raw SQL with better-sqlite3",
      "rationale": "PRD requires minimal dependencies, synchronous ops preferred",
      "alternatives_considered": ["Prisma", "TypeORM", "Knex.js"]
    }
  ],

  "tasks_completed": ["task-005", "task-006"],
  "commits_created": ["abc123f", "def456a"],
  "questions_asked": [
    {
      "timestamp": "2026-01-04T05:30:30Z",
      "question": "Should todos have due dates?",
      "answer": "No - keeping MVP minimal per PRD",
      "source": "inferred_from_prd"
    }
  ],

  "status": "completed",
  "completed_at": "2026-01-04T05:45:00Z"
}
```

### Lineage Tree Structure

**File:** `.agent/lineage.json`

```json
{
  "orchestrator-main": {
    "spawned_at": "2026-01-04T05:00:00Z",
    "children": [
      "eng-001-backend-api",
      "eng-002-frontend-ui",
      "qa-001-contract-tests"
    ]
  },
  "eng-001-backend-api": {
    "spawned_at": "2026-01-04T05:30:00Z",
    "parent": "orchestrator-main",
    "children": []
  },
  "eng-002-frontend-ui": {
    "spawned_at": "2026-01-04T06:00:00Z",
    "parent": "orchestrator-main",
    "children": [
      "eng-003-component-library"
    ]
  }
}
```

### Context Preservation Rules

1. **Immutable Inheritance:** Agents CANNOT modify inherited context
2. **Decision Logging:** All decisions MUST be logged to agent context file
3. **Lineage Reference:** All commits MUST reference parent agent ID
4. **Question Tracking:** Agents MUST log clarifying questions and answers
5. **Context Handoff:** When agent completes, context is archived but lineage preserved

### Preventing Context Drift

**Problem:** Multiple agents with inconsistent understanding of project state.

**Solution:**
1. Read `.agent/sub-agents/${parent_id}.json` before spawning
2. Inherit immutable context (tech stack, constraints, decisions)
3. Log all new decisions to own context file
4. Reference lineage in all commits
5. Periodic context sync: check if inherited context has been updated upstream

### Benefits

1. **No Context Drift:** All agents see same project state
2. **Decision Auditability:** Know why every choice was made
3. **Blame Chain:** Trace decisions back to spawning agent
4. **Learning:** Successor agents see previous agents' decisions
5. **Debugging:** Full context trail for troubleshooting

## Constitution: Machine-Enforceable Rules

**CRITICAL:** All agent behavior is governed by `autonomy/CONSTITUTION.md` - a machine-enforceable contract.

### Core Principles (Reference Only - Full Details in CONSTITUTION.md)

1. **Specification-First Development:** No code before spec exists
2. **Git Checkpoint System:** Every task completion creates commit
3. **Context Preservation:** All agents inherit from parent
4. **Iterative Specification Questions:** Ask before assuming
5. **Machine-Readable Rules:** JSON/YAML over markdown prose

### Quality Gates (From Constitution)

**Pre-Commit (BLOCKING):**
- Linting (auto-fix enabled)
- Type checking (strict mode)
- Contract tests (80% coverage minimum)
- Spec validation (Spectral)

**Post-Implementation (AUTO-FIX):**
- Static analysis (ESLint, Prettier, TSC)
- Security scan (Semgrep, Snyk)
- Performance check (Lighthouse score 90+)

### Runtime Invariants

All agents MUST pass these assertions:
- `SPEC_BEFORE_CODE`: Implementation tasks require spec reference
- `TASK_HAS_COMMIT`: Completed tasks have git commit SHA
- `AGENT_HAS_LINEAGE`: All agents have lineage array
- `CONTINUITY_EXISTS`: CONTINUITY.md must always exist
- `QUALITY_GATES_PASSED`: Completed tasks passed all quality checks

**See:** `autonomy/CONSTITUTION.md` for full behavioral contract.

## Spec-Driven Development (SDD)

**CRITICAL:** Specifications are the shared source of truth. Write specs BEFORE code, not after.

### Philosophy: Specification as Contract

Traditional approach (BAD):
```
Code → Tests → Documentation → API Spec (if we're lucky)
```

Spec-Driven approach (GOOD):
```
Spec → Tests from Spec → Code to Satisfy Spec → Validation
```

**Benefits:**
- Spec is executable contract between frontend/backend
- Prevents API drift and breaking changes
- Enables parallel development (frontend mocks from spec)
- AI agents have clear target to implement against
- Documentation is always accurate (generated from spec)

### Spec-First Workflow

**Phase 1: Specification Generation (BEFORE Architecture)**

1. **Parse PRD and Extract API Requirements**
   ```bash
   # Identify all user-facing functionality
   # Map to API operations (CRUD, searches, workflows)
   # Document data models and relationships
   ```

2. **Generate OpenAPI 3.1 Specification**
   ```yaml
   openapi: 3.1.0
   info:
     title: Product API
     version: 1.0.0
   paths:
     /auth/login:
       post:
         summary: Authenticate user and return JWT
         requestBody:
           required: true
           content:
             application/json:
               schema:
                 type: object
                 required: [email, password]
                 properties:
                   email: { type: string, format: email }
                   password: { type: string, minLength: 8 }
         responses:
           200:
             description: Success
             content:
               application/json:
                 schema:
                   type: object
                   properties:
                     token: { type: string }
                     expiresAt: { type: string, format: date-time }
           401:
             description: Invalid credentials
   components:
     schemas:
       User:
         type: object
         required: [id, email, createdAt]
         properties:
           id: { type: string, format: uuid }
           email: { type: string, format: email }
           name: { type: string }
           createdAt: { type: string, format: date-time }
   ```

3. **Validate Spec**
   ```bash
   # Install OpenAPI tools
   npm install -g @stoplight/spectral-cli

   # Lint the spec
   spectral lint .loki/specs/openapi.yaml

   # Validate against OpenAPI 3.1 schema
   swagger-cli validate .loki/specs/openapi.yaml
   ```

4. **Generate Artifacts from Spec**
   ```bash
   # Generate TypeScript types
   npx openapi-typescript .loki/specs/openapi.yaml --output src/types/api.ts

   # Generate client SDK
   npx openapi-generator-cli generate \
     -i .loki/specs/openapi.yaml \
     -g typescript-axios \
     -o src/clients/api

   # Generate server stubs
   npx openapi-generator-cli generate \
     -i .loki/specs/openapi.yaml \
     -g nodejs-express-server \
     -o backend/generated

   # Generate documentation
   npx redoc-cli bundle .loki/specs/openapi.yaml -o docs/api.html
   ```

**Phase 2: Contract Testing**

Implement contract tests BEFORE implementation:

```typescript
// tests/contract/auth.contract.test.ts
import { OpenAPIValidator } from 'express-openapi-validator';
import spec from '../../.loki/specs/openapi.yaml';

describe('Auth API Contract', () => {
  const validator = new OpenAPIValidator({ apiSpec: spec });

  it('POST /auth/login validates against spec', async () => {
    const request = {
      method: 'POST',
      path: '/auth/login',
      body: { email: 'user@example.com', password: 'password123' }
    };

    const response = {
      statusCode: 200,
      body: {
        token: 'eyJhbGc...',
        expiresAt: '2025-01-03T10:00:00Z'
      }
    };

    // Validate request/response match spec
    await validator.validate(request, response);
  });

  it('POST /auth/login rejects invalid email', async () => {
    const request = {
      method: 'POST',
      path: '/auth/login',
      body: { email: 'not-an-email', password: 'password123' }
    };

    // Should fail validation
    await expect(validator.validate(request, {})).rejects.toThrow();
  });
});
```

**Phase 3: Implementation Against Spec**

Agents implement ONLY what's in the spec:

```markdown
## GOAL
Implement /auth/login endpoint that EXACTLY matches .loki/specs/openapi.yaml specification

## CONSTRAINTS
- MUST validate all requests against openapi.yaml schema
- MUST return responses matching spec (status codes, schemas)
- NO additional fields not in spec
- NO missing required fields from spec
- Performance: <200ms p99 (as documented in spec x-performance)

## VALIDATION
Before marking complete:
1. Run contract tests: npm run test:contract
2. Validate implementation: spectral lint .loki/specs/openapi.yaml
3. Test with Postman collection (auto-generated from spec)
4. Verify documentation matches implementation
```

**Phase 4: Continuous Spec Validation**

In CI/CD pipeline:

```yaml
# .github/workflows/spec-validation.yml
name: Spec Validation

on: [push, pull_request]

jobs:
  validate-spec:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3

      # Validate OpenAPI spec
      - name: Validate OpenAPI
        run: |
          npm install -g @stoplight/spectral-cli
          spectral lint .loki/specs/openapi.yaml --fail-severity warn

      # Check for breaking changes
      - name: Detect Breaking Changes
        run: |
          npx @openapitools/openapi-diff \
            origin/main:.loki/specs/openapi.yaml \
            HEAD:.loki/specs/openapi.yaml \
            --fail-on-incompatible

      # Run contract tests
      - name: Contract Tests
        run: npm run test:contract

      # Validate implementation matches spec
      - name: Validate Implementation
        run: |
          # Start server in background
          npm start &
          sleep 5

          # Test all endpoints against spec
          npx @schemathesis/schemathesis run \
            .loki/specs/openapi.yaml \
            --base-url http://localhost:3000 \
            --checks all
```

### Spec Evolution & Versioning

**When to Version:**
- Breaking changes: increment major version (v1 → v2)
- New endpoints/fields: increment minor version (v1.0 → v1.1)
- Bug fixes: increment patch version (v1.0.0 → v1.0.1)

**Maintaining Backwards Compatibility:**

```yaml
# Support multiple versions simultaneously
paths:
  /v1/auth/login:  # Old version
    post:
      deprecated: true
      description: Use /v2/auth/login instead

  /v2/auth/login:  # New version
    post:
      summary: Enhanced login with MFA support
```

**Migration Path:**
1. Announce deprecation in spec (with sunset date)
2. Add deprecation warnings to v1 responses
3. Give clients 6 months to migrate
4. Remove v1 endpoints

### Spec-Driven Development Checklist

For EVERY new feature:
- [ ] PRD requirement identified
- [ ] OpenAPI spec written/updated FIRST
- [ ] Spec validated with Spectral
- [ ] TypeScript types generated from spec
- [ ] Contract tests written
- [ ] Implementation developed against spec
- [ ] Contract tests pass
- [ ] Documentation auto-generated from spec
- [ ] Breaking change analysis run
- [ ] Postman collection updated

**Store specs in:** `.loki/specs/openapi.yaml`

**Spec takes precedence over:**
- PRD (if conflict, update PRD to match agreed spec)
- Code (if code doesn't match spec, code is wrong)
- Documentation (docs are generated FROM spec)

## Model Context Protocol (MCP) Integration

**CRITICAL:** Loki Mode agents communicate using standardized MCP protocol for composability and interoperability.

### MCP Architecture

**What is MCP?**
- Standardized protocol for AI agents and tools to exchange context
- Enables modular "ingredient" composition (browser automation, knowledge systems, GitHub tools)
- Allows multiple AI agents (Anthropic, OpenAI, Google) to collaborate on shared tasks

**Loki Mode as MCP Ecosystem:**

```
┌─────────────────────────────────────────────────────────────┐
│                   Loki Mode Orchestrator                    │
│                (MCP Server Coordinator)                     │
└─────────────────────────────────────────────────────────────┘
                           │
        ┌──────────────────┼──────────────────┐
        │                  │                  │
┌───────▼────────┐  ┌──────▼───────┐  ┌──────▼───────┐
│  MCP Server:   │  │ MCP Server:  │  │ MCP Server:  │
│   Engineering  │  │  Operations  │  │   Business   │
│     Swarm      │  │    Swarm     │  │    Swarm     │
└────────────────┘  └──────────────┘  └──────────────┘
        │                  │                  │
    ┌───┴───┐          ┌───┴───┐          ┌───┴───┐
    │ Agent │          │ Agent │          │ Agent │
    │ Agent │          │ Agent │          │ Agent │
    │ Agent │          │ Agent │          │ Agent │
    └───────┘          └───────┘          └───────┘
```

### MCP Server Implementation

Each swarm is an MCP server exposing tools and resources:

```typescript
// .loki/mcp/servers/engineering-swarm.ts
import { McpServer } from '@modelcontextprotocol/sdk';

const server = new McpServer({
  name: 'loki-engineering-swarm',
  version: '1.0.0',
  description: 'Engineering swarm: frontend, backend, database, mobile, QA agents'
});

// Register tools (agent capabilities)
server.addTool({
  name: 'implement-feature',
  description: 'Implement a feature from specification',
  parameters: {
    type: 'object',
    properties: {
      spec: { type: 'string', description: 'OpenAPI spec path' },
      feature: { type: 'string', description: 'Feature to implement' },
      goal: { type: 'string', description: 'What success looks like' },
      constraints: {
        type: 'array',
        items: { type: 'string' },
        description: 'Implementation constraints'
      }
    },
    required: ['spec', 'feature', 'goal']
  },
  handler: async (params) => {
    // Dispatch to appropriate agent
    const agent = selectAgent(params.feature);
    return await agent.implement(params);
  }
});

server.addTool({
  name: 'review-code',
  description: 'Run 3-stage code review (static analysis + A

…(truncated)
