diff --git a/.gitignore b/.gitignore index 5a67d6cd..53da5c53 100644 --- a/.gitignore +++ b/.gitignore @@ -31,6 +31,19 @@ src-tauri/gen/schemas # Tool artifacts .playwright-mcp/ +__pycache__/ +*.pyc + +# Local settings and secrets +.env +.env.* +!.env.example + +# Claude Code's per-machine state (the shared launch.json and skills stay tracked) +.claude/settings.local.json +.claude/worktrees/ +.claude/checkpoints/ +.claude/scheduled_tasks.* # Overrides a global "research/" ignore: these docs and the adapter test fixtures belong in the repo !docs/research/ diff --git a/.gitleaks.toml b/.gitleaks.toml new file mode 100644 index 00000000..b74e63b6 --- /dev/null +++ b/.gitleaks.toml @@ -0,0 +1,9 @@ +# The default rules, plus one allowance: recorded CLI output carries Anthropic API message ids +# (`"api_message_id":"msg_…"`), which the generic-api-key rule takes for keys. +[extend] +useDefault = true + +[[allowlists]] +description = "API message ids in recorded CLI output" +regexTarget = "match" +regexes = ['''api_message_id"\s*:\s*"msg_[A-Za-z0-9]+"?'''] diff --git a/README.md b/README.md index c41bc494..b98c712d 100644 --- a/README.md +++ b/README.md @@ -7,116 +7,34 @@ ▶ [Watch the 3-minute tour](https://cdn.jsdelivr.net/gh/jwuthri-cloud/Codly@ed48fc5f4c9288d5e500d73756b29836b638e716/docs/media/codly-tour.mp4): ask the Lead, run its plan, approve, merge, and start a long-term agent of your own. -Codly turns the coding CLIs you already pay for (Claude Code, Codex, Gemini CLI and OpenCode) into one -team on your Mac. A Lead agent plans the work, each agent builds in its own git worktree, and nothing -lands on your branch until you merge it. It is a macOS app built with Tauri, Svelte and Rust. +## What Codly is -![Codly's World view: coding agents at work in a 3D office](site/shots/office.jpg) - -## Why - -Running several coding agents in one repo gets messy fast. They step on each other's files, you lose -track of who is doing what, and every approval is a prompt in a separate terminal. Codly puts them -under one supervisor and shows the same events in two synchronized views: - -- **Workspace**: chat with the Lead or talk 1:1 with any agent. Per-agent timeline, shared board, task - dependency graph, diffs, terminals, and an approvals inbox. -- **World**: a three.js office. Agents walk to the library to search, to the server room to run tests, - and raise a hand when they need you. Every motion comes from a real event. - -## Screenshots - -These come from the built-in demo: a fake `acme/web` repo with a scripted team. - -### The Lead proposes a plan - -Describe the goal to the Lead. It reads the repo read-only and either answers or proposes a small plan: -tasks, dependencies, the agent for each task, and any assumptions it made. You run it, change it or -cancel it. +Codly runs the coding CLIs you already have (Claude Code, Codex, Gemini CLI and OpenCode) as one +team on your Mac. A Lead agent plans the work. Each worker builds in its own git worktree. Codly +checks the work, can have another agent review it, and merges it into a branch of its own. Nothing +lands on your branch until you press Merge. It is a macOS app built with Tauri, Svelte and Rust. -![The Lead proposes a plan with three tasks and assumptions to confirm](site/shots/plan.jpg) - -### Follow the plan as it runs - -The plan room lists every task with its checks and the files it may write. A task that depends on -another waits until that one is merged. - -![Plan room showing tasks in progress and tasks waiting on them](site/shots/planroom.jpg) - -### Review finished work +Running several agents in one repo by hand gets messy: they edit the same files, you lose track of +who does what, and every approval is a prompt in another terminal. Codly puts them under one +supervisor and shows the same events in two views: -Each finished task shows the verify command that ran, the size of the diff, and the integration branch it -merged into. Agents can ask the Lead a question mid-task, and the answer comes back into the thread. - -![A finished task with its test result, diff size and merge target](site/shots/done.jpg) +- **Workspace**: chat with the Lead or talk 1:1 with any agent. A timeline per agent, a shared + board, the task graph, diffs, terminals and the approval cards. +- **World**: a three.js office. Agents walk to the library to search, to the server room to run + tests, and raise a hand when they need you. Every work motion comes from a real event. -### Approve what matters - -Commands an agent wants to run arrive in one approvals inbox. Codly checks each request against its rules -first (here: it deletes files, stays inside the agent's worktree, and makes no network calls), then asks -you. Approve once, allow for the session, or deny. For a command you trust, or a tool of an MCP server -that a Claude Code agent asks for, choose "Always allow in this repo": Codly then stops asking every agent in that repo about it (never about -deletes, `git push`, `sudo`, secrets or paths outside the worktree), and Settings lists the rules so you -can remove them. - -![Approval request for a shell command, with Approve once, Allow for this session and Deny](site/shots/approval.jpg) - -## How it works - -1. **Ask the Lead.** It reads the repo read-only and either answers or submits a task plan. Each request - has a mode: Ask (answers only), Plan (you press Run plan), Auto (plans and runs) or Direct (hands the - work straight to a team member or consultant). Tasks go to your standing team or to a consultant the - Lead hires for one task. -2. **Validate and run.** Codly checks the plan for cycles and for two tasks writing the same files at once. - You click **Run plan**. -3. **Work in isolation.** Each task runs in its own git worktree and branch. The worker gets a pointer pack - of the relevant code and the team's memory. -4. **Land the work.** When a worker finishes, Codly commits, re-runs the verify commands, checks the write - scope, optionally asks a reviewer from another vendor, and merges into the plan's integration branch. - Agents never commit on their own. -5. **You merge.** Review the diff and merge it into your branch. Codly pushes your branch only when you - press Push. For a review on GitHub, **Create pull request** pushes the plan's branch and opens a pull - request with a title and a description drafted from the plan, which you can edit first. - -Agents coordinate through Codly's MCP tools, so every exchange is typed, validated and visible. Every -agent gets `codly_get_task`, `codly_board`, `codly_search`, `codly_memory_search`, `codly_memory_write`, -`codly_kg_query`, `codly_kg_add` and `codly_post_note`. The Lead adds `codly_submit_plan`, -`codly_message_member`, `codly_quick_task` and `codly_reassign`. Workers add `codly_submit_report` and -`codly_ask_lead`. Reviewers get `codly_submit_review`. The Lead and workers can also raise -`codly_ask_user` to ask you a decision. - -## Supported agents - -| Agent | How Codly talks to it | -| ----------- | -------------------------------------------------------------------------------------- | -| Claude Code | `claude` in stream-JSON mode, with the stdin control protocol for approvals and interrupts | -| Codex | One `codex app-server` per agent (JSON-RPC over stdio): live command output, real approvals | -| Gemini CLI | ACP (`gemini --acp`) | -| OpenCode | ACP (`opencode acp`) | - -Cursor and Copilot use the same ACP adapter, but they are less tested. - -## First run - -A short onboarding quest line checks which agent CLIs are installed, offers a visible "Run it for me" -install terminal for the missing ones, and walks you through setting up a Lead, a crew and a first -mission. - -Approvals have four modes: balanced, strict, autonomous and Full access (auto-approves everything except -a few hard floors; off unless you choose it). Autonomous is a list of risky commands, not a sandbox: see -[What an agent's commands can do](#subscriptions-and-safety). Settings also holds Triggers (schedules and -network mode) and Inbound (webhook sources for the Lead; Slack is not available yet). - -## Requirements +![Codly's World view: coding agents at work in a 3D office](site/shots/office.jpg) -- macOS 14 or later -- At least one agent CLI, installed and signed in +Status: early. This is the v0.1 vertical slice. Expect rough edges, and read +[Limits and known gaps](#limits-and-known-gaps) before you point it at a repository you care about. ## Install +You need macOS 14 or later and at least one agent CLI, installed and signed in. + ### Download -Coming with the first release: there is no download yet. Until a release is on the +There is no release yet. Until one is on the [Releases page](https://github.com/jwuthri-cloud/Codly/releases), build Codly from source (below). When a release is there: @@ -144,7 +62,7 @@ Codly does not update itself yet: for a newer version, download it again. ### Build from source -You need Rust 1.90+, Node 22+ and pnpm. +You need Rust 1.90 or later, Node (CI uses Node 22) and pnpm. ```bash pnpm install @@ -152,256 +70,516 @@ pnpm tauri dev # run the desktop app from the checkout scripts/install-app.sh # or build Codly.app and put it in /Applications ``` -Other useful commands: +To look at the UI without building the app, `pnpm dev` serves it in a browser on a scripted demo: +no agent CLI runs and nothing is written to disk. [docs/DEMO.md](docs/DEMO.md) lists the URL +parameters that open each screen. -```bash -pnpm dev # the UI alone in a browser, on a scripted demo session -pnpm test # frontend tests (Vitest) -pnpm check # svelte-check and TypeScript -cargo test --workspace # core tests; adapters replay captured CLI transcripts -pnpm tauri build # build the macOS app and .dmg -``` +## First run -To use Codly from a browser instead of its window, run the app with `serve`: +The onboarding is a short quest line. It checks which agent CLIs are installed and signed in, offers +**Install for me** (a visible terminal that runs the vendor's install command) for the missing ones, +and walks you through a Lead, a crew and a first request. Then open a repository (⌘O). -```bash -/Applications/Codly.app/Contents/MacOS/codly serve # prints a link with a token; --port N -``` +## The main flow -It runs without a window or Dock icon until Ctrl+C. Run while the app is already open, -the open app serves too and opens the link in your browser. +These screenshots come from the browser demo: a made-up `acme/web` repo with a scripted team. -`codly serve` listens on this Mac only (127.0.0.1). The page can open terminals and control your -agents, and the traffic is plain HTTP, so to reach it from another machine use an SSH tunnel: -`ssh -L 4280:127.0.0.1:4280 `, then open the link on that machine. `--host
` -with an address other machines can reach is refused unless you add `--allow-remote`; the link -then works for anyone on your network until Codly stops. Quit the app first: an app that is -already open does not serve to the network. `codly --help` lists every command and -`codly --version` prints the version. +### 1. Ask -## Develop +Write to the Lead. It reads the repo read-only. Each request has a mode, picked under the composer +or with ⇧⇥: -Before you push, run the checks that CI runs: +- **Ask**: the Lead only answers. +- **Plan** (the default): the Lead proposes a plan and you press **Run plan**. +- **Auto**: the plan runs at once. **Run plans without asking** in Settings makes Auto the default. +- **Direct**: no plan card; the work goes straight to a team member or a consultant. -```bash -scripts/verify.sh # pnpm check, pnpm test, pnpm build, cargo test --workspace -``` +You can also start a request from a GitHub issue or pull request (**From issue…**, **From pull +request…** in the `/` menu): your own `gh` reads it. Each request has its own Lead and thread +(⌘N for a new one), so several requests can run side by side. -It also fails when the tests rewrite `src/lib/gen`: those TypeScript types are generated from the -Rust types by `cargo test`, so commit them with the change that needs them. +### 2. Plan -CI (`.github/workflows/ci.yml`) runs the same script on Linux for every pull request and every -push to `main`, and compiles the workspace on macOS. To run it on Linux yourself, install the -system packages the workflow lists. +The plan lists tasks, their dependencies, the agent for each task, the files each task may write, +the commands that check it, and the assumptions the Lead made. Codly checks the plan: no cycles, +and two tasks that would write the same files run one after the other. You run it, change it or +cancel it. A task whose checks cannot fail (`true`, `test -f …`) is marked on the card. -## Troubleshooting +![The Lead proposes a plan with three tasks and assumptions to confirm](site/shots/plan.jpg) -Settings → General → Troubleshooting collects what a bug report needs: the Codly version, your -system, your agent CLIs and the last log lines. Tokens, keys, email addresses and paths under your -home folder are taken out. Repository and agent names can remain: read it, then paste it in the -issue. The same button is on the “Codly couldn’t start” screen. +### 3. Run -The log file is `~/Library/Application Support/dev.codly.desktop/logs/codly.log` (at most 5 MB; -the file before it is `codly.1.log`). An internal error (a panic) writes its place and backtrace -there. To log more, start Codly with `CODLY_LOG=debug`: the file then also takes Codly's own -debug lines (those of the libraries it uses go to the terminal only). +Each task runs in its own git worktree and branch, started from the plan's integration branch. The +worker gets a pointer pack of the relevant code and the team's memory. A task that depends on +another waits until that one is merged. Tasks go to your standing team (set in Settings → Team) or +to a consultant the Lead hires for one task. -## Project layout - -- `crates/codly-core/`: the engine, with no Tauri dependency. Orchestrator (Lead, team, planner, scheduler, - merge queue, approval broker, triggers), agent adapters, SQLite store, git, code index, memory, inbound - sources and the MCP server. -- `src-tauri/`: the macOS shell (Tauri 2) that hosts the engine, and `codly serve` (the same UI in a - browser). -- `src/`: the Svelte 5 UI: the Workspace, the World (`src/office/`, three.js), the neighbourhood map - (`src/world/`), Settings (`src/overlays/`) and onboarding. -- `public/`: the office's furniture models and sounds. These are third-party assets (CC0 and CC BY); - each folder has its licence or credits file. -- `site/`: the landing page and the live demo build. -- `scripts/`: `install-app.sh` builds Codly.app and installs it in /Applications; `kaykit-clips.py` - converts animation clips for the World. -- `voice/`: experimental and optional. A Python relay that lets you talk to an agent out loud through - OpenAI Realtime, used only by `codly serve`. Its start script needs the author's own OpenAI workload - identity, so nobody else can run it as it is. Without the relay everything else works; a voice call - fails with "the voice relay is not running". -- `research-skills/`: optional skills for research work. They are not part of the app; you install them - by hand with `research-skills/install.sh`. -- `docs/`: architecture, design notes and the research behind them. +![Plan room showing tasks in progress and tasks waiting on them](site/shots/planroom.jpg) -The full code map is in [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md), section 8. +### 4. Approve -## Subscriptions and safety - -**Your sign-ins and keys** - -- Codly spawns the unmodified CLIs you installed and signed in to. It does not proxy them. To see who is - signed in, it runs the CLI's own status command (Claude Code, Codex) or reads the CLI's settings file - (Gemini: the sign-in method and the account email, no token). -- Codly does not read your CLIs' sign-in tokens, with one exception that is off until you turn it on: - **Show Claude usage before an agent runs** (Settings → Accounts). With it on, each time Codly checks - your sign-ins it reads the Claude Code sign-in token (from the Keychain, or from the sign-in's - `.credentials.json` file) and sends it to `api.anthropic.com` to ask for your usage, as `/usage` does. - Codly does not store or log the token. Check Anthropic's terms first: they may not allow another app to - use this token. With it off, a sign-in shows its usage once an agent has run on it. -- Keys that you give to Codly are stored in the macOS Keychain, not in Codly's settings or database: your - own API keys (Settings → API keys; each one goes to one CLI only), the Groq key for dictation, webhook - secrets, and the keys of the tool servers you switch on for agents. -- Each agent shows a billing badge (subscription, API key or third party). API-key variables that would - silently switch billing are removed from agent environments, unless you turned on your own API key for - that vendor. -- The same goes for the variables that give Claude Code another sign-in than `claude auth login`: - `CLAUDE_CODE_USE_BEDROCK`, `CLAUDE_CODE_USE_VERTEX` and `CLAUDE_CODE_OAUTH_TOKEN` (a token from - `claude setup-token`). Codly removes them from agent environments unless you turn on **Use my shell's - Claude sign-in** (Settings → Safety). With it on, Claude agents keep them from your login shell, as - Claude Code does in your terminal, and that account pays. Codly does not store the token. Check - Anthropic's terms before you use a subscription token this way. Every other `CLAUDE_CODE_*` variable - is always removed, so that an agent never takes itself for a part of the Claude Code session that - started Codly. +What an agent wants to do and Codly's rules do not settle comes to you as a card in the +conversation. Codly reads each request against its rules first (for example: it deletes files, it +reaches outside the agent's worktree, it uses the network), then asks you: **Approve once**, +**Allow for this session** or **Deny** (⌘↵, ⌥⌘↵, ⌘⌫; ⇧⌘⌫ denies with a note). A Codex request for +more permissions says in words which folders or network it wants and which are outside its +worktree. Questions an agent asks you come the same way: 1 to 9 pick an option and ⌘↵ sends the +answer. A plan a Claude agent shows you has no plain "no": you send it back with a note, since +without one Claude Code shows the same plan again. What you said with an answer (a note, an +answer, a changed plan) stays on the closed card. See [Safety](#safety) for the approval modes +and the saved rules. -**Your repository** +![Approval request for a shell command, with Approve once, Allow for this session and Deny](site/shots/approval.jpg) + +### 5. Review + +When a worker finishes, Codly commits its work (agents never commit by themselves), runs the task's +checks again, checks that it wrote only the files it was allowed to, and, if you turned on +**Cross-vendor review before merge**, asks an agent of another CLI to review it. A failure goes back +to the worker to fix. Work that passes merges into the plan's integration branch. + +In the Changes room you can read each diff, comment on lines, tick files as viewed, and send a task +back with your comments. **Last turn** shows only what an agent's last turn changed. On a finished +plan that is not merged yet, **Send back** makes your comments one more task of the plan, for the +agent that wrote those files; on merged work it opens a new request with them. + +![A finished task with its test result, diff size and merge target](site/shots/done.jpg) + +### 6. Merge + +A finished plan's card has **Merge into \**. Before you merge you can try the work: +**Run…** runs a command you type (for example `pnpm dev --port $CODLY_PORT_BASE`) in the plan's +worktree, and **Open in terminal** opens a shell there. If your branch moved since the plan +started, Codly first runs the plan's checks on the merge result; if the merge conflicts, **Have an +agent resolve it** gives the plan one more task. **Push to \** pushes your branch. +**Create pull request…** pushes the plan's own branch instead and opens a pull request with your +`gh`, with a title and description drafted from the plan that you can edit first. + +### 7. Undo + +**Undo merge** takes the last merge back while nothing was committed or pushed after it. Before +each turn of an agent Codly keeps a checkpoint of its worktree: **Restore files to this point** (in +the agent's Git tab) puts the files back, and can itself be undone. In a 1:1 chat with an agent +that rests, Esc Esc or `/undo` opens **Undo a turn**: pick one of its turns, and its files go back +to how they were before it. + +### Talk to one agent + +Besides requests to the Lead, you can hire a long-term 1:1 agent and chat with it, as in its own +CLI. **Quick start with …** on the add-agent wizard's first step, or "Start an agent with …" in the +palette (⌘K), starts one with the CLI's defaults. It works in its own worktree (or, with **Git +isolation** off, in your project folder), and its Git tab has merge, push, pull request and +checkpoints. The composer's `/` menu has the agent's controls, as its CLI's slash commands do: +compact, context, mode, model, undo the last turn, your terminal, its MCP servers. For a Claude +Code agent ⇧⇥ switches its mode (ask for edits, accept edits, plan first), and a mode or model +change needs no restart. Its sheet lists its MCP servers with Reconnect, **Turn off** and **Turn +on**, and its background commands and helpers (subagents) with **Stop**. Codly opens on the +request you left. When you come back to a conversation, one row before the first new one says what +came while you were away. **Open in my +terminal** hands a Claude Code agent's session to your terminal (`claude --resume`), and **Give it +back** returns it to Codly. + +### How agents talk to Codly + +Agents coordinate through Codly's own MCP tools, so every exchange is typed, checked and visible. +Every agent gets `codly_get_task`, `codly_board`, `codly_search`, `codly_memory_search`, +`codly_memory_write`, `codly_kg_query`, `codly_kg_add` and `codly_post_note`. The Lead adds +`codly_submit_plan`, `codly_message_member`, `codly_quick_task` and `codly_reassign`. Workers add +`codly_submit_report` and `codly_ask_lead`. Reviewers get `codly_submit_review`. The Lead and +workers can also use `codly_ask_user` to ask you a decision. + +## Long runs and restarts + +- **Keep the Mac awake while agents work** (on by default): the Mac does not go to sleep by itself + while an agent works or a plan runs. It may sleep when all work waits for you. Closing the lid + still puts it to sleep. +- **Ask before quitting while agents work** (on by default). Agents are child processes of Codly: + they stop when it quits. +- **Resume work when Codly opens** (Ask by default): work that was under way when Codly closed does + not go on by itself. A bar at the top asks once: **Resume work** or **Not now**; until you + resume, no task starts, also after a pause or a budget ends. Always and Never are the other + choices. +- Silent agents: a turn with no output for 10 minutes is flagged and you are notified; at twice + that, the turn is interrupted once; after as long again, the run is stopped. A tool call that + gives no sign of life gets 60 minutes; Claude Code says every 30 s that a command, an MCP tool + or a helper still runs, so a hung one of those is noticed after 10. Settings → Safety → Limits + sets the times. +- A worker turn that fails is retried after a wait; at its third failure in a row the task is + blocked with the error, and **Retry** is on the row that says so. A plan that cannot go on says + so in its thread. +- Notifications (Settings → General → Notifications): one switch per kind, and by default only + while Codly is not in front. +- Budgets (Settings → Safety → Limits): a token budget and a cost budget for all agents + together, both off by default. A used-up budget stops new work; it never kills an agent. + +## Safety + +### Approval modes and saved rules + +Settings → Safety → Approvals has four modes: + +| Mode | What asks you | +| --- | --- | +| Balanced (default) | Codly's rules settle the obvious cases; what has a risk (`rm -rf`, `git push`, a path outside the worktree, a network install) asks you. | +| Ask first | Every command and edit the CLI would ask about. | +| Autonomous | Only what Codly sees a risk in. | +| Full access | Nothing about commands or edits, risky ones included, except a few hard floors (below). | + +In Full access these still ask: an agent's questions, a plan an agent shows you, permission +changes, changes to an agent's own CLI settings, writes to Codly's own data, anything from a read-only agent, and a command that can +lose work in your project folder itself (a history rewrite, `git reset --hard`, `git clean`, a force +push, `rm -rf` outside the build folders). + +The rules read the text of a command. They do not see what a script, a test or a program does once +it runs. So Autonomous is a list of risky commands, not a sandbox: a command with no risk in its +text runs without asking, with the rights of your account. + +For a command you trust, or a tool of an MCP server that a Claude Code agent asks for, choose +**Always allow in this repo** on its card: Codly then stops asking every agent in that repo about +it. A rule never covers deletes, `git push`, `sudo`, secrets, paths outside the worktree or a +command that can lose work in your project folder. +Settings → Safety → Approvals lists the rules so you can remove them. + +### OS sandboxes + +- Codex agents always start in Codex's own OS sandbox (`workspace-write`), which keeps their + writes in their working folder (its worktree) and a temporary folder. A command that Codex wants + to run outside the sandbox asks first, and the approval rules decide it like any other request: + Full access approves it. The sandbox's network is closed unless you turn on **Let Codex agents + use the network** (Settings → Safety → Sandbox; off by default). With it on, a command that needs + the network (a `git push`, a download) runs inside the sandbox without asking, so the approval + rules do not see it. +- Claude Code agents have no OS sandbox, unless you turn on **Sandbox Claude's shell** (Settings → + Safety → Sandbox; off by default). With it on, Claude Code runs the shell commands of workers + and 1:1 agents in its own OS sandbox: + - A sandboxed command can write only in the agent's folder (its worktree), a temporary folder and + the repository's git data. It can still read your other files. + - It can reach only the hosts that your Claude Code settings allow. Codly adds no host and no + folder. When a command wants another host, Codly asks you, in every approval mode except Full + access: the approval card names the host. Approve once lets this command connect. Claude Code + then does not ask again for this host while this agent keeps running. When the agent starts + again (Codly restarts, or a change that restarts the agent) it asks again. If you deny it, the + command gets a network error. + - Commands still go through the approval rules, as they do with the switch off: what the rules + ask about (a `git push`, an `rm -rf`, a download) still asks you first. The sandbox is a second + check under the rules, not a way around them. So one command can ask twice: once for itself, + and once for a host it wants. + - A command that Claude wants to run outside the sandbox asks you first, in every approval mode + except Full access. The approval card says that it runs outside the sandbox. + - When an agent starts, Codly asks Claude Code whether its sandbox is really on. If it is not + (your system cannot run it, or a setting of your organization changes it), the agent does not + start and Codly tells you why. + - The sandbox covers shell commands only. File edits and tool servers (MCP) are not sandboxed: + they go through approvals as before. Codly's own checks (a task's verify commands, the setup + script) are not sandboxed either. +- Gemini, OpenCode, Cursor and Copilot agents have no OS sandbox. For them, and for Claude Code + agents without the switch, the approval rules are the only check. + +### Folder trust + +A repo's own agent configuration (Claude Code project settings with hooks or allow rules, project +MCP servers, and the like for the other CLIs) loads only after you trusted the folder. Codly asks +when it opens such a repo and again when those files change. Until then Claude Code starts without +them, and a CLI that Codly cannot start without them (Gemini CLI, OpenCode, Cursor) is not started +in that repo: it takes no task and reviews none. A worktree whose files are not the ones of your +folder (an agent changed them there) is shown with its own files, to trust by itself. A choice +counts from an agent's next start: a Claude run that started without the folder's files says so +in its record, and goes on without them until the agent starts again. + +The choice is about the repo's files, not yours: a Codex agent starts the MCP servers of your own +Codex config in every folder, trusted or not. To keep them out, turn off **Use my own CLI setup** +(Settings → General → Plans). + +Text that other people write is never taken as yours: a webhook message, or the issue or pull +request a request starts from, reaches the Lead as quoted data, and the plans made from it wait for +**Run plan** in every mode. The plan's card says why it waits. + +### What Codly never does without you - Codly commits and merges by itself only on its own `codly/…` branches: a task's branch, then the plan's integration branch after the task's checks pass. -- Codly's commit of an agent's work leaves out a new folder with more than 2,000 files and a new file - over 25 MB (build output or a dependency folder that the repository does not ignore). The task says - what was left out, its worker is asked once to ignore it, delete it or stage it (`git add`) as work - before the checks run, and the files stay in the worktree. Checkpoints leave the same paths out. - Every commit Codly makes says it in the same way, also the one before a merge, a push or a pull - request of a solo agent's branch. When no worker turn follows (you re-run a task's checks or merge - it anyway), the task goes on without the files, and the Lead tells you when **Lead follow-ups** is on. -- Codly changes your branch only when you press a button: **Merge** (a plan's integration branch, or one - agent's branch, into the branch you have checked out), **Commit** (your own uncommitted changes) and - **Push** (the branch you have checked out, to its remote, through your own SSH agent). +- It changes your branch only when you press a button: **Merge** (a plan's integration branch, or + one agent's branch, into the branch you have checked out), **Commit** (your own uncommitted + changes) and **Push** (the branch you have checked out, to its remote, through your own SSH + agent). - Before a merge writes to your branch, Codly keeps the branch as it was under the ref - `refs/codly/before-merge` in your repository, until the next merge. **Undo merge** takes the last merge - back while nothing was committed or pushed after it. Before you merge, a plan's card says how many - commits the plan is behind your branch. -- **Create pull request** pushes one of Codly's own `codly/…` branches (a plan's, or one agent's), never - a branch of yours and never with force. It asks first and names the remote, the branch and the base. - Your own `gh` opens the pull request with its sign-in: Codly stores no GitHub token. Without `gh` you - can still push the branch and open the compare page in your browser. A Codly branch starts from your - branch: when yours has commits that the remote does not have yet, they go with the push, and the - dialog says how many before you confirm. -- One kind of agent edits your project folder directly: an agent that you hire with **Git isolation** - switched off. The hire screen warns you about it. A command that can lose work in your folder (a - history rewrite, `git reset --hard`, `git clean`, a force push, `rm -rf` outside the build - folders) asks you first in every approval mode, Full access included: from that agent, and from - any agent that points such a command at your folder from its worktree. -- A repo's own agent configuration (Claude Code project settings with hooks or allow rules, project - MCP servers, and the like for the other CLIs) loads only after you trusted the folder. Codly asks - when it opens such a repo and again when those files change. Until then Claude Code starts - without them, and a CLI that Codly cannot start without them (Gemini CLI, OpenCode, Cursor) is not - started in that repo: it takes no task and reviews none. A worktree whose files are not the ones - of your folder (an agent changed them there) is shown with its own files, to trust by itself. - The choice is about the repo's files, not yours: a Codex agent starts the MCP servers of your own - Codex config in every folder, trusted or not. To keep them out, turn off "Use my own CLI setup" in - Settings. -- An agent that wants to run `git push` itself must ask you first, in every approval mode except Full - access, which approves it. That holds with **Sandbox Claude's shell** on too (below). -- By itself, Codly removes a worktree only when it is clean and merged, and deletes a `codly/…` branch - only when its work is merged and its plan has been over for a day. Work that is not committed or not - merged stays until you delete it in **Settings → Storage**, which first names what you would lose. - Raw logs of agent runs are deleted after 30 days; you can change that there too. + `refs/codly/before-merge` in your repository, until the next merge. Before you merge, a plan's + card says how many commits the plan is behind your branch. +- **Create pull request** pushes one of Codly's own `codly/…` branches (a plan's, or one agent's), + never a branch of yours and never with force. It asks first and names the remote, the branch and + the base. Your own `gh` opens the pull request with its sign-in: Codly stores no GitHub token. + Without `gh` you can still push the branch and open the compare page in your browser. A Codly + branch starts from your branch: when yours has commits that the remote does not have yet, they go + with the push, and the dialog says how many before you confirm. +- An agent that wants to run `git push` itself must ask you first, in every approval mode except + Full access, which approves it, and no saved rule covers it. That holds with **Sandbox Claude's + shell** on too. One exception: with **Let Codex agents use the network** on, a Codex agent's push + runs inside its sandbox without a request. +- One kind of agent edits your project folder directly: an agent that you hire with **Git + isolation** switched off. The hire screen warns you about it. A command that can lose work in + your folder asks you first in every approval mode, Full access included: from that agent, and from + any agent that points such a command at your folder from its worktree. Such an agent has no + checkpoints, because Codly never puts files back in your own folder. +- By itself, Codly removes a worktree only when it is clean and merged, and deletes a `codly/…` + branch only when its work is merged and its plan has been over for a day. Work that is not + committed or not merged stays until you delete it in **Settings → General → Storage**, which first + names what you would lose. Raw logs of agent runs are deleted after 30 days. Storage also has the + switch for this cleanup and the number of days for logs. + +### What Codly commits, copies and runs + +- Codly's commit of an agent's work leaves out a new folder with more than 2,000 files and a new + file over 25 MB (build output or a dependency folder that the repository does not ignore). The + task says what was left out, its worker is asked once to ignore it, delete it or stage it + (`git add`) as work before the checks run, and the files stay in the worktree. Checkpoints leave + the same paths out. - A new worktree gets copies of files that git ignores and an agent needs: `node_modules`, `.venv`, - `venv` and the `.env` files at the top of the repo, plus what a `.worktreeinclude` file at the top of - the repo lists (same syntax as `.gitignore`). Codly copies a file only when git ignores it in your - checkout and in the new worktree too, so that it stays out of the commits: commit the `.gitignore` - line first, or the task says that the file was not copied. To copy one file from a folder that git - ignores as a whole, write its path (`secrets/dev.env`), not only its name. Codly remembers what it - copied into each worktree: on a branch that does not ignore a copy, its commit leaves the copy out - and says so. The worker is then asked for the `.gitignore` line only, never to delete or commit the - copy. -- To try work before you merge it, a finished plan and a solo agent's Git tab have **Run…** and **Open - in terminal**. Run… runs a command you type (for example `pnpm dev --port $CODLY_PORT_BASE`) in that - worktree and shows its output. Codly keeps your last command for the repo and never picks one for - you. The command ends when you press Stop, when you merge that work, or when you quit Codly. In a - solo agent's worktree, a file the command writes becomes part of the agent's work unless git - ignores it. + `venv`, `.env`, `.env.local`, `.env.development.local` and `.env.test.local` at the top of the + repo, plus what a `.worktreeinclude` file at the + top of the repo lists (same syntax as `.gitignore`). Codly copies a file only when git ignores it + in your checkout and in the new worktree too, so that it stays out of the commits. Each worktree + gets its own block of ports in `$CODLY_PORT_BASE`. - A repo can have a setup script, `.codly/setup.sh`, that Codly runs once in each new worktree (to - install packages, or to write the worktree's own ports from `$CODLY_PORT_BASE` into a local env - file). It is off until you turn it on in Settings → Safety, which shows you the script. Codly runs - only the text you turned on: if the file changes, it asks you again. It runs a copy of that text - in the worktree's top folder, with the program its first line names (`#!/usr/bin/env bash`) or - `/bin/sh`: use paths from that folder, or `$CODLY_REPO_PATH` for your checkout, not the script's - own place (`$0`). The script is not sandboxed. + install packages, or to write the worktree's ports into a local env file). It is off until you + turn it on in Settings → Safety → Worktrees, which shows you the script. Codly runs only the + text you turned on: if the file changes, it asks you again. Use paths from the worktree's top + folder, or `$CODLY_REPO_PATH` for your checkout. The script is not sandboxed. - You decide what passes. Write the commands that must pass in `.codly/checks`, one on each line - (`pnpm check`, `pnpm test`), and turn them on in Settings → Safety → Required checks, which shows + (`pnpm check`, `pnpm test`), and turn them on in Settings → Safety → Checks, which shows them. Codly then runs them for every task, after the checks the Lead wrote, and again on every finished plan; **Check the work**, in the Git tab of an agent you chat with, runs them on that - agent's work. Codly runs only the text you turned on: if the file changes, tasks wait until you read - it again, and go on by themselves once you turn it on again or off. A plan card also marks a task - whose own checks cannot fail (`true`, `test -f …`). -- Before each turn of an agent, Codly keeps the files of the agent's worktree as a checkpoint (a commit - under a private ref, on no branch). **Restore files to this point**, in the agent's Git tab, puts the - files back and can be undone. It changes files only: the agent still remembers its later turns. An agent - with Git isolation off has no checkpoints, because Codly never puts files back in your own folder. - **Restore this file** puts one file of a checkpoint back and leaves the others. **Last turn**, in the - Git tab and on a task's diff in the Changes room, shows only what the last turn changed. A file or - folder that is too big for a commit is not in a checkpoint either: the Git tab names it, and a restore - that would write over it is refused. - -**What an agent's commands can do** - -- The approval rules read the text of a command. They do not see what a script, a test or a program does - once it runs. So **Autonomous** mode is a list of risky commands, not a sandbox: a command with no risk - in its text runs without asking, with the rights of your account. -- Codex agents always run in Codex's own OS sandbox, which keeps their writes in their worktree. -- Claude Code agents have no OS sandbox, unless you turn on **Sandbox Claude's shell** (Settings → - Safety; off by default). With it on, Claude Code runs the shell commands of workers and 1:1 agents in - its own OS sandbox: - - A sandboxed command can write only in the agent's folder (its worktree), a temporary folder and the - repository's git data. It can still read your other files. - - It can reach only the hosts that your Claude Code settings allow. Codly adds no host and no folder. - When a command wants another host, Codly asks you, in every approval mode except Full access: the - approval card names the host. If you allow it, the host stays allowed for the rest of that agent's - session, for every later command. If you deny it, the command gets a network error. - - Commands still go through the approval rules, as they do with the switch off: what the rules ask - about (a `git push`, an `rm -rf`, a download) still asks you first. The sandbox is a second check - under the rules, not a way around them. So one command can ask twice: once for itself, and once - for a host it wants. - - A command that Claude wants to run outside the sandbox asks you first, in every approval mode except - Full access. The approval card says that it runs outside the sandbox. - - When an agent starts, Codly asks Claude Code whether its sandbox is really on. If it is not (your - system cannot run it, or a setting of your organization changes it), the agent does not start - and Codly tells you why. - - The sandbox covers shell commands only. File edits and tool servers (MCP) are not sandboxed: they go - through approvals as before. Codly's own checks (a task's verify commands, the setup script) are - not sandboxed either. -- Gemini, OpenCode, Cursor and Copilot agents have no OS sandbox. For them, and for Claude Code agents - without the switch, the approval rules are the only check. - -**The network** + agent's work. If the file changes, tasks wait until you read it again. +- The Lead's verify commands go through the same risk rules: one with a risk waits for your OK on + its task. A check runs for at most 10 minutes by default (Settings → Safety → Checks). + +### Your sign-ins and keys + +- Codly spawns the unmodified CLIs you installed and signed in to. It does not proxy them. To see + who is signed in, it runs the CLI's own status command (Claude Code, Codex) or reads the CLI's + settings file (Gemini: the sign-in method and the account email, no token). +- Codly does not read your CLIs' sign-in tokens, with one exception that is off until you turn it + on: **Show Claude usage before an agent runs** (Settings → Team → Accounts). With it on, each time + Codly checks your sign-ins it reads the Claude Code sign-in token (from the Keychain, or from the + sign-in's `.credentials.json` file) and sends it to `api.anthropic.com` to ask for your usage, as + `/usage` does. Codly does not store or log the token. Check Anthropic's terms first: they may not + allow another app to use this token. With it off, a sign-in shows its usage once an agent has run + on it. +- Keys that you give to Codly are stored in the macOS Keychain, not in Codly's settings or + database: your own API keys (Settings → Team → API keys; each one goes to one CLI only), the Groq + key for dictation, webhook secrets, and the keys of the tool servers you switch on for agents. +- Each agent shows a billing badge (subscription, API key or third party). API-key variables that + would silently switch billing are removed from agent environments, unless you turned on your own + API key for that vendor. +- The same goes for the variables that give Claude Code another sign-in than `claude auth login`: + `CLAUDE_CODE_USE_BEDROCK`, `CLAUDE_CODE_USE_VERTEX` and `CLAUDE_CODE_OAUTH_TOKEN` (a token from + `claude setup-token`). Codly removes them from agent environments unless you turn on **Use my + shell's Claude sign-in** (Settings → Safety → Trust). With it on, Claude agents keep them + from your login shell, as Claude Code does in your terminal, and that account pays. Codly does not + store the token. Check Anthropic's terms before you use a subscription token this way. Every + other `CLAUDE_CODE_*` variable is always removed, so that an agent never takes itself for a part + of the Claude Code session that started Codly. (Codly sets one of its own for Claude agents: + `CLAUDE_CODE_DISABLE_AUTO_MEMORY=1`.) + +### The network - There are no Codly servers: no account, nothing to sync. Your CLIs talk to their own providers as before. -- Codly itself goes online only to install a CLI or a skill when you click, to fetch the tool servers - that agents start with (through `npx` or `uvx`), to push when you press Push or Create pull request - (your `gh` then opens the pull request, and reads its state and checks when you press Refresh), to read - an issue or a pull request with your `gh` when you start a request from one (**From issue…**, **From - pull request…**: the Lead gets its text as quoted data, nothing is written to GitHub, and because other - people write that text, the plans of that request wait for Run plan in every mode until one of them is - done; the plan's card says why), and for two - features that - are off until you turn them on: dictation (audio goes to Groq with your key) and Show Claude usage. - The voice relay in `voice/` talks to OpenAI, and only if you run it. -- Inbound webhooks listen on this Mac only (loopback) and are created switched off. A webhook message - shows under its endpoint's name, not as yours, and a plan made from it waits for Run plan unless you - let that endpoint run plans without asking; the plan's card says why it waits. Until your next - message, the Lead is also stopped before it messages a team member or reassigns a task. An agent you - pick to answer webhook messages asks as its approval mode says, whatever trust you gave it, from the - turn that reads such a message until a turn that your own message to it starts. `codly serve` also - listens on this Mac only, unless you pass `--host`. +- Codly itself goes online only to install a CLI or a skill when you click, to fetch the tool + servers that agents start with (through `npx` or `uvx`), to push when you press Push or Create + pull request, to use your `gh` for a pull request (it reads the pull request's state and checks + only when you press Refresh) or to read an issue or a pull request you start a request from, and + for two features that are off until you turn them on: dictation (audio goes to Groq with your + key) and Show Claude usage. The voice relay in `voice/` talks to OpenAI, and only if you run it. +- Inbound webhooks (Settings → Automation) listen on this Mac only (loopback) and are created + switched off. A webhook message shows under its endpoint's name, not as yours, and a plan made + from it waits for Run plan unless you let that endpoint run plans without asking. Until your next + message, the Lead is also stopped before it messages a team member or reassigns a task. An agent + you pick to answer webhook messages asks as its approval mode says, whatever trust you gave it, + from the turn that reads such a message until a turn that your own message to it starts. +- `codly serve` also listens on this Mac only; another `--host` needs `--allow-remote` (below). Provider terms change. Check them before heavy parallel use. +## The CLIs + +| CLI | How Codly runs it | What was checked | +| --- | --- | --- | +| Claude Code | `claude` in stream-JSON mode, with the stdin control protocol for approvals, interrupts, mode and model changes | The adapter's tests replay real recordings of Claude Code 2.1.311 (`docs/research/fixtures/claude-2.1.311/`, described in `docs/research/cli-claude-stream-json-2.1.311*.md`). | +| Codex | One `codex app-server` per sign-in (JSON-RPC over stdio), one thread per agent | Recorded live with Codex 0.161 before this release's work. The newer parts (subagents, Compact now, usage read, thread names) are built from the protocol types that codex-cli 0.166.0 generates and were never run live. | +| Gemini CLI | ACP (`gemini --acp --skip-trust`) | Recorded transcripts only; never run live during this release's work. | +| OpenCode | ACP (`opencode acp`) | Recorded transcripts only; never run live during this release's work. | +| Cursor, Copilot | ACP (`cursor-agent acp`, `copilot --acp`) | Never run: not installed on the test machine. | + +What works with each: + +- Every CLI: plans, tasks, worktrees, the gate, approvals through Codly's broker, Codly's MCP + tools, merge and pull request. +- Claude Code only: the opt-in OS sandbox, **Open in my terminal**, the mode switch, the MCP + server list with Reconnect and Turn off / Turn on, Stop for a background command or a helper, and + saved rules for MCP tools. A message sent mid-turn reaches the agent during the turn. +- Codex: its own OS sandbox, Compact now, usage windows read with its own sign-in, subagents shown + as rows. A message sent mid-turn reaches it in the turn too. +- Gemini CLI, OpenCode, Cursor and Copilot: no OS sandbox and no take-over to your terminal. + Gemini CLI, OpenCode and Cursor are not started in a folder whose own CLI files you did not + trust. + +Several sign-ins per CLI are supported (Settings → Team → Accounts); work is spread by quota left +or taken in order. + +## Settings + +Settings has five tabs: General, Team, Safety, Automation and Developer. The switches whose default +matters most: + +| Setting | Where | Default | +| --- | --- | --- | +| Approval mode | Safety → Approvals | Balanced | +| Run plans without asking | General → Plans | Off | +| Lead follow-ups | General → Plans | On | +| Use my own CLI setup | General → Plans | On | +| Keep the Mac awake while agents work | General → Long runs | On | +| Ask before quitting while agents work | General → Long runs | On | +| Resume work when Codly opens | General → Long runs | Ask | +| Office rules affect work | General → Office | Off: the office game never delays, refuses or changes work | +| Keep the office moving behind the chat | General → Office | Off | +| Notifications | General → Notifications | Every kind on, only while Codly is not in front | +| Agents at once | Team | 3 | +| Workers per account | Team → Accounts | 2 | +| Show Claude usage before an agent runs | Team → Accounts | Off | +| Sandbox Claude's shell | Safety → Sandbox | Off | +| Use my shell's Claude sign-in | Safety → Trust | Off | +| Let Codex agents use the network | Safety → Sandbox | Off | +| Cross-vendor review before merge | Safety → Checks | Off | +| Time limit for checks | Safety → Checks | 10 minutes | +| Circuit breaker | Safety → Limits | On; token and cost budgets off | +| Silent agents | Safety → Limits | Flag after 10 min (60 with a silent tool call open), idle after 2 min | +| Webhooks | Automation | Each new endpoint off | + +## Keyboard shortcuts + +Press `?` in the app for the full sheet. The main ones: + +| Keys | Action | +| --- | --- | +| ⌘K | Search and commands; it also finds what was said in this repo's conversations | +| ⌘N, ⌘[ / ⌘] | New request; previous / next request | +| ⇧⌘N | New task | +| ⌘F | Find in the conversation | +| ⌘↵ | Approve once, send a question's answer, or run the plan | +| 1 … 9 | Pick an option of the question that waits | +| ⌥⌘↵ | Allow for this session | +| ⌘⌫, ⇧⌘⌫ | Deny; deny with a note | +| Esc | Close, deselect; Esc Esc stops the running turn, or, in a 1:1 with an agent that rests, opens **Undo a turn** | +| ↑ | Bring back what you sent (on an empty line) | +| @, # | Talk to one agent or mention a file; mention a task | +| ⇧⇥ | Next request mode: Ask, Plan, Auto, Direct; in a 1:1 with Claude, its next mode | +| ⌘1, ⌘2, ⌘3 | Full office, full work, the neighbourhood map | +| ⌘. | Focus: dim the office | +| G then H, P, C, K, T, S | Home, Plan, Changes, Knowledge, Terminal, Settings | +| ⌘O, ⌘, | Open repository; Settings | + +## Codly in a browser (`codly serve`) + +To use Codly from a browser instead of its window: + +```bash +/Applications/Codly.app/Contents/MacOS/codly serve # prints a link with a token; --port N +``` + +It listens on 127.0.0.1, port 4280 by default, and runs without a window or Dock icon until Ctrl+C. +Run while the app is already open, the open app serves too and opens the link in your browser. + +The page can open terminals and control your agents, and the traffic is plain HTTP. To reach it +from another machine, use an SSH tunnel: `ssh -L 4280:127.0.0.1:4280 `, then open the +link on that machine. `--host
` with an address other machines can reach is refused +unless you add `--allow-remote`; the link then works for anyone on your network until Codly stops. +Quit the app first: an app that is already open does not serve to the network. `codly --help` +lists every command and `codly --version` prints the version. + +When `codly serve` stops or restarts, the page keeps what it shows, and a bar at the top says +"Codly is not reachable. Trying again…" with the time of the last try. The page tries again after +1, 2, 5 and 10 seconds, then every 10 seconds until Codly is back; **Try now** tries at once. Once +it is back, the page catches up on what happened meanwhile. With `--allow-remote` each start +prints a new link: the page then says it is signed out, and you open the new link. Notifications +show on the Mac that runs Codly, not in the browser. + +## Troubleshooting + +Settings → General → Troubleshooting collects what a bug report needs: the Codly version, your +system, your agent CLIs and the last log lines. Tokens, keys, email addresses and paths under your +home folder are taken out. Repository and agent names can remain: read it, then paste it in the +issue. The same button is on the "Codly couldn't start" screen. + +The log file is `~/Library/Application Support/dev.codly.desktop/logs/codly.log` (at most 5 MB; +the file before it is `codly.1.log`). An internal error (a panic) writes its place and backtrace +there. To log more, start Codly with `CODLY_LOG=debug`: the file then also takes Codly's own +debug lines (those of the libraries it uses go to the terminal only). + +## Limits and known gaps + +- macOS only. The Linux CI builds and tests the code, but macOS-only code is compiled only by the + macOS CI job, and the packaged app has not been driven end to end by a test. +- Live CLI runs: Gemini CLI, OpenCode, Cursor and Copilot were not run during the latest work; Codex + features newer than version 0.161 come from its generated protocol types. See [The CLIs](#the-clis). +- Agents are children of the app. They stop when it quits or the Mac sleeps; a command an agent + left running with `&` keeps running after its agent stops. +- The approval rules read command text, not what a program does. Only Codex, and Claude Code with + its switch on, have an OS sandbox. +- **Open in my terminal** works for Claude Code agents only, between turns, and never for the Lead. +- Slack as an inbound source is not connected yet: its settings show "Not available yet". +- `voice/` is experimental. Its start script needs the author's own OpenAI workload identity, so + nobody else can run it as it is; without it a voice call fails with "the voice relay is not + running". +- The browser demo has no git, `gh` or shell behind it: diffs, commits and command output there are + made up. + +## Develop + +```bash +pnpm dev # the UI alone in a browser, on a scripted demo session +pnpm test # frontend tests (Vitest) +pnpm check # svelte-check and TypeScript +cargo test --workspace # core tests; adapters replay recorded CLI transcripts +pnpm tauri build # build the macOS app and .dmg +``` + +Before you push, run the checks that CI runs: + +```bash +scripts/verify.sh # pnpm check, pnpm test, pnpm build, cargo test --workspace +``` + +It also fails when the tests rewrite `src/lib/gen`: those TypeScript types are generated from the +Rust types by `cargo test`, so commit them with the change that needs them. + +CI (`.github/workflows/ci.yml`) runs the same script on Linux for every pull request and every +push to `main`, and compiles the workspace on macOS. To run it on Linux yourself, install the +system packages the workflow lists. + +### Project layout + +- `crates/codly-core/`: the engine, with no Tauri dependency. Orchestrator (Lead, team, planner, + scheduler, gate and merge queue, approval broker, triggers), agent adapters, SQLite store, git, + code index, memory, inbound sources and the MCP server. +- `src-tauri/`: the macOS shell (Tauri 2) that hosts the engine, and `codly serve`. +- `src/`: the Svelte 5 UI: the Workspace, the World (`src/office/`, three.js), the neighbourhood + map (`src/world/`), Settings (`src/overlays/`) and onboarding. +- `public/`: the office's furniture models and sounds. These are third-party assets (CC0 and CC + BY); each folder has its licence or credits file. +- `site/`: the landing page and the live demo build. +- `scripts/`: `install-app.sh` builds Codly.app and installs it in /Applications; + `kaykit-clips.py` converts animation clips for the World; `verify.sh` runs every check. +- `voice/`: the experimental voice relay (see above). +- `research-skills/`: optional skills for research work. They are not part of the app; you install + them by hand with `research-skills/install.sh`. +- `docs/`: architecture, design notes and the research behind them. + +The full code map is in [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md), section 8. + ## Docs - [Architecture](docs/ARCHITECTURE.md): decisions, processes, event model, orchestration and memory. - [Release](docs/RELEASE.md): how a release is built, signed and published, and where the version is set. - [Browser demo](docs/DEMO.md): the scripted demo behind `pnpm dev`, and the URL parameters that open each screen. -- [Research](docs/research/): the reports behind each decision, and the consolidated - [critique](docs/research/CRITIQUE.md). - -## Status - -Early: this is the v0.1 vertical slice. Expect rough edges. +- [Research](docs/research/): the reports behind each decision, the Claude Code recordings, and the + consolidated [critique](docs/research/CRITIQUE.md). diff --git a/crates/codly-core/examples/adapter_smoke.rs b/crates/codly-core/examples/adapter_smoke.rs index fd37265a..3a99b4ad 100644 --- a/crates/codly-core/examples/adapter_smoke.rs +++ b/crates/codly-core/examples/adapter_smoke.rs @@ -211,6 +211,7 @@ async fn main() { raw_log: raw_log.clone(), byok_command: None, sandbox_shell: false, + max_budget_usd: None, }; println!("spawning {} ({:?}, model {:?}) in {}", spec.bin.display(), spec.role, spec.model, repo.display()); diff --git a/crates/codly-core/src/adapters/acp.rs b/crates/codly-core/src/adapters/acp.rs index 2b250139..184484a4 100644 --- a/crates/codly-core/src/adapters/acp.rs +++ b/crates/codly-core/src/adapters/acp.rs @@ -1299,7 +1299,7 @@ mod tests { /// Feed the agent→client side of an ACP probe capture through the normalizer, answering /// permissions with allow-once like the probe did. Returns events and the answers. fn replay(provider: Provider, name: &str) -> (Vec, Vec) { - let mut norm = AcpNormalizer::new(provider, "a1", "r1", PathBuf::from("/private/tmp/claude-501/-Users-julien-Documents-Repos-Codly/ae7e9f7f-d897-4679-8080-c22a339ba5b7/scratchpad/fixture-repo2")); + let mut norm = AcpNormalizer::new(provider, "a1", "r1", PathBuf::from("/tmp/scratch/fixture-repo2")); let mut events = norm.turn_started("prompt"); let mut answers = Vec::new(); let mut prompt_id = None; @@ -1571,6 +1571,7 @@ mod tests { raw_log: PathBuf::from("/tmp/r/raw.ndjson"), byok_command: None, sandbox_shell: false, + max_budget_usd: None, }; let (a, env) = launch(&spec, Some(Path::new("/tmp/r/gemini-policy.toml"))); assert_eq!(a, ["--acp", "--skip-trust", "-m", "gemini-2.5-flash", "--policy", "/tmp/r/gemini-policy.toml"]); @@ -1632,6 +1633,7 @@ mod tests { raw_log: dir.join("raw.ndjson"), byok_command: None, sandbox_shell: false, + max_budget_usd: None, }; let (events, events_rx) = mpsc::unbounded_channel(); let actor = Actor { diff --git a/crates/codly-core/src/adapters/claude.rs b/crates/codly-core/src/adapters/claude.rs index d9f2369b..e2090734 100644 --- a/crates/codly-core/src/adapters/claude.rs +++ b/crates/codly-core/src/adapters/claude.rs @@ -103,6 +103,11 @@ pub const DEFAULT_MODEL: &str = "default"; /// (`SessionRequest::Settings`). pub const EFFORT_LEVELS: &[&str] = &["low", "medium", "high", "xhigh", "max"]; +/// The adapter's own answer to a `stop_task` for an id that names nothing running beside the +/// agent (a task that left the list, or a helper that ended, a moment before): nothing is sent +/// to the CLI. Whoever asked shows it as it is: it is not Claude Code's answer. +pub const NOT_RUNNING: &str = "that work is not running any more"; + /// The model an `assistant` line names when the CLI wrote its text itself (the output of a /// local command such as `/compact`): no model ran. const SYNTHETIC_MODEL: &str = ""; @@ -119,6 +124,17 @@ const INTERRUPT_TIMEOUT: Duration = Duration::from_secs(8); /// which it ends them itself. Short, so that both fit in the time the app waits at exit. const STOP_TASKS_TIMEOUT: Duration = Duration::from_secs(2); +/// How long the interrupt that starts the stop of an agent has to end the running turn (its +/// `result`). Recorded: 0.02 to 0.09 s (part 4 §1 and §2). +const STOP_INTERRUPT_TIMEOUT: Duration = Duration::from_secs(5); + +/// How long the interrupt that starts the stop of an agent with NO turn running has to end its +/// background helpers (the list without them). Recorded: 0.02 to 0.09 s (part 4 §2), at once +/// beside a background command (part 5 §5, `r7-shutdown-helper-and-command-*`, n=2). Short, so +/// that it and the stop of the commands after it (`STOP_TASKS_TIMEOUT`) end before the app +/// gives up on the process at exit (`RUNS_GRACE`, 4 s, workspace.rs). +const STOP_HELPERS_TIMEOUT: Duration = Duration::from_secs(1); + pub fn tools_for(spec: &SpawnSpec) -> Vec<&'static str> { let mut t = if spec.read_only { READ_ONLY_TOOLS } else { WORKER_TOOLS }.to_vec(); if spec.use_user_setup { @@ -235,6 +251,12 @@ impl std::error::Error for SandboxNotOn {} impl SandboxNotOn { /// The way out that ends every text: the switch that asked for the sandbox. const SWITCH: &'static str = "turn off \"Sandbox Claude's shell\" in Settings → Safety"; + /// The words every text has: `retry::needs_you` knows by them a start that only you can + /// fix (no wait turns a sandbox on). + pub(crate) const NOT_STARTED: &'static str = "did not start this agent"; + /// The words of the one text that a later start can get past (`no_answer`): the CLI was + /// slow, not the sandbox off. `retry::needs_you` lets the task try again by itself. + pub(crate) const NO_ANSWER: &'static str = "did not answer Codly's check of its sandbox"; /// Claude Code did not turn its sandbox on and gave no reason: the CLI said so /// (`sandbox_refusal`), or it ended at its start because of it (`startup::explain`). @@ -246,7 +268,7 @@ impl SandboxNotOn { /// (`get_sandbox_dialog`) before the time for a start was over. fn no_answer() -> Self { let waited = INIT_TIMEOUT.as_secs(); - Self(format!("Claude Code did not answer Codly's check of its sandbox within {waited} s, so Codly did not start this agent. Try again, or {}", Self::SWITCH)) + Self(format!("Claude Code {} within {waited} s, so Codly did not start this agent. Try again, or {}", Self::NO_ANSWER, Self::SWITCH)) } } @@ -340,7 +362,13 @@ pub fn build_args(spec: &SpawnSpec, session_id: &str, mcp_config_path: Option<&P } a.extend(["--tools".into(), tools_for(spec).join(",")]); // Strict = only Codly's server and the Connections; the user's own setup adds their MCP - // servers, plugins and project settings, as in their own Claude Code. + // servers, plugins and project settings, as in their own Claude Code. A folder you have + // not trusted always gets strict (`orchestrator/trust.rs`), also when "Use my Claude setup" + // is on. Dropping it there stays on hold (part 6 §1): the folder's own `.mcp.json` server + // started in none of 40 recordings, but under `--setting-sources user,local` the folder's + // `.claude/settings.local.json` switched on a plugin the user had turned off, and that + // plugin's MCP server started (4 of 4); a plugin the user never installed, named by a file + // of the folder, is not recorded. if !spec.use_user_setup { a.push("--strict-mcp-config".into()); } @@ -364,12 +392,37 @@ pub fn build_args(spec: &SpawnSpec, session_id: &str, mcp_config_path: Option<&P if let Some(settings) = settings_json(spec) { a.extend(["--settings".into(), settings.to_string()]); } + if let Some(usd) = spec.max_budget_usd { + a.extend(["--max-budget-usd".into(), usd.to_string()]); + } let role = format!("{:?}", spec.role).to_lowercase(); let short: String = spec.agent_id.chars().rev().take(8).collect::>().into_iter().rev().collect(); a.extend(["-n".into(), format!("codly:{role}-{short}")]); a } +/// Why a turn failed that reached the limit its run started with (`SpawnSpec::max_budget_usd`): +/// the adapter's own words, which ask you to send your message again. Codly knows such a turn +/// by these words (`is_run_limit_reached`) and may say what comes next in their place +/// (`run_limit_reached_then`). +pub fn run_limit_reached(agent: &str, limit_usd: f64) -> String { + run_limit_reached_then(agent, limit_usd, "Send your message again: the next run starts with what is left now.") +} + +/// The same words with `next`, what comes next for that run. They end by saying that the run +/// can cost a little more than its limit: Claude Code finishes the model requests that were on +/// their way when the limit passed (part 6 §6: the totals ended 19% and 45% above it, n=2). +pub fn run_limit_reached_then(agent: &str, limit_usd: f64, next: &str) -> String { + format!( + "This run of {agent} reached the limit it started with ({limit_usd:.2} USD of your budget were left then). {next} It can end a little above the limit: a request that was on its way is finished." + ) +} + +/// Does `said` (a failed turn's reason) say that the run of `agent` reached its limit? +pub fn is_run_limit_reached(said: &str, agent: &str, limit_usd: f64) -> bool { + said == run_limit_reached(agent, limit_usd) +} + pub async fn spawn(spec: SpawnSpec, events: mpsc::UnboundedSender) -> anyhow::Result { let session_id = match &spec.session { SessionMode::New { session_id: Some(id) } => id.clone(), @@ -511,6 +564,9 @@ enum Stage { Running, /// Shutdown asked while a turn ran: interrupt sent, waiting for its `result`. Interrupting, + /// Shutdown asked while no turn ran and the CLI's last list named a helper: interrupt + /// sent, waiting for the list without helpers. + StoppingHelpers, /// Shutdown, the turn is over: `stop_task` sent for each background command, waiting for /// the CLI to say that none is left. StoppingTasks, @@ -685,6 +741,12 @@ impl Actor { if resp["request_id"].as_str() == Some(init_id) { let Some(r) = ready.take() else { return }; if resp["subtype"] == "success" { + // A second answer with the id of `initialize` (in no recording) while the + // sandbox check waits for its own answer: that one still decides the start. + if matches!(self.sandbox_check, Some(SandboxCheck::Asked { .. })) { + *ready = Some(r); + return; + } let started = self.norm.on_initialize(&resp["response"]); if let Some(SandboxCheck::Due { asked }) = self.sandbox_check.take() { // The run asked for the shell sandbox: it has not started before the @@ -709,7 +771,8 @@ impl Actor { self.on_sandbox_status(started, resp, ready).await; } else if let Some((request, reply)) = resp["request_id"].as_str().and_then(|id| self.session_replies.remove(id)) { self.session_answered(request, reply, resp); - // (what the answer makes Codly ask next: the MCP servers' state after a reconnect) + // (what the answer makes Codly ask next: the MCP servers' state after a + // reconnect or a switch) for line in std::mem::take(&mut self.norm.outbox) { self.write(&line).await; } @@ -727,10 +790,21 @@ impl Actor { // The agent is being stopped and its turn is over. What the CLI does from here (a turn // for a prompt it still held, a turn of its own) is not shown as this agent's work. // Its list of background tasks is still followed: the stop waits for it (`wind_down`). + // While the stop waits for its helpers to end, their task lines and the list are still + // shown: the helper rows end as the CLI says. if self.stage != Stage::Running && !self.turn_active { - if listed { + let helpers_end = self.stage == Stage::StoppingHelpers + && v["type"] == "system" + && matches!(v["subtype"].as_str(), Some("task_updated" | "task_notification" | "background_tasks_changed")); + if helpers_end { + for e in self.norm.on_message(&v) { + self.emit(e); + } + } else if listed { self.norm.on_background_tasks(&v["tasks"], &mut Vec::new()); - self.on_background_tasks(); + } + if listed { + self.on_background_tasks().await; } return; } @@ -744,8 +818,10 @@ impl Actor { self.cancels_queued = can("interrupt_cancel_queued_v1"); } // No prompt of Codly's opened this turn: the CLI started it by itself (a background task - // that ended woke it). `system/init` opens every turn, and a `result` ends one: it never - // comes for a turn that is not open. + // that ended woke it; a helper stopped during the last model request of a turn wakes it + // after that turn's `result`, a stopped command does not: part 6 §5, n=2 and n=5). + // `system/init` opens every turn, and a `result` ends one: it never comes for a turn + // that is not open. if !self.turn_active && (init || v["type"] == "result") { self.open_turn(None); } @@ -758,7 +834,7 @@ impl Actor { self.write(&reply).await; } if listed { - self.on_background_tasks(); + self.on_background_tasks().await; } if turn_done { self.turn_active = false; @@ -840,10 +916,12 @@ impl Actor { /// The CLI said its list of background tasks again (`system/background_tasks_changed`, /// part 2 §6; the normalizer holds the list). A stop of the agent that waits for its - /// commands to end goes on when none is left. - fn on_background_tasks(&mut self) { - if self.stage == Stage::StoppingTasks && self.norm.commands_in_background().is_empty() { - self.close_stdin(); + /// helpers or its commands to end goes on when none is left. + async fn on_background_tasks(&mut self) { + match self.stage { + Stage::StoppingHelpers if !self.norm.helpers_in_background() => self.wind_down().await, + Stage::StoppingTasks if self.norm.commands_in_background().is_empty() => self.close_stdin(), + _ => {} } } @@ -961,13 +1039,21 @@ impl Actor { SessionRequest::Model(model) => ("set_model", json!({ "model": model })), SessionRequest::ContextUsage => ("get_context_usage", json!({})), SessionRequest::McpReconnect(server) => ("mcp_reconnect", json!({ "serverName": server })), - SessionRequest::StopTask(task) => ("stop_task", json!({ "task_id": task })), + SessionRequest::McpEnabled(server, on) => ("mcp_toggle", json!({ "serverName": server, "enabled": on })), + SessionRequest::StopTask(id) => match self.norm.task_to_stop(id) { + Some(task) => ("stop_task", json!({ "task_id": task })), + None => { + let _ = reply.send(Err(NOT_RUNNING.to_string())); + return; + } + }, SessionRequest::Effort(level) => { // The CLI would answer "success" and drop a word it does not know (recorded). - if !EFFORT_LEVELS.contains(&level.as_str()) { + if let Some(level) = level.as_deref().filter(|l| !EFFORT_LEVELS.contains(l)) { let _ = reply.send(Err(format!("Claude Code has no effort level \"{level}\""))); return; } + // (None: `effortLevel: null` takes the level away; the CLI's default follows) ("apply_flag_settings", json!({ "settings": { "effortLevel": level } })) } SessionRequest::Settings => ("get_settings", json!({})), @@ -988,12 +1074,12 @@ impl Actor { /// The CLI answered a session request: the answer goes to whoever asked (an error too: it /// is theirs to show, not a line of the timeline). fn session_answered(&mut self, request: SessionRequest, reply: SessionReply, resp: &Value) { - let answer = if resp["subtype"] == "success" { + let mut answer = if resp["subtype"] == "success" { Ok(resp["response"].clone()) } else { Err(resp["error"].as_str().map_or_else(|| resp["error"].to_string(), str::to_owned)) }; - match (&request, &answer) { + match (&request, &mut answer) { // A refused switch leaves the CLI in the mode it had, which this request overwrote // here: its next status line says which one it is. (SessionRequest::PermissionMode(_), Err(_)) => self.norm.permission_mode = None, @@ -1001,9 +1087,18 @@ impl Actor { self.norm.model = Some(model.clone()).filter(|m| m != DEFAULT_MODEL); self.norm.model_switched(); } - // Connected or not, the server's state may be another now: the CLI is asked, and - // the answer is reported like the one at the start of the run. - (SessionRequest::McpReconnect(_), _) => self.norm.ask_mcp_status(), + // Connected or not, switched or not, the server's state may be another now. The + // answer does not say it (recorded, `r5-mcp-reconnect-toggle`: a success has no + // body), so the CLI is asked, and its answer is reported like the one at the + // start of the run. + (SessionRequest::McpReconnect(_) | SessionRequest::McpEnabled(..), _) => self.norm.ask_mcp_status(), + // A helper stopped by the id of its call: whoever asked gets its description with + // the CLI's (empty) answer, for the record of the stop. + (SessionRequest::StopTask(id), Ok(said)) => { + if let (Some(helper), Some(said)) = (self.norm.helpers.get(id.as_str()), said.as_object_mut()) { + said.insert("helper".into(), json!(helper.description)); + } + } _ => {} } // Nobody waits any more (the asker gave up): the request still took effect. @@ -1034,17 +1129,35 @@ impl Actor { } } - /// Shutdown ladder: interrupt (≤ 5 s for the result) → stop the background commands (≤ 2 s) - /// → close stdin (≤ 3 s) → SIGTERM → SIGKILL. With a prompt that still waits in the CLI, or - /// a background command it did not report as stopped, the CLI would not exit when stdin - /// closes: there SIGTERM comes at once. + /// Shutdown ladder: interrupt (≤ 5 s for the result, or with no turn running ≤ 1 s for the + /// end of the background helpers) → stop the background commands (≤ 2 s) → close stdin (≤ 3 s) + /// → SIGTERM → SIGKILL. With a prompt that still waits in the CLI, or a background command + /// it did not report as stopped, the CLI would not exit when stdin closes: there SIGTERM + /// comes at once. + /// + /// The interrupt ends every helper, background ones too, with or without a turn running, + /// and starts no turn (part 4 §1 and §2: `r6-shutdown-helper-sequence-*` with a turn, + /// `-idle-interrupt-*` without, n=2 each; with a turn the helpers are gone before its + /// `result`). So with no turn running it is sent only when the CLI's last list names a + /// helper. A helper never gets `stop_task` here: after it the CLI starts a turn by itself, + /// which runs to its end also when stdin is closed at once (`-idle-close-now-*`, n=2). async fn begin_shutdown(&mut self) { if self.stage != Stage::Running { return; } self.queue.clear(); if !self.turn_active { - return self.wind_down().await; + // (A prompt that still waits in the CLI ends the process at once: `wind_down`.) + if !self.norm.helpers_in_background() || !self.waiting.is_empty() { + return self.wind_down().await; + } + self.control("interrupt", json!({})).await; + if self.stdin.is_none() { + return self.wind_down().await; // (it did not reach the CLI: no list will come) + } + self.stage = Stage::StoppingHelpers; + self.deadline = Some(tokio::time::Instant::now() + STOP_HELPERS_TIMEOUT); + return; } self.norm.interrupt_requested = true; // `cancel_queued`: the CLI drops the prompts that wait in it, and its `cancelled` line @@ -1053,15 +1166,25 @@ impl Actor { let request = if self.cancels_queued && !self.waiting.is_empty() { json!({ "cancel_queued": true }) } else { json!({}) }; self.control("interrupt", request).await; self.stage = Stage::Interrupting; - self.deadline = Some(tokio::time::Instant::now() + Duration::from_secs(5)); - } - - /// The stopped agent's turn is over, or none ran: end the background commands the CLI - /// still tracks, then close stdin. With one of them open the CLI does not exit when stdin - /// closes: it waits for the command and then runs a turn (recorded: 43 s, part 2 §7). - /// `stop_task` ends a running command at once and starts no turn (part 2 §6). The commands - /// are the ones of the CLI's last list; what `stop_task` does to a background subagent is - /// not recorded, so that one is left to the later steps of the stop. + self.deadline = Some(tokio::time::Instant::now() + STOP_INTERRUPT_TIMEOUT); + } + + /// The stopped agent's turn is over, or none ran, and its helpers are ended + /// (`begin_shutdown`): end the background commands the CLI still tracks, then close stdin. + /// With one of them open the CLI does not exit when stdin closes: it waits for the command + /// and then runs a turn (recorded: 43 s, part 2 §7). An interrupt does not end such a + /// command (part 3 §4); `stop_task` ends it at once and starts no turn (part 2 §6). The + /// steps are recorded as one run (part 3 §4, `r5-stop-sequence`, n=1): the interrupt, + /// `stop_task` right after the stopped turn's `result`, stdin closed once the list is + /// empty, and the exit a second later with nothing left running. The commands are the ones + /// of the CLI's last list. With a helper AND a command in the background and no turn + /// running (part 5 §5, `r7-shutdown-helper-and-command-*`, n=2): the interrupt ends the + /// helper and leaves the command listed, `stop_task` ends the command, and the process + /// exits 0.70 s after stdin is closed, with nothing left in its process group. With a turn, + /// a helper and a command at once (part 6 §11, `r8-shutdown-all-*`, n=2): the interrupt + /// ends the helper and the turn and leaves the command listed, `stop_task` after the turn's + /// `result` ends the command, and the process exits 0.73 s after stdin is closed, with + /// nothing left in its group. async fn wind_down(&mut self) { self.drop_unsent(); let commands = self.norm.commands_in_background(); @@ -1117,6 +1240,9 @@ impl Actor { self.drop_unsent(); self.close_stdin(); } + // A helper is still listed: the commands are stopped as in any stop, and the steps + // after them end what is left (at SIGTERM the CLI ends what it tracks). + Stage::StoppingHelpers => self.wind_down().await, // A command is still open as far as the CLI says. With stdin closed the CLI would // wait for it; at SIGTERM it ends it. Stage::StoppingTasks => { @@ -1168,6 +1294,8 @@ struct Helper { /// The CLI's id of it as a task, once its `task_started` line said it: the id that the /// list of background tasks names. task_id: Option, + /// Why it failed, once a `task_updated` line said it (`patch.error`). + error: Option, done: bool, } @@ -1335,7 +1463,7 @@ pub struct ClaudeNormalizer { helpers: HashMap, /// The `mcp_status` requests with no answer yet, oldest first: for each, the user's MCP /// servers that `system/init` gave as failed when it was written, until its answer says - /// why (none for a request after a reconnect or at the end of a turn). The CLI answers + /// why (none for a request after a reconnect, a switch or the end of a turn). The CLI answers /// its control requests in the order it reads them (as in every recording), so the next /// answer is the one to the oldest request. mcp_asked: VecDeque>, @@ -1371,6 +1499,11 @@ pub struct ClaudeNormalizer { /// Lines the actor must write: answers to the CLI's requests (e.g. errors for unsupported /// ones) and the normalizer's own `mcp_status` request. pub outbox: Vec, + /// What a turn that reached the run's own spending limit says (`SpawnSpec::max_budget_usd`). + run_limit: Option, + /// What the earlier runs on a resumed session cost (`SpawnSpec::session_cost_usd`): the + /// session's totals of a `result` include it (`on_result`). + cost_before: f64, } impl ClaudeNormalizer { @@ -1413,6 +1546,8 @@ impl ClaudeNormalizer { last_context: None, interrupt_requested: false, outbox: Vec::new(), + run_limit: spec.max_budget_usd.map(|usd| run_limit_reached(&spec.agent_name, usd)), + cost_before: spec.session_cost_usd, } } @@ -1453,8 +1588,15 @@ impl ClaudeNormalizer { /// `errors` without its diagnostic lines). fn failure_reason(&self, v: &Value, retried: Option) -> Option { // The spending limit of the process (`--max-budget-usd`, 2.1.311 §6): every later - // turn of this run ends the same way, at once. + // turn of this run ends the same way, at once. Codly gave it what was left of your + // budget, and ends the run on this turn (`breaker_run.rs`, `run_limit_turn_end`): the + // process can do no more work, and a command of this turn can still be running there, + // in no list, until the process ends (part 5 §10, `r7-budget-during-call-*`, n=2: a + // Bash call cut off with no result ran on until stdin was closed). if v["subtype"] == "error_max_budget_usd" { + if let Some(reached) = &self.run_limit { + return Some(reached.clone()); + } let said = cli_errors(v); let detail = if said.is_empty() { String::new() } else { format!(": {said}") }; return Some(format!("Claude Code reached its spending limit, so it does no more work in this run{detail}")); @@ -1551,8 +1693,15 @@ impl ClaudeNormalizer { "rate_limit_event" => self.on_rate_limit(v, &mut out), "control_request" => self.on_control_request(v, &mut out), "control_cancel_request" => self.on_cancel(v, &mut out), - // A heartbeat every 30 s while a Bash call runs, with the call's id in - // `parent_tool_use_id` and no output (part 2 §8): a life sign for the watchdog. + // A heartbeat every 30 s while a tool call runs, with the call's id in + // `parent_tool_use_id` and no output: a life sign for the watchdog. Recorded for a + // Bash call (part 2 §8), a tool of an MCP server and the `Agent` call that waits for + // a subagent (part 3 §3, `r5-tool-progress-mcp` and `-subagent`, n=1 each), and a + // slow tool of an HTTP MCP server, whatever its server sends meanwhile (part 6 §10, + // `r8-http-slow-*`, n=2 per kind: its progress notifications add no line). A Bash + // call inside a subagent has none of its own: the `Agent` call's stands for it. + // WebFetch and WebSearch are not recorded (`watchdog::has_heartbeat`). Every + // recorded line names its call; one that names none says nothing. "tool_progress" => { if let Some(call_id) = v["parent_tool_use_id"].as_str() { out.push(EventKind::ToolProgress { call_id: call_id.into() }); @@ -1620,11 +1769,11 @@ impl ClaudeNormalizer { self.problem("The model refused this request, and Claude Code has no fallback model to go on with".into(), false, out) } // Bookkeeping the timeline has no use for (the user's hooks, command lists, the - // session title, the CLI's own summaries, a task's change of state that its - // `task_notification` says again, a commit that its tool call already shows): - // known lines, kept in the raw log only. + // session title, the CLI's own summaries, a commit that its tool call already + // shows): known lines, kept in the raw log only. "hook_started" | "hook_progress" | "hook_response" | "commands_changed" | "session_title_changed" | "files_persisted" - | "post_turn_summary" | "task_updated" | "vcs_state_changed" => {} + | "post_turn_summary" | "vcs_state_changed" => {} + "task_updated" => self.on_task_updated(v), // The whole list of what the CLI still runs in the background, said at every change // (cli-claude-stream-json-2.1.311-part2 §6). No request reads it: Codly keeps the last one. "background_tasks_changed" => self.on_background_tasks(&v["tasks"], out), @@ -1678,11 +1827,15 @@ impl ClaudeNormalizer { } } - /// The CLI took a model switch that Codly asked for, and whoever asked says so. A request - /// that is on its way still writes lines on the model the session had (not recorded: no - /// recording has a line after a switch during a turn), and the switch itself is no news - /// of the CLI's. So nothing is said about the model of a line before the next turn's - /// `system/init` names the session's model again. + /// The CLI took a model switch that Codly asked for, and whoever asked says so: the + /// switch is no news of the CLI's. Recorded (part 3 §8, `r5-model-midturn`, n=1): a + /// switch during a turn takes effect at the next model request of that same turn, so the + /// turn's later lines name the new model while its `system/init` named the old one, and + /// the next turn's `system/init` names the new one. A switch while an answer is being + /// written leaves the rest of that answer and its line on the old model (part 4 §5, + /// `r6-model-while-streaming-1` and `-2`, n=2). So nothing is said about the model of a + /// line before the next turn's `system/init` names the session's model again: no "now + /// runs on" for the model Codly asked for, and no "runs on … again" after it. fn model_switched(&mut self) { self.session_model = None; self.turn_model = None; @@ -1848,7 +2001,22 @@ impl ClaudeNormalizer { /// that runs beside the agent's own calls. A subagent (`task_type: "local_agent"`) gets /// its events. A command (`local_bash`) already is a tool call; one that is left running /// in the background is in the CLI's list of background tasks (`on_background_tasks`), - /// and the word of its `task_notification` says there how it ended. + /// and the word of its `task_notification` says there how it ended. The recorded words: + /// "completed"; "failed" for a command that ends with another exit code than 0 (part 3 + /// §2, `r5-background-fail`, n=1), for a command whose shell is killed by SIGTERM or + /// SIGKILL (part 4 §3, `r6-fails-signal-term` and `-kill`, n=1 each: there is no word for + /// a signal) and for a subagent that fails by itself (part 4 §3, `r6-fails-helper-*`, n=1 + /// each); "stopped" after `stop_task`, for a command (part 2 §6) and for a subagent (part + /// 3 §1, part 4 §2), and after an interrupt for every subagent (part 4 §1, part 5 §4). A + /// command the agent waits for becomes a task about 3 s after its call starts (`local_bash`, + /// `is_backgrounded` false, the call's `tool_use_id`): its `task_notification` (its own task + /// id; "completed" when it ends by itself, written just before the call's result, with no + /// `task_updated` and no list line: part 5 §12, `r7-bash-becomes-task-*`, n=2 per duration; + /// "failed" when it ends by itself with another exit code than 0, and "stopped" at an + /// interrupt: part 6 §7, `r8-bash-task-fails-*`, n=2, and part 4 §1) ends no subagent and no + /// listed task. The call's own result ends it. Its `output_file` is empty in those lines, + /// but not always: a call cut off by a budget stop, ended when stdin closed, names a file + /// there (part 5 §10, `r7-budget-during-call-1-t1`). Codly does not read it. fn on_task(&mut self, subtype: &str, v: &Value, out: &mut Vec) { if subtype == "task_notification" && let (Some(task_id), Some(word)) = (v["task_id"].as_str(), v["status"].as_str()) @@ -1862,7 +2030,8 @@ impl ClaudeNormalizer { self.helper_started(call_id, v["description"].as_str().unwrap_or(""), out); } self.helper_named(call_id, v["subagent_type"].as_str(), out); - let Some(helper) = self.helpers.get_mut(call_id) else { return }; + // (a subagent's end is said once: its row was closed before, by its list) + let Some(helper) = self.helpers.get_mut(call_id).filter(|h| !h.done) else { return }; let (tool_uses, tokens) = (v["usage"]["tool_uses"].as_i64(), v["usage"]["total_tokens"].as_i64()); let text = |key: &str| v[key].as_str().map(str::trim).filter(|t| !t.is_empty()).map(str::to_owned); match subtype { @@ -1874,30 +2043,53 @@ impl ClaudeNormalizer { let step = text("description"); out.push(EventKind::SubAgentProgress { call_id: call_id.into(), name: None, step, tool_call_id: None, tool_uses, tokens, report: None }); } - // task_notification: it ended, and `summary` is what it reported + // task_notification: it ended, and `summary` is what it reported. The line of a + // subagent that was stopped has the subagent's description there (recorded, + // `r5-stop-subagent-1` and `-2`): it reported nothing. One that failed reports why: + // the error of its `task_updated` line, which `summary` repeats (recorded). _ => { helper.done = true; - let report = text("summary"); - out.push(EventKind::SubAgentProgress { call_id: call_id.into(), name: None, step: None, tool_call_id: None, tool_uses, tokens, report }); + let report = helper.error.take().or_else(|| text("summary").filter(|said| *said != helper.description)); + if report.is_some() || tool_uses.is_some() || tokens.is_some() { + out.push(EventKind::SubAgentProgress { call_id: call_id.into(), name: None, step: None, tool_call_id: None, tool_uses, tokens, report }); + } let status = v["status"].as_str().unwrap_or("completed").to_string(); out.push(EventKind::SubAgent { call_id: call_id.into(), description: helper.description.clone(), status }); } } } + /// `system/task_updated`: a task's change of state, which its `task_notification` then + /// says again. Only the reason of a subagent that failed is kept from it: `patch.error`, + /// recorded only beside `patch.status` "failed" (part 4 §3, `r6-fails-helper-background` + /// and `-foreground`, n=1 each). Its end row reports it (`on_task`). + fn on_task_updated(&mut self, v: &Value) { + let (Some(task_id), Some(error)) = (v["task_id"].as_str(), v["patch"]["error"].as_str().map(str::trim).filter(|e| !e.is_empty())) else { return }; + if let Some(helper) = self.helpers.values_mut().find(|h| !h.done && h.task_id.as_deref() == Some(task_id)) { + helper.error = Some(error.to_string()); + } + } + /// `system/background_tasks_changed`: the CLI's whole list of what runs in the background /// (part 2 §6: a command left running with `run_in_background`, a subagent), said at /// every change. The event carries the list and what left it since the last one, each /// with the word of its `task_notification` line (recorded: that line comes before the /// list line, when a task ends by itself, at `stop_task` and at SIGTERM), or "ended" when /// none came. The list is the whole truth each time, so a line that was missed leaves - /// nothing open. + /// nothing open. What is listed (part 3 §2, `r5-background-fail`, n=1): a background + /// command, a background subagent, and a foreground command from the moment the CLI is + /// told to move it to the background. A foreground subagent or command is in no list. + /// A task starts with the first list that names it: it keeps that time in later lists. fn on_background_tasks(&mut self, tasks: &Value, out: &mut Vec) { - let tasks = background_tasks(tasks); + let mut tasks = background_tasks(tasks); + for t in &mut tasks { + t.started_at = self.background.iter().find(|known| known.id == t.id).map_or(Some(now_ms()), |known| known.started_at); + } let gone: Vec = self.background.iter().filter(|t| !tasks.iter().any(|now| now.id == t.id)).cloned().collect(); - // A background subagent that left the list with no `task_notification`: its row is - // closed here, or it would say "running" for good. (A subagent that never was in a - // list is left as it is: a foreground one in the list is not recorded.) + // A background subagent that left the list with no `task_notification` (not recorded: + // at `stop_task` and at its own end that line comes first): its row is closed here, + // or it would say "running" for good. (A subagent that never was in a list is left + // as it is: a foreground one is in none.) for (call_id, helper) in &mut self.helpers { let listed = |t: &BackgroundTask| helper.task_id.as_deref() == Some(t.id.as_str()); if helper.background && !helper.done && gone.iter().any(listed) { @@ -1923,8 +2115,25 @@ impl ClaudeNormalizer { self.background.iter().filter(|t| t.kind == "command").map(|t| t.id.clone()).collect() } + /// Does the CLI's last list of background tasks name a helper? + fn helpers_in_background(&self) -> bool { + self.background.iter().any(|t| t.kind == "helper") + } + + /// The task id that `stop_task` takes for `id`: a task of the CLI's last list as it is, or + /// the call id of a helper at work, whose task id its `task_started` line said. `stop_task` + /// with that id ends a helper whose `Agent` call still waits: the call returns an error + /// result and the turn goes on (part 4 §2, `r6-shutdown-helper-foreground-stop-*`, n=2). + /// None: nothing by that id runs beside the agent. + fn task_to_stop(&self, id: &str) -> Option { + if self.background.iter().any(|t| t.id == id) { + return Some(id.to_string()); + } + self.helpers.get(id).filter(|h| !h.done).and_then(|h| h.task_id.clone()) + } + fn helper_started(&mut self, call_id: &str, description: &str, out: &mut Vec) { - let helper = Helper { description: description.to_string(), name: None, background: false, task_id: None, done: false }; + let helper = Helper { description: description.to_string(), name: None, background: false, task_id: None, error: None, done: false }; self.helpers.insert(call_id.to_string(), helper); out.push(EventKind::SubAgent { call_id: call_id.to_string(), description: description.to_string(), status: "running".into() }); } @@ -2167,7 +2376,11 @@ impl ClaudeNormalizer { if structured["status"] == "async_launched" { // The call only started it: `task_notification` says when it is done. helper.background = true; - } else if !helper.done { + } else if !helper.done && (ok || helper.task_id.is_none()) { + // (A call that failed does not end a subagent whose task lines Codly + // follows: an interrupt rejects the call BEFORE those lines say "killed" / + // "stopped": part 4 §1, `r6-interrupt-helper-foreground-*`, n=2. They end + // it, or the end of the turn does when none comes.) helper.done = true; let status = if ok { "completed" } else { "failed" }; out.push(EventKind::SubAgent { call_id: id, description: helper.description.clone(), status: status.into() }); @@ -2275,10 +2488,15 @@ impl ClaudeNormalizer { return; } self.flush_text(MessagePhase::Final, out); - // Per-turn delta: `model_usage_since_last_result` (modelUsage and total_cost_usd are - // session-cumulative, including earlier runs after --resume). + // Per-turn delta: `model_usage_since_last_result`. `modelUsage` and `total_cost_usd` are + // the session's totals: with this process's earlier turns, and after `--resume` with + // what the earlier runs cost (part 6 §3, `r8-fork-*`, n=2: the first `total_cost_usd` + // after a resume or a fork is the old total plus the new turn, to the last digit). So + // a turn's cost from one of them is that total less what the earlier runs cost + // (`cost_before`) and less what this process counted before. let (mut input, mut output, mut cache_r, mut cache_w, mut cost, mut window) = (0, 0, 0, 0, 0.0, None::); - let per_model = v["model_usage_since_last_result"].as_object().or(v["modelUsage"].as_object()); + let per_turn = v["model_usage_since_last_result"].as_object(); + let per_model = per_turn.or(v["modelUsage"].as_object()); if let Some(models) = per_model { for m in models.values() { input += m["inputTokens"].as_i64().unwrap_or(0); @@ -2293,7 +2511,10 @@ impl ClaudeNormalizer { output = u["output_tokens"].as_i64().unwrap_or(0); cache_r = u["cache_read_input_tokens"].as_i64().unwrap_or(0); cache_w = u["cache_creation_input_tokens"].as_i64().unwrap_or(0); - cost = v["total_cost_usd"].as_f64().unwrap_or(0.0) - self.usage.cost_usd.unwrap_or(0.0); + cost = v["total_cost_usd"].as_f64().unwrap_or(0.0); + } + if per_turn.is_none() { + cost -= self.cost_before + self.usage.cost_usd.unwrap_or(0.0); } for m in v["modelUsage"].as_object().into_iter().flat_map(|m| m.values()) { if let Some(w) = m["contextWindow"].as_i64() { @@ -2361,8 +2582,19 @@ impl ClaudeNormalizer { }); self.interrupt_requested = false; self.blocks.clear(); - // A background subagent works on past the end of the turn: it and its open calls stay. - // One whose `Agent` call still waited for it is over with the turn. + // A background subagent works on past the end of a turn that ends as completed: it and + // its open calls stay. One whose `Agent` call still waited for it is over with the turn. + // An interrupted turn takes every subagent with it, background ones too, and the stream + // says so itself before the turn's `result` (`task_notification` "stopped", the list + // without them: part 4 §1, 6 of 6 recordings, each with ONE subagent in the middle of a + // Bash call; an interrupt with no turn running ends two helpers, and one that waits for + // its model answer, the same way: part 5 §4, n=2 each), so none is left here. A turn that + // fails by a limit (`error_max_turns`) ends no background subagent: it stays listed, + // ends by its own `task_notification`, and the CLI then starts a turn by itself (part 5 + // §3, `r7-failed-turn-helper-*`, n=2); so it stays here, as after a completed turn. So + // does one at a budget stop: the CLI ends it after the `result`, and its own lines say + // so (part 6 §6, `r8-after-budget-helper-goes-on-2-t2`, n=1). Not recorded: a turn that + // fails by an API error while a subagent works. self.helpers.retain(|id, h| { if !h.done && !h.background { out.push(EventKind::SubAgent { call_id: id.clone(), description: h.description.clone(), status: "stopped".into() }); @@ -2371,6 +2603,10 @@ impl ClaudeNormalizer { }); let helpers = &self.helpers; self.tools.retain(|_, t| t.helper.as_ref().is_some_and(|h| helpers.contains_key(h))); + // A call is repeated only in the lines of its own turn: the ids of the calls that are + // over go, or the set would grow with every call of a long run. + let open = &self.tools; + self.tools_seen.retain(|id| open.contains_key(id)); self.user_denied.clear(); self.denials_known.clear(); self.set_status(AgentStatus::Idle, out); @@ -2603,7 +2839,8 @@ fn background_tasks(tasks: &Value) -> Vec { Some("local_agent") => "helper", _ => "task", }; - Some(BackgroundTask { id: t["task_id"].as_str()?.to_string(), kind: kind.into(), description: t["description"].as_str().unwrap_or_default().to_string() }) + let description = t["description"].as_str().unwrap_or_default().to_string(); + Some(BackgroundTask { id: t["task_id"].as_str()?.to_string(), kind: kind.into(), description, started_at: None }) }; tasks.as_array().into_iter().flatten().filter_map(task).collect() } @@ -2613,12 +2850,15 @@ fn background_tasks(tasks: &Value) -> Vec { /// answer of testdata/claude-interrupt-live.jsonl). Whether `system/init` keeps that mark is /// not recorded, so it never makes two names differ. /// -/// Nor does a name that is part of the other one. Every recording is of Anthropic's own API, -/// where `system/init` and the agent's lines spell a model the same way. Another provider is -/// not recorded, and there the two can differ for one model: the id the session was set up -/// with (a region and vendor in front, a version behind) and the plain id of the answer, or a -/// short name and its dated id. A false "now runs on" in every run would be worse than a -/// missed one for two models where one's name starts the other's. +/// Nor does a name that is part of the other one. Every recording is of Anthropic's own API. +/// There `system/init` and the agent's lines spell a model the same way for an alias and for +/// a dated id, and differently for an undated name of a dated model: a session started with +/// `claude-haiku-4-5` says that name in `system/init` and `claude-haiku-4-5-20251001` in +/// every line of the agent (part 3 §8, `r5-model-start-undated`, n=1). Another provider is +/// not recorded, and there the two can differ for one model too: the id the session was set +/// up with (a region and vendor in front, a version behind) and the plain id of the answer. +/// A false "now runs on" in every run would be worse than a missed one for two models where +/// one's name starts the other's. fn same_model(a: &str, b: &str) -> bool { fn id(m: &str) -> &str { m.split('[').next().unwrap_or(m) @@ -2639,8 +2879,11 @@ fn written_by_the_cli(v: &Value) -> bool { /// The permission suggestions of a request that "for this session" and "always" may send /// back: allow rules for the tool that asked, and directories inside the agent's own folder. /// Never `setMode`: sent back, it puts the whole session in another permission mode -/// (recorded, cli-claude-stream-json-2.1.311 §10), which is more than the request you -/// approved. A directory outside `cwd` would let later edits there pass without a question. +/// (recorded, cli-claude-stream-json-2.1.311 §10; for an Edit request's own and only +/// suggestion too, part 5 §7, `r7-allow-set-mode-*`, n=2; for a Bash request's, and for a +/// mode the request did not suggest, `plan` and `dontAsk`: part 6 §9, `r8-bash-set-mode-*`, +/// n=2 per variant), which is more than the request you approved. A directory outside `cwd` +/// would let later edits there pass without a question. fn grantable(tool: &str, suggestions: &Value, cwd: &Path) -> Vec { let keep = |s: &&Value| match s["type"].as_str() { Some("addRules") => s["behavior"] == "allow" && s["rules"].as_array().is_some_and(|r| !r.is_empty() && r.iter().all(|r| r["toolName"] == tool)), @@ -2696,7 +2939,7 @@ mod tests { provider: Provider::Claude, role, model: Some("haiku:low".into()), - cwd: PathBuf::from("/private/tmp/claude-501/-Users-julien-Documents-Repos-Codly/ae7e9f7f-d897-4679-8080-c22a339ba5b7/scratchpad/fixture-repo"), + cwd: PathBuf::from("/tmp/scratch/fixture-repo"), bin: PathBuf::from("claude"), env: HashMap::new(), session: SessionMode::New { session_id: None }, @@ -2710,6 +2953,7 @@ mod tests { raw_log: PathBuf::from("/tmp/x/raw.ndjson"), byok_command: None, sandbox_shell: false, + max_budget_usd: None, } } @@ -2731,11 +2975,11 @@ mod tests { fn byok_token_command_becomes_an_api_key_helper() { let s = spec(Role::Worker, false); assert!(!build_args(&s, "s", None, &[]).contains(&"--settings".to_string()), "no BYOK, no --settings"); - let s = SpawnSpec { byok_command: Some("~/bin/wif-token \"anthropic\"".into()), ..s }; + let s = SpawnSpec { byok_command: Some("~/bin/get-token \"anthropic\"".into()), ..s }; let a = build_args(&s, "s", None, &[]); let i = a.iter().position(|x| x == "--settings").unwrap(); let v: Value = serde_json::from_str(&a[i + 1]).unwrap(); - assert_eq!(v, serde_json::json!({ "apiKeyHelper": "~/bin/wif-token \"anthropic\"" })); + assert_eq!(v, serde_json::json!({ "apiKeyHelper": "~/bin/get-token \"anthropic\"" })); } /// The `--settings` value of an argv, parsed. There is at most one. @@ -2859,8 +3103,9 @@ mod tests { on["response"]["dependencies"]["errors"] = json!(["a warning in the wrong list"]); assert_eq!(refusal(&on), None); - for why in [off, unasked, refused, failed, missing, odd, unsupported] { - assert!(why.contains("did not start this agent") && why.ends_with("in Settings → Safety"), "{why}"); + // Every refusal has the words by which a task's retry knows it (`retry::needs_you`). + for why in [off, unasked, refused, failed, missing, odd, unsupported, SandboxNotOn::no_answer().to_string()] { + assert!(why.contains(SandboxNotOn::NOT_STARTED) && why.ends_with("in Settings → Safety"), "{why}"); } } @@ -2948,6 +3193,43 @@ mod tests { assert!(!std::fs::read_to_string(dir.path().join("raw.ndjson")).unwrap().contains("get_sandbox_dialog")); } + /// A second success answer with the id of `initialize` while the sandbox check waits for + /// its own answer (no recording has one: the recorded answer, played twice). Before, it + /// took the waiting check away and started the run, and the CLI's real answer about its + /// sandbox was then read by nobody. Now the run is not started, the check is asked once, + /// and its own answer decides. + #[tokio::test] + async fn a_second_initialize_answer_does_not_start_a_run_before_the_sandbox_is_checked() { + let asked = json!({ "subtype": "get_sandbox_dialog" }); + let (_, init) = recorded_control(&recording("r4-sandbox-required-available"), &json!({ "subtype": "initialize", "hooks": null })); + let init_id = init["response"]["request_id"].as_str().unwrap().to_owned(); + for (status_of, starts) in [("r4-sandbox-noauto", true), ("sandbox-off", false)] { + let dir = tempfile::tempdir().unwrap(); + let (mut actor, mut events, _child) = silent_actor(dir.path()); + actor.sandbox_check = Some(SandboxCheck::Due { asked: oneshot::channel().0 }); + let (tx, mut started) = oneshot::channel(); + let mut ready = Some(tx); + + actor.on_json(init.clone(), &init_id, &mut ready).await; + let wrote = last_sent(dir.path()); + assert_eq!(wrote["request"], asked); + actor.on_json(init.clone(), &init_id, &mut ready).await; + assert!(ready.is_some() && started.try_recv().is_err(), "{status_of}: not started by the second answer"); + assert!(emitted(&mut events).is_empty(), "{status_of}: no event before the check's answer"); + assert!(matches!(actor.sandbox_check, Some(SandboxCheck::Asked { .. })), "{status_of}: the check still waits for its answer"); + assert_eq!(last_sent(dir.path()), wrote, "{status_of}: asked once"); + + let (_, mut status) = recorded_control(&recording(status_of), &asked); + status["response"]["request_id"] = wrote["request_id"].clone(); + actor.on_json(status, &init_id, &mut ready).await; + let outcome = started.try_recv().expect("the start is decided"); + assert_eq!(outcome.is_ok(), starts, "{status_of}: {outcome:?}"); + let kinds = emitted(&mut events); + assert_eq!(kinds.len(), usize::from(starts), "{status_of}: {kinds:?}"); + assert_eq!(actor.start_failed, !starts, "{status_of}"); + } + } + /// A settings file saved before the two Claude switches existed loads with both off. #[test] fn an_older_settings_file_has_the_claude_switches_off() { @@ -3188,12 +3470,12 @@ mod tests { EventKind::TextDelta { item_id, text } => Some((item_id.clone(), text.clone())), _ => None, }); - assert_eq!(delta, Some(("msg_011CgPgZ5DraWXssRR4rfPzQ:0".into(), "DONE".into()))); + assert_eq!(delta, Some(("msg-2:0".into(), "DONE".into()))); let msg = events.iter().find_map(|e| match e { EventKind::Message { item_id, text, phase } => Some((item_id.clone(), text.clone(), *phase)), _ => None, }); - assert_eq!(msg, Some(("msg_011CgPgZ5DraWXssRR4rfPzQ:0".into(), "DONE".into(), MessagePhase::Final))); + assert_eq!(msg, Some(("msg-2:0".into(), "DONE".into(), MessagePhase::Final))); assert!(events.iter().any(|e| matches!(e, EventKind::RateLimit { window, .. } if window == "five_hour"))); // Usage after each of the two API calls, then the result's own numbers: the same totals. @@ -3476,6 +3758,13 @@ mod tests { sp.use_user_setup = false; let a = joined(&sp); assert!(a.contains("--setting-sources user --") && a.contains("--strict-mcp-config") && !a.contains("ToolSearch")); + // Also with the folder's local settings file: under `user,local` that file can switch on + // a plugin you turned off, whose MCP server then starts (part 6 §1, n=4). So such a + // folder gets only Codly's servers, with and without that file. + for local_settings in [false, true] { + let a = joined(&SpawnSpec { use_user_setup: false, local_settings, ..spec(Role::Solo, false) }); + assert!(a.contains("--strict-mcp-config"), "local settings {local_settings}: {a}"); + } // the Lead stays read-only either way let lead = joined(&SpawnSpec { use_user_setup: true, ..spec(Role::Lead, true) }); assert!(lead.contains("Skill,LSP") && !lead.contains("Bash") && !lead.contains("Monitor")); @@ -3802,6 +4091,40 @@ mod tests { assert!(norm.mcp_asked.is_empty()); } + /// A server that still connected at the end of a turn is asked about (first request). + /// Before that answer comes, the next turn's init line gives the server as failed, so a + /// second request waits to say why. The first answer already gives it as failed: it + /// reports the server's state and leaves the line to the request that carries the server. + /// Without that, both answers said the line: two lines for one failure. (Lines written + /// here in the recorded shapes: an init line with `pending` is not recorded.) + #[test] + fn a_failed_server_that_a_later_request_waits_for_is_said_by_that_requests_answer() { + use McpServerStatus::{Connecting, Failed}; + let init = |status: &str| json!({ "type": "system", "subtype": "init", "tools": [], "mcp_servers": [{ "name": "codly", "status": "connected" }, { "name": "slow", "status": status }] }); + let result = json!({ "type": "result", "subtype": "success", "is_error": false, "result": "done", "duration_ms": 5 }); + let answer = json!({ "type": "control_response", "response": { "subtype": "success", "request_id": MCP_STATUS_REQUEST, "response": { + "mcpServers": [{ "name": "slow", "status": "failed", "error": "Connection closed" }] + } } }); + + let mut norm = ClaudeNormalizer::new(&spec(Role::Worker, false), "sess-1".into()); + norm.turn_started("go"); + assert_eq!(mcp_states(&norm.on_message(&init("pending"))), [("slow", Connecting, None)]); + norm.on_message(&result); + assert_eq!(norm.outbox.len(), 1, "asked at the turn's end: the server still connected"); + norm.turn_started("again"); + assert!(mcp_states(&norm.on_message(&init("failed"))).is_empty(), "an init line gives no reason: the answer reports the server"); + assert_eq!(norm.outbox.len(), 2, "a second request, for the reason"); + assert!(norm.mcp_reason_asked("slow")); + + let first = norm.on_message(&answer); + assert_eq!(mcp_states(&first), [("slow", Failed, Some("Connection closed"))]); + assert!(errors(&first).is_empty(), "the request that carries the server says the line: {first:?}"); + let second = norm.on_message(&answer); + assert!(mcp_states(&second).is_empty(), "its state is known: {second:?}"); + assert_eq!(errors(&second), [("These MCP servers did not start, so the agent works without their tools in this run: slow (Connection closed)", false)]); + assert!(norm.mcp_asked.is_empty()); + } + /// The MCP server events, as (name, state, reason). fn mcp_states(events: &[EventKind]) -> Vec<(&str, McpServerStatus, Option<&str>)> { events.iter().filter_map(|e| if let EventKind::McpServer { name, status, error } = e { Some((name.as_str(), *status, error.as_deref())) } else { None }).collect() @@ -3834,6 +4157,35 @@ mod tests { assert!(norm.on_message(&json!({ "type": "tool_progress", "elapsed_time_seconds": 30 })).is_empty()); } + /// Recordings `r5-tool-progress-mcp` and `r5-tool-progress-subagent` (part 3 §3, n=1 + /// each): a tool of an MCP server that takes 100 s, and an `Agent` call that waits 100 s + /// for its subagent. Each gets the heartbeat a long Bash call gets, with the call's id. + /// The subagent's own Bash call gets none: the event after its start says whose call it + /// is, which is how the watchdog knows not to wait for a heartbeat of it. + #[test] + fn a_long_mcp_call_and_a_call_that_waits_for_a_subagent_give_a_life_sign_every_30_s() { + let played = |name: &str| { + let mut norm = ClaudeNormalizer::new(&spec(Role::Solo, false), "sess-1".into()); + let mut events = norm.turn_started("go"); + events.extend(replay(&mut norm, &recorded(name))); + events + }; + let beats = |events: &[EventKind]| -> Vec { events.iter().filter_map(|e| if let EventKind::ToolProgress { call_id } = e { Some(call_id.clone()) } else { None }).collect() }; + + let mcp = played("r5-tool-progress-mcp"); + assert_eq!(tool_calls(&mcp), [("toolu-1", "mcp__ping-slow__ping")]); + assert_eq!(beats(&mcp), ["toolu-1", "toolu-1", "toolu-1"]); + + let helper = played("r5-tool-progress-subagent"); + assert_eq!(tool_calls(&helper), [("toolu-1", "Agent"), ("toolu-2", "Bash")]); + assert_eq!(beats(&helper), ["toolu-1", "toolu-1", "toolu-1"], "the heartbeats are the Agent call's"); + let own = helper.iter().position(|e| matches!(e, EventKind::ToolStarted { call_id, .. } if call_id == "toolu-2")).unwrap(); + assert!(matches!(&helper[own + 1], EventKind::SubAgentProgress { call_id, tool_call_id: Some(id), .. } if call_id == "toolu-1" && id == "toolu-2"), "{:?}", helper[own + 1]); + let first_beat = helper.iter().position(|e| matches!(e, EventKind::ToolProgress { .. })).unwrap(); + let ended = helper.iter().position(|e| matches!(e, EventKind::ToolCompleted { call_id, .. } if call_id == "toolu-2")).unwrap(); + assert!(own < first_beat && first_beat < ended, "they came while the subagent's call ran"); + } + /// The subagent events, one short line each: only what the event says. fn subagent_lines(events: &[EventKind]) -> Vec { events @@ -4014,6 +4366,42 @@ mod tests { assert_eq!(said("r4-tool-progress").0, Vec::::new()); } + /// Recording `r5-background-fail` (part 3 §2, n=1). A background command that ends with + /// exit code 1 leaves the list with the CLI's word "failed". A subagent the agent waits + /// for is in no list, and neither is a command the agent waits for, until the CLI is told + /// to move it to the background (the driver's `background_tasks` request, which Codly + /// does not send): from then on it is listed, and its end is said like any other. + #[test] + fn a_background_command_that_fails_leaves_the_list_as_failed() { + let lines = recorded("r5-background-fail"); + let mut norm = ClaudeNormalizer::new(&spec(Role::Worker, false), "sess-1".into()); + let mut events = norm.turn_started("go"); + events.extend(replay(&mut norm, &lines)); + assert_eq!( + background_lines(&events), + [ + "tid-1 command: Run sleep 4 then exit 1 in background | -", + "- | tid-1 command failed: Run sleep 4 then exit 1 in background", + "tid-4 command: Echo a, sleep 20 seconds, echo b | -", + "- | tid-4 command completed: Echo a, sleep 20 seconds, echo b", + ] + ); + // The foreground subagent of the third turn: its row, and no list line. + assert!(lines.iter().any(|l| l["subtype"] == "task_started" && l["task_type"] == "local_agent" && l["is_backgrounded"] == false)); + assert_eq!( + subagent_lines(&events), + [ + "toolu-2 running: Run echo with sleep in subagent", + "toolu-2 name=general-purpose", + "toolu-2 step=Running Echo a, sleep 6 seconds, echo b uses=1 tokens=5187", + "toolu-2 call=toolu-3", + "toolu-2 report=```\na\nb\n``` uses=1 tokens=6042", + "toolu-2 completed: Run echo with sleep in subagent", + ] + ); + assert!(!events.iter().any(|e| matches!(e, EventKind::Unknown { .. })), "{events:?}"); + } + /// What no recording has: a kind of task Codly has no name for, an entry with no id, and /// a task that leaves the list with no `task_notification` before (a line that was /// missed). The list is the whole list each time, so nothing stays open. @@ -4181,6 +4569,39 @@ mod tests { assert_eq!(own_errors(&events), [budget], "said once, before the first turn's end"); } + /// Codly gives a run a limit of its own only through `SpawnSpec::max_budget_usd`. + #[test] + fn a_run_with_a_limit_of_its_own_passes_it_to_claude_code() { + let flag = |s: &SpawnSpec| { + let a = build_args(s, "s", None, &[]); + a.iter().position(|x| x == "--max-budget-usd").map(|i| a[i + 1].clone()) + }; + let s = spec(Role::Worker, false); + assert_eq!(flag(&s), None); + assert_eq!(flag(&SpawnSpec { max_budget_usd: Some(0.6), ..s }), Some("0.6".into())); + } + + /// Recordings `r6-budget-midturn-1-c1` (the model answered in text, with no tool call) + /// and `r6-budget-midturn-1-c3` (the limit came after one tool call had run; the call the + /// last request asked for did not run), on a resumed process with `--max-budget-usd`: the + /// turn fails with the run's own reason, and the turn after it fails the same way at once. + /// Codly ends the run at the first one (`breaker_run.rs`, `run_limit_turn_end`). + #[test] + fn a_turn_that_reaches_the_runs_own_limit_says_what_to_do() { + let limited = SpawnSpec { max_budget_usd: Some(0.01), session: SessionMode::Resume { session_id: "sess-1".into() }, ..spec(Role::Solo, false) }; + let reason = "This run of Ada reached the limit it started with (0.01 USD of your budget were left then). Send your message again: the next run starts with what is left now. It can end a little above the limit: a request that was on its way is finished."; + for name in ["r6-budget-midturn-1-c1", "r6-budget-midturn-1-c3"] { + let mut norm = ClaudeNormalizer::new(&limited, "sess-1".into()); + let mut events = norm.turn_started("Run the Bash command `echo one`, then `echo two`, then `echo three`"); + events.extend(replay(&mut norm, &recorded(name))); + assert_eq!(turn_ends(&events), [(TurnStatus::Failed, Some(reason)), (TurnStatus::Failed, Some(reason))], "{name}"); + assert_eq!(errors(&events).iter().filter(|(message, _)| *message == reason).count(), 1, "said once: {name}"); + // The turn's own cost is counted, not the session's `total_cost_usd`. + let cost = events.iter().rev().find_map(|e| if let EventKind::UsageUpdated { usage } = e { usage.cost_usd } else { None }).unwrap(); + assert!(cost > 0.0 && cost < 0.001, "{name}: {cost}"); + } + } + /// Recording `misc-events`: the result's `permission_denials` lists calls Codly itself was /// asked about. The same entry for a call nobody asked about is Claude Code's own denial. #[test] @@ -4897,8 +5318,91 @@ mod tests { assert!(cli.actor.stage == Stage::Closing && cli.actor.stdin.is_none() && cli.actor.deadline.is_some(), "{:?}", cli.actor.stage); } - /// A background command the CLI does not report as stopped is not waited for without end, - /// and a CLI that still holds a message is asked for nothing more: its process is ended. + /// Recording `r5-stop-sequence` (part 3 §4, n=1): the whole stop of an agent as one run of + /// the CLI. A background command runs, a turn runs a command, a third message waits in the + /// CLI. The driver sends what Codly sends, in Codly's order: the interrupt with + /// `cancel_queued`, `stop_task` right after the stopped turn's `result`, then it closes + /// stdin (the recorded CLI exits a second later, with neither command left running). + #[tokio::test] + async fn a_stop_is_an_interrupt_then_stop_task_then_stdin_closed_as_recorded() { + let mut cli = Replay::of("r5-stop-sequence"); + let kinds = cli.play(|l| l["_sent"]["request"]["subtype"] == "interrupt").await; + assert_eq!(turns(&kinds), ["start:Run", "end:Completed", "start:Run"]); + assert_eq!(cli.actor.norm.commands_in_background(), ["tid-1"], "the command of the first turn runs on"); + assert_eq!(cli.actor.waiting.len(), 1, "the third message waits in the CLI"); + + // 1. The interrupt: the CLI drops the message that waits and ends the turn. + cli.in_place_of_the_drivers_request(AgentCmd::Shutdown).await; + assert_eq!(cli.actor.stage, Stage::Interrupting); + let kinds = cli.play(|l| l["type"] == "result").await; + assert_eq!(turns(&kinds), ["end:Interrupted"]); + assert!(cli.actor.waiting.is_empty() && !cli.actor.left_in_cli, "the CLI dropped the message"); + + // 2. `stop_task` for the background command, written with no wait after that result: + // the driver's next request is the same line. + let recorded = cli.lines.iter().find(|l| l["_sent"]["type"] == "control_request").expect("the driver's stop_task")["_sent"].clone(); + let wrote = last_sent(cli.dir.path()); + assert_eq!((&wrote["type"], &wrote["request"]), (&recorded["type"], &recorded["request"])); + assert_eq!(wrote["request"], json!({ "subtype": "stop_task", "task_id": "tid-1" })); + assert!(cli.actor.stage == Stage::StoppingTasks && cli.actor.stdin.is_some(), "{:?}", cli.actor.stage); + + // 3. The CLI says that nothing runs in the background any more: stdin is closed. + let kinds = cli.play(|_| false).await; + assert!(kinds.is_empty(), "not shown as this agent's work: {kinds:?}"); + assert!(cli.actor.norm.commands_in_background().is_empty()); + assert!(cli.actor.stage == Stage::Closing && cli.actor.stdin.is_none() && cli.actor.deadline.is_some(), "{:?}", cli.actor.stage); + assert_eq!(cli.written().len(), 3, "no message is sent again"); + } + + /// Recordings `r5-stop-subagent-1` and `-2` (part 3 §1, n=2; the first is played here): + /// `stop_task` with the task id of a background subagent, as "Stop" sends it. The + /// subagent's row ends as "stopped", with no report (the line's `summary` only repeats its + /// description), its own call is closed, and the list is empty. Then the CLI starts a turn + /// by itself: a turn with no prompt of yours, and its own end. + #[tokio::test] + async fn a_stopped_background_subagent_ends_as_stopped_and_the_cli_starts_a_turn_by_itself() { + for name in ["r5-stop-subagent-1", "r5-stop-subagent-2"] { + let lines = recorded(name); + let order: Vec<&str> = lines.iter().skip_while(|l| l["subtype"] != "task_updated").filter_map(|l| l["subtype"].as_str().or(l["type"].as_str())).take(4).collect(); + assert_eq!(order, ["task_updated", "task_notification", "background_tasks_changed", "control_response"], "{name}"); + } + + let mut cli = Replay::of("r5-stop-subagent-1"); + // The turn that starts the subagent in the background, and the subagent's own call. + let mut kinds = cli.play(|l| l["_sent"]["request"]["subtype"] == "get_task_output").await; + assert_eq!(turns(&kinds), ["start:Use", "end:Completed"]); + // (The driver first asked for the subagent's output, which Codly does not do: the CLI + // has no such output, and its answer is an error.) + let no_output = cli.lines.pop_front().unwrap(); + assert_eq!(no_output["response"]["subtype"], "error"); + + cli.play(|l| l["_sent"]["request"]["subtype"] == "stop_task").await; + let (reply, mut answer) = mpsc::unbounded_channel(); + cli.in_place_of_the_drivers_request(AgentCmd::Session { request: SessionRequest::StopTask("tid-1".into()), reply }).await; + kinds.extend(cli.play(|l| l["type"] == "result").await); + assert_eq!(answer.try_recv().expect("the CLI's answer reaches whoever asked"), Ok(json!({}))); + + assert_eq!( + subagent_lines(&kinds), + [ + "toolu-1 running: Run delayed echo command", + "toolu-1 name=general-purpose", + "toolu-1 call=toolu-2", + "toolu-1 step=Running Print begin, wait 113 seconds, print end uses=1 tokens=5189", + "toolu-1 stopped: Run delayed echo command", + ] + ); + assert_eq!(background_lines(&kinds), ["tid-1 helper: Run delayed echo command | -", "- | tid-1 helper stopped: Run delayed echo command"]); + assert!(kinds.iter().any(|k| matches!(k, EventKind::ToolCompleted { call_id, ok: false, .. } if call_id == "toolu-2")), "the subagent's own call is closed"); + assert_eq!(turns(&kinds), ["start:Use", "end:Completed", "start", "end:Completed"], "the turn after the stop has no prompt"); + assert!(!kinds.iter().any(|k| matches!(k, EventKind::Unknown { .. })), "{kinds:?}"); + assert!(!cli.actor.turn_active && cli.actor.session_replies.is_empty()); + } + + /// A background helper and a command that the CLI does not report as stopped are not + /// waited for without end, and a CLI that still holds a message is asked for nothing more: + /// its process is ended. (The lists are written here: no recording has a CLI that ignores + /// the stop.) #[tokio::test] async fn a_background_command_that_does_not_stop_does_not_hold_the_stop() { let tasks = json!({ "type": "system", "subtype": "background_tasks_changed", "tasks": [ @@ -4916,8 +5420,13 @@ mod tests { let dir = tempfile::tempdir().unwrap(); let (mut actor, _events, _child) = silent_actor(dir.path()); actor.on_json(tasks.clone(), "codly-0", &mut None).await; - assert_eq!(actor.norm.commands_in_background(), ["tid-1"], "the command; `stop_task` on a subagent is not recorded"); + assert_eq!(actor.norm.commands_in_background(), ["tid-1"], "the command; the helper gets no `stop_task`"); + // The helper first: the interrupt. Its list does not come in time: the command is + // stopped all the same. actor.on_cmd(AgentCmd::Shutdown).await; + assert_eq!((interrupts_sent(dir.path()), actor.stage), (1, Stage::StoppingHelpers)); + assert!(stops_sent(dir.path()).is_empty()); + actor.on_deadline().await; assert_eq!(stops_sent(dir.path()), [json!("tid-1")]); assert_eq!(actor.stage, Stage::StoppingTasks); actor.on_deadline().await; @@ -4947,8 +5456,19 @@ mod tests { // The other end of the actor's pipe is closed: it was the stdin of a process that is gone. let env = HashMap::from([("PATH".to_string(), "/usr/bin:/bin".to_string())]); let mut gone = proc::command(Path::new("/bin/sh"), &["-c".into(), "exit 0".into()], dir.path(), &env).spawn().unwrap(); - actor.stdin = gone.stdin.take(); + let mut stdin = gone.stdin.take().unwrap(); gone.wait().await.unwrap(); + // A process that another test starts while this one is started gets a copy of that end + // too, and keeps it until its exec: for that long a write still goes into the pipe. + // The end is closed for good once a write fails. + let closed = async { + use tokio::io::AsyncWriteExt; + while stdin.write_all(b"\n").await.is_ok() { + tokio::time::sleep(Duration::from_millis(1)).await; + } + }; + tokio::time::timeout(Duration::from_secs(10), closed).await.expect("nothing reads the pipe of a process that is gone"); + actor.stdin = Some(stdin); actor.on_cmd(AgentCmd::Shutdown).await; assert!(actor.stage == Stage::Killing && actor.stdin.is_none() && actor.deadline.is_none(), "no wait for a list: {:?}", actor.stage); @@ -5007,6 +5527,21 @@ mod tests { answer.try_recv().expect("the CLI's answer reaches whoever asked") } + /// As `ask_as_recorded`, for the request the recording's driver sent under the id `host` + /// (a recording that sends one request more than once). + async fn ask_in_place_of(actor: &mut Actor, dir: &Path, lines: &[Value], request: SessionRequest, host: &str) -> Result { + let sent = lines.iter().map(|l| &l["_sent"]).find(|s| s["request_id"] == host).unwrap_or_else(|| panic!("no recorded request {host}")); + let answered = |l: &&Value| l["type"] == "control_response" && l["response"]["request_id"] == host; + let mut response = lines.iter().find(answered).unwrap_or_else(|| panic!("no recorded answer to {host}")).clone(); + let (reply, mut answer) = mpsc::unbounded_channel(); + actor.on_cmd(AgentCmd::Session { request, reply }).await; + let wrote = last_sent(dir); + assert_eq!((&wrote["type"], &wrote["request"]), (&sent["type"], &sent["request"]), "Codly writes the recorded request {host}"); + response["response"]["request_id"] = wrote["request_id"].clone(); + actor.on_json(response, "codly-0", &mut None).await; + answer.try_recv().expect("the CLI's answer reaches whoever asked") + } + #[tokio::test] async fn session_requests_go_out_and_come_back_as_recorded() { let dir = tempfile::tempdir().unwrap(); @@ -5060,6 +5595,12 @@ mod tests { assert_eq!(answer.try_recv().unwrap(), Err("Claude Code is shutting down".to_string())); } + /// The recorded list line of `lines` that names the background task `id`. + fn list_naming(lines: &[Value], id: &str) -> Value { + let names = |l: &&Value| l["subtype"] == "background_tasks_changed" && l["tasks"].as_array().is_some_and(|t| t.iter().any(|t| t["task_id"] == id)); + lines.iter().find(names).unwrap_or_else(|| panic!("no recorded list names {id}")).clone() + } + /// Recording `r4-background-life`: `stop_task` on a background command that runs. The /// answer is empty: the CLI's list of its background tasks says that the task is gone. #[tokio::test] @@ -5067,6 +5608,7 @@ mod tests { let dir = tempfile::tempdir().unwrap(); let (mut actor, _events, _child) = silent_actor(dir.path()); let lines = recording("r4-background-life"); + actor.on_json(list_naming(&lines, "tid-2"), "codly-0", &mut None).await; let request = json!({ "subtype": "stop_task", "task_id": "tid-2" }); let answer = ask_as_recorded(&mut actor, dir.path(), &lines, SessionRequest::StopTask("tid-2".into()), request).await; assert_eq!(answer, Ok(json!({}))); @@ -5102,6 +5644,8 @@ mod tests { ); let lines = recording("r4-background-life"); + actor.on_json(list_naming(&lines, "tid-2"), "codly-0", &mut None).await; + emitted(&mut events); let request = json!({ "subtype": "stop_task", "task_id": "tid-2" }); let answer = ask_as_recorded(&mut actor, dir, &lines, SessionRequest::StopTask("tid-2".into()), request).await; assert_eq!(answer, Ok(json!({}))); @@ -5109,6 +5653,53 @@ mod tests { assert!(emitted(&mut events).is_empty() && actor.session_replies.is_empty()); } + /// Recording `r5-mcp-reconnect-toggle` (part 3 §10, n=1): a server that exits at its + /// start, a reconnect while it still fails, a reconnect that works, then "Turn off" and + /// "Turn on" (`mcp_toggle`). Every request goes out as recorded. A success has no body, so + /// the answer says nothing about the server: Codly asks where the servers stand after + /// each one, and the recorded answer to that is the server's next state. + #[tokio::test] + async fn an_mcp_server_is_turned_off_and_on_as_recorded() { + use McpServerStatus::{Connected, Disabled, Failed}; + let dir = tempfile::tempdir().unwrap(); + let (mut actor, mut events, _child) = silent_actor(dir.path()); + let lines = recording("r5-mcp-reconnect-toggle"); + let dir = dir.path(); + let asked = json!({ "type": "control_request", "request_id": MCP_STATUS_REQUEST, "request": { "subtype": "mcp_status" } }); + // The CLI's recorded answer to the driver's `mcp_status` under this id, as the answer + // to the request Codly wrote. + let status = |host: &str| { + let mut answer = lines.iter().find(|l| l["response"]["request_id"] == host).unwrap_or_else(|| panic!("no answer {host}")).clone(); + assert!(answer["response"]["response"]["mcpServers"].is_array(), "{host} answers `mcp_status`"); + answer["response"]["request_id"] = json!(MCP_STATUS_REQUEST); + answer + }; + let reconnect = || SessionRequest::McpReconnect("ping-flaky".into()); + let switch = |on: bool| SessionRequest::McpEnabled("ping-flaky".into(), on); + // (the driver's request, its recorded answer, the driver's `mcp_status` after it, the server then) + let steps = [ + (reconnect(), "host-2", Err("Connection closed".to_string()), "host-3", (Failed, Some("Connection closed"))), + (reconnect(), "host-4", Ok(Value::Null), "host-5", (Connected, None)), + (switch(false), "host-6", Ok(Value::Null), "host-7", (Disabled, None)), + (switch(true), "host-8", Ok(Value::Null), "host-9", (Connected, None)), + ]; + for (request, host, answer, then, (state, reason)) in steps { + assert_eq!(ask_in_place_of(&mut actor, dir, &lines, request, host).await, answer, "{host}"); + assert!(emitted(&mut events).is_empty(), "{host}: the answer is the asker's, not a line of the timeline"); + assert_eq!(last_sent(dir), asked, "{host}: the servers' state is asked for after it"); + actor.on_json(status(then), "codly-0", &mut None).await; + let said = emitted(&mut events); + assert_eq!(mcp_states(&said), [("ping-flaky", state, reason)], "{then}"); + } + assert_eq!(lines.iter().find(|l| l["_sent"]["request_id"] == "host-6").unwrap()["_sent"]["request"], json!({ "subtype": "mcp_toggle", "serverName": "ping-flaky", "enabled": false })); + assert!(actor.session_replies.is_empty() && actor.norm.mcp_asked.is_empty()); + + // The turn after it: its init line gives the server as connected, which is no news. + let init = lines.iter().find(|l| l["subtype"] == "init").expect("the recorded init line"); + assert_eq!(init["mcp_servers"], json!([{ "name": "ping-flaky", "status": "connected", "source": "dynamic" }])); + assert!(mcp_states(&actor.norm.on_message(init)).is_empty()); + } + /// The plan-mode recording: `ExitPlanMode` arrives as a request with the plan in it. Sent /// back with a note, the session stays in plan mode and the plan comes again; accepted, /// the CLI leaves plan mode by itself and Codly records that. @@ -5253,7 +5844,7 @@ mod tests { // An effort level: the answer is a bare success, and the settings say what the session // works with. let request = json!({ "subtype": "apply_flag_settings", "settings": { "effortLevel": "low" } }); - let set = ask_as_recorded(&mut actor, dir, &lines, SessionRequest::Effort("low".into()), request).await; + let set = ask_as_recorded(&mut actor, dir, &lines, SessionRequest::Effort(Some("low".into())), request).await; assert_eq!(set, Ok(Value::Null)); let (reply, mut answer) = mpsc::unbounded_channel(); actor.on_cmd(AgentCmd::Session { request: SessionRequest::Settings, reply }).await; @@ -5271,7 +5862,7 @@ mod tests { assert_eq!(answer_to("host-9")["response"]["subtype"], "success"); assert_eq!(answer_to("host-10")["response"]["response"]["applied"]["effort"], "low"); let (reply, mut answer) = mpsc::unbounded_channel(); - actor.on_cmd(AgentCmd::Session { request: SessionRequest::Effort("not-a-level".into()), reply }).await; + actor.on_cmd(AgentCmd::Session { request: SessionRequest::Effort(Some("not-a-level".into())), reply }).await; assert_eq!(answer.try_recv().unwrap(), Err("Claude Code has no effort level \"not-a-level\"".to_string())); assert_eq!(last_sent(dir), wrote, "nothing was written"); assert!(actor.session_replies.is_empty()); @@ -5347,6 +5938,69 @@ mod tests { assert_eq!(notices(&mut events), ["Claude Code now runs on claude-haiku-5-5, not on claude-sonnet-5-5"]); } + /// The model each `assistant` line of the agent's own names, in order, without repeats. + fn models_said(lines: &[Value]) -> Vec<&str> { + let mut said: Vec<&str> = lines.iter().filter(|l| l["type"] == "assistant" && l["parent_tool_use_id"].is_null()).filter_map(|l| l["message"]["model"].as_str()).collect(); + said.dedup(); + said + } + + /// Recording `r5-model-midturn` (part 3 §8, n=1): Codly's own switch to sonnet while a + /// command of a turn on haiku runs, then to the CLI's default model and back to haiku + /// between turns. The turn's line after the switch is on sonnet while its init line said + /// haiku. Every change here is one Codly asked for, and whoever asked says so: no row + /// says "now runs on", and none says "runs on … again". + #[tokio::test] + async fn a_model_switch_during_a_turn_makes_no_rows_about_the_model_as_recorded() { + let mut cli = Replay::of("r5-model-midturn"); + let lines = recording("r5-model-midturn"); + assert_eq!(models_said(&lines), ["claude-haiku-5-5", "claude-sonnet-5-5", "claude-opus-5-5", "claude-haiku-5-5"]); + let first_turn = lines.iter().position(|l| l["type"] == "result").unwrap(); + assert_eq!(lines[..first_turn].iter().find(|l| l["subtype"] == "init").unwrap()["model"], "claude-haiku-5-5"); + assert_eq!(models_said(&lines[..first_turn]), ["claude-haiku-5-5", "claude-sonnet-5-5"], "the switch shows inside the turn"); + + let mut kinds = Vec::new(); + for (model, resolved) in [("sonnet", "claude-sonnet-5-5"), (DEFAULT_MODEL, "claude-opus-5-5"), ("haiku", "claude-haiku-5-5")] { + kinds.extend(cli.play(|l| l["_sent"]["request"]["subtype"] == "set_model").await); + let (reply, mut answer) = mpsc::unbounded_channel(); + cli.in_place_of_the_drivers_request(AgentCmd::Session { request: SessionRequest::Model(model.into()), reply }).await; + // the CLI's own line about the switch, then its answer + kinds.extend(cli.play(|l| l["type"] == "control_response").await); + assert_eq!(answer.try_recv().expect("the CLI's answer reaches whoever asked"), Ok(json!({ "model": resolved })), "{model}"); + } + kinds.extend(cli.play(|_| false).await); + + assert_eq!(turns(&kinds), ["start:Run", "end:Completed", "start:Reply", "end:Completed", "start:Reply", "end:Completed", "start:Reply", "end:Completed"]); + let notices: Vec<&str> = kinds.iter().filter_map(|k| if let EventKind::Notice { text } = k { Some(text.as_str()) } else { None }).collect(); + assert_eq!(notices, Vec::<&str>::new()); + assert!(!kinds.iter().any(|k| matches!(k, EventKind::Unknown { .. })), "the CLI's own lines about a switch are known: {kinds:?}"); + assert_eq!(cli.actor.norm.session_model.as_deref(), Some("claude-haiku-5-5")); + } + + /// Recording `r5-model-start-undated` (part 3 §8, n=1): a session started with the + /// undated name of a dated model. Its init line says `claude-haiku-4-5`, every line of + /// the agent `claude-haiku-4-5-20251001`. That is one model: no row says that the turn + /// runs on another one. (The three other starts of that section spell the model the + /// same way in both places.) + #[test] + fn an_undated_model_name_and_its_dated_id_are_one_model() { + let lines = recorded("r5-model-start-undated"); + let init = lines.iter().find(|l| l["subtype"] == "init").expect("the recorded init line"); + assert_eq!(init["model"], "claude-haiku-4-5"); + assert_eq!(models_said(&lines), ["claude-haiku-4-5-20251001"]); + let mut norm = ClaudeNormalizer::new(&spec(Role::Solo, false), "sess-1".into()); + let mut events = norm.turn_started("Reply with the single word: pong"); + events.extend(replay(&mut norm, &lines)); + assert!(events.iter().any(|e| matches!(e, EventKind::TurnCompleted { status: TurnStatus::Completed, .. })), "{events:?}"); + assert!(!events.iter().any(|e| matches!(e, EventKind::Notice { .. })), "{events:?}"); + assert!(same_model("claude-haiku-4-5", "claude-haiku-4-5-20251001") && !same_model("claude-haiku-4-5-20251001", "claude-haiku-5-5")); + for name in ["r5-model-start-alias", "r5-model-start-full", "r5-model-start-dated"] { + let lines = recorded(name); + let init = lines.iter().find(|l| l["subtype"] == "init").expect("the recorded init line"); + assert_eq!(models_said(&lines), [init["model"].as_str().unwrap()], "{name}"); + } + } + /// Plan mode on a session started as Codly starts a 1:1 agent (part 2, scenarios 10 and /// 11). Before, a plan could only be accepted as it was or sent back, and nothing said that /// the plan was made by another model than the session's. @@ -5384,8 +6038,10 @@ mod tests { assert_eq!(notices, ["Claude Code now runs on claude-sonnet-5-5, not on claude-haiku-5-5", "Claude Code runs on claude-haiku-5-5 again"]); // A mark for the context window is no other model. assert!(same_model("claude-fable-5-1[1m]", "claude-fable-5-1") && !same_model("claude-sonnet-5-5", "claude-haiku-5-5")); - // Nor is another spelling of one model (not recorded: names in the style of a cloud - // provider's ids, and a short name with its dated id). No line says the model changed. + // Nor is another spelling of one model: names in the style of a cloud provider's ids + // (not recorded), and a short name with its dated id (recorded for Anthropic's own + // API: `an_undated_model_name_and_its_dated_id_are_one_model`). No line says the + // model changed. let (cloud, plain) = ("us.anthropic.claude-sonnet-5-5-20261001-v1:0", "claude-sonnet-5-5-20261001"); assert!(same_model(cloud, plain) && same_model(plain, cloud) && same_model("claude-sonnet-5-5", plain)); assert!(!same_model(cloud, "claude-haiku-5-5-20261001")); @@ -5475,4 +6131,802 @@ mod tests { let ev = norm.on_message(&json!({ "type": "user", "message": { "role": "user", "content": "x" } })); assert!(matches!(&ev[..], [EventKind::Unknown { raw_type }] if raw_type == "user"), "{ev:?}"); } + + // ───── helpers and the stop, as part 4 of the 2.1.311 recordings has them (`r6-*`) ───── + + /// The subtypes of the control requests Codly wrote to the CLI so far, in order. + fn requests_sent(dir: &Path) -> Vec { + let log = std::fs::read_to_string(dir.join("raw.ndjson")).unwrap(); + log.lines().filter_map(|l| serde_json::from_str::(l).unwrap()["codly_sent"]["request"]["subtype"].as_str().map(str::to_owned)).collect() + } + + /// The ends of the subagent rows, one line each: " : ". + fn subagent_ends(events: &[EventKind]) -> Vec { + subagent_lines(events).into_iter().filter(|l| [" completed: ", " stopped: ", " failed: "].iter().any(|end| l.contains(end))).collect() + } + + /// Recordings `r6-shutdown-helper-sequence-1` and `-2` (part 4 §2, n=2; the first is + /// played here): a helper in the background and a turn that runs a command, then the + /// stop. The interrupt ends both: the helper's row ends as "stopped" and its list empties + /// before the turn's `result`, and stdin is closed right after that result. No `stop_task` + /// is written (the recorded driver's one after the result answered `{}` and changed + /// nothing; the process then exited with nothing left running). + #[tokio::test] + async fn a_stop_with_a_helper_and_a_turn_at_work_is_one_interrupt_as_recorded() { + let mut cli = Replay::of("r6-shutdown-helper-sequence-1"); + let mut kinds = cli.play(|l| l["_sent"]["request"]["subtype"] == "interrupt").await; + assert_eq!(turns(&kinds), ["start:Use", "end:Completed", "start:Run"]); + assert!(cli.actor.norm.helpers_in_background() && cli.actor.norm.commands_in_background().is_empty()); + + cli.in_place_of_the_drivers_request(AgentCmd::Shutdown).await; + assert_eq!(cli.actor.stage, Stage::Interrupting); + kinds.extend(cli.play(|l| l["type"] == "result").await); + assert_eq!(turns(&kinds), ["start:Use", "end:Completed", "start:Run", "end:Interrupted"]); + assert_eq!(subagent_ends(&kinds), ["toolu-1 stopped: Run delayed echo command"]); + assert_eq!(background_lines(&kinds).last().map(String::as_str), Some("- | tid-1 helper stopped: Run delayed echo command")); + assert!(cli.actor.stage == Stage::Closing && cli.actor.stdin.is_none(), "{:?}", cli.actor.stage); + + let rest = cli.play(|_| false).await; + assert!(rest.is_empty(), "{rest:?}"); + assert_eq!(requests_sent(cli.dir.path()), ["interrupt"]); + } + + /// Recordings `r6-shutdown-helper-idle-interrupt-1` and `-2` (part 4 §2, n=2; the first + /// is played here): a helper in the background and NO turn running, then the stop. Before, + /// the stop closed stdin at once and left the helper to the later steps. Now the interrupt + /// comes first: the helper's row ends as "stopped", the list empties, no turn starts, and + /// stdin is closed when the list has no helper (the recorded process exited 0.53 s later). + #[tokio::test] + async fn a_stop_with_a_helper_and_no_turn_interrupts_first_as_recorded() { + let mut cli = Replay::of("r6-shutdown-helper-idle-interrupt-1"); + let kinds = cli.play(|l| l["_sent"]["request"]["subtype"] == "interrupt").await; + assert_eq!(turns(&kinds), ["start:Use", "end:Completed"]); + assert!(!cli.actor.turn_active && cli.actor.norm.helpers_in_background()); + + cli.in_place_of_the_drivers_request(AgentCmd::Shutdown).await; + assert!(cli.actor.stage == Stage::StoppingHelpers && cli.actor.stdin.is_some() && cli.actor.deadline.is_some(), "{:?}", cli.actor.stage); + let kinds = cli.play(|l| l["subtype"] == "background_tasks_changed").await; + assert_eq!(subagent_ends(&kinds), ["toolu-1 stopped: Run echo begin/sleep/end"]); + assert_eq!(background_lines(&kinds), ["- | tid-1 helper stopped: Run echo begin/sleep/end"]); + assert!(turns(&kinds).is_empty(), "no turn: {kinds:?}"); + assert!(cli.actor.stage == Stage::Closing && cli.actor.stdin.is_none(), "{:?}", cli.actor.stage); + + let rest = cli.play(|_| false).await; + assert!(rest.is_empty(), "{rest:?}"); + assert_eq!(requests_sent(cli.dir.path()), ["interrupt"], "the helper gets no `stop_task`"); + } + + /// Recordings `r6-interrupt-helper-*-1` (part 4 §1; with the `-2` runs n=2 each, and each + /// has ONE helper in the middle of a Bash call). An interrupt ends every helper: one whose + /// `Agent` call still waits (`foreground`), one in the background while another turn runs + /// (`background`) and one in the background with no turn running (`idle`). Each helper row + /// ends once, as "stopped", the list empties, and no turn starts by itself. The + /// `task_notification` of a Bash call that had become a task (its own task id, an empty + /// `output_file`) ends nothing. Before, the foreground helper ended twice: "failed" at the + /// rejected `Agent` call, then "stopped". + #[tokio::test] + async fn an_interrupt_ends_every_helper_once_as_recorded() { + let cases = [ + ("r6-interrupt-helper-foreground-1", "Run timed echo/sleep command", vec!["start:Use", "end:Interrupted", "start:Reply", "end:Completed"]), + ("r6-interrupt-helper-background-1", "Run delayed echo command", vec!["start:Use", "end:Completed", "start:Run", "end:Interrupted", "start:Reply", "end:Completed"]), + ("r6-interrupt-helper-idle-1", "Run sleep echo test", vec!["start:Use", "end:Completed", "start:Reply", "end:Completed"]), + ]; + for (name, helper, turns_said) in cases { + let lines = recorded(name); + let bash_task = |l: &Value| l["subtype"] == "task_notification" && l["output_file"] == "" && l["task_id"] == "tid-2"; + assert!(lines.iter().any(bash_task), "{name}: the helper's own Bash call is a task, and its end is said"); + + let mut cli = Replay::of(name); + let mut kinds = cli.play(|l| l["_sent"]["request"]["subtype"] == "interrupt").await; + cli.in_place_of_the_drivers_request(AgentCmd::Interrupt).await; + kinds.extend(cli.play(|_| false).await); + assert_eq!(turns(&kinds), turns_said, "{name}"); + assert_eq!(subagent_ends(&kinds), [format!("toolu-1 stopped: {helper}")], "{name}"); + let listed = background_lines(&kinds); + if name.ends_with("foreground-1") { + assert!(listed.is_empty(), "a helper the agent waits for is in no list: {listed:?}"); + } else { + assert_eq!(listed, [format!("tid-1 helper: {helper} | -"), format!("- | tid-1 helper stopped: {helper}")], "{name}"); + } + assert!(cli.actor.norm.background.is_empty() && cli.actor.norm.helpers.is_empty(), "{name}: nothing is left open"); + assert!(!kinds.iter().any(|k| matches!(k, EventKind::Unknown { .. })), "{name}: {kinds:?}"); + assert_eq!(cli.actor.stage, Stage::Running, "{name}"); + } + } + + /// Recordings `r6-fails-helper-background` and `-foreground` (part 4 §3, n=1 each): a + /// helper whose model request is refused. Its row ends as "failed", with the reason of its + /// `task_updated` line as its report; the background one leaves the list as "failed" too. + /// Recording `r6-fails-signal-term` (n=1): a background command whose shell got SIGTERM + /// leaves the list as "failed" (there is no word for a signal). + #[test] + fn a_helper_that_fails_says_why_and_a_killed_command_ends_as_failed_as_recorded() { + for (name, helper) in [("r6-fails-helper-background", "Run echo hi"), ("r6-fails-helper-foreground", "Run echo hi via no-model")] { + let lines = recorded(name); + let updated = lines.iter().find(|l| l["subtype"] == "task_updated").expect("the recorded task_updated line"); + assert_eq!(updated["patch"]["status"], "failed", "{name}"); + let error = updated["patch"]["error"].as_str().expect("its reason"); + assert!(error.starts_with("Agent terminated early due to an API error"), "{error}"); + + let mut norm = ClaudeNormalizer::new(&spec(Role::Worker, false), "sess-1".into()); + let mut events = norm.turn_started("go"); + events.extend(replay(&mut norm, &lines)); + let reported: Vec<&str> = events.iter().filter_map(|e| if let EventKind::SubAgentProgress { report: Some(r), .. } = e { Some(r.as_str()) } else { None }).collect(); + assert_eq!(reported, [error], "{name}"); + assert_eq!(subagent_ends(&events), [format!("toolu-1 failed: {helper}")], "{name}: once, the tool result after it adds nothing"); + if name.ends_with("background") { + assert_eq!(background_lines(&events), [format!("tid-1 helper: {helper} | -"), format!("- | tid-1 helper failed: {helper}")]); + } else { + assert!(background_lines(&events).is_empty()); + } + assert!(!events.iter().any(|e| matches!(e, EventKind::Unknown { .. })), "{name}: {events:?}"); + } + + // In both recordings the `summary` of the `task_notification` repeats the error, so they + // alone do not show where the report comes from. Written lines in the recorded shape + // (`r6-fails-helper-foreground` lines 21, 27, 28) with a `summary` that is the helper's + // description, then with none: the report is still the error of `task_updated`. + let description = "Run echo hi via no-model"; + let error = "Agent terminated early due to an API error: the model was not found"; + for summary in [json!(description), Value::Null] { + let lines = [ + json!({ "type": "system", "subtype": "task_started", "task_id": "tid-1", "tool_use_id": "toolu-1", "description": description, "subagent_type": "no-model", "is_backgrounded": false, "task_type": "local_agent" }), + json!({ "type": "system", "subtype": "task_updated", "task_id": "tid-1", "patch": { "status": "failed", "error": error } }), + json!({ "type": "system", "subtype": "task_notification", "task_id": "tid-1", "tool_use_id": "toolu-1", "status": "failed", "summary": summary }), + ]; + let mut norm = ClaudeNormalizer::new(&spec(Role::Worker, false), "sess-1".into()); + let mut events = norm.turn_started("go"); + events.extend(replay(&mut norm, &lines)); + let reported: Vec<&str> = events.iter().filter_map(|e| if let EventKind::SubAgentProgress { report: Some(r), .. } = e { Some(r.as_str()) } else { None }).collect(); + assert_eq!(reported, [error], "summary {summary}"); + assert_eq!(subagent_ends(&events), [format!("toolu-1 failed: {description}")], "summary {summary}"); + } + + let mut norm = ClaudeNormalizer::new(&spec(Role::Worker, false), "sess-1".into()); + let mut events = norm.turn_started("go"); + events.extend(replay(&mut norm, &recorded("r6-fails-signal-term"))); + let command = "Run delayed echo sequence in background"; + assert_eq!(background_lines(&events), [format!("tid-1 command: {command} | -"), format!("- | tid-1 command failed: {command}")]); + assert!(subagent_lines(&events).is_empty(), "a command is no helper"); + } + + /// Recording `r6-shutdown-helper-foreground-stop-1` (part 4 §2, n=2 with `-2`): "Stop" on + /// a helper whose `Agent` call still waits. Codly gets the helper by the id of its call + /// (the id its row has) and sends its task id, as recorded. The helper's row ends as + /// "stopped", whoever asked gets its description with the CLI's answer, and the agent's + /// turn goes on to its own end. An id that is neither a listed task nor a helper at work + /// is refused, and nothing reaches the CLI. + #[tokio::test] + async fn a_helper_at_work_is_stopped_by_the_id_of_its_call_as_recorded() { + let mut cli = Replay::of("r6-shutdown-helper-foreground-stop-1"); + let mut kinds = cli.play(|l| l["_sent"]["request"]["subtype"] == "stop_task").await; + assert_eq!(turns(&kinds), ["start:Use"]); + assert!(background_lines(&kinds).is_empty(), "a helper the agent waits for is in no list"); + + // An id that names nothing running: refused, and nothing is written. + let before = requests_sent(cli.dir.path()); + for unknown in ["toolu-9", "tid-9", "toolu-2"] { + let (reply, mut answer) = mpsc::unbounded_channel(); + cli.actor.on_cmd(AgentCmd::Session { request: SessionRequest::StopTask(unknown.into()), reply }).await; + let refused = answer.try_recv().expect("an answer at once").unwrap_err(); + assert_eq!(refused, NOT_RUNNING, "{unknown}"); + } + assert_eq!(requests_sent(cli.dir.path()), before); + + let (reply, mut answer) = mpsc::unbounded_channel(); + cli.in_place_of_the_drivers_request(AgentCmd::Session { request: SessionRequest::StopTask("toolu-1".into()), reply }).await; + kinds.extend(cli.play(|l| l["type"] == "result").await); + assert_eq!(answer.try_recv().expect("the CLI's answer reaches whoever asked"), Ok(json!({ "helper": "Run sleep echo command" }))); + assert_eq!(subagent_ends(&kinds), ["toolu-1 stopped: Run sleep echo command"]); + assert!(kinds.iter().any(|k| matches!(k, EventKind::ToolCompleted { call_id, ok: false, .. } if call_id == "toolu-1")), "the Agent call returns an error"); + assert_eq!(turns(&kinds), ["start:Use", "end:Completed"], "the turn went on to its own end"); + // Once it ended, its call id names nothing any more. + let (reply, mut answer) = mpsc::unbounded_channel(); + cli.actor.on_cmd(AgentCmd::Session { request: SessionRequest::StopTask("toolu-1".into()), reply }).await; + assert!(answer.try_recv().unwrap().is_err()); + } + + /// Recording `r6-effort-null-first-fresh` (part 4 §4, n=2 with `-after-turn`): a process + /// started with `--effort high`, and `effortLevel: null` as the first such request. It goes + /// out as recorded, and the settings then say "medium": the level is taken away with no + /// restart. + #[tokio::test] + async fn an_effort_is_taken_away_as_recorded() { + let dir = tempfile::tempdir().unwrap(); + let (mut actor, mut events, _child) = silent_actor(dir.path()); + let lines = recording("r6-effort-null-first-fresh"); + let dir = dir.path(); + let set = ask_in_place_of(&mut actor, dir, &lines, SessionRequest::Effort(None), "host-3").await; + assert_eq!(set, Ok(Value::Null), "a bare success"); + assert_eq!(last_sent(dir)["request"], json!({ "subtype": "apply_flag_settings", "settings": { "effortLevel": null } })); + let settings = ask_in_place_of(&mut actor, dir, &lines, SessionRequest::Settings, "host-4").await.unwrap(); + assert_eq!(settings["applied"]["effort"], "medium"); + assert!(emitted(&mut events).is_empty() && actor.session_replies.is_empty()); + } + + /// Recording `r6-model-while-streaming-1` (part 4 §5, n=2 with `-2`): `set_model sonnet` + /// while an answer on haiku is written, a turn on sonnet, then `set_model haiku` and a turn + /// on it. The rest of the first answer stays on haiku. Each switch is Codly's own: no row + /// says that Claude Code "runs on" another model. + #[tokio::test] + async fn a_model_switch_while_an_answer_is_written_makes_no_rows_about_the_model_as_recorded() { + let mut cli = Replay::of("r6-model-while-streaming-1"); + let lines = recording("r6-model-while-streaming-1"); + assert_eq!(models_said(&lines), ["claude-haiku-5-5", "claude-sonnet-5-5", "claude-haiku-5-5"]); + let mut kinds = Vec::new(); + for (model, resolved) in [("sonnet", "claude-sonnet-5-5"), ("haiku", "claude-haiku-5-5")] { + kinds.extend(cli.play(|l| l["_sent"]["request"]["subtype"] == "set_model").await); + let (reply, mut answer) = mpsc::unbounded_channel(); + cli.in_place_of_the_drivers_request(AgentCmd::Session { request: SessionRequest::Model(model.into()), reply }).await; + kinds.extend(cli.play(|l| l["type"] == "control_response").await); + assert_eq!(answer.try_recv().expect("the CLI's answer reaches whoever asked"), Ok(json!({ "model": resolved })), "{model}"); + } + kinds.extend(cli.play(|_| false).await); + assert_eq!(turns(&kinds), ["start:Write", "end:Completed", "start:Reply", "end:Completed", "start:Reply", "end:Completed"]); + let notices: Vec<&str> = kinds.iter().filter_map(|k| if let EventKind::Notice { text } = k { Some(text.as_str()) } else { None }).collect(); + assert_eq!(notices, Vec::<&str>::new()); + assert!(!kinds.iter().any(|k| matches!(k, EventKind::Unknown { .. })), "{kinds:?}"); + } + + /// A background task starts with the first list that names it: every later list that + /// names it carries that time, so a row read again from a later list still has its timer. + /// (Lists written here, in the recorded shape.) + #[test] + fn a_background_task_keeps_the_time_of_the_first_list_that_named_it() { + let mut norm = ClaudeNormalizer::new(&spec(Role::Worker, false), "sess-1".into()); + let task = |id: &str| json!({ "task_id": id, "task_type": "local_bash", "description": "npm run dev" }); + let starts = |events: Vec| -> Vec<(String, Option)> { + let Some(EventKind::BackgroundTasks { tasks, .. }) = events.into_iter().find(|e| matches!(e, EventKind::BackgroundTasks { .. })) else { panic!("a list event") }; + tasks.into_iter().map(|t| (t.id, t.started_at)).collect() + }; + let before = now_ms(); + let first = starts(norm.on_message(&list_line(json!([task("tid-1")])))); + let started = first[0].1.expect("a start time"); + assert!(started >= before); + std::thread::sleep(Duration::from_millis(5)); + let second = starts(norm.on_message(&list_line(json!([task("tid-1"), task("tid-2")])))); + assert_eq!(second[0], ("tid-1".to_string(), Some(started)), "one start time for one task"); + assert!(second[1].1.is_some_and(|t| t > started), "{second:?}"); + // Gone, then named again: that is work that starts anew. + starts(norm.on_message(&list_line(json!([])))); + std::thread::sleep(Duration::from_millis(5)); + let again = starts(norm.on_message(&list_line(json!([task("tid-1")])))); + assert!(again[0].1.is_some_and(|t| t > started), "{again:?}"); + } + + // ───── part 5 of the 2.1.311 recordings (`r7-*`) ───── + + /// Recordings `r7-shutdown-helper-and-command-1` and `-2` (part 5 §5, n=2; the first is + /// played here): a helper AND a command in the background, no turn running, then the stop. + /// The interrupt ends the helper (its row ends as "stopped") and the list still names the + /// command: its `stop_task` goes out at once, stdin is closed when the list is empty, and + /// the recorded process exits 0.70 s later with nothing left in its group. Before, the + /// comment said this was not recorded as one run. + #[tokio::test] + async fn a_stop_with_a_helper_and_a_command_and_no_turn_is_interrupt_then_stop_task_as_recorded() { + let mut cli = Replay::of("r7-shutdown-helper-and-command-1"); + let kinds = cli.play(|l| l["_sent"]["request"]["subtype"] == "interrupt").await; + assert_eq!(turns(&kinds), ["start:Do", "end:Completed"]); + assert!(!cli.actor.turn_active && cli.actor.norm.helpers_in_background()); + assert_eq!(cli.actor.norm.commands_in_background(), ["tid-2"]); + + cli.in_place_of_the_drivers_request(AgentCmd::Shutdown).await; + assert_eq!(cli.actor.stage, Stage::StoppingHelpers); + let kinds = cli.play(|l| l["_sent"]["request"]["subtype"] == "stop_task").await; + assert_eq!(subagent_ends(&kinds), ["toolu-2 stopped: Run background sleep 199 command"]); + assert_eq!(background_lines(&kinds), ["tid-2 command: Run background echo and sleep 197 | tid-1 helper stopped: Run background sleep 199 command"]); + assert!(turns(&kinds).is_empty(), "no turn: {kinds:?}"); + // Codly wrote the driver's `stop_task` as soon as the list had no helper. + let recorded = cli.drivers_request.take().expect("the driver's stop_task"); + assert_eq!(last_sent(cli.dir.path())["request"], recorded["request"]); + assert_eq!(cli.actor.stage, Stage::StoppingTasks); + + // The command's end, then the helper's rejected call: not shown as this agent's work. + let rest = cli.play(|_| false).await; + assert!(rest.is_empty(), "{rest:?}"); + assert!(cli.actor.norm.background.is_empty(), "the CLI's last list is empty"); + assert!(cli.actor.stage == Stage::Closing && cli.actor.stdin.is_none(), "{:?}", cli.actor.stage); + assert_eq!(requests_sent(cli.dir.path()), ["interrupt", "stop_task"]); + } + + /// The stop of an idle agent whose helper does not leave the list: its background command + /// is stopped 1 s after the interrupt, not 5, so the interrupt and the stop of the commands + /// end before the app gives up on the process at exit (4 s, `RUNS_GRACE` in workspace.rs). + /// Before, the command's stop waited 5 s behind the helper, the app killed the process + /// group first, and the command ran on. (The list is written here in the shape of + /// `r7-shutdown-helper-and-command-1`; no recorded helper ignored the interrupt. The + /// deadline is read, not waited for: tokio's paused clock is not among the workspace's + /// features.) + #[tokio::test] + async fn an_idle_agents_commands_are_stopped_one_second_after_the_interrupt() { + let dir = tempfile::tempdir().unwrap(); + let (mut actor, _events, _child) = silent_actor(dir.path()); + let listed = list_line(json!([ + { "task_id": "tid-1", "run_id": "run-1", "task_type": "local_agent", "subagent_type": "general-purpose", "description": "Run background sleep 199 command" }, + { "task_id": "tid-2", "run_id": "run-2", "task_type": "local_bash", "description": "npm run dev" }, + ])); + actor.on_json(listed, "codly-0", &mut None).await; + let before = tokio::time::Instant::now(); + actor.on_cmd(AgentCmd::Shutdown).await; + let after = tokio::time::Instant::now(); + assert_eq!((interrupts_sent(dir.path()), actor.stage), (1, Stage::StoppingHelpers)); + let deadline = actor.deadline.expect("the helpers' wait has an end"); + assert!(before + STOP_HELPERS_TIMEOUT <= deadline && deadline <= after + STOP_HELPERS_TIMEOUT, "1 s"); + + // The helper is still listed at that deadline: the command's stop goes out. + actor.on_deadline().await; + assert_eq!(requests_sent(dir.path()), ["interrupt", "stop_task"]); + assert_eq!(last_sent(dir.path())["request"], json!({ "subtype": "stop_task", "task_id": "tid-2" })); + assert_eq!(actor.stage, Stage::StoppingTasks); + let deadline = actor.deadline.expect("the commands' wait has an end"); + assert!(deadline <= tokio::time::Instant::now() + STOP_TASKS_TIMEOUT); + assert_eq!((STOP_HELPERS_TIMEOUT + STOP_TASKS_TIMEOUT).as_secs(), 3, "inside the app's wait at exit (4 s)"); + } + + /// Recordings `r7-failed-turn-helper-1` and `-2` (part 5 §3, n=2; the first is played + /// here): a helper in the background, then a turn that fails by the turn limit. The failed + /// turn ends no helper: its row and its list entry stay through it, its own Bash call + /// completes after it, and the helper ends "completed" at its own line. Then the CLI starts + /// a turn by itself, which is a turn of the run. + #[tokio::test] + async fn a_turn_that_fails_by_a_limit_ends_no_background_helper_as_recorded() { + let mut cli = Replay::of("r7-failed-turn-helper-1"); + let mut kinds = cli.play(|l| l["type"] == "result" && l["subtype"] == "error_max_turns").await; + assert_eq!(turns(&kinds), ["start:Use", "end:Completed", "start:Run", "end:MaxTurns"]); + assert!(subagent_ends(&kinds).is_empty(), "{kinds:?}"); + assert!(cli.actor.norm.helpers.get("toolu-1").is_some_and(|h| h.background && !h.done), "the helper still works"); + assert!(cli.actor.norm.helpers_in_background()); + + kinds.extend(cli.play(|_| false).await); + assert_eq!(turns(&kinds), ["start:Use", "end:Completed", "start:Run", "end:MaxTurns", "start", "end:Completed"]); + assert_eq!(subagent_ends(&kinds), ["toolu-1 completed: Run delayed echo command"]); + assert_eq!(background_lines(&kinds), ["tid-1 helper: Run delayed echo command | -", "- | tid-1 helper completed: Run delayed echo command"]); + let own_call = kinds.iter().filter(|k| matches!(k, EventKind::ToolCompleted { call_id, ok: true, .. } if call_id == "toolu-2")).count(); + assert_eq!(own_call, 1, "the helper's own Bash call completes once, after the failed turn"); + assert!(!kinds.iter().any(|k| matches!(k, EventKind::Unknown { .. })), "{kinds:?}"); + assert!(cli.actor.norm.helpers.is_empty() && cli.actor.norm.background.is_empty()); + } + + /// Recordings `r7-interrupt-two-helpers-1` and `r7-interrupt-helper-model-1` (part 5 §4; + /// with the `-2` runs n=2 each): an interrupt with no turn running ends TWO background + /// helpers, each in the middle of a Bash call, and one helper that waits for its model + /// answer. Each row ends once, as "stopped", the list empties, and no turn starts by + /// itself: the next turn is the next message's. + #[tokio::test] + async fn an_interrupt_ends_two_helpers_and_one_that_waits_for_its_model_as_recorded() { + let cases = [ + ( + "r7-interrupt-two-helpers-1", + vec!["toolu-1 stopped: Run echo a sleep 181 command", "toolu-2 stopped: Run echo b sleep 191 command"], + vec![ + "tid-2 helper: Run echo b sleep 191 command | tid-1 helper stopped: Run echo a sleep 181 command", + "- | tid-2 helper stopped: Run echo b sleep 191 command", + ], + ), + ("r7-interrupt-helper-model-1", vec!["toolu-1 stopped: Write lighthouse keeper story"], vec!["- | tid-1 helper stopped: Write lighthouse keeper story"]), + ]; + for (name, ends, listed) in cases { + let mut cli = Replay::of(name); + let mut kinds = cli.play(|l| l["_sent"]["request"]["subtype"] == "interrupt").await; + assert!(subagent_ends(&kinds).is_empty(), "{name}"); + assert!(!cli.actor.turn_active, "{name}: no turn runs"); + cli.in_place_of_the_drivers_request(AgentCmd::Interrupt).await; + let after = cli.play(|l| l["type"] == "control_response").await; + assert_eq!(subagent_ends(&after), ends, "{name}: each before the interrupt's answer"); + assert_eq!(background_lines(&after), listed, "{name}"); + kinds.extend(after); + kinds.extend(cli.play(|_| false).await); + assert_eq!(subagent_ends(&kinds), ends, "{name}: once each"); + assert_eq!(turns(&kinds), ["start:Use", "end:Completed", "start:Reply", "end:Completed"], "{name}"); + assert!(cli.actor.norm.background.is_empty() && cli.actor.norm.helpers.is_empty(), "{name}: nothing is left open"); + assert!(!kinds.iter().any(|k| matches!(k, EventKind::Unknown { .. })), "{name}: {kinds:?}"); + assert_eq!(cli.actor.stage, Stage::Running, "{name}"); + } + } + + /// Recording `r7-bash-becomes-task-1` (part 5 §12, n=2 per duration with `-2`): foreground + /// Bash calls of 1 to 14 s. Each call of 3 s or more becomes a task about 3 s after it + /// starts, and its end by itself is one `task_notification` "completed" with an empty + /// `output_file`. Those lines start and end no helper row and no background row: each call + /// completes once, by its own result. + #[tokio::test] + async fn a_command_the_agent_waits_for_that_becomes_a_task_ends_nothing_as_recorded() { + let lines = recorded("r7-bash-becomes-task-1"); + let ends = lines.iter().filter(|l| l["subtype"] == "task_notification" && l["status"] == "completed" && l["output_file"] == "").count(); + assert_eq!(ends, 5, "the calls of 3, 4, 6, 9 and 14 s"); + let mut cli = Replay::of("r7-bash-becomes-task-1"); + let kinds = cli.play(|_| false).await; + assert_eq!(turns(&kinds), ["start:Run", "end:Completed"].repeat(7)); + assert!(subagent_lines(&kinds).is_empty(), "{kinds:?}"); + assert!(background_lines(&kinds).is_empty(), "{kinds:?}"); + for n in 1..=7 { + let call = format!("toolu-{n}"); + let completed = kinds.iter().filter(|k| matches!(k, EventKind::ToolCompleted { call_id, ok: true, .. } if *call_id == call)).count(); + assert_eq!(completed, 1, "{call}"); + } + assert!(!kinds.iter().any(|k| matches!(k, EventKind::Unknown { .. })), "{kinds:?}"); + assert!(cli.actor.norm.background.is_empty() && cli.actor.norm.helpers.is_empty()); + } + + /// Recording `r7-budget-during-call-1-t1` (part 5 §10, n=2 with `-2-t1`): the run's own + /// limit is passed by a helper's request while the turn's Bash call (`sleep 61.5`) runs. + /// The helper ends "completed" first; the turn fails with the run's own reason, which is + /// the text Codly knows such a turn by (`is_run_limit_reached`, which + /// `breaker_run.rs::run_limit_words` asks); the call gets no result and is in no list (it + /// runs on until stdin is closed, as the end of the run does); the turn the CLI starts by + /// itself and the next message fail the same way. + #[test] + fn a_limit_passed_during_a_long_call_fails_the_turn_with_the_runs_own_reason_as_recorded() { + let limited = SpawnSpec { max_budget_usd: Some(0.01), ..spec(Role::Solo, false) }; + let mut norm = ClaudeNormalizer::new(&limited, "sess-1".into()); + let mut events = norm.turn_started("Do these steps in order"); + events.extend(replay(&mut norm, &recorded("r7-budget-during-call-1-t1"))); + let reason = run_limit_reached("Ada", 0.01); + assert_eq!(turn_ends(&events), [(TurnStatus::Failed, Some(reason.as_str())); 3]); + // What the adapter made of the recorded `result` lines is what Codly ends the run by. + let said: Vec<&str> = errors(&events).into_iter().map(|(message, _)| message).filter(|m| is_run_limit_reached(m, "Ada", 0.01)).collect(); + assert!(!said.is_empty(), "{events:?}"); + for (_, ended) in turn_ends(&events) { + let ended = ended.expect("a failed turn says why"); + assert!(is_run_limit_reached(ended, "Ada", 0.01), "{ended}"); + assert!(!is_run_limit_reached(ended, "Ada", 0.02) && !is_run_limit_reached(ended, "Bob", 0.01), "the words name this run and its limit"); + } + assert!(!is_run_limit_reached("Claude Code reached its spending limit, so it does no more work in this run", "Ada", 0.01)); + + let helper_end = events.iter().position(|e| matches!(e, EventKind::SubAgent { status, .. } if status == "completed")).expect("the helper's end"); + let first_end = events.iter().position(|e| matches!(e, EventKind::TurnCompleted { .. })).unwrap(); + assert!(helper_end < first_end, "the helper had completed before the stop"); + assert!(!events.iter().any(|e| matches!(e, EventKind::ToolCompleted { call_id, .. } if call_id == "toolu-2")), "the cut-off call has no result"); + let helper = "Write lighthouse keeper story"; + assert_eq!(background_lines(&events), [format!("tid-1 helper: {helper} | -"), format!("- | tid-1 helper completed: {helper}")], "the call is in no list"); + assert!(!events.iter().any(|e| matches!(e, EventKind::Unknown { .. })), "{events:?}"); + } + + // ───── part 6 of the 2.1.311 recordings (`r8-*`) ───── + + /// The cost the adapter last reported for the run. + fn last_cost(events: &[EventKind]) -> f64 { + events.iter().rev().find_map(|e| if let EventKind::UsageUpdated { usage } = e { usage.cost_usd } else { None }).expect("a usage event") + } + + /// What a `result` line says the turn's own model requests cost. + fn own_cost(result: &Value) -> f64 { + result["model_usage_since_last_result"].as_object().into_iter().flat_map(|m| m.values()).filter_map(|m| m["costUSD"].as_f64()).sum() + } + + /// Recordings `r8-bash-task-fails-1` and `-2` (part 6 §7, n=2): a command the agent waits + /// for becomes a task and fails by itself (exit code 3: "failed"), and one is cut by an + /// interrupt ("stopped"). Each `task_notification` has an empty `output_file`, and ends no + /// helper row and no background row: each call ends once, by its own result. + #[test] + fn a_command_the_agent_waits_for_that_fails_or_is_interrupted_ends_nothing_as_recorded() { + for name in ["r8-bash-task-fails-1", "r8-bash-task-fails-2"] { + let lines = recorded(name); + let ends: Vec<&Value> = lines.iter().filter(|l| l["subtype"] == "task_notification").collect(); + assert_eq!(ends.iter().map(|l| l["status"].as_str().unwrap()).collect::>(), ["failed", "stopped"], "{name}"); + assert!(ends.iter().all(|l| l["output_file"] == ""), "{name}"); + let calls: Vec<&str> = ends.iter().map(|l| l["tool_use_id"].as_str().unwrap()).collect(); + + let mut norm = ClaudeNormalizer::new(&spec(Role::Solo, false), "sess-1".into()); + let events = replay(&mut norm, &lines); + assert!(subagent_lines(&events).is_empty(), "{name}: {events:?}"); + assert!(background_lines(&events).is_empty(), "{name}: {events:?}"); + let completed: Vec<(&str, bool, Option)> = events + .iter() + .filter_map(|e| if let EventKind::ToolCompleted { call_id, ok, exit_code, .. } = e { Some((call_id.as_str(), *ok, *exit_code)) } else { None }) + .collect(); + assert_eq!(completed, [(calls[0], false, Some(3)), (calls[1], false, None)], "{name}: once each, by the call's own result"); + assert_eq!(turn_ends(&events).iter().map(|t| t.0).collect::>(), [TurnStatus::Completed, TurnStatus::Interrupted], "{name}"); + assert!(!events.iter().any(|e| matches!(e, EventKind::Unknown { .. })), "{name}: {events:?}"); + assert!(norm.background.is_empty() && norm.helpers.is_empty(), "{name}"); + } + } + + /// Recordings `r8-shutdown-all-1` and `-2` (part 6 §11, n=2): the stop of an agent with a + /// turn running, a helper and a command in the background at once. The interrupt ends the + /// helper (its row ends as "stopped") and the turn, and the list still names the command; + /// `stop_task` for the command goes out right after the turn's `result`, as the driver + /// sent it; stdin is closed when the list is empty. The recorded process exited 0.73 s + /// later with nothing left in its group. + #[tokio::test] + async fn a_stop_with_a_turn_a_helper_and_a_command_at_once_ends_each_as_recorded() { + for name in ["r8-shutdown-all-1", "r8-shutdown-all-2"] { + let mut cli = Replay::of(name); + let kinds = cli.play(|l| l["_sent"]["request"]["subtype"] == "interrupt").await; + assert_eq!(turns(&kinds), ["start:Do", "end:Completed", "start:Run"], "{name}"); + assert!(cli.actor.turn_active && cli.actor.norm.helpers_in_background(), "{name}"); + assert_eq!(cli.actor.norm.commands_in_background(), ["tid-2"], "{name}"); + + // 1. The interrupt: the helper and the turn end, the command stays listed. + cli.in_place_of_the_drivers_request(AgentCmd::Shutdown).await; + assert_eq!(cli.actor.stage, Stage::Interrupting, "{name}"); + let kinds = cli.play(|l| l["type"] == "result").await; + assert_eq!(turns(&kinds), ["end:Interrupted"], "{name}"); + let ends = subagent_ends(&kinds); + assert!(ends.len() == 1 && ends[0].starts_with("toolu-2 stopped: "), "{name}: {ends:?}"); + let listed = background_lines(&kinds); + assert!(listed.len() == 1 && listed[0].starts_with("tid-2 command: ") && listed[0].contains(" | tid-1 helper stopped: "), "{name}: {listed:?}"); + + // 2. `stop_task` for the command, written with no wait after that result. + assert_eq!(last_sent(cli.dir.path())["request"], json!({ "subtype": "stop_task", "task_id": "tid-2" }), "{name}"); + assert!(cli.actor.stage == Stage::StoppingTasks && cli.actor.stdin.is_some(), "{name}: {:?}", cli.actor.stage); + let kinds = cli.play(|l| l["_sent"]["request"]["subtype"] == "stop_task").await; + assert!(kinds.is_empty(), "{name}: {kinds:?}"); + let recorded = cli.drivers_request.take().expect("the driver's stop_task"); + assert_eq!(recorded["request"], last_sent(cli.dir.path())["request"], "{name}: the request the driver sent"); + + // 3. The command's end and the empty list: not shown as this agent's work; stdin closes. + let rest = cli.play(|_| false).await; + assert!(rest.is_empty(), "{name}: {rest:?}"); + assert!(cli.actor.stage == Stage::Closing && cli.actor.stdin.is_none(), "{name}: {:?}", cli.actor.stage); + assert_eq!(requests_sent(cli.dir.path()), ["interrupt", "stop_task"], "{name}"); + assert!(cli.actor.norm.background.is_empty() && cli.actor.norm.helpers.is_empty(), "{name}: nothing is left"); + } + } + + /// Recordings `r8-stop-helper-last-request-1` and `-2` (part 6 §5, n=2): "Stop" on a + /// background helper while the turn makes its last model request. The helper's row ends as + /// "stopped", the turn ends as it would, and then the CLI starts a turn by itself to tell + /// the model: a turn with no prompt, which takes none of Codly's. + #[tokio::test] + async fn a_helper_stopped_in_the_last_request_of_a_turn_wakes_a_turn_of_its_own_as_recorded() { + for name in ["r8-stop-helper-last-request-1", "r8-stop-helper-last-request-2"] { + let mut cli = Replay::of(name); + let mut kinds = cli.play(|l| l["_sent"]["request"]["subtype"] == "stop_task").await; + assert_eq!(turns(&kinds), ["start:Use", "end:Completed", "start:Write"], "{name}"); + let task = cli.drivers_request.as_ref().unwrap()["request"]["task_id"].as_str().unwrap().to_string(); + let (reply, mut answer) = mpsc::unbounded_channel(); + cli.in_place_of_the_drivers_request(AgentCmd::Session { request: SessionRequest::StopTask(task), reply }).await; + kinds.extend(cli.play(|_| false).await); + assert_eq!(answer.try_recv().expect("the CLI's answer reaches whoever asked"), Ok(json!({})), "{name}"); + + assert_eq!(turns(&kinds), ["start:Use", "end:Completed", "start:Write", "end:Completed", "start", "end:Completed"], "{name}"); + let ends = subagent_ends(&kinds); + assert!(ends.len() == 1 && ends[0].starts_with("toolu-1 stopped: "), "{name}: {ends:?}"); + assert_eq!(cli.written().len(), 2, "{name}: the turn by itself took no prompt"); + assert!(cli.actor.waiting.is_empty() && cli.actor.queue.is_empty() && !cli.actor.turn_active, "{name}"); + assert!(cli.actor.norm.background.is_empty() && cli.actor.norm.helpers.is_empty(), "{name}"); + assert!(!kinds.iter().any(|k| matches!(k, EventKind::Unknown { .. })), "{name}: {kinds:?}"); + } + } + + /// Recordings `r8-stop-command-mid-turn-1`, `-3` and `-4` (part 6 §5, n=3): "Stop" on a + /// background command while a turn runs its own command. The command leaves the list as + /// "stopped", the turn's own call completes, and no turn follows. + #[tokio::test] + async fn a_command_stopped_while_a_turn_runs_wakes_no_turn_as_recorded() { + for name in ["r8-stop-command-mid-turn-1", "r8-stop-command-mid-turn-3", "r8-stop-command-mid-turn-4"] { + let mut cli = Replay::of(name); + let mut kinds = cli.play(|l| l["_sent"]["request"]["subtype"] == "stop_task").await; + assert_eq!(turns(&kinds), ["start:Run", "end:Completed", "start:Run"], "{name}"); + let task = cli.drivers_request.as_ref().unwrap()["request"]["task_id"].as_str().unwrap().to_string(); + assert_eq!(cli.actor.norm.commands_in_background(), [task.clone()], "{name}"); + let (reply, mut answer) = mpsc::unbounded_channel(); + cli.in_place_of_the_drivers_request(AgentCmd::Session { request: SessionRequest::StopTask(task.clone()), reply }).await; + kinds.extend(cli.play(|_| false).await); + assert_eq!(answer.try_recv().expect("the CLI's answer reaches whoever asked"), Ok(json!({})), "{name}"); + + assert_eq!(turns(&kinds), ["start:Run", "end:Completed", "start:Run", "end:Completed"], "{name}: no turn by itself"); + assert!(subagent_lines(&kinds).is_empty(), "{name}: {kinds:?}"); + let listed = background_lines(&kinds); + assert!(listed.last().is_some_and(|l| l.starts_with(&format!("- | {task} command stopped: "))), "{name}: {listed:?}"); + let own = kinds.iter().filter(|k| matches!(k, EventKind::ToolCompleted { call_id, ok: true, .. } if call_id == "toolu-2")).count(); + assert_eq!(own, 1, "{name}: the turn's own call ran to its end"); + assert!(cli.actor.norm.background.is_empty() && !cli.actor.turn_active, "{name}"); + assert!(!kinds.iter().any(|k| matches!(k, EventKind::Unknown { .. })), "{name}: {kinds:?}"); + } + } + + /// Recordings `r8-after-budget-*` (part 6 §6, n=2 per variant: an interrupt after the stop, + /// `stop_task` for the call that runs on, a helper with requests left). Every turn fails + /// with the run's own reason; the turn costs what its own requests cost (the turn the CLI + /// starts by itself after it costs nothing). After the last `result` the lines make no row: + /// the end of the call that ran on is in no list and has no result. Only a helper that was + /// still at work at the stop ends there, once, as "stopped" (n=1). + #[test] + fn after_a_budget_stop_later_lines_make_no_rows_and_the_turn_costs_its_own_as_recorded() { + let tries = [ + "r8-after-budget-interrupt-1-t2", + "r8-after-budget-interrupt-2-t2", + "r8-after-budget-stop-task-1-t1", + "r8-after-budget-stop-task-2-t2", + "r8-after-budget-helper-goes-on-1-t3", + "r8-after-budget-helper-goes-on-2-t2", + ]; + let limited = SpawnSpec { max_budget_usd: Some(0.001), ..spec(Role::Solo, false) }; + let reason = run_limit_reached("Ada", 0.001); + for name in tries { + let lines = recorded(name); + let results: Vec<&Value> = lines.iter().filter(|l| l["type"] == "result").collect(); + assert!(results.iter().all(|r| r["subtype"] == "error_max_budget_usd"), "{name}"); + let last = lines.iter().rposition(|l| l["type"] == "result").unwrap(); + + let mut norm = ClaudeNormalizer::new(&limited, "sess-1".into()); + let mut events = norm.turn_started("Do these steps in order"); + events.extend(replay(&mut norm, &lines[..=last])); + let ends = turn_ends(&events); + assert!(!ends.is_empty() && ends.iter().all(|end| *end == (TurnStatus::Failed, Some(reason.as_str()))), "{name}: {ends:?}"); + let own: f64 = results.iter().map(|r| own_cost(r)).sum(); + assert!((last_cost(&events) - own).abs() < 1e-12, "{name}: {} vs {own}", last_cost(&events)); + let helper_at_work = norm.helpers.values().any(|h| !h.done); + + let after = replay(&mut norm, &lines[last + 1..]); + let rows: Vec<&EventKind> = after.iter().filter(|e| !matches!(e, EventKind::SubAgent { .. } | EventKind::SubAgentProgress { .. } | EventKind::BackgroundTasks { .. })).collect(); + assert!(rows.is_empty(), "{name}: {rows:?}"); + if helper_at_work { + let ends = subagent_ends(&after); + assert!(ends.len() == 1 && ends[0].starts_with("toolu-1 stopped: "), "{name}: {ends:?}"); + } else { + assert!(after.is_empty(), "{name}: {after:?}"); + } + assert!(norm.helpers.values().all(|h| h.done), "{name}: nothing is left open"); + } + } + + /// Recordings `r8-bash-set-mode-*` (part 6 §9, n=2 per variant): the CLI obeys the mode a + /// `setMode` item of an allow names, the request's own (`acceptEdits`) and any other + /// (`plan`, `dontAsk`), and an `addRules` item sent back is written to the folder's + /// settings. So whatever Codly sends for "once", "for this session" and "always" carries + /// no mode and no rule for another tool than the one that asked. (A rule for another tool + /// is added here to the recorded request: no recording has one.) + #[test] + fn an_allow_never_sends_a_mode_or_a_rule_for_another_tool_as_recorded() { + let other_tool = json!({ "type": "addRules", "rules": [{ "toolName": "Edit", "ruleContent": "**" }], "behavior": "allow", "destination": "localSettings" }); + for variant in ["only-set-mode", "all", "plan", "dont-ask"] { + for label in [1, 2] { + let name = format!("r8-bash-set-mode-{variant}-{label}"); + let lines = recorded(&name); + let asked = lines.iter().find(|l| l["request"]["subtype"] == "can_use_tool").expect("the recorded request").clone(); + let suggested: Vec<&str> = asked["request"]["permission_suggestions"].as_array().unwrap().iter().filter_map(|s| s["type"].as_str()).collect(); + assert_eq!(suggested, ["addRules", "addDirectories", "setMode"], "{name}"); + let mut widened = asked.clone(); + widened["request"]["permission_suggestions"].as_array_mut().unwrap().push(other_tool.clone()); + + for request in [&asked, &widened] { + for choice in [ApprovalChoice::AllowOnce, ApprovalChoice::AllowSession, ApprovalChoice::AllowAlways] { + let mut s = spec(Role::Solo, false); + s.cwd = PathBuf::from(format!("/tmp/work/{name}")); + let mut norm = ClaudeNormalizer::new(&s, "sess-1".into()); + let a = approval_of(&norm.on_message(request)); + assert!(a.choices.contains(&choice), "{name}: {:?}", a.choices); + let (reply, _) = norm.answer(&a.id, &ApprovalDecision { choice, message: None, answers: None }).unwrap(); + let granted = &reply["response"]["response"]["updatedPermissions"]; + if choice == ApprovalChoice::AllowOnce { + assert!(granted.is_null(), "{name}: {granted}"); + continue; + } + let granted = granted.as_array().unwrap_or_else(|| panic!("{name} {choice:?}: {reply}")); + assert!(!granted.is_empty(), "{name}"); + for item in granted { + assert!(item["mode"].is_null(), "{name} {choice:?}: {item}"); + match item["type"].as_str() { + Some("addRules") => assert!(item["rules"].as_array().unwrap().iter().all(|r| r["toolName"] == "Bash"), "{name} {choice:?}: {item}"), + Some("addDirectories") => {} + _ => panic!("{name} {choice:?}: {item}"), + } + } + } + } + } + } + } + + /// Recordings `r8-http-slow-*` (part 6 §10, n=2 per kind): a tool of an HTTP MCP server + /// that takes 70 s, with an event stream, with progress notifications, and with a JSON + /// answer given more time. In each the only lines while it runs are the CLI's heartbeats + /// at 30 and 60 s, each a life sign of that call for the watchdog (`has_heartbeat`). + #[test] + fn a_slow_tool_of_an_http_server_gives_a_life_sign_every_30_s_as_recorded() { + for variant in ["sse", "progress", "json-env", "json-timeout"] { + for label in [1, 2] { + let name = format!("r8-http-slow-{variant}-{label}"); + let mut norm = ClaudeNormalizer::new(&spec(Role::Solo, false), "sess-1".into()); + let mut events = norm.turn_started("Call the tool mcp__ping-http__ping once"); + events.extend(replay(&mut norm, &recorded(&name))); + assert_eq!(tool_calls(&events), [("toolu-1", "mcp__ping-http__ping")], "{name}"); + let signs: Vec<&str> = events.iter().filter_map(|e| if let EventKind::ToolProgress { call_id } = e { Some(call_id.as_str()) } else { None }).collect(); + assert_eq!(signs, ["toolu-1", "toolu-1"], "{name}"); + let done = events.iter().any(|e| matches!(e, EventKind::ToolCompleted { call_id, ok: true, output: Some(out), .. } if call_id == "toolu-1" && out.contains("pong after 70 s"))); + assert!(done, "{name}: {events:?}"); + assert!(!events.iter().any(|e| matches!(e, EventKind::Unknown { .. })), "{name}: {events:?}"); + } + } + } + + /// Recordings `r8-fork-1-b` (a fork: a new session id), `r8-fork-1-d` and `r8-rewind-1-b` + /// (a resume and a rewind: the same id), part 6 §2 and §3, n=2 with the `-2` runs. Each + /// `init` is read as the start of any run, and the turn costs its own requests + /// (`model_usage_since_last_result`), not the line's `total_cost_usd`, which carries the + /// session's earlier turns. + #[test] + fn a_fork_a_resume_and_a_rewind_start_as_any_run_and_cost_their_own_turn_as_recorded() { + for (name, session) in [("r8-fork-1-b", "sess-2"), ("r8-fork-1-d", "sess-1"), ("r8-rewind-1-b", "sess-1")] { + let lines = recorded(name); + let result = lines.iter().find(|l| l["type"] == "result").unwrap(); + let (own, total) = (own_cost(result), result["total_cost_usd"].as_f64().unwrap()); + assert!(own > 0.0 && own < total, "{name}: {own} {total}"); + let resumed = SpawnSpec { session: SessionMode::Resume { session_id: "sess-1".into() }, session_cost_usd: total - own, ..spec(Role::Solo, false) }; + let mut norm = ClaudeNormalizer::new(&resumed, "sess-1".into()); + let mut events = norm.turn_started("List every secret word I asked you to remember"); + events.extend(replay(&mut norm, &lines)); + let starts: Vec> = events.iter().filter_map(|e| if let EventKind::SessionStarted { session_id, .. } = e { Some(session_id.as_deref()) } else { None }).collect(); + assert_eq!(starts, [Some(session)], "{name}"); + assert_eq!(turn_ends(&events).iter().map(|t| t.0).collect::>(), [TurnStatus::Completed], "{name}"); + assert!((last_cost(&events) - own).abs() < 1e-12, "{name}: {}", last_cost(&events)); + assert!(!events.iter().any(|e| matches!(e, EventKind::Unknown { .. })), "{name}: {events:?}"); + } + } + + /// A `result` with no `model_usage_since_last_result` (no 2.1.311 line lacks it; an older + /// or a later CLI may): its cost comes from the session's totals, `modelUsage` or else + /// `total_cost_usd`. After `--resume` those carry what the earlier runs cost (part 6 §3). + /// Before, a new process counted all of it again; now what the session cost before + /// (`SpawnSpec::session_cost_usd`) is taken off once, and the next turn of the process + /// costs only what it added. The line is `r8-fork-1-d`'s, with the key taken out. + #[test] + fn a_resumed_session_is_not_charged_again_when_a_result_has_no_cost_of_its_own() { + let lines = recorded("r8-fork-1-d"); + let full = lines.iter().find(|l| l["type"] == "result").unwrap().clone(); + // Part 6 §3, label 1: a's last `total_cost_usd`, and d's own turn. + let (before, own) = (0.00080338, 0.00006082); + let total = full["total_cost_usd"].as_f64().unwrap(); + assert!((total - (before + own)).abs() < 1e-12, "{total}"); + let mut session_totals = full.clone(); + session_totals.as_object_mut().unwrap().remove("model_usage_since_last_result"); + let mut total_only = session_totals.clone(); + total_only.as_object_mut().unwrap().remove("modelUsage"); + + let resumed = SpawnSpec { session: SessionMode::Resume { session_id: "sess-1".into() }, session_cost_usd: before, ..spec(Role::Solo, false) }; + let new = spec(Role::Solo, false); + let cost_of = |spec: &SpawnSpec, results: &[&Value]| { + let mut norm = ClaudeNormalizer::new(spec, "sess-1".into()); + let mut events = norm.turn_started("List every secret word"); + for result in results { + events.extend(norm.on_message(result)); + } + last_cost(&events) + }; + for (what, line) in [("modelUsage", &session_totals), ("total_cost_usd", &total_only)] { + assert!((cost_of(&resumed, &[line]) - own).abs() < 1e-6, "{what}: the turn's own cost"); + assert!((cost_of(&new, &[line]) - total).abs() < 1e-12, "{what}: a new session costs its total"); + } + // The next turn of the same process: what the session's total added since. + let mut next = total_only.clone(); + next["total_cost_usd"] = json!(total + 0.0001); + assert!((cost_of(&resumed, &[&total_only, &next]) - (own + 0.0001)).abs() < 1e-6); + // The per-turn key, when it is there, is the cost, whatever the session cost before. + assert!((cost_of(&resumed, &[&full]) - own_cost(&full)).abs() < 1e-12); + } + + /// Every tool call of a run was kept by its id until the run ended. Now the end of a turn + /// forgets the calls that are over, and keeps those still open (a background helper's). + #[test] + fn a_long_run_forgets_the_calls_that_are_over() { + let mut norm = ClaudeNormalizer::new(&spec(Role::Solo, false), "sess-1".into()); + norm.turn_started("go"); + norm.on_message(&tool_use("toolu-helper", "Agent", json!({ "description": "Look around" }))); + norm.on_message(&tool_result("toolu-helper", "Async agent launched successfully.", json!({ "status": "async_launched" }), false)); + // The helper's own call, which stays open through every turn. + let mut helpers_call = tool_use("toolu-helpers-call", "Bash", json!({ "command": "sleep 600" })); + helpers_call["parent_tool_use_id"] = json!("toolu-helper"); + norm.on_message(&helpers_call); + let result = json!({ "type": "result", "subtype": "success", "result": "ok", "model_usage_since_last_result": {} }); + norm.on_message(&result); + for turn in 0..100 { + norm.turn_started("go on"); + for call in 0..100 { + let id = format!("toolu-{turn}-{call}"); + norm.on_message(&tool_use(&id, "Bash", json!({ "command": "true" }))); + // (the last call of each turn gets no result: the turn's end cuts it off) + if call < 99 { + norm.on_message(&tool_result(&id, "", json!({}), false)); + } + } + norm.on_message(&result); + assert!(norm.tools_seen.len() <= norm.tools.len(), "turn {turn}: {} ids for {} open calls", norm.tools_seen.len(), norm.tools.len()); + } + assert_eq!(norm.tools_seen, HashSet::from(["toolu-helpers-call".to_string()]), "the open call is kept"); + let again = norm.on_message(&helpers_call); + assert!(tool_calls(&again).is_empty(), "a line that repeats the open call starts nothing: {again:?}"); + } } diff --git a/crates/codly-core/src/adapters/codex.rs b/crates/codly-core/src/adapters/codex.rs index 3b95904f..4f6848c8 100644 --- a/crates/codly-core/src/adapters/codex.rs +++ b/crates/codly-core/src/adapters/codex.rs @@ -1154,7 +1154,9 @@ impl CodexAgent { self.start_turn(text).await; } } - AgentCmd::Interrupt => self.interrupt().await, + AgentCmd::Interrupt => { + self.interrupt().await; + } AgentCmd::Approval { approval_id, decision } => match self.norm.answer(&approval_id, &decision) { Some((reply, events)) => match self.server.send(&reply, &self.raw).await { Ok(()) => self.emit_all(events), @@ -1228,43 +1230,55 @@ impl CodexAgent { self.request("turn/steer", params, Pending::Steer(text)).await; } - async fn interrupt(&mut self) { + /// False: a request could not be written. The server takes no more lines, the error of + /// that request said so (`request`), and no further one was tried: it would only fail + /// with the same words. + async fn interrupt(&mut self) -> bool { match (self.thread_id.clone(), self.active_turn.clone()) { (Some(tid), Some(turn)) => { self.norm.interrupt_requested = true; - self.request("turn/interrupt", json!({ "threadId": tid, "turnId": turn }), Pending::Interrupt).await; - self.interrupt_subagents().await; + let own = self.request("turn/interrupt", json!({ "threadId": tid, "turnId": turn }), Pending::Interrupt).await; + let sent = own && self.interrupt_subagents().await; self.wait_at_most(INTERRUPT_TIMEOUT); + sent } // The limit of its `turn/start` still runs. - _ if self.turn_pending => self.interrupt_after_start = true, + _ if self.turn_pending => { + self.interrupt_after_start = true; + true + } // No turn of its own, but its subagents may still work. _ => self.interrupt_subagents().await, } } /// A subagent's turn runs on its own thread: stopping the agent's turn does not stop it, - /// and nobody else can. - async fn interrupt_subagents(&mut self) { + /// and nobody else can. False: as for `interrupt`. + async fn interrupt_subagents(&mut self) -> bool { for (thread, turn) in self.norm.subagent_turns() { - self.request("turn/interrupt", json!({ "threadId": thread, "turnId": turn }), Pending::Interrupt).await; + if !self.request("turn/interrupt", json!({ "threadId": thread, "turnId": turn }), Pending::Interrupt).await { + return false; + } } + true } /// interrupt the turn (≤ 5 s) → thread/unsubscribe (≤ 3 s) → done. The server keeps - /// running for the other agents. + /// running for the other agents. A server that takes no more lines is asked nothing + /// after the first request that fails: the run ends at once, with that one error. async fn begin_shutdown(&mut self) { if self.stage != Stage::Running { return; } self.queue.clear(); self.steer_queue.clear(); + if !self.interrupt().await { + return self.finish(); + } if self.active_turn.is_some() || self.turn_pending { - self.interrupt().await; self.stage = Stage::Interrupting; self.deadline = Some(tokio::time::Instant::now() + Duration::from_secs(5)); } else { - self.interrupt_subagents().await; self.unsubscribe().await; } } @@ -1429,8 +1443,8 @@ enum AnswerShape { Decisions(Vec<(ApprovalChoice, Value)>), /// `{permissions, scope}` Permissions(Value), - /// `{answers}` - UserInput, + /// `{answers}`, keyed by the id of each question asked: (id, text). + UserInput(Vec<(String, String)>), /// `{action, content}` Elicitation, } @@ -2163,7 +2177,13 @@ impl CodexNormalizer { "item/permissions/requestApproval" => { (ApprovalSubject::Permissions { detail: p.clone() }, AnswerShape::Permissions(p["permissions"].clone()), p["reason"].as_str().map(str::to_owned)) } - "item/tool/requestUserInput" => (ApprovalSubject::Question { questions: p["questions"].clone() }, AnswerShape::UserInput, None), + "item/tool/requestUserInput" => { + let asked = p["questions"].as_array().into_iter().flatten(); + let ids = asked + .filter_map(|q| Some((q["id"].as_str()?.to_owned(), q["question"].as_str().unwrap_or_default().to_owned()))) + .collect(); + (ApprovalSubject::Question { questions: p["questions"].clone() }, AnswerShape::UserInput(ids), None) + } "mcpServer/elicitation/request" => { let reason = p["message"].as_str().map(str::to_owned); (ApprovalSubject::Question { questions: p.clone() }, AnswerShape::Elicitation, reason) @@ -2177,7 +2197,7 @@ impl CodexNormalizer { let choices = match &shape { AnswerShape::Decisions(list) => list.iter().map(|(c, _)| *c).collect(), AnswerShape::Permissions(_) => vec![ApprovalChoice::AllowOnce, ApprovalChoice::AllowSession, ApprovalChoice::Deny], - AnswerShape::UserInput => vec![ApprovalChoice::AllowOnce, ApprovalChoice::Cancel], + AnswerShape::UserInput(_) => vec![ApprovalChoice::AllowOnce, ApprovalChoice::Cancel], AnswerShape::Elicitation => vec![ApprovalChoice::AllowOnce, ApprovalChoice::Deny, ApprovalChoice::Cancel], }; // A subagent's request is the agent's to get answered: the card says who asks. @@ -2221,7 +2241,7 @@ impl CodexNormalizer { ApprovalChoice::AllowSession | ApprovalChoice::AllowAlways => json!({ "permissions": perms, "scope": "session" }), _ => json!({ "permissions": {}, "scope": "turn" }), }, - AnswerShape::UserInput => json!({ "answers": if allow { d.answers.clone().unwrap_or_else(|| json!({})) } else { json!({}) } }), + AnswerShape::UserInput(asked) => json!({ "answers": if allow { user_input_answers(&asked, d.answers.as_ref()) } else { json!({}) } }), AnswerShape::Elicitation => match d.choice { _ if allow => json!({ "action": "accept", "content": d.answers.clone().unwrap_or(Value::Null) }), ApprovalChoice::Deny => json!({ "action": "decline" }), @@ -2421,6 +2441,31 @@ fn pick_decision(list: &[(ApprovalChoice, Value)], choice: ApprovalChoice) -> Va .unwrap_or_else(|| json!(if matches!(choice, AllowOnce | AllowSession | AllowAlways) { "accept" } else { "decline" })) } +/// The `answers` of a `requestUserInput` response: for every question asked (id, text), its +/// id → `{ answers: [..] }` (`ToolRequestUserInputResponse`, `ToolRequestUserInputAnswer` of +/// codex-cli 0.166.0; from the generated types, not verified on a live run). The card files an +/// answer under the question's text, as a string or a list of strings; one filed under the id +/// is read too, also in Codex's own `{ answers }` form. A question with no answer gets an empty +/// list, and an answer that names no question asked is dropped. +fn user_input_answers(asked: &[(String, String)], given: Option<&Value>) -> Value { + let strings = |v: &Value| -> Vec { + let picked = match v { + Value::Object(o) => o.get("answers").and_then(Value::as_array).cloned().unwrap_or_default(), + Value::Array(a) => a.clone(), + other => vec![other.clone()], + }; + picked.into_iter().filter(|a| a.as_str().is_some_and(|s| !s.is_empty())).collect() + }; + let out: serde_json::Map = asked + .iter() + .map(|(id, text)| { + let answer = given.and_then(|g| g.get(id.as_str()).or_else(|| g.get(text.as_str()))); + (id.clone(), json!({ "answers": answer.map(strings).unwrap_or_default() })) + }) + .collect(); + Value::Object(out) +} + #[cfg(test)] mod tests { use super::*; @@ -2441,7 +2486,7 @@ mod tests { /// an interrupt) through the normalizer, answering approvals like the probe did. #[test] fn replays_the_app_server_fixture() { - let mut norm = CodexNormalizer::new("a1", "r1", PathBuf::from("/private/tmp/claude-501/-Users-julien-Documents-Repos-Codly/ae7e9f7f-d897-4679-8080-c22a339ba5b7/scratchpad/fixture-repo"), false); + let mut norm = CodexNormalizer::new("a1", "r1", PathBuf::from("/tmp/scratch/fixture-repo"), false); let mut events = Vec::new(); let mut replies = Vec::new(); for line in fixture() { @@ -2611,6 +2656,55 @@ mod tests { assert!(ev.iter().any(|e| matches!(e, EventKind::ApprovalResolved { approval_id, status: ApprovalStatus::Cancelled, .. } if *approval_id == a.id))); } + /// The card files your answers under each question's text, as a string or a list. Codex + /// reads them under each question's id, as `{ answers: [..] }`. The request and the + /// responses are written from the generated types of codex-cli 0.166.0 + /// (`ToolRequestUserInputParams`, `ToolRequestUserInputResponse`), not from a live run. + #[test] + fn the_answers_to_a_codex_question_are_filed_under_its_ids() { + let mut norm = CodexNormalizer::new("a", "r", PathBuf::from("/w"), false); + let option = |label: &str| json!({ "label": label, "description": "" }); + let qs = json!([ + { "id": "db", "header": "DB", "question": "Which database?", "isOther": false, "isSecret": false, "options": [option("sqlite"), option("postgres")] }, + { "id": "parts", "header": "Parts", "question": "Which parts?", "isOther": false, "isSecret": false, "options": [option("api"), option("ui")] }, + { "id": "name", "header": "Name", "question": "Its name?", "isOther": true, "isSecret": false, "options": null }, + { "id": "skip", "header": "More", "question": "Anything else?", "isOther": true, "isSecret": false, "options": null }, + { "id": "none", "header": "Notes", "question": "Notes?", "isOther": true, "isSecret": false, "options": null }, + ]); + let params = json!({ "threadId": "t", "turnId": "u", "itemId": "i", "questions": qs, "isBlocking": true, "autoResolutionMs": null }); + let ask = |norm: &mut CodexNormalizer, n: i64| approval_of(&norm.on_request(&json!(n), "item/tool/requestUserInput", ¶ms).0).id; + + // The card's shape: one pick, several picks, a typed answer, an empty one, one not + // given, and a key that names no question. + let card = json!({ + "Which database?": "sqlite", + "Which parts?": ["api", "ui"], + "Its name?": "billing", + "Anything else?": "", + "Who asked?": "me", + }); + let codex = json!({ + "db": { "answers": ["sqlite"] }, + "parts": { "answers": ["api", "ui"] }, + "name": { "answers": ["billing"] }, + "skip": { "answers": [] }, + "none": { "answers": [] }, + }); + let id = ask(&mut norm, 1); + let (r, _) = norm.answer(&id, &ApprovalDecision { choice: ApprovalChoice::AllowOnce, message: None, answers: Some(card) }).unwrap(); + assert_eq!(r["result"]["answers"], codex); + + // Answers filed under the ids, in Codex's own form, mean the same. + let id = ask(&mut norm, 2); + let (r, _) = norm.answer(&id, &ApprovalDecision { choice: ApprovalChoice::AllowOnce, message: None, answers: Some(codex.clone()) }).unwrap(); + assert_eq!(r["result"]["answers"], codex); + + // A cancel answers nothing. + let id = ask(&mut norm, 3); + let (r, _) = norm.answer(&id, &ApprovalDecision { choice: ApprovalChoice::Cancel, message: None, answers: Some(codex) }).unwrap(); + assert_eq!(r["result"], json!({ "answers": {} })); + } + #[test] fn notifications_map_to_events() { let mut norm = CodexNormalizer::new("a", "r", PathBuf::from("/w"), true); @@ -3099,6 +3193,7 @@ mod tests { raw_log: PathBuf::from("/tmp/r/raw.ndjson"), byok_command: cmd.map(str::to_owned), sandbox_shell: false, + max_budget_usd: None, }; let off = spec(&[("CODEX_HOME", "/h")], None); assert!(byok_overrides(&off).is_empty()); @@ -3145,6 +3240,7 @@ mod tests { raw_log: PathBuf::from("/tmp/r/raw.ndjson"), byok_command: None, sandbox_shell: false, + max_budget_usd: None, }; let (model, effort) = classify::split_model_effort(spec.model.as_deref()); let (m, p) = thread_request(&spec, model.as_deref(), effort.as_deref(), &[], &[]); @@ -3521,6 +3617,40 @@ mod tests { assert!(server.state.lock().unwrap().routes.is_empty(), "the agent's threads are let go"); } + /// The same server when the stopped agent's subagent is in a turn: one cause, said once, + /// and nothing is waited for. Before, every request of the stop failed with the same + /// words: the interrupt of the agent's turn, the one of the subagent's turn, then (5 s + /// later, with a turn of the agent's own) the request that lets the thread go. + /// (`thread/started` and `turn/started` lines of a subagent's thread, written from the + /// codex-cli 0.166.0 schema types. Not verified live.) + #[tokio::test] + async fn a_server_that_takes_no_more_lines_is_said_once_when_a_subagent_still_works() { + let dir = tempfile::tempdir().unwrap(); + // the agent's own turn runs too (true), or only its subagent's (false) + for own_turn in [true, false] { + let server = fake_server(dir.path()); // every write fails + let (mut agent, mut events) = fake_agent(&server); + (agent.started, agent.thread_id) = (true, Some("t".into())); + agent.active_turn = own_turn.then(|| "u".to_string()); + agent.norm.thread = agent.thread_id.clone(); + server.state.lock().unwrap().routes.insert("t".into(), agent.route.clone()); + server.route_line(br#"{"method":"thread/started","params":{"thread":{"id":"s","parentThreadId":"t"}}}"#); + agent.on_notification("turn/started", &json!({ "threadId": "s", "turn": { "id": "su" } })).await; + assert_eq!(agent.norm.subagent_turns(), [("s".to_string(), "su".to_string())]); + emitted(&mut events); + + agent.on_cmd(AgentCmd::Shutdown).await; + assert_eq!(agent.stage, Stage::Done, "own turn {own_turn}: nothing to wait for, no request went out"); + let kinds = emitted(&mut events); + let errors: Vec<&str> = kinds.iter().filter_map(|e| if let EventKind::Error { message, .. } = e { Some(message.as_str()) } else { None }).collect(); + assert_eq!(errors, ["turn/interrupt: codex app-server stdin is closed"], "own turn {own_turn}"); + // The agent's own turn is closed as interrupted: a failed one would send a stopped worker to the gate. + assert_eq!(turn_ends(&kinds), if own_turn { vec![TurnStatus::Interrupted] } else { vec![] }, "own turn {own_turn}: {kinds:?}"); + assert!(matches!(kinds.last(), Some(EventKind::Exited { .. })), "{kinds:?}"); + assert!(server.state.lock().unwrap().routes.is_empty(), "the agent's threads are let go"); + } + } + /// A subagent's turn ends on its own thread: the agent's turn goes on. Its end is neither /// kept back behind a steer nor taken for the end of the agent's turn. #[tokio::test] @@ -3845,7 +3975,11 @@ mod tests { #[tokio::test] async fn shutdown_closes_the_open_turn_as_interrupted() { let dir = tempfile::tempdir().unwrap(); + let env = HashMap::from([("PATH".to_string(), "/usr/bin:/bin".to_string())]); + // an app-server that takes every line and answers none + let mut sink = proc::command(Path::new("/bin/sh"), &["-c".into(), "cat > /dev/null".into()], dir.path(), &env).spawn().unwrap(); let server = fake_server(dir.path()); + *server.stdin.lock().await = sink.stdin.take(); // the turn runs (false), or its `turn/start` is not answered yet (true) for pending in [false, true] { let (mut agent, mut events) = fake_agent(&server); @@ -3855,6 +3989,8 @@ mod tests { agent.on_cmd(AgentCmd::Shutdown).await; assert_eq!(agent.stage, Stage::Interrupting); agent.on_deadline().await; + assert_eq!(agent.stage, Stage::Unsubscribing, "the thread is let go, and that request gets no answer either"); + agent.on_deadline().await; assert_eq!(agent.stage, Stage::Done); let kinds = emitted(&mut events); // Interrupted, not Failed: a failed turn sends a stopped worker to the gate @@ -4012,6 +4148,7 @@ mod tests { raw_log: cwd.join("raw.ndjson"), byok_command: None, sandbox_shell: false, + max_budget_usd: None, cwd, } } diff --git a/crates/codly-core/src/adapters/codex/account.rs b/crates/codly-core/src/adapters/codex/account.rs index 44f2afc0..c00a13c1 100644 --- a/crates/codly-core/src/adapters/codex/account.rs +++ b/crates/codly-core/src/adapters/codex/account.rs @@ -67,6 +67,7 @@ impl AccountQuery { local_settings: false, raw_log: self.raw_log.clone(), byok_command: self.byok_command.clone(), + max_budget_usd: None, } } diff --git a/crates/codly-core/src/adapters/mod.rs b/crates/codly-core/src/adapters/mod.rs index e30464ac..6df48c5c 100644 --- a/crates/codly-core/src/adapters/mod.rs +++ b/crates/codly-core/src/adapters/mod.rs @@ -90,8 +90,10 @@ pub struct SpawnSpec { pub env: HashMap, pub session: SessionMode, /// What the earlier runs on the resumed session cost together, as Codly counted them (0 for - /// a new session). For ACP agents: they report a session's cost as a running total, and the - /// adapter takes this off, so a run's cost starts from zero as with every other CLI. + /// a new session; not given to Codex). ACP agents report a session's cost as a running + /// total, and so does Claude Code in a `result` that has no cost of the turn's own (after + /// `--resume` its totals carry the earlier runs: 2.1.311 part 6, section 3): the adapter + /// takes this off, so a run's cost starts from zero as with every other CLI. pub session_cost_usd: f64, /// Static role rules, appended to the CLI's own system prompt where supported /// (Claude `--append-system-prompt`, Codex `developerInstructions`); for ACP agents @@ -122,6 +124,20 @@ pub struct SpawnSpec { /// (`Settings.claude_sandbox`, `claude::settings_json`). Codex always has its own sandbox, /// and the ACP agents have none. pub sandbox_shell: bool, + /// Claude only: `--max-budget-usd`, what was left of your cost budget when the run started + /// (`breaker::rest_usd`). Claude Code counts this process alone and stops a turn right + /// after the model request that passes it: the tool call that request asked for does not + /// run, and every later turn of the process fails at once (2.1.311 part 4, section 10), so + /// Codly ends the run there. Reached during a long tool call (a helper's request passed + /// it: part 5, section 10, n=2): the turn ends, not the call, which runs on in no list + /// until stdin is closed, as the end of the run does (an interrupt does not end it; + /// `stop_task` with its task id does: part 6, section 6, n=2 each). One run's own total can + /// pass its limit: the requests on their way when it passed are finished and paid, and a + /// helper with requests left made one more (part 6, section 6: the totals ended 19% and + /// 45% above the limit, n=2; after the `result` nothing more came in 40 s). Several Claude + /// agents at once each hold the whole rest, so together they can pass the budget until + /// their turns end (the check between turns stays). None: no limit of its own. + pub max_budget_usd: Option, } /// Commands the orchestrator sends to a running agent. @@ -153,17 +169,29 @@ pub enum SessionRequest { Model(String), /// `get_context_usage`: how full the context is. ContextUsage, - /// `mcp_reconnect`: try again to connect the MCP server of this name. Recorded for - /// servers that still could not connect: the answer is an error with the CLI's reason. + /// `mcp_reconnect`: try again to connect the MCP server of this name. Recorded: for a + /// server that still cannot connect the answer is an error with the CLI's reason; for one + /// that connects it is a success with no body (part 3 §10, n=1). McpReconnect(String), - /// `stop_task`, with the id of a background task (`BackgroundTask::id`): the CLI ends it. - /// The answer is empty also when nothing was stopped (recorded, part 2 §6): the CLI's next - /// list of its background tasks says whether the task is gone. + /// `mcp_toggle`: turn the MCP server of this name off (false) or on (true). Recorded + /// (part 3 §10, n=1): a success with no body either way; the server is then `disabled`, + /// or started again and `connected`. Where it stands is in `mcp_status`. Not recorded: + /// whether the CLI saves the switch (no process was started after an "off"), and what it + /// answers for a server that does not start or that it does not know. + McpEnabled(String, bool), + /// `stop_task`, with the id of a background task (`BackgroundTask::id`), or the call id of + /// a helper at work (`EventKind::SubAgent::call_id`, in the background or not): the CLI + /// ends it. The answer is empty also when nothing was stopped (recorded, part 2 §6): the + /// CLI's next list of its background tasks, and a helper's own row, say what ended. For a + /// helper found by its call id the adapter adds its description (`helper`). An id that is + /// neither is refused, and nothing reaches the CLI. StopTask(String), /// `apply_flag_settings` with `effortLevel`: the reasoning effort of the session, one of - /// `claude::EFFORT_LEVELS` (the adapter sends no other word). The CLI answers "success" - /// also for a level it then drops, so `Settings` is asked after it. - Effort(String), + /// `claude::EFFORT_LEVELS` (the adapter sends no other word), or None for no level of its + /// own (`null`: the CLI's default, recorded as "medium" on a process started with + /// `--effort high`, part 4 §4, n=2). The CLI answers "success" also for a level it then + /// drops, so `Settings` is asked after it. + Effort(Option), /// `get_settings`: what the session works with now (`applied.model`, `applied.effort`). Settings, } diff --git a/crates/codly-core/src/adapters/startup.rs b/crates/codly-core/src/adapters/startup.rs index 2497b024..4286a3cd 100644 --- a/crates/codly-core/src/adapters/startup.rs +++ b/crates/codly-core/src/adapters/startup.rs @@ -224,6 +224,7 @@ mod tests { raw_log: "/tmp/raw.ndjson".into(), byok_command: None, sandbox_shell: false, + max_budget_usd: None, } } diff --git a/crates/codly-core/src/adapters/testdata/claude-interrupt-live.jsonl b/crates/codly-core/src/adapters/testdata/claude-interrupt-live.jsonl index b6550c0d..2ac84785 100644 --- a/crates/codly-core/src/adapters/testdata/claude-interrupt-live.jsonl +++ b/crates/codly-core/src/adapters/testdata/claude-interrupt-live.jsonl @@ -1,7 +1,7 @@ {"_note": "Captured live 2026-10-25 from claude 2.1.309 through Codly's adapter (adapter_smoke --interrupt-at-approval): TaskCreate x2, a Bash can_use_tool, Codly's interrupt, control_cancel_request, interrupted result. Hooks dropped; init and the initialize response trimmed; account redacted."} {"type":"system","subtype":"session_title_changed","title":"codly:solo-fc681054","uuid":"a6e21a4e-d8f7-47ff-adb1-feb0f8061191","session_id":"4a6796bf-c299-4975-8a0e-6bc9eaf3b8e2"} {"type":"control_response","response":{"subtype":"success","request_id":"codly-1","response":{"claude_code_version":"2.1.309","models":[{"value":"default","resolvedModel":"claude-opus-5-5","displayName":"Default (recommended)","description":"Opus 5.5 \u00b7 Best for everyday, complex tasks","supportsEffort":true,"supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsFastMode":true,"supportsAutoMode":true,"supportsThinkingOff":false},{"value":"opus","resolvedModel":"claude-opus-5-5","displayName":"Opus","description":"Opus 5.5 \u00b7 Best for everyday, complex tasks","supportsEffort":true,"supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsFastMode":true,"supportsAutoMode":true,"supportsThinkingOff":false},{"value":"claude-fable-5-1[1m]","resolvedModel":"claude-fable-5-1","displayName":"Fable","description":"Fable 5.1 \u00b7 Most capable for your hardest and longest-running tasks","supportsEffort":true,"supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsThinkingOff":false},{"value":"sonnet","resolvedModel":"claude-sonnet-5-5","displayName":"Sonnet","description":"Sonnet 5.5 \u00b7 Efficient for routine tasks","supportsEffort":true,"supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsThinkingOff":false},{"value":"haiku","resolvedModel":"claude-haiku-5-5","displayName":"Haiku","description":"Haiku 5.5 \u00b7 Fastest for quick answers","supportsEffort":true,"supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsThinkingOff":false}],"account":{"subscriptionType":"Claude Team","apiProvider":"firstParty"},"current_permission_mode":"default"},"pending_permission_requests":[],"pending_user_dialog_requests":[]}} -{"type":"system","subtype":"init","cwd":"/private/tmp/claude-501/-Users-julien-Documents-Repos-Codly/ae7e9f7f-d897-4679-8080-c22a339ba5b7/scratchpad/smoke/claude-1792971712/repo","session_id":"4a6796bf-c299-4975-8a0e-6bc9eaf3b8e2","tools":["Task","Bash","Edit","Glob","Grep","Read","TaskCreate","TaskGet","TaskList","TaskUpdate","WebFetch","WebSearch","Write"],"mcp_servers":[],"model":"claude-haiku-5-5","permissionMode":"default","apiKeySource":"none","claude_code_version":"2.1.309","uuid":"2bca4d0b-dfb0-4e13-9b5d-b62fd0f661fc"} +{"type":"system","subtype":"init","cwd":"/tmp/scratch/smoke/claude-1792971712/repo","session_id":"4a6796bf-c299-4975-8a0e-6bc9eaf3b8e2","tools":["Task","Bash","Edit","Glob","Grep","Read","TaskCreate","TaskGet","TaskList","TaskUpdate","WebFetch","WebSearch","Write"],"mcp_servers":[],"model":"claude-haiku-5-5","permissionMode":"default","apiKeySource":"none","claude_code_version":"2.1.309","uuid":"2bca4d0b-dfb0-4e13-9b5d-b62fd0f661fc","slash_commands":[],"skills":[],"plugins":[],"agents":[]} {"type":"system","subtype":"status","status":"requesting","session_id":"4a6796bf-c299-4975-8a0e-6bc9eaf3b8e2","uuid":"00646daf-acee-4e82-9166-61739ad3f215"} {"type":"stream_event","event":{"type":"message_start","message":{"model":"claude-haiku-5-5","id":"msg_011CgPqj1YRr7aLVbofoqAE5","type":"message","role":"assistant","content":[],"container":null,"stop_reason":null,"stop_sequence":null,"stop_details":null,"usage":{"input_tokens":2,"cache_creation_input_tokens":3685,"cache_read_input_tokens":13025,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":3685},"output_tokens":5,"service_tier":"standard","inference_geo":"global","speed":"standard"},"input_transformations":[],"diagnostics":null,"context_management":null}},"session_id":"4a6796bf-c299-4975-8a0e-6bc9eaf3b8e2","parent_tool_use_id":null,"uuid":"ab997ffe-631b-437a-a4ac-97b5add84c74","ttft_ms":522,"thinking_display":"updates","api_message_id":"msg_011CgPqj1YRr7aLVbofoqAE5"} {"type":"stream_event","event":{"type":"content_block_start","index":0,"content_block":{"type":"thinking","thinking":"","signature":""}},"session_id":"4a6796bf-c299-4975-8a0e-6bc9eaf3b8e2","parent_tool_use_id":null,"uuid":"0556803e-bbe1-429a-bde6-54e04ae784c2","thinking_display":"updates","api_message_id":"msg_011CgPqj1YRr7aLVbofoqAE5"} @@ -50,7 +50,7 @@ {"type":"stream_event","event":{"type":"content_block_stop","index":0},"session_id":"4a6796bf-c299-4975-8a0e-6bc9eaf3b8e2","parent_tool_use_id":null,"uuid":"b115b430-a8fb-404d-8986-e4b134d16be1","api_message_id":"msg_011CgPqj89Z61iHp6Zon8Qwo"} {"type":"stream_event","event":{"type":"message_delta","delta":{"stop_reason":"tool_use","stop_sequence":null,"stop_details":null,"container":null},"usage":{"input_tokens":2,"cache_creation_input_tokens":456,"cache_read_input_tokens":16710,"output_tokens":86,"output_tokens_details":{"thinking_tokens":0},"iterations":[{"input_tokens":2,"output_tokens":86,"cache_read_input_tokens":16710,"cache_creation_input_tokens":456,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":456},"type":"message"}]},"context_management":{"applied_edits":[]}},"session_id":"4a6796bf-c299-4975-8a0e-6bc9eaf3b8e2","parent_tool_use_id":null,"uuid":"e60ae996-3eec-4842-87d4-3c581f9c2cb7","api_message_id":"msg_011CgPqj89Z61iHp6Zon8Qwo"} {"type":"stream_event","event":{"type":"message_stop"},"session_id":"4a6796bf-c299-4975-8a0e-6bc9eaf3b8e2","parent_tool_use_id":null,"uuid":"419bbb90-6e88-4e9a-ac25-6638059b9a45","api_message_id":"msg_011CgPqj89Z61iHp6Zon8Qwo"} -{"type":"control_request","request_id":"f1ca9041-58c8-423a-bcaf-26808ed3c678","request":{"subtype":"can_use_tool","tool_name":"Bash","display_name":"Bash","input":{"command":"echo codly > hello.txt","description":"Write codly to hello.txt"},"description":"Write codly to hello.txt","permission_suggestions":[{"type":"addRules","rules":[{"toolName":"Bash","ruleContent":"echo codly *"}],"behavior":"allow","destination":"localSettings"},{"type":"addDirectories","directories":["/private/tmp/claude-501/-Users-julien-Documents-Repos-Codly/ae7e9f7f-d897-4679-8080-c22a339ba5b7/scratchpad/smoke/claude-1792971712/repo"],"destination":"session"}],"blocked_path":"/private/tmp/claude-501/-Users-julien-Documents-Repos-Codly/ae7e9f7f-d897-4679-8080-c22a339ba5b7/scratchpad/smoke/claude-1792971712/repo/hello.txt","tool_use_id":"toolu_01JRYxwSSVJXG2f2ax6jxtTJ"}} +{"type":"control_request","request_id":"f1ca9041-58c8-423a-bcaf-26808ed3c678","request":{"subtype":"can_use_tool","tool_name":"Bash","display_name":"Bash","input":{"command":"echo codly > hello.txt","description":"Write codly to hello.txt"},"description":"Write codly to hello.txt","permission_suggestions":[{"type":"addRules","rules":[{"toolName":"Bash","ruleContent":"echo codly *"}],"behavior":"allow","destination":"localSettings"},{"type":"addDirectories","directories":["/tmp/scratch/smoke/claude-1792971712/repo"],"destination":"session"}],"blocked_path":"/tmp/scratch/smoke/claude-1792971712/repo/hello.txt","tool_use_id":"toolu_01JRYxwSSVJXG2f2ax6jxtTJ"}} {"type":"control_cancel_request","request_id":"f1ca9041-58c8-423a-bcaf-26808ed3c678"} {"type":"control_response","response":{"subtype":"success","request_id":"codly-2","response":{"still_queued":[]}}} {"type":"user","message":{"role":"user","content":[{"type":"tool_result","content":"The user doesn't want to proceed with this tool use. The tool use was rejected (eg. if it was a file edit, the new_string was NOT written to the file). STOP what you are doing and wait for the user to tell you how to proceed.","is_error":true,"tool_use_id":"toolu_01JRYxwSSVJXG2f2ax6jxtTJ"}]},"parent_tool_use_id":null,"session_id":"4a6796bf-c299-4975-8a0e-6bc9eaf3b8e2","uuid":"6946fd36-4f9b-4384-ba87-590624c3f6e8","timestamp":"2026-10-25T23:41:56.778Z","tool_use_result":"User rejected tool use","tool_result_meta":[{"id":"toolu_01JRYxwSSVJXG2f2ax6jxtTJ","non_execution_kind":"user-rejected"}]} diff --git a/crates/codly-core/src/adapters/testdata/codex-mcp-live.jsonl b/crates/codly-core/src/adapters/testdata/codex-mcp-live.jsonl index d11cfbe9..e1894b97 100644 --- a/crates/codly-core/src/adapters/testdata/codex-mcp-live.jsonl +++ b/crates/codly-core/src/adapters/testdata/codex-mcp-live.jsonl @@ -1,5 +1,5 @@ {"_note": "Captured live 2026-10-25 from codex-cli 0.161.0 app-server through Codly's adapter (adapter_smoke codex --mcp): approvalPolicy on-request + workspace-write, a codly MCP tool call (default_tools_approval_mode approve: no prompt), an escalated shell command approval. Server->client messages only; other users' MCP servers dropped."} -{"method":"thread/started","params":{"thread":{"id":"01a1756f-dce3-72b1-a5dd-cc0881c2cbe6","environments":[{"environmentId":"local","cwd":"/private/tmp/claude-501/-Users-julien-Documents-Repos-Codly/ae7e9f7f-d897-4679-8080-c22a339ba5b7/scratchpad/smoke/codex-1792971625/repo","runtimeWorkspaceRoots":["/private/tmp/claude-501/-Users-julien-Documents-Repos-Codly/ae7e9f7f-d897-4679-8080-c22a339ba5b7/scratchpad/smoke/codex-1792971625/repo"]}],"extra":null,"sessionId":"01a1756f-dce3-72b1-a5dd-cc0881c2cbe6","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":"low","createdAt":1792971627,"updatedAt":1792971627,"recencyAt":1792971627,"status":{"type":"idle"},"path":"/Users/julien/.codex/sessions/2026/10/25/rollout-2026-10-25T16-40-27-01a1756f-dce3-72b1-a5dd-cc0881c2cbe6.jsonl","cwd":"/private/tmp/claude-501/-Users-julien-Documents-Repos-Codly/ae7e9f7f-d897-4679-8080-c22a339ba5b7/scratchpad/smoke/codex-1792971625/repo","cliVersion":"0.161.0","originator":"codly","source":"vscode","canAcceptDirectInput":true,"threadSource":"codly","agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]}},"emittedAtMs":1792971627867} +{"method":"thread/started","params":{"thread":{"id":"01a1756f-dce3-72b1-a5dd-cc0881c2cbe6","environments":[{"environmentId":"local","cwd":"/tmp/scratch/smoke/codex-1792971625/repo","runtimeWorkspaceRoots":["/tmp/scratch/smoke/codex-1792971625/repo"]}],"extra":null,"sessionId":"01a1756f-dce3-72b1-a5dd-cc0881c2cbe6","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":"low","createdAt":1792971627,"updatedAt":1792971627,"recencyAt":1792971627,"status":{"type":"idle"},"path":"/Users/me/.codex/sessions/2026/10/25/rollout-2026-10-25T16-40-27-01a1756f-dce3-72b1-a5dd-cc0881c2cbe6.jsonl","cwd":"/tmp/scratch/smoke/codex-1792971625/repo","cliVersion":"0.161.0","originator":"codly","source":"vscode","canAcceptDirectInput":true,"threadSource":"codly","agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]}},"emittedAtMs":1792971627867} {"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a1756f-dce3-72b1-a5dd-cc0881c2cbe6","name":"codly","status":"starting","error":null,"failureReason":null},"emittedAtMs":1792971627867} {"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a1756f-dce3-72b1-a5dd-cc0881c2cbe6","name":"codly","status":"ready","error":null,"failureReason":null},"emittedAtMs":1792971627867} {"method":"thread/status/changed","params":{"threadId":"01a1756f-dce3-72b1-a5dd-cc0881c2cbe6","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1792971628195} @@ -13,11 +13,11 @@ {"method":"thread/tokenUsage/updated","params":{"threadId":"01a1756f-dce3-72b1-a5dd-cc0881c2cbe6","turnId":"01a1756f-dd5c-7be0-8b7c-9413e83b1f98","tokenUsage":{"total":{"totalTokens":37899,"inputTokens":37827,"cachedInputTokens":31104,"cacheWriteInputTokens":0,"outputTokens":72,"reasoningOutputTokens":0},"last":{"totalTokens":19019,"inputTokens":18983,"cachedInputTokens":18688,"cacheWriteInputTokens":0,"outputTokens":36,"reasoningOutputTokens":0},"modelContextWindow":258400}},"emittedAtMs":1792971631717} {"method":"account/rateLimits/updated","params":{"rateLimits":{"limitId":"codex","limitName":null,"normalModelSlug":null,"primary":{"usedPercent":0,"windowDurationMins":300,"resetsAt":1792982616},"secondary":{"usedPercent":0,"windowDurationMins":10080,"resetsAt":1793569416},"credits":{"hasCredits":false,"unlimited":false,"balance":"0"},"individualLimit":null,"spendControlReached":null,"planType":"plus","rateLimitReachedType":null}},"emittedAtMs":1792971631717} {"method":"thread/status/changed","params":{"threadId":"01a1756f-dce3-72b1-a5dd-cc0881c2cbe6","status":{"type":"active","activeFlags":["waitingOnApproval"]}},"emittedAtMs":1792971632659} -{"method":"item/started","params":{"item":{"type":"commandExecution","id":"exec-b4812e6c-c4bc-47bf-bf1c-c16cdd8c82dc","pluginId":null,"scriptPath":null,"command":"/bin/zsh -lc 'echo codly > hello.txt'","cwd":"/private/tmp/claude-501/-Users-julien-Documents-Repos-Codly/ae7e9f7f-d897-4679-8080-c22a339ba5b7/scratchpad/smoke/codex-1792971625/repo","processId":null,"source":"agent","status":"inProgress","commandActions":[{"type":"unknown","command":"echo codly > hello.txt"}],"aggregatedOutput":null,"exitCode":null,"durationMs":null},"threadId":"01a1756f-dce3-72b1-a5dd-cc0881c2cbe6","turnId":"01a1756f-dd5c-7be0-8b7c-9413e83b1f98","startedAtMs":1792971632660},"emittedAtMs":1792971632660} -{"method":"item/commandExecution/requestApproval","id":0,"params":{"kind":"command","threadId":"01a1756f-dce3-72b1-a5dd-cc0881c2cbe6","turnId":"01a1756f-dd5c-7be0-8b7c-9413e83b1f98","itemId":"exec-b4812e6c-c4bc-47bf-bf1c-c16cdd8c82dc","startedAtMs":1792971632659,"environmentId":"local","reason":"May I run the requested shell command with elevated approval?","command":"/bin/zsh -lc 'echo codly > hello.txt'","cwd":"/private/tmp/claude-501/-Users-julien-Documents-Repos-Codly/ae7e9f7f-d897-4679-8080-c22a339ba5b7/scratchpad/smoke/codex-1792971625/repo","commandActions":[{"type":"unknown","command":"echo codly > hello.txt"}],"proposedExecpolicyAmendment":["/bin/zsh","-lc","echo codly > hello.txt"],"availableDecisions":["accept",{"acceptWithExecpolicyAmendment":{"execpolicy_amendment":["/bin/zsh","-lc","echo codly > hello.txt"]}},"cancel"]}} +{"method":"item/started","params":{"item":{"type":"commandExecution","id":"exec-b4812e6c-c4bc-47bf-bf1c-c16cdd8c82dc","pluginId":null,"scriptPath":null,"command":"/bin/zsh -lc 'echo codly > hello.txt'","cwd":"/tmp/scratch/smoke/codex-1792971625/repo","processId":null,"source":"agent","status":"inProgress","commandActions":[{"type":"unknown","command":"echo codly > hello.txt"}],"aggregatedOutput":null,"exitCode":null,"durationMs":null},"threadId":"01a1756f-dce3-72b1-a5dd-cc0881c2cbe6","turnId":"01a1756f-dd5c-7be0-8b7c-9413e83b1f98","startedAtMs":1792971632660},"emittedAtMs":1792971632660} +{"method":"item/commandExecution/requestApproval","id":0,"params":{"kind":"command","threadId":"01a1756f-dce3-72b1-a5dd-cc0881c2cbe6","turnId":"01a1756f-dd5c-7be0-8b7c-9413e83b1f98","itemId":"exec-b4812e6c-c4bc-47bf-bf1c-c16cdd8c82dc","startedAtMs":1792971632659,"environmentId":"local","reason":"May I run the requested shell command with elevated approval?","command":"/bin/zsh -lc 'echo codly > hello.txt'","cwd":"/tmp/scratch/smoke/codex-1792971625/repo","commandActions":[{"type":"unknown","command":"echo codly > hello.txt"}],"proposedExecpolicyAmendment":["/bin/zsh","-lc","echo codly > hello.txt"],"availableDecisions":["accept",{"acceptWithExecpolicyAmendment":{"execpolicy_amendment":["/bin/zsh","-lc","echo codly > hello.txt"]}},"cancel"]}} {"method":"serverRequest/resolved","params":{"threadId":"01a1756f-dce3-72b1-a5dd-cc0881c2cbe6","requestId":0},"emittedAtMs":1792971632661} {"method":"thread/status/changed","params":{"threadId":"01a1756f-dce3-72b1-a5dd-cc0881c2cbe6","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1792971632661} -{"method":"item/completed","params":{"item":{"type":"commandExecution","id":"exec-b4812e6c-c4bc-47bf-bf1c-c16cdd8c82dc","pluginId":null,"scriptPath":null,"command":"/bin/zsh -lc 'echo codly > hello.txt'","cwd":"/private/tmp/claude-501/-Users-julien-Documents-Repos-Codly/ae7e9f7f-d897-4679-8080-c22a339ba5b7/scratchpad/smoke/codex-1792971625/repo","processId":"18199","source":"unifiedExecStartup","status":"completed","commandActions":[{"type":"unknown","command":"echo codly > hello.txt"}],"aggregatedOutput":null,"exitCode":0,"durationMs":0},"threadId":"01a1756f-dce3-72b1-a5dd-cc0881c2cbe6","turnId":"01a1756f-dd5c-7be0-8b7c-9413e83b1f98","completedAtMs":1792971632752},"emittedAtMs":1792971632754} +{"method":"item/completed","params":{"item":{"type":"commandExecution","id":"exec-b4812e6c-c4bc-47bf-bf1c-c16cdd8c82dc","pluginId":null,"scriptPath":null,"command":"/bin/zsh -lc 'echo codly > hello.txt'","cwd":"/tmp/scratch/smoke/codex-1792971625/repo","processId":"18199","source":"unifiedExecStartup","status":"completed","commandActions":[{"type":"unknown","command":"echo codly > hello.txt"}],"aggregatedOutput":null,"exitCode":0,"durationMs":0},"threadId":"01a1756f-dce3-72b1-a5dd-cc0881c2cbe6","turnId":"01a1756f-dd5c-7be0-8b7c-9413e83b1f98","completedAtMs":1792971632752},"emittedAtMs":1792971632754} {"method":"thread/tokenUsage/updated","params":{"threadId":"01a1756f-dce3-72b1-a5dd-cc0881c2cbe6","turnId":"01a1756f-dd5c-7be0-8b7c-9413e83b1f98","tokenUsage":{"total":{"totalTokens":57025,"inputTokens":56893,"cachedInputTokens":49920,"cacheWriteInputTokens":0,"outputTokens":132,"reasoningOutputTokens":0},"last":{"totalTokens":19126,"inputTokens":19066,"cachedInputTokens":18816,"cacheWriteInputTokens":0,"outputTokens":60,"reasoningOutputTokens":0},"modelContextWindow":258400}},"emittedAtMs":1792971632757} {"method":"account/rateLimits/updated","params":{"rateLimits":{"limitId":"codex","limitName":null,"normalModelSlug":null,"primary":{"usedPercent":0,"windowDurationMins":300,"resetsAt":1792982616},"secondary":{"usedPercent":0,"windowDurationMins":10080,"resetsAt":1793569416},"credits":{"hasCredits":false,"unlimited":false,"balance":"0"},"individualLimit":null,"spendControlReached":null,"planType":"plus","rateLimitReachedType":null}},"emittedAtMs":1792971632757} {"method":"item/started","params":{"item":{"type":"agentMessage","id":"msg_082e615bbdddc5f4016ade93714354819b880a6a9d6223e266","text":"","phase":"final_answer","memoryCitation":null,"delivery":null,"questions":null},"threadId":"01a1756f-dce3-72b1-a5dd-cc0881c2cbe6","turnId":"01a1756f-dd5c-7be0-8b7c-9413e83b1f98","startedAtMs":1792971633228},"emittedAtMs":1792971633229} diff --git a/crates/codly-core/src/byok.rs b/crates/codly-core/src/byok.rs index 931dcefb..1a2946d3 100644 --- a/crates/codly-core/src/byok.rs +++ b/crates/codly-core/src/byok.rs @@ -339,7 +339,7 @@ mod tests { assert!(validate_source(ByokSource::Key, false).is_err()); assert_eq!(validate_source(ByokSource::Key, true).unwrap(), ByokSource::Key); assert_eq!(validate_source(ByokSource::Off, false).unwrap(), ByokSource::Off); - assert_eq!(validate_source(cmd(" wif-token anthropic \n"), false).unwrap(), cmd("wif-token anthropic")); + assert_eq!(validate_source(cmd(" get-token anthropic \n"), false).unwrap(), cmd("get-token anthropic")); assert!(validate_source(cmd(" "), false).is_err()); assert!(validate_source(cmd("a\nb"), false).is_err()); assert!(validate_source(cmd(&"a".repeat(2049)), false).is_err()); diff --git a/crates/codly-core/src/git.rs b/crates/codly-core/src/git.rs index eae8e4af..21d27be9 100644 --- a/crates/codly-core/src/git.rs +++ b/crates/codly-core/src/git.rs @@ -791,12 +791,21 @@ impl Git { /// work is this one, and the orchestrator puts what it reports on record /// (`orchestrator/left_out.rs`). pub async fn commit_work(&self, wt: &Path, message: &str) -> Result { + self.commit_work_without(wt, message, &[]).await + } + + /// `commit_work` that also leaves out the new paths `kept_out`, as `untracked` lists + /// them (a folder ends in `/` and stands for the new files under it): they are not the + /// work this commit is for. They stay untracked. A change to a file that the branch + /// tracks is work wherever the file is, also under such a folder. The caller knows the + /// paths and puts them on record, so they are not in `left_out`. + pub async fn commit_work_without(&self, wt: &Path, message: &str, kept_out: &[String]) -> Result { let [c1, hooks, c2, fsmonitor] = Self::SAFE; let left_out = self.not_work(wt, &self.git_path(wt, "--git-dir").await?).await?; if !left_out.is_empty() { tracing::info!("commit in {}: left out: {}", wt.display(), left_out.iter().map(LeftOut::to_string).collect::>().join(", ")); } - for add in add_all_but(&left_out) { + for add in add_all_but(&left_out, kept_out) { let mut args = vec![c1, hooks, c2, fsmonitor]; args.extend(add.iter().map(String::as_str)); self.ok(wt, &args, false).await?; @@ -1082,20 +1091,24 @@ fn copied_among(record: &[String], files: &[String]) -> Vec { } /// The `git add` calls, in order, that stage everything in a worktree but the paths in -/// `left_out`: `add -A` without them. A folder that is too big is new as a whole, but a folder +/// `left_out` and the new paths `kept_out` (`commit_work_without`): `add -A` without them. +/// A folder that is too big is new as a whole, but a folder /// that Codly copied in can hold files that the branch tracks (an older branch of the same /// worktree, a file that somebody staged), and leaving the folder out leaves their changes /// out too. So with such a folder, `add -u` first takes every change to a tracked file, -/// wherever it is: only the new files of the folder stay out. -fn add_all_but(left_out: &[LeftOut]) -> Vec> { +/// wherever it is: only the new files of the folder stay out. The same for `kept_out`: a +/// path that was new when the caller listed it can be tracked by now (a merge brought a file +/// into a folder that was new before it). +fn add_all_but(left_out: &[LeftOut], kept_out: &[String]) -> Vec> { let mut all = vec!["add".to_string(), "-A".to_string()]; - if left_out.is_empty() { + if left_out.is_empty() && kept_out.is_empty() { return vec![all]; } all.extend(["--".to_string(), ".".to_string()]); - all.extend(left_out.iter().map(|l| format!(":(exclude,literal){}", l.path()))); + let paths = left_out.iter().map(LeftOut::path).chain(kept_out.iter().map(String::as_str)); + all.extend(paths.map(|path| format!(":(exclude,literal){path}"))); let copied_folder = left_out.iter().any(|l| matches!(l, LeftOut::Copied { path } if path.ends_with('/'))); - let tracked = copied_folder.then(|| vec!["add".to_string(), "-u".to_string()]); + let tracked = (copied_folder || !kept_out.is_empty()).then(|| vec!["add".to_string(), "-u".to_string()]); tracked.into_iter().chain([all]).collect() } @@ -1165,6 +1178,24 @@ impl Git { let out = self.run(wt, &["-c", "core.fsmonitor=false", "diff", "--no-index", "--no-color", "--no-ext-diff", "--no-textconv", "-U3", "--", "/dev/null", rel], true).await?; Ok(out.stdout) } + + /// All the uncommitted work of a checkout as one diff, read only: no index is written and + /// no object is stored (a private index, as `snapshot` uses, would store every changed + /// file in the repository). The tracked files against HEAD, then each new file that is + /// work (untracked, not ignored, and not what `commit_work` leaves out: a copy of Codly's, + /// a new folder or file that is too big) against nothing. The checkout must have a commit. + pub async fn uncommitted_diff(&self, wt: &Path) -> Result { + let mut out = self.read(wt, &["diff", "HEAD", "--no-color", "--no-ext-diff", "--no-textconv", "--find-renames", "-U3", "--"]).await?; + let dir = self.git_path(wt, "--git-dir").await?; + let left_out = self.not_work(wt, &dir).await?; + // A folder's path ends in `/`. + let covers = |l: &LeftOut, f: &str| l.path() == f || (l.path().ends_with('/') && f.starts_with(l.path())); + let new = split_z(&self.read(wt, &["ls-files", "-z", "--others", "--exclude-standard"]).await?); + for f in new.iter().filter(|f| !left_out.iter().any(|l| covers(l, f))) { + out.push_str(&self.diff_file(wt, f, true).await?); + } + Ok(out) + } } /// A local branch as Settings → Storage lists it. @@ -1306,7 +1337,7 @@ impl Git { Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} // nothing was ever staged there Err(e) => bail!("cannot copy the index of {}: {e}", wt.display()), } - for add in add_all_but(&left_out) { + for add in add_all_but(&left_out, &[]) { self.on_index(wt, &index, &add.iter().map(String::as_str).collect::>()).await?; } Ok((index, left_out)) @@ -2547,6 +2578,45 @@ mod tests { assert_eq!(git.untracked(&repo).await.unwrap(), ["note.txt", "out/"]); } + /// A commit can leave out new paths that are not its work: a file and a folder that were + /// in the worktree before stay untracked, with the new files under the folder, and + /// everything else is committed, a new file too. A file that the branch tracks by now + /// under that folder (a merge brought it in after the list was made) is work when it + /// changes: the commit has it. A path among them that is gone is no error. + #[tokio::test] + async fn commit_work_without_leaves_the_named_new_paths_out() { + let (_d, repo) = repo(); + let git = Git::from_process_env(); + std::fs::create_dir_all(repo.join("cache")).unwrap(); + for file in ["notes.tmp", "cache/built.txt"] { + std::fs::write(repo.join(file), "from before\n").unwrap(); + } + let before = git.untracked(&repo).await.unwrap(); + assert_eq!(before, ["cache/", "notes.tmp"]); + // After the list was made, a commit brings a tracked file into the folder that was new. + std::fs::write(repo.join("cache/schema.json"), "{}\n").unwrap(); + sh(&repo, &["add", "cache/schema.json"]); + sh(&repo, &["commit", "-qm", "schema"]); + + // The work: two tracked files changed (one of them in the old folder), a new file, + // and one more new file in the old folder. + std::fs::write(repo.join("a.txt"), "changed\n").unwrap(); + std::fs::write(repo.join("cache/schema.json"), "{\"v\": 2}\n").unwrap(); + std::fs::write(repo.join("new.txt"), "new\n").unwrap(); + std::fs::write(repo.join("cache/more.txt"), "later\n").unwrap(); + let kept_out: Vec = before.into_iter().chain(["gone.txt".to_string()]).collect(); + let snap = git.commit_work_without(&repo, "work", &kept_out).await.unwrap(); + assert_eq!((snap.commit.unwrap().files, snap.left_out), (vec!["a.txt".to_string(), "cache/schema.json".to_string(), "new.txt".to_string()], vec![])); + assert_eq!(git.read(&repo, &["show", "HEAD:cache/schema.json"]).await.unwrap().trim(), "{\"v\": 2}"); + assert_eq!(git.untracked(&repo).await.unwrap(), ["cache/built.txt", "cache/more.txt", "notes.tmp"]); + assert_eq!(std::fs::read_to_string(repo.join("notes.tmp")).unwrap(), "from before\n"); + + // Nothing but those paths is new: no commit. Without the list, they are work. + assert_eq!(git.commit_work_without(&repo, "again", &kept_out).await.unwrap().commit, None); + let all = git.commit_work(&repo, "all").await.unwrap().commit.unwrap(); + assert_eq!(all.files, ["cache/built.txt", "cache/more.txt", "notes.tmp"]); + } + /// A ref that is set again moves, where `create_ref` would refuse. #[tokio::test] async fn set_ref_moves_a_ref_that_exists() { diff --git a/crates/codly-core/src/housekeeping/connections.rs b/crates/codly-core/src/housekeeping/connections.rs index 4b7b045f..238a701f 100644 --- a/crates/codly-core/src/housekeeping/connections.rs +++ b/crates/codly-core/src/housekeeping/connections.rs @@ -190,10 +190,8 @@ impl SecretStore for KeychainStore { fn set(&self, account: &str, value: &str) -> anyhow::Result<()> { use std::io::Write; - anyhow::ensure!(!account.contains(['"', '\'', '\\', ' ', '\n']), "bad account name"); - let hex: String = value.bytes().map(|b| format!("{b:02x}")).collect(); + let cmd = add_line(account, value)?; let mut child = Command::new("security").arg("-i").stdin(Stdio::piped()).stdout(Stdio::null()).stderr(Stdio::piped()).spawn()?; - let cmd = format!("add-generic-password -U -s {KEYCHAIN_SERVICE} -a {account} -X {hex}\n"); child.stdin.take().ok_or_else(|| anyhow::anyhow!("no stdin"))?.write_all(cmd.as_bytes())?; let out = child.wait_with_output()?; anyhow::ensure!(out.status.success() && out.stderr.is_empty(), "the Keychain refused the key: {}", String::from_utf8_lossy(&out.stderr).trim()); @@ -212,6 +210,14 @@ impl SecretStore for KeychainStore { } } +/// The `security -i` line that stores `value`: hex after `-X`, so no character of the key can +/// end the word or the line. +fn add_line(account: &str, value: &str) -> anyhow::Result { + anyhow::ensure!(!account.contains(['"', '\'', '\\', ' ', '\n']), "bad account name"); + let hex: String = value.bytes().map(|b| format!("{b:02x}")).collect(); + Ok(format!("add-generic-password -U -s {KEYCHAIN_SERVICE} -a {account} -X {hex}\n")) +} + /// All slots of an entry have a key. pub fn has_keys(e: &CatalogEntry, store: &dyn SecretStore) -> bool { e.secrets.iter().all(|s| store.get(&account(e.id, s.env)).is_some()) @@ -370,6 +376,14 @@ pub(crate) mod tests { use super::*; + #[test] + fn the_keychain_line_carries_the_key_as_hex_on_one_line() { + assert_eq!(add_line("github:GITHUB_TOKEN", "a b\"\n").unwrap(), "add-generic-password -U -s codly-mcp -a github:GITHUB_TOKEN -X 612062220a\n"); + for bad in ["a b", "a\"b", "a'b", "a\\b", "a\nb"] { + assert!(add_line(bad, "k").is_err(), "{bad:?}"); + } + } + #[derive(Default)] pub struct MemoryStore(RefCell>); diff --git a/crates/codly-core/src/inbound/secrets.rs b/crates/codly-core/src/inbound/secrets.rs index 207c9ddb..91b58f72 100644 --- a/crates/codly-core/src/inbound/secrets.rs +++ b/crates/codly-core/src/inbound/secrets.rs @@ -81,6 +81,14 @@ fn plain(s: &str) -> bool { !s.is_empty() && s.len() <= 512 && s.bytes().all(|b| b.is_ascii_alphanumeric() || b"._:/+=@-".contains(&b)) } +/// The `security -i` line that stores `value` (stdin, not argv: other processes can read argv). +fn add_line(service: &str, key: &str, value: &str) -> Result { + if !plain(key) || !plain(value) { + bail!("the value contains characters the Keychain helper cannot take (use letters, digits and . _ : / + = @ -)"); + } + Ok(format!("add-generic-password -U -s {service} -a {key} -w {value}\n")) +} + impl SecretStore for Keychain { fn get(&self, key: &str) -> Result> { if !plain(key) { @@ -95,11 +103,8 @@ impl SecretStore for Keychain { } fn set(&self, key: &str, value: &str) -> Result<()> { - if !plain(key) || !plain(value) { - bail!("the value contains characters the Keychain helper cannot take (use letters, digits and . _ : / + = @ -)"); - } + let line = add_line(&self.service, key, value)?; let mut child = Command::new("security").arg("-i").stdin(Stdio::piped()).stdout(Stdio::null()).stderr(Stdio::null()).spawn()?; - let line = format!("add-generic-password -U -s {} -a {key} -w {value}\n", self.service); child.stdin.take().expect("piped").write_all(line.as_bytes())?; child.wait()?; // `-i` exits 0 even when a command failed, so read it back if self.get(key)?.as_deref() != Some(value) { @@ -223,6 +228,14 @@ mod tests { assert!(ct_eq(b"", b"")); } + #[test] + fn the_keychain_line_takes_plain_words_only() { + assert_eq!(add_line("dev.codly.inbound", "slack_bot", "xoxb-1-abc.DEF_ghi").unwrap(), "add-generic-password -U -s dev.codly.inbound -a slack_bot -w xoxb-1-abc.DEF_ghi\n"); + for (key, value) in [("a b", "v"), ("k", "two words"), ("k", "a\nadd-generic-password"), ("k", "\"q\""), ("", "v"), ("k", "")] { + assert!(add_line("s", key, value).is_err(), "{key:?} {value:?}"); + } + } + #[test] fn secrets_do_not_debug_print() { assert_eq!(format!("{:?}", Secret::new("hunter2")), "Secret(***)"); diff --git a/crates/codly-core/src/model.rs b/crates/codly-core/src/model.rs index d8d28944..333c843b 100644 --- a/crates/codly-core/src/model.rs +++ b/crates/codly-core/src/model.rs @@ -1065,6 +1065,12 @@ pub struct BackgroundTask { pub kind: String, /// The command, or what the helper was asked to do. pub description: String, + /// When the first list that named it came (ms), as the adapter saw it: later lists keep + /// it, so a row read again from a later list still knows how long the work runs. None + /// from an adapter that does not say it, and in rows written before it was kept. + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub started_at: Option, } /// Something that left the list of a run's background work (`EventKind::BackgroundTasks`). @@ -1573,6 +1579,19 @@ pub enum EventKind { ApprovalRequested { approval: Approval, }, + /// What you said with your answer to a request, when it carried words: the note of a "no", + /// the answer to a question, or that you changed a plan before you accepted it. It comes + /// just before the `ApprovalResolved` of that answer, and only for an answer that went to + /// the agent. A request answered without words has no such row. + ApprovalSaid { + approval_id: Id, + /// What you told the agent to do instead (at most 2000 characters). + note: Option, + /// Your answers to a question, on one line (at most 500 characters). + answer: Option, + /// The plan was accepted with your text in place of the agent's. + plan_changed: bool, + }, ApprovalResolved { approval_id: Id, status: ApprovalStatus, @@ -1752,6 +1771,7 @@ impl EventKind { EventKind::FilesChanged { .. } => "files_changed", EventKind::PlanUpdated { .. } => "plan_updated", EventKind::ApprovalRequested { .. } => "approval_requested", + EventKind::ApprovalSaid { .. } => "approval_said", EventKind::ApprovalResolved { .. } => "approval_resolved", EventKind::UsageUpdated { .. } => "usage_updated", EventKind::RateLimit { .. } => "rate_limit", diff --git a/crates/codly-core/src/orchestrator/agent_git.rs b/crates/codly-core/src/orchestrator/agent_git.rs index 813ad1b4..04f6a3d8 100644 --- a/crates/codly-core/src/orchestrator/agent_git.rs +++ b/crates/codly-core/src/orchestrator/agent_git.rs @@ -4,13 +4,20 @@ //! fixed list (the only variable is the `-C` directory, the agent's own worktree), and the //! worktree is checked to be a real linked worktree of the repo before git runs in it (an agent //! can rewrite its `.git` pointer; see `git.rs`). The parsers are pure and unit-tested. +//! +//! `agent_diff` is a 1:1 agent's whole work for the Changes room: what its branch and its files +//! add to the branch it will merge into, read the way a checkpoint reads a worktree (a private +//! index), so neither the worktree nor its index changes. Your own checkout (an agent that +//! works in your project folder) is only read: no index and no object is written there. -use std::path::Path; +use std::path::{Path, PathBuf}; +use anyhow::{anyhow, bail}; use serde::{Deserialize, Serialize}; use ts_rs::TS; use super::Core; +use crate::model::Role; /// One changed path in the worktree (`git status --porcelain`). #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)] @@ -130,6 +137,41 @@ impl Core { } Ok(view) } + + /// "All changes" of a 1:1 agent: its commits, its uncommitted edits and its new files, as + /// one diff from where its branch left the branch checked out in your project folder (the + /// branch its merge goes into) to its files as they are. Its files are read into a private + /// index (`Git::snapshot`), as a checkpoint reads them: the changed files are stored as git + /// objects, and neither the worktree nor its index changes. An agent that works in your + /// project folder itself: its uncommitted changes against HEAD and its new files, read + /// without writing anything (`Git::uncommitted_diff`). Either way, what a commit of Codly's + /// leaves out (a huge new folder or file) is not in it. No worktree: an empty diff. + pub async fn agent_diff(&self, agent_id: &str) -> anyhow::Result { + let inner = &self.inner; + let agent = inner.agent(agent_id)?; + if agent.role != Role::Solo { + bail!("only a 1:1 agent has changes of its own; a task's changes are in its plan"); + } + let Some(wt) = agent.worktree.as_deref().map(PathBuf::from).filter(|w| w.is_dir()) else { return Ok(String::new()) }; + let ws_id = inner.store.agent_workspace(agent_id)?.ok_or_else(|| anyhow!("{} is in no office", agent.name))?; + let ws = inner.store.workspace(&ws_id)?.ok_or_else(|| anyhow!("unknown workspace {ws_id}"))?; + let repo = PathBuf::from(&ws.repo_path); + let git = &inner.git; + let target = git.head(&repo).await?.ok_or_else(|| anyhow!("your project has no commit yet, so there is nothing to compare with"))?; + if wt == repo { + // Your own checkout: read only, so no object of it goes into your repository. + return git.uncommitted_diff(&repo).await; + } + // An agent can rewrite its `.git` pointer (see `git.rs`): no git runs in such a worktree. + git.check_worktree(&repo, &wt).await?; + let tip = git.head(&wt).await?.ok_or_else(|| anyhow!("{}'s worktree has no commit", agent.name))?; + let base = git + .merge_base(&repo, &target, &tip) + .await? + .ok_or_else(|| anyhow!("{}'s branch shares no history with your checked-out branch", agent.name))?; + let now = git.worktree_tree(&wt).await?; + git.diff_trees(&wt, &base, &now).await + } } #[cfg(test)] diff --git a/crates/codly-core/src/orchestrator/approvals.rs b/crates/codly-core/src/orchestrator/approvals.rs index fc1540f1..6c61242a 100644 --- a/crates/codly-core/src/orchestrator/approvals.rs +++ b/crates/codly-core/src/orchestrator/approvals.rs @@ -40,13 +40,18 @@ //! when "Sandbox Claude's shell" is on in Settings. That sandbox is a second wall, not a way //! around these rules: Codly starts it with `autoAllowBashIfSandboxed: false` //! (`adapters/claude.rs`, `settings_json`), so a sandboxed command still sends its request -//! and is judged here like any other. The other CLIs have no sandbox. +//! and is judged here like any other. Recorded with Claude Code 2.1.311: with auto-allow off, +//! the same commands ask with the sandbox as without it (fixtures `r5-commands-noauto` +//! against `r5-commands-off`, and the same pair in manual mode; section 5 of +//! docs/research/cli-claude-stream-json-2.1.311-part3.md). The one request the sandbox adds +//! is its own, for a host a command reaches. The other CLIs have no sandbox. //! //! The shell checks err toward asking: a "read-only command" is a bare program name (no path, //! no `VAR=x` prefix, no wrapper, no `$` expansion) whose arguments use none of its options //! that write or run something; risks look through wrappers (`timeout 5 git push`) and nested //! `sh -c`; a word whose value the shell computes (`$HOME/x`) counts as outside the worktree. +use std::collections::{HashMap, HashSet}; use std::path::{Component, Path, PathBuf}; use std::sync::RwLock; @@ -217,7 +222,7 @@ pub fn rule_offer(a: &Approval, ctx: &PolicyCtx) -> ApprovalRuleOffer { let download = detected.iter().any(|r| r == PACKAGE_INSTALL || r == NPX_DOWNLOAD) && !detected.iter().any(|r| r == "network"); let by_prefix = |r: &String| [PACKAGE_INSTALL, NPX_DOWNLOAD, GIT_WRITE].contains(&r.as_str()) || (r == "network" && download); let by_exact = |r: &String| r == "network" || by_prefix(r); - if !a.risks.iter().chain(&detected).all(by_exact) || own_account(command, 0) || checkout_loss(&a.subject, ctx).is_some() { + if !a.risks.iter().chain(&detected).all(by_exact) || own_account(command) || checkout_loss(&a.subject, ctx).is_some() { return none; } let prefix = if a.risks.iter().chain(&detected).all(by_prefix) { rule_prefix(command) } else { None }; @@ -259,20 +264,114 @@ const MANY_TARGETS: &[&str] = &["make", "just", "task", "gradle", "mvn"]; const OWN_ACCOUNT: &[&str] = &["config", "login", "logout", "publish"]; /// Does the line run one of the `OWN_ACCOUNT` subcommands (`cargo login x`, -/// `npm config set …`, `npm c set …`, `git config …`), behind a wrapper or `sh -c` too? -fn own_account(cmd: &str, depth: u8) -> bool { +/// `npm config set …`, `npm c set …`, `git config …`), behind a wrapper, `sh -c` or `env -S` +/// too, and behind a program that starts another (`pnpm exec git config …`, +/// `npx -c 'git config …'`, `uv run git config …`)? A line that starts more commands than +/// `MAX_STARTED` is not read to the end and gets yes, so nothing is offered for it, as +/// `command_risks` says "runs dynamic code" for it. +fn own_account(cmd: &str) -> bool { + line_own_account(cmd, 0, &mut 0) +} + +/// `own_account` for a line that stands `depth` lines deep, with the count of the commands +/// that the line around it started already. +fn line_own_account(cmd: &str, depth: u8, started: &mut usize) -> bool { parse(cmd).segments.iter().any(|seg| { let texts: Vec = seg.iter().map(|w| w.text.clone()).collect(); - let Some((prog, args)) = classify::command_start(&texts).and_then(|i| texts[i..].split_first()) else { return false }; + runs_own_account(&texts, depth, started) + }) +} + +/// `own_account` for the words of one command, and for every command they run +/// (`each_command`). +fn runs_own_account(words: &[String], depth: u8, started: &mut usize) -> bool { + // Deeper than this, `command_risks` says "runs dynamic code": nothing is offered. + let line = |inner: &str, _: bool, started: &mut usize| (depth < 3 && (one_more(started) || line_own_account(inner, depth + 1, started))).then_some(()); + let own = |prog: &str, args: &[String]| { + // Behind an option's value too (`npm --prefix web config set …`). + let subs = if prog == "git" { git_sub(args).0.into_iter().collect() } else { subcommands(prog, args) }; + (SUBCOMMAND_TOOLS.contains(&prog) && subs.iter().any(|sub| OWN_ACCOUNT.contains(sub) || names_config(prog, sub))).then_some(()) + }; + each_command(words, started, Some(()), own, line).is_some() +} + +/// Reads each command that the words of one simple command run: the program behind its +/// wrappers and behind an `env` in front (`env_run`), every command that program starts +/// (`started_by`), and the ones those start in turn. `command` gets each program by its name, +/// with its arguments: a part of `words` that ends where `words` end. A line for a shell +/// (`sh -c`, `env -S`, `npx -c`) goes to `line`, told whether a program started it +/// (`started_by`), with the count of started commands. The first answer ends the reading. +/// +/// Each command is read once. A command a program starts is a part of these same words, and +/// the same part is found again behind each program in front of it (`uv run uv run uv run x`: +/// the last `uv run x` behind the first `uv` and behind the second), so the work stays small +/// on a long line, as in `command_risks`. Once more than `MAX_STARTED` commands are started, +/// the answer is `past`; when that is None, what the programs start is not looked for any +/// more, and the commands found already are still read. +fn each_command( + words: &[String], + started: &mut usize, + past: Option, + mut command: impl FnMut(&str, &[String]) -> Option, + mut line: impl FnMut(&str, bool, &mut usize) -> Option, +) -> Option { + // The commands to read, and where each one stands in `words` (the same place is the same + // command). + let mut commands = vec![words]; + let mut places = HashSet::from([std::ptr::from_ref(words)]); + let (mut read, mut past_count) = (0, false); + while let Some(&words) = commands.get(read) { + read += 1; + let start = match classify::command_start(words) { + Some(start) => Some(start), + None => { + let run = env_run(words); + if let Some(found) = run.line.and_then(|inner| line(&inner, false, started)) { + return Some(found); + } + run.program + } + }; + let Some((prog, args)) = start.and_then(|start| words[start..].split_first()) else { continue }; let prog = basename(prog); if classify::SHELLS.contains(&prog) { - // Deeper than this, `command_risks` says "runs dynamic code": nothing is offered. - return matches!(classify::shell_run(args), ShellRun::Command(inner) if depth < 3 && own_account(inner, depth + 1)); + if let ShellRun::Command(inner) = classify::shell_run(args) + && let Some(found) = line(inner, false, started) + { + return Some(found); + } + continue; } - // Behind an option's value too (`npm --prefix web config set …`). - let subs = if prog == "git" { git_sub(args).0.into_iter().collect() } else { subcommands(prog, args) }; - SUBCOMMAND_TOOLS.contains(&prog) && subs.iter().any(|sub| OWN_ACCOUNT.contains(sub) || names_config(prog, sub)) - }) + if let Some(found) = command(prog, args) { + return Some(found); + } + if past_count { + continue; + } + for next in started_by(prog, args) { + match next { + Started::Program(next) => { + if !places.insert(std::ptr::from_ref(next)) { + continue; + } + if one_more(started) { + if past.is_some() { + return past; + } + past_count = true; + break; + } + commands.push(next); + } + Started::ShellLine(inner) => { + if let Some(found) = line(&inner, true, started) { + return Some(found); + } + } + } + } + } + None } /// Do these words only say that something runs, so the next word names what @@ -317,8 +416,14 @@ fn rule_prefix(cmd: &str) -> Option { if prog == "git" && (!GIT_PREFIXES.contains(&sub) || git_forced(sub, rest)) { return None; } + let more_runs = if prog == "make" { + let args: Vec = seg[1..].iter().map(|w| w.text.clone()).collect(); + !make_builds_only(sub, &args) + } else { + MANY_TARGETS.contains(&prog) && rest.iter().any(|w| !w.text.starts_with('-')) + }; // `mix do a + b` runs several tasks, as a second target does. - if (MANY_TARGETS.contains(&prog) && rest.iter().any(|w| !w.text.starts_with('-'))) || (prog == "mix" && sub == "do") { + if more_runs || (prog == "mix" && sub == "do") { return None; } let mut prefix = vec![prog, sub]; @@ -327,7 +432,9 @@ fn rule_prefix(cmd: &str) -> Option { // A program with subcommands of its own, started by another (`pnpm exec npm …`, // `uv run cargo …`): these words would cover everything it can do, which the prefix // of the plain command (`npm install`) never does. - if starts_a_program(&prefix) && SUBCOMMAND_TOOLS.contains(&next) { + // The same for a wrapper or a shell that starts yet another program (`uv run env …`, + // `poetry run nice …`, `uv run sh …`): only the exact command is offered. + if starts_a_program(&prefix) && (SUBCOMMAND_TOOLS.contains(&next) || classify::is_wrapper(next) || classify::SHELLS.contains(&next)) { return None; } prefix.push(next); @@ -335,6 +442,20 @@ fn rule_prefix(cmd: &str) -> Option { Some(prefix.join(" ")) } +/// Does a `make` line build this one target and nothing else, with no option beside it but +/// those that say how to build, not what: `-j` with its count (`-j 8`, `-j8`, `--jobs 8`), +/// `-k` and `-s` with their long names? The words are read as `build_words` reads them, so +/// the count after `-j` is no second target. `-C dir`, `-f file`, a variable (`V=1`) and +/// every other option can change what runs: such a line gives no prefix. +fn make_builds_only(target: &str, args: &[String]) -> bool { + let (targets, options) = build_words("make", args); + let plain = |option: &&str| match option.strip_prefix("--") { + Some(long) => ["jobs", "keep-going", "silent", "quiet"].contains(&long.split('=').next().unwrap_or(long)), + None => option[1..].chars().all(|c| "jks".contains(c) || c.is_ascii_digit()), + }; + targets == [target] && options.iter().all(plain) +} + /// Is the next word, after these words that only say that something runs (`names_what_runs`), /// the name of a program (`pnpm exec `, `uv run `) and not of a script, a /// package or a subcommand (`npm run + reach, so it is told here. `global`: App mounts two of these inside a nested {#if}. While it + goes Svelte makes it inert: then it is closing and no key is its own any more (lib/util/modal.ts `CLOSING`). -->