ππΌββοΈ The blackboard for coding agents - agentic development environment for claude code, codex, cursor, opencode, grok and more.
Rust adeai-agentsclaudeclaude-codecodexcursorgeminigrokopencodespec-driven-developmentvibe-codingvim
feat: hook-based phase status for gemini, cursor, grok and antigravity (#141)
Fynn Fluegge4865e48a498f
diff --git a/CLAUDE.md b/CLAUDE.mdindex 0932dab..dd9b5e6 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -27,7 +27,7 @@ cargo build --release./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+./target/release/agtx hook --env <agent> [--event <Name>] < payload.json# Version, and self-update to the latest GitHub release./target/release/agtx --version@@ -68,6 +68,8 @@ src/βββ agent/β βββ mod.rs # Agent struct, detection, command builders (all derived from spec.rs)β βββ spec.rs # AgentSpec table β one declarative record per agent + kind enums+β βββ hook_status.rs # Agent-reported liveness: per-agent event vocabularies,+β # what agtx registers, atomic status writes, stalenessβ βββ trust.rs # Reads each agent's own workspace-trust store; seeds antigravity'sβ βββ trust_tests.rs # Unit tests for trust.rs (included via #[path])β βββ operations.rs # AgentOperations/CodingAgent traits (mockable)@@ -207,7 +209,7 @@ Canonical copy always at `.agtx/skills/agtx-plan/SKILL.md`.| antigravity | `.agents/mcp_config.json` | JSON, `mcpServers` || opencode | opencode config | JSON, `mcp` |-Two writers **merge** instead of overwriting, because their file may already be tracked in the repo: grok appends `[mcp_servers.agtx]` to any existing `.grok/config.toml`, and antigravity parses `.agents/mcp_config.json`, inserts `mcpServers.agtx`, and writes it back β preserving other servers and top-level sibling keys. (`.agents/` is vendor-neutral, so a project is more likely to ship one.)+Three writers **merge** instead of overwriting, because their file may already exist in the worktree β either tracked in the repo, or copied in from the project root by `AGENT_CONFIG_DIRS`. Grok appends `[mcp_servers.agtx]` to any existing `.grok/config.toml`; antigravity parses `.agents/mcp_config.json` and inserts `mcpServers.agtx`, preserving other servers and top-level sibling keys (`.agents/` is vendor-neutral, so a project is more likely to ship one); gemini inserts into `.gemini/settings.json`, which otherwise loses the user's theme, model and any other `mcpServers`. Claude's `settings.local.json` side-effect below merges for the same reason.Claude needs an extra side-effect to avoid an interactive dialog on first open: `.claude/settings.local.json` gets `enableAllProjectMcpServers: true` plus `skipDangerousModePermissionPrompt: true`, which is what actually preflights the bypass-permissions warning (see the dialog table).@@ -240,9 +242,13 @@ Two consequences worth knowing: `resolve_skill_command(collapse: false)` is used**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 dismiss+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. **How many Enters this takes is not fixed** β see *Submitting is its own delivery problem* below3. **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+**Submitting is its own delivery problem.** A message with a prompt after the command submits on the first Enter. A **bare skill command** β what a phase whose command carries no `{task}`/`{task_id}` sends, which is `review` β exactly matches a skill name, so the composer's command picker opens *on the paste*. That Enter is then consumed by the picker ("Press enter to insert"), which inserts the command and repaints, leaving it parked. Measured against codex-cli 0.144.5 and cursor-agent 2026.08.25: both open the picker on a pasted bare command, and both submit on the second Enter.++So `submit_message()` counts nothing and watches the composer instead: it presses Enter until the text is **gone from the bottom `COMPOSER_TAIL_LINES` of the pane**, bounded by `SUBMIT_ATTEMPTS`. A repaint is not a submit β that was the old test, and a picker opening satisfies it. The window is 14 lines because the picker draws its suggestions *below* the composer and cursor's footer wraps the worktree path, putting the text eight or more lines off the bottom; sizing it from the tidy pane left behind *after* a failure is how a too-narrow window looks correct. Erring wide costs one inert Enter into a submitted composer; erring narrow parks the command forever.+**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).@@ -293,6 +299,7 @@ Dialogs are declared per agent on `AgentSpec::dialogs` and **matched against the| claude | bypass-permissions warning | `Yes, I accept` / `I accept the risk` | `2` `Enter` | Launch β suppressed by the `skipDangerousModePermissionPrompt` preflight; backstop only. Options are inverted (`1. No, exit`), so never a lone Enter || 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 | hook review | `Hooks need review` | `3` `Enter` (Continue without trusting) | Launch β fires when the project ships a `.codex/hooks.json` codex has not seen. Answered because option 3 *declines*; option 2 would trust every hook in the repo || 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 |@@ -661,30 +668,89 @@ Agents that support lifecycle hooks report their own state instead of agtx guessoutput.```-Claude Code ββhookβββΊ agtx hook <task-id> <worktree> βββΊ {worktree}/.agtx/status/{task_id}.json- β- maybe_spawn_session_refresh ββββΊ apply_session_refresh+agent ββhookβββΊ agtx hook --env <agent> βββΊ {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+**Five of eight agents report their own state.** Every one of them takes a **project-local** hook+config, so agtx writes into the worktree and never into the user's global agent config; removing the+worktree removes the registration, and there is nothing to uninstall. `write_hook_config()` is the+writer, selected by `AgentSpec::hook_config` (`HookConfigKind`). `None` β no hooks, keep the+pane-hash heuristic β is a supported state, not a degraded one.++| Agent | Config file | Handler shape | Payload event key | Can report `Blocked` |+|---|---|---|---|---|+| claude | `.claude/settings.local.json` | `{hooks:[{type,command}]}` | `hook_event_name`, PascalCase | yes β `PermissionRequest`, `Notification` |+| gemini | `.gemini/settings.json` | same | `hook_event_name`, PascalCase | yes β `Notification` |+| cursor | `.cursor/hooks.json` | **flat `{command}`** | `hook_event_name`, camelCase | no |+| grok | `.grok/hooks/agtx.json` | `{hooks:[{type,command}]}` | `hookEventName`, **snake_case value** | yes β `Notification` scoped to `permission_prompt` |+| antigravity | `.agents/hooks.json` | keyed by hook *name*, then event | **none** β passed as `--event` | no |+| codex | `.codex/hooks.json` | `{description, hooks:{β¦}}` | `hook_event_name`, PascalCase | mapped, **not deployed** |+| opencode, copilot | β | β | β | no hooks; see `HookConfigKind` |++The formats are **not interchangeable**, and every mismatch below fails silently β a valid-looking+config in the worktree and no status file ever written. This is why `tests/smoke/agent_smoke.py` is+the gate: the unit suite cannot see "the agent ignored it".++- **cursor** takes a flat `[{command}]` list; with Claude's `{hooks:[{type,command}]}` wrapper the+ file parses, loads, and fires nothing+- **grok** registers `PreToolUse` and reports `pre_tool_use`, so both spellings must map β that is+ `squash()`. It also sends `hookEventName`/`sessionId`/`transcriptPath` in camelCase, hence the+ serde aliases on `HookPayload`+- **antigravity's `PreToolUse` is not subscribable.** Its `decision` output is *required* and+ anything else reads as a refusal, so registering it blocks every tool call. Answering `"allow"`+ would make a liveness reporter into a permission granter β the line agtx declines to cross with+ trust dialogs. `PostToolUse` carries the heartbeat instead, and does include the tool name despite+ its docs. Its two event shapes also differ: tool events group under a `matcher`, the rest are a+ flat handler list, and the wrong shape is ignored+- **codex's `hooks` key in `.codex/config.toml` is a table, not a path.** `hooks.json` is+ auto-discovered; assigning a string to that key makes codex reject the whole config+ (`invalid type: string, expected struct HooksToml`) and lose its MCP server with it++**Codex is off, deliberately.** Its hooks work and speak Claude's schema, but a project-local+`.codex/hooks.json` triggers a startup review β *"N hooks are new or changed. Hooks can run outside+the sandbox after you trust them."* β whose only enabling answer trusts **every** hook the repo+ships, as does `--dangerously-bypass-hook-trust`. Not agtx's decision, on the same reasoning as+never choosing codex's "Update now". The vocabulary is mapped and the writer exists, so enabling it+is one field if codex gains per-hook trust. The dialog is in `AgentSpec::dialogs` regardless+(answered `3`, *Continue without trusting*, `security: false` because it declines rather than+grants) β a project shipping its own hooks file parks every codex task there whether or not agtx+writes one.++- **Writers merge where the file is shared.** Claude's and Gemini's hooks live in the same file as+ their MCP config, and `.claude`/`.gemini`/`.codex` are in `AGENT_CONFIG_DIRS`, so a project+ shipping its own settings has them copied into every worktree. `merge_claude_hooks()` keeps user+ entries on the same events and replaces only agtx's own, matched on the `" hook --env"` invocation+ rather than the binary path, so redeploying is idempotent and a moved agtx still recognises its own+ work. `write_hook_config` runs **after** `write_mcp_config` because both read-modify-write those+ two files+- **The hook command is task-agnostic**: `agtx hook --env <agent>`. The task comes 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+ resumed or switched agent inherits them). Baking the task id in breaks `skip_worktree`, where every+ task shares one settings file. The hook exits silently when those are absent, so a registration+ stays inert outside agtx, and when `CLAUDE_JOB_DIR` is set, since a backgrounded task inherits its+ parent's env+- **`--event <Name>`** supplies the event for an agent whose payload carries none+ (`HookEventSource::Argv`, antigravity only). The payload wins when it has one+- **`hook_events(kind)` and `map_hook_event(kind, β¦)` are the two halves of one contract** and live+ in the same file so a test can guard the drift. An event registered but unmapped fires and reports+ nothing; an event mapped but unregistered pays a process spawn to decide nothing. Both directions+ are asserted. The kind is a *parameter*, not a fallback chain: `Stop` means "turn over" to four+ agents while Gemini's equivalent is `AfterAgent` and Cursor's is lowercase `stop`, so one shared+ table would let a registration typo succeed against the wrong agent's arm+- **Grok also scans `.claude/settings*.json` and `.cursor/hooks.json`** for vendor compatibility, so+ in a multi-phase-agent worktree it fires agtx's Claude- and cursor-registered hooks too. Mostly+ inert: the vocabulary is chosen by the agent named in the command agtx wrote, and grok's snake_case+ payloads do not resolve against Claude's PascalCase arm. **Cursor's arm is the exception** β it is+ lowercase and contains `stop`, which is exactly what grok reports, so a grok turn can write a+ record labelled `agent: "cursor"`. The *state* is right either way (both map `stop` to `Waiting`)+ and nothing reads that label, so this is a wrong name on a correct record rather than a wrong+ status+- **Claude's registered events** (verified against Claude Code 2.1.247): `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, atomicwrite-then-rename, staleness, and `merge_event`'s guard preventing a late `PreToolUse` fromclearing a fresh `Blocked`@@ -692,21 +758,30 @@ Claude Code ββhookβββΊ agtx hook <task-id> <worktree> βββΊ {worktrpane-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+- The pane capture is skipped only on a **fresh `Working`** report β one fewer `capture-pane` per+ task per refresh, and proof the pane is past whatever gated startup. A `waiting`/`ended` record+ never expires, so letting one suppress the capture would hide a dialog rendered after a relaunch,+ which is exactly the resume path. Codex's MCP approval auto-dismiss runs outside that branch so it+ fires either way+- **Consumers**: an agent-reported `Blocked` fires the orchestrator stuck-task notification+ *immediately* (with the reason text from `blocked_reasons`), where `Idle` keeps its 60s settle+ because it is still a guess. A **trust-blocked** task is excluded from that notification+ altogether: the orchestrator's only remedies are a nudge β which would be typed into the dialog β+ and escalation, and only the user can answer it. The merge-conflict trigger fires on `Ready` and+ `Idle` only, so it never sends into a `Blocked` pane. 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 bothfor worktrees created earlier. `write_skills_to_worktree` records the deploying binary in`.agtx/deployed-by`; `refresh_stale_worktree_configs` re-deploys mismatched worktrees on abackground thread at startup. `is_agtx_hook_command` matches on the `" hook --env"` invocationrather 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+- **Not wired**: codex (hook-trust review, above); opencode, whose lifecycle callbacks are a+ TypeScript plugin API rather than shell commands, so it would need agtx to ship a JS shim; and+ copilot, whose hook support is *unknown* rather than absent β it is not installed on any machine+ this was measured on, and that distinction is recorded in its spec so it is not filled in from+ documentation### Task References & Dependencies- In description input, type `!` (at start of line or after space) to search existing tasks@@ -816,7 +891,11 @@ Half of this is now one table entry; the other half is still per-agent match arm7. 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+9b. Set `hook_config` / `hook_event_source` on the spec if the agent supports lifecycle hooks, add+ its `HookConfigKind` arm to `write_hook_config`, `hook_events` and `map_hook_event`, and extend+ `vocabulary()` in `tests/hook_status_tests.rs`. Leave `hook_config: None` until a real run writes+ a `.agtx/status/*.json`: a wrong handler shape or event spelling fails silently (see+ *Hook-Based Phase Status*), and `None` is a supported state, not a failure10. 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 popupdiff --git a/src/agent/hook_status.rs b/src/agent/hook_status.rsindex e156388..fc1d95e 100644--- a/src/agent/hook_status.rs+++ b/src/agent/hook_status.rs@@ -1,16 +1,23 @@//! 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.+//! Agents that support lifecycle hooks are configured to invoke `agtx hook --env+//! <agent>` 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.+//!+//! Which agents, and where their config goes, is [`HookConfigKind`]; every one+//! of them is project-local, so registration lives and dies with the worktree.+//!+//! Two things here are per-agent: [`map_hook_event`], because the vocabularies+//! differ, and where the event name comes from ([`super::spec::HookEventSource`]).+//! Merging, staleness, the `Blocked` guard and the atomic write are shared.//!//! 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 crate::agent::spec::HookConfigKind;use anyhow::Result;use serde::{Deserialize, Serialize};use std::io::Read;@@ -26,8 +33,8 @@ pub const STATUS_DIR: &str = ".agtx/status";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.+/// `Working` event. An agent can emit its tool heartbeat for the very tool it is+/// requesting permission for, which would otherwise clear the block instantly.pub const BLOCKED_GUARD_SECS: i64 = 2;/// Maximum stdin payload accepted from a hook invocation.@@ -72,17 +79,163 @@ pub enum HookState {Ended,}-/// Map a Claude Code `hook_event_name` to a state.+/// Map one agent's lifecycle event name to a state.+///+/// `None` means the event carries no transition and the stored record is left+/// alone. An event from another agent's vocabulary also returns `None`: the kind+/// is a parameter, not a fallback chain, so a registration typo cannot resolve+/// against the wrong agent's arm. `Stop` means "turn over" to four agents while+/// Gemini's equivalent is `AfterAgent` and Cursor's is lowercase `stop`.///-/// `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,+/// Each arm names the version it was read from.+pub fn map_hook_event(kind: HookConfigKind, event: &str) -> Option<HookState> {+ use HookConfigKind::*;+ match kind {+ // claude 2.1.247.+ ClaudeSettings => match event {+ "SessionStart" | "UserPromptSubmit" | "PreToolUse" => Some(HookState::Working),+ "PermissionRequest" | "Notification" => Some(HookState::Blocked),+ "Stop" | "StopFailure" => Some(HookState::Waiting),+ "SessionEnd" => Some(HookState::Ended),+ _ => None,+ },+ // codex-cli 0.144.5. Claude's schema minus `SessionEnd` (window-gone+ // detection covers Exited) and `Notification`.+ CodexHooksJson => match event {+ "SessionStart" | "UserPromptSubmit" | "PreToolUse" | "PostToolUse" => {+ Some(HookState::Working)+ }+ "PermissionRequest" => Some(HookState::Blocked),+ "Stop" => Some(HookState::Waiting),+ _ => None,+ },+ // gemini-cli 0.46.0. Its own vocabulary: the turn boundary is+ // `BeforeAgent`/`AfterAgent` and the tool heartbeat is `BeforeTool`.+ // `Notification` fires on a ToolPermission alert and carries `message`.+ GeminiSettings => match event {+ "SessionStart" | "BeforeAgent" | "BeforeTool" | "AfterTool" => {+ Some(HookState::Working)+ }+ "Notification" => Some(HookState::Blocked),+ "AfterAgent" => Some(HookState::Waiting),+ "SessionEnd" => Some(HookState::Ended),+ _ => None,+ },+ // cursor-agent 2026.08.25. camelCase, and no event for a human-blocking+ // prompt: the `beforeShellExecution` family are policy gates that decide,+ // not prompts that wait. Cursor never reports Blocked.+ CursorHooksJson => match event {+ "sessionStart" | "beforeSubmitPrompt" | "preToolUse" | "postToolUse" => {+ Some(HookState::Working)+ }+ "stop" => Some(HookState::Waiting),+ "sessionEnd" => Some(HookState::Ended),+ _ => None,+ },+ // grok 1.0.5. Config and payload disagree about spelling: hooks are+ // registered under `PreToolUse` and arrive as `"pre_tool_use"`, so both+ // must map β hence `squash`.+ //+ // `notification` counts as Blocked only because the registration pins+ // `matcher: "permission_prompt"`; unscoped it also fires for+ // `idle_prompt` and `task_complete`.+ GrokHooksJson => match squash(event).as_str() {+ "sessionstart" | "userpromptsubmit" | "pretooluse" => Some(HookState::Working),+ "notification" => Some(HookState::Blocked),+ "stop" | "stopfailure" | "stopcancelled" => Some(HookState::Waiting),+ "sessionend" => Some(HookState::Ended),+ _ => None,+ },+ // agy 1.1.21. Five events, no session lifecycle and no permission event.+ // `PreInvocation` fires before each model call β its nearest thing to a+ // turn start; `Stop` ends the execution loop, not the session.+ AntigravityHooksJson => match event {+ "PreInvocation" | "PostInvocation" | "PostToolUse" => Some(HookState::Working),+ "Stop" => Some(HookState::Waiting),+ _ => None,+ },+ }+}++/// Lowercase and drop underscores, so one arm accepts both spellings grok uses+/// for an event: `PreToolUse` when registered, `pre_tool_use` when reported.+fn squash(event: &str) -> String {+ event.chars().filter(|c| *c != '_').flat_map(char::to_lowercase).collect()+}++/// The events agtx registers for one agent.+///+/// The write half of the pair whose read half is [`map_hook_event`]. A name+/// listed here but not mapped there is a hook that fires and reports nothing, so+/// `tests/hook_status_tests.rs` asserts the two agree in both directions.+///+/// The second element is the event's tool matcher, or `None` when the event is+/// not tool-scoped.+pub fn hook_events(kind: HookConfigKind) -> &'static [(&'static str, Option<&'static str>)] {+ use HookConfigKind::*;+ match kind {+ ClaudeSettings => &[+ // Liveness: a turn started, or a tool is about to run (heartbeat).+ ("SessionStart", None),+ ("UserPromptSubmit", None),+ ("PreToolUse", Some("*")),+ // Blocked: the agent is stopped waiting on a human.+ ("PermissionRequest", Some("*")),+ ("Notification", None),+ // Turn over / session over.+ ("Stop", None),+ ("StopFailure", None),+ ("SessionEnd", None),+ ],+ CodexHooksJson => &[+ ("SessionStart", None),+ ("UserPromptSubmit", None),+ ("PreToolUse", Some("*")),+ ("PostToolUse", Some("*")),+ ("PermissionRequest", Some("*")),+ ("Stop", None),+ ],+ GeminiSettings => &[+ ("SessionStart", Some("*")),+ ("BeforeAgent", Some("*")),+ ("BeforeTool", Some("*")),+ ("AfterTool", Some("*")),+ ("Notification", Some("*")),+ ("AfterAgent", Some("*")),+ ("SessionEnd", Some("*")),+ ],+ CursorHooksJson => &[+ ("sessionStart", None),+ ("beforeSubmitPrompt", None),+ ("preToolUse", None),+ ("postToolUse", None),+ ("stop", None),+ ("sessionEnd", None),+ ],+ // Registered in PascalCase, reported in snake_case; see the grok arm of+ // `map_hook_event`.+ GrokHooksJson => &[+ ("SessionStart", None),+ ("UserPromptSubmit", None),+ ("PreToolUse", Some("*")),+ // Scoped: unmatched, this also fires on idle and task-complete.+ ("Notification", Some("permission_prompt")),+ ("Stop", None),+ ("StopFailure", None),+ ("StopCancelled", None),+ ("SessionEnd", None),+ ],+ // No `PreToolUse`, deliberately: antigravity makes that hook's+ // `decision` output *required* and reads anything else as a refusal, so+ // subscribing blocks every tool call. Answering `"allow"` would make a+ // liveness reporter into a permission granter. `PostToolUse` carries the+ // heartbeat instead and wants exactly the `{}` this hook prints.+ AntigravityHooksJson => &[+ ("PreInvocation", None),+ ("PostInvocation", None),+ ("PostToolUse", Some("*")),+ ("Stop", None),+ ],}}@@ -125,11 +278,11 @@ pub fn write_status(worktree: &Path, task_id: &str, status: &AgentHookStatus) ->/// 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.+/// an event with no mapping *for this agent* is ignored, and a `Working` event is+/// dropped while a fresh `Blocked` record stands (see [`BLOCKED_GUARD_SECS`]).pub fn merge_event(previous: Option<&AgentHookStatus>,+ kind: HookConfigKind,event: &str,now: i64,agent: &str,@@ -138,7 +291,7 @@ pub fn merge_event(message: Option<String>,tool: Option<String>,) -> Option<AgentHookStatus> {- let state = map_claude_event(event)?;+ let state = map_hook_event(kind, event)?;if state == HookState::Working {if let Some(prev) = previous {@@ -182,15 +335,33 @@ fn truncate(s: &str) -> String {trimmed.chars().take(MAX_FIELD_CHARS).collect()}-/// Fields lifted from a hook's JSON payload. Every field is optional β agents+/// 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.+///+/// The aliases carry the two agents that do not send `snake_case`.#[derive(Debug, Default, Deserialize)]struct HookPayload {+ /// Grok spells this `hookEventName`, with a snake_case value.+ #[serde(alias = "hookEventName")]hook_event_name: Option<String>,+ #[serde(alias = "sessionId")]session_id: Option<String>,+ /// `conversationId` is antigravity's session identifier.+ #[serde(alias = "conversationId")]+ conversation_id: Option<String>,+ #[serde(alias = "transcriptPath")]transcript_path: Option<String>,message: Option<String>,+ #[serde(alias = "toolName")]tool_name: Option<String>,+ /// Antigravity's `PreToolUse` payload nests the tool under `toolCall.name`.+ #[serde(alias = "toolCall")]+ tool_call: Option<ToolCall>,+}++#[derive(Debug, Default, Deserialize)]+struct ToolCall {+ name: Option<String>,}/// Environment variables identifying the task a hook is reporting about, set on@@ -198,25 +369,37 @@ struct HookPayload {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]`.+/// Entry point for `agtx hook --env <agent> [--event <Name>]` (preferred) or the+/// legacy `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.+/// `--env` reads the task from the process environment, so one registered command+/// serves every task β necessary under `skip_worktree`, where all of them share+/// the project's agent config.///-/// If the variables are absent the hook exits silently: a globally registered-/// hook must be inert in the user's own sessions outside agtx.+/// `--event` names the firing event for an agent whose payload does not+/// ([`super::spec::HookEventSource::Argv`]). The payload wins when it has one, so+/// an agent that starts sending an event name is not shadowed by a stale argv+/// value.///-/// 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.+/// If the task variables are absent the hook exits silently, so a registration+/// stays inert outside agtx.+///+/// Always succeeds. A hook that reports an error can break the agent's turn, so+/// every failure path 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!("{{}}");+ // Lifted out first so the positional parsing below is unaffected.+ let mut argv_event: Option<String> = None;+ let mut args: Vec<String> = args.to_vec();+ if let Some(i) = args.iter().position(|a| a == "--event") {+ argv_event = args.get(i + 1).cloned();+ args.drain(i..=(i + 1).min(args.len() - 1));+ }+ let args = &args[..];+let from_env = args.first().map(String::as_str) == Some("--env");let (task_id, worktree, agent);if from_env {@@ -252,9 +435,37 @@ pub fn run_hook_cli(args: &[String]) -> Result<()> {{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(());+ record_hook_event(task_id, worktree, agent, argv_event.as_deref(), &buf);+ Ok(())+}++/// Everything after the argv and stdin plumbing: decide what the payload means+/// and persist it. Split out so tests can supply a payload without real stdin.+///+/// `argv_event` names the firing event for an agent whose payload does not carry+/// one; it is consulted only when the payload has no `hook_event_name`.+pub fn record_hook_event(+ task_id: &str,+ worktree: &str,+ agent: &str,+ argv_event: Option<&str>,+ payload: &[u8],+) {+ // An unknown agent name β a typo, or a spec removed under a live worktree β+ // must not borrow another agent's vocabulary. See `map_hook_event`.+ let Some(kind) = crate::agent::spec(agent).and_then(|s| s.hook_config) else {+ return;+ };++ let payload: HookPayload = serde_json::from_slice(payload).unwrap_or_default();+ // Payload first: an agent that sends an event name outranks the registration.+ let Some(event) = payload+ .hook_event_name+ .as_deref()+ .or(argv_event)+ .filter(|e| !e.is_empty())+ else {+ return;};let worktree = Path::new(worktree);@@ -263,15 +474,15 @@ pub fn run_hook_cli(args: &[String]) -> Result<()> {if let Some(next) = merge_event(previous.as_ref(),+ kind,event,now,agent,- payload.session_id,+ payload.session_id.or(payload.conversation_id),payload.transcript_path,payload.message,- payload.tool_name,+ payload.tool_name.or(payload.tool_call.and_then(|t| t.name)),) {let _ = write_status(worktree, task_id, &next);}- Ok(())}diff --git a/src/agent/mod.rs b/src/agent/mod.rsindex fabea94..2978c1e 100644--- a/src/agent/mod.rs+++ b/src/agent/mod.rs@@ -5,8 +5,8 @@ pub mod trust;pub use operations::{AgentOperations, AgentRegistry, CodingAgent, RealAgentRegistry};pub use spec::{- spec, AgentDialog, AgentSpec, CommandSyntax, DialogScope, McpConfigKind, PromptForm,- ResumeArgs, SendStrategy, SkillLayout, AGENT_SPECS,+ spec, AgentDialog, AgentSpec, CommandSyntax, DialogScope, HookConfigKind, HookEventSource,+ McpConfigKind, PromptForm, ResumeArgs, SendStrategy, SkillLayout, AGENT_SPECS,};#[cfg(feature = "test-mocks")]diff --git a/src/agent/spec.rs b/src/agent/spec.rsindex 1d84be1..a553218 100644--- a/src/agent/spec.rs+++ b/src/agent/spec.rs@@ -170,6 +170,48 @@ pub enum McpConfigKind {OpenCode,}+/// Where and how an agent's lifecycle-hook config is written, and which event+/// vocabulary its payloads speak.+///+/// One kind per agent, like [`McpConfigKind`], because the formats differ. The+/// location does not: every variant is **project-local**, so agtx writes into+/// the worktree and never into the user's global agent config. Removing the+/// worktree removes the registration.+///+/// `hook_config: None` β opencode, copilot β keeps the pane-hash heuristic,+/// which is a supported state, not a degraded one.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum HookConfigKind {+ /// `.claude/settings.local.json`, `hooks` key. Shared with the MCP preflight+ /// keys, so the writer merges.+ ClaudeSettings,+ /// `.codex/hooks.json`, auto-discovered: `{description, hooks: {β¦}}` with+ /// PascalCase event keys. The `hooks` key in `.codex/config.toml` is a table,+ /// not a path, and pointing it at a file makes codex reject the whole config.+ CodexHooksJson,+ /// `.gemini/settings.json`, `hooks` key. Shared with gemini's MCP config, so+ /// the writer merges.+ GeminiSettings,+ /// `.cursor/hooks.json`, `{version, hooks: {β¦}}`, camelCase event names.+ CursorHooksJson,+ /// `.grok/hooks/agtx.json`. Grok scans the whole directory, so agtx owns one+ /// file in it and never merges.+ GrokHooksJson,+ /// `.agents/hooks.json`, keyed by hook *name* first and event second. The+ /// payload carries no event name, so the event is passed in argv.+ AntigravityHooksJson,+}++/// How the firing event reaches `agtx hook`.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum HookEventSource {+ /// The payload names the event, so one command serves every event.+ Payload,+ /// The payload has no event field, so each event registers its own command+ /// with `--event <Name>`. Antigravity only.+ Argv,+}+/// Everything agtx knows about one coding agent.#[derive(Debug, Clone, Copy)]pub struct AgentSpec {@@ -231,6 +273,12 @@ pub struct AgentSpec {/// 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>,+ /// How this agent's lifecycle-hook config is written, or `None` for an agent+ /// that reports nothing and falls back to the pane-hash heuristic.+ pub hook_config: Option<HookConfigKind>,+ /// Where `agtx hook` learns which event fired. Ignored when `hook_config` is+ /// `None`.+ pub hook_event_source: HookEventSource,// ββ process / liveness βββββββββββββββββββββββββββββββββββββββββββββββ/// Process names this agent may appear as in `pane_current_command`.@@ -294,6 +342,9 @@ pub const AGENT_SPECS: &[AgentSpec] = &[skill_scan_dir: Some(".claude/commands"),command_syntax: CommandSyntax::Colon,mcp_config: Some(McpConfigKind::ClaudeJson),+ // Verified against claude 2.1.247.+ hook_config: Some(HookConfigKind::ClaudeSettings),+ hook_event_source: HookEventSource::Payload,process_names: &["claude"],active_indicators: &["Claude Code"],exit_command: Some("/exit"),@@ -383,6 +434,14 @@ pub const AGENT_SPECS: &[AgentSpec] = &[skill_scan_dir: Some(".codex/skills"),command_syntax: CommandSyntax::Dollar,mcp_config: Some(McpConfigKind::CodexToml),+ // Off: codex gates project hooks behind a startup trust review whose only+ // enabling answers ("Trust all and continue", or+ // `--dangerously-bypass-hook-trust`) trust *every* hook the repo ships,+ // not just agtx's. That is the user's decision. The vocabulary is mapped+ // and the writer exists, so enabling it is one field once codex offers+ // per-hook trust. codex-cli 0.144.5.+ hook_config: None,+ hook_event_source: HookEventSource::Payload,process_names: &["codex"],active_indicators: &["OpenAI Codex"],exit_command: None,@@ -413,6 +472,23 @@ pub const AGENT_SPECS: &[AgentSpec] = &[answer: &["2", "Enter"],scope: DialogScope::Launch,},+ // Hook review, shown at launch when the project ships a+ // `.codex/hooks.json` codex has not seen. Options are `1. Review+ // hooks` / `2. Trust all and continue` / `3. Continue without+ // trusting`.+ //+ // `3` and `security: false`, for the same reason as the update prompt+ // above: declining grants nothing and decides nothing about safety,+ // where `2` would trust every hook the repo ships. Fires whether or+ // not agtx writes hooks for codex β the project's own file is enough.+ // codex-cli 0.144.5.+ AgentDialog {+ patterns: &["Hooks need review"],+ security: false,+ require_all: false,+ answer: &["3", "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.@@ -453,6 +529,10 @@ pub const AGENT_SPECS: &[AgentSpec] = &[command_syntax: CommandSyntax::None,// Copilot is not wired to the MCP server.mcp_config: None,+ // Unknown, not absent β copilot has never been measured. Same rule as+ // `api_key_env` above: fill this in from the real binary, not from docs.+ hook_config: None,+ hook_event_source: HookEventSource::Payload,process_names: &["copilot"],active_indicators: &[],exit_command: Some("/exit"),@@ -492,6 +572,8 @@ pub const AGENT_SPECS: &[AgentSpec] = &[skill_scan_dir: Some(".gemini/commands"),command_syntax: CommandSyntax::Colon,mcp_config: Some(McpConfigKind::GeminiJson),+ hook_config: Some(HookConfigKind::GeminiSettings),+ hook_event_source: HookEventSource::Payload,process_names: &["gemini"],active_indicators: &["Type your message"],exit_command: Some("/quit"),@@ -541,6 +623,11 @@ pub const AGENT_SPECS: &[AgentSpec] = &[skill_scan_dir: Some(".config/opencode/command"),command_syntax: CommandSyntax::Hyphen,mcp_config: Some(McpConfigKind::OpenCode),+ // OpenCode's lifecycle callbacks are a TypeScript plugin API+ // (`.opencode/plugin/*.ts`), not shell commands in a config file β there+ // is no `hooks` key to write. opencode 1.18.20.+ hook_config: None,+ hook_event_source: HookEventSource::Payload,process_names: &["opencode"],active_indicators: &["Ask anything"],exit_command: Some("/exit"),@@ -576,6 +663,8 @@ pub const AGENT_SPECS: &[AgentSpec] = &[skill_scan_dir: Some(".cursor/skills"),command_syntax: CommandSyntax::Hyphen,mcp_config: Some(McpConfigKind::CursorJson),+ hook_config: Some(HookConfigKind::CursorHooksJson),+ hook_event_source: HookEventSource::Payload,process_names: &["agent"],active_indicators: &["Cursor Agent"],exit_command: None,@@ -629,6 +718,8 @@ pub const AGENT_SPECS: &[AgentSpec] = &[skill_scan_dir: Some(".grok/skills"),command_syntax: CommandSyntax::Hyphen,mcp_config: Some(McpConfigKind::GrokTomlMerge),+ hook_config: Some(HookConfigKind::GrokHooksJson),+ hook_event_source: HookEventSource::Payload,process_names: &["grok"],active_indicators: &["Grok Build", "Shift+Tab:mode"],exit_command: Some("/quit"),@@ -673,6 +764,10 @@ pub const AGENT_SPECS: &[AgentSpec] = &[skill_scan_dir: Some(".agents/skills"),command_syntax: CommandSyntax::Hyphen,mcp_config: Some(McpConfigKind::AntigravityJsonMerge),+ // Its payload is protojson camelCase (`conversationId`, `stepIdx`) with+ // no event key, so each event registers its own `--event`. agy 1.1.21.+ hook_config: Some(HookConfigKind::AntigravityHooksJson),+ hook_event_source: HookEventSource::Argv,process_names: &["agy"],// Shown only once the session is interactive: the trust dialog's own// footer reads "β/β Navigate Β· enter Confirm" instead, so this cannotdiff --git a/src/config/mod.rs b/src/config/mod.rsindex 50f195e..aca6ac7 100644--- a/src/config/mod.rs+++ b/src/config/mod.rs@@ -323,7 +323,16 @@ impl GlobalConfig {}/// Get the path to the global data directory+ ///+ /// Honours `AGTX_DATA_DIR` like `Database::data_root`, so a test or smoke run+ /// that redirects the databases also redirects the first-run probe that looks+ /// for `index.db` beside them.pub fn data_dir() -> Result<PathBuf> {+ if let Ok(dir) = std::env::var("AGTX_DATA_DIR") {+ if !dir.is_empty() {+ return Ok(PathBuf::from(dir));+ }+ }let dirs = directories::ProjectDirs::from("", "", "agtx").context("Could not determine data directory")?;Ok(dirs.data_dir().to_path_buf())diff --git a/src/db/models.rs b/src/db/models.rsindex f8a4484..5bab668 100644--- a/src/db/models.rs+++ b/src/db/models.rs@@ -236,7 +236,12 @@ 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.+ ///+ /// Set from an agent-reported hook event, or from a match against that+ /// agent's own `security` dialogs in the pane (`visible_security_dialog`,+ /// which runs only while `auto_trust` is off). Never from silence: "no output+ /// for 15s" is [`Idle`](Self::Idle), which guesses, where this names what the+ /// task is waiting on.Blocked,/// Agent output hasn't changed for 15s β may need user inputIdle,diff --git a/src/db/schema.rs b/src/db/schema.rsindex fe855a7..086e6b5 100644--- a/src/db/schema.rs+++ b/src/db/schema.rs@@ -10,17 +10,33 @@ pub struct Database {}impl Database {+ /// Root directory holding `index.db` and `projects/`.+ ///+ /// `AGTX_DATA_DIR` overrides it so tests (and the smoke runner) can open real+ /// databases without writing into the user's own store β otherwise every+ /// `Database::open_project(TempDir)` in the suite leaves an orphan DB behind,+ /// keyed by a temp path that no longer exists. Same reasoning as+ /// `AGTX_AGENT_HOME`.+ pub fn data_root() -> Result<std::path::PathBuf> {+ if let Ok(dir) = std::env::var("AGTX_DATA_DIR") {+ if !dir.is_empty() {+ return Ok(std::path::PathBuf::from(dir));+ }+ }+ let dirs = directories::ProjectDirs::from("", "", "agtx")+ .context("Could not determine config directory")?;+ Ok(dirs.config_dir().to_path_buf())+ }+/// Open or create a project database (stored centrally in config dir)pub fn open_project(project_path: &Path) -> Result<Self> {- let config_dir = directories::ProjectDirs::from("", "", "agtx")- .context("Could not determine config directory")?;+ let config_dir = Self::data_root()?;// Create a stable ID from the project path using a hashlet path_str = project_path.to_string_lossy();let path_hash = Self::hash_path(&path_str);let db_path = config_dir- .config_dir().join("projects").join(format!("{}.db", path_hash));@@ -33,7 +49,6 @@ impl Database {if !db_path.exists() {let old_hash = Self::hash_path_legacy(&path_str);let old_db_path = config_dir- .config_dir().join("projects").join(format!("{}.db", old_hash));if old_db_path.exists() {@@ -82,9 +97,7 @@ impl Database {/// Open or create the global index databasepub fn open_global() -> Result<Self> {- let config_dir = directories::ProjectDirs::from("", "", "agtx")- .context("Could not determine config directory")?;- let db_path = config_dir.config_dir().join("index.db");+ let db_path = Self::data_root()?.join("index.db");// Ensure config directory existsif let Some(parent) = db_path.parent() {diff --git a/src/tui/app.rs b/src/tui/app.rsindex 98149a5..55bb2ba 100644--- a/src/tui/app.rs+++ b/src/tui/app.rs@@ -9428,34 +9428,79 @@ fn wait_for_pane_settled(tmux_ops: &Arc<dyn TmuxOperations>, target: &str) -> bo/// 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.-/// Press Enter, and confirm the message actually left the composer.+/// Lines at the bottom of a pane treated as the composer.///-/// [`deliver_message`] proves the *text* arrived. It says nothing about the Enter-/// that submits it β those are separate keystrokes into the same TUI, and an Ink-/// composer that has just accepted a bracketed paste can still be mid-render when-/// the Enter lands. The keystroke is dropped, the paste sits on screen, and the-/// phase never starts.+/// Sized from the worst real layout, not from the composer alone: while the+/// command picker is open the agent draws its suggestions *below* the composer,+/// and cursor's footer wraps the worktree path over three more lines. That puts+/// the text being submitted eight or more lines off the bottom β a snugger+/// window reads it as already gone and stops pressing Enter after one.///-/// Observed against gemini 0.46.0, on the first smoke run where its credentials-/// worked well enough to reach a second phase: `/agtx:execute <id>` sat in the-/// composer while the agent reported "Waiting for approval". The fixed 150ms-/// sleep this replaces was the whole guarantee, and for gemini it was not enough.+/// The cost of erring wide is one extra Enter into a composer that already+/// submitted, which is inert; the cost of erring narrow is a command parked+/// forever.+const COMPOSER_TAIL_LINES: usize = 14;++/// Whether the message is still sitting in the composer rather than submitted.+///+/// Only the bottom of the pane is examined: after a submit the text moves up into+/// the scrollback, and finding it *there* is proof it went, not that it stayed.+fn composer_holds(pane: &str, needle: &str) -> bool {+ // Trailing blanks first. `capture-pane -p` emits one line per pane *row*, not+ // per rendered line β verified against tmux 3.5a: a 20-row pane holding one+ // word comes back as 20 lines, 19 of them empty. Anchoring the window to the+ // raw end would put it entirely inside that padding whenever the agent's+ // output has not yet filled the pane, find nothing, and stop pressing Enter+ // after one β the very park this exists to catch.+ let mut lines: Vec<&str> = pane.lines().collect();+ while lines.last().is_some_and(|l| l.trim().is_empty()) {+ lines.pop();+ }+ let start = lines.len().saturating_sub(COMPOSER_TAIL_LINES);+ pane_shows(&lines[start..].join("\n"), needle)+}++/// Press Enter until the message actually leaves the composer.///-/// Retried only while the pane is **unchanged** β the same rule the paste and the-/// dialog answers use. Submitting clears the composer and moves the message up,-/// which is a visible change; an unchanged pane means the Enter was dropped.-/// Never retried blindly: a stray Enter into an already-empty composer is its own-/// bug, and is exactly why codex stopped getting a second one.-fn submit_message(tmux_ops: &Arc<dyn TmuxOperations>, target: &str) {+/// The check is "the text is gone from the composer", not "the pane changed".+/// A repaint is not a submit: a **bare skill command** β one with no prompt after+/// it, which is what a phase whose command carries no `{task}`/`{task_id}` sends β+/// exactly matches a skill name, so the composer's command picker opens *on the+/// paste*. Enter is then consumed by the picker ("Press enter to insert"), which+/// inserts the command and repaints. The old change-detector read that repaint as+/// success and returned, leaving the command parked in the composer forever.+///+/// Measured against codex-cli 0.144.5 and cursor-agent 2026.08.25: both open the+/// picker on a pasted bare command, both need the second Enter, and both run the+/// skill once it arrives.+///+/// Falls back to the change-detector when the text is too short to track, and is+/// bounded either way β an agent that never submits costs `SUBMIT_ATTEMPTS`+/// keypresses, not an unbounded stream.+///+/// Known cost: agents echo the submitted message into the transcript just above+/// the composer, so a *successful* submit can leave the needle inside the window+/// and spend the remaining attempts. Those Enters land in an empty composer,+/// which is inert β except against a dialog that renders mid-submit, where a bare+/// Enter picks the highlighted option. `answer_session_dialogs` is what answers+/// those, and it runs on the refresh loop rather than here.+fn submit_message(tmux_ops: &Arc<dyn TmuxOperations>, target: &str, text: &str) {+ let needle = delivery_needle(text);for _ in 0..SUBMIT_ATTEMPTS {let before = tmux_ops.capture_pane(target).unwrap_or_default();let _ = tmux_ops.send_key(target, "Enter");for _ in 0..SUBMIT_CONFIRM_POLLS {std::thread::sleep(std::time::Duration::from_millis(200));- if let Ok(now) = tmux_ops.capture_pane(target) {- if now != before {- return;- }+ let Ok(now) = tmux_ops.capture_pane(target) else {+ continue;+ };+ match needle.as_deref() {+ Some(n) if !composer_holds(&now, n) => return,+ Some(_) => {}+ // Nothing distinctive enough to look for; the pane moving is all+ // there is to go on.+ None if now != before => return,+ None => {}}}}@@ -9687,16 +9732,11 @@ fn send_skill_and_prompt(// is unchanged, and only then is it submitted.deliver_message(tmux_ops, target, &text, true);std::thread::sleep(std::time::Duration::from_millis(150));- submit_message(tmux_ops, target);-- // 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.+ // How many Enters this takes is not fixed. A message with a prompt+ // after the command submits on the first; a bare command opens the+ // command picker on the paste and needs a second. `submit_message`+ // decides by watching the composer rather than counting keypresses.+ submit_message(tmux_ops, target, &text);}return;}@@ -10748,40 +10788,54 @@ 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.+/// The `agtx hook` invocation registered for one agent.+///+/// Task-agnostic: the hook reads AGTX_TASK_ID / AGTX_WORKTREE from the window+/// env. Baking the task id in breaks `skip_worktree`, where every task shares one+/// config file.+fn hook_command(agtx_bin: &str, agent: &str) -> String {+ format!("{} hook --env {}", agtx_bin, agent)+}+/// 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.+/// Event names verified against claude 2.1.247. Unregistered names are ignored,+/// so listing one an older build does not know is harmless.+#[cfg(test)]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!({+ claude_shaped_hooks(agtx_bin, "claude", agent::HookConfigKind::ClaudeSettings)+}++/// The `{Event: [{matcher, hooks: [{type, command}]}]}` shape, which four of the+/// six agents share. Where the object goes and what the events are called still+/// differ β that is `write_hook_config` and [`hook_events`].+fn claude_shaped_hooks(+ agtx_bin: &str,+ agent_name: &str,+ kind: agent::HookConfigKind,+) -> serde_json::Value {+ let base = hook_command(agtx_bin, agent_name);+ let argv_event = agent::spec(agent_name)+ .is_some_and(|s| s.hook_event_source == agent::HookEventSource::Argv);+ let mut out = serde_json::Map::new();+ for (event, matcher) in hook_status::hook_events(kind) {+ let command = if argv_event {+ format!("{} --event {}", base, event)+ } else {+ base.clone()+ };+ let mut group = serde_json::json!({"hooks": [{ "type": "command", "command": command }]});- if let (Some(m), Some(obj)) = (matcher, e.as_object_mut()) {+ if let (Some(m), Some(obj)) = (matcher, group.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),- })+ out.insert(+ (*event).to_string(),+ serde_json::Value::Array(vec![group]),+ );+ }+ serde_json::Value::Object(out)}/// Re-deploy agent configs for worktrees that were set up by a different agtx@@ -10897,38 +10951,67 @@ 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+ let mut hooks = 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));+ merge_hook_events(&mut hooks, ours);+ // Pruning to nothing removes the key rather than leaving `"hooks": {}`, so a+ // worktree with hooks turned off is byte-identical to one that never had them.+ if hooks.is_empty() {+ settings.remove("hooks");+ } else {+ settings.insert("hooks".to_string(), serde_json::Value::Object(hooks));+ }+}++/// True when a handler entry is one agtx wrote, in either shape agents accept:+/// the Claude wrapper `{hooks: [{command}]}` or cursor's flat `{command}`.+///+/// Matched 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.+fn is_agtx_hook_entry(def: &serde_json::Value) -> bool {+ if def["command"].as_str().is_some_and(is_agtx_hook_command) {+ return true;+ }+ def["hooks"].as_array().is_some_and(|hooks| {+ hooks+ .iter()+ .any(|h| h["command"].as_str().is_some_and(is_agtx_hook_command))+ })+}++/// Replace agtx's handlers under each event in `ours`, leaving the user's own+/// entries on those events untouched and every other event alone.+///+/// An event whose `ours` value is an empty array is *pruned*: agtx's handlers are+/// stripped and nothing replaces them, and the key is dropped entirely when+/// nothing else was registered under it. That is what turning `agent_hooks` off+/// uses to unregister from a worktree that already has hooks deployed.+fn merge_hook_events(+ existing: &mut serde_json::Map<String, serde_json::Value>,+ ours: serde_json::Value,+) {+ let Some(ours) = ours.as_object() else {+ return;+ };+ 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_agtx_hook_entry(d)).cloned().collect())+ .unwrap_or_default();+ if let Some(arr) = our_defs.as_array() {+ defs.extend(arr.iter().cloned());+ }+ if defs.is_empty() {+ existing.remove(event);+ } else {+ existing.insert(event.clone(), serde_json::Value::Array(defs));}}- settings.insert("hooks".to_string(), serde_json::Value::Object(merged));}fn write_skills_to_worktree(@@ -11011,13 +11094,12 @@ fn write_skills_to_worktree(let _ = std::fs::write(Path::new(worktree_path).join(DEPLOY_MARKER), &agtx_bin);for agent_name in agent_names {if let Some(spec) = agent::spec(agent_name) {- write_mcp_config(- spec,- worktree_path,- &project_path_str,- &agtx_bin,- agent_hooks,- );+ write_mcp_config(spec, worktree_path, &project_path_str, &agtx_bin);+ // After the MCP writer, never before: two agents keep their hooks in+ // the same file as their MCP config, and both writers+ // read-modify-write it. Called even when hooks are off, so a worktree+ // deployed with them on gets them removed rather than left firing.+ write_hook_config(spec, worktree_path, &agtx_bin, agent_hooks);}}@@ -11044,6 +11126,209 @@ fn write_skills_to_worktree(}}+/// Write one agent's lifecycle-hook config into its worktree.+///+/// Selected by [`HookConfigKind`](agent::HookConfigKind); `None` means the agent+/// reports nothing and the pane-hash heuristic runs unchanged.+///+/// Every path here is inside the worktree β all six agents accept a project-local+/// hook config, so agtx never writes into `~/.codex`, `~/.gemini` or `~/.cursor`+/// and removing the worktree removes the registration.+///+/// The writers whose file is shared with an MCP config, or may be committed,+/// merge; the rest own their file and are written outright.+fn write_hook_config(+ spec: &agent::AgentSpec,+ worktree_path: &str,+ agtx_bin: &str,+ enabled: bool,+) {+ let Some(kind) = spec.hook_config else {+ return;+ };+ let wt = Path::new(worktree_path);+ // When hooks are off this is an *empty* set of handlers under the same event+ // names, which `merge_hook_events` reads as "strip agtx's and add nothing".+ // Skipping the call instead would leave a worktree deployed while hooks were+ // on firing `agtx hook` forever after they were turned off.+ let ours = if enabled {+ claude_shaped_hooks(agtx_bin, spec.name, kind)+ } else {+ empty_hook_events(kind)+ };++ match kind {+ // Shares `.claude/settings.local.json` with the MCP preflight keys+ // `write_mcp_config` just wrote.+ agent::HookConfigKind::ClaudeSettings => {+ merge_hooks_into_json_settings(&wt.join(".claude").join("settings.local.json"), ours);+ }+ // Same shape; `.gemini/settings.json` also carries `mcpServers` and+ // `trust: true`.+ agent::HookConfigKind::GeminiSettings => {+ merge_hooks_into_json_settings(&wt.join(".gemini").join("settings.json"), ours);+ }+ // `.codex/hooks.json` is auto-discovered β no pointer in+ // `.codex/config.toml`, whose `hooks` key is a table, not a path;+ // assigning a string to it makes codex reject the entire config with+ // "invalid type: string, expected struct HooksToml" and lose its MCP+ // server with it. The events sit under a `hooks` object beside an+ // optional `description`. codex-cli 0.144.5.+ agent::HookConfigKind::CodexHooksJson => {+ let dir = wt.join(".codex");+ let _ = std::fs::create_dir_all(&dir);+ let path = dir.join("hooks.json");+ let mut root = read_json_object(&path);+ let mut hooks = root+ .get("hooks")+ .and_then(|v| v.as_object().cloned())+ .unwrap_or_default();+ merge_hook_events(&mut hooks, ours);+ if hooks.is_empty() {+ root.remove("hooks");+ } else {+ root.entry("description".to_string())+ .or_insert_with(|| serde_json::json!("agtx phase status"));+ root.insert("hooks".to_string(), serde_json::Value::Object(hooks));+ }+ write_json(&path, &serde_json::Value::Object(root));+ }+ // `{version, hooks: {event: [{command}]}}`. The one agent that does not+ // take the Claude-shaped `{hooks: [{type, command}]}` wrapper β its+ // handlers are a flat list of `{command}`, and written the other way the+ // file parses, loads, and fires nothing. cursor-agent 2026.08.25.+ agent::HookConfigKind::CursorHooksJson => {+ let command = hook_command(agtx_bin, spec.name);+ let mut ours = serde_json::Map::new();+ for (event, _) in hook_status::hook_events(kind) {+ let defs = if enabled {+ serde_json::json!([{ "command": command }])+ } else {+ serde_json::json!([])+ };+ ours.insert((*event).to_string(), defs);+ }+ // Merges, like every other writer whose file the project may ship. A+ // worktree is a full checkout, so a repo that tracks+ // `.cursor/hooks.json` has it here β and clobbering it would both+ // destroy the user's hooks and leave a modified tracked file on the+ // task branch for the agent to commit. `.cursor` is not in+ // AGENT_CONFIG_DIRS either, so the diff view would not hide it.+ let dir = wt.join(".cursor");+ let _ = std::fs::create_dir_all(&dir);+ let path = dir.join("hooks.json");+ let mut root = read_json_object(&path);+ let mut hooks = root+ .get("hooks")+ .and_then(|v| v.as_object().cloned())+ .unwrap_or_default();+ merge_hook_events(&mut hooks, serde_json::Value::Object(ours));+ if hooks.is_empty() {+ root.remove("hooks");+ } else {+ root.insert("version".to_string(), serde_json::json!(1));+ root.insert("hooks".to_string(), serde_json::Value::Object(hooks));+ }+ write_json(&path, &serde_json::Value::Object(root));+ }+ // Grok scans the directory, so agtx owns one file in it and never merges.+ agent::HookConfigKind::GrokHooksJson => {+ let dir = wt.join(".grok").join("hooks");+ let _ = std::fs::create_dir_all(&dir);+ write_json(&dir.join("agtx.json"), &serde_json::json!({ "hooks": ours }));+ }+ // Keyed by hook *name* first, event second; every handler carries its own+ // `--event` because the payload has no event name. `.agents/` is+ // vendor-neutral and may be committed, so this merges.+ agent::HookConfigKind::AntigravityHooksJson => {+ let dir = wt.join(".agents");+ let _ = std::fs::create_dir_all(&dir);+ let path = dir.join("hooks.json");+ let mut root = read_json_object(&path);+ // Keyed by hook name, so agtx owns one key and pruning is a removal+ // rather than a per-event filter.+ if enabled {+ root.insert(+ AGTX_HOOK_NAME.to_string(),+ antigravity_hook_spec(agtx_bin, spec, kind),+ );+ } else {+ root.remove(AGTX_HOOK_NAME);+ }+ write_json(&path, &serde_json::Value::Object(root));+ }+ }+}++/// The same event keys with no handlers, which `merge_hook_events` prunes.+fn empty_hook_events(kind: agent::HookConfigKind) -> serde_json::Value {+ let mut out = serde_json::Map::new();+ for (event, _) in hook_status::hook_events(kind) {+ out.insert((*event).to_string(), serde_json::json!([]));+ }+ serde_json::Value::Object(out)+}++/// The name agtx registers its hooks under, where the format is keyed by name.+const AGTX_HOOK_NAME: &str = "agtx";++/// Antigravity's per-event handlers, each carrying its own `--event`.+///+/// Its two event shapes are not interchangeable: tool events are grouped under a+/// `matcher`, the rest are a flat list of handlers, and the wrong shape is+/// silently ignored.+fn antigravity_hook_spec(+ agtx_bin: &str,+ spec: &agent::AgentSpec,+ kind: agent::HookConfigKind,+) -> serde_json::Value {+ let handler = |event: &str| {+ let base = hook_command(agtx_bin, spec.name);+ // `--event` only where the agent's payload carries no event name. Read+ // from the spec rather than assumed, so an agent that later needs the+ // same treatment gets it by setting one field.+ let command = match spec.hook_event_source {+ agent::HookEventSource::Argv => format!("{} --event {}", base, event),+ agent::HookEventSource::Payload => base,+ };+ serde_json::json!({ "type": "command", "command": command })+ };+ let mut out = serde_json::Map::new();+ for (event, matcher) in hook_status::hook_events(kind) {+ let entry = match matcher {+ Some(m) => serde_json::json!([{ "matcher": m, "hooks": [handler(event)] }]),+ None => serde_json::json!([handler(event)]),+ };+ out.insert((*event).to_string(), entry);+ }+ serde_json::Value::Object(out)+}++/// Read a JSON file as an object, or an empty one if it is missing or not an+/// object. Never an error: a config the user can fix is not a reason to refuse to+/// set up their worktree.+fn read_json_object(path: &Path) -> serde_json::Map<String, serde_json::Value> {+ std::fs::read_to_string(path)+ .ok()+ .and_then(|raw| serde_json::from_str::<serde_json::Value>(&raw).ok())+ .and_then(|v| v.as_object().cloned())+ .unwrap_or_default()+}++fn write_json(path: &Path, value: &serde_json::Value) {+ let _ = std::fs::write(path, serde_json::to_string_pretty(value).unwrap_or_default());+}++/// Merge agtx's hooks into a settings file it shares with other keys.+fn merge_hooks_into_json_settings(path: &Path, ours: serde_json::Value) {+ if let Some(parent) = path.parent() {+ let _ = std::fs::create_dir_all(parent);+ }+ let mut settings = read_json_object(path);+ merge_claude_hooks(&mut settings, ours);+ write_json(path, &serde_json::Value::Object(settings));+}+/// Write the project-scoped MCP server config for one agent into its worktree.////// Selected by [`McpConfigKind`](agent::McpConfigKind) rather than agent name.@@ -11060,7 +11345,6 @@ fn write_mcp_config(worktree_path: &str,project_path_str: &str,agtx_bin: &str,- agent_hooks: bool,) {let Some(kind) = spec.mcp_config else {return;@@ -11110,9 +11394,6 @@ fn write_mcp_config("skipDangerousModePermissionPrompt".to_string(),serde_json::json!(true),);- if agent_hooks {- merge_claude_hooks(obj, claude_hook_settings(&agtx_bin));- }}let _ = std::fs::write(&settings_path,@@ -11146,17 +11427,31 @@ fn write_mcp_config(// see `agent_trust`.}agent::McpConfigKind::GeminiJson => {- let cfg = serde_json::json!({- "mcpServers": {- "agtx": { "command": agtx_bin, "args": ["mcp-serve", &project_path_str], "trust": true }- }- });+ // Merge, don't overwrite. `.gemini` is in AGENT_CONFIG_DIRS, so a+ // project shipping its own settings.json has it copied into every+ // worktree, and a plain write drops the user's theme, model and any+ // `mcpServers` besides agtx. Same rule as the Claude writer above.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(),+ let path = dir.join("settings.json");+ let mut settings = read_json_object(&path);+ let mut servers = settings+ .get("mcpServers")+ .and_then(|v| v.as_object().cloned())+ .unwrap_or_default();+ servers.insert(+ "agtx".to_string(),+ serde_json::json!({+ "command": agtx_bin,+ "args": ["mcp-serve", &project_path_str],+ "trust": true+ }),+ );+ settings.insert(+ "mcpServers".to_string(),+ serde_json::Value::Object(servers),);+ write_json(&path, &serde_json::Value::Object(settings));}agent::McpConfigKind::CursorJson => {let cfg = serde_json::json!({diff --git a/src/tui/app_tests.rs b/src/tui/app_tests.rsindex 8989f2b..bf4a4b0 100644--- a/src/tui/app_tests.rs+++ b/src/tui/app_tests.rs@@ -4422,6 +4422,25 @@ fn redirect_agent_home() -> (std::path::PathBuf, std::sync::MutexGuard<'static,(dir.path().to_path_buf(), guard)}+/// Point `Database` at a throwaway data root.+///+/// `switch_to_project_keep_sidebar` opens a *real* project database for the path+/// it is handed. Without the redirect every run of the suite leaves an orphan+/// `projects/<hash>.db` in the user's own store, keyed by a temp dir that is+/// gone by the time the test returns. Same reasoning as `redirect_agent_home`,+/// and the lock is needed for the same reason: the target is process-global.+///+/// Hold the returned guard for the duration of the test.+fn redirect_data_dir() -> std::sync::MutexGuard<'static, ()> {+ static DATA_DIR: std::sync::OnceLock<tempfile::TempDir> = std::sync::OnceLock::new();+ static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());+ // A panicking test poisons the lock; the data is unit, so recover and carry on.+ let guard = LOCK.lock().unwrap_or_else(|e| e.into_inner());+ let dir = DATA_DIR.get_or_init(|| tempfile::tempdir().unwrap());+ std::env::set_var("AGTX_DATA_DIR", dir.path());+ guard+}+#[test]fn test_write_skills_to_worktree_mcp_antigravity() {let dir = tempfile::tempdir().unwrap();@@ -11079,6 +11098,8 @@ fn test_switch_to_project_reloads_config() {use std::fs;use tempfile::TempDir;+ let _data_dir = redirect_data_dir();+// Create a temp dir simulating a project with review = "codex"let project_dir = TempDir::new().unwrap();let agtx_dir = project_dir.path().join(".agtx");@@ -11227,6 +11248,406 @@ fn test_agent_hooks_false_writes_no_hooks() {assert!(v.get("hooks").is_none());}+// ββ hook configs for the other five agents ββββββββββββββββββββββββββββββββββ+//+// Formats and paths were read off each agent's own binary or bundled docs; see+// `HookConfigKind` for the versions. What these tests actually protect is the+// merge discipline: three of the six files may already exist in the user's repo,+// and a plain write would destroy settings agtx does not own.++/// Every agent with hook support must land a config the agent can find, with a+/// task-agnostic `agtx hook --env <agent>` command in it. A missing file is the+/// silent-failure mode: the board just keeps guessing from pane hashes.+#[test]+#[cfg(feature = "test-mocks")]+fn test_hook_config_is_written_for_every_hook_capable_agent() {+ let expected: &[(&str, &str)] = &[+ ("claude", ".claude/settings.local.json"),+ ("gemini", ".gemini/settings.json"),+ ("codex", ".codex/hooks.json"),+ ("cursor", ".cursor/hooks.json"),+ ("grok", ".grok/hooks/agtx.json"),+ ("antigravity", ".agents/hooks.json"),+ ];+ for (name, rel) in expected {+ let spec = crate::agent::spec(name).unwrap();+ if spec.hook_config.is_none() {+ continue; // codex is off pending its hook-trust review; see spec.rs+ }+ let dir = tempfile::tempdir().unwrap();+ let wt = dir.path().to_string_lossy().to_string();+ write_skills_to_worktree(&wt, dir.path(), &None, &[name], true);++ let raw = std::fs::read_to_string(dir.path().join(rel))+ .unwrap_or_else(|e| panic!("{name}: no hook config at {rel}: {e}"));+ assert!(+ raw.contains(&format!("hook --env {name}")),+ "{name}: {rel} must register the task-agnostic command, got {raw}"+ );+ }+}++/// The agents whose hook file is shared with something else must merge. Gemini's+/// `.gemini/settings.json` also carries `mcpServers` and `trust`, and the user's+/// own hooks may already be in it.+#[test]+#[cfg(feature = "test-mocks")]+fn test_gemini_hooks_merge_with_existing_settings() {+ let dir = tempfile::tempdir().unwrap();+ let wt = dir.path().to_string_lossy().to_string();+ std::fs::create_dir_all(dir.path().join(".gemini")).unwrap();+ std::fs::write(+ dir.path().join(".gemini/settings.json"),+ r#"{"theme":"Dracula","hooks":{"BeforeTool":[{"hooks":[{"type":"command","command":"mine.sh"}]}]}}"#,+ )+ .unwrap();++ write_skills_to_worktree(&wt, dir.path(), &None, &["gemini"], true);+ let v: serde_json::Value = serde_json::from_str(+ &std::fs::read_to_string(dir.path().join(".gemini/settings.json")).unwrap(),+ )+ .unwrap();++ assert_eq!(v["theme"], serde_json::json!("Dracula"), "user key survived");+ assert_eq!(v["mcpServers"]["agtx"]["command"].is_string(), true);+ let before_tool = v["hooks"]["BeforeTool"].as_array().unwrap();+ assert_eq!(before_tool.len(), 2, "user hook kept, agtx hook appended");+ assert_eq!(before_tool[0]["hooks"][0]["command"], "mine.sh");+ assert_eq!(v["hooks"]["AfterAgent"][0]["hooks"][0]["command"].is_string(), true);+}++/// Redeploying must replace agtx's entries rather than accumulate them β+/// otherwise the hook fires N times per event, once per deploy. Matched on the+/// `hook --env` invocation, not the binary path, so a moved agtx still+/// recognises its own work.+#[test]+#[cfg(feature = "test-mocks")]+fn test_redeploying_hooks_is_idempotent_for_every_agent() {+ for name in ["claude", "gemini", "cursor", "grok", "antigravity"] {+ if crate::agent::spec(name).unwrap().hook_config.is_none() {+ continue;+ }+ let dir = tempfile::tempdir().unwrap();+ let wt = dir.path().to_string_lossy().to_string();+ write_skills_to_worktree(&wt, dir.path(), &None, &[name], true);+ let once = read_all_configs(dir.path());+ write_skills_to_worktree(&wt, dir.path(), &None, &[name], true);+ let twice = read_all_configs(dir.path());+ assert_eq!(once, twice, "{name}: second deploy changed the config");+ }+}++fn read_all_configs(root: &Path) -> Vec<(String, String)> {+ let mut out = Vec::new();+ for rel in [+ ".claude/settings.local.json",+ ".gemini/settings.json",+ ".codex/hooks.json",+ ".codex/config.toml",+ ".cursor/hooks.json",+ ".grok/hooks/agtx.json",+ ".agents/hooks.json",+ ] {+ if let Ok(body) = std::fs::read_to_string(root.join(rel)) {+ out.push((rel.to_string(), body));+ }+ }+ out+}++/// `.agents/` is vendor-neutral and a project may well ship one, so this file+/// must survive agtx writing into it β the same rule the antigravity MCP writer+/// follows next door.+#[test]+#[cfg(feature = "test-mocks")]+fn test_antigravity_hooks_preserve_a_projects_own_hooks() {+ let dir = tempfile::tempdir().unwrap();+ let wt = dir.path().to_string_lossy().to_string();+ std::fs::create_dir_all(dir.path().join(".agents")).unwrap();+ std::fs::write(+ dir.path().join(".agents/hooks.json"),+ r#"{"lint-checker":{"PostToolUse":[{"matcher":"run_command","hooks":[{"command":"./lint.sh"}]}]}}"#,+ )+ .unwrap();++ write_skills_to_worktree(&wt, dir.path(), &None, &["antigravity"], true);+ let v: serde_json::Value = serde_json::from_str(+ &std::fs::read_to_string(dir.path().join(".agents/hooks.json")).unwrap(),+ )+ .unwrap();++ assert_eq!(v["lint-checker"]["PostToolUse"][0]["hooks"][0]["command"], "./lint.sh");+ // Its payload carries no event name, so every handler must name its own.+ assert!(v["agtx"]["Stop"][0]["command"]+ .as_str()+ .unwrap()+ .ends_with("--event Stop"));+ assert!(v["agtx"]["PostToolUse"][0]["hooks"][0]["command"]+ .as_str()+ .unwrap()+ .ends_with("--event PostToolUse"));+ // Grouped vs flat is not cosmetic: antigravity ignores the wrong shape.+ assert!(v["agtx"]["PostToolUse"][0]["matcher"].is_string());+ assert!(v["agtx"]["Stop"][0]["matcher"].is_null());+ // The gating hook must stay unsubscribed; see hook_status_tests.+ assert!(v["agtx"]["PreToolUse"].is_null());+}++/// Cursor rejects a hooks file with no version envelope.+#[test]+#[cfg(feature = "test-mocks")]+fn test_cursor_hooks_carry_the_version_envelope() {+ let dir = tempfile::tempdir().unwrap();+ let wt = dir.path().to_string_lossy().to_string();+ write_skills_to_worktree(&wt, dir.path(), &None, &["cursor"], true);+ let v: serde_json::Value =+ serde_json::from_str(&std::fs::read_to_string(dir.path().join(".cursor/hooks.json")).unwrap())+ .unwrap();+ assert_eq!(v["version"], serde_json::json!(1));+ // Flat `{command}`, not the Claude `{hooks:[{type,command}]}` wrapper β+ // cursor loads the wrapped form without complaint and never fires it.+ assert!(v["hooks"]["stop"][0]["command"].is_string());+ assert!(v["hooks"]["stop"][0]["hooks"].is_null());+}++/// The toggle has to reach every agent, not just Claude.+#[test]+#[cfg(feature = "test-mocks")]+fn test_agent_hooks_false_writes_no_hooks_for_any_agent() {+ for name in ["claude", "gemini", "cursor", "grok", "antigravity"] {+ let dir = tempfile::tempdir().unwrap();+ let wt = dir.path().to_string_lossy().to_string();+ write_skills_to_worktree(&wt, dir.path(), &None, &[name], false);+ for (rel, body) in read_all_configs(dir.path()) {+ assert!(+ !body.contains("hook --env"),+ "{name}: agent_hooks=false still wrote hooks into {rel}"+ );+ }+ }+}++/// `capture-pane -p` pads its output to the pane height, so a composer that has+/// not been pushed to the bottom yet sits above a block of empty rows. Anchoring+/// the window to the raw end finds nothing there and stops after one Enter β+/// the park this exists to catch, reintroduced silently.+#[test]+fn test_composer_holds_looks_past_trailing_blank_rows() {+ let padded = format!("βΊ $agtx-review\n{}", "\n".repeat(30));+ assert!(+ composer_holds(&padded, "$agtx-review"),+ "trailing pane padding must not push the composer out of the window"+ );+}++// ββ hook configs the project may already ship βββββββββββββββββββββββββββββββ++/// A worktree is a full checkout, so a repo that tracks `.cursor/hooks.json` has+/// it here. Overwriting destroys the user's hooks *and* leaves a modified tracked+/// file on the task branch for the agent to commit.+#[test]+#[cfg(feature = "test-mocks")]+fn test_cursor_hooks_preserve_a_projects_own_hooks() {+ let dir = tempfile::tempdir().unwrap();+ let wt = dir.path().to_string_lossy().to_string();+ std::fs::create_dir_all(dir.path().join(".cursor")).unwrap();+ std::fs::write(+ dir.path().join(".cursor/hooks.json"),+ r#"{"version":1,"hooks":{"stop":[{"command":"./mine.sh"}],"afterFileEdit":[{"command":"./fmt.sh"}]}}"#,+ )+ .unwrap();++ write_skills_to_worktree(&wt, dir.path(), &None, &["cursor"], true);+ let v: serde_json::Value = serde_json::from_str(+ &std::fs::read_to_string(dir.path().join(".cursor/hooks.json")).unwrap(),+ )+ .unwrap();++ // An event agtx does not touch survives untouched.+ assert_eq!(v["hooks"]["afterFileEdit"][0]["command"], "./fmt.sh");+ // An event agtx shares keeps the user's handler and gains agtx's.+ let stop = v["hooks"]["stop"].as_array().unwrap();+ assert_eq!(stop.len(), 2);+ assert_eq!(stop[0]["command"], "./mine.sh");+ assert!(stop[1]["command"].as_str().unwrap().contains("hook --env cursor"));+}++/// Redeploying must replace agtx's own flat `{command}` entries, not stack them.+/// The Claude-shaped matcher looks inside a `hooks` array that cursor's entries+/// do not have, so a shape-blind match would duplicate on every deploy.+#[test]+#[cfg(feature = "test-mocks")]+fn test_cursor_hooks_do_not_accumulate_across_deploys() {+ let dir = tempfile::tempdir().unwrap();+ let wt = dir.path().to_string_lossy().to_string();+ write_skills_to_worktree(&wt, dir.path(), &None, &["cursor"], true);+ write_skills_to_worktree(&wt, dir.path(), &None, &["cursor"], true);+ let v: serde_json::Value = serde_json::from_str(+ &std::fs::read_to_string(dir.path().join(".cursor/hooks.json")).unwrap(),+ )+ .unwrap();+ assert_eq!(v["hooks"]["stop"].as_array().unwrap().len(), 1);+}++/// Turning hooks off has to reach worktrees that already have them, or they keep+/// firing `agtx hook` for the life of the task.+#[test]+#[cfg(feature = "test-mocks")]+fn test_turning_hooks_off_unregisters_an_existing_worktree() {+ for name in ["claude", "gemini", "cursor", "grok", "antigravity"] {+ let dir = tempfile::tempdir().unwrap();+ let wt = dir.path().to_string_lossy().to_string();+ write_skills_to_worktree(&wt, dir.path(), &None, &[name], true);+ assert!(+ read_all_configs(dir.path())+ .iter()+ .any(|(_, b)| b.contains("hook --env")),+ "{name}: nothing was deployed to un-deploy"+ );++ write_skills_to_worktree(&wt, dir.path(), &None, &[name], false);+ for (rel, body) in read_all_configs(dir.path()) {+ assert!(+ !body.contains("hook --env"),+ "{name}: {rel} still fires agtx hook after agent_hooks was turned off"+ );+ }+ }+}++/// The user's own hooks must survive that un-deploy β pruning removes agtx's+/// entries, not the file.+#[test]+#[cfg(feature = "test-mocks")]+fn test_turning_hooks_off_leaves_the_users_own_hooks() {+ let dir = tempfile::tempdir().unwrap();+ let wt = dir.path().to_string_lossy().to_string();+ std::fs::create_dir_all(dir.path().join(".cursor")).unwrap();+ std::fs::write(+ dir.path().join(".cursor/hooks.json"),+ r#"{"version":1,"hooks":{"stop":[{"command":"./mine.sh"}]}}"#,+ )+ .unwrap();+ write_skills_to_worktree(&wt, dir.path(), &None, &["cursor"], true);+ write_skills_to_worktree(&wt, dir.path(), &None, &["cursor"], false);++ let v: serde_json::Value = serde_json::from_str(+ &std::fs::read_to_string(dir.path().join(".cursor/hooks.json")).unwrap(),+ )+ .unwrap();+ assert_eq!(v["hooks"]["stop"].as_array().unwrap().len(), 1);+ assert_eq!(v["hooks"]["stop"][0]["command"], "./mine.sh");+}++/// `--event` is driven by the spec, not by the agent's name, so an agent that+/// later needs it gets it from one field.+#[test]+fn test_argv_event_agents_carry_their_event_in_the_command() {+ for spec in agent::AGENT_SPECS {+ let Some(kind) = spec.hook_config else {+ continue;+ };+ let json = claude_shaped_hooks("/bin/agtx", spec.name, kind);+ for (event, _) in hook_status::hook_events(kind) {+ let cmd = json[event][0]["hooks"][0]["command"].as_str().unwrap_or("");+ let wants_argv = spec.hook_event_source == agent::HookEventSource::Argv;+ assert_eq!(+ cmd.contains("--event"),+ wants_argv,+ "{}: {event} command disagrees with hook_event_source",+ spec.name+ );+ }+ }+}++// ββ submitting a message ββββββββββββββββββββββββββββββββββββββββββββββββββββ+//+// Pane text below is captured verbatim from live sessions. The bare-command case+// is the one that mattered: a repaint used to count as a submit, so a command+// parked in a picker looked delivered and the phase never advanced.++/// codex 0.144.5, after pasting a bare `$agtx-review`: the picker is open and the+/// command is still in the composer. Enter here *inserts*; it does not submit.+const CODEX_PARKED: &str = "\+β’ You have 1 usage limit reset available. Run /usage to use one.+βΊ $agtx-review+ agtx-review [Skill] Self-review completed work. Check for correctnessβ¦+ Press enter to insert or esc to close";++/// The same session after the command was actually submitted: the composer is+/// back to its placeholder and the text has moved into the scrollback.+const CODEX_SUBMITTED: &str = "\+β’ I'm using the agtx-review skill to inspect the task's diff and commits.+β’ Ran sed -n '1,240p' .codex/skills/agtx-review/SKILL.md+β’ Working (6s β’ esc to interrupt)+βΊ Use /skills to list available skills+ gpt-5.6-sol default Β· /private/tmp/β¦";++/// cursor-agent 2026.08.25, parked with its picker open β the state+/// `submit_message` actually sees, not the tidied one left behind afterwards.+/// The suggestion renders *below* the composer box and the footer wraps the+/// worktree path, so the text being submitted sits eight lines off the bottom.+const CURSOR_PARKED: &str = "\+ ββββββββββββββββββββ+ β /agtx-review+ ββββββββββββββββββββ+ β /agtx-review Self-review completed work. Check for correctnessβ¦+ Auto Β· 9.6% Β· 4 files edited Run Everything+ /private/tmp/claude-501/-Users-fynn-workspace-agtx/69231794-89a8-48a+ 5da1fead47/scratchpad/fixrun/cursor-agtx/.agtx/worktrees/21edaf6d-sm+ r-agtx Β· task/21edaf6d-smoke-cursor-agtx";++#[test]+fn test_composer_holds_sees_a_parked_command() {+ assert!(+ composer_holds(CODEX_PARKED, "$agtx-review"),+ "a command sitting in the composer must not read as submitted"+ );+ assert!(+ composer_holds(CURSOR_PARKED, "/agtx-review"),+ "an open picker and a wrapped footer put the text eight lines up; \+ the window must still reach it"+ );+}++#[test]+fn test_composer_holds_ignores_the_scrollback() {+ // The skill name appears in the agent's own narration above the composer.+ // Finding it there is proof the message went, not that it stayed.+ assert!(+ !composer_holds(CODEX_SUBMITTED, "$agtx-review"),+ "text echoed into the scrollback must not read as still-pending"+ );+}++/// The regression itself: a bare command needs a second Enter, and the first+/// one's repaint must not be mistaken for success.+#[test]+#[cfg(feature = "test-mocks")]+fn test_submit_message_presses_enter_again_when_the_picker_ate_the_first() {+ let mut mock = MockTmuxOperations::new();+ let seq = Arc::new(std::sync::Mutex::new(0usize));+ let c = seq.clone();+ // Parked before and after the first Enter β a repaint, not a submit β then+ // submitted once the second lands.+ mock.expect_capture_pane().returning(move |_| {+ let n = *c.lock().unwrap();+ Ok(if n < 2 { CODEX_PARKED } else { CODEX_SUBMITTED }.to_string())+ });+ let c2 = seq.clone();+ mock.expect_send_key()+ .times(2)+ .withf(|_, k| k == "Enter")+ .returning(move |_, _| {+ *c2.lock().unwrap() += 1;+ Ok(())+ });++ let ops: Arc<dyn TmuxOperations> = Arc::new(mock);+ submit_message(&ops, "t:1", "$agtx-review");+}+// ββ first-launch dialog handling (wait_for_agent_ready) ββββββββββββββββββββββ/// Regression: a native-binary agent changes `pane_current_command` the moment@@ -11871,6 +12292,9 @@ fn test_launch_dialog_derivation_matches_the_previous_literals() {vec!["1", "Enter"],),(vec!["Update now (runs"], vec!["2", "Enter"]),+ // "Continue without trusting" β declines rather than grants, so it is+ // answered like the update prompt above rather than left to the user.+ (vec!["Hooks need review"], vec!["3", "Enter"]),// Enter alone: an arrow-navigated menu with the safe option preselected.(vec!["Do you trust the contents of this project?"],@@ -12386,11 +12810,12 @@ fn test_trust_block_clears_once_the_dialog_is_gone() {// submit_message β the Enter that submits is its own delivery problem// ===========================================================================-/// A dropped Enter is retried, because an unchanged pane means the composer-/// never took it.+/// A dropped Enter is retried while the message is still in the composer, and+/// the retries are bounded β an agent that never submits must cost a fixed+/// number of keypresses, not an unbounded stream into its composer.#[test]#[cfg(feature = "test-mocks")]-fn test_submit_message_retries_while_the_pane_is_unchanged() {+fn test_submit_message_retries_while_the_composer_still_holds_it() {let mut mock = MockTmuxOperations::new();// Same frame every time: nothing ever submits.mock.expect_capture_pane()@@ -12400,14 +12825,14 @@ fn test_submit_message_retries_while_the_pane_is_unchanged() {.withf(|_, k| k == "Enter").returning(|_, _| Ok(()));let ops: Arc<dyn TmuxOperations> = Arc::new(mock);- submit_message(&ops, "t:1");+ submit_message(&ops, "t:1", "/agtx:execute abc");}/// One Enter is enough when the composer clears β a second would fire into an-/// empty composer, which is the bug codex's double-Enter used to be.+/// already-empty composer.#[test]#[cfg(feature = "test-mocks")]-fn test_submit_message_stops_once_the_pane_changes() {+fn test_submit_message_stops_once_the_composer_clears() {let mut mock = MockTmuxOperations::new();let calls = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));let c = std::sync::Arc::clone(&calls);@@ -12426,7 +12851,7 @@ fn test_submit_message_stops_once_the_pane_changes() {.withf(|_, k| k == "Enter").returning(|_, _| Ok(()));let ops: Arc<dyn TmuxOperations> = Arc::new(mock);- submit_message(&ops, "t:1");+ submit_message(&ops, "t:1", "/agtx:execute abc");}// === Update notice ===diff --git a/tests/db_tests.rs b/tests/db_tests.rsindex a6dc8f5..186cf2e 100644--- a/tests/db_tests.rs+++ b/tests/db_tests.rs@@ -509,8 +509,28 @@ fn test_consume_notifications_atomic_under_concurrent_consumers() {use std::path::Path;use tempfile::TempDir;+/// Point `Database` at a throwaway data root for the tests below.+///+/// These are the only tests that open a *real* database rather than an+/// in-memory one. Without the redirect each run leaves an orphan+/// `projects/<hash>.db` in the user's own store, keyed by a temp path that no+/// longer exists β nothing ever collects them. The lock is needed because the+/// redirect target is process-global.+///+/// Hold the returned guard for the duration of the test.+fn redirect_data_dir() -> (std::path::PathBuf, std::sync::MutexGuard<'static, ()>) {+ static DATA_DIR: std::sync::OnceLock<TempDir> = std::sync::OnceLock::new();+ static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());+ // A panicking test poisons the lock; the data is unit, so recover and carry on.+ let guard = LOCK.lock().unwrap_or_else(|e| e.into_inner());+ let dir = DATA_DIR.get_or_init(|| TempDir::new().unwrap());+ std::env::set_var("AGTX_DATA_DIR", dir.path());+ (dir.path().to_path_buf(), guard)+}+#[test]fn test_open_project_same_path_returns_same_db() {+ let (_data_dir, _guard) = redirect_data_dir();let temp_dir = TempDir::new().unwrap();let project_path = temp_dir.path();@@ -528,6 +548,7 @@ fn test_open_project_same_path_returns_same_db() {#[test]fn test_open_project_different_paths_are_isolated() {+ let (_data_dir, _guard) = redirect_data_dir();let temp1 = TempDir::new().unwrap();let temp2 = TempDir::new().unwrap();@@ -547,6 +568,7 @@ fn test_project_db_file_permissions_are_0600() {use sha2::{Digest, Sha256};use std::os::unix::fs::PermissionsExt;+ let (data_dir, _guard) = redirect_data_dir();let temp_dir = TempDir::new().unwrap();let _db = Database::open_project(temp_dir.path()).unwrap();@@ -562,11 +584,7 @@ fn test_project_db_file_permissions_are_0600() {u64::from_be_bytes(result[..8].try_into().unwrap()));- let config_dir = directories::ProjectDirs::from("", "", "agtx").unwrap();- let db_path = config_dir- .config_dir()- .join("projects")- .join(format!("{}.db", path_hash));+ let db_path = data_dir.join("projects").join(format!("{}.db", path_hash));assert!(db_path.exists(),@@ -583,19 +601,21 @@ fn test_project_db_file_permissions_are_0600() {fn test_global_db_file_permissions_are_0600() {use std::os::unix::fs::PermissionsExt;+ let (data_dir, _guard) = redirect_data_dir();let _db = Database::open_global().unwrap();- let config_dir = directories::ProjectDirs::from("", "", "agtx").unwrap();- let db_path = config_dir.config_dir().join("index.db");+ // The redirect makes this unconditional: before it, the test opened the+ // user's own index.db and skipped the assertion when it happened not to+ // exist yet.+ let db_path = data_dir.join("index.db");+ assert!(db_path.exists(), "Expected index.db at {:?}", db_path);- if db_path.exists() {- let perms = std::fs::metadata(&db_path).unwrap().permissions();- let mode = perms.mode() & 0o777;- assert_eq!(- mode, 0o600,- "Global DB file should be owner-only read/write"- );- }+ let perms = std::fs::metadata(&db_path).unwrap().permissions();+ let mode = perms.mode() & 0o777;+ assert_eq!(+ mode, 0o600,+ "Global DB file should be owner-only read/write"+ );}// === Dependency-graph integration tests (real Database + deps_satisfied) ===diff --git a/tests/hook_status_tests.rs b/tests/hook_status_tests.rsindex bcd18a6..96c4507 100644--- a/tests/hook_status_tests.rs+++ b/tests/hook_status_tests.rs@@ -4,12 +4,46 @@//! `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,+ map_hook_event, read_status, status_path, write_status, AgentHookStatus, HookState,+ BLOCKED_GUARD_SECS, HOOK_STALE_SECS,};+use agtx::agent::HookConfigKind;use std::path::Path;use tempfile::TempDir;+/// Claude's arm of the kind-keyed mapper.+///+/// These two shims keep every assertion below independent of the extra parameter+/// the functions take, so a change to Claude's behaviour shows up as a failing+/// assertion rather than a diff. Do not inline them.+fn map_claude_event(event: &str) -> Option<HookState> {+ map_hook_event(HookConfigKind::ClaudeSettings, event)+}++#[allow(clippy::too_many_arguments)]+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> {+ agtx::agent::hook_status::merge_event(+ previous,+ HookConfigKind::ClaudeSettings,+ event,+ now,+ agent,+ session_id,+ transcript_path,+ message,+ tool,+ )+}+fn status(state: HookState, ts: i64) -> AgentHookStatus {AgentHookStatus {ts,@@ -340,3 +374,367 @@ fn env_mode_ignores_background_workers() {"a background worker must not write status for its parent task");}++// ββ every agent, not just Claude βββββββββββββββββββββββββββββββββββββ+//+// The vocabularies below were read off each agent's binary or bundled docs at the+// versions named in `src/agent/spec.rs`. Literals on purpose, like the launch+// strings in `agent_parity_tests.rs`: a diff here means an agent's contract+// changed.++/// Guards a failure that is invisible in production: the agent accepts a+/// registration for an event nothing maps, fires it, and the board goes on+/// guessing from pane hashes. Nothing logs, nothing fails.+#[test]+fn every_registered_event_has_a_state_mapping() {+ for kind in ALL_KINDS {+ for (event, _) in agtx::agent::hook_status::hook_events(*kind) {+ assert!(+ map_hook_event(*kind, event).is_some(),+ "{:?} registers {event:?} but map_hook_event does not map it β \+ the hook would fire and report nothing",+ kind+ );+ }+ }+}++const ALL_KINDS: &[HookConfigKind] = &[+ HookConfigKind::ClaudeSettings,+ HookConfigKind::CodexHooksJson,+ HookConfigKind::GeminiSettings,+ HookConfigKind::CursorHooksJson,+ HookConfigKind::GrokHooksJson,+ HookConfigKind::AntigravityHooksJson,+];++/// Registering an event agtx cannot act on is dead weight in the agent's turn:+/// every fire pays a process spawn to decide nothing.+#[test]+fn every_mapped_event_is_actually_registered() {+ for kind in ALL_KINDS {+ let registered: Vec<&str> = agtx::agent::hook_status::hook_events(*kind)+ .iter()+ .map(|(e, _)| *e)+ .collect();+ for event in vocabulary(*kind) {+ if map_hook_event(*kind, event).is_some() {+ assert!(+ registered.contains(event),+ "{:?} maps {event:?} but never registers it",+ kind+ );+ }+ }+ }+}++/// Each agent's full published event vocabulary, mapped or not β the input to+/// the coverage checks above.+fn vocabulary(kind: HookConfigKind) -> &'static [&'static str] {+ match kind {+ // Claude Code 2.1.247.+ HookConfigKind::ClaudeSettings => &[+ "SessionStart",+ "UserPromptSubmit",+ "PreToolUse",+ "PostToolUse",+ "PermissionRequest",+ "Notification",+ "Stop",+ "StopFailure",+ "SubagentStop",+ "PreCompact",+ "PostCompact",+ "SessionEnd",+ ],+ // codex-cli 0.144.5, from the hook schema embedded in the binary.+ HookConfigKind::CodexHooksJson => &[+ "SessionStart",+ "UserPromptSubmit",+ "PreToolUse",+ "PostToolUse",+ "PermissionRequest",+ "PreCompact",+ "PostCompact",+ "Stop",+ "SubagentStart",+ "SubagentStop",+ ],+ // gemini-cli 0.46.0, from bundled docs/hooks/index.md.+ HookConfigKind::GeminiSettings => &[+ "SessionStart",+ "SessionEnd",+ "BeforeAgent",+ "AfterAgent",+ "BeforeModel",+ "AfterModel",+ "BeforeToolSelection",+ "BeforeTool",+ "AfterTool",+ "PreCompress",+ "Notification",+ ],+ // cursor-agent 2026.08.25.+ HookConfigKind::CursorHooksJson => &[+ "sessionStart",+ "sessionEnd",+ "beforeSubmitPrompt",+ "preToolUse",+ "postToolUse",+ "postToolUseFailure",+ "stop",+ "subagentStart",+ "subagentStop",+ "preCompact",+ "workspaceOpen",+ "beforeShellExecution",+ "beforeMCPExecution",+ "beforeReadFile",+ "afterFileEdit",+ ],+ // grok 1.0.5. Registration spelling; its payloads report the snake_case+ // form of the same names, which `squash` reconciles.+ HookConfigKind::GrokHooksJson => &[+ "SessionStart",+ "SessionEnd",+ "UserPromptSubmit",+ "PreToolUse",+ "PostToolUse",+ "PostToolUseFailure",+ "PermissionDenied",+ "Notification",+ "Stop",+ "StopFailure",+ "StopCancelled",+ "SubagentStart",+ "SubagentStop",+ "PreCompact",+ "PostCompact",+ ],+ // agy 1.1.21 β the whole vocabulary is five events. `PreToolUse` is one+ // of them and is deliberately neither mapped nor registered; see the+ // antigravity arm of `hook_events`.+ HookConfigKind::AntigravityHooksJson => &[+ "PreInvocation",+ "PostInvocation",+ "PostToolUse",+ "Stop",+ ],+ }+}++/// One agent's event name must not resolve against another's arm: `Stop` means+/// "turn over" to four agents, while Gemini's equivalent is `AfterAgent` and+/// Cursor's is lowercase `stop`. A typo matching the wrong arm would report a+/// plausible-looking wrong state.+#[test]+fn vocabularies_do_not_leak_across_agents() {+ assert_eq!(map_hook_event(HookConfigKind::GeminiSettings, "Stop"), None);+ assert_eq!(map_hook_event(HookConfigKind::CursorHooksJson, "Stop"), None);+ assert_eq!(+ map_hook_event(HookConfigKind::ClaudeSettings, "stop"),+ None,+ "Cursor's lowercase stop must not resolve against Claude"+ );+ assert_eq!(+ map_hook_event(HookConfigKind::ClaudeSettings, "AfterAgent"),+ None+ );+ assert_eq!(+ map_hook_event(HookConfigKind::AntigravityHooksJson, "SessionEnd"),+ None,+ "antigravity has no session lifecycle event at all"+ );+}++/// The two states that drive a feature rather than an icon: `Blocked` fires the+/// orchestrator's immediate stuck-task notification, and `Waiting` is what makes+/// a finished turn distinguishable from a stalled one.+#[test]+fn turn_end_is_expressible_for_every_agent() {+ for kind in ALL_KINDS {+ let ends: Vec<&str> = agtx::agent::hook_status::hook_events(*kind)+ .iter()+ .map(|(e, _)| *e)+ .filter(|e| map_hook_event(*kind, e) == Some(HookState::Waiting))+ .collect();+ assert!(+ !ends.is_empty(),+ "{:?} can never report Waiting β every turn would look like work in \+ progress until the staleness timer expired",+ kind+ );+ }+}++/// Cursor and Antigravity have no human-blocking event to subscribe to. Pinned+/// so the gap is not closed later with a wrong mapping.+#[test]+fn only_agents_with_a_permission_event_report_blocked() {+ let can_block: Vec<HookConfigKind> = ALL_KINDS+ .iter()+ .copied()+ .filter(|k| {+ agtx::agent::hook_status::hook_events(*k)+ .iter()+ .any(|(e, _)| map_hook_event(*k, e) == Some(HookState::Blocked))+ })+ .collect();+ assert_eq!(+ can_block,+ vec![+ HookConfigKind::ClaudeSettings,+ HookConfigKind::CodexHooksJson,+ HookConfigKind::GeminiSettings,+ HookConfigKind::GrokHooksJson,+ ],+ "Cursor exposes only policy gates that decide (beforeShellExecution), and \+ Antigravity's five events contain no permission prompt"+ );+}++/// Antigravity's payload is protojson camelCase with no event name and no+/// `session_id`: the event arrives in argv, and the identity fields resolve by+/// alias or not at all.+#[test]+fn antigravity_payload_round_trips_through_the_cli() {+ let dir = TempDir::new().unwrap();+ std::env::set_var("AGTX_TASK_ID", "t-agy");+ std::env::set_var("AGTX_WORKTREE", dir.path());++ // A real `PostToolUse` payload: protojson camelCase, `stepIdx`, and no+ // `hook_event_name` anywhere in it.+ let payload = serde_json::json!({+ "conversationId": "ec33ebf9-0cba-4100-8142-c61503f6c587",+ "workspacePaths": ["/tmp/wt"],+ "transcriptPath": "/tmp/wt/.gemini/antigravity-cli/transcript.jsonl",+ "artifactDirectoryPath": "/tmp/wt/.gemini/antigravity-cli/artifacts",+ "modelName": "auto",+ "stepIdx": 19,+ })+ .to_string();++ agtx::agent::hook_status::record_hook_event(+ "t-agy",+ &dir.path().to_string_lossy(),+ "antigravity",+ Some("PostToolUse"),+ payload.as_bytes(),+ );++ let got = read_status(dir.path(), "t-agy", 0).expect("argv event must be honoured");+ std::env::remove_var("AGTX_TASK_ID");+ std::env::remove_var("AGTX_WORKTREE");++ assert_eq!(got.state, HookState::Working);+ assert_eq!(got.agent, "antigravity");+ assert_eq!(+ got.session_id.as_deref(),+ Some("ec33ebf9-0cba-4100-8142-c61503f6c587"),+ "conversationId is antigravity's session id"+ );+ assert_eq!(+ got.transcript_path.as_deref(),+ Some("/tmp/wt/.gemini/antigravity-cli/transcript.jsonl")+ );+}++/// An agent with `hook_config: None` writes nothing even when the CLI is invoked+/// in its name, so a registration left behind by an older agtx cannot keep+/// reporting under a vocabulary that no longer exists.+#[test]+fn an_agent_without_hooks_writes_nothing() {+ let dir = TempDir::new().unwrap();+ std::env::set_var("AGTX_TASK_ID", "t-oc");+ std::env::set_var("AGTX_WORKTREE", dir.path());++ let wt = dir.path().to_string_lossy().to_string();+ let payload = br#"{"hook_event_name":"SessionStart"}"#;++ agtx::agent::hook_status::record_hook_event("t-oc", &wt, "opencode", None, payload);+ let a = read_status(dir.path(), "t-oc", 0);++ agtx::agent::hook_status::record_hook_event("t-oc", &wt, "not-an-agent", None, payload);+ let b = read_status(dir.path(), "t-oc", 0);++ std::env::remove_var("AGTX_TASK_ID");+ std::env::remove_var("AGTX_WORKTREE");+ assert!(a.is_none(), "opencode has no hook support");+ assert!(b.is_none(), "an unknown agent must not borrow a vocabulary");+}++/// Grok registers `PreToolUse` and reports `pre_tool_use`. Matching only the+/// registered spelling is a silent no-op: the hook fires, the payload parses, and+/// no state is written.+#[test]+fn grok_answers_to_both_of_its_spellings() {+ for (registered, reported) in [+ ("SessionStart", "session_start"),+ ("UserPromptSubmit", "user_prompt_submit"),+ ("PreToolUse", "pre_tool_use"),+ ("Stop", "stop"),+ ("StopCancelled", "stop_cancelled"),+ ("SessionEnd", "session_end"),+ ] {+ let a = map_hook_event(HookConfigKind::GrokHooksJson, registered);+ let b = map_hook_event(HookConfigKind::GrokHooksJson, reported);+ assert!(a.is_some(), "{registered} unmapped");+ assert_eq!(a, b, "{registered} and {reported} are the same event");+ }+}++/// A status hook must not decide whether a tool runs. Antigravity's `PreToolUse`+/// makes `decision` required and reads anything else as a refusal, so subscribing+/// blocks every tool call β and the only safe subscription would answer+/// `"allow"`, a permission decision a liveness reporter has no business making.+#[test]+fn antigravity_never_subscribes_to_its_gating_hook() {+ let registered: Vec<&str> =+ agtx::agent::hook_status::hook_events(HookConfigKind::AntigravityHooksJson)+ .iter()+ .map(|(e, _)| *e)+ .collect();+ assert!(+ !registered.contains(&"PreToolUse"),+ "antigravity's PreToolUse requires a decision field; subscribing blocks every tool call"+ );+ assert_eq!(+ map_hook_event(HookConfigKind::AntigravityHooksJson, "PreToolUse"),+ None+ );+ assert_eq!(+ map_hook_event(HookConfigKind::AntigravityHooksJson, "PostToolUse"),+ Some(HookState::Working),+ "PostToolUse carries the heartbeat instead, and its contract wants the empty \+ JSON object this hook already prints"+ );+}++/// Grok scans `.claude/settings*.json` and `.cursor/hooks.json` for vendor+/// compatibility, so in a worktree configured for several phase agents it fires+/// agtx's Claude- and cursor-registered hooks with *its own* payloads.+///+/// Claude's arm rejects them outright. Cursor's does not: it is lowercase and+/// contains `stop`, which is exactly what grok reports. That is a real overlap,+/// pinned here rather than assumed away β the state agrees (both mean the turn+/// ended), so the cost is a record carrying a neighbouring agent's name, and+/// nothing reads that name.+#[test]+fn a_grok_payload_reaching_a_neighbours_registration() {+ for event in ["session_start", "user_prompt_submit", "pre_tool_use"] {+ assert_eq!(+ map_hook_event(HookConfigKind::ClaudeSettings, event),+ None,+ "grok's {event} must not resolve against Claude's PascalCase arm"+ );+ assert_eq!(map_hook_event(HookConfigKind::CursorHooksJson, event), None);+ }+ // The one that does overlap, and agrees.+ assert_eq!(+ map_hook_event(HookConfigKind::CursorHooksJson, "stop"),+ map_hook_event(HookConfigKind::GrokHooksJson, "stop"),+ "grok's `stop` resolves against cursor's arm; it must at least mean the same"+ );+ assert_eq!(map_hook_event(HookConfigKind::ClaudeSettings, "stop"), None);+}diff --git a/tests/smoke/agent_smoke.py b/tests/smoke/agent_smoke.pyindex 7e840c4..f52c26c 100755--- a/tests/smoke/agent_smoke.py+++ b/tests/smoke/agent_smoke.py@@ -592,6 +592,27 @@ def tmux(server: str, *args: str, check: bool = False) -> subprocess.CompletedPrreturn run(["tmux", "-L", server, *args], check=check)+def isolate_agtx_store(workdir: Path) -> Path:+ """Point agtx's databases at the scratch workdir for this run.++ Every scratch repo agtx opens is upserted into the global project index, and+ nothing ever removes a row β so without this each run permanently adds one+ sidebar entry per case, pointing at a mkdtemp path that is deleted minutes+ later. A single run of the full matrix adds seven.++ Set in `os.environ` so `agtx trust` and `agtx mcp-serve` inherit it; the TUI+ gets it explicitly via `new-session -e`, because a tmux server left running+ by an earlier run would otherwise hand the new session that run's environment.+ """+ store = workdir / "agtx-store"+ store.mkdir(parents=True, exist_ok=True)+ os.environ["AGTX_DATA_DIR"] = str(store)+ # A smoke run must not spend a GitHub API call, nor render an update notice+ # over the pane content the checks read.+ os.environ["AGTX_NO_UPDATE_CHECK"] = "1"+ return store++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)@@ -600,6 +621,8 @@ def start_tui(session: str, repo: Path, agtx_bin: str) -> None:# 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",+ "-e", f"AGTX_DATA_DIR={os.environ['AGTX_DATA_DIR']}",+ "-e", "AGTX_NO_UPDATE_CHECK=1",f"{shlex.quote(str(agtx_bin))} {shlex.quote(str(repo))}",)if proc.returncode != 0:@@ -856,13 +879,34 @@ def agent_is_live(target: str, pane: str, agent: dict) -> bool:return False-def check_command_submitted(pane: str, command: str | None, work_landed: bool) -> Check:+def check_command_submitted(+ pane: str, command: str | None, work_landed: bool, pane_before: str = ""+) -> 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.+ understood it", and it is the one that has to be hard to fool: a command the+ agent never read looks, from the outside, exactly like one it read and+ ignored.++ **How a park is recognised.** A submitted command has the agent's response+ rendered under it. A parked one has nothing under it but the composer's own+ furniture β box borders, a status bar, the worktree path, a picker+ suggestion. Distance from the bottom cannot tell those apart: a genuinely+ submitted command can sit four lines up with its output below, and a parked+ one five lines up behind cursor's wrapped footer. So the test is whether+ anything below the command is *new* β absent from `pane_before`, the pane as+ it looked before this phase was requested. Furniture is identical across the+ two; agent output is not.++ `pane_before` is empty for the first phase, whose command is handed over in+ argv at launch and so cannot park in a composer at all. That case keeps the+ older rule: a command with nothing under it at all.++ Known limit: a picker that is still *open* at capture time renders its own+ hint line, which reads as output. Not worth pattern-matching per agent β the+ pane is captured long after the phase settles, and by then the picker has+ closed and the command is parked, which is the state these fixtures pin.Two deliberate softenings, both because the pane is a rendered TUI ratherthan a log:@@ -870,10 +914,11 @@ def check_command_submitted(pane: str, command: str | None, work_landed: bool) -- the command not appearing at all is `unknown`, not a failure β severalTUIs redraw their scrollback, and check 2 catches a genuinely undeliveredcommand anyway;- - the command at the bottom of the screen only fails when nothing landed.+ - a command with no new output under it only fails when nothing landed.Claude Code renders a dim *suggestion* for the next phase's command in itsempty 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.+ `capture-pane -p` strips), so a bare command on screen is not proof of a+ park."""if not command:return Check("submitted", "n/a", "agent has no interactive command syntax")@@ -886,9 +931,32 @@ def check_command_submitted(pane: str, command: str | None, work_landed: bool) -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:++ below = [l.strip() for l in lines[hits[-1] + 1 :] if l.strip()]+ if pane_before:+ furniture = {l.strip() for l in pane_before.splitlines() if l.strip()}+ # An echo of the command is not evidence it ran. A picker renders the+ # skill under the composer *without* the sigil agtx sent it with+ # (`$agtx-review` is offered as `agtx-review`), so the sigil is stripped+ # before matching. This also swallows narration that merely names the+ # skill, which is deliberate: a phase that really ran leaves more behind+ # than its own name, and over-filtering here can only mislabel a phase+ # that has already failed β `work_landed` short-circuits the rest.+ echo = needle.split()[0].lstrip("/$@!:")+ produced = [+ l for l in below if l not in furniture and echo not in l and needle not in l+ ]+ if produced:+ return Check("submitted", "pass")+ if not work_landed:+ return Check(+ "submitted",+ "fail",+ "command is parked in the composer β nothing new rendered under it",+ )+ return Check("submitted", "pass")++ if not below and not work_landed:return Check("submitted", "fail", "command is the last thing on screen and nothing ran")@@ -1032,7 +1100,14 @@ class CaseRunner:raise TimeoutError(f"{what} not reached within {timeout}s")# -- phases ----------------------------------------------------------- def drive_phase(self, task_id: str, phase: str, worktree: Path, cycle: int) -> PhaseResult:+ def drive_phase(+ self,+ task_id: str,+ phase: str,+ worktree: Path,+ cycle: int,+ pane_before: str = "",+ ) -> 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@@ -1091,7 +1166,7 @@ class CaseRunner:result = PhaseResult(phase=phase, pane_tail=tail(pane, 20))result.checks = [- check_command_submitted(pane, command, work_landed),+ check_command_submitted(pane, command, work_landed, pane_before),marker_check,artifact_check,check_usable(@@ -1181,8 +1256,14 @@ class CaseRunner:write_fixture(worktree, task_id, artifacts, self.opts.phases)self.log(f"worktree {worktree}")+ # What the pane looked like before each phase was requested. Check 1+ # subtracts it to tell the agent's output from the composer's own+ # furniture; the first phase has none, and needs none.+ pane_before = ""for index, phase in enumerate(self.opts.phases):- phase_res = self.drive_phase(task_id, phase, worktree, task.get("cycle", 1))+ phase_res = self.drive_phase(+ task_id, phase, worktree, task.get("cycle", 1), pane_before+ )res.phases.append(phase_res)if phase_res.outcome != PASS:res.outcome = phase_res.outcome@@ -1192,6 +1273,9 @@ class CaseRunner:)breakif index + 1 < len(self.opts.phases):+ # Captured before the transition, so the next phase's command+ # has not been sent yet and anything under it will be new.+ pane_before = self.pane(task_id)self.move_forward(task_id)nxt = self.opts.phases[index + 1]task = self.wait_for(@@ -1460,9 +1544,11 @@ def main(argv: list[str] | None = None) -> int:tempfile.mkdtemp(prefix="agtx-smoke-"))workdir.mkdir(parents=True, exist_ok=True)+ isolate_agtx_store(workdir)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}")+ print(f"agtx store: {os.environ['AGTX_DATA_DIR']}")results: list[CaseResult] = []for case in cases:diff --git a/tests/smoke/test_agent_smoke.py b/tests/smoke/test_agent_smoke.pyindex 8520e3a..a667a3d 100644--- a/tests/smoke/test_agent_smoke.py+++ b/tests/smoke/test_agent_smoke.py@@ -258,6 +258,90 @@ class Checks(unittest.TestCase):smoke.check_command_submitted(pane, "/agtx:plan abc-123", False).state, "pass")+ # The two panes below are captured verbatim from live sessions where agtx+ # pasted a bare skill command, the agent's picker ate the Enter, and the+ # command sat unsent. Both reported `submitted=pass` under the old+ # distance-from-the-bottom rule β the harness certified the exact failure it+ # exists to catch. They are the regression fixtures for that.++ CODEX_BEFORE = "\n".join([+ "β’ Implementation complete. Summary written to .agtx/execute.md.",+ "",+ "βΊ Use /skills to list available skills",+ " gpt-5.6-sol default Β· /private/tmp/β¦",+ ])+ CODEX_PARKED = "\n".join([+ "β’ Implementation complete. Summary written to .agtx/execute.md.",+ "",+ "βΊ $agtx-review",+ " gpt-5.6-sol default Β· /private/tmp/β¦",+ ])+ CURSOR_BEFORE = "\n".join([+ " Implementation complete. Summary written to .agtx/execute.md.",+ " ββββββββββββββββββββ",+ " β Add a follow-up",+ " ββββββββββββββββββββ",+ " Auto Β· 9.6% Β· 4 files edited Run Everything",+ " /private/tmp/claude-501/-Users-fynn-workspace-agtx/69231794-89a8",+ " 5da1fead47/scratchpad/fixrun/cursor-agtx/.agtx/worktrees/21edaf6d",+ " r-agtx Β· task/21edaf6d-smoke-cursor-agtx",+ ])+ CURSOR_PARKED = CURSOR_BEFORE.replace("β Add a follow-up", "β /agtx-review")++ def test_a_parked_bare_command_is_not_reported_as_submitted(self):+ """codex 0.144.5: two lines up, behind a status bar."""+ check = smoke.check_command_submitted(+ self.CODEX_PARKED, "$agtx-review", False, self.CODEX_BEFORE+ )+ self.assertEqual(check.state, "fail")+ self.assertIn("parked", check.detail)++ def test_a_park_behind_a_wrapped_footer_is_still_a_park(self):+ """cursor 2026.08.25: five lines up, behind a box border and a path that+ wraps. Distance from the bottom cannot separate this from a submitted+ command with output under it β only the baseline can."""+ check = smoke.check_command_submitted(+ self.CURSOR_PARKED, "/agtx-review", False, self.CURSOR_BEFORE+ )+ self.assertEqual(check.state, "fail")+ self.assertIn("parked", check.detail)++ def test_output_under_the_command_still_counts_as_submitted(self):+ """A submitted command scrolls up out of the composer with the agent's+ response under it β the same furniture below, but no longer adjacent."""+ pane = "\n".join([+ " Implementation complete. Summary written to .agtx/execute.md.",+ " β /agtx-review",+ " Reviewing the diffβ¦",+ " Wrote .agtx/review.md",+ " ββββββββββββββββββββ",+ " β Add a follow-up",+ " ββββββββββββββββββββ",+ " Auto Β· 9.6% Β· 4 files edited Run Everything",+ " r-agtx Β· task/21edaf6d-smoke-cursor-agtx",+ ])+ self.assertEqual(+ smoke.check_command_submitted(+ pane, "/agtx-review", False, self.CURSOR_BEFORE+ ).state,+ "pass",+ )++ def test_an_echo_of_the_command_is_not_evidence_it_ran(self):+ """A picker offers the skill under the composer *without* the sigil agtx+ sent it with, so `$agtx-review` comes back as `agtx-review`. Matching the+ sent string alone would read that echo as the agent's output."""+ pane = self.CODEX_PARKED.replace(+ " gpt-5.6-sol default Β· /private/tmp/β¦",+ " agtx-review [Skill] Self-review completed work.\n"+ " gpt-5.6-sol default Β· /private/tmp/β¦",+ )+ check = smoke.check_command_submitted(+ pane, "$agtx-review", False, self.CODEX_BEFORE+ )+ self.assertEqual(check.state, "fail")+ self.assertIn("parked", check.detail)+def test_invisible_command_is_unknown_not_a_failure(self):"""Several TUIs redraw their scrollback; check 2 catches real misses."""self.assertEqual(