# RHA Wrapper

**A compiler-shaped pipeline for LLM code generation.** The prompt is the source language, a frozen test suite is the intermediate representation, the implementation is the target, and the Recursive Healing Algorithm (RHA) is the verification backend — all recorded on a supergit substrate: a real git repository carrying an append-only decision ledger with LLM-workflow metadata.

This is the productization of three layers:

| Layer | Doctrine | Implementation |
|---|---|---|
| **L1 — Test-First IR** | Tests are generated from the spec *before any implementation exists* and then frozen; they are the canonical, machine-checkable contract every later stage must satisfy. | `src/core/pipeline.ts` (Phases A/B), freeze hashes, deterministic IR gate |
| **L2 — RHA** | Failure-triggered, bounded, tree-recursive repair guided by a standing taxonomy of mechanical AI bug classes. | `src/core/rha.ts`, `src/core/taxonomy.ts` |
| **L3 — Supergit** | Every decision is a typed node in an append-only ledger over a real git repo: step index, tree parents, backward causal links, **forward dependency pointers**, commit trailers. | `src/core/substrate.ts` |

## The user experience (unaltered, three steps)

1. **Compile.** The user types a product prompt. The system feature-codes it (F1, F2, …), derives edge cases from each feature's *actual function*, and generates one frozen vitest suite per feature — with strict input isolation: no implementation exists yet, so the tests cannot rationalize one. The user reviews the **IR contract** (feature tree, case inventory, edge/integration counts) and approves. Approval assigns the deterministic contract to development; the suites become read-only (enforced by hash checks and a write-boundary filter, not by prompt discipline).
2. **Build & authenticate.** Each feature is implemented in dependency order against its frozen suite and **authenticated in real time** — its suite runs the moment its code lands. Failures are not patched here; they are recorded as error nodes in the ledger. The user reviews the authentication table and approves.
3. **Applying RHA…** Fully automatic; the user just sees loading. RHA sweeps the artifact with (a) the deterministic bug-class taxonomy — tsc-backed import/symbol/type checks, wiring-contract checks, stub detection, env-var checks — and (b) the full frozen corpus. Each finding is bound to its feature node through the ownership index (**localization**) while detectors run across every node in the same pass and same-class instances elsewhere are fed into the repair context (**generalization by tree inheritance**). RHA picks the upstream-most failing node (the smallest meaningful target), applies a bounded repair (the model can only return files that node owns — anything else is rejected deterministically), reruns the affected check, then reruns the dependents' checks read from the forward pointers. A failure surfacing at a dependent becomes its own error node and its own bounded repair: the recursion is bidirectional and moves through the software like a diagnostic tree. When the corpus is green, the artifact is complete and fully automatically tested.

The final report states, structurally rather than rhetorically: **the artifact was never wholly regenerated** — there is no code path in this system that can write outside one node's ownership boundary, and the frozen IR is verified byte-identical before build, before every episode, and in the final report.

## The supergit substrate

Each job's workspace *is* the open-source git instantiation. On top of it:

- **`.supergit/ledger.csv`** — append-only. Typed rows: `genesis, decision, spec, test, code, result, error, repair, edge`, each with a monotone step index, a tree `parent_id`, and a backward `cause_id`. Forward (downstream-dependency) pointers are dedicated `edge` rows — appended when discovered, never mutating earlier rows.
- **Commit trailers** — every artifact mutation commits with `Supergit-Node / Supergit-Step / Supergit-Type`, synchronizing code position with ledger position in both directions (`node → commit` via `git log --grep`, `commit → node` via the trailer). Error placement maps into the same coordinates through the file-ownership index.
- **`.supergit/graph.json`** — the derived, deterministically rebuildable materialization of the tree + edges that RHA traverses, so repair consumes the pre-computed graph instead of reconstructing it from code.
- **`.supergit/spec.json`, `.supergit/ir-manifest.json`** — the feature-coded spec and the IR schema document (feature ↔ suite ↔ case inventory ↔ freeze hashes).

A healed run reads like this in the ledger (real output):

```
28 error  F3  undefined-symbol open  1 finding(s) ... has no exported member 'encode'
30 repair F3  undefined-symbol       bounded repair attempt 1 on F3 (1 file)
31 result F3  pass                   local recheck: tests 6/6, detectors 0 findings
32 result F3  fail                   parent recheck (F4): 3 passed, 3 failed
33 edge       N0030 -> N0022         repair of F3 is in the blast radius of F4
34 error  F4  todo-stub open         ... ← the parent-failure-triggered recursion
```

## The V1 bug-class taxonomy (the deterministic half of the oracle)

`syntax`, `unresolved-import`, `undefined-symbol`, `type-mismatch` (tsc-backed) · `unwired-export` (wiring contract: declared exports must exist — the "button wired to nothing" class) · `test-orphan` (frozen test imports a symbol the implementation doesn't export) · `todo-stub` (committed placeholders) · `env-var-unset` · `test-failure` (idiosyncratic: behavior diverges from the frozen IR).

The frozen suite is the second half. Intent capture remains human — that is what the two approval gates are.

## Architecture

```
web/                    React UI: 3-step approval flow (SSE + poll)
src/server/             Express API: jobs, approvals, events, ledger download
src/core/
  types.ts              domain model (features, ledger, findings, jobs)
  prompts.ts            phase doctrine (input isolation, boundary rules)
  llm.ts                Claude client (claude-opus-4-8, adaptive thinking,
                        xhigh effort, structured outputs, streaming)
  pipeline.ts           Phases A-C + tree utils + boundary enforcement
  rha.ts                Phase D: the healing engine
  taxonomy.ts           deterministic bug-class detectors
  substrate.ts          supergit: ledger + git + trailers + graph
  sandbox.ts            workspace scaffold + vitest/tsc runners
src/mock/mockLlm.ts     deterministic fixtures (3 injected bugs) for offline runs
tests/                  21 tests incl. the end-to-end healing proof
workspaces/<job>/       the generated artifacts (each its own git repo)
```

## Running it

```bash
npm install
npm run build:web

# offline demo (no API key; deterministic fixture with 3 injected bugs)
MOCK_LLM=1 npm run dev

# live (uses ANTHROPIC_API_KEY or an `ant auth login` profile)
npm run dev
```

Open http://localhost:4100. Tests: `npm test` (includes the full mock pipeline: build authenticates 8 failures across 3 bug classes, RHA heals all of them, IR verified untouched, clean nodes verified byte-identical).

## V1 scope

- Generated artifacts are dependency-free TypeScript libraries/service layers (Node stdlib, ESM, vitest). No design, no creative — V1 does not solve for those.
- One repair model: bounded single-node repair with parent recheck and escalation after a fixed attempt budget. Escalations stop and surface; they never fall back to regeneration.
- Runners are synchronous child processes (vitest/tsc); the UI compensates with SSE + polling.

## Known V2 directions

- Async runners; mutation-testing adequacy gate on the IR (the validation report's "IR thinness" exposure); richer artifact classes (HTTP APIs with runtime deps); ledger-driven repair context windows; multi-candidate repair with diversity measurement (the Knight–Leveson caution).

## License

**Source-available under the [PolyForm Shield License 1.0.0](LICENSE)** — SPDX: `LicenseRef-PolyForm-Shield-1.0.0`.

You may use, modify, self-host, and build on RHA Wrapper for almost any purpose, free of charge — **including commercially, and including shipping and selling your own product built with it.** The one restriction: you may not use it to provide a product or service that **competes with RHA Wrapper itself.**

For competing use — or if you want a warranty, indemnity, support, or a written exception — a separate **commercial license** is available. See [COMMERCIAL-LICENSE.md](COMMERCIAL-LICENSE.md) or email `info@rha.software`.

> Note: this is a *source-available* license, not an OSI-approved open-source license. Please describe it as "source-available," not "open source."

Contributions are dual-licensed to keep the commercial option viable — see [CONTRIBUTING.md](CONTRIBUTING.md).

Note: the bundled **Trajan Pro 3** font is a commercial Adobe font under its own license (not covered by the PolyForm Shield License) — swap it for a redistributable face (e.g. Cinzel, OFL) before publicly hosting or forking. See [LICENSE](LICENSE) for details.
