diff --git a/.genie/INDEX.md b/.genie/INDEX.md index d0f96cbe6..392afda9b 100644 --- a/.genie/INDEX.md +++ b/.genie/INDEX.md @@ -17,8 +17,6 @@ - [genie-boards-ui](brainstorms/genie-boards-ui/DRAFT.md) — WRS 70; genie desktop boards module: ABSORB of the G4 kanban decided by Felipe; tab + split-toggle layout tentatively locked ("that looks good", confirm at crystallize); archive section + per-project .genie-commit checkboxes added to scope; roadmap shape (per-project board + groom-with-agent task) recommended, awaiting Felipe; depends on ui-bridge board-payload extension (protocol 1.1) + genie-ui-dash G5 (2026-07-21) - [intent-to-wish-compiler](brainstorms/intent-to-wish-compiler/DRAFT.md) — **LIVE (re-verified 2026-07-21):** WRS 92; Demand→Patch/Standard/Program router + circuit-breaker (flex cuts autonomous, payout cuts human-only); invisible routing compiled from intent — program-scale, splits at pour time - [brainstorm-domain-map](brainstorms/brainstorm-domain-map/DRAFT.md) — **LIVE (re-verified 2026-07-21):** WRS 80; executable spec compiler (intent → requirement-ID → oracle-class → execution → proof-packet); deterministic gates, residual-risk review only; subjective-truth ownership still open (umbrella G8) -- [cross-agent-delegate](brainstorms/cross-agent-delegate/DRAFT.md) — **re-scoped 2026-07-21:** Codex skill-distribution prerequisite solved by agent-sync (#2541); remaining live: delegate skill (Codex+Hermes), wish companion sessions, refine style cards, auto plan-gate counter-read (umbrella G6) - ## Ready @@ -35,6 +33,8 @@ ## Poured +- [cross-agent-delegate — DESIGN](brainstorms/cross-agent-delegate/DESIGN.md) → [WISH](wishes/cross-agent-delegate/WISH.md) — **APPROVED 2026-08-11** (design SHIP digest `c15d6a9e…` after 2 fix loops; plan SHIP with all 7 findings applied in-document, incl. the A1/A2 gate split; re-opened orca-inspired 2026-08-10, umbrella G6): W1 declared-routing wish — `assigned_agent`+`assigned_reason` on the card (default = current agent), roster allowlist (claude/codex/pi/hermes/prime), `create --agent/--why` + `task assign --clear`, lane-path-only `board --json` (laneless stays byte-frozen), roadmap-sync lockstep; 4 groups A1 → A2 ∥ B ∥ C, 5 board cards. Follow-on `delegate-bridge` (W2 turn-per-launch remotty bridge + W3 fan-out) pours after the 5 logged residuals are applied to the design and the remotty `headless-turn-open` wish exists; unblocks remotty's `assigned_agent` rendering ask + - [WISH: genie-official-roadmap](wishes/genie-official-roadmap/WISH.md) — **APPROVED 2026-07-28** ([DESIGN](brainstorms/genie-official-roadmap/DESIGN.md) SHIP after 1 fix loop, digest `36097b0d…`; plan SHIP after 2 fix loops, all findings execution-verified by the reviewer): triage of all 36 wishes (3-scout evidence audit) into the official roadmap — archive 29 DONE-verified wishes with full link-rewrite inventory, cold-seed the `roadmap` board with 19 lifecycle cards (Work order: dogfood-remediation → v4-residue → release-ops → proportional-validation, Felipe-ratified), rewrite INDEX with a Shipped section, draft `public-roadmap-polish`. 3 groups: archive+links ∥ board-seed → INDEX rewrite; single commit in G3. - khal-native-theme — **APPROVED 2026-07-23, RELOCATED same day** to `khal-os/genie-desktop:.genie/` (branch `wish/khal-native-theme`, commit `484c243`; Felipe: desktop context lives in the desktop repo — the fork's own genie.db carries the 6 seeded group tasks and its WISH adds the live-visual-checkpoint protocol CP-1..6). Design SHIP digest `bdd54325…`, plan SHIP after 1 fix loop, 3-lens ledger verify 0 must-fix. This repo's 7 stale task rows are hard-blocked with a relocation reason. First of Theme→Identity→SSH diff --git a/.genie/brainstorms/cross-agent-delegate/DESIGN.md b/.genie/brainstorms/cross-agent-delegate/DESIGN.md new file mode 100644 index 000000000..963c3216c --- /dev/null +++ b/.genie/brainstorms/cross-agent-delegate/DESIGN.md @@ -0,0 +1,122 @@ +# Design: Cross-Agent Delegation — teammates on the board + +| Field | Value | +|-------|-------| +| **Slug** | `cross-agent-delegate` | +| **Date** | 2026-08-10 (fix loops 1–2 applied 2026-08-10/11) | +| **WRS** | 100/100 | + +## Problem + +Genie lifecycle stages run in whichever coding agent Felipe happens to be sitting in; there is no way to declare *which* agent (Claude Code, Codex, pi, Hermes, prime) works a given card at a given stage and why, and no durable back-and-forth channel between agents working as teammates. This wastes the roster (cost arbitrage, dissent diversity — established 2026-07-09) and keeps delegation manual and invisible. + +## Scope + +### IN + +**W1 — declared routing (mechanical, ships first, gated by nothing below; pours as its own wish immediately):** +- Additive `tasks.assigned_agent` + `assigned_reason` columns; `genie task create --agent --why `; a `task assign` verb for existing cards. `assigned_agent` is validated against the known roster names (allowlist) at create/assign time. +- Serialization on the **lane-path** `genie board --json` only, following the `enforcedBlock` precedent; the laneless `--json` shape stays byte-frozen per the prior boards-first-class WISH decision. Stated consumer consequence: a client reading a non-lane-defining board or the frozen laneless shape does not see these fields — that is by design, not a bug. +- Roadmap-sync lockstep for the two new columns: `EXPECTED_SCHEMA.tasks` + `schemaIsCurrent`, the hand-enumerated `insertSnapshotRows` insert, and three-way `task sync` baseline coverage — routing must survive export/import/sync or Decision 1's rationale is void. + +**W2 — the delegate bridge (follow-on wish, opened by a bounded spike; blocked on the named remotty dependency below):** +- Spike first: one bounded session that proves the seam end-to-end (headless turn → brief pickup → hand-back → second turn) with a live transcript, before any bridge code lands. +- **Turn-per-launch model.** Remotty has no verb that sends input to a running session, so a "conversation" is a sequence of launches: every turn — the opening brief and every follow-up — invokes the same headless verb on the same named worktree with a per-turn argv (the follow-up turns use the agent's id-free continue form so the agent resumes its own conversation state). Adapter launch forms MUST exit when the turn is done; an adapter that launches a bare interactive binary produces a session that never ends, never hands back, and never heartbeats, and is therefore non-conforming. +- Bridge flow, per routed card: validate `assigned_agent` against the roster → `genie task checkout --worker ` (the bridge claims on the delegate's behalf) → `remotty worktree prepare ` with candidate name `-` (in-contract today; prints `ok ` / `skip `) → write the turn brief **outside the worktree** under `$GENIE_HOME` (e.g. `$GENIE_HOME/briefs/-/turn-.md`: card id, acceptance criteria, expected verbs — `task comment`/`report`/`heartbeat`; never shell-interpolated argv) → invoke the headless verb with the adapter's argv (brief path filled into its `{brief}` placeholder) → persist the returned `{session, worktreePath, branch}` as a card timeline event, using the *returned* session name (it may be uniquified) as the durable handle for follow-up turns. +- Teammate channel: hand-backs land as `task comment`/`report` timeline events (worktrees share the main repo's `genie.db`, so the delegate writes its own state); the card timeline is the durable thread; the live terminal is visible in the remotty client. Conversation ids are recorded opportunistically but are never load-bearing (non-unique in remotty's own state contract; hermes has none). +- Adapters for all five roster agents — claude, codex, pi, hermes, prime — as **genie-side data with explicit placeholders**: per-agent cards defining the opening-turn argv and the id-free continue-form argv, each with a `{brief}` slot, plus the agent's autonomy/permission flags (e.g. codex `--full-auto` + PTY, claude `-p` with its permission mode set) — without which an agent completes a turn while never being allowed to write. This is deliberately distinct from remotty's `~/.config/remotty/agents` file, whose lines are verbatim and interpolation-free; that file stays remotty's business and genie never edits it. +- Fail-open degradation: any spawn/adapter failure logs a named reason on the card timeline, **releases the claim** (`task release`), and disposes of the prepared worktree — attempt `remotty worktree prune`; if prune refuses (dirty tree), log the orphan's path on the timeline rather than retrying silently. The orchestrator may then work the card directly (extends the 2026-07-09 counter-read policy). + +**W3 — fan-out (last; rides the W2 wish; never gates W1):** +- `genie task fan --agents a,b,c` runs the W2 bridge N times with candidate names `-`; each candidate's resolved worktree path, branch (`wt/`, remotty's prefix rule), and returned session name are recorded as timeline-event content so ranking and pruning are mechanical. Briefs living outside the worktree keep every candidate tree clean, so non-forced prune works on losers. +- The review stage ranks candidate diffs against the group's acceptance criteria with rationale; Felipe ratifies the winner in the orchestrating session (CLI picker); losers are pruned via `remotty worktree prune` (branches survive, per remotty's own rule). + +**Cross-repo dependency (remotty repo, its own named wish — consumed here, not built here):** +- A **headless variant of `worktree open`**: inputs ` `; opens a detached shpool session on the **existing** named worktree (refuses to create a worktree of its own — no `worktree_decide` fallback, no silently degraded isolation); launches the supplied argv; returns machine-readable refs `{session, worktreePath, branch}` — the returned session name is authoritative since `worktree open` uniquifies when taken — with a meaningful exit code. The same verb carries every turn (opening brief and follow-ups alike). +- Rendering `assigned_agent`/`assigned_reason` on cards in the remotty clients. +- Tracked as a named wish in the remotty repo (working slug `headless-turn-open`) with a board card; the genie W2/W3 wish declares `depends-on` it, so the external stall is visible on the board instead of discovered at execution. + +### OUT +- Cross-server delegation — a delegated/fanned agent always runs where the task already runs (Felipe, 2026-08-10). Consequence made explicit: the bridge always targets the machine it is running on, remotty host token `local`; registry-name mapping for remote hosts is deferred (see Simplicity Case). +- Remotty GUI work beyond the two cross-repo deliverables above. No diff-compare UI; ratification happens in the orchestrating session. +- Any new message bus, daemon, or agent-inbox table — the timeline + named per-turn sessions are the channel. +- Approval-gated spawns (genie spawns, user watches — D-E); unattended auto-merge of fan-out winners (ratification required — D-F). +- Global/stage-level routing config files and WISH.md agent pins — routing is board-card-driven only. +- kimi adapter (present in remotty's roster; not in the requested five). +- External-agent budget/limits and companion-session retirement — deferred behind measurable triggers (first observed host contention; first shipped wish with live sessions). +- Extending the laneless `board --json` shape — it stays byte-frozen. +- Editing remotty's `~/.config/remotty/agents` file from genie. + +## Approach + +**Board-as-contract, thin spawn bridge.** Genie remains the brain (board, routing declaration, lifecycle, review); remotty remains the body (shpool terminal server, worktree isolation, fleet visibility, GUI clients). The interface is two seams: genie invokes remotty plumbing to run turns, and remotty reads `board --json` (read-only, its existing contract) to render assignments. Delegated agents write genie state themselves by running the genie CLI inside their worktree (comment/report/heartbeat — viable because worktrees share the main repo's `genie.db` via `git rev-parse --git-common-dir`); the remotty *client* still never writes. + +The fix-loop reviews established the exact seam shape. In-contract today: `worktree prepare` (caller-supplied name, machine-readable `ok ` output) and `worktree open` (caller-supplied name on an existing tree) — so candidate naming needs no remotty change. Missing today: every session-opening verb exec's into an interactive attach, nothing returns refs to a caller, and nothing sends input to a running session. Hence one remotty-side deliverable — the headless `worktree open` variant — and the **turn-per-launch** conversation model built on it, instead of smuggling behavior through interactive verbs or pretending live sessions can be driven externally. Everything downstream (refs on the timeline, fan-out naming, loud isolation failure, prunable losers) keys off that verb's contract. W2's spike is the checkpoint that the contract holds live before bridge code lands; the verb lives in a named remotty wish the W2/W3 wish depends on, and W1 pours as its own wish so the external dependency gates nothing mechanical. + +Routing semantics: `assigned_agent` NULL means the current orchestrating agent works the card (Felipe's default); a declared assignment carries its `assigned_reason` ("the why"). Declared assignment stays deliberately distinct from observed identity (`claimed_by`/`agent_kind`/heartbeat, shipped by boards-first-class) — during a delegation the two are linked by the bridge's checkout (`claimed_by = assigned_agent`), and divergence outside a delegation is diagnostic signal, not error. + +Trust posture: brief content (card title, `assigned_reason`, acceptance criteria) becomes instructions a tool-enabled agent follows. That text is Felipe-authored board content, and this design accepts it as trusted; the injection controls (Decision 11) close the *shell* and *argv* boundaries, not the prompt boundary, and say so explicitly. + +Alternatives rejected: **hire_roster-centric routing** (per-wish and machine-local — contradicts per-task declaration that syncs through roadmap.json); **remotty-driven orchestration** (violates remotty's never-write posture and D-E); **new message-bus/inbox table or Omni as the bus** (machinery without a present requirement); **bridge-without-remotty-changes** (post-hoc `state --json` joins under an exec'd attach cannot return refs or surface isolation downgrade — rejected by fix-loop-1 evidence); **driving live sessions** (no remotty verb sends input to a running session — rejected by fix-loop-2 evidence in favor of turn-per-launch). + +## Simplicity Case + +- **Simplest complete design:** two additive nullable columns + two CLI verbs + one bridge code path reused by every turn, by single delegation, and by fan-out + timeline events as the thread + one remotty headless verb. No new tables, no daemon, no protocol beyond one JSON line of refs per turn. +- **Added machinery:** the remotty headless `worktree open` variant (justified: fix-loop evidence — every existing session-opening verb attaches interactively and returns nothing; it is the wish's dominant cost and why W2 opens with a spike); turn-per-launch adapters with `{brief}` placeholders and autonomy flags (justified: no live-session input channel exists, and permissionless launches produce empty smoke passes); the `task fan` verb (justified: Felipe decided fan-out fully IN); roster allowlist validation (justified: assigned text reaches a shell and another agent's prompt). +- **Deferred until measured:** budget/concurrency limits (trigger: first observed host contention); session retirement (trigger: first shipped wish with live sessions); remotty diff-compare UI (trigger: CLI ratification proves painful live); cross-server spawning + host registry-name mapping (trigger: Felipe reverses D-G — until then the same-server invariant makes `local` always correct); driving live sessions instead of turn-per-launch (trigger: a measured need for mid-turn steering that re-launching cannot serve). +- **Complexity removed:** no agent-inbox schema, no Omni coupling, no approval queue on spawns, no global routing config, no WISH.md routing dialect, no winner-auto-merge state machine, no convo-id-keyed session registry (session names are the durable handle), no in-worktree state files (briefs live under `$GENIE_HOME`, keeping candidate trees clean and prunable). + +## Decisions + +| # | Decision | Rationale | +|---|----------|-----------| +| 1 | Routing lives on the board card (`assigned_agent`/`assigned_reason`); default = current agent | Felipe 2026-08-10; board is the one tracker; syncs via roadmap.json unlike machine-local hire_roster — hence the W1 sync-lockstep scope | +| 2 | Remotty is the spawn/terminal substrate; genie consumes its plumbing | Terminal server, worktrees, naming-capable `worktree prepare`/`open`, fleet visibility and GUI exist today; headless turn execution and machine-readable refs do **not** — they are the named cross-repo deliverable, not assumed | +| 3 | Genie spawns, user watches | Felipe 2026-08-10; zero-friction, overnight-capable, sessions appear live in remotty clients | +| 4 | Channel = card timeline (comment/report) + turn-per-launch sessions; no new bus | Both substrates already shipped; a bus adds durable states without a present requirement; no remotty verb can drive a live session, so turns are launches | +| 5 | Fan-out fully IN, review ranks, Felipe ratifies, losers pruned (branches survive) | Felipe 2026-08-10; reuses the bridge; ratification keeps merges human-gated | +| 6 | Same-server delegation only; host token is always `local` | Felipe 2026-08-10 verbatim ("no cross server"); the invariant makes host derivation trivial and removes remote failure modes | +| 7 | Adapter cards are genie-side data: opening + continue argv with a `{brief}` placeholder, plus autonomy/permission flags; adapters must exit per turn | Five runtimes, materially different forms; remotty's own agents file is verbatim/interpolation-free so it cannot carry this — it stays remotty's business; exit-per-turn is what makes hand-back and heartbeat possible | +| 8 | Fail-open on spawn/adapter failure: named timeline reason + claim release + worktree disposition (prune, or log the orphan path on refusal) | Extends the proven 2026-07-09 counter-read policy; never block a stage on external availability, never strand a claim, never leak a tree silently | +| 9 | Declared assignment stays distinct from observed claim identity; the bridge links them via `checkout --worker ` | `claimed_by`/`agent_kind` are observed at claim/heartbeat (boards-first-class); the bridge makes ownership during delegation explicit instead of conflating the fields | +| 10 | Lane-path-only `board --json` serialization | The laneless shape is byte-frozen by prior WISH decision; `enforcedBlock` is the precedent for lane-path-only runtime fields | +| 11 | Briefs and follow-ups are files under `$GENIE_HOME`, never argv and never inside the worktree; `assigned_agent` is roster-allowlisted | Card text crosses a shell boundary and another agent's prompt (trust posture stated in Approach); out-of-tree briefs keep candidate worktrees clean so non-forced prune works and the winner's diff carries no noise | +| 12 | Returned session name (+ worktree path + branch) is the durable ref; convo id is opportunistic | Remotty's state contract: convo ids are non-unique, hermes carries none; `worktree open` uniquifies names, so the *returned* name is authoritative and is what prune consumes | +| 13 | Pour as two genie wishes: W1 now; W2+W3 follow-on with `depends-on` the named remotty wish (`headless-turn-open`) | Two of three waves are externally blocked; a single wish would stall at W2 on another repo — the split makes the stall a visible board edge instead of an execution surprise | + +## Risks & Assumptions + +| # | Risk | Severity | Mitigation | +|---|------|----------|------------| +| 1 | Remotty `headless-turn-open` doesn't land, or its contract drifts (separate repo, version skew) | High | Named cross-repo wish + `depends-on` edge on the W2/W3 wish; W2 opens with a live-transcript spike against the real verb; bridge treats the JSON refs + exit code as the contract and fails open with a named reason; W1 ships regardless | +| 2 | pi/prime environments lack genie skills (agent-sync covers claude/codex/hermes today) | Medium | The brief is self-contained (card id, criteria, exact `genie task …` commands) — delegation needs the genie binary on the host, not skills; per-agent smoke criterion | +| 3 | Per-agent forms drift (hermes flag varies by version; prime binary ≠ roster name; autonomy flags change) | Medium | Adapter cards are data, correctable without code; each form verified in the per-agent smoke test whose pass requires a non-empty diff; a wrong continue form fails visibly on the next turn, not silently | +| 4 | Fan-out N× cost and same-host load | Medium | Fan is explicit per-card (never default); budget/limits deferred behind the contention trigger | +| 5 | Delegated agent dies mid-turn, never exits, or never picks up the brief | Medium | Turn-per-launch bounds each turn's lifetime; heartbeat liveness (▶/⏸/☠) already ships; stale claims release; the spike proves brief pickup per agent before the adapter is declared supported | +| 6 | `board --json` growth breaks remotty parsing | Low | Lane-path additive keys only; remotty draws nothing for unknown gaps by its own design | +| 7 | Assumption: remotty CLI + genie binary present on any server where delegation is exercised | — | Bridge preflights both and degrades open with a doctor-style hint; same-server rule means no remote naming to resolve | + +## Success Criteria + +- [ ] **W1 assignment round-trip:** `genie task create --title x --agent codex --why "dissent on parser"` persists both fields; `task assign` sets them on an existing card; a non-roster name is rejected; both fields appear in lane-path `genie board --json` while the laneless shape stays byte-identical; both fields survive `task export` → `task import` → three-way `task sync`. +- [ ] **W2 spike transcript:** one live session proving a headless opening turn (brief pickup from `$GENIE_HOME`) → `task comment` hand-back → a second turn through the same headless verb on the same worktree via the continue form — with the returned `{session, worktreePath, branch}` refs recorded on the card timeline. +- [ ] **W2 delegation round-trip:** a routed card is claimed by the bridge (`claimed_by = assigned_agent`), delegated, handed back, and continued for a second turn — all evidenced on the card timeline. +- [ ] **Adapter smoke ×5:** claude, codex, pi, hermes, prime each complete brief → hand-back once via the bridge with a **non-empty diff** (proving the autonomy flags let the agent act; hermes/prime explicitly exercise the id-free continue form). +- [ ] **W3 fan-out round-trip:** `genie task fan --agents claude,codex,pi` yields three named candidates with refs on the timeline; review emits a ranked verdict with rationale against the group's acceptance criteria; ratification merges the winner; losers pruned non-forced with branches surviving (clean trees — briefs live out-of-tree). +- [ ] **Degradation:** a forced spawn failure logs a named reason on the timeline, releases the claim, disposes of the prepared worktree (or logs the orphan path if prune refuses), leaves the card claimable, and blocks nothing. +- [ ] **Genie-side contract for clients:** `assigned_agent`/`assigned_reason` are readable by any board client from lane-path `board --json` (non-lane and laneless readers see nothing, by design; remotty rendering itself is the cross-repo dependency, tracked in the remotty repo, not gated here). + +The wish must attach a concrete command + expected artifact to every criterion (review LOW-2, loop 1). + +## Next Step + +After an independent design review returns SHIP, persist the evidence below and verify its content digest before running `wish`. + + +## Design Review Evidence + +- **Verdict:** SHIP +- **Reviewed content SHA-256:** `c15d6a9e1de0daf39543ed71e5bfa4c7c3ad866de6a9294c6c833a2a39c00edd` +- **Reviewer:** design-review-cross-agent-delegate +- **Reviewed at:** 2026-08-11T00:14:02.000Z + diff --git a/.genie/brainstorms/cross-agent-delegate/DRAFT.md b/.genie/brainstorms/cross-agent-delegate/DRAFT.md index c2c213ba6..007298742 100644 --- a/.genie/brainstorms/cross-agent-delegate/DRAFT.md +++ b/.genie/brainstorms/cross-agent-delegate/DRAFT.md @@ -2,6 +2,77 @@ **Parent:** [genie-token-efficiency-program](../genie-token-efficiency-program/DESIGN.md) · **Status:** Simmering +## RE-OPENED 2026-08-10 — orca-inspired teammate delegation (Felipe) + +Felipe now runs genie in **five runtimes**: Claude Code, Codex, pi, Hermes, agent-prime. New framing on top of the 2026-07 decisions: + +1. **Stage routing policy** — decide *who does what at which lifecycle stage and why* (brainstorm/wish/work/review/etc.), as an explicit, inspectable policy — not "whatever runtime I happen to be sitting in." +2. **Teammate channel** — a clear back-and-forth channel between agents ("coding agents are teammates"), beyond one-shot JSON hand-back. + +**Orca reference (github.com/stablyai/orca, fetched 2026-08-10):** desktop/mobile ADE, "AI Orchestrator for 100x builders." Key mechanics: (a) harness for ANY CLI-based agent — no custom protocol, wraps terminal execution; (b) parallel git worktrees — fan one prompt across multiple agents, compare diffs, merge the winner; (c) no explicit handoff protocol — orchestration happens through version control + UI review; (d) annotate-diffs feedback loop (comments on generated code flow back into agent prompts); (e) SSH worktrees for remote agents. Genie already has the worktree-per-group substrate (`launch`/warp-launch) and a CLI-adapter posture (nous-skills evidence above) — the orca deltas are the *fan-out-and-compare* pattern and the *feedback-annotation* channel. + +### DECIDED 2026-08-10 (Felipe picker) + +- **D-A Routing policy home = the board card.** Default agent for a task = the current coding agent (whoever is orchestrating); at task creation there is an option to declare which coding agent works it (with the "why"). Board-driven override, not global config, not WISH.md pins. +- **D-B Substrate = remotty, not a new channel.** Remotty already ships the orca-harness half: shpool terminal server, `spawn [--worktree] ` / `resume ` / `revive` plumbing, per-session git worktrees under `/.worktrees/`, fleet state, and two GUI clients that render the genie board (read-only, by contract — see `wishes/remotty-board-asks/HANDOFF-from-remotty.md`). The user *sees* spawning agents in the remotty client, orca-style. Back-and-forth rides resumable sessions + genie card timeline (`task comment`/`report` verbs) as the durable thread. +- **D-C Fan-out fully IN.** Same task fanned to N agents in N worktrees, compare, merge winner. Remotty's worktree-per-session already isolates; the compare/merge policy is the open design work. +- **D-D Roster wave 1 = all five.** claude, codex, pi, hermes, prime — all already in remotty's built-in agent roster (`config/agents.example`; `prime` runs `prime-agent`, kimi also present). Adapter-specific facts: pi has `-p` one-shot + `--mode json|rpc` + `--session-id`; codex `resume --last`; hermes' resume flag varies by version (config-file override is the mechanism); `prime-agent`/`kimi` continue-forms in roster. Agents-as-data: adding an agent = a roster line, not code. + +- **D-E Spawn driver = genie.** The orchestrating agent calls remotty's spawn plumbing when a routed card starts; the user watches the session appear in the remotty client. No approval friction; the board is the authority. +- **D-F Merge policy = review ranks, Felipe ratifies.** The review stage compares fan-out candidate diffs against the group's acceptance criteria and ranks with rationale; Felipe confirms the winner before merge. Loser worktrees pruned via remotty `worktree prune` (branches survive by remotty's own rule). +- **D-G Same-server delegation only.** A delegated/fanned agent always runs on the server the task already runs on (local or remote); cross-server spawning is OUT. + +### SUBSTRATE FACTS (verified in-repo 2026-08-10) + +- `tasks` already has `claimed_by` + `agent_kind` + `heartbeat_at` — but those are **observed** identity (set at claim/heartbeat, boards-first-class runtime liveness ▶/⏸/☠). Declared routing needs its own additive columns; never conflate assignment with observation. +- `hire_roster` (wish, agent_adapter_id, profile, worktree, hired_at, state) exists (genie-ui-dash G5), machine-local, excluded from roadmap.json sync — per-wish hires, not the per-task declaration Felipe asked for; left as-is. +- `task comment` / `report` verbs + `task_events` timeline exist — the durable thread substrate is already shipped. +- warp-launch panes carry arbitrary shell commands — a remotty launch backend is a sibling emitter, not a rework. +- remotty plumbing contract (from `--help`): `spawn [--worktree] ` · `resume ` · `revive` · `worktree prune` (refuses dirty trees, only wt/* branches, branch survives). Built-in roster: claude/codex/prime/pi/kimi/hermes. + +### APPROACH (chosen 2026-08-10) — board-as-contract, thin spawn bridge + +Genie wish: (1) additive `tasks.assigned_agent` + `assigned_reason` columns, `task create --agent/--why` + a `task assign` verb, exposed in `board --json` (remotty handoff ask-pattern: serialize or the client can't render); (2) a delegate bridge — when a routed card starts, genie invokes `remotty spawn --worktree ` with a curated brief, persists the session/convo ref on the card timeline, hand-backs land as `task comment`/`report` events, follow-ups resume the same session; (3) fan-out `task fan --agents a,b,c` reuses the same spawn path N times, candidates tracked as timeline events + `wt/-` worktree convention (no new table), review ranks against group acceptance criteria, Felipe ratifies, winner merges, losers pruned via `remotty worktree prune`. Remotty-side (separate, tiny, its own repo): render `assigned_agent` on cards — noted as a cross-repo dependency, not built here. + +Alternatives rejected: hire_roster-centric routing (per-wish + machine-local, contradicts per-task-in-git declaration); remotty-driven orchestration (violates remotty's never-write contract and D-E). + +Degradation (extends 2026-07-09 policy): spawn/adapter failure **fails open** — logged on the card timeline, card returns to claimable, orchestrator may work it directly; never block a stage on external-agent availability, never silently pretend the delegation happened. + +### CRITERIA (draft) + +1. Assignment round-trip: `--agent codex --why "…"` persists and appears in `board --json`. +2. Delegation round-trip: routed card start → remotty session on the same host in a worktree, ref on timeline; hand-back event lands; a follow-up resumes the same session (2 turns proven). +3. Fan-out round-trip: 3 agents → 3 worktrees/sessions → ranked review verdict → ratified merge → losers pruned, branches survive. +4. All five adapters (claude, codex, pi, hermes, prime) pass a one-shot brief→hand-back smoke. +5. Spawn failure degrades open (timeline log, card claimable, no hang). + +### GAPS 2026-08-10 (supersede the 2026-07 gap list where they overlap) + +- [x] Cross-repo split — decided: remotty-side is render-only, its own repo, cross-repo dependency note in the wish. +- [ ] Prior gaps still open, deferred behind triggers: external-agent budget/limits (trigger: first observed host contention); companion-session retirement policy (trigger: first shipped wish with live sessions). + +**WRS: 100/100 — crystallizing to DESIGN.md (2026-08-10).** + +### FIX LOOP 1 (design review FIX-FIRST, 2026-08-10T23:55:17Z, digest `b98b2629…`) + +Reviewer (design-review-cross-agent-delegate) verified the seam against remotty's actual code and found the documented plumbing cannot serve headless delegation: `spawn` exec's into an interactive attach (no refs returned, no exit code to probe), the `~/.config/remotty/agents` file governs only resume (id never interpolated), and worktree names are computed internally (`basename(dir)-[-N]`) with silent isolation downgrade on `no-git`/`add-failed`. Repairs applied to DESIGN.md: remotty-side **headless spawn verb** promoted to an explicit cross-repo deliverable (detached session, brief-file launch, loud worktree failure, machine-readable `{session, worktreePath, branch}` output); brief = file in the worktree, never argv; `assigned_agent` allowlisted against the roster; durable refs = session name + worktree path + branch (convo id opportunistic — hermes has none); bridge claims via `task checkout --worker ` and releases on spawn failure; lane-path-only `board --json` serialization (laneless shape is byte-frozen by prior WISH decision); roadmap-sync lockstep work added to IN; criterion 6 restated genie-side; host token = always `local` (same-server invariant); W1 routing → W2 spike+bridge → W3 fan-out wave order with W1 never gated. + +### FIX LOOP 2 (re-review FIX-FIRST narrow, 2026-08-11T00:06:33Z, digest `f2be7349…`) + +12/14 loop-1 findings verified closed; reviewer also confirmed `worktree prepare`/`open` accept caller-supplied names in-contract today (recovering most of the naming problem without remotty changes). Residuals repaired in DESIGN.md: cross-repo verb respecified as a **headless `worktree open` variant** (name input on an existing tree, refuses self-created worktrees, returns the authoritative uniquified session name); **turn-per-launch** conversation model (no remotty verb drives a live session — every turn, brief or follow-up, is a launch through the same verb with per-turn argv; adapters must exit per turn); briefs moved **out of the worktree** to `$GENIE_HOME/briefs/…` (untracked in-tree files would make every fan-out loser un-prunable under non-forced prune); failed-delegation cleanup rule (prune, or log orphan path on refusal); adapter cards = genie-side data with explicit `{brief}` placeholder + autonomy/permission flags + non-empty-diff smoke requirement (remotty's verbatim agents file cannot carry interpolation and stays remotty's business); trust posture stated (brief text is Felipe-authored, prompt boundary accepted); **pour as two genie wishes** (W1 now; W2+W3 blocked on named remotty wish `headless-turn-open`) so the external stall is a board edge (new Decision 13); lane-path consumer consequence clause added. + +### SHIP (loop-2 re-review, 2026-08-11T00:14:02Z, digest `c15d6a9e…`, evidence stamped + verified) + +All loop-2 repairs verified real against code. **Five residuals confined to W2/W3, to be applied as DESIGN edits (with fresh review) BEFORE the W2/W3 wish pours — none touch W1:** + +1. **MEDIUM-1 hermes continue:** hermes has no id-free continue form (roster file: "--resume is the whole answer"; sessions in `~/.hermes/state.db`, invisible to remotty's convo scan; `-c ` has a title-fallback trap). Before W2 pour: name hermes' real mechanism (continue-by-title keyed to candidate name, stateless turns with accumulated-context briefs, or single-turn scope) and fix Criterion 4. +2. **MEDIUM-2 cross-repo edge:** `task_dependencies` is same-DB FK-constrained — a depends-on to a remotty-repo wish is inexpressible. Use `genie task block --reason "blocked on remotty headless-turn-open"` (`block_kind='work'`) on the W2/W3 card instead. **Also reconcile DESIGN.md line 37** — it still says the W2/W3 wish "declares `depends-on`" the remotty wish; the W1 plan review (LOW-5) confirmed the wish's `task block` wording is the right story and the design sentence is stale. +3. **MEDIUM-3 dirty-orphan deadlock:** `.worktrees/` path is NOT uniquified by prepare (only the `wt/` branch is) — a dirty orphan makes every retry of the same card×agent fail at prepare forever. Decide: attempt/turn-counter suffix on candidate names, or operator-cleanup surfaced in `doctor`. +4. **MEDIUM-4 remotty ask shape:** the headless verb must take BOTH the roster name (for manifest identity — `revive`/fleet state/client rendering join on it) AND the launch argv. Write the remotty `headless-turn-open` wish from the amended paragraph. +5. **LOW-1 brief reach:** brief under `$GENIE_HOME` is outside several runtimes' default cwd sandbox — adapter cards must carry a read grant for the brief path, or the launcher passes the brief on stdin. + +Keep (reviewer): the id-free continue form is unambiguous **by cwd** — each candidate worktree is its own conversation scope; that's what makes turn-per-launch safe under fan-out. Make it explicit in the adapter rationale at W2 pour. + ## KNOWN (evidence — nous-skills-research 2026-07-09) - NousResearch/hermes-agent `skills/autonomous-ai-agents/` = one adapter skill per external CLI (claude-code, codex, hermes, opencode), all CLI-over-terminal. Portable mechanics: - codex: `codex exec` one-shot needs git repo + PTY + `--full-auto`; JSON output; `codex review --base origin/main`; parallel via git worktrees; auth via OPENAI_API_KEY or ~/.codex/auth.json. diff --git a/.genie/wishes/cross-agent-delegate/WISH.md b/.genie/wishes/cross-agent-delegate/WISH.md new file mode 100644 index 000000000..be31870dc --- /dev/null +++ b/.genie/wishes/cross-agent-delegate/WISH.md @@ -0,0 +1,270 @@ +# Wish: Declared Agent Routing on the Board (cross-agent W1) + +| Field | Value | +|-------|-------| +| **Status** | APPROVED | +| **Slug** | `cross-agent-delegate` | +| **Date** | 2026-08-11 | +| **Author** | Felipe + genie orchestrator | +| **Appetite** | small-medium | +| **Branch** | `wish/cross-agent-delegate` | +| **Repos touched** | genie only | +| **Design** | [DESIGN.md](../../brainstorms/cross-agent-delegate/DESIGN.md) | + +## Summary + +Wave 1 of the SHIP-reviewed cross-agent-delegation design: declare on the board card *which* coding agent (claude, codex, pi, hermes, prime) works a task and *why*, with NULL meaning the current orchestrating agent. This is the routing substrate the delegate bridge (follow-on wish, blocked on remotty `headless-turn-open`) consumes, and it alone unblocks remotty's client-rendering ask. Fully mechanical, no external dependencies. + +## Scope + +### IN + +- Additive nullable `tasks.assigned_agent` + `assigned_reason` columns: CREATE TABLE + additive-backfill path + `EXPECTED_SCHEMA.tasks`/`schemaIsCurrent` lockstep + `TaskRow` mapping. +- Roster allowlist (`claude`, `codex`, `pi`, `hermes`, `prime`) as a typed constant; non-roster names rejected with a named error at every write path. +- `genie task create --agent --why ` (`--agent` requires `--why`; `--why` alone is rejected). +- New `genie task assign --agent --why ` verb for existing cards, with `--clear` to remove an assignment (mirrors the `set-wish`/`--clear` precedent); each assign/clear appends a timeline note so the routing history rides the card thread. +- Assignment surfaced in `genie task status` and serialized on the **lane-path** `genie board --json` only (`enforcedBlock` precedent); the laneless `--json` shape stays byte-frozen. +- Roadmap-sync lockstep: `task export` payload, hand-enumerated `insertSnapshotRows`, older-snapshot null backfill (`?? null` pattern), and three-way `task sync` baseline coverage — assignment must survive export → import → sync. + +### OUT + +- Everything W2/W3 of the design: the delegate bridge, the seam spike, `task fan`, adapter cards, briefs, and the remotty `headless-turn-open` verb — follow-on wish (design Decision 13). +- Checkout enforcement: assignment is declaration only; `task checkout --worker` remains ungated, and `claimed_by`/`agent_kind` stay observed identity. The W2 bridge is what links them. +- Any change to the laneless `board --json` shape (byte-frozen by the boards-first-class WISH decision). +- Routing config files, WISH.md agent pins, stage-level defaults — routing is board-card-driven only. +- Remotty-side rendering of the new fields (remotty-repo work, tracked there). +- kimi in the allowlist (not in the requested five; the constant is a one-line extension when wanted). + +## Decisions + +| # | Decision | Rationale | +|---|----------|-----------| +| 1 | Two additive nullable TEXT columns, no `user_version` bump | Matches the `lane`/`agent_kind` additive precedent and the documented `?? null` snapshot-compat pattern in `insertSnapshotRows` | +| 2 | Allowlist is a typed in-code constant of the five roster names | Design Decision 11 (injection surface: assigned text reaches a shell and another agent's prompt in W2); constant-as-data keeps extension a one-line change | +| 3 | `--agent` requires `--why` | The design's routing semantics: an assignment *carries its rationale*; a why-less assignment is exactly the invisible routing this wish exists to kill | +| 4 | `task assign` gets `--clear`; assign/clear write timeline notes | Mis-assignments need correction without delete-and-recreate (the remotty-handoff lesson); notes make routing history part of the card thread the teammate channel will read | +| 5 | Lane-path-only serialization | Design Decision 10; laneless byte-freeze is a standing contract with its own regression tests | + +## Simplicity Case + +- **Simplest complete design:** two nullable columns + one constant + one flag pair on `create` + one new verb + lane-path serializer additions + sync lockstep. No new tables, no config surface, no enforcement, no migration bump. +- **Added machinery:** `--clear` (justified: correcting a wrong assignment must not require delete-and-recreate; follows the shipped `set-wish --clear` precedent); timeline notes on assign/clear (justified: design Decision 4 makes the card timeline the durable thread — routing changes are thread events). +- **Deferred until measured:** checkout gating on assignment (trigger: the W2 bridge, which claims via `checkout --worker`); roster as configuration (trigger: first roster change that can't wait for a release); any stage-level routing defaults (trigger: Felipe reverses the board-only decision). +- **Complexity removed:** no enforcement states, no config file, no WISH.md routing dialect, no laneless-shape change, no cross-repo work. + +## Dependencies + +**depends-on:** none +**blocks:** none + +Forward pointer (not yet a DAG edge — the wish linter requires existing slugs): `delegate-bridge`, the planned W2/W3 follow-on wish (design Decision 13), consumes these columns and must declare `depends-on: cross-agent-delegate` when poured; it is additionally blocked on the remotty `headless-turn-open` wish, recorded as a `task block` on its card per the design's cross-repo mechanism. + +## Success Criteria + +- [ ] `genie task create --title x --agent codex --why "dissent on parser"` persists both fields; `genie task status` displays them. +- [ ] `genie task assign --agent pi --why "…"` sets and overwrites on an existing card; `--clear` nulls both; each writes a timeline note. +- [ ] A non-roster name (`--agent gpt6`) is rejected with exit ≠ 0 and an error naming the allowed roster; `--agent` without `--why` is rejected. +- [ ] Lane-path `genie board --json` carries `assignedAgent`/`assignedReason`; the laneless shape is proven byte-identical to pre-change output on a fixture board (leak lists in `v5-board.test.ts`/`mcp.test.ts` extended). +- [ ] `task export` → `task import` → three-way `task sync` round-trip preserves both fields; importing an older snapshot without the keys succeeds with null backfill. +- [ ] `bun run wishes:lint` passes on this wish and the full gate `bun run check` passes on the branch. + +## Execution Strategy + +### Wave 1 (sequential gate — schema core only, kept small on purpose) + +| Group | Agent | Complexity | Model | Description | +|-------|-------|------------|-------|-------------| +| A1 | engineer | 3 — stateful SQLite schema (+2), documented `EXPECTED_SCHEMA`/`schemaIsCurrent` silent-skip trap (+1) | `engineer-standard` / high | Columns, additive backfill, lockstep, `TaskRow` mapping, roster constant + rejection error | + +### Wave 2 (parallel — all depend only on A1) + +| Group | Agent | Complexity | Model | Description | +|-------|-------|------------|-------|-------------| +| A2 | engineer | 2 — two CLI surfaces over a settled state API (+2 routing-semantics surface) | `engineer-standard` / medium | `create --agent/--why`, `task assign [--clear]`, timeline notes, `status` display, CLI docs | +| B | engineer | 2 — deterministic serialization against a byte-freeze contract (+2 contract-sensitive presentation) | `engineer-standard` / medium | Lane-path `board --json` fields + lane-path exact-key and laneless byte-freeze regressions | +| C | engineer | 3 — stateful three-way sync (+2), snapshot-compat trap (+1 prior-rework) | `engineer-standard` / high | `insertSnapshotRows`/sync-baseline lockstep + round-trip tests | + +Group A was split per plan-review MEDIUM-1: A1 is the only sequential gate, so a stumble in CLI surfaces (A2) no longer stalls B and C. + +## Execution Groups + +### Group A1: Schema core — columns, lockstep, roster + +**Goal:** The state engine carries validated assignment fields, upgrades existing DBs additively, and exposes them on `TaskRow`. + +**Deliverables:** +1. `assigned_agent`/`assigned_reason` nullable TEXT columns: CREATE TABLE, additive backfill for existing DBs, `EXPECTED_SCHEMA.tasks` + `schemaIsCurrent` lockstep, `TaskRow`/row-mapping updates (`src/lib/v5/genie-db.ts`, `src/lib/v5/task-state.ts`). +2. `ROSTER` allowlist constant (`claude|codex|pi|hermes|prime`) with a typed rejection error exported for every write path. +3. State-layer assign/clear functions (used by A2's verbs) enforcing allowlist + reason-required invariants at the API boundary. + +**Acceptance Criteria:** +- [ ] Assignment fields persist and round-trip through `TaskRow`. +- [ ] Non-roster agent and agent-without-reason are rejected at the state API (typed errors). +- [ ] A pre-existing DB (columns absent) upgrades additively on open — no `user_version` bump, no data loss; `schemaIsCurrent` returns false for the pre-upgrade shape so backfill cannot be skipped. + +**Validation:** +```bash +bun test src/lib/v5/task-state.test.ts src/lib/v5/genie-db.test.ts && bun run check +``` +Scope: the two files carrying the schema change, then the repository full gate — required because this group changes shared runtime schema (the wish skill's schema-change escalation rule; `bun run check` is the repo-documented gate). + +**depends-on:** none + +--- + +### Group A2: CLI verbs, timeline notes, and docs + +**Goal:** Assignment is settable at creation or later from the CLI, with history on the timeline and the verb documented where consumers look. + +**Deliverables:** +1. `task create --agent/--why` and new `task assign --agent --why [--clear]` in `src/term-commands/v5-task.ts`, calling the A1 state API; assign/clear append timeline notes; `task status` shows the assignment. +2. Docs (plan-review MEDIUM-2): add `task assign` and the `create` flags to the Task subcommands table in `CLAUDE.md`, noting the lane-path-only serialization consequence (non-lane/laneless readers do not see assignment, by design); if the `.docs-vendor` submodule is checked out in the execution worktree, update the CLI reference under `docs/_internal/` the same way. + +**Acceptance Criteria:** +- [ ] Create-with-assignment persists; assign overwrites; `--clear` nulls both fields. +- [ ] Non-roster agent and `--agent`-without-`--why` are rejected (exit ≠ 0, named errors). +- [ ] Assign/clear work at any card status — claimed, in-progress, done, blocked — with no status gate (declaration only; plan-review LOW-4). +- [ ] Assign/clear each append a visible timeline note; `task status` displays agent + why. +- [ ] `CLAUDE.md` Task subcommands table documents the new verb and flags. + +**Validation:** +```bash +bun test src/term-commands/v5-task.test.ts && grep -q 'task assign' CLAUDE.md +``` +Scope: the CLI surface's own test file plus a docs presence check; schema reach was already full-gated in A1, and the wish-level Success Criteria re-run `bun run check` on the branch. + +**depends-on:** group-a1 + +--- + +### Group B: Lane-path serialization + byte-freeze regression + +**Goal:** Any lane-board client can read assignments from `board --json`; laneless consumers see byte-identical output. + +**Deliverables:** +1. `assignedAgent`/`assignedReason` on lane-path card payloads in `src/term-commands/v5-board.ts` (alongside `enforcedBlock`). +2. The lane-path exact-sorted-key assertion (`v5-board.test.ts:350-363`, currently 12 keys) updated to include both fields — making "exactly these runtime fields on this path" an explicit, updated statement (plan-review LOW-1). +3. Laneless leak lists in `src/term-commands/v5-board.test.ts` and `src/term-commands/mcp.test.ts` extended with both fields; a byte-identical laneless regression against a fixture board. + +**Acceptance Criteria:** +- [ ] Lane-path `board --json` exposes both fields on assigned cards and omits nothing for unassigned ones (null semantics documented in the payload test). +- [ ] Laneless `--json` output for a fixture board is byte-identical to pre-change output; leak tests fail if either field escapes. + +**Validation:** +```bash +bun test src/term-commands/v5-board.test.ts src/term-commands/mcp.test.ts +``` +Scope: presentation-boundary change fully covered by the two serializer test files (the freeze contract's own regression home); the wish-level full gate in Group A's validation and the Success Criteria covers type/lint reach. + +**depends-on:** group-a1 + +--- + +### Group C: Roadmap-sync lockstep + +**Goal:** Assignments survive the canonical roadmap.json round-trip and three-way sync — Decision 1 of the design ("syncs via roadmap.json") becomes true. + +**Deliverables:** +1. `insertSnapshotRows` enumeration extended; older-snapshot imports backfill null via the documented `?? null` pattern (`src/lib/v5/task-state.ts`). Note: `exportState` is column-blind (`SELECT *`), so export needs no change (plan-review LOW-2) — verify with a test rather than editing it. +2. Three-way `task sync` baseline handling covers the new fields (no false diverged-state from their introduction). Disposition for `src/lib/v5/roadmap-sync.ts` (plan-review LOW-3): the existing pre-backfill-baseline pattern (`task-state.ts:1663`, test at `task-state.test.ts:1028`) likely already covers column introduction — verify, and either change it or record in the group's report that no change was needed. +3. Round-trip tests: export → import → sync preserves assignment; importing a pre-change snapshot succeeds. + +**Acceptance Criteria:** +- [ ] Export/import/sync round-trip preserves `assigned_agent`/`assigned_reason` exactly. +- [ ] A snapshot produced by an older build (keys absent) imports cleanly with nulls. +- [ ] Introducing the columns does not flip an in-sync repo to diverged on the next `task sync`. + +**Validation:** +```bash +bun test src/lib/v5/task-state.test.ts src/lib/v5/genie-db.test.ts && bun run check +``` +Scope: sync is shared runtime/core behavior touching the git-hook path — focused state-engine tests plus the repository full gate per the wish skill's escalation rule. + +**depends-on:** group-a1 + +--- + +## QA Criteria + +_What must be verified on dev after merge. The QA agent tests each criterion._ + +- [ ] Functional: in a real repo, `genie task create --title t --agent codex --why w` then `genie board --board --json` shows both fields; `task assign --clear` removes them. +- [ ] Integration: commit → pull cycle through the git-hook `task sync` path preserves an assignment across two checkouts of the same repo. +- [ ] Regression: laneless `genie board --json` output on an existing board is unchanged byte-for-byte from the prior release. + +--- + +## Assumptions / Risks + +| Risk | Severity | Mitigation | +|------|----------|------------| +| Laneless byte-freeze violated by accident | Medium | Dedicated byte-identical regression + extended leak lists fail the build | +| `EXPECTED_SCHEMA`/`schemaIsCurrent` omission lets initialized DBs skip backfill (documented trap) | Medium | Group A acceptance criterion tests the pre-existing-DB upgrade path explicitly | +| Sync-baseline false-diverged on column introduction | Medium | Group C acceptance criterion covers first-sync-after-upgrade | +| Allowlist too rigid for future roster changes | Low | Constant-as-data; one-line change, kimi already identified as first candidate | +| First `task export --write` after upgrade adds two null keys to every card in git-tracked `.genie/roadmap.json` | Low | Expected one-time diff (export is column-blind) — noted here so PR reviewers expect it rather than question it (plan-review LOW-2) | + +--- + +## Review Results + +_The read-only reviewer returns evidence; the invoking orchestrator appends a timestamped block here after plan, execution, and PR reviews._ + +### Plan review — SHIP (2026-08-11T00:21:16Z) + +- **Reviewer:** design-review-cross-agent-delegate (read-only; same reviewer as the design's two fix loops) +- **Verdict:** SHIP — "a faithful, complete W1 pour of the SHIP'd design"; mechanics verified against the repo (all named test files exist; `wishes:lint` passes; leak-list/freeze assertions located at `v5-board.test.ts:744-780`, `mcp.test.ts:419-436`; full-gate escalation correctly applied to schema/sync groups and withheld from the presentation group; scope fidelity confirmed in both directions; no conflict with the five W2/W3 design residuals). +- **Findings and dispositions (all applied in-document before status flip):** + - MEDIUM-1 (Group A under-routed as sequential gate) → **split into A1 (schema core, sole gate) + A2 (CLI verbs/docs, parallel with B/C)** — the reviewer's preferred resolution. + - MEDIUM-2 (new verb undocumented) → docs deliverable added to A2 (`CLAUDE.md` Task subcommands table + lane-path consumer consequence; `docs/_internal/` CLI reference if the submodule is checked out). + - LOW-1 (lane-path exact-key assertion) → named as Group B deliverable 2 (`v5-board.test.ts:350-363`). + - LOW-2 (`exportState` column-blind; one-time roadmap.json null-key diff) → Group C deliverable reworded; expected-diff row added to Risks. + - LOW-3 (`roadmap-sync.ts` unlisted) → verify-only disposition added to Group C and Files (pre-backfill-baseline pattern at `task-state.ts:1663` likely covers it). + - LOW-4 (assign vs card status unspecified) → A2 acceptance criterion: assign/clear allowed at any status, no gate (declaration only). + - LOW-5 (design line 37 stale on the cross-repo mechanism — wish is right, design stale) → reconciliation note added to the DRAFT residual list; the design edit lands with the W2/W3 residual application and its fresh review. +- **Kept from the review:** W1's allowlist is declaration-time only, so a hermes single-turn scoping in W2 requires no W1 rework — declaration and turn capability are independent (design Decision 9). + +--- + +## Files to Create/Modify + +``` +src/lib/v5/genie-db.ts # columns, EXPECTED_SCHEMA, schemaIsCurrent, backfill +src/lib/v5/genie-db.test.ts +src/lib/v5/task-state.ts # TaskRow, ROSTER allowlist, assign API, insertSnapshotRows +src/lib/v5/task-state.test.ts +src/lib/v5/roadmap-sync.ts # verify only — pre-backfill baseline likely covers column introduction (LOW-3) +src/term-commands/v5-task.ts # create --agent/--why, assign verb, status display +src/term-commands/v5-task.test.ts +src/term-commands/v5-board.ts # lane-path serialization +src/term-commands/v5-board.test.ts # lane-path exact-key list + laneless leak lists +src/term-commands/mcp.test.ts # leak-list extension +CLAUDE.md # Task subcommands table: assign verb + create flags (MEDIUM-2) +``` + +### Execution review — SHIP (2026-08-11T01:56:19Z) + +- **Reviewers:** reviewer-a1, reviewer-a2, reviewer-b, reviewer-c (per-group, all independent of the engineers), reviewer-quality (whole-branch security/maintainability/perf pass). Reviewer ≠ engineer held throughout. +- **Verdicts:** A1 schema core SHIP · A2 CLI verbs+docs SHIP · B lane-path serialization SHIP · C sync lockstep SHIP · Quality pass SHIP — zero must-fix findings across all five reviews. +- **Branch:** `wish/cross-agent-delegate` (base `8211b56ac` = dev HEAD). Commits: `5bd2cbaaa` (A1), `f8f3c5de6` (A2), `91cead7de` (B), `c69ae7c27` (C), on top of `c08aba486` (wish docs). +- **Validation evidence (orchestrator-run):** focused suites — A1 `131 pass/0 fail`, A2 `75 pass/0 fail`, B `69 pass/0 fail`, C `134 pass/0 fail`; combined quality-pass run `278 pass/0 fail`; `bun run wishes:lint` OK (76 files). Full gate `bun run check`: **3192 pass / 14 fail — all 14 are the pre-existing environment set** (local-delivery-repair ×3, doctor 120ms latency budget ×1, agent-sync ×4, update-command ×4, codex dogfood ×2), proven at base `c08aba486` by a detached-baseline re-run (13 reproduce identically; the 14th is a timing flake); zero wish-related failures. The 4 B-owned presentation assertions that were red after A1 are green after B landed. +- **Executed as planned, with two authorized deviations, both verified legitimate:** + 1. `src/lib/v5/mcp-tools.ts` added to B's file set — `genieTask` returns the raw `TaskRow` so the laneless byte-freeze requires stripping the two fields there (A1 engineer finding, confirmed by reviewer-b). + 2. `src/lib/v5/card-render.test.ts` 2-line fixture tweak in A1 — `TaskRow` fields are required, so the hand-built `TaskCardRow` fixture needed nulls; typecheck-forced, behavior-neutral (confirmed by reviewer-a1). +- **Dispositions per plan-review residuals:** LOW-2 confirmed — `exportState` is column-blind (`SELECT *`), no edit needed, verified by test; LOW-3 confirmed — `roadmap-sync.ts` needed NO change (hash-based sync: db gains two null keys per card → `dbChanged && !fileChanged` → export branch, never diverged; first sync `exported`, second `none`), verified by reviewer-c; LOW-4 confirmed — assign/clear work at any card status (claimed/in_progress/done/blocked tested). A1's assign/clear timeline events are appended in-transaction by the state API; CLI verbs do not double-append (A2 criterion, verified). +- **Non-blocking INFO items recorded (no action required for W1):** roster case-sensitivity not pinned; identical-pair no-op is a pre-transaction TOCTOU (duplicate audit event possible under concurrent identical assigns — cosmetic, matches `setTaskWish` precedent; W2 bridge should read-modify-write inside the transaction); pre-existing stale `listTasksWithLane` docstring ('export stays byte-identical') now superseded by design — export intentionally gains the two keys; imported snapshots store assignment raw (declaration-only by design, `block_kind` precedent) — the W2 bridge must validate at consumption (design Decision 2 contract). +- **QA Criteria handoff:** functional/integration/regression criteria from the wish's QA section remain to be verified on dev after merge by the QA agent; the laneless byte-identity regression is already enforced in-tree by B's fixture test. + +### Pre-merge independent review — SHIP (2026-08-11T14:09:03Z) + +- **Reviewer:** reviewer-final-cross-agent-delegate (fresh reviewer, independent of the work session's engineers and reviewers; read-only, evidence re-derived — not inherited from the execution-review block above). +- **Target:** `ca391178299d452dd9ad6f61c350058b624277f9` on `wish/cross-agent-delegate`, base `8211b56ac` confirmed via merge-base; clean tree verified at review start and end. +- **Verdict:** SHIP — all six wish success criteria PASS on independently derived evidence; diff confined to the wish's Files section plus the two authorized deviations (both re-verified minimal); no secrets; all commits conventional and wish-attributed; no machinery beyond the approved Simplicity Case. +- **Evidence (reviewer-run):** full gate `bun run check` 3192 pass / 14 fail — all 14 attributed by test name to the declared pre-existing environment set, every one outside wish-touched surfaces; focused suites (`task-state`, `genie-db`, `v5-task`, `v5-board`, `mcp`, `card-render`) 286 pass / 0 fail (1241 expects); `wishes:lint` OK 76 files. Real-CLI transcripts in a throwaway repo (tmpdir `GENIE_HOME`): create/status display, assign→overwrite→clear with in-transaction timeline notes, ten rejection cases all exit 1 with named stderr errors (incl. `CODEX` case-sensitivity and `codex; rm -rf /` injection probe), lane-path `board --json` carries both fields while live laneless output stays at the ten frozen keys (freeze is structural: `Omit` in both `toLanelessJsonCard` and `toFrozenTaskRow`), and export → sync×2 (`none`,`none`) → DB wipe → import → older-keyless-snapshot import all round-trip correctly. +- **Gaps (none blocking):** + - MEDIUM — the Decision-2 "validate at consumption" contract exists only in wish prose: snapshot import stores `assigned_agent`/`assigned_reason` raw (confirmed by injection probe; harmless in W1 where nothing executes the value). Fix is a one-line doc on `TaskRow`'s `assignedAgent` (or above `mapTask`) mirroring the `blockKindOf` untrusted-TEXT warning, directing consumers to `requireRosterAgent` before any shell/prompt use. **Carried into `delegate-bridge` (W2) as a named prerequisite.** + - LOW — create-time routing writes no timeline entry (conforms to wish; W2 timeline readers won't see the original declaration). + - LOW — `task status` `Assigned to:` value misaligned one column vs. sibling labels (`src/term-commands/v5-task.ts:141-144`). + - INFO — roster matching is case-sensitive (recorded as a decision, not an accident). + - Checked and cleared: `task status | head` EPIPE trace is pre-existing (`out()` helper, untouched by this diff). +- **Next step per SHIP:** PR targeting `dev`; wish remains pre-SHIPPED until authorized merge plus QA criteria pass on dev. diff --git a/CLAUDE.md b/CLAUDE.md index a59da8c1f..2a0f23cb9 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -94,11 +94,12 @@ Fourteen top-level commands (run `genie --help` for detail): ### Task subcommands ```bash -genie task create --title 'x' # Create a task +genie task create --title 'x' [--agent --why ] # Create a task; --agent/--why declare routing (pair required) genie task list # List tasks (with filters) genie task checkout --worker w # Atomically claim a ready task for a worker -genie task status # Task detail, dependencies, stage log +genie task status # Task detail, dependencies, stage log (shows the declared assignment) genie task set-wish --wish w # Attach/re-point wish identity on an existing card (--clear removes) +genie task assign --agent --why # Declare/reassign which roster agent works a card (--clear removes) genie task delete # Hard-delete a card (refused while other cards depend on it) genie task done # Orchestrator only: mark reviewed work done + recompute ready set genie task export # Emit the complete DB state as JSON @@ -107,6 +108,11 @@ genie task import [--replace] # Restore genie.db from .genie/roadmap.jso genie task sync # Three-way reconcile genie.db <-> roadmap.json (run by git hooks on pull/commit) ``` +`--agent` names a roster agent (`claude|codex|pi|hermes|prime`) and requires `--why`; +`--why` alone is rejected too. Assignment is declaration-only (no checkout gate) +and serializes on the lane path only — non-lane/laneless readers do not see it, +by design. + ### Omni subcommands ```bash diff --git a/src/lib/v5/card-render.test.ts b/src/lib/v5/card-render.test.ts index dc711ace1..dcd283d8a 100644 --- a/src/lib/v5/card-render.test.ts +++ b/src/lib/v5/card-render.test.ts @@ -30,6 +30,8 @@ function card(over: Partial = {}): TaskCardRow { heartbeatAt: null, blockedBy: null, blockedReason: null, + assignedAgent: null, + assignedReason: null, ...over, }; } diff --git a/src/lib/v5/genie-db.test.ts b/src/lib/v5/genie-db.test.ts index 28bc61e25..4318bd7a1 100644 --- a/src/lib/v5/genie-db.test.ts +++ b/src/lib/v5/genie-db.test.ts @@ -277,6 +277,80 @@ describe('pre-lanes DB backfill (additive, no version bump)', () => { }); }); +// --------------------------------------------------------------------------- +// Pre-assignment backfill (cross-agent-delegate W1): a DB initialized by a +// build that predates tasks.assigned_agent/assigned_reason must be detected as +// NOT current (EXPECTED_SCHEMA lockstep) so ensureSchema re-runs and backfills +// additively — no user_version bump, no data loss. The documented trap is +// omitting the columns from EXPECTED_SCHEMA: schemaIsCurrent would then return +// true for the pre-upgrade shape and the backfill would be silently skipped. +// --------------------------------------------------------------------------- +describe('pre-assignment DB backfill (additive, no version bump)', () => { + test('a full-schema DB missing only the assignment columns is not current and heals on open', () => { + const path = join(dir, 'pre-assignment.db'); + const db1 = openDb({ path }); + // A card with real assignment data, plus an unassigned one — both must + // survive the drop/re-add cycle intact. + db1 + .query( + "INSERT INTO tasks (id, title, status, created_at, updated_at, assigned_agent, assigned_reason) VALUES ('t_a', 'routed', 'ready', 1, 1, 'codex', 'dissent on parser')", + ) + .run(); + db1 + .query("INSERT INTO tasks (id, title, status, created_at, updated_at) VALUES ('t_b', 'plain', 'ready', 1, 1)") + .run(); + // Simulate a DB stamped by the previous build: drop ONLY the two new + // columns; everything else stays at the current shape. + db1.exec('ALTER TABLE tasks DROP COLUMN assigned_agent'); + db1.exec('ALTER TABLE tasks DROP COLUMN assigned_reason'); + // The lockstep contract: the pre-upgrade shape must NOT read as current — + // otherwise openDb's fast path would skip ensureSchema and the backfill + // would silently never run on already-initialized DBs. + expect(isCurrentGenieDb(db1)).toBe(false); + expect(isReadableGenieDb(db1)).toBe(false); + db1.close(); + + const db2 = openDb({ path }); + // Additive migration — user_version unchanged. + expect((db2.query('PRAGMA user_version').get() as { user_version: number }).user_version).toBe( + CURRENT_SCHEMA_VERSION, + ); + // Both columns backfilled; every pre-existing row (and its assignment) + // survived. + const cols = new Set((db2.query('PRAGMA table_info(tasks)').all() as Array<{ name: string }>).map((c) => c.name)); + expect(cols.has('assigned_agent')).toBe(true); + expect(cols.has('assigned_reason')).toBe(true); + // The pre-existing row survived the heal; the re-added columns read as NULL + // (a real pre-assignment DB never carried assignment data — SQLite DROP + // COLUMN discards values, so the fresh column starts null exactly as it + // would on a database that predates the feature). + const routed = db2.query('SELECT title, assigned_agent, assigned_reason FROM tasks WHERE id = ?').get('t_a') as { + title: string; + assigned_agent: string | null; + assigned_reason: string | null; + }; + expect(routed).toEqual({ title: 'routed', assigned_agent: null, assigned_reason: null }); + const plain = db2.query('SELECT assigned_agent, assigned_reason FROM tasks WHERE id = ?').get('t_b') as { + assigned_agent: string | null; + assigned_reason: string | null; + }; + expect(plain).toEqual({ assigned_agent: null, assigned_reason: null }); + // The healed DB is now current, and a re-open is a pure no-op. + expect(isCurrentGenieDb(db2)).toBe(true); + db2.close(); + expect(isCurrentGenieDb(openDb({ path }))).toBe(true); + }); + + test('a fresh DB carries the assignment columns from CREATE TABLE', () => { + const path = join(dir, 'fresh.db'); + const db = openDb({ path }); + const cols = new Set((db.query('PRAGMA table_info(tasks)').all() as Array<{ name: string }>).map((c) => c.name)); + db.close(); + expect(cols.has('assigned_agent')).toBe(true); + expect(cols.has('assigned_reason')).toBe(true); + }); +}); + // --------------------------------------------------------------------------- // Busy classification: a contended write lock is transient, not corruption. The // production bug was openDb wrapping SQLITE_BUSY into MalformedDbError under diff --git a/src/lib/v5/genie-db.ts b/src/lib/v5/genie-db.ts index 6eb652fc0..cf2b8047b 100644 --- a/src/lib/v5/genie-db.ts +++ b/src/lib/v5/genie-db.ts @@ -435,6 +435,8 @@ const EXPECTED_SCHEMA = { 'blocked_by', 'blocked_reason', 'block_kind', + 'assigned_agent', + 'assigned_reason', ], wish_groups: [ 'wish', @@ -451,8 +453,9 @@ const EXPECTED_SCHEMA = { /** * True when the DB is already at the current schema — every expected table plus - * the additive lane/wish columns backfilled by {@link ensureTaskColumns} and - * {@link ensureBoardColumns}. Pure reads (no write lock), so a known-current DB + * the additive lane/wish/assignment columns backfilled by + * {@link ensureTaskColumns} and {@link ensureBoardColumns}. Pure reads (no + * write lock), so a known-current DB * opens without contending on the schema lock. A pre-column v1 DB (missing any * of these) returns false → ensureSchema runs and backfills. This MUST stay in * lockstep with the ensure* helpers: an added column absent here would let an @@ -533,16 +536,18 @@ CREATE TABLE IF NOT EXISTS boards ( ); CREATE TABLE IF NOT EXISTS tasks ( - id TEXT PRIMARY KEY, - board_id TEXT REFERENCES boards(id) ON DELETE SET NULL, - title TEXT NOT NULL, - status TEXT NOT NULL CHECK (status IN ('blocked', 'ready', 'in_progress', 'done')), - claimed_by TEXT, - claimed_at INTEGER, - wish TEXT, - group_name TEXT, - created_at INTEGER NOT NULL, - updated_at INTEGER NOT NULL + id TEXT PRIMARY KEY, + board_id TEXT REFERENCES boards(id) ON DELETE SET NULL, + title TEXT NOT NULL, + status TEXT NOT NULL CHECK (status IN ('blocked', 'ready', 'in_progress', 'done')), + claimed_by TEXT, + claimed_at INTEGER, + wish TEXT, + group_name TEXT, + assigned_agent TEXT, + assigned_reason TEXT, + created_at INTEGER NOT NULL, + updated_at INTEGER NOT NULL ); CREATE TABLE IF NOT EXISTS task_dependencies ( @@ -632,6 +637,11 @@ function ensureTaskColumns(db: Database): void { if (!cols.has('blocked_by')) db.exec('ALTER TABLE tasks ADD COLUMN blocked_by TEXT'); if (!cols.has('blocked_reason')) db.exec('ALTER TABLE tasks ADD COLUMN blocked_reason TEXT'); if (!cols.has('block_kind')) db.exec('ALTER TABLE tasks ADD COLUMN block_kind TEXT'); + // Declared routing (cross-agent-delegate W1): which roster agent works the + // card and why. Nullable ⇒ no user_version bump; both halves travel together + // (an assignment without its reason is rejected at the state API). + if (!cols.has('assigned_agent')) db.exec('ALTER TABLE tasks ADD COLUMN assigned_agent TEXT'); + if (!cols.has('assigned_reason')) db.exec('ALTER TABLE tasks ADD COLUMN assigned_reason TEXT'); } /** Meta key marking the one-time stage_log → task_events backfill as complete. */ diff --git a/src/lib/v5/mcp-tools.ts b/src/lib/v5/mcp-tools.ts index 992b8b3a7..b2717ca9d 100644 --- a/src/lib/v5/mcp-tools.ts +++ b/src/lib/v5/mcp-tools.ts @@ -31,6 +31,7 @@ import { BUSY_TIMEOUT_MS } from './sqlite-open.js'; // the readonly bun:sqlite open out of the eager genie.ts import graph. export { isCurrentGenieDb, type ProjectContext, resolveProjectContext } from './genie-db.js'; import { + type FrozenTaskRow, type TaskFilter, type TaskRow, type WishGroupRow, @@ -38,6 +39,7 @@ import { getTask, listTasks, listWishSlugs, + toFrozenTaskRow, } from './task-state.js'; // ============================================================================ @@ -383,10 +385,17 @@ function genieWorktreeContext(ctx: ToolContext, args: Record): // --- genie_task ------------------------------------------------------------ -function genieTask(ctx: ToolContext, args: Record): TaskRow | { error: 'not_found'; id: string } { +// The frozen `genie_task` payload is exactly the pre-assignment TaskRow key +// set (WISH Decision 7) — the shared projection lives in task-state.ts next +// to TaskRow, so `task list --json` and this MCP shape cannot drift apart. + +function genieTask( + ctx: ToolContext, + args: Record, +): FrozenTaskRow | { error: 'not_found'; id: string } { const id = argString(args, 'id') ?? ''; const task = ctx.db ? getTask(ctx.db, id) : null; - return task ?? { error: 'not_found', id }; + return task ? toFrozenTaskRow(task) : { error: 'not_found', id }; } // --- genie_active ---------------------------------------------------------- diff --git a/src/lib/v5/task-state.test.ts b/src/lib/v5/task-state.test.ts index 73b9be729..dafabca9d 100644 --- a/src/lib/v5/task-state.test.ts +++ b/src/lib/v5/task-state.test.ts @@ -1,10 +1,13 @@ import type { Database } from 'bun:sqlite'; import { afterEach, beforeEach, describe, expect, test } from 'bun:test'; -import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { createHash } from 'node:crypto'; +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { ensureSchema, isCurrentGenieDb, openDb } from './genie-db.js'; +import { roadmapSnapshot, syncRoadmap } from './roadmap-sync.js'; import { + AssignmentReasonRequiredError, CheckoutConflictError, CycleError, DEFAULT_LIFECYCLE_LANES, @@ -13,18 +16,22 @@ import { LIVENESS_RUNNING_MS, LIVENESS_STALE_MS, LaneError, + ROSTER, TaskBlockedError, TaskCompleteError, TaskHasDependentsError, TaskNotReadyError, TaskReleaseError, type TaskRow, + UnknownRosterAgentError, UnknownTaskError, addDependency, appendStage, appendTaskEvent, + assignTask, blockTask, claimTask, + clearTaskAssignment, commentCounts, completeTask, countBoardTasks, @@ -43,6 +50,7 @@ import { getTaskLane, hireAgent, importState, + isRosterAgent, linkTaskToWish, listBoards, listHires, @@ -735,12 +743,17 @@ describe('lane projection carries enforcedBlock', () => { expect(byId.get(held.id)?.enforcedBlock).toEqual({ reason: 'parked until Q3', kind: 'hold' }); }); - test('the lane projection gains ONLY enforcedBlock — provenance and heartbeat stay off it', () => { - const a = createTask(db, { title: 'a' }); + test('the lane projection gains ONLY enforcedBlock beyond TaskRow — provenance and heartbeat stay off it', () => { + const a = createTask(db, { title: 'a', assignedAgent: 'codex', assignedReason: 'dissent' }); blockTask(db, a.id, 'r', HUMAN, 'hold'); recordHeartbeat(db, a.id); const row = listTasksWithLane(db).find((t) => t.id === a.id) as unknown as Record; + // LaneTaskRow = TaskRow (assignment fields included, per W1) + lane + + // enforcedBlock. The runtime layer (agentKind/heartbeatAt/blockedBy/ + // blockedReason) stays off this projection. expect(Object.keys(row).sort()).toEqual([ + 'assignedAgent', + 'assignedReason', 'boardId', 'claimedAt', 'claimedBy', @@ -754,6 +767,8 @@ describe('lane projection carries enforcedBlock', () => { 'updatedAt', 'wish', ]); + expect(row.assignedAgent).toBe('codex'); + expect(row.assignedReason).toBe('dissent'); }); test('the frozen TaskRow path never gains enforcedBlock', () => { @@ -913,6 +928,216 @@ describe('runtime layer — claim / release timeline events', () => { }); }); +describe('declared routing — roster allowlist + assignment state API (W1)', () => { + test('ROSTER is the typed five-agent allowlist', () => { + expect(ROSTER).toEqual(['claude', 'codex', 'pi', 'hermes', 'prime']); + expect(isRosterAgent('codex')).toBe(true); + expect(isRosterAgent('gpt6')).toBe(false); + }); + + test('createTask persists an assignment and round-trips through TaskRow', () => { + const task = createTask(db, { + title: 'dissent review', + assignedAgent: 'codex', + assignedReason: 'dissent on parser', + }); + expect(task.assignedAgent).toBe('codex'); + expect(task.assignedReason).toBe('dissent on parser'); + const fetched = getTask(db, task.id); + expect(fetched).toEqual(task); + expect(listTasks(db)[0]?.assignedAgent).toBe('codex'); + // Both columns on the raw row, both null when unassigned. + const row = db.query('SELECT assigned_agent, assigned_reason FROM tasks WHERE id = ?').get(task.id) as { + assigned_agent: string | null; + assigned_reason: string | null; + }; + expect(row).toEqual({ assigned_agent: 'codex', assigned_reason: 'dissent on parser' }); + const plain = createTask(db, { title: 'unassigned' }); + expect(plain.assignedAgent).toBeNull(); + expect(plain.assignedReason).toBeNull(); + }); + + test('createTask rejects a non-roster agent with UnknownRosterAgentError naming the roster', () => { + expect(() => createTask(db, { title: 'x', assignedAgent: 'gpt6', assignedReason: 'why' })).toThrow( + UnknownRosterAgentError, + ); + try { + createTask(db, { title: 'x', assignedAgent: 'gpt6', assignedReason: 'why' }); + throw new Error('expected UnknownRosterAgentError'); + } catch (err) { + if (err instanceof UnknownRosterAgentError) { + expect(err.agent).toBe('gpt6'); + expect(err.message).toContain('claude'); + expect(err.message).toContain('prime'); + } else throw err; + } + }); + + test('createTask rejects a half-written assignment either way round (Decision 3)', () => { + // --agent without --why + expect(() => createTask(db, { title: 'x', assignedAgent: 'codex' })).toThrow(AssignmentReasonRequiredError); + // --why alone + expect(() => createTask(db, { title: 'x', assignedReason: 'why' })).toThrow(AssignmentReasonRequiredError); + // blank reason is not a reason + expect(() => createTask(db, { title: 'x', assignedAgent: 'codex', assignedReason: ' ' })).toThrow( + AssignmentReasonRequiredError, + ); + // nothing was written by the rejected attempts + expect(listTasks(db)).toEqual([]); + }); + + test('assignTask sets the pair, bumps updated_at, and appends one assign event', () => { + const task = createTask(db, { title: 't' }); + const assigned = assignTask(db, task.id, 'pi', 'cost arbitrage', { author: 'felipe', authorKind: 'human' }, 5_000); + expect(assigned.assignedAgent).toBe('pi'); + expect(assigned.assignedReason).toBe('cost arbitrage'); + expect(assigned.updatedAt).toBe(5_000); + expect(getTask(db, task.id)).toEqual(assigned); + const events = getTaskEvents(db, task.id); + expect(events.map((e) => e.kind)).toEqual(['assign']); + expect(events[0]?.note).toBe('assigned to pi: cost arbitrage'); + expect(events[0]?.author).toBe('felipe'); + expect(events[0]?.authorKind).toBe('human'); + }); + + test('assignTask overwrites a prior assignment with a fresh event', () => { + const task = createTask(db, { title: 't', assignedAgent: 'codex', assignedReason: 'first opinion' }); + const reassigned = assignTask(db, task.id, 'hermes', 'second opinion', { author: 'felipe', authorKind: 'human' }); + expect(reassigned.assignedAgent).toBe('hermes'); + expect(reassigned.assignedReason).toBe('second opinion'); + expect(getTaskEvents(db, task.id).map((e) => e.note)).toEqual(['assigned to hermes: second opinion']); + }); + + test('re-assigning the exact stored pair is a silent no-op (set-wish precedent)', () => { + const task = createTask(db, { title: 't' }); + assignTask(db, task.id, 'codex', 'dissent', { author: 'felipe', authorKind: 'human' }, 9_000); + const eventsAfterFirst = JSON.stringify(getTaskEvents(db, task.id)); + const again = assignTask(db, task.id, 'codex', 'dissent', { author: 'felipe', authorKind: 'human' }, 10_000); + expect(again.updatedAt).toBe(9_000); // no row write + expect(JSON.stringify(getTaskEvents(db, task.id))).toBe(eventsAfterFirst); // no new event + }); + + test('assignTask enforces the allowlist + reason invariants at the API boundary', () => { + const task = createTask(db, { title: 't' }); + expect(() => assignTask(db, task.id, 'gpt6', 'why')).toThrow(UnknownRosterAgentError); + expect(() => assignTask(db, task.id, 'codex', ' ')).toThrow(AssignmentReasonRequiredError); + expect(() => assignTask(db, task.id, '', 'why')).toThrow(AssignmentReasonRequiredError); + expect(getTask(db, task.id)?.assignedAgent).toBeNull(); + }); + + test('assignTask works at any status — declaration only, no status gate', () => { + const task = createTask(db, { title: 't' }); + claimTask(db, task.id, 'worker-1', { now: 1_000 }); + completeTask(db, task.id); // done + const assigned = assignTask(db, task.id, 'claude', 'review the merge'); + expect(assigned.assignedAgent).toBe('claude'); + expect(assigned.status).toBe('done'); + }); + + test('assignTask and clearTaskAssignment throw UnknownTaskError for unknown ids', () => { + expect(() => assignTask(db, 't_missing', 'codex', 'why')).toThrow(UnknownTaskError); + expect(() => clearTaskAssignment(db, 't_missing')).toThrow(UnknownTaskError); + }); + + test('clearTaskAssignment nulls both halves and appends a clear event naming the prior pair', () => { + const task = createTask(db, { title: 't', assignedAgent: 'codex', assignedReason: 'dissent on parser' }); + const cleared = clearTaskAssignment(db, task.id, { author: 'felipe', authorKind: 'human' }, 7_000); + expect(cleared.assignedAgent).toBeNull(); + expect(cleared.assignedReason).toBeNull(); + expect(cleared.updatedAt).toBe(7_000); + const events = getTaskEvents(db, task.id); + expect(events.map((e) => e.kind)).toEqual(['clear']); + expect(events[0]?.note).toBe('assignment cleared (was codex: dissent on parser)'); + expect(events[0]?.author).toBe('felipe'); + }); + + test('clearing an already-unassigned card is a silent no-op', () => { + const task = createTask(db, { title: 't' }); + const cleared = clearTaskAssignment(db, task.id, { author: 'felipe', authorKind: 'human' }, 5_000); + expect(cleared.updatedAt).not.toBe(5_000); + expect(getTaskEvents(db, task.id)).toEqual([]); + }); +}); + +describe('declared routing — roadmap snapshot round-trip (roadmap-sync lockstep)', () => { + // Mirrors roadmap-sync's canonicalHash: sha256 over the parsed JSON form, so + // whitespace/formatting differences never count as content changes. + function canonicalHash(value: unknown): string { + return createHash('sha256').update(JSON.stringify(value)).digest('hex'); + } + + test('export carries assigned_agent/assigned_reason (SELECT *) and round-trips them through import', () => { + const a = createTask(db, { title: 'a', assignedAgent: 'codex', assignedReason: 'dissent on parser' }); + const snapshot = exportState(db); + // exportState is column-blind — the raw keys must travel with the row. + expect(snapshot.tasks[0].assigned_agent).toBe('codex'); + expect(snapshot.tasks[0].assigned_reason).toBe('dissent on parser'); + + const path = join(dir, 'round-trip-assignment.db'); + const fresh = openDb({ path }); + importState(fresh, snapshot); + const card = getTask(fresh, a.id); + fresh.close(); + expect(card?.assignedAgent).toBe('codex'); + expect(card?.assignedReason).toBe('dissent on parser'); + }); + + test('a same-version snapshot whose tasks omit the assignment keys imports cleanly as nulls', () => { + const a = createTask(db, { title: 'a', assignedAgent: 'hermes', assignedReason: 'second opinion' }); + const snapshot = exportState(db); + // An older build at the same schemaVersion never wrote the keys at all. + const older = { + ...snapshot, + tasks: snapshot.tasks.map(({ assigned_agent: _droppedAgent, assigned_reason: _droppedReason, ...rest }) => rest), + } as unknown as typeof snapshot; + + const path = join(dir, 'older-snapshot-assignment.db'); + const fresh = openDb({ path }); + const summary = importState(fresh, older); + const card = getTask(fresh, a.id); + fresh.close(); + expect(summary.tasks).toBe(1); + expect(card?.assignedAgent).toBeNull(); + expect(card?.assignedReason).toBeNull(); + }); + + test('introducing the assignment columns does not flip an in-sync repo to diverged', () => { + // Repo state BEFORE the columns existed: roadmap.json without the keys and a + // baseline marker describing that exact (file, db) pair as in-sync. + const repo = join(dir, 'sync-upgrade'); + mkdirSync(join(repo, '.genie'), { recursive: true }); + const d = openDb({ path: join(repo, 'genie.db') }); + const task = createTask(d, { title: 'assigned card', assignedAgent: 'codex', assignedReason: 'dissent' }); + const current = roadmapSnapshot(d); + const preUpgrade = { + ...current, + tasks: current.tasks.map(({ assigned_agent: _droppedAgent, assigned_reason: _droppedReason, ...rest }) => rest), + } as unknown as typeof current; + const preUpgradeHash = canonicalHash(preUpgrade); + writeFileSync(join(repo, '.genie', 'roadmap.json'), `${JSON.stringify(preUpgrade, null, 2)}\n`); + writeFileSync( + join(repo, '.genie', 'roadmap-sync'), + `${JSON.stringify({ fileHash: preUpgradeHash, dbHash: preUpgradeHash }, null, 2)}\n`, + ); + + // First sync after the upgrade: the db side gained two null keys per card, + // the file did not move. That is a db-only change → export, never a + // divergence (precedent: lane/agent_kind/block_kind shipped identically). + const first = syncRoadmap(d, repo); + expect(first.action).not.toBe('diverged'); + expect(first.action).toBe('exported'); + const published = JSON.parse(readFileSync(join(repo, '.genie', 'roadmap.json'), 'utf-8')); + expect(published.tasks[0]?.assigned_agent).toBe('codex'); + expect(published.tasks[0]?.assigned_reason).toBe('dissent'); + + // The one-time diff settles: the next sync is a no-op, pair intact. + const second = syncRoadmap(d, repo); + d.close(); + expect(second.action).toBe('none'); + expect(task.assignedAgent).toBe('codex'); // sanity: the seeded pair + }); +}); + describe('completeTask is orchestrator-authoritative (status CAS only)', () => { const WORKER_A = { author: 'worker-a', authorKind: 'claude-code' }; const ORCHESTRATOR = { author: 'orchestrator', authorKind: 'claude-code' }; diff --git a/src/lib/v5/task-state.ts b/src/lib/v5/task-state.ts index b2aa8ca90..59fa5a740 100644 --- a/src/lib/v5/task-state.ts +++ b/src/lib/v5/task-state.ts @@ -32,10 +32,38 @@ export interface TaskRow { wish: string | null; /** Wish-group name this task belongs to, or null. */ group: string | null; + /** Declared roster agent that works this card, or null when the current orchestrating agent does (W1 routing). */ + assignedAgent: string | null; + /** Why the declared agent was assigned; always present when assignedAgent is set. */ + assignedReason: string | null; createdAt: number; updatedAt: number; } +/** + * The frozen pre-assignment TaskRow key set. The two declared-routing fields + * live on TaskRow but serialize on the additive lane board `--json` path only + * (WISH decision: lane-path-only); every other machine-readable task payload + * ships this projection. + */ +export type FrozenTaskRow = Omit; + +/** Explicit key-picking — strips the two assignment fields. */ +export function toFrozenTaskRow(t: TaskRow): FrozenTaskRow { + return { + id: t.id, + boardId: t.boardId, + title: t.title, + status: t.status, + claimedBy: t.claimedBy, + claimedAt: t.claimedAt, + wish: t.wish, + group: t.group, + createdAt: t.createdAt, + updatedAt: t.updatedAt, + }; +} + export interface CreateTaskInput { title: string; boardId?: string; @@ -47,6 +75,10 @@ export interface CreateTaskInput { lane?: string; /** IDs of existing tasks this task depends on. Non-empty ⇒ starts `blocked`. */ dependsOn?: string[]; + /** Declared roster agent that works this card; requires `assignedReason` (W1 routing). */ + assignedAgent?: string; + /** Why `assignedAgent` was chosen; only valid together with `assignedAgent`. */ + assignedReason?: string; } /** @@ -240,6 +272,36 @@ export interface HireAgentInput { state?: string; } +// ============================================================================ +// Declared routing roster (cross-agent-delegate W1) +// ============================================================================ + +/** + * The allowlisted coding agents a card can be declared to. A typed in-code + * constant, NOT config (WISH Decision 2): `assigned_agent` text eventually + * reaches a shell and another agent's prompt, so every write path validates + * against this closed set. Extension is a one-line change. + */ +export const ROSTER = ['claude', 'codex', 'pi', 'hermes', 'prime'] as const; + +/** One member of the {@link ROSTER} allowlist. */ +export type RosterAgent = (typeof ROSTER)[number]; + +/** True when `agent` names a member of the roster allowlist. */ +export function isRosterAgent(agent: string): agent is RosterAgent { + return (ROSTER as readonly string[]).includes(agent); +} + +/** + * Validate an agent name against the roster allowlist, throwing + * {@link UnknownRosterAgentError} with the allowed names when it is not a + * member. The one funnel every assignment write path uses. + */ +export function requireRosterAgent(agent: string): RosterAgent { + if (!isRosterAgent(agent)) throw new UnknownRosterAgentError(agent); + return agent; +} + // ============================================================================ // Typed errors // ============================================================================ @@ -282,6 +344,37 @@ export class DuplicateBoardError extends Error { } } +/** + * An assignment write named an agent outside the {@link ROSTER} allowlist (WISH + * Decision 2). `assigned_agent` text reaches a shell and another agent's prompt + * in W2, so the closed roster is enforced at every write path and the allowed + * names ride the error so the CLI can surface them verbatim. + */ +export class UnknownRosterAgentError extends Error { + readonly agent: string; + constructor(agent: string) { + super( + `Unknown agent "${agent}" — not in the roster (${ROSTER.join(', ')}). Assignment requires an allowlisted agent.`, + ); + this.name = 'UnknownRosterAgentError'; + this.agent = agent; + } +} + +/** + * An assignment write omitted half of the required pair (WISH Decision 3: an + * assignment carries its rationale — `--agent` requires `--why`, and `--why` + * alone is equally rejected). Thrown for both a declared agent with no reason + * and a reason with no declared agent: a half-written assignment is exactly the + * invisible routing this wish exists to kill. + */ +export class AssignmentReasonRequiredError extends Error { + constructor() { + super('Assignment requires both halves: a declared agent AND the reason it was assigned (--agent requires --why).'); + this.name = 'AssignmentReasonRequiredError'; + } +} + /** An invalid lane reference or a move against a board that defines no lanes. */ export class LaneError extends Error { constructor(message: string) { @@ -412,6 +505,8 @@ interface RawTask { blocked_by: string | null; blocked_reason: string | null; block_kind: string | null; + assigned_agent: string | null; + assigned_reason: string | null; created_at: number; updated_at: number; } @@ -426,6 +521,8 @@ function mapTask(row: RawTask): TaskRow { claimedAt: row.claimed_at, wish: row.wish, group: row.group_name, + assignedAgent: row.assigned_agent, + assignedReason: row.assigned_reason, createdAt: row.created_at, updatedAt: row.updated_at, }; @@ -537,6 +634,11 @@ export function createTask(db: Database, input: CreateTaskInput): TaskRow { const now = Date.now(); const status: TaskStatus = deps.length === 0 ? 'ready' : 'blocked'; + // Assignment invariants enforced at the API boundary (WISH Decisions 2-3): + // agent allowlisted, both halves or neither. Pure validation, so it runs + // before any DB read. + const assignment = validateAssignmentPair(input.assignedAgent ?? null, input.assignedReason ?? null); + // Validate the board up front so a missing reference surfaces as a typed // UnknownBoardError rather than a raw foreign-key SqliteError from the insert. if (input.boardId != null && !getBoard(db, input.boardId)) { @@ -545,8 +647,9 @@ export function createTask(db: Database, input: CreateTaskInput): TaskRow { const insert = db.transaction(() => { db.query( - `INSERT INTO tasks (id, board_id, title, status, wish, group_name, lane, created_at, updated_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, + `INSERT INTO tasks (id, board_id, title, status, wish, group_name, lane, + assigned_agent, assigned_reason, created_at, updated_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, ).run( id, input.boardId ?? null, @@ -555,6 +658,8 @@ export function createTask(db: Database, input: CreateTaskInput): TaskRow { input.wish ?? null, input.group ?? null, input.lane ?? null, + assignment.agent, + assignment.reason, now, now, ); @@ -1040,6 +1145,103 @@ export function unblockTask(db: Database, taskId: string, author: EventAuthor): return getTask(db, taskId) as TaskRow; } +// ============================================================================ +// Declared routing (cross-agent-delegate W1) +// ============================================================================ + +/** + * Validate one assignment pair against the W1 invariants — agent allowlisted + * (WISH Decision 2) and both halves or neither (Decision 3) — returning the + * normalized pair (reason trimmed). `null`/blank on both sides is the valid + * "no assignment" state; exactly one blank half is rejected; a non-blank agent + * must be a roster member. The single funnel every assignment write path uses. + */ +function validateAssignmentPair( + agent: string | null, + reason: string | null, +): { agent: RosterAgent | null; reason: string | null } { + const agentValue = agent?.trim() || null; + const reasonValue = reason?.trim() || null; + if (agentValue == null && reasonValue == null) return { agent: null, reason: null }; + if (agentValue == null || reasonValue == null) throw new AssignmentReasonRequiredError(); + return { agent: requireRosterAgent(agentValue), reason: reasonValue }; +} + +/** + * Declare which roster agent works a card and why — the W1 routing substrate + * (assignment is declaration-only: no checkout gating, WISH Scope OUT). Works + * at any card status; only the assignment columns and `updated_at` move, and an + * `assign` event records the routing on the card timeline so the history rides + * the thread. The write and the event are one transaction, so a card can never + * carry an assignment with no matching timeline entry. + * + * Re-assigning the exact stored pair is fully silent: no row write (so + * `updated_at` keeps its earlier value) and no timeline entry — the + * set-wish/--clear precedent. + */ +export function assignTask( + db: Database, + taskId: string, + agent: string, + reason: string, + author: EventAuthor = { author: null, authorKind: null }, + now: number = Date.now(), +): TaskRow { + requireTask(db, taskId); + const pair = validateAssignmentPair(agent, reason); + if (pair.agent == null) throw new AssignmentReasonRequiredError(); + const current = getTask(db, taskId) as TaskRow; + if (current.assignedAgent === pair.agent && current.assignedReason === pair.reason) return current; + const apply = db.transaction(() => { + db.query('UPDATE tasks SET assigned_agent = ?, assigned_reason = ?, updated_at = ? WHERE id = ?').run( + pair.agent, + pair.reason, + now, + taskId, + ); + appendTaskEvent(db, taskId, { + kind: 'assign', + note: `assigned to ${pair.agent}: ${pair.reason}`, + authorKind: author.authorKind ?? undefined, + author: author.author ?? undefined, + }); + }); + apply.immediate(); + return getTask(db, taskId) as TaskRow; +} + +/** + * Remove a card's declared routing — both halves together — and append a + * `clear` event that names what was removed, so the routing history stays a + * self-contained thread. Declaration-only like {@link assignTask}: no status + * gate, and clearing an already-unassigned card is a silent no-op (the + * set-wish/--clear precedent: no row write, no timeline entry). + */ +export function clearTaskAssignment( + db: Database, + taskId: string, + author: EventAuthor = { author: null, authorKind: null }, + now: number = Date.now(), +): TaskRow { + requireTask(db, taskId); + const current = getTask(db, taskId) as TaskRow; + if (current.assignedAgent == null && current.assignedReason == null) return current; + const apply = db.transaction(() => { + db.query('UPDATE tasks SET assigned_agent = NULL, assigned_reason = NULL, updated_at = ? WHERE id = ?').run( + now, + taskId, + ); + appendTaskEvent(db, taskId, { + kind: 'clear', + note: `assignment cleared (was ${current.assignedAgent}: ${current.assignedReason})`, + authorKind: author.authorKind ?? undefined, + author: author.author ?? undefined, + }); + }); + apply.immediate(); + return getTask(db, taskId) as TaskRow; +} + /** * Record a liveness heartbeat for a claimed card — a bare `heartbeat_at` write, * NOT a timeline event (liveness is render-derived from this timestamp, never @@ -1517,22 +1719,21 @@ export function hasOperationalState(db: Database, opts: { includeHireRoster?: bo return false; } -function insertSnapshotRows(db: Database, state: StateExport): void { - const meta = db.query('INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)'); - for (const m of state.meta) meta.run(m.key, m.value); - - const board = db.query('INSERT INTO boards (id, name, lanes, created_at) VALUES (?, ?, ?, ?)'); - for (const b of state.boards) board.run(b.id, b.name, b.lanes ?? null, b.created_at); - - // Nullable-with-?? throughout: additive columns (lane, agent_kind, …) backfill - // without a user_version bump, so a same-version snapshot from an older build - // may legitimately omit them. +/** + * Insert the tasks slice of a snapshot. Column enumeration lives HERE — 18 + * columns, the widest row the snapshot carries. Nullable-with-?? throughout: + * additive columns (lane, agent_kind, …, assigned_agent/assigned_reason) + * backfill without a user_version bump, so a same-version snapshot from an + * older build may legitimately omit them. + */ +function insertTaskRows(db: Database, tasks: StateExport['tasks']): void { const task = db.query( `INSERT INTO tasks (id, board_id, title, status, claimed_by, claimed_at, wish, group_name, + assigned_agent, assigned_reason, lane, agent_kind, heartbeat_at, blocked_by, blocked_reason, block_kind, created_at, updated_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, ); - for (const t of state.tasks) { + for (const t of tasks) { task.run( t.id, t.board_id ?? null, @@ -1542,6 +1743,8 @@ function insertSnapshotRows(db: Database, state: StateExport): void { t.claimed_at ?? null, t.wish ?? null, t.group_name ?? null, + t.assigned_agent ?? null, + t.assigned_reason ?? null, t.lane ?? null, t.agent_kind ?? null, t.heartbeat_at ?? null, @@ -1552,6 +1755,16 @@ function insertSnapshotRows(db: Database, state: StateExport): void { t.updated_at, ); } +} + +function insertSnapshotRows(db: Database, state: StateExport): void { + const meta = db.query('INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)'); + for (const m of state.meta) meta.run(m.key, m.value); + + const board = db.query('INSERT INTO boards (id, name, lanes, created_at) VALUES (?, ?, ?, ?)'); + for (const b of state.boards) board.run(b.id, b.name, b.lanes ?? null, b.created_at); + + insertTaskRows(db, state.tasks); const dep = db.query('INSERT INTO task_dependencies (task_id, depends_on_id) VALUES (?, ?)'); for (const d of state.task_dependencies) dep.run(d.task_id, d.depends_on_id); diff --git a/src/term-commands/mcp.test.ts b/src/term-commands/mcp.test.ts index cab42f262..f0b9eec72 100644 --- a/src/term-commands/mcp.test.ts +++ b/src/term-commands/mcp.test.ts @@ -418,10 +418,11 @@ describe('mcp tools/call', () => { describe('mcp runtime-layer backward compatibility', () => { test('genie_task keeps the frozen TaskRow shape — no runtime/lane fields leak', async () => { const { taskId } = seed(repo); - // Add runtime state (block + claim) so a leak would actually surface if any. + // Add runtime state (block + claim) and a declared routing so a leak would + // actually surface if any. const db = openDb({ cwd: repo }); db.query( - "UPDATE tasks SET blocked_by='x', blocked_reason='r', heartbeat_at=1, agent_kind='codex', lane='Idea' WHERE id=?", + "UPDATE tasks SET blocked_by='x', blocked_reason='r', heartbeat_at=1, agent_kind='codex', lane='Idea', assigned_agent='codex', assigned_reason='routed' WHERE id=?", ).run(taskId); db.exec('PRAGMA wal_checkpoint(TRUNCATE)'); db.close(); @@ -432,7 +433,7 @@ describe('mcp runtime-layer backward compatibility', () => { { jsonrpc: '2.0', id: 40, method: 'tools/call', params: { name: 'genie_task', arguments: { id: taskId } } }, ]); const task = toolPayload>(responses.find((r) => r.id === 40)!); - // The projection is byte-frozen: exactly the pre-runtime TaskRow keys. + // The projection is byte-frozen: exactly the pre-assignment TaskRow keys. expect(Object.keys(task).sort()).toEqual([ 'boardId', 'claimedAt', @@ -445,7 +446,15 @@ describe('mcp runtime-layer backward compatibility', () => { 'updatedAt', 'wish', ]); - for (const leaked of ['lane', 'agentKind', 'heartbeatAt', 'blockedBy', 'blockedReason']) { + for (const leaked of [ + 'lane', + 'agentKind', + 'heartbeatAt', + 'blockedBy', + 'blockedReason', + 'assignedAgent', + 'assignedReason', + ]) { expect(leaked in task).toBe(false); } }); diff --git a/src/term-commands/v5-board.test.ts b/src/term-commands/v5-board.test.ts index d7d84dfdc..a29a44f0e 100644 --- a/src/term-commands/v5-board.test.ts +++ b/src/term-commands/v5-board.test.ts @@ -319,12 +319,19 @@ describe('lane-grouped render', () => { expect(payload.lanes.map((l) => l.name)).toEqual(['Idea', 'Brainstorm', 'Wish', 'Work', 'Review', 'Done']); }); - test('--json carries enforcedBlock on every lane card and nothing else from the runtime layer', async () => { + test('--json carries enforcedBlock and the declared routing on every lane card and nothing else from the runtime layer', async () => { const db = openDb({ cwd: repo }); const road = createBoard(db, 'roadmap', DEFAULT_LIFECYCLE_LANES); createTask(db, { title: 'open card', boardId: road.id, lane: 'Idea' }); const held = createTask(db, { title: 'held card', boardId: road.id, lane: 'Idea' }); const broken = createTask(db, { title: 'broken card', boardId: road.id, lane: 'Idea' }); + createTask(db, { + title: 'assigned card', + boardId: road.id, + lane: 'Idea', + assignedAgent: 'codex', + assignedReason: 'declared routing', + }); blockTask(db, held.id, 'parked until Q3', { author: 'felipe', authorKind: 'human' }, 'hold'); blockTask(db, broken.id, 'awaiting a decision', { author: 'felipe', authorKind: 'human' }); recordHeartbeat(db, held.id); // a runtime field that must NOT reach this shape @@ -342,12 +349,21 @@ describe('lane-grouped render', () => { expect(cards.get('held card')?.enforcedBlock).toEqual({ reason: 'parked until Q3', kind: 'hold' }); expect(cards.get('broken card')?.enforcedBlock).toEqual({ reason: 'awaiting a decision', kind: 'work' }); - // The lane shape gains exactly one runtime field — its provenance, identity, - // and heartbeat siblings stay off this path. + // Null semantics: every lane card carries the assignment keys; unassigned + // cards read null, assigned cards carry the declared roster agent + reason. + expect(cards.get('open card')?.assignedAgent).toBeNull(); + expect(cards.get('open card')?.assignedReason).toBeNull(); + expect(cards.get('assigned card')?.assignedAgent).toBe('codex'); + expect(cards.get('assigned card')?.assignedReason).toBe('declared routing'); + + // The lane shape carries the two declared-routing fields plus exactly one + // runtime field — provenance, identity, and heartbeat siblings stay off it. for (const leaked of ['agentKind', 'heartbeatAt', 'blockedBy', 'blockedReason']) { expect(leaked in (cards.get('held card') as Record)).toBe(false); } expect(Object.keys(cards.get('held card') as Record).sort()).toEqual([ + 'assignedAgent', + 'assignedReason', 'boardId', 'claimedAt', 'claimedBy', @@ -742,10 +758,19 @@ describe('laneless board render is unchanged', () => { expect(r.code).toBe(0); const payload = JSON.parse(r.stdout) as { columns: Record>> }; expect(Object.keys(payload.columns).sort()).toEqual(['blocked', 'done', 'in_progress', 'ready']); - // The frozen TaskRow shape never gains a `lane` key NOR any runtime field on - // the laneless path — the byte-freeze survives the runtime layer (Decision 7). + // The frozen TaskRow shape never gains a `lane` key NOR any runtime or + // declared-routing field on the laneless path — the byte-freeze survives + // the runtime layer (Decision 7) and the assignment layer (W1). const card = payload.columns.ready[0]; - for (const leaked of ['lane', 'agentKind', 'heartbeatAt', 'blockedBy', 'blockedReason']) { + for (const leaked of [ + 'lane', + 'agentKind', + 'heartbeatAt', + 'blockedBy', + 'blockedReason', + 'assignedAgent', + 'assignedReason', + ]) { expect(leaked in card).toBe(false); } // The exact frozen key set, sorted — a byte-level guard against additions. @@ -775,6 +800,11 @@ describe('laneless board render is unchanged', () => { const payload = JSON.parse(r.stdout) as { columns: Record>> }; // The block does not move the lifecycle status, so the card is still `ready`. const card = payload.columns.ready[0]; + // The two declared-routing fields must not escape onto the laneless path + // even when the row carries an enforced block (lane-only, Decision 7 + W1). + for (const leaked of ['assignedAgent', 'assignedReason', 'enforcedBlock']) { + expect(leaked in card).toBe(false); + } expect(Object.keys(card).sort()).toEqual([ 'boardId', 'claimedAt', @@ -788,6 +818,49 @@ describe('laneless board render is unchanged', () => { 'wish', ]); }); + + test('--json laneless output is byte-identical to the pre-assignment shape even for an assigned card', async () => { + const db = openDb({ cwd: repo }); + const plain = createBoard(db, 'plain'); + const assigned = createTask(db, { + title: 'assigned card', + boardId: plain.id, + assignedAgent: 'codex', + assignedReason: 'declared routing', + }); + db.close(); + + const r = await board(repo, '--board', 'plain', '--json'); + expect(r.code).toBe(0); + + // The pre-assignment byte shape, reconstructed independently of the + // serializer: exactly the TaskRow keys from before A1, in mapTask's + // insertion order, with the assignment values stripped. Any field added, + // removed, or reordered on the laneless path changes these bytes. + const expected = { + scope: 'board "plain"', + columns: { + blocked: [], + ready: [ + { + id: assigned.id, + boardId: plain.id, + title: 'assigned card', + status: 'ready', + claimedBy: null, + claimedAt: null, + wish: null, + group: null, + createdAt: assigned.createdAt, + updatedAt: assigned.updatedAt, + }, + ], + in_progress: [], + done: [], + }, + }; + expect(r.stdout).toBe(`${JSON.stringify(expected, null, 2)}\n`); + }); }); // Every visual state is asserted by substring against a fixture with injected diff --git a/src/term-commands/v5-board.ts b/src/term-commands/v5-board.ts index 08993bb9f..48db2af47 100644 --- a/src/term-commands/v5-board.ts +++ b/src/term-commands/v5-board.ts @@ -65,15 +65,39 @@ function run(handler: () => void): void { * The `--json` grouping key is the raw four-status enum — FROZEN. Byte-freeze * (WISH Decision 7): the machine shape keeps all four keys and never gains a * runtime/lane field, even though the human render below collapses to three - * columns. `groupByStatus` maps frozen {@link TaskRow}s (via {@link listTasks}), - * so the serialized shape is byte-identical to the pre-runtime board. + * columns. `groupByStatus` maps the explicit {@link toLanelessJsonCard} + * projection of each TaskRow, so the serialized shape is byte-identical to the + * pre-assignment board — `assignedAgent`/`assignedReason` stay lane-path-only. */ -function groupByStatus(tasks: TaskRow[]): Record { - const groups: Record = { blocked: [], ready: [], in_progress: [], done: [] }; +function groupByStatus(tasks: T[]): Record { + const groups: Record = { blocked: [], ready: [], in_progress: [], done: [] }; for (const t of tasks) groups[t.status].push(t); return groups; } +/** + * One card on the frozen laneless `--json` path — exactly the pre-assignment + * TaskRow key set, picked explicitly (toSummary-style) so a TaskRow field can + * never silently reach this byte-frozen shape. Only the additive lane path + * serializes the two declared-routing fields. + */ +type FrozenJsonCard = Omit; + +function toLanelessJsonCard(t: TaskRow): FrozenJsonCard { + return { + id: t.id, + boardId: t.boardId, + title: t.title, + status: t.status, + claimedBy: t.claimedBy, + claimedAt: t.claimedAt, + wish: t.wish, + group: t.group, + createdAt: t.createdAt, + updatedAt: t.updatedAt, + }; +} + /** * The HUMAN laneless render is three columns — `blocked` is a badge, never a * column (WISH Decision 1). A `blocked`-status card folds into Ready badged ⛔; @@ -263,9 +287,11 @@ function handleBoard(opts: BoardOptions): void { return; } - // `--json` FROZEN path: frozen TaskRows grouped by the four raw statuses. + // `--json` FROZEN path: pre-assignment TaskRows grouped by the four raw + // statuses. The explicit projection strips the two assignment fields A1 + // added to TaskRow — the laneless payload stays byte-identical (Decision 7). if (opts.json) { - const grouped = groupByStatus(listTasks(db, filter)); + const grouped = groupByStatus(listTasks(db, filter).map(toLanelessJsonCard)); out(JSON.stringify({ scope: scopeLabel, columns: grouped }, null, 2)); return; } @@ -318,19 +344,47 @@ function groupByLane(lanes: Lane[], tasks: T[]): Map ({ name: l.name, label: l.label ?? null, action: l.action ?? null, - cards: byLane.get(l.name) ?? [], + cards: (byLane.get(l.name) ?? []).map(toLaneJsonCard), })); out(JSON.stringify({ scope: scopeLabel, lanes: laneGroups }, null, 2)); return; diff --git a/src/term-commands/v5-task.test.ts b/src/term-commands/v5-task.test.ts index d9a925158..18e22599f 100644 --- a/src/term-commands/v5-task.test.ts +++ b/src/term-commands/v5-task.test.ts @@ -23,6 +23,7 @@ import { getTaskEvents, getTaskLane, hireAgent, + listTasks, } from '../lib/v5/task-state.js'; const GENIE = join(import.meta.dir, '..', 'genie.ts'); @@ -130,6 +131,50 @@ describe('task create', () => { expect(r.code).toBe(0); expect(r.stderr).toBe(''); }); + + test('creates a task with a declared assignment and persists both halves', async () => { + const r = await cli(repo, 'create', '--title', 'routed', '--agent', 'claude', '--why', 'owns the parser'); + expect(r.code).toBe(0); + expect(r.stderr).toBe(''); + expect(r.stdout).toMatch(/Created task t_\w+ "routed" \(ready\)\./); + const id = /Created task (t_\w+)/.exec(r.stdout)?.[1] as string; + + const db = openDb({ cwd: repo }); + const task = getTask(db, id); + db.close(); + expect(task?.assignedAgent).toBe('claude'); + expect(task?.assignedReason).toBe('owns the parser'); + + const status = await cli(repo, 'status', id); + expect(status.code).toBe(0); + expect(status.stdout).toContain('Assigned to: claude — owns the parser'); + }); + + test('rejects a non-roster agent, naming the allowed roster in stderr', async () => { + const r = await cli(repo, 'create', '--title', 'rogue', '--agent', 'kimi', '--why', 'wants in'); + expect(r.code).toBe(1); + expect(r.stdout).toBe(''); + expect(r.stderr).toContain('Unknown agent "kimi"'); + expect(r.stderr).toContain('not in the roster'); + expect(r.stderr).toContain('claude, codex, pi, hermes, prime'); + }); + + test('rejects a half-written assignment either way round (Decision 3 pair invariant)', async () => { + const agentOnly = await cli(repo, 'create', '--title', 'half', '--agent', 'claude'); + expect(agentOnly.code).toBe(1); + expect(agentOnly.stdout).toBe(''); + expect(agentOnly.stderr).toContain('Assignment requires both halves'); + + const whyOnly = await cli(repo, 'create', '--title', 'half', '--why', 'no agent'); + expect(whyOnly.code).toBe(1); + expect(whyOnly.stdout).toBe(''); + expect(whyOnly.stderr).toContain('Assignment requires both halves'); + + // Nothing was written by the rejected attempts. + const db = openDb({ cwd: repo }); + expect(listTasks(db)).toEqual([]); + db.close(); + }); }); describe('task link', () => { @@ -273,6 +318,29 @@ describe('task list', () => { expect(rows[0].title).toBe('a'); expect(rows[0].wish).toBe('demo'); }); + + test('--json stays on the frozen pre-assignment shape even for an assigned card', async () => { + await cli(repo, 'create', '--title', 'routed', '--agent', 'codex', '--why', 'dissent on parser'); + const r = await cli(repo, 'list', '--json'); + expect(r.code).toBe(0); + const rows = JSON.parse(r.stdout) as Array>; + expect(rows).toHaveLength(1); + expect(Object.keys(rows[0]).sort()).toEqual([ + 'boardId', + 'claimedAt', + 'claimedBy', + 'createdAt', + 'group', + 'id', + 'status', + 'title', + 'updatedAt', + 'wish', + ]); + for (const leaked of ['assignedAgent', 'assignedReason']) { + expect(leaked in rows[0]).toBe(false); + } + }); }); describe('task status / done / checkout', () => { @@ -514,6 +582,215 @@ describe('task set-wish', () => { }); }); +describe('task assign', () => { + async function seedTask(title: string, dependsOn?: string[]): Promise { + const db = openDb({ cwd: repo }); + const task = createTask(db, { title, dependsOn }); + db.close(); + return task.id; + } + + test('declares an assignment, appends one assign event, and shows it in status', async () => { + const id = await seedTask('route me'); + const r = await cli(repo, 'assign', id, '--agent', 'codex', '--why', 'dissent on the parser'); + expect(r.code).toBe(0); + expect(r.stderr).toBe(''); + expect(r.stdout).toBe(`Assigned task ${id} to codex: dissent on the parser.\n`); + + const db = openDb({ cwd: repo }); + const task = getTask(db, id); + const events = getTaskEvents(db, id); + db.close(); + expect(task?.assignedAgent).toBe('codex'); + expect(task?.assignedReason).toBe('dissent on the parser'); + expect(events).toHaveLength(1); + expect(events[0].kind).toBe('assign'); + expect(events[0].note).toBe('assigned to codex: dissent on the parser'); + + const status = await cli(repo, 'status', id); + expect(status.code).toBe(0); + expect(status.stdout).toContain('Assigned to: codex — dissent on the parser'); + expect(status.stdout).toContain('Timeline:'); + expect(status.stdout).toContain('assign by'); + expect(status.stdout).toContain('assigned to codex: dissent on the parser'); + }); + + test('overwrites a prior assignment, keeping both notes on the timeline', async () => { + const id = await seedTask('reassign me'); + const first = await cli(repo, 'assign', id, '--agent', 'codex', '--why', 'first opinion'); + expect(first.code).toBe(0); + + const r = await cli(repo, 'assign', id, '--agent', 'hermes', '--why', 'second opinion'); + expect(r.code).toBe(0); + expect(r.stdout).toBe(`Assigned task ${id} to hermes: second opinion.\n`); + + const db = openDb({ cwd: repo }); + const task = getTask(db, id); + const events = getTaskEvents(db, id); + db.close(); + expect(task?.assignedAgent).toBe('hermes'); + expect(task?.assignedReason).toBe('second opinion'); + expect(events.map((e) => e.kind)).toEqual(['assign', 'assign']); + expect(events.map((e) => e.note)).toEqual([ + 'assigned to codex: first opinion', + 'assigned to hermes: second opinion', + ]); + }); + + test('re-assigning the exact stored pair is a silent no-op (set-wish precedent)', async () => { + const id = await seedTask('idempotent assign'); + await cli(repo, 'assign', id, '--agent', 'pi', '--why', 'cost arbitrage'); + + const sentinelDb = openDb({ cwd: repo }); + sentinelDb.query('UPDATE tasks SET updated_at = 1234 WHERE id = ?').run(id); + const beforeEvents = JSON.stringify(getTaskEvents(sentinelDb, id)); + sentinelDb.close(); + + const r = await cli(repo, 'assign', id, '--agent', 'pi', '--why', 'cost arbitrage'); + expect(r.code).toBe(0); + expect(r.stderr).toBe(''); + + const db = openDb({ cwd: repo }); + expect(getTask(db, id)?.updatedAt).toBe(1_234); + expect(JSON.stringify(getTaskEvents(db, id))).toBe(beforeEvents); + db.close(); + }); + + test('--clear removes both halves and appends a clear event naming the prior pair', async () => { + const id = await seedTask('unroute me'); + await cli(repo, 'assign', id, '--agent', 'codex', '--why', 'dissent on parser'); + + const r = await cli(repo, 'assign', id, '--clear'); + expect(r.code).toBe(0); + expect(r.stderr).toBe(''); + expect(r.stdout).toBe(`Cleared assignment on task ${id}.\n`); + + const db = openDb({ cwd: repo }); + const task = getTask(db, id); + const events = getTaskEvents(db, id); + db.close(); + expect(task?.assignedAgent).toBeNull(); + expect(task?.assignedReason).toBeNull(); + expect(events.map((e) => e.kind)).toEqual(['assign', 'clear']); + expect(events[1].note).toBe('assignment cleared (was codex: dissent on parser)'); + + const status = await cli(repo, 'status', id); + expect(status.code).toBe(0); + expect(status.stdout).not.toContain('Assigned to:'); + expect(status.stdout).toContain('clear by'); + expect(status.stdout).toContain('assignment cleared (was codex: dissent on parser)'); + }); + + test('--clear on an already-unassigned card is a silent no-op', async () => { + const id = await seedTask('never assigned'); + const before = openDb({ cwd: repo }); + const created = getTask(before, id); + before.close(); + + const r = await cli(repo, 'assign', id, '--clear'); + expect(r.code).toBe(0); + expect(r.stderr).toBe(''); + + const db = openDb({ cwd: repo }); + const after = getTask(db, id); + const events = getTaskEvents(db, id); + db.close(); + expect(after?.assignedAgent).toBeNull(); + expect(after?.updatedAt).toBe(created?.updatedAt as number); + expect(events).toHaveLength(0); + }); + + test('--clear combined with --agent or --why is refused', async () => { + const id = await seedTask('ambiguous assign'); + const withAgent = await cli(repo, 'assign', id, '--clear', '--agent', 'claude'); + expect(withAgent.code).toBe(1); + expect(withAgent.stdout).toBe(''); + expect(withAgent.stderr).toContain('--clear cannot be combined with --agent or --why.'); + + const withWhy = await cli(repo, 'assign', id, '--clear', '--why', 'x'); + expect(withWhy.code).toBe(1); + expect(withWhy.stderr).toContain('--clear cannot be combined with --agent or --why.'); + }); + + test('works at any card status — claimed, done, and blocked (declaration only)', async () => { + const claimed = await seedTask('claimed card'); + expect((await cli(repo, 'checkout', claimed, '--worker', 'w1')).code).toBe(0); + const claimedAssign = await cli(repo, 'assign', claimed, '--agent', 'claude', '--why', 'takes over the claim'); + expect(claimedAssign.code).toBe(0); + const claimedDb = openDb({ cwd: repo }); + expect(getTask(claimedDb, claimed)?.assignedAgent).toBe('claude'); + expect(getTask(claimedDb, claimed)?.status).toBe('in_progress'); + expect(getTask(claimedDb, claimed)?.claimedBy).toBe('w1'); + claimedDb.close(); + + const done = await seedTask('done card'); + expect((await cli(repo, 'done', done)).code).toBe(0); + const doneAssign = await cli(repo, 'assign', done, '--agent', 'prime', '--why', 'verify the merge'); + expect(doneAssign.code).toBe(0); + const doneDb = openDb({ cwd: repo }); + expect(getTask(doneDb, done)?.assignedAgent).toBe('prime'); + expect(getTask(doneDb, done)?.status).toBe('done'); + doneDb.close(); + + const upstream = await seedTask('upstream blocker'); + const blocked = await seedTask('blocked card', [upstream]); + const blockedDb = openDb({ cwd: repo }); + expect(getTask(blockedDb, blocked)?.status).toBe('blocked'); + blockedDb.close(); + const blockedAssign = await cli(repo, 'assign', blocked, '--agent', 'hermes', '--why', 'own the waiting'); + expect(blockedAssign.code).toBe(0); + const blockedAfter = openDb({ cwd: repo }); + expect(getTask(blockedAfter, blocked)?.assignedAgent).toBe('hermes'); + expect(getTask(blockedAfter, blocked)?.status).toBe('blocked'); + blockedAfter.close(); + }); + + test('rejects a non-roster agent, naming the allowed roster in stderr', async () => { + const id = await seedTask('rogue assign'); + const r = await cli(repo, 'assign', id, '--agent', 'gpt6', '--why', 'wants in'); + expect(r.code).toBe(1); + expect(r.stdout).toBe(''); + expect(r.stderr).toContain('Unknown agent "gpt6"'); + expect(r.stderr).toContain('not in the roster'); + expect(r.stderr).toContain('claude, codex, pi, hermes, prime'); + + // The failed attempt wrote nothing. + const db = openDb({ cwd: repo }); + expect(getTask(db, id)?.assignedAgent).toBeNull(); + db.close(); + }); + + test('rejects --agent without --why, --why alone, and neither (Decision 3 pair invariant)', async () => { + const id = await seedTask('half assign'); + const agentOnly = await cli(repo, 'assign', id, '--agent', 'claude'); + expect(agentOnly.code).toBe(1); + expect(agentOnly.stdout).toBe(''); + expect(agentOnly.stderr).toContain('Assignment requires both halves'); + + const whyOnly = await cli(repo, 'assign', id, '--why', 'no agent'); + expect(whyOnly.code).toBe(1); + expect(whyOnly.stdout).toBe(''); + expect(whyOnly.stderr).toContain('Assignment requires both halves'); + + const neither = await cli(repo, 'assign', id); + expect(neither.code).toBe(1); + expect(neither.stdout).toBe(''); + expect(neither.stderr).toContain('Assignment requires both halves'); + + const db = openDb({ cwd: repo }); + expect(getTask(db, id)?.assignedAgent).toBeNull(); + expect(getTaskEvents(db, id)).toEqual([]); + db.close(); + }); + + test('an unknown id fails with exit 1 and a typed error', async () => { + const r = await cli(repo, 'assign', 't_nope', '--agent', 'claude', '--why', 'x'); + expect(r.code).toBe(1); + expect(r.stdout).toBe(''); + expect(r.stderr).toContain('Task not found: t_nope'); + }); +}); + describe('task delete', () => { async function seedTask(title: string, dependsOn?: string[]): Promise { const db = openDb({ cwd: repo }); diff --git a/src/term-commands/v5-task.ts b/src/term-commands/v5-task.ts index a5199a291..178c2dd58 100644 --- a/src/term-commands/v5-task.ts +++ b/src/term-commands/v5-task.ts @@ -6,11 +6,12 @@ * no runtime registry — the database is the only shared medium. * * Subcommands: - * task create --title [--board ] [--wish ] [--group ] + * task create --title [--board ] [--wish ] [--group ] [--agent --why ] * task link --wish [--group ] * task list [--status ] [--board ] [--wish ] [--json] * task status * task set-wish (--wish [--group ] | --clear) + * task assign (--agent --why | --clear) * task delete * task done * task checkout [--worker ] @@ -43,8 +44,10 @@ import { type TaskStatus, UnknownTaskError, appendTaskEvent, + assignTask, blockTask, claimTask, + clearTaskAssignment, completeTask, createTask, deleteTask, @@ -63,6 +66,7 @@ import { releaseTask, resolveBoard, setTaskWish, + toFrozenTaskRow, unblockTask, } from '../lib/v5/task-state.js'; @@ -138,6 +142,10 @@ function printDetailHeader(task: TaskCardRow): void { out(` Status: ${statusLabel(task.status)}`); if (task.boardId) out(` Board: ${task.boardId}`); if (task.wish) out(` Wish: ${task.group ? `${task.wish}#${task.group}` : task.wish}`); + if (task.assignedAgent) { + const why = task.assignedReason ? ` — ${task.assignedReason}` : ''; + out(` Assigned to: ${task.assignedAgent}${why}`); + } if (task.claimedBy) { const badge = livenessBadge(task, Date.now()); const liveness = badge ? ` ${badge}` : ''; @@ -193,6 +201,8 @@ interface CreateOptions { board?: string; wish?: string; group?: string; + agent?: string; + why?: string; } function handleCreate(opts: CreateOptions): void { @@ -204,7 +214,17 @@ function handleCreate(opts: CreateOptions): void { const db = openDb(); try { const boardId = opts.board ? resolveBoard(db, opts.board).id : undefined; - const task = createTask(db, { title, boardId, wish: opts.wish, group: opts.group }); + // The assignment pair invariant (both halves or neither) and the roster + // allowlist are enforced by the state API — the typed errors surface here + // through run() with the roster named verbatim. + const task = createTask(db, { + title, + boardId, + wish: opts.wish, + group: opts.group, + assignedAgent: opts.agent, + assignedReason: opts.why, + }); out(`Created task ${task.id} "${task.title}" (${task.status}).`); } finally { db.close(); @@ -254,7 +274,9 @@ function handleList(opts: ListOptions): void { if (opts.wish) filter.wish = opts.wish; const tasks = listTasks(db, filter); if (opts.json) { - out(JSON.stringify(tasks, null, 2)); + // Assignment serializes on the lane board `--json` path only; this + // machine-readable payload stays on the frozen pre-assignment shape. + out(JSON.stringify(tasks.map(toFrozenTaskRow), null, 2)); return; } printTaskTable(tasks); @@ -308,6 +330,41 @@ function handleSetWish(id: string, opts: SetWishOptions): void { }); } +interface AssignOptions { + agent?: string; + why?: string; + clear?: boolean; +} + +/** + * Declare which roster agent works a card and why — or `--clear` the + * declaration. Mirrors the `set-wish`/`--clear` precedent: the pair invariant + * (both halves or neither) and the roster allowlist are enforced by the state + * API, which also appends the assign/clear timeline note inside its own + * transaction, so this verb only maps flags and prints the result. + */ +function handleAssign(id: string, opts: AssignOptions): void { + const agent = opts.agent?.trim(); + const why = opts.why?.trim(); + if (opts.clear && (agent || why)) fail('--clear cannot be combined with --agent or --why.'); + + run(() => { + const db = openDb(); + try { + const task = opts.clear + ? clearTaskAssignment(db, id, resolveEventAuthor()) + : assignTask(db, id, agent ?? '', why ?? '', resolveEventAuthor()); + out( + opts.clear + ? `Cleared assignment on task ${task.id}.` + : `Assigned task ${task.id} to ${task.assignedAgent}: ${task.assignedReason}.`, + ); + } finally { + db.close(); + } + }); +} + /** * Remove a mistakenly created card outright. The verb is deliberately flagless: * a hard delete with no archive, refused while anything depends on the card, and @@ -672,6 +729,8 @@ export function registerV5TaskCommands(v5: Command): void { .option('--board ', 'Board id or name') .option('--wish ', 'Wish slug this task belongs to') .option('--group ', 'Wish-group name (requires --wish)') + .option('--agent ', 'Declared roster agent for this task (claude|codex|pi|hermes|prime; requires --why)') + .option('--why ', 'Why the declared agent was assigned (requires --agent)') .action((opts: CreateOptions) => handleCreate(opts)); task @@ -703,6 +762,14 @@ export function registerV5TaskCommands(v5: Command): void { .option('--clear', 'Remove the wish and group from the card') .action((id: string, opts: SetWishOptions) => handleSetWish(id, opts)); + task + .command('assign ') + .description('Declare which roster agent works a card and why (appends an assign event; --clear removes)') + .option('--agent ', 'Roster agent to declare (claude|codex|pi|hermes|prime; requires --why)') + .option('--why ', 'Why the agent was assigned (requires --agent)') + .option('--clear', 'Remove the assignment from the card') + .action((id: string, opts: AssignOptions) => handleAssign(id, opts)); + task .command('delete ') .description('Permanently delete a card, its edges, and its timeline (refused while other cards depend on it)')