# Module Priority Sequencer Agent

> **Greek:** Taxis (Táxis) — "order/arrangement"
> **Sanskrit:** क्रम (Krama) — "sequence/order"
> **Tagline:** *"Build what matters first"*

---

## Agent Identity

| Field | Value |
|---|---|
| ID | `module_sequencer` |
| Name | Module Priority Sequencer Agent |
| Phase | 8 — Reconciliation & Decisions |
| Type | `pipeline` |
| Granularity | `global` |
| Interaction | `autonomous` |
| Mode | `all` |
| Domain | `dev` |

---

## Goal & Objectives

**Goal:** Determine the optimal build order for module implementation by analyzing cross-module dependencies, story priorities, and complexity estimates — producing a sequenced plan that respects dependency constraints, identifies the critical path, and groups independent modules for parallel execution.

| Priority | Objective |
|---|---|
| primary | Produce a dependency-respecting build sequence where no module is scheduled before its dependencies (if billing depends on auth, auth goes first) |
| secondary | Identify the critical path — the longest chain of dependent modules that determines the minimum total build time |
| tertiary | Group independent modules into parallel execution batches to maximize throughput during implementation |

---

## Inputs

### module_flow.json (per module)
- **Source:** `architect_reconcile` agent -> `agent_output/reconciliation/{module_id}/module_flow.json`
- **Required:** yes
- **Shape:**
```json
{
  "module_id": {
    "type": "string",
    "example": "auth"
  },
  "cross_module_dependencies": {
    "type": "array",
    "description": "Dependencies this module has on other modules",
    "items": {
      "target_module": {
        "type": "string",
        "example": "billing"
      },
      "dependency_type": {
        "type": "string",
        "enum": ["service_call", "shared_entity", "navigation", "event"],
        "example": "service_call"
      },
      "description": {
        "type": "string",
        "example": "Auth service provides getCurrentUser to billing"
      }
    }
  },
  "layers": {
    "type": "object",
    "description": "Layer details used for complexity estimation",
    "fields": {
      "fe": { "nodes": { "type": "array" }, "screen_count": { "type": "number" } },
      "be": { "nodes": { "type": "array" }, "endpoint_count": { "type": "number" } },
      "db": { "nodes": { "type": "array" }, "model_count": { "type": "number" } }
    }
  }
}
```

### story_priority.json (per module)
- **Source:** `user_stories` agent -> `agent_output/stories/{module_id}/user_stories_{module_id}.json` (priority field per story)
- **Required:** yes
- **Shape:**
```json
{
  "module_id": {
    "type": "string",
    "example": "auth"
  },
  "stories": {
    "type": "array",
    "items": {
      "story_id": {
        "type": "string",
        "example": "US-AUTH-001"
      },
      "priority": {
        "type": "string",
        "enum": ["must", "should", "could", "wont"],
        "example": "must"
      }
    }
  },
  "priority_summary": {
    "type": "object",
    "description": "Count of stories by priority level",
    "fields": {
      "must_count": { "type": "number", "example": 5 },
      "should_count": { "type": "number", "example": 3 },
      "could_count": { "type": "number", "example": 2 },
      "wont_count": { "type": "number", "example": 0 }
    }
  }
}
```

### traceability.json
- **Source:** `architect_reconcile` agent -> `agent_output/reconciliation/traceability.json`
- **Required:** yes
- **Shape:**
```json
{
  "chains": {
    "type": "array",
    "items": {
      "story_id": { "type": "string" },
      "module_id": { "type": "string" },
      "chain_status": { "type": "string", "enum": ["complete", "partial", "broken"] }
    }
  }
}
```

### decisions.json
- **Source:** `decision_pack` agent -> `agent_output/reconciliation/decisions.json`
- **Required:** yes
- **Shape:**
```json
{
  "gap_decisions": {
    "type": "array",
    "items": {
      "question_id": { "type": "string" },
      "selected_option": { "type": "string" },
      "affects_modules": { "type": "array", "items": { "type": "string" } }
    }
  },
  "conflict_decisions": {
    "type": "array",
    "items": {
      "question_id": { "type": "string" },
      "selected_option": { "type": "string" },
      "affects_modules": { "type": "array", "items": { "type": "string" } }
    }
  }
}
```

---

## Outputs

### module_priority_sequence.json
- **Path:** `agent_output/reconciliation/module_priority_sequence.json`
- **Format:** `json`
- **Consumers:** `impl_prep`, `pre_code_analysis`, `orchestrator`, all implementation agents
- **Shape:**
```json
{
  "generated_at": {
    "type": "string",
    "format": "ISO-8601"
  },
  "total_modules": {
    "type": "number",
    "description": "Total modules in the sequence",
    "example": 5
  },
  "sequence": {
    "type": "array",
    "description": "Ordered list of modules in build priority",
    "items": {
      "order": {
        "type": "number",
        "description": "1-based position in the build sequence",
        "example": 1
      },
      "module_id": {
        "type": "string",
        "description": "Module identifier",
        "example": "auth"
      },
      "reason": {
        "type": "string",
        "description": "Why this module is at this position",
        "example": "Auth has no dependencies and is required by 3 other modules (billing, reports, dashboard). It has the highest must-story ratio."
      },
      "dependencies": {
        "type": "array",
        "description": "Module IDs this module depends on (must be built before this one)",
        "items": { "type": "string" },
        "example": []
      },
      "dependents": {
        "type": "array",
        "description": "Module IDs that depend on this module",
        "items": { "type": "string" },
        "example": ["billing", "reports", "dashboard"]
      },
      "estimated_complexity": {
        "type": "string",
        "enum": ["low", "medium", "high"],
        "description": "Estimated implementation complexity based on screen count, endpoint count, model count, and story priority mix",
        "example": "medium"
      },
      "complexity_factors": {
        "type": "object",
        "description": "Breakdown of what contributes to complexity estimate",
        "fields": {
          "screen_count": { "type": "number", "example": 4 },
          "endpoint_count": { "type": "number", "example": 8 },
          "model_count": { "type": "number", "example": 3 },
          "must_story_count": { "type": "number", "example": 5 },
          "integration_count": { "type": "number", "example": 1 },
          "cross_module_dep_count": { "type": "number", "example": 0 }
        }
      },
      "is_on_critical_path": {
        "type": "boolean",
        "description": "Whether this module is on the critical path",
        "example": true
      }
    }
  },
  "parallel_groups": {
    "type": "array",
    "description": "Groups of modules that can be built simultaneously because they have no interdependencies",
    "items": {
      "group_id": {
        "type": "number",
        "description": "1-based group number",
        "example": 1
      },
      "modules": {
        "type": "array",
        "description": "Module IDs in this parallel group",
        "items": { "type": "string" },
        "example": ["auth"]
      },
      "prerequisites_met": {
        "type": "string",
        "description": "What must be complete before this group can start",
        "example": "impl_prep complete"
      },
      "estimated_group_complexity": {
        "type": "string",
        "enum": ["low", "medium", "high"],
        "description": "Complexity of the most complex module in the group (determines group duration)",
        "example": "medium"
      }
    }
  },
  "critical_path": {
    "type": "array",
    "description": "The longest dependency chain — modules that block everything else",
    "items": {
      "module_id": {
        "type": "string",
        "example": "auth"
      },
      "blocks": {
        "type": "array",
        "description": "What this module blocks on the critical path",
        "items": { "type": "string" },
        "example": ["billing"]
      },
      "estimated_complexity": {
        "type": "string",
        "enum": ["low", "medium", "high"],
        "example": "medium"
      }
    }
  },
  "sequencing_rationale": {
    "type": "string",
    "description": "Human-readable explanation of how the sequence was determined",
    "example": "Sequence determined by: 1) topological sort of module dependency graph, 2) must-story ratio as tiebreaker, 3) dependency fan-out (modules that unblock the most others go first). Critical path: auth -> billing -> reports."
  }
}
```

---

## Dependencies

| Depends On | Agent | Artifact | Why |
|---|---|---|---|
| input | `architect_reconcile` | `module_flow.json` (per module) | Cross-module dependencies for topological sorting |
| input | `user_stories` | `user_stories_{module_id}.json` (per module) | Story priorities for tiebreaking and complexity estimation |
| input | `architect_reconcile` | `traceability.json` | Chain completeness affects module readiness |
| input | `decision_pack` | `decisions.json` | User decisions may affect module dependencies or priorities |

| Blocks | Agent | Why |
|---|---|---|
| output | `impl_prep` | Implementation prep uses the sequence to set up project structure in dependency order |
| output | `pre_code_analysis` | Pre-code analysis uses the sequence to know which module to analyze first |
| output | `orchestrator` | Orchestrator uses the sequence to trigger implementation agents in order |

---

## Orchestrator Communication

> Reference: `v2/architecture/agent-orchestrator-communication.md`

### Agent Identity

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

### Tracker Access

| Direction | Compressed Keys | Purpose |
|---|---|---|
| read | `md.a` | Read active modules to know which modules to sequence |
| write | `ag` | Report agent status (completed/failed) |

### Output Meta

This agent may produce sequencing metadata (module order, parallel groups) stored in `agent_output_meta` for orchestrator consumption.

### Completion Signal

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

### Scope Resolution

Global agent — runs once across all modules. Reads `md.a` from tracker via `tracker_read` to know which modules to include in sequencing.

---

## Compressed Keymap

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

**module_priority_sequence.json**

| Key | Full Name | Description |
|---|---|---|
| `ga` | generated_at | Timestamp of generation |
| `tm` | total_modules | Total number of modules sequenced |
| `sq` | sequence | Ordered array of module sequence entries |
| `sq.or` | order | Execution order position (1-based) |
| `sq.m` | module_id | Module identifier |
| `sq.rn` | reason | Rationale for this position |
| `sq.dp` | dependencies | Modules this module depends on |
| `sq.dt` | dependents | Modules that depend on this module |
| `sq.ec` | estimated_complexity | Estimated complexity score |
| `sq.cf` | complexity_factors | Complexity factor breakdown object |
| `sq.cf.sc` | screen_count | Number of screens in module |
| `sq.cf.ep` | endpoint_count | Number of endpoints in module |
| `sq.cf.mc` | model_count | Number of DB models in module |
| `sq.cf.ms` | must_story_count | Number of must-have stories |
| `sq.cf.ic` | integration_count | Number of external integrations |
| `sq.cf.cd` | cross_module_dep_count | Number of cross-module dependencies |
| `sq.cp` | is_on_critical_path | Whether module is on critical path |
| `pg` | parallel_groups | Array of parallelizable module groups |
| `pg.gi` | group_id | Group identifier |
| `pg.ms` | modules | Modules in this parallel group |
| `pg.pm` | prerequisites_met | Prerequisites completed before group |
| `pg.gc` | estimated_group_complexity | Combined group complexity |
| `cp` | critical_path | Ordered critical path array |
| `cp.m` | module_id | Module on critical path |
| `cp.bl` | blocks | What this module blocks |
| `cp.ec` | estimated_complexity | Complexity of this critical path node |
| `sr` | sequencing_rationale | Overall sequencing rationale text |

---

## Tools Required

| Tool | Purpose | Exists? |
|---|---|---|
| `node_write` | Write sequencing output via registry-validated compressed keys. Agent calls `node_write(agent_id: "module_sequencer", output_key: "sequence", data: {...})`. | Pending |
| `node_read` | Read upstream artifacts (module_flow, story_priority, traceability, decisions). Agent calls `node_read(agent_id: "module_sequencer", input_key: "module_flow", unit_id: "{module_id}")`. | Pending |
| `tracker_read` | Read active modules. Agent calls `tracker_read(agent_id: "module_sequencer", fields: ["md.a"])`. | Pending |
| `tracker_update` | Report completion/failure. Agent calls `tracker_update(agent_id: "module_sequencer", status: "completed")`. | Pending |

---

## Guardrails

### Rules

| ID | Category | Severity | Rule |
|---|---|---|---|
| R-001 | `constraint` | `must` | Must respect cross-module dependencies. If module A depends on module B, B must appear before A in the sequence. |
| R-002 | `constraint` | `must` | Must identify the critical path — the longest chain of sequential dependencies that determines minimum build time. |
| R-003 | `constraint` | `must` | Must group independent modules into parallel_groups. Modules with no interdependencies should be grouped for simultaneous execution. |
| R-004 | `constraint` | `must` | Must detect circular dependencies and report them as errors. Circular deps make topological sorting impossible. |
| R-005 | `output_quality` | `must` | Every module in modules_registry.json must appear exactly once in the sequence. No module may be omitted or duplicated. |
| R-006 | `output_quality` | `must` | Each sequence entry must include reason, dependencies, dependents, and estimated_complexity. No empty fields. |
| R-007 | `scope_boundary` | `should` | When two modules have no dependency relationship, the one with more "must" priority stories should go first. |
| R-008 | `output_quality` | `should` | Modules that unblock the most dependents (highest fan-out) should be prioritized as tiebreakers. |
| R-009 | `interaction` | `may` | May present the sequence to the user for confirmation if the sequencing_rationale involves subjective trade-offs. |
| R-010 | `data_handling` | `must` | Must use decisions.json to adjust dependencies or priorities if user decisions changed module relationships. |
| R-011 | `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-012 | `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-013 | `constraint` | `must` | Must call `tracker_update(agent_id: "module_sequencer", status: "completed")` before exiting on success. Must call `tracker_update(agent_id: "module_sequencer", status: "failed", add_intervention: {...})` before exiting on failure. |
| R-014 | `constraint` | `must` | Must read active modules via `tracker_read(agent_id: "module_sequencer", fields: ["md.a"])` when resolving scope. Must not hardcode module lists. |

### Limits

| Resource | Value |
|---|---|
| max_retries | 3 |
| max_tokens | 8192 |
| max_modules | 20 |
| timeout_seconds | 120 |

---

## Scope Boundary

**In scope:**
- Topological sorting of module dependency graph
- Estimating module complexity from quantitative metrics
- Identifying the critical path
- Grouping independent modules for parallel execution
- Using story priorities as tiebreakers
- Incorporating user decisions that affect module relationships
- Producing a human-readable sequencing rationale

**Out of scope:**
- Implementing any modules
- Modifying module dependencies or contracts
- Making architectural decisions
- Estimating timelines in hours or days (complexity is relative: low/medium/high)
- Deciding which modules to skip or defer (all modules are included)
- Breaking modules into smaller units

---

## Triggers

- Orchestrator activates this agent after architect_reconcile and decision_pack complete
- Requires module_flow.json for all modules and decisions.json to be available
- In retrofit mode, produces an updated sequence reflecting only the affected modules plus their dependents

---

## Checkpoints

| ID | Description | Action |
|---|---|---|
| `CP-001` | All module flows and story priorities loaded | `log` |
| `CP-002` | Module dependency graph constructed | `log` |
| `CP-003` | Circular dependency check complete | `notify` — if circular deps found, report error |
| `CP-004` | Topological sort complete | `log` |
| `CP-005` | Complexity estimates calculated for all modules | `log` |
| `CP-006` | Parallel groups identified | `log` |
| `CP-007` | Critical path identified | `notify` — critical path determines minimum build time |
| `CP-008` | module_priority_sequence.json written and validated | `log` |

---

## Validation Criteria

- Every module in modules_registry.json appears exactly once in sequence[]
- No module appears before any of its dependencies in the sequence
- No circular dependencies exist (if found, agent reports error and halts)
- parallel_groups contain only modules with no mutual dependencies
- critical_path represents the longest dependency chain in the graph
- All sequence entries have non-empty reason, dependencies, dependents, and estimated_complexity
- complexity_factors values are non-negative numbers
- parallel_groups.prerequisites_met is defined for every group
- sequencing_rationale is a non-empty human-readable explanation

---

## Context Sources

- module_flow.json per module (cross-module dependency data)
- user_stories_{module_id}.json per module (story priorities)
- traceability.json (chain completeness for readiness assessment)
- decisions.json (user decisions affecting module relationships)
- modules_registry.json (master list of all modules)

---

## Operation Mode

| Field | Value |
|---|---|
| Type | `autonomous` |
| Fallback | `none` — if sequencing fails, orchestrator cannot determine implementation order |

---

## 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 active modules -- blocked |
| `TG-004` | `tracker_update` MCP tool not yet built | this agent | Cannot report completion -- blocked |
| `TG-005` | Dependency graph topological sorter that handles DAG validation, cycle detection, and produces a valid linear ordering | this agent | Would need to implement sorting algorithm manually; incorrect sort could cause modules to be built before their dependencies |
| `TG-006` | Complexity estimator that calculates relative complexity from quantitative metrics (screen count, endpoint count, model count, integration count) | this agent | Complexity estimates would be ad-hoc guesses, reducing the accuracy of parallel grouping and critical path analysis |

---

## Generation Readiness

| `generate_agent` Param | Status | Notes |
|---|---|---|
| `fileName` | ready | `module-sequencer` |
| `agentName` | ready | `module_sequencer` |
| `agentRole` | ready | "Module Build Order Optimizer with Critical Path Analysis" |
| `agentDescription` | ready | Full description available from Goal section |
| `operationMode` | ready | `autonomous`, no fallback |
| `goal` | ready | 3 objectives defined with priorities |
| `inputs` | ready | 4 inputs: module_flow.json (per module), story priorities, traceability.json, decisions.json |
| `guardrails` | ready | 14 rules defined across constraint, output_quality, scope_boundary, interaction, data_handling categories |
| `scopeBoundary` | ready | 7 in-scope items, 6 out-of-scope items |
| `outputFormat` | ready | JSON output with full schema for module_priority_sequence.json |
| `triggers` | ready | 3 triggers defined |
| `checkpoints` | ready | 8 checkpoints with actions |
| `validation` | ready | 9 validation criteria |
| `contextSources` | ready | 5 context sources |
| `metadata` | ready | phase: "8", mode: "all", granularity: "global" |
