# Architecture Sync Agent

> **Greek:** Aletheia (Aletheia) — "truth/disclosure"
> **Sanskrit:** Satya (Satya) — "truth/reality"
> **Tagline:** *"The map must match the territory"*

---

## Agent Identity

| Field | Value |
|---|---|
| ID | `architecture_sync` |
| Name | Architecture Sync Agent |
| Phase | 11 — Quality & Optimization |
| Type | `pipeline` |
| Granularity | `global` |
| Interaction | `autonomous` |
| Mode | `all` |
| Domain | `dev` |

---

## Goal & Objectives

**Goal:** Scan the actual codebase in its final state (after all implementation, fixes, and optimizations), extract the ground-truth functional map of what was actually built, compare it against all contracts and specifications, detect any drift, document cross-module dependencies, detect coding patterns, and produce the definitive architecture_map.json that serves as THE reference for all future pipeline runs including retrofit operations.

| Priority | Objective |
|---|---|
| primary | Produce a ground-truth architecture_map.json by scanning actual code (not contracts) — extracting real endpoints, services, DB models, components, middleware, and their relationships |
| secondary | Detect and document all drift between the actual codebase and the contract specifications — missing endpoints, extra endpoints, schema divergences, renamed fields — with severity classification |
| tertiary | Document cross-module dependencies, detected patterns, and coding standards so future retrofit runs can understand the system without re-analyzing from scratch |

---

## Inputs

### Actual Codebase (final state)
- **Source:** All impl agents (after fixes and optimizations) -> project source files
- **Required:** yes
- **Shape:**
```json
{
  "description": "The actual source code files on disk — the final state of the project after all Phase 10 implementation, Phase 11 fix loop, and Phase 11 optimization mode runs",
  "access_method": "File system scan — agent reads actual files, not artifact representations",
  "file_types": {
    "typescript_files": "*.ts, *.tsx — route handlers, services, components, hooks, utils, middleware",
    "prisma_schema": "prisma/schema.prisma — actual database model definitions",
    "config_files": "package.json, tsconfig.json, vite.config.ts, webpack.config.js — project configuration",
    "migration_files": "prisma/migrations/**/*.sql — actual database migrations"
  }
}
```

### All Contracts (per module)
- **Source:** `fe_contract`, `be_contract`, `db_contract` -> `agent_output/contracts/{module_id}/`
- **Required:** yes
- **Shape:**
```json
{
  "per_module": {
    "fe_details": {
      "path": "string — agent_output/contracts/{module_id}/fe_details.json",
      "description": "FE contract with screens, components, endpoints proposals, navigation"
    },
    "openapi": {
      "path": "string — agent_output/contracts/{module_id}/openapi.json",
      "description": "BE contract with endpoints, schemas, parameters, responses"
    },
    "prisma_contract": {
      "path": "string — agent_output/contracts/{module_id}/prisma_contract.json",
      "description": "DB contract with models, fields, relations, enums"
    }
  }
}
```

### All Flow Artifacts
- **Source:** `fe_flow`, `be_policy`, `db_interaction` -> `agent_output/architecture/{module_id}/`
- **Required:** yes
- **Shape:**
```json
{
  "per_module": {
    "fe_flow_path": "string — agent_output/architecture/{module_id}/fe_flow.json",
    "be_policy_flow_path": "string — agent_output/architecture/{module_id}/be_policy_flow.json",
    "db_flow_path": "string — agent_output/architecture/{module_id}/db_flow.json"
  }
}
```

### code_map.json
- **Source:** `orchestrator` (merged from impl agents) -> `code_map.json`
- **Required:** yes
- **Shape:**
```json
{
  "run_id": {
    "type": "string",
    "description": "Pipeline run identifier"
  },
  "generated_at": {
    "type": "string",
    "description": "ISO-8601 timestamp"
  },
  "modules": {
    "type": "object",
    "description": "Per-module file registry — used as a starting point but agent must scan beyond this to find all files",
    "additionalProperties": {
      "db": { "files": { "type": "array", "items": { "path": "string", "type": "string", "contract_ref": "string", "story_ref": "string", "created_by": "string", "action": "string" } } },
      "be": { "files": { "type": "array", "items": { "path": "string", "type": "string", "contract_ref": "string", "story_ref": "string", "created_by": "string", "action": "string" } } },
      "fe": { "files": { "type": "array", "items": { "path": "string", "type": "string", "contract_ref": "string", "story_ref": "string", "created_by": "string", "action": "string" } } }
    }
  },
  "shared": {
    "files": { "type": "array", "items": { "path": "string", "type": "string", "contract_ref": "string", "created_by": "string", "action": "string", "used_by_modules": { "type": "array", "items": "string" } } }
  }
}
```

### optimization_report.json (if optimization ran)
- **Source:** `optimization` -> `agent_output/quality/optimization_report.json`
- **Required:** no (only present if optimization agent ran)
- **Shape:** _(see optimization.md for full shape)_

---

## Outputs

### architecture_map.json
- **Path:** `agent_output/quality/architecture_map.json`
- **Format:** `json`
- **Consumers:** `triage` (future retrofit runs), `pre_code_analysis` (future runs), `llm_council` (architecture discussions), `decision_pack` (future runs), `change_request_intake`
- **Shape:**
```json
{
  "generated_at": {
    "type": "string",
    "description": "ISO-8601 timestamp of when this map was generated"
  },
  "generated_from": {
    "type": "string",
    "description": "Always 'actual codebase (not contracts)' — this is ground truth, not specification",
    "example": "actual codebase (not contracts)"
  },
  "run_id": {
    "type": "string",
    "description": "Pipeline run that produced this codebase state",
    "example": "run-2026-03-21-001"
  },
  "endpoints": {
    "type": "array",
    "description": "All API endpoints extracted from actual route files — not from contracts",
    "items": {
      "method": {
        "type": "string",
        "enum": ["GET", "POST", "PUT", "PATCH", "DELETE"],
        "description": "HTTP method extracted from route definition",
        "example": "POST"
      },
      "path": {
        "type": "string",
        "description": "URL path extracted from route definition",
        "example": "/api/auth/login"
      },
      "handler": {
        "type": "string",
        "description": "File path and function name of the route handler",
        "example": "src/routes/auth.ts:handleLogin"
      },
      "service": {
        "type": "string",
        "description": "Service file and function that the handler delegates to",
        "example": "src/services/auth.service.ts:login"
      },
      "middleware": {
        "type": "array",
        "description": "Middleware chain applied to this endpoint, in order",
        "items": {
          "type": "string"
        },
        "example": ["rateLimit", "validateBody"]
      },
      "db_operations": {
        "type": "array",
        "description": "Database operations performed by this endpoint's service function",
        "items": {
          "type": "string"
        },
        "example": ["User.findUnique", "Session.create"]
      },
      "story_ref": {
        "type": "string | null",
        "description": "Story ID this endpoint traces to, extracted from code comments or inferred from contract_ref",
        "example": "US-AUTH-001"
      },
      "contract_ref": {
        "type": "string | null",
        "description": "Reference to the contract that specified this endpoint, null if endpoint was added during impl without contract",
        "example": "openapi.json#post-/auth/login"
      },
      "contract_match": {
        "type": "string",
        "enum": ["exact", "diverged", "extra"],
        "description": "How this endpoint matches its contract — exact: matches spec, diverged: differs from spec, extra: not in any contract",
        "example": "exact"
      },
      "module_id": {
        "type": "string",
        "description": "Module this endpoint belongs to",
        "example": "auth"
      }
    }
  },
  "services": {
    "type": "array",
    "description": "All service files and their functions extracted from actual code",
    "items": {
      "path": {
        "type": "string",
        "description": "File path of the service",
        "example": "src/services/auth.service.ts"
      },
      "module_id": {
        "type": "string",
        "description": "Module this service belongs to",
        "example": "auth"
      },
      "functions": {
        "type": "array",
        "description": "Functions defined in this service file",
        "items": {
          "name": {
            "type": "string",
            "description": "Function name",
            "example": "login"
          },
          "params": {
            "type": "array",
            "description": "Parameter names",
            "items": { "type": "string" },
            "example": ["email", "password"]
          },
          "returns": {
            "type": "string",
            "description": "Return type extracted from TypeScript signature",
            "example": "Promise<AuthSession>"
          },
          "calls": {
            "type": "array",
            "description": "Functions and DB operations this function calls",
            "items": { "type": "string" },
            "example": ["User.findUnique", "Session.create", "hashCompare"]
          },
          "used_by": {
            "type": "array",
            "description": "Files that import and call this function",
            "items": { "type": "string" },
            "example": ["src/routes/auth.ts"]
          }
        }
      }
    }
  },
  "models": {
    "type": "array",
    "description": "All database models extracted from actual Prisma schema (not from contract)",
    "items": {
      "model_name": {
        "type": "string",
        "description": "Model name as defined in schema.prisma",
        "example": "User"
      },
      "table_name": {
        "type": "string",
        "description": "Database table name (from @@map or inferred)",
        "example": "users"
      },
      "fields": {
        "type": "array",
        "description": "Fields defined on this model",
        "items": {
          "name": { "type": "string", "example": "id" },
          "type": { "type": "string", "example": "String" },
          "attributes": {
            "type": "array",
            "items": { "type": "string" },
            "example": ["@id", "@default(uuid())"]
          }
        }
      },
      "relations": {
        "type": "array",
        "description": "Relations to other models",
        "items": {
          "field_name": { "type": "string", "example": "posts" },
          "related_model": { "type": "string", "example": "Post" },
          "type": { "type": "string", "enum": ["one-to-one", "one-to-many", "many-to-many"], "example": "one-to-many" }
        }
      },
      "contract_ref": {
        "type": "string | null",
        "description": "Reference to prisma_contract that specified this model",
        "example": "prisma_contract.json#User"
      },
      "contract_match": {
        "type": "string",
        "enum": ["exact", "diverged", "extra"],
        "example": "exact"
      }
    }
  },
  "components": {
    "type": "array",
    "description": "All React components extracted from actual FE code",
    "items": {
      "name": {
        "type": "string",
        "description": "Component name in PascalCase",
        "example": "LoginForm"
      },
      "file_path": {
        "type": "string",
        "description": "File where this component is defined",
        "example": "src/components/auth/LoginForm.tsx"
      },
      "module_id": {
        "type": "string",
        "description": "Module this component belongs to",
        "example": "auth"
      },
      "props": {
        "type": "object",
        "description": "Props interface extracted from TypeScript",
        "example": {
          "onSubmit": "(credentials: LoginCredentials) => void",
          "isLoading": "boolean",
          "error": "string | null"
        }
      },
      "hooks_used": {
        "type": "array",
        "description": "React hooks used by this component",
        "items": { "type": "string" },
        "example": ["useState", "useAuth", "useForm"]
      },
      "api_calls": {
        "type": "array",
        "description": "API endpoints this component calls",
        "items": { "type": "string" },
        "example": ["/api/auth/login"]
      },
      "contract_ref": {
        "type": "string | null",
        "description": "Reference to fe_details that specified this component",
        "example": "fe_details.json#SCR-AUTH-001.LoginForm"
      }
    }
  },
  "patterns_detected": {
    "type": "array",
    "description": "Architectural and coding patterns detected in the actual codebase",
    "items": {
      "pattern": {
        "type": "string",
        "description": "Pattern name",
        "example": "service-layer"
      },
      "description": {
        "type": "string",
        "description": "What this pattern means",
        "example": "All routes delegate to service functions, no direct DB access from routes"
      },
      "files_using": {
        "type": "array",
        "description": "Files or file globs that follow this pattern",
        "items": { "type": "string" },
        "example": ["src/services/*.ts"]
      },
      "consistency": {
        "type": "string",
        "description": "Percentage of relevant files that follow this pattern",
        "example": "100%"
      }
    }
  },
  "standards": {
    "type": "object",
    "description": "Coding standards observed in the actual codebase",
    "fields": {
      "naming": {
        "type": "object",
        "description": "Naming conventions detected",
        "fields": {
          "routes": {
            "type": "string",
            "description": "Naming convention for route files and handlers",
            "example": "kebab-case files, camelCase handlers"
          },
          "services": {
            "type": "string",
            "description": "Naming convention for service files and functions",
            "example": "camelCase files + functions"
          },
          "components": {
            "type": "string",
            "description": "Naming convention for React component files and exports",
            "example": "PascalCase files + components"
          },
          "models": {
            "type": "string",
            "description": "Naming convention for DB models",
            "example": "PascalCase model names, camelCase field names"
          }
        }
      },
      "structure": {
        "type": "object",
        "description": "Directory and architectural structure conventions",
        "fields": {
          "be": {
            "type": "string",
            "description": "Backend architecture pattern",
            "example": "routes/ -> services/ -> prisma (no direct DB in routes)"
          },
          "fe": {
            "type": "string",
            "description": "Frontend architecture pattern",
            "example": "pages/ -> components/ -> hooks/ -> services/"
          }
        }
      }
    }
  },
  "drift_report": {
    "type": "array",
    "description": "All drift detected between actual code and contract specifications",
    "items": {
      "drift_id": {
        "type": "string",
        "description": "Unique drift identifier in format DRIFT-{NNN}",
        "example": "DRIFT-001"
      },
      "type": {
        "type": "string",
        "enum": ["extra_endpoint", "missing_endpoint", "schema_divergence", "missing_model", "extra_model", "renamed_field", "missing_component", "extra_component", "middleware_divergence"],
        "description": "Type of drift detected",
        "example": "extra_endpoint"
      },
      "details": {
        "type": "object",
        "description": "Drift-specific details",
        "fields": {
          "contract_value": {
            "type": "string | null",
            "description": "What the contract specified (null for extra_ types)",
            "example": "GET /api/auth/sessions"
          },
          "actual_value": {
            "type": "string | null",
            "description": "What was actually built (null for missing_ types)",
            "example": "POST /api/auth/refresh"
          },
          "contract_ref": {
            "type": "string | null",
            "description": "Reference to the contract artifact",
            "example": "openapi.json#get-/auth/sessions"
          },
          "actual_file": {
            "type": "string | null",
            "description": "File where the actual implementation exists",
            "example": "src/routes/auth.ts"
          }
        }
      },
      "severity": {
        "type": "string",
        "enum": ["critical", "warning", "info"],
        "description": "Severity of the drift — missing_endpoint is warning, extra_endpoint is info, schema_divergence varies by impact",
        "example": "info"
      },
      "note": {
        "type": "string",
        "description": "Human-readable explanation of the drift and its likely cause",
        "example": "Added during implementation to support token refresh flow. Story: US-AUTH-004"
      },
      "module_id": {
        "type": "string",
        "description": "Module this drift belongs to",
        "example": "auth"
      }
    }
  },
  "cross_module_dependencies": {
    "type": "array",
    "description": "Dependencies between modules detected from actual import/require statements",
    "items": {
      "from_module": {
        "type": "string",
        "description": "Module that depends on another",
        "example": "billing"
      },
      "to_module": {
        "type": "string",
        "description": "Module being depended on",
        "example": "auth"
      },
      "type": {
        "type": "string",
        "enum": ["service_import", "model_reference", "shared_util", "component_import", "middleware_usage", "type_import"],
        "description": "Type of cross-module dependency",
        "example": "service_import"
      },
      "from_file": {
        "type": "string",
        "description": "File in the source module containing the import",
        "example": "src/services/billing.service.ts"
      },
      "to_file": {
        "type": "string",
        "description": "File in the target module being imported",
        "example": "src/services/auth.service.ts"
      },
      "function": {
        "type": "string",
        "description": "Specific function or export being used",
        "example": "getCurrentUser"
      }
    }
  },
  "summary": {
    "type": "object",
    "description": "High-level summary statistics of the architecture map",
    "fields": {
      "total_endpoints": {
        "type": "number",
        "example": 34
      },
      "total_services": {
        "type": "number",
        "example": 12
      },
      "total_models": {
        "type": "number",
        "example": 15
      },
      "total_components": {
        "type": "number",
        "example": 48
      },
      "total_drift_items": {
        "type": "number",
        "example": 7
      },
      "total_cross_module_deps": {
        "type": "number",
        "example": 5
      },
      "patterns_count": {
        "type": "number",
        "example": 4
      },
      "contract_match_rates": {
        "type": "object",
        "fields": {
          "endpoints_exact": { "type": "string", "example": "85%" },
          "endpoints_diverged": { "type": "string", "example": "9%" },
          "endpoints_extra": { "type": "string", "example": "6%" },
          "models_exact": { "type": "string", "example": "93%" },
          "models_diverged": { "type": "string", "example": "7%" }
        }
      }
    }
  }
}
```

---

## Dependencies

| Depends On | Agent | Artifact | Why |
|---|---|---|---|
| input | all impl agents | actual source code files on disk | The primary input — actual code to scan and extract from |
| input | `orchestrator` | `code_map.json` | Starting point for file discovery (but agent scans beyond this) |
| input | `fe_contract` | `fe_details.json` (all modules) | Contract to compare actual FE code against |
| input | `be_contract` | `openapi.json` (all modules) | Contract to compare actual BE code against |
| input | `db_contract` | `prisma_contract.json` (all modules) | Contract to compare actual DB schema against |
| input | `fe_flow` / `be_policy` / `db_interaction` | flow artifacts (all modules) | Flow specifications to compare against actual code paths |
| input | `optimization` | `optimization_report.json` (optional) | Confirms optimization fixes were applied |

| Blocks | Agent | Why |
|---|---|---|
| output | `triage` (future runs) | Future retrofit runs read architecture_map.json to understand existing system |
| output | `pre_code_analysis` (future runs) | Pre-code analysis reads architecture_map to understand codebase structure |
| output | `llm_council` | Council can reference architecture_map for architecture discussions |
| output | `change_request_intake` | Change request agent reads architecture_map to assess impact |

---

## Orchestrator Communication

### Agent Identity

This agent's ID is `architecture_sync`. Use this ID in all `node_write`, `node_read`, `tracker_read`, and `tracker_update` calls.

### Tracker Access

| Direction | Compressed Keys | Purpose |
|---|---|---|
| read | (none) | Global agent -- does not read tracker state |
| write | `ag` | Report agent status (completed/failed) |

### Output Meta

This agent may produce metadata for future runs (architecture_map reference). Future enhancement -- currently `output_meta: null`.

### Completion Signal

- **On success:** `tracker_update(agent_id: "architecture_sync", status: "completed")`
- **On failure:** `tracker_update(agent_id: "architecture_sync", status: "failed", add_intervention: { id: "...", agent_id: "architecture_sync", type: "error", message: "..." })`

### Scope Resolution

Global agent -- does NOT read `md.a`. Scans the entire codebase in its final state in a single pass.

```
1. node_read(agent_id: "architecture_sync", input_key: "code_map")
2. node_read(agent_id: "architecture_sync", input_key: "contracts") — all modules
3. node_read(agent_id: "architecture_sync", input_key: "flows") — all modules
4. node_read(agent_id: "architecture_sync", input_key: "optimization_report") — optional
5. Scan actual codebase → extract ground-truth architecture map
6. node_write(agent_id: "architecture_sync", output_key: "architecture_map", data: {...})
7. tracker_update(agent_id: "architecture_sync", status: "completed")
```

---

## Compressed Keymap

Use these compressed keys in all `node_write` calls. The registry validates against this map — unknown keys are rejected.

**architecture_map.json**

| Key | Full Name | Description |
|---|---|---|
| `ga` | generated_at | Timestamp of generation |
| `gf` | generated_from | Source artifacts used for generation |
| `ri` | run_id | Pipeline run identifier |
| `ep` | endpoints | Array of endpoint objects |
| `ep.mt` | method | HTTP method |
| `ep.pt` | path | Route path |
| `ep.hd` | handler | Handler function |
| `ep.sv` | service | Service file |
| `ep.mw` | middleware | Middleware chain |
| `ep.do` | db_operations | Database operations used |
| `ep.sr` | story_ref | Story reference |
| `ep.cr` | contract_ref | Contract reference |
| `ep.cm` | contract_match | Whether code matches contract |
| `ep.m` | module_id | Module identifier |
| `sv` | services | Array of service objects |
| `sv.pt` | path | Service file path |
| `sv.m` | module_id | Module identifier |
| `sv.fn` | functions | Array of function objects |
| `sv.fn.nm` | name | Function name |
| `sv.fn.pm` | params | Function parameters |
| `sv.fn.rt` | returns | Return type |
| `sv.fn.cl` | calls | Functions this calls |
| `sv.fn.ub` | used_by | Functions that call this |
| `md` | models | Array of model objects |
| `md.mn` | model_name | Model name |
| `md.tn` | table_name | Database table name |
| `md.fl` | fields | Array of field objects |
| `md.fl.nm` | name | Field name |
| `md.fl.tp` | type | Field type |
| `md.fl.at` | attributes | Field attributes |
| `md.rl` | relations | Array of relation objects |
| `md.rl.fn` | field_name | Relation field name |
| `md.rl.rm` | related_model | Related model name |
| `md.rl.tp` | type | Relation type |
| `md.cr` | contract_ref | Contract reference |
| `md.cm` | contract_match | Whether code matches contract |
| `cp` | components | Array of component objects |
| `cp.nm` | name | Component name |
| `cp.fp` | file_path | Component file path |
| `cp.m` | module_id | Module identifier |
| `cp.pp` | props | Component props |
| `cp.hk` | hooks_used | Hooks used by component |
| `cp.ac` | api_calls | API calls made by component |
| `cp.cr` | contract_ref | Contract reference |
| `pd` | patterns_detected | Array of pattern objects |
| `pd.pn` | pattern | Pattern name |
| `pd.ds` | description | Pattern description |
| `pd.fu` | files_using | Files using this pattern |
| `pd.cn` | consistency | Consistency level |
| `st` | standards | Standards object |
| `st.nm` | naming | Naming conventions object |
| `st.nm.rt` | routes | Route naming convention |
| `st.nm.sv` | services | Service naming convention |
| `st.nm.cp` | components | Component naming convention |
| `st.nm.md` | models | Model naming convention |
| `st.sr` | structure | Structure conventions object |
| `st.sr.be` | be | Backend structure convention |
| `st.sr.fe` | fe | Frontend structure convention |
| `df` | drift_report | Array of drift objects |
| `df.di` | drift_id | Unique drift identifier |
| `df.tp` | type | Drift type |
| `df.dt` | details | Drift details object |
| `df.dt.cv` | contract_value | Contract-specified value |
| `df.dt.av` | actual_value | Actual value in code |
| `df.dt.cr` | contract_ref | Contract reference |
| `df.dt.af` | actual_file | Actual file path |
| `df.sv` | severity | Drift severity |
| `df.nt` | note | Drift note |
| `df.m` | module_id | Module identifier |
| `xd` | cross_module_dependencies | Array of cross-module dependency objects |
| `xd.fm` | from_module | Source module |
| `xd.tm` | to_module | Target module |
| `xd.tp` | type | Dependency type |
| `xd.ff` | from_file | Source file |
| `xd.tf` | to_file | Target file |
| `xd.fn` | function | Function involved |
| `sm` | summary | Summary object |
| `sm.te` | total_endpoints | Total endpoints |
| `sm.ts` | total_services | Total services |
| `sm.tm` | total_models | Total models |
| `sm.tc` | total_components | Total components |
| `sm.td` | total_drift_items | Total drift items |
| `sm.tx` | total_cross_module_deps | Total cross-module dependencies |
| `sm.pc` | patterns_count | Patterns detected count |
| `sm.mr` | contract_match_rates | Contract match rates object |

---

## Tools Required

| Tool | Purpose | Exists? |
|---|---|---|
| `node_write` | Write architecture_map output via registry-validated compressed keys. Agent calls `node_write(agent_id: "architecture_sync", output_key: "architecture_map", data: {...})`. | Pending |
| `node_read` | Read upstream artifacts (code_map, contracts, flows, optimization_report). Agent calls `node_read(agent_id: "architecture_sync", input_key: "code_map")`. | Pending |
| `tracker_read` | Read pipeline state. Agent calls `tracker_read(agent_id: "architecture_sync", fields: [...])`. | Pending |
| `tracker_update` | Report completion/failure. Agent calls `tracker_update(agent_id: "architecture_sync", status: "completed")`. | Pending |

---

## Guardrails

### Rules

| ID | Category | Severity | Rule |
|---|---|---|---|
| R-001 | `constraint` | `must` | Must scan ALL code files in the project — not just files listed in code_map.json. Impl agents may have created files not in the registry, and the architecture map must capture everything. |
| R-002 | `constraint` | `must` | Must detect ALL drift between actual code and contracts. No silent mismatches — every divergence must appear in drift_report with appropriate severity. |
| R-003 | `not_allowed` | `must` | Must not modify any code. This agent is strictly read-only — it observes and documents but never changes. |
| R-004 | `output_quality` | `must` | Must produce deterministic output — given the same codebase, the agent must produce the same architecture_map.json. No random ordering, no non-deterministic analysis. |
| R-005 | `constraint` | `must` | Drift severity classification: missing_endpoint is "warning" (contracted but not built), extra_endpoint is "info" (intentional addition during impl), schema_divergence severity depends on impact (field rename = info, type change = warning, missing field = warning). |
| R-006 | `constraint` | `must` | Must document ALL cross-module dependencies — every import/require that crosses module boundaries must appear in cross_module_dependencies. |
| R-007 | `data_handling` | `must` | Must preserve story_refs wherever they can be traced — from code comments, from contract_refs, or from code_map entries. |
| R-008 | `output_quality` | `must` | Every endpoint must have a handler file reference that points to an actual file. No fabricated file paths. |
| R-009 | `output_quality` | `should` | Pattern detection should report consistency percentage — what fraction of relevant files follow the detected pattern. |
| R-010 | `scope_boundary` | `should` | Standards detection should be descriptive, not prescriptive — document what conventions are used, do not recommend changes. |
| R-011 | `constraint` | `must` | The architecture_map.json must be self-contained — any agent reading it in a future run must be able to understand the full system structure without referencing other artifacts. |
| R-012 | `data_handling` | `must` | Must include the run_id so future runs can determine which pipeline execution produced this architecture map. |
| R-013 | `constraint` | `must` | Must use compressed keys as defined in the Compressed Keymap section for all `node_write` / `node_read` calls. Never use expanded/full key names. |
| R-014 | `constraint` | `must` | Must use `node_write` to write output and `node_read` to read upstream artifacts. Must not use raw file writes, generic file_writer, or any other method. |
| R-015 | `constraint` | `must` | Must call `tracker_update(agent_id: "architecture_sync", status: "completed")` before exiting on success. Must call `tracker_update(agent_id: "architecture_sync", status: "failed", add_intervention: {...})` before exiting on failure. |

### Limits

| Resource | Value |
|---|---|
| max_retries | 3 |
| max_tokens | 64000 |
| max_files_to_scan | 5000 |
| timeout_seconds | 900 |

---

## Scope Boundary

**In scope:**
- Scanning all actual code files (TypeScript, JavaScript, Prisma schema, config files)
- Extracting endpoints from route files (method, path, handler function, middleware chain)
- Extracting services and their functions (name, params, returns, calls, used_by)
- Extracting DB models from actual Prisma schema (models, fields, relations)
- Extracting React components (name, props, hooks, API calls)
- Comparing extracted reality against contracted specifications (fe_details, openapi, prisma_contract)
- Detecting all drift types (missing, extra, diverged, renamed)
- Documenting cross-module dependencies from import statements
- Detecting architectural patterns (service-layer, middleware-chain, etc.)
- Snapshotting coding standards (naming conventions, structure conventions)
- Producing deterministic, self-contained architecture_map.json

**Out of scope:**
- Modifying any code (strictly read-only)
- Fixing drift or divergences (that was the fix planner's job)
- Optimizing code (that was the optimization agent's job)
- Making architectural recommendations (the map documents what IS, not what SHOULD BE)
- Running tests or validating functionality
- Producing deployment artifacts or CI/CD configuration
- Scanning node_modules or third-party dependencies (only project source code)

---

## Triggers

- Orchestrator activates this agent LAST in the pipeline — after all fix loops and optimization loops complete
- Runs once globally (not per-module) because it needs the complete final state of the entire codebase
- In retrofit mode, always runs to update the architecture map with changes from the retrofit run

---

## Checkpoints

| ID | Description | Action |
|---|---|---|
| `CP-001` | Full codebase scan initiated — all source files discovered | `log` |
| `CP-002` | Endpoint extraction complete — all route files parsed | `log` |
| `CP-003` | Service extraction complete — all service files parsed | `log` |
| `CP-004` | DB model extraction complete — Prisma schema parsed | `log` |
| `CP-005` | Component extraction complete — all React files parsed | `log` |
| `CP-006` | Contract comparison complete — drift report generated | `notify` — user can review drift before architecture map is finalized |
| `CP-007` | Cross-module dependency scan complete | `log` |
| `CP-008` | Pattern detection and standards snapshot complete | `log` |
| `CP-009` | architecture_map.json written and schema-validated — pipeline complete | `notify` — user informed that the pipeline is complete and architecture map is available |

---

## Validation Criteria

- Every source file in the project (excluding node_modules, .git, dist) is scanned — no files missed
- Every endpoint extracted has a valid handler reference to an actual file that exists
- Every service function has accurate calls and used_by arrays
- Every model in architecture_map matches or is documented as diverged from prisma_contract
- Every drift item has a severity classification and a human-readable note
- cross_module_dependencies contains every import that crosses module boundaries
- patterns_detected includes consistency percentages
- standards section documents naming and structure conventions
- Output is deterministic — running the agent twice on the same codebase produces identical output
- architecture_map.json is self-contained and passes schema validation
- summary statistics accurately reflect the counts in the detailed arrays
- contract_match_rates percentages sum correctly within each category

---

## Context Sources

- Actual source code files on disk (TypeScript, Prisma schema, config files)
- code_map.json from orchestrator (file registry for starting point)
- fe_details.json from Phase 5 FE contract (comparison baseline)
- openapi.json from Phase 5 BE contract (comparison baseline)
- prisma_contract.json from Phase 5 DB contract (comparison baseline)
- Flow artifacts from Phase 7 (be_policy_flow, fe_flow, db_flow)
- optimization_report.json from Phase 11 optimization agent (if present)
- Previous architecture_map.json from prior runs (if retrofit mode)

---

## Operation Mode

| Field | Value |
|---|---|
| Type | `autonomous` |
| Fallback | `none` — if architecture sync fails, the pipeline is considered complete but without a ground-truth map; future retrofit runs will need to re-analyze from scratch |

---

## Tool Gaps

| Gap ID | Description | Needed By | Impact Without |
|---|---|---|---|
| `TG-001` | `node_write` MCP tool not yet built | this agent | Cannot write output with registry validation -- blocked |
| `TG-002` | `node_read` MCP tool not yet built | this agent | Cannot read upstream artifacts with field enforcement -- blocked |
| `TG-003` | `tracker_read` MCP tool not yet built | this agent | Cannot read pipeline state -- blocked |
| `TG-004` | `tracker_update` MCP tool not yet built | this agent | Cannot report completion -- blocked |
| `TG-005` | TypeScript/JavaScript AST parser for extracting endpoints, functions, imports, exports, and component definitions from actual code files | this agent | Agent must use regex or LLM-based extraction; risk of missing dynamically registered routes, computed imports, or HOC-wrapped components |
| `TG-006` | Prisma schema parser for extracting models, fields, relations, enums, and custom attributes from schema.prisma | this agent | Agent must parse Prisma DSL text manually; risk of misinterpreting relation syntax or custom directives |
| `TG-007` | OpenAPI diff tool for structured comparison between extracted endpoints and contracted API spec | this agent | Must manually compare each endpoint; risk of missing param-level or response-level divergences that are not obvious from path comparison alone |
| `TG-008` | Pattern detector that analyzes call graphs and file structure to identify recurring architectural patterns | this agent | Pattern detection limited to heuristic analysis; may fail to detect patterns that span multiple abstraction layers |
| `TG-009` | Cross-reference builder that traces import/require/from statements to build a complete cross-module dependency graph | this agent | Must trace imports manually through file content; risk of missing re-exports, barrel imports, or dynamic imports |

---

## Generation Readiness

| `generate_agent` Param | Status | Notes |
|---|---|---|
| `fileName` | ready | `architecture-sync` |
| `agentName` | ready | `architecture_sync` |
| `agentRole` | ready | "Architecture Sync Agent — Ground-Truth Codebase Map Generator" |
| `agentDescription` | ready | Full description available from Goal section |
| `operationMode` | ready | `autonomous`, no fallback |
| `goal` | ready | 3 objectives defined with priorities |
| `inputs` | ready | 5 input categories: actual codebase, all contracts, all flows, code_map.json, optimization_report (optional) |
| `guardrails` | ready | 15 rules covering constraints, not_allowed, output_quality, data_handling, scope_boundary, universal tools, and completion signal |
| `scopeBoundary` | ready | 11 in-scope items, 7 out-of-scope items |
| `outputFormat` | ready | JSON output with full schema for architecture_map.json including endpoints, services, models, components, patterns, standards, drift_report, cross_module_dependencies, and summary |
| `triggers` | ready | 3 triggers defined |
| `checkpoints` | ready | 9 checkpoints covering full extraction and comparison pipeline |
| `validation` | ready | 12 validation criteria |
| `contextSources` | ready | 8 context sources |
| `metadata` | ready | phase: "11", mode: "both", granularity: "global" |
