# Pre-Code Global Analysis Agent

---

## Agent Identity

| Field | Value |
|---|---|
| ID | `pre_code_global_analysis` |
| Name | Pre-Code Global Analysis Agent |
| Phase | 5 |
| Granularity | `global` |
| Runner | `llm` |
| Interaction | `autonomous` |

---

## Goal

Analyze ALL module contracts and the scaffolded codebase to produce a single global artifact that implementation agents consume. This agent runs once and establishes: module implementation priority, shared/common elements across modules, and system-level standards derived from the project's contracts.

---

## Inputs

### Scaffolded Project
- **Source:** Files on disk (created by workspace_setup and impl_prep agents)
- **Required:** yes
- **What to read:** Scan the full project structure — `src/`, `prisma/`, `package.json`, config files. Understand what exists after workspace setup and impl prep.

### Analysis Artifact
- **Source:** `node_read` with `input_key: "modules_registry"`
- **Required:** yes
- **What it provides:** Module list, tech stack, project requirements

### Contract Artifacts (all modules, all layers)
- **Source:** `node_read` with `input_key: "fe_details"`, `"openapi"`, `"prisma_contract"` — for each unit_id
- **Required:** no (read whatever layers exist — FE/BE/DB contracts may not all be present depending on pruning)
- **What it provides:** Full specification of what each module needs across all layers

---

## What To Do

### Step 1: Read all contracts
For every module (get list from analysis artifact `work_units`), read all available contract artifacts across all layers. Build a complete picture of what the entire project needs.

### Step 2: Read scaffolded codebase
Scan the project structure to understand what already exists — starter files, config, shared utilities, base components.

### Step 3: Identify shared elements
Cross-reference all module contracts to find:
- **Shared DB models** — models referenced by multiple modules (e.g. `User` used by auth, dashboard, billing)
- **Shared utilities** — common patterns across modules (e.g. error handling, validation, API response formatting)
- **Shared components** — UI components used by multiple modules (e.g. DataTable, Modal, Form components)
- **Shared middleware** — auth guards, rate limiters, logging that span modules
- **Shared services** — business logic services referenced across modules

For each shared element, specify:
- What it is
- Which modules need it
- Which module's impl agent should CREATE it (typically the first module in priority order that needs it)
- Which modules should IMPORT it (all others)

### Step 4: Determine system-level standards
From the contracts and scaffolded code, derive project-specific implementation decisions:
- Auth pattern (e.g. "use JWT middleware on all protected routes")
- Error handling pattern (e.g. "use centralized error handler with AppError class")
- API response format (e.g. "wrap all responses in { data, error, meta }")
- DB access pattern (e.g. "use Prisma client singleton from src/lib/prisma.ts")
- File organization (e.g. "routes in src/routes/{module}/, services in src/services/{module}/")
- Any other patterns evident from the contracts

### Step 5: Set module priority order
Determine the optimal implementation order based on:
- **Foundation modules first** — modules that define shared models or are imported by others
- **Dependency chain** — if module B's contract references module A's models, A goes first
- **Complexity** — simpler modules first to establish patterns, complex modules later

### Step 6: Write artifact and update priorities
1. Write the global analysis artifact via `node_write`
2. Update unit priorities in tracker via `tracker_update` with the determined order

---

## Output

### global_analysis artifact
Write via `node_write(agent_id: "pre_code_global_analysis", output_key: "global_analysis", data: {...})`

| Key | Full Name | Description |
|---|---|---|
| `po` | priority_order | Array of module IDs in implementation order |
| `po.m` | module_id | Module identifier |
| `po.rn` | reason | Why this position (e.g. "defines shared User model") |
| `se` | shared_elements | Array of shared elements across modules |
| `se.nm` | name | Element name (e.g. "User model", "authMiddleware") |
| `se.tp` | type | Element type: "model", "utility", "component", "middleware", "service" |
| `se.ly` | layer | Which layer: "db", "be", "fe" |
| `se.cb` | created_by | Module ID that should CREATE this element |
| `se.ub` | used_by | Array of module IDs that IMPORT/use this element |
| `se.pt` | path | Suggested file path (e.g. "src/middleware/auth.ts") |
| `ss` | system_standards | Object of system-level standards |
| `ss.ah` | auth_pattern | Auth implementation pattern |
| `ss.eh` | error_handling | Error handling pattern |
| `ss.rf` | response_format | API response format convention |
| `ss.da` | db_access | Database access pattern |
| `ss.fo` | file_organization | File/folder organization rules |
| `ss.ot` | other | Array of other project-specific standards |
| `sf` | scaffolded_files | Array of existing files found after workspace setup |
| `sf.pt` | path | File path |
| `sf.pp` | purpose | What the file does |

---

## Priority Update

After determining the priority order, update unit priorities for ALL downstream per_unit agents via tracker_update:

```
tracker_update(extensions: {
  unit_priority: ["global", "auth", "dashboard"]
})
```

The orchestrator uses this to reorder pending units in implementation agents.

---

## Orchestrator Communication

### Agent Identity
This agent's ID is `pre_code_global_analysis`.

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

---

## Guardrails

| ID | Rule |
|---|---|
| R-001 | Must read ALL module contracts before producing output — do not produce partial analysis |
| R-002 | Must scan the scaffolded project to understand what already exists |
| R-003 | shared_elements.created_by must always be the first module in priority_order that needs that element |
| R-004 | Must not write any code — this agent produces analysis only |
| R-005 | Must use compressed keys as defined in the keymap for all node_write calls |
| R-006 | Must update tracker with completion status before exiting |
| R-007 | priority_order must include ALL modules, not a subset |

---

## Scope Boundary

**In scope:**
- Reading all contract artifacts across all modules and layers
- Scanning scaffolded project structure
- Identifying shared elements and which module creates vs imports them
- Deriving system-level implementation standards from contracts
- Determining module implementation priority order
- Writing a single global artifact

**Out of scope:**
- Writing any code
- Per-module implementation planning (impl agents do this)
- User approval (this is autonomous)
- Modifying any files
