# Design Documentation: `pi-c-review`

> **Detailed Technical Design Specification**  
> Document Version: 1.0.0  
> Status: Approved & Implemented

---

## 1. Introduction

This document describes the internal software design, data structures, algorithms, and interfaces of `pi-c-review`. It serves as the definitive reference for engineers maintaining, testing, or extending the extension.

---

## 2. Domain Models & Data Contracts (`src/types.ts`)

The domain model represents the core entities involved in C code audits, findings, rule configurations, and code modifications.

```typescript
export type Severity = "critical" | "warning" | "style";

export interface Violation {
  line?: number;
  rule: string;
  severity: Severity;
  explanation: string;
  suggestedFix: string;
}

export interface ReviewResult {
  filePath?: string;
  violations: Violation[];
  correctedCode: string;
  summary: string;
  rulesApplied: string[];
}

export interface RulePreset {
  name: string;
  description: string;
  rules: string[];
}

export interface CReviewConfig {
  presets?: string[];
  customRules?: string[];
  createBackup?: boolean;
  strictMode?: boolean;
}

export interface ReviewRequest {
  code: string;
  filePath?: string;
  adHocRequirements?: string[];
  config?: CReviewConfig;
}
```

---

## 3. Component Design & Specifications

### 3.1. Configuration Manager (`src/config.ts`)

#### Responsibilities
- Locate configuration files up the directory hierarchy starting from `process.cwd()`.
- Parse `.creviewrc.json` with fallback defaults.
- Merge preset rules, project rules, and ad-hoc rules into a unified execution ruleset.
- Scaffold starter configuration templates on demand.

#### Configuration Cascading Hierarchy
```
┌──────────────────────────────────────────────┐
│  Ad-hoc Command Rules (e.g. from CLI prompt) │ (Highest Priority)
├──────────────────────────────────────────────┤
│  Custom Rules in .creviewrc.json             │ (Project Specific)
├──────────────────────────────────────────────┤
│  Active Presets in .creviewrc.json           │ (Selected Profiles)
├──────────────────────────────────────────────┤
│  Default Presets (memory-safety, buffer-sec) │ (Lowest Fallback)
└──────────────────────────────────────────────┘
```

#### Supported Configuration File Names
1. `.creviewrc.json`
2. `.creviewrc`
3. `c-review.config.json`

---

### 3.2. Rule Presets Catalog (`src/presets/`)

Rule sets are modularized into separate TypeScript modules conforming to `RulePreset`:

| Preset | Target Focus | Key Guardrails |
| :--- | :--- | :--- |
| **`memory-safety.ts`** | Dynamic Memory | • Immediate NULL check after `malloc`, `calloc`, `realloc`.<br>• Deallocation on all exit paths (early returns, error branches).<br>• Zero out pointer (`ptr = NULL`) after `free(ptr)`.<br>• Prevent double-free and use-after-free.<br>• Safe `realloc` pattern (temporary pointer to prevent leak on failure). |
| **`buffer-security.ts`** | Buffer & String Safety | • Total ban on `gets()` (replace with `fgets()`).<br>• Replace unbounded string copies (`strcpy`, `strcat`) with bounded variants (`strncpy`, `strncat`).<br>• Enforce explicit null-termination `buf[size - 1] = '\0'`.<br>• Replace `sprintf()` with `snprintf()`.<br>• Array boundary validation before copy operations. |
| **`embedded-misra.ts`** | Safety-Critical / MISRA-C | • Mandatory fixed-width types from `<stdint.h>` (`uint8_t`, `int32_t`).<br>• Explicit variable initialization before first read.<br>• Compulsory `default:` clause on all `switch` statements.<br>• Prohibition of non-structured `goto` jumps.<br>• Mandatory return value checking for library/OS calls (`fopen`, `fclose`, etc.).<br>• Explicit `volatile` qualifier for hardware registers. |

---

### 3.3. Prompt Engineering & Parser Engine (`src/engine/prompt-builder.ts`)

#### Prompt Structure
The review prompt is strictly separated into a **System Prompt** defining the persona and schema constraints, and a **User Prompt** containing the C code and numbered rules.

```
+-------------------------------------------------------------+
| System Prompt                                               |
| - Role: Expert static analysis engine & senior C programmer |
| - Output Contract: Strict JSON format                       |
| - Fields: summary, violations (line, rule, fix), correctedCode |
+-------------------------------------------------------------+
| User Prompt                                                 |
| - Active Requirements List (1..N)                           |
| - File Path (if applicable)                                 |
| - Target C Source Code (enclosed in ```c fences)            |
+-------------------------------------------------------------+
```

#### Defensive JSON Parser
Language models occasionally prepend conversational pleasantries or enclose JSON inside Markdown code fences (` ```json ... ``` `). The parser:
1. Strips leading and trailing Markdown code fences.
2. Extracts substring spanning from the first occurrence of `{` to the last occurrence of `}`.
3. Parses with `JSON.parse` and maps fields into a strongly typed `ReviewResult`.
4. Sanitizes severity strings to valid enum values (`critical` | `warning` | `style`).

---

### 3.4. Local Static Scanner Engine (`src/engine/static-scanner.ts`)

#### Responsibilities
- Instantaneous (< 10ms) local pattern analysis on C source code without external dependencies or LLM token overhead.
- Contextual multi-line analysis for allocation checks (`malloc`/`calloc`/`realloc` followed by `if (!ptr)`), pointer nullification after `free()`, and `fopen()` validation.
- Support for inline suppression comments (`// NOLINT` or `// NOLINT(RULE-ID)`).

#### Static Pattern Catalog
- `SEC-01`: Banned `gets()` (Critical)
- `SEC-02`: Banned `strcpy()` (Critical)
- `SEC-03`: Banned `strcat()` (Critical)
- `SEC-04`: Banned `sprintf()` (Critical)
- `SEC-05`: Unsafe `atoi()` (Warning)
- `SEC-06`: Unsafe `atof()` (Warning)
- `MEM-01`: Allocation without NULL check (Critical, contextual)
- `MEM-02`: Free without pointer nullification (Warning, contextual)
- `RES-01`: File open without NULL check (Warning, contextual)
- `FLO-01..04`: Control flow statements (`if`, `else`, `for`, `while`) without compound braces `{ ... }` (Warning)
- `TYP-01..02`: Non-fixed-width types `short`, `long long` (Style)

---

### 3.5. Compliance Scoring Engine (`src/engine/scoring.ts`)

#### Scoring Formula
- **Starting Base**: 100 points
- **Critical Penalty**: -15 points each (capped at -60 max deduction)
- **Warning Penalty**: -5 points each (capped at -25 max deduction)
- **Style Penalty**: -1 point each (capped at -10 max deduction)
- **Grade Scale**:
  - `A`: 90 - 100
  - `B`: 75 - 89
  - `C`: 60 - 74
  - `D`: 40 - 59
  - `F`: 0 - 39
- **Visual Terminal Rendering**: ANSI progress bar (`████░░░░`) and boxed summary scorecard.

---

### 3.6. Multi-File Project Audit (`src/commands/review-all-command.ts`)

#### Responsibilities
- Recursively discovers all `.c` and `.h` files under target directory (skipping `node_modules`, `.git`, `build`, `dist`).
- Executes static analysis across all files in parallel.
- Sorts results by score ascending (lowest score / most vulnerable files first).
- Generates ASCII/ANSI formatted summary table with file scores, grades, and issue breakdowns.
- Prompts developer with `ctx.ui.confirm` to send critical files to LLM for full auto-correction.

---

### 3.7. LCS Terminal Diff Engine (`src/engine/diff-renderer.ts`)

#### Algorithm
The diff engine uses the **Longest Common Subsequence (LCS)** dynamic programming algorithm to compare the original and corrected C source code line-by-line:

1. Let $O = [o_1, o_2, \dots, o_m]$ be the original lines and $C = [c_1, c_2, \dots, c_n]$ be the corrected lines.
2. Construct DP table:
   $$DP[i][j] = \begin{cases} DP[i-1][j-1] + 1 & \text{if } o_{i} = c_{j} \\ \max(DP[i-1][j], DP[i][j-1]) & \text{otherwise} \end{cases}$$
3. Backtrack from $(m, n)$ to $(0, 0)$ to reconstruct the list of `added`, `removed`, and `unchanged` diff lines.
4. **Context Windowing**: Filters diff to show only modified lines surrounded by $k$ (default: 3) lines of unchanged context.
5. **ANSI Colorization**:
   - `+ <line>`: Green (`\x1b[32m`)
   - `- <line>`: Red (`\x1b[31m`)
   - `  <line>`: Dark Gray (`\x1b[90m`)
   - `@@ -Diff @@`: Cyan (`\x1b[36m`)

---

### 3.5. Command Implementations (`src/commands/`)

```mermaid
classDiagram
    class ReviewCommand {
        +register(pi: ExtensionAPI)
        +handler(args: string, ctx: ExtensionCommandContext)
        -parseArgs(args: string): {filePath, adHocRequirement}
        -buildUserMessage(code, rules): string
    }

    class FixCommand {
        +register(pi: ExtensionAPI)
        +handler(args: string, ctx: ExtensionCommandContext)
        -requestConfirmation(ctx): boolean
        -createBackupFile(filePath): string
        -dispatchFixMessage(pi, prompt)
    }

    class RulesCommand {
        +register(pi: ExtensionAPI)
        +handler(args: string, ctx: ExtensionCommandContext)
        -listActiveRules(ctx)
        -initConfigFile(): string
        -displayPresets(ctx)
    }

    ReviewCommand ..> ExtensionAPI
    FixCommand ..> ExtensionAPI
    RulesCommand ..> ExtensionAPI
```

---

### 3.6. Tool Registration (`src/tools/c-review-tool.ts`)

Exposes `c_review_and_fix` via TypeBox parameters:
```typescript
parameters: Type.Object({
  code: Type.String({ description: "The C source code to review and correct" }),
  filePath: Type.Optional(Type.String({ description: "Relative or absolute path to the C file (optional)" })),
  customRequirements: Type.Optional(Type.Array(Type.String())),
  presets: Type.Optional(Type.Array(Type.String()))
})
```
When invoked by the agent LLM, it resolves configuration, constructs prompts, and returns the actionable audit package as structured JSON.

---

## 4. Error Handling & Edge Cases

| Scenario | Handled By | Behavior |
| :--- | :--- | :--- |
| Target file does not exist | `review-command`, `fix-command` | Alerts user via `ctx.ui.notify("File not found: ...", "error")` without throwing unhandled exceptions. |
| `.creviewrc.json` has invalid JSON syntax | `config.ts` | Logs error to console, falls back cleanly to `DEFAULT_CONFIG` without crashing. |
| User rejects confirmation in `/c-fix` | `fix-command.ts` | Halts execution gracefully and logs info notification. |
| File has write permissions issues | `fix-command.ts` | Catches FS errors and notifies user. |
| Code contains no changes | `diff-renderer.ts` | Returns friendly green message `"✓ No changes detected"`. |
| LLM returns text outside JSON | `prompt-builder.ts` | Defensive regex and brace isolation extracts valid JSON substring. |
