hird 0.3.0

Cross-harness agent work queue and shared assertion memory, backed by one local SQLite database
Documentation
# The factory — Step 0 plan

Status: **built.** All five features shipped as planned, in the commits
listed in §7, and DESIGN.md §33 is now the specification. This file is kept
as the plan of record. Its "as built" notes record where the build refined
the plan. Section 1 describes hird *before* the factory: the schema has
since gone from 12 migrations to 15.

The split is already decided: **core `hird`** gets generic building blocks, a
new **`hird-factory`** crate holds the role-gated policy, and **`hird-server`**
is the only way into the factory.

---

## 1. What hird is today

### Data model (12 migrations, `src/db.rs`)

| Table | What it holds |
|---|---|
| `tasks` | `id` (ulid), `seq`, `project`, `title`, `body`, `status` (CHECK: `open, claimed, in_progress, done, failed, cancelled`), `priority`, `claimed_by`, `lease_expires_at`, `result`, `review` flag (m6), timestamps |
| `task_events` | Append-only by convention (nothing in `src/` updates or deletes rows): `actor`, `kind` (24 `EventKind`s), `detail`, `at` |
| `task_deps` (m2) | `task_id → depends_on_id`, acyclic by construction |
| `task_paths` (m2) | Declared file scopes (glob patterns) |
| `task_witness` / `task_changes` (m3), `witness_blobs` (m8) | The working tree the queue observed |
| `task_plan_nodes` (m4) | Plan-file identity |
| `assertion_footing` etc. (m5) | Memory provenance |
| `task_recusals` (m6) | "Whoever worked `from_task_id` may not work `task_id`" |
| `task_verdicts` (m7) | `upheld` / `sent_back`, `worker`, `reviewer`, append-only |
| `task_tenures`, `tenure_changes` (m9) | One row per holding: holder, how it ended, baseline |
| `task_questions` (m10) | At most one open question per task; `hird answer` closes it |
| `task_requirements` (m11) | Capability labels a claimant must carry |
| `project_recess` (m12) | Project stood down by the human |

The schema version is `meta.schema_version`. A database from a newer binary is
refused when it is opened.

### Identity

The actor is `[principal/]harness:session`. Locally the harness comes from
`HIRD_HARNESS`, or else from the MCP client's own name, and the principal from
`HIRD_IDENTITY`. **There is no model anywhere.** On `hird-server`, the roster
(`server/src/roster.rs`) maps a bearer token to an identity, a project,
capabilities, and an **optional** pinned harness. If the harness is not pinned,
the client names it itself.

### MCP tools (exactly twelve; `src/mcp.rs`, test-enforced)

`task_list, task_get, task_claim, task_next, task_scope, task_update,
task_split, task_complete (verdict?), task_fail, task_release (question?),
mem_store, mem_search`. `hird-server` serves the same twelve over HTTP, with
one `StreamableHttpService` per roster entry.

### Claim → complete

- **Claim** (`claim_in_tx`, `src/repo/tasks.rs:1127`) runs in one `IMMEDIATE`
  transaction. The checks run in order: recess → unanswered question →
  unmet dependencies (`Clearance` from the `under_review` config) → recusal
  (`bars_in`) → capabilities. Then the compare-and-set
  `UPDATE … WHERE status='open'`, a `claimed` event, the scope declaration and
  its overlap check. It returns dependency "ground" and the question history.
  `claim_next` applies the same gates as filters, then claims.
- **Lease:** the TTL is `lease_ttl_minutes` (15). `task_update` renews it.
  `sweep_leases` runs lazily before reads and writes and returns expired work
  to `open` with a `lease_expired` event.
- **Finish** (`finish`, `tasks.rs:844`) checks that the caller is the holder,
  applies the status transition, writes the event, and then, in the same
  transaction:
  `verdict::deliver_in_tx` (a review *must* carry a verdict; `sent_back`
  reopens the judged task with the findings appended to its body) and
  `recusal::file_review` (if `review = 1`, it files a review task recused from
  the work).
- **Human moves** (`cancel`, `reopen`, `answer`) exist only in the CLI and TUI.
  No MCP tool reaches them.

---

## 2. The feature list against the code

| # | Feature | Verdict | Where |
|---|---|---|---|
| 1 | States ready→…→merged, rejected, escalated | **Partial.** Six statuses plus derived facts cover everything except `merged`. | `model.rs` `Status::apply`; `verdict.rs`; `questions.rs` |
| 1 | Role-restricted transitions | **Missing.** There are no roles. Human moves are "humans only" because the twelve tools don't expose them, not because anything checks. | — |
| 1 | Builder can never review | **Partial, with a gap.** `bars_in` bars the harness of `worker_of`, which is the *latest* claim/complete/fail actor only. If harness A builds, its lease lapses and harness B finishes, A may review. | `recusal.rs:185` |
| 1 | Record the reviewer's harness/model | **Partial.** `task_verdicts.reviewer` is the actor, so the harness is recorded. The model is not. | `verdict.rs:287` |
| 1 | "Reviewer harness ≠ builder harness" policy | **Exists, always on**, but only against the last worker and only as strong as the harness name. On the server an unpinned harness is client-chosen, so it can be spoofed. | `recusal.rs`, roster |
| 2 | TTL + heartbeat, expiry → ready | **Exists.** Review tasks are ordinary tasks, so reviewers hold leases too. | `tasks.rs:433` |
| 3 | Gate output stored on rejection | **Partial.** `sent_back` appends prose to `body`. There is no structured record, and CI cannot reject anything. | `verdict.rs:321` |
| 3 | Next claimant gets the history | **Partial.** The findings are in the body. Verdicts are reachable through `task_get`, not handed over with the claim. | — |
| 3 | Escalate after N attempts | **Missing.** There is no counter. Sent-back loops run "until a review upholds". | — |
| 4 | Claimable only after dependencies finish | **Exists**, on `done`. `under_review = "holds"` waits for a verdict. Nothing knows `merged`. | `deps.rs`, `config.rs:51` |
| 4 | Reject cycles | **Exists**, and names the chain. | `deps.rs:59`, `dependency_path` |
| 5 | Branch / worktree / PR | **Missing.** | — |
| 5 | Audit log of transitions | **Partial.** `task_events` has who, when and a free-text detail. No model, role, from/to state or structured evidence. Append-only only by convention. | `tasks.rs:1245` |
| — | Race safety | **Exists.** `IMMEDIATE` plus compare-and-set; `exactly_one_of_many_racing_claimants_wins` and `concurrent_sweeps_expire_each_lease_exactly_once` already test it. | `tasks.rs:1717,1766` |

---

## 3. The factory state machine

### 3.1 Stages are derived, not stored

Core keeps its six statuses. `hird-factory` computes a **stage** for each work
task from core state plus two new stored facts: **attempts** (§F3) and
**merges** (§F1). Review tasks have no stage of their own; they are the means
by which work moves through `in_review`.

| Stage | Derived from |
|---|---|
| `ready` | `open`, no unanswered question (blocked tasks show `ready` with their blockers, as core already does) |
| `claimed` | `claimed` or `in_progress` |
| `built` | `done`, not merged, latest verdict not `upheld`, and no review of it currently held |
| `in_review` | `done`, and an unfinished review of it is `claimed`/`in_progress` |
| `approved` | `done`, latest verdict `upheld`, not merged |
| `merged` | `done` with a `task_merges` row ← **new fact** |
| `rejected` | **Not a resting state.** It is a recorded transition: an attempt row plus a reopen. Afterwards the task's stage is `ready` (with `attempts > 0`) or `escalated`. |
| `escalated` | `failed`, **or** `open` with an unanswered question. Escalation after N attempts *asks* a question (§F3), so the existing gate holds it until a human answers. |
| (`cancelled`) | `cancelled`: outside the factory flow |

Where the mapping fails, and what I'd do:
- **`done` without a review.** `file_review` declines when the witness saw
  nothing and no scope was declared. On `hird-server` there is normally *no
  witness* (the working tree is on another machine), so work could finish and
  never be reviewed. **Fix:** in factory mode every work task is created with
  `review = 1`, and the gate tells `file_review` to file even without
  observed or declared files. The review body then points at the branch and
  PR links (§F5).
- **`rejected` as a state.** The verdict loop already reopens in the same
  transaction, so a resting `rejected` would add a status for nothing. I keep
  it as a transition and an audit row.

### 3.2 Roles

Roles are a **set per roster entry** (`roles = ["builder", "reviewer"]`), read
only from the roster and never from the client. A token with no `roles` key
behaves exactly as today, so existing rosters keep working. Every factory
worker with `builder` or `reviewer` **must pin `harness`**, or the
different-harness policy could be spoofed. The roster refuses to load
otherwise.

### 3.3 Transitions

"Holder" means the current lease holder. Every row runs in one `IMMEDIATE`
transaction with a compare-and-set on the precondition.

| # | From | Action (tool) | To | Roles | Preconditions |
|---|---|---|---|---|---|
| T1 | ready | `task_claim` / `task_next` on work | claimed | builder | core gates; every dependency **merged** (§F4) |
| T2 | claimed | `task_update` | claimed (renewed) | holder | — |
| T3 | claimed | lease expiry | ready | system | **not** an attempt |
| T4 | claimed | `task_release` | ready | holder | — |
| T5 | claimed | `task_release` + `question` | escalated | holder | — |
| T6 | claimed | `task_complete` | built | holder (builder) | files a review (forced in factory mode) |
| T7 | claimed | `task_fail` | escalated | holder (builder) | records an attempt (outcome `failed`) |
| T8 | built | claim the review task | in_review | reviewer | **never held the work in any tenure**; with `reviewer_harness_differs`, harness ∉ harnesses of every past holder; not ci-failed (if `require_ci_before_review`) |
| T9 | in_review | review lease expiry / release | built | system / holder | — |
| T10 | in_review | `task_complete(review, upheld)` | approved | reviewer (holder of the review) | — |
| T11 | in_review | `task_complete(review, sent_back)` | rejected → ready | reviewer (holder of the review) | attempt recorded with the findings; if attempts ≥ `max_attempts` → escalated |
| T12 | built / in_review / approved | `factory_gate(fail)` | rejected → ready | ci | attempt recorded with the gate output; same escalation rule. An in-flight review is cancelled. |
| T13 | built / in_review / approved | `factory_gate(pass)` | unchanged | ci | recorded as evidence |
| T14 | approved | `factory_merge` | merged | ci, human | evidence required (commit SHA or PR URL); latest CI result is a pass if `require_ci_to_merge` |
| T15 | escalated | `hird answer` / `factory_decide(answer)` | ready | human | — |
| T16 | escalated (failed) | `hird reopen` / `factory_decide(reopen)` | ready | human | — |
| T17 | approved / built / in_review | `factory_decide(approve or reject)` | approved / rejected → ready | human | human override, recorded as such |
| T18 | any non-terminal | `hird cancel` / `factory_decide(cancel)` | cancelled | human | — |
| T19 | merged | `factory_decide(reopen)` | ready | human | the only way out of merged |

Each of these is **forbidden** and gets a named test:
- `builder_cannot_approve_own_task`: same actor, as reviewer (T8/T10).
- `builder_on_another_session_of_same_harness_cannot_review`.
- `earlier_holder_whose_lease_lapsed_cannot_review`: the gap found in §2.
- `reviewer_on_builders_harness_is_refused_when_policy_on`.
- A builder token claiming a review task, and a reviewer-only token claiming
  work.
- ci or human tokens claiming anything; a builder or reviewer calling
  `factory_merge`, `factory_gate` or `factory_decide`.
- `merge_before_approval_is_refused`; merging an escalated or ready task.
- `factory_gate` on a ready or claimed task.
- Any transition out of `merged` except T19.
- Two racing reviewers, two racing merges, a gate failure racing an approval:
  exactly one wins.

### 3.4 How the gate reaches the twelve core tools

Role checks must apply to `task_claim` and `task_complete` themselves, or a
builder token could claim a review through a core tool. Core therefore gains a
**`Gate` trait** (no roles, no HTTP):

```rust
pub trait Gate: Send + Sync {
    fn may_claim(&self, tx: &Transaction, task: &Task, actor: &str) -> Result<()>;
    fn may_finish(&self, tx: &Transaction, task: &Task, actor: &str, how: Finish) -> Result<()>;
    fn requires_review(&self) -> bool;          // forces file_review
    fn after_verdict(&self, tx: &Transaction, ...) -> Result<()>; // attempts/escalation
}
```

`Session` carries `Option<Arc<dyn Gate>>`. It is `None` locally, so behaviour
is unchanged. `hird-server` builds one per roster entry, with the role baked
in. `claim_in_tx` calls it after the recusal check, `claim_next` uses it as a
filter (as it does recusal), and `finish` calls it before the status update.
All of these run inside the existing transaction.

---

## 4. Invariants this plan touches

| Invariant (DESIGN / ROADMAP) | How the plan stays inside it | Needs approval? |
|---|---|---|
| **Twelve MCP tools** | Local `hird mcp` stays at twelve. The tool-count test stays. `hird-server` serves twelve **plus four factory tools**. | **Yes.** ROADMAP says a 13th tool needs a better design first. The factory tools have no core equivalent (ci and human acting remotely). |
| **Six statuses** | Kept. Stages are derived (§3.1). The `CHECK` constraint is unchanged. | No |
| **No accounts** | Roles live in the operator's roster file, as identities already do. No user table. | No |
| **No HTTP in `hird`** | `hird-factory` has no HTTP dependency either. The server wraps it. The CI `cargo tree` check gains `-p hird-factory`. | No |
| **Not a scheduler or router** | Roles and the self-review bar are constraints, like recusal. Escalation *stops* work and never retries or schedules it. Nothing assigns work. | No |
| **Terminal statuses leave only by human reopen** (bent once by §16) | T12 lets **ci** reopen `done` work. It bends the same way `sent_back` did: the trust comes from a role the operator granted. | **Yes** |
| **Recusal bars the harness of the last worker** | Tightened in core for everyone: bar every harness that held the work in any tenure. Strictly safer. A single-harness queue already has its reviews unclaimable, so nothing new locks up. | **Yes** (behaviour change in core) |
| **Existing tool signatures** | No change, except the optional `branch`/`worktree`/`pr_url` on `task_update` (§F5), which follows the `verdict?` and `question?` precedent. | **Yes** (flagged signature change) |
| **Events are append-only** | Made real: `BEFORE UPDATE/DELETE` triggers that `RAISE(ABORT)` on `task_events`. Nothing in `src/` mutates events today, so nothing breaks. | No |
| **Plans are data** | Roles, attempts and merges stay out of plan files. | No |
| **Escalation default** | Core `max_attempts = 0` (off) so local users see no change. The factory policy defaults to `3`. | **Yes** (you said N defaults to 3; this applies it to the factory only) |

---

## 5. New MCP tools (`hird-server` only, when the roster has any `roles`)

They are exposed by a wrapper `ServerHandler` in the server crate, which lists
`HirdMcp`'s twelve tools plus these and routes calls by name. Feature 1 starts
with a spike to confirm that rmcp `3.0.0-beta.4` allows this cleanly. If it
doesn't, I'll stop and report.

| Tool | Roles | Input | Result |
|---|---|---|---|
| `factory_gate` | ci | `seq`, `outcome` (`pass`/`fail`), `output` (text, required on fail), `evidence?` (URL/SHA) | stage before/after, attempt number, escalated? |
| `factory_merge` | ci, human | `seq`, `evidence` (commit SHA or PR URL) | stage `merged`, dependents released |
| `factory_decide` | human | `seq`, `action` (`answer`/`reopen`/`approve`/`reject`/`cancel`), `text` | stage before/after |
| `factory_board` | any | `stage?` | each work task's stage, attempts, links, builder(s), reviewer, model |

Existing tool results gain **additive** fields only: `attempts` on claim
results, `stage` and `links` on `task_get`/`task_list` when served by a
factory. **No existing parameter changes**, except the flagged optional
parameters in §F5.

---

## 6. Feature plans

### F1: Gated state machine
- **Core:** migration 13 adds `task_events` columns `model`, `role`,
  `from_state`, `to_state` and `evidence` (JSON), all `DEFAULT ''`, plus the
  append-only triggers, plus `task_merges(task_id, actor, model, evidence, at)`.
  `AgentId` gains an optional `model` (`HIRD_MODEL` locally, roster `model` on
  the server), stored in the new column and **not** in the actor string, so no
  existing parser breaks. The `Gate` trait goes in. `bars_in` checks every
  past holder.
- **`hird-factory` (`factory/`):** `Role`, `Policy` (`reviewer_harness_differs`
  = true, `max_attempts` = 3, `require_ci_to_merge` = true,
  `require_ci_before_review` = false), `stage()` derivation, the `Gate`
  implementation, and the transition table as data, which is what drives the
  exhaustive tests.
- **Server:** roster `roles`/`model`, the pinned-harness rule, the wrapper
  handler, and the factory tools. Policy comes from a `[factory]` table in the
  roster file (the server's own operator file; see `examples/factory-roster.toml`).

### F2: Leases
No new mechanism. Tests only: a review task's lease expires and returns its
work to `built`; lease expiry records no attempt; a builder racing the sweep
loses exactly once. These use the existing `expire_lease` test helper, which
backdates `lease_expires_at`. **Correction to my earlier prompt:** the public
repo API reads the clock itself, and only the `_in_tx` internals take `now`.
Backdating the row is how the current tests already avoid sleeping.

### F3: Attempts and failure context
- **Core:** migration 14 adds
  `task_attempts(id, task_id, n, holder, model, outcome('sent_back','ci_failed','failed','human_rejected'), source_id, output, at)`.
  It is append-only, with the same triggers. `sent_back` writes a row
  alongside its existing body append. `Claim` gains `attempts: Vec<Attempt>`,
  serialized as an additive field on `task_claim`/`task_next`. Config
  `max_attempts` (core default 0): on reaching it, `questions::ask_in_tx` asks
  "N attempts rejected — decide how to proceed", so the task holds for a human.
- **Factory:** `factory_gate(fail)` and `factory_decide(reject)` write
  attempts. The policy sets `max_attempts = 3`.

### F4: Dependencies
- **Factory:** `may_claim` refuses a work task while any dependency is not
  merged, and names the unmerged ones. It is a factory predicate; core
  `Clearance` is untouched. `factory_merge` runs the herald for newly
  claimable dependents.
- Cycle rejection already exists. I'll add a factory-level test that it holds
  for tasks created through the server.
- *As built:* core's `Gate` gains `holds(conn, task)` — a hold on the task
  whoever asks — which the herald consults before announcing, so a
  dependent is announced by the merge that clears its last dependency and
  never by the completion or approval before it. "Merged" means a merge
  recorded after the work's latest completion, in audit order: merged work
  that is reopened and rebuilt waits to be merged again, and so do its
  dependents. `factory_board` rows carry `waiting_on`.

### F5: Traceability
- **Core:** migration 15 adds `task_links(task_id PK, branch, worktree, pr_url, updated_by, at)`.
  It is current state; every change *also* lands as an event, so the history
  stays in the append-only trail. CLI: `hird link <seq> [--branch] [--worktree] [--pr]`,
  plus links shown in `hird show`. MCP: optional `branch?`, `worktree?`,
  `pr_url?` on `task_update` (holder-only; **flagged**). The fallback if you
  decline is a factory-only `factory_link` tool, which local agents would not
  have.
- *As built:* `hird link` works whoever holds the task (the human's path);
  `task_update` is the holder's. An empty value clears a link; a change that
  moves nothing writes nothing. Links show in `hird show` and as `links` in
  `task_get`; `task_update` echoes them only when it set some, so a plain
  heartbeat's reply is unchanged. `examples/links.sh` runs under
  `just examples`.
- **Audit:** every factory transition writes one event with `role`, `model`,
  `from_state`, `to_state` and `evidence`. Core transitions fill
  `from_state`/`to_state` with statuses.

### Migrations and tests
- A **fixture** is committed *first*: `tests/fixtures/schema-v12.db`, a
  database built by the current binary (tasks in every status, dependencies,
  a recusal and verdicts, a question, tenures, memory). The test loads it,
  opens it with the new code, and asserts: `schema_version` is current, every
  row survives, `task_list`/`task_get` read it, and new columns hold their
  defaults.
- **Concurrency:** N threads × {claim, review claim, merge, gate-fail vs
  upheld} on one task, with exactly one winner. Lease-expiry races use the
  existing sweep test pattern.

### Just recipes
`just test-factory` (`cargo test -p hird-factory`), `just serve` (runs
`hird-server` against `examples/roster.toml`), `just factory-demo` (seeds a
temporary database and walks a task from ready to merged through the server).
`just check` and CI include the new crate.

---

## 7. Commit plan

Every commit passes `just check`. Commits are grouped by feature and never mix
features.

0. `Factory: the Step 0 plan`: this file.
1. `F1: freeze a v12 database and test upgrades from it`: the fixture and the migration test (passes at v12).
2. `F1: events record model, role, state change and evidence; make them append-only` (migration 13, `AgentId.model`).
3. `F1: recusal bars every hand that held the work`: the tenure gap fix and its tests.
4. `F1: a gate the server can put in front of claims and finishes`: the `Gate` trait, no-op locally, tested with a fake gate.
5. `F1: hird-factory — roles, stages, the transition table`: the crate, plus exhaustive allowed/forbidden tests.
6. `F1: hird-server serves the factory — roster roles, merge, gate, decide`: wrapper handler, tools, role tests, race tests.
7. `F2: review leases lapse back to built, and expiry costs no attempt`: tests, plus any fixes they expose.
8. `F3: attempts — gate output on the record, handed to the next claimant, escalation after N`.
9. `F4: in the factory, a dependency clears only once merged`.
10. `F5: branch, worktree and PR links on a task`.
11. `Factory: DESIGN §33, README, ROADMAP, examples`.

**Approval checkpoints:** after this document, and after commit 6.

---

## 8. Decisions I need from you

1. **Factory tools on the server only** (four tools on top of the twelve). Approve?
2. **`task_update` gains optional `branch`/`worktree`/`pr_url`** (a flagged signature change), or use a factory-only `factory_link`?
3. **Tighten recusal in core for everyone** (bar every past holder's harness), not only in factory mode?
4. **CI may reopen `done` work** (bending the "only a human reopens" invariant, as §16 did for reviews)?
5. **`max_attempts`:** core default 0 (off), factory default 3. OK?
6. **CI placement:** CI may report at any stage, and a pass is required to merge, but **not** before review (`require_ci_before_review = false`). Or should CI gate review too?
7. **`rejected` as a transition, not a resting state.** OK?
8. **Builder and reviewer tokens must pin their harness in the roster.** OK?