Skip to content
Back to search

plannotator

MarketplaceWorks with Claude CodeGitHub

Annotate and review coding agent plans and code diffs visually, share with your team, send feedback to agents with one click.

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today

Check it deeper on your machine

It has changed since its scan on 11 Nov 2026. Its scripts were only partly scanned.

As a Claude Code plugin, install it and then ask Claude Code:

/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/backnotprop/plannotator with scanskillsafety

Or from a terminal, clone it and run it:

git clone https://github.com/keithmackay/scanskillsafety-skill ~/.claude/skills/scanskillsafetynode ~/.claude/skills/scanskillsafety/cli.cjs --deep 'https://github.com/backnotprop/plannotator'

It checks the exact commit: every file, its packages against OSV (api.osv.dev), how it compares with this page's scan (findsafeskills.com receives the repository's address), and, if you agree, Claude reading every file with your own Claude subscription. It never runs the code.

Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/backnotprop-plannotator/badge.svg)](/listings/backnotprop-plannotator)

HTML

<a href="/listings/backnotprop-plannotator"><img src="/api/listings/backnotprop-plannotator/badge.svg" alt="findsafeskills safety rating" /></a>

Install

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

These steps run a script from the network that findsafeskills does not scan.

One installer covers almost every agent. It installs the `plannotator` binary, auto-detects your installed agents, and configures hooks, skills, and slash commands for each:

# macOS / Linux / WSL
curl -fsSL https://plannotator.ai/install.sh | bash
# Windows PowerShell
irm https://plannotator.ai/install.ps1 | iex

The installer downloads the binary from GitHub Releases. A full install can also contact GitHub for release resolution and agent files, Ataraxy-Labs/sem for the optional `sem` sidecar, and npm for Pi, selected extra skills, or the managed agent-terminal runtime. Pinning `--version` skips only GitHub API release resolution, not the release download. See the [privacy policy](https://plannotator.ai/privacy) for the complete network boundaries.

Want just the binary and nothing else? Pass `--minimal` (or export `PLANNOTATOR_MINIMAL=1`) to install only the `plannotator` binary to `~/.local/bin`, skipping every skill, hook, slash command, and per-agent config:

curl -fsSL https://plannotator.ai/install.sh | bash -s -- --minimal

Then finish the step for your agent:

| Agent | After the installer | Details | |---|---|---| | **Amp** | Copy [`plannotator.ts`](apps/amp-plugin/plannotator.ts) into `~/.config/amp/plugins/`, then `plugins: reload`. Workflows live in the command palette. | [README](apps/amp-plugin/README.md) | | **Claude Code** | `/plugin marketplace add backnotprop/plannotator`, then `/plugin install plannotator@plannotator`. Restart Claude Code. | [README](apps/hook/README.md) | | **Codex** | Nothing. Plan review is enabled automatically via Codex's experimental `Stop` hook (macOS/Linux/WSL; on native Windows, Codex hooks are experimental and the installer prints manual setup steps). `$plannotator-review`, `$plannotator-annotate`, and `$plannotator-last` skills included. | [README](apps/codex/README.md) | | **Copilot CLI** | `/plugin marketplace add backnotprop/plannotator`, then `/plugin install plannotator-copilot@plannotator`. Restart. Plan review activates in plan mode (`Shift+Tab`). | [README](apps/copilot/README.md) | | **Droid** | `droid plugin marketplace add https://github.com/backnotprop/plannotator`, then `droid plugin install plannotator@plannotator`. Commands only, no plan interception yet. | [README](apps/droid-plugin/README.md) | | **Gemini CLI** | Nothing. The hook, policy, and slash commands are configured automatically. Requires Gemini CLI 0.36.0+. | [README](apps/gemini/README.md) | | **Kiro CLI** | Nothing. Skills and an example agent are installed automatically. Try `kiro-cli chat --agent plannotator`. | [README](apps/kiro-cli/README.md) | | **OpenCode** | Add `"plugin": ["@plannotator/opencode@latest"]` to `opencode.json`. Restart OpenCode. | [README](apps/opencode-plugin/README.md) | | **Pi** | Skip the installer. Just `pi install npm:@plannotator/pi-extension`. Start Pi with `--plan`, or toggle with `/plannotator-plan-mode`. | [README](apps/pi-extension/README.md) |

**Updating:** run the installer again for the binary and slash commands. Claude Code plugin: `claude plugin marketplace update plannotator`, then `claude plugin update plannotator@plannotator`, then restart Claude Code (refreshing the marketplace alone does not update the plugin). Pi: `pi update --extensions` (a plain `pi update` updates only Pi).

On Claude Code 2.1.287 or newer, plan review, code review and annotate don't make Claude wait: Claude ends its turn and your decision arrives later as a message. Set `PLANNOTATOR_CLAUDE_MOD=0` to go back to the classic flow.

Full walkthroughs live in the [installation docs](https://docs.plannotator.ai/open-source/start/installation).

Uninstall

The safe default removes recognized Plannotator-installed components and keeps your local plans, history, drafts, guides, and settings:

plannotator uninstall

Use `--purge` for a full removal of known local Plannotator data as well:

plannotator uninstall --purge

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

.claude-plugin/marketplace.json · Manifest · 13 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.

  1. {
  2. "name": "plannotator",
  3. "owner": {
  4. "name": "backnotprop"
  5. },
  6. "plugins": [
  7. {
  8. "name": "plannotator",
  9. "source": "./apps/hook",
  10. "description": "Interactive Plan Review: Mark up and refine your plans using a UI, easily share for team collaboration, automatically integrates with plan mode hooks."
  11. }
  12. ]
  13. }
README.md · README · 602 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.

  1. <p align="center">
  2. <img src=".github/assets/banner.webp" alt="Plannotator" width="640" />
  3. </p>
  4. <p align="center">
  5. <strong>Everything you need to annotate and stay in the loop with your agents</strong><br/>
  6. <strong>Inbox Surface • Artifacts • Code Review</strong><br/>
  7. <sub>Annotate plans, specs, markdown, HTML, and other interactive artifacts. Review diffs and PRs. Send feedback to your agent.</sub>
  8. </p>
  9. <p align="center">
  10. <img src=".github/assets/icons/amp.svg" alt="Amp" title="Amp" height="28" />&nbsp;&nbsp;
  11. <img src=".github/assets/icons/claude.svg" alt="Claude Code" title="Claude Code" height="28" />&nbsp;&nbsp;
  12. <img src=".github/assets/icons/codex.png" alt="Codex" title="Codex" height="28" />&nbsp;&nbsp;
  13. <picture>
  14. <source media="(prefers-color-scheme: dark)" srcset=".github/assets/icons/copilot-dark.svg" />
  15. <img src=".github/assets/icons/copilot-light.svg" alt="Copilot CLI" title="Copilot CLI" height="28" />
  16. </picture>&nbsp;&nbsp;
  17. <img src=".github/assets/icons/droid.png" alt="Droid" title="Droid" height="28" />&nbsp;&nbsp;
  18. <img src=".github/assets/icons/gemini.png" alt="Gemini CLI" title="Gemini CLI" height="28" />&nbsp;&nbsp;
  19. <img src=".github/assets/icons/kiro.svg" alt="Kiro" title="Kiro" height="28" />&nbsp;&nbsp;
  20. <picture>
  21. <source media="(prefers-color-scheme: dark)" srcset=".github/assets/icons/opencode-dark.svg" />
  22. <img src=".github/assets/icons/opencode-light.svg" alt="OpenCode" title="OpenCode" height="28" />
  23. </picture>&nbsp;&nbsp;
  24. <picture>
  25. <source media="(prefers-color-scheme: dark)" srcset=".github/assets/icons/pi-dark.svg" />
  26. <img src=".github/assets/icons/pi-light.svg" alt="Pi" title="Pi" height="28" />
  27. </picture>
  28. </p>
  29. <p align="center">
  30. <a href="#plannotator-inbox">Plannotator Inbox</a> · <a href="https://plannotator.ai/">Official site</a> · <a href="https://plannotator.ai/code-review">Code Review</a> · <a href="https://github.com/plannotator/effective-html">Visual HTML Skills</a> · <a href="#herdr-annotate-plannotator-in-the-terminal">Herdr Annotate</a> · <a href="https://www.youtube.com/watch?v=a_AT7cEN_9I">(Legacy) Plan Mode</a>
  31. </p>
  32. # Plannotator
  33. **⭐️ NEW:** [Plannotator Inbox](https://plannotator.ai/inbox/) is the missing review layer between you and multi-agent work. It surfaces decisions, prototypes, variations, plans, and everything you need to stay in the loop. Works with all coding agents and personal assistants.
  34. Plannotator is a local, browser-based review surface for AI coding agents: Claude Code, Codex, Copilot CLI, Gemini CLI, OpenCode, Kiro, Droid, Amp, DeepSeek Harness, and Pi. Plannotator Inbox also works with personal assistants (Grok Bot, Muse, Hermes, OpenClaw).
  35. **It plugs directly into your agent** through plugins, hooks and commands. When the agent proposes a decision, plan, html, or finishes working, the app opens in your browser and you mark it up, comment, and send feedback directly to the agent for it to act on it.
  36. <table>
  37. <tr>
  38. <td width="40%" valign="middle">
  39. ### Review documents, plans, and agent messages
  40. Annotate plans, specs, messages, html, then send the feedback to your agent.
  41. </td>
  42. <td width="60%">
  43. <img src=".github/assets/annotate.webp" alt="Annotate UI with inline annotations" width="100%" />
  44. </td>
  45. </tr>
  46. <tr>
  47. <td width="40%" valign="middle">
  48. ### Code Review
  49. Review local changes or remote PRs. Comment on diffs, suggest code. Your comments go back to the agent. Works with Git, GitButler, Jujutsu (`jj`), Perforce (`p4`), GitHub, and GitLab.
  50. For a big change, start a [guided review](https://plannotator.ai/code-review#guided-review): an agent sorts the diff into chapters, the most important first.
  51. </td>
  52. <td width="60%">
  53. <img src=".github/assets/review.webp" alt="Code review with file tree and side-by-side diff" width="100%" />
  54. </td>
  55. </tr>
  56. </table>
  57. ## Plannotator Inbox
  58. <p align="center">
  59. <a href="https://plannotator.ai/inbox/">
  60. <picture>
  61. <source media="(prefers-color-scheme: dark)" srcset=".github/assets/inbox-dark.webp" />
  62. <img src=".github/assets/inbox-light.webp" alt="Plannotator Inbox on a desktop and a phone: threads from several agents grouped by what each needs, a question with picture choices open beside the list, and a question with an attached chart on the phone" width="720" />
  63. </picture>
  64. </a>
  65. </p>
  66. <p align="center">
  67. <a href="https://plannotator.ai/assets/inbox-film.mp4"><strong>Watch the demo</strong></a> · <a href="https://plannotator.ai/inbox/">More on the Inbox</a> · <a href="https://plannotator.ai/docs/reference/inbox/">Docs</a>
  68. </p>
  69. The Plannotator Inbox is one local window where your agents leave you messages, questions, files, and guided reviews while they keep working. Answer a question with a click, annotate a file, and press Send when you can. Nothing holds an agent session open while you do, and your reply goes back to the session that asked.
  70. ```
  71. plannotator inbox
  72. ```
  73. Claude Code, Pi, and OpenCode connect through Plannotator's plugins, and your replies arrive as their next turn. Any other agent reaches it over MCP with `plannotator inbox mcp`, and `plannotator inbox --help` is the guide an agent reads.
  74. ## Herdr Annotate: Plannotator in the Terminal
  75. <p align="center">
  76. <a href="https://github.com/plannotator/herdr-annotate">
  77. <img src=".github/assets/herdr-annotate-banner.svg" alt="Herdr Annotate" width="300" align="middle" />
  78. </a>
  79. &nbsp;&nbsp;
  80. <img src=".github/assets/herdr-annotate.png" alt="Plannotator TUI annotating a markdown folder in the terminal" width="480" align="middle" />
  81. </p>
  82. [Herdr Annotate](https://github.com/plannotator/herdr-annotate) brings Plannotator-style review to the terminal: annotate terminal text, review whole Markdown documents and your coding agent's replies inside [Herdr](https://herdr.dev), and send the feedback straight back to the agent as its next message. Works with Claude Code, Codex, Pi, Copilot CLI, and Droid replies. Annotations are saved in the Plannotator data directory, so terminal reviews and app reviews compound.
  83. ```
  84. herdr plugin install plannotator/herdr-annotate
  85. ```
  86. Prefer it standalone? [Plannotator TUI](https://github.com/plannotator/plannotator-tui) powers the document review and runs without Herdr: `brew install plannotator/tap/plannotator-tui`.
  87. ## HTML artifacts, live sites, and guided reviews
  88. <table>
  89. <tr>
  90. <td width="40%" valign="middle">
  91. ### Annotate HTML artifacts and live sites
  92. Annotate rendered HTML files, or any site running on your machine. A local address opens your app live through a local proxy: you comment on the real page, and hot reload keeps working.
  93. `plannotator annotate http://localhost:5173`
  94. </td>
  95. <td width="60%">
  96. <img src=".github/assets/html.webp" alt="Annotating a rendered HTML artifact" width="100%" />
  97. </td>
  98. </tr>
  99. <tr>
  100. <td width="40%" valign="middle">
  101. ### Guided reviews
  102. In code review, press **Guide** (or `Cmd/Ctrl+Shift+G`) and an agent sorts the diff into chapters: the heart of the change first, then its effects, then the glue. Each chapter puts a short overview next to the real diff. Comments you leave there go back to the agent with the rest of your review. [More on guided reviews](https://plannotator.ai/code-review#guided-review)
  103. </td>
  104. <td width="60%">
  105. <img src=".github/assets/guided-review.webp" alt="A guided review chapter: an overview of the change on the left, the annotatable diff on the right" width="100%" />
  106. </td>
  107. </tr>
  108. </table>
  109. ---
  110. ## Commands
  111. <sub>On Codex, swap the slash commands for `!plannotator …` (e.g. `!plannotator review`) or the `$plannotator-*` skills.</sub>
  112. ### Annotate
  113. ```
  114. /plannotator-annotate README.md # Local markdown file
  115. /plannotator-annotate src/ # Browse and annotate files in a folder
  116. /plannotator-annotate https://docs.rs/… # Fetch and annotate any URL
  117. /plannotator-annotate report.html --render-html # Render HTML as-is instead of converting
  118. /plannotator-last # Annotate the agent's last message
  119. ```
  120. Need a realistic document to try? Copy the [product requirements document template and filled example](https://docs.plannotator.ai/templates/product-requirements-document) as Markdown.
  121. ### Code review
  122. ```
  123. /plannotator-review # Review uncommitted changes
  124. /plannotator-review <github-pr-url> # Review a GitHub pull request
  125. /plannotator-review <gitlab-mr-url> # Review a GitLab merge request
  126. plannotator review --gitbutler # Review an active GitButler workspace
  127. plannotator review --patch-file reading.diff # Review a static caller-supplied unified diff
  128. ```
  129. GitButler users can review the whole workspace, one stack, or one branch layer. See the [GitButler workflow guide](https://docs.plannotator.ai/open-source/workflows/gitbutler).
  130. ### Plan mode
  131. No command needed. Plan mode is wired in through each harness's hooks. Any time your agent creates a plan, the markdown review surface opens for you.
  132. ### CLI
  133. ```
  134. plannotator sessions # List active Plannotator sessions
  135. plannotator sessions --open 1 # Reopen a session in the browser
  136. plannotator archive # Browse saved plan decisions read-only
  137. ```
  138. ---
  139. ## AI built in
  140. Ask AI about anything you're reviewing, or launch AI reviews that post comments to the diff.
  141. ---
  142. ## Sharing
  143. Send a plan as a link. A teammate annotates it, and you import their feedback for your agent.
  144. Small shares live in the link itself. Large ones are encrypted before upload and expire after 7 days. Anyone with the full link can read it. Turn sharing off with `PLANNOTATOR_SHARE=disabled`. [How sharing works](https://docs.plannotator.ai/open-source/workflows/sharing)
  145. <p align="center">
  146. <a href="https://plannotator.ai/workspaces">
  147. <picture>
  148. <source media="(prefers-color-scheme: dark)" srcset=".github/assets/workspaces-dark.png" />
  149. <img src=".github/assets/workspaces-light.png" alt="Plannotator Workspaces: several cursors working in one shared space" width="720" />
  150. </picture>
  151. </a>
  152. </p>
  153. <p align="center">
  154. For teams: <a href="https://plannotator.ai/workspaces"><strong>join the Workspaces waitlist</strong></a>
  155. </p>
  156. ---
  157. ## Install
  158. One installer covers almost every agent. It installs the `plannotator` binary, auto-detects your installed agents, and configures hooks, skills, and slash commands for each:
  159. ```bash
  160. # macOS / Linux / WSL
  161. curl -fsSL https://plannotator.ai/install.sh | bash
  162. ```
  163. ```powershell
  164. # Windows PowerShell
  165. irm https://plannotator.ai/install.ps1 | iex
  166. ```
  167. The installer downloads the binary from GitHub Releases. A full install can also contact GitHub for release resolution and agent files, and npm for Pi, selected extra skills, or the managed agent-terminal runtime. Pinning `--version` skips only GitHub API release resolution, not the release download. See the [privacy policy](https://plannotator.ai/privacy) for the complete network boundaries.
  168. Want just the binary and nothing else? Pass `--minimal` (or export `PLANNOTATOR_MINIMAL=1`) to install only the `plannotator` binary to `~/.local/bin`, skipping every skill, hook, slash command, and per-agent config:
  169. ```bash
  170. curl -fsSL https://plannotator.ai/install.sh | bash -s -- --minimal
  171. ```
  172. Then finish the step for your agent:
  173. | Agent | After the installer | Details |
  174. |---|---|---|
  175. | **Amp** | Copy [`plannotator.ts`](apps/amp-plugin/plannotator.ts) into `~/.config/amp/plugins/`, then `plugins: reload`. Workflows live in the command palette. | [README](apps/amp-plugin/README.md) |
  176. | **Claude Code** | `/plugin marketplace add backnotprop/plannotator`, then `/plugin install plannotator@plannotator`. Restart Claude Code. | [README](apps/hook/README.md) |
  177. | **Codex** | Nothing. Plan review is enabled automatically via Codex's experimental `Stop` hook (macOS/Linux/WSL; on native Windows, Codex hooks are experimental and the installer prints manual setup steps). `$plannotator-review`, `$plannotator-annotate`, and `$plannotator-last` skills included. | [README](apps/codex/README.md) |
  178. | **Copilot CLI** | `/plugin marketplace add backnotprop/plannotator`, then `/plugin install plannotator-copilot@plannotator`. Restart. Plan review activates in plan mode (`Shift+Tab`). | [README](apps/copilot/README.md) |
  179. | **DeepSeek Harness** | Add `@plannotator/dsh` on DSH's Plugins page, or run `dsh plugin --profile <profile> add @plannotator/dsh`. Plan review opens on `exit_plan_mode`. The plugin adds `/plannotator-review`, `/plannotator-annotate` and `/plannotator-last`, which open without blocking the session. | [README](apps/dsh-plugin/README.md) |
  180. | **Droid** | `droid plugin marketplace add https://github.com/backnotprop/plannotator`, then `droid plugin install plannotator@plannotator`. Commands only, no plan interception yet. | [README](apps/droid-plugin/README.md) |
  181. | **Gemini CLI** | Nothing. The hook, policy, and slash commands are configured automatically. Requires Gemini CLI 0.36.0+. | [README](apps/gemini/README.md) |
  182. | **Kiro CLI** | Nothing. Skills and an example agent are installed automatically. Try `kiro-cli chat --agent plannotator`. | [README](apps/kiro-cli/README.md) |
  183. | **OpenCode** | Add `"plugin": ["@plannotator/opencode@latest"]` to `opencode.json`. Restart OpenCode. | [README](apps/opencode-plugin/README.md) |
  184. | **Pi** | Skip the installer. Just `pi install npm:@plannotator/pi-extension`. Start Pi with `--plan`, or toggle with `/plannotator-plan-mode`. | [README](apps/pi-extension/README.md) |
  185. | **T3 Code** | For Claude threads in T3: run `plannotator t3 --help` and follow its two steps (sign in to T3 once, add the `--t3` MCP entry). Your Inbox replies then arrive in the thread as new turns. | [README](packages/t3-code/README.md) |
  186. **Updating:** run the installer again for the binary and slash commands. It also updates an installed Claude Code plugin when the `claude` command is on your PATH (opt out with `--skip-claude-plugin`); otherwise run `claude plugin marketplace update plannotator`, then `claude plugin update plannotator@plannotator`, then restart Claude Code (refreshing the marketplace alone does not update the plugin). Pi: `pi update --extensions` (a plain `pi update` updates only Pi).
  187. On Claude Code 2.1.287 or newer, plan review, code review and annotate don't make Claude wait: Claude ends its turn and your decision arrives later as a message. Set `PLANNOTATOR_CLAUDE_MOD=0` to go back to the classic flow.
  188. Full walkthroughs live in the [installation docs](https://docs.plannotator.ai/open-source/start/installation).
  189. ### Uninstall
  190. The safe default removes recognized Plannotator-installed components and keeps
  191. your local plans, history, drafts, guides, and settings:
  192. ```bash
  193. plannotator uninstall
  194. ```
  195. Use `--purge` for a full removal of known local Plannotator data as well:
  196. ```bash
  197. plannotator uninstall --purge
  198. ```
  199. <details>
  200. <summary>What uninstall removes, what it keeps, and when it stops</summary>
  201. Purge requires typing `purge` at the prompt and explains that the data is
  202. local-only: it is not stored on a Plannotator server and cannot be recovered.
  203. For automation, pass `--yes` (or `-y`); non-interactive removal refuses to run
  204. without it. Use `--dry-run` to preview recognized work without making changes.
  205. Host integrations are always part of uninstall. If a broken or unavailable
  206. host prevents safe cleanup, the command names the blocking plugin manager or
  207. configuration, gives exact manual cleanup instructions, and stops before
  208. deleting the binary. Complete that cleanup and rerun uninstall.
  209. It also keeps the binary when an agent's config file can't be read (another
  210. tool's too), or when a hook it did not install still runs Plannotator. The
  211. error names the file, the tool, and what to do. A `plannotator-inbox` entry
  212. you added yourself, or a Claude Code or Droid plugin installed for one project,
  213. is named with how to remove it and does not keep the binary.
  214. These mechanics keep the ordinary confirmation default-negative, make the
  215. irreversible outcome require a stronger explicit word, and still give package
  216. managers and scripts a conventional non-interactive flag.
  217. The command covers the conventional macOS, Linux, WSL, and Windows binary
  218. locations; the managed `sem` sidecar and agent-terminal runtime; installer
  219. skills, commands, hooks, policies, caches, and recognizable Amp/Kiro files; and
  220. detected Claude Code, Copilot CLI, Droid, Pi, and VS Code installations through
  221. their host CLIs. Shared JSONC settings are edited surgically, while strict JSON
  222. updates preserve the file's indentation, line endings, and trailing-newline
  223. style. Custom
  224. or unrecognized files, separately installed optional skills, project-local
  225. integrations, external plan-save locations, and invalid configs are preserved
  226. (malformed host config is a fail-safe error). If cleanup reports an error,
  227. the CLI remains available for a safe retry, and its Windows PATH entry is
  228. retained or restored when possible. If PATH restoration itself fails, the
  229. output gives the full CLI path for retry and asks for manual PATH repair.
  230. For safety, purge refuses filesystem roots, the home directory, the shared
  231. temporary directory, symlinked data directories, and non-directory data paths.
  232. Existing paths are compared by filesystem identity, so case aliases, symlinks,
  233. hardlinks, and bind mounts cannot bypass the root/home/ancestor checks.
  234. That identity and every containment guard are revalidated after awaited host
  235. commands, immediately before the synchronous data-removal block; a replaced
  236. data directory is refused without touching either the old or replacement data.
  237. If your dedicated data directory is symlinked, point `PLANNOTATOR_DATA_DIR` at
  238. its resolved target and retry.
  239. </details>
  240. If you installed only the standalone Pi extension and do not have the
  241. `plannotator` CLI, use `pi remove npm:@plannotator/pi-extension`.
  242. <details>
  243. <summary>Claude Code: manual hook setup (without the plugin system)</summary>
  244. Add to `~/.claude/settings.json`:
  245. ```json
  246. {
  247. "hooks": {
  248. "PermissionRequest": [
  249. {
  250. "matcher": "ExitPlanMode",
  251. "hooks": [
  252. {
  253. "type": "command",
  254. "command": "plannotator",
  255. "timeout": 345600
  256. }
  257. ]
  258. }
  259. ]
  260. }
  261. }
  262. ```
  263. </details>
  264. <details>
  265. <summary>Pin a specific version</summary>
  266. ```bash
  267. curl -fsSL https://plannotator.ai/install.sh | bash -s -- --version vX.Y.Z
  268. ```
  269. ```powershell
  270. & ([scriptblock]::Create((irm https://plannotator.ai/install.ps1))) -Version vX.Y.Z
  271. ```
  272. </details>
  273. ### Try it
  274. The fastest way to see what Plannotator does is to invoke it yourself, right now, from your agent:
  275. ```
  276. /plannotator-last # annotate the agent's last reply
  277. /plannotator-review # review your current diff, PR-style
  278. /plannotator-annotate report.html # annotate any file, folder, or URL
  279. ```
  280. (Slash commands in most agents; `$plannotator-*` skills in Codex, command palette in Amp.)
  281. Plan review needs no command at all. The next time your agent proposes a plan, it opens in your browser automatically.
  282. ---
  283. ## How it works
  284. ### Plan review
  285. ```
  286. Agent calls ExitPlanMode
  287. -> PermissionRequest hook fires
  288. -> Local server reads plan from hook input
  289. -> Browser opens with review UI
  290. -> You annotate and approve/deny
  291. -> Approve: agent proceeds
  292. -> Deny: structured feedback sent to agent
  293. -> Agent revises, plan diff shows what changed
  294. ```
  295. ### Code review
  296. ```
  297. You run /plannotator-review
  298. -> git diff captures changes (or PR fetched by URL)
  299. -> Browser opens with diff viewer
  300. -> Annotate lines, stage/unstage files
  301. -> Send feedback: returned to agent session
  302. -> Approve: "LGTM" sent
  303. ```
  304. ---
  305. ## Integrations
  306. **VS Code**: Open plans in editor tabs, view diffs inline, add annotations from the editor gutter. Install from the [VS Code Marketplace](https://marketplace.visualstudio.com/items?itemName=backnotprop.plannotator-webview).
  307. **Obsidian**: Auto-save approved plans to a vault with YAML frontmatter, tags from the plan title, and backlinks for graph connectivity. Configure in Plannotator's Settings panel.
  308. **Bear**: Save plans as Bear notes with nested tags and project metadata.
  309. **Notion**: Save plans as Markdown child pages under a shared Notion page. Set `NOTION_TOKEN` in the environment that starts Plannotator, then configure the parent page in Settings.
  310. **GitHub / GitLab**: Pass any PR or MR URL to `/plannotator-review` and review it with the full diff viewer, annotations, and file tree.
  311. ---
  312. ## Remote / SSH / devcontainer
  313. Plannotator auto-detects SSH sessions and switches to fixed port `19432`. For a different port, or in a devcontainer or Docker:
  314. ```bash
  315. export PLANNOTATOR_REMOTE=1
  316. export PLANNOTATOR_PORT=9999 # forward this port
  317. ```
  318. VS Code devcontainers forward the port automatically (check the Ports tab). For raw SSH, add this to `~/.ssh/config`, using your `PLANNOTATOR_PORT` value if you set one:
  319. ```
  320. Host your-server
  321. LocalForward 19432 localhost:19432
  322. ```
  323. In remote mode the server listens on every interface (`0.0.0.0`) with no login, so anyone who can reach the port can use it, even when you use an SSH tunnel. Keep the port closed to networks you don't trust.
  324. ---
  325. ## Security
  326. Every released binary ships with a SHA256 sidecar. [SLSA provenance](https://slsa.dev/) attestations are available from v0.17.2. The current release workflow also attaches a CycloneDX JSON SBOM, evaluates it with a fresh Grype database before anything is attested or published, and creates a GitHub/Sigstore SBOM attestation for the shipped binaries and npm tarballs.
  327. The SBOM is intentionally labeled as a release-wide Syft inventory of the monorepo's locked build inputs and dependencies. It is not an exact per-binary runtime inventory: Bun standalone executables do not expose their bundled JavaScript package metadata to Syft. The canonical [installation and verification docs](https://docs.plannotator.ai/open-source/start/installation#pin-or-verify-a-release) cover the existing installer path; the exact new SBOM commands are included below and must be copied to that Mintlify page before the first SBOM-enabled release.
  328. The release gate rejects scanner-side ignored matches and treats unknown applicability conservatively as runtime when evaluating CISA KEV and fixable Critical findings. Its explicit Grype configuration, complete JSON results, database status, and repository policy decision remain available as workflow evidence.
  329. To verify a released Linux x64 binary, its existing provenance, and the new SBOM evidence directly:
  330. ```bash
  331. tag=vX.Y.Z
  332. version="${tag#v}"
  333. mkdir -p /tmp/plannotator-release-verify
  334. gh release download "$tag" --repo backnotprop/plannotator \
  335. --pattern 'plannotator-linux-x64*' \
  336. --pattern "plannotator-${version}-release-sbom.cdx.json*" \
  337. --dir /tmp/plannotator-release-verify
  338. (cd /tmp/plannotator-release-verify && sha256sum --check plannotator-linux-x64.sha256)
  339. (cd /tmp/plannotator-release-verify && sha256sum --check "plannotator-${version}-release-sbom.cdx.json.sha256")
  340. gh attestation verify /tmp/plannotator-release-verify/plannotator-linux-x64 \
  341. --repo backnotprop/plannotator --source-ref "refs/tags/$tag" \
  342. --signer-workflow backnotprop/plannotator/.github/workflows/release.yml \
  343. --predicate-type https://slsa.dev/provenance/v1
  344. gh attestation verify /tmp/plannotator-release-verify/plannotator-linux-x64 \
  345. --repo backnotprop/plannotator --source-ref "refs/tags/$tag" \
  346. --signer-workflow backnotprop/plannotator/.github/workflows/release.yml \
  347. --predicate-type https://cyclonedx.org/bom
  348. ```
  349. These are separate claims over the same artifact digest: provenance identifies its builder/source/workflow, while the CycloneDX predicate describes the release-wide inventory. The release runbook also canonicalizes the downloaded SBOM and attested predicate with `jq -S` and compares them.
  350. To verify on install:
  351. ```bash
  352. curl -fsSL https://plannotator.ai/install.sh | bash -s -- --verify-attestation
  353. ```
  354. Requires the `gh` CLI, but no login: the installer fetches the attestation bundle from GitHub's public attestations API and verifies it with `gh attestation verify --bundle` (the extraction needs node, python3, or jq on PATH; gh's authenticated fetch is the fallback). Can also be set persistently in `~/.plannotator/config.json`:
  355. ```json
  356. { "verifyAttestation": true }
  357. ```
  358. Installer verification remains opt-in and verifies SLSA build provenance; normal installation does not require `gh`. See the [canonical installation docs](https://docs.plannotator.ai/open-source/start/installation#pin-or-verify-a-release) for details.
  359. ---
  360. ## Configuration
  361. Settings are saved in cookies (not localStorage) because each hook invocation runs on a random port. You can also set options through environment variables or `~/.plannotator/config.json`.
  362. ### Optional Vim controls
  363. Plan and annotate views offer a default-off **Vim controls** profile under
  364. **Settings → Vim**. Once enabled, focus the document and use `j` / `k`
  365. to move one rendered block at a time. After `l` refines into a semantic level,
  366. `j` / `k` move among sibling rows, cells, or inline targets; `h` moves back to
  367. the containing target. Refining past the deepest target enters text. `v`
  368. starts characterwise Visual selection and
  369. `V` selects whole blocks. `Space` opens the normal annotation toolbar; `c`,
  370. `d`, `m`, and `t` select comment, redline, markup, and label actions. The same
  371. semantic target graph drives pointer Pinpoint and keyboard navigation. Press
  372. `?` in the document for the contextual key reference. Inputs, dialogs,
  373. editors, `Tab`, and all pointer interactions retain their native behavior.
  374. The document takes focus automatically when the page is otherwise neutral;
  375. press `Escape` from app chrome to return to it without clicking.
  376. An additional default-off **Vim HUD** toggle appears beneath Vim controls. It
  377. uses the product-demo styling for the live target reticle and navigation
  378. context. Its bottom-right **Key panel** is independently hideable while the
  379. reticle remains active; `?` still opens the complete key map on demand. The
  380. panel shows recent handled keys, the current block/line/word/Visual phase, and
  381. the command meaning without capturing text typed into comments or other
  382. controls.
  383. See [Vim controls](docs/vim-controls.md) for the interaction contract and
  384. implementation architecture.
  385. | Variable | Description |
  386. |---|---|
  387. | `PLANNOTATOR_REMOTE` | `1`/`true` for remote mode, `0`/`false` for local, unset for SSH auto-detection |
  388. | `PLANNOTATOR_PORT` | Fixed port (default: random locally, `19432` remote) |
  389. | `PLANNOTATOR_BROWSER` | Custom browser to open plans in. `none` (also `false`, `0`, `off`, `no`, `true`, `1`, `:`) opens no browser at all; the session URL is always printed. |
  390. | `PLANNOTATOR_AI` | `disabled` to disable Ask AI, Review Agents, and Guided Review; the annotate agent terminal is separate |
  391. | `PLANNOTATOR_SHARE` | `disabled` to turn off URL sharing |
  392. | `PLANNOTATOR_SHARE_URL` | Custom base URL for share links (self-hosted portal) |
  393. | `PLANNOTATOR_PASTE_URL` | Base URL of the paste service API |
  394. | `PLANNOTATOR_ORIGIN` | Override agent detection: `claude-code`, `amp`, `droid`, `opencode`, `codex`, `copilot-cli`, `gemini-cli`, `kiro-cli`, `pi` |
  395. | `PLANNOTATOR_JINA` | `0`/`false` to disable Jina Reader for URL annotation |
  396. | `JINA_API_KEY` | Jina Reader API key for higher rate limits |
  397. | `PLANNOTATOR_DATA_DIR` | Base directory for Plannotator-managed files (plans, history, drafts, `config.json`). Default: `~/.plannotator`; if that directory doesn't exist and `$XDG_DATA_HOME` is set to an absolute path, `$XDG_DATA_HOME/plannotator` is used instead (also when `~/.plannotator` holds none of Plannotator's data but the XDG folder does). `plannotator data-dir` prints the folder in use |
  398. Plannotator-managed files live under `~/.plannotator` by default. Some UI preferences are stored in functional browser cookies. To relocate the files (for example, for an XDG-clean home):
  399. ```bash
  400. export PLANNOTATOR_DATA_DIR=~/.local/share/plannotator
  401. ```
  402. ---
  403. ## Development
  404. ```bash
  405. bun install
  406. bun run dev:hook # Plan review server
  407. bun run dev:review # Code review editor
  408. bun run dev:marketing # Marketing site (plannotator.ai)
  409. bun run dev:vscode # VS Code extension (watch mode)
  410. ```
  411. ### Build
  412. ```bash
  413. bun run build # Main targets (hook + opencode + dsh)
  414. bun run build:hook # Single-file HTML for the hook server
  415. bun run build:review # Code review editor
  416. bun run build:opencode # OpenCode plugin
  417. bun run build:dsh # DeepSeek Harness plugin
  418. bun run build:vscode # VS Code extension
  419. ```
  420. Build order matters. The hook build copies pre-built HTML from `apps/review/dist/`. If you change UI code in `packages/ui/`, `packages/editor/`, or `packages/review-editor/`, rebuild the review app first:
  421. ```bash
  422. bun run --cwd apps/review build && bun run build:hook
  423. ```
  424. Test the plugin locally:
  425. ```bash
  426. claude --plugin-dir ./apps/hook
  427. ```
  428. Full binary build:
  429. ```bash
  430. bun run --cwd apps/review build && bun run build:hook && \
  431. bun build apps/hook/server/index.ts --compile --outfile ~/.local/bin/plannotator
  432. ```
  433. ---
  434. ## License
  435. Copyright 2025-2026 backnotprop
  436. Dual-licensed under [Apache 2.0](LICENSE-APACHE) or [MIT](LICENSE-MIT) at your option.
  437. Contributions are dual-licensed under the same terms unless you explicitly state otherwise.
apps/hook/hooks/mod/plan.ts · Bundled script · 156 lines · 2 findings marked
  1. /**
  2. * Non-blocking plan review: the decisions behind the `tool.call` hook on
  3. * ExitPlanMode and the `classic.PermissionRequest` answer. Pure.
  4. */
  5. import { isAbsolutePath } from './paths'
  6. /** Claude Code's plan-mode tool. */
  7. export const PLAN_TOOL = 'ExitPlanMode'
  8. /** The annotate cap the CLI applies to a plan file it trusts (MAX_ANNOTATABLE_FILE_BYTES). */
  9. export const MAX_PLAN_FILE_BYTES = 2 * 1024 * 1024
  10. /**
  11. * Whether the plan file named by ExitPlanMode may be read instead of its
  12. * inline `plan` (the #1667 stale-snapshot fix, mirrored from
  13. * `apps/hook/server/claude-plan.ts`): an absolute `.md` path.
  14. * The caller also requires a regular file within MAX_PLAN_FILE_BYTES.
  15. */
  16. export function isTrustablePlanPath(path: unknown): path is string {
  17. return typeof path === 'string' && isAbsolutePath(path) && /\.md$/i.test(path)
  18. }
  19. /** Hash input: trailing whitespace is not a different plan. */
  20. export function normalizePlanForHash(plan: string): string {
  21. return plan.replace(/\s+$/, '')
  22. }
  23. /** The approval the reviewer gave, waiting for Claude's next ExitPlanMode. */
  24. export interface PendingApproval {
  25. hash: string
  26. plan: string
  27. permissionMode?: string
  28. version: number
  29. }
  30. /** The open review of this session, if any. */
  31. export interface OpenPlanReview {
  32. launchId: string
  33. dir: string
  34. version: number
  35. revisionSeq: number
  36. url?: string
  37. }
  38. export type PlanCallAction =
  39. | { kind: 'pass-approved'; approval: PendingApproval }
  40. | { kind: 'revise'; review: OpenPlanReview }
  41. | { kind: 'start' }
  42. /** What an ExitPlanMode call does, given the session's plan review state. */
  43. export function planCallAction(
  44. planHash: string,
  45. state: { approval: PendingApproval | null; open: OpenPlanReview | null },
  46. ): PlanCallAction {
  47. if (state.approval && state.approval.hash === planHash) return { kind: 'pass-approved', approval: state.approval }
  48. if (state.open) return { kind: 'revise', review: state.open }
  49. return { kind: 'start' }
  50. }
  51. /**
  52. * The approved call's record for the plugin's own PermissionRequest command
  53. * hook (#2007). On Team/Enterprise accounts Claude Code seats its built-in
  54. * guard (`cc-plugin-sec-default`) above the person's plugins, and it sends
  55. * `classic.PermissionRequest` past this mod. The event then reaches the
  56. * command hook (`plannotator`), which reads this record and allows the call
  57. * instead of opening a second review. Written while the approved call is in
  58. * flight, removed when it settles.
  59. *
  60. * A copy of the CLI's contract (`apps/hook/server/mod-plan-approval.ts`; a
  61. * hooks module imports only its own files); `mod-plan-approval.test.ts` keeps
  62. * them equal.
  63. */
  64. export const PLAN_APPROVALS_DIR = 'plan-approvals'
  65. export const PLAN_APPROVAL_RECORD_VERSION = 1
  66. export interface PlanApprovalRecord {
  67. v: typeof PLAN_APPROVAL_RECORD_VERSION
  68. hash: string
  69. plan: string
  70. permissionMode?: string
  71. at: number
  72. }
  73. export function planApprovalRecord(approval: PendingApproval, at: number): PlanApprovalRecord {
  74. return {
  75. v: PLAN_APPROVAL_RECORD_VERSION,
  76. hash: approval.hash,
  77. plan: approval.plan,
  78. ...(approval.permissionMode ? { permissionMode: approval.permissionMode } : {}),
  79. at,
  80. }
  81. }
  82. /** The `classic.PermissionRequest` decision that lets the approved plan through. */
  83. export function approvedPermissionDecision(toolInput: unknown, approval: PendingApproval) {
  84. const input = toolInput && typeof toolInput === 'object' ? (toolInput as Record<string, unknown>) : {}
  85. return {
  86. behavior: 'allow' as const,
  87. // Claude Code drops an ExitPlanMode allow without updatedInput (>= 2.1.199);
  88. // carry the approved text so execution starts from what the reviewer saw.
  89. updatedInput: { ...input, plan: approval.plan },
  90. ...(approval.permissionMode
  91. ? { updatedPermissions: [{ type: 'setMode' as const, mode: approval.permissionMode, destination: 'session' as const }] }
  92. : {}),
  93. }
  94. }
  95. // --- Copy (what Claude reads in the denied ExitPlanMode result) -----------
  96. export function waitingDenyText(version: number, url?: string): string {
  97. const where = url ? ` (${url})` : ''
  98. return `Plan v${version} is open in Plannotator for the user's review${where}. It is NOT approved. Stay in plan mode and do not implement. End your turn. The user's decision will arrive as a message from the plannotator plugin. Until then you may answer questions, and you may revise the plan by calling ExitPlanMode again.`
  99. }
  100. export function revisedDenyText(version: number): string {
  101. return `Plan v${version} replaced v${version - 1} in the open review. Still not approved. End your turn and wait for the decision.`
  102. }
  103. export function unchangedDenyText(version: number): string {
  104. return `Plan v${version} is unchanged and still in review. It is NOT approved. End your turn and wait for the decision.`
  105. }
  106. export function decidingDenyText(): string {
  107. return 'The user is recording a decision on the plan in Plannotator right now, so this revision was not added. It is NOT approved. End your turn and wait for the decision message from the plannotator plugin.'
  108. }
  109. export function revisionPendingDenyText(version: number): string {
  110. return `Plan v${version} was sent to the open Plannotator review. It is NOT approved. End your turn and wait for the decision.`
  111. }
  112. /**
  113. * Whether a `plannotator claude-mod-plan` launch failed because the CLI is
  114. * older than the plugin (the two update separately) and has no such
  115. * subcommand: 0.27.11+ answers "Unknown command", and older CLIs read any
  116. * unknown subcommand as the classic hook, which finds no hook event on stdin.
  117. */
  118. export function cliLacksModPlan(stderr: string): boolean {
  119. return /Unknown command: claude-mod-plan\b/.test(stderr) || /No plan content in hook event/.test(stderr)
  120. }
  121. /** Logged once per session when the CLI has no non-blocking plan review. */
  122. export const CLASSIC_PLAN_REVIEW_TEXT =
  123. 'Your plannotator CLI is older than the Plannotator plugin and has no non-blocking plan review, so plans open in the classic review, which holds this session until you decide. Update the CLI (curl -fsSL https://plannotator.ai/install.sh | bash, or on Windows irm https://plannotator.ai/install.ps1 | iex) and start or resume a session to get non-blocking plan review.'
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Note: Runs a downloaded PowerShell script (iex / Invoke-Expression)
    • Line 144 on GitHub
  124. /**
  125. * Sent to Claude when the old CLI refused only after the ExitPlanMode call had
  126. * already been told a review was open: nothing is open, so ask for the call again.
  127. */
  128. export const CLASSIC_PLAN_RETRY_TEXT =
  129. "The plan review did not open: the user's plannotator CLI is older than the Plannotator plugin and has no non-blocking plan review. The plan is NOT approved. Call ExitPlanMode again with the same plan; it will open in the classic review."
  130. /** Shown in the status line and toasts. */
  131. export function planWaitingStatus(version: number): string {
  132. return `Plan v${version} · waiting for your review`
  133. }
apps/hook/server/decision-target.test.ts · Bundled script · 28 lines · 1 finding marked
  1. import { describe, expect, test } from "bun:test";
  2. import { annotateDecisionTarget, HOST_REVIEW_ID_ENV, reviewDecisionTarget, takeHostReviewId } from "./decision-target";
  3. // The failure these guard: a decision record or registry row that names a
  4. // review by something other than what the server actually opened (a relative
  5. // word, the wrong one of several files), or a host review id that leaks into
  6. // every process the server spawns.
  7. describe("decision target", () => {
  8. test("review: a PR URL wins, then the patch file, then the reviewed directory, all absolute", () => {
  9. expect(reviewDecisionTarget({ prUrl: "https://github.com/o/r/pull/9", cwd: "/repo", invocationCwd: "/x" })).toBe("https://github.com/o/r/pull/9");
  10. expect(reviewDecisionTarget({ patchFile: "fix.patch", cwd: "/repo", invocationCwd: "/work" })).toBe("/work/fix.patch");
  11. expect(reviewDecisionTarget({ patchFile: "-", cwd: "/repo", invocationCwd: "/work" })).toBeUndefined();
  12. expect(reviewDecisionTarget({ cwd: "/repo/app/../app", invocationCwd: "/work" })).toBe("/repo/app");
  13. });
  14. test("annotate: a bundle names every file in order, else the folder, else the file or URL", () => {
  15. expect(annotateDecisionTarget({ bundlePaths: ["/w/b.md", "/w/a.md"], absolutePath: "/w/b.md" })).toEqual(["/w/b.md", "/w/a.md"]);
  16. expect(annotateDecisionTarget({ folderPath: "/w/docs", absolutePath: "/w/docs" })).toBe("/w/docs");
  17. expect(annotateDecisionTarget({ absolutePath: "https://example.com/" })).toBe("https://example.com/");
  18. });
  19. test("the host review id is taken once, validated and scrubbed", () => {
  20. const env: NodeJS.ProcessEnv = { [HOST_REVIEW_ID_ENV]: "PN-ABC123" };
  21. expect(takeHostReviewId(env)).toBe("pn-abc123");
  22. expect(env[HOST_REVIEW_ID_ENV]).toBeUndefined();
  23. expect(takeHostReviewId({ [HOST_REVIEW_ID_ENV]: "pn-abc123; rm -rf /" })).toBeUndefined();
    • Note: Quoted as data in code: Runs `rm -rf` against a root or home-directory path
    • Line 26 on GitHub
  24. });
  25. });
apps/hook/server/inbox-call-command.test.ts · Bundled script · 883 lines · 1 finding marked
  1. /**
  2. * `plannotator inbox call …` (approval "inbox-scripting-command") as real
  3. * processes against a real sandbox Inbox: the Inbox runs in this test process
  4. * so its store's clock can be set back (`storeNow`, what Tidy's ages need), and
  5. * every call is the CLI, finding it through the data dir's `inbox.json`.
  6. *
  7. * What can regress: a script writing as another agent, a script's writes not
  8. * counting for the Tidy that asked for them, a double post on a rerun, a
  9. * failure a script reads as a result, and a result cut short in a pipe. Every
  10. * process gets a temp HOME and data dir, and a PATH of agent stubs
  11. * (tests/helpers/agent-cli-guard.ts): no real agent CLI ever runs.
  12. */
  13. import { afterAll, afterEach, beforeAll, describe, expect, test } from "bun:test";
  14. import { chmodSync, existsSync, mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from "node:fs";
  15. import { tmpdir } from "node:os";
  16. import { delimiter, dirname, join, resolve } from "node:path";
  17. import { Client, StreamableHTTPClientTransport } from "@modelcontextprotocol/client";
  18. import type { InboxMessage, InboxThread, InboxTidyPlan, InboxTidyRun } from "@plannotator/core/inbox-types";
  19. import { INBOX_TIDY_INSTRUCTION } from "@plannotator/core/inbox-types";
  20. import { INBOX_BRIDGE_EVENT_PATH, INBOX_BRIDGE_POLL_PATH, parseInboxBridgeCommands } from "@plannotator/shared/inbox/connection";
  21. import { attachedImagesNotInBodyText } from "@plannotator/shared/inbox/attached-images";
  22. import { questionOpenersWithTextText } from "@plannotator/shared/inbox/question-openers";
  23. import { startInboxServer, type InboxServer } from "@plannotator/server/inbox";
  24. import { createAgentEnvironmentFor } from "@plannotator/server/inbox-agents";
  25. import { codexRolloutDayFolders } from "@plannotator/server/inbox-codex-wake";
  26. import { stubbedAgentClis } from "../../../tests/helpers/agent-cli-guard";
  27. import { createFakeAgents, type FakeAgents } from "../../../tests/helpers/fake-agents";
  28. import { removeStubbedHtml, stubHookDistHtml } from "../../../tests/helpers/hook-dist-stub";
  29. import { type InboxEntry, inboxEntryOf, stopProvenInboxes } from "../../../tests/helpers/inbox-process";
  30. import { NO_BROWSER } from "../../../tests/helpers/no-browser";
  31. import { T3_THREAD_ID_FORMS } from "../../../tests/helpers/fake-t3";
  32. import { INBOX_CALL_ACTIONS, INBOX_CALL_USAGE } from "./cli";
  33. import { type CallCommandDeps, inboxCallerOf, parseCallCommand, routineCallArgs, runInboxCallCommand } from "./inbox-call-command";
  34. const entry = resolve(import.meta.dir, "index.ts");
  35. const HOUR = 60 * 60_000;
  36. const CODEX_THREAD = "019a2b3c-4d5e-7f00-8a9b-0c1d2e3f4a5b";
  37. const QWEN_SESSION = "11111111-2222-4333-8444-555555555555";
  38. const T3_THREAD = "6f1c2d3e-4a5b-4c6d-8e7f-0a1b2c3d4e5f";
  39. let stubs: string[] = [];
  40. const roots: string[] = [];
  41. const servers: InboxServer[] = [];
  42. const clients: Client[] = [];
  43. const fakes: FakeAgents[] = [];
  44. const detached: { entry: InboxEntry; root: string }[] = [];
  45. beforeAll(() => {
  46. // The CLI imports the built HTML; these tests never read the pages.
  47. stubs = stubHookDistHtml();
  48. });
  49. afterAll(() => {
  50. removeStubbedHtml(stubs);
  51. });
  52. afterEach(async () => {
  53. for (const client of clients.splice(0)) await client.close().catch(() => {});
  54. for (const server of servers.splice(0)) server.stop();
  55. // Throws when a fake CLI outlived the test.
  56. for (const fake of fakes.splice(0)) fake.remove();
  57. await stopProvenInboxes(detached.splice(0), { signal: "SIGKILL" });
  58. for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true });
  59. });
  60. // After the cleanup hooks: a stub's failure stops the hooks registered behind it.
  61. const agents = stubbedAgentClis();
  62. function sandbox() {
  63. const root = realpathSync(mkdtempSync(join(tmpdir(), "plannotator-inbox-call-")));
  64. roots.push(root);
  65. const dataDir = join(root, "home", ".plannotator");
  66. const project = join(root, "code", "billing");
  67. mkdirSync(project, { recursive: true });
  68. mkdirSync(dataDir, { recursive: true });
  69. // The Board and thread steps are things the person turns on: on here, so every action the command takes is served.
  70. writeFileSync(join(dataDir, "config.json"), JSON.stringify({ inboxBoard: true, inboxSteps: true }));
  71. const env: Record<string, string> = {
  72. ...agents.env,
  73. HOME: join(root, "home"),
  74. TMPDIR: tmpdir(),
  75. PLANNOTATOR_RELAY_URL: "http://127.0.0.1:9",
  76. PLANNOTATOR_DATA_DIR: dataDir,
  77. PLANNOTATOR_BROWSER: NO_BROWSER,
  78. PLANNOTATOR_INBOX_CONNECT: "0",
  79. PLANNOTATOR_UPDATE_CHECK: "0",
  80. GIT_CONFIG_GLOBAL: "/dev/null",
  81. GIT_CONFIG_NOSYSTEM: "1",
  82. };
  83. return { root, dataDir, project, env };
  84. }
  85. type Box = ReturnType<typeof sandbox>;
  86. /** A sandbox with an Inbox running; what a test writes while `clock.behind` is set reads as that much older. */
  87. async function world() {
  88. const box = sandbox();
  89. const clock = { behind: 0 };
  90. // This Inbox runs in the test's process: named here, so a run the preload missed still has no agents, on PATH or in /Applications.
  91. const agentsHome = join(box.dataDir, "agents-home");
  92. const server = await startInboxServer({
  93. dataDir: box.dataDir,
  94. binaryPath: null,
  95. board: true,
  96. steps: true,
  97. scheduled: true,
  98. storeNow: () => new Date(Date.now() - clock.behind),
  99. agentEnvironment: createAgentEnvironmentFor({ platform: process.platform, homeDir: agentsHome, env: { HOME: agentsHome, PATH: "" } }),
  100. codexWake: { extraClis: [] },
  101. });
  102. servers.push(server);
  103. const client = new Client({ name: "inbox-call-test", version: "1.0.0" });
  104. await client.connect(new StreamableHTTPClientTransport(new URL(`http://127.0.0.1:${server.port}/mcp`)));
  105. clients.push(client);
  106. return { ...box, clock, server, client };
  107. }
  108. type World = Awaited<ReturnType<typeof world>>;
  109. async function cli(box: Box, args: string[], options: { env?: Record<string, string>; stdin?: string | Uint8Array; cwd?: string } = {}) {
  110. const proc = Bun.spawn([process.execPath, "run", entry, "inbox", "call", ...args], {
  111. cwd: options.cwd ?? box.project,
  112. env: { ...box.env, ...options.env },
  113. stdin: options.stdin === undefined ? "ignore" : typeof options.stdin === "string" ? new TextEncoder().encode(options.stdin) : options.stdin,
  114. stdout: "pipe",
  115. stderr: "pipe",
  116. });
  117. const [stdout, stderr, code] = await Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text(), proc.exited]);
  118. return { code, stdout, stderr };
  119. }
  120. const tool = async (client: Client, name: string, args: Record<string, unknown>) => {
  121. const result = (await client.callTool({ name, arguments: args })) as { isError?: boolean; content: { text: string }[]; structuredContent: Record<string, any> };
  122. if (result.isError) throw new Error(result.content[0]!.text);
  123. return result.structuredContent;
  124. };
  125. const base = (server: InboxServer) => `http://127.0.0.1:${server.port}`;
  126. const post = (server: InboxServer, path: string, body: Record<string, unknown>) =>
  127. fetch(`${base(server)}${path}`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ serverSession: server.serverSession, ...body }) });
  128. const bridge = (server: InboxServer, path: string, body: unknown) =>
  129. fetch(`${base(server)}${path}`, { method: "POST", headers: { "Content-Type": "application/json", Authorization: `Bearer ${server.token}` }, body: JSON.stringify(body) });
  130. const threadOf = async (server: InboxServer, id: string) => ((await (await fetch(`${base(server)}/api/inbox/threads/${id}`)).json()) as { thread: InboxThread }).thread;
  131. const planOf = async (server: InboxServer, query = "") => (await (await fetch(`${base(server)}/api/inbox/tidy${query}`)).json()) as InboxTidyPlan;
  132. const runOf = async (server: InboxServer) => (await planOf(server)).run!;
  133. /** A connection's poll for `session`: live for the next 30 s; the commands it hands out. */
  134. async function poll(server: InboxServer, session: string, project: string, host = "claude-code") {
  135. const response = await bridge(server, INBOX_BRIDGE_POLL_PATH, { session, host, project_path: project, waitMs: 0, busy: false, idle_since: Date.now() - HOUR });
  136. return parseInboxBridgeCommands(await response.text());
  137. }
  138. /** The session's Tidy wake, handed out and delivered. */
  139. async function wakeOf(server: InboxServer, session: string, project: string, host = "claude-code") {
  140. const [command] = await poll(server, session, project, host);
  141. await bridge(server, INBOX_BRIDGE_EVENT_PATH, { session, host, type: "delivered", id: command!.id });
  142. return command!;
  143. }
  144. /** The exact value the wake gives the session, as an agent reads it. */
  145. const sessionValueIn = (body: string) => /`--session ([^`]+)`/.exec(body)?.[1];
  146. const block = (prompt: string) => [":::question", prompt, "", "- [ ] Yes", "- [ ] No", ":::"].join("\n");
  147. const action = (order: string) => [":::action", order, "", "Why it matters.", ":::"].join("\n");
  148. describe("what a script gets", () => {
  149. test("a refused call leaves stdout empty and says the tool's code on stderr; a good one prints one JSON value", async () => {
  150. const box = await world();
  151. const sent = await cli(box, ["send_message", '{"body":"Starting the ledger lane.","subject":"Ledger","thread":"Ledger"}'], { env: { PLANNOTATOR_SESSION_TAG: "claude-code:ses-a" } });
  152. expect(sent.code).toBe(0);
  153. expect(sent.stderr).toBe("");
  154. const message = JSON.parse(sent.stdout);
  155. expect(message.message_id).toBe((await threadOf(box.server, message.thread_id)).messages[0]!.id);
  156. const refused = await cli(box, ["read_thread", '{"thread_id":"msg_nope"}']);
  157. expect(refused).toMatchObject({ code: 1, stdout: "" });
  158. expect(refused.stderr).toStartWith("thread_not_found: ");
  159. // A field the tool's schema does not take is refused by the MCP layer, in plain words.
  160. const unknown = await cli(box, ["resolve_message", '{"message_id":"x","nope":1}']);
  161. expect(unknown).toMatchObject({ code: 1, stdout: "" });
  162. expect(unknown.stderr).toStartWith("invalid_arguments: ");
  163. });
  164. test("snooze_thread from a script: it snoozes, says until when as JSON, and until: null ends it", async () => {
  165. const box = await world();
  166. const sent = JSON.parse((await cli(box, ["send_message", '{"body":"News.","subject":"Ledger"}'], { env: { PLANNOTATOR_SESSION_TAG: "claude-code:ses_call" } })).stdout);
  167. const until = new Date(Date.now() + 3_600_000).toISOString();
  168. const snoozed = await cli(box, ["snooze_thread", JSON.stringify({ thread_id: sent.thread_id, until })]);
  169. expect(snoozed.code).toBe(0);
  170. expect(JSON.parse(snoozed.stdout).snoozed.until).toBe(until);
  171. expect(box.server.store.snoozes().map((s) => s.thread_id)).toEqual([sent.thread_id]);
  172. const ended = await cli(box, ["snooze_thread", JSON.stringify({ thread_id: sent.thread_id, until: null })]);
  173. expect(JSON.parse(ended.stdout)).toEqual({ thread_id: sent.thread_id, snoozed: null, ended: `Thread ${sent.thread_id}: snooze ended.` });
  174. expect(box.server.store.snoozes()).toEqual([]);
  175. });
  176. // Review of #2567, finding 2: with thread steps off an agent reads no word of them, so the error's list leaves out
  177. // `steps` (as the usage does); the action itself still goes through (the Inbox answers steps_off while off).
  178. test("an unknown action's list never names steps; steps itself is an action", () => {
  179. const unknown = parseCallCommand(["blorp"]);
  180. expect(unknown).toMatchObject({ ok: false, code: "unknown_action" });
  181. expect((unknown as { error: string }).error).toContain("send_message");
  182. expect((unknown as { error: string }).error).not.toMatch(/\bsteps\b/);
  183. expect(parseCallCommand(["steps", "{}"])).toMatchObject({ ok: true, action: "steps" });
  184. });
  185. test("plannotator routine <op> is inbox call routine with the op inside its JSON, the session passed on", () => {
  186. expect(routineCallArgs(["update", '{"id":"sch_1","name":"Morning triage"}', "--session", "s-maya"])).toEqual(["--session", "s-maya", "routine", '{"id":"sch_1","name":"Morning triage","op":"update"}']);
  187. expect(routineCallArgs([])).toMatchObject({ code: "usage" });
  188. });
  189. test("bad JSON, a non-object, an unknown action, wait_for_reply and a named identity are usage errors, sent nowhere", async () => {
  190. const box = sandbox();
  191. for (const [args, code] of [
  192. [["read_thread", "{nope"], "invalid_json"],
  193. [["read_thread", "[1]"], "invalid_json"],
  194. [["read_thread", "-"], "invalid_json"],
  195. [["blorp"], "unknown_action"],
  196. [["wait_for_reply", "{}"], "unknown_action"],
  197. [["read_thread", '{"agent_session":"someone-else"}'], "invalid_arguments"],
  198. [["send_message", '{"body":"x","agent_host":"codex"}'], "invalid_arguments"],
  199. ] as const) {
  200. const result = await cli(box, [...args], { stdin: "" });
  201. expect(result).toMatchObject({ code: 2, stdout: "" });
  202. expect(result.stderr).toStartWith(`${code}: `);
  203. }
  204. // None of these reached for an Inbox, so none started one.
  205. expect(existsSync(join(box.dataDir, "inbox", "inbox.json"))).toBe(false);
  206. });
  207. test("an Inbox started without the test sandbox still reaches only a stub", async () => {
  208. const box = sandbox();
  209. const { PLANNOTATOR_TEST_SANDBOX: _sandbox, ...env } = box.env;
  210. const sent = await cli({ ...box, env }, ["send_message", '{"body":"From a Codex thread."}'], { env: { CODEX_THREAD_ID: CODEX_THREAD } });
  211. const inbox = inboxEntryOf(box.dataDir);
  212. if (inbox) detached.push({ entry: inbox, root: box.root });
  213. expect(sent.code).toBe(0);
  214. expect(agents.takeCalls()).toEqual(["codex --version"]);
  215. }, 30_000);
  216. test("a stopped Inbox starts in the background with no browser, as `inbox mcp` does", async () => {
  217. const box = sandbox();
  218. const marker = join(box.root, "browser-opened");
  219. const browser = join(box.root, "fake-browser.sh");
  220. writeFileSync(browser, `#!/bin/sh\necho "$1" >> '${marker}'\n`);
  221. chmodSync(browser, 0o755);
  222. const first = await cli(box, ["read_thread", "{}"], { env: { PLANNOTATOR_BROWSER: browser } });
  223. const inbox = inboxEntryOf(box.dataDir);
  224. if (inbox) detached.push({ entry: inbox, root: box.root });
  225. expect(first.code).toBe(0);
  226. expect(JSON.parse(first.stdout)).toMatchObject({ threads: [], total: 0 });
  227. expect(inbox).not.toBeNull();
  228. expect(existsSync(marker)).toBe(false);
  229. });
  230. test("an Inbox that cannot start or answer is a clear failure with nothing on stdout", async () => {
  231. const out: string[] = [];
  232. const err: string[] = [];
  233. const deps: CallCommandDeps = { cwd: "/", env: {}, ensureRunning: () => Promise.reject(new Error("the start timed out")), out: (text) => void out.push(text), err: (text) => void err.push(text) };
  234. expect(await runInboxCallCommand(["read_thread", "{}"], deps)).toBe(1);
  235. expect(err.join("")).toStartWith("inbox_not_running: ");
  236. const entry = { port: 9 } as Awaited<ReturnType<CallCommandDeps["ensureRunning"]>>;
  237. err.length = 0;
  238. expect(await runInboxCallCommand(["read_thread", "{}"], { ...deps, ensureRunning: async () => entry, timeoutMs: 1000 })).toBe(1);
  239. expect(err.join("")).toStartWith("inbox_no_answer: ");
  240. expect(out).toEqual([]);
  241. });
  242. test("- reads the JSON from stdin, a PowerShell BOM and all, and a long result reaches a pipe whole", async () => {
  243. const box = await world();
  244. const body = "é".repeat(2_000_000);
  245. const sent = await cli(box, ["send_message", "-"], {
  246. env: { PLANNOTATOR_SESSION_TAG: "claude-code:ses-a" },
  247. stdin: `${JSON.stringify({ body, subject: "Long", thread: "Long" })}`,
  248. });
  249. expect(sent.code).toBe(0);
  250. const { thread_id } = JSON.parse(sent.stdout);
  251. const read = await cli(box, ["read_thread", JSON.stringify({ thread_id, format: "full" })]);
  252. expect(read.code).toBe(0);
  253. expect(JSON.parse(read.stdout).thread.messages[0].body).toBe(body);
  254. });
  255. test("read_thread gives a script the line naming the file on screen when a reply went from the floating box", async () => {
  256. const box = await world();
  257. writeFileSync(join(box.project, "take.png"), "not really a png");
  258. const sent = await tool(box.client, "send_message", { body: "A take.", subject: "Takes", thread: "Takes", attachments: ["take.png"], project_path: box.project, agent_session: "ses-a", agent_host: "claude-code" });
  259. const posted = await post(box.server, `/api/inbox/messages/${sent.message_id}/reply`, { idempotency_key: "k1", words: "Good.", questions: [], viewing: { attachment_id: sent.attachments[0].id, time: "8:47 PM" } });
  260. expect(posted.status).toBe(200);
  261. const read = await cli(box, ["read_thread", JSON.stringify({ thread_id: sent.thread_id, format: "full" })]);
  262. expect(read.code).toBe(0);
  263. const reply = JSON.parse(read.stdout).thread.messages.at(-1);
  264. expect(reply.body).toBe("Good.");
  265. expect(reply.viewing).toContain(`while viewing \`take.png\`, from the 8:47 PM message ${sent.message_id}.`);
  266. });
  267. test("a relative project_path and relative attachments mean where the script runs, even in a reply", async () => {
  268. const box = await world();
  269. const sub = join(box.project, "reports");
  270. mkdirSync(sub);
  271. writeFileSync(join(sub, "notes.md"), "# Notes\n");
  272. const first = await tool(box.client, "send_message", { body: "Starting.", subject: "Reports", thread: "Reports", project_path: box.project, agent_session: "ses-a", agent_host: "claude-code" });
  273. const reply = await cli(box, ["send_message", JSON.stringify({ reply_to: first.message_id, body: "Here.", attachments: ["notes.md"] })], { cwd: sub, env: { PLANNOTATOR_SESSION_TAG: "claude-code:ses-a" } });
  274. expect(reply.code).toBe(0);
  275. expect(JSON.parse(reply.stdout).attachments[0].name).toBe("notes.md");
  276. const listed = await cli(box, ["read_thread", JSON.stringify({ project_path: ".." })], { cwd: sub });
  277. expect(JSON.parse(listed.stdout).project.root).toBe(box.project);
  278. });
  279. test("a picture attached but not shown in the body: sent, stdout still one JSON value, the advice on stderr", async () => {
  280. const box = await world();
  281. writeFileSync(join(box.project, "look.png"), Buffer.from("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==", "base64"));
  282. const sent = await cli(box, ["send_message", JSON.stringify({ body: "The new look.", thread: "Look", attachments: ["look.png"] })]);
  283. expect(sent.code).toBe(0);
  284. expect(JSON.parse(sent.stdout).attached_images_not_in_body).toEqual(["look.png"]);
  285. expect(sent.stderr).toBe(`${attachedImagesNotInBodyText(1).trim()}\n`);
  286. const shown = await cli(box, ["send_message", JSON.stringify({ body: "The new look: ![look](look.png)", thread: "Look", attachments: ["look.png"] })]);
  287. expect(shown.code).toBe(0);
  288. expect(shown.stderr).toBe("");
  289. });
  290. test("a question opener with text after its name: sent, stdout still one JSON value, the warning on stderr", async () => {
  291. const box = await world();
  292. const sent = await cli(box, ["send_message", JSON.stringify({ body: "Pick:\n:::question {#bar}\nWhich bar?\n- [ ] Top\n:::", thread: "Bars" })]);
  293. expect(sent.code).toBe(0);
  294. expect(JSON.parse(sent.stdout).question_openers_with_text).toEqual([{ line: 2, directive: ":::question" }]);
  295. expect(sent.stderr).toBe(`${questionOpenersWithTextText([{ line: 2, directive: ":::question" }]).trim()}\n`);
  296. });
  297. test("inside an agent Ask AI started the Inbox is off: nothing is started or sent", async () => {
  298. const box = sandbox();
  299. const result = await cli(box, ["read_thread", "{}"], { env: { PLANNOTATOR_ASK_AI_CHILD: "1" } });
  300. expect(result).toMatchObject({ code: 1, stdout: "" });
  301. expect(result.stderr).toStartWith("inbox_off: ");
  302. expect(existsSync(join(box.dataDir, "inbox", "inbox.json"))).toBe(false);
  303. });
  304. test("every action the command takes is one a real Inbox serves", async () => {
  305. const box = await world();
  306. const { tools } = await box.client.listTools();
  307. expect(tools.map((t) => t.name)).toEqual(expect.arrayContaining([...INBOX_CALL_ACTIONS]));
  308. });
  309. });
  310. describe("who is calling", () => {
  311. const HOSTS: { name: string; host: string; session: string; agentName: string; env: Record<string, string>; flag?: string }[] = [
  312. { name: "Claude Code", host: "claude-code", session: "ses-claude", agentName: "Claude Code", env: { PLANNOTATOR_SESSION_TAG: "claude-code:ses-claude", CLAUDECODE: "1" } },
  313. { name: "Pi", host: "pi", session: "ses-pi", agentName: "Pi", env: { PI_SESSION_ID: "ses-pi" } },
  314. { name: "Codex", host: "codex", session: CODEX_THREAD, agentName: "Codex", env: { CODEX_THREAD_ID: CODEX_THREAD } },
  315. { name: "Qwen Code", host: "qwen", session: QWEN_SESSION, agentName: "Qwen Code", env: { QWEN_CODE_SESSION_ID: QWEN_SESSION, QWEN_CODE: "1" } },
  316. // DeepSeek Harness sets DSH_SESSION_ID (and DSH_SHELL) in every model shell.
  317. { name: "DeepSeek Harness", host: "dsh", session: "session-0b9c8e4e", agentName: "DeepSeek Harness", env: { DSH_SHELL: "1", DSH_SESSION_ID: "session-0b9c8e4e" } },
  318. // T3 Code runs Claude through the Agent SDK (the mod is off there): the thread, beside Claude's own marker.
  319. { name: "T3 Code", host: "t3", session: T3_THREAD, agentName: "T3 Code", env: { T3CODE_THREAD_ID: T3_THREAD, CLAUDECODE: "1", CLAUDE_CODE_ENTRYPOINT: "sdk-ts" } },
  320. // OpenCode names no session in its shell: only the value its Tidy gives it says who it is.
  321. { name: "OpenCode", host: "opencode", session: "ses_opencode1", agentName: "OpenCode", env: { OPENCODE: "1" }, flag: "opencode:ses_opencode1" },
  322. ];
  323. for (const { name, host, session, agentName, env, flag } of HOSTS) {
  324. test(`${name}: a script's message is the session's own, as its tool writes it`, async () => {
  325. const box = await world();
  326. const byTool = await tool(box.client, "send_message", { body: "From the tool.", subject: name, project_path: box.project, agent_session: session, agent_host: host, agent_name: agentName });
  327. const byScript = await cli(box, [...(flag ? ["--session", flag] : []), "send_message", JSON.stringify({ reply_to: byTool.message_id, body: "From a script." })], { env });
  328. expect(byScript.code).toBe(0);
  329. const [first, second] = (await threadOf(box.server, byTool.thread_id)).messages;
  330. expect(second!.author).toEqual(first!.author);
  331. // "Your" threads and cards are this session's.
  332. const listed = await cli(box, [...(flag ? ["--session", flag] : []), "read_thread", "{}"], { env });
  333. expect(JSON.parse(listed.stdout).threads.map((t: { thread_id: string }) => t.thread_id)).toEqual([byTool.thread_id]);
  334. });
  335. }
  336. test("with no session anywhere it is a raw MCP client: nobody's message, and lists read everyone's", async () => {
  337. const box = await world();
  338. const theirs = await tool(box.client, "send_message", { body: "Theirs.", subject: "Theirs", thread: "Theirs", project_path: box.project, agent_session: "ses-other", agent_host: "claude-code" });
  339. await tool(box.client, "card", { op: "create", title: "Their card", project_path: box.project, agent_session: "ses-other", agent_host: "claude-code" });
  340. expect(JSON.parse((await cli(box, ["read_thread", "{}"])).stdout).threads.map((t: { thread_id: string }) => t.thread_id)).toEqual([theirs.thread_id]);
  341. expect(JSON.parse((await cli(box, ["card", '{"op":"list"}'])).stdout).total).toBe(1);
  342. const reply = await cli(box, ["send_message", JSON.stringify({ reply_to: theirs.message_id, body: "A person's script." })]);
  343. const message = (await threadOf(box.server, theirs.thread_id)).messages.find((m) => m.id === JSON.parse(reply.stdout).message_id)!;
  344. expect(message.author).toMatchObject({ kind: "agent", host: null, session: null });
  345. });
  346. test("an MCP-only agent is its session with the bare value; a bare session has no host to claim", async () => {
  347. const box = await world();
  348. const mine = await tool(box.client, "send_message", { body: "Mine.", subject: "Mine", thread: "Mine", project_path: box.project, agent_session: "ses_mcponly", agent_name: "Some Client" });
  349. await tool(box.client, "send_message", { body: "Another's.", subject: "Other", thread: "Other", project_path: box.project, agent_session: "ses_other" });
  350. const listed = await cli(box, ["--session", "ses_mcponly", "read_thread", "{}"]);
  351. expect(JSON.parse(listed.stdout).threads.map((t: { thread_id: string }) => t.thread_id)).toEqual([mine.thread_id]);
  352. });
  353. test("a card's owner is the session, so `your cards` means this agent's and another's stays out", async () => {
  354. const box = await world();
  355. await tool(box.client, "send_message", { body: "Lane.", subject: "Lane", thread: "Lane", project_path: box.project, agent_session: "ses-a", agent_host: "claude-code" });
  356. await tool(box.client, "card", { op: "create", title: "Other lane", project_path: box.project, agent_session: "ses-b", agent_host: "claude-code" });
  357. const env = { PLANNOTATOR_SESSION_TAG: "claude-code:ses-a" };
  358. const made = await cli(box, ["card", '{"op":"create","title":"My lane","column":"in_progress"}'], { env });
  359. expect(JSON.parse(made.stdout).card.agent).toMatchObject({ host: "claude-code", session: "ses-a", name: "Claude Code" });
  360. const mine = JSON.parse((await cli(box, ["card", '{"op":"list"}'], { env })).stdout);
  361. expect(mine.cards.map((c: { title: string }) => c.title)).toEqual(["My lane"]);
  362. });
  363. // Twelve CLI starts in a row and no waiting between them: about 4.5 s alone, so the default 5 s fails under load.
  364. test("an agent started from another agent's shell never writes as that agent", async () => {
  365. const box = await world();
  366. const seen = await tool(box.client, "send_message", { body: "Outer.", subject: "Outer", thread: "Outer", project_path: box.project, agent_session: "ses-outer", agent_host: "claude-code" });
  367. const count = async () => (await threadOf(box.server, seen.thread_id)).messages.length;
  368. const send = JSON.stringify({ reply_to: seen.message_id, body: "Whose is this?" });
  369. for (const env of [
  370. { PLANNOTATOR_SESSION_TAG: "claude-code:ses-outer", CODEX_THREAD_ID: CODEX_THREAD },
  371. { PLANNOTATOR_SESSION_TAG: "claude-code:ses-outer", OPENCODE: "1" },
  372. { PI_SESSION_ID: "ses-pi", QWEN_CODE_SESSION_ID: QWEN_SESSION },
  373. { CODEX_THREAD_ID: CODEX_THREAD, CLAUDECODE: "1" },
  374. { CODEX_THREAD_ID: CODEX_THREAD, OMPCODE: "1" },
  375. { PI_SESSION_ID: "ses-pi", CLAUDECODE: "1" },
  376. { PLANNOTATOR_SESSION_TAG: "claude-code:ses-outer", QWEN_CODE: "1" },
  377. // Claude Code or Pi started from a DeepSeek Harness shell: DSH_* is inherited.
  378. { DSH_SHELL: "1", DSH_SESSION_ID: "session-outer", CLAUDECODE: "1" },
  379. { DSH_SHELL: "1", DSH_SESSION_ID: "session-outer", PI_SESSION_ID: "ses-pi" },
  380. ]) {
  381. const refused = await cli(box, ["send_message", send], { env });
  382. expect(refused).toMatchObject({ code: 1, stdout: "" });
  383. expect(refused.stderr).toStartWith("session_ambiguous: ");
  384. }
  385. // A value this shell contradicts: a wake that went stale, or a script another agent left behind.
  386. const stale = await cli(box, ["--session", "claude-code:ses-other", "send_message", send], { env: { PLANNOTATOR_SESSION_TAG: "claude-code:ses-outer" } });
  387. expect(stale).toMatchObject({ code: 1, stdout: "" });
  388. expect(stale.stderr).toStartWith("session_mismatch: ");
  389. expect(await count()).toBe(1);
  390. // The agent's own value settles it: Codex inside Claude Code.
  391. const settled = await cli(box, ["--session", `codex:${CODEX_THREAD}`, "send_message", send], { env: { PLANNOTATOR_SESSION_TAG: "claude-code:ses-outer", CODEX_THREAD_ID: CODEX_THREAD } });
  392. expect(settled.code).toBe(0);
  393. expect((await threadOf(box.server, seen.thread_id)).messages.at(-1)!.author).toMatchObject({ host: "codex", session: CODEX_THREAD });
  394. // OpenCode inside Claude Code: its shell names only the outer session, and its Tidy says who it is.
  395. const nested = await cli(box, ["--session", "opencode:ses_nested", "read_thread", "{}"], { env: { PLANNOTATOR_SESSION_TAG: "claude-code:ses-outer", OPENCODE: "1" } });
  396. expect(nested.code).toBe(0);
  397. }, 30_000);
  398. test("the rules alone: what each shell and value resolve to", () => {
  399. const caller = (flag: string | null, env: Record<string, string>) => {
  400. const answer = inboxCallerOf(flag, env);
  401. return answer.ok ? answer.caller : answer.code;
  402. };
  403. expect(caller(null, {})).toBeNull();
  404. expect(caller(null, { OPENCODE: "1", GEMINI_CLI: "1" })).toBeNull();
  405. // A host's marker beside its own session is its own shell, not a nested agent.
  406. expect(caller(null, { PLANNOTATOR_SESSION_TAG: "claude-code:s", CLAUDECODE: "1" })).toEqual({ host: "claude-code", session: "s", name: "Claude Code" });
  407. expect(caller(null, { QWEN_CODE_SESSION_ID: QWEN_SESSION, QWEN_CODE: "1" })).toEqual({ host: "qwen", session: QWEN_SESSION, name: "Qwen Code" });
  408. expect(caller(null, { PI_SESSION_ID: "s", OMPCODE: "1" })).toEqual({ host: "pi", session: "s", name: "Pi" });
  409. expect(caller(null, { CLAUDECODE: "1" })).toBeNull();
  410. // DeepSeek Harness: its marker beside its own session is its own shell; DSH_SHELL alone names no session.
  411. expect(caller(null, { DSH_SHELL: "1", DSH_SESSION_ID: "session-s" })).toEqual({ host: "dsh", session: "session-s", name: "DeepSeek Harness" });
  412. expect(caller(null, { DSH_SHELL: "1" })).toBeNull();
  413. expect(caller(null, { DSH_SHELL: "1", DSH_SESSION_ID: "session-s", GEMINI_CLI: "1" })).toBe("session_ambiguous");
  414. // The person's own terminal in DSH Web (DSH_SESSION_ID, no DSH_SHELL): no DSH session, so whoever runs there is themselves.
  415. expect(caller(null, { DSH_SESSION_ID: "session-s" })).toBeNull();
  416. expect(caller(null, { DSH_SESSION_ID: "session-s", PI_SESSION_ID: "ses-pi" })).toEqual({ host: "pi", session: "ses-pi", name: "Pi" });
  417. expect(caller(null, { DSH_SESSION_ID: "session-s", PLANNOTATOR_SESSION_TAG: "claude-code:s", CLAUDECODE: "1" })).toEqual({ host: "claude-code", session: "s", name: "Claude Code" });
  418. expect(caller(null, { DSH_SESSION_ID: "session-s", CODEX_THREAD_ID: CODEX_THREAD })).toEqual({ host: "codex", session: CODEX_THREAD, name: "Codex" });
  419. // A subagent's model shell: the session Plannotator's plugin names (its parent).
  420. const sub = { DSH_SHELL: "1", DSH_SESSION_ID: "session-child", DSH_PLANNOTATOR_SESSION_ID: "session-parent", DSH_PLANNOTATOR_SESSION_FOR: "session-child" };
  421. expect(caller(null, sub)).toEqual({ host: "dsh", session: "session-parent", name: "DeepSeek Harness" });
  422. expect(caller(null, { ...sub, DSH_PLANNOTATOR_SESSION_FOR: "session-other" })).toEqual({ host: "dsh", session: "session-child", name: "DeepSeek Harness" });
  423. // A mismatch names the variable the session came from, so unsetting it changes something.
  424. const mismatch = inboxCallerOf("dsh:session-mine", sub);
  425. expect(mismatch.ok ? null : mismatch.message).toContain("from DSH_PLANNOTATOR_SESSION_ID");
  426. expect(mismatch.ok ? null : mismatch.message).not.toContain("from DSH_SESSION_ID");
  427. const plain = inboxCallerOf("dsh:session-mine", { DSH_SHELL: "1", DSH_SESSION_ID: "session-child" });
  428. expect(plain.ok ? null : plain.message).toContain("from DSH_SESSION_ID");
  429. // T3 Code: its thread beside Claude's own CLAUDECODE is the thread (T3 runs Claude, and the mod is off there).
  430. const t3 = { host: "t3", session: T3_THREAD, name: "T3 Code" };
  431. expect(caller(null, { T3CODE_THREAD_ID: T3_THREAD, CLAUDECODE: "1" })).toEqual(t3);
  432. expect(caller(null, { T3CODE_THREAD_ID: T3_THREAD })).toEqual(t3);
  433. // Anything else beside it is ambiguous: a Codex started in a T3 shell is the caller, not the thread; a tag can be
  434. // inherited from a Claude Code that started T3; a DSH model shell or another agent is its own.
  435. for (const other of [
  436. { CODEX_THREAD_ID: CODEX_THREAD },
  437. { PLANNOTATOR_SESSION_TAG: "claude-code:s" },
  438. { DSH_SHELL: "1" },
  439. { DSH_SHELL: "1", DSH_SESSION_ID: "session-s" },
  440. { GEMINI_CLI: "1" },
  441. ]) {
  442. expect(caller(null, { T3CODE_THREAD_ID: T3_THREAD, CLAUDECODE: "1", ...other })).toBe("session_ambiguous");
  443. }
  444. expect(caller(null, { T3CODE_THREAD_ID: T3_THREAD, CODEX_THREAD_ID: CODEX_THREAD })).toBe("session_ambiguous");
  445. // The wake's own value settles it.
  446. expect(caller(`t3:${T3_THREAD}`, { T3CODE_THREAD_ID: T3_THREAD, CODEX_THREAD_ID: CODEX_THREAD, CLAUDECODE: "1" })).toEqual(t3);
  447. // A launched, scheduled, delegated or provider thread is the thread too, from the variable and from the wake's value.
  448. for (const id of Object.values(T3_THREAD_ID_FORMS)) {
  449. expect(caller(null, { T3CODE_THREAD_ID: id, CLAUDECODE: "1" })).toEqual({ ...t3, session: id });
  450. expect(caller(`t3:${id}`, { T3CODE_THREAD_ID: id, CODEX_THREAD_ID: CODEX_THREAD, CLAUDECODE: "1" })).toEqual({ ...t3, session: id });
  451. }
  452. // Nothing T3 would give a thread: no T3 session, never a guess.
  453. for (const id of [`:${T3_THREAD}`, `${T3_THREAD} x`, "thread/../x"]) {
  454. expect(caller(null, { T3CODE_THREAD_ID: id, CLAUDECODE: "1" })).toBeNull();
  455. }
  456. expect(caller("t3:not a thread", {})).toBe("invalid_session");
  457. // A malformed variable is no session, as in the shim.
  458. expect(caller(null, { PLANNOTATOR_SESSION_TAG: "cursor:ses", CODEX_THREAD_ID: "not-a-uuid" })).toBeNull();
  459. // One session named twice is one session.
  460. expect(caller(null, { PLANNOTATOR_SESSION_TAG: `codex:${CODEX_THREAD}`, CODEX_THREAD_ID: CODEX_THREAD })).toEqual({ host: "codex", session: CODEX_THREAD, name: "Codex" });
  461. // Agrees with the shell.
  462. expect(caller("claude-code:s", { PLANNOTATOR_SESSION_TAG: "claude-code:s" })).toEqual({ host: "claude-code", session: "s", name: "Claude Code" });
  463. expect(caller("claude-code:s", { PLANNOTATOR_SESSION_TAG: "opencode:s" })).toBe("session_mismatch");
  464. expect(caller("cursor:ses_x", {})).toEqual({ host: "cursor", session: "ses_x", name: "Cursor" });
  465. expect(caller("ses_x", {})).toEqual({ session: "ses_x" });
  466. // Not a value a wake could have given.
  467. for (const bad of ["a b", "claude-code:", ":x", "$(rm -rf /)", "codex:not-a-uuid", "qwen:ses_x"]) expect(caller(bad, {})).toBe("invalid_session");
    • Note: Quoted as data in code: Runs `rm -rf` against a root or home-directory path
    • Line 499 on GitHub
  468. });
  469. test("--session is parsed anywhere and only once", () => {
  470. expect(parseCallCommand(["card", '{"op":"list"}', "--session", "pi:s"])).toEqual({ ok: true, action: "card", json: '{"op":"list"}', stdin: false, session: "pi:s" });
  471. expect(parseCallCommand(["--session"])).toMatchObject({ ok: false, code: "invalid_session" });
  472. expect(parseCallCommand(["--session", "a", "--session", "b", "card"])).toMatchObject({ ok: false, code: "invalid_session" });
  473. expect(parseCallCommand(["card", "{}", "{}"])).toMatchObject({ ok: false, code: "usage" });
  474. expect(parseCallCommand(["card", "--json"])).toMatchObject({ ok: false, code: "usage" });
  475. // zsh does not split `cmd $S`: the one word says what to do about it.
  476. expect(parseCallCommand(["--session ses_x", "card"])).toMatchObject({ ok: false, code: "usage", error: expect.stringContaining("separate words") });
  477. });
  478. test("a read with no session settles nothing for the thread's owner; one that names the owner's session does; a raw MCP client's settles only its own", async () => {
  479. const box = await world();
  480. const { client, server, project } = box;
  481. await poll(server, "ses-a", project);
  482. const answer = async (messageId: string, subject: string) =>
  483. ((await (await post(server, `/api/inbox/messages/${messageId}/reply`, { words: `${subject} yes.`, idempotency_key: subject })).json()) as { reply: { id: string } }).reply.id;
  484. const replied = async (subject: string, session: string | null = "ses-a") => {
  485. const asked = await tool(client, "send_message", { body: `${subject}?`, subject, thread: subject, project_path: project, ...(session ? { agent_session: session, agent_host: "claude-code" } : {}) });
  486. return { thread: asked.thread_id as string, reply: await answer(asked.message_id, subject) };
  487. };
  488. const scripted = await replied("Scripted");
  489. const raw = await replied("Raw");
  490. const named = await replied("Named");
  491. // A raw MCP client that names no session, sending and reading: the reply to it is its own to settle.
  492. const own = await replied("Own", null);
  493. const checked = async (thread: string) => (await threadOf(server, thread)).messages[0]!.agent_checked_seq ?? null;
  494. for (const json of [{ thread_id: scripted.thread }, { thread_id: scripted.thread, format: "full" }]) {
  495. const read = await cli(box, ["read_thread", JSON.stringify(json)]);
  496. expect(read.code).toBe(0);
  497. expect(read.stdout).toContain("Scripted yes.");
  498. }
  499. // A script's read with no session is a peek, even of a reply to a message sent with none.
  500. expect((await cli(box, ["read_thread", JSON.stringify({ thread_id: own.thread, format: "full" })])).code).toBe(0);
  501. expect(await checked(own.thread)).toBeNull();
  502. // A raw MCP client's read with no session is not a peek: it settles the reply to its own message...
  503. await tool(client, "read_thread", { thread_id: own.thread });
  504. expect(await checked(own.thread)).not.toBeNull();
  505. // ...but not one owed to ses-a, whose connection takes it (only a reply's recipient settles it).
  506. await tool(client, "read_thread", { thread_id: raw.thread });
  507. expect((await cli(box, ["--session", "claude-code:ses-a", "read_thread", JSON.stringify({ thread_id: named.thread })])).code).toBe(0);
  508. const handedOut = (await poll(server, "ses-a", project)).map((command) => command.id);
  509. expect(handedOut).toContain(scripted.reply);
  510. expect(handedOut).toContain(raw.reply);
  511. expect(handedOut).not.toContain(named.reply);
  512. });
  513. test("a list with no session is what a raw MCP client gets, and is never an empty one that hides the project", async () => {
  514. const box = await world();
  515. const { client, project } = box;
  516. await tool(client, "send_message", { body: "Still there?", subject: "Listed", thread: "Listed", project_path: project, agent_session: "ses-a", agent_host: "claude-code" });
  517. const above = dirname(project);
  518. const listed = await cli(box, ["read_thread", "{}"], { cwd: above });
  519. expect(listed.code).toBe(0);
  520. const raw = await tool(client, "read_thread", { project_path: above });
  521. expect(raw.projects_inside).toEqual([expect.objectContaining({ root: project })]);
  522. expect(JSON.parse(listed.stdout).projects_inside).toEqual(raw.projects_inside);
  523. });
  524. });
  525. /** The agent's tidy, as one script: the command on PATH, its output read with nothing but grep. */
  526. const TIDY_SCRIPT = String.raw`#!/bin/bash
  527. set -euo pipefail
  528. call() { plannotator inbox call --session "$SESSION" "$@"; }
  529. for card in $(call card '{"op":"list"}' | grep -o '"id":"crd_[0-9A-Z]*"' | cut -d'"' -f4); do
  530. call card "{\"op\":\"move\",\"card_id\":\"$card\",\"column\":\"in_review\",\"you\":\"Look at the lane\"}" > /dev/null
  531. done
  532. call send_message "{\"reply_to\":\"$ACTION\",\"done\":[\"$ACTION\"],\"body\":\"Saw the deploy go green.\",\"idempotency_key\":\"tidy-done\"}" > /dev/null
  533. call send_message "{\"reply_to\":\"$QUESTION\",\"supersedes\":[\"$QUESTION\"],\"body\":\"The ledger moved, so this no longer applies.\",\"idempotency_key\":\"tidy-withdraw\"}" > /dev/null
  534. call send_message - < "$ANSWER_JSON" | grep -o '"replayed":[a-z]*'
  535. `;
  536. /** The script's world: a `plannotator` on PATH that is this CLI, and the script. */
  537. function scriptOf(box: Box) {
  538. const bin = join(box.root, "bin");
  539. mkdirSync(bin);
  540. const plannotator = join(bin, "plannotator");
  541. writeFileSync(plannotator, `#!/bin/sh\nexec '${process.execPath}' run '${entry}' "$@"\n`);
  542. chmodSync(plannotator, 0o755);
  543. const script = join(box.root, "tidy.sh");
  544. writeFileSync(script, TIDY_SCRIPT);
  545. return async (env: Record<string, string>) => {
  546. const proc = Bun.spawn(["/bin/bash", script], { cwd: box.project, env: { ...box.env, PATH: `${bin}${delimiter}${box.env.PATH}`, ...env }, stdin: "ignore", stdout: "pipe", stderr: "pipe" });
  547. const [stdout, stderr, code] = await Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text(), proc.exited]);
  548. return { code, stdout, stderr };
  549. };
  550. }
  551. describe("a Tidy run from one script", () => {
  552. async function seed(box: World) {
  553. const { client, project, clock, server } = box;
  554. const agent = (session: string, args: Record<string, unknown>) => tool(client, "send_message", { project_path: project, agent_session: session, agent_host: "claude-code", ...args });
  555. clock.behind = 3 * 24 * HOUR;
  556. await poll(server, "ses-a", project);
  557. await poll(server, "ses-b", project);
  558. const question = await agent("ses-a", { subject: "Ledger", thread: "Ledger", body: block("Backfill the ledger first?") });
  559. const deploy = await agent("ses-a", { subject: "Deploy", thread: "Deploy", body: action("Approve the deploy") });
  560. const words = await agent("ses-a", { subject: "Webhooks", thread: "Webhooks", body: "Webhooks are done; screenshots next." });
  561. await tool(client, "card", { op: "create", title: "Ledger lane", column: "in_progress", thread_id: question.thread_id, project_path: project, agent_session: "ses-a", agent_host: "claude-code" });
  562. await tool(client, "card", { op: "create", title: "Docs lane", column: "in_progress", project_path: project, agent_session: "ses-a", agent_host: "claude-code" });
  563. const others = await agent("ses-b", { subject: "Refunds", thread: "Refunds", body: block("Move refunds now?") });
  564. await tool(client, "card", { op: "create", title: "Refunds lane", column: "in_progress", project_path: project, agent_session: "ses-b", agent_host: "claude-code" });
  565. clock.behind = 2 * HOUR;
  566. expect((await post(server, `/api/inbox/messages/${words.message_id}/reply`, { words: "Still waiting on those screenshots.", idempotency_key: "r1" })).status).toBe(200);
  567. for (const command of await poll(server, "ses-a", project)) await bridge(server, INBOX_BRIDGE_EVENT_PATH, { session: "ses-a", host: "claude-code", type: "delivered", id: command.id });
  568. clock.behind = 0;
  569. await poll(server, "ses-a", project);
  570. await poll(server, "ses-b", project);
  571. return { question, deploy, words, others };
  572. }
  573. test("the list's Tidy: one script lists cards, moves several, marks an item done and answers threads; a rerun posts nothing twice", async () => {
  574. const box = await world();
  575. const { server, project } = box;
  576. const { question, deploy, words, others } = await seed(box);
  577. const run = async () => (await runOf(server)).agents;
  578. const started = await post(server, "/api/inbox/tidy", { sessions: ["ses-a", "ses-b"], idempotency_key: "t1" });
  579. expect(started.status).toBe(200);
  580. const wake = await wakeOf(server, "ses-a", project);
  581. await wakeOf(server, "ses-b", project);
  582. // A write counts once it is after the delivery (a later clock tick).
  583. await Bun.sleep(5);
  584. const lastPerson = (await threadOf(server, words.thread_id)).messages.filter((m) => m.author.kind === "person" && !m.tidy).at(-1)!;
  585. const answerJson = join(box.root, "answer.json");
  586. writeFileSync(answerJson, JSON.stringify({ reply_to: lastPerson.id, body: "Screenshots are attached to the card.", idempotency_key: "tidy-answer" }));
  587. const script = scriptOf(box);
  588. // The session comes from the wake alone: this shell names none, as OpenCode's does not.
  589. const env = { SESSION: sessionValueIn(wake.body)!, ACTION: deploy.message_id, QUESTION: question.message_id, ANSWER_JSON: answerJson };
  590. expect(env.SESSION).toBe("claude-code:ses-a");
  591. const first = await script(env);
  592. expect(first).toMatchObject({ code: 0, stdout: '"replayed":false\n' });
  593. // The Inbox's state: its cards moved and only its cards, the item done, the question withdrawn, the words answered.
  594. const cards = JSON.parse((await cli(box, ["card", '{"op":"list","asked_by":"anyone"}'])).stdout).cards as { title: string; column: string; heard_by: { session: string } }[];
  595. expect(Object.fromEntries(cards.map((c) => [c.title, c.column]))).toEqual({ "Ledger lane": "in_review", "Docs lane": "in_review", "Refunds lane": "in_progress" });
  596. const deployThread = await threadOf(server, deploy.thread_id);
  597. expect(deployThread.messages[0]!.questions![0]!.action_result).toMatchObject({ by: "agent" });
  598. const ledger = await threadOf(server, question.thread_id);
  599. expect(ledger.messages[0]!.questions![0]!.state).toBe("superseded");
  600. const webhooks = await threadOf(server, words.thread_id);
  601. const answer = webhooks.messages.filter((m) => !m.tidy).at(-1) as InboxMessage;
  602. expect(answer.body).toBe("Screenshots are attached to the card.");
  603. expect(answer.author).toMatchObject({ host: "claude-code", session: "ses-a", name: "Claude Code" });
  604. // The wake of a session its connection reaches stays the connection's to deliver: the script read no Tidy text.
  605. expect(first.stderr).not.toContain(INBOX_TIDY_INSTRUCTION);
  606. // Tidy's progress: ses-a tidied, in the three threads it was asked about; ses-b, which wrote nothing, not.
  607. const byScript = Object.fromEntries((await run()).map((a) => [a.session, [a.state, a.updated]]));
  608. expect(byScript).toEqual({ "ses-a": ["tidied", 3], "ses-b": ["delivered", 0] });
  609. expect((await threadOf(server, others.thread_id)).messages.every((m) => m.author.session !== "ses-a")).toBe(true);
  610. // A rerun: nothing posts twice, and the cards stay where they are.
  611. const counts = async () => Promise.all([question, deploy, words].map(async ({ thread_id }) => (await threadOf(server, thread_id)).messages.length));
  612. const before = await counts();
  613. const again = await script(env);
  614. expect(again).toMatchObject({ code: 0, stdout: '"replayed":true\n' });
  615. expect(await counts()).toEqual(before);
  616. expect((await run()).find((a) => a.session === "ses-a")!.updated).toBe(3);
  617. }, 120_000);
  618. for (const [name, stale] of [
  619. ["Claude Code", { PLANNOTATOR_SESSION_TAG: "claude-code:ses-old" }],
  620. ["Qwen Code", { QWEN_CODE_SESSION_ID: QWEN_SESSION }],
  621. ] as const) {
  622. test(`a ${name} shell older than its session: refused with no route into the old session, and the way out counts for the Tidy`, async () => {
  623. const box = await world();
  624. const { server, project } = box;
  625. const { words } = await seed(box);
  626. expect((await post(server, "/api/inbox/tidy", { sessions: ["ses-a"], idempotency_key: "t1" })).status).toBe(200);
  627. const wake = await wakeOf(server, "ses-a", project);
  628. await Bun.sleep(5);
  629. const value = sessionValueIn(wake.body)!;
  630. const send = (key: string) => JSON.stringify({ reply_to: words.message_id, body: "Screenshots are on the card.", idempotency_key: key });
  631. const authors = async () => (await threadOf(server, words.thread_id)).messages.filter((m) => m.author.kind === "agent").map((m) => m.author.session);
  632. const before = await authors();
  633. const refused = await cli(box, ["--session", value, "send_message", send("k1")], { env: stale });
  634. expect(refused).toMatchObject({ code: 1, stdout: "" });
  635. expect(refused.stderr).toStartWith("session_mismatch: ");
  636. // It names the variable to clear, the way out that writes as the Tidy's session.
  637. expect(refused.stderr).toContain(Object.keys(stale)[0]!);
  638. expect(refused.stderr).not.toContain("Leave --session out");
  639. expect(await authors()).toEqual(before);
  640. expect((await runOf(server)).agents[0]).toMatchObject({ state: "delivered" });
  641. // A new shell, or that variable unset: the same call is the session the Tidy asked, and it counts.
  642. const unset = await cli(box, ["--session", value, "send_message", send("k2")]);
  643. expect(unset.code).toBe(0);
  644. expect((await authors()).at(-1)).toBe("ses-a");
  645. expect((await runOf(server)).agents[0]).toMatchObject({ state: "tidied", updated: 1 });
  646. });
  647. }
  648. test("the worked examples in --help run as written", async () => {
  649. const box = await world();
  650. const { client, server, project } = box;
  651. const asker = { project_path: project, agent_session: "ses-a", agent_host: "claude-code" };
  652. const question = await tool(client, "send_message", { ...asker, body: block("Ship the ledger?"), subject: "Ledger", thread: "Ledger" });
  653. const item = await tool(client, "send_message", { ...asker, body: action("Approve the deploy"), reply_to: question.message_id });
  654. const made = await tool(client, "card", { ...asker, op: "create", title: "Ledger lane", column: "in_progress" });
  655. const real = (json: string) => json.replaceAll("msg_1", question.message_id).replaceAll("msg_2", item.message_id).replaceAll("crd_1", made.card.id);
  656. const examples = [...INBOX_CALL_USAGE.matchAll(/plannotator inbox call (\w+) '(.+)'$/gm)].map(([, name, json]) => [name!, real(json!)] as const);
  657. expect(examples.map(([name]) => name)).toEqual(["card", "card", "send_message"]);
  658. for (const [name, json] of examples) expect(await cli(box, [name, json], { env: { PLANNOTATOR_SESSION_TAG: "claude-code:ses-a" } })).toMatchObject({ code: 0, stderr: "" });
  659. const [withdrawn, done] = (await threadOf(server, question.thread_id)).messages;
  660. expect(withdrawn!.questions![0]!.state).toBe("superseded");
  661. expect(done!.questions![0]!.action_result).toMatchObject({ by: "agent" });
  662. const cards = JSON.parse((await cli(box, ["card", '{"op":"list","asked_by":"anyone","include_resolved":true}'])).stdout).cards as { column: string }[];
  663. expect(cards.map((c) => c.column)).toEqual(["done"]);
  664. });
  665. test("the Board's Tidy: a script that only moves cards counts as tidied, for that session", async () => {
  666. const box = await world();
  667. const { server, project, client, clock } = box;
  668. clock.behind = 3 * 24 * HOUR;
  669. await poll(server, "ses_oc1", project, "opencode");
  670. await poll(server, "ses-b", project);
  671. await tool(client, "send_message", { project_path: project, agent_session: "ses_oc1", agent_host: "opencode", subject: "Lane", thread: "Lane", body: "Starting." });
  672. await tool(client, "card", { op: "create", title: "Lane", column: "in_progress", project_path: project, agent_session: "ses_oc1", agent_host: "opencode" });
  673. await tool(client, "send_message", { project_path: project, agent_session: "ses-b", agent_host: "claude-code", subject: "Other", thread: "Other", body: "Starting." });
  674. await tool(client, "card", { op: "create", title: "Other", column: "in_progress", project_path: project, agent_session: "ses-b", agent_host: "claude-code" });
  675. clock.behind = 0;
  676. await poll(server, "ses_oc1", project, "opencode");
  677. await poll(server, "ses-b", project);
  678. const asked = await planOf(server, "?surface=board");
  679. expect(asked.agents.map((a) => a.session).sort()).toEqual(["ses-b", "ses_oc1"]);
  680. expect((await post(server, "/api/inbox/tidy", { sessions: ["ses_oc1", "ses-b"], idempotency_key: "t1", surface: "board" })).status).toBe(200);
  681. const wake = await wakeOf(server, "ses_oc1", project, "opencode");
  682. await wakeOf(server, "ses-b", project);
  683. await Bun.sleep(5);
  684. // OpenCode's shell marks itself and names no session.
  685. const env = { OPENCODE: "1" };
  686. const session = sessionValueIn(wake.body)!;
  687. expect(session).toBe("opencode:ses_oc1");
  688. const mine = JSON.parse((await cli(box, ["--session", session, "card", '{"op":"list"}'], { env })).stdout);
  689. expect(mine.cards.map((c: { title: string }) => c.title)).toEqual(["Lane"]);
  690. const moved = await cli(box, ["--session", session, "card", JSON.stringify({ op: "move", card_id: mine.cards[0].id, column: "in_review", you: "Pick a name" })], { env });
  691. expect(moved.code).toBe(0);
  692. expect(JSON.parse(moved.stdout).card.heard_by).toMatchObject({ host: "opencode", session: "ses_oc1" });
  693. expect(Object.fromEntries((await runOf(server)).agents.map((a) => [a.session, a.state]))).toEqual({ ses_oc1: "tidied", "ses-b": "delivered" });
  694. }, 60_000);
  695. test("an MCP-only agent: the text reaches the script's reader on stderr, once, and the value makes its writes count", async () => {
  696. const box = await world();
  697. const { server, client, project, clock } = box;
  698. clock.behind = 3 * HOUR;
  699. const asked = await tool(client, "send_message", { project_path: project, agent_session: "ses_mcp", agent_host: "cursor", subject: "Keys", thread: "Keys", body: block("Rebind keys?") });
  700. clock.behind = 0;
  701. await tool(client, "read_thread", { thread_id: asked.thread_id, agent_session: "ses_mcp" });
  702. expect((await post(server, "/api/inbox/tidy", { sessions: ["ses_mcp"], idempotency_key: "t1" })).status).toBe(200);
  703. const first = await cli(box, ["--session", "cursor:ses_mcp", "read_thread", JSON.stringify({ thread_id: asked.thread_id })]);
  704. expect(first.code).toBe(0);
  705. expect(first.stderr).toContain(INBOX_TIDY_INSTRUCTION);
  706. expect(sessionValueIn(first.stderr)).toBe("cursor:ses_mcp");
  707. expect(JSON.parse(first.stdout).tidy.text).toContain(INBOX_TIDY_INSTRUCTION);
  708. await Bun.sleep(5);
  709. const reply = await cli(box, ["--session", "cursor:ses_mcp", "send_message", JSON.stringify({ reply_to: asked.message_id, body: "No longer applies.", idempotency_key: "k1" })]);
  710. expect(reply.code).toBe(0);
  711. expect(reply.stderr).toBe("");
  712. expect((await runOf(server)).agents).toEqual([expect.objectContaining({ session: "ses_mcp", state: "tidied", updated: 1 })]);
  713. });
  714. });
  715. describe("a Codex thread's script and the reply wake (#2573)", () => {
  716. /**
  717. * The Inbox runs with a fake `codex` (tests/helpers/fake-agents.ts) and its
  718. * own scratch CODEX_HOME, where the thread's rollout says what started it.
  719. * The thread never called the Inbox tool: only `plannotator inbox call` from
  720. * its shell (CODEX_THREAD_ID), as an agent that did not find the MCP tools.
  721. */
  722. type Rollout = { source: unknown; originator: string };
  723. /** The thread's rollout, in the day folder its UUIDv7 id names (`created`), or a later one (a thread resumed months on). */
  724. function writeRollout(codexHome: string, rollout: Rollout, where: "created" | "later" = "created") {
  725. const day = join(codexHome, "sessions", where === "created" ? codexRolloutDayFolders(CODEX_THREAD)[0]! : join("2026", "11", "03"));
  726. mkdirSync(day, { recursive: true });
  727. const meta = { timestamp: "2026-11-03T10:00:00.000Z", type: "session_meta", payload: { id: CODEX_THREAD, timestamp: "2026-11-03T10:00:00.000Z", cwd: "/tmp", cli_version: "0.166.0", ...rollout } };
  728. writeFileSync(join(day, `rollout-2026-11-03T10-00-00-${CODEX_THREAD}.jsonl`), `${JSON.stringify(meta)}\n`);
  729. }
  730. async function codexWorld(rollout: Rollout | null, options: { where?: "created" | "later"; env?: (root: string) => Record<string, string>; now?: () => number } = {}) {
  731. const box = sandbox();
  732. const fake = createFakeAgents("plannotator-inbox-call-codex-");
  733. fakes.push(fake);
  734. fake.install("codex");
  735. if (rollout) writeRollout(fake.env.CODEX_HOME!, rollout, options.where);
  736. const server = await startInboxServer({
  737. dataDir: box.dataDir,
  738. binaryPath: null,
  739. agentEnvironment: createAgentEnvironmentFor({ platform: "linux", homeDir: fake.home, env: { ...fake.env, ...options.env?.(fake.root) } }),
  740. codexWake: { extraClis: [], ...(options.now ? { now: options.now } : {}) },
  741. });
  742. servers.push(server);
  743. return { ...box, fake, server };
  744. }
  745. type CodexWorld = Awaited<ReturnType<typeof codexWorld>>;
  746. const queues = (fake: FakeAgents) => fake.calls().filter((call) => call.name === "codex" && call.args[0] === "queue");
  747. /** A send from the thread's shell, and whether the message it stored wakes. */
  748. async function scriptSends(w: CodexWorld, body: string) {
  749. const sent = await cli(w, ["send_message", JSON.stringify({ body })], { env: { CODEX_THREAD_ID: CODEX_THREAD } });
  750. expect(sent.code).toBe(0);
  751. const { message_id, thread_id } = JSON.parse(sent.stdout) as { message_id: string; thread_id: string };
  752. const message = (await threadOf(w.server, thread_id)).messages.find((m) => m.id === message_id)!;
  753. return { message_id, thread_id, message, wakes: message.wakes === true };
  754. }
  755. const answer = (w: CodexWorld, messageId: string, words: string) => post(w.server, `/api/inbox/messages/${messageId}/reply`, { idempotency_key: `k-${messageId}`, words });
  756. const interactive: [string, Rollout, "created" | "later"][] = [
  757. ["the TUI", { source: "cli", originator: "codex-tui" }, "created"],
  758. ["the Codex app, resumed months after it was made", { source: "vscode", originator: "Codex Desktop" }, "later"],
  759. ];
  760. for (const [name, rollout, where] of interactive) {
  761. test(`a thread of ${name}: its script's message wakes, and the person's reply goes in through codex queue`, async () => {
  762. const w = await codexWorld(rollout, { where });
  763. const sent = await scriptSends(w, "Ship the worker today?");
  764. expect(sent.message.author).toMatchObject({ kind: "agent", host: "codex", session: CODEX_THREAD });
  765. expect(sent.wakes).toBe(true);
  766. expect((await answer(w, sent.message_id, "Yes, ship it.")).status).toBe(200);
  767. await w.server.codexWake.sweep();
  768. const calls = queues(w.fake);
  769. expect(calls).toHaveLength(1);
  770. expect(calls[0]!.args[1]).toBe(`--thread=${CODEX_THREAD}`);
  771. expect(calls[0]!.args[2]).toContain("Yes, ship it.");
  772. });
  773. }
  774. const never: [string, Rollout | null][] = [
  775. ["a codex exec run", { source: "exec", originator: "codex_exec" }],
  776. ["a codex exec run whose source reads cli", { source: "cli", originator: "codex_exec" }],
  777. ["a subagent", { source: { subagent: "review" }, originator: "codex-tui" }],
  778. ["a thread with no rollout", null],
  779. ];
  780. for (const [name, rollout] of never) {
  781. test(`${name} is never woken from its script: nothing is queued for the reply`, async () => {
  782. const w = await codexWorld(rollout);
  783. const sent = await scriptSends(w, "One turn only.");
  784. expect(sent.wakes).toBe(false);
  785. expect((await answer(w, sent.message_id, "Yes.")).status).toBe(200);
  786. await w.server.codexWake.sweep();
  787. expect(queues(w.fake)).toEqual([]);
  788. });
  789. }
  790. test("a rollout not found is not looked for on every send; one written since is found once that wait is over", async () => {
  791. const clock = { ahead: 0 };
  792. const w = await codexWorld(null, { now: () => Date.now() + clock.ahead });
  793. expect((await scriptSends(w, "Before Codex wrote its rollout.")).wakes).toBe(false);
  794. writeRollout(w.fake.env.CODEX_HOME!, { source: "cli", originator: "codex-tui" });
  795. expect((await scriptSends(w, "Within the minute.")).wakes).toBe(false);
  796. clock.ahead = 61_000;
  797. const later = await scriptSends(w, "A minute on.");
  798. expect(later.wakes).toBe(true);
  799. expect((await answer(w, later.message_id, "Got it.")).status).toBe(200);
  800. await w.server.codexWake.sweep();
  801. expect(queues(w.fake).map((call) => call.args[2])).toEqual([expect.stringContaining("Got it.")]);
  802. });
  803. test("a thread codex queue said it does not know: its script no longer wakes it, whatever its rollout says", async () => {
  804. const w = await codexWorld({ source: "cli", originator: "codex-tui" }, { env: (root) => ({ FAKE_CODEX_UNKNOWN_FILE: join(root, "unknown") }) });
  805. writeFileSync(join(w.fake.root, "unknown"), CODEX_THREAD);
  806. const first = await scriptSends(w, "Ship it?");
  807. expect(first.wakes).toBe(true);
  808. expect((await answer(w, first.message_id, "Yes.")).status).toBe(200);
  809. await w.server.codexWake.sweep();
  810. expect(queues(w.fake)).toHaveLength(1);
  811. expect(w.server.codexWake.status(CODEX_THREAD)).toBe("dead");
  812. // Its shell's call says it is there (off `dead`), not that Codex knows it again: still no wake.
  813. const again = await scriptSends(w, "Still there?");
  814. expect(again.wakes).toBe(false);
  815. expect((await answer(w, again.message_id, "Yes, still.")).status).toBe(200);
  816. await w.server.codexWake.sweep();
  817. expect(queues(w.fake).some((call) => call.args[2]!.includes("Yes, still."))).toBe(false);
  818. });
  819. });

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.