ππΌββοΈ The blackboard for coding agents - agentic development environment for claude code, codex, cursor, opencode, grok and more.
Rust adeai-agentsclaudeclaude-codecodexcursorgeminigrokopencodespec-driven-developmentvibe-codingvim
feat: one-shot a project on an agtx board (/agtx:oneshot) (#156)
Fynn Flueggebb400ebb6cd9
diff --git a/CLAUDE.md b/CLAUDE.mdindex 46d2dd2..1c5b00c 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -129,7 +129,9 @@ web/ # The mobile PWA β plain ES modules, no build stepskills/ # Plugin skill files β auto-discovered as /agtx:* (Claude) or @agtx:* (Codex)βββ sweep/SKILL.md # Sweep skill β push any conversation to the board (/agtx:sweep)-βββ brainstorm/SKILL.md # Brainstorm skill β free-form exploration (/agtx:brainstorm)+βββ brainstorm/SKILL.md # Brainstorm skill β free-form exploration (/agtx:brainstorm)+βββ oneshot/SKILL.md # Oneshot skill β an outside session runs the board as the human,+ # all five columns, driven by wait_for_board_change (/agtx:oneshot).claude-plugin/ # Claude Code plugin manifestβββ plugin.json # Plugin metadata + MCP server registration@@ -233,6 +235,94 @@ have a worktree and no branch. Branch deletion stays paired with having had a wotask with a branch and no worktree is one that reached Done, whose branch the workflow keeps, and`delete_branch` is `git branch -D`.+#### Reaping what a task spawned++`kill-window` signals the pane's own process group, which misses anything the agent backgrounded+into a group of its own β a dev server, a watcher, a `python3 -m http.server`. Those get reparented+to init and keep holding their ports β a static server can go on serving a worktree that has been+deleted, and a later agent loads stale code from it.++`reap_task_processes` finds them **two ways, because neither alone is enough**:++- **By environment.** `create_window` sets `AGTX_TASK_ID` on the window, and a child inherits the+ environment at spawn and never loses it. This is the one that catches a daemonized process, and+ attribution is exact.+- **By descent from the pane**, as the backstop for anything that never received the environment.+ This half runs before `kill_window`, since the parent links vanish with the window.++**Descent alone is not sufficient, and ordering does not make it so.** A process reparented to init+*before* cleanup runs is already out of the tree, which is precisely the case that matters.++**The alternatives were measured and rejected.** A cwd scan (`lsof -u <uid> -d cwd`) takes ~12s;+`lsof +D <worktree>` walks the tree β 26s on a large checkout β and matches nothing once the+directory is gone, which is the state cleanup leaves. Session id is not readable per-process from+`ps` on macOS (`sess=` reports 0).++Whether `ps -Eww` exposes another process's environment varies by platform and by how the caller was+launched, so `processes_for_task` reads `/proc/<pid>/environ` where it exists and falls back to `ps`+β Linux's `ps -E` means something else entirely, so the two cannot share one command. The parsing is+split into `pids_matching_env` and tested against fixtures, because that is the half that can+regress into signalling the wrong pids.++**A root pid is refused, not reaped.** On macOS pid 0 is the ancestor of launchd, so+`descendants_of(0)` returns *every process on the machine*. A pane can never legitimately be pid 0+or 1, so a value that low means tmux answered with something that is not a pane pid, and the only+safe response is to reap nothing. `a_root_pid_is_refused_rather_than_reaped` asserts both halves β+that pid 0 really does own the whole tree, and that cleanup declines it. agtx's own pid is filtered+for the same reason: it cannot currently match, and the cost of being wrong is killing the board.++Children are signalled before parents so a supervisor cannot restart one on the way down, TERM then+KILL. `descendants_of` builds the tree from one `ps -Ao pid=,ppid=` snapshot rather than walking+`/proc`, which does not exist on macOS. The signals go through the `kill` command rather than a+`libc` dependency: this file already reaches git and tmux the same way, and it keeps the path free+of `unsafe`.++#### agtx's own files are excluded from git++`.agtx/` and the per-agent configs agtx deploys show as untracked in every worktree, and+`has_changes` β which the Done guard reads from `git status --porcelain` β counts untracked files.+Left visible, agtx's own bookkeeping would trip agtx's own guard on a project's first task, before+any `.gitignore` exists. A guard that cries wolf first and means it second stops being believed, and+a caller that works around it with a committed `.gitignore` is doing agtx's job.++`exclude_agtx_files_from_git` writes `AGTX_WRITTEN_PATHS` into the repository's exclude file at+worktree setup, once, inside a marked block.++**There is exactly one place this can go.** Measured against git 2.55.0: a per-worktree+`.git/worktrees/<name>/info/exclude` is *ignored*; only `$GIT_COMMON_DIR/info/exclude` takes effect,+and it applies to the main checkout as well as every worktree.++Sharing it with the user's own checkout is safe because **exclude patterns only affect untracked+files** β also measured, and `the_exclude_cannot_hide_a_file_the_project_tracks` pins it: a tracked+`.mcp.json` still reports its modification with `.mcp.json` excluded. So a project that deliberately+tracks any of these keeps tracking it, and nothing a user committed can be hidden. The patterns are+specific rather than whole dotdirs (`.claude/commands/agtx/`, not `.claude/`) because a project may+keep its own content there, and only what agtx creates is agtx's to hide.++This is what makes `git add -A` safe in the phase skills below.++#### The phase skills commit++`execute.md` and `review.md` end by committing. Done requires a clean tree and merging requires+commits, so a phase that ends with its work uncommitted leaves a task that cannot reach Done β and+the work sits in a worktree that Done deletes. Committing is the skill's job, not something left to+the agent's initiative or a caller's instruction.++#### A repository with no commits++A worktree must be cut from a commit, so `git init` with no history β the starting state of any+greenfield project β cannot host a task as it stands. `detect_main_branch` checks the exit status+of its `git rev-parse --abbrev-ref HEAD` fallback: on an unborn branch that fails with 128 *and+still prints the literal string* `HEAD`, which is not a revision a worktree can be cut from+(`git worktree add` answers `invalid reference: HEAD`).++When `has_no_commits` confirms the repository is genuinely empty, `create_initial_commit` makes one+(`git commit --allow-empty -m init`) and setup proceeds. Refusing would be defensible, but "run+`git commit --allow-empty` and start again" is the only answer to that refusal, and an empty commit+on a repo with no history discards nothing and conflicts with nothing. The check is what keeps this+narrow β a repository that has commits and fails for some other reason surfaces that error and never+has history written into it.+### Workflow PluginsPlugins customize the task lifecycle per phase. A plugin is a TOML file (`plugin.toml`) that defines:- **commands**: Slash commands sent to the agent at each phase (auto-translated per agent). Supports `preresearch` (one-time setup) and `research` (default research command).@@ -736,9 +826,245 @@ A dedicated Claude Code agent that autonomously manages the kanban board. Enable- On startup, if an orchestrator tmux session already exists, it is detected and reconnected; catch-up notifications are created for tasks that completed phases while the TUI was down (deduplicated via `peek_notifications`)**MCP tools**:-- Discovery: `list_projects` (global mode only)-- Read: `list_tasks`, `get_task` (includes `allowed_actions`), `get_transition_status`, `check_conflicts`, `get_notifications`, `read_pane_content`-- Write: `move_task` (queues a transition request; actions `research`, `move_forward`, `move_to_planning`, `move_to_running`, `move_to_review`, `move_to_done`, `resume`, `escalate_to_user`), `send_to_task` (Planning/Running only, 4096-byte cap)+- Discovery: `list_projects` (global mode only), `get_config` (the global and project configs+ already merged β what actually governs a run). It exists because there is no other way for a+ caller to learn `auto_trust`: the setting is global-only *by design*, since a project config that+ could grant itself trust defeats the trust system, and `AGTX_CONFIG_DIR` means the global file is+ not reliably at `~/.config/agtx/config.toml`, so reading that path directly can give a stale+ answer. The response carries both file paths, so a+ caller can name the file to edit instead of guessing+- Read: `list_tasks`, `get_task` (includes `allowed_actions`), `wait_for_board_change`, `get_transition_status`, `check_conflicts`, `get_notifications`, `read_pane_content`. `list_tasks` and `get_task` also carry `phase_status` + `phase_age_secs` + `tui_connected` β see *Publishing phase status* below. `list_tasks` returns `{tui_connected, tasks: [...]}` rather than a bare array: `tui_connected` is one answer for the whole board, and a caller needs it on *every* poll β a separate tool is one a polling loop skips, and skipping it means reading frozen rows as live state. `list_tasks` leaves descriptions out unless `include_description` is set, and omits empty optional fields β see *Waiting for the board to change*. `read_pane_content` returns a real tail (`pane_tail`): `capture-pane -S -N` starts N lines back in the scrollback and runs to the bottom of the visible screen, and a full-screen agent keeps no scrollback, so without the trim every read is the whole screen β measured, 15 lines asked, 49 returned+- Write: `move_task` (queues a transition request; actions `research`, `move_forward`, `move_to_planning`, `move_to_running`, `move_to_review`, `move_to_done`, `move_to_done_and_merge`, `resume`, `escalate_to_user`), `send_to_task` (Planning, Running and Review, 4096-byte cap; delivered as a bracketed paste plus a watched submit β see *When a phase counts as done*). Review is included (`accepts_task_input`) so a reviewer can be handed a small fix in place, with no transition made just to send a message; `resume` sends the task round a whole execute cycle and is for significant rework++#### Publishing phase status++`task_runtime` is how a process that is not the TUI learns a phase's status, and+the TUI publishes it only while someone is reading β `board_watch`, a 10-minute+window. Two readers mark it: the web server on a board request, and the MCP+server on `list_tasks` / `get_task` (throttled to 30s, since `get_task` is called+once per task in a polling loop).++**It is not gated on the `serve` feature.** A default build has no web server but+always has `agtx mcp-serve`, and an orchestrator or oneshot session polling phase status+is exactly the out-of-process reader the table is for; compiling the publish call+out would leave every such client reading a table nothing ever writes.++Read `phase_status` against `phase_age_secs`, never alone. The refresh+republishes every live task on every pass, so a small age means "seen just now"+and a large one means nothing is watching this board β which needs the opposite+response from a task that is genuinely idle.++`phase_status` is the TUI's verdict and `agent_state` is the agent's own report;+they are not duplicates. `agent_state` needs hooks and covers five of eight+agents, while `phase_status` covers all of them and is the only signal that can+say `ready` (the phase artifact exists) or `exited` (the window is gone).++**`tui_connected` is the one that says whether any of it is current.** It reads+`tui_heartbeat` through `Database::tui_is_live`, on the same 6-second window the+web API uses β three beats of `TRANSITION_POLL_INTERVAL`, so one missed tick is+not a disconnect. Without it a caller can only *infer* a dead board from+`phase_age_secs` climbing across every task at once, and until it does, a frozen+row reads as live state: a task shows `blocked` while its agent works normally,+because that was the last verdict published before the TUI exited.++#### Waiting for the board to change++A session supervising the board pays for every turn it takes, and a turn costs its whole+context, re-read. Measured on a 14-task oneshot run: 336 turns, context grown to 839k+tokens, 137M tokens of cache reads. Polling was two turns per pass β 73 `sleep` calls and+96 `list_tasks` β and those listings were the largest share of every tool result the+session re-read afterwards, 80% of their bytes task descriptions the caller had written+itself.++`wait_for_board_change` replaces the loop. It blocks **inside the server**, re-reading the+board every `WAIT_POLL_INTERVAL`, and answers once β with only the tasks that differ from+what this session was last shown by it, `list_tasks` or `get_task`. It also carries the+outcome of every `move_task` the session queued, so `get_transition_status` needs no+polling either. Timeout defaults to `DEFAULT_WAIT_SECS`, capped at `MAX_WAIT_SECS`; a+timeout is an answer, not an error.++- **What wakes it is narrower than what changed.** A task wakes the wait when it reaches a+ state that needs the caller β `ready`/`idle`/`blocked`/`exited`, Done, a startable+ Backlog task, an escalation β or appears or vanishes; also a failed transition and a+ `tui_connected` flip. `working` and an absent phase status do not: they are what a task+ looks like between the caller's move and its outcome, and waking on them costs a turn+ per transition to learn nothing. Those moves are still *reported* the next time+ something wakes. `TaskMark::needs_attention` is the rule.+- **Per session, and held in the server.** Each client spawns its own `agtx mcp-serve`+ over stdio, so `AgtxMcpServer::boards` lives exactly as long as the caller it+ describes. The pure half β `src/mcp/board_watch.rs` β has no database or clock, and+ `tests/mcp_tests.rs` drives it directly.+- **Two maps, because each misses a case the other catches.** Against what was+ *reported* alone, an agent nudged out of `idle` that works and stops again inside one+ wait looks unchanged. Against the last *poll* alone, a task that went `ready` while the+ caller was busy between two waits is already `ready` at the first poll and looks+ unchanged too.+- **`turn_ts` tells two `idle`s apart.** An agent with hooks stamps each turn boundary, so+ a nudge answered while the caller was between waits β which no poll saw as `working` β+ still reads as a new state. It is `None` while the agent reports `working`, since every+ tool call bumps that timestamp.+- **A state already reported does not wake again.** A caller that leaves a `blocked` task+ for the user would otherwise be woken for it every second.+- **It is `async`.** The sleep between polls is `tokio::time::sleep`, and each poll is a+ synchronous helper that drops the database handle and the lock before it returns, so+ nothing is held across an `await`.+- **It keeps marking the board watched.** The TUI publishes phase status only while+ someone has read it recently; a long wait is a reader for its whole length.++#### When a phase counts as done++`ready` promises a caller that the phase is finished β safe to advance, merge or+resume. Three rules keep it; without them a caller acting on `ready` would+advance a task that has done no work, resume a reviewer mid-turn, and read+`review:ready` for a review nobody has run.++- **The artifact must be written during this phase.** `Task::phase_entered_at`+ is stamped by `Database::update_task` whenever the status changes, in either+ direction, by a SQL `CASE` against the stored row β one writer, so no route+ that moves a task can forget it. `phase_artifact_fresh` counts an artifact only+ if its mtime is at or after that stamp, so the previous cycle's+ `execute.md` cannot make a resumed task read `ready` the moment it arrives.+ `phase_artifact_exists` stays for the gating callers, which ask whether a+ *prior* phase ever produced its artifact. `None` (a row from before the column)+ and glob templates fall back to existence. Research runs inside Backlog with no+ status change, so it is not stamped; agtx refuses to start research on a task+ that already has a session, which is the only way its artifact could be stale.+- **A verdict applies only to the status it was computed for.** The refresh+ snapshots tasks before its thread runs, so a transition that lands meanwhile+ leaves the verdict describing the previous phase β Running's `execute.md`+ reads as `review:ready`.+ `apply_session_refresh` drops such a verdict, and `TaskRuntime::status`+ records what each published row was computed for so MCP and the phone API can+ withhold a row that no longer matches. `phase_age_secs` cannot catch this: the+ row's timestamp is fresh; it is the phase that is wrong.+- **The agent's turn must be over.** An agent writes its artifact mid-turn and+ keeps going, so `gate_ready_on_turn` holds a fresh artifact at `working` while+ the hook reports `working` or `blocked`. There is deliberately no timestamp+ comparison: the status file holds only the latest event, and writing the+ artifact is itself a tool call whose `PreToolUse` sets `working` first, so a+ current `waiting`/`ended` must post-date the write β while hook `ts` is whole+ seconds against a sub-second mtime, so comparing them would hold a task whose+ `Stop` landed in the same second. It cannot hold one forever: a finished turn+ reports `waiting`, an exited agent leaves `ended` or a missing window, and a+ silent one's `working` record stops being trusted after `HOOK_STALE_SECS`.++`send_to_task` goes through `core::input::send_user_text` β a bracketed paste and+a watched submit β not a raw `send-keys`. Measured against Claude Code 2.1.268: a+1644-byte message typed with `send-keys` arrived as its last 622 bytes, the first+1022 silently dropped, while the same bytes as a bracketed paste arrived whole. A+raw-mode `cat` received every byte either way, so tmux and the pty are not the+cause; the agent discards the head of a large typed burst, and then acts on the+tail of an instruction with its premise gone.++#### Serialized worktree setup++Worktree setup runs one at a time β `setup_rx` is a single slot β because it does+`git worktree add`, file copies, an init script, a tmux window and an agent+spawn. Everything that starts a Backlog task goes through `setup_queue`, which+carries a `SetupIntent` alongside the task id: the dependency overlay's batch+move lets each task's plugin choose between research and planning+(`PluginDefault`), while an MCP request names one transition and must not be+answered with a different one.++A queued MCP request stays **claimed and unprocessed** β `get_transition_status`+answers `pending` β until the drain starts it. Marking it completed at enqueue+time would tell a caller the task had moved while it was still in a queue. Every+way the drain can decline one (task gone, left Backlog, deps unsatisfied, the+start itself failing) resolves the request with an error instead, because a+dropped request leaves a caller polling `pending` forever.++A busy slot never rejects a transition. `move_task` has already answered+`queued` by then, so a rejection would be visible only to a caller polling each+request, and nothing would retry the task.++**A claim outlives the instance holding it, so claims are reclaimed.** Deferring+the mark opens a window where a request is claimed and unprocessed, and+`get_pending_transition_requests` filters claimed rows out β so a TUI that exits+with a setup queued strands it, until `cleanup_old_transition_requests` deletes it+an hour later, never executed.+`Database::reclaim_stale_transition_requests` releases claims held by another+instance after `RECLAIM_CLAIMS_AFTER` (5 minutes), called at the top of each+drain rather than only at startup β a TUI that dies mid-run should not wait for+the next launch. The age window keeps a *live* second instance's genuine backlog+out of reach; reclaiming one anyway is safe rather than merely unlikely, since+the drain re-validates each task and the loser resolves its copy with an error+instead of setting the worktree up twice.++#### `move_to_done_and_merge`++Merges the task's branch into its base branch in the **project's own checkout**,+then moves it to Done. It exists for a caller that integrates locally; a person+lands the same work by merging the PR on the remote, which is why+`allowed_actions` offers it to `Orchestrator` and not to `Human` β two ways to+land one branch is worse than one.++`git::merge_task_branch` is the primitive, and it is deliberately narrow: it+merges only when the checkout is already on the base branch with no *tracked*+modifications, and returns `Refused` otherwise rather than stashing, switching+branches, or moving HEAD out from under the user. Untracked files are not part of+the gate β the project root always has some, since worktrees live under `.agtx/`+β and git refuses on its own if the merge would overwrite one.++The alternatives are worse, and were measured: `git fetch . branch:base` needs no+working tree but git refuses it while `base` is checked out, which is the normal+case here; `git update-ref` evades that check but leaves the user's index+disagreeing with HEAD, so the working tree reads as "everything deleted".++**Every route to Done must appear in the uncommitted-changes guard.** Reaching Done deletes+the worktree, and `GitOperations::has_changes` reads `git status --porcelain`, which counts+**untracked** files β an agent that wrote its work and never ran `git commit` has all of it+there and nowhere else. A route missing from the `matches!` list beside `move_to_done` and+`move_forward` merges an empty branch, reaches Done, and cleanup deletes the work; only the+`.md` artifacts survive, in `.agtx/archive/`. A new route to Done that forgets that line is+a silent data-loss bug, not a missing check, and+`every_route_to_done_refuses_a_worktree_with_uncommitted_work` iterates all three.++**An empty branch is refused rather than merged**, as the second layer. `git merge` exits+0 for a branch with no commits β "Already up to date" β so the exit status alone reports a+success that landed nothing, and the caller then deletes the worktree on the strength of+it. `commits_ahead` is checked first and `MergeOutcome::NothingToMerge` says so+explicitly; the task stays in Review and the error names where the work would be. The two+layers catch different states: the first, work that exists but is uncommitted; the second,+a branch that is genuinely empty.++**A conflict leaves the task in Review**, sets `escalation_note`, and sends+`/agtx:merge-conflicts` to the task's own agent. That ordering is the whole point+of doing both halves in one action: Done removes the worktree, and the worktree is+where the agent that wrote the branch has to resolve it. The virtual merge+(`check_merge_conflicts`) runs first so a conflict is *reported* rather than left+half-applied in the user's checkout β and `merge_branch` runs `git merge --abort`+on failure, since a stray `MERGE_HEAD` makes every later git command in the+project root report a merge in progress.++Note `fetch_and_check_conflicts` β used by the Review auto-conflict trigger β runs+`git fetch origin` first and so is inert on a local-only repo. `merge_task_branch`+uses the local `check_merge_conflicts`, which needs no remote.++#### Incremental re-review++Leaving Review for Running β the `resume` path β writes the worktree's current HEAD to+`.agtx/reviewed-at` (`mark_reviewed_point`). The review skill reads it: present, it+reviews `<marker>..HEAD` plus the prior `.agtx/review.md` and checks those points were+addressed; absent, it reviews the whole branch.++Without it every resume costs a full re-review: `clear_context_on_advance` means the+review agent starts with no memory of its own previous pass, so it would re-read the+entire branch each cycle to re-confirm what it had already approved.++A file in the worktree rather than a column on `Task`: the only reader is the skill, which+is already reading `.agtx/`, nothing queries it, and it is removed with the worktree it+describes.++**Two things about the marker's scope.** It is a commit, so it covers committed work only+β which is why the skill pairs the range with a second command for what is not committed+yet. The two can overlap, and that is the intended direction: work uncommitted when the+marker was written and committed afterwards is reviewed twice, never zero times.++And that second command is **`git status --short`, not `git diff HEAD`**: `git diff` does+not show untracked files at all. A new file from the running phase is absent from the+range diff (not committed) and absent from the working-tree diff (not tracked), so the+obvious pairing would review it in neither. `??` lines are where the newest work usually+is. `the_marker_never_covers_uncommitted_work` pins this.- CRUD (Backlog only for update/delete): `create_task`, `create_tasks_batch` (max 50, index-based `depends_on` wiring), `update_task`, `delete_task`### MCP Server Modes@@ -748,7 +1074,7 @@ Two modes, selected by whether a path argument is passed to `agtx mcp-serve`:| Mode | Command | Used by ||------|---------|---------|| **Project-scoped** | `agtx mcp-serve <path>` | Orchestrator (bound to one project) |-| **Global** | `agtx mcp-serve` | Sweep skill, any ad-hoc session |+| **Global** | `agtx mcp-serve` | Sweep and oneshot skills, any ad-hoc session |In global mode all CRUD tools (`list_tasks`, `create_task`, etc.) require a `project_id` parameter. The agent calls `list_projects` first to resolve it. In project-scoped mode `project_id` is ignored β the path is fixed at startup.@@ -1235,11 +1561,21 @@ writes one.`UserPromptSubmit`, `PreToolUse` (heartbeat) β `working`; `PermissionRequest`, `Notification` β`blocked`; `Stop`, `StopFailure` β `waiting`; `SessionEnd` β `ended`. Unregistered names areignored by the agent+- **Claude's `Notification` is scoped to `permission_prompt`**, like grok's, and for the same+ reason. Measured against Claude Code 2.1.263, the payload carries a `notification_type`:+ `permission_prompt` ("Claude needs your permission") and `idle_prompt` ("Claude is waiting for+ your input"), the latter fired ~66s after a turn simply ends. Unscoped, an agent that has simply+ finished its turn would report `Blocked` β and an agent-reported `Blocked` fires the stuck-task+ notification *immediately*, with no settle window, so a caller would interrupt an agent that is+ merely quiet. Verified that Claude honours a matcher on this event: with it, an idle turn produces no+ hook call at all. The scoping therefore lives in `hook_events`, not `map_hook_event` β the payload+ never reaches the mapper. A worktree deployed by an earlier binary keeps the unscoped+ registration until `refresh_stale_worktree_configs` re-deploys it- **`src/agent/hook_status.rs`** is pure (no tmux/DB/TUI types): event mapping, atomicwrite-then-rename, staleness, and `merge_event`'s guard preventing a late `PreToolUse` fromclearing a fresh `Blocked`-- **Precedence** in the refresh thread: artifact β `Ready` > window gone β `Exited` > hook status >- pane-hash heuristic. Only *liveness* is replaced; artifact detection is untouched+- **Precedence** in the refresh thread: fresh artifact with the turn over β `Ready` > window gone β+ `Exited` > hook status > pane-hash heuristic (see *When a phase counts as done*). Only *liveness* is replaced; artifact detection is untouched- **Purely additive**: no status file means the pre-existing 15s pane-hash heuristic runs unchanged.A `working` record older than `HOOK_STALE_SECS` (300s) is distrusted and also falls back- The pane capture is skipped only on a **fresh `Working`** report β one fewer `capture-pane` perdiff --git a/README.md b/README.mdindex ed6c270..aca93af 100644--- a/README.md+++ b/README.md@@ -24,12 +24,12 @@<a href="#features">Features</a> β’<a href="#usage">Usage</a> β’<a href="#mobile">Mobile</a> β’- <a href="#brainstorm--sweep-skills">Skills</a> β’+ <a href="#skills">Skills</a> β’+ <a href="#oneshot-skill">Oneshot</a> β’<a href="#mcp-server">MCP Server</a> β’<a href="#plugins">Plugins</a> β’<a href="#orchestrator-agent-experimental">Orchestrator</a> β’- <a href="#configuration">Configuration</a> β’- <a href="#benchmark">Benchmark</a>+ <a href="#configuration">Configuration</a></p>---@@ -62,6 +62,7 @@- **Vim-native Keybindings**: Control the board and agent sessions with your Vim-powered muscle memory.- **Mobile support**: Press `W` and scan the QR for an installable web app with the board, task details, diffs and the agent's live terminal β including a keyboard, so you can answer a permission prompt without going back to your desk. Over your wifi, or from anywhere via your tailnet. See <a href="#mobile">Mobile</a>.- **Orchestrator agent (experimental)**: A dedicated agent that autonomously manages your kanban board via MCP β delegates to coding agents, advances phases, checks for merge conflicts.+- **Oneshot skill**: Give a coding agent session a goal with `/agtx:oneshot` and it runs the whole board unattended β plans the work in milestone waves, starts tasks, unblocks the workers, judges Review, and merges each task. See <a href="#oneshot-skill">Oneshot Skill</a>.- **Brainstorm & Sweep skills**: Capture ideas and push them to the board from any coding agent session β `/agtx:brainstorm` to explore freely, `/agtx:sweep` to decompose and create tasks with one confirmation step.- **Spec-driven plugins**: Plug in [GSD](https://github.com/fynnfluegge/get-shit-done-cc), [Spec-kit](https://github.com/github/spec-kit), [OpenSpec](https://github.com/Fission-AI/OpenSpec), [BMAD](https://github.com/bmad-code-org/BMAD-METHOD), [Superpowers](https://github.com/obra/superpowers) and more β fully customizable. Ddefine your own workflow via a single TOML file. See <a href="#plugins">Plugins</a> how to create a plugin.@@ -335,14 +336,15 @@ accepted and then wait β the board says so rather than pretending. Creating,editing and deleting Backlog tasks take effect immediately, since they need noagent. Starting the server with `W` keeps the two together by construction.-## Brainstorm & Sweep Skills+## Skills-Two companion skills for capturing ideas in any coding agent session and turning them into tasks in the agtx board.+Companion skills for any coding agent session: capture ideas, turn them into tasks on the agtx board, or hand a session the whole board.| Skill | Command | When to use ||-------|---------|-------------|| **Brainstorm** | `/agtx:brainstorm` | Explore a feature idea β discussion only, no planning or implementation || **Sweep** | `/agtx:sweep` | Push conversation outcomes to the agtx board as tasks |+| **Oneshot** | `/agtx:oneshot` | Give a goal and let the session run the whole board unattended β see [Oneshot Skill](#oneshot-skill) |**Typical flow:**```@@ -357,6 +359,8 @@ The brainstorm skill keeps the agent in discussion mode β asking questions, su### Install+The Claude Code plugin brings all three skills. Oneshot runs from Claude Code; the steps for the other agents install sweep.+<details><summary><strong>Claude Code</strong></summary>@@ -466,6 +470,71 @@ Register `agtx mcp-serve` as an MCP server, then copy `skills/sweep/SKILL.md` in> [!NOTE]> The project must have been opened in agtx at least once to appear in `list_projects`. Run `agtx` in your project directory first.+## Oneshot Skill++> Give it a goal, not a task list. It runs the board until the goal is built and merged.++`/agtx:oneshot` turns a Claude Code session into the person sitting at the board. It breaks+the goal into milestones, turns the current milestone into tasks, starts them, watches the+workers, answers their questions, judges each Review, and merges the finished work into your+base branch β then plans the next wave from what was actually built. The workers write the+code; the oneshot session only writes tasks and its own state file.++### Setup++1. **Install the plugin and MCP server for Claude Code** β see [Install](#install).+2. **Let agtx answer trust prompts.** Nobody is at the board to answer an agent's trust or+ bypass-permissions dialog, so without this every task parks as blocked:+ ```toml+ # ~/.config/agtx/config.toml+ auto_trust = true+ ```+3. **Open your coding agent once in the project root** and accept its trust prompt. Task+ worktrees live inside the project, so they inherit that decision.+4. **Start from a clean base branch.** An empty repository works too β `git init -b main` is+ enough, and agtx makes the first commit.++### Run++```bash+# Terminal 1 β the board. Nothing moves without it.+cd your-project && agtx++# Terminal 2 β the session that runs the board+cd your-project && claude+> /agtx:oneshot Build a CLI todo app in Rust with SQLite storage and tests+```++Then leave it. Follow along on the board, or on your phone with `W`.++### What it does++- **Plans in waves.** A spine of 4β8 milestones first, then tasks for the current milestone+ only, with dependencies wired so a task waits for the ones it builds on. The next wave is+ planned from what the workers built.+- **Runs 3β6 tasks at once**, starting the next as its dependencies reach Review or Done.+- **Waits instead of polling.** `wait_for_board_change` blocks until a task needs attention+ and returns only what changed, so the session spends turns only when something happened.+- **Unblocks the workers.** It answers a tool's yes/no prompt, or a question its milestone+ plan already settles. Anything that would change the product goes to you under *Open+ questions* in `oneshot-state.md`, while the rest of the board keeps moving.+- **Judges Review.** A small fix goes to the reviewer in place with `send_to_task`; real+ rework sends the task back to Running.+- **Merges each task** with `move_to_done_and_merge`. On a conflict the task stays in Review+ and its own agent resolves it with `/agtx:merge-conflicts`.+- **Keeps a durable record** in `oneshot-state.md` β milestones, board, decisions and open+ questions β so a fresh session can pick up the run.++> [!IMPORTANT]+> Oneshot merges into your **local** base branch, in your own checkout. Leave that checkout+> on the base branch with no uncommitted changes to tracked files while it runs. Otherwise the+> merge is refused and nothing is touched β agtx never switches your branch or stashes your+> work. Nothing is pushed.++> [!NOTE]+> A full run takes hours and many turns of the session running the board. Start with a small+> goal to see how it works on your project.+## ConfigurationConfig file location: `~/.config/agtx/config.toml`@@ -811,13 +880,13 @@ The sandbox:## MCP Server-The agtx MCP server (`agtx mcp-serve`) exposes the board to any coding agent session via the [Model Context Protocol](https://modelcontextprotocol.io). Used by the orchestrator agent and the brainstorm & sweep skills.+The agtx MCP server (`agtx mcp-serve`) exposes the board to any coding agent session via the [Model Context Protocol](https://modelcontextprotocol.io). Used by the orchestrator agent, the oneshot skill, and the brainstorm & sweep skills.### Modes| Mode | Command | Used by ||------|---------|---------|-| **Global** | `agtx mcp-serve` | Sweep/brainstorm skills β works across all projects |+| **Global** | `agtx mcp-serve` | Brainstorm, sweep and oneshot skills β works across all projects || **Project-scoped** | `agtx mcp-serve <path>` | Orchestrator β bound to one project at startup |In global mode all tools require a `project_id` parameter. Call `list_projects` first to resolve it.@@ -827,18 +896,20 @@ In global mode all tools require a `project_id` parameter. Call `list_projects`| Tool | Description ||------|-------------|| `list_projects` | List all projects indexed in agtx |-| `list_tasks` | List tasks, optionally filtered by status |+| `get_config` | The project's effective config, global and project merged β e.g. whether `auto_trust` is on |+| `list_tasks` | List tasks with their phase status, optionally filtered by status (descriptions on request) || `get_task` | Get task details + `allowed_actions` for valid transitions |+| `wait_for_board_change` | Block until a task needs attention, then return only what changed and the outcome of queued transitions || `create_task` | Create a single backlog task || `create_tasks_batch` | Batch-create tasks with index-based dependencies || `update_task` | Modify a backlog task (title, description, deps) || `delete_task` | Delete a backlog task |-| `move_task` | Queue a phase transition |+| `move_task` | Queue a phase transition, including `move_to_done_and_merge` || `get_transition_status` | Check if a queued transition completed or errored || `check_conflicts` | Non-destructive merge conflict check against default branch || `get_notifications` | Fetch pending orchestrator notifications || `read_pane_content` | Read the last N lines of a task's tmux pane |-| `send_to_task` | Send a message to a task's agent pane |+| `send_to_task` | Send a message to a task's agent (Planning, Running or Review) |## Orchestrator Agent (Experimental)@@ -857,7 +928,7 @@ agtx --experimental # then press O- Detects stuck tasks (idle for 1+ minute without a phase artifact) and reads the agent pane to diagnose the cause- Nudges stuck agents, answers CLI prompts automatically, or escalates to you with a reason when human input is needed-**You triage. It executes.** Move tasks from Backlog into Planning or Running β the orchestrator handles the rest. Merging is your call.+**You triage. It executes.** Move tasks from Backlog into Planning or Running β the orchestrator handles the rest. Merging is your call. For a session that owns the whole board, from planning the work to merging it, see the [Oneshot Skill](#oneshot-skill).### MCP Integrationdiff --git a/plugins/agtx-terse/skills/agtx-execute/SKILL.md b/plugins/agtx-terse/skills/agtx-execute/SKILL.mdindex 6d08e2c..285d151 100644--- a/plugins/agtx-terse/skills/agtx-execute/SKILL.md+++ b/plugins/agtx-terse/skills/agtx-execute/SKILL.md@@ -24,6 +24,7 @@ mcp__agtx__get_task(task_id: "<the id passed to this command>")2. Implement the changes3. Run relevant tests to verify your changes4. Fix any issues found during testing+5. Commit. `git add -A`, commit with a short imperative message, verify `git status --short` clean. Your worktree is deleted at task completion β uncommitted work is destroyed and the merge is blocked. agtx's own files are already git-excluded, so `add -A` takes only your work.## Outputdiff --git a/plugins/agtx-terse/skills/agtx-review/SKILL.md b/plugins/agtx-terse/skills/agtx-review/SKILL.mdindex adbe2f1..cb05bc9 100644--- a/plugins/agtx-terse/skills/agtx-review/SKILL.md+++ b/plugins/agtx-terse/skills/agtx-review/SKILL.md@@ -9,7 +9,7 @@ You are in the **review phase** of an agtx-managed task.## Instructions-1. Review all changes made during execution: run `git diff HEAD` (staged+unstaged) and `git log --oneline $(git merge-base HEAD origin/HEAD)..HEAD` to see only your commits. Do NOT diff against `main` or `origin/main` β those may include unrelated upstream history.+1. Pick the scope. If `.agtx/reviewed-at` exists, a prior review covered everything up to that commit: review `git diff $(cat .agtx/reviewed-at)..HEAD` plus `git status --short` for uncommitted work, and read the prior `.agtx/review.md` β check its points were addressed, don't re-review the branch. Otherwise review all changes made during execution: `git diff HEAD` (staged+unstaged) and `git log --oneline $(git merge-base HEAD origin/HEAD)..HEAD` for your commits. Do NOT diff against `main` or `origin/main` β those may include unrelated upstream history. Either way `??` lines in `git status --short` are untracked files that `git diff` never shows β read them in full.2. Check for:- Correctness and edge cases- Error handling@@ -17,6 +17,7 @@ You are in the **review phase** of an agtx-managed task.- Test coverage- Security issues (injection, XSS, etc.)3. Fix any issues you find+4. Commit them. `git add -A`, commit, verify `git status --short` clean. Uncommitted = destroyed at task completion; merge is blocked until clean.## Outputdiff --git a/plugins/agtx/skills/execute.md b/plugins/agtx/skills/execute.mdindex 8fd6388..e862615 100644--- a/plugins/agtx/skills/execute.md+++ b/plugins/agtx/skills/execute.md@@ -24,6 +24,14 @@ mcp__agtx__get_task(task_id: "<the id passed to this command>")2. Implement the changes3. Run relevant tests to verify your changes4. Fix any issues found during testing+5. **Commit your work.** `git add -A`, then commit with a short imperative message+ describing what you built. Verify with `git status --short` that the tree is clean.++ This is not optional and not someone else's job. Your worktree is deleted when the+ task completes, so **anything you have not committed is destroyed** β a task cannot+ be merged, and the phase cannot complete, until its work is in a commit. agtx's own+ files (`.agtx/`, agent configs) are already excluded from git, so `git add -A` picks+ up your work and nothing else.## Outputdiff --git a/plugins/agtx/skills/orchestrate.md b/plugins/agtx/skills/orchestrate.mdindex 4eeeaf1..6f28f73 100644--- a/plugins/agtx/skills/orchestrate.md+++ b/plugins/agtx/skills/orchestrate.md@@ -26,7 +26,7 @@ You have access to these agtx MCP tools:- **read_pane_content(task_id, lines?)** β Read the last N lines of a task's agent pane(default 50). Use this to see what an agent is showing when a task is stuck.- **send_to_task(task_id, message)** β Send a message + Enter to a task's agent pane.- Only works for Planning or Running tasks. Use to answer CLI prompts or nudge stuck agents.+ Works for Planning, Running and Review tasks. Use to answer CLI prompts or nudge stuck agents.## How You Receive UpdatesNotifications are **pushed to you automatically** when you are idle (waiting for input).diff --git a/plugins/agtx/skills/review.md b/plugins/agtx/skills/review.mdindex 4837ee7..c0058d0 100644--- a/plugins/agtx/skills/review.md+++ b/plugins/agtx/skills/review.md@@ -9,7 +9,21 @@ You are in the **review phase** of an agtx-managed task.## Instructions-1. Review all changes made during execution: run `git diff HEAD` (staged+unstaged) and `git log --oneline $(git merge-base HEAD origin/HEAD)..HEAD` to see only your commits. Do NOT diff against `main` or `origin/main` β those may include unrelated upstream history.+1. Work out what to review. **If `.agtx/reviewed-at` exists**, a previous review already+ passed over everything up to the commit named in it, and you are looking only at what+ was done since:+ - `git diff $(cat .agtx/reviewed-at)..HEAD` β what has been committed since+ - `git status --short` β everything not yet committed. Lines starting `??` are+ **untracked files, which `git diff` does not show at all**; read those files in full,+ they are usually the newest work+ - Read the previous `.agtx/review.md` first β it says what was asked for. Your job is+ to check those points were actually addressed, not to re-litigate the whole branch.++ **Otherwise** review all changes made during execution: `git diff HEAD`+ (staged+unstaged), `git status --short` for untracked files, and+ `git log --oneline $(git merge-base HEAD origin/HEAD)..HEAD` to see only your commits.+ Do NOT diff against `main` or `origin/main` β those may include unrelated upstream+ history.2. Check for:- Correctness and edge cases- Error handling@@ -17,6 +31,9 @@ You are in the **review phase** of an agtx-managed task.- Test coverage- Security issues (injection, XSS, etc.)3. Fix any issues you find+4. **Commit anything you changed.** `git add -A`, commit, and confirm `git status --short`+ is clean. Fixes left uncommitted are destroyed when the task completes, and the task+ cannot be merged until the tree is clean.## Outputdiff --git a/skills/oneshot/SKILL.md b/skills/oneshot/SKILL.mdnew file mode 100644index 0000000..525c044--- /dev/null+++ b/skills/oneshot/SKILL.md@@ -0,0 +1,288 @@+---+name: agtx-oneshot+description: "One-shot a whole project on an agtx board: decompose the goal, run every task unattended, unblock the workers, and merge each one. Use when the user wants a long autonomous run rather than a single session."+disable-model-invocation: true+---++# agtx β One-Shotting a Project++You are **one-shotting** a project on an agtx kanban board: a goal too large for one+session, run to completion unattended.+Ordinarily a person sits at the board and does this. Here, you are that person.++This is not the built-in orchestrator (`O`), which only advances Planning β Running β+Review and refuses to touch Backlog. **You own all five columns**: you decompose the+goal into tasks, decide what starts, watch the workers, unblock them, judge Review, and+merge. The workers do the coding; you never write feature code yourself.++```+Backlog β Planning β Running β Review β Done+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^+ all of it is yours+```++## Before anything else: verify the board is live++**Nothing you do executes unless the agtx TUI is running.** `move_task` writes a row to+a queue; the TUI drains it and performs the real work β worktree creation, agent spawn,+skill deployment. With no TUI, every transition sits pending forever and the board looks+frozen for no visible reason.++1. Call `list_projects` and take the `project_id` of this project; pass it to every other+ agtx tool. If the MCP server does not answer, tell the user to register it and stop:+ ```bash+ claude mcp add --scope user agtx -- agtx mcp-serve+ ```+ If this project is not listed, it has never been opened in agtx β ask the user to run+ `agtx` in the project root, which is needed anyway (below). Then call `list_tasks`.+2. Check `tui_connected` in that response. If it is `false`, no TUI is draining the+ queue β ask the user to open `agtx` in another terminal on this project, and do not+ queue anything into a dead board.++Also confirm before a long unattended run:++- **Call `get_config` and check `auto_trust`.** It must be `true`, or agents' trust and+ bypass-permission dialogs are detected but left unanswered and every task parks as+ Blocked waiting for a human who is not there. Use the tool β do **not** read+ `~/.config/agtx/config.toml` yourself: `AGTX_CONFIG_DIR` relocates that file, so the path+ is not authoritative and you will get a stale answer. `get_config` also tells you which+ file to edit. `auto_trust` is global-only, so a project config cannot turn it on.+- **Open the coding agent once in the project root and accept its trust prompt** before+ starting. Your own session parks on that dialog in a directory the agent has not seen,+ and an unattended run has nobody to answer it.+- The project has a **base branch** and a clean tree.++## Four things that differ from a normal agtx session++**1. `allowed_actions` is not written for you.** `get_task` computes that field for the+built-in orchestrator, which is forbidden from triaging Backlog β so it comes back empty+for every Backlog task. **Ignore it.** `move_task` itself does not enforce it: `research`,+`move_to_planning`, `move_to_running`, `move_forward`, `move_to_review`, `move_to_done`+and `resume` all work from here. The only real gate is dependencies (below).++**2. No notifications reach you.** `get_notifications` only fills when the built-in+orchestrator is running. Assume it returns nothing. `wait_for_board_change` is your whole+feedback loop (see *The loop*).++**3. Read `phase_status` against `phase_age_secs`, never alone.** `list_tasks` and+`get_task` both carry the board's own verdict on each task:++| `phase_status` | Meaning |+|---|---|+| `working` | The agent is producing output. Leave it alone. |+| `ready` | The phase artifact was written this phase and the agent's turn is over β the phase is **complete**. Advance it. |+| `blocked` | The agent reported it is waiting on a human. |+| `idle` | No output for 15s. A guess, not a report. |+| `exited` | The tmux window is gone. |++**`tui_connected` decides whether any of that is current.** `list_tasks` and+`wait_for_board_change` both carry it. When it is `false`, nothing is executing transitions and+every `phase_status` is frozen at whatever was last observed β **stop and tell the user**;+do not read those rows as task state. A task can show `blocked` while its agent works+normally, purely because the TUI has exited.++`phase_age_secs` is the corroborating detail: the board republishes every live task on+every pass, so a small age means "seen just now". Check `tui_connected` first β it is the+direct answer; age is the symptom.++Two other signals, for when you need more than the verdict:++| Signal | How | Use |+|---|---|---|+| `agent_state` | `get_task`, hook-reported | `blocked_reason` names the exact prompt the agent is waiting on |+| `read_pane_content` | last N lines of the pane | Ground truth, but costs context β diagnose with it, never poll with it |++Artifact files are the fallback if `phase_status` is absent. For the default `agtx`+plugin, relative to `worktree_path`: `.agtx/research.md`, `.agtx/plan.md`,+`.agtx/execute.md`, `.agtx/review.md`. Other plugins declare their own under+`[artifacts]` in `plugins/<name>/plugin.toml`.++**4. Starting tasks is serialized, and that is fine.** Worktree setup runs one at a+time. Queue as many `move_to_planning` calls as you like in one pass β they line up and+drain in order. A start waiting for the slot has simply not resolved yet. You do not need+to poll `get_transition_status`: `wait_for_board_change` reports the outcome of every+move you queued in its `transitions` list, and wakes you if one fails. Only an `error`+means it will not happen.++## Decomposition++A goal this size cannot be enumerated up front, and trying wastes the run. Work in+**waves**.++1. Write a milestone spine first β 4β8 milestones, coarse, in `oneshot-state.md` (below).+ Nothing goes on the board yet.+2. Turn **only the current milestone** into tasks. One task = one reviewable,+ independently mergeable PR. `create_tasks_batch` takes up to 50 and wires+ dependencies by 0-based index into the same array (no forward references).+3. When a milestone is mostly in Review/Done, write the next wave β informed by what the+ workers actually built, which is the point of not planning it all on day one.++Task quality decides whether the run survives:++- **Title**: imperative, β€ 8 words, β€ 120 characters (hard cap β creation fails above it).+- **Description**: 3β6 sentences. The worker agent has **zero** context from this+ conversation. Name the files, the interfaces it must match, the constraints, and what+ "done" looks like. A vague description is the single most common cause of a task that+ burns an hour and produces nothing.+- **Dependencies are a real gate.** A Backlog task whose referenced tasks are not yet in+ Review or Done cannot be advanced at all β the move is refused. Use this deliberately+ to sequence, and don't over-wire it: a false dependency stalls a whole branch of the DAG.++```json+create_tasks_batch({+ "tasks": [+ { "title": "Add entity component store", "description": "..." },+ { "title": "Add physics step over the store", "description": "...", "depends_on": [0] },+ { "title": "Add render pass over the store", "description": "...", "depends_on": [0] }+ ]+})+```++Keep 3β6 tasks running at once. More than that and you cannot actually supervise them,+and the machine starts thrashing on parallel agent sessions.++## The loop++**Call `wait_for_board_change`, act on what it returns, and call it again.** It blocks+inside the server until something needs you, then returns only the tasks that changed+since you last looked. The first call returns the whole board.++Do not `sleep` and re-list instead. Every poll is a turn, and every turn re-reads your+entire context β so a run's cost is set by how many turns it takes far more than by what+any one call returns. A task starting to work does not wake the wait; you hear about a+task when it needs you.++Each time it returns:++1. `tui_connected: false` β the TUI is gone and every `phase_status` is frozen. Stop and+ say so rather than acting on it.+2. `transitions` β the outcome of each move you queued. An `error` is the one failure+ nothing else on the board shows; read it and act on it (see *Review and merge* for+ merge refusals and conflicts).+3. For each task in `tasks`:+ - `ready` in Planning or Running β `move_task` with `move_forward`.+ - `ready` in Review β judge it (below).+ - `blocked` β `get_task` for `blocked_reason`. A permission or trust prompt is a+ config problem (`auto_trust`), not something to answer by typing into the pane β+ surface it to the user. A question: see *Answering questions* below.+ - `idle` β `read_pane_content`, then act on what you see. For an agent without hooks+ `idle` is a guess from pane output, so confirm before nudging.+ - `exited` β the session died. `resume` it, or investigate before restarting.+ - `done` β record it; its dependents may now start.+ - Backlog with `deps_satisfied` β start it if it fits the concurrency budget β+ `move_to_planning`. Starts serialize on their own.+4. Update `oneshot-state.md`, then wait again.++`timed_out: true` means nothing needed you β wait again. It is not a reason to inspect+every task.++**Keep the board in `oneshot-state.md`, not in your head.** The wait tells you what+changed; the state file is what you apply it to. When your context has been compacted,+or you are picking up a run, call `list_tasks` once to re-sync β it leaves descriptions+out, and `get_task` has the full task when you need one. A session that has memorised a+stale board makes confident wrong moves.++### Keeping durable state++Maintain `oneshot-state.md` in the project root. It is what a fresh session reads to pick+up the run:++```markdown+# Oneshot state β <goal>+Updated: <timestamp>++## Milestones+- [x] M1 core loop+- [ ] M2 world streaming β current wave+- [ ] M3 ...++## Board+| id | title | status | notes |+|----|-------|--------|-------|+| a1b2c3 | Add entity component store | Done | merged |+| d4e5f6 | Add physics step | Running | nudged once, was idle |++## Decisions+- Physics runs fixed-step at 60Hz; renderer interpolates. (M1, task a1b2c3)++## Open questions for the user+- (none)+```++Rewrite the Board table each pass; **append** to Decisions and Open questions.+Decisions are what stop later tasks contradicting earlier ones.++## Review and merge++Review is where an unattended run quietly produces garbage, so spend your judgment here+rather than on scheduling.++1. Read the diff (`git -C <worktree_path> diff <base>...HEAD`). Ask only: does this do+ what the task said, and does it break the milestone spine? You are not doing a+ line-level code review β the Review phase agent does that.+2. **If it is wrong, decide how wrong before acting.** Small fixes go to the reviewer in+ place; `resume` is only for real rework.+ - **A small, contained change** β a wrong sentence, a missing guard, a rename, a test+ to add β send it with `send_to_task` **while the task stays in Review**. Say exactly+ what to change, and to commit and update `.agtx/review.md` when done. The reviewer+ makes it where it is: no transition, no second execute cycle. Its turn restarts, so+ `phase_status` reads `working` until it has finished; wait for `ready`, re-read the+ diff, then merge.+ - **Significant rework** β the approach is wrong, a requirement was missed, the work+ needs replanning β `resume` the task, then `send_to_task` the correction. **`resume`+ puts the task back in Running**, so when the agent is done you must `move_forward` to+ Review again before you can merge; merging straight after a resume is refused.++ Either way, act only once the agent has stopped. `ready` means that for an agent with+ hooks; for one without, read the pane first. An agent writes `review.md` and keeps+ working after it, and a message sent into a turn that has not ended lands in a busy+ pane. Vague feedback produces another wrong attempt, in either lane.+3. **Land it with `move_to_done_and_merge`.** This merges the branch into its base in the+ project checkout and then moves the task to Done. Plain `move_to_done` keeps the branch+ and merges nothing β use it only if you are integrating some other way, otherwise you+ finish the run with N parallel branches and an empty base branch.+4. **On conflict the task stays in Review** and its own agent is sent+ `/agtx:merge-conflicts` automatically, with the conflicting files named. The+ transition reports an error saying so. Do not retry immediately and do not try to+ resolve it yourself β wait for that task to go `ready` again, then call+ `move_to_done_and_merge` a second time.+5. **A refusal is about the project checkout, not the branch.** "on X, not the base+ branch" or "has uncommitted changes" means someone left the project root dirty or on+ another branch. Nothing was changed. Tell the user β you must not switch their branch+ or stash their work to get around it.+6. **`move_to_done` is refused while the *worktree* has uncommitted changes.** Different+ error, different fix: `send_to_task` telling the agent to commit, then retry. Do not+ queue it repeatedly; it will keep failing.++Merges are serialized with everything else the board does, so several tasks reaching+Done in one pass is safe.++## Answering questions++When a worker asks something, classify before acting:++- **A tool's yes/no prompt** β the uppercase letter is the default; `send_to_task` it.+- **A numbered menu with a marked default** β send that number.+- **A question about the goal that your milestone spine or Decisions already answers** β+ answer it. That is why you keep those.+- **A question that changes the shape of the product**, or a menu with no default, or a+ trust/permission prompt β **stop and ask the user.** Record it under *Open questions*+ and keep the rest of the board moving while you wait. Do not invent product decisions+ the user would want to make; a wrong answer here propagates into every later task.++If the same task goes idle twice after you nudged it, stop nudging. Escalate to the user+or delete and rewrite the task with a better description.++## Rules++- You never write feature code. You write tasks, and `oneshot-state.md`.+- Drive the run with `wait_for_board_change`, never with `sleep`. Use `list_tasks` to+ re-sync after a gap, never to poll.+- Ignore `allowed_actions`; respect dependency refusals.+- One task = one mergeable PR. Split anything with "and" in its title.+- Cap concurrency at what you can actually supervise (3β6).+- Nothing executes without the TUI. If transitions stop completing, or `phase_age_secs`+ climbs across the whole board, say so and stop.+- Never touch the user's checkout to get a merge through β no branch switch, no stash.+- Surface product decisions to the user rather than deciding them.+- Report honestly. A milestone with three failed tasks is a result; say it plainly.diff --git a/src/agent/hook_status.rs b/src/agent/hook_status.rsindex fc1d95e..8303461 100644--- a/src/agent/hook_status.rs+++ b/src/agent/hook_status.rs@@ -94,6 +94,11 @@ pub fn map_hook_event(kind: HookConfigKind, event: &str) -> Option<HookState> {// claude 2.1.247.ClaudeSettings => match event {"SessionStart" | "UserPromptSubmit" | "PreToolUse" => Some(HookState::Working),+ // `Notification` counts as Blocked only because the registration+ // pins `matcher: "permission_prompt"`; unscoped it also fires for+ // `idle_prompt`. Same arrangement as grok's, and the scoping lives+ // in [`hook_events`] rather than here because the payload never+ // reaches this function."PermissionRequest" | "Notification" => Some(HookState::Blocked),"Stop" | "StopFailure" => Some(HookState::Waiting),"SessionEnd" => Some(HookState::Ended),@@ -181,7 +186,17 @@ pub fn hook_events(kind: HookConfigKind) -> &'static [(&'static str, Option<&'st("PreToolUse", Some("*")),// Blocked: the agent is stopped waiting on a human.("PermissionRequest", Some("*")),- ("Notification", None),+ // Scoped for the same reason grok's is: `Notification` is not one+ // event. Measured against Claude Code 2.1.263, it carries a+ // `notification_type` β `permission_prompt` ("Claude needs your+ // permission") and `idle_prompt` ("Claude is waiting for your+ // input"), the latter fired ~66s after a turn simply ends.+ // Unscoped, an agent that has simply finished its turn would report+ // Blocked, and an agent-reported Blocked fires the stuck-task path+ // *immediately*, with no settle window β so a caller would interrupt+ // an agent that is merely quiet. Claude honours the matcher here+ // (verified): with it, an idle turn produces no event at all.+ ("Notification", Some("permission_prompt")),// Turn over / session over.("Stop", None),("StopFailure", None),diff --git a/src/core/actions.rs b/src/core/actions.rsindex 6330647..dfd110f 100644--- a/src/core/actions.rs+++ b/src/core/actions.rs@@ -30,10 +30,26 @@ pub const ACTIONS: &[&str] = &["move_to_running","move_to_review","move_to_done",+ "move_to_done_and_merge","resume","escalate_to_user",];+/// Whether a task's agent can be sent a message through `send_to_task`.+///+/// Planning, Running and Review all have a live agent in their window. Review is+/// included so a reviewer can be handed a small fix in place, with no board+/// transition made just to deliver a message. `resume` sends the task round a+/// whole execute cycle, and is for going back to implement more.+///+/// Backlog has no agent unless it is researching, and Done has none at all.+pub fn accepts_task_input(status: TaskStatus) -> bool {+ matches!(+ status,+ TaskStatus::Planning | TaskStatus::Running | TaskStatus::Review+ )+}+/// The longest a task title may be. Mirrors the wizard's own cap, so a task/// created from a phone cannot be one the desktop refuses to edit.pub const MAX_TASK_TITLE_CHARS: usize = 120;@@ -68,6 +84,13 @@ pub fn allowed_actions(task: &Task, deps_satisfied: bool, caller: CallerKind) ->TaskStatus::Review => {actions.push("move_to_done".to_string());actions.push("resume".to_string());+ // Integrating locally is the unattended caller's problem alone. A+ // person reaches Done through a PR merged on the remote, and+ // offering them a button that merges into their own checkout+ // instead would be a second, conflicting way to land the same work.+ if caller == CallerKind::Orchestrator {+ actions.push("move_to_done_and_merge".to_string());+ }}TaskStatus::Done => {}}diff --git a/src/db/models.rs b/src/db/models.rsindex 2421404..fd35800 100644--- a/src/db/models.rs+++ b/src/db/models.rs@@ -74,6 +74,13 @@ pub struct Task {pub referenced_tasks: Option<String>,pub escalation_note: Option<String>,pub base_branch: Option<String>,+ /// When the task last changed status. An artifact counts toward the phase it+ /// is in only if it was written after this, so a previous cycle's+ /// `execute.md` cannot make a resumed task read as done before it has run.+ /// Stamped by `Database::update_task` on any status change. `None` for a task+ /// stored before the column existed: unknown, so no freshness check applies,+ /// rather than failing every artifact that predates the upgrade.+ pub phase_entered_at: Option<DateTime<Utc>>,pub created_at: DateTime<Utc>,pub updated_at: DateTime<Utc>,}@@ -103,6 +110,7 @@ impl Task {referenced_tasks: None,escalation_note: None,base_branch: None,+ phase_entered_at: Some(now),created_at: now,updated_at: now,}@@ -344,6 +352,12 @@ impl PhaseStatus {pub struct TaskRuntime {pub task_id: String,pub phase_status: PhaseStatus,+ /// The task status this verdict was computed for. A reader must not apply+ /// it to a task that has since moved: the refresh snapshots tasks before it+ /// runs, so a pass in flight across a transition returns the *previous*+ /// phase's verdict stamped with a fresh `updated_at`. `None` for a row+ /// written before the column existed.+ pub status: Option<TaskStatus>,/// Hash of the last pane capture, and when it last changed. Carried so a/// reader can distinguish "idle because the agent is quiet" from "idle/// because nothing has refreshed this row".diff --git a/src/db/schema.rs b/src/db/schema.rsindex b32769d..28cb480 100644--- a/src/db/schema.rs+++ b/src/db/schema.rs@@ -206,6 +206,9 @@ impl Database {let _ = self.conn.execute("ALTER TABLE tasks ADD COLUMN base_branch TEXT", []);+ let _ = self+ .conn+ .execute("ALTER TABLE tasks ADD COLUMN phase_entered_at TEXT", []);// MCP transition request queueself.conn.execute_batch(@@ -239,6 +242,11 @@ impl Database {"#,)?;+ // The status each published verdict was computed for; see `TaskRuntime::status`.+ let _ = self+ .conn+ .execute("ALTER TABLE task_runtime ADD COLUMN status TEXT", []);+// Migration: add reason column to transition_requests if it doesn't existlet _ = self.conn@@ -345,8 +353,8 @@ impl Database {pub fn create_task(&self, task: &Task) -> Result<()> {self.conn.execute(r#"- INSERT INTO tasks (id, title, description, status, agent, project_id, session_name, worktree_path, branch_name, pr_number, pr_url, plugin, cycle, referenced_tasks, escalation_note, base_branch, created_at, updated_at)- VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16, ?17, ?18)+ INSERT INTO tasks (id, title, description, status, agent, project_id, session_name, worktree_path, branch_name, pr_number, pr_url, plugin, cycle, referenced_tasks, escalation_note, base_branch, created_at, updated_at, phase_entered_at)+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16, ?17, ?18, ?19)"#,params![task.id,@@ -367,6 +375,7 @@ impl Database {task.base_branch,task.created_at.to_rfc3339(),task.updated_at.to_rfc3339(),+ task.phase_entered_at.map(|t| t.to_rfc3339()),],)?;Ok(())@@ -377,8 +386,8 @@ impl Database {for task in tasks {tx.execute(r#"- INSERT INTO tasks (id, title, description, status, agent, project_id, session_name, worktree_path, branch_name, pr_number, pr_url, plugin, cycle, referenced_tasks, escalation_note, base_branch, created_at, updated_at)- VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16, ?17, ?18)+ INSERT INTO tasks (id, title, description, status, agent, project_id, session_name, worktree_path, branch_name, pr_number, pr_url, plugin, cycle, referenced_tasks, escalation_note, base_branch, created_at, updated_at, phase_entered_at)+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16, ?17, ?18, ?19)"#,params![task.id,@@ -399,6 +408,7 @@ impl Database {task.base_branch,task.created_at.to_rfc3339(),task.updated_at.to_rfc3339(),+ task.phase_entered_at.map(|t| t.to_rfc3339()),],)?;}@@ -406,6 +416,14 @@ impl Database {Ok(())}+ /// Persist `task`. A change of status also stamps `phase_entered_at`.+ ///+ /// Stamped here, in the one writer every route goes through, rather than at+ /// each call site that moves a task: a forgotten call site is a phase whose+ /// stale artifact reads as done. The comparison is in SQL, against the stored+ /// row β `status` in the `CASE` is the value *before* this update, since+ /// SQLite evaluates every `SET` expression against the old row β so the stamp+ /// needs no read first and cannot race one.pub fn update_task(&self, task: &Task) -> Result<()> {self.conn.execute(r#"@@ -424,7 +442,8 @@ impl Database {referenced_tasks = ?13,escalation_note = ?14,base_branch = ?15,- updated_at = ?16+ updated_at = ?16,+ phase_entered_at = CASE WHEN status != ?4 THEN ?17 ELSE phase_entered_at ENDWHERE id = ?1"#,params![@@ -444,6 +463,7 @@ impl Database {task.escalation_note,task.base_branch,task.updated_at.to_rfc3339(),+ chrono::Utc::now().to_rfc3339(),],)?;Ok(())@@ -474,6 +494,12 @@ impl Database {referenced_tasks: row.get("referenced_tasks").ok().flatten(),escalation_note: row.get("escalation_note").ok().flatten(),base_branch: row.get("base_branch").ok().flatten(),+ phase_entered_at: row+ .get::<_, Option<String>>("phase_entered_at")+ .ok()+ .flatten()+ .and_then(|s| chrono::DateTime::parse_from_rfc3339(&s).ok())+ .map(|dt| dt.with_timezone(&chrono::Utc)),created_at: chrono::DateTime::parse_from_rfc3339(&row.get::<_, String>("created_at")?).map(|dt| dt.with_timezone(&chrono::Utc)).unwrap_or_else(|_| chrono::Utc::now()),@@ -672,6 +698,42 @@ impl Database {Ok(rows == 1)}+ /// Release claims left behind by a TUI that is no longer running, so the+ /// next one re-drains them.+ ///+ /// A claim is taken the moment a request is picked up, but a Backlog+ /// transition is only *marked* once the serialized setup slot frees up and+ /// it actually starts. Between those two points the request is claimed and+ /// unprocessed, and [`get_pending_transition_requests`] filters claimed rows+ /// out β so a TUI that exits while a setup is queued strands it. Nothing+ /// re-runs it; `cleanup_old_transition_requests` eventually deletes it, an+ /// hour later, having never executed the transition the caller asked for.+ ///+ /// Rows claimed by `this_instance` are left alone: this instance's own+ /// in-memory queue still owns them.+ ///+ /// `older_than` keeps a *live* second instance's genuine backlog out of+ /// reach. Reclaiming one anyway is safe rather than merely unlikely β the+ /// drain re-validates each task before starting it, so the loser of the race+ /// resolves its copy with an error instead of setting the worktree up twice.+ pub fn reclaim_stale_transition_requests(+ &self,+ this_instance: &str,+ older_than: chrono::Duration,+ ) -> Result<usize> {+ let cutoff = (chrono::Utc::now() - older_than).to_rfc3339();+ let rows = self.conn.execute(+ "UPDATE transition_requests+ SET claimed_by = NULL+ WHERE processed_at IS NULL+ AND claimed_by IS NOT NULL+ AND claimed_by != ?1+ AND requested_at < ?2",+ params![this_instance, cutoff],+ )?;+ Ok(rows)+ }+pub fn cleanup_old_transition_requests(&self) -> Result<()> {let cutoff = (chrono::Utc::now() - chrono::Duration::hours(1)).to_rfc3339();self.conn.execute(@@ -998,10 +1060,11 @@ impl Database {for rt in rows {tx.execute("INSERT INTO task_runtime- (task_id, phase_status, pane_hash, pane_changed_at, updated_at)- VALUES (?1, ?2, ?3, ?4, ?5)+ (task_id, phase_status, pane_hash, pane_changed_at, updated_at, status)+ VALUES (?1, ?2, ?3, ?4, ?5, ?6)ON CONFLICT(task_id) DO UPDATE SETphase_status = excluded.phase_status,+ status = excluded.status,pane_hash = excluded.pane_hash,pane_changed_at = excluded.pane_changed_at,updated_at = excluded.updated_at",@@ -1011,6 +1074,7 @@ impl Database {rt.pane_hash,rt.pane_changed_at.map(|t| t.to_rfc3339()),rt.updated_at.to_rfc3339(),+ rt.status.map(|s| s.as_str()),],)?;}@@ -1055,6 +1119,11 @@ impl Database {// the honest fallback: it is the state that claims the least.phase_status: PhaseStatus::from_str(&row.get::<_, String>("phase_status")?).unwrap_or(PhaseStatus::Working),+ status: row+ .get::<_, Option<String>>("status")+ .ok()+ .flatten()+ .and_then(|s| TaskStatus::from_str(&s)),pane_hash: row.get("pane_hash")?,pane_changed_at: row.get::<_, Option<String>>("pane_changed_at")?diff --git a/src/git/mod.rs b/src/git/mod.rsindex ceaaaae..9b301b7 100644--- a/src/git/mod.rs+++ b/src/git/mod.rs@@ -49,6 +49,43 @@ pub fn current_branch(path: &Path) -> Result<String> {Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())}+/// How many commits `branch` has that `base` does not.+pub fn commits_ahead(path: &Path, base: &str, branch: &str) -> Result<usize> {+ let output = Command::new("git")+ .current_dir(path)+ .args(["rev-list", "--count", &format!("{base}..{branch}")])+ .output()+ .context("Failed to count commits ahead of the base branch")?;++ if !output.status.success() {+ anyhow::bail!(+ "Failed to compare '{branch}' with '{base}': {}",+ String::from_utf8_lossy(&output.stderr).trim()+ );+ }+ Ok(String::from_utf8_lossy(&output.stdout)+ .trim()+ .parse()+ .unwrap_or(0))+}++/// The commit HEAD currently points at, as a full SHA.+pub fn head_sha(path: &Path) -> Result<String> {+ let output = Command::new("git")+ .current_dir(path)+ .args(["rev-parse", "HEAD"])+ .output()+ .context("Failed to read HEAD")?;++ if !output.status.success() {+ anyhow::bail!(+ "Failed to read HEAD: {}",+ String::from_utf8_lossy(&output.stderr).trim()+ );+ }+ Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())+}+/// Whether `rev` resolves to a commit in the repository at `path`.////// Needed because [`diff_stat`] and [`diff_full`] only fail when git cannot be@@ -101,12 +138,119 @@ pub fn merge_branch(path: &Path, branch: &str, message: &str) -> Result<()> {.context("Failed to merge branch")?;if !output.status.success() {+ // A conflicted merge leaves MERGE_HEAD and a half-written index behind.+ // Leaving that for the user to find is how a failed automatic merge+ // turns into a repository nobody can explain β every later git command+ // in the project root reports a merge in progress.+ let _ = Command::new("git")+ .current_dir(path)+ .args(["merge", "--abort"])+ .output();anyhow::bail!("Merge failed: {}", String::from_utf8_lossy(&output.stderr));}Ok(())}+/// What happened when a task branch was merged into its base.+#[derive(Debug, Clone, PartialEq, Eq)]+pub enum MergeOutcome {+ /// The merge commit was made.+ Merged,+ /// The branch has no commits the base does not already have, so there is+ /// nothing to land.+ ///+ /// Distinguished from [`Merged`](Self::Merged) because `git merge` reports+ /// success for this case β "Already up to date", exit 0 β and a caller that+ /// believes it would conclude the work is safely on the base branch. It is+ /// not: the usual cause is an agent that wrote files and never committed+ /// them, so the work exists only in the worktree's working directory, which+ /// is about to be deleted.+ NothingToMerge,+ /// The branches conflict. Nothing was changed; the files are the ones the+ /// virtual merge reported.+ Conflicts(Vec<String>),+ /// The merge was not attempted, because the working tree is not in a state+ /// where merging into it would be safe. Carries the reason, for a user.+ Refused(String),+}++/// Merge a task branch into `base` in the project's own working tree.+///+/// Merging needs a working tree, and the project root is the only one that+/// belongs to `base`. That makes this the one agtx operation that writes to the+/// user's own checkout, so it is deliberately narrow: it merges when the+/// checkout is *already* on `base` with no tracked modifications, and refuses+/// otherwise rather than stashing, switching branches, or moving HEAD out from+/// under whatever the user is doing.+///+/// The alternatives were considered and are worse. `git fetch . branch:base`+/// needs no working tree but git refuses it while `base` is checked out, which+/// is the normal case here. `git update-ref` evades that check but leaves the+/// user's index disagreeing with HEAD β the working tree silently reads as+/// "everything deleted". A detached integration worktree merges cleanly but+/// then faces the same problem moving `base` to the result.+///+/// Untracked files are not part of the gate: they do not block a merge, and the+/// project root always has some (worktrees live under `.agtx/`). git refuses on+/// its own if the merge would overwrite one, and that arrives as `Refused`.+pub fn merge_task_branch(+ project_path: &Path,+ base: &str,+ branch: &str,+ message: &str,+) -> Result<MergeOutcome> {+ let current = current_branch(project_path)?;+ if current != base {+ return Ok(MergeOutcome::Refused(format!(+ "project checkout is on '{current}', not the base branch '{base}'"+ )));+ }++ let dirty = Command::new("git")+ .current_dir(project_path)+ .args(["status", "--porcelain", "--untracked-files=no"])+ .output()+ .context("Failed to check the project working tree")?;+ if !dirty.stdout.is_empty() {+ return Ok(MergeOutcome::Refused(format!(+ "project checkout has uncommitted changes on '{base}'"+ )));+ }++ // A branch with nothing on it is not a merge, whatever git's exit status+ // says. Reported rather than performed, because the caller's next step is+ // to delete the worktree and an empty branch means the work β if there is+ // any β is still sitting in it uncommitted.+ if commits_ahead(project_path, base, branch)? == 0 {+ return Ok(MergeOutcome::NothingToMerge);+ }++ // Ask before acting: `git merge` on a conflict leaves the working tree mid-+ // merge, and this is the user's checkout. The virtual merge touches nothing+ // and names the files, which is what the agent needs to resolve them.+ let (conflicts, files) = check_merge_conflicts(project_path, base, branch)?;+ if conflicts {+ return Ok(MergeOutcome::Conflicts(files));+ }++ // The check above is not a guarantee β the branch can move between the two+ // commands β so a merge that fails anyway is aborted and reported as a+ // conflict rather than trusted to have left nothing behind.+ match merge_branch(project_path, branch, message) {+ Ok(()) => Ok(MergeOutcome::Merged),+ Err(e) => {+ let (conflicts, files) = check_merge_conflicts(project_path, base, branch)+ .unwrap_or((false, Vec::new()));+ if conflicts {+ Ok(MergeOutcome::Conflicts(files))+ } else {+ Ok(MergeOutcome::Refused(e.to_string()))+ }+ }+ }+}+/// Check if merging a branch into the base branch would produce conflicts./// Uses `git merge-tree --write-tree` (Git 2.38+) for a non-destructive check./// Returns Ok((has_conflicts, conflicting_files)).diff --git a/src/git/worktree.rs b/src/git/worktree.rsindex bfadd07..ad05325 100644--- a/src/git/worktree.rs+++ b/src/git/worktree.rs@@ -314,13 +314,91 @@ pub fn detect_main_branch(project_path: &Path) -> Result<String> {return Ok("master".to_string());}- // Fallback: get the current branch+ // Fallback: get the current branch.+ //+ // The exit status matters here and reading stdout alone is not enough. On an+ // unborn branch β a fresh `git init` with no commits, which is exactly how a+ // greenfield project starts β this fails with 128 *and still prints the+ // literal string* `HEAD`, which is not a revision a worktree can be cut from+ // (`git worktree add` answers `invalid reference: HEAD`).let output = Command::new("git").current_dir(project_path).args(["rev-parse", "--abbrev-ref", "HEAD"]).output().context("Failed to get current branch")?;+ if !output.status.success() {+ // Distinguish "no commits yet" from any other failure before acting: the+ // recovery below writes to the user's repository, and it is only+ // unambiguously safe on a repo that has no history to disturb.+ if has_no_commits(project_path) {+ create_initial_commit(project_path)?;+ return current_branch_name(project_path);+ }+ anyhow::bail!(+ "Could not determine the base branch: {}",+ String::from_utf8_lossy(&output.stderr).trim()+ );+ }++ Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())+}++/// Whether the repository has no commits at all (HEAD is unborn).+fn has_no_commits(project_path: &Path) -> bool {+ Command::new("git")+ .current_dir(project_path)+ .args(["rev-parse", "--verify", "HEAD"])+ .output()+ .map(|o| !o.status.success())+ .unwrap_or(false)+}++/// Give an empty repository the one commit a worktree needs to branch from.+///+/// A worktree must be cut from a commit, so a repository with no history cannot+/// host a task at all. Refusing would be defensible, but "run `git commit+/// --allow-empty` and start again" is the only answer to that refusal, and+/// making the user type it buys nothing: an empty commit on a repo with no+/// history discards nothing and conflicts with nothing.+///+/// Deliberately narrow. This runs only when [`has_no_commits`] holds, so it can+/// never rewrite, amend or displace work that already exists.+fn create_initial_commit(project_path: &Path) -> Result<()> {+ tracing::info!(+ project = %project_path.display(),+ "Repository has no commits; creating an empty initial commit so a worktree can be cut"+ );+ let output = Command::new("git")+ .current_dir(project_path)+ .args(["commit", "--allow-empty", "-m", "init"])+ .output()+ .context("Failed to create the initial commit")?;++ if !output.status.success() {+ anyhow::bail!(+ "Repository has no commits and one could not be created: {}. \+ Make a commit first, then retry.",+ String::from_utf8_lossy(&output.stderr).trim()+ );+ }+ Ok(())+}++/// The current branch name, after HEAD is known to exist.+fn current_branch_name(project_path: &Path) -> Result<String> {+ let output = Command::new("git")+ .current_dir(project_path)+ .args(["rev-parse", "--abbrev-ref", "HEAD"])+ .output()+ .context("Failed to get current branch")?;++ if !output.status.success() {+ anyhow::bail!(+ "Could not determine the current branch: {}",+ String::from_utf8_lossy(&output.stderr).trim()+ );+ }Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())}diff --git a/src/mcp/board_watch.rs b/src/mcp/board_watch.rsnew file mode 100644index 0000000..bc415c8--- /dev/null+++ b/src/mcp/board_watch.rs@@ -0,0 +1,197 @@+//! "What changed since I last looked" β the state behind `wait_for_board_change`.+//!+//! A caller supervising the board unattended pays for every turn it takes, and+//! the price of a turn is its whole context, re-read. Polling is two turns per+//! pass β a sleep, then a full listing β and most passes find nothing to do.+//! Measured on a 14-task run: 73 sleeps and 96 listings, with the listings alone+//! the largest share of every tool result the session re-read afterwards.+//!+//! So the wait blocks inside the server and answers once, when something needs+//! the caller, with only the tasks that differ from what it was last shown.+//!+//! Pure: no database, no tmux, no clock. The server feeds it one [`TaskMark`]+//! per task per poll.++use std::collections::{HashMap, HashSet};++use crate::db::TaskStatus;++/// The parts of a task a caller acts on. Two equal marks mean "nothing for the+/// caller here", so what goes in decides what can wake it.+///+/// `phase_age_secs` is deliberately absent: it changes on every refresh, and a+/// mark that always differs wakes nothing but reports everything.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct TaskMark {+ pub status: TaskStatus,+ /// The TUI's verdict, already withheld when it describes a previous status.+ pub phase_status: Option<String>,+ /// When the agent's hook last reported a turn boundary β `waiting`,+ /// `ended` or `blocked` β and `None` while it reports `working`.+ ///+ /// This is what tells two `idle`s apart. A caller nudges an idle agent, the+ /// agent works and stops again, and the board reads `idle` before and after:+ /// equal marks, and a caller that is never told its nudge was answered. The+ /// second `Stop` carries a new timestamp. `None` while working keeps a busy+ /// agent's heartbeat out of the mark, since every tool call bumps it.+ pub turn_ts: Option<i64>,+ pub deps_satisfied: bool,+ pub escalation_note: Option<String>,+}++impl TaskMark {+ /// Whether a task in this state is waiting on the caller.+ ///+ /// `working` and an absent status are not: they are what a task looks like+ /// between the caller's move and the outcome of it, and waking on them costs+ /// a turn per transition to learn nothing. A status change alone is not+ /// either β the caller asked for it β except into Done, which is where a+ /// merge landed and dependents may have come free.+ pub fn needs_attention(&self) -> bool {+ if self.escalation_note.is_some() {+ return true;+ }+ match self.status {+ TaskStatus::Done => true,+ // A research session runs in Backlog, so it has a phase of its own;+ // otherwise a Backlog task wants the caller once it can be started.+ TaskStatus::Backlog => self.deps_satisfied || self.phase_needs_attention(),+ TaskStatus::Planning | TaskStatus::Running | TaskStatus::Review => {+ self.phase_needs_attention()+ }+ }+ }++ fn phase_needs_attention(&self) -> bool {+ matches!(+ self.phase_status.as_deref(),+ Some("ready" | "idle" | "blocked" | "exited")+ )+ }+}++/// What one caller has been shown of one board.+///+/// Two maps, because "changed since the caller last saw it" and "changed since+/// the last poll" are different questions, and each misses a case the other+/// catches. Against `reported` alone, an agent nudged out of `idle` that works+/// and goes idle again inside one wait looks unchanged. Against `observed`+/// alone, a task that went `ready` while the caller was busy between two waits+/// is already `ready` at the first poll and looks unchanged too.+#[derive(Debug, Default)]+pub struct BoardView {+ /// The mark each task had when the caller was last shown it.+ reported: HashMap<String, TaskMark>,+ /// The mark each task had at the last poll.+ observed: HashMap<String, TaskMark>,+ /// Tasks that woke a wait while matching `reported` β see [`Self::poll`].+ woken: HashSet<String>,+ /// What the caller was last told about the TUI. `None` until it has been+ /// told anything, which is not a change to wake for.+ tui_connected: Option<bool>,+}++/// The answer to a wait: which tasks to show the caller.+#[derive(Debug, Default, PartialEq, Eq)]+pub struct BoardDiff {+ /// Tasks whose mark differs from what the caller was last shown, or that+ /// woke this wait. In board order.+ pub changed: Vec<String>,+ /// Tasks the caller was shown that no longer exist.+ pub removed: Vec<String>,+}++impl BoardView {+ /// Record that the caller was just shown these tasks β by `list_tasks` or+ /// `get_task` β so a wait does not wake to repeat them.+ ///+ /// A partial listing (one status, one task) records only what it showed;+ /// the rest of the board stays unseen, as it is. A task never shown wakes+ /// the next wait at once, which is also what makes a caller's first wait a+ /// baseline of the whole board.+ pub fn mark_seen<'a>(+ &mut self,+ tasks: impl IntoIterator<Item = (&'a str, &'a TaskMark)>,+ tui_connected: bool,+ ) {+ for (id, mark) in tasks {+ self.reported.insert(id.to_string(), mark.clone());+ self.observed.insert(id.to_string(), mark.clone());+ self.woken.remove(id);+ }+ self.tui_connected = Some(tui_connected);+ }++ /// One poll of the whole board. True when the caller should be woken.+ ///+ /// Wakes when a task is in a state that needs the caller *and* the caller+ /// has not seen it there β either it differs from what was reported, or it+ /// moved since the last poll. The second half is what catches a return to+ /// the same state; such a task matches `reported`, so it is remembered in+ /// `woken` to be included in the answer regardless.+ ///+ /// A task already reported in a state that needs attention does not wake+ /// again while it stays there. A caller that chooses to leave a `blocked`+ /// task alone must not be woken for it on every poll.+ pub fn poll(&mut self, board: &[(String, TaskMark)], tui_connected: bool) -> bool {+ let mut wake = false;+ if self.tui_connected.is_some_and(|t| t != tui_connected) {+ wake = true;+ }+ for (id, mark) in board {+ let unseen = self.reported.get(id) != Some(mark);+ let moved = self.observed.get(id) != Some(mark);+ if mark.needs_attention() && (unseen || moved) {+ wake = true;+ if !unseen {+ self.woken.insert(id.clone());+ }+ }+ // A task the caller has never been shown is news in any state.+ if !self.reported.contains_key(id) {+ wake = true;+ }+ self.observed.insert(id.clone(), mark.clone());+ }+ let present: HashSet<&str> = board.iter().map(|(id, _)| id.as_str()).collect();+ if self+ .reported+ .keys()+ .any(|id| !present.contains(id.as_str()))+ {+ wake = true;+ }+ self.observed.retain(|id, _| present.contains(id.as_str()));+ wake+ }++ /// What to show the caller now, and record that it has been shown.+ ///+ /// Called when a wait answers, whether it woke or timed out: a timeout+ /// still reports the moves into non-actionable states it accumulated, so+ /// the next wait starts from what the caller actually knows.+ pub fn report(&mut self, board: &[(String, TaskMark)], tui_connected: bool) -> BoardDiff {+ let present: HashSet<&str> = board.iter().map(|(id, _)| id.as_str()).collect();+ let mut removed: Vec<String> = self+ .reported+ .keys()+ .filter(|id| !present.contains(id.as_str()))+ .cloned()+ .collect();+ removed.sort();+ for id in &removed {+ self.reported.remove(id);+ }++ let mut changed = Vec::new();+ for (id, mark) in board {+ if self.reported.get(id) != Some(mark) || self.woken.contains(id) {+ changed.push(id.clone());+ self.reported.insert(id.clone(), mark.clone());+ }+ }+ self.woken.clear();+ self.tui_connected = Some(tui_connected);+ BoardDiff { changed, removed }+ }+}diff --git a/src/mcp/mod.rs b/src/mcp/mod.rsindex 90df880..919cebf 100644--- a/src/mcp/mod.rs+++ b/src/mcp/mod.rs@@ -1,3 +1,4 @@+pub mod board_watch;mod prehandshake;mod server;diff --git a/src/mcp/server.rs b/src/mcp/server.rsindex 8ecb809..29725b1 100644--- a/src/mcp/server.rs+++ b/src/mcp/server.rs@@ -1,5 +1,8 @@+use std::collections::HashMap;use std::path::PathBuf;use std::process::Command;+use std::sync::{Arc, Mutex};+use std::time::{Duration, Instant};use rmcp::{handler::server::{router::tool::ToolRouter, wrapper::Parameters},@@ -8,6 +11,8 @@ use rmcp::{};use serde::{Deserialize, Serialize};+use super::board_watch::{BoardView, TaskMark};+use crate::agent::hook_status::{AgentHookStatus, HookState};use crate::config::{GlobalConfig, ProjectConfig};use crate::core::actions::CallerKind;use crate::db::{Database, Task, TaskStatus, TransitionRequest};@@ -27,11 +32,40 @@ pub enum ServerMode {#[derive(Debug, Deserialize, schemars::JsonSchema)]pub struct ListProjectsParams {}+#[derive(Debug, Deserialize, schemars::JsonSchema)]+pub struct GetConfigParams {+ /// Project ID (required in global mode β call list_projects first to get IDs).+ #[schemars(+ description = "Project ID. Required in global mode. Call list_projects first to get project IDs."+ )]+ pub project_id: Option<String>,+}+#[derive(Debug, Deserialize, schemars::JsonSchema)]pub struct ListTasksParams {/// Filter by status: "backlog", "planning", "running", "review", "done". Omit for all tasks.#[schemars(description = "Filter by status: backlog, planning, running, review, done")]pub status: Option<String>,+ /// Include each task's description. Off by default: a description is most+ /// of a listing's bytes and a polling caller wrote them itself.+ #[schemars(+ description = "Include each task's full description (default false). get_task always includes it."+ )]+ pub include_description: Option<bool>,+ /// Project ID (required in global mode β call list_projects first to get IDs).+ #[schemars(+ description = "Project ID. Required in global mode. Call list_projects first to get project IDs."+ )]+ pub project_id: Option<String>,+}++#[derive(Debug, Deserialize, schemars::JsonSchema)]+pub struct WaitForBoardChangeParams {+ /// How long to wait for something to need you before answering anyway.+ #[schemars(+ description = "Seconds to wait before answering anyway (default 300, max 900). A timeout is not an error: it means nothing needed you."+ )]+ pub timeout_secs: Option<u64>,/// Project ID (required in global mode β call list_projects first to get IDs).#[schemars(description = "Project ID. Required in global mode. Call list_projects first to get project IDs."@@ -253,21 +287,165 @@ struct ProjectSummary {path: String,}+/// One card, as a polling caller sees it.+///+/// Every optional field is omitted when empty, and the description only on+/// request: this is the response a supervising session receives most, and it+/// re-reads each one on every later turn. Measured on a 14-task run,+/// descriptions were 80% of a listing's bytes β text the caller wrote itself+/// when it created the tasks.#[derive(Serialize)]struct TaskSummary {id: String,title: String,+ #[serde(skip_serializing_if = "Option::is_none")]description: Option<String>,status: String,agent: String,+ #[serde(skip_serializing_if = "Option::is_none")]branch_name: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]pr_url: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]plugin: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]referenced_tasks: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]base_branch: Option<String>,+ /// Why the task was flagged for a person β a merge conflict, an+ /// escalation. Present only when set.+ #[serde(skip_serializing_if = "Option::is_none")]+ escalation_note: Option<String>,deps_satisfied: bool,+ /// The TUI's published phase status, or `None` when nothing has been+ /// observed for this task. Weigh it against `phase_age_secs` rather than+ /// treating it as live β with no TUI running, nothing refreshes it.+ #[serde(skip_serializing_if = "Option::is_none")]+ phase_status: Option<String>,+ /// How many seconds ago that status was observed. The refresh republishes+ /// every live task on every pass, so a small age means "seen just now" and+ /// a large one means nothing is watching this board β which is a different+ /// problem from a task that is genuinely idle.+ #[serde(skip_serializing_if = "Option::is_none")]+ phase_age_secs: Option<i64>,}+/// The settings that decide how a run behaves, already merged.+///+/// Only the fields a caller acts on. The theme is not here β nothing driving+/// the board makes a decision from it β and neither is anything secret.+#[derive(Serialize)]+struct EffectiveConfig {+ /// Where these values came from, so a caller can say *which* file to edit+ /// rather than guess at `~/.config/agtx/config.toml`.+ global_config_path: String,+ project_config_path: String,+ project_config_exists: bool,+ /// Whether agtx answers agents' trust and bypass-permission dialogs. When+ /// false, an unattended run parks every task as `blocked` on its first+ /// dialog with nobody to answer it. Global-only: a project config cannot+ /// set this, because a repository must not be able to grant itself trust.+ auto_trust: bool,+ default_agent: String,+ /// Per-phase overrides. A phase absent here uses `default_agent`.+ phase_agents: serde_json::Value,+ worktree_enabled: bool,+ skip_worktree: bool,+ auto_cleanup: bool,+ /// Empty means auto-detect (main, then master).+ base_branch: String,+ worktree_dir: String,+ branch_prefix: String,+ workflow_plugin: Option<String>,+ agent_hooks: bool,+ github_url: Option<String>,+}++/// The board, plus the one fact that says whether any of it is live.+///+/// `tui_connected` belongs at board level rather than on each card: it is one+/// answer for the whole project, and repeating it per task would imply it could+/// differ between them. It is wrapped around the task list rather than offered+/// as a separate tool because a caller needs it on *every* poll β a separate+/// call is one a polling loop will skip, and skipping it means reading frozen+/// rows as live state.+#[derive(Serialize)]+struct BoardListing {+ /// Whether a TUI has beaten recently. When false, nothing is executing+ /// queued transitions and every `phase_status` below is frozen at whatever+ /// was last observed β stale, not current.+ tui_connected: bool,+ tasks: Vec<TaskSummary>,+}++/// The answer to `wait_for_board_change`: only what differs from what this+/// session was last shown.+#[derive(Serialize)]+struct BoardChanges {+ tui_connected: bool,+ /// True when the wait ran out with nothing needing the caller. `tasks` can+ /// still be non-empty β moves into states that ask nothing of it, such as+ /// a task starting to work, are reported but do not wake a wait.+ timed_out: bool,+ tasks: Vec<TaskSummary>,+ /// Ids of tasks this session was shown that no longer exist.+ #[serde(skip_serializing_if = "Vec::is_empty")]+ removed: Vec<String>,+ /// Outcomes of `move_task` requests this session queued, since it was last+ /// told. What makes polling `get_transition_status` unnecessary.+ #[serde(skip_serializing_if = "Vec::is_empty")]+ transitions: Vec<ResolvedTransition>,+}++#[derive(Debug, Serialize, Clone)]+struct ResolvedTransition {+ request_id: String,+ task_id: String,+ action: String,+ /// `completed` or `error`.+ status: String,+ #[serde(skip_serializing_if = "Option::is_none")]+ error: Option<String>,+}++/// A `move_task` request this session queued and has not been told the+/// outcome of.+#[derive(Debug, Clone)]+struct QueuedMove {+ request_id: String,+ task_id: String,+ action: String,+}++/// One MCP session's view of one board, for `wait_for_board_change`.+///+/// Kept in the server because the server *is* the session: each client spawns+/// its own `agtx mcp-serve` over stdio, so this map lives exactly as long as+/// the caller it describes.+#[derive(Debug, Default)]+struct SessionBoard {+ view: BoardView,+ queued: Vec<QueuedMove>,+ /// Outcomes found by a poll but not yet returned to the caller.+ resolved: Vec<ResolvedTransition>,+}++/// One pass of a wait, read and folded into the session's view.+struct BoardPoll {+ snapshot: Vec<(TaskSummary, TaskMark)>,+ tui_connected: bool,+ wake: bool,+}++/// How long a wait lasts when the caller does not say.+const DEFAULT_WAIT_SECS: u64 = 300;+/// The longest wait a caller can ask for. A timeout is cheap β one turn β and+/// a cap keeps a stuck call from outliving a client's own tool-call limit.+const MAX_WAIT_SECS: u64 = 900;+/// How often a wait re-reads the board. The TUI refreshes phase status every+/// two seconds, so reading faster than this finds nothing new.+const WAIT_POLL_INTERVAL: Duration = Duration::from_secs(1);+#[derive(Serialize)]struct TaskDetail {id: String,@@ -303,6 +481,19 @@ struct TaskDetail {/// the permission prompt or question text the agent itself reported.#[serde(skip_serializing_if = "Option::is_none")]blocked_reason: Option<String>,+ /// The TUI's own verdict on the phase: working, blocked, idle, ready or+ /// exited. Distinct from `agent_state`, which is what the agent reports+ /// about itself β this one also covers agents with no hooks, and is the+ /// only signal that can say `ready` (the phase artifact exists) or+ /// `exited` (the window is gone).+ #[serde(skip_serializing_if = "Option::is_none")]+ phase_status: Option<String>,+ /// How many seconds ago `phase_status` was observed. See `TaskSummary`.+ #[serde(skip_serializing_if = "Option::is_none")]+ phase_age_secs: Option<i64>,+ /// Whether a TUI is running for this project. When false, `phase_status` is+ /// frozen rather than current, and no queued transition will execute.+ tui_connected: bool,}#[derive(Serialize)]@@ -402,11 +593,23 @@ struct DeleteTaskResponse {message: String,}+/// How long a TUI heartbeat stays trusted. Three beats of the TUI's+/// `TRANSITION_POLL_INTERVAL`, so one missed tick is not read as a disconnect β+/// the same window the web API applies, since the two answer the same question.+const TUI_HEARTBEAT_STALE_AFTER: chrono::Duration = chrono::Duration::seconds(6);+// === MCP Server ===#[derive(Debug, Clone)]pub struct AgtxMcpServer {mode: ServerMode,+ /// When each project's `board_watch` row was last marked, so a read burst+ /// costs one write rather than one per tool call. Shared across clones+ /// because rmcp clones the server per request.+ watched: Arc<Mutex<HashMap<String, Instant>>>,+ /// What this session has been shown of each project's board, keyed by+ /// project path. Shared across clones for the same reason as `watched`.+ boards: Arc<Mutex<HashMap<String, SessionBoard>>>,tool_router: ToolRouter<Self>,}@@ -414,10 +617,238 @@ impl AgtxMcpServer {fn new(mode: ServerMode) -> Self {Self {mode,+ watched: Arc::new(Mutex::new(HashMap::new())),+ boards: Arc::new(Mutex::new(HashMap::new())),tool_router: Self::tool_router(),}}+ fn project_key(&self, project_id: Option<&str>) -> Result<String, String> {+ self.resolve_project_path(project_id)+ .map(|p| p.to_string_lossy().to_string())+ }++ /// Run `f` on this session's view of a project's board.+ fn with_board<R>(&self, key: &str, f: impl FnOnce(&mut SessionBoard) -> R) -> R {+ let mut boards = self.boards.lock().unwrap_or_else(|e| e.into_inner());+ f(boards.entry(key.to_string()).or_default())+ }++ /// When the agent's hook last reported a turn boundary β see+ /// [`TaskMark::turn_ts`].+ fn turn_ts(hook: Option<&AgentHookStatus>) -> Option<i64> {+ hook.filter(|h| h.state != HookState::Working).map(|h| h.ts)+ }++ /// Summaries of `tasks`, each with the mark a wait compares.+ ///+ /// One runtime query for the whole board rather than one per task: this is+ /// what a polling caller runs most, and the one that grows with the project.+ fn board_snapshot(+ db: &Database,+ tasks: Vec<Task>,+ include_description: bool,+ ) -> Vec<(TaskSummary, TaskMark)> {+ let runtime = db.list_task_runtime().unwrap_or_default();+ let now = chrono::Utc::now().timestamp();+ tasks+ .into_iter()+ .map(|t| {+ let deps_satisfied = db.deps_satisfied(&t);+ let (phase_status, phase_age_secs) =+ Self::runtime_fields(runtime.iter().find(|r| r.task_id == t.id), t.status);+ let hook = t.worktree_path.as_ref().and_then(|wt| {+ crate::agent::hook_status::read_status(std::path::Path::new(wt), &t.id, now)+ });+ let mark = TaskMark {+ status: t.status,+ phase_status: phase_status.clone(),+ turn_ts: Self::turn_ts(hook.as_ref()),+ deps_satisfied,+ escalation_note: t.escalation_note.clone(),+ };+ let summary = TaskSummary {+ phase_status,+ phase_age_secs,+ id: t.id,+ title: t.title,+ description: t.description.filter(|_| include_description),+ status: t.status.as_str().to_string(),+ agent: t.agent,+ branch_name: t.branch_name,+ pr_url: t.pr_url,+ plugin: t.plugin,+ referenced_tasks: t.referenced_tasks,+ base_branch: t.base_branch,+ escalation_note: t.escalation_note,+ deps_satisfied,+ };+ (summary, mark)+ })+ .collect()+ }++ /// Record what a read tool just showed the caller, so the next wait does+ /// not wake to show it again.+ fn remember_seen<'a>(+ &self,+ project_id: Option<&str>,+ seen: impl IntoIterator<Item = (&'a str, &'a TaskMark)>,+ tui_connected: bool,+ ) {+ if let Ok(key) = self.project_key(project_id) {+ self.with_board(&key, |b| b.view.mark_seen(seen, tui_connected));+ }+ }++ /// One pass of a wait. Synchronous on purpose: the database handle and the+ /// lock both stay inside it, so nothing is held across the wait's sleep.+ fn poll_board(&self, project_id: Option<&str>, key: &str) -> Result<BoardPoll, String> {+ // A wait is a reader for its whole length, not just when it starts: the+ // TUI stops publishing phase status once nobody has read it for a while.+ self.note_board_watched(project_id);+ let db = self.open_project_db_for(project_id)?;+ let tasks = db+ .get_all_tasks()+ .map_err(|e| format!("Error listing tasks: {}", e))?;+ let snapshot = Self::board_snapshot(&db, tasks, false);+ let tui_connected = self.tui_connected(project_id);+ let marks: Vec<(String, TaskMark)> = snapshot+ .iter()+ .map(|(s, m)| (s.id.clone(), m.clone()))+ .collect();++ let wake = self.with_board(key, |board| {+ // A failed move wakes: nothing on the board shows it, so it is the+ // one outcome the caller cannot learn any other way. A completed+ // one does not β the status it changed is already on the board.+ let mut failed = false;+ for q in std::mem::take(&mut board.queued) {+ match db.get_transition_request(&q.request_id) {+ Ok(Some(req)) if req.processed_at.is_some() => {+ failed |= req.error.is_some();+ board.resolved.push(ResolvedTransition {+ request_id: q.request_id,+ task_id: q.task_id,+ action: q.action,+ status: if req.error.is_some() {+ "error"+ } else {+ "completed"+ }+ .to_string(),+ error: req.error,+ });+ }+ // Processed requests are deleted after an hour; one gone+ // before a wait saw it has nothing left to report.+ Ok(None) => {}+ _ => board.queued.push(q),+ }+ }+ board.view.poll(&marks, tui_connected) || failed+ });+ Ok(BoardPoll {+ snapshot,+ tui_connected,+ wake,+ })+ }++ /// Answer a wait with what changed, and record that the caller has seen it.+ fn answer_wait(&self, key: &str, poll: BoardPoll, timed_out: bool) -> String {+ let marks: Vec<(String, TaskMark)> = poll+ .snapshot+ .iter()+ .map(|(s, m)| (s.id.clone(), m.clone()))+ .collect();+ let (diff, transitions) = self.with_board(key, |board| {+ (+ board.view.report(&marks, poll.tui_connected),+ std::mem::take(&mut board.resolved),+ )+ });+ let changed: std::collections::HashSet<String> = diff.changed.into_iter().collect();+ let changes = BoardChanges {+ tui_connected: poll.tui_connected,+ timed_out,+ tasks: poll+ .snapshot+ .into_iter()+ .filter(|(s, _)| changed.contains(&s.id))+ .map(|(s, _)| s)+ .collect(),+ removed: diff.removed,+ transitions,+ };+ serde_json::to_string_pretty(&changes)+ .unwrap_or_else(|e| format!("Error serializing: {}", e))+ }++ /// Tell the TUI someone is reading this board, so it starts publishing+ /// `task_runtime`.+ ///+ /// Publishing is gated on a recent reader because a board nobody reads+ /// should cost no writes. An MCP client is such a reader β without this the+ /// orchestrator and any oneshot session poll a table that is never written,+ /// and every task reports no phase status forever.+ ///+ /// Throttled on the same reasoning as the web server's copy: the question+ /// it answers resolves in minutes, and `get_task` is called once per task+ /// in a polling loop.+ fn note_board_watched(&self, project_id: Option<&str>) {+ const NOTE_INTERVAL: Duration = Duration::from_secs(30);+ let Ok(path) = self.resolve_project_path(project_id) else {+ return;+ };+ let key = path.to_string_lossy().to_string();+ {+ let mut watched = self.watched.lock().unwrap_or_else(|e| e.into_inner());+ if watched.get(&key).is_some_and(|at| at.elapsed() < NOTE_INTERVAL) {+ return;+ }+ watched.insert(key.clone(), Instant::now());+ }+ if let Ok(db) = Database::open_global() {+ let _ = db.note_board_watched(&key);+ }+ }++ /// Whether a TUI has beaten for this project recently enough to be draining+ /// the queue and refreshing phase status.+ ///+ /// Without this a caller can only *infer* a dead board from `phase_age_secs`+ /// climbing across every task at once β and until it does, a frozen row+ /// reads as live state: a task shows `blocked` while its agent works+ /// normally.+ fn tui_connected(&self, project_id: Option<&str>) -> bool {+ let Ok(path) = self.resolve_project_path(project_id) else {+ return false;+ };+ let Ok(db) = Database::open_global() else {+ return false;+ };+ db.tui_is_live(&path.to_string_lossy(), TUI_HEARTBEAT_STALE_AFTER)+ .unwrap_or(false)+ }++ /// The published phase status for a task, as `(status, age_secs)`.+ ///+ /// A row computed for a status the task has since left is withheld: it+ /// describes the previous phase, and its `updated_at` is fresh, so age alone+ /// cannot catch it. Returning nothing reads as "not yet observed", which is+ /// what it is.+ fn runtime_fields(+ rt: Option<&crate::db::TaskRuntime>,+ current: TaskStatus,+ ) -> (Option<String>, Option<i64>) {+ let rt = rt.filter(|r| r.status.map_or(true, |s| s == current));+ (+ rt.map(|r| r.phase_status.as_str().to_string()),+ rt.map(|r| (chrono::Utc::now() - r.updated_at).num_seconds()),+ )+ }+/// Resolve a project path from an optional `project_id`.////// - In `Project` mode the fixed path is always returned; `project_id` is ignored.@@ -516,10 +947,53 @@ impl AgtxMcpServer {}#[tool(- description = "List tasks for a project, optionally filtered by status (backlog, planning, running, review, done). In global mode, project_id is required β call list_projects first."+ description = "Read the effective agtx configuration for a project β the global config merged with the project's own, which is what actually governs a run. Use this instead of reading ~/.config/agtx/config.toml: that path is not authoritative (AGTX_CONFIG_DIR relocates it), and a project config overrides much of it. Returns auto_trust (whether agents' trust dialogs are answered automatically β an unattended run needs this true), default_agent, per-phase agents, worktree settings, the active workflow plugin, and the paths both files live at."+ )]+ fn get_config(&self, Parameters(params): Parameters<GetConfigParams>) -> String {+ tracing::info!(tool = "get_config", project_id = ?params.project_id, "MCP tool called");+ let project_path = match self.resolve_project_path(params.project_id.as_deref()) {+ Ok(p) => p,+ Err(e) => return e,+ };+ let global = GlobalConfig::load().unwrap_or_default();+ let project = ProjectConfig::load(&project_path).unwrap_or_default();+ let merged = crate::config::MergedConfig::merge(&global, &project);++ let project_config_path = project_path.join(".agtx").join("config.toml");+ let cfg = EffectiveConfig {+ global_config_path: GlobalConfig::config_path()+ .map(|p| p.to_string_lossy().to_string())+ .unwrap_or_else(|_| "<unresolved>".to_string()),+ project_config_exists: project_config_path.exists(),+ project_config_path: project_config_path.to_string_lossy().to_string(),+ auto_trust: merged.auto_trust,+ default_agent: merged.default_agent,+ phase_agents: serde_json::json!({+ "research": merged.phase_agents.research,+ "planning": merged.phase_agents.planning,+ "running": merged.phase_agents.running,+ "review": merged.phase_agents.review,+ }),+ worktree_enabled: merged.worktree_enabled,+ skip_worktree: merged.skip_worktree,+ auto_cleanup: merged.auto_cleanup,+ base_branch: merged.base_branch,+ worktree_dir: merged.worktree_dir,+ branch_prefix: merged.branch_prefix,+ workflow_plugin: merged.workflow_plugin,+ agent_hooks: merged.agent_hooks,+ github_url: merged.github_url,+ };+ serde_json::to_string_pretty(&cfg)+ .unwrap_or_else(|e| format!("Error serializing: {}", e))+ }++ #[tool(+ description = "List tasks for a project, optionally filtered by status (backlog, planning, running, review, done). Descriptions are left out unless include_description is true β get_task has the full task. To watch the board, call wait_for_board_change instead of calling this in a loop. In global mode, project_id is required β call list_projects first.")]fn list_tasks(&self, Parameters(params): Parameters<ListTasksParams>) -> String {tracing::info!(tool = "list_tasks", status = ?params.status, project_id = ?params.project_id, "MCP tool called");+ self.note_board_watched(params.project_id.as_deref());match self.open_project_db_for(params.project_id.as_deref()) {Ok(db) => {let tasks_result = if let Some(status_str) = ¶ms.status {@@ -532,26 +1006,22 @@ impl AgtxMcpServer {};match tasks_result {Ok(tasks) => {- let summaries: Vec<TaskSummary> = tasks- .into_iter()- .map(|t| {- let deps_satisfied = db.deps_satisfied(&t);- TaskSummary {- id: t.id,- title: t.title,- description: t.description,- status: t.status.as_str().to_string(),- agent: t.agent,- branch_name: t.branch_name,- pr_url: t.pr_url,- plugin: t.plugin,- referenced_tasks: t.referenced_tasks,- base_branch: t.base_branch,- deps_satisfied,- }- })- .collect();- serde_json::to_string_pretty(&summaries)+ let snapshot = Self::board_snapshot(+ &db,+ tasks,+ params.include_description.unwrap_or(false),+ );+ let tui_connected = self.tui_connected(params.project_id.as_deref());+ self.remember_seen(+ params.project_id.as_deref(),+ snapshot.iter().map(|(s, m)| (s.id.as_str(), m)),+ tui_connected,+ );+ let listing = BoardListing {+ tui_connected,+ tasks: snapshot.into_iter().map(|(s, _)| s).collect(),+ };+ serde_json::to_string_pretty(&listing).unwrap_or_else(|e| format!("Error serializing: {}", e))}Err(e) => format!("Error listing tasks: {}", e),@@ -566,6 +1036,7 @@ impl AgtxMcpServer {)]fn get_task(&self, Parameters(params): Parameters<GetTaskParams>) -> String {tracing::info!(tool = "get_task", task_id = %params.task_id, "MCP tool called");+ self.note_board_watched(params.project_id.as_deref());match self.open_project_db_for(params.project_id.as_deref()) {Ok(db) => match db.get_task(¶ms.task_id) {Ok(Some(t)) => {@@ -611,8 +1082,26 @@ impl AgtxMcpServer {.to_string()});let blocked_reason = hook.as_ref().and_then(|h| h.message.clone());+ let runtime = db.get_task_runtime(¶ms.task_id).ok().flatten();+ let (phase_status, phase_age_secs) = Self::runtime_fields(runtime.as_ref(), t.status);+ let tui_connected = self.tui_connected(params.project_id.as_deref());+ let mark = TaskMark {+ status: t.status,+ phase_status: phase_status.clone(),+ turn_ts: Self::turn_ts(hook.as_ref()),+ deps_satisfied: deps_ok,+ escalation_note: t.escalation_note.clone(),+ };+ self.remember_seen(+ params.project_id.as_deref(),+ [(t.id.as_str(), &mark)],+ tui_connected,+ );let detail = TaskDetail {+ phase_status,+ phase_age_secs,+ tui_connected,id: t.id,title: t.title,description: t.description,@@ -648,7 +1137,42 @@ impl AgtxMcpServer {}#[tool(- description = "Queue a task state transition. The agtx TUI will process it and execute all side effects (worktree creation, agent spawning, etc). Use get_transition_status to check completion. Actions: research (start research phase for backlog task), move_forward, move_to_planning, move_to_running, move_to_review, move_to_done, resume, escalate_to_user (flag task for user attention with an optional reason)"+ description = "Block until something on the board needs you, then return only what changed since you last looked (via this tool, list_tasks or get_task). Wakes when a task reaches ready, idle, blocked or exited, reaches Done, becomes startable in Backlog, is escalated, appears or is deleted; when one of your move_task requests fails; or when the TUI connects or disconnects. A task merely starting to work does not wake it. The first call returns the whole board. Also reports the outcome of every move_task you queued, so get_transition_status is not needed. Use this as the polling loop instead of sleeping and calling list_tasks. timed_out: true means nothing needed you. In global mode, project_id is required β call list_projects first."+ )]+ async fn wait_for_board_change(+ &self,+ Parameters(params): Parameters<WaitForBoardChangeParams>,+ ) -> String {+ tracing::info!(tool = "wait_for_board_change", timeout_secs = ?params.timeout_secs, "MCP tool called");+ let timeout = Duration::from_secs(+ params+ .timeout_secs+ .unwrap_or(DEFAULT_WAIT_SECS)+ .clamp(1, MAX_WAIT_SECS),+ );+ let project_id = params.project_id.as_deref();+ let key = match self.project_key(project_id) {+ Ok(k) => k,+ Err(e) => return e,+ };+ let started = Instant::now();+ loop {+ let poll = match self.poll_board(project_id, &key) {+ Ok(p) => p,+ Err(e) => return e,+ };+ if poll.wake {+ return self.answer_wait(&key, poll, false);+ }+ if started.elapsed() >= timeout {+ return self.answer_wait(&key, poll, true);+ }+ tokio::time::sleep(WAIT_POLL_INTERVAL).await;+ }+ }++ #[tool(+ description = "Queue a task state transition. The agtx TUI will process it and execute all side effects (worktree creation, agent spawning, etc). Use get_transition_status to check completion β a transition out of Backlog waits for the single worktree-setup slot, so it stays 'pending' until its turn. Actions: research (start research phase for backlog task), move_forward, move_to_planning, move_to_running, move_to_review, move_to_done, move_to_done_and_merge (merge the task branch into its base branch in the project checkout first, and stay in Review if it conflicts β for unattended callers that integrate locally instead of through a PR), resume, escalate_to_user (flag task for user attention with an optional reason)")]fn move_task(&self, Parameters(params): Parameters<MoveTaskParams>) -> String {tracing::info!(tool = "move_task", task_id = %params.task_id, action = %params.action, "MCP tool called");@@ -690,6 +1214,15 @@ impl AgtxMcpServer {match db.create_transition_request(&req) {Ok(()) => {+ if let Ok(key) = self.project_key(params.project_id.as_deref()) {+ self.with_board(&key, |b| {+ b.queued.push(QueuedMove {+ request_id: request_id.clone(),+ task_id: params.task_id.clone(),+ action: params.action.clone(),+ })+ });+ }let result = MoveTaskResult {request_id,message: format!(@@ -848,7 +1381,7 @@ impl AgtxMcpServer {}#[tool(- description = "Read the last N lines of a task's agent tmux pane. Use this to understand what the agent is showing β e.g., when a task has been idle for a while. Returns pane content as text."+ description = "Read the last N lines of what a task's agent pane shows (default 50), blank rows at the bottom dropped. Use this to understand what the agent is showing β e.g., when a task has been idle for a while. An agent that draws full-screen, like Claude Code, keeps no history outside its visible screen, so nothing older than that screen can be read this way. Ask for only as many lines as you need: the answer stays in your context.")]fn read_pane_content(&self, Parameters(params): Parameters<ReadPaneParams>) -> String {tracing::info!(tool = "read_pane_content", task_id = %params.task_id, "MCP tool called");@@ -886,7 +1419,8 @@ impl AgtxMcpServer {match output {Ok(out) => {- let content = String::from_utf8_lossy(&out.stdout).to_string();+ let content =+ crate::tmux::pane_tail(&String::from_utf8_lossy(&out.stdout), lines as usize);let response = ReadPaneResponse {task_id: params.task_id,session_name,@@ -901,7 +1435,7 @@ impl AgtxMcpServer {}#[tool(- description = "Send a message to a task's agent pane (followed by Enter). Only works for tasks in Planning or Running status. Use this to nudge a stuck agent, answer a CLI prompt (e.g. 'y' for yes), or provide guidance."+ description = "Send a message to a task's agent pane (followed by Enter). Works for tasks in Planning, Running or Review. Use this to nudge a stuck agent, answer a CLI prompt (e.g. 'y' for yes), or provide guidance. In Review it is how to give the reviewer a small fix to make in place, without moving the task back to Running β resume is for significant rework.")]fn send_to_task(&self, Parameters(params): Parameters<SendToTaskParams>) -> String {tracing::info!(tool = "send_to_task", task_id = %params.task_id, "MCP tool called");@@ -930,10 +1464,11 @@ impl AgtxMcpServer {Err(e) => return format!("Error getting task: {}", e),};- // Only allow sending to active phases- if !matches!(task.status, TaskStatus::Planning | TaskStatus::Running) {+ // Review is included so a reviewer can be given a small fix in place;+ // see `accepts_task_input`.+ if !crate::core::actions::accepts_task_input(task.status) {return format!(- "Error: task is not in an active phase (current: {}). send_to_task only works for Planning or Running tasks.",+ "Error: task has no agent to receive input (current: {}). send_to_task works for Planning, Running and Review tasks.",task.status.as_str());}@@ -943,40 +1478,29 @@ impl AgtxMcpServer {None => return format!("Task {} has no active session", params.task_id),};- // Send the message text- let send_text = Command::new("tmux")- .args([- "-L",- "agtx",- "send-keys",- "-t",- &session_name,- ¶ms.message,- ])- .output();-- if let Err(e) = send_text {- return format!("Error sending message: {}", e);- }-- // Send Enter- let send_enter = Command::new("tmux")- .args(["-L", "agtx", "send-keys", "-t", &session_name, "Enter"])- .output();-- match send_enter {- Ok(_) => {- let response = SendToTaskResponse {- task_id: params.task_id,- session_name,- success: true,- message: format!("Message sent: {}", params.message),- };- serde_json::to_string_pretty(&response)- .unwrap_or_else(|e| format!("Error serializing: {}", e))- }- Err(e) => format!("Error sending Enter: {}", e),+ // A bracketed paste, then a watched submit: the path agtx uses for every+ // other whole message, via `core::input::send_user_text`.+ //+ // Not a raw `send-keys` of the text, which loses the head of a long+ // message. Measured against Claude Code 2.1.268: a+ // 1644-byte message typed that way arrived as its last 622 bytes, the first+ // 1022 silently dropped, while the same bytes as a bracketed paste arrived+ // whole. tmux and the pty are not the cause β a raw-mode `cat` received+ // every byte by both methods β the agent's input handling discards the+ // start of a large typed burst. The agent then acts on the tail of an+ // instruction with its premise gone, which is worse than receiving nothing.+ let tmux_ops: Arc<dyn crate::tmux::TmuxOperations> = Arc::new(crate::tmux::RealTmuxOps);+ if !crate::core::input::send_user_text(&tmux_ops, &session_name, ¶ms.message, true) {+ return format!("Error sending message to {}", session_name);}+ let response = SendToTaskResponse {+ task_id: params.task_id,+ session_name,+ success: true,+ message: format!("Message sent: {}", params.message),+ };+ serde_json::to_string_pretty(&response)+ .unwrap_or_else(|e| format!("Error serializing: {}", e))}#[tool(@@ -1237,13 +1761,17 @@ impl ServerHandler for AgtxMcpServer {Use list_tasks to see tasks, create_task or create_tasks_batch to add new tasks \(with optional dependency wiring via referenced_tasks), update_task to modify backlog \task fields, move_task to transition tasks between phases, get_transition_status to \- check if a transition completed, and delete_task to remove backlog tasks.",+ check if a transition completed, and delete_task to remove backlog tasks. \+ To supervise the board, call wait_for_board_change in a loop rather than sleeping \+ and re-listing: it returns only what changed.",ServerMode::Project(_) =>"agtx MCP server β control the terminal kanban board for coding agents. \Use list_tasks to see current tasks, create_task or create_tasks_batch to add new tasks \(with optional dependency wiring via referenced_tasks), update_task to modify backlog \task fields, move_task to transition tasks between phases, get_transition_status to \- check if a transition completed, and delete_task to remove backlog tasks.",+ check if a transition completed, and delete_task to remove backlog tasks. \+ To supervise the board, call wait_for_board_change in a loop rather than sleeping \+ and re-listing: it returns only what changed.",};ServerInfo::new(ServerCapabilities::builder().enable_tools().build()).with_instructions(instructions)diff --git a/src/tmux/mod.rs b/src/tmux/mod.rsindex 33b5e95..5566a71 100644--- a/src/tmux/mod.rs+++ b/src/tmux/mod.rs@@ -117,6 +117,27 @@ pub fn capture_pane(session_name: &str, lines: i32) -> Result<String> {Ok(String::from_utf8_lossy(&output.stdout).to_string())}+/// The last `n` lines of a pane capture, after dropping the blank rows below+/// the last line of output.+///+/// `capture-pane -p` emits one line per pane *row*, so the raw end of a capture+/// is padding whenever the output has not filled the pane. Trailing blank rows+/// go first, so `n` counts lines of output rather than the empty rows under a+/// short one.+///+/// Nor is `capture-pane -S -N` a tail: it starts N lines back in the scrollback+/// and runs to the bottom of the *visible* screen. An agent that draws+/// full-screen keeps no tmux scrollback, so the capture is the whole screen+/// whatever N is β measured, a request for 15 lines returns 49.+pub fn pane_tail(content: &str, n: usize) -> String {+ let lines: Vec<&str> = content.lines().collect();+ let end = lines+ .iter()+ .rposition(|l| !l.trim().is_empty())+ .map_or(0, |i| i + 1);+ lines[end.saturating_sub(n)..end].join("\n")+}+/// Send keys to a sessionpub fn send_keys(session_name: &str, keys: &str) -> Result<()> {Command::new("tmux")@@ -197,3 +218,29 @@ impl SessionInfo {self.name.split("--").nth(1)}}++#[cfg(test)]+mod tests {+ use super::pane_tail;++ #[test]+ fn a_pane_read_returns_only_the_lines_asked_for() {+ let screen: String = (1..=49).map(|i| format!("line {i}\n")).collect();+ let tail = pane_tail(&screen, 15);+ assert_eq!(tail.lines().count(), 15);+ assert!(tail.starts_with("line 35"));+ assert!(tail.ends_with("line 49"));+ }++ #[test]+ fn blank_rows_below_the_output_do_not_count() {+ let screen = "prompt\nβ― working\n\n \n\n";+ assert_eq!(pane_tail(screen, 1), "β― working");+ }++ #[test]+ fn asking_for_more_than_there_is_returns_all_of_it() {+ assert_eq!(pane_tail("a\nb\n", 50), "a\nb");+ assert_eq!(pane_tail("\n\n", 5), "");+ }+}diff --git a/src/tmux/operations.rs b/src/tmux/operations.rsindex aafdac8..cd77f04 100644--- a/src/tmux/operations.rs+++ b/src/tmux/operations.rs@@ -33,6 +33,13 @@ pub trait TmuxOperations: Send + Sync {/// This window's tmux pane id (`%7`), for matching `%output` notifications.fn pane_id(&self, target: &str) -> Option<String>;+ /// The OS process id of the window's pane β the shell tmux started.+ ///+ /// The root for finding what a task spawned. Distinct from+ /// [`pane_id`](Self::pane_id), which is tmux's own `%7` handle and means+ /// nothing to the operating system.+ fn pane_pid(&self, target: &str) -> Option<u32>;+/// Every window on the server as `session:window`.////// One call answers [`window_exists`](Self::window_exists) for every task on@@ -311,6 +318,18 @@ impl TmuxOperations for RealTmuxOps {(!id.is_empty()).then_some(id)}+ fn pane_pid(&self, target: &str) -> Option<u32> {+ let out = std::process::Command::new("tmux")+ .args(["-L", super::AGENT_SERVER])+ .args(["display", "-p", "-t", target, "#{pane_pid}"])+ .output()+ .ok()?;+ if !out.status.success() {+ return None;+ }+ String::from_utf8_lossy(&out.stdout).trim().parse().ok()+ }+fn list_window_targets(&self) -> Result<Vec<String>> {let output = std::process::Command::new("tmux").args(["-L", super::AGENT_SERVER])diff --git a/src/tui/app.rs b/src/tui/app.rsindex 5c87684..13c621c 100644--- a/src/tui/app.rs+++ b/src/tui/app.rs@@ -28,7 +28,8 @@ use crate::git::{};use crate::skills;use crate::tmux::{- self, InputConfig, InputError, PaneInput, PaneInputSink, RealTmuxOps, TmuxOperations,+ self, pane_tail, InputConfig, InputError, PaneInput, PaneInputSink, RealTmuxOps,+ TmuxOperations,};use crate::AppMode;@@ -445,13 +446,52 @@ struct AppState {/// kills the child. Someone opens `W`, scans, closes it, and carries on/// using the board; the server has to survive that.serve_session: Option<crate::tui::serve_control::ServeSession>,- // Queue of task IDs awaiting serialized worktree setup (batch-move from the- // dependency view). Worktree setup runs one-at-a-time via `setup_rx`; this- // queue is drained as each setup completes.- setup_queue: VecDeque<String>,+ // Tasks awaiting serialized worktree setup, with what each was asked to do.+ // Worktree setup runs one-at-a-time via `setup_rx`; this queue is drained as+ // each setup completes. Fed by the dependency view's batch move and by MCP+ // transition requests, which is why the intent travels with the id: those+ // two disagree about where a Backlog task should land.+ setup_queue: VecDeque<QueuedSetup>,instance_id: String,}+/// Where a queued Backlog task should go once a setup slot frees up.+///+/// The dependency overlay and the MCP queue want different things from the same+/// mechanism: the overlay moves whatever the user marked and lets each task's+/// plugin decide between research and planning, while an MCP request names one+/// transition and must not be answered with a different one.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+enum SetupIntent {+ /// Research if the task's plugin defines a research command, else planning.+ PluginDefault,+ Research,+ Planning,+ Running,+}++/// A task waiting for the single worktree-setup slot.+#[derive(Debug, Clone)]+struct QueuedSetup {+ task_id: String,+ intent: SetupIntent,+ /// The MCP transition request this came from, if any. It stays claimed and+ /// unprocessed β so `get_transition_status` reports `pending` β until the+ /// drain either starts the setup or gives up on it. Marking it completed at+ /// enqueue time would tell a caller the task had moved while it was still+ /// sitting in a queue.+ request_id: Option<String>,+}++/// What `execute_transition_request` did with a request.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+enum TransitionOutcome {+ /// Handled now; the caller marks it processed.+ Applied,+ /// Waiting for the setup slot. The drain owns marking it from here.+ Queued,+}+/// State for the dependency-graph overlay.struct DepGraphPopup {graph: crate::tui::dep_graph::DepGraph,@@ -5849,7 +5889,7 @@ impl App {let Some(ref wt_path) = task.worktree_path else {return false;};- if phase_artifact_exists(wt_path, current_status, &plugin, task.cycle) {+ if phase_artifact_fresh(wt_path, current_status, &plugin, task.cycle, task.phase_entered_at) {return false;}let agent_running = task.session_name.as_ref().map_or(false, |target| {@@ -6942,13 +6982,35 @@ impl App {/// Enqueue unblocked tasks for serialized worktree setup, then kick off the first.fn batch_move_unblocked(&mut self, task_ids: Vec<String>) -> Result<()> {for id in task_ids {- if !self.state.setup_queue.contains(&id) {- self.state.setup_queue.push_back(id);- }+ self.enqueue_setup(&id, SetupIntent::PluginDefault, None);}self.try_start_next_queued_setup()}+ /// Queue a Backlog task for the setup slot, unless it is already waiting.+ ///+ /// Deduplicated on the task rather than on the pair: a task queued twice+ /// with different intents is a caller changing its mind, and running the+ /// first one and then the second would set the worktree up twice. The+ /// duplicate's request is resolved rather than dropped, so a caller polling+ /// it is not left waiting on a row nothing will ever touch.+ fn enqueue_setup(&mut self, task_id: &str, intent: SetupIntent, request_id: Option<String>) {+ if self.state.setup_queue.iter().any(|q| q.task_id == task_id) {+ if let (Some(db), Some(rid)) = (&self.state.db, request_id) {+ let _ = db.mark_transition_processed(+ &rid,+ Some("Task is already queued for worktree setup"),+ );+ }+ return;+ }+ self.state.setup_queue.push_back(QueuedSetup {+ task_id: task_id.to_string(),+ intent,+ request_id,+ });+ }+/// If no worktree setup is currently running, start the next queued batch task./// Routes each task to research when its plugin supports it, else to planning.fn try_start_next_queued_setup(&mut self) -> Result<()> {@@ -6956,28 +7018,70 @@ impl App {if self.state.setup_rx.is_some() {return Ok(());}- while let Some(task_id) = self.state.setup_queue.pop_front() {+ while let Some(QueuedSetup {+ task_id,+ intent,+ request_id,+ }) = self.state.setup_queue.pop_front()+ {// Re-validate: the task may have changed status or deps since queuing.+ // A queued request outlives the state it was accepted against, so+ // each way of failing here has to resolve the request β dropping it+ // silently leaves a caller polling `pending` forever.let Some(db) = self.state.db.as_ref() else {+ self.resolve_queued_request(&request_id, Some("No project database"));continue;};let Some(task) = db.get_task(&task_id).ok().flatten() else {+ self.resolve_queued_request(&request_id, Some("Task no longer exists"));continue;};- if task.status != TaskStatus::Backlog || !db.deps_satisfied(&task) {+ if task.status != TaskStatus::Backlog {+ self.resolve_queued_request(+ &request_id,+ Some(&format!(+ "Task left Backlog while queued (now: {})",+ task.status.as_str()+ )),+ );+ continue;+ }+ if !db.deps_satisfied(&task) {+ self.resolve_queued_request(+ &request_id,+ Some("Cannot advance task: dependencies not in Review/Done"),+ );continue;}- // Prefer research if the plugin defines a research/preresearch command.- let plugin = self.load_task_plugin(&task);- let has_research_cmd = plugin.as_ref().map_or(false, |p| {- p.commands.research.is_some() || p.commands.preresearch.is_some()- });+ let intent = match intent {+ // Prefer research if the plugin defines a research/preresearch command.+ SetupIntent::PluginDefault => {+ let plugin = self.load_task_plugin(&task);+ let has_research_cmd = plugin.as_ref().map_or(false, |p| {+ p.commands.research.is_some() || p.commands.preresearch.is_some()+ });+ if has_research_cmd {+ SetupIntent::Research+ } else {+ SetupIntent::Planning+ }+ }+ explicit => explicit,+ };- if has_research_cmd {- self.start_research(&task_id)?;- } else {- self.start_planning_from_backlog(&task_id)?;+ // A failure here belongs to this request, not to the drain: taking+ // `?` would abandon everything queued behind it and leave every one+ // of their requests pending.+ let started = match intent {+ SetupIntent::Research => self.start_research(&task_id),+ SetupIntent::Planning => self.start_planning_from_backlog(&task_id),+ SetupIntent::Running => self.move_backlog_to_running_by_id(&task_id),+ SetupIntent::PluginDefault => unreachable!("resolved above"),+ };+ match started {+ Ok(()) => self.resolve_queued_request(&request_id, None),+ Err(e) => self.resolve_queued_request(&request_id, Some(&e.to_string())),}// start_research / start_planning_from_backlog set setup_rx when they@@ -6991,6 +7095,33 @@ impl App {Ok(())}+ /// Queue a Backlog task's setup and try to start it now.+ ///+ /// Every Backlog transition from MCP comes through here, whether or not the+ /// setup slot is free, so the queue is the single ordering authority and no+ /// transition is rejected for arriving while the slot is busy. A rejection+ /// there would be invisible: `move_task` has already answered `queued`, and+ /// nothing would retry the task.+ fn queue_backlog_setup(+ &mut self,+ req: &TransitionRequest,+ intent: SetupIntent,+ ) -> Result<TransitionOutcome> {+ self.enqueue_setup(&req.task_id, intent, Some(req.id.clone()));+ self.try_start_next_queued_setup()?;+ Ok(TransitionOutcome::Queued)+ }++ /// Mark a queued request's transition row processed, if it came from one.+ ///+ /// `TransitionOutcome::Queued` defers the marking to here, so this is the+ /// only place a setup queued from MCP stops reporting `pending`.+ fn resolve_queued_request(&self, request_id: &Option<String>, error: Option<&str>) {+ if let (Some(db), Some(rid)) = (&self.state.db, request_id) {+ let _ = db.mark_transition_processed(rid, error);+ }+ }+/// Move a Backlog task into Planning (the planning fallback for plugins with/// no research phase). Mirrors `move_task_right`'s BacklogβPlanning branch.fn start_planning_from_backlog(&mut self, task_id: &str) -> Result<()> {@@ -7284,6 +7415,8 @@ impl App {return Ok(());}+ mark_reviewed_point(&task);+// Switch agent if running phase uses a different agent than reviewlet (running_agent, agent_switch) =needs_agent_switch(&self.state.config, &task, "running");@@ -7509,6 +7642,23 @@ impl App {/// Poll the transition_requests table for unprocessed requests and execute them.fn process_transition_requests(&mut self) -> Result<()> {+ let instance_id = self.state.instance_id.clone();++ // Recover anything a previous TUI claimed and never finished, before+ // reading the queue, so a reclaimed request is drained in this same+ // pass. Done here rather than only at startup: a TUI that dies mid-run+ // strands its queue, and the recovery should not wait for whenever+ // someone next launches agtx.+ if let Some(db) = self.state.db.as_ref() {+ match db.reclaim_stale_transition_requests(&instance_id, RECLAIM_CLAIMS_AFTER) {+ Ok(n) if n > 0 => {+ tracing::info!(count = n, "Reclaimed transition requests from a dead instance")+ }+ Ok(_) => {}+ Err(e) => tracing::warn!(error = %e, "Failed to reclaim transition requests"),+ }+ }+// `self.state.db` is re-borrowed per use site to avoid holding it across `&mut self`.let pending = match self.state.db.as_ref() {Some(db) => db.get_pending_transition_requests()?,@@ -7534,7 +7684,10 @@ impl App {let result = self.execute_transition_request(&req);if let Some(db) = &self.state.db {let _ = match &result {- Ok(()) => db.mark_transition_processed(&req.id, None),+ // A queued setup stays claimed and unprocessed; the drain+ // marks it when the slot frees up and it actually starts.+ Ok(TransitionOutcome::Queued) => Ok(()),+ Ok(TransitionOutcome::Applied) => db.mark_transition_processed(&req.id, None),Err(e) => db.mark_transition_processed(&req.id, Some(&e.to_string())),};}@@ -7549,7 +7702,10 @@ impl App {Ok(())}- fn execute_transition_request(&mut self, req: &TransitionRequest) -> Result<()> {+ fn execute_transition_request(+ &mut self,+ req: &TransitionRequest,+ ) -> Result<TransitionOutcome> {tracing::info!(task_id = %req.task_id,action = %req.action,@@ -7569,9 +7725,20 @@ impl App {// Recheck when the queue is drained: an agent may have written more// work since the phone rendered the card or submitted the request.- // Include move_forward so stale/legacy requests cannot bypass this.+ //+ // **Every** action that can reach Done must be listed here, because+ // reaching Done deletes the worktree and `has_changes` reads+ // `git status --porcelain`, which counts *untracked* files. An agent+ // that wrote its work and never ran `git commit` has all of it here and+ // nowhere else, so a route to Done missing from this list merges an+ // empty branch and then deletes the work β a silent data-loss bug, not a+ // missing check. `move_forward` is listed so a stale request cannot be a+ // way around it.if task.status == TaskStatus::Review- && matches!(req.action.as_str(), "move_to_done" | "move_forward")+ && matches!(+ req.action.as_str(),+ "move_to_done" | "move_to_done_and_merge" | "move_forward"+ )&& task.worktree_path.as_ref()@@ -7602,9 +7769,12 @@ impl App {"Task already has an active session (research may already be running)");}- self.start_research(&req.task_id)?;+ return self.queue_backlog_setup(req, SetupIntent::Research);}"move_forward" => {+ if task.status == TaskStatus::Backlog {+ return self.queue_backlog_setup(req, SetupIntent::Planning);+ }self.execute_forward_transition(&mut task, &project_path)?;}"move_to_planning" => {@@ -7614,7 +7784,7 @@ impl App {task.status.as_str());}- self.execute_forward_transition(&mut task, &project_path)?;+ return self.queue_backlog_setup(req, SetupIntent::Planning);}"move_to_running" => {if task.status != TaskStatus::Planning && task.status != TaskStatus::Backlog {@@ -7624,10 +7794,9 @@ impl App {);}if task.status == TaskStatus::Backlog {- self.move_backlog_to_running_by_id(&req.task_id)?;- } else {- self.execute_forward_transition(&mut task, &project_path)?;+ return self.queue_backlog_setup(req, SetupIntent::Running);}+ self.execute_forward_transition(&mut task, &project_path)?;}"move_to_review" => {if task.status != TaskStatus::Running {@@ -7647,6 +7816,25 @@ impl App {}self.force_move_to_done(&task.id)?;}+ "move_to_done_and_merge" => {+ if task.status != TaskStatus::Review {+ // Names the action asked for, and β for the state this+ // actually gets asked from β what to do about it. A resume+ // puts a task back in Running, and trying to merge straight+ // afterwards is the common way a caller lands here.+ let fix = if task.status == TaskStatus::Running {+ " Move it forward to Review first."+ } else {+ ""+ };+ anyhow::bail!(+ "Task must be in Review to merge and move to Done (current: {}).{}",+ task.status.as_str(),+ fix+ );+ }+ self.merge_then_done(&task, &project_path)?;+ }"resume" => {if task.status != TaskStatus::Review {anyhow::bail!(@@ -7678,7 +7866,7 @@ impl App {}}- Ok(())+ Ok(TransitionOutcome::Applied)}/// Execute a forward transition (next column), mirroring move_task_right logic.@@ -7694,9 +7882,6 @@ impl App {// Skip the phase-incomplete confirmation for MCP requestslet handled = match (task.status, next_status) {(TaskStatus::Backlog, TaskStatus::Planning) => {- if self.state.setup_rx.is_some() {- anyhow::bail!("Another task setup is already in progress, try again shortly");- }self.transition_to_planning(task, project_path)?}(TaskStatus::Planning, TaskStatus::Running) => self.transition_to_running(task)?,@@ -7722,6 +7907,122 @@ impl App {Ok(())}+ /// Merge a Review task's branch into its base, then move it to Done.+ ///+ /// The two halves are one action because doing them separately loses the+ /// only chance to keep the worktree: Done removes it, and a conflict is+ /// resolved by the task's own agent, in that worktree, against the branch it+ /// has been working on. So a conflict leaves the task exactly where it was β+ /// in Review, with its session alive β and hands the work to the agent that+ /// is already there.+ ///+ /// Merging is synchronous, unlike the cleanup that follows it. Done is+ /// reversible in the sense that matters (the branch survives); a merge+ /// commit in the user's checkout is not, so its outcome has to be known+ /// before the task's status is changed to match.+ fn merge_then_done(&mut self, task: &Task, project_path: &Path) -> Result<()> {+ let Some(branch) = task.branch_name.clone() else {+ anyhow::bail!("Task has no branch to merge");+ };+ let base = match task.base_branch.as_deref() {+ Some(b) if !b.trim().is_empty() => b.trim().to_string(),+ _ => crate::git::detect_main_branch(project_path)?,+ };++ let message = format!("Merge task '{}' ({})", task.title, branch);+ match crate::git::merge_task_branch(project_path, &base, &branch, &message)? {+ crate::git::MergeOutcome::Merged => {+ tracing::info!(task_id = %task.id, %branch, %base, "Merged task branch");+ self.force_move_to_done(&task.id)+ }+ crate::git::MergeOutcome::NothingToMerge => {+ anyhow::bail!(+ "Branch '{branch}' has no commits β nothing to merge into '{base}', \+ and the task stays in Review. If the agent wrote files, they are \+ uncommitted in the worktree and would be destroyed by Done: tell it \+ to commit, then retry."+ );+ }+ crate::git::MergeOutcome::Conflicts(files) => {+ self.send_to_conflict_resolution(task, &base, &files)?;+ let shown: Vec<&str> = files.iter().take(5).map(String::as_str).collect();+ let more = files.len().saturating_sub(shown.len());+ anyhow::bail!(+ "Branch '{}' conflicts with '{}' in {} file(s): {}{}. \+ Task stays in Review; its agent was asked to resolve them. \+ Retry once it reports done.",+ branch,+ base,+ files.len(),+ shown.join(", "),+ if more > 0 {+ format!(" (+{more} more)")+ } else {+ String::new()+ }+ );+ }+ crate::git::MergeOutcome::Refused(why) => {+ anyhow::bail!(+ "Cannot merge '{branch}' into '{base}': {why}. \+ Nothing was changed."+ );+ }+ }+ }++ /// Hand a conflicting Review task to its own agent, and mark the card.+ ///+ /// The escalation note is set whether or not the agent could be reached: a+ /// conflict the caller cannot resolve is exactly what the user needs to see+ /// on the board, and a task whose session has already exited is the case+ /// where that matters most.+ fn send_to_conflict_resolution(+ &mut self,+ task: &Task,+ base: &str,+ files: &[String],+ ) -> Result<()> {+ if let Some(db) = &self.state.db {+ if let Some(mut t) = db.get_task(&task.id)? {+ t.escalation_note = Some(format!(+ "Merge conflicts with {base} in {} file(s)",+ files.len()+ ));+ t.updated_at = chrono::Utc::now();+ db.update_task(&t)?;+ }+ }++ if let Some(session) = task.session_name.clone() {+ if self.state.tmux_ops.window_exists(&session).unwrap_or(false) {+ let skill_cmd =+ skills::transform_plugin_command("/agtx:merge-conflicts", &task.agent);+ let prompt = format!(+ "The feature branch has merge conflicts with {base} in: {}. \+ Please resolve them now.",+ files.join(", ")+ );+ let tmux_ops = Arc::clone(&self.state.tmux_ops);+ let agent_name = task.agent.clone();+ std::thread::spawn(move || {+ send_skill_and_prompt(+ &tmux_ops,+ &session,+ &skill_cmd,+ &prompt,+ &None,+ "",+ &agent_name,+ &[],+ false,+ );+ });+ }+ }+ self.refresh_tasks()+ }+/// MCP version of transition_to_review: sends review prompt but skips PR popup.fn mcp_transition_to_review(&mut self, task: &mut Task) -> Result<()> {let (review_agent, agent_switch) = needs_agent_switch(&self.state.config, task, "review");@@ -8234,6 +8535,7 @@ impl App {t.cycle,was_ready,t.agent.clone(),+ t.phase_entered_at,)}).collect();@@ -8270,6 +8572,7 @@ impl App {cycle,was_ready,agent,+ phase_entered_at,) in tasks_to_check{let plugin =@@ -8315,7 +8618,7 @@ impl App {PhaseStatus::Working}} else if let Some(ref wt) = worktree_path {- if phase_artifact_exists(wt, status, plugin, cycle) {+ if phase_artifact_fresh(wt, status, plugin, cycle, phase_entered_at) {PhaseStatus::Ready} else {PhaseStatus::Working@@ -8324,6 +8627,23 @@ impl App {PhaseStatus::Working};+ // An artifact is written mid-turn; `Ready` waits for the turn to end+ // (`gate_ready_on_turn`). Decided here, before the copy-back below+ // acts on `Ready`, and the record is read once and reused for the+ // `Working` path further down.+ let window_alive = !window_is_gone(session_name.as_deref(), live_windows.as_ref());+ let hook_record = if window_alive+ && matches!(phase_status, PhaseStatus::Working | PhaseStatus::Ready)+ {+ worktree_path+ .as_ref()+ .and_then(|wt| hook_status::read_status(Path::new(wt), &task_id, now_secs))+ } else {+ None+ };+ let phase_status =+ gate_ready_on_turn(phase_status, hook_record.as_ref().map(|h| h.state));+// Copy-back on Working β Ready transitionif phase_status == PhaseStatus::Ready && !was_ready {if let (Some(ref wt), Some(ref pp)) = (&worktree_path, &project_path) {@@ -8355,9 +8675,7 @@ impl App {// The agent's own report of what it is doing, when it writes one.// Authoritative over the pane heuristic below.let hook_status = if phase_status == PhaseStatus::Working && !window_gone {- worktree_path- .as_ref()- .and_then(|wt| hook_status::read_status(Path::new(wt), &task_id, now_secs))+ hook_record} else {None};@@ -8473,20 +8791,25 @@ impl App {/// for the life of every agtx session, forever, on the chance a phone might/// one day connect.///- /// So it is gated twice. Without the `serve` feature there is no server in- /// this binary and nothing could ever read the table, so the call is- /// compiled out entirely. With it, publishing starts when someone actually- /// asks for a board and stops when they stop β the web server marks- /// `board_watch` on a board request, and the overlay's own child counts too,- /// since starting it is an explicit request for mobile.+ /// So publishing starts when someone actually asks for a board and stops+ /// when they stop. Two kinds of reader mark `board_watch`: the web server,+ /// on a board request β the `W` overlay's own child counts too, since+ /// starting it is an explicit request for mobile β and the MCP server, on+ /// `list_tasks` / `get_task`.+ ///+ /// The MCP reader is why this is not gated on the `serve` feature. A+ /// default build has no web server, but it always has `agtx mcp-serve`, and+ /// an orchestrator or oneshot session polling phase status is exactly the+ /// out-of-process reader this table is for. Compiling the call out would+ /// leave every such client reading a table nothing ever writes.////// The window is generous because the board no longer polls: someone can/// read it for minutes without issuing a request, and going quiet mid-read/// would freeze their phase icons rather than save anything worth having.- #[cfg(feature = "serve")]fn should_publish_runtime(&self) -> bool {const WATCH_WINDOW: i64 = 10 * 60;+ #[cfg(feature = "serve")]if self.state.serve_session.is_some() {return true;}@@ -8502,11 +8825,6 @@ impl App {.unwrap_or(false)}- #[cfg(not(feature = "serve"))]- fn should_publish_runtime(&self) -> bool {- false- }-/// Apply results from the background session refresh thread.fn apply_session_refresh(&mut self, result: SessionRefreshResult) {let now = Instant::now();@@ -8534,6 +8852,21 @@ impl App {continue;}+ // The pass snapshotted tasks before it ran, so a transition that+ // landed meanwhile leaves this verdict describing the *previous*+ // phase β Running's `execute.md` would read as `review:ready`.+ // Dropped rather than applied; the next pass, two seconds on,+ // computes it against the right phase.+ if self+ .state+ .board+ .tasks+ .iter()+ .any(|t| t.id == task_status.task_id && t.status != task_status.status)+ {+ continue;+ }+let mut phase = task_status.phase_status;// A trust prompt outranks every liveness signal below it. The agent is@@ -8630,6 +8963,7 @@ impl App {runtime_rows.push(crate::db::TaskRuntime {task_id: task_status.task_id.clone(),phase_status: phase,+ status: Some(task_status.status),pane_hash: pane.map(|(h, _)| h.to_string()),// `Instant` has no epoch, so the stored wall-clock time is// derived from how long ago the change was.@@ -9185,6 +9519,17 @@ fn cleanup_task_resources(}if let Some(session_name) = session_name {+ // Reap the pane's descendants *before* the window dies. `kill-window`+ // signals the pane's own process group, which misses anything the agent+ // backgrounded into a group of its own β a dev server, a watcher, a+ // `python3 -m http.server`. Those survive, get reparented to init, and+ // keep holding their ports long after the task is Done and its worktree+ // is gone.+ //+ // Order matters and is the whole reason this is not simply a `pkill`+ // afterwards: once the window is killed the parent links are gone and+ // the survivors can no longer be attributed to this task at all.+ reap_task_processes(task_id, session_name, tmux_ops);let _ = tmux_ops.kill_window(session_name);}if let Some(worktree) = worktree_path {@@ -9195,6 +9540,352 @@ fn cleanup_task_resources(}}+/// The paths agtx writes into a worktree, as git exclude patterns.+///+/// Must track the writers in `write_skills_to_worktree`, `write_mcp_config` and+/// `write_hook_config`. Deliberately specific rather than whole dotdirs: a+/// project may keep its own `.claude/` or `.cursor/` content, and only the+/// entries agtx creates are agtx's to hide.+const AGTX_WRITTEN_PATHS: &[&str] = &[+ ".agtx/",+ ".mcp.json",+ ".claude/settings.local.json",+ ".claude/commands/agtx/",+ ".gemini/settings.json",+ ".gemini/commands/agtx/",+ ".codex/config.toml",+ ".codex/skills/agtx-*/",+ ".cursor/mcp.json",+ ".cursor/hooks.json",+ ".cursor/skills/agtx-*/",+ ".grok/config.toml",+ ".grok/hooks/agtx.json",+ ".grok/skills/agtx-*/",+ ".agents/mcp_config.json",+ ".agents/hooks.json",+ ".agents/skills/agtx-*/",+ ".opencode/command/agtx-*.md",+ ".github/agents/agtx/",+ ".pi/mcp.json",+ ".pi/skills/agtx-*/",+];++/// Marks agtx's block in `info/exclude` so it is written once and is obvious to+/// anyone who finds it.+const AGTX_EXCLUDE_MARKER: &str = "# agtx: files agtx writes into worktrees";++/// Hide agtx's own bookkeeping from git, so it does not read as the agent's+/// uncommitted work.+///+/// Without this, `.agtx/` and the per-agent config agtx deploys show as+/// untracked in every worktree β and `has_changes`, which the Done guard reads+/// from `git status --porcelain`, counts untracked files. agtx's own writes+/// would trip agtx's own guard on a project's first task, before any+/// `.gitignore` exists, and a guard that cries wolf first and means it second+/// stops being believed.+///+/// **There is exactly one place this can go.** Measured against git 2.55.0: a+/// per-worktree `.git/worktrees/<name>/info/exclude` is *ignored*; only+/// `$GIT_COMMON_DIR/info/exclude` takes effect, and it applies to the main+/// checkout as well as every worktree.+///+/// Sharing it with the user's own checkout is safe because **exclude patterns+/// only affect untracked files** β also measured: a tracked `.mcp.json` still+/// reports its modification with `.mcp.json` excluded. So a+/// project that deliberately tracks any of these keeps tracking it, and nothing+/// a user committed can be hidden. What this changes is only whether files agtx+/// created show up as noise.+fn exclude_agtx_files_from_git(worktree: &Path) {+ let Ok(out) = std::process::Command::new("git")+ .current_dir(worktree)+ .args(["rev-parse", "--git-common-dir"])+ .output()+ else {+ return;+ };+ if !out.status.success() {+ return;+ }+ let common = String::from_utf8_lossy(&out.stdout).trim().to_string();+ if common.is_empty() {+ return;+ }+ // `--git-common-dir` answers relative to the worktree unless it is absolute.+ let common = {+ let p = Path::new(&common);+ if p.is_absolute() {+ p.to_path_buf()+ } else {+ worktree.join(p)+ }+ };++ let exclude = common.join("info").join("exclude");+ let existing = std::fs::read_to_string(&exclude).unwrap_or_default();+ if existing.contains(AGTX_EXCLUDE_MARKER) {+ return;+ }++ let mut out = existing;+ if !out.is_empty() && !out.ends_with('\n') {+ out.push('\n');+ }+ out.push_str(&format!(+ "\n{AGTX_EXCLUDE_MARKER}\n\+ # Only untracked files are affected; anything this project tracks is untouched.\n\+ # Delete this block to see them in `git status` again.\n"+ ));+ for pattern in AGTX_WRITTEN_PATHS {+ out.push_str(pattern);+ out.push('\n');+ }++ if let Some(dir) = exclude.parent() {+ if std::fs::create_dir_all(dir).is_err() {+ return;+ }+ }+ if let Err(e) = std::fs::write(&exclude, out) {+ tracing::warn!(path = %exclude.display(), error = %e, "Failed to write git exclude");+ }+}++/// Record where review got to, so the next one can read only what came after.+///+/// Written when a task leaves Review for Running β the resume path β because+/// that commit is exactly "what the last review already looked at". The next+/// review reads the file and diffs from there instead of re-reading the whole+/// branch, which it would otherwise do every cycle: `clear_context_on_advance`+/// means the review agent starts with no memory of its own previous pass.+///+/// A file in the worktree rather than a column on the task, because the only+/// reader is the review skill and it is already reading `.agtx/`. Nothing+/// queries this, so a schema change would buy nothing, and it is removed with+/// the worktree it describes.+///+/// **This is a commit, so it describes committed work only** β a phase that+/// leaves changes uncommitted is not represented here. That is why the skill+/// pairs `<marker>..HEAD` with `git status --short`: between them they cover+/// what was committed since the marker *and* whatever is still uncommitted now.+/// The two can overlap β work that was uncommitted when the marker was written+/// and committed afterwards falls into both β so such a change is reviewed+/// twice. Erring that way is deliberate: the failure mode is a redundant read,+/// never a skipped one.+///+/// The second half is `git status --short` and not `git diff HEAD` because+/// **`git diff` does not show untracked files at all**. A brand-new file from+/// the running phase is absent from the range diff (not committed) and absent+/// from the working-tree diff (not tracked), so the obvious pairing reviews it+/// in neither. `the_marker_never_covers_uncommitted_work` pins that.+///+/// Best-effort: a task with no worktree, or a repository that cannot be read,+/// simply leaves no marker and the next review falls back to the full diff β+/// which is the correct answer when the reviewed point is unknown.+fn mark_reviewed_point(task: &Task) {+ let Some(worktree) = task.worktree_path.as_deref() else {+ return;+ };+ let worktree = Path::new(worktree);+ let Ok(sha) = crate::git::head_sha(worktree) else {+ return;+ };+ let dir = worktree.join(".agtx");+ if std::fs::create_dir_all(&dir).is_err() {+ return;+ }+ if let Err(e) = std::fs::write(dir.join(REVIEWED_AT_FILE), format!("{sha}\n")) {+ tracing::warn!(task_id = %task.id, error = %e, "Failed to record the reviewed point");+ }+}++/// Terminate everything a task started, before its window and worktree go.+///+/// Two ways of finding them, because neither alone is enough:+///+/// - **By environment.** `create_window` sets `AGTX_TASK_ID` on the tmux window,+/// and a child inherits the environment at spawn and never loses it. This is+/// what catches a *daemonized* process: one reparented to init as soon as it+/// was backgrounded still carries the task id. Attribution is exact, and+/// enumerating costs ~0.1s.+/// - **By descent from the pane.** The backstop for anything that never received+/// the environment.+///+/// Walking the pane's descendants alone is not enough: a process reparented to+/// init *before* cleanup runs is no longer in the tree, so ordering the walk+/// ahead of `kill-window` β necessary, since the links vanish with the window β+/// still misses exactly the case that matters.+///+/// The alternatives were measured and rejected. A cwd scan+/// (`lsof -u <uid> -d cwd`) takes ~12s, and `lsof +D <worktree>` walks the tree+/// β 26s on a large checkout β while matching nothing once the directory is+/// gone. Session id is not readable per-process from `ps` on macOS.+///+/// Children are signalled before parents so a supervisor cannot restart one on+/// the way down. Best-effort by design: a process that has already exited is+/// skipped rather than treated as a failure. Cleanup runs on a background thread+/// after the task is already Done, and there is nothing useful to abort.+fn reap_task_processes(task_id: &str, target: &str, tmux_ops: &dyn TmuxOperations) {+ let mut victims = processes_for_task(task_id);+ for pid in pane_descendants(target, tmux_ops) {+ if !victims.contains(&pid) {+ victims.push(pid);+ }+ }+ // Never signal agtx itself. It carries no `AGTX_TASK_ID` and is not+ // descended from the pane, so this cannot currently match β it is here+ // because the cost of being wrong is killing the board mid-cleanup.+ let me = std::process::id();+ victims.retain(|pid| *pid != me);++ if victims.is_empty() {+ return;+ }+ tracing::info!(+ task_id = %task_id,+ target = %target,+ count = victims.len(),+ "Terminating processes started by a task"+ );+ signal_all(&victims, "TERM");+ std::thread::sleep(std::time::Duration::from_millis(300));+ signal_all(&victims, "KILL");+}++/// Every process carrying this task's `AGTX_TASK_ID`, however it was reparented.+///+/// Reads `/proc/<pid>/environ` where it exists and falls back to `ps -Eww`,+/// which is what macOS offers. The two cannot share one command: Linux's `ps -E`+/// means something else entirely.+fn processes_for_task(task_id: &str) -> Vec<u32> {+ let needle = format!("{}={}", hook_status::ENV_TASK_ID, task_id);++ if Path::new("/proc").is_dir() {+ let mut found = Vec::new();+ if let Ok(entries) = std::fs::read_dir("/proc") {+ for entry in entries.flatten() {+ let Some(pid) = entry+ .file_name()+ .to_str()+ .and_then(|n| n.parse::<u32>().ok())+ else {+ continue;+ };+ // NUL-separated; a lossy read is fine, the needle is ASCII.+ if let Ok(env) = std::fs::read(entry.path().join("environ")) {+ if String::from_utf8_lossy(&env)+ .split('\0')+ .any(|v| v == needle)+ {+ found.push(pid);+ }+ }+ }+ }+ return found;+ }++ // `-A` is load-bearing: without a process selector `ps` lists only the+ // processes attached to the caller's own terminal, so a daemonized orphan β+ // the entire reason this function exists β never appears. Verified against a+ // real survivor: no selector found nothing, `-A` found it.+ let Ok(out) = std::process::Command::new("ps")+ .args(["-AEww", "-o", "pid=,command="])+ .output()+ else {+ return Vec::new();+ };+ pids_matching_env(&String::from_utf8_lossy(&out.stdout), &needle)+}++/// Pick the pids out of `ps -Eww -o pid=,command=` output whose line carries+/// `needle`.+///+/// Split out because the surrounding call cannot be tested reliably: whether+/// `ps` exposes another process's environment depends on the platform and on+/// how the caller itself was launched. The parsing is what can regress, and a+/// mis-parse here signals the wrong pids to kill.+fn pids_matching_env(ps_output: &str, needle: &str) -> Vec<u32> {+ ps_output+ .lines()+ .filter(|line| line.contains(needle))+ .filter_map(|line| line.split_whitespace().next()?.parse().ok())+ .collect()+}++/// Every process descended from a task pane, deepest first.+fn pane_descendants(target: &str, tmux_ops: &dyn TmuxOperations) -> Vec<u32> {+ let Some(root) = tmux_ops.pane_pid(target) else {+ return Vec::new();+ };+ // pid 0 and pid 1 are the roots of the whole process tree β on macOS pid 0+ // is the ancestor of launchd, so `descendants_of(0)` returns *every process+ // on the machine*. A pane can never legitimately be either, so a value this+ // low means tmux answered with something that is not a pane pid, and the+ // only safe response is to reap nothing.+ if root <= 1 {+ tracing::warn!(target = %target, pane_pid = root, "Refusing to reap from a root pid");+ return Vec::new();+ }+ descendants_of(root)+}++/// Send one signal to every pid, children before parents.+///+/// Shelling out to `kill` rather than taking a `libc` dependency for two+/// signals: this file already reaches git and tmux the same way, and it keeps+/// the whole path free of `unsafe`.+fn signal_all(pids: &[u32], signal: &str) {+ if pids.is_empty() {+ return;+ }+ let mut cmd = std::process::Command::new("kill");+ cmd.arg(format!("-{signal}"));+ for pid in pids.iter().rev() {+ cmd.arg(pid.to_string());+ }+ // Non-zero here means "already gone", which is the desired end state.+ let _ = cmd.output();+}++/// Every descendant of `root`, parents before children.+///+/// Built from one `ps` snapshot rather than by walking `/proc`, which does not+/// exist on macOS. `root` itself is excluded β `kill-window` owns the pane.+fn descendants_of(root: u32) -> Vec<u32> {+ let Ok(out) = std::process::Command::new("ps")+ .args(["-Ao", "pid=,ppid="])+ .output()+ else {+ return Vec::new();+ };+ let text = String::from_utf8_lossy(&out.stdout);++ let mut children: HashMap<u32, Vec<u32>> = HashMap::new();+ for line in text.lines() {+ let mut it = line.split_whitespace();+ if let (Some(Ok(pid)), Some(Ok(ppid))) = (+ it.next().map(str::parse::<u32>),+ it.next().map(str::parse::<u32>),+ ) {+ children.entry(ppid).or_default().push(pid);+ }+ }++ let mut found = Vec::new();+ let mut queue = std::collections::VecDeque::from([root]);+ while let Some(pid) = queue.pop_front() {+ for &child in children.get(&pid).map(Vec::as_slice).unwrap_or(&[]) {+ // A cycle is impossible in a real process tree, but the snapshot is+ // read from text and a malformed row must not spin forever.+ if child != root && !found.contains(&child) {+ found.push(child);+ queue.push_back(child);+ }+ }+ }+ found+}+/// Set up a worktree and tmux window for a task./// Creates worktree, initializes it (copy files + init script), creates tmux window with agent./// Updates task fields (session_name, worktree_path, branch_name) in place.@@ -10183,6 +10874,20 @@ const REDRAW_BACKSTOP: std::time::Duration = std::time::Duration::from_secs(1);/// phase status it acts on is itself refreshed on a 2-second cache.const TRANSITION_POLL_INTERVAL: std::time::Duration = std::time::Duration::from_secs(2);+/// How long a claimed-but-unfinished transition request must sit before another+/// instance may take it over.+///+/// The window has to clear the longest legitimate wait for the serialized setup+/// slot β a queued task waits out every setup ahead of it β while still+/// recovering promptly from a TUI that died holding a queue. Five minutes is+/// well past a normal setup and well inside the hour after which+/// `cleanup_old_transition_requests` deletes the row unexecuted.+const RECLAIM_CLAIMS_AFTER: chrono::Duration = chrono::Duration::minutes(5);++/// Where the last review's end point is recorded, inside a task's `.agtx/`.+/// Read by the review skill; see [`mark_reviewed_point`].+const REVIEWED_AT_FILE: &str = "reviewed-at";+/// How long a phase status is trusted before the refresh looks again.const PHASE_STATUS_CACHE_TTL: std::time::Duration = std::time::Duration::from_secs(2);@@ -11895,6 +12600,80 @@ fn determine_phase_variant(}}+/// Whether the current phase's artifact was written *during* this phase.+///+/// Existence alone is what `phase_artifact_exists` answers, and it is the wrong+/// question after a resume: the previous cycle's `execute.md` is still on disk,+/// so a task sent back to Running would read `ready` the moment it arrived,+/// before doing any work. The artifact counts only if its mtime is at or after `entered_at`.+///+/// `phase_artifact_exists` stays for its other callers, which ask whether a+/// *prior* phase ever produced its artifact β a gating question, where any plan+/// on disk is the right answer.+///+/// Two fallbacks, both to the existence check: `entered_at` is `None` for a+/// task stored before the column existed, and a glob template names a set of+/// files rather than one, so it has no single mtime to compare.+fn phase_artifact_fresh(+ worktree_path: &str,+ status: TaskStatus,+ plugin: &Option<WorkflowPlugin>,+ cycle: i32,+ entered_at: Option<chrono::DateTime<chrono::Utc>>,+) -> bool {+ let Some(entered_at) = entered_at else {+ return phase_artifact_exists(worktree_path, status, plugin, cycle);+ };+ let rel_template = plugin.as_ref().and_then(|p| match status {+ TaskStatus::Planning => p.artifacts.planning.as_deref(),+ TaskStatus::Running => p.artifacts.running.as_deref(),+ TaskStatus::Review => p.artifacts.review.as_deref(),+ _ => None,+ });+ let Some(rel_template) = rel_template else {+ return false;+ };+ if rel_template.contains('*') {+ return artifact_path_exists(worktree_path, rel_template, cycle);+ }+ let entered_at = std::time::SystemTime::from(entered_at);+ [format!("{:02}", cycle), cycle.to_string()].iter().any(|phase_str| {+ let full = Path::new(worktree_path).join(rel_template.replace("{phase}", phase_str));+ std::fs::metadata(&full)+ .and_then(|m| m.modified())+ .is_ok_and(|mtime| mtime >= entered_at)+ })+}++/// `Ready` only once the agent's turn is over.+///+/// An agent writes its phase artifact mid-turn and keeps going β measured, a+/// reviewer wrote `review.md`, then ran `git status` and printed a summary β so+/// a fresh artifact under a live `working` report is not done yet, and a caller+/// acting on it would resume an agent that has not stopped. `blocked` likewise: the+/// artifact exists but the agent is now waiting on a person.+///+/// No timestamp comparison, deliberately. The status file holds only the latest+/// event, and writing the artifact is itself a tool call whose `PreToolUse` sets+/// `working` before the file exists, so a current `waiting`/`ended` can only have+/// come after the write. Comparing times would be worse than redundant: hook+/// `ts` is whole seconds against a sub-second mtime, and a `Stop` in the same+/// second as the write would read as older and hold the task at `working`.+///+/// It cannot hold a task forever. A turn that ends reports `waiting`; an agent+/// that exits leaves `ended` or a window that is gone; one that falls silent+/// leaves a `working` record `read_status` stops trusting after+/// `HOOK_STALE_SECS`, and `None` falls back to the artifact alone.+fn gate_ready_on_turn(phase: PhaseStatus, hook: Option<hook_status::HookState>) -> PhaseStatus {+ match (phase, hook) {+ (+ PhaseStatus::Ready,+ Some(hook_status::HookState::Working | hook_status::HookState::Blocked),+ ) => PhaseStatus::Working,+ (phase, _) => phase,+ }+}+/// Check if an artifact path exists, trying both zero-padded and non-padded {phase} substitution.fn artifact_path_exists(worktree_path: &str, rel_template: &str, cycle: i32) -> bool {// Try zero-padded first (e.g. "01"), then non-padded (e.g. "1")@@ -12093,7 +12872,7 @@ fn run_orchestrator_catchup(db: &Database, tasks: &[Task], project_path: Option<let Some(ref wt) = task.worktree_path else {continue;};- if !phase_artifact_exists(wt, task.status, &plugin, task.cycle) {+ if !phase_artifact_fresh(wt, task.status, &plugin, task.cycle, task.phase_entered_at) {continue;}let short_id = if task.id.len() >= 8 {@@ -12436,20 +13215,6 @@ fn scoped_indicators_for(agent_name: Option<&str>) -> &'static [&'static str] {/// How many lines from the bottom of a capture count as "live now".const PANE_TAIL_LINES: usize = 5;-/// The bottom `n` lines of a captured pane, trailing blank rows dropped first.-///-/// `capture-pane -p` emits one line per pane *row*, so the raw end of a capture-/// is padding whenever the agent's output has not filled the pane; anchoring the-/// window there would look at nothing. Same reasoning as `composer_holds`.-fn pane_tail(content: &str, n: usize) -> String {- let mut lines: Vec<&str> = content.lines().collect();- while lines.last().is_some_and(|l| l.trim().is_empty()) {- lines.pop();- }- let start = lines.len().saturating_sub(n);- lines[start..].join("\n")-}-/// Per-launch state for [`dismiss_launch_dialog`].#[derive(Default)]struct LaunchDialogState {@@ -13011,6 +13776,10 @@ fn write_skills_to_worktree(agent_names: &[&str],agent_hooks: bool,) {+ // Before anything else agtx writes here, so the files below are invisible to+ // git the moment they appear.+ exclude_agtx_files_from_git(Path::new(worktree_path));+// Replay the project's existing trust onto this worktree, for the one agent// that needs it. Antigravity matches trusted paths **exactly** β no ancestor// inheritance at any depth β so a user who already trusted the project woulddiff --git a/src/tui/app_tests.rs b/src/tui/app_tests.rsindex 17abfbc..0b9d778 100644--- a/src/tui/app_tests.rs+++ b/src/tui/app_tests.rs@@ -316,6 +316,7 @@ fn test_create_pr_with_content_success() {referenced_tasks: None,escalation_note: None,base_branch: None,+ phase_entered_at: None,created_at: chrono::Utc::now(),updated_at: chrono::Utc::now(),};@@ -415,6 +416,7 @@ fn test_create_pr_with_content_no_changes() {referenced_tasks: None,escalation_note: None,base_branch: None,+ phase_entered_at: None,created_at: chrono::Utc::now(),updated_at: chrono::Utc::now(),};@@ -473,6 +475,7 @@ fn test_create_pr_with_content_push_failure() {referenced_tasks: None,escalation_note: None,base_branch: None,+ phase_entered_at: None,created_at: chrono::Utc::now(),updated_at: chrono::Utc::now(),};@@ -537,6 +540,7 @@ fn test_push_changes_to_existing_pr_success() {referenced_tasks: None,escalation_note: None,base_branch: None,+ phase_entered_at: None,created_at: chrono::Utc::now(),updated_at: chrono::Utc::now(),};@@ -592,6 +596,7 @@ fn test_push_changes_to_existing_pr_no_changes() {referenced_tasks: None,escalation_note: None,base_branch: None,+ phase_entered_at: None,created_at: chrono::Utc::now(),updated_at: chrono::Utc::now(),};@@ -630,6 +635,7 @@ fn test_push_changes_to_existing_pr_no_url() {referenced_tasks: None,escalation_note: None,base_branch: None,+ phase_entered_at: None,created_at: chrono::Utc::now(),updated_at: chrono::Utc::now(),};@@ -10476,6 +10482,9 @@ fn test_run_orchestrator_catchup_emits_for_planning_artifact() {let mut task = Task::new("compose release notes", "claude", "proj");task.id = "abcdef1234".to_string();task.status = TaskStatus::Planning;+ // Entered Planning before the plan was written, as a real task does: an+ // artifact that predates its phase counts for nothing (`phase_artifact_fresh`).+ task.phase_entered_at = Some(chrono::Utc::now() - chrono::Duration::minutes(1));task.worktree_path = Some(tmp.to_string_lossy().to_string());task.plugin = None; // None β bundled agtx plugindb.create_task(&task).unwrap();@@ -10619,6 +10628,9 @@ fn test_detect_existing_orchestrator_runs_catchup() {let mut task = Task::new("compose release notes", "claude", "proj");task.id = "abcdef1234".to_string();task.status = TaskStatus::Planning;+ // Entered Planning before the plan was written, as a real task does: an+ // artifact that predates its phase counts for nothing (`phase_artifact_fresh`).+ task.phase_entered_at = Some(chrono::Utc::now() - chrono::Duration::minutes(1));task.worktree_path = Some(tmp.to_string_lossy().to_string());task.plugin = None;db.create_task(&task).unwrap();@@ -11346,6 +11358,14 @@ fn test_cleanup_task_resources_archives_md_files() {#[cfg(feature = "test-mocks")]fn test_cleanup_task_resources_kills_window_and_removes_worktree() {let mut mock_tmux = MockTmuxOperations::new();+ // Asked before the window dies, so the pane's descendants can still be+ // attributed to this task. `None` β tmux cannot answer β is the case where+ // cleanup has nothing to reap and must carry on regardless.+ mock_tmux+ .expect_pane_pid()+ .with(mockall::predicate::eq("proj:task-win"))+ .times(1)+ .returning(|_| None);mock_tmux.expect_kill_window().with(mockall::predicate::eq("proj:task-win"))@@ -16069,3 +16089,998 @@ fn queued_completion_allows_clean_worktree() {.error.is_none());}++// =============================================================================+// Serialized worktree setup β the single slot, and what queues for it+// =============================================================================++/// Occupy the setup slot the way a real setup does, without running one.+#[cfg(feature = "test-mocks")]+fn occupy_setup_slot(app: &mut App) -> mpsc::Sender<SetupResult> {+ let (tx, rx) = mpsc::channel::<SetupResult>();+ app.state.setup_rx = Some(rx);+ tx+}++/// Worktree setup runs one at a time. A caller that asks for several Backlog+/// transitions in one pass β the dependency overlay, or an MCP client moving a+/// wave of tasks β must have them all queued: a task rejected for arriving+/// while the slot is busy stays in Backlog with nothing retrying it, after+/// `move_task` has already answered `queued`.+#[test]+#[cfg(feature = "test-mocks")]+fn backlog_transitions_queue_behind_a_busy_setup_slot() {+ let _data = redirect_data_dir();+ let _config = redirect_config_dir();+ let dir = tempfile::tempdir().unwrap();+ let mut app = make_test_app_at(dir.path());+ let _slot = occupy_setup_slot(&mut app);++ let db = app.state.db.as_ref().unwrap();+ let mut ids = Vec::new();+ for title in ["one", "two", "three"] {+ let task = Task::new(title, "claude", "p1");+ db.create_task(&task).unwrap();+ ids.push(task.id);+ }++ for id in &ids {+ let req = TransitionRequest::new(id, "move_to_planning");+ app.state+ .db+ .as_ref()+ .unwrap()+ .create_transition_request(&req)+ .unwrap();+ let outcome = app.execute_transition_request(&req).unwrap();++ assert_eq!(+ outcome,+ TransitionOutcome::Queued,+ "a Backlog transition goes through the queue, busy slot or not"+ );++ // Still claimed and unprocessed, so `get_transition_status` answers+ // `pending` β the task has not moved yet, and saying `completed` here+ // would tell a caller that it had.+ let stored = app+ .state+ .db+ .as_ref()+ .unwrap()+ .get_transition_request(&req.id)+ .unwrap()+ .unwrap();+ assert!(stored.processed_at.is_none());+ assert!(stored.error.is_none());+ }++ let queued: Vec<&str> = app+ .state+ .setup_queue+ .iter()+ .map(|q| q.task_id.as_str())+ .collect();+ assert_eq!(queued, ids.iter().map(String::as_str).collect::<Vec<_>>());+ assert!(app+ .state+ .setup_queue+ .iter()+ .all(|q| q.intent == SetupIntent::Planning));+}++/// The intent travels with the task because the two callers disagree about+/// where a Backlog task should land: the overlay lets the plugin choose, while+/// an MCP request names one transition and must not be answered with another.+#[test]+#[cfg(feature = "test-mocks")]+fn each_queued_task_keeps_the_intent_it_was_queued_with() {+ let _data = redirect_data_dir();+ let _config = redirect_config_dir();+ let dir = tempfile::tempdir().unwrap();+ let mut app = make_test_app_at(dir.path());+ let _slot = occupy_setup_slot(&mut app);++ app.enqueue_setup("a", SetupIntent::Research, None);+ app.enqueue_setup("b", SetupIntent::Running, None);+ app.enqueue_setup("c", SetupIntent::PluginDefault, None);++ let got: Vec<(&str, SetupIntent)> = app+ .state+ .setup_queue+ .iter()+ .map(|q| (q.task_id.as_str(), q.intent))+ .collect();+ assert_eq!(+ got,+ vec![+ ("a", SetupIntent::Research),+ ("b", SetupIntent::Running),+ ("c", SetupIntent::PluginDefault),+ ]+ );+}++/// Queuing a task twice would set its worktree up twice. The duplicate's+/// request is resolved rather than dropped, so a caller polling it is not left+/// waiting on a row nothing will ever touch.+#[test]+#[cfg(feature = "test-mocks")]+fn a_task_queued_twice_is_queued_once_and_the_duplicate_is_answered() {+ let _data = redirect_data_dir();+ let _config = redirect_config_dir();+ let dir = tempfile::tempdir().unwrap();+ let mut app = make_test_app_at(dir.path());+ let _slot = occupy_setup_slot(&mut app);++ let task = Task::new("only once", "claude", "p1");+ app.state.db.as_ref().unwrap().create_task(&task).unwrap();++ let first = TransitionRequest::new(&task.id, "move_to_planning");+ let second = TransitionRequest::new(&task.id, "move_to_running");+ for req in [&first, &second] {+ app.state+ .db+ .as_ref()+ .unwrap()+ .create_transition_request(req)+ .unwrap();+ app.execute_transition_request(req).unwrap();+ }++ assert_eq!(app.state.setup_queue.len(), 1);+ assert_eq!(app.state.setup_queue[0].intent, SetupIntent::Planning);++ let db = app.state.db.as_ref().unwrap();+ assert!(db+ .get_transition_request(&first.id)+ .unwrap()+ .unwrap()+ .processed_at+ .is_none());+ let dup = db.get_transition_request(&second.id).unwrap().unwrap();+ assert!(dup.processed_at.is_some());+ assert!(dup.error.is_some(), "the duplicate says why it did nothing");+}++/// A queued request outlives the state it was accepted against. Every way the+/// drain can decline one has to resolve it β dropping it silently leaves a+/// caller polling `pending` forever.+#[test]+#[cfg(feature = "test-mocks")]+fn a_queued_task_that_left_backlog_resolves_its_request_with_an_error() {+ let _data = redirect_data_dir();+ let _config = redirect_config_dir();+ let dir = tempfile::tempdir().unwrap();+ let mut app = make_test_app_at(dir.path());+ let slot = occupy_setup_slot(&mut app);++ let mut task = Task::new("moved on", "claude", "p1");+ app.state.db.as_ref().unwrap().create_task(&task).unwrap();+ let req = TransitionRequest::new(&task.id, "move_to_planning");+ app.state+ .db+ .as_ref()+ .unwrap()+ .create_transition_request(&req)+ .unwrap();+ app.execute_transition_request(&req).unwrap();+ assert_eq!(app.state.setup_queue.len(), 1);++ // The task advances by some other route while it waits its turn.+ task.status = TaskStatus::Running;+ app.state.db.as_ref().unwrap().update_task(&task).unwrap();++ // Free the slot and drain.+ drop(slot);+ app.state.setup_rx = None;+ app.try_start_next_queued_setup().unwrap();++ assert!(app.state.setup_queue.is_empty());+ let stored = app+ .state+ .db+ .as_ref()+ .unwrap()+ .get_transition_request(&req.id)+ .unwrap()+ .unwrap();+ assert!(stored.processed_at.is_some());+ assert!(+ stored.error.as_deref().unwrap_or_default().contains("Backlog"),+ "the error says what changed: {:?}",+ stored.error+ );+}++// =============================================================================+// move_to_done_and_merge β landing a branch in the project's own checkout+// =============================================================================++/// A git repo on `main` with one commit, at `dir`.+#[cfg(feature = "test-mocks")]+fn init_repo_at(dir: &std::path::Path) {+ let git = |args: &[&str]| {+ std::process::Command::new("git")+ .current_dir(dir)+ .args(args)+ .output()+ .unwrap();+ };+ git(&["init", "-q"]);+ git(&["config", "user.email", "[email protected]"]);+ git(&["config", "user.name", "Test User"]);+ std::fs::write(dir.join("README.md"), "# base\n").unwrap();+ git(&["add", "."]);+ git(&["commit", "-qm", "initial"]);+ git(&["branch", "-M", "main"]);+}++/// A conflict must not cost the task its worktree. Done removes it, and the+/// worktree is exactly where the agent that wrote the branch has to resolve the+/// conflict β so the task stays in Review, carrying a note the board can show.+#[test]+#[cfg(feature = "test-mocks")]+fn a_conflicting_merge_leaves_the_task_in_review_with_a_note() {+ let _data = redirect_data_dir();+ let _config = redirect_config_dir();+ let dir = tempfile::tempdir().unwrap();+ init_repo_at(dir.path());+ let git = |args: &[&str]| {+ std::process::Command::new("git")+ .current_dir(dir.path())+ .args(args)+ .output()+ .unwrap();+ };++ // Two edits to the same line, from the same starting point.+ git(&["checkout", "-q", "-b", "task/thing"]);+ std::fs::write(dir.path().join("README.md"), "# from the task\n").unwrap();+ git(&["commit", "-qam", "task edit"]);+ git(&["checkout", "-q", "main"]);+ std::fs::write(dir.path().join("README.md"), "# from main\n").unwrap();+ git(&["commit", "-qam", "main edit"]);++ let mut app = make_test_app_at(dir.path());+ let mut task = Task::new("the thing", "claude", "p1");+ task.status = TaskStatus::Review;+ task.branch_name = Some("task/thing".to_string());+ task.base_branch = Some("main".to_string());+ // No session: the tmux send is skipped, but the note is not β a task whose+ // agent has already exited is when that note matters most.+ app.state.db.as_ref().unwrap().create_task(&task).unwrap();++ let req = TransitionRequest::new(&task.id, "move_to_done_and_merge");+ let err = app.execute_transition_request(&req).unwrap_err().to_string();+ assert!(err.contains("conflicts"), "{err}");+ assert!(err.contains("README.md"), "{err}");++ let stored = app+ .state+ .db+ .as_ref()+ .unwrap()+ .get_task(&task.id)+ .unwrap()+ .unwrap();+ assert_eq!(stored.status, TaskStatus::Review);+ assert!(stored+ .escalation_note+ .as_deref()+ .unwrap_or_default()+ .contains("Merge conflicts"));++ // The user's checkout is untouched: no half-finished merge, no lost edit.+ assert!(!dir.path().join(".git").join("MERGE_HEAD").exists());+ assert_eq!(+ std::fs::read_to_string(dir.path().join("README.md")).unwrap(),+ "# from main\n"+ );+}++/// The refusal is about the *project checkout*, and it must not be worked+/// around: agtx does not switch the user's branch or stash their work to land a+/// merge.+#[test]+#[cfg(feature = "test-mocks")]+fn merging_into_a_checkout_on_the_wrong_branch_is_refused_and_changes_nothing() {+ let _data = redirect_data_dir();+ let _config = redirect_config_dir();+ let dir = tempfile::tempdir().unwrap();+ init_repo_at(dir.path());+ let git = |args: &[&str]| {+ std::process::Command::new("git")+ .current_dir(dir.path())+ .args(args)+ .output()+ .unwrap();+ };+ git(&["checkout", "-q", "-b", "task/thing"]);+ std::fs::write(dir.path().join("feature.txt"), "work\n").unwrap();+ git(&["add", "."]);+ git(&["commit", "-qm", "task work"]);+ // The user is left somewhere that is neither main nor the task branch.+ git(&["checkout", "-q", "-b", "user-was-here", "main"]);++ let mut app = make_test_app_at(dir.path());+ let mut task = Task::new("the thing", "claude", "p1");+ task.status = TaskStatus::Review;+ task.branch_name = Some("task/thing".to_string());+ task.base_branch = Some("main".to_string());+ app.state.db.as_ref().unwrap().create_task(&task).unwrap();++ let req = TransitionRequest::new(&task.id, "move_to_done_and_merge");+ let err = app.execute_transition_request(&req).unwrap_err().to_string();+ assert!(err.contains("user-was-here"), "{err}");+ assert!(err.contains("Nothing was changed"), "{err}");++ let stored = app+ .state+ .db+ .as_ref()+ .unwrap()+ .get_task(&task.id)+ .unwrap()+ .unwrap();+ assert_eq!(stored.status, TaskStatus::Review);+ assert!(!dir.path().join("feature.txt").exists());+ let branch = String::from_utf8_lossy(+ &std::process::Command::new("git")+ .current_dir(dir.path())+ .args(["rev-parse", "--abbrev-ref", "HEAD"])+ .output()+ .unwrap()+ .stdout,+ )+ .trim()+ .to_string();+ assert_eq!(branch, "user-was-here", "the user's branch is left alone");+}++/// The pane is inspected *before* `kill_window`, because once the window is gone+/// the parent links are gone with it. Necessary but not sufficient β a process+/// reparented to init earlier is already out of the tree, which is what the+/// environment lookup in `processes_for_task` exists to catch.+#[test]+#[cfg(feature = "test-mocks")]+fn cleanup_reaps_pane_descendants_before_killing_the_window() {+ use std::sync::atomic::{AtomicUsize, Ordering as AtomicOrdering};+ static SEQ: AtomicUsize = AtomicUsize::new(0);+ static PANE_PID_AT: AtomicUsize = AtomicUsize::new(0);+ static KILL_AT: AtomicUsize = AtomicUsize::new(0);+ SEQ.store(0, AtomicOrdering::SeqCst);++ let mut mock_tmux = MockTmuxOperations::new();+ mock_tmux.expect_pane_pid().times(1).returning(|_| {+ PANE_PID_AT.store(SEQ.fetch_add(1, AtomicOrdering::SeqCst), AtomicOrdering::SeqCst);+ None+ });+ mock_tmux.expect_kill_window().times(1).returning(|_| {+ KILL_AT.store(SEQ.fetch_add(1, AtomicOrdering::SeqCst), AtomicOrdering::SeqCst);+ Ok(())+ });++ let mut mock_git = MockGitOperations::new();+ mock_git+ .expect_remove_worktree()+ .times(1)+ .returning(|_, _| Ok(()));++ cleanup_task_resources(+ "task-id",+ "claude",+ &Some("task/branch".to_string()),+ &Some("proj:task-win".to_string()),+ &Some("/tmp/wt".to_string()),+ None,+ Path::new("/tmp/proj"),+ &mock_tmux,+ &mock_git,+ );++ assert!(+ PANE_PID_AT.load(AtomicOrdering::SeqCst) < KILL_AT.load(AtomicOrdering::SeqCst),+ "the pane must be inspected before it is destroyed"+ );+}++/// `descendants_of` walks a real `ps` snapshot, and pid 0 is the ancestor of+/// every process on macOS β so asked for the tree under a root pid it returns+/// the entire machine. Reaping from there would kill the user's session, their+/// editor, and agtx itself.+///+/// The guard lives in `pane_descendants` rather than in `descendants_of`,+/// which is an honest tree walk and correct as written. This test pins the+/// hazard so nobody moves the check or feeds it an unvalidated pid.+#[test]+#[cfg(feature = "test-mocks")]+fn a_root_pid_is_refused_rather_than_reaped() {+ assert!(+ !descendants_of(0).is_empty(),+ "pid 0 really is the ancestor of everything β that is why the guard exists"+ );++ let mut mock_tmux = MockTmuxOperations::new();+ mock_tmux.expect_pane_pid().times(1).returning(|_| Some(0));+ mock_tmux.expect_kill_window().times(1).returning(|_| Ok(()));+ let mut mock_git = MockGitOperations::new();+ mock_git+ .expect_remove_worktree()+ .times(1)+ .returning(|_, _| Ok(()));++ // Reaching `kill_window` at all proves the reap declined and returned+ // rather than signalling the tree it found.+ cleanup_task_resources(+ "task-id",+ "claude",+ &None,+ &Some("proj:task-win".to_string()),+ &Some("/tmp/wt".to_string()),+ None,+ Path::new("/tmp/proj"),+ &mock_tmux,+ &mock_git,+ );+}++// =============================================================================+// Incremental re-review β recording where the last review got to+// =============================================================================++/// A resume from Review records the commit the last review covered, so the next+/// one reads only what came after it. Without this the review agent re-reads the+/// whole branch every cycle: `clear_context_on_advance` clears its memory of its+/// own previous pass, so it has nothing else to go on.+#[test]+#[cfg(feature = "test-mocks")]+fn leaving_review_records_the_reviewed_commit() {+ let dir = tempfile::tempdir().unwrap();+ let wt = dir.path();+ let git = |args: &[&str]| {+ std::process::Command::new("git")+ .current_dir(wt)+ .args(args)+ .output()+ .unwrap();+ };+ git(&["init", "-q"]);+ git(&["config", "user.email", "[email protected]"]);+ git(&["config", "user.name", "T"]);+ git(&["commit", "-q", "--allow-empty", "-m", "reviewed work"]);++ let mut task = Task::new("reviewed thing", "claude", "p1");+ task.worktree_path = Some(wt.to_string_lossy().to_string());++ mark_reviewed_point(&task);++ let recorded = std::fs::read_to_string(wt.join(".agtx").join(REVIEWED_AT_FILE)).unwrap();+ let head = crate::git::head_sha(wt).unwrap();+ assert_eq!(recorded.trim(), head);+}++/// A later resume moves the marker forward, so cycle three reviews only what+/// cycle two produced rather than everything since the first review.+#[test]+#[cfg(feature = "test-mocks")]+fn a_second_resume_moves_the_marker_forward() {+ let dir = tempfile::tempdir().unwrap();+ let wt = dir.path();+ let git = |args: &[&str]| {+ std::process::Command::new("git")+ .current_dir(wt)+ .args(args)+ .output()+ .unwrap();+ };+ git(&["init", "-q"]);+ git(&["config", "user.email", "[email protected]"]);+ git(&["config", "user.name", "T"]);+ git(&["commit", "-q", "--allow-empty", "-m", "first"]);++ let mut task = Task::new("thing", "claude", "p1");+ task.worktree_path = Some(wt.to_string_lossy().to_string());+ mark_reviewed_point(&task);+ let first = std::fs::read_to_string(wt.join(".agtx").join(REVIEWED_AT_FILE)).unwrap();++ git(&["commit", "-q", "--allow-empty", "-m", "addressed the feedback"]);+ mark_reviewed_point(&task);+ let second = std::fs::read_to_string(wt.join(".agtx").join(REVIEWED_AT_FILE)).unwrap();++ assert_ne!(first.trim(), second.trim());+ assert_eq!(second.trim(), crate::git::head_sha(wt).unwrap());+}++/// No worktree means no marker, and the next review falls back to the full diff+/// β the right answer when the reviewed point is unknown. It must not panic or+/// leave a marker pointing at some other repository.+#[test]+#[cfg(feature = "test-mocks")]+fn a_task_with_no_worktree_records_nothing() {+ let task = Task::new("no worktree", "claude", "p1");+ mark_reviewed_point(&task); // must not panic+ assert!(task.worktree_path.is_none());+}++/// The marker is a commit, so a phase that leaves work uncommitted is not+/// represented in it. That is why the review skill pairs `<marker>..HEAD` with+/// `git status --short`: this test pins the property those two rely on β the+/// marker never advances past uncommitted work β and why the second half cannot+/// be `git diff HEAD`, which does not show an untracked file at all.+#[test]+#[cfg(feature = "test-mocks")]+fn the_marker_never_covers_uncommitted_work() {+ let dir = tempfile::tempdir().unwrap();+ let wt = dir.path();+ let git = |args: &[&str]| {+ std::process::Command::new("git")+ .current_dir(wt)+ .args(args)+ .output()+ .unwrap();+ };+ git(&["init", "-q"]);+ git(&["config", "user.email", "[email protected]"]);+ git(&["config", "user.name", "T"]);+ std::fs::write(wt.join("a.txt"), "reviewed\n").unwrap();+ git(&["add", "."]);+ git(&["commit", "-q", "-m", "committed work"]);++ // The running phase leaves this behind without committing it.+ std::fs::write(wt.join("b.txt"), "not committed\n").unwrap();++ let mut task = Task::new("thing", "claude", "p1");+ task.worktree_path = Some(wt.to_string_lossy().to_string());+ mark_reviewed_point(&task);++ let marker = std::fs::read_to_string(wt.join(".agtx").join(REVIEWED_AT_FILE)).unwrap();+ let marker = marker.trim();++ // `<marker>..HEAD` is empty β the marker *is* HEAD β so the uncommitted file+ // is invisible to that half...+ let ranged = std::process::Command::new("git")+ .current_dir(wt)+ .args(["diff", "--name-only", &format!("{marker}..HEAD")])+ .output()+ .unwrap();+ assert!(String::from_utf8_lossy(&ranged.stdout).trim().is_empty());++ // ...and `git diff HEAD` does not catch it either: an untracked file is+ // invisible to `git diff` entirely. That is the trap this test exists for β+ // the obvious pairing would have left new files reviewed by neither half.+ let dirty = std::process::Command::new("git")+ .current_dir(wt)+ .args(["diff", "--name-only", "HEAD"])+ .output()+ .unwrap();+ assert!(+ !String::from_utf8_lossy(&dirty.stdout).contains("b.txt"),+ "if this ever passes, git changed and the skill can be simplified"+ );++ // `git status --short` is what actually sees it, which is why the skill+ // asks for that rather than a second diff.+ let status = std::process::Command::new("git")+ .current_dir(wt)+ .args(["status", "--short"])+ .output()+ .unwrap();+ let status = String::from_utf8_lossy(&status.stdout);+ assert!(status.contains("b.txt"), "{status}");+ assert!(status.contains("??"), "reported as untracked: {status}");+}++/// The refusal names the action that was asked for, rather than reading as+/// though the caller requested a different one.+#[test]+#[cfg(feature = "test-mocks")]+fn refusing_a_merge_names_the_merge_and_the_way_out() {+ let _data = redirect_data_dir();+ let _config = redirect_config_dir();+ let dir = tempfile::tempdir().unwrap();+ init_repo_at(dir.path());+ let mut app = make_test_app_at(dir.path());++ // Running is the state this is actually reached from: `resume` puts a task+ // back here, and a caller then tries to merge without returning to Review.+ let mut task = Task::new("mid-flight", "claude", "p1");+ task.status = TaskStatus::Running;+ app.state.db.as_ref().unwrap().create_task(&task).unwrap();++ let req = TransitionRequest::new(&task.id, "move_to_done_and_merge");+ let err = app.execute_transition_request(&req).unwrap_err().to_string();++ assert!(err.contains("merge"), "names the action asked for: {err}");+ assert!(err.contains("running"), "names the state it is in: {err}");+ assert!(err.contains("Review first"), "names the way out: {err}");+}++/// An App whose git ops report a worktree as dirty or clean on demand.+///+/// `make_test_app_at` leaves `has_changes` unmocked, which is fine until a test+/// exercises a path that asks it β every route to Done does.+#[cfg(feature = "test-mocks")]+fn make_test_app_with_dirty_worktree(project: &std::path::Path, dirty: bool) -> App {+ let mut mock_tmux = MockTmuxOperations::new();+ mock_tmux.expect_window_exists().returning(|_| Ok(false));+ mock_tmux.expect_has_session().returning(|_| false);++ let mut mock_git = MockGitOperations::new();+ mock_git.expect_has_changes().returning(move |_| dirty);++ App::new_for_test(+ Some(project.to_path_buf()),+ Arc::new(mock_tmux),+ Arc::new(mock_git),+ Arc::new(MockGitProviderOperations::new()),+ Arc::new(MockAgentRegistry::new()),+ )+ .unwrap()+}++/// Reaching Done deletes the worktree, and `has_changes` reads+/// `git status --porcelain`, which counts **untracked** files. An agent that+/// wrote its work and never committed has all of it there and nowhere else, so+/// a route to Done that skips the guard destroys it.+#[test]+#[cfg(feature = "test-mocks")]+fn every_route_to_done_refuses_a_worktree_with_uncommitted_work() {+ for action in ["move_to_done", "move_to_done_and_merge", "move_forward"] {+ let _data = redirect_data_dir();+ let _config = redirect_config_dir();+ let dir = tempfile::tempdir().unwrap();+ init_repo_at(dir.path());++ // Work the agent wrote and never committed β untracked, so only+ // `git status` sees it.+ std::fs::write(dir.path().join("uncommitted.js"), "the whole feature\n").unwrap();++ // `has_changes` is the real guard's input; production reads+ // `git status --porcelain`, which counts the untracked file above.+ let mut app = make_test_app_with_dirty_worktree(dir.path(), true);+ let mut task = Task::new("wrote but never committed", "claude", "p1");+ task.status = TaskStatus::Review;+ task.branch_name = Some("task/thing".to_string());+ task.base_branch = Some("main".to_string());+ task.worktree_path = Some(dir.path().to_string_lossy().to_string());+ app.state.db.as_ref().unwrap().create_task(&task).unwrap();++ let req = TransitionRequest::new(&task.id, action);+ let err = app+ .execute_transition_request(&req)+ .expect_err(&format!("{action} must refuse to destroy uncommitted work"))+ .to_string();+ assert!(err.contains("Uncommitted changes"), "{action}: {err}");++ let stored = app+ .state+ .db+ .as_ref()+ .unwrap()+ .get_task(&task.id)+ .unwrap()+ .unwrap();+ assert_eq!(stored.status, TaskStatus::Review, "{action} left Review");+ assert!(+ dir.path().join("uncommitted.js").exists(),+ "{action} destroyed the work"+ );+ }+}++/// Second layer, for when the tree is clean but the branch is empty: merging+/// lands nothing, so Done would be reached on the strength of a merge that did+/// not happen.+#[test]+#[cfg(feature = "test-mocks")]+fn merging_an_empty_branch_refuses_instead_of_reaching_done() {+ let _data = redirect_data_dir();+ let _config = redirect_config_dir();+ let dir = tempfile::tempdir().unwrap();+ init_repo_at(dir.path());+ std::process::Command::new("git")+ .current_dir(dir.path())+ .args(["branch", "task/empty"])+ .output()+ .unwrap();++ // Clean tree β the first layer passes, and the empty branch must still stop it.+ let mut app = make_test_app_with_dirty_worktree(dir.path(), false);+ let mut task = Task::new("produced nothing", "claude", "p1");+ task.status = TaskStatus::Review;+ task.branch_name = Some("task/empty".to_string());+ task.base_branch = Some("main".to_string());+ task.worktree_path = Some(dir.path().to_string_lossy().to_string());+ app.state.db.as_ref().unwrap().create_task(&task).unwrap();++ let req = TransitionRequest::new(&task.id, "move_to_done_and_merge");+ let err = app.execute_transition_request(&req).unwrap_err().to_string();++ assert!(err.contains("no commits"), "{err}");+ assert!(err.contains("uncommitted"), "says where the work would be: {err}");+ let stored = app+ .state+ .db+ .as_ref()+ .unwrap()+ .get_task(&task.id)+ .unwrap()+ .unwrap();+ assert_eq!(stored.status, TaskStatus::Review);+}++++/// The parse behind `processes_for_task`. Split out because whether `ps` will+/// expose another process's environment depends on the platform and on how the+/// caller was launched β but a mis-parse here signals the wrong pids to kill,+/// which is worth pinning regardless.+///+/// The format is `ps -Eww -o pid=,command=`: leading pid, then the command line+/// with the environment appended.+#[test]+#[cfg(feature = "test-mocks")]+fn task_id_lookup_matches_only_the_task_that_owns_the_process() {+ let out = "\+ 501 python3 -m http.server 8137 AGTX_TASK_ID=aaa AGTX_WORKTREE=/w/aaa+ 502 node server.js AGTX_TASK_ID=bbb AGTX_WORKTREE=/w/bbb+ 503 vim notes.md+ 1234 python3 -m http.server 9000 AGTX_TASK_ID=aaa+";+ assert_eq!(pids_matching_env(out, "AGTX_TASK_ID=aaa"), vec![501, 1234]);+ assert_eq!(pids_matching_env(out, "AGTX_TASK_ID=bbb"), vec![502]);+ assert!(+ pids_matching_env(out, "AGTX_TASK_ID=ccc").is_empty(),+ "an unknown task owns nothing"+ );+}++/// A task id that is a prefix of another must not sweep up its processes β+/// that would kill a live task's server because its id starts the same way.+#[test]+#[cfg(feature = "test-mocks")]+fn a_task_id_prefix_does_not_match_a_longer_id() {+ let out = "\+ 501 srv AGTX_TASK_ID=abc123+ 502 srv AGTX_TASK_ID=abc+";+ // The needle carries the `=`, so matching is on the full assignment; only a+ // genuinely longer *value* can still collide, which is why ids are UUIDs.+ assert_eq!(pids_matching_env(out, "AGTX_TASK_ID=abc123"), vec![501]);+}++/// Empty or unreadable `ps` output must yield nothing rather than panic β the+/// reap runs on a cleanup thread where there is nothing useful to abort.+#[test]+#[cfg(feature = "test-mocks")]+fn task_id_lookup_survives_junk_input() {+ assert!(pids_matching_env("", "AGTX_TASK_ID=x").is_empty());+ assert!(pids_matching_env("not a ps line at all\n", "AGTX_TASK_ID=x").is_empty());+ assert!(pids_matching_env(" AGTX_TASK_ID=x no pid here\n", "AGTX_TASK_ID=x").is_empty());+}++/// agtx's own writes must not read as the agent's uncommitted work. Without the+/// exclude, `.agtx/` and the deployed agent configs show as untracked in every+/// worktree, and `has_changes` β which the Done guard reads from+/// `git status --porcelain` β counts untracked files, so agtx's bookkeeping+/// would trip agtx's own guard on a project's first task.+#[test]+#[cfg(feature = "test-mocks")]+fn agtx_files_are_hidden_from_git_in_a_worktree() {+ let dir = tempfile::tempdir().unwrap();+ let repo = dir.path();+ let git = |cwd: &std::path::Path, args: &[&str]| {+ std::process::Command::new("git")+ .current_dir(cwd)+ .args(args)+ .output()+ .unwrap()+ };+ git(repo, &["init", "-q"]);+ git(repo, &["config", "user.email", "[email protected]"]);+ git(repo, &["config", "user.name", "T"]);+ git(repo, &["commit", "-q", "--allow-empty", "-m", "init"]);+ git(repo, &["worktree", "add", "-q", "wt", "-b", "feat"]);+ let wt = repo.join("wt");++ // What agtx deploys into a worktree.+ std::fs::create_dir_all(wt.join(".agtx/status")).unwrap();+ std::fs::write(wt.join(".agtx/status/t.json"), "{}").unwrap();+ std::fs::write(wt.join(".mcp.json"), "{}").unwrap();++ let dirty = |p: &std::path::Path| {+ String::from_utf8_lossy(&git(p, &["status", "--porcelain"]).stdout).to_string()+ };+ assert!(!dirty(&wt).is_empty(), "precondition: agtx files show as noise");++ exclude_agtx_files_from_git(&wt);++ assert_eq!(dirty(&wt), "", "agtx's own files must be invisible to git");+ // The agent's real work is untouched by the exclude.+ std::fs::write(wt.join("feature.js"), "export const x = 1;\n").unwrap();+ assert!(+ dirty(&wt).contains("feature.js"),+ "the agent's work must still be visible: {:?}",+ dirty(&wt)+ );+}++/// Writing it twice must not append twice β worktree setup runs again on an+/// agent switch, and a file that grows a block per switch is its own bug.+#[test]+#[cfg(feature = "test-mocks")]+fn the_git_exclude_block_is_written_once() {+ let dir = tempfile::tempdir().unwrap();+ let repo = dir.path();+ std::process::Command::new("git")+ .current_dir(repo)+ .args(["init", "-q"])+ .output()+ .unwrap();++ exclude_agtx_files_from_git(repo);+ let after_first = std::fs::read_to_string(repo.join(".git/info/exclude")).unwrap();+ exclude_agtx_files_from_git(repo);+ let after_second = std::fs::read_to_string(repo.join(".git/info/exclude")).unwrap();++ assert_eq!(after_first, after_second);+ assert_eq!(after_second.matches(AGTX_EXCLUDE_MARKER).count(), 1);+}++/// A project that deliberately tracks one of these keeps tracking it: exclude+/// patterns only affect untracked files. This is what makes writing to the+/// user's shared `info/exclude` safe β measured against git 2.55.0, and the+/// whole design rests on it.+#[test]+#[cfg(feature = "test-mocks")]+fn the_exclude_cannot_hide_a_file_the_project_tracks() {+ let dir = tempfile::tempdir().unwrap();+ let repo = dir.path();+ let git = |args: &[&str]| {+ std::process::Command::new("git")+ .current_dir(repo)+ .args(args)+ .output()+ .unwrap()+ };+ git(&["init", "-q"]);+ git(&["config", "user.email", "[email protected]"]);+ git(&["config", "user.name", "T"]);+ std::fs::write(repo.join(".mcp.json"), "{\"tracked\": true}").unwrap();+ git(&["add", "-A"]);+ git(&["commit", "-q", "-m", "project tracks .mcp.json"]);++ exclude_agtx_files_from_git(repo);+ std::fs::write(repo.join(".mcp.json"), "{\"tracked\": true, \"edited\": 1}").unwrap();++ let status = String::from_utf8_lossy(&git(&["status", "--porcelain"]).stdout).to_string();+ assert!(+ status.contains(".mcp.json"),+ "a tracked file must still report its modification: {status:?}"+ );+}++/// `ps` needs an explicit process selector. Without one it lists only the+/// processes attached to the caller's own terminal β so a daemonized orphan,+/// the entire reason `processes_for_task` exists, never appears. Verified+/// against a real survivor: no selector found nothing, `-A` found it.+///+/// Asserted on the command rather than on live processes because whether `ps`+/// exposes another process's environment depends on the platform and on how the+/// caller was launched; the flag is what silently regresses.+#[test]+#[cfg(feature = "test-mocks")]+fn the_process_lookup_asks_ps_for_every_process() {+ let src = include_str!("app.rs");+ let call = src+ .find("\"-AEww\"")+ .map(|i| &src[i..(i + 40).min(src.len())]);+ assert!(+ call.is_some(),+ "processes_for_task must pass -A; without it ps lists only this terminal's processes"+ );+}++// =============================================================================+// `ready` means the phase is done β not merely that a file exists+// =============================================================================++/// After a resume the previous cycle's artifact is still on disk. Counting it+/// would make a task sent back to Running read `ready` the moment it arrives,+/// before it has done any work.+#[test]+fn an_artifact_from_before_the_phase_began_does_not_count() {+ let dir = tempfile::tempdir().unwrap();+ std::fs::create_dir_all(dir.path().join(".agtx")).unwrap();+ std::fs::write(dir.path().join(".agtx/execute.md"), "cycle one").unwrap();+ let plugin = skills::load_bundled_plugin("agtx");+ let wt = dir.path().to_str().unwrap();+ let now = chrono::Utc::now();++ assert!(+ phase_artifact_fresh(wt, TaskStatus::Running, &plugin, 1, Some(now - chrono::Duration::seconds(60))),+ "written after the phase began: counts"+ );+ assert!(+ !phase_artifact_fresh(wt, TaskStatus::Running, &plugin, 1, Some(now + chrono::Duration::seconds(60))),+ "written before the phase began β the previous cycle's β must not count"+ );+ assert!(+ phase_artifact_fresh(wt, TaskStatus::Running, &plugin, 1, None),+ "a task stored before the column existed falls back to existence"+ );+ assert!(+ !phase_artifact_fresh(wt, TaskStatus::Review, &plugin, 1, None),+ "and a phase with no artifact at all is still not ready"+ );+}++/// An agent writes its artifact mid-turn and keeps going, so `ready` waits for+/// the turn to end. A live report holds it back; a finished or absent one lets+/// the artifact stand; and it never promotes a phase that was not ready.+#[test]+fn ready_waits_for_the_turn_to_end() {+ use crate::agent::hook_status::HookState;+ let gate = gate_ready_on_turn;+ assert_eq!(gate(PhaseStatus::Ready, Some(HookState::Working)), PhaseStatus::Working);+ assert_eq!(gate(PhaseStatus::Ready, Some(HookState::Blocked)), PhaseStatus::Working);+ assert_eq!(gate(PhaseStatus::Ready, Some(HookState::Waiting)), PhaseStatus::Ready);+ assert_eq!(gate(PhaseStatus::Ready, Some(HookState::Ended)), PhaseStatus::Ready);+ assert_eq!(+ gate(PhaseStatus::Ready, None),+ PhaseStatus::Ready,+ "no trustworthy record β no hooks, or a stale one β falls back to the artifact"+ );+ assert_eq!(gate(PhaseStatus::Working, Some(HookState::Waiting)), PhaseStatus::Working);+}++/// The refresh snapshots tasks before it runs, so a pass in flight across a+/// transition returns the previous phase's verdict β Running's artifact reads+/// as `review:ready`. The same verdict for a task still in that status must apply β otherwise this+/// test would pass by applying nothing.+#[test]+#[cfg(feature = "test-mocks")]+fn a_refresh_verdict_for_a_status_the_task_has_left_is_dropped() {+ let _data = redirect_data_dir();+ let _config = redirect_config_dir();+ let dir = tempfile::tempdir().unwrap();+ let mut app = make_test_app_at(dir.path());++ let verdict = |task: &Task, status: TaskStatus| SessionTaskStatus {+ task_id: task.id.clone(),+ phase_status: PhaseStatus::Ready,+ content_hash: None,+ status,+ worktree_path: None,+ session_name: None,+ agent: "claude".into(),+ was_ready: true,+ hook_status: None,+ awaiting_trust: None,+ };++ let mut moved_on = Task::new("moved on", "claude", "p1");+ moved_on.status = TaskStatus::Review;+ moved_on.session_name = Some("proj:task-moved".into());+ let mut still_there = Task::new("still running", "claude", "p1");+ still_there.status = TaskStatus::Running;+ still_there.session_name = Some("proj:task-still".into());+ app.state.board.tasks = vec![moved_on.clone(), still_there.clone()];++ app.apply_session_refresh(SessionRefreshResult {+ statuses: vec![+ verdict(&moved_on, TaskStatus::Running),+ verdict(&still_there, TaskStatus::Running),+ ],+ });++ assert!(+ !matches!(app.state.phase_status_cache.get(&moved_on.id), Some((PhaseStatus::Ready, _))),+ "a Running verdict must not reach a task now in Review"+ );+ assert!(+ matches!(app.state.phase_status_cache.get(&still_there.id), Some((PhaseStatus::Ready, _))),+ "a verdict for the task's current status still applies"+ );+}diff --git a/src/tui/dep_graph.rs b/src/tui/dep_graph.rsindex 0a39c8f..32820fc 100644--- a/src/tui/dep_graph.rs+++ b/src/tui/dep_graph.rs@@ -230,6 +230,7 @@ mod tests {referenced_tasks: refs.map(|s| s.to_string()),escalation_note: None,base_branch: None,+ phase_entered_at: None,created_at: Utc::now(),updated_at: Utc::now(),}diff --git a/src/web/routes.rs b/src/web/routes.rsindex 96cf805..ac9229a 100644--- a/src/web/routes.rs+++ b/src/web/routes.rs@@ -272,6 +272,9 @@ fn card(conflict: Option<ConflictState>,) -> TaskCard {let deps_ok = db.deps_satisfied(&t);+ // A verdict computed for a status the task has since left describes the+ // previous phase; see `TaskRuntime::status`. Withheld, it reads as unknown.+ let runtime = runtime.filter(|r| r.status.map_or(true, |s| s == t.status));TaskCard {conflicted: conflict.as_ref().map(|c| c.conflicted),conflicting_files: conflict.map(|c| c.files).unwrap_or_default(),diff --git a/tests/agent_parity_tests.rs b/tests/agent_parity_tests.rsindex 8eff71c..53b236d 100644--- a/tests/agent_parity_tests.rs+++ b/tests/agent_parity_tests.rs@@ -641,3 +641,112 @@ fn the_size_cap_is_counted_in_bytes_not_chars() {assert!(wide.len() > MAX_LAUNCH_PROMPT_BYTES);assert!(!can_launch_with_prompt(PromptInjection::Argv, &wide));}++// =============================================================================+// Launch dialogs β what agtx will answer, and on whose behalf+// =============================================================================++/// Every dialog agtx knows, pinned as a literal.+///+/// Written out rather than derived, like the rest of this file: a diff here has+/// to mean somebody changed what agtx answers on a user's behalf. The answers+/// are *positional* β `2` on codex's update menu is `Skip` only while the menu+/// keeps that order β so the pin is what turns a silent change of meaning into+/// a failing test.+///+/// It cannot detect the agent reordering its own menu; only a real run can, and+/// `tests/smoke/` is where that belongs. This covers the half that is agtx's.+fn dialog_table() -> Vec<(&'static str, &'static str, Vec<&'static str>, bool)> {+ let mut rows = Vec::new();+ for agent in AGENTS {+ if let Some(spec) = agtx::agent::spec(agent) {+ for d in spec.dialogs {+ rows.push((+ *agent,+ d.patterns[0],+ d.answer.to_vec(),+ d.security,+ ));+ }+ }+ }+ rows+}++#[test]+fn dialog_answers_are_pinned() {+ let expected: Vec<(&str, &str, Vec<&str>, bool)> = vec![+ ("claude", "Yes, I trust this folder", vec!["1", "Enter"], true),+ ("claude", "Yes, I accept", vec!["2", "Enter"], true),+ (+ "codex",+ "Do you trust the contents of this directory?",+ vec!["1", "Enter"],+ true,+ ),+ // `Skip`. Never "Update now": agtx must not upgrade an agent binary+ // behind the user's back.+ ("codex", "Update now (runs", vec!["2", "Enter"], false),+ // `Continue without trusting`. `2` would be "Trust all and continue",+ // which lets the repo's hooks run *outside* codex's sandbox.+ ("codex", "Hooks need review", vec!["3", "Enter"], false),+ ("codex", "Allow the", vec!["3", "Enter"], false),+ (+ "gemini",+ "Do you trust the files in this folder?",+ vec!["1", "Enter"],+ true,+ ),+ // The access key the dialog advertises, so it survives an option being+ // added above the highlighted row.+ ("cursor", "Workspace Trust Required", vec!["a"], true),+ // Arrow-navigated with the safe option preselected β a digit would land+ // in the composer it opens.+ (+ "antigravity",+ "Do you trust the contents of this project?",+ vec!["Enter"],+ true,+ ),+ ];++ assert_eq!(+ dialog_table(),+ expected,+ "the set of dialogs agtx answers changed β confirm each answer still \+ selects the option its comment claims before updating this table"+ );+}++/// A dialog that decides whether the agent may be trusted, or may run+/// unattended, is the user's call: `security: true` is what stops agtx answering+/// it unless `auto_trust` is explicitly on.+///+/// The flag is hand-written per entry with nothing checking it, so a new trust+/// prompt added with `security: false` would be answered unconditionally β the+/// one mistake in this table that hands away a decision silently.+#[test]+fn trust_prompts_are_classified_as_security_decisions() {+ let mut checked = 0;+ for (agent, pattern, answer, security) in dialog_table() {+ let looks_like_trust = pattern.to_lowercase().contains("trust")+ || pattern.contains("I accept")+ || pattern.contains("accept the risk");+ if looks_like_trust {+ checked += 1;+ assert!(+ security,+ "{agent}: {pattern:?} answers {answer:?} and reads as a trust or \+ permission-bypass prompt, but is not marked `security` β it would \+ be answered with auto_trust off, which is the user's decision"+ );+ }+ }+ // Without this the test passes by matching nothing, which is how a guard+ // quietly stops guarding.+ assert!(+ checked >= 6,+ "only {checked} trust-shaped patterns matched; the heuristic has drifted \+ away from the table it is meant to police"+ );+}diff --git a/tests/config_tests.rs b/tests/config_tests.rsindex b301f48..1b4ac25 100644--- a/tests/config_tests.rs+++ b/tests/config_tests.rs@@ -768,3 +768,48 @@ fn clearing_the_agents_section_removes_it_entirely() {assert!(!text.contains("[agents]"), "empty section lingered: {text}");assert!(ProjectConfig::load(dir.path()).unwrap().agents.is_none());}++/// `auto_trust` is global-only, and that is a security boundary rather than an+/// oversight: it decides whether agtx answers an agent's trust and+/// bypass-permission dialogs on the user's behalf. If a project config could set+/// it, any cloned repository could ship an `.agtx/config.toml` that grants+/// itself trust β which is exactly what the trust system exists to prevent.+///+/// This is also why a oneshot session has to read the *merged* config through+/// `get_config` rather than a project file: there is no project-local way to+/// turn it on, so the answer lives only in the global config, wherever+/// `AGTX_CONFIG_DIR` puts it.+#[test]+fn auto_trust_comes_from_the_global_config_alone() {+ let mut global = GlobalConfig::default();+ global.auto_trust = true;++ // A project config carries no `auto_trust` field to override it with.+ let project = ProjectConfig::default();+ let merged = MergedConfig::merge(&global, &project);+ assert!(merged.auto_trust);++ global.auto_trust = false;+ let merged = MergedConfig::merge(&global, &ProjectConfig::default());+ assert!(!merged.auto_trust);+}++/// The companion property: things a project *may* override still do override,+/// so `get_config` has to report the merge rather than either file alone.+#[test]+fn a_project_config_overrides_the_global_default_agent() {+ let global = GlobalConfig {+ default_agent: "opencode".to_string(),+ ..GlobalConfig::default()+ };+ let project = ProjectConfig {+ default_agent: Some("claude".to_string()),+ ..ProjectConfig::default()+ };++ assert_eq!(MergedConfig::merge(&global, &project).default_agent, "claude");+ assert_eq!(+ MergedConfig::merge(&global, &ProjectConfig::default()).default_agent,+ "opencode"+ );+}diff --git a/tests/db_tests.rs b/tests/db_tests.rsindex af21397..f810b10 100644--- a/tests/db_tests.rs+++ b/tests/db_tests.rs@@ -709,6 +709,7 @@ fn runtime_for(task_id: &str, phase: PhaseStatus) -> TaskRuntime {TaskRuntime {task_id: task_id.to_string(),phase_status: phase,+ status: None,pane_hash: Some("abc123".to_string()),pane_changed_at: Some(chrono::Utc::now()),updated_at: chrono::Utc::now(),@@ -866,3 +867,63 @@ fn notification_kind_spellings_match_serde() {assert_eq!(NotificationKind::from_str(kind.as_str()), Some(kind));}}++// === phase_entered_at and the runtime row's status ===++/// A status change restarts the phase; an edit that keeps the status does not.+/// Backward moves count as much as forward ones β `resume` is exactly where a+/// previous cycle's artifact made a task read as done.+#[test]+#[cfg(feature = "test-mocks")]+fn a_status_change_stamps_phase_entered_at_and_other_edits_do_not() {+ use agtx::db::{Database, Task, TaskStatus};+ let entered = |db: &Database, id: &str| db.get_task(id).unwrap().unwrap().phase_entered_at.unwrap();+ let pause = || std::thread::sleep(std::time::Duration::from_millis(15));++ let db = Database::open_in_memory_project().unwrap();+ let mut task = Task::new("t", "claude", "p");+ db.create_task(&task).unwrap();+ let created = entered(&db, &task.id);++ pause();+ task.title = "renamed".into();+ db.update_task(&task).unwrap();+ assert_eq!(entered(&db, &task.id), created, "an edit that keeps the status is not a new phase");++ pause();+ task.status = TaskStatus::Planning;+ db.update_task(&task).unwrap();+ let planning = entered(&db, &task.id);+ assert!(planning > created);++ task.status = TaskStatus::Review;+ db.update_task(&task).unwrap();+ let review = entered(&db, &task.id);+ pause();+ task.status = TaskStatus::Running; // resume+ db.update_task(&task).unwrap();+ assert!(entered(&db, &task.id) > review, "a backward move is a new phase too");+}++/// A published verdict remembers the status it was computed for, so a reader+/// can refuse one that describes a phase the task has since left.+#[test]+#[cfg(feature = "test-mocks")]+fn a_runtime_row_remembers_the_status_it_was_computed_for() {+ use agtx::db::{Database, PhaseStatus, Task, TaskRuntime, TaskStatus};+ let db = Database::open_in_memory_project().unwrap();+ let task = Task::new("t", "claude", "p");+ db.create_task(&task).unwrap();+ db.publish_task_runtime(&[TaskRuntime {+ task_id: task.id.clone(),+ phase_status: PhaseStatus::Ready,+ status: Some(TaskStatus::Running),+ pane_hash: None,+ pane_changed_at: None,+ updated_at: chrono::Utc::now(),+ }])+ .unwrap();+ let row = db.get_task_runtime(&task.id).unwrap().unwrap();+ assert_eq!(row.status, Some(TaskStatus::Running));+ assert_eq!(row.phase_status, PhaseStatus::Ready);+}diff --git a/tests/git_tests.rs b/tests/git_tests.rsindex 61bd722..571bffb 100644--- a/tests/git_tests.rs+++ b/tests/git_tests.rs@@ -852,3 +852,258 @@ fn test_initialize_worktree_symlink_traversal_blocked() {assert!(warnings[0].contains("outside project root"));}}++// =============================================================================+// merge_task_branch β integrating a task branch into its base+// =============================================================================++/// Commit `content` to `file` on a branch cut from `base`, then return to base.+fn commit_on_branch(repo: &std::path::Path, branch: &str, file: &str, content: &str, base: &str) {+ Command::new("git")+ .current_dir(repo)+ .args(["checkout", "-q", "-b", branch, base])+ .output()+ .unwrap();+ std::fs::write(repo.join(file), content).unwrap();+ Command::new("git")+ .current_dir(repo)+ .args(["add", "."])+ .output()+ .unwrap();+ Command::new("git")+ .current_dir(repo)+ .args(["commit", "-q", "-m", &format!("work on {branch}")])+ .output()+ .unwrap();+ Command::new("git")+ .current_dir(repo)+ .args(["checkout", "-q", base])+ .output()+ .unwrap();+}++fn head_message(repo: &std::path::Path) -> String {+ let out = Command::new("git")+ .current_dir(repo)+ .args(["log", "-1", "--pretty=%s"])+ .output()+ .unwrap();+ String::from_utf8_lossy(&out.stdout).trim().to_string()+}++#[test]+fn merging_a_clean_branch_lands_a_merge_commit() {+ let temp = setup_git_repo();+ let repo = temp.path();+ commit_on_branch(repo, "task/feature", "feature.txt", "hello", "main");++ let outcome =+ git::merge_task_branch(repo, "main", "task/feature", "Merge task 'feature'").unwrap();++ assert_eq!(outcome, git::MergeOutcome::Merged);+ assert!(repo.join("feature.txt").exists());+ assert_eq!(head_message(repo), "Merge task 'feature'");+}++#[test]+fn conflicting_branches_are_reported_without_touching_the_checkout() {+ let temp = setup_git_repo();+ let repo = temp.path();++ // Both sides edit the same file, from the same starting point.+ commit_on_branch(repo, "task/feature", "README.md", "# From the task", "main");+ std::fs::write(repo.join("README.md"), "# From main").unwrap();+ Command::new("git")+ .current_dir(repo)+ .args(["commit", "-qam", "diverge on main"])+ .output()+ .unwrap();+ let before = head_message(repo);++ let outcome = git::merge_task_branch(repo, "main", "task/feature", "merge").unwrap();++ match outcome {+ git::MergeOutcome::Conflicts(files) => assert_eq!(files, vec!["README.md".to_string()]),+ other => panic!("expected conflicts, got {other:?}"),+ }++ // Nothing was attempted, so no merge is left half-finished for the user to+ // find: the checkout is exactly where it was.+ assert_eq!(head_message(repo), before);+ assert!(!repo.join(".git").join("MERGE_HEAD").exists());+ assert_eq!(+ std::fs::read_to_string(repo.join("README.md")).unwrap(),+ "# From main"+ );+}++#[test]+fn merging_is_refused_when_the_checkout_is_on_another_branch() {+ let temp = setup_git_repo();+ let repo = temp.path();+ commit_on_branch(repo, "task/feature", "feature.txt", "hello", "main");+ Command::new("git")+ .current_dir(repo)+ .args(["checkout", "-q", "-b", "somewhere-else"])+ .output()+ .unwrap();++ let outcome = git::merge_task_branch(repo, "main", "task/feature", "merge").unwrap();++ match outcome {+ git::MergeOutcome::Refused(why) => {+ assert!(why.contains("somewhere-else"), "{why}");+ assert!(why.contains("main"), "{why}");+ }+ other => panic!("expected refusal, got {other:?}"),+ }+ // The merge must not have happened on the branch that *was* checked out.+ assert!(!repo.join("feature.txt").exists());+}++#[test]+fn merging_is_refused_when_the_checkout_has_uncommitted_changes() {+ let temp = setup_git_repo();+ let repo = temp.path();+ commit_on_branch(repo, "task/feature", "feature.txt", "hello", "main");+ std::fs::write(repo.join("README.md"), "edited by the user").unwrap();++ let outcome = git::merge_task_branch(repo, "main", "task/feature", "merge").unwrap();++ match outcome {+ git::MergeOutcome::Refused(why) => assert!(why.contains("uncommitted"), "{why}"),+ other => panic!("expected refusal, got {other:?}"),+ }+ assert_eq!(+ std::fs::read_to_string(repo.join("README.md")).unwrap(),+ "edited by the user"+ );+}++/// An untracked file is not a reason to refuse: the project root always has+/// some, since worktrees live under `.agtx/`.+#[test]+fn untracked_files_do_not_block_a_merge() {+ let temp = setup_git_repo();+ let repo = temp.path();+ commit_on_branch(repo, "task/feature", "feature.txt", "hello", "main");+ std::fs::create_dir_all(repo.join(".agtx/worktrees")).unwrap();+ std::fs::write(repo.join(".agtx/worktrees/stray"), "not tracked").unwrap();++ let outcome = git::merge_task_branch(repo, "main", "task/feature", "merge").unwrap();++ assert_eq!(outcome, git::MergeOutcome::Merged);+}++// =============================================================================+// A repository with no commits+// =============================================================================++/// A worktree must be cut from a commit, so a `git init` with no history β the+/// starting state of any greenfield project β gets one before setup proceeds.+/// `git rev-parse --abbrev-ref HEAD` fails there *and still prints* the literal+/// string `HEAD`, which is not a revision a worktree can be cut from.+#[test]+fn a_repo_with_no_commits_gets_one_so_a_worktree_can_be_cut() {+ let temp = TempDir::new().unwrap();+ let repo = temp.path();+ for args in [+ vec!["init", "-q"],+ vec!["config", "user.email", "[email protected]"],+ vec!["config", "user.name", "T"],+ ] {+ Command::new("git")+ .current_dir(repo)+ .args(&args)+ .output()+ .unwrap();+ }++ // Precondition: HEAD really is unborn.+ assert!(!Command::new("git")+ .current_dir(repo)+ .args(["rev-parse", "--verify", "HEAD"])+ .output()+ .unwrap()+ .status+ .success());++ let branch = git::detect_main_branch(repo).expect("should recover, not fail");+ assert!(!branch.is_empty());+ assert_ne!(branch, "HEAD", "the literal rev-parse output is not a branch");++ // The repo now has exactly one commit, and a worktree can be cut from it.+ let log = Command::new("git")+ .current_dir(repo)+ .args(["log", "--oneline"])+ .output()+ .unwrap();+ assert_eq!(String::from_utf8_lossy(&log.stdout).lines().count(), 1);++ let wt = git::create_worktree(repo, "some-task").expect("worktree from the new commit");+ assert!(wt.join(".git").exists());+}++/// The recovery is scoped to an *empty* repo. A repo that has commits and fails+/// for some other reason must surface that, not have history written into it.+#[test]+fn a_repo_with_commits_is_never_given_an_extra_one() {+ let temp = setup_git_repo();+ let repo = temp.path();+ let before = Command::new("git")+ .current_dir(repo)+ .args(["rev-parse", "HEAD"])+ .output()+ .unwrap();++ assert_eq!(git::detect_main_branch(repo).unwrap(), "main");++ let after = Command::new("git")+ .current_dir(repo)+ .args(["rev-parse", "HEAD"])+ .output()+ .unwrap();+ assert_eq!(before.stdout, after.stdout, "HEAD must not have moved");+}++/// `git merge` reports success for a branch with no commits β "Already up to+/// date", exit 0 β so a caller that trusts the exit status concludes the work+/// landed. It did not. The usual cause is an agent that wrote files and never+/// committed them, and the caller's next step is to delete the worktree those+/// files live in.+#[test]+fn a_branch_with_no_commits_reports_nothing_to_merge_rather_than_success() {+ let temp = setup_git_repo();+ let repo = temp.path();+ // A branch, but no work committed on it β what an agent leaves behind when+ // it writes files and never runs `git commit`.+ Command::new("git")+ .current_dir(repo)+ .args(["branch", "task/empty"])+ .output()+ .unwrap();++ let outcome = git::merge_task_branch(repo, "main", "task/empty", "merge").unwrap();++ assert_eq!(outcome, git::MergeOutcome::NothingToMerge);+ assert_eq!(+ git::commits_ahead(repo, "main", "task/empty").unwrap(),+ 0,+ "and the count is what the outcome is derived from"+ );+}++/// The companion: a branch with real commits still merges, so the guard above+/// cannot be satisfied by refusing everything.+#[test]+fn a_branch_with_commits_still_merges() {+ let temp = setup_git_repo();+ let repo = temp.path();+ commit_on_branch(repo, "task/real", "real.txt", "work", "main");++ assert_eq!(git::commits_ahead(repo, "main", "task/real").unwrap(), 1);+ assert_eq!(+ git::merge_task_branch(repo, "main", "task/real", "merge").unwrap(),+ git::MergeOutcome::Merged+ );+}diff --git a/tests/hook_status_tests.rs b/tests/hook_status_tests.rsindex 96c4507..436c340 100644--- a/tests/hook_status_tests.rs+++ b/tests/hook_status_tests.rs@@ -738,3 +738,46 @@ fn a_grok_payload_reaching_a_neighbours_registration() {);assert_eq!(map_hook_event(HookConfigKind::ClaudeSettings, "stop"), None);}++/// `Notification` is not one event. Measured against Claude Code 2.1.263 it+/// carries a `notification_type`: `permission_prompt` when the agent is stopped+/// waiting on a human, and `idle_prompt` roughly a minute after any turn simply+/// ends. Both map to the same `Notification` name, so only the registration+/// matcher can separate them.+///+/// Unscoped, an agent that has simply finished its turn would report Blocked β+/// and an agent-reported Blocked fires the stuck-task path immediately, with no+/// settle window, so a caller would interrupt an agent that is merely quiet.+#[test]+fn claude_only_subscribes_to_permission_notifications() {+ let matcher = agtx::agent::hook_status::hook_events(HookConfigKind::ClaudeSettings)+ .iter()+ .find(|(event, _)| *event == "Notification")+ .map(|(_, m)| *m)+ .expect("Claude registers Notification");++ assert_eq!(+ matcher,+ Some("permission_prompt"),+ "an unscoped Notification also fires on idle and reports a working agent as Blocked"+ );+}++/// Grok scopes it the same way; the two must not drift, because the failure is+/// silent in both directions β a wrong Blocked looks like a stuck+/// agent, and a missing one looks like a hung task nobody is told about.+#[test]+fn every_agent_that_subscribes_to_notification_scopes_it_to_permissions() {+ for kind in [HookConfigKind::ClaudeSettings, HookConfigKind::GrokHooksJson] {+ if let Some((_, matcher)) = agtx::agent::hook_status::hook_events(kind)+ .iter()+ .find(|(event, _)| event.eq_ignore_ascii_case("notification"))+ {+ assert_eq!(+ *matcher,+ Some("permission_prompt"),+ "{kind:?} subscribes to Notification without scoping it"+ );+ }+ }+}diff --git a/tests/mcp_tests.rs b/tests/mcp_tests.rsindex 25549ca..7cfdb0c 100644--- a/tests/mcp_tests.rs+++ b/tests/mcp_tests.rs@@ -538,30 +538,348 @@ fn test_normal_messages_pass_validation() {#[test]#[cfg(feature = "test-mocks")]fn test_send_to_task_requires_active_phase() {- // Tasks in Backlog, Review, or Done should not accept send_to_task- let db = Database::open_in_memory_project().unwrap();+ // The real rule, not a copy of it: the server calls this same function.+ use agtx::core::actions::accepts_task_input;++ // No agent to receive it.+ for status in [TaskStatus::Backlog, TaskStatus::Done] {+ assert!(!accepts_task_input(status), "{status:?} must refuse input");+ }+ // Review is included so a reviewer can be handed a small fix in place,+ // rather than the task being resumed to Running just to deliver a message.+ for status in [TaskStatus::Planning, TaskStatus::Running, TaskStatus::Review] {+ assert!(accepts_task_input(status), "{status:?} must accept input");+ }+}++// === Local integration action ===++fn review_task() -> Task {+ let mut t = Task::new("Add the thing", "claude", "p1");+ t.status = TaskStatus::Review;+ t+}- for status in &[TaskStatus::Backlog, TaskStatus::Review, TaskStatus::Done] {- let mut task = Task::new("Test", "claude", "proj");- task.status = *status;- db.create_task(&task).unwrap();+/// Merging into the project's own checkout is the unattended caller's path to+/// Done. A person lands the same work by merging the PR on the remote, so+/// offering them both would be two ways to land one branch.+#[test]+fn local_merge_is_offered_to_the_orchestrator_and_not_to_a_person() {+ use agtx::core::actions::{allowed_actions, CallerKind};++ let task = review_task();+ let orchestrator = allowed_actions(&task, true, CallerKind::Orchestrator);+ let human = allowed_actions(&task, true, CallerKind::Human);++ assert!(orchestrator.contains(&"move_to_done_and_merge".to_string()));+ assert!(!human.contains(&"move_to_done_and_merge".to_string()));+ // It is an addition, not a replacement: a caller that does its integration+ // elsewhere still reaches Done the plain way.+ assert!(orchestrator.contains(&"move_to_done".to_string()));+ assert!(human.contains(&"move_to_done".to_string()));+}- // The server checks: !matches!(task.status, TaskStatus::Planning | TaskStatus::Running)+#[test]+fn local_merge_is_only_valid_from_review() {+ use agtx::core::actions::{validate_action, CallerKind};++ let task = review_task();+ assert!(validate_action(&task, true, CallerKind::Orchestrator, "move_to_done_and_merge").is_ok());++ for status in [+ TaskStatus::Backlog,+ TaskStatus::Planning,+ TaskStatus::Running,+ TaskStatus::Done,+ ] {+ let mut t = review_task();+ t.status = status;assert!(- !matches!(task.status, TaskStatus::Planning | TaskStatus::Running),- "Status {:?} should not be an active phase for send_to_task",- status+ validate_action(&t, true, CallerKind::Orchestrator, "move_to_done_and_merge").is_err(),+ "should be refused from {}",+ status.as_str());}+}- // Planning and Running should be allowed- for status in &[TaskStatus::Planning, TaskStatus::Running] {- let mut task = Task::new("Test", "claude", "proj");- task.status = *status;- assert!(- matches!(task.status, TaskStatus::Planning | TaskStatus::Running),- "Status {:?} should be an active phase for send_to_task",- status- );+/// The verb has to be in `ACTIONS` or `move_task` rejects it as unknown before+/// it ever reaches the executor.+#[test]+fn local_merge_is_a_known_action() {+ assert!(agtx::core::actions::ACTIONS.contains(&"move_to_done_and_merge"));+}++// === Reclaiming a dead instance's claims ===++/// A Backlog transition is claimed when picked up but only *marked* once the+/// serialized setup slot frees up and it actually starts. A TUI that exits in+/// between strands it: the row is claimed, so `get_pending_transition_requests`+/// filters it out and no restarted TUI ever runs it.+#[test]+#[cfg(feature = "test-mocks")]+fn a_dead_instance_claim_is_reclaimed_and_becomes_pending_again() {+ let db = Database::open_in_memory_project().unwrap();+ let req = TransitionRequest::new("task-1", "move_to_planning");+ db.create_transition_request(&req).unwrap();+ assert!(db.claim_transition_request(&req.id, "dead-instance").unwrap());+ assert!(+ db.get_pending_transition_requests().unwrap().is_empty(),+ "a claimed row is invisible to the drain β that is what strands it"+ );++ // Zero window: everything not held by this instance is fair game.+ let n = db+ .reclaim_stale_transition_requests("live-instance", chrono::Duration::zero())+ .unwrap();++ assert_eq!(n, 1);+ let pending = db.get_pending_transition_requests().unwrap();+ assert_eq!(pending.len(), 1);+ assert_eq!(pending[0].id, req.id);+}++/// This instance's own claims are its in-memory queue. Reclaiming them would+/// have it race itself and set the same worktree up twice.+#[test]+#[cfg(feature = "test-mocks")]+fn an_instance_never_reclaims_its_own_claims() {+ let db = Database::open_in_memory_project().unwrap();+ let req = TransitionRequest::new("task-1", "move_to_planning");+ db.create_transition_request(&req).unwrap();+ db.claim_transition_request(&req.id, "me").unwrap();++ let n = db+ .reclaim_stale_transition_requests("me", chrono::Duration::zero())+ .unwrap();++ assert_eq!(n, 0);+ assert!(db.get_pending_transition_requests().unwrap().is_empty());+}++/// The age window is what keeps a *live* second instance's genuine backlog out+/// of reach β a queued task waits out every setup ahead of it.+#[test]+#[cfg(feature = "test-mocks")]+fn a_recent_claim_is_left_alone() {+ let db = Database::open_in_memory_project().unwrap();+ let req = TransitionRequest::new("task-1", "move_to_planning");+ db.create_transition_request(&req).unwrap();+ db.claim_transition_request(&req.id, "other-instance").unwrap();++ let n = db+ .reclaim_stale_transition_requests("me", chrono::Duration::minutes(5))+ .unwrap();++ assert_eq!(n, 0, "claimed seconds ago β the other instance may be alive");+}++/// A processed row is finished, whoever claimed it.+#[test]+#[cfg(feature = "test-mocks")]+fn a_processed_request_is_not_reclaimed() {+ let db = Database::open_in_memory_project().unwrap();+ let req = TransitionRequest::new("task-1", "move_to_planning");+ db.create_transition_request(&req).unwrap();+ db.claim_transition_request(&req.id, "dead-instance").unwrap();+ db.mark_transition_processed(&req.id, None).unwrap();++ let n = db+ .reclaim_stale_transition_requests("me", chrono::Duration::zero())+ .unwrap();++ assert_eq!(n, 0);+ assert!(db.get_pending_transition_requests().unwrap().is_empty());+}++// === wait_for_board_change: what wakes a caller, and what it is shown ===++use agtx::mcp::board_watch::{BoardView, TaskMark};++fn mark(status: TaskStatus, phase: Option<&str>) -> TaskMark {+ TaskMark {+ status,+ phase_status: phase.map(str::to_string),+ turn_ts: None,+ deps_satisfied: true,+ escalation_note: None,}}++fn board(tasks: &[(&str, TaskMark)]) -> Vec<(String, TaskMark)> {+ tasks+ .iter()+ .map(|(id, m)| (id.to_string(), m.clone()))+ .collect()+}++/// A view whose caller has already been shown `tasks`.+fn seen(tasks: &[(String, TaskMark)]) -> BoardView {+ let mut view = BoardView::default();+ view.mark_seen(tasks.iter().map(|(id, m)| (id.as_str(), m)), true);+ view+}++#[test]+fn a_first_wait_answers_at_once_with_the_whole_board() {+ let b = board(&[+ ("a", mark(TaskStatus::Running, Some("working"))),+ ("b", mark(TaskStatus::Planning, Some("working"))),+ ]);+ let mut view = BoardView::default();++ assert!(+ view.poll(&b, true),+ "nothing has been shown yet β that is news"+ );+ assert_eq!(view.report(&b, true).changed, vec!["a", "b"]);+}++#[test]+fn a_task_starting_to_work_does_not_wake_but_is_reported_with_what_does() {+ let before = board(&[+ ("a", mark(TaskStatus::Planning, Some("ready"))),+ ("b", mark(TaskStatus::Running, Some("working"))),+ ]);+ let mut view = seen(&before);++ // The caller advanced `a`. Its status changed and its phase went through+ // absent to working β the expected aftermath of its own move.+ let moved = board(&[+ ("a", mark(TaskStatus::Running, None)),+ ("b", mark(TaskStatus::Running, Some("working"))),+ ]);+ assert!(!view.poll(&moved, true));+ let working = board(&[+ ("a", mark(TaskStatus::Running, Some("working"))),+ ("b", mark(TaskStatus::Running, Some("working"))),+ ]);+ assert!(!view.poll(&working, true));++ let done = board(&[+ ("a", mark(TaskStatus::Running, Some("working"))),+ ("b", mark(TaskStatus::Running, Some("ready"))),+ ]);+ assert!(view.poll(&done, true), "b finished its phase");+ assert_eq!(view.report(&done, true).changed, vec!["a", "b"]);+}++#[test]+fn a_state_already_reported_does_not_wake_again() {+ let b = board(&[("a", mark(TaskStatus::Running, Some("blocked")))]);+ let mut view = seen(&b);++ // A caller that chose to leave a blocked task alone must not be woken for+ // it on every poll β that is a busy loop, one turn per second.+ assert!(!view.poll(&b, true));+ assert!(!view.poll(&b, true));+ assert!(view.report(&b, true).changed.is_empty());+}++#[test]+fn a_return_to_the_same_state_inside_one_wait_wakes() {+ let idle = board(&[("a", mark(TaskStatus::Running, Some("idle")))]);+ let mut view = seen(&idle);++ // Nudged: the agent works, then goes quiet again. An agent without hooks+ // has no turn timestamp, so the only evidence is the working in between.+ let working = board(&[("a", mark(TaskStatus::Running, Some("working")))]);+ assert!(!view.poll(&working, true));+ assert!(view.poll(&idle, true), "the nudge was answered");+ assert_eq!(+ view.report(&idle, true).changed,+ vec!["a"],+ "it matches what was reported, and must be shown anyway"+ );+}++#[test]+fn a_new_turn_end_wakes_even_with_the_phase_unchanged() {+ let mut first = mark(TaskStatus::Review, Some("ready"));+ first.turn_ts = Some(100);+ let mut view = seen(&board(&[("a", first)]));++ // A small fix sent in Review: the reviewer's turn ended again while the+ // caller was busy between two waits, so no poll saw it working.+ let mut second = mark(TaskStatus::Review, Some("ready"));+ second.turn_ts = Some(160);+ let b = board(&[("a", second)]);+ assert!(view.poll(&b, true));+ assert_eq!(view.report(&b, true).changed, vec!["a"]);+}++#[test]+fn reaching_done_wakes_and_a_startable_backlog_task_wakes() {+ let mut blocked_dep = mark(TaskStatus::Backlog, None);+ blocked_dep.deps_satisfied = false;+ let before = board(&[+ ("a", mark(TaskStatus::Review, Some("ready"))),+ ("b", blocked_dep),+ ]);+ let mut view = seen(&before);++ let after = board(&[+ ("a", mark(TaskStatus::Done, None)),+ ("b", mark(TaskStatus::Backlog, None)),+ ]);+ assert!(view.poll(&after, true));+ assert_eq!(view.report(&after, true).changed, vec!["a", "b"]);+}++#[test]+fn a_blocked_dependency_alone_does_not_wake() {+ let mut waiting = mark(TaskStatus::Backlog, None);+ waiting.deps_satisfied = false;+ let b = board(&[("a", waiting)]);+ let mut view = seen(&b);++ assert!(!view.poll(&b, true));+}++#[test]+fn an_escalation_wakes() {+ let b = board(&[("a", mark(TaskStatus::Review, Some("working")))]);+ let mut view = seen(&b);++ let mut escalated = mark(TaskStatus::Review, Some("working"));+ escalated.escalation_note = Some("merge conflict in src/lib.rs".to_string());+ assert!(view.poll(&board(&[("a", escalated)]), true));+}++#[test]+fn a_deleted_task_wakes_and_is_listed_as_removed() {+ let b = board(&[+ ("a", mark(TaskStatus::Running, Some("working"))),+ ("b", mark(TaskStatus::Backlog, None)),+ ]);+ let mut view = seen(&b);++ let after = board(&[("a", mark(TaskStatus::Running, Some("working")))]);+ assert!(view.poll(&after, true));+ let diff = view.report(&after, true);+ assert!(diff.changed.is_empty());+ assert_eq!(diff.removed, vec!["b"]);++ assert!(!view.poll(&after, true), "reported once, not again");+}++#[test]+fn the_tui_going_away_wakes() {+ let b = board(&[("a", mark(TaskStatus::Running, Some("working")))]);+ let mut view = seen(&b);++ assert!(!view.poll(&b, true));+ assert!(+ view.poll(&b, false),+ "every phase status is frozen from here"+ );+ view.report(&b, false);+ assert!(!view.poll(&b, false));+}++#[test]+fn what_a_listing_showed_does_not_wake_the_next_wait() {+ let b = board(&[("a", mark(TaskStatus::Running, Some("ready")))]);+ let mut view = seen(&b);++ assert!(!view.poll(&b, true), "list_tasks already showed a as ready");+}diff --git a/tests/tmux_control_tests.rs b/tests/tmux_control_tests.rsindex 26414d9..8003a9e 100644--- a/tests/tmux_control_tests.rs+++ b/tests/tmux_control_tests.rs@@ -193,6 +193,14 @@ impl TmuxOperations for TestTmuxOps {let id = String::from_utf8_lossy(&out.stdout).trim().to_string();(!id.is_empty()).then_some(id)}+ fn pane_pid(&self, target: &str) -> Option<u32> {+ let out = Command::new("tmux")+ .args(["-L", &self.server])+ .args(["display", "-p", "-t", target, "#{pane_pid}"])+ .output()+ .ok()?;+ String::from_utf8_lossy(&out.stdout).trim().parse().ok()+ }fn list_window_targets(&self) -> Result<Vec<String>> {let out = Command::new("tmux").args(["-L", &self.server])diff --git a/tests/web_tests.rs b/tests/web_tests.rsindex 4ad4081..9ccb6f5 100644--- a/tests/web_tests.rs+++ b/tests/web_tests.rs@@ -256,6 +256,7 @@ async fn the_board_carries_actions_and_phase_status() {db.publish_task_runtime(&[TaskRuntime {task_id: planning.id.clone(),phase_status: agtx::db::PhaseStatus::Blocked,+ status: None,pane_hash: None,pane_changed_at: None,updated_at: chrono::Utc::now(),