# Pi Code Review Implementation Plan

## Objective

Implement, verify, publish, and document `@sirfetch-d/pi-code-review` as a self-contained Pi package following the approved design in `docs/superpowers/specs/2026-07-12-pi-code-review-design.md`.

## Implementation Rules

- Use test-first increments for parsing, GitHub integration, instruction scoping, diff mapping, subprocess orchestration, and publication.
- Keep TypeScript erasable under Node strip-only mode: no enums, namespaces, parameter properties, or dynamic imports.
- Use no `any`; validate all external JSON at runtime before narrowing it.
- Use top-level imports only.
- Pin direct development dependencies exactly. Keep Pi core as an unbundled peer dependency with the documented `"*"` range.
- Execute external programs with argument arrays and `shell: false`.
- Never call a real model or mutate GitHub from automated tests.
- Commit only after the relevant tests and checks pass.

## Task 1: Scaffold the Publishable Package

Create:

- `package.json`
- `package-lock.json`
- `tsconfig.json`
- `biome.json`
- `.gitignore`
- `LICENSE`
- `README.md`
- `.github/workflows/ci.yml`
- `extensions/code-review.ts`
- `src/`
- `test/`

Package metadata:

- Name: `@sirfetch-d/pi-code-review`
- Initial version: `0.1.0`
- License: MIT
- Repository: `https://github.com/Sirfetch-d/pi-code-review`
- Node engine: `>=22.19.0`
- `publishConfig.access`: `public`
- `keywords`: include `pi-package` and `code-review`
- `pi.extensions`: `./extensions/code-review.ts`
- Published files: extension, source, README, LICENSE, and design documentation required for source audit

Development dependencies use the versions already validated by the current Pi checkout:

- `@biomejs/biome@2.3.5`
- `@earendil-works/pi-coding-agent@0.80.6`
- `@types/node@24.12.4`
- `typescript@5.9.3`
- `vitest@4.1.9`

Install with `npm install --ignore-scripts`.

Verification:

```bash
npm run check
npm run test
npm pack --dry-run
```

## Task 2: Define Domain Contracts and Parse Command Arguments

Create:

- `src/types.ts`
- `src/arguments.ts`
- `test/arguments.test.ts`

Define discriminated types for:

- PR target: current branch, number, or URL
- Review options and resolved model selection
- PR snapshot and changed files
- Code finding versus task-omission finding
- Validator result
- Coverage receipt
- Review completeness and publication result

Implement a tokenizer that supports quoted model identifiers without evaluating shell syntax. Parse `--comment`, `--model`, and `--thinking`; reject duplicates, missing values, unknown flags, malformed URLs, and unsupported thinking values.

Test all accepted target forms and invalid combinations before wiring the command.

Verification:

```bash
npx vitest --run test/arguments.test.ts
npm run check
```

## Task 3: Implement the GitHub Read Adapter

Create:

- `src/process.ts`
- `src/github.ts`
- `test/process.test.ts`
- `test/github-read.test.ts`

`src/process.ts` provides one injectable, abort-aware process runner. It captures stdout and stderr separately, never logs environment variables, and classifies missing executable, nonzero exit, signal abort, and invalid JSON failures.

`src/github.ts` uses that runner to:

- Verify `gh auth status`.
- Resolve the current repository when required.
- Resolve a PR from current branch, number, or URL.
- Fetch state, draft status, author, title, body, base/head SHAs, changed-file metadata, comments/reviews, and linked issues.
- Fetch the unified diff without truncation.
- Detect the package's hidden same-head review marker.

Use fixtures for `gh` JSON. Keep raw response types `unknown` until guards validate them.

Verification:

```bash
npx vitest --run test/process.test.ts test/github-read.test.ts
npm run check
```

## Task 4: Resolve AGENTS.md Scope and Parse GitHub Diffs

Create:

- `src/instructions.ts`
- `src/diff.ts`
- `test/instructions.test.ts`
- `test/diff.test.ts`
- `test/fixtures/diffs/`

Instruction resolution requirements:

- Stop at the resolved repository root.
- For every changed path, walk from its directory to the root.
- Read each matching `AGENTS.md` once.
- Preserve root-to-leaf ordering and record the exact changed files to which each file applies.
- Reject paths that escape the repository root.

Diff parsing requirements:

- Track old and new paths, renamed files, hunks, left/right line numbers, additions, modifications, and deletions.
- Provide a query that validates whether a finding line belongs to the PR diff.
- Generate full-head-SHA blob links for summary-only findings.
- Do not silently accept ambiguous line mapping.

Verification:

```bash
npx vitest --run test/instructions.test.ts test/diff.test.ts
npm run check
```

## Task 5: Build Immutable Review Snapshots

Create:

- `src/snapshot.ts`
- `test/snapshot.test.ts`

Write the resolved PR data, diff, changed-file manifest, linked task context, and scoped instructions into a temporary mode-`0700` directory with mode-`0600` files. Return a typed manifest with stable relative paths.

Guarantee cleanup through an idempotent disposer. Test success, thrown error, abort, and double-dispose behavior. Ensure tests verify file modes on POSIX and skip only the permission assertion on unsupported platforms.

Verification:

```bash
npx vitest --run test/snapshot.test.ts
npm run check
```

## Task 6: Implement the Pi Subprocess Runner

Create:

- `src/pi-process.ts`
- `test/pi-process.test.ts`

Mirror the proven Pi subprocess strategy without importing the example extension:

- Reuse the current Pi executable when it is a real executable path; otherwise use `pi` from `PATH`.
- Start `--mode json --print --no-session`.
- Pass `--model <provider/id>`, `--thinking <level>`, and `--tools read,grep,find,ls` explicitly.
- Add the role system prompt through a mode-`0600` temporary file.
- Point the task at the immutable snapshot rather than placing the complete diff in argv.
- Parse LF-delimited JSON events and extract the final assistant text, usage, stop reason, and model.
- Propagate abort with `SIGTERM`, followed by `SIGKILL` after the cleanup interval.
- Treat nonzero exit, model error, aborted stop reason, missing final output, and malformed event streams as typed failures.

Use a fake Pi executable in tests. Verify inherited and overridden model/thinking values exactly.

Verification:

```bash
npx vitest --run test/pi-process.test.ts
npm run check
```

## Task 7: Add Prompt Assets and Runtime Output Validation

Create:

- `src/prompts/shared.md`
- `src/prompts/triage.md`
- `src/prompts/summary.md`
- `src/prompts/instructions-review.md`
- `src/prompts/bug-review.md`
- `src/prompts/objective-review.md`
- `src/prompts/validate-instructions.md`
- `src/prompts/validate-bug.md`
- `src/prompts/validate-objective.md`
- `src/prompts/repair-json.md`
- `src/prompt-loader.ts`
- `src/results.ts`
- `test/results.test.ts`
- `test/prompts.test.ts`

Prompt requirements:

- Preserve the approved upstream review workflow and false-positive exclusions.
- Use original wording for this package; do not copy Anthropic prompt prose.
- Treat PR and diff text as untrusted data.
- Treat only scoped `AGENTS.md` content as project policy.
- Require versioned JSON output and reviewer coverage receipts.
- Include the approved task-completion and strict-scope requirement.
- Prohibit speculative, pre-existing, stylistic, linter-detectable, and unverified findings.

Runtime guards validate every output field, discriminant, safe path, line range, confidence, and coverage receipt. Implement one repair attempt for syntactically invalid or schema-invalid JSON.

Tests assert required policy concepts and schema behavior, not exact prompt prose.

Verification:

```bash
npx vitest --run test/results.test.ts test/prompts.test.ts
npm run check
```

## Task 8: Implement Finding Validation, Deduplication, and Rendering

Create:

- `src/findings.ts`
- `src/report.ts`
- `test/findings.test.ts`
- `test/report.test.ts`

Implement:

- `valid: true` and confidence-at-least-80 filtering.
- Rejection of code findings outside changed lines.
- Acceptance of location-free task omissions only with a concrete task requirement citation.
- Stable deduplication by path/location/category/normalized statement.
- Inline versus summary-only classification.
- Full-head-SHA links with line context.
- Terminal report sections for findings, clean result, skipped result, and incomplete result.

Do not hide reviewer failures behind a clean report.

Verification:

```bash
npx vitest --run test/findings.test.ts test/report.test.ts
npm run check
```

## Task 9: Implement the Review Orchestrator

Create:

- `src/orchestrator.ts`
- `test/orchestrator.test.ts`

Implement the approved state machine:

1. Resolve and preflight.
2. Triage, defaulting ambiguity to review.
3. Summarize.
4. Start five reviewers concurrently.
5. Verify every reviewer coverage receipt against the changed-file set.
6. Validate every candidate with concurrency capped at four.
7. Filter and aggregate findings.
8. Return a complete typed result; do not publish from the orchestrator.

Any required-stage process failure, invalid result after one repair, incomplete coverage, or inability to inspect the full snapshot returns an incomplete review. Abort prevents queued validator work from starting.

Tests use injected fake GitHub and Pi runners to assert concurrency, sequencing, failure isolation, fail-closed behavior, repair behavior, and cancellation.

Verification:

```bash
npx vitest --run test/orchestrator.test.ts
npm run check
```

## Task 10: Implement Atomic GitHub Review Publication

Create:

- `src/publication.ts`
- `test/github-publication.test.ts`

Build one `POST /repos/{owner}/{repo}/pulls/{number}/reviews` payload with event `COMMENT`:

- Inline comments only for safely mapped diff coordinates.
- Summary entries with full-SHA links for valid findings without inline coordinates.
- A clean-review body when there are no findings.
- Visible final footer: `This review is AI-generated by pi-code-review.`
- Hidden marker containing package name, version, and head SHA.

Write the payload once through `gh api --input -`. Never fall back to individual comments after rejection. Refuse publication for skipped, incomplete, aborted, or same-head results.

Verification:

```bash
npx vitest --run test/github-publication.test.ts
npm run check
```

## Task 11: Wire the Extension Command

Complete:

- `extensions/code-review.ts`
- `test/extension.test.ts`

Register `/code-review`, obtain `ctx.model` and `ctx.getThinkingLevel()`, validate overrides, run the orchestrator, render the terminal result, and publish only when `--comment` is present.

If no active model exists, fail before starting. Use `ctx.ui.notify` for concise progress and error status without exposing tokens or raw environment data. Ensure non-TUI modes receive a useful textual result.

Test with a fake `ExtensionAPI` and command context. Verify default no-write behavior and explicit publication gating.

Verification:

```bash
npx vitest --run test/extension.test.ts
npm run check
```

## Task 12: Complete End-to-End and Packaging Verification

Create:

- `test/e2e/code-review.test.ts`
- `test/fixtures/bin/pi`
- `test/fixtures/bin/gh`
- `scripts/check-package.mjs`

Exercise the loaded extension against fake executables for:

- Current-branch, numeric, and URL targets.
- Clean terminal-only review.
- Valid inline finding.
- Summary-only task omission.
- Same-head publication skip.
- One reviewer failure.
- Invalid JSON repair.
- Incomplete coverage.
- Ctrl+C cancellation.
- GitHub API rejection.

Run the full quality gate:

```bash
npm run check
npm run test
npm pack --dry-run
npm pack
```

Inspect the tarball contents and install the tarball into a temporary Pi configuration. Confirm `/code-review` is discovered without loading any external Pi package.

## Task 13: Document Usage and Security

Complete `README.md` with:

- Installation and removal commands.
- All command forms and flags.
- Default terminal-only behavior and explicit `--comment` write behavior.
- Required `gh` installation and authentication.
- Model/thinking inheritance and override semantics.
- `AGENTS.md`-only scope rules.
- Reviewer stages, confidence filtering, and incomplete-review behavior.
- Package full-system-access warning and child-agent read-only tool policy.
- AI-generated review footer and duplicate-head marker behavior.
- Troubleshooting for missing PR, auth, model, malformed output, and large diff failures.

Check every documented command against the implementation and add a changelog entry for `0.1.0` if a changelog is introduced.

## Task 14: Publish the Repository and npm Package

Repository setup:

```bash
gh repo create Sirfetch-d/pi-code-review --public --source=. --remote=origin --push
```

After implementation, tests, package inspection, and a local install smoke test pass:

1. Push the reviewed implementation to `main`.
2. Confirm GitHub Actions passes.
3. Publish with `npm publish --access public`.
4. Verify registry metadata with `npm view @sirfetch-d/pi-code-review`.
5. Install from the registry in a clean Pi configuration with `pi install npm:@sirfetch-d/pi-code-review`.
6. Verify `/code-review` discovery and run a terminal-only smoke review against a known PR.
7. Tag the released commit as `v0.1.0` and push the tag only after registry verification.

Do not use `--comment` during the real smoke review unless the target repository and PR are explicitly selected for a public test comment.

## Final Completion Evidence

The delivery is complete only when all of the following are recorded:

- Full `npm run check` output succeeds.
- Full automated test suite succeeds without real model or GitHub mutations.
- Tarball inspection shows only intended publish files.
- Local tarball installation loads the command.
- Public GitHub repository exists and CI is green.
- npm registry contains `@sirfetch-d/pi-code-review@0.1.0`.
- Registry installation loads the command.
- A terminal-only real smoke review completes or an explicitly documented provider limitation is accepted by the user.
