ππΌββοΈ The blackboard for coding agents - agentic development environment for claude code, codex, cursor, opencode, grok and more.
Rust adeai-agentsclaudeclaude-codecodexcursorgeminigrokopencodespec-driven-developmentvibe-codingvim
Agent-reported phase status, native prompt injection, and one declarative record per agent (#137)
Fynn Fluegge8e7f780e1b48
diff --git a/.gitignore b/.gitignoreindex a9a11c4..c2cca28 100644--- a/.gitignore+++ b/.gitignore@@ -19,3 +19,11 @@ Thumbs.db# Logs*.log++# In-flight design notes β untracked by convention (see CLAUDE.md)+/docs/planning/++# SWE-bench harness run output+/benchmark/swebench_output/++*__pycache__diff --git a/CLAUDE.md b/CLAUDE.mdindex 5c106f2..5382cba 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -25,6 +25,9 @@ cargo build --release# Run the MCP server (global mode, or project-scoped with a path)./target/release/agtx mcp-serve [path]++# Record an agent lifecycle event (invoked by agent hooks, not by hand)+./target/release/agtx hook <task-id> <worktree> [agent] < payload.json```Logs are written as JSON to `~/.config/agtx/logs/agtx.log` (daily rotation, `RUST_LOG` respected).@@ -59,7 +62,8 @@ src/β βββ operations.rs # GitOperations trait (mockable for testing)β βββ provider.rs # GitProviderOperations trait (GitHub PR ops)βββ agent/-β βββ mod.rs # Agent definitions, detection, spawn args+β βββ mod.rs # Agent struct, detection, command builders (all derived from spec.rs)+β βββ spec.rs # AgentSpec table β one declarative record per agent + kind enumsβ βββ operations.rs # AgentOperations/CodingAgent traits (mockable)βββ mcp/β βββ mod.rs # Re-exports@@ -106,9 +110,17 @@ tests/βββ board_tests.rs # Board navigation testsβββ git_tests.rs # Git worktree testsβββ agent_tests.rs # Agent detection and spawn args tests+βββ agent_parity_tests.rs # Per-agent behaviour lock (launch/resume/skill paths/syntax)+βββ hook_status_tests.rs # Agent lifecycle-hook status reportingβββ mcp_tests.rs # MCP server testsβββ mock_infrastructure_tests.rs # Mock infrastructure tests-βββ shell_popup_tests.rs # Shell popup logic tests+βββ shell_popup_tests.rs # Shell popup logic tests+βββ smoke/ # Per-agent smoke tests β real binaries, no mocks, opt-in+ βββ agent_smoke.py # The runner: scratch repo β TUI in tmux β phases over MCP+ βββ test_agent_smoke.py # Deterministic tests for the harness itself (no tmux/auth)+ βββ agent_matrix.rs # Dumps AGENT_SPECS + BUNDLED_PLUGINS as JSON for the runner+ β # (a [[example]] in Cargo.toml, so `cargo test` compiles it)+ βββ README.md # What it asserts, its outcomes, and what it has foundbenchmark/ # SWE-bench harnessdocker/ # Container images for sandboxed runs@@ -195,14 +207,79 @@ Commands are written once in canonical format (`/ns:command`) and auto-translate- Copilot: no interactive skill invocation (prompt only, no commands sent)### Sending Skills & Prompts to Agents-`send_skill_and_prompt()` has **three** send paths, because agent TUIs disagree about how a slash command plus arguments must arrive. Getting this wrong is the usual cause of "the agent started but never got the task":+Prompt delivery has **two lanes**. Getting this wrong is the usual cause of "the agent started but never got the task".++**Launch lane β the first message of a task's life.** The skill command and prompt are composed by `compose_launch_text()` and handed to the process in **argv**, so the agent starts with the task already in hand: no readiness polling, no window in which a keystroke can be dropped. Gated by `spec::can_launch_with_prompt()`, which requires both an agent whose launch form is *verified* (`AgentSpec::launch_prompt_verified` β Claude only today) and a prompt under `MAX_LAUNCH_PROMPT_BYTES` (128 KiB; `execve` counts bytes). Anything else falls through to the mid-session lane. `setup_task_worktree` returns `(target, launched_with_prompt)` and its callers skip the send entirely when true.++Two consequences worth knowing: `resolve_skill_command(collapse: false)` is used here, so `{task}` keeps its paragraphs and lists (the typed path must flatten them); and `spec::normalize_prompt()` strips NUL, `\r` and other control characters that cannot survive argv, keeping `\n` and `\t`.++**The prompt is quoted twice, and both layers must escape.** `compose_command` single-quotes the prompt, then `create_window` nests the whole command inside `sh -c β¦`. Interpolating it raw ends the outer word at the first inner quote and the shell parses the prompt as code β verified against tmux 3.5a, claude received argv `["--dangerously-skip-permissions", "/agtx:plan"]` with the task id and entire task silently gone, and codex's `$agtx-plan` lost `$agtx` to expansion. `single_quote()` in `src/tmux/operations.rs` is the second layer; its tests run the wrapper through a real `sh` and assert the delivered argv, because a string-equality test would have passed on the broken version.-1. **opencode** β its picker strips arguments if the whole string is typed at once. So: send the bare command name β wait for the picker β Enter (inserts it) β send the args β Enter-2. **gemini / codex / cursor / antigravity** β always combine skill + prompt into a *single* message via `send_keys_literal`, then poll the pane until the text renders before pressing Enter (Ink TUIs drop keys sent too early). Gemini executes-and-loses a separately sent prompt; Codex's `$skill` mentions are inline references that do nothing when sent standalone. Codex additionally needs a second Enter to dismiss its command picker. Antigravity's slash-command picker closes as soon as arguments are typed, so the combined text submits on a single Enter (verified against agy 1.1.19) β no Codex-style second Enter+**Mid-session lane β phase advances into an already-running agent.** `send_skill_and_prompt()`, three paths, because agent TUIs disagree about how a slash command plus arguments must arrive:++1. **opencode** β its picker strips arguments if the whole string is typed at once. So: send the bare command name β wait for the picker β Enter (inserts it) β send the args β Enter. Still on the typed path: it is the one flow where the text has to arrive in two pieces by design+2. **gemini / codex / cursor / antigravity** β skill + prompt combined into a *single* message delivered by **bracketed paste** (`paste_text`), then one Enter. The paste is atomic, so the old poll-until-it-renders step is gone, and the `\n\n` joining command to prompt stays literal text instead of arriving as a real Enter that submits the message half-written. Gemini executes-and-loses a separately sent prompt; Codex's `$skill` mentions are inline references that do nothing when sent standalone. **No second Enter for Codex**: its command picker opens on *typing*, not on a paste (verified against codex-cli 0.144.5), so there is nothing to dismiss3. **everything else** (claude, copilot, grok) β the generic `match (skill_cmd, prompt_trigger)` path using `send_keys`, waiting on `prompt_triggers` between the command and the prompt when configured+**Atomic is not the same as delivered.** An agent TUI that has not attached its stdin reader yet discards what it is sent β bracketed paste included, because the discard happens in the application, not in the pty β and `wait_for_agent_ready` cannot prove otherwise. So paths 1 and 2 go through `deliver_message()`, which resends **while the pane is unchanged** (three attempts, 2s each) and stops the moment it redraws, on the same reasoning `dismiss_launch_dialog` uses: a redraw means it landed, and resending would double the message. Landing is judged by the pane changing rather than by finding the text, because a composer wraps, re-indents and box-draws what it echoes.+`clear_context_on_advance` is applied before all three, and only for Claude (`/clear`, then poll until the pane stabilises).+**tmux send primitives** β pick by what you are sending, they are not interchangeable:++| Method | tmux | Use for |+|---|---|---|+| `paste_text` | `load-buffer` + `paste-buffer -p` | a whole message; bracketed, atomic, newlines stay literal |+| `send_text` | `send-keys -l --` | literal text; no key-name lookup |+| `send_key` | `send-keys` (no `-l`) | **key names** β `Enter`, `C-c`, dialog answers |+| `send_keys` | `send-keys` + `Enter` | text plus a submit, generic path |++Without `-l`, tmux resolves an argument that matches a key name *as that key*: `"Space"` arrives as `0x20`, `"Escape"` as `ESC`, `"Up"` as `\033[A` (tmux 3.5a). So `send_key` must never carry task-derived text β that is what `send_text` is for.++### First-Launch Dialogs+Agents gate a brand-new directory behind an interactive dialog, and every task gets a brand-new+worktree β so these fire on the *first* launch of nearly every task, not just in containers.+`LAUNCH_DIALOGS` (`src/tui/app.rs`) is the table of `(patterns, answer)`; `dismiss_launch_dialog`+answers any that is visible.++Dialogs are declared per agent on `AgentSpec::dialogs` and **matched against the running agent's own entries** β a stray digit typed into another agent's live composer is real corruption. An agent with no spec falls back to matching every known dialog, which beats leaving its pane blocked forever.++`answer` is a **key sequence**, not one key, because menus differ in kind: a numbered menu needs the digit and then an Enter to confirm, while an arrow-navigated menu whose safe option is already highlighted needs only the Enter β and sending it a digit first would type a stray character into the composer it opens.++| Agent | Dialog | Match | Answer | Scope |+|---|---|---|---|---|+| claude | workspace trust | `Yes, I trust this folder` | `1` `Enter` | Launch β per directory, `projects."<dir>".hasTrustDialogAccepted` in `~/.claude.json` |+| claude | bypass-permissions warning | `Yes, I accept` / `I accept the risk` | `2` `Enter` | Launch β the `bypassPermissionsModeAccepted` preflight does **not** reliably suppress it |+| codex | directory trust | `Do you trust the contents of this directory?` | `1` `Enter` | Launch β per directory. Worded unlike Claude's *and* Gemini's, so neither pattern catches it |+| codex | update prompt | `Update now (runs` | `2` `Enter` (Skip) | Launch β never "Update now": agtx must not upgrade an agent binary behind the user's back |+| codex | MCP tool approval | `Allow the` + `MCP server to run tool` + `Always allow` | `3` `Enter` | **Session** β mid-session, matched only against a codex pane |+| gemini | folder trust | `Do you trust the files in this folder?` | `1` `Enter` | Launch β answering it restarts the process |+| cursor | workspace trust | `Workspace Trust Required` | `a` alone | Launch β its question line is *identical* to codex's, so it is matched on the heading. Answered with the access key the dialog advertises, which survives an option being added above the highlighted row |+| antigravity | project trust | `Do you trust the contents of this project?` | `Enter` alone | Launch β arrow-navigated with "Yes, I trust this folder" preselected, so a digit would land in the composer. Its own wording, not Claude's; codex's differs by one word (`directory`) |++`require_all` distinguishes alternatives (several wordings of one prompt) from conjunctions (a prompt identified only by a combination of phrases).++It runs in **both** `wait_for_agent_ready` loops *and* the session-refresh loop: the readiness+budget expires after ~60s and a slow agent can render its dialog later than that. A retry only+happens while the pane is **unchanged** β a redraw means the answer landed, and resending would+type a stray digit into the agent's live composer.++Missing an arm is silent and total: the task's prompt is delivered but never read, because the+agent never reaches its composer. Antigravity and cursor are the worked examples β same bug, two+agents, found within a day of each other by the same smoke run. Antigravity's is the fuller story. It was left unhandled on the+reasoning that its wording matched Claude's and the choice belonged to the user β but "unhandled"+was never neutral: agtx pasted the task into a menu that ignores text, and its follow-up Enter+confirmed the dialog, so **every** antigravity task reached its composer empty with the prompt gone.+Per-agent scoping is what made answering it safe, and the per-agent smoke run+(`tests/smoke/agent_smoke.py`) is what found it. Cursor's was the same shape, and shows why the+scoping matters: its question line is *character-identical* to codex's, whose answer (`1`) is not+even an option in cursor's menu.++Some prompts must stay unanswered, and that is a different thing from being undeclared. Gemini's+first-run `Opening authentication page in your browser. Do you want to continue?` has `1. Yes`+preselected β an Enter would start an OAuth flow and open a browser, which is not a side effect a+phase transition gets to have. Same reasoning as never choosing codex's "Update now".+### Session Persistence- Tmux window stays open when moving Running β Review- Resume from Review simply changes status back to Running (window already exists)@@ -299,6 +376,7 @@ Global config lives at `~/.config/agtx/config.toml` (`GlobalConfig`):```tomldefault_agent = "claude"fullscreen_on_enter = false # When true, Enter on a task attaches to tmux directly instead of opening the in-TUI popup+agent_hooks = true # Write agent lifecycle-hook configs into worktrees (see Hook-Based Phase Status)[agents] # Per-phase agent overrides (PhaseAgentsConfig)research = "claude"@@ -472,11 +550,63 @@ Plugin defaults to the project's active plugin (set via `P` on the board).- Overlap guard: only one refresh thread runs at a time (`session_refresh_rx.is_some()`)- Thread does all expensive work: plugin TOML loading, artifact file checks, `tmux capture-pane`, copy-back side effects- `apply_session_refresh()` applies results on main thread (non-blocking `try_recv`)-- Idle detection (Working β Idle) handled on main thread using `pane_content_hashes` timestamps-- Four states (`PhaseStatus` in `src/db/models.rs`): Working (spinner), Idle (pause icon, 15s no output), Ready (checkmark), Exited (no window)+- Idle detection (Working β Idle) handled on main thread using `pane_content_hashes` timestamps β **only for tasks with no hook report**, see below+- Five states (`PhaseStatus` in `src/db/models.rs`): Working (spinner), Blocked (bold `?`, agent-reported only), Idle (pause icon, 15s no output), Ready (checkmark), Exited (no window)- Phase artifact paths come from the task's plugin or agtx defaults- Plugin instances cached per task in `HashMap<Option<String>, Option<WorkflowPlugin>>` to avoid repeated disk reads+### Hook-Based Phase Status+Agents that support lifecycle hooks report their own state instead of agtx guessing it from pane+output.++```+Claude Code ββhookβββΊ agtx hook <task-id> <worktree> βββΊ {worktree}/.agtx/status/{task_id}.json+ β+ maybe_spawn_session_refresh ββββΊ apply_session_refresh+```++- **Writing the config**: `write_skills_to_worktree()` merges a `hooks` block into the worktree's+ `.claude/settings.local.json` (the same file that carries `enableAllProjectMcpServers`). Built by+ `claude_hook_settings()`. Gated on `config.agent_hooks`; Claude-only today+- **The Claude settings writer merges, it does not overwrite.** `.claude` is in+ `AGENT_CONFIG_DIRS`, so a project shipping its own `settings.local.json` has it copied into every+ worktree β a plain write would drop the user's `permissions`/`env`/`hooks`. `merge_claude_hooks()`+ keeps user entries on the same events and replaces only agtx's own (matched by the agtx binary+ path in the command), so redeploying is idempotent instead of accumulating duplicate hooks. Same+ merge-don't-overwrite rule as the grok and antigravity MCP writers+- **The hook command is task-agnostic**: `agtx hook --env claude`. The task is read from+ `AGTX_TASK_ID` / `AGTX_WORKTREE`, set on the tmux **window** by `create_window` (tmux `-e`, so a+ resumed or switched agent inherits them). Baking the task id into the command breaks+ `skip_worktree`, where every task shares the project's `.claude/settings.local.json` and the last+ deploy would re-point every other task's agent at its own status file. The hook exits silently+ when the variables are absent, so a future user-global registration stays inert outside agtx, and+ when `CLAUDE_JOB_DIR` is set, since a backgrounded task inherits its parent's env+- **Registered events** (verified against Claude Code 2.1.241): `SessionStart`, `UserPromptSubmit`,+ `PreToolUse` (heartbeat) β `working`; `PermissionRequest`, `Notification` β `blocked`; `Stop`,+ `StopFailure` β `waiting`; `SessionEnd` β `ended`. Unregistered names are ignored by the agent+- **`src/agent/hook_status.rs`** is pure (no tmux/DB/TUI types): event mapping, atomic+ write-then-rename, staleness, and `merge_event`'s guard preventing a late `PreToolUse` from+ clearing 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+- **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 is **not** captured when a hook report exists β one fewer `capture-pane` per task per+ refresh. Codex's MCP approval auto-dismiss runs outside that branch so it fires either way+- **Consumers**: `Blocked` fires the orchestrator stuck-task notification *immediately* (with the+ reason text from `blocked_reasons`) rather than after 60s of `Idle`; the merge-conflict trigger+ skips `Blocked` entirely. MCP `get_task` exposes `agent_state` + `blocked_reason`, read straight+ from the file β it works cross-process precisely because it is a file, not TUI state+- **Binary-path drift**: the absolute `agtx` path from `current_exe()` is baked into the hook command+ *and* every MCP config a worktree gets, so moving or reinstalling agtx would silently break both+ for worktrees created earlier. `write_skills_to_worktree` records the deploying binary in+ `.agtx/deployed-by`; `refresh_stale_worktree_configs` re-deploys mismatched worktrees on a+ background thread at startup. `is_agtx_hook_command` matches on the `" hook --env"` invocation+ rather than the binary path so the merge still recognises its own entries across a move+- Not yet wired for Codex/Gemini/Cursor: those read hooks from user-global paths+ (`~/.codex/hooks.json`, `~/.gemini/settings.json`, `~/.cursor/hooks.json`) and need an+ install/uninstall lifecycle plus `cwd`-based routing+### Task References & Dependencies- In description input, type `!` (at start of line or after space) to search existing tasks- Selecting a task inserts `![task-title]` and tracks the reference ID@@ -498,9 +628,13 @@ Plugin defaults to the project's active plugin (set via `P` on the board).- The skill instructs the agent to: commit current work β merge origin/main β resolve conflicts β review only conflicted files against both parents β run tests### Agent Integration+- Every per-agent value below is one field of that agent's `AgentSpec` in `src/agent/spec.rs`; the+ functions here read the table rather than matching on the agent's name- Agents spawned via `build_interactive_command()` in `src/agent/mod.rs`- Each agent has its own flags: Claude (`--dangerously-skip-permissions`), Codex (`--sandbox workspace-write`), Gemini (`GEMINI_TRUST_WORKSPACE=true` + `--approval-mode yolo`), Copilot (`--allow-all-tools`), Cursor (`agent --yolo`), Grok (`--yolo --trust`, where `--trust` also ungates the repo-local `.grok/config.toml` MCP server and suppresses the directory-trust dialog), Antigravity (`agy --dangerously-skip-permissions --mode accept-edits` β two orthogonal controls: the flag governs shell/MCP/URL approvals, `--mode` governs the file-edit diff review, and both are needed to run unattended)-- `build_resume_command()` is the recovery variant used after a tmux/server restart β mostly `--continue`, but Gemini uses `--resume` and Codex uses `codex resume --last`+- `build_resume_command()` is the recovery variant used after a tmux/server restart β mostly `--continue` appended to the launch flags (`ResumeArgs::Append`), but Gemini uses `--resume` and Codex's `resume --last` *replaces* them (`ResumeArgs::Replace`: `codex resume` rejects `--sandbox`)+- `tests/agent_parity_tests.rs` pins every one of these strings per agent. It is written against+ behaviour, not derived from the table, so a diff there means something actually changed- Skills deployed to agent-native paths via `write_skills_to_worktree()` in app.rs- Commands resolved per-task via `resolve_skill_command()` (plugin command + agent transform)- Prompts resolved per-task via `resolve_prompt()` (pure template substitution, agent-agnostic)@@ -516,8 +650,24 @@ cargo test# Run tests with mock supportcargo test --features test-mocks++# Per-agent smoke tests β real binaries, real auth, real tokens (opt-in, never CI)+tests/smoke/agent_smoke.py # installed agents x the agtx plugin+python3 tests/smoke/test_agent_smoke.py # tests for the harness itself```+The smoke runner answers the one question the Rust suite cannot: **does a real agent binary actually+receive its work?** Unit tests mock `TmuxOperations` and `agent_parity_tests.rs` pins the strings+agtx builds, so neither can see "the agent ignored it" β the gap where every silent-hang bug so far+has lived. Per phase it asserts the command was *submitted* (not parked in a composer), that a marker+file carries the **task id** that was passed in, that the artifact appeared and the phase advanced,+and that the session is still usable (process alive, no dialog on screen). Dialogs are never+pre-answered β they are the thing under test. Details: `tests/smoke/README.md`.++`cargo run --example agent_matrix` (source in `tests/smoke/`) dumps `AGENT_SPECS` ++`BUNDLED_PLUGINS` as JSON. The smoke runner reads it instead of keeping its own copy of the agent+table, and `cargo test` compiles it, so a new spec field breaks the build rather than drifting.+Dependencies require:- A recent stable Rust (CI builds on `stable`; no MSRV is pinned in `Cargo.toml`)- SQLite (bundled via rusqlite)@@ -539,32 +689,38 @@ Dependencies require:3. Use `hex_to_color(&state.config.theme.color_*)` in app.rs### Adding a new agent-Adding grok touched every one of these β use `git log -p` for that change as a worked example. Required:--**`src/agent/mod.rs`**-1. Add to `known_agents()` (name, binary, description, git co-author)-2. Add a `build_interactive_command()` match arm (with and without a prompt)-3. Add a `build_resume_command()` match arm (usually `--continue`)--**`src/agent/operations.rs`**-4. Add a `generate_text()` match arm β the headless/print invocation used for PR descriptions--**`src/skills.rs`**-5. Add the agent-native skill dir to `agent_native_skill_dir()`-6. Add the plugin command transform to `transform_plugin_command()`-7. Add a `scan_agent_skills()` branch so the agent's existing skills show up in the `/` skill picker--**`src/tui/app.rs`**-8. Add the binary to `AGENT_COMMANDS` (pane process detection)-9. Add an activity indicator to `AGENT_ACTIVE_INDICATORS` if the agent is an Ink/Node TUI (runs inside bash)-10. Add exit command handling in `switch_agent_in_tmux()` (graceful exit cmd or Ctrl+C)-11. Add the skill-deploy branch in **both** `write_skills_to_worktree()` and `deploy_skill()` (e.g. `"codex" | "cursor" | "grok"` for SKILL.md subdirectories)-12. Add the per-agent MCP config writer in `write_skills_to_worktree()` β note the format varies (JSON vs TOML, `mcpServers` vs `mcp_servers`)-13. Add an agent label color in the task-card footer `match task.agent.as_str()`-14. If Ink/Node TUI: add to the combined-send branch `matches!(agent_name, "gemini" | "codex" | ...)` in `send_skill_and_prompt()`; add double-Enter handling if the agent has a command picker popup+Half of this is now one table entry; the other half is still per-agent match arms in `app.rs`.++**`src/agent/spec.rs`** β the declarative half+1. Add one `AgentSpec` entry to `AGENT_SPECS`: identity (name, binary, description, git co-author),+ launching (`env`, `base_args`, `prompt_form`, `resume`, `headless_args`), and skills+ (`skill_dir`, `skill_layout`, `skill_scan_dir`, `command_syntax`). Everything in+ `src/agent/mod.rs`, `src/agent/operations.rs` and `src/skills.rs` is derived from it β+ `known_agents`, both command builders, the headless invocation, the skill paths, the+ command syntax, and skill discovery+2. Declare `prompt_form` (how the CLI takes a prompt: `Argv` or `Flag("-i")`) but leave+ `launch_prompt_verified: false` until that form is checked against the real binary. A+ `-p`-style flag that runs headless and exits swallows the task text silently; flipping the bool+ is what opts the agent into the launch lane+3. If no existing `SkillLayout` / `CommandSyntax` variant fits, add **one** variant plus the arm in+ the single function that reads it β never a new match on the agent's name++**`tests/agent_parity_tests.rs`**+4. Extend every parity table with the new agent (`parity_covers_every_known_agent` fails until you+ do). These are literals on purpose: a diff there means behaviour changed++**`src/tui/app.rs`** β still per-agent, until stage E+5. Add the binary to `AGENT_COMMANDS` (pane process detection)+6. Add an activity indicator to `AGENT_ACTIVE_INDICATORS` if the agent is an Ink/Node TUI (runs inside bash)+7. Add exit command handling in `switch_agent_in_tmux()` (graceful exit cmd or Ctrl+C)+8. Add the skill-deploy branch in **both** `write_skills_to_worktree()` and `deploy_skill()` (e.g. `"codex" | "cursor" | "grok"` for SKILL.md subdirectories)+9. Add the per-agent MCP config writer in `write_skills_to_worktree()` β note the format varies (JSON vs TOML, `mcpServers` vs `mcp_servers`)+9b. If the agent supports lifecycle hooks, register them so it reports its own phase status (see *Hook-Based Phase Status*); otherwise it falls back to the pane-hash heuristic+10. Add an agent label color in the task-card footer `match task.agent.as_str()`+11. If Ink/Node TUI: add to the combined-send branch `matches!(agent_name, "gemini" | "codex" | ...)` in `send_skill_and_prompt()`; add double-Enter handling if the agent has a command picker popup**Plugins**-15. Add the agent to `supported_agents` in any `plugins/*/plugin.toml` that whitelists agents+12. Add the agent to `supported_agents` in any `plugins/*/plugin.toml` that whitelists agents### Adding a keyboard shortcut1. Find the appropriate `handle_*_key` function in `src/tui/app.rs`diff --git a/Cargo.toml b/Cargo.tomlindex 7cc4974..362fcc7 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -46,6 +46,16 @@ rmcp = { version = "1.7", features = ["server", "macros", "transport-io"] }default = []test-mocks = ["dep:mockall"]+# Dev tooling for the smoke tests, not part of the shipped binary. Declared with+# an explicit path so it can live next to its only consumer in tests/smoke/+# rather than in an `examples/` directory that implies "here is how to use the+# library". Kept an example rather than a bin so `cargo install` never ships it,+# while `cargo test` still compiles it β a new `AgentSpec` field or enum variant+# breaks the build here instead of silently drifting from the runner.+[[example]]+name = "agent_matrix"+path = "tests/smoke/agent_matrix.rs"+[dev-dependencies]tempfile = "3"mockall = "0.13"diff --git a/benchmark/swebench/benchmark.py b/benchmark/swebench/benchmark.pyindex b2f3b6d..cdf9839 100755--- a/benchmark/swebench/benchmark.py+++ b/benchmark/swebench/benchmark.py@@ -149,7 +149,22 @@ class McpClient:self._proc.stdin.write(line)self._proc.stdin.flush()+ # A reply should take milliseconds. This is not a latency budget, it is a+ # deadlock guard: `readline()` on a live-but-silent server blocks forever, and+ # no --phase-timeout can rescue it because the block is inside the MCP call+ # rather than inside the artifact poll that the timeout governs.+ RECV_TIMEOUT_SECONDS = 120+def _recv(self) -> dict:+ import selectors++ with selectors.DefaultSelector() as sel:+ sel.register(self._proc.stdout, selectors.EVENT_READ)+ if not sel.select(timeout=self.RECV_TIMEOUT_SECONDS):+ raise McpError(+ f"MCP server did not respond within {self.RECV_TIMEOUT_SECONDS}s "+ "(agent may be parked on an interactive prompt or a usage limit)"+ )line = self._proc.stdout.readline()if not line:raise McpError("MCP server closed connection")@@ -637,6 +652,40 @@ def setup_container(check=True, capture_output=not verbose,)+ # macOS keeps the Claude OAuth credentials in the login Keychain, not in+ # ~/.claude/.credentials.json, so a subscription login does not travel with the+ # file copy above and the container lands on "Not logged in Β· Please run /login".+ # Materialise the same JSON that Claude Code writes on Linux.+ #+ # The secret is piped through stdin: never written to a host temp file, and+ # never placed in argv where `ps` would expose it.+ if sys.platform == "darwin" and not (claude_dir / ".credentials.json").exists():+ creds = ""+ try:+ creds = subprocess.run(+ ["security", "find-generic-password", "-s", "Claude Code-credentials", "-w"],+ capture_output=True, text=True, check=True,+ ).stdout.strip()+ except (subprocess.CalledProcessError, FileNotFoundError):+ pass+ if creds:+ subprocess.run(+ ["docker", "exec", "-i", container_id, "/bin/bash", "-c",+ "umask 077 && cat > /home/bench/.claude/.credentials.json"],+ input=creds, text=True, check=True, capture_output=not verbose,+ )+ if verbose:+ print(" [docker] Claude credentials taken from the macOS Keychain.",+ file=sys.stderr)+ else:+ print(+ " [docker] WARNING: no Claude credentials found. On macOS the OAuth token "+ "lives in the Keychain; `security` could not read it (you may need to allow "+ "access when prompted). Set ANTHROPIC_API_KEY instead, or the agent will "+ "report 'Not logged in'.",+ file=sys.stderr,+ )+# Copy ~/.claude.json as a snapshot so Claude skips the first-launch welcome screen.claude_json = home / ".claude.json"if claude_json.exists():@@ -688,6 +737,31 @@ def setup_container(capture_output=True,)+ # Drop empty auth keys from the container's settings.json. Because that `env`+ # block outranks process env, an `ANTHROPIC_AUTH_TOKEN: ""` left over from a+ # proxy setup can shadow both the Keychain credentials and a real+ # ANTHROPIC_API_KEY, and the agent reports "Not logged in" with valid auth+ # available. Host file untouched.+ subprocess.run(+ ["docker", "exec", container_id, "/bin/bash", "-c",+ "python3 - <<'ENDOFPATCH'\n"+ "import json\n"+ "p='/home/bench/.claude/settings.json'\n"+ "try:\n"+ " d=json.load(open(p))\n"+ "except Exception:\n"+ " raise SystemExit(0)\n"+ "env=d.get('env')\n"+ "if isinstance(env, dict):\n"+ " drop=[k for k,v in env.items() if v == '']\n"+ " for k in drop: env.pop(k)\n"+ " if drop:\n"+ " json.dump(d, open(p,'w'), indent=2)\n"+ " print('dropped empty env keys: ' + ', '.join(drop))\n"+ "ENDOFPATCH"],+ capture_output=not verbose,+ )+# Write global agtx config for bench user so the TUI skips the agent-selection wizardglobal_config_content = f'default_agent = "{default_agent}"\n'if verbose:@@ -810,7 +884,7 @@ def start_tui_in_container(slug: str, container_id: str, verbose: bool = False)# Pass through API keys that agents read from the environment (only when set# on the host). Grok uses XAI_API_KEY when ~/.grok/auth.json is absent.passthrough_env = {- k: v for k in ("XAI_API_KEY",) if (v := os.environ.get(k))+ k: v for k in ("XAI_API_KEY", "ANTHROPIC_API_KEY") if (v := os.environ.get(k))}for key, val in passthrough_env.items():env_prefix += f" {key}={shlex.quote(val)}"@@ -1269,6 +1343,12 @@ class TaskRunner:r"\[Y/N\]",r"Press Enter to continue",r"Press any key",+ # Claude's usage-limit pause. It ends the turn and waits on a keypress+ # that nothing sends, so the task parks indefinitely β observed sitting+ # ~50 minutes, past both the stated reset time and --phase-timeout.+ # Matching it turns a silent stall into a named failure.+ r"You've hit your session limit",+ r"Press .* to continue after reset",]def _check_interactive_prompt(self, content: str) -> str | None:@@ -1341,6 +1421,20 @@ class TaskRunner:def run(self) -> dict:start = time.monotonic()+ # What `git diff <base_commit>` already reports before the agent has done+ # anything. SWE-bench images are not pristine checkouts of base_commit:+ # for astropy-12907 the baseline is 1861 files (3722 lines of+ # `old mode 100644` / `new mode 100755`) plus the image's own+ # `setuptools==68.0.0` pin in pyproject.toml. Subtracted at collection so+ # a real fix is not buried in ~224KB of noise.+ self.baseline_patch = self._raw_diff()+ if self.verbose and self.baseline_patch:+ n = self.baseline_patch.count("diff --git ")+ print(+ f" [{self.instance_id}] Baseline diff: {n} file(s) already differ from "+ f"base_commit before the agent runs; these are excluded from the prediction.",+ file=sys.stderr,+ )if self.verbose:print(f" [{self.instance_id}] Starting MCP handshake...", file=sys.stderr)self.mcp = McpClient(self.agtx_bin, str(self.repo_path), container_id=self.container_id)@@ -1469,7 +1563,47 @@ class TaskRunner:if self.mcp:self.mcp.close()+ @staticmethod+ def _split_file_sections(patch: str) -> dict[str, str]:+ """Split a unified diff into {path_header: section_text}."""+ sections: dict[str, str] = {}+ current: str | None = None+ buf: list[str] = []+ for line in patch.splitlines(keepends=True):+ if line.startswith("diff --git "):+ if current is not None:+ sections[current] = "".join(buf)+ current = line.strip()+ buf = [line]+ elif current is not None:+ buf.append(line)+ if current is not None:+ sections[current] = "".join(buf)+ return sections++ def _strip_baseline(self, patch: str) -> str:+ """Drop file sections identical to the pre-agent baseline.++ Per file rather than per line: a file the agent genuinely edited has a+ different section and survives whole, so an agent that legitimately+ touches pyproject.toml is not silently dropped along with the image's+ own pin of it.+ """+ baseline = getattr(self, "baseline_patch", "") or ""+ if not baseline:+ return patch+ base_sections = self._split_file_sections(baseline)+ kept = [+ text+ for header, text in self._split_file_sections(patch).items()+ if base_sections.get(header) != text+ ]+ return "".join(kept)+def _collect_patch(self, task: dict) -> str:+ return self._strip_baseline(self._raw_diff(task))++ def _raw_diff(self, task: dict | None = None) -> str:base_commit = self.instance["base_commit"]if self.container_id:@@ -1486,7 +1620,7 @@ class TaskRunner:return ""return result.stdout.decode("utf-8", errors="replace")- worktree_path = task.get("worktree_path")+ worktree_path = (task or {}).get("worktree_path") or str(self.repo_path)if not worktree_path:return ""# Diff the worktree's actual files against the base commit.diff --git a/src/agent/hook_status.rs b/src/agent/hook_status.rsnew file mode 100644index 0000000..e156388--- /dev/null+++ b/src/agent/hook_status.rs@@ -0,0 +1,277 @@+//! Agent-reported lifecycle status, written by agent hooks and read by the TUI.+//!+//! Agents that support lifecycle hooks (currently Claude Code) are configured to+//! invoke `agtx hook <task-id> <worktree>` on session/turn/tool events. That+//! subcommand parses the hook's JSON payload from stdin and writes+//! `.agtx/status/{task_id}.json` inside the worktree. The board's session-refresh+//! thread reads that file instead of guessing liveness from `tmux capture-pane`+//! output.+//!+//! This module is deliberately free of tmux, database and TUI types so the event+//! mapping and staleness rules can be unit-tested in isolation β the same+//! precedent as `src/tui/dep_graph.rs`.++use anyhow::Result;+use serde::{Deserialize, Serialize};+use std::io::Read;+use std::path::{Path, PathBuf};++/// Directory (relative to a worktree) holding per-task status files.+pub const STATUS_DIR: &str = ".agtx/status";++/// A `Working` record older than this is distrusted and the caller falls back to+/// the pane-hash heuristic. Covers an agent killed without firing `SessionEnd`+/// and an agent build that dropped an event. Only `Working` decays β a blocked+/// agent stays blocked indefinitely.+pub const HOOK_STALE_SECS: i64 = 300;++/// How long a `Blocked` record is protected from being overwritten by a+/// `Working` event. Claude can emit a `PreToolUse` for the very tool it is+/// asking permission for, which would otherwise clear the block immediately.+pub const BLOCKED_GUARD_SECS: i64 = 2;++/// Maximum stdin payload accepted from a hook invocation.+pub const MAX_PAYLOAD_BYTES: usize = 64 * 1024;++/// Longest `message` / `tool` string retained; hook payloads are untrusted input+/// and this text reaches the TUI and orchestrator notifications.+const MAX_FIELD_CHARS: usize = 512;++/// What the agent last told us about itself.+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]+pub struct AgentHookStatus {+ /// Unix seconds when the event was recorded.+ pub ts: i64,+ pub state: HookState,+ /// Agent-reported session id, for future resume-by-id.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub session_id: Option<String>,+ /// Path to the agent's own transcript, when reported.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub transcript_path: Option<String>,+ /// The permission prompt or question text, when the agent is Blocked.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub message: Option<String>,+ /// Tool name from the last PreToolUse β heartbeat detail.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub tool: Option<String>,+ /// Which agent wrote this record.+ pub agent: String,+}++#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]+#[serde(rename_all = "snake_case")]+pub enum HookState {+ /// Turn in progress, or a tool is running.+ Working,+ /// Stopped, awaiting a permission decision or an answer from the user.+ Blocked,+ /// Turn ended; the composer is idle and accepting input.+ Waiting,+ /// Session terminated.+ Ended,+}++/// Map a Claude Code `hook_event_name` to a state.+///+/// `None` means the event carries no state transition and any stored record+/// should be left alone rather than overwritten.+pub fn map_claude_event(event: &str) -> Option<HookState> {+ match event {+ "SessionStart" | "UserPromptSubmit" | "PreToolUse" => Some(HookState::Working),+ "PermissionRequest" | "Notification" => Some(HookState::Blocked),+ "Stop" | "StopFailure" => Some(HookState::Waiting),+ "SessionEnd" => Some(HookState::Ended),+ _ => None,+ }+}++/// Path to a task's status file inside its worktree.+pub fn status_path(worktree: &Path, task_id: &str) -> PathBuf {+ worktree.join(STATUS_DIR).join(format!("{}.json", task_id))+}++/// Read and parse a task's status record.+///+/// Returns `None` when the file is missing, unparseable, or holds a `Working`+/// record older than [`HOOK_STALE_SECS`] β in every one of those cases the+/// caller should fall back to the pane-hash heuristic.+pub fn read_status(worktree: &Path, task_id: &str, now: i64) -> Option<AgentHookStatus> {+ let raw = std::fs::read_to_string(status_path(worktree, task_id)).ok()?;+ let status: AgentHookStatus = serde_json::from_str(&raw).ok()?;+ if status.state == HookState::Working && now.saturating_sub(status.ts) > HOOK_STALE_SECS {+ return None;+ }+ Some(status)+}++/// Write a status record atomically: temp file in the same directory, then rename.+///+/// The rename is what makes a concurrent reader see either the old record or the+/// new one, never a half-written file.+pub fn write_status(worktree: &Path, task_id: &str, status: &AgentHookStatus) -> Result<()> {+ let path = status_path(worktree, task_id);+ if let Some(parent) = path.parent() {+ std::fs::create_dir_all(parent)?;+ }+ // Include the pid so two hooks racing on the same task can't truncate each+ // other's temp file before either rename lands.+ let tmp = path.with_extension(format!("tmp{}", std::process::id()));+ std::fs::write(&tmp, serde_json::to_string(status)?)?;+ std::fs::rename(&tmp, &path)?;+ Ok(())+}++/// Decide the record to persist given an incoming event and whatever is stored.+///+/// Returns `None` when the event should not change the stored record. Two rules:+/// an event with no state mapping is ignored, and a `Working` event is dropped+/// while a fresh `Blocked` record stands β Claude emits `PreToolUse` for the very+/// tool it is requesting permission for, which would otherwise clear the block.+pub fn merge_event(+ previous: Option<&AgentHookStatus>,+ event: &str,+ now: i64,+ agent: &str,+ session_id: Option<String>,+ transcript_path: Option<String>,+ message: Option<String>,+ tool: Option<String>,+) -> Option<AgentHookStatus> {+ let state = map_claude_event(event)?;++ if state == HookState::Working {+ if let Some(prev) = previous {+ if prev.state == HookState::Blocked && now.saturating_sub(prev.ts) <= BLOCKED_GUARD_SECS+ {+ return None;+ }+ }+ }++ // Carry forward identity fields the current event didn't report, so a `Stop`+ // payload doesn't erase the session id learned at `SessionStart`.+ let prev_session = previous.and_then(|p| p.session_id.clone());+ let prev_transcript = previous.and_then(|p| p.transcript_path.clone());++ Some(AgentHookStatus {+ ts: now,+ state,+ session_id: session_id.or(prev_session),+ transcript_path: transcript_path.or(prev_transcript),+ // `message` is only meaningful for the event that produced it.+ message: if state == HookState::Blocked {+ message.map(|m| truncate(&m))+ } else {+ None+ },+ tool: tool.map(|t| truncate(&t)),+ agent: agent.to_string(),+ })+}++fn truncate(s: &str) -> String {+ let cleaned: String = s+ .chars()+ .filter(|c| !c.is_control() || *c == '\n' || *c == '\t')+ .collect();+ let trimmed = cleaned.trim();+ if trimmed.chars().count() <= MAX_FIELD_CHARS {+ return trimmed.to_string();+ }+ trimmed.chars().take(MAX_FIELD_CHARS).collect()+}++/// Fields lifted from a hook's JSON payload. Every field is optional β agents+/// disagree about which they send, and a missing field must never be fatal.+#[derive(Debug, Default, Deserialize)]+struct HookPayload {+ hook_event_name: Option<String>,+ session_id: Option<String>,+ transcript_path: Option<String>,+ message: Option<String>,+ tool_name: Option<String>,+}++/// Environment variables identifying the task a hook is reporting about, set on+/// the tmux window by `create_window`.+pub const ENV_TASK_ID: &str = "AGTX_TASK_ID";+pub const ENV_WORKTREE: &str = "AGTX_WORKTREE";++/// Entry point for `agtx hook --env` (preferred) or `agtx hook <task-id> <worktree> [agent]`.+///+/// `--env` reads the task from the process environment instead of argv, so the+/// registered hook command is identical for every task. That matters because a+/// single config file can serve several tasks β under `skip_worktree` they all+/// share the project's `.claude/settings.local.json` β and because a+/// task-agnostic command is what a future user-global install would need.+///+/// If the variables are absent the hook exits silently: a globally registered+/// hook must be inert in the user's own sessions outside agtx.+///+/// Always succeeds. A hook that reports an error can break the agent's turn, and+/// no status update is worth that β every failure path here is a silent no-op+/// after the mandatory `{}` on stdout.+pub fn run_hook_cli(args: &[String]) -> Result<()> {+ // Claude-compatible permission hooks fail closed on empty stdout, so this+ // must be printed before any early return.+ println!("{{}}");++ let from_env = args.first().map(String::as_str) == Some("--env");+ let (task_id, worktree, agent);+ if from_env {+ // A backgrounded agent task runs in a worker that inherited the pane's+ // env, so these would name a task it is not running in.+ if std::env::var_os("CLAUDE_JOB_DIR").is_some() {+ return Ok(());+ }+ let (Ok(t), Ok(w)) = (std::env::var(ENV_TASK_ID), std::env::var(ENV_WORKTREE)) else {+ return Ok(());+ };+ if t.is_empty() || w.is_empty() {+ return Ok(());+ }+ task_id = t;+ worktree = w;+ agent = args.get(1).cloned().unwrap_or_else(|| "claude".to_string());+ } else {+ let (Some(t), Some(w)) = (args.first(), args.get(1)) else {+ return Ok(());+ };+ task_id = t.clone();+ worktree = w.clone();+ agent = args.get(2).cloned().unwrap_or_else(|| "claude".to_string());+ }+ let (task_id, worktree, agent) = (task_id.as_str(), worktree.as_str(), agent.as_str());++ let mut buf = Vec::new();+ if std::io::stdin()+ .take(MAX_PAYLOAD_BYTES as u64)+ .read_to_end(&mut buf)+ .is_err()+ {+ return Ok(());+ }+ let payload: HookPayload = serde_json::from_slice(&buf).unwrap_or_default();+ let Some(event) = payload.hook_event_name.as_deref() else {+ return Ok(());+ };++ let worktree = Path::new(worktree);+ let now = chrono::Utc::now().timestamp();+ let previous = read_status(worktree, task_id, now);++ if let Some(next) = merge_event(+ previous.as_ref(),+ event,+ now,+ agent,+ payload.session_id,+ payload.transcript_path,+ payload.message,+ payload.tool_name,+ ) {+ let _ = write_status(worktree, task_id, &next);+ }+ Ok(())+}diff --git a/src/agent/mod.rs b/src/agent/mod.rsindex 2cc06a9..3e94596 100644--- a/src/agent/mod.rs+++ b/src/agent/mod.rs@@ -1,6 +1,12 @@+pub mod hook_status;mod operations;+pub mod spec;pub use operations::{AgentOperations, AgentRegistry, CodingAgent, RealAgentRegistry};+pub use spec::{+ spec, AgentDialog, AgentSpec, CommandSyntax, DialogScope, McpConfigKind, PromptForm,+ ResumeArgs, SendStrategy, SkillLayout, AGENT_SPECS,+};#[cfg(feature = "test-mocks")]pub use operations::{MockAgentOperations, MockAgentRegistry};@@ -12,22 +18,69 @@ use serde::{Deserialize, Serialize};pub struct Agent {pub name: String,pub command: String,- pub args: Vec<String>,pub description: String,pub co_author: String,}+/// How an agent accepts an initial prompt at launch.+///+/// `Argv`/`FlagInteractive` let agtx hand the opening message to the process+/// itself, so there is no window in which keystrokes can be dropped and nothing+/// to poll for. `Unknown` keeps the historical path: launch bare, wait for the+/// TUI to look ready, then type.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum PromptInjection {+ /// Positional argument: `claude "<text>"`.+ Argv,+ /// Interactive prompt flag: `gemini -i "<text>"`.+ FlagInteractive(&'static str),+ /// No verified interactive launch form β send after readiness instead.+ Unknown,+}+impl Agent {+ /// Whether this agent can take the opening message at launch.+ ///+ /// Derived from the agent's spec: the launch *form* is always known, but it+ /// is only used once verified against the real binary, because getting this+ /// wrong means the task text is silently swallowed (a `-p`-style flag that+ /// runs headless and exits) rather than failing loudly.+ pub fn prompt_injection(&self) -> PromptInjection {+ match spec::spec(&self.name) {+ Some(s) if s.launch_prompt_verified => match s.prompt_form {+ spec::PromptForm::Argv => PromptInjection::Argv,+ spec::PromptForm::Flag(flag) => PromptInjection::FlagInteractive(flag),+ },+ _ => PromptInjection::Unknown,+ }+ }+pub fn new(name: &str, command: &str, description: &str, co_author: &str) -> Self {Self {name: name.to_string(),command: command.to_string(),- args: vec![],description: description.to_string(),co_author: co_author.to_string(),}}+ /// Argv for the agent's headless (print) invocation, used for one-shot+ /// generation like PR descriptions.+ ///+ /// Note this deliberately does *not* apply the interactive launch env+ /// (Gemini's `GEMINI_TRUST_WORKSPACE`): headless runs never touch the+ /// workspace, and adding it here would change behaviour.+ pub fn headless_invocation<'a>(&'a self, prompt: &'a str) -> (&'a str, Vec<&'a str>) {+ match spec::spec(&self.name) {+ Some(s) => {+ let mut args: Vec<&str> = s.headless_args.to_vec();+ args.push(prompt);+ (s.binary, args)+ }+ None => (self.command.as_str(), vec![prompt]),+ }+ }+/// Check if this agent is installed on the systempub fn is_available(&self) -> bool {which::which(&self.command).is_ok()@@ -36,116 +89,38 @@ impl Agent {/// Build the shell command to resume the agent's most recent session/// in the current working directory. Used to recover from tmux/server restarts.pub fn build_resume_command(&self) -> String {- match self.name.as_str() {- "claude" => "claude --dangerously-skip-permissions --continue".to_string(),- "codex" => "codex resume --last".to_string(),- "copilot" => "copilot --allow-all-tools --continue".to_string(),- "gemini" => "GEMINI_TRUST_WORKSPACE=true gemini --approval-mode yolo --resume".to_string(),- "opencode" => "opencode --continue".to_string(),- "cursor" => "agent --yolo --continue".to_string(),- "grok" => "grok --yolo --trust --continue".to_string(),- "antigravity" => {- "agy --dangerously-skip-permissions --mode accept-edits --continue".to_string()- }- _ => self.build_interactive_command(""),- }+ let Some(s) = spec::spec(&self.name) else {+ // Nothing is known about how this agent resumes; start it fresh.+ return self.build_interactive_command("");+ };+ let args: Vec<&str> = match s.resume {+ spec::ResumeArgs::Append(extra) => s.base_args.iter().chain(extra).copied().collect(),+ spec::ResumeArgs::Replace(args) => args.to_vec(),+ };+ spec::compose_command(s, &args, None)}/// Build the shell command to start the agent interactively./// When prompt is empty, the agent starts with no initial message/// (task content and skill commands are sent later via tmux send_keys).pub fn build_interactive_command(&self, prompt: &str) -> String {- if prompt.is_empty() {- return match self.name.as_str() {- "claude" => "claude --dangerously-skip-permissions".to_string(),- "codex" => "codex --sandbox workspace-write".to_string(),- "copilot" => "copilot --allow-all-tools".to_string(),- "gemini" => "GEMINI_TRUST_WORKSPACE=true gemini --approval-mode yolo".to_string(),- "opencode" => "opencode".to_string(),- "cursor" => "agent --yolo".to_string(),- "grok" => "grok --yolo --trust".to_string(),- "antigravity" => {- "agy --dangerously-skip-permissions --mode accept-edits".to_string()- }- _ => self.command.clone(),- };- }-- let escaped_prompt = prompt.replace('\'', "'\"'\"'");- match self.name.as_str() {- "claude" => format!("claude --dangerously-skip-permissions '{}'", escaped_prompt),- "codex" => format!("codex --sandbox workspace-write '{}'", escaped_prompt),- "copilot" => format!("copilot --allow-all-tools -p '{}'", escaped_prompt),- "gemini" => format!("GEMINI_TRUST_WORKSPACE=true gemini --approval-mode yolo -i '{}'", escaped_prompt),- "opencode" => format!("opencode -p '{}'", escaped_prompt),- "cursor" => format!("agent --yolo '{}'", escaped_prompt),- "grok" => format!("grok --yolo --trust '{}'", escaped_prompt),- // -i / --prompt-interactive runs the prompt and keeps the session open,- // the same shape as Gemini's -i.- "antigravity" => format!(- "agy --dangerously-skip-permissions --mode accept-edits -i '{}'",- escaped_prompt- ),- _ => format!("{} '{}'", self.command, escaped_prompt),+ match spec::spec(&self.name) {+ Some(s) => spec::compose_command(s, s.base_args, Some(prompt)),+ None if prompt.is_empty() => self.command.clone(),+ None => format!("{} '{}'", self.command, prompt.replace('\'', "'\"'\"'")),}}}-/// Get the list of known agents+/// Get the list of known agents, in preference order.+///+/// Derived from [`AGENT_SPECS`] β adding an agent means adding a spec entry,+/// not editing this function.pub fn known_agents() -> Vec<Agent> {- vec![- Agent::new(- "claude",- "claude",- "Anthropic's Claude Code CLI",- "Claude <[email protected]>",- ),- Agent::new(- "codex",- "codex",- "OpenAI's Codex CLI",- "Codex <[email protected]>",- ),- Agent::new(- "copilot",- "copilot",- "GitHub Copilot CLI",- "GitHub Copilot <[email protected]>",- ),- Agent::new(- "gemini",- "gemini",- "Google Gemini CLI",- "Gemini <[email protected]>",- ),- Agent::new(- "opencode",- "opencode",- "AI-powered coding assistant",- "OpenCode <[email protected]>",- ),- Agent::new(- "cursor",- "agent",- "Cursor Agent CLI",- "Cursor Agent <[email protected]>",- ),- Agent::new(- "grok",- "grok",- "xAI's Grok Build CLI",- "Grok <[email protected]>",- ),- Agent::new(- "antigravity",- "agy",- "Google's Antigravity CLI",- "Antigravity <[email protected]>",- ),- // TODO: investigate CLI usage before enabling- // Agent::new("aider", "aider", "AI pair programming in your terminal", "Aider <[email protected]>"),- // Agent::new("cline", "cline", "AI coding assistant for VS Code", "Cline <[email protected]>"),- ]+ spec::AGENT_SPECS+ .iter()+ .map(|s| Agent::new(s.name, s.binary, s.description, s.co_author))+ .collect()}/// Detect which agents are available on the system@@ -194,4 +169,3 @@ pub fn parse_agent_selection(input: &str, agent_count: usize) -> Option<usize> {}None}-diff --git a/src/agent/operations.rs b/src/agent/operations.rsindex 36fdde7..2c2e7f4 100644--- a/src/agent/operations.rs+++ b/src/agent/operations.rs@@ -32,6 +32,12 @@ pub trait AgentOperations: Send + Sync {/// in the current working directory. Used to recover from tmux/server restarts.fn build_resume_command(&self) -> String;+ /// Whether this agent takes the opening message at launch; see+ /// [`crate::agent::PromptInjection`].+ fn prompt_injection(&self) -> crate::agent::PromptInjection {+ crate::agent::PromptInjection::Unknown+ }+/// Build the full shell command to run this agent as an orchestrator./// Includes MCP registration (if supported by the agent) and cleanup on exit./// Default implementation: no MCP, just launches the agent interactively.@@ -54,17 +60,7 @@ impl CodingAgent {impl AgentOperations for CodingAgent {fn generate_text(&self, working_dir: &Path, prompt: &str) -> Result<String> {- // Build the command based on agent type- let (cmd, args) = match self.agent.name.as_str() {- "claude" => ("claude", vec!["--print", prompt]),- "codex" => ("codex", vec!["exec", "--sandbox", "workspace-write", prompt]),- "copilot" => ("copilot", vec!["-p", prompt]),- "gemini" => ("gemini", vec!["-p", prompt]),- "cursor" => ("agent", vec!["--print", "--yolo", prompt]),- "grok" => ("grok", vec!["-p", prompt]),- "antigravity" => ("agy", vec!["-p", prompt]),- _ => (self.agent.command.as_str(), vec![prompt]),- };+ let (cmd, args) = self.agent.headless_invocation(prompt);let output = std::process::Command::new(cmd).current_dir(working_dir)@@ -91,6 +87,10 @@ impl AgentOperations for CodingAgent {self.agent.build_resume_command()}+ fn prompt_injection(&self) -> crate::agent::PromptInjection {+ self.agent.prompt_injection()+ }+fn build_orchestrator_command(&self, mcp_json: &str, _agtx_bin: &str) -> String {match self.agent.name.as_str() {// Register under a unique name (`agtx-orchestrator`) rather than@@ -104,16 +104,17 @@ impl AgentOperations for CodingAgent {// `mcp remove`) so `add-json` doesn't fail with "already exists" and// short-circuit the `&&` into an empty shell.//- // The JSON must be single-quoted for `add-json`, but this whole- // command is itself wrapped in `sh -c '...'` by create_window. A bare- // `'{json}'` would close that outer quote and let the shell mangle the- // JSON (yielding "Invalid configuration: Invalid input"). Escape the- // wrapping quotes as `'\''` (the POSIX single-quote-in-single-quote- // idiom, same convention build_interactive_command uses for prompts)- // so they survive the outer `sh -c` layer intact.+ // The JSON is a single-quoted word for `add-json`, and that is all+ // this layer does. `create_window` wraps the whole command in+ // `sh -c 'β¦'` and quotes it properly on the way through+ // (`single_quote` in src/tmux/operations.rs), so the wrapping quotes+ // must **not** be pre-escaped here β doing so double-escapes them and+ // the inner shell dies on an unterminated quote before `add-json`+ // ever runs. Any apostrophe *inside* the JSON is escaped by the+ // caller, which is the only thing that needs handling at this layer."claude" => format!("claude mcp remove agtx-orchestrator --scope local 2>/dev/null || true; \- claude mcp add-json agtx-orchestrator '\\''{}'\\'' --scope local && {}; \+ claude mcp add-json agtx-orchestrator '{}' --scope local && {}; \claude mcp remove agtx-orchestrator --scope local",mcp_json,self.build_interactive_command("")diff --git a/src/agent/spec.rs b/src/agent/spec.rsnew file mode 100644index 0000000..c523645--- /dev/null+++ b/src/agent/spec.rs@@ -0,0 +1,747 @@+//! One declarative record per coding agent.+//!+//! Everything agtx knows about an agent that is *data* lives here; everything+//! that is *behaviour* is selected by a small closed enum stored in the record+//! rather than by re-matching the agent's name in each function. The short+//! version is that a name-match ending in `_ => {}` cannot tell you an agent was+//! only half added, and a kind-match over a closed enum can.+//!+//! The record is deliberately pure data (no closures, no `String`) so that it+//! can later be deserialized from a `[[agents]]` block in `config.toml`, which+//! is what makes user-defined agents possible.+//!+//! Adding an agent is one entry in [`AGENT_SPECS`]. If a field cannot express+//! it, the right move is one new enum variant plus one new match arm in the one+//! function that reads that enum β not a new match on the agent's name.++/// How a non-empty prompt is appended to the agent's launch command.+///+/// This is the *shape of the CLI*, not a statement about whether agtx trusts it+/// β see [`AgentSpec::launch_prompt_verified`] for that.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum PromptForm {+ /// Positional argument: `claude '<text>'`.+ Argv,+ /// Prompt flag: `gemini -i '<text>'`.+ Flag(&'static str),+}++/// How the resume flags combine with [`AgentSpec::base_args`].+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum ResumeArgs {+ /// Appended after the launch flags: `claude --dangerously-skip-permissions --continue`.+ Append(&'static [&'static str]),+ /// Replaces the launch flags entirely: `codex resume --last` takes no `--sandbox`.+ Replace(&'static [&'static str]),+}++/// How skill files are laid out in the agent's native discovery directory, and+/// therefore also how existing skills are found when scanning a project.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum SkillLayout {+ /// `{base}/{namespace}/{short-name}.md` β Claude, Copilot.+ CommandFile,+ /// `{base}/{namespace}/{short-name}.toml` β Gemini's TOML command format.+ GeminiToml,+ /// `{base}/{full-name}/SKILL.md` β Codex, Cursor, Grok, Antigravity.+ SkillDir,+ /// `{base}/{full-name}.md`, flat, no namespace subdir β OpenCode.+ OpenCodeFlat,+}++/// Slash-command syntax the agent's TUI accepts for an invocable skill.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum CommandSyntax {+ /// `/ns:command` β the canonical form, unchanged.+ Colon,+ /// `/ns-command` β colon becomes a hyphen, the slash is kept.+ Hyphen,+ /// `$ns-command` β Codex's inline skill reference.+ Dollar,+ /// No interactive skill invocation; callers fall back to a file-path+ /// reference. Copilot, and any agent agtx has not been taught.+ None,+}++/// When an agent's dialog appears, which decides how it is matched.+///+/// The distinction is forced by what each call site knows. `wait_for_agent_ready`+/// is handed only a tmux target, so it matches `Launch` dialogs against any pane+/// regardless of agent β a false positive is possible in principle. The+/// session-refresh loop *does* know which agent runs in the pane, so `Session`+/// dialogs are matched only against their own agent.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum DialogScope {+ /// Shown once when the agent opens in a directory it has not seen.+ Launch,+ /// Shown mid-session, e.g. the first time the agent calls an MCP tool.+ Session,+}++/// An interactive prompt that blocks the agent until it is answered.+#[derive(Debug, Clone, Copy)]+pub struct AgentDialog {+ /// Text to look for in the pane. Combined per [`require_all`](Self::require_all).+ pub patterns: &'static [&'static str],+ /// When false the patterns are **alternatives**: any one matching is enough,+ /// which is how a dialog whose wording varies between versions is caught.+ /// When true they are a **conjunction**: all must be present, for a prompt+ /// identified by a combination of phrases rather than one distinctive string.+ pub require_all: bool,+ /// The keys that answer it, in order, sent through tmux's key-name lookup.+ ///+ /// A sequence rather than a single key because menus differ in kind: a+ /// numbered menu needs the digit *and* an Enter to confirm it, while an+ /// arrow-navigated menu whose safe option is already highlighted needs only+ /// the Enter β antigravity's trust prompt is the latter, and sending it a+ /// digit first would type a stray character into the composer it opens.+ pub answer: &'static [&'static str],+ pub scope: DialogScope,+}++impl AgentDialog {+ /// Whether this dialog is visible in `content`.+ pub fn matches(&self, content: &str) -> bool {+ if self.require_all {+ self.patterns.iter().all(|p| content.contains(p))+ } else {+ self.patterns.iter().any(|p| content.contains(p))+ }+ }+}++/// How a mid-session message (a phase advance into a running agent) is delivered.+///+/// The plan that introduced this sketched a fourth variant, `CombinedThenPicker`,+/// for Codex's second Enter. Bracketed paste removed the need for it: Codex's+/// `$skill` picker opens on typing, not on a paste, so there is nothing to+/// dismiss. Three variants, not four.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum SendStrategy {+ /// Send the command, optionally wait on a `prompt_trigger`, then the prompt.+ Generic,+ /// Combine skill and prompt into one bracketed paste, then a single Enter.+ /// Ink-class TUIs need this: they lose a separately-sent prompt, and a typed+ /// newline submits the message half-written.+ Combined,+ /// OpenCode's command picker strips arguments when the whole string is typed+ /// at once, so the text must arrive in two pieces by design.+ OpenCodePicker,+}++/// Where and how an agent's project-scoped MCP server config is written.+///+/// Seven variants for seven agents, which looks untidy and is: the formats+/// genuinely differ (JSON vs TOML, `mcpServers` vs `mcp_servers` vs `mcp`). What+/// the enum buys is that the mess lives in one function instead of a 170-line+/// match inside `write_skills_to_worktree`, and that the names now say *why* the+/// arms differ.+///+/// The `β¦Merge` variants must not overwrite: their file is vendor-neutral or+/// otherwise likely to be tracked in the repo already, so clobbering it destroys+/// the user's own settings.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum McpConfigKind {+ /// `.mcp.json`. Also writes `.claude/settings.local.json`+ /// (`enableAllProjectMcpServers`, the bypass preflight, and agtx's hooks).+ ClaudeJson,+ /// `.codex/config.toml`. Also appends a trust entry for the worktree to the+ /// user's global `~/.codex/config.toml`, without which Codex prompts on open.+ CodexToml,+ /// `.gemini/settings.json`, which additionally needs `trust: true`.+ GeminiJson,+ /// `.cursor/mcp.json`.+ CursorJson,+ /// `.grok/config.toml` β appended if the agtx table is absent.+ GrokTomlMerge,+ /// `.agents/mcp_config.json` β parsed, agtx inserted, written back, so other+ /// servers and sibling top-level keys survive.+ AntigravityJsonMerge,+ /// `opencode.json`, whose key is `mcp` and whose entry shape differs.+ OpenCode,+}++/// Everything agtx knows about one coding agent.+#[derive(Debug, Clone, Copy)]+pub struct AgentSpec {+ // ββ identity βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+ pub name: &'static str,+ /// Executable name, which is not always the agent's name: `cursor` ships+ /// `agent`, `antigravity` ships `agy`.+ pub binary: &'static str,+ pub description: &'static str,+ pub co_author: &'static str,++ // ββ launching ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+ /// Environment assignments prefixed to the interactive launch command.+ /// Not applied to the headless invocation, which never touches the workspace.+ pub env: &'static [(&'static str, &'static str)],+ /// Flags that make the agent run unattended (permission bypass, sandbox mode).+ pub base_args: &'static [&'static str],+ pub prompt_form: PromptForm,+ /// Whether [`prompt_form`](Self::prompt_form) has been checked against the+ /// real binary and may be used to hand the agent its opening message at+ /// launch.+ ///+ /// Deliberately conservative. Getting this wrong swallows the task text+ /// silently rather than failing loudly: OpenCode's `-p`, like Copilot's used+ /// to be, is print mode β it answers once and exits, killing the window.+ /// Flip this only after verifying against the installed CLI.+ pub launch_prompt_verified: bool,+ pub resume: ResumeArgs,+ /// Flags for the one-shot print invocation used to generate PR descriptions.+ pub headless_args: &'static [&'static str],++ // ββ skills & commands ββββββββββββββββββββββββββββββββββββββββββββββββ+ /// `(base_dir, namespace_subdir)` relative to the worktree, or `None` for an+ /// agent with no native skill discovery. The namespace is empty for layouts+ /// that carry the prefix in the file or directory name instead.+ pub skill_dir: Option<(&'static str, &'static str)>,+ pub skill_layout: SkillLayout,+ /// Directory scanned for the agent's *pre-existing* skills. Normally the+ /// same as `skill_dir`'s base; OpenCode is the exception.+ pub skill_scan_dir: Option<&'static str>,+ pub command_syntax: CommandSyntax,++ // ββ integration ββββββββββββββββββββββββββββββββββββββββββββββββββββββ+ /// How this agent's project-scoped MCP config is written, or `None` for an+ /// agent agtx does not wire up to the MCP server.+ pub mcp_config: Option<McpConfigKind>,++ // ββ process / liveness βββββββββββββββββββββββββββββββββββββββββββββββ+ /// Process names this agent may appear as in `pane_current_command`.+ ///+ /// Node/Ink agents often report `node` or `bash` instead of their own name,+ /// which is what `active_indicators` is for.+ pub process_names: &'static [&'static str],+ /// Strings in pane content that mean this agent's TUI is up and ready.+ ///+ /// Needed for agents that run inside bash/node and so never show their own+ /// name in `pane_current_command`.+ pub active_indicators: &'static [&'static str],+ /// Command that makes the agent exit cleanly, or `None` when Ctrl+C is the+ /// only way out.+ pub exit_command: Option<&'static str>,++ // ββ display ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+ /// Foreground colour of the agent label on a task card.+ pub label_fg: (u8, u8, u8),+ /// Background colour, for the agents whose branding is a filled chip.+ pub label_bg: Option<(u8, u8, u8)>,++ // ββ sending ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+ pub send_strategy: SendStrategy,+ /// Command that clears the agent's context, for `clear_context_on_advance`.+ /// `None` where no such command is known β the phase advance then just sends+ /// normally. Tracked in issue #46.+ pub clear_context_command: Option<&'static str>,++ // ββ dialogs ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+ /// Interactive prompts this agent shows that agtx answers on the user's+ /// behalf. Missing one is silent and total: the task's prompt is delivered+ /// but never read, because the agent never reaches its composer.+ pub dialogs: &'static [AgentDialog],+}++/// Every agent agtx ships with.+///+/// Ordered by preference β [`crate::agent::known_agents`] and the agent pickers+/// present them in this order.+pub const AGENT_SPECS: &[AgentSpec] = &[+ AgentSpec {+ name: "claude",+ binary: "claude",+ description: "Anthropic's Claude Code CLI",+ co_author: "Claude <[email protected]>",+ env: &[],+ base_args: &["--dangerously-skip-permissions"],+ prompt_form: PromptForm::Argv,+ // Verified against claude 2.1.241: `claude [prompt]` starts an+ // interactive session with the prompt submitted, and a leading+ // `/agtx:plan β¦` still expands as a slash command.+ launch_prompt_verified: true,+ resume: ResumeArgs::Append(&["--continue"]),+ headless_args: &["--print"],+ skill_dir: Some((".claude/commands", "agtx")),+ skill_layout: SkillLayout::CommandFile,+ skill_scan_dir: Some(".claude/commands"),+ command_syntax: CommandSyntax::Colon,+ mcp_config: Some(McpConfigKind::ClaudeJson),+ process_names: &["claude"],+ active_indicators: &["Claude Code"],+ exit_command: Some("/exit"),+ label_fg: (227, 148, 62), // orange+ label_bg: None,+ send_strategy: SendStrategy::Generic,+ clear_context_command: Some("/clear"),+ dialogs: &[+ // Workspace trust, shown before the bypass warning in any directory+ // Claude has not seen. Recorded per directory as+ // `projects."<dir>".hasTrustDialogAccepted` in ~/.claude.json, and+ // every task gets a new worktree β so this fires on the first launch+ // of nearly every Claude task, not just in containers.+ AgentDialog {+ patterns: &["Yes, I trust this folder"],+ require_all: false,+ answer: &["1", "Enter"],+ scope: DialogScope::Launch,+ },+ // `--dangerously-skip-permissions` acceptance. Not covered by+ // hasTrustDialogAccepted, so copying ~/.claude.json (as the swebench+ // harness does) does not suppress it.+ AgentDialog {+ // Alternatives: the wording has varied across Claude versions.+ patterns: &["Yes, I accept", "I accept the risk"],+ require_all: false,+ answer: &["2", "Enter"],+ scope: DialogScope::Launch,+ },+ ],+ },+ AgentSpec {+ name: "codex",+ binary: "codex",+ description: "OpenAI's Codex CLI",+ co_author: "Codex <[email protected]>",+ env: &[],+ base_args: &["--sandbox", "workspace-write"],+ prompt_form: PromptForm::Argv,+ // Verified against codex-cli 0.144.5: `codex --sandbox workspace-write+ // '$agtx-plan <id>\n\n<task>'` starts interactively with the prompt+ // submitted, and the `$skill` mention resolves and runs.+ launch_prompt_verified: true,+ // `codex resume` is its own subcommand and rejects the launch flags.+ resume: ResumeArgs::Replace(&["resume", "--last"]),+ headless_args: &["exec", "--sandbox", "workspace-write"],+ skill_dir: Some((".codex/skills", "")),+ skill_layout: SkillLayout::SkillDir,+ skill_scan_dir: Some(".codex/skills"),+ command_syntax: CommandSyntax::Dollar,+ mcp_config: Some(McpConfigKind::CodexToml),+ process_names: &["codex"],+ active_indicators: &["OpenAI Codex"],+ exit_command: None,+ label_fg: (255, 255, 255), // white on black+ label_bg: Some((20, 20, 20)),+ send_strategy: SendStrategy::Combined,+ clear_context_command: None,+ dialogs: &[+ // Directory trust, per directory, so it fires on the first launch of+ // every codex task. Worded differently from both Claude's ("Yes, I+ // trust this folder") and Gemini's ("files in this folder"), so+ // neither of their patterns catches it. Verified against+ // codex-cli 0.144.5.+ AgentDialog {+ patterns: &["Do you trust the contents of this directory?"],+ require_all: false,+ answer: &["1", "Enter"],+ scope: DialogScope::Launch,+ },+ // Update prompt, shown whenever a newer codex is published. "Skip"+ // rather than "Update now": agtx must never upgrade a user's agent+ // binary behind their back, but leaving the pane blocked is worse.+ AgentDialog {+ patterns: &["Update now (runs"],+ require_all: false,+ answer: &["2", "Enter"],+ scope: DialogScope::Launch,+ },+ // MCP tool approval, shown mid-session the first time the agent calls+ // an agtx tool β not at launch, so it is matched only against a pane+ // known to be running codex.+ AgentDialog {+ // A conjunction: none of these three is distinctive alone.+ patterns: &["Allow the", "MCP server to run tool", "Always allow"],+ require_all: true,+ answer: &["3", "Enter"],+ scope: DialogScope::Session,+ },+ ],+ },+ AgentSpec {+ name: "copilot",+ binary: "copilot",+ description: "GitHub Copilot CLI",+ co_author: "GitHub Copilot <[email protected]>",+ env: &[],+ base_args: &["--allow-all-tools"],+ // `-i` keeps the session interactive; `-p` is print mode and exits on+ // completion, which killed every copilot task until it was fixed.+ prompt_form: PromptForm::Flag("-i"),+ launch_prompt_verified: false,+ resume: ResumeArgs::Append(&["--continue"]),+ headless_args: &["-p"],+ skill_dir: Some((".github/agents", "agtx")),+ skill_layout: SkillLayout::CommandFile,+ skill_scan_dir: Some(".github/agents"),+ // Copilot has no interactive slash-command invocation, so skills reach+ // it as a file-path reference in the prompt instead. Its skills are+ // still discovered and listed by the `/` picker.+ command_syntax: CommandSyntax::None,+ // Copilot is not wired to the MCP server.+ mcp_config: None,+ process_names: &["copilot"],+ active_indicators: &[],+ exit_command: Some("/exit"),+ label_fg: (255, 255, 255), // default white+ label_bg: None,+ send_strategy: SendStrategy::Generic,+ clear_context_command: None,+ dialogs: &[],+ },+ AgentSpec {+ name: "gemini",+ binary: "gemini",+ description: "Google Gemini CLI",+ co_author: "Gemini <[email protected]>",+ env: &[("GEMINI_TRUST_WORKSPACE", "true")],+ base_args: &["--approval-mode", "yolo"],+ prompt_form: PromptForm::Flag("-i"),+ launch_prompt_verified: false,+ resume: ResumeArgs::Append(&["--resume"]),+ headless_args: &["-p"],+ skill_dir: Some((".gemini/commands", "agtx")),+ skill_layout: SkillLayout::GeminiToml,+ skill_scan_dir: Some(".gemini/commands"),+ command_syntax: CommandSyntax::Colon,+ mcp_config: Some(McpConfigKind::GeminiJson),+ process_names: &["gemini"],+ active_indicators: &["Type your message"],+ exit_command: Some("/quit"),+ label_fg: (234, 130, 180), // pink+ label_bg: None,+ send_strategy: SendStrategy::Combined,+ clear_context_command: None,+ dialogs: &[+ // Answering this restarts the process.+ AgentDialog {+ patterns: &["Do you trust the files in this folder?"],+ require_all: false,+ answer: &["1", "Enter"],+ scope: DialogScope::Launch,+ },+ ],+ },+ AgentSpec {+ name: "opencode",+ binary: "opencode",+ description: "AI-powered coding assistant",+ co_author: "OpenCode <[email protected]>",+ env: &[],+ base_args: &[],+ prompt_form: PromptForm::Flag("-p"),+ launch_prompt_verified: false,+ resume: ResumeArgs::Append(&["--continue"]),+ headless_args: &[],+ skill_dir: Some((".opencode/command", "")),+ skill_layout: SkillLayout::OpenCodeFlat,+ // Deliberately not `.opencode/command`: agtx deploys into the worktree+ // tree, but OpenCode's own project commands live under `.config/`.+ skill_scan_dir: Some(".config/opencode/command"),+ command_syntax: CommandSyntax::Hyphen,+ mcp_config: Some(McpConfigKind::OpenCode),+ process_names: &["opencode"],+ active_indicators: &["Ask anything"],+ exit_command: Some("/exit"),+ label_fg: (255, 255, 255), // white on grey+ label_bg: Some((80, 80, 80)),+ send_strategy: SendStrategy::OpenCodePicker,+ clear_context_command: None,+ dialogs: &[],+ },+ AgentSpec {+ name: "cursor",+ binary: "agent",+ description: "Cursor Agent CLI",+ co_author: "Cursor Agent <[email protected]>",+ env: &[],+ base_args: &["--yolo"],+ prompt_form: PromptForm::Argv,+ launch_prompt_verified: false,+ resume: ResumeArgs::Append(&["--continue"]),+ headless_args: &["--print", "--yolo"],+ skill_dir: Some((".cursor/skills", "")),+ skill_layout: SkillLayout::SkillDir,+ skill_scan_dir: Some(".cursor/skills"),+ command_syntax: CommandSyntax::Hyphen,+ mcp_config: Some(McpConfigKind::CursorJson),+ process_names: &["agent"],+ active_indicators: &["Cursor Agent"],+ exit_command: None,+ label_fg: (255, 255, 255), // default white+ label_bg: None,+ send_strategy: SendStrategy::Combined,+ clear_context_command: None,+ dialogs: &[+ // Workspace trust, per directory, so it fires on the first launch of+ // every cursor task. Its question line is *identical* to codex's+ // ("Do you trust the contents of this directory?"), which is why it+ // is matched on the heading instead β and why per-agent scoping is+ // what makes declaring it safe.+ //+ // Answered with the access key the dialog itself advertises ("or+ // press the key shown") rather than an Enter on the highlighted row:+ // explicit, and it survives an option being added above it. Verified+ // against cursor-agent 2026.08.11 β "a" trusts the workspace without+ // restarting the process, and a paste lands immediately after.+ AgentDialog {+ patterns: &["Workspace Trust Required"],+ require_all: false,+ answer: &["a"],+ scope: DialogScope::Launch,+ },+ ],+ },+ AgentSpec {+ name: "grok",+ binary: "grok",+ description: "xAI's Grok Build CLI",+ co_author: "Grok <[email protected]>",+ env: &[],+ // `--trust` also ungates the repo-local `.grok/config.toml` MCP server+ // and suppresses the directory-trust dialog.+ base_args: &["--yolo", "--trust"],+ prompt_form: PromptForm::Argv,+ // Verified against Grok 4.6: `grok --yolo --trust '/agtx-plan <id>\n\n<task>'`+ // delivered the prompt at launch, the skill ran, and `--trust` meant no+ // dialog appeared at all.+ launch_prompt_verified: true,+ resume: ResumeArgs::Append(&["--continue"]),+ headless_args: &["-p"],+ skill_dir: Some((".grok/skills", "")),+ skill_layout: SkillLayout::SkillDir,+ skill_scan_dir: Some(".grok/skills"),+ command_syntax: CommandSyntax::Hyphen,+ mcp_config: Some(McpConfigKind::GrokTomlMerge),+ process_names: &["grok"],+ active_indicators: &["Grok Build", "Shift+Tab:mode"],+ exit_command: Some("/quit"),+ label_fg: (20, 20, 20), // black on white+ label_bg: Some((255, 255, 255)),+ send_strategy: SendStrategy::Generic,+ clear_context_command: None,+ dialogs: &[],+ },+ AgentSpec {+ name: "antigravity",+ binary: "agy",+ description: "Google's Antigravity CLI",+ co_author: "Antigravity <[email protected]>",+ env: &[],+ // Two orthogonal controls: the flag governs shell/MCP/URL approvals,+ // `--mode` governs the file-edit diff review. Both are needed to run+ // unattended.+ base_args: &["--dangerously-skip-permissions", "--mode", "accept-edits"],+ prompt_form: PromptForm::Flag("-i"),+ // Deliberately still false, for a narrower reason than before. `agy β¦ -i+ // '<prompt>'` *does* deliver β the skill ran and wrote its file β and the+ // trust dialog that used to strand the session afterwards is now answered+ // (see `dialogs` below). What is unverified is the *ordering*: on a first+ // launch the dialog is up before the composer exists, and whether an+ // argv-delivered prompt survives being handed to a menu has not been+ // checked against the real binary. The mid-session lane works, so this+ // stays off until someone measures it β flipping it wrong swallows the+ // task silently.+ launch_prompt_verified: false,+ resume: ResumeArgs::Append(&["--continue"]),+ headless_args: &["-p"],+ // Antigravity reads workspace skills from the vendor-neutral `.agents/`+ // tree, not from an agent-specific dotdir.+ skill_dir: Some((".agents/skills", "")),+ skill_layout: SkillLayout::SkillDir,+ skill_scan_dir: Some(".agents/skills"),+ command_syntax: CommandSyntax::Hyphen,+ mcp_config: Some(McpConfigKind::AntigravityJsonMerge),+ process_names: &["agy"],+ // Shown only once the session is interactive: the trust dialog's own+ // footer reads "β/β Navigate Β· enter Confirm" instead, so this cannot+ // fire while the pane is still blocked. Without it antigravity had no+ // readiness signal at all β `pane_current_command` reports `bash` for its+ // npm wrapper, and the content-stabilisation fallback needs three pane+ // changes where its splash produces two.+ active_indicators: &["? for shortcuts"],+ exit_command: Some("/exit"),+ label_fg: (120, 190, 255), // light blue+ label_bg: None,+ send_strategy: SendStrategy::Combined,+ clear_context_command: None,+ dialogs: &[+ // Project trust, shown on the first launch in any directory β which+ // is every task, because every task gets a new worktree. It was+ // deliberately left unanswered while dialogs were matched flat, when+ // answering it meant Claude's identical "Yes, I trust this folder"+ // pattern firing in any pane. Per-agent scoping removed that risk,+ // and leaving it stood the session up blocked: the paste went into a+ // menu that ignores text and agtx's follow-up Enter confirmed the+ // dialog, so every antigravity task reached its composer empty.+ //+ // Answered with a bare Enter: this menu is arrow-navigated with+ // "Yes, I trust this folder" preselected, so a digit would be typed+ // into the composer the Enter then opens. Verified against+ // antigravity 1.1.20 β the process does not restart, and a paste+ // lands immediately afterwards.+ AgentDialog {+ // Its own wording, not Claude's. Codex's differs by one word+ // ("directory"), which is why each is matched separately.+ patterns: &["Do you trust the contents of this project?"],+ require_all: false,+ answer: &["Enter"],+ scope: DialogScope::Launch,+ },+ ],+ },+ // TODO: investigate CLI usage before enabling+ // aider β "AI pair programming in your terminal", Aider <[email protected]>+ // cline β "AI coding assistant for VS Code", Cline <[email protected]>+];++/// Look up an agent's spec by name. `None` for agents agtx has not been taught,+/// which fall back to generic behaviour throughout.+pub fn spec(name: &str) -> Option<&'static AgentSpec> {+ AGENT_SPECS.iter().find(|s| s.name == name)+}++/// Build a shell command for `spec`: env prefix, binary, the given args, then+/// the prompt in the agent's own form.+///+/// The prompt is single-quoted with the POSIX `'"'"'` idiom because the result+/// is wrapped in `sh -c 'β¦'` by `create_window`; a bare quote would close that+/// outer quote and let the shell mangle the text.+/// Largest prompt agtx will hand to a process in argv.+///+/// `ARG_MAX` is ~1 MB on macOS and Linux and task descriptions are far below+/// that, but the limit should be explicit rather than incidental: past this the+/// caller falls back to the mid-session lane, which has no such ceiling. Counted+/// in bytes, not chars, because that is what `execve` counts.+pub const MAX_LAUNCH_PROMPT_BYTES: usize = 128 * 1024;++/// Strip characters that cannot survive the trip through argv intact.+///+/// The command string is handed to tmux, which runs it through a shell, so the+/// prompt is embedded in a single-quoted word. Single quotes are escaped by+/// [`compose_command`]; this handles the rest:+///+/// - **NUL** would truncate the argument at the C-string boundary, silently+/// discarding the rest of the task.+/// - **`\r`** renders as a carriage return, moving the agent's cursor to column+/// zero and corrupting the echoed prompt. It is almost always a paste artifact+/// from a CRLF source.+/// - **Other control characters** (ESC in particular) let pasted text move the+/// cursor or set colours in the agent's TUI.+///+/// `\n` and `\t` are kept: they are ordinary structure in a task description,+/// and inside a single-quoted argv word they are just bytes.+pub fn normalize_prompt(prompt: &str) -> String {+ prompt+ .chars()+ .filter(|c| *c == '\n' || *c == '\t' || !c.is_control())+ .collect()+}++/// Whether `text` can be delivered as a launch argument for this injection mode.+///+/// False sends the caller down the mid-session lane instead β either because the+/// agent's launch form is unverified, or because the text is too large for argv.+pub fn can_launch_with_prompt(injection: crate::agent::PromptInjection, text: &str) -> bool {+ !text.is_empty()+ && !matches!(injection, crate::agent::PromptInjection::Unknown)+ && text.len() <= MAX_LAUNCH_PROMPT_BYTES+}++pub fn compose_command(spec: &AgentSpec, args: &[&str], prompt: Option<&str>) -> String {+ let mut out = String::new();+ for (key, value) in spec.env {+ out.push_str(key);+ out.push('=');+ out.push_str(value);+ out.push(' ');+ }+ out.push_str(spec.binary);+ for arg in args {+ out.push(' ');+ out.push_str(arg);+ }+ if let Some(prompt) = prompt.filter(|p| !p.is_empty()) {+ if let PromptForm::Flag(flag) = spec.prompt_form {+ out.push(' ');+ out.push_str(flag);+ }+ // POSIX single-quote escaping: close, emit a literal quote, reopen. The+ // whole command is itself wrapped in `sh -c 'β¦'` by create_window, so a+ // bare quote here would end that outer word and let the shell interpret+ // the rest of the task as code.+ let prompt = normalize_prompt(prompt);+ out.push_str(&format!(" '{}'", prompt.replace('\'', "'\"'\"'")));+ }+ out+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn every_known_agent_has_exactly_one_spec() {+ let names: Vec<&str> = AGENT_SPECS.iter().map(|s| s.name).collect();+ let mut sorted = names.clone();+ sorted.sort_unstable();+ sorted.dedup();+ assert_eq!(sorted.len(), names.len(), "duplicate agent name in table");++ let known: Vec<String> = crate::agent::known_agents()+ .into_iter()+ .map(|a| a.name)+ .collect();+ assert_eq!(+ known, names,+ "known_agents() must be derived from the table"+ );+ }++ #[test]+ fn spec_lookup_is_exhaustive_and_exclusive() {+ for entry in AGENT_SPECS {+ assert_eq!(spec(entry.name).map(|s| s.name), Some(entry.name));+ }+ assert!(spec("mistral").is_none());+ assert!(spec("").is_none());+ }++ #[test]+ fn skill_dirs_stay_inside_the_worktree() {+ for entry in AGENT_SPECS {+ for dir in entry+ .skill_dir+ .map(|(b, _)| b)+ .into_iter()+ .chain(entry.skill_scan_dir)+ {+ assert!(+ !dir.starts_with('/'),+ "{}: {dir} must be relative",+ entry.name+ );+ assert!(+ !dir.contains(".."),+ "{}: {dir} must stay in-worktree",+ entry.name+ );+ }+ }+ }++ #[test]+ fn a_verified_launch_prompt_is_never_a_print_flag() {+ // `-p` is print mode for every agent that has it: it answers once and+ // exits, killing the task window. Marking such an agent verified is the+ // bug this guard exists for.+ for entry in AGENT_SPECS.iter().filter(|s| s.launch_prompt_verified) {+ assert_ne!(+ entry.prompt_form,+ PromptForm::Flag("-p"),+ "{} cannot deliver its prompt at launch through print mode",+ entry.name+ );+ }+ }+}diff --git a/src/config/mod.rs b/src/config/mod.rsindex d2f55d2..5d954d3 100644--- a/src/config/mod.rs+++ b/src/config/mod.rs@@ -24,6 +24,16 @@ pub struct GlobalConfig {/// Whether to automatically fullscreen-attach to the tmux session when opening a task popup#[serde(default)]pub fullscreen_on_enter: bool,++ /// Write agent lifecycle-hook configs into worktrees so agents report their+ /// own phase status. When false, agtx falls back to inferring liveness from+ /// tmux pane output.+ #[serde(default = "default_agent_hooks")]+ pub agent_hooks: bool,+}++fn default_agent_hooks() -> bool {+ true}impl Default for GlobalConfig {@@ -34,6 +44,7 @@ impl Default for GlobalConfig {worktree: WorktreeConfig::default(),theme: ThemeConfig::default(),fullscreen_on_enter: false,+ agent_hooks: default_agent_hooks(),}}}@@ -368,6 +379,7 @@ pub struct MergedConfig {pub workflow_plugin: Option<String>,pub fullscreen_on_enter: bool,pub branch_prefix: String,+ pub agent_hooks: bool,}impl MergedConfig {@@ -403,6 +415,7 @@ impl MergedConfig {cleanup_script: project.cleanup_script.clone(),workflow_plugin: project.workflow_plugin.clone(),fullscreen_on_enter: global.fullscreen_on_enter,+ agent_hooks: global.agent_hooks,branch_prefix: project.branch_prefix.clone()@@ -578,7 +591,10 @@ impl WorkflowPlugin {name);}- if !name.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') {+ if !name+ .chars()+ .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')+ {anyhow::bail!("Plugin name '{}' contains invalid characters (only a-z, A-Z, 0-9, -, _ allowed)",name@@ -689,14 +705,15 @@ impl TrustStore {pub fn hash_config(project_path: &Path) -> Option<String> {let config_path = project_path.join(".agtx").join("config.toml");let content = std::fs::read(&config_path).ok()?;- use sha2::{Sha256, Digest};+ use sha2::{Digest, Sha256};let hash = Sha256::digest(&content);Some(format!("{:x}", hash))}/// Check if a project's config is trusted (hash matches stored value).pub fn is_trusted(&self, project_path: &Path) -> bool {- let canonical = project_path.canonicalize()+ let canonical = project_path+ .canonicalize().unwrap_or_else(|_| project_path.to_path_buf());let key = canonical.to_string_lossy().to_string();match (self.projects.get(&key), Self::hash_config(project_path)) {@@ -708,7 +725,8 @@ impl TrustStore {/// Mark a project's current config as trusted.pub fn trust_project(&mut self, project_path: &Path) -> Result<()> {- let canonical = project_path.canonicalize()+ let canonical = project_path+ .canonicalize().unwrap_or_else(|_| project_path.to_path_buf());let key = canonical.to_string_lossy().to_string();if let Some(hash) = Self::hash_config(project_path) {diff --git a/src/db/models.rs b/src/db/models.rsindex 5614cf3..f8a4484 100644--- a/src/db/models.rs+++ b/src/db/models.rs@@ -235,6 +235,9 @@ impl Notification {pub enum PhaseStatus {/// Agent is still working, no artifact yetWorking,+ /// Agent is stopped waiting on a permission prompt or a question.+ /// Only ever set from an agent-reported hook event β never inferred.+ Blocked,/// Agent output hasn't changed for 15s β may need user inputIdle,/// Phase artifact detected, ready to advancediff --git a/src/main.rs b/src/main.rsindex 5bf092f..0b830dd 100644--- a/src/main.rs+++ b/src/main.rs@@ -15,6 +15,17 @@ use std::path::PathBuf;#[tokio::main]async fn main() -> Result<()> {+ // Fast path: `agtx hook <task-id> <worktree> [agent]` is invoked by agent+ // lifecycle hooks, potentially on every tool call. Handle it before the+ // logging and config setup below β building a daily rolling file appender+ // per invocation is pure waste, and the agent consumes this process's stdout.+ {+ let raw: Vec<String> = std::env::args().collect();+ if raw.get(1).map(String::as_str) == Some("hook") {+ return agtx::agent::hook_status::run_hook_cli(&raw[2..]);+ }+ }+// Initialize audit logging to ~/.config/agtx/logs/let log_dir = GlobalConfig::config_path()?.parent()@@ -48,9 +59,7 @@ async fn main() -> Result<()> {let mode = match positional_args.first().copied() {Some("mcp-serve") => {- let project_path = positional_args- .get(1)- .map(PathBuf::from);+ let project_path = positional_args.get(1).map(PathBuf::from);let project_path = match project_path {Some(p) => {let p = p.canonicalize()?;@@ -84,7 +93,10 @@ async fn main() -> Result<()> {}};- let flags = FeatureFlags { experimental, no_init_scripts };+ let flags = FeatureFlags {+ experimental,+ no_init_scripts,+ };// First-run: determine action based on config/data statelet config_path = GlobalConfig::config_path()?;diff --git a/src/mcp/server.rs b/src/mcp/server.rsindex fbf47a7..3d78d89 100644--- a/src/mcp/server.rs+++ b/src/mcp/server.rs@@ -4,8 +4,7 @@ use std::process::Command;use rmcp::{handler::server::{router::tool::ToolRouter, wrapper::Parameters},model::{ServerCapabilities, ServerInfo},- schemars, tool, tool_handler, tool_router,- ServerHandler, ServiceExt,+ schemars, tool, tool_handler, tool_router, ServerHandler, ServiceExt,};use serde::{Deserialize, Serialize};@@ -125,7 +124,9 @@ pub struct SendToTaskParams {#[schemars(description = "The task ID (UUID)")]pub task_id: String,/// Message to send to the task's agent pane (followed by Enter). Max 4096 bytes, no null bytes.- #[schemars(description = "Message to send to the task's agent pane (followed by Enter). Max 4096 bytes.")]+ #[schemars(+ description = "Message to send to the task's agent pane (followed by Enter). Max 4096 bytes."+ )]pub message: String,/// Project ID (required in global mode β call list_projects first to get IDs).#[schemars(@@ -188,7 +189,9 @@ pub struct BatchTask {#[derive(Debug, Deserialize, schemars::JsonSchema)]pub struct CreateTasksBatchParams {/// Array of tasks to create, with index-based dependency wiring- #[schemars(description = "Array of tasks to create. Use depends_on with 0-based indices to wire dependencies between them.")]+ #[schemars(+ description = "Array of tasks to create. Use depends_on with 0-based indices to wire dependencies between them."+ )]pub tasks: Vec<BatchTask>,/// Project ID (required in global mode β call list_projects first to get IDs).#[schemars(@@ -290,6 +293,15 @@ struct TaskDetail {blocking_tasks: Vec<BlockingTask>,/// Actions the orchestrator can take on this task given its current status and plugin rules.allowed_actions: Vec<String>,+ /// The agent's own report of what it is doing: "working", "blocked",+ /// "waiting" or "ended". Absent when the agent reports nothing (hooks+ /// disabled, or an agent that does not support them).+ #[serde(skip_serializing_if = "Option::is_none")]+ agent_state: Option<String>,+ /// What the agent is waiting for, when `agent_state` is "blocked". This is+ /// the permission prompt or question text the agent itself reported.+ #[serde(skip_serializing_if = "Option::is_none")]+ blocked_reason: Option<String>,}#[derive(Serialize)]@@ -430,8 +442,7 @@ impl AgtxMcpServer {/// Open a project DB, resolving the path via `resolve_project_path`.fn open_project_db_for(&self, project_id: Option<&str>) -> Result<Database, String> {let path = self.resolve_project_path(project_id)?;- Database::open_project(&path)- .map_err(|e| format!("Failed to open project database: {}", e))+ Database::open_project(&path).map_err(|e| format!("Failed to open project database: {}", e))}fn open_project_db(&self) -> Result<Database, String> {@@ -475,12 +486,9 @@ impl AgtxMcpServer {let mut actions = Vec::new();let _plugin = match &task.plugin {- Some(name) => crate::config::WorkflowPlugin::load(- name,- project_path.as_deref(),- )- .ok()- .or_else(|| crate::skills::load_bundled_plugin(name)),+ Some(name) => crate::config::WorkflowPlugin::load(name, project_path.as_deref())+ .ok()+ .or_else(|| crate::skills::load_bundled_plugin(name)),None => crate::skills::load_bundled_plugin("agtx"),};@@ -589,7 +597,7 @@ impl AgtxMcpServer {}#[tool(- description = "Get full details of a specific task by its ID. Includes allowed_actions based on the task's current status and plugin rules. In global mode, project_id is required β call list_projects first."+ description = "Get full details of a specific task by its ID. Includes allowed_actions based on the task's current status and plugin rules, and agent_state (working/blocked/waiting/ended) as reported by the agent itself β when it is \"blocked\", blocked_reason names what the agent is waiting for. In global mode, project_id is required β call list_projects first.")]fn get_task(&self, Parameters(params): Parameters<GetTaskParams>) -> String {tracing::info!(tool = "get_task", task_id = %params.task_id, "MCP tool called");@@ -607,10 +615,7 @@ impl AgtxMcpServer {.ok().flatten().filter(|dep| {- !matches!(- dep.status,- TaskStatus::Review | TaskStatus::Done- )+ !matches!(dep.status, TaskStatus::Review | TaskStatus::Done)}).map(|dep| BlockingTask {id: dep.id,@@ -621,6 +626,27 @@ impl AgtxMcpServer {.collect(),_ => Vec::new(),};+ // Read the agent's own status file, written by its hooks.+ // Works cross-process precisely because it is a file rather+ // than TUI state.+ let hook = t.worktree_path.as_ref().and_then(|wt| {+ crate::agent::hook_status::read_status(+ std::path::Path::new(wt),+ &t.id,+ chrono::Utc::now().timestamp(),+ )+ });+ let agent_state = hook.as_ref().map(|h| {+ match h.state {+ crate::agent::hook_status::HookState::Working => "working",+ crate::agent::hook_status::HookState::Blocked => "blocked",+ crate::agent::hook_status::HookState::Waiting => "waiting",+ crate::agent::hook_status::HookState::Ended => "ended",+ }+ .to_string()+ });+ let blocked_reason = hook.as_ref().and_then(|h| h.message.clone());+let detail = TaskDetail {id: t.id,title: t.title,@@ -643,6 +669,8 @@ impl AgtxMcpServer {deps_satisfied: deps_ok,blocking_tasks: blocking,allowed_actions: allowed,+ agent_state,+ blocked_reason,};serde_json::to_string_pretty(&detail).unwrap_or_else(|e| format!("Error serializing: {}", e))@@ -1043,11 +1071,12 @@ impl AgtxMcpServer {#[tool(description = "Create multiple tasks at once with index-based dependency wiring. Each task's depends_on field uses 0-based indices into the tasks array (no forward references). Returns all created task IDs. In global mode, project_id is required β call list_projects first.")]- fn create_tasks_batch(- &self,- Parameters(params): Parameters<CreateTasksBatchParams>,- ) -> String {- tracing::info!(tool = "create_tasks_batch", count = params.tasks.len(), "MCP tool called");+ fn create_tasks_batch(&self, Parameters(params): Parameters<CreateTasksBatchParams>) -> String {+ tracing::info!(+ tool = "create_tasks_batch",+ count = params.tasks.len(),+ "MCP tool called"+ );if params.tasks.is_empty() {return "Error: tasks array is empty".to_string();}diff --git a/src/skills.rs b/src/skills.rsindex 3153da0..ae698db 100644--- a/src/skills.rs+++ b/src/skills.rs@@ -1,6 +1,12 @@-/// Default skill content for agtx phases.-/// Skills follow the Agent Skills spec (SKILL.md with YAML frontmatter + markdown).-/// Content is loaded from .md files at compile time via include_str!().+//! Default skill content for agtx phases, and the per-agent skill/command+//! plumbing that deploys and discovers it.+//!+//! Skills follow the Agent Skills spec (SKILL.md with YAML frontmatter ++//! markdown). Content is loaded from .md files at compile time via+//! `include_str!()`. Agent-specific paths and syntax are read from the agent's+//! [`AgentSpec`](crate::agent::AgentSpec) rather than matched on its name.++use crate::agent::{CommandSyntax, SkillLayout};pub const RESEARCH_SKILL: &str = include_str!("../plugins/agtx/skills/research.md");pub const PLAN_SKILL: &str = include_str!("../plugins/agtx/skills/plan.md");@@ -101,23 +107,12 @@ fn discover_custom_plugins_in(dirs: &[std::path::PathBuf]) -> Vec<CustomPlugin>}/// Agent-native command/skill directory paths.-/// Returns (base_dir_relative_to_worktree, namespace_subdir) or None if agent has no native discovery.-/// Returns (base_dir_relative_to_worktree, namespace_subdir) or None if agent has no native discovery.-/// For Codex, namespace is empty because skills go directly under `.codex/skills/{skill-name}/SKILL.md`.+/// Returns (base_dir_relative_to_worktree, namespace_subdir), or None for an+/// agent with no native discovery. The namespace is empty for layouts that carry+/// the `agtx-` prefix in the file or directory name instead (Codex, Cursor,+/// Grok, Antigravity, OpenCode).pub fn agent_native_skill_dir(agent_name: &str) -> Option<(&'static str, &'static str)> {- match agent_name {- "claude" => Some((".claude/commands", "agtx")),- "gemini" => Some((".gemini/commands", "agtx")),- "opencode" => Some((".opencode/command", "")),- "codex" => Some((".codex/skills", "")),- "cursor" => Some((".cursor/skills", "")),- "grok" => Some((".grok/skills", "")),- // Antigravity reads workspace skills from the vendor-neutral `.agents/` tree,- // not from an agent-specific dotdir.- "antigravity" => Some((".agents/skills", "")),- "copilot" => Some((".github/agents", "agtx")),- _ => None,- }+ crate::agent::spec(agent_name).and_then(|s| s.skill_dir)}/// Transform SKILL.md frontmatter `name: agtx-plan` to command name `agtx:plan`.@@ -130,64 +125,47 @@ pub fn skill_name_to_command(skill_name: &str) -> String {}}-/// Map internal skill directory name to agent-native command file name.-/// Format depends on the agent:-/// - Claude/Gemini: "agtx-plan" β "plan.md" / "plan.toml" (namespace subdir handles prefix)-/// - OpenCode: "agtx-plan" β "agtx-plan.md" (flat directory, full name)-/// - Codex: uses SKILL.md in skill directories (handled separately)+/// Map internal skill directory name to agent-native command file name,+/// according to the agent's [`SkillLayout`](crate::agent::SkillLayout):+/// - `CommandFile` / `SkillDir`: "agtx-plan" β "plan.md" (the namespace subdir+/// or the skill directory itself carries the prefix)+/// - `GeminiToml`: "agtx-plan" β "plan.toml"+/// - `OpenCodeFlat`: "agtx-plan" β "agtx-plan.md" (flat directory, full name)pub fn skill_dir_to_filename(skill_dir_name: &str, agent_name: &str) -> String {- match agent_name {- "gemini" => {- let short = skill_dir_name- .strip_prefix("agtx-")- .unwrap_or(skill_dir_name);- format!("{}.toml", short)- }- "opencode" => {- // Flat structure: command/agtx-plan.md (invoked as /agtx-plan)- format!("{}.md", skill_dir_name)- }- _ => {- let short = skill_dir_name- .strip_prefix("agtx-")- .unwrap_or(skill_dir_name);- format!("{}.md", short)- }+ let short = || {+ skill_dir_name+ .strip_prefix("agtx-")+ .unwrap_or(skill_dir_name)+ };+ match crate::agent::spec(agent_name).map(|s| s.skill_layout) {+ Some(SkillLayout::GeminiToml) => format!("{}.toml", short()),+ Some(SkillLayout::OpenCodeFlat) => format!("{}.md", skill_dir_name),+ _ => format!("{}.md", short()),}}-/// Generate the send_keys command to invoke a skill interactively.-/// Returns None for agents without interactive skill invocation./// Transform a canonical plugin command (Claude/Gemini format) for a specific agent.////// Plugin commands in plugin.toml are stored in canonical form: `/namespace:command args`-/// This transforms them for each agent's expected syntax:-/// - Claude/Gemini: unchanged (`/gsd:plan-phase 1`)-/// - OpenCode: colon β hyphen (`/gsd-plan-phase 1`)-/// - Codex: slash β dollar + colon β hyphen (`$gsd-plan-phase 1`)-/// - Cursor/Grok/Antigravity: colon β hyphen, slash kept (`/gsd-plan-phase 1`)-/// - Unsupported agents: None (will fall back to file-path reference)+/// This transforms them for each agent's [`CommandSyntax`](crate::agent::CommandSyntax):+/// - `Colon` (Claude, Gemini): unchanged (`/gsd:plan-phase 1`)+/// - `Hyphen` (OpenCode, Cursor, Grok, Antigravity): colon β hyphen (`/gsd-plan-phase 1`)+/// - `Dollar` (Codex): slash β dollar, colon β hyphen (`$gsd-plan-phase 1`)+/// - `None` (Copilot, unknown agents): None β callers fall back to a file-path reference+///+/// Only the first colon is rewritten; arguments may legitimately contain more.pub fn transform_plugin_command(canonical_cmd: &str, agent_name: &str) -> Option<String> {- match agent_name {- "claude" | "gemini" => Some(canonical_cmd.to_string()),- "opencode" => {- // /gsd:plan-phase 1 β /gsd-plan-phase 1- Some(canonical_cmd.replacen(':', "-", 1))- }- "codex" => {- // /gsd:plan-phase 1 β $gsd-plan-phase 1+ match crate::agent::spec(agent_name).map(|s| s.command_syntax) {+ Some(CommandSyntax::Colon) => Some(canonical_cmd.to_string()),+ Some(CommandSyntax::Hyphen) => Some(canonical_cmd.replacen(':', "-", 1)),+ Some(CommandSyntax::Dollar) => {let transformed = canonical_cmd.replacen(':', "-", 1);- if let Some(rest) = transformed.strip_prefix('/') {- Some(format!("${}", rest))- } else {- Some(transformed)- }+ Some(match transformed.strip_prefix('/') {+ Some(rest) => format!("${}", rest),+ None => transformed,+ })}- "cursor" | "grok" | "antigravity" => {- // /agtx:plan β /agtx-plan (slash kept, colon β hyphen)- Some(canonical_cmd.replacen(':', "-", 1))- }- _ => None,+ Some(CommandSyntax::None) | None => None,}}@@ -335,156 +313,124 @@ fn extract_description_from_toml(path: &std::path::Path) -> Option<String> {/// Scan the active agent's native command directory for available skills./// Returns `(command, description)` tuples in agent-native invocation format.+///+/// Driven by the agent's [`SkillLayout`](crate::agent::SkillLayout), so an agent+/// reusing an existing layout needs nothing here.pub fn scan_agent_skills(agent_name: &str,project_path: &std::path::Path,) -> Vec<(String, String)> {- let mut results = Vec::new();-- match agent_name {- "claude" | "copilot" => {- // Namespaced subdirectories with .md files- let (base_dir, _) = match agent_native_skill_dir(agent_name) {- Some(v) => v,- None => return results,- };- let base = project_path.join(base_dir);- let entries = match std::fs::read_dir(&base) {- Ok(e) => e,- Err(_) => return results,- };- for ns_entry in entries.flatten() {- if !ns_entry.path().is_dir() {- continue;- }- let namespace = ns_entry.file_name().to_string_lossy().to_string();- let files = match std::fs::read_dir(ns_entry.path()) {- Ok(e) => e,- Err(_) => continue,- };- for file_entry in files.flatten() {- let path = file_entry.path();- if path.extension().and_then(|e| e.to_str()) != Some("md") {- continue;- }- let stem = match path.file_stem().and_then(|s| s.to_str()) {- Some(s) => s.to_string(),- None => continue,- };- let command = format!("/{}:{}", namespace, stem);- let description = extract_description_from_file(&path)- .unwrap_or_else(|| stem.replace('-', " "));- results.push((command, description));- }- }+ let Some(spec) = crate::agent::spec(agent_name) else {+ return Vec::new();+ };+ let Some(scan_dir) = spec.skill_scan_dir else {+ return Vec::new();+ };+ let base = project_path.join(scan_dir);++ let mut results = match spec.skill_layout {+ // Namespaced subdirectories of command files, invoked as `/namespace:name`.+ // Gemini's are TOML with a `description` key; the rest are markdown with+ // YAML frontmatter.+ SkillLayout::CommandFile | SkillLayout::GeminiToml => {+ let toml = spec.skill_layout == SkillLayout::GeminiToml;+ let ext = if toml { "toml" } else { "md" };+ scan_namespaced_commands(&base, ext, toml)}- "gemini" => {- // Namespaced subdirectories with .toml files- let (base_dir, _) = match agent_native_skill_dir(agent_name) {- Some(v) => v,- None => return results,- };- let base = project_path.join(base_dir);- let entries = match std::fs::read_dir(&base) {- Ok(e) => e,- Err(_) => return results,+ // Skill subdirectories each holding a SKILL.md, invoked by directory name.+ SkillLayout::SkillDir => {+ let prefix = if spec.command_syntax == CommandSyntax::Dollar {+ "$"+ } else {+ "/"};- for ns_entry in entries.flatten() {- if !ns_entry.path().is_dir() {- continue;- }- let namespace = ns_entry.file_name().to_string_lossy().to_string();- let files = match std::fs::read_dir(ns_entry.path()) {- Ok(e) => e,- Err(_) => continue,- };- for file_entry in files.flatten() {- let path = file_entry.path();- if path.extension().and_then(|e| e.to_str()) != Some("toml") {- continue;- }- let stem = match path.file_stem().and_then(|s| s.to_str()) {- Some(s) => s.to_string(),- None => continue,- };- let command = format!("/{}:{}", namespace, stem);- let description = extract_description_from_toml(&path)- .unwrap_or_else(|| stem.replace('-', " "));- results.push((command, description));- }- }+ scan_skill_dirs(&base, prefix)}- "codex" => {- // Skill subdirectories with SKILL.md- let base = project_path.join(".codex/skills");- let entries = match std::fs::read_dir(&base) {- Ok(e) => e,- Err(_) => return results,- };- for dir_entry in entries.flatten() {- if !dir_entry.path().is_dir() {- continue;- }- let dirname = dir_entry.file_name().to_string_lossy().to_string();- let skill_file = dir_entry.path().join("SKILL.md");- if skill_file.exists() {- let command = format!("${}", dirname);- let description = extract_description_from_file(&skill_file)- .unwrap_or_else(|| dirname.replace('-', " "));- results.push((command, description));- }- }+ // Flat directory of command files, invoked as `/name`.+ SkillLayout::OpenCodeFlat => scan_flat_commands(&base),+ };++ results.sort_by(|a, b| a.0.cmp(&b.0));+ results+}++/// `{base}/{namespace}/{name}.{ext}` β `/namespace:name`.+fn scan_namespaced_commands(+ base: &std::path::Path,+ ext: &str,+ description_from_toml: bool,+) -> Vec<(String, String)> {+ let mut results = Vec::new();+ let Ok(entries) = std::fs::read_dir(base) else {+ return results;+ };+ for ns_entry in entries.flatten() {+ if !ns_entry.path().is_dir() {+ continue;}- "cursor" | "grok" | "antigravity" => {- // Skill subdirectories with SKILL.md, invoked as /skill-name- let base_dir = match agent_native_skill_dir(agent_name) {- Some((dir, _)) => dir,- None => return results,- };- let base = project_path.join(base_dir);- let entries = match std::fs::read_dir(&base) {- Ok(e) => e,- Err(_) => return results,- };- for dir_entry in entries.flatten() {- if !dir_entry.path().is_dir() {- continue;- }- let dirname = dir_entry.file_name().to_string_lossy().to_string();- let skill_file = dir_entry.path().join("SKILL.md");- if skill_file.exists() {- let command = format!("/{}", dirname);- let description = extract_description_from_file(&skill_file)- .unwrap_or_else(|| dirname.replace('-', " "));- results.push((command, description));- }+ let namespace = ns_entry.file_name().to_string_lossy().to_string();+ let Ok(files) = std::fs::read_dir(ns_entry.path()) else {+ continue;+ };+ for file_entry in files.flatten() {+ let path = file_entry.path();+ if path.extension().and_then(|e| e.to_str()) != Some(ext) {+ continue;}- }- "opencode" => {- // Flat directory with .md files- let base = project_path.join(".config/opencode/command");- let entries = match std::fs::read_dir(&base) {- Ok(e) => e,- Err(_) => return results,+ let Some(stem) = path.file_stem().and_then(|s| s.to_str()) else {+ continue;};- for file_entry in entries.flatten() {- let path = file_entry.path();- if path.extension().and_then(|e| e.to_str()) != Some("md") {- continue;- }- let stem = match path.file_stem().and_then(|s| s.to_str()) {- Some(s) => s.to_string(),- None => continue,- };- let command = format!("/{}", stem);- let description = stem.replace('-', " ");- results.push((command, description));+ let description = if description_from_toml {+ extract_description_from_toml(&path)+ } else {+ extract_description_from_file(&path)}+ .unwrap_or_else(|| stem.replace('-', " "));+ results.push((format!("/{}:{}", namespace, stem), description));}- _ => {} // Copilot has no interactive invocation, unknown agents skipped}+ results+}- results.sort_by(|a, b| a.0.cmp(&b.0));+/// `{base}/{name}/SKILL.md` β `{prefix}{name}`.+fn scan_skill_dirs(base: &std::path::Path, prefix: &str) -> Vec<(String, String)> {+ let mut results = Vec::new();+ let Ok(entries) = std::fs::read_dir(base) else {+ return results;+ };+ for dir_entry in entries.flatten() {+ if !dir_entry.path().is_dir() {+ continue;+ }+ let dirname = dir_entry.file_name().to_string_lossy().to_string();+ let skill_file = dir_entry.path().join("SKILL.md");+ if !skill_file.exists() {+ continue;+ }+ let description =+ extract_description_from_file(&skill_file).unwrap_or_else(|| dirname.replace('-', " "));+ results.push((format!("{}{}", prefix, dirname), description));+ }+ results+}++/// `{base}/{name}.md` β `/name`. No frontmatter is read: OpenCode commands are+/// deployed with theirs stripped.+fn scan_flat_commands(base: &std::path::Path) -> Vec<(String, String)> {+ let mut results = Vec::new();+ let Ok(entries) = std::fs::read_dir(base) else {+ return results;+ };+ for file_entry in entries.flatten() {+ let path = file_entry.path();+ if path.extension().and_then(|e| e.to_str()) != Some("md") {+ continue;+ }+ let Some(stem) = path.file_stem().and_then(|s| s.to_str()) else {+ continue;+ };+ results.push((format!("/{}", stem), stem.replace('-', " ")));+ }results}diff --git a/src/tmux/operations.rs b/src/tmux/operations.rsindex cf4749d..2ddcc6b 100644--- a/src/tmux/operations.rs+++ b/src/tmux/operations.rs@@ -11,6 +11,9 @@ pub trait TmuxOperations: Send + Sync {/// Create a new tmux window. `keep_shell_on_exit=true` drops to a shell/// after `command` exits (task panes); `false` lets tmux close the window/// (orchestrator, where a leftover shell looks like a zombie).+ /// Create a window. `env` is set on the **window** (tmux `-e`), so anything+ /// started in it later β a resumed agent, a switched agent β inherits it,+ /// which a per-command `env VAR=x` prefix would not.fn create_window(&self,session: &str,@@ -18,6 +21,7 @@ pub trait TmuxOperations: Send + Sync {working_dir: &str,command: Option<String>,keep_shell_on_exit: bool,+ env: &[(String, String)],) -> Result<()>;/// Kill a tmux window@@ -26,11 +30,30 @@ pub trait TmuxOperations: Send + Sync {/// Check if a window existsfn window_exists(&self, target: &str) -> Result<bool>;- /// Send keys to a window (with Enter at the end)+ /// Send keys to a window (with Enter at the end).+ ///+ /// Like [`send_key`](Self::send_key), this goes through+ /// tmux's **key-name** lookup β see the note there.fn send_keys(&self, target: &str, keys: &str) -> Result<()>;- /// Send keys to a window without pressing Enter- fn send_keys_literal(&self, target: &str, keys: &str) -> Result<()>;+ /// Send a **key name** to a window, without a trailing Enter.+ ///+ /// This deliberately does *not* pass `-l`, so tmux resolves the argument as a+ /// key when it matches a key name: `"Enter"`, `"C-c"`, `"C-d"`, `"1"`.+ /// Callers answering a dialog or pressing a control key want exactly that.+ ///+ /// Never use it for text, because the same lookup applies: verified against+ /// tmux 3.5a, `"Space"` arrives as `0x20`, `"Escape"` as `ESC`, and `"Up"` as+ /// `\033[A`. Use [`send_text`](Self::send_text) β or, for a whole message,+ /// [`paste_text`](Self::paste_text) β instead.+ fn send_key(&self, target: &str, keys: &str) -> Result<()>;++ /// Send literal text to a window (`send-keys -l`), without a trailing Enter.+ ///+ /// Unlike [`send_key`](Self::send_key) the argument is never+ /// interpreted as a key name, so text that happens to spell one survives+ /// intact. Use this for anything user- or task-derived.+ fn send_text(&self, target: &str, text: &str) -> Result<()>;/// Paste a block of text into a pane using tmux load-buffer + paste-buffer./// This sends proper bracketed paste sequences to the target pane.@@ -58,6 +81,38 @@ pub trait TmuxOperations: Send + Sync {fn create_session(&self, session: &str, working_dir: &str) -> Result<()>;}+/// Wrap `text` as one POSIX single-quoted shell word.+///+/// [`create_window`](TmuxOperations::create_window) nests the agent's launch+/// command inside `sh -c β¦`, and that command has **already** been quoted by+/// [`compose_command`](crate::agent::spec::compose_command) β which single-quotes+/// the task prompt. Interpolating it into another pair of single quotes ends the+/// outer word at the first inner quote, and the shell then parses the prompt as+/// code: verified against tmux 3.5a, `claude --dangerously-skip-permissions+/// '/agtx:plan <id>\n\n<task>'` reached the process as argv+/// `["--dangerously-skip-permissions", "/agtx:plan"]` β the id and the whole task+/// silently gone β and codex's `$agtx-plan` fared worse still, with `$agtx`+/// expanded to nothing and only `-plan` surviving.+///+/// So the inner command is quoted here rather than interpolated raw, closing the+/// quote and reopening it around each literal `'` in the usual POSIX way.+fn single_quote(text: &str) -> String {+ format!("'{}'", text.replace('\'', "'\"'\"'"))+}++/// The shell command tmux is asked to run for an agent pane.+///+/// `keep_shell_on_exit` drops to a login shell afterwards, so a task pane+/// survives the agent quitting and can be inspected.+fn wrap_launch_command(shell_cmd: &str, keep_shell_on_exit: bool) -> String {+ let inner = single_quote(shell_cmd);+ if keep_shell_on_exit {+ format!("env -u CLAUDECODE -u CLAUDE_CODE_ENTRYPOINT sh -c {inner}; exec $SHELL")+ } else {+ format!("env -u CLAUDECODE -u CLAUDE_CODE_ENTRYPOINT sh -c {inner}")+ }+}+/// Real implementation using actual tmux commandspub struct RealTmuxOps;@@ -69,6 +124,7 @@ impl TmuxOperations for RealTmuxOps {working_dir: &str,command: Option<String>,keep_shell_on_exit: bool,+ env: &[(String, String)],) -> Result<()> {let mut cmd = std::process::Command::new("tmux");let target = format!("{}:", session);@@ -76,23 +132,18 @@ impl TmuxOperations for RealTmuxOps {.args(["new-window", "-d", "-t", &target, "-n", window_name]).args(["-c", working_dir]);+ // tmux 3.0+; sets the variable on the window so every process started in+ // it inherits it, including agents launched later by resume or switch.+ for (key, value) in env {+ cmd.args(["-e", &format!("{}={}", key, value)]);+ }+if let Some(ref shell_cmd) = command {// Unset Claude Code's nesting-detection env vars so that agents// launched in task panes are not blocked by the "launched inside// another Claude Code session" check.- if keep_shell_on_exit {- let wrapped = format!(- "env -u CLAUDECODE -u CLAUDE_CODE_ENTRYPOINT sh -c '{}'; exec $SHELL",- shell_cmd- );- cmd.args(["sh", "-c", &wrapped]);- } else {- let wrapped = format!(- "env -u CLAUDECODE -u CLAUDE_CODE_ENTRYPOINT sh -c '{}'",- shell_cmd- );- cmd.args(["sh", "-c", &wrapped]);- }+ let wrapped = wrap_launch_command(shell_cmd, keep_shell_on_exit);+ cmd.args(["sh", "-c", &wrapped]);}let output = cmd.output()?;@@ -147,7 +198,7 @@ impl TmuxOperations for RealTmuxOps {Ok(())}- fn send_keys_literal(&self, target: &str, keys: &str) -> Result<()> {+ fn send_key(&self, target: &str, keys: &str) -> Result<()> {std::process::Command::new("tmux").args(["-L", super::AGENT_SERVER]).args(["send-keys", "-t", target, keys])@@ -155,6 +206,16 @@ impl TmuxOperations for RealTmuxOps {Ok(())}+ fn send_text(&self, target: &str, text: &str) -> Result<()> {+ // `-l` disables key-name lookup; `--` stops tmux parsing text that begins+ // with a dash as flags.+ std::process::Command::new("tmux")+ .args(["-L", super::AGENT_SERVER])+ .args(["send-keys", "-t", target, "-l", "--", text])+ .output()?;+ Ok(())+ }+fn paste_text(&self, target: &str, text: &str) -> Result<()> {use std::io::Write;let mut child = std::process::Command::new("tmux")@@ -256,3 +317,146 @@ impl TmuxOperations for RealTmuxOps {Ok(())}}++#[cfg(test)]+mod tests {+ use super::*;++ /// Run the wrapper through a real `sh`, exactly as tmux does, and report the+ /// argv the launched process actually received.+ fn argv_delivered_by(shell_cmd: &str) -> Vec<String> {+ let wrapped = wrap_launch_command(shell_cmd, false);+ let out = std::process::Command::new("sh")+ .arg("-c")+ .arg(&wrapped)+ .output()+ .expect("sh should run");+ String::from_utf8_lossy(&out.stdout)+ .split('\u{1}')+ .filter(|s| !s.is_empty())+ .map(|s| s.to_string())+ .collect()+ }++ /// `printf` with a NUL-free separator, so an argument containing newlines+ /// stays one argument in the parsed output.+ fn dump_argv_command(args: &[&str]) -> String {+ let quoted: Vec<String> = args.iter().map(|a| single_quote(a)).collect();+ format!("printf '%s\u{1}' {}", quoted.join(" "))+ }++ #[test]+ fn a_launch_prompt_reaches_the_process_intact() {+ // The shape `compose_command` produces for the launch lane: flags, then+ // the whole opening message as one single-quoted word.+ let prompt = "/agtx:plan 57d57fe8-5990\n\nSMOKE TEST line two";+ let cmd = dump_argv_command(&["--dangerously-skip-permissions", prompt]);+ assert_eq!(+ argv_delivered_by(&cmd),+ vec!["--dangerously-skip-permissions".to_string(), prompt.to_string()],+ );+ }++ #[test]+ fn a_dollar_command_is_not_expanded_away() {+ // Codex's skill syntax is `$agtx-plan`. Interpolated into the wrapper+ // unquoted, the shell expanded `$agtx` to nothing and only `-plan`+ // survived β the whole task text with it.+ let prompt = "$agtx-plan 468b79fa\n\nSMOKE TEST";+ let cmd = dump_argv_command(&["--sandbox", "workspace-write", prompt]);+ assert_eq!(+ argv_delivered_by(&cmd),+ vec![+ "--sandbox".to_string(),+ "workspace-write".to_string(),+ prompt.to_string(),+ ],+ );+ }++ #[test]+ fn a_quote_in_the_task_survives_both_quoting_layers() {+ let prompt = "fix the parser so it's correct";+ let cmd = dump_argv_command(&[prompt]);+ assert_eq!(argv_delivered_by(&cmd), vec![prompt.to_string()]);+ }++ /// Run the wrapped command with a fake `claude` on `PATH` that echoes its+ /// argv, and return what that binary actually received.+ ///+ /// `sh -n` is not enough here: it parses only the *outer* layer, and the+ /// wrapper is always outer-valid. A mis-quoted inner command parses fine and+ /// then dies at run time with "unexpected EOF while looking for matching `''"+ /// β verified, and the reason the first version of this test had no teeth.+ #[cfg(unix)]+ fn argv_seen_by_fake_claude(shell_cmd: &str) -> (bool, String) {+ use std::os::unix::fs::PermissionsExt;+ let dir = tempfile::tempdir().expect("tempdir");+ let fake = dir.path().join("claude");+ std::fs::write(&fake, "#!/bin/sh\nprintf '%s\\n' \"$@\"\n").expect("write fake");+ std::fs::set_permissions(&fake, std::fs::Permissions::from_mode(0o755)).expect("chmod");+ let path = format!(+ "{}:{}",+ dir.path().display(),+ std::env::var("PATH").unwrap_or_default()+ );+ let out = std::process::Command::new("sh")+ .arg("-c")+ .arg(wrap_launch_command(shell_cmd, false))+ .env("PATH", path)+ .output()+ .expect("sh should run");+ (+ out.status.success(),+ String::from_utf8_lossy(&out.stdout).to_string(),+ )+ }++ /// The orchestrator command is the other thing `create_window` wraps, and it+ /// carries a single-quoted JSON blob for `claude mcp add-json`.+ ///+ /// It used to pre-escape its own wrapping quotes because it was interpolated+ /// raw. Now that `single_quote` quotes the whole command, that pre-escape+ /// double-escapes: the pane dies on an unterminated quote before `add-json`+ /// runs, silently, because the window is created either way. Nothing else+ /// covers this path β the TUI tests mock the command builder.+ #[cfg(unix)]+ #[test]+ fn the_orchestrator_command_reaches_claude_with_its_json_intact() {+ let agent = crate::agent::Agent::new("claude", "claude", "", "");+ let ops = crate::agent::CodingAgent::new(agent);+ let json = r#"{"type":"stdio","command":"/bin/agtx","args":["mcp-serve","/tmp/repo"]}"#;+ let cmd = crate::agent::AgentOperations::build_orchestrator_command(&ops, json, "/bin/agtx");+ let (ok, seen) = argv_seen_by_fake_claude(&cmd);+ assert!(ok, "the wrapped orchestrator command must run: {seen}");+ assert!(+ seen.lines().any(|l| l == json),+ "claude must receive the JSON as one intact argument; got:\n{seen}"+ );+ }++ /// ...and a project path containing an apostrophe still arrives intact,+ /// because the caller escapes it for the single-quoted word it lands in.+ #[cfg(unix)]+ #[test]+ fn an_apostrophe_in_the_mcp_json_survives_both_layers() {+ let agent = crate::agent::Agent::new("claude", "claude", "", "");+ let ops = crate::agent::CodingAgent::new(agent);+ let raw = r#"{"args":["mcp-serve","/tmp/it's a repo"]}"#;+ let escaped = raw.replace('\'', "'\"'\"'");+ let cmd =+ crate::agent::AgentOperations::build_orchestrator_command(&ops, &escaped, "/bin/agtx");+ let (ok, seen) = argv_seen_by_fake_claude(&cmd);+ assert!(ok, "the wrapped orchestrator command must run: {seen}");+ assert!(+ seen.lines().any(|l| l == raw),+ "claude must receive the unescaped JSON; got:\n{seen}"+ );+ }++ #[test]+ fn the_pane_drops_to_a_shell_only_when_asked() {+ assert!(wrap_launch_command("claude", true).ends_with("; exec $SHELL"));+ assert!(!wrap_launch_command("claude", false).contains("exec $SHELL"));+ }+}diff --git a/src/tui/app.rs b/src/tui/app.rsindex 89cf626..19bc146 100644--- a/src/tui/app.rs+++ b/src/tui/app.rs@@ -15,6 +15,7 @@ use std::sync::{};use std::time::Instant;+use crate::agent::hook_status::{self, HookState};use crate::agent::{self, AgentOperations};use crate::config::{GlobalConfig, MergedConfig, ProjectConfig, ThemeConfig, WorkflowPlugin};use crate::db::{Database, PhaseStatus, Task, TaskStatus, TransitionRequest};@@ -292,6 +293,8 @@ struct AppState {spinner_frame: usize,// Idle detection: (content_hash, last_change_time) per taskpane_content_hashes: HashMap<String, (u64, Instant)>,+ /// Why a task is Blocked, as reported by its agent's hook payload.+ blocked_reasons: HashMap<String, String>,// Guard: task IDs for which merge-conflict check has already been performedmerge_conflict_checked: HashSet<String>,// Guard: task IDs for which stuck-task notification has been fired (reset on phase advance)@@ -402,6 +405,8 @@ struct SessionTaskStatus {agent: String,/// Whether this task was already Ready before this refresh cycle.was_ready: bool,+ /// The agent's own report of its state, when it writes one.+ hook_status: Option<hook_status::AgentHookStatus>,}/// Results sent back from the background session refresh thread.@@ -569,55 +574,66 @@ impl App {let available_agents = agent::detect_available_agents();// Setup based on mode- let (db, project_path, project_name, tmux_project_name, project_config, trust_warning) = match &mode {- AppMode::Dashboard => (- None,- None,- "Dashboard".to_string(),- tmux::safe_session_name("Dashboard"),- ProjectConfig::default(),- None,- ),- AppMode::Project(path) => {- let canonical = path.canonicalize().unwrap_or_else(|_| path.clone());- let name = canonical- .file_name()- .and_then(|n| n.to_str())- .unwrap_or("unknown")- .to_string();- let tmux_name = tmux::safe_session_name(&name);- let mut project_config = ProjectConfig::load(&canonical).unwrap_or_default();- let db = Database::open_project(&canonical)?;-- // Trust-on-first-use: suppress dangerous config fields from untrusted projects- let trust_store = crate::config::TrustStore::load().unwrap_or_default();- let trust_warning = if !trust_store.is_trusted(&canonical) {- if project_config.init_script.is_some() || project_config.copy_files.is_some() || project_config.cleanup_script.is_some() {- tracing::warn!(- project = %canonical.display(),- "Untrusted project config β init_script, cleanup_script, and copy_files suppressed"- );- project_config.init_script = None;- project_config.cleanup_script = None;- project_config.copy_files = None;- Some("Untrusted project config: init_script, cleanup_script, and copy_files disabled. Run `agtx trust` to enable.".to_string())+ let (db, project_path, project_name, tmux_project_name, project_config, trust_warning) =+ match &mode {+ AppMode::Dashboard => (+ None,+ None,+ "Dashboard".to_string(),+ tmux::safe_session_name("Dashboard"),+ ProjectConfig::default(),+ None,+ ),+ AppMode::Project(path) => {+ let canonical = path.canonicalize().unwrap_or_else(|_| path.clone());+ let name = canonical+ .file_name()+ .and_then(|n| n.to_str())+ .unwrap_or("unknown")+ .to_string();+ let tmux_name = tmux::safe_session_name(&name);+ let mut project_config = ProjectConfig::load(&canonical).unwrap_or_default();+ let db = Database::open_project(&canonical)?;++ // Trust-on-first-use: suppress dangerous config fields from untrusted projects+ let trust_store = crate::config::TrustStore::load().unwrap_or_default();+ let trust_warning = if !trust_store.is_trusted(&canonical) {+ if project_config.init_script.is_some()+ || project_config.copy_files.is_some()+ || project_config.cleanup_script.is_some()+ {+ tracing::warn!(+ project = %canonical.display(),+ "Untrusted project config β init_script, cleanup_script, and copy_files suppressed"+ );+ project_config.init_script = None;+ project_config.cleanup_script = None;+ project_config.copy_files = None;+ Some("Untrusted project config: init_script, cleanup_script, and copy_files disabled. Run `agtx trust` to enable.".to_string())+ } else {+ None+ }} else {None- }- } else {- None- };+ };- // Register project in global database- let project = crate::db::Project::new(&name, canonical.to_string_lossy());- global_db.upsert_project(&project)?;+ // Register project in global database+ let project = crate::db::Project::new(&name, canonical.to_string_lossy());+ global_db.upsert_project(&project)?;- // Ensure tmux session exists for this project- ensure_project_tmux_session(&tmux_name, &canonical, tmux_ops.as_ref());+ // Ensure tmux session exists for this project+ ensure_project_tmux_session(&tmux_name, &canonical, tmux_ops.as_ref());- (Some(db), Some(canonical), name, tmux_name, project_config, trust_warning)- }- };+ (+ Some(db),+ Some(canonical),+ name,+ tmux_name,+ project_config,+ trust_warning,+ )+ }+ };let config = MergedConfig::merge(&global_config, &project_config);@@ -681,6 +697,7 @@ impl App {phase_status_cache: HashMap::new(),spinner_frame: 0,pane_content_hashes: HashMap::new(),+ blocked_reasons: HashMap::new(),merge_conflict_checked: HashSet::new(),stuck_task_notified: HashSet::new(),stuck_task_idle_since: HashMap::new(),@@ -711,6 +728,26 @@ impl App {// Load projects from global databaseapp.refresh_projects()?;+ // Re-deploy agent configs for worktrees set up by a different agtx binary.+ if let Some(ref project_path) = app.state.project_path {+ let candidates: Vec<(String, Option<String>)> = app+ .state+ .board+ .tasks+ .iter()+ .filter(|t| t.status != TaskStatus::Done)+ .filter_map(|t| t.worktree_path.clone().map(|wt| (wt, t.plugin.clone())))+ .collect();+ if !candidates.is_empty() {+ refresh_stale_worktree_configs(+ candidates,+ project_path.clone(),+ collect_phase_agents(&app.state.config),+ app.state.config.agent_hooks,+ );+ }+ }+// Recover tasks whose tmux windows were lost (server restart, manual kill, etc.){let tasks_to_recover: Vec<_> = app@@ -737,10 +774,7 @@ impl App {let _ = recover_task_session(task,&app.state.tmux_project_name,- app.state- .project_path- .as_deref()- .unwrap_or(Path::new(".")),+ app.state.project_path.as_deref().unwrap_or(Path::new(".")),app.state.tmux_ops.as_ref(),agent_ops.as_ref(),);@@ -759,7 +793,7 @@ impl App {let tmux_ops = Arc::clone(&app.state.tmux_ops);let ready_flag = Arc::clone(&app.state.orchestrator_ready);std::thread::spawn(move || {- if wait_for_agent_ready(&tmux_ops, &orch_target).is_some() {+ if wait_for_agent_ready(&tmux_ops, &orch_target, Some("claude")).is_some() {ready_flag.store(true, Ordering::Release);}});@@ -868,6 +902,7 @@ impl App {phase_status_cache: HashMap::new(),spinner_frame: 0,pane_content_hashes: HashMap::new(),+ blocked_reasons: HashMap::new(),merge_conflict_checked: HashSet::new(),stuck_task_notified: HashSet::new(),stuck_task_idle_since: HashMap::new(),@@ -1370,10 +1405,7 @@ impl App {push_wrapped(&mut lines,vec![- Span::styled(- " Title: ".to_string(),- Style::default().fg(dimmed_color),- ),+ Span::styled(" Title: ".to_string(), Style::default().fg(dimmed_color)),Span::styled(state.pending_task_title.clone(),Style::default().fg(text_color),@@ -1391,10 +1423,7 @@ impl App {push_wrapped(&mut lines,vec![- Span::styled(- " Plugin: ".to_string(),- Style::default().fg(dimmed_color),- ),+ Span::styled(" Plugin: ".to_string(), Style::default().fg(dimmed_color)),Span::styled(plugin_name, Style::default().fg(text_color)),],);@@ -1459,10 +1488,7 @@ impl App {opt.description.clone(),Style::default().fg(desc_color),),- Span::styled(- check.to_string(),- Style::default().fg(Color::Green),- ),+ Span::styled(check.to_string(), Style::default().fg(Color::Green)),],);}@@ -2292,9 +2318,9 @@ impl App {let level_count = popup.graph.level_count();if level_count == 0 {let empty = Paragraph::new("No tasks").block(- Block::default().borders(Borders::ALL).border_style(- Style::default().fg(hex_to_color(&theme.color_popup_border)),- ),+ Block::default()+ .borders(Borders::ALL)+ .border_style(Style::default().fg(hex_to_color(&theme.color_popup_border))),);frame.render_widget(empty, body);} else {@@ -2309,11 +2335,7 @@ impl App {// on screen β covers the initial open (cursor may start in a far// level) and every navigation (the key handler just moves the cursor// and lets this clamp re-scroll).- let sel_level = popup- .graph- .nodes- .get(popup.selected)- .map_or(0, |n| n.level);+ let sel_level = popup.graph.nodes.get(popup.selected).map_or(0, |n| n.level);let start = clamp_scroll_to_selected(popup.scroll_levels.get(),sel_level,@@ -2467,7 +2489,10 @@ impl App {String::new()} else {let joined = node.dep_titles.join(", ");- format!("\u{2190} {}", truncate_str(&joined, inner.width.saturating_sub(2) as usize))+ format!(+ "\u{2190} {}",+ truncate_str(&joined, inner.width.saturating_sub(2) as usize)+ )};let hint_line = Line::from(Span::styled(hint,@@ -2572,6 +2597,12 @@ impl App {let spinner = SPINNER_FRAMES[spinner_frame % SPINNER_FRAMES.len()];Span::styled(format!("{} ", spinner), Style::default().fg(Color::Yellow))}+ Some((PhaseStatus::Blocked, _)) => Span::styled(+ "? ",+ Style::default()+ .fg(hex_to_color(&theme.color_accent))+ .bold(),+ ),Some((PhaseStatus::Idle, _)) => Span::styled("\u{23f8} ",Style::default().fg(hex_to_color(&theme.color_dimmed)),@@ -2605,8 +2636,7 @@ impl App {} else if deps_blocked {let lock_span = Span::styled("\u{2298} ",- Style::default()- .fg(hex_to_color(&theme.color_dimmed)),+ Style::default().fg(hex_to_color(&theme.color_dimmed)),);let title_spans = Line::from(vec![lock_span, Span::styled(title, title_style)]);let title_line = Paragraph::new(title_spans);@@ -2680,14 +2710,25 @@ impl App {width: inner.width,height: 1,};- let agent_style = match task.agent.as_str() {- "claude" => Style::default().fg(Color::Rgb(227, 148, 62)), // orange- "gemini" => Style::default().fg(Color::Rgb(234, 130, 180)), // pink- "opencode" => Style::default().fg(Color::White).bg(Color::Rgb(80, 80, 80)), // white on grey- "codex" => Style::default().fg(Color::White).bg(Color::Rgb(20, 20, 20)), // white on black- "grok" => Style::default().fg(Color::Rgb(20, 20, 20)).bg(Color::White), // black on white- "antigravity" => Style::default().fg(Color::Rgb(120, 190, 255)), // light blue- _ => Style::default().fg(Color::White),+ // Pure white stays `Color::White` rather than becoming truecolor: it+ // is an ANSI palette entry, which a themed terminal renders as its+ // own white. Rgb(255,255,255) would override the user's theme.+ let to_color = |(r, g, b): (u8, u8, u8)| {+ if (r, g, b) == (255, 255, 255) {+ Color::White+ } else {+ Color::Rgb(r, g, b)+ }+ };+ let agent_style = match agent::spec(task.agent.as_str()) {+ Some(spec) => {+ let style = Style::default().fg(to_color(spec.label_fg));+ match spec.label_bg {+ Some(bg) => style.bg(to_color(bg)),+ None => style,+ }+ }+ None => Style::default().fg(Color::White),};let agent_label = Paragraph::new(format!(" {} ", task.agent)).style(agent_style)@@ -2912,7 +2953,9 @@ impl App {InputMode::Normal => {// Ctrl+f = fullscreen attach (handled here since handle_normal_key only gets KeyCode)if key.code == KeyCode::Char('f')- && key.modifiers.contains(crossterm::event::KeyModifiers::CONTROL)+ && key+ .modifiers+ .contains(crossterm::event::KeyModifiers::CONTROL){if let Some(task) = self.state.board.selected_task() {if let Some(window_name) = task.session_name.clone() {@@ -3026,7 +3069,8 @@ impl App {self.state.config = crate::config::MergedConfig::merge(&global_config, &project_config);self.state.flags.no_init_scripts = false;self.state.warning_message = Some((- "Project trusted. init_script, cleanup_script, and copy_files are now active.".to_string(),+ "Project trusted. init_script, cleanup_script, and copy_files are now active."+ .to_string(),Instant::now(),));}@@ -3928,8 +3972,7 @@ impl App {}KeyCode::Delete => {if self.state.input_cursor < self.state.input_buffer.len() {- let end =- next_char_boundary(&self.state.input_buffer, self.state.input_cursor);+ let end = next_char_boundary(&self.state.input_buffer, self.state.input_cursor);self.state.input_buffer.drain(self.state.input_cursor..end);}}@@ -4286,8 +4329,7 @@ impl App {}KeyCode::Delete => {if self.state.input_cursor < self.state.input_buffer.len() {- let end =- next_char_boundary(&self.state.input_buffer, self.state.input_cursor);+ let end = next_char_boundary(&self.state.input_buffer, self.state.input_cursor);self.state.input_buffer.drain(self.state.input_cursor..end);}}@@ -4699,8 +4741,10 @@ impl App {if current_status == TaskStatus::Backlog {if let Some(db) = &self.state.db {if !db.deps_satisfied(&task) {- self.state.warning_message =- Some(("Dependencies not in Review/Done β cannot start task".to_string(), Instant::now()));+ self.state.warning_message = Some((+ "Dependencies not in Review/Done β cannot start task".to_string(),+ Instant::now(),+ ));return Ok(());}}@@ -4773,7 +4817,7 @@ impl App {}let agent_running = task.session_name.as_ref().map_or(false, |target| {self.state.tmux_ops.window_exists(target).unwrap_or(false)- && is_agent_active(&*self.state.tmux_ops, target)+ && is_agent_active(&*self.state.tmux_ops, target, Some(task.agent.as_str()))});if agent_running {self.state.move_confirm_popup = Some(MoveConfirmPopup {@@ -4834,6 +4878,7 @@ impl App {&task_content,task.cycle,&task.id,+ true,);let prompt =resolve_prompt(&plugin, planning_phase, &task_content, &task.id, task.cycle);@@ -4844,6 +4889,8 @@ impl App {spawn_send_to_agent(Arc::clone(&self.state.tmux_ops),Arc::clone(&self.state.agent_registry),+ task.id.clone(),+ self.state.config.agent_hooks,target,task.agent.clone(),planning_agent.clone(),@@ -4875,6 +4922,19 @@ impl App {&task_content,task.cycle,&task.id,+ true,+ );+ // The launch lane hands the command to the process in argv, so it keeps the+ // task's own line structure. Only the send-after-ready fallback below needs+ // the flattened form. See `resolve_skill_command`.+ let skill_cmd_launch = resolve_skill_command(+ &plugin,+ "planning",+ &planning_agent,+ &task_content,+ task.cycle,+ &task.id,+ false,);let prompt_trigger = resolve_prompt_trigger(&plugin, "planning");let all_agents = collect_phase_agents(&self.state.config);@@ -4894,6 +4954,7 @@ impl App {};let skip_init_scripts = self.state.flags.no_init_scripts;let skip_worktree = self.state.config.skip_worktree;+ let agent_hooks = self.state.config.agent_hooks;let tmux_ops = Arc::clone(&self.state.tmux_ops);let git_ops = Arc::clone(&self.state.git_ops);let agent_ops = self.state.agent_registry.get(&planning_agent);@@ -4956,10 +5017,12 @@ impl App {&referenced_tasks,skip_init_scripts,skip_worktree,+ agent_hooks,+ skill_cmd_launch.as_deref(),);match result {- Ok(target) => {+ Ok((target, launched_with_prompt)) => {let _ = tx.send(SetupResult {task_id: task_id.clone(),session_name: tmp_task.session_name.unwrap_or_default(),@@ -4970,7 +5033,13 @@ impl App {plugin: plugin_name,error: None,});- if let Some(target) = wait_for_agent_ready(&tmux_ops, &target) {+ // Skip the whole send-after-ready dance when the agent was+ // launched with the opening message already in argv.+ if launched_with_prompt {+ // nothing to send+ } else if let Some(target) =+ wait_for_agent_ready(&tmux_ops, &target, Some(&planning_agent_clone))+ {send_skill_and_prompt(&tmux_ops,&target,@@ -5024,6 +5093,7 @@ impl App {&task_content,task.cycle,&task.id,+ true,);let prompt = resolve_prompt(&plugin, run_phase, &task_content, &task.id, task.cycle);let prompt_trigger = resolve_prompt_trigger(&plugin, run_phase);@@ -5033,6 +5103,8 @@ impl App {spawn_send_to_agent(Arc::clone(&self.state.tmux_ops),Arc::clone(&self.state.agent_registry),+ task.id.clone(),+ self.state.config.agent_hooks,session_name.clone(),task.agent.clone(),running_agent.clone(),@@ -5058,8 +5130,15 @@ impl App {if let Some(session_name) = &task.session_name {let plugin = self.load_task_plugin(task);let task_content = task.content_text();- let skill_cmd =- resolve_skill_command(&plugin, "review", &review_agent, &task_content, task.cycle, &task.id);+ let skill_cmd = resolve_skill_command(+ &plugin,+ "review",+ &review_agent,+ &task_content,+ task.cycle,+ &task.id,+ true,+ );let prompt = resolve_prompt(&plugin, "review", &task_content, &task.id, task.cycle);let prompt_trigger = resolve_prompt_trigger(&plugin, "review");let auto_dismiss = plugin@@ -5068,6 +5147,8 @@ impl App {spawn_send_to_agent(Arc::clone(&self.state.tmux_ops),Arc::clone(&self.state.agent_registry),+ task.id.clone(),+ self.state.config.agent_hooks,session_name.clone(),task.agent.clone(),review_agent.clone(),@@ -5265,6 +5346,7 @@ impl App {};let skip_init_scripts = self.state.flags.no_init_scripts;let skip_worktree = self.state.config.skip_worktree;+ let agent_hooks = self.state.config.agent_hooks;let tmux_ops = Arc::clone(&self.state.tmux_ops);let git_ops = Arc::clone(&self.state.git_ops);@@ -5307,10 +5389,14 @@ impl App {&[],skip_init_scripts,skip_worktree,+ agent_hooks,+ // Research keeps the send-after-ready path for now: its skill is+ // resolved later in the thread, and the launch lane is planning-only.+ None,);match result {- Ok(target) => {+ Ok((target, launched_with_prompt)) => {let worktree_path = tmp_task.worktree_path.clone().unwrap_or_default();// Determine preresearch vs research by checking if preresearch artifacts@@ -5344,6 +5430,7 @@ impl App {&task_content,task_cycle,&task_id,+ true,);let prompt_trigger = resolve_prompt_trigger(&plugin, research_phase);@@ -5359,7 +5446,13 @@ impl App {});// Wait for agent ready and send skill+prompt- if let Some(target) = wait_for_agent_ready(&tmux_ops, &target) {+ // Skip the whole send-after-ready dance when the agent was+ // launched with the opening message already in argv.+ if launched_with_prompt {+ // nothing to send+ } else if let Some(target) =+ wait_for_agent_ready(&tmux_ops, &target, Some(&agent_name))+ {send_skill_and_prompt(&tmux_ops,&target,@@ -5398,17 +5491,15 @@ impl App {};let tasks = db.get_all_tasks().unwrap_or_default();if tasks.is_empty() {- self.state.warning_message =- Some(("No tasks to show in the dependency view".to_string(), Instant::now()));+ self.state.warning_message = Some((+ "No tasks to show in the dependency view".to_string(),+ Instant::now(),+ ));return Ok(());}let graph = crate::tui::dep_graph::build_dep_graph(&tasks, |t| db.deps_satisfied(t));// Start the cursor on the first unblocked node if there is one.- let selected = graph- .nodes- .iter()- .position(|n| n.unblocked)- .unwrap_or(0);+ let selected = graph.nodes.iter().position(|n| n.unblocked).unwrap_or(0);self.state.dep_graph_popup = Some(DepGraphPopup {graph,selected,@@ -5594,7 +5685,10 @@ impl App {return Ok(());}let (mut task, project_path) = match (- self.state.db.as_ref().and_then(|db| db.get_task(task_id).ok().flatten()),+ self.state+ .db+ .as_ref()+ .and_then(|db| db.get_task(task_id).ok().flatten()),self.state.project_path.clone(),) {(Some(t), Some(p)) => (t, p),@@ -5654,8 +5748,10 @@ impl App {// Block when dependencies are not satisfiedif let Some(db) = &self.state.db {if !db.deps_satisfied(&task) {- self.state.warning_message =- Some(("Dependencies not in Review/Done β cannot start task".to_string(), Instant::now()));+ self.state.warning_message = Some((+ "Dependencies not in Review/Done β cannot start task".to_string(),+ Instant::now(),+ ));return Ok(());}}@@ -5699,6 +5795,17 @@ impl App {&task_content,task.cycle,&task.id,+ true,+ );+ // Verbatim variant for the launch lane β see the planning path above.+ let skill_cmd_launch = resolve_skill_command(+ &plugin,+ "running",+ &running_agent,+ &task_content,+ task.cycle,+ &task.id,+ false,);let prompt_trigger = resolve_prompt_trigger(&plugin, "running");let auto_dismiss = plugin@@ -5718,6 +5825,8 @@ impl App {spawn_send_to_agent(Arc::clone(&self.state.tmux_ops),Arc::clone(&self.state.agent_registry),+ task.id.clone(),+ self.state.config.agent_hooks,target,task.agent.clone(),agent_switch_agent.clone(),@@ -5757,6 +5866,7 @@ impl App {};let skip_init_scripts = self.state.flags.no_init_scripts;let skip_worktree = self.state.config.skip_worktree;+ let agent_hooks = self.state.config.agent_hooks;let tmux_ops = Arc::clone(&self.state.tmux_ops);let git_ops = Arc::clone(&self.state.git_ops);let agent_ops = self.state.agent_registry.get(&running_agent);@@ -5791,10 +5901,12 @@ impl App {&[],skip_init_scripts,skip_worktree,+ agent_hooks,+ skill_cmd_launch.as_deref(),);match result {- Ok(target) => {+ Ok((target, launched_with_prompt)) => {let _ = tx.send(SetupResult {task_id: task_id.clone(),session_name: tmp_task.session_name.unwrap_or_default(),@@ -5806,7 +5918,13 @@ impl App {error: None,});- if let Some(target) = wait_for_agent_ready(&tmux_ops, &target) {+ // Skip the whole send-after-ready dance when the agent was+ // launched with the opening message already in argv.+ if launched_with_prompt {+ // nothing to send+ } else if let Some(target) =+ wait_for_agent_ready(&tmux_ops, &target, Some(&running_agent_clone))+ {send_skill_and_prompt(&tmux_ops,&target,@@ -5853,6 +5971,7 @@ impl App {if agent_switch {if let Some(session_name) = &task.session_name {let session_clone = session_name.clone();+ let hook_task_id = task.id.clone();let tmux_ops = Arc::clone(&self.state.tmux_ops);let agent_registry = Arc::clone(&self.state.agent_registry);let running_agent_clone = running_agent.clone();@@ -5865,6 +5984,7 @@ impl App {&session_clone,agent_ops.as_ref(),wt_path.as_deref(),+ &hook_task_id,);let new_cmd = agent_ops.build_interactive_command("");switch_agent_in_tmux(@@ -5915,6 +6035,7 @@ impl App {&task_content,task.cycle,&task.id,+ true,);let prompt =resolve_prompt(&plugin, "planning", &task_content, &task.id, task.cycle);@@ -5922,6 +6043,7 @@ impl App {if let Some(session_name) = &task.session_name {let session_clone = session_name.clone();+ let hook_task_id = task.id.clone();let tmux_ops = Arc::clone(&self.state.tmux_ops);let agent_registry = Arc::clone(&self.state.agent_registry);let planning_agent_clone = planning_agent.clone();@@ -5939,6 +6061,7 @@ impl App {&session_clone,agent_ops.as_ref(),wt_path.as_deref(),+ &hook_task_id,);if agent_switch {let new_cmd = agent_ops.build_interactive_command("");@@ -5948,7 +6071,9 @@ impl App {¤t_agent_clone,&new_cmd,);- let _ = wait_for_agent_ready(&tmux_ops, &session_clone);+ // The *new* agent is what has to become ready.+ let _ =+ wait_for_agent_ready(&tmux_ops, &session_clone, Some(&planning_agent_clone));}send_skill_and_prompt(&tmux_ops,@@ -5987,6 +6112,7 @@ impl App {if agent_switch {if let Some(session_name) = &task.session_name {let session_clone = session_name.clone();+ let hook_task_id = task.id.clone();let tmux_ops = Arc::clone(&self.state.tmux_ops);let agent_registry = Arc::clone(&self.state.agent_registry);let planning_agent_clone = planning_agent.clone();@@ -5999,6 +6125,7 @@ impl App {&session_clone,agent_ops.as_ref(),wt_path.as_deref(),+ &hook_task_id,);let new_cmd = agent_ops.build_interactive_command("");switch_agent_in_tmux(@@ -6051,9 +6178,7 @@ impl App {if let Some(db) = &self.state.db {let _ = match &result {Ok(()) => db.mark_transition_processed(&req.id, None),- Err(e) => {- db.mark_transition_processed(&req.id, Some(&e.to_string()))- }+ Err(e) => db.mark_transition_processed(&req.id, Some(&e.to_string())),};}self.refresh_tasks()?;@@ -6091,9 +6216,7 @@ impl App {"move_forward" | "move_to_planning" | "move_to_running" | "research");if is_forward && task.status == TaskStatus::Backlog && !db.deps_satisfied(&task) {- anyhow::bail!(- "Cannot advance task: dependencies not in Review/Done"- );+ anyhow::bail!("Cannot advance task: dependencies not in Review/Done");}match req.action.as_str() {@@ -6235,8 +6358,15 @@ impl App {if let Some(session_name) = &task.session_name {let plugin = self.load_task_plugin(task);let task_content = task.content_text();- let skill_cmd =- resolve_skill_command(&plugin, "review", &review_agent, &task_content, task.cycle, &task.id);+ let skill_cmd = resolve_skill_command(+ &plugin,+ "review",+ &review_agent,+ &task_content,+ task.cycle,+ &task.id,+ true,+ );let prompt = resolve_prompt(&plugin, "review", &task_content, &task.id, task.cycle);let prompt_trigger = resolve_prompt_trigger(&plugin, "review");let auto_dismiss = plugin@@ -6245,6 +6375,8 @@ impl App {spawn_send_to_agent(Arc::clone(&self.state.tmux_ops),Arc::clone(&self.state.agent_registry),+ task.id.clone(),+ self.state.config.agent_hooks,session_name.clone(),task.agent.clone(),review_agent.clone(),@@ -6287,8 +6419,7 @@ impl App {// If orchestrator is running, open the popup to view itif is_orchestrator_live(self.state.tmux_ops.as_ref(), &orch_target) {- let first_time =- self.state.orchestrator_session.as_deref() != Some(&orch_target);+ let first_time = self.state.orchestrator_session.as_deref() != Some(&orch_target);self.state.orchestrator_session = Some(orch_target.clone());if first_time {@@ -6307,7 +6438,7 @@ impl App {let ready_flag = Arc::clone(&self.state.orchestrator_ready);let target = orch_target.clone();std::thread::spawn(move || {- if wait_for_agent_ready(&tmux_ops, &target).is_some() {+ if wait_for_agent_ready(&tmux_ops, &target, Some("claude")).is_some() {ready_flag.store(true, Ordering::Release);}});@@ -6362,7 +6493,12 @@ impl App {"command": agtx_bin,"args": ["mcp-serve", &project_path_str]});- let mcp_json_str = mcp_json.to_string().replace('\'', "'\\''");+ // Escaped for the single-quoted word it becomes inside the orchestrator+ // command (`add-json β¦ '<json>'`). Only reachable when the project path+ // contains an apostrophe. The *outer* `sh -c` layer is handled by+ // `single_quote` in create_window β pre-escaping for it here would+ // double-escape and break the command.+ let mcp_json_str = mcp_json.to_string().replace('\'', "'\"'\"'");let agent_cmd = agent.build_orchestrator_command(&mcp_json_str, &agtx_bin);@@ -6380,6 +6516,8 @@ impl App {&project_path_str,Some(agent_cmd),false,+ // The orchestrator is not a task, so it reports no hook status.+ &[],)?;self.state.orchestrator_session = Some(orch_target.clone());@@ -6413,7 +6551,11 @@ impl App {);if let Some(ref db) = self.state.db {- run_orchestrator_catchup(db, &self.state.board.tasks, self.state.project_path.as_deref());+ run_orchestrator_catchup(+ db,+ &self.state.board.tasks,+ self.state.project_path.as_deref(),+ );}// Send the /agtx:orchestrate command once the agent is ready@@ -6423,7 +6565,7 @@ impl App {let ready_flag = Arc::clone(&self.state.orchestrator_ready);let target = orch_target;std::thread::spawn(move || {- if let Some(ready_target) = wait_for_agent_ready(&tmux_ops, &target) {+ if let Some(ready_target) = wait_for_agent_ready(&tmux_ops, &target, Some(&default_agent)) {let _ = tmux_ops.send_keys(&ready_target, &skill_cmd);ready_flag.store(true, Ordering::Release);}@@ -6443,11 +6585,7 @@ impl App {.unwrap_or(true){let agent_ops = self.state.agent_registry.get(&task.agent);- let project_path = self- .state- .project_path- .as_deref()- .unwrap_or(Path::new("."));+ let project_path = self.state.project_path.as_deref().unwrap_or(Path::new("."));let _ = recover_task_session(task,&self.state.tmux_project_name,@@ -6527,9 +6665,14 @@ impl App {// window_name is already session:window format, use it directly.let _ = std::process::Command::new("tmux").args([- "-L", tmux::AGENT_SERVER,- "select-window", "-t", window_name,- ";", "resize-window", "-A",+ "-L",+ tmux::AGENT_SERVER,+ "select-window",+ "-t",+ window_name,+ ";",+ "resize-window",+ "-A",]).output();} else {@@ -6547,10 +6690,18 @@ impl App {// Unset $TMUX so tmux allows attaching when inside a different tmux.let _ = std::process::Command::new("tmux").args([- "-L", tmux::AGENT_SERVER,- "attach", "-t", session,- ";", "select-window", "-t", window_name,- ";", "resize-window", "-A",+ "-L",+ tmux::AGENT_SERVER,+ "attach",+ "-t",+ session,+ ";",+ "select-window",+ "-t",+ window_name,+ ";",+ "resize-window",+ "-A",]).env_remove("TMUX").status();@@ -6653,7 +6804,9 @@ impl App {// Check window still existsif !is_orchestrator_live(self.state.tmux_ops.as_ref(), &orch_target) {self.state.orchestrator_session = None;- self.state.orchestrator_ready.store(false, Ordering::Release);+ self.state+ .orchestrator_ready+ .store(false, Ordering::Release);return;}@@ -6773,6 +6926,7 @@ impl App {std::thread::spawn(move || {let mut plugin_cache: HashMap<Option<String>, Option<WorkflowPlugin>> = HashMap::new();let mut statuses = Vec::new();+ let now_secs = chrono::Utc::now().timestamp();for (task_id,@@ -6864,22 +7018,51 @@ impl App {phase_status};- // Capture tmux content hash for idle detection (only when Working and window alive)- let content_hash = if phase_status == PhaseStatus::Working && !window_gone {+ // 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))+ } else {+ None+ };++ // Interactive prompts that block an agent are answered here as well+ // as during startup, because `wait_for_agent_ready` gives up after+ // ~60s and a slow agent can render its first-launch dialog later+ // than that β observed in an emulated swebench container, where+ // Claude showed the bypass warning well after the readiness window+ // had closed and nothing was left watching for it.+ if phase_status == PhaseStatus::Working && !window_gone && hook_status.is_none() {+ if let Some(sn) = session_name.as_ref() {+ if let Ok(content) = tmux_ops.capture_pane(sn) {+ // A fresh state each poll: the attempt cap guards a+ // single startup burst, whereas here the 2s cadence+ // between polls is itself the pacing.+ let mut st = LaunchDialogState::default();+ dismiss_launch_dialog(&tmux_ops, sn, Some(&agent), &content, &mut st);++ // Mid-session approval prompts (Codex's "allow this+ // MCP server to run tool") β a workaround for an+ // interactive prompt, not part of status detection.+ // Matched against this agent's own dialogs only: the+ // refresh loop knows what runs in the pane, unlike+ // `wait_for_agent_ready`.+ answer_session_dialogs(&tmux_ops, sn, &agent, &content);+ }+ }+ }++ // Pane hash is the fallback for agents that report nothing.+ // Skipping it when a hook status exists also drops one+ // `capture-pane` subprocess per task per refresh.+ let content_hash = if phase_status == PhaseStatus::Working+ && !window_gone+ && hook_status.is_none()+ {session_name.as_ref().and_then(|sn| {tmux_ops.capture_pane(sn).ok().map(|content| {- // Auto-dismiss Codex MCP tool approval prompt ("Always allow")- // so agents can call agtx MCP tools without manual confirmation.- if agent == "codex"- && content.contains("Allow the")- && content.contains("MCP server to run tool")- && content.contains("Always allow")- {- let _ = tmux_ops.send_keys_literal(sn, "3");- std::thread::sleep(std::time::Duration::from_millis(100));- let _ = tmux_ops.send_keys_literal(sn, "Enter");- }-use std::hash::{Hash, Hasher};let mut hasher = std::collections::hash_map::DefaultHasher::new();content.hash(&mut hasher);@@ -6894,6 +7077,7 @@ impl App {task_id,phase_status,content_hash,+ hook_status,status,worktree_path,session_name,@@ -6914,17 +7098,41 @@ impl App {let mut phase = task_status.phase_status;if phase == PhaseStatus::Working {- // Idle detection: check if content hash has been stable for 15s- if let Some(hash) = task_status.content_hash {- let entry = self- .state- .pane_content_hashes- .entry(task_status.task_id.clone())- .or_insert((hash, now));- if entry.0 != hash {- *entry = (hash, now);- } else if now.duration_since(entry.1) >= std::time::Duration::from_secs(15) {+ match task_status.hook_status.as_ref().map(|h| h.state) {+ // The agent told us what it is doing β believe it, and drop+ // the pane history so a later fallback starts clean.+ Some(HookState::Working) => {+ self.state.pane_content_hashes.remove(&task_status.task_id);+ }+ Some(HookState::Blocked) => {+ phase = PhaseStatus::Blocked;+ self.state.pane_content_hashes.remove(&task_status.task_id);+ }+ // Turn ended with no artifact yet: what Idle has always meant.+ Some(HookState::Waiting) => {phase = PhaseStatus::Idle;+ self.state.pane_content_hashes.remove(&task_status.task_id);+ }+ Some(HookState::Ended) => {+ phase = PhaseStatus::Exited;+ self.state.pane_content_hashes.remove(&task_status.task_id);+ }+ // No hook report: unchanged 15s pane-hash heuristic.+ None => {+ if let Some(hash) = task_status.content_hash {+ let entry = self+ .state+ .pane_content_hashes+ .entry(task_status.task_id.clone())+ .or_insert((hash, now));+ if entry.0 != hash {+ *entry = (hash, now);+ } else if now.duration_since(entry.1)+ >= std::time::Duration::from_secs(15)+ {+ phase = PhaseStatus::Idle;+ }+ }}}} else if phase == PhaseStatus::Ready {@@ -6933,6 +7141,21 @@ impl App {self.state.pane_content_hashes.remove(&task_status.task_id);}+ // Keep the reason text alongside the status so the card and the+ // orchestrator notification can name what the agent is waiting for.+ match (phase, task_status.hook_status.as_ref()) {+ (PhaseStatus::Blocked, Some(h)) => {+ if let Some(msg) = h.message.clone() {+ self.state+ .blocked_reasons+ .insert(task_status.task_id.clone(), msg);+ }+ }+ _ => {+ self.state.blocked_reasons.remove(&task_status.task_id);+ }+ }+let newly_ready = phase == PhaseStatus::Ready && !task_status.was_ready;self.state.phase_status_cache@@ -7042,20 +7265,25 @@ impl App {if matches!(task_status.status,TaskStatus::Planning | TaskStatus::Running- ) && phase == PhaseStatus::Idle+ ) && matches!(phase, PhaseStatus::Idle | PhaseStatus::Blocked)&& self.state.orchestrator_session.is_some()&& should_send_stuck_notification(task_plugin){let stuck_key = format!("{}:{}", task_status.task_id, task_status.status.as_str());if !self.state.stuck_task_notified.contains(&stuck_key) {- // Track when this task first became Idle+ // Blocked is agent-reported: the agent has *said* it is+ // waiting on a human, so there is nothing to wait out. Idle is+ // still a guess from pane output, so it keeps its 1m settle.+ let blocked = phase == PhaseStatus::Blocked;let idle_since = self.state.stuck_task_idle_since.entry(task_status.task_id.clone()).or_insert(now);- if now.duration_since(*idle_since) >= std::time::Duration::from_secs(60) {+ if blocked+ || now.duration_since(*idle_since) >= std::time::Duration::from_secs(60)+ {self.state.stuck_task_notified.insert(stuck_key);if let Some(db) = &self.state.db {@@ -7072,18 +7300,34 @@ impl App {} else {&task_status.task_id};- let notif = crate::db::Notification::new(format!(- "Task \"{}\" ({}) has been idle for 1m in phase: {}",- task_title,- short_id,- task_status.status.as_str()- ));+ let reason = self.state.blocked_reasons.get(&task_status.task_id);+ let notif = crate::db::Notification::new(match (blocked, reason) {+ (true, Some(r)) => format!(+ "Task \"{}\" ({}) is blocked in phase {} waiting for: {}",+ task_title,+ short_id,+ task_status.status.as_str(),+ r+ ),+ (true, None) => format!(+ "Task \"{}\" ({}) is blocked in phase {} waiting for user input",+ task_title,+ short_id,+ task_status.status.as_str()+ ),+ _ => format!(+ "Task \"{}\" ({}) has been idle for 1m in phase: {}",+ task_title,+ short_id,+ task_status.status.as_str()+ ),+ });let _ = db.create_notification(¬if);}}}- } else if phase != PhaseStatus::Idle {- // Task is no longer idle β reset the idle-since timer+ } else if !matches!(phase, PhaseStatus::Idle | PhaseStatus::Blocked) {+ // Task is working again β reset the idle-since timerself.state.stuck_task_idle_since.remove(&task_status.task_id);@@ -7273,7 +7517,14 @@ fn recover_task_session(let resume_cmd = agent_ops.build_resume_command();- tmux_ops.create_window(session, window, worktree_path, Some(resume_cmd), true)?;+ tmux_ops.create_window(+ session,+ window,+ worktree_path,+ Some(resume_cmd),+ true,+ &agtx_task_env(&task.id, worktree_path),+ )?;Ok(target.clone())}@@ -7299,7 +7550,6 @@ fn copy_back_to_project(worktree: &Path, project_root: &Path, entries: &[String]}}-/// Generate a URL-safe slug from task ID and titlefn generate_task_slug(task_id: &str, title: &str) -> String {let title_slug: String = title@@ -7465,7 +7715,9 @@ fn setup_task_worktree(referenced_tasks: &[ReferencedTaskInfo],skip_init_scripts: bool,skip_worktree: bool,-) -> Result<String> {+ agent_hooks: bool,+ skill_cmd: Option<&str>,+) -> Result<(String, bool)> {let unique_slug = generate_task_slug(&task.id, &task.title);let window_name = format!("task-{}", unique_slug);let target = format!("{}:{}", tmux_project_name, window_name);@@ -7476,7 +7728,13 @@ fn setup_task_worktree(project_path.to_string_lossy().to_string()} else {// Create git worktree from the configured base branch- match git_ops.create_worktree(project_path, &unique_slug, base_branch, worktree_dir, branch_prefix) {+ match git_ops.create_worktree(+ project_path,+ &unique_slug,+ base_branch,+ worktree_dir,+ branch_prefix,+ ) {Ok(path) => path,Err(e) => {eprintln!("Failed to create worktree: {}", e);@@ -7526,7 +7784,13 @@ fn setup_task_worktree(// Write skills to worktree .agtx/skills/ and agent-native discovery paths// Deploy for all unique agents configured across phaseslet agent_refs: Vec<&str> = all_phase_agents.iter().map(|s| s.as_str()).collect();- write_skills_to_worktree(&worktree_path_str, project_path, plugin, &agent_refs);+ write_skills_to_worktree(+ &worktree_path_str,+ project_path,+ plugin,+ &agent_refs,+ agent_hooks,+ );// Copy referenced task artifacts into .agtx/references/if !referenced_tasks.is_empty() {@@ -7601,14 +7865,25 @@ fn setup_task_worktree(}}- // Build the interactive command. For agents with skill/command support,- // start with no prompt β the skill command and task content are sent via send_keys.- let has_skill_support =- resolve_skill_command(plugin, "planning", agent_name, "", task.cycle, &task.id).is_some();- let agent_cmd = if has_skill_support {- agent_ops.build_interactive_command("")+ // Hand the opening message to the agent process when it can take one. That+ // removes the send-after-ready race entirely for the first message: there is+ // no window in which a keystroke can be dropped, and nothing to poll for.+ // Agents without a verified launch form β or a task too large for argv β+ // fall back to the historical path (launch bare, wait for readiness, type).+ let launch_text = compose_launch_text(skill_cmd, prompt);+ let launched_with_prompt =+ agent::spec::can_launch_with_prompt(agent_ops.prompt_injection(), &launch_text);+ let agent_cmd = if launched_with_prompt {+ agent_ops.build_interactive_command(&launch_text)} else {- agent_ops.build_interactive_command(prompt)+ let has_skill_support =+ resolve_skill_command(plugin, "planning", agent_name, "", task.cycle, &task.id, true)+ .is_some();+ if has_skill_support {+ agent_ops.build_interactive_command("")+ } else {+ agent_ops.build_interactive_command(prompt)+ }};// Ensure project tmux session exists@@ -7627,13 +7902,14 @@ fn setup_task_worktree(&worktree_path_str,Some(agent_cmd),true,+ &agtx_task_env(&task.id, &worktree_path_str),)?;task.session_name = Some(target.clone());task.worktree_path = Some(worktree_path_str);task.branch_name = Some(format!("{}/{}", branch_prefix, unique_slug));- Ok(target)+ Ok((target, launched_with_prompt))}/// Delete task resources: kill tmux window, run cleanup script, remove worktree, delete branch@@ -7970,13 +8246,9 @@ fn send_key_to_tmux(_ => return,};- let key_str = if has_alt {- format!("M-{}", base)- } else {- base- };+ let key_str = if has_alt { format!("M-{}", base) } else { base };- let _ = tmux_ops.send_keys_literal(window_name, &key_str);+ let _ = tmux_ops.send_key(window_name, &key_str);}/// Parse ANSI escape sequences to ratatui Lines with colors@@ -8460,6 +8732,17 @@ fn resolve_prompt(/// Resolve the skill command to send via send_keys for a given phase./// Returns the plugin command transformed for the target agent, or None if no command is configured.+/// `collapse` controls how `{task}` is substituted.+///+/// `true` flattens the task to a single line, which the **typed** send path+/// needs: it delivers the command with `send_keys`, where an embedded newline is+/// a real Enter and would submit the message half-written.+///+/// `false` substitutes it verbatim. The **launch lane** passes the command in+/// argv, where newlines are just bytes, so a task keeps the paragraphs and lists+/// its author wrote β `spec-kit`'s `/speckit.specify {task}` and `openspec`'s+/// `/opsx:propose {task}` are the two bundled plugins this affects.+#[allow(clippy::too_many_arguments)]fn resolve_skill_command(plugin: &Option<WorkflowPlugin>,phase: &str,@@ -8467,6 +8750,7 @@ fn resolve_skill_command(task_content: &str,cycle: i32,task_id: &str,+ collapse: bool,) -> Option<String> {let p = plugin.as_ref()?;@@ -8495,14 +8779,17 @@ fn resolve_skill_command(if phase == "planning_with_research" || phase == "running_with_research_or_planning" {cmd.replace("{task}", "").trim().to_string()} else {- // Collapse task content to single line for commands (newlines β spaces)- let task_oneline = task_content- .lines()- .map(|l| l.trim())- .filter(|l| !l.is_empty())- .collect::<Vec<_>>()- .join(" ");- cmd.replace("{task}", &task_oneline)+ let task_text = if collapse {+ task_content+ .lines()+ .map(|l| l.trim())+ .filter(|l| !l.is_empty())+ .collect::<Vec<_>>()+ .join(" ")+ } else {+ task_content.to_string()+ };+ cmd.replace("{task}", &task_text)};let expanded = expanded.replace("{phase}", &cycle.to_string());let expanded = expanded.replace("{task_id}", task_id);@@ -8511,9 +8798,12 @@ fn resolve_skill_command(/// Spawn a background thread that optionally switches agent, waits for readiness,/// then sends a skill command and prompt to the tmux pane.+#[allow(clippy::too_many_arguments)]fn spawn_send_to_agent(tmux_ops: Arc<dyn TmuxOperations>,agent_registry: Arc<dyn agent::AgentRegistry>,+ task_id: String,+ agent_hooks: bool,target: String,current_agent: String,target_agent: String,@@ -8536,6 +8826,7 @@ fn spawn_send_to_agent(&target,agent_ops.as_ref(),worktree_path.as_deref(),+ &task_id,);}@@ -8556,13 +8847,20 @@ fn spawn_send_to_agent(}).unwrap_or(true); // no native path for this agent β nothing to deployif !already_deployed {- write_skills_to_worktree(wt_path, &project_path, &plugin, &[&target_agent]);+ write_skills_to_worktree(+ wt_path,+ &project_path,+ &plugin,+ &[&target_agent],+ agent_hooks,+ );}}let agent_ops = agent_registry.get(&target_agent);let new_cmd = agent_ops.build_interactive_command("");switch_agent_in_tmux(tmux_ops.as_ref(), &target, ¤t_agent, &new_cmd);- let _ = wait_for_agent_ready(&tmux_ops, &target);+ // The *new* agent is what has to become ready.+ let _ = wait_for_agent_ready(&tmux_ops, &target, Some(&target_agent));}let clear_context = plugin.as_ref()@@ -8582,6 +8880,139 @@ fn spawn_send_to_agent(});}+/// Attempts and per-attempt budget for [`deliver_message`].+///+/// Worst case is `DELIVERY_ATTEMPTS Γ (settle + confirm)` = 3 Γ (10s + 2s) = 36s,+/// because the settle runs *inside* the attempt loop β and the OpenCodePicker+/// path calls this twice, so ~72s. That only happens when the pane never goes+/// quiet and nothing ever lands, i.e. a session that is already broken; every+/// call site is a background thread, so it delays that task's send and nothing+/// else.+const DELIVERY_ATTEMPTS: u32 = 3;+const DELIVERY_CONFIRM_POLLS: u32 = 10; // x 200ms = 2s+/// Pane-settle budget before each attempt: 1s of quiet, given up on after 10s.+const SETTLE_STABLE_POLLS: u32 = 5;+const SETTLE_MAX_POLLS: u32 = 50;++/// Longest prefix of a message used to confirm it landed on a pane that never+/// went quiet. Short on purpose: a composer wraps and re-indents what it echoes,+/// so a long needle straddles a line break and reads as absent.+const DELIVERY_NEEDLE_CHARS: usize = 16;++/// Whitespace-collapsed prefix of `text`, or `None` when there is nothing+/// distinctive enough to look for.+fn delivery_needle(text: &str) -> Option<String> {+ let flat: String = text.split_whitespace().collect::<Vec<_>>().join(" ");+ let needle: String = flat.chars().take(DELIVERY_NEEDLE_CHARS).collect();+ (needle.chars().count() >= 4).then_some(needle)+}++/// Whether `needle` is visible in `pane`, comparing both whitespace-collapsed so+/// a wrap or re-indent in the composer does not hide it.+fn pane_shows(pane: &str, needle: &str) -> bool {+ let flat: String = pane.split_whitespace().collect::<Vec<_>>().join(" ");+ flat.contains(needle)+}++/// Wait for the pane to stop changing, up to [`SETTLE_MAX_POLLS`].+///+/// Returns whether it settled; callers proceed either way, since a pane that+/// never settles (a spinner, a clock) must not block the send forever.+fn wait_for_pane_settled(tmux_ops: &Arc<dyn TmuxOperations>, target: &str) -> bool {+ let mut last = String::new();+ let mut stable = 0u32;+ for _ in 0..SETTLE_MAX_POLLS {+ std::thread::sleep(std::time::Duration::from_millis(200));+ let now = tmux_ops.capture_pane(target).unwrap_or_default();+ if now == last {+ stable += 1;+ if stable >= SETTLE_STABLE_POLLS {+ return true;+ }+ } else {+ stable = 0;+ last = now;+ }+ }+ false+}++/// Put `text` into the agent's composer, resending while nothing lands.+///+/// An agent TUI that has not attached its stdin reader yet silently discards+/// what it is sent, and bracketed paste does not help: the discard happens in+/// the application, not in the pty. `wait_for_agent_ready` narrows that window+/// but cannot close it β it has no signal for an agent that reports its npm+/// wrapper in `pane_current_command` and declares no readiness indicator, so it+/// falls through to a timeout and sends into whatever is there.+///+/// Landing is judged by **the pane changing**, not by finding the text in it: a+/// composer wraps, re-indents and box-draws what it echoes, so any needle longer+/// than a few characters is unreliable. Conversely a resend only happens while+/// the pane is unchanged β the same rule [`dismiss_launch_dialog`] uses, and for+/// the same reason: a redraw means the first one landed, and resending would+/// double the message.+///+/// Returns whether the message was seen to land. Callers submit either way,+/// because a false negative (a pane that happened not to redraw) must not+/// swallow the task.+fn deliver_message(+ tmux_ops: &Arc<dyn TmuxOperations>,+ target: &str,+ text: &str,+ paste: bool,+) -> bool {+ let needle = delivery_needle(text);+ for attempt in 0..DELIVERY_ATTEMPTS {+ // Settle first, for two reasons. A composer that is still rendering the+ // previous turn may not take the message at all β a phase advance fires+ // as soon as the artifact appears, which can be while the agent is still+ // writing its closing lines. And a pane that is changing on its own makes+ // change-detection meaningless, because the change it sees would be the+ // agent's output rather than the echo of what was sent.+ let settled = wait_for_pane_settled(tmux_ops, target);++ // Clear the composer before a *resend* only. A resend happens because+ // nothing was seen to land, but "seen" is not "did not" β if the first+ // send did land and merely rendered late, appending a second copy gives+ // the agent the message twice, concatenated. Ctrl+U is best-effort: an+ // agent that does not map it to kill-line is no worse off than before+ // this guard, and the first send is never preceded by one, so a fresh+ // composer is never touched.+ if attempt > 0 {+ let _ = tmux_ops.send_key(target, "C-u");+ std::thread::sleep(std::time::Duration::from_millis(150));+ }++ let before = tmux_ops.capture_pane(target).unwrap_or_default();+ let _ = if paste {+ tmux_ops.paste_text(target, text)+ } else {+ tmux_ops.send_text(target, text)+ };+ for _ in 0..DELIVERY_CONFIRM_POLLS {+ std::thread::sleep(std::time::Duration::from_millis(200));+ let Ok(now) = tmux_ops.capture_pane(target) else {+ continue;+ };+ // On a pane that went quiet, any change is the echo. On one that+ // never did, a change proves nothing β it is the agent still+ // writing β so the text itself has to be found. Without that+ // distinction a busy pane confirms on its first poll every time,+ // which is precisely the case the settle step exists for.+ let landed = match (settled, needle.as_deref()) {+ (true, _) => now != before,+ (false, Some(n)) => pane_shows(&now, n),+ (false, None) => now != before,+ };+ if landed {+ return true;+ }+ }+ }+ false+}+/// Send skill command and prompt to the agent via tmux./// When there is no prompt_trigger, combines skill command + prompt into a single message/// (separated by a newline). When a prompt_trigger is set, sends them as two separate messages@@ -8597,11 +9028,12 @@ fn send_skill_and_prompt(auto_dismiss: &[crate::config::AutoDismiss],clear_context: bool,) {- // Opt-in context clear on phase advance. Only Claude Code has a known- // clear command; other agents are tbd per issue #46 and fall through- // to normal send unchanged.- if clear_context && agent_name == "claude" {- let _ = tmux_ops.send_keys(target, "/clear");+ // Opt-in context clear on phase advance. Agents with no known clear command+ // (`clear_context_command: None`, tbd per issue #46) fall through to a normal+ // send unchanged.+ let clear_cmd = agent::spec(agent_name).and_then(|s| s.clear_context_command);+ if let (true, Some(cmd)) = (clear_context, clear_cmd) {+ let _ = tmux_ops.send_keys(target, cmd);// Wait for Claude to clear its buffer and return to idle prompt.// Pattern mirrors the stability-poll loops used elsewhere in this// function: poll until pane content stabilises (no changes for ~1s),@@ -8631,7 +9063,9 @@ fn send_skill_and_prompt(//// Fix: send just the command name, wait for picker, Enter to confirm (inserts cmd),// then send the args (picker dismissed, input now has just the command), then Enter.- if agent_name == "opencode" {+ let strategy = agent::spec(agent_name).map_or(agent::SendStrategy::Generic, |s| s.send_strategy);++ if strategy == agent::SendStrategy::OpenCodePicker {// Build the full message: skill command (if any) + prompt (if any)let full_text = if let Some(cmd) = skill_cmd {if !prompt.is_empty() {@@ -8660,58 +9094,34 @@ fn send_skill_and_prompt(let rest = &full_text[first_line.len()..]; // rest of the message after first lineif cmd_name.starts_with('/') {- // Send just the command name to trigger the picker- let _ = tmux_ops.send_keys_literal(target, cmd_name);- // Wait for picker to appear (command name visible in pane)- for _ in 0..20 {- std::thread::sleep(std::time::Duration::from_millis(200));- if let Ok(content) = tmux_ops.capture_pane(target) {- if content.contains(cmd_name) {- break;- }- }- }+ // Send just the command name to trigger the picker. Typed,+ // not pasted β the picker opens on typing β so this is the+ // step most exposed to a TUI that is not reading stdin yet,+ // and losing it loses the whole message: the Enter below then+ // confirms nothing and the args are typed into an empty+ // composer. `deliver_message` resends while the pane is+ // unchanged.+ deliver_message(tmux_ops, target, cmd_name, false);std::thread::sleep(std::time::Duration::from_millis(200));// Enter confirms/inserts the command from picker- let _ = tmux_ops.send_keys_literal(target, "Enter");+ let _ = tmux_ops.send_key(target, "Enter");std::thread::sleep(std::time::Duration::from_millis(200));// Now send the args + any remaining prompt textlet remaining = format!("{}{}", cmd_args, rest);- let _ = tmux_ops.send_keys_literal(target, &remaining);- // Wait for args to appear in pane- let check = cmd_args.trim();- if !check.is_empty() {- for _ in 0..20 {- std::thread::sleep(std::time::Duration::from_millis(200));- if let Ok(content) = tmux_ops.capture_pane(target) {- if content.contains(check) {- break;- }- }- }- }+ deliver_message(tmux_ops, target, &remaining, false);std::thread::sleep(std::time::Duration::from_millis(200));- let _ = tmux_ops.send_keys_literal(target, "Enter");+ let _ = tmux_ops.send_key(target, "Enter");return;}}- // No args (or no slash command): simple send + wait for visibility + Enter- let _ = tmux_ops.send_keys_literal(target, &full_text);- let check_str = full_text.lines().next().unwrap_or(&full_text);- for _ in 0..20 {- std::thread::sleep(std::time::Duration::from_millis(200));- if let Ok(content) = tmux_ops.capture_pane(target) {- if content.contains(check_str) {- break;- }- }- }+ // No args (or no slash command): one send, confirmed, then Enter.+ deliver_message(tmux_ops, target, &full_text, false);std::thread::sleep(std::time::Duration::from_millis(200));// Enter to confirm picker (if any), then second Enter to submit- let _ = tmux_ops.send_keys_literal(target, "Enter");+ let _ = tmux_ops.send_key(target, "Enter");std::thread::sleep(std::time::Duration::from_millis(400));- let _ = tmux_ops.send_keys_literal(target, "Enter");+ let _ = tmux_ops.send_key(target, "Enter");}return;}@@ -8725,7 +9135,7 @@ fn send_skill_and_prompt(// Antigravity: descends from the Gemini CLI lineage (settings live under// ~/.gemini/), so it is treated as Ink-class and gets the same// wait-for-echo send. Not yet confirmed against a live session.- if matches!(agent_name, "gemini" | "codex" | "cursor" | "antigravity") {+ if strategy == agent::SendStrategy::Combined {let text_to_send = if let Some(cmd) = skill_cmd {if !prompt.is_empty() {Some(format!("{}\n\n{}", cmd, prompt))@@ -8749,37 +9159,38 @@ fn send_skill_and_prompt(};if let Some(text) = text_to_send {- let _ = tmux_ops.send_keys_literal(target, &text);- // Wait for text to appear in pane before sending Enter (Ink TUIs need time to render)- let check_str = text.lines().next().unwrap_or(&text);- for _ in 0..20 {- // up to 4s- std::thread::sleep(std::time::Duration::from_millis(200));- if let Ok(content) = tmux_ops.capture_pane(target) {- if content.contains(check_str) {- break;- }- }- }- std::thread::sleep(std::time::Duration::from_millis(200));- let _ = tmux_ops.send_keys_literal(target, "Enter");-- // Codex shows a command picker popup when a skill is typed.- // The first Enter confirms/closes the picker; a second Enter is needed- // to actually submit the message.- if agent_name == "codex" {- for _ in 0..20 {- // up to 4s- std::thread::sleep(std::time::Duration::from_millis(200));- if let Ok(content) = tmux_ops.capture_pane(target) {- if !content.contains("Press enter to insert") {- break;- }- }- }- std::thread::sleep(std::time::Duration::from_millis(200));- let _ = tmux_ops.send_keys_literal(target, "Enter");- }+ // Bracketed paste rather than typed keystrokes. Two reasons, both of+ // which the echo-poll this replaces was only working around:+ //+ // 1. It is atomic. `send-keys` streams characters into a TUI that may+ // not have attached its stdin reader yet, so the old code typed the+ // text and then polled `capture_pane` for up to 4s waiting for it to+ // render before daring to press Enter. A paste arrives as one write+ // wrapped in \x1b[200~ β¦ \x1b[201~, so there is no window to lose+ // keystrokes in and nothing to poll for.+ // 2. It keeps newlines as newlines. A skill command and its prompt are+ // joined by "\n\n", and `send-keys` delivers those as real Enter+ // presses β an Ink composer submits on the first one and the rest of+ // the message arrives as a second, truncated turn. Inside a bracketed+ // paste they are literal text.+ //+ // Atomic is not the same as delivered, though: an agent that has+ // not attached its stdin reader discards the paste whole, which is+ // how every antigravity task reached its composer empty. So the+ // paste goes through `deliver_message`, which resends while the pane+ // is unchanged, and only then is it submitted.+ deliver_message(tmux_ops, target, &text, true);+ std::thread::sleep(std::time::Duration::from_millis(150));+ let _ = tmux_ops.send_key(target, "Enter");++ // No second Enter for Codex any more. Its command picker ("Press enter+ // to insert") opens in response to *typing* a `$skill`, not to a paste,+ // so with bracketed paste there is no picker to dismiss and the first+ // Enter submits. Verified against codex-cli 0.144.5: pasting+ // "$agtx-plan <id>\n\n<task>" put both lines in the composer with the+ // newlines intact, no picker appeared, and a single Enter submitted β+ // the skill resolved and ran. A second Enter here would fire into an+ // already-empty composer.}return;}@@ -8859,7 +9270,8 @@ fn send_skill_and_prompt(.collect::<Vec<_>>().join(" ");if !oneline.is_empty() {- let _ = tmux_ops.send_keys_literal(target, &oneline);+ // Task-derived text: must not go through key-name lookup.+ let _ = tmux_ops.send_text(target, &oneline);}}}@@ -8917,7 +9329,7 @@ fn wait_for_prompt_trigger("Auto-dismiss rule triggered");for key in rule.response.split('\n') {- let _ = tmux_ops.send_keys_literal(target, key);+ let _ = tmux_ops.send_key(target, key);std::thread::sleep(std::time::Duration::from_millis(100));}stable_ticks = 0;@@ -9117,10 +9529,15 @@ fn collect_phase_agents(config: &MergedConfig) -> Vec<String> {/// can fire for them rather than Check 1 firing too early./// Note: on systems where agents are installed via asdf/nvm, all agents run as `node`/// and Check 1 never fires β AGENT_ACTIVE_INDICATORS is the only reliable signal there.-const AGENT_COMMANDS: &[&str] = &[- "claude", "codex", "gemini", "copilot", "opencode", "agent", "grok", "agy", "python3",- "python",-];+static AGENT_COMMANDS: std::sync::LazyLock<Vec<&'static str>> = std::sync::LazyLock::new(|| {+ agent::AGENT_SPECS+ .iter()+ .flat_map(|s| s.process_names.iter().copied())+ // Not agent binaries: a pane running a Python entry point (the swebench+ // harness) must not read as "back at the shell".+ .chain(["python3", "python"])+ .collect()+});/// Strings in pane content that indicate an agent TUI is active and ready./// Used by `is_agent_active` to detect agents like Gemini, Cursor and Grok that@@ -9128,15 +9545,19 @@ const AGENT_COMMANDS: &[&str] = &[/// (Grok is a native binary, but the npm package launches it through a wrapper,/// so the pane still reports `bash`.)/// Also used by `wait_for_agent_ready` (Check 2) to detect readiness for these agents.-const AGENT_ACTIVE_INDICATORS: &[&str] = &[- "Claude Code", // Claude- "Type your message", // Gemini- "Ask anything", // OpenCode- "Cursor Agent", // Cursor- "OpenAI Codex", // Codex- "Grok Build", // Grok β splash/footer- "Shift+Tab:mode", // Grok β session footer once a turn has run-];+/// Flattened across all agents deliberately: matching is done against any pane+/// regardless of which agent runs there. Attributing each string to its agent+/// would be strictly more correct β "Ask anything" matching in a Claude pane is a+/// false positive today β but that *changes behaviour*, so it belongs in its own+/// change with its own test rather than riding inside a refactor that is meant to+/// preserve it.+static AGENT_ACTIVE_INDICATORS: std::sync::LazyLock<Vec<&'static str>> =+ std::sync::LazyLock::new(|| {+ agent::AGENT_SPECS+ .iter()+ .flat_map(|s| s.active_indicators.iter().copied())+ .collect()+ });/// Check if the pane is running a shell (i.e. the agent has exited)./// Returns true when `pane_current_command` reports a shell (bash, zsh, sh, fish)@@ -9188,11 +9609,7 @@ fn kill_windows_by_name(tmux_ops: &dyn TmuxOperations, target: &str) -> bool {}/// Replay "completed phase" notifications for tasks whose artifact is on disk.-fn run_orchestrator_catchup(- db: &Database,- tasks: &[Task],- project_path: Option<&Path>,-) {+fn run_orchestrator_catchup(db: &Database, tasks: &[Task], project_path: Option<&Path>) {let existing: HashSet<String> = db.peek_notifications().unwrap_or_default()@@ -9235,7 +9652,7 @@ fn run_orchestrator_catchup(/// Check if an agent is actively running in the pane./// Uses both `pane_current_command` (works for Claude, Codex, Copilot) and/// pane content indicators (works for Gemini which runs inside bash).-fn is_agent_active(tmux_ops: &dyn TmuxOperations, target: &str) -> bool {+fn is_agent_active(tmux_ops: &dyn TmuxOperations, target: &str, agent_name: Option<&str>) -> bool {// Check 1: agent process visible in pane_current_commandif !is_pane_at_shell(tmux_ops, target) {return true;@@ -9248,7 +9665,7 @@ fn is_agent_active(tmux_ops: &dyn TmuxOperations, target: &str) -> bool {let bottom = lines.len().saturating_sub(5);let tail = &lines[bottom..];let tail_text = tail.join("\n");- if AGENT_ACTIVE_INDICATORS+ if active_indicators_for(agent_name).iter().any(|s| tail_text.contains(s)){@@ -9265,6 +9682,7 @@ fn ensure_window_or_recover(target: &str,agent_ops: &dyn AgentOperations,worktree_path: Option<&str>,+ task_id: &str,) {if !tmux_ops.window_exists(target).unwrap_or(true) {let Some(wt_path) = worktree_path else { return };@@ -9278,7 +9696,14 @@ fn ensure_window_or_recover(let _ = tmux_ops.create_session(session, wt_path);}let resume_cmd = agent_ops.build_resume_command();- let _ = tmux_ops.create_window(session, window, wt_path, Some(resume_cmd), true);+ let _ = tmux_ops.create_window(+ session,+ window,+ wt_path,+ Some(resume_cmd),+ true,+ &agtx_task_env(task_id, wt_path),+ );}}@@ -9301,20 +9726,16 @@ fn switch_agent_in_tmux(new_agent_cmd: &str,) {// 1. Send the graceful exit command for the current agent.- let exit_cmd = match current_agent {- "codex" => None, // Codex has no exit command β Ctrl+C is the only way- "gemini" => Some("/quit"),- "cursor" => None, // Ink/Node TUI β Ctrl+C is the only reliable exit- "grok" => Some("/quit"),- _ => Some("/exit"), // claude, opencode, and others- };+ // `None` means Ctrl+C is the only way out (codex, cursor). An agent agtx does+ // not know keeps the historical default of /exit.+ let exit_cmd = agent::spec(current_agent).map_or(Some("/exit"), |s| s.exit_command);if let Some(cmd) = exit_cmd {// For Gemini (Ink/Node TUI): send text first, wait for it to appear in pane,// then send Enter β same pattern as send_skill_and_prompt. Without this delay,// Enter fires before the Ink TUI has rendered the input, and /quit is lost.if current_agent == "gemini" {- let _ = tmux_ops.send_keys_literal(target, cmd);+ let _ = tmux_ops.send_text(target, cmd);for _ in 0..20 {std::thread::sleep(std::time::Duration::from_millis(200));if let Ok(content) = tmux_ops.capture_pane(target) {@@ -9324,12 +9745,12 @@ fn switch_agent_in_tmux(}}std::thread::sleep(std::time::Duration::from_millis(200));- let _ = tmux_ops.send_keys_literal(target, "Enter");+ let _ = tmux_ops.send_key(target, "Enter");} else {let _ = tmux_ops.send_keys(target, cmd);}} else {- let _ = tmux_ops.send_keys_literal(target, "C-c");+ let _ = tmux_ops.send_key(target, "C-c");}// 2. Poll for agent exit. If the agent was busy, the exit command@@ -9341,7 +9762,7 @@ fn switch_agent_in_tmux(for _ in 0..30 {// 3sstd::thread::sleep(std::time::Duration::from_millis(100));- if !is_agent_active(tmux_ops, target) {+ if !is_agent_active(tmux_ops, target, Some(current_agent)) {found_shell = true;break;}@@ -9349,12 +9770,12 @@ fn switch_agent_in_tmux(// 3. If still running, the agent was likely busy. Ctrl+C to cancel, then retry exit.if !found_shell {- let _ = tmux_ops.send_keys_literal(target, "C-c");+ let _ = tmux_ops.send_key(target, "C-c");std::thread::sleep(std::time::Duration::from_millis(1000));if let Some(cmd) = exit_cmd {if current_agent == "gemini" {- let _ = tmux_ops.send_keys_literal(target, cmd);+ let _ = tmux_ops.send_text(target, cmd);for _ in 0..20 {std::thread::sleep(std::time::Duration::from_millis(200));if let Ok(content) = tmux_ops.capture_pane(target) {@@ -9364,7 +9785,7 @@ fn switch_agent_in_tmux(}}std::thread::sleep(std::time::Duration::from_millis(200));- let _ = tmux_ops.send_keys_literal(target, "Enter");+ let _ = tmux_ops.send_key(target, "Enter");} else {let _ = tmux_ops.send_keys(target, cmd);}@@ -9374,7 +9795,7 @@ fn switch_agent_in_tmux(for _ in 0..50 {// 5sstd::thread::sleep(std::time::Duration::from_millis(100));- if !is_agent_active(tmux_ops, target) {+ if !is_agent_active(tmux_ops, target, Some(current_agent)) {found_shell = true;break;}@@ -9383,11 +9804,11 @@ fn switch_agent_in_tmux(// 4. Last resort: Ctrl+D to force exitif !found_shell {- let _ = tmux_ops.send_keys_literal(target, "C-d");+ let _ = tmux_ops.send_key(target, "C-d");for _ in 0..20 {// 2sstd::thread::sleep(std::time::Duration::from_millis(100));- if !is_agent_active(tmux_ops, target) {+ if !is_agent_active(tmux_ops, target, Some(current_agent)) {break;}}@@ -9431,7 +9852,161 @@ fn switch_agent_in_tmux(/// 3s of no pane content changes = agent has finished loading its TUI.const CONTENT_STABLE_THRESHOLD: u32 = 3;-fn wait_for_agent_ready(tmux_ops: &Arc<dyn TmuxOperations>, target: &str) -> Option<String> {+/// Known first-launch dialogs that block an agent before it accepts any input,+/// paired with the keystroke that answers them.+///+/// A worktree is a brand-new directory every time, so these fire on most task+/// starts β they are the normal case, not an edge case.+/// Every agent's `Launch`-scope dialog, flattened.+///+/// Flat because `wait_for_agent_ready` is handed only a tmux target and does not+/// know which agent runs there. Attributing these at match time is strictly more+/// correct but *changes behaviour*, so it gets its own change. `Session`-scope+/// dialogs are excluded: they are matched against their own agent only, by the+/// refresh loop.+static LAUNCH_DIALOGS: std::sync::LazyLock<Vec<&'static agent::AgentDialog>> =+ std::sync::LazyLock::new(|| {+ agent::AGENT_SPECS+ .iter()+ .flat_map(|s| s.dialogs.iter())+ .filter(|d| d.scope == agent::DialogScope::Launch)+ .collect()+ });++/// The launch dialogs to match in a pane running `agent_name`.+///+/// Attributed when the agent is known, so one agent's prompt is never answered in+/// another's pane β answering sends a menu digit, and a stray "2" typed into a+/// live composer is a real corruption. Falls back to every agent's dialogs for an+/// agent agtx has no spec for, which is the historical behaviour and better than+/// leaving such a pane blocked forever.+fn launch_dialogs_for(agent_name: Option<&str>) -> Vec<&'static agent::AgentDialog> {+ match agent_name.and_then(agent::spec) {+ Some(spec) => spec+ .dialogs+ .iter()+ .filter(|d| d.scope == agent::DialogScope::Launch)+ .collect(),+ None => LAUNCH_DIALOGS.clone(),+ }+}++/// The readiness indicators to look for in a pane running `agent_name`.+///+/// Same reasoning: "Ask anything" appearing in a Claude pane used to read as+/// OpenCode being ready. Unknown agents keep the flat list.+fn active_indicators_for(agent_name: Option<&str>) -> Vec<&'static str> {+ match agent_name.and_then(agent::spec) {+ Some(spec) => spec.active_indicators.to_vec(),+ None => AGENT_ACTIVE_INDICATORS.clone(),+ }+}++/// Per-launch state for [`dismiss_launch_dialog`].+#[derive(Default)]+struct LaunchDialogState {+ /// Answers sent per dialog, and a hash of the pane at the last attempt.+ /// Indexed by position in [`LAUNCH_DIALOGS`], so it grows with the table+ /// rather than needing a hand-maintained size.+ attempts: Vec<(u8, u64)>,+}++/// An agent TUI that has not yet started reading stdin drops the keystrokes, so+/// a single attempt is not enough on a slow machine.+///+/// Sized to span the whole readiness budget (30 polls in step 1 + 30 in the+/// settle loop, one per second), because that is how long the agent has to+/// become ready. An earlier value of 5 exhausted itself in the first five+/// seconds of an emulated swebench container β every answer was dropped, and+/// Claude sat on the bypass warning for the rest of the run. The cap is only a+/// backstop against a pattern that matches something which is not a dialog;+/// the real guard is that a retry requires an unchanged pane.+const LAUNCH_DIALOG_MAX_ATTEMPTS: u8 = 60;++fn hash_of(content: &str) -> u64 {+ use std::hash::{Hash, Hasher};+ let mut h = std::collections::hash_map::DefaultHasher::new();+ content.hash(&mut h);+ h.finish()+}++/// Answer any `Session`-scope dialog this agent shows, visible in `content`.+///+/// Unlike the launch dialogs these are matched **only** against their own agent,+/// because the caller knows which agent occupies the pane and these prompts can+/// appear at any point in a session rather than once at startup.+fn answer_session_dialogs(+ tmux_ops: &Arc<dyn TmuxOperations>,+ target: &str,+ agent_name: &str,+ content: &str,+) {+ let Some(spec) = agent::spec(agent_name) else {+ return;+ };+ for dialog in spec+ .dialogs+ .iter()+ .filter(|d| d.scope == agent::DialogScope::Session)+ {+ if dialog.matches(content) {+ for key in dialog.answer {+ let _ = tmux_ops.send_key(target, key);+ std::thread::sleep(std::time::Duration::from_millis(100));+ }+ }+ }+}++/// Answer any known first-launch dialog visible in `content`.+///+/// Retries only while **nothing has changed** since the last attempt: an+/// unchanged pane means the keystrokes were dropped, whereas any redraw means+/// they landed and resending would type a stray "2" into the agent's live+/// composer. Capped at [`LAUNCH_DIALOG_MAX_ATTEMPTS`] so a pattern that matches+/// something which is not really a dialog cannot hammer the pane forever.+///+/// Returns true when an answer was sent.+fn dismiss_launch_dialog(+ tmux_ops: &Arc<dyn TmuxOperations>,+ target: &str,+ agent_name: Option<&str>,+ content: &str,+ state: &mut LaunchDialogState,+) -> bool {+ let dialogs = launch_dialogs_for(agent_name);+ let content_hash = hash_of(content);+ if state.attempts.len() < dialogs.len() {+ state.attempts.resize(dialogs.len(), (0, 0));+ }+ for (i, dialog) in dialogs.iter().enumerate() {+ if !dialog.matches(content) {+ continue;+ }+ let (attempts, last_hash) = state.attempts[i];+ if attempts >= LAUNCH_DIALOG_MAX_ATTEMPTS {+ continue;+ }+ // The pane redrew since the last answer β it landed; the lingering text+ // is just the previous frame. Do not send into a live composer.+ if attempts > 0 && last_hash != content_hash {+ continue;+ }+ for key in dialog.answer {+ let _ = tmux_ops.send_key(target, key);+ std::thread::sleep(std::time::Duration::from_millis(200));+ }+ state.attempts[i] = (attempts + 1, content_hash);+ return true;+ }+ false+}++fn wait_for_agent_ready(+ tmux_ops: &Arc<dyn TmuxOperations>,+ target: &str,+ agent_name: Option<&str>,+) -> Option<String> {// Step 1: detect the ready signal (up to 30s).// Three detection methods, whichever fires first:// 1. Agent process detected via pane_current_command (Claude, Codex, Copilot)@@ -9440,43 +10015,44 @@ fn wait_for_agent_ready(tmux_ops: &Arc<dyn TmuxOperations>, target: &str) -> Optlet mut last_content = String::new();let mut stable_ticks: u32 = 0;let mut change_count: u32 = 0;+ // Shared with the settle loop below so attempt counts carry across both.+ let mut dialog_state = LaunchDialogState::default();for _ in 0..30 {// 30s (30 * 1s)std::thread::sleep(std::time::Duration::from_secs(1));- // Check 1: agent process detected via pane_current_command- if !is_pane_at_shell(tmux_ops.as_ref(), target) {- break;- }-- // Check 2 & 3: pane content checks- if let Ok(content) = tmux_ops.capture_pane(target) {- // Handle Claude bypass prompt immediately- if content.contains("Yes, I accept") || content.contains("I accept the risk") {- let _ = tmux_ops.send_keys_literal(target, "2");- std::thread::sleep(std::time::Duration::from_millis(50));- let _ = tmux_ops.send_keys_literal(target, "Enter");- // Fall through to settle wait below- break;- }-- // Handle Gemini trust dialog β auto-trust the folder so MCP servers- // and skills are loaded. After answering, Gemini restarts; reset- // stabilization counters so we wait for the new instance to be ready.- if content.contains("Do you trust the files in this folder?") {- let _ = tmux_ops.send_keys_literal(target, "1");- std::thread::sleep(std::time::Duration::from_millis(50));- let _ = tmux_ops.send_keys_literal(target, "Enter");- // Reset stabilization β Gemini will restart and we must wait again+ // A blocking dialog is checked BEFORE anything that can break out of this+ // loop. A native-binary agent (claude, grok) changes+ // `pane_current_command` to its own name the moment it execs β before it+ // has rendered anything β so Check 1 used to win this race and leave the+ // dialog standing, with the task prompt then typed into the menu.+ let content = tmux_ops.capture_pane(target).ok();+ if let Some(ref c) = content {+ if dismiss_launch_dialog(tmux_ops, target, agent_name, c, &mut dialog_state) {+ // Keep looping rather than breaking: the answer may have been+ // dropped by a TUI that was not reading stdin yet, and the+ // readiness checks below would otherwise run against a pane+ // that is still showing the dialog.last_content = String::new();stable_ticks = 0;change_count = 0;continue;}+ }+ // Check 1: agent process detected via pane_current_command+ if !is_pane_at_shell(tmux_ops.as_ref(), target) {+ break;+ }++ // Check 2 & 3: pane content checks+ if let Some(content) = content {// Check 2: known ready indicator in pane content- if AGENT_ACTIVE_INDICATORS.iter().any(|s| content.contains(s)) {+ if active_indicators_for(agent_name)+ .iter()+ .any(|s| content.contains(s))+ {break;}@@ -9506,6 +10082,15 @@ fn wait_for_agent_ready(tmux_ops: &Arc<dyn TmuxOperations>, target: &str) -> Opt// 30s hard timeoutstd::thread::sleep(std::time::Duration::from_secs(1));if let Ok(content) = tmux_ops.capture_pane(target) {+ // The dialog can render *after* the process is detectable, so it must+ // be watched for here too β this is the case that actually bit in a+ // swebench container: claude exec'd, Check 1 broke out of step 1, and+ // the warning appeared only once we were already in this loop.+ if dismiss_launch_dialog(tmux_ops, target, agent_name, &content, &mut dialog_state) {+ last_content = String::new();+ stable_ticks = 0;+ continue;+ }if content != last_content {stable_ticks = 0;last_content = content;@@ -9588,11 +10173,195 @@ fn agent_trust_home() -> Option<PathBuf> {/// Write skill files to a worktree's .agtx/skills/ directory and agent-native discovery paths./// `agent_names` determines which native paths to use (e.g. `.claude/commands/agtx/` for Claude)./// When multiple agents are configured for different phases, skills are deployed for all of them.+/// Build the `hooks` block for a worktree's `.claude/settings.local.json`.+///+/// Every registered event invokes `agtx hook <task-id> <worktree>`, which writes+/// the agent's own view of its state to `.agtx/status/{task_id}.json`. Event+/// names were verified against Claude Code 2.1.241; unregistered names are+/// ignored by older builds, so listing one Claude does not know is harmless.+fn claude_hook_settings(agtx_bin: &str) -> serde_json::Value {+ // Task-agnostic on purpose: the hook reads AGTX_TASK_ID / AGTX_WORKTREE from+ // the window env. Baking the task id in here would break `skip_worktree`,+ // where every task shares one settings file and the last deploy would+ // re-point every other task's agent at its own status file.+ let command = format!("{} hook --env claude", agtx_bin);+ let entry = |matcher: Option<&str>| {+ let mut e = serde_json::json!({+ "hooks": [{ "type": "command", "command": command }]+ });+ if let (Some(m), Some(obj)) = (matcher, e.as_object_mut()) {+ obj.insert("matcher".to_string(), serde_json::json!(m));+ }+ serde_json::json!([e])+ };+ serde_json::json!({+ // Liveness: a turn started, or a tool is about to run (heartbeat).+ "SessionStart": entry(None),+ "UserPromptSubmit": entry(None),+ "PreToolUse": entry(Some("*")),+ // Blocked: the agent is stopped waiting on a human.+ "PermissionRequest": entry(Some("*")),+ "Notification": entry(None),+ // Turn over / session over.+ "Stop": entry(None),+ "StopFailure": entry(None),+ "SessionEnd": entry(None),+ })+}++/// Re-deploy agent configs for worktrees that were set up by a different agtx+/// binary.+///+/// The hook command and every MCP config embed an absolute path from+/// `current_exe()`. After `cargo install`, a Homebrew upgrade, or a `cargo clean`+/// following a debug-build session, those paths dangle: hooks stop reporting (the+/// board silently falls back to the pane heuristic) and the task's MCP server+/// stops resolving. Neither failure is visible.+///+/// Runs on a background thread at startup and rewrites only worktrees whose+/// marker disagrees with the running binary.+fn refresh_stale_worktree_configs(+ stale_candidates: Vec<(String, Option<String>)>,+ project_path: PathBuf,+ agent_names: Vec<String>,+ agent_hooks: bool,+) {+ let Ok(current_bin) = std::env::current_exe() else {+ return;+ };+ let current_bin = current_bin.to_string_lossy().to_string();++ std::thread::spawn(move || {+ let mut plugin_cache: HashMap<Option<String>, Option<WorkflowPlugin>> = HashMap::new();+ let refs: Vec<&str> = agent_names.iter().map(|s| s.as_str()).collect();++ for (worktree, plugin_name) in stale_candidates {+ let wt = Path::new(&worktree);+ if !wt.exists() {+ continue;+ }+ // A missing marker means the worktree predates the marker itself, so+ // its paths cannot be verified β redeploy to be sure.+ if read_deploy_marker(wt).as_deref() == Some(current_bin.as_str()) {+ continue;+ }+ let plugin = plugin_cache+ .entry(plugin_name.clone())+ .or_insert_with(|| match &plugin_name {+ Some(name) => WorkflowPlugin::load(name, Some(project_path.as_path()))+ .ok()+ .or_else(|| skills::load_bundled_plugin(name)),+ None => skills::load_bundled_plugin("agtx"),+ })+ .clone();++ tracing::info!(+ worktree = %worktree,+ "Re-deploying agent configs: worktree was set up by a different agtx binary"+ );+ write_skills_to_worktree(&worktree, &project_path, &plugin, &refs, agent_hooks);+ }+ });+}++/// True when a hook command is one agtx wrote, regardless of where the binary+/// lived at the time. See `merge_claude_hooks`.+fn is_agtx_hook_command(command: &str) -> bool {+ command.contains(" hook --env")+}++/// Records which agtx binary deployed a worktree's agent configs.+///+/// The absolute path from `current_exe()` is baked into the hook command and+/// every MCP config, so moving or reinstalling agtx silently breaks both for+/// worktrees deployed earlier. This marker makes the mismatch detectable in O(1)+/// per task instead of parsing seven different config formats.+const DEPLOY_MARKER: &str = ".agtx/deployed-by";++fn read_deploy_marker(worktree: &Path) -> Option<String> {+ std::fs::read_to_string(worktree.join(DEPLOY_MARKER))+ .ok()+ .map(|s| s.trim().to_string())+}++/// Compose the opening message handed to an agent at launch: the phase skill+/// command followed by the task prompt.+///+/// Same text `send_skill_and_prompt` builds for the combined-send agents, but+/// given to the process instead of typed at it.+fn compose_launch_text(skill_cmd: Option<&str>, prompt: &str) -> String {+ match (skill_cmd, prompt.trim().is_empty()) {+ (Some(cmd), false) => format!("{}\n\n{}", cmd, prompt),+ (Some(cmd), true) => cmd.to_string(),+ (None, false) => prompt.to_string(),+ (None, true) => String::new(),+ }+}++/// Environment identifying which task a tmux window belongs to.+///+/// Set on the window (tmux `-e`) so the agent β and any hook it spawns β+/// inherits it. Agent hooks are registered once with a task-agnostic command and+/// read these to know what they are reporting about, which is what lets several+/// tasks share one `.claude/settings.local.json` under `skip_worktree`.+fn agtx_task_env(task_id: &str, worktree: &str) -> Vec<(String, String)> {+ vec![+ ("AGTX_TASK_ID".to_string(), task_id.to_string()),+ ("AGTX_WORKTREE".to_string(), worktree.to_string()),+ ]+}++/// Merge agtx's hook entries into an existing `hooks` object, preserving the+/// user's own entries on the same events.+///+/// agtx's previous entries (identified by the agtx binary path in the command,+/// the same way orca matches on its managed script filename) are dropped first,+/// so re-running against an existing worktree replaces them rather than+/// accumulating duplicates that would fire the hook N times per event.+fn merge_claude_hooks(+ settings: &mut serde_json::Map<String, serde_json::Value>,+ ours: serde_json::Value,+) {+ // Match on the invocation, not the binary path: the path changes when agtx is+ // moved or reinstalled, and a prefix match would then stop recognising our own+ // entries β leaving the stale one behind and appending a duplicate.+ let is_ours = |def: &serde_json::Value| -> bool {+ def["hooks"].as_array().is_some_and(|hooks| {+ hooks+ .iter()+ .any(|h| h["command"].as_str().is_some_and(is_agtx_hook_command))+ })+ };++ let existing = settings+ .get("hooks")+ .and_then(|h| h.as_object())+ .cloned()+ .unwrap_or_default();+ let mut merged = existing.clone();++ if let Some(ours) = ours.as_object() {+ for (event, our_defs) in ours {+ let mut defs: Vec<serde_json::Value> = existing+ .get(event)+ .and_then(|d| d.as_array())+ .map(|a| a.iter().filter(|d| !is_ours(d)).cloned().collect())+ .unwrap_or_default();+ if let Some(arr) = our_defs.as_array() {+ defs.extend(arr.iter().cloned());+ }+ merged.insert(event.clone(), serde_json::Value::Array(defs));+ }+ }+ settings.insert("hooks".to_string(), serde_json::Value::Object(merged));+}+fn write_skills_to_worktree(worktree_path: &str,project_path: &Path,plugin: &Option<WorkflowPlugin>,agent_names: &[&str],+ agent_hooks: bool,) {let agtx_dir = Path::new(worktree_path).join(".agtx");let _ = std::fs::create_dir_all(&agtx_dir);@@ -9637,156 +10406,27 @@ fn write_skills_to_worktree(.to_string_lossy().to_string();let project_path_str = project_path.to_string_lossy().to_string();+ // Marker for the startup drift check; see DEPLOY_MARKER.+ let _ = std::fs::write(Path::new(worktree_path).join(DEPLOY_MARKER), &agtx_bin);for agent_name in agent_names {- match *agent_name {- "claude" => {- let cfg = serde_json::json!({- "mcpServers": {- "agtx": { "command": agtx_bin, "args": ["mcp-serve", &project_path_str] }- }- });- let _ = std::fs::write(- Path::new(worktree_path).join(".mcp.json"),- serde_json::to_string_pretty(&cfg).unwrap_or_default(),- );- // Pre-trust the agtx MCP server so Claude doesn't show an interactive- // trust dialog when the agent window opens for the first time.- let settings = serde_json::json!({ "enableAllProjectMcpServers": true });- let claude_dir = Path::new(worktree_path).join(".claude");- let _ = std::fs::create_dir_all(&claude_dir);- let _ = std::fs::write(- claude_dir.join("settings.local.json"),- serde_json::to_string_pretty(&settings).unwrap_or_default(),- );- }- "codex" => {- let toml = format!(- "[mcp_servers.agtx]\ncommand = \"{}\"\nargs = [\"mcp-serve\", \"{}\"]\n",- agtx_bin, project_path_str- );- let dir = Path::new(worktree_path).join(".codex");- let _ = std::fs::create_dir_all(&dir);- let _ = std::fs::write(dir.join("config.toml"), toml);-- // Codex only loads project-local .codex/config.toml for trusted paths.- // Add a trust entry for this worktree to ~/.codex/config.toml.- if let Some(home) = agent_trust_home() {- let global_config_path = home.join(".codex").join("config.toml");- let trust_entry = format!(- "\n[projects.\"{}\"]\ntrust_level = \"trusted\"\n",- worktree_path- );- let existing = std::fs::read_to_string(&global_config_path).unwrap_or_default();- if !existing.contains(worktree_path) {- let _ = std::fs::OpenOptions::new()- .create(true)- .append(true)- .open(&global_config_path)- .and_then(|mut f| {- use std::io::Write;- f.write_all(trust_entry.as_bytes())- });- }- }- }- "gemini" => {- let cfg = serde_json::json!({- "mcpServers": {- "agtx": { "command": agtx_bin, "args": ["mcp-serve", &project_path_str], "trust": true }- }- });- let dir = Path::new(worktree_path).join(".gemini");- let _ = std::fs::create_dir_all(&dir);- let _ = std::fs::write(- dir.join("settings.json"),- serde_json::to_string_pretty(&cfg).unwrap_or_default(),- );- }- "cursor" => {- let cfg = serde_json::json!({- "mcpServers": {- "agtx": { "command": agtx_bin, "args": ["mcp-serve", &project_path_str] }- }- });- let dir = Path::new(worktree_path).join(".cursor");- let _ = std::fs::create_dir_all(&dir);- let _ = std::fs::write(- dir.join("mcp.json"),- serde_json::to_string_pretty(&cfg).unwrap_or_default(),- );- }- "grok" => {- // Grok reads project-scoped MCP servers from .grok/config.toml (TOML, not JSON),- // walking from the worktree up to the git root.- let esc = |v: &str| v.replace('\\', "\\\\").replace('"', "\\\"");- let cfg = format!(- "[mcp_servers.agtx]\ncommand = \"{}\"\nargs = [\"mcp-serve\", \"{}\"]\n",- esc(&agtx_bin),- esc(&project_path_str)- );- let dir = Path::new(worktree_path).join(".grok");- let _ = std::fs::create_dir_all(&dir);- // A repo may already ship a .grok/config.toml β append the agtx table- // instead of clobbering the project's own settings.- let path = dir.join("config.toml");- let existing = std::fs::read_to_string(&path).unwrap_or_default();- if !existing.contains("[mcp_servers.agtx]") {- let merged = if existing.trim().is_empty() {- cfg- } else {- format!("{}\n\n{}", existing.trim_end(), cfg)- };- let _ = std::fs::write(&path, merged);- }- }- "antigravity" => {- // Antigravity reads workspace MCP servers from .agents/mcp_config.json- // (JSON, `mcpServers`). `.agents/` is vendor-neutral and may already be- // tracked in the repo, so merge the agtx entry into any existing file- // instead of clobbering the project's own servers.- let dir = Path::new(worktree_path).join(".agents");- let _ = std::fs::create_dir_all(&dir);- let path = dir.join("mcp_config.json");- let mut root = std::fs::read_to_string(&path)- .ok()- .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())- .filter(|v| v.is_object())- .unwrap_or_else(|| serde_json::json!({}));- if !root["mcpServers"].is_object() {- root["mcpServers"] = serde_json::json!({});- }- root["mcpServers"]["agtx"] = serde_json::json!({- "command": &agtx_bin,- "args": ["mcp-serve", &project_path_str]- });- let _ = std::fs::write(- &path,- serde_json::to_string_pretty(&root).unwrap_or_default(),- );-- }- "opencode" => {- let cfg = serde_json::json!({- "mcp": {- "agtx": {- "type": "local",- "command": [&agtx_bin, "mcp-serve", &project_path_str]- }- }- });- let _ = std::fs::write(- Path::new(worktree_path).join("opencode.json"),- serde_json::to_string_pretty(&cfg).unwrap_or_default(),- );- }- _ => {}+ if let Some(spec) = agent::spec(agent_name) {+ write_mcp_config(+ spec,+ worktree_path,+ &project_path_str,+ &agtx_bin,+ agent_hooks,+ );}}// Write to agent-native discovery paths (e.g. .claude/commands/agtx/)// Deploy for all configured agents so skills are available across phase transitionsfor agent_name in agent_names {- if let Some((base_dir, namespace)) = skills::agent_native_skill_dir(agent_name) {+ let Some(spec) = agent::spec(agent_name) else {+ continue;+ };+ if let Some((base_dir, namespace)) = spec.skill_dir {let native_dir = if namespace.is_empty() {Path::new(worktree_path).join(base_dir)} else {@@ -9797,37 +10437,249 @@ fn write_skills_to_worktree(for (skill_dir_name, default_content) in skills::BUILTIN_SKILLS {let content =resolve_skill_content(plugin, skill_dir_name, project_path, default_content);+ write_skill_file(spec, skill_dir_name, &content, &native_dir);+ }+ }+ }+}- match *agent_name {- "gemini" => {- // Gemini uses .toml command files with description + prompt fields- let description = skills::extract_description(&content)- .unwrap_or_else(|| format!("agtx {} phase skill", skill_dir_name));- let toml_content = skills::skill_to_gemini_toml(&description, &content);- let filename = skills::skill_dir_to_filename(skill_dir_name, agent_name);- let _ = std::fs::write(native_dir.join(&filename), toml_content);- }- "codex" | "cursor" | "grok" | "antigravity" => {- // Codex/Cursor/Grok/Antigravity use SKILL.md in skill-name/ subdirectories- let skill_subdir = native_dir.join(skill_dir_name);- let _ = std::fs::create_dir_all(&skill_subdir);- let _ = std::fs::write(skill_subdir.join("SKILL.md"), &content);- }- "opencode" => {- // OpenCode uses flat .md command files: .opencode/command/agtx-research.md- // Commands have description frontmatter + prompt template- let oc_content = transform_skill_for_opencode(&content);- let filename = skills::skill_dir_to_filename(skill_dir_name, agent_name);- let _ = std::fs::write(native_dir.join(&filename), oc_content);- }- _ => {- // Claude and others: .md files with transformed frontmatter- let content = transform_skill_frontmatter(&content);- let filename = skills::skill_dir_to_filename(skill_dir_name, agent_name);- let _ = std::fs::write(native_dir.join(&filename), content);- }+/// Write the project-scoped MCP server config for one agent into its worktree.+///+/// Selected by [`McpConfigKind`](agent::McpConfigKind) rather than agent name.+/// The variants are genuinely seven, not one parameterised writer: the formats+/// differ (JSON vs TOML, `mcpServers` vs `mcp_servers` vs `mcp`), two must+/// **merge** rather than overwrite because their file may already be tracked in+/// the repo, and two carry a side-effect beyond the config file itself β so the+/// `β¦Merge` names mark where clobbering a user's file is the failure mode.+///+/// `project_path_str` is the *project root*, not the worktree, so the server+/// opens the project DB where tasks actually live.+fn write_mcp_config(+ spec: &agent::AgentSpec,+ worktree_path: &str,+ project_path_str: &str,+ agtx_bin: &str,+ agent_hooks: bool,+) {+ let Some(kind) = spec.mcp_config else {+ return;+ };+ match kind {+ agent::McpConfigKind::ClaudeJson => {+ let cfg = serde_json::json!({+ "mcpServers": {+ "agtx": { "command": agtx_bin, "args": ["mcp-serve", &project_path_str] }+ }+ });+ let _ = std::fs::write(+ Path::new(worktree_path).join(".mcp.json"),+ serde_json::to_string_pretty(&cfg).unwrap_or_default(),+ );+ // Merge into any existing settings rather than replacing them:+ // `.claude` is in AGENT_CONFIG_DIRS, so a project that ships its own+ // settings.local.json has it copied into every worktree, and a plain+ // write would silently drop the user's permissions/env/hooks.+ // Same merge-don't-overwrite rule the grok and antigravity writers follow.+ let claude_dir = Path::new(worktree_path).join(".claude");+ let _ = std::fs::create_dir_all(&claude_dir);+ let settings_path = claude_dir.join("settings.local.json");+ let mut settings = std::fs::read_to_string(&settings_path)+ .ok()+ .and_then(|raw| serde_json::from_str::<serde_json::Value>(&raw).ok())+ .filter(|v| v.is_object())+ .unwrap_or_else(|| serde_json::json!({}));++ if let Some(obj) = settings.as_object_mut() {+ // Pre-trust the agtx MCP server so Claude doesn't show an interactive+ // trust dialog when the agent window opens for the first time.+ obj.insert(+ "enableAllProjectMcpServers".to_string(),+ serde_json::json!(true),+ );+ // agtx always launches Claude with --dangerously-skip-permissions, and+ // since Claude Code ~2.1 that mode is gated behind an interactive+ // "Yes, I accept" dialog. A worktree is a brand-new directory every+ // time, so without this the agent parks on that dialog and the task+ // prompt is typed into the menu. (IS_SANDBOX=1 covers only the+ // separate root-user check, not this one.)+ obj.insert(+ "bypassPermissionsModeAccepted".to_string(),+ serde_json::json!(true),+ );+ if agent_hooks {+ merge_claude_hooks(+ obj,+ claude_hook_settings(&agtx_bin),+ );}}+ let _ = std::fs::write(+ &settings_path,+ serde_json::to_string_pretty(&settings).unwrap_or_default(),+ );+ }+ agent::McpConfigKind::CodexToml => {+ let toml = format!(+ "[mcp_servers.agtx]\ncommand = \"{}\"\nargs = [\"mcp-serve\", \"{}\"]\n",+ agtx_bin, project_path_str+ );+ let dir = Path::new(worktree_path).join(".codex");+ let _ = std::fs::create_dir_all(&dir);+ let _ = std::fs::write(dir.join("config.toml"), toml);++ // Codex only loads project-local .codex/config.toml for trusted paths.+ // Add a trust entry for this worktree to ~/.codex/config.toml.+ if let Some(home) = agent_trust_home() {+ let global_config_path = home.join(".codex").join("config.toml");+ let trust_entry = format!(+ "\n[projects.\"{}\"]\ntrust_level = \"trusted\"\n",+ worktree_path+ );+ let existing = std::fs::read_to_string(&global_config_path).unwrap_or_default();+ if !existing.contains(worktree_path) {+ let _ = std::fs::OpenOptions::new()+ .create(true)+ .append(true)+ .open(&global_config_path)+ .and_then(|mut f| {+ use std::io::Write;+ f.write_all(trust_entry.as_bytes())+ });+ }+ }+ }+ agent::McpConfigKind::GeminiJson => {+ let cfg = serde_json::json!({+ "mcpServers": {+ "agtx": { "command": agtx_bin, "args": ["mcp-serve", &project_path_str], "trust": true }+ }+ });+ let dir = Path::new(worktree_path).join(".gemini");+ let _ = std::fs::create_dir_all(&dir);+ let _ = std::fs::write(+ dir.join("settings.json"),+ serde_json::to_string_pretty(&cfg).unwrap_or_default(),+ );+ }+ agent::McpConfigKind::CursorJson => {+ let cfg = serde_json::json!({+ "mcpServers": {+ "agtx": { "command": agtx_bin, "args": ["mcp-serve", &project_path_str] }+ }+ });+ let dir = Path::new(worktree_path).join(".cursor");+ let _ = std::fs::create_dir_all(&dir);+ let _ = std::fs::write(+ dir.join("mcp.json"),+ serde_json::to_string_pretty(&cfg).unwrap_or_default(),+ );+ }+ agent::McpConfigKind::GrokTomlMerge => {+ // Grok reads project-scoped MCP servers from .grok/config.toml (TOML, not JSON),+ // walking from the worktree up to the git root.+ let esc = |v: &str| v.replace('\\', "\\\\").replace('"', "\\\"");+ let cfg = format!(+ "[mcp_servers.agtx]\ncommand = \"{}\"\nargs = [\"mcp-serve\", \"{}\"]\n",+ esc(&agtx_bin),+ esc(&project_path_str)+ );+ let dir = Path::new(worktree_path).join(".grok");+ let _ = std::fs::create_dir_all(&dir);+ // A repo may already ship a .grok/config.toml β append the agtx table+ // instead of clobbering the project's own settings.+ let path = dir.join("config.toml");+ let existing = std::fs::read_to_string(&path).unwrap_or_default();+ if !existing.contains("[mcp_servers.agtx]") {+ let merged = if existing.trim().is_empty() {+ cfg+ } else {+ format!("{}\n\n{}", existing.trim_end(), cfg)+ };+ let _ = std::fs::write(&path, merged);+ }+ }+ agent::McpConfigKind::AntigravityJsonMerge => {+ // Antigravity reads workspace MCP servers from .agents/mcp_config.json+ // (JSON, `mcpServers`). `.agents/` is vendor-neutral and may already be+ // tracked in the repo, so merge the agtx entry into any existing file+ // instead of clobbering the project's own servers.+ let dir = Path::new(worktree_path).join(".agents");+ let _ = std::fs::create_dir_all(&dir);+ let path = dir.join("mcp_config.json");+ let mut root = std::fs::read_to_string(&path)+ .ok()+ .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())+ .filter(|v| v.is_object())+ .unwrap_or_else(|| serde_json::json!({}));+ if !root["mcpServers"].is_object() {+ root["mcpServers"] = serde_json::json!({});+ }+ root["mcpServers"]["agtx"] = serde_json::json!({+ "command": &agtx_bin,+ "args": ["mcp-serve", &project_path_str]+ });+ let _ = std::fs::write(+ &path,+ serde_json::to_string_pretty(&root).unwrap_or_default(),+ );+ }+ agent::McpConfigKind::OpenCode => {+ let cfg = serde_json::json!({+ "mcp": {+ "agtx": {+ "type": "local",+ "command": [&agtx_bin, "mcp-serve", &project_path_str]+ }+ }+ });+ let _ = std::fs::write(+ Path::new(worktree_path).join("opencode.json"),+ serde_json::to_string_pretty(&cfg).unwrap_or_default(),+ );+ }+ }+}++/// Write one skill into an agent's native discovery directory, in that agent's+/// layout.+///+/// `native_dir` is the already-created base directory (plus namespace subdir if+/// the agent uses one). Selected by [`SkillLayout`] rather than by agent name, so+/// an agent reusing an existing layout needs no code here.+///+/// This is the single implementation behind both [`deploy_skill`] and+/// [`write_skills_to_worktree`], which each carried their own copy of this branch+/// and had already drifted: the latter treated Claude's format as its `_`+/// fallback, so a future agent with a skill dir but no arm would silently get+/// Claude's `.md` layout from one and nothing from the other.+fn write_skill_file(+ spec: &agent::AgentSpec,+ skill_name: &str,+ content: &str,+ native_dir: &Path,+) {+ match spec.skill_layout {+ agent::SkillLayout::CommandFile => {+ let transformed = transform_skill_frontmatter(content);+ let filename = skills::skill_dir_to_filename(skill_name, spec.name);+ let _ = std::fs::write(native_dir.join(&filename), transformed);+ }+ agent::SkillLayout::GeminiToml => {+ let description = skills::extract_description(content)+ .unwrap_or_else(|| format!("agtx {} skill", skill_name));+ let toml_content = skills::skill_to_gemini_toml(&description, content);+ let filename = skills::skill_dir_to_filename(skill_name, spec.name);+ let _ = std::fs::write(native_dir.join(&filename), toml_content);+ }+ agent::SkillLayout::SkillDir => {+ let skill_subdir = native_dir.join(skill_name);+ let _ = std::fs::create_dir_all(&skill_subdir);+ let _ = std::fs::write(skill_subdir.join("SKILL.md"), content);+ }+ agent::SkillLayout::OpenCodeFlat => {+ let oc_content = transform_skill_for_opencode(content);+ let filename = skills::skill_dir_to_filename(skill_name, spec.name);+ let _ = std::fs::write(native_dir.join(&filename), oc_content);}}}@@ -9841,39 +10693,17 @@ fn deploy_skill(target_dir: &Path, skill_name: &str, content: &str, agent_name:let _ = std::fs::write(canonical_dir.join("SKILL.md"), content);// Write to agent-native discovery path- if let Some((base_dir, namespace)) = skills::agent_native_skill_dir(agent_name) {+ let Some(spec) = agent::spec(agent_name) else {+ return;+ };+ if let Some((base_dir, namespace)) = spec.skill_dir {let native_dir = if namespace.is_empty() {target_dir.join(base_dir)} else {target_dir.join(base_dir).join(namespace)};let _ = std::fs::create_dir_all(&native_dir);-- match agent_name {- "claude" | "copilot" => {- let transformed = transform_skill_frontmatter(content);- let filename = skills::skill_dir_to_filename(skill_name, agent_name);- let _ = std::fs::write(native_dir.join(&filename), transformed);- }- "gemini" => {- let description = skills::extract_description(content)- .unwrap_or_else(|| format!("agtx {} skill", skill_name));- let toml_content = skills::skill_to_gemini_toml(&description, content);- let filename = skills::skill_dir_to_filename(skill_name, agent_name);- let _ = std::fs::write(native_dir.join(&filename), toml_content);- }- "codex" | "cursor" | "grok" | "antigravity" => {- let skill_subdir = native_dir.join(skill_name);- let _ = std::fs::create_dir_all(&skill_subdir);- let _ = std::fs::write(skill_subdir.join("SKILL.md"), content);- }- "opencode" => {- let oc_content = transform_skill_for_opencode(content);- let filename = skills::skill_dir_to_filename(skill_name, agent_name);- let _ = std::fs::write(native_dir.join(&filename), oc_content);- }- _ => {}- }+ write_skill_file(spec, skill_name, content, &native_dir);}}diff --git a/src/tui/app_tests.rs b/src/tui/app_tests.rsindex 9e42e9c..1c8a478 100644--- a/src/tui/app_tests.rs+++ b/src/tui/app_tests.rs@@ -15,6 +15,9 @@ use crate::tmux::MockTmuxOperations;fn test_generate_pr_description_with_diff_and_agent() {let mut mock_git = MockGitOperations::new();let mut mock_agent = MockAgentOperations::new();+ mock_agent+ .expect_prompt_injection()+ .returning(|| crate::agent::PromptInjection::Unknown);// Setup: git returns a diff statmock_git@@ -77,6 +80,9 @@ fn test_generate_pr_description_without_worktree() {fn test_generate_pr_description_with_empty_diff() {let mut mock_git = MockGitOperations::new();let mut mock_agent = MockAgentOperations::new();+ mock_agent+ .expect_prompt_injection()+ .returning(|| crate::agent::PromptInjection::Unknown);// Git returns empty diff (no changes from main)mock_git@@ -107,6 +113,9 @@ fn test_generate_pr_description_with_empty_diff() {fn test_generate_pr_description_agent_failure() {let mut mock_git = MockGitOperations::new();let mut mock_agent = MockAgentOperations::new();+ mock_agent+ .expect_prompt_injection()+ .returning(|| crate::agent::PromptInjection::Unknown);mock_git.expect_diff_stat_from_main()@@ -191,6 +200,9 @@ fn test_create_pr_with_content_success() {let mut mock_git = MockGitOperations::new();let mut mock_git_provider = MockGitProviderOperations::new();let mut mock_agent = MockAgentOperations::new();+ mock_agent+ .expect_prompt_injection()+ .returning(|| crate::agent::PromptInjection::Unknown);let task = Task {id: "test-123".to_string(),@@ -255,13 +267,15 @@ fn test_create_pr_with_content_success() {// Expect: create PRmock_git_provider.expect_create_pr()- .withf(|path: &Path, title: &str, body: &str, branch: &str, base: &Option<String>| {- path == Path::new("/project")- && title == "Test PR"- && body == "Test body"- && branch == "feature/test"- && base.is_none()- })+ .withf(+ |path: &Path, title: &str, body: &str, branch: &str, base: &Option<String>| {+ path == Path::new("/project")+ && title == "Test PR"+ && body == "Test body"+ && branch == "feature/test"+ && base.is_none()+ },+ ).times(1).returning(|_, _, _, _, _| Ok((42, "https://github.com/org/repo/pull/42".to_string())));@@ -343,6 +357,9 @@ fn test_create_pr_with_content_push_failure() {let mut mock_git = MockGitOperations::new();let mock_git_provider = MockGitProviderOperations::new();let mut mock_agent = MockAgentOperations::new();+ mock_agent+ .expect_prompt_injection()+ .returning(|| crate::agent::PromptInjection::Unknown);let task = Task {id: "test-123".to_string(),@@ -404,6 +421,9 @@ fn test_create_pr_with_content_push_failure() {fn test_push_changes_to_existing_pr_success() {let mut mock_git = MockGitOperations::new();let mut mock_agent = MockAgentOperations::new();+ mock_agent+ .expect_prompt_injection()+ .returning(|| crate::agent::PromptInjection::Unknown);let task = Task {id: "test-456".to_string(),@@ -689,7 +709,7 @@ fn test_send_key_to_tmux_char() {let mut mock_tmux = MockTmuxOperations::new();mock_tmux- .expect_send_keys_literal()+ .expect_send_key().with(mockall::predicate::eq("test-window"),mockall::predicate::eq("a"),@@ -711,7 +731,7 @@ fn test_send_key_to_tmux_enter() {let mut mock_tmux = MockTmuxOperations::new();mock_tmux- .expect_send_keys_literal()+ .expect_send_key().with(mockall::predicate::eq("test-window"),mockall::predicate::eq("Enter"),@@ -734,7 +754,7 @@ fn test_send_key_to_tmux_special_keys() {// Test Escapemock_tmux- .expect_send_keys_literal()+ .expect_send_key().with(mockall::predicate::eq("win"),mockall::predicate::eq("Escape"),@@ -750,7 +770,7 @@ fn test_send_key_to_tmux_special_keys() {// Test Backspacelet mut mock_tmux2 = MockTmuxOperations::new();mock_tmux2- .expect_send_keys_literal()+ .expect_send_key().with(mockall::predicate::eq("win"),mockall::predicate::eq("BSpace"),@@ -771,7 +791,7 @@ fn test_send_key_to_tmux_function_key() {let mut mock_tmux = MockTmuxOperations::new();mock_tmux- .expect_send_keys_literal()+ .expect_send_key().with(mockall::predicate::eq("win"), mockall::predicate::eq("F5")).returning(|_, _| Ok(()));@@ -788,8 +808,11 @@ fn test_send_key_to_tmux_function_key() {fn test_send_key_to_tmux_alt_arrow_keys() {let mut mock_tmux = MockTmuxOperations::new();mock_tmux- .expect_send_keys_literal()- .with(mockall::predicate::eq("win"), mockall::predicate::eq("M-Left"))+ .expect_send_key()+ .with(+ mockall::predicate::eq("win"),+ mockall::predicate::eq("M-Left"),+ ).times(1).returning(|_, _| Ok(()));@@ -801,8 +824,11 @@ fn test_send_key_to_tmux_alt_arrow_keys() {let mut mock_tmux2 = MockTmuxOperations::new();mock_tmux2- .expect_send_keys_literal()- .with(mockall::predicate::eq("win"), mockall::predicate::eq("M-Right"))+ .expect_send_key()+ .with(+ mockall::predicate::eq("win"),+ mockall::predicate::eq("M-Right"),+ ).times(1).returning(|_, _| Ok(()));@@ -819,7 +845,7 @@ fn test_send_key_to_tmux_alt_arrow_keys() {fn test_send_key_to_tmux_alt_b_f() {let mut mock_tmux = MockTmuxOperations::new();mock_tmux- .expect_send_keys_literal()+ .expect_send_key().with(mockall::predicate::eq("win"), mockall::predicate::eq("M-b")).times(1).returning(|_, _| Ok(()));@@ -832,7 +858,7 @@ fn test_send_key_to_tmux_alt_b_f() {let mut mock_tmux2 = MockTmuxOperations::new();mock_tmux2- .expect_send_keys_literal()+ .expect_send_key().with(mockall::predicate::eq("win"), mockall::predicate::eq("M-f")).times(1).returning(|_, _| Ok(()));@@ -1088,13 +1114,7 @@ fn test_delete_task_resources_full_cleanup() {task.worktree_path = Some("/tmp/worktree".to_string());task.branch_name = Some("task/abc-feature".to_string());- delete_task_resources(- &task,- None,- Path::new("/project"),- &mock_tmux,- &mock_git,- );+ delete_task_resources(&task, None, Path::new("/project"), &mock_tmux, &mock_git);}/// Test delete_task_resources handles task without resources@@ -1110,13 +1130,7 @@ fn test_delete_task_resources_no_resources() {let task = Task::new("Simple task", "claude", "project-1");// No session_name, worktree_path, or branch_name- delete_task_resources(- &task,- None,- Path::new("/project"),- &mock_tmux,- &mock_git,- );+ delete_task_resources(&task, None, Path::new("/project"), &mock_tmux, &mock_git);}// =============================================================================@@ -1441,12 +1455,20 @@ fn test_footer_text_fullscreen_on_enter_hides_ctrl_f() {// Columns 1-3 should hide [C-f] when fullscreen_on_enter is truefor col in 1..=3 {let text = build_footer_text(InputMode::Normal, false, col, false, true);- assert!(!text.contains("[C-f]"), "Column {} should hide [C-f] when fullscreen_on_enter=true", col);+ assert!(+ !text.contains("[C-f]"),+ "Column {} should hide [C-f] when fullscreen_on_enter=true",+ col+ );}// And show it when falsefor col in 1..=3 {let text = build_footer_text(InputMode::Normal, false, col, false, false);- assert!(text.contains("[C-f]"), "Column {} should show [C-f] when fullscreen_on_enter=false", col);+ assert!(+ text.contains("[C-f]"),+ "Column {} should show [C-f] when fullscreen_on_enter=false",+ col+ );}}@@ -1502,6 +1524,9 @@ fn test_setup_task_worktree_success() {let mut mock_tmux = MockTmuxOperations::new();let mut mock_git = MockGitOperations::new();let mut mock_agent = MockAgentOperations::new();+ mock_agent+ .expect_prompt_injection()+ .returning(|| crate::agent::PromptInjection::Unknown);// Expect worktree creationmock_git@@ -1523,7 +1548,7 @@ fn test_setup_task_worktree_success() {mock_tmux.expect_create_window()- .returning(|_, _, _, _, _| Ok(()));+ .returning(|_, _, _, _, _, _| Ok(()));let mut task = Task::new("Add login feature", "claude", "project-1");task.status = TaskStatus::Backlog;@@ -1547,10 +1572,12 @@ fn test_setup_task_worktree_success() {&[],false,false,+ false,+ None,);assert!(result.is_ok());- let target = result.unwrap();+ let (target, _launched) = result.unwrap();assert!(target.starts_with("my-project:task-"));assert!(task.session_name.is_some());assert!(task.worktree_path.is_some());@@ -1567,6 +1594,9 @@ fn test_setup_task_worktree_sets_task_fields() {let mut mock_tmux = MockTmuxOperations::new();let mut mock_git = MockGitOperations::new();let mut mock_agent = MockAgentOperations::new();+ mock_agent+ .expect_prompt_injection()+ .returning(|| crate::agent::PromptInjection::Unknown);mock_git.expect_create_worktree()@@ -1580,7 +1610,7 @@ fn test_setup_task_worktree_sets_task_fields() {mock_tmux.expect_has_session().returning(|_| true);mock_tmux.expect_create_window()- .returning(|_, _, _, _, _| Ok(()));+ .returning(|_, _, _, _, _, _| Ok(()));let mut task = Task::new("Fix bug", "claude", "project-1");@@ -1603,8 +1633,11 @@ fn test_setup_task_worktree_sets_task_fields() {&[],false,false,+ false,+ None,).unwrap();+ let (target, _launched) = target;// session_name should be the returned targetassert_eq!(task.session_name.as_ref().unwrap(), &target);@@ -1615,7 +1648,13 @@ fn test_setup_task_worktree_sets_task_fields() {.unwrap().contains(".agtx/worktrees/"));// branch_name should be {prefix}/{slug}- let slug = task.branch_name.as_ref().unwrap().rsplit_once('/').unwrap().1;+ let slug = task+ .branch_name+ .as_ref()+ .unwrap()+ .rsplit_once('/')+ .unwrap()+ .1;assert!(task.worktree_path.as_ref().unwrap().ends_with(slug));}@@ -1628,6 +1667,9 @@ fn test_setup_task_worktree_worktree_creation_fails() {let mut mock_tmux = MockTmuxOperations::new();let mut mock_git = MockGitOperations::new();let mut mock_agent = MockAgentOperations::new();+ mock_agent+ .expect_prompt_injection()+ .returning(|| crate::agent::PromptInjection::Unknown);// Worktree creation failsmock_git@@ -1644,7 +1686,7 @@ fn test_setup_task_worktree_worktree_creation_fails() {mock_tmux.expect_has_session().returning(|_| true);mock_tmux.expect_create_window()- .returning(|_, _, _, _, _| Ok(()));+ .returning(|_, _, _, _, _, _| Ok(()));let mut task = Task::new("Test task", "claude", "project-1");@@ -1667,6 +1709,8 @@ fn test_setup_task_worktree_worktree_creation_fails() {&[],false,false,+ false,+ None,);// Should succeed despite worktree creation failure (uses fallback path)@@ -1688,6 +1732,9 @@ fn test_setup_task_worktree_tmux_window_fails() {let mut mock_tmux = MockTmuxOperations::new();let mut mock_git = MockGitOperations::new();let mut mock_agent = MockAgentOperations::new();+ mock_agent+ .expect_prompt_injection()+ .returning(|| crate::agent::PromptInjection::Unknown);mock_git.expect_create_worktree()@@ -1703,7 +1750,7 @@ fn test_setup_task_worktree_tmux_window_fails() {// Tmux window creation failsmock_tmux.expect_create_window()- .returning(|_, _, _, _, _| Err(anyhow::anyhow!("tmux not running")));+ .returning(|_, _, _, _, _, _| Err(anyhow::anyhow!("tmux not running")));let mut task = Task::new("Test task", "claude", "project-1");@@ -1726,6 +1773,8 @@ fn test_setup_task_worktree_tmux_window_fails() {&[],false,false,+ false,+ None,);// Should propagate the error@@ -1742,6 +1791,9 @@ fn test_setup_task_worktree_creates_session_when_missing() {let mut mock_tmux = MockTmuxOperations::new();let mut mock_git = MockGitOperations::new();let mut mock_agent = MockAgentOperations::new();+ mock_agent+ .expect_prompt_injection()+ .returning(|| crate::agent::PromptInjection::Unknown);mock_git.expect_create_worktree()@@ -1758,7 +1810,7 @@ fn test_setup_task_worktree_creates_session_when_missing() {mock_tmux.expect_create_session().returning(|_, _| Ok(()));mock_tmux.expect_create_window()- .returning(|_, _, _, _, _| Ok(()));+ .returning(|_, _, _, _, _, _| Ok(()));let mut task = Task::new("New task", "claude", "project-1");@@ -1781,6 +1833,8 @@ fn test_setup_task_worktree_creates_session_when_missing() {&[],false,false,+ false,+ None,);assert!(result.is_ok());@@ -1795,6 +1849,9 @@ fn test_setup_task_worktree_passes_init_config() {let mut mock_tmux = MockTmuxOperations::new();let mut mock_git = MockGitOperations::new();let mut mock_agent = MockAgentOperations::new();+ mock_agent+ .expect_prompt_injection()+ .returning(|| crate::agent::PromptInjection::Unknown);mock_git.expect_create_worktree()@@ -1816,7 +1873,7 @@ fn test_setup_task_worktree_passes_init_config() {mock_tmux.expect_has_session().returning(|_| true);mock_tmux.expect_create_window()- .returning(|_, _, _, _, _| Ok(()));+ .returning(|_, _, _, _, _, _| Ok(()));let mut task = Task::new("Task with config", "claude", "project-1");@@ -1839,6 +1896,8 @@ fn test_setup_task_worktree_passes_init_config() {&[],false,false,+ false,+ None,);assert!(result.is_ok());@@ -2151,23 +2210,23 @@ fn test_enumerate_available_skills_opencode() {fn test_resolve_skill_command_no_plugin() {// No plugin: no commands, returns None for all agents/phasesassert_eq!(- resolve_skill_command(&None, "planning", "claude", "", 1, ""),+ resolve_skill_command(&None, "planning", "claude", "", 1, "", true),None);assert_eq!(- resolve_skill_command(&None, "running", "codex", "", 1, ""),+ resolve_skill_command(&None, "running", "codex", "", 1, "", true),None);assert_eq!(- resolve_skill_command(&None, "review", "gemini", "", 1, ""),+ resolve_skill_command(&None, "review", "gemini", "", 1, "", true),None);assert_eq!(- resolve_skill_command(&None, "planning", "opencode", "", 1, ""),+ resolve_skill_command(&None, "planning", "opencode", "", 1, "", true),None);assert_eq!(- resolve_skill_command(&None, "planning", "copilot", "", 1, ""),+ resolve_skill_command(&None, "planning", "copilot", "", 1, "", true),None);}@@ -2201,42 +2260,42 @@ fn test_resolve_skill_command_with_plugin() {});// Claude/Gemini: canonical form unchangedassert_eq!(- resolve_skill_command(&plugin, "planning", "claude", "", 1, ""),+ resolve_skill_command(&plugin, "planning", "claude", "", 1, "", true),Some("/gsd:plan-phase 1".to_string()));assert_eq!(- resolve_skill_command(&plugin, "running", "claude", "", 1, ""),+ resolve_skill_command(&plugin, "running", "claude", "", 1, "", true),Some("/gsd:execute-phase 1".to_string()));assert_eq!(- resolve_skill_command(&plugin, "review", "gemini", "", 1, ""),+ resolve_skill_command(&plugin, "review", "gemini", "", 1, "", true),Some("/gsd:verify-work 1".to_string()));assert_eq!(- resolve_skill_command(&plugin, "research", "claude", "", 1, ""),+ resolve_skill_command(&plugin, "research", "claude", "", 1, "", true),Some("/gsd:discuss-phase 1".to_string()));// OpenCode: colon β hyphenassert_eq!(- resolve_skill_command(&plugin, "planning", "opencode", "", 1, ""),+ resolve_skill_command(&plugin, "planning", "opencode", "", 1, "", true),Some("/gsd-plan-phase 1".to_string()));assert_eq!(- resolve_skill_command(&plugin, "research", "opencode", "", 1, ""),+ resolve_skill_command(&plugin, "research", "opencode", "", 1, "", true),Some("/gsd-discuss-phase 1".to_string()));// Codex: slash β dollar, colon β hyphenassert_eq!(- resolve_skill_command(&plugin, "planning", "codex", "", 1, ""),+ resolve_skill_command(&plugin, "planning", "codex", "", 1, "", true),Some("$gsd-plan-phase 1".to_string()));assert_eq!(- resolve_skill_command(&plugin, "running", "codex", "", 1, ""),+ resolve_skill_command(&plugin, "running", "codex", "", 1, "", true),Some("$gsd-execute-phase 1".to_string()));// Unsupported agents: None (will use file-path fallback in prompt)assert_eq!(- resolve_skill_command(&plugin, "planning", "copilot", "", 1, ""),+ resolve_skill_command(&plugin, "planning", "copilot", "", 1, "", true),None);}@@ -2578,7 +2637,7 @@ fn test_resolve_skill_command_research_phase() {[artifacts]"#;let plugin: WorkflowPlugin = toml::from_str(plugin_toml).unwrap();- let cmd = resolve_skill_command(&Some(plugin), "research", "claude", "", 1, "");+ let cmd = resolve_skill_command(&Some(plugin), "research", "claude", "", 1, "", true);assert_eq!(cmd, Some("/gsd:new-project".to_string()));}@@ -2597,7 +2656,7 @@ fn test_resolve_skill_command_planning_with_plugin() {[artifacts]"#;let plugin: WorkflowPlugin = toml::from_str(plugin_toml).unwrap();- let cmd = resolve_skill_command(&Some(plugin), "planning", "claude", "", 1, "");+ let cmd = resolve_skill_command(&Some(plugin), "planning", "claude", "", 1, "", true);assert_eq!(cmd, Some("/gsd:plan-phase 1".to_string()));}@@ -3095,7 +3154,7 @@ fn test_switch_agent_claude_sends_exit() {}Ok(())});- mock.expect_send_keys_literal().returning(|_, _| Ok(()));+ mock.expect_send_key().returning(|_, _| Ok(()));// Return shell immediately so polling exits fastmock.expect_pane_current_command().returning(|_| Some("bash".to_string()));@@ -3123,8 +3182,10 @@ fn test_switch_agent_gemini_sends_quit() {let quit_sent_c = quit_sent.clone();mock.expect_send_keys().returning(|_, _| Ok(()));- // Gemini /quit is sent via send_keys_literal (needs delay before Enter for Ink TUI)- mock.expect_send_keys_literal().returning(move |_, k| {+ mock.expect_send_key().returning(|_, _| Ok(()));+ // Gemini's /quit is *text*, sent via send_text (`send-keys -l`) with a delay+ // before the separate Enter keypress, which the Ink TUI needs to render first.+ mock.expect_send_text().returning(move |_, k| {if k == "/quit" {quit_sent_c.store(true, Ordering::SeqCst);}@@ -3152,7 +3213,7 @@ fn test_switch_agent_codex_sends_ctrl_c() {let ctrl_c_sent_c = ctrl_c_sent.clone();mock.expect_send_keys().returning(|_, _| Ok(()));- mock.expect_send_keys_literal().returning(move |_, k| {+ mock.expect_send_key().returning(move |_, k| {if k == "C-c" {ctrl_c_sent_c.store(true, Ordering::SeqCst);}@@ -3173,6 +3234,67 @@ fn test_switch_agent_codex_sends_ctrl_c() {// Tests for cyclic phase support and {phase} substitution// =============================================================================+/// The launch lane passes the command in argv, where a newline is just a byte,+/// so `{task}` keeps the structure its author wrote. The typed path cannot: it+/// sends with `send_keys`, where a newline is a real Enter that would submit the+/// message half-written.+#[test]+fn test_resolve_skill_command_collapse_controls_task_structure() {+ use crate::config::WorkflowPlugin;+ let plugin: WorkflowPlugin = toml::from_str(+ r#"+ name = "spec-kit"+ [commands]+ planning = "/speckit.specify {task}"+ [prompts]+ [artifacts]+ "#,+ )+ .unwrap();+ let plugin = Some(plugin);+ let task = "Add a login form.\n\n- email field\n- password field";++ let collapsed =+ resolve_skill_command(&plugin, "planning", "claude", task, 1, "id-1", true).unwrap();+ assert_eq!(+ collapsed,+ "/speckit.specify Add a login form. - email field - password field",+ "typed path must stay on one line"+ );+ assert!(!collapsed.contains('\n'));++ let verbatim =+ resolve_skill_command(&plugin, "planning", "claude", task, 1, "id-1", false).unwrap();+ assert_eq!(verbatim, format!("/speckit.specify {task}"));+ assert!(+ verbatim.contains("\n\n- email field"),+ "launch lane must preserve blank lines and list structure: {verbatim:?}"+ );+}++/// Collapsing is only about `{task}`; a command without the placeholder is+/// identical either way.+#[test]+fn test_resolve_skill_command_collapse_is_a_noop_without_task_placeholder() {+ use crate::config::WorkflowPlugin;+ let plugin: WorkflowPlugin = toml::from_str(+ r#"+ name = "agtx"+ [commands]+ planning = "/agtx:plan {task_id}"+ [prompts]+ [artifacts]+ "#,+ )+ .unwrap();+ let plugin = Some(plugin);+ let task = "line one\nline two";+ assert_eq!(+ resolve_skill_command(&plugin, "planning", "claude", task, 1, "id-1", true),+ resolve_skill_command(&plugin, "planning", "claude", task, 1, "id-1", false),+ );+}+#[test]fn test_resolve_skill_command_phase_substitution() {use crate::config::{PluginCommands, WorkflowPlugin};@@ -3193,35 +3315,35 @@ fn test_resolve_skill_command_phase_substitution() {// Cycle 1: {phase} β "1"assert_eq!(- resolve_skill_command(&p, "planning", "claude", "", 1, ""),+ resolve_skill_command(&p, "planning", "claude", "", 1, "", true),Some("/gsd:plan-phase 1".to_string()));assert_eq!(- resolve_skill_command(&p, "running", "claude", "", 1, ""),+ resolve_skill_command(&p, "running", "claude", "", 1, "", true),Some("/gsd:execute-phase 1".to_string()));assert_eq!(- resolve_skill_command(&p, "review", "claude", "", 1, ""),+ resolve_skill_command(&p, "review", "claude", "", 1, "", true),Some("/gsd:verify-work 1".to_string()));// Cycle 2: {phase} β "2"assert_eq!(- resolve_skill_command(&p, "planning", "claude", "", 2, ""),+ resolve_skill_command(&p, "planning", "claude", "", 2, "", true),Some("/gsd:plan-phase 2".to_string()));assert_eq!(- resolve_skill_command(&p, "running", "claude", "", 2, ""),+ resolve_skill_command(&p, "running", "claude", "", 2, "", true),Some("/gsd:execute-phase 2".to_string()));assert_eq!(- resolve_skill_command(&p, "review", "claude", "", 2, ""),+ resolve_skill_command(&p, "review", "claude", "", 2, "", true),Some("/gsd:verify-work 2".to_string()));// preresearch also gets {phase} substitution (falls back to research command)assert_eq!(- resolve_skill_command(&p, "preresearch", "claude", "", 1, ""),+ resolve_skill_command(&p, "preresearch", "claude", "", 1, "", true),Some("/gsd:new-project".to_string()));}@@ -3357,7 +3479,7 @@ fn test_resolve_skill_command_preresearch_fallback() {let plugin: WorkflowPlugin = toml::from_str(plugin_toml).unwrap();let p = Some(plugin);assert_eq!(- resolve_skill_command(&p, "preresearch", "claude", "", 1, ""),+ resolve_skill_command(&p, "preresearch", "claude", "", 1, "", true),Some("/test:discuss".to_string()));}@@ -3415,6 +3537,252 @@ fn test_gsd_plugin_has_cyclic_and_copy_back() {// Tests for send_skill_and_prompt// =============================================================================+/// A message the agent's TUI never echoed was dropped, not delayed β that is+/// what a pane unchanged across the whole confirm budget means. Resending is the+/// only recovery: `wait_for_agent_ready` cannot prove an Ink-class TUI has+/// attached its stdin reader, and a dropped send is otherwise silent and total.+#[test]+#[cfg(feature = "test-mocks")]+fn test_deliver_message_resends_while_the_pane_is_unchanged() {+ let mut mock = MockTmuxOperations::new();+ let pastes = std::sync::Arc::new(std::sync::Mutex::new(0usize));+ let pastes_c = pastes.clone();+ mock.expect_send_key().returning(|_, _| Ok(())); // the C-u before each resend+ mock.expect_paste_text().returning(move |_, _| {+ *pastes_c.lock().unwrap() += 1;+ Ok(())+ });+ mock.expect_capture_pane()+ .returning(|_| Ok("frozen splash".to_string()));++ let tmux: std::sync::Arc<dyn TmuxOperations> = std::sync::Arc::new(mock);+ assert!(!deliver_message(&tmux, "sess:win", "hello", true));+ assert_eq!(*pastes.lock().unwrap(), DELIVERY_ATTEMPTS as usize);+}++/// ...and the moment the pane redraws it stops, because a redraw means the+/// message landed and a resend would double it β the same rule+/// `dismiss_launch_dialog` uses for a dropped keystroke.+#[test]+#[cfg(feature = "test-mocks")]+fn test_deliver_message_stops_as_soon_as_the_pane_redraws() {+ let mut mock = MockTmuxOperations::new();+ let sends = std::sync::Arc::new(std::sync::Mutex::new(0usize));+ let sends_c = sends.clone();+ mock.expect_send_text().returning(move |_, _| {+ *sends_c.lock().unwrap() += 1;+ Ok(())+ });+ expect_echoing_pane(&mut mock, "composer");++ let tmux: std::sync::Arc<dyn TmuxOperations> = std::sync::Arc::new(mock);+ assert!(deliver_message(&tmux, "sess:win", "hello", false));+ assert_eq!(*sends.lock().unwrap(), 1, "no resend after a redraw");+}++/// The antigravity failure mode end to end: the paste is dropped by a TUI that+/// is not reading yet, so the combined send must retry rather than submit an+/// empty composer.+#[test]+#[cfg(feature = "test-mocks")]+fn test_combined_send_retries_a_dropped_paste() {+ let mut mock = MockTmuxOperations::new();+ let pastes = std::sync::Arc::new(std::sync::Mutex::new(Vec::<String>::new()));+ let pastes_c = pastes.clone();+ mock.expect_send_key().returning(|_, _| Ok(()));+ mock.expect_paste_text().returning(move |_, text| {+ pastes_c.lock().unwrap().push(text.to_string());+ Ok(())+ });+ mock.expect_capture_pane()+ .returning(|_| Ok("Do you trust the contents of this project?".to_string()));++ let tmux: std::sync::Arc<dyn TmuxOperations> = std::sync::Arc::new(mock);+ send_skill_and_prompt(+ &tmux,+ "sess:win",+ &Some("/agtx-plan abc".to_string()),+ "",+ &None,+ "task",+ "antigravity",+ &[],+ false,+ );+ let pasted = pastes.lock().unwrap();+ assert_eq!(pasted.len(), DELIVERY_ATTEMPTS as usize);+ assert!(pasted.iter().all(|p| p.contains("/agtx-plan abc")));+}++/// A pane that never goes quiet cannot confirm delivery by "something changed" β+/// the change is the agent's own output. Confirming on the text itself is what+/// keeps the busy case honest; without it the first poll always says "landed",+/// which is exactly the case the settle step was added for.+#[test]+#[cfg(feature = "test-mocks")]+fn test_deliver_message_on_a_busy_pane_confirms_on_the_text_not_the_change() {+ let mut mock = MockTmuxOperations::new();+ let sends = std::sync::Arc::new(std::sync::Mutex::new(0usize));+ let sends_c = sends.clone();+ let counter = std::sync::Arc::new(std::sync::Mutex::new(0usize));+ mock.expect_send_key().returning(|_, _| Ok(()));+ mock.expect_paste_text().returning(move |_, _| {+ *sends_c.lock().unwrap() += 1;+ Ok(())+ });+ // Never the same twice, and never containing the message: a streaming pane+ // that dropped what it was sent.+ mock.expect_capture_pane().returning(move |_| {+ let mut n = counter.lock().unwrap();+ *n += 1;+ Ok(format!("streaming line {n}"))+ });++ let tmux: std::sync::Arc<dyn TmuxOperations> = std::sync::Arc::new(mock);+ assert!(!deliver_message(&tmux, "sess:win", "/agtx-plan abc-123", true));+ assert_eq!(+ *sends.lock().unwrap(),+ DELIVERY_ATTEMPTS as usize,+ "a busy pane that never shows the text must still retry"+ );+}++/// ...and once the text does appear on that busy pane, it stops.+#[test]+#[cfg(feature = "test-mocks")]+fn test_deliver_message_on_a_busy_pane_stops_once_the_text_appears() {+ let mut mock = MockTmuxOperations::new();+ let sends = std::sync::Arc::new(std::sync::Mutex::new(0usize));+ let sends_c = sends.clone();+ let counter = std::sync::Arc::new(std::sync::Mutex::new(0usize));+ mock.expect_send_key().returning(|_, _| Ok(()));+ mock.expect_paste_text().returning(move |_, _| {+ *sends_c.lock().unwrap() += 1;+ Ok(())+ });+ mock.expect_capture_pane().returning(move |_| {+ let mut n = counter.lock().unwrap();+ *n += 1;+ // Still streaming, but the composer now echoes the message β wrapped and+ // re-indented, the way a real one does.+ Ok(format!("streaming {n}\n > /agtx-plan\n abc-123"))+ });++ let tmux: std::sync::Arc<dyn TmuxOperations> = std::sync::Arc::new(mock);+ assert!(deliver_message(&tmux, "sess:win", "/agtx-plan abc-123", true));+ assert_eq!(*sends.lock().unwrap(), 1, "no resend once the text is visible");+}++/// A resend clears the composer first: "nothing was seen to land" is not "nothing+/// landed", and a late redraw would otherwise leave the agent holding the message+/// twice, concatenated.+#[test]+#[cfg(feature = "test-mocks")]+fn test_deliver_message_clears_the_composer_before_a_resend() {+ let mut mock = MockTmuxOperations::new();+ let keys = std::sync::Arc::new(std::sync::Mutex::new(Vec::<String>::new()));+ let keys_c = keys.clone();+ mock.expect_send_key().returning(move |_, k| {+ keys_c.lock().unwrap().push(k.to_string());+ Ok(())+ });+ mock.expect_paste_text().returning(|_, _| Ok(()));+ mock.expect_capture_pane()+ .returning(|_| Ok("frozen".to_string()));++ let tmux: std::sync::Arc<dyn TmuxOperations> = std::sync::Arc::new(mock);+ assert!(!deliver_message(&tmux, "sess:win", "hello there", true));+ let keys = keys.lock().unwrap();+ assert_eq!(+ keys.iter().filter(|k| k.as_str() == "C-u").count(),+ DELIVERY_ATTEMPTS as usize - 1,+ "one clear before each resend, never before the first send: {keys:?}"+ );+}++/// The needle is short and whitespace-insensitive on both sides, because a+/// composer wraps and re-indents what it echoes.+#[test]+fn test_delivery_needle_survives_wrapping() {+ let needle = delivery_needle("/agtx-plan 57d57fe8-5990\n\nSMOKE TEST").unwrap();+ assert!(pane_shows(" > /agtx-plan\n 57d57fe8-5990 ...", &needle));+ assert!(!pane_shows(" > waiting for input", &needle));+ // Nothing distinctive enough to look for.+ assert!(delivery_needle("hi").is_none());+ assert!(delivery_needle(" ").is_none());+}++/// A phase advance fires as soon as the artifact appears, which can be while the+/// agent is still writing its closing lines β and a composer mid-render may not+/// take the message at all. Worse, a pane changing on its own makes the delivery+/// confirmation meaningless: the change it sees is the agent's output, not the+/// echo. So the send waits for quiet first.+#[test]+#[cfg(feature = "test-mocks")]+fn test_deliver_message_waits_for_the_pane_to_go_quiet_first() {+ let mut mock = MockTmuxOperations::new();+ let captures_before_send = std::sync::Arc::new(std::sync::Mutex::new(0usize));+ let counter = std::sync::Arc::new(std::sync::Mutex::new(0usize));+ let seen = captures_before_send.clone();+ let sent = std::sync::Arc::new(std::sync::Mutex::new(false));+ let sent_c = sent.clone();+ let counter_c = counter.clone();++ mock.expect_capture_pane().returning(move |_| {+ let mut n = counter_c.lock().unwrap();+ *n += 1;+ if !*sent_c.lock().unwrap() {+ *seen.lock().unwrap() = *n;+ }+ // Streaming output for the first few polls, then quiet.+ Ok(if *n <= 3 {+ format!("streaming {n}")+ } else if *sent_c.lock().unwrap() {+ "echoed".to_string()+ } else {+ "quiet".to_string()+ })+ });+ let sent_w = sent.clone();+ mock.expect_paste_text().returning(move |_, _| {+ *sent_w.lock().unwrap() = true;+ Ok(())+ });++ let tmux: std::sync::Arc<dyn TmuxOperations> = std::sync::Arc::new(mock);+ assert!(deliver_message(&tmux, "sess:win", "hello", true));+ assert!(+ *captures_before_send.lock().unwrap() > 3,+ "the send must wait out the streaming output, not fire into it"+ );+}++/// A `capture_pane` that models an idle pane which then echoes what was sent:+/// quiet long enough for `wait_for_pane_settled`, then changed once, so+/// [`deliver_message`] confirms on its first poll and does not resend.+///+/// The number of quiet captures is derived from the settle constants rather than+/// hardcoded, so tuning them does not silently turn these tests into+/// resend-three-times tests. A pane that *never* changes is what a dropped+/// message looks like, and is covered on purpose by+/// `test_deliver_message_resends_while_the_pane_is_unchanged`.+#[cfg(feature = "test-mocks")]+fn expect_echoing_pane(mock: &mut MockTmuxOperations, echoed: &'static str) {+ // `wait_for_pane_settled` needs one baseline capture plus SETTLE_STABLE_POLLS+ // identical ones; `deliver_message` then takes its own baseline.+ let quiet = SETTLE_STABLE_POLLS as usize + 2;+ let calls = std::sync::Arc::new(std::sync::Mutex::new(0usize));+ mock.expect_capture_pane().returning(move |_| {+ let mut n = calls.lock().unwrap();+ *n += 1;+ Ok(if *n <= quiet {+ "idle composer".to_string()+ } else {+ echoed.to_string()+ })+ });+}+#[test]#[cfg(feature = "test-mocks")]fn test_send_skill_and_prompt_gemini_combined() {@@ -3422,12 +3790,18 @@ fn test_send_skill_and_prompt_gemini_combined() {let literal_calls = std::sync::Arc::new(std::sync::Mutex::new(Vec::<String>::new()));let literal_c = literal_calls.clone();- mock.expect_send_keys_literal().returning(move |_, text| {+ let pastes = std::sync::Arc::new(std::sync::Mutex::new(Vec::<String>::new()));+ let pastes_c = pastes.clone();++ mock.expect_send_key().returning(move |_, text| {literal_c.lock().unwrap().push(text.to_string());Ok(())});- mock.expect_capture_pane()- .returning(|_| Ok("/agtx:plan\n\nmy task".to_string()));+ mock.expect_paste_text().returning(move |_, text| {+ pastes_c.lock().unwrap().push(text.to_string());+ Ok(())+ });+ expect_echoing_pane(&mut mock, "/agtx:plan\n\nmy task");let tmux: std::sync::Arc<dyn TmuxOperations> = std::sync::Arc::new(mock);send_skill_and_prompt(@@ -3441,11 +3815,23 @@ fn test_send_skill_and_prompt_gemini_combined() {&[],false,);+ // The message arrives as one bracketed paste, newlines intact β not as typed+ // keystrokes, which an Ink composer would submit at the first newline.+ let pasted = pastes.lock().unwrap();+ assert_eq!(pasted.len(), 1, "exactly one paste");+ assert!(pasted[0].contains("/agtx:plan") && pasted[0].contains("my task"));+ assert!(pasted[0].contains('\n'), "newlines preserved in the paste");+let calls = literal_calls.lock().unwrap();- assert!(calls- .iter()- .any(|c| c.contains("/agtx:plan") && c.contains("my task")));- assert!(calls.iter().any(|c| c == "Enter"));+ assert!(+ !calls.iter().any(|c| c.contains("my task")),+ "the message must not also be typed: {calls:?}"+ );+ assert_eq!(+ calls.iter().filter(|c| *c == "Enter").count(),+ 1,+ "exactly one Enter submits it: {calls:?}"+ );}#[test]@@ -3455,12 +3841,18 @@ fn test_send_skill_and_prompt_codex_combined() {let literal_calls = std::sync::Arc::new(std::sync::Mutex::new(Vec::<String>::new()));let literal_c = literal_calls.clone();- mock.expect_send_keys_literal().returning(move |_, text| {+ let pastes = std::sync::Arc::new(std::sync::Mutex::new(Vec::<String>::new()));+ let pastes_c = pastes.clone();++ mock.expect_send_key().returning(move |_, text| {literal_c.lock().unwrap().push(text.to_string());Ok(())});- mock.expect_capture_pane()- .returning(|_| Ok("$agtx-plan\n\ndo the thing".to_string()));+ mock.expect_paste_text().returning(move |_, text| {+ pastes_c.lock().unwrap().push(text.to_string());+ Ok(())+ });+ expect_echoing_pane(&mut mock, "$agtx-plan\n\ndo the thing");let tmux: std::sync::Arc<dyn TmuxOperations> = std::sync::Arc::new(mock);send_skill_and_prompt(@@ -3474,11 +3866,20 @@ fn test_send_skill_and_prompt_codex_combined() {&[],false,);+ let pasted = pastes.lock().unwrap();+ assert_eq!(pasted.len(), 1, "exactly one paste");+ assert!(pasted[0].contains("$agtx-plan") && pasted[0].contains("do the thing"));++ // Codex used to need a second Enter to dismiss its `$skill` command picker.+ // That picker opens on *typing*, not on a paste, so with bracketed paste there+ // is nothing to dismiss and a second Enter would fire into an empty composer.+ // Verified against codex-cli 0.144.5.let calls = literal_calls.lock().unwrap();- assert!(calls- .iter()- .any(|c| c.contains("$agtx-plan") && c.contains("do the thing")));- assert!(calls.iter().any(|c| c == "Enter"));+ assert_eq!(+ calls.iter().filter(|c| *c == "Enter").count(),+ 1,+ "codex must send exactly one Enter after a paste: {calls:?}"+ );}#[test]@@ -3492,7 +3893,7 @@ fn test_send_skill_and_prompt_claude_with_trigger() {keys_c.lock().unwrap().push(k.to_string());Ok(())});- mock.expect_send_keys_literal().returning(|_, _| Ok(()));+ mock.expect_send_key().returning(|_, _| Ok(()));// Return trigger text immediatelymock.expect_capture_pane().returning(|_| Ok("Ready for input >".to_string()));@@ -3533,7 +3934,7 @@ fn test_send_skill_and_prompt_clear_context_claude() {keys_c.lock().unwrap().push(k.to_string());Ok(())});- mock.expect_send_keys_literal().returning(|_, _| Ok(()));+ mock.expect_send_key().returning(|_, _| Ok(()));// Simulate stable pane after /clear so the poll exits quickly.mock.expect_capture_pane().returning(|_| Ok("β» Welcome to Claude Code!".to_string()));@@ -3578,9 +3979,9 @@ fn test_send_skill_and_prompt_clear_context_ignored_for_non_claude() {keys_c.lock().unwrap().push(k.to_string());Ok(())});- mock.expect_send_keys_literal().returning(|_, _| Ok(()));- mock.expect_capture_pane()- .returning(|_| Ok(String::new()));+ mock.expect_send_key().returning(|_, _| Ok(()));+ mock.expect_paste_text().returning(|_, _| Ok(()));+ mock.expect_capture_pane().returning(|_| Ok(String::new()));let tmux: std::sync::Arc<dyn TmuxOperations> = std::sync::Arc::new(mock);send_skill_and_prompt(@@ -3634,13 +4035,17 @@ fn test_send_skill_and_prompt_prompt_only() {#[cfg(feature = "test-mocks")]fn test_send_skill_and_prompt_void_prefill() {let mut mock = MockTmuxOperations::new();- let literal_calls = std::sync::Arc::new(std::sync::Mutex::new(Vec::<String>::new()));- let literal_c = literal_calls.clone();-- mock.expect_send_keys_literal().returning(move |_, text| {- literal_c.lock().unwrap().push(text.to_string());+ let texts = std::sync::Arc::new(std::sync::Mutex::new(Vec::<String>::new()));+ let texts_c = texts.clone();++ // Task-derived text goes through `send_text` (`send-keys -l`), never the+ // key-name path β a prefill that happened to spell "Up" or "Space" would+ // otherwise arrive as an arrow key or a bare space.+ mock.expect_send_text().returning(move |_, text| {+ texts_c.lock().unwrap().push(text.to_string());Ok(())});+ mock.expect_send_key().never();let tmux: std::sync::Arc<dyn TmuxOperations> = std::sync::Arc::new(mock);send_skill_and_prompt(@@ -3654,7 +4059,7 @@ fn test_send_skill_and_prompt_void_prefill() {&[],false,);- let calls = literal_calls.lock().unwrap();+ let calls = texts.lock().unwrap();assert_eq!(calls.len(), 1);assert_eq!(calls[0], "fix the login bug");}@@ -3693,7 +4098,7 @@ fn test_wait_for_prompt_trigger_auto_dismiss_then_trigger() {Ok("Ready for input >".to_string())}});- mock.expect_send_keys_literal().returning(move |_, k| {+ mock.expect_send_key().returning(move |_, k| {if k == "y" {dismiss_c.store(true, std::sync::atomic::Ordering::SeqCst);}@@ -3724,7 +4129,7 @@ fn test_wait_for_agent_ready_detects_agent_process() {mock.expect_capture_pane().returning(|_| Ok(String::new()));let tmux: std::sync::Arc<dyn TmuxOperations> = std::sync::Arc::new(mock);- let result = wait_for_agent_ready(&tmux, "sess:win");+ let result = wait_for_agent_ready(&tmux, "sess:win", None);assert_eq!(result, Some("sess:win".to_string()));}@@ -3738,7 +4143,7 @@ fn test_wait_for_agent_ready_detects_ready_indicator() {.returning(|_| Ok("Welcome to Gemini\nType your message".to_string()));let tmux: std::sync::Arc<dyn TmuxOperations> = std::sync::Arc::new(mock);- let result = wait_for_agent_ready(&tmux, "sess:win");+ let result = wait_for_agent_ready(&tmux, "sess:win", None);assert_eq!(result, Some("sess:win".to_string()));}@@ -3753,13 +4158,13 @@ fn test_wait_for_agent_ready_claude_bypass_accept() {.returning(|_| Some("bash".to_string()));mock.expect_capture_pane().returning(|_| Ok("Do you trust this? Yes, I accept the terms".to_string()));- mock.expect_send_keys_literal().returning(move |_, k| {+ mock.expect_send_key().returning(move |_, k| {literal_c.lock().unwrap().push(k.to_string());Ok(())});let tmux: std::sync::Arc<dyn TmuxOperations> = std::sync::Arc::new(mock);- let result = wait_for_agent_ready(&tmux, "sess:win");+ let result = wait_for_agent_ready(&tmux, "sess:win", None);assert_eq!(result, Some("sess:win".to_string()));let calls = literal_calls.lock().unwrap();assert!(@@ -3778,7 +4183,7 @@ fn test_write_skills_to_worktree_claude() {let dir = tempfile::tempdir().unwrap();let wt = dir.path().to_string_lossy().to_string();- write_skills_to_worktree(&wt, dir.path(), &None, &["claude"]);+ write_skills_to_worktree(&wt, dir.path(), &None, &["claude"], false);// Canonical skillsassert!(dir.path().join(".agtx/skills/agtx-plan/SKILL.md").exists());@@ -3810,7 +4215,7 @@ fn test_write_skills_to_worktree_gemini_toml() {let dir = tempfile::tempdir().unwrap();let wt = dir.path().to_string_lossy().to_string();- write_skills_to_worktree(&wt, dir.path(), &None, &["gemini"]);+ write_skills_to_worktree(&wt, dir.path(), &None, &["gemini"], false);let toml_path = dir.path().join(".gemini/commands/agtx/plan.toml");assert!(toml_path.exists());@@ -3832,7 +4237,7 @@ fn test_write_skills_to_worktree_codex() {let dir = tempfile::tempdir().unwrap();let wt = dir.path().to_string_lossy().to_string();- write_skills_to_worktree(&wt, dir.path(), &None, &["codex"]);+ write_skills_to_worktree(&wt, dir.path(), &None, &["codex"], false);// Codex uses subdirectories with SKILL.mdassert!(dir.path().join(".codex/skills/agtx-plan/SKILL.md").exists());@@ -3847,7 +4252,7 @@ fn test_write_skills_to_worktree_opencode() {let dir = tempfile::tempdir().unwrap();let wt = dir.path().to_string_lossy().to_string();- write_skills_to_worktree(&wt, dir.path(), &None, &["opencode"]);+ write_skills_to_worktree(&wt, dir.path(), &None, &["opencode"], false);let md_path = dir.path().join(".opencode/command/agtx-plan.md");assert!(md_path.exists());@@ -3863,7 +4268,7 @@ fn test_write_skills_to_worktree_mcp_claude() {let dir = tempfile::tempdir().unwrap();let wt = dir.path().to_string_lossy().to_string();- write_skills_to_worktree(&wt, dir.path(), &None, &["claude"]);+ write_skills_to_worktree(&wt, dir.path(), &None, &["claude"], false);let mcp = dir.path().join(".mcp.json");assert!(mcp.exists(), ".mcp.json should be written for claude");@@ -3878,10 +4283,13 @@ fn test_write_skills_to_worktree_mcp_gemini() {let dir = tempfile::tempdir().unwrap();let wt = dir.path().to_string_lossy().to_string();- write_skills_to_worktree(&wt, dir.path(), &None, &["gemini"]);+ write_skills_to_worktree(&wt, dir.path(), &None, &["gemini"], false);let cfg = dir.path().join(".gemini/settings.json");- assert!(cfg.exists(), ".gemini/settings.json should be written for gemini");+ assert!(+ cfg.exists(),+ ".gemini/settings.json should be written for gemini"+ );let content = std::fs::read_to_string(&cfg).unwrap();let v: serde_json::Value = serde_json::from_str(&content).unwrap();assert!(v["mcpServers"]["agtx"]["command"].is_string());@@ -3892,10 +4300,13 @@ fn test_write_skills_to_worktree_mcp_cursor() {let dir = tempfile::tempdir().unwrap();let wt = dir.path().to_string_lossy().to_string();- write_skills_to_worktree(&wt, dir.path(), &None, &["cursor"]);+ write_skills_to_worktree(&wt, dir.path(), &None, &["cursor"], false);let cfg = dir.path().join(".cursor/mcp.json");- assert!(cfg.exists(), ".cursor/mcp.json should be written for cursor");+ assert!(+ cfg.exists(),+ ".cursor/mcp.json should be written for cursor"+ );let content = std::fs::read_to_string(&cfg).unwrap();let v: serde_json::Value = serde_json::from_str(&content).unwrap();assert!(v["mcpServers"]["agtx"]["command"].is_string());@@ -3906,7 +4317,7 @@ fn test_write_skills_to_worktree_mcp_grok() {let dir = tempfile::tempdir().unwrap();let wt = dir.path().to_string_lossy().to_string();- write_skills_to_worktree(&wt, dir.path(), &None, &["grok"]);+ write_skills_to_worktree(&wt, dir.path(), &None, &["grok"], false);let cfg = dir.path().join(".grok/config.toml");assert!(cfg.exists(), ".grok/config.toml should be written for grok");@@ -3927,7 +4338,7 @@ fn test_write_skills_to_worktree_mcp_grok_preserves_existing_config() {).unwrap();- write_skills_to_worktree(&wt, dir.path(), &None, &["grok"]);+ write_skills_to_worktree(&wt, dir.path(), &None, &["grok"], false);let content = std::fs::read_to_string(grok_dir.join("config.toml")).unwrap();assert!(@@ -3942,12 +4353,18 @@ fn test_write_skills_to_worktree_grok_skills() {let dir = tempfile::tempdir().unwrap();let wt = dir.path().to_string_lossy().to_string();- write_skills_to_worktree(&wt, dir.path(), &None, &["grok"]);+ write_skills_to_worktree(&wt, dir.path(), &None, &["grok"], false);let skill = dir.path().join(".grok/skills/agtx-plan/SKILL.md");- assert!(skill.exists(), "grok skills go to .grok/skills/<name>/SKILL.md");+ assert!(+ skill.exists(),+ "grok skills go to .grok/skills/<name>/SKILL.md"+ );let content = std::fs::read_to_string(&skill).unwrap();- assert!(content.starts_with("---"), "frontmatter must be kept for grok");+ assert!(+ content.starts_with("---"),+ "frontmatter must be kept for grok"+ );// Canonical copy is always written tooassert!(dir.path().join(".agtx/skills/agtx-plan/SKILL.md").exists());}@@ -3977,7 +4394,7 @@ fn test_write_skills_to_worktree_mcp_antigravity() {let dir = tempfile::tempdir().unwrap();let wt = dir.path().to_string_lossy().to_string();- write_skills_to_worktree(&wt, dir.path(), &None, &["antigravity"]);+ write_skills_to_worktree(&wt, dir.path(), &None, &["antigravity"], false);let cfg = dir.path().join(".agents/mcp_config.json");assert!(@@ -4002,7 +4419,7 @@ fn test_write_skills_to_worktree_mcp_antigravity_preserves_existing_config() {).unwrap();- write_skills_to_worktree(&wt, dir.path(), &None, &["antigravity"]);+ write_skills_to_worktree(&wt, dir.path(), &None, &["antigravity"], false);let content = std::fs::read_to_string(agents_dir.join("mcp_config.json")).unwrap();let v: serde_json::Value = serde_json::from_str(&content).unwrap();@@ -4025,7 +4442,7 @@ fn test_write_skills_to_worktree_mcp_antigravity_replaces_malformed_config() {std::fs::create_dir_all(&agents_dir).unwrap();std::fs::write(agents_dir.join("mcp_config.json"), "not json at all").unwrap();- write_skills_to_worktree(&wt, dir.path(), &None, &["antigravity"]);+ write_skills_to_worktree(&wt, dir.path(), &None, &["antigravity"], false);let content = std::fs::read_to_string(agents_dir.join("mcp_config.json")).unwrap();let v: serde_json::Value =@@ -4038,7 +4455,7 @@ fn test_write_skills_to_worktree_antigravity_skills() {let dir = tempfile::tempdir().unwrap();let wt = dir.path().to_string_lossy().to_string();- write_skills_to_worktree(&wt, dir.path(), &None, &["antigravity"]);+ write_skills_to_worktree(&wt, dir.path(), &None, &["antigravity"], false);let skill = dir.path().join(".agents/skills/agtx-plan/SKILL.md");assert!(@@ -4060,10 +4477,13 @@ fn test_write_skills_to_worktree_mcp_codex() {let dir = tempfile::tempdir().unwrap();let wt = dir.path().to_string_lossy().to_string();- write_skills_to_worktree(&wt, dir.path(), &None, &["codex"]);+ write_skills_to_worktree(&wt, dir.path(), &None, &["codex"], false);let cfg = dir.path().join(".codex/config.toml");- assert!(cfg.exists(), ".codex/config.toml should be written for codex");+ assert!(+ cfg.exists(),+ ".codex/config.toml should be written for codex"+ );let content = std::fs::read_to_string(&cfg).unwrap();assert!(content.contains("[mcp_servers.agtx]"));assert!(content.contains("mcp-serve"));@@ -4074,7 +4494,7 @@ fn test_write_skills_to_worktree_mcp_opencode() {let dir = tempfile::tempdir().unwrap();let wt = dir.path().to_string_lossy().to_string();- write_skills_to_worktree(&wt, dir.path(), &None, &["opencode"]);+ write_skills_to_worktree(&wt, dir.path(), &None, &["opencode"], false);let cfg = dir.path().join("opencode.json");assert!(cfg.exists(), "opencode.json should be written for opencode");@@ -4286,7 +4706,6 @@ fn type_str(app: &mut App, s: &str) {}}-// --- Smoke tests ---#[test]@@ -5178,8 +5597,7 @@ fn assert_cursor_matches_wrap(text: &str, prefix: usize, wrap_width: usize) {let spans = vec![ratatui::text::Span::raw(combined)];let lines = super::wrap_spans(spans, wrap_width);- let (col, row) =- super::wrapped_cursor_pos(text, text.len(), prefix, wrap_width);+ let (col, row) = super::wrapped_cursor_pos(text, text.len(), prefix, wrap_width);assert_eq!(row,@@ -5589,7 +6007,7 @@ fn test_transition_to_planning_reuses_live_session() {// spawn_send_to_agent may call these; allow any number of callsmock_tmux.expect_send_keys().returning(|_, _| Ok(()));mock_tmux- .expect_send_keys_literal()+ .expect_send_key().returning(|_, _| Ok(()));mock_tmux.expect_capture_pane()@@ -5711,7 +6129,7 @@ fn test_transition_to_running_with_session_returns_false() {let mut mock_tmux = MockTmuxOperations::new();mock_tmux.expect_send_keys().returning(|_, _| Ok(()));mock_tmux- .expect_send_keys_literal()+ .expect_send_key().returning(|_, _| Ok(()));mock_tmux.expect_capture_pane()@@ -5752,7 +6170,7 @@ fn test_transition_to_review_no_pr_sets_review_confirm_popup() {let mut mock_tmux = MockTmuxOperations::new();mock_tmux.expect_send_keys().returning(|_, _| Ok(()));mock_tmux- .expect_send_keys_literal()+ .expect_send_key().returning(|_, _| Ok(()));mock_tmux.expect_capture_pane()@@ -5792,7 +6210,7 @@ fn test_transition_to_review_existing_pr_spawns_push() {let mut mock_tmux = MockTmuxOperations::new();mock_tmux.expect_send_keys().returning(|_, _| Ok(()));mock_tmux- .expect_send_keys_literal()+ .expect_send_key().returning(|_, _| Ok(()));mock_tmux.expect_capture_pane()@@ -5961,6 +6379,7 @@ fn make_session_task_status(task_id: task_id.to_string(),phase_status,content_hash: None,+ hook_status: None,status,worktree_path: None,session_name: None,@@ -6012,21 +6431,33 @@ fn test_apply_session_refresh_ready_inserts_cache() {assert!(!app.state.pane_content_hashes.contains_key("t1"));}-#[test]+// ββ hook-reported status βββββββββββββββββββββββββββββββββββββββββββββββββββββ+#[cfg(feature = "test-mocks")]-fn test_apply_session_refresh_working_becomes_idle_after_15s() {- // Working with same content hash stable for β₯15s β promoted to Idle- let mut app = make_test_app();- let old_instant = std::time::Instant::now() - std::time::Duration::from_secs(20);- app.state- .pane_content_hashes- .insert("t1".to_string(), (99, old_instant));+fn hook(state: crate::agent::hook_status::HookState) -> crate::agent::hook_status::AgentHookStatus {+ crate::agent::hook_status::AgentHookStatus {+ ts: 0,+ state,+ session_id: None,+ transcript_path: None,+ message: None,+ tool: None,+ agent: "claude".to_string(),+ }+}+#[cfg(feature = "test-mocks")]+fn refresh_with_hook(+ app: &mut App,+ hook_status: Option<crate::agent::hook_status::AgentHookStatus>,+ content_hash: Option<u64>,+) -> PhaseStatus {let result = SessionRefreshResult {statuses: vec![SessionTaskStatus {task_id: "t1".to_string(),phase_status: PhaseStatus::Working,- content_hash: Some(99), // same hash β stable+ content_hash,+ hook_status,status: TaskStatus::Planning,worktree_path: None,session_name: None,@@ -6035,25 +6466,176 @@ fn test_apply_session_refresh_working_becomes_idle_after_15s() {}],};app.apply_session_refresh(result);- let (phase, _) = app.state.phase_status_cache["t1"];- assert_eq!(phase, PhaseStatus::Idle);+ app.state.phase_status_cache["t1"].0}+/// The regression that motivates the whole change: an agent thinking silently+/// for longer than 15s used to be reported as Idle.#[test]#[cfg(feature = "test-mocks")]-fn test_apply_session_refresh_working_stays_working_hash_changed() {- // Working with changed content hash β still Working (timer resets)+fn test_hook_working_beats_a_stale_pane_hash() {+ use crate::agent::hook_status::HookState;let mut app = make_test_app();- let old_instant = std::time::Instant::now() - std::time::Duration::from_secs(20);+ let old = std::time::Instant::now() - std::time::Duration::from_secs(20);app.state.pane_content_hashes- .insert("t1".to_string(), (99, old_instant));+ .insert("t1".to_string(), (99, old));- let result = SessionRefreshResult {- statuses: vec![SessionTaskStatus {- task_id: "t1".to_string(),+ let phase = refresh_with_hook(&mut app, Some(hook(HookState::Working)), Some(99));++ assert_eq!(+ phase,+ PhaseStatus::Working,+ "a hook saying Working must override 20s of unchanged pane output"+ );+ assert!(+ !app.state.pane_content_hashes.contains_key("t1"),+ "pane history should be dropped once the agent reports for itself"+ );+}++#[test]+#[cfg(feature = "test-mocks")]+fn test_hook_blocked_maps_to_blocked_and_records_reason() {+ use crate::agent::hook_status::HookState;+ let mut app = make_test_app();+ let mut h = hook(HookState::Blocked);+ h.message = Some("Allow Bash(rm -rf /)?".to_string());++ assert_eq!(+ refresh_with_hook(&mut app, Some(h), None),+ PhaseStatus::Blocked+ );+ assert_eq!(+ app.state.blocked_reasons.get("t1").map(String::as_str),+ Some("Allow Bash(rm -rf /)?")+ );+}++#[test]+#[cfg(feature = "test-mocks")]+fn test_blocked_reason_is_cleared_when_the_agent_resumes() {+ use crate::agent::hook_status::HookState;+ let mut app = make_test_app();+ let mut h = hook(HookState::Blocked);+ h.message = Some("Allow Bash?".to_string());+ refresh_with_hook(&mut app, Some(h), None);++ refresh_with_hook(&mut app, Some(hook(HookState::Working)), None);++ assert!(+ !app.state.blocked_reasons.contains_key("t1"),+ "a stale reason must not linger on the card after the agent resumes"+ );+}++#[test]+#[cfg(feature = "test-mocks")]+fn test_hook_waiting_maps_to_idle() {+ use crate::agent::hook_status::HookState;+ let mut app = make_test_app();+ // "turn ended, no artifact yet" is what Idle has always meant, so the+ // merge-conflict and stuck-task consumers keep working unchanged.+ assert_eq!(+ refresh_with_hook(&mut app, Some(hook(HookState::Waiting)), None),+ PhaseStatus::Idle+ );+}++#[test]+#[cfg(feature = "test-mocks")]+fn test_hook_ended_maps_to_exited() {+ use crate::agent::hook_status::HookState;+ let mut app = make_test_app();+ assert_eq!(+ refresh_with_hook(&mut app, Some(hook(HookState::Ended)), None),+ PhaseStatus::Exited+ );+}++/// The fallback contract: with no hook report, behaviour is exactly as before.+#[test]+#[cfg(feature = "test-mocks")]+fn test_no_hook_status_keeps_the_pane_heuristic() {+ let mut app = make_test_app();+ let old = std::time::Instant::now() - std::time::Duration::from_secs(20);+ app.state+ .pane_content_hashes+ .insert("t1".to_string(), (99, old));++ assert_eq!(+ refresh_with_hook(&mut app, None, Some(99)),+ PhaseStatus::Idle+ );+}++/// Artifact detection is untouched by this plan β Ready still wins.+#[test]+#[cfg(feature = "test-mocks")]+fn test_ready_artifact_outranks_a_working_hook() {+ use crate::agent::hook_status::HookState;+ let mut app = make_test_app();+ let result = SessionRefreshResult {+ statuses: vec![SessionTaskStatus {+ task_id: "t1".to_string(),+ phase_status: PhaseStatus::Ready,+ content_hash: None,+ hook_status: Some(hook(HookState::Working)),+ status: TaskStatus::Planning,+ worktree_path: None,+ session_name: None,+ agent: "claude".to_string(),+ was_ready: false,+ }],+ };+ app.apply_session_refresh(result);+ assert_eq!(app.state.phase_status_cache["t1"].0, PhaseStatus::Ready);+}++#[test]+#[cfg(feature = "test-mocks")]+fn test_apply_session_refresh_working_becomes_idle_after_15s() {+ // Working with same content hash stable for β₯15s β promoted to Idle+ let mut app = make_test_app();+ let old_instant = std::time::Instant::now() - std::time::Duration::from_secs(20);+ app.state+ .pane_content_hashes+ .insert("t1".to_string(), (99, old_instant));++ let result = SessionRefreshResult {+ statuses: vec![SessionTaskStatus {+ task_id: "t1".to_string(),+ phase_status: PhaseStatus::Working,+ content_hash: Some(99), // same hash β stable+ hook_status: None,+ status: TaskStatus::Planning,+ worktree_path: None,+ session_name: None,+ agent: "claude".to_string(),+ was_ready: false,+ }],+ };+ app.apply_session_refresh(result);+ let (phase, _) = app.state.phase_status_cache["t1"];+ assert_eq!(phase, PhaseStatus::Idle);+}++#[test]+#[cfg(feature = "test-mocks")]+fn test_apply_session_refresh_working_stays_working_hash_changed() {+ // Working with changed content hash β still Working (timer resets)+ let mut app = make_test_app();+ let old_instant = std::time::Instant::now() - std::time::Duration::from_secs(20);+ app.state+ .pane_content_hashes+ .insert("t1".to_string(), (99, old_instant));++ let result = SessionRefreshResult {+ statuses: vec![SessionTaskStatus {+ task_id: "t1".to_string(),phase_status: PhaseStatus::Working,content_hash: Some(100), // different hash β timer resets+ hook_status: None,status: TaskStatus::Planning,worktree_path: None,session_name: None,@@ -7343,10 +7925,12 @@ fn test_toggle_orchestrator_spawns_new_session() {mock_tmux.expect_create_session().returning(|_, _| Ok(()));mock_tmux.expect_create_window()- .withf(|_session, window_name, _dir, _cmd, keep_shell_on_exit: &bool| {- window_name == "orchestrator" && !keep_shell_on_exit- })- .returning(|_, _, _, _, _| Ok(()));+ .withf(+ |_session, window_name, _dir, _cmd, keep_shell_on_exit: &bool, _env: &[(String, String)]| {+ window_name == "orchestrator" && !keep_shell_on_exit+ },+ )+ .returning(|_, _, _, _, _, _| Ok(()));mock_tmux.expect_resize_window().returning(|_, _, _| Ok(()));mock_tmux.expect_capture_pane_with_history()@@ -7436,9 +8020,7 @@ fn test_toggle_orchestrator_reattaches_to_live_orchestrator_from_other_instance(.expect_capture_pane().withf(|t| t == "test-project:orchestrator").returning(|_| Ok("Claude Code\n".to_string()));- mock_tmux- .expect_resize_window()- .returning(|_, _, _| Ok(()));+ mock_tmux.expect_resize_window().returning(|_, _, _| Ok(()));mock_tmux.expect_capture_pane_with_history().returning(|_, _| vec![]);@@ -7482,10 +8064,12 @@ fn test_toggle_orchestrator_clears_stale_session_and_respawns() {// Respawn must keep `keep_shell_on_exit=false` β else zombie shell on exit.mock_tmux.expect_create_window()- .withf(|_session, window_name, _dir, _cmd, keep_shell_on_exit: &bool| {- window_name == "orchestrator" && !keep_shell_on_exit- })- .returning(|_, _, _, _, _| Ok(()));+ .withf(+ |_session, window_name, _dir, _cmd, keep_shell_on_exit: &bool, _env: &[(String, String)]| {+ window_name == "orchestrator" && !keep_shell_on_exit+ },+ )+ .returning(|_, _, _, _, _, _| Ok(()));mock_tmux.expect_resize_window().returning(|_, _, _| Ok(()));mock_tmux.expect_capture_pane_with_history()@@ -7837,13 +8421,7 @@ fn test_deliver_orchestrator_notifications_clears_state_when_window_gone() {assert!(app.state.orchestrator_session.is_none());assert!(!app.state.orchestrator_ready.load(Ordering::Acquire));- let remaining = app- .state- .db- .as_ref()- .unwrap()- .peek_notifications()- .unwrap();+ let remaining = app.state.db.as_ref().unwrap().peek_notifications().unwrap();assert_eq!(remaining.len(), 1, "notifications preserved for next spawn");}@@ -7872,7 +8450,11 @@ fn test_run_orchestrator_catchup_emits_for_planning_artifact() {run_orchestrator_catchup(&db, &[task.clone()], None);let notifs = db.peek_notifications().unwrap();- assert_eq!(notifs.len(), 1, "expected exactly one catch-up notification");+ assert_eq!(+ notifs.len(),+ 1,+ "expected exactly one catch-up notification"+ );assert!(notifs[0].message.contains("compose release notes"),"message should include task title, got: {}",@@ -8013,7 +8595,11 @@ fn test_detect_existing_orchestrator_runs_catchup() {assert!(result.is_some());let notifs = db.peek_notifications().unwrap();- assert_eq!(notifs.len(), 1, "catch-up should have queued one notification");+ assert_eq!(+ notifs.len(),+ 1,+ "catch-up should have queued one notification"+ );let _ = std::fs::remove_dir_all(&tmp);}@@ -8523,7 +9109,7 @@ fn test_is_agent_active_true_when_agent_process_running() {mock_tmux.expect_pane_current_command().returning(|_| Some("claude".to_string()));- assert!(is_agent_active(&mock_tmux, "proj:task"));+ assert!(is_agent_active(&mock_tmux, "proj:task", None));}#[test]@@ -8537,7 +9123,7 @@ fn test_is_agent_active_true_when_gemini_indicator_in_pane() {mock_tmux.expect_capture_pane().returning(|_| Ok("some output\nType your message\n".to_string()));- assert!(is_agent_active(&mock_tmux, "proj:task"));+ assert!(is_agent_active(&mock_tmux, "proj:task", None));}#[test]@@ -8550,7 +9136,7 @@ fn test_is_agent_active_false_when_at_shell_no_indicator() {mock_tmux.expect_capture_pane().returning(|_| Ok("$ ".to_string()));- assert!(!is_agent_active(&mock_tmux, "proj:task"));+ assert!(!is_agent_active(&mock_tmux, "proj:task", None));}// --- collect_task_diff ---@@ -8673,6 +9259,45 @@ fn test_cleanup_task_for_done_no_ops_when_no_session_or_worktree() {assert_eq!(task.status, TaskStatus::Done);}+/// `.agtx/status/` is runtime scratch written by agent hooks, not a phase+/// artifact. The archive step only copies top-level `.md` files, so it is+/// excluded today β this pins that, since a future recursive archive would+/// otherwise start snapshotting status records.+#[test]+#[cfg(feature = "test-mocks")]+fn test_cleanup_does_not_archive_hook_status_files() {+ let mock_tmux = MockTmuxOperations::new();+ let mut mock_git = MockGitOperations::new();+ mock_git.expect_remove_worktree().returning(|_, _| Ok(()));++ let wt = tempfile::tempdir().unwrap();+ let status_dir = wt.path().join(".agtx").join("status");+ std::fs::create_dir_all(&status_dir).unwrap();+ std::fs::write(+ status_dir.join("t9.json"),+ r#"{"ts":1,"state":"working","agent":"claude"}"#,+ )+ .unwrap();++ let project_dir = tempfile::tempdir().unwrap();+ let mut task = make_test_task("t9", "Status task", TaskStatus::Review);+ task.session_name = None;+ task.worktree_path = Some(wt.path().to_string_lossy().to_string());+ task.branch_name = Some("task/my-slug".to_string());++ cleanup_task_for_done(&mut task, None, project_dir.path(), &mock_tmux, &mock_git);++ let archived = project_dir+ .path()+ .join(".agtx")+ .join("archive")+ .join("my-slug");+ assert!(+ !archived.join("status").exists() && !archived.join("t9.json").exists(),+ "hook status records must not be archived"+ );+}+#[test]#[cfg(feature = "test-mocks")]fn test_cleanup_task_for_done_archives_md_files() {@@ -8696,13 +9321,7 @@ fn test_cleanup_task_for_done_archives_md_files() {task.worktree_path = Some(wt.path().to_string_lossy().to_string());task.branch_name = Some("task/my-slug".to_string());- cleanup_task_for_done(- &mut task,- None,- project_dir.path(),- &mock_tmux,- &mock_git,- );+ cleanup_task_for_done(&mut task, None, project_dir.path(), &mock_tmux, &mock_git);// Archived file should exist under .agtx/archive/my-slug/plan.mdlet archive = project_dir@@ -8788,13 +9407,7 @@ fn test_delete_task_resources_kills_window_removes_worktree_and_deletes_branch()task.worktree_path = Some("/tmp/wt".to_string());task.branch_name = Some("task/my-task".to_string());- delete_task_resources(- &task,- None,- Path::new("/tmp/proj"),- &mock_tmux,- &mock_git,- );+ delete_task_resources(&task, None, Path::new("/tmp/proj"), &mock_tmux, &mock_git);}#[test]@@ -8805,13 +9418,7 @@ fn test_delete_task_resources_noop_when_no_session_or_worktree() {let task = make_test_task("t2", "Nothing to clean", TaskStatus::Backlog);// session_name and worktree_path both None β no mock calls- delete_task_resources(- &task,- None,- Path::new("/tmp/proj"),- &mock_tmux,- &mock_git,- );+ delete_task_resources(&task, None, Path::new("/tmp/proj"), &mock_tmux, &mock_git);}// --- save_task ---@@ -8998,9 +9605,9 @@ fn test_switch_agent_claude_sends_exit_then_new_cmd() {fn test_switch_agent_codex_sends_ctrl_c_not_exit() {// Codex has no exit command β sends C-c insteadlet mut mock_tmux = MockTmuxOperations::new();- // C-c via send_keys_literal (not send_keys)+ // C-c via send_key (not send_keys)mock_tmux- .expect_send_keys_literal()+ .expect_send_key().withf(|_, key: &str| key == "C-c").times(1).returning(|_, _| Ok(()));@@ -9012,11 +9619,18 @@ fn test_switch_agent_codex_sends_ctrl_c_not_exit() {.returning(|_| Ok(String::new()));mock_tmux.expect_send_keys()- .withf(|_, cmd: &str| cmd == "env -u CLAUDECODE -u CLAUDE_CODE_ENTRYPOINT codex --sandbox workspace-write")+ .withf(|_, cmd: &str| {+ cmd == "env -u CLAUDECODE -u CLAUDE_CODE_ENTRYPOINT codex --sandbox workspace-write"+ }).times(1).returning(|_, _| Ok(()));- switch_agent_in_tmux(&mock_tmux, "proj:task", "codex", "codex --sandbox workspace-write");+ switch_agent_in_tmux(+ &mock_tmux,+ "proj:task",+ "codex",+ "codex --sandbox workspace-write",+ );}#[test]@@ -9049,7 +9663,7 @@ fn test_switch_agent_retries_with_ctrl_c_when_shell_not_found() {.returning(|_| Ok(String::new()));// C-c sent on retrymock_tmux- .expect_send_keys_literal()+ .expect_send_key().withf(|_, key: &str| key == "C-c").times(1).returning(|_, _| Ok(()));@@ -9078,13 +9692,13 @@ fn test_switch_agent_sends_ctrl_d_as_last_resort() {.returning(|_| Some("claude".to_string()));// C-c on retrymock_tmux- .expect_send_keys_literal()+ .expect_send_key().withf(|_, key: &str| key == "C-c").times(1).returning(|_, _| Ok(()));// C-d as last resortmock_tmux- .expect_send_keys_literal()+ .expect_send_key().withf(|_, key: &str| key == "C-d").times(1).returning(|_, _| Ok(()));@@ -9111,7 +9725,7 @@ fn test_switch_agent_always_sends_new_agent_cmd() {.expect_pane_current_command().returning(|_| Some("claude".to_string()));mock_tmux- .expect_send_keys_literal()+ .expect_send_key().returning(|_, _| Ok(()));// This is the key assertion β new_agent_cmd must be sent exactly oncemock_tmux@@ -9141,6 +9755,7 @@ fn test_wait_for_agent_ready_returns_when_process_detected() {let result = wait_for_agent_ready(&(Arc::new(mock_tmux) as Arc<dyn TmuxOperations>),"proj:task",+ None,);assert_eq!(result, Some("proj:task".to_string()));}@@ -9160,6 +9775,7 @@ fn test_wait_for_agent_ready_returns_when_ready_indicator_in_pane() {let result = wait_for_agent_ready(&(Arc::new(mock_tmux) as Arc<dyn TmuxOperations>),"proj:task",+ None,);assert_eq!(result, Some("proj:task".to_string()));}@@ -9175,22 +9791,24 @@ fn test_wait_for_agent_ready_handles_claude_bypass_prompt() {mock_tmux.expect_capture_pane().returning(|_| Ok("Yes, I accept\nSome prompt text".to_string()));- // Must send "2" to accept+ // Must send "2" to accept. The mock pane never changes, which is exactly how+ // a dropped keystroke looks, so the answer is retried up to the cap.mock_tmux- .expect_send_keys_literal()+ .expect_send_key().withf(|_, key: &str| key == "2")- .times(1)+ .times(LAUNCH_DIALOG_MAX_ATTEMPTS as usize).returning(|_, _| Ok(()));// Must send Enter to confirmmock_tmux- .expect_send_keys_literal()+ .expect_send_key().withf(|_, key: &str| key == "Enter")- .times(1)+ .times(LAUNCH_DIALOG_MAX_ATTEMPTS as usize).returning(|_, _| Ok(()));let result = wait_for_agent_ready(&(Arc::new(mock_tmux) as Arc<dyn TmuxOperations>),"proj:task",+ None,);assert_eq!(result, Some("proj:task".to_string()));}@@ -9222,6 +9840,7 @@ fn test_wait_for_agent_ready_returns_when_content_stabilizes() {let result = wait_for_agent_ready(&(Arc::new(mock_tmux) as Arc<dyn TmuxOperations>),"proj:task",+ None,);assert_eq!(result, Some("proj:task".to_string()));}@@ -9247,6 +9866,7 @@ fn test_wait_for_agent_ready_always_returns_some() {let result = wait_for_agent_ready(&(Arc::new(mock_tmux) as Arc<dyn TmuxOperations>),"proj:task",+ None,);assert_eq!(result, Some("proj:task".to_string()));}@@ -9296,7 +9916,7 @@ fn test_is_agent_active_detects_claude_via_indicator() {mock.expect_capture_pane().returning(|_| Ok("Claude Code v2.1.72\n> ".to_string()));assert!(- is_agent_active(&mock, "t"),+ is_agent_active(&mock, "t", None),"Claude Code indicator should trigger is_agent_active");}@@ -9310,7 +9930,7 @@ fn test_is_agent_active_detects_gemini_via_indicator() {mock.expect_capture_pane().returning(|_| Ok("some output\nType your message".to_string()));assert!(- is_agent_active(&mock, "t"),+ is_agent_active(&mock, "t", None),"Gemini indicator should trigger is_agent_active");}@@ -9324,7 +9944,7 @@ fn test_is_agent_active_detects_opencode_via_indicator() {mock.expect_capture_pane().returning(|_| Ok("some output\nAsk anything".to_string()));assert!(- is_agent_active(&mock, "t"),+ is_agent_active(&mock, "t", None),"OpenCode indicator should trigger is_agent_active");}@@ -9338,7 +9958,7 @@ fn test_is_agent_active_detects_cursor_via_indicator() {mock.expect_capture_pane().returning(|_| Ok("some output\nCursor Agent\n> ".to_string()));assert!(- is_agent_active(&mock, "t"),+ is_agent_active(&mock, "t", None),"Cursor indicator should trigger is_agent_active");}@@ -9352,7 +9972,7 @@ fn test_is_agent_active_detects_codex_via_indicator() {mock.expect_capture_pane().returning(|_| Ok("some output\nOpenAI Codex".to_string()));assert!(- is_agent_active(&mock, "t"),+ is_agent_active(&mock, "t", None),"Codex indicator should trigger is_agent_active");}@@ -9366,7 +9986,7 @@ fn test_is_agent_active_returns_false_when_no_indicator() {mock.expect_capture_pane().returning(|_| Ok("just some shell output".to_string()));assert!(- !is_agent_active(&mock, "t"),+ !is_agent_active(&mock, "t", None),"no indicator should return false");}@@ -9384,7 +10004,7 @@ fn test_wait_for_agent_ready_detects_claude_via_banner() {.returning(|_| Some("bash".to_string()));mock.expect_capture_pane().returning(|_| Ok("Claude Code v2.1.72\nsome context".to_string()));- let result = wait_for_agent_ready(&(Arc::new(mock) as Arc<dyn TmuxOperations>), "proj:task");+ let result = wait_for_agent_ready(&(Arc::new(mock) as Arc<dyn TmuxOperations>), "proj:task", None);assert_eq!(result, Some("proj:task".to_string()));}@@ -9396,7 +10016,7 @@ fn test_wait_for_agent_ready_detects_cursor_via_banner() {.returning(|_| Some("bash".to_string()));mock.expect_capture_pane().returning(|_| Ok("Cursor Agent\n> ".to_string()));- let result = wait_for_agent_ready(&(Arc::new(mock) as Arc<dyn TmuxOperations>), "proj:task");+ let result = wait_for_agent_ready(&(Arc::new(mock) as Arc<dyn TmuxOperations>), "proj:task", None);assert_eq!(result, Some("proj:task".to_string()));}@@ -9408,7 +10028,7 @@ fn test_wait_for_agent_ready_detects_opencode_via_banner() {.returning(|_| Some("bash".to_string()));mock.expect_capture_pane().returning(|_| Ok("Ask anything\n> ".to_string()));- let result = wait_for_agent_ready(&(Arc::new(mock) as Arc<dyn TmuxOperations>), "proj:task");+ let result = wait_for_agent_ready(&(Arc::new(mock) as Arc<dyn TmuxOperations>), "proj:task", None);assert_eq!(result, Some("proj:task".to_string()));}@@ -9420,7 +10040,7 @@ fn test_wait_for_agent_ready_detects_codex_via_banner() {.returning(|_| Some("bash".to_string()));mock.expect_capture_pane().returning(|_| Ok("OpenAI Codex\nsome output".to_string()));- let result = wait_for_agent_ready(&(Arc::new(mock) as Arc<dyn TmuxOperations>), "proj:task");+ let result = wait_for_agent_ready(&(Arc::new(mock) as Arc<dyn TmuxOperations>), "proj:task", None);assert_eq!(result, Some("proj:task".to_string()));}@@ -9434,7 +10054,7 @@ fn test_switch_agent_cursor_sends_ctrl_c_not_exit() {// Cursor is an Ink/Node TUI β uses Ctrl+C to exit, no /exit commandlet mut mock_tmux = MockTmuxOperations::new();mock_tmux- .expect_send_keys_literal()+ .expect_send_key().withf(|_, key: &str| key == "C-c").times(1).returning(|_, _| Ok(()));@@ -9460,16 +10080,14 @@ fn test_switch_agent_opencode_sends_exit() {let mut mock_tmux = MockTmuxOperations::new();let exit_sent = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));let exit_sent_c = exit_sent.clone();+ mock_tmux.expect_send_keys().returning(move |_, cmd| {+ if cmd == "/exit" {+ exit_sent_c.store(true, std::sync::atomic::Ordering::SeqCst);+ }+ Ok(())+ });mock_tmux- .expect_send_keys()- .returning(move |_, cmd| {- if cmd == "/exit" {- exit_sent_c.store(true, std::sync::atomic::Ordering::SeqCst);- }- Ok(())- });- mock_tmux- .expect_send_keys_literal()+ .expect_send_key().returning(|_, _| Ok(()));mock_tmux.expect_pane_current_command()@@ -9493,14 +10111,20 @@ fn test_send_skill_and_prompt_opencode_combined_with_double_enter() {let mut mock = MockTmuxOperations::new();let literal_calls = std::sync::Arc::new(std::sync::Mutex::new(Vec::<String>::new()));let literal_c = literal_calls.clone();+ let texts = std::sync::Arc::new(std::sync::Mutex::new(Vec::<String>::new()));+ let texts_c = texts.clone();- mock.expect_send_keys_literal().returning(move |_, text| {+ mock.expect_send_key().returning(move |_, text| {literal_c.lock().unwrap().push(text.to_string());Ok(())});- // capture_pane returns content with skill+prompt text so the wait loop exits quickly- mock.expect_capture_pane()- .returning(|_| Ok("/agtx-plan\n\ndo the thing".to_string()));+ // The message itself is text, so it goes through send_text (`send-keys -l`);+ // only the Enters are keys.+ mock.expect_send_text().returning(move |_, text| {+ texts_c.lock().unwrap().push(text.to_string());+ Ok(())+ });+ expect_echoing_pane(&mut mock, "/agtx-plan\n\ndo the thing");let tmux: std::sync::Arc<dyn TmuxOperations> = std::sync::Arc::new(mock);send_skill_and_prompt(@@ -9514,14 +10138,14 @@ fn test_send_skill_and_prompt_opencode_combined_with_double_enter() {&[],false,);- let calls = literal_calls.lock().unwrap();+ let sent = texts.lock().unwrap();// Combined message sentassert!(- calls- .iter()+ sent.iter().any(|c| c.contains("/agtx-plan") && c.contains("do the thing")),"skill+prompt should be combined for opencode");+ let calls = literal_calls.lock().unwrap();// Two Enters sent (first to close picker, second to submit)assert_eq!(calls.iter().filter(|c| c.as_str() == "Enter").count(),@@ -9533,17 +10157,22 @@ fn test_send_skill_and_prompt_opencode_combined_with_double_enter() {#[test]#[cfg(feature = "test-mocks")]fn test_send_skill_and_prompt_cursor_combined_single_enter() {- // Cursor: skill+prompt combined, only one Enter needed (no command picker)+ // Cursor: skill+prompt combined into one bracketed paste, one Enter to submit.let mut mock = MockTmuxOperations::new();let literal_calls = std::sync::Arc::new(std::sync::Mutex::new(Vec::<String>::new()));let literal_c = literal_calls.clone();+ let pastes = std::sync::Arc::new(std::sync::Mutex::new(Vec::<String>::new()));+ let pastes_c = pastes.clone();- mock.expect_send_keys_literal().returning(move |_, text| {+ mock.expect_send_key().returning(move |_, text| {literal_c.lock().unwrap().push(text.to_string());Ok(())});- mock.expect_capture_pane()- .returning(|_| Ok("/agtx-plan\n\nmy task".to_string()));+ mock.expect_paste_text().returning(move |_, text| {+ pastes_c.lock().unwrap().push(text.to_string());+ Ok(())+ });+ expect_echoing_pane(&mut mock, "/agtx-plan\n\nmy task");let tmux: std::sync::Arc<dyn TmuxOperations> = std::sync::Arc::new(mock);send_skill_and_prompt(@@ -9557,14 +10186,14 @@ fn test_send_skill_and_prompt_cursor_combined_single_enter() {&[],false,);- let calls = literal_calls.lock().unwrap();+ let pasted = pastes.lock().unwrap();+ assert_eq!(pasted.len(), 1, "exactly one paste");assert!(- calls- .iter()- .any(|c| c.contains("/agtx-plan") && c.contains("my task")),+ pasted[0].contains("/agtx-plan") && pasted[0].contains("my task"),"skill+prompt should be combined for cursor");// Only one Enter (cursor has no command picker)+ let calls = literal_calls.lock().unwrap();assert_eq!(calls.iter().filter(|c| c.as_str() == "Enter").count(),1,@@ -9577,11 +10206,13 @@ fn test_write_skills_to_worktree_cursor() {let dir = tempfile::tempdir().unwrap();let wt = dir.path().to_string_lossy().to_string();- write_skills_to_worktree(&wt, dir.path(), &None, &["cursor"]);+ write_skills_to_worktree(&wt, dir.path(), &None, &["cursor"], false);// Cursor uses subdirectories with SKILL.md (same structure as Codex)assert!(- dir.path().join(".cursor/skills/agtx-plan/SKILL.md").exists(),+ dir.path()+ .join(".cursor/skills/agtx-plan/SKILL.md")+ .exists(),".cursor/skills/agtx-plan/SKILL.md should exist");assert!(@@ -9605,11 +10236,7 @@ fn test_artifact_path_exists_zero_padded() {std::fs::write(phase_dir.join("PLAN.md"), "plan").unwrap();assert!(- artifact_path_exists(- &dir.path().to_string_lossy(),- "{phase}/PLAN.md",- 1- ),+ artifact_path_exists(&dir.path().to_string_lossy(), "{phase}/PLAN.md", 1),"should find zero-padded path 01/PLAN.md for cycle 1");}@@ -9623,11 +10250,7 @@ fn test_artifact_path_exists_non_padded_fallback() {std::fs::write(phase_dir.join("PLAN.md"), "plan").unwrap();assert!(- artifact_path_exists(- &dir.path().to_string_lossy(),- "{phase}/PLAN.md",- 1- ),+ artifact_path_exists(&dir.path().to_string_lossy(), "{phase}/PLAN.md", 1),"should fall back to non-padded path 1/PLAN.md when 01 is missing");}@@ -9641,19 +10264,11 @@ fn test_artifact_path_exists_cycle_2_zero_padded() {std::fs::write(phase_dir.join("PLAN.md"), "plan").unwrap();assert!(- artifact_path_exists(- &dir.path().to_string_lossy(),- "{phase}/PLAN.md",- 2- ),+ artifact_path_exists(&dir.path().to_string_lossy(), "{phase}/PLAN.md", 2),"cycle 2 should match 02/PLAN.md");assert!(- !artifact_path_exists(- &dir.path().to_string_lossy(),- "{phase}/PLAN.md",- 1- ),+ !artifact_path_exists(&dir.path().to_string_lossy(), "{phase}/PLAN.md", 1),"cycle 1 should not match 02/PLAN.md");}@@ -9665,19 +10280,11 @@ fn test_artifact_path_exists_no_phase_placeholder() {std::fs::write(dir.path().join("CONTEXT.md"), "ctx").unwrap();assert!(- artifact_path_exists(- &dir.path().to_string_lossy(),- "CONTEXT.md",- 1- ),+ artifact_path_exists(&dir.path().to_string_lossy(), "CONTEXT.md", 1),"should find plain file with no {{phase}} placeholder");assert!(- !artifact_path_exists(- &dir.path().to_string_lossy(),- "MISSING.md",- 1- ),+ !artifact_path_exists(&dir.path().to_string_lossy(), "MISSING.md", 1),"should return false for missing plain file");}@@ -9689,19 +10296,11 @@ fn test_artifact_path_exists_glob_pattern() {std::fs::write(dir.path().join("01-CONTEXT.md"), "ctx").unwrap();assert!(- artifact_path_exists(- &dir.path().to_string_lossy(),- "{phase}-CONTEXT.md",- 1- ),+ artifact_path_exists(&dir.path().to_string_lossy(), "{phase}-CONTEXT.md", 1),"wildcard pattern should match 01-CONTEXT.md for cycle 1");assert!(- !artifact_path_exists(- &dir.path().to_string_lossy(),- "{phase}-CONTEXT.md",- 2- ),+ !artifact_path_exists(&dir.path().to_string_lossy(), "{phase}-CONTEXT.md", 2),"wildcard pattern should not match cycle 2 when only cycle 1 file exists");}@@ -9715,11 +10314,7 @@ fn test_research_artifact_exists_no_plugin() {// No plugin β always falselet dir = tempfile::tempdir().unwrap();assert!(- !research_artifact_exists(- &dir.path().to_string_lossy(),- "task-123",- &None- ),+ !research_artifact_exists(&dir.path().to_string_lossy(), "task-123", &None),"no plugin should return false");}@@ -9738,11 +10333,7 @@ fn test_research_artifact_exists_no_artifact_in_plugin() {let dir = tempfile::tempdir().unwrap();assert!(- !research_artifact_exists(- &dir.path().to_string_lossy(),- "task-123",- &Some(plugin)- ),+ !research_artifact_exists(&dir.path().to_string_lossy(), "task-123", &Some(plugin)),"plugin with no research artifact should return false");}@@ -9766,11 +10357,7 @@ fn test_research_artifact_exists_file_present() {std::fs::write(planning_dir.join("task-123-CONTEXT.md"), "ctx").unwrap();assert!(- research_artifact_exists(- &dir.path().to_string_lossy(),- "task-123",- &Some(plugin)- ),+ research_artifact_exists(&dir.path().to_string_lossy(), "task-123", &Some(plugin)),"should find artifact when file matching {{task_id}} template exists");}@@ -9789,11 +10376,7 @@ fn test_research_artifact_exists_file_missing() {let dir = tempfile::tempdir().unwrap();assert!(- !research_artifact_exists(- &dir.path().to_string_lossy(),- "task-123",- &Some(plugin)- ),+ !research_artifact_exists(&dir.path().to_string_lossy(), "task-123", &Some(plugin)),"should return false when artifact file is missing");}@@ -9823,7 +10406,10 @@ fn test_deploy_skill_claude_transforms_frontmatter() {deploy_skill(dir.path(), "agtx-plan", content, "claude");let native = dir.path().join(".claude/commands/agtx/plan.md");- assert!(native.exists(), ".claude/commands/agtx/plan.md should be written");+ assert!(+ native.exists(),+ ".claude/commands/agtx/plan.md should be written"+ );let written = std::fs::read_to_string(&native).unwrap();assert!(written.contains("name: agtx:plan"),@@ -9839,10 +10425,19 @@ fn test_deploy_skill_gemini_writes_toml() {deploy_skill(dir.path(), "agtx-plan", content, "gemini");let native = dir.path().join(".gemini/commands/agtx/plan.toml");- assert!(native.exists(), ".gemini/commands/agtx/plan.toml should be written");+ assert!(+ native.exists(),+ ".gemini/commands/agtx/plan.toml should be written"+ );let written = std::fs::read_to_string(&native).unwrap();- assert!(written.contains("description"), "gemini toml should have description field");- assert!(written.contains("prompt"), "gemini toml should have prompt field");+ assert!(+ written.contains("description"),+ "gemini toml should have description field"+ );+ assert!(+ written.contains("prompt"),+ "gemini toml should have prompt field"+ );}#[test]@@ -9866,7 +10461,10 @@ fn test_deploy_skill_opencode_writes_flat_md() {deploy_skill(dir.path(), "agtx-plan", content, "opencode");let native = dir.path().join(".opencode/command/agtx-plan.md");- assert!(native.exists(), ".opencode/command/agtx-plan.md should be written");+ assert!(+ native.exists(),+ ".opencode/command/agtx-plan.md should be written"+ );let written = std::fs::read_to_string(&native).unwrap();assert!(written.starts_with("---\ndescription:"),@@ -9882,7 +10480,9 @@ fn test_deploy_skill_cursor_writes_skill_subdir() {deploy_skill(dir.path(), "agtx-plan", content, "cursor");assert!(- dir.path().join(".cursor/skills/agtx-plan/SKILL.md").exists(),+ dir.path()+ .join(".cursor/skills/agtx-plan/SKILL.md")+ .exists(),".cursor/skills/agtx-plan/SKILL.md should be written");}@@ -9922,7 +10522,10 @@ fn test_load_task_plugin_supported_agent_returns_plugin() {task.plugin = Some("agtx".to_string());// "agtx" bundled plugin has empty supported_agents (all supported)let plugin = load_task_plugin(&task, None, "claude");- assert!(plugin.is_some(), "agtx plugin should be returned for claude");+ assert!(+ plugin.is_some(),+ "agtx plugin should be returned for claude"+ );}#[test]@@ -9931,11 +10534,7 @@ fn test_load_task_plugin_unsupported_agent_returns_none_explicit() {use crate::db::Task;let dir = tempfile::tempdir().unwrap();- let plugin_dir = dir- .path()- .join(".agtx")- .join("plugins")- .join("gemini-only");+ let plugin_dir = dir.path().join(".agtx").join("plugins").join("gemini-only");std::fs::create_dir_all(&plugin_dir).unwrap();std::fs::write(plugin_dir.join("plugin.toml"),@@ -10042,7 +10641,12 @@ fn test_load_plugin_if_configured_unknown_plugin_falls_back_to_agtx() {#[test]fn test_resolve_skill_content_no_plugin_returns_default() {- let result = resolve_skill_content(&None, "agtx-plan", std::path::Path::new("/tmp"), "default content");+ let result = resolve_skill_content(+ &None,+ "agtx-plan",+ std::path::Path::new("/tmp"),+ "default content",+ );assert_eq!(result, "default content");}@@ -10062,23 +10666,22 @@ fn test_resolve_skill_content_plugin_override_on_disk() {).unwrap();- let plugin: WorkflowPlugin = toml::from_str(- "name = \"myplugin\"\n[commands]\n[prompts]\n[artifacts]\n",- )- .unwrap();+ let plugin: WorkflowPlugin =+ toml::from_str("name = \"myplugin\"\n[commands]\n[prompts]\n[artifacts]\n").unwrap();let result = resolve_skill_content(&Some(plugin), "agtx-plan", dir.path(), "default content");- assert_eq!(result, "custom plan skill", "plugin override should take precedence");+ assert_eq!(+ result, "custom plan skill",+ "plugin override should take precedence"+ );}#[test]fn test_resolve_skill_content_plugin_no_override_returns_default() {// Plugin configured but no custom skill file β returns defaultuse crate::config::WorkflowPlugin;- let plugin: WorkflowPlugin = toml::from_str(- "name = \"myplugin\"\n[commands]\n[prompts]\n[artifacts]\n",- )- .unwrap();+ let plugin: WorkflowPlugin =+ toml::from_str("name = \"myplugin\"\n[commands]\n[prompts]\n[artifacts]\n").unwrap();let result = resolve_skill_content(&Some(plugin),@@ -10086,7 +10689,10 @@ fn test_resolve_skill_content_plugin_no_override_returns_default() {std::path::Path::new("/nonexistent"),"default content",);- assert_eq!(result, "default content", "should fall back to default when no override on disk");+ assert_eq!(+ result, "default content",+ "should fall back to default when no override on disk"+ );}// =============================================================================@@ -10157,7 +10763,10 @@ fn test_wait_for_prompt_trigger_returns_false_on_timeout() {let tmux: std::sync::Arc<dyn TmuxOperations> = std::sync::Arc::new(mock);// Verify that the trigger IS found when present (positive case β complements the timeout)let result = wait_for_prompt_trigger(&tmux, "sess:win", "no trigger here", &[]);- assert!(result, "trigger present in first response should return true immediately");+ assert!(+ result,+ "trigger present in first response should return true immediately"+ );}#[test]@@ -10182,7 +10791,7 @@ fn test_wait_for_prompt_trigger_repeated_auto_dismiss() {Ok("Ready for input >".to_string())}});- mock.expect_send_keys_literal().returning(move |_, k| {+ mock.expect_send_key().returning(move |_, k| {if k == "y" {dismiss_c.fetch_add(1, std::sync::atomic::Ordering::SeqCst);}@@ -10287,7 +10896,7 @@ fn test_task_has_live_session_returns_false_on_tmux_error() {#[cfg(feature = "test-mocks")]fn test_handle_paste_into_shell_popup_calls_paste_text() {// When shell popup is open, handle_paste must call paste_text exactly once- // with the full pasted string (not send_keys_literal character by character).+ // with the full pasted string (not send_key character by character).let mut mock_tmux = MockTmuxOperations::new();mock_tmux.expect_window_exists().returning(|_| Ok(false));mock_tmux.expect_has_session().returning(|_| false);@@ -10324,7 +10933,7 @@ fn test_handle_paste_into_shell_popup_calls_paste_text() {#[test]#[cfg(feature = "test-mocks")]-fn test_handle_paste_into_shell_popup_does_not_call_send_keys_literal() {+fn test_handle_paste_into_shell_popup_does_not_call_send_key() {// Verify the old per-character path is not taken for paste events.let mut mock_tmux = MockTmuxOperations::new();mock_tmux.expect_window_exists().returning(|_| Ok(false));@@ -10334,8 +10943,8 @@ fn test_handle_paste_into_shell_popup_does_not_call_send_keys_literal() {.expect_paste_text().times(1).returning(|_, _| Ok(()));- // send_keys_literal must NOT be called β mockall panics if an unexpected call occurs- mock_tmux.expect_send_keys_literal().times(0);+ // send_key must NOT be called β mockall panics if an unexpected call occurs+ mock_tmux.expect_send_key().times(0);let mut app = App::new_for_test(Some(PathBuf::from("/tmp/test-project")),@@ -10420,9 +11029,7 @@ fn test_switch_to_project_reloads_config() {let mut mock_tmux = MockTmuxOperations::new();mock_tmux.expect_window_exists().returning(|_| Ok(false));mock_tmux.expect_has_session().returning(|_| false);- mock_tmux- .expect_create_session()- .returning(|_, _| Ok(()));+ mock_tmux.expect_create_session().returning(|_, _| Ok(()));// App starts with default config (no per-phase overrides)let mut app = App::new_for_test(@@ -10500,3 +11107,997 @@ fn dep_scroll_zero_visible_treated_as_one() {// Defensive: a zero viewport width must not panic (treated as 1 column).assert_eq!(clamp_scroll_to_selected(0, 5, 0, 10), 5);}++/// The generated `hooks` block must keep the MCP pre-trust key it shares the+/// file with, and every registered event must invoke `agtx hook`.+#[test]+#[cfg(feature = "test-mocks")]+fn test_write_skills_emits_a_valid_claude_hook_config() {+ let dir = tempfile::tempdir().unwrap();+ let wt = dir.path().to_string_lossy().to_string();+ write_skills_to_worktree(&wt, dir.path(), &None, &["claude"], true);++ let raw = std::fs::read_to_string(dir.path().join(".claude/settings.local.json")).unwrap();+ let v: serde_json::Value = serde_json::from_str(&raw).unwrap();++ assert_eq!(v["enableAllProjectMcpServers"], serde_json::json!(true));+ for event in [+ "SessionStart",+ "UserPromptSubmit",+ "PreToolUse",+ "PermissionRequest",+ "Notification",+ "Stop",+ "StopFailure",+ "SessionEnd",+ ] {+ let cmd = v["hooks"][event][0]["hooks"][0]["command"]+ .as_str()+ .unwrap_or_else(|| panic!("{} missing a command", event));+ assert!(+ cmd.contains("hook --env"),+ "{} must use the task-agnostic form: {}",+ event,+ cmd+ );+ }+ // Tool-scoped events need a matcher; lifecycle events must not have one.+ assert_eq!(+ v["hooks"]["PreToolUse"][0]["matcher"],+ serde_json::json!("*")+ );+ assert!(v["hooks"]["Stop"][0]["matcher"].is_null());+}++/// The toggle must remove the hooks entirely, restoring pre-hook behaviour.+#[test]+#[cfg(feature = "test-mocks")]+fn test_agent_hooks_false_writes_no_hooks() {+ let dir = tempfile::tempdir().unwrap();+ let wt = dir.path().to_string_lossy().to_string();+ write_skills_to_worktree(&wt, dir.path(), &None, &["claude"], false);++ let raw = std::fs::read_to_string(dir.path().join(".claude/settings.local.json")).unwrap();+ let v: serde_json::Value = serde_json::from_str(&raw).unwrap();++ assert_eq!(v["enableAllProjectMcpServers"], serde_json::json!(true));+ assert!(v.get("hooks").is_none());+}++// ββ first-launch dialog handling (wait_for_agent_ready) ββββββββββββββββββββββ++/// Regression: a native-binary agent changes `pane_current_command` the moment+/// it execs, so the process check used to break out of the readiness loop before+/// the dialog check below it ever ran. Observed live in a swebench container:+/// Claude sat on the bypass warning for 300s and the task prompt was typed into+/// the menu.+#[test]+#[cfg(feature = "test-mocks")]+fn test_dismiss_launch_dialog_answers_claude_bypass_warning() {+ let mut mock = MockTmuxOperations::new();+ let mut seq = mockall::Sequence::new();+ mock.expect_send_key()+ .times(1)+ .in_sequence(&mut seq)+ .withf(|_, k| k == "2")+ .returning(|_, _| Ok(()));+ mock.expect_send_key()+ .times(1)+ .in_sequence(&mut seq)+ .withf(|_, k| k == "Enter")+ .returning(|_, _| Ok(()));++ let ops: Arc<dyn TmuxOperations> = Arc::new(mock);+ assert!(dismiss_launch_dialog(+ &ops,+ "t:1",+ Some("claude"),+ "WARNING: Claude Code running in Bypass Permissions mode\n 1. No, exit\n 2. Yes, I accept",+ &mut LaunchDialogState::default(),+ ));+}++/// Claude's workspace-trust gate, shown *before* the bypass warning on the first+/// launch in any new directory β which is every task's worktree. Pane text+/// captured verbatim from claude 2.1.241; answered with "1" ("Yes, I trust this+/// folder"), not the "2" the bypass warning takes.+#[test]+#[cfg(feature = "test-mocks")]+fn test_dismiss_launch_dialog_answers_claude_workspace_trust() {+ let mut mock = MockTmuxOperations::new();+ let mut seq = mockall::Sequence::new();+ mock.expect_send_key()+ .times(1)+ .in_sequence(&mut seq)+ .withf(|_, k| k == "1")+ .returning(|_, _| Ok(()));+ mock.expect_send_key()+ .times(1)+ .in_sequence(&mut seq)+ .withf(|_, k| k == "Enter")+ .returning(|_, _| Ok(()));++ let ops: Arc<dyn TmuxOperations> = Arc::new(mock);+ assert!(dismiss_launch_dialog(+ &ops,+ "t:1",+ Some("claude"),+ "Accessing workspace:\n /tmp/wt/task-slug\n\n\+ Quick safety check: Is this a project you created or one you trust?\n\+ Claude Code'll be able to read, edit, and execute files here.\n\+ \u{276f} 1. Yes, I trust this folder\n 2. No, exit\n\+ Enter to confirm \u{b7} Esc to cancel",+ &mut LaunchDialogState::default(),+ ));+}++/// The two Claude gates are answered differently ("1" vs "2"), so a pane+/// showing one must never match the other's arm.+#[test]+#[cfg(feature = "test-mocks")]+fn test_claude_launch_dialogs_do_not_overlap() {+ let trust = "\u{276f} 1. Yes, I trust this folder\n 2. No, exit";+ let bypass = "WARNING: Claude Code running in Bypass Permissions mode\n 1. No, exit\n 2. Yes, I accept";+ let matches = |content: &str| -> Vec<&'static [&'static str]> {+ LAUNCH_DIALOGS+ .iter()+ .filter(|d| d.matches(content))+ .map(|d| d.answer)+ .collect()+ };+ assert_eq!(matches(trust), vec![&["1", "Enter"][..]], "trust dialog");+ assert_eq!(matches(bypass), vec![&["2", "Enter"][..]], "bypass dialog");+}++#[test]+#[cfg(feature = "test-mocks")]+fn test_dismiss_launch_dialog_answers_gemini_trust() {+ let mut mock = MockTmuxOperations::new();+ mock.expect_send_key()+ .times(2)+ .returning(|_, _| Ok(()));++ let ops: Arc<dyn TmuxOperations> = Arc::new(mock);+ assert!(dismiss_launch_dialog(+ &ops,+ "t:1",+ Some("gemini"),+ "Do you trust the files in this folder?",+ &mut LaunchDialogState::default(),+ ));+}++/// Ordinary agent output must never be mistaken for a dialog β a false positive+/// injects a stray "2" or "1" into the agent's composer.+#[test]+#[cfg(feature = "test-mocks")]+fn test_dismiss_launch_dialog_ignores_normal_output() {+ let mut mock = MockTmuxOperations::new();+ mock.expect_send_key().never();++ let ops: Arc<dyn TmuxOperations> = Arc::new(mock);+ assert!(!dismiss_launch_dialog(+ &ops,+ "t:1",+ None,+ "β― Claude Code\n Ask anything\nβ» Cooked for 3s",+ &mut LaunchDialogState::default(),+ ));+}++/// A dropped keystroke must be retried: an agent TUI that is not reading stdin+/// yet silently loses the answer. Observed in an emulated swebench container,+/// where a one-shot guard left Claude parked on the bypass warning.+#[test]+#[cfg(feature = "test-mocks")]+fn test_dismiss_launch_dialog_retries_while_the_pane_is_unchanged() {+ let mut mock = MockTmuxOperations::new();+ mock.expect_send_key()+ .times(4) // two rounds of ("2", Enter)+ .returning(|_, _| Ok(()));++ let ops: Arc<dyn TmuxOperations> = Arc::new(mock);+ let mut st = LaunchDialogState::default();+ let pane = "WARNING: Bypass Permissions mode\n 2. Yes, I accept";++ assert!(dismiss_launch_dialog(&ops, "t:1", None, pane, &mut st));+ assert!(+ dismiss_launch_dialog(&ops, "t:1", None, pane, &mut st),+ "an unchanged pane means the answer was dropped β retry"+ );+}++/// ...but once the pane redraws, the answer landed. Resending would type a+/// stray "2" into the agent's live composer, ahead of the task prompt.+#[test]+#[cfg(feature = "test-mocks")]+fn test_dismiss_launch_dialog_stops_once_the_pane_redraws() {+ let mut mock = MockTmuxOperations::new();+ mock.expect_send_key()+ .times(2) // exactly one round+ .returning(|_, _| Ok(()));++ let ops: Arc<dyn TmuxOperations> = Arc::new(mock);+ let mut st = LaunchDialogState::default();++ assert!(dismiss_launch_dialog(&ops, "t:1", None, "2. Yes, I accept", &mut st));+ // Same dialog text, but the frame changed β it is the previous render.+ assert!(!dismiss_launch_dialog(+ &ops,+ "t:1",+ None,+ "2. Yes, I accept\n(redrawing...)",+ &mut st+ ));+}++/// A pattern that matches something which is not really a dialog must not+/// hammer the pane forever.+#[test]+#[cfg(feature = "test-mocks")]+fn test_dismiss_launch_dialog_gives_up_after_max_attempts() {+ let mut mock = MockTmuxOperations::new();+ mock.expect_send_key()+ .times((LAUNCH_DIALOG_MAX_ATTEMPTS as usize) * 2)+ .returning(|_, _| Ok(()));++ let ops: Arc<dyn TmuxOperations> = Arc::new(mock);+ let mut st = LaunchDialogState::default();+ let pane = "2. Yes, I accept";++ for _ in 0..LAUNCH_DIALOG_MAX_ATTEMPTS {+ assert!(dismiss_launch_dialog(&ops, "t:1", None, pane, &mut st));+ }+ assert!(!dismiss_launch_dialog(&ops, "t:1", None, pane, &mut st));+}++/// The two dialogs are tracked independently β answering Claude's must not+/// suppress Gemini's, which can appear in the same launch after a restart.+#[test]+#[cfg(feature = "test-mocks")]+fn test_dismiss_launch_dialog_tracks_dialogs_independently() {+ let mut mock = MockTmuxOperations::new();+ mock.expect_send_key()+ .times(4)+ .returning(|_, _| Ok(()));++ let ops: Arc<dyn TmuxOperations> = Arc::new(mock);+ let mut answered = LaunchDialogState::default();+ assert!(dismiss_launch_dialog(&ops, "t:1", None, "2. Yes, I accept", &mut answered));+ assert!(dismiss_launch_dialog(+ &ops,+ "t:1",+ Some("gemini"),+ "Do you trust the files in this folder?",+ &mut answered+ ));+}++/// A project may ship its own `.claude/settings.local.json`, and agtx copies+/// `.claude/` into every worktree (AGENT_CONFIG_DIRS). The MCP/hook writer must+/// merge into that file, not replace it.+#[test]+#[cfg(feature = "test-mocks")]+fn test_write_skills_preserves_existing_claude_settings() {+ let dir = tempfile::tempdir().unwrap();+ let claude = dir.path().join(".claude");+ std::fs::create_dir_all(&claude).unwrap();+ // What the user's copied-in file might contain.+ std::fs::write(+ claude.join("settings.local.json"),+ r#"{+ "permissions": { "allow": ["Bash(cargo test:*)"] },+ "env": { "MY_VAR": "1" },+ "hooks": { "Stop": [{"hooks":[{"type":"command","command":"my-own-hook"}]}] }+ }"#,+ )+ .unwrap();++ let wt = dir.path().to_string_lossy().to_string();+ write_skills_to_worktree(&wt, dir.path(), &None, &["claude"], true);++ let raw = std::fs::read_to_string(claude.join("settings.local.json")).unwrap();+ let v: serde_json::Value = serde_json::from_str(&raw).unwrap();++ assert_eq!(v["permissions"]["allow"][0], "Bash(cargo test:*)", "permissions lost");+ assert_eq!(v["env"]["MY_VAR"], "1", "env lost");+ assert_eq!(v["enableAllProjectMcpServers"], serde_json::json!(true));+ // agtx's hooks must be present...+ assert!(v["hooks"]["SessionStart"][0]["hooks"][0]["command"]+ .as_str()+ .unwrap_or("")+ .contains("hook --env"));+ // ...without discarding the user's own hook on an event agtx also uses.+ let stop = v["hooks"]["Stop"].as_array().expect("Stop missing");+ let has_user_hook = stop.iter().any(|d| {+ d["hooks"].as_array().map_or(false, |h| {+ h.iter().any(|x| x["command"] == "my-own-hook")+ })+ });+ assert!(has_user_hook, "user's own Stop hook was discarded: {}", raw);+}++/// Re-deploying into an existing worktree (e.g. an agent switch) must replace+/// agtx's own hook entries, not append a second copy β duplicates would fire+/// `agtx hook` twice per event, forever.+#[test]+#[cfg(feature = "test-mocks")]+fn test_write_skills_is_idempotent_for_hooks() {+ let dir = tempfile::tempdir().unwrap();+ let wt = dir.path().to_string_lossy().to_string();++ write_skills_to_worktree(&wt, dir.path(), &None, &["claude"], true);+ write_skills_to_worktree(&wt, dir.path(), &None, &["claude"], true);+ write_skills_to_worktree(&wt, dir.path(), &None, &["claude"], true);++ let raw = std::fs::read_to_string(dir.path().join(".claude/settings.local.json")).unwrap();+ let v: serde_json::Value = serde_json::from_str(&raw).unwrap();+ for event in ["SessionStart", "Stop", "PreToolUse"] {+ assert_eq!(+ v["hooks"][event].as_array().map(|a| a.len()),+ Some(1),+ "{} accumulated duplicate hook entries",+ event+ );+ }+}++/// A corrupt settings file must not take the worktree down with it β agtx+/// starts fresh rather than refusing to deploy.+#[test]+#[cfg(feature = "test-mocks")]+fn test_write_skills_survives_corrupt_claude_settings() {+ let dir = tempfile::tempdir().unwrap();+ let claude = dir.path().join(".claude");+ std::fs::create_dir_all(&claude).unwrap();+ std::fs::write(claude.join("settings.local.json"), "{ not json").unwrap();++ let wt = dir.path().to_string_lossy().to_string();+ write_skills_to_worktree(&wt, dir.path(), &None, &["claude"], true);++ let raw = std::fs::read_to_string(claude.join("settings.local.json")).unwrap();+ let v: serde_json::Value = serde_json::from_str(&raw).unwrap();+ assert_eq!(v["enableAllProjectMcpServers"], serde_json::json!(true));+}++/// Under `skip_worktree` the "worktree" IS the project root, so every task+/// deploys into the *same* `.claude/settings.local.json`. The registered command+/// must therefore be task-agnostic: a per-task command would mean the last+/// deploy re-points every other task's agent at its own status file.+#[test]+#[cfg(feature = "test-mocks")]+fn test_skip_worktree_tasks_share_one_task_agnostic_hook() {+ let dir = tempfile::tempdir().unwrap();+ let root = dir.path().to_string_lossy().to_string();++ // Two tasks, same "worktree" (the project root).+ write_skills_to_worktree(&root, dir.path(), &None, &["claude"], true);+ write_skills_to_worktree(&root, dir.path(), &None, &["claude"], true);++ let raw = std::fs::read_to_string(dir.path().join(".claude/settings.local.json")).unwrap();+ let v: serde_json::Value = serde_json::from_str(&raw).unwrap();+ let stop = v["hooks"]["Stop"].as_array().unwrap();++ assert_eq!(stop.len(), 1, "deploys must not accumulate entries: {}", raw);+ let cmd = stop[0]["hooks"][0]["command"].as_str().unwrap();+ assert!(+ cmd.contains("hook --env"),+ "command must carry no task id, or tasks would clobber each other: {}",+ cmd+ );+}++// ββ binary-path drift ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ++/// Deploying records which binary did it, so the startup check is O(1) per task+/// instead of parsing seven config formats.+#[test]+#[cfg(feature = "test-mocks")]+fn test_deploy_writes_a_binary_marker() {+ let dir = tempfile::tempdir().unwrap();+ let wt = dir.path().to_string_lossy().to_string();+ write_skills_to_worktree(&wt, dir.path(), &None, &["claude"], true);++ let marker = read_deploy_marker(dir.path()).expect("marker missing");+ let current = std::env::current_exe().unwrap().to_string_lossy().to_string();+ assert_eq!(marker, current);+}++/// The regression this whole fix exists for: after the binary moves, agtx must+/// still recognise its own hook entries. A path-prefix matcher would not, and a+/// redeploy would keep the dead entry *and* add a live one.+#[test]+#[cfg(feature = "test-mocks")]+fn test_hooks_are_replaced_not_duplicated_after_the_binary_moves() {+ let dir = tempfile::tempdir().unwrap();+ let claude = dir.path().join(".claude");+ std::fs::create_dir_all(&claude).unwrap();+ // A deployment from a binary that no longer exists at that path.+ std::fs::write(+ claude.join("settings.local.json"),+ r#"{"hooks":{"Stop":[{"hooks":[{"type":"command",+ "command":"/old/gone/agtx hook --env claude"}]}]}}"#,+ )+ .unwrap();++ let wt = dir.path().to_string_lossy().to_string();+ write_skills_to_worktree(&wt, dir.path(), &None, &["claude"], true);++ let raw = std::fs::read_to_string(claude.join("settings.local.json")).unwrap();+ let v: serde_json::Value = serde_json::from_str(&raw).unwrap();+ let stop = v["hooks"]["Stop"].as_array().unwrap();++ assert_eq!(stop.len(), 1, "stale entry was not replaced: {}", raw);+ assert!(!raw.contains("/old/gone/agtx"), "dead path survived: {}", raw);+}++#[test]+#[cfg(feature = "test-mocks")]+fn test_is_agtx_hook_command_ignores_unrelated_hooks() {+ assert!(is_agtx_hook_command("/any/path/agtx hook --env claude"));+ assert!(is_agtx_hook_command("agtx hook --env claude"));+ assert!(!is_agtx_hook_command("my-own-linter --fix"));+ // A user hook that merely mentions agtx must not be treated as ours.+ assert!(!is_agtx_hook_command("echo agtx is running"));+}++/// Claude Code ~2.1 gates `--dangerously-skip-permissions` behind an interactive+/// acceptance. agtx always launches with that flag and every worktree is a fresh+/// directory, so the acceptance must be preflighted or the agent parks on the+/// dialog and the task prompt is typed into the menu.+#[test]+#[cfg(feature = "test-mocks")]+fn test_claude_settings_preflight_bypass_acceptance() {+ let dir = tempfile::tempdir().unwrap();+ let wt = dir.path().to_string_lossy().to_string();+ write_skills_to_worktree(&wt, dir.path(), &None, &["claude"], true);++ let raw = std::fs::read_to_string(dir.path().join(".claude/settings.local.json")).unwrap();+ let v: serde_json::Value = serde_json::from_str(&raw).unwrap();+ assert_eq!(v["bypassPermissionsModeAccepted"], serde_json::json!(true));+}++/// Deploying one skill for every supported agent lands at exactly these paths.+///+/// `deploy_skill` and+/// `write_skills_to_worktree` each carried their own copy of this layout branch+/// and had already drifted apart, so the layouts are pinned as literals here+/// rather than derived from the same table the code reads.+#[test]+fn test_deploy_skill_paths_for_every_agent() {+ let expected: &[(&str, &str)] = &[+ ("claude", ".claude/commands/agtx/plan.md"),+ ("copilot", ".github/agents/agtx/plan.md"),+ ("gemini", ".gemini/commands/agtx/plan.toml"),+ ("codex", ".codex/skills/agtx-plan/SKILL.md"),+ ("cursor", ".cursor/skills/agtx-plan/SKILL.md"),+ ("grok", ".grok/skills/agtx-plan/SKILL.md"),+ ("antigravity", ".agents/skills/agtx-plan/SKILL.md"),+ ("opencode", ".opencode/command/agtx-plan.md"),+ ];+ let content = "---\nname: agtx-plan\ndescription: Plan the work\n---\n\nbody\n";++ for (agent, rel) in expected {+ let dir = tempfile::tempdir().unwrap();+ deploy_skill(dir.path(), "agtx-plan", content, agent);++ let native = dir.path().join(rel);+ assert!(native.exists(), "{agent}: expected {rel}");+ assert!(+ !std::fs::read_to_string(&native).unwrap().is_empty(),+ "{agent}: {rel} is empty"+ );++ // The canonical copy is written for every agent, whatever the layout.+ assert!(+ dir.path().join(".agtx/skills/agtx-plan/SKILL.md").exists(),+ "{agent}: canonical copy missing"+ );+ }+}++/// Copilot declares `mcp_config: None` β agtx does not wire it to the MCP+/// server, so no config file should appear anywhere in its worktree. Guards the+/// new `Option<McpConfigKind>`: before it, "no MCP arm" and "an arm that does+/// nothing" were indistinguishable.+#[test]+fn test_write_skills_to_worktree_writes_no_mcp_config_for_copilot() {+ let dir = tempfile::tempdir().unwrap();+ let wt = dir.path().to_string_lossy().to_string();++ write_skills_to_worktree(&wt, dir.path(), &None, &["copilot"], false);++ // Its skills still deploy β only the MCP wiring is absent.+ assert!(dir.path().join(".github/agents/agtx/plan.md").exists());++ for absent in [+ ".mcp.json",+ "opencode.json",+ ".codex/config.toml",+ ".gemini/settings.json",+ ".cursor/mcp.json",+ ".grok/config.toml",+ ".agents/mcp_config.json",+ ] {+ assert!(+ !dir.path().join(absent).exists(),+ "copilot should get no MCP config, found {absent}"+ );+ }+}++/// `AGENT_COMMANDS` and `AGENT_ACTIVE_INDICATORS` are now derived from+/// `AGENT_SPECS`. These pin the *result* against the literals they replaced, so+/// the derivation is checked rather than assumed β a test that rebuilt them from+/// the same table would assert nothing.+#[test]+fn test_agent_commands_derivation_matches_the_previous_literals() {+ let mut got: Vec<&str> = AGENT_COMMANDS.to_vec();+ got.sort_unstable();+ let mut want = vec![+ "claude", "codex", "gemini", "copilot", "opencode", "agent", "grok", "agy",+ // Not agent binaries, but a Python entry point must not read as "shell".+ "python3", "python",+ ];+ want.sort_unstable();+ assert_eq!(got, want);+}++#[test]+fn test_active_indicator_derivation_matches_the_previous_literals() {+ let mut got: Vec<&str> = AGENT_ACTIVE_INDICATORS.to_vec();+ got.sort_unstable();+ let mut want = vec![+ "Claude Code", // Claude+ "Type your message", // Gemini+ "Ask anything", // OpenCode+ "Cursor Agent", // Cursor+ "OpenAI Codex", // Codex+ "Grok Build", // Grok β splash/footer+ "Shift+Tab:mode", // Grok β session footer once a turn has run+ // Antigravity, added after the smoke run found it had no readiness+ // signal at all: its npm wrapper reports `bash` in pane_current_command,+ // and its splash produces two pane changes where the stabilisation+ // fallback needs three. Its trust dialog's footer reads+ // "β/β Navigate Β· enter Confirm", so this cannot fire while blocked.+ "? for shortcuts",+ ];+ want.sort_unstable();+ assert_eq!(got, want);+}++/// The arm most easily lost in migration: an agent with no exit command must get+/// Ctrl+C, not a `/exit` typed into a TUI that does not understand it.+#[test]+fn test_exit_command_per_agent() {+ for (agent, want) in [+ ("claude", Some("/exit")),+ ("opencode", Some("/exit")),+ ("copilot", Some("/exit")),+ ("antigravity", Some("/exit")),+ ("gemini", Some("/quit")),+ ("grok", Some("/quit")),+ ("codex", None),+ ("cursor", None),+ ] {+ assert_eq!(+ crate::agent::spec(agent).unwrap().exit_command,+ want,+ "{agent}"+ );+ }+ // An agent agtx has never heard of keeps the historical default.+ assert!(crate::agent::spec("mistral").is_none());+}++/// Which send path each agent takes, pinned as literals. `Combined` is the+/// bracketed-paste path; `OpenCodePicker` is the one flow where the text must+/// arrive in two pieces by design.+#[test]+fn test_send_strategy_per_agent() {+ use crate::agent::SendStrategy;+ for (agent, want) in [+ ("claude", SendStrategy::Generic),+ ("copilot", SendStrategy::Generic),+ ("grok", SendStrategy::Generic),+ ("gemini", SendStrategy::Combined),+ ("codex", SendStrategy::Combined),+ ("cursor", SendStrategy::Combined),+ ("antigravity", SendStrategy::Combined),+ ("opencode", SendStrategy::OpenCodePicker),+ ] {+ assert_eq!(+ crate::agent::spec(agent).unwrap().send_strategy,+ want,+ "{agent}"+ );+ }+}++/// `/clear` is Claude-only today (issue #46). An agent with `None` must fall+/// through to a normal send rather than typing a command it does not understand+/// into its composer.+#[test]+fn test_clear_context_command_is_claude_only() {+ assert_eq!(+ crate::agent::spec("claude").unwrap().clear_context_command,+ Some("/clear")+ );+ for agent in ["codex", "gemini", "cursor", "antigravity", "opencode", "grok", "copilot"] {+ assert_eq!(+ crate::agent::spec(agent).unwrap().clear_context_command,+ None,+ "{agent}"+ );+ }+}++/// `LAUNCH_DIALOGS` is now derived from `AGENT_SPECS`. Pinned against the+/// literals it replaced, and asserting `Session`-scope dialogs stay out β they+/// are matched per agent, not against any pane.+#[test]+fn test_launch_dialog_derivation_matches_the_previous_literals() {+ let mut got: Vec<(Vec<&str>, Vec<&str>)> = LAUNCH_DIALOGS+ .iter()+ .map(|d| (d.patterns.to_vec(), d.answer.to_vec()))+ .collect();+ got.sort();+ // The first three are the literals this derivation replaced; the two codex+ // entries were added afterwards, each verified against codex-cli 0.144.5,+ // and antigravity's after its trust dialog was found parking every task.+ let mut want = vec![+ (vec!["Yes, I accept", "I accept the risk"], vec!["2", "Enter"]),+ (vec!["Yes, I trust this folder"], vec!["1", "Enter"]),+ (vec!["Do you trust the files in this folder?"], vec!["1", "Enter"]),+ (+ vec!["Do you trust the contents of this directory?"],+ vec!["1", "Enter"],+ ),+ (vec!["Update now (runs"], vec!["2", "Enter"]),+ // Enter alone: an arrow-navigated menu with the safe option preselected.+ (+ vec!["Do you trust the contents of this project?"],+ vec!["Enter"],+ ),+ // Cursor advertises its own access key, so that is what it is sent.+ (vec!["Workspace Trust Required"], vec!["a"]),+ ];+ want.sort();+ assert_eq!(got, want);++ // Codex's MCP approval is Session-scope and must not leak into the flat list:+ // there it would fire for any agent's pane, and during startup too.+ assert!(+ !LAUNCH_DIALOGS+ .iter()+ .any(|d| d.patterns.contains(&"MCP server to run tool")),+ "session dialogs must not be matched against any pane"+ );+}++/// Codex's mid-session MCP approval, previously hand-rolled in the refresh loop.+#[test]+#[cfg(feature = "test-mocks")]+fn test_answer_session_dialogs_handles_codex_mcp_approval() {+ let pane = "Allow the agtx MCP server to run tool get_task?\n 1. Yes 2. No 3. Always allow";++ let mut mock = MockTmuxOperations::new();+ let mut seq = mockall::Sequence::new();+ mock.expect_send_key()+ .times(1)+ .in_sequence(&mut seq)+ .withf(|_, k| k == "3")+ .returning(|_, _| Ok(()));+ mock.expect_send_key()+ .times(1)+ .in_sequence(&mut seq)+ .withf(|_, k| k == "Enter")+ .returning(|_, _| Ok(()));+ let ops: Arc<dyn TmuxOperations> = Arc::new(mock);+ answer_session_dialogs(&ops, "t:1", "codex", pane);+}++/// The same pane under a different agent must be left alone β session dialogs+/// are matched only against the agent that owns them.+#[test]+#[cfg(feature = "test-mocks")]+fn test_answer_session_dialogs_is_scoped_to_its_own_agent() {+ let pane = "Allow the agtx MCP server to run tool get_task?\n 3. Always allow";+ let mut mock = MockTmuxOperations::new();+ mock.expect_send_key().never();+ let ops: Arc<dyn TmuxOperations> = Arc::new(mock);+ answer_session_dialogs(&ops, "t:1", "claude", pane);+ answer_session_dialogs(&ops, "t:1", "mistral", pane);+}++/// All three patterns are required for the codex prompt: none is distinctive+/// enough alone, and a partial match would type a stray "3" into the composer.+#[test]+#[cfg(feature = "test-mocks")]+fn test_answer_session_dialogs_requires_every_pattern() {+ let mut mock = MockTmuxOperations::new();+ mock.expect_send_key().never();+ let ops: Arc<dyn TmuxOperations> = Arc::new(mock);+ answer_session_dialogs(&ops, "t:1", "codex", "Allow the tool to run? Always allow");+}++// =============================================================================+// Per-agent attribution of indicators and launch dialogs (open question 1)+// =============================================================================++/// Another agent's readiness string in this agent's pane no longer counts.+/// "Ask anything" is OpenCode's; a Claude pane showing it β in conversation+/// output, say β used to read as an agent being up.+#[test]+#[cfg(feature = "test-mocks")]+fn test_active_indicators_are_scoped_to_their_agent() {+ let mut mock = MockTmuxOperations::new();+ mock.expect_pane_current_command()+ .returning(|_| Some("zsh".to_string()));+ mock.expect_capture_pane()+ .returning(|_| Ok("some output mentioning Ask anything\n".to_string()));++ // OpenCode's own indicator still counts in an OpenCode pane.+ assert!(is_agent_active(&mock, "proj:task", Some("opencode")));+ // In a Claude pane it does not.+ assert!(!is_agent_active(&mock, "proj:task", Some("claude")));+ // An agent agtx has no spec for keeps the historical flat match, so such a+ // pane is not left undetectable.+ assert!(is_agent_active(&mock, "proj:task", None));+}++/// Answering a dialog sends a menu digit. Doing that in the wrong agent's pane+/// types a stray "1" into a live composer, so a dialog is only answered for the+/// agent that owns it.+#[test]+#[cfg(feature = "test-mocks")]+fn test_launch_dialogs_are_scoped_to_their_agent() {+ let gemini_pane = "Do you trust the files in this folder?\n 1. Yes 2. No";++ // In a Claude pane, Gemini's dialog is ignored.+ let mut mock = MockTmuxOperations::new();+ mock.expect_send_key().never();+ let ops: Arc<dyn TmuxOperations> = Arc::new(mock);+ assert!(!dismiss_launch_dialog(+ &ops,+ "t:1",+ Some("claude"),+ gemini_pane,+ &mut LaunchDialogState::default(),+ ));++ // In a Gemini pane it is answered.+ let mut mock2 = MockTmuxOperations::new();+ mock2.expect_send_key().times(2).returning(|_, _| Ok(()));+ let ops2: Arc<dyn TmuxOperations> = Arc::new(mock2);+ assert!(dismiss_launch_dialog(+ &ops2,+ "t:1",+ Some("gemini"),+ gemini_pane,+ &mut LaunchDialogState::default(),+ ));+}++/// An unknown agent keeps the flat behaviour: better to answer a dialog that may+/// not be its own than to leave the pane blocked forever.+#[test]+#[cfg(feature = "test-mocks")]+fn test_unknown_agent_falls_back_to_every_dialog() {+ let mut mock = MockTmuxOperations::new();+ mock.expect_send_key().times(2).returning(|_, _| Ok(()));+ let ops: Arc<dyn TmuxOperations> = Arc::new(mock);+ assert!(dismiss_launch_dialog(+ &ops,+ "t:1",+ None,+ "Do you trust the files in this folder?",+ &mut LaunchDialogState::default(),+ ));+}++/// Codex's own directory-trust dialog, worded differently from Claude's and+/// Gemini's so neither of their patterns catches it. Per directory, so it fires+/// on the first launch of every codex task. Captured verbatim from codex-cli+/// 0.144.5.+#[test]+#[cfg(feature = "test-mocks")]+fn test_dismiss_launch_dialog_answers_codex_directory_trust() {+ let pane = "> You are in /tmp/wt/task-slug\n \+ Do you trust the contents of this directory? Working with untrusted contents \+ comes with higher risk of prompt injection.\n\+ \u{203a} 1. Yes, continue\n 2. No, quit\n Press enter to continue";++ let mut mock = MockTmuxOperations::new();+ let mut seq = mockall::Sequence::new();+ mock.expect_send_key()+ .times(1)+ .in_sequence(&mut seq)+ .withf(|_, k| k == "1")+ .returning(|_, _| Ok(()));+ mock.expect_send_key()+ .times(1)+ .in_sequence(&mut seq)+ .withf(|_, k| k == "Enter")+ .returning(|_, _| Ok(()));++ let ops: Arc<dyn TmuxOperations> = Arc::new(mock);+ assert!(dismiss_launch_dialog(+ &ops,+ "t:1",+ Some("codex"),+ pane,+ &mut LaunchDialogState::default(),+ ));+}++/// The update prompt is answered "Skip", never "Update now" β agtx must not+/// upgrade a user's agent binary behind their back, but a blocked pane is worse+/// than a skipped update.+#[test]+#[cfg(feature = "test-mocks")]+fn test_dismiss_launch_dialog_skips_codex_update_prompt() {+ let pane = " \u{2728} Update available! 0.144.5 -> 0.147.0\n\+ \u{203a} 1. Update now (runs `sh -c 'curl -fsSL https://example/install.sh | sh'`)\n\+ 2. Skip\n 3. Skip until next version\n Press enter to continue";++ let mut mock = MockTmuxOperations::new();+ let mut seq = mockall::Sequence::new();+ mock.expect_send_key()+ .times(1)+ .in_sequence(&mut seq)+ .withf(|_, k| k == "2")+ .returning(|_, _| Ok(()));+ mock.expect_send_key()+ .times(1)+ .in_sequence(&mut seq)+ .withf(|_, k| k == "Enter")+ .returning(|_, _| Ok(()));++ let ops: Arc<dyn TmuxOperations> = Arc::new(mock);+ assert!(dismiss_launch_dialog(+ &ops,+ "t:1",+ Some("codex"),+ pane,+ &mut LaunchDialogState::default(),+ ));+}++/// Antigravity's trust dialog fires on the first launch in any directory, and+/// every task gets a new worktree. Leaving it unanswered did not leave the choice+/// to the user in any useful sense: agtx pasted the task into a menu that ignores+/// text, then sent the Enter that confirmed the dialog, so every antigravity task+/// arrived at an empty composer with its prompt gone. Verified against+/// antigravity 1.1.20.+///+/// It is answered with a **bare Enter**: the menu is arrow-navigated with "Yes, I+/// trust this folder" preselected, so a digit would be typed into the composer+/// that the Enter opens.+#[test]+#[cfg(feature = "test-mocks")]+fn test_antigravity_trust_dialog_is_answered_with_a_bare_enter() {+ let pane = "Do you trust the contents of this project?\n\+ > Yes, I trust this folder\n No, exit\n \u{2191}/\u{2193} Navigate \u{b7} enter Confirm";++ let keys = std::sync::Arc::new(std::sync::Mutex::new(Vec::<String>::new()));+ let keys_c = keys.clone();+ let mut mock = MockTmuxOperations::new();+ mock.expect_send_key().returning(move |_, k| {+ keys_c.lock().unwrap().push(k.to_string());+ Ok(())+ });+ let ops: Arc<dyn TmuxOperations> = Arc::new(mock);+ assert!(dismiss_launch_dialog(+ &ops,+ "t:1",+ Some("antigravity"),+ pane,+ &mut LaunchDialogState::default(),+ ));+ assert_eq!(*keys.lock().unwrap(), vec!["Enter".to_string()]);+}++/// Cursor's workspace-trust dialog asks *the same question as codex* β "Do you+/// trust the contents of this directory?" β so it is matched on its heading. It+/// went undeclared until the smoke run caught agtx answering it by accident: the+/// paste went into the menu and the follow-up Enter selected the highlighted row.+#[test]+#[cfg(feature = "test-mocks")]+fn test_cursor_workspace_trust_is_answered_with_its_access_key() {+ let pane = "\u{26a0} Workspace Trust Required\n\+ Cursor Agent can execute code and access files in this directory.\n\+ Do you trust the contents of this directory?\n\+ \u{25b6} [a] Trust this workspace\n [q] Quit\n\+ Use arrow keys to navigate, Enter to select, or press the key shown";++ let keys = std::sync::Arc::new(std::sync::Mutex::new(Vec::<String>::new()));+ let keys_c = keys.clone();+ let mut mock = MockTmuxOperations::new();+ mock.expect_send_key().returning(move |_, k| {+ keys_c.lock().unwrap().push(k.to_string());+ Ok(())+ });+ let ops: Arc<dyn TmuxOperations> = Arc::new(mock);+ assert!(dismiss_launch_dialog(+ &ops,+ "t:1",+ Some("cursor"),+ pane,+ &mut LaunchDialogState::default(),+ ));+ assert_eq!(*keys.lock().unwrap(), vec!["a".to_string()]);+}++/// ...and the shared question line must not make codex's entry fire in a cursor+/// pane, or vice versa: codex's answer is "1", which in cursor's dialog is not+/// an option at all.+#[test]+#[cfg(feature = "test-mocks")]+fn test_cursor_and_codex_trust_dialogs_do_not_cross_fire() {+ let cursor_pane = "\u{26a0} Workspace Trust Required\nDo you trust the contents of this directory?";+ // Codex's entry matches the shared question line β and its answer is "1",+ // which is not an option in cursor's menu at all. Scoping is what keeps it+ // from firing here, so this must be asserted against *codex*, not against an+ // agent that declares no matching dialog (which would pass vacuously).+ let codex_keys = std::sync::Arc::new(std::sync::Mutex::new(Vec::<String>::new()));+ let codex_keys_c = codex_keys.clone();+ let mut cursor_mock = MockTmuxOperations::new();+ cursor_mock.expect_send_key().returning(move |_, k| {+ codex_keys_c.lock().unwrap().push(k.to_string());+ Ok(())+ });+ let cursor_ops: Arc<dyn TmuxOperations> = Arc::new(cursor_mock);+ assert!(dismiss_launch_dialog(+ &cursor_ops,+ "t:1",+ Some("cursor"),+ cursor_pane,+ &mut LaunchDialogState::default(),+ ));+ assert_eq!(+ *codex_keys.lock().unwrap(),+ vec!["a".to_string()],+ "cursor's own answer, never codex's digit"+ );++ let mut mock = MockTmuxOperations::new();+ mock.expect_send_key().never();+ let ops: Arc<dyn TmuxOperations> = Arc::new(mock);+ // ...and cursor's heading is absent from codex's own dialog.+ let codex_pane = "Do you trust the contents of this directory?\n 1. Yes\n 2. No";+ let keys = std::sync::Arc::new(std::sync::Mutex::new(Vec::<String>::new()));+ let keys_c = keys.clone();+ let mut mock2 = MockTmuxOperations::new();+ mock2.expect_send_key().returning(move |_, k| {+ keys_c.lock().unwrap().push(k.to_string());+ Ok(())+ });+ let ops2: Arc<dyn TmuxOperations> = Arc::new(mock2);+ assert!(dismiss_launch_dialog(+ &ops2,+ "t:1",+ Some("cursor"),+ codex_pane,+ &mut LaunchDialogState::default(),+ ) == false);+}++/// The reverse of the scoping guard: antigravity's own wording must not be+/// answered in someone else's pane. Codex's differs by a single word+/// ("directory" vs "project"), so a sloppy pattern would cross-fire.+#[test]+#[cfg(feature = "test-mocks")]+fn test_antigravity_trust_dialog_is_scoped_to_antigravity() {+ let pane = "Do you trust the contents of this project?\n> Yes, I trust this folder";+ let mut mock = MockTmuxOperations::new();+ mock.expect_send_key().never();+ let ops: Arc<dyn TmuxOperations> = Arc::new(mock);+ assert!(!dismiss_launch_dialog(+ &ops,+ "t:1",+ Some("codex"),+ pane,+ &mut LaunchDialogState::default(),+ ));+}diff --git a/tests/agent_parity_tests.rs b/tests/agent_parity_tests.rsnew file mode 100644index 0000000..dcca9ba--- /dev/null+++ b/tests/agent_parity_tests.rs@@ -0,0 +1,609 @@+//! Byte-for-byte lock on every pure per-agent function, for all supported agents.+//!+//! Written against the behaviour that existed *before* the `AgentSpec` table,+//! and must not change value while that refactor proceeds: a diff in this file+//! is the signal that a launch string, skill path or command syntax silently+//! changed, which is exactly the failure mode this refactor risks β an agent+//! that still compiles and still starts, but misbehaves inside a worktree.+//!+//! Expected values are written as literals on purpose. Deriving them from the+//! same table the code reads would assert nothing.++use agtx::agent::{get_agent, known_agents, Agent, PromptInjection};+use agtx::skills::{agent_native_skill_dir, skill_dir_to_filename, transform_plugin_command};++/// Every agent agtx ships with. Parity is asserted for all of them, and the+/// list itself is asserted against `known_agents()` so adding an agent without+/// extending this file fails loudly.+const AGENTS: &[&str] = &[+ "claude",+ "codex",+ "copilot",+ "gemini",+ "opencode",+ "cursor",+ "grok",+ "antigravity",+];++fn agent(name: &str) -> Agent {+ get_agent(name).unwrap_or_else(|| panic!("{name} missing from known_agents()"))+}++/// An agent agtx has never heard of, exercising the generic fallback arms.+fn unknown() -> Agent {+ Agent::new(+ "mistral",+ "mistral-vibe",+ "Not a known agent",+ "Mistral <[email protected]>",+ )+}++#[test]+fn parity_covers_every_known_agent() {+ let known: Vec<String> = known_agents().into_iter().map(|a| a.name).collect();+ let covered: Vec<String> = AGENTS.iter().map(|s| s.to_string()).collect();+ assert_eq!(+ known, covered,+ "known_agents() changed β extend tests/agent_parity_tests.rs with the new agent \+ before migrating it"+ );+}++// =============================================================================+// build_interactive_command+// =============================================================================++#[test]+fn interactive_command_parity_without_prompt() {+ let expected: &[(&str, &str)] = &[+ ("claude", "claude --dangerously-skip-permissions"),+ ("codex", "codex --sandbox workspace-write"),+ ("copilot", "copilot --allow-all-tools"),+ (+ "gemini",+ "GEMINI_TRUST_WORKSPACE=true gemini --approval-mode yolo",+ ),+ ("opencode", "opencode"),+ ("cursor", "agent --yolo"),+ ("grok", "grok --yolo --trust"),+ (+ "antigravity",+ "agy --dangerously-skip-permissions --mode accept-edits",+ ),+ ];+ for (name, want) in expected {+ assert_eq!(&agent(name).build_interactive_command(""), want, "{name}");+ }+ assert_eq!(unknown().build_interactive_command(""), "mistral-vibe");+}++#[test]+fn interactive_command_parity_with_prompt() {+ let expected: &[(&str, &str)] = &[+ ("claude", "claude --dangerously-skip-permissions 'hi'"),+ ("codex", "codex --sandbox workspace-write 'hi'"),+ // `-i` keeps the session interactive; `-p` is print mode and exits,+ // which killed every copilot task until it was fixed. Do not "simplify"+ // this back to `-p`.+ ("copilot", "copilot --allow-all-tools -i 'hi'"),+ (+ "gemini",+ "GEMINI_TRUST_WORKSPACE=true gemini --approval-mode yolo -i 'hi'",+ ),+ ("opencode", "opencode -p 'hi'"),+ ("cursor", "agent --yolo 'hi'"),+ ("grok", "grok --yolo --trust 'hi'"),+ (+ "antigravity",+ "agy --dangerously-skip-permissions --mode accept-edits -i 'hi'",+ ),+ ];+ for (name, want) in expected {+ assert_eq!(&agent(name).build_interactive_command("hi"), want, "{name}");+ }+ assert_eq!(+ unknown().build_interactive_command("hi"),+ "mistral-vibe 'hi'"+ );+}++#[test]+fn interactive_command_escapes_single_quotes_for_every_agent() {+ // The command is wrapped in `sh -c '...'` downstream, so a prompt quote must+ // survive as the POSIX '"'"' idiom for every agent, including the fallback.+ for name in AGENTS.iter().copied() {+ let cmd = agent(name).build_interactive_command("it's");+ assert!(+ cmd.ends_with(r#"'it'"'"'s'"#),+ "{name} lost single-quote escaping: {cmd}"+ );+ }+ assert!(unknown()+ .build_interactive_command("it's")+ .ends_with(r#"'it'"'"'s'"#));+}++// =============================================================================+// build_resume_command+// =============================================================================++#[test]+fn resume_command_parity() {+ let expected: &[(&str, &str)] = &[+ ("claude", "claude --dangerously-skip-permissions --continue"),+ // Codex resume *replaces* the launch flags rather than appending to+ // them: there is no `--sandbox` here.+ ("codex", "codex resume --last"),+ ("copilot", "copilot --allow-all-tools --continue"),+ (+ "gemini",+ "GEMINI_TRUST_WORKSPACE=true gemini --approval-mode yolo --resume",+ ),+ ("opencode", "opencode --continue"),+ ("cursor", "agent --yolo --continue"),+ ("grok", "grok --yolo --trust --continue"),+ (+ "antigravity",+ "agy --dangerously-skip-permissions --mode accept-edits --continue",+ ),+ ];+ for (name, want) in expected {+ assert_eq!(&agent(name).build_resume_command(), want, "{name}");+ }+ // Unknown agents have no resume form and fall back to a bare launch.+ assert_eq!(unknown().build_resume_command(), "mistral-vibe");+}++// =============================================================================+// headless (print) invocation β generate_text+// =============================================================================++#[test]+fn headless_invocation_parity() {+ let expected: &[(&str, &str, &[&str])] = &[+ ("claude", "claude", &["--print"]),+ ("codex", "codex", &["exec", "--sandbox", "workspace-write"]),+ ("copilot", "copilot", &["-p"]),+ ("gemini", "gemini", &["-p"]),+ ("opencode", "opencode", &[]),+ ("cursor", "agent", &["--print", "--yolo"]),+ ("grok", "grok", &["-p"]),+ ("antigravity", "agy", &["-p"]),+ ];+ for (name, bin, flags) in expected {+ let a = agent(name);+ let (cmd, args) = a.headless_invocation("PROMPT");+ assert_eq!(&cmd, bin, "{name} binary");+ let mut want: Vec<&str> = flags.to_vec();+ want.push("PROMPT");+ assert_eq!(args, want, "{name} args");+ }+ let fallback = unknown();+ let (cmd, args) = fallback.headless_invocation("PROMPT");+ assert_eq!(cmd, "mistral-vibe");+ assert_eq!(args, vec!["PROMPT"]);+}++#[test]+fn headless_invocation_does_not_carry_launch_env() {+ // Gemini's GEMINI_TRUST_WORKSPACE belongs to the interactive launch only;+ // headless runs never touch the workspace. Locked because the table makes+ // it tempting to apply `env` uniformly.+ let gemini = agent("gemini");+ let (cmd, _) = gemini.headless_invocation("PROMPT");+ assert_eq!(cmd, "gemini");+}++// =============================================================================+// prompt_injection β which agents take the opening message at launch+// =============================================================================++/// Which agents may take the opening message at launch.+///+/// Each `Argv`/`FlagInteractive` entry below was checked against the real binary+/// in a scratch worktree: the skill command had to expand, the skill body had to+/// run, and the session had to stay usable afterwards. Everything else keeps the+/// send-after-ready path β guessing here silently swallows the task text.+#[test]+fn prompt_injection_parity() {+ let verified: &[(&str, PromptInjection)] = &[+ // claude 2.1.241+ ("claude", PromptInjection::Argv),+ // codex-cli 0.144.5+ ("codex", PromptInjection::Argv),+ // Grok 4.6+ ("grok", PromptInjection::Argv),+ ];+ for (name, want) in verified {+ assert_eq!(agent(name).prompt_injection(), *want, "{name}");+ }++ let unverified = ["copilot", "gemini", "opencode", "cursor", "antigravity"];+ for name in unverified {+ assert_eq!(+ agent(name).prompt_injection(),+ PromptInjection::Unknown,+ "{name} must stay unverified until checked against the real binary"+ );+ }+ // antigravity is the interesting one: `agy β¦ -i` *does* deliver the prompt,+ // but the session is then parked on its trust dialog, which agtx does not+ // answer by design. Delivering into a blocked session is not a working lane.++ assert_eq!(+ verified.len() + unverified.len(),+ AGENTS.len(),+ "every agent must be classified"+ );+ assert_eq!(unknown().prompt_injection(), PromptInjection::Unknown);+}++// =============================================================================+// agent_native_skill_dir+// =============================================================================++#[test]+fn native_skill_dir_parity() {+ let expected: &[(&str, Option<(&str, &str)>)] = &[+ ("claude", Some((".claude/commands", "agtx"))),+ ("codex", Some((".codex/skills", ""))),+ ("copilot", Some((".github/agents", "agtx"))),+ ("gemini", Some((".gemini/commands", "agtx"))),+ ("opencode", Some((".opencode/command", ""))),+ ("cursor", Some((".cursor/skills", ""))),+ ("grok", Some((".grok/skills", ""))),+ // Vendor-neutral tree, not an agent dotdir.+ ("antigravity", Some((".agents/skills", ""))),+ ];+ for (name, want) in expected {+ assert_eq!(agent_native_skill_dir(name), *want, "{name}");+ }+ assert_eq!(agent_native_skill_dir("mistral"), None);+}++#[test]+fn native_skill_dirs_are_relative_and_contained() {+ for name in AGENTS.iter().copied() {+ let (base, _) = agent_native_skill_dir(name).unwrap();+ assert!(!base.starts_with('/'), "{name}: {base} must be relative");+ assert!(!base.contains(".."), "{name}: {base} must stay in-worktree");+ }+}++// =============================================================================+// skill_dir_to_filename+// =============================================================================++#[test]+fn skill_filename_parity() {+ let expected: &[(&str, &str)] = &[+ ("claude", "plan.md"),+ ("codex", "plan.md"),+ ("copilot", "plan.md"),+ ("gemini", "plan.toml"),+ // Flat directory, so the full prefixed name is the filename.+ ("opencode", "agtx-plan.md"),+ ("cursor", "plan.md"),+ ("grok", "plan.md"),+ ("antigravity", "plan.md"),+ ];+ for (name, want) in expected {+ assert_eq!(&skill_dir_to_filename("agtx-plan", name), want, "{name}");+ }+ assert_eq!(skill_dir_to_filename("agtx-plan", "mistral"), "plan.md");+ // A name without the agtx- prefix is passed through unshortened.+ assert_eq!(skill_dir_to_filename("custom", "claude"), "custom.md");+ assert_eq!(skill_dir_to_filename("custom", "gemini"), "custom.toml");+ assert_eq!(skill_dir_to_filename("custom", "opencode"), "custom.md");+}++// =============================================================================+// transform_plugin_command+// =============================================================================++#[test]+fn plugin_command_parity() {+ let expected: &[(&str, Option<&str>)] = &[+ ("claude", Some("/gsd:plan-phase 1")),+ ("codex", Some("$gsd-plan-phase 1")),+ // Quirk-lock: copilot has no interactive skill invocation, so it gets a+ // file-path reference instead. Giving it a syntax here is a behaviour+ // change, not a migration.+ ("copilot", None),+ ("gemini", Some("/gsd:plan-phase 1")),+ ("opencode", Some("/gsd-plan-phase 1")),+ ("cursor", Some("/gsd-plan-phase 1")),+ ("grok", Some("/gsd-plan-phase 1")),+ ("antigravity", Some("/gsd-plan-phase 1")),+ ];+ for (name, want) in expected {+ assert_eq!(+ transform_plugin_command("/gsd:plan-phase 1", name).as_deref(),+ *want,+ "{name}"+ );+ }+ assert_eq!(+ transform_plugin_command("/gsd:plan-phase 1", "mistral"),+ None+ );+}++#[test]+fn plugin_command_replaces_only_the_first_colon() {+ // Arguments may contain colons; only the namespace separator is rewritten.+ assert_eq!(+ transform_plugin_command("/gsd:plan a:b", "grok").as_deref(),+ Some("/gsd-plan a:b")+ );+ assert_eq!(+ transform_plugin_command("/gsd:plan a:b", "codex").as_deref(),+ Some("$gsd-plan a:b")+ );+}++// =============================================================================+// identity+// =============================================================================++#[test]+fn identity_parity() {+ let expected: &[(&str, &str, &str, &str)] = &[+ (+ "claude",+ "claude",+ "Anthropic's Claude Code CLI",+ "Claude <[email protected]>",+ ),+ (+ "codex",+ "codex",+ "OpenAI's Codex CLI",+ "Codex <[email protected]>",+ ),+ (+ "copilot",+ "copilot",+ "GitHub Copilot CLI",+ "GitHub Copilot <[email protected]>",+ ),+ (+ "gemini",+ "gemini",+ "Google Gemini CLI",+ "Gemini <[email protected]>",+ ),+ (+ "opencode",+ "opencode",+ "AI-powered coding assistant",+ "OpenCode <[email protected]>",+ ),+ (+ "cursor",+ "agent",+ "Cursor Agent CLI",+ "Cursor Agent <[email protected]>",+ ),+ (+ "grok",+ "grok",+ "xAI's Grok Build CLI",+ "Grok <[email protected]>",+ ),+ (+ "antigravity",+ "agy",+ "Google's Antigravity CLI",+ "Antigravity <[email protected]>",+ ),+ ];+ for (name, binary, description, co_author) in expected {+ let a = agent(name);+ assert_eq!(&a.command, binary, "{name} binary");+ assert_eq!(&a.description, description, "{name} description");+ assert_eq!(&a.co_author, co_author, "{name} co-author");+ }+}++// =============================================================================+// scan_agent_skills β discovery of an agent's pre-existing skills+// =============================================================================++fn write(root: &std::path::Path, rel: &str, body: &str) {+ let path = root.join(rel);+ std::fs::create_dir_all(path.parent().unwrap()).unwrap();+ std::fs::write(path, body).unwrap();+}++const MD_SKILL: &str = "---\ndescription: Plan the work\n---\n\nbody\n";++#[test]+fn scan_agent_skills_parity() {+ // One project carrying every agent's layout at once, so each assertion also+ // proves an agent scans *only* its own tree.+ let tmp = tempfile::tempdir().unwrap();+ let root = tmp.path();+ write(root, ".claude/commands/agtx/plan.md", MD_SKILL);+ write(root, ".github/agents/agtx/plan.md", MD_SKILL);+ write(+ root,+ ".gemini/commands/agtx/plan.toml",+ "description = \"Plan the work\"\n\nprompt = \"\"\"\nbody\n\"\"\"\n",+ );+ write(root, ".codex/skills/agtx-plan/SKILL.md", MD_SKILL);+ write(root, ".cursor/skills/agtx-plan/SKILL.md", MD_SKILL);+ write(root, ".grok/skills/agtx-plan/SKILL.md", MD_SKILL);+ write(root, ".agents/skills/agtx-plan/SKILL.md", MD_SKILL);+ // OpenCode's project commands live under .config/, not in the tree agtx+ // deploys into (.opencode/command). Both are written here to lock which one+ // the scan reads.+ write(root, ".config/opencode/command/agtx-plan.md", "body\n");+ write(root, ".opencode/command/ignored.md", "body\n");++ let expected: &[(&str, &[(&str, &str)])] = &[+ ("claude", &[("/agtx:plan", "Plan the work")]),+ ("codex", &[("$agtx-plan", "Plan the work")]),+ // Copilot cannot invoke a skill interactively, but its skills are still+ // discovered and offered by the `/` picker.+ ("copilot", &[("/agtx:plan", "Plan the work")]),+ ("gemini", &[("/agtx:plan", "Plan the work")]),+ // Flat layout reads no frontmatter: the description is the stem.+ ("opencode", &[("/agtx-plan", "agtx plan")]),+ ("cursor", &[("/agtx-plan", "Plan the work")]),+ ("grok", &[("/agtx-plan", "Plan the work")]),+ ("antigravity", &[("/agtx-plan", "Plan the work")]),+ ];+ for (name, want) in expected {+ let got = agtx::skills::scan_agent_skills(name, root);+ let want: Vec<(String, String)> = want+ .iter()+ .map(|(c, d)| (c.to_string(), d.to_string()))+ .collect();+ assert_eq!(got, want, "{name}");+ }+ assert!(agtx::skills::scan_agent_skills("mistral", root).is_empty());+}++#[test]+fn scan_agent_skills_falls_back_to_the_name_without_frontmatter() {+ let tmp = tempfile::tempdir().unwrap();+ let root = tmp.path();+ write(+ root,+ ".claude/commands/agtx/plan-phase.md",+ "no frontmatter\n",+ );+ write(+ root,+ ".grok/skills/agtx-plan-phase/SKILL.md",+ "no frontmatter\n",+ );+ assert_eq!(+ agtx::skills::scan_agent_skills("claude", root),+ vec![("/agtx:plan-phase".to_string(), "plan phase".to_string())]+ );+ // The skill-directory layout falls back to the full directory name, which+ // still carries the `agtx-` prefix.+ assert_eq!(+ agtx::skills::scan_agent_skills("grok", root),+ vec![(+ "/agtx-plan-phase".to_string(),+ "agtx plan phase".to_string()+ )]+ );+}++#[test]+fn scan_agent_skills_is_sorted_and_skips_malformed_entries() {+ let tmp = tempfile::tempdir().unwrap();+ let root = tmp.path();+ write(root, ".claude/commands/agtx/zeta.md", MD_SKILL);+ write(root, ".claude/commands/agtx/alpha.md", MD_SKILL);+ // Wrong extension, and a loose file where a namespace directory belongs.+ write(root, ".claude/commands/agtx/notes.txt", MD_SKILL);+ write(root, ".claude/commands/stray.md", MD_SKILL);+ // A skill directory without a SKILL.md is not a skill.+ std::fs::create_dir_all(root.join(".grok/skills/empty")).unwrap();++ let commands: Vec<String> = agtx::skills::scan_agent_skills("claude", root)+ .into_iter()+ .map(|(c, _)| c)+ .collect();+ assert_eq!(commands, vec!["/agtx:alpha", "/agtx:zeta"]);+ assert!(agtx::skills::scan_agent_skills("grok", root).is_empty());+}++// =============================================================================+// Prompt normalization and the launch-lane size cap+// =============================================================================++use agtx::agent::spec::{can_launch_with_prompt, normalize_prompt, MAX_LAUNCH_PROMPT_BYTES};++#[test]+fn shell_metacharacters_survive_as_literal_text() {+ // The command is wrapped in `sh -c 'β¦'`, so anything that could end the+ // quoted word or start a substitution must come back out verbatim. This is+ // the case that turns a task description into executed code if it regresses.+ let nasty = r#"fix `rm -rf /` and $(whoami) and ${HOME} and "quotes" and it's"#;+ let cmd = agent("claude").build_interactive_command(nasty);++ // Exactly one opening quote, and the payload is escaped, not interpreted.+ assert!(cmd.starts_with("claude --dangerously-skip-permissions '"));+ assert!(cmd.ends_with('\''));+ assert!(cmd.contains("`rm -rf /`"), "backticks kept literal: {cmd}");+ assert!(+ cmd.contains("$(whoami)"),+ "substitution kept literal: {cmd}"+ );+ assert!(cmd.contains("${HOME}"), "expansion kept literal: {cmd}");+ // Every single quote from the input is escaped by the POSIX idiom; no bare+ // quote can appear except the two wrapping ones.+ let inner = &cmd["claude --dangerously-skip-permissions '".len()..cmd.len() - 1];+ for (i, _) in inner.match_indices('\'') {+ let around = &inner[i.saturating_sub(2)..(i + 3).min(inner.len())];+ assert!(+ around.contains(r#"'"'"#) || around.contains(r#""'"#),+ "unescaped quote at {i} in {inner:?}"+ );+ }+}++#[test]+fn newlines_and_tabs_survive_normalization() {+ // Ordinary structure in a task description, and just bytes inside a quoted+ // argv word β plan D phase 4 depends on them reaching the agent intact.+ let text = "line one\n\n- bullet\n\tindented";+ assert_eq!(normalize_prompt(text), text);+ assert!(agent("claude")+ .build_interactive_command(text)+ .contains("\n\n- bullet"));+}++#[test]+fn normalization_strips_characters_that_cannot_survive_argv() {+ // NUL truncates the C string, silently dropping the rest of the task.+ assert_eq!(normalize_prompt("before\u{0}after"), "beforeafter");+ // CR is a paste artifact from CRLF sources; it would move the agent's cursor+ // to column zero and corrupt the echoed prompt.+ assert_eq!(+ normalize_prompt("line one\r\nline two"),+ "line one\nline two"+ );+ // ESC would let pasted text drive the agent's TUI.+ assert_eq!(normalize_prompt("plain\u{1b}[31mred"), "plain[31mred");+ // A prompt of nothing but control characters collapses to empty, which the+ // launch check then treats as "no prompt".+ assert_eq!(normalize_prompt("\u{0}\r\u{1b}"), "");+}++#[test]+fn launch_lane_is_declined_for_oversized_prompts() {+ use agtx::agent::PromptInjection;++ let ok = "x".repeat(MAX_LAUNCH_PROMPT_BYTES);+ let too_big = "x".repeat(MAX_LAUNCH_PROMPT_BYTES + 1);++ assert!(can_launch_with_prompt(PromptInjection::Argv, &ok));+ assert!(+ !can_launch_with_prompt(PromptInjection::Argv, &too_big),+ "oversized prompts must fall back to the mid-session lane"+ );+ // Unverified agents never take the lane, whatever the size.+ assert!(!can_launch_with_prompt(PromptInjection::Unknown, &ok));+ // Neither does an empty prompt β there would be nothing to deliver.+ assert!(!can_launch_with_prompt(PromptInjection::Argv, ""));+}++#[test]+fn the_size_cap_is_counted_in_bytes_not_chars() {+ use agtx::agent::PromptInjection;+ // `execve` counts bytes. A multi-byte character must not let a prompt slip+ // past the cap by being counted as one.+ let wide = "Γ©".repeat(MAX_LAUNCH_PROMPT_BYTES); // 2 bytes each+ assert!(wide.chars().count() <= MAX_LAUNCH_PROMPT_BYTES);+ assert!(wide.len() > MAX_LAUNCH_PROMPT_BYTES);+ assert!(!can_launch_with_prompt(PromptInjection::Argv, &wide));+}diff --git a/tests/agent_tests.rs b/tests/agent_tests.rsindex 8ed5f6e..bba969d 100644--- a/tests/agent_tests.rs+++ b/tests/agent_tests.rs@@ -198,12 +198,20 @@ fn test_build_orchestrator_command_claude_is_idempotent() {"must register under a unique name, not bare `agtx`:\n{cmd}");- // The JSON's wrapping single quotes must be escaped (`'\''`) so the command- // survives create_window's outer `sh -c '...'` layer. A bare `'{json}'` would- // break out of that wrapper and mangle the JSON.+ // The JSON is a plainly single-quoted word. It used to be pre-escaped as+ // `'\''{json}'\''` because `create_window` interpolated this command raw into+ // `sh -c 'β¦'`; that wrapper now quotes what it is given, so pre-escaping here+ // double-escapes and the pane dies on an unterminated quote before+ // `add-json` ever runs. The end-to-end guarantee β the JSON reaching `claude`+ // as one intact argument through both layers β is asserted in+ // `tmux::operations::tests::the_orchestrator_command_reaches_claude_with_its_json_intact`.assert!(- cmd.contains(r"'\''"),- "JSON quotes must be escaped for the outer sh -c wrapper:\n{cmd}"+ !cmd.contains(r"'\''"),+ "JSON quotes must not be pre-escaped; the tmux wrapper quotes this command:\n{cmd}"+ );+ assert!(+ cmd.contains(r#"add-json agtx-orchestrator '{"type":"stdio"}'"#),+ "JSON must be a plainly single-quoted word:\n{cmd}");let pre_section = &cmd[..add_idx];diff --git a/tests/hook_status_tests.rs b/tests/hook_status_tests.rsnew file mode 100644index 0000000..bcd18a6--- /dev/null+++ b/tests/hook_status_tests.rs@@ -0,0 +1,342 @@+//! Tests for agent-reported hook status (`src/agent/hook_status.rs`).+//!+//! Event names and payload shapes here were captured from a live+//! `claude -p` run (Claude Code 2.1.241), not assumed.++use agtx::agent::hook_status::{+ map_claude_event, merge_event, read_status, status_path, write_status, AgentHookStatus,+ HookState, BLOCKED_GUARD_SECS, HOOK_STALE_SECS,+};+use std::path::Path;+use tempfile::TempDir;++fn status(state: HookState, ts: i64) -> AgentHookStatus {+ AgentHookStatus {+ ts,+ state,+ session_id: None,+ transcript_path: None,+ message: None,+ tool: None,+ agent: "claude".to_string(),+ }+}++// ββ event mapping βββββββββββββββββββββββββββββββββββββββββββββββββββ++#[test]+fn maps_every_registered_claude_event() {+ assert_eq!(map_claude_event("SessionStart"), Some(HookState::Working));+ assert_eq!(+ map_claude_event("UserPromptSubmit"),+ Some(HookState::Working)+ );+ assert_eq!(map_claude_event("PreToolUse"), Some(HookState::Working));+ assert_eq!(+ map_claude_event("PermissionRequest"),+ Some(HookState::Blocked)+ );+ assert_eq!(map_claude_event("Notification"), Some(HookState::Blocked));+ assert_eq!(map_claude_event("Stop"), Some(HookState::Waiting));+ assert_eq!(map_claude_event("StopFailure"), Some(HookState::Waiting));+ assert_eq!(map_claude_event("SessionEnd"), Some(HookState::Ended));+}++#[test]+fn unknown_event_carries_no_transition() {+ // Unregistered events must leave the stored record alone rather than+ // resetting it β agents emit events we do not subscribe to.+ assert_eq!(map_claude_event("PostToolUse"), None);+ assert_eq!(map_claude_event("PreCompact"), None);+ assert_eq!(map_claude_event(""), None);+}++/// The exact sequence a real `claude -p` turn emits, verified against+/// Claude Code 2.1.241.+#[test]+fn real_turn_sequence_walks_working_to_ended() {+ let states: Vec<_> = [+ "SessionStart",+ "UserPromptSubmit",+ "PreToolUse",+ "Stop",+ "SessionEnd",+ ]+ .iter()+ .map(|e| map_claude_event(e).unwrap())+ .collect();++ assert_eq!(+ states,+ vec![+ HookState::Working,+ HookState::Working,+ HookState::Working,+ HookState::Waiting,+ HookState::Ended,+ ]+ );+}++// ββ persistence βββββββββββββββββββββββββββββββββββββββββββββββββββββ++#[test]+fn write_then_read_round_trips() {+ let dir = TempDir::new().unwrap();+ let mut s = status(HookState::Working, 1_000);+ s.session_id = Some("abc-123".into());+ s.tool = Some("Write".into());++ write_status(dir.path(), "task1", &s).unwrap();+ let back = read_status(dir.path(), "task1", 1_000).unwrap();++ assert_eq!(back, s);+}++#[test]+fn missing_file_reads_as_none() {+ let dir = TempDir::new().unwrap();+ assert!(read_status(dir.path(), "nope", 0).is_none());+}++#[test]+fn corrupt_json_reads_as_none_without_panicking() {+ let dir = TempDir::new().unwrap();+ let path = status_path(dir.path(), "task1");+ std::fs::create_dir_all(path.parent().unwrap()).unwrap();+ std::fs::write(&path, "{ this is not json").unwrap();++ assert!(read_status(dir.path(), "task1", 0).is_none());+}++#[test]+fn write_leaves_no_temp_file_behind() {+ let dir = TempDir::new().unwrap();+ write_status(dir.path(), "task1", &status(HookState::Working, 1)).unwrap();++ let entries: Vec<_> = std::fs::read_dir(dir.path().join(".agtx/status"))+ .unwrap()+ .map(|e| e.unwrap().file_name().to_string_lossy().to_string())+ .collect();++ assert_eq!(entries, vec!["task1.json"]);+}++#[test]+fn status_path_is_scoped_by_task_id() {+ // Under skip_worktree every task shares one directory, so the filename+ // is the only thing keeping their records apart.+ let a = status_path(Path::new("/wt"), "task-a");+ let b = status_path(Path::new("/wt"), "task-b");+ assert_ne!(a, b);+ assert!(a.ends_with(".agtx/status/task-a.json"));+}++// ββ staleness βββββββββββββββββββββββββββββββββββββββββββββββββββββββ++#[test]+fn stale_working_record_is_distrusted() {+ let dir = TempDir::new().unwrap();+ write_status(dir.path(), "task1", &status(HookState::Working, 1_000)).unwrap();++ let just_inside = 1_000 + HOOK_STALE_SECS;+ let past_it = just_inside + 1;++ assert!(read_status(dir.path(), "task1", just_inside).is_some());+ assert!(+ read_status(dir.path(), "task1", past_it).is_none(),+ "a Working record older than HOOK_STALE_SECS must fall back to the pane heuristic"+ );+}++#[test]+fn only_working_decays() {+ // A blocked agent stays blocked indefinitely; so does a finished one.+ // Decaying these would silently resurrect the heuristic they replaced.+ let dir = TempDir::new().unwrap();+ let ancient = 1_000 + HOOK_STALE_SECS * 10;++ for state in [HookState::Blocked, HookState::Waiting, HookState::Ended] {+ write_status(dir.path(), "task1", &status(state, 1_000)).unwrap();+ assert!(+ read_status(dir.path(), "task1", ancient).is_some(),+ "{:?} must not decay",+ state+ );+ }+}++// ββ merge rules βββββββββββββββββββββββββββββββββββββββββββββββββββββ++#[test]+fn blocked_survives_an_immediate_pretooluse() {+ // Claude emits PreToolUse for the very tool it is requesting permission+ // for. Without this guard the block clears itself instantly.+ let blocked = status(HookState::Blocked, 1_000);+ let merged = merge_event(+ Some(&blocked),+ "PreToolUse",+ 1_000 + BLOCKED_GUARD_SECS,+ "claude",+ None,+ None,+ None,+ Some("Bash".into()),+ );+ assert!(merged.is_none(), "Working must not clobber a fresh Blocked");+}++#[test]+fn blocked_yields_to_work_once_the_guard_expires() {+ let blocked = status(HookState::Blocked, 1_000);+ let merged = merge_event(+ Some(&blocked),+ "PreToolUse",+ 1_000 + BLOCKED_GUARD_SECS + 1,+ "claude",+ None,+ None,+ None,+ None,+ );+ assert_eq!(merged.unwrap().state, HookState::Working);+}++#[test]+fn stop_does_not_clobber_a_blocked_record() {+ // Only Working is guarded β a real Stop after a permission denial is a+ // genuine transition and must land.+ let blocked = status(HookState::Blocked, 1_000);+ let merged = merge_event(+ Some(&blocked),+ "Stop",+ 1_000,+ "claude",+ None,+ None,+ None,+ None,+ );+ assert_eq!(merged.unwrap().state, HookState::Waiting);+}++#[test]+fn session_identity_carries_across_events() {+ // SessionStart reports the id; a later event that omits it must not+ // erase it, or resume-by-id has nothing to resume.+ let start = merge_event(+ None,+ "SessionStart",+ 1_000,+ "claude",+ Some("sess-1".into()),+ Some("/t.jsonl".into()),+ None,+ None,+ )+ .unwrap();++ let stop = merge_event(+ Some(&start),+ "Stop",+ 1_010,+ "claude",+ None,+ None,+ None,+ None,+ )+ .unwrap();++ assert_eq!(stop.session_id.as_deref(), Some("sess-1"));+ assert_eq!(stop.transcript_path.as_deref(), Some("/t.jsonl"));+}++#[test]+fn blocked_reason_is_kept_and_cleared_with_the_block() {+ let blocked = merge_event(+ None,+ "PermissionRequest",+ 1_000,+ "claude",+ None,+ None,+ Some("Allow Bash(rm -rf /)?".into()),+ None,+ )+ .unwrap();+ assert_eq!(blocked.message.as_deref(), Some("Allow Bash(rm -rf /)?"));++ // Once the agent moves on the stale reason must not linger on the card.+ let working = merge_event(+ Some(&blocked),+ "UserPromptSubmit",+ 1_100,+ "claude",+ None,+ None,+ None,+ None,+ )+ .unwrap();+ assert_eq!(working.message, None);+}++#[test]+fn untrusted_message_text_is_bounded_and_stripped() {+ // Hook payloads are untrusted input that reaches the TUI; control+ // characters would corrupt the rendered card.+ let hostile = format!("bad\u{1b}[31mescape{}", "x".repeat(5_000));+ let merged = merge_event(+ None,+ "Notification",+ 1,+ "claude",+ None,+ None,+ Some(hostile),+ None,+ )+ .unwrap();++ let msg = merged.message.unwrap();+ assert!(msg.chars().count() <= 512);+ assert!(!msg.contains('\u{1b}'));+}++#[test]+fn unknown_event_produces_no_record() {+ assert!(merge_event(None, "PostToolUse", 1, "claude", None, None, None, None).is_none());+}++// ββ env routing (agtx hook --env) ββββββββββββββββββββββββββββββββββββ++/// The hook must be inert when the env vars are absent, so a future+/// user-global registration cannot hijack the user's own agent sessions.+#[test]+fn env_mode_is_a_noop_without_the_task_env() {+ std::env::remove_var("AGTX_TASK_ID");+ std::env::remove_var("AGTX_WORKTREE");+ // Returns Ok and writes nothing; a failing hook must never break a turn.+ assert!(agtx::agent::hook_status::run_hook_cli(&["--env".to_string()]).is_ok());+}++/// A backgrounded agent task inherits the pane's env, so it would otherwise+/// report status against the task that spawned it.+#[test]+fn env_mode_ignores_background_workers() {+ let dir = TempDir::new().unwrap();+ std::env::set_var("AGTX_TASK_ID", "t-bg");+ std::env::set_var("AGTX_WORKTREE", dir.path());+ std::env::set_var("CLAUDE_JOB_DIR", "/tmp/job");++ let _ = agtx::agent::hook_status::run_hook_cli(&["--env".to_string()]);++ std::env::remove_var("CLAUDE_JOB_DIR");+ std::env::remove_var("AGTX_TASK_ID");+ std::env::remove_var("AGTX_WORKTREE");+ assert!(+ read_status(dir.path(), "t-bg", 0).is_none(),+ "a background worker must not write status for its parent task"+ );+}diff --git a/tests/mock_infrastructure_tests.rs b/tests/mock_infrastructure_tests.rsindex d343f07..3f2a65a 100644--- a/tests/mock_infrastructure_tests.rs+++ b/tests/mock_infrastructure_tests.rs@@ -119,7 +119,7 @@ fn test_tmux_session_management() {mock_tmux.expect_create_window().times(1)- .returning(|_, _, _, _, _| Ok(()));+ .returning(|_, _, _, _, _, _| Ok(()));// Session exists after creationmock_tmux@@ -140,6 +140,7 @@ fn test_tmux_session_management() {"/home/user/project/.agtx/worktrees/task-1",None,true,+ &[],).unwrap();assert!(mock_tmux.has_session("my-project"));diff --git a/tests/smoke/README.md b/tests/smoke/README.mdnew file mode 100644index 0000000..bf48eae--- /dev/null+++ b/tests/smoke/README.md@@ -0,0 +1,120 @@+# Per-agent smoke tests++Does a real agent binary actually receive its work?++Nothing else in the tree answers that. The unit suite mocks `TmuxOperations`, so it pins what agtx+*sends* and by construction cannot catch "the agent ignored it". `tests/agent_parity_tests.rs` pins+launch strings as literals, which proves agtx builds the string it used to build, not that any binary+accepts it. Three silent-hang bugs found by hand in a single session lived in exactly that gap β all+of the same shape: **the prompt was delivered and then never read**.++```sh+cargo build --release++tests/smoke/agent_smoke.py # installed agents x the agtx plugin+tests/smoke/agent_smoke.py --agents claude,codex+tests/smoke/agent_smoke.py --agents claude --plugins all --force-unsupported+tests/smoke/agent_smoke.py --phases planning,running,review --json out.json+```++Opt-in, never CI: it needs real agent auth and spends real tokens. Run it before a release, or after+touching the send path. A full pass is ~60-70s per (agent, plugin) case.++## What each phase asserts++| # | Check | Passes when |+|---|---|---|+| 1 | `submitted` | the resolved skill command reached the agent as a *submitted message*, not text parked in a composer |+| 2 | `skill-ran` | the marker file contains the **task id** that was passed in β argument substitution, not merely "a skill fired" |+| 3 | `artifact` | the phase artifact appeared, and agtx moved the task to the next status |+| 4 | `usable` | the agent process is alive and no dialog is on screen |++Check 4 is the one that matters most. Antigravity's skill *ran* and wrote its file while the session+sat blocked on an unanswered trust dialog: a harness that only asserted output would have certified+it green.++Check 1 reports `?` when the command text is not visible in the pane β several TUIs redraw their+scrollback, and check 2 catches a genuinely undelivered command anyway. It reports `β` for copilot,+which has no interactive slash-command syntax at all.++## Outcomes++| Outcome | Meaning |+|---|---|+| `PASS` | every applicable check passed for every phase |+| `FAIL` | a check failed; the report prints which, plus the last 20 pane lines and the scratch repo path |+| `SKIP` | the case was **not tested** β agent not installed, plugin needs project setup, agent not in the plugin's `supported_agents` |+| `PARK` | delivered its work and *then* parked on a dialog agtx does not answer (see below) |+| `QUOTA` | the agent hit a usage limit β a known park, not a send-path bug |+| `AUTH` | the case failed and the pane shows a login prompt |+| `ERROR` | the harness itself could not complete the case (MCP timeout, tmux failure) |++Skips are printed in a block of their own at the end, listing every untested case with its reason. A+green run that quietly tested two of eight agents is worse than no run, because it invites the+assumption that the other six work.++Exit code is 1 if anything is `FAIL` or `ERROR`, 0 otherwise.++## How it works++```+scratch git repo (one commit) βββΊ agtx TUI in tmux -L agtx-smoke+ β β+ β .agtx/config.toml pins the agent β spawns the agent on tmux -L agtx+ βΌ βΌ+ agtx mcp-serve <repo> βββ create_task / move_task / get_task ββ the runner+```++Phases are driven through **agtx's own MCP server**, exactly as `benchmark/swebench/benchmark.py`+does. Reimplementing skill deployment or phase transitions in the runner would test the runner.++The agent Γ plugin matrix is not duplicated here: `cargo run --example agent_matrix` dumps+`AGENT_SPECS` and `BUNDLED_PLUGINS` as JSON β binaries, dialogs, liveness signals, per-agent command+syntax (through the real `transform_plugin_command`), artifacts. The runner reads that, so it cannot+drift from what agtx actually does. Its source is `agent_matrix.rs` in this directory, declared as an+`[[example]]` with an explicit path: an example rather than a bin so `cargo install` never ships it,+and still compiled by `cargo test` so a new spec field breaks the build instead of the runner.++### Dialogs are never pre-answered++All three motivating bugs were dialog bugs. A harness that made itself reliable by writing+`hasTrustDialogAccepted`, passing `--trust`, or copying `~/.claude.json` would have been green+through every one of them. The scratch repo gets `agtx trust` β that is agtx's *project config*+trust, which gates plugin init scripts β and nothing else. No agent trust state is seeded.++### The fixture++The task is "write this one file and stop", costing a few hundred tokens per phase. The marker+carries the task id rather than fixed text, because a skill that runs but drops its argument is a+real failure mode.++Each phase artifact is written with one line pointing at `.agtx/smoke/INSTRUCTIONS.md`, which the+runner drops in the worktree. This is not decoration: agtx's `execute` skill says, in as many words,+*"if `.agtx/plan.md` exists, read it β do NOT call `get_task`"*, and the agtx plugin clears the+agent's context between phases. An artifact containing `smoke` strands the running phase with no idea+what it was asked for. Pointing at a file carries the fixture forward through the same mechanism the+plugin uses to carry a plan forward.++## Testing the harness++```sh+python3 tests/smoke/test_agent_smoke.py+```++Deterministic β no tmux, no agent binaries, no auth. Covers the two paths whose failure would make+the harness lie: an uninstalled agent must report `skipped` and never `pass`, and a case that never+delivers must report a failure carrying pane output rather than hanging.++One test needs `cargo`, because it cross-checks the runner's list of dialogs *agtx does not answer*+against the ones `AGENT_SPECS` declares β a pattern must not be on both lists, and it was, once. It+skips rather than fails without a toolchain.++## Known limits++- The matrix runs cases sequentially. Parallelism would need one tmux server and one project DB per+ case, which is doable but not worth it at ~60s per case.+- `--plugins all` reaches plugins that need `npx`, a framework install, or a `.specify`/`openspec`+ directory in the project root. Those are skipped by default with a reason derived from the plugin's+ own TOML; `--force-unsupported` runs them anyway, with the network cost that implies.+- The `void` plugin sends the agent nothing by design, so it is always skipped: there is no delivery+ to observe.diff --git a/tests/smoke/agent_matrix.rs b/tests/smoke/agent_matrix.rsnew file mode 100644index 0000000..5bd5b07--- /dev/null+++ b/tests/smoke/agent_matrix.rs@@ -0,0 +1,173 @@+//! Dump the agent Γ plugin matrix as JSON, for the smoke runner.+//!+//! `agent_smoke.py`, next to this file, needs to know per agent: the binary to look+//! for on `PATH`, the dialogs agtx answers, how a skill command is spelled, and+//! how the agent's liveness is detected. Every one of those is already declared+//! in [`agtx::agent::AGENT_SPECS`], so the runner reads it from here rather than+//! keeping a second copy that can drift.+//!+//! The resolved commands are produced by the real+//! [`agtx::skills::transform_plugin_command`], so the syntax the runner looks+//! for in a pane is the syntax agtx actually sends.+//!+//! ```sh+//! cargo run --quiet --example agent_matrix+//! ```+//!+//! Placeholders (`{task}`, `{task_id}`, `{phase}`) are left unsubstituted: they+//! are runtime values the runner fills in.++use agtx::agent::{spec, AGENT_SPECS};+use agtx::skills::{transform_plugin_command, BUNDLED_PLUGINS};+use serde_json::{json, Map, Value};++/// Phases the runner can drive. `preresearch` is deliberately absent: it is a+/// one-time project-setup step, not a task phase.+const PHASES: &[&str] = &["research", "planning", "running", "review"];++fn command_for(plugin: &agtx::config::WorkflowPlugin, phase: &str) -> Option<String> {+ match phase {+ "research" => plugin.commands.research.clone(),+ "planning" => plugin.commands.planning.clone(),+ "running" => plugin.commands.running.clone(),+ "review" => plugin.commands.review.clone(),+ _ => None,+ }+}++fn prompt_for(plugin: &agtx::config::WorkflowPlugin, phase: &str) -> Option<String> {+ match phase {+ "research" => plugin.prompts.research.clone(),+ "planning" => plugin.prompts.planning.clone(),+ "running" => plugin.prompts.running.clone(),+ "review" => plugin.prompts.review.clone(),+ _ => None,+ }+}++fn artifact_for(plugin: &agtx::config::WorkflowPlugin, phase: &str) -> Option<String> {+ match phase {+ "research" => plugin.artifacts.research.clone(),+ "planning" => plugin.artifacts.planning.clone(),+ "running" => plugin.artifacts.running.clone(),+ "review" => plugin.artifacts.review.clone(),+ _ => None,+ }+}++fn main() {+ let plugins: Vec<(String, agtx::config::WorkflowPlugin)> = BUNDLED_PLUGINS+ .iter()+ .filter_map(|(name, _, content)| {+ toml::from_str::<agtx::config::WorkflowPlugin>(content)+ .ok()+ .map(|p| (name.to_string(), p))+ })+ .collect();++ let mut agents = Vec::new();+ for s in AGENT_SPECS {+ // The command syntax the runner should expect to see in the pane, per+ // plugin and phase. `None` means the agent has no interactive skill+ // invocation (copilot), so nothing command-shaped is ever sent.+ let mut commands = Map::new();+ for (plugin_name, plugin) in &plugins {+ let mut per_phase = Map::new();+ for phase in PHASES {+ if let Some(canonical) = command_for(plugin, phase) {+ let resolved = transform_plugin_command(&canonical, s.name);+ per_phase.insert(+ phase.to_string(),+ match resolved {+ Some(cmd) => Value::String(cmd),+ None => Value::Null,+ },+ );+ }+ }+ commands.insert(plugin_name.clone(), Value::Object(per_phase));+ }++ let dialogs: Vec<Value> = s+ .dialogs+ .iter()+ .map(|d| {+ json!({+ "patterns": d.patterns,+ "require_all": d.require_all,+ "answer": d.answer,+ "scope": match d.scope {+ spec::DialogScope::Launch => "launch",+ spec::DialogScope::Session => "session",+ },+ })+ })+ .collect();++ agents.push(json!({+ "name": s.name,+ "binary": s.binary,+ "description": s.description,+ "launch_prompt_verified": s.launch_prompt_verified,+ "prompt_form": match s.prompt_form {+ spec::PromptForm::Argv => Value::String("argv".into()),+ spec::PromptForm::Flag(f) => Value::String(format!("flag:{f}")),+ },+ "send_strategy": match s.send_strategy {+ spec::SendStrategy::Generic => "generic",+ spec::SendStrategy::Combined => "combined",+ spec::SendStrategy::OpenCodePicker => "opencode_picker",+ },+ "command_syntax": match s.command_syntax {+ spec::CommandSyntax::Colon => "colon",+ spec::CommandSyntax::Hyphen => "hyphen",+ spec::CommandSyntax::Dollar => "dollar",+ spec::CommandSyntax::None => "none",+ },+ "process_names": s.process_names,+ "active_indicators": s.active_indicators,+ "dialogs": dialogs,+ "commands": commands,+ }));+ }++ let plugin_json: Vec<Value> = plugins+ .iter()+ .map(|(name, p)| {+ let mut artifacts = Map::new();+ let mut phase_commands = Map::new();+ let mut phase_prompts = Map::new();+ for phase in PHASES {+ if let Some(a) = artifact_for(p, phase) {+ artifacts.insert(phase.to_string(), Value::String(a));+ }+ if let Some(c) = command_for(p, phase) {+ phase_commands.insert(phase.to_string(), Value::String(c));+ }+ if let Some(pr) = prompt_for(p, phase) {+ phase_prompts.insert(phase.to_string(), Value::String(pr));+ }+ }+ json!({+ "name": name,+ "description": p.description,+ "supported_agents": p.supported_agents,+ "init_script": p.init_script,+ "copy_dirs": p.copy_dirs,+ "copy_files": p.copy_files,+ "cyclic": p.cyclic,+ "clear_context_on_advance": p.clear_context_on_advance,+ "artifacts": artifacts,+ "commands": phase_commands,+ "prompts": phase_prompts,+ })+ })+ .collect();++ let out = json!({+ "phases": PHASES,+ "agents": agents,+ "plugins": plugin_json,+ });+ println!("{}", serde_json::to_string_pretty(&out).unwrap());+}diff --git a/tests/smoke/agent_smoke.py b/tests/smoke/agent_smoke.pynew file mode 100755index 0000000..ac9a1a9--- /dev/null+++ b/tests/smoke/agent_smoke.py@@ -0,0 +1,1301 @@+#!/usr/bin/env python3+"""Per-agent smoke tests: does a real agent binary actually receive its work?++Rationale, decisions and findings: see README.md next to this file. The short+version: three silent-hang bugs were found by hand in one session, all of the same shape+β the prompt was delivered and then never read. None was catchable by the unit+suite, which mocks tmux, or by the parity tests, which pin the strings agtx+builds. They live in the gap between agtx and a real agent binary.++Per phase this asserts, in order:++ 1. command submitted the resolved skill command reached the agent as a+ submitted message, not as text parked in a composer+ 2. skill ran a marker file contains the task id that was passed in,+ proving argument substitution rather than "a skill fired"+ 3. artifact + advance the phase artifact appeared and agtx moved the task on+ 4. session usable the agent process is alive and no dialog is on screen++Check 4 is the one that matters most: antigravity's skill *ran* and wrote its+file while the session sat blocked on an unanswered trust dialog. A harness that+only asserts output would have certified it green.++Never pre-answers dialogs and never pre-seeds trust for the agent under test.+All three bugs were dialog bugs; a harness that made itself reliable by writing+`hasTrustDialogAccepted` would have been green through every one of them.++Usage:+ tests/smoke/agent_smoke.py # installed agents x agtx plugin+ tests/smoke/agent_smoke.py --agents claude,codex+ tests/smoke/agent_smoke.py --agents claude --plugins all+ tests/smoke/agent_smoke.py --phases planning,running,review --json out.json++Requires: a built agtx binary (cargo build --release), tmux, git, cargo, and+real agent auth. Spends real tokens β opt-in, never CI.+"""++from __future__ import annotations++import argparse+import json+import os+import queue+import re+import shlex+import shutil+import subprocess+import sys+import tempfile+import threading+import time+from dataclasses import dataclass, field+from glob import glob+from pathlib import Path+from typing import Any, Iterable++REPO_ROOT = Path(__file__).resolve().parents[2]++# The tmux server the runner starts TUIs on. agtx spawns agent windows on its+# own `agtx` server; keeping the TUIs elsewhere means killing ours never takes+# an agent pane with it.+TUI_SERVER = "agtx-smoke"+AGENT_SERVER = "agtx"++# Phases the runner can drive, in order. Research is deliberately absent: it runs+# in place on a Backlog task and is a different transition shape.+ORDERED_PHASES = ["planning", "running", "review"]+PHASE_STATUS = {"planning": "planning", "running": "running", "review": "review"}++# Dialogs agtx does **not** answer, so they never appear in AGENT_SPECS. Check 4+# exists to catch exactly this class: a session that took the prompt and then+# parked, or one where agtx's own Enter answered a menu by accident.+#+# Antigravity's "Do you trust the contents of this project?" used to head this+# list, with a note that agtx deliberately left it to the user. This runner is+# what proved that reasoning wrong β the session did not wait for the user, it+# swallowed the paste and took agtx's Enter as the answer β so the dialog is+# declared now and comes from AGENT_SPECS like the rest. Anything left here is a+# prompt no agent claims; add to it rather than assuming a blocked pane is fine.+UNHANDLED_DIALOG_PATTERNS = [+ "Press Enter to continue",+ "Press any key to continue",+ "[y/N]",+ "[Y/n]",+]++# Agents known to park on a dialog agtx does not answer. A case that delivers its+# work and *then* parks is reported as `expected-park`, not `pass` and not+# `fail`: the delivery worked, the session is unusable, and both facts matter.+#+# **Empty, and that is the point.** It held `antigravity` for exactly one run.+# The harness then reported the entry as stale β the agent passed cleanly once+# agtx learned to answer its trust dialog β which is the guard the plan asked for+# (open question 4) doing its job: an expectation that encodes today's behaviour+# must announce itself the moment today's behaviour improves, or it silently+# becomes the specification.+EXPECTED_PARK_AGENTS: set[str] = set()++# A usage-limit park is a known failure mode of long agent runs and is not a bug+# in the send path. Reported distinctly so it never shows up as a red column.+#+# Narrow on purpose. A bare "usage limit" matched Codex's startup tip ("You have+# 1 usage limit reset available"), turning a live session into a QUOTA row and+# hiding a real delivery failure underneath it. Every pattern here must describe+# a limit that has actually been *hit*.+QUOTA_PATTERNS = [+ # Covers Claude's "You've hit your session limit" and Grok's "You hit your+ # free usage limit." β same sentence, different agents, different wording.+ r"You(?:'ve)? hit your [\w ]*limit",+ r"usage limit (reached|exceeded)",+ r"rate limit (reached|exceeded)",+ r"quota exceeded",+ r"Press .* to continue after reset",+ r"upgrade to increase your usage limit",+]++# Only consulted to explain an already-failing case β an unauthenticated agent+# looks exactly like an undelivered prompt from the outside.+AUTH_PATTERNS = [+ r"Sign in to",+ r"Please log in",+ r"/login",+ r"not authenticated",+ r"(No|Invalid|missing) API key",+ # Gemini's wording, and the machine-readable reason next to it. Both are+ # unambiguous credential rejections β unlike its own "This request failed"+ # summary line, which is generic and would launder real failures if matched.+ r"API key not valid",+ r"API_KEY_INVALID",+ # A provider misconfiguration reads exactly like an undelivered prompt from+ # the outside: the command was submitted, the model call failed, no artifact+ # appeared. opencode on Amazon Bedrock with no AWS credentials produced this+ # and the case was reported as a send-path FAIL until the pattern was added.+ r"requires AWS credentials",+ r"access key ID setting is missing",+ r"authentication (failed|error)",+ # Gemini's first-run OAuth prompt. agtx deliberately does not answer it β an+ # Enter would confirm "Yes" and open a browser to start an OAuth flow, which+ # is not a side effect a task transition gets to have.+ r"Opening authentication page",+ r"credentials (are )?(not )?(set|missing|required)",+]++# Interpreters an agent may be shipped as. Finding one in the pane's process+# tree means something other than a shell is running there.+RUNTIME_NAMES = {"node", "bun", "deno", "python", "python3", "ruby", "java"}++PASS, FAIL, SKIP = "pass", "fail", "skipped"+QUOTA, AUTH, PARK, ERROR = "blocked-on-quota", "blocked-on-auth", "expected-park", "error"+++# ---------------------------------------------------------------------------+# Matrix β read from the agent spec table rather than duplicated here+# ---------------------------------------------------------------------------++def load_matrix(cargo: str = "cargo") -> dict:+ """Run the `agent_matrix` example and parse its JSON.++ Everything per-agent (binary name, dialogs, command syntax, liveness+ signals) and per-plugin (artifacts, commands, prompts) comes from the real+ tables in src/, so the runner cannot drift from what agtx actually does.+ """+ proc = subprocess.run(+ [cargo, "run", "--quiet", "--example", "agent_matrix"],+ cwd=REPO_ROOT,+ capture_output=True,+ text=True,+ )+ if proc.returncode != 0:+ raise RuntimeError(+ f"cargo run --example agent_matrix failed:\n{proc.stderr.strip()}"+ )+ return json.loads(proc.stdout)+++# ---------------------------------------------------------------------------+# MCP client (JSON-RPC 2.0 over the agtx MCP server's stdio)+# ---------------------------------------------------------------------------++class McpError(Exception):+ pass+++class McpClient:+ """Minimal MCP client. Mirrors benchmark/swebench/benchmark.py's client.++ `_recv` has a hard timeout because a bare `readline()` on a live-but-silent+ server blocks forever, and no phase timeout can rescue it β the block is+ inside the MCP call rather than inside the poll the timeout governs.+ """++ RECV_TIMEOUT_SECONDS = 120++ def __init__(self, agtx_bin: str, repo_path: str):+ self._seq = 0+ self._lock = threading.Lock()+ self._proc = subprocess.Popen(+ [agtx_bin, "mcp-serve", repo_path],+ stdin=subprocess.PIPE,+ stdout=subprocess.PIPE,+ stderr=subprocess.DEVNULL,+ text=True,+ bufsize=1,+ )+ # Lines are read on a thread rather than by selecting on the fd. A+ # `readline()` on a TextIOWrapper can pull several lines into Python's+ # buffer at once; selecting on the raw descriptor afterwards then reports+ # nothing readable and the next `_recv` times out on a response that is+ # already in hand. Reachable whenever the server flushes a notification+ # and a reply together, which `_request`'s skip-until-matching-id loop+ # does not otherwise mind.+ self._lines: queue.Queue = queue.Queue()+ self._reader = threading.Thread(target=self._pump, daemon=True)+ self._reader.start()+ self._handshake()++ def _pump(self) -> None:+ for line in self._proc.stdout:+ self._lines.put(line)+ self._lines.put(None) # EOF sentinel++ def _next_id(self) -> int:+ with self._lock:+ self._seq += 1+ return self._seq++ def _send(self, msg: dict) -> None:+ self._proc.stdin.write(json.dumps(msg) + "\n")+ self._proc.stdin.flush()++ def _recv(self) -> dict:+ try:+ line = self._lines.get(timeout=self.RECV_TIMEOUT_SECONDS)+ except queue.Empty:+ raise McpError(f"MCP server silent for {self.RECV_TIMEOUT_SECONDS}s")+ if line is None:+ raise McpError("MCP server closed connection")+ return json.loads(line)++ def _request(self, method: str, params: dict) -> Any:+ req_id = self._next_id()+ self._send({"jsonrpc": "2.0", "id": req_id, "method": method, "params": params})+ while True:+ msg = self._recv()+ if msg.get("id") != req_id:+ continue # notification+ if "error" in msg:+ raise McpError(f"MCP error: {msg['error']}")+ result = msg.get("result", {})+ content = result.get("content", [])+ if content and content[0].get("type") == "text":+ text = content[0]["text"]+ try:+ return json.loads(text)+ except json.JSONDecodeError:+ # Tools report failures as plain text, not JSON-RPC errors.+ raise McpError(text.strip())+ if result.get("isError"):+ raise McpError(f"Tool returned error: {content}")+ return result++ def _notify(self, method: str, params: dict) -> None:+ self._send({"jsonrpc": "2.0", "method": method, "params": params})++ def _handshake(self) -> None:+ req_id = self._next_id()+ self._send({+ "jsonrpc": "2.0",+ "id": req_id,+ "method": "initialize",+ "params": {+ "protocolVersion": "2024-11-05",+ "capabilities": {},+ "clientInfo": {"name": "agtx-smoke", "version": "1.0"},+ },+ })+ while True:+ if self._recv().get("id") == req_id:+ break+ self._notify("notifications/initialized", {})++ def call(self, tool: str, **kwargs) -> Any:+ params = {k: v for k, v in kwargs.items() if v is not None}+ return self._request("tools/call", {"name": tool, "arguments": params})++ def close(self) -> None:+ try:+ self._proc.stdin.close()+ self._proc.wait(timeout=5)+ except Exception:+ self._proc.kill()+++# ---------------------------------------------------------------------------+# Case planning+# ---------------------------------------------------------------------------++@dataclass+class Case:+ agent: str+ plugin: str+ skip_reason: str | None = None+++def plugin_prereq(plugin: dict) -> str | None:+ """Why this plugin cannot run against a scratch repo, or None.++ Derived from the plugin's own TOML rather than a hand-kept list:++ - an `init_script` installs a framework (npx, `claude plugin install`), which+ needs the network and a real toolchain;+ - `copy_dirs` names a directory the framework creates in the project root+ (`.specify`, `openspec`), and its slash commands only exist once it is there;+ - a plugin with no command and no prompt for any phase (void) sends the agent+ nothing at all, so there is no delivery to observe.+ """+ if plugin.get("init_script"):+ return "plugin init_script needs network/toolchain setup"+ if plugin.get("copy_dirs"):+ dirs = ", ".join(plugin["copy_dirs"])+ return f"plugin needs {dirs} in the project root"+ if not plugin.get("commands") and not plugin.get("prompts"):+ return "plugin sends the agent nothing by design"+ return None+++def phase_is_assertable(plugin: dict, phase: str) -> bool:+ """Whether the task text can reach the agent in this phase at all.++ A phase whose command and prompt carry neither `{task}` nor `{task_id}`+ (agtx's `review`, which sends a bare `/agtx:review`) gives the agent no way+ to learn what the smoke task asked for β especially under+ `clear_context_on_advance`. Such a phase is still driven, but only checks 3+ and 4 apply to it.+ """+ text = (plugin.get("commands", {}).get(phase) or "") + (+ plugin.get("prompts", {}).get(phase) or ""+ )+ return "{task}" in text or "{task_id}" in text+++def plan_cases(+ matrix: dict,+ agents_arg: str,+ plugins_arg: str,+ force: bool = False,+) -> list[Case]:+ """Build the case list, marking every excluded case with a visible reason.++ A silently narrowed matrix is worse than no run: it invites the assumption+ that the agents it never touched work. Every exclusion becomes a `skipped`+ row with a reason, never an omission.+ """+ by_agent = {a["name"]: a for a in matrix["agents"]}+ by_plugin = {p["name"]: p for p in matrix["plugins"]}++ if agents_arg in ("installed", ""):+ agent_names = [n for n, a in by_agent.items() if shutil.which(a["binary"])]+ if not agent_names:+ agent_names = list(by_agent)+ elif agents_arg == "all":+ agent_names = list(by_agent)+ else:+ agent_names = [n.strip() for n in agents_arg.split(",") if n.strip()]++ if plugins_arg == "all":+ plugin_names = list(by_plugin)+ else:+ plugin_names = [p.strip() for p in plugins_arg.split(",") if p.strip()]++ cases: list[Case] = []+ for plugin_name in plugin_names:+ plugin = by_plugin.get(plugin_name)+ for agent_name in agent_names:+ agent = by_agent.get(agent_name)+ if agent is None:+ cases.append(Case(agent_name, plugin_name, "unknown agent"))+ continue+ if plugin is None:+ cases.append(Case(agent_name, plugin_name, "unknown plugin"))+ continue+ if not shutil.which(agent["binary"]):+ cases.append(+ Case(agent_name, plugin_name, f"{agent['binary']} not installed")+ )+ continue+ supported = plugin.get("supported_agents") or []+ if supported and agent_name not in supported:+ cases.append(+ Case(agent_name, plugin_name, "agent not in supported_agents")+ )+ continue+ prereq = plugin_prereq(plugin)+ if prereq and not force:+ cases.append(Case(agent_name, plugin_name, prereq))+ continue+ cases.append(Case(agent_name, plugin_name))+ return cases+++# ---------------------------------------------------------------------------+# Scratch repo+# ---------------------------------------------------------------------------++def run(cmd: list[str], cwd: Path | None = None, check: bool = True) -> subprocess.CompletedProcess:+ proc = subprocess.run(cmd, cwd=cwd, capture_output=True, text=True)+ if check and proc.returncode != 0:+ raise RuntimeError(+ f"{' '.join(cmd)} failed ({proc.returncode}): {proc.stderr.strip()}"+ )+ return proc+++def make_scratch_repo(workdir: Path, slug: str) -> Path:+ """A one-commit git repo β the smallest thing agtx will open as a project."""+ repo = workdir / slug+ repo.mkdir(parents=True, exist_ok=True)+ run(["git", "init", "-b", "main"], cwd=repo)+ run(["git", "config", "user.email", "[email protected]"], cwd=repo)+ run(["git", "config", "user.name", "agtx smoke"], cwd=repo)+ run(["git", "config", "commit.gpgsign", "false"], cwd=repo)+ (repo / "README.md").write_text(+ "# agtx smoke test scratch repo\n\nDisposable. Created by tests/smoke/agent_smoke.py.\n"+ )+ (repo / "main.py").write_text('def main():\n print("hello")\n')+ run(["git", "add", "-A"], cwd=repo)+ run(["git", "commit", "-m", "initial commit"], cwd=repo)+ return repo+++def write_project_config(repo: Path, agent: str, plugin: str) -> None:+ agtx_dir = repo / ".agtx"+ agtx_dir.mkdir(exist_ok=True)+ (agtx_dir / "config.toml").write_text(+ "\n".join(+ [+ f'default_agent = "{agent}"',+ 'base_branch = "main"',+ 'worktree_dir = ".agtx/worktrees"',+ 'branch_prefix = "task"',+ f'workflow_plugin = "{plugin}"',+ "",+ ]+ )+ )+ exclude = repo / ".git" / "info" / "exclude"+ exclude.parent.mkdir(parents=True, exist_ok=True)+ with exclude.open("a") as f:+ f.write("\n# agtx smoke artifacts\n.agtx/\n")+++def trust_project(agtx_bin: str, repo: Path) -> None:+ """Trust the scratch repo's own config.++ This trusts *agtx's* project config, which is what gates plugin init scripts+ and copy_files. It deliberately does **not** touch any agent's trust state β+ the agent dialogs are the thing under test.+ """+ run([agtx_bin, "trust"], cwd=repo)+++# ---------------------------------------------------------------------------+# tmux+# ---------------------------------------------------------------------------++def tmux(server: str, *args: str, check: bool = False) -> subprocess.CompletedProcess:+ return run(["tmux", "-L", server, *args], check=check)+++def start_tui(session: str, repo: Path, agtx_bin: str) -> None:+ tmux(TUI_SERVER, "kill-session", "-t", session)+ tmux(AGENT_SERVER, "kill-session", "-t", repo.name)+ # tmux runs this through a shell, so both words are quoted: a --workdir+ # containing a space would otherwise make agtx open the wrong path, and the+ # failure would surface much later as "no worktree" with no obvious cause.+ proc = tmux(+ TUI_SERVER, "new-session", "-d", "-s", session, "-x", "200", "-y", "50",+ f"{shlex.quote(str(agtx_bin))} {shlex.quote(str(repo))}",+ )+ if proc.returncode != 0:+ raise RuntimeError(f"tmux new-session failed: {proc.stderr.strip()}")+++def stop_tui(session: str, repo: Path) -> None:+ tmux(TUI_SERVER, "kill-session", "-t", session)+ tmux(AGENT_SERVER, "kill-session", "-t", repo.name)+++def pane_command(target: str) -> str | None:+ proc = tmux(+ AGENT_SERVER, "display-message", "-p", "-t", target, "#{pane_current_command}"+ )+ if proc.returncode != 0:+ return None+ return proc.stdout.strip() or None+++def pane_pid(target: str) -> int | None:+ proc = tmux(AGENT_SERVER, "display-message", "-p", "-t", target, "#{pane_pid}")+ if proc.returncode != 0:+ return None+ try:+ return int(proc.stdout.strip())+ except ValueError:+ return None+++# ---------------------------------------------------------------------------+# Task description β the fixture+# ---------------------------------------------------------------------------++def concrete_artifact(template: str, cycle: int = 1) -> str:+ """A writable path for an artifact template.++ `{phase}` becomes the cycle number and `*` becomes a literal `smoke`, so the+ agent is told one exact path while `find_artifact` still accepts anything the+ glob matches β which is what agtx itself checks.+ """+ return template.replace("{phase}", str(cycle)).replace("*", "smoke")+++def find_artifact(worktree: Path, template: str, cycle: int = 1) -> bool:+ """Mirror of agtx's `artifact_path_exists`: both {phase} spellings, glob-aware."""+ for phase_str in (f"{cycle:02d}", str(cycle)):+ rel = template.replace("{phase}", phase_str)+ full = str(worktree / rel)+ if "*" in rel:+ if glob(full):+ return True+ elif Path(full).exists():+ return True+ return False+++def marker_rel(phase: str) -> str:+ return f".agtx/smoke/{phase}.txt"+++INSTRUCTIONS_REL = ".agtx/smoke/INSTRUCTIONS.md"++# Every phase artifact is written with this one line, and it is the whole reason+# the fixture survives a phase advance.+#+# A later phase does not necessarily see the task description again: agtx's+# `execute` skill says, in as many words, "if .agtx/plan.md exists, read it β do+# NOT call get_task", and the agtx plugin clears the agent's context between+# phases. So an artifact holding "smoke" strands the running phase with no idea+# what it was asked for. Pointing at a file the runner drops in the worktree+# carries the fixture forward through exactly the mechanism the plugin uses to+# carry a plan forward.+ARTIFACT_POINTER = f"SMOKE TEST β follow the instructions in {INSTRUCTIONS_REL}"+++def phase_instructions(task_id: str, artifacts: dict[str, str], phases: list[str]) -> str:+ """The per-phase file list, shared by the task description and the fixture."""+ lines = []+ for phase in phases:+ lines.append(f"{phase.upper()} phase β write these files, then stop:")+ lines.append(f" 1. {marker_rel(phase)} containing one line: DELIVERED {task_id}")+ if artifacts.get(phase):+ lines.append(f" 2. {artifacts[phase]} containing one line: {ARTIFACT_POINTER}")+ lines.append("")+ return "\n".join(lines)+++SMOKE_RULES = [+ "SMOKE TEST β this is not a coding task.",+ "These instructions override anything the phase skill tells you to do.",+ "",+ "Rules: do not read, create, or modify any source file. Do not explore the",+ "codebase. Do not run tests, builds, installs, or git commands. Do not spawn",+ "subagents. Do not write a summary.",+ "",+ "Do the work for the phase you are currently in, then stop and wait. Ignore the",+ "other phases' entries.",+ "",+]+++def build_description(task_id: str, artifacts: dict[str, str], phases: list[str]) -> str:+ """The smallest task that still proves delivery.++ The marker carries the **task id** rather than fixed text: a skill that runs+ but drops its argument is a real failure mode, and a fixed-content marker+ cannot see it. For the agtx plugin the id only reaches the agent as the+ argument to `/agtx:plan <id>`, and the description itself is only readable by+ calling `get_task` with it β so a correct marker proves the whole chain.+ """+ return "\n".join(+ SMOKE_RULES+ + [phase_instructions(task_id, artifacts, phases)]+ + [+ f"The id to write into the marker is exactly: {task_id}",+ f"If a phase skill tells you not to fetch the task description, read",+ f"{INSTRUCTIONS_REL} instead β it holds this same list.",+ "Paths are relative to the current working directory; create parent dirs as needed.",+ "Write nothing else and stop as soon as the files exist.",+ ]+ )+++def write_fixture(worktree: Path, task_id: str, artifacts: dict[str, str],+ phases: list[str]) -> None:+ """Drop the instruction fixture into the worktree.++ Written by the runner rather than by the agent so that a phase which never+ sees the description again still has somewhere to look β see+ [`ARTIFACT_POINTER`].+ """+ path = worktree / INSTRUCTIONS_REL+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(+ "\n".join(SMOKE_RULES + [phase_instructions(task_id, artifacts, phases)])+ )+++# ---------------------------------------------------------------------------+# Assertions+# ---------------------------------------------------------------------------++@dataclass+class Check:+ name: str+ state: str # pass | fail | unknown | n/a+ detail: str = ""++ SYMBOLS = {"pass": "β", "fail": "β", "unknown": "?", "n/a": "β"}++ @property+ def symbol(self) -> str:+ return self.SYMBOLS.get(self.state, "?")+++def tail(text: str, n: int) -> str:+ lines = [l for l in text.splitlines()]+ return "\n".join(lines[-n:])+++def match_any(patterns: Iterable[str], text: str) -> str | None:+ for pat in patterns:+ m = re.search(pat, text, re.IGNORECASE)+ if m:+ return m.group(0)+ return None+++def visible_dialog(pane: str, all_dialogs: list[dict]) -> str | None:+ """A dialog on screen right now, whether or not agtx knows how to answer it.++ Scans only the pane tail: a dialog is modal, so if it is still blocking it is+ on the visible screen. Matching further back would re-find dialogs agtx+ already answered, which scroll away but stay in history.+ """+ screen = tail(pane, 30)+ for dialog in all_dialogs:+ patterns = dialog["patterns"]+ hit = (+ all(p in screen for p in patterns)+ if dialog.get("require_all")+ else any(p in screen for p in patterns)+ )+ if hit:+ owner = dialog.get("owner", "?")+ return f"{owner}: {patterns[0]}"+ for pat in UNHANDLED_DIALOG_PATTERNS:+ if pat in screen:+ return f"unhandled: {pat}"+ return None+++def process_tree(pid: int) -> list[str]:+ """Command names of `pid` and every descendant.++ One `ps` call, then a downward walk β portable across macOS and Linux.+ """+ proc = run(["ps", "-eo", "pid=,ppid=,comm="], check=False)+ if proc.returncode != 0:+ return []+ children: dict[int, list[int]] = {}+ names: dict[int, str] = {}+ for line in proc.stdout.splitlines():+ parts = line.split(None, 2)+ if len(parts) < 3:+ continue+ try:+ child, parent = int(parts[0]), int(parts[1])+ except ValueError:+ continue+ names[child] = Path(parts[2].strip().lstrip("-")).name+ children.setdefault(parent, []).append(child)+ seen, stack, out = set(), [pid], []+ while stack:+ current = stack.pop()+ if current in seen:+ continue+ seen.add(current)+ if current in names:+ out.append(names[current])+ stack.extend(children.get(current, []))+ return out+++def agent_is_live(target: str, pane: str, agent: dict) -> bool:+ """Is the agent process still running in this pane?++ Deliberately stronger than agtx's own `is_agent_active`, which asks tmux for+ `pane_current_command`. That reports the **pane leader**, and every agent is+ launched as `sh -c '<agent>'` with `exec $SHELL` behind it, so a live Claude+ pane reports `bash` and a dead one reports `bash` too. Verified against+ tmux 3.5a on macOS: `pane_current_command` was `bash` while `claude` ran as+ its child.++ So the pane's process **tree** is what is checked: an agent shipped as a node+ script shows up as `node`, one shipped as a binary under its own name, and a+ pane whose agent has exited has nothing but a shell left. `active_indicators`+ alone does not generalise β copilot and antigravity declare none.+ """+ cmd = pane_command(target)+ if cmd and any(name in cmd for name in agent["process_names"]):+ return True+ pid = pane_pid(target)+ if pid:+ tree = process_tree(pid)+ if any(name in tree for name in agent["process_names"]):+ return True+ if any(name in RUNTIME_NAMES for name in tree):+ return True+ indicators = agent.get("active_indicators") or []+ if indicators and any(i in tail(pane, 6) for i in indicators):+ return True+ return False+++def check_command_submitted(pane: str, command: str | None, work_landed: bool) -> Check:+ """Check 1: the command was submitted, not left sitting in a composer.++ This is the check that separates "agtx typed something" from "the agent+ understood it". A submitted message has the agent's response rendered under+ it; a command parked in a composer is the last thing on screen with nothing+ below.++ Two deliberate softenings, both because the pane is a rendered TUI rather+ than a log:++ - the command not appearing at all is `unknown`, not a failure β several+ TUIs redraw their scrollback, and check 2 catches a genuinely undelivered+ command anyway;+ - the command at the bottom of the screen only fails when nothing landed.+ Claude Code renders a dim *suggestion* for the next phase's command in its+ empty composer (verified against 2.1.245: the line carries SGR 2, which+ `capture-pane -p` strips), so the bottom line is not proof of a park.+ """+ if not command:+ return Check("submitted", "n/a", "agent has no interactive command syntax")+ needle = command.strip()+ lines = [l.rstrip() for l in pane.splitlines()]+ hits = [i for i, l in enumerate(lines) if needle in l]+ if not hits:+ # Wrapped panes break long commands across lines; fall back to the head.+ head = needle.split()[0]+ hits = [i for i, l in enumerate(lines) if head in l]+ if not hits:+ return Check("submitted", "unknown", "command text not visible in pane")+ non_empty = [i for i, l in enumerate(lines) if l.strip()]+ last = non_empty[-1] if non_empty else 0+ if last - hits[-1] <= 1 and not work_landed:+ return Check(+ "submitted", "fail", "command is the last thing on screen and nothing ran"+ )+ return Check("submitted", "pass")+++def check_marker(worktree: Path, phase: str, task_id: str, assertable: bool) -> Check:+ """Check 2: the skill body ran, with the argument it was given."""+ if not assertable:+ return Check("skill-ran", "n/a", "phase carries no task text")+ path = worktree / marker_rel(phase)+ if not path.exists():+ return Check("skill-ran", "fail", f"{marker_rel(phase)} never written")+ content = path.read_text(errors="replace").strip()+ if task_id not in content:+ return Check(+ "skill-ran", "fail", f"marker lacks the task id: {content[:120]!r}"+ )+ return Check("skill-ran", "pass")+++def check_artifact(worktree: Path, template: str | None, cycle: int) -> Check:+ if not template:+ return Check("artifact", "n/a", "plugin declares no artifact for this phase")+ if find_artifact(worktree, template, cycle):+ return Check("artifact", "pass")+ return Check("artifact", "fail", f"{template} never appeared")+++def check_usable(target: str, pane: str, agent: dict, all_dialogs: list[dict],+ agent_state: str | None, work_landed: bool = False) -> Check:+ """Check 4: is this session still usable by a human?++ The honest floor (plan open question 1): the agent process is alive **and**+ no dialog matches. `active_indicators` alone does not generalise β copilot+ and antigravity declare none, so "the agent's own indicator is visible" is+ not a definition that covers the matrix.++ The agent's hook-reported state is folded in, but only as a tiebreaker when+ nothing landed. agtx maps Claude's `Notification` event to `blocked`, and+ that event covers both "waiting on a permission prompt" and "has been+ waiting for your input" β a phase that finished and went idle reports+ `blocked` too. Failing on it unconditionally would mark every completed+ phase unusable.+ """+ dialog = visible_dialog(pane, all_dialogs)+ if dialog:+ return Check("usable", "fail", f"dialog on screen β {dialog}")+ if not agent_is_live(target, pane, agent):+ return Check("usable", "fail", "agent process is gone (pane at shell)")+ if agent_state == "blocked" and not work_landed:+ return Check("usable", "fail", "agent reports itself blocked and nothing ran")+ return Check("usable", "pass")+++# ---------------------------------------------------------------------------+# Driving one case+# ---------------------------------------------------------------------------++@dataclass+class PhaseResult:+ phase: str+ checks: list[Check] = field(default_factory=list)+ outcome: str = PASS+ pane_tail: str = ""++ def failed(self) -> bool:+ return any(c.state == "fail" for c in self.checks)+++@dataclass+class CaseResult:+ agent: str+ plugin: str+ outcome: str+ reason: str = ""+ phases: list[PhaseResult] = field(default_factory=list)+ seconds: float = 0.0+ workdir: str = ""++ @property+ def phase_reached(self) -> str:+ return self.phases[-1].phase if self.phases else "-"+++class CaseRunner:+ def __init__(self, case: Case, matrix: dict, opts: argparse.Namespace, workdir: Path):+ self.case = case+ self.opts = opts+ self.agent = next(a for a in matrix["agents"] if a["name"] == case.agent)+ self.plugin = next(p for p in matrix["plugins"] if p["name"] == case.plugin)+ # Every agent's declared dialogs, tagged with their owner. Check 4 wants+ # any dialog on screen, including one belonging to another agent β that+ # is itself a bug worth seeing.+ self.all_dialogs = [+ dict(d, owner=a["name"]) for a in matrix["agents"] for d in a["dialogs"]+ ]+ self.workdir = workdir+ self.repo: Path | None = None+ self.mcp: McpClient | None = None+ self.session = f"smoke-{case.agent}-{case.plugin}"++ # -- helpers ---------------------------------------------------------+ def log(self, msg: str) -> None:+ if self.opts.verbose:+ print(f" [{self.case.agent}/{self.case.plugin}] {msg}", file=sys.stderr)++ def pane(self, task_id: str, lines: int = 200) -> str:+ try:+ return self.mcp.call("read_pane_content", task_id=task_id, lines=lines).get(+ "content", ""+ )+ except McpError:+ return ""++ def poll_transition(self, request_id: str, timeout: int) -> None:+ deadline = time.monotonic() + timeout+ while time.monotonic() < deadline:+ res = self.mcp.call("get_transition_status", request_id=request_id)+ if res.get("status") == "completed":+ return+ if res.get("status") == "error":+ raise RuntimeError(f"transition failed: {res.get('error')}")+ time.sleep(2)+ raise TimeoutError(f"transition {request_id} timed out after {timeout}s")++ def move_forward(self, task_id: str) -> None:+ res = self.mcp.call("move_task", task_id=task_id, action="move_forward")+ self.poll_transition(res["request_id"], self.opts.transition_timeout)++ def wait_for(self, task_id: str, predicate, timeout: int, what: str) -> dict:+ deadline = time.monotonic() + timeout+ while time.monotonic() < deadline:+ task = self.mcp.call("get_task", task_id=task_id)+ if predicate(task):+ return task+ time.sleep(3)+ raise TimeoutError(f"{what} not reached within {timeout}s")++ # -- phases ----------------------------------------------------------+ def drive_phase(self, task_id: str, phase: str, worktree: Path, cycle: int) -> PhaseResult:+ """Wait for the phase to land, then run the four checks.++ The wait ends early on a dialog or a quota park: both mean nothing more+ is coming, and burning the full timeout only delays the diagnosis.+ """+ assertable = phase_is_assertable(self.plugin, phase)+ artifact = self.plugin.get("artifacts", {}).get(phase)+ marker = worktree / marker_rel(phase)+ deadline = time.monotonic() + self.opts.phase_timeout+ pane = ""+ early = None++ while time.monotonic() < deadline:+ pane = self.pane(task_id)+ quota = match_any(QUOTA_PATTERNS, tail(pane, 40))+ if quota:+ early = (QUOTA, f"agent parked on a usage limit: {quota!r}")+ break+ # A credential error is terminal for the phase β the model was never+ # reached β so there is nothing to gain from waiting out the timeout.+ auth = match_any(AUTH_PATTERNS, tail(pane, 40))+ if auth:+ early = (AUTH, f"provider rejected the request: {auth!r}")+ break+ done_marker = (not assertable) or marker.exists()+ done_artifact = (not artifact) or find_artifact(worktree, artifact, cycle)+ if done_marker and done_artifact:+ # Let the agent settle so check 1 sees the response rendered+ # under the command rather than mid-stream.+ time.sleep(5)+ pane = self.pane(task_id)+ break+ dialog = visible_dialog(pane, self.all_dialogs)+ if dialog:+ # Give agtx its dismissal window before calling it stuck: the+ # readiness loop and the session-refresh loop both answer known+ # dialogs, the latter only after the pane stops changing.+ time.sleep(20)+ pane = self.pane(task_id)+ if visible_dialog(pane, self.all_dialogs):+ early = (FAIL, f"session parked on a dialog: {dialog}")+ break+ time.sleep(5)+ else:+ early = (FAIL, f"phase did not complete within {self.opts.phase_timeout}s")++ task = self.mcp.call("get_task", task_id=task_id)+ target = task.get("session_name") or ""+ command = self.resolved_command(phase, task_id, cycle)++ # Check 2 and 3 first: check 1 needs to know whether anything landed+ # before it can read a bottom-of-screen command as a parked composer.+ marker_check = check_marker(worktree, phase, task_id, assertable)+ artifact_check = check_artifact(worktree, artifact, cycle)+ work_landed = marker_check.state == "pass" or artifact_check.state == "pass"++ result = PhaseResult(phase=phase, pane_tail=tail(pane, 20))+ result.checks = [+ check_command_submitted(pane, command, work_landed),+ marker_check,+ artifact_check,+ check_usable(+ target, pane, self.agent, self.all_dialogs, task.get("agent_state"),+ work_landed,+ ),+ ]++ if early and early[0] in (QUOTA, AUTH):+ result.outcome = early[0]+ result.checks.append(Check("note", "unknown", early[1]))+ return result++ # Also consulted at the end: an auth prompt that only appears once the+ # phase has already failed still explains the failure.+ auth = match_any(AUTH_PATTERNS, tail(pane, 40))+ if result.failed() and auth:+ result.outcome = AUTH+ result.checks.append(Check("note", "unknown", f"auth prompt: {auth!r}"))+ return result++ # The checks are the verdict, not the reason the wait ended: an+ # artifact landing between the last poll and the capture is a pass, not a+ # timeout.+ result.outcome = FAIL if result.failed() else PASS+ return result++ def resolved_command(self, phase: str, task_id: str, cycle: int) -> str | None:+ template = self.agent["commands"].get(self.case.plugin, {}).get(phase)+ if not template:+ return None+ return (+ template.replace("{task_id}", task_id)+ .replace("{phase}", str(cycle))+ .split("{task}")[0]+ .strip()+ )++ # -- lifecycle -------------------------------------------------------+ def run(self) -> CaseResult:+ started = time.monotonic()+ res = CaseResult(self.case.agent, self.case.plugin, PASS)+ try:+ slug = f"{self.case.agent}-{self.case.plugin}"+ self.repo = make_scratch_repo(self.workdir, slug)+ res.workdir = str(self.repo)+ write_project_config(self.repo, self.case.agent, self.case.plugin)+ trust_project(self.opts.agtx_bin, self.repo)+ self.log(f"scratch repo at {self.repo}")++ start_tui(self.session, self.repo, self.opts.agtx_bin)+ time.sleep(3) # let the TUI open the project DB+ self.mcp = McpClient(self.opts.agtx_bin, str(self.repo))++ created = self.mcp.call(+ "create_task",+ title=f"smoke {self.case.agent} {self.case.plugin}",+ description="placeholder",+ plugin=self.case.plugin,+ )+ task_id = created["id"]+ artifacts = {+ p: concrete_artifact(t)+ for p, t in (self.plugin.get("artifacts") or {}).items()+ }+ self.mcp.call(+ "update_task",+ task_id=task_id,+ description=build_description(task_id, artifacts, self.opts.phases),+ )+ self.log(f"task {task_id}")++ self.move_forward(task_id)+ task = self.wait_for(+ task_id,+ lambda t: t.get("status") == "planning" and t.get("worktree_path"),+ self.opts.worktree_timeout,+ "planning + worktree",+ )+ worktree = Path(task["worktree_path"])+ write_fixture(worktree, task_id, artifacts, self.opts.phases)+ self.log(f"worktree {worktree}")++ for index, phase in enumerate(self.opts.phases):+ phase_res = self.drive_phase(task_id, phase, worktree, task.get("cycle", 1))+ res.phases.append(phase_res)+ if phase_res.outcome != PASS:+ res.outcome = phase_res.outcome+ res.reason = next(+ (c.detail for c in phase_res.checks if c.state == "fail"),+ next((c.detail for c in phase_res.checks if c.detail), ""),+ )+ break+ if index + 1 < len(self.opts.phases):+ self.move_forward(task_id)+ nxt = self.opts.phases[index + 1]+ task = self.wait_for(+ task_id,+ lambda t, s=PHASE_STATUS[nxt]: t.get("status") == s,+ self.opts.transition_timeout,+ f"status {nxt}",+ )+ else:+ res.outcome = PASS++ res = self.apply_park_expectation(res)+ except (McpError, TimeoutError, RuntimeError, OSError) as exc:+ res.outcome = ERROR+ res.reason = f"{type(exc).__name__}: {exc}"+ finally:+ if self.mcp:+ self.mcp.close()+ if not self.opts.keep_sessions and self.repo:+ stop_tui(self.session, self.repo)+ res.seconds = time.monotonic() - started+ return res++ def apply_park_expectation(self, res: CaseResult) -> CaseResult:+ """Re-label the antigravity-shaped outcome: delivered, then parked."""+ if self.case.agent not in EXPECTED_PARK_AGENTS:+ return res+ if res.outcome == PASS:+ res.reason = (+ "expectation is stale: this agent was expected to park on an "+ "unanswered dialog but completed cleanly β drop it from "+ "EXPECTED_PARK_AGENTS"+ )+ return res+ if res.outcome != FAIL or not res.phases:+ return res+ last = res.phases[-1]+ usable = next((c for c in last.checks if c.name == "usable"), None)+ others = [c for c in last.checks if c.name != "usable"]+ if usable and usable.state == "fail" and not any(c.state == "fail" for c in others):+ res.outcome = PARK+ res.reason = f"delivered, then parked β {usable.detail}"+ return res+++# ---------------------------------------------------------------------------+# Reporting+# ---------------------------------------------------------------------------++OUTCOME_STYLE = {+ PASS: "PASS",+ FAIL: "FAIL",+ SKIP: "SKIP",+ QUOTA: "QUOTA",+ AUTH: "AUTH",+ PARK: "PARK",+ ERROR: "ERROR",+}+++def report(results: list[CaseResult]) -> None:+ width_agent = max([len(r.agent) for r in results] + [5])+ width_plugin = max([len(r.plugin) for r in results] + [6])+ header = (+ f"{'agent':<{width_agent}} {'plugin':<{width_plugin}} "+ f"{'phase':<8} {'checks':<11} {'outcome':<6} {'time':>7}"+ )+ print()+ print(header)+ print("-" * len(header))+ for r in results:+ checks = "".join(c.symbol for c in r.phases[-1].checks[:4]) if r.phases else "----"+ secs = f"{r.seconds:.0f}s" if r.seconds else "-"+ print(+ f"{r.agent:<{width_agent}} {r.plugin:<{width_plugin}} "+ f"{r.phase_reached:<8} {checks:<11} {OUTCOME_STYLE[r.outcome]:<6} {secs:>7}"+ )+ if r.reason:+ print(f" {r.reason}")+ print()+ print("checks: 1 submitted 2 skill-ran 3 artifact 4 usable "+ "(β pass β fail ? unknown β n/a)")++ counts: dict[str, int] = {}+ for r in results:+ counts[r.outcome] = counts.get(r.outcome, 0) + 1+ summary = " ".join(f"{OUTCOME_STYLE[k]}={v}" for k, v in sorted(counts.items()))+ print(f"\n{summary}")++ skipped = [r for r in results if r.outcome == SKIP]+ if skipped:+ # Loud on purpose: a green run that quietly tested two of eight agents is+ # worse than no run at all.+ print(f"\n{len(skipped)} of {len(results)} cases were NOT tested:")+ for r in skipped:+ print(f" - {r.agent}/{r.plugin}: {r.reason}")++ for r in results:+ if r.outcome in (PASS, SKIP):+ continue+ print(f"\n--- {r.agent}/{r.plugin} [{OUTCOME_STYLE[r.outcome]}] {r.reason}")+ for p in r.phases:+ details = " ".join(+ f"{c.name}={c.symbol}" + (f" ({c.detail})" if c.detail else "")+ for c in p.checks+ )+ print(f" {p.phase}: {details}")+ if r.phases and r.phases[-1].pane_tail:+ print(" pane tail:")+ for line in r.phases[-1].pane_tail.splitlines():+ print(f" | {line}")+ if r.workdir:+ print(f" scratch repo: {r.workdir}")+++def to_json(results: list[CaseResult]) -> list[dict]:+ return [+ {+ "agent": r.agent,+ "plugin": r.plugin,+ "outcome": r.outcome,+ "reason": r.reason,+ "seconds": round(r.seconds, 1),+ "workdir": r.workdir,+ "phases": [+ {+ "phase": p.phase,+ "outcome": p.outcome,+ "checks": [+ {"name": c.name, "state": c.state, "detail": c.detail}+ for c in p.checks+ ],+ "pane_tail": p.pane_tail,+ }+ for p in r.phases+ ],+ }+ for r in results+ ]+++# ---------------------------------------------------------------------------+# main+# ---------------------------------------------------------------------------++def parse_args(argv: list[str] | None = None) -> argparse.Namespace:+ p = argparse.ArgumentParser(+ description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter+ )+ p.add_argument(+ "--agents",+ default="installed",+ help="comma-separated agent names, 'installed' (default), or 'all'",+ )+ p.add_argument(+ "--plugins",+ default="agtx",+ help="comma-separated plugin names (default: agtx), or 'all'",+ )+ p.add_argument(+ "--phases",+ default="planning,running",+ help="phases to drive, in order (default: planning,running)",+ )+ p.add_argument("--agtx-bin", default=str(REPO_ROOT / "target/release/agtx"))+ p.add_argument("--cargo", default="cargo")+ p.add_argument("--workdir", default=None, help="where scratch repos are created")+ p.add_argument("--phase-timeout", type=int, default=300)+ p.add_argument("--worktree-timeout", type=int, default=240)+ p.add_argument("--transition-timeout", type=int, default=180)+ p.add_argument("--keep-sessions", action="store_true", help="leave tmux sessions running")+ p.add_argument("--clean", action="store_true", help="delete scratch repos on success")+ p.add_argument(+ "--force-unsupported",+ action="store_true",+ help="run plugins that need project setup (init scripts, framework dirs)",+ )+ p.add_argument("--json", dest="json_out", default=None)+ p.add_argument("-v", "--verbose", action="store_true")+ opts = p.parse_args(argv)+ opts.phases = [p_ for p_ in opts.phases.split(",") if p_.strip()]+ bad = [p_ for p_ in opts.phases if p_ not in ORDERED_PHASES]+ if bad:+ p.error(f"unknown phase(s): {', '.join(bad)}")+ if opts.phases != [p_ for p_ in ORDERED_PHASES if p_ in opts.phases]:+ p.error("--phases must be in workflow order: planning,running,review")+ return opts+++def main(argv: list[str] | None = None) -> int:+ opts = parse_args(argv)++ if not Path(opts.agtx_bin).exists():+ print(f"agtx binary not found: {opts.agtx_bin}", file=sys.stderr)+ print("build it first: cargo build --release", file=sys.stderr)+ return 2+ for tool in ("tmux", "git"):+ if not shutil.which(tool):+ print(f"required tool not found: {tool}", file=sys.stderr)+ return 2++ matrix = load_matrix(opts.cargo)+ cases = plan_cases(matrix, opts.agents, opts.plugins, opts.force_unsupported)+ if not cases:+ print("no cases to run", file=sys.stderr)+ return 2++ workdir = Path(opts.workdir) if opts.workdir else Path(+ tempfile.mkdtemp(prefix="agtx-smoke-")+ )+ workdir.mkdir(parents=True, exist_ok=True)+ runnable = [c for c in cases if not c.skip_reason]+ print(f"agtx smoke: {len(runnable)} case(s) to run, {len(cases) - len(runnable)} skipped")+ print(f"scratch: {workdir}")++ results: list[CaseResult] = []+ for case in cases:+ if case.skip_reason:+ results.append(CaseResult(case.agent, case.plugin, SKIP, case.skip_reason))+ continue+ print(f"β {case.agent} / {case.plugin} β¦", flush=True)+ results.append(CaseRunner(case, matrix, opts, workdir).run())+ print(f" {OUTCOME_STYLE[results[-1].outcome]}", flush=True)++ report(results)++ if opts.json_out:+ Path(opts.json_out).write_text(json.dumps(to_json(results), indent=2))+ print(f"\nwrote {opts.json_out}")++ failed = [r for r in results if r.outcome in (FAIL, ERROR)]+ if opts.clean and not failed:+ shutil.rmtree(workdir, ignore_errors=True)+ return 1 if failed else 0+++if __name__ == "__main__":+ try:+ sys.exit(main())+ except KeyboardInterrupt:+ print("\ninterrupted", file=sys.stderr)+ sys.exit(130)diff --git a/tests/smoke/test_agent_smoke.py b/tests/smoke/test_agent_smoke.pynew file mode 100644index 0000000..f2dab11--- /dev/null+++ b/tests/smoke/test_agent_smoke.py@@ -0,0 +1,574 @@+#!/usr/bin/env python3+"""Tests for the smoke harness itself.++Two things worth automating, because getting either wrong makes the harness lie+rather than fail:++ - the **skipped-agent path**: an uninstalled agent must report `skipped`, never+ `pass`. A green run that quietly tested two of eight agents is worse than no+ run;+ - the **failure path**: pointed at an agent that never delivers, the runner+ must report a failure carrying pane output, and must terminate rather than+ hang waiting for a marker that will never appear.++Everything here is deterministic β no tmux, no agent binaries, no auth.++ python3 tests/smoke/test_agent_smoke.py+"""++import argparse+import os+import shutil+import tempfile+import unittest+from pathlib import Path+from unittest import mock++import agent_smoke as smoke+++def fake_matrix() -> dict:+ return {+ "phases": ["research", "planning", "running", "review"],+ "agents": [+ {+ "name": "claude",+ "binary": "claude",+ "launch_prompt_verified": True,+ "process_names": ["claude"],+ "active_indicators": ["Claude Code"],+ "dialogs": [+ {+ "patterns": ["Yes, I trust this folder"],+ "require_all": False,+ "answer": "1",+ "scope": "launch",+ }+ ],+ "commands": {"agtx": {"planning": "/agtx:plan {task_id}", "review": "/agtx:review"}},+ },+ {+ "name": "ghost",+ "binary": "ghost-cli",+ "launch_prompt_verified": False,+ "process_names": ["ghost-cli"],+ "active_indicators": [],+ "dialogs": [],+ "commands": {"agtx": {"planning": "/agtx-plan {task_id}"}},+ },+ ],+ "plugins": [+ {+ "name": "agtx",+ "supported_agents": [],+ "init_script": None,+ "copy_dirs": [],+ "artifacts": {"planning": ".agtx/plan.md", "running": ".agtx/execute.md"},+ "commands": {"planning": "/agtx:plan {task_id}", "review": "/agtx:review"},+ "prompts": {},+ },+ {+ "name": "gsd",+ "supported_agents": ["claude"],+ "init_script": "npx get-shit-done-cc",+ "copy_dirs": [],+ "artifacts": {"planning": ".planning/phases/*/{phase}-PLAN.md"},+ "commands": {"planning": "/gsd:plan-phase {phase}"},+ "prompts": {"research": "Task: {task}"},+ },+ {+ "name": "void",+ "supported_agents": [],+ "init_script": None,+ "copy_dirs": [],+ "artifacts": {},+ "commands": {},+ "prompts": {},+ },+ ],+ }+++def opts(**overrides) -> argparse.Namespace:+ base = dict(+ agents="installed",+ plugins="agtx",+ phases=["planning"],+ agtx_bin="/nonexistent/agtx",+ cargo="cargo",+ workdir=None,+ phase_timeout=1,+ worktree_timeout=1,+ transition_timeout=1,+ keep_sessions=True,+ clean=False,+ force_unsupported=False,+ json_out=None,+ verbose=False,+ )+ base.update(overrides)+ return argparse.Namespace(**base)+++def only(which: str):+ """A `shutil.which` that finds exactly one binary."""+ return lambda binary: f"/usr/local/bin/{binary}" if binary == which else None+++class PlanCases(unittest.TestCase):+ def test_uninstalled_agent_is_skipped_never_run(self):+ with mock.patch.object(smoke.shutil, "which", only("claude")):+ cases = smoke.plan_cases(fake_matrix(), "claude,ghost", "agtx")+ by_agent = {c.agent: c for c in cases}+ self.assertIsNone(by_agent["claude"].skip_reason)+ self.assertIn("ghost-cli not installed", by_agent["ghost"].skip_reason)++ def test_installed_selection_only_picks_present_binaries(self):+ with mock.patch.object(smoke.shutil, "which", only("claude")):+ cases = smoke.plan_cases(fake_matrix(), "installed", "agtx")+ self.assertEqual([c.agent for c in cases], ["claude"])++ def test_every_excluded_case_still_appears_with_a_reason(self):+ """An exclusion must be a visible row, never an omission."""+ with mock.patch.object(smoke.shutil, "which", only("claude")):+ cases = smoke.plan_cases(fake_matrix(), "all", "all")+ self.assertEqual(len(cases), 6) # 2 agents x 3 plugins, nothing dropped+ for case in cases:+ if case.skip_reason is None:+ continue+ self.assertTrue(case.skip_reason.strip())++ def test_unsupported_agent_for_plugin_is_skipped(self):+ with mock.patch.object(smoke.shutil, "which", lambda b: "/bin/" + b):+ cases = smoke.plan_cases(fake_matrix(), "ghost", "gsd", force=True)+ self.assertIn("supported_agents", cases[0].skip_reason)++ def test_plugins_needing_setup_are_skipped_unless_forced(self):+ with mock.patch.object(smoke.shutil, "which", only("claude")):+ skipped = smoke.plan_cases(fake_matrix(), "claude", "gsd")+ forced = smoke.plan_cases(fake_matrix(), "claude", "gsd", force=True)+ self.assertIn("init_script", skipped[0].skip_reason)+ self.assertIsNone(forced[0].skip_reason)+++class PluginClassification(unittest.TestCase):+ def test_prereqs_are_derived_from_the_plugin_toml(self):+ self.assertIsNone(smoke.plugin_prereq({"commands": {"planning": "/x"}}))+ self.assertIn("init_script", smoke.plugin_prereq({"init_script": "npx foo"}))+ self.assertIn(+ ".specify", smoke.plugin_prereq({"copy_dirs": [".specify"], "commands": {"a": "b"}})+ )+ self.assertIn("nothing", smoke.plugin_prereq({"commands": {}, "prompts": {}}))++ def test_a_phase_without_task_text_is_not_assertable(self):+ plugin = fake_matrix()["plugins"][0]+ self.assertTrue(smoke.phase_is_assertable(plugin, "planning"))+ # agtx sends a bare `/agtx:review`, and clears context on advance β the+ # agent has no way to know what the smoke task asked for.+ self.assertFalse(smoke.phase_is_assertable(plugin, "review"))+++class Fixture(unittest.TestCase):+ def test_description_carries_the_real_task_id_per_phase(self):+ desc = smoke.build_description(+ "abc-123", {"planning": ".agtx/plan.md"}, ["planning", "running"]+ )+ self.assertIn("DELIVERED abc-123", desc)+ self.assertIn(".agtx/smoke/planning.txt", desc)+ self.assertIn(".agtx/smoke/running.txt", desc)+ self.assertIn(".agtx/plan.md", desc)++ def test_the_artifact_carries_the_fixture_into_the_next_phase(self):+ """agtx's execute skill reads plan.md and is told NOT to call get_task."""+ desc = smoke.build_description(+ "abc-123", {"planning": ".agtx/plan.md"}, ["planning", "running"]+ )+ self.assertIn(smoke.ARTIFACT_POINTER, desc)+ self.assertIn(smoke.INSTRUCTIONS_REL, smoke.ARTIFACT_POINTER)++ def test_the_fixture_file_repeats_the_phase_list(self):+ with tempfile.TemporaryDirectory() as tmp:+ wt = Path(tmp)+ smoke.write_fixture(wt, "abc-123", {"running": ".agtx/execute.md"}, ["running"])+ text = (wt / smoke.INSTRUCTIONS_REL).read_text()+ self.assertIn("DELIVERED abc-123", text)+ self.assertIn(".agtx/smoke/running.txt", text)++ def test_concrete_artifact_resolves_wildcards_and_phase(self):+ self.assertEqual(+ smoke.concrete_artifact(".planning/phases/*/{phase}-PLAN.md"),+ ".planning/phases/smoke/1-PLAN.md",+ )++ def test_find_artifact_matches_both_phase_spellings_and_globs(self):+ with tempfile.TemporaryDirectory() as tmp:+ wt = Path(tmp)+ (wt / ".planning" / "phases" / "anything").mkdir(parents=True)+ (wt / ".planning" / "phases" / "anything" / "01-PLAN.md").write_text("x")+ self.assertTrue(+ smoke.find_artifact(wt, ".planning/phases/*/{phase}-PLAN.md", 1)+ )+ self.assertFalse(smoke.find_artifact(wt, ".agtx/plan.md", 1))+++class Checks(unittest.TestCase):+ def test_marker_must_contain_the_id_that_was_passed_in(self):+ with tempfile.TemporaryDirectory() as tmp:+ wt = Path(tmp)+ self.assertEqual(+ smoke.check_marker(wt, "planning", "abc-123", True).state, "fail"+ )+ marker = wt / smoke.marker_rel("planning")+ marker.parent.mkdir(parents=True)+ marker.write_text("DELIVERED some-other-id\n")+ check = smoke.check_marker(wt, "planning", "abc-123", True)+ self.assertEqual(check.state, "fail")+ self.assertIn("lacks the task id", check.detail)+ marker.write_text("DELIVERED abc-123\n")+ self.assertEqual(+ smoke.check_marker(wt, "planning", "abc-123", True).state, "pass"+ )++ def test_marker_is_not_applicable_when_the_phase_carries_no_task_text(self):+ with tempfile.TemporaryDirectory() as tmp:+ self.assertEqual(+ smoke.check_marker(Path(tmp), "review", "abc", False).state, "n/a"+ )++ def test_command_parked_in_a_composer_is_a_failure(self):+ pane = "\n".join(["welcome", "", "> /agtx:plan abc-123"])+ check = smoke.check_command_submitted(pane, "/agtx:plan abc-123", False)+ self.assertEqual(check.state, "fail")+ self.assertIn("nothing ran", check.detail)++ def test_command_at_the_bottom_is_not_a_park_when_work_landed(self):+ """Claude Code renders a dim suggestion in its empty composer."""+ pane = "\n".join(["wrote the files", "", "> /agtx:execute abc-123"])+ self.assertEqual(+ smoke.check_command_submitted(pane, "/agtx:execute abc-123", True).state,+ "pass",+ )++ def test_command_with_output_under_it_counts_as_submitted(self):+ pane = "\n".join(+ ["> /agtx:plan abc-123", "", "Reading the taskβ¦", "Wrote .agtx/plan.md", "β―"]+ )+ self.assertEqual(+ smoke.check_command_submitted(pane, "/agtx:plan abc-123", False).state, "pass"+ )++ def test_invisible_command_is_unknown_not_a_failure(self):+ """Several TUIs redraw their scrollback; check 2 catches real misses."""+ self.assertEqual(+ smoke.check_command_submitted("nothing here", "/agtx:plan abc", False).state,+ "unknown",+ )++ def test_agent_without_command_syntax_is_not_applicable(self):+ self.assertEqual(smoke.check_command_submitted("x", None, False).state, "n/a")++ def test_dialog_is_matched_only_on_the_visible_tail(self):+ dialogs = [+ dict(d, owner="claude") for d in fake_matrix()["agents"][0]["dialogs"]+ ]+ on_screen = "some output\nYes, I trust this folder"+ self.assertIsNotNone(smoke.visible_dialog(on_screen, dialogs))+ scrolled_away = "Yes, I trust this folder\n" + "\n".join(+ f"line {i}" for i in range(60)+ )+ self.assertIsNone(smoke.visible_dialog(scrolled_away, dialogs))++ def test_dialogs_agtx_does_not_answer_are_still_caught(self):+ """The antigravity trap: no agent declares it, the session still parks.++ Antigravity's own wording is no longer the example here β this runner is+ what got it declared. What the check still has to catch is a prompt that+ belongs to no agent's spec at all.+ """+ self.assertIn(+ "unhandled",+ smoke.visible_dialog("Continue? Press Enter to continue", []),+ )++ def test_a_declared_dialog_is_no_longer_listed_as_unhandled(self):+ """Guards the contradiction directly: a pattern cannot be both.++ The only test here that needs the crate, since the declared side comes+ from `AGENT_SPECS`. Skipped rather than failed without a toolchain, so+ the rest stay runnable anywhere.+ """+ if not shutil.which("cargo"):+ self.skipTest("cargo not available")+ try:+ matrix = smoke.load_matrix()+ except (RuntimeError, OSError) as exc:+ self.skipTest(f"could not load the agent matrix: {exc}")+ declared = {+ p for a in matrix["agents"] for d in a["dialogs"] for p in d["patterns"]+ }+ overlap = declared & set(smoke.UNHANDLED_DIALOG_PATTERNS)+ self.assertEqual(+ overlap,+ set(),+ "a dialog agtx answers must not also be listed as unhandled",+ )++ def test_usable_requires_a_live_process_and_a_clear_screen(self):+ agent = fake_matrix()["agents"][0]+ with mock.patch.object(smoke, "pane_command", return_value="claude"), \+ mock.patch.object(smoke, "pane_pid", return_value=None):+ self.assertEqual(+ smoke.check_usable("t:1", "all good", agent, [], None).state, "pass"+ )+ self.assertEqual(+ smoke.check_usable("t:1", "ok", agent, [], "blocked", False).state, "fail"+ )+ # A finished phase reports `blocked` too: agtx maps Claude's+ # Notification event, which also means "waiting for your input".+ self.assertEqual(+ smoke.check_usable("t:1", "ok", agent, [], "blocked", True).state, "pass"+ )+ with mock.patch.object(smoke, "pane_command", return_value="zsh"), \+ mock.patch.object(smoke, "pane_pid", return_value=4242), \+ mock.patch.object(smoke, "process_tree", return_value=["sh", "zsh"]):+ check = smoke.check_usable("t:1", "no indicators", agent, [], None)+ self.assertEqual(check.state, "fail")+ self.assertIn("agent process is gone", check.detail)++ def test_a_wrapper_shell_does_not_hide_a_live_agent(self):+ """`pane_current_command` reports `bash` for a live Claude pane."""+ agent = fake_matrix()["agents"][0]+ with mock.patch.object(smoke, "pane_command", return_value="bash"), \+ mock.patch.object(smoke, "pane_pid", return_value=4242), \+ mock.patch.object(smoke, "process_tree", return_value=["sh", "claude"]):+ self.assertEqual(+ smoke.check_usable("t:1", "no indicators here", agent, [], None).state,+ "pass",+ )++ def test_an_agent_shipped_as_a_node_script_counts_as_live(self):+ agent = fake_matrix()["agents"][1]+ with mock.patch.object(smoke, "pane_command", return_value="bash"), \+ mock.patch.object(smoke, "pane_pid", return_value=4242), \+ mock.patch.object(smoke, "process_tree", return_value=["sh", "node"]):+ self.assertEqual(+ smoke.check_usable("t:1", "", agent, [], None).state, "pass"+ )+++class ProcessTree(unittest.TestCase):+ def test_the_ps_walk_finds_this_very_process(self):+ """Guards the `ps` parsing itself β the format differs across platforms."""+ tree = smoke.process_tree(os.getpid())+ self.assertTrue(+ any("python" in name for name in tree),+ f"expected a python process in {tree}",+ )++ def test_a_pid_with_no_processes_yields_nothing(self):+ self.assertEqual(smoke.process_tree(0x7FFFFFFF), [])+++class StubMcp:+ """Just enough MCP for drive_phase: a fixed pane and a fixed task record."""++ def __init__(self, pane: str, task: dict | None = None):+ self.pane = pane+ self.task = task or {"session_name": "smoke:task", "status": "planning"}++ def call(self, tool: str, **kwargs):+ if tool == "read_pane_content":+ return {"content": self.pane}+ if tool == "get_task":+ return self.task+ raise AssertionError(f"unexpected tool {tool}")+++class FailurePath(unittest.TestCase):+ """Pointed at an agent that never delivers, the runner must report, not hang."""++ def runner(self, pane: str, **opt_overrides) -> smoke.CaseRunner:+ case = smoke.Case("claude", "agtx")+ r = smoke.CaseRunner(case, fake_matrix(), opts(**opt_overrides), Path("/tmp"))+ r.mcp = StubMcp(pane)+ return r++ def test_undelivered_prompt_fails_with_pane_output(self):+ pane = "\n".join(["claude starting", "", "> /agtx:plan abc-123"])+ r = self.runner(pane)+ with tempfile.TemporaryDirectory() as tmp, \+ mock.patch.object(smoke.time, "sleep"), \+ mock.patch.object(smoke, "pane_command", return_value="claude"), \+ mock.patch.object(smoke, "pane_pid", return_value=None):+ result = r.drive_phase("abc-123", "planning", Path(tmp), 1)+ self.assertEqual(result.outcome, smoke.FAIL)+ self.assertTrue(result.pane_tail, "a failure must carry pane output")+ self.assertIn("/agtx:plan abc-123", result.pane_tail)+ states = {c.name: c.state for c in result.checks}+ self.assertEqual(states["skill-ran"], "fail")+ self.assertEqual(states["artifact"], "fail")++ def test_a_parked_dialog_is_reported_not_waited_out(self):+ r = self.runner("Yes, I trust this folder", phase_timeout=600)+ with tempfile.TemporaryDirectory() as tmp, \+ mock.patch.object(smoke.time, "sleep"), \+ mock.patch.object(smoke, "pane_command", return_value="claude"), \+ mock.patch.object(smoke, "pane_pid", return_value=None):+ result = r.drive_phase("abc-123", "planning", Path(tmp), 1)+ self.assertEqual(result.outcome, smoke.FAIL)+ usable = next(c for c in result.checks if c.name == "usable")+ self.assertEqual(usable.state, "fail")+ self.assertIn("dialog on screen", usable.detail)++ def test_usage_limit_is_reported_separately_from_a_failure(self):+ r = self.runner("You've hit your session limit", phase_timeout=600)+ with tempfile.TemporaryDirectory() as tmp, \+ mock.patch.object(smoke.time, "sleep"), \+ mock.patch.object(smoke, "pane_command", return_value="claude"), \+ mock.patch.object(smoke, "pane_pid", return_value=None):+ result = r.drive_phase("abc-123", "planning", Path(tmp), 1)+ self.assertEqual(result.outcome, smoke.QUOTA)++ def test_a_credential_error_short_circuits_as_auth(self):+ r = self.runner("AWS SigV4 authentication requires AWS credentials.",+ phase_timeout=600)+ with tempfile.TemporaryDirectory() as tmp, \+ mock.patch.object(smoke.time, "sleep"), \+ mock.patch.object(smoke, "pane_command", return_value="opencode"), \+ mock.patch.object(smoke, "pane_pid", return_value=None):+ result = r.drive_phase("abc-123", "planning", Path(tmp), 1)+ self.assertEqual(result.outcome, smoke.AUTH)++ def test_a_complete_phase_passes_every_check(self):+ pane = "\n".join(+ ["> /agtx:plan abc-123", "", "wrote the files", "β―"]+ )+ r = self.runner(pane, phase_timeout=600)+ with tempfile.TemporaryDirectory() as tmp, \+ mock.patch.object(smoke.time, "sleep"), \+ mock.patch.object(smoke, "pane_command", return_value="claude"), \+ mock.patch.object(smoke, "pane_pid", return_value=None):+ wt = Path(tmp)+ marker = wt / smoke.marker_rel("planning")+ marker.parent.mkdir(parents=True)+ marker.write_text("DELIVERED abc-123")+ (wt / ".agtx" / "plan.md").write_text("smoke")+ result = r.drive_phase("abc-123", "planning", wt, 1)+ self.assertEqual(result.outcome, smoke.PASS)+ self.assertEqual([c.state for c in result.checks], ["pass"] * 4)+++class QuotaPatterns(unittest.TestCase):+ def test_an_informational_tip_is_not_a_quota_park(self):+ """Codex prints this at startup on a perfectly healthy session."""+ self.assertIsNone(+ smoke.match_any(+ smoke.QUOTA_PATTERNS,+ "β’ You have 1 usage limit reset available. Run /usage to use one.",+ )+ )++ def test_a_real_park_is_still_caught(self):+ for line in (+ "You've hit your session limit. Press Enter to continue after reset",+ "usage limit reached",+ # Grok's wording β no apostrophe, and a word in the middle. It was+ # reported as a send-path FAIL until the pattern was widened.+ "You hit your free usage limit.",+ ):+ self.assertIsNotNone(smoke.match_any(smoke.QUOTA_PATTERNS, line), line)+++class AuthPatterns(unittest.TestCase):+ def test_a_provider_credential_error_is_classified_as_auth(self):+ """It looks exactly like an undelivered prompt from the outside."""+ for line in (+ "AWS SigV4 authentication requires AWS credentials. Please provide either:",+ "Original error: AWS access key ID setting is missing.",+ "Opening authentication page in your browser.",+ '"message": "API key not valid. Please pass a valid API key."',+ ):+ self.assertIsNotNone(smoke.match_any(smoke.AUTH_PATTERNS, line), line)++ def test_ordinary_output_is_not_an_auth_prompt(self):+ self.assertIsNone(+ smoke.match_any(smoke.AUTH_PATTERNS, "Wrote .agtx/plan.md and stopped.")+ )++ def test_a_generic_failure_summary_is_not_laundered_into_auth(self):+ """Gemini prints this next to a real credential error and to any other."""+ self.assertIsNone(+ smoke.match_any(+ smoke.AUTH_PATTERNS,+ "This request failed. Press F12 for diagnostics",+ )+ )+++class ParkExpectation(unittest.TestCase):+ """The set is empty today, so every case here installs its own entry.++ The mechanism stays tested rather than deleted: the next agent that parks on+ a dialog agtx cannot answer needs it, and its guards β never excusing a lost+ prompt, and flagging itself stale β are the whole reason it is safe to have.+ """++ def setUp(self):+ patcher = mock.patch.object(smoke, "EXPECTED_PARK_AGENTS", {"antigravity"})+ patcher.start()+ self.addCleanup(patcher.stop)++ def runner(self, agent: str) -> smoke.CaseRunner:+ matrix = fake_matrix()+ matrix["agents"][1]["name"] = agent+ return smoke.CaseRunner(smoke.Case(agent, "agtx"), matrix, opts(), Path("/tmp"))++ def result(self, agent: str, outcome: str, usable_state: str) -> smoke.CaseResult:+ phase = smoke.PhaseResult("planning")+ phase.checks = [+ smoke.Check("submitted", "pass"),+ smoke.Check("skill-ran", "pass"),+ smoke.Check("artifact", "pass"),+ smoke.Check("usable", usable_state, "dialog on screen β unhandled: trust"),+ ]+ return smoke.CaseResult(agent, "agtx", outcome, phases=[phase])++ def test_delivered_then_parked_is_its_own_outcome(self):+ r = self.runner("antigravity")+ out = r.apply_park_expectation(self.result("antigravity", smoke.FAIL, "fail"))+ self.assertEqual(out.outcome, smoke.PARK)+ self.assertIn("delivered, then parked", out.reason)++ def test_a_clean_pass_flags_the_expectation_as_stale(self):+ r = self.runner("antigravity")+ out = r.apply_park_expectation(self.result("antigravity", smoke.PASS, "pass"))+ self.assertEqual(out.outcome, smoke.PASS)+ self.assertIn("stale", out.reason)++ def test_an_undelivered_prompt_is_never_excused_as_a_park(self):+ """The park expectation covers a blocked session, not a lost prompt."""+ r = self.runner("antigravity")+ res = self.result("antigravity", smoke.FAIL, "fail")+ res.phases[0].checks[1] = smoke.Check("skill-ran", "fail", "never written")+ self.assertEqual(r.apply_park_expectation(res).outcome, smoke.FAIL)++ def test_other_agents_are_unaffected(self):+ r = self.runner("ghost")+ out = r.apply_park_expectation(self.result("ghost", smoke.FAIL, "fail"))+ self.assertEqual(out.outcome, smoke.FAIL)+++class Args(unittest.TestCase):+ def test_phases_must_be_in_workflow_order(self):+ with self.assertRaises(SystemExit):+ smoke.parse_args(["--phases", "running,planning"])+ with self.assertRaises(SystemExit):+ smoke.parse_args(["--phases", "backlog"])+ self.assertEqual(+ smoke.parse_args(["--phases", "planning,review"]).phases,+ ["planning", "review"],+ )+++if __name__ == "__main__":+ unittest.main(verbosity=2)