# Architecture Documentation: `pi-c-review`

> **Extension Architecture for Pi Coding Agent (`pi.dev`)**  
> Document Version: 1.0.0  
> Status: Approved & Implemented

---

## 1. Executive Summary

`pi-c-review` is a modular TypeScript extension engineered for the **Pi Coding Agent** (`@earendil-works/pi-coding-agent` / `pi.dev`). Its primary architecture bridges human developer workflows, terminal user interfaces (TUI), and LLM reasoning to enforce strict C programming standards (memory management, buffer boundaries, MISRA-C rules, and project-specific requirements) while delivering deterministic, compilation-ready corrected C code.

---

## 2. Architectural Principles

1. **Zero External Binary Dependency**: Operates out-of-the-box without requiring host-installed compilers (`gcc`, `clang`) or static linters (`cppcheck`, `clang-tidy`), while leaving open hooks for hybrid static verification.
2. **Deterministic Contract Enforcing**: Uses TypeBox runtime schemas for tool parameters and strict JSON response formatting for LLM communication.
3. **Fail-Safe Mutations**: No destructive file writes occur without developer confirmation (`ctx.ui.confirm`) and automatic `.bak` backup generation.
4. **Pluggable Rules Engine**: Rules are organized hierarchically: Built-in Presets → Project Configuration (`.creviewrc.json`) → Ad-hoc Command Line Directives.
5. **Seamless Pi Integration**: Deeply integrates with Pi's `ExtensionAPI`, `ExtensionContext`, slash command registry, agent event bus, and TUI components.

---

## 3. High-Level Architecture Diagram

```mermaid
graph TD
    subgraph PiTerminal["Pi.dev Runtime Environment"]
        UI["Terminal User Interface (TUI)"]
        EventBus["Agent Event Bus (pi.on)"]
        CmdRegistry["Command Registry (pi.registerCommand)"]
        ToolRegistry["Tool Registry (pi.registerTool)"]
        AgentCore["Agent Reasoning Loop (LLM)"]
    end

    subgraph PiCReview["pi-c-review Extension Core"]
        Entry["Extension Entrypoint (src/index.ts)"]
        
        subgraph Commands["Command Subsystem"]
            CRevCmd["/c-review (review-command.ts)"]
            CFixCmd["/c-fix (fix-command.ts)"]
            CRulesCmd["/c-rules (rules-command.ts)"]
            CRevAllCmd["/c-review-all (review-all-command.ts)"]
        end

        subgraph Tools["Tool Subsystem"]
            CTool["c_review_and_fix (c-review-tool.ts)"]
        end

        subgraph Engine["Engine Subsystem"]
            ConfigMgr["Config & Rules Resolver (config.ts)"]
            Presets["Built-in Presets (memory, buffer, misra)"]
            StaticScan["Static Pre-Scanner (static-scanner.ts)"]
            ScoreEngine["Compliance Scoring (scoring.ts)"]
            PromptBld["Prompt Builder & JSON Parser (prompt-builder.ts)"]
            DiffRnd["LCS Diff Engine (diff-renderer.ts)"]
        end

        subgraph Storage["File System & Persistence"]
            TargetC["Target C Source (.c / .h)"]
            ConfigJSON[".creviewrc.json"]
            BackupFile["*.bak Backup Files"]
        end
    end

    %% Wiring
    Entry --> CmdRegistry
    Entry --> ToolRegistry
    Entry --> EventBus

    CmdRegistry --> CRevCmd
    CmdRegistry --> CFixCmd
    CmdRegistry --> CRulesCmd

    ToolRegistry --> CTool

    CRevCmd --> ConfigMgr
    CFixCmd --> ConfigMgr
    CRulesCmd --> ConfigMgr
    CTool --> ConfigMgr

    ConfigMgr --> Presets
    ConfigMgr --> ConfigJSON

    CRevCmd --> TargetC
    CFixCmd --> TargetC
    CFixCmd --> BackupFile

    CRevCmd --> PromptBld
    CFixCmd --> PromptBld
    CTool --> PromptBld

    PromptBld --> AgentCore
    AgentCore --> PromptBld
    PromptBld --> DiffRnd
    DiffRnd --> UI
```

---

## 4. Subsystem Breakdown

### 4.1. Extension Entrypoint (`src/index.ts`)
The root module exported as default function `cReviewExtension(pi: ExtensionAPI)`. It handles:
- Registering interactive slash commands with Pi's command parser.
- Registering the TypeBox-validated tool `c_review_and_fix`.
- Subscribing to Pi's lifecycle events (e.g. `tool_result`) to detect whenever `.c` or `.h` files are modified by other agent tools and advising the developer to review them.

### 4.2. Command Subsystem (`src/commands/`)
Interactive developer controls mapped directly to terminal slash commands:
- **`review-command.ts`**: Implements `/c-review <filepath> [custom requirement]`. Runs fast static pre-scan, computes compliance score, and dispatches a structured review request into Pi's conversation stream.
- **`fix-command.ts`**: Implements `/c-fix <filepath> [custom requirement]`. Requests confirmation via `ctx.ui.confirm()`, creates a `.bak` backup file, invokes review and code generation, and instructs the agent to write the corrected code.
- **`rules-command.ts`**: Implements `/c-rules [list|init|presets]`. Displays active configuration or creates a starter `.creviewrc.json`.
- **`review-all-command.ts`**: Implements `/c-review-all [directory]`. Discovers all `.c` and `.h` files, executes local static audits, outputs project-wide health metrics and scores, and offers interactive deep LLM review for critical files.

### 4.3. Tool Subsystem (`src/tools/`)
- **`c-review-tool.ts`**: Exposes the `c_review_and_fix` tool to Pi's LLM agent. Defined using `@sinclair/typebox` schema, allowing autonomous subagents or primary agents to review arbitrary C snippets or files during implementation tasks.

### 4.4. Rules & Presets Engine (`src/presets/`, `src/config.ts`)
A three-tier hierarchical rules resolution engine:
1. **Tier 1 (Built-in Presets)**: `memory-safety`, `buffer-security`, `embedded-misra`.
2. **Tier 2 (Project Config)**: `.creviewrc.json` searched upwards from the active workspace directory.
3. **Tier 3 (Ad-hoc Rules)**: User-specified constraints passed as arguments to slash commands or tool executions.

### 4.5. Analysis, Scoring & Diff Engine (`src/engine/`)
- **`static-scanner.ts`**: High-performance local pattern analyzer executing in < 10ms. Intercepts banned functions (`gets`, `strcpy`, `strcat`, `sprintf`, `atoi`), checks contextual allocations for NULL verification (`malloc`/`calloc`/`realloc`), verifies pointer nullification after `free()`, checks `fopen()`, enforces compound braces on control flow statements, and recognizes `// NOLINT` inline suppression tags.
- **`scoring.ts`**: Computes weighted 0-100 compliance scores and letter grades (`A` through `F`). Penalizes critical (-15), warning (-5), and style (-1) violations with category caps, and renders visual terminal progress bars and scorecards.
- **`prompt-builder.ts`**: Builds system and user prompts instructing the LLM to analyze C code line-by-line and return a strict JSON payload containing `violations` and complete `correctedCode`. Includes a resilient parser that strips markdown code fences and handles trailing conversational artifacts.
- **`diff-renderer.ts`**: A standalone Longest Common Subsequence (LCS) line-diff algorithm that computes unified diffs and formats them with ANSI colors (`+` green, `-` red, context gray) for the terminal UI.

---

## 5. Interaction Lifecycles

### 5.1. User Slash Command Flow (`/c-review`)

```mermaid
sequenceDiagram
    autonumber
    actor Dev as Developer
    participant PiTUI as Pi Terminal UI
    participant Cmd as review-command
    participant Config as config.ts
    participant FS as Local File System
    participant Agent as Pi Agent Loop

    Dev->>PiTUI: /c-review src/main.c "Ensure NULL check on malloc"
    PiTUI->>Cmd: execute(args, ctx)
    Cmd->>FS: readFileSync("src/main.c")
    Cmd->>Config: loadConfig() + resolveAllRules()
    Config-->>Cmd: Return active rules list
    Cmd->>PiTUI: ctx.ui.notify("Reviewing src/main.c against N rules...")
    Cmd->>Agent: pi.sendUserMessage(structuredPrompt)
    Agent->>PiTUI: Stream violations list + full corrected C code
```

### 5.2. Auto-Fix Flow (`/c-fix`)

```mermaid
sequenceDiagram
    autonumber
    actor Dev as Developer
    participant PiTUI as Pi Terminal UI
    participant FixCmd as fix-command
    participant FS as Local File System
    participant Agent as Pi Agent Loop

    Dev->>PiTUI: /c-fix src/main.c
    FixCmd->>PiTUI: ctx.ui.confirm("Apply corrections to src/main.c?")
    Dev-->>PiTUI: Confirmed (Yes)
    FixCmd->>FS: writeFileSync("src/main.c.bak", originalCode)
    FixCmd->>PiTUI: ctx.ui.notify("Backup created at src/main.c.bak")
    FixCmd->>Agent: pi.sendUserMessage(fixInstructions)
    Agent->>FS: Overwrite src/main.c with corrected C code
    Agent->>PiTUI: Display diff and completion summary
```

---

## 6. Security & Isolation

- **Non-destructive Defaults**: Automatic backup file generation (`<file>.bak`) prior to applying fixes.
- **Explicit User Consent**: Interactive prompt confirmation before mutating code on disk.
- **Sandboxed Execution**: Extension runs within Node.js / Pi process boundaries without invoking external shell sub-processes (`child_process.exec`), mitigating shell injection vulnerabilities.

---

## 7. Deployment & Distribution Models

1. **Project-Local Installation**: Located at `.pi/extensions/pi-c-review` within any C project workspace.
2. **Global Installation**: Copied to `~/.pi/agent/extensions/pi-c-review` for machine-wide availability across all C projects.
3. **Package Distribution**: Installable via `pi install npm:pi-c-review` or `pi install git:<repo>`.
