---

stage: 4
stage_id: "04"
title: "Project Synthesis"
workflow: understand
estimated_tokens: 3000

context:
  static:
    persona: "software architect creating project-level understanding"
    purpose: "Synthesize module understandings into project architecture"
  dynamic:
    - key: mode
      source: cli_arg
      default: "standard"

tier:
  name: balanced
  hint: "Architectural reasoning task requiring synthesis of module understandings"

pre_validation:
  - check: module_aggregation_complete
    description: "Stage 3 completed with module-level understanding cached"
    severity: error

# Guardrails
guardrails:
  enforcement: active
  allowed_tools:
    - civyk-repoix
    - Read
    - Grep
    - Glob
    - Bash
  forbidden_actions:
    - "Delete any files"
    - "Modify any source files"
  read_only: true

execution_flow:
  - step: 1
    type: action
    name: recall_modules
    instruction: "Recall all module-level understandings"
    output_variable: module_summaries
  - step: 2
    type: action
    name: identify_architecture
    instruction: "Identify architectural patterns and component relationships"
    output_variable: architecture
  - step: 3
    type: action
    name: map_dependencies
    instruction: "Map cross-module dependencies and data flows"
    output_variable: dependencies
  - step: 4
    type: action
    name: store_project_understanding
    instruction: "Store project-level understanding in cache"


post_validation:
  - check: project_understanding_stored
    description: "Project-level understanding stored in cache"
    severity: error

next:
  terminal: true
  description: "Stage 4 is always terminal — docstrings are handled in Stage 2"
version: 1.0.0
---

# Stage 4: Project Synthesis

Synthesize module-level understandings into a comprehensive project architecture understanding.

## Prerequisites

- Stage 3 completed (module aggregation done)
- Module understandings cached in repoix

## Mode Check

```text
IF mode == "quick" OR mode == "standard" THEN
    SKIP "Mode is '{mode}' - skipping project synthesis"
    OUTPUT "Mode is '{mode}' - skipping project synthesis"
    EXIT completed
END IF
```

## Critical Rules

| Rule | Action |
|------|--------|
| Recall all modules | **MUST** get all module understandings first |
| Identify patterns | **MUST** analyze architectural patterns |
| Map relationships | **MUST** document component relationships |
| Store project | **MUST** call understand(action="store") with scope="project" |
| No sub-agents | **DO NOT** spawn sub-agents for this stage |
| Save checkpoint | **MUST** clear checkpoint after completion |

**CRITICAL: DO NOT Use Sub-Agents**

Project synthesis requires consolidating ALL module understandings into a single
coherent architectural view. This synthesis task:

- Needs full context from all modules simultaneously
- Cannot be parallelized (single output)
- Would lose critical context if delegated to a sub-agent

**Run this stage directly in the main agent.** Sub-agents are appropriate for
independent parallel tasks (Stage 2 file analysis, Stage 3 module aggregation),
but NOT for synthesis tasks that require full context.

---

## Tier Specification

```text
Tier: balanced
Hint: Architectural reasoning requiring synthesis of multiple modules
```

This stage uses the `balanced` tier for project synthesis. Creating a coherent architectural understanding from multiple modules requires significant reasoning.

---

## Step 1: Recall All Module Understandings

```text
# Get all module-level understandings
understand(action="stats", scope="module")

FOR each module in modules:
    understand(action="recall", target="<module_path>")
    collect for synthesis
```

---

## Step 2: Identify Architectural Patterns

Analyze the collected module understandings to identify:

| Pattern | Description |
|---------|-------------|
| Layered Architecture | Clear separation of concerns (UI, business, data) |
| MVC/MVP/MVVM | Model-View-Controller or variants |
| Microservices | Independent, loosely-coupled services |
| Monolithic | Single unified codebase |
| Plugin/Extension | Core with extensible plugins |
| Event-Driven | Components communicate via events |
| Repository Pattern | Data access abstraction |
| Factory Pattern | Object creation abstraction |

**Document:**
- Primary architecture pattern
- Secondary patterns used
- Deviations or hybrid approaches

---

## Step 3: Map Component Relationships

Create a high-level component map:

```text
+------------------+     +------------------+
|      CLI         |---->|    Core Engine   |
+------------------+     +------------------+
        |                        |
        v                        v
+------------------+     +------------------+
|   MCP Server     |     |   Data Layer     |
+------------------+     +------------------+
        |                        |
        +----------+-------------+
                   |
                   v
          +------------------+
          |   External APIs  |
          +------------------+
```

**Document:**
- Entry points (CLI, API, UI)
- Core components and their responsibilities
- Data flow between components
- External dependencies and integrations

---

## Step 4: Store Project Understanding

```text
understand(
    action="store",
    scope="project",
    target="project",
    purpose="<one-line project purpose from README or analysis>",
    importance="critical",
    key_points=[
        "Architecture: <primary pattern>",
        "Core modules: <list main modules>",
        "Entry points: <CLI, API, etc.>",
        "Key patterns: <design patterns used>"
    ],
    gotchas=[
        "<critical initialization order>",
        "<cross-cutting concerns>",
        "<common pitfalls>"
    ],
    analysis="<detailed analysis - 3-5 sentences describing the project's
              architecture, main components, how they interact, and key
              design decisions>"
)
```

**Example:**

```text
understand(
    action="store",
    scope="project",
    target="project",
    purpose="Civyk Hatch Advanced - MCP-based development workflow tool",
    importance="critical",
    key_points=[
        "Architecture: Layered with CLI + MCP server interfaces",
        "Core modules: workflow engine, prompt loader, state manager",
        "Entry points: CLI (typer), MCP server (JSON-RPC)",
        "Key patterns: State machine workflows, YAML prompts, Jinja2 templates"
    ],
    gotchas=[
        "MCP and CLI share workflow configs via SkillExecutor",
        "State persists in .civyk-hatch/ or specs/<feature>/ folders",
        "Prompts use frontmatter for metadata + markdown for content",
        "repoix MCP provides codebase intelligence"
    ],
    analysis="Civyk Hatch Advanced provides structured development workflows via
              CLI or MCP interface. The core engine executes stage-based workflows
              defined in Python configs with prompts stored as markdown files.
              The SkillExecutor orchestrates context loading, validation, and
              prompt rendering. State management handles both project-level and
              feature-scoped workflows. The architecture supports extension via
              new workflow configs and prompt files."
)
```

---

## Step 5: Generate Completion Report

```text
=== PROJECT SYNTHESIS COMPLETE ===

Duration: {duration}
Mode: {mode}

=== PROJECT UNDERSTANDING ===
Architecture: {architecture_pattern}
|-- Primary pattern: {primary_pattern}
|-- Secondary patterns: {secondary_patterns}

Core modules: {module_count}
|-- Critical: {critical_count}
|-- High importance: {high_count}
|-- Medium importance: {medium_count}

Entry points: {entry_points}
|-- CLI: {cli_entries}
|-- API: {api_entries}
|-- Other: {other_entries}

=== COMPONENT MAP ===
Dependencies mapped: {dependency_count}
|-- Internal dependencies: {internal_deps}
|-- External dependencies: {external_deps}

Data flows identified: {flow_count}
|-- Request/response: {request_flows}
|-- Event-based: {event_flows}
|-- Data pipeline: {pipeline_flows}

=== CACHE STATUS ===
Understanding stored:
|-- Scope: project
|-- Target: project
|-- Importance: critical

Total cache entries:
|-- File-level: {file_entries}
|-- Module-level: {module_entries}
|-- Project-level: 1

=== CHECKPOINT STATUS ===
Checkpoint: Cleared (stage complete)
[ok] UNDERSTAND WORKFLOW COMPLETE (deep mode)
```

---

## Exit Conditions

### Mode Check - Quick/Standard Mode

If `mode != "deep"`:

```text
=== SKIPPING PROJECT SYNTHESIS ===

Mode '{mode}' does not include project synthesis.
Use --mode=deep for full project understanding.

[ok] UNDERSTAND WORKFLOW COMPLETE ({mode} mode)
```

### Project Synthesis Complete

```text
=== PROJECT SYNTHESIS COMPLETE ===

Project-level understanding has been stored.

[ok] UNDERSTAND WORKFLOW COMPLETE (deep mode)
```
