# PRD Generation Agent

> **Greek:** Logos (Lógos) — "word/reason/document"
> **Sanskrit:** प्रलेख (Pralekha) — "document/record"
> **Tagline:** *"The contract the whole team reads"*

---

## Agent Identity

| Field | Value |
|---|---|
| ID | `prd_generation` |
| Name | PRD Generation Agent |
| Phase | 8 — Reconciliation & Decisions |
| Type | `pipeline` |
| Granularity | `global` |
| Interaction | `autonomous` |
| Mode | `all` |
| Domain | `dev` |

---

## Goal & Objectives

**Goal:** Generate a comprehensive, standalone HTML PRD document that covers ALL layers (frontend, backend, database) — not just FE like v1 — by consuming every analysis, story, contract, flow, global output, and decision artifact produced by the pipeline, and presenting them in a navigable, human-readable format that serves as the authoritative reference for the entire project.

| Priority | Objective |
|---|---|
| primary | Produce a standalone HTML PRD that covers all three layers (FE, BE, DB) with per-module detail including stories, screens, endpoints, DB models, and flows |
| secondary | Include all decisions from decisions.json and present them in context, showing what was decided, why, and what impact each decision has on the system |
| tertiary | Make the PRD navigable with a table of contents, anchor links, and cross-references so any team member can quickly find information about any module, story, or decision |

---

## Inputs

### analysis_output.json (per module)
- **Source:** `analysis` agent -> `agent_output/discovery/{module_id}/analysis_output.json`
- **Required:** yes
- **Shape:**
```json
{
  "module_id": { "type": "string" },
  "module_name": { "type": "string" },
  "description": { "type": "string" },
  "features": {
    "type": "array",
    "items": {
      "feature_id": { "type": "string" },
      "name": { "type": "string" },
      "priority": { "type": "string", "enum": ["must_have", "should_have", "nice_to_have"] }
    }
  },
  "requirements": {
    "type": "object",
    "fields": {
      "functional": { "type": "array" },
      "non_functional": { "type": "array" }
    }
  },
  "data_entities": { "type": "array" },
  "integrations": { "type": "array" }
}
```

### user_stories_{module_id}.json (per module)
- **Source:** `user_stories` agent -> `agent_output/stories/{module_id}/user_stories_{module_id}.json`
- **Required:** yes
- **Shape:**
```json
{
  "module_id": { "type": "string" },
  "stories": {
    "type": "array",
    "items": {
      "story_id": { "type": "string" },
      "role": { "type": "string" },
      "action": { "type": "string" },
      "outcome": { "type": "string" },
      "acceptance_criteria": { "type": "array", "items": { "type": "string" } },
      "priority": { "type": "string", "enum": ["must", "should", "could", "wont"] }
    }
  }
}
```

### fe_details.json (per module)
- **Source:** `fe_contract` agent -> `agent_output/contracts/{module_id}/fe_details.json`
- **Required:** yes
- **Shape:**
```json
{
  "module_id": { "type": "string" },
  "screens": {
    "type": "array",
    "items": {
      "screen_id": { "type": "string" },
      "name": { "type": "string" },
      "route": { "type": "string" },
      "components": { "type": "array" },
      "story_refs": { "type": "array", "items": { "type": "string" } }
    }
  }
}
```

### openapi.json (per module)
- **Source:** `be_contract` agent -> `agent_output/contracts/{module_id}/openapi.json`
- **Required:** yes
- **Shape:**
```json
{
  "openapi": { "type": "string", "example": "3.0.3" },
  "info": {
    "type": "object",
    "fields": {
      "title": { "type": "string" },
      "version": { "type": "string" }
    }
  },
  "paths": {
    "type": "object",
    "description": "OpenAPI paths with operations, request/response schemas"
  }
}
```

### prisma_contract.json (per module)
- **Source:** `db_contract` agent -> `agent_output/contracts/{module_id}/prisma_contract.json`
- **Required:** yes
- **Shape:**
```json
{
  "module_id": { "type": "string" },
  "models": {
    "type": "array",
    "items": {
      "name": { "type": "string" },
      "fields": { "type": "array" },
      "relations": { "type": "array" },
      "indexes": { "type": "array" }
    }
  }
}
```

### 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" },
  "layers": {
    "type": "object",
    "fields": {
      "fe": { "type": "object" },
      "be": { "type": "object" },
      "db": { "type": "object" }
    }
  },
  "cross_layer_links": { "type": "array" },
  "cross_module_dependencies": { "type": "array" }
}
```

### global_flow.json
- **Source:** `architect_reconcile` agent -> `agent_output/reconciliation/global_flow.json`
- **Required:** yes
- **Shape:**
```json
{
  "total_modules": { "type": "number" },
  "system_dependency_graph": { "type": "object" },
  "global_architecture_summary": { "type": "object" }
}
```

### traceability.json
- **Source:** `architect_reconcile` agent -> `agent_output/reconciliation/traceability.json`
- **Required:** yes
- **Shape:**
```json
{
  "chains": { "type": "array" },
  "summary": {
    "type": "object",
    "fields": {
      "total_stories": { "type": "number" },
      "completeness_percentage": { "type": "number" }
    }
  }
}
```

### decisions.json
- **Source:** `decision_pack` agent -> `agent_output/reconciliation/decisions.json`
- **Required:** yes
- **Shape:**
```json
{
  "gap_decisions": { "type": "array" },
  "conflict_decisions": { "type": "array" },
  "summary": {
    "type": "object",
    "fields": {
      "total_questions": { "type": "number" },
      "modules_affected": { "type": "array" }
    }
  }
}
```

### All Global Outputs
- **Source:** Phase 7 global agents -> `agent_output/global/*.json`
- **Required:** yes
- **Shape:** (references to global_services_registry, global_middleware_registry, global_security_policies, global_integrations, environment_config_schema, production_bootstrap, global_navigation, global_db_patterns)

---

## Outputs

### prd.html
- **Path:** `agent_output/reconciliation/prd.html`
- **Format:** `html`
- **Consumers:** `user` (human-readable reference), `impl_prep` (project context), all implementation agents (reference)
- **Shape:**
```json
{
  "format": "standalone HTML document",
  "description": "Self-contained HTML file with embedded CSS. No external dependencies.",
  "sections": {
    "executive_summary": {
      "type": "string",
      "description": "High-level overview of the entire system — what it does, who it serves, key metrics (module count, story count, endpoint count)"
    },
    "table_of_contents": {
      "type": "string",
      "description": "Navigable TOC with anchor links to every section and subsection"
    },
    "modules_overview": {
      "type": "string",
      "description": "Summary table of all modules with feature counts, story counts, dependencies, and status"
    },
    "per_module_detail": {
      "type": "array",
      "description": "One section per module containing all layer details",
      "items": {
        "module_header": {
          "type": "string",
          "description": "Module name, description, features list"
        },
        "stories_section": {
          "type": "string",
          "description": "All user stories for this module with acceptance criteria"
        },
        "screens_section": {
          "type": "string",
          "description": "All FE screens with components, routes, state requirements"
        },
        "endpoints_section": {
          "type": "string",
          "description": "All BE endpoints from OpenAPI with request/response schemas"
        },
        "db_models_section": {
          "type": "string",
          "description": "All DB models from Prisma contract with fields and relations"
        },
        "flows_section": {
          "type": "string",
          "description": "Module flow diagram showing FE -> BE -> DB interactions"
        },
        "traceability_section": {
          "type": "string",
          "description": "Story traceability chains for this module"
        }
      }
    },
    "global_architecture": {
      "type": "string",
      "description": "System-wide architecture: shared services, middleware, security, integrations"
    },
    "security_section": {
      "type": "string",
      "description": "Security policies, auth strategy, RBAC, data protection"
    },
    "integrations_section": {
      "type": "string",
      "description": "External integration points and configurations"
    },
    "decisions_section": {
      "type": "string",
      "description": "All decisions made during decision pack with reasoning and impact"
    },
    "appendix": {
      "type": "string",
      "description": "Environment variables, DB patterns, production bootstrap data"
    }
  }
}
```

---

## Dependencies

| Depends On | Agent | Artifact | Why |
|---|---|---|---|
| input | `analysis` | `analysis_output.json` (per module) | Module descriptions, features, requirements for executive summary and module detail |
| input | `user_stories` | `user_stories_{module_id}.json` (per module) | Stories for per-module detail section |
| input | `fe_contract` | `fe_details.json` (per module) | Screen definitions for FE layer documentation |
| input | `be_contract` | `openapi.json` (per module) | Endpoint definitions for BE layer documentation |
| input | `db_contract` | `prisma_contract.json` (per module) | DB model definitions for DB layer documentation |
| input | `architect_reconcile` | `module_flow.json` (per module), `global_flow.json`, `traceability.json` | Merged flows, system graph, and traceability chains |
| input | `decision_pack` | `decisions.json` | User decisions to include in decisions section |
| input | Phase 7 agents | All global outputs | Architecture, security, integrations for global sections |

| Blocks | Agent | Why |
|---|---|---|
| output | `user` | PRD is the primary human-readable deliverable of the analysis and design phases |

---

## Orchestrator Communication

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

### Agent Identity

This agent's ID is `prd_generation`. 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 include in the PRD |
| write | `ag` | Report agent status (completed/failed) |

### Output Meta

This agent does not produce routing/coordination metadata. `output_meta: null`.

### Completion Signal

- **On success:** `tracker_update(agent_id: "prd_generation", status: "completed")`
- **On failure:** `tracker_update(agent_id: "prd_generation", status: "failed", add_intervention: { id: "...", agent_id: "prd_generation", 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 document.

---

## Compressed Keymap

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

**prd.html**

| Key | Full Name | Description |
|---|---|---|
| `fm` | format | Output format (html) |
| `ds` | description | PRD document description |
| `sc` | sections | Top-level sections object |
| `sc.es` | executive_summary | Executive summary section |
| `sc.tc` | table_of_contents | Table of contents section |
| `sc.mo` | modules_overview | Modules overview section |
| `sc.pm` | per_module_detail | Array of per-module detail sections |
| `sc.pm.mh` | module_header | Module header and metadata |
| `sc.pm.ss` | stories_section | User stories for the module |
| `sc.pm.sr` | screens_section | Screen definitions for the module |
| `sc.pm.ep` | endpoints_section | API endpoint definitions |
| `sc.pm.db` | db_models_section | Database model definitions |
| `sc.pm.fl` | flows_section | Flow diagrams and descriptions |
| `sc.pm.tr` | traceability_section | Story-to-artifact traceability |
| `sc.ga` | global_architecture | Global architecture section |
| `sc.se` | security_section | Security requirements section |
| `sc.ig` | integrations_section | External integrations section |
| `sc.dc` | decisions_section | Decisions log section |
| `sc.ap` | appendix | Appendix section |

---

## Tools Required

| Tool | Purpose | Exists? |
|---|---|---|
| `node_write` | Write PRD output via registry-validated compressed keys. Agent calls `node_write(agent_id: "prd_generation", output_key: "prd", data: {...})`. | Pending |
| `node_read` | Read all upstream artifacts (analysis, stories, contracts, flows, global outputs, decisions). Agent calls `node_read(agent_id: "prd_generation", input_key: "analysis", unit_id: "{module_id}")`. | Pending |
| `tracker_read` | Read active modules. Agent calls `tracker_read(agent_id: "prd_generation", fields: ["md.a"])`. | Pending |
| `tracker_update` | Report completion/failure. Agent calls `tracker_update(agent_id: "prd_generation", status: "completed")`. | Pending |

---

## Guardrails

### Rules

| ID | Category | Severity | Rule |
|---|---|---|---|
| R-001 | `constraint` | `must` | Must cover ALL three layers (FE, BE, DB) for every module. This is not an FE-only PRD like v1. |
| R-002 | `constraint` | `must` | Must be standalone HTML — no external CSS, JS, or image dependencies. Everything embedded inline. |
| R-003 | `constraint` | `must` | Must include all decisions from decisions.json with reasoning and impact. No decision may be omitted. |
| R-004 | `output_quality` | `must` | Must be navigable with a table of contents and working anchor links. Every section and module must be linkable. |
| R-005 | `constraint` | `must` | Must read ALL inputs — analysis, stories, contracts (FE, BE, DB), flows, global outputs, decisions, traceability. Partial reads produce incomplete PRDs. |
| R-006 | `output_quality` | `must` | Every module section must include stories, screens, endpoints, DB models, and flows. No layer may be silently omitted. |
| R-007 | `scope_boundary` | `must` | Must not include implementation details or code. The PRD documents what and why, not how. |
| R-008 | `output_quality` | `should` | Should include an executive summary with key metrics: total modules, total stories, total endpoints, total DB models, traceability completeness percentage. |
| R-009 | `output_quality` | `should` | Should render flow diagrams (even as ASCII/text-based) for each module showing the FE -> BE -> DB interaction pattern. |
| R-010 | `data_handling` | `should` | Should include the traceability chain for each module, highlighting any remaining gaps after decisions. |
| R-011 | `output_quality` | `should` | HTML should be clean, readable, and printable. Should use a professional, minimal design with good typography. |
| R-012 | `not_allowed` | `must` | Must not fabricate content. Every piece of information in the PRD must trace to an input artifact. |
| 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: "prd_generation", status: "completed")` before exiting on success. Must call `tracker_update(agent_id: "prd_generation", status: "failed", add_intervention: {...})` before exiting on failure. |
| R-016 | `constraint` | `must` | Must read active modules via `tracker_read(agent_id: "prd_generation", fields: ["md.a"])` when resolving scope. Must not hardcode module lists. |

### Limits

| Resource | Value |
|---|---|
| max_retries | 3 |
| max_tokens | 65536 |
| max_html_size_mb | 10 |
| timeout_seconds | 900 |

---

## Scope Boundary

**In scope:**
- Generating a comprehensive HTML PRD from all upstream artifacts
- Covering all three layers (FE, BE, DB) for every module
- Including executive summary, module overview, per-module detail
- Documenting all decisions with reasoning and impact
- Creating navigable TOC with anchor links
- Including global architecture, security, integrations sections
- Including traceability information and completeness metrics
- Rendering flow diagrams within the HTML

**Out of scope:**
- Generating implementation code
- Making decisions (decisions come from decisions.json)
- Modifying any input artifacts
- Producing separate documents per module (single unified PRD)
- Interactive content (the HTML is static/read-only)
- Hosting or deploying the PRD

---

## Triggers

- Orchestrator activates this agent after both architect_reconcile and decision_pack complete
- Requires decisions.json to exist (even if empty)
- In retrofit mode, the PRD reflects only changed modules but maintains the full document structure

---

## Checkpoints

| ID | Description | Action |
|---|---|---|
| `CP-001` | All input artifacts loaded from all phases | `log` |
| `CP-002` | Executive summary and module overview generated | `log` |
| `CP-003` | Per-module detail sections generated for all modules | `notify` — progress update on large systems |
| `CP-004` | Global architecture and security sections generated | `log` |
| `CP-005` | Decisions section generated with all user decisions | `log` |
| `CP-006` | TOC and anchor links generated and validated | `log` |
| `CP-007` | prd.html written and validated as well-formed HTML | `notify` — PRD is ready for user review |

---

## Validation Criteria

- prd.html file exists and is valid HTML
- HTML has no external dependencies (all CSS inline, no external scripts or images)
- Every module in modules_registry.json has a corresponding section in the PRD
- Every module section contains stories, screens, endpoints, DB models, and flows subsections
- All decisions from decisions.json appear in the decisions section
- TOC links resolve to valid anchor targets within the document
- Executive summary contains key metrics (module count, story count, etc.)
- Global architecture section covers services, middleware, security, and integrations
- No fabricated content — every data point traces to an input artifact
- File size is under the max_html_size_mb limit

---

## Context Sources

- analysis_output.json per module (Phase 1)
- user_stories_{module_id}.json per module (Phase 3)
- fe_details.json per module (Phase 5)
- openapi.json per module (Phase 5)
- prisma_contract.json per module (Phase 5)
- module_flow.json per module, global_flow.json, traceability.json (Phase 8)
- decisions.json (Phase 8)
- All 8 global output artifacts (Phase 7)
- modules_registry.json (Phase 1)

---

## Operation Mode

| Field | Value |
|---|---|
| Type | `autonomous` |
| Fallback | `none` — if PRD generation fails, the user loses the primary documentation deliverable but pipeline can still proceed to implementation prep |

---

## 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` | HTML document generator that produces structured, well-formed HTML with embedded CSS, TOC, anchor links, and professional styling | this agent | Would need to construct HTML strings manually, risking broken markup and poor visual quality |
| `TG-006` | Diagram renderer that can produce inline SVG or ASCII flow diagrams showing FE -> BE -> DB interactions per module | this agent | Flow sections would be text-only descriptions, harder for stakeholders to understand the system architecture |
| `TG-007` | Markdown-to-HTML converter for embedding formatted content within the HTML document structure | this agent | Content authoring would require direct HTML, increasing complexity and error risk |

---

## Generation Readiness

| `generate_agent` Param | Status | Notes |
|---|---|---|
| `fileName` | ready | `prd-generation` |
| `agentName` | ready | `prd_generation` |
| `agentRole` | ready | "Comprehensive HTML PRD Document Generator" |
| `agentDescription` | ready | Full description available from Goal section |
| `operationMode` | ready | `autonomous`, no fallback |
| `goal` | ready | 3 objectives defined with priorities |
| `inputs` | ready | All upstream artifacts: analysis, stories, contracts (FE/BE/DB), flows, global outputs, decisions, traceability |
| `guardrails` | ready | 16 rules defined across constraint, output_quality, scope_boundary, data_handling, not_allowed categories |
| `scopeBoundary` | ready | 8 in-scope items, 6 out-of-scope items |
| `outputFormat` | ready | HTML output with full section structure defined |
| `triggers` | ready | 3 triggers defined |
| `checkpoints` | ready | 7 checkpoints with actions |
| `validation` | ready | 10 validation criteria |
| `contextSources` | ready | 9 context source categories |
| `metadata` | ready | phase: "8", mode: "both", granularity: "global" |
