# Self-Healing Loop

CoreReflex self-healing turns customer bug reports into human-reviewed repair briefs. It is intentionally human-in-the-loop: the agent may open a PR, but it must never merge.

## Data Flow

1. A support ticket with `category = bug` is created.
2. `src/self-heal.js` creates or reuses one `self_heal_briefs` row for that ticket.
3. The God Console reads active briefs from `GET /api/admin/self-heal/queue`.
4. Local operators materialize queued briefs with `scripts/self-heal-sync.mjs`.
5. `/schedule` works the markdown files in `self-healing/inbox/`, opens a PR, and stops.
6. The PR/status is reported back with `scripts/self-heal-report.mjs` or `POST /api/admin/self-heal/:id/status`.

## Table

`self_heal_briefs` stores:

- `ticket_id` and optional `conversation_id`
- `title`, `severity`, and `status`
- `brief_markdown`
- `suspected_areas`
- optional `pr_url`

Statuses are `queued`, `in_progress`, `pr_open`, `done`, and `dismissed`.

## Commands

```bash
node scripts/self-heal-sync.mjs
node scripts/self-heal-sync.mjs --dry --limit 5
node scripts/self-heal-report.mjs --id <brief-id> --status pr_open --pr-url https://github.com/Girard-Media/corereflex/pull/<n>
```

Use `DATABASE_MIGRATION_URL` or `DATABASE_URL`, same as the migration and chat-ingest scripts.

## Admin Endpoints

- `GET /api/admin/self-heal/queue`
- `POST /api/admin/self-heal/:id/status`

Both are God Mode gated. `pr_url` accepts GitHub pull request URLs; invalid URLs are stored as `null`.

## Safety Rules

- The `/schedule` worker opens a branch and PR only.
- It must run `npm run lint` and `npm test` before reporting `pr_open`.
- It must never merge a PR.
- Humans move a brief to `done` only after review.
