diff --git a/CHANGELOG.md b/CHANGELOG.md index 144f6a7ad..2df263e30 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,9 +1,28 @@ # Changelog -## 1.0.18-beta.0 — 2026-11-30 +## 1.0.18 — 2026-11-30 + +### Features + +- Self Reports: every agent failproofai supports gets a `report` tool (MCP server `failproofai_local`) and calls it once, with a category and a one-sentence reason, when it is stuck on something it cannot fix (a missing or expired key, a 401, a command that keeps failing, missing information, a request it cannot do). Each call is a `self_report` event on its session in FailproofAI Cloud, for alerts, audits and patterns. On unless turned off in Cloud (or `self-report disable` off-Cloud); `self-report status` shows everything. Each CLI gets the tool and the instruction through a channel it always loads (Claude Code `alwaysLoad`, Codex `AGENTS.md`, Copilot instructions file, Antigravity rules plugin and `eager`, Factory SessionStart, OpenClaw per-turn context, the Pi, Hermes and OpenClaw plugins). Python and TypeScript SDK tools for custom agents. Tested on all 12 CLIs with real models: 40 of 40 stuck runs reported, 0 false reports in 27 normal runs, and no change in agent behaviour with the tool on vs off (#1062) +- Agents can no longer edit any agent's settings or hook files to switch failproofai off, through file tools or the shell; `config --status` flags a Claude Code `disableAllHooks` that would (#1053) +- CI: the contributor-welcome workflow now greets only external contributors (not owners, org members, collaborators or bots, so Dependabot PRs no longer get a thank-you comment), pages the team in Slack's #oss-contributor channel through the `SLACK_OSS_CONTRIBUTOR_WEBHOOK_URL` secret, and tells the contributor that @NiveditJain has been paged, with his X and the team Discord to follow up on (#1066) ### Fixes +- The settings guard treats a reader (`cat`, `jq`, `grep`, `head`, …) that names an agent settings file as read-only only when it is the real system tool: a project's own `./cat`, a copy found earlier on the agent's PATH, or a reader redefined on the same line no longer gets the exemption; an editor opened on the file (`code`, `open`) follows the same rule (#1105) +- The state and settings guards keep judging the lines after a heredoc fed to `cat` or `tee`; before, a command placed after the heredoc's closing line was not checked (#1105) +- Self Reports: when the daemon evaluates a hook, the report tool's exemption is judged against the configuration the calling agent uses (its `CODEX_HOME`, `CLAUDE_CONFIG_DIR` and the like, sent by the hook), not the daemon's; with none sent, there is no exemption (#1105) +- The settings guard reads a Codex command's `workdir`, and when Codex reports none it assumes the command may run in Codex's own config directory, so a relative write to Codex's `config.toml` or `hooks.json` is refused; ordinary relative writes elsewhere stay allowed (#1105) +- The Codex interactive-session guard also refuses a pass-through pipe into a shell (`cat | bash`), a shell started through `script -c` or `su -c`, and an interpreter reading its program from typed input (`node -`, `ruby -`, `perl -`, `/dev/stdin`) (#1105) +- The settings guard also covers OpenCode's `opencode.json(c)` in any directory and `.vscode/settings.json` (its `chat.hookFilesLocations` decides which hook files VS Code agent mode loads) (#1105) +- Self Reports: the report tool's exemption accepts only the calling agent's own spelling of the tool name, and none when another configured server, extension or tool file could produce the same name (#1105) +- Setup warns again when Codex has not trusted failproofai's hooks, with how to fix it (#1105) +- Self Reports: the stdio server answers a request whose handler fails with a JSON-RPC error instead of leaving the agent waiting; old post-failure hint files are cleaned up; the agent-process lookup runs only while Self Reports is on, and on macOS walks up with `ps -p` instead of `ps -A` (#1105) +- Harden Codex and Copilot tool input handling: text sent to a running shell (Copilot `write_bash` and `write_powershell`, Codex `write_stdin`) is checked by the shell policies as the command lines it runs where the agent reports it, input that cannot be read as whole command lines is refused, and a Codex command that opens an interactive shell or REPL is refused (#1058) +- The always-on guard (`block-failproofai-commands`) also refuses agent writes of `node_modules/.bin/failproofai`, the file a project-scope hook's `npx -y failproofai` runs before the installed CLI, in the project or any directory above it: through the file tools (symlinks included) and every file a patch names (Codex's native `apply_patch` carries no `file_path`, and OpenClaw's reaches policies under its own name), and through shell commands that write it, copy, move, link or download a file of that name (`scp`, `wget`, `curl -O` included), name it as a value glued to an option (`curl -so`), in curl's `--output-dir` or as a file a sed script writes, or put a whole directory into npm's `.bin`, including after a `cd` (or one that may have failed, or a `cd -P` through a link), through a symlink (one the same line makes is resolved as the kernel resolves it, and a glob is expanded where its directories really are, on disk as the shell expands it), through a variable the same line sets (whichever of its values a subshell or a one-command assignment leaves it, read when it is assigned, through another variable, an operator such as `${D%/}` or `${X:-bins}`, a `cd`, a loop, `read`, `printf -v` or `declare -n`), through a glob however many names it matches (`tee many/*` with a link among them) and a write that sweeps a bin directory (`tee bins/*`), through a long option cut short as curl before 8 and getopt_long take it (`--output-di`), wget's `--default-page` and `-e`, curl's other output files (`--stderr`, the cookie jar), a sed script, patch or curl config read from a file, an archive extracted into a bin directory, or behind a trailing redirect. A Codex command, which may run in a `workdir` its hook does not report, is refused when a relative destination would plant the entry, through any directory on the way. One Write of an `exit 0` stub there had turned every later hook in that tree into an allow. The same fixes close five ways around the state guard: a native patch naming it, a redirect after the destination (`cp /dev/null ~/.failproofai/policies-config.json 2>/dev/null`), another user's home in a glob (`rm -rf /home/alice/.failproof*`), a variable spliced into the path (`X=ai; rm -rf ~/.failproof$X`), and an output file glued to curl's option (`curl -so~/.failproofai/policies-config.json `); and quoted text that `echo` or `printf` only prints (`echo 'cat > ~/.failproofai/policies-config.json'`), to the terminal or into a documentation file nothing on the line runs, is no longer read as a redirect. npx's other inputs (a `package.json` `bin` entry, `.npmrc`, dependency installs) are not covered (FailproofAI/agenteye#1795, #1058) +- An agent can no longer switch its own enforcement off by editing its CLI's settings: the always-on guard (`block-failproofai-commands`) refused writes to `~/.failproofai` only, so `"disableAllHooks": true` in the Claude Code settings layer that decides it, or failproofai's entries taken out of any agent's hooks file, stopped every policy, the guard included. It now refuses agent writes to every integration's settings and hook files (Claude Code, Codex `hooks.json` and `config.toml`, Copilot, Cursor, OpenCode, Pi, Antigravity, Goose, Factory, Devin, Hermes, OpenClaw, and the file the hook was loaded from when `CLAUDE_CONFIG_DIR` or `CODEX_HOME` moved it): Write, Edit, MultiEdit, NotebookEdit and `apply_patch` edits, checked after symlinks (a `..` after a link included, and every file behind Hermes' installed plugin link or in failproofai's own plugin directories), and shell writes, through a link's name too, by the same walk that protects `~/.failproofai`, plus `codex features disable hooks`. That walk now reads a command the way a shell does (quotes, comments, `${…}`, `$(…)`, heredocs), judges text piped into a shell (the failproofai CLI's too), follows a `cd` to the file a relative destination lands on (`cd -`, `cd -P` and a `cd` that may fail included), and catches `yq -i`, `awk -i inplace`, `sed`'s `e`/`W` and bundled `-i`, output options (`git log --output`, `sort -o`), commands git runs (`rebase -x`, `filter-branch`) and file-moving `git` subcommands, `xargs`, process substitutions, variables spliced into a path, a copy followed by a redirect (`2>/dev/null`) or given a target directory however spelled (`-t`), and interpreters' inline programs, for the state as well; it no longer reads commit messages, PR bodies, comments or other quoted arguments as commands, and git hooks in `.github/hooks/` stay editable. A shell write that never names the file (a script written earlier and run later) is not seen. This guard leaves reads alone (the opt-in `block-read-outside-cwd` refuses them when enabled), and `failproofai config --status` now reports a `disableAllHooks` that is switching failproofai's Claude Code hooks off (#1053, FailproofAI/agenteye#1794) +- `failproofai audit` reads Codex's code-mode transcripts. From about Codex 0.146, and for every tool call on 0.172, Codex logs a tool call as a `custom_tool_call` (`exec`, whose input is a script calling `tools.exec_command(…)` and the other tools, or a freeform `apply_patch`), which audit skipped, so those sessions scanned as zero tool calls. Each call in the script is now read as its own event without running it; a command built from a variable is kept as the script. Codex's `exec_command {cmd, workdir}` now maps to `Bash {command, cwd}`, so the Bash builtins fire on older Codex transcripts too, and an `apply_patch` names the file it touches. Codex entries already in the audit cache are re-scanned once (#1053) - Preserve bracketed units in Cloud CLI query results, so column labels like `latency [ms]` keep their units in the terminal (#1031). - Copilot: map the `task` tool to `Task` and `web_search` to `WebSearch`, so policies matching them fire on Copilot sessions instead of silently never running. The subagent tool reaches the PascalCase hooks as `Agent` (verified against Copilot CLI 1.0.117) and Copilot's session log as `task`, so both names map (#1101, from #693, #792, #844, fixes #690) - The Codex session cache (`state/codex-session-paths.json`) is written to a temp file and renamed into place. A write cut short by a full disk or a killed hook used to leave a torn file, and the next read discarded every cached session (#1102, from #692, #847, fixes #689) @@ -29,14 +48,92 @@ - `fpai-collect`: update `notify` from 8.2.2 to 9.0.0 and `rusqlite` from 0.42.0 to 0.43.0 (#1049) - Update `posthog-node` from 5.73.0 to 6.0.5. The dashboard server's events now go to PostHog's Capture V1 endpoint (`/i/v1/analytics/events`) and keep the `$lib` they set, so they report `$lib: failproofai` with a `$lib_version` instead of `posthog-node`; the real delivery test checks the new endpoint, its bearer token, per-event acknowledgements and retries (#1043) -## 1.0.18-beta.0 — 2026-11-24 +## 1.0.18-beta.4 — 2026-11-29 ### Features +- Self Reports: `task_failure` now also covers anything else that blocks the agent and no other category describes, so a report never has to be forced into the wrong category (#1062) + +- Self Reports: the `report` tool is a direct tool on Hermes and OpenClaw, which defer MCP tools behind their tool search with no per-server switch (so the model saw only a name and never reported). failproofai's Hermes plugin registers it natively and puts it on Hermes' never-deferred list, and the OpenClaw plugin registers a `catalogMode: "direct-only"` tool; both put the server's instructions in the prompt (`pre_llm_call`, `before_prompt_build`) and hand each call to failproofaid's own Self Reports server, so the text, attribution, dedup and logs are the MCP path's. Sync writes no Hermes or OpenClaw MCP entry and removes the old ones (#1062) +- Self Reports: Claude Code's entry sets `alwaysLoad: true` (its tools are never deferred behind tool search), Antigravity's sets `eager: true` (direct tools rather than `call_mcp_tool`), Copilot gets the instructions in a marked `~/.copilot/instructions/failproofai-self-reports.instructions.md` (Copilot shows server instructions only for its built-in allowlist), and Factory droid, which defers every other MCP server, gets them as SessionStart context (#1062) +- Self Reports: the instructions now reach Codex, Antigravity and OpenClaw through a channel each always loads, since their models rarely looked for a deferred `report` tool. Codex gets a marked block in its global `$CODEX_HOME/AGENTS.md` (or `AGENTS.override.md` when that exists) with one more line telling it to search its tools for `failproofai_local`; Antigravity gets a marked plugin, `~/.gemini/config/plugins/failproofai-self-reports/`, whose `rules/AGENTS.md` it merges into every session; the OpenClaw plugin returns them as per-turn `appendContext` as well as `appendSystemContext`. Both files carry this machine's categories and guidance (the daemon now re-syncs when Cloud changes those), are written only while Self Reports is on for a hooked agent, leave everything outside the markers alone, and are removed by `self-report disable`, `policies --uninstall` and `uninstall` (#1062) +- Self Reports: after a tool call failure that clearly blocks (an auth or credential error such as a 401 or 403, an invalid or expired key or token, or a `*_TOKEN` that is not set; or the same tool or command failing a second time in the session), one line of context once per session suggests calling `report` if the agent cannot fix it. One non-zero exit, and read-only exploration (`ls`, `cat`, `grep`, `find`, `test`, Read, Glob) failing, never earn it. On Claude Code, Codex, Cursor, Copilot (its failure event) and Factory. Never on success, on the report call, after a failproofai deny, or while Self Reports is off; it is not a policy and never replaces one's answer (#1062) + +### Fixes +- Self Reports on macOS: the stdio server's log lines after the first reached the daemon log again. Each line's connection was torn down as soon as its write finished, and macOS drops a connection the daemon has not accepted yet, data and all; the client now half-closes and waits for the daemon to close. The process lookup (`ps`, synchronous on macOS) also runs once at start, and a budget timer that fires late gets one more budget (#1062) +- `update` and `config` no longer say "restart the gateway" for Hermes or OpenClaw on a machine where that program is not installed: with no `hermes` or `openclaw` there is no gateway to restart (#1062) +- Quieter `update`, `config` and `policies --install`/`--uninstall`: no `Hermes: hermes/default already current, gateway restarting` or `OpenClaw: openclaw/default gateway restarting` rows and no `Self Reports: on for N agents` line when all went well. Only what needs the user is printed (a gateway to restart by hand, a Hermes failure, an agent the Self Reports sync could not update); `self-report status` shows the last update's gateway rows (#1062) +- Self Reports: the daemon log's report preview is cut on a character boundary and marked with an ASCII `...`, so no multi-byte character is split (seen as `enviro�`); the stdio server and the CLI cut the preview and the guidance line by code point, never through a surrogate pair (#1062) +- Self Reports: upgrading takes the `failproofai_local` MCP entry an earlier version wrote out of Hermes' `config.yaml` and OpenClaw's `openclaw.json` (their tool now comes from the plugin) before their gateways restart, so a restarted OpenClaw no longer starts the stdio server for it. Setup also syncs Self Reports before it restarts gateways, for the same reason (#1062) +- Self Reports: the server instructions and the tool description now open with what to do (when stuck, call the `report` tool with `category` and a one-sentence `detail`). Codex 0.172's code mode keeps only about 250 characters of each, so the old opening never got as far as how to call it (#1062) +- Self Reports: a Devin report is recorded once, as devin. Devin also runs Claude Code's hooks, so the Claude path recorded the same call as claude; it now recognises a Devin call (a `devin` process above the hook, or Devin's payload shape) and leaves it to Devin's MCP server (#1062) +- Self Reports: a Cloud settings file is bound to the enrolment whose poll wrote it. After switching to another org, the previous org's "on" no longer records until the new org's setting arrives: every reader (CLI, hook, stdio server, the daemon's HTTP server) treats a file from another enrolment, or from before this change, as missing, which is off while enrolled (#1062) +- Self Reports: the SDK tool name `failproofai_report` is no longer let past the policies in the hook path. It is also OpenCode's name for a `report` tool on any MCP server called `failproofai`, so a foreign server's tool skipped every policy (#1062) +- `block-failproofai-commands` no longer treats any `python -c` program as a read: its read-only vetting could be bypassed with dynamic builtin lookups. Nothing in a command is treated as inert when the same command defines a function or alias, or sets `PATH` (#1062) +- Self Reports: the stdio server suppresses a Claude Code or Codex report only when that agent's hook recorded the same call: same working directory, and each hook row vouches for one call. A report the hook recorded in one project no longer swallows an identical one from another (#1062) +- Self Reports: Claude Code and Codex are registered over stdio, never on the daemon's endpoint, which records nothing for them. Their entry is user-wide while a project can turn the hooks off (`disableAllHooks` in `.claude/settings.local.json`), and every report from such a project was lost; the stdio server now records what the hook did not (#1062) +- Self Reports: a report is always filed under a listed category. A call with no `category` (seen from Copilot), a near-miss spelling, or a name that is not on the list is resolved to the listed name it normalises to, else inferred from the category and detail by keyword (a missing token or a 401 is `invalid_tool_or_credential`), else `task_failure` (or an org list's first category); it was recorded with a blank or unknown category. The same rules run in the stdio server, the hook path, the daemon and both SDKs (test-fixtures/self-report/category-inference.json), and the daemon log says `inferred_category=true` with what the model sent (#1062) +- Self Reports: the hook lets the `report` tool past the policies only when the `failproofai_local` server the agent would use is failproofai's own: its user-wide entry passes the installer's ownership test (our `mcp --agent` command or our loopback URL), no project-scope config (`.mcp.json`, `.cursor/mcp.json`, Claude Code's per-project entries in `.claude.json`, and the like) defines that name, and for Hermes, OpenClaw and Pi no other server of that name collides with the plugin's tool. A foreign server registered as `failproofai_local` was let past a deny-all policy; now it, and anything that cannot be read, goes through the policies like any other tool (#1062) +- `block-failproofai-commands` treats a quoted `grep`/`rg`/`jq` argument as data only when the command word is the standard tool: a bare name while PATH has no relative entry, or a path in `/usr/bin` or `/bin`. A project's own `./grep` (or any other program of that name) that ran its argument was judged by its basename and could run the pause CLI. A `PATH` or `BASH_ENV` assignment the shell assembles from quoted or escaped pieces (`PA""TH=…`) is now seen too, and turns the exemption off like a plain one (#1062) +- Self Reports: a Claude Code or Codex hook row now stands only for a call from its own agent process. The hook stamps a report call with the processes above it, and the stdio server suppresses its copy only when its own parent (the agent that started it) is one of them. Another session in the same directory, whose hooks did not run, no longer has its identical report swallowed by the first session's row and then filed under the wrong session; when the hook could not tell, the server records (#1062) +- Self Reports: the Hermes plugin registers the `report` tool even when Self Reports is off (or failproofaid cannot be reached) as the gateway starts. A gateway started that way kept no tool, so `self-report enable` never reached it until a restart; now the tool's availability and the instructions in `pre_llm_call` follow the daemon live, at most a minute behind, and the heartbeat records whether reporting was on at start (#1062) +- Self Reports: the Pi extension asks for the `report` tool again, at most once a minute, when a session starts or a prompt is sent, not only when Pi loads. A Pi started while Self Reports was off, or while it waited for FailproofAI Cloud's setting, kept no tool until it was reloaded; it now gets the tool from its next prompt, and turning Self Reports off takes the tool out of Pi's active tools (#1062) +- Self Reports: the stdio server sends the daemon a report's whole detail (bounded at 2000 characters) for its log line, so secrets are scrubbed from all of it before the line is cut to 40 characters. It used to cut the detail to 200 characters first, and a JWT longer than that reached the scrubber in pieces and its start was logged (#1062) +- Self Reports: the daemon and hook log lines show the category the model sent (`category`, `raw_category`) only when it is shaped like a category name (lowercase, at most 32 characters, at most 4 digits); anything else, such as a token passed as the category, is logged as `(N characters, not shown)`. It was logged verbatim over both stdio and HTTP (#1062) +- Self Reports: the `report` tool's exemption from the policies now needs a stdio entry whose command, followed through every link, is this failproofai's own CLI entry point, run as `mcp --agent `; a foreign program merely named like failproofai, or a loopback HTTP entry, takes the policy path. A project beneath your home directory no longer has the agents' own user-wide configs (`~/.codex/config.toml`, `~/.cursor/mcp.json`, …) read as project overrides, which refused the genuine tool there (#1062) +- `block-failproofai-commands` decides whether a bare `grep`/`rg`/`jq` (or `cat`/`tee` for a heredoc) is the standard tool from the agent's own PATH, which the hook client now carries in the payload, not from the PATH of the process evaluating it. Through failproofaid that was the daemon's PATH, so a shadow `grep` early on the agent's PATH could run a quoted argument; with no agent PATH (an older client, the Hermes and OpenClaw plugins) no bare name is exempt (#1062) +- Self Reports: the stdio server matches hook rows and picks the session for a report by its own agent process, exactly: each side names the nearest process above it that is not a shell or exec wrapper, and session-start and prompt rows now carry it too. An agent started inside another one in the same directory no longer has its hook rows claimed, or its reports filed, under the outer agent's session; with no session of its own it takes its own transcript, else `unattributed` (#1062) +- Self Reports: the daemon log's report preview is scrubbed from the detail as the agent sent it (bounded at 64 KiB), not from the 2000-character report. A credential that straddled that cut, such as a JWT starting near the beginning and running past it, was cut into something the scrubber no longer recognised, and its start reached the log over both stdio and HTTP (#1062) +- Self Reports: commands that send a log event to the daemon (the stdio MCP server, `self-report enable`/`disable`) exit 0 again instead of 13. The log client now waits for the daemon to close the connection, and with both its socket and its budget timer unref'd nothing kept Node running while it waited; the budget timer now does, for at most the budget (#1062) +- Self Reports: the `report` tool's exemption also needs the entry to be exactly what the installer writes for that agent: any `env` (`NODE_OPTIONS`, `PATH`, `LD_PRELOAD`, …), `envFile`, `cwd`, extra argument or other field can change what runs, so such an entry takes the policy path. Sync and uninstall now treat an entry as theirs only when its command resolves to a failproofai package's CLI (any version, so an earlier install's entry is still upgraded) or is a failproofai launcher that no longer exists; a foreign program merely named like failproofai is reported as a conflict and left alone instead of replaced (#1062) +- Self Reports: right after an upgrade, while failproofaid still runs the previous build's worker, a Claude Code or Codex report is no longer recorded twice. The hook client stamps the report call in both the current and the earlier form, and the stdio server matches a row stamped either way; a row whose stamp it cannot read is still recorded rather than dropped (#1062) +- Self Reports: a report's detail is cut to 2,000 characters without ever keeping part of a word: when the cut lands inside one, that whole word goes (a detail that is one long word reads `[detail cut]`). A credential that ran past the cut, such as a long JWT, was kept as a 2,000-character fragment that upload redaction no longer recognised, and was uploaded raw through the hook, the stdio and HTTP servers and both SDKs. The same rule runs in all of them and is pinned in the shared golden fixture (#1062) +- Self Reports: the daemon log's detail, bounded at 64 KiB before the daemon scrubs it, is cut the same way, so a token straddling that bound no longer reaches the log as a recognisable-to-no-one prefix (#1062) -- CI: the contributor-welcome workflow now greets only external contributors (not owners, org members, collaborators or bots, so Dependabot PRs no longer get a thank-you comment), pages the team in Slack's #oss-contributor channel through the `SLACK_OSS_CONTRIBUTOR_WEBHOOK_URL` secret, and tells the contributor that @NiveditJain has been paged, with his X and the team Discord to follow up on (#1066) +### Docs + +- Self Reports docs: Pi has MCP from 0.99, but its MCP tools default to `codemode`; failproofai keeps giving Pi the report tool through its extension, verified on Pi 0.85.1 and 1.7.0 (#1062) +- Self Reports docs: Cloud has no Self Reports page; a report shows on the agent's session timeline and on the event itself, and the Cloud audit agent always sees it in transcripts. Settings and alerts stay. Also covers the tighter failure hint, the quieter output and Devin running Claude Code's hooks (#1062) + +## 1.0.18-beta.3 — 2026-11-27 + +### Fixes + +- Self Reports: the daemon's sync after a Cloud setting failed with exit 1 for every agent the MCP server records (Copilot, Cursor, OpenCode, Hermes, OpenClaw, Factory, Devin, Antigravity, Goose): under the service's `PATH` no `failproofai` was found and the CLI it runs is named `cli.mjs`, so there was no stdio command to write. The sync now takes the `failproofai` npm installed beside the daemon's Node (then npm's and bun's global bins), `self-report sync --quiet` names each agent it could not update on stderr, and the daemon logs those lines as warnings ahead of its verdict (#1062) +- Self Reports: the daemon also syncs the agents when it first writes the Cloud settings file and when the file's source changes, not only when `enabled` or the port does. A machine that enrolled with its own settings file (which reads as off until Cloud answers) got the org's "on" with no sync, so no agent was registered until a manual `self-report sync` (#1062) +- Self Reports: a Codex report is no longer lost when Codex does not run failproofai's hooks (Codex 0.129+ runs an untrusted `~/.codex/hooks.json` hook never), nor a Claude Code one with `disableAllHooks`. The stdio server records a Claude Code or Codex report unless the agent's hook already recorded that report (the hook runs before the MCP call), filed on the session the agent's own rollout or transcript names; such an agent is registered over stdio rather than on the daemon's endpoint, `status` says who records each one's reports and how to trust the Codex hooks, and `self-report test` follows the same path (#1062) +- Self Reports on Pi: Pi before 0.99 has no MCP at all, so the `failproofai_local` entry in `~/.pi/agent/mcp.json` never reached the model, `exposure: "direct"` or not. failproofai's Pi extension now registers `mcp__failproofai_local__report` itself, with the server's description, categories and instructions (as a system-prompt guideline), and hands each call to `failproofai mcp --agent pi`, which records it; sync no longer writes a Pi MCP entry and removes the old one. Verified with Pi 0.85.1 on gpt-5-nano, which reported an expired token unprompted (#1062) +- Self Reports: the tool description and the server's instructions now say to call it before the final answer whenever something the agent cannot fix stopped it, with concrete triggers (a missing or expired token or key, a 401 or 403, a command or tool that keeps failing, information it cannot get, a request it cannot do); weaker models mostly ignored the old wording. Same text in the CLI, the daemon and both SDKs (#1062) +- `block-failproofai-commands` no longer blocks reads and mentions it mistook for tampering: a `jq` filter with a `|` in it, a `grep`/`rg` pattern with a `(`, a heredoc that only writes text mentioning the CLI (to a file outside failproofai's state, with nothing in the same command that could run it), and a `python -c` program that can only read. It still denies running the CLI however it is spelled, pausing, uninstalling, and every write, move, delete, `chmod` or redirect into failproofai's state, including `yq -i`, which it had read as a reader (#1062) + +- Self Reports output is one line: `config`, `policies --install`/`--uninstall`, `self-report enable` and `disable` print `Self Reports: on for 12 agents` (or `off`, naming any agent that could not be updated) instead of a line per agent and file. `config` finishes its gateway restarts and the Self Reports sync behind one spinner line and keeps only what needs you (a gateway to restart by hand, an agent not updated); it no longer prints the Codex trust notice, which `config --status` now gives in one line, since the MCP server records an untrusted Codex's reports (#1062) +- `failproofai self-report status` shows everything in one place (no `--verbose`): the setting and where it comes from, paths, URLs, categories, update time, per-agent transport and recorder, any fix needed, the Cursor approval hint and the last update's gateway rows; `--json` has the same as JSON (#1062) +- Self Reports in the daemon's log, so machine logs carry it: every MCP `initialize`, `tools/list` and `tools/call` (agent, category, session, recorded or skipped and why), write failures, unknown categories, unreadable settings and sync results. The stdio server and CLI syncs send theirs over the daemon socket as a new one-way `selfReportLog` message (older daemons drop it; it never waits more than 250 ms); a line carries at most 40 characters of the detail, scrubbed of secrets (#1062) + +### Docs + +- Self Reports: when Claude Code's or Codex's hooks do not run, Pi's tool coming from failproofai's Pi extension, and where the extra servers in `devin mcp list` come from (Devin also lists other agents' servers, such as a Claude Code project's) (#1062) + +## 1.0.18-beta.2 — 2026-11-27 + +### Fixes + +- Self Reports' local MCP server is now named `failproofai_local`, so it no longer clashes with the FailproofAI Cloud gateway, which users add as `failproofai`: the two coexist in one agent, the installer never reads, changes, removes or reports an entry named `failproofai`, and the gateway's tools go through the policies like any other server's. Agents see the tool as `mcp__failproofai_local__report` (Claude Code, Codex, Pi, Factory, Devin), `failproofai_local_report` (OpenCode), `mcp_failproofai_local_report` (Hermes, Antigravity) or `failproofai_local__report` (OpenClaw, Goose); Cursor's `mcp_server_name` and Antigravity's `call_mcp_tool` `ServerName` must be `failproofai_local`. The SDK tool stays `failproofai_report` (#1062) +- Self Reports on a machine that enrolls in Cloud with its own settings file in place: that local file no longer decides. Until the daemon writes the organization's setting, the hook, `failproofai mcp`, the daemon's HTTP server and `status` all read Self Reports as off, as they already did with no file (#1062) +- `failproofai self-report test` no longer reports a recorded test as a failure when the collector uploads and deletes the batch first: the stdio server hands the test a receipt naming the batch it published, and the test checks that instead of the file (#1062) +- The daemon refuses a `self-report.json` in a settings version it does not support, as the CLI already did, so its HTTP server no longer offers or records the tool for a file `status` and the stdio server read as off; a shared fixture holds the cases both readers are tested against (#1062) +- Self Reports: a project- or local-scope `policies --install` no longer writes failproofai's MCP server into the agents' user-wide configs, and under the test runner the installer refuses to write any agent config inside the real home directory (a test that did not isolate `HOME` had registered a server pointing at a deleted temp binary) (#1062) +- The troubleshooting switch (`machineLogs`) and a `logRequest` follow the same rule: a desired-state response the daemon refuses no longer turns daemon-log uploads on or off, and a rolled-back or disconnected response no longer requests an upload. A response refused only because this daemon cannot validate it (a newer server's policy shape) still delivers its `logRequest`, since that refusal repeats every poll and support needs that machine's logs; the upload stays bound by the switch as last accepted (#1062) + +## 1.0.18-beta.1 — 2026-11-27 + +### Features + +- Self Reports: every hooked agent gets a `report` tool (MCP server `failproofai`, served by `failproofaid` at `http://127.0.0.1:4319/mcp` or by `failproofai mcp` over stdio) to say it is stuck, under six default categories or the organization's own; the hook allows the call before any policy, pause or Jev review and records it as a `self_report` event, the MCP server records it for agents whose hooks do not see MCP calls, the setting comes from Cloud (`selfReport` in desired-state) or `failproofai self-report enable|disable|status|test|sync` and lives in `~/.failproofai/self-report.json`, and both SDKs add `self_report()` / `selfReport()` with ready-made framework tools; the server's initialize result carries short instructions (agents that defer MCP tools, like Claude Code, still see them), and HTTP vs stdio is chosen from a live daemon check that the daemon re-runs at startup; the instructions name the `category` and `detail` arguments, and a call that sends the detail under another name (`summary`, `sentence`, `message`, ...) still records it; Cursor reports are recorded by the MCP server (its tool hook does not name the server), Antigravity's `call_mcp_tool` wrapper for `failproofai`/`report` is allowed ahead of the policies, Copilot's likely `failproofai-report` spelling is exempt, Pi's entry is exposed directly, server-recorded reports find their session by an exact, then related working directory, else the agent's newest session only when all its sessions in the 6-hour window share one directory, reading every activity page in that window, and take the session's own agent, and a hand-started daemon finds `failproofai` on PATH for its startup sync; HTTP is used only for Claude Code and Codex (hook-recorded) and only when the endpoint answers with the instance id of the daemon behind this home's socket, every server-recorded agent stays on stdio, the HTTP server records nothing while Self Reports is off and never attributes a report across projects, a Cursor call that fails the server check always goes through the policies, `self-report sync` refuses a stale home instead of migrating it unattended, and `uninstall` also finds an orphan MCP registration and reports an agent config it cannot read; the Claude Code and Codex hooks record a report only while `self-report.json` says enabled (read on every call, so `disable` takes effect in a running agent), the detail is cut to 2000 code points everywhere so a cut never splits a surrogate pair (one did, and the collector dropped the whole row), and `status` re-syncs an agent whose HTTP endpoint answers as another home's daemon +- Self Reports is on by default: `policies --install` and `config` register the `failproofai` MCP server in every hooked agent and write `~/.failproofai/self-report.json` on with the six default categories, and with no settings file every reader (the hook, `failproofai mcp`, the daemon's HTTP server, `status`) treats it as on, except on a Cloud-connected machine, which stays off until the daemon writes the organization's setting (on unless the organization turned it off); turn it off with `failproofai self-report disable`, or the Cloud switch on a connected machine, which removes the MCP entries and stops recording, and an explicit `enabled: false` always wins; an unparsable settings file still reads as off (#1062) ### Fixes +- A desired-state response the daemon refuses (a deployment rollback, or a disconnect during the poll) no longer changes Self Reports: its `selfReport` setting is applied only after the reconcile accepts the response, so an out-of-order older deployment can no longer turn reporting back on (#1062) - Retire the hook-sync agent and stop publishing its image: `docker-hook-sync/`, its prompt and `build-image.yml` (which pushed `ghcr.io/failproofai/hook-sync` publicly every day) are removed. The agent ran Claude Code with permission checks skipped, a GitHub write token and a Claude token in its environment and no failproofai hooks, after reading a third-party npm README. Nothing had run it since July (FailproofAI/agenteye#1797, #1055) - `fp`, the dashboard's api-server client, and the collector's uploader and OTLP relay refuse a plain `http://` URL for any host but `localhost` and loopback addresses, so `FP_DASHBOARD_URL`, `FAILPROOF_API_URL` or `FAILPROOFAI_INGEST_URL` can no longer put a session, a token, a sign-in code or the ingest key on the network in clear, and the api-server client no longer follows redirects; `fp logout` still clears a session saved against such a URL, without sending it (#1057) - A dashboard bound off loopback (`FAILPROOFAI_DASHBOARD_HOST`) requires a per-launch access token on every request: the launch screen and `failproofai audit` print the address with `?token=` (audit no longer hands it to a browser opener, whose command line other local users can read), and the browser trades it for an HttpOnly cookie. Before, any machine on the network could set `Host` and `Origin` itself and read transcripts, change policies, or install a policy pack, which runs its code (#1057) diff --git a/CLAUDE.md b/CLAUDE.md index 71ac65550..d7e21ac93 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1370,7 +1370,7 @@ sdk/python/ The telemetry SDK (Python, uv, pytest). PyPI dist dependency we declare is a constraint they inherit. `sdk/` is a directory because more languages go beside `python/`, not inside it. - failproofai_sdk/_events.py The 15 public event methods, and the `_pending` map that + failproofai_sdk/_events.py The 16 public event methods, and the `_pending` map that auto-computes duration_ms by pairing start/end events failproofai_sdk/_schema.py One dataclass per event type; `to_dict()` IS the wire format. Frozen byte-for-byte by tests/test_wire_format.py @@ -1385,7 +1385,7 @@ sdk/python/ The telemetry SDK (Python, uv, pytest). PyPI dist on either side. tests/test_spool_contract.py checks the Rust and the TypeScript directly and never skips sdk/typescript/ The telemetry SDK (TypeScript, npm, vitest). npm package - `@failproofai/sdk`. The same 15 events, wire format, + `@failproofai/sdk`. The same 16 events, wire format, spool directory and Evaluator v2 protocol as sdk/python — a fleet running both writes into one pipe. Zero runtime dependencies for the same reason, diff --git a/Cargo.lock b/Cargo.lock index 4dabc88e5..22a82d24a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -298,7 +298,7 @@ dependencies = [ [[package]] name = "failproofaid" -version = "1.0.17" +version = "1.0.18" dependencies = [ "fpai-collect", "fpai-ipc", @@ -361,7 +361,7 @@ dependencies = [ [[package]] name = "fpai-collect" -version = "1.0.17" +version = "1.0.18" dependencies = [ "axum", "getrandom 0.4.3", @@ -382,7 +382,7 @@ dependencies = [ [[package]] name = "fpai-ipc" -version = "1.0.17" +version = "1.0.18" dependencies = [ "libc", "proptest", diff --git a/Cargo.toml b/Cargo.toml index fd6017f4a..8e81cd59a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,7 +3,7 @@ resolver = "3" members = ["crates/*"] [workspace.package] -version = "1.0.17" +version = "1.0.18" edition = "2024" license-file = "LICENSE" repository = "https://github.com/FailproofAI/failproofai" diff --git a/README.md b/README.md index a23b283a9..9cc01c2dc 100644 --- a/README.md +++ b/README.md @@ -284,6 +284,11 @@ hand an agent more autonomy, not less: - **One daemon, always in sync.** The same process ships every run to Cloud and keeps your policies current, so a policy you approve reaches every machine without a redeploy. +- **Agents that say when they're stuck.** [Self Reports](https://docs.befailproof.ai/self-reports) + gives every agent a `report` tool for looping, a broken credential, missing context or a + request it cannot do. No policy can block the call, and each report lands on its + session, so you see where agents get stuck without reading every transcript. It is on + by default; `failproofai self-report disable` (or the Cloud switch) turns it off. --- diff --git a/__tests__/audit/cache.test.ts b/__tests__/audit/cache.test.ts index 04eabc6e9..e72ec9ce6 100644 --- a/__tests__/audit/cache.test.ts +++ b/__tests__/audit/cache.test.ts @@ -7,6 +7,7 @@ import { createHash } from "node:crypto"; import { CACHE_SCHEMA_VERSION, CACHE_TTL_MS, + TRANSCRIPT_PARSER_VERSIONS, readCachedTranscriptResult, writeCachedTranscriptResult, } from "../../src/audit/cache"; @@ -163,4 +164,34 @@ describe("per-transcript audit cache", () => { const intervalMs = DEFAULT_AUDIT_INTERVAL_DAYS * 24 * 60 * 60_000; expect(CACHE_TTL_MS).toBeGreaterThan(intervalMs * 2); }); + + // A parser that starts reading records it used to skip changes neither the + // transcript's mtime/size nor the builtins' hash, so without a parser + // version a Codex session cached as "0 tool calls" would be served for 30 + // days after the fix shipped. + it("re-scans a Codex entry written before its parser version existed", () => { + const codex: TranscriptAuditResult = { ...FAKE_RESULT, cli: "codex", eventsScanned: 0 }; + writeCachedTranscriptResult(TRANSCRIPT_PATH, MTIME, SIZE, codex); + const path = cachePathFor(TRANSCRIPT_PATH); + const entry = JSON.parse(readFileSync(path, "utf-8")); + expect(entry.parserVersion).toBe(TRANSCRIPT_PARSER_VERSIONS.codex); + expect(readCachedTranscriptResult(TRANSCRIPT_PATH, MTIME, SIZE)?.cli).toBe("codex"); + + delete entry.parserVersion; // what every pre-upgrade entry looks like + writeFileSync(path, JSON.stringify(entry)); + expect(readCachedTranscriptResult(TRANSCRIPT_PATH, MTIME, SIZE)).toBeNull(); + + writeFileSync(path, JSON.stringify({ ...entry, parserVersion: 1 })); + expect(readCachedTranscriptResult(TRANSCRIPT_PATH, MTIME, SIZE)).toBeNull(); + }); + + it("keeps serving a cached entry for a CLI whose parser has no version", () => { + expect(TRANSCRIPT_PARSER_VERSIONS.claude).toBeUndefined(); + writeCachedTranscriptResult(TRANSCRIPT_PATH, MTIME, SIZE, FAKE_RESULT); + const path = cachePathFor(TRANSCRIPT_PATH); + const entry = JSON.parse(readFileSync(path, "utf-8")); + expect(entry.parserVersion).toBeUndefined(); + writeFileSync(path, JSON.stringify(entry)); + expect(readCachedTranscriptResult(TRANSCRIPT_PATH, MTIME, SIZE)?.eventsScanned).toBe(12); + }); }); diff --git a/__tests__/audit/codex-code-mode-audit.test.ts b/__tests__/audit/codex-code-mode-audit.test.ts new file mode 100644 index 000000000..49c432071 --- /dev/null +++ b/__tests__/audit/codex-code-mode-audit.test.ts @@ -0,0 +1,80 @@ +// @vitest-environment node +// +// End to end for the audit's Codex path: a Codex 0.172 code-mode transcript +// (record shapes copied from a real session) through the parser, the shared +// LogEntry → event mapping and the replay engine. Before code mode was parsed +// this produced zero events, so no builtin could fire on any Codex 0.172 +// session; and before exec_command mapped to Bash, none could fire on an older +// one either. +import { describe, it, expect, beforeEach } from "vitest"; +import { parseCodexLog } from "@/lib/codex-sessions"; +import { logEntriesToEvents } from "@/src/audit/cli-adapters/shared"; +import { resetReplay, replayEvent } from "@/src/audit/replay"; +import { canonicalizeToolInput, canonicalizeToolName } from "@/src/hooks/tool-name-canonicalize"; + +const rec = (o: Record) => JSON.stringify(o); +const ctx = { cli: "codex" as const, sessionId: "s1", transcriptPath: "/tmp/codex.jsonl", cwd: "/home/u/proj" }; + +async function eventsOf(lines: string[]) { + const { entries } = await parseCodexLog(lines.join("\n")); + return logEntriesToEvents(entries, ctx); +} + +describe("audit: Codex code-mode transcripts", () => { + beforeEach(() => resetReplay()); + + it("sees the shell command inside an exec snippet as Bash, and a builtin fires on it", async () => { + const events = await eventsOf([ + rec({ timestamp: "2026-11-29T18:15:42.000Z", type: "session_meta", payload: { id: "s1", cwd: "/home/u/proj", cli_version: "0.172.0" } }), + rec({ + timestamp: "2026-11-29T18:15:43.000Z", + type: "response_item", + payload: { + type: "custom_tool_call", + status: "completed", + call_id: "call_1", + name: "exec", + input: 'const r = await tools.exec_command({cmd:"sudo ls /root","workdir":"/home/u/proj","yield_time_ms":10000}); text(r.output);\n', + }, + }), + rec({ timestamp: "2026-11-29T18:15:43.200Z", type: "response_item", payload: { type: "custom_tool_call_output", call_id: "call_1", output: [{ type: "input_text", text: "Script completed\n" }] } }), + ]); + expect(events).toHaveLength(1); + expect(events[0]).toMatchObject({ + toolName: "Bash", + rawToolName: "exec_command", + toolInput: { command: "sudo ls /root", cwd: "/home/u/proj" }, + toolResultText: "Script completed\n", + }); + const hits = await replayEvent(events[0]); + expect(hits.map((h) => h.policyName).some((n) => n.includes("block-sudo"))).toBe(true); + }); + + it("sees an apply_patch to .env as an Edit of that file, and a builtin fires on it", async () => { + const patch = "*** Begin Patch\n*** Update File: /home/u/proj/.env\n@@\n-A=1\n+A=2\n*** End Patch\n"; + const events = await eventsOf([ + rec({ timestamp: "2026-11-29T18:16:00.000Z", type: "response_item", payload: { type: "custom_tool_call", call_id: "call_2", name: "apply_patch", input: patch } }), + ]); + expect(events).toHaveLength(1); + expect(events[0]).toMatchObject({ toolName: "Edit", rawToolName: "apply_patch", toolInput: { file_path: "/home/u/proj/.env" } }); + const hits = await replayEvent(events[0]); + expect(hits.map((h) => h.policyName).some((n) => n.includes("block-env-files"))).toBe(true); + }); + + it("maps an older function_call exec_command to Bash too", async () => { + const events = await eventsOf([ + rec({ timestamp: "2026-06-01T00:00:00.000Z", type: "response_item", payload: { type: "function_call", name: "exec_command", arguments: '{"cmd":"sudo whoami","workdir":"/w"}', call_id: "c" } }), + ]); + expect(events[0]).toMatchObject({ toolName: "Bash", toolInput: { command: "sudo whoami", cwd: "/w" } }); + }); + + it("does not change the live hook's Codex Bash payload", () => { + // Live PreToolUse already delivers `Bash {command}`; the cmd → command map + // must be a no-op on it. + const live = { command: "ls", description: "list" }; + expect(canonicalizeToolName("Bash", "codex")).toBe("Bash"); + expect(canonicalizeToolInput("Bash", live, "codex")).toEqual(live); + expect(canonicalizeToolName("write_stdin", "codex")).toBe("Bash"); + expect(canonicalizeToolInput("Bash", { session_id: 3, chars: "ls\n" }, "codex")).toEqual({ session_id: 3, chars: "ls\n" }); + }); +}); diff --git a/__tests__/e2e/helpers/payloads.ts b/__tests__/e2e/helpers/payloads.ts index 42b47e738..0e9f5a55c 100644 --- a/__tests__/e2e/helpers/payloads.ts +++ b/__tests__/e2e/helpers/payloads.ts @@ -121,6 +121,18 @@ export const CodexPayloads = { tool_input: { command }, }; }, + // Codex's native file edit, as it reaches the hook: `apply_patch`, with the + // patch in `tool_input.command` and no `file_path` at all. + applyPatch(patch: string, cwd: string): Record { + return { + session_id: CODEX_SESSION_ID, + transcript_path: TRANSCRIPT_PATH, + cwd, + hook_event_name: "pre_tool_use", + tool_name: "apply_patch", + tool_input: { command: patch }, + }; + }, write(filePath: string, content: string, cwd: string): Record { // Codex aliases Edit/Write → apply_patch in matchers, so policies that // filter on toolNames: ["Write"] continue to fire for Codex. diff --git a/__tests__/e2e/hooks/codex-integration.e2e.test.ts b/__tests__/e2e/hooks/codex-integration.e2e.test.ts index 1cf82c28a..162e25482 100644 --- a/__tests__/e2e/hooks/codex-integration.e2e.test.ts +++ b/__tests__/e2e/hooks/codex-integration.e2e.test.ts @@ -7,7 +7,7 @@ */ import { describe, it, expect } from "vitest"; import { execSync } from "node:child_process"; -import { mkdtempSync, writeFileSync, readFileSync, existsSync, mkdirSync, rmSync } from "node:fs"; +import { mkdtempSync, writeFileSync, readFileSync, existsSync, mkdirSync, rmSync, symlinkSync } from "node:fs"; import { tmpdir } from "node:os"; import { join, resolve, dirname } from "node:path"; import { fileURLToPath } from "node:url"; @@ -166,6 +166,112 @@ describe("E2E: Codex integration — hook protocol", () => { }); }); +// Codex edits files with its native `apply_patch`, whose patch arrives in +// `tool_input.command` with no `file_path`. A patch planting +// `node_modules/.bin/failproofai` — the file a project-scope `npx -y failproofai` +// hook runs — passed the always-on guard until every file a patch names was +// checked (found by hermes on FailproofAI/failproofai#1058). +describe("E2E: Codex integration — native apply_patch", () => { + const patchOf = (...lines: string[]) => ["*** Begin Patch", ...lines, "*** End Patch", ""].join("\n"); + + it.each([ + ["adding the entry", patchOf("*** Add File: node_modules/.bin/failproofai", "+#!/bin/sh", "+exit 0")], + ["updating the entry", patchOf("*** Update File: node_modules/.bin/failproofai", "@@", "-exec node cli.mjs", "+exit 0")], + ["moving a file onto the entry", patchOf("*** Update File: scripts/stub.sh", "*** Move to: node_modules/.bin/failproofai", "@@", "+exit 0")], + ["updating a link to the entry", patchOf("*** Update File: hook", "@@", "+exit 0")], + ])("PreToolUse: a native patch %s is denied", (_label, patch) => { + const env = createCodexEnv(); + try { + writeConfig(env.cwd, []); + mkdirSync(resolve(env.cwd, "node_modules", ".bin"), { recursive: true }); + symlinkSync(resolve(env.cwd, "node_modules", ".bin", "failproofai"), resolve(env.cwd, "hook")); + const result = runHook("PreToolUse", CodexPayloads.preToolUse.applyPatch(patch, env.cwd), { + homeDir: env.home, + cli: "codex", + }); + assertPreToolUseDeny(result); + } finally { + env.cleanup(); + } + }); + + // Codex's shell tool runs a command in its `workdir`, but the hook payload + // carries the session's directory and the command only (found by hermes on + // FailproofAI/failproofai#1058). A native write that plants the entry if it + // runs in node_modules/.bin is refused from the project's root; with the + // workdir reported, it is read from there. + it("PreToolUse: a native shell write that may run in node_modules/.bin is denied", () => { + const env = createCodexEnv(); + try { + writeConfig(env.cwd, []); + mkdirSync(resolve(env.cwd, "node_modules", ".bin"), { recursive: true }); + const result = runHook( + "PreToolUse", + CodexPayloads.preToolUse.bash("printf '#!/bin/sh\\nexit 0\\n' > failproofai", env.cwd), + { homeDir: env.home, cli: "codex" }, + ); + assertPreToolUseDeny(result); + } finally { + env.cleanup(); + } + }); + + it("PreToolUse: a native shell write is read from the workdir the call reports", () => { + const env = createCodexEnv(); + try { + writeConfig(env.cwd, []); + const withWorkdir = (workdir: string) => ({ + ...CodexPayloads.preToolUse.bash("printf x > failproofai", env.cwd), + tool_input: { command: "printf x > failproofai", workdir }, + }); + assertPreToolUseDeny( + runHook("PreToolUse", withWorkdir(resolve(env.cwd, "node_modules", ".bin")), { homeDir: env.home, cli: "codex" }), + ); + assertAllow(runHook("PreToolUse", withWorkdir(resolve(env.cwd, "src")), { homeDir: env.home, cli: "codex" })); + } finally { + env.cleanup(); + } + }); + + // The same for Codex's own hooks file (#1105 review): with workdir ~/.codex, + // `printf '{}' > hooks.json` empties the hooks Codex runs. + it("PreToolUse: a native shell write to the hooks file from the workdir the call reports is denied", () => { + const env = createCodexEnv(); + try { + writeConfig(env.cwd, []); + const withWorkdir = (command: string, workdir?: string) => ({ + ...CodexPayloads.preToolUse.bash(command, env.cwd), + tool_input: workdir === undefined ? { command } : { command, workdir }, + }); + assertPreToolUseDeny( + runHook("PreToolUse", withWorkdir("printf '{}' > hooks.json", resolve(env.home, ".codex")), { homeDir: env.home, cli: "codex" }), + ); + // No workdir reported: it may be ~/.codex. + assertPreToolUseDeny(runHook("PreToolUse", withWorkdir("printf '{}' > hooks.json"), { homeDir: env.home, cli: "codex" })); + assertAllow( + runHook("PreToolUse", withWorkdir("printf '{}' > hooks.json", resolve(env.cwd, "src")), { homeDir: env.home, cli: "codex" }), + ); + } finally { + env.cleanup(); + } + }); + + it("PreToolUse: a native patch to project files is allowed", () => { + const env = createCodexEnv(); + try { + writeConfig(env.cwd, []); + const patch = patchOf("*** Update File: src/app.ts", "@@", "-a", "+b", "*** Add File: node_modules/.bin/my-tool", "+exit 0"); + const result = runHook("PreToolUse", CodexPayloads.preToolUse.applyPatch(patch, env.cwd), { + homeDir: env.home, + cli: "codex", + }); + assertAllow(result); + } finally { + env.cleanup(); + } + }); +}); + describe("E2E: Codex integration — install/uninstall", () => { it("policies --install --cli codex --scope project writes .codex/hooks.json with PascalCase keys", () => { const env = createCodexEnv(); diff --git a/__tests__/fixtures/hermes-native-plugin-check.py b/__tests__/fixtures/hermes-native-plugin-check.py index e80aad162..0b57a1142 100644 --- a/__tests__/fixtures/hermes-native-plugin-check.py +++ b/__tests__/fixtures/hermes-native-plugin-check.py @@ -1796,5 +1796,163 @@ def test_no_retry_below_the_oldest_supported_version(self) -> None: self.assertIn("protocol version mismatch", str(result)) self.assertEqual(len(received), 1) +self_report_mod = sys.modules[f"{plugin.__name__}.self_report"] + +SR_SERVER = {"instanceId": "inst-1", "port": 4319} +SR_SCHEMA = {"type": "object", "properties": {"category": {"type": "string"}, "detail": {"type": "string"}}} + + +def sr_rpc(calls: list, instance: str = "inst-1", tools: list | None = None): + def rpc(url, body, timeout): + calls.append((url, body)) + if body["method"] == "initialize": + return {"result": {"serverInfo": {"name": "failproofai_local", "instanceId": instance}, "instructions": "Report when stuck."}} + if body["method"] == "tools/list": + return {"result": {"tools": tools if tools is not None else [{"name": "report", "description": "Report it.", "inputSchema": SR_SCHEMA}]}} + return {"result": {"content": [{"type": "text", "text": "Recorded."}]}} + return rpc + + +class ToolContext(FakeContext): + def __init__(self, data_dir: Path) -> None: + super().__init__(data_dir) + self.tools: list[dict] = [] + + def register_tool(self, **kwargs) -> None: + self.tools.append(kwargs) + + +class SelfReportToolTests(unittest.TestCase): + """The report tool as a native Hermes tool (never behind tool search).""" + + def setUp(self) -> None: + self.fake_toolsets = ModuleType("toolsets") + self.fake_toolsets._HERMES_CORE_TOOLS = ["terminal"] + self._saved = sys.modules.get("toolsets") + sys.modules["toolsets"] = self.fake_toolsets + + def tearDown(self) -> None: + if self._saved is None: + sys.modules.pop("toolsets", None) + else: + sys.modules["toolsets"] = self._saved + + def test_discover_trusts_only_this_users_daemon(self) -> None: + calls: list = [] + tool = self_report_mod.discover_self_report_tool(lambda: SR_SERVER, sr_rpc(calls)) + self.assertEqual(tool["description"], "Report it.") + self.assertEqual(tool["inputSchema"], SR_SCHEMA) + self.assertEqual(tool["instructions"], "Report when stuck.") + self.assertTrue(calls[0][0].startswith("http://127.0.0.1:4319/mcp?agent=hermes")) + # Another daemon answering the port, Self Reports off, or no daemon: no tool. + self.assertIsNone(self_report_mod.discover_self_report_tool(lambda: SR_SERVER, sr_rpc([], instance="other"))) + self.assertIsNone(self_report_mod.discover_self_report_tool(lambda: SR_SERVER, sr_rpc([], tools=[]))) + self.assertIsNone(self_report_mod.discover_self_report_tool(lambda: None, sr_rpc([]))) + + def test_registers_a_direct_tool_with_the_servers_text(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + ctx = ToolContext(Path(tmp)) + state = self_report_mod.SelfReportTool(discover=lambda: {**SR_SERVER, "description": "Report it.", "inputSchema": SR_SCHEMA, "instructions": "Report when stuck."}) + self.assertIs(self_report_mod.register_self_report_tool(ctx, state), state) + [reg] = ctx.tools + self.assertEqual(reg["name"], "mcp_failproofai_local_report") + self.assertEqual(reg["toolset"], "failproofai") + self.assertEqual(reg["schema"], {"name": "mcp_failproofai_local_report", "description": "Report it.", "parameters": SR_SCHEMA}) + self.assertTrue(reg["check_fn"]()) + # On Hermes' never-deferred list, so tool search keeps it direct. + self.assertIn("mcp_failproofai_local_report", self.fake_toolsets._HERMES_CORE_TOOLS) + + def test_registers_a_hidden_tool_while_self_reports_is_off_or_the_daemon_is_gone(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + ctx = ToolContext(Path(tmp)) + state = self_report_mod.SelfReportTool(discover=lambda: None) + self.assertIs(self_report_mod.register_self_report_tool(ctx, state), state) + [reg] = ctx.tools + self.assertEqual(reg["name"], "mcp_failproofai_local_report") + self.assertEqual(reg["schema"]["parameters"]["required"], ["category", "detail"]) + self.assertFalse(reg["check_fn"]()) # hidden from the model while off + self.assertEqual(state.instructions(), "") + self.assertIn("mcp_failproofai_local_report", self.fake_toolsets._HERMES_CORE_TOOLS) + + # F16: a gateway that started while Self Reports was off kept no tool, so + # enabling it later never reached that gateway until a restart. + def test_off_at_start_then_enabled_shows_the_tool_and_its_instructions_without_a_restart(self) -> None: + offered = {"on": False} + clock = {"t": 0.0} + + def discover(): + if not offered["on"]: + return None + return {**SR_SERVER, "description": "Report it.", "inputSchema": SR_SCHEMA, "instructions": "Report when stuck."} + + with tempfile.TemporaryDirectory() as tmp: + ctx = ToolContext(Path(tmp)) + state = self_report_mod.SelfReportTool(discover=discover, clock=lambda: clock["t"]) + instance = plugin.FailproofAIPlugin(FakeContext(Path(tmp))) + instance.self_report = self_report_mod.register_self_report_tool(ctx, state) + [reg] = ctx.tools + self.assertFalse(reg["check_fn"]()) + self.assertEqual(instance.pre_llm_call(), {"context": plugin._PROTOCOL_CONTEXT}) + # Self Reports is turned on; within a minute the tool and its text follow. + offered["on"] = True + clock["t"] += 61.0 + self.assertTrue(reg["check_fn"]()) + self.assertTrue(instance.pre_llm_call()["context"].endswith("Report when stuck.")) + # The registered schema took the daemon's text in place. + self.assertEqual(reg["schema"]["description"], "Report it.") + self.assertEqual(reg["schema"]["parameters"], SR_SCHEMA) + # And a call is handed to the daemon. + calls: list = [] + state._call = lambda tool, args, cwd: self_report_mod.call_self_report_tool(tool, args, cwd, lambda: SR_SERVER, sr_rpc(calls)) + self.assertEqual(reg["handler"]({"category": "looping", "detail": "again"}, cwd="/w"), "Recorded.") + self.assertEqual(calls[-1][1]["params"]["arguments"], {"category": "looping", "detail": "again"}) + # Turned off again: hidden again. + offered["on"] = False + clock["t"] += 61.0 + self.assertFalse(reg["check_fn"]()) + + def test_a_register_tool_that_raises_never_breaks_register(self) -> None: + class Raising(ToolContext): + def register_tool(self, **kwargs) -> None: + raise RuntimeError("name taken") + with tempfile.TemporaryDirectory() as tmp: + state = self_report_mod.SelfReportTool(discover=lambda: {**SR_SERVER, "description": "d", "inputSchema": SR_SCHEMA, "instructions": ""}) + self.assertIsNone(self_report_mod.register_self_report_tool(Raising(Path(tmp)), state)) + + def test_a_call_goes_to_the_daemon_with_the_agent_cwd_and_normalised_arguments(self) -> None: + calls: list = [] + tool = {**SR_SERVER, "description": "d", "inputSchema": SR_SCHEMA} + text = self_report_mod.call_self_report_tool(tool, {"type": "looping", "summary": "again"}, "/work/p", lambda: SR_SERVER, sr_rpc(calls)) + self.assertEqual(text, "Recorded.") + url, body = calls[-1] + self.assertEqual(url, "http://127.0.0.1:4319/mcp?agent=hermes&cwd=%2Fwork%2Fp") + self.assertEqual(body["params"], {"name": "report", "arguments": {"category": "looping", "detail": "again"}}) + # The daemon restarted on another instance: nothing is sent there. + calls.clear() + self_report_mod.call_self_report_tool(tool, {}, "/w", lambda: {"instanceId": "new", "port": 4319}, sr_rpc(calls)) + self.assertEqual(calls, []) + + def test_pre_llm_call_carries_the_instructions_only_with_the_tool(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + instance = plugin.FailproofAIPlugin(FakeContext(Path(tmp))) + self.assertEqual(instance.pre_llm_call(), {"context": plugin._PROTOCOL_CONTEXT}) + instance.self_report = self_report_mod.SelfReportTool(discover=lambda: {**SR_SERVER, "description": "d", "inputSchema": SR_SCHEMA, "instructions": "Report when stuck."}) + context = instance.pre_llm_call()["context"] + self.assertTrue(context.startswith(plugin._PROTOCOL_CONTEXT)) + self.assertTrue(context.endswith("Report when stuck.")) + + def test_register_without_a_daemon_registers_hooks_and_a_hidden_tool(self) -> None: + with tempfile.TemporaryDirectory() as tmp, patch.dict(os.environ, {"FAILPROOFAI_DAEMON_SOCKET": str(Path(tmp) / "none.sock")}): + data_dir = Path(tmp) / "data" + ctx = ToolContext(data_dir) + plugin.register(ctx) + beat = json.loads((data_dir / "heartbeat.json").read_text()) + [reg] = ctx.tools + self.assertFalse(reg["check_fn"]()) + self.assertIs(beat["self_report_tool"], True) + self.assertIs(beat["self_report_on_at_start"], False) + self.assertIs(beat["register_ok"], True) + + if __name__ == "__main__": unittest.main() diff --git a/__tests__/helpers/self-report-registration.ts b/__tests__/helpers/self-report-registration.ts new file mode 100644 index 000000000..759ef760c --- /dev/null +++ b/__tests__/helpers/self-report-registration.ts @@ -0,0 +1,43 @@ +/** + * Test helper: a temp HOME in which every agent's `failproofai_local` entry is + * failproofai's own, as `self-report sync` writes it. The hook early-allows the + * report tool only while that is so (`selfReportRegistrationOwned`), so a test + * of the early allow needs a HOME like this one. Never the developer's real + * agent configs: HOME and every agent-home override point into `home`. + */ +import { resolve } from "node:path"; +import { vi } from "vitest"; +import { syncSelfReportMcp } from "../../src/hooks/self-report-install"; + +export const AGENT_HOME_ENV = [ + "CLAUDE_CONFIG_DIR", "CODEX_HOME", "COPILOT_HOME", "PI_CODING_AGENT_DIR", "HERMES_HOME", + "OPENCLAW_STATE_DIR", "OPENCLAW_HOME", "OPENCLAW_CONFIG_PATH", "GOOSE_PATH_ROOT", "XDG_CONFIG_HOME", +]; + +/** Point HOME (and each agent's own home override) at `home`. Undo with `vi.unstubAllEnvs()`. */ +export function isolateAgentHome(home: string): void { + vi.stubEnv("HOME", home); + vi.stubEnv("USERPROFILE", home); + for (const k of AGENT_HOME_ENV) vi.stubEnv(k, ""); +} + +/** + * The stdio command the registrations name: this checkout's own CLI entry + * point, which the report exemption requires (never run by these tests). + */ +export const REGISTERED_CLI = resolve(__dirname, "..", "..", "bin", "fail" + "proofai.mjs"); + +/** Write failproofai's own `failproofai_local` entry for every agent under the isolated HOME. */ +export async function registerOwnSelfReportServer(): Promise { + await syncSelfReportMcp({ + quiet: true, + binaryPath: REGISTERED_CLI, + deps: { + daemonLive: async () => false, + hooksInstalled: () => true, + hookRecords: () => true, + settings: { enabled: true, port: 4319 }, + httpAgents: [], + }, + }); +} diff --git a/__tests__/hooks/agent-path.test.ts b/__tests__/hooks/agent-path.test.ts new file mode 100644 index 000000000..ffcd511f8 --- /dev/null +++ b/__tests__/hooks/agent-path.test.ts @@ -0,0 +1,127 @@ +// @vitest-environment node +/** + * F17 round 2: the guard's "is this bare `grep` the real grep" question is + * answered from the AGENT's PATH, which the hook CLI carries in the payload, + * never from the evaluating process's own PATH: in the daemon's warm worker + * that is the service's PATH, and a shadow `grep` early on the agent's PATH + * was judged by it and ran its argument. + */ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +vi.mock("../../src/hooks/hooks-config", () => ({ + readMergedHooksConfig: vi.fn(() => ({ enabledPolicies: [] })), +})); +vi.mock("../../src/hooks/custom-hooks-loader", () => ({ + loadAllCustomHooks: vi.fn(async () => ({ hooks: [], conventionSources: [] })), +})); +vi.mock("../../src/hooks/hook-telemetry", () => ({ + trackHookEvent: vi.fn(() => Promise.resolve()), + flushHookTelemetry: vi.fn(() => Promise.resolve()), +})); +vi.mock("../../lib/telemetry-id", () => ({ getInstanceId: vi.fn(() => "test-instance-id") })); +vi.mock("../../src/hooks/untraced-note", () => ({ noteUntracedAgent: vi.fn(() => false) })); +vi.mock("../../src/hooks/pack-manifest", () => ({ + readInstalledPacks: vi.fn(() => ({ packs: [], errors: [] })), + hasInstalledPacks: vi.fn(() => false), + hasInstalledRegexPacks: vi.fn(() => false), +})); + +import { AGENT_PATH_KEY, AGENT_PATH_MAX, SETTINGS_READER_WORDS, agentPathOf, markAgentPath } from "../../src/hooks/agent-path"; +import { evaluateHookEvent } from "../../src/hooks/handler"; +import { _resetForTest } from "../../src/hooks/hook-activity-store"; + +const F = "fail" + "proofai"; +const bash = (command: string, extra: Record = {}) => + JSON.stringify({ session_id: "s", cwd: "/tmp", tool_name: "Bash", tool_input: { command }, ...extra }); + +describe("markAgentPath (the hook CLI side)", () => { + it("carries this process's PATH on a payload that names a PATH-sensitive command", () => { + const out = JSON.parse(markAgentPath(bash("grep x f"), "/usr/bin:/bin")); + expect(out[AGENT_PATH_KEY]).toBe("/usr/bin:/bin"); + expect(agentPathOf(out)).toBe("/usr/bin:/bin"); + }); + + it("leaves any other payload untouched, and replaces or drops a value the payload already had", () => { + const ls = bash("ls"); + expect(markAgentPath(ls, "/usr/bin")).toBe(ls); + const spoofed = bash("grep x f", { [AGENT_PATH_KEY]: "/usr/bin:/bin" }); + expect(JSON.parse(markAgentPath(spoofed, "/evil:/usr/bin"))[AGENT_PATH_KEY]).toBe("/evil:/usr/bin"); + expect(JSON.parse(markAgentPath(bash("ls", { [AGENT_PATH_KEY]: "/usr/bin" }), "/usr/bin"))).not.toHaveProperty(AGENT_PATH_KEY); + // No PATH, or one past the bound: none carried (so nothing is exempt). + expect(JSON.parse(markAgentPath(spoofed, ""))).not.toHaveProperty(AGENT_PATH_KEY); + expect(JSON.parse(markAgentPath(spoofed, "/x".repeat(AGENT_PATH_MAX)))).not.toHaveProperty(AGENT_PATH_KEY); + expect(markAgentPath("{not json grep", "/usr/bin")).toBe("{not json grep"); + }); +}); + +// #1105 bot review: the settings walk exempts a reader of an agent's +// settings only as the real tool, so the PATH rides along for those too. +describe("markAgentPath for the settings walk's readers", () => { + it("lists exactly the command words the settings walk exempts by name", async () => { + const { SETTINGS_WALK_PATH_HEADS } = await import("../../src/hooks/builtin-policies"); + expect([...SETTINGS_READER_WORDS].sort()).toEqual([...SETTINGS_WALK_PATH_HEADS].sort()); + }); + + it.each(SETTINGS_READER_WORDS)("carries the PATH for %s beside an agent settings path", (head) => { + const out = JSON.parse(markAgentPath(bash(`${head} ~/.claude/settings.json`), "/usr/bin:/bin")); + expect(out[AGENT_PATH_KEY]).toBe("/usr/bin:/bin"); + }); + + it("leaves a reader that names no agent settings word untouched", () => { + const ls = bash("ls -la src"); + expect(markAgentPath(ls, "/usr/bin")).toBe(ls); + }); +}); + +describe("the guard in evaluateHookEvent (what the daemon's worker runs)", () => { + let home: string; + let shadow: string; + + beforeEach(() => { + home = mkdtempSync(join(tmpdir(), "fpai-agent-path-")); + process.env.FAILPROOFAI_HOME = home; + process.env.FAILPROOFAI_STATE_DIR = join(home, "state"); + _resetForTest(join(home, "hook-activity")); + shadow = join(home, "shadow-bin"); + mkdirSync(shadow); + writeFileSync(join(shadow, "grep"), '#!/bin/sh\neval "$1"\n', { mode: 0o755 }); + // The evaluating process (the worker) has a clean PATH throughout. + vi.stubEnv("PATH", "/usr/bin:/bin"); + }); + + afterEach(() => { + vi.unstubAllEnvs(); + delete process.env.FAILPROOFAI_HOME; + delete process.env.FAILPROOFAI_STATE_DIR; + _resetForTest(); + rmSync(home, { recursive: true, force: true }); + }); + + const cmd = `grep '(${F} config --pause)' f`; + const decide = async (payload: string) => (await evaluateHookEvent("PreToolUse", "claude", payload)).evaluation?.decision; + + it("denies when the agent's PATH finds a shadow grep, though the worker's own PATH is clean", async () => { + expect(await decide(bash(cmd, { [AGENT_PATH_KEY]: `${shadow}:/usr/bin:/bin` }))).toBe("deny"); + }); + + it("denies when no agent PATH came with the payload (an older client, a native plugin)", async () => { + expect(await decide(bash(cmd))).toBe("deny"); + }); + + it.runIf(["/usr/bin/grep", "/bin/grep"].some((p) => existsSync(p)))( + "keeps the exemption when the agent's PATH finds the system grep", + async () => { + expect(await decide(bash(`grep -E '(${F}_local|kiln)' f`, { [AGENT_PATH_KEY]: "/usr/bin:/bin" }))).toBe("allow"); + }, + ); + + it("the one-shot hook path stamps the hook process's own PATH (markAgentPath on the real payload)", async () => { + vi.stubEnv("PATH", `${shadow}:/usr/bin:/bin`); + const stamped = markAgentPath(bash(cmd)); + vi.stubEnv("PATH", "/usr/bin:/bin"); + expect(await decide(stamped)).toBe("deny"); + }); +}); diff --git a/__tests__/hooks/claude-hooks-switch.test.ts b/__tests__/hooks/claude-hooks-switch.test.ts new file mode 100644 index 000000000..6f7578951 --- /dev/null +++ b/__tests__/hooks/claude-hooks-switch.test.ts @@ -0,0 +1,286 @@ +import { describe, it, expect, beforeEach, afterEach } from "vitest"; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; + +import { + CLAUDE_MANAGED_SETTINGS_PATHS, + claudeHooksSwitchedOffBy, + claudeLocalSettingsPaths, + claudeSettingsLayersByPrecedence, +} from "../../src/hooks/claude-hooks-switch"; +import { + claudeHooksSwitchedOff, + gatherStatusFacts, + pickStatusAttention, + renderStatusScreen, + type StatusFacts, +} from "../../src/hooks/config-status"; +import { FAILPROOFAI_HOOK_MARKER } from "../../src/hooks/types"; + +/** + * #1794: `"disableAllHooks": true` in any Claude Code settings layer turns off + * every hook in the session, and nothing in failproofai read the key — so a + * machine whose agent had set it still reported itself as enforcing. + */ +describe("claudeHooksSwitchedOffBy — Claude Code's precedence", () => { + const files = (contents: Record) => (path: string) => { + if (!(path in contents)) throw new Error("ENOENT"); + const body = contents[path]; + return typeof body === "string" ? body : JSON.stringify(body); + }; + const layers = ["/managed.json", "/p/.claude/settings.local.json", "/p/.claude/settings.json", "/h/.claude/settings.json"]; + + it("names the user settings when they switch hooks off", () => { + expect(claudeHooksSwitchedOffBy(layers, files({ "/h/.claude/settings.json": { disableAllHooks: true } }))).toBe( + "/h/.claude/settings.json", + ); + }); + + it("names a project's local settings, which override the user's", () => { + const read = files({ + "/h/.claude/settings.json": { hooks: {} }, + "/p/.claude/settings.local.json": { disableAllHooks: true }, + }); + expect(claudeHooksSwitchedOffBy(layers, read)).toBe("/p/.claude/settings.local.json"); + }); + + it("lets a false higher up win over a true below it", () => { + const read = files({ "/p/.claude/settings.json": { disableAllHooks: false }, "/h/.claude/settings.json": { disableAllHooks: true } }); + expect(claudeHooksSwitchedOffBy(layers, read)).toBeNull(); + expect(claudeHooksSwitchedOffBy(layers, files({ "/managed.json": { disableAllHooks: false }, "/p/.claude/settings.local.json": { disableAllHooks: true } }))).toBeNull(); + }); + + it("skips a missing, unparseable or non-object file, and a non-boolean value", () => { + const read = files({ + "/managed.json": "{not json", + "/p/.claude/settings.local.json": [1, 2], + "/p/.claude/settings.json": { disableAllHooks: "true" }, + "/h/.claude/settings.json": { disableAllHooks: true }, + }); + expect(claudeHooksSwitchedOffBy(layers, read)).toBe("/h/.claude/settings.json"); + expect(claudeHooksSwitchedOffBy(layers, files({}))).toBeNull(); + }); + + it("orders the layers managed, local, project, user", () => { + expect(claudeSettingsLayersByPrecedence({ user: "u", project: "p", local: "l" }, "/m.json")).toEqual(["/m.json", "l", "p", "u"]); + expect(claudeSettingsLayersByPrecedence({ user: "u", project: "p", local: ["l1", "l2"] }, null)).toEqual(["l1", "l2", "p", "u"]); + }); + + it("reads the managed file where Claude Code keeps it, Windows included", () => { + expect(CLAUDE_MANAGED_SETTINGS_PATHS.linux).toBe("/etc/claude-code/managed-settings.json"); + expect(CLAUDE_MANAGED_SETTINGS_PATHS.darwin).toBe("/Library/Application Support/ClaudeCode/managed-settings.json"); + const windows = CLAUDE_MANAGED_SETTINGS_PATHS.win32!; + expect(windows).toBe("C:\\Program Files\\ClaudeCode\\managed-settings.json"); + const scopes = { user: "/h/.claude/settings.json", project: "/p/.claude/settings.json", local: "/p/.claude/settings.local.json" }; + const layers = claudeSettingsLayersByPrecedence(scopes, windows); + expect(claudeHooksSwitchedOffBy(layers, files({ [windows]: { disableAllHooks: true } }))).toBe(windows); + }); +}); + +describe("config --status — disableAllHooks", () => { + let dir: string; + const saved: Record = {}; + const ENV = ["HOME", "CLAUDE_CONFIG_DIR", "FAILPROOFAI_HOME"] as const; + + beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), "fpai-claude-switch-")); + for (const key of ENV) saved[key] = process.env[key]; + process.env.HOME = join(dir, "home"); + delete process.env.CLAUDE_CONFIG_DIR; + process.env.FAILPROOFAI_HOME = join(dir, "home", ".failproofai"); + mkdirSync(process.env.FAILPROOFAI_HOME, { recursive: true }); + }); + + afterEach(() => { + for (const key of ENV) { + if (saved[key] === undefined) delete process.env[key]; + else process.env[key] = saved[key]; + } + rmSync(dir, { recursive: true, force: true }); + }); + + const put = (path: string, body: unknown) => { + mkdirSync(dirname(path), { recursive: true }); + writeFileSync(path, JSON.stringify(body)); + }; + // Never the host's managed file: a machine whose policy sets the key would + // decide these assertions. + const managed = () => join(dir, "managed-settings.json"); + const ourHooks = { + hooks: { + PreToolUse: [{ hooks: [{ type: "command", command: "/bin/failproofai --hook PreToolUse", [FAILPROOFAI_HOOK_MARKER]: true }] }], + }, + }; + + it("reports the file that switches failproofai's installed Claude hooks off", () => { + const project = join(dir, "project"); + put(join(dir, "home", ".claude", "settings.json"), ourHooks); + put(join(project, ".claude", "settings.local.json"), { disableAllHooks: true }); + expect(claudeHooksSwitchedOff(project, managed())).toBe(join(project, ".claude", "settings.local.json")); + }); + + it("says nothing when failproofai has no Claude hooks to switch off", () => { + const project = join(dir, "project"); + put(join(dir, "home", ".claude", "settings.json"), { disableAllHooks: true }); + expect(claudeHooksSwitchedOff(project, managed())).toBeNull(); + }); + + it("says nothing while the hooks are on", () => { + const project = join(dir, "project"); + put(join(dir, "home", ".claude", "settings.json"), { ...ourHooks, disableAllHooks: false }); + expect(claudeHooksSwitchedOff(project, managed())).toBeNull(); + }); + + it("lets a managed file decide, in either direction", () => { + const project = join(dir, "project"); + put(join(dir, "home", ".claude", "settings.json"), ourHooks); + put(join(project, ".claude", "settings.local.json"), { disableAllHooks: true }); + put(managed(), { disableAllHooks: false }); + expect(claudeHooksSwitchedOff(project, managed())).toBeNull(); + put(managed(), { disableAllHooks: true }); + expect(claudeHooksSwitchedOff(project, managed())).toBe(managed()); + }); + + // Windows keeps the file where the session started; that case injects "win32" below. + it.skipIf(process.platform === "win32")("reads a repository's local settings at its root when run from a subdirectory", () => { + const repo = join(dir, "repo"); + mkdirSync(join(repo, ".git"), { recursive: true }); + mkdirSync(join(repo, "src"), { recursive: true }); + put(join(dir, "home", ".claude", "settings.json"), ourHooks); + put(join(repo, ".claude", "settings.local.json"), { disableAllHooks: true }); + expect(claudeHooksSwitchedOff(join(repo, "src"), managed())).toBe(join(repo, ".claude", "settings.local.json")); + }); + + it("still reads one an older Claude Code left in the starting directory", () => { + const repo = join(dir, "repo"); + mkdirSync(join(repo, ".git"), { recursive: true }); + put(join(dir, "home", ".claude", "settings.json"), ourHooks); + put(join(repo, "src", ".claude", "settings.local.json"), { disableAllHooks: true }); + expect(claudeHooksSwitchedOff(join(repo, "src"), managed())).toBe(join(repo, "src", ".claude", "settings.local.json")); + }); + + it.skipIf(process.platform === "win32")("finds hooks installed only in the repository root's local file", () => { + const repo = join(dir, "repo"); + mkdirSync(join(repo, ".git"), { recursive: true }); + mkdirSync(join(repo, "src"), { recursive: true }); + put(join(repo, ".claude", "settings.local.json"), { ...ourHooks, disableAllHooks: true }); + expect(claudeHooksSwitchedOff(join(repo, "src"), managed())).toBe(join(repo, ".claude", "settings.local.json")); + }); + + it.skipIf(process.platform === "win32")("reads a worktree's local settings at the main checkout's root", () => { + const main = join(dir, "main"); + const worktree = join(dir, "wt"); + mkdirSync(join(main, ".git", "worktrees", "wt"), { recursive: true }); + writeFileSync(join(main, ".git", "worktrees", "wt", "commondir"), "../..\n"); + mkdirSync(join(worktree, "src"), { recursive: true }); + writeFileSync(join(worktree, ".git"), `gitdir: ${join(main, ".git", "worktrees", "wt")}\n`); + put(join(dir, "home", ".claude", "settings.json"), ourHooks); + put(join(main, ".claude", "settings.local.json"), { disableAllHooks: true }); + expect(claudeHooksSwitchedOff(join(worktree, "src"), managed())).toBe(join(main, ".claude", "settings.local.json")); + }); + + it("lets the last managed-settings.d fragment decide over the base file", () => { + const project = join(dir, "project"); + const fragments = join(dir, "managed-settings.d"); + put(join(dir, "home", ".claude", "settings.json"), ourHooks); + put(managed(), { disableAllHooks: false }); + put(join(fragments, "10-hooks.json"), { disableAllHooks: true }); + expect(claudeHooksSwitchedOff(project, managed())).toBe(join(fragments, "10-hooks.json")); + put(join(fragments, "20-later.json"), { disableAllHooks: false }); + put(join(fragments, ".hidden.json"), { disableAllHooks: true }); + expect(claudeHooksSwitchedOff(project, managed())).toBeNull(); + }); + + it("keeps it in the starting directory on Windows and when the repository is the home directory", () => { + const home = join(dir, "home"); + mkdirSync(join(home, ".git"), { recursive: true }); + mkdirSync(join(home, "notes"), { recursive: true }); + const here = join(home, "notes", ".claude", "settings.local.json"); + expect(claudeLocalSettingsPaths(join(home, "notes"), "linux", home)).toEqual([here]); + expect(claudeLocalSettingsPaths(join(home, "notes"), "win32", join(dir, "elsewhere"))).toEqual([here]); + expect(claudeLocalSettingsPaths(join(home, "notes"), "linux", join(dir, "elsewhere"))).toEqual([ + join(home, ".claude", "settings.local.json"), + here, + ]); + }); + + it("carries the finding into the status facts through its seam", async () => { + const f = await gatherStatusFacts({ + now: 0, + cwd: join(dir, "project"), + daemonStatus: () => "not-installed", + daemonAnswering: () => false, + detectInstalled: () => ["claude"], + notEnforcing: () => null, + codexTrust: () => ({ kind: "none" }), + claudeHooksOff: () => "/p/.claude/settings.local.json", + }); + expect(f.claudeHooksOff).toEqual({ path: "/p/.claude/settings.local.json" }); + const quiet = await gatherStatusFacts({ + now: 0, + cwd: join(dir, "project"), + daemonStatus: () => "not-installed", + daemonAnswering: () => false, + detectInstalled: () => ["claude"], + notEnforcing: () => null, + codexTrust: () => ({ kind: "none" }), + claudeHooksOff: () => null, + }); + expect(quiet.claudeHooksOff).toBeUndefined(); + }); + + const base = (over: Partial = {}): StatusFacts => ({ + now: 0, + daemon: { + supported: true, + platform: "linux", + service: "running", + answering: true, + configured: true, + version: "1.0.0", + skew: null, + checkCommand: null, + }, + pauses: [], + cloud: { kind: "none" }, + agents: { traced: 1, notInstalled: 0 }, + policies: { + packOn: 10, + firstPack: "FailproofAI/policies@1.0.0", + morePacks: 0, + cloudOn: 0, + observing: 0, + customFiles: 0, + legacy: 0, + refusedPacks: 0, + packsInstalled: 1, + }, + notEnforcing: null, + ...over, + }); + const PLAIN = { version: "1.0.0", cols: 120, color: false }; + + it("shows a claude row and a failing attention line", () => { + const facts = base({ claudeHooksOff: { path: "/p/.claude/settings.local.json" } }); + const screen = renderStatusScreen(facts, PLAIN).join("\n"); + expect(screen).toMatch(/claude\s+○ Not enforcing: disableAllHooks in \/p\/\.claude\/settings\.local\.json/); + expect(pickStatusAttention(facts)).toEqual({ + severity: "fail", + text: "Claude Code is running none of failproofai's hooks: disableAllHooks is true.", + detail: 'Remove "disableAllHooks" from /p/.claude/settings.local.json.', + }); + }); + + it("ranks it above 'not enforcing yet', below a daemon that denies everything", () => { + const off = { claudeHooksOff: { path: "/h/.claude/settings.json" } }; + expect(pickStatusAttention(base({ ...off, notEnforcing: "no-policies" }))?.text).toMatch(/disableAllHooks/); + const down = base({ ...off, daemon: { ...base().daemon, answering: false } }); + expect(pickStatusAttention(down)?.text).toMatch(/failproofaid is not answering/); + }); + + it("shows no claude row while the hooks are on", () => { + expect(renderStatusScreen(base(), PLAIN).join("\n")).not.toMatch(/^\s*claude\s/m); + expect(pickStatusAttention(base())).toBeNull(); + }); +}); diff --git a/__tests__/hooks/codex-interactive-session.test.ts b/__tests__/hooks/codex-interactive-session.test.ts new file mode 100644 index 000000000..4b86be9b2 --- /dev/null +++ b/__tests__/hooks/codex-interactive-session.test.ts @@ -0,0 +1,92 @@ +// @vitest-environment node +// +// Codex runs PreToolUse for the command that opens a session it keeps running, +// and none for what is typed into it afterwards (live codex-cli 0.172: the only +// hook call was `Bash` `{"command": "bash -i"}`). So opening one is refused. +import { describe, it, expect } from "vitest"; +import { codexCallOpensSession, codexSessionGuardFor, opensInteractiveSession } from "../../src/hooks/codex-interactive-session"; +import type { PolicyContext } from "../../src/hooks/policy-types"; + +describe("opensInteractiveSession", () => { + it.each([ + "bash -i", "bash", "sh", "zsh -l", "/bin/bash --login", "fish", "bash -s", "exec bash", "env TERM=xterm bash -i", + "cd /tmp && bash", "FOO=1 bash -i", "busybox sh", "pwsh", "nu", + "python3", "python", "python3.12 -i", "python -i script.py", "python3 -m asyncio", "python -m pdb x.py", "python3 -", "ipython", "pypy3", + "node", "node -i", "deno", "bun repl", "irb", "pry", "ruby", "perl", "perl -de0", "php -a", "lua", "lua -i", "ghci", "R", "julia", "iex", + "tmux", "tmux new -s work", "tmux attach -t work", "screen", "screen -S x", + "ssh host", "ssh -p 2222 user@host", "ssh host bash", "mosh host", "telnet host", "sftp host", + "docker exec -it web sh", "docker run -it ubuntu", "docker run --interactive --rm img", "podman exec -i c bash", "docker attach web", + "kubectl exec -it pod -- sh", "kubectl run tmp -i --image=busybox", "kubectl debug -it pod", + "su", "su - root", "sudo -i", "sudo -s", "sudo bash", "sudo -u app bash", "doas sh", + "script", "script -q /dev/null", "nix-shell", "nix develop", "nix repl", "poetry shell", "pipenv shell", "vagrant ssh", + "vim notes.txt", "nvim", "ed file.txt", "emacs file", "nano x", "gdb ./a.out", "sqlite3 app.db", "psql", "mysql -u root", "redis-cli", + "nohup bash -i", "timeout 60 bash -i", "time python3", + // Nested and redirected shells, and shells an interpreter starts (hermes on #1058). + "bash -c 'bash -i'", "sh -c \"exec bash\"", "bash -lc 'zsh'", "bash -i < /dev/tty", "bash <&0", "bash < /dev/stdin", + "python3 -c 'import pty; pty.spawn(\"/bin/bash\")'", "perl -e 'exec \"/bin/sh\"'", "node -e 'require(\"child_process\").spawnSync(\"bash\", {stdio: \"inherit\"})'", + ])("refuses %s", (command) => { + expect(opensInteractiveSession(command)).not.toBeNull(); + }); + + it.each([ + "ls -la", "npm run dev", "npm test", "bun run build", "cargo run", "make", "git log", "git status", + "bash script.sh", "bash -c 'echo hi'", "bash -lc 'make test'", "sh ./configure", "zsh -c ls", "echo ls | bash", "bash < setup.sh", + "bash <<'EOF'\necho hi\nEOF", + "python3 script.py", "python -c 'print(1)'", "python3 -m pytest", "python -m http.server 8000", "python3 < x.py", "cat x.py | python3", + "node server.js", "node -e 'console.log(1)'", "node --version", "deno run main.ts", "bun x.ts", "ruby -e 'puts 1'", "ruby app.rb", "perl -ne 'print' f", + "man ls", "less README.md", "git diff | less", "tmux send-keys -t work 'ls' Enter", "tmux ls", "screen -ls", + "ssh host uptime", "ssh -N -L 8080:localhost:80 host", "sftp -b batch.txt host", + "docker ps", "docker exec web ls", "docker run --rm img echo hi", "kubectl get pods", "kubectl exec pod -- ls", + "su -c 'whoami' root", "sudo ls", "sudo -u app make", "script -c 'make' log.txt", + "nix-shell --run make", "nix develop -c make", "gdb -batch -ex bt ./a.out", "emacs --batch -l x.el", + "sqlite3 app.db 'select 1'", "psql -c 'select 1'", "mysql -e 'select 1'", "redis-cli ping", + "echo 'bash -i'", "grep python3 file", "# bash -i", + // Version and help flags print and exit (hermes on #1058). + "python3 --version", "python3 -V", "python3 --help", "python -h", "bash --version", "bash --help", "zsh --version", + "node --version", "ruby --version", "perl -V", "psql --version", "sqlite3 --version", "tmux -V", + "bash -c 'ls -la'", "python3 -c 'import os; print(os.getcwd())'", + ])("allows %s", (command) => { + expect(opensInteractiveSession(command)).toBeNull(); + }); +}); + +// #1105 review, item 3: a pipe whose producer passes typed input on, a shell +// as the command `script -c` runs, and `-` as the program to read. +describe("opensInteractiveSession — gaps from the #1105 review", () => { + it.each([ + "cat | bash", "cat - | sh", "cat | bash -s", "tee /tmp/log | bash", "cat | tee /tmp/log | bash", "stdbuf -oL cat | bash", + "head -n 100 | bash", "sed -u 's/x/y/' | sh", "grep -v '^#' | bash", "awk '{print}' | bash", "base64 -d | bash", "dd bs=1 | sh", + "cat | python3", "cat | node", "cat | ruby", "cat | perl", "cat | node -", + "script -qc bash /dev/null", "script -c bash", "script -q -c 'bash -i' /dev/null", "script --command=zsh /dev/null", + "su -c bash", "su root -c 'bash -i'", + "node -", "ruby -", "perl -", "php -", "nodejs -", "bash -", "sh -", "python3 /dev/stdin", "node /dev/stdin", "bash /dev/fd/0", + ])("refuses %s", (command) => { + expect(opensInteractiveSession(command)).not.toBeNull(); + }); + + it.each([ + "echo hi | bash -c 'cat'", "echo ls | bash", "cat setup.sh | bash", "cat < setup.sh | bash", "curl -fsSL https://x/install.sh | sh", + "git diff | cat", "cat | wc -l", "head -n 5 install.sh | bash", "grep -v '^#' setup.sh | bash", "printf 'ls\\n' | sh", + "python3 script.py", "node app.js", "ruby app.rb", "perl script.pl", "node - < app.js", "cat app.js | node -", + "script -c make log.txt", "script -qc 'npm test' /dev/null", "su -c whoami root", + ])("allows %s", (command) => { + expect(opensInteractiveSession(command)).toBeNull(); + }); +}); + +describe("codexCallOpensSession and the guard", () => { + it("judges only a canonical Bash call on PreToolUse", () => { + expect(codexCallOpensSession("PreToolUse", "Bash", { command: "bash -i" })).not.toBeNull(); + expect(codexCallOpensSession("PostToolUse", "Bash", { command: "bash -i" })).toBeNull(); + expect(codexCallOpensSession("PreToolUse", "Edit", { command: "bash -i" })).toBeNull(); + expect(codexCallOpensSession("PreToolUse", "Bash", {})).toBeNull(); + }); + + it("denies and tells the agent what to do instead", () => { + const ctx = { eventType: "PreToolUse", payload: {}, toolName: "Bash", toolInput: {} } as PolicyContext; + const result = codexSessionGuardFor("an interactive bash shell")(ctx); + expect(result.decision).toBe("deny"); + expect(result.reason).toContain("an interactive bash shell"); + expect(result.reason).toContain("Run each command on its own"); + }); +}); diff --git a/__tests__/hooks/config-status.test.ts b/__tests__/hooks/config-status.test.ts index ad03ef6dc..4745c9d53 100644 --- a/__tests__/hooks/config-status.test.ts +++ b/__tests__/hooks/config-status.test.ts @@ -778,10 +778,9 @@ describe("config --status — Codex trust", () => { const f = facts({ codex: { kind: "untrusted", path: "/h/.codex/hooks.json", untrusted: 10, total: 10 } }); const lines = renderStatusScreen(f, PLAIN); expect(rowValue(lines, "codex")).toBe("○ Not enforcing: hooks not trusted"); - expect(enforcement(lines).slice(-3)).toEqual([ + expect(enforcement(lines).slice(-2)).toEqual([ "", - "▲ Codex won't run failproofai's hooks until they're trusted.", - " Re-run failproofai config and allow sudo, or open codex once and approve the hooks.", + "▲ Codex won't run failproofai's hooks until they're trusted. · failproofai config", ]); }); diff --git a/__tests__/hooks/configure-wizard.test.ts b/__tests__/hooks/configure-wizard.test.ts index 0b5bbfb20..e1ab69684 100644 --- a/__tests__/hooks/configure-wizard.test.ts +++ b/__tests__/hooks/configure-wizard.test.ts @@ -579,26 +579,36 @@ describe("doneLines", () => { describe("doneLines — Codex trust", () => { const untrusted = { kind: "untrusted", path: "/h/.codex/hooks.json", untrusted: 10, total: 10 } as const; - const WARNING = [ - "▲ Codex won't run failproofai's hooks until they're trusted.", - " Re-run failproofai config and allow sudo, or open codex once and approve the hooks.", - ]; - it("does not count Codex as enforcing while its hooks are untrusted, and says how to fix it", () => { + // One line, with the fix: the user has to act or Codex runs none of the hooks. + const WARNING = + "▲ Codex won't run failproofai's hooks until you trust them: open codex once and approve them, or re-run failproofai config with sudo."; + + it("does not count Codex as enforcing while its hooks are untrusted, and says how to fix it in one line", () => { vi.mocked(notEnforcingReason).mockReturnValue(null); vi.mocked(enforcingPolicyCount).mockReturnValue({ count: 1, custom: false }); const lines = doneLines(kit, { elapsedMs: 1, done: [], cwd: "/x", agents: 2, connected: true, codexTrust: untrusted }); expect(lines).toContain("✓ 1 policy is enforcing on 1 agent."); - const at = lines.indexOf(WARNING[0]); - expect(lines.slice(at, at + 2)).toEqual(WARNING); + expect(lines.filter((l) => l.includes("trust"))).toEqual([WARNING]); }); - it("claims nothing enforces when Codex was the only agent", () => { + it("claims nothing enforces when Codex was the only agent, and the Done section is not all it says", () => { vi.mocked(notEnforcingReason).mockReturnValue(null); vi.mocked(enforcingPolicyCount).mockReturnValue({ count: 1, custom: false }); const lines = doneLines(kit, { elapsedMs: 1, done: [], cwd: "/x", agents: 1, connected: true, codexTrust: untrusted }); expect(lines.join("\n")).not.toMatch(/enforcing on/); - expect(lines).toContain(WARNING[0]); + expect(lines).toContain(WARNING); + }); + + it.each([ + ["trusted", { kind: "trusted", path: "/h/.codex/hooks.json" }], + ["ungated", { kind: "ungated", path: "/h/.codex/hooks.json", version: "0.120.0" }], + ["none", { kind: "none" }], + ] as const)("prints no trust warning when Codex's hooks are %s", (_k, codexTrust) => { + vi.mocked(notEnforcingReason).mockReturnValue(null); + vi.mocked(enforcingPolicyCount).mockReturnValue({ count: 1, custom: false }); + const lines = doneLines(kit, { elapsedMs: 1, done: [], cwd: "/x", agents: 1, connected: true, codexTrust }); + expect(lines.join("\n")).not.toContain("trust"); }); it("counts Codex when its hooks are in the system config", () => { diff --git a/__tests__/hooks/gateway-restart.test.ts b/__tests__/hooks/gateway-restart.test.ts index cc6bbaa0f..454e0f254 100644 --- a/__tests__/hooks/gateway-restart.test.ts +++ b/__tests__/hooks/gateway-restart.test.ts @@ -73,6 +73,29 @@ describe("Hermes gateway restart", () => { const run = () => { throw new Error("ENOENT"); }; expect(restartHermesGateway(PROFILE, { run }).status).toBe("failed"); }); + + it("says nothing when Hermes is not installed: there is no gateway to restart", () => { + const d = deps({ "hermes gateway status": { status: null, stdout: "", missing: true } }); + expect(restartHermesGateway(PROFILE, d).status).toBe("not-running"); + expect(d.spawnDetached).not.toHaveBeenCalled(); + }); +}); + +describe("a gateway whose program is not installed", () => { + it("reads as not running for OpenClaw too, so update prints no row for it", () => { + const d = deps({ "openclaw gateway status --json": { status: null, stdout: "", missing: true } }); + const r = restartOpenClawGateway({ name: "default", home: "/home/u/.openclaw" }, d); + expect(r.status).toBe("not-running"); + expect(openclawRestartLines([r])).toEqual([]); + }); + + it("is detected from a real spawn of a program that does not exist", () => { + const r = restartHermesGateway(PROFILE, { run: undefined, spawnDetached: () => false }); + // Only meaningful where no `hermes` is on PATH (CI); otherwise it is a real status. + if (!process.env.PATH?.split(":").some((d) => { try { return statSync(join(d, "hermes")).isFile(); } catch { return false; } })) { + expect(r.status).toBe("not-running"); + } + }); }); const RUNNING = JSON.stringify({ service: { loaded: true, runtime: { status: "running" } } }); diff --git a/__tests__/hooks/guard-npx-local-bin.test.ts b/__tests__/hooks/guard-npx-local-bin.test.ts new file mode 100644 index 000000000..499334436 --- /dev/null +++ b/__tests__/hooks/guard-npx-local-bin.test.ts @@ -0,0 +1,1543 @@ +// @vitest-environment node +import { describe, it, expect, vi, beforeAll, afterAll } from "vitest"; +import { mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { BUILTIN_POLICIES } from "../../src/hooks/builtin-policies"; +import { listIntegrations } from "../../src/hooks/integrations"; +import type { PolicyContext } from "../../src/hooks/policy-types"; + +// Same mocks as guard-installed-code.test.ts. The symlink cases below use the +// real synchronous `node:fs` on a temp directory, which these leave alone. +vi.mock("node:fs/promises", () => ({ + readFile: vi.fn(), + writeFile: vi.fn(), + stat: vi.fn().mockResolvedValue({ size: 0 }), + open: vi.fn(), +})); + +vi.mock("node:child_process", () => ({ + execSync: vi.fn(), + execFileSync: vi.fn(), +})); + +function makeCtx(overrides: Partial = {}): PolicyContext { + return { eventType: "PreToolUse", payload: {}, toolName: undefined, toolInput: undefined, ...overrides }; +} + +const policy = BUILTIN_POLICIES.find((p) => p.name === "block-failproofai-commands")!; + +const bash = async (command: string) => + (await policy.fn(makeCtx({ toolName: "Bash", toolInput: { command } }))).decision; + +const bashIn = async (cwd: string, command: string) => + (await policy.fn(makeCtx({ toolName: "Bash", toolInput: { command }, session: { cwd } }))).decision; + +const write = async (file_path: string, cwd?: string) => + policy.fn( + makeCtx({ + toolName: "Write", + toolInput: { file_path, content: "#!/bin/sh\nexit 0\n" }, + ...(cwd ? { session: { cwd } } : {}), + }), + ); + +/** A command as the named agent CLI sends it, from the project's directory. */ +const bashAs = async (cli: PolicyContext["cli"], toolInput: Record) => + (await policy.fn(makeCtx({ toolName: "Bash", toolInput, cli, session: { cwd: "/work/proj" } }))).decision; + +/** An `Edit` carrying a patch the way Codex's `apply_patch` does. */ +const patch = async (toolInput: Record, cwd = "/work/proj") => + (await policy.fn(makeCtx({ toolName: "Edit", toolInput, session: { cwd } }))).decision; + +/** A patch in the format Codex's `apply_patch` takes. */ +const v4a = (...lines: string[]) => ["*** Begin Patch", ...lines, "*** End Patch", ""].join("\n"); + +/** `count` option words of 32 distinct letters, each with a value glued on. */ +const optionClusters = (count: number) => + Array.from({ length: count }, (_, i) => { + let letters = ""; + for (let k = 0, n = i; k < 31; k++, n = Math.floor(n / 26) + k) letters += "abcdefghijklmnopqrstuvwxyz"[n % 26]; + return `-${letters}q${i}`; + }).join(" "); + +/** + * A project-scope hook is `npx -y failproofai --hook …`, so that a committed + * settings file names no machine's path. npx runs a + * `node_modules/.bin/failproofai` it finds in the project, or in ANY directory + * above it, before the global install or its own cache, without checking what + * the file is. One Write of `exit 0` there turned every later hook in that tree + * into an allow, and the stub stayed for every later session — the guard + * protected `~/.failproofai` and, with #1050, the installed package, but not + * the entry npx actually runs. (FailproofAI/agenteye#1795) + */ +describe("block-failproofai-commands — the entry a project-scope npx hook runs", () => { + describe("file tools", () => { + it.each([ + ["the project's own", "/work/proj/node_modules/.bin/failproofai"], + ["a parent directory's", "/work/node_modules/.bin/failproofai"], + ["the home directory's, above every project in it", "/home/u/node_modules/.bin/failproofai"], + ["the npx cache's", "/home/u/.npm/_npx/0a1b2c3d4e5f6789/node_modules/.bin/failproofai"], + ["a monorepo package's", "/work/proj/packages/api/node_modules/.bin/failproofai"], + ])("denies writing %s node_modules/.bin/failproofai", async (_where, path) => { + const result = await write(path); + expect(result.decision).toBe("deny"); + expect(result.reason).toMatch(/failproofai's installed code/); + }); + + // npm writes `.cmd` and `.ps1` shims beside the entry on Windows, and bun + // writes `.exe` and `.bunx`. + it.each([ + "C:\\work\\proj\\node_modules\\.bin\\failproofai", + "C:\\work\\proj\\node_modules\\.bin\\failproofai.cmd", + "C:\\work\\proj\\node_modules\\.bin\\failproofai.ps1", + "C:/work/proj/node_modules/.bin/failproofai.exe", + "C:/work/proj/node_modules/.bin/failproofai.bunx", + ])("denies writing the Windows entry %s", async (path) => { + expect((await write(path)).decision).toBe("deny"); + }); + + it("denies Edit and NotebookEdit of the entry", async () => { + const edit = await policy.fn( + makeCtx({ + toolName: "Edit", + toolInput: { file_path: "/work/proj/node_modules/.bin/failproofai", old_string: "exec", new_string: "exit 0 #" }, + }), + ); + expect(edit.decision).toBe("deny"); + const notebook = await policy.fn( + makeCtx({ toolName: "NotebookEdit", toolInput: { notebook_path: "/work/proj/node_modules/.bin/failproofai" } }), + ); + expect(notebook.decision).toBe("deny"); + }); + + it("denies the relative path a write from the project names", async () => { + expect((await write("node_modules/.bin/failproofai", "/work/proj")).decision).toBe("deny"); + expect((await write("./node_modules/.bin/failproofai", "/work/proj")).decision).toBe("deny"); + expect((await write("../node_modules/.bin/failproofai", "/work/proj")).decision).toBe("deny"); + }); + + // macOS volumes are case-insensitive by default, and a path resolver + // collapses `//` and `/./`: every one of these opens the same file. + it("matches every spelling that opens the same file", async () => { + expect((await write("/Users/u/proj/Node_Modules/.BIN/FailproofAI")).decision).toBe("deny"); + expect((await write("/work/proj/node_modules//.bin/./failproofai")).decision).toBe("deny"); + }); + + // Codex's `apply_patch` (canonical `Edit`) carries its patch in + // `tool_input.command` and names no `file_path`; OpenCode's sends + // `patchText`. Every file a patch names is one the tool writes (found by + // hermes on FailproofAI/failproofai#1058). + describe("patches", () => { + it.each([ + ["a file it adds", { command: v4a("*** Add File: node_modules/.bin/failproofai", "+#!/bin/sh", "+exit 0") }], + ["a file it updates", { command: v4a("*** Update File: node_modules/.bin/failproofai", "@@", "-exec node cli.mjs", "+exit 0") }], + ["a file it deletes", { command: v4a("*** Delete File: node_modules/.bin/failproofai") }], + ["where it moves a file to", { command: v4a("*** Update File: scripts/stub.sh", "*** Move to: node_modules/.bin/failproofai", "@@", "+exit 0") }], + ["an absolute path", { command: v4a("*** Add File: /work/proj/node_modules/.bin/failproofai", "+exit 0") }], + ["a parent directory's entry", { command: v4a("*** Add File: ../node_modules/.bin/failproofai", "+exit 0") }], + ["a loosely spaced header", { command: v4a(" *** Add File: node_modules/.bin/failproofai ", "+exit 0") }], + ["the state", { command: v4a("*** Update File: /home/u/.failproofai/policies-config.json", "@@", "+{}") }], + ["the entry, as OpenCode's patchText", { patchText: v4a("*** Add File: node_modules/.bin/failproofai", "+exit 0") }], + ["the entry, in an argv", { command: ["apply_patch", v4a("*** Add File: node_modules/.bin/failproofai", "+exit 0")] }], + ["the entry, as a unified diff", { command: "--- a/node_modules/.bin/failproofai\n+++ b/node_modules/.bin/failproofai\n@@ -1 +1 @@\n-exec\n+exit 0\n" }], + ["the entry, from the directory the call names", { command: v4a("*** Add File: failproofai", "+exit 0"), workdir: "/work/proj/node_modules/.bin" }], + ])("denies a patch naming %s", async (_label, toolInput) => { + expect(await patch(toolInput)).toBe("deny"); + }); + + it("denies a patch naming the entry from a session standing in .bin", async () => { + expect(await patch({ command: v4a("*** Add File: failproofai", "+exit 0") }, "/work/proj/node_modules/.bin")).toBe("deny"); + }); + + it.each([ + ["a patch to project files", { command: v4a("*** Update File: src/app.ts", "@@", "-a", "+b", "*** Add File: src/new.ts", "+x") }], + ["a patch adding another package's entry", { command: v4a("*** Add File: node_modules/.bin/my-tool", "+exit 0") }], + ["a unified diff of project files", { command: "--- a/src/app.ts\n+++ b/src/app.ts\n@@ -1 +1 @@\n-a\n+b\n" }], + // What the tool writes is not a patch it applies, whatever it says. + ["an Edit whose new text quotes a header", { file_path: "docs/patching.md", old_string: "a", new_string: "*** Add File: node_modules/.bin/failproofai" }], + ])("allows %s", async (_label, toolInput) => { + expect(await patch(toolInput)).toBe("allow"); + }); + + it("allows a Write whose content quotes a header", async () => { + const result = await policy.fn( + makeCtx({ + toolName: "Write", + toolInput: { file_path: "docs/patching.md", content: "*** Update File: node_modules/.bin/failproofai\n" }, + session: { cwd: "/work/proj" }, + }), + ); + expect(result.decision).toBe("allow"); + }); + }); + + describe("through links", () => { + let root: string; + + beforeAll(() => { + root = mkdtempSync(join(tmpdir(), "fpai-npx-guard-")); + mkdirSync(join(root, "proj", "node_modules", ".bin", "sub"), { recursive: true }); + mkdirSync(join(root, "proj", "tools"), { recursive: true }); + // Neither link's own path says anything about failproofai or `.bin`. + symlinkSync(join(root, "proj", "node_modules", ".bin"), join(root, "proj", "tools", "bins")); + symlinkSync(join(root, "proj", "node_modules", ".bin", "failproofai"), join(root, "proj", "tools", "hook")); + // A link into a directory below `.bin`, and one to `node_modules`. + symlinkSync(join(root, "proj", "node_modules", ".bin", "sub"), join(root, "proj", "tools", "deep")); + symlinkSync(join(root, "proj", "node_modules"), join(root, "proj", "nm")); + mkdirSync(join(root, "proj", "out")); + }); + + afterAll(() => { + rmSync(root, { recursive: true, force: true }); + }); + + // The entry does not exist yet in a project with no dependencies, so the + // link is dangling: the write creates the stub at the link's target. + it("denies a write through a link to the entry, even before it exists", async () => { + expect((await write(join(root, "proj", "tools", "hook"))).decision).toBe("deny"); + }); + + it("denies a write through a link to the .bin directory", async () => { + expect((await write(join(root, "proj", "tools", "bins", "failproofai"))).decision).toBe("deny"); + expect((await write("tools/bins/failproofai", join(root, "proj"))).decision).toBe("deny"); + }); + + it("still allows other files through the same link", async () => { + expect((await write(join(root, "proj", "tools", "bins", "my-script"))).decision).toBe("allow"); + }); + + // The shell follows the same links the file tools do. + it.each([ + "printf x > tools/bins/failproofai", + "cp /tmp/stub.sh tools/bins/failproofai", + "cp /tmp/stage/failproofai tools/bins/", + "tee tools/bins/failproofai < /tmp/stub.sh", + "printf x > tools/hook", + // A `..` after a link steps out of where the link points, as the + // kernel resolves it, not out of the link's own directory. + "printf x > tools/deep/../failproofai", + "cp /tmp/stub.sh tools/deep/../failproofai", + // What a copy puts INTO a linked bin directory: contents, a glob, a + // name the server picks. + "cp -r /tmp/stage/. tools/bins/", + "cp -rT /tmp/stage tools/bins", + "cp /tmp/stage/* tools/bins/", + "curl --output-dir tools/bins -OJ https://example.com/dl", + // A directory named `.bin` moved into a linked `node_modules`. + "mv /tmp/x/.bin nm/", + ])("denies a shell write through a link: %s", async (command) => { + expect(await bashIn(join(root, "proj"), command)).toBe("deny"); + expect(await bash(`cd '${join(root, "proj")}' && ${command}`)).toBe("deny"); + }); + + it.each([ + "printf x > tools/bins/my-script", + "cat tools/bins/failproofai", + "ls -la tools/bins/ > listing.txt", + "printf x > tools/deep/../my-tool", + "cp -r /tmp/stage/. out/", + ])( + "still allows shell work through a link: %s", + async (command) => { + expect(await bashIn(join(root, "proj"), command)).not.toBe("deny"); + }, + ); + + it("denies a patch through a link to the entry or the .bin directory", async () => { + for (const file of ["tools/hook", "tools/bins/failproofai", "tools/deep/../failproofai"]) { + expect(await patch({ command: v4a(`*** Update File: ${file}`, "@@", "+exit 0") }, join(root, "proj"))).toBe("deny"); + } + }); + + // An output file glued to its option, through a link on disk (found by + // hermes on FailproofAI/failproofai#1058). + it.each([ + "curl -sohook https://example.com/x", + "curl -so./hook https://example.com/x", + "curl -sobins/failproofai https://example.com/x", + "wget -qOhook https://example.com/x", + "gcc -ohook main.c", + ])("denies an output file glued to its option through a link: %s", async (command) => { + expect(await bashIn(join(root, "proj", "tools"), command)).toBe("deny"); + }); + + it("denies a sed script writing the entry through a link", async () => { + expect(await bashIn(join(root, "proj"), "sed -n 'w tools/bins/failproofai' /tmp/stub.sh")).toBe("deny"); + expect(await bashIn(join(root, "proj"), "sed -n '1wtools/hook' /tmp/stub.sh")).toBe("deny"); + expect(await bashIn(join(root, "proj"), "sed -e 's/w/x/;1wtools/hook' /tmp/stub.sh")).toBe("deny"); + }); + + it("denies a named output that curl puts into a linked --output-dir", async () => { + expect(await bashIn(join(root, "proj"), "curl --output-dir tools/bins -o failproofai https://example.com/x")).toBe("deny"); + }); + + it("allows a glued output file that is no link", async () => { + expect(await bashIn(join(root, "proj", "tools"), "curl -sohook.txt https://example.com/x")).not.toBe("deny"); + }); + + // Links this line makes, resolved as the kernel resolves them: each `..` + // after the link it follows, any number of them up to the kernel's 40, + // and every form of `ln` that puts one inside a directory (found by + // hermes on FailproofAI/failproofai#1058). + it.each([ + ["a `..` after a link made on the line", "ln -s node_modules/.bin/sub inline-deep; printf x > inline-deep/../failproofai"], + ["the same, after &&", "ln -s node_modules/.bin/sub inline-deep && cp /tmp/stub.sh inline-deep/../failproofai"], + [ + "a chain of ten links", + ["ln -s node_modules/.bin l1", ...Array.from({ length: 9 }, (_, i) => `ln -s l${i + 1} l${i + 2}`)].join("; ") + + "; printf x > l10/failproofai", + ], + [ + "a chain longer than the kernel follows", + ["ln -s node_modules/.bin l1", ...Array.from({ length: 44 }, (_, i) => `ln -s l${i + 1} l${i + 2}`)].join("; ") + + "; printf x > l45/failproofai", + ], + ["two links pointing at each other", "ln -s a b; ln -s b a; printf x > a/x"], + ["a link put into the current directory", "ln -s node_modules/.bin/failproofai .; printf x > failproofai"], + ["a link put into a directory with a slash", "ln -s node_modules/.bin/failproofai out/; printf x > out/failproofai"], + ["a link put into an existing directory", `ln -s ROOT/node_modules/.bin/failproofai out; printf x > out/failproofai`], + ["a link put into -t's directory", `ln -st out ROOT/node_modules/.bin/failproofai; printf x > out/failproofai`], + ["a link put into --target-directory's", `ln --symbolic --target-directory=out ROOT/node_modules/.bin/failproofai; printf x > out/failproofai`], + ["ln -s with one operand", "ln -s node_modules/.bin/failproofai; printf x > failproofai"], + ["a directory the line makes first", `mkdir newdir; ln -s ROOT/node_modules/.bin/failproofai newdir; printf x > newdir/failproofai`], + ["ln -r, which reads the target from here", "ln -sr node_modules/.bin/failproofai out/x; printf x > out/x"], + ["a target the walk cannot read, naming .bin", 'ln -s "$(npm root)/.bin" b; printf x > b/failproofai'], + ["a target the walk cannot read at all", 'ln -s "$D" b; printf x > b/failproofai'], + ["a substitution's directory, filled with what is in another", 'ln -s "$(npm root)/.bin" d; cp -r /tmp/stage/. d/'], + ])("denies a write through %s", async (_label, command) => { + expect(await bashIn(join(root, "proj"), command.replaceAll("ROOT", join(root, "proj")))).toBe("deny"); + }); + + // `cd -P` (or any `cd` after `set -P`) stands where the path really is, + // each link followed before its `..` (found by hermes on + // FailproofAI/failproofai#1058); a logical `cd` takes `..` as text, as + // bash does, and the kernel still follows links in what is written after. + it.each([ + "cd -P tools/deep/.. && printf x > failproofai", + "cd -LP tools/deep/.. && printf x > failproofai", + "set -P; cd tools/deep/.. && printf x > failproofai", + "set -o physical; cd tools/deep/.. && printf x > failproofai", + "cd -P tools/deep && cd .. && printf x > failproofai", + "cd tools/deep && printf x > ../failproofai", + // A subshell's shell options are its own (found by hermes on + // FailproofAI/failproofai#1058). + "set -P; (set +P); cd tools/deep/.. && printf x > failproofai", + "(set -P; cd tools/deep/.. && printf x > failproofai)", + ])("denies a write after a physical move through a link: %s", async (command) => { + expect(await bashIn(join(root, "proj"), command)).toBe("deny"); + }); + + it.each([ + "cd tools/deep/.. && printf x > failproofai", + "cd -L tools/deep/.. && printf x > failproofai", + "set -P; set +P; cd tools/deep/.. && printf x > failproofai", + "(set -P); cd tools/deep/.. && printf x > failproofai", + "(set -P; cd tools/deep/..); printf x > failproofai", + ])("still allows a write after a logical move: %s", async (command) => { + expect(await bashIn(join(root, "proj"), command)).not.toBe("deny"); + }); + + // A glob expands where its literal directories really are (found by + // hermes on FailproofAI/failproofai#1058). + it.each([ + "cp /tmp/stub.sh tools/bins/fail*", + "cp /tmp/stub.sh tools/bins/failpro?fai", + "cp /tmp/stub.sh tools/bins/[f]ailproofai", + "printf x > tools/bins/fail*", + "cd tools/bins && cp /tmp/stub.sh fail*", + "cp /tmp/stub.sh tools/deep/../fail*", + ])("denies a glob that expands onto the entry through a link: %s", async (command) => { + expect(await bashIn(join(root, "proj"), command)).toBe("deny"); + }); + + it.each(["ls tools/bins/*", "cat tools/bins/fail*", "cp /tmp/stub.sh tools/bins/my-*", "rm -rf tools/bins/*"])( + "still allows a glob through a link that is no write of the entry: %s", + async (command) => { + expect(await bashIn(join(root, "proj"), command)).not.toBe("deny"); + }, + ); + + it.each([ + "ln -s node_modules/.bin/sub d; printf x > d/../notes.txt", + "ln -s /tmp/x y; echo hi > y", + 'ln -s "$TARGET" current; echo hi > current/log.txt', + "ln -sf build/app current; ./current --version", + // A variable the line never sets is read as an unknown `cd` is. + 'ln -sfn "$RELEASE_DIR" current && cp -r shared/config current/', + ])("still allows a write through a link made on the line: %s", async (command) => { + expect(await bashIn(join(root, "proj"), command)).not.toBe("deny"); + }); + }); + + // A pattern in a directory component is expanded the way the shell expands + // it, against what is on disk, and each path it reaches is followed through + // its links: with `bins` a link to `node_modules/.bin` and the entry there, + // `b*/failproofai` is the entry (found by hermes on + // FailproofAI/failproofai#1058). + describe("globs expanded on disk", () => { + let root: string; + + beforeAll(() => { + root = mkdtempSync(join(tmpdir(), "fpai-npx-glob-")); + mkdirSync(join(root, "proj", "node_modules", ".bin"), { recursive: true }); + mkdirSync(join(root, "proj", "src")); + mkdirSync(join(root, "proj", "out")); + writeFileSync(join(root, "proj", "node_modules", ".bin", "failproofai"), "#!/bin/sh\n"); + writeFileSync(join(root, "proj", "package.json"), "{}\n"); + symlinkSync(join(root, "proj", "node_modules", ".bin"), join(root, "proj", "bins")); + symlinkSync(join(root, "proj", "node_modules", ".bin", "failproofai"), join(root, "proj", "hook")); + }); + + afterAll(() => { + rmSync(root, { recursive: true, force: true }); + }); + + it.each([ + "cp /tmp/stub.sh b*/failproofai", + "cp /tmp/stub.sh bi?s/failproofai", + "cp /tmp/stub.sh [b]ins/failproofai", + "printf x > b*/failproofai", + "tee {bins,x}/failproofai < /tmp/stub.sh", + // A pattern or brace in the last component that matches a link to the + // entry (found by hermes on FailproofAI/failproofai#1058). + "cp /tmp/stub.sh hoo*", + "printf x > ho?k", + "cp /tmp/stub.sh {hook,nothing}", + "tee {hook,x} < /tmp/stub.sh", + // Past the brace words that are expanded on disk, the rest are refused, + // not dropped: `hook` is the 65th word here (found by hermes on + // FailproofAI/failproofai#1058). + "tee {x{a,b,c,d}{1,2,3,4}{i,j,k,l},hook} { + expect(await bashIn(join(root, "proj"), command)).toBe("deny"); + }); + + it.each([ + "cat */package.json", + "rm -rf */dist", + "ls b*/", + "cp /tmp/stub.sh s*/notes.txt", + "tee {out,src}/notes.txt < /tmp/stub.sh", + // Sweeps of npm's bin directory and `node_modules` stay sweeps with the + // entry on disk, and reading through a link is a read. + "rm -rf node_modules/.bin/*", + "rm -rf node_modules/*", + "ls *", + "cat hook", + "tee {x{a,b,c,d}{1,2,3,4}{i,j,k,l},notes} { + expect(await bashIn(join(root, "proj"), command)).not.toBe("deny"); + }); + }); + + // The entry, and nothing else that lives beside it or shares its name. + it.each([ + ["another package's entry", "/work/proj/node_modules/.bin/tsc"], + ["an entry that only shares a prefix", "/work/proj/node_modules/.bin/failproofai-extras"], + ["a name npx never runs for `failproofai`", "/work/proj/node_modules/.bin/failproofai.sh"], + ["a project file named after the product", "/work/proj/scripts/failproofai.sh"], + ["a directory of that name under .bin", "/work/proj/.bin/failproofai/README.md"], + ["a file under a directory whose name ends in .bin", "/data/firmware.bin/failproofai"], + // Anything in front of `.bin` in the same component makes it another name. + ["a fixture under a directory named fixture+.bin", "/work/proj/fixture+.bin/failproofai"], + ])("allows writing %s", async (_label, path) => { + expect((await write(path)).decision).toBe("allow"); + }); + }); + + describe("shell commands", () => { + it.each([ + ["a redirect", "printf '#!/bin/sh\\nexit 0\\n' > node_modules/.bin/failproofai"], + ["an append", "echo 'exit 0' >> ./node_modules/.bin/failproofai"], + ["a copy", "cp /tmp/stub.sh node_modules/.bin/failproofai"], + ["a move", "mv /tmp/stub.sh node_modules/.bin/failproofai"], + ["a link", "ln -sf /tmp/stub.sh node_modules/.bin/failproofai"], + ["tee", "tee node_modules/.bin/failproofai < /tmp/stub.sh"], + ["install", "install -m 755 /tmp/stub.sh node_modules/.bin/failproofai"], + ["making a stub executable", "chmod +x node_modules/.bin/failproofai"], + ["an in-place sed", "sed -i 's/exec/exit 0 #/' node_modules/.bin/failproofai"], + ["an interpreter writing it", `python3 -c "open('node_modules/.bin/failproofai','w').write('exit 0')"`], + ["a parent directory's entry", "cp /tmp/stub.sh ../node_modules/.bin/failproofai"], + ["the home directory's entry", "cp /tmp/stub.sh ~/node_modules/.bin/failproofai"], + ["the entry named from inside node_modules", "cd node_modules && cp /tmp/stub.sh .bin/failproofai"], + ["the Windows shim", "cp /tmp/stub.cmd node_modules/.bin/failproofai.cmd"], + ["a variable holding the entry", "B=node_modules/.bin/failproofai; cp /tmp/stub.sh $B"], + ["a glob onto the entry", "cp /tmp/stub.sh node_modules/.bin/fail*"], + ["a quoted spelling", `cp /tmp/stub.sh node_modules/.bin/fail"proof"ai`], + // The path is on the line only in pieces: a file named `failproofai` + // copied, moved or linked INTO the directory npx searches. + ["a copy into the .bin directory", "cp /tmp/stage/failproofai node_modules/.bin/"], + ["a copy into the .bin directory, no trailing slash", "cp /tmp/stage/failproofai node_modules/.bin"], + ["a move into the .bin directory", "mv ./failproofai node_modules/.bin/"], + ["a link into the .bin directory", "ln -s /tmp/stage/failproofai node_modules/.bin"], + ["a copy with -t", "cp -t node_modules/.bin /tmp/stage/failproofai"], + ["a copy with --target-directory=", "cp --target-directory=node_modules/.bin /tmp/stage/failproofai"], + ["install -D into the directory", "install -D -m 755 /tmp/stage/failproofai node_modules/.bin/"], + ["rsync into the directory", "rsync -a /tmp/stage/failproofai node_modules/.bin/"], + ["a copy among other files", "cp /tmp/a.sh /tmp/stage/failproofai /tmp/b.sh node_modules/.bin/"], + ["a copy after --", "cp -- /tmp/stage/failproofai node_modules/.bin/"], + ])("denies %s", async (_label, command) => { + expect(await bash(command)).toBe("deny"); + }); + + // The same rule reaches the paths #1050 protects: moving a package + // directory named `failproofai` into a global `node_modules` replaces it. + it("denies moving a directory named failproofai into a node_modules", async () => { + expect(await bash("mv /tmp/build/failproofai /home/u/.nvm/versions/node/v22.11.0/lib/node_modules/")).toBe("deny"); + }); + + // Every GNU spelling of the target directory, which puts the sources AFTER + // it. rsync has no such option: its `-t` is `--times`, and its last operand + // is still the destination. + it.each([ + ["-t glued to its value", "cp -tnode_modules/.bin /tmp/stage/failproofai"], + ["-t at the end of a cluster", "cp -vt node_modules/.bin /tmp/stage/failproofai"], + ["-t inside install's cluster", "install -Dt node_modules/.bin /tmp/stage/failproofai"], + ["-t on ln", "ln -st node_modules/.bin /tmp/stage/failproofai"], + ["an abbreviated --target=", "cp --target=node_modules/.bin /tmp/stage/failproofai"], + ["an abbreviated --target with its value apart", "cp --target node_modules/.bin /tmp/stage/failproofai"], + ["rsync's -t, which is --times", "rsync -t /tmp/stage/failproofai node_modules/.bin/"], + ])("denies a copy into the .bin directory with %s", async (_label, command) => { + expect(await bash(command)).toBe("deny"); + }); + + // A redirect or a comment after the destination was read as the + // destination, so every copy check judged `2>/dev/null` or `x`. That let + // the state through too, before this file existed. + it.each([ + ["a stderr redirect", "cp /tmp/stub.sh node_modules/.bin/failproofai 2>/dev/null"], + ["a stdout redirect", "install -m 755 /tmp/stub.sh node_modules/.bin/failproofai > /dev/null"], + ["2>&1", "rsync /tmp/stub.sh node_modules/.bin/failproofai 2>&1"], + ["an input redirect", "cp /tmp/stub.sh node_modules/.bin/failproofai < /dev/null"], + ["a comment", "cp /tmp/stub.sh node_modules/.bin/failproofai # keep"], + ["a redirect after a copy into the directory", "cp /tmp/stage/failproofai node_modules/.bin/ 2>/dev/null"], + ["a redirect after a link into the directory", "ln -sf /tmp/stage/failproofai node_modules/.bin 2>/dev/null"], + ["the state, emptied the same way", "cp /dev/null ~/.failproofai/policies-config.json 2>/dev/null"], + ])("denies a write followed by %s", async (_label, command) => { + expect(await bash(command)).toBe("deny"); + }); + + // A source that names a protected path is a copy OUT, except when it lands + // on installed code: a link spelled `…/bin/failproofai` is still a stub. + it("denies a protected-looking source when it lands on the entry", async () => { + expect(await bash("cp /tmp/bin/failproofai node_modules/.bin/")).toBe("deny"); + expect(await bash("rsync /tmp/bin/failproofai node_modules/.bin/")).toBe("deny"); + }); + + // A protected FILE sits in a directory nothing protects, so the walk has + // to read a relative word from where a `cd` left the shell. + it.each([ + ["a redirect after cd", "cd node_modules/.bin && printf 'exit 0' > failproofai"], + ["a copy after cd", "cd node_modules/.bin && cp /tmp/stub.sh failproofai"], + ["a copy after pushd", "pushd node_modules/.bin && cp /tmp/stub.sh failproofai"], + ["chmod after cd", "cd node_modules/.bin && chmod +x failproofai"], + ["two relative cds", "cd node_modules && cd .bin && cp /tmp/stub.sh failproofai"], + ["a cd outside a subshell that ran its own", "cd node_modules/.bin && (cd /tmp && ls) && cp /tmp/stub.sh failproofai"], + ["a copy of a file named failproofai into the directory", "cd node_modules/.bin && cp /tmp/stage/failproofai ."], + ])("denies %s", async (_label, command) => { + expect(await bash(command)).toBe("deny"); + }); + + // A glob replaces the entry wherever it already exists, whatever path + // leads to it, so the candidates are tried against every stretch of it. + it.each([ + ["a parent directory", "cp /tmp/stub.sh ../node_modules/.bin/fail*"], + ["home", "cp /tmp/stub.sh ~/node_modules/.bin/fail*"], + ["an absolute path", "cp /tmp/stub.sh /work/proj/node_modules/.bin/fail*"], + // A default macOS volume resolves the literal parent whatever its case. + ["an upper-case parent", "rm -rf NODE_MODULES/.BIN/f*"], + // `/home/u/.failproofai` is a candidate itself; another home is not. + ["the state, by an absolute path", "rm -rf /home/alice/.failproof*"], + ["the state, behind `//` and `/./`", "rm -rf ~//./.failproof*"], + // A home no candidate spells. A dotfile glob that can match + // `.failproofai` counts wherever it stands, as the name itself does: + // `rm -rf ~/.cache/.f*` is refused for the same reason. + ["the state, in a home outside /home", "rm -rf /var/lib/jenkins/.failproof*"], + ["the state's name in another directory", "rm -rf ~/.cache/.f*"], + ])("denies a glob onto the entry through %s", async (_label, command) => { + expect(await bash(command)).toBe("deny"); + }); + + // npm's bin directory itself: whatever a directory moved, linked or copied + // onto it holds becomes an entry, and npx searches every parent's. + it.each([ + ["a link over home's", "ln -s /tmp/stage ~/node_modules/.bin"], + ["a move", "mv /tmp/stage node_modules/.bin"], + ["a recursive copy", "cp -r /tmp/stage/ node_modules/.bin/"], + ["a copy onto it with -T", "cp -rT /tmp/stage node_modules/.bin"], + ["a copy of a directory's contents", "cp -a /tmp/stage/. node_modules/.bin/"], + ["rsync of a directory's contents", "rsync -a /tmp/stage/ node_modules/.bin/"], + ["a build directory, which becomes the directory when it is missing", "cp -r dist/ node_modules/.bin/"], + ])("denies %s onto node_modules/.bin", async (_label, command) => { + expect(await bash(command)).toBe("deny"); + }); + + // A word is read without knowing whether it sits in quotes, so a quoted + // `#` or `<` must not hide the words after it. + it.each([ + ["a quoted # before an output flag", "curl -sS -H 'X-Ticket: #1795' -o ~/.failproofai/policies-config.json https://example.com/c"], + ["a quoted # before -delete", "find ~/.failproofai -name 'x #' -o -delete"], + ["a quoted # before tee's file", "printf 'exit 0' | tee 'a #' node_modules/.bin/failproofai"], + ["a quoted < in an option value", 'cp /tmp/stub.sh --suffix "y < " node_modules/.bin/failproofai'], + ["a {fd} redirect after the destination", "cp /tmp/stub.sh node_modules/.bin/failproofai {fd}>/dev/null"], + ["an abbreviated option's value after the destination", "cp /dev/null ~/.failproofai/policies-config.json --suf x"], + ["an rsync option's value after the destination", "rsync /tmp/stub.sh node_modules/.bin/failproofai --max-delete 5"], + ["a .. that steps back into .bin", "cp /tmp/stub.sh node_modules/.bin/x/../failproofai"], + ])("denies %s", async (_label, command) => { + expect(await bash(command)).toBe("deny"); + }); + + // Paths built from what the same line assigns, and the shell's position + // carried through every way a shell moves it. + it.each([ + ["a variable holding the directory", "D=node_modules/.bin; cp /tmp/stub.sh $D/failproofai"], + ["a variable spliced into the state", "X=ai; rm -rf ~/.failproof$X"], + ["a variable holding npm's bin directory", "B=~/node_modules/.bin; ln -s /tmp/stage $B"], + ["a cd into a variable", "D=node_modules/.bin; cd $D && cp /tmp/stub.sh failproofai"], + ["$PWD after a cd", "cd node_modules/.bin && cp /tmp/stub.sh $PWD/failproofai"], + ["popd back to the directory", "pushd node_modules/.bin && pushd /tmp && popd && cp /tmp/stub.sh failproofai"], + ["cd - back to the directory", "cd node_modules/.bin && cd /tmp && cd - && cp /tmp/stub.sh failproofai"], + ["parentheses inside quotes", 'echo "(" && cd node_modules/.bin && echo ")" && cp /tmp/stub.sh failproofai'], + ["a directory named .bin moved into a node_modules", "mv /tmp/x/.bin ~/node_modules/"], + ["a glob of sources into the directory", "cp /tmp/stage/* node_modules/.bin/"], + ["a glob of sources after -t", "cp -t node_modules/.bin /tmp/stage/*"], + ["an abbreviated --recursive", "cp --rec /tmp/stage ~/node_modules/.bin"], + // A `popd` with nothing to return to fails and leaves the shell there. + ["a popd on an empty stack", "cd node_modules/.bin; popd; cp /tmp/stub.sh failproofai"], + ["$HOME spelled out", "cd $HOME/node_modules/.bin && cp /tmp/stub.sh failproofai"], + // A `cd` the walk cannot follow may land in npm's bin directory. + ["a cd into a command substitution", 'cd "$(npm root)/.bin" && cp /tmp/stub.sh failproofai'], + ["a redirect after a cd into a substitution", "cd $(npm root)/.bin && printf 'exit 0' > failproofai"], + ["a cd into backticks", "cd `npm root`/.bin && cp /tmp/stub.sh failproofai"], + ["a cd into a variable the line does not set", "cd $NODE_BIN && cp /tmp/stub.sh failproofai"], + ["a copy into . after a cd the walk cannot follow", 'cd "$(npm root)/.bin" && cp /tmp/stage/failproofai .'], + ])("denies %s", async (_label, command) => { + expect(await bash(command)).toBe("deny"); + }); + + // Shell moves the walk follows as bash makes them, so that none of them + // leaves the walk somewhere safer than the shell really is. + it.each([ + ["slashes after the directory", "cd ~/.failproofai//////////////////// && rm -rf *"], + ["slashes after npm's bin directory", "cd node_modules/.bin//////////////////// && printf 'exit 0' > failproofai"], + ["a redirect before the cd operand", "cd 2>/dev/null ~/.failproofai && rm -rf *"], + ["a popd with nothing to pop", "cd ~/.failproofai; popd; rm -rf *"], + ['cd ""', 'cd ~/.failproofai; cd ""; rm -rf *'], + ["cd - to an OLDPWD the line sets", "OLDPWD=~/.failproofai; cd -; rm -rf *"], + ["~- after a cd away", "cd ~/.failproofai && cd /tmp && rm -rf ~-/*"], + ["a bare cd to a HOME the line sets", "HOME=~/.failproofai; cd; rm -rf *"], + ["pushd +1 back onto the directory", "cd ~/.failproofai && pushd /tmp && pushd +1 && rm -rf *"], + ["a subshell's cd undone", "cd ~/.failproofai && (cd /tmp) && rm -rf *"], + ["an escaped parenthesis in a subshell", "cd ~/.failproofai && (echo \\) && cd /tmp) && rm -rf *"], + ["a cd into a substitution that names the state", 'cd "$(echo ~/.failproofai)" && rm -rf *'], + // An assignment the shell never makes (`:` is a no-op) cannot replace + // the value the walk judges: the word is judged as written too. + ["a decoy assignment before a copy", "D=~/.failproofai/policies-config.json; : D=x; cp /dev/null $D"], + ["a decoy assignment before a redirect", "D=~/.failproofai/policies-config.json; : D=x; echo {} > $D"], + // A complete option name is not an abbreviation of a longer one. + ["rsync --partial", "rsync --partial /tmp/stage/failproofai node_modules/.bin/"], + ["rsync --checksum", "rsync --checksum /tmp/stage/failproofai node_modules/.bin/"], + ["rsync -a --compress of a directory's contents", "rsync -a --compress /tmp/stage/ node_modules/.bin/"], + ["install --strip", "install --strip /tmp/stage/failproofai node_modules/.bin/"], + // A program handed to a shell is judged as the command it is. + ["bash -c around a copy", "bash -c 'cp /tmp/stub.sh node_modules/.bin/failproofai'"], + // A `cd` that fails leaves the shell where it was, and `;` runs the next + // command anyway. + ["a cd out of the state that may fail", "cd ~/.failproofai; cat config.json; cd /elsewhere; rm -rf *"], + // A `..` that climbs above the sixteen directories the walk reads from. + ["a climb above a deep cd", "cd node_modules/.bin && cd a/b/c/d/e/f/g/h/i/j/k/l/m/n/o/p/q && printf x > ../../../../../../../../../../../../../../../../../failproofai"], + // Symlinks the same line makes, before any `lstat` could see them. + ["a write through a link the line makes to the directory", "ln -s /work/proj/node_modules/.bin /tmp/bins && printf x > /tmp/bins/failproofai"], + ["a write through a link the line makes to the entry", "ln -s /work/proj/node_modules/.bin/failproofai /tmp/hook && printf x > /tmp/hook"], + // In a loop, an assignment later on the line can come first. + ["a loop that assigns the directory after the copy", 'while :; do cp /tmp/x "$D/failproofai"; D=/work/proj/node_modules/.bin; done'], + // Shim names spelled with a glob, as a destination and as a source. + ["a glob for npm's cmd shim", "cp /tmp/stub.cmd node_modules/.bin/failproofai.[c]md"], + ["a glob source for npm's cmd shim", "cp /tmp/stage/failproofai.[c]md node_modules/.bin/"], + ["moving a .bin directory given with a trailing slash", "mv /tmp/x/.bin/ ~/node_modules/"], + // A command word that is also an Object property name once threw inside + // the guard, and a policy that throws is skipped. + ["a command named like an Object method", "constructor -v; cp /tmp/x node_modules/.bin/failproofai"], + ["a command named __proto__", "__proto__ -v; rm -rf ~/.failproofai"], + ])("denies %s", async (_label, command) => { + expect(await bash(command)).toBe("deny"); + }); + + // The session's directory is where the command starts: a `cd` in an + // earlier call persists. + it.each([ + ["/work/proj/node_modules/.bin", "cp /tmp/stub.sh failproofai"], + ["/work/proj/node_modules/.bin", "printf 'exit 0' > failproofai"], + ["/work/proj/node_modules", "echo 'exit 0' >.bin/failproofai"], + ["/work/proj/node_modules", "printf x 2>.bin/failproofai"], + ["/work/proj/node_modules", "wget -q -O.bin/failproofai https://example.com/x"], + // The same path glued to the last option of a cluster, however long. + ["/work/proj/node_modules", "curl -so.bin/failproofai https://example.com/x"], + ["/work/proj/node_modules", `wget -${"q".repeat(40)}O.bin/failproofai https://example.com/x`], + ])("denies a write from the session directory %s: %s", async (cwd, command) => { + expect(await bashIn(cwd, command)).toBe("deny"); + }); + + // A move that can fail leaves the shell where it already was, and only + // `&&` makes the next command wait for it. + it.each([ + ["/work/proj/node_modules/.bin", "cd /nonexistent; printf x > failproofai"], + ["/work/proj/node_modules/.bin", "cd /tmp || true; cp /tmp/stub.sh failproofai"], + ["/work/proj/node_modules/.bin", "cd /tmp && true; printf x > failproofai"], + ["/work/proj/node_modules/.bin", "cd /a && cd /b; cp /tmp/stub.sh failproofai"], + ["/work/proj/node_modules/.bin/sub", "cd /tmp; cd ..; printf x > failproofai"], + ["/work/proj/node_modules/.bin", "cd /nonexistent; popd; printf x > failproofai"], + // `-n` changes the stack and leaves the shell where it is. + ["/work/proj/node_modules/.bin", "pushd -n /tmp; printf x > failproofai"], + ["/work/proj/node_modules/.bin", "popd -n; printf x > failproofai"], + ["/work/proj/node_modules/.bin", "cd a/b/c/d/e/f/g/h/i/j/k/l/m/n/o/p/q && cp /tmp/x ../../../../../../../../../../../../../../../../../failproofai"], + ["/work/proj", "ln -s node_modules/.bin bins; cp /tmp/stub.sh bins/failproofai"], + ["/work/proj", "ln -sfn node_modules/.bin bins && cp /tmp/failproofai bins/"], + // More possible directories than the walk tracks: the oldest is not + // forgotten, so a failed first cd still leaves the shell in .bin. + ["/work/proj/node_modules/.bin", "cd /a && cd /b && cd /c && cd /d && cd /e; printf x > failproofai"], + ["/work/proj/node_modules/.bin", "cd /a && cd /b && cd /c && cd /d && cd /e && cd /f && cd /g && cd /h && cd /i; printf x > failproofai"], + // `$PWD` and `~+` are wherever the shell may stand. + ["/work/proj/node_modules/.bin", 'cd /tmp; printf x > "$PWD/failproofai"'], + ["/work/proj/node_modules/.bin", "cd /tmp; cp /tmp/stub.sh ${PWD}/failproofai"], + ["/work/proj/node_modules/.bin", "cd /tmp; printf x > ~+/failproofai"], + ])("denies a write where the shell may still stand, from %s: %s", async (cwd, command) => { + expect(await bashIn(cwd, command)).toBe("deny"); + }); + + // A download names its file after the URL, so the line never spells the + // entry's path; scp and a remote rsync source copy like cp. + it.each([ + ["/work/proj/node_modules/.bin", "wget https://example.com/failproofai"], + ["/work/proj/node_modules/.bin", "wget -q example.com/dl/failproofai"], + ["/work/proj/node_modules/.bin", "curl -sSLO https://example.com/failproofai"], + ["/work/proj/node_modules/.bin", "curl -O https://example.com/failproofai%2Ecmd"], + // The server picks the name, or a file lists the URLs. + ["/work/proj/node_modules/.bin", "curl -OJ https://example.com/download"], + ["/work/proj/node_modules/.bin", "wget --content-disposition https://example.com/download"], + ["/work/proj/node_modules/.bin", "wget -i urls.txt"], + ["/work/proj/node_modules/.bin", "wget -r -nd https://example.com/dl/"], + ["/work/proj", "wget -P node_modules/.bin https://example.com/failproofai"], + ["/work/proj", "wget -qPnode_modules/.bin https://example.com/failproofai"], + ["/work/proj", "wget --directory-prefix=node_modules/.bin https://example.com/failproofai"], + ["/work/proj", "curl --output-dir node_modules/.bin -O https://example.com/failproofai"], + ["/work/proj", "cd node_modules/.bin && wget https://example.com/failproofai"], + ["/work/proj", "scp host:failproofai node_modules/.bin/"], + ["/work/proj", "scp -T user@host:/tmp/failproofai node_modules/.bin/"], + ["/work/proj", "rsync host:failproofai node_modules/.bin/"], + // An output file glued to its option, alone or after a cluster. + ["/work/proj", "curl -sonode_modules/.bin/failproofai https://example.com/x"], + ["/work/proj", "curl -so~/.failproofai/policies-config.json https://example.com/x"], + // A file `-o` names lands in `--output-dir` (found by hermes on + // FailproofAI/failproofai#1058). + ["/work/proj", "curl --output-dir node_modules/.bin -o failproofai https://example.com/x"], + ["/work/proj", "curl --output-dir=node_modules/.bin -sofailproofai https://example.com/x"], + ["/work/proj", "curl --output-dir node_modules/.bin --output failproofai https://example.com/x"], + // An absolute name is joined to it too, and each `--next` transfer keeps + // its own directory (found by hermes on FailproofAI/failproofai#1058). + ["/work/proj", "curl --output-dir node_modules/.bin -o /failproofai https://example.com/x"], + ["/work/proj", "curl --output-dir node_modules/.bin -O https://example.com/dl/failproofai --next --output-dir /tmp -O https://example.com/y"], + ["/work/proj", "curl -o /tmp/a https://example.com/a -: --output-dir node_modules/.bin -o failproofai https://example.com/b"], + ])("denies a download or remote copy from %s: %s", async (cwd, command) => { + expect(await bashIn(cwd, command)).toBe("deny"); + }); + + it.each([ + ["/work/proj", "wget https://example.com/failproofai"], + ["/work/proj/node_modules/.bin", "wget https://example.com/my-tool"], + ["/work/proj", "curl -O https://registry.npmjs.org/failproofai/-/failproofai-1.0.0.tgz"], + ["/work/proj/node_modules/.bin", "curl -o /tmp/x https://example.com/failproofai"], + ["/work/proj/node_modules/.bin", "curl https://example.com/failproofai"], + ["/work/proj/node_modules/.bin", "wget -r https://example.com/docs/"], + ["/work/proj", "curl -OJ https://example.com/download"], + ["/work/proj", "scp ./failproofai host:node_modules/.bin/"], + ["/work/proj", "scp -r host:project ./backup"], + ["/work/proj", "wget -qO- https://example.com/api | jq ."], + ])("allows a download or remote copy from %s: %s", async (cwd, command) => { + expect(await bashIn(cwd, command)).not.toBe("deny"); + }); + + // A value glued to its option is a path, read from where the shell stands + // like any other (found by hermes on FailproofAI/failproofai#1058). Where a + // command's value-taking letters are known the cluster is read as getopt + // reads it; elsewhere every split of it is tried. + it.each([ + ["/work/proj/node_modules/.bin", "curl -sofailproofai https://example.com/x"], + ["/work/proj/node_modules/.bin", "curl --output=failproofai https://example.com/x"], + ["/work/proj/node_modules/.bin", "wget -Ofailproofai https://example.com/x"], + ["/work/proj/node_modules/.bin", "wget -qOfailproofai https://example.com/x"], + ["/work/proj/node_modules/.bin", "wget --output-document=failproofai https://example.com/x"], + ["/work/proj/node_modules/.bin", "sort -ofailproofai notes.txt"], + ["/work/proj/node_modules/.bin", "gcc -ofailproofai main.c"], + ["/work/proj/node_modules/.bin", "tar -cffailproofai src"], + ["/work/proj/node_modules/.bin", "curl -" + "s".repeat(40) + "ofailproofai https://example.com/x"], + // A cluster longer than anyone writes is not tried at every split. + ["/work/proj/node_modules/.bin", "foo -" + "a".repeat(40) + "ofailproofai"], + ["/work/proj", "cd node_modules/.bin && curl -sofailproofai https://example.com/x"], + ["/work/proj", "D=failproofai; cd node_modules/.bin && curl -so$D https://example.com/x"], + ])("denies an output file glued to its option from %s: %s", async (cwd, command) => { + expect(await bashIn(cwd, command)).toBe("deny"); + }); + + // A file a sed script writes with `w`, `W` or the `w` flag of `s///`, + // glued on or after spaces (found by hermes on FailproofAI/failproofai#1058). + it.each([ + ["/work/proj", "sed -n 'w node_modules/.bin/failproofai' /tmp/stub.sh"], + ["/work/proj", "sed -n 'wnode_modules/.bin/failproofai' /tmp/stub.sh"], + ["/work/proj", "sed 's/a/b/wnode_modules/.bin/failproofai' /tmp/stub.sh"], + ["/work/proj", "sed -e 's/a/b/gw node_modules/.bin/failproofai' /tmp/stub.sh"], + ["/work/proj", "sed -n 'Wnode_modules/.bin/failproofai' /tmp/stub.sh"], + ["/work/proj", "sed -n --expression='w node_modules/failproofai/dist/cli.mjs' /tmp/stub.sh"], + ["/work/proj/node_modules/.bin", "sed -n 'wfailproofai' /tmp/stub.sh"], + ["/work/proj", "cd node_modules/.bin && sed -n 'wfailproofai' /tmp/stub.sh"], + // After an address, and in a script whose `;` is quoted text (found by + // hermes on FailproofAI/failproofai#1058). + ["/work/proj", "sed -n '1wnode_modules/.bin/failproofai' /tmp/stub.sh"], + ["/work/proj", "sed -n '10,20wnode_modules/.bin/failproofai' /tmp/stub.sh"], + ["/work/proj", "sed -n '$wnode_modules/.bin/failproofai' /tmp/stub.sh"], + ["/work/proj", "sed -n '1!wnode_modules/.bin/failproofai' /tmp/stub.sh"], + ["/work/proj/node_modules/.bin", "sed -e 's/w/x/;1wfailproofai' /tmp/stub.sh"], + ])("denies a sed script writing the entry from %s: %s", async (cwd, command) => { + expect(await bashIn(cwd, command)).toBe("deny"); + }); + + it.each([ + "sed -n 's/a/b/p' notes.txt", + "sed 's/raw/cooked/' notes.txt", + "sed -n 'w out.txt' notes.txt", + "sed -n '/failproofai/p' notes.txt", + "sed 's/www/web/g' urls.txt", + "sed -n 'w /tmp/copy.txt' node_modules/.bin/failproofai", + "sed -n '1w out.txt' notes.txt", + "sed -n 'bigwig' notes.txt", + "sed 's/new/old/g; s/a/b/' notes.txt", + ])("allows a sed script that writes no protected file: %s", async (command) => { + expect(await bashIn("/work/proj", command)).not.toBe("deny"); + }); + + // A value set only in a subshell, only for one command, or only if a test + // passes does not replace the one before it, so a word is read with every + // value the line gives its variables (found by hermes on + // FailproofAI/failproofai#1058). + it.each([ + ["/work/proj/node_modules/.bin", "F=failproofai; (F=x); printf y > $F"], + ["/work/proj/node_modules/.bin", "F=failproofai; F=x true; printf y > $F"], + ["/work/proj/node_modules/.bin", "F=failproofai; F=x env; cp /tmp/stub.sh $F"], + ["/work/proj/node_modules/.bin", Array.from({ length: 70 }, (_, i) => `F=v${i}`).join("; ") + "; F=failproofai; false && F=x; printf y > $F"], + ["/work/proj/node_modules/.bin", "F=failproofai; " + Array.from({ length: 70 }, (_, i) => `F=y${i} true`).join("; ") + "; printf y > $F"], + ["/work/proj", "D=node_modules/.bin; (D=/tmp); printf y > $D/failproofai"], + ["/work/proj", "D=node_modules/.bin; (D=/tmp); cp /tmp/stage/failproofai $D/"], + ["/work/proj/node_modules/.bin", "F=failproofai; F=x | true; printf y > $F"], + // Every combination of the values of the variables one word names + // (found by hermes on FailproofAI/failproofai#1058). + ["/work/proj", "A=fail; B=proofai; (A=x; B=y); printf x > node_modules/.bin/$A$B"], + ["/work/proj", "A=fail; B=proofai; A=x true; B=y true; printf x > node_modules/.bin/${A}${B}"], + ["/work/proj", "A=fa; B=il; C=proofai; (A=x; B=y; C=z); printf x > node_modules/.bin/$A$B$C"], + // More combinations than are tried is refused, not guessed at. + ["/work/proj", Array.from({ length: 13 }, (_, i) => `V${i}=a; V${i}=b`).join("; ") + "; printf x > " + Array.from({ length: 13 }, (_, i) => `$V${i}`).join("")], + ])("denies a write through a variable another value may hold, from %s: %s", async (cwd, command) => { + expect(await bashIn(cwd, command)).toBe("deny"); + }); + + it.each([ + ["/work/proj/node_modules/.bin", "F=a; F=b; printf y > $F"], + ["/work/proj", "D=dist; (D=build); rm -rf $D"], + ["/work/proj", "F=a; F=b; echo " + Array(2000).fill("$F/$F").join(" ")], + ["/work/proj", "A=a; A=b; B=c; B=d; printf x > $A$B"], + ["/work/proj", Array.from({ length: 12 }, (_, i) => `V${i}=a; V${i}=b`).join("; ") + "; printf x > " + Array.from({ length: 12 }, (_, i) => `$V${i}`).join("")], + ])("allows a reassigned variable that never reaches the entry, from %s: %s", async (cwd, command) => { + expect(await bashIn(cwd, command)).not.toBe("deny"); + }); + + it.each([ + ["/work/proj/node_modules/.bin", "curl -somy-tool https://example.com/x"], + ["/work/proj/node_modules/.bin", "grep -ffailproofai notes.txt"], + ["/work/proj", "gcc -O2 -Wall -o build/app main.c"], + ["/work/proj", "tar -czf backup.tgz src"], + ["/work/proj", "curl -sSfL -o /tmp/x https://example.com/x"], + ["/work/proj", "git log --format=%h -n 5"], + ])("allows option values from %s: %s", async (cwd, command) => { + expect(await bashIn(cwd, command)).not.toBe("deny"); + }); + + // `echo` and `printf` print quoted text and run none of it, so documenting + // a command is not running it (found by hermes on + // FailproofAI/failproofai#1058). Text a shell does run is still read as + // one, and so is a real redirect. + it.each([ + "echo 'cat > node_modules/.bin/failproofai'", + "printf '%s\\n' '> node_modules/.bin/failproofai'", + 'echo "cat > node_modules/.bin/failproofai"', + "echo 'cat > ~/.failproofai/policies-config.json'", + "echo 'never run: cat > node_modules/.bin/failproofai' && npm test", + // Escaped and ANSI-C quoted, to another descriptor or nowhere, through + // readers that only show it, and beside a subshell that is not around it. + "echo cat \\> node_modules/.bin/failproofai", + "echo $'cat > node_modules/.bin/failproofai\\n'", + "echo 'cat > node_modules/.bin/failproofai' >&2", + "echo 'cat > node_modules/.bin/failproofai' > /dev/null", + "echo 'cat > node_modules/.bin/failproofai' | cat", + "printf '%s\\n' 'cat > node_modules/.bin/failproofai' | grep cat | wc -l", + "(cd src && ls); echo 'cat > node_modules/.bin/failproofai'", + // Into a documentation file, when nothing on the line runs a file (found + // by hermes on FailproofAI/failproofai#1058). + "echo 'cat > node_modules/.bin/failproofai' >> docs/notes.md", + "printf '%s\\n' '> node_modules/.bin/failproofai' > docs/recipe.md", + "echo 'cat > node_modules/.bin/failproofai' | tee -a docs/notes.md", + "echo 'printf x > node_modules/.bin/failproofai' | tee /tmp/s.sh", + "echo 'printf x > node_modules/.bin/failproofai' | cat > /tmp/s.sh", + "echo 'cat > node_modules/.bin/failproofai'; echo done", + "echo 'cat > node_modules/.bin/failproofai' > docs/notes.md && git add docs/notes.md", + ])("allows printing a command as text: %s", async (command) => { + expect(await bash(command)).toBe("allow"); + }); + + it.each([ + "bash -c 'printf x > node_modules/.bin/failproofai'", + "echo 'printf x > node_modules/.bin/failproofai' | sh", + "echo 'printf x > node_modules/.bin/failproofai' |& sh", + "echo 'printf x > node_modules/.bin/failproofai' > /tmp/s.sh && sh /tmp/s.sh", + "printf -v c 'printf x > node_modules/.bin/failproofai'; eval \"$c\"", + "(echo 'printf x > node_modules/.bin/failproofai') | sh", + "{ echo 'printf x > node_modules/.bin/failproofai'; } | sh", + "xargs -I{} sh -c {} <<'EOF'\necho 'printf x > node_modules/.bin/failproofai'\nEOF", + "/tmp/bin/echo 'printf x > node_modules/.bin/failproofai'", + "echo 'exit 0' > node_modules/.bin/failproofai", + 'echo x >node_modules/.bin/fail"proof"ai', + // A reader that keeps it, a loop or condition piped into a shell, an + // `echo` the line redefines, the shell's own output sent to one, and a + // substitution, which runs. + "echo 'printf x > node_modules/.bin/failproofai' | grep x | sh", + // A file printed into, then run on the same line. + "echo 'printf x > node_modules/.bin/failproofai' > docs/s.sh && sh docs/s.sh", + "echo 'printf x > node_modules/.bin/failproofai' > s.sh; ./s.sh", + "echo 'printf x > node_modules/.bin/failproofai' | tee s.sh | sh", + "for i in 1; do\necho 'printf x > node_modules/.bin/failproofai'\ndone | sh", + "if true; then\necho 'printf x > node_modules/.bin/failproofai'\nfi | sh", + 'echo() { sh -c "$*"; }; echo \'printf x > node_modules/.bin/failproofai\'', + "alias echo='sh -c'\necho 'printf x > node_modules/.bin/failproofai'", + "exec > >(sh); echo 'printf x > node_modules/.bin/failproofai'", + "exec >/tmp/s.sh; echo 'printf x > node_modules/.bin/failproofai'; sh /tmp/s.sh", + 'echo "$(cat > node_modules/.bin/failproofai < /tmp/stub.sh)"', + // An interpreter spelled with quotes or an escape is still an + // interpreter, and so is one behind `time` or a variable (found by + // hermes on FailproofAI/failproofai#1058). + "echo 'printf x > .failproofai/policies-config.json' > notes; 'sh' notes", + "echo 'printf x > .failproofai/policies-config.json' > notes; \"sh\" notes", + "echo 'printf x > .failproofai/policies-config.json' > notes; s'h' notes", + "echo 'printf x > .failproofai/policies-config.json' > notes; \\sh notes", + "echo 'printf x > .failproofai/policies-config.json' > notes; time sh notes", + "echo 'printf x > .failproofai/policies-config.json' > notes; \"$SHELL\" notes", + ])("denies quoted text something runs, or a real redirect: %s", async (command) => { + expect(await bash(command)).toBe("deny"); + }); + + // Codex runs a command in the `workdir` its shell tool names, and its hook + // payload reports the session's directory only (found by hermes on + // FailproofAI/failproofai#1058). A relative destination that would plant + // the entry, were that directory npm's bin directory, is refused; nothing + // else is read differently. + it.each([ + "printf '#!/bin/sh\\nexit 0\\n' > failproofai", + "printf x >> ../../failproofai", + "cd src && printf x > ../failproofai", + "tee failproofai < /tmp/stub.sh", + "cp /tmp/stub.sh ./failproofai", + "cp /tmp/stage/failproofai .", + "mv /tmp/stub.sh failproofai.cmd", + "ln -s /tmp/stub.sh failproofai", + "curl -sofailproofai https://example.com/x", + "wget -O failproofai https://example.com/x", + "wget https://example.com/dl/failproofai", + "curl -OJ https://example.com/download", + "gcc -o failproofai main.c", + "dd if=/tmp/stub.sh of=failproofai", + "printf x > failproofai/dist/cli.mjs", + // Through a directory that may be a link where the command really runs. + "printf x > tbins/failproofai", + "printf x > x/y/failproofai.cmd", + "cp /tmp/stub.sh deps/failproofai/dist/cli.mjs", + "sed -n 'wfailproofai' /tmp/stub.sh", + "F=failproofai; (F=x); printf y > $F", + 'F=failproofai; F=x true; printf y > "$F"', + ])("denies a Codex command planting the entry wherever it runs: %s", async (command) => { + expect(await bashAs("codex", { command })).toBe("deny"); + }); + + it.each([ + "which failproofai", + "npm view failproofai version", + "rm -rf dist/*", + "twine upload dist/*", + "cat failproofai", + "printf x > src/failproofai.ts", + "cd /tmp && printf x > failproofai", + "printf x > tbins/notes.txt", + "printf x > docs/intro.md", + ])("allows a Codex command that plants nothing: %s", async (command) => { + expect(await bashAs("codex", { command })).toBe("allow"); + }); + + it("reads a Codex command from the workdir the call reports", async () => { + expect(await bashAs("codex", { command: "printf x > failproofai", workdir: "/work/proj/node_modules/.bin" })).toBe("deny"); + expect(await bashAs("codex", { command: "printf x > failproofai", workdir: "/work/proj/src" })).toBe("allow"); + }); + + it("reads other agents' commands from the session's directory", async () => { + expect(await bashAs("claude", { command: "printf x > failproofai" })).toBe("allow"); + expect(await bashAs(undefined, { command: "printf x > failproofai" })).toBe("allow"); + }); + + it.each([ + ["running another package's binary", "./node_modules/.bin/vitest run"], + ["running a binary through node", "node node_modules/.bin/eslint src"], + ["running a binary by its relative path", "node_modules/.bin/tsc --noEmit -p ."], + ["listing the directory", "ls -la node_modules/.bin"], + ["looking at the entry", "ls -l node_modules/.bin/failproofai"], + ["reading the entry", "cat node_modules/.bin/failproofai"], + ["resolving the entry", "readlink -f node_modules/.bin/failproofai"], + ["a clean reinstall", "rm -rf node_modules && npm ci"], + ["clearing every entry", "rm -rf node_modules/.bin/*"], + ["clearing every entry under an upper-case parent", "rm -rf NODE_MODULES/.BIN/*"], + ["installing dependencies", "npm install"], + ["adding a dev dependency", "npm i -D vitest"], + ["copying another tool into the directory", "cp /tmp/stage/my-tool node_modules/.bin/"], + ["copying an entry out", "cp node_modules/.bin/failproofai /tmp/inspect"], + ["copying an entry out into a directory", "cp node_modules/.bin/failproofai /tmp/inspect/"], + ["moving a source file", "mv src/failproofai.ts src/guard.ts"], + ["backing a directory up", "cp -r node_modules/.bin /tmp/bin-backup"], + ["backing the state up into a directory", "cp -r ~/.failproofai /tmp/backup/"], + ["backing the state up with a redirect", "cp ~/.failproofai/config.json /tmp/backup.json 2>/dev/null"], + ["reading the state with a redirect", "cat ~/.failproofai/config.json 2>/dev/null"], + // A value is not a source. + ["installing a binary owned by a user of that name", "install -o failproofai -g failproofai -m 0755 build/agentd /usr/local/bin/"], + ["creating directories owned by a user of that name", "install -d -o failproofai /srv/app/bin"], + // `.bin` starts a path component, or it is another name. + ["copying a file onto one whose name ends in .bin", "cp failproofai release.bin"], + ["running a binary after a cd", "cd node_modules/.bin && ./vitest run"], + ["a cd that a subshell undoes", "(cd node_modules/.bin && ls) && cp /tmp/stub.sh failproofai"], + ["copying a tool after a cd", "cd node_modules/.bin && cp /tmp/stage/my-tool ."], + ["clearing a tree's .bin directories", "rm -rf ~/projects/*/node_modules/.bin/*"], + // Somebody's own `~/.bin` is not npm's. + ["moving a tool into ~/.bin", "mv /tmp/tool ~/.bin/"], + ["linking a script into ~/.bin", "ln -s ~/dotfiles/scripts/deploy ~/.bin/"], + ["copying scripts into ~/.bin", "cp -r ./scripts/ ~/.bin/"], + ["syncing dotfiles into ~/.bin", "rsync -a dotfiles/bin/ ~/.bin/"], + ["moving a binary into a project's .bin", "mv golangci-lint .bin/"], + // `ln` cannot create a directory given a trailing `/`. + ["linking a package's CLI into node_modules/.bin/", "ln -s ../my-pkg/cli.js node_modules/.bin/"], + // A one-segment glob below another directory is not aimed at the state. + ["a glob ending in ai", "rm -rf models/*ai"], + ["a glob ending in i", "rm -f out/*i"], + ["a glob around proof", "rm -rf vendor/*proof*"], + ["a sed program that looks like a glob", "sed -i 's/.*ai/X/' notes.txt"], + ["a commit message with a #", "git commit -m 'fix #12: cp a b'"], + ["a loop copying files out", "for f in *.txt; do cp $f /tmp/; done"], + ["a cd and a build", "cd packages/api && npm run build"], + ["clearing a scratch directory", "cd /tmp && rm -rf *"], + // A `cd` the walk cannot follow changes nothing for ordinary names. + ["tests from the repository root", 'cd "$(git rev-parse --show-toplevel)" && npm test'], + ["a cleanup from the repository root", 'cd "$(git rev-parse --show-toplevel)" && rm -rf dist *.log'], + ["a note in a temporary directory", 'cd "$(mktemp -d)" && echo hi > notes.txt'], + ["a listing of home", "cd $HOME && ls -la"], + // Redirects and comments are not operands, and a comment line runs nothing. + ["a comment line that names the state", "# Look at ~/.failproofai\nls -la ~/.failproofai"], + ["reading the state through an input redirect", "uniq -c < ~/.failproofai/x.log | sort -rn"], + ["tee fed from the state", "tee -a /tmp/x < ~/.failproofai/policies-config.json"], + ["a backup with a comment naming the state", "cp -r ~/.failproofai /tmp/bak # copy of ~/.failproofai"], + ["a find whose comment names -delete", "find ~/.failproofai -name '*.log' -print # not -delete yet"], + ["a read run through bash -c", "bash -c 'cat ~/.failproofai/policies-config.json'"], + // rsync puts a source directory inside the destination; it does not + // become npm's bin directory. + ["syncing a directory into the bin directory", "rsync -a /tmp/my-tool node_modules/.bin/"], + // Outside a loop the shell reads a variable as it stands at that point. + ["a variable assigned only after its use", 'D=/tmp; cp notes.txt "$D/failproofai"; D=/work/proj/node_modules/.bin'], + // Each stage of a pipeline is a subshell, so its cd moves nothing after it. + ["a cd in a pipeline stage", "cd node_modules/.bin | true; cp notes.txt failproofai"], + // `cd -` and `popd` return to where the shell already stood. + ["a cd - back out of the state", "cd ~/.failproofai; cat config.json; cd -; rm -rf node_modules"], + ["leaving through a link to elsewhere", "ln -s /work/proj/dist current && rm -rf current/x"], + ])("allows %s", async (_label, command) => { + expect(await bash(command)).not.toBe("deny"); + }); + + it.each([ + // The session's own directory exists, so a cd back to it does not fail. + ["/work/proj", "cd ~/.failproofai; cat config.json; cd /work/proj; rm -rf node_modules"], + ["/work/proj", "cd frontend; npm install; cd ..; rm -rf node_modules"], + ["/work/proj", "cd /tmp; printf x > notes.txt"], + ["/work/proj", "cd node_modules/.bin && ls -la && cd ../.. && rm -rf build"], + ["/work/proj", "pushd /tmp && make && popd && rm -rf out"], + ["/work/proj", "cd a && cd b && cd c && cd d && cd e; rm -rf build"], + ["/work/proj", "cd a; make; cd ..; cd b; make; cd ..; cd c; make; cd ..; cd d; make; cd ..; cd e; make; cd ..; rm -rf dist"], + // After `&&` the cd has succeeded, so `$PWD` is where it went. + ["/work/proj/node_modules/.bin", 'cd /tmp && printf x > "$PWD/failproofai"'], + ])("allows ordinary moves from %s: %s", async (cwd, command) => { + expect(await bashIn(cwd, command)).not.toBe("deny"); + }); + + it.each([ + ["a checkout of failproofai itself", "/home/u/src/failproofai", "npm test"], + ["a checkout of failproofai itself", "/home/u/src/failproofai", "rm -rf dist"], + ["node_modules/.bin", "/work/proj/node_modules/.bin", "cp README.md /tmp/"], + ["node_modules/.bin", "/work/proj/node_modules/.bin", "./vitest run"], + // The command word is a program, not a path written to, and an option + // is not a path: neither is read from the directory. + ["failproofai's own state", "/home/u/.failproofai/logs", "date"], + ["failproofai's own state", "/home/u/.failproofai/logs", "uname -a"], + ["an installed package", "/home/u/proj/node_modules/failproofai/dist", "uname -a"], + ])("allows ordinary work from %s", async (_label, cwd, command) => { + expect(await bashIn(cwd, command)).not.toBe("deny"); + }); + + // The walk runs on every tool call, and one evaluation holds up every hook + // on the machine. A directory that grew with each `cd` made later words + // slower to judge without bound (28.9 s for the first input in review). + it.each([ + ["a script of 700 cd / build / cd ../.. steps", "bash <<'EOF'\n" + Array.from({ length: 700 }, (_, i) => `cd packages/pkg-${i}\nnpm run build\ncd ../..`).join("\n") + "\nEOF"], + ["2,000 relative cds", Array(2000).fill("cd a").join(" && ") + " && ls"], + ["1,000 cds into globs", Array(1000).fill("cd a*").join(" && ") + " && ls"], + // Each `;` keeps the directories a failed cd would leave the shell in. + ["2,000 cds that may each fail", Array(2000).fill("cd a").join("; ") + "; ls"], + ["2,000 cds into globs that may each fail", Array(2000).fill("cd a*").join("; ") + "; ls"], + [ + "1,000 links and a write through each", + Array.from({ length: 1000 }, (_, i) => `ln -s /tmp/t${i} /tmp/l${i}; printf x > /tmp/l${i}/f`).join("; "), + ], + ["a 2,000-segment glob", "rm -rf " + Array(2000).fill("*").join("/")], + // A value that refers to itself grew with every expansion pass. + ["a self-referring variable", "A=" + "$A".repeat(100) + "; echo $A"], + // The envelope's 128 KB field cap. A lookbehind that scanned back over a + // run of letters at every position took 16 s at 32 KB, and a long path + // walked on disk one component at a time took a second at 128 KB. + ["a 128 KB word of letters after a command", "find . -name '*.sqlite' -delete " + "x".repeat(128_000)], + ["a 128 KB run of option letters", "echo -" + "a".repeat(128_000)], + ["thirty long option clusters, each glued to .bin", "echo " + Array(30).fill("-" + "a".repeat(4_000) + ".bin/x").join(" ")], + ["a 128 KB run of letters ending in .bin", "echo -" + "a".repeat(128_000) + ".bin/failproofai.txt"], + ["a 128 KB path of one-letter directories", "echo " + "a/".repeat(64_000)], + [ + "thirty paths just under PATH_MAX", + "echo " + Array.from({ length: 30 }, (_, i) => `w${i}/` + "a/".repeat(2_040)).join(" "), + ], + ])("judges %s in bounded time", async (_label, command) => { + const started = performance.now(); + await bash(command); + expect(performance.now() - started).toBeLessThan(3000); + }); + + // From a directory on disk, where a glued value may be a link: one per + // letter of a long line's option words was a second of path walks. + it.each([ + ["128 KB of distinct option clusters, each with a value glued on", "foo " + optionClusters(3_700)], + ["curl with 128 KB of glued output files", "curl " + optionClusters(3_700).replaceAll(" -", " -so")], + ["a chain of 2,000 links made on the line", Array.from({ length: 2000 }, (_, i) => `ln -s l${i} l${i + 1}`).join("; ") + "; printf x > l2000/x"], + ["1,000 links put into a directory, each written through", Array.from({ length: 1000 }, (_, i) => `ln -s /tmp/t${i} out/; printf x > out/t${i}`).join("; ")], + ["128 KB of echo with quoted redirects", Array.from({ length: 6_000 }, (_, i) => `echo 'a > b${i}'`).join("; ")], + ])("judges %s from a directory on disk in bounded time", async (_label, command) => { + const started = performance.now(); + await bashIn(tmpdir(), command); + expect(performance.now() - started).toBeLessThan(3000); + }); + + it("judges a patch naming 7,000 files in bounded time", async () => { + const files = Array.from({ length: 7_000 }, (_, i) => `*** Add File: src/f${i}.ts\n+x`); + const started = performance.now(); + expect(await patch({ command: v4a(...files) }, tmpdir())).toBe("allow"); + expect(performance.now() - started).toBeLessThan(3000); + }); + }); + + // The guard protects the entry by NAME, so it has to be the name every + // project-scope hook hands npx. If an integration ever installs a different + // package or bin name, this fails instead of the guard silently protecting a + // file no hook runs. + it("protects the name every project-scope npx hook command runs", async () => { + const names = new Set(); + const viaNpx: string[] = []; + const otherwise: string[] = []; + const mixed: string[] = []; + for (const integration of listIntegrations()) { + if (!integration.scopes.includes("project")) continue; + // Every event's entry, not just one: an event launched some other way + // would be a hook the guard was never checked against. + const launched = integration.eventTypes.map((eventType) => { + const entry = JSON.stringify(integration.buildHookEntry("/opt/fp/bin/failproofai", eventType, "project")); + const found = [...entry.matchAll(/npx -y (\S+)/g)].map(([, name]) => name); + for (const name of found) names.add(name); + return found.length > 0; + }); + if (launched.every(Boolean)) viaNpx.push(integration.id); + else if (launched.some(Boolean)) mixed.push(integration.id); + else otherwise.push(integration.id); + } + expect(mixed).toEqual([]); + // A new integration, or a new launcher (`npx --yes`, `bunx`), lands in one + // of these lists and fails here until the guard is checked against it. + expect(viaNpx.sort()).toEqual(["antigravity", "claude", "codex", "copilot", "cursor", "devin", "factory", "goose"]); + // OpenCode runs npx from the shim checked below; Pi loads the extension by + // a package path, which runs the CLI next to it, not through npx. + expect(otherwise.sort()).toEqual(["opencode", "pi"]); + // OpenCode's entry is a plugin path; the npx call is inside the shim that + // install writes next to it. + const dir = mkdtempSync(join(tmpdir(), "fpai-npx-guard-opencode-")); + const cwd = vi.spyOn(process, "cwd").mockReturnValue(dir); + try { + listIntegrations() + .find((integration) => integration.id === "opencode")! + .writeHookEntries({}, "/opt/fp/bin/failproofai", "project"); + const shim = readFileSync(join(dir, ".opencode", "plugins", "failproofai.mjs"), "utf8"); + // The launcher and its arguments, tied to the same switch, so a shim that + // kept these arguments for another program would fail here. + expect(shim).toContain("const USE_NPX = true;"); + expect(shim).toMatch(/const cmd = USE_NPX \? "npx" :/); + const spawned = [...shim.matchAll(/USE_NPX\s*\?\s*\["-y", "([^"]+)"/g)].map(([, name]) => name); + expect(spawned.length).toBeGreaterThan(0); + for (const name of spawned) names.add(name); + } finally { + cwd.mockRestore(); + rmSync(dir, { recursive: true, force: true }); + } + expect([...names]).toEqual(["failproofai"]); + for (const name of names) { + expect((await write(`/work/proj/node_modules/.bin/${name}`)).decision).toBe("deny"); + expect(await bash(`cp /tmp/stub.sh node_modules/.bin/${name}`)).toBe("deny"); + } + }); +}); + +/** + * hermes's seventh review of FailproofAI/failproofai#1058, each reproduced with + * real bash, curl and wget in a scratch project first: a final-component glob + * over more names than the walk expanded (F7), variable values that reach a + * destination through another variable, an operator, or a `cd` (F11), and a + * long option cut short (`--output-di`), which curl before 8 and every + * getopt_long tool take. Alongside, the same paths through a sweep of npm's + * bin directory, a link made earlier on the line, a loop, the builtins that set + * a variable without `=`, and a sed script read from a file. + */ +describe("block-failproofai-commands — hermes's seventh round", () => { + let root: string; + let proj: string; + + beforeAll(() => { + root = mkdtempSync(join(tmpdir(), "fpai-npx-round7-")); + proj = join(root, "proj"); + mkdirSync(join(proj, "node_modules", ".bin"), { recursive: true }); + mkdirSync(join(proj, "out")); + mkdirSync(join(proj, "many")); + writeFileSync(join(proj, "node_modules", ".bin", "failproofai"), "#!/bin/sh\n"); + symlinkSync(join(proj, "node_modules", ".bin"), join(proj, "bins")); + symlinkSync(join(proj, "node_modules", ".bin", "failproofai"), join(proj, "hook")); + // More plain names than a glob was expanded to, and one link among them. + for (let i = 0; i < 4200; i++) writeFileSync(join(proj, "many", `a${String(i).padStart(4, "0")}`), ""); + symlinkSync(join(proj, "node_modules", ".bin", "failproofai"), join(proj, "many", "hook")); + writeFileSync(join(proj, "writes.sed"), "w hook\n"); + writeFileSync(join(proj, "prints.sed"), "p\n"); + writeFileSync(join(proj, "out", "a.txt"), ""); + const diff = (path: string) => `--- a/${path}\n+++ b/${path}\n@@ -1 +1 @@\n-#!/bin/sh\n+exit 0\n`; + writeFileSync(join(proj, "entry.patch"), diff("node_modules/.bin/failproofai")); + writeFileSync(join(proj, "links.patch"), diff("bins/failproofai")); + writeFileSync(join(proj, "app.patch"), diff("src/app.ts")); + writeFileSync(join(proj, "output.cfg"), "silent\noutput = hook\n"); + writeFileSync(join(proj, "landing.cfg"), "output-dir = bins\nremote-name\n"); + writeFileSync(join(proj, "quiet.cfg"), "# just quiet\nsilent\n"); + }); + + afterAll(() => { + rmSync(root, { recursive: true, force: true }); + }); + + it.each([ + // F7: past 4096 plain names, the link among them still counts. + "tee many/* < /tmp/stub.sh", + "cat /tmp/stub.sh | tee many/?*", + "cd many && tee * < /tmp/stub.sh", + "for f in many/*; do cat /tmp/stub.sh > \"$f\"; done", + // A write that sweeps npm's bin directory writes the entry in it. + "tee bins/* < /tmp/stub.sh", + "tee node_modules/.bin/* < /tmp/stub.sh", + "cp /tmp/stub.sh node_modules/.bin/*", + // A glob reads the links this line made before it. + "ln -s ../node_modules/.bin out/b && cp /tmp/stub.sh out/b*/failproofai", + "ln -s ../node_modules/.bin out/b && cd out/b* && printf x > failproofai", + ])("denies a glob that writes the entry: %s", async (command) => { + expect(await bashIn(proj, command)).toBe("deny"); + }); + + it.each([ + // F11: a value through another variable, read when it is assigned. + "A=bins; (A=out); B=$A; cp /tmp/stub.sh $B/failproofai", + "A=bins; A=out true; B=$A; cp /tmp/stub.sh $B/failproofai", + "A=bins; (A=out); B=${A}; cp /tmp/stub.sh ${B}/failproofai", + "N=fail; M=${N}proofai; (N=x); printf x > bins/$M", + // A `cd` to each value the operand may hold. + "D=bins; (D=out); cd $D && printf x > failproofai", + "D=bins; D=out true; cd \"${D}\" && printf x > failproofai", + "D=bins; (D=out); pushd $D > /dev/null && printf x > failproofai", + "export D=bins; (D=out); cd $D; printf x > failproofai", + // Operators as bash applies them. + "D=bins; cd ${D%/} && printf x > failproofai", + "D=out; cp /tmp/stub.sh ${D/out/bins}/failproofai", + "cp /tmp/stub.sh ${X:-bins}/failproofai", + "N=D; D=bins; cp /tmp/stub.sh ${!N}/failproofai", + // Values set without `=`, and ones the walk cannot read. + "D=bins; declare -n R=D; cp /tmp/stub.sh $R/failproofai", + "read D <<< bins; cp /tmp/stub.sh $D/failproofai", + "printf -v D bins; cp /tmp/stub.sh $D/failproofai", + "for d in out bins; do cp /tmp/stub.sh $d/failproofai; done", + "for n in x failproofai; do printf x > bins/$n; done", + "D=$(echo bins); cp /tmp/stub.sh $D/failproofai", + "D=`echo bins`; cp /tmp/stub.sh $D/failproofai", + ])("denies a variable that carries the write onto the entry: %s", async (command) => { + expect(await bashIn(proj, command)).toBe("deny"); + }); + + it.each([ + // A long option cut short, as curl before 8 and getopt_long take it. + "curl -s --output-di bins -O https://example.test/failproofai", + "curl -s --output-d node_modules/.bin --remote-name https://example.test/failproofai", + "curl -s --output-dir bins --remote-name-a https://example.test/failproofai", + "curl -s --output-dir out -O https://example.test/x --nex --output-di bins -O https://example.test/failproofai", + "wget -q --directory-p=bins https://example.test/failproofai", + "wget -q --dir bins https://example.test/failproofai", + // The names wget gives that are not the URL's last segment. + "cd bins && wget -q --default-page=failproofai https://example.test/", + "wget -q -P bins --default-p=failproofai https://example.test/", + "wget -q -e dir_prefix=bins https://example.test/failproofai", + "cd bins && wget -q --trust-server-names https://example.test/x", + // The other files curl writes. + "curl -s --stderr hook -o /dev/null https://example.test/x", + "curl -s --stde hook -o /dev/null https://example.test/x", + "curl -s -c hook https://example.test/x", + "curl -s --cookie-j hook https://example.test/x", + ])("denies a download option that lands on the entry: %s", async (command) => { + expect(await bashIn(proj, command)).toBe("deny"); + }); + + it.each([ + "sed -n -f writes.sed /tmp/notes", + "sed -n --file=writes.sed /tmp/notes", + "sed -nf writes.sed /tmp/notes", + "sed -n -f missing.sed /tmp/notes", + ])("denies a sed script file that writes the entry, or one it cannot read: %s", async (command) => { + expect(await bashIn(proj, command)).toBe("deny"); + }); + + it.each([ + // An archive extracted into npm's bin directory. + "tar -xf /tmp/stub.tar -C bins", + "tar --extract --file=/tmp/stub.tar --directory=node_modules/.bin", + "cd bins && tar -xzf /tmp/stub.tgz", + "unzip -o /tmp/stub.zip -d bins", + // A patch file that names the entry, directly or through a link. + "patch -p1 < entry.patch", + "patch -p1 -i links.patch", + "git apply entry.patch", + "git -C . apply links.patch", + "cat entry.patch | patch -p1", + "patch -p1 < missing.patch", + // A curl config read onto the line. + "curl -K output.cfg https://example.test/x", + "curl --config landing.cfg https://example.test/failproofai", + "curl -sK missing.cfg https://example.test/x", + ])("denies an archive, patch or config that writes the entry: %s", async (command) => { + expect(await bashIn(proj, command)).toBe("deny"); + }); + + it.each([ + "rm -rf node_modules/.bin/*", + "tar -xf /tmp/stub.tar -C out", + "tar -czf out/backup.tgz node_modules", + "patch -p1 < app.patch", + "git apply app.patch", + "curl -K quiet.cfg https://example.test/x -o out/x", + "ls many/* > /dev/null", + "wc -l many/* > out/counts", + "for f in out/*.txt; do cp \"$f\" \"$f.bak\"; done", + "for f in many/a000*; do cat \"$f\" > /dev/null; done", + "D=out; cp /tmp/stub.sh ${D}/notes", + "D=out/; cp /tmp/stub.sh ${D%/}/x", + "OUT=out/log.txt; echo hi > \"$OUT\"", + "cp /tmp/stub.sh ${X:-out}/notes", + "read D <<< out; cp /tmp/stub.sh $D/notes", + "cd out && curl -sO https://example.test/failproofai/my-tool", + "curl -s --cookie hook https://example.test/x", + "sed -n -f prints.sed /tmp/notes > out/x", + "cd out && wget -q --default-page=index.txt https://example.test/", + ])("still allows: %s", async (command) => { + expect(await bashIn(proj, command)).toBe("allow"); + }); + + // F13: curl's `-O` takes no value, so the URL after it is no file name, and + // a download from a directory Codex does not report lands by the URL's last + // segment, `my-tool` here. + it.each([ + "cd out && curl -sO http://host/failproofai/my-tool", + "cd out && curl -s -O http://host/failproofai/my-tool", + "cd out && curl -sSLO http://host/failproofai/my-tool", + ])("allows a Codex download whose URL only passes through a failproofai directory: %s", async (command) => { + expect(await bashAs("codex", { command })).toBe("allow"); + }); + + it.each([ + "curl -sD failproofai http://host/x", + "curl -s --stderr failproofai http://host/x", + "curl -so failproofai http://host/x", + ])("denies a Codex download that names the entry as a file curl writes: %s", async (command) => { + expect(await bashAs("codex", { command })).toBe("deny"); + }); +}); + +// Found end to end on macOS, whose default shell is zsh: Claude Code runs the +// agent's command there, `**/` recurses with no option, and `setopt globdots` +// lets `*` match `.bin`. +describe("block-failproofai-commands — globs read the way zsh expands them", () => { + let root: string; + let proj: string; + + beforeAll(() => { + root = mkdtempSync(join(tmpdir(), "fpai-zsh-glob-")); + proj = join(root, "proj"); + mkdirSync(join(proj, "node_modules", ".bin"), { recursive: true }); + mkdirSync(join(proj, "deep", "a", "b"), { recursive: true }); + mkdirSync(join(proj, "src", "lib"), { recursive: true }); + symlinkSync(join(proj, "node_modules", ".bin", "failproofai"), join(proj, "deep", "a", "b", "hook")); + }); + + afterAll(() => { + rmSync(root, { recursive: true, force: true }); + }); + + it.each([ + "cp /tmp/stub.sh deep/**/hook", + "cp /tmp/stub.sh deep/***/hook", + "setopt globdots; cp /tmp/stub.sh node_modules/*/failproofai", + "setopt GLOB_DOTS; cp /tmp/stub.sh node_modules/*/failproofai", + "setopt extendedglob; cp /tmp/stub.sh deep/a/b/(#i)HOOK", + ])("denies %s", async (command) => { + expect(await bashIn(proj, command)).toBe("deny"); + }); + + it("still allows a recursive cleanup in a tree with more directories than one glob component reads", async () => { + for (let i = 0; i < 1100; i++) mkdirSync(join(proj, "src", "many", `d${i}`), { recursive: true }); + expect(await bashIn(proj, "rm -rf **/*.log")).toBe("allow"); + }); + + it.each(["rm -f src/**/*.orig", "rm -rf **/__pycache__", "cp /tmp/stub.sh node_modules/*/notes"])( + "still allows %s", + async (command) => { + expect(await bashIn(proj, command)).toBe("allow"); + }, + ); +}); + +// hermes's eighth round on 52c478da: each wrote the entry for real with +// GNU tar, curl and bash while the guard allowed it. +describe("block-failproofai-commands — option clusters, nested configs and operators, round eight", () => { + let root: string; + let proj: string; + + beforeAll(() => { + root = mkdtempSync(join(tmpdir(), "fpai-round8-")); + proj = join(root, "proj"); + mkdirSync(join(proj, "node_modules", ".bin"), { recursive: true }); + mkdirSync(join(proj, "long"), { recursive: true }); + const entry = join(proj, "node_modules", ".bin", "failproofai"); + symlinkSync(entry, join(proj, "hook")); + symlinkSync(entry, join(proj, "long", "hook")); + symlinkSync(join(proj, "node_modules", ".bin"), join(proj, "bins")); + writeFileSync(join(proj, "inner.cfg"), "url = http://127.0.0.1/failproofai\noutput = hook\n"); + writeFileSync(join(proj, "outer.cfg"), "config = inner.cfg\n"); + writeFileSync(join(proj, "outer2.cfg"), "-K outer.cfg\n"); + writeFileSync(join(proj, "plain.cfg"), "url = http://127.0.0.1/x\noutput = notes.txt\n"); + writeFileSync(join(proj, "loop.cfg"), "config = loop.cfg\n"); + }); + + afterAll(() => { + rmSync(root, { recursive: true, force: true }); + }); + + it.each([ + ["a curl -K glued at the end of a cluster", "curl -sKinner.cfg"], + ["a curl -K glued with more flags before it", "curl -fsSLKinner.cfg"], + ["a config naming another", "curl -s -K outer.cfg"], + ["a config naming another as -K", "curl -s --config outer2.cfg"], + ["configs that name each other forever", "curl -s -K loop.cfg"], + ["tar's -C glued to its directory", "tar -xf stub.tar -Cbins"], + ["tar's -f glued to its archive", "tar -xfstub.tar -C bins"], + ["tar's -C glued after other flags", "tar -xvzf stub.tgz -Cbins"], + ["the longest suffix removed", "A=long/out/x; cp stub ${A%%/*}/hook"], + ["printf -v reusing its format", "printf -v D '%s' ho ok; cp stub $D"], + ])("denies %s", async (_label, command) => { + expect(await bashIn(proj, command)).toBe("deny"); + }); + + it.each([ + "curl -s -K plain.cfg", + "curl -oK http://127.0.0.1/x", + "tar -xf stub.tar -Cout", + "tar -xfstub.tar", + "A=long/out/x; cp stub ${A%/*}/notes", + "printf -v D '%s' a b; cp stub out/$D", + ])("still allows %s", async (command) => { + expect(await bashIn(proj, command)).toBe("allow"); + }); +}); + +// hermes's ninth round on e0d88d81. +describe("block-failproofai-commands — printf conversions and tar's -C order, round nine", () => { + let root: string; + let proj: string; + + beforeAll(() => { + root = mkdtempSync(join(tmpdir(), "fpai-round9-")); + proj = join(root, "proj"); + mkdirSync(join(proj, "node_modules", ".bin"), { recursive: true }); + mkdirSync(join(proj, "out"), { recursive: true }); + const entry = join(proj, "node_modules", ".bin", "failproofai"); + symlinkSync(entry, join(proj, "16")); + symlinkSync(entry, join(proj, "8")); + symlinkSync(entry, join(proj, "ff")); + // Named after what bash prints, so a deny below means the guard computed the same. + for (const name of ["3.1", "1.600000e+01", "1.23457e+06", "3.14", "0.0001"]) symlinkSync(entry, join(proj, name)); + symlinkSync(join(proj, "node_modules", ".bin"), join(proj, "bins")); + }); + + afterAll(() => { + rmSync(root, { recursive: true, force: true }); + }); + + it.each([ + ["a hexadecimal %d", "printf -v D '%d' 0x10; cp stub $D"], + ["an octal %d", "printf -v D '%d' 010; cp stub $D"], + ["%i", "printf -v D '%i' 0x10; cp stub $D"], + ["%x", "printf -v D '%x' 255; cp stub $D"], + ["%u of a hexadecimal", "printf -v D '%u' 0x10; cp stub $D"], + ["a width this does not compute", "printf -v D '%2d' 16; cp stub $D"], + // hermes on db411090: bash assigns the valid prefix of a bad number, and floats. + ["the prefix of an invalid number", "printf -v D '%d' 16junk; cp stub $D"], + ["%.0f", "printf -v D '%.0f' 16; cp stub $D"], + ["%.1f", "printf -v D '%.1f' 3.14159; cp stub $D"], + ["%e", "printf -v D '%e' 16; cp stub $D"], + ["%g of a whole number", "printf -v D '%g' 16; cp stub $D"], + ["%g in exponent form", "printf -v D '%g' 1234567; cp stub $D"], + ["%g of a small number", "printf -v D '%g' 0.0001; cp stub $D"], + ["a padded %f, split into words", "printf -v D '%5.2f' 3.14159; cp stub $D"], + ["tar extracting one member into an earlier -C", 'tar -xfstub.tar -C bins failproofai -C "$PWD/out" other'], + ["tar's -C relative to the one before it", "tar -xf stub.tar -C node_modules -C .bin"], + ["tar's --directory before another -C", "tar -x -f stub.tar --directory=bins failproofai -C out x"], + ])("denies %s", async (_label, command) => { + expect(await bashIn(proj, command)).toBe("deny"); + }); + + it.each([ + "printf -v D '%d' 42; cp stub out/$D", + "printf -v N '%03d' 7; echo $N", + "tar -xf stub.tar -C out a -C out b", + ])("still allows %s", async (command) => { + expect(await bashIn(proj, command)).toBe("allow"); + }); +}); diff --git a/__tests__/hooks/guard-openclaw-apply-patch.test.ts b/__tests__/hooks/guard-openclaw-apply-patch.test.ts new file mode 100644 index 000000000..fe203a63c --- /dev/null +++ b/__tests__/hooks/guard-openclaw-apply-patch.test.ts @@ -0,0 +1,43 @@ +// @vitest-environment node +import { beforeEach, describe, expect, it } from "vitest"; +import { registerBuiltinPolicies } from "../../src/hooks/builtin-policies"; +import { evaluatePolicies } from "../../src/hooks/policy-evaluator"; +import { clearPolicies } from "../../src/hooks/policy-registry"; + +/** + * OpenClaw passes its own `apply_patch` tool to policies under that name, + * uncanonicalized, where Codex's arrives as `Edit`. The always-on guard matched + * only Bash and the file tools, so an OpenClaw patch that planted + * `node_modules/.bin/failproofai`, or rewrote failproofai's state, never + * reached it (FailproofAI/failproofai#1058). This runs the guard the way the + * handler does: registered from its catalog matcher, then evaluated. + */ +describe("block-failproofai-commands — OpenClaw's native apply_patch", () => { + beforeEach(() => { + clearPolicies(); + registerBuiltinPolicies([]); + }); + + const patchOf = (...lines: string[]) => ["*** Begin Patch", ...lines, "*** End Patch", ""].join("\n"); + const evaluate = (toolInput: Record) => + evaluatePolicies( + "PreToolUse", + { tool_name: "apply_patch", tool_input: toolInput, cwd: "/work/proj" }, + { cli: "openclaw", cwd: "/work/proj" }, + ); + + it.each([ + ["adding the npx entry", { input: patchOf("*** Add File: node_modules/.bin/failproofai", "+exit 0") }], + ["rewriting the state", { input: patchOf("*** Update File: /home/u/.failproofai/policies-config.json", "@@", "+{}") }], + ["rewriting the installed package", { patch: patchOf("*** Update File: node_modules/failproofai/dist/cli.mjs", "@@", "+exit 0") }], + ])("denies a patch %s", async (_label, toolInput) => { + const result = await evaluate(toolInput); + expect(result.decision).toBe("deny"); + expect(result.policyName).toBe("failproofai/block-failproofai-commands"); + }); + + it("allows a patch to project files", async () => { + const result = await evaluate({ input: patchOf("*** Update File: src/app.ts", "@@", "-a", "+b") }); + expect(result.decision).toBe("allow"); + }); +}); diff --git a/__tests__/hooks/help-index.test.ts b/__tests__/hooks/help-index.test.ts index 9b1baae78..aedca4dca 100644 --- a/__tests__/hooks/help-index.test.ts +++ b/__tests__/hooks/help-index.test.ts @@ -24,7 +24,7 @@ import { join, resolve } from "node:path"; const BINARY = resolve(__dirname, "..", "..", "bin", "failproofai.mjs"); /** The redesign's index, with room for a row or two more — not a second screen's worth. */ -const MAX_LINES = 36; +const MAX_LINES = 37; // +1: the Self Reports row (self-report) const MAX_COLUMNS = 80; const HEADINGS = ["GET STARTED", "SET UP", "ENFORCE", "OBSERVE", "LESS OFTEN", "EXAMPLES"]; diff --git a/__tests__/hooks/hermes-update.test.ts b/__tests__/hooks/hermes-update.test.ts index 75c7cd94f..a6ff652e2 100644 --- a/__tests__/hooks/hermes-update.test.ts +++ b/__tests__/hooks/hermes-update.test.ts @@ -36,7 +36,7 @@ import { runHermesUpdateMigration } from "../../src/hooks/hermes-update"; import { FAILPROOFAI_HOOK_MARKER } from "../../src/hooks/types"; const ORIG_CWD = process.cwd(); -const PLUGIN_FILES = ["plugin.yaml", "__init__.py", "client.py", "ledger.py"]; +const PLUGIN_FILES = ["plugin.yaml", "__init__.py", "client.py", "ledger.py", "self_report.py"]; let tempDir: string; let packageRoot: string; @@ -158,7 +158,7 @@ describe("linked Hermes plugin install", () => { // plugin.yaml says name: failproofai. Neither is proof of ownership. const lookalike = resolve(tempDir, "vendor", "hermes-plugin"); mkdirSync(lookalike, { recursive: true }); - for (const f of ["plugin.yaml", "__init__.py", "client.py", "ledger.py"]) { + for (const f of ["plugin.yaml", "__init__.py", "client.py", "ledger.py", "self_report.py"]) { writeFileSync(resolve(lookalike, f), f === "plugin.yaml" ? "name: failproofai\n" : "# not ours\n"); } mkdirSync(resolve(home(), "plugins"), { recursive: true }); @@ -174,7 +174,7 @@ describe("linked Hermes plugin install", () => { const pkg = resolve(tempDir, "prefix", "lib", "node_modules", "failproofai"); mkdirSync(resolve(pkg, "hermes-plugin"), { recursive: true }); writeFileSync(resolve(pkg, "package.json"), JSON.stringify({ name: "failproofai", version: "1.0.9-beta.1" })); - for (const f of ["plugin.yaml", "__init__.py", "client.py", "ledger.py"]) { + for (const f of ["plugin.yaml", "__init__.py", "client.py", "ledger.py", "self_report.py"]) { writeFileSync(resolve(pkg, "hermes-plugin", f), f === "plugin.yaml" ? "name: failproofai\n" : "#\n"); } mkdirSync(resolve(home(), "plugins"), { recursive: true }); diff --git a/__tests__/hooks/integrations.test.ts b/__tests__/hooks/integrations.test.ts index 46038bd89..828d2b6b7 100644 --- a/__tests__/hooks/integrations.test.ts +++ b/__tests__/hooks/integrations.test.ts @@ -631,7 +631,7 @@ describe("Hermes integration", () => { /** What a 1.0.6–1.0.8 install left behind: a marked COPY of the plugin. */ function makeManagedCopy(destination: string): void { mkdirSync(destination, { recursive: true }); - for (const file of ["plugin.yaml", "__init__.py", "client.py", "ledger.py"]) { + for (const file of ["plugin.yaml", "__init__.py", "client.py", "ledger.py", "self_report.py"]) { cpSync(resolve(ORIG_CWD, "hermes-plugin", file), resolve(destination, file)); } writeFileSync(resolve(destination, ".failproofai-managed"), "Managed by failproofai.\n"); @@ -685,7 +685,7 @@ describe("Hermes integration", () => { const installedPlugin = pluginPath(path); expect(lstatSync(installedPlugin).isSymbolicLink()).toBe(true); expect(readlinkSync(installedPlugin)).toBe(resolve(packageRoot, "hermes-plugin")); - for (const file of ["plugin.yaml", "__init__.py", "client.py", "ledger.py"]) { + for (const file of ["plugin.yaml", "__init__.py", "client.py", "ledger.py", "self_report.py"]) { expect(existsSync(resolve(installedPlugin, file))).toBe(true); } expect(hermesProfileHealth()[0]).toMatchObject({ pluginMode: "link", healthy: true, cronUnchecked: false }); diff --git a/__tests__/hooks/manager.test.ts b/__tests__/hooks/manager.test.ts index cc52e8bb7..6aa2c4442 100644 --- a/__tests__/hooks/manager.test.ts +++ b/__tests__/hooks/manager.test.ts @@ -90,6 +90,15 @@ const USER_SETTINGS_PATH = resolve(homedir(), ".claude", "settings.json"); const PROJECT_SETTINGS_PATH = resolve(process.cwd(), ".claude", "settings.json"); const LOCAL_SETTINGS_PATH = resolve(process.cwd(), ".claude", "settings.local.json"); +// Self Reports MCP registration has its own suite (self-report-install.test.ts); +// here only the calls into it are checked. +vi.mock("../../src/hooks/self-report-install", () => ({ + syncSelfReportMcp: vi.fn(() => []), + removeSelfReportMcp: vi.fn(() => []), + selfReportSyncLines: vi.fn(() => []), + selfReportSummary: vi.fn(() => null), +})); + describe("hooks/manager", () => { beforeEach(() => { vi.resetAllMocks(); @@ -173,6 +182,33 @@ describe("hooks/manager", () => { } }); + it("syncs the Self Reports MCP server for the agents it just hooked, with the hooks' binary", async () => { + vi.mocked(existsSync).mockReturnValue(true); + vi.mocked(readFileSync).mockReturnValue("{}"); + const sr = await import("../../src/hooks/self-report-install"); + + const { installHooks } = await import("../../src/hooks/manager"); + await installHooks(); + + expect(sr.syncSelfReportMcp).toHaveBeenCalledWith({ + quiet: true, + alsoHooked: ["claude"], + binaryPath: "/usr/local/bin/failproofai", + }); + }); + + it("a project-scope install never touches the agents' user-wide MCP configs", async () => { + vi.mocked(existsSync).mockReturnValue(true); + vi.mocked(readFileSync).mockReturnValue("{}"); + const sr = await import("../../src/hooks/self-report-install"); + vi.mocked(sr.syncSelfReportMcp).mockClear(); + + const { installHooks } = await import("../../src/hooks/manager"); + await installHooks(undefined, "project", "/tmp/some-project"); + + expect(sr.syncSelfReportMcp).not.toHaveBeenCalled(); + }); + // `--install` with no names WIRES HOOKS. It does not choose policies, and // it used to: a second picker opened here over BUILTIN_POLICIES — the // compiled catalog, which is not how policies arrive any more — and wrote @@ -824,6 +860,22 @@ describe("hooks/manager", () => { }); describe("removeHooks", () => { + it("removes the Self Reports MCP server for the agents whose user-scope hooks go", async () => { + vi.mocked(existsSync).mockReturnValue(false); + const sr = await import("../../src/hooks/self-report-install"); + const { removeHooks } = await import("../../src/hooks/manager"); + + await removeHooks(undefined, "all", undefined, { cli: ["claude", "codex"] }); + expect(sr.removeSelfReportMcp).toHaveBeenCalledWith({ agents: ["claude", "codex"], quiet: true }); + + vi.mocked(sr.removeSelfReportMcp).mockClear(); + await removeHooks(undefined, "project", undefined, { cli: ["claude"] }); + expect(sr.removeSelfReportMcp).not.toHaveBeenCalled(); + + await removeHooks(["block-sudo"], "user", undefined, { cli: ["claude"] }); + expect(sr.removeSelfReportMcp).not.toHaveBeenCalled(); + }); + it("removes only failproofai hooks, preserving others", async () => { vi.mocked(existsSync).mockReturnValue(true); const settings = { diff --git a/__tests__/hooks/openclaw-self-report.test.ts b/__tests__/hooks/openclaw-self-report.test.ts new file mode 100644 index 000000000..7d0ca199c --- /dev/null +++ b/__tests__/hooks/openclaw-self-report.test.ts @@ -0,0 +1,133 @@ +// @vitest-environment node +import { afterEach, describe, expect, it, vi } from "vitest"; +import { createServer, type Server } from "node:net"; +import { mkdtempSync, readFileSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import { + SELF_REPORT_OPENCLAW_TOOL, + callSelfReportTool, + discoverSelfReportTool, + pingSelfReportServer, + prepareSelfReportArguments, + registerSelfReportTool, +} from "../../openclaw-plugin/self-report.js"; +import { isSelfReportToolName } from "../../src/hooks/self-report-names"; + +const SERVER = { instanceId: "inst-1", port: 4319 }; +const SCHEMA = { type: "object", properties: { category: { type: "string" }, detail: { type: "string" } } }; + +function fakeFetch(calls: Array<{ url: string; body: Record }>, opts: { instance?: string; tools?: unknown[] } = {}) { + return vi.fn(async (url: unknown, init?: { body?: unknown }) => { + const body = JSON.parse(String(init?.body)) as Record; + calls.push({ url: String(url), body }); + const reply = + body.method === "initialize" + ? { result: { serverInfo: { name: "failproofai_local", instanceId: opts.instance ?? "inst-1" }, instructions: "Report when stuck." } } + : body.method === "tools/list" + ? { result: { tools: opts.tools ?? [{ name: "report", description: "Report it.", inputSchema: SCHEMA }] } } + : { result: { content: [{ type: "text", text: "Recorded." }] } }; + return { ok: true, status: 200, json: async () => reply } as unknown as Response; + }) as unknown as typeof fetch; +} + +const servers: Server[] = []; +const dirs: string[] = []; +afterEach(() => { + for (const s of servers.splice(0)) s.close(); + for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true }); +}); + +describe("OpenClaw Self Reports tool", () => { + it("is named with a spelling the hook lets past every policy", () => { + expect(isSelfReportToolName(SELF_REPORT_OPENCLAW_TOOL, "openclaw")).toBe(true); + const manifest = JSON.parse(readFileSync(resolve(__dirname, "../../openclaw-plugin/openclaw.plugin.json"), "utf8")); + expect(manifest.contracts.tools).toEqual([SELF_REPORT_OPENCLAW_TOOL]); + }); + + it("reads the daemon's selfReport server from its pong over the socket", async () => { + const dir = mkdtempSync(join(tmpdir(), "fpai-oc-sr-")); + dirs.push(dir); + const socketPath = join(dir, "d.sock"); + const server = createServer((sock) => { + sock.once("data", () => { + const body = Buffer.from(JSON.stringify({ type: "pong", protocolVersion: 2, selfReport: SERVER })); + const head = Buffer.alloc(4); + head.writeUInt32BE(body.length, 0); + sock.end(Buffer.concat([head, body])); + }); + }); + servers.push(server); + await new Promise((ok) => server.listen(socketPath, ok)); + expect(await pingSelfReportServer({ socketPath })).toEqual(SERVER); + expect(await pingSelfReportServer({ socketPath: join(dir, "none.sock") })).toBeNull(); + }); + + it("trusts only the endpoint that answers as this user's daemon, and offers nothing while off", async () => { + const calls: Array<{ url: string; body: Record }> = []; + const tool = await discoverSelfReportTool({ ping: async () => SERVER, fetchImpl: fakeFetch(calls) }); + expect(tool).toMatchObject({ description: "Report it.", inputSchema: SCHEMA, instructions: "Report when stuck.", port: 4319 }); + expect(calls[0].url).toBe("http://127.0.0.1:4319/mcp?agent=openclaw"); + expect(await discoverSelfReportTool({ ping: async () => SERVER, fetchImpl: fakeFetch([], { instance: "other" }) })).toBeNull(); + expect(await discoverSelfReportTool({ ping: async () => SERVER, fetchImpl: fakeFetch([], { tools: [] }) })).toBeNull(); + expect(await discoverSelfReportTool({ ping: async () => null, fetchImpl: fakeFetch([]) })).toBeNull(); + }); + + it("hands a call to the daemon with the workspace and normalised arguments", async () => { + const calls: Array<{ url: string; body: Record }> = []; + const tool = { ...SERVER, description: "d", inputSchema: SCHEMA }; + const text = await callSelfReportTool(tool, { category: "looping", detail: "again" }, "/work/p", { + ping: async () => SERVER, + fetchImpl: fakeFetch(calls), + }); + expect(text).toBe("Recorded."); + expect(calls[0].url).toBe("http://127.0.0.1:4319/mcp?agent=openclaw&cwd=%2Fwork%2Fp"); + expect(calls[0].body.params).toEqual({ name: "report", arguments: { category: "looping", detail: "again" } }); + // A different daemon instance now: nothing is sent. + const none: typeof calls = []; + await callSelfReportTool(tool, {}, "/w", { ping: async () => ({ instanceId: "new", port: 4319 }), fetchImpl: fakeFetch(none) }); + expect(none).toEqual([]); + expect(prepareSelfReportArguments({ type: "looping", summary: "s" })).toEqual({ category: "looping", detail: "s" }); + }); + + it("registers a direct-only tool and the system-prompt instructions once the daemon offers the tool", async () => { + let factory: ((ctx: unknown) => Record | null) | undefined; + const hooks: Record unknown> = {}; + const api = { + config: {}, + registerTool: vi.fn((f, opts) => { + factory = f; + expect(opts).toEqual({ name: SELF_REPORT_OPENCLAW_TOOL }); + }), + on: vi.fn((name: string, handler: (...a: unknown[]) => unknown) => { + hooks[name] = handler; + }), + }; + const call = vi.fn(async () => "Recorded."); + const workspace = { resolveWorkspace: vi.fn(() => "/work/p") }; + const sr = registerSelfReportTool(api, { + discover: async () => ({ ...SERVER, description: "Report it.", inputSchema: SCHEMA, instructions: "Report when stuck." }), + call, + workspace, + }); + await sr.refresh(); + const tool = factory!({ sessionKey: "s" })!; + expect(tool).toMatchObject({ name: SELF_REPORT_OPENCLAW_TOOL, description: "Report it.", parameters: SCHEMA, catalogMode: "direct-only" }); + const result = await (tool.execute as (id: string, p: unknown) => Promise)("call-1", { kind: "looping", reason: "r" }); + expect(call).toHaveBeenCalledWith(expect.objectContaining({ description: "Report it." }), { category: "looping", detail: "r" }, "/work/p"); + expect(result).toEqual({ content: [{ type: "text", text: "Recorded." }], details: { recorded: true } }); + expect(await hooks.before_prompt_build({}, {})).toEqual({ appendSystemContext: "Report when stuck.", appendContext: "Report when stuck." }); + }); + + it("offers no tool and no instructions while Self Reports is off or the daemon is gone", async () => { + let factory: ((ctx: unknown) => unknown) | undefined; + const hooks: Record unknown> = {}; + const sr = registerSelfReportTool( + { registerTool: (f: (ctx: unknown) => unknown) => (factory = f), on: (n: string, h: (...a: unknown[]) => unknown) => (hooks[n] = h) }, + { discover: async () => null }, + ); + await sr.refresh(); + expect(factory!({})).toBeNull(); + expect(await hooks.before_prompt_build({}, {})).toBeUndefined(); + }); +}); diff --git a/__tests__/hooks/pi-self-report-sync.test.ts b/__tests__/hooks/pi-self-report-sync.test.ts new file mode 100644 index 000000000..32349fd45 --- /dev/null +++ b/__tests__/hooks/pi-self-report-sync.test.ts @@ -0,0 +1,125 @@ +// @vitest-environment node +/** + * F21: a Pi started while Self Reports was off (or while it waited for + * FailproofAI Cloud's setting) kept no report tool for the whole process. + * The extension now asks again on session_start / before_agent_start, at most + * once a minute, registers the tool when it appears, and takes it out of the + * active tools when it goes away. + */ +import { describe, expect, it, vi } from "vitest"; + +vi.mock("node:child_process", () => ({ + // No server in these tests: every lookup goes through the injected `discover`. + spawn: () => { + throw new Error("no server in this test"); + }, + spawnSync: () => ({ pid: 0, output: [], status: 0, signal: null, stderr: "", stdout: "" }), +})); + +import failproofaiBridge, { selfReportToolSync } from "../../pi-extension/index"; + +const TOOL = { description: "Report it.", inputSchema: { type: "object", properties: {} }, instructions: "Report when stuck." }; +const NAME = "mcp__failproofai_local__report"; + +function fakePi(bound = true) { + const tools = new Map>(); + let active: string[] = ["read", "bash"]; + const pi = { + on: vi.fn(), + registerTool: vi.fn((t: Record) => { + tools.set(t.name as string, t); + if (!active.includes(t.name as string)) active = [...active, t.name as string]; + }), + getActiveTools: vi.fn(() => { + if (!bound) throw new Error("Extension runtime not initialized"); + return active; + }), + setActiveTools: vi.fn((names: string[]) => { + active = names; + }), + }; + return { pi, tools, active: () => active }; +} + +describe("selfReportToolSync", () => { + it("off at start, then turned on: the tool is registered on the next look, without a restart", async () => { + let offered: typeof TOOL | null = null; + let now = 0; + const { pi, tools, active } = fakePi(); + const sync = selfReportToolSync(pi, async () => offered, () => now); + await sync.refresh(true); + expect(tools.size).toBe(0); + expect(sync.offered()).toBe(false); + offered = TOOL; + // Within the minute: not asked again. + await sync.refresh(); + expect(tools.size).toBe(0); + now += 60_000; + await sync.refresh(); + expect(tools.get(NAME)).toMatchObject({ name: NAME, description: "Report it.", promptGuidelines: ["Report when stuck."] }); + expect(active()).toContain(NAME); + expect(sync.offered()).toBe(true); + }); + + it("turned off again: taken out of the active tools; back on: active again, re-registered only when its text changed", async () => { + let offered: typeof TOOL | null = TOOL; + let now = 0; + const { pi, active } = fakePi(); + const sync = selfReportToolSync(pi, async () => offered, () => now); + await sync.refresh(true); + expect(pi.registerTool).toHaveBeenCalledTimes(1); + offered = null; + now += 60_000; + await sync.refresh(); + expect(active()).not.toContain(NAME); + expect(sync.offered()).toBe(false); + offered = TOOL; + now += 60_000; + await sync.refresh(); + expect(active()).toContain(NAME); + expect(pi.registerTool).toHaveBeenCalledTimes(1); + offered = { ...TOOL, instructions: "New guidance." }; + now += 60_000; + await sync.refresh(); + expect(pi.registerTool).toHaveBeenCalledTimes(2); + }); + + it("a lookup that fails or throws leaves nothing registered and never rejects", async () => { + const { pi, tools } = fakePi(); + const sync = selfReportToolSync(pi, async () => { + throw new Error("spawn failed"); + }); + await expect(sync.refresh(true)).resolves.toBeUndefined(); + expect(tools.size).toBe(0); + }); + + it("does not ask twice at once", async () => { + let calls = 0; + let release: (v: typeof TOOL | null) => void = () => {}; + const { pi } = fakePi(); + const sync = selfReportToolSync(pi, () => { + calls++; + return new Promise((r) => (release = r)); + }); + const a = sync.refresh(true); + const b = sync.refresh(true); + release(TOOL); + await Promise.all([a, b]); + expect(calls).toBe(1); + }); +}); + +describe("the extension asks again on session_start and before_agent_start", () => { + it("registers handlers that start a lookup without waiting on it", async () => { + const handlers: Record unknown> = {}; + const { pi } = fakePi(false); + pi.on.mockImplementation((name: string, fn: (e: unknown) => unknown) => { + handlers[name] = fn; + }); + await failproofaiBridge(pi); + // No server here, so no tool; the handlers still answer synchronously. + expect(pi.registerTool).not.toHaveBeenCalled(); + expect(handlers.session_start({ type: "session_start", cwd: "/p" })).toBeUndefined(); + expect(handlers.before_agent_start({ type: "before_agent_start", cwd: "/p", systemPrompt: "" })).toBeUndefined(); + }); +}); diff --git a/__tests__/hooks/scope-attribution.test.ts b/__tests__/hooks/scope-attribution.test.ts index 6ff6094ba..16727766a 100644 --- a/__tests__/hooks/scope-attribution.test.ts +++ b/__tests__/hooks/scope-attribution.test.ts @@ -58,7 +58,7 @@ describe("which scopes actually hold hooks", () => { ); const pluginDir = join(home, ".hermes", "plugins", "failproofai"); mkdirSync(pluginDir, { recursive: true }); - for (const file of ["plugin.yaml", "__init__.py", "client.py", "ledger.py", ".failproofai-managed"]) { + for (const file of ["plugin.yaml", "__init__.py", "client.py", "ledger.py", "self_report.py", ".failproofai-managed"]) { writeFileSync(join(pluginDir, file), "", "utf8"); } diff --git a/__tests__/hooks/self-report-ancestry.test.ts b/__tests__/hooks/self-report-ancestry.test.ts new file mode 100644 index 000000000..d6c4a9d41 --- /dev/null +++ b/__tests__/hooks/self-report-ancestry.test.ts @@ -0,0 +1,142 @@ +// @vitest-environment node +/** + * Which agent process a hook event or a stdio report came from (F14): the + * nearest process above that is not a shell or exec wrapper, matched EXACTLY + * (self-report-hook-trust.test.ts covers the dedup and the session choice). + */ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { writeEffectiveSelfReport } from "../../src/hooks/self-report"; +import { + SELF_REPORT_AGENT_PID_KEY, + SELF_REPORT_AGENT_PIDS_KEY_V1, + selfReportAgentPid, + selfReportAgentPidOf, + selfReportAncestry, + selfReportMarkAgentPid, +} from "../../src/hooks/self-report-ancestry"; + +const report = (extra: Record = {}) => + JSON.stringify({ session_id: "s", tool_name: "mcp__failproofai_local__report", tool_input: { category: "looping", detail: "x" }, ...extra }); + +describe("selfReportAncestry / selfReportAgentPid", () => { + it.runIf(process.platform === "linux" || process.platform === "darwin")("starts at this process's parent", () => { + const up = selfReportAncestry(); + expect(up[0].pid).toBe(process.ppid); + expect(up.length).toBeLessThanOrEqual(8); + }); + + it("skips shells and exec wrappers to the agent, and only them", () => { + const tree = (...names: string[]) => () => names.map((name, i) => ({ pid: 100 + i, name })); + expect(selfReportAgentPid(tree("sh", "claude", "bash"))).toBe(101); + expect(selfReportAgentPid(tree("bash", "npm exec failpr", "sh", "codex"))).toBe(103); + expect(selfReportAgentPid(tree("-zsh", "env", "node"))).toBe(102); + // A nested agent: B (its hook runs under B's shell) is found before A. + expect(selfReportAgentPid(tree("sh", "claude", "bash", "claude"))).toBe(101); + expect(selfReportAgentPid(tree("sh", "bash"))).toBeUndefined(); + expect(selfReportAgentPid(() => [])).toBeUndefined(); + }); +}); + +describe("selfReportMarkAgentPid", () => { + const pid = () => 4001; + // Stamping now needs Self Reports on: a home of its own where it is, never the developer's. + let home: string; + beforeEach(() => { + home = mkdtempSync(join(tmpdir(), "fpai-sr-anc-on-")); + vi.stubEnv("FAILPROOFAI_HOME", home); + writeEffectiveSelfReport({ enabled: true }); + }); + afterEach(() => { + vi.unstubAllEnvs(); + rmSync(home, { recursive: true, force: true }); + }); + + it("stamps a Claude Code or Codex report call, and any agent's session-start and prompt events", () => { + for (const cli of ["claude", "codex"]) { + const out = JSON.parse(selfReportMarkAgentPid(cli, "PreToolUse", report(), pid)); + expect(out[SELF_REPORT_AGENT_PID_KEY]).toBe(4001); + // And the earlier list form, which a worker of the previous build copies. + expect(out[SELF_REPORT_AGENT_PIDS_KEY_V1]).toEqual([4001]); + } + const spoofedV1 = report({ [SELF_REPORT_AGENT_PIDS_KEY_V1]: [9, 8] }); + expect(JSON.parse(selfReportMarkAgentPid("claude", "PreToolUse", spoofedV1, () => undefined))).not.toHaveProperty(SELF_REPORT_AGENT_PIDS_KEY_V1); + for (const [cli, event] of [["cursor", "SessionStart"], ["claude", "UserPromptSubmit"], ["copilot", "UserPromptSubmit"]]) { + const payload = JSON.stringify({ session_id: "s", prompt: "hi" }); + expect(JSON.parse(selfReportMarkAgentPid(cli, event, payload, pid))[SELF_REPORT_AGENT_PID_KEY], `${cli} ${event}`).toBe(4001); + } + }); + + it("leaves every other call as it was, and replaces or drops a value the payload carried", () => { + const bash = JSON.stringify({ tool_name: "Bash", tool_input: { command: "ls failproofai_local" } }); + expect(selfReportMarkAgentPid("claude", "PreToolUse", bash, pid)).toBe(bash); + expect(selfReportMarkAgentPid("cursor", "PreToolUse", report(), pid)).toBe(report()); + const spoofed = report({ [SELF_REPORT_AGENT_PID_KEY]: 12345 }); + expect(JSON.parse(selfReportMarkAgentPid("claude", "PreToolUse", spoofed, pid))[SELF_REPORT_AGENT_PID_KEY]).toBe(4001); + expect(JSON.parse(selfReportMarkAgentPid("claude", "PreToolUse", spoofed, () => undefined))).not.toHaveProperty(SELF_REPORT_AGENT_PID_KEY); + const bashSpoof = JSON.stringify({ tool_name: "Bash", [SELF_REPORT_AGENT_PID_KEY]: 5 }); + expect(JSON.parse(selfReportMarkAgentPid("claude", "PreToolUse", bashSpoof, pid))).not.toHaveProperty(SELF_REPORT_AGENT_PID_KEY); + expect(selfReportMarkAgentPid("claude", "SessionStart", "{not json", pid)).toBe("{not json"); + }); +}); + +describe("selfReportMarkAgentPid only while Self Reports is on (review #1105 item 10)", () => { + const session = JSON.stringify({ session_id: "s", prompt: "hi" }); + + it("with Self Reports off, never looks up the ancestry (no `ps` on macOS), and still drops a carried value", () => { + const lookup = vi.fn(() => 4001); + for (const [cli, event, payload] of [ + ["claude", "SessionStart", session], + ["cursor", "UserPromptSubmit", session], + ["codex", "PreToolUse", report()], + ] as const) { + expect(selfReportMarkAgentPid(cli, event, payload, lookup, () => false)).toBe(payload); + } + const spoofed = report({ [SELF_REPORT_AGENT_PID_KEY]: 12345 }); + expect(JSON.parse(selfReportMarkAgentPid("claude", "PreToolUse", spoofed, lookup, () => false))).not.toHaveProperty(SELF_REPORT_AGENT_PID_KEY); + expect(lookup).not.toHaveBeenCalled(); + }); + + it("the default check reads the effective settings: off in self-report.json means no lookup", () => { + const home = mkdtempSync(join(tmpdir(), "fpai-sr-anc-")); + vi.stubEnv("FAILPROOFAI_HOME", home); + try { + const lookup = vi.fn(() => 4001); + writeEffectiveSelfReport({ enabled: false }); + expect(selfReportMarkAgentPid("claude", "SessionStart", session, lookup)).toBe(session); + expect(lookup).not.toHaveBeenCalled(); + writeEffectiveSelfReport({ enabled: true }); + expect(JSON.parse(selfReportMarkAgentPid("claude", "SessionStart", session, lookup))[SELF_REPORT_AGENT_PID_KEY]).toBe(4001); + expect(lookup).toHaveBeenCalledTimes(1); + } finally { + vi.unstubAllEnvs(); + rmSync(home, { recursive: true, force: true }); + } + }); + + it("an ordinary tool call reads neither the settings nor the ancestry", () => { + const lookup = vi.fn(() => 4001); + const enabled = vi.fn(() => true); + const bash = JSON.stringify({ tool_name: "Bash", tool_input: { command: "ls" } }); + expect(selfReportMarkAgentPid("claude", "PreToolUse", bash, lookup, enabled)).toBe(bash); + expect(enabled).not.toHaveBeenCalled(); + expect(lookup).not.toHaveBeenCalled(); + }); +}); + +describe("selfReportAncestry stops early", () => { + it.runIf(process.platform === "linux" || process.platform === "darwin")("at the first process the caller is looking for", () => { + const up = selfReportAncestry(8, () => true); + expect(up).toHaveLength(1); + expect(up[0].pid).toBe(process.ppid); + }); +}); + +describe("selfReportAgentPidOf", () => { + it("keeps only a real pid", () => { + expect(selfReportAgentPidOf(5)).toBe(5); + for (const v of [1, 0, -3, 7.5, "6", [5], undefined]) expect(selfReportAgentPidOf(v)).toBeUndefined(); + }); +}); diff --git a/__tests__/hooks/self-report-devin.test.ts b/__tests__/hooks/self-report-devin.test.ts new file mode 100644 index 000000000..548c43a65 --- /dev/null +++ b/__tests__/hooks/self-report-devin.test.ts @@ -0,0 +1,85 @@ +// @vitest-environment node +import { describe, it, expect } from "vitest"; +import { + selfReportAncestryIsDevin, + selfReportClaudeHookFromDevin, + selfReportMarkDevinOrigin, + SELF_REPORT_DEVIN_MARKER, + selfReportParentProcessNames, +} from "../../src/hooks/self-report-devin"; + +const none = () => [] as string[]; + +describe("selfReportClaudeHookFromDevin", () => { + it("a Claude Code payload (transcript_path, toolu_ id) is Claude's", () => { + expect( + selfReportClaudeHookFromDevin({ transcript_path: "/h/.claude/projects/x/s.jsonl", tool_use_id: "toolu_01A" }, none), + ).toBe(false); + }); + + it("a payload with no id and no transcript is not taken for Devin's on its own", () => { + expect(selfReportClaudeHookFromDevin({ session_id: "s" }, none)).toBe(false); + }); + + it("Devin's call- id with no transcript_path is Devin's", () => { + expect( + selfReportClaudeHookFromDevin({ tool_use_id: "call-46ba525a-305d-4f99-8053-0cf0d1a1da73" }, none), + ).toBe(true); + }); + + it("a call- id alongside a transcript_path is not enough", () => { + expect( + selfReportClaudeHookFromDevin( + { transcript_path: "/t.jsonl", tool_use_id: "call-46ba525a-305d-4f99-8053-0cf0d1a1da73" }, + none, + ), + ).toBe(false); + }); + + it("tool_provenance (a Devin-only field) is Devin's", () => { + expect(selfReportClaudeHookFromDevin({ transcript_path: "/t.jsonl", tool_provenance: "mcp" }, none)).toBe(true); + }); + + it("a devin process above the hook is Devin's", () => { + expect(selfReportClaudeHookFromDevin({ transcript_path: "/t.jsonl", tool_use_id: "toolu_1" }, () => ["sh", "devin"])).toBe(true); + }); +}); + +describe("selfReportAncestryIsDevin", () => { + it("nearest agent wins: Claude Code started from a Devin shell is Claude", () => { + expect(selfReportAncestryIsDevin(["sh", "claude", "bash", "devin"])).toBe(false); + expect(selfReportAncestryIsDevin(["sh", "/usr/local/bin/devin", "zsh"])).toBe(true); + expect(selfReportAncestryIsDevin(["sh", "bash", "tmux"])).toBe(false); + expect(selfReportAncestryIsDevin([])).toBe(false); + }); +}); + +describe("selfReportParentProcessNames", () => { + it("reads this process's real ancestry without throwing", () => { + const names = selfReportParentProcessNames(3); + expect(Array.isArray(names)).toBe(true); + if (process.platform === "linux") expect(names.length).toBeGreaterThan(0); + }); +}); + +describe("selfReportMarkDevinOrigin (runs in the hook process, before the daemon)", () => { + const call = JSON.stringify({ tool_name: "mcp__failproofai_local__report", tool_input: {}, transcript_path: "/t.jsonl" }); + const devin = () => ["sh", "devin"]; + + it("marks a Claude-path report call made under Devin, and the worker then reads it as Devin's", () => { + const out = selfReportMarkDevinOrigin("claude", call, devin); + const parsed = JSON.parse(out) as Record; + expect(parsed[SELF_REPORT_DEVIN_MARKER]).toBe(true); + expect(selfReportClaudeHookFromDevin(parsed, none)).toBe(true); + }); + + it("leaves everything else byte-for-byte alone", () => { + expect(selfReportMarkDevinOrigin("claude", call, () => ["sh", "claude"])).toBe(call); + expect(selfReportMarkDevinOrigin("devin", call, devin)).toBe(call); + const bash = JSON.stringify({ tool_name: "Bash", tool_input: { command: "ls" } }); + expect(selfReportMarkDevinOrigin("claude", bash, devin)).toBe(bash); + const other = JSON.stringify({ tool_name: "Bash", tool_input: { command: "cat failproofai_local.txt" } }); + expect(selfReportMarkDevinOrigin("claude", other, devin)).toBe(other); + expect(selfReportMarkDevinOrigin("claude", "not json failproofai_local", devin)).toBe("not json failproofai_local"); + }); +}); diff --git a/__tests__/hooks/self-report-golden.test.ts b/__tests__/hooks/self-report-golden.test.ts new file mode 100644 index 000000000..d2fc5a2c4 --- /dev/null +++ b/__tests__/hooks/self-report-golden.test.ts @@ -0,0 +1,229 @@ +// @vitest-environment node +/** + * Self Reports: the CLI side of the shared golden files in + * test-fixtures/self-report/. The Rust daemon (crates/fpai-collect) and the + * TypeScript SDK (sdk/typescript) are tested against the same files, so the + * tool description, input schema, default categories, recognised tool names, + * server-recorded integrations and the `self_report` event's fields cannot + * drift apart between them. Change a golden file only together with every + * implementation. + */ +import { INTEGRATION_TYPES } from "../../src/hooks/types"; +import { describe, it, expect, beforeEach, afterEach } from "vitest"; +import { mkdtempSync, readFileSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import { + SELF_REPORT_ARG_ALIASES, + SELF_REPORT_CATEGORY_RULES, + SELF_REPORT_DEFAULT_CATEGORIES, + SELF_REPORT_FALLBACK_CATEGORY, + resolveSelfReportCategory, + SELF_REPORT_SERVER_RECORDS, + selfReportArgs, + selfReportClip, + selfReportCutDetail, + SELF_REPORT_DETAIL_CUT_MARKER, + describeSelfReportTool, + isSelfReportCursorCall, + isSelfReportToolName, + isAnySelfReportToolName, + selfReportToolSpellings, + selfReportInputSchema, + selfReportInstructions, +} from "../../src/hooks/self-report"; +import { writeSelfReportEvent } from "../../src/hooks/self-report-mcp"; + +const ROOT = resolve(__dirname, "..", ".."); +const GOLDEN = join(ROOT, "test-fixtures", "self-report"); +const golden = (name: string) => readFileSync(join(GOLDEN, name), "utf8"); +const lines = (name: string) => golden(name).split("\n").filter((l) => l !== ""); + +describe("Self Reports golden files (CLI)", () => { + it("builds the description byte for byte", () => { + expect(describeSelfReportTool(SELF_REPORT_DEFAULT_CATEGORIES, null)).toBe(golden("description.golden.txt")); + expect( + describeSelfReportTool(SELF_REPORT_DEFAULT_CATEGORIES, "Report a missing repository as missing_context."), + ).toBe(golden("description-guidance.golden.txt")); + }); + + it("builds the MCP server instructions byte for byte", () => { + expect(selfReportInstructions(SELF_REPORT_DEFAULT_CATEGORIES, null)).toBe(golden("instructions.golden.txt")); + expect( + selfReportInstructions(SELF_REPORT_DEFAULT_CATEGORIES, "Report a missing repository as missing_context."), + ).toBe(golden("instructions-guidance.golden.txt")); + expect(golden("instructions.golden.txt").length).toBeLessThan(600); + }); + + it("cuts text in code points, as the shared truncation cases say", () => { + const fixture = JSON.parse(golden("truncation.golden.json")) as { + max: number; + cases: { pad_char: string; pad: number; tail: string; expected_tail: string }[]; + }; + for (const c of fixture.cases) { + const input = c.pad_char.repeat(c.pad) + c.tail; + const want = c.pad_char.repeat(c.pad) + c.expected_tail; + const label = `${c.pad} x ${JSON.stringify(c.pad_char)} + ${JSON.stringify(c.tail)}`; + expect(selfReportClip(input, fixture.max), label).toBe(want); + } + // A lone surrogate (which no golden JSON can carry) becomes U+FFFD, never an unpaired escape. + expect(selfReportClip("a\ud83d")).toBe("a\ufffd"); + expect(selfReportClip("\ude00b")).toBe("\ufffdb"); + expect(JSON.stringify(selfReportArgs({ detail: "x\ud83d" }))).not.toMatch(/\\ud83d/); + }); + + // Round 3: a credential running past the 2000 cut was kept as a fragment no + // scrubber recognised, and uploaded raw. The detail cut never leaves part of + // a token at the end, the same way in every implementation. + it("cuts a report's detail without leaving part of a token, as the shared detail_cut cases say", () => { + const fixture = JSON.parse(golden("truncation.golden.json")) as { + max: number; + detail_cut: { marker: string; whitespace: string; cases: { name: string; input: [string, number][]; expected: [string, number][] }[] }; + }; + const join = (parts: [string, number][]) => parts.map(([t, n]) => t.repeat(n)).join(""); + expect(SELF_REPORT_DETAIL_CUT_MARKER).toBe(fixture.detail_cut.marker); + expect(fixture.detail_cut.cases.length).toBeGreaterThan(5); + for (const c of fixture.detail_cut.cases) { + const input = join(c.input); + const want = join(c.expected); + expect(selfReportCutDetail(input, fixture.max), c.name).toBe(want); + expect(selfReportArgs({ category: "looping", detail: input }).detail, c.name).toBe(want); + } + // Every whitespace character in the list splits a token; nothing else does. + for (const ws of fixture.detail_cut.whitespace) { + expect(selfReportCutDetail(`ok${ws}${"t".repeat(2100)}`, fixture.max), JSON.stringify(ws)).toBe("ok"); + } + expect(selfReportCutDetail(`ok\u00a0${"t".repeat(2100)}`, fixture.max)).toBe(SELF_REPORT_DETAIL_CUT_MARKER); + }); + + it("resolves a report's category by the shared rules and runs every shared case", () => { + const fixture = JSON.parse(golden("category-inference.json")) as { + rules: { category: string; keywords: string[] }[]; + fallback: string; + cases: { name: string; categories?: string[]; args: Record; category: string; inferred: boolean }[]; + }; + expect(SELF_REPORT_CATEGORY_RULES).toEqual(fixture.rules); + expect(SELF_REPORT_FALLBACK_CATEGORY).toBe(fixture.fallback); + const defaults = SELF_REPORT_DEFAULT_CATEGORIES.map((c) => c.name); + expect(fixture.cases.length).toBeGreaterThan(0); + for (const c of fixture.cases) { + const { category, detail } = selfReportArgs(c.args); + expect(resolveSelfReportCategory(category, detail, c.categories ?? defaults), c.name).toEqual({ + category: c.category, + inferred: c.inferred, + }); + } + }); + + it("reads argument aliases from the shared list, for raw and hook-wrapped arguments", () => { + const fixture = JSON.parse(golden("arg-aliases.json")) as { + aliases: { category: string[]; detail: string[] }; + cases: { args: Record; category: string; detail: string }[]; + }; + expect(SELF_REPORT_ARG_ALIASES).toEqual(fixture.aliases); + for (const c of fixture.cases) { + const want = { category: c.category, detail: c.detail }; + expect(selfReportArgs(c.args), JSON.stringify(c.args)).toEqual(want); + expect(selfReportArgs(JSON.stringify(c.args)), JSON.stringify(c.args)).toEqual(want); + expect(selfReportArgs({ arguments: c.args }), JSON.stringify(c.args)).toEqual(want); + expect(selfReportArgs({ args: JSON.stringify(c.args) }), JSON.stringify(c.args)).toEqual(want); + } + }); + + it("builds the input schema byte for byte", () => { + expect(`${JSON.stringify(selfReportInputSchema(SELF_REPORT_DEFAULT_CATEGORIES))}\n`).toBe(golden("input-schema.golden.json")); + }); + + it("ships the six default categories", () => { + expect(SELF_REPORT_DEFAULT_CATEGORIES).toEqual(JSON.parse(golden("categories.golden.json"))); + }); + + it("recognises every per-agent spelling of the tool, and nothing near it", () => { + // The golden list is the SDKs' and includes their own `failproofai_report`, + // which the hook path must never match: it is also OpenCode's name for + // tool `report` on a server called `failproofai`. + // The hook takes each agent's own spellings only (review #1105), a subset + // of the SDKs' golden list. + const golden = new Set(lines("tool-names.golden.txt")); + for (const cli of INTEGRATION_TYPES) { + for (const name of selfReportToolSpellings(cli)) { + expect(golden.has(name), name).toBe(true); + expect(isSelfReportToolName(name, cli), `${cli} ${name}`).toBe(true); + expect(isSelfReportToolName(name.toUpperCase(), cli), `${cli} ${name}`).toBe(true); + } + } + expect(isAnySelfReportToolName("failproofai_report")).toBe(false); + // The Cloud gateway's server is `failproofai`; its tools are never ours. + const gateway = ["mcp__failproofai__report", "failproofai__report", "failproofai___report", "mcp_failproofai_report", "failproofai-report", "failproofai/report"]; + for (const name of ["report", "MCP:report", "mcp__other__report", "failproofai_report_x", "xfailproofai_local__report", "failproofai", "failproofai_local", ...gateway]) { + expect(isAnySelfReportToolName(name), name).toBe(false); + } + }); + + it("recognises Cursor's MCP hook only with the failproofai_local server name", () => { + expect(isSelfReportCursorCall({ tool_name: "report", mcp_server_name: "failproofai" })).toBe(false); + expect(isSelfReportCursorCall({ tool_name: "report", mcp_server_name: "failproofai_local" })).toBe(true); + expect(isSelfReportCursorCall({ tool_name: "MCP:report", mcp_server_name: "failproofai_local" })).toBe(true); + expect(isSelfReportCursorCall({ tool_name: "report", mcp_server_name: "linear" })).toBe(false); + expect(isSelfReportCursorCall({ tool_name: "report" })).toBe(false); + expect(isSelfReportCursorCall({ tool_name: "MCP:report" })).toBe(false); + expect(isSelfReportCursorCall({ tool_name: "search", mcp_server_name: "failproofai_local" })).toBe(false); + }); + + it("keeps the TypeScript SDK's tool-name list equal to the golden list", () => { + const src = readFileSync(join(ROOT, "sdk", "typescript", "src", "self-report-spec.ts"), "utf8"); + const block = src.match(/SELF_REPORT_TOOL_SPELLINGS[^=]*=\s*Object\.freeze\(\[([\s\S]*?)\]\)/); + expect(block, "SELF_REPORT_TOOL_SPELLINGS in the SDK").not.toBeNull(); + const names = [...block![1].matchAll(/"([^"]+)"/g)].map((m) => m[1]); + expect(names).toEqual(lines("tool-names.golden.txt")); + }); + + it("lists the same server-recorded integrations as the Rust daemon", () => { + expect([...SELF_REPORT_SERVER_RECORDS]).toEqual(lines("server-records.golden.txt")); + const rs = readFileSync(join(ROOT, "crates", "fpai-collect", "src", "self_report.rs"), "utf8"); + const block = rs.match(/pub const SERVER_RECORDS: &\[&str\] = &\[([\s\S]*?)\];/); + expect(block, "SERVER_RECORDS in self_report.rs").not.toBeNull(); + expect([...block![1].matchAll(/"([^"]+)"/g)].map((m) => m[1])).toEqual([...SELF_REPORT_SERVER_RECORDS]); + for (const hooked of ["claude", "codex"]) expect(SELF_REPORT_SERVER_RECORDS).not.toContain(hooked); + }); + + describe("the stdio server's fallback event", () => { + let home: string; + let saved: string | undefined; + beforeEach(() => { + home = mkdtempSync(join(tmpdir(), "fpai-sr-golden-")); + saved = process.env.FAILPROOFAI_HOME; + process.env.FAILPROOFAI_HOME = home; + }); + afterEach(() => { + if (saved === undefined) delete process.env.FAILPROOFAI_HOME; + else process.env.FAILPROOFAI_HOME = saved; + rmSync(home, { recursive: true, force: true }); + }); + + it("writes the golden fields in wire order", async () => { + const spec = JSON.parse(golden("event-fields.golden.json")) as { order: string[]; fallbackExtras: string[] }; + const { path, event } = await writeSelfReportEvent({ + integration: "hermes", + category: "looping", + detail: "Same step again.", + cwd: home, + now: Date.parse("2026-11-25T10:00:00Z"), + }); + expect(Object.keys(event)).toEqual([...spec.order, ...spec.fallbackExtras]); + expect(Object.keys(JSON.parse(readFileSync(path, "utf8").trim()))).toEqual([...spec.order, ...spec.fallbackExtras]); + }); + + it("writes a detail cut at a surrogate boundary as valid UTF-8, with no lone surrogate", async () => { + const { path, event } = await writeSelfReportEvent({ + integration: "hermes", + category: "looping", + detail: `${"a".repeat(1999)}\u{1F600} tail \ud83d`, + cwd: home, + now: Date.parse("2026-11-25T10:00:00Z"), + }); + expect(event.detail).toBe(`${"a".repeat(1999)}\u{1F600}`); + expect(readFileSync(path, "utf8")).not.toMatch(/\\ud[89a-f][0-9a-f]{2}/i); + }); + }); +}); diff --git a/__tests__/hooks/self-report-handler.test.ts b/__tests__/hooks/self-report-handler.test.ts new file mode 100644 index 000000000..cc5aa13fc --- /dev/null +++ b/__tests__/hooks/self-report-handler.test.ts @@ -0,0 +1,867 @@ +// @vitest-environment node +/** + * The Self Reports short-circuit in evaluateHookEvent: a call to the report + * tool is allowed before ANY policy, pause, fail-closed or Jev logic, and is + * recorded on its activity row. The control call in each case (a plain Bash + * call) shows the same setup really does deny, so an allow is not vacuous. + */ +import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; +import { mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +vi.mock("../../src/hooks/hooks-config", () => ({ + readMergedHooksConfig: vi.fn(() => ({ enabledPolicies: [] })), +})); +vi.mock("../../src/hooks/custom-hooks-loader", () => ({ loadAllCustomHooks: vi.fn() })); +vi.mock("../../src/hooks/hook-telemetry", () => ({ + trackHookEvent: vi.fn(() => Promise.resolve()), + flushHookTelemetry: vi.fn(() => Promise.resolve()), +})); +vi.mock("../../lib/telemetry-id", () => ({ getInstanceId: vi.fn(() => "test-instance-id") })); +vi.mock("../../src/hooks/untraced-note", () => ({ noteUntracedAgent: vi.fn(() => false) })); +vi.mock("../../src/hooks/pack-manifest", () => ({ + readInstalledPacks: vi.fn(() => ({ packs: [], errors: [] })), + hasInstalledPacks: vi.fn(() => false), + hasInstalledRegexPacks: vi.fn(() => false), +})); +vi.mock("../../src/hooks/effective-reviewers", async (orig) => { + const real = await orig(); + // "Jev is configured": every gate that reaches the two-tier path asks this. + return { ...real, jevChecksInstalled: vi.fn(() => true), packJevChecksInstalled: vi.fn(() => true) }; +}); + +import { evaluateHookEvent } from "../../src/hooks/handler"; +import { loadAllCustomHooks } from "../../src/hooks/custom-hooks-loader"; +import { readMergedHooksConfig } from "../../src/hooks/hooks-config"; +import { jevChecksInstalled } from "../../src/hooks/effective-reviewers"; +import { writePause } from "../../src/hooks/session-pause"; +import { _resetForTest } from "../../src/hooks/hook-activity-store"; +import { INTEGRATION_TYPES } from "../../src/hooks/types"; +import { HEALTH_PROBE_SOURCE } from "../../src/hooks/health-probe"; +import { writeEffectiveSelfReport } from "../../src/hooks/self-report"; +import { REGISTERED_CLI, isolateAgentHome, registerOwnSelfReportServer } from "../helpers/self-report-registration"; + +const SESSION = "sr-session"; +let home: string; +/** The project the calls come from (inside the temp home, so no real file above it is read). */ +let project: string; + +function payload(toolName: string, toolInput: unknown, extra: Record = {}): string { + return JSON.stringify({ session_id: SESSION, cwd: project, tool_name: toolName, tool_input: toolInput, ...extra }); +} +const report = (extra: Record = {}) => + payload("mcp__failproofai_local__report", { category: "invalid_tool_or_credential", detail: "tracker rejected its API key" }, extra); +const bash = () => payload("Bash", { command: "echo hi" }); + +function rows(): Array> { + try { + return readFileSync(join(home, "hook-activity", "current.jsonl"), "utf8") + .split("\n") + .filter(Boolean) + .map((l) => JSON.parse(l) as Record); + } catch { + return []; + } +} + +beforeEach(async () => { + vi.clearAllMocks(); + home = mkdtempSync(join(tmpdir(), "fpai-sr-handler-")); + project = join(home, "project"); + mkdirSync(project, { recursive: true }); + // Every agent's failproofai_local entry is ours: the early allow needs that. + isolateAgentHome(join(home, "user")); + await registerOwnSelfReportServer(); + process.env.FAILPROOFAI_HOME = home; + process.env.FAILPROOFAI_STATE_DIR = join(home, "state"); + _resetForTest(join(home, "hook-activity")); + // Self Reports on: the hook records a report only while the setting says so. + writeEffectiveSelfReport({ enabled: true }); + // A custom policy that denies everything, on every event. + vi.mocked(loadAllCustomHooks).mockImplementation((async () => ({ + hooks: [ + Object.assign( + { name: "deny-all", description: "", match: {}, fn: async () => ({ decision: "deny", reason: "nothing passes" }) }, + { __policyId: "custom:/tmp/deny.mjs:deny-all" }, + ), + ], + conventionSources: [], + })) as never); +}); + +afterEach(() => { + vi.unstubAllEnvs(); + delete process.env.FAILPROOFAI_HOME; + delete process.env.FAILPROOFAI_STATE_DIR; + _resetForTest(); + rmSync(home, { recursive: true, force: true }); +}); + +describe("Self Reports short-circuit", () => { + it("control: the deny-everything policy really denies an ordinary call", async () => { + const out = await evaluateHookEvent("PreToolUse", "claude", bash()); + expect(out.evaluation?.decision).toBe("deny"); + expect(out.stdout).toContain("deny"); + }); + + it("allows the report tool even with a deny-everything custom policy, and loads no policy at all", async () => { + const out = await evaluateHookEvent("PreToolUse", "claude", report()); + expect(out).toMatchObject({ exitCode: 0, stdout: "", stderr: "" }); + expect(out.evaluation?.decision).toBe("allow"); + expect(loadAllCustomHooks).not.toHaveBeenCalled(); + expect(readMergedHooksConfig).not.toHaveBeenCalled(); + }); + + it("records the report on its activity row", async () => { + await evaluateHookEvent("PreToolUse", "claude", report({ tool_use_id: "toolu_1" })); + const [row] = rows(); + expect(row).toMatchObject({ + eventType: "PreToolUse", + integration: "claude", + toolName: "mcp__failproofai_local__report", + decision: "allow", + policyName: null, + sessionId: SESSION, + toolCallId: "toolu_1", + selfReport: { category: "invalid_tool_or_credential", detail: "tracker rejected its API key", source: "mcp" }, + }); + }); + + describe("the current Self Reports setting", () => { + const settings = () => join(home, "self-report.json"); + + it.each([ + [ + "missing on a Cloud-enrolled machine", + () => { + rmSync(settings(), { force: true }); + writeFileSync(join(home, "credentials.json"), JSON.stringify({ cloud: { url: "https://x", machine_id: "m", token: "t" } })); + }, + ], + [ + "missing with config.json selfReport.enabled false", + () => { + rmSync(settings(), { force: true }); + writeFileSync(join(home, "config.json"), JSON.stringify({ selfReport: { enabled: false } })); + }, + ], + ["disabled", () => writeEffectiveSelfReport({ enabled: false })], + ["malformed", () => writeFileSync(settings(), "{ not json")], + ["of another version", () => writeFileSync(settings(), JSON.stringify({ version: 2, enabled: true }))], + ])("%s: still allows the call (Claude and Codex) but records no report", async (_name, setUp) => { + setUp(); + for (const [event, cli] of [["PreToolUse", "claude"], ["pre_tool_use", "codex"]] as const) { + const out = await evaluateHookEvent(event, cli, report()); + expect(out.evaluation?.decision).toBe("allow"); + expect(loadAllCustomHooks).not.toHaveBeenCalled(); + } + const all = rows(); + expect(all).toHaveLength(2); + expect(all.every((r) => r.selfReport === undefined)).toBe(true); + }); + + it("missing off Cloud: on by default, the report is recorded with no settings file", async () => { + rmSync(settings(), { force: true }); + for (const [event, cli] of [["PreToolUse", "claude"], ["pre_tool_use", "codex"]] as const) { + expect((await evaluateHookEvent(event, cli, report())).evaluation?.decision).toBe("allow"); + } + const all = rows(); + expect(all).toHaveLength(2); + expect(all.every((r) => (r.selfReport as { source?: string } | undefined)?.source === "mcp")).toBe(true); + }); + + it("disabling during a session stops the next call's report, and enabling brings it back", async () => { + await evaluateHookEvent("PreToolUse", "claude", report()); + writeEffectiveSelfReport({ enabled: false }); + expect((await evaluateHookEvent("PreToolUse", "claude", report())).evaluation?.decision).toBe("allow"); + writeEffectiveSelfReport({ enabled: true }); + await evaluateHookEvent("PreToolUse", "claude", report()); + expect(rows().map((r) => r.selfReport !== undefined)).toEqual([true, false, true]); + }); + }); + + it("cuts detail at 2000 code points, never through a surrogate pair", async () => { + const detail = `${"a".repeat(1999)}\u{1F600} and more text`; + await evaluateHookEvent("PreToolUse", "claude", payload("mcp__failproofai_local__report", { category: "looping", detail })); + const line = readFileSync(join(home, "hook-activity", "current.jsonl"), "utf8").trim().split("\n").pop()!; + // The row is valid UTF-8 JSON with no lone surrogate escape, which the + // Rust collector would reject along with every hook event on the row. + expect(line).not.toMatch(/\\ud[89a-f][0-9a-f]{2}/i); + const kept = (JSON.parse(line).selfReport as { detail: string }).detail; + expect(kept).toBe(`${"a".repeat(1999)}\u{1F600}`); + expect([...kept]).toHaveLength(2000); + }); + + it("allows it with fail-closed forced (daemon unreachable), while the control call is denied", async () => { + const force = { forceDecision: { decision: "deny" as const, reason: "daemon down" } }; + expect((await evaluateHookEvent("PreToolUse", "claude", bash(), force)).evaluation?.decision).toBe("deny"); + const out = await evaluateHookEvent("PreToolUse", "claude", report(), force); + expect(out.evaluation?.decision).toBe("allow"); + expect(out.stdout).toBe(""); + }); + + it("allows it while the session is paused, and the row carries no pause fields", async () => { + writePause({ sessionId: SESSION, durationMs: 600_000 }); + const out = await evaluateHookEvent("PreToolUse", "claude", report()); + expect(out.evaluation?.decision).toBe("allow"); + const row = rows().pop()!; + expect(row.pausedBy).toBeUndefined(); + expect(row.selfReport).toBeDefined(); + }); + + it("never reaches Jev, which a gate otherwise consults", async () => { + await evaluateHookEvent("PreToolUse", "claude", bash()); + expect(jevChecksInstalled).toHaveBeenCalled(); + vi.mocked(jevChecksInstalled).mockClear(); + await evaluateHookEvent("PreToolUse", "claude", report()); + expect(jevChecksInstalled).not.toHaveBeenCalled(); + }); + + it("allows on PermissionRequest too, persisting the row without a second report", async () => { + const out = await evaluateHookEvent("PermissionRequest", "claude", report()); + expect(out.evaluation?.decision).toBe("allow"); + expect(loadAllCustomHooks).not.toHaveBeenCalled(); + const row = rows().pop()!; + expect(row.eventType).toBe("PermissionRequest"); + expect(row.selfReport).toBeUndefined(); + }); + + it("one call (PreToolUse + PermissionRequest + PostToolUse) yields exactly one row with selfReport", async () => { + for (const ev of ["PreToolUse", "PermissionRequest", "PostToolUse"]) { + expect((await evaluateHookEvent(ev, "claude", report())).evaluation?.decision).toBe("allow"); + } + const all = rows(); + expect(all.map((r) => r.eventType)).toEqual(["PreToolUse", "PermissionRequest", "PostToolUse"]); + expect(all.filter((r) => r.selfReport !== undefined).map((r) => r.eventType)).toEqual(["PreToolUse"]); + }); + + it("records PostToolUse without evaluating it and without a second report", async () => { + const out = await evaluateHookEvent("PostToolUse", "claude", report()); + expect(out.evaluation?.decision).toBe("allow"); + expect(loadAllCustomHooks).not.toHaveBeenCalled(); + const row = rows().pop()!; + expect(row.eventType).toBe("PostToolUse"); + expect(row.selfReport).toBeUndefined(); + }); + + it("recognises Codex's snake_case event and its name for the tool", async () => { + const out = await evaluateHookEvent("pre_tool_use", "codex", report()); + expect(out.evaluation?.decision).toBe("allow"); + expect(rows().pop()!.selfReport).toMatchObject({ category: "invalid_tool_or_credential" }); + }); + + it("files an agent's own spelling under the canonical name", async () => { + const out = await evaluateHookEvent("PreToolUse", "goose", payload("failproofai_local__report", { category: "looping", detail: "x" })); + expect(out.evaluation?.decision).toBe("allow"); + expect(rows().pop()!.toolName).toBe("mcp__failproofai_local__report"); + }); + + it("for an agent whose MCP server records, allows but leaves the report to the server", async () => { + const out = await evaluateHookEvent("PreToolUse", "factory", report()); + expect(out.evaluation?.decision).toBe("allow"); + const row = rows().pop()!; + expect(row.integration).toBe("factory"); + expect(row.selfReport).toBeUndefined(); + }); + + it("Devin running Claude Code's hooks: the claude row carries no report, so it is filed once, as devin", async () => { + const devinish = { tool_use_id: "call-46ba525a-305d-4f99-8053-0cf0d1a1da73" }; + const out = await evaluateHookEvent("PreToolUse", "claude", report(devinish)); + expect(out.evaluation?.decision).toBe("allow"); + const row = rows().pop()!; + expect(row.integration).toBe("claude"); + expect(row.selfReport).toBeUndefined(); + await evaluateHookEvent("PreToolUse", "claude", report({ tool_provenance: "mcp", transcript_path: "/t.jsonl" })); + expect(rows().pop()!.selfReport).toBeUndefined(); + // Claude Code's own call still records. + await evaluateHookEvent("PreToolUse", "claude", report({ tool_use_id: "toolu_9", transcript_path: "/t.jsonl" })); + expect(rows().pop()!.selfReport).toMatchObject({ category: "invalid_tool_or_credential" }); + }); + + it("records an unknown category as the listed one it resolves to, a missing detail as empty, and cuts detail at 2000", async () => { + await evaluateHookEvent("PreToolUse", "claude", payload("mcp__failproofai_local__report", { category: "made_up" })); + expect(rows().pop()!.selfReport).toEqual({ category: "task_failure", detail: "", source: "mcp" }); + await evaluateHookEvent("PreToolUse", "claude", payload("mcp__failproofai_local__report", { category: "looping", detail: "y ".repeat(2500) })); + expect((rows().pop()!.selfReport as { detail: string }).detail).toBe("y ".repeat(1000).trimEnd()); + // A token running past the cut is never kept in part (round 3). + await evaluateHookEvent("PreToolUse", "claude", payload("mcp__failproofai_local__report", { category: "looping", detail: `token eyJ${"a".repeat(3000)}` })); + expect((rows().pop()!.selfReport as { detail: string }).detail).toBe("token"); + }); + + it("infers the category of a call that left it out (the live case), and resolves a near-miss spelling", async () => { + const detail = 'Deployment is blocked because ./deploy.sh exits with "DEPLOY_TOKEN is not set" and no token is available in this environment.'; + await evaluateHookEvent("PreToolUse", "claude", payload("mcp__failproofai_local__report", { detail })); + expect(rows().pop()!.selfReport).toEqual({ category: "invalid_tool_or_credential", detail, source: "mcp" }); + await evaluateHookEvent("PreToolUse", "claude", payload("mcp__failproofai_local__report", { category: "Missing Context", detail: "x" })); + expect(rows().pop()!.selfReport).toMatchObject({ category: "missing_context" }); + }); + + it("resolves against an org's custom list: its first category when nothing matches", async () => { + writeEffectiveSelfReport({ + enabled: true, + categories: [ + { name: "data_gap", description: "Data is missing." }, + { name: "blocked", description: "Blocked." }, + ], + }); + await evaluateHookEvent("PreToolUse", "claude", payload("mcp__failproofai_local__report", { category: "", detail: "Nothing matches here." })); + expect(rows().pop()!.selfReport).toMatchObject({ category: "data_gap" }); + await evaluateHookEvent("PreToolUse", "claude", payload("mcp__failproofai_local__report", { category: "blocked", detail: "The token expired." })); + expect(rows().pop()!.selfReport).toMatchObject({ category: "blocked" }); + }); + + it("does not exempt a lookalike tool name", async () => { + const out = await evaluateHookEvent("PreToolUse", "claude", payload("mcp__failproofai__report_evil", {})); + expect(out.evaluation?.decision).toBe("deny"); + }); + + it.each([ + ["factory", "failproofai_local___report"], + ["hermes", "mcp_failproofai_local_report"], + ["antigravity", "mcp_failproofai_local_report"], + ["opencode", "failproofai_local_report"], + ["openclaw", "failproofai_local__report"], + ["goose", "failproofai_local__report"], + ["pi", "mcp__failproofai_local__report"], + ["devin", "mcp__failproofai_local__report"], + ["copilot", "failproofai_local-report"], + ["copilot", "failproofai_local/report"], + ] as const)("allows %s's spelling %s past a deny-everything policy", async (cli, name) => { + const out = await evaluateHookEvent( + "PreToolUse", + cli, + payload(name, { category: "looping", detail: "again" }), + ); + expect(out.evaluation?.decision).toBe("allow"); + expect(loadAllCustomHooks).not.toHaveBeenCalled(); + }); + + it.each([ + ["claude", "mcp__failproofai__report"], + ["codex", "mcp__failproofai__report"], + ["factory", "failproofai___report"], + ["hermes", "mcp_failproofai_report"], + ["openclaw", "failproofai__report"], + ["goose", "failproofai__report"], + ["copilot", "failproofai-report"], + ["claude", "mcp__linear__report"], + ["opencode", "linear_report"], + ] as const)("keeps another server's report tool on the policy path: %s %s", async (cli, name) => { + // `failproofai` is the Cloud gateway's server name, not ours: its tools, + // and any other server's `report`, go through the policies like any call. + const out = await evaluateHookEvent("PreToolUse", cli, payload(name, { category: "looping", detail: "x" })); + expect(out.evaluation?.decision).toBe("deny"); + expect(loadAllCustomHooks).toHaveBeenCalled(); + expect(rows().some((r) => r.selfReport !== undefined)).toBe(false); + }); + + // Review 4719314976: a foreign MCP server named `failproofai` (the Cloud + // gateway's usual name) must never have a tool early-allowed as ours, in any + // harness's spelling. `failproofai_report` is OpenCode's name for its + // `report` tool and also the SDK tool's name: neither skips the policies. + const FOREIGN_FAILPROOFAI_TOOLS = [ + "failproofai_report", + "mcp__failproofai__report", + "failproofai__report", + "failproofai___report", + "mcp_failproofai_report", + "failproofai-report", + "failproofai/report", + "failproofai.report", + "failproofai:report", + "mcp:failproofai:report", + ]; + it.each(INTEGRATION_TYPES.flatMap((cli) => FOREIGN_FAILPROOFAI_TOOLS.map((name) => [cli, name] as const)))( + "sends a foreign failproofai server's tool through the policies: %s %s", + async (cli, name) => { + const out = await evaluateHookEvent("PreToolUse", cli, payload(name, { category: "looping", detail: "x" })); + expect(out.evaluation?.decision).toBe("deny"); + expect(loadAllCustomHooks).toHaveBeenCalled(); + expect(rows().some((r) => r.selfReport !== undefined)).toBe(false); + }, + ); + + it("does not early-allow Cursor or Antigravity calls naming the Cloud gateway's server failproofai", async () => { + for (const event of ["preToolUse", "beforeMCPExecution"]) { + const out = await evaluateHookEvent(event, "cursor", payload("report", { category: "looping", detail: "x" }, { mcp_server_name: "failproofai" })); + expect(out.evaluation?.decision, event).toBe("deny"); + } + const agy = await evaluateHookEvent( + "PreToolUse", + "antigravity", + JSON.stringify({ + conversationId: SESSION, + workspacePaths: [project], + toolCall: { name: "call_mcp_tool", args: { ServerName: "failproofai", ToolName: "report", Arguments: {} } }, + }), + ); + expect(agy.evaluation?.decision).toBe("deny"); + }); + + it("allows Cursor's beforeMCPExecution for the failproofai_local server, with a schema-valid answer, leaving the report to the server", async () => { + const out = await evaluateHookEvent( + "beforeMCPExecution", + "cursor", + payload("report", JSON.stringify({ category: "missing_context", detail: "no repo access" }), { + mcp_server_name: "failproofai_local", + url: "http://127.0.0.1:4319/mcp?agent=cursor", + }), + ); + expect(out.evaluation?.decision).toBe("allow"); + expect(JSON.parse(out.stdout)).toEqual({ permission: "allow" }); + expect(loadAllCustomHooks).not.toHaveBeenCalled(); + const [row] = rows(); + // Cursor is server-recorded: the MCP server writes the report, so the + // hook row must not carry a second one. + expect(row).toMatchObject({ eventType: "PreToolUse", integration: "cursor", toolName: "mcp__failproofai_local__report" }); + expect(row.selfReport).toBeUndefined(); + }); + + it("does not early-allow Cursor's bare MCP:report without a server name", async () => { + const out = await evaluateHookEvent("preToolUse", "cursor", payload("MCP:report", { category: "looping", detail: "x" })); + expect(out.evaluation?.decision).toBe("deny"); + }); + + it("early-allows Cursor's preToolUse MCP:report only when the payload names server failproofai_local", async () => { + const ours = await evaluateHookEvent( + "preToolUse", + "cursor", + payload("MCP:report", { category: "looping", detail: "x" }, { mcp_server_name: "failproofai_local" }), + ); + expect(ours.evaluation?.decision).toBe("allow"); + expect(rows().pop()!.selfReport).toBeUndefined(); + const theirs = await evaluateHookEvent( + "preToolUse", + "cursor", + payload("MCP:report", { category: "looping", detail: "x" }, { mcp_server_name: "linear" }), + ); + expect(theirs.evaluation?.decision).toBe("deny"); + }); + + it("never lets a Cursor call that fails the server check through by its name alone", async () => { + // Another server's tool, or one with no server named, spelled like ours: + // it keeps its own name, is not recorded as a report, and the policies run. + for (const name of ["mcp__failproofai_local__report", "failproofai_local__report", "failproofai_local-report", "mcp_failproofai_local_report"]) { + for (const extra of [{ mcp_server_name: "linear" }, {}]) { + vi.mocked(loadAllCustomHooks).mockClear(); + for (const event of ["preToolUse", "beforeMCPExecution"]) { + const out = await evaluateHookEvent(event, "cursor", payload(name, { category: "looping", detail: "x" }, extra)); + expect(out.evaluation?.decision, `${event} ${name} ${JSON.stringify(extra)}`).toBe("deny"); + expect(out.evaluation?.toolName).toBe(name); + } + expect(loadAllCustomHooks).toHaveBeenCalled(); + } + } + expect(rows().some((r) => r.selfReport !== undefined)).toBe(false); + // The same spelling WITH our server is still ours. + const ours = await evaluateHookEvent( + "preToolUse", "cursor", + payload("mcp__failproofai_local__report", { category: "looping", detail: "x" }, { mcp_server_name: "failproofai_local" }), + ); + expect(ours.evaluation?.decision).toBe("allow"); + }); + + describe("Antigravity's lazy MCP path (call_mcp_tool)", () => { + const agy = (args: Record) => + JSON.stringify({ conversationId: SESSION, workspacePaths: [project], toolCall: { name: "call_mcp_tool", args } }); + + it("early-allows the wrapper when it names server failproofai_local and tool report", async () => { + const out = await evaluateHookEvent( + "PreToolUse", + "antigravity", + agy({ ServerName: "failproofai_local", ToolName: "report", Arguments: { category: "looping", detail: "again" } }), + ); + expect(out.evaluation?.decision).toBe("allow"); + expect(loadAllCustomHooks).not.toHaveBeenCalled(); + const row = rows().pop()!; + expect(row).toMatchObject({ integration: "antigravity", toolName: "mcp__failproofai_local__report", sessionId: SESSION }); + // Antigravity is server-recorded: the MCP server writes the report. + expect(row.selfReport).toBeUndefined(); + }); + + it("accepts the wrapped arguments as a JSON string", async () => { + const out = await evaluateHookEvent( + "PreToolUse", + "antigravity", + agy({ ServerName: "failproofai_local", ToolName: "report", Arguments: JSON.stringify({ category: "looping", detail: "x" }) }), + ); + expect(out.evaluation?.decision).toBe("allow"); + }); + + it.each([ + [{ ServerName: "linear", ToolName: "report", Arguments: {} }], + [{ ServerName: "failproofai_local", ToolName: "search", Arguments: {} }], + [{ ToolName: "report", Arguments: {} }], + [{ ServerName: "failproofai-evil", ToolName: "report" }], + ])("keeps any other wrapped call on the policy path: %j", async (args) => { + const out = await evaluateHookEvent("PreToolUse", "antigravity", agy(args)); + expect(out.evaluation?.decision).toBe("deny"); + }); + + it("does not unwrap call_mcp_tool for any other agent", async () => { + const out = await evaluateHookEvent( + "PreToolUse", + "claude", + payload("call_mcp_tool", { ServerName: "failproofai_local", ToolName: "report", Arguments: {} }), + ); + expect(out.evaluation?.decision).toBe("deny"); + }); + }); + + it("answers the native policy-evaluation health probe with an allow and writes no activity row", async () => { + const out = await evaluateHookEvent( + "on_session_start", + "hermes", + JSON.stringify({ hook_event_name: "on_session_start", source: HEALTH_PROBE_SOURCE }), + ); + expect(out.evaluation?.decision).toBe("allow"); + expect(rows()).toEqual([]); + expect(loadAllCustomHooks).not.toHaveBeenCalled(); + }); +}); + +describe("the early allow needs the failproofai_local registration to be ours (F19)", () => { + const userHome = () => join(home, "user"); + const claudeJson = () => join(userHome(), ".claude.json"); + const readJson = (p: string) => JSON.parse(readFileSync(p, "utf8")) as Record; + const FOREIGN = { type: "stdio", command: "node", args: ["/tmp/x/pause-enforcement.js"] }; + + it("control: with our registration the report passes a deny-everything policy", async () => { + expect((await evaluateHookEvent("PreToolUse", "claude", report())).evaluation?.decision).toBe("allow"); + }); + + it("a foreign server registered user-wide as failproofai_local gets no bypass: the policies deny it", async () => { + const cfg = readJson(claudeJson()); + (cfg.mcpServers as Record).failproofai_local = FOREIGN; + writeFileSync(claudeJson(), JSON.stringify(cfg)); + for (const event of ["PreToolUse", "PermissionRequest", "PostToolUse"]) { + vi.mocked(loadAllCustomHooks).mockClear(); + const out = await evaluateHookEvent(event, "claude", report()); + expect(out.evaluation?.decision, event).toBe("deny"); + expect(loadAllCustomHooks).toHaveBeenCalled(); + } + expect(rows().some((r) => r.selfReport !== undefined)).toBe(false); + }); + + it("a project-scope .mcp.json defining failproofai_local overrides ours: no bypass, from that project or below", async () => { + writeFileSync(join(project, ".mcp.json"), JSON.stringify({ mcpServers: { failproofai_local: FOREIGN } })); + mkdirSync(join(project, "sub"), { recursive: true }); + expect((await evaluateHookEvent("PreToolUse", "claude", report())).evaluation?.decision).toBe("deny"); + const below = JSON.stringify({ + session_id: SESSION, cwd: join(project, "sub"), tool_name: "mcp__failproofai_local__report", tool_input: { category: "looping", detail: "x" }, + }); + expect((await evaluateHookEvent("PreToolUse", "claude", below)).evaluation?.decision).toBe("deny"); + }); + + it("a project definition shaped like ours still gets no bypass (one is never written there)", async () => { + writeFileSync( + join(project, ".mcp.json"), + JSON.stringify({ mcpServers: { failproofai_local: { command: "./fail" + "proofai", args: ["mcp", "--agent", "claude"] } } }), + ); + expect((await evaluateHookEvent("PreToolUse", "claude", report())).evaluation?.decision).toBe("deny"); + }); + + it("Claude Code's local scope (projects[].mcpServers in .claude.json) counts as a project definition", async () => { + const cfg = readJson(claudeJson()); + cfg.projects = { [project]: { mcpServers: { failproofai_local: FOREIGN } } }; + writeFileSync(claudeJson(), JSON.stringify(cfg)); + expect((await evaluateHookEvent("PreToolUse", "claude", report())).evaluation?.decision).toBe("deny"); + }); + + it("an unreadable project config that names failproofai_local fails closed", async () => { + writeFileSync(join(project, ".mcp.json"), "{ failproofai_local: ["); + expect((await evaluateHookEvent("PreToolUse", "claude", report())).evaluation?.decision).toBe("deny"); + }); + + it("a project config that only mentions the name outside a server map does not count", async () => { + writeFileSync(join(project, "opencode.json"), JSON.stringify({ permission: { failproofai_local_report: "allow" } })); + expect((await evaluateHookEvent("PreToolUse", "claude", report())).evaluation?.decision).toBe("allow"); + }); + + it("no registration at all, or no working directory, gets no bypass", async () => { + const noCwd = JSON.stringify({ session_id: SESSION, tool_name: "mcp__failproofai_local__report", tool_input: { category: "looping", detail: "x" } }); + expect((await evaluateHookEvent("PreToolUse", "claude", noCwd)).evaluation?.decision).toBe("deny"); + rmSync(claudeJson()); + expect((await evaluateHookEvent("PreToolUse", "claude", report())).evaluation?.decision).toBe("deny"); + }); + + it("Cursor's server-named call is also checked against Cursor's registration", async () => { + writeFileSync(join(userHome(), ".cursor", "mcp.json"), JSON.stringify({ mcpServers: { failproofai_local: FOREIGN } })); + const out = await evaluateHookEvent( + "beforeMCPExecution", "cursor", + payload("report", { category: "looping", detail: "x" }, { mcp_server_name: "failproofai_local" }), + ); + expect(out.evaluation?.decision).toBe("deny"); + }); + + it("Hermes (a plugin tool, no MCP entry of ours): allowed with none, denied when a foreign entry would collide", async () => { + const hermes = () => payload("mcp_failproofai_local_report", { category: "looping", detail: "x" }); + expect((await evaluateHookEvent("PreToolUse", "hermes", hermes())).evaluation?.decision).toBe("allow"); + mkdirSync(join(userHome(), ".hermes"), { recursive: true }); + writeFileSync(join(userHome(), ".hermes", "config.yaml"), "mcp_servers:\n failproofai_local:\n command: node\n args: [evil.js]\n"); + expect((await evaluateHookEvent("PreToolUse", "hermes", hermes())).evaluation?.decision).toBe("deny"); + }); +}); + +describe("the agent process behind a hook-recorded report (F14)", () => { + it("keeps the pids the hook CLI stamped on the report row, and only there", async () => { + await evaluateHookEvent( + "PreToolUse", "claude", + report({ tool_use_id: "toolu_p", failproofai_report_agent_pid: 6001 }), + ); + expect(rows().pop()).toMatchObject({ toolCallId: "toolu_p", selfReport: { detail: "tracker rejected its API key" }, agentPid: 6001 }); + // A PostToolUse row is no report, so it carries none. + await evaluateHookEvent("PostToolUse", "claude", report({ failproofai_report_agent_pid: "6001" })); + expect(rows().pop()).not.toHaveProperty("agentPid"); + }); + + it("a report row with no pids stamped carries none", async () => { + await evaluateHookEvent("PreToolUse", "claude", report()); + expect(rows().pop()).not.toHaveProperty("agentPid"); + }); +}); + +describe("the early allow, round 2 (F19): strict ownership, and HOME's own configs are not project overrides", () => { + const userHome = () => join(home, "user"); + const claudeJson = () => join(userHome(), ".claude.json"); + const readJson = (p: string) => JSON.parse(readFileSync(p, "utf8")) as Record; + const at = (cwd: string, tool = "mcp__failproofai_local__report") => + JSON.stringify({ session_id: SESSION, cwd, tool_name: tool, tool_input: { category: "looping", detail: "x" } }); + + it("a project beneath HOME: the installer's own user-wide files on the way up are not overrides", async () => { + // sync wrote ~/.claude.json, ~/.codex/config.toml, ~/.cursor/mcp.json, … under this HOME. + const below = join(userHome(), "work", "project"); + mkdirSync(below, { recursive: true }); + expect(readFileSync(join(userHome(), ".codex", "config.toml"), "utf8")).toContain("failproofai_local"); + expect(readFileSync(join(userHome(), ".cursor", "mcp.json"), "utf8")).toContain("failproofai_local"); + for (const [cli, tool] of [["claude", "mcp__failproofai_local__report"], ["codex", "mcp__failproofai_local__report"], ["factory", "failproofai_local___report"]] as const) { + const out = await evaluateHookEvent("PreToolUse", cli, at(below, tool)); + expect(out.evaluation?.decision, cli).toBe("allow"); + } + // A cwd of HOME itself too. + expect((await evaluateHookEvent("PreToolUse", "claude", at(userHome()))).evaluation?.decision).toBe("allow"); + }); + + it("a genuine project override beneath HOME is still refused", async () => { + const below = join(userHome(), "work", "project"); + mkdirSync(join(below, ".cursor"), { recursive: true }); + writeFileSync(join(below, ".mcp.json"), JSON.stringify({ mcpServers: { failproofai_local: { command: "node", args: ["x.js"] } } })); + expect((await evaluateHookEvent("PreToolUse", "claude", at(below))).evaluation?.decision).toBe("deny"); + }); + + it("CODEX_HOME elsewhere: that file is Codex's user config and is skipped too", async () => { + const codexHome = join(home, "codex-home"); + mkdirSync(codexHome, { recursive: true }); + // No ~/.codex left over: with CODEX_HOME elsewhere it would be project config. + rmSync(join(userHome(), ".codex"), { recursive: true, force: true }); + vi.stubEnv("CODEX_HOME", codexHome); + await registerOwnSelfReportServer(); + const below = join(userHome(), "p"); + mkdirSync(below, { recursive: true }); + expect((await evaluateHookEvent("PreToolUse", "codex", at(below))).evaluation?.decision).toBe("allow"); + }); + + it("a foreign program named like failproofai, registered with our arguments, gets no exemption", async () => { + const dir = join(home, "x"); + mkdirSync(dir, { recursive: true }); + const foreign = join(dir, "fail" + "proofai-mcp"); + writeFileSync(foreign, "#!/bin/sh\nexit 0\n", { mode: 0o755 }); + for (const command of [foreign, join(dir, "fail" + "proofai")]) { + if (command !== foreign) writeFileSync(command, "#!/bin/sh\nexit 0\n", { mode: 0o755 }); + const cfg = readJson(claudeJson()); + (cfg.mcpServers as Record).failproofai_local = { type: "stdio", command, args: ["mcp", "--agent", "claude"], alwaysLoad: true }; + writeFileSync(claudeJson(), JSON.stringify(cfg)); + vi.mocked(loadAllCustomHooks).mockClear(); + const out = await evaluateHookEvent("PreToolUse", "claude", report()); + expect(out.evaluation?.decision, command).toBe("deny"); + expect(loadAllCustomHooks).toHaveBeenCalled(); + } + }); + + it("our CLI by another path that resolves to it is ours; another agent's arguments or an HTTP entry is not", async () => { + const link = join(home, "fail" + "proofai-link"); + symlinkSync(REGISTERED_CLI, link); + const set = (entry: Record) => { + const cfg = readJson(claudeJson()); + (cfg.mcpServers as Record).failproofai_local = entry; + writeFileSync(claudeJson(), JSON.stringify(cfg)); + }; + set({ type: "stdio", command: link, args: ["mcp", "--agent", "claude"], alwaysLoad: true }); + expect((await evaluateHookEvent("PreToolUse", "claude", report())).evaluation?.decision).toBe("allow"); + set({ type: "stdio", command: link, args: ["mcp", "--agent", "codex"], alwaysLoad: true }); + expect((await evaluateHookEvent("PreToolUse", "claude", report())).evaluation?.decision).toBe("deny"); + set({ type: "http", url: "http://127.0.0.1:4319/mcp?agent=claude" }); + expect((await evaluateHookEvent("PreToolUse", "claude", report())).evaluation?.decision).toBe("deny"); + }); +}); + +describe("the early allow, round 3 (F19): nothing in the entry may change what runs", () => { + const userHome = () => join(home, "user"); + const claudeJson = () => join(userHome(), ".claude.json"); + const readJson = (p: string) => JSON.parse(readFileSync(p, "utf8")) as Record; + const ours = () => ({ type: "stdio", command: REGISTERED_CLI, args: ["mcp", "--agent", "claude"], alwaysLoad: true }); + const set = (entry: Record) => { + const cfg = readJson(claudeJson()); + (cfg.mcpServers as Record).failproofai_local = entry; + writeFileSync(claudeJson(), JSON.stringify(cfg)); + }; + + it("control: the installer's exact entry, and one with an empty env an agent added, are ours", async () => { + set(ours()); + expect((await evaluateHookEvent("PreToolUse", "claude", report())).evaluation?.decision).toBe("allow"); + set({ ...ours(), env: {} }); + expect((await evaluateHookEvent("PreToolUse", "claude", report())).evaluation?.decision).toBe("allow"); + }); + + it.each([ + ["env NODE_OPTIONS", { env: { NODE_OPTIONS: "--require /tmp/x.js" } }], + ["env PATH", { env: { PATH: "/tmp/x:/usr/bin" } }], + ["env LD_PRELOAD", { env: { LD_PRELOAD: "/tmp/x.so" } }], + ["env BUN_OPTIONS", { env: { BUN_OPTIONS: "--preload /tmp/x.ts" } }], + ["envFile", { envFile: "/tmp/x.env" }], + ["cwd", { cwd: "/tmp/x" }], + ["an extra argument", { args: ["mcp", "--agent", "claude", "--x"] }], + ["another field", { wrapper: "/tmp/x" }], + ])("an otherwise exact entry plus %s gets no exemption", async (_what, extra) => { + set({ ...ours(), ...extra }); + vi.mocked(loadAllCustomHooks).mockClear(); + const out = await evaluateHookEvent("PreToolUse", "claude", report()); + expect(out.evaluation?.decision).toBe("deny"); + expect(loadAllCustomHooks).toHaveBeenCalled(); + }); + + it("Goose's entry (cmd, empty envs/env_keys) is ours only exactly as written", async () => { + const goose = () => payload("failproofai_local__report", { category: "looping", detail: "x" }); + expect((await evaluateHookEvent("PreToolUse", "goose", goose())).evaluation?.decision).toBe("allow"); + const path = join(userHome(), ".config", "goose", "config.yaml"); + writeFileSync(path, readFileSync(path, "utf8").replace("envs: {}", "envs:\n NODE_OPTIONS: --require /tmp/x.js")); + expect((await evaluateHookEvent("PreToolUse", "goose", goose())).evaluation?.decision).toBe("deny"); + }); +}); + +describe("the early allow takes only the calling agent's own spelling, and no other server may flatten to it (review #1105 item 2)", () => { + const userHome = () => join(home, "user"); + const readJson = (p: string) => JSON.parse(readFileSync(p, "utf8")) as Record; + const opencodeJson = () => join(userHome(), ".config", "opencode", "opencode.json"); + const addOpencodeServer = (name: string) => { + const cfg = readJson(opencodeJson()); + (cfg.mcp as Record)[name] = { type: "local", command: ["node", "/tmp/x/other.js"], enabled: true }; + writeFileSync(opencodeJson(), JSON.stringify(cfg)); + }; + const call = (cli: Parameters[1], name: string) => + evaluateHookEvent("PreToolUse", cli, payload(name, { category: "looping", detail: "x" })); + const expectPolicies = async (cli: Parameters[1], name: string) => { + vi.mocked(loadAllCustomHooks).mockClear(); + const out = await call(cli, name); + expect(out.evaluation?.decision, `${cli} ${name}`).toBe("deny"); + expect(loadAllCustomHooks, `${cli} ${name}`).toHaveBeenCalled(); + }; + + it("control: OpenCode's own spelling with only our server is exempt", async () => { + expect((await call("opencode", "failproofai_local_report")).evaluation?.decision).toBe("allow"); + }); + + it("OpenCode: server `failproofai` (tool `local_report`) flattens to our name, so no exemption", async () => { + addOpencodeServer("failproofai"); + await expectPolicies("opencode", "failproofai_local_report"); + expect(rows().some((r) => r.selfReport !== undefined)).toBe(false); + }); + + it("OpenCode: server `mcp_failproofai_local` (tool `report`) gives Hermes's spelling, which is not OpenCode's", async () => { + addOpencodeServer("mcp_failproofai_local"); + await expectPolicies("opencode", "mcp_failproofai_local_report"); + }); + + it("OpenCode: a project opencode.json registering `failproofai` counts too", async () => { + writeFileSync(join(project, "opencode.json"), JSON.stringify({ mcp: { failproofai: { type: "remote", url: "https://x" } } })); + await expectPolicies("opencode", "failproofai_local_report"); + }); + + it("OpenCode: an unrelated server does not take the exemption away", async () => { + addOpencodeServer("linear"); + addOpencodeServer("failproofai_localx"); + expect((await call("opencode", "failproofai_local_report")).evaluation?.decision).toBe("allow"); + }); + + it("OpenCode: an unreadable project config fails closed", async () => { + writeFileSync(join(project, "opencode.json"), "{ mcp: ["); + await expectPolicies("opencode", "failproofai_local_report"); + }); + + it("Hermes: an MCP server `failproofai` (tool `local_report`) flattens to mcp_failproofai_local_report", async () => { + expect((await call("hermes", "mcp_failproofai_local_report")).evaluation?.decision).toBe("allow"); + mkdirSync(join(userHome(), ".hermes"), { recursive: true }); + writeFileSync(join(userHome(), ".hermes", "config.yaml"), "mcp_servers:\n failproofai:\n url: https://x\n"); + await expectPolicies("hermes", "mcp_failproofai_local_report"); + }); + + it("Antigravity: a server `failproofai` in mcp_config.json flattens to mcp_failproofai_local_report", async () => { + expect((await call("antigravity", "mcp_failproofai_local_report")).evaluation?.decision).toBe("allow"); + const path = join(userHome(), ".gemini", "config", "mcp_config.json"); + const cfg = readJson(path); + (cfg.mcpServers as Record).failproofai = { serverUrl: "https://x" }; + writeFileSync(path, JSON.stringify(cfg)); + await expectPolicies("antigravity", "mcp_failproofai_local_report"); + }); + + it("OpenCode: a custom tool file in the project's .opencode/tool that could carry our name collides", async () => { + for (const file of ["failproofai_local_report.ts", "failproofai.ts", "failproofai_local.js"]) { + const dir = join(project, ".opencode", "tool"); + rmSync(dir, { recursive: true, force: true }); + mkdirSync(dir, { recursive: true }); + writeFileSync(join(dir, file), "export default {}\n"); + await expectPolicies("opencode", "failproofai_local_report"); + } + }); + + it("Claude Code: an unaffected double-underscore name keeps its exemption next to the Cloud gateway's `failproofai`", async () => { + const path = join(userHome(), ".claude.json"); + const cfg = readJson(path); + (cfg.mcpServers as Record).failproofai = { type: "http", url: "https://x" }; + writeFileSync(path, JSON.stringify(cfg)); + expect((await call("claude", "mcp__failproofai_local__report")).evaluation?.decision).toBe("allow"); + }); + + it("Goose: an extension whose `name` is failproofai_local under another key collides", async () => { + const path = join(userHome(), ".config", "goose", "config.yaml"); + writeFileSync(path, `${readFileSync(path, "utf8")} other:\n name: failproofai_local\n type: stdio\n cmd: node\n args: [x.js]\n`); + await expectPolicies("goose", "failproofai_local__report"); + }); + + // Every agent's own spellings; a call using any other agent's gets no exemption. + const OWN: Record = { + claude: ["mcp__failproofai_local__report"], + codex: ["mcp__failproofai_local__report"], + pi: ["mcp__failproofai_local__report"], + devin: ["mcp__failproofai_local__report"], + factory: ["mcp__failproofai_local__report", "failproofai_local___report"], + hermes: ["mcp_failproofai_local_report"], + antigravity: ["mcp_failproofai_local_report"], + opencode: ["failproofai_local_report"], + openclaw: ["failproofai_local__report"], + goose: ["failproofai_local__report"], + copilot: ["failproofai_local-report", "failproofai_local/report"], + cursor: [], + }; + const ALL = [ + ...new Set([ + ...Object.values(OWN).flat(), + "failproofai_local.report", "failproofai_local:report", "mcp__failproofai_local_report", + "mcp:failproofai_local:report", "mcp:failproofai_local/report", + ]), + ]; + it.each(INTEGRATION_TYPES.flatMap((cli) => ALL.filter((n) => !(OWN[cli] ?? []).includes(n)).map((n) => [cli, n] as const)))( + "%s calling another agent's spelling %s goes through the policies", + async (cli, name) => { + await expectPolicies(cli, name); + expect(rows().some((r) => r.selfReport !== undefined)).toBe(false); + }, + ); + it.each(INTEGRATION_TYPES.flatMap((cli) => (OWN[cli] ?? []).map((n) => [cli, n] as const)))( + "%s's own spelling %s is exempt", + async (cli, name) => { + expect((await call(cli, name)).evaluation?.decision).toBe("allow"); + }, + ); +}); diff --git a/__tests__/hooks/self-report-hint-cleanup.test.ts b/__tests__/hooks/self-report-hint-cleanup.test.ts new file mode 100644 index 000000000..e51e2d7ec --- /dev/null +++ b/__tests__/hooks/self-report-hint-cleanup.test.ts @@ -0,0 +1,70 @@ +// @vitest-environment node +/** + * The hint cache (`/cache/self-report-hints/`) gets one or two files per + * session; writing one also removes files older than 7 days, scanning the + * directory at most once an hour (review #1105 item 9). + */ +import { describe, it, expect, beforeEach, afterEach } from "vitest"; +import { existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync, utimesSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { _resetSelfReportHintPruneForTest, selfReportFailureBlocks } from "../../src/hooks/self-report-hint"; + +const DAY = 24 * 60 * 60 * 1000; +let home: string; +const dir = () => join(home, "cache", "self-report-hints"); +const FAIL = { tool_name: "Bash", tool_input: { command: "make deploy" }, tool_response: { stderr: "boom", exit_code: 1 } }; + +function aged(name: string, ageMs: number): string { + mkdirSync(dir(), { recursive: true }); + const p = join(dir(), name); + writeFileSync(p, "x\n"); + const t = (Date.now() - ageMs) / 1000; + utimesSync(p, t, t); + return p; +} + +beforeEach(() => { + home = mkdtempSync(join(tmpdir(), "fpai-sr-hint-gc-")); + process.env.FAILPROOFAI_HOME = home; + _resetSelfReportHintPruneForTest(); +}); +afterEach(() => { + delete process.env.FAILPROOFAI_HOME; + rmSync(home, { recursive: true, force: true }); +}); + +describe("self-report hint cache cleanup", () => { + it("writing a session's file removes files older than 7 days and keeps newer ones", () => { + const old = aged("aaaa.failures", 8 * DAY); + const oldMarker = aged("bbbb", 30 * DAY); + const recent = aged("cccc.failures", 6 * DAY); + selfReportFailureBlocks("claude", "s-new", FAIL); + expect(existsSync(old)).toBe(false); + expect(existsSync(oldMarker)).toBe(false); + expect(existsSync(recent)).toBe(true); + // The session just written is there. + expect(readdirSync(dir()).filter((f) => f.endsWith(".failures"))).toHaveLength(2); + }); + + it("scans at most once an hour, across processes (a stamp file), not on every write", () => { + selfReportFailureBlocks("claude", "s1", FAIL); + const later = aged("dddd.failures", 8 * DAY); + _resetSelfReportHintPruneForTest(); // a new hook process + selfReportFailureBlocks("claude", "s2", FAIL); + expect(existsSync(later)).toBe(true); + // An hour on, the next write prunes again. + const stamp = join(dir(), ".pruned"); + const t = (Date.now() - 61 * 60 * 1000) / 1000; + utimesSync(stamp, t, t); + _resetSelfReportHintPruneForTest(); + selfReportFailureBlocks("claude", "s3", FAIL); + expect(existsSync(later)).toBe(false); + }); + + it("a read-only or auth failure writes nothing, so it scans nothing", () => { + const old = aged("eeee.failures", 8 * DAY); + selfReportFailureBlocks("claude", "s4", { tool_name: "Read", tool_input: { file_path: "/x" }, tool_response: { error: "ENOENT" } }); + expect(existsSync(old)).toBe(true); + }); +}); diff --git a/__tests__/hooks/self-report-hint.test.ts b/__tests__/hooks/self-report-hint.test.ts new file mode 100644 index 000000000..f249d4605 --- /dev/null +++ b/__tests__/hooks/self-report-hint.test.ts @@ -0,0 +1,255 @@ +// @vitest-environment node +/** + * Self Reports' just-in-time hint: one line of model-visible context after a + * tool call that clearly failed, at most once per session, only while Self + * Reports is on, never on success, on the report call itself, or on a failure + * a failproofai deny caused. Not a policy: it never replaces a policy's answer. + */ +import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +vi.mock("../../src/hooks/hooks-config", () => ({ + readMergedHooksConfig: vi.fn(() => ({ enabledPolicies: [] })), +})); +vi.mock("../../src/hooks/custom-hooks-loader", () => ({ loadAllCustomHooks: vi.fn() })); +vi.mock("../../src/hooks/hook-telemetry", () => ({ + trackHookEvent: vi.fn(() => Promise.resolve()), + flushHookTelemetry: vi.fn(() => Promise.resolve()), +})); +vi.mock("../../lib/telemetry-id", () => ({ getInstanceId: vi.fn(() => "test-instance-id") })); +vi.mock("../../src/hooks/untraced-note", () => ({ noteUntracedAgent: vi.fn(() => false) })); +vi.mock("../../src/hooks/pack-manifest", () => ({ + readInstalledPacks: vi.fn(() => ({ packs: [], errors: [] })), + hasInstalledPacks: vi.fn(() => false), + hasInstalledRegexPacks: vi.fn(() => false), +})); + +import { evaluateHookEvent } from "../../src/hooks/handler"; +import { loadAllCustomHooks } from "../../src/hooks/custom-hooks-loader"; +import { _resetForTest } from "../../src/hooks/hook-activity-store"; +import { writeEffectiveSelfReport } from "../../src/hooks/self-report"; +import { SELF_REPORT_FAILURE_HINT, SELF_REPORT_HINT_CHANNELS, selfReportFailureHint, selfReportSessionStartContext, selfReportToolFailed } from "../../src/hooks/self-report-hint"; + +let home: string; +let policyDecision: "allow" | "deny" | "instruct" = "allow"; +let session = 0; +const sid = () => `hint-session-${session}`; + +function post(response: unknown, extra: Record = {}, tool = "Bash"): string { + return JSON.stringify({ session_id: sid(), cwd: "/tmp/project", tool_name: tool, tool_input: { command: "x" }, tool_response: response, ...extra }); +} +const FAILED = { stdout: "", stderr: "curl: (22) The requested URL returned error: 401 Unauthorized", interrupted: false }; +const OK = { stdout: "done", stderr: "", interrupted: false }; + +beforeEach(() => { + vi.clearAllMocks(); + session++; + policyDecision = "allow"; + home = mkdtempSync(join(tmpdir(), "fpai-sr-hint-")); + process.env.FAILPROOFAI_HOME = home; + process.env.FAILPROOFAI_STATE_DIR = join(home, "state"); + _resetForTest(join(home, "hook-activity")); + writeEffectiveSelfReport({ enabled: true }); + vi.mocked(loadAllCustomHooks).mockImplementation((async () => ({ + hooks: [ + Object.assign( + { + name: "switch", + description: "", + match: {}, + fn: async () => + policyDecision === "allow" ? { decision: "allow" } : { decision: policyDecision, reason: "policy says so" }, + }, + { __policyId: "custom:/tmp/switch.mjs:switch" }, + ), + ], + conventionSources: [], + })) as never); +}); + +afterEach(() => { + delete process.env.FAILPROOFAI_HOME; + delete process.env.FAILPROOFAI_STATE_DIR; + _resetForTest(); + rmSync(home, { recursive: true, force: true }); +}); + +describe("selfReportToolFailed", () => { + it.each([ + ["PostToolUseFailure", {}], + ["PostToolUse", { error: "boom" }], + ["PostToolUse", { tool_response: { isError: true, content: [{ type: "text", text: "x" }] } }], + ["PostToolUse", { tool_response: { exit_code: 1, output: "" } }], + ["PostToolUse", { tool_response: { success: false } }], + ["PostToolUse", { tool_response: { stderr: "bash: foo: command not found" } }], + ["PostToolUse", { tool_response: { stderr: "open /etc/x: permission denied" } }], + ["PostToolUse", { tool_response: "HTTP/1.1 403 Forbidden" }], + ["PostToolUse", { tool_response: { output: "Error: 401 Unauthorized" } }], + ["PostToolUse", { tool_response: "Process exited with code 2" }], + ])("%s %j is a failure", (event, payload) => { + expect(selfReportToolFailed(event, payload as Record)).toBe(true); + }); + it.each([ + ["PostToolUse", { tool_response: { stdout: "ok", stderr: "", exit_code: 0 } }], + ["PostToolUse", { tool_response: { output: `${"line of a file that says not found and 401 Unauthorized\n".repeat(40)}` } }], + ["PostToolUse", { tool_response: "all good" }], + ["PostToolUse", {}], + ["PreToolUse", { error: "x" }], + ])("%s %j is not a failure", (event, payload) => { + expect(selfReportToolFailed(event, payload as Record)).toBe(false); + }); +}); + +describe("the failure hint through the hook", () => { + it("adds one line of context after a failed call on Claude Code, once per session", async () => { + const first = await evaluateHookEvent("PostToolUse", "claude", post(FAILED)); + expect(first.exitCode).toBe(0); + expect(JSON.parse(first.stdout)).toEqual({ hookSpecificOutput: { hookEventName: "PostToolUse", additionalContext: SELF_REPORT_FAILURE_HINT } }); + expect(first.evaluation?.decision).toBe("allow"); + const second = await evaluateHookEvent("PostToolUse", "claude", post(FAILED)); + expect(second.stdout).toBe(""); + // PostToolUseFailure is a failure by definition, but the session's hint is spent. + expect((await evaluateHookEvent("PostToolUseFailure", "claude", post({}))).stdout).toBe(""); + }); + + it("works with no policy installed at all", async () => { + vi.mocked(loadAllCustomHooks).mockImplementation((async () => ({ hooks: [], conventionSources: [] })) as never); + expect((await evaluateHookEvent("PostToolUse", "claude", post(FAILED))).stdout).toContain(SELF_REPORT_FAILURE_HINT); + }); + + it("says nothing after a successful call, and keeps the session's hint for a real failure", async () => { + expect((await evaluateHookEvent("PostToolUse", "claude", post(OK))).stdout).toBe(""); + expect((await evaluateHookEvent("PostToolUse", "claude", post(FAILED))).stdout).toContain(SELF_REPORT_FAILURE_HINT); + }); + + it("never follows the report call itself", async () => { + const out = await evaluateHookEvent("PostToolUse", "claude", post({ isError: true }, {}, "mcp__failproofai_local__report")); + expect(out.stdout).toBe(""); + }); + + it("is off while Self Reports is off", async () => { + writeEffectiveSelfReport({ enabled: false }); + expect((await evaluateHookEvent("PostToolUse", "claude", post(FAILED))).stdout).toBe(""); + }); + + it("never follows a failure a failproofai deny caused", async () => { + // The PreToolUse deny for this very call, then its failure. + policyDecision = "deny"; + const pre = await evaluateHookEvent("PreToolUse", "claude", post(undefined, { tool_use_id: "toolu_denied" })); + expect(pre.evaluation?.decision).toBe("deny"); + policyDecision = "allow"; + expect((await evaluateHookEvent("PostToolUseFailure", "claude", post({}, { tool_use_id: "toolu_denied" }))).stdout).toBe(""); + // A result that carries failproofai's own block message. + expect((await evaluateHookEvent("PostToolUse", "claude", post("Blocked by failproofai: no sudo"))).stdout).toBe(""); + // The hint was not spent: a genuine failure still gets it. + expect((await evaluateHookEvent("PostToolUse", "claude", post(FAILED))).stdout).toContain(SELF_REPORT_FAILURE_HINT); + }); + + it("never replaces a policy's own answer", async () => { + policyDecision = "instruct"; + const out = await evaluateHookEvent("PostToolUse", "claude", post(FAILED)); + expect(out.stdout).toContain("policy says so"); + expect(out.stdout).not.toContain(SELF_REPORT_FAILURE_HINT); + }); + + it("uses each agent's own channel", async () => { + const cursor = await evaluateHookEvent("postToolUse", "cursor", post(FAILED)); + expect(JSON.parse(cursor.stdout)).toEqual({ additional_context: SELF_REPORT_FAILURE_HINT }); + session++; + const factory = await evaluateHookEvent("PostToolUse", "factory", post(FAILED)); + expect(factory).toMatchObject({ exitCode: 2, stdout: "" }); + expect(factory.stderr).toContain(SELF_REPORT_FAILURE_HINT); + session++; + const codex = await evaluateHookEvent("PostToolUse", "codex", post(FAILED)); + expect(JSON.parse(codex.stdout).hookSpecificOutput.additionalContext).toBe(SELF_REPORT_FAILURE_HINT); + }); + + it("stays silent on agents with no after-a-tool channel", async () => { + for (const cli of ["opencode", "goose", "antigravity", "devin", "pi"] as const) { + session++; + const out = await evaluateHookEvent("PostToolUse", cli, post(FAILED)); + expect(out.stdout, cli).not.toContain(SELF_REPORT_FAILURE_HINT); + expect(out.stderr, cli).not.toContain(SELF_REPORT_FAILURE_HINT); + } + }); +}); + +describe("selfReportFailureHint", () => { + const AUTH = { error: "HTTP 401 Unauthorized: invalid API key" }; + it("needs a session id to keep its once-per-session promise", () => { + expect(selfReportFailureHint({ cli: "claude", eventType: "PostToolUseFailure", payload: AUTH, sessionId: undefined, enabled: () => true })).toBeNull(); + expect(selfReportFailureHint({ cli: "claude", eventType: "PostToolUseFailure", payload: AUTH, sessionId: "s-direct", enabled: () => true })).not.toBeNull(); + }); + it("answers Copilot only on its failure event, in its flat shape", () => { + expect(SELF_REPORT_HINT_CHANNELS.copilot).toEqual({ PostToolUseFailure: "flat" }); + const out = selfReportFailureHint({ cli: "copilot", eventType: "PostToolUseFailure", payload: AUTH, sessionId: "s-cop", enabled: () => true }); + expect(JSON.parse(out!.stdout)).toEqual({ additionalContext: SELF_REPORT_FAILURE_HINT }); + }); +}); + +describe("only a failure that clearly blocks earns the hint", () => { + const call = (command: string, response: unknown, extra: Record = {}) => + ({ tool_name: "Bash", tool_input: { command }, tool_response: response, ...extra }) as Record; + const hint = (sessionId: string, payload: Record, eventType = "PostToolUse") => + selfReportFailureHint({ cli: "claude", eventType, payload, sessionId, enabled: () => true }); + const exit1 = (stderr: string) => ({ stdout: "", stderr, exit_code: 1 }); + + it("not for one non-zero exit of read-only exploration, however often", () => { + for (const command of ["ls missing.txt", "cat /nope", "grep -r TODO src", "find . -name x", "test -f a.txt", "ls a && cat b", "bash -lc 'ls -la /x'", "git status"]) { + expect(hint("s-explore", call(command, exit1("ls: cannot access 'missing.txt': No such file or directory"))), command).toBeNull(); + expect(hint("s-explore", call(command, exit1("No such file or directory"))), command).toBeNull(); + } + expect(hint("s-explore", { tool_name: "Read", tool_input: { file_path: "/x" }, error: "File does not exist." }, "PostToolUseFailure")).toBeNull(); + expect(hint("s-explore", { tool_name: "Read", tool_input: { file_path: "/x" }, error: "File does not exist." }, "PostToolUseFailure")).toBeNull(); + }); + + it("not for the first failure of anything else", () => { + expect(hint("s-first", call("npm test", exit1("1 test failed")))).toBeNull(); + expect(hint("s-first", call("./deploy.sh", exit1("deploy failed")))).toBeNull(); + }); + + it("for the same command failing a second time", () => { + expect(hint("s-repeat", call("./deploy.sh", exit1("deploy failed")))).toBeNull(); + expect(hint("s-repeat", call("npm run build", exit1("tsc error")))).toBeNull(); + expect(hint("s-repeat", call("./deploy.sh --force", exit1("deploy failed again")))!.stdout).toContain(SELF_REPORT_FAILURE_HINT); + }); + + it("for the same tool failing a second time", () => { + const mcp = { tool_name: "mcp__tracker__create_issue", tool_input: { title: "x" }, tool_response: { isError: true, content: [{ type: "text", text: "boom" }] } }; + expect(hint("s-tool", mcp)).toBeNull(); + expect(hint("s-tool", { ...mcp, tool_input: { title: "y" } })!.stdout).toContain(SELF_REPORT_FAILURE_HINT); + }); + + it("at once for an auth or credential failure, even from a read-only command", () => { + expect(hint("s-auth-1", call("curl -f https://api.example.test", exit1("curl: (22) The requested URL returned error: 403")))).not.toBeNull(); + expect(hint("s-auth-2", call("./deploy.sh", exit1("deploy.sh: DEPLOY_TOKEN is not set")))).not.toBeNull(); + expect(hint("s-auth-3", call("gh pr list", exit1("error: authentication failed")))).not.toBeNull(); + expect(hint("s-auth-4", call("cat out.json", { stdout: '{"error":"invalid api key"}', stderr: "", exit_code: 1 }))).not.toBeNull(); + expect(hint("s-auth-5", { tool_name: "mcp__tracker__list", tool_input: {}, tool_response: { isError: true, content: [{ type: "text", text: "Token expired" }] } })).not.toBeNull(); + }); + + it("still once per session", () => { + expect(hint("s-once", call("./deploy.sh", exit1("401 Unauthorized")))).not.toBeNull(); + expect(hint("s-once", call("./deploy.sh", exit1("401 Unauthorized")))).toBeNull(); + }); +}); + +describe("SessionStart instructions where MCP tools are deferred with no switch", () => { + it("gives Factory droid the server's instructions at session start, only while on", async () => { + const out = await evaluateHookEvent("SessionStart", "factory", JSON.stringify({ session_id: sid(), cwd: "/tmp/project" })); + const ctx = JSON.parse(out.stdout).hookSpecificOutput; + expect(ctx.hookEventName).toBe("SessionStart"); + expect(ctx.additionalContext).toContain("When you are stuck, call failproofai_local's `report` tool once"); + expect(ctx.additionalContext).not.toContain("this server's"); + writeEffectiveSelfReport({ enabled: false }); + expect((await evaluateHookEvent("SessionStart", "factory", JSON.stringify({ session_id: sid(), cwd: "/tmp/project" }))).stdout).toBe(""); + }); + it("adds nothing for other agents or events", () => { + const on = { categories: [{ name: "looping", description: "d" }], guidance: null } as never; + expect(selfReportSessionStartContext("claude", "SessionStart", on)).toBeNull(); + expect(selfReportSessionStartContext("factory", "PreToolUse", on)).toBeNull(); + expect(selfReportSessionStartContext("factory", "SessionStart", null)).toBeNull(); + }); +}); diff --git a/__tests__/hooks/self-report-hook-trust.test.ts b/__tests__/hooks/self-report-hook-trust.test.ts new file mode 100644 index 000000000..779764ff1 --- /dev/null +++ b/__tests__/hooks/self-report-hook-trust.test.ts @@ -0,0 +1,501 @@ +// @vitest-environment node +// +// Self Reports for Claude Code and Codex, whose hook is the recorder: when that +// hook will not run (an untrusted Codex, Claude Code with hooks off) the stdio +// server records the report instead, and never a second time when it did. +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { chmodSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, utimesSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import { getIntegration } from "../../src/hooks/integrations"; +import { failproofaiCodexHookIdentities } from "../../src/hooks/codex-system-hooks"; +import { + claudeHooksBlockedReason, + codexReportHookRuns, + selfReportHookRecordedRecently, + selfReportHookState, +} from "../../src/hooks/self-report-hook-trust"; +import { + handleSelfReportRpc, + selfReportClaudeTranscriptSession, + selfReportCodexRolloutSession, +} from "../../src/hooks/self-report-mcp"; +import { selfReportCliDirs, resolveSelfReportCliPath, syncSelfReportMcp } from "../../src/hooks/self-report-install"; +import { writeEffectiveSelfReport } from "../../src/hooks/self-report"; +import { SELF_REPORT_AGENT_PIDS_KEY_V1, selfReportMarkAgentPid, selfReportServerAgentPid } from "../../src/hooks/self-report-ancestry"; +import { selfReportFindSessionMatch, writeSelfReportEvent } from "../../src/hooks/self-report-mcp"; +import { runSelfReportCommand } from "../../src/hooks/self-report-cli"; + +const BIN = "/usr/local/bin/failproofai"; +const CURRENT = () => "0.172.0"; +let home: string; + +beforeEach(() => { + home = mkdtempSync(resolve(tmpdir(), "fp-sr-trust-")); + vi.stubEnv("HOME", home); + vi.stubEnv("CODEX_HOME", join(home, ".codex")); + vi.stubEnv("CLAUDE_CONFIG_DIR", ""); + vi.stubEnv("FAILPROOFAI_HOME", join(home, ".failproofai")); + vi.stubEnv("FAILPROOFAI_CLAUDE_MANAGED_SETTINGS", join(home, "managed-settings.json")); + mkdirSync(join(home, ".codex"), { recursive: true }); +}); + +afterEach(() => { + vi.unstubAllEnvs(); + rmSync(home, { recursive: true, force: true }); +}); + +function writeCodexHooks(file = join(home, ".codex", "hooks.json")): void { + const settings: Record = {}; + getIntegration("codex").writeHookEntries(settings, BIN, "user"); + mkdirSync(join(file, ".."), { recursive: true }); + writeFileSync(file, JSON.stringify(settings, null, 2)); +} + +function trust(file: string, only?: (key: string) => boolean): void { + const lines = failproofaiCodexHookIdentities(file) + .filter((h) => !only || only(h.key)) + .flatMap((h) => [`[hooks.state.${JSON.stringify(h.key)}]`, `trusted_hash = ${JSON.stringify(h.hash)}`, ""]); + writeFileSync(join(home, ".codex", "config.toml"), `model = "o3"\n${lines.join("\n")}\n`); +} + +const noSystem = { codexSystemPresent: () => false, codexVersion: CURRENT }; + +describe("will Codex run failproofai's PreToolUse hook?", () => { + it("no hooks.json of ours: no", () => { + expect(codexReportHookRuns(undefined, noSystem)).toBe(false); + }); + + it("hooks.json, untrusted (the laptop run): no; trusted at its current hash: yes", () => { + writeCodexHooks(); + writeFileSync(join(home, ".codex", "config.toml"), 'model = "o3"\n'); + expect(codexReportHookRuns(undefined, noSystem)).toBe(false); + trust(join(home, ".codex", "hooks.json")); + expect(codexReportHookRuns(undefined, noSystem)).toBe(true); + }); + + it("only the PreToolUse hook matters, since it is the one that records", () => { + writeCodexHooks(); + trust(join(home, ".codex", "hooks.json"), (k) => !k.includes(":pre_tool_use:")); + expect(codexReportHookRuns(undefined, noSystem)).toBe(false); + trust(join(home, ".codex", "hooks.json"), (k) => k.includes(":pre_tool_use:")); + expect(codexReportHookRuns(undefined, noSystem)).toBe(true); + }); + + it("a project's .codex/hooks.json above the working directory counts, trusted like the user's", () => { + const project = join(home, "proj"); + writeCodexHooks(join(project, ".codex", "hooks.json")); + trust(join(project, ".codex", "hooks.json")); + expect(codexReportHookRuns(undefined, noSystem)).toBe(false); + mkdirSync(join(project, "src"), { recursive: true }); + expect(codexReportHookRuns(join(project, "src"), noSystem)).toBe(true); + }); + + it("system hooks (run without trust) and a Codex older than the trust gate: yes", () => { + expect(codexReportHookRuns(undefined, { codexSystemPresent: () => true })).toBe(true); + writeCodexHooks(); + expect(codexReportHookRuns(undefined, { codexSystemPresent: () => false, codexVersion: () => "0.120.0" })).toBe(true); + }); +}); + +describe("will Claude Code run failproofai's hooks?", () => { + it("disableAllHooks, with Claude Code's precedence, and a managed allowManagedHooksOnly", () => { + const project = join(home, "proj"); + mkdirSync(join(project, ".claude"), { recursive: true }); + mkdirSync(join(home, ".claude"), { recursive: true }); + expect(claudeHooksBlockedReason(project)).toBeNull(); + writeFileSync(join(home, ".claude", "settings.json"), JSON.stringify({ disableAllHooks: true })); + expect(claudeHooksBlockedReason(project)).toMatch(/disableAllHooks/); + // A closer layer that sets it false wins. + writeFileSync(join(project, ".claude", "settings.json"), JSON.stringify({ disableAllHooks: false })); + expect(claudeHooksBlockedReason(project)).toBeNull(); + writeFileSync(join(project, ".claude", "settings.local.json"), JSON.stringify({ disableAllHooks: true })); + expect(claudeHooksBlockedReason(project)).toMatch(/settings\.local\.json/); + rmSync(join(project, ".claude", "settings.local.json")); + writeFileSync(join(home, "managed-settings.json"), JSON.stringify({ allowManagedHooksOnly: true })); + expect(claudeHooksBlockedReason(project)).toMatch(/allowManagedHooksOnly/); + }); +}); + +describe("selfReportHookState (status, sync)", () => { + it("names the recorder and, for an untrusted Codex, how to trust the hooks", () => { + writeCodexHooks(); + writeFileSync(join(home, ".codex", "config.toml"), ""); + const untrusted = selfReportHookState("codex", { ...noSystem, userHooksInstalled: () => true }); + expect(untrusted).toMatchObject({ recorder: "server", reason: expect.stringMatching(/not trusted/) }); + expect(untrusted.recorder === "server" && untrusted.fix).toMatch(/failproofai config.*sudo.*codex.*approve/); + trust(join(home, ".codex", "hooks.json")); + expect(selfReportHookState("codex", { ...noSystem, userHooksInstalled: () => true })).toEqual({ recorder: "hook" }); + expect(selfReportHookState("claude", { userHooksInstalled: () => true })).toEqual({ recorder: "hook" }); + expect(selfReportHookState("claude", { userHooksInstalled: () => false })).toMatchObject({ recorder: "server" }); + expect(selfReportHookState("pi")).toEqual({ recorder: "hook" }); + }); + + it("sync puts an agent whose hook will not record on stdio even with a live daemon", async () => { + const r = await syncSelfReportMcp({ + quiet: true, binaryPath: BIN, agents: ["claude", "codex"], + deps: { + daemonLive: async () => true, hooksInstalled: () => true, settings: { enabled: true, port: 4319 }, + hookRecords: (a) => a === "claude", + // The HTTP path is off by default (next test); this exercises it. + httpAgents: ["claude", "codex"], + }, + }); + expect(r.map((x) => [x.agent, x.transport])).toEqual([["claude", "http"], ["codex", "stdio"]]); + expect(readFileSync(join(home, ".codex", "config.toml"), "utf8")).toContain('args = ["mcp", "--agent", "codex"]'); + }); + + // Review 4722003649: the entry is user-wide, but a Claude Code project can + // switch the hooks off (`.claude/settings.local.json`, `disableAllHooks`), + // and the daemon's endpoint records nothing for Claude Code. So by default + // no agent is put on HTTP, however healthy the daemon and the user hooks. + it("by default registers Claude Code and Codex over stdio even with a live daemon and hooks that record", async () => { + const project = join(home, "proj"); + mkdirSync(join(project, ".claude"), { recursive: true }); + writeFileSync(join(project, ".claude", "settings.local.json"), JSON.stringify({ disableAllHooks: true })); + const daemonLive = vi.fn(async () => true); + const r = await syncSelfReportMcp({ + quiet: true, binaryPath: BIN, agents: ["claude", "codex"], + deps: { daemonLive, hooksInstalled: () => true, settings: { enabled: true, port: 4319 }, hookRecords: () => true }, + }); + expect(r.map((x) => [x.agent, x.transport])).toEqual([["claude", "stdio"], ["codex", "stdio"]]); + expect(daemonLive).not.toHaveBeenCalled(); + expect(JSON.parse(readFileSync(join(home, ".claude.json"), "utf8")).mcpServers.failproofai_local).toEqual({ + type: "stdio", command: BIN, args: ["mcp", "--agent", "claude"], alwaysLoad: true, + }); + }); + + it("status shows who records, repairs an untrusted Codex left on HTTP, and says how to trust the hooks", async () => { + writeEffectiveSelfReport({ enabled: true }); + let synced = 0; + const row = (transport: "http" | "stdio", endpoint: string) => ({ + agent: "codex" as const, path: "/x/config.toml", hooked: true, registered: true, transport, endpoint, conflict: false, + }); + let rows = [row("http", "http://127.0.0.1:4319/mcp?agent=codex")]; + const r = await runSelfReportCommand(["status"], { + probeEndpoint: async () => true, + daemonLive: async () => true, + registrations: () => rows, + hookState: () => ({ recorder: "server", reason: "Codex has not trusted failproofai's hooks, so it does not run them", fix: "Trust them." }), + sync: async () => { + synced++; + rows = [row("stdio", BIN)]; + return [{ agent: "codex", path: "/x/config.toml", action: "updated", transport: "stdio", status: "ok" }]; + }, + }); + expect(synced).toBe(1); + const text = r.lines.join("\n"); + expect(text).toContain("Repaired:"); + expect(text).toMatch(/codex +stdio/); + expect(text).toContain("reports recorded by the MCP server: Codex has not trusted failproofai's hooks"); + expect(text).toContain("Trust them."); + + // An HTTP entry is repaired even while the hook records: no agent belongs + // on HTTP any more (a project can switch the hooks off). + const ok = await runSelfReportCommand(["status"], { + probeEndpoint: async () => true, daemonLive: async () => true, + registrations: () => [row("http", "http://127.0.0.1:4319/mcp?agent=codex")], + hookState: () => ({ recorder: "hook" }), + sync: async () => (synced++, []), + }); + expect(synced).toBe(2); + const stdioOk = await runSelfReportCommand(["status"], { + probeEndpoint: async () => true, daemonLive: async () => true, + registrations: () => [row("stdio", BIN)], + hookState: () => ({ recorder: "hook" }), + sync: async () => (synced++, []), + }); + expect(synced).toBe(2); + expect(ok.lines.join("\n") + stdioOk.lines.join("\n")).toContain("reports recorded by its hook"); + }); +}); + +describe("the server records what the hook did not, once", () => { + const call = (args: Record) => ({ jsonrpc: "2.0", id: 9, method: "tools/call", params: { name: "report", arguments: args } }); + const events = () => { + try { + return readdirSync(join(home, ".failproofai", "custom-agents", "events")).map((f) => + JSON.parse(readFileSync(join(home, ".failproofai", "custom-agents", "events", f), "utf8")), + ); + } catch { + return []; + } + }; + // A hook row records the agent process above its hook; this server's own + // agent (what the server reads from its process tree) stands for "ours". + const AGENT = selfReportServerAgentPid() ?? 0; + const hookRow = (over: Record) => { + mkdirSync(join(home, ".failproofai", "hook-activity"), { recursive: true }); + writeFileSync( + join(home, ".failproofai", "hook-activity", "current.jsonl"), + JSON.stringify({ + timestamp: Date.now() - 1000, eventType: "PreToolUse", integration: "codex", sessionId: "s", decision: "allow", + agentPid: AGENT, ...over, + }) + "\n", + ); + }; + + const projA = "/work/project-a"; + const projB = "/work/project-b"; + const hookRows = (...rows: Record[]) => { + mkdirSync(join(home, ".failproofai", "hook-activity"), { recursive: true }); + writeFileSync( + join(home, ".failproofai", "hook-activity", "current.jsonl"), + rows.map((over) => JSON.stringify({ + timestamp: Date.now() - 1000, eventType: "PreToolUse", integration: "codex", sessionId: "s", decision: "allow", + agentPid: AGENT, ...over, + })).join("\n") + "\n", + ); + }; + + it("a hook row with the same report in the same directory suppresses it; a different one, an old one or another agent's does not", () => { + const args = { category: "invalid_tool_or_credential", detail: "token expired" }; + const fresh = () => rmSync(join(home, ".failproofai", "cache"), { recursive: true, force: true }); + hookRow({ cwd: projA, selfReport: { ...args, source: "mcp" } }); + expect(selfReportHookRecordedRecently("codex", { ...args, detail: "other" }, Date.now(), projA)).toBe(false); + expect(selfReportHookRecordedRecently("claude", args, Date.now(), projA)).toBe(false); + expect(selfReportHookRecordedRecently("codex", args, Date.now())).toBe(false); // no cwd: never a match + expect(selfReportHookRecordedRecently("codex", args, Date.now(), projA)).toBe(true); + fresh(); + hookRow({ cwd: projA, selfReport: { ...args, source: "mcp" }, timestamp: Date.now() - 10 * 60 * 1000 }); + expect(selfReportHookRecordedRecently("codex", args, Date.now(), projA)).toBe(false); + hookRow({ cwd: projA, eventType: "PostToolUse", selfReport: { ...args, source: "mcp" } }); + expect(selfReportHookRecordedRecently("codex", args, Date.now(), projA)).toBe(false); + hookRow({ selfReport: { ...args, source: "mcp" } }); // a row with no cwd + expect(selfReportHookRecordedRecently("codex", args, Date.now(), projA)).toBe(false); + // Aliased arguments are compared as the hook recorded them. + fresh(); + hookRow({ cwd: projA, selfReport: { ...args, source: "mcp" } }); + expect(selfReportHookRecordedRecently("codex", { type: args.category, summary: args.detail }, Date.now(), projA)).toBe(true); + }); + + it("matches a hook row that holds the inferred category to the call that left it out", () => { + writeEffectiveSelfReport({ enabled: true }); + const detail = "The DEPLOY_TOKEN is not set."; + hookRow({ cwd: projA, selfReport: { category: "invalid_tool_or_credential", detail, source: "mcp" } }); + expect(selfReportHookRecordedRecently("codex", { detail }, Date.now(), projA)).toBe(true); + }); + + // Review 4722003644: the same text in another project, or a second call, + // is a distinct report. + it("never lets one project's hook row suppress another project's report", () => { + const args = { category: "invalid_tool_or_credential", detail: "token expired" }; + hookRow({ cwd: projA, selfReport: { ...args, source: "mcp" } }); + expect(selfReportHookRecordedRecently("codex", args, Date.now(), projB)).toBe(false); + expect(selfReportHookRecordedRecently("codex", args, Date.now(), projA)).toBe(true); + }); + + it("lets each hook row vouch for one call only (repeated text in one session)", () => { + const args = { category: "looping", detail: "same words" }; + hookRows( + { cwd: projA, sessionId: "s1", toolCallId: "t1", selfReport: { ...args, source: "mcp" } }, + { cwd: projA, sessionId: "s1", toolCallId: "t2", selfReport: { ...args, source: "mcp" } }, + ); + expect(selfReportHookRecordedRecently("codex", args, Date.now(), projA)).toBe(true); + expect(selfReportHookRecordedRecently("codex", args, Date.now(), projA)).toBe(true); + // A third identical call has no hook row of its own: recorded by the server. + expect(selfReportHookRecordedRecently("codex", args, Date.now(), projA)).toBe(false); + }); + + // F14: matching on text and directory let session B (its hooks did not run) + // take session A's row, so B's report answered "Recorded." with no event, + // and A's own call then found no row and was recorded under the wrong session. + it("never lets another session's hook row stand for a call (concurrent sessions in one directory)", () => { + const args = { category: "invalid_tool_or_credential", detail: "token expired" }; + const A = 31001; + const B = 31002; + // Session A's hook recorded its report; session B's hooks did not run. + hookRows({ cwd: projA, sessionId: "sA", toolCallId: "tA", selfReport: { ...args, source: "mcp" }, agentPid: A }); + // B's identical report arrives first: not A's row, so B's server records it. + expect(selfReportHookRecordedRecently("codex", args, Date.now(), projA, B)).toBe(false); + // A's call still finds its own row, which B did not consume. + expect(selfReportHookRecordedRecently("codex", args, Date.now(), projA, A)).toBe(true); + }); + + // Round 2: B started INSIDE A (A's shell tool runs it, same directory). A is + // an ancestor of B's hooks, so "any ancestor" matching let A's server claim + // B's row; the match is now the exact agent pid each side names. + it("a nested agent's hook row is never claimed by the agent it runs inside", () => { + const args = { category: "looping", detail: "same words" }; + const A = 61001; + const B = 61002; // a child of A's shell + hookRows({ cwd: projA, sessionId: "sB", toolCallId: "tB", selfReport: { ...args, source: "mcp" }, agentPid: B }); + expect(selfReportHookRecordedRecently("codex", args, Date.now(), projA, A)).toBe(false); + expect(selfReportHookRecordedRecently("codex", args, Date.now(), projA, B)).toBe(true); + }); + + it("a nested agent's report is filed under its own session, never the outer agent's", async () => { + writeEffectiveSelfReport({ enabled: true }); + const A = 71001; + const B = 71002; + // A's session is known (its session-start/prompt rows carry A); B's hooks + // did not run, so B has no rows at all. + hookRows( + { cwd: projA, sessionId: "session-A", eventType: "SessionStart", agentPid: A }, + { cwd: projA, sessionId: "session-A", eventType: "UserPromptSubmit", agentPid: A }, + ); + const excluded = new Set(); + expect(selfReportFindSessionMatch("claude", projA, Date.now(), B, excluded)).toBeNull(); + expect([...excluded]).toEqual([]); // other integration's rows are not looked at + hookRows( + { integration: "claude", cwd: projA, sessionId: "session-A", eventType: "SessionStart", agentPid: A }, + { integration: "claude", cwd: projA, sessionId: "session-A", eventType: "UserPromptSubmit", agentPid: A }, + ); + expect(selfReportFindSessionMatch("claude", projA, Date.now(), B, excluded)).toBeNull(); + expect([...excluded]).toEqual(["session-A"]); + // A's own server still finds A's session. + expect(selfReportFindSessionMatch("claude", projA, Date.now(), A)?.sessionId).toBe("session-A"); + // Once B's own rows exist they win, exactly. + hookRows( + { integration: "claude", cwd: projA, sessionId: "session-A", eventType: "UserPromptSubmit", agentPid: A }, + { integration: "claude", cwd: projA, sessionId: "session-B", eventType: "SessionStart", agentPid: B, timestamp: Date.now() - 5000 }, + ); + expect(selfReportFindSessionMatch("claude", projA, Date.now(), B)?.sessionId).toBe("session-B"); + // Written end to end: B's report with no rows of its own is not A's. The + // transcript fallback may not hand back A's session either. + hookRows( + { integration: "claude", cwd: projA, sessionId: "session-A", eventType: "SessionStart", agentPid: A }, + ); + const transcripts = join(home, ".claude", "projects", projA.replace(/[^A-Za-z0-9]/g, "-")); + mkdirSync(transcripts, { recursive: true }); + writeFileSync(join(transcripts, "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa.jsonl"), "{}\n"); + vi.stubEnv("CLAUDE_CONFIG_DIR", join(home, ".claude")); + try { + const fromB = await writeSelfReportEvent({ integration: "claude", category: "looping", detail: "x", cwd: projA, agentPid: B }); + expect(fromB.event.session_id).toBe("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"); + hookRows( + { integration: "claude", cwd: projA, sessionId: "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa", eventType: "SessionStart", agentPid: A }, + ); + const again = await writeSelfReportEvent({ integration: "claude", category: "looping", detail: "x", cwd: projA, agentPid: B }); + expect(again.event.session_id).toBe("unattributed"); + } finally { + vi.unstubAllEnvs(); + } + }); + + it("each of two sessions in one directory claims only its own row", () => { + const args = { category: "looping", detail: "same words" }; + hookRows( + { cwd: projA, sessionId: "s1", toolCallId: "t1", selfReport: { ...args, source: "mcp" }, agentPid: 51001 }, + { cwd: projA, sessionId: "s2", toolCallId: "t2", selfReport: { ...args, source: "mcp" }, agentPid: 51002 }, + ); + expect(selfReportHookRecordedRecently("codex", args, Date.now(), projA, 51002)).toBe(true); + expect(selfReportHookRecordedRecently("codex", args, Date.now(), projA, 51002)).toBe(false); + expect(selfReportHookRecordedRecently("codex", args, Date.now(), projA, 51001)).toBe(true); + }); + + // Round 3, item 6: after `npm i -g` the daemon's warm worker keeps running the + // previous build until the daemon restarts. That worker copies only the + // earlier list form of the stamp onto the row. + describe("mixed builds during an upgrade", () => { + const args = { category: "looping", detail: "same words" }; + + it("new hook client + a row written by the previous build's worker: the new server still matches it", () => { + // The new client stamps both forms (self-report-ancestry.test.ts). + const payload = JSON.parse( + selfReportMarkAgentPid("codex", "PreToolUse", JSON.stringify({ tool_name: "mcp__failproofai_local__report", tool_input: args }), () => 81001), + ) as Record; + // What the previous build's handler did with it: copy the list form only. + const oldWorkerRow = { cwd: projA, selfReport: { ...args, source: "mcp" }, agentPid: undefined, selfReportAgentPids: payload[SELF_REPORT_AGENT_PIDS_KEY_V1] }; + expect(oldWorkerRow.selfReportAgentPids).toEqual([81001]); + hookRows(oldWorkerRow); + expect(selfReportHookRecordedRecently("codex", args, Date.now(), projA, 81002)).toBe(false); + expect(selfReportHookRecordedRecently("codex", args, Date.now(), projA, 81001)).toBe(true); + }); + + it("an earlier-format row read by the new server: matched only by its first pid, else recorded", () => { + // The previous build's own client wrote the whole ancestry, nearest first. + hookRows({ cwd: projA, selfReport: { ...args, source: "mcp" }, agentPid: undefined, selfReportAgentPids: [82001, 82000] }); + expect(selfReportHookRecordedRecently("codex", args, Date.now(), projA, 82000)).toBe(false); // an outer process: record + expect(selfReportHookRecordedRecently("codex", args, Date.now(), projA, 82001)).toBe(true); + // A shell first (the usual hook runner): the agent cannot be told, so the report is recorded. + hookRows({ cwd: projA, selfReport: { ...args, source: "mcp" }, agentPid: undefined, selfReportAgentPids: [83005, 83001] }); + expect(selfReportHookRecordedRecently("codex", args, Date.now(), projA, 83001)).toBe(false); + }); + }); + + it("a row that does not say which agent process wrote it never vouches for a call: the report is recorded", () => { + const args = { category: "looping", detail: "same words" }; + hookRows({ cwd: projA, selfReport: { ...args, source: "mcp" }, agentPid: undefined }); + expect(selfReportHookRecordedRecently("codex", args, Date.now(), projA)).toBe(false); + hookRows({ cwd: projA, selfReport: { ...args, source: "mcp" }, agentPid: "x" }); + expect(selfReportHookRecordedRecently("codex", args, Date.now(), projA)).toBe(false); + // A server whose agent is gone (reparented to init) cannot be matched either. + hookRows({ cwd: projA, selfReport: { ...args, source: "mcp" }, agentPid: 1 }); + expect(selfReportHookRecordedRecently("codex", args, Date.now(), projA, 1)).toBe(false); + expect(selfReportHookRecordedRecently("codex", args, Date.now(), projA, undefined)).toBe(false); + }); + + it("an untrusted Codex's report lands once, on the session Codex's own rollout names", async () => { + writeEffectiveSelfReport({ enabled: true }); + const project = join(home, "proj"); + const day = new Date(); + const pad = (n: number) => String(n).padStart(2, "0"); + const dir = join(home, ".codex", "sessions", String(day.getFullYear()), pad(day.getMonth() + 1), pad(day.getDate())); + mkdirSync(dir, { recursive: true }); + mkdirSync(project, { recursive: true }); + const meta = (id: string, cwd: string) => JSON.stringify({ type: "session_meta", payload: { id, cwd } }) + "\n"; + writeFileSync(join(dir, "rollout-a-elsewhere.jsonl"), meta("other-id", join(home, "elsewhere"))); + writeFileSync(join(dir, "rollout-b.jsonl"), meta("codex-session-1", project)); + expect(selfReportCodexRolloutSession(project)).toEqual({ sessionId: "codex-session-1", cwd: project }); + // Too old: outside the 6 h window. + const old = new Date(Date.now() - 7 * 60 * 60 * 1000); + utimesSync(join(dir, "rollout-b.jsonl"), old, old); + expect(selfReportCodexRolloutSession(project)).toBeNull(); + utimesSync(join(dir, "rollout-b.jsonl"), new Date(), new Date()); + + const args = { category: "invalid_tool_or_credential", detail: "tickets: 401, token expired" }; + const reply = await handleSelfReportRpc(call(args), { agent: "codex", cwd: project }); + expect(reply).toMatchObject({ result: { content: [{ type: "text", text: "Recorded." }] } }); + expect(events()).toEqual([expect.objectContaining({ integration: "codex", session_id: "codex-session-1", agent_id: "codex-proj", ...args })]); + + // The same call after the hook recorded it: nothing more. + hookRow({ cwd: project, selfReport: { ...args, source: "mcp" } }); + await handleSelfReportRpc(call(args), { agent: "codex", cwd: project }); + expect(events()).toHaveLength(1); + }); + + it("Claude Code with hooks off: attributed to its newest transcript in that directory", () => { + const project = join(home, "my.proj"); + const dir = join(home, ".claude", "projects", project.replace(/[^A-Za-z0-9]/g, "-")); + mkdirSync(dir, { recursive: true }); + writeFileSync(join(dir, "11111111-1111-4111-8111-111111111111.jsonl"), "{}\n"); + const older = new Date(Date.now() - 60_000); + utimesSync(join(dir, "11111111-1111-4111-8111-111111111111.jsonl"), older, older); + writeFileSync(join(dir, "22222222-2222-4222-8222-222222222222.jsonl"), "{}\n"); + expect(selfReportClaudeTranscriptSession(project)).toEqual({ sessionId: "22222222-2222-4222-8222-222222222222", cwd: project }); + expect(selfReportClaudeTranscriptSession(join(home, "other"))).toBeNull(); + }); +}); + +describe("the CLI a daemon's sync registers for stdio", () => { + it("looks beside the node that runs it, then npm's and bun's global bins", () => { + const dirs = selfReportCliDirs({ NPM_CONFIG_PREFIX: "/opt/npm" }, "/home/u/.nvm/versions/node/v26/bin/node", "/home/u"); + expect(dirs).toEqual([ + "/home/u/.nvm/versions/node/v26/bin", + "/opt/npm/bin", + "/home/u/.npm-global/bin", + "/usr/local/bin", + "/home/u/.bun/bin", + ]); + }); + + it("finds the npm link next to node when PATH has no failproofai (a systemd unit's PATH)", () => { + const bin = join(home, "nodebin"); + mkdirSync(bin); + writeFileSync(join(bin, "failproofai"), "#!/bin/sh\n"); + chmodSync(join(bin, "failproofai"), 0o755); + vi.stubEnv("PATH", "/nonexistent"); + vi.stubEnv("FAILPROOFAI_BINARY_OVERRIDE", ""); + const execPath = process.execPath; + Object.defineProperty(process, "execPath", { value: join(bin, "node"), configurable: true }); + const argv1 = process.argv[1]; + process.argv[1] = "/x/lib/node_modules/failproofai/dist/cli.mjs"; + try { + expect(resolveSelfReportCliPath()).toBe(join(bin, "failproofai")); + } finally { + Object.defineProperty(process, "execPath", { value: execPath, configurable: true }); + process.argv[1] = argv1; + } + }); +}); diff --git a/__tests__/hooks/self-report-install.test.ts b/__tests__/hooks/self-report-install.test.ts new file mode 100644 index 000000000..c4c6567d9 --- /dev/null +++ b/__tests__/hooks/self-report-install.test.ts @@ -0,0 +1,959 @@ +// @vitest-environment node +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, resolve } from "node:path"; +import { parse as parseToml } from "smol-toml"; +import { parse as parseYaml } from "yaml"; +import { parse as parseJsonc } from "jsonc-parser/lib/esm/main.js"; +import { createServer as createHttpServer, type Server as HttpServer } from "node:http"; +import { createServer as createNetServer, type Server as NetServer } from "node:net"; +import { + SELF_REPORT_COMPANION_MARKER, + SELF_REPORT_MCP_TARGETS, + isOurMcpEntry, + probeSelfReportHttp, + probeSelfReportHttpInstance, + selfReportDaemonLive, + selfReportHttpAllowed, + selfReportSyncChanged, + readSelfReportMcpSettings, + removeSelfReportMcp, + selfReportRegistrationStatus, + syncSelfReportMcp, + type SyncSelfReportMcpOptions, +} from "../../src/hooks/self-report-install"; +import { mergeTomlManagedBlock } from "../../src/hooks/toml-managed-block"; +import { INTEGRATION_TYPES, type IntegrationType } from "../../src/hooks/types"; +import { + SELF_REPORT_SERVER_RECORDS, + ensureSelfReportSettingsFile, + readEffectiveSelfReport, + readEnabledSelfReport, +} from "../../src/hooks/self-report"; +import { runSelfReportCommand } from "../../src/hooks/self-report-cli"; + +const CLI = "/usr/local/bin/failproofai"; +let home: string; + +function enabledOpts(extra: Partial = {}, daemon = true): SyncSelfReportMcpOptions { + return { + quiet: true, + binaryPath: CLI, + ...extra, + deps: { + daemonLive: async () => daemon, + hooksInstalled: () => true, + hookRecords: () => true, + settings: { enabled: true, port: 4319 }, + // No agent is on HTTP by default (SELF_REPORT_HTTP_AGENTS); most tests + // here exercise the HTTP path, which is kept, so they turn it on. + httpAgents: ["claude", "codex"], + ...extra.deps, + }, + }; +} + +function pathOf(agent: IntegrationType): string { + return SELF_REPORT_MCP_TARGETS[agent].paths()[0]; +} + +function put(path: string, text: string): void { + mkdirSync(dirname(path), { recursive: true }); + writeFileSync(path, text); +} + +function read(path: string): string { + return readFileSync(path, "utf8"); +} + +/** The parsed `failproofai_local` entry, whatever the agent's format. */ +function entryIn(agent: IntegrationType): Record | undefined { + const path = pathOf(agent); + if (!existsSync(path)) return undefined; + const text = read(path); + const t = SELF_REPORT_MCP_TARGETS[agent]; + const doc = (t.format === "toml" ? parseToml(text) : t.format === "yaml" ? parseYaml(text) ?? {} : parseJsonc(text)) as Record; + const container = t.container(doc); + let v: unknown = doc; + for (const k of [...container, "failproofai_local"]) v = (v as Record | undefined)?.[k]; + return v as Record | undefined; +} + +beforeEach(() => { + home = mkdtempSync(resolve(tmpdir(), "fp-selfreport-")); + vi.stubEnv("HOME", home); + vi.stubEnv("USERPROFILE", home); + for (const k of [ + "CLAUDE_CONFIG_DIR", "CODEX_HOME", "COPILOT_HOME", "PI_CODING_AGENT_DIR", "HERMES_HOME", + "OPENCLAW_STATE_DIR", "OPENCLAW_HOME", "OPENCLAW_CONFIG_PATH", "GOOSE_PATH_ROOT", "XDG_CONFIG_HOME", + "FAILPROOFAI_SELF_REPORT_PORT", + ]) vi.stubEnv(k, ""); + vi.stubEnv("FAILPROOFAI_HOME", resolve(home, ".failproofai")); +}); + +afterEach(() => { + vi.unstubAllEnvs(); + rmSync(home, { recursive: true, force: true }); +}); + +// A pre-existing user server and some other setting, per format. +const USER_JSON = (container: string[]) => { + const inner: Record = { mine: { command: "node", args: ["my-server.js"] } }; + let obj: Record = inner; + for (const k of [...container].reverse()) obj = { [k]: obj }; + return { theme: "dark", ...obj }; +}; + +describe("syncSelfReportMcp: every agent round-trips", () => { + for (const agent of INTEGRATION_TYPES.filter((a) => !SELF_REPORT_MCP_TARGETS[a].extension)) { + const target = SELF_REPORT_MCP_TARGETS[agent]; + it(`${agent}: adds, is idempotent, keeps the user's entries, removes only ours`, async () => { + const path = pathOf(agent); + let original: string; + if (target.format === "toml") { + original = '# my codex config\nmodel = "gpt-5"\n\n[mcp_servers.mine]\ncommand = "node" # inline note\nargs = ["my-server.js"]\n'; + } else if (target.format === "yaml") { + const key = target.container({})[0]; + original = `# my config\nmodel: some-model\n${key}:\n # my server\n mine:\n command: node\n args: [my-server.js]\n`; + } else { + original = `// a comment\n${JSON.stringify(USER_JSON(target.container({})), null, 2)}\n`; + if (agent === "claude") original = JSON.stringify(USER_JSON(["mcpServers"]), null, 2) + "\n"; + } + put(path, original); + + // With a live daemon: HTTP for a hook-recorded agent, stdio for one the + // server records (it must know the caller's cwd). + const want = selfReportHttpAllowed(agent, ["claude", "codex"]) ? "http" : "stdio"; + const first = await syncSelfReportMcp(enabledOpts({ agents: [agent] })); + expect(first.map((r) => [r.action, r.status, r.transport])).toEqual( + first.map(() => ["added", "ok", want]), + ); + const entry = entryIn(agent)!; + expect(isOurMcpEntry(entry)).toBe(true); + expect(JSON.stringify(entry)).toContain( + want === "http" ? `http://127.0.0.1:4319/mcp?agent=${agent}` : JSON.stringify(["mcp", "--agent", agent]).slice(1, -1), + ); + const afterAdd = read(path); + // the user's things are still there, comments included + expect(afterAdd).toContain("mine"); + expect(afterAdd).toContain(target.format === "json" && agent === "claude" ? "dark" : target.format === "toml" ? "# inline note" : target.format === "yaml" ? "# my server" : "// a comment"); + + const second = await syncSelfReportMcp(enabledOpts({ agents: [agent] })); + expect(second.every((r) => r.action === "unchanged" && r.status === "ok")).toBe(true); + expect(read(path)).toBe(afterAdd); + + const removed = removeSelfReportMcp({ agents: [agent], quiet: true }); + expect(removed.map((r) => r.action)).toEqual(removed.map(() => "removed")); + expect(entryIn(agent)).toBeUndefined(); + const afterRemove = read(path); + expect(afterRemove).toContain("mine"); + if (target.format === "toml") expect(afterRemove).toBe(original); + + const again = removeSelfReportMcp({ agents: [agent], quiet: true }); + expect(again.every((r) => r.action === "unchanged")).toBe(true); + expect(read(path)).toBe(afterRemove); + }); + } +}); + +describe("transport choice", () => { + it("puts no agent on HTTP by default, and when the HTTP path is on, never a server-recorded agent", async () => { + // Review 4722003649: Claude Code projects can switch the hooks off, so no + // agent relies on its hook through the daemon's endpoint by default. + expect(INTEGRATION_TYPES.filter((a) => selfReportHttpAllowed(a))).toEqual([]); + const defaults = await syncSelfReportMcp({ ...enabledOpts({}, true), deps: { ...enabledOpts({}, true).deps, httpAgents: undefined } }); + const extension = (a: IntegrationType) => SELF_REPORT_MCP_TARGETS[a].extension === true; + for (const x of defaults) expect(x.transport).toBe(extension(x.agent) ? "extension" : "stdio"); + const on = ["claude", "codex"] as const; + expect(INTEGRATION_TYPES.filter((a) => selfReportHttpAllowed(a, [...INTEGRATION_TYPES]))).toEqual(on); + for (const a of SELF_REPORT_SERVER_RECORDS) expect(selfReportHttpAllowed(a as IntegrationType, [...INTEGRATION_TYPES])).toBe(false); + const r = await syncSelfReportMcp(enabledOpts({}, true)); + for (const x of r) expect(x.transport).toBe(extension(x.agent) ? "extension" : selfReportHttpAllowed(x.agent, on) ? "http" : "stdio"); + // Every agent's HTTP shape is still one we recognise (a stale one is moved). + for (const a of INTEGRATION_TYPES) { + const t = SELF_REPORT_MCP_TARGETS[a]; + expect(isOurMcpEntry(t.entry({ kind: "http", url: `http://127.0.0.1:4319/mcp?agent=${a}` }, t.container({})))).toBe(true); + } + }); + + it("never asks for the live check when only server-recorded agents want an entry", async () => { + const daemonLive = vi.fn(async () => true); + await syncSelfReportMcp(enabledOpts({ agents: ["copilot", "pi", "hermes"], deps: { daemonLive } })); + expect(daemonLive).not.toHaveBeenCalled(); + }); + + it("moves a server-recorded agent's older HTTP entry to stdio", async () => { + put(pathOf("copilot"), JSON.stringify({ mcpServers: { failproofai_local: { type: "http", url: "http://127.0.0.1:4319/mcp?agent=copilot", tools: ["*"] } } })); + const r = await syncSelfReportMcp(enabledOpts({ agents: ["copilot"] }, true)); + expect(r[0]).toMatchObject({ action: "updated", transport: "stdio" }); + expect(entryIn("copilot")).toEqual({ type: "local", command: CLI, args: ["mcp", "--agent", "copilot"], tools: ["*"] }); + }); + + it("uses stdio with the CLI path and --agent when no daemon is live", async () => { + await syncSelfReportMcp(enabledOpts({ agents: ["claude", "codex", "opencode", "goose"] }, false)); + expect(entryIn("claude")).toEqual({ type: "stdio", command: CLI, args: ["mcp", "--agent", "claude"], alwaysLoad: true }); + expect(entryIn("codex")).toEqual({ command: CLI, args: ["mcp", "--agent", "codex"] }); + expect(entryIn("opencode")).toEqual({ type: "local", command: [CLI, "mcp", "--agent", "opencode"], enabled: true }); + expect(entryIn("goose")).toMatchObject({ type: "stdio", cmd: CLI, args: ["mcp", "--agent", "goose"], enabled: true }); + }); + + // Pi before 0.99 has no MCP, so an mcp.json entry never reached its model: + // failproofai's Pi extension offers the tool instead (pi-extension/index.ts). + it("writes no Pi MCP entry, takes out one an earlier version wrote, and keeps the user's", async () => { + const r0 = await syncSelfReportMcp(enabledOpts({ agents: ["pi"] }, false)); + expect(r0).toEqual([{ agent: "pi", path: "", action: "unchanged", transport: "extension", status: "ok" }]); + expect(existsSync(pathOf("pi"))).toBe(false); + for (const old of [ + { command: CLI, args: ["mcp", "--agent", "pi"], exposure: "direct" }, + { url: "http://127.0.0.1:4319/mcp?agent=pi" }, + ]) { + put(pathOf("pi"), JSON.stringify({ mcpServers: { failproofai_local: old, mine: { command: "node", args: ["x.js"] } } })); + const r = await syncSelfReportMcp(enabledOpts({ agents: ["pi"] }, true)); + expect(r[0]).toMatchObject({ action: "removed", status: "ok" }); + expect(r[1]).toMatchObject({ action: "unchanged", transport: "extension" }); + expect(entryIn("pi")).toBeUndefined(); + expect(read(pathOf("pi"))).toContain("mine"); + } + // A failproofai_local of the user's own is not ours: left alone. + put(pathOf("pi"), JSON.stringify({ mcpServers: { failproofai_local: { command: "node", args: ["mine.js"] } } })); + await syncSelfReportMcp(enabledOpts({ agents: ["pi"] }, true)); + expect(entryIn("pi")).toEqual({ command: "node", args: ["mine.js"] }); + // Off, or not hooked: no tool from the extension either. + const off = await syncSelfReportMcp(enabledOpts({ agents: ["pi"], enabled: false }, true)); + expect(off.at(-1)).toMatchObject({ transport: null, status: "ok" }); + const unhooked = await syncSelfReportMcp(enabledOpts({ agents: ["pi"], deps: { hooksInstalled: () => false } }, true)); + expect(unhooked.at(-1)).toMatchObject({ transport: null, status: "not-hooked" }); + }); + + it("tells the user how cursor-agent approves the server when Cursor's entry is written", async () => { + const { selfReportSyncLines } = await import("../../src/hooks/self-report-install"); + const lines = selfReportSyncLines(await syncSelfReportMcp(enabledOpts({ agents: ["cursor", "claude"] }))); + expect(lines.filter((l) => l.includes("cursor-agent mcp enable failproofai_local"))).toHaveLength(1); + expect(lines.findIndex((l) => l.includes("cursor-agent mcp enable"))).toBe( + lines.findIndex((l) => l.includes("Cursor")) + 1, + ); + }); + + it("switches an existing entry between transports in place", async () => { + await syncSelfReportMcp(enabledOpts({ agents: ["codex"] }, false)); + const r = await syncSelfReportMcp(enabledOpts({ agents: ["codex"] }, true)); + expect(r[0]).toMatchObject({ action: "updated", transport: "http" }); + const text = read(pathOf("codex")); + expect(text.match(/\[mcp_servers\.failproofai_local\]/g)).toHaveLength(1); + expect(entryIn("codex")).toEqual({ url: "http://127.0.0.1:4319/mcp?agent=codex" }); + }); + + it("takes the port from self-report.json", async () => { + const p = resolve(home, ".failproofai", "self-report.json"); + put(p, JSON.stringify({ version: 1, enabled: true, mcp: { port: 5555, url: "http://127.0.0.1:5555/mcp" } })); + expect(readSelfReportMcpSettings()).toEqual({ enabled: true, port: 5555 }); + await syncSelfReportMcp({ quiet: true, agents: ["claude"], deps: { daemonLive: async () => true, hooksInstalled: () => true, httpAgents: ["claude"] } }); + expect(entryIn("claude")).toEqual({ type: "http", url: "http://127.0.0.1:5555/mcp?agent=claude", alwaysLoad: true }); + }); + + it("reads a missing file as on off Cloud, off on Cloud, and a broken file as off", async () => { + // On by default: no file and no local config on an open-source machine. + expect(readSelfReportMcpSettings()).toEqual({ enabled: true, port: 4319 }); + // Cloud enrolled, the daemon has not written the file yet: off. + vi.stubEnv("FAILPROOFAI_CLOUD_URL", "https://cloud.example.com"); + expect(readSelfReportMcpSettings()).toEqual({ enabled: false, port: 4319 }); + vi.stubEnv("FAILPROOFAI_CLOUD_URL", ""); + put(resolve(home, ".failproofai", "credentials.json"), JSON.stringify({ cloud: { url: "https://x", machine_id: "m", token: "t" } })); + expect(readSelfReportMcpSettings().enabled).toBe(false); + // Switched back to open source: the default applies again. + put(resolve(home, ".failproofai", "config.json"), JSON.stringify({ mode: { kind: "oss" } })); + expect(readSelfReportMcpSettings().enabled).toBe(true); + // A malformed file is off whatever else is true (fail safe). + put(resolve(home, ".failproofai", "self-report.json"), "{nope"); + expect(readSelfReportMcpSettings()).toEqual({ enabled: false, port: 4319 }); + }); + + it("reports an error, writing nothing, when stdio is needed and no CLI is known", async () => { + const base = enabledOpts({ agents: ["cursor"] }, false); + const r = await syncSelfReportMcp({ ...base, binaryPath: undefined, deps: { ...base.deps, resolveCliPath: () => null } }); + expect(r[0]).toMatchObject({ status: "error", action: "skipped" }); + expect(existsSync(pathOf("cursor"))).toBe(false); + }); +}); + +describe("ownership", () => { + it("never touches a failproofai_local entry it did not write, and reports it as a conflict", async () => { + const path = pathOf("claude"); + const foreign = { mcpServers: { failproofai_local: { type: "http", url: "https://elsewhere.example.com/mcp" } } }; + put(path, JSON.stringify(foreign, null, 2) + "\n"); + const before = read(path); + expect((await syncSelfReportMcp(enabledOpts({ agents: ["claude"] })))[0]).toMatchObject({ status: "conflict", action: "skipped" }); + expect(removeSelfReportMcp({ agents: ["claude"], quiet: true })[0]).toMatchObject({ status: "conflict" }); + expect(read(path)).toBe(before); + }); + + // Review round 3: a name containing "failproofai" made a foreign program ours, + // and sync replaced it. Ours now means: resolves to a failproofai package's + // CLI entry point (any version), or a dangling failproofai launcher. + it("leaves a foreign program named like ours alone, with our arguments, and reports it as a conflict", async () => { + const dir = resolve(home, "x"); + mkdirSync(dir, { recursive: true }); + for (const name of ["fail" + "proofai-foreign", "fail" + "proofai"]) { + const program = resolve(dir, name); + writeFileSync(program, "#!/bin/sh\nexit 0\n", { mode: 0o755 }); + const path = pathOf("claude"); + put(path, JSON.stringify({ mcpServers: { failproofai_local: { type: "stdio", command: program, args: ["mcp", "--agent", "claude"] } } }, null, 2) + "\n"); + const before = read(path); + expect(isOurMcpEntry(entryIn("claude")), name).toBe(false); + expect((await syncSelfReportMcp(enabledOpts({ agents: ["claude"] })))[0], name).toMatchObject({ status: "conflict", action: "skipped" }); + expect(removeSelfReportMcp({ agents: ["claude"], quiet: true })[0], name).toMatchObject({ status: "conflict" }); + expect(read(path), name).toBe(before); + } + }); + + it("still recognises and migrates what an earlier install wrote: a launcher into any failproofai package, or a dangling one", async () => { + // An earlier version's npm link: /bin/failproofai -> /bin/failproofai.mjs. + const pkg = resolve(home, "old-prefix", "lib", "node_modules", "fail" + "proofai"); + mkdirSync(resolve(pkg, "bin"), { recursive: true }); + writeFileSync(resolve(pkg, "package.json"), JSON.stringify({ name: "fail" + "proofai", version: "1.0.0" })); + writeFileSync(resolve(pkg, "bin", "fail" + "proofai.mjs"), "#!/usr/bin/env node\n", { mode: 0o755 }); + const binDir = resolve(home, "old-prefix", "bin"); + mkdirSync(binDir, { recursive: true }); + const link = resolve(binDir, "fail" + "proofai"); + symlinkSync(resolve(pkg, "bin", "fail" + "proofai.mjs"), link); + const dangling = resolve(home, "gone", "bin", "fail" + "proofai"); + for (const command of [link, dangling]) { + put(pathOf("claude"), JSON.stringify({ mcpServers: { failproofai_local: { type: "stdio", command, args: ["mcp", "--agent", "claude"] } } }, null, 2) + "\n"); + expect(isOurMcpEntry(entryIn("claude")), command).toBe(true); + const [r] = await syncSelfReportMcp(enabledOpts({ agents: ["claude"], deps: { httpAgents: [] } })); + expect(r, command).toMatchObject({ status: "ok", action: "updated" }); + expect(entryIn("claude")?.command).toBe(CLI); + } + }); + + it("treats a hand-written codex [mcp_servers.failproofai_local] outside our markers as foreign", async () => { + const path = pathOf("codex"); + put(path, '[mcp_servers.failproofai_local]\nurl = "http://127.0.0.1:4319/mcp?agent=codex"\n'); + const before = read(path); + expect((await syncSelfReportMcp(enabledOpts({ agents: ["codex"] })))[0].status).toBe("conflict"); + expect(read(path)).toBe(before); + }); + + // The Cloud MCP gateway is registered as `failproofai`. Ours is + // `failproofai_local`, so the gateway's entry is never read, changed, + // removed or reported, in any format, even one shaped exactly like ours. + const GATEWAY_URL = "https://gateway.befailproof.ai/mcp"; + const gatewayFixtures: Array<[IntegrationType, string, (text: string) => unknown]> = [ + ["claude", JSON.stringify({ mcpServers: { failproofai: { type: "http", url: GATEWAY_URL } } }, null, 2) + "\n", + (t) => (JSON.parse(t) as { mcpServers: Record }).mcpServers.failproofai], + ["cursor", JSON.stringify({ mcpServers: { failproofai: { url: GATEWAY_URL } } }, null, 2) + "\n", + (t) => (JSON.parse(t) as { mcpServers: Record }).mcpServers.failproofai], + ["opencode", JSON.stringify({ mcp: { failproofai: { type: "remote", url: GATEWAY_URL, enabled: true } } }, null, 2) + "\n", + (t) => (JSON.parse(t) as { mcp: Record }).mcp.failproofai], + ["codex", `[mcp_servers.failproofai]\nurl = "${GATEWAY_URL}"\n`, + (t) => (parseToml(t) as { mcp_servers: Record }).mcp_servers.failproofai], + ["goose", `extensions:\n failproofai:\n name: failproofai\n type: streamable_http\n enabled: true\n uri: ${GATEWAY_URL}\n`, + (t) => (parseYaml(t) as { extensions: Record }).extensions.failproofai], + ]; + for (const [agent, text, gatewayOf] of gatewayFixtures) { + it(`${agent}: leaves a Cloud gateway entry named failproofai untouched next to ours`, async () => { + put(pathOf(agent), text); + const path = pathOf(agent); + const gateway = gatewayOf(read(path)); + const added = await syncSelfReportMcp(enabledOpts({ agents: [agent] })); + expect(added.map((r) => [r.action, r.status])).toEqual([["added", "ok"]]); + expect(isOurMcpEntry(entryIn(agent))).toBe(true); + expect(gatewayOf(read(path))).toEqual(gateway); + const status = selfReportRegistrationStatus({ agents: [agent], hooksInstalled: () => true }); + expect(status.map((r) => [r.registered, r.conflict])).toEqual([[true, false]]); + // Disable and uninstall take out ours only. + expect(removeSelfReportMcp({ agents: [agent], quiet: true }).map((r) => r.action)).toEqual(["removed"]); + expect(entryIn(agent)).toBeUndefined(); + expect(gatewayOf(read(path))).toEqual(gateway); + }); + } + + it("leaves a failproofai entry alone even when it is shaped like ours", async () => { + const path = pathOf("claude"); + put(path, JSON.stringify({ mcpServers: { failproofai: { type: "http", url: "http://127.0.0.1:4319/mcp?agent=claude", alwaysLoad: true } } }, null, 2) + "\n"); + await syncSelfReportMcp(enabledOpts({ agents: ["claude"] })); + removeSelfReportMcp({ agents: ["claude"], quiet: true }); + expect(JSON.parse(read(path)).mcpServers.failproofai).toEqual({ type: "http", url: "http://127.0.0.1:4319/mcp?agent=claude", alwaysLoad: true }); + }); + + it("refuses a codex config whose inline mcp_servers table would collide, leaving it as is", async () => { + const path = pathOf("codex"); + put(path, 'mcp_servers = { mine = { command = "node" } }\n'); + const before = read(path); + const r = (await syncSelfReportMcp(enabledOpts({ agents: ["codex"] })))[0]; + expect(r.status).toBe("error"); + expect(read(path)).toBe(before); + }); + + it("refuses an unparsable config", async () => { + const path = pathOf("cursor"); + put(path, "{ not json"); + const r = (await syncSelfReportMcp(enabledOpts({ agents: ["cursor"] })))[0]; + expect(r.status).toBe("error"); + expect(read(path)).toBe("{ not json"); + }); + + it("recognises only our shapes", async () => { + expect(isOurMcpEntry({ url: "http://127.0.0.1:4319/mcp?agent=claude" })).toBe(true); + expect(isOurMcpEntry({ serverUrl: "http://localhost:4319/mcp?agent=antigravity" })).toBe(true); + expect(isOurMcpEntry({ command: "/x/bin/failproofai", args: ["mcp", "--agent", "pi"] })).toBe(true); + expect(isOurMcpEntry({ url: "https://gateway.example.com/mcp" })).toBe(false); + expect(isOurMcpEntry({ command: "/x/bin/failproofai", args: ["--hook", "PreToolUse"] })).toBe(false); + expect(isOurMcpEntry({ command: "node", args: ["mcp", "--agent", "pi"] })).toBe(false); + }); +}); + +describe("which agents", () => { + it("enabled: only hooked agents get an entry; unhooked ones are left alone", async () => { + const r = await syncSelfReportMcp(enabledOpts({ deps: { hooksInstalled: (a) => a === "claude" } })); + expect(r.filter((x) => x.action === "added").map((x) => x.agent)).toEqual(["claude"]); + expect(r.filter((x) => x.agent !== "claude").every((x) => x.status === "not-hooked")).toBe(true); + expect(existsSync(pathOf("cursor"))).toBe(false); + }); + + it("alsoHooked registers agents installHooks just wrote", async () => { + const r = await syncSelfReportMcp(enabledOpts({ agents: ["cursor"], alsoHooked: ["cursor"], deps: { hooksInstalled: () => false } })); + expect(r[0].action).toBe("added"); + }); + + it("keeps and repairs an existing registration whose hooks are only at project scope", async () => { + // Installed with project-scope hooks (alsoHooked) while the daemon was up. + await syncSelfReportMcp(enabledOpts({ agents: ["claude"], alsoHooked: ["claude"], deps: { hooksInstalled: () => false } }, true)); + expect(entryIn("claude")).toEqual({ type: "http", url: "http://127.0.0.1:4319/mcp?agent=claude", alwaysLoad: true }); + // A later sync sees no user-scope hooks; the daemon is gone. The entry is + // moved to stdio, not stranded on a dead endpoint. + const r = await syncSelfReportMcp(enabledOpts({ agents: ["claude", "factory"], deps: { hooksInstalled: () => false } }, false)); + expect(r.find((x) => x.agent === "claude")).toMatchObject({ action: "updated", transport: "stdio", status: "ok" }); + expect(entryIn("claude")).toEqual({ type: "stdio", command: CLI, args: ["mcp", "--agent", "claude"], alwaysLoad: true }); + // An agent never registered and without hooks is still left alone. + expect(r.find((x) => x.agent === "factory")).toMatchObject({ action: "skipped", status: "not-hooked" }); + expect(existsSync(pathOf("factory"))).toBe(false); + }); + + it("the live check is asked for an unhooked agent that already has our entry", async () => { + await syncSelfReportMcp(enabledOpts({ agents: ["codex"], alsoHooked: ["codex"], deps: { hooksInstalled: () => false } }, false)); + const daemonLive = vi.fn(async () => true); + const r = await syncSelfReportMcp(enabledOpts({ agents: ["codex"], deps: { daemonLive, hooksInstalled: () => false } })); + expect(daemonLive).toHaveBeenCalledTimes(1); + expect(r[0]).toMatchObject({ action: "updated", transport: "http" }); + }); + + it("disabled: removes ours from every agent, hooked or not", async () => { + await syncSelfReportMcp(enabledOpts({ agents: ["claude", "factory"] })); + const r = await syncSelfReportMcp({ quiet: true, deps: { settings: { enabled: false, port: 4319 }, hooksInstalled: () => false, daemonLive: async () => true } }); + expect(r.filter((x) => x.action === "removed").map((x) => x.agent).sort()).toEqual(["claude", "factory"]); + expect(entryIn("claude")).toBeUndefined(); + }); + + // Hermes and OpenClaw defer MCP tools behind tool search with no + // per-server switch, so their tool now comes from failproofai's own plugin + // (hermes-plugin/self_report.py, openclaw-plugin/self-report.js): sync writes + // no MCP entry for either, takes out one an earlier version wrote in every + // profile, and keeps the user's own servers. + it("writes no Hermes or OpenClaw MCP entry and takes out every profile's old one", async () => { + const old = { command: CLI, args: ["mcp", "--agent", "hermes"] }; + put(resolve(home, ".hermes", "config.yaml"), `model: x\nmcp_servers:\n failproofai_local:\n command: ${CLI}\n args: [mcp, --agent, hermes]\n mine:\n command: node\n`); + put(resolve(home, ".hermes", "profiles", "work", "config.yaml"), `model: y\nmcp_servers:\n failproofai_local:\n command: ${CLI}\n args: [mcp, --agent, hermes]\n`); + const r = await syncSelfReportMcp(enabledOpts({ agents: ["hermes"] })); + expect(r.map((x) => x.action)).toEqual(["removed", "removed", "unchanged"]); + expect(r.at(-1)).toMatchObject({ transport: "extension", status: "ok" }); + for (const p of [resolve(home, ".hermes", "config.yaml"), resolve(home, ".hermes", "profiles", "work", "config.yaml")]) { + const doc = parseYaml(read(p)) as { mcp_servers?: Record }; + expect(doc.mcp_servers?.failproofai_local).toBeUndefined(); + } + expect((parseYaml(read(resolve(home, ".hermes", "config.yaml"))) as { mcp_servers: Record }).mcp_servers.mine).toEqual({ command: "node" }); + expect(old.args).toEqual(["mcp", "--agent", "hermes"]); + // A second sync writes nothing. + const again = await syncSelfReportMcp(enabledOpts({ agents: ["hermes"] })); + expect(again.map((x) => x.action)).toEqual(["unchanged"]); + + put(pathOf("openclaw"), JSON.stringify({ mcp: { servers: { failproofai_local: { command: CLI, args: ["mcp", "--agent", "openclaw"] }, mine: { command: "node" } } } })); + const oc = await syncSelfReportMcp(enabledOpts({ agents: ["openclaw"] })); + expect(oc.map((x) => x.action)).toEqual(["removed", "unchanged"]); + const servers = (JSON.parse(read(pathOf("openclaw"))) as { mcp: { servers: Record } }).mcp.servers; + expect(servers.failproofai_local).toBeUndefined(); + expect(servers.mine).toEqual({ command: "node" }); + expect(selfReportRegistrationStatus({ agents: ["hermes", "openclaw"], hooksInstalled: () => true }).map((x) => [x.agent, x.transport])).toEqual([ + ["hermes", "extension"], + ["openclaw", "extension"], + ]); + }); + + it("keeps Claude Code's tools out of tool search (alwaysLoad) and Antigravity's out of call_mcp_tool (eager)", async () => { + await syncSelfReportMcp(enabledOpts({ agents: ["claude", "antigravity", "cursor"] }, false)); + expect(entryIn("claude")).toEqual({ type: "stdio", command: CLI, args: ["mcp", "--agent", "claude"], alwaysLoad: true }); + expect(entryIn("antigravity")).toEqual({ command: CLI, args: ["mcp", "--agent", "antigravity"], eager: true }); + // Only our entries: another agent's shape is unchanged. + expect(entryIn("cursor")).toEqual({ type: "stdio", command: CLI, args: ["mcp", "--agent", "cursor"] }); + // An entry an earlier version wrote without the flag is updated in place. + put(pathOf("antigravity"), JSON.stringify({ mcpServers: { failproofai_local: { command: CLI, args: ["mcp", "--agent", "antigravity"] } } })); + const r = await syncSelfReportMcp(enabledOpts({ agents: ["antigravity"] }, false)); + expect(r[0]).toMatchObject({ action: "updated" }); + expect(entryIn("antigravity")).toMatchObject({ eager: true }); + }); + + it("writes Copilot's instructions file beside its entry, and removes it with the entry", async () => { + const instructions = resolve(home, ".copilot", "instructions", "failproofai-self-reports.instructions.md"); + await syncSelfReportMcp(enabledOpts({ agents: ["copilot"] }, false)); + const text = read(instructions); + expect(text.startsWith('---\napplyTo: "**"\n---\n')).toBe(true); + expect(text).toContain(SELF_REPORT_COMPANION_MARKER); + expect(text).toContain("`report` tool of the `failproofai_local` MCP server"); + // Hooks no longer detected but our entry is still there: the entry is kept, and the file repaired. + rmSync(instructions); + await syncSelfReportMcp(enabledOpts({ agents: ["copilot"], deps: { hooksInstalled: () => false } }, false)); + expect(existsSync(instructions)).toBe(true); + removeSelfReportMcp({ agents: ["copilot"], quiet: true }); + expect(existsSync(instructions)).toBe(false); + // A file of the same name that is not ours is never touched. + put(instructions, "my own notes\n"); + await syncSelfReportMcp(enabledOpts({ agents: ["copilot"] }, false)); + expect(read(instructions)).toBe("my own notes\n"); + removeSelfReportMcp({ agents: ["copilot"], quiet: true }); + expect(read(instructions)).toBe("my own notes\n"); + }); + + describe("Codex: a marked block in the global AGENTS.md", () => { + const BEGIN = ""; + const END = ""; + const agentsMd = () => resolve(home, ".codex", "AGENTS.md"); + + it("creates the file with only our block, is idempotent, and removes the file it created", async () => { + await syncSelfReportMcp(enabledOpts({ agents: ["codex"] }, false)); + const text = read(agentsMd()); + expect(text.startsWith(`${BEGIN}\n`)).toBe(true); + expect(text.endsWith(`${END}\n`)).toBe(true); + expect(text).toContain("When you are stuck, call failproofai_local's `report` tool once"); + expect(text).toContain("`category` is one of: looping, cannot_do_request"); + expect(text).toContain("If the tool is not listed directly, search your tools for `failproofai_local`."); + await syncSelfReportMcp(enabledOpts({ agents: ["codex"] }, false)); + expect(read(agentsMd())).toBe(text); + removeSelfReportMcp({ agents: ["codex"], quiet: true }); + expect(existsSync(agentsMd())).toBe(false); + }); + + it("keeps the user's own content byte for byte, around the block and after it is removed", async () => { + const mine = "# My global rules\n\nAlways run tests.\n"; + put(agentsMd(), mine); + await syncSelfReportMcp(enabledOpts({ agents: ["codex"] }, false)); + const text = read(agentsMd()); + expect(text.startsWith(`${mine}\n${BEGIN}\n`)).toBe(true); + // The user edits around our block; the next sync keeps that too. + put(agentsMd(), `${text}\nAdded later.\n`); + await syncSelfReportMcp(enabledOpts({ agents: ["codex"] }, false)); + expect(read(agentsMd())).toBe(`${text}\nAdded later.\n`); + await syncSelfReportMcp(enabledOpts({ agents: ["codex"], enabled: false }, false)); + expect(read(agentsMd())).toBe(`${mine}\n\nAdded later.\n`); + expect(read(agentsMd())).not.toContain("failproofai"); + }); + + it("rewrites the block when the categories or guidance change", async () => { + await syncSelfReportMcp(enabledOpts({ agents: ["codex"] }, false)); + const { writeEffectiveSelfReport } = await import("../../src/hooks/self-report"); + writeEffectiveSelfReport({ enabled: true, categories: [{ name: "deploy_blocked", description: "Deploys fail." }], guidance: "Be brief." }); + await syncSelfReportMcp(enabledOpts({ agents: ["codex"] }, false)); + const text = read(agentsMd()); + expect(text).toContain("`category` is one of: deploy_blocked."); + expect(text).toContain("Be brief."); + expect(text.split(BEGIN)).toHaveLength(2); + }); + + it("honours CODEX_HOME, and writes AGENTS.override.md when Codex would read that instead", async () => { + vi.stubEnv("CODEX_HOME", resolve(home, "cx")); + put(resolve(home, "cx", "AGENTS.override.md"), "override rules\n"); + await syncSelfReportMcp(enabledOpts({ agents: ["codex"] }, false)); + expect(read(resolve(home, "cx", "AGENTS.override.md"))).toContain(BEGIN); + expect(existsSync(resolve(home, "cx", "AGENTS.md"))).toBe(false); + expect(existsSync(agentsMd())).toBe(false); + removeSelfReportMcp({ agents: ["codex"], quiet: true }); + expect(read(resolve(home, "cx", "AGENTS.override.md"))).toBe("override rules\n"); + }); + + it("leaves a file with a half block alone and reports the error", async () => { + put(agentsMd(), `mine\n${BEGIN}\nhalf\n`); + const r = await syncSelfReportMcp(enabledOpts({ agents: ["codex"] }, false)); + expect(r.some((x) => x.status === "error" && x.path === agentsMd())).toBe(true); + expect(read(agentsMd())).toBe(`mine\n${BEGIN}\nhalf\n`); + }); + }); + + describe("Antigravity: a plugin of ours in the global customization root", () => { + const dir = () => resolve(home, ".gemini", "config", "plugins", "failproofai-self-reports"); + + it("creates the marked plugin, is idempotent, and removes it", async () => { + await syncSelfReportMcp(enabledOpts({ agents: ["antigravity"] }, false)); + expect(JSON.parse(read(resolve(dir(), "plugin.json")))).toEqual({ name: "failproofai-self-reports" }); + expect(existsSync(resolve(dir(), ".failproofai-managed"))).toBe(true); + const rules = read(resolve(dir(), "rules", "AGENTS.md")); + expect(rules).toContain("When you are stuck, call failproofai_local's `report` tool once"); + expect(rules).toContain("`category` is one of: looping"); + await syncSelfReportMcp(enabledOpts({ agents: ["antigravity"] }, false)); + expect(read(resolve(dir(), "rules", "AGENTS.md"))).toBe(rules); + removeSelfReportMcp({ agents: ["antigravity"], quiet: true }); + expect(existsSync(dir())).toBe(false); + // Other plugins beside it are untouched. + expect(existsSync(resolve(home, ".gemini", "config", "plugins"))).toBe(true); + }); + + it("never writes into or removes a directory of that name without our marker", async () => { + put(resolve(dir(), "plugin.json"), '{"name":"mine"}\n'); + await syncSelfReportMcp(enabledOpts({ agents: ["antigravity"] }, false)); + expect(read(resolve(dir(), "plugin.json"))).toBe('{"name":"mine"}\n'); + expect(existsSync(resolve(dir(), "rules"))).toBe(false); + removeSelfReportMcp({ agents: ["antigravity"], quiet: true }); + expect(read(resolve(dir(), "plugin.json"))).toBe('{"name":"mine"}\n'); + }); + }); + + it("writes no always-on instructions while Self Reports is disabled, and uninstall removes them", async () => { + const agentsMd = resolve(home, ".codex", "AGENTS.md"); + const plugin = resolve(home, ".gemini", "config", "plugins", "failproofai-self-reports"); + await syncSelfReportMcp(enabledOpts({ agents: ["codex", "antigravity"], enabled: false }, false)); + expect(existsSync(agentsMd)).toBe(false); + expect(existsSync(plugin)).toBe(false); + // Hooked but disabled in the settings file: nothing either. + await syncSelfReportMcp(enabledOpts({ agents: ["codex", "antigravity"], deps: { settings: { enabled: false, port: 4319 } } }, false)); + expect(existsSync(agentsMd)).toBe(false); + expect(existsSync(plugin)).toBe(false); + // Not hooked: nothing. + await syncSelfReportMcp(enabledOpts({ agents: ["codex", "antigravity"], deps: { hooksInstalled: () => false } }, false)); + expect(existsSync(agentsMd)).toBe(false); + expect(existsSync(plugin)).toBe(false); + // The uninstall path (every agent, whatever the settings). + await syncSelfReportMcp(enabledOpts({}, false)); + expect(existsSync(agentsMd)).toBe(true); + expect(existsSync(plugin)).toBe(true); + removeSelfReportMcp({ quiet: true }); + expect(existsSync(agentsMd)).toBe(false); + expect(existsSync(plugin)).toBe(false); + }); + + it("puts Copilot's instructions file under COPILOT_HOME", async () => { + vi.stubEnv("COPILOT_HOME", resolve(home, "cop")); + await syncSelfReportMcp(enabledOpts({ agents: ["copilot"] }, false)); + expect(existsSync(resolve(home, "cop", "instructions", "failproofai-self-reports.instructions.md"))).toBe(true); + }); + + it("honours CLAUDE_CONFIG_DIR, CODEX_HOME and COPILOT_HOME", async () => { + vi.stubEnv("CLAUDE_CONFIG_DIR", resolve(home, "claude-work")); + vi.stubEnv("CODEX_HOME", resolve(home, "codex-x")); + vi.stubEnv("COPILOT_HOME", resolve(home, "cop")); + expect(pathOf("claude")).toBe(resolve(home, "claude-work", ".claude.json")); + expect(pathOf("codex")).toBe(resolve(home, "codex-x", "config.toml")); + expect(pathOf("copilot")).toBe(resolve(home, "cop", "mcp-config.json")); + }); + + it("uses OpenCode v2's mcp.servers when the file already has it", async () => { + put(pathOf("opencode"), JSON.stringify({ mcp: { servers: { mine: { type: "local", command: ["node"] } } } })); + await syncSelfReportMcp(enabledOpts({ agents: ["opencode"] })); + const doc = JSON.parse(read(pathOf("opencode"))); + expect(doc.mcp.servers.failproofai_local).toEqual({ type: "local", command: [CLI, "mcp", "--agent", "opencode"] }); + expect(doc.mcp.failproofai_local).toBeUndefined(); + }); + + it("keeps a backup of the file it changed", async () => { + put(pathOf("factory"), '{"mcpServers":{}}\n'); + await syncSelfReportMcp(enabledOpts({ agents: ["factory"] })); + expect(read(`${pathOf("factory")}.failproofai-backup`)).toBe('{"mcpServers":{}}\n'); + }); +}); + +// ── Live transport check ──────────────────────────────────────────────────── + +/** + * A fake daemon socket: answers every framed request with a framed pong. With + * `selfReport`, the pong names the MCP server it serves (instance id + port). + */ +function fakeDaemon(path: string, answer = true, selfReport?: { instanceId: string; port: number }): Promise { + const server = createNetServer((sock) => { + // The sync's one-way `selfReportLog` frames close their end straight away; + // answering one would write to a closed socket (EPIPE), so ignore the error. + sock.on("error", () => {}); + let buf = Buffer.alloc(0); + sock.on("data", (chunk) => { + buf = Buffer.concat([buf, chunk as Buffer]); + if (buf.length < 4 || buf.length < 4 + buf.readUInt32BE(0)) return; + if (!answer) return; // accepted, never answered + const req = JSON.parse(buf.subarray(4, 4 + buf.readUInt32BE(0)).toString("utf8")); + if (req.type === "selfReportLog") return; // one-way: never answered + const body = Buffer.from(JSON.stringify({ type: "pong", protocolVersion: req.protocolVersion, ...(selfReport ? { selfReport } : {}) })); + const head = Buffer.alloc(4); + head.writeUInt32BE(body.length, 0); + sock.end(Buffer.concat([head, body])); + }); + }); + return new Promise((ok) => server.listen(path, () => ok(server))); +} + +/** A fake MCP endpoint on an ephemeral loopback port. */ +function fakeMcp(serverName = "failproofai_local", instanceId: string | null = "inst-1"): Promise<{ server: HttpServer; port: number }> { + const server = createHttpServer((req, res) => { + let body = ""; + req.on("data", (c) => (body += c)); + req.on("end", () => { + const msg = JSON.parse(body || "{}"); + res.setHeader("content-type", "application/json"); + res.end(JSON.stringify({ jsonrpc: "2.0", id: msg.id, result: { protocolVersion: "2025-06-18", capabilities: {}, serverInfo: { name: serverName, version: "1", ...(instanceId === null ? {} : { instanceId }) } } })); + }); + }); + return new Promise((ok) => server.listen(0, "127.0.0.1", () => ok({ server, port: (server.address() as { port: number }).port }))); +} + +/** A loopback port nothing listens on. */ +async function deadPort(): Promise { + const { server, port } = await fakeMcp(); + await new Promise((ok) => server.close(ok)); + return port; +} + +const closeAll: Array<() => Promise> = []; +afterEach(async () => { + while (closeAll.length) await closeAll.pop()!(); +}); +function track void): unknown }>(server: T): T { + closeAll.push(() => new Promise((ok) => server.close(() => ok(undefined)))); + return server; +} + +describe("live transport check", () => { + const socket = () => resolve(home, "daemon.sock"); + + it("a leftover socket file with no daemon behind it gives stdio, not a dead HTTP entry", async () => { + // What a hard-killed daemon leaves: the path exists, nothing listens on it. + writeFileSync(socket(), ""); + vi.stubEnv("FAILPROOFAI_DAEMON_SOCKET", socket()); + const port = await deadPort(); + expect(await selfReportDaemonLive(port)).toBe(false); + const r = await syncSelfReportMcp({ + quiet: true, agents: ["claude"], binaryPath: CLI, + deps: { hooksInstalled: () => true, settings: { enabled: true, port } }, + }); + expect(r[0]).toMatchObject({ action: "added", transport: "stdio" }); + expect(entryIn("claude")).toEqual({ type: "stdio", command: CLI, args: ["mcp", "--agent", "claude"], alwaysLoad: true }); + }); + + it("a daemon answering ping AND an MCP initialize gives http; a later sync moves it back once it is gone", async () => { + vi.stubEnv("FAILPROOFAI_DAEMON_SOCKET", socket()); + const { server, port } = await fakeMcp(); + const daemon = await fakeDaemon(socket(), true, { instanceId: "inst-1", port }); + expect(await selfReportDaemonLive(port)).toBe(true); + const opts = { + quiet: true, agents: ["claude"] as IntegrationType[], binaryPath: CLI, + deps: { hooksInstalled: () => true, settings: { enabled: true, port }, httpAgents: ["claude"] as IntegrationType[] }, + }; + expect((await syncSelfReportMcp(opts))[0]).toMatchObject({ action: "added", transport: "http" }); + expect(entryIn("claude")).toEqual({ type: "http", url: `http://127.0.0.1:${port}/mcp?agent=claude`, alwaysLoad: true }); + + await new Promise((ok) => daemon.close(ok)); + await new Promise((ok) => server.close(ok)); + expect((await syncSelfReportMcp(opts))[0]).toMatchObject({ action: "updated", transport: "stdio" }); + }); + + it("needs both halves: a ping without the endpoint, or the endpoint without a ping, is stdio", async () => { + vi.stubEnv("FAILPROOFAI_DAEMON_SOCKET", socket()); + const dead = await deadPort(); + const daemon = track(await fakeDaemon(socket(), true, { instanceId: "inst-1", port: dead })); + expect(await selfReportDaemonLive(dead)).toBe(false); + await new Promise((ok) => daemon.close(ok)); + closeAll.pop(); + const { server, port } = await fakeMcp(); + track(server); + expect(await selfReportDaemonLive(port)).toBe(false); + }); + + it("a daemon that accepts but never answers the ping is not live", async () => { + vi.stubEnv("FAILPROOFAI_DAEMON_SOCKET", socket()); + track(await fakeDaemon(socket(), false)); + const { server, port } = await fakeMcp(); + track(server); + expect(await selfReportDaemonLive(port)).toBe(false); + }, 10_000); + + it("the endpoint must be served by the daemon behind this socket", async () => { + vi.stubEnv("FAILPROOFAI_DAEMON_SOCKET", socket()); + // Another daemon (another home) holds the port; this one's bind failed, so + // its pong names no MCP server: stdio, even though the port answers. + const { server, port } = await fakeMcp("failproofai_local", "other-daemon"); + track(server); + const daemon = track(await fakeDaemon(socket())); + expect(await probeSelfReportHttpInstance(port)).toBe("other-daemon"); + expect(await selfReportDaemonLive(port)).toBe(false); + const r = await syncSelfReportMcp({ + quiet: true, agents: ["claude"], binaryPath: CLI, + deps: { hooksInstalled: () => true, settings: { enabled: true, port } }, + }); + expect(r[0]).toMatchObject({ transport: "stdio" }); + await new Promise((ok) => daemon.close(ok)); + closeAll.pop(); + // This daemon serves MCP too, under its own id, but the port answers with + // another id: still stdio. + track(await fakeDaemon(socket(), true, { instanceId: "this-daemon", port })); + expect(await selfReportDaemonLive(port)).toBe(false); + }); + + it("a pong naming another port, or an endpoint with no instance id, is stdio", async () => { + vi.stubEnv("FAILPROOFAI_DAEMON_SOCKET", socket()); + const { server, port } = await fakeMcp("failproofai_local", "inst-1"); + track(server); + const daemon = track(await fakeDaemon(socket(), true, { instanceId: "inst-1", port: port + 1 })); + expect(await selfReportDaemonLive(port)).toBe(false); + await new Promise((ok) => daemon.close(ok)); + closeAll.pop(); + const old = await fakeMcp("failproofai_local", null); + track(old.server); + expect(await probeSelfReportHttpInstance(old.port)).toBe(""); + track(await fakeDaemon(socket(), true, { instanceId: "inst-1", port: old.port })); + expect(await selfReportDaemonLive(old.port)).toBe(false); + }); + + it("another server on the port is not ours", async () => { + const { server, port } = await fakeMcp("someone-else"); + track(server); + expect(await probeSelfReportHttp(port)).toBe(false); + }); + + it("is not asked when the feature is off or no agent would get an entry", async () => { + const daemonLive = vi.fn(async () => true); + await syncSelfReportMcp({ quiet: true, deps: { daemonLive, hooksInstalled: () => true, settings: { enabled: false, port: 4319 } } }); + await syncSelfReportMcp({ quiet: true, binaryPath: CLI, deps: { daemonLive, hooksInstalled: () => false, settings: { enabled: true, port: 4319 } } }); + expect(daemonLive).not.toHaveBeenCalled(); + }); + + it("selfReportSyncChanged is true only for an add, update or remove", async () => { + const first = await syncSelfReportMcp(enabledOpts({ agents: ["claude"] })); + expect(selfReportSyncChanged(first)).toBe(true); + expect(selfReportSyncChanged(await syncSelfReportMcp(enabledOpts({ agents: ["claude"] })))).toBe(false); + }); +}); + +describe("selfReportRegistrationStatus", () => { + it("reports registered, transport, conflict and hooked per file without writing", async () => { + await syncSelfReportMcp(enabledOpts({ agents: ["claude"] }, false)); + put(pathOf("cursor"), JSON.stringify({ mcpServers: { failproofai_local: { url: "https://elsewhere" } } })); + const s = selfReportRegistrationStatus({ agents: ["claude", "cursor", "factory"], hooksInstalled: (a) => a === "claude" }); + expect(s).toEqual([ + expect.objectContaining({ agent: "claude", hooked: true, registered: true, transport: "stdio", endpoint: CLI, conflict: false }), + expect.objectContaining({ agent: "cursor", hooked: false, registered: false, conflict: true }), + expect.objectContaining({ agent: "factory", hooked: false, registered: false, conflict: false }), + ]); + expect(existsSync(pathOf("factory"))).toBe(false); + }); +}); + +describe("mergeTomlManagedBlock", () => { + const M = { begin: "# >>> b >>>", end: "# <<< b <<<" }; + it("appends, replaces in place and removes byte for byte", async () => { + const orig = 'a = 1\n[t]\nb = 2 # c\n'; + const one = mergeTomlManagedBlock(orig, "# >>> b >>>\nx = 1\n# <<< b <<<\n", M); + expect(one).toBe(`${orig}\n# >>> b >>>\nx = 1\n# <<< b <<<\n`); + const two = mergeTomlManagedBlock(one, "# >>> b >>>\nx = 2\n# <<< b <<<\n", M); + expect(two).toContain("x = 2"); + expect(two).not.toContain("x = 1"); + expect(mergeTomlManagedBlock(two, null, M)).toBe(orig); + }); + it("throws on a half block", async () => { + expect(() => mergeTomlManagedBlock("# >>> b >>>\nx=1\n", null, M)).toThrow(); + }); +}); + +describe("on by default: install, disable, enable", () => { + const settingsFile = () => resolve(home, ".failproofai", "self-report.json"); + /** The sync the CLI runs, against this test's agents and with no daemon. */ + const sync = () => + syncSelfReportMcp({ + quiet: true, + binaryPath: CLI, + agents: ["claude", "cursor"], + deps: { daemonLive: async () => false, hooksInstalled: () => true }, + }); + + it("a fresh install with no file writes it on, registers the server and records", async () => { + expect(existsSync(settingsFile())).toBe(false); + const written = await ensureSelfReportSettingsFile(); + expect(written).toMatchObject({ enabled: true, source: "local" }); + expect(readEffectiveSelfReport()?.categories.map((c) => c.name)).toEqual([ + "looping", "cannot_do_request", "invalid_tool_or_credential", "missing_context", "repeated_tool_failure", "task_failure", + ]); + const results = await sync(); + expect(results.map((r) => r.status)).toEqual(["ok", "ok"]); + expect(entryIn("claude")).toMatchObject({ type: "stdio" }); + expect(entryIn("cursor")).toBeDefined(); + expect(readEnabledSelfReport()).not.toBeNull(); + // A second install leaves the file as it is. + expect(await ensureSelfReportSettingsFile()).toBeNull(); + }); + + it("disable removes the entries and stops recording; enable brings both back", async () => { + await ensureSelfReportSettingsFile(); + await sync(); + expect(entryIn("claude")).toBeDefined(); + + const off = await runSelfReportCommand(["disable"], { sync }); + expect(off.exitCode).toBe(0); + expect(readEffectiveSelfReport()?.enabled).toBe(false); + expect(readEnabledSelfReport()).toBeNull(); + expect(entryIn("claude")).toBeUndefined(); + expect(entryIn("cursor")).toBeUndefined(); + const config = JSON.parse(read(resolve(home, ".failproofai", "config.json"))); + expect(config.selfReport.enabled).toBe(false); + + // An explicit off wins over a later install, with or without the file. + expect(await ensureSelfReportSettingsFile()).toBeNull(); + rmSync(settingsFile()); + expect(readEnabledSelfReport()).toBeNull(); + expect(await ensureSelfReportSettingsFile()).toMatchObject({ enabled: false }); + expect((await sync()).every((r) => r.status === "ok")).toBe(true); + expect(entryIn("claude")).toBeUndefined(); + + const on = await runSelfReportCommand(["enable"], { sync }); + expect(on.exitCode).toBe(0); + expect(readEnabledSelfReport()).not.toBeNull(); + expect(entryIn("claude")).toBeDefined(); + expect(entryIn("cursor")).toBeDefined(); + }); + + it("a Cloud-enrolled machine writes no file on install and stays off until the daemon writes it", async () => { + vi.stubEnv("FAILPROOFAI_CLOUD_URL", "https://cloud.example.com"); + expect(await ensureSelfReportSettingsFile()).toBeNull(); + expect(existsSync(settingsFile())).toBe(false); + expect(readEnabledSelfReport()).toBeNull(); + await sync(); + expect(entryIn("claude")).toBeUndefined(); + const refused = await runSelfReportCommand(["disable"], { sync }); + expect(refused.exitCode).toBe(1); + expect(refused.lines.join("\n")).toContain("Settings > Self Reports"); + }); + + it("a malformed file is off and an install leaves it alone", async () => { + put(settingsFile(), "{ not json"); + expect(await ensureSelfReportSettingsFile()).toBeNull(); + expect(read(settingsFile())).toBe("{ not json"); + expect(readEnabledSelfReport()).toBeNull(); + await sync(); + expect(entryIn("claude")).toBeUndefined(); + }); +}); + +describe("the test-only real-home guard", () => { + it("refuses to write an agent config under the developer's real home", async () => { + const { userInfo } = await import("node:os"); + const { join } = await import("node:path"); + const realHome = userInfo().homedir; + const prev = process.env.HOME; + // Simulate a test that forgot to move HOME: the writer resolves the real home. + process.env.HOME = realHome; + try { + const mod = await import("../../src/hooks/self-report-install"); + const results = await mod.syncSelfReportMcp({ enabled: true, quiet: true, agents: ["cursor"], alsoHooked: ["cursor"] } as never); + const target = join(realHome, ".cursor", "mcp.json"); + const written = results.find((r: { agent: string; path?: string; action?: string }) => r.agent === "cursor"); + expect(written?.action).not.toBe("added"); + expect(written?.action).not.toBe("updated"); + expect(String(written?.path ?? target).startsWith(realHome)).toBe(true); + } finally { + if (prev === undefined) delete process.env.HOME; + else process.env.HOME = prev; + } + }); +}); diff --git a/__tests__/hooks/self-report-log-exit.test.ts b/__tests__/hooks/self-report-log-exit.test.ts new file mode 100644 index 000000000..8b42ffe75 --- /dev/null +++ b/__tests__/hooks/self-report-log-exit.test.ts @@ -0,0 +1,125 @@ +// @vitest-environment node +/** + * The real CLI exits 0 after its Self Reports log events, whatever the daemon + * does with the connection. The log client half-closes and waits for the + * daemon to close (macOS drops a not-yet-accepted connection's data when the + * client destroys it), and that wait is bounded by the budget. With both the + * socket and the budget timer unref'd, a process with nothing else to do + * found its flush pending and Node exited 13 (unsettled top-level await). + */ +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from "vitest"; +import { execFileSync, spawn } from "node:child_process"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, join, resolve } from "node:path"; +import { createServer, type Server, type Socket } from "node:net"; + +const ROOT = resolve(__dirname, "..", ".."); +const ENTRY = resolve(ROOT, "bin", "fail" + "proofai.mjs"); +// The packaged CLI is the bundle run by Node (package.json "bin"), where an +// unsettled top-level await is exit 13; Bun does not report it. Built the way +// `build:cli` builds it, into a cache directory beside node_modules so its +// externals resolve. +const BUNDLE = resolve(ROOT, "node_modules", ".cache", `fp-exit-test-${process.pid}`, "cli.mjs"); + +beforeAll(() => { + execFileSync("bun", ["build", "--target=node", "--format=esm", `--outfile=${BUNDLE}`, ENTRY, "--external", "sql.js"], { + cwd: ROOT, + stdio: "ignore", + }); +}, 120_000); + +afterAll(() => { + rmSync(dirname(BUNDLE), { recursive: true, force: true }); +}); +const INIT = { jsonrpc: "2.0", id: 1, method: "initialize", params: { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "t", version: "1" } } }; +const LIST = { jsonrpc: "2.0", id: 2, method: "tools/list" }; + +let home: string; +let server: Server | null = null; +const held: Socket[] = []; + +beforeEach(() => { + home = mkdtempSync(join(tmpdir(), "fpai-srlog-exit-")); +}); + +afterEach(async () => { + for (const s of held.splice(0)) s.destroy(); + await new Promise((ok) => (server ? server.close(() => ok()) : ok())); + server = null; + rmSync(home, { recursive: true, force: true }); +}); + +/** A fake daemon socket: reads every frame, then closes after `closeAfterMs`, or never (null). */ +function fakeDaemon(path: string, closeAfterMs: number | null): Promise<{ frames: () => number }> { + let frames = 0; + server = createServer((socket) => { + held.push(socket); + socket.on("data", () => frames++); + socket.on("error", () => {}); + socket.on("end", () => { + if (closeAfterMs !== null) setTimeout(() => socket.destroy(), closeAfterMs); + }); + }); + return new Promise((ok) => server!.listen(path, () => ok({ frames: () => frames }))); +} + +function run(args: string[], input: string): Promise<{ code: number | null; ms: number; stdout: string; stderr: string }> { + return new Promise((done, fail) => { + const started = Date.now(); + const child = spawn(process.execPath, [BUNDLE, ...args], { + env: { + ...process.env, + HOME: join(home, "user"), + FAILPROOFAI_HOME: home, + FAILPROOFAI_DAEMON_SOCKET: join(home, "d.sock"), + FAILPROOFAI_TELEMETRY_DISABLED: "1", + FAILPROOFAI_CODEX_SYSTEM_CONFIG: "off", + }, + stdio: ["pipe", "pipe", "pipe"], + }); + let stdout = ""; + let stderr = ""; + child.stdout.on("data", (b: Buffer) => (stdout += b.toString())); + child.stderr.on("data", (b: Buffer) => (stderr += b.toString())); + child.on("error", fail); + child.on("close", (code) => done({ code, ms: Date.now() - started, stdout, stderr })); + child.stdin.end(input); + }); +} + +const mcpInput = [INIT, LIST].map((m) => JSON.stringify(m)).join("\n") + "\n"; + +describe("the CLI exits 0 after its log events", () => { + it("mcp: the daemon reads and closes late (within the budget)", async () => { + const daemon = await fakeDaemon(join(home, "d.sock"), 120); + const r = await run(["mcp", "--agent", "claude"], mcpInput); + expect(r.code, r.stderr).toBe(0); + expect(r.stdout).toContain('"id":2'); + expect(daemon.frames()).toBeGreaterThan(0); + }, 30_000); + + it("mcp: the daemon reads and never closes: exits 0 once the budget runs out, not later", async () => { + const daemon = await fakeDaemon(join(home, "d.sock"), null); + const control = await run(["--version"], ""); + const r = await run(["mcp", "--agent", "claude"], mcpInput); + expect(r.code, r.stderr).toBe(0); + expect(daemon.frames()).toBeGreaterThan(0); + // Startup varies; the wait for a daemon that never closes is bounded by + // the budget (250 ms, at most once more when the timer fires late). + expect(r.ms - control.ms).toBeLessThan(1_500); + }, 30_000); + + it("mcp: no daemon socket at all", async () => { + const r = await run(["mcp", "--agent", "claude"], mcpInput); + expect(r.code, r.stderr).toBe(0); + }, 30_000); + + it("self-report enable and disable exit 0 with a daemon that never closes", async () => { + await fakeDaemon(join(home, "d.sock"), null); + for (const sub of ["disable", "enable"]) { + const r = await run(["self-report", sub], ""); + expect(r.code, `${sub}: ${r.stderr}${r.stdout}`).toBe(0); + } + }, 60_000); +}); diff --git a/__tests__/hooks/self-report-log.test.ts b/__tests__/hooks/self-report-log.test.ts new file mode 100644 index 000000000..ac76bc832 --- /dev/null +++ b/__tests__/hooks/self-report-log.test.ts @@ -0,0 +1,399 @@ +// @vitest-environment node +/** + * Lean Self Reports output and the daemon-log events: + * - the one summary line install, config, uninstall, enable and disable print; + * - the sync result line the daemon logs; + * - `selfReportLog` frames from the stdio server and syncs, over the daemon + * socket, fire-and-forget (no daemon, a dead socket, an old daemon: dropped); + * - setup's finish step: one spinner, then only what needs the user. + */ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { createServer, type Server } from "node:net"; +import { + selfReportSummaryLine, + selfReportSyncLogLine, + type SelfReportMcpResult, +} from "../../src/hooks/self-report-install"; +import { SELF_REPORT_LOG_BUDGET_MS, flushSelfReportLogs, sendSelfReportLog } from "../../src/hooks/self-report-log"; +import { handleSelfReportRpc, runSelfReportMcpServer } from "../../src/hooks/self-report-mcp"; +import { writeEffectiveSelfReport } from "../../src/hooks/self-report"; +import { progressLine } from "../../src/hooks/tui"; +import { selfReportLogCategoryText } from "../../src/hooks/self-report-names"; +import { PassThrough } from "node:stream"; + +let home: string; +const saved: Record = {}; + +beforeEach(() => { + home = mkdtempSync(join(tmpdir(), "fpai-srlog-")); + for (const k of ["FAILPROOFAI_HOME", "FAILPROOFAI_DAEMON_SOCKET", "FAILPROOFAI_CLOUD_URL", "FAILPROOFAI_SELF_REPORT_SYNC_LOG"]) { + saved[k] = process.env[k]; + delete process.env[k]; + } + process.env.FAILPROOFAI_HOME = home; + process.env.FAILPROOFAI_DAEMON_SOCKET = join(home, "d.sock"); +}); + +afterEach(() => { + for (const [k, v] of Object.entries(saved)) { + if (v === undefined) delete process.env[k]; + else process.env[k] = v; + } + rmSync(home, { recursive: true, force: true }); +}); + +const r = (agent: string, action: string, extra: Partial = {}): SelfReportMcpResult => + ({ agent, path: `/h/${agent}.json`, action, transport: action === "removed" ? "stdio" : "stdio", status: "ok", ...extra }) as SelfReportMcpResult; + +describe("the one Self Reports line", () => { + it("counts the agents left registered, once each", () => { + const results = [r("claude", "added"), r("codex", "unchanged"), r("hermes", "added"), r("hermes", "updated"), r("pi", "unchanged", { transport: "extension" })]; + expect(selfReportSummaryLine(results, "on")).toBe("✓ Self Reports: on for 4 agents"); + expect(selfReportSummaryLine([r("claude", "unchanged")], "on")).toBe("✓ Self Reports: on for 1 agent"); + // On with nothing hooked: nothing to say. + expect(selfReportSummaryLine([r("goose", "skipped", { transport: null, status: "not-hooked" })], "on")).toBeNull(); + }); + + it("off is one line whatever was removed, and names Cloud while it waits for it", () => { + const removed = Array.from({ length: 12 }, (_, i) => r(`a${i}`, "removed")); + expect(selfReportSummaryLine(removed, "off")).toBe("✓ Self Reports: off"); + expect(selfReportSummaryLine(removed, "waiting")).toBe("✓ Self Reports: off until Cloud sends this machine's setting"); + expect(selfReportSummaryLine([r("claude", "removed"), r("codex", "removed")], "removed")).toBe("✓ Self Reports: removed from 2 agents"); + expect(selfReportSummaryLine([r("claude", "unchanged", { transport: null })], "removed")).toBeNull(); + }); + + it("names the agents that failed in the same line, with the fix", () => { + const results = [ + r("claude", "added"), + r("codex", "skipped", { transport: null, status: "error", detail: "EACCES" }), + r("cursor", "skipped", { transport: null, status: "conflict" }), + ]; + expect(selfReportSummaryLine(results, "on")).toBe( + "▲ Self Reports: on for 1 agent; not updated for OpenAI Codex, Cursor Agent · failproofai self-report sync", + ); + expect(selfReportSummaryLine([results[1]], "removed")).toBe( + "▲ Self Reports: not updated for OpenAI Codex · failproofai self-report sync", + ); + }); +}); + +describe("the sync line the daemon logs", () => { + it("names agents and transports, never a path, and nothing when nothing changed", () => { + const line = selfReportSyncLogLine([ + r("claude", "added", { transport: "http" }), + r("cursor", "updated"), + r("pi", "removed"), + r("codex", "unchanged"), + r("factory", "skipped", { transport: null, status: "error", detail: "no daemon is answering here" }), + ]); + expect(line).toBe("added claude (http); updated cursor (stdio); removed pi; failed factory (no daemon is answering here)"); + expect(line).not.toContain("/h/"); + expect(selfReportSyncLogLine([r("codex", "unchanged")])).toBeNull(); + }); +}); + +/** A fake daemon socket that records every frame it is sent. */ +function fakeDaemon(path: string): Promise<{ server: Server; frames: Array> }> { + const frames: Array> = []; + const server = createServer((socket) => { + let buf = Buffer.alloc(0); + socket.on("data", (chunk: Buffer) => { + buf = Buffer.concat([buf, chunk]); + while (buf.length >= 4 && buf.length >= 4 + buf.readUInt32BE(0)) { + const len = buf.readUInt32BE(0); + frames.push(JSON.parse(buf.subarray(4, 4 + len).toString("utf8"))); + buf = buf.subarray(4 + len); + } + }); + socket.on("error", () => {}); + }); + return new Promise((ok) => server.listen(path, () => ok({ server, frames }))); +} + +describe("selfReportLog over the daemon socket", () => { + it("sends one framed selfReportLog with the whole (bounded) detail, for the daemon to scrub before it cuts", async () => { + const { server, frames } = await fakeDaemon(process.env.FAILPROOFAI_DAEMON_SOCKET!); + try { + await sendSelfReportLog({ event: "tools/call", agent: "hermes", transport: "stdio", outcome: "recorded", preview: "x ".repeat(35_000) }); + await vi.waitFor(() => expect(frames).toHaveLength(1)); + expect(frames[0]).toMatchObject({ type: "selfReportLog", protocolVersion: 2, event: { event: "tools/call", agent: "hermes", outcome: "recorded" } }); + // Bounded at 64 KiB, at a word boundary (the trailing space goes too). + expect(((frames[0].event as Record).preview).length).toBe(64 * 1024 - 1); + } finally { + server.close(); + } + }); + + // F18: cutting the detail to 200 characters here cut a long JWT into two + // segments, which the daemon's scrubber no longer recognised, so its raw + // start reached the daemon log over stdio (HTTP logged [redacted:jwt]). + it("sends a JWT longer than 200 characters whole, and the raw category whole", async () => { + const { server, frames } = await fakeDaemon(process.env.FAILPROOFAI_DAEMON_SOCKET!); + try { + const seg = (n: number) => "a".repeat(n); + const jwt = `eyJhbGciOiJIUzI1NiJ9.eyJ${seg(250)}.${seg(43)}`; + await sendSelfReportLog({ event: "tools/call", transport: "stdio", preview: `token ${jwt} rejected`, rawCategory: `ghp_${"A".repeat(36)}` }); + await vi.waitFor(() => expect(frames).toHaveLength(1)); + const event = frames[0].event as Record; + expect(event.preview).toBe(`token ${jwt} rejected`); + expect(event.rawCategory).toBe(`ghp_${"A".repeat(36)}`); + } finally { + server.close(); + } + }); + + // F18 round 3: a JWT straddling the 64 KiB bound was cut into a fragment the + // daemon's scrubber no longer recognised, and its start reached the log. + it("never sends part of a token at the 64 KiB bound", async () => { + const { server, frames } = await fakeDaemon(process.env.FAILPROOFAI_DAEMON_SOCKET!); + try { + const jwt = `eyJhbGciOiJIUzI1NiJ9.eyJ${"a".repeat(70_000)}.sig`; + await sendSelfReportLog({ event: "tools/call", transport: "stdio", preview: `token ${jwt} rejected` }); + await handleSelfReportRpc( + { jsonrpc: "2.0", id: 3, method: "tools/call", params: { name: "report", arguments: { category: "looping", detail: jwt } } }, + { agent: "copilot", cwd: home }, + ); + await flushSelfReportLogs(1000); + await vi.waitFor(() => expect(frames.length).toBeGreaterThanOrEqual(2)); + const previews = frames.map((f) => (f.event as Record).preview); + expect(previews[0]).toBe("token"); + expect(previews.some((p) => p?.includes("eyJ"))).toBe(false); + } finally { + server.close(); + } + }); + + it("bounds the preview on a character boundary, never through a surrogate pair", async () => { + const { server, frames } = await fakeDaemon(process.env.FAILPROOFAI_DAEMON_SOCKET!); + try { + // 65535 ASCII then emoji: the 65536th code point is whole, nothing after it. + await sendSelfReportLog({ event: "tools/call", transport: "stdio", preview: `${"a".repeat(64 * 1024 - 1)}😀 environment` }); + await vi.waitFor(() => expect(frames).toHaveLength(1)); + const preview = (frames[0].event as Record).preview; + expect(preview).toBe(`${"a".repeat(64 * 1024 - 1)}😀`); + expect(preview).not.toContain("�"); + } finally { + server.close(); + } + }); + + // macOS: the stdio server's process lookup runs `ps` synchronously. A blocked + // event loop made the budget timer fire before the (already finished) + // connect was delivered, and the line was dropped as if no daemon answered. + it("still delivers when the event loop was blocked past the budget while it connected", async () => { + const { server, frames } = await fakeDaemon(process.env.FAILPROOFAI_DAEMON_SOCKET!); + try { + const sent = sendSelfReportLog({ event: "tools/call", agent: "claude", transport: "stdio", outcome: "recorded" }); + const until = Date.now() + SELF_REPORT_LOG_BUDGET_MS + 200; + while (Date.now() < until) { + // a synchronous call holding the event loop, like execFileSync("ps") + } + await sent; + await vi.waitFor(() => expect(frames).toHaveLength(1)); + expect(frames[0]).toMatchObject({ event: { event: "tools/call", outcome: "recorded" } }); + } finally { + server.close(); + } + }); + + it("never waits on a daemon: none, a dead socket, or one that never reads", async () => { + // None. + let t = Date.now(); + await sendSelfReportLog({ event: "initialize" }); + expect(Date.now() - t).toBeLessThan(50); + // A socket file nobody listens on. + writeFileSync(process.env.FAILPROOFAI_DAEMON_SOCKET!, ""); + t = Date.now(); + await sendSelfReportLog({ event: "initialize" }); + expect(Date.now() - t).toBeLessThan(SELF_REPORT_LOG_BUDGET_MS + 100); + rmSync(process.env.FAILPROOFAI_DAEMON_SOCKET!); + // A listener that accepts and never answers (an old daemon reads, fails to + // parse, and closes; this one does not even close). + const held = createServer(() => {}); + await new Promise((ok) => held.listen(process.env.FAILPROOFAI_DAEMON_SOCKET!, () => ok())); + try { + t = Date.now(); + await sendSelfReportLog({ event: "initialize" }); + await flushSelfReportLogs(); + expect(Date.now() - t).toBeLessThan(SELF_REPORT_LOG_BUDGET_MS + 100); + } finally { + held.close(); + } + }); + + it("the stdio server logs initialize, tools/list and each call: recorded, with its session, or skipped and why", async () => { + const { server, frames } = await fakeDaemon(process.env.FAILPROOFAI_DAEMON_SOCKET!); + try { + writeEffectiveSelfReport({ enabled: true }); + const opts = { agent: "copilot", cwd: home }; + await handleSelfReportRpc({ jsonrpc: "2.0", id: 1, method: "initialize", params: {} }, opts); + await handleSelfReportRpc({ jsonrpc: "2.0", id: 2, method: "tools/list" }, opts); + const call = (args: Record) => + handleSelfReportRpc({ jsonrpc: "2.0", id: 3, method: "tools/call", params: { name: "report", arguments: args } }, opts); + await call({ category: "looping", detail: "stuck" }); + await call({ category: "made_up", detail: "odd" }); + writeEffectiveSelfReport({ enabled: false }); + await call({ category: "looping", detail: "off now" }); + writeFileSync(join(home, "self-report.json"), "{broken"); + await call({ category: "looping", detail: "broken" }); + await handleSelfReportRpc({ jsonrpc: "2.0", id: 4, method: "tools/call", params: { name: "report", arguments: {} } }, { cwd: home }); + await flushSelfReportLogs(1000); + await vi.waitFor(() => expect(frames).toHaveLength(7)); + const events = frames.map((f) => f.event as Record); + expect(events[0]).toMatchObject({ event: "initialize", agent: "copilot", transport: "stdio", outcome: "on" }); + expect(events[1]).toMatchObject({ event: "tools/list", outcome: "report" }); + expect(events[2]).toMatchObject({ event: "tools/call", outcome: "recorded", category: "looping", knownCategory: true, session: "unattributed", preview: "stuck" }); + // An unlisted category is recorded as the one it resolves to; the log keeps what was sent. + expect(events[3]).toMatchObject({ outcome: "recorded", category: "task_failure", knownCategory: false, rawCategory: "made_up" }); + expect(events[2].rawCategory).toBeUndefined(); + expect(events[4]).toMatchObject({ outcome: "skipped", reason: "Self Reports is off" }); + expect(events[5]).toMatchObject({ outcome: "skipped", reason: "settings unreadable" }); + expect(events[6]).toMatchObject({ outcome: "skipped", reason: "no --agent" }); + // Two reports were written, as before. + expect(readdirSync(join(home, "custom-agents", "events")).filter((f) => f.endsWith(".jsonl"))).toHaveLength(2); + } finally { + server.close(); + } + }); + + // F18 round 2: a JWT that starts in the preview and runs past the + // 2,000-character report cut. The report is cut there, but the log frame + // carries the detail as sent, so the daemon's scrubber sees the whole token + // (crates/failproofaid/tests/self_report_e2e.rs checks the daemon's half). + it("the stdio server sends the log the detail as sent, not the 2000-character report cut", async () => { + const { server, frames } = await fakeDaemon(process.env.FAILPROOFAI_DAEMON_SOCKET!); + try { + writeEffectiveSelfReport({ enabled: true }); + const jwt = `eyJhbGciOiJIUzI1NiJ9.eyJ${"a".repeat(2500)}.${"b".repeat(43)}`; + const detail = `token ${jwt} rejected`; + await handleSelfReportRpc( + { jsonrpc: "2.0", id: 3, method: "tools/call", params: { name: "report", arguments: { category: "looping", detail } } }, + { agent: "copilot", cwd: home }, + ); + await flushSelfReportLogs(1000); + await vi.waitFor(() => expect(frames).toHaveLength(1)); + expect((frames[0].event as Record).preview).toBe(detail); + // The report itself is cut at 2000, without the part of the token before the cut. + const [file] = readdirSync(join(home, "custom-agents", "events")).filter((f) => f.endsWith(".jsonl")); + const event = JSON.parse(readFileSync(join(home, "custom-agents", "events", file), "utf8")); + expect(event.detail).toBe("token"); + } finally { + server.close(); + } + }); + + it("the stdio server's run waits for its events, at most the budget, before it ends", async () => { + const { server, frames } = await fakeDaemon(process.env.FAILPROOFAI_DAEMON_SOCKET!); + try { + writeEffectiveSelfReport({ enabled: true }); + const input = new PassThrough(); + const output = new PassThrough(); + const run = runSelfReportMcpServer({ agent: "goose", cwd: home, input, output }); + input.end(`${JSON.stringify({ jsonrpc: "2.0", id: 1, method: "initialize", params: {} })}\n`); + await run; + await vi.waitFor(() => expect(frames.map((f) => (f.event as { event: string }).event)).toEqual(["initialize"])); + } finally { + server.close(); + } + }); +}); + +describe("progressLine", () => { + it("piped: draws nothing while it runs, then prints only the lines to keep", () => { + let out = ""; + const stream = { isTTY: false, write: (s: string) => ((out += s), true) } as unknown as NodeJS.WritableStream; + const p = progressLine(stream, "Working…"); + p.set("Still working…"); + p.done(["✓ Self Reports: on for 3 agents"]); + expect(out).toBe("✓ Self Reports: on for 3 agents\n"); + out = ""; + const q = progressLine(stream, "Working…"); + q.done([]); + expect(out).toBe(""); + }); + + it("on a terminal: one spinner line, erased when there is nothing to keep", () => { + const noColor = process.env.NO_COLOR; + delete process.env.NO_COLOR; + let out = ""; + const stream = { isTTY: true, columns: 80, write: (s: string) => ((out += s), true) } as unknown as NodeJS.WritableStream; + const p = progressLine(stream, "Restarting agent gateways…"); + expect(out).toContain("Restarting agent gateways…"); + out = ""; + p.done([]); + // Up one line, clear to the end, cursor back; nothing printed. + expect(out).toBe("\x1b[1A\x1b[J\x1b[?25h"); + if (noColor !== undefined) process.env.NO_COLOR = noColor; + }); +}); + +describe("setup's finish step", () => { + it("leaves the Self Reports line and only what needs the user", async () => { + vi.resetModules(); + const realUpdateRun = await vi.importActual("../../src/hooks/update-run"); + vi.doMock("../../src/hooks/update-run", () => ({ + setupNeedsUpdateSteps: () => true, + runUpdateSteps: async () => ({ + ok: true, + lines: [" hermes/default already current, gateway restarting", "✕ Hermes: plugin could not be updated"], + restarts: [ + { host: "openclaw", profile: "default", status: "restarting" }, + { host: "hermes", profile: "work", status: "not-supervised" }, + ], + }), + setupGatewayLine: realUpdateRun.setupGatewayLine, + restartNewlyPlugged: async () => [], + markUpdated: vi.fn(), + })); + vi.doMock("../../src/hooks/self-report-install", async () => ({ + ...(await vi.importActual("../../src/hooks/self-report-install")), + syncSelfReportMcp: async () => Array.from({ length: 12 }, (_, i) => r(`a${i}`, "added")), + })); + try { + writeEffectiveSelfReport({ enabled: true }); + const { finishSetup } = await import("../../src/hooks/setup-finish"); + let out = ""; + const stream = { isTTY: false, write: (s: string) => ((out += s), true) } as unknown as NodeJS.WritableStream; + expect(await finishSetup({ version: "9.9.9", pluggedBefore: [], out: stream })).toBe(0); + expect(out.trimEnd().split("\n")).toEqual([ + "✕ Hermes: plugin could not be updated", + "▲ hermes/work: restart the gateway", + ]); + // A sync that worked says nothing; `self-report status` does. + expect(out).not.toContain("Self Reports"); + expect(out).not.toContain("gateway restarting"); + expect(out).not.toContain("MCP server"); + } finally { + vi.doUnmock("../../src/hooks/update-run"); + vi.doUnmock("../../src/hooks/self-report-install"); + vi.resetModules(); + } + }); +}); + +// F20: the model's category was logged verbatim (raw_category=""). +describe("selfReportLogCategoryText", () => { + it("shows a category-shaped name as written", () => { + for (const c of ["", "looping", "token_expired", "auth-failure", "operator_blocker", "error 401", "v2.api_down"]) { + expect(selfReportLogCategoryText(c), c).toBe(c); + } + }); + + it("hides anything else, tokens included, saying only how long it was", () => { + const cases: Array<[string, number]> = [ + [`ghp_${"A".repeat(36)}`, 40], + ["AKIAIOSFODNN7EXAMPLE", 20], + ["sk-proj-abc123def456ghi789", 26], + ["eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxIn0.sig", 40], + ["d41d8cd98f00b204e9800998ecf8427e", 32], + ["Looping", 7], + ["a".repeat(33), 33], + ["xoxb-123456789012-abcdefghijkl", 30], + ["token=hunter2", 13], + ]; + for (const [raw, n] of cases) expect(selfReportLogCategoryText(raw), raw).toBe(`(${n} characters, not shown)`); + }); +}); diff --git a/__tests__/hooks/self-report-mcp-errors.test.ts b/__tests__/hooks/self-report-mcp-errors.test.ts new file mode 100644 index 000000000..b9cb1c29c --- /dev/null +++ b/__tests__/hooks/self-report-mcp-errors.test.ts @@ -0,0 +1,85 @@ +// @vitest-environment node +/** + * The stdio Self Reports MCP server never leaves a request unanswered (review + * #1105 item 8): a handler that throws gets a JSON-RPC internal error for that + * request, a notification gets nothing, and the server keeps serving. + */ +import { describe, it, expect, vi, beforeEach } from "vitest"; +import { PassThrough } from "node:stream"; + +const boom = vi.hoisted(() => ({ on: false })); +vi.mock("../../src/hooks/self-report", async (orig) => { + const real = await orig(); + return { + ...real, + readEnabledSelfReport: (...args: Parameters) => { + if (boom.on) throw new Error("forced failure"); + return real.readEnabledSelfReport(...args); + }, + }; +}); +vi.mock("../../src/hooks/self-report-log", async (orig) => { + const real = await orig(); + return { ...real, sendSelfReportLog: vi.fn(async () => {}), flushSelfReportLogs: vi.fn(async () => {}) }; +}); + +import { runSelfReportMcpServer } from "../../src/hooks/self-report-mcp"; + +async function exchange(lines: unknown[]): Promise { + const input = new PassThrough(); + const output = new PassThrough(); + let text = ""; + output.on("data", (d: Buffer) => (text += d.toString("utf8"))); + const stderr = vi.spyOn(process.stderr, "write").mockImplementation(() => true); + try { + const run = runSelfReportMcpServer({ agent: "goose", cwd: "/", input, output }); + input.end(lines.map((l) => `${JSON.stringify(l)}\n`).join("")); + await run; + } finally { + stderr.mockRestore(); + } + return text.split("\n").filter(Boolean).map((l) => JSON.parse(l) as unknown); +} + +beforeEach(() => { + boom.on = false; +}); + +describe("stdio MCP server: a handler that throws", () => { + it("answers that request with -32603, says nothing to a notification, and keeps serving", async () => { + boom.on = true; + const replies = await exchange([ + { jsonrpc: "2.0", id: 7, method: "tools/list", params: {} }, + { jsonrpc: "2.0", method: "notifications/initialized" }, + { jsonrpc: "2.0", id: "s1", method: "tools/list" }, + { jsonrpc: "2.0", id: 8, method: "ping" }, + ]); + expect(replies).toEqual([ + { jsonrpc: "2.0", id: 7, error: { code: -32603, message: "Internal error: forced failure" } }, + { jsonrpc: "2.0", id: "s1", error: { code: -32603, message: "Internal error: forced failure" } }, + { jsonrpc: "2.0", id: 8, result: {} }, + ]); + }); + + it("inside a batch: the throwing request gets its error, the others their results", async () => { + boom.on = true; + const replies = await exchange([ + [ + { jsonrpc: "2.0", id: 1, method: "tools/list" }, + { jsonrpc: "2.0", id: 2, method: "ping" }, + { jsonrpc: "2.0", method: "notifications/initialized" }, + ], + ]); + expect(replies).toEqual([ + [ + { jsonrpc: "2.0", id: 1, error: { code: -32603, message: "Internal error: forced failure" } }, + { jsonrpc: "2.0", id: 2, result: {} }, + ], + ]); + }); + + it("control: without the forced failure the same request is answered normally", async () => { + const [reply] = await exchange([{ jsonrpc: "2.0", id: 7, method: "tools/list" }]); + expect(reply).toMatchObject({ jsonrpc: "2.0", id: 7, result: { tools: expect.any(Array) } }); + }); +}); diff --git a/__tests__/hooks/self-report-origin-config.test.ts b/__tests__/hooks/self-report-origin-config.test.ts new file mode 100644 index 000000000..d30d9ecbc --- /dev/null +++ b/__tests__/hooks/self-report-origin-config.test.ts @@ -0,0 +1,210 @@ +// @vitest-environment node +/** + * The report exemption must judge the registration the CALLING agent uses, + * not the one the daemon's warm worker would find in its own environment + * (bot review of #1105, handler.ts ~959). Driven through the worker's real + * socket loop: the worker process's env plays the daemon's (a genuine + * registration under its HOME), while the agent ran with CODEX_HOME / + * CLAUDE_CONFIG_DIR elsewhere. + */ +import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; +import { createConnection, type Server, type Socket } from "node:net"; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +vi.mock("../../src/hooks/hooks-config", () => ({ + readMergedHooksConfig: vi.fn(() => ({ enabledPolicies: [] })), +})); +vi.mock("../../src/hooks/custom-hooks-loader", () => ({ loadAllCustomHooks: vi.fn() })); +vi.mock("../../src/hooks/hook-telemetry", () => ({ + trackHookEvent: vi.fn(() => Promise.resolve()), + flushHookTelemetry: vi.fn(() => Promise.resolve()), +})); +vi.mock("../../lib/telemetry-id", () => ({ getInstanceId: vi.fn(() => "test-instance-id") })); +vi.mock("../../src/hooks/untraced-note", () => ({ noteUntracedAgent: vi.fn(() => false) })); +vi.mock("../../src/hooks/pack-manifest", () => ({ + readInstalledPacks: vi.fn(() => ({ packs: [], errors: [] })), + hasInstalledPacks: vi.fn(() => false), + hasInstalledRegexPacks: vi.fn(() => false), +})); + +import { loadAllCustomHooks } from "../../src/hooks/custom-hooks-loader"; +import { _resetForTest } from "../../src/hooks/hook-activity-store"; +import { writeEffectiveSelfReport } from "../../src/hooks/self-report"; +import { markAgentEnv } from "../../src/hooks/agent-env"; +import { isolateAgentHome, registerOwnSelfReportServer } from "../helpers/self-report-registration"; + +function encodeFrame(value: unknown): Buffer { + const body = Buffer.from(JSON.stringify(value), "utf8"); + const header = Buffer.alloc(4); + header.writeUInt32BE(body.length, 0); + return Buffer.concat([header, body]); +} + +function send(socketPath: string, request: unknown): Promise> { + return new Promise((resolveP, reject) => { + const socket: Socket = createConnection({ path: socketPath }, () => socket.write(encodeFrame(request))); + let buf = Buffer.alloc(0); + socket.on("data", (chunk: Buffer) => { + buf = Buffer.concat([buf, chunk]); + if (buf.length < 4) return; + const len = buf.readUInt32BE(0); + if (buf.length < 4 + len) return; + socket.end(); + resolveP(JSON.parse(buf.subarray(4, 4 + len).toString("utf8")) as Record); + }); + socket.on("error", reject); + }); +} + +let root: string; +let daemonHome: string; +let project: string; +let socketPath: string; +let server: Server; +const FOREIGN_TOML = '[mcp_servers.failproofai_local]\ncommand = "node"\nargs = ["/tmp/x/evil.js"]\n'; +const FOREIGN_JSON = { mcpServers: { failproofai_local: { type: "stdio", command: "node", args: ["/tmp/x/evil.js"] } } }; + +const tool = "mcp__failproofai_local__report"; +const payload = () => JSON.stringify({ session_id: "s", cwd: project, tool_name: tool, tool_input: { category: "looping", detail: "x" } }); +/** What this build's hook CLI sends, run by an agent whose environment is `env`. */ +const fromClient = (env: Record) => markAgentEnv(payload(), env); + +async function decide(cli: string, stdin: string, agentSettingsPath: string): Promise { + const res = await send(socketPath, { type: "hook", protocolVersion: 2, hookEvent: "PreToolUse", cli, stdin, cwd: project, agentSettingsPath }); + return (res.evaluation as { decision?: string } | undefined)?.decision; +} + +beforeEach(async () => { + root = mkdtempSync(join(tmpdir(), "fpai-sr-origin-")); + daemonHome = join(root, "daemon-home"); + project = join(root, "project"); + mkdirSync(project, { recursive: true }); + // The daemon's environment: a genuine registration for every agent. + isolateAgentHome(daemonHome); + await registerOwnSelfReportServer(); + vi.stubEnv("FAILPROOFAI_HOME", join(root, "fp")); + vi.stubEnv("FAILPROOFAI_STATE_DIR", join(root, "fp", "state")); + _resetForTest(join(root, "fp", "hook-activity")); + writeEffectiveSelfReport({ enabled: true }); + vi.mocked(loadAllCustomHooks).mockImplementation((async () => ({ + hooks: [ + Object.assign( + { name: "deny-all", description: "", match: {}, fn: async () => ({ decision: "deny", reason: "nothing passes" }) }, + { __policyId: "custom:/tmp/deny.mjs:deny-all" }, + ), + ], + conventionSources: [], + })) as never); + socketPath = join(tmpdir(), `fpai-sr-origin-${process.pid}-${Date.now()}.sock`); + const { startWorkerServer } = await import("../../src/hooks/worker-server"); + server = startWorkerServer(socketPath); + await new Promise((r) => (server.listening ? r() : server.once("listening", () => r()))); +}); + +afterEach(async () => { + await new Promise((r) => server.close(() => r())); + vi.unstubAllEnvs(); + _resetForTest(); + rmSync(root, { recursive: true, force: true }); +}); + +describe("Codex with CODEX_HOME elsewhere than the daemon's", () => { + it("control: the deny-all policy denies an ordinary call through the worker", async () => { + const bash = JSON.stringify({ session_id: "s", cwd: project, tool_name: "Bash", tool_input: { command: "ls" } }); + expect(await decide("codex", bash, join(daemonHome, ".codex", "hooks.json"))).toBe("deny"); + }); + + it("control: the daemon's own registration, from a client with the same environment, is exempt", async () => { + expect(await decide("codex", fromClient({ ...process.env }), join(daemonHome, ".codex", "hooks.json"))).toBe("allow"); + }); + + it("a foreign failproofai_local in the agent's CODEX_HOME gets no exemption, though the daemon's is genuine", async () => { + const alt = join(root, "alt-codex"); + mkdirSync(alt, { recursive: true }); + writeFileSync(join(alt, "config.toml"), FOREIGN_TOML); + expect(await decide("codex", fromClient({ ...process.env, CODEX_HOME: alt }), join(alt, "hooks.json"))).toBe("deny"); + }); + + it("a client that sent no environment (older client, raw socket) gets no exemption from the worker", async () => { + const alt = join(root, "alt-codex"); + mkdirSync(alt, { recursive: true }); + writeFileSync(join(alt, "config.toml"), FOREIGN_TOML); + expect(await decide("codex", payload(), join(alt, "hooks.json"))).toBe("deny"); + }); + + it("a genuine registration in the agent's CODEX_HOME is exempt", async () => { + const alt = join(root, "alt-codex"); + mkdirSync(alt, { recursive: true }); + vi.stubEnv("CODEX_HOME", alt); + await registerOwnSelfReportServer(); + vi.stubEnv("CODEX_HOME", ""); + expect(await decide("codex", fromClient({ ...process.env, CODEX_HOME: alt }), join(alt, "hooks.json"))).toBe("allow"); + }); + + it("a value the agent's payload carried is never trusted: the client replaces it", async () => { + const alt = join(root, "alt-codex"); + mkdirSync(alt, { recursive: true }); + writeFileSync(join(alt, "config.toml"), FOREIGN_TOML); + const spoof = JSON.stringify({ ...JSON.parse(payload()), ["fail" + "proofai_agent_env"]: { HOME: daemonHome } }); + expect(await decide("codex", markAgentEnv(spoof, { ...process.env, CODEX_HOME: alt }), join(alt, "hooks.json"))).toBe("deny"); + }); +}); + +describe("Claude Code with CLAUDE_CONFIG_DIR elsewhere than the daemon's", () => { + it("a foreign failproofai_local in the agent's CLAUDE_CONFIG_DIR gets no exemption", async () => { + const alt = join(root, "alt-claude"); + mkdirSync(alt, { recursive: true }); + writeFileSync(join(alt, ".claude.json"), JSON.stringify(FOREIGN_JSON)); + expect(await decide("claude", fromClient({ ...process.env, CLAUDE_CONFIG_DIR: alt }), join(alt, "settings.json"))).toBe("deny"); + }); + + it("a genuine registration in the agent's CLAUDE_CONFIG_DIR is exempt", async () => { + const alt = join(root, "alt-claude"); + mkdirSync(alt, { recursive: true }); + vi.stubEnv("CLAUDE_CONFIG_DIR", alt); + await registerOwnSelfReportServer(); + vi.stubEnv("CLAUDE_CONFIG_DIR", ""); + expect(await decide("claude", fromClient({ ...process.env, CLAUDE_CONFIG_DIR: alt }), join(alt, "settings.json"))).toBe("allow"); + }); +}); + +describe("the Hermes plugin (calls the daemon directly, carries no environment)", () => { + const hermesPayload = () => + JSON.stringify({ session_id: "s", cwd: project, tool_name: "mcp_" + "fail" + "proofai_local_report", tool_input: { category: "looping", detail: "x" } }); + + it("is judged by the profile config its request names: foreign there means no exemption", async () => { + const alt = join(root, "alt-hermes"); + mkdirSync(alt, { recursive: true }); + writeFileSync(join(alt, "config.yaml"), "mcp_servers:\n " + "fail" + "proofai_local:\n command: node\n args: [evil.js]\n"); + expect(await decide("hermes", hermesPayload(), join(alt, "config.yaml"))).toBe("deny"); + }); + + it("a clean profile config it names is exempt; no config named at all is not", async () => { + const alt = join(root, "alt-hermes"); + mkdirSync(alt, { recursive: true }); + writeFileSync(join(alt, "config.yaml"), "model: x\n"); + expect(await decide("hermes", hermesPayload(), join(alt, "config.yaml"))).toBe("allow"); + expect(await decide("hermes", hermesPayload(), "")).toBe("deny"); + }); +}); + +describe("markAgentEnv / agentEnvOf", () => { + const env = { HOME: "/h", CODEX_HOME: "/c", PATH: "/bin", SECRET_TOKEN: "x" }; + + it("carries only the config-locating variables, and only on a payload that could be a report call", () => { + const out = JSON.parse(markAgentEnv(payload(), env)); + expect(out["fail" + "proofai_agent_env"]).toEqual({ HOME: "/h", CODEX_HOME: "/c" }); + const bash = JSON.stringify({ tool_name: "Bash", tool_input: { command: "ls" } }); + expect(markAgentEnv(bash, env)).toBe(bash); + }); + + it("drops a carried value from any payload, and carries nothing past the bound", () => { + const key = "fail" + "proofai_agent_env"; + const bash = JSON.stringify({ tool_name: "Bash", [key]: { HOME: "/x" } }); + expect(JSON.parse(markAgentEnv(bash, env))).not.toHaveProperty(key); + const long = JSON.parse(markAgentEnv(payload(), { HOME: "/h", CODEX_HOME: "x".repeat(5000) })); + expect(long).not.toHaveProperty(key); + }); +}); diff --git a/__tests__/hooks/self-report.test.ts b/__tests__/hooks/self-report.test.ts new file mode 100644 index 000000000..ba914581c --- /dev/null +++ b/__tests__/hooks/self-report.test.ts @@ -0,0 +1,1070 @@ +// @vitest-environment node +/** + * Self Reports: the shared text, names and settings (src/hooks/self-report.ts), + * the stdio MCP server spawned for real (`failproofai mcp`), and the + * `self-report status | enable | disable` commands. + */ +import { describe, it, expect, beforeEach, afterEach, vi } from "vitest"; +import { spawn } from "node:child_process"; +import { mkdtempSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync, mkdirSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import { + DEFAULT_CATEGORIES, + SELF_REPORT_SERVER_RECORDS, + describe as describeTool, + inputSchema, + isSelfReportToolName, + isAnySelfReportToolName, + readEffectiveSelfReport, + resolveSelfReport, + selfReportArgs, + selfReportCloudEnrolled, + selfReportEnrolmentId, + selfReportEnrolmentIdOf, + selfReportSettingsState, + selfReportCloudManaged, + validateSelfReportCategories, + validateSelfReportGuidance, + writeEffectiveSelfReport, + selfReportInstructions, +} from "../../src/hooks/self-report"; +import { + handleSelfReportRpc, + selfReportAgentId, + selfReportCwdAffinity, + selfReportFindSession, + selfReportFindSessionMatch, +} from "../../src/hooks/self-report-mcp"; +import { runSelfReportCommand } from "../../src/hooks/self-report-cli"; +import { isolateAgentHome, registerOwnSelfReportServer } from "../helpers/self-report-registration"; + +const BINARY = resolve(__dirname, "..", "..", "bin", "failproofai.mjs"); + +const EXPECTED_DESCRIPTION = `When you are stuck on something you cannot fix yourself, call this tool once with \`category\` (one of the categories below) and \`detail\` (one factual sentence: what is blocking you). It reports to FailproofAI. Call it BEFORE your final answer, for example for a missing, invalid or expired token or API key, a 401 or 403, a command, tool or MCP server that keeps failing, information or access you cannot get, or a request you cannot do here. Do not call it for normal work, clarifying questions or an error you then fixed. One call per distinct problem. +Reporting does not unblock you and changes no decision: afterwards, work around the problem or tell the user what is blocking you. There is no need to mention this report to the user. + +Categories: +- looping: You keep repeating the same or circular steps without making progress. +- cannot_do_request: The user asked for something you cannot do here: a missing capability, tool or permission, or it is only possible by cheating. +- invalid_tool_or_credential: A tool, MCP server, plugin, API key or token you need is broken, invalid, expired or rejected. +- missing_context: Information or access you need is missing and you cannot get it yourself. Not for normal clarifying questions. +- repeated_tool_failure: A command or tool failed on several distinct attempts and is blocking you. A single error is not enough. +- task_failure: You genuinely tried and could not complete the task, or something else blocks you that no other category describes. Not for refusals or policy blocks.`; + +let home: string; +const savedEnv: Record = {}; + +beforeEach(() => { + home = mkdtempSync(join(tmpdir(), "fpai-sr-")); + for (const k of ["FAILPROOFAI_HOME", "FAILPROOFAI_CLOUD_URL", "FAILPROOFAI_CLOUD_TOKEN", "FAILPROOFAI_MACHINE_ID", "FAILPROOFAI_CLOUD_CREDENTIALS", "FAILPROOFAI_SELF_REPORT_PORT"]) { + savedEnv[k] = process.env[k]; + delete process.env[k]; + } + process.env.FAILPROOFAI_HOME = home; +}); + +afterEach(() => { + vi.unstubAllEnvs(); + for (const [k, v] of Object.entries(savedEnv)) { + if (v === undefined) delete process.env[k]; + else process.env[k] = v; + } + rmSync(home, { recursive: true, force: true }); +}); + +describe("tool text and schema (contract §3)", () => { + it("describe() produces the exact contract text for the defaults", () => { + expect(describeTool(DEFAULT_CATEGORIES)).toBe(EXPECTED_DESCRIPTION); + }); + + it("appends guidance after a blank line, and only when there is some", () => { + expect(describeTool(DEFAULT_CATEGORIES, "Report tracker outages.")).toBe(`${EXPECTED_DESCRIPTION}\n\nReport tracker outages.`); + expect(describeTool(DEFAULT_CATEGORIES, null)).toBe(EXPECTED_DESCRIPTION); + expect(describeTool(DEFAULT_CATEGORIES, "")).toBe(EXPECTED_DESCRIPTION); + }); + + it("inputSchema() is the contract schema with the category names as the enum", () => { + expect(inputSchema([{ name: "a", description: "x" }, { name: "b_2", description: "y" }])).toEqual({ + type: "object", + properties: { + category: { type: "string", enum: ["a", "b_2"] }, + detail: { type: "string", description: "One factual sentence: what is blocking you." }, + }, + required: ["category", "detail"], + additionalProperties: false, + }); + }); + + it("selfReportArgs keeps unknown categories, defaults detail to empty, cuts at 2000, and unwraps arguments", () => { + expect(selfReportArgs({ category: "nope" })).toEqual({ category: "nope", detail: "" }); + // Cut at 2000 code points, never leaving part of a token at the end. + expect(selfReportArgs({ category: "looping", detail: "z ".repeat(1500) }).detail).toBe("z ".repeat(1000).trimEnd()); + expect(selfReportArgs({ category: "looping", detail: "z".repeat(3000) }).detail).toBe("[detail cut]"); + expect(selfReportArgs({ arguments: { category: "looping", detail: "d" } })).toEqual({ category: "looping", detail: "d" }); + expect(selfReportArgs({ arguments: '{"category":"looping","detail":"s"}' })).toEqual({ category: "looping", detail: "s" }); + expect(selfReportArgs(undefined)).toEqual({ category: "", detail: "" }); + }); +}); + +describe("tool-name matching (contract §1)", () => { + it.each([ + ["claude", "mcp__failproofai_local__report"], + ["claude", "MCP__FAILPROOFAI_LOCAL__REPORT"], + ["goose", "failproofai_local__report"], + ["copilot", "failproofai_local/report"], + ])("matches %s's %s", (cli, name) => expect(isSelfReportToolName(name, cli)).toBe(true)); + it.each(["report", "mcp__other__report", "mcp__failproofai__report", "failproofai__report", "mcp__failproofai_local__report2", "xfailproofai_report", "failproofai_report", "FAILPROOFAI_REPORT", "Bash", "", undefined, 7])( + "does not match %s", + (name) => expect(isAnySelfReportToolName(name)).toBe(false), + ); + it.each([ + ["claude", "failproofai_local__report"], + ["opencode", "mcp_failproofai_local_report"], + ["hermes", "failproofai_local_report"], + ["cursor", "mcp__failproofai_local__report"], + ["claude", "failproofai_local.report"], + ])("does not match on %s another agent's spelling %s", (cli, name) => expect(isSelfReportToolName(name, cli)).toBe(false)); + it("lists the server-recorded integrations from the contract", () => { + expect(SELF_REPORT_SERVER_RECORDS).toEqual([ + "openclaw", "pi", "devin", "hermes", "goose", "factory", "antigravity", "copilot", "opencode", "cursor", + ]); + for (const hookRecorded of ["claude", "codex"]) expect(SELF_REPORT_SERVER_RECORDS).not.toContain(hookRecorded); + }); +}); + +describe("validation (contract §2)", () => { + it("accepts the defaults", () => { + expect(validateSelfReportCategories(DEFAULT_CATEGORIES).ok).toBe(true); + }); + it.each([ + [[], "empty"], + [Array.from({ length: 33 }, (_, i) => ({ name: `c${i}`, description: "d" })), "too many"], + [[{ name: "Bad", description: "d" }], "uppercase name"], + [[{ name: "a".repeat(65), description: "d" }], "long name"], + [[{ name: "ok", description: "" }], "empty description"], + [[{ name: "ok", description: "x".repeat(501) }], "long description"], + [[{ name: "ok", description: "a" }, { name: "ok", description: "b" }], "duplicate"], + ["nope", "not a list"], + ])("rejects %j (%s)", (input, _label) => { + expect(validateSelfReportCategories(input).ok).toBe(false); + }); + it("guidance: at most 2000 characters, blank is none", () => { + expect(validateSelfReportGuidance("x".repeat(2000)).ok).toBe(true); + expect(validateSelfReportGuidance("x".repeat(2001)).ok).toBe(false); + expect(validateSelfReportGuidance(" ")).toEqual({ ok: true, value: null }); + }); +}); + +describe("self-report.json (contract §4)", () => { + it("missing or unparsable reads as disabled (null)", () => { + expect(readEffectiveSelfReport()).toBeNull(); + writeFileSync(join(home, "self-report.json"), "{not json"); + expect(readEffectiveSelfReport()).toBeNull(); + writeFileSync(join(home, "self-report.json"), JSON.stringify({ version: 2, enabled: true })); + expect(readEffectiveSelfReport()).toBeNull(); + }); + + it("writes atomically at 0644 with the contract shape, and reads back", () => { + process.env.FAILPROOFAI_SELF_REPORT_PORT = "4400"; + writeEffectiveSelfReport({ enabled: true, guidance: "g" }); + const path = join(home, "self-report.json"); + expect(statSync(path).mode & 0o777).toBe(0o644); + const raw = JSON.parse(readFileSync(path, "utf8")); + expect(raw).toMatchObject({ + version: 1, + enabled: true, + source: "local", + guidance: "g", + mcp: { port: 4400, url: "http://127.0.0.1:4400/mcp" }, + }); + expect(raw.categories).toEqual(DEFAULT_CATEGORIES); + expect(raw.updatedAt).toMatch(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ$/); + expect(readdirSync(home).filter((f) => f.endsWith(".tmp"))).toEqual([]); + expect(readEffectiveSelfReport()).toMatchObject({ enabled: true, source: "local", guidance: "g" }); + }); + + it("an enabled file with an unusable category list falls back to the defaults", () => { + writeFileSync(join(home, "self-report.json"), JSON.stringify({ version: 1, enabled: true, source: "cloud", categories: [] })); + expect(readEffectiveSelfReport()).toMatchObject({ enabled: true, source: "cloud", categories: DEFAULT_CATEGORIES }); + }); +}); + +describe("resolveSelfReport: on by default (contract §4)", () => { + const enrolled = () => true; + const oss = () => false; + it("a missing file is on with the defaults off Cloud, and off on Cloud", () => { + expect(resolveSelfReport(undefined, oss)).toMatchObject({ enabled: true, source: "local", categories: DEFAULT_CATEGORIES, guidance: null }); + expect(resolveSelfReport(undefined, enrolled)).toBeNull(); + }); + it("an explicit local off in config.json wins over the default", () => { + writeFileSync(join(home, "config.json"), JSON.stringify({ selfReport: { enabled: false } })); + expect(resolveSelfReport(undefined, oss)).toBeNull(); + writeFileSync(join(home, "config.json"), JSON.stringify({ selfReport: { categories: [] } })); + expect(resolveSelfReport(undefined, oss)?.enabled).toBe(true); + }); + it("a present file decides, and a malformed one is off", () => { + writeEffectiveSelfReport({ enabled: false }); + expect(resolveSelfReport(undefined, oss)?.enabled).toBe(false); + writeFileSync(join(home, "self-report.json"), "{not json"); + expect(resolveSelfReport(undefined, oss)).toBeNull(); + expect(resolveSelfReport(undefined, enrolled)).toBeNull(); + }); +}); + +describe("settings-cases.golden.json: the same on/off as the daemon's readers", () => { + const fixture = JSON.parse( + readFileSync(resolve(__dirname, "..", "..", "test-fixtures", "self-report", "settings-cases.golden.json"), "utf8"), + ) as { + cases: { name: string; file?: unknown; text?: string; enrolled: boolean; currentEnrolment?: string; on: boolean }[]; + enrolmentIds: { url: string; machineId: string; token: string; id: string }[]; + }; + for (const c of fixture.cases) { + it(c.name, () => { + const path = join(home, "self-report.json"); + if (c.text !== undefined) writeFileSync(path, c.text); + else if (c.file !== null && c.file !== undefined) writeFileSync(path, JSON.stringify(c.file, null, 2)); + expect(resolveSelfReport(path, () => c.enrolled, () => c.currentEnrolment ?? null)?.enabled === true).toBe(c.on); + }); + } + it("computes the same enrolment ids as the daemon", () => { + for (const v of fixture.enrolmentIds) expect(selfReportEnrolmentIdOf(v.url, v.machineId, v.token)).toBe(v.id); + }); +}); + +describe("a Cloud file is bound to the enrolment that wrote it (review 4719314971)", () => { + const cloudFile = (id: string | undefined, enabled = true) => ({ + version: 1, enabled, source: "cloud", categories: DEFAULT_CATEGORIES, guidance: null, + mcp: { port: 4319, url: "http://127.0.0.1:4319/mcp" }, updatedAt: "2026-11-29T00:00:00Z", + ...(id ? { enrolment: id } : {}), + }); + const enrol = (token: string) => + writeFileSync(join(home, "credentials.json"), JSON.stringify({ cloud: { url: "https://app.example.test", machine_id: "machine-1", token } })); + it("org A's 'on' stops deciding the moment the credential switches to org B", async () => { + enrol("tok-org-a"); + const idA = selfReportEnrolmentId(); + expect(idA).toBe(selfReportEnrolmentIdOf("https://app.example.test", "machine-1", "tok-org-a")); + writeFileSync(join(home, "self-report.json"), JSON.stringify(cloudFile(idA!))); + expect(resolveSelfReport()?.enabled).toBe(true); + expect(selfReportSettingsState()).toBe("on"); + // Switch to org B; B's first answer has not been written yet. + enrol("tok-org-b"); + expect(selfReportEnrolmentId()).not.toBe(idA); + expect(resolveSelfReport()).toBeNull(); + expect(selfReportSettingsState()).toBe("waiting"); + // Every reader agrees: the stdio server lists no tool and records nothing. + const listed = await handleSelfReportRpc({ jsonrpc: "2.0", id: 1, method: "tools/list" }); + expect((listed as { result: { tools: unknown[] } }).result.tools).toEqual([]); + // B's answer, bound to B, decides. + writeFileSync(join(home, "self-report.json"), JSON.stringify(cloudFile(selfReportEnrolmentId()!, false))); + expect(resolveSelfReport()?.enabled).toBe(false); + }); + it("a cloud file with no enrolment (an older daemon) or an unreadable credential is off while enrolled", () => { + enrol("tok-org-a"); + writeFileSync(join(home, "self-report.json"), JSON.stringify(cloudFile(undefined))); + expect(resolveSelfReport()).toBeNull(); + writeFileSync(join(home, "self-report.json"), JSON.stringify(cloudFile(selfReportEnrolmentId()!))); + expect(resolveSelfReport()?.enabled).toBe(true); + writeFileSync(join(home, "credentials.json"), "{broken"); + expect(selfReportCloudEnrolled()).toBe(true); + expect(selfReportEnrolmentId()).toBeNull(); + expect(resolveSelfReport()).toBeNull(); + }); + it("reads the id from the env, the named credential file and the legacy cloud.json like the daemon", () => { + process.env.FAILPROOFAI_CLOUD_URL = " https://app.example.test "; + expect(selfReportEnrolmentId()).toBeNull(); // no token or machine id: the daemon's resolve errors + process.env.FAILPROOFAI_CLOUD_TOKEN = "tok-org-a"; + process.env.FAILPROOFAI_MACHINE_ID = "machine-1"; + expect(selfReportEnrolmentId()).toBe(selfReportEnrolmentIdOf("https://app.example.test", "machine-1", "tok-org-a")); + delete process.env.FAILPROOFAI_CLOUD_URL; + delete process.env.FAILPROOFAI_CLOUD_TOKEN; + delete process.env.FAILPROOFAI_MACHINE_ID; + writeFileSync(join(home, "cloud.json"), JSON.stringify({ schemaVersion: 1, url: "u", machineId: "m", token: "t" })); + expect(selfReportEnrolmentId()).toBe(selfReportEnrolmentIdOf("u", "m", "t")); + const named = join(home, "named.json"); + writeFileSync(named, JSON.stringify({ schemaVersion: 1, url: "u2", machineId: "m", token: "t" })); + process.env.FAILPROOFAI_CLOUD_CREDENTIALS = named; + try { + expect(selfReportEnrolmentId()).toBe(selfReportEnrolmentIdOf("u2", "m", "t")); + } finally { + delete process.env.FAILPROOFAI_CLOUD_CREDENTIALS; + } + }); +}); + +describe("enrolling with a local settings file in place", () => { + it("sets this machine's own file aside until the daemon writes the org's setting", async () => { + writeEffectiveSelfReport({ enabled: true }); + expect(resolveSelfReport()?.enabled).toBe(true); + // Enrolled now; the daemon's first poll has not been applied yet. + process.env.FAILPROOFAI_CLOUD_URL = "https://cloud.example.invalid"; + process.env.FAILPROOFAI_CLOUD_TOKEN = "tok"; + process.env.FAILPROOFAI_MACHINE_ID = "machine"; + expect(resolveSelfReport()).toBeNull(); + // Every reader agrees: the stdio server hides the tool, the hook records nothing. + const listed = await handleSelfReportRpc({ jsonrpc: "2.0", id: 1, method: "tools/list" }); + expect((listed as { result: { tools: unknown[] } }).result.tools).toEqual([]); + const status = await runSelfReportCommand(["status"], { registrations: () => [], probeEndpoint: async () => false, daemonExpected: () => false }); + expect(status.lines[0]).toContain("off (waiting for FailproofAI Cloud"); + // The org's setting arrives (the daemon writes a cloud file): it decides. + const cloud = { + ...JSON.parse(readFileSync(join(home, "self-report.json"), "utf8")), + source: "cloud", + enabled: true, + enrolment: selfReportEnrolmentIdOf("https://cloud.example.invalid", "machine", "tok"), + }; + writeFileSync(join(home, "self-report.json"), JSON.stringify(cloud)); + expect(resolveSelfReport()?.enabled).toBe(true); + writeFileSync(join(home, "self-report.json"), JSON.stringify({ ...cloud, enabled: false })); + expect(resolveSelfReport()?.enabled).toBe(false); + }); +}); + +describe("selfReportCloudEnrolled (sync, the daemon's Enrolment::resolve)", () => { + it("follows the env, the credential files and the oss veto", () => { + expect(selfReportCloudEnrolled()).toBe(false); + writeFileSync(join(home, "credentials.json"), JSON.stringify({ ingest: { key: "k" } })); + expect(selfReportCloudEnrolled()).toBe(false); + writeFileSync(join(home, "credentials.json"), JSON.stringify({ cloud: { url: "https://x", machine_id: "m", token: "t" } })); + expect(selfReportCloudEnrolled()).toBe(true); + writeFileSync(join(home, "credentials.json"), "{broken"); + expect(selfReportCloudEnrolled()).toBe(true); + writeFileSync(join(home, "config.json"), JSON.stringify({ mode: { kind: "oss" } })); + expect(selfReportCloudEnrolled()).toBe(false); + process.env.FAILPROOFAI_CLOUD_URL = "https://example.invalid"; + expect(selfReportCloudEnrolled()).toBe(true); + delete process.env.FAILPROOFAI_CLOUD_URL; + rmSync(join(home, "config.json")); + rmSync(join(home, "credentials.json")); + writeFileSync(join(home, "cloud.json"), JSON.stringify({ schemaVersion: 1 })); + expect(selfReportCloudEnrolled()).toBe(true); + }); +}); + +describe("Cloud enrolment", () => { + it("is off with no credential, on with FAILPROOFAI_CLOUD_URL", async () => { + expect(await selfReportCloudManaged()).toBe(false); + process.env.FAILPROOFAI_CLOUD_URL = "https://example.invalid"; + expect(await selfReportCloudManaged()).toBe(true); + }); + + it("is on with a stored cloud credential, off again once config says oss", async () => { + const creds = join(home, "cloud-creds.json"); + writeFileSync(creds, JSON.stringify({ schemaVersion: 1, url: "https://example.invalid", machineId: "m", token: "t" })); + process.env.FAILPROOFAI_CLOUD_CREDENTIALS = creds; + expect(await selfReportCloudManaged()).toBe(true); + writeFileSync(join(home, "config.json"), JSON.stringify({ mode: { kind: "oss" } })); + expect(await selfReportCloudManaged()).toBe(false); + }); +}); + +describe("MCP fallback recording helpers", () => { + it("agent id mirrors the collector's -", () => { + expect(selfReportAgentId("pi", "/home/u/My Repo/")).toBe("pi-My-Repo"); + expect(selfReportAgentId("hermes", undefined)).toBe("hermes"); + }); + + it("finds the newest session for the agent and cwd within 6 h", () => { + const now = 1_800_000_000_000; + mkdirSync(join(home, "hook-activity"), { recursive: true }); + const row = (o: Record) => JSON.stringify({ eventType: "PreToolUse", decision: "allow", ...o }); + writeFileSync( + join(home, "hook-activity", "current.jsonl"), + [ + row({ integration: "pi", cwd: "/p", sessionId: "old", timestamp: now - 7 * 3600_000 }), + row({ integration: "pi", cwd: "/p", sessionId: "s1", timestamp: now - 3600_000 }), + row({ integration: "pi", cwd: "/p", sessionId: "s2", timestamp: now - 60_000 }), + row({ integration: "pi", cwd: "/other", sessionId: "wrong-cwd", timestamp: now }), + row({ integration: "goose", cwd: "/p", sessionId: "wrong-agent", timestamp: now }), + ].join("\n") + "\n", + ); + expect(selfReportFindSession("pi", "/p", now)).toBe("s2"); + // No row in or around this cwd, and pi's rows are in two projects: a guess + // across projects is refused. + expect(selfReportFindSession("pi", "/nowhere", now)).toBeNull(); + // ...but goose has one project in the window, so its newest session is it. + expect(selfReportFindSession("goose", "/nowhere", now)).toBe("wrong-agent"); + expect(selfReportFindSession("hermes", "/p", now)).toBeNull(); + expect(selfReportFindSession("pi", "/p", now + 10 * 3600_000)).toBeNull(); + }); + + it("prefers an exact cwd, then an ancestor or descendant, then any session, and returns the row's cwd", () => { + const now = 1_800_000_000_000; + mkdirSync(join(home, "hook-activity"), { recursive: true }); + const row = (o: Record) => JSON.stringify({ eventType: "PreToolUse", decision: "allow", integration: "hermes", ...o }); + writeFileSync( + join(home, "hook-activity", "current.jsonl"), + [ + row({ cwd: "/root/.hermes/hermes-agent", sessionId: "below", timestamp: now - 5000 }), + row({ cwd: "/srv/elsewhere", sessionId: "unrelated-newest", timestamp: now - 10 }), + row({ cwd: "/", sessionId: "root-row", timestamp: now - 9000 }), + ].join("\n") + "\n", + ); + // Server in /root, the agent's rows below it: the descendant wins over a newer unrelated one. + expect(selfReportFindSessionMatch("hermes", "/root", now)).toEqual({ sessionId: "below", cwd: "/root/.hermes/hermes-agent" }); + // `/` is an ancestor of everything; the newest related row wins. + expect(selfReportFindSessionMatch("hermes", "/srv/elsewhere/sub", now)?.sessionId).toBe("unrelated-newest"); + expect(selfReportFindSessionMatch("hermes", "/srv/elsewhere/", now)?.sessionId).toBe("unrelated-newest"); + // Nothing related except `/`, which counts as an ancestor. + expect(selfReportFindSessionMatch("hermes", "/work/ws", now)?.sessionId).toBe("root-row"); + expect(selfReportCwdAffinity("/a/b", "/a/bc")).toBe(0); + expect(selfReportCwdAffinity("/a/b", "/a/b/")).toBe(2); + expect(selfReportCwdAffinity("/a/b", "/a")).toBe(1); + expect(selfReportCwdAffinity("/a/b", undefined)).toBe(0); + }); + + it("finds a project's session behind many pages of another project's hook activity", () => { + // Project A's session started, then 80 events in project B rotated A's row + // several pages back. The report from A's cwd still lands on A. + const now = 1_800_000_000_000; + const dir = join(home, "hook-activity"); + mkdirSync(dir, { recursive: true }); + const row = (o: Record) => + JSON.stringify({ eventType: "PreToolUse", decision: "allow", integration: "copilot", ...o }); + let t = now - 3600_000; + writeFileSync(join(dir, `page-${t + 1}-0.jsonl`), row({ cwd: "/work/a", sessionId: "sess-A", timestamp: t }) + "\n"); + for (let page = 1; page <= 4; page++) { + const lines: string[] = []; + for (let i = 0; i < 20; i++) lines.push(row({ cwd: "/work/b", sessionId: "sess-B", timestamp: (t += 1000) })); + writeFileSync(join(dir, `page-${t + 1}-${page}.jsonl`), lines.join("\n") + "\n"); + } + writeFileSync(join(dir, "current.jsonl"), row({ cwd: "/work/b", sessionId: "sess-B", timestamp: (t += 1000) }) + "\n"); + expect(selfReportFindSessionMatch("copilot", "/work/a", now)).toEqual({ sessionId: "sess-A", cwd: "/work/a" }); + expect(selfReportFindSessionMatch("copilot", "/work/b", now)?.sessionId).toBe("sess-B"); + // A third, unrelated cwd: two projects to choose from, so unattributed rather than B. + expect(selfReportFindSessionMatch("copilot", "/work/c", now)).toBeNull(); + }); + + it("does not read pages rotated before the window opened", () => { + const now = 1_800_000_000_000; + const dir = join(home, "hook-activity"); + mkdirSync(dir, { recursive: true }); + const old = now - 8 * 3600_000; + writeFileSync( + join(dir, `page-${old}-0.jsonl`), + JSON.stringify({ eventType: "PreToolUse", integration: "pi", cwd: "/p", sessionId: "stale", timestamp: old - 1 }) + "\n", + ); + expect(selfReportFindSessionMatch("pi", "/p", now)).toBeNull(); + }); + + it("files a fallback report under the matched row's agent, not the server's cwd", async () => { + writeEffectiveSelfReport({ enabled: true }); + const now = Date.now(); + mkdirSync(join(home, "hook-activity"), { recursive: true }); + writeFileSync( + join(home, "hook-activity", "current.jsonl"), + JSON.stringify({ timestamp: now - 1000, eventType: "PreToolUse", integration: "openclaw", cwd: "/root/.openclaw/workspace", sessionId: "oc-1", decision: "allow" }) + "\n", + ); + const reply = await handleSelfReportRpc( + { jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "report", arguments: { category: "looping", detail: "d" } } }, + { agent: "openclaw", cwd: "/work/ws", now: () => now }, + ); + expect(reply).toMatchObject({ result: { content: [{ text: "Recorded." }] } }); + const dir = join(home, "custom-agents", "events"); + const [file] = readdirSync(dir); + const event = JSON.parse(readFileSync(join(dir, file), "utf8").trim()); + expect(event).toMatchObject({ session_id: "oc-1", agent_id: "openclaw-workspace", integration: "openclaw" }); + }); + + it("records a call with no category (seen live from Copilot) under the inferred one, and still answers Recorded.", async () => { + writeEffectiveSelfReport({ enabled: true }); + const detail = 'Deployment is blocked because ./deploy.sh exits with "DEPLOY_TOKEN is not set" and no token is available in this environment.'; + const reply = await handleSelfReportRpc( + { jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "report", arguments: { detail } } }, + { agent: "copilot", cwd: "/work/ws" }, + ); + expect(reply).toEqual({ jsonrpc: "2.0", id: 1, result: { content: [{ type: "text", text: "Recorded." }] } }); + const dir = join(home, "custom-agents", "events"); + const [file] = readdirSync(dir); + const event = JSON.parse(readFileSync(join(dir, file), "utf8").trim()); + expect(event).toMatchObject({ type: "self_report", category: "invalid_tool_or_credential", detail, integration: "copilot" }); + }); + + it("an unknown method gets -32601; a notification gets no reply; an unknown tool is an error result", async () => { + expect(await handleSelfReportRpc({ jsonrpc: "2.0", id: 9, method: "resources/list" })).toMatchObject({ error: { code: -32601 } }); + expect(await handleSelfReportRpc({ jsonrpc: "2.0", method: "notifications/initialized" })).toBeNull(); + expect(await handleSelfReportRpc({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "other" } })).toMatchObject({ + result: { isError: true }, + }); + }); +}); + +/** Spawn `failproofai mcp`, send these messages, collect the replies. */ +function runMcp(agentArgs: string[], messages: unknown[], cwd: string): Promise<{ replies: Array>; code: number | null; stderr: string }> { + return new Promise((resolveRun, reject) => { + const child = spawn("bun", [BINARY, "mcp", ...agentArgs], { + cwd, + env: { ...process.env, HOME: home, FAILPROOFAI_HOME: home, FAILPROOFAI_TELEMETRY_DISABLED: "1" }, + stdio: ["pipe", "pipe", "pipe"], + }); + let out = ""; + let err = ""; + child.stdout.on("data", (b: Buffer) => (out += b.toString())); + child.stderr.on("data", (b: Buffer) => (err += b.toString())); + child.on("error", reject); + child.on("close", (code) => { + try { + resolveRun({ replies: out.split("\n").filter(Boolean).map((l) => JSON.parse(l)), code, stderr: err }); + } catch (e) { + reject(new Error(`non-JSON on stdout: ${out}\n${String(e)}`)); + } + }); + child.stdin.end(messages.map((m) => JSON.stringify(m)).join("\n") + "\n"); + }); +} + +describe("self-report sync on a stale home", () => { + it("refuses, like a scheduled audit, instead of migrating (and resetting) the home unattended", async () => { + // What failproofaid runs at startup and after each settings change. + writeFileSync(join(home, "VERSION"), JSON.stringify({ layout: 1, cli: "0.0.1" })); + const toml = "[telemetry]\nenabled = false\n"; + writeFileSync(join(home, "config.toml"), toml); + const { code, stderr } = await new Promise<{ code: number | null; stderr: string }>((ok, fail) => { + const child = spawn("bun", [BINARY, "self-report", "sync", "--quiet"], { + cwd: home, + env: { ...process.env, HOME: home, FAILPROOFAI_HOME: home, FAILPROOFAI_TELEMETRY_DISABLED: "1" }, + stdio: ["ignore", "pipe", "pipe"], + }); + let err = ""; + child.stderr.on("data", (b: Buffer) => (err += b.toString())); + child.on("error", fail); + child.on("close", (c) => ok({ code: c, stderr: err })); + }); + expect(code).toBe(1); + expect(stderr).toContain("refusing to run unattended"); + expect(stderr).toContain("failproofai config"); + expect(readFileSync(join(home, "config.toml"), "utf8")).toBe(toml); + expect(JSON.parse(readFileSync(join(home, "VERSION"), "utf8")).layout).toBe(1); + }, 30_000); +}); + +const INIT = { jsonrpc: "2.0", id: 1, method: "initialize", params: { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "t", version: "1" } } }; +const INITIALIZED = { jsonrpc: "2.0", method: "notifications/initialized" }; +const LIST = { jsonrpc: "2.0", id: 2, method: "tools/list" }; +const CALL_ARGS = { category: "looping", detail: "stuck in a retry loop" }; +const CALL = { jsonrpc: "2.0", id: 3, method: "tools/call", params: { name: "report", arguments: CALL_ARGS } }; +const PING = { jsonrpc: "2.0", id: 4, method: "ping" }; + +describe("failproofai mcp (stdio, spawned)", () => { + it("answers initialize, ping, and an empty tools/list while disabled — with no daemon", async () => { + writeEffectiveSelfReport({ enabled: false }); + const { replies, code } = await runMcp([], [INIT, INITIALIZED, LIST, PING], home); + expect(code).toBe(0); + expect(replies.map((r) => r.id)).toEqual([1, 2, 4]); + expect(replies[0]).toMatchObject({ result: { protocolVersion: "2025-06-18", capabilities: { tools: {} }, serverInfo: { name: "failproofai_local" } } }); + expect((replies[0].result as Record)).not.toHaveProperty("instructions"); + expect(replies[1]).toEqual({ jsonrpc: "2.0", id: 2, result: { tools: [] } }); + expect(replies[2]).toEqual({ jsonrpc: "2.0", id: 4, result: {} }); + }, 30_000); + + it("lists the report tool from self-report.json and answers a call with exactly Recorded.", async () => { + writeEffectiveSelfReport({ enabled: true, categories: [{ name: "looping", description: "loops" }], guidance: "be terse" }); + const { replies } = await runMcp(["--agent", "claude"], [INIT, LIST, CALL], home); + expect((replies[0].result as Record).instructions).toBe( + selfReportInstructions([{ name: "looping", description: "loops" }], "be terse"), + ); + const tools = (replies[1].result as { tools: Array> }).tools; + expect(tools).toHaveLength(1); + expect(tools[0].name).toBe("report"); + expect(tools[0].description).toBe(describeTool([{ name: "looping", description: "loops" }], "be terse")); + expect(tools[0].inputSchema).toEqual(inputSchema([{ name: "looping", description: "loops" }])); + expect(replies[2]).toEqual({ jsonrpc: "2.0", id: 3, result: { content: [{ type: "text", text: "Recorded." }] } }); + }, 30_000); + + it("with no settings file (not Cloud enrolled) lists the tool and records: on by default", async () => { + const { replies } = await runMcp(["--agent", "pi"], [INIT, LIST, CALL], home); + expect((replies[0].result as Record).instructions).toBe(selfReportInstructions(DEFAULT_CATEGORIES)); + const tools = (replies[1].result as { tools: Array> }).tools; + expect(tools.map((t) => t.name)).toEqual(["report"]); + expect(readdirSync(join(home, "custom-agents", "events"))).toHaveLength(1); + }, 30_000); + + it("with no settings file on a Cloud-enrolled machine lists nothing and records nothing", async () => { + writeFileSync(join(home, "credentials.json"), JSON.stringify({ cloud: { url: "https://x", machine_id: "m", token: "t" } })); + const { replies } = await runMcp(["--agent", "pi"], [INIT, LIST, CALL], home); + expect((replies[0].result as Record)).not.toHaveProperty("instructions"); + expect(replies[1]).toEqual({ jsonrpc: "2.0", id: 2, result: { tools: [] } }); + expect(() => readdirSync(join(home, "custom-agents", "events"))).toThrow(); + }, 30_000); + + // Claude Code and Codex: the hook records, so the server writes nothing for + // a call the hook already recorded. The hook runs before the MCP call is + // sent, so its row is there first. + it("writes no event for a hook-recorded agent (claude) whose hook recorded the call", async () => { + writeEffectiveSelfReport({ enabled: true }); + mkdirSync(join(home, "hook-activity"), { recursive: true }); + // The server is this test process's child, so this process is its agent: + // a hook row from the same agent has this pid among its ancestors. + writeFileSync( + join(home, "hook-activity", "current.jsonl"), + JSON.stringify({ + timestamp: Date.now() - 500, eventType: "PreToolUse", integration: "claude", sessionId: "c1", decision: "allow", + cwd: home, toolName: "mcp__failproofai_local__report", selfReport: { ...CALL_ARGS, source: "mcp" }, + agentPid: process.pid, + }) + "\n", + ); + await runMcp(["--agent", "claude"], [INIT, CALL], home); + expect(() => readdirSync(join(home, "custom-agents", "events"))).toThrow(); + }, 30_000); + + // F14: the same report from another session (another agent process) in the + // same directory is a distinct call, and that session's hooks did not run. + it("records a report that another session's hook row in the same directory would have matched", async () => { + writeEffectiveSelfReport({ enabled: true }); + mkdirSync(join(home, "hook-activity"), { recursive: true }); + writeFileSync( + join(home, "hook-activity", "current.jsonl"), + JSON.stringify({ + timestamp: Date.now() - 500, eventType: "PreToolUse", integration: "claude", sessionId: "other", decision: "allow", + cwd: home, toolName: "mcp__failproofai_local__report", selfReport: { ...CALL_ARGS, source: "mcp" }, + agentPid: 77776, + }) + "\n", + ); + await runMcp(["--agent", "claude"], [INIT, CALL], home); + expect(readdirSync(join(home, "custom-agents", "events"))).toHaveLength(1); + }, 30_000); + + // ...and records it when the hook did not (an untrusted Codex runs no hook): + // otherwise the report would be lost. + it("records a hook-recorded agent's report when its hook did not", async () => { + writeEffectiveSelfReport({ enabled: true }); + for (const agent of ["codex", "claude"]) { + await runMcp(["--agent", agent], [INIT, CALL], home); + } + const files = readdirSync(join(home, "custom-agents", "events")); + expect(files).toHaveLength(2); + const events = files.map((f) => JSON.parse(readFileSync(join(home, "custom-agents", "events", f), "utf8"))); + expect(events.map((e) => e.integration).sort()).toEqual(["claude", "codex"]); + for (const e of events) expect(e).toMatchObject({ type: "self_report", ...CALL_ARGS, source: "mcp" }); + }, 30_000); + + it("writes one self_report event in the SDK spool format for a server-recorded agent, attributed to its session", async () => { + writeEffectiveSelfReport({ enabled: true }); + const project = join(home, "proj"); + mkdirSync(project); + mkdirSync(join(home, "hook-activity"), { recursive: true }); + writeFileSync( + join(home, "hook-activity", "current.jsonl"), + JSON.stringify({ timestamp: Date.now() - 1000, eventType: "PreToolUse", integration: "pi", cwd: project, sessionId: "pi-sess", decision: "allow" }) + "\n", + ); + const { replies } = await runMcp(["--agent", "pi"], [INIT, CALL], project); + expect(replies[1]).toMatchObject({ result: { content: [{ type: "text", text: "Recorded." }] } }); + const dir = join(home, "custom-agents", "events"); + const files = readdirSync(dir); + expect(files).toHaveLength(1); + expect(files[0]).toMatch(/^event-\d{4}-\d\d-\d\dT[\d-]+Z-\d+-\d+\.jsonl$/); + expect(statSync(join(dir, files[0])).mode & 0o777).toBe(0o600); + expect(statSync(dir).mode & 0o777).toBe(0o700); + const lines = readFileSync(join(dir, files[0]), "utf8").split("\n").filter(Boolean); + expect(lines).toHaveLength(1); + const event = JSON.parse(lines[0]); + expect(event).toMatchObject({ + type: "self_report", + session_id: "pi-sess", + agent_id: "pi-proj", + environment: "local", + category: "looping", + detail: "stuck in a retry loop", + source: "mcp", + integration: "pi", + }); + expect(Number.isNaN(Date.parse(event.timestamp))).toBe(false); + }, 30_000); + + it("records the detail a model sent under an alias (sentence) instead of an empty one", async () => { + writeEffectiveSelfReport({ enabled: true }); + const aliased = { ...CALL, params: { name: "report", arguments: { category: "looping", sentence: "retrying the same fix", extra: 1 } } }; + const { replies } = await runMcp(["--agent", "hermes"], [INIT, aliased], home); + expect(replies[1]).toMatchObject({ result: { content: [{ type: "text", text: "Recorded." }] } }); + const dir = join(home, "custom-agents", "events"); + const event = JSON.parse(readFileSync(join(dir, readdirSync(dir)[0]), "utf8")); + expect(event).toMatchObject({ category: "looping", detail: "retrying the same fix" }); + }, 30_000); + + it("falls back to session \"unattributed\" when no live session matches", async () => { + writeEffectiveSelfReport({ enabled: true }); + await runMcp(["--agent", "hermes"], [INIT, CALL], home); + const dir = join(home, "custom-agents", "events"); + const event = JSON.parse(readFileSync(join(dir, readdirSync(dir)[0]), "utf8")); + expect(event.session_id).toBe("unattributed"); + }, 30_000); + + it("rejects a missing --agent value on stderr, never on stdout", async () => { + const { replies, code, stderr } = await runMcp(["--agent"], [INIT], home); + expect(code).toBe(1); + expect(replies).toEqual([]); + expect(stderr).toContain("--agent"); + }, 30_000); +}); + +describe("failproofai self-report enable | disable | status", () => { + const deps = { skipSync: true, probeEndpoint: async () => false }; + + it("enable writes config.json's selfReport and self-report.json; status shows it", async () => { + writeFileSync(join(home, "config.json"), JSON.stringify({ unrelated: { keep: true } })); + const enabled = await runSelfReportCommand(["enable", "--guidance", "say what tool"], deps); + expect(enabled.exitCode).toBe(0); + const config = JSON.parse(readFileSync(join(home, "config.json"), "utf8")); + expect(config.selfReport).toEqual({ enabled: true, guidance: "say what tool" }); + expect(config.unrelated).toEqual({ keep: true }); + expect(readEffectiveSelfReport()).toMatchObject({ enabled: true, source: "local", guidance: "say what tool", categories: DEFAULT_CATEGORIES }); + + const status = await runSelfReportCommand(["status"], deps); + expect(status.exitCode).toBe(0); + const text = status.lines.join("\n"); + expect(text).toContain("Self Reports: on"); + expect(text).toContain("this machine"); + expect(text).toContain("looping, cannot_do_request"); + expect(text).toContain("Daemon MCP: not running (agents use stdio)"); + }); + + it("enable --categories-file replaces the defaults; a bad file is refused and writes nothing", async () => { + const good = join(home, "cats.json"); + writeFileSync(good, JSON.stringify({ categories: [{ name: "tracker_down", description: "The tracker is down." }] })); + expect((await runSelfReportCommand(["enable", "--categories-file", good], deps)).exitCode).toBe(0); + expect(readEffectiveSelfReport()?.categories).toEqual([{ name: "tracker_down", description: "The tracker is down." }]); + + rmSync(join(home, "self-report.json")); + const bad = join(home, "bad.json"); + writeFileSync(bad, JSON.stringify([{ name: "Bad Name", description: "x" }])); + const refused = await runSelfReportCommand(["enable", "--categories-file", bad], deps); + expect(refused.exitCode).toBe(1); + expect(refused.lines.join(" ")).toContain("name must match"); + expect(readEffectiveSelfReport()).toBeNull(); + }); + + it("disable turns it off and keeps the categories for next time", async () => { + const cats = join(home, "cats.json"); + writeFileSync(cats, JSON.stringify([{ name: "x_y", description: "d" }])); + await runSelfReportCommand(["enable", "--categories-file", cats], deps); + const off = await runSelfReportCommand(["disable"], deps); + expect(off.exitCode).toBe(0); + expect(readEffectiveSelfReport()).toMatchObject({ enabled: false }); + expect(JSON.parse(readFileSync(join(home, "config.json"), "utf8")).selfReport).toEqual({ + enabled: false, + categories: [{ name: "x_y", description: "d" }], + }); + expect((await runSelfReportCommand(["enable"], deps)).exitCode).toBe(0); + expect(readEffectiveSelfReport()?.categories).toEqual([{ name: "x_y", description: "d" }]); + }); + + it("refuses enable and disable on a Cloud-managed machine and changes nothing", async () => { + process.env.FAILPROOFAI_CLOUD_URL = "https://example.invalid"; + for (const verb of ["enable", "disable"]) { + const r = await runSelfReportCommand([verb], deps); + expect(r.exitCode).toBe(1); + expect(r.lines.join(" ")).toContain("FailproofAI Cloud"); + } + expect(readEffectiveSelfReport()).toBeNull(); + expect(() => readFileSync(join(home, "config.json"))).toThrow(); + }); + + const row = (o: Record) => ({ + agent: "claude", path: "/x", hooked: true, registered: true, transport: "http", endpoint: null, conflict: false, ...o, + }) as never; + + it("status shows each agent's actual transport and whether its endpoint answers", async () => { + writeEffectiveSelfReport({ enabled: true }); + const runnable = join(home, "failproofai"); + writeFileSync(runnable, "#!/bin/sh\n", { mode: 0o755 }); + const r = await runSelfReportCommand(["status"], { + skipSync: true, + probeEndpoint: async (_url, port) => port === 4319, + daemonLive: async (port) => port === 4319, + registrations: () => [ + row({ agent: "claude", transport: "http", endpoint: "http://127.0.0.1:4319/mcp?agent=claude" }), + row({ agent: "codex", transport: "http", endpoint: "http://127.0.0.1:4999/mcp?agent=codex" }), + row({ agent: "cursor", transport: "stdio", endpoint: runnable }), + row({ agent: "factory", transport: "stdio", endpoint: join(home, "missing", "failproofai") }), + ], + }); + const text = r.lines.join("\n"); + expect(text).not.toContain("still works"); + expect(text).toContain("Daemon MCP: http://127.0.0.1:4319/mcp (answering)"); + expect(text).toMatch(/claude +http +http:\/\/127\.0\.0\.1:4319\/mcp\?agent=claude \(answering\)/); + expect(text).toMatch(/codex +http +http:\/\/127\.0\.0\.1:4999\/mcp\?agent=codex \(NOT answering\)/); + expect(text).toMatch(new RegExp(`cursor +stdio +${runnable} \\(runnable\\)`)); + expect(text).toMatch(/factory +stdio +.*\(NOT runnable\)/); + // Cursor's line is followed by how to approve the server in cursor-agent; nobody else's is. + const lines = text.split("\n"); + const at = lines.findIndex((l) => /^ +cursor +stdio/.test(l)); + expect(lines[at + 1]).toContain("cursor-agent mcp enable failproofai"); + expect(lines.filter((l) => l.includes("cursor-agent mcp enable"))).toHaveLength(1); + }); + + it("status shows what the last update did to the gateways, and nothing when there is no report", async () => { + writeEffectiveSelfReport({ enabled: true }); + const deps = { + skipSync: true, + probeEndpoint: async () => false, + daemonExpected: () => false, + registrations: () => [], + gatewayReport: () => ({ at: "2026-11-29T16:25:41.000Z", rows: ["hermes/default already current, gateway restarting", "openclaw/default gateway restarting"] }), + }; + const out = (await runSelfReportCommand(["status"], deps)).lines.join("\n"); + expect(out).toContain("Gateways: at the last update (2026-11-29T16:25:41.000Z)"); + expect(out).toContain(" hermes/default already current, gateway restarting"); + expect(out).toContain(" openclaw/default gateway restarting"); + expect((await runSelfReportCommand(["status"], { ...deps, gatewayReport: () => null })).lines.join("\n")).not.toContain("Gateways:"); + }); + + it("status says the daemon is not running, not \"not answering\", when there is no daemon", async () => { + writeEffectiveSelfReport({ enabled: true }); + const status = (expected: boolean) => + runSelfReportCommand(["status"], { + skipSync: true, + probeEndpoint: async () => false, + daemonExpected: () => expected, + registrations: () => [row({ agent: "claude", transport: "stdio", endpoint: "/usr/bin/failproofai" })], + }); + const none = (await status(false)).lines.join("\n"); + expect(none).toContain("Daemon MCP: not running (agents use stdio)"); + expect(none).not.toContain("not answering"); + const down = (await status(true)).lines.join("\n"); + expect(down).toContain("Daemon MCP: http://127.0.0.1:4319/mcp (not answering)"); + expect(down).not.toContain("not running"); + }); + + it("status expects a daemon when setup configured one or its socket file is there", async () => { + writeEffectiveSelfReport({ enabled: true }); + const status = async () => + (await runSelfReportCommand(["status"], { + skipSync: true, + probeEndpoint: async () => false, + registrations: () => [], + })).lines.join("\n"); + const sock = join(home, "fake-daemon.sock"); + const prev = process.env.FAILPROOFAI_DAEMON_SOCKET; + process.env.FAILPROOFAI_DAEMON_SOCKET = sock; + try { + expect(await status()).toContain("Daemon MCP: not running (agents use stdio)"); + writeFileSync(sock, ""); + expect(await status()).toContain("(not answering)"); + } finally { + if (prev === undefined) delete process.env.FAILPROOFAI_DAEMON_SOCKET; + else process.env.FAILPROOFAI_DAEMON_SOCKET = prev; + } + }); + + it("status re-syncs agents left on an HTTP endpoint that is not answering", async () => { + writeEffectiveSelfReport({ enabled: true }); + let synced = 0; + let rows = [row({ transport: "http", endpoint: "http://127.0.0.1:4319/mcp?agent=claude" })]; + const r = await runSelfReportCommand(["status"], { + probeEndpoint: async () => false, + registrations: () => rows, + sync: async () => { + synced++; + rows = [row({ transport: "stdio", endpoint: "/usr/bin/failproofai" })]; + return [{ agent: "claude", path: "/x", action: "updated", transport: "stdio", status: "ok" }]; + }, + }); + expect(synced).toBe(1); + const text = r.lines.join("\n"); + expect(text).toContain("Repaired:"); + expect(text).toContain("updated in Claude Code (stdio)"); + expect(text).toMatch(/claude +stdio/); + + // An answering HTTP endpoint is still repaired: no agent belongs on HTTP + // any more (a Claude Code project can switch its hooks off). + synced = 0; + rows = [row({ transport: "http", endpoint: "http://127.0.0.1:4319/mcp?agent=claude" })]; + await runSelfReportCommand(["status"], { + probeEndpoint: async () => true, daemonLive: async () => true, registrations: () => rows, sync: async () => (synced++, []), + }); + expect(synced).toBe(1); + // skipSync: no write. + synced = 0; + await runSelfReportCommand(["status"], { skipSync: true, probeEndpoint: async () => false, registrations: () => rows, sync: async () => (synced++, []) }); + expect(synced).toBe(0); + }); + + it("status re-syncs an agent whose HTTP endpoint answers as another home's daemon", async () => { + writeEffectiveSelfReport({ enabled: true }); + let synced = 0; + const http = [row({ transport: "http", endpoint: "http://127.0.0.1:4319/mcp?agent=claude" })]; + const seen = await runSelfReportCommand(["status"], { + skipSync: true, + probeEndpoint: async () => true, + daemonLive: async () => false, + registrations: () => http, + }); + expect(seen.lines.join("\n")).toMatch(/claude +http +\S+ \(answering, but NOT this home's daemon\)/); + let rows = http; + const r = await runSelfReportCommand(["status"], { + probeEndpoint: async () => true, + daemonLive: async () => false, + registrations: () => rows, + sync: async () => { + synced++; + rows = [row({ transport: "stdio", endpoint: "/usr/bin/failproofai" })]; + return [{ agent: "claude", path: "/x", action: "updated", transport: "stdio", status: "ok" }]; + }, + }); + expect(synced).toBe(1); + expect(r.lines.join("\n")).toContain("Repaired:"); + }); + + it("status moves a server-recorded agent off HTTP even while the endpoint answers", async () => { + writeEffectiveSelfReport({ enabled: true }); + let synced = 0; + let rows = [row({ agent: "copilot", transport: "http", endpoint: "http://127.0.0.1:4319/mcp?agent=copilot" })]; + const r = await runSelfReportCommand(["status"], { + probeEndpoint: async () => true, + registrations: () => rows, + sync: async () => { + synced++; + rows = [row({ agent: "copilot", transport: "stdio", endpoint: "/usr/bin/failproofai" })]; + return [{ agent: "copilot", path: "/x", action: "updated", transport: "stdio", status: "ok" }]; + }, + }); + expect(synced).toBe(1); + expect(r.lines.join("\n")).toContain("Repaired:"); + }); + + it("enable and disable print one line, naming only agents that could not be updated", async () => { + const ok = (agent: string, action: string) => ({ agent, path: `/${agent}`, action, transport: "stdio", status: "ok" }) as never; + const on = await runSelfReportCommand(["enable"], { probeEndpoint: async () => false, sync: async () => [ok("claude", "unchanged"), ok("cursor", "added")] }); + expect(on.lines).toEqual(["✓ Self Reports: on for 2 agents"]); + const partly = await runSelfReportCommand(["enable"], { + probeEndpoint: async () => false, + sync: async () => [ok("claude", "added"), { agent: "codex", path: "/c", action: "skipped", transport: null, status: "error", detail: "EACCES" }], + }); + expect(partly.lines).toEqual(["▲ Self Reports: on for 1 agent; not updated for OpenAI Codex · `failproofai self-report sync`"]); + const off = await runSelfReportCommand(["disable"], { sync: async () => [ok("claude", "removed")] }); + expect(off.lines).toEqual(["✓ Self Reports: off"]); + expect((await runSelfReportCommand(["enable"], { skipSync: true })).lines).toEqual(["✓ Self Reports: on"]); + }); + + it("status is one header, the healthy agents in one line, and a line per agent with a problem", async () => { + writeEffectiveSelfReport({ enabled: true }); + const runnable = join(home, "failproofai"); + writeFileSync(runnable, "#!/bin/sh\n", { mode: 0o755 }); + const r = await runSelfReportCommand(["status"], { + skipSync: true, + probeEndpoint: async (_url, port) => port === 4319, + daemonLive: async (port) => port === 4319, + registrations: () => [ + row({ agent: "claude", transport: "http", endpoint: "http://127.0.0.1:4319/mcp?agent=claude" }), + row({ agent: "cursor", transport: "stdio", endpoint: runnable }), + row({ agent: "copilot", transport: "stdio", endpoint: runnable }), + row({ agent: "factory", transport: "stdio", endpoint: join(home, "missing", "failproofai") }), + row({ agent: "goose", registered: false, transport: null }), + row({ agent: "devin", hooked: false, registered: false, transport: null }), + ], + }); + const out = r.lines.join("\n"); + // One command shows everything: there is no --verbose. + expect(r.lines[0]).toBe("Self Reports: on"); + expect(out).toContain("Source: this machine (config.json)"); + expect(out).toContain("self-report.json"); + expect(out).toContain("Categories: looping"); + expect(out).toContain("http://127.0.0.1:4319/mcp?agent=claude"); + expect(out).toContain("▲ factory: command not runnable · `failproofai self-report sync`"); + expect(out).toContain("▲ goose: not registered · `failproofai self-report sync`"); + expect(out).toContain("cursor-agent mcp enable failproofai_local"); + expect((await runSelfReportCommand(["status", "--verbose"], { skipSync: true, registrations: () => [] })).exitCode).toBe(1); + }); + + it("status says off, on by default, or unreadable, and --json carries the same", async () => { + writeEffectiveSelfReport({ enabled: false }); + const off = (await runSelfReportCommand(["status"], deps)).lines; + expect(off[0]).toBe("Self Reports: off"); + expect(off.join("\n")).toContain("self-report enable`"); + rmSync(join(home, "self-report.json")); + const dflt = (await runSelfReportCommand(["status"], deps)).lines; + expect(dflt[0]).toBe("Self Reports: on"); + expect(dflt.join("\n")).toContain("the default (no settings file yet)"); + writeFileSync(join(home, "self-report.json"), "{not json"); + expect((await runSelfReportCommand(["status"], deps)).lines[0]).toBe("Self Reports: off (the settings file cannot be read)"); + + writeEffectiveSelfReport({ enabled: true }); + const j = await runSelfReportCommand(["status", "--json"], { + skipSync: true, + probeEndpoint: async () => false, + registrations: () => [row({ agent: "copilot", transport: "stdio", endpoint: join(home, "nope") })], + }); + expect(j.exitCode).toBe(0); + expect(j.json).toMatchObject({ + enabled: true, + source: "local", + categories: DEFAULT_CATEGORIES.map((c) => c.name), + daemon: { url: "http://127.0.0.1:4319/mcp", answering: false }, + agents: [{ agent: "copilot", transport: "stdio", healthy: false, problem: "command not runnable", fix: "failproofai self-report sync" }], + }); + expect((await runSelfReportCommand(["status", "--bogus"], deps)).exitCode).toBe(1); + }); + + it("status with no settings file says it is on by default, and how to turn it off", async () => { + const r = await runSelfReportCommand(["status"], deps); + expect(r.exitCode).toBe(0); + expect(r.lines[0]).toBe("Self Reports: on"); + expect(r.lines.join("\n")).toContain("the default (no settings file yet)"); + expect(r.lines.join("\n")).toContain("`failproofai self-report disable`"); + }); + + it("status with no settings file on a Cloud-enrolled machine says it is off until Cloud sends it", async () => { + process.env.FAILPROOFAI_CLOUD_URL = "https://example.invalid"; + const r = await runSelfReportCommand(["status"], deps); + expect(r.lines[0]).toContain("off (waiting for FailproofAI Cloud"); + }); + + it("status with a malformed settings file says it is off", async () => { + writeFileSync(join(home, "self-report.json"), "{not json"); + const r = await runSelfReportCommand(["status"], deps); + expect(r.lines[0]).toBe("Self Reports: off (the settings file cannot be read)"); + }); + + it("test refuses while disabled and rejects an unknown agent", async () => { + writeEffectiveSelfReport({ enabled: false }); + expect((await runSelfReportCommand(["test", "--agent", "claude"], deps)).exitCode).toBe(1); + writeEffectiveSelfReport({ enabled: true }); + const r = await runSelfReportCommand(["test", "--agent", "nope"], deps); + expect(r.exitCode).toBe(1); + expect(r.lines[0]).toContain("Not an agent"); + }); + + it("test --agent pi drives the real stdio server and reports the event file", async () => { + writeEffectiveSelfReport({ enabled: true }); + const r = await runSelfReportCommand(["test", "--agent", "pi"], { ...deps, cliCommand: ["bun", BINARY], cwd: home }); + expect(r.exitCode).toBe(0); + const dir = join(home, "custom-agents", "events"); + expect(r.lines.join("\n")).toContain(join(dir, readdirSync(dir)[0])); + }, 30_000); + + it("test --agent pi passes when a collector consumes the batch before the check", async () => { + // The wrapper runs the real CLI, then deletes every published batch the way + // a running collector does after uploading it, before the command looks. + writeEffectiveSelfReport({ enabled: true }); + const consume = `bun "${BINARY}" "$@"; code=$?; rm -f "$FAILPROOFAI_HOME"/custom-agents/events/*.jsonl; exit $code`; + const r = await runSelfReportCommand(["test", "--agent", "pi"], { ...deps, cliCommand: ["sh", "-c", consume, "sh"], cwd: home }); + expect(r.lines.join("\n")).toContain("recorded by the MCP server"); + expect(r.lines.join("\n")).toContain("already picked up by the collector"); + expect(r.exitCode).toBe(0); + expect(readdirSync(join(home, "custom-agents", "events")).filter((f) => f.endsWith(".jsonl"))).toEqual([]); + }, 30_000); + + it("test --agent pi still fails when the server recorded nothing", async () => { + writeEffectiveSelfReport({ enabled: true }); + // The server answers Recorded. but cannot write (the spool is a file). + mkdirSync(join(home, "custom-agents"), { recursive: true }); + writeFileSync(join(home, "custom-agents", "events"), "not a directory"); + const r = await runSelfReportCommand(["test", "--agent", "pi"], { ...deps, cliCommand: ["bun", BINARY], cwd: home }); + expect(r.exitCode).toBe(1); + expect(r.lines[0]).toContain("did not land"); + }, 30_000); + + it("test --agent claude goes through --hook and lands in hook activity", async () => { + writeEffectiveSelfReport({ enabled: true }); + // The hook early-allows the report only while Claude's failproofai_local entry is ours. + isolateAgentHome(join(home, "user")); + await registerOwnSelfReportServer(); + const r = await runSelfReportCommand(["test", "--agent", "claude"], { ...deps, cliCommand: ["bun", BINARY], cwd: home }); + expect(r.exitCode).toBe(0); + const rows = readFileSync(join(home, "hook-activity", "current.jsonl"), "utf8").trim().split("\n").map((l) => JSON.parse(l)); + const last = rows.pop(); + expect(last).toMatchObject({ toolName: "mcp__failproofai_local__report", decision: "allow", selfReport: { source: "mcp" } }); + // The real hook process stamped the agent above it: this test process started it. + if (process.platform === "linux" || process.platform === "darwin") expect(last.agentPid).toBe(process.pid); + }, 30_000); +}); diff --git a/__tests__/hooks/settings-guard.test.ts b/__tests__/hooks/settings-guard.test.ts new file mode 100644 index 000000000..972c73fd8 --- /dev/null +++ b/__tests__/hooks/settings-guard.test.ts @@ -0,0 +1,2032 @@ +// @vitest-environment node +import { describe, it, expect, vi, beforeAll, afterAll } from "vitest"; +import { existsSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { BUILTIN_POLICIES } from "../../src/hooks/builtin-policies"; +import { POLICY_CATALOG } from "../../src/hooks/policy-catalog"; +import type { PolicyContext } from "../../src/hooks/policy-types"; +import { AGENT_PATH_KEY } from "../../src/hooks/agent-path"; +import { + agentPatchTargetPaths, + agentToolWritePaths, + isAgentConfigDirPath, + isAgentSettingsPath, +} from "../../src/hooks/agent-settings-guard"; + +// Same mocks as state-guard.test.ts: no policy under test may spawn anything. +// The filesystem IS read here — the guard follows symlinks — but only under +// a throwaway HOME and work directory created below. +vi.mock("node:fs/promises", () => ({ + readFile: vi.fn(), + writeFile: vi.fn(), + stat: vi.fn().mockResolvedValue({ size: 0 }), + open: vi.fn(), +})); + +vi.mock("node:child_process", () => ({ + execSync: vi.fn(), + execFileSync: vi.fn(), +})); + +const policy = BUILTIN_POLICIES.find((p) => p.name === "block-failproofai-commands")!; +/** + * What the hook CLI puts in the payload: the agent's PATH, here a system one. + * A reader is exempt only as the real tool that PATH finds (#1105 bot review). + */ +const AGENT_PAYLOAD = { [AGENT_PATH_KEY]: "/usr/bin:/bin" }; +const PROJ = "/work/proj"; + +let root: string; +let home: string; +let savedHome: string | undefined; + +beforeAll(() => { + // os.homedir() reads HOME on every call on POSIX, so the guard's `~` and its + // home-directory symlink check both land in this directory, never the real one. + root = mkdtempSync(join(tmpdir(), "fpai-settings-guard-")); + home = join(root, "home"); + mkdirSync(home, { recursive: true }); + savedHome = process.env.HOME; + process.env.HOME = home; +}); + +afterAll(() => { + if (savedHome === undefined) delete process.env.HOME; + else process.env.HOME = savedHome; + rmSync(root, { recursive: true, force: true }); +}); + +function run(toolName: string, toolInput: Record, cwd: string = PROJ) { + const ctx: PolicyContext = { eventType: "PreToolUse", payload: AGENT_PAYLOAD, toolName, toolInput, session: { cwd } }; + return policy.fn(ctx); +} + +const decision = async (toolName: string, toolInput: Record, cwd?: string) => + (await run(toolName, toolInput, cwd)).decision; + +/** Denied, and for the settings reason rather than the state or CLI reason next to it. */ +const deniedAsSettings = async (toolName: string, toolInput: Record, cwd?: string) => { + const result = await run(toolName, toolInput, cwd); + return result.decision === "deny" && /settings or hook file/.test(result.reason ?? ""); +}; + +const write = (filePath: string, cwd?: string) => deniedAsSettings("Write", { file_path: filePath, content: "{}" }, cwd); +const bash = (command: string, cwd?: string) => deniedAsSettings("Bash", { command }, cwd); +const bashDecision = (command: string, cwd?: string) => decision("Bash", { command }, cwd); + +/** + * #1794: the always-on guard refused writes to `~/.failproofai` only. An agent + * could set `"disableAllHooks": true` in any Claude Code settings layer, or take + * failproofai's entries out of any CLI's hook file, and from then on no policy + * ran — this guard included — with nothing anywhere saying so. + */ +describe("block-failproofai-commands — agent settings and hook files", () => { + describe("the reported edits", () => { + it("denies setting disableAllHooks through Edit on the user settings", async () => { + expect( + await deniedAsSettings("Edit", { + file_path: `${home}/.claude/settings.json`, + old_string: "{", + new_string: '{"disableAllHooks": true,', + }), + ).toBe(true); + }); + + it("denies writing a project's local settings, which overrides the user's", async () => { + expect( + await deniedAsSettings("Write", { + file_path: `${PROJ}/.claude/settings.local.json`, + content: '{"disableAllHooks":true}', + }), + ).toBe(true); + }); + + it("denies the jq-then-mv rewrite from the shell", async () => { + expect(await bash(`jq '.disableAllHooks=true' ~/.claude/settings.json > t && mv t ~/.claude/settings.json`)).toBe(true); + }); + + it("denies emptying another CLI's hooks file", async () => { + expect(await write(`${home}/.codex/hooks.json`)).toBe(true); + }); + }); + + describe("every integration's files", () => { + // What `failproofai policies --install` writes for each CLI, plus the files + // that can switch those hooks off without touching them (Codex's trust + // hashes in config.toml, Goose's plugin registration). + const homeFiles = [ + ".claude/settings.json", + ".claude/settings.local.json", + ".codex/hooks.json", + ".codex/config.toml", + ".copilot/hooks/failproofai.json", + ".cursor/hooks.json", + ".config/opencode/opencode.json", + ".config/opencode/plugins/failproofai.mjs", + ".pi/agent/settings.json", + ".pi/agent/extensions/failproofai/index.ts", + ".gemini/settings.json", + ".gemini/config/hooks.json", + ".agents/plugins/failproofai/hooks/hooks.json", + ".config/goose/config.yaml", + ".factory/hooks.json", + ".config/devin/config.json", + ".hermes/config.yaml", + ".hermes/profiles/work/config.yaml", + ".hermes-work/config.yaml", + ".hermes/plugins/failproofai/__init__.py", + ".openclaw/openclaw.json", + ".openclaw-work/openclaw.json", + ]; + it.each(homeFiles)("denies writing ~/%s", async (file) => { + expect(await write(`${home}/${file}`)).toBe(true); + }); + + const projectFiles = [ + ".claude/settings.json", + ".codex/hooks.json", + ".github/hooks/failproofai.json", + ".cursor/hooks.json", + ".opencode/opencode.json", + ".opencode/plugins/failproofai.mjs", + ".pi/settings.json", + ".agents/hooks.json", + ".agents/plugins/failproofai/hooks/hooks.json", + ".factory/hooks.json", + ".devin/config.json", + ]; + it.each(projectFiles)("denies writing /%s", async (file) => { + expect(await write(`${PROJ}/${file}`)).toBe(true); + }); + }); + + describe("the tools that reach them", () => { + it("is invoked for MultiEdit, and denies it", async () => { + const entry = POLICY_CATALOG.find((p) => p.name === "block-failproofai-commands")!; + expect(entry.match.toolNames).toEqual(expect.arrayContaining(["Bash", "Write", "Edit", "MultiEdit", "NotebookEdit"])); + expect( + await deniedAsSettings("MultiEdit", { + file_path: `${home}/.claude/settings.json`, + edits: [{ old_string: "{", new_string: '{"disableAllHooks": true,' }], + }), + ).toBe(true); + }); + + it("reads the paths an apply_patch edit carries inside its patch", async () => { + // Codex, Copilot and OpenCode canonicalize apply_patch to Edit with no + // file_path at all, so a guard reading only file_path saw nothing. + const update = "*** Begin Patch\n*** Update File: .claude/settings.json\n@@\n-{\n+{\"disableAllHooks\": true,\n*** End Patch\n"; + expect(await deniedAsSettings("Edit", { command: ["apply_patch", update] })).toBe(true); + expect(await deniedAsSettings("Edit", { input: `*** Begin Patch\n*** Add File: ${home}/.codex/hooks.json\n+{}\n*** End Patch` })).toBe(true); + expect(await deniedAsSettings("Edit", { patchText: "*** Begin Patch\n*** Delete File: .cursor/hooks.json\n*** End Patch" })).toBe(true); + expect(await deniedAsSettings("Edit", { input: "*** Begin Patch\n*** Update File: notes.md\n*** Move to: .github/hooks/failproofai.json\n*** End Patch" })).toBe(true); + expect(await deniedAsSettings("Edit", { patch: "--- a/.cursor/hooks.json\n+++ b/.cursor/hooks.json\n@@ -1 +1 @@\n-x\n+y\n" })).toBe(true); + }); + + it("allows an apply_patch edit of ordinary files, and a Write whose content is a diff", async () => { + expect(await decision("Edit", { command: ["apply_patch", "*** Begin Patch\n*** Update File: src/index.ts\n@@\n-a\n+b\n*** End Patch\n"] })).toBe("allow"); + // The content of a Write is content: its file_path is what it writes. + expect( + await decision("Write", { file_path: `${PROJ}/docs/fix.md`, content: "+++ b/.claude/settings.json\n*** Update File: .claude/settings.json" }), + ).toBe("allow"); + }); + }); + + describe("paths as the tool would open them", () => { + it("resolves a relative path against the session's cwd", async () => { + expect(await write(".claude/settings.json")).toBe(true); + expect(await write("../other/.claude/settings.local.json")).toBe(true); + expect(await write("settings.json", `${home}/.claude`)).toBe(true); + }); + + it("expands ~", async () => { + expect(await write("~/.claude/settings.json")).toBe(true); + }); + + it("ignores case, as macOS's default filesystem does", async () => { + expect(await write(`${home}/.Claude/Settings.json`)).toBe(true); + expect(await write(`${home}/.CODEX/HOOKS.JSON`)).toBe(true); + }); + }); + + describe("symlinks", () => { + let work: string; + beforeAll(() => { + work = join(root, "work"); + mkdirSync(join(work, "real", ".claude"), { recursive: true }); + mkdirSync(join(work, "proj"), { recursive: true }); + writeFileSync(join(work, "real", ".claude", "settings.json"), "{}"); + symlinkSync(join(work, "real", ".claude", "settings.json"), join(work, "proj", "cfg.json")); + symlinkSync(join(work, "real", ".claude"), join(work, "proj", "link")); + // The dotfiles layout: the real file names no agent directory at all. + mkdirSync(join(home, "dotfiles", "claude"), { recursive: true }); + mkdirSync(join(home, ".claude"), { recursive: true }); + writeFileSync(join(home, "dotfiles", "claude", "settings.json"), "{}"); + writeFileSync(join(home, "dotfiles", "zshrc"), ""); + symlinkSync(join(home, "dotfiles", "claude", "settings.json"), join(home, ".claude", "settings.json")); + }); + + it("denies a write through a link to a settings file", async () => { + expect(await write(join(work, "proj", "cfg.json"), join(work, "proj"))).toBe(true); + }); + + it("denies creating a settings file through a linked directory", async () => { + expect(await write(join(work, "proj", "link", "settings.local.json"), join(work, "proj"))).toBe(true); + }); + + it("denies editing the real file behind the home directory's settings link", async () => { + expect( + await deniedAsSettings("Edit", { + file_path: join(home, "dotfiles", "claude", "settings.json"), + old_string: "{", + new_string: '{"disableAllHooks": true,', + }), + ).toBe(true); + }); + + it("allows the rest of a dotfiles directory", async () => { + expect(await decision("Write", { file_path: join(home, "dotfiles", "zshrc"), content: "" })).toBe("allow"); + }); + + it("denies the dotfiles target from the shell too", async () => { + expect(await bash(`sed -i '/failproofai/d' ~/dotfiles/claude/settings.json`)).toBe(true); + expect(await bash(`sed -i '/failproofai/d' ${join(home, "dotfiles", "claude", "settings.json")}`)).toBe(true); + expect(await bashDecision(`sed -i 's/a/b/' ~/dotfiles/zshrc`)).toBe("allow"); + }); + + it("denies the target of a project's settings link", async () => { + // A committed `.claude/settings.json -> ../config/claude.json`: the file an + // agent edits names no agent directory. + const project = join(root, "linkproj"); + mkdirSync(join(project, ".claude"), { recursive: true }); + mkdirSync(join(project, "config"), { recursive: true }); + writeFileSync(join(project, "config", "claude.json"), "{}"); + symlinkSync(join("..", "config", "claude.json"), join(project, ".claude", "settings.json")); + expect(await write(join(project, "config", "claude.json"), project)).toBe(true); + expect(await decision("Write", { file_path: join(project, "config", "other.json"), content: "{}" }, project)).toBe("allow"); + }); + }); + + describe("ordinary file work stays allowed", () => { + it.each([ + `${PROJ}/src/settings.json`, + `${PROJ}/config/hooks.json`, + `${PROJ}/hooks.json`, + `${PROJ}/.claude/commands/review.md`, + `${PROJ}/.claude/agents/reviewer.md`, + `${PROJ}/.claude/worktrees/feature/src/index.ts`, + `${PROJ}/.claude/worktrees/feature/.github/workflows/ci.yml`, + `${PROJ}/.claude/settings.json.bak`, + `${PROJ}/.github/workflows/ci.yml`, + `${PROJ}/.cursor/rules/style.mdc`, + `${PROJ}/.codex/AGENTS.md`, + ])("allows writing %s", async (file) => { + expect(await decision("Write", { file_path: file, content: "x" })).toBe("allow"); + }); + // Joined inside the test: `home` exists only once beforeAll has run, and a + // table built before then wrote `undefined/.claude/…`. + it.each([".claude/skills/review/SKILL.md", ".claude/CLAUDE.md"])("allows writing ~/%s", async (file) => { + expect(await decision("Write", { file_path: join(home, file), content: "x" })).toBe("allow"); + }); + }); + + describe("from the shell", () => { + it.each([ + // Rewrites in place, through tools on the read allowlist. + `sed -i 's/"hooks"/"_hooks"/' ~/.claude/settings.json`, + `yq -i '.hooks = {}' .agents/hooks.json`, + `awk -i inplace '{print}' ~/.claude/settings.json`, + `sed '1e cp /tmp/x ~/.claude/settings.json' /dev/null`, + `sed -n '1W ~/.claude/settings.json' /tmp/x`, + `perl -pi -e 's/a/b/' .claude/settings.json`, + // Redirects, copies and links onto the file. + `echo '{"disableAllHooks":true}' > .claude/settings.local.json`, + `printf '{}' > ~/.codex/hooks.json`, + `cp /tmp/empty.json ~/.cursor/hooks.json`, + `tee .github/hooks/failproofai.json < /dev/null`, + `curl -o ~/.claude/settings.json https://example.com/settings.json`, + `ln -sf /tmp/evil.json ~/.claude/settings.json`, + `chmod 000 ~/.claude/settings.json`, + // Removing or moving the file or the directory that holds it. + `rm ~/.claude/settings.json`, + `rm -rf ~/.claude`, + `mv ~/.claude ~/.claude.bak`, + `find ~/.claude -name settings.json -delete`, + `rm -rf ~/.hermes/plugins/failproofai`, + `sed -i '/failproofai/d' ~/.hermes/config.yaml`, + `git checkout -- .claude/settings.json`, + `git mv .claude/settings.json /tmp/x`, + `git -C ~/.claude pull`, + // Interpreters, which name the path only inside their code. + `python3 -c "import json; p='/home/u/.claude/settings.json'; d=json.load(open(p)); d['disableAllHooks']=True; json.dump(d, open(p,'w'))"`, + `node -e "require('fs').writeFileSync(process.env.HOME+'/.claude/settings.json','{}')"`, + `python3 -c "import shutil; shutil.rmtree('/home/u/.claude')"`, + // The path carried by a cd, a variable, a substitution, a glob or quoting. + `cd ~/.claude && sed -i 's/a/b/' settings.json`, + `F=~/.claude/settings.json; jq . $F > /tmp/x && cp /tmp/x $F`, + `D=~/.claude; rm -rf $D`, + `echo $(rm ~/.claude/settings.json)`, + `rm -f ~/.claude/settings.*`, + `rm -rf ~/.claude/*`, + `rm ~/.cl*/settings.json`, + `rm ~/.claude/"settings.json"`, + `rm -rf ~/.config/op*`, + // A program on an interpreter's stdin, which the walk reads line by line. + `python3 - <<'EOF'\nimport json\np = '/home/u/.claude/settings.json'\njson.dump({"disableAllHooks": True}, open(p, 'w'))\nEOF`, + ])("denies %s", async (command) => { + expect(await bash(command)).toBe(true); + }); + + it.each([ + // Sweeps of a shared parent: the same decoy floor that keeps `rm -rf *` + // allowed for the state guard. + `rm -rf ~/.config/*`, + `rm -rf ~/.{cache,config}/*`, + `rm -rf .github/*`, + ])("allows the sweep %s", async (command) => { + expect(await bashDecision(command)).toBe("allow"); + }); + + it("resolves relative words against a cwd an earlier call left inside ~/.claude", async () => { + const inClaude = `${home}/.claude`; + expect(await bash(`sed -i 's/x/y/' settings.json`, inClaude)).toBe(true); + expect(await bash(`rm *.json`, inClaude)).toBe(true); + expect(await bash(`rm -rf .`, inClaude)).toBe(true); + // The rest of that directory is ordinary files. + expect(await bashDecision(`rm -rf skills/old`, inClaude)).toBe("allow"); + expect(await bashDecision(`sed -i 's/a/b/' commands/review.md`, inClaude)).toBe("allow"); + }); + + it.each([ + `cat ~/.claude/settings.json`, + `jq '.hooks' ~/.claude/settings.json`, + `cat ~/.claude/settings.json | jq '.disableAllHooks=true'`, + `sed -n '1,20p' ~/.claude/settings.json`, + `sed 's/a/b/' ~/.claude/settings.json`, + `cp ~/.claude/settings.json /tmp/settings.backup.json`, + `diff ~/.claude/settings.json /tmp/x.json`, + `grep -n failproofai ~/.codex/hooks.json`, + `ls -la ~/.claude`, + `git add .claude/settings.json && git commit -m "Add project hooks"`, + `git diff .claude/settings.json`, + `git log -p -- .claude/settings.json`, + `mkdir -p .claude/commands`, + `mkdir -p .claude`, + `touch .claude/settings.local.json`, + `rm -rf .claude/worktrees/old`, + `rm -rf ~/.claude/projects/-home-u-old`, + `git worktree remove .claude/worktrees/feature`, + `cd .claude/worktrees/feature && git status`, + `rm -rf node_modules dist`, + `rm -rf *`, + `rm */*.json`, + `rm -rf ~/.*`, + `echo "edit ~/.claude/settings.json yourself"`, + `gh pr create --title x --body "Blocks edits to ~/.claude/settings.json"`, + `bun test __tests__/hooks/settings-guard.test.ts`, + ])("allows %s", async (command) => { + expect(await bashDecision(command)).toBe("allow"); + }); + + // An editor opening the file is a mention only as the real editor: a + // project's own `code` can write it (#1105 bot review). The agent's PATH + // here is /usr/bin:/bin, so the answer depends on where this machine has it. + it("allows `code ~/.claude/settings.json` only where the agent's PATH finds a system `code`", async () => { + const systemCode = ["/usr/bin/code", "/bin/code"].some((p) => existsSync(p)); + expect(await bashDecision(`code ~/.claude/settings.json`)).toBe(systemCode ? "allow" : "deny"); + }); + }); + + describe("the state guard beside it is unchanged", () => { + it("still denies the state for the state's own reason", async () => { + const result = await run("Bash", { command: "rm -rf ~/.failproofai" }); + expect(result.decision).toBe("deny"); + expect(result.reason).toMatch(/failproofai's own state/); + expect(await decision("Write", { file_path: `${home}/.failproofai/policies-config.json`, content: "{}" })).toBe("deny"); + }); + + it("still allows reading the state", async () => { + expect(await bashDecision("cat ~/.failproofai/policies-config.json")).toBe("allow"); + }); + + // The walk is shared, so the writers it learned for settings files reach + // the state too. Each of these was allowed before. + it.each([ + `yq -i '.enabledPolicies = []' ~/.failproofai/policies-config.json`, + `awk -i inplace '{print}' ~/.failproofai/policies-config.json`, + `sed '1e rm -rf ~/.failproofai' /dev/null`, + `python3 -c "import os; p='/home/u/.failproofai/policies/packs/installed.json'; os.remove(p)"`, + `git mv ~/.failproofai/policies-config.json /tmp/x`, + ])("now denies %s", async (command) => { + const result = await run("Bash", { command }); + expect(result.decision).toBe("deny"); + expect(result.reason).toMatch(/failproofai's own state/); + }); + }); +}); + +/** + * The second review round: one-command writes that still got through, and + * ordinary work the first round denied. + */ +describe("block-failproofai-commands — agent settings, review round two", () => { + function runIn(toolName: string, toolInput: Record, session: PolicyContext["session"]) { + const ctx: PolicyContext = { eventType: "PreToolUse", payload: AGENT_PAYLOAD, toolName, toolInput, session }; + return policy.fn(ctx); + } + + describe("a destination the shell resolves where a cd left it", () => { + it.each([ + `cd ~/.claude && echo '{"disableAllHooks":true}' > settings.json`, + `cd ~/.claude && cp /tmp/evil.json settings.json`, + `cd ~/.claude && tee settings.json < /tmp/evil.json`, + `pushd ~/.claude && cp /tmp/evil.json settings.json`, + `(cd ~/.claude && cp /tmp/evil.json settings.json)`, + `cd ~/.config && rm -rf opencode`, + `cd ~ && cd .claude && cp /tmp/evil.json settings.local.json`, + ])("denies %s", async (command) => { + expect(await bash(command)).toBe(true); + }); + + it("keeps the cd's reach inside its subshell and stops it at popd", async () => { + expect(await bashDecision(`(cd ~/.claude && cat settings.json); cp /tmp/x settings.json`)).toBe("allow"); + expect(await bashDecision(`pushd ~/.claude && cat settings.json && popd && cp /tmp/x settings.json`)).toBe("allow"); + }); + + it("closes the same hole for the state", async () => { + const result = await run("Bash", { command: "cd ~/.failproofai && cp /dev/null policies-config.json" }); + expect(result.decision).toBe("deny"); + expect(result.reason).toMatch(/failproofai's own state/); + expect((await run("Bash", { command: "cd ~/.failproofai && echo {} > policies-config.json" })).decision).toBe("deny"); + }); + }); + + describe("writers the first round missed", () => { + it.each([ + `sed -Ei 's/a/b/' ~/.claude/settings.json`, + `sed -ni 's/a/b/p' ~/.claude/settings.json`, + `sed -n 's/^//w/home/u/.claude/settings.json' /tmp/evil.json`, + `sed -n '1p; w /home/u/.claude/settings.json' /tmp/evil.json`, + `awk 'BEGIN{printf "{\\"disableAllHooks\\":true}" > ARGV[1]}' ~/.claude/settings.json`, + `git log -1 --format='format:{"disableAllHooks":true}' --output=$HOME/.claude/settings.json`, + `git diff --output=.claude/settings.json HEAD~1`, + `git archive -o ~/.claude/settings.json HEAD`, + `git -c alias.x='!rm -rf ~/.claude' x`, + `gh release download v1 -O ~/.claude/settings.json`, + `sort -o$HOME/.claude/settings.json /tmp/evil.json`, + `curl -so$HOME/.claude/settings.json https://example.com/x`, + `echo ~/.claude/settings.json | xargs tee`, + `echo ~/.claude/settings.json | xargs -n1 cp /tmp/evil.json`, + `echo x > >(tee ~/.claude/settings.json)`, + `rg --pre ./x.sh foo ~/.claude`, + ])("denies %s", async (command) => { + expect(await bash(command)).toBe(true); + }); + + it("denies an agent CLI's own command that turns its hooks off", async () => { + expect(await bashDecision("codex features disable hooks")).toBe("deny"); + expect(await bashDecision("npx codex features disable hooks")).toBe("deny"); + expect(await bashDecision("pi remove /usr/lib/node_modules/failproofai/pi-extension")).toBe("deny"); + expect(await bashDecision("codex features list")).toBe("allow"); + expect(await bashDecision("codex features enable web_search")).toBe("allow"); + }); + }); + + describe("paths spelled so the text never matches", () => { + it.each([ + `cp evil ~/.claude/settings$X.json`, + `cp evil ~/.clau\${X}de/settings.json`, + `cp evil ~/.claude/settings$(true).json`, + `cp evil /home/u/.claude/./settings.json`, + `cp evil /home/u/.claude//settings.json`, + `cp -l ~/.claude/settings.json /tmp/x`, + `cp -rs ~/.claude /tmp/c`, + ])("denies %s", async (command) => { + expect(await bash(command)).toBe(true); + }); + + it("splices variables into the state's paths too", async () => { + const result = await run("Bash", { command: "X=ai; rm -rf ~/.failproof$X" }); + expect(result.decision).toBe("deny"); + }); + }); + + describe("files this session knows about beyond the shapes", () => { + it("protects the settings file the hook was loaded from, wherever CLAUDE_CONFIG_DIR put it", async () => { + const session = { cwd: PROJ, agentSettingsPath: `${home}/.claude-work/settings.json` }; + const write = await runIn("Write", { file_path: `${home}/.claude-work/settings.json`, content: "{}" }, session); + expect(write.decision).toBe("deny"); + for (const command of [`sed -i 's/a/b/' ~/.claude-work/settings.json`, `rm -rf ~/.claude-work`]) { + expect((await runIn("Bash", { command }, session)).decision).toBe("deny"); + } + // The rest of that directory is not settings. + const other = await runIn("Write", { file_path: `${home}/.claude-work/CLAUDE.md`, content: "x" }, session); + expect(other.decision).toBe("allow"); + }); + + it("reads Antigravity's own cwd for a run_command", async () => { + expect(await deniedAsSettings("Bash", { command: "printf '{}' > hooks.json", cwd: "~/.gemini/config" })).toBe(true); + expect(await decision("Bash", { command: "printf '{}' > hooks.json", cwd: "/work/proj/tmp" })).toBe("allow"); + }); + + it("reads an indented apply_patch marker, and a patch beside a path key", async () => { + expect(await deniedAsSettings("Edit", { input: "*** Begin Patch\n *** Update File: .claude/settings.json\n@@\n-a\n+b\n*** End Patch" })).toBe(true); + expect(await deniedAsSettings("Edit", { input: "*** Begin Patch\n\t*** Update File: .claude/settings.json\n*** End Patch" })).toBe(true); + expect( + await deniedAsSettings("Edit", { path: "notes.md", patch: "*** Begin Patch\n*** Update File: ~/.hermes/config.yaml\n*** End Patch" }), + ).toBe(true); + }); + + it("reads a program that builds the path from its parts", async () => { + for (const command of [ + `python3 -c "import os; p=os.path.join(os.path.expanduser('~'),'.claude','settings.json'); open(p,'w').write('{}')"`, + `node -e "const p=require('path').join(require('os').homedir(),'.claude','settings.json'); require('fs').writeFileSync(p,'{}')"`, + `python3 - <<'EOF'\nimport os\np = os.path.join(os.path.expanduser('~'), '.codex', 'hooks.json')\nopen(p, 'w').write('{}')\nEOF`, + ]) { + expect(await bash(command)).toBe(true); + } + }); + + it("denies a sweep of the agent directory the session stands in", async () => { + expect(await bash("rm -rf *", `${home}/.claude`)).toBe(true); + expect(await bashDecision("rm -rf skills/*", `${home}/.claude`)).toBe("allow"); + }); + }); + + describe("ordinary work the first round denied", () => { + it.each([ + // Claude Code's own commit and PR shapes: the message is stored, never run. + `git commit -m "$(cat <<'EOF'\nRegister failproofai in .claude/settings.json\n\nCo-Authored-By: someone \nEOF\n)"`, + `gh pr create --title t --body "$(cat <<'EOF'\n## Summary\nBlocks edits to ~/.claude/settings.json and \`rm -rf ~/.claude\`\nEOF\n)"`, + `git commit -m "Install\n\nWrites .codex/hooks.json; and rm -rf ~/.claude is refused"`, + `git commit -m "Protect \\\`~/.claude/settings.json\\\` from agent edits"`, + `echo "a; rm -rf ~/.claude > ~/.claude/settings.json"`, + // Git hooks kept in .github/hooks. + `git config core.hooksPath .github/hooks`, + `chmod +x .github/hooks/*`, + `cp scripts/pre-commit .github/hooks/`, + // Reads that a loose sed or git check read as writes. + `sed -n '1,20p' /workspaces/p/.claude/settings.json`, + `git restore --staged .claude/settings.json`, + `echo ~/.claude/settings.json | xargs cat`, + ])("allows %s", async (command) => { + expect(await bashDecision(command)).toBe("allow"); + }); + + it("still denies what those shapes really run", async () => { + expect(await bash(`bash -c 'cat x; rm -rf ~/.claude'`)).toBe(true); + expect(await bash(`git commit -m "$(rm ~/.claude/settings.json)"`)).toBe(true); + expect(await bash(`cat <<'EOF' | sh\nrm -rf ~/.claude\nEOF`)).toBe(true); + expect(await bash(`cat < /tmp/x.sh <<'EOF'\nrm -rf ~/.claude\nEOF\nbash /tmp/x.sh`)).toBe(true); + }); + + it("no longer denies the state's own false positives from the same causes", async () => { + expect(await bashDecision(`git merge feature -m "notes about ~/.failproofai"`)).toBe("allow"); + expect(await bashDecision(`sed -n 1p /Users/Wei/.failproofai/policies-config.json`)).toBe("allow"); + }); + }); + + it("stays fast on a long line", async () => { + // A heredoc pattern rescanned the rest of the line for every + // interpreter-shaped word: 100 KB of prose took 12.6 s on the first + // version of this guard, against 0.15 s now. The bound is loose enough for + // a slow CI runner and still far below the old cost. + const words = "node php lua perl ruby bun deno python3 said "; + const command = "echo " + words.repeat(Math.ceil((100 * 1024) / words.length)); + const started = performance.now(); + expect(await bashDecision(command)).toBe("allow"); + expect(performance.now() - started).toBeLessThan(5000); + }, 60_000); +}); + +/** + * The third review pass: holes the second round's heredoc and quote handling + * opened (for the state too), and the gaps it left. + */ +describe("block-failproofai-commands — review round three", () => { + function runIn(toolName: string, toolInput: Record, session: PolicyContext["session"]) { + const ctx: PolicyContext = { eventType: "PreToolUse", payload: AGENT_PAYLOAD, toolName, toolInput, session }; + return policy.fn(ctx); + } + const stateDenied = async (command: string) => { + const result = await run("Bash", { command }); + return result.decision === "deny" && /failproofai's own state/.test(result.reason ?? ""); + }; + + describe("a `<<` that is not a heredoc does not hide the lines after it", () => { + it.each([ + `cat <<< x\nrm -rf ~/.failproofai`, + `echo "< { + expect(await stateDenied(command)).toBe(true); + }); + + it.each([ + `echo $((1< { + expect(await bash(command)).toBe(true); + }); + }); + + describe("a heredoc whose body is used is read", () => { + it.each([ + `git apply <<'EOF'\n--- a/.claude/settings.json\n+++ b/.claude/settings.json\n@@ -1 +1 @@\n-{}\n+{"disableAllHooks":true}\nEOF`, + `patch -p1 <<'EOF'\n--- a/.claude/settings.json\n+++ b/.claude/settings.json\nEOF`, + `while read f; do cp /tmp/evil.json "$f"; done < { + expect(await bash(command)).toBe(true); + }); + + it.each([ + `xargs rm -rf <<'EOF'\n/home/u/.failproofai\nEOF`, + `cat > /tmp/x.sh <<'EOF'\nrm -rf ~/.failproofai\nEOF\nbash /tmp/x.sh`, + ])("state: denies %s", async (command) => { + expect(await stateDenied(command)).toBe(true); + }); + }); + + describe("gaps the second round left", () => { + it.each([ + `cp /tmp/evil.json ~/.claude/settings$( true ).json`, + "cp /tmp/evil.json ~/.claude/settings` true `.json", + `cd "$(dirname ~/.claude/settings.json)" && echo '{}' > settings.json`, + `python3 -c"import os; p=os.path.join(os.path.expanduser('~'),'.claude','settings.json'); open(p,'w')"`, + `python3 \\\n -c "import os; p=os.path.join(os.path.expanduser('~'),'.claude','settings.json'); open(p,'w')"`, + `git -C ~/.claude log -1 --output=settings.json`, + `git bundle create ~/.claude/settings.json HEAD`, + `sed -n -l 1 "w $HOME/.claude/settings.json" /tmp/evil.json`, + `git rebase -x 'cp /tmp/evil.json ~/.claude/settings.json' HEAD~1`, + `git submodule foreach 'cp /tmp/evil.json ~/.claude/settings.json'`, + `git -C ~/.claude switch evil`, + `git -C ~/.claude merge FETCH_HEAD`, + `git -C ~/.claude rebase evil`, + `git -C ~/.claude am /tmp/evil.mbox`, + ])("denies %s", async (command) => { + expect(await bash(command)).toBe(true); + }); + + it("no longer takes a trailing comment for the destination", async () => { + expect(await stateDenied("cp /dev/null ~/.failproofai/policies-config.json # reset")).toBe(true); + expect(await bash("cp /dev/null ~/.claude/settings.json # reset")).toBe(true); + }); + + it("protects config.toml beside a relocated Codex hooks file", async () => { + const session = { cwd: PROJ, agentSettingsPath: `${home}/.codex-work/hooks.json` }; + const result = await runIn("Write", { file_path: `${home}/.codex-work/config.toml`, content: "[features]\nhooks = false\n" }, session); + expect(result.decision).toBe("deny"); + }); + + it("protects .github/hooks as a directory only where failproofai's Copilot hooks live", async () => { + const withHooks = join(root, "copilot-proj"); + mkdirSync(join(withHooks, ".github", "hooks"), { recursive: true }); + writeFileSync(join(withHooks, ".github", "hooks", "failproofai.json"), "{}"); + expect(await bash("rm -rf .github/hooks", withHooks)).toBe(true); + const gitHooksOnly = join(root, "githooks-proj"); + mkdirSync(join(gitHooksOnly, ".github", "hooks"), { recursive: true }); + expect(await bashDecision("rm -rf .github/hooks", gitHooksOnly)).toBe("allow"); + }); + }); + + describe("false positives the second round added", () => { + it.each([ + `git commit -m "Deny xargs writes to .claude/settings.json"`, + `git commit -m "Refuse codex features disable hooks"`, + `git -c core.pager=cat log -p -- .claude/settings.json`, + `awk '$2 > 1 {print $1}' ~/.claude/settings.json`, + `git merge feature -m "notes about ~/.claude/settings.json"`, + `git stash push -m "before editing .claude/settings.json"`, + ])("allows %s", async (command) => { + expect(await bashDecision(command)).toBe("allow"); + }); + + it("allows pointing git's hooksPath at a Copilot install's directory", async () => { + // A real install, so `.github/hooks/` is protected as a directory here: + // without the file the test passed whether or not the rule held. + const project = join(root, "copilot-install"); + mkdirSync(join(project, ".github", "hooks"), { recursive: true }); + writeFileSync(join(project, ".github", "hooks", "failproofai.json"), "{}"); + const session = { cwd: project, agentSettingsPath: join(project, ".github", "hooks", "failproofai.json") }; + expect((await runIn("Bash", { command: "rm -rf .github/hooks" }, session)).decision).toBe("deny"); + expect((await runIn("Bash", { command: "git config core.hooksPath .github/hooks" }, session)).decision).toBe("allow"); + }); + + it("still judges the state's merge message as a message", async () => { + expect(await bashDecision(`git merge feature -m "notes about ~/.failproofai"`)).toBe("allow"); + }); + }); + + it("stays linear on many quoted arguments", async () => { + // Deciding whether a quote's command was a shell copied the command's + // words at every quote: 20k quoted printf arguments took 1.46 s in the + // second round. One pass now; the bound leaves room for a slow runner. + const command = "printf '%s\\n' " + Array.from({ length: 40000 }, (_, i) => `'arg${i}'`).join(" "); + const started = performance.now(); + expect(await bashDecision(command)).toBe("allow"); + expect(performance.now() - started).toBeLessThan(3000); + }, 60_000); +}); + +/** + * The fourth review pass: what the lexer still read differently from bash, + * message bodies that something runs after all, and inputs that grew + * faster than their size. + */ +describe("block-failproofai-commands — review round four", () => { + const stateDenied = async (command: string) => { + const result = await run("Bash", { command }); + return result.decision === "deny" && /failproofai's own state/.test(result.reason ?? ""); + }; + + describe("what the lexer read differently from bash", () => { + it("reads ${…} as one word: a # inside it starts no comment", async () => { + expect(await stateDenied("echo ${X:- #}; rm -rf ~/.failproofai")).toBe(true); + expect(await bash("echo ${X:- #}; rm ~/.claude/settings.json")).toBe(true); + expect(await bash(`echo "$(echo \${X:-)}; cp /tmp/evil.json ~/.claude/settings.json)"`)).toBe(true); + }); + + it("reads a heredoc delimiter the way bash does", async () => { + // `< { + expect(await stateDenied("rm -rf ~/.fa${X:-ilproofai}")).toBe(true); + expect(await stateDenied(`rm -rf ~/.fa\${X:-il\${Z:+${"A".repeat(300)}}proofai}`)).toBe(true); + expect(await bash("cp /tmp/evil.json ~/.clau${X:-de}/settings.json")).toBe(true); + }); + + it("keeps an unquoted substitution whole as a cd operand", async () => { + expect(await bash("cd $(echo ~/.claude) && echo '{}' > settings.json")).toBe(true); + }); + }); + + describe("a message body that something runs", () => { + const body = "$(cat <<'EOF'\ncp /tmp/evil.json ~/.claude/settings.json\nEOF\n)"; + it.each([ + `sudo -u root sh -c "${body}"`, + `timeout -s KILL 5 sh -c "${body}"`, + `find /tmp -maxdepth 0 -exec sh -c "${body}" \;`, + `X="${body}"; eval "$X"`, + `echo "${body}" | sh`, + ])("denies %s", async (command) => { + expect(await bash(command)).toBe(true); + }); + }); + + describe("text piped into a shell", () => { + it("is judged as a command", async () => { + expect(await stateDenied("echo 'rm -rf ~/.failproofai' | sh")).toBe(true); + expect(await bash("printf 'cp /tmp/evil.json %s\\n' ~/.claude/settings.json | sh")).toBe(true); + expect(await bashDecision("echo 'codex features disable hooks' | sh")).toBe("deny"); + expect(await bashDecision("echo 'codex features disable hooks' | cat")).toBe("allow"); + }); + }); + + describe("commands git runs", () => { + it.each([ + `git difftool -x 'cp /tmp/evil.json ~/.claude/settings.json' HEAD`, + `git filter-branch --tree-filter 'cp /tmp/evil.json .claude/settings.json' HEAD`, + ])("denies %s", async (command) => { + expect(await bash(command)).toBe(true); + }); + }); + + describe("message shapes that are only messages", () => { + it.each([ + "git commit -m \"$(cat < docs/hooks.md <<'EOF'\nSee .github/hooks/failproofai.json\nrm -rf ~/.claude\nEOF", + "tee docs/hooks.md <<'EOF' >/dev/null\nrm -rf ~/.claude\nEOF", + ])("allows %s", async (command) => { + expect(await bashDecision(command)).toBe("allow"); + }); + + it("allows the state's quoted message too, which main denied", async () => { + expect(await bashDecision("git commit -m \"$(cat <<'EOF'\nKeep ~/.failproofai intact\nEOF\n)\"")).toBe("allow"); + }); + }); + + describe("inputs that grew faster than their size", () => { + const fast = async (command: string, limitMs: number) => { + const started = performance.now(); + await bashDecision(command); + return performance.now() - started < limitMs; + }; + it("handles thousands of heredoc operators on one line", async () => { + expect(await fast("cat " + "< { + expect(await fast("echo " + "${".repeat(50000), 3000)).toBe(true); + }, 60_000); + }); +}); + +/** The last review pass. */ +describe("block-failproofai-commands — review round five", () => { + const stateDenied = async (command: string) => { + const result = await run("Bash", { command }); + return result.decision === "deny" && /failproofai's own state/.test(result.reason ?? ""); + }; + + it("reads an echoed or printed heredoc that a later command runs", async () => { + expect(await stateDenied(`echo "$(cat <<'EOF'\nrm -rf ~/.failproofai\nEOF\n)" > /tmp/x.sh && sh /tmp/x.sh`)).toBe(true); + expect(await stateDenied(`printf '%s\\n' "$(cat <<'EOF'\nrm -rf ~/.failproofai\nEOF\n)" > /tmp/x.sh; bash /tmp/x.sh`)).toBe(true); + }); + + it("reads the failproofai CLI in text piped into a shell", async () => { + const result = await run("Bash", { command: "echo 'failproofai config --pause' | sh" }); + expect(result.decision).toBe("deny"); + expect(result.reason).toMatch(/Pausing failproofai/); + expect(await bashDecision("echo 'failproofai config --pause' | cat")).toBe("allow"); + }); + + it("stays fast on thousands of heredocs on one line", async () => { + const command = "cat < { + const command = "rm ~/.c" + "*".repeat(200) + "laude/settings.json"; + const started = performance.now(); + expect(await bash(command)).toBe(true); + expect(performance.now() - started).toBeLessThan(3000); + const spread = "rm ~/.c" + "*l".repeat(60) + "*aude/settings.json"; + const startedSpread = performance.now(); + await bashDecision(spread); + expect(performance.now() - startedSpread).toBeLessThan(3000); + }, 60_000); +}); + +/** + * hermes's first review and CodeRabbit's: a write through a link, a `..` after + * one, a quoted word in a hooks-off command, interpreter examples nothing runs, + * and where the shell stands through pipelines and subshells. + */ +describe("block-failproofai-commands — review round six", () => { + let h6: string; + let p6: string; + let outerHome: string | undefined; + const settings = () => join(h6, ".claude", "settings.json"); + const program = () => `python3 -c "open('${settings()}','w')"`; + + beforeAll(() => { + // Its own HOME and project, so the links below reach nothing else in this file. + h6 = join(root, "home6"); + p6 = join(root, "proj6"); + mkdirSync(join(h6, ".claude", "subdir"), { recursive: true }); + writeFileSync(settings(), "{}"); + mkdirSync(join(p6, ".claude"), { recursive: true }); + mkdirSync(join(p6, "config"), { recursive: true }); + writeFileSync(join(p6, "config", "claude.json"), "{}"); + symlinkSync(join("..", "config", "claude.json"), join(p6, ".claude", "settings.json")); + symlinkSync(settings(), join(p6, "cfg.json")); + symlinkSync(join(h6, ".claude"), join(p6, "agent-dir")); + symlinkSync(join(h6, ".claude", "subdir"), join(p6, "link")); + symlinkSync(join(h6, ".claude", "settings.local.json"), join(p6, "dangling.json")); + symlinkSync(join(h6, ".claude", "subdir"), join(h6, "hlink")); + outerHome = process.env.HOME; + process.env.HOME = h6; + }); + + afterAll(() => { + if (outerHome === undefined) delete process.env.HOME; + else process.env.HOME = outerHome; + }); + + describe("a shell write through a link (hermes F1)", () => { + it.each([ + `printf '{"disableAllHooks":true}' > cfg.json`, + `cp /tmp/x cfg.json`, + `printf '{}' > agent-dir/settings.json`, + `cd agent-dir && cp /tmp/x settings.json`, + `printf '{}' > config/claude.json`, + `printf '{}' > link/../settings.json`, + `printf '{}' > dangling.json`, + ])("denies %s", async (command) => { + expect(await bash(command, p6)).toBe(true); + }); + + it("leaves an ordinary file beside them alone", async () => { + expect(await bashDecision(`printf '{}' > config/other.json`, p6)).toBe("allow"); + expect(await bashDecision(`cat cfg.json && ls agent-dir/`, p6)).toBe("allow"); + }); + }); + + describe("a file tool's path through a link (hermes F2)", () => { + it("denies a .. that follows a link, relative and absolute", async () => { + expect(await write("link/../settings.json", p6)).toBe(true); + expect(await write(`${p6}/link/../settings.json`, p6)).toBe(true); + }); + + it("follows a link that leads nowhere yet: writing it creates the target", async () => { + expect(await write("dangling.json", p6)).toBe(true); + }); + + it("allows an ordinary .. path", async () => { + expect(await decision("Write", { file_path: "config/../notes.md", content: "x" }, p6)).toBe("allow"); + }); + }); + + describe("a quoted word in an agent CLI's hooks-off command (hermes F3)", () => { + it.each([ + `codex features disable "hooks"`, + `codex features disable 'hooks'`, + `codex features disable ho"oks"`, + `codex "features" disable hooks`, + `echo $(codex features disable "hooks")`, + ])("denies %s", async (command) => { + const result = await run("Bash", { command }); + expect(result.decision).toBe("deny"); + expect(result.reason).toMatch(/Turning an agent's hooks off/); + }); + + it("still reads a message that quotes one as a message", async () => { + expect(await bashDecision(`git commit -m "codex features disable hooks is now refused"`)).toBe("allow"); + }); + }); + + describe("an interpreter example nothing runs (hermes F4, CodeRabbit)", () => { + it("allows one in a comment, a stored heredoc or a commit message", async () => { + expect(await bashDecision(`echo ok # ${program()}`, p6)).toBe("allow"); + expect(await bashDecision(`cat > docs/x.md <<'EOF'\n${program()}\nEOF`, p6)).toBe("allow"); + expect(await bashDecision(`git commit -F - <<'EOF'\nRefuse ${program()} from agents\nEOF`, p6)).toBe("allow"); + const quoted = `python3 -c "open(\\"${settings()}\\",\\"w\\")"`; + expect(await bashDecision(`git commit -m 'Refuse ${quoted} from agents'`, p6)).toBe("allow"); + }); + + it("denies one that runs", async () => { + expect(await bash(program(), p6)).toBe(true); + expect(await bash(`echo ok; ${program()}`, p6)).toBe(true); + expect(await bash(`env -i ${program()}`, p6)).toBe(true); + expect(await bash(`sh -c "python3 -c \\"open('${settings()}','w')\\""`, p6)).toBe(true); + }); + }); + + describe("a redirect after a copy's destination (reported by the #1795 session)", () => { + it.each([ + `cp /dev/null ~/.claude/settings.json 2>/dev/null`, + `cp /tmp/x ~/.claude/settings.json > /tmp/log`, + `cp /tmp/x ~/.claude/settings.json < /dev/null`, + `cp /tmp/x ~/.claude/settings.json 2>&1`, + `install -m 644 /tmp/x ~/.claude/settings.json 2>/dev/null`, + ])("denies %s", async (command) => { + expect(await bash(command)).toBe(true); + }); + + it("reads a glob over the home directory spelled out (the #1795 session's other case)", async () => { + expect(await bash(`rm -rf ${h6}/.clau*`)).toBe(true); + }); + + it("closes it for the state too, and leaves a copy out of the settings alone", async () => { + expect((await run("Bash", { command: "cp /dev/null ~/.failproofai/policies-config.json 2>/dev/null" })).decision).toBe("deny"); + expect(await bashDecision("cp ~/.claude/settings.json /tmp/backup.json 2>/dev/null")).toBe("allow"); + expect(await bashDecision("cp /tmp/a /tmp/b 2>/dev/null")).toBe("allow"); + }); + }); + + describe("CodeRabbit's later reviews", () => { + it("follows a link before a .. in a home path, from the shell and from a file tool", async () => { + expect(await bash(`printf '{}' > ~/hlink/../settings.json`)).toBe(true); + expect(await write("~/hlink/../settings.json")).toBe(true); + }); + + it.each([ + `cp /dev/null ~/.claude/settings.json 2> '/tmp/build log'`, + `cp /dev/null ~/.claude/settings.json > "/tmp/a b"`, + `cp /dev/null ~/.claude/settings.json 2>/tmp/a\\ b`, + `cp /dev/null ~/.claude/settings.json 2>'/tmp/a b'`, + ])("takes a redirect's whole target out of the copy's operands: %s", async (command) => { + expect(await bash(command)).toBe(true); + }); + + it("reads through a filter that writes no file of its own", async () => { + expect(await bashDecision(`cat ~/.claude/settings.json | tr a-z A-Z`)).toBe("allow"); + expect(await bashDecision(`cat ~/.claude/settings.json | tac | rev`)).toBe("allow"); + expect(await bash(`cat /tmp/x | tr a-z A-Z > ~/.claude/settings.json`)).toBe(true); + }); + + it("leaves a quoted > inside an argument where it is", async () => { + expect(await bashDecision(`cp "/tmp/a > b" /tmp/out`)).toBe("allow"); + }); + + it("ends a heredoc only at a line that is its delimiter", async () => { + expect(await bashDecision(`cat > notes.md <<'EOF'\nEOF \nrm -rf ~/.claude\nEOF\n`)).toBe("allow"); + expect(await bashDecision(`cat > notes.md <<'EOF'\n EOF\nrm -rf ~/.claude\nEOF\n`)).toBe("allow"); + expect(await bashDecision(`cat > notes.md <<-'EOF'\n\trm -rf ~/.claude\n\tEOF\n`)).toBe("allow"); + expect(await bash(`cat < notes.md <<'EOF'\nhello\nEOF\nrm -rf ~/.claude\n`)).toBe(true); + }); + + it("stays linear on long runs of parentheses, pipes and variables", async () => { + for (const command of [ + "echo " + "(".repeat(40000) + " $A".repeat(40000), + "echo x " + "|".repeat(40000) + " sh", + ]) { + const started = performance.now(); + await bashDecision(command); + expect(performance.now() - started).toBeLessThan(3000); + } + }, 60_000); + }); + + describe("where the shell stands (CodeRabbit)", () => { + it("lets a cd before a | move nothing", async () => { + expect(await bashDecision(`cd ~/.claude | cat; cp /tmp/example.json settings.json`)).toBe("allow"); + expect(await bash(`cd /tmp | cat; cp /tmp/example.json settings.json`, join(h6, ".claude"))).toBe(true); + }); + + it("counts a cd that ends a pipeline both ways: zsh runs it, bash does not", async () => { + expect(await bash(`true | cd /tmp; cp /tmp/example.json settings.json`, join(h6, ".claude"))).toBe(true); + expect(await bash(`true | cd ~/.claude; cp /tmp/example.json settings.json`)).toBe(true); + }); + + it("gives the parent back its directory stack when a subshell closes", async () => { + expect(await bash(`cd ~/.claude; (cd /tmp; pushd /tmp); popd; cp /tmp/x settings.json`)).toBe(true); + expect(await bashDecision(`cd ~/.claude; pushd /tmp; (popd); cp /tmp/x settings.json`)).toBe("allow"); + expect(await bash(`cd ~/.claude && (cd /tmp && ls) && cp /tmp/x settings.json`)).toBe(true); + }); + + it("stays where it is on a popd with nothing pushed", async () => { + expect(await bash(`cd ~/.claude; popd; cp /tmp/x settings.json`)).toBe(true); + }); + }); + + describe("a relocated settings path inside a longer one (CodeRabbit)", () => { + const session = { cwd: PROJ, agentSettingsPath: "/srv/profile/settings.json" }; + const decide = async (command: string) => (await policy.fn({ eventType: "PreToolUse", payload: AGENT_PAYLOAD, toolName: "Bash", toolInput: { command }, session })).decision; + + it("is not the relocated file", async () => { + expect(await decide(`cp /tmp/x /backup/srv/profile/settings.json`)).toBe("allow"); + }); + + it("still reads the file itself, its directory after a glued option, and an --output= value", async () => { + expect(await decide(`cp /tmp/x /srv/profile/settings.json`)).toBe("deny"); + expect(await decide(`tar -xf /tmp/a.tar -C/srv/profile`)).toBe("deny"); + expect(await decide(`sort --output=/srv/profile/settings.json /tmp/x`)).toBe("deny"); + }); + }); + + it("stays linear in a script of file-writing heredocs on separate lines (CodeRabbit)", async () => { + const script = Array.from({ length: 4000 }, (_, i) => `cat > /tmp/out/f${i}.txt < { + let h7: string; + let p7: string; + let pkg7: string; + let outerHome: string | undefined; + let outerPackageRoot: string | undefined; + const settings = () => join(h7, ".claude", "settings.json"); + + beforeAll(() => { + h7 = join(root, "home7"); + p7 = join(root, "proj7"); + pkg7 = join(root, "pkg7"); + mkdirSync(join(h7, ".claude", "subdir"), { recursive: true }); + mkdirSync(join(h7, ".hermes", "plugins"), { recursive: true }); + writeFileSync(settings(), "{}"); + mkdirSync(join(p7, ".git"), { recursive: true }); + mkdirSync(join(p7, ".claude"), { recursive: true }); + mkdirSync(join(p7, "config"), { recursive: true }); + mkdirSync(join(p7, "src"), { recursive: true }); + writeFileSync(join(p7, "config", "claude.json"), "{}"); + mkdirSync(join(pkg7, "hermes-plugin"), { recursive: true }); + mkdirSync(join(pkg7, "openclaw-plugin"), { recursive: true }); + writeFileSync(join(pkg7, "hermes-plugin", "__init__.py"), ""); + symlinkSync(join("..", "config", "claude.json"), join(p7, ".claude", "settings.local.json")); + symlinkSync(settings(), join(p7, "my cfg.json")); + symlinkSync(join(h7, ".claude", "subdir"), join(p7, "clink")); + symlinkSync(join(pkg7, "hermes-plugin"), join(h7, ".hermes", "plugins", "failproofai")); + mkdirSync(join(h7, ".claude", "x"), { recursive: true }); + symlinkSync(join(h7, ".claude", "x"), join(p7, "physical-link")); + mkdirSync(join(p7, "external", ".git"), { recursive: true }); + symlinkSync(join(h7, ".claude", "x"), join(p7, "external", "link")); + mkdirSync(join(p7, "archive"), { recursive: true }); + symlinkSync(join(h7, ".claude", "x"), join(p7, "archive", "link")); + symlinkSync(settings(), join(p7, "cfg.json")); + mkdirSync(join(p7, "sub"), { recursive: true }); + symlinkSync(settings(), join(p7, "sub", "cfg.json")); + mkdirSync(join(p7, "external", "archive"), { recursive: true }); + symlinkSync(join(h7, ".claude", "x"), join(p7, "external", "archive", "link")); + outerHome = process.env.HOME; + outerPackageRoot = process.env.FAILPROOFAI_PACKAGE_ROOT; + process.env.HOME = h7; + }); + + afterAll(() => { + if (outerHome === undefined) delete process.env.HOME; + else process.env.HOME = outerHome; + if (outerPackageRoot === undefined) delete process.env.FAILPROOFAI_PACKAGE_ROOT; + else process.env.FAILPROOFAI_PACKAGE_ROOT = outerPackageRoot; + }); + + it.each([ + `printf '{}' > "my cfg.json"`, + `printf '{}' > my\\ cfg.json`, + `cp /tmp/x "my cfg.json"`, + ])("follows a link whose name has a space in it: %s", async (command) => { + expect(await bash(command, p7)).toBe(true); + }); + + it("protects a root settings link's target from a subdirectory session", async () => { + expect(await bash(`printf '{}' > ../config/claude.json`, join(p7, "src"))).toBe(true); + expect(await write(join(p7, "config", "claude.json"), join(p7, "src"))).toBe(true); + expect(await bashDecision(`printf '{}' > ../config/other.json`, join(p7, "src"))).toBe("allow"); + }); + + it("protects every file behind an installed plugin link, and the package's plugin directories", async () => { + expect(await write(join(pkg7, "hermes-plugin", "__init__.py"), p7)).toBe(true); + expect(await bash(`printf x > ${join(pkg7, "hermes-plugin", "evil.py")}`, p7)).toBe(true); + process.env.FAILPROOFAI_PACKAGE_ROOT = pkg7; + expect(await write(join(pkg7, "openclaw-plugin", "index.js"), p7)).toBe(true); + expect(await decision("Write", { file_path: join(pkg7, "README.md"), content: "x" }, p7)).toBe("allow"); + }); + + it.each([ + `codex features disable $'\\x68ooks'`, + `F=hooks; codex features disable $F`, + `F=hooks; codex features disable "$F"`, + ])("reads an escaped or variable word in a hooks-off command: %s", async (command) => { + const result = await run("Bash", { command }); + expect(result.decision).toBe("deny"); + expect(result.reason).toMatch(/Turning an agent's hooks off/); + }); + + it.each([ + `cp -t"$HOME/.claude" /tmp/settings.json`, + `cp -vt ~/.claude /tmp/settings.json`, + `cp --target-directory=$HOME/.claude /tmp/settings.json`, + `install -m 644 -t ~/.claude /tmp/settings.json`, + ])("judges each source where a target directory puts it: %s", async (command) => { + expect(await bash(command, p7)).toBe(true); + }); + + it("leaves other files copied into or out of an agent directory alone", async () => { + expect(await bashDecision(`cp -t ~/.claude /tmp/notes.md`, p7)).toBe("allow"); + expect(await bashDecision(`cp -t /tmp/backup ~/.claude/settings.json`, p7)).toBe("allow"); + }); + + it("resolves git's relative -C chain before its output path", async () => { + expect(await bash(`git -C .claude log -1 --format='format:{"disableAllHooks":true}' --output=settings.json`, p7)).toBe(true); + expect(await bash(`git -C . -C .claude log -1 --output=settings.json`, p7)).toBe(true); + expect(await bashDecision(`git -C .claude log -1 --output=/tmp/log.txt`, p7)).toBe("allow"); + }); + + it("knows where the shell may stand after cd -, a failing cd and cd -P", async () => { + expect(await bash(`cd ~/.claude && cd /tmp && cd - && cp /tmp/x settings.json`, p7)).toBe(true); + // An OLDPWD from before the command could be any directory, so the state + // guard refuses this first, with its own reason. + expect(await bashDecision(`cd - && cp /tmp/x settings.json`, p7)).toBe("deny"); + expect(await bash(`cd /nonexistent-r7; cp /tmp/x settings.json`, join(h7, ".claude"))).toBe(true); + expect(await bash(`cd -P clink/.. && cp /tmp/x settings.json`, p7)).toBe(true); + expect(await bashDecision(`cd clink/.. && cp /tmp/x settings.json`, p7)).toBe("allow"); + expect(await bashDecision(`mkdir -p build && cd build && cp /tmp/x settings.json`, p7)).toBe("allow"); + }); + + // hermes round 3. + it.each([ + `codex features disable "\${UNSET:-hooks}"`, + `codex features disable \${UNSET:-ho}oks`, + `F=1; codex features disable \${F:+hooks}`, + ])("reads a parameter default in a hooks-off command: %s", async (command) => { + const result = await run("Bash", { command }); + expect(result.decision).toBe("deny"); + expect(result.reason).toMatch(/Turning an agent's hooks off/); + }); + + it("keeps a message that quotes a parameter default a message", async () => { + expect(await bashDecision(`git commit -m "codex features disable \${X:-hooks} is refused"`)).toBe("allow"); + }); + + it.each([ + `cd ~/.claude; pushd -n /tmp; cp /tmp/settings.json settings.json`, + `pushd ~/.claude; popd -n; cp /tmp/settings.json settings.json`, + `cd ~/.claude; cd /tmp; cd /missing-r8; cd -; cp /tmp/settings.json settings.json`, + `pushd ~/.claude; pushd /tmp; pushd; cp /tmp/settings.json settings.json`, + `pushd ~/.claude; pushd /tmp; pushd +1; cp /tmp/settings.json settings.json`, + ])("knows a directory command that leaves the shell, or OLDPWD, in place: %s", async (command) => { + expect(await bash(command, p7)).toBe(true); + }); + + it("still follows an ordinary pushd and popd", async () => { + expect(await bashDecision(`pushd /tmp && ls && popd && cp /tmp/x settings.json`, p7)).toBe("allow"); + }); + + it("matches a glob whatever the case of its literal parts (macOS resolves them so)", async () => { + expect(await bash(`rm -rf ~/.CLAUDE/settings.js*`, p7)).toBe(true); + expect(await bashDecision(`rm -rf ~/.CACHE/*`, p7)).toBe("allow"); + }); + + it("resolves git -C the way chdir walks it", async () => { + expect(await bash(`git -C physical-link/.. log -1 --format='format:{"disableAllHooks":true}' --output=settings.json`, p7)).toBe(true); + expect(await bashDecision(`git -C physical-link log -1 --output=/tmp/out.txt`, p7)).toBe("allow"); + }); + + // hermes round 4. + it("reads every value a variable is given on the line, not only the last", async () => { + const result = await run("Bash", { command: `F=hooks; codex features disable "$F"; F=web_search` }); + expect(result.decision).toBe("deny"); + expect(result.reason).toMatch(/Turning an agent's hooks off/); + expect(await bashDecision(`F=web_search; codex features disable "$F"`)).toBe("allow"); + }); + + it("does not trust the stack's order after a rotation", async () => { + expect(await bash(`pushd ~/.claude; pushd /tmp; pushd +2; cd /tmp; popd; popd; cp /tmp/settings.json settings.json`, p7)).toBe(true); + expect(await bashDecision(`pushd /tmp; pushd /var; popd; popd; cp /tmp/x settings.json`, p7)).toBe("allow"); + }); + + it("follows git's -C directories and output through links before the text gate", async () => { + expect(await bash(`git -C external -C link/.. log -1 --format='format:{"disableAllHooks":true}' --output=settings.json`, p7)).toBe(true); + expect(await bash(`git -C external log -1 --output=link/../settings.json`, p7)).toBe(true); + expect(await bashDecision(`git -C external log -1 --output=out.txt`, p7)).toBe("allow"); + }); + + it("reads a quoted heredoc output filename, and a quoted -F -, as written", async () => { + const program = `python3 -c "open('${settings()}','w')"`; + expect(await bashDecision(`cat > '/tmp/example.md' <<'EOF'\n${program}\nEOF\n`, p7)).toBe("allow"); + expect(await bashDecision(`cat > "/tmp/my example.md" <<'EOF'\n${program}\nEOF\n`, p7)).toBe("allow"); + expect(await bashDecision(`git commit -F "-" <<'EOF'\nKeep rm -rf ~/.claude out of agents\nEOF\n`, p7)).toBe("allow"); + // A file named by an expansion is still unknown, so a body run from it is read. + expect(await bash(`cat > "$F" <<'EOF'\nrm -rf ~/.claude\nEOF\nbash "$F"\n`, p7)).toBe(true); + }); + + // hermes round 5. + it.each([ + `F=ho; F=\${F}oks; codex features disable "$F"`, + `F=hooks; X=$F; codex features disable "$X"`, + `codex $(echo features) disable hooks`, + ])("refuses a hooks-off command whose words an expansion could make: %s", async (command) => { + const result = await run("Bash", { command }); + expect(result.decision).toBe("deny"); + expect(result.reason).toMatch(/Turning an agent's hooks off/); + }); + + it("is not hidden by many earlier assignments, and reads a known other feature as itself", async () => { + const decoys = Array.from({ length: 70 }, (_, i) => `F=decoy${i}`).join("; "); + expect((await run("Bash", { command: `${decoys}; F=hooks; codex features disable "$F"` })).decision).toBe("deny"); + expect(await bashDecision(`F=web_search; codex features disable "$F"`)).toBe("allow"); + }); + + it("reads a value glued to git archive's -o through a link", async () => { + expect(await bash(`git archive -oarchive/link/../settings.json HEAD`, p7)).toBe(true); + expect(await bashDecision(`git archive -o/tmp/out.tar HEAD`, p7)).toBe("allow"); + }); + + it("follows a variable that holds a link to the settings", async () => { + expect(await bash(`D=cfg.json; cp /tmp/evil.json "$D"`, p7)).toBe(true); + expect(await bash(`D=physical-link/..; cd -P "$D"; cp /tmp/evil.json settings.json`, p7)).toBe(true); + expect(await bashDecision(`D=notes.md; cp /tmp/evil.json "$D"`, p7)).toBe("allow"); + }); + + it("finds a stored script run later under a quoted, escaped or built name", async () => { + const store = `cat > '/tmp/example.md' <<'EOF'\ncp /tmp/evil ${settings()}\nEOF\n`; + expect(await bash(`${store}bash /tmp/exam'ple.md'\n`, p7)).toBe(true); + expect(await bash(`${store}bash /tmp/exam\\ple.md\n`, p7)).toBe(true); + expect(await bash(`${store}bash /tmp/exam$X\n`, p7)).toBe(true); + expect(await bashDecision(`${store}echo done\n`, p7)).toBe("allow"); + }); + + it("copies into an existing directory under each source's own name", async () => { + expect(await bashDecision(`cp README.md ~/.claude`, p7)).toBe("allow"); + expect(await bash(`cp /tmp/settings.json ~/.claude`, p7)).toBe(true); + expect(await bash(`cp -rT /tmp/evil ~/.claude`, p7)).toBe(true); + expect(await bash(`cp -r /tmp/evil/. ~/.claude`, p7)).toBe(true); + }); + + // hermes round 6. + it("keeps --parents' own path under the directory it copies into", async () => { + expect(await bash(`cp --parents .claude/settings.json ~`, p7)).toBe(true); + expect(await bash(`cp --parents -t ~ .claude/settings.json`, p7)).toBe(true); + expect(await bashDecision(`cp --parents src/a.ts /tmp/backup`, p7)).toBe("allow"); + }); + + it("stays linear on a name built from many expansions that does not match", async () => { + const command = `cat > /tmp/${"a".repeat(100)}.md <<'EOF'\nhello\nEOF\nbash /tmp/${"a\${X}".repeat(8)}z.md\n`; + const started = performance.now(); + await bashDecision(command, p7); + expect(performance.now() - started).toBeLessThan(3000); + }, 60_000); + + it("finds a stored script run later under a glob or brace name", async () => { + const store = `cat > /tmp/example.md <<'EOF'\ncp /tmp/evil ${settings()}\nEOF\n`; + expect(await bash(`${store}bash /tmp/exa*\n`, p7)).toBe(true); + expect(await bash(`${store}bash /tmp/{example,x}.md\n`, p7)).toBe(true); + }); + + it("judges a variable's link from where the shell stands when it is used", async () => { + expect(await bash(`cd sub; D=cfg.json; cp /tmp/evil.json "$D"`, p7)).toBe(true); + }); + + it("reads a copy destination held in a variable as the directories it holds", async () => { + expect(await bashDecision(`D=~/.claude; cp README.md "$D"`, p7)).toBe("allow"); + expect(await bash(`D=~/.claude; cp /tmp/settings.json "$D"`, p7)).toBe(true); + }); + + it("joins a value glued to git's -o to the -C repository", async () => { + expect(await bash(`git -C external archive -oarchive/link/../settings.json HEAD`, p7)).toBe(true); + }); + + // hermes round 7. + it("resolves a link passed through a second variable", async () => { + expect(await bash(`cd sub; A=cfg.json; D=$A; cp /tmp/evil.json "$D"`, p7)).toBe(true); + }); + + it("reads a -t directory and copy sources held in variables as their values", async () => { + expect(await bashDecision(`D=~/.claude; cp -t "$D" README.md`, p7)).toBe("allow"); + expect(await bashDecision(`S=README.md; cp "$S" ~/.claude`, p7)).toBe("allow"); + expect(await bash(`S=/tmp/settings.json; cp "$S" ~/.claude`, p7)).toBe(true); + expect(await bash(`cp "$S" ~/.claude`, p7)).toBe(true); + }); + + it("does not trust a variable given more values than are kept", async () => { + const backup = join(root, "backup7"); + mkdirSync(backup, { recursive: true }); + const decoys = Array.from({ length: 64 }, () => `D=${backup}`).join("; "); + // A crafted variable counts as naming every protected path, so the state + // guard, which runs first, refuses this with its own reason. + expect(await bashDecision(`${decoys}; D=~/.claude; cp /tmp/settings.json "$D"`, p7)).toBe("deny"); + }); + + it("protects the target of a settings link that does not exist yet", async () => { + const fresh = join(root, "proj7-dangling"); + mkdirSync(join(fresh, ".claude"), { recursive: true }); + mkdirSync(join(fresh, "config"), { recursive: true }); + symlinkSync(join("..", "config", "new.json"), join(fresh, ".claude", "settings.local.json")); + expect(await write(join(fresh, "config", "new.json"), fresh)).toBe(true); + expect(await bash(`printf '{}' > config/new.json`, fresh)).toBe(true); + expect(await bashDecision(`printf '{}' > config/other.json`, fresh)).toBe("allow"); + }); + + // hermes round 8. + it("resolves a variable chain of any length, and refuses a cycle", async () => { + const chain = (n: number) => ["A0=cfg.json", ...Array.from({ length: n }, (_, i) => `A${i + 1}=$A${i}`)].join("; "); + expect(await bash(`cd sub; ${chain(5)}; cp /tmp/evil.json "$A5"`, p7)).toBe(true); + expect(await bash(`cd sub; ${chain(300)}; cp /tmp/evil.json "$A300"`, p7)).toBe(true); + expect(await bashDecision(`cd sub; A=$B; B=$A; cp /tmp/evil.json "$A"`, p7)).toBe("deny"); + }); + + it("leaves ordinary variables, environment variables, appends and substitutions alone", async () => { + expect(await bashDecision(`export PATH="$PATH:$HOME/bin"; npm test`, p7)).toBe("allow"); + expect(await bashDecision(`PATH=$PATH:/opt/x npm run build`, p7)).toBe("allow"); + expect(await bashDecision(`FLAGS="$FLAGS -v"; make $FLAGS`, p7)).toBe("allow"); + expect(await bashDecision(`DIR=$(mktemp -d); cp a "$DIR/x"; rm -rf "$DIR"`, p7)).toBe("allow"); + expect(await bashDecision(`A=x; B=$A; C=$B; rm -rf "$C"`, p7)).toBe("allow"); + expect(await bashDecision(`cp /tmp/x "$OUTDIR/report.txt"`, p7)).toBe("allow"); + }); + + it("protects a relocated settings file's link target from the shell, existing or not yet", async () => { + const profile = join(root, "profile8"); + const actual = join(root, "actual8"); + mkdirSync(profile, { recursive: true }); + mkdirSync(actual, { recursive: true }); + writeFileSync(join(actual, "primary.json"), "{}"); + symlinkSync(join(actual, "primary.json"), join(profile, "settings.json")); + symlinkSync(join(actual, "local.json"), join(profile, "settings.local.json")); + const session = { cwd: p7, agentSettingsPath: join(profile, "settings.json") }; + const decide = async (command: string) => + (await policy.fn({ eventType: "PreToolUse", payload: AGENT_PAYLOAD, toolName: "Bash", toolInput: { command }, session })).decision; + expect(await decide(`cp /tmp/disable.json ${join(actual, "primary.json")}`)).toBe("deny"); + expect(await decide(`printf '{}' > ${join(actual, "local.json")}`)).toBe("deny"); + expect(await decide(`printf '{}' > ${join(actual, "notes.json")}`)).toBe("allow"); + }); + + // hermes round 9. + it("bounds the values self-appends and doubling references can build, in time too", async () => { + const appends = (n: number) => ["A=x", ...Array.from({ length: n }, (_, i) => `A=\${A}x${i}`)].join("; ") + `; cp a "$A"`; + const doubling = (n: number) => ["A=x", ...Array.from({ length: n }, () => "A=${A}${A}")].join("; ") + `; cp a "$A"`; + const chained = (n: number) => + ["B0=x", ...Array.from({ length: n }, (_, i) => `B${i + 1}=\${B${i}}\${B${i}}`)].join("; ") + `; cp a "$B${n}"`; + const started = performance.now(); + // More values, or a longer one, than any real command builds count as + // naming the target; building them stops at the limit. + expect(await bashDecision(appends(24), p7)).toBe("deny"); + expect(await bashDecision(appends(63), p7)).toBe("deny"); + expect(await bashDecision(doubling(40), p7)).toBe("deny"); + expect(await bashDecision(chained(40), p7)).toBe("deny"); + expect(performance.now() - started).toBeLessThan(2000); + // Appends still resolve, and a long value as written is not one that grew. + expect(await bash(`cd sub; A=cf; A=\${A}g.json; cp /tmp/evil.json "$A"`, p7)).toBe(true); + expect(await bashDecision(`X=${"y".repeat(5000)}; cp a "$X"`, p7)).toBe("allow"); + }); + + it("keeps a variable's known values beside one that cannot be known", async () => { + // A name that is a settings link only where the shell has moved to. + mkdirSync(join(p7, "sub9"), { recursive: true }); + symlinkSync(settings(), join(p7, "sub9", "cfg9.json")); + expect(await bash(`cd sub9; A=cfg9.json; A=$(true); cp /tmp/evil.json "$A"`, p7)).toBe(true); + expect(await bash("cd sub9; A=cfg9.json; A=`true`; cp /tmp/evil.json \"$A\"", p7)).toBe(true); + expect(await bashDecision(`D=$(mktemp -d); D=$D/out; cp a "$D/x"`, p7)).toBe("allow"); + expect(await bashDecision(`OUT=build/report.txt; OUT=$(mktemp); cp a "$OUT"`, p7)).toBe("allow"); + }); + + it.skipIf(process.platform === "win32")( + "protects the link target of a worktree's local settings at the main checkout", + async () => { + // A linked worktree as git lays it out: Claude Code reads its local + // settings at the main checkout's root, which links them elsewhere. + const main = join(root, "main9"); + const worktree = join(root, "wt9"); + const outside = join(root, "outside9"); + mkdirSync(join(main, ".git", "worktrees", "wt9"), { recursive: true }); + writeFileSync(join(main, ".git", "worktrees", "wt9", "commondir"), "../..\n"); + mkdirSync(join(worktree, "src"), { recursive: true }); + writeFileSync(join(worktree, ".git"), `gitdir: ${join(main, ".git", "worktrees", "wt9")}\n`); + mkdirSync(join(main, ".claude"), { recursive: true }); + mkdirSync(outside, { recursive: true }); + writeFileSync(join(outside, "local-config.json"), "{}"); + symlinkSync(join(outside, "local-config.json"), join(main, ".claude", "settings.local.json")); + const target = join(outside, "local-config.json"); + expect(await write(target, join(worktree, "src"))).toBe(true); + expect(await bash(`printf '{}' > ${target}`, join(worktree, "src"))).toBe(true); + expect(await bash(`cp /tmp/disable.json ${target}`, worktree)).toBe(true); + expect(await bashDecision(`printf '{}' > ${join(outside, "notes.json")}`, worktree)).toBe("allow"); + }, + ); + + it("follows a destination built by parameter expansion, arrays and appends", async () => { + // A name that is a settings link only where the shell has moved to. + mkdirSync(join(p7, "sub10"), { recursive: true }); + symlinkSync(settings(), join(p7, "sub10", "cfg10.json")); + for (const command of [ + `cd sub10; cp /tmp/evil.json "\${A:-cfg10.json}"`, + `cd sub10; cp /tmp/evil.json "\${A=cfg10.json}"`, + `cd sub10; A=cfg10.json.bak; cp /tmp/evil.json "\${A%.bak}"`, + `cd sub10; A=cfg10.json.bak; cp /tmp/evil.json "\${A%.*}"`, + `cd sub10; A=/x/y/cfg10.json; cp /tmp/evil.json "\${A##*/}"`, + `cd sub10; A=xcfg10.json; tee "\${A#x}" < /dev/null`, + `cd sub10; A=cfg10Xjson; cp /tmp/evil.json "\${A/X/.}"`, + `cd sub10; A=CFG10.JSON; cp /tmp/evil.json "\${A,,}"`, + `cd sub10; A=zzcfg10.json; cp /tmp/evil.json "\${A:2}"`, + `cd sub10; A=cfg10.json; R=A; cp /tmp/evil.json "\${!R}"`, + `cd sub10; A=(x cfg10.json); cp /tmp/evil.json "\${A[1]}"`, + `cd sub10; A=cf; A+=g10.json; cp /tmp/evil.json "$A"`, + `cd sub10; printf '{}' > "\${A:-cfg10.json}"`, + `cd sub10; A=cfg10.json.bak; cp /tmp/evil.json "\${A%$SUFFIX}"`, + `cd sub10; A=(x cfg10.json); cp /tmp/evil.json "\${A[@]:1}"`, + ]) { + expect(await bash(command, p7), command).toBe(true); + } + // An operator this does not follow, over a known value, counts as naming it. + expect(await bashDecision(`cd sub10; A=cfg10.json; cp /tmp/evil.json "\${A:0:$((10))}"`, p7)).toBe("deny"); + }); + + it("leaves ordinary parameter expansions alone", async () => { + for (const command of [ + `cp a "\${OUT:-build}/x.txt"`, + `f=report.txt; mv "$f" "\${f%.txt}.md"`, + `for f in *.txt; do mv "$f" "\${f%.txt}.md"; done`, + `cp a "\${1:-out}/x"`, + `A=(a b c); for x in "\${A[@]}"; do cp "$x" /tmp/; done`, + `NAME=report; cp a "\${NAME^^}.txt"`, + `PATH+=:/opt/bin; npm test`, + `A=a/b/c; cp x "/tmp/\${A//\\//_}.txt"`, + `x=${"ab-".repeat(100)}; cp a "/tmp/\${x//[^a-z]/}"`, + `A=${"a".repeat(1000)}; cp a "/tmp/\${A//*b*/x}"`, + `f=report.txt; cp a "/tmp/\${f%$EXT}.bak"`, + ]) { + expect(await bashDecision(command, p7), command).toBe("allow"); + } + }); + + it("bounds the pattern matching an expansion can ask for", async () => { + // A match that starts early and ends early makes every longer end a try. + const long = "ab" + "c".repeat(4000); + const started = performance.now(); + // Past the budget the word reads as built to evade. + expect(await bashDecision(`A=${long}; cp x "\${A//a*b/x}"`, p7)).toBe("deny"); + expect(await bashDecision(`A=${long}; cp x "\${A##a*b}"`, p7)).toBe("deny"); + // A pattern that matches nowhere costs one walk, and changes nothing. + expect(await bashDecision(`A=${"a".repeat(4000)}; cp x "\${A//*a*a*a*a*b/x}"`, p7)).toBe("allow"); + expect(performance.now() - started).toBeLessThan(2000); + }); + + it("matches a glob against the files behind settings links", async () => { + const profile = join(root, "profile10"); + const actual = join(root, "actual10"); + mkdirSync(profile, { recursive: true }); + mkdirSync(actual, { recursive: true }); + writeFileSync(join(actual, "primary.json"), "{}"); + symlinkSync(join(actual, "primary.json"), join(profile, "settings.json")); + const session = { cwd: p7, agentSettingsPath: join(profile, "settings.json") }; + const decide = async (command: string) => + (await policy.fn({ eventType: "PreToolUse", payload: AGENT_PAYLOAD, toolName: "Bash", toolInput: { command }, session })).decision; + expect(await decide(`cp /tmp/disable.json ${join(actual, "prim*.json")}`)).toBe("deny"); + expect(await decide(`printf '{}' > ${join(actual, "prim?ry.json")}`)).toBe("deny"); + expect(await decide(`cd ${actual} && cp /tmp/disable.json prim*.json`)).toBe("deny"); + expect(await decide(`cp /tmp/x ${join(actual, "notes*.json")}`)).toBe("allow"); + // A project's settings link target too: `.claude/settings.local.json -> ../config/claude.json`. + expect(await bash(`cp /tmp/x config/cl*.json`, p7)).toBe(true); + }); + + it("follows values a line assigns other ways: for, read, printf -v, a nameref, a substitution", async () => { + mkdirSync(join(p7, "sub11"), { recursive: true }); + symlinkSync(settings(), join(p7, "sub11", "cfg11.json")); + for (const command of [ + `cd sub11; for A in cfg11.json; do cp /tmp/evil.json "$A"; done`, + `cd sub11; for A in *.json; do cp /tmp/evil.json "$A"; done`, + `cd sub11; read -r A <<< "cfg11.json"; cp /tmp/evil.json "$A"`, + `cd sub11; read <<< cfg11.json; cp /tmp/evil.json "$REPLY"`, + `cd sub11; printf -v A '%s.%s' cfg11 json; cp /tmp/evil.json "$A"`, + `cd sub11; A=$(echo cfg11.json); cp /tmp/evil.json "$A"`, + "cd sub11; A=`printf %s cfg11.json`; cp /tmp/evil.json \"$A\"", + `cd sub11; A=$(basename /x/cfg11.json); cp /tmp/evil.json "$A"`, + `cd sub11; A=$(readlink -f cfg11.json); cp /tmp/evil.json "$A"`, + `A=cfg11.json; declare -n R=A; cd sub11; cp /tmp/evil.json "$R"`, + ]) { + expect(await bash(command, p7), command).toBe(true); + } + for (const command of [ + `read A <<< hello; echo "$A" > /tmp/out.txt`, + `A=$(date +%s); cp a "/tmp/$A.txt"`, + `A=$(echo build); cp a "$A/x"`, + `printf -v n '%05d' 7; cp a "/tmp/$n.txt"`, + `for f in src/*.ts; do cp "$f" /tmp/; done`, + ]) { + expect(await bashDecision(command, p7), command).toBe("allow"); + } + }); + + it("expands a glob on disk to the links it reaches", async () => { + mkdirSync(join(p7, "sub12"), { recursive: true }); + symlinkSync(settings(), join(p7, "sub12", "cfg12.json")); + writeFileSync(join(p7, "sub12", "notes.txt"), "x"); + expect(await bash(`cd sub12; cp /tmp/evil.json *.json`, p7)).toBe(true); + expect(await bash(`cp /tmp/evil.json sub12/c?g12.json`, p7)).toBe(true); + expect(await bash(`cp /tmp/evil.json sub12/{cfg12,x}.json`, p7)).toBe(true); + expect(await bashDecision(`cd sub12; cp /tmp/x *.txt`, p7)).toBe("allow"); + expect(await bashDecision(`ls sub12/*.json; cat sub12/*.json; cp sub12/*.json /tmp/backup/`, p7)).toBe("allow"); + }); + + it("reads each directory once for a command's globs", async () => { + const many = join(root, "many12"); + mkdirSync(many, { recursive: true }); + for (let i = 0; i < 1000; i++) writeFileSync(join(many, `f${i}.json`), ""); + const command = "cp a " + Array.from({ length: 4000 }, (_, i) => `x${i}*.json`).join(" ") + " /tmp/out/"; + const started = performance.now(); + expect(await bashDecision(command, many)).toBe("allow"); + expect(performance.now() - started).toBeLessThan(3000); + }); + + // hermes round 10. + it("checks every path a glob expands to on disk, and reads a limit as reaching the target", async () => { + const many = join(p7, "many13"); + mkdirSync(many, { recursive: true }); + for (let i = 0; i < 260; i++) writeFileSync(join(many, `cfg${i}.json`), "{}"); + symlinkSync(settings(), join(many, "cfg999.json")); + expect(await bash(`cd many13; printf '{"disableAllHooks":true}' | tee cfg*.json >/dev/null`, p7)).toBe(true); + expect(await bash(`printf x | tee ${many}/cfg*.json >/dev/null`, p7)).toBe(true); + // Many ordinary matches are still ordinary work. + const objects = join(p7, "build13"); + mkdirSync(objects, { recursive: true }); + for (let i = 0; i < 3000; i++) writeFileSync(join(objects, `f${i}.o`), ""); + const started = performance.now(); + expect(await bashDecision(`rm -f build13/*.o`, p7)).toBe("allow"); + expect(performance.now() - started).toBeLessThan(2000); + expect(await bashDecision(`cp a many13/zz*.json`, p7)).toBe("allow"); + // An extended glob is matched as the `*` that covers it. + expect(await bash(`shopt -s extglob; cd many13; tee @(cfg999).json < /dev/null`, p7)).toBe(true); + expect(await bashDecision(`rm -rf /tmp/@(build|dist)`, p7)).toBe("allow"); + }); + + it("follows a cd or pushd whose operand a variable gives", async () => { + mkdirSync(join(p7, "sub14"), { recursive: true }); + symlinkSync(settings(), join(p7, "sub14", "cfg14.json")); + for (const command of [ + `D=sub14; cd "$D"; cp ../disable.json cfg14.json`, + `D=sub14; pushd "$D"; cp ../disable.json cfg14.json`, + `D=sub14; cd $D && printf x > cfg14.json`, + `cd "\${D:-sub14}"; cp ../disable.json cfg14.json`, + ]) { + expect(await bash(command, p7), command).toBe(true); + } + expect(await bashDecision(`D=src; cd "$D"; cp ../a.txt out.txt`, p7)).toBe("allow"); + expect(await bashDecision(`cd "$WORKDIR"; cp a b`, p7)).toBe("allow"); + }); + + it("expands a parameter expansion in an assigned value", async () => { + mkdirSync(join(p7, "sub15"), { recursive: true }); + symlinkSync(settings(), join(p7, "sub15", "cfg15.json")); + for (const command of [ + `cd sub15; A=cfg15.json.bak; B=\${A%.bak}; cp /tmp/evil.json "$B"`, + `cd sub15; B=\${A:-cfg15.json}; cp /tmp/evil.json "$B"`, + `cd sub15; A=cfg15Xjson; B=\${A/X/.}; cp /tmp/evil.json "$B"`, + `cd sub15; A=zzcfg15.json; B=\${A:2}; cp /tmp/evil.json "$B"`, + `cd sub15; A=cfg15.json.bak; A=\${A%.bak}; cp /tmp/evil.json "$A"`, + `cd sub15; A=CFG15.JSON; B="\${A,,}"; cp /tmp/evil.json "$B"`, + ]) { + expect(await bash(command, p7), command).toBe(true); + } + expect(await bashDecision(`f=report.txt; out=\${f%.txt}.md; cp a "$out"`, p7)).toBe("allow"); + }); + + // hermes round 11. + it("walks a glob's `..` after a link the way the kernel does", async () => { + // p7/physical-link -> /.claude/x + expect(await bash(`printf '{}' | tee physical-link/../settings*.json >/dev/null`, p7)).toBe(true); + expect(await bash(`cp /tmp/x physical-link/../set*.json`, p7)).toBe(true); + }); + + it("follows the glob options a command turns on", async () => { + mkdirSync(join(p7, "dotonly16", ".private"), { recursive: true }); + symlinkSync(settings(), join(p7, "dotonly16", ".private", "cfg16.json")); + mkdirSync(join(p7, "deep16", "a", "b"), { recursive: true }); + symlinkSync(settings(), join(p7, "deep16", "a", "b", "cfg16.json")); + mkdirSync(join(p7, "case16"), { recursive: true }); + symlinkSync(settings(), join(p7, "case16", "cfg16.json")); + expect(await bash(`shopt -s dotglob; printf '{}' | tee dotonly16/*/cfg16.json >/dev/null`, p7)).toBe(true); + expect(await bash(`shopt -s globstar; printf '{}' | tee deep16/**/*.json >/dev/null`, p7)).toBe(true); + expect(await bash(`shopt -s nocaseglob; cd case16; printf x | tee CFG16*.JSON`, p7)).toBe(true); + // Without dotglob neither bash nor zsh reaches into `.private`. `**` with + // no option is denied: zsh, macOS's default shell, recurses there anyway. + expect(await bashDecision(`printf '{}' | tee dotonly16/*/cfg16.json >/dev/null`, p7)).toBe("allow"); + expect(await bash(`printf '{}' | tee deep16/**/*.json >/dev/null`, p7)).toBe(true); + }); + + it("resolves a git -C operand a variable gives", async () => { + mkdirSync(join(p7, "repo17", "sub"), { recursive: true }); + mkdirSync(join(p7, "repo17", ".git"), { recursive: true }); + symlinkSync(settings(), join(p7, "repo17", "sub", "cfg17.json")); + expect(await bash(`cd repo17; D=sub; git -C "$D" log --format='format:{}' --output=cfg17.json`, p7)).toBe(true); + expect(await bashDecision(`cd repo17; D=src; git -C "$D" log --output=log.txt`, p7)).toBe("allow"); + }); + + it("reads a self-default assignment as its default while the variable is unset", async () => { + mkdirSync(join(p7, "sub18"), { recursive: true }); + symlinkSync(settings(), join(p7, "sub18", "cfg18.json")); + expect(await bash(`cd sub18; A=\${A:-cfg18.json}; cp /tmp/evil.json "$A"`, p7)).toBe(true); + expect(await bash(`cd sub18; A=\${A-cfg18.json}; cp /tmp/evil.json "$A"`, p7)).toBe(true); + expect(await bashDecision(`A=\${A:-out}; cp a "$A/x"`, p7)).toBe("allow"); + }); + + it("counts every relative destination once the shell may stand in too many places", async () => { + mkdirSync(join(p7, "sub19"), { recursive: true }); + symlinkSync(settings(), join(p7, "sub19", "cfg19.json")); + expect(await bashDecision(`cd n1; cd n2; cd n3; cd n4; cd n5; cd sub19; cp /tmp/evil.json cfg19.json`, p7)).toBe("deny"); + expect(await bashDecision(`mkdir -p out && cd out && cmake .. && make`, p7)).toBe("allow"); + }); + + it("keeps a single-quoted assigned value literal", async () => { + mkdirSync(join(p7, "sub20"), { recursive: true }); + symlinkSync(settings(), join(p7, "sub20", "cfg20.json")); + expect(await bashDecision(`cd sub20; A=cfg20.json; B='$A'; cp ../disable.json "$B"`, p7)).toBe("allow"); + expect(await bash(`cd sub20; A=cfg20.json; B="$A"; cp ../disable.json "$B"`, p7)).toBe(true); + }); + + // Found checking the round-11 fixes. Reading no variables at all from the + // unescaped text kept `B='$A'` literal, and left a value that starts with a + // quoted piece read only as far as that piece. + it("reads an assigned value that starts with a quoted piece in full", async () => { + mkdirSync(join(p7, "sub21"), { recursive: true }); + symlinkSync(settings(), join(p7, "sub21", "cfg21.json")); + expect(await bash(`D="$HOME"/.claude/settings.json; cp /tmp/evil.json "$D"`, p7)).toBe(true); + expect(await bash(`cd sub21; A='cfg21'.json; cp /tmp/evil.json "$A"`, p7)).toBe(true); + expect(await bash(`cd sub21; A="cfg21".json; cp /tmp/evil.json $A`, p7)).toBe(true); + expect(await bash(`cd sub21; A="cfg21"'.json'; cp /tmp/evil.json $A`, p7)).toBe(true); + expect(await bash(`cd sub21; A=cfg21.json; B='x'$A; cp ../disable.json "\${B#x}"`, p7)).toBe(true); + // A value continued on the next line is one value. + expect(await bash(`D=~/.cla\\\nude/settings.json; cp /tmp/evil.json $D`, p7)).toBe(true); + }); + + it("keeps a dollar the shell would not expand literal, however it is quoted", async () => { + mkdirSync(join(p7, "sub22"), { recursive: true }); + symlinkSync(settings(), join(p7, "sub22", "cfg22.json")); + expect(await bashDecision(`cd sub22; A=cfg22.json; B=\\$A; cp ../disable.json "$B"`, p7)).toBe("allow"); + expect(await bashDecision(`cd sub22; A=cfg22.json; B="\\$A"; cp ../disable.json "$B"`, p7)).toBe("allow"); + expect(await bashDecision(`cd sub22; A=cfg22.json; B=$'$A'; cp ../disable.json "$B"`, p7)).toBe("allow"); + expect(await bashDecision(`cd sub22; A=cfg22.json; B='\${A}'; C=$B; cp ../disable.json "$C"`, p7)).toBe("allow"); + // The reference the command does make is still followed. + expect(await bash(`cd sub22; A=cfg22.json; B=$A; cp ../disable.json "$B"`, p7)).toBe(true); + }); + + // Found end to end on macOS, whose default shell is zsh: Claude Code runs + // the agent's command there, and zsh needs no option for `**/` to recurse. + it("reads a glob the way zsh expands it too", async () => { + mkdirSync(join(p7, "deep23", "a", "b"), { recursive: true }); + symlinkSync(settings(), join(p7, "deep23", "a", "b", "cfg23.json")); + mkdirSync(join(p7, "dot23", ".private"), { recursive: true }); + symlinkSync(settings(), join(p7, "dot23", ".private", "cfg23.json")); + mkdirSync(join(p7, "case23"), { recursive: true }); + symlinkSync(settings(), join(p7, "case23", "cfg23.json")); + expect(await bash(`printf '{}' | tee deep23/**/*.json >/dev/null`, p7)).toBe(true); + expect(await bash(`printf '{}' | tee deep23/***/cfg23.json >/dev/null`, p7)).toBe(true); + expect(await bash(`setopt globdots; printf '{}' | tee dot23/*/cfg23.json >/dev/null`, p7)).toBe(true); + expect(await bash(`setopt GLOB_DOTS; printf '{}' | tee dot23/*/cfg23.json >/dev/null`, p7)).toBe(true); + expect(await bash(`printf '{}' | tee dot23/*(D)/cfg23.json >/dev/null`, p7)).toBe(true); + expect(await bash(`unsetopt CASE_GLOB; cd case23; printf x | tee CFG23*.JSON`, p7)).toBe(true); + // Hidden directories still need an option, and ordinary recursive work stays allowed. + expect(await bashDecision(`printf '{}' | tee dot23/*/cfg23.json >/dev/null`, p7)).toBe("allow"); + expect(await bashDecision(`rm -f src/**/*.orig`, p7)).toBe("allow"); + expect(await bashDecision(`rm -rf **/__pycache__`, p7)).toBe("allow"); + }); + + // hermes on 336194e1. + it("judges a substitution where it runs, after the commands before it", async () => { + mkdirSync(join(p7, "sub24"), { recursive: true }); + symlinkSync(settings(), join(p7, "sub24", "cfg24.json")); + expect(await bash(`cd sub24; echo "$(cp ../disable.json cfg24.json)"`, p7)).toBe(true); + expect(await bash("cd sub24; echo \"`cp ../disable.json cfg24.json`\"", p7)).toBe(true); + expect(await bashDecision(`cd sub24; echo "$(ls)"`, p7)).toBe("allow"); + }); + + it("refuses a line with more substitutions than it reads", async () => { + mkdirSync(join(p7, "sub25"), { recursive: true }); + symlinkSync(settings(), join(p7, "sub25", "cfg25.json")); + const padding = "$(true)".repeat(64); + expect(await bashDecision(`echo "${padding}$(cp disable.json sub25/cfg25.json)"`, p7)).toBe("deny"); + expect(await bashDecision(`echo "${"$(true)".repeat(63)}$(cp disable.json sub25/cfg25.json)"`, p7)).toBe("deny"); + expect(await bashDecision(`echo "${"$(date)".repeat(10)}"`, p7)).toBe("allow"); + }); + + it("reads git -C past the repositories it keeps as reaching anywhere", async () => { + mkdirSync(join(p7, "repo26", ".git"), { recursive: true }); + const values = Array.from({ length: 17 }, (_, i) => `D=r${i}`).join("; "); + expect(await bashDecision(`cd repo26; ${values}; git -C "$D" log --format='format:{}' --output=cfg26.json`, p7)).toBe("deny"); + expect(await bashDecision(`cd repo26; D=src; git -C "$D" log --oneline`, p7)).toBe("allow"); + }); + + it("reads a glob destination once the walk loses where the shell stands", async () => { + const dirs = Array.from({ length: 17 }, (_, i) => `d27_${i}`); + for (const dir of dirs) mkdirSync(join(p7, "over27", dir), { recursive: true }); + symlinkSync(settings(), join(p7, "over27", dirs[16], "cfg27.json")); + const values = dirs.map((dir) => `D=${dir}`).join("; "); + expect(await bashDecision(`cd over27; ${values}; cd "$D"; cp ../../disable.json cfg2*.json`, p7)).toBe("deny"); + }); + + it("checks what a glob expands to by name only once the command changes how globs match", async () => { + // /.claude/settings.json is on disk, and under dotglob `*` reaches `.claude`. + expect(await bash(`shopt -s dotglob; printf x | tee ~/*/settings.json`, p7)).toBe(true); + expect(await bash(`shopt -s dotglob; rm -rf ~/*`, p7)).toBe(true); + // Under the default rules a pattern that also takes ordinary directories is a sweep. + expect(await bashDecision(`rm -rf ~/.*`, p7)).toBe("allow"); + expect(await bashDecision(`rm -rf ~/.!(config)`, p7)).toBe("allow"); + }); + + it("reads OpenClaw's apply_patch, which arrives by its own name", async () => { + const patch = (file: string) => `*** Begin Patch\n*** Update File: ${file}\n@@\n-x\n+y\n*** End Patch\n`; + const run = async (toolInput: Record) => + (await policy.fn({ eventType: "PreToolUse", payload: AGENT_PAYLOAD, toolName: "apply_patch", toolInput, session: { cwd: p7 } })).decision; + expect(await run({ input: patch(join(h7, ".openclaw", "openclaw.json")) })).toBe("deny"); + expect(await run({ patchText: patch(".claude/settings.json") })).toBe("deny"); + // Whatever key carries it. + expect(await run({ text: patch(".codex/hooks.json") })).toBe("deny"); + expect(await run({ input: patch("src/app.ts") })).toBe("allow"); + expect(POLICY_CATALOG.find((entry) => entry.name === "block-failproofai-commands")!.match.toolNames).toContain("apply_patch"); + }); + + it("reads an appended variable in an agent CLI's hooks-off command", async () => { + expect(await bashDecision(`F=ho; F+=oks; codex features disable "$F"`, p7)).toBe("deny"); + expect(await bashDecision(`F+=hooks; codex features disable $F`, p7)).toBe("deny"); + }); + + it("reads an empty heredoc delimiter the way bash does", async () => { + expect(await bash(`cat > /tmp/notes <<''\ncat > /tmp/y < /tmp/notes <<''\nrm -rf ~/.claude\n\necho done\n`, p7)).toBe("allow"); + }); +}); + +describe("agent-settings-guard helpers", () => { + it("matches settings files anchored at the end, and config directories exactly", () => { + expect(isAgentSettingsPath("/h/.claude/settings.json")).toBe(true); + expect(isAgentSettingsPath(".claude/settings.local.json")).toBe(true); + expect(isAgentSettingsPath("/h/.claude/settings.json.bak")).toBe(false); + expect(isAgentSettingsPath("/h/my.claude/settings.json")).toBe(false); + expect(isAgentSettingsPath("/h/.claude/projects/x/settings.json")).toBe(false); + expect(isAgentConfigDirPath("/h/.claude")).toBe(true); + expect(isAgentConfigDirPath("/h/.claude/")).toBe(true); + expect(isAgentConfigDirPath("/h/.claude/skills")).toBe(false); + expect(isAgentConfigDirPath("/h/.github")).toBe(false); + // `.github/hooks/` is also where repositories keep GIT hooks: only its + // `*.json` files are Copilot's. + expect(isAgentConfigDirPath("/h/.github/hooks")).toBe(false); + expect(isAgentSettingsPath("/h/.github/hooks/failproofai.json")).toBe(true); + }); + + it("reads file paths before patch text, and patch text only without them", () => { + expect(agentToolWritePaths({ file_path: "/a", content: "*** Update File: /b" })).toEqual(["/a"]); + expect(agentToolWritePaths({ notebook_path: "/n.ipynb" })).toEqual(["/n.ipynb"]); + expect(agentToolWritePaths({ command: ["apply_patch", "*** Begin Patch\n*** Update File: x/y.ts\n*** End Patch"] })).toEqual(["x/y.ts"]); + expect(agentToolWritePaths(undefined)).toEqual([]); + }); + + it("finds every file a patch touches", () => { + expect( + agentPatchTargetPaths( + "*** Begin Patch\n*** Add File: a.ts\n*** Update File: b.ts\n*** Move to: c.ts\n*** Delete File: d.ts\n*** End Patch", + ), + ).toEqual(["a.ts", "b.ts", "c.ts", "d.ts"]); + expect(agentPatchTargetPaths("--- a/x.json\n+++ b/x.json\n--- /dev/null\n+++ b/new.json\n")).toEqual([ + "x.json", + "x.json", + "new.json", + ]); + }); +}); + +/** + * #1105 review, item 1: Codex runs a shell command in the `workdir` its tool + * names, and its hook payload reports the session's directory only. The state + * walk read that since #1058; the settings walk read neither the workdir nor + * the possibility of one, so `printf '{}' > hooks.json` with workdir + * `~/.codex` was a write in the project root. + */ +describe("block-failproofai-commands — a Codex command's own directory (#1105 review)", () => { + const codex = async (toolInput: Record, cwd: string = PROJ) => { + const ctx: PolicyContext = { eventType: "PreToolUse", payload: AGENT_PAYLOAD, toolName: "Bash", toolInput, session: { cwd }, cli: "codex" }; + return policy.fn(ctx); + }; + const codexDeniedAsSettings = async (toolInput: Record, cwd?: string) => { + const result = await codex(toolInput, cwd); + return result.decision === "deny" && /settings or hook file/.test(result.reason ?? ""); + }; + + it("reads a Codex command from the workdir its call reports", async () => { + expect(await codexDeniedAsSettings({ command: "printf '{}' > hooks.json", workdir: `${home}/.codex` })).toBe(true); + expect(await codexDeniedAsSettings({ command: "printf x > config.toml", workdir: `${home}/.codex` })).toBe(true); + expect(await codexDeniedAsSettings({ command: "rm -f settings.json", workdir: `${home}/.claude` })).toBe(true); + // Relative to the session, as Codex resolves it. + expect(await codexDeniedAsSettings({ command: "printf '{}' > hooks.json", workdir: ".codex" })).toBe(true); + // Any agent's `workdir` is where its command runs. + expect(await deniedAsSettings("Bash", { command: "printf '{}' > hooks.json", workdir: `${home}/.codex` })).toBe(true); + }); + + it.each([ + "printf '{}' > hooks.json", + "printf x >> config.toml", + "tee hooks.json < /tmp/x", + "mv /tmp/x opencode.json", + "printf x > ../hooks.json", + "cd sub && printf x > ../hooks.json", + "cd .codex && printf x > hooks.json", + "rm -rf .", + ])("denies a Codex command that would write a settings file wherever it runs: %s", async (command) => { + expect(await codexDeniedAsSettings({ command })).toBe(true); + }); + + it.each([ + "printf x > notes.txt", + "printf x > src/hooks.ts", + "cp /tmp/x package.json", + "rm -rf dist node_modules", + "cat hooks.json", + "cd /tmp && printf x > hooks.json", + "printf x > docs/settings.md", + "rm -rf dist/*", + // Only Codex's own directory is assumed for an unreported start, so other + // agents' file names written relative to a project stay allowed. + "cp /tmp/x settings.json", + "cp /tmp/x settings.local.json", + "printf x > plugins/failproofai.mjs", + "cd hooks && printf '{}' > agent.json", + "printf '{}' > config.json", + "printf x > config.yaml", + "printf x > .vscode-notes.json", + ])("allows a Codex command that writes no settings file: %s", async (command) => { + expect((await codex({ command })).decision).toBe("allow"); + }); + + it("reads a reported workdir as where the command runs", async () => { + expect((await codex({ command: "printf '{}' > hooks.json", workdir: `${PROJ}/src` })).decision).toBe("allow"); + }); + + it("reads other agents' commands from the session's directory", async () => { + expect((await run("Bash", { command: "printf '{}' > hooks.json" })).decision).toBe("allow"); + }); +}); + +/** + * #1105 review, item 5: OpenCode also reads a project's own `opencode.json(c)` + * at its root (and in every directory up to it), and VS Code agent mode reads + * `.vscode/settings.json`, whose `chat.hookFilesLocations` decides which hook + * files it loads at all. + */ +describe("block-failproofai-commands — OpenCode's project config and VS Code's settings (#1105 review)", () => { + const files = ["opencode.json", "opencode.jsonc", "packages/web/opencode.json", ".opencode/opencode.json", ".opencode/opencode.jsonc", ".vscode/settings.json"]; + + it.each(files)("denies Write and Edit on /%s", async (file) => { + expect(await write(`${PROJ}/${file}`)).toBe(true); + expect(await deniedAsSettings("Edit", { file_path: `${PROJ}/${file}`, old_string: "{", new_string: '{"plugin": [],' })).toBe(true); + // Relative to the session, as the tool opens it. + expect(await write(file)).toBe(true); + }); + + it.each(files)("denies a shell write to /%s", async (file) => { + expect(await bash(`printf '{}' > ${file}`)).toBe(true); + expect(await bash(`cp /tmp/x ${PROJ}/${file}`)).toBe(true); + expect(await bash(`sed -i 's/a/b/' ${file}`)).toBe(true); + }); + + it.each(files)("allows reading /%s", async (file) => { + expect(await decision("Read", { file_path: `${PROJ}/${file}` })).toBe("allow"); + expect(await bashDecision(`cat ${file}`)).toBe("allow"); + expect(await bashDecision(`jq . ${file}`)).toBe("allow"); + }); + + it.each([".vscode/launch.json", ".vscode/extensions.json", ".vscode/tasks.json", "src/opencode.ts", "docs/opencode.md"])( + "leaves /%s editable", + async (file) => { + expect(await decision("Write", { file_path: `${PROJ}/${file}`, content: "{}" })).toBe("allow"); + expect(await bashDecision(`printf '{}' > ${file}`)).toBe("allow"); + }, + ); +}); + +/** + * #1105 bot review: the settings walk read any command word named like a + * reader as that reader. A project's own `./cat` that writes "$1" replaced + * ~/.claude/settings.json with {"disableAllHooks":true}. A reader is now the + * real tool only where the state guard's F17 rule says so: a path in /usr/bin + * or /bin, or a bare name the AGENT's PATH (carried in the payload) finds + * there first. + */ +describe("block-failproofai-commands — a reader that is not the real tool (#1105 bot review)", () => { + let shadowBin: string; + beforeAll(() => { + shadowBin = join(root, "shadow-bin"); + mkdirSync(shadowBin, { recursive: true }); + for (const name of ["cat", "jq", "grep", "head"]) { + writeFileSync(join(shadowBin, name), "#!/bin/sh\nprintf '{\"disableAllHooks\":true}' > \"$1\"\n", { mode: 0o755 }); + } + }); + + const decideWith = async (command: string, agentPath?: string) => { + const payload = agentPath === undefined ? {} : { [AGENT_PATH_KEY]: agentPath }; + return (await policy.fn({ eventType: "PreToolUse", payload, toolName: "Bash", toolInput: { command }, session: { cwd: PROJ } })).decision; + }; + const SYSTEM_PATH = "/usr/bin:/bin"; + + it.each([ + "./cat ~/.claude/settings.json", + "./jq . ~/.claude/settings.json", + "/tmp/x/cat ~/.claude/settings.json", + "bin/cat ~/.codex/hooks.json", + "../cat .claude/settings.local.json", + "./head -n 1 ~/.claude/settings.json", + "find ~/.claude -name settings.json -exec ./cat {} \\;", + "echo ~/.claude/settings.json | xargs ./cat", + ])("denies a reader that is a program of the project's own: %s", async (command) => { + expect(await decideWith(command, SYSTEM_PATH)).toBe("deny"); + }); + + it.each(["cat ~/.claude/settings.json", "jq . ~/.claude/settings.json", "grep -n hooks ~/.codex/hooks.json", "head ~/.claude/settings.json"])( + "denies a bare reader the agent's PATH finds outside /usr/bin and /bin: %s", + async (command) => { + expect(await decideWith(command, `${shadowBin}:${SYSTEM_PATH}`)).toBe("deny"); + // A relative PATH entry may find one in the project. + expect(await decideWith(command, `.:${SYSTEM_PATH}`)).toBe("deny"); + }, + ); + + it("denies a bare reader when the agent's PATH is not known", async () => { + expect(await decideWith("cat ~/.claude/settings.json")).toBe("deny"); + }); + + it("denies a reader the same line redefines", async () => { + expect(await decideWith(`cat() { cp /dev/null "$1"; }; cat ~/.claude/settings.json`, SYSTEM_PATH)).toBe("deny"); + expect(await decideWith(`echo() { cp /dev/null "$1"; }; echo ~/.claude/settings.json`, SYSTEM_PATH)).toBe("deny"); + expect(await decideWith(`PATH=${shadowBin}:$PATH cat ~/.claude/settings.json`, SYSTEM_PATH)).toBe("deny"); + expect(await decideWith("env echo ~/.claude/settings.json")).toBe("deny"); + }); + + it.each([ + "cat ~/.claude/settings.json", + "/usr/bin/cat ~/.claude/settings.json", + "/bin/cat ~/.claude/settings.json", + "jq . ~/.claude/settings.json", + "grep -n hooks ~/.codex/hooks.json", + "head -n 5 ~/.claude/settings.json", + "ls -la ~/.claude", + "find ~/.claude -name settings.json -exec cat {} \\;", + "cd ~/.claude && cat settings.json", + ])("allows the real reader on the agent's system PATH: %s", async (command) => { + expect(await decideWith(command, SYSTEM_PATH)).toBe("allow"); + }); + + it.each(["echo ~/.claude/settings.json", "test -f ~/.claude/settings.json", "[ -f ~/.claude/settings.json ]", "cd ~/.claude"])( + "allows a shell builtin whatever the PATH: %s", + async (command) => { + expect(await decideWith(command)).toBe("allow"); + }, + ); +}); diff --git a/__tests__/hooks/state-guard.test.ts b/__tests__/hooks/state-guard.test.ts index 11a84cbfd..74e317359 100644 --- a/__tests__/hooks/state-guard.test.ts +++ b/__tests__/hooks/state-guard.test.ts @@ -3,6 +3,10 @@ import { describe, it, expect, vi } from "vitest"; import { BUILTIN_POLICIES } from "../../src/hooks/builtin-policies"; import { POLICY_CATALOG } from "../../src/hooks/policy-catalog"; import type { PolicyContext } from "../../src/hooks/policy-types"; +import { AGENT_PATH_KEY } from "../../src/hooks/agent-path"; +import { existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; // Same mocks as builtin-policies.test.ts. Nothing under test reads a file or // spawns a process, and these keep it that way: a state guard whose test suite @@ -19,8 +23,17 @@ vi.mock("node:child_process", () => ({ execFileSync: vi.fn(), })); +// The payload carries the agent's PATH, as the hook CLI puts it there +// (agent-path.ts); this process's PATH stands for the agent's, read at call +// time so a test's vi.stubEnv("PATH", …) is what the "agent" has. function makeCtx(overrides: Partial = {}): PolicyContext { - return { eventType: "PreToolUse", payload: {}, toolName: undefined, toolInput: undefined, ...overrides }; + return { + eventType: "PreToolUse", + payload: { [AGENT_PATH_KEY]: process.env.PATH }, + toolName: undefined, + toolInput: undefined, + ...overrides, + }; } const policy = BUILTIN_POLICIES.find((p) => p.name === "block-failproofai-commands")!; @@ -655,8 +668,10 @@ describe("block-failproofai-commands — the state guard", () => { // when the path is BUILT at run time the literal never appears, so there is // nothing to match. The real fix is action-gating on the resolved path, // which is not something a string check can do. + // (`~/.failproof$X` used to sit here too. It is caught now, as a variable + // spliced into a path and as one the line assigns; see settings-guard.test.ts + // and guard-npx-local-bin.test.ts.) it("does not catch a path assembled at run time", async () => { - expect(await decide("X=ai; rm -rf ~/.failproof$X")).toBe("allow"); expect(await decide('echo ~/.failproofai > /tmp/t; rm -rf "$(cat /tmp/t)"')).toBe("allow"); expect(await decide("find ~ -inum 12345 -delete")).toBe("allow"); }); @@ -673,10 +688,14 @@ describe("block-failproofai-commands — the state guard", () => { // enforcement silently; an allowlist miss denies a command the operator can // see and report. These two are misses of the second kind — a backup and a // read — and they are pinned so the next person knows they are a decision - // rather than an accident. + // rather than an accident. A `python -c` read is the second one: no + // syntactic check can prove a Python program only reads (a vetting + // exemption was bypassed with dynamic builtin lookups), so every + // interpreter program that names the state is denied. it("over-denies a tar backup and an interpreter read, which is the chosen failure", async () => { expect(await decide("tar -cf /tmp/backup.tar ~/.failproofai")).toBe("deny"); - expect(await decide("python3 -c \"print(open('/home/u/.failproofai/policies-config.json').read())\"")).toBe("deny"); + expect(await decide("python3 -c \"import os; print(open('/home/u/.failproofai/policies-config.json').read())\"")).toBe("deny"); + expect(await decide("node -e \"console.log(require('fs').readFileSync('/home/u/.failproofai/policies-config.json','utf8'))\"")).toBe("deny"); }); }); @@ -805,4 +824,210 @@ describe("block-failproofai-commands — the state guard", () => { expect(await reason("failproofai config --pause")).toMatch(/human action/); }); }); + + // Found by a full end-to-end run: an agent diagnosing Self Reports was denied + // a read-only jq and python read of self-report.json, a grep for the MCP + // server's name, and a heredoc that only wrote notes mentioning the CLI. + describe("reads and mentions are not tampering", () => { + const F = "fail" + "proofai"; + it("allows a jq whose filter has a pipe", async () => { + for (const c of [ + `jq '.categories | length' ~/.${F}/self-report.json`, + `jq -r '.enabled, .source' ~/.${F}/self-report.json`, + ]) expect(await decide(c), c).toBe("allow"); + }); + + it("allows a grep whose pattern names the CLI or the MCP server", async () => { + for (const c of [ + `grep '${F}_local' ~/.codex/config.toml`, + `grep -E '(${F}_local|kiln)' ~/.codex/config.toml`, + `grep -rn '${F} config --pause' docs/`, + `grep -r 'npm uninstall -g ${F}' docs`, + ]) expect(await decide(c), c).toBe("allow"); + // rg counts as the real tool only where PATH finds it in /usr/bin or /bin + // (a user-writable ~/.cargo/bin rg could run its arguments). + const systemRg = ["/usr/bin/rg", "/bin/rg"].some((p) => existsSync(p)); + vi.stubEnv("PATH", "/usr/bin:/bin"); + try { + expect(await decide(`rg '(${F}_local)' ~/.config`)).toBe(systemRg ? "allow" : "deny"); + } finally { + vi.unstubAllEnvs(); + } + }); + + it("allows a heredoc that only writes text mentioning the CLI", async () => { + for (const c of [ + `cat > ~/Desktop/notes.md <<'EOF'\nRun ${F} self-report sync to fix it.\n${F} config --pause is for people.\nEOF`, + `cat > ~/Desktop/n.md <<'EOF'\nnpm uninstall -g ${F}\nrm -rf ~/.${F}\nEOF`, + `cat <<-EOF > ~/Desktop/n.md\n\t${F} policies --install\n\tEOF`, + `tee ~/Desktop/n.md <<'EOF'\n${F} self-report status\nEOF`, + ]) expect(await decide(c), c).toBe("allow"); + }); + + it("still denies running the CLI, pausing and uninstalling, however the command is dressed", async () => { + for (const c of [ + `${F} self-report sync`, + `npx ${F} config --pause`, + `npx -y ${F}@latest policies --uninstall`, + `npm uninstall -g ${F}`, + `fail"proof"ai config --pause`, + `grep x f; fail\\proofai self-report sync`, + `grep -e '(x' f ; ${F} policies`, + `grep "$(${F} config --pause)" f`, + `jq -n "$(${F} config --pause)"`, + `python3 -c "print(1)" ; ${F} config --pause`, + ]) expect(await decide(c), c).toBe("deny"); + }); + + // A quoted grep/jq/cat argument is inert only while the command word is + // the real tool: a function, alias or PATH set up in the same command can + // make `grep` run its arguments. + it("treats nothing as inert when the same command can redefine the command word", async () => { + // Without this rule each is allowed (the cut hides the CLI inside a + // quoted pattern), and each runs the CLI, because the command word is not + // the real tool. + for (const c of [ + `grep() { eval "$1"; }; grep '(${F} config --pause)'`, + `function grep { eval "$1"; }; grep '(${F} config --pause)'`, + `PATH=/tmp/x grep '(${F} config --pause)' f`, + `export PATH=/tmp/x:$PATH; grep -E '(${F} config --pause)' f`, + `alias grep=eval; grep '(${F} config --pause)'`, + `jq() { eval "$1"; }; jq '(${F} config --pause)'`, + `cat() { sh; }; cat <<'EOF'\n${F} config --pause\nEOF`, + ]) expect(await decide(c), c).toBe("deny"); + }); + + // F17: a project-local `./grep` holding `eval "$1"` ran the pause CLI from + // its quoted "pattern", which the guard had cut as inert by basename. + it("treats a quoted argument as inert only for the standard tool, not a program of that name elsewhere", async () => { + for (const c of [ + `./grep '(${F} config --pause)'`, + `./grep -E '(${F} config --pause)' f`, + `/tmp/x/grep '(${F} config --pause)'`, + `bin/jq '(${F} config --pause)'`, + `~/bin/rg '(${F} config --pause)' .`, + `/usr/local/bin/grep '(${F} config --pause)' f`, + `/usr/bin/../../tmp/x/grep '(${F} config --pause)' f`, + ]) expect(await decide(c), c).toBe("deny"); + // The real tool, by name or from /usr/bin or /bin, keeps the exemption. + for (const c of [ + `grep -E '(${F}_local|kiln)' f`, + `/usr/bin/grep -E '(${F}_local|kiln)' f`, + `/bin/grep '(${F} config --pause)' docs/notes.md`, + ]) expect(await decide(c), c).toBe("allow"); + }); + + it("treats nothing as inert when PATH has a relative entry, which can find the project's own grep", async () => { + vi.stubEnv("PATH", `.:${process.env.PATH ?? "/usr/bin"}`); + try { + expect(await decide(`grep '(${F} config --pause)' f`)).toBe("deny"); + } finally { + vi.unstubAllEnvs(); + } + vi.stubEnv("PATH", `/usr/bin::/bin`); + try { + expect(await decide(`grep '(${F} config --pause)' f`)).toBe("deny"); + } finally { + vi.unstubAllEnvs(); + } + }); + + it("treats a bare tool name as the real tool only when PATH finds it in a system directory", async () => { + // A user-writable directory earlier on PATH (~/.local/bin, a package + // manager's bin) can hold a `grep` that runs its arguments. + const dir = mkdtempSync(join(tmpdir(), "fp-guard-path-")); + try { + writeFileSync(join(dir, "grep"), '#!/bin/sh\neval "$1"\n', { mode: 0o755 }); + vi.stubEnv("PATH", `${dir}:/usr/bin:/bin`); + expect(await decide(`grep '(${F} config --pause)' f`)).toBe("deny"); + vi.stubEnv("PATH", `/usr/bin:/bin:${dir}`); + expect(await decide(`grep -E '(${F}_local|kiln)' f`)).toBe("allow"); + } finally { + vi.unstubAllEnvs(); + rmSync(dir, { recursive: true, force: true }); + } + }); + + it("sees a PATH assignment the shell assembles from quoted or escaped pieces", async () => { + for (const c of [ + `PA""TH=/tmp/x grep '(${F} config --pause)' f`, + `PA''TH=/tmp/x grep '(${F} config --pause)' f`, + `P\\ATH=/tmp/x grep '(${F} config --pause)' f`, + `"PATH"=/tmp/x grep '(${F} config --pause)' f`, + `export PA""TH=/tmp/x; grep '(${F} config --pause)' f`, + `BASH_""ENV=/tmp/x grep '(${F} config --pause)' f`, + ]) expect(await decide(c), c).toBe("deny"); + }); + + it("still runs a heredoc's body when it can execute", async () => { + for (const c of [ + `sh <<'EOF'\n${F} config --pause\nEOF`, + `bash -s <<'EOF'\n${F} self-report disable\nEOF`, + `cat <<'EOF' | sh\n${F} config --pause\nEOF`, + `cat > /tmp/p.sh <<'EOF'\n${F} config --pause\nEOF\nsh /tmp/p.sh`, + `cat <<'EOF' > /tmp/x\n${F} config --pause\nEOF\nchmod +x /tmp/x && /tmp/x`, + // An unquoted delimiter expands $(...) and backticks while writing. + `cat > n < n < n <<'EOF'\nx\nEOF\n${F} config --pause`, + `cat > f <<'EOF' ; ${F} config --pause\nbody\nEOF`, + ]) expect(await decide(c), c).toBe("deny"); + }); + + // Found while fixing the #1105 bot review: taking an inert heredoc's body + // out took its delimiter line too, so the walk read every line after it + // as more of the heredoc and judged none of them. + it("still judges the lines after a heredoc whose body is taken out", async () => { + for (const c of [ + `cat > notes.md <<'EOF'\nhello\nEOF\nrm -rf ~/.${F}\n`, + `tee notes.md < notes.md <<-'EOF'\n\thello\n\tEOF\nrm -rf ~/.${F}`, + `cat > notes.md <<'EOF'\nhello\nEOF\nrm -f ~/.codex/hooks.json`, + ]) expect(await decide(c), c).toBe("deny"); + expect(await decide(`cat > notes.md <<'EOF'\nhello\nEOF\nls`)).toBe("allow"); + }); + + it("still denies every write, move, delete, chmod and redirect into the state", async () => { + for (const c of [ + `rm ~/.${F}/self-report.json`, + `echo '{}' > ~/.${F}/self-report.json`, + `echo x >> ~/.${F}/policies-config.json`, + `chmod 000 ~/.${F}/policies-config.json`, + `mv ~/.${F} /tmp/x`, + `jq '.enabled=false' ~/.${F}/self-report.json > /tmp/t && mv /tmp/t ~/.${F}/self-report.json`, + `jq '.' ~/.${F}/a | tee ~/.${F}/b`, + `grep x ~/.${F}/f > ~/.${F}/g`, + `yq -i '.a=1' ~/.${F}/x.yaml`, + `tee ~/.${F}/self-report.json <<'EOF'\n{}\nEOF`, + `cat > ~/.${F}/self-report.json <<'EOF'\n{}\nEOF`, + `python3 -c "import json; json.load(open('/x/.${F}/a'))" > ~/.${F}/b`, + ]) expect(await denialIsAboutState(c), c).toBe(true); + }); + + // Review 4722003642: the `python -c` read exemption is gone. Every one of + // these names the state from a Python program and is denied, the + // dynamic-builtin escapes that walked past the old vetting included. + it("denies every python -c that names the state, reads included", async () => { + for (const c of [ + `python3 -c 'import sys; sys._getframe().f_builtins["o"+"pen"](sys.argv[1], "w")' ~/.${F}/self-report.json`, + `python3 -c 'import sys; b=sys._getframe().f_builtins; b["op"+"en"](sys.argv[1],"w")' ~/.${F}/policies-config.json`, + `python3 -c 'import json; json.loads.__globals__' ~/.${F}/a`, + `python3 -c "import json; print(json.load(open('/home/u/.${F}/self-report.json'))['enabled'])"`, + `python3 -c 'import json,sys; d=json.load(open(sys.argv[1])); print(d["source"])' ~/.${F}/self-report.json`, + `python3 -c "import json; print(open('/home/u/.${F}/self-report.json', 'r', encoding='utf-8').read())"`, + `python3 -c "import os; os.remove('/home/u/.${F}/self-report.json')"`, + `python3 -c "open('/home/u/.${F}/self-report.json','w').write('{}')"`, + `python3 -c "import json;o=open;o('/x/.${F}/a','w')"`, + `python3 -c "open('/x/.${F}/a', mode='w')"`, + `python3 -c "open('/x/.${F}/a', 'r+')"`, + `python3 -c "import os; print(open('/x/.${F}/a').read())"`, + `python3 -c "import json; getattr(json, 'load')(open('/x/.${F}/a'))"`, + `python3 -c "__import__('os').remove('/x/.${F}/a')"`, + `python3 -c "import json; print(open('/x/.${F}/a').read())" -c "x"; rm ~/.${F}/a`, + `python3 -c "import shutil; shutil.rmtree('/x/.${F}')"`, + `python3 -c "import json; exec('\\x6f')" ~/.${F}/a`, + ]) expect(await decide(c), c).toBe("deny"); + }); + }); }); diff --git a/__tests__/hooks/two-tier/runner.ts b/__tests__/hooks/two-tier/runner.ts index e3342f117..3224766ef 100644 --- a/__tests__/hooks/two-tier/runner.ts +++ b/__tests__/hooks/two-tier/runner.ts @@ -52,6 +52,15 @@ export function enterSandbox(): CorpusSandbox { const packs = join(root, "packs"); mkdirSync(fpHome, { recursive: true }); mkdirSync(packs, { recursive: true }); + // Self Reports off. The golden was recorded before Self Reports existed, and + // on by default it now answers Factory's SessionStart with its instructions + // and adds a one-time hint after a failed tool call: intended, and pinned + // in __tests__/hooks/self-report-hint.test.ts, not here, where the claim is + // only that Jev unconfigured changes nothing. + writeFileSync( + join(fpHome, "self-report.json"), + JSON.stringify({ version: 1, enabled: false, source: "local", categories: [], guidance: null, mcp: { port: 4319, url: "http://127.0.0.1:4319/mcp" }, updatedAt: "" }), + ); process.env.HOME = home; process.env.FAILPROOFAI_HOME = fpHome; process.env.FAILPROOFAI_PACK_DIR = packs; diff --git a/__tests__/hooks/typed-shell-input-handler.test.ts b/__tests__/hooks/typed-shell-input-handler.test.ts new file mode 100644 index 000000000..59b7c29ad --- /dev/null +++ b/__tests__/hooks/typed-shell-input-handler.test.ts @@ -0,0 +1,137 @@ +// @vitest-environment node +// +// Whether the handler moves typed shell text into `command` and registers the +// refusal guard. The text's reading is covered in typed-shell-input.test.ts. +import { describe, it, expect, vi, beforeEach, afterAll } from "vitest"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +const scratch = mkdtempSync(join(tmpdir(), "fp-typed-input-")); +process.env.FAILPROOFAI_HOME = scratch; + +vi.mock("../../src/hooks/policy-registry", async (importOriginal) => ({ + ...(await importOriginal()), + clearPolicies: vi.fn(), + registerPolicy: vi.fn(), + getPoliciesForEvent: vi.fn(() => []), +})); +vi.mock("../../src/hooks/custom-hooks-loader", () => ({ + loadAllCustomHooks: vi.fn(async () => ({ hooks: [], conventionSources: [] })), +})); +vi.mock("../../src/hooks/cloud-managed-policies", async (importOriginal) => ({ + ...(await importOriginal()), + readActiveCloudManagedPolicies: vi.fn(() => []), + readCloudJevMode: vi.fn(() => null), + readCloudJevState: vi.fn(() => ({ jevMode: null, deployment: null, errors: [] })), + readCloudAuthorityInputs: vi.fn(() => []), +})); +vi.mock("../../src/hooks/session-pause", async (importOriginal) => ({ + ...(await importOriginal()), + readActivePause: vi.fn(() => null), +})); +vi.mock("../../src/hooks/hook-activity-store", () => ({ persistHookActivity: vi.fn() })); +vi.mock("../../src/hooks/policy-evaluator", () => ({ + evaluatePolicies: vi.fn(() => ({ exitCode: 0, stdout: "", stderr: "", policyName: null, reason: null, decision: "allow" })), +})); +vi.mock("../../src/hooks/hook-telemetry", () => ({ + trackHookEvent: vi.fn(() => Promise.resolve()), + flushHookTelemetry: vi.fn(() => Promise.resolve()), +})); +vi.mock("../../lib/telemetry-id", () => ({ getInstanceId: vi.fn(() => "test-id") })); +vi.mock("../../src/hooks/hook-logger", () => ({ hookLogInfo: vi.fn(), hookLogWarn: vi.fn(), hookLogError: vi.fn() })); +vi.mock("../../src/hooks/untraced-note", () => ({ noteUntracedAgent: vi.fn(() => false) })); +vi.mock("../../src/hooks/pack-manifest", () => ({ + readInstalledPacks: vi.fn(() => ({ packs: [], errors: [] })), + hasInstalledPacks: vi.fn(() => false), + hasInstalledRegexPacks: vi.fn(() => false), +})); + +import { evaluateHookEvent } from "../../src/hooks/handler"; +import { TYPED_INPUT_GUARD_NAME } from "../../src/hooks/typed-shell-input"; +import { CODEX_SESSION_GUARD_NAME } from "../../src/hooks/codex-interactive-session"; +import { readActiveCloudManagedPolicies } from "../../src/hooks/cloud-managed-policies"; +import { readActivePause } from "../../src/hooks/session-pause"; +import { registerPolicy } from "../../src/hooks/policy-registry"; +import { evaluatePolicies } from "../../src/hooks/policy-evaluator"; + +const codex = (tool_name: string, tool_input: Record) => + JSON.stringify({ session_id: "s1", cwd: "/tmp/p", hook_event_name: "PreToolUse", tool_name, tool_input }); +const registered = () => vi.mocked(registerPolicy).mock.calls.some(([name]) => name === TYPED_INPUT_GUARD_NAME); +const evaluatedInput = () => (vi.mocked(evaluatePolicies).mock.calls[0]?.[1] as Record)?.tool_input as Record; +const CLOUD = { id: "org", version: 1, sha256: "a".repeat(64), path: "/x.mjs", deployment: 1 }; + +beforeEach(() => { + vi.clearAllMocks(); + vi.mocked(readActivePause).mockReturnValue(null); + vi.mocked(readActiveCloudManagedPolicies).mockReturnValue([]); +}); + +afterAll(() => { + rmSync(scratch, { recursive: true, force: true }); +}); + +describe("handler: text typed into a running shell", () => { + it("hands Codex write_stdin's chars to the shell policies as the command", async () => { + await evaluateHookEvent("pre_tool_use", "codex", codex("write_stdin", { session_id: 7, chars: "rm -rf ~/.failproofai\n" })); + expect(evaluatedInput()).toMatchObject({ command: "rm -rf ~/.failproofai", chars: "rm -rf ~/.failproofai\n" }); + expect(registered()).toBe(false); + }); + + it("hands Copilot write_bash's input to the shell policies as the command", async () => { + await evaluateHookEvent( + "PreToolUse", + "copilot", + JSON.stringify({ session_id: "s1", cwd: "/tmp/p", tool_name: "write_bash", tool_input: { shellId: "a", input: "sudo ls\n" } }), + ); + expect(evaluatedInput()).toMatchObject({ command: "sudo ls" }); + }); + + it("registers the guard for a partial line", async () => { + await evaluateHookEvent("pre_tool_use", "codex", codex("write_stdin", { session_id: 7, chars: "rm -rf ~/.fail" })); + expect(registered()).toBe(true); + }); + + it("does not register it for an empty poll or an ordinary command", async () => { + await evaluateHookEvent("pre_tool_use", "codex", codex("write_stdin", { session_id: 7, chars: "" })); + await evaluateHookEvent("pre_tool_use", "codex", codex("Bash", { command: "ls" })); + expect(registered()).toBe(false); + }); + + it("a pause lifts it unless an enforcing Cloud policy is deployed", async () => { + vi.mocked(readActivePause).mockReturnValue({ sessionId: "s1" } as never); + await evaluateHookEvent("pre_tool_use", "codex", codex("write_stdin", { session_id: 7, chars: "x" })); + expect(registered()).toBe(false); + vi.mocked(readActiveCloudManagedPolicies).mockReturnValue([CLOUD] as never); + await evaluateHookEvent("pre_tool_use", "codex", codex("write_stdin", { session_id: 7, chars: "x" })); + expect(registered()).toBe(true); + }); +}); + +describe("handler: a Codex command that opens an interactive session", () => { + const sessionGuard = () => vi.mocked(registerPolicy).mock.calls.some(([name]) => name === CODEX_SESSION_GUARD_NAME); + + it("registers the guard for Codex's bash -i, the one call Codex hooks for a kept-open shell", async () => { + await evaluateHookEvent("pre_tool_use", "codex", codex("Bash", { command: "bash -i" })); + expect(sessionGuard()).toBe(true); + }); + + it("does not register it for a one-shot command, or on another CLI", async () => { + await evaluateHookEvent("pre_tool_use", "codex", codex("Bash", { command: "npm test" })); + await evaluateHookEvent( + "PreToolUse", + "claude", + JSON.stringify({ session_id: "s1", cwd: "/tmp/p", tool_name: "Bash", tool_input: { command: "bash -i" } }), + ); + expect(sessionGuard()).toBe(false); + }); + + it("is lifted by a pause unless an enforcing Cloud policy is deployed", async () => { + vi.mocked(readActivePause).mockReturnValue({ sessionId: "s1" } as never); + await evaluateHookEvent("pre_tool_use", "codex", codex("Bash", { command: "bash -i" })); + expect(sessionGuard()).toBe(false); + vi.mocked(readActiveCloudManagedPolicies).mockReturnValue([CLOUD] as never); + await evaluateHookEvent("pre_tool_use", "codex", codex("Bash", { command: "bash -i" })); + expect(sessionGuard()).toBe(true); + }); +}); diff --git a/__tests__/hooks/typed-shell-input.test.ts b/__tests__/hooks/typed-shell-input.test.ts new file mode 100644 index 000000000..a0f7995b1 --- /dev/null +++ b/__tests__/hooks/typed-shell-input.test.ts @@ -0,0 +1,119 @@ +// @vitest-environment node +// +// Text an agent types into a running shell (FailproofAI/agenteye#1898): Codex's +// `write_stdin` sends it as `chars`, Copilot's `write_bash` as `input`, and every +// shell policy reads only `command`. Payload shapes are taken from the agents' +// own tool schemas: codex-cli 0.172 and Copilot CLI 1.0.114. +import { describe, it, expect } from "vitest"; +import { readTypedText, typedShellInput, typedInputGuardFor, typedInputGuardActive } from "../../src/hooks/typed-shell-input"; +import type { PolicyContext } from "../../src/hooks/policy-types"; + +describe("readTypedText", () => { + it.each([ + ["one line", "rm -rf ~/.failproofai\n", "rm -rf ~/.failproofai"], + ["several lines", "ls -la\nrm -rf x\n", "ls -la\nrm -rf x"], + ["a carriage return as Enter", "ls\r", "ls"], + ["CRLF line ends", "a\r\nb\r\n", "a\nb"], + ["a heredoc sent whole", "cat > notes <<'EOF'\nline\nEOF\n", "cat > notes <<'EOF'\nline\nEOF"], + ["an escaped backslash at the end", "echo a\\\\\n", "echo a\\\\"], + ["a quote closed on the same line", "echo 'it''s'\n", "echo 'it''s'"], + ["a dollar inside single quotes", "echo '$HOME'\n", "echo '$HOME'"], + ["an environment assignment for one command", "NODE_ENV=test npm test\n", "NODE_ENV=test npm test"], + ["a comment with a quote in it", "ls # don't\n", "ls # don't"], + ])("reads %s as the lines it runs", (_label, text, command) => { + expect(readTypedText(text)).toEqual({ kind: "command", command }); + }); + + it.each([ + ["an empty write, which polls for output", ""], + ["Ctrl-C", "\u0003"], + ["Ctrl-D", "\u0004"], + ["an arrow key and Enter", "\u001b[A\n"], + ["Enter alone", "\n"], + // Every write it accepts ends its line and carries no editing keys, so the + // shell's kill buffer only ever holds text that was already judged. + ["Ctrl-Y alone", "\u0019\n"], + ])("gives nothing to judge for %s", (_label, text) => { + expect(readTypedText(text)).toEqual({ kind: "command", command: "" }); + }); + + it.each([ + ["a partial line, which a later write would finish", "rm -rf ~/.fail"], + ["text after the last line end", "ls\nrm -rf ~/.fail"], + ["Tab completion", "rm -rf ~/.failpr\t\n"], + ["Ctrl-W", "rm -rf ~/x\u0017~/.failproofai\n"], + ["a cursor key mid-line", "rm -rf ~/.f\u001b[Dx\n"], + ["a trailing backslash, continued in the next write", "cp source \\\n"], + ["an unclosed quote", "cp source 'ho\n"], + ["a heredoc whose closing line has not been sent", "cat > notes < { + expect(readTypedText(text).kind).toBe("unreadable"); + }); +}); + +describe("typedShellInput", () => { + it("reads Codex write_stdin's chars", () => { + expect(typedShellInput("codex", "write_stdin", "Bash", { session_id: 1, chars: "rm -rf x\n" })).toEqual({ + kind: "command", + command: "rm -rf x", + }); + }); + + it.each(["write_bash", "write_powershell"])("reads Copilot %s's input", (tool) => { + expect(typedShellInput("copilot", tool, "Bash", { shellId: "s1", input: "rm -rf x\n", delay: 1 })).toEqual({ + kind: "command", + command: "rm -rf x", + }); + }); + + it("knows a typing call by its shape when the name already arrives as Bash", () => { + expect(typedShellInput("copilot", "Bash", "Bash", { shellId: "s1", input: "rm -rf x\n" })?.kind).toBe("command"); + expect(typedShellInput("codex", "Bash", "Bash", { session_id: 3, chars: "rm -rf x" })?.kind).toBe("unreadable"); + }); + + it.each([ + ["a Codex shell command", "codex", "Bash", { command: "ls" }], + ["Copilot's read_bash, which types nothing", "copilot", "read_bash", { shellId: "s1", delay: 1 }], + ["Copilot's bash with a shell id", "copilot", "bash", { command: "ls", shellId: "s1" }], + ["another CLI's tool with an input field", "claude", "Bash", { input: "x", shellId: "s" }], + ] as const)("leaves %s alone", (_label, cli, raw, input) => { + expect(typedShellInput(cli, raw, "Bash", input)).toBeUndefined(); + }); + + it("leaves a call that is not a shell call alone", () => { + expect(typedShellInput("codex", "write_stdin", "Edit", { chars: "x" })).toBeUndefined(); + }); +}); + +describe("the guard", () => { + const ctx = (eventType: string): PolicyContext => ({ eventType, payload: {}, toolName: "Bash", toolInput: {} } as PolicyContext); + + it("denies on PreToolUse and says why", () => { + const result = typedInputGuardFor("it does not end its line")(ctx("PreToolUse")); + expect(result.decision).toBe("deny"); + expect(result.reason).toContain("it does not end its line"); + }); + + it("allows on any other event", () => { + expect(typedInputGuardFor("x")(ctx("PostToolUse")).decision).toBe("allow"); + }); + + it("is lifted by a pause unless an enforcing Cloud policy is deployed", () => { + expect(typedInputGuardActive(false, [])).toBe(true); + expect(typedInputGuardActive(true, [])).toBe(false); + expect(typedInputGuardActive(true, [{ effect: "observe" }])).toBe(false); + expect(typedInputGuardActive(true, [{}])).toBe(true); + }); +}); diff --git a/__tests__/hooks/uninstall-cli.test.ts b/__tests__/hooks/uninstall-cli.test.ts index 7d9b1dcaa..01c1d845c 100644 --- a/__tests__/hooks/uninstall-cli.test.ts +++ b/__tests__/hooks/uninstall-cli.test.ts @@ -38,6 +38,12 @@ vi.mock("../../src/hooks/manager", () => ({ }), })); +// Self Reports MCP removal reads agent configs through the real integrations; +// its own behaviour is covered in self-report-install.test.ts. +vi.mock("../../src/hooks/self-report-install", () => ({ + removeSelfReportMcp: vi.fn(() => []), + selfReportRegistrationStatus: vi.fn(() => []), +})); vi.mock("../../src/hooks/agent-skill", () => ({ installedAgentSkillDirs: () => skillDirs, removeAgentSkill: vi.fn(() => { @@ -566,3 +572,94 @@ describe("hooks/uninstall-cli — the agent selection is not uninstall's to chan }); }); }); + +describe("hooks/uninstall-cli — Self Reports MCP server", () => { + it("an orphan MCP registration alone is something to uninstall, named in the plan", async () => { + installedClis = []; + configured = false; + rmSync(servicePath, { force: true }); + const mod = await import("../../src/hooks/self-report-install"); + const orphan = { agent: "copilot", path: "/x/.copilot/mcp-config.json", hooked: false, registered: true, transport: "stdio", endpoint: "/x/failproofai", conflict: false } as const; + vi.mocked(mod.selfReportRegistrationStatus).mockReturnValue([ + orphan, + { ...orphan, agent: "claude", path: "/x/.claude.json", registered: false, transport: null, endpoint: null }, + ]); + const { runUninstallCommand } = await import("../../src/hooks/uninstall-cli"); + try { + const dry = await runUninstallCommand({ dryRun: true }); + expect(dry.lines.join("\n")).not.toContain("Nothing to uninstall"); + expect(dry.lines.join("\n")).toContain("the Self Reports MCP server from 1 agent config"); + expect(vi.mocked(mod.removeSelfReportMcp)).not.toHaveBeenCalled(); + + vi.mocked(mod.removeSelfReportMcp).mockReturnValueOnce([ + { agent: "copilot", path: orphan.path, action: "removed", transport: "stdio", status: "ok" }, + ]); + const res = await runUninstallCommand({ yes: true }); + expect(res.exitCode).toBe(0); + expect(res.lines.join("\n")).toContain("Removed the Self Reports MCP server from 1 agent config."); + } finally { + vi.mocked(mod.selfReportRegistrationStatus).mockReturnValue([]); + } + }); + + it("an agent config that cannot be inspected is not \"nothing to uninstall\": the cleanup is tried and reported incomplete", async () => { + installedClis = []; + configured = false; + rmSync(servicePath, { force: true }); + const mod = await import("../../src/hooks/self-report-install"); + const broken = { + agent: "copilot", path: "/x/.copilot/mcp-config.json", hooked: false, registered: false, + transport: null, endpoint: null, conflict: false, error: "Unexpected token } in JSON", + } as const; + vi.mocked(mod.selfReportRegistrationStatus).mockReturnValue([broken]); + const { runUninstallCommand } = await import("../../src/hooks/uninstall-cli"); + try { + const dry = await runUninstallCommand({ dryRun: true }); + const plan = dry.lines.join("\n"); + expect(plan).not.toContain("Nothing to uninstall"); + expect(plan).toContain("could not be read"); + expect(plan).toContain(broken.path); + + vi.mocked(mod.removeSelfReportMcp).mockReturnValueOnce([ + { agent: "copilot", path: broken.path, action: "skipped", transport: null, status: "error", detail: broken.error }, + ]); + const res = await runUninstallCommand({ yes: true }); + expect(res.exitCode).toBe(1); + expect(res.lines.join("\n")).toContain(`Could not remove the Self Reports MCP server from ${broken.path}`); + } finally { + vi.mocked(mod.selfReportRegistrationStatus).mockReturnValue([]); + } + }); + + it("with every agent config genuinely absent, there is still nothing to uninstall", async () => { + installedClis = []; + configured = false; + rmSync(servicePath, { force: true }); + const mod = await import("../../src/hooks/self-report-install"); + vi.mocked(mod.selfReportRegistrationStatus).mockReturnValue([ + { agent: "copilot", path: "/x/.copilot/mcp-config.json", hooked: false, registered: false, transport: null, endpoint: null, conflict: false }, + ]); + const { runUninstallCommand } = await import("../../src/hooks/uninstall-cli"); + try { + const res = await runUninstallCommand({ yes: true }); + expect(res.exitCode).toBe(0); + expect(res.lines.join("\n")).toContain("Nothing to uninstall"); + } finally { + vi.mocked(mod.selfReportRegistrationStatus).mockReturnValue([]); + } + }); + + it("removes failproofai's MCP server from every agent and says so", async () => { + const mod = await import("../../src/hooks/self-report-install"); + vi.mocked(mod.removeSelfReportMcp).mockReturnValueOnce([ + { agent: "claude", path: "/x/.claude.json", action: "removed", transport: "http", status: "ok" }, + { agent: "codex", path: "/x/.codex/config.toml", action: "unchanged", transport: null, status: "ok" }, + ]); + const { runUninstallCommand } = await import("../../src/hooks/uninstall-cli"); + const res = await runUninstallCommand({ yes: true, cwd: join(home, "project") }); + + expect(res.exitCode).toBe(0); + expect(vi.mocked(mod.removeSelfReportMcp)).toHaveBeenCalledWith({ quiet: true }); + expect(res.lines.join("\n")).toContain("Removed the Self Reports MCP server from 1 agent config."); + }); +}); diff --git a/__tests__/hooks/update-run.test.ts b/__tests__/hooks/update-run.test.ts index 66b8c2fc4..9e727f63d 100644 --- a/__tests__/hooks/update-run.test.ts +++ b/__tests__/hooks/update-run.test.ts @@ -4,9 +4,9 @@ * instead of leaving that to a `failproofai update` nobody knew to run. */ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { mkdtempSync, readFileSync, rmSync, statSync } from "node:fs"; +import { mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; -import { join } from "node:path"; +import { dirname, join } from "node:path"; const svc = vi.hoisted(() => ({ isDaemonSupportedPlatform: vi.fn(() => true), @@ -42,6 +42,7 @@ vi.mock("../../src/hooks/codex-system-hooks", async (importOriginal) => ({ import { markUpdated, + readGatewayReport, readUpdatedVersion, restartNewlyPlugged, runUpdateSteps, @@ -95,7 +96,7 @@ describe("the version marker", () => { describe("runUpdateSteps as config runs it (no layout, no daemon, restart)", () => { const AS_CONFIG = { layout: false, daemon: false, restart: true } as const; - it("restarts running gateways onto the plugin on disk, and says so", async () => { + it("restarts running gateways onto the plugin on disk, printing nothing routine but keeping it for status", async () => { hermesWith("current"); gateways.restartOpenClawGateways.mockReturnValue([{ host: "openclaw", profile: "default", status: "restarting" }]); const run = await runUpdateSteps(AS_CONFIG); @@ -103,12 +104,26 @@ describe("runUpdateSteps as config runs it (no layout, no daemon, restart)", () expect(run.changed).toBe(true); expect(gateways.restartHermesGateway).toHaveBeenCalledTimes(1); expect(gateways.restartOpenClawGateways).toHaveBeenCalledTimes(1); - expect(run.lines).toContain(" hermes/default already current, gateway restarting"); - expect(run.lines).toContain(" openclaw/default gateway restarting"); + expect(run.lines.join("\n")).not.toMatch(/Hermes|OpenClaw|gateway restarting|already current/); + expect(readGatewayReport()?.rows).toEqual(["hermes/default already current, gateway restarting", "openclaw/default gateway restarting"]); // Setup already brought the daemon to this version. expect(svc.refreshDaemonToCliVersion).not.toHaveBeenCalled(); }); + it("still prints a gateway the user has to restart by hand", async () => { + hermesWith("current"); + gateways.restartHermesGateway.mockReturnValueOnce({ host: "hermes", profile: "default", status: "not-supervised" }); + gateways.restartOpenClawGateways.mockReturnValue([ + { host: "openclaw", profile: "default", status: "restarting" }, + { host: "openclaw", profile: "work", status: "failed" }, + ]); + const run = await runUpdateSteps(AS_CONFIG); + const text = run.lines.join("\n"); + expect(text).toContain("Hermes:"); + expect(text).toContain("OpenClaw:"); + expect(gateways.openclawRestartLines).toHaveBeenCalledWith([{ host: "openclaw", profile: "work", status: "failed" }]); + }); + it("touches no gateway when the daemon is not running", async () => { hermesWith("current"); svc.daemonServiceStatus.mockReturnValue("stopped"); @@ -124,6 +139,35 @@ describe("runUpdateSteps as config runs it (no layout, no daemon, restart)", () const run = await runUpdateSteps(AS_CONFIG); expect(run).toMatchObject({ ok: true, changed: false, lines: [] }); }); + + // An upgrade from a version that registered the MCP server in Hermes and + // OpenClaw: those entries come out before any gateway restarts, so no + // restarted gateway loads them again. The user's own servers stay. + it("takes out Hermes' and OpenClaw's old Self Reports MCP entries before restarting their gateways", async () => { + const hermesCfg = join(home, ".hermes", "config.yaml"); + const openclawCfg = join(home, ".openclaw", "openclaw.json"); + mkdirSync(dirname(hermesCfg), { recursive: true }); + mkdirSync(dirname(openclawCfg), { recursive: true }); + const cli = "/usr/local/bin/failproofai"; + writeFileSync(hermesCfg, `model: x\nmcp_servers:\n failproofai_local:\n url: http://127.0.0.1:4319/mcp?agent=hermes\n mine:\n command: node\n`); + writeFileSync( + openclawCfg, + JSON.stringify({ mcp: { servers: { failproofai_local: { command: cli, args: ["mcp", "--agent", "openclaw"] }, mine: { command: "node" } } } }), + ); + const seenAtRestart: string[] = []; + hermes.runHermesUpdateMigration.mockImplementation(async (deps: { restartGateway?: (p: unknown) => unknown }) => { + seenAtRestart.push(readFileSync(hermesCfg, "utf8"), readFileSync(openclawCfg, "utf8")); + deps.restartGateway?.({ name: "default", home: join(home, ".hermes") }); + return { ok: true, lines: [], profiles: [{ name: "default", status: "current" }] }; + }); + await runUpdateSteps(AS_CONFIG); + expect(gateways.restartHermesGateway).toHaveBeenCalledTimes(1); + expect(seenAtRestart.join("\n")).not.toContain("failproofai_local"); + expect(readFileSync(hermesCfg, "utf8")).toContain("mine:"); + expect((JSON.parse(readFileSync(openclawCfg, "utf8")) as { mcp: { servers: Record } }).mcp.servers).toEqual({ + mine: { command: "node" }, + }); + }); }); describe("runUpdateSteps as update runs it", () => { diff --git a/__tests__/lib/codex-code-mode.test.ts b/__tests__/lib/codex-code-mode.test.ts new file mode 100644 index 000000000..3be465e3c --- /dev/null +++ b/__tests__/lib/codex-code-mode.test.ts @@ -0,0 +1,113 @@ +// @vitest-environment node +import { describe, it, expect } from "vitest"; +import { extractCodeModeCalls, patchedFiles } from "@/lib/codex-code-mode"; + +describe("lib/codex-code-mode: extractCodeModeCalls", () => { + it("reads an exec_command call with unquoted and quoted keys, as Codex 0.172 writes it", () => { + const code = + 'const r = await tools.exec_command({cmd:"pwd && rg --files -g \'AGENTS.md\'","workdir":"/home/u/proj","yield_time_ms":10000,"max_output_tokens":2000}); text(r.output);\n'; + expect(extractCodeModeCalls(code)).toEqual([ + { + name: "exec_command", + arg: { cmd: "pwd && rg --files -g 'AGENTS.md'", workdir: "/home/u/proj", yield_time_ms: 10000, max_output_tokens: 2000 }, + partial: false, + }, + ]); + }); + + it("decodes escapes in the command", () => { + const [call] = extractCodeModeCalls('tools.exec_command({cmd:"echo \\"a\\tb\\"\\nls \\u0041"})'); + expect(call.arg).toEqual({ cmd: 'echo "a\tb"\nls A' }); + }); + + it("reads write_stdin's session id and typed characters", () => { + const [call] = extractCodeModeCalls('const r = await tools.write_stdin({session_id:92857,chars:"rm -rf x\\n",yield_time_ms:1000});'); + expect(call).toEqual({ name: "write_stdin", arg: { session_id: 92857, chars: "rm -rf x\n", yield_time_ms: 1000 }, partial: false }); + }); + + it("returns every call site in source order", () => { + const code = [ + 'const a = await tools.exec_command({cmd:"git status"});', + 'const b = await tools.exec_command({cmd:"git diff --stat", workdir:"/w"});', + 'await tools.update_plan({plan:[{step:"x",status:"done"}]});', + ].join("\n"); + expect(extractCodeModeCalls(code).map((c) => [c.name, c.arg])).toEqual([ + ["exec_command", { cmd: "git status" }], + ["exec_command", { cmd: "git diff --stat", workdir: "/w" }], + ["update_plan", { plan: [{ step: "x", status: "done" }] }], + ]); + }); + + it("leaves a command built from a variable unread, and says so", () => { + const code = 'const jobs = [{cmd:"cargo test"}];\nfor (const j of jobs) { await tools.exec_command({cmd: j.cmd, workdir: "/w"}); }'; + expect(extractCodeModeCalls(code)).toEqual([{ name: "exec_command", arg: { workdir: "/w" }, partial: true }]); + }); + + it("treats shorthand, spread and computed keys as unread", () => { + expect(extractCodeModeCalls("tools.exec_command({cmd})")[0]).toEqual({ name: "exec_command", arg: {}, partial: true }); + expect(extractCodeModeCalls('tools.exec_command({...opts, workdir:"/w"})')[0]).toEqual({ name: "exec_command", arg: { workdir: "/w" }, partial: true }); + expect(extractCodeModeCalls('tools.exec_command({[k]:"ls"})')[0]).toEqual({ name: "exec_command", arg: {}, partial: true }); + expect(extractCodeModeCalls("tools.exec_command(opts)")[0]).toEqual({ name: "exec_command", arg: undefined, partial: true }); + }); + + it("keeps a template literal's text, substitutions as written", () => { + const code = "tools.apply_patch(`*** Begin Patch\\n*** Add File: ${root}/a.txt\\n+hi\\n*** End Patch`)"; + expect(extractCodeModeCalls(code)).toEqual([ + { name: "apply_patch", arg: "*** Begin Patch\n*** Add File: ${root}/a.txt\n+hi\n*** End Patch", partial: true }, + ]); + }); + + it("finds a call made inside a template substitution", () => { + const calls = extractCodeModeCalls('text(`out: ${(await tools.exec_command({cmd:"date"})).output}`)'); + expect(calls).toEqual([{ name: "exec_command", arg: { cmd: "date" }, partial: false }]); + }); + + it("never reads text inside a string, a comment or a regex as a call", () => { + const code = [ + 'const note = "tools.exec_command({cmd:\\"rm -rf /\\"})";', + "// tools.exec_command({cmd:\"rm -rf /\"})", + "/* tools.exec_command({cmd:\"rm -rf /\"}) */", + "const re = /tools.exec_command\\(\"/;", + "const t = `tools.exec_command({cmd:\"x\"})`;", + "const hits = ALL_TOOLS.filter(x => /exec_command|get_goal/.test(x.name));", + 'await tools.exec_command({cmd:"ls"});', + ].join("\n"); + expect(extractCodeModeCalls(code)).toEqual([{ name: "exec_command", arg: { cmd: "ls" }, partial: false }]); + }); + + it("does not take x.tools.y() or mytools.y() for a tool call", () => { + expect(extractCodeModeCalls('ctx.tools.exec_command({cmd:"a"}); mytools.exec_command({cmd:"b"});')).toEqual([]); + }); + + it("returns nothing for a snippet that calls no tool", () => { + expect(extractCodeModeCalls("const hits = ALL_TOOLS.filter(x => /search/i.test(x.name)); text(hits);")).toEqual([]); + }); + + it("survives truncated and malformed input", () => { + for (const code of ['tools.exec_command({cmd:"unterminated', "tools.exec_command({cmd:", "tools.exec_command(", "`${", "/*", '"', "tools."]) { + expect(() => extractCodeModeCalls(code)).not.toThrow(); + } + expect(extractCodeModeCalls('tools.exec_command({cmd:"unterminated')).toEqual([ + { name: "exec_command", arg: undefined, partial: true }, + ]); + }); + + it("stays linear on a large snippet", () => { + const code = 'await tools.exec_command({cmd:"' + "a".repeat(500_000) + '"});' + ' "x"'.repeat(50_000) + " `${".repeat(5_000); + const t = performance.now(); + const calls = extractCodeModeCalls(code); + expect(performance.now() - t).toBeLessThan(2000); + expect(calls).toHaveLength(1); + }); +}); + +describe("lib/codex-code-mode: patchedFiles", () => { + it("lists every Add/Update/Delete target in order", () => { + const patch = "*** Begin Patch\n*** Update File: src/a.ts\n@@\n-x\n+y\n*** Add File: /abs/b.md\n+hi\n*** Delete File: c.txt\n*** End Patch"; + expect(patchedFiles(patch)).toEqual(["src/a.ts", "/abs/b.md", "c.txt"]); + }); + + it("returns an empty list for text that is not a patch", () => { + expect(patchedFiles("hello")).toEqual([]); + }); +}); diff --git a/__tests__/lib/codex-sessions.test.ts b/__tests__/lib/codex-sessions.test.ts index 1a5175614..9a45121d2 100644 --- a/__tests__/lib/codex-sessions.test.ts +++ b/__tests__/lib/codex-sessions.test.ts @@ -189,6 +189,76 @@ describe("lib/codex-sessions: parseCodexLog", () => { expect(entries).toHaveLength(1); expect(rawLines).toHaveLength(1); }); + + // Codex code mode (0.146+; every tool call on 0.172) writes `custom_tool_call` + // records. Before these were parsed, audit counted zero tool calls for them. + describe("code mode (custom_tool_call)", () => { + const exec = (callId: string, input: string, ts = "2026-11-29T18:15:42.000Z") => + line({ timestamp: ts, type: "response_item", payload: { type: "custom_tool_call", status: "completed", call_id: callId, name: "exec", input } }); + const out = (callId: string, texts: string[], ts = "2026-11-29T18:15:42.300Z") => + line({ timestamp: ts, type: "response_item", payload: { type: "custom_tool_call_output", call_id: callId, output: texts.map((text) => ({ type: "input_text", text })) } }); + const toolUses = (entries: import("@/lib/log-entries").LogEntry[]) => + entries.flatMap((e) => (e.type === "assistant" ? e.message.content.filter((b) => b.type === "tool_use") : [])); + + it("turns an exec snippet into the exec_command it runs, with its output", async () => { + const content = [ + exec("call_A", 'const r = await tools.exec_command({cmd:"./deploy.sh","workdir":"/home/u/stuck","yield_time_ms":10000}); text(JSON.stringify(r));\n'), + out("call_A", ["Script completed\nWall time 0.0 seconds\nOutput:\n", "error: DEPLOY_TOKEN is not set\n"]), + ].join("\n"); + const { entries } = await parseCodexLog(content); + const [tu] = toolUses(entries); + expect(tu).toMatchObject({ type: "tool_use", id: "call_A", name: "exec_command", input: { cmd: "./deploy.sh", workdir: "/home/u/stuck" } }); + if (tu?.type !== "tool_use") throw new Error("expected tool_use"); + expect(tu.input).not.toHaveProperty("code"); + expect(tu.result?.content).toBe("Script completed\nWall time 0.0 seconds\nOutput:\nerror: DEPLOY_TOKEN is not set\n"); + expect(tu.result?.durationMs).toBe(300); + }); + + it("emits one tool_use per call site, the output on the first only", async () => { + const content = [ + exec("call_B", 'const a = await tools.exec_command({cmd:"git status"});\nawait tools.write_stdin({session_id:7,chars:"y\\n"});'), + out("call_B", ["done"]), + ].join("\n"); + const uses = toolUses((await parseCodexLog(content)).entries); + expect(uses.map((u) => u.type === "tool_use" && [u.id, u.name, u.input])).toEqual([ + ["call_B#0", "exec_command", { cmd: "git status" }], + ["call_B#1", "write_stdin", { session_id: 7, chars: "y\n" }], + ]); + expect(uses[0].type === "tool_use" && uses[0].result?.content).toBe("done"); + expect(uses[1].type === "tool_use" && uses[1].result).toBeUndefined(); + }); + + it("keeps the snippet as `code` when the command is not a literal", async () => { + const code = 'for (const c of ["a","b"]) await tools.exec_command({cmd: c});'; + const [tu] = toolUses((await parseCodexLog(exec("call_C", code))).entries); + expect(tu).toMatchObject({ name: "exec_command", input: { code } }); + }); + + it("still records a snippet that calls no tool, as `exec`", async () => { + const code = "text(ALL_TOOLS.filter(x => /search/.test(x.name)));"; + const [tu] = toolUses((await parseCodexLog(exec("call_D", code))).entries); + expect(tu).toMatchObject({ id: "call_D", name: "exec", input: { code } }); + }); + + it("gives a freeform apply_patch the file it touches", async () => { + const patch = "*** Begin Patch\n*** Update File: /home/u/proj/.env\n@@\n-A=1\n+A=2\n*** Add File: notes.md\n+hi\n*** End Patch\n"; + const content = line({ timestamp: "2026-11-29T18:00:00.000Z", type: "response_item", payload: { type: "custom_tool_call", call_id: "call_E", name: "apply_patch", input: patch } }); + const [tu] = toolUses((await parseCodexLog(content)).entries); + expect(tu).toMatchObject({ name: "apply_patch", input: { patch, file_path: "/home/u/proj/.env", files: ["/home/u/proj/.env", "notes.md"] } }); + }); + + it("reads apply_patch called from inside an exec snippet", async () => { + const code = 'await tools.apply_patch("*** Begin Patch\\n*** Add File: a.txt\\n+x\\n*** End Patch\\n");'; + const [tu] = toolUses((await parseCodexLog(exec("call_F", code))).entries); + expect(tu).toMatchObject({ name: "apply_patch", input: { file_path: "a.txt", patch: "*** Begin Patch\n*** Add File: a.txt\n+x\n*** End Patch\n" } }); + }); + + it("keeps an output with no matching call as a system entry", async () => { + const { entries } = await parseCodexLog(out("call_missing", ["x"])); + expect(entries).toHaveLength(1); + expect(entries[0].type).toBe("system"); + }); + }); }); describe("lib/codex-sessions: findCodexTranscript", () => { diff --git a/bin/failproofai.mjs b/bin/failproofai.mjs index af3c4d1a3..b541c9232 100755 --- a/bin/failproofai.mjs +++ b/bin/failproofai.mjs @@ -189,10 +189,30 @@ if (hookIdx >= 0) { const { evaluateHookEvent } = await import("../src/hooks/handler"); const stdinRead = await readStdinPayload(); + // Devin runs Claude Code's hooks too. Whether Devin is the agent above + // this process can only be read here (the worker's parent is the daemon), + // so a Claude-path report call made under Devin is marked for the worker. + const { selfReportMarkDevinOrigin } = await import("../src/hooks/self-report-devin"); + // Likewise which agent process a Claude Code / Codex report call came + // from, so its stdio server can tell this call's row from another + // session's (self-report-ancestry.ts). + const { selfReportMarkAgentPid } = await import("../src/hooks/self-report-ancestry"); + const { canonicalizeEventType } = await import("../src/hooks/handler"); + // And this process's PATH (the agent's, unlike the daemon worker's), for + // the guard that asks where a bare `grep` really resolves (agent-path.ts). + const { markAgentPath } = await import("../src/hooks/agent-path"); + // And where this agent keeps its configs (its CODEX_HOME, HOME, …), for + // the Self Reports exemption, which must read the agent's registration, + // not the one the daemon's environment points at (agent-env.ts). + const { markAgentEnv } = await import("../src/hooks/agent-env"); const attempt = await attemptDaemonHook({ hookEvent: eventType, cli, - stdin: stdinRead.payload, + stdin: markAgentEnv( + markAgentPath( + selfReportMarkAgentPid(cli, canonicalizeEventType(eventType, cli), selfReportMarkDevinOrigin(cli, stdinRead.payload)), + ), + ), // The client's own cwd IS the originating CLI session's cwd — this // process is spawned fresh, at that location, by the calling agent // CLI's own hook mechanism. See daemon-client.ts / PROTOCOL.md. @@ -324,6 +344,43 @@ if (hookIdx >= 0) { } } +// mcp [--agent ] — the Self Reports MCP server over stdio, spawned +// by an agent that registered it. Outside runCli() like --hook: stdout is the +// JSON-RPC stream, so nothing else (layout notices, onboarding, the install +// report) may run or print first, and it must work with no daemon. +const SELF_REPORT_MCP_HELP = { + name: "mcp", + usage: [["failproofai mcp [--agent ]", "Serve the Self Reports tool over stdio MCP"]], + options: [ + ["--agent ", "The agent this server was registered for"], + ["", "claude, codex, copilot, cursor, opencode, pi,"], + ["", "hermes, openclaw, factory, devin, antigravity, goose"], + ], +}; +if (args[0] === "mcp") { + if (args.includes("--help") || args.includes("-h")) { + await printHelp(SELF_REPORT_MCP_HELP); + await exitAfterFlush(0); + } + const agentIdx = args.indexOf("--agent"); + const agentArg = agentIdx >= 0 ? args[agentIdx + 1] : undefined; + const stray = args.slice(1).find((a, i) => a !== "--agent" && args[i] !== "--agent"); + if ((agentIdx >= 0 && (!agentArg || agentArg.startsWith("-"))) || stray) { + process.stderr.write( + `✕ ${stray ? `Unexpected argument: ${stray}.` : "Missing agent name after --agent."}\n Run failproofai help mcp for usage.\n`, + ); + await exitAfterFlush(1); + } + try { + const { runSelfReportMcpServer } = await import("../src/hooks/self-report-mcp"); + await runSelfReportMcpServer({ agent: agentArg }); + await exitAfterFlush(0); + } catch (err) { + process.stderr.write(`✕ failproofai mcp: ${err instanceof Error ? err.message : String(err)}\n`); + await exitAfterFlush(1); + } +} + /** * Centralised error handler for all CLI subcommands. * CliError → clean message, no stack trace, exit exitCode (1 or 2) @@ -480,7 +537,7 @@ async function runCli() { // at all, only the paragraph in the top-level dump that this rewrite moved. // `help` and `publish` are new. `policy` and `pack` are canonicalized to // `policies` above and never reach this list. - const SUBCOMMANDS = ["policies", "audit", "config", "uninstall", "backfill", "flush", "harness", "otel", "jev", "publish", "update", "migrate", "help"]; + const SUBCOMMANDS = ["policies", "audit", "config", "uninstall", "backfill", "flush", "harness", "otel", "jev", "self-report", "publish", "update", "migrate", "help"]; // ── help ───────────────────────────────────────────────────────────────── // // The index and the reference manual used to be the same document: 152 lines, @@ -511,6 +568,12 @@ async function runCli() { process.exit(0); process.exit(0); } + // `mcp` is machine-facing too (an agent spawns it), so like --hook it is a + // help topic rather than a row on the index. + if (helpTopic === "mcp") { + await printHelp(SELF_REPORT_MCP_HELP); + process.exit(0); + } // Canonicalize the topic the same way a typed command is canonicalized, so // `help pack` and `help policy` answer instead of erroring. const canonical = @@ -579,6 +642,7 @@ async function runCli() { ["(no args)", "Open the policy dashboard on localhost:8020"], ["audit", "Scan your agents' history for risky and wasteful patterns"], ["otel", "Opt in to OpenTelemetry from agents and apps"], + ["self-report", "Let agents report to you when they are stuck (on by default)"], ]), ...section("Less often", [ ["harness", "Collect sessions from extra locations per agent"], @@ -655,7 +719,14 @@ async function runCli() { { const isHelpOrVersion = args.includes("--help") || args.includes("-h") || args.includes("--version") || args.includes("-v"); - if (args[0] === "audit" && args.includes("--scheduled")) { + // `self-report sync` takes it too: failproofaid runs it (`--quiet`) at + // startup and after every settings change, unattended, exactly like a + // scheduled audit. A person running it by hand on a stale home is told to + // run `failproofai config`, which migrates visibly. + const unattended = + (args[0] === "audit" && args.includes("--scheduled")) || + (args[0] === "self-report" && args[1] === "sync" && !isHelpOrVersion); + if (unattended) { // NOT `layoutWarningForHook` — that one answers the hook's question // ("are policies unenforced?") and deliberately stays quiet when the // global config is readable. This gate is about the LAYOUT, and must @@ -754,6 +825,52 @@ async function runCli() { // over. Every precondition a person can get wrong is still checked HERE, // synchronously, because reporting success and leaving the real failure in the // journal is what already cost twenty minutes on a live machine. + // `failproofai self-report sync [--quiet]`: add or remove failproofai's + // Self Reports MCP server in every agent with failproofai hooks, from + // ~/.failproofai/self-report.json. The daemon runs it with --quiet whenever + // that file's `enabled` (or port) changes; it is idempotent. + // Dispatched ahead of the status|enable|disable|test branch below, which + // lists it on the `self-report --help` page. + if (args[0] === "self-report" && args[1] === "sync") { + const subArgs = args.slice(2); + if (subArgs.includes("--help") || subArgs.includes("-h")) { + await printHelp({ + name: "self-report sync", + usage: [["failproofai self-report sync [--quiet]", "Register or remove the Self Reports MCP server (failproofai_local) in each hooked agent"]], + options: [["--quiet", "Print nothing; the exit code says whether every agent succeeded"]], + optionsCol: 12, + }); + process.exit(0); + } + const unknown = subArgs.find((a) => a !== "--quiet"); + if (unknown) { + throw new CliError(`Unexpected argument: ${unknown}.\nRun \`failproofai self-report sync --help\` for usage.`); + } + lastSubcommand = "self-report"; + const { syncSelfReportMcp, selfReportSyncLines } = await import("../src/hooks/self-report-install"); + const results = await syncSelfReportMcp({ quiet: true }); + const failed = results.some((r) => r.status === "error"); + if (!subArgs.includes("--quiet")) { + const lines = selfReportSyncLines(results); + await printLines(lines.length > 0 ? lines : ["Self Reports MCP registration is already up to date."], !failed); + } else { + // The daemon runs this with --quiet and logs our stdout and stderr: what + // changed (one line), and each agent that failed, so "exit 1" is never + // all its journal says. + if (process.env.FAILPROOFAI_SELF_REPORT_SYNC_LOG === "stdout") { + const { selfReportSyncLogLine } = await import("../src/hooks/self-report-install"); + const changed = selfReportSyncLogLine(results.filter((x) => x.status !== "error" && x.status !== "conflict")); + if (changed) process.stdout.write(`${changed}\n`); + } + for (const r of results.filter((x) => x.status === "error")) { + process.stderr.write(`${r.agent}: not updated in ${r.path || "its config"}: ${r.detail ?? "error"}\n`); + } + } + lastSubcommand = null; + await exitAfterFlush(failed ? 1 : 0); + return; + } + if (args[0] === "flush") { const subArgs = args.slice(1); if (subArgs.includes("--help") || subArgs.includes("-h")) { @@ -994,6 +1111,55 @@ async function runCli() { return; } + // self-report status | enable | disable | test + // + // Self Reports: the `report` tool agents call when they are stuck. On by + // default. On a machine managed by FailproofAI Cloud the setting comes from + // Cloud and enable/disable refuse; otherwise they write config.json's + // `selfReport` and ~/.failproofai/self-report.json, then update the agents' + // MCP entries (disable removes them and stops recording). + if (args[0] === "self-report") { + const subArgs = args.slice(1); + if (subArgs.length === 0 || subArgs.includes("--help") || subArgs.includes("-h")) { + await printHelp({ + name: "self-report", + usage: [ + ["failproofai self-report status [--json]", "Whether it is on, the agents it serves, and any that need a fix"], + ["failproofai self-report enable [options]", "Turn it back on for this machine, or change its categories"], + ["failproofai self-report disable", "Turn it off: removes the MCP entries and stops recording"], + ["failproofai self-report test --agent ", "Send one test report end to end"], + ["failproofai self-report sync [--quiet]", "Update each hooked agent's failproofai_local MCP entry (the daemon runs this)"], + ], + options: [ + ["--categories-file ", "JSON list of {name, description}; replaces the defaults"], + ["--guidance ", "Extra instructions appended to the tool description"], + ["--agent ", "With test: the agent to send it as"], + ["--verbose", "With status: paths, endpoints, categories and each agent's transport"], + ["--json", "With status: everything, as JSON"], + ], + examples: [ + "failproofai self-report status", + "failproofai self-report disable", + "failproofai self-report test --agent claude", + ], + }); + process.exit(0); + } + lastSubcommand = "self-report"; + const { runSelfReportCommand } = await import("../src/hooks/self-report-cli"); + const result = await runSelfReportCommand(subArgs); + if (result.json !== undefined) process.stdout.write(`${JSON.stringify(result.json, null, 2)}\n`); + else await printReport(`self-report ${subArgs[0]}`, result.lines, { ok: result.exitCode === 0 }); + await track("cli_self_report", { + ok: result.exitCode === 0, + // The subcommand only — never a category, guidance text or a path. + sub: ["status", "enable", "disable", "test", "sync"].includes(subArgs[0]) ? subArgs[0] : "unknown", + }); + lastSubcommand = null; + await exitAfterFlush(result.exitCode); + return; + } + // jev --url | jev setup | status | test | remove // // The customer's own Jev endpoint and key (BYOK), the only opt-in to the @@ -2059,30 +2225,13 @@ async function runCli() { // running Hermes or OpenClaw gateway kept the plugin it loaded before (or // none) until someone thought to run `update`. Setup has already brought // the daemon to this version and the entry check migrated the home. + // Then Self Reports: every hooked agent's MCP entry brought in line with + // self-report.json. Both behind one spinner line, which leaves the Self + // Reports line and only what needs the user (src/hooks/setup-finish.ts). let updateExit = 0; if (result.applied) { - const { runUpdateSteps, markUpdated, setupNeedsUpdateSteps, setupGatewayLine, restartNewlyPlugged } = - await import("../src/hooks/update-run"); - const { screenKit, colorsEnabled } = await import("../src/hooks/tui"); - const kit = screenKit({ color: colorsEnabled(process.stdout) }); - if (!setupNeedsUpdateSteps(version)) { - // Already updated on this version: only a profile this run plugged in - // (one created since) has a gateway still running without the plugin. - const gateway = setupGatewayLine(await restartNewlyPlugged(pluggedBefore).catch(() => [])); - if (gateway) process.stdout.write(`${gateway.ok ? kit.ok(gateway.text) : kit.caution(gateway.text)}\n`); - } else { - const run = await runUpdateSteps({ layout: false, daemon: false, restart: true }); - // One line at most, in update's own words; a Hermes failure keeps its - // existing ✕ line so it is not lost. - const gateway = setupGatewayLine(run.restarts); - const out = [ - ...run.lines.filter((l) => l.startsWith("✕")), - ...(gateway ? [gateway.ok ? kit.ok(gateway.text) : kit.caution(gateway.text)] : []), - ]; - if (out.length > 0) process.stdout.write(`${out.join("\n")}\n`); - if (run.ok) markUpdated(version); - else updateExit = 1; - } + const { finishSetup } = await import("../src/hooks/setup-finish"); + updateExit = await finishSetup({ version, pluggedBefore }); } await warnTokenOnArgv(); await track("cli_configure_invoked", { diff --git a/crates/PROTOCOL.md b/crates/PROTOCOL.md index c07b936cc..d2121beef 100644 --- a/crates/PROTOCOL.md +++ b/crates/PROTOCOL.md @@ -66,6 +66,75 @@ Tagged JSON, `"type"` as the discriminant, camelCase field names. } ``` +`stdin` is the agent's payload with top-level keys added by the hook client, +because only the process the agent started can know them (the daemon's +worker has the daemon's PATH and parent). The client overwrites or removes +each one, so none is ever taken from the payload the agent sent, and the +daemon relays `stdin` untouched, so neither side needs a version bump: an +older daemon carries them, and from an older client they are simply absent. + +- `failproofai_agent_path` (string, at most 16,384 characters): the client's + `PATH`, set only on a payload that names `grep`, `rg`, `jq`, `cat` or `tee`. + `block-failproofai-commands` decides whether a bare command word is the + standard tool from this PATH alone; without it (an older client, or the + Hermes and OpenClaw plugins, which call the daemon directly) nothing is + exempt. +- `failproofai_report_agent_pid` (number): the agent process above the hook + (the nearest that is not a shell or exec wrapper), on a Claude Code / Codex + Self Reports call and on every agent's session-start and prompt events. The + worker keeps it on the activity row as `agentPid` (local only), and the + stdio server matches rows and sessions to its own agent by it, exactly. + The client also sends `failproofai_report_agent_pids: [pid]`, the earlier + list form, which a worker of the previous build (still running after an + upgrade until the daemon restarts) copies onto the row as + `selfReportAgentPids`; the server reads the first pid of that list too. +- `failproofai_agent_env` (object of strings, each at most 4,096 characters): + the client's config-locating variables (`HOME`, `USERPROFILE`, `APPDATA`, + `XDG_CONFIG_HOME`, `CLAUDE_CONFIG_DIR`, `CODEX_HOME`, `COPILOT_HOME`, + `PI_CODING_AGENT_DIR`, `HERMES_HOME`, `OPENCLAW_STATE_DIR`, `OPENCLAW_HOME`, + `OPENCLAW_CONFIG_PATH`, `OPENCLAW_PROFILE`, `GOOSE_PATH_ROOT`, + `OPENCODE_CONFIG`; unset ones are left out), set only on a payload that + names `failproofai_local`. The worker decides the Self Reports exemption + (whether the `failproofai_local` registration the agent uses is + failproofai's own) under exactly these, never its own environment, and + refuses the exemption without them (an older client, a value past the + bound). The Hermes and OpenClaw plugins send none; their exemption reads + the profile config named by the request's `agentSettingsPath`, and none + without it. +- `failproofai_via_devin` (true): a Claude-path Self Reports call made under + Devin. + +```jsonc +// One Self Reports MCP event from outside the daemon — the stdio server +// `failproofai mcp` (a child of each agent) or a CLI `self-report sync` — +// for the daemon's log, which machine logs ship. ONE-WAY: the daemon writes +// no reply and closes the connection; the sender never reads one. +{ + "type": "selfReportLog", + "protocolVersion": 2, + "event": { + "event": "tools/call", // initialize | tools/list | tools/call | sync | error + "agent": "hermes", // every field below is optional + "transport": "stdio", // stdio | cli + "outcome": "recorded", // recorded | skipped | failed (calls); on | off (initialize) + "reason": "Self Reports is off", + "category": "looping", + "knownCategory": true, // false: the category sent is not listed, and `category` was resolved from it + "rawCategory": "", // only when knownCategory is false: what was sent (maybe empty), ≤ 2000 chars; logged only when shaped like a name + "session": "…", + "preview": "the detail as the agent sent it (before the 2000-char report cut), ≤ 65,536 chars; the daemon scrubs secrets from all of it, then logs ≤ 40", + "summary": "added claude (stdio); failed codex (…)" // sync only + } +} +``` + +`selfReportLog` needs no version bump: a daemon that predates it fails to parse +the unknown `type` and closes the connection (see "Malformed input handling"), +which drops the event — exactly what a one-way message wants. Unknown fields in +`event` are ignored, so either side can add one. The client sends it only when +the socket file exists, gives the whole send 250 ms, and drops it on any error, +so an agent is never held up. + `cwd` must be the *originating* CLI process's cwd, captured by the thin client before dispatch — never the daemon's own cwd. The daemon is a single long-lived process; its own `cwd` does not vary per request and must never be @@ -85,6 +154,11 @@ an unnamed agent would escape: there it fails closed. ```jsonc { "type": "pong", "protocolVersion": 2 } +// While the Self Reports MCP listener is bound, a pong also carries +// "selfReport": { "instanceId": "", "port": 4319 } +// (optional and additive: older clients ignore it). The endpoint's MCP +// initialize returns the same id as serverInfo.instanceId, so a client can +// prove the HTTP port belongs to the daemon behind this socket. { "type": "hookResult", diff --git a/crates/failproofaid/src/audit_lane.rs b/crates/failproofaid/src/audit_lane.rs index 0b37f68f1..2fe514a75 100644 --- a/crates/failproofaid/src/audit_lane.rs +++ b/crates/failproofaid/src/audit_lane.rs @@ -567,7 +567,7 @@ enum Outcome { /// system PATH. There is deliberately no fallback to a bare `failproofai`: one /// that resolved to a DIFFERENT installation than the one that wrote this unit /// would scan with a different build's audit engine, silently. -fn cli_command() -> Option { +pub(crate) fn cli_command() -> Option { usable_cli_command(std::env::var("FAILPROOFAI_CLI_CMD").ok()) } diff --git a/crates/failproofaid/src/cloud_client.rs b/crates/failproofaid/src/cloud_client.rs index becfb4d6e..d2b4caffa 100644 --- a/crates/failproofaid/src/cloud_client.rs +++ b/crates/failproofaid/src/cloud_client.rs @@ -418,6 +418,9 @@ pub struct CloudClient { token: String, machine_id: String, client: Client, + /// [`fpai_collect::self_report::enrolment_id`] of the credential as + /// stored (before the URL is normalised), the value the CLI computes too. + self_report_enrolment: String, } /// On-disk enrolment, written by `failproofai config --connect`. @@ -600,6 +603,21 @@ fn enrolment_withdrawn() -> bool { matches!(Enrolment::resolve(), Ok(None)) } +/// Which enrolment this machine is under, for Self Reports' settings readers +/// (`fpai_collect::self_report::effective_settings`). The same resolution as +/// the policy poll; an unreadable credential counts as enrolled with no known +/// identity, so neither a missing file nor any written one turns it on. +pub fn self_report_enrolled() -> fpai_collect::self_report::Enrolment { + use fpai_collect::self_report::{Enrolment as SrEnrolment, enrolment_id}; + match Enrolment::resolve() { + Ok(None) => SrEnrolment::NotEnrolled, + Ok(Some(e)) => { + SrEnrolment::Enrolled(Some(enrolment_id(&e.base_url, &e.machine_id, &e.token))) + } + Err(_) => SrEnrolment::Enrolled(None), + } +} + impl Enrolment { fn resolve() -> Result, String> { if let Some(enrolment) = Self::from_env()? { @@ -733,6 +751,8 @@ impl Enrolment { impl CloudClient { fn new(base_url: &str, token: String, machine_id: String) -> Result { + let self_report_enrolment = + fpai_collect::self_report::enrolment_id(base_url, &machine_id, &token); let mut base_url = Url::parse(base_url).map_err(|err| format!("invalid FAILPROOFAI_CLOUD_URL: {err}"))?; if !matches!(base_url.scheme(), "http" | "https") { @@ -785,6 +805,7 @@ impl CloudClient { token, machine_id, client, + self_report_enrolment, }) } @@ -839,7 +860,7 @@ impl CloudClient { &self, applied: Option, policy_errors: Option<&str>, - ) -> Result { + ) -> Result<(DesiredState, CloudSettings), PollFailure> { let mut url = self .base_url .join("enforcement/v1/desired-state") @@ -878,20 +899,21 @@ impl CloudClient { .json::() .map_err(|err| PollFailure::payload(format!("invalid desired-state response: {err}"))) .and_then(|raw| { - // Applied only once the whole response is known good: a response - // this daemon refuses (an unknown schemaVersion, a payload that - // does not decode) must not turn troubleshooting back on or start - // an upload, so the last valid answer keeps standing. - let (desired, consent) = decode_desired_state(raw)?; - // The org's troubleshooting switch: `machineLogs: false` means - // send no daemon log (logship.rs). Absent, from a Cloud with it - // on or one that predates the key, means send. - crate::logship::set_cloud_allows(consent.machine_logs != Some(false)); - // An operator asked for this machine's logs (logship.rs). - if let Some(id) = consent.log_request { - crate::logship::note_request(&id); - } - Ok(desired) + // Nothing is applied here. A response this daemon refuses to + // decode (an unknown schemaVersion, a payload that does not + // decode) carries no settings at all, and one that decodes can + // still be refused by the reconcile (a deployment rollback, a + // withdrawn enrolment). The caller applies `selfReport`, + // `machineLogs` and `logRequest` once it knows which + // (`reconcile_and_apply_settings`). + let (desired, consent, self_report) = decode_desired_state(raw)?; + Ok(( + desired, + CloudSettings { + consent, + self_report, + }, + )) }) } @@ -1197,6 +1219,16 @@ pub fn spawn_maintenance( // `desired-state.json` through `reconcile`, which raises the floor // straight back to the old number. Replay protection resumes from // the new identity's first success. + // Self Reports follow enrolment: written from the response just + // accepted, or released when the machine left Cloud. Unknown + // (unreadable credential) changes nothing. + // Enrolled answers are bound to the credential this pass polled + // with, so a later org never inherits an earlier one's file. + let self_report_enrolment = match &cloud { + Ok(Some(client)) => Some(Some(client.self_report_enrolment.clone())), + Ok(None) => Some(None), + Err(_) => None, + }; if maintenance_tick( &store, cloud, @@ -1206,6 +1238,11 @@ pub fn spawn_maintenance( ) { floor_reset_pending = false; } + crate::self_report::tick( + self_report_enrolment, + &self_report_enrolled, + &enrolment_withdrawn, + ); wait_until_shutdown( &shutdown, if enrolled { @@ -1324,16 +1361,39 @@ fn report_and_reclaim(cloud: &CloudClient, path: &Path, home: &Path, roster: &Ag } /// The log-shipping fields of a desired-state response (logship.rs). -#[derive(Debug, Default, PartialEq, Eq)] +#[derive(Debug, Default, Clone, PartialEq, Eq)] struct LogConsent { machine_logs: Option, log_request: Option, } +/// The machine settings a desired-state response carries beside its policies, +/// applied by `reconcile_and_apply_settings` only from a response the reconcile +/// accepted. +#[derive(Debug, Default, Clone, PartialEq, Eq)] +struct CloudSettings { + consent: LogConsent, + /// `None`: absent, which means Self Reports are off. + self_report: Option, +} + /// Validates a desired-state response and decodes it. The log-shipping fields /// come back only with a response that was accepted, so a refused one has /// nothing to apply. -fn decode_desired_state(raw: serde_json::Value) -> Result<(DesiredState, LogConsent), PollFailure> { +/// +/// The third value is the optional `selfReport` block (`None`: absent, which +/// means Self Reports are off). It is read leniently and never refuses the +/// response: a malformed block must not take the policies beside it down. +fn decode_desired_state( + raw: serde_json::Value, +) -> Result< + ( + DesiredState, + LogConsent, + Option, + ), + PollFailure, +> { // THE VERSION IS CHECKED BEFORE THE FIELDS, which is the whole // point of having one. `SUPPORTED_SCHEMA_VERSIONS` accepts 1 as // well, and its comment says that is "for files on DISK, never for @@ -1372,9 +1432,10 @@ fn decode_desired_state(raw: serde_json::Value) -> Result<(DesiredState, LogCons .and_then(serde_json::Value::as_str) .map(str::to_owned), }; + let self_report = crate::self_report::decode(&raw); let desired = serde_json::from_value::(raw) .map_err(|err| PollFailure::payload(format!("invalid desired-state response: {err}")))?; - Ok((desired, consent)) + Ok((desired, consent, self_report)) } /// One poll and its reconcile. `withdrawn` is asked right before anything is @@ -1415,7 +1476,7 @@ fn poll_once_guarded( ) .map(|errors| encode_policy_errors(&errors)); match cloud.poll_desired_state(applied, report.as_deref()) { - Ok(desired) => { + Ok((desired, settings)) => { // The GET created/checked-in the machine row the PUT requires. // Do not let a roster network outage interrupt local enforcement. if let Ok(path) = agent_roster::roster_path() @@ -1424,8 +1485,10 @@ fn poll_once_guarded( { report_and_reclaim(cloud, &path, Path::new(&home), &roster); } - match store.reconcile_unless( + match reconcile_and_apply_settings( + store, &desired, + settings, &|policy: &DesiredPolicy| cloud.artifact(policy), withdrawn, ) { @@ -1479,6 +1542,60 @@ fn poll_once_guarded( } } +/// Reconcile `desired`, then apply the settings beside it: `selfReport` (to +/// the maintenance lane), `machineLogs` and `logRequest` (to logship.rs), only +/// when the reconcile accepted the response. +/// +/// Refused means: the response itself failed validation (an unknown shape, a +/// deployment below the rollback floor — both `InvalidDesiredState`), or the +/// machine was disconnected while the poll was in flight (`Withdrawn`). Such a +/// response is not an answer this machine acts on, so its settings must not +/// change anything: an out-of-order deployment 99 that says "on" after +/// deployment 100 said "off" leaves the feature off, and troubleshooting off. +/// +/// An artifact failure (fetch, hash, I/O) is not a refusal: the response passed +/// the rollback guard and is the server's newest answer, and an org toggle must +/// not wait on an unrelated policy download that may keep failing. +/// +/// `machineLogs` keeps its rules: `false` means send no daemon log, absent +/// (a Cloud with it on, or one that predates the key) means send. A refused +/// response leaves the last accepted answer standing either way. +fn reconcile_and_apply_settings( + store: &PolicyStore, + desired: &DesiredState, + settings: CloudSettings, + fetcher: &impl crate::cloud_policies::ArtifactFetcher, + withdrawn: &dyn Fn() -> bool, +) -> Result { + let result = store.reconcile_unless(desired, fetcher, withdrawn); + if matches!(result, Err(ReconcileError::Withdrawn)) || withdrawn() { + // Disconnected: this response is not Cloud's to act on any more, and + // a log request would only queue an upload for a machine that left. + return result; + } + let accepted = !matches!(result, Err(ReconcileError::InvalidDesiredState(_))); + if accepted { + crate::self_report::note_desired(settings.self_report); + // Before the request: turning troubleshooting off drops an open one. + crate::logship::set_cloud_allows(settings.consent.machine_logs != Some(false)); + } + // `logRequest` is the one exception, and only for a response that is not + // stale. A deployment this daemon cannot validate (a newer server's policy + // shape, a jevMode or authority this version does not know) is refused on + // every poll until the daemon is upgraded, and that machine is the one + // support needs logs from: a request is how they pull them. Out-of-order + // responses (below the rollback floor) are still ignored, and the upload + // stays bound by the org's switch as last accepted, since `note_request` + // queues nothing while troubleshooting is off. For an accepted response + // the floor is its own deployment, so this is every accepted response too. + if let Some(id) = &settings.consent.log_request + && desired.deployment >= store.server_high_water() + { + crate::logship::note_request(id); + } + result +} + pub fn poll_interval_from_env() -> Duration { let milliseconds = env_value("FAILPROOFAI_CLOUD_POLICY_POLL_MS") .and_then(|value| value.parse::().ok()) @@ -1542,6 +1659,7 @@ mod tests { /// The poll without an error report, for the tests that predate it. fn desired_state(&self, applied: Option) -> Result { self.poll_desired_state(applied, None) + .map(|(desired, _)| desired) .map_err(|failure| failure.message) } } @@ -1809,12 +1927,62 @@ mod tests { } fn decode(body: &str) -> Result<(DesiredState, LogConsent), String> { + decode_with_self_report(body).map(|(desired, consent, _)| (desired, consent)) + } + + fn decode_with_self_report( + body: &str, + ) -> Result< + ( + DesiredState, + LogConsent, + Option, + ), + String, + > { decode_desired_state(serde_json::from_str(body).unwrap()).map_err(|f| { assert!(f.reportable, "a refused payload is the server's to see"); f.message }) } + /// `selfReport` rides an accepted response; absent stays absent, and a + /// malformed block never refuses the policies beside it. + #[test] + fn a_desired_state_response_carries_its_self_report_block() { + let (_, _, self_report) = decode_with_self_report( + r#"{"schemaVersion":2,"deployment":7,"policies":[], + "selfReport":{"enabled":true,"categories":[{"name":"x","description":"X."}],"guidance":"g"}}"#, + ) + .expect("a valid response is accepted"); + assert_eq!( + self_report, + Some(crate::self_report::Desired { + enabled: true, + categories: Some(vec![fpai_collect::self_report::Category { + name: "x".into(), + description: "X.".into(), + }]), + guidance: Some("g".into()), + }) + ); + + let (_, _, self_report) = + decode_with_self_report(r#"{"schemaVersion":2,"deployment":7,"policies":[]}"#) + .expect("an older server's response is accepted"); + assert_eq!(self_report, None, "absent means disabled"); + + let (desired, _, self_report) = decode_with_self_report( + r#"{"schemaVersion":2,"deployment":7,"policies":[],"selfReport":[1,2]}"#, + ) + .expect("a malformed block does not refuse the response"); + assert_eq!(desired.deployment, 7); + assert_eq!(self_report, None); + + decode_with_self_report(r#"{"schemaVersion":999,"selfReport":{"enabled":true}}"#) + .expect_err("a refused response carries nothing to apply"); + } + /// A response the daemon refuses carries no consent to apply: the refusal /// used to land AFTER `machineLogs` and `logRequest` were applied, so an /// unknown schemaVersion with no `machineLogs` read as "on", removed @@ -2226,6 +2394,353 @@ mod tests { store } + fn self_report_on(enabled: bool) -> Option { + Some(crate::self_report::Desired { + enabled, + categories: None, + guidance: None, + }) + } + + /// The settings beside the policies, as a desired-state response carries + /// them. + fn settings( + self_report: Option, + machine_logs: Option, + log_request: Option<&str>, + ) -> CloudSettings { + CloudSettings { + consent: LogConsent { + machine_logs, + log_request: log_request.map(str::to_owned), + }, + self_report, + } + } + + /// Every test below drives logship.rs's process-wide state; this holds its + /// lock and starts from troubleshooting on with nothing requested. + fn lock_logship() -> std::sync::MutexGuard<'static, ()> { + let guard = crate::logship::TEST_LOCK + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + crate::logship::reset_for_test(true); + guard + } + + /// A response this daemon cannot validate: a `jevMode` it does not know. + fn unvalidatable_state(deployment: u64) -> DesiredState { + let mut desired = jev_state(deployment); + desired.jev_mode = Some("from-a-newer-server".into()); + desired + } + + /// The review's replay: deployment 100 switched Self Reports off, then an + /// out-of-order deployment 99 said on. The rollback is refused, and its + /// `selfReport` must be refused with it: nothing is queued for the lane, so + /// the feature stays off and `active.json` stays at 100. + #[test] + fn a_rolled_back_response_does_not_change_self_reports() { + let _env = lock_env(); + let _logs = lock_logship(); + let _ = crate::self_report::take_pending(); + let store = temp_store("self-report-rollback"); + + reconcile_and_apply_settings( + &store, + &jev_state(100), + settings(self_report_on(false), None, None), + &serve, + &|| false, + ) + .unwrap(); + assert_eq!( + crate::self_report::take_pending(), + Some(self_report_on(false)), + "an accepted response queues its setting" + ); + + let refused = reconcile_and_apply_settings( + &store, + &jev_state(99), + settings(self_report_on(true), None, None), + &serve, + &|| false, + ); + assert!( + matches!(&refused, Err(ReconcileError::InvalidDesiredState(m)) if m.contains("rollback")), + "{refused:?}" + ); + assert_eq!( + crate::self_report::take_pending(), + None, + "a rolled-back response must not queue its selfReport" + ); + assert_eq!(store.read_active().unwrap().unwrap().deployment, 100); + + // Absent `selfReport` on a rolled-back response is refused the same way: + // it must not switch an enabled machine off either. + let _ = reconcile_and_apply_settings( + &store, + &jev_state(98), + CloudSettings::default(), + &serve, + &|| false, + ); + assert_eq!(crate::self_report::take_pending(), None); + fs::remove_dir_all(store.root()).ok(); + } + + /// A response whose reconcile runs into `config --disconnect` is discarded, + /// its `selfReport` included. + #[test] + fn a_withdrawn_response_does_not_change_self_reports() { + let _env = lock_env(); + let _logs = lock_logship(); + let _ = crate::self_report::take_pending(); + let store = temp_store("self-report-withdrawn"); + let result = reconcile_and_apply_settings( + &store, + &jev_state(5), + settings(self_report_on(true), None, None), + &serve, + &|| true, + ); + assert!( + matches!(result, Err(ReconcileError::Withdrawn)), + "{result:?}" + ); + assert_eq!(crate::self_report::take_pending(), None); + fs::remove_dir_all(store.root()).ok(); + } + + /// A response that passed validation and the rollback guard is the server's + /// newest answer even when one of its artifacts fails to download: the org's + /// toggle still applies rather than waiting on an unrelated policy. + #[test] + fn an_accepted_response_with_a_failed_artifact_still_applies_self_reports() { + let _env = lock_env(); + let _logs = lock_logship(); + let _ = crate::self_report::take_pending(); + let store = temp_store("self-report-fetch-fail"); + let result = reconcile_and_apply_settings( + &store, + &jev_state(5), + settings(self_report_on(true), None, None), + &|_: &DesiredPolicy| Err::, String>("offline".into()), + &|| false, + ); + assert!( + matches!(result, Err(ReconcileError::Fetch { .. })), + "{result:?}" + ); + assert_eq!( + crate::self_report::take_pending(), + Some(self_report_on(true)) + ); + fs::remove_dir_all(store.root()).ok(); + } + + /// The same replay for troubleshooting: an out-of-order deployment 99 must + /// neither turn it back on (absent `machineLogs` means on) nor off, and its + /// `logRequest` must not start an upload. + #[test] + fn a_rolled_back_response_does_not_change_troubleshooting() { + let _env = lock_env(); + let _logs = lock_logship(); + let store = temp_store("logs-rollback"); + + // 100 turned troubleshooting off; 99 has no key (on) and a request. + reconcile_and_apply_settings( + &store, + &jev_state(100), + settings(None, Some(false), None), + &serve, + &|| false, + ) + .unwrap(); + assert_eq!(crate::logship::consent_for_test(), (false, None)); + let refused = reconcile_and_apply_settings( + &store, + &jev_state(99), + settings(None, None, Some("req-99")), + &serve, + &|| false, + ); + assert!( + matches!(&refused, Err(ReconcileError::InvalidDesiredState(m)) if m.contains("rollback")), + "{refused:?}" + ); + assert_eq!( + crate::logship::consent_for_test(), + (false, None), + "a rolled-back response must not turn troubleshooting back on" + ); + + // 101 turned it on; 98 says off and asks for logs. + reconcile_and_apply_settings( + &store, + &jev_state(101), + settings(None, Some(true), None), + &serve, + &|| false, + ) + .unwrap(); + assert_eq!(crate::logship::consent_for_test(), (true, None)); + let _ = reconcile_and_apply_settings( + &store, + &jev_state(98), + settings(None, Some(false), Some("req-98")), + &serve, + &|| false, + ); + assert_eq!( + crate::logship::consent_for_test(), + (true, None), + "a rolled-back response must neither turn troubleshooting off nor request logs" + ); + assert_eq!(store.read_active().unwrap().unwrap().deployment, 101); + fs::remove_dir_all(store.root()).ok(); + } + + /// A response discarded by `config --disconnect` changes neither the switch + /// nor queues its request. + #[test] + fn a_withdrawn_response_does_not_change_troubleshooting() { + let _env = lock_env(); + let _logs = lock_logship(); + let store = temp_store("logs-withdrawn"); + let result = reconcile_and_apply_settings( + &store, + &jev_state(5), + settings(None, Some(false), Some("req-5")), + &serve, + &|| true, + ); + assert!( + matches!(result, Err(ReconcileError::Withdrawn)), + "{result:?}" + ); + assert_eq!(crate::logship::consent_for_test(), (true, None)); + fs::remove_dir_all(store.root()).ok(); + } + + /// An accepted response whose artifact failed still applies both: `false` + /// turns troubleshooting off, and a request on a later one is queued. + #[test] + fn an_accepted_response_with_a_failed_artifact_still_applies_troubleshooting() { + let _env = lock_env(); + let _logs = lock_logship(); + let store = temp_store("logs-fetch-fail"); + let offline = |_: &DesiredPolicy| Err::, String>("offline".into()); + + let result = reconcile_and_apply_settings( + &store, + &jev_state(5), + settings(None, Some(false), Some("req-5")), + &offline, + &|| false, + ); + assert!( + matches!(result, Err(ReconcileError::Fetch { .. })), + "{result:?}" + ); + assert_eq!( + crate::logship::consent_for_test(), + (false, None), + "off applies, and drops the request that came with it" + ); + + let result = reconcile_and_apply_settings( + &store, + &jev_state(6), + settings(None, None, Some("req-6")), + &offline, + &|| false, + ); + assert!( + matches!(result, Err(ReconcileError::Fetch { .. })), + "{result:?}" + ); + assert_eq!( + crate::logship::consent_for_test(), + (true, Some("req-6".to_string())), + "absent means on, and the request is queued" + ); + fs::remove_dir_all(store.root()).ok(); + } + + /// The one exception: a current response this daemon refuses only because it + /// cannot validate it (a newer server's policy shape) still delivers its + /// `logRequest`, since that refusal repeats every poll and support needs + /// that machine's logs. Its `machineLogs` and `selfReport` are not applied, + /// and a request is still bound by the switch as last accepted. + #[test] + fn an_unvalidatable_current_response_still_delivers_its_log_request() { + let _env = lock_env(); + let _logs = lock_logship(); + let _ = crate::self_report::take_pending(); + let store = temp_store("logs-unvalidatable"); + reconcile_and_apply_settings( + &store, + &jev_state(100), + settings(None, Some(true), None), + &serve, + &|| false, + ) + .unwrap(); + let _ = crate::self_report::take_pending(); + + let refused = reconcile_and_apply_settings( + &store, + &unvalidatable_state(101), + settings(self_report_on(true), Some(false), Some("req-101")), + &serve, + &|| false, + ); + assert!( + matches!(&refused, Err(ReconcileError::InvalidDesiredState(m)) if m.contains("jevMode")), + "{refused:?}" + ); + assert_eq!( + crate::logship::consent_for_test(), + (true, Some("req-101".to_string())), + "the request is queued; the refused response's `false` is not applied" + ); + assert_eq!(crate::self_report::take_pending(), None); + assert_eq!(store.read_active().unwrap().unwrap().deployment, 100); + + // An unvalidatable response that is also stale is ignored entirely. + crate::logship::reset_for_test(true); + let _ = reconcile_and_apply_settings( + &store, + &unvalidatable_state(99), + settings(None, None, Some("req-99")), + &serve, + &|| false, + ); + assert_eq!(crate::logship::consent_for_test(), (true, None)); + + // With troubleshooting off (as last accepted), the request queues nothing. + reconcile_and_apply_settings( + &store, + &jev_state(102), + settings(None, Some(false), None), + &serve, + &|| false, + ) + .unwrap(); + let _ = reconcile_and_apply_settings( + &store, + &unvalidatable_state(103), + settings(None, Some(true), Some("req-103")), + &serve, + &|| false, + ); + assert_eq!(crate::logship::consent_for_test(), (false, None)); + fs::remove_dir_all(store.root()).ok(); + } + /// Exactly what `config --disconnect` removes /// (`clearActiveCloudManagedPolicies` in `cloud-managed-policies.ts`). fn disconnect_like_the_cli(store: &PolicyStore) { diff --git a/crates/failproofaid/src/cloud_policies.rs b/crates/failproofaid/src/cloud_policies.rs index ff42b5bc8..0aeac291c 100644 --- a/crates/failproofaid/src/cloud_policies.rs +++ b/crates/failproofaid/src/cloud_policies.rs @@ -535,6 +535,12 @@ impl PolicyStore { &self.root } + /// The highest deployment the server has offered this process (the + /// rollback floor). A response below it is an out-of-order older answer. + pub fn server_high_water(&self) -> u64 { + self.server_high_water.load(Ordering::Relaxed) + } + /// Forgets the highest deployment the server has offered this process. /// /// The deployment counter is the server's per (org, machine) — a different diff --git a/crates/failproofaid/src/logship.rs b/crates/failproofaid/src/logship.rs index ca21d8f71..f4372961a 100644 --- a/crates/failproofaid/src/logship.rs +++ b/crates/failproofaid/src/logship.rs @@ -917,6 +917,19 @@ fn ship_at(machine_id: &str, scrub: &Scrub, post: &dyn Fn(&Value) -> PostOutcome } } +/// Serialises every test that touches the process-wide state, in this module +/// and in `cloud_client`'s desired-state tests. +#[cfg(test)] +pub(crate) static TEST_LOCK: Mutex<()> = Mutex::new(()); + +/// What the org's switch and the open request are: (`uploads allowed`, +/// `requested id`). +#[cfg(test)] +pub(crate) fn consent_for_test() -> (bool, Option) { + let st = state(); + (!st.cloud_off, st.requested.clone()) +} + #[cfg(test)] pub(crate) fn reset_for_test(enabled: bool) { let mut st = state(); @@ -930,7 +943,7 @@ mod tests { use std::cell::RefCell; // The module keeps one process-wide state; serialise the tests that use it. - static LOCK: Mutex<()> = Mutex::new(()); + use super::TEST_LOCK as LOCK; fn line(level: &str, target: &str, msg: &str) -> String { format!("2026-11-18T13:18:37.676211Z {level:>5} {target}: {msg}\n") diff --git a/crates/failproofaid/src/main.rs b/crates/failproofaid/src/main.rs index 8ec543a1f..b910d4c76 100644 --- a/crates/failproofaid/src/main.rs +++ b/crates/failproofaid/src/main.rs @@ -9,6 +9,7 @@ mod lock; mod logfile; mod logship; mod paths; +mod self_report; mod server; mod telemetry; #[cfg(test)] @@ -272,6 +273,26 @@ fn run() -> Result<(), Box> { // WITHOUT root, against a system unit — takes effect without a restart. let mut audit_lane = audit_lane::spawn(shutdown.clone()); + // Self Reports: the `report` tool's MCP server on 127.0.0.1. Its own + // thread and runtime rather than a collector task, because the collector + // runs only with an ingest credential and an OSS machine needs this too. + // Always listening; `tools/list` is empty while Self Reports is off. On by + // default: a missing `self-report.json` reads as on unless this machine is + // Cloud enrolled, and the server asks the same enrolment check the policy + // poll uses. A busy port logs a warning and the daemon carries on. + fpai_collect::self_report::set_enrolment_check(std::sync::Arc::new( + cloud_client::self_report_enrolled, + )); + let (self_report_listening, self_report_ready) = std::sync::mpsc::channel(); + let mut self_report_mcp = paths::failproofai_home().ok().and_then(|home| { + fpai_collect::self_report::spawn( + home, + self_report::port(), + shutdown.clone(), + self_report_listening, + ) + }); + // Handled rather than `?`-ed, because a bare `?` here returns past every // join below — including the telemetry flush — so a daemon that cannot bind // its socket would buffer `daemon_started` and then take it to the grave. @@ -293,6 +314,11 @@ fn run() -> Result<(), Box> { } }; tracing::info!("listening on {}", socket_path.display()); + // Self Reports: once the MCP server is listening and this socket is bound, + // re-run the agent sync so agents registered over stdio while the daemon + // was down move to its HTTP server (the sync's live check pings this + // socket and the MCP port). Only when Self Reports is on. + self_report::spawn_startup_sync(self_report_ready, shutdown.clone()); let run_result = srv.run_until(shutdown); @@ -314,6 +340,7 @@ fn run() -> Result<(), Box> { // waits on its child and kills the process group rather than waiting the // scan out, so a `systemctl stop` is never held up by an audit. join_lane(&mut audit_lane); + join_lane(&mut self_report_mcp); // Joined BEFORE the stop event is recorded, so nothing contends with the // final send. `run_result` is what distinguishes the two ways this daemon diff --git a/crates/failproofaid/src/self_report.rs b/crates/failproofaid/src/self_report.rs new file mode 100644 index 000000000..c1086757c --- /dev/null +++ b/crates/failproofaid/src/self_report.rs @@ -0,0 +1,1294 @@ +//! Self Reports on a Cloud-managed machine: the desired-state field, the +//! effective settings file the daemon writes from it, and the sync it runs when +//! the feature flips (CONTRACT §4–§6). +//! +//! The daemon owns `self-report.json` only while the machine is Cloud +//! enrolled. Off Cloud the TypeScript CLI writes it from the local config, so +//! nothing here touches it then — except a file this daemon itself wrote for an +//! org the machine has since left, which is removed (a departed org's toggle +//! must not decide this machine any more). With the file gone the machine is an +//! open-source one, where Self Reports is on by default unless `config.json` +//! turned it off, so agents are re-synced to match. + +use std::io; +use std::path::{Path, PathBuf}; +use std::process::{Child, Command, Stdio}; +use std::sync::Mutex; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::time::{Duration, Instant}; + +use fpai_collect::self_report::{self as sr, Category, McpEndpoint, Settings}; +use serde_json::Value; + +/// `sync` is bounded: a wedged CLI must not hold a sync slot forever. +const SYNC_TIMEOUT: Duration = Duration::from_secs(60); + +/// The `selfReport` block of a desired-state response, as the server sent it. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct Desired { + pub enabled: bool, + /// `None`: the server sent none, so the defaults apply. + pub categories: Option>, + pub guidance: Option, +} + +/// Read `selfReport` off a desired-state body. Absent ⇒ `None` (disabled). +/// +/// Lenient on purpose: this rides the policy response, and a malformed block +/// must not refuse the policies beside it. An `enabled` that is not `true` +/// reads as off; a category without a string name and description is dropped. +pub fn decode(raw: &Value) -> Option { + let block = raw.get("selfReport")?.as_object()?; + let categories = block + .get("categories") + .and_then(Value::as_array) + .map(|items| { + items + .iter() + .filter_map(|item| { + Some(Category { + name: item.get("name")?.as_str()?.to_string(), + description: item.get("description")?.as_str()?.to_string(), + }) + }) + .collect() + }); + Some(Desired { + enabled: block.get("enabled").and_then(Value::as_bool) == Some(true), + categories, + guidance: block + .get("guidance") + .and_then(Value::as_str) + .map(str::to_string), + }) +} + +/// The last accepted response's block, waiting for the maintenance lane to +/// apply it. Outer `None`: no fresh response since the last apply. The lane +/// writes it bound to the enrolment that polled ([`tick`]). +static PENDING: Mutex>> = Mutex::new(None); + +/// Called with every ACCEPTED desired-state response. +pub fn note_desired(desired: Option) { + *PENDING.lock().unwrap_or_else(|p| p.into_inner()) = Some(desired); +} + +pub(crate) fn take_pending() -> Option> { + PENDING.lock().unwrap_or_else(|p| p.into_inner()).take() +} + +/// The settings the file should hold for this response. +pub fn effective(desired: Option<&Desired>, port: u16, updated_at: String) -> Settings { + let enabled = desired.is_some_and(|d| d.enabled); + Settings { + version: sr::SETTINGS_VERSION, + enabled, + source: "cloud".to_string(), + categories: sr::sanitize_categories(desired.and_then(|d| d.categories.as_deref())), + guidance: sr::sanitize_guidance(desired.and_then(|d| d.guidance.as_deref())), + mcp: McpEndpoint::on_port(port), + updated_at, + enrolment: None, + } +} + +/// What one apply did. +#[derive(Debug, PartialEq, Eq)] +pub struct Applied { + pub written: bool, + /// What an agent's entry would be may have changed: agent configs need + /// `self-report sync`. + pub needs_sync: bool, +} + +/// Whether going from `previous` to `next` can change what `self-report sync` +/// writes into an agent's config. Everything an entry is built from does, and +/// while on, so do categories and guidance: the MCP server reads those on +/// every request, but Codex's global AGENTS.md block and Antigravity's plugin +/// rules carry a copy of the instructions, which only a sync rewrites: +/// +/// - no file before: this is the first Cloud write. Before it the machine was +/// either on by default (it just enrolled) or off while it waited for this +/// answer (`failproofai config` syncs then and removes every entry), so no +/// file says nothing about what the agents hold; +/// - `source`: a local file is set aside while the org's setting is awaited, +/// which reads as off, so an org "on" that matches the old local "on" still +/// has agents to register; +/// - `enrolment`: a file another enrolment wrote (a previous org) read as off +/// for this one, so the same holds; +/// - `enabled`, and the endpoint while on (its port is in the HTTP entries); +/// - categories and guidance while on (the always-on instruction copies). +fn entries_may_change(previous: Option<&Settings>, next: &Settings) -> bool { + let Some(previous) = previous else { + return true; + }; + previous.source != next.source + || previous.enrolment != next.enrolment + || previous.enabled != next.enabled + || (next.enabled + && (previous.mcp != next.mcp + || previous.categories != next.categories + || previous.guidance != next.guidance)) +} + +/// Write `path` for this response, only when its content (not `updatedAt`) +/// changed. +/// +/// `enrolment` is [`sr::enrolment_id`] of the credential whose poll produced +/// `desired`; readers honour the file only while the machine is enrolled as +/// that same credential. +pub fn apply( + path: &Path, + desired: Option<&Desired>, + port: u16, + enrolment: &str, +) -> io::Result { + let previous = sr::read_settings(path); + let mut next = effective(desired, port, now_rfc3339()); + next.enrolment = Some(enrolment.to_string()); + if previous.as_ref().is_some_and(|p| p.same_content(&next)) { + return Ok(Applied { + written: false, + needs_sync: false, + }); + } + sr::write_settings(path, &next)?; + Ok(Applied { + written: true, + needs_sync: entries_may_change(previous.as_ref(), &next), + }) +} + +/// The machine is not enrolled: remove a file this daemon wrote for Cloud. +/// Returns whether agent configs need a sync: the removed file was enabled, or +/// the open-source default that now applies (on, unless `config.json` says +/// off) differs from it. +pub fn release(path: &Path) -> io::Result { + let Some(previous) = sr::read_settings(path) else { + return Ok(false); + }; + if previous.source != "cloud" { + return Ok(false); + } + match std::fs::remove_file(path) { + Ok(()) => { + let now_on = path + .parent() + .and_then(|home| sr::effective_settings(home, &|| sr::Enrolment::NotEnrolled)) + .is_some_and(|s| s.enabled); + Ok(previous.enabled || now_on) + } + Err(err) if err.kind() == io::ErrorKind::NotFound => Ok(false), + Err(err) => Err(err), + } +} + +/// One maintenance-lane pass. `polled_as`: `Some(Some(id))` enrolled, with +/// [`sr::enrolment_id`] of the credential this pass polled with, +/// `Some(None)` definitely not enrolled, `None` unknown (credential +/// unreadable: change nothing). `current` is the enrolment right now. +pub fn tick( + polled_as: Option>, + current: &dyn Fn() -> sr::Enrolment, + withdrawn: &dyn Fn() -> bool, +) { + let Ok(home) = crate::paths::failproofai_home() else { + return; + }; + let path = sr::settings_path(&home); + match polled_as { + Some(Some(enrolment)) => { + let Some(desired) = take_pending() else { + return; + }; + // A disconnect that landed during the poll: its answer is not ours + // to apply any more. + if withdrawn() { + return; + } + // The credential changed while the poll was in flight (another + // org): this answer is the previous enrolment's. Drop it; the next + // poll answers for the new one, and until then readers find no + // file of this enrolment's and treat the feature as off. + if !pending_still_applies(&enrolment, ¤t()) { + tracing::info!( + "Self Reports: the Cloud credential changed during the poll; \ + waiting for the new enrolment's setting" + ); + return; + } + match apply(&path, desired.as_ref(), port(), &enrolment) { + Ok(Applied { + written: true, + needs_sync, + }) => { + tracing::info!( + "Self Reports {} by FailproofAI Cloud", + if desired.as_ref().is_some_and(|d| d.enabled) { + "enabled" + } else { + "disabled" + } + ); + if needs_sync { + spawn_sync(); + } + } + Ok(_) => {} + Err(err) => tracing::warn!( + "could not write {}: {err}; Self Reports settings unchanged", + path.display() + ), + } + } + Some(None) => { + // Drop any response still pending from before the disconnect. + let _ = take_pending(); + match release(&path) { + Ok(true) => { + tracing::info!( + "Self Reports settings from FailproofAI Cloud removed; \ + this machine's own setting applies" + ); + spawn_sync(); + } + Ok(false) => {} + Err(err) => tracing::warn!("could not remove {}: {err}", path.display()), + } + } + None => {} + } +} + +/// Whether an answer polled as `polled_as` may still be written: the machine +/// is enrolled right now as that same credential. +fn pending_still_applies(polled_as: &str, current: &sr::Enrolment) -> bool { + matches!(current, sr::Enrolment::Enrolled(Some(id)) if id == polled_as) +} + +/// Log one Self Reports event that arrived over the socket (`selfReportLog`): +/// the stdio server's MCP traffic, or a CLI sync's result. Written exactly as +/// the HTTP server's own events, so the machine logs hold both the same way. +/// The preview is scrubbed and cut again here: the sender is not trusted to. +pub fn log_remote(ev: &fpai_ipc::SelfReportLogEvent) { + let transport = match ev.transport.as_deref() { + Some("cli") => "cli", + _ => "stdio", + }; + sr::log_event(&sr::McpLog { + event: &ev.event, + transport, + agent: ev.agent.as_deref(), + outcome: ev.outcome.as_deref(), + reason: ev.reason.as_deref(), + category: ev.category.as_deref(), + known_category: ev.known_category, + raw_category: ev.raw_category.as_deref(), + session: ev.session.as_deref(), + detail: ev.preview.as_deref(), + summary: ev.summary.as_deref(), + }); +} + +/// Set on the sync child: print the sync's result on stdout (which this +/// daemon logs) rather than send it back over the socket. +pub const SYNC_LOG_ENV: &str = "FAILPROOFAI_SELF_REPORT_SYNC_LOG"; + +/// The MCP port, from `FAILPROOFAI_SELF_REPORT_PORT` once per process. +pub fn port() -> u16 { + static PORT: std::sync::OnceLock = std::sync::OnceLock::new(); + *PORT.get_or_init(sr::port_from_env) +} + +fn now_rfc3339() -> String { + time::OffsetDateTime::now_utc() + .format(&time::format_description::well_known::Rfc3339) + .unwrap_or_default() +} + +// ── `failproofai self-report sync` ─────────────────────────────────────────── + +/// How long the startup sync waits for the MCP server to report its bind. +const STARTUP_LISTEN_WAIT: Duration = Duration::from_secs(10); + +/// Whether the startup sync should run: Self Reports is on (a missing file is +/// on off Cloud; `sr::effective_settings`). +fn enabled_on_disk(home: &Path, enrolled: &dyn Fn() -> sr::Enrolment) -> bool { + sr::effective_settings(home, enrolled).is_some_and(|s| s.enabled) +} + +/// Run `failproofai self-report sync --quiet` once at startup, after the MCP +/// server has bound its port (or failed to: then the sync's live check finds +/// no endpoint and keeps agents on stdio, which is right), when the feature is +/// on. Off its own thread: the accept loop starts right after this returns, +/// and the sync child's ping waits in the socket's backlog until it does. +pub fn spawn_startup_sync( + listening: std::sync::mpsc::Receiver, + shutdown: std::sync::Arc, +) { + let started = std::thread::Builder::new() + .name("fpai-self-report-startup".to_string()) + .spawn(move || { + let bound = listening.recv_timeout(STARTUP_LISTEN_WAIT); + if shutdown.load(Ordering::Relaxed) { + return; + } + let Ok(home) = crate::paths::failproofai_home() else { + return; + }; + if !enabled_on_disk(&home, &*sr::enrolment_check()) { + return; + } + if bound != Ok(true) { + tracing::warn!("Self Reports MCP server is not listening; syncing agents to stdio"); + } + spawn_sync(); + }); + if let Err(err) = started { + tracing::warn!("could not start the Self Reports startup sync: {err}"); + } +} + +static SYNC_RUNNING: AtomicBool = AtomicBool::new(false); +static SYNC_AGAIN: AtomicBool = AtomicBool::new(false); + +/// Run `failproofai self-report sync --quiet` off the lane's thread. One at a +/// time: a flip while one runs queues exactly one more, since `sync` reads the +/// file afresh and is idempotent. +pub fn spawn_sync() { + SYNC_AGAIN.store(true, Ordering::SeqCst); + if SYNC_RUNNING.swap(true, Ordering::SeqCst) { + return; + } + let started = std::thread::Builder::new() + .name("fpai-self-report-sync".to_string()) + .spawn(|| { + loop { + while SYNC_AGAIN.swap(false, Ordering::SeqCst) { + run_sync_once(); + } + SYNC_RUNNING.store(false, Ordering::SeqCst); + // A request that arrived between the last swap and the store. + if !SYNC_AGAIN.load(Ordering::SeqCst) || SYNC_RUNNING.swap(true, Ordering::SeqCst) { + break; + } + } + }); + if let Err(err) = started { + SYNC_RUNNING.store(false, Ordering::SeqCst); + tracing::warn!("could not start the Self Reports sync: {err}"); + } +} + +/// The command that runs the CLI for `self-report sync`: the service unit's +/// `FAILPROOFAI_CLI_CMD` (the same one the audit lane runs), else a +/// `failproofai` found on `PATH` or in the npm/bun global bin directories. A +/// daemon started by hand in a container has no unit and so no +/// `FAILPROOFAI_CLI_CMD`, while the CLI an `npm install -g` put there is right +/// beside it. +fn sync_cli_command() -> Option { + crate::audit_lane::cli_command().or_else(|| { + let home = std::env::var_os("HOME").map(PathBuf::from); + let dirs = global_bin_dirs( + std::env::var_os("NPM_CONFIG_PREFIX") + .or_else(|| std::env::var_os("npm_config_prefix")) + .map(PathBuf::from), + home.as_deref(), + ); + find_cli(std::env::var_os("PATH").as_deref(), &dirs).map(|path| shell_quote(&path)) + }) +} + +/// npm's (and bun's) global bin directories, beyond `PATH`: `$NPM_CONFIG_PREFIX/bin`, +/// `~/.npm-global/bin`, `/usr/local/bin` (npm's default prefix in the Node +/// images), `~/.bun/bin`. +fn global_bin_dirs(npm_prefix: Option, home: Option<&Path>) -> Vec { + let mut dirs = Vec::new(); + if let Some(prefix) = npm_prefix.filter(|p| !p.as_os_str().is_empty()) { + dirs.push(prefix.join("bin")); + } + if let Some(home) = home { + dirs.push(home.join(".npm-global").join("bin")); + } + dirs.push(PathBuf::from("/usr/local/bin")); + if let Some(home) = home { + dirs.push(home.join(".bun").join("bin")); + } + dirs +} + +/// The first executable `failproofai` in `PATH`, then in `extra`. +fn find_cli(path_var: Option<&std::ffi::OsStr>, extra: &[PathBuf]) -> Option { + use std::os::unix::fs::PermissionsExt; + let on_path = path_var.map(|p| std::env::split_paths(p).collect::>()); + on_path + .unwrap_or_default() + .into_iter() + .chain(extra.iter().cloned()) + .filter(|dir| dir.is_absolute()) + .map(|dir| dir.join("failproofai")) + .find(|candidate| { + std::fs::metadata(candidate) + .is_ok_and(|m| m.is_file() && m.permissions().mode() & 0o111 != 0) + }) +} + +/// `path` as one `sh` word. +fn shell_quote(path: &Path) -> String { + format!("'{}'", path.display().to_string().replace('\'', "'\\''")) +} + +fn run_sync_once() { + let Some(cli) = sync_cli_command() else { + tracing::warn!( + "no FAILPROOFAI_CLI_CMD and no `failproofai` on PATH or in the npm global bin, \ + so Self Reports agent configs were not synced — run `failproofai self-report sync`" + ); + return; + }; + // The service runs as its user (`failproofaid@`, `User=` + an + // explicit `HOME=`), so the child inherits that account and home. Checked + // rather than assumed: a daemon started as root over someone else's home + // (`sudo -E`, a hand-written unit without `User=`) would have root rewrite + // that person's agent configs, and one whose home resolves to root's would + // register the server where the user's agents never look. + let home = match crate::paths::failproofai_home() { + Ok(home) => home, + Err(err) => { + tracing::warn!("Self Reports sync skipped: {err}"); + return; + } + }; + // SAFETY: geteuid has no preconditions and cannot fail. + let euid = unsafe { libc::geteuid() }; + if let Some(problem) = sync_identity_problem(&home, euid) { + tracing::warn!("Self Reports sync skipped: {problem}"); + return; + } + report_sync(run_with_timeout( + &format!("{cli} self-report sync --quiet"), + &home, + SYNC_TIMEOUT, + )); +} + +/// The daemon's log line for one sync child's exit. +fn report_sync(result: io::Result>) { + match result { + Ok(Some(0)) => tracing::info!("Self Reports agent configs synced"), + Ok(Some(code)) => tracing::warn!("`failproofai self-report sync` failed (exit {code})"), + Ok(None) => tracing::warn!("`failproofai self-report sync` was killed (timeout or signal)"), + Err(err) => tracing::warn!("could not run `failproofai self-report sync`: {err}"), + } +} + +/// Run `command` under `sh -c` in its own process group; kill the group after +/// `timeout`. `Ok(None)`: it ended by a signal (including the timeout's). +/// Why `self-report sync` must not run as this process for `home`, if it must +/// not: the home (`~/.failproofai`, else the directory that would hold it) +/// belongs to another account than the one the daemon runs as. +fn sync_identity_problem(home: &Path, euid: u32) -> Option { + use std::os::unix::fs::MetadataExt; + let probe = if home.exists() { + home + } else { + home.parent().unwrap_or(home) + }; + let owner = std::fs::metadata(probe).ok()?.uid(); + (owner != euid).then(|| { + format!( + "{} belongs to uid {owner} but the daemon runs as uid {euid}; run the service as that user \ + (failproofaid@) or run `failproofai self-report sync` as them", + probe.display() + ) + }) +} + +fn run_with_timeout(command: &str, home: &Path, timeout: Duration) -> io::Result> { + run_with_timeout_in(command, home, timeout, None) +} + +/// [`run_with_timeout`] with the child's whole environment given (tests: a +/// service's bare `PATH` and a scratch `HOME`, nothing inherited). +fn run_with_timeout_in( + command: &str, + home: &Path, + timeout: Duration, + only_env: Option<&[(&str, &std::ffi::OsStr)]>, +) -> io::Result> { + use std::os::unix::process::CommandExt; + let mut command = { + let mut c = Command::new("sh"); + c.arg("-c").arg(command); + if let Some(env) = only_env { + c.env_clear(); + for (k, v) in env { + c.env(k, v); + } + } + c + }; + let mut child = command + // The CLI resolves the same home the daemon read self-report.json from. + .env("FAILPROOFAI_HOME", home) + .env(SYNC_LOG_ENV, "stdout") + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .process_group(0) + .spawn()?; + let (done_tx, done_rx) = std::sync::mpsc::channel::<()>(); + let mut readers = 0; + for (label, pipe) in [ + ( + "stdout", + child + .stdout + .take() + .map(|p| Box::new(p) as Box), + ), + ( + "stderr", + child + .stderr + .take() + .map(|p| Box::new(p) as Box), + ), + ] { + // `sync --quiet` prints nothing on success and one line per agent it + // could not update on stderr, so a failure in the journal says which + // agent and why. stderr is a warning; anything on stdout is info. + if let Some(pipe) = pipe { + let done = done_tx.clone(); + std::thread::spawn(move || { + use std::io::BufRead; + for line in io::BufReader::new(pipe).lines().map_while(Result::ok) { + if label == "stderr" { + tracing::warn!("self-report sync: {line}"); + } else { + tracing::info!("self-report sync: {line}"); + } + } + let _ = done.send(()); + }); + readers += 1; + } + } + drop(done_tx); + let started = Instant::now(); + let code = loop { + if let Some(status) = child.try_wait()? { + break status.code(); + } + if started.elapsed() > timeout { + kill_group(&mut child); + break None; + } + std::thread::sleep(Duration::from_millis(100)); + }; + // Let the output reach the log ahead of the caller's verdict line, but + // never wait on a pipe some leftover grandchild still holds. + let deadline = Instant::now() + Duration::from_secs(1); + for _ in 0..readers { + let left = deadline.saturating_duration_since(Instant::now()); + if done_rx.recv_timeout(left).is_err() { + break; + } + } + Ok(code) +} + +fn kill_group(child: &mut Child) { + unsafe { + libc::kill(-(child.id() as libc::pid_t), libc::SIGKILL); + } + let _ = child.wait(); +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + use std::path::PathBuf; + + fn temp_path(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!( + "fpaid-self-report-{name}-{}-{:?}", + std::process::id(), + std::thread::current().id() + )); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir.join("self-report.json") + } + + #[test] + fn the_block_is_read_leniently() { + assert_eq!(decode(&json!({"schemaVersion": 2})), None); + assert_eq!(decode(&json!({"selfReport": "on"})), None); + assert_eq!( + decode(&json!({"selfReport": {"enabled": true}})), + Some(Desired { + enabled: true, + categories: None, + guidance: None + }) + ); + let d = decode(&json!({"selfReport": { + "enabled": "yes", + "categories": [{"name": "a", "description": "A."}, {"name": 3}, "x"], + "guidance": "Be brief." + }})) + .unwrap(); + assert!(!d.enabled, "only a real true enables"); + assert_eq!( + d.categories, + Some(vec![Category { + name: "a".into(), + description: "A.".into() + }]) + ); + assert_eq!(d.guidance.as_deref(), Some("Be brief.")); + } + + #[test] + fn absent_means_disabled_with_the_defaults() { + let s = effective(None, 4319, "t".into()); + assert!(!s.enabled); + assert_eq!(s.source, "cloud"); + assert_eq!(s.categories, sr::default_categories()); + assert_eq!(s.guidance, None); + assert_eq!(s.mcp.url, "http://127.0.0.1:4319/mcp"); + + let s = effective( + Some(&Desired { + enabled: true, + categories: Some(vec![]), + guidance: Some(" ".into()), + }), + 5000, + "t".into(), + ); + assert!(s.enabled); + assert_eq!(s.categories, sr::default_categories(), "never empty"); + assert_eq!(s.guidance, None); + assert_eq!(s.mcp.port, 5000); + } + + #[test] + fn the_file_is_rewritten_only_when_its_content_changes() { + let path = temp_path("apply"); + let on = Desired { + enabled: true, + categories: None, + guidance: None, + }; + + // First write, even while off: before it the machine was on by default + // (or off while it waited), so the agents' entries are unknown. + assert_eq!( + apply(&path, None, 4319, "enrolment-a").unwrap(), + Applied { + written: true, + needs_sync: true + } + ); + let first = std::fs::read_to_string(&path).unwrap(); + assert_eq!( + apply(&path, None, 4319, "enrolment-a").unwrap(), + Applied { + written: false, + needs_sync: false + } + ); + assert_eq!(std::fs::read_to_string(&path).unwrap(), first, "untouched"); + + assert_eq!( + apply(&path, Some(&on), 4319, "enrolment-a").unwrap(), + Applied { + written: true, + needs_sync: true + } + ); + assert!(sr::read_settings(&path).unwrap().enabled); + + // Categories changing syncs while on: Codex's AGENTS.md block and + // Antigravity's plugin rules carry a copy of the instructions. + let custom = Desired { + enabled: true, + categories: Some(vec![Category { + name: "x".into(), + description: "X.".into(), + }]), + guidance: None, + }; + assert_eq!( + apply(&path, Some(&custom), 4319, "enrolment-a").unwrap(), + Applied { + written: true, + needs_sync: true + } + ); + // The same categories again: nothing to write or sync. + assert_eq!( + apply(&path, Some(&custom), 4319, "enrolment-a").unwrap(), + Applied { + written: false, + needs_sync: false + } + ); + // A new port does, while enabled. + assert_eq!( + apply(&path, Some(&custom), 4400, "enrolment-a").unwrap(), + Applied { + written: true, + needs_sync: true + } + ); + assert_eq!( + apply(&path, None, 4400, "enrolment-a").unwrap(), + Applied { + written: true, + needs_sync: true + } + ); + let s = sr::read_settings(&path).unwrap(); + assert!(!s.enabled); + use std::os::unix::fs::PermissionsExt; + assert_eq!( + std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, + 0o644 + ); + } + + #[test] + fn the_first_cloud_write_syncs_even_when_it_matches_the_local_file() { + // The laptop run: `config` wrote a local, enabled file, then synced + // while enrolled (a local file then reads as off) and removed every + // entry. The org's first answer, "on", matched the old `enabled`. + let on = Desired { + enabled: true, + ..Default::default() + }; + let path = temp_path("first-cloud"); + assert_eq!( + apply(&path, Some(&on), 4319, "enrolment-a").unwrap(), + Applied { + written: true, + needs_sync: true + }, + "no file before" + ); + + let path = temp_path("local-to-cloud"); + let mut local = effective(Some(&on), 4319, "t".into()); + local.source = "local".into(); + sr::write_settings(&path, &local).unwrap(); + assert_eq!( + apply(&path, Some(&on), 4319, "enrolment-a").unwrap(), + Applied { + written: true, + needs_sync: true + }, + "a local file replaced by the org's" + ); + // From then on, only a change an entry or an instruction copy is + // built from syncs: new guidance while on does. + assert_eq!( + apply( + &path, + Some(&Desired { + enabled: true, + guidance: Some("Be brief.".into()), + ..Default::default() + }), + 4319, + "enrolment-a" + ) + .unwrap(), + Applied { + written: true, + needs_sync: true + } + ); + // New guidance while off does not: off removes every copy. + let off = Desired { + enabled: false, + guidance: Some("Be brief.".into()), + ..Default::default() + }; + apply(&path, Some(&off), 4319, "enrolment-a").unwrap(); + assert_eq!( + apply( + &path, + Some(&Desired { + guidance: Some("Be briefer.".into()), + ..off + }), + 4319, + "enrolment-a" + ) + .unwrap(), + Applied { + written: true, + needs_sync: false + } + ); + let _ = std::fs::remove_dir_all(path.parent().unwrap()); + } + + /// Review 4719314971: a file written for org A must not decide for org B. + /// The file is bound to the enrolment that polled; a switch rewrites it + /// and syncs, and until then a reader enrolled as B finds it off. + #[test] + fn a_cloud_file_is_bound_to_the_enrolment_that_wrote_it() { + let path = temp_path("bound"); + let home = path.parent().unwrap().to_path_buf(); + let on = Desired { + enabled: true, + ..Default::default() + }; + apply(&path, Some(&on), 4319, "enrolment-a").unwrap(); + assert_eq!( + sr::read_settings(&path).unwrap().enrolment.as_deref(), + Some("enrolment-a") + ); + let as_a = || sr::Enrolment::Enrolled(Some("enrolment-a".into())); + let as_b = || sr::Enrolment::Enrolled(Some("enrolment-b".into())); + let unknown = || sr::Enrolment::Enrolled(None); + assert!(enabled_on_disk(&home, &as_a), "A's own file"); + assert!( + !enabled_on_disk(&home, &as_b), + "A's file while enrolled as B" + ); + assert!(!enabled_on_disk(&home, &unknown), "credential unreadable"); + // B's first answer rewrites the file (same content otherwise) and syncs. + assert_eq!( + apply(&path, Some(&on), 4319, "enrolment-b").unwrap(), + Applied { + written: true, + needs_sync: true + } + ); + assert!(enabled_on_disk(&home, &as_b)); + assert!(!enabled_on_disk(&home, &as_a)); + // An answer polled as A is not written once the machine is B. + assert!(pending_still_applies("enrolment-b", &as_b())); + assert!(!pending_still_applies("enrolment-a", &as_b())); + assert!(!pending_still_applies("enrolment-a", &unknown())); + assert!(!pending_still_applies( + "enrolment-a", + &sr::Enrolment::NotEnrolled + )); + let _ = std::fs::remove_dir_all(home); + } + + #[test] + fn leaving_cloud_removes_only_a_cloud_file() { + let path = temp_path("release"); + assert!(!release(&path).unwrap(), "no file"); + + let mut local = effective(None, 4319, "t".into()); + local.source = "local".into(); + local.enabled = true; + sr::write_settings(&path, &local).unwrap(); + assert!(!release(&path).unwrap()); + assert!(path.exists(), "the CLI's own file is kept"); + + apply( + &path, + Some(&Desired { + enabled: true, + ..Default::default() + }), + 4319, + "enrolment-a", + ) + .unwrap(); + assert!( + release(&path).unwrap(), + "an enabled cloud file needs a sync" + ); + assert!(!path.exists()); + + // A disabled cloud file: the machine is open source now, where Self + // Reports is on by default, so agents need the sync too... + apply(&path, None, 4319, "enrolment-a").unwrap(); + assert!( + release(&path).unwrap(), + "off -> the open-source default (on)" + ); + assert!(!path.exists()); + + // ...unless config.json turned it off here: off stays off. + let home = path.parent().unwrap(); + std::fs::write( + home.join("config.json"), + r#"{"selfReport":{"enabled":false}}"#, + ) + .unwrap(); + apply(&path, None, 4319, "enrolment-a").unwrap(); + assert!( + !release(&path).unwrap(), + "a disabled one with a local off does not" + ); + assert!(!path.exists()); + let _ = std::fs::remove_dir_all(home); + } + + #[test] + fn a_sync_that_overruns_is_killed() { + let started = Instant::now(); + assert_eq!( + run_with_timeout( + "sleep 30", + &std::env::temp_dir(), + Duration::from_millis(300) + ) + .unwrap(), + None + ); + assert!(started.elapsed() < Duration::from_secs(5)); + assert_eq!( + run_with_timeout("exit 3", &std::env::temp_dir(), Duration::from_secs(5)).unwrap(), + Some(3) + ); + assert_eq!( + run_with_timeout("echo hi", &std::env::temp_dir(), Duration::from_secs(5)).unwrap(), + Some(0) + ); + } + + #[test] + fn the_startup_sync_runs_only_when_self_reports_is_on() { + let home = temp_path("startup").parent().unwrap().to_path_buf(); + let oss = || sr::Enrolment::NotEnrolled; + let cloud = || sr::Enrolment::Enrolled(Some("enrolment-a".into())); + assert!( + enabled_on_disk(&home, &oss), + "no file, open source: on by default" + ); + assert!( + !enabled_on_disk(&home, &cloud), + "no file, enrolled: off until written" + ); + let mut s = effective(None, 4319, "2026-11-26T00:00:00Z".into()); + s.enrolment = Some("enrolment-a".into()); + sr::write_settings(&sr::settings_path(&home), &s).unwrap(); + assert!(!enabled_on_disk(&home, &oss), "disabled"); + s.enabled = true; + sr::write_settings(&sr::settings_path(&home), &s).unwrap(); + assert!(enabled_on_disk(&home, &cloud), "enabled"); + std::fs::write(sr::settings_path(&home), "garbage").unwrap(); + assert!(!enabled_on_disk(&home, &oss), "unparsable: off"); + let _ = std::fs::remove_dir_all(&home); + } + + #[test] + fn sync_runs_only_as_the_owner_of_the_home() { + use std::os::unix::fs::MetadataExt; + let dir = temp_path("sync-identity"); + let home = dir.parent().unwrap().to_path_buf(); + let me = std::fs::metadata(&home).unwrap().uid(); + assert_eq!(sync_identity_problem(&home, me), None); + // A home that does not exist yet is judged by its parent. + assert_eq!(sync_identity_problem(&home.join(".failproofai"), me), None); + let other = me.wrapping_add(1); + let problem = sync_identity_problem(&home, other).expect("a mismatch is refused"); + assert!(problem.contains(&format!("uid {me}")), "{problem}"); + assert!(problem.contains(&format!("uid {other}")), "{problem}"); + let _ = std::fs::remove_dir_all(&home); + } + + #[test] + fn the_cli_is_found_on_path_then_in_the_global_bins() { + use std::os::unix::fs::PermissionsExt; + let root = temp_path("find-cli").parent().unwrap().to_path_buf(); + let (a, b, global) = (root.join("a"), root.join("b"), root.join("g/bin")); + for d in [&a, &b, &global] { + std::fs::create_dir_all(d).unwrap(); + } + let make = |dir: &Path, mode: u32| { + let f = dir.join("failproofai"); + std::fs::write(&f, "#!/bin/sh\n").unwrap(); + std::fs::set_permissions(&f, std::fs::Permissions::from_mode(mode)).unwrap(); + f + }; + // Not executable in `a`: skipped. Executable in `b`: found. + make(&a, 0o644); + let in_b = make(&b, 0o755); + let path = std::env::join_paths([&a, &b]).unwrap(); + assert_eq!(find_cli(Some(path.as_os_str()), &[]), Some(in_b)); + // Nothing on PATH: the global bin. + let in_global = make(&global, 0o755); + let empty = std::env::join_paths([&a]).unwrap(); + assert_eq!( + find_cli(Some(empty.as_os_str()), std::slice::from_ref(&global)), + Some(in_global) + ); + assert_eq!(find_cli(None, std::slice::from_ref(&a)), None); + // A relative PATH entry is never used. + assert_eq!(find_cli(Some(std::ffi::OsStr::new("relative")), &[]), None); + + let dirs = global_bin_dirs(Some(root.join("g")), Some(Path::new("/home/u"))); + assert_eq!(dirs[0], global); + assert!(dirs.contains(&PathBuf::from("/home/u/.npm-global/bin"))); + assert!(dirs.contains(&PathBuf::from("/usr/local/bin"))); + assert_eq!( + shell_quote(Path::new("/x/it's/failproofai")), + "'/x/it'\\''s/failproofai'" + ); + let _ = std::fs::remove_dir_all(&root); + } + + #[test] + fn the_sync_child_gets_the_daemons_home() { + let dir = temp_path("sync-env"); + let home = dir.parent().unwrap().to_path_buf(); + let out = home.join("seen"); + let code = run_with_timeout( + &format!("printf %s \"$FAILPROOFAI_HOME\" > '{}'", out.display()), + &home, + Duration::from_secs(10), + ) + .unwrap(); + assert_eq!(code, Some(0)); + assert_eq!( + std::fs::read_to_string(&out).unwrap(), + home.display().to_string() + ); + let _ = std::fs::remove_dir_all(&home); + } + + /// A machine laid out like an nvm install run by a service: `node` and + /// npm's `failproofai` link side by side in `/nvm/bin`, the package's + /// `dist/cli.mjs` (here a shim that runs this checkout's CLI with bun) in + /// `lib/node_modules`, and a scratch `HOME`. Nothing is inherited from the + /// test's environment, so no real agent config is ever read or written. + struct ServiceMachine { + root: PathBuf, + home: PathBuf, + bin: PathBuf, + /// How the service runs the CLI: ` …/dist/cli.mjs`. + cli: String, + } + + impl ServiceMachine { + fn new(name: &str) -> Self { + let root = temp_path(name).parent().unwrap().to_path_buf(); + let home = root.join("home"); + let bin = root.join("nvm").join("bin"); + let pkg = root.join("nvm/lib/node_modules/failproofai/dist"); + std::fs::create_dir_all(home.join(".failproofai")).unwrap(); + std::fs::create_dir_all(&bin).unwrap(); + std::fs::create_dir_all(&pkg).unwrap(); + let bun = std::env::var_os("PATH") + .and_then(|p| find_named(&p, "bun")) + .expect("bun on PATH (cargo test runs the TypeScript CLI with it)"); + // A real file, not a symlink: bun reports a symlink's target as its + // execPath, and the point is the `node` the service was given. + let node = bin.join("node"); + if std::fs::hard_link(&bun, &node).is_err() { + std::fs::copy(&bun, &node).unwrap(); + } + let repo_cli = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../bin/failproofai.mjs"); + let cli_mjs = pkg.join("cli.mjs"); + std::fs::write( + &cli_mjs, + format!( + "#!/usr/bin/env node\nawait import({:?});\n", + repo_cli.canonicalize().unwrap().display().to_string() + ), + ) + .unwrap(); + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&cli_mjs, std::fs::Permissions::from_mode(0o755)).unwrap(); + } + std::os::unix::fs::symlink(&cli_mjs, bin.join("failproofai")).unwrap(); + let cli = format!("{} {}", shell_quote(&node), shell_quote(&cli_mjs)); + ServiceMachine { + root, + home, + bin, + cli, + } + } + + fn fp_home(&self) -> PathBuf { + self.home.join(".failproofai") + } + + /// Run ` ` with `PATH`, the scratch `HOME`, and nothing else. + fn run(&self, args: &str, path: &str) -> Option { + let env: [(&str, &std::ffi::OsStr); 3] = [ + ("PATH", std::ffi::OsStr::new(path)), + ("HOME", self.home.as_os_str()), + ("FAILPROOFAI_TELEMETRY_DISABLED", std::ffi::OsStr::new("1")), + ]; + run_with_timeout_in( + &format!("{} {args}", self.cli), + &self.fp_home(), + SYNC_TIMEOUT, + Some(&env), + ) + .unwrap() + } + + /// The agent configs that hold a `failproofai_local` entry. + fn registered(&self) -> Vec<&'static str> { + [ + ("claude", ".claude.json"), + ("codex", ".codex/config.toml"), + ("cursor", ".cursor/mcp.json"), + ("copilot", ".copilot/mcp-config.json"), + ("factory", ".factory/mcp.json"), + ("devin", ".config/devin/mcp_config.json"), + ] + .into_iter() + .filter(|(_, file)| { + std::fs::read_to_string(self.home.join(file)) + .is_ok_and(|text| text.contains("failproofai_local")) + }) + .map(|(agent, _)| agent) + .collect() + } + + fn config(&self, file: &str) -> String { + std::fs::read_to_string(self.home.join(file)).unwrap_or_default() + } + } + + impl Drop for ServiceMachine { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.root); + } + } + + fn find_named(path: &std::ffi::OsStr, name: &str) -> Option { + std::env::split_paths(path) + .map(|dir| dir.join(name)) + .find(|p| p.is_file()) + .and_then(|p| p.canonicalize().ok()) + } + + const HOOKED: &str = "claude codex cursor copilot factory devin"; + + /// The laptop run, end to end: no settings file; `config` (here its hook + /// install) runs while the machine is enrolled with no org setting yet, + /// which is off, so its sync registers nothing; then the daemon writes the + /// org's "on". That first Cloud write must sync, and the sync, run the way + /// the service runs it (bare PATH, ` dist/cli.mjs`), must register + /// every hooked agent with no manual `self-report sync`. + #[test] + fn the_first_cloud_write_after_an_enrolled_config_registers_every_hooked_agent() { + let m = ServiceMachine::new("cloud-first-sync"); + // A real enrolment: the org's file is bound to it, and the CLI's + // readers compute the same id from this credential. + std::fs::write( + m.fp_home().join("credentials.json"), + r#"{"cloud":{"url":"https://app.example.test","machine_id":"machine-1","token":"tok-org-a"}}"#, + ) + .unwrap(); + let enrolment = sr::enrolment_id("https://app.example.test", "machine-1", "tok-org-a"); + let settings = sr::settings_path(&m.fp_home()); + assert!(!settings.exists()); + + // `config` runs in the user's shell, where nvm's bin is on PATH. + let shell_path = format!("{}:/usr/bin:/bin", m.bin.display()); + assert_eq!( + m.run( + &format!("policies --install --cli {HOOKED} --scope user"), + &shell_path + ), + Some(0) + ); + assert!( + !settings.exists(), + "an enrolled machine waits for the org's setting" + ); + assert_eq!( + m.registered(), + Vec::<&str>::new(), + "enrolled with no setting is off" + ); + + // The daemon's maintenance lane, with the org's first answer. + let on = Desired { + enabled: true, + ..Default::default() + }; + let applied = apply(&settings, Some(&on), 4319, &enrolment).unwrap(); + assert_eq!( + applied, + Applied { + written: true, + needs_sync: true + } + ); + // The sync the lane spawns, under the service's environment. + assert_eq!(m.run("self-report sync --quiet", "/usr/bin:/bin"), Some(0)); + assert_eq!( + m.registered(), + vec!["claude", "codex", "cursor", "copilot", "factory", "devin"] + ); + // No daemon answers here, so every entry is stdio, on npm's link + // beside the service's node (on no PATH the service has). + let link = m.bin.join("failproofai").display().to_string(); + assert!( + m.config(".cursor/mcp.json").contains(&link), + "{}", + m.config(".cursor/mcp.json") + ); + assert!(m.config(".codex/config.toml").contains(&link)); + // And the same answer again changes nothing. + assert_eq!( + apply(&settings, Some(&on), 4319, &enrolment).unwrap(), + Applied { + written: false, + needs_sync: false + } + ); + } + + /// The startup sync under a service's PATH: `failproofai` is on no PATH + /// the service has and the CLI runs as `dist/cli.mjs`, so the only way to + /// a stdio command is npm's link beside the service's node. Without that + /// link every server-recorded agent fails and the sync exits 1. + #[test] + fn the_startup_sync_finds_the_cli_beside_the_services_node() { + let m = ServiceMachine::new("service-path"); + let shell_path = format!("{}:/usr/bin:/bin", m.bin.display()); + assert_eq!( + m.run( + &format!("policies --install --cli {HOOKED} --scope user"), + &shell_path + ), + Some(0) + ); + // Not enrolled and no file: on by default, so the install registered them. + assert_eq!(m.registered().len(), 6); + // Start over from no entries, then the daemon's startup sync. + for file in [ + ".claude.json", + ".codex/config.toml", + ".cursor/mcp.json", + ".copilot/mcp-config.json", + ".factory/mcp.json", + ".config/devin/mcp_config.json", + ] { + let _ = std::fs::remove_file(m.home.join(file)); + } + assert_eq!(m.run("self-report sync --quiet", "/usr/bin:/bin"), Some(0)); + assert_eq!(m.registered().len(), 6); + let link = m.bin.join("failproofai").display().to_string(); + assert!(m.config(".copilot/mcp-config.json").contains(&link)); + + // The control: without the link the same sync fails, as it did. + std::fs::remove_file(m.bin.join("failproofai")).unwrap(); + for file in [".cursor/mcp.json", ".copilot/mcp-config.json"] { + let _ = std::fs::remove_file(m.home.join(file)); + } + assert_eq!(m.run("self-report sync --quiet", "/usr/bin:/bin"), Some(1)); + } +} diff --git a/crates/failproofaid/src/server.rs b/crates/failproofaid/src/server.rs index 97e93cf5e..bf9af8348 100644 --- a/crates/failproofaid/src/server.rs +++ b/crates/failproofaid/src/server.rs @@ -321,6 +321,11 @@ pub fn handle_connection(stream: UnixStream, worker: &Worker) -> io::Result<()> Ok(msg) => msg, Err(_) => return Ok(()), // malformed frame: nothing to respond to, nothing to act on }; + // One-way: logged, and the connection closes with no reply. + if let ClientMessage::SelfReportLog { event, .. } = &request { + crate::self_report::log_remote(event); + return Ok(()); + } // The worker call is deliberately OUTSIDE the connection budget: it is our // own evaluation taking time, not the peer withholding bytes, and it has @@ -470,6 +475,12 @@ fn evaluate(request: ClientMessage, worker: &Worker) -> ServerMessage { match request { ClientMessage::Ping { .. } => ServerMessage::Pong { protocol_version: PROTOCOL_VERSION, + self_report: fpai_collect::self_report::listening().map(|port| { + fpai_ipc::SelfReportServer { + instance_id: fpai_collect::self_report::instance_id().to_string(), + port, + } + }), }, ClientMessage::Hook { hook_event, @@ -568,6 +579,14 @@ fn evaluate(request: ClientMessage, worker: &Worker) -> ServerMessage { }, } } + // `handle_connection` logs these and replies nothing; never reached. + ClientMessage::SelfReportLog { event, .. } => { + crate::self_report::log_remote(&event); + ServerMessage::Error { + protocol_version: PROTOCOL_VERSION, + message: "selfReportLog takes no reply".to_string(), + } + } } } @@ -691,7 +710,8 @@ mod tests { assert_eq!( response, ServerMessage::Pong { - protocol_version: PROTOCOL_VERSION + protocol_version: PROTOCOL_VERSION, + self_report: None } ); } @@ -1042,7 +1062,8 @@ mod tests { assert_eq!( response, ServerMessage::Pong { - protocol_version: 1 + protocol_version: 1, + self_report: None } ); @@ -1223,7 +1244,8 @@ mod tests { assert_eq!( response, ServerMessage::Pong { - protocol_version: PROTOCOL_VERSION + protocol_version: PROTOCOL_VERSION, + self_report: None } ); }) @@ -1264,7 +1286,8 @@ mod tests { assert_eq!( response, ServerMessage::Pong { - protocol_version: PROTOCOL_VERSION + protocol_version: PROTOCOL_VERSION, + self_report: None } ); } diff --git a/crates/failproofaid/tests/audit_lane_e2e.rs b/crates/failproofaid/tests/audit_lane_e2e.rs index 43913dd56..7ee03b3ca 100644 --- a/crates/failproofaid/tests/audit_lane_e2e.rs +++ b/crates/failproofaid/tests/audit_lane_e2e.rs @@ -144,9 +144,13 @@ fn read_schedule(home: &Path) -> serde_json::Value { /// A stand-in for the CLI: records that it ran (with the arguments the lane /// appended) and exits with `exit_code`. +/// The CLI the daemon runs, standing in for `failproofai audit`. It ignores the +/// `self-report sync` the daemon also runs at startup (Self Reports is on by +/// default, so a home with no `self-report.json` gets that sync too): only an +/// audit leaves the marker. fn stub_cli(marker: &Path, exit_code: i32) -> String { format!( - "sh -c 'printf \"%s\" \"$*\" > {} ; exit {exit_code}' fp", + "sh -c 'case \"$1\" in self-report) exit 0;; esac; printf \"%s\" \"$*\" > {} ; exit {exit_code}' fp", marker.display() ) } diff --git a/crates/failproofaid/tests/daemon_e2e.rs b/crates/failproofaid/tests/daemon_e2e.rs index 67eba1017..9054361c9 100644 --- a/crates/failproofaid/tests/daemon_e2e.rs +++ b/crates/failproofaid/tests/daemon_e2e.rs @@ -176,11 +176,15 @@ fn real_binary_answers_ping_over_a_real_socket() { ) .unwrap(); let response: ServerMessage = read_message(&mut stream).unwrap(); - assert_eq!( - response, - ServerMessage::Pong { - protocol_version: PROTOCOL_VERSION - } + assert!( + matches!( + response, + ServerMessage::Pong { + protocol_version: PROTOCOL_VERSION, + .. + } + ), + "{response:?}" ); let status = daemon.terminate(); @@ -226,11 +230,15 @@ fn a_second_daemon_on_the_same_socket_refuses_to_start() { ) .unwrap(); let response: ServerMessage = read_message(&mut stream).unwrap(); - assert_eq!( - response, - ServerMessage::Pong { - protocol_version: PROTOCOL_VERSION - } + assert!( + matches!( + response, + ServerMessage::Pong { + protocol_version: PROTOCOL_VERSION, + .. + } + ), + "{response:?}" ); first.terminate(); @@ -256,11 +264,15 @@ fn a_fresh_daemon_can_bind_again_after_the_previous_one_shut_down_cleanly() { ) .unwrap(); let response: ServerMessage = read_message(&mut stream).unwrap(); - assert_eq!( - response, - ServerMessage::Pong { - protocol_version: PROTOCOL_VERSION - } + assert!( + matches!( + response, + ServerMessage::Pong { + protocol_version: PROTOCOL_VERSION, + .. + } + ), + "{response:?}" ); second.terminate(); @@ -442,11 +454,15 @@ fn a_fifo_log_after_an_unclean_exit_does_not_stall_startup() { ) .unwrap(); let response: ServerMessage = read_message(&mut stream).unwrap(); - assert_eq!( - response, - ServerMessage::Pong { - protocol_version: PROTOCOL_VERSION - } + assert!( + matches!( + response, + ServerMessage::Pong { + protocol_version: PROTOCOL_VERSION, + .. + } + ), + "{response:?}" ); assert!(daemon.terminate().success()); } diff --git a/crates/failproofaid/tests/self_report_e2e.rs b/crates/failproofaid/tests/self_report_e2e.rs new file mode 100644 index 000000000..063decce6 --- /dev/null +++ b/crates/failproofaid/tests/self_report_e2e.rs @@ -0,0 +1,436 @@ +//! The real daemon binary serves the Self Reports MCP endpoint without any +//! ingest credential (an OSS machine), and a busy port never costs the +//! enforcement socket. +use std::io::BufRead; +use std::net::TcpListener; +use std::os::unix::net::UnixStream; +use std::path::PathBuf; +use std::process::{Child, Command, Stdio}; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; + +use fpai_ipc::{ClientMessage, PROTOCOL_VERSION, ServerMessage, read_message, write_message}; + +struct Daemon { + child: Child, + home: PathBuf, + log: Arc>, +} + +impl Drop for Daemon { + fn drop(&mut self) { + let _ = self.child.kill(); + let _ = self.child.wait(); + let _ = std::fs::remove_dir_all(&self.home); + } +} + +fn spawn(port: u16) -> Daemon { + let home = std::env::temp_dir().join(format!( + "fpai-self-report-daemon-{}", + fpai_collect::uploader::new_request_id() + )); + std::fs::create_dir_all(&home).unwrap(); + std::fs::write( + home.join("config.json"), + r#"{"telemetry":{"enabled":false},"audit":{"auto":false}}"#, + ) + .unwrap(); + let mut child = Command::new(env!("CARGO_BIN_EXE_failproofaid")) + .env("HOME", &home) + .env("FAILPROOFAI_HOME", &home) + .env( + "FAILPROOFAI_DAEMON_SOCKET", + home.join("run/failproofaid.sock"), + ) + .env("FAILPROOFAI_TELEMETRY_DISABLED", "1") + .env("FAILPROOFAI_SELF_REPORT_PORT", port.to_string()) + .stdout(Stdio::null()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + let log = Arc::new(Mutex::new(String::new())); + let sink = log.clone(); + let pipe = child.stderr.take().unwrap(); + std::thread::spawn(move || { + for line in std::io::BufReader::new(pipe).lines().map_while(Result::ok) { + let mut log = sink.lock().unwrap(); + log.push_str(&line); + log.push('\n'); + } + }); + Daemon { child, home, log } +} + +fn wait(what: &str, predicate: impl Fn() -> bool) { + let start = Instant::now(); + while !predicate() { + assert!( + start.elapsed() < Duration::from_secs(20), + "timed out: {what}" + ); + std::thread::sleep(Duration::from_millis(50)); + } +} + +fn ping(daemon: &Daemon) -> ServerMessage { + let mut stream = UnixStream::connect(daemon.home.join("run/failproofaid.sock")).unwrap(); + stream + .set_read_timeout(Some(Duration::from_secs(2))) + .unwrap(); + write_message( + &mut stream, + &ClientMessage::Ping { + protocol_version: PROTOCOL_VERSION, + }, + ) + .unwrap(); + let response: ServerMessage = read_message(&mut stream).unwrap(); + assert!(matches!(response, ServerMessage::Pong { .. })); + response +} + +fn pong_self_report(daemon: &Daemon) -> Option { + match ping(daemon) { + ServerMessage::Pong { self_report, .. } => self_report, + other => panic!("{other:?}"), + } +} + +fn initialize(port: u16) -> Option { + reqwest::blocking::Client::new() + .post(format!("http://127.0.0.1:{port}/mcp")) + .header("Content-Type", "application/json") + .body(r#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}"#) + .send() + .ok() + .and_then(|r| r.json::().ok()) +} + +fn free_port() -> u16 { + TcpListener::bind(("127.0.0.1", 0)) + .unwrap() + .local_addr() + .unwrap() + .port() +} + +#[test] +fn an_oss_daemon_serves_the_report_tool() { + let port = free_port(); + let daemon = spawn(port); + fpai_collect::self_report::write_settings( + &daemon.home.join("self-report.json"), + &fpai_collect::self_report::Settings { + version: 1, + enabled: true, + source: "local".into(), + categories: fpai_collect::self_report::default_categories(), + guidance: None, + mcp: fpai_collect::self_report::McpEndpoint::on_port(port), + updated_at: "2026-11-25T10:00:00Z".into(), + enrolment: None, + }, + ) + .unwrap(); + let client = reqwest::blocking::Client::new(); + let url = format!("http://127.0.0.1:{port}/mcp"); + let list = || { + client + .post(&url) + .header("Content-Type", "application/json") + .body(r#"{"jsonrpc":"2.0","id":1,"method":"tools/list"}"#) + .send() + .ok() + .and_then(|r| r.json::().ok()) + }; + wait("the MCP endpoint", || list().is_some()); + let reply = list().unwrap(); + assert_eq!(reply["result"]["tools"][0]["name"], "report"); + let call = client + .post(&url) + .body(r#"{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"report","arguments":{"category":"looping","detail":"d"}}}"#) + .send() + .unwrap() + .json::() + .unwrap(); + assert_eq!(call["result"]["content"][0]["text"], "Recorded."); + ping(&daemon); + // OSS: the daemon never writes the settings file itself. + let written = + fpai_collect::self_report::read_settings(&daemon.home.join("self-report.json")).unwrap(); + assert_eq!(written.source, "local"); +} + +#[test] +fn a_busy_self_report_port_never_costs_the_enforcement_socket() { + let holder = TcpListener::bind(("127.0.0.1", 0)).unwrap(); + let port = holder.local_addr().unwrap().port(); + let mut daemon = spawn(port); + wait("the busy-port warning", || { + daemon + .log + .lock() + .unwrap() + .contains("Self Reports MCP server off") + }); + wait("the socket", || { + daemon.home.join("run/failproofaid.sock").exists() + }); + ping(&daemon); + std::thread::sleep(Duration::from_millis(300)); + assert!(daemon.child.try_wait().unwrap().is_none(), "still running"); + assert_eq!( + daemon + .log + .lock() + .unwrap() + .matches("Self Reports MCP server off") + .count(), + 1, + "logged once, not restarted in a loop" + ); + drop(holder); +} + +/// Two daemons with separate homes and one port: the second's bind fails. Its +/// pong must say it serves no MCP endpoint, and the first's pong must name the +/// instance that answers the port, so a client of the second never takes the +/// first's endpoint for its own. +#[test] +fn the_pong_names_the_daemon_that_holds_the_mcp_port() { + let port = free_port(); + let first = spawn(port); + wait("the first daemon's MCP endpoint", || { + initialize(port).is_some() + }); + wait("the first daemon's socket", || { + first.home.join("run/failproofaid.sock").exists() + }); + let served = initialize(port).unwrap(); + let id = served["result"]["serverInfo"]["instanceId"] + .as_str() + .expect("an instanceId") + .to_string(); + let mine = pong_self_report(&first).expect("the first daemon serves MCP"); + assert_eq!(mine.instance_id, id); + assert_eq!(mine.port, port); + + let second = spawn(port); + wait("the second daemon's busy-port warning", || { + second + .log + .lock() + .unwrap() + .contains("Self Reports MCP server off") + }); + wait("the second daemon's socket", || { + second.home.join("run/failproofaid.sock").exists() + }); + assert_eq!(pong_self_report(&second), None); + // The port still answers, as the first daemon. + assert_eq!( + initialize(port).unwrap()["result"]["serverInfo"]["instanceId"], + id.as_str() + ); +} + +/// Every Self Reports MCP event lands in the daemon's log: the HTTP server's +/// own, and a stdio server's sent over the socket (`selfReportLog`, one-way: +/// no reply). The preview is scrubbed of secrets and cut short; nothing else +/// of the detail is logged. +#[test] +fn self_report_mcp_events_reach_the_daemon_log() { + let port = free_port(); + let daemon = spawn(port); + fpai_collect::self_report::write_settings( + &daemon.home.join("self-report.json"), + &fpai_collect::self_report::Settings { + version: 1, + enabled: true, + source: "local".into(), + categories: fpai_collect::self_report::default_categories(), + guidance: None, + mcp: fpai_collect::self_report::McpEndpoint::on_port(port), + updated_at: "2026-11-25T10:00:00Z".into(), + enrolment: None, + }, + ) + .unwrap(); + wait("the MCP endpoint", || initialize(port).is_some()); + wait("the socket", || { + daemon.home.join("run/failproofaid.sock").exists() + }); + let secret = "sk-ant-api03-abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGH"; + let detail = + format!("the key {secret} was rejected with a 401 and everything after this point is long"); + let call = serde_json::json!({ + "jsonrpc": "2.0", "id": 3, "method": "tools/call", + "params": {"name": "report", "arguments": {"category": "not_a_category", "detail": detail}} + }); + let client = reqwest::blocking::Client::new(); + let url = format!("http://127.0.0.1:{port}/mcp?agent=copilot"); + for body in [ + serde_json::json!({"jsonrpc": "2.0", "id": 2, "method": "tools/list"}), + call, + ] { + let reply = client + .post(&url) + .header("Content-Type", "application/json") + .body(body.to_string()) + .send() + .unwrap(); + assert!(reply.status().is_success()); + } + wait("the HTTP tools/call line", || { + daemon + .log + .lock() + .unwrap() + .contains("Self Reports MCP tools/call over http agent=copilot outcome=recorded") + }); + + // A stdio server's event, over the socket. + let mut stream = UnixStream::connect(daemon.home.join("run/failproofaid.sock")).unwrap(); + write_message( + &mut stream, + &ClientMessage::SelfReportLog { + protocol_version: PROTOCOL_VERSION, + event: fpai_ipc::SelfReportLogEvent { + event: "tools/call".into(), + agent: Some("hermes".into()), + transport: Some("stdio".into()), + outcome: Some("recorded".into()), + category: Some("looping".into()), + known_category: Some(true), + session: Some("sess-42".into()), + preview: Some(detail.clone()), + ..Default::default() + }, + }, + ) + .unwrap(); + // No reply: the daemon closes the connection. + stream + .set_read_timeout(Some(Duration::from_secs(5))) + .unwrap(); + let mut buf = [0u8; 1]; + assert_eq!(std::io::Read::read(&mut stream, &mut buf).unwrap(), 0); + wait("the stdio tools/call line", || { + daemon + .log + .lock() + .unwrap() + .contains("Self Reports MCP tools/call over stdio agent=hermes outcome=recorded") + }); + // The socket still answers after it. + ping(&daemon); + + let log = daemon.log.lock().unwrap().clone(); + assert!( + log.contains("Self Reports MCP tools/list over http agent=copilot"), + "{log}" + ); + assert!(log.contains("session=sess-42"), "{log}"); + // An unlisted category is a warning; a listed one is not. + let http_line = log + .lines() + .find(|l| l.contains("over http agent=copilot outcome=recorded")) + .unwrap(); + assert!(http_line.contains("WARN"), "{http_line}"); + // Recorded under the category it resolves to (the 401), naming what was sent. + assert!( + http_line.contains("category=\"invalid_tool_or_credential\" inferred_category=true raw_category=\"not_a_category\""), + "{http_line}" + ); + let stdio_line = log + .lines() + .find(|l| l.contains("over stdio agent=hermes")) + .unwrap(); + assert!(stdio_line.contains("INFO"), "{stdio_line}"); + assert!(!log.contains(secret), "the key reached the log:\n{log}"); + assert!(!log.contains("everything after this point"), "{log}"); +} + +/// F18 round 2: a JWT that starts inside the 40-character preview and runs +/// past the 2,000-character report cut is scrubbed from the daemon log over +/// both transports (HTTP: the daemon's own server; stdio: the frame the stdio +/// server now sends with the detail as sent). +#[test] +fn a_jwt_straddling_the_report_cut_never_reaches_the_daemon_log() { + let port = free_port(); + let daemon = spawn(port); + fpai_collect::self_report::write_settings( + &daemon.home.join("self-report.json"), + &fpai_collect::self_report::Settings { + version: 1, + enabled: true, + source: "local".into(), + categories: fpai_collect::self_report::default_categories(), + guidance: None, + mcp: fpai_collect::self_report::McpEndpoint::on_port(port), + updated_at: "2026-11-25T10:00:00Z".into(), + enrolment: None, + }, + ) + .unwrap(); + wait("the MCP endpoint", || initialize(port).is_some()); + wait("the socket", || { + daemon.home.join("run/failproofaid.sock").exists() + }); + let jwt = format!( + "eyJhbGciOiJIUzI1NiJ9.eyJ{}.{}", + "a".repeat(2500), + "b".repeat(43) + ); + let detail = format!("token {jwt} rejected"); + let call = serde_json::json!({ + "jsonrpc": "2.0", "id": 3, "method": "tools/call", + "params": {"name": "report", "arguments": {"category": "looping", "detail": detail}} + }); + let reply = reqwest::blocking::Client::new() + .post(format!("http://127.0.0.1:{port}/mcp?agent=copilot")) + .header("Content-Type", "application/json") + .body(call.to_string()) + .send() + .unwrap(); + assert!(reply.status().is_success()); + wait("the HTTP tools/call line", || { + daemon + .log + .lock() + .unwrap() + .contains("Self Reports MCP tools/call over http agent=copilot outcome=recorded") + }); + let mut stream = UnixStream::connect(daemon.home.join("run/failproofaid.sock")).unwrap(); + write_message( + &mut stream, + &ClientMessage::SelfReportLog { + protocol_version: PROTOCOL_VERSION, + event: fpai_ipc::SelfReportLogEvent { + event: "tools/call".into(), + agent: Some("claude".into()), + transport: Some("stdio".into()), + outcome: Some("recorded".into()), + category: Some("looping".into()), + known_category: Some(true), + preview: Some(detail.clone()), + ..Default::default() + }, + }, + ) + .unwrap(); + wait("the stdio tools/call line", || { + daemon + .log + .lock() + .unwrap() + .contains("Self Reports MCP tools/call over stdio agent=claude outcome=recorded") + }); + let log = daemon.log.lock().unwrap().clone(); + assert!( + !log.contains("eyJhbGci"), + "a JWT prefix reached the log:\n{log}" + ); + assert!(log.matches("[redacted:").count() >= 2, "{log}"); +} diff --git a/crates/fpai-collect/src/lib.rs b/crates/fpai-collect/src/lib.rs index c32c2fa8a..06d13f213 100644 --- a/crates/fpai-collect/src/lib.rs +++ b/crates/fpai-collect/src/lib.rs @@ -20,6 +20,7 @@ pub mod health; pub mod org_boundary; pub mod otlp; pub mod redact; +pub mod self_report; pub mod sources; pub mod spool; #[cfg(feature = "sqlite")] diff --git a/crates/fpai-collect/src/self_report.rs b/crates/fpai-collect/src/self_report.rs new file mode 100644 index 000000000..d9987c681 --- /dev/null +++ b/crates/fpai-collect/src/self_report.rs @@ -0,0 +1,2933 @@ +//! Self Reports: the `report` tool an agent calls when it is stuck. +//! +//! This module owns three things every other part reads the same way: +//! +//! - the effective settings file, `$FAILPROOFAI_HOME/self-report.json`, and the +//! tool built from it (name, description, input schema); +//! - the daemon's MCP server, Streamable HTTP on `127.0.0.1:/mcp`, +//! answering JSON (no SSE stream); +//! - the server-side fallback recording for agents whose hooks never see an +//! MCP call: such a call is written here as a `self_report` event in the SDK +//! spool format, so it reaches Cloud through the existing upload. +//! +//! The settings file is written by the daemon when the machine is Cloud +//! managed and by the TypeScript CLI otherwise. Self Reports is on by default: +//! a MISSING file means on with the default categories on a machine that is +//! not Cloud enrolled (unless `config.json`'s `selfReport.enabled` is `false`), +//! and off on an enrolled one until the daemon writes it. An unparsable file +//! always means off (see [`effective_settings`]). +//! +//! The server binds loopback only and refuses any request whose `Host` or +//! `Origin` is not this port on `127.0.0.1` / `localhost`, so a web page in a +//! browser cannot reach it (DNS rebinding or a cross-origin POST). It has no +//! auth, on purpose: everything it can do is append one report. + +use std::fs; +use std::io::{self, Write}; +use std::net::{Ipv4Addr, SocketAddr}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU32, AtomicU64, Ordering}; +use std::sync::{Arc, Mutex, OnceLock}; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +use axum::Router; +use axum::body::{Body, to_bytes}; +use axum::extract::{Request, State}; +use axum::http::{HeaderMap, Method, StatusCode}; +use axum::response::Response; +use axum::routing::any; +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; + +use crate::sources::hooks::transform::{self, HookRow}; +use crate::supervisor::{Shutdown, TaskError}; + +/// The settings file under the failproofai home. +pub const SETTINGS_FILE: &str = "self-report.json"; +/// Default loopback port of the MCP server. +pub const DEFAULT_PORT: u16 = 4319; +/// Overrides [`DEFAULT_PORT`]; read by the daemon at start. +pub const PORT_ENV: &str = "FAILPROOFAI_SELF_REPORT_PORT"; +/// MCP server name, as registered in each agent. +pub const SERVER_NAME: &str = "failproofai_local"; +/// The tool's name inside the MCP server. +pub const TOOL_NAME: &str = "report"; +/// The one thing a call ever returns. +pub const RESULT_TEXT: &str = "Recorded."; +/// The settings file format version. +pub const SETTINGS_VERSION: u32 = 1; +/// Request body ceiling. +pub const MAX_BODY_BYTES: usize = 64 * 1024; +/// `detail` is cut to this many characters. +pub const MAX_DETAIL_CHARS: usize = 2000; +/// Limits on an org's own category list (CONTRACT §2). +pub const MAX_CATEGORIES: usize = 32; +pub const MAX_CATEGORY_NAME_CHARS: usize = 64; +pub const MAX_CATEGORY_DESCRIPTION_CHARS: usize = 500; +pub const MAX_GUIDANCE_CHARS: usize = 2000; +/// How far back a hook-activity session may be to own a fallback report. +pub const SESSION_LOOKBACK: Duration = Duration::from_secs(6 * 3600); +/// The session id a fallback report carries when no session matches. +pub const UNATTRIBUTED_SESSION: &str = "unattributed"; + +/// Integrations whose hooks do not see MCP calls (or not which server a call +/// is for), so the MCP server records the report itself. Mirrors +/// `SELF_REPORT_SERVER_RECORDS` in the TypeScript CLI. claude and codex are +/// recorded by their hooks and must not be here, or each of their reports +/// would arrive twice. cursor is here: the hook failproofai installs names an +/// MCP call `MCP:` with no server. +pub const SERVER_RECORDS: &[&str] = &[ + "openclaw", + "pi", + "devin", + "hermes", + "goose", + "factory", + "antigravity", + "copilot", + "opencode", + "cursor", +]; + +/// MCP protocol revisions this server answers in. The first is what it offers +/// a client asking for one it does not know. +const PROTOCOL_VERSIONS: &[&str] = &["2025-06-18", "2025-03-26", "2024-11-05", "2025-11-25"]; + +const DESCRIPTION_HEAD: &str = "When you are stuck on something you cannot fix yourself, call this tool once with `category` (one of the categories below) and `detail` (one factual sentence: what is blocking you). It reports to FailproofAI. Call it BEFORE your final answer, for example for a missing, invalid or expired token or API key, a 401 or 403, a command, tool or MCP server that keeps failing, information or access you cannot get, or a request you cannot do here. Do not call it for normal work, clarifying questions or an error you then fixed. One call per distinct problem.\nReporting does not unblock you and changes no decision: afterwards, work around the problem or tell the user what is blocking you. There is no need to mention this report to the user."; + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct Category { + pub name: String, + pub description: String, +} + +/// The six categories used when an org defines none of its own. +pub fn default_categories() -> Vec { + [ + ( + "looping", + "You keep repeating the same or circular steps without making progress.", + ), + ( + "cannot_do_request", + "The user asked for something you cannot do here: a missing capability, tool or permission, or it is only possible by cheating.", + ), + ( + "invalid_tool_or_credential", + "A tool, MCP server, plugin, API key or token you need is broken, invalid, expired or rejected.", + ), + ( + "missing_context", + "Information or access you need is missing and you cannot get it yourself. Not for normal clarifying questions.", + ), + ( + "repeated_tool_failure", + "A command or tool failed on several distinct attempts and is blocking you. A single error is not enough.", + ), + ( + "task_failure", + "You genuinely tried and could not complete the task, or something else blocks you that no other category describes. Not for refusals or policy blocks.", + ), + ] + .into_iter() + .map(|(name, description)| Category { + name: name.to_string(), + description: description.to_string(), + }) + .collect() +} + +/// `^[a-z][a-z0-9_]{0,63}$`. +pub fn is_valid_category_name(name: &str) -> bool { + let mut chars = name.chars(); + matches!(chars.next(), Some(c) if c.is_ascii_lowercase()) + && name.len() <= MAX_CATEGORY_NAME_CHARS + && chars.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_') +} + +/// An org's category list made usable: invalid entries and duplicate names +/// dropped, over-long descriptions cut, at most [`MAX_CATEGORIES`]. Falls back +/// to the defaults when nothing usable is left, because an enabled tool with +/// an empty enum could never be called. +pub fn sanitize_categories(categories: Option<&[Category]>) -> Vec { + let mut out: Vec = Vec::new(); + for category in categories.unwrap_or_default() { + let description = category.description.trim(); + if !is_valid_category_name(&category.name) + || description.is_empty() + || out.iter().any(|c| c.name == category.name) + { + continue; + } + out.push(Category { + name: category.name.clone(), + description: truncate_chars(description, MAX_CATEGORY_DESCRIPTION_CHARS), + }); + if out.len() == MAX_CATEGORIES { + break; + } + } + if out.is_empty() { + default_categories() + } else { + out + } +} + +/// Guidance trimmed and capped; empty becomes `None`. +pub fn sanitize_guidance(guidance: Option<&str>) -> Option { + guidance + .map(str::trim) + .filter(|g| !g.is_empty()) + .map(|g| truncate_chars(g, MAX_GUIDANCE_CHARS)) +} + +pub fn truncate_chars(s: &str, max: usize) -> String { + match s.char_indices().nth(max) { + Some((at, _)) => s[..at].to_string(), + None => s.to_string(), + } +} + +/// What a detail cut down to nothing reads as +/// (test-fixtures/self-report/truncation.golden.json `detail_cut`). +pub const DETAIL_CUT_MARKER: &str = "[detail cut]"; + +/// The whitespace [`cut_detail`] splits on: ASCII only, so every +/// implementation agrees (Rust's `char::is_whitespace` is wider). +fn is_cut_whitespace(c: char) -> bool { + matches!(c, ' ' | '\t' | '\n' | '\r' | '\u{0c}' | '\u{0b}') +} + +/// A report's detail cut to `max` chars without leaving part of a token at +/// the end. A credential running past the cut (a long JWT or key) would +/// otherwise be kept as a fragment no secret scrubber recognises, and be +/// uploaded and logged as such. When the char right after the cut is not +/// whitespace, the trailing run of non-whitespace is dropped; then trailing +/// whitespace; an empty result is [`DETAIL_CUT_MARKER`]. Text that fits is +/// kept whole. The CLI (`selfReportCutDetail`) and both SDKs do the same; +/// truncation.golden.json `detail_cut` holds the cases. +pub fn cut_detail(s: &str, max: usize) -> String { + let Some((at, next)) = s.char_indices().nth(max) else { + return s.to_string(); + }; + let mut head = &s[..at]; + if !is_cut_whitespace(next) { + head = head.trim_end_matches(|c: char| !is_cut_whitespace(c)); + } + let head = head.trim_end_matches(is_cut_whitespace); + if head.is_empty() { + DETAIL_CUT_MARKER.to_string() + } else { + head.to_string() + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct McpEndpoint { + pub port: u16, + pub url: String, +} + +impl McpEndpoint { + pub fn on_port(port: u16) -> Self { + McpEndpoint { + port, + url: format!("http://127.0.0.1:{port}/mcp"), + } + } +} + +/// `self-report.json`. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct Settings { + pub version: u32, + pub enabled: bool, + /// `cloud` | `local`. + pub source: String, + pub categories: Vec, + pub guidance: Option, + pub mcp: McpEndpoint, + #[serde(rename = "updatedAt")] + pub updated_at: String, + /// A `cloud` file's enrolment: [`enrolment_id`] of the credential whose + /// poll wrote it. A cloud file decides only while the machine is enrolled + /// as that same credential; one left by a previous org (or one without + /// this field, from an older daemon) reads as missing until this + /// credential's own answer is written. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub enrolment: Option, +} + +impl Settings { + /// Equal in everything but when it was written. + pub fn same_content(&self, other: &Settings) -> bool { + Settings { + updated_at: String::new(), + ..self.clone() + } == Settings { + updated_at: String::new(), + ..other.clone() + } + } +} + +pub fn settings_path(home: &Path) -> PathBuf { + home.join(SETTINGS_FILE) +} + +/// The file, or `None` when it is missing, does not parse, or is not +/// [`SETTINGS_VERSION`] (the CLI's `readEffectiveSelfReport` refuses any other +/// version too, so every transport agrees on such a file). Readers that decide +/// whether the feature is on use [`effective_settings`], which tells a missing +/// file from a broken one. +pub fn read_settings(path: &Path) -> Option { + let text = fs::read_to_string(path).ok()?; + parse_settings(&text) +} + +/// `self-report.json`'s text as [`Settings`], only in the supported version. +pub fn parse_settings(text: &str) -> Option { + serde_json::from_str::(text) + .ok() + .filter(|s| s.version == SETTINGS_VERSION) +} + +/// Whether a file that parsed may decide anything (identical to the CLI's +/// `resolveSelfReport`): +/// +/// - not enrolled: the file decides (a `cloud` one is released by the daemon's +/// next tick); +/// - enrolled: only a `cloud` file written for THIS enrolment +/// (`enrolment == Some(current id)`). This machine's own file, a file the +/// previous org's poll wrote, and any file while the credential cannot be +/// read (no current id) are set aside: off until this enrolment's answer is +/// written, exactly as with no file at all. +fn authoritative(settings: Settings, enrolment: &dyn Fn() -> Enrolment) -> Option { + match enrolment() { + Enrolment::NotEnrolled => Some(settings), + Enrolment::Enrolled(current) => { + (settings.source == "cloud" && current.is_some() && settings.enrolment == current) + .then_some(settings) + } + } +} + +/// Which Cloud enrolment this machine is under, for the settings readers. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Enrolment { + NotEnrolled, + /// Enrolled, as [`enrolment_id`] of the credential; `None` when the + /// credential cannot be read (enrolled, identity unknown). + Enrolled(Option), +} + +impl Enrolment { + pub fn is_enrolled(&self) -> bool { + matches!(self, Enrolment::Enrolled(_)) + } +} + +/// The id a `cloud` settings file is bound to: a hash of the Cloud URL, the +/// machine id and the token, so a switch to another org (whose token differs +/// even when the machine id is kept) or a re-enrolment changes it. One-way +/// and truncated: the file is world-readable. Same value as the CLI's +/// `selfReportEnrolmentId`. +pub fn enrolment_id(url: &str, machine_id: &str, token: &str) -> String { + use sha2::{Digest, Sha256}; + let mut hasher = Sha256::new(); + hasher.update(b"failproofai self-report enrolment v1"); + for part in [url, machine_id, token] { + hasher.update((part.len() as u64).to_be_bytes()); + hasher.update(part.as_bytes()); + } + hasher.finalize()[..16] + .iter() + .map(|b| format!("{b:02x}")) + .collect() +} + +/// Which enrolment is this machine under? Asked on every read. The daemon +/// installs its own check (the same `Enrolment::resolve` its policy poll +/// uses) with [`set_enrolment_check`]. +pub type EnrolmentCheck = Arc Enrolment + Send + Sync>; + +static ENROLMENT_CHECK: OnceLock = OnceLock::new(); + +/// Install the enrolment check every reader in this process uses. First call wins. +pub fn set_enrolment_check(check: EnrolmentCheck) { + let _ = ENROLMENT_CHECK.set(check); +} + +/// The installed check; without one (no daemon in this process), not enrolled. +pub fn enrolment_check() -> EnrolmentCheck { + ENROLMENT_CHECK + .get() + .cloned() + .unwrap_or_else(|| Arc::new(|| Enrolment::NotEnrolled)) +} + +/// The settings a reader acts on (CONTRACT §4), identical to the TypeScript +/// `resolveSelfReport` in src/hooks/self-report.ts: +/// +/// - the file, when it is there and parses as version [`SETTINGS_VERSION`], +/// except, on a Cloud-enrolled machine, any file but a `cloud` one written +/// for this enrolment: `None`, off until the daemon writes the +/// organization's setting ([`authoritative`]); +/// - an unparsable, unreadable or other-version file: `None`, off (fail safe: +/// a half-written or hand-broken file must not turn recording on); +/// - a missing file on a Cloud-enrolled machine: `None`, off until the daemon +/// writes it from the org's setting; +/// - a missing file otherwise: on with the default categories, unless +/// `config.json`'s `selfReport.enabled` is `false` (an explicit off wins). +pub fn effective_settings(home: &Path, enrolled: &dyn Fn() -> Enrolment) -> Option { + match fs::read_to_string(settings_path(home)) { + Ok(text) => authoritative(parse_settings(&text)?, enrolled), + Err(err) if err.kind() == io::ErrorKind::NotFound => missing_file_settings(home, enrolled), + Err(_) => None, + } +} + +/// What a missing `self-report.json` means (see [`effective_settings`]). +fn missing_file_settings(home: &Path, enrolled: &dyn Fn() -> Enrolment) -> Option { + if enrolled().is_enrolled() || local_config_disabled(home) { + return None; + } + Some(default_settings(port_from_env())) +} + +/// On, local, the default categories, no guidance: what a machine with no +/// settings file and no explicit off runs. +pub fn default_settings(port: u16) -> Settings { + Settings { + version: SETTINGS_VERSION, + enabled: true, + source: "local".to_string(), + categories: default_categories(), + guidance: None, + mcp: McpEndpoint::on_port(port), + updated_at: String::new(), + enrolment: None, + } +} + +/// `config.json`'s `selfReport.enabled` is exactly `false`. +fn local_config_disabled(home: &Path) -> bool { + let Ok(text) = fs::read_to_string(home.join("config.json")) else { + return false; + }; + let Ok(root) = serde_json::from_str::(&text) else { + return false; + }; + root.get("selfReport") + .and_then(|b| b.get("enabled")) + .and_then(Value::as_bool) + == Some(false) +} + +/// Write the settings atomically (tmp + rename), mode 0644. +pub fn write_settings(path: &Path, settings: &Settings) -> io::Result<()> { + use std::os::unix::fs::OpenOptionsExt; + use std::os::unix::fs::PermissionsExt; + let dir = path + .parent() + .ok_or_else(|| io::Error::other("settings path has no parent"))?; + fs::create_dir_all(dir)?; + let mut text = serde_json::to_string_pretty(settings).map_err(io::Error::other)?; + text.push('\n'); + let tmp = dir.join(format!( + ".{SETTINGS_FILE}.{}.{}.tmp", + std::process::id(), + next_seq() + )); + let result = (|| { + let mut file = fs::OpenOptions::new() + .write(true) + .create_new(true) + .mode(0o644) + .open(&tmp)?; + // The umask may have taken bits off the mode above; readers run as + // other users (a system daemon writes, an agent reads), so set it. + file.set_permissions(fs::Permissions::from_mode(0o644))?; + file.write_all(text.as_bytes())?; + file.sync_all()?; + fs::rename(&tmp, path) + })(); + if result.is_err() { + let _ = fs::remove_file(&tmp); + } + result +} + +/// The port from [`PORT_ENV`], else [`DEFAULT_PORT`]. A value that is not a +/// port number falls back to the default with a warning. +pub fn port_from_env() -> u16 { + port_from(std::env::var(PORT_ENV).ok().as_deref()) +} + +pub fn port_from(raw: Option<&str>) -> u16 { + match raw.map(str::trim).filter(|v| !v.is_empty()) { + None => DEFAULT_PORT, + Some(v) => match v.parse::() { + Ok(port) if port > 0 => port, + _ => { + tracing::warn!("{PORT_ENV}={v:?} is not a port number; using {DEFAULT_PORT}"); + DEFAULT_PORT + } + }, + } +} + +/// The tool description (identical text in every implementation). +pub fn describe(categories: &[Category], guidance: Option<&str>) -> String { + let mut text = String::from(DESCRIPTION_HEAD); + text.push_str("\n\nCategories:"); + for category in categories { + text.push_str(&format!("\n- {}: {}", category.name, category.description)); + } + if let Some(g) = guidance.filter(|g| !g.is_empty()) { + text.push_str("\n\n"); + text.push_str(g); + } + text +} + +pub fn input_schema(categories: &[Category]) -> Value { + let names: Vec<&str> = categories.iter().map(|c| c.name.as_str()).collect(); + json!({ + "type": "object", + "properties": { + "category": {"type": "string", "enum": names}, + "detail": {"type": "string", "description": "One factual sentence: what is blocking you."} + }, + "required": ["category", "detail"], + "additionalProperties": false + }) +} + +/// The MCP server's `instructions` (identical text in the TypeScript stdio +/// server, `selfReportInstructions`). Claude Code defers MCP tools behind tool +/// search, so the model never reads the tool description up front; a server's +/// instructions go into the system prompt. The first sentence alone says what +/// to do: Codex's code mode keeps only about 250 characters of it. +pub fn instructions(categories: &[Category], guidance: Option<&str>) -> String { + let names: Vec<&str> = categories.iter().map(|c| c.name.as_str()).collect(); + let mut text = format!( + "When you are stuck, call failproofai_local's `report` tool once with `category` and \ + `detail` (one factual sentence: what is blocking you). Stuck means something you cannot \ + fix yourself: a missing or expired token or key, a 401 or 403, a command or tool that \ + keeps failing, information you cannot get, a request you cannot do. `category` is one \ + of: {}. Call it before your final answer, not when the task succeeded. It does not \ + unblock you, and there is no need to mention it to the user.", + names.join(", ") + ); + if let Some(g) = guidance.filter(|g| !g.is_empty()) { + text.push_str("\n\n"); + text.push_str(g); + } + text +} + +fn effective_categories(settings: &Settings) -> Vec { + if settings.categories.is_empty() { + default_categories() + } else { + settings.categories.clone() + } +} + +/// The initialize result's `instructions`, or `None` when the feature is off. +pub fn server_instructions(settings: Option<&Settings>) -> Option { + let settings = settings.filter(|s| s.enabled)?; + Some(instructions( + &effective_categories(settings), + settings.guidance.as_deref(), + )) +} + +/// The MCP tool definition, or `None` when the feature is off. +pub fn tool_definition(settings: Option<&Settings>) -> Option { + let settings = settings.filter(|s| s.enabled)?; + let categories = effective_categories(settings); + Some(json!({ + "name": TOOL_NAME, + "description": describe(&categories, settings.guidance.as_deref()), + "inputSchema": input_schema(&categories), + })) +} + +// ── Settings cache ─────────────────────────────────────────────────────────── + +/// `self-report.json`, re-read only when its mtime or size changes. A missing +/// file is resolved on every call ([`effective_settings`]): it is cheap, and an +/// enrolment or a `config.json` off must take effect on the next request. +struct SettingsCache { + home: PathBuf, + path: PathBuf, + enrolled: EnrolmentCheck, + state: Mutex)>>, +} + +impl SettingsCache { + fn new(home: &Path, enrolled: EnrolmentCheck) -> Self { + SettingsCache { + home: home.to_path_buf(), + path: settings_path(home), + enrolled, + state: Mutex::new(None), + } + } + + fn current(&self) -> Option { + let meta = match fs::metadata(&self.path) { + Ok(meta) => Some(meta), + Err(err) if err.kind() == io::ErrorKind::NotFound => { + *self.state.lock().unwrap_or_else(|p| p.into_inner()) = None; + return missing_file_settings(&self.home, &*self.enrolled); + } + Err(_) => None, + }; + let stamp = meta.and_then(|m| Some((m.modified().ok()?, m.len()))); + let mut state = self.state.lock().unwrap_or_else(|p| p.into_inner()); + let Some((mtime, len)) = stamp else { + *state = None; + return None; + }; + let settings = match state.as_ref() { + Some((cached_mtime, cached_len, settings)) + if *cached_mtime == mtime && *cached_len == len => + { + settings.clone() + } + _ => { + let settings = read_settings(&self.path); + *state = Some((mtime, len, settings.clone())); + settings + } + }; + drop(state); + // Asked on every call, not cached: an enrolment must take effect on + // the next request, even with the file unchanged. + authoritative(settings?, &*self.enrolled) + } +} + +// ── This daemon's identity ─────────────────────────────────────────────────── + +/// Random per process, sent as `serverInfo.instanceId` in the MCP +/// `initialize` result and in the daemon's IPC `Pong`. The CLI points agents at +/// the HTTP endpoint only when the two agree: a socket ping and a port probe +/// can otherwise reach two different daemons (another user's, or another +/// FAILPROOFAI_HOME's whose bind won the port), and the report would then be +/// recorded and uploaded under that daemon's home and credentials. +pub fn instance_id() -> &'static str { + static ID: OnceLock = OnceLock::new(); + ID.get_or_init(crate::uploader::new_request_id) +} + +/// The port this process's MCP listener is bound to, 0 while none is. +static LISTENING_PORT: AtomicU32 = AtomicU32::new(0); + +/// The port [`spawn`]'s listener holds right now, or `None` when it never +/// bound (a busy port) or has stopped. The daemon's `Pong` carries it. +pub fn listening() -> Option { + match LISTENING_PORT.load(Ordering::SeqCst) { + 0 => None, + port => u16::try_from(port).ok(), + } +} + +// ── The HTTP server ────────────────────────────────────────────────────────── + +struct Server { + home: PathBuf, + port: u16, + settings: SettingsCache, +} + +/// Start the daemon's MCP server on its own thread and its own small runtime. +/// +/// Not a collector task: the collector runs only with an ingest credential, +/// and OSS machines need this too. Not the collector's supervisor either, so it +/// never shows up in (or is cycled with) the collector's lifecycle. A busy +/// port logs one warning and the thread ends; the daemon carries on, as with +/// the OTLP relay. Stops when `shutdown` is set. +/// +/// `listening` hears `true` once the port is bound (connections are accepted +/// from then on) or `false` when it could not be; the daemon waits on it to +/// run its startup `self-report sync` against a server that is really there. +pub fn spawn( + home: PathBuf, + port: u16, + shutdown: Arc, + listening: std::sync::mpsc::Sender, +) -> Option> { + std::thread::Builder::new() + .name("fpai-self-report".to_string()) + .spawn(move || { + let runtime = match tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + { + Ok(rt) => rt, + Err(err) => { + tracing::warn!(%err, "Self Reports MCP server off: no runtime; daemon continues"); + let _ = listening.send(false); + return; + } + }; + runtime.block_on(async move { + let address = SocketAddr::from((Ipv4Addr::LOCALHOST, port)); + let listener = match tokio::net::TcpListener::bind(address).await { + Ok(listener) => listener, + Err(err) => { + tracing::warn!( + port, + %err, + "Self Reports MCP server off: loopback port unavailable; daemon continues" + ); + let _ = listening.send(false); + return; + } + }; + tracing::info!(port, "Self Reports MCP server listening on 127.0.0.1"); + LISTENING_PORT.store(u32::from(port), Ordering::SeqCst); + let _ = listening.send(true); + if let Err(err) = serve(listener, home, Shutdown::from_daemon(shutdown)).await { + tracing::warn!(%err, "Self Reports MCP server stopped"); + } + LISTENING_PORT.store(0, Ordering::SeqCst); + }); + }) + .inspect_err(|err| tracing::warn!(%err, "could not start the Self Reports MCP server")) + .ok() +} + +/// Serve on an already-bound listener until shutdown. The Host/Origin checks +/// use the listener's own port. +pub async fn serve( + listener: tokio::net::TcpListener, + home: PathBuf, + sd: Shutdown, +) -> Result<(), TaskError> { + serve_with_enrolment(listener, home, sd, enrolment_check()).await +} + +/// [`serve`] with an explicit enrolment check (tests; the daemon installs its +/// own with [`set_enrolment_check`]). +pub async fn serve_with_enrolment( + listener: tokio::net::TcpListener, + home: PathBuf, + sd: Shutdown, + enrolled: EnrolmentCheck, +) -> Result<(), TaskError> { + let port = listener + .local_addr() + .map_err(|e| TaskError(e.to_string()))? + .port(); + let server = Arc::new(Server { + settings: SettingsCache::new(&home, enrolled), + home, + port, + }); + let app = Router::new().route("/mcp", any(handle)).with_state(server); + axum::serve(listener, app) + .with_graceful_shutdown(async move { while sd.sleep(Duration::from_millis(100)).await {} }) + .await + .map_err(|e| TaskError(e.to_string())) +} + +fn status(code: StatusCode) -> Response { + Response::builder() + .status(code) + .body(Body::empty()) + .unwrap() +} + +fn json_response(code: StatusCode, body: &Value) -> Response { + Response::builder() + .status(code) + .header("Content-Type", "application/json") + .body(Body::from(body.to_string())) + .unwrap() +} + +/// `Host` must be this port on a loopback name; `Origin`, when sent, too. +fn allowed(headers: &HeaderMap, port: u16) -> bool { + let hosts = [format!("127.0.0.1:{port}"), format!("localhost:{port}")]; + let host_ok = headers + .get("host") + .and_then(|v| v.to_str().ok()) + .is_some_and(|h| hosts.iter().any(|ok| h.eq_ignore_ascii_case(ok))); + if !host_ok { + return false; + } + match headers.get("origin") { + None => true, + Some(origin) => origin.to_str().ok().is_some_and(|o| { + hosts + .iter() + .any(|ok| o.eq_ignore_ascii_case(&format!("http://{ok}"))) + }), + } +} + +/// `?agent=` and `?cwd=` from the request URI. +#[derive(Debug, Default, Clone)] +struct Caller { + agent: Option, + cwd: Option, +} + +impl Caller { + fn from_query(query: Option<&str>) -> Self { + let mut caller = Caller::default(); + for pair in query.unwrap_or_default().split('&') { + let (key, value) = pair.split_once('=').unwrap_or((pair, "")); + let value = percent_decode(value); + if value.is_empty() { + continue; + } + match key { + "agent" => caller.agent = Some(value), + "cwd" => caller.cwd = Some(value), + _ => {} + } + } + caller + } +} + +fn percent_decode(s: &str) -> String { + let bytes = s.as_bytes(); + let mut out = Vec::with_capacity(bytes.len()); + let mut i = 0; + while i < bytes.len() { + match bytes[i] { + b'+' => out.push(b' '), + b'%' if i + 2 < bytes.len() => { + let hex = std::str::from_utf8(&bytes[i + 1..i + 3]).ok(); + match hex.and_then(|h| u8::from_str_radix(h, 16).ok()) { + Some(b) => { + out.push(b); + i += 2; + } + None => out.push(b'%'), + } + } + b => out.push(b), + } + i += 1; + } + String::from_utf8_lossy(&out).into_owned() +} + +async fn handle(State(server): State>, request: Request) -> Response { + if !allowed(request.headers(), server.port) { + return status(StatusCode::FORBIDDEN); + } + if request.method() != Method::POST { + // No SSE stream and no session to delete. + return Response::builder() + .status(StatusCode::METHOD_NOT_ALLOWED) + .header("Allow", "POST") + .body(Body::empty()) + .unwrap(); + } + let caller = Caller::from_query(request.uri().query()); + let Ok(body) = to_bytes(request.into_body(), MAX_BODY_BYTES).await else { + return status(StatusCode::PAYLOAD_TOO_LARGE); + }; + let Ok(message) = serde_json::from_slice::(&body) else { + return json_response( + StatusCode::BAD_REQUEST, + &rpc_error(Value::Null, -32700, "Parse error"), + ); + }; + let server2 = server.clone(); + let answer = tokio::task::spawn_blocking(move || match message { + Value::Array(batch) if !batch.is_empty() => { + let replies: Vec = batch + .into_iter() + .filter_map(|m| server2.dispatch(m, &caller)) + .collect(); + (!replies.is_empty()).then_some(Value::Array(replies)) + } + Value::Array(_) => Some(rpc_error(Value::Null, -32600, "Invalid Request")), + single => server2.dispatch(single, &caller), + }) + .await; + match answer { + Ok(Some(reply)) => json_response(StatusCode::OK, &reply), + // Only notifications (or responses) were sent. + Ok(None) => status(StatusCode::ACCEPTED), + Err(_) => status(StatusCode::INTERNAL_SERVER_ERROR), + } +} + +fn rpc_result(id: Value, result: Value) -> Value { + json!({"jsonrpc": "2.0", "id": id, "result": result}) +} + +fn rpc_error(id: Value, code: i64, message: &str) -> Value { + json!({"jsonrpc": "2.0", "id": id, "error": {"code": code, "message": message}}) +} + +impl Server { + /// One JSON-RPC message. `None` for a notification or a client response. + fn dispatch(&self, message: Value, caller: &Caller) -> Option { + let Some(obj) = message.as_object() else { + return Some(rpc_error(Value::Null, -32600, "Invalid Request")); + }; + let method = obj.get("method").and_then(Value::as_str); + let id = obj.get("id").cloned(); + let Some(method) = method else { + // A response to something we never asked, or garbage. + return id.map(|id| rpc_error(id, -32600, "Invalid Request")); + }; + // A notification (`notifications/initialized`, `notifications/cancelled`…) + // gets no reply. + let id = id?; + let params = obj.get("params").cloned().unwrap_or(Value::Null); + Some(match method { + "initialize" => { + let asked = params.get("protocolVersion").and_then(Value::as_str); + let version = asked + .filter(|v| PROTOCOL_VERSIONS.contains(v)) + .unwrap_or(PROTOCOL_VERSIONS[0]); + let mut result = json!({ + "protocolVersion": version, + // listChanged is false: answers are plain JSON with no + // stream to push the notification on. A client sees a + // changed list on its next tools/list. + "capabilities": {"tools": {"listChanged": false}}, + "serverInfo": { + "name": SERVER_NAME, + "version": env!("CARGO_PKG_VERSION"), + "instanceId": instance_id(), + }, + }); + let current = self.settings.current(); + log_event(&McpLog { + event: "initialize", + transport: "http", + agent: caller.agent.as_deref(), + outcome: Some(if current.as_ref().is_some_and(|s| s.enabled) { + "on" + } else { + "off" + }), + ..Default::default() + }); + if let Some(text) = server_instructions(current.as_ref()) { + result["instructions"] = Value::String(text); + } + rpc_result(id, result) + } + "ping" => rpc_result(id, json!({})), + "tools/list" => { + let tools: Vec = tool_definition(self.settings.current().as_ref()) + .into_iter() + .collect(); + log_event(&McpLog { + event: "tools/list", + transport: "http", + agent: caller.agent.as_deref(), + outcome: Some(if tools.is_empty() { + "no tool (off)" + } else { + "report" + }), + ..Default::default() + }); + rpc_result(id, json!({"tools": tools})) + } + "tools/call" => { + let name = params.get("name").and_then(Value::as_str); + if name != Some(TOOL_NAME) { + log_event(&McpLog { + event: "tools/call", + transport: "http", + agent: caller.agent.as_deref(), + outcome: Some("skipped"), + reason: Some("unknown tool"), + ..Default::default() + }); + return Some(rpc_error(id, -32602, "Unknown tool")); + } + let args = params.get("arguments").cloned().unwrap_or(Value::Null); + self.record(&args, caller); + rpc_result( + id, + json!({"content": [{"type": "text", "text": RESULT_TEXT}], "isError": false}), + ) + } + _ => rpc_error(id, -32601, "Method not found"), + }) + } + + /// The fallback recording. A failure is logged and never reaches the agent: + /// the call's answer is `Recorded.` whatever happens here. + /// + /// Nothing is recorded unless the settings say enabled right now + /// ([`effective_settings`]: a missing file is on off Cloud): a client that + /// listed the tool before it was turned off (or that never listed it) can + /// still send a call. Read from disk, not the cache, so a disable is + /// honoured on the very next call (as the stdio server does). + fn record(&self, args: &Value, caller: &Caller) { + let mut report = Report::from_args(args); + let raw_category = report.category.clone(); + let mut log = McpLog { + event: "tools/call", + transport: "http", + agent: caller.agent.as_deref(), + outcome: Some("skipped"), + category: Some(&raw_category), + ..Default::default() + }; + // The log line gets the detail as sent, scrubbed whole before its cut. + let detail = Report::log_detail(args); + log.detail = Some(&detail); + let Some(agent) = caller + .agent + .as_deref() + .filter(|a| SERVER_RECORDS.contains(a)) + else { + log.reason = Some(if caller.agent.is_none() { + "no agent in the URL" + } else { + "its hook records it" + }); + log_event(&log); + return; + }; + let settings = match effective_settings(&self.home, &*self.settings.enrolled) { + Some(s) if s.enabled => s, + _ => { + log.reason = Some(if settings_unreadable(&self.home) { + "settings unreadable" + } else { + "Self Reports is off" + }); + log_event(&log); + return; + } + }; + // A missing, unlisted or misspelt category is recorded as the listed + // one it resolves to; the log keeps what the model sent. + let categories = effective_categories(&settings); + let names: Vec<&str> = categories.iter().map(|c| c.name.as_str()).collect(); + let (resolved, inferred) = resolve_category(&raw_category, &report.detail, &names); + report.category = resolved; + log.known_category = Some(!inferred); + log.category = Some(&report.category); + if inferred { + log.raw_category = Some(&raw_category); + } + let event = fallback_event(&self.home, agent, caller.cwd.as_deref(), &report, now_ms()); + let session = event + .get("session_id") + .and_then(Value::as_str) + .map(str::to_string); + log.session = session.as_deref(); + let failure; + match write_event_file(&self.home, &[event]) { + Ok(_) => log.outcome = Some("recorded"), + Err(err) => { + failure = format!("write failed: {err}"); + log.outcome = Some("failed"); + log.reason = Some(&failure); + } + } + log_event(&log); + } +} + +// ── Logging ────────────────────────────────────────────────────────────────── + +/// How much of a report's detail a log line carries, after secrets are +/// scrubbed from the whole detail. +pub const LOG_PREVIEW_CHARS: usize = 40; + +/// One Self Reports MCP event, as the daemon logs it: the HTTP server's own, +/// and the stdio server's and CLI syncs' that arrive over the socket +/// (`selfReportLog`, crates/PROTOCOL.md). +#[derive(Debug, Default, Clone)] +pub struct McpLog<'a> { + /// `initialize`, `tools/list`, `tools/call`, `sync` or `error`. + pub event: &'a str, + /// `http`, `stdio` or `cli`. + pub transport: &'a str, + pub agent: Option<&'a str>, + pub outcome: Option<&'a str>, + pub reason: Option<&'a str>, + pub category: Option<&'a str>, + pub known_category: Option, + /// What the model sent as the category (maybe empty), when `category` + /// was inferred from it ([`resolve_category`]). + pub raw_category: Option<&'a str>, + pub session: Option<&'a str>, + /// The report's detail; only [`log_preview`] of it is logged. + pub detail: Option<&'a str>, + pub summary: Option<&'a str>, +} + +/// The detail as a log line may show it: secrets scrubbed from the whole +/// text first (a cut token would no longer match), then one line, then the +/// first [`LOG_PREVIEW_CHARS`] characters. Machine logs can leave the machine +/// and scrub only the home directory and the machine key, so this is the +/// whole of what protects the detail. +/// +/// Cut on a character boundary, never inside a UTF-8 sequence, and marked +/// with an ASCII `...`: a three-byte `…` at the very end was the one place a +/// reader that caps the line by bytes split a character (`enviro\u{FFFD}`). +pub fn log_preview(detail: &str) -> String { + let scrubbed = crate::redact::scrub_str(detail).map_or_else(|| detail.to_string(), |(s, _)| s); + let flat: String = scrubbed + .chars() + .map(|c| if c.is_control() { ' ' } else { c }) + .collect(); + let flat = flat.trim(); + let cut = truncate_chars(flat, LOG_PREVIEW_CHARS); + if cut.len() < flat.len() { + format!("{}...", cut.trim_end()) + } else { + cut + } +} + +/// The longest agent-sent category [`log_category_text`] shows as written. +pub const LOG_CATEGORY_CHARS: usize = 32; + +/// A category the model sent, as a log line may show it: as written only +/// when it is shaped like a category name (lowercase ASCII letters, digits, +/// `_`, `-`, `.` or a space, starting with a letter, at most +/// [`LOG_CATEGORY_CHARS`] characters and at most 4 digits), else +/// `(N characters, not shown)`. The model can put anything in the field, a +/// token included, and machine logs can leave the machine; no credential +/// format is that short, lowercase and digit-poor. The TypeScript side +/// (`selfReportLogCategoryText`, src/hooks/self-report-names.ts) applies the +/// same rule to the hook's own log line. +pub fn log_category_text(raw: &str) -> String { + let n = raw.chars().count(); + let digits = raw.chars().filter(char::is_ascii_digit).count(); + let mut chars = raw.chars(); + let shaped = matches!(chars.next(), Some(c) if c.is_ascii_lowercase()) + && chars.all(|c| { + c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '_' | '.' | ' ' | '-') + }); + if raw.is_empty() || (shaped && n <= LOG_CATEGORY_CHARS && digits <= 4) { + raw.to_string() + } else { + format!("({n} characters, not shown)") + } +} + +/// The line [`log_event`] writes (without its level). +pub fn log_line(ev: &McpLog) -> String { + fn word(v: &str, max: usize) -> String { + let clean: String = v + .chars() + .map(|c| if c.is_control() { ' ' } else { c }) + .collect(); + truncate_chars(clean.trim(), max) + } + let mut line = format!( + "Self Reports MCP {} over {}", + word(ev.event, 32), + word(ev.transport, 16) + ); + let mut field = |key: &str, value: String| line.push_str(&format!(" {key}={value}")); + if let Some(v) = ev.agent { + field("agent", word(v, 64)); + } + if let Some(v) = ev.outcome { + field("outcome", word(v, 32)); + } + // `category` is the listed name a call resolved to, or, for a call that + // was skipped before resolving, what the model sent; either way it goes + // through the same rule as `raw_category`, which a listed name passes. + if let Some(v) = ev.category { + field("category", format!("{:?}", log_category_text(v))); + } + match (ev.known_category, ev.raw_category) { + (Some(false), Some(raw)) => { + field("inferred_category", "true".to_string()); + field("raw_category", format!("{:?}", log_category_text(raw))); + } + // A sender older than inference: it recorded the category as sent. + (Some(false), None) => field("unknown_category", "true".to_string()), + _ => {} + } + if let Some(v) = ev.session { + field("session", word(v, 128)); + } + if let Some(v) = ev.reason { + let v = crate::redact::scrub_str(v).map_or_else(|| v.to_string(), |(s, _)| s); + field("reason", format!("{:?}", word(&v, 300))); + } + if let Some(v) = ev.summary { + let v = crate::redact::scrub_str(v).map_or_else(|| v.to_string(), |(s, _)| s); + field("result", format!("{:?}", word(&v, 1000))); + } + if let Some(v) = ev.detail.filter(|d| !d.trim().is_empty()) { + field("preview", format!("{:?}", log_preview(v))); + } + line +} + +/// Log one event: WARN for a failure, an `error` event, a report whose +/// category was not on the settings' list as sent, or settings that cannot be read; +/// INFO otherwise. +pub fn log_event(ev: &McpLog) { + let line = log_line(ev); + let warn = ev.event == "error" + || ev.outcome == Some("failed") + || ev.known_category == Some(false) + || ev.reason == Some("settings unreadable"); + if warn { + tracing::warn!("{line}"); + } else { + tracing::info!("{line}"); + } +} + +/// Whether `self-report.json` is there but cannot be read or parsed. +fn settings_unreadable(home: &Path) -> bool { + let path = settings_path(home); + match fs::read_to_string(&path) { + Ok(text) => parse_settings(&text).is_none(), + Err(err) => err.kind() != io::ErrorKind::NotFound, + } +} + +// ── Recording ──────────────────────────────────────────────────────────────── + +/// Other names a model uses for `category` when it calls the tool without +/// loading its schema. Identical in the CLI (`SELF_REPORT_ARG_ALIASES`) and +/// both SDKs; test-fixtures/self-report/arg-aliases.json holds the list. +pub const CATEGORY_ALIASES: &[&str] = &["type", "kind"]; + +/// Other names for `detail` (seen live: `summary` and `sentence`). +pub const DETAIL_ALIASES: &[&str] = &[ + "summary", + "sentence", + "message", + "description", + "reason", + "text", + "details", +]; + +/// A call's arguments, as the model sent them ([`Server::record`] then +/// resolves the category with [`resolve_category`]); a missing or empty argument falls back to its first non-empty alias, else ""; +/// unknown keys are ignored. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Report { + pub category: String, + pub detail: String, +} + +impl Report { + pub fn from_args(args: &Value) -> Self { + Report { + category: arg_text(args, "category", CATEGORY_ALIASES), + detail: cut_detail(&arg_text(args, "detail", DETAIL_ALIASES), MAX_DETAIL_CHARS), + } + } + + /// The detail exactly as sent, for the log line only: [`log_preview`] + /// scrubs secrets from the whole of it before it cuts. Cutting to + /// [`MAX_DETAIL_CHARS`] first could split a credential that straddles the + /// cut (a JWT whose second segment runs past it) into something the + /// scrubber no longer recognises, and its start was logged (F18). Bounded + /// by the transport: the HTTP body is at most [`MAX_BODY_BYTES`]. + pub fn log_detail(args: &Value) -> String { + // Bounded without leaving part of a token at the bound either. + cut_detail(&arg_text(args, "detail", DETAIL_ALIASES), MAX_BODY_BYTES) + } +} + +/// The first non-empty string among `key` and its aliases. +fn arg_text(args: &Value, key: &str, aliases: &[&str]) -> String { + std::iter::once(key) + .chain(aliases.iter().copied()) + .filter_map(|k| args.get(k).and_then(Value::as_str)) + .find(|v| !v.is_empty()) + .unwrap_or_default() + .to_string() +} + +/// Keyword rules for a category the model did not name (or named wrongly), in +/// order: the first rule whose target is on the active list and whose keyword +/// appears in the lowercased `category + " " + detail` wins. Identical in the +/// CLI (`SELF_REPORT_CATEGORY_RULES`) and both SDKs; +/// test-fixtures/self-report/category-inference.json holds the rules and cases. +pub const CATEGORY_RULES: &[(&str, &[&str])] = &[ + ( + "invalid_tool_or_credential", + &[ + "token", + "api key", + "apikey", + "api_key", + "credential", + "unauthorized", + "unauthenticated", + "forbidden", + "401", + "403", + "expired", + "revoked", + "auth", + "password", + "secret", + ], + ), + ( + "looping", + &[ + "loop", + "looping", + "circular", + "in circles", + "repeating the same", + ], + ), + ( + "repeated_tool_failure", + &[ + "keeps failing", + "keep failing", + "repeatedly", + "several attempts", + "multiple attempts", + "retried", + "retries", + "again and again", + ], + ), + ( + "missing_context", + &[ + "missing", + "not found", + "no information", + "not provided", + "cannot find", + "can't find", + "need more information", + "unclear", + ], + ), + ( + "cannot_do_request", + &[ + "cannot", + "can't", + "unable", + "not possible", + "impossible", + "not supported", + "unsupported", + "not allowed", + ], + ), +]; + +/// The category a report falls back to when nothing matched, if it is listed. +pub const FALLBACK_CATEGORY: &str = "task_failure"; + +fn has_keyword(text: &str, keyword: &str) -> bool { + let word = |c: Option| c.is_some_and(|c| c.is_ascii_lowercase() || c.is_ascii_digit()); + text.match_indices(keyword).any(|(at, _)| { + !word(text[..at].chars().next_back()) && !word(text[at + keyword.len()..].chars().next()) + }) +} + +/// The category a report is recorded under, and whether it was inferred (is +/// not `raw` itself): `raw` when it is on `names`; else the listed name it +/// normalises to (lowercase, trimmed, runs of spaces and hyphens as `_`); else +/// the first [`CATEGORY_RULES`] rule that matches the category and detail and +/// targets a listed name; else [`FALLBACK_CATEGORY`] when listed, else the +/// first listed name. An empty list keeps `raw`. +pub fn resolve_category(raw: &str, detail: &str, names: &[&str]) -> (String, bool) { + if names.is_empty() || names.contains(&raw) { + return (raw.to_string(), false); + } + let mut normalised = String::new(); + let mut gap = false; + for c in raw.trim().to_lowercase().chars() { + if c.is_whitespace() || c == '-' { + if !gap { + normalised.push('_'); + } + gap = true; + } else { + normalised.push(c); + gap = false; + } + } + if names.contains(&normalised.as_str()) { + return (normalised, true); + } + let text = format!("{raw} {detail}").to_lowercase(); + for (target, keywords) in CATEGORY_RULES { + if names.contains(target) && keywords.iter().any(|k| has_keyword(&text, k)) { + return (target.to_string(), true); + } + } + let fallback = if names.contains(&FALLBACK_CATEGORY) { + FALLBACK_CATEGORY + } else { + names[0] + }; + (fallback.to_string(), true) +} + +/// How closely a hook row's cwd matches the caller's: 2 the same directory, +/// 1 an ancestor or descendant of it, 0 unrelated or unknown. Trailing slashes +/// are ignored; `/` is an ancestor of every absolute path. Same as +/// `selfReportCwdAffinity` in the CLI's stdio server. +pub fn cwd_affinity(want: &str, have: Option<&str>) -> u8 { + let Some(have) = have.filter(|h| !h.is_empty()) else { + return 0; + }; + let a = want.trim_end_matches('/'); + let b = have.trim_end_matches('/'); + if a == b { + return 2; + } + if a.is_empty() || b.is_empty() { + return 1; + } + let under = |child: &str, parent: &str| { + child + .strip_prefix(parent) + .is_some_and(|rest| rest.starts_with('/')) + }; + u8::from(under(b, a) || under(a, b)) +} + +/// The session a report from `integration` belongs to, in hook activity +/// within [`SESSION_LOOKBACK`] of `now_ms`, with the cwd its row had. Most +/// specific first when `cwd` is known: the newest session in exactly that +/// directory, else in one above or below it. +/// +/// Never a cross-project guess. When `cwd` is unknown (an HTTP call carries +/// only `?agent=`) or no row is related to it, the newest row is taken only if +/// every row of that integration in the window has the same cwd, i.e. there is +/// one project to choose from; otherwise `None`, and the report is +/// `unattributed`. The installer registers every agent recorded here over +/// stdio, where the CLI knows the server's real cwd; this guards a +/// hand-written or older HTTP registration. +pub fn find_session( + home: &Path, + integration: &str, + cwd: Option<&str>, + now_ms: i64, +) -> Option<(String, Option)> { + let dir = home.join("hook-activity"); + let oldest = now_ms - SESSION_LOOKBACK.as_millis() as i64; + let mut files = vec![dir.join("current.jsonl")]; + files.extend(pages_since(&dir, oldest)); + let mut best: Option<(u8, i64, String, Option)> = None; + // The distinct cwds seen, to tell one project from several. + let mut cwds: Vec> = Vec::new(); + for file in files { + let Ok(text) = read_tail(&file, 1024 * 1024) else { + continue; + }; + for line in text.lines() { + let Ok(row) = serde_json::from_str::(line.trim()) else { + continue; + }; + let Some(session) = row.session_id.as_deref().filter(|s| !s.is_empty()) else { + continue; + }; + if row.integration.as_deref() != Some(integration) || row.timestamp < oldest { + continue; + } + let row_cwd = row + .cwd + .as_deref() + .map(|c| c.trim_end_matches('/').to_string()); + if !cwds.contains(&row_cwd) { + cwds.push(row_cwd); + } + let rank = cwd.map_or(0, |want| cwd_affinity(want, row.cwd.as_deref())); + if best + .as_ref() + .is_some_and(|(r, at, _, _)| (*r, *at) >= (rank, row.timestamp)) + { + continue; + } + best = Some((rank, row.timestamp, session.to_string(), row.cwd.clone())); + } + } + match best { + Some((0, ..)) if cwds.len() > 1 => None, + Some((_, _, session, cwd)) => Some((session, cwd)), + None => None, + } +} + +/// Slack on a page's rotation stamp, as `ROTATION_CLOCK_SLACK_MS` in the CLI's +/// hook-activity store: a clock stepped back a little costs one more page read +/// rather than a row missed. +const ROTATION_CLOCK_SLACK_MS: i64 = 10 * 60 * 1000; + +/// Every archived activity page that can hold a row stamped at or after +/// `oldest_ms`, newest first. `current.jsonl` rotates to +/// `page--.jsonl` every 25 rows, so another busy project's +/// hooks can push a session's rows many pages back within the window; reading +/// only the newest pages lost them (and could see one project where there +/// were two). Every row in a page is at or before its rotation stamp, so the +/// listing stops at the first page rotated before the window opened, as the +/// CLI's `getHookActivityEntriesSince` does. +fn pages_since(dir: &Path, oldest_ms: i64) -> Vec { + let Ok(entries) = fs::read_dir(dir) else { + return Vec::new(); + }; + let mut pages: Vec<((i64, i64), PathBuf)> = entries + .filter_map(Result::ok) + .filter_map(|e| { + let name = e.file_name().into_string().ok()?; + let stem = name.strip_prefix("page-")?.strip_suffix(".jsonl")?; + let mut parts = stem.split('-'); + let at = parts.next()?.parse::().ok()?; + let seq = parts + .next() + .and_then(|p| p.parse::().ok()) + .unwrap_or(0); + Some(((at, seq), e.path())) + }) + .collect(); + pages.sort_by_key(|p| std::cmp::Reverse(p.0)); + pages + .into_iter() + .take_while(|((at, _), _)| *at >= oldest_ms - ROTATION_CLOCK_SLACK_MS) + .map(|(_, path)| path) + .collect() +} + +/// The last `max` bytes of a file, from the first whole line in them. +fn read_tail(path: &Path, max: u64) -> io::Result { + use std::io::{Read, Seek, SeekFrom}; + let mut file = fs::File::open(path)?; + let len = file.metadata()?.len(); + let start = len.saturating_sub(max); + file.seek(SeekFrom::Start(start))?; + let mut buf = Vec::new(); + file.read_to_end(&mut buf)?; + let mut text = String::from_utf8_lossy(&buf).into_owned(); + if start > 0 + && let Some(nl) = text.find('\n') + { + text.drain(..=nl); + } + Ok(text) +} + +/// The collector's `environment` label, as the hook events carry it. +fn environment(home: &Path) -> (String, crate::config::Redact) { + match crate::config::load(home) { + Ok(cfg) => (cfg.settings.environment, cfg.settings.redact), + Err(_) => { + let defaults = crate::config::Settings::default(); + (defaults.environment, defaults.redact) + } + } +} + +/// The `self_report` event the MCP server writes for an integration in +/// [`SERVER_RECORDS`]. +pub fn fallback_event( + home: &Path, + integration: &str, + cwd: Option<&str>, + report: &Report, + now_ms: i64, +) -> Value { + let found = find_session(home, integration, cwd, now_ms); + let (session_id, row_cwd) = match found { + Some((session, row_cwd)) => (session, row_cwd), + None => (UNATTRIBUTED_SESSION.to_string(), None), + }; + let identity = HookRow { + integration: Some(integration.to_string()), + cwd: row_cwd.or_else(|| cwd.map(str::to_string)), + ..Default::default() + }; + let (environment, redact) = environment(home); + let mut event = json!({ + "type": "self_report", + "session_id": session_id, + "agent_id": transform::agent_id(&identity), + "timestamp": transform::to_rfc3339_micros(now_ms, 0).unwrap_or_default(), + "environment": environment, + "category": report.category, + "detail": report.detail, + "source": "mcp", + "integration": integration, + }); + crate::redact::scrub_value(&mut event, redact); + event +} + +static SEQ: AtomicU64 = AtomicU64::new(0); + +fn next_seq() -> u64 { + SEQ.fetch_add(1, Ordering::Relaxed) +} + +fn now_ms() -> i64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_millis() as i64) + .unwrap_or(0) +} + +/// Write one batch into `/custom-agents/events/` in the SDK writer's +/// format: `event---.jsonl`, one JSON event +/// per line, written to `.tmp` (0600, exclusive), fsynced, then renamed. +pub fn write_event_file(home: &Path, events: &[Value]) -> io::Result { + use std::os::unix::fs::{DirBuilderExt, OpenOptionsExt}; + let dir = home.join("custom-agents").join("events"); + fs::DirBuilder::new() + .recursive(true) + .mode(0o700) + .create(&dir)?; + let now = time::OffsetDateTime::now_utc(); + const FMT: &[time::format_description::BorrowedFormatItem<'_>] = time::macros::format_description!( + "[year]-[month]-[day]T[hour]-[minute]-[second]-[subsecond digits:3]Z" + ); + let stamp = now.format(FMT).map_err(io::Error::other)?; + let stem = format!( + "event-{stamp}-{}-self-report-{}", + std::process::id(), + next_seq() + ); + let tmp = dir.join(format!("{stem}.tmp")); + let path = dir.join(format!("{stem}.jsonl")); + let mut content = String::new(); + for event in events { + content.push_str(&event.to_string()); + content.push('\n'); + } + let result = (|| { + let mut file = fs::OpenOptions::new() + .write(true) + .create_new(true) + .mode(0o600) + .open(&tmp)?; + file.write_all(content.as_bytes())?; + file.sync_all()?; + fs::rename(&tmp, &path) + })(); + if result.is_err() { + let _ = fs::remove_file(&tmp); + } + result.map(|()| path) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// F18: the stdio sender used to cut the detail to 200 characters before + /// sending it, so a JWT longer than that reached this scrubber in pieces + /// and its raw start was logged. The sender now sends the whole (bounded) + /// detail; this is what the daemon does with it. + #[test] + fn a_log_preview_scrubs_a_jwt_longer_than_two_hundred_characters() { + let jwt = format!( + "eyJhbGciOiJIUzI1NiJ9.eyJ{}.{}", + "a".repeat(250), + "b".repeat(43) + ); + assert!(jwt.len() > 200); + let preview = log_preview(&format!("token {jwt} rejected")); + assert!(!preview.contains("eyJhbGci"), "{preview}"); + assert!(preview.contains("[redacted:"), "{preview}"); + } + + /// F18 round 2: a JWT that starts in the preview and runs past the + /// 2,000-character report cut. Cut first, it has two segments and the + /// scrubber passes it; the log gets the detail as sent. + #[test] + fn a_jwt_straddling_the_report_cut_is_scrubbed_from_the_log_preview() { + let jwt = format!( + "eyJhbGciOiJIUzI1NiJ9.eyJ{}.{}", + "a".repeat(2500), + "b".repeat(43) + ); + let args = json!({"category": "looping", "detail": format!("token {jwt} rejected")}); + // The report itself keeps no part of the token (round 3). + let clipped = Report::from_args(&args).detail; + assert_eq!(clipped, "token"); + let raw = Report::log_detail(&args); + assert!(raw.ends_with(" rejected")); + let preview = log_preview(&raw); + assert!(!preview.contains("eyJhbGci"), "{preview}"); + assert!(preview.contains("[redacted:"), "{preview}"); + // The aliases resolve as for the report itself. + assert_eq!(Report::log_detail(&json!({"summary": "s"})), "s"); + } + + #[test] + fn a_category_is_logged_only_when_it_is_shaped_like_a_name() { + for name in [ + "", + "looping", + "token_expired", + "auth-failure", + "operator_blocker", + "error 401", + "v2.api_down", + ] { + assert_eq!(log_category_text(name), name); + } + for (raw, n) in [ + (format!("ghp_{}", "A".repeat(36)), 40), + ("AKIAIOSFODNN7EXAMPLE".to_string(), 20), + ("sk-proj-abc123def456ghi789".to_string(), 26), + ("d41d8cd98f00b204e9800998ecf8427e".to_string(), 32), + ("Looping".to_string(), 7), + ("a".repeat(33), 33), + ("token=hunter2".to_string(), 13), + ("ünïcode".to_string(), 7), + ] { + assert_eq!( + log_category_text(&raw), + format!("({n} characters, not shown)"), + "{raw}" + ); + } + } + + #[test] + fn a_log_preview_is_scrubbed_before_it_is_cut() { + // The key starts inside the first 40 characters and ends after them: + // cut first, the half left would no longer look like a key. + let detail = + "auth failed: sk-ant-api03-abcdefghijklmnopqrstuvwxyz0123456789 then more\nlines"; + let preview = log_preview(detail); + assert!(!preview.contains("abcdefghij"), "{preview}"); + assert!(preview.starts_with("auth failed: "), "{preview}"); + assert!( + preview.chars().count() <= LOG_PREVIEW_CHARS + 3, + "{preview}" + ); + assert!(!preview.contains('\n')); + assert_eq!(log_preview("short"), "short"); + assert_eq!( + log_preview(&"é".repeat(50)), + format!("{}...", "é".repeat(40)) + ); + } + + #[test] + fn a_log_preview_never_splits_a_character() { + // A multi-byte character at, just before and just after the cut. + let cases = [ + "deploy.sh requires a DEPLOY_TOKEN environment variable that is not set".to_string(), + format!("{}é and more", "a".repeat(LOG_PREVIEW_CHARS - 1)), + format!("{}😀😀 more", "a".repeat(LOG_PREVIEW_CHARS - 1)), + format!("{}中文字 more", "a".repeat(LOG_PREVIEW_CHARS - 2)), + "😀".repeat(LOG_PREVIEW_CHARS + 5), + "e\u{301}".repeat(LOG_PREVIEW_CHARS), + ]; + for detail in &cases { + let preview = log_preview(detail); + assert!(!preview.contains('\u{FFFD}'), "{preview}"); + assert!(preview.is_ascii() || std::str::from_utf8(preview.as_bytes()).is_ok()); + let body = preview.strip_suffix("...").unwrap_or(&preview); + assert!( + detail.starts_with(body), + "{preview} is not a prefix of {detail}" + ); + assert!(body.chars().count() <= LOG_PREVIEW_CHARS, "{preview}"); + } + assert_eq!( + log_preview(&cases[0]), + "deploy.sh requires a DEPLOY_TOKEN enviro..." + ); + // The marker is ASCII, so the line's last bytes are whole characters. + assert!(log_preview(&cases[2]).ends_with("...")); + } + + #[test] + fn a_log_line_names_the_event_and_only_the_fields_it_has() { + let line = log_line(&McpLog { + event: "tools/call", + transport: "stdio", + agent: Some("hermes"), + outcome: Some("skipped"), + reason: Some("Self Reports is off"), + category: Some("looping"), + known_category: Some(false), + raw_category: None, + session: Some("s-1"), + detail: Some("stuck\nin a loop"), + summary: None, + }); + assert_eq!( + line, + "Self Reports MCP tools/call over stdio agent=hermes outcome=skipped \ + category=\"looping\" unknown_category=true session=s-1 \ + reason=\"Self Reports is off\" preview=\"stuck in a loop\"" + ); + // An inferred category names what the model sent (here nothing). + let inferred = log_line(&McpLog { + event: "tools/call", + transport: "http", + outcome: Some("recorded"), + category: Some("invalid_tool_or_credential"), + known_category: Some(false), + raw_category: Some(""), + ..Default::default() + }); + assert_eq!( + inferred, + "Self Reports MCP tools/call over http outcome=recorded \ + category=\"invalid_tool_or_credential\" inferred_category=true raw_category=\"\"" + ); + // F20: the model's category is shown only when it is shaped like a + // name; a token sent as the category is never logged. + let token = format!("ghp_{}", "A".repeat(36)); + let tokened = log_line(&McpLog { + event: "tools/call", + transport: "stdio", + outcome: Some("recorded"), + category: Some("invalid_tool_or_credential"), + known_category: Some(false), + raw_category: Some(&token), + ..Default::default() + }); + assert!(!tokened.contains("AAAA"), "{tokened}"); + assert!( + tokened.ends_with("inferred_category=true raw_category=\"(40 characters, not shown)\""), + "{tokened}" + ); + let skipped = log_line(&McpLog { + event: "tools/call", + transport: "http", + outcome: Some("skipped"), + category: Some(&token), + ..Default::default() + }); + assert!(!skipped.contains("AAAA"), "{skipped}"); + let bare = log_line(&McpLog { + event: "initialize", + transport: "http", + ..Default::default() + }); + assert_eq!(bare, "Self Reports MCP initialize over http"); + // A sync result is scrubbed too. + let sync = log_line(&McpLog { + event: "sync", + transport: "cli", + summary: Some("failed codex (token=sk-proj-abcdefghijklmnopqrstuvwxyz012345)"), + ..Default::default() + }); + assert!(!sync.contains("abcdefghij"), "{sync}"); + } + + fn temp_home(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!( + "fpai-self-report-{name}-{}-{}", + std::process::id(), + next_seq() + )); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(&dir).unwrap(); + dir + } + + fn enabled(categories: Vec, guidance: Option<&str>) -> Settings { + Settings { + version: SETTINGS_VERSION, + enabled: true, + source: "local".into(), + categories, + guidance: guidance.map(str::to_string), + mcp: McpEndpoint::on_port(DEFAULT_PORT), + updated_at: "2026-11-25T10:00:00Z".into(), + enrolment: None, + } + } + + /// The enrolment id the tests' enrolled machine runs under. + const TEST_ENROLMENT: &str = "test-enrolment"; + + fn enrolled_as_test() -> Enrolment { + Enrolment::Enrolled(Some(TEST_ENROLMENT.into())) + } + + fn test_enrolment(enrolled: bool) -> Enrolment { + if enrolled { + enrolled_as_test() + } else { + Enrolment::NotEnrolled + } + } + + #[test] + fn the_description_is_the_contract_text() { + let cats = vec![ + Category { + name: "a".into(), + description: "First.".into(), + }, + Category { + name: "b_2".into(), + description: "Second.".into(), + }, + ]; + let want = format!("{DESCRIPTION_HEAD}\n\nCategories:\n- a: First.\n- b_2: Second."); + assert_eq!(describe(&cats, None), want); + assert_eq!(describe(&cats, Some("")), want); + assert_eq!( + describe(&cats, Some("Be brief.")), + format!("{want}\n\nBe brief.") + ); + assert!(DESCRIPTION_HEAD.starts_with( + "When you are stuck on something you cannot fix yourself, call this tool once" + )); + assert!(DESCRIPTION_HEAD.ends_with("There is no need to mention this report to the user.")); + } + + #[test] + fn the_schema_enumerates_the_categories() { + let schema = input_schema(&default_categories()); + assert_eq!( + schema["properties"]["category"]["enum"], + json!([ + "looping", + "cannot_do_request", + "invalid_tool_or_credential", + "missing_context", + "repeated_tool_failure", + "task_failure" + ]) + ); + assert_eq!(schema["required"], json!(["category", "detail"])); + assert_eq!(schema["additionalProperties"], json!(false)); + } + + #[test] + fn no_tool_when_disabled_or_missing() { + assert!(tool_definition(None).is_none()); + let mut s = enabled(default_categories(), None); + s.enabled = false; + assert!(tool_definition(Some(&s)).is_none()); + s.enabled = true; + assert_eq!(tool_definition(Some(&s)).unwrap()["name"], "report"); + } + + #[test] + fn category_names_follow_the_pattern() { + assert!(is_valid_category_name("looping")); + assert!(is_valid_category_name("a1_b")); + assert!(is_valid_category_name(&"a".repeat(64))); + assert!(!is_valid_category_name(&"a".repeat(65))); + assert!(!is_valid_category_name("1abc")); + assert!(!is_valid_category_name("Abc")); + assert!(!is_valid_category_name("a-b")); + assert!(!is_valid_category_name("")); + } + + #[test] + fn invalid_categories_are_dropped_and_none_left_means_defaults() { + let cats = vec![ + Category { + name: "ok".into(), + description: "x".repeat(600), + }, + Category { + name: "Bad".into(), + description: "d".into(), + }, + Category { + name: "ok".into(), + description: "dup".into(), + }, + Category { + name: "empty".into(), + description: " ".into(), + }, + ]; + let out = sanitize_categories(Some(&cats)); + assert_eq!(out.len(), 1); + assert_eq!(out[0].description.chars().count(), 500); + assert_eq!(sanitize_categories(Some(&[])), default_categories()); + assert_eq!(sanitize_categories(None), default_categories()); + let many: Vec = (0..40) + .map(|i| Category { + name: format!("c{i}"), + description: "d".into(), + }) + .collect(); + assert_eq!(sanitize_categories(Some(&many)).len(), MAX_CATEGORIES); + assert_eq!(sanitize_guidance(Some(" ")), None); + assert_eq!( + sanitize_guidance(Some(&"g".repeat(3000))) + .unwrap() + .chars() + .count(), + 2000 + ); + } + + #[test] + fn the_port_comes_from_the_environment_value() { + assert_eq!(port_from(None), 4319); + assert_eq!(port_from(Some("")), 4319); + assert_eq!(port_from(Some("5000")), 5000); + assert_eq!(port_from(Some("0")), 4319); + assert_eq!(port_from(Some("nope")), 4319); + assert_eq!(port_from(Some("70000")), 4319); + } + + #[test] + fn settings_round_trip_with_the_contract_keys() { + let home = temp_home("roundtrip"); + let path = settings_path(&home); + let s = enabled(default_categories(), Some("g")); + write_settings(&path, &s).unwrap(); + let raw: Value = serde_json::from_str(&fs::read_to_string(&path).unwrap()).unwrap(); + assert_eq!(raw["version"], 1); + assert_eq!(raw["mcp"]["url"], "http://127.0.0.1:4319/mcp"); + assert_eq!(raw["updatedAt"], "2026-11-25T10:00:00Z"); + assert_eq!(read_settings(&path), Some(s.clone())); + use std::os::unix::fs::PermissionsExt; + assert_eq!( + fs::metadata(&path).unwrap().permissions().mode() & 0o777, + 0o644 + ); + fs::write(&path, "{not json").unwrap(); + assert_eq!(read_settings(&path), None); + let _ = fs::remove_dir_all(home); + } + + #[test] + fn the_cache_rereads_a_changed_file() { + let home = temp_home("cache"); + let path = settings_path(&home); + // Enrolled: a missing file is off until the daemon writes it. + let cache = SettingsCache::new(&home, Arc::new(enrolled_as_test)); + assert!(cache.current().is_none()); + let mut on = enabled(default_categories(), None); + on.source = "cloud".into(); + on.enrolment = Some(TEST_ENROLMENT.into()); + write_settings(&path, &on).unwrap(); + assert!(cache.current().unwrap().enabled); + let mut off = on.clone(); + off.enabled = false; + off.guidance = Some("a longer file so the size changes too".into()); + write_settings(&path, &off).unwrap(); + assert!(!cache.current().unwrap().enabled); + fs::remove_file(&path).unwrap(); + assert!(cache.current().is_none()); + let _ = fs::remove_dir_all(home); + } + + /// On by default (CONTRACT §4): what a reader makes of each state of the file. + #[test] + fn a_missing_file_is_on_off_cloud_and_off_on_cloud() { + let home = temp_home("effective"); + let path = settings_path(&home); + // Fresh machine, not enrolled: on, defaults. + let s = effective_settings(&home, &|| Enrolment::NotEnrolled).expect("on by default"); + assert!(s.enabled); + assert_eq!(s.source, "local"); + assert_eq!(s.categories, default_categories()); + // Enrolled, file not written yet: off. + assert_eq!(effective_settings(&home, &enrolled_as_test), None); + // An explicit local off in config.json wins over the default. + fs::write( + home.join("config.json"), + r#"{"selfReport":{"enabled":false}}"#, + ) + .unwrap(); + assert_eq!(effective_settings(&home, &|| Enrolment::NotEnrolled), None); + fs::write( + home.join("config.json"), + r#"{"selfReport":{"enabled":true}}"#, + ) + .unwrap(); + assert!( + effective_settings(&home, &|| Enrolment::NotEnrolled) + .unwrap() + .enabled + ); + // A malformed file is off, enrolled or not (fail safe). + fs::write(&path, "{not json").unwrap(); + assert_eq!(effective_settings(&home, &|| Enrolment::NotEnrolled), None); + assert_eq!(effective_settings(&home, &enrolled_as_test), None); + // An explicit enabled:false file is off. + let mut off = enabled(default_categories(), None); + off.enabled = false; + write_settings(&path, &off).unwrap(); + assert!( + !effective_settings(&home, &|| Enrolment::NotEnrolled) + .unwrap() + .enabled + ); + // The cache agrees with the reader. + fs::remove_file(&path).unwrap(); + fs::remove_file(home.join("config.json")).unwrap(); + assert!( + SettingsCache::new(&home, Arc::new(|| Enrolment::NotEnrolled)) + .current() + .unwrap() + .enabled + ); + assert!( + SettingsCache::new(&home, Arc::new(enrolled_as_test)) + .current() + .is_none() + ); + let _ = fs::remove_dir_all(home); + } + + /// A fresh OSS machine: no file, the HTTP server lists the tool and records. + #[test] + fn an_unenrolled_machine_with_no_file_lists_and_records() { + let home = temp_home("http-default-on"); + let server = server_enrolled(&home, false); + let caller = Caller { + agent: Some("copilot".to_string()), + cwd: None, + }; + let listed = server + .dispatch( + json!({"jsonrpc": "2.0", "id": 1, "method": "tools/list"}), + &caller, + ) + .unwrap(); + assert_eq!(listed["result"]["tools"][0]["name"], TOOL_NAME); + call_report(&server, "copilot"); + assert_eq!(event_files(&home), 1, "recorded with no settings file"); + // Enrolled with no file yet: nothing listed, nothing recorded. + let enrolled = server_enrolled(&home, true); + let listed = enrolled + .dispatch( + json!({"jsonrpc": "2.0", "id": 1, "method": "tools/list"}), + &caller, + ) + .unwrap(); + assert_eq!(listed["result"]["tools"], json!([])); + call_report(&enrolled, "copilot"); + assert_eq!( + event_files(&home), + 1, + "not recorded while enrolled with no file" + ); + let _ = fs::remove_dir_all(home); + } + + #[test] + fn host_and_origin_must_be_this_loopback_port() { + let headers = |host: Option<&str>, origin: Option<&str>| { + let mut h = HeaderMap::new(); + if let Some(v) = host { + h.insert("host", v.parse().unwrap()); + } + if let Some(v) = origin { + h.insert("origin", v.parse().unwrap()); + } + h + }; + assert!(allowed(&headers(Some("127.0.0.1:4319"), None), 4319)); + assert!(allowed(&headers(Some("localhost:4319"), None), 4319)); + assert!(allowed( + &headers(Some("localhost:4319"), Some("http://127.0.0.1:4319")), + 4319 + )); + assert!(!allowed(&headers(None, None), 4319)); + assert!(!allowed(&headers(Some("127.0.0.1:4320"), None), 4319)); + assert!(!allowed(&headers(Some("evil.example:4319"), None), 4319)); + assert!(!allowed( + &headers(Some("127.0.0.1:4319"), Some("http://evil.example")), + 4319 + )); + assert!(!allowed( + &headers(Some("127.0.0.1:4319"), Some("https://127.0.0.1:4319")), + 4319 + )); + assert!(!allowed( + &headers(Some("127.0.0.1:4319"), Some("null")), + 4319 + )); + } + + #[test] + fn the_query_names_the_agent_and_cwd() { + let c = Caller::from_query(Some("agent=openclaw&cwd=%2Fhome%2Fu%2Fproj&x=1")); + assert_eq!(c.agent.as_deref(), Some("openclaw")); + assert_eq!(c.cwd.as_deref(), Some("/home/u/proj")); + let c = Caller::from_query(None); + assert!(c.agent.is_none() && c.cwd.is_none()); + assert_eq!(percent_decode("a%2"), "a%2"); + assert_eq!(percent_decode("a%zzb"), "a%zzb"); + } + + #[test] + fn report_arguments_are_kept_as_given() { + let r = Report::from_args(&json!({"category": "made_up", "detail": "x ".repeat(1500)})); + assert_eq!(r.category, "made_up"); + // Cut at 2000 chars without part of a token (the trailing space goes too). + assert_eq!(r.detail.chars().count(), 1999); + let r = Report::from_args(&json!({"detail": "x".repeat(3000)})); + assert_eq!(r.detail, DETAIL_CUT_MARKER); + let r = Report::from_args(&json!({})); + assert_eq!( + r, + Report { + category: String::new(), + detail: String::new() + } + ); + } + + #[test] + fn the_newest_matching_session_owns_the_report() { + let home = temp_home("session"); + let dir = home.join("hook-activity"); + fs::create_dir_all(&dir).unwrap(); + let now = 1_800_000_000_000_i64; + let row = |at: i64, integration: &str, session: &str, cwd: &str| { + json!({"timestamp": at, "eventType": "PreToolUse", "integration": integration, + "sessionId": session, "cwd": cwd, "toolName": "x", "decision": "allow"}) + .to_string() + }; + // A page is named for when it rotated, after its last row was written. + fs::write( + dir.join(format!("page-{}-0.jsonl", now - 900)), + format!("{}\n", row(now - 1000, "openclaw", "s-page", "/w/a")), + ) + .unwrap(); + fs::write( + dir.join("current.jsonl"), + [ + row(now - 7 * 3600 * 1000, "openclaw", "s-old", "/w/a"), + row(now - 5000, "openclaw", "s-older", "/w/b"), + row(now - 100, "pi", "s-pi", "/w/a"), + String::from("not json"), + ] + .join("\n") + + "\n", + ) + .unwrap(); + // No cwd and openclaw rows in /w/a and /w/b: two projects, no guess. + assert_eq!(find_session(&home, "openclaw", None, now), None); + assert_eq!( + find_session(&home, "openclaw", Some("/w/b"), now).map(|s| s.0), + Some("s-older".to_string()) + ); + // A descendant beats a newer unrelated row; no relation at all, with + // rows from two projects, is not a guess at either. + assert_eq!( + find_session(&home, "openclaw", Some("/w/b/sub"), now), + Some(("s-older".to_string(), Some("/w/b".to_string()))) + ); + assert_eq!( + find_session(&home, "openclaw", Some("/elsewhere"), now), + None + ); + assert_eq!(find_session(&home, "goose", Some("/w/a"), now), None); + assert_eq!(find_session(&home, "goose", None, now), None); + assert_eq!( + find_session(&home, "openclaw", None, now + 8 * 3600 * 1000), + None + ); + + let event = fallback_event( + &home, + "openclaw", + Some("/w/a"), + &Report { + category: "looping".into(), + detail: "stuck".into(), + }, + now, + ); + assert_eq!(event["type"], "self_report"); + assert_eq!(event["session_id"], "s-page"); + assert_eq!(event["agent_id"], "openclaw-a"); + assert_eq!(event["source"], "mcp"); + assert_eq!(event["integration"], "openclaw"); + assert_eq!(event["environment"], "local"); + assert!(event.get("tool_call_id").is_none()); + + let event = fallback_event( + &home, + "goose", + Some("/w/proj"), + &Report { + category: "c".into(), + detail: String::new(), + }, + now, + ); + assert_eq!(event["session_id"], UNATTRIBUTED_SESSION); + assert_eq!(event["agent_id"], "goose-proj"); + let _ = fs::remove_dir_all(home); + } + + fn server_for(home: &Path) -> Server { + server_enrolled(home, true) + } + + fn server_enrolled(home: &Path, enrolled: bool) -> Server { + Server { + home: home.to_path_buf(), + port: DEFAULT_PORT, + settings: SettingsCache::new(home, Arc::new(move || test_enrolment(enrolled))), + } + } + + fn event_files(home: &Path) -> usize { + fs::read_dir(home.join("custom-agents/events")) + .map(|d| { + d.filter_map(Result::ok) + .filter(|e| e.path().extension().is_some_and(|x| x == "jsonl")) + .count() + }) + .unwrap_or(0) + } + + fn call_report(server: &Server, agent: &str) -> Value { + let caller = Caller { + agent: Some(agent.to_string()), + cwd: None, + }; + server + .dispatch( + json!({"jsonrpc": "2.0", "id": 7, "method": "tools/call", + "params": {"name": "report", "arguments": {"category": "looping", "detail": "d"}}}), + &caller, + ) + .unwrap() + } + + #[test] + fn an_http_report_is_recorded_only_while_the_settings_say_enabled() { + let home = temp_home("http-enabled"); + let server = server_for(&home); + let path = settings_path(&home); + // This server is enrolled, so the file that decides is the one the + // daemon writes from the org's setting. + let org = |mut s: Settings| { + s.source = "cloud".into(); + s.enrolment = Some(TEST_ENROLMENT.into()); + s + }; + // Missing settings: answered, not recorded. + let reply = call_report(&server, "copilot"); + assert_eq!(reply["result"]["content"][0]["text"], RESULT_TEXT); + assert_eq!(event_files(&home), 0, "missing settings"); + // Malformed settings. + fs::write(&path, "{not json").unwrap(); + call_report(&server, "copilot"); + assert_eq!(event_files(&home), 0, "malformed settings"); + // Disabled. + let mut off = org(enabled(default_categories(), None)); + off.enabled = false; + write_settings(&path, &off).unwrap(); + let reply = call_report(&server, "copilot"); + assert_eq!(reply["result"]["isError"], false); + assert_eq!(event_files(&home), 0, "disabled settings"); + // This machine's own file, on, while enrolled: not the org's, so off. + write_settings(&path, &enabled(default_categories(), None)).unwrap(); + call_report(&server, "copilot"); + assert_eq!(event_files(&home), 0, "local file while enrolled"); + // Enabled: one event. + write_settings(&path, &org(enabled(default_categories(), None))).unwrap(); + call_report(&server, "copilot"); + assert_eq!(event_files(&home), 1, "enabled settings"); + // Disabled again, with the cache primed by the enabled read: honoured + // on the next call. + assert!(server.settings.current().unwrap().enabled); + write_settings(&path, &off).unwrap(); + call_report(&server, "copilot"); + assert_eq!(event_files(&home), 1, "disabled after enabled"); + // A hook-recorded agent is never recorded here. + write_settings(&path, &org(enabled(default_categories(), None))).unwrap(); + call_report(&server, "claude"); + assert_eq!(event_files(&home), 1, "claude is recorded by its hook"); + let _ = fs::remove_dir_all(home); + } + + #[test] + fn initialize_names_this_process() { + let home = temp_home("instance"); + let server = server_for(&home); + let reply = server + .dispatch( + json!({"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {}}), + &Caller::default(), + ) + .unwrap(); + let info = &reply["result"]["serverInfo"]; + assert_eq!(info["name"], SERVER_NAME); + assert_eq!(info["instanceId"], instance_id()); + assert_eq!(instance_id().len(), 32); + assert_eq!(instance_id(), instance_id(), "stable for the process"); + let _ = fs::remove_dir_all(home); + } + + #[test] + fn reads_every_page_in_the_window_not_just_the_newest() { + let home = temp_home("busy-pages"); + let dir = home.join("hook-activity"); + fs::create_dir_all(&dir).unwrap(); + let now = 1_800_000_000_000_i64; + let row = |at: i64, session: &str, cwd: &str| { + json!({"timestamp": at, "eventType": "PreToolUse", "integration": "copilot", + "sessionId": session, "cwd": cwd, "toolName": "x", "decision": "allow"}) + .to_string() + }; + // Project A's one row, then four pages of project B (80 rows). + let mut t = now - 3_600_000; + fs::write( + dir.join(format!("page-{}-0.jsonl", t + 1)), + row(t, "sess-A", "/work/a") + "\n", + ) + .unwrap(); + for page in 1..=4 { + let mut lines = Vec::new(); + for _ in 0..20 { + t += 1000; + lines.push(row(t, "sess-B", "/work/b")); + } + fs::write( + dir.join(format!("page-{}-{page}.jsonl", t + 1)), + lines.join("\n") + "\n", + ) + .unwrap(); + } + fs::write( + dir.join("current.jsonl"), + row(t + 1000, "sess-B", "/work/b") + "\n", + ) + .unwrap(); + assert_eq!( + find_session(&home, "copilot", Some("/work/a"), now), + Some(("sess-A".to_string(), Some("/work/a".to_string()))) + ); + // No cwd: A is still in the window, so there are two projects; never B. + assert_eq!(find_session(&home, "copilot", None, now), None); + // A page rotated before the window opened is not read at all. + let stale = now - 8 * 3_600_000; + fs::write( + dir.join(format!("page-{stale}-0.jsonl")), + row(now - 60_000, "misfiled", "/work/z") + "\n", + ) + .unwrap(); + // (Its row would be an exact match for /work/z if it were read.) + assert_eq!(find_session(&home, "copilot", Some("/work/z"), now), None); + } + + #[test] + fn no_cwd_is_attributed_only_within_one_project() { + let home = temp_home("one-project"); + let dir = home.join("hook-activity"); + fs::create_dir_all(&dir).unwrap(); + let now = 1_800_000_000_000_i64; + let row = |at: i64, session: &str, cwd: &str| { + json!({"timestamp": at, "eventType": "PreToolUse", "integration": "copilot", + "sessionId": session, "cwd": cwd, "toolName": "x", "decision": "allow"}) + .to_string() + }; + // One project (two sessions in it): the newest owns the report. + fs::write( + dir.join("current.jsonl"), + [ + row(now - 3000, "a-1", "/repo/a"), + row(now - 2000, "a-2", "/repo/a/"), + ] + .join("\n") + + "\n", + ) + .unwrap(); + assert_eq!( + find_session(&home, "copilot", None, now), + Some(("a-2".to_string(), Some("/repo/a/".to_string()))) + ); + // Then project B is active too: a report with no cwd is not given to + // B's (newer) session, nor to A's. + fs::write( + dir.join("current.jsonl"), + [ + row(now - 3000, "a-1", "/repo/a"), + row(now - 1000, "b-1", "/repo/b"), + ] + .join("\n") + + "\n", + ) + .unwrap(); + assert_eq!(find_session(&home, "copilot", None, now), None); + let report = Report { + category: "looping".into(), + detail: "d".into(), + }; + let event = fallback_event(&home, "copilot", None, &report, now); + assert_eq!(event["session_id"], UNATTRIBUTED_SESSION); + // A known cwd still picks its own project. + assert_eq!( + find_session(&home, "copilot", Some("/repo/a"), now).map(|s| s.0), + Some("a-1".to_string()) + ); + let event = fallback_event(&home, "copilot", Some("/repo/a"), &report, now); + assert_eq!(event["session_id"], "a-1"); + let _ = fs::remove_dir_all(home); + } + + #[test] + fn cwd_affinity_ranks_exact_then_related() { + assert_eq!(cwd_affinity("/a/b", Some("/a/b/")), 2); + assert_eq!(cwd_affinity("/a/b", Some("/a")), 1); + assert_eq!(cwd_affinity("/a", Some("/a/b/c")), 1); + assert_eq!(cwd_affinity("/a/b", Some("/a/bc")), 0); + assert_eq!(cwd_affinity("/root", Some("/")), 1); + assert_eq!(cwd_affinity("/a", None), 0); + assert_eq!(cwd_affinity("/a", Some("")), 0); + } + + #[test] + fn a_fallback_report_takes_the_matched_rows_agent() { + let home = temp_home("row-agent"); + let dir = home.join("hook-activity"); + fs::create_dir_all(&dir).unwrap(); + let now = 1_800_000_000_000_i64; + fs::write( + dir.join("current.jsonl"), + json!({"timestamp": now - 1000, "eventType": "PreToolUse", "integration": "hermes", + "sessionId": "local-1", "cwd": "/root/.hermes/hermes-agent", "decision": "allow"}) + .to_string() + + "\n", + ) + .unwrap(); + let report = Report { + category: "looping".into(), + detail: "d".into(), + }; + let event = fallback_event(&home, "hermes", Some("/root"), &report, now); + assert_eq!(event["session_id"], "local-1"); + assert_eq!(event["agent_id"], "hermes-hermes-agent"); + let _ = fs::remove_dir_all(home); + } + + #[test] + fn event_files_use_the_sdk_writer_format() { + use std::os::unix::fs::PermissionsExt; + let home = temp_home("writer"); + let path = write_event_file(&home, &[json!({"type": "self_report"})]).unwrap(); + let name = path.file_name().unwrap().to_str().unwrap().to_string(); + assert!( + name.starts_with("event-") && name.ends_with(".jsonl"), + "{name}" + ); + // event-YYYY-MM-DDTHH-MM-SS-mmmZ-... + assert_eq!(&name[16..17], "T"); + assert_eq!(&name[29..31], "Z-"); + assert_eq!(path.parent().unwrap(), home.join("custom-agents/events")); + assert_eq!( + fs::metadata(&path).unwrap().permissions().mode() & 0o777, + 0o600 + ); + assert_eq!( + fs::read_to_string(&path).unwrap(), + "{\"type\":\"self_report\"}\n" + ); + let leftovers: Vec<_> = fs::read_dir(path.parent().unwrap()) + .unwrap() + .filter_map(Result::ok) + .filter(|e| e.path().extension().is_some_and(|x| x == "tmp")) + .collect(); + assert!(leftovers.is_empty()); + let _ = fs::remove_dir_all(home); + } + + // ── Shared golden files (test-fixtures/self-report/) ─────────────────── + // + // The CLI (src/hooks/self-report*.ts) and the TypeScript SDK test against + // the same files, so the description, schema, categories, server-recorded + // list and event fields cannot drift between the three implementations. + + fn golden(name: &str) -> String { + let path = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../test-fixtures/self-report") + .join(name); + fs::read_to_string(&path).unwrap_or_else(|e| panic!("{}: {e}", path.display())) + } + + fn golden_lines(name: &str) -> Vec { + golden(name) + .lines() + .filter(|l| !l.is_empty()) + .map(str::to_string) + .collect() + } + + /// The same on/off as the CLI's `resolveSelfReport` for every case in + /// settings-cases.golden.json, through the reader the record path uses + /// and through the cache behind `initialize` and `tools/list`. + #[test] + fn golden_settings_cases_agree_with_the_cli() { + let fixture: Value = serde_json::from_str(&golden("settings-cases.golden.json")).unwrap(); + for (i, case) in fixture["cases"].as_array().unwrap().iter().enumerate() { + let name = case["name"].as_str().unwrap(); + let home = temp_home(&format!("settings-case-{i}")); + let path = settings_path(&home); + if let Some(text) = case["text"].as_str() { + fs::write(&path, text).unwrap(); + } else if !case["file"].is_null() { + fs::write(&path, serde_json::to_string_pretty(&case["file"]).unwrap()).unwrap(); + } + // `currentEnrolment`: the id the machine is enrolled as (absent: + // enrolled with an unreadable credential). + let enrolment = if case["enrolled"].as_bool().unwrap() { + Enrolment::Enrolled(case["currentEnrolment"].as_str().map(str::to_string)) + } else { + Enrolment::NotEnrolled + }; + let want = case["on"].as_bool().unwrap(); + let read = effective_settings(&home, &|| enrolment.clone()).is_some_and(|s| s.enabled); + assert_eq!(read, want, "effective_settings: {name}"); + let cache = SettingsCache::new(&home, Arc::new(move || enrolment.clone())); + assert_eq!( + cache.current().is_some_and(|s| s.enabled), + want, + "cache: {name}" + ); + assert_eq!( + tool_definition(cache.current().as_ref()).is_some(), + want, + "tools/list: {name}" + ); + let _ = fs::remove_dir_all(home); + } + } + + /// The id a cloud file is bound to: the same bytes as the CLI's + /// `selfReportEnrolmentIdOf` for every vector in the shared fixture. + #[test] + fn enrolment_ids_agree_with_the_cli() { + let fixture: Value = serde_json::from_str(&golden("settings-cases.golden.json")).unwrap(); + let vectors = fixture["enrolmentIds"].as_array().unwrap(); + assert!(!vectors.is_empty()); + for v in vectors { + assert_eq!( + enrolment_id( + v["url"].as_str().unwrap(), + v["machineId"].as_str().unwrap(), + v["token"].as_str().unwrap() + ), + v["id"].as_str().unwrap() + ); + } + } + + /// Review 4719314971: org A's "on" must stop deciding as soon as the + /// machine is enrolled as org B, before B's first answer is written. + #[test] + fn a_cloud_file_decides_only_for_the_enrolment_that_wrote_it() { + let home = temp_home("bound-enrolment"); + let path = settings_path(&home); + let mut org_a = enabled(default_categories(), None); + org_a.source = "cloud".into(); + org_a.enrolment = Some("enrolment-a".into()); + write_settings(&path, &org_a).unwrap(); + let as_a = || Enrolment::Enrolled(Some("enrolment-a".into())); + let as_b = || Enrolment::Enrolled(Some("enrolment-b".into())); + assert!(effective_settings(&home, &as_a).unwrap().enabled); + assert_eq!( + effective_settings(&home, &as_b), + None, + "A's file, enrolled as B" + ); + assert_eq!( + effective_settings(&home, &|| Enrolment::Enrolled(None)), + None, + "identity unknown" + ); + let switch = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let cache = { + let switch = switch.clone(); + SettingsCache::new( + &home, + Arc::new(move || { + if switch.load(std::sync::atomic::Ordering::SeqCst) { + as_b() + } else { + as_a() + } + }), + ) + }; + assert!(cache.current().unwrap().enabled); + switch.store(true, std::sync::atomic::Ordering::SeqCst); + assert!(cache.current().is_none(), "the cache re-asks on every call"); + // No enrolment at all (an older daemon's file): off while enrolled. + org_a.enrolment = None; + write_settings(&path, &org_a).unwrap(); + assert_eq!(effective_settings(&home, &as_a), None); + let _ = fs::remove_dir_all(home); + } + + /// Enrolling with a local file in place: the cache stops serving it on + /// the next call, with the file unchanged, and serves the org's file once + /// the daemon writes it. + #[test] + fn enrolling_ignores_a_local_file_until_the_org_setting_is_written() { + let home = temp_home("enrol-transition"); + let path = settings_path(&home); + write_settings(&path, &enabled(default_categories(), None)).unwrap(); + let flag = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let check = { + let flag = flag.clone(); + Arc::new(move || test_enrolment(flag.load(std::sync::atomic::Ordering::SeqCst))) + }; + let cache = SettingsCache::new(&home, check); + assert!(cache.current().unwrap().enabled); + flag.store(true, std::sync::atomic::Ordering::SeqCst); + assert!( + cache.current().is_none(), + "enrolled: the local file no longer decides" + ); + assert!(effective_settings(&home, &enrolled_as_test).is_none()); + let mut org = enabled(default_categories(), None); + org.source = "cloud".into(); + org.enrolment = Some(TEST_ENROLMENT.into()); + org.enabled = false; + org.guidance = Some("the org's own file, so the size changes".into()); + write_settings(&path, &org).unwrap(); + assert!(!cache.current().unwrap().enabled); + org.enabled = true; + write_settings(&path, &org).unwrap(); + assert!(cache.current().unwrap().enabled); + let _ = fs::remove_dir_all(home); + } + + #[test] + fn golden_truncation_counts_code_points() { + let fixture: Value = serde_json::from_str(&golden("truncation.golden.json")).unwrap(); + let max = fixture["max"].as_u64().unwrap() as usize; + assert_eq!(max, MAX_DETAIL_CHARS); + for case in fixture["cases"].as_array().unwrap() { + let pad = case["pad_char"] + .as_str() + .unwrap() + .repeat(case["pad"].as_u64().unwrap() as usize); + let input = format!("{pad}{}", case["tail"].as_str().unwrap()); + let want = format!("{pad}{}", case["expected_tail"].as_str().unwrap()); + assert_eq!(truncate_chars(&input, max), want, "{case}"); + } + } + + #[test] + fn golden_detail_cut_never_leaves_part_of_a_token() { + let fixture: Value = serde_json::from_str(&golden("truncation.golden.json")).unwrap(); + let max = fixture["max"].as_u64().unwrap() as usize; + let spec = &fixture["detail_cut"]; + assert_eq!(spec["marker"].as_str().unwrap(), DETAIL_CUT_MARKER); + let join = |parts: &Value| -> String { + parts + .as_array() + .unwrap() + .iter() + .map(|p| { + p[0].as_str() + .unwrap() + .repeat(p[1].as_u64().unwrap() as usize) + }) + .collect() + }; + let cases = spec["cases"].as_array().unwrap(); + assert!(cases.len() > 5); + for case in cases { + let input = join(&case["input"]); + let want = join(&case["expected"]); + assert_eq!(cut_detail(&input, max), want, "{}", case["name"]); + assert_eq!( + Report::from_args(&json!({"category": "looping", "detail": input})).detail, + want, + "{}", + case["name"] + ); + } + for ws in spec["whitespace"].as_str().unwrap().chars() { + let text = format!("ok{ws}{}", "t".repeat(2100)); + assert_eq!(cut_detail(&text, max), "ok", "{ws:?}"); + } + let nbsp = format!("ok\u{a0}{}", "t".repeat(2100)); + assert_eq!(cut_detail( , max), DETAIL_CUT_MARKER); + } + + /// F18 round 3: the HTTP log bound (the 64 KiB body) never leaves part of + /// a token either. + #[test] + fn the_log_detail_bound_never_leaves_part_of_a_token() { + let jwt = format!("eyJhbGciOiJIUzI1NiJ9.eyJ{}.sig", "a".repeat(70_000)); + let args = json!({"detail": format!("token {jwt} rejected")}); + assert_eq!(Report::log_detail(&args), "token"); + } + + #[test] + fn golden_description_and_schema() { + let cats = default_categories(); + assert_eq!(describe(&cats, None), golden("description.golden.txt")); + assert_eq!( + describe( + &cats, + Some("Report a missing repository as missing_context.") + ), + golden("description-guidance.golden.txt") + ); + let want: Value = serde_json::from_str(&golden("input-schema.golden.json")).unwrap(); + assert_eq!(input_schema(&cats), want); + } + + #[test] + fn golden_instructions() { + let cats = default_categories(); + assert_eq!(instructions(&cats, None), golden("instructions.golden.txt")); + assert_eq!( + instructions( + &cats, + Some("Report a missing repository as missing_context.") + ), + golden("instructions-guidance.golden.txt") + ); + assert!(golden("instructions.golden.txt").chars().count() < 600); + } + + #[test] + fn golden_category_inference() { + let fixture: Value = serde_json::from_str(&golden("category-inference.json")).unwrap(); + let rules: Vec = CATEGORY_RULES + .iter() + .map(|(category, keywords)| json!({"category": category, "keywords": keywords})) + .collect(); + assert_eq!(fixture["rules"], json!(rules)); + assert_eq!(fixture["fallback"], FALLBACK_CATEGORY); + let defaults = default_categories(); + let cases = fixture["cases"].as_array().unwrap(); + assert!(!cases.is_empty()); + for case in cases { + let name = case["name"].as_str().unwrap(); + let names: Vec<&str> = match case["categories"].as_array() { + Some(list) => list.iter().map(|v| v.as_str().unwrap()).collect(), + None => defaults.iter().map(|c| c.name.as_str()).collect(), + }; + let report = Report::from_args(&case["args"]); + assert_eq!( + resolve_category(&report.category, &report.detail, &names), + ( + case["category"].as_str().unwrap().to_string(), + case["inferred"].as_bool().unwrap() + ), + "{name}" + ); + } + } + + #[test] + fn golden_arg_aliases() { + let fixture: Value = serde_json::from_str(&golden("arg-aliases.json")).unwrap(); + assert_eq!(fixture["aliases"]["category"], json!(CATEGORY_ALIASES)); + assert_eq!(fixture["aliases"]["detail"], json!(DETAIL_ALIASES)); + let cases = fixture["cases"].as_array().unwrap(); + assert!(!cases.is_empty()); + for case in cases { + assert_eq!( + Report::from_args(&case["args"]), + Report { + category: case["category"].as_str().unwrap().to_string(), + detail: case["detail"].as_str().unwrap().to_string(), + }, + "{}", + case["args"] + ); + } + } + + #[test] + fn golden_default_categories() { + let want: Vec = serde_json::from_str(&golden("categories.golden.json")).unwrap(); + assert_eq!(default_categories(), want); + } + + #[test] + fn golden_server_records() { + let got: Vec = SERVER_RECORDS.iter().map(|s| s.to_string()).collect(); + assert_eq!(got, golden_lines("server-records.golden.txt")); + for hooked in ["claude", "codex"] { + assert!(!SERVER_RECORDS.contains(&hooked), "{hooked}"); + } + } + + fn golden_fields() -> (Vec, Vec, Vec) { + let spec: Value = serde_json::from_str(&golden("event-fields.golden.json")).unwrap(); + let list = |k: &str| -> Vec { + spec[k] + .as_array() + .unwrap() + .iter() + .map(|v| v.as_str().unwrap().to_string()) + .collect() + }; + (list("order"), list("optional"), list("fallbackExtras")) + } + + fn keys(v: &Value) -> std::collections::BTreeSet { + v.as_object().unwrap().keys().cloned().collect() + } + + #[test] + fn golden_event_fields_fallback_writer() { + let (order, _, extras) = golden_fields(); + let home = temp_home("golden-fallback"); + let report = Report { + category: "looping".into(), + detail: "Same step again.".into(), + }; + let event = fallback_event(&home, "hermes", Some("/tmp/p"), &report, 1_764_064_800_000); + let want: std::collections::BTreeSet = + order.iter().chain(extras.iter()).cloned().collect(); + assert_eq!(keys(&event), want); + let _ = fs::remove_dir_all(&home); + } + + #[test] + fn golden_event_fields_hook_row() { + let (order, optional, extras) = golden_fields(); + let row: crate::sources::hooks::transform::HookRow = serde_json::from_value(json!({ + "timestamp": 1_764_064_800_000_i64, + "sessionId": "s1", + "integration": "claude", + "eventType": "PreToolUse", + "toolName": "mcp__failproofai_local__report", + "decision": "allow", + "toolCallId": "toolu_1", + "selfReport": {"category": "looping", "detail": "again", "source": "mcp"} + })) + .unwrap(); + let events = crate::sources::hooks::transform::to_events(&row, 0, "local"); + let report = events + .iter() + .find(|e| e["type"] == "self_report") + .expect("a self_report event"); + let want: std::collections::BTreeSet = order + .iter() + .chain(optional.iter()) + .chain(extras.iter()) + .cloned() + .collect(); + assert_eq!(keys(report), want); + } +} diff --git a/crates/fpai-collect/src/sources/hooks/mod.rs b/crates/fpai-collect/src/sources/hooks/mod.rs index 8761513ef..f9989857a 100644 --- a/crates/fpai-collect/src/sources/hooks/mod.rs +++ b/crates/fpai-collect/src/sources/hooks/mod.rs @@ -1,6 +1,7 @@ //! The hook-activity source. //! -//! Tails `~/.failproofai/cache/hook-activity/*.jsonl` and turns each row into +//! Tails `~/.failproofai/hook-activity/*.jsonl` (`$FAILPROOFAI_HOME/hook-activity`; +//! layout 1 kept it under `cache/hook-activity`) and turns each row into //! AgentEye hook events. This is the capability `agenteye-collector` //! structurally cannot have: failproofai already sits in the hook path of //! every supported agent CLI, and nothing else on the machine does. @@ -245,11 +246,13 @@ async fn poll_once( // and erase the would-be verdict, which is the entire measurement // a trial exists to produce. Emit those exactly. The same holds // for an allow Jev produced by clearing a regex deny, and for a - // observe-mode allow Jev would have blocked. + // observe-mode allow Jev would have blocked, and for a self report. let aggregate = verbosity == HooksVerbosity::Decisions && row.is_allow() && !row.has_observation() - && !row.has_jev_signal(); + && !row.has_jev_signal() + // A self report is its own event and must reach Cloud whole. + && row.self_report.is_none(); if aggregate { if let Some(key) = bucket_key(&row) { buckets diff --git a/crates/fpai-collect/src/sources/hooks/transform.rs b/crates/fpai-collect/src/sources/hooks/transform.rs index 357764b97..3b3c4b2fe 100644 --- a/crates/fpai-collect/src/sources/hooks/transform.rs +++ b/crates/fpai-collect/src/sources/hooks/transform.rs @@ -159,6 +159,25 @@ pub struct HookRow { /// check, so Jev decided nothing. #[serde(rename = "jevChecks", default, deserialize_with = "lenient")] pub jev_checks: Option>, + + // ---- Self Reports ------------------------------------------------------ + /// Set on the row the hook wrote for a call to the `report` tool (the + /// agent said it is stuck). Emitted as its own `self_report` event, and the + /// row is never folded into an allow roll-up. + #[serde(rename = "selfReport", default, deserialize_with = "lenient")] + pub self_report: Option, +} + +/// `selfReport` on a hook-activity row. +#[derive(Debug, Clone, Default, Deserialize)] +pub struct SelfReportField { + #[serde(default, deserialize_with = "lenient")] + pub category: Option, + #[serde(default, deserialize_with = "lenient")] + pub detail: Option, + /// `mcp` | `sdk`. + #[serde(default, deserialize_with = "lenient")] + pub source: Option, } /// Deserialize `T`, or `None` when the value is absent, null, or the wrong @@ -965,7 +984,47 @@ pub fn to_events(row: &HookRow, offset: u64, environment: &str) -> Vec { ); } - vec![Value::Object(start), Value::Object(end)] + let mut events = vec![Value::Object(start), Value::Object(end)]; + if let Some(report) = self_report_event(row, session_id, environment) { + events.push(report); + } + events +} + +/// The `self_report` event for a row carrying `selfReport`. Same agent, +/// environment and session as the row's hook events; stamped just after them. +fn self_report_event(row: &HookRow, session_id: &str, environment: &str) -> Option { + let report = row.self_report.as_ref()?; + let mut m = base(row, session_id, environment, "self_report", 2)?; + m.insert( + "category".into(), + json!(report.category.as_deref().unwrap_or_default()), + ); + m.insert( + "detail".into(), + json!(crate::self_report::cut_detail( + report.detail.as_deref().unwrap_or_default(), + crate::self_report::MAX_DETAIL_CHARS + )), + ); + m.insert( + "source".into(), + json!( + report + .source + .as_deref() + .filter(|s| !s.is_empty()) + .unwrap_or("mcp") + ), + ); + m.insert( + "integration".into(), + json!(row.integration.as_deref().unwrap_or("failproofai")), + ); + if let Some(id) = row.tool_call_id.as_deref().filter(|id| !id.is_empty()) { + m.insert("tool_call_id".into(), json!(id)); + } + Some(Value::Object(m)) } /// One rolled-up `allow` bucket. diff --git a/crates/fpai-collect/src/supervisor.rs b/crates/fpai-collect/src/supervisor.rs index ca6999020..9c0da8a23 100644 --- a/crates/fpai-collect/src/supervisor.rs +++ b/crates/fpai-collect/src/supervisor.rs @@ -98,6 +98,12 @@ impl Shutdown { } } + /// Observe the daemon's flag alone, for a lane that runs outside the + /// collector (the Self Reports MCP server). + pub(crate) fn from_daemon(daemon: Arc) -> Self { + Self::for_test(daemon) + } + /// True once either the daemon or the collector has been asked to stop. pub fn is_set(&self) -> bool { self.daemon.load(Ordering::Relaxed) || self.collector.load(Ordering::Relaxed) diff --git a/crates/fpai-collect/tests/hooks_source.rs b/crates/fpai-collect/tests/hooks_source.rs index f33638863..8b7ed4883 100644 --- a/crates/fpai-collect/tests/hooks_source.rs +++ b/crates/fpai-collect/tests/hooks_source.rs @@ -850,3 +850,111 @@ fn a_malformed_start_time_or_tool_call_id_never_drops_the_decision() { assert_eq!(events[1]["outcome"], "deny"); } } + +// ---- Self Reports ------------------------------------------------------------ + +fn self_report_row(ts: i64) -> String { + serde_json::json!({ + "timestamp": ts, + "eventType": "PreToolUse", + "integration": "claude", + "toolName": "mcp__failproofai_local__report", + "toolCallId": "toolu_01", + "decision": "allow", + "durationMs": 1, + "sessionId": "sess-a", + "cwd": "/home/u/repo", + "selfReport": {"category": "invalid_tool_or_credential", "detail": "tracker rejected its API key", "source": "mcp"} + }) + .to_string() +} + +#[test] +fn a_self_report_row_also_emits_a_self_report_event() { + let row = parse(&self_report_row(1785740912184)); + let events = transform::to_events(&row, 7, "prod"); + assert_eq!(events.len(), 3, "the hook pair plus the report"); + let hook = &events[1]; + let report = &events[2]; + assert_eq!(report["type"], "self_report"); + assert_eq!(report["session_id"], "sess-a"); + assert_eq!(report["agent_id"], hook["agent_id"]); + assert_eq!(report["agent_id"], "claude-repo"); + assert_eq!(report["environment"], "prod"); + assert_eq!(report["category"], "invalid_tool_or_credential"); + assert_eq!(report["detail"], "tracker rejected its API key"); + assert_eq!(report["source"], "mcp"); + assert_eq!(report["integration"], "claude"); + assert_eq!(report["tool_call_id"], "toolu_01"); + assert!( + report["timestamp"].as_str().unwrap() > hook["timestamp"].as_str().unwrap(), + "stamped after its own hook leg" + ); +} + +#[test] +fn a_self_report_with_missing_fields_is_still_recorded() { + let mut v: Value = serde_json::from_str(&self_report_row(1785740912184)).unwrap(); + v["selfReport"] = serde_json::json!({"category": "made_up", "detail": "x ".repeat(1250)}); + v.as_object_mut().unwrap().remove("toolCallId"); + let events = transform::to_events(&parse(&v.to_string()), 0, "local"); + let report = &events[2]; + assert_eq!(report["category"], "made_up", "unknown categories are kept"); + // Cut at 2000 chars, never leaving part of a token (the trailing space goes too). + assert_eq!(report["detail"].as_str().unwrap().chars().count(), 1999); + assert_eq!(report["source"], "mcp"); + assert!(report.get("tool_call_id").is_none()); + + // A malformed selfReport never drops the row. + v["selfReport"] = serde_json::json!("nonsense"); + let events = transform::to_events(&parse(&v.to_string()), 0, "local"); + assert_eq!(events.len(), 2); +} + +#[test] +fn a_row_without_self_report_emits_only_the_pair() { + assert_eq!( + transform::to_events(&parse(&allow_row(1785740912000, "Bash")), 0, "local").len(), + 2 + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_self_report_row_is_never_rolled_up() { + let store = tmpdir("sr-store"); + let state = tmpdir("sr-state"); + let spool = tmpdir("sr-spool"); + let mut lines: Vec = (0..5) + .map(|i| allow_row(1785740912000 + i * 100, "Bash")) + .collect(); + lines.push(self_report_row(1785740912700)); + fs::write(store.join("current.jsonl"), lines.join("\n") + "\n").unwrap(); + + run_once(&store, &state, &spool, HooksVerbosity::Decisions).await; + + let events = spooled(&spool); + let reports: Vec<_> = events + .iter() + .filter(|e| e["type"] == "self_report") + .collect(); + assert_eq!(reports.len(), 1); + assert_eq!(reports[0]["category"], "invalid_tool_or_credential"); + let agg = events + .iter() + .find(|e| e["type"] == "hook_completed" && e["failproofai_allow_count"].is_number()) + .expect("the plain allows still roll up"); + assert_eq!( + agg["failproofai_allow_count"], 5, + "the report row is not in it" + ); + assert!( + events + .iter() + .any(|e| e["type"] == "hook_completed" && e["tool_call_id"] == "toolu_01"), + "the report row keeps its exact hook pair" + ); + + fs::remove_dir_all(&store).ok(); + fs::remove_dir_all(&state).ok(); + fs::remove_dir_all(&spool).ok(); +} diff --git a/crates/fpai-collect/tests/self_report_mcp.rs b/crates/fpai-collect/tests/self_report_mcp.rs new file mode 100644 index 000000000..f05ba6ddb --- /dev/null +++ b/crates/fpai-collect/tests/self_report_mcp.rs @@ -0,0 +1,558 @@ +//! The daemon's Self Reports MCP server, driven over real HTTP on an ephemeral +//! loopback port: the JSON-RPC methods, the tool built from `self-report.json`, +//! the Host/Origin/body-size refusals and the fallback recording. + +use std::fs; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::sync::atomic::AtomicBool; +use std::time::{SystemTime, UNIX_EPOCH}; + +use fpai_collect::self_report::{self, Category, McpEndpoint, Settings}; +use fpai_collect::supervisor::Shutdown; +use serde_json::{Value, json}; + +fn tmpdir(name: &str) -> PathBuf { + let d = std::env::temp_dir().join(format!( + "fpai-sr-mcp-{}-{}-{}", + name, + std::process::id(), + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + fs::create_dir_all(&d).unwrap(); + d +} + +fn write_settings(home: &Path, enabled: bool, categories: Vec) { + self_report::write_settings( + &self_report::settings_path(home), + &Settings { + version: 1, + enabled, + source: "local".into(), + categories, + guidance: Some("Prefer one report.".into()), + mcp: McpEndpoint::on_port(4319), + updated_at: "2026-11-25T10:00:00Z".into(), + enrolment: None, + }, + ) + .unwrap(); +} + +struct Running { + port: u16, + stop: Arc, + task: tokio::task::JoinHandle<()>, + client: reqwest::Client, +} + +impl Running { + async fn start(home: &Path) -> Self { + Self::start_enrolled(home, false).await + } + + async fn start_enrolled(home: &Path, enrolled: bool) -> Self { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + let stop = Arc::new(AtomicBool::new(false)); + let sd = Shutdown::for_test(stop.clone()); + let home = home.to_path_buf(); + let task = tokio::spawn(async move { + self_report::serve_with_enrolment( + listener, + home, + sd, + Arc::new(move || { + if enrolled { + self_report::Enrolment::Enrolled(None) + } else { + self_report::Enrolment::NotEnrolled + } + }), + ) + .await + .unwrap(); + }); + Running { + port, + stop, + task, + client: reqwest::Client::new(), + } + } + + fn url(&self, query: &str) -> String { + format!("http://127.0.0.1:{}/mcp{query}", self.port) + } + + async fn rpc(&self, query: &str, body: Value) -> (u16, Option) { + let response = self + .client + .post(self.url(query)) + .header("Accept", "application/json, text/event-stream") + .header("Content-Type", "application/json") + .body(body.to_string()) + .send() + .await + .unwrap(); + let status = response.status().as_u16(); + let content_type = response + .headers() + .get("content-type") + .map(|v| v.to_str().unwrap().to_string()); + let text = response.text().await.unwrap(); + if text.is_empty() { + return (status, None); + } + assert_eq!(content_type.as_deref(), Some("application/json")); + (status, Some(serde_json::from_str(&text).unwrap())) + } + + async fn stop(self) { + self.stop.store(true, std::sync::atomic::Ordering::Relaxed); + self.task.await.unwrap(); + } +} + +async fn list(server: &Running) -> Value { + let request = json!({"jsonrpc":"2.0","id":1,"method":"tools/list"}); + server.rpc("", request).await.1.unwrap()["result"]["tools"].clone() +} + +fn event_files(home: &Path) -> Vec { + let dir = home.join("custom-agents").join("events"); + let Ok(entries) = fs::read_dir(&dir) else { + return Vec::new(); + }; + let mut out = Vec::new(); + for entry in entries.filter_map(Result::ok) { + if entry.path().extension().is_some_and(|x| x == "jsonl") { + for line in fs::read_to_string(entry.path()).unwrap().lines() { + out.push(serde_json::from_str(line).unwrap()); + } + } + } + out +} + +#[tokio::test(flavor = "multi_thread")] +async fn initialize_list_and_call_the_report_tool() { + let home = tmpdir("flow"); + write_settings(&home, true, self_report::default_categories()); + let server = Running::start(&home).await; + + let (status, reply) = server + .rpc( + "", + json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{ + "protocolVersion":"2025-06-18","capabilities":{}, + "clientInfo":{"name":"test","version":"0"}}}), + ) + .await; + assert_eq!(status, 200); + let reply = reply.unwrap(); + assert_eq!(reply["id"], 1); + assert_eq!(reply["result"]["protocolVersion"], "2025-06-18"); + assert_eq!(reply["result"]["serverInfo"]["name"], "failproofai_local"); + assert!(reply["result"]["capabilities"]["tools"].is_object()); + // The instructions Claude Code puts in the system prompt (its tools are + // deferred behind tool search, so the description alone is never seen). + assert_eq!( + reply["result"]["instructions"], + self_report::instructions( + &self_report::default_categories(), + Some("Prefer one report.") + ) + ); + + // An unknown revision is answered in ours. + let (_, reply) = server + .rpc( + "", + json!({"jsonrpc":"2.0","id":"x","method":"initialize","params":{"protocolVersion":"1999-01-01"}}), + ) + .await; + assert_eq!(reply.unwrap()["result"]["protocolVersion"], "2025-06-18"); + + let (status, reply) = server + .rpc( + "", + json!({"jsonrpc":"2.0","method":"notifications/initialized"}), + ) + .await; + assert_eq!((status, reply), (202, None)); + + let (_, reply) = server + .rpc("", json!({"jsonrpc":"2.0","id":2,"method":"ping"})) + .await; + assert_eq!(reply.unwrap()["result"], json!({})); + + let (_, reply) = server + .rpc("", json!({"jsonrpc":"2.0","id":3,"method":"tools/list"})) + .await; + let tools = reply.unwrap()["result"]["tools"].clone(); + assert_eq!(tools.as_array().unwrap().len(), 1); + let tool = &tools[0]; + assert_eq!(tool["name"], "report"); + let categories = self_report::default_categories(); + assert_eq!( + tool["description"], + self_report::describe(&categories, Some("Prefer one report.")) + ); + assert_eq!(tool["inputSchema"], self_report::input_schema(&categories)); + + let (status, reply) = server + .rpc( + "", + json!({"jsonrpc":"2.0","id":4,"method":"tools/call","params":{ + "name":"report","arguments":{"category":"looping","detail":"same edit three times"}}}), + ) + .await; + assert_eq!(status, 200); + let reply = reply.unwrap(); + assert_eq!(reply["id"], 4); + assert_eq!( + reply["result"]["content"], + json!([{"type":"text","text":"Recorded."}]) + ); + // No ?agent= (or a hook-recorded agent): nothing written server-side. + assert!(event_files(&home).is_empty()); + + let (_, reply) = server + .rpc( + "", + json!({"jsonrpc":"2.0","id":5,"method":"tools/call","params":{"name":"other","arguments":{}}}), + ) + .await; + assert_eq!(reply.unwrap()["error"]["code"], -32602); + let (_, reply) = server + .rpc( + "", + json!({"jsonrpc":"2.0","id":6,"method":"resources/list"}), + ) + .await; + assert_eq!(reply.unwrap()["error"]["code"], -32601); + + // A batch answers each request and skips the notification. + let (_, reply) = server + .rpc( + "", + json!([{"jsonrpc":"2.0","id":7,"method":"ping"},{"jsonrpc":"2.0","method":"notifications/initialized"}]), + ) + .await; + assert_eq!(reply.unwrap().as_array().unwrap().len(), 1); + + let response = server + .client + .post(server.url("")) + .body("{not json") + .send() + .await + .unwrap(); + assert_eq!(response.status().as_u16(), 400); + + let response = server.client.get(server.url("")).send().await.unwrap(); + assert_eq!(response.status().as_u16(), 405); + + server.stop().await; + fs::remove_dir_all(&home).ok(); +} + +#[tokio::test(flavor = "multi_thread")] +async fn the_tool_list_follows_the_settings_file() { + let home = tmpdir("follow"); + let init = json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18"}}); + let instructions = |reply: Option| reply.unwrap()["result"].get("instructions").cloned(); + + // Cloud enrolled and the daemon has not written the file yet: off. + let enrolled = Running::start_enrolled(&home, true).await; + assert_eq!(list(&enrolled).await, json!([]), "enrolled, no file: off"); + assert_eq!( + instructions(enrolled.rpc("", init.clone()).await.1), + None, + "enrolled, no file: no instructions field" + ); + enrolled.stop().await; + + // Not enrolled: on by default, with the default categories. + let server = Running::start(&home).await; + let tools = list(&server).await; + assert_eq!(tools[0]["name"], "report", "no file: on by default"); + assert_eq!( + tools[0]["inputSchema"]["properties"]["category"]["enum"][0], + "looping" + ); + assert!( + instructions(server.rpc("", init.clone()).await.1).is_some(), + "no file: instructions sent" + ); + + write_settings( + &home, + true, + vec![Category { + name: "org_custom".into(), + description: "An org's own category.".into(), + }], + ); + let tools = list(&server).await; + assert_eq!( + tools[0]["inputSchema"]["properties"]["category"]["enum"], + json!(["org_custom"]) + ); + let text = instructions(server.rpc("", init.clone()).await.1).unwrap(); + assert!( + text.as_str() + .unwrap() + .contains("`category` is one of: org_custom."), + "{text}" + ); + assert!( + text.as_str().unwrap().ends_with("\n\nPrefer one report."), + "{text}" + ); + + write_settings(&home, false, self_report::default_categories()); + assert_eq!(list(&server).await, json!([]), "disabled: empty list"); + assert_eq!( + instructions(server.rpc("", init.clone()).await.1), + None, + "disabled: no instructions field" + ); + + fs::write(self_report::settings_path(&home), "garbage").unwrap(); + assert_eq!(list(&server).await, json!([]), "unparsable: off"); + + server.stop().await; + fs::remove_dir_all(&home).ok(); +} + +#[tokio::test(flavor = "multi_thread")] +async fn foreign_hosts_and_origins_are_refused() { + let home = tmpdir("guard"); + write_settings(&home, true, self_report::default_categories()); + let server = Running::start(&home).await; + let body = json!({"jsonrpc":"2.0","id":1,"method":"ping"}).to_string(); + let send = |host: Option, origin: Option<&str>| { + let mut request = server.client.post(server.url("")).body(body.clone()); + if let Some(h) = host { + request = request.header("Host", h); + } + if let Some(o) = origin { + request = request.header("Origin", o); + } + async move { request.send().await.unwrap().status().as_u16() } + }; + let port = server.port; + assert_eq!(send(None, None).await, 200); + assert_eq!(send(Some(format!("localhost:{port}")), None).await, 200); + assert_eq!( + send(None, Some(&format!("http://localhost:{port}"))).await, + 200 + ); + assert_eq!(send(Some("evil.example".into()), None).await, 403); + assert_eq!(send(Some(format!("evil.example:{port}")), None).await, 403); + assert_eq!(send(None, Some("https://evil.example")).await, 403); + assert_eq!(send(None, Some("null")).await, 403); + + // A refused GET is refused for its Host, before its method. + let status = server + .client + .get(server.url("")) + .header("Origin", "http://evil.example") + .send() + .await + .unwrap() + .status() + .as_u16(); + assert_eq!(status, 403); + + let big = format!( + r#"{{"jsonrpc":"2.0","id":1,"method":"ping","params":{{"pad":"{}"}}}}"#, + "x".repeat(70 * 1024) + ); + let status = server + .client + .post(server.url("")) + .body(big) + .send() + .await + .unwrap() + .status() + .as_u16(); + assert_eq!(status, 413); + + server.stop().await; + fs::remove_dir_all(&home).ok(); +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_server_recorded_agent_gets_its_report_written() { + let home = tmpdir("record"); + write_settings(&home, true, self_report::default_categories()); + let activity = home.join("hook-activity"); + fs::create_dir_all(&activity).unwrap(); + let now = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_millis() as i64; + fs::write( + activity.join("current.jsonl"), + json!({"timestamp": now - 1000, "eventType": "PreToolUse", "integration": "openclaw", + "sessionId": "oc-session", "cwd": "/srv/agents/helpdesk", "decision": "allow"}) + .to_string() + + "\n", + ) + .unwrap(); + let server = Running::start(&home).await; + let call = |query: &'static str, category: &'static str| { + server.rpc( + query, + json!({"jsonrpc":"2.0","id":1,"method":"tools/call","params":{ + "name":"report","arguments":{"category":category,"detail":"the ticket API returns 401"}}}), + ) + }; + + // Hook-recorded agents are never written here: their hook already does. + let (_, reply) = call("?agent=claude", "invalid_tool_or_credential").await; + assert_eq!(reply.unwrap()["result"]["content"][0]["text"], "Recorded."); + assert!(event_files(&home).is_empty()); + + let (_, reply) = call("?agent=openclaw", "invalid_tool_or_credential").await; + assert_eq!(reply.unwrap()["result"]["content"][0]["text"], "Recorded."); + let events = event_files(&home); + assert_eq!(events.len(), 1); + let event = &events[0]; + assert_eq!(event["type"], "self_report"); + assert_eq!(event["session_id"], "oc-session"); + assert_eq!(event["agent_id"], "openclaw-helpdesk"); + assert_eq!(event["integration"], "openclaw"); + assert_eq!(event["source"], "mcp"); + assert_eq!(event["category"], "invalid_tool_or_credential"); + assert_eq!(event["detail"], "the ticket API returns 401"); + assert_eq!(event["environment"], "local"); + + // No matching session: still recorded, unattributed. + let (_, _) = call("?agent=goose", "made_up").await; + let events = event_files(&home); + let goose = events + .iter() + .find(|e| e["integration"] == "goose") + .expect("recorded"); + assert_eq!(goose["session_id"], "unattributed"); + // An unlisted category is recorded as the listed one it resolves to (the 401). + assert_eq!(goose["category"], "invalid_tool_or_credential"); + + // No category at all (seen live from Copilot): inferred from the detail. + let detail = "Deployment is blocked because ./deploy.sh exits with \"DEPLOY_TOKEN is not set\" and no token is available in this environment."; + let (_, reply) = server + .rpc( + "?agent=copilot", + json!({"jsonrpc":"2.0","id":3,"method":"tools/call","params":{ + "name":"report","arguments":{"detail": detail}}}), + ) + .await; + assert_eq!(reply.unwrap()["result"]["content"][0]["text"], "Recorded."); + let events = event_files(&home); + let copilot = events + .iter() + .find(|e| e["integration"] == "copilot") + .expect("recorded"); + assert_eq!(copilot["category"], "invalid_tool_or_credential"); + assert_eq!(copilot["detail"], detail); + + // A model that guessed the argument names: the detail is kept, extras ignored. + let (_, reply) = server + .rpc( + "?agent=pi", + json!({"jsonrpc":"2.0","id":2,"method":"tools/call","params":{ + "name":"report","arguments":{"category":"looping","sentence":"same edit again","extra":1}}}), + ) + .await; + assert_eq!(reply.unwrap()["result"]["content"][0]["text"], "Recorded."); + let events = event_files(&home); + let pi = events + .iter() + .find(|e| e["integration"] == "pi") + .expect("recorded"); + assert_eq!(pi["category"], "looping"); + assert_eq!(pi["detail"], "same edit again"); + + server.stop().await; + fs::remove_dir_all(&home).ok(); +} + +#[test] +fn spawn_reports_whether_it_is_listening() { + let home = tmpdir("spawn"); + let stop = Arc::new(AtomicBool::new(false)); + + // Bound: `true`, and the port answers. + let holder = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let port = holder.local_addr().unwrap().port(); + drop(holder); + let (tx, rx) = std::sync::mpsc::channel(); + let handle = self_report::spawn(home.clone(), port, stop.clone(), tx).unwrap(); + assert_eq!( + rx.recv_timeout(std::time::Duration::from_secs(10)), + Ok(true) + ); + assert!(std::net::TcpStream::connect(("127.0.0.1", port)).is_ok()); + + // Busy port: `false`, and the daemon carries on. + let (tx2, rx2) = std::sync::mpsc::channel(); + let busy = self_report::spawn(home.clone(), port, stop.clone(), tx2).unwrap(); + assert_eq!( + rx2.recv_timeout(std::time::Duration::from_secs(10)), + Ok(false) + ); + busy.join().unwrap(); + + stop.store(true, std::sync::atomic::Ordering::Relaxed); + handle.join().unwrap(); + fs::remove_dir_all(&home).ok(); +} + +#[tokio::test(flavor = "multi_thread")] +async fn http_hides_the_tool_for_a_local_file_while_enrolled_and_for_another_version() { + let home = tmpdir("gate"); + // Enrolled, with this machine's own file on: the org decides, and it has + // not been written yet, so the HTTP server agrees with the CLI: off. + write_settings(&home, true, self_report::default_categories()); + let enrolled = Running::start_enrolled(&home, true).await; + assert_eq!( + list(&enrolled).await, + json!([]), + "enrolled, local file: off" + ); + enrolled.stop().await; + let open = Running::start(&home).await; + assert_eq!( + list(&open).await[0]["name"], + "report", + "not enrolled, local file: on" + ); + open.stop().await; + + // A complete enabled file in a version this build does not know: off, as + // the CLI's reader and the stdio server read it. + let path = self_report::settings_path(&home); + let mut raw: Value = serde_json::from_str(&fs::read_to_string(&path).unwrap()).unwrap(); + raw["version"] = json!(2); + raw["source"] = json!("cloud"); + fs::write(&path, serde_json::to_string(&raw).unwrap()).unwrap(); + for enrolled in [false, true] { + let server = Running::start_enrolled(&home, enrolled).await; + assert_eq!( + list(&server).await, + json!([]), + "version 2, enrolled={enrolled}: off" + ); + server.stop().await; + } + fs::remove_dir_all(&home).ok(); +} diff --git a/crates/fpai-ipc/src/envelope.rs b/crates/fpai-ipc/src/envelope.rs index ae7808144..1a7ce044d 100644 --- a/crates/fpai-ipc/src/envelope.rs +++ b/crates/fpai-ipc/src/envelope.rs @@ -8,7 +8,10 @@ use serde::{Deserialize, Serialize}; -/// Bumped whenever a change is made to either message enum below. +/// Bumped whenever a request or reply gains a field that changes how a request +/// is answered. A new one-way message ([`ClientMessage::SelfReportLog`]) needs +/// no bump: an older daemon fails to parse its unknown `type` and closes the +/// connection, which is exactly "ignored" for a message that expects no reply. pub const PROTOCOL_VERSION: u32 = 2; /// The oldest version the daemon still answers, and the oldest a client will @@ -72,13 +75,72 @@ pub enum ClientMessage { #[serde(default, skip_serializing_if = "Option::is_none")] agent_settings_path: Option, }, + /// One Self Reports MCP event from a process outside the daemon (the + /// stdio server `failproofai mcp`, or a CLI `self-report sync`), for the + /// daemon's log. One-way: the daemon writes no reply and the sender does + /// not wait for one. An older daemon cannot parse it and closes the + /// connection, which drops it. + #[serde(rename_all = "camelCase")] + SelfReportLog { + protocol_version: u32, + event: SelfReportLogEvent, + }, +} + +/// See [`ClientMessage::SelfReportLog`]. Every field but `event` is optional +/// and unknown fields are ignored, so either side can add one. +#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase", default)] +pub struct SelfReportLogEvent { + /// `initialize`, `tools/list`, `tools/call`, `sync` or `error`. + pub event: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub agent: Option, + /// `stdio` (the stdio server) or `cli` (a sync). + #[serde(skip_serializing_if = "Option::is_none")] + pub transport: Option, + /// For a call: `recorded`, `skipped` or `failed`. + #[serde(skip_serializing_if = "Option::is_none")] + pub outcome: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub reason: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub category: Option, + /// Whether the category the model sent is on the settings' list; when it + /// is not, `category` is the one it was resolved to. + #[serde(skip_serializing_if = "Option::is_none")] + pub known_category: Option, + /// What the model sent as the category (maybe empty), when `category` + /// was inferred from it. Absent from a sender older than inference. + #[serde(skip_serializing_if = "Option::is_none")] + pub raw_category: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub session: Option, + /// The start of the report's detail. The daemon scrubs secrets from it + /// and cuts it again before it logs anything. + #[serde(skip_serializing_if = "Option::is_none")] + pub preview: Option, + /// A sync's result: `added claude (http); removed pi; failed …`. + #[serde(skip_serializing_if = "Option::is_none")] + pub summary: Option, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] #[serde(tag = "type", rename_all = "camelCase")] pub enum ServerMessage { #[serde(rename_all = "camelCase")] - Pong { protocol_version: u32 }, + Pong { + protocol_version: u32, + /// The Self Reports MCP server this daemon is serving, present only + /// while its loopback listener is bound. An optional, additive field + /// that older clients ignore. A client about to point agents at + /// `http://127.0.0.1:/mcp` compares this with the `instanceId` + /// the endpoint's `initialize` returns, which proves the port is held + /// by the daemon behind THIS socket and not by another daemon (another + /// user or another FAILPROOFAI_HOME) whose own bind won. + #[serde(default, skip_serializing_if = "Option::is_none")] + self_report: Option, + }, #[serde(rename_all = "camelCase")] HookResult { protocol_version: u32, @@ -109,6 +171,17 @@ pub enum ServerMessage { }, } +/// See [`ServerMessage::Pong`]. +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub struct SelfReportServer { + /// Random per daemon process; the MCP `initialize` result carries the + /// same value as `serverInfo.instanceId`. + pub instance_id: String, + /// The loopback port the MCP listener bound. + pub port: u16, +} + impl ClientMessage { pub fn protocol_version(&self) -> u32 { match self { @@ -119,6 +192,9 @@ impl ClientMessage { ClientMessage::PolicyEvaluation { protocol_version, .. } => *protocol_version, + ClientMessage::SelfReportLog { + protocol_version, .. + } => *protocol_version, } } } @@ -160,7 +236,7 @@ impl ClientMessage { cwd, agent_settings_path: agent_settings_path.filter(|_| keep_settings), }, - ping @ ClientMessage::Ping { .. } => ping, + other @ (ClientMessage::Ping { .. } | ClientMessage::SelfReportLog { .. }) => other, } } } @@ -170,7 +246,9 @@ impl ServerMessage { /// checks for its own version accepts an answer from a newer daemon. pub fn with_protocol_version(mut self, version: u32) -> Self { match &mut self { - ServerMessage::Pong { protocol_version } + ServerMessage::Pong { + protocol_version, .. + } | ServerMessage::HookResult { protocol_version, .. } @@ -186,7 +264,9 @@ impl ServerMessage { pub fn protocol_version(&self) -> u32 { match self { - ServerMessage::Pong { protocol_version } => *protocol_version, + ServerMessage::Pong { + protocol_version, .. + } => *protocol_version, ServerMessage::HookResult { protocol_version, .. } => *protocol_version, @@ -300,6 +380,61 @@ mod tests { assert_eq!(decoded, msg); } + #[test] + fn a_pong_carries_the_self_report_server_only_when_there_is_one() { + let bare = ServerMessage::Pong { + protocol_version: PROTOCOL_VERSION, + self_report: None, + }; + let json = serde_json::to_value(&bare).unwrap(); + assert!(json.get("selfReport").is_none(), "{json}"); + // A pong from a daemon that predates the field still parses. + let old: ServerMessage = + serde_json::from_value(serde_json::json!({"type": "pong", "protocolVersion": 2})) + .unwrap(); + assert_eq!(old, bare); + let full = ServerMessage::Pong { + protocol_version: PROTOCOL_VERSION, + self_report: Some(SelfReportServer { + instance_id: "abc".into(), + port: 4319, + }), + }; + let json = serde_json::to_value(&full).unwrap(); + assert_eq!(json["selfReport"]["instanceId"], "abc"); + assert_eq!(json["selfReport"]["port"], 4319); + assert_eq!(serde_json::from_value::(json).unwrap(), full); + } + + #[test] + fn a_self_report_log_reads_with_only_its_event_and_ignores_unknown_fields() { + let msg: ClientMessage = serde_json::from_value(serde_json::json!({ + "type": "selfReportLog", + "protocolVersion": PROTOCOL_VERSION, + "event": {"event": "tools/call", "agent": "copilot", "knownCategory": false, "rawCategory": "", "later": 1} + })) + .unwrap(); + let ClientMessage::SelfReportLog { event, .. } = msg else { + panic!("expected SelfReportLog"); + }; + assert_eq!(event.event, "tools/call"); + assert_eq!(event.agent.as_deref(), Some("copilot")); + assert_eq!(event.known_category, Some(false)); + assert_eq!(event.raw_category.as_deref(), Some("")); + assert_eq!(event.session, None); + // Absent fields stay off the wire. + let json = serde_json::to_value(ClientMessage::SelfReportLog { + protocol_version: PROTOCOL_VERSION, + event: SelfReportLogEvent { + event: "initialize".into(), + ..Default::default() + }, + }) + .unwrap(); + assert_eq!(json["type"], "selfReportLog"); + assert_eq!(json["event"], serde_json::json!({"event": "initialize"})); + } + #[test] fn protocol_version_accessor_matches_every_variant() { assert_eq!( diff --git a/crates/fpai-ipc/src/lib.rs b/crates/fpai-ipc/src/lib.rs index af3d2e0f3..261a69462 100644 --- a/crates/fpai-ipc/src/lib.rs +++ b/crates/fpai-ipc/src/lib.rs @@ -7,7 +7,7 @@ pub mod framing; pub mod peer; pub use envelope::{ - ClientMessage, MIN_PROTOCOL_VERSION, PROTOCOL_VERSION, ServerMessage, - is_supported_protocol_version, + ClientMessage, MIN_PROTOCOL_VERSION, PROTOCOL_VERSION, SelfReportLogEvent, SelfReportServer, + ServerMessage, is_supported_protocol_version, }; pub use framing::{FramingError, MAX_FRAME_LEN, read_message, write_message}; diff --git a/docs/docs.json b/docs/docs.json index 907ce3131..8a3b30c17 100644 --- a/docs/docs.json +++ b/docs/docs.json @@ -152,6 +152,7 @@ "group": "Find and manage failures", "pages": [ "sessions/sentiment", + "self-reports", "audits/overview", "audits/local-audit", "audits/setup", diff --git a/docs/policies/local-configuration.mdx b/docs/policies/local-configuration.mdx index 46fcbace5..2d394823d 100644 --- a/docs/policies/local-configuration.mdx +++ b/docs/policies/local-configuration.mdx @@ -22,6 +22,8 @@ failproofai policies Not every harness supports local scope; the CLI rejects a scope the selected harness cannot represent. +Project-scope hooks run `npx -y failproofai`, so the committed file names no machine's path (Pi's are the exception: its project file points at the extension inside the installed package). npx runs a `failproofai` the project provides before the installed one: `node_modules/.bin/failproofai` in the project or any directory above it, or a `failproofai` entry in the project's `package.json` `bin`. It also applies the project's `.npmrc` and your own `~/.npmrc`. `block-failproofai-commands` refuses agent commands and file edits that write `node_modules/.bin/failproofai` or put a directory onto a `node_modules/.bin`. It does not refuse a dependency install or an edit to `package.json` or `.npmrc`, any of which can replace what the hook runs. It reads a command as written and as the shell expands it, with the sed scripts, patches and curl configs the command names, so it cannot see a path a command only computes as it runs: one read from a pipe or a file (`read`, `xargs`), one a sourced file sets, one a tool takes from its own configuration (`~/.curlrc`, `~/.wgetrc`), or one a script run by an interpreter writes (`python -c`, `node -e`, `awk`). User-scope hooks, which `failproofai config` installs, run the installed CLI by its absolute path, so a repository does not decide which CLI they run: where an agent must not be able to change its own enforcement from inside a repository, keep its user-scope hooks installed. + Which pack policies are on is **not** scoped. The switch is recorded with the installed pack, so `failproofai policies add ` turns a policy on for the whole machine, whatever `--scope` says. | Scope | Policy configuration file | diff --git a/docs/reference/custom-agents-typescript.mdx b/docs/reference/custom-agents-typescript.mdx index 39785bf81..247ea8c19 100644 --- a/docs/reference/custom-agents-typescript.mdx +++ b/docs/reference/custom-agents-typescript.mdx @@ -194,7 +194,7 @@ A `using` block that catches its own failure reports it with `span.fail(error)` ## Event catalog -The same fifteen methods as the Python SDK, in camelCase. Most come in **pairs** — you call the opener, then the closer, and the SDK times the gap. +The same sixteen methods as the Python SDK, in camelCase. Most come in **pairs** — you call the opener, then the closer, and the SDK times the gap. | | Opens | Closes | | --- | --- | --- | @@ -205,7 +205,7 @@ The same fifteen methods as the Python SDK, in camelCase. Most come in **pairs** | **Hooks** | `hookTriggered` | `hookCompleted` | | **Humans** | `humanWait` | `humanInput` | -Three stand alone: `error`, `humanPause`, `humanInterrupt`. +Four stand alone: `error`, `humanPause`, `humanInterrupt`, and `selfReport` (see [Self Reports](#self-reports)). @@ -228,6 +228,7 @@ Every method also takes `sessionId` and `agentId`, which the scopes fill in for | `humanInput` | `inputId` | `response` | | `humanPause` | — | `reason`, `userId` | | `humanInterrupt` | — | `reason`, `userId`, `atStep` | +| `selfReport` | `category` | `detail`, `toolCallId` | Any other key you add becomes a custom payload field. Namespace anything framework-specific `fw_*`; a name that collides with a declared field is refused rather than silently overwriting a promoted column. @@ -393,6 +394,30 @@ Identity is ambient: everything inside `agent()` lands on that run's session wit [`sdk/typescript/examples/research-agent.ts`](https://github.com/FailproofAI/failproofai/blob/main/sdk/typescript/examples/research-agent.ts) in the repository is the complete, runnable version: a real OpenAI tool loop instrumented exactly like this, run in CI on every change as an ES module and as CommonJS. +## Self Reports + +Offer your agent one more tool, `failproofai_report`, so the model can say it is stuck. The call records a `self_report` event in the current session and agent, with `source: "sdk"`, and answers `Recorded.`. See [Self Reports](/self-reports) for the categories. + +With a framework, add the ready-made tool from its subpath: + +```ts +import { selfReportTool } from "@failproofai/sdk/ai"; // Vercel AI SDK +await generateText({ model, prompt, tools: { failproofai_report: selfReportTool(), ...tools } }); + +import { selfReportTool } from "@failproofai/sdk/langchain"; // @langchain/core +createReactAgent({ llm, tools: [selfReportTool(), ...tools] }); +``` + +`@failproofai/sdk/mastra` and `@failproofai/sdk/llamaindex` export the same `selfReportTool()`. With a provider SDK directly: + +```ts +const tools = [failproofai.openaiTool(), ...yours]; // or openaiResponsesTool(), anthropicTool() +const answer = failproofai.handleToolCall(call.name, call.arguments, { toolCallId: call.id }); +if (answer !== null) toolResults.push({ id: call.id, content: answer }); // "Recorded." +``` + +`handleToolCall` returns `null` for any other tool and never throws. `failproofai.selfReport(category, detail)` records a report from your own code, `failproofai.selfReportSpec()` returns `{ name, description, inputSchema }` for any other tool format, and `failproofai.isSelfReportTool(name)` lets you hide the call in your UI. The categories come from `~/.failproofai/self-report.json`, else the six defaults. Edge builds offer the same tools, which answer `Recorded.` and record nothing. + ## Evaluations ```ts diff --git a/docs/reference/events-and-configuration.mdx b/docs/reference/events-and-configuration.mdx index 82e932b12..2e5e3064b 100644 --- a/docs/reference/events-and-configuration.mdx +++ b/docs/reference/events-and-configuration.mdx @@ -12,9 +12,24 @@ icon: "list-tree" - Hook triggered and completed - Human wait, input, pause, and interrupt - Explicit errors +- Self reports (`self_report`): an agent saying it is stuck Every event carries a timestamp, session ID, agent ID, event type, and environment. Event-specific fields contain model, tool, correlation, outcome, content, duration, or error data. +### The `self_report` event + +Written when an agent calls the [Self Reports](/self-reports) tool. Besides the common fields it carries: + +| Field | Value | +| --- | --- | +| `category` | The category the agent chose, recorded as given even when it is not on the list | +| `detail` | The agent's one-sentence description of what blocks it, at most 2,000 characters, cut between words (a single longer word reads `[detail cut]`); `""` when it gave none | +| `source` | `mcp` from a coding agent (its hook or failproofai's MCP server), `sdk` from the Python or TypeScript SDK | +| `tool_call_id` | The model's id for the call, when known | +| `integration` | The coding agent it came from, such as `claude` or `hermes` (not set by the SDKs) | + +A report the MCP server records itself is attributed to that agent's newest session in the same working directory within the last 6 hours, else to the session `unattributed`. + ## Inspect an event contract @@ -61,9 +76,26 @@ Do not use `timestamp`, `session_id`, `agent_id`, `type`, or `environment` as cu - `failproofai-sdk` always spools under `~/.failproofai/custom-agents`. `FAILPROOFAI_HOME` relocates that home; the `custom-agents` segment is always appended, so the spool cannot be placed outside it. Only the SDK's own `configure(base_dir=...)` writes elsewhere. `AGENTEYE_HOME` is read by the older `agenteye-collector` to choose what to watch, and no longer affects where the SDK writes. - Environment labels can be set through SDK configuration or `AGENTEYE_ENVIRONMENT`. - Daemon credentials are stored separately from non-secret settings. +- `~/.failproofai/self-report.json` holds the effective [Self Reports](/self-reports) setting every reader uses: the daemon's MCP server, `failproofai mcp`, both SDKs, and `failproofai self-report status`. Self Reports is on by default: a missing file means on with the default categories, except on a machine connected to Failproof AI Cloud, where it means off until `failproofaid` writes the file from your organization's setting. A file that cannot be parsed means off. Use stable, low-cardinality environment names. Commas are not supported in daemon environment labels. +### `self-report.json` + +```json +{ + "version": 1, + "enabled": true, + "source": "cloud", + "categories": [{ "name": "looping", "description": "You keep repeating the same or circular steps without making progress." }], + "guidance": null, + "mcp": { "port": 4319, "url": "http://127.0.0.1:4319/mcp" }, + "updatedAt": "2026-11-25T10:00:00Z" +} +``` + +`source` is `cloud` when `failproofaid` wrote it from your organization's setting, or `local` when failproofai wrote it on this machine: `policies --install` and `config` write it on when it is missing, and `failproofai self-report enable` or `disable` rewrite it. The file is written atomically with mode 0644, so agent processes running as another account can read it. `FAILPROOFAI_HOME` moves it with the rest of `~/.failproofai`, and `FAILPROOFAI_SELF_REPORT_PORT`, read when the daemon starts, sets the port. + ## Change an environment label diff --git a/docs/reference/failproof-cli.mdx b/docs/reference/failproof-cli.mdx index 81d079e66..a8aa2876b 100644 --- a/docs/reference/failproof-cli.mdx +++ b/docs/reference/failproof-cli.mdx @@ -179,6 +179,12 @@ Use configuration files for persistent machine behavior. Environment variables a Agent-specific home variables such as `CLAUDE_PROJECTS_PATH`, `CURSOR_HOME`, `HERMES_HOME`, and `OPENCLAW_HOME` override where Failproof AI discovers local sessions for that harness. +## Agent hook settings + +Agents cannot edit the files their CLI loads failproofai's hooks from: Claude Code's `settings*.json` in `~/.claude/` and in any project's `.claude/`, Codex's `hooks.json` and `config.toml`, and the hook and plugin files of the other supported agents, also when they reach them through a symlink. One line there can switch every policy off — in Claude Code, `"disableAllHooks": true` in the highest-precedence settings file that sets the key, though only managed settings can switch off hooks that managed settings install — so `block-failproofai-commands` refuses those writes, from file tools and from the shell alike. It judges a shell command by its text, so a script written earlier and run later is not seen. This guard does not restrict reading these files; if a read is denied, the opt-in `block-read-outside-cwd` policy denied it. Change them yourself, or with `failproofai policies --install` and `--uninstall`. + +`failproofai config --status` reports a `disableAllHooks` that is switching failproofai's Claude Code hooks off, and names the file that sets it. + ## Pause or remove a machine safely ```bash diff --git a/docs/reference/mcp.mdx b/docs/reference/mcp.mdx index 8d63fdd24..b6cc097f6 100644 --- a/docs/reference/mcp.mdx +++ b/docs/reference/mcp.mdx @@ -14,6 +14,10 @@ There is one address for everyone, hosted or self-hosted: https://gateway.befailproof.ai/mcp ``` + + This page is about the **Cloud MCP gateway**, which lets you query Failproof AI Cloud from an AI tool. It is not the local `failproofai_local` MCP server that [Self Reports](#the-local-self-reports-server) adds to your agents. + + ## Connect a client Add the address to your client. The first time a tool is used, your browser opens. Choose where your Failproof AI Cloud is, sign in, pick one organization, and select **Allow**. **Cancel** connects nothing. @@ -120,6 +124,19 @@ Tool calls and their results pass through the hosted Failproof AI gateway on the Results go to the AI tool you connected, and that tool's provider handles them under its own terms. For each tool call, Failproof AI logs the tool's name, its outcome, how long it took, and the organization, never the arguments or results. See the [privacy policy](https://befailproof.ai/privacy/). +## The local Self Reports server + +[Self Reports](/self-reports) registers a different MCP server in your agents, named `failproofai_local`. It runs on your machine, serves one tool, `report`, and needs no sign-in: + +| | Cloud MCP gateway | Local Self Reports server | +| --- | --- | --- | +| Address | `https://gateway.befailproof.ai/mcp` | `http://127.0.0.1:4319/mcp` (served by `failproofaid`, for Claude Code and Codex), or `failproofai mcp` over stdio | +| Who adds it | You, in each client | failproofai, in every agent with failproofai hooks, while Self Reports is on | +| What it offers | Your organization's data, with your permissions | One `report` tool an agent calls when it is stuck | +| Sign-in | OAuth, one organization per connection | None. It answers only on `127.0.0.1` and refuses requests from web pages | + +The two have different names, so they coexist in the same agent: add the gateway as `failproofai` and failproofai adds `failproofai_local` beside it. failproofai never changes, removes or reports an entry named `failproofai`, and a call to one of the gateway's tools goes through your policies like any other tool call. + ## Troubleshooting | What you see | What to do | diff --git a/docs/self-reports.mdx b/docs/self-reports.mdx new file mode 100644 index 000000000..6dcd74c30 --- /dev/null +++ b/docs/self-reports.mdx @@ -0,0 +1,186 @@ +--- +title: "Self Reports" +description: "Let your agents tell you when they are stuck: looping, a broken credential, missing context, or a request they cannot do." +icon: "flag" +--- + +Self Reports gives every agent one extra tool, `report`. An agent that is blocked and cannot make progress on its own calls it with a category and one factual sentence. Failproof AI records the call as a `self_report` event on the agent's session, and the tool answers `Recorded.`. + +A report never unblocks the agent and never changes a decision. Afterwards the agent works around the problem or tells the user what is blocking it. No policy can block or rewrite a report: failproofai's hook allows the call before any policy, session pause, or Jev review runs. + +## Where reports show up + +Reports are internal to your organization. In Failproof AI Cloud a report appears on the agent's session timeline, at the point the agent made it, and on the `self_report` event itself. The Cloud audit agent always sees reports when it reads a session's transcript. There is no separate Self Reports page: what Cloud keeps for Self Reports is its settings (on or off, categories, guidance) and alerts. + +## On by default + +Self Reports is on as soon as failproofai is installed. `failproofai policies --install` and `failproofai config` register the `failproofai_local` MCP server in every agent they install hooks for, and write `~/.failproofai/self-report.json` with the default categories so every reader sees the same settings. + + + + On a machine connected to Failproof AI Cloud, the setting comes from your organization, and it is on unless someone turned it off. + + 1. Go to **settings → self reports**. + 2. Keep it on, or switch it off. Keep the default categories or write your own, and optionally add guidance for the agents. + + Every connected machine picks the change up on its next policy poll. `failproofaid` writes `~/.failproofai/self-report.json` from it and adds the `failproofai_local` MCP server to every agent that has failproofai hooks, or removes it when the switch is off. Until the first poll after connecting writes that file, the machine treats Self Reports as off. The daemon updates the agents whenever what their entries depend on changes: the first time it writes the file, when the file's source changes (a machine's own file replaced by the organization's), when the switch flips, and when the port changes. + + The file is bound to the enrolment whose poll wrote it. After the machine switches to another organization, or reconnects with a new token, the previous file reads as missing (off) until the new enrolment's setting is written. + + On a Cloud-managed machine, `failproofai self-report enable` and `disable` refuse and point you to the dashboard. + + + ```bash + failproofai self-report status + failproofai self-report disable + failproofai self-report enable + failproofai self-report test --agent claude + ``` + + With no settings file and no `selfReport` block in `~/.failproofai/config.json`, Self Reports is on with the default categories. + + `failproofai self-report disable` turns it off. It writes `enabled: false` to the `selfReport` block of `~/.failproofai/config.json` and to `~/.failproofai/self-report.json`, and removes the MCP entries from every agent. Your categories are kept for next time. An agent that is already running keeps the tool it loaded, but from then on its calls are allowed and not recorded. An explicit `enabled: false` always wins: a later install leaves it off. + + `failproofai self-report enable` turns it back on and registers the MCP server again. To replace the default categories, pass `--categories-file `, a JSON list of `{name, description}`. To append instructions to the tool's description, pass `--guidance ""`. + + `test` sends one report end to end as the agent you name and shows where it landed. + + + +A settings file that cannot be parsed counts as off, so a broken file never starts recording. Run `failproofai self-report enable` or `disable` to write it again. + +## Categories + +An organization's own list replaces these entirely. Names are lowercase letters, digits, and underscores; a list holds 1 to 32 categories. + +| Category | Description shown to the agent | +| --- | --- | +| `looping` | You keep repeating the same or circular steps without making progress. | +| `cannot_do_request` | The user asked for something you cannot do here: a missing capability, tool or permission, or it is only possible by cheating. | +| `invalid_tool_or_credential` | A tool, MCP server, plugin, API key or token you need is broken, invalid, expired or rejected. | +| `missing_context` | Information or access you need is missing and you cannot get it yourself. Not for normal clarifying questions. | +| `repeated_tool_failure` | A command or tool failed on several distinct attempts and is blocking you. A single error is not enough. | +| `task_failure` | You genuinely tried and could not complete the task, or something else blocks you that no other category describes. Not for refusals or policy blocks. | + +A report is always filed under a category on the list. A missing category, a near-miss spelling such as `Invalid Tool Or Credential`, or a name that is not listed is resolved to the listed name it normalises to, else to the first listed category whose keywords appear in the category or detail (a missing token or a 401 is `invalid_tool_or_credential`, going in circles is `looping`), else to `task_failure`, or to the first category of a list without it. The detail is cut to 2,000 characters (Unicode code points, so an emoji or other character outside the Basic Multilingual Plane counts once and is never split), and never in the middle of a word: when the cut lands inside one, that whole word goes, so a long token or key running past the cut is never kept in part, where redaction could no longer recognise it. A detail that is a single word longer than that reads `[detail cut]`. An agent that calls the tool without loading its schema sometimes guesses the argument names, so when `detail` is missing or empty the first non-empty of `summary`, `sentence`, `message`, `description`, `reason`, `text` and `details` is recorded instead, and when `category` is, `type` or `kind`. Other unknown arguments are ignored; a call is never rejected. + +## Agent support + +failproofai registers one MCP server, named `failproofai_local`, in each agent's user-level MCP settings, except Pi, Hermes and OpenClaw, whose tool comes from failproofai's own extension or plugin (see below). Agents see the tool as `mcp__failproofai_local__report` (Claude Code, Codex, Factory, Devin, Pi), `failproofai_local_report` (OpenCode), `mcp_failproofai_local_report` (Hermes, Antigravity) or `failproofai_local__report` (OpenClaw, Goose). The name is not `failproofai`, which is the name the [Cloud MCP gateway](/reference/mcp) is usually added under, so the two coexist; no tool of a server named `failproofai` is ever let past your policies, in any agent's spelling. Every entry runs `failproofai mcp --agent ` over stdio. Claude Code and Codex used to point at the daemon's local server, `http://127.0.0.1:4319/mcp`, while their hooks would run, but the entry is per user and a project can switch the hooks off (`disableAllHooks` in `.claude/settings.local.json`), and that endpoint records nothing for an agent whose hook records, so such a project's reports were lost. Over stdio the server records any report the hook did not (see [When the hooks do not run](#when-the-hooks-do-not-run)), and every other agent's report is recorded by the server, which needs the agent's working directory to find the session (see below). Every entry is marked as failproofai's, so removing it never touches a server you added. + +The sync writes the stdio command as the `failproofai` that npm installed beside the daemon's Node, so it finds it even under the service's own `PATH`, and when it cannot update an agent the daemon's log names the agent and the reason. When the daemon starts, it re-runs `failproofai self-report sync`. An HTTP entry an earlier version wrote is moved to stdio by the next sync, and `failproofai self-report status` repairs one it finds. A running agent keeps the server it loaded at startup. The daemon's HTTP server (`FAILPROOFAI_SELF_REPORT_PORT` moves it) still serves the Hermes and OpenClaw plugins, which check that it answers as the daemon behind this account's socket (both carry the daemon's instance id) before they send it anything, and any entry written by hand. + +### How the tool reaches the model + +The server sends short instructions in the MCP handshake: when to report, the category names, and your guidance. Several agents load MCP tools only on demand, behind a tool search, which shows the model a name and no description. failproofai keeps the tool direct, or the instructions in front of the model, in every agent: + +| Agent | How the tool and its instructions reach the model | +| --- | --- | +| Claude Code | The entry sets `alwaysLoad: true`, so its tools are never deferred behind tool search. Server instructions go in the system prompt. | +| Codex | In code mode (Codex 0.172) tools run through `exec`, MCP tools are deferred, and only about the first 250 characters of the server's instructions and of the tool's description are shown, so both open with what to do: when stuck, call `failproofai_local`'s `report` tool with a `category` and a one-sentence `detail`. The same instructions, with your categories and guidance, also go in a marked block (`` to ``) in the global `~/.codex/AGENTS.md` (under `CODEX_HOME` when set; `AGENTS.override.md` when that file exists, since Codex then reads it instead), which Codex loads in every session, with one more line: search your tools for `failproofai_local` if `report` is not listed. Nothing outside the markers is changed; removing the block deletes the file only when nothing else is left in it. | +| Cursor | MCP tools are listed directly. | +| Copilot CLI | Tools are listed directly. Copilot passes server instructions only for its built-in allowlist (or with `--allow-all-mcp-server-instructions`), so the same instructions go in a marked `~/.copilot/instructions/failproofai-self-reports.instructions.md` (under `COPILOT_HOME` when set), written and removed with the entry. | +| OpenCode | MCP tools are listed directly. | +| Pi | failproofai's Pi extension registers the tool, with the instructions in the system prompt. | +| Hermes | failproofai's Hermes plugin registers the tool natively and adds it to Hermes' never-deferred list, so `tools.tool_search` does not hide it, with the instructions in `pre_llm_call` context. | +| OpenClaw | failproofai's OpenClaw plugin registers a `catalogMode: "direct-only"` tool, which Tool Search never defers. `before_prompt_build` returns the instructions both as system context (`appendSystemContext`) and as context for the current turn (`appendContext`): models saw the system copy alone and still did not report. | +| Factory | droid defers MCP tools behind its tool search, with no setting per server. The instructions arrive as SessionStart context, so the model knows to load `report` from the deferred list. | +| Devin | Devin can defer MCP tools behind its `tool_search`, with no setting per server, so the model may see the tool's name first and load it. | +| Antigravity | The entry sets `eager: true`, so the tools are direct rather than behind the `call_mcp_tool` wrapper. Antigravity ignores MCP server instructions, so failproofai adds a plugin in its global customization root, `~/.gemini/config/plugins/failproofai-self-reports/` (`plugin.json`, the instructions in `rules/AGENTS.md`, and a `.failproofai-managed` marker), whose rules Antigravity merges into every session. A directory of that name without the marker is never written to or removed. | +| Goose | Extensions' tools are listed directly. | + +Pi before 0.99 has no MCP support, and from 0.99 (checked on 1.7.0) an MCP server's tools are hidden behind Pi's `codemode` unless its entry sets `"exposure": "direct"`. Rather than an MCP entry, failproofai's Pi extension, which every Pi with failproofai hooks already loads, registers the tool itself as `mcp__failproofai_local__report` on every Pi version, with the server's instructions in Pi's system prompt. It asks `failproofai mcp --agent pi` for the tool when Pi starts, and again at most once a minute when a session starts or a prompt is sent, and hands each call to it, so the text, the categories and the recording are the same as every other agent's. A Pi started while Self Reports was off (or while it waited for FailproofAI Cloud's setting) gets the tool from its next prompt after Self Reports is turned on, without a reload, and turning it off takes the tool out of Pi's active tools. The Hermes and OpenClaw plugins do the same against the daemon's Self Reports server: they ask it for the tool when the gateway starts (and every minute after, for the instructions and the on/off switch) and send each call to it as `?agent=hermes` or `?agent=openclaw` with the gateway's working directory, so it is attributed, deduped and logged like an MCP call. Without a daemon, or while Self Reports is off, the model sees no tool. The Hermes plugin registers the tool even then, hidden, so a gateway started while Self Reports was off shows it within a minute of `self-report enable`, without a restart. On Hermes the tool's schema is fixed when it registers (a short generic one when the daemon had not answered yet), so new categories reach the schema at the gateway's next start; they reach the model at once through the instructions. `self-report sync` writes no Pi, Hermes or OpenClaw MCP entry and takes out one an earlier version wrote, in every profile. `failproofai update` (and the first `failproofai config` on a new version) takes out a Hermes or OpenClaw one before it restarts their gateways, so a restarted gateway does not load it again; OpenClaw would otherwise also start the stdio server for it. + +Where an agent's hooks see MCP tool calls and the server they belong to, the hook records the report. Where they do not, failproofai's MCP server records it. It attributes the report to that agent's newest session seen by the hooks in the last 6 hours: in the server's working directory if there is one, else in a directory above or below it. With neither, it takes the agent's newest session only when all of the agent's sessions in those 6 hours are in one directory, and files the report as `unattributed` otherwise, rather than guess between projects. The lookup reads every page of hook activity written in the 6 hours, however busy other agents or projects kept the hooks, so a session that is still in the window is found. The agent the report is filed under comes from that session's own hook events. + +These agents are registered over stdio for that reason: the MCP entry is per user, not per project, so an HTTP URL could carry only `?agent=`, and the server could not tell which project called. The daemon's HTTP server still answers an entry like that (one written by hand, or by an earlier version until the next sync), but it never guesses across projects: with no working directory, it files the report under that agent's newest session only when all of the agent's recent sessions are in one directory, and as `unattributed` otherwise. It records nothing while Self Reports is off. + +| Agent | Where the server is registered | Recorded by | +| --- | --- | --- | +| Claude Code | `~/.claude.json` | Hook, or the MCP server while hooks are off | +| Codex | `~/.codex/config.toml`, plus the block in `~/.codex/AGENTS.md` above | Hook, or the MCP server while Codex has not trusted the hooks | +| Cursor | `~/.cursor/mcp.json` | MCP server. Cursor's tool hook names the call `MCP:report`, without the server, so it cannot tell our `report` from another server's, and the call goes through the policies like any other. When the daemon cannot be reached, it is denied with every other call | +| Copilot CLI | `~/.copilot/mcp-config.json`, plus the instructions file above | MCP server | +| OpenCode | `~/.config/opencode/opencode.json` | MCP server | +| Pi | failproofai's Pi extension | MCP server | +| Hermes | failproofai's Hermes plugin, in each profile | The daemon's Self Reports server | +| OpenClaw | failproofai's OpenClaw plugin, in each profile | The daemon's Self Reports server | +| Factory | `~/.factory/mcp.json` | MCP server | +| Devin | `~/.config/devin/mcp_config.json` | MCP server | +| Antigravity | `~/.gemini/config/mcp_config.json`, plus the plugin above | MCP server | +| Goose | `~/.config/goose/config.yaml` | MCP server | + +### When the hooks do not run + +Claude Code and Codex can load the MCP server while skipping failproofai's hooks, and then no hook records a report: + +- Codex 0.129 and later runs a hook from `~/.codex/hooks.json` only once a person trusted it, at its current hash. Hooks in Codex's system config (`/etc/codex/config.toml`, where `failproofai config` puts them when it has sudo) run without trust. +- Claude Code runs no hooks with `disableAllHooks: true`, and only managed ones with a managed `allowManagedHooksOnly: true`. + +So the stdio server records a Claude Code or Codex report itself unless that agent's hook already recorded that same call: the agent runs its hook before it sends the MCP call, so the server looks for the hook's record of the same report, from the last two minutes and in the same working directory, and each hook record vouches for one call only. The same words in another project, or a second identical call, are recorded. A report is recorded once either way, and a person who trusts the hooks while the agent runs changes nothing. A report the server records goes on the session the agent's own files name (Codex's rollout, Claude Code's transcript for that directory). `self-report sync` registers these agents over stdio, never on the daemon's endpoint, which records nothing for them. `self-report status` says who records each one's reports and, for an untrusted Codex, how to trust the hooks: re-run `failproofai config` and allow sudo, or open `codex` once and approve them. + +### Devin and Claude Code's hooks + +Devin runs the hooks in `~/.claude/settings.json` as well as its own, so a Devin call to `report` reaches failproofai's hook twice, once as Devin and once as Claude Code. Devin's report is recorded by its MCP server, so the Claude Code hook leaves a call that came from Devin alone: it recognises one by a `devin` process above the hook, or by Devin's payload (a `call-…` tool call id and no transcript path). The report is recorded once, as Devin's. + +### Other agents' servers + +Devin also lists the MCP servers of other agents' configs: `~/.claude.json` (user and per-project servers), a project's `.mcp.json`, and `.cursor/mcp.json` in the directory it runs in. It keeps one server per name, and its own `~/.config/devin/mcp_config.json` wins over the imported ones, except that a `.cursor/mcp.json` in the working directory (so `~/.cursor/mcp.json` when Devin runs in your home directory) wins over Devin's own. Servers under other names are listed beside ours: a `failproofai` or `failproofai-local` that `devin mcp list` shows comes from one of those files (for example a Claude Code project's `mcpServers`), not from failproofai, which only ever writes `failproofai_local`. + +### Cursor approval + +If `cursor-agent mcp list` shows `failproofai_local` as "not loaded (needs approval)", run `cursor-agent mcp enable failproofai_local`. cursor-agent asks for approval of servers in a project's `.cursor/mcp.json`, so this happens, for example, when it runs with your home directory as the project. The approval is per project and per entry, so failproofai does not write it for you. `self-report sync` and `self-report status` say so for Cursor. + +On Antigravity, an MCP call can come through its `call_mcp_tool` wrapper. The hook lets that call through ahead of the policies only when the wrapper names server `failproofai_local` and tool `report`. A wrapped call to any other server goes through the policies as usual. + +`failproofai self-report status` prints everything in one place: on or off and where the setting comes from, the settings file, the categories, the daemon's endpoint (`not running (agents use stdio)` when no daemon is set up here), each agent's transport, URL or command, who records its reports and the fix for any agent with a problem, and the gateway rows from the last `update`. `--json` prints all of it as JSON. + +`enable` and `disable` print one line, such as `Self Reports: on for 12 agents`, which also names any agent they could not update. `policies --install`, `policies --uninstall`, `config` and `update` print nothing about Self Reports when it all worked, and one line naming the agents they could not update when it did not. They also leave out routine gateway rows (`hermes/default already current, gateway restarting`) and print only a gateway you have to restart yourself; `self-report status` shows the rows from the last update. `self-report sync` lists every change. + +If an MCP server named `failproofai_local` that failproofai did not write is already there, it is left alone and reported as a conflict. A server named `failproofai`, such as the [Cloud MCP gateway](/reference/mcp), is never touched or reported: it sits next to `failproofai_local`, and its tools go through your policies like any other server's. + +## When a tool call fails + +Once per session, after a tool call failure that clearly blocks the agent, failproofai adds one line the model reads: "If this blocks you and you can't fix it, call failproofai_local's `report` tool once." A failure clearly blocks when: + +- it is an auth or credential error: its error output or a short result says 401 or 403, unauthorized, forbidden, authentication failed, an invalid or expired key, token or credentials, or names a `*_TOKEN`, `*_KEY` or `*_SECRET` that is not set, or +- the same tool, or for a shell call the same program, already failed earlier in the session. + +One non-zero exit is ordinary work and gets no line. Neither does read-only exploration failing, however often: `ls`, `cat`, `grep`, `find`, `test` and similar commands, `git status` or `git log`, and tools such as Read, Glob and Grep, unless the failure is an auth error. There is no line after a successful call, after the report call itself, after a failure a failproofai deny caused (that is already recorded as a block), or while Self Reports is off. It is part of Self Reports, not a policy, and it never replaces a policy's answer. + +| Agent | Where the line goes | +| --- | --- | +| Claude Code | `additionalContext` on PostToolUse and PostToolUseFailure | +| Codex | `additionalContext` on PostToolUse | +| Cursor | `additional_context` on postToolUse | +| Copilot CLI | `additionalContext` on postToolUseFailure (its postToolUse reads only a block) | +| Factory | PostToolUse feedback, which droid adds as a message only the model sees | +| OpenCode, Pi, Hermes, OpenClaw, Devin, Antigravity, Goose | None: these agents have no channel that adds context after a tool runs (OpenCode's only route is a new prompt) | + +## The daemon's log + +The daemon's log (`~/.failproofai/logs/daemon.log`, which machine logs upload) has a line for every Self Reports MCP event: each `initialize` and `tools/list`, each `tools/call` with the agent, the category, the session it was filed under, and whether it was recorded or skipped and why, and each sync's result. A write failure, a report whose category was inferred (the line says `inferred_category=true` and gives the `raw_category` the agent sent, which may be empty; a category not shaped like a name, such as a token, is shown only as `(N characters, not shown)`), and an unreadable settings file are warnings. A line carries at most the first 40 characters of the report's detail, after secrets are scrubbed from the whole of it, cut on a character boundary and followed by `...` when there was more. The stdio server, which runs as a child of each agent, sends its events to the daemon over its socket and never waits for it: with no daemon, or a version that predates this, they are dropped. + +## Containers + +In a container, run `failproofaid` in the foreground as the container's main process, with the agent started beside it. Reports, like every other hook event, reach Failproof AI Cloud only through the daemon: without it, the agent still gets the tool over stdio, but reports stay on disk in the container. + +A daemon you start by hand has no service unit, so it has none of the commands the unit would give it: + +- **The startup sync** runs the CLI named by `FAILPROOFAI_CLI_CMD`. Without it, the daemon looks for `failproofai` on `PATH`, then in npm's global bin (`$NPM_CONFIG_PREFIX/bin`, `~/.npm-global/bin`, `/usr/local/bin`) and `~/.bun/bin`. After an `npm install -g failproofai`, agents therefore move to HTTP when the daemon starts. If the CLI is somewhere else, set `FAILPROOFAI_CLI_CMD` to the command that runs it, or run `failproofai self-report sync` once the daemon is up. +- **The policy worker** evaluates every hook the daemon receives, from every agent, Claude Code included. Without `FAILPROOFAI_WORKER_CMD`, the daemon looks for `dist/worker.mjs` relative to its working directory. If it is not there, every hook routed through the daemon fails closed: Claude Code's tool calls, for example, are denied. `policies --install --cli hermes` (or `openclaw`) refuses outright. Set it to the worker in the installed package: + + ```bash + export FAILPROOFAI_WORKER_CMD="node $(npm root -g)/failproofai/dist/worker.mjs" + failproofaid & + ``` + +## Your own agents + +The Python and TypeScript SDKs offer the same tool, named `failproofai_report`, as ready-made tools for LangChain, LangGraph, CrewAI, LlamaIndex, Pydantic AI, the Vercel AI SDK and Mastra, and as raw OpenAI and Anthropic tool definitions. See [Python custom agents](/start/integrations/custom-agents#self-reports) and [TypeScript custom agents](/reference/custom-agents-typescript#self-reports). SDK reports carry `source: "sdk"`; reports from coding agents carry `source: "mcp"`. + +## Privacy + +The tool's description tells the agent there is no need to mention the report to the user. Terminal agents still show the tool call on screen; in your own UI, hide it with `is_self_report_tool(name)` (Python) or `isSelfReportTool(name)` (TypeScript). + +A report holds the category, the agent's one-sentence detail, and the session, agent, and environment it came from. It is uploaded with the session's other events. diff --git a/docs/start/integrations/crewai.mdx b/docs/start/integrations/crewai.mdx index abfcc0b42..fa80e5fbe 100644 --- a/docs/start/integrations/crewai.mdx +++ b/docs/start/integrations/crewai.mdx @@ -180,6 +180,21 @@ human_input the answer, with the wait measured Because the `Task(human_input=True)` path is a wrapper around CrewAI's input provider rather than an event subscription, it is restored on `uninstrument()` and re-raises whatever `input()` raises, `KeyboardInterrupt` included, unchanged. +## Self Reports + +Give the agent a tool to say it is stuck: looping, a broken tool or credential, missing context, a request it cannot do. + +```python +from crewai import Agent +from failproofai_sdk.integrations.crewai import self_report_tool + +analyst = Agent(role="Analyst", goal="...", backstory="...", tools=[search, self_report_tool()]) +``` + +A CrewAI `BaseTool`. While the adapter is installed the report lands on the agent that ran the tool; otherwise on the enclosing `failproofai_sdk.session()`. + +The tool's description and its `category` enum come from `~/.failproofai/self-report.json` (your organization's categories when Self Reports is on in Failproof AI Cloud, or set locally with `failproofai self-report enable`), and fall back to six built-in categories. It always answers `Recorded.` and changes nothing; the call becomes a `self_report` event on the agent's session. To keep it out of a transcript you show users, filter on `failproofai_sdk.is_self_report_tool(name)`. See [Self Reports](/self-reports). + ## Common problems diff --git a/docs/start/integrations/custom-agents.mdx b/docs/start/integrations/custom-agents.mdx index 778a69708..8e8d8fde5 100644 --- a/docs/start/integrations/custom-agents.mdx +++ b/docs/start/integrations/custom-agents.mdx @@ -74,7 +74,7 @@ The error is emitted before `agent_end`, because the dashboard closes the span a ## The event methods -Fifteen methods in six families. Most come in pairs — you emit the opener, then the closer, and the SDK measures the span between them. +Sixteen methods in seven families. Most come in pairs — you emit the opener, then the closer, and the SDK measures the span between them. | Family | Opens | Closes | Standalone | | --- | --- | --- | --- | @@ -85,6 +85,7 @@ Fifteen methods in six families. Most come in pairs — you emit the opener, the | **Hooks** | `hook_triggered` | `hook_completed` | — | | **Humans** | `human_wait` | `human_input` | `human_pause`, `human_interrupt` | | **Failures** | — | — | `error` | +| **Self Reports** | — | — | `self_report` | Prefer the scopes — `agent()` and `tool_call()` — wherever they fit. They guarantee the closing event even when the body raises. Reach for these methods directly when your control flow doesn't nest, such as a model call inside a helper. @@ -625,7 +626,7 @@ flowchart LR | Stage | Job | Runs in | | --- | --- | --- | -| Adapter | Translates a framework callback into one of 15 event types | Your process | +| Adapter | Translates a framework callback into one of 16 event types | Your process | | Writer | Queues, batches, writes JSONL atomically | Your process, background thread | | Spool | Durable handoff, survives your process exiting | Local disk | | Daemon | Watches the spool, ships batches, deletes what it shipped | Your machine | @@ -704,6 +705,22 @@ The default is right in production and wrong while debugging, because it can onl + +## Self Reports + +Give the model one more tool, so it can say when it is stuck. With a provider SDK directly, offer the tool and route the call: + +```python +tools = [failproofai_sdk.openai_tool(), *my_tools] # anthropic_tool() for Claude +for call in message.tool_calls: + if failproofai_sdk.is_self_report_tool(call.function.name): + result = failproofai_sdk.handle_tool_call( + call.function.name, call.function.arguments, tool_call_id=call.id + ) # always "Recorded." +``` + +To record a report from your own code, call `failproofai_sdk.self_report("missing_context", "The customer id was never provided.")`. The categories and the tool's wording come from `~/.failproofai/self-report.json`, else six built-in categories. See [Self Reports](/self-reports). + ## Common problems diff --git a/docs/start/integrations/langchain.mdx b/docs/start/integrations/langchain.mdx index 9d5427ddb..1b2893f98 100644 --- a/docs/start/integrations/langchain.mdx +++ b/docs/start/integrations/langchain.mdx @@ -191,6 +191,23 @@ with failproofai_sdk.session(): `human_wait` to `human_input` carries the prompt and the answer (both are dropped under `capture_content=False`, along with retrieval document sources — the document count survives). `agent_pause` to `agent_resume` is the only pair that feeds paused time, so without it a ten-minute human wait is billed as active agent time. The root span stays open across the gap, keeping both calls in one session. +## Self Reports + +Give the agent a tool to say it is stuck: looping, a broken tool or credential, missing context, a request it cannot do. + +```python +from failproofai_sdk.integrations.langchain import self_report_tool +from langgraph.prebuilt import ToolNode + +tools = [search, self_report_tool()] +model = model.bind_tools(tools) +graph.add_node("tools", ToolNode(tools)) +``` + +A `StructuredTool`. While the adapter is installed the report lands on the agent whose run called it, with the model's `tool_call_id`; otherwise on the enclosing `failproofai_sdk.session()`. + +The tool's description and its `category` enum come from `~/.failproofai/self-report.json` (your organization's categories when Self Reports is on in Failproof AI Cloud, or set locally with `failproofai self-report enable`), and fall back to six built-in categories. It always answers `Recorded.` and changes nothing; the call becomes a `self_report` event on the agent's session. To keep it out of a transcript you show users, filter on `failproofai_sdk.is_self_report_tool(name)`. See [Self Reports](/self-reports). + ## Common problems diff --git a/docs/start/integrations/llamaindex.mdx b/docs/start/integrations/llamaindex.mdx index 22a630bd4..cee11e008 100644 --- a/docs/start/integrations/llamaindex.mdx +++ b/docs/start/integrations/llamaindex.mdx @@ -210,6 +210,21 @@ async def ask_human(question: str) -> str: `ctx.wait_for_event` in a plain workflow step is not captured. The runtime catches the drop before it reaches the dispatcher, so the step exits and re-runs later with no signal to key a pause on. The FunctionAgent pattern, which LlamaIndex documents, waits inside a tool and is captured in full. +## Self Reports + +Give the agent a tool to say it is stuck: looping, a broken tool or credential, missing context, a request it cannot do. + +```python +from llama_index.core.agent.workflow import FunctionAgent +from failproofai_sdk.integrations.llama_index import self_report_tool + +agent = FunctionAgent(name="researcher", llm=llm, tools=[search, self_report_tool()]) +``` + +A `FunctionTool`. While the adapter is installed the report lands on the agent whose tool span called it; otherwise on the enclosing `failproofai_sdk.session()`. + +The tool's description and its `category` enum come from `~/.failproofai/self-report.json` (your organization's categories when Self Reports is on in Failproof AI Cloud, or set locally with `failproofai self-report enable`), and fall back to six built-in categories. It always answers `Recorded.` and changes nothing; the call becomes a `self_report` event on the agent's session. To keep it out of a transcript you show users, filter on `failproofai_sdk.is_self_report_tool(name)`. See [Self Reports](/self-reports). + ## Common problems diff --git a/docs/start/integrations/pydantic-ai.mdx b/docs/start/integrations/pydantic-ai.mdx index 88cf4736a..312e578e7 100644 --- a/docs/start/integrations/pydantic-ai.mdx +++ b/docs/start/integrations/pydantic-ai.mdx @@ -174,6 +174,24 @@ failproofai_sdk.instrument( ) ``` +## Self Reports + +Give the agent a tool to say it is stuck: looping, a broken tool or credential, missing context, a request it cannot do. + +```python +from pydantic_ai import Agent +from failproofai_sdk.integrations.pydantic_ai import FailproofAI, self_report_tool + +agent = Agent("openai:gpt-5.6-sol", tools=[self_report_tool()]) + +# or let the capability add it to the agent +agent = Agent("openai:gpt-5.6-sol", capabilities=[FailproofAI(self_report=True)]) +``` + +A Pydantic AI `Tool` carrying the model's `tool_call_id`. `self_report=True` is opt-in: the capability otherwise only observes, and adding a tool changes what the model sees. + +The tool's description and its `category` enum come from `~/.failproofai/self-report.json` (your organization's categories when Self Reports is on in Failproof AI Cloud, or set locally with `failproofai self-report enable`), and fall back to six built-in categories. It always answers `Recorded.` and changes nothing; the call becomes a `self_report` event on the agent's session. To keep it out of a transcript you show users, filter on `failproofai_sdk.is_self_report_tool(name)`. See [Self Reports](/self-reports). + ## Common problems diff --git a/docs/start/quickstart.mdx b/docs/start/quickstart.mdx index daef2d525..763803fc4 100644 --- a/docs/start/quickstart.mdx +++ b/docs/start/quickstart.mdx @@ -92,7 +92,7 @@ This quickstart gets one machine reporting sessions, runs an audit, and deploys Read any pack before taking it with `failproofai policies show /`, and see [policy packs](/policies/packs) for taking only part of one. - Until this runs, the only thing enforcing is `block-failproofai-commands` — the always-on guard that stops an agent switching Failproof AI off. `failproofai policies` lists what is on. + Until this runs, the only thing enforcing is `block-failproofai-commands` — the always-on guard that stops an agent switching Failproof AI off, whether through its CLI, its files, or the agent's own hook settings. `failproofai policies` lists what is on. Follow [Prevent your first failure with a policy](/start/first-policy). Start in observe mode, inspect matches, then enforce the reviewed version. diff --git a/hermes-plugin/__init__.py b/hermes-plugin/__init__.py index 0c75071d7..f6359dd0b 100644 --- a/hermes-plugin/__init__.py +++ b/hermes-plugin/__init__.py @@ -19,6 +19,7 @@ from .client import PolicyVerdict, evaluate_policy from .ledger import InstructionLedger, LedgerError +from .self_report import SelfReportTool, register_self_report_tool logger = logging.getLogger(__name__) @@ -665,6 +666,9 @@ def setting(key: str, default: Any) -> Any: ) self._handoff = _ReminderHandoff() self._delivered = _TurnDeliveries() + # Set by register() once the Self Reports tool is registered: its + # instructions then ride pre_llm_call with the protocol hint. + self.self_report: SelfReportTool | None = None def _fallback(self, error: Exception) -> dict[str, str] | None: logger.error("FailproofAI evaluator unavailable: %s", error) @@ -980,7 +984,13 @@ def subagent_stop(self, session_id: str = "", **kwargs: Any) -> None: @_guarded(_protocol_context) def pre_llm_call(self, **kwargs: Any) -> dict[str, str]: - return {"context": _PROTOCOL_CONTEXT} + instructions = "" + if self.self_report is not None: + try: + instructions = self.self_report.instructions() + except Exception as exc: + logger.warning("FailproofAI Self Reports instructions unavailable: %s", exc) + return {"context": f"{_PROTOCOL_CONTEXT}\n\n{instructions}" if instructions else _PROTOCOL_CONTEXT} @_guarded(_nothing) def on_session_reset(self, session_id: str = "", **kwargs: Any) -> None: @@ -1034,16 +1044,30 @@ def register(ctx: Any) -> None: except Exception as exc: logger.error("FailproofAI could not register Hermes tool_execution middleware: %s", exc) middleware = plugin.wraps_execution + # Self Reports: the report tool as a direct native tool (never behind + # Hermes' tool search), recorded by failproofaid like the MCP call was. + # Registered even while Self Reports is off: its check_fn and the + # pre_llm_call instructions follow the daemon live. + try: + plugin.self_report = register_self_report_tool(ctx) + except Exception as exc: + logger.error("FailproofAI could not register the Self Reports tool: %s", exc) + self_report_tool = plugin.self_report is not None + self_report_on = self_report_tool and plugin.self_report.current is not None except Exception as exc: logger.exception("FailproofAI plugin failed to register") error = f"{type(exc).__name__}: {exc}" middleware = False + self_report_tool = False + self_report_on = False beat.update( stage="end", register_ok=not error and hooks == list(_HOOKS), hooks_registered=hooks, middleware_registered=middleware, + self_report_tool=self_report_tool, + self_report_on_at_start=self_report_on, ) if error: beat["error"] = error diff --git a/hermes-plugin/plugin.yaml b/hermes-plugin/plugin.yaml index 5525d5425..8e89eef66 100644 --- a/hermes-plugin/plugin.yaml +++ b/hermes-plugin/plugin.yaml @@ -1,5 +1,5 @@ name: failproofai -version: 1.0.17 +version: 1.0.18 description: Real-time FailproofAI policy enforcement for Hermes manifest_version: 2 api_version: 1 diff --git a/hermes-plugin/self_report.py b/hermes-plugin/self_report.py new file mode 100644 index 000000000..34d3847cd --- /dev/null +++ b/hermes-plugin/self_report.py @@ -0,0 +1,298 @@ +"""Self Reports on Hermes: failproofai's ``report`` tool as a NATIVE plugin tool. + +Hermes defers MCP tools behind its tool search (``tools.tool_search``, on by +default), and plugin tools too: only names in ``toolsets._HERMES_CORE_TOOLS`` +never defer (``tools/tool_search.py`` ``is_deferrable_tool_name``, 0.20.0 and +0.21.x). There is no per-server or per-tool setting, so a ``failproofai_local`` +MCP entry reached the model only as a name in the deferred listing and the +model never reported (0/2 on a strong model). This plugin, which every hooked +Hermes profile already loads, registers the tool itself and adds its name to +that core list, so it is a direct tool, and puts the server's instructions in +``pre_llm_call`` context. ``self-report sync`` writes no Hermes MCP entry and +removes one an earlier version wrote. + +The text and the recording come from failproofaid's own Self Reports MCP +server: the description and schema are what its ``tools/list`` returns, and +each call is its ``tools/call``, sent as ``?agent=hermes&cwd=`` so the report +is attributed, deduped and logged exactly as the MCP path did. The endpoint is +trusted only when it answers ``initialize`` with the ``instanceId`` the daemon +behind this user's socket reports in its pong. + +The tool is registered whether or not Self Reports is on when Hermes starts +(review finding F16): a gateway that started while it was off, or while the +daemon could not be reached, kept no tool, so turning it on later never +reached that gateway. Its ``check_fn`` follows the daemon live (at most a +minute behind), so the model sees the tool, and ``pre_llm_call`` its +instructions, only while the daemon offers them. Registered before the daemon +answered, it carries a short generic description (``_FALLBACK_*``) until the +first answer, which is copied into the registered schema in place. +""" + +from __future__ import annotations + +import json +import logging +import os +import threading +import time +import urllib.parse +import urllib.request +from typing import Any, Callable, Mapping + +from .client import PROTOCOL_VERSION, _exchange + +logger = logging.getLogger(__name__) + +# Hermes' spelling of the MCP tool (``mcp__``): the hook lets it +# past every policy, exactly as it did the MCP call. +TOOL_NAME = "mcp_failproofai_local_report" +TOOLSET = "failproofai" + +_TIMEOUT_S = 3.0 +_CALL_TIMEOUT_S = 20.0 +_REFRESH_S = 60.0 +# The registration's text when the daemon has not offered the tool yet. The +# categories and guidance reach the model in the instructions, which are live. +_FALLBACK_DESCRIPTION = ( + "When you are stuck on something you cannot fix yourself, call this tool once with " + "`category` and `detail` (one factual sentence: what is blocking you). It reports to " + "FailproofAI. It does not unblock you: continue, or tell the user what is blocking you." +) +_FALLBACK_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "category": {"type": "string", "description": "What kind of blocker this is."}, + "detail": {"type": "string", "description": "One factual sentence: what is blocking you."}, + }, + "required": ["category", "detail"], +} +_ARG_ALIASES = { + "category": ("category", "type", "kind"), + "detail": ("detail", "summary", "sentence", "message", "description", "reason", "text", "details"), +} + + +def ping_self_report_server(timeout_s: float = _TIMEOUT_S) -> dict[str, Any] | None: + """The daemon's pong ``selfReport`` ({instanceId, port}), or None.""" + body = json.dumps({"type": "ping", "protocolVersion": PROTOCOL_VERSION}).encode("utf-8") + try: + reply = _exchange(body, int(timeout_s * 1000), time.monotonic() + timeout_s) + except Exception: + return None + server = reply.get("selfReport") if isinstance(reply, Mapping) and reply.get("type") == "pong" else None + if not isinstance(server, Mapping): + return None + instance, port = server.get("instanceId"), server.get("port") + if not isinstance(instance, str) or not isinstance(port, int) or isinstance(port, bool): + return None + return {"instanceId": instance, "port": port} + + +def _rpc(url: str, body: Mapping[str, Any], timeout_s: float) -> Any: + request = urllib.request.Request( + url, + data=json.dumps(body).encode("utf-8"), + headers={"content-type": "application/json", "accept": "application/json, text/event-stream"}, + method="POST", + ) + # A loopback URL only: no proxy may see a report. + opener = urllib.request.build_opener(urllib.request.ProxyHandler({})) + with opener.open(request, timeout=timeout_s) as response: + return json.loads(response.read().decode("utf-8")) + + +_INIT = { + "jsonrpc": "2.0", + "id": 1, + "method": "initialize", + "params": { + "protocolVersion": "2025-06-18", + "capabilities": {}, + "clientInfo": {"name": "failproofai-hermes-plugin", "version": "1"}, + }, +} + + +def discover_self_report_tool( + ping: Callable[[], dict[str, Any] | None] = ping_self_report_server, + rpc: Callable[[str, Mapping[str, Any], float], Any] = _rpc, +) -> dict[str, Any] | None: + """The tool as failproofaid offers it now, or None (no daemon, not this + user's daemon on the port, or Self Reports off).""" + server = ping() + if not server: + return None + base = f"http://127.0.0.1:{server['port']}/mcp?agent=hermes" + try: + init = rpc(base, _INIT, _TIMEOUT_S) + result = init.get("result") if isinstance(init, Mapping) else None + info = result.get("serverInfo") if isinstance(result, Mapping) else None + if not isinstance(info, Mapping) or info.get("instanceId") != server["instanceId"]: + return None + listed = rpc(base, {"jsonrpc": "2.0", "id": 2, "method": "tools/list"}, _TIMEOUT_S) + tools = (listed.get("result") or {}).get("tools") if isinstance(listed, Mapping) else None + tool = tools[0] if isinstance(tools, list) and tools else None + if not isinstance(tool, Mapping) or not isinstance(tool.get("description"), str): + return None + schema = tool.get("inputSchema") + if not isinstance(schema, Mapping): + return None + instructions = result.get("instructions") + return { + "port": server["port"], + "instanceId": server["instanceId"], + "description": tool["description"], + "inputSchema": dict(schema), + "instructions": instructions if isinstance(instructions, str) and instructions else "", + } + except Exception: + return None + + +def prepare_arguments(raw: Any) -> dict[str, str]: + """A model that guessed the argument names still reports (contract §3).""" + args = raw if isinstance(raw, Mapping) else {} + out: dict[str, str] = {} + for key, aliases in _ARG_ALIASES.items(): + out[key] = "" + for alias in aliases: + value = args.get(alias) + if isinstance(value, str) and value.strip(): + out[key] = value + break + return out + + +def call_self_report_tool( + tool: Mapping[str, Any], + args: Any, + cwd: str, + ping: Callable[[], dict[str, Any] | None] = ping_self_report_server, + rpc: Callable[[str, Mapping[str, Any], float], Any] = _rpc, +) -> str: + """Hand one call to failproofaid's server; the text it answers.""" + server = ping() + if not server or server["instanceId"] != tool.get("instanceId") or server["port"] != tool.get("port"): + return "Recorded." + query = {"agent": "hermes", **({"cwd": cwd} if cwd else {})} + url = f"http://127.0.0.1:{tool['port']}/mcp?{urllib.parse.urlencode(query)}" + try: + reply = rpc( + url, + {"jsonrpc": "2.0", "id": 3, "method": "tools/call", + "params": {"name": "report", "arguments": prepare_arguments(args)}}, + _CALL_TIMEOUT_S, + ) + content = ((reply or {}).get("result") or {}).get("content") + first = content[0] if isinstance(content, list) and content else {} + text = first.get("text") if isinstance(first, Mapping) else None + return text if isinstance(text, str) else "Recorded." + except Exception: + return "Recorded." + + +def _keep_direct(name: str) -> bool: + """Put ``name`` on Hermes' never-deferred list (``toolsets._HERMES_CORE_TOOLS``).""" + try: + import toolsets # type: ignore[import-not-found] + except Exception: + return False + core = getattr(toolsets, "_HERMES_CORE_TOOLS", None) + try: + if isinstance(core, list): + if name not in core: + core.append(name) + return True + if isinstance(core, set): + core.add(name) + return True + except Exception: + return False + return False + + +class SelfReportTool: + """The registered tool's live state: refreshed from the daemon at most once a minute.""" + + def __init__( + self, + discover: Callable[[], dict[str, Any] | None] = discover_self_report_tool, + call: Callable[..., str] = call_self_report_tool, + clock: Callable[[], float] = time.monotonic, + ) -> None: + self._discover = discover + self._call = call + self._clock = clock + self._lock = threading.Lock() + self.current: dict[str, Any] | None = None + self._fetched = float("-inf") + # The schema dict handed to Hermes at registration; refreshed in place. + self.schema: dict[str, Any] | None = None + + def refresh(self, force: bool = False) -> dict[str, Any] | None: + with self._lock: + if not force and self._clock() - self._fetched < _REFRESH_S: + return self.current + self._fetched = self._clock() + tool = None + try: + tool = self._discover() + except Exception: + tool = None + with self._lock: + self.current = tool + if tool and self.schema is not None: + # Best effort: a registry that kept our dict sees the daemon's text. + try: + self.schema["description"] = tool["description"] + self.schema["parameters"] = tool["inputSchema"] + except Exception: + pass + return tool + + def available(self) -> bool: + return self.refresh() is not None + + def instructions(self) -> str: + tool = self.refresh() + return (tool or {}).get("instructions") or "" + + def handler(self, args: Any = None, **kwargs: Any) -> str: + tool = self.current or self.refresh(force=True) + if not tool: + return "Recorded." + cwd = kwargs.get("cwd") if isinstance(kwargs.get("cwd"), str) and kwargs.get("cwd") else os.getcwd() + return self._call(tool, args, cwd) + + +def register_self_report_tool(ctx: Any, state: SelfReportTool | None = None) -> SelfReportTool | None: + """Register the native tool on ``ctx``, whether or not failproofaid offers + one right now. Never raises. ``check_fn`` follows the daemon live, so a + tool registered while Self Reports was off (or the daemon was down) shows + up once it is on, without restarting the gateway. The schema is the + daemon's when it answered here, else the generic fallback; Hermes keeps + what it was given, so new categories reach its schema on the gateway's + next start (they reach the model at once through the instructions).""" + state = state or SelfReportTool() + if not hasattr(ctx, "register_tool"): + return None + tool = state.refresh(force=True) + description = tool["description"] if tool else _FALLBACK_DESCRIPTION + parameters = tool["inputSchema"] if tool else dict(_FALLBACK_SCHEMA) + schema = {"name": TOOL_NAME, "description": description, "parameters": parameters} + state.schema = schema + try: + ctx.register_tool( + name=TOOL_NAME, + toolset=TOOLSET, + schema=schema, + handler=state.handler, + check_fn=state.available, + description=description, + ) + except Exception as exc: + logger.warning("FailproofAI could not register the Self Reports tool: %s", exc) + return None + if not _keep_direct(TOOL_NAME): + logger.warning("FailproofAI could not keep the Self Reports tool out of Hermes' tool search") + return state diff --git a/lib/codex-code-mode.ts b/lib/codex-code-mode.ts new file mode 100644 index 000000000..ebc937a53 --- /dev/null +++ b/lib/codex-code-mode.ts @@ -0,0 +1,399 @@ +/** + * Codex "code mode" transcript support. + * + * From roughly Codex 0.146, and for every tool call on 0.172, Codex writes a + * tool call as a `custom_tool_call` record rather than a `function_call`. Two + * names occur: + * + * - `exec` — `input` is a JavaScript snippet the model wrote, which + * calls the real tools through `tools.(...)`, e.g. + * `const r = await tools.exec_command({cmd:"ls",workdir:"/x"});` + * - `apply_patch` — `input` is the freeform patch text itself. + * + * This module turns an `exec` snippet into the tool calls it makes, so the + * audit sees `exec_command {cmd}` (→ Bash) instead of one opaque script. + * + * It READS LITERALS ONLY and never evaluates anything. An argument it cannot + * read as a literal (a variable, a function call, a spread) is left out, and + * the call carries the whole snippet as `code` so nothing is hidden: a guessed + * command would be worse than an unknown one. Template literals are kept as + * their source text, `${…}` included. + */ + +export interface CodeModeCall { + /** Inner tool name, e.g. `exec_command`, `write_stdin`, `apply_patch`. */ + name: string; + /** The first argument, read as a literal. Object properties that are not + * literals are omitted. A string argument (apply_patch) is returned as-is + * under `input` by the caller. */ + arg: unknown; + /** True when some or all of the argument could not be read as a literal. */ + partial: boolean; +} + +const IDENT_START = /[A-Za-z_$]/; +const IDENT_PART = /[A-Za-z0-9_$]/; + +/** Template-in-substitution nesting past which the rest of the snippet is + * treated as opaque (never as calls). Real snippets nest one or two deep. */ +const MAX_NESTING = 16; + +/** Characters after which a `/` starts a regex literal rather than division. */ +const REGEX_PRECEDERS = new Set(["", "(", ",", "=", ":", "[", "!", "&", "|", "?", "{", "}", ";", "+", "-", "*", "%", "<", ">", "~", "^"]); + +/** Skip a quoted string starting at `i` (the opening quote). Returns the index + * just past the closing quote, or `s.length` when unterminated. */ +function skipQuoted(s: string, i: number): number { + const q = s[i]; + let j = i + 1; + while (j < s.length) { + const c = s[j]; + if (c === "\\") { j += 2; continue; } + if (c === q) return j + 1; + if (c === "\n" && q !== "`") return j; // unterminated single-line string + j++; + } + return s.length; +} + +/** Skip a template literal starting at `i` (the backtick), including any + * `${…}` substitutions and whatever strings they contain. */ +function skipTemplate(s: string, i: number, nest = 0): number { + if (nest > MAX_NESTING) return s.length; + let j = i + 1; + while (j < s.length) { + const c = s[j]; + if (c === "\\") { j += 2; continue; } + if (c === "`") return j + 1; + if (c === "$" && s[j + 1] === "{") { + j = skipCode(s, j + 2, "}", nest + 1); + continue; + } + j++; + } + return s.length; +} + +function skipRegex(s: string, i: number): number { + let j = i + 1; + let inClass = false; + while (j < s.length) { + const c = s[j]; + if (c === "\\") { j += 2; continue; } + if (c === "\n") return j; + if (inClass) { if (c === "]") inClass = false; } + else if (c === "[") inClass = true; + else if (c === "/") { + j++; + while (j < s.length && IDENT_PART.test(s[j])) j++; + return j; + } + j++; + } + return s.length; +} + +/** Advance through code from `i` until the matching `close` at depth 0, + * skipping strings, templates, comments and regexes. Returns the index just + * past `close`, or `s.length`. */ +function skipCode(s: string, i: number, close: string, nest = 0): number { + if (nest > MAX_NESTING) return s.length; + let depth = 0; + let prev = ""; + let j = i; + while (j < s.length) { + const c = s[j]; + if (c === "\"" || c === "'") { j = skipQuoted(s, j); prev = "a"; continue; } + if (c === "`") { j = skipTemplate(s, j, nest + 1); prev = "a"; continue; } + if (c === "/" && s[j + 1] === "/") { const n = s.indexOf("\n", j); j = n < 0 ? s.length : n; continue; } + if (c === "/" && s[j + 1] === "*") { const n = s.indexOf("*/", j + 2); j = n < 0 ? s.length : n + 2; continue; } + if (c === "/" && REGEX_PRECEDERS.has(prev)) { j = skipRegex(s, j); prev = "a"; continue; } + if (c === "(" || c === "[" || c === "{") depth++; + else if (c === ")" || c === "]" || c === "}") { + if (depth === 0 && c === close) return j + 1; + depth--; + } + if (!/\s/.test(c)) prev = IDENT_PART.test(c) ? "a" : c; + j++; + } + return s.length; +} + +// ── Literal reader ── + +class Unreadable extends Error {} + +interface Reader { s: string; i: number; partial: boolean } + +function ws(r: Reader): void { + for (;;) { + while (r.i < r.s.length && /\s/.test(r.s[r.i])) r.i++; + if (r.s.startsWith("//", r.i)) { const n = r.s.indexOf("\n", r.i); r.i = n < 0 ? r.s.length : n; continue; } + if (r.s.startsWith("/*", r.i)) { const n = r.s.indexOf("*/", r.i + 2); r.i = n < 0 ? r.s.length : n + 2; continue; } + return; + } +} + +function decodeEscape(s: string, i: number): [string, number] { + // s[i] is the character after the backslash. + const c = s[i]; + switch (c) { + case "n": return ["\n", i + 1]; + case "t": return ["\t", i + 1]; + case "r": return ["\r", i + 1]; + case "b": return ["\b", i + 1]; + case "f": return ["\f", i + 1]; + case "v": return ["\v", i + 1]; + case "0": return ["\0", i + 1]; + case "\n": return ["", i + 1]; // line continuation + case "x": { + const h = s.slice(i + 1, i + 3); + if (/^[0-9a-fA-F]{2}$/.test(h)) return [String.fromCharCode(parseInt(h, 16)), i + 3]; + return ["x", i + 1]; + } + case "u": { + if (s[i + 1] === "{") { + const end = s.indexOf("}", i + 2); + const h = end < 0 ? "" : s.slice(i + 2, end); + if (/^[0-9a-fA-F]{1,6}$/.test(h) && parseInt(h, 16) <= 0x10ffff) return [String.fromCodePoint(parseInt(h, 16)), end + 1]; + return ["u", i + 1]; + } + const h = s.slice(i + 1, i + 5); + if (/^[0-9a-fA-F]{4}$/.test(h)) return [String.fromCharCode(parseInt(h, 16)), i + 5]; + return ["u", i + 1]; + } + default: return [c ?? "", i + 1]; + } +} + +function readString(r: Reader): string { + const q = r.s[r.i]; + let out = ""; + let j = r.i + 1; + while (j < r.s.length) { + const c = r.s[j]; + if (c === "\\") { const [t, n] = decodeEscape(r.s, j + 1); out += t; j = n; continue; } + if (c === q) { r.i = j + 1; return out; } + if (c === "\n") throw new Unreadable(); + out += c; + j++; + } + throw new Unreadable(); +} + +/** A template literal's text, escapes decoded, `${…}` kept as written. */ +function readTemplate(r: Reader): string { + let out = ""; + let j = r.i + 1; + while (j < r.s.length) { + const c = r.s[j]; + if (c === "\\") { const [t, n] = decodeEscape(r.s, j + 1); out += t; j = n; continue; } + if (c === "`") { r.i = j + 1; return out; } + if (c === "$" && r.s[j + 1] === "{") { + const end = skipCode(r.s, j + 2, "}"); + out += r.s.slice(j, end); + r.partial = true; + j = end; + continue; + } + out += c; + j++; + } + throw new Unreadable(); +} + +function readIdent(r: Reader): string { + const start = r.i; + if (!IDENT_START.test(r.s[r.i] ?? "")) throw new Unreadable(); + while (r.i < r.s.length && IDENT_PART.test(r.s[r.i])) r.i++; + return r.s.slice(start, r.i); +} + +/** Skip one expression we cannot read, stopping before a `,` or the closing + * bracket at depth 0. */ +function skipExpression(r: Reader): void { + let depth = 0; + while (r.i < r.s.length) { + const c = r.s[r.i]; + if (c === "\"" || c === "'") { r.i = skipQuoted(r.s, r.i); continue; } + if (c === "`") { r.i = skipTemplate(r.s, r.i); continue; } + if (c === "(" || c === "[" || c === "{") depth++; + else if (c === ")" || c === "]" || c === "}") { if (depth === 0) return; depth--; } + else if (c === "," && depth === 0) return; + r.i++; + } +} + +const NOT_A_VALUE = Symbol("not-a-value"); + +function readValue(r: Reader, depth: number): unknown { + if (depth > 32) throw new Unreadable(); + ws(r); + const c = r.s[r.i]; + if (c === "\"" || c === "'") return readString(r); + if (c === "`") return readTemplate(r); + if (c === "{") return readObject(r, depth); + if (c === "[") return readArray(r, depth); + const num = /^-?(?:0[xX][0-9a-fA-F]+|(?:\d[\d_]*)?\.?\d[\d_]*(?:[eE][+-]?\d+)?)/.exec(r.s.slice(r.i, r.i + 64)); + if (num && num[0] !== "-") { + const after = r.s[r.i + num[0].length] ?? ""; + if (!IDENT_PART.test(after) && after !== ".") { + r.i += num[0].length; + return Number(num[0].replace(/_/g, "")); + } + } + if (IDENT_START.test(c ?? "")) { + const save = r.i; + const id = readIdent(r); + ws(r); + const next = r.s[r.i] ?? ""; + if ([",", "}", "]", ")"].includes(next)) { + if (id === "true") return true; + if (id === "false") return false; + if (id === "null") return null; + if (id === "undefined") return undefined; + } + r.i = save; + } + // Anything else: a variable, a call, arithmetic. Not read. + skipExpression(r); + r.partial = true; + return NOT_A_VALUE; +} + +function readObject(r: Reader, depth: number): Record { + r.i++; // { + const out: Record = {}; + for (;;) { + ws(r); + if (r.s[r.i] === "}") { r.i++; return out; } + if (r.i >= r.s.length) throw new Unreadable(); + let key: string | undefined; + const c = r.s[r.i]; + if (c === "\"" || c === "'") key = readString(r); + else if (r.s.startsWith("...", r.i) || c === "[") { skipExpression(r); r.partial = true; } + else if (/\d/.test(c)) { const m = /^\d+/.exec(r.s.slice(r.i))!; key = m[0]; r.i += m[0].length; } + else key = readIdent(r); + ws(r); + if (key !== undefined) { + if (r.s[r.i] === ":") { + r.i++; + const v = readValue(r, depth + 1); + if (v !== NOT_A_VALUE) out[key] = v; + } else if (r.s[r.i] === "(") { + skipExpression(r); // method shorthand + r.partial = true; + } else { + r.partial = true; // shorthand `{ cmd }` — a variable + } + } + ws(r); + if (r.s[r.i] === ",") { r.i++; continue; } + if (r.s[r.i] === "}") { r.i++; return out; } + throw new Unreadable(); + } +} + +function readArray(r: Reader, depth: number): unknown[] { + r.i++; // [ + const out: unknown[] = []; + for (;;) { + ws(r); + if (r.s[r.i] === "]") { r.i++; return out; } + if (r.i >= r.s.length) throw new Unreadable(); + const v = readValue(r, depth + 1); + if (v !== NOT_A_VALUE) out.push(v); + ws(r); + if (r.s[r.i] === ",") { r.i++; continue; } + if (r.s[r.i] === "]") { r.i++; return out; } + throw new Unreadable(); + } +} + +/** Read the first argument of a call whose `(` is at `open`. */ +function readFirstArgument(code: string, open: number): { arg: unknown; partial: boolean } { + const r: Reader = { s: code, i: open + 1, partial: false }; + try { + ws(r); + if (r.s[r.i] === ")") return { arg: undefined, partial: false }; + const v = readValue(r, 0); + if (v === NOT_A_VALUE) return { arg: undefined, partial: true }; + return { arg: v, partial: r.partial }; + } catch { + return { arg: undefined, partial: true }; + } +} + +/** Upper bound on calls taken from one snippet. A loop issues one call site + * however many times it runs, so real snippets stay far below this. */ +const MAX_CALLS = 64; + +/** + * The `tools.(…)` call sites in a Codex code-mode `exec` snippet, in + * source order. Text inside strings, templates, comments and regex literals is + * never mistaken for a call. A call site inside a loop appears once. + */ +export function extractCodeModeCalls(code: string, nest = 0): CodeModeCall[] { + if (nest > MAX_NESTING) return []; + const calls: CodeModeCall[] = []; + let prev = ""; + let i = 0; + while (i < code.length && calls.length < MAX_CALLS) { + const c = code[i]; + if (c === "\"" || c === "'") { i = skipQuoted(code, i); prev = "a"; continue; } + if (c === "`") { + // A template's own substitutions can make calls: `${await tools.x(…)}`. + const end = skipTemplate(code, i); + const inner = code.slice(i + 1, end - 1); + let k = inner.indexOf("${"); + while (k >= 0 && calls.length < MAX_CALLS) { + const close = skipCode(inner, k + 2, "}"); + for (const call of extractCodeModeCalls(inner.slice(k + 2, close - 1), nest + 1)) { + if (calls.length < MAX_CALLS) calls.push(call); + } + k = inner.indexOf("${", close); + } + i = end; + prev = "a"; + continue; + } + if (c === "/" && code[i + 1] === "/") { const n = code.indexOf("\n", i); i = n < 0 ? code.length : n; continue; } + if (c === "/" && code[i + 1] === "*") { const n = code.indexOf("*/", i + 2); i = n < 0 ? code.length : n + 2; continue; } + if (c === "/" && REGEX_PRECEDERS.has(prev)) { i = skipRegex(code, i); prev = "a"; continue; } + + if (IDENT_START.test(c)) { + let j = i; + while (j < code.length && IDENT_PART.test(code[j])) j++; + const word = code.slice(i, j); + // `tools` as its own identifier, not `x.tools` or `mytools`. + if (word === "tools" && prev !== ".") { + const m = /^\s*\.\s*([A-Za-z_$][A-Za-z0-9_$]*)\s*\(/.exec(code.slice(j, j + 256)); + if (m) { + const open = j + m[0].length - 1; + const { arg, partial } = readFirstArgument(code, open); + calls.push({ name: m[1], arg, partial }); + // Keep scanning inside the arguments: `tools.a({x: await tools.b()})` + // is rare but real calls should not hide in each other. + i = open + 1; + prev = "("; + continue; + } + } + i = j; + prev = "a"; + continue; + } + if (!/\s/.test(c)) prev = c; + i++; + } + return calls; +} + +/** Every `*** Add|Update|Delete File:` path in a Codex patch, in order. */ +export function patchedFiles(patch: string): string[] { + const out: string[] = []; + const re = /^\*\*\* (?:Add|Update|Delete) File: (.+?)\s*$/gm; + let m: RegExpExecArray | null; + while ((m = re.exec(patch)) !== null) out.push(m[1]); + return out; +} diff --git a/lib/codex-sessions.ts b/lib/codex-sessions.ts index 409fd6d34..3f95180b6 100644 --- a/lib/codex-sessions.ts +++ b/lib/codex-sessions.ts @@ -7,7 +7,9 @@ * The schema is uniform `{ timestamp, type, payload }` records: * - type: session_meta — metadata (cwd, model, base instructions) * - type: turn_context — per-turn config (approval_policy, sandbox) - * - type: response_item — message / function_call / function_call_output + * - type: response_item — message / function_call / function_call_output, + * and in code mode custom_tool_call / _output + * (see lib/codex-code-mode.ts) * - type: event_msg — task_started, user_message, agent_message, * exec_command_begin/end, token_count, … * @@ -35,6 +37,7 @@ import { } from "./log-entries"; import { formatDuration } from "./format-duration"; import { codexSessionPathsFile } from "../src/hooks/fp-home"; +import { extractCodeModeCalls, patchedFiles } from "./codex-code-mode"; // ── Transcript discovery ── @@ -153,6 +156,53 @@ function safeJsonParse(s: string | undefined): Record { } } +/** A Codex patch as a tool input: the patch text, plus the file(s) it names so + * path policies have a `file_path` to check. */ +function patchInput(patch: string): Record { + const files = patchedFiles(patch); + const input: Record = { patch }; + if (files.length > 0) input.file_path = files[0]; + if (files.length > 1) input.files = files; + return input; +} + +/** The tool_use blocks one code-mode `custom_tool_call` stands for. */ +function codeModeToolUses(name: string, rawInput: unknown, id: string): ToolUseBlock[] { + const text = typeof rawInput === "string" ? rawInput : JSON.stringify(rawInput ?? ""); + if (name === "apply_patch") { + return [{ type: "tool_use", id, name, input: patchInput(text) }]; + } + if (name !== "exec") { + return [{ type: "tool_use", id, name, input: { input: text } }]; + } + const calls = extractCodeModeCalls(text); + if (calls.length === 0) { + // A snippet that calls no tool (e.g. filtering ALL_TOOLS) still ran code. + return [{ type: "tool_use", id, name: "exec", input: { code: text } }]; + } + return calls.map((call, i) => { + let input: Record; + if (call.name === "apply_patch" && typeof call.arg === "string") input = patchInput(call.arg); + else if (call.arg && typeof call.arg === "object" && !Array.isArray(call.arg)) input = { ...(call.arg as Record) }; + else if (call.arg !== undefined) input = { input: call.arg }; + else input = {}; + // Whatever could not be read as a literal stays visible as the snippet. + if (call.partial) input.code = text; + return { type: "tool_use", id: calls.length === 1 ? id : `${id}#${i}`, name: call.name, input }; + }); +} + +/** `custom_tool_call_output.output`: a string, or `[{type:"input_text",text}]`. */ +function customOutputText(output: unknown): string { + if (typeof output === "string") return output; + if (Array.isArray(output)) { + return output + .map((b) => (b && typeof b === "object" && typeof (b as { text?: unknown }).text === "string" ? (b as { text: string }).text : "")) + .join(""); + } + return JSON.stringify(output ?? ""); +} + function joinTexts(blocks: CodexContentBlock[] | undefined, wantedType: "input_text" | "output_text"): string { if (!Array.isArray(blocks)) return ""; return blocks @@ -300,6 +350,52 @@ export async function parseCodexLog( continue; } + // Codex code mode (≈0.146+, every tool call on 0.172): `exec` carries a + // JavaScript snippet that calls the real tools via `tools.(…)`; + // `apply_patch` carries the freeform patch text. Emit one tool_use per + // inner call so the audit sees `exec_command {cmd}` rather than nothing. + if (subType === "custom_tool_call") { + const callId = payload.call_id as string | undefined; + const name = (payload.name as string | undefined) ?? "custom_tool_call"; + const rawInput = payload.input; + const blocks = codeModeToolUses(name, rawInput, callId ?? `${timestamp}-${name}`); + entries.push({ + type: "assistant", + ...baseEntry(rawCopy, timestamp, date, source), + message: { role: "assistant", content: blocks }, + } satisfies AssistantEntry); + if (callId && blocks.length > 0) { + // One output covers the whole snippet; it is attached to the first + // inner call only, so a result-scanning policy counts it once. + toolUseById.set(callId, blocks[0]); + toolUseStartMs.set(callId, date.getTime()); + } + continue; + } + + if (subType === "custom_tool_call_output") { + const callId = payload.call_id as string | undefined; + const block = callId ? toolUseById.get(callId) : undefined; + if (block) { + const startMs = toolUseStartMs.get(callId!) ?? date.getTime(); + const duration = Math.max(0, date.getTime() - startMs); + block.result = { + timestamp, + timestampFormatted: formatTimestamp(date), + content: customOutputText(payload.output), + durationMs: duration, + durationFormatted: formatDuration(duration), + }; + continue; + } + entries.push({ + type: "system", + ...baseEntry(rawCopy, timestamp, date, source), + raw: rawCopy, + } satisfies GenericEntry); + continue; + } + // Unknown response_item subtype — preserve raw. entries.push({ type: "system", diff --git a/openclaw-plugin/hooks.js b/openclaw-plugin/hooks.js index f4aa23dc4..5cc9cddb8 100644 --- a/openclaw-plugin/hooks.js +++ b/openclaw-plugin/hooks.js @@ -22,7 +22,8 @@ import { createWorkspaceContext } from "./workspace-context.js"; import { openclawAgentSettingsPath, requestHookVerdict } from "./daemon-client.js"; const sharedRetryGate = createInstructRetryGate(); -const sharedWorkspace = createWorkspaceContext(); +/** Shared with the Self Reports tool, so its reports land in the workspace the hooks saw. */ +export const sharedWorkspace = createWorkspaceContext(); const OBSERVATION_EVENTS = [ "after_tool_call", diff --git a/openclaw-plugin/index.js b/openclaw-plugin/index.js index e1cf93d65..b6f046071 100644 --- a/openclaw-plugin/index.js +++ b/openclaw-plugin/index.js @@ -27,7 +27,8 @@ * happens inside register()'s handlers. */ import { definePluginEntry } from "openclaw/plugin-sdk/plugin-entry"; -import { registerFailproofaiHooks } from "./hooks.js"; +import { registerFailproofaiHooks, sharedWorkspace } from "./hooks.js"; +import { registerSelfReportTool } from "./self-report.js"; export default definePluginEntry({ id: "failproofai", @@ -35,5 +36,7 @@ export default definePluginEntry({ description: "Real-time policy enforcement for OpenClaw by failproofai", register(api) { registerFailproofaiHooks(api); + // Self Reports: the `report` tool as a direct (never deferred) plugin tool. + registerSelfReportTool(api, { workspace: sharedWorkspace }); }, }); diff --git a/openclaw-plugin/openclaw.plugin.json b/openclaw-plugin/openclaw.plugin.json index 879fcde17..d47a454cb 100644 --- a/openclaw-plugin/openclaw.plugin.json +++ b/openclaw-plugin/openclaw.plugin.json @@ -2,5 +2,10 @@ "id": "failproofai", "name": "failproofai", "description": "Real-time policy enforcement for OpenClaw by failproofai", - "configSchema": {} + "configSchema": {}, + "contracts": { + "tools": [ + "failproofai_local__report" + ] + } } diff --git a/openclaw-plugin/self-report.js b/openclaw-plugin/self-report.js new file mode 100644 index 000000000..1b9965a06 --- /dev/null +++ b/openclaw-plugin/self-report.js @@ -0,0 +1,235 @@ +/** + * Self Reports on OpenClaw: failproofai's `report` tool as a NATIVE plugin tool. + * + * OpenClaw defers MCP tools behind its Tool Search (`tools.toolSearch`, on by + * default for embedded runs) and has no per-server setting that keeps one + * server's tools direct, so a `failproofai_local` MCP entry reached the model + * only as a name in the deferred directory; the model never read the tool's + * description and never reported (0/2 on a strong model). A plugin tool marked + * `catalogMode: "direct-only"` stays model-visible (docs/tools/tool-search.md), + * so this plugin, which every hooked OpenClaw already loads, registers the tool + * itself and puts the server's instructions in the system prompt AND in the + * turn's own context (`before_prompt_build` → `appendSystemContext` + + * `appendContext`, docs plugins/hooks/prompt-and-session.md). The system + * context alone was seen and ignored (0/3 stuck runs reported); with the + * per-turn copy too, 3/3 did, and 0/2 normal runs reported falsely. + * `self-report sync` writes no OpenClaw MCP entry and removes one an earlier + * version wrote. + * + * The text and the recording come from failproofaid's own Self Reports MCP + * server (crates/fpai-collect/src/self_report.rs), so this file holds no copy + * of either: the tool's description and schema are what its `tools/list` + * returns (none while Self Reports is off), and each call is its `tools/call`, + * sent as `?agent=openclaw&cwd=` so the report is attributed, deduped + * and logged exactly as the MCP path did. The endpoint is trusted only when it + * answers `initialize` with the `instanceId` the daemon behind THIS user's + * socket reports in its pong: a port held by another user's daemon is never + * sent a report. + * + * Node built-ins and siblings only (the plugin is loaded from a captured copy). + */ +import { createConnection } from "node:net"; +import { daemonSocketPath, PROTOCOL_VERSION } from "./daemon-client.js"; + +/** OpenClaw's spelling of the MCP tool (`__`): the hook lets it past every policy. */ +export const SELF_REPORT_OPENCLAW_TOOL = "failproofai_local__report"; + +const REFRESH_MS = 60_000; +const REQUEST_TIMEOUT_MS = 5_000; +const CALL_TIMEOUT_MS = 20_000; +const MAX_FRAME_BYTES = 1024 * 1024; + +/** The daemon's pong `selfReport` ({instanceId, port}) or null. */ +export function pingSelfReportServer({ socketPath = daemonSocketPath(), timeoutMs = REQUEST_TIMEOUT_MS } = {}) { + return new Promise((done) => { + let settled = false; + let buf = Buffer.alloc(0); + const finish = (value) => { + if (settled) return; + settled = true; + clearTimeout(timer); + try { sock.destroy(); } catch { /* closed */ } + done(value); + }; + const sock = createConnection(socketPath); + const timer = setTimeout(() => finish(null), timeoutMs); + sock.on("error", () => finish(null)); + sock.on("connect", () => { + const body = Buffer.from(JSON.stringify({ type: "ping", protocolVersion: PROTOCOL_VERSION }), "utf8"); + const head = Buffer.alloc(4); + head.writeUInt32BE(body.length, 0); + sock.write(Buffer.concat([head, body])); + }); + sock.on("data", (chunk) => { + buf = Buffer.concat([buf, chunk]); + if (buf.length < 4) return; + const len = buf.readUInt32BE(0); + if (len > MAX_FRAME_BYTES) return finish(null); + if (buf.length < 4 + len) return; + try { + const msg = JSON.parse(buf.subarray(4, 4 + len).toString("utf8")); + const sr = msg && msg.type === "pong" ? msg.selfReport : null; + finish(sr && typeof sr.instanceId === "string" && Number.isInteger(sr.port) ? sr : null); + } catch { + finish(null); + } + }); + sock.on("close", () => finish(null)); + }); +} + +async function rpc(url, body, timeoutMs, fetchImpl) { + const res = await fetchImpl(url, { + method: "POST", + headers: { "content-type": "application/json", accept: "application/json, text/event-stream" }, + body: JSON.stringify(body), + signal: AbortSignal.timeout(timeoutMs), + }); + if (!res.ok) throw new Error(`HTTP ${res.status}`); + return res.json(); +} + +const INIT = { + jsonrpc: "2.0", + id: 1, + method: "initialize", + params: { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "failproofai-openclaw-plugin", version: "1" } }, +}; + +/** + * The report tool as failproofaid offers it right now, or null: no daemon, an + * endpoint that is not this user's daemon, or Self Reports off (empty list). + */ +export async function discoverSelfReportTool({ ping = pingSelfReportServer, fetchImpl = globalThis.fetch } = {}) { + const server = await ping(); + if (!server || typeof fetchImpl !== "function") return null; + const base = `http://127.0.0.1:${server.port}/mcp?agent=openclaw`; + try { + const init = await rpc(base, INIT, REQUEST_TIMEOUT_MS, fetchImpl); + if (init?.result?.serverInfo?.instanceId !== server.instanceId) return null; + const listed = await rpc(base, { jsonrpc: "2.0", id: 2, method: "tools/list" }, REQUEST_TIMEOUT_MS, fetchImpl); + const tool = Array.isArray(listed?.result?.tools) ? listed.result.tools[0] : undefined; + if (!tool || typeof tool.description !== "string" || !tool.inputSchema || typeof tool.inputSchema !== "object") return null; + const instructions = init.result.instructions; + return { + port: server.port, + instanceId: server.instanceId, + description: tool.description, + inputSchema: tool.inputSchema, + ...(typeof instructions === "string" && instructions ? { instructions } : {}), + }; + } catch { + return null; + } +} + +/** Hand one call to failproofaid's server; the text it answers (always "Recorded." today). */ +export async function callSelfReportTool(tool, args, cwd, { fetchImpl = globalThis.fetch, ping = pingSelfReportServer } = {}) { + // Re-check the port's owner: the daemon may have restarted on another port. + const server = await ping(); + if (!server || server.instanceId !== tool.instanceId || server.port !== tool.port) return "Recorded."; + const url = `http://127.0.0.1:${tool.port}/mcp?agent=openclaw${cwd ? `&cwd=${encodeURIComponent(cwd)}` : ""}`; + try { + const reply = await rpc( + url, + { jsonrpc: "2.0", id: 3, method: "tools/call", params: { name: "report", arguments: args ?? {} } }, + CALL_TIMEOUT_MS, + fetchImpl, + ); + const first = Array.isArray(reply?.result?.content) ? reply.result.content[0] : undefined; + return typeof first?.text === "string" ? first.text : "Recorded."; + } catch { + return "Recorded."; + } +} + +function pick(args, keys) { + for (const k of keys) { + const v = args[k]; + if (typeof v === "string" && v.trim() !== "") return v; + } + return ""; +} + +/** A model that guessed the argument names still reports (contract §3), like the MCP server. */ +export function prepareSelfReportArguments(raw) { + const a = raw && typeof raw === "object" && !Array.isArray(raw) ? raw : {}; + return { + category: pick(a, ["category", "type", "kind"]), + detail: pick(a, ["detail", "summary", "sentence", "message", "description", "reason", "text", "details"]), + }; +} + +/** + * Register the native tool and the prompt instructions on `api`. The tool + * definition is fetched from the daemon at load and every minute after, so a + * Cloud switch or new categories reach the next turn; while none is known + * (off, or no daemon) the factory offers no tool and no instructions are added. + */ +export function registerSelfReportTool(api, { + discover = discoverSelfReportTool, + call = callSelfReportTool, + workspace = /** @type {{ resolveWorkspace?: (p: object, c: object, config: unknown) => string | undefined } | null} */ (null), + refreshMs = REFRESH_MS, + now = () => Date.now(), +} = {}) { + let current = null; + let fetchedAt = -Infinity; + let inflight = null; + const refresh = () => { + if (inflight) return inflight; + inflight = Promise.resolve() + .then(() => discover()) + .then((tool) => { current = tool ?? null; }) + .catch(() => { current = null; }) + .finally(() => { fetchedAt = now(); inflight = null; }); + return inflight; + }; + const maybeRefresh = () => { + if (now() - fetchedAt >= refreshMs) void refresh(); + }; + void refresh(); + + if (typeof api?.registerTool === "function") { + try { + api.registerTool( + (toolContext) => { + maybeRefresh(); + const tool = current; + if (!tool) return null; + return { + name: SELF_REPORT_OPENCLAW_TOOL, + label: "Report (FailproofAI)", + description: tool.description, + parameters: tool.inputSchema, + // Never behind Tool Search: the model must read when to call it. + catalogMode: "direct-only", + prepareArguments: prepareSelfReportArguments, + async execute(_toolCallId, params) { + const cwd = workspace?.resolveWorkspace?.({}, toolContext ?? {}, api.config) ?? process.cwd(); + const text = await call(tool, prepareSelfReportArguments(params), cwd); + return { content: [{ type: "text", text }], details: { recorded: true } }; + }, + }; + }, + { name: SELF_REPORT_OPENCLAW_TOOL }, + ); + } catch (err) { + try { api.logger?.error?.(`[failproofai] could not register the Self Reports tool: ${err?.message ?? String(err)}`); } catch { /* no logger */ } + } + } + + if (typeof api?.on === "function") { + api.on( + "before_prompt_build", + async () => { + if (now() - fetchedAt >= refreshMs) await refresh(); + const instructions = current?.instructions; + return instructions ? { appendSystemContext: instructions, appendContext: instructions } : undefined; + }, + { priority: 100, timeoutMs: 10_000 }, + ); + } + + return { refresh, current: () => current }; +} diff --git a/package.json b/package.json index 2a38f51e3..f07734165 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "failproofai", - "version": "1.0.17", + "version": "1.0.18", "description": "The reliability layer for AI agents: see every failure, stop it in realtime. Policies hooked into 12 agent harnesses — Claude Code, Codex, Cursor, Hermes, OpenClaw and more — block the tool call before it runs. Local dashboard included, no account needed.", "bin": { "failproofai": "./dist/cli.mjs", diff --git a/pi-extension/index.ts b/pi-extension/index.ts index 21b2022e0..de3571720 100644 --- a/pi-extension/index.ts +++ b/pi-extension/index.ts @@ -25,7 +25,7 @@ * spawns extensions with an undefined cwd contract, so paths are resolved * relative to this file via `import.meta.url`, NOT process.cwd(). */ -import { spawnSync } from "node:child_process"; +import { spawn, spawnSync } from "node:child_process"; import { resolve, dirname, join } from "node:path"; import { fileURLToPath } from "node:url"; import { existsSync, readdirSync, statSync } from "node:fs"; @@ -333,9 +333,218 @@ interface PiBeforeAgentStartEvent { interface PiExtensionApi { on(event: string, handler: (event: unknown) => unknown): void; + /** Pi's custom tools (every Pi failproofai supports has it; checked anyway). */ + registerTool?(tool: Record): void; + /** Which tools the model sees; only callable once Pi has bound the extension (not during load). */ + getActiveTools?(): string[]; + setActiveTools?(toolNames: string[]): void; } -export default function failproofaiBridge(pi: PiExtensionApi) { +// ── Self Reports ──────────────────────────────────────────────────────────── +// +// Pi has no MCP of its own before 0.99 (its README: "No MCP."), so the +// `failproofai_local` entry in ~/.pi/agent/mcp.json reached no model there, +// with or without `exposure: "direct"`. This extension, which every hooked Pi +// already loads, offers the report tool itself instead, on every Pi version. +// The tool's text and the recording both come from failproofai's own stdio MCP +// server (`failproofai mcp --agent pi`), so this file holds no copy of either: +// it asks the server for the tool (none while Self Reports is off), and a call +// is handed to the server, which records it against Pi's session. +// +// It asks at load and again, at most once a minute, on `session_start` and +// `before_agent_start` (review finding F21): a Pi started while Self Reports +// was off, or while it waited for FailproofAI Cloud's setting, otherwise kept +// no tool until it was restarted. Pi takes `registerTool` after startup too +// (refreshed into the same session) and replaces a tool of the same name, so +// a tool that appears or changes is registered then, and one that goes away +// is taken out of the active tools (`setActiveTools`) until it is back. + +/** Pi spells it like Claude Code: one of the names the hook lets past every policy. */ +const SELF_REPORT_PI_TOOL = "mcp__failproofai_local__report"; + +interface SelfReportTool { + description: string; + inputSchema: Record; + instructions?: string; +} + +/** Send JSON-RPC lines to `failproofai mcp --agent pi`; resolves with the replies by id. */ +function selfReportServer(lines: unknown[], cwd: string, timeoutMs: number): Promise>> { + const { cmd, args } = resolveSpawn(); + return new Promise((resolveRun) => { + const replies = new Map>(); + let out = ""; + let settled = false; + let child: ReturnType; + try { + child = spawn(cmd, [...args, "mcp", "--agent", "pi"], { cwd, stdio: ["pipe", "pipe", "ignore"] }); + } catch { + resolveRun(replies); + return; + } + const timer = setTimeout(() => child.kill("SIGKILL"), timeoutMs); + child.stdout?.on("data", (b: Buffer) => (out += b.toString("utf8"))); + const done = () => { + if (settled) return; + settled = true; + clearTimeout(timer); + for (const line of out.split("\n")) { + try { + const msg = JSON.parse(line) as { id?: unknown; result?: Record }; + if (typeof msg.id === "number" && msg.result) replies.set(msg.id, msg.result); + } catch { + // not a reply + } + } + resolveRun(replies); + }; + child.on("error", done); + child.on("close", done); + child.stdin?.on("error", () => {}); + child.stdin?.end(lines.map((l) => JSON.stringify(l)).join("\n") + "\n"); + }); +} + +const SELF_REPORT_INIT = { + jsonrpc: "2.0", + id: 1, + method: "initialize", + params: { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "failproofai-pi-extension", version: "1" } }, +}; + +/** The report tool as the server offers it right now, or null (off, or no server). */ +async function selfReportToolFromServer(): Promise { + const replies = await selfReportServer( + [SELF_REPORT_INIT, { jsonrpc: "2.0", method: "notifications/initialized" }, { jsonrpc: "2.0", id: 2, method: "tools/list" }], + process.cwd(), + 10_000, + ); + const tools = replies.get(2)?.tools; + const tool = Array.isArray(tools) ? (tools[0] as Record | undefined) : undefined; + if (!tool || typeof tool.description !== "string" || !tool.inputSchema || typeof tool.inputSchema !== "object") return null; + const instructions = replies.get(1)?.instructions; + return { + description: tool.description, + inputSchema: tool.inputSchema as Record, + ...(typeof instructions === "string" ? { instructions } : {}), + }; +} + +/** The first non-empty string among `keys` (the server accepts the same aliases). */ +function selfReportPick(args: Record, keys: string[]): string { + for (const k of keys) { + const v = args[k]; + if (typeof v === "string" && v.trim() !== "") return v; + } + return ""; +} + +function registerSelfReportTool(pi: PiExtensionApi, tool: SelfReportTool): boolean { + if (typeof pi.registerTool !== "function") return false; + pi.registerTool({ + name: SELF_REPORT_PI_TOOL, + label: "Report (FailproofAI)", + description: tool.description, + // The server's instructions go into Pi's system prompt, as an MCP client + // that honours them would put them. + ...(tool.instructions ? { promptSnippet: "Report to FailproofAI when you are blocked", promptGuidelines: [tool.instructions] } : {}), + parameters: tool.inputSchema, + // A model that guessed the argument names still reports (contract §3). + prepareArguments: (raw: unknown) => { + const a = raw && typeof raw === "object" && !Array.isArray(raw) ? (raw as Record) : {}; + return { + category: selfReportPick(a, ["category", "type", "kind"]), + detail: selfReportPick(a, ["detail", "summary", "sentence", "message", "description", "reason", "text", "details"]), + }; + }, + async execute(_id: string, params: Record, _signal: unknown, _update: unknown, ctx?: { cwd?: string }) { + const replies = await selfReportServer( + [ + SELF_REPORT_INIT, + { jsonrpc: "2.0", method: "notifications/initialized" }, + { jsonrpc: "2.0", id: 2, method: "tools/call", params: { name: "report", arguments: params } }, + ], + ctx?.cwd ?? process.cwd(), + 20_000, + ); + const content = replies.get(2)?.content; + const first = Array.isArray(content) ? (content[0] as { text?: unknown } | undefined) : undefined; + const text = typeof first?.text === "string" ? first.text : "Recorded."; + return { content: [{ type: "text", text }], details: {} }; + }, + }); + return true; +} + +/** How often the extension asks the server again whether it offers the tool. */ +const SELF_REPORT_REFRESH_MS = 60_000; + +/** Keeps the registered report tool in step with what the server offers. */ +export interface SelfReportToolSync { + /** Ask the server (at most once a minute unless `force`); resolves when done. Never rejects. */ + refresh(force?: boolean): Promise; + /** Whether a tool is registered and not taken out of the active tools. */ + offered(): boolean; +} + +export function selfReportToolSync( + pi: PiExtensionApi, + discover: () => Promise = selfReportToolFromServer, + clock: () => number = Date.now, +): SelfReportToolSync { + let registeredAs: string | null = null; + let hidden = false; + let last = -Infinity; + let inflight: Promise | null = null; + const setActive = (on: boolean): void => { + if (typeof pi.getActiveTools !== "function" || typeof pi.setActiveTools !== "function") return; + try { + const active = pi.getActiveTools(); + const has = active.includes(SELF_REPORT_PI_TOOL); + if (on && !has) pi.setActiveTools([...active, SELF_REPORT_PI_TOOL]); + if (!on && has) pi.setActiveTools(active.filter((n) => n !== SELF_REPORT_PI_TOOL)); + hidden = !on; + } catch { + // Not bound yet (during load): nothing to switch. + } + }; + const run = async (): Promise => { + let tool: SelfReportTool | null = null; + try { + tool = await discover(); + } catch (err) { + debug(`self-report tool lookup failed: ${err instanceof Error ? err.message : String(err)}`); + } + if (tool) { + const key = JSON.stringify(tool); + if (key !== registeredAs) { + try { + if (registerSelfReportTool(pi, tool)) registeredAs = key; + } catch (err) { + debug(`self-report tool not registered: ${err instanceof Error ? err.message : String(err)}`); + } + } + if (registeredAs !== null && hidden) setActive(true); + } else if (registeredAs !== null && !hidden) { + setActive(false); + } + }; + return { + refresh(force = false) { + if (inflight) return inflight; + if (!force && clock() - last < SELF_REPORT_REFRESH_MS) return Promise.resolve(); + last = clock(); + inflight = run().finally(() => { + inflight = null; + }); + return inflight; + }, + offered: () => registeredAs !== null && !hidden, + }; +} + +export default async function failproofaiBridge(pi: PiExtensionApi) { + const selfReport = selfReportToolSync(pi); // tool_call → PreToolUse. Block tool execution when failproofai denies. pi.on("tool_call", (event: unknown): unknown => { const e = event as PiToolCallEvent; @@ -428,6 +637,8 @@ export default function failproofaiBridge(pi: PiExtensionApi) { // activity feed records the session and any UserPromptSubmit policies that // need session_id continuity see the metadata. pi.on("session_start", (event: unknown): unknown => { + // Self Reports may have been turned on since the last look; never awaited. + void selfReport.refresh(); const e = event as PiSessionStartEvent; callPolicy("session_start", { session_id: resolveSessionId(e.sessionId, resolveCwd(e.cwd)), @@ -492,6 +703,9 @@ export default function failproofaiBridge(pi: PiExtensionApi) { // already carries the policy-attributed MANDATORY ACTION wording from // policy-evaluator's Pi-Stop branch. pi.on("before_agent_start", (event: unknown): unknown => { + // Self Reports may have been turned on since the last look; never awaited, + // so a prompt never waits on it (the tool shows from the next turn). + void selfReport.refresh(); const e = event as PiBeforeAgentStartEvent; const cwd = resolveCwd(e.cwd); const sessionId = resolveSessionId(e.sessionId, cwd); @@ -534,4 +748,7 @@ export default function failproofaiBridge(pi: PiExtensionApi) { if (sessionId) pendingStopBlockBySession.delete(sessionId); return undefined; }); + + // Last, so the policy hooks above are in place whatever this does. + await selfReport.refresh(true); } diff --git a/sdk/python/CHANGELOG.md b/sdk/python/CHANGELOG.md index b46f1243b..d1465e969 100644 --- a/sdk/python/CHANGELOG.md +++ b/sdk/python/CHANGELOG.md @@ -11,6 +11,32 @@ see `scripts/changelog-section.py`. ## 0.0.1b7 — 2026-10-16 +### Features + +- **Self Reports.** A tool the agent calls when it is stuck, recorded as a new + `self_report` event (`category`, `detail`, `source: "sdk"`, optional + `tool_call_id`) in the current session and agent scope. New API: + `failproofai_sdk.self_report()` / `event.self_report()`, `self_report_spec()`, + `openai_tool()`, `openai_responses_tool()`, `anthropic_tool()`, + `handle_tool_call()` (always answers `Recorded.`, never raises into the agent + loop) and `is_self_report_tool()`. Ready-made tools: + `integrations..self_report_tool()`, + and the Pydantic AI capability adds it with `FailproofAI(self_report=True)` / + `instrument("pydantic_ai", self_report=True)`. Categories and guidance come from + `$FAILPROOFAI_HOME/self-report.json`, else six defaults. A report with no + session bound matches an open tool call only within one session (never the + newest of several), and open calls are tracked per session; a `tool_call_id` + open in several sessions is never resolved by the tool name instead, and with + an explicit session the call id is taken only from the one open report call of + that session and agent. `detail` is cut to 2000 code points with no lone + surrogate, as the daemon cuts it, and never with part of a token left at the + end: a credential running past the cut is dropped whole, so upload redaction + still recognises what is kept (a detail that is one long token reads + `[detail cut]`). `openai_responses_tool()` sets + `strict: True`. `uninstrument("pydantic_ai")` leaves runs of a hand-attached + `FailproofAI()` to finish. The CrewAI tool is never cached and runs in the + caller's context on CrewAI's async path. Still no runtime dependencies. + ### Dependencies - **The CrewAI extra no longer brings ChromaDB.** crewai 1.15.44 made `chromadb` an diff --git a/sdk/python/README.md b/sdk/python/README.md index 5931ed9ab..f88c154d2 100644 --- a/sdk/python/README.md +++ b/sdk/python/README.md @@ -74,6 +74,69 @@ standard library. See `skill/references/frameworks.md` for the per-framework mapping, and `docs/` for a per-framework integration guide with runnable examples beside it. +## Self Reports + +A tool your agent calls when it is stuck — looping, a broken tool or credential, +missing context, a request it cannot do, a task it failed. Each call becomes a +`self_report` event on the session, shown on the session's timeline in +FailproofAI Cloud. The tool always answers `Recorded.` and changes nothing. + +Ready-made tools, one per framework (each imports its framework only when called): + +```python +from failproofai_sdk.integrations.langchain import self_report_tool # StructuredTool (LangChain / LangGraph) +from failproofai_sdk.integrations.crewai import self_report_tool # crewai BaseTool +from failproofai_sdk.integrations.llama_index import self_report_tool # FunctionTool +from failproofai_sdk.integrations.pydantic_ai import self_report_tool # pydantic_ai Tool + +tools = [*my_tools, self_report_tool()] +``` + +Pydantic AI can also add it through the capability, opt in: +`FailproofAI(self_report=True)` or `failproofai_sdk.instrument("pydantic_ai", self_report=True)`. + +With a raw provider API: + +```python +tools = [failproofai_sdk.openai_tool(), *my_tools] # or openai_responses_tool(), anthropic_tool() + +for call in message.tool_calls: + if failproofai_sdk.is_self_report_tool(call.function.name): + output = failproofai_sdk.handle_tool_call( + call.function.name, call.function.arguments, tool_call_id=call.id + ) # "Recorded."; arguments may be a dict or a JSON string +``` + +Or record one directly, in the current session and agent scope: + +```python +failproofai_sdk.self_report("invalid_tool_or_credential", "The search API rejects our key.") +``` + +- **Spec.** `failproofai_sdk.self_report_spec()` returns `{name: "failproofai_report", + description, input_schema}`. The categories (the `category` enum) and any extra + guidance come from `$FAILPROOFAI_HOME/self-report.json` — written by the daemon + from your org's Cloud setting, or by the failproofai CLI — read each + time a spec is built. When that file is missing, unreadable or disabled, six + defaults are used (`looping`, `cannot_do_request`, `invalid_tool_or_credential`, + `missing_context`, `repeated_tool_failure`, `task_failure`): the tool works by + default, and adding it is itself the opt-in. Pass `categories=[...]` (and + `guidance=`) to any helper to override. +- **Event.** `{type: "self_report", category, detail, source: "sdk", tool_call_id?}` + plus the usual `session_id` / `agent_id` / `timestamp` / `environment`. An + unknown category is recorded as given; `detail` is cut to 2,000 characters. +- **Session.** Most specific first: an explicit `session_id=` (framework tools + also take one on the factory); the run the adapter is recording (framework + tools, when instrumented); the open `tool_use` for this call (by + `tool_call_id`, then the newest open report-tool call) within the enclosing + session; the enclosing `session()` / `agent()` scope; otherwise the report is + filed under `"unattributed"` with one warning. Unlike the other event methods, + a missing session never raises, and the tool helpers never raise into your + agent loop at all. +- **Hiding it.** `failproofai_sdk.is_self_report_tool(name)` is true for + `failproofai_report` and the coding-agent MCP spellings + (`mcp__failproofai_local__report`, `failproofai_local__report`, ...). + ## OpenTelemetry (opt in) Already emitting OpenTelemetry spans? Install `opentelemetry-sdk` separately, @@ -439,6 +502,22 @@ failproofai_sdk.event.error( --- +### `event.self_report()` + +The agent reports it is stuck. See [Self Reports](#self-reports). + +```python +failproofai_sdk.event.self_report( + "looping", # category: str, required (recorded as given) + "same search, third time", # detail: str | None, cut to 2000 chars + session_id="run-001", + agent_id="planner", + tool_call_id="call_1", # str | None +) +``` + +--- + ## Custom fields Any extra keyword arguments are appended to the event after the standard fields: @@ -501,7 +580,7 @@ uv run pytest tests/test_sdk.py -k duration -v | Suite | What it holds | |---|---| | `test_sdk.py` | The public API — every event method, unit and on-disk | -| `test_wire_format.py` | Golden bytes for all 15 event types, frozen | +| `test_wire_format.py` | Golden bytes for all 16 event types, frozen | | `test_server_contract.py` | The keys ingest promotes to indexed columns | | `test_spool_contract.py` | Agreement with the daemons that read the spool | | `test_durability.py` | Concurrency, crash and retry paths — nothing silently lost | diff --git a/sdk/python/docs/README.md b/sdk/python/docs/README.md index aa2e7aa04..6bbbbeb74 100644 --- a/sdk/python/docs/README.md +++ b/sdk/python/docs/README.md @@ -108,7 +108,7 @@ which is almost never what you want. --- -## the fifteen event types +## the sixteen event types | group | events | what they mean | |---|---|---| @@ -120,6 +120,7 @@ which is almost never what you want. | humans | `human_wait` `human_input` | you asked a person / they answered | | | `human_pause` `human_interrupt` | a person paused / stopped the agent | | failures | `error` | something went wrong | +| self reports | `self_report` | the agent said it is stuck (see below) | **Events come in pairs.** The closing event carries a `duration_ms` measured from the matching opening one. An opening event with no close renders as a span @@ -141,12 +142,17 @@ Measured from the real runs in this directory, not declared. | `human_wait` / `human_input` | yes | yes | yes | — | you | | `agent_pause` / `agent_resume` | yes | yes | yes | — | you | | `human_pause` / `human_interrupt` | — | — | — | — | you | +| `self_report` | tool | tool | tool | tool / capability | you | A dash means the framework has no such concept, not that it is missing. Pydantic AI has no node boundary and no built-in human pause, so there is nothing to map. `human_pause` and `human_interrupt` describe a *person* acting on the agent — a stop button — which no framework signals; emit those yourself. +`self_report` comes from the report tool the agent itself calls when it is +stuck. Add it with `self_report_tool()` from the framework's integration module +(each guide shows the line), or call `failproofai_sdk.self_report(...)` yourself. + --- ## running the examples diff --git a/sdk/python/docs/crewai/README.md b/sdk/python/docs/crewai/README.md index 6d0ad958f..adf1f7daf 100644 --- a/sdk/python/docs/crewai/README.md +++ b/sdk/python/docs/crewai/README.md @@ -254,6 +254,30 @@ never added. --- +## Self Reports + +Give the agent a tool to say it is stuck: looping, a broken tool or credential, +missing context, a request it cannot do. + +```python +from crewai import Agent +from failproofai_sdk.integrations.crewai import self_report_tool + +analyst = Agent(role="Analyst", goal="...", backstory="...", tools=[search, self_report_tool()]) +``` + +A CrewAI `BaseTool`. While the adapter is installed the report lands on the agent that ran the tool; otherwise on the enclosing `failproofai_sdk.session()`. + +The tool's description and its `category` enum come from +`~/.failproofai/self-report.json` (your org's categories when Self Reports is on +in FailproofAI Cloud, or set locally with `failproofai self-report enable`), and +fall back to six built-in categories. It always answers `Recorded.` and changes +nothing; the call becomes a `self_report` event on the agent's session. To keep +it out of a transcript you show users, filter on +`failproofai_sdk.is_self_report_tool(name)`. + +--- + ## Pitfalls ### Roles with ids in them wreck the facet diff --git a/sdk/python/docs/langgraph/README.md b/sdk/python/docs/langgraph/README.md index c8801076a..d34c9c508 100644 --- a/sdk/python/docs/langgraph/README.md +++ b/sdk/python/docs/langgraph/README.md @@ -361,6 +361,32 @@ The root agent span deliberately stays **open** across the gap, so the two --- +## Self Reports + +Give the agent a tool to say it is stuck: looping, a broken tool or credential, +missing context, a request it cannot do. + +```python +from failproofai_sdk.integrations.langchain import self_report_tool +from langgraph.prebuilt import ToolNode + +tools = [search, self_report_tool()] +model = model.bind_tools(tools) +graph.add_node("tools", ToolNode(tools)) +``` + +A `StructuredTool`. While the adapter is installed the report lands on the agent whose run called it, with the model's `tool_call_id`; otherwise on the enclosing `failproofai_sdk.session()`. + +The tool's description and its `category` enum come from +`~/.failproofai/self-report.json` (your org's categories when Self Reports is on +in FailproofAI Cloud, or set locally with `failproofai self-report enable`), and +fall back to six built-in categories. It always answers `Recorded.` and changes +nothing; the call becomes a `self_report` event on the agent's session. To keep +it out of a transcript you show users, filter on +`failproofai_sdk.is_self_report_tool(name)`. + +--- + ## Pitfalls ### A raising tool aborts the whole graph diff --git a/sdk/python/docs/llama_index/README.md b/sdk/python/docs/llama_index/README.md index 138b2ddc1..332ff42df 100644 --- a/sdk/python/docs/llama_index/README.md +++ b/sdk/python/docs/llama_index/README.md @@ -263,6 +263,30 @@ tool and is captured in full. --- +## Self Reports + +Give the agent a tool to say it is stuck: looping, a broken tool or credential, +missing context, a request it cannot do. + +```python +from llama_index.core.agent.workflow import FunctionAgent +from failproofai_sdk.integrations.llama_index import self_report_tool + +agent = FunctionAgent(name="researcher", llm=llm, tools=[search, self_report_tool()]) +``` + +A `FunctionTool`. While the adapter is installed the report lands on the agent whose tool span called it; otherwise on the enclosing `failproofai_sdk.session()`. + +The tool's description and its `category` enum come from +`~/.failproofai/self-report.json` (your org's categories when Self Reports is on +in FailproofAI Cloud, or set locally with `failproofai self-report enable`), and +fall back to six built-in categories. It always answers `Recorded.` and changes +nothing; the call becomes a `self_report` event on the agent's session. To keep +it out of a transcript you show users, filter on +`failproofai_sdk.is_self_report_tool(name)`. + +--- + ## Pitfalls ### Every token count is null diff --git a/sdk/python/docs/manual/README.md b/sdk/python/docs/manual/README.md index 39c628e81..2d9d4662d 100644 --- a/sdk/python/docs/manual/README.md +++ b/sdk/python/docs/manual/README.md @@ -9,7 +9,7 @@ adapters call underneath — they are translation tables over the same API. - [Install](#install) - [The three scopes](#the-three-scopes) - [What a scope does on the way out](#what-a-scope-does-on-the-way-out) -- [The fifteen event methods](#the-fifteen-event-methods) +- [The sixteen event methods](#the-sixteen-event-methods) - [A complete example](#a-complete-example) - [Threads and async](#threads-and-async) - [Instrumenting an unsupported framework](#instrumenting-an-unsupported-framework) @@ -105,7 +105,7 @@ is reported exactly once by the enclosing `agent()`. --- -## The fifteen event methods +## The sixteen event methods ### agents @@ -191,6 +191,32 @@ failproofai_sdk.event.error( Usually emitted for you by `agent()`. Call it directly for a failure that does not raise — a validation rejection, a guardrail trip. +### self reports + +```python +failproofai_sdk.self_report("missing_context", "The customer id was never provided.") +# the same event: failproofai_sdk.event.self_report(category=..., detail=...) +``` + +The agent saying it is stuck. Usually the MODEL makes this call, through the +report tool; with a raw provider API give it the tool and route the call: + +```python +tools = [failproofai_sdk.openai_tool(), *my_tools] # anthropic_tool() for Claude +... +for call in message.tool_calls: + if failproofai_sdk.is_self_report_tool(call.function.name): + result = failproofai_sdk.handle_tool_call( + call.function.name, call.function.arguments, tool_call_id=call.id + ) # always "Recorded." +``` + +`self_report_spec()` returns the bare `{name, description, input_schema}`. +Categories and wording come from `~/.failproofai/self-report.json`, else six +built-in defaults. `handle_tool_call` never raises into your loop. With no +session bound, a report is filed under `"unattributed"` (one warning) instead +of raising. + --- ## A complete example @@ -395,7 +421,7 @@ Instrumenting it means wrapping each agent at each construction site, which is a wrapper you paste into your own code — precisely the ergonomics the adapters exist to remove. -If AutoGen matters to you, the three seams above record the same fifteen event +If AutoGen matters to you, the three seams above record the same sixteen event types at the same fidelity. It just costs you the call sites. --- diff --git a/sdk/python/docs/pydantic_ai/README.md b/sdk/python/docs/pydantic_ai/README.md index b9d9d162e..40f51479e 100644 --- a/sdk/python/docs/pydantic_ai/README.md +++ b/sdk/python/docs/pydantic_ai/README.md @@ -214,6 +214,7 @@ failproofai_sdk.instrument( "pydantic_ai", session_id=None, # pin every run to one session id capture_content=True, # False drops prompts and completions from payloads + self_report=False, # True adds the report tool to every agent (see Self Reports) ) ``` @@ -241,6 +242,36 @@ error" rather than raising an `AttributeError` inside your run. --- +## Self Reports + +Give the agent a tool to say it is stuck: looping, a broken tool or credential, +missing context, a request it cannot do. + +```python +from pydantic_ai import Agent +from failproofai_sdk.integrations.pydantic_ai import FailproofAI, self_report_tool + +agent = Agent("openai:gpt-5.6-sol", tools=[self_report_tool()]) + +# or let the capability add it to the agent +agent = Agent("openai:gpt-5.6-sol", capabilities=[FailproofAI(self_report=True)]) + +# or to every agent built from now on +failproofai_sdk.instrument("pydantic_ai", self_report=True) +``` + +A Pydantic AI `Tool` whose JSON schema is exactly the spec, carrying the model's `tool_call_id`. `self_report=True` is opt-in: the capability otherwise only observes, and adding a tool changes what the model sees. + +The tool's description and its `category` enum come from +`~/.failproofai/self-report.json` (your org's categories when Self Reports is on +in FailproofAI Cloud, or set locally with `failproofai self-report enable`), and +fall back to six built-in categories. It always answers `Recorded.` and changes +nothing; the call becomes a `self_report` event on the agent's session. To keep +it out of a transcript you show users, filter on +`failproofai_sdk.is_self_report_tool(name)`. + +--- + ## Pitfalls ### An empty trace, no errors anywhere diff --git a/sdk/python/failproofai_sdk/__init__.py b/sdk/python/failproofai_sdk/__init__.py index 5291fcbae..29208fb6c 100644 --- a/sdk/python/failproofai_sdk/__init__.py +++ b/sdk/python/failproofai_sdk/__init__.py @@ -7,7 +7,10 @@ under `with` and `async with`. * **Adapters** — `instrument()`. Auto-detects LangChain/LangGraph, CrewAI, LlamaIndex and Pydantic AI in the process and wires them to the scopes above. -* **`event.*`** — the 15 event methods, for anything the adapters do not cover. +* **`event.*`** — the 16 event methods, for anything the adapters do not cover. +* **Self Reports** — `self_report()` and the report tool for the model + (`openai_tool()`, `anthropic_tool()`, `handle_tool_call()`, `is_self_report_tool()`); + ready-made framework tools are `integrations..self_report_tool()`. `session_id` and `agent_id` are optional on every event method: omitted, they resolve from the enclosing scope. Nothing bound and nothing passed is an error, @@ -25,6 +28,15 @@ from failproofai_sdk._environment import _reject_comma from failproofai_sdk._writer import _validated_interval from failproofai_sdk import _runtime +from failproofai_sdk._self_report import ( + anthropic_tool, + handle_tool_call, + is_self_report_tool, + openai_responses_tool, + openai_tool, + self_report, + self_report_spec, +) __all__ = [ "__version__", @@ -39,6 +51,13 @@ "instrument", "uninstrument", "OtelSpanExporter", + "self_report", + "self_report_spec", + "openai_tool", + "openai_responses_tool", + "anthropic_tool", + "handle_tool_call", + "is_self_report_tool", "_writer", ] diff --git a/sdk/python/failproofai_sdk/_events.py b/sdk/python/failproofai_sdk/_events.py index 0f8ade53b..0dd939d2a 100644 --- a/sdk/python/failproofai_sdk/_events.py +++ b/sdk/python/failproofai_sdk/_events.py @@ -18,6 +18,7 @@ HumanWaitEvent, ModelRequestEvent, ModelResponseEvent, + SelfReportEvent, ToolResultEvent, ToolUseEvent, ) @@ -63,6 +64,68 @@ _U32_MAX = 2**32 - 1 +#: Longest `detail` a `self_report` carries. The same limit every recorder of +#: the event applies (hook, MCP server, both SDKs), so a report reads the same +#: whichever path wrote it. +SELF_REPORT_DETAIL_LIMIT = 2000 + + +def clip_report_text(text: str, limit: "int | None" = SELF_REPORT_DETAIL_LIMIT) -> str: + """`text` with no lone surrogate, cut to `limit` code points (`None`: not cut). + + Code points are what the daemon (`truncate_chars`) and the CLI count, so + every recorder keeps the same prefix of a long detail. A surrogate pair + spelled as two code points is joined; a lone one becomes U+FFFD. Either + would otherwise reach the event file as an unpaired `\\ud8xx` escape, which + the Rust collector rejects, losing the report. The shared cases are in + test-fixtures/self-report/truncation.golden.json. + """ + if any("\ud800" <= ch <= "\udfff" for ch in text): + text = text.encode("utf-16", "surrogatepass").decode("utf-16", "replace") + return text if limit is None else text[:limit] + + +#: What a detail cut down to nothing reads as (truncation.golden.json `detail_cut`). +DETAIL_CUT_MARKER = "[detail cut]" + +#: The whitespace the detail cut splits on: ASCII only, so every implementation +#: agrees (`str.isspace` is wider). +_CUT_WHITESPACE = frozenset(" \t\n\r\f\v") + + +def cut_report_detail(text: str, limit: int = SELF_REPORT_DETAIL_LIMIT) -> str: + """A report's detail cut to `limit` code points without leaving part of a token. + + A credential running past the cut (a long JWT or key) would otherwise be + kept as a fragment that no secret scrubber recognises, and be uploaded as + such. When the code point right after the cut is not whitespace, the + trailing run of non-whitespace is dropped; then trailing whitespace; an + empty result is `DETAIL_CUT_MARKER`. Text that fits is kept whole (with + lone surrogates replaced, as `clip_report_text` does). The CLI, the daemon + and the TypeScript SDK do the same; truncation.golden.json `detail_cut` + holds the cases. + """ + text = clip_report_text(text, None) + if len(text) <= limit: + return text + head = text[:limit] + if text[limit] not in _CUT_WHITESPACE: + end = len(head) + while end > 0 and head[end - 1] not in _CUT_WHITESPACE: + end -= 1 + head = head[:end] + end = len(head) + while end > 0 and head[end - 1] in _CUT_WHITESPACE: + end -= 1 + head = head[:end] + return head if head else DETAIL_CUT_MARKER + + +#: The session a `self_report` is filed under when nothing else identifies one — +#: the same value the MCP server fallback uses. +UNATTRIBUTED_SESSION = "unattributed" +_warned_unattributed = False + def _validate_promoted_numeric(name: str, value) -> None: """Reject anything `pu32()` would silently turn into NULL. @@ -287,6 +350,14 @@ class EventNamespace: def __init__(self, writer) -> None: self._writer = writer self._pending: dict[str, datetime] = {} + # _tool_key(session_id, tool_call_id) -> (session_id, agent_id, + # tool_name, tool_call_id) for every tool_use not yet closed by its + # tool_result. Keyed by session like `_pending`: two sessions may reuse + # one call id, and a bare key let the second replace (and its result + # remove) the first's entry. Read only by `self_report`, so a report + # made from inside a tool the caller already brackets lands on that + # tool's session and agent. Same cap and eviction as `_pending`. + self._open_tools: dict[str, tuple[str, str, str, str]] = {} def _track_pending(self, key: str, ts: datetime) -> None: # Evicting has to tolerate another thread doing the same thing, because @@ -321,6 +392,100 @@ def _track_pending(self, key: str, ts: datetime) -> None: self._pending.pop(oldest, None) # may already be gone self._pending[key] = ts + def _track_open_tool(self, key: str, entry: "tuple[str, str, str, str]") -> None: + # Tolerant for the reasons spelled out in `_track_pending`. + if len(self._open_tools) >= _PENDING_CAP: + try: + oldest = next(iter(self._open_tools)) + except (StopIteration, RuntimeError): + pass + else: + self._open_tools.pop(oldest, None) + self._open_tools.pop(key, None) # re-insert at the end: newest last + self._open_tools[key] = entry + + def _report_identity( + self, tool_call_id: "str | None", agent_id: "str | None" + ) -> "tuple[str, str, str | None]": + """Where a `self_report` with no explicit `session_id` belongs, and its call id. + + Most specific first, within the ambient session when one is bound: + the open `tool_use` with this `tool_call_id`; then, only when no open + call has that id (or none was given), the newest open `tool_use` of + the report tool itself, since an adapter may have recorded its own id + rather than the model's; then the enclosing scope; then + `"unattributed"` with one warning. With no ambient session, an open + `tool_use` is used only when every candidate is in one session: the + newest of several sessions would be a guess. An id open in several + sessions is such a guess too, and never falls back to the tool name. + Never raises: a report is evidence, and losing it to a missing scope is + the worse outcome. + + The third item is the `tool_call_id` to record: the caller's, else the + matched `tool_use`'s own id, so a tool that cannot see the model's call + id (LlamaIndex, CrewAI) still joins the call the adapter recorded. + """ + global _warned_unattributed + from failproofai_sdk._self_report import is_self_report_tool + + ambient = _context.session_id() + try: + open_tools = list(self._open_tools.values()) + except RuntimeError: # resized under us by another thread + open_tools = [] + candidates = [e for e in open_tools if ambient is None or e[0] == ambient] + + def unambiguous(found: "list[tuple[str, str, str, str]]") -> "tuple[str, str, str, str] | None": + if not found or (ambient is None and len({e[0] for e in found}) > 1): + return None + return found[-1] + + by_id = [e for e in candidates if e[3] == tool_call_id] if tool_call_id is not None else [] + if by_id: + # The id is known here: its call, or no guess at all. + match = unambiguous(by_id) + else: + match = unambiguous([e for e in candidates if is_self_report_tool(e[2])]) + if match is not None: + entry = match + call_id = entry[3] + return ( + entry[0], + agent_id if agent_id is not None else entry[1], + tool_call_id if tool_call_id is not None else call_id, + ) + if agent_id is None: + agent_id = _context.agent_id() + if ambient is not None: + return ambient, agent_id, tool_call_id + if not _warned_unattributed: + _warned_unattributed = True + logger.warning( + "Failproof AI recorded a self report with no session bound; it is filed " + "under session_id=%r. Pass session_id=... or wrap the agent in " + "`failproofai_sdk.session()`.", + UNATTRIBUTED_SESSION, + ) + return UNATTRIBUTED_SESSION, agent_id, tool_call_id + + def _open_report_call_id(self, session_id: str, agent_id: str) -> "str | None": + """The id of the one open report-tool `tool_use` of this session and agent. + + None when there is none, or several: two report calls open at once + (parallel tool calls) would make the id a guess between them. + """ + from failproofai_sdk._self_report import is_self_report_tool + + try: + open_tools = list(self._open_tools.values()) + except RuntimeError: # resized under us by another thread + return None + found = [ + e[3] for e in open_tools + if e[0] == session_id and e[1] == agent_id and is_self_report_tool(e[2]) + ] + return found[0] if len(found) == 1 else None + def _validate_fields(self, fields: dict) -> None: bad = _RESERVED & fields.keys() if bad: @@ -367,6 +532,7 @@ def tool_use( session_id, agent_id = _resolve_identity(session_id, agent_id) ts = self._now() self._track_pending(_tool_key(session_id, tool_call_id), ts) + self._track_open_tool(_tool_key(session_id, tool_call_id), (session_id, agent_id, tool_name, tool_call_id)) self._writer.submit( ToolUseEvent( timestamp=self._fmt_ts(ts), @@ -396,6 +562,7 @@ def tool_result( session_id, agent_id = _resolve_identity(session_id, agent_id) ts = self._now() start_ts = self._pending.pop(_tool_key(session_id, tool_call_id), None) + self._open_tools.pop(_tool_key(session_id, tool_call_id), None) duration_ms = _measured_duration_ms(start_ts, ts) self._writer.submit( ToolResultEvent( @@ -770,3 +937,69 @@ def human_interrupt( extra_fields=fields, ).to_dict() ) + + def self_report( + self, + category: str, + detail: "str | None" = "", + *, + session_id: str | None = None, + agent_id: str | None = None, + tool_call_id: str | None = None, + **fields, + ) -> None: + """Record that the agent reported itself stuck (a `self_report` event). + + `category` is recorded as given, even if it is not one of the configured + categories: a report is evidence, and refusing one because the model + picked a stale name would lose exactly the signal this exists for. + `detail` of `None` is recorded as `""`; anything longer than + `SELF_REPORT_DETAIL_LIMIT` characters is cut to it. + + `source` is always `"sdk"` and cannot be overridden: it is how the + dashboard tells an SDK report from one the coding-agent hook recorded. + + Session, most specific first: an explicit `session_id`; the open + `tool_use` for this call (by `tool_call_id`, then the newest open + report-tool call) within the enclosing session; the enclosing scope; + otherwise `"unattributed"` with one warning. A missing session never + raises here, unlike the other event methods — the TypeError/ValueError + checks on the arguments themselves still apply. With no `tool_call_id` + given, the report takes the id of the open report-tool `tool_use` it + was matched to (or, with an explicit `session_id`, of the one such call + open for that session and agent; none when several are open). + """ + if "source" in fields: + raise ValueError("source is set by the SDK (always \"sdk\") and cannot be passed by the caller") + self._validate_fields(fields) + if not isinstance(category, str): + raise TypeError( + f"category must be a str, got {type(category).__name__}: {category!r}" + ) + if detail is None: + detail = "" + if not isinstance(detail, str): + raise TypeError(f"detail must be a str, got {type(detail).__name__}: {detail!r}") + if tool_call_id is not None: + _validate_promoted_string("tool_call_id", tool_call_id) + if session_id is None: + session_id, agent_id, tool_call_id = self._report_identity(tool_call_id, agent_id) + elif tool_call_id is None: + # A framework tool that resolved its session from the adapter's run + # (LlamaIndex, CrewAI) but cannot see the model's call id. The agent + # is resolved first, so only that agent's open call is a candidate. + session_id, agent_id = _resolve_identity(session_id, agent_id) + tool_call_id = self._open_report_call_id(session_id, agent_id) + session_id, agent_id = _resolve_identity(session_id, agent_id) + ts = self._now() + self._writer.submit( + SelfReportEvent( + timestamp=self._fmt_ts(ts), + session_id=session_id, + agent_id=agent_id, + category=clip_report_text(category, None), + detail=cut_report_detail(detail), + tool_call_id=tool_call_id, + extra_fields=fields, + ).to_dict() + ) diff --git a/sdk/python/failproofai_sdk/_schema.py b/sdk/python/failproofai_sdk/_schema.py index c16d9ba9a..95d3e3e40 100644 --- a/sdk/python/failproofai_sdk/_schema.py +++ b/sdk/python/failproofai_sdk/_schema.py @@ -315,3 +315,32 @@ def to_dict(self) -> dict: [("reason", self.reason), ("user_id", self.user_id), ("at_step", self.at_step)], self.extra_fields, ) + + +@dataclass(kw_only=True) +class SelfReportEvent: + """The agent said it is stuck. See `failproofai_sdk.self_report`. + + `category` and `detail` are always present, even when empty: the report is + the event, and a row without them would render as a blank line on the Self + Reports page. `source` says which path recorded it (`"sdk"` here; the hook + and MCP paths write `"mcp"`). + """ + + timestamp: str + session_id: str + agent_id: str + category: str + detail: str + source: str = "sdk" + tool_call_id: str | None = None + extra_fields: dict = field(default_factory=dict) + + def to_dict(self) -> dict: + return _build( + {"timestamp": self.timestamp, "session_id": self.session_id, "agent_id": self.agent_id, + "type": "self_report", "category": self.category, "detail": self.detail, + "source": self.source}, + [("tool_call_id", self.tool_call_id)], + self.extra_fields, + ) diff --git a/sdk/python/failproofai_sdk/_self_report.py b/sdk/python/failproofai_sdk/_self_report.py new file mode 100644 index 000000000..044ef50f6 --- /dev/null +++ b/sdk/python/failproofai_sdk/_self_report.py @@ -0,0 +1,564 @@ +"""Self Reports: a tool the agent calls when it is stuck. + +The agent decides when to call it, from the tool's description alone. A call is +recorded as a `self_report` event on the agent's session and the tool answers +`Recorded.` — it never unblocks anything or changes a decision. + + import failproofai_sdk as fp + + tools = [fp.openai_tool(), *my_tools] # or anthropic_tool() + ... + if fp.is_self_report_tool(call.name): + result = fp.handle_tool_call(call.name, call.arguments) # "Recorded." + +Ready-made framework tools live next to each adapter, e.g. +`from failproofai_sdk.integrations.langchain import self_report_tool`. + +Categories and extra guidance come from `$FAILPROOFAI_HOME/self-report.json` +(written by the FailproofAI daemon from the org's Cloud setting, or by +`failproofai self-report enable`). When the file is missing, unreadable, or says +the feature is off, the defaults below are used: a developer who added this tool +to their agent asked for it explicitly, so it always has a usable spec. + +Stdlib only, like the rest of the core (`tests/test_zero_dependencies.py`). +""" + +from __future__ import annotations + +import copy +import json +import logging +import re +from pathlib import Path +from typing import Any + +from failproofai_sdk import _runtime +from failproofai_sdk._events import clip_report_text, cut_report_detail +from failproofai_sdk._resolver import failproofai_home + +logger = logging.getLogger(__name__) + +__all__ = [ + "TOOL_NAME", + "RESULT", + "DEFAULT_CATEGORIES", + "self_report", + "self_report_spec", + "describe", + "load_settings", + "settings_path", + "openai_tool", + "openai_responses_tool", + "anthropic_tool", + "handle_tool_call", + "is_self_report_tool", +] + +#: The SDK tool's name. The coding-agent MCP tool is `report` on server +#: `failproofai`; `is_self_report_tool` recognises every spelling of both. +TOOL_NAME = "failproofai_report" + +#: The tool's result text, exactly. Nothing else is ever returned to the model. +RESULT = "Recorded." + +#: Used when no org categories are configured. An org's own list REPLACES these. +DEFAULT_CATEGORIES: tuple[dict[str, str], ...] = ( + {"name": "looping", "description": "You keep repeating the same or circular steps without making progress."}, + {"name": "cannot_do_request", "description": "The user asked for something you cannot do here: a missing capability, tool or permission, or it is only possible by cheating."}, + {"name": "invalid_tool_or_credential", "description": "A tool, MCP server, plugin, API key or token you need is broken, invalid, expired or rejected."}, + {"name": "missing_context", "description": "Information or access you need is missing and you cannot get it yourself. Not for normal clarifying questions."}, + {"name": "repeated_tool_failure", "description": "A command or tool failed on several distinct attempts and is blocking you. A single error is not enough."}, + {"name": "task_failure", "description": "You genuinely tried and could not complete the task, or something else blocks you that no other category describes. Not for refusals or policy blocks."}, +) + +_PREAMBLE = ( + "When you are stuck on something you cannot fix yourself, call this tool once with " + "`category` (one of the categories below) and `detail` (one factual sentence: what is " + "blocking you). It reports to FailproofAI. Call it BEFORE your final answer, for example " + "for a missing, invalid or " + "expired token or API key, a 401 or 403, a command, tool or MCP server that keeps failing, " + "information or access you cannot get, or a request you cannot do here. Do not call it for " + "normal work, clarifying questions or an error you then fixed. One call per distinct " + "problem.\n" + "Reporting does not unblock you and changes no decision: afterwards, work around the " + "problem or tell the user what is blocking you. There is no need to mention this report " + "to the user." +) + +_DETAIL_DESCRIPTION = "One factual sentence: what is blocking you." + +_NAME_PATTERN = r"[a-z][a-z0-9_]{0,63}" # compiled on first use: nothing runs at import +_MAX_CATEGORIES = 32 +_MAX_DESCRIPTION = 500 +_MAX_GUIDANCE = 2000 + +#: Every spelling the report tool reaches a host under (case-insensitive, +#: exact): the SDK name, and the MCP tool `report` on server +#: `failproofai_local` as each agent prefixes it: Claude Code, Codex, Pi, +#: Factory and Devin `mcp__failproofai_local__report`, Factory's matcher form +#: `failproofai_local___report`, OpenCode `failproofai_local_report`, Hermes +#: and Antigravity `mcp_failproofai_local_report`, OpenClaw and Goose +#: `failproofai_local__report`, Copilot CLI (likely, unverified) +#: `failproofai_local-report` / `failproofai_local/report`, plus other +#: server-qualified forms. The CLI and the TypeScript SDK test the same list +#: against the repository's test-fixtures/self-report/tool-names.golden.txt. +TOOL_SPELLINGS: tuple[str, ...] = ( + "mcp__failproofai_local__report", + "failproofai_local___report", + "failproofai_local__report", + "failproofai_report", + "failproofai_local_report", + "failproofai_local.report", + "failproofai_local/report", + "failproofai_local:report", + "mcp_failproofai_local_report", + "mcp__failproofai_local_report", + "mcp:failproofai_local:report", + "mcp:failproofai_local/report", + "failproofai_local-report", +) +_TOOL_NAMES = frozenset(TOOL_SPELLINGS) + + +# --------------------------------------------------------------------------- +# Settings +# --------------------------------------------------------------------------- + +def settings_path() -> Path: + """`$FAILPROOFAI_HOME/self-report.json` (default `~/.failproofai/self-report.json`).""" + return failproofai_home() / "self-report.json" + + +def _valid_category(entry: Any) -> bool: + if not isinstance(entry, dict): + return False + name, description = entry.get("name"), entry.get("description") + return ( + isinstance(name, str) + and re.fullmatch(_NAME_PATTERN, name) is not None + and isinstance(description, str) + and 1 <= len(description) <= _MAX_DESCRIPTION + ) + + +def _clean_categories(raw: Any) -> list[dict[str, str]] | None: + """`raw` as a clean category list, or None when it is not a valid one. + + All or nothing: 1-32 entries, every name `^[a-z][a-z0-9_]{0,63}$` and + unique, every description 1-500 chars. Anything else means the defaults — + the same rule the MCP server and the TypeScript SDK apply. + """ + if not isinstance(raw, list) or not 1 <= len(raw) <= _MAX_CATEGORIES: + return None + out: list[dict[str, str]] = [] + seen: set[str] = set() + for entry in raw: + if not _valid_category(entry) or entry["name"] in seen: + return None # one bad entry invalidates the list: defaults, as every reader does + seen.add(entry["name"]) + out.append({"name": entry["name"], "description": entry["description"]}) + return out + + +def load_settings() -> dict[str, Any]: + """The effective settings: `{"enabled", "categories", "guidance"}`. + + Read fresh on every call (the file is tiny, and the daemon rewrites it when + the org changes its categories). Missing or unparsable file: disabled, with + the default categories. File present but disabled: the default categories + and no guidance — the org's list only applies while the org has it on. + """ + result: dict[str, Any] = { + "enabled": False, + "categories": [dict(c) for c in DEFAULT_CATEGORIES], + "guidance": None, + } + try: + data = json.loads(settings_path().read_text(encoding="utf-8")) + except (OSError, ValueError): + return result + if not isinstance(data, dict) or data.get("enabled") is not True: + return result + result["enabled"] = True + categories = _clean_categories(data.get("categories")) + if categories: + result["categories"] = categories + guidance = data.get("guidance") + if isinstance(guidance, str) and guidance and len(guidance) <= _MAX_GUIDANCE: + result["guidance"] = guidance # over the limit: dropped, never cut mid-sentence + return result + + +# --------------------------------------------------------------------------- +# The spec +# --------------------------------------------------------------------------- + +def describe(categories: Any, guidance: str | None = None) -> str: + """The tool description. Identical text in every FailproofAI implementation.""" + lines = [_PREAMBLE, "", "Categories:"] + lines.extend(f"- {c['name']}: {c['description']}" for c in categories) + text = "\n".join(lines) + if guidance: + text += "\n\n" + guidance + return text + + +def _input_schema(names: list[str]) -> dict[str, Any]: + return { + "type": "object", + "properties": { + "category": {"type": "string", "enum": names}, + "detail": {"type": "string", "description": _DETAIL_DESCRIPTION}, + }, + "required": ["category", "detail"], + "additionalProperties": False, + } + + +def self_report_spec( + *, + categories: list[dict[str, str]] | None = None, + guidance: str | None = None, +) -> dict[str, Any]: + """`{"name", "description", "input_schema"}` for the report tool. + + Built from `self-report.json`, or the defaults. Pass `categories` (and + optionally `guidance`) to override both explicitly; an invalid list raises + `ValueError` rather than shipping a tool the model cannot call correctly. + """ + if categories is None: + settings = load_settings() + cats = settings["categories"] + if guidance is None: + guidance = settings["guidance"] + else: + cats = _clean_categories(categories) + if cats is None: + raise ValueError( + "categories must be a non-empty list (at most 32) of " + '{"name": <^[a-z][a-z0-9_]{0,63}$>, "description": <1-500 chars>} with unique names' + ) + if guidance is not None and not isinstance(guidance, str): + raise TypeError(f"guidance must be a str or None, got {type(guidance).__name__}") + return { + "name": TOOL_NAME, + "description": describe(cats, guidance), + "input_schema": _input_schema([c["name"] for c in cats]), + } + + +def openai_tool(**overrides: Any) -> dict[str, Any]: + """The tool for OpenAI Chat Completions `tools=[...]`.""" + spec = self_report_spec(**overrides) + return { + "type": "function", + "function": { + "name": spec["name"], + "description": spec["description"], + "parameters": spec["input_schema"], + }, + } + + +def openai_responses_tool(**overrides: Any) -> dict[str, Any]: + """The tool for the OpenAI Responses API `tools=[...]` (flat function shape). + + `strict: True`, as the TypeScript SDK's `openaiResponsesTool()`: the schema + already meets strict mode (every property required, no extra properties). + """ + spec = self_report_spec(**overrides) + return { + "type": "function", + "name": spec["name"], + "description": spec["description"], + "parameters": spec["input_schema"], + "strict": True, + } + + +def anthropic_tool(**overrides: Any) -> dict[str, Any]: + """The tool for the Anthropic Messages API `tools=[...]`.""" + return copy.deepcopy(self_report_spec(**overrides)) + + +# --------------------------------------------------------------------------- +# Recording +# --------------------------------------------------------------------------- + +def self_report(category: str, detail: str | None = "", **fields: Any) -> None: + """Record a `self_report` event in the current session and agent scope. + + Same writer as every `event.*` method. `session_id=` / `agent_id=` may be + passed; otherwise the open `tool_use` for this call, then the enclosing + `failproofai_sdk.session()` / `agent()` scope, and with nothing bound the + report is filed under `"unattributed"` (one warning) rather than raising. + The event carries `source: "sdk"`. + """ + _runtime.event.self_report(category, detail, **fields) + + +def is_self_report_tool(name: Any, server: Any = None) -> bool: + """True for the report tool under any of its names. + + Use it to hide the call from your UI or transcript: `failproofai_report` + (this SDK), and the MCP tool as agents spell it + (`mcp__failproofai_local__report`, `mcp_failproofai_local_report`, + `failproofai_local__report`, ...). `server` is for + hosts that name an MCP tool and its server separately (Cursor's + `tool_name` + `mcp_server_name`): a bare `report` matches only when the + server is `failproofai_local`. + """ + if not isinstance(name, str): + return False + lower = name.strip().lower() + if lower in _TOOL_NAMES: + return True + return ( + isinstance(server, str) + and server.strip().lower() == "failproofai_local" + and lower in ("report", "mcp:report") + ) + + +def _coerce_text(value: Any) -> str: + if value is None: + return "" + return value if isinstance(value, str) else str(value) + + +# Other names a model uses for an argument when it calls the tool without +# loading its schema (seen live: `summary` and `sentence` for `detail`). The +# first non-empty one is used when the real argument is missing or empty; +# unknown keys are ignored. The same list as the CLI and the daemon: +# test-fixtures/self-report/arg-aliases.json. +ARG_ALIASES: dict[str, tuple[str, ...]] = { + "category": ("type", "kind"), + "detail": ("summary", "sentence", "message", "description", "reason", "text", "details"), +} + + +# Keyword rules for a category the model did not name (or named wrongly), in +# order: the first rule whose target is on the active list and whose keyword +# appears in the lowercased `category + " " + detail` wins. The same rules as +# the CLI and the daemon: test-fixtures/self-report/category-inference.json. +CATEGORY_RULES: tuple[tuple[str, tuple[str, ...]], ...] = ( + ( + "invalid_tool_or_credential", + ("token", "api key", "apikey", "api_key", "credential", "unauthorized", "unauthenticated", + "forbidden", "401", "403", "expired", "revoked", "auth", "password", "secret"), + ), + ("looping", ("loop", "looping", "circular", "in circles", "repeating the same")), + ( + "repeated_tool_failure", + ("keeps failing", "keep failing", "repeatedly", "several attempts", "multiple attempts", + "retried", "retries", "again and again"), + ), + ( + "missing_context", + ("missing", "not found", "no information", "not provided", "cannot find", "can't find", + "need more information", "unclear"), + ), + ( + "cannot_do_request", + ("cannot", "can't", "unable", "not possible", "impossible", "not supported", "unsupported", + "not allowed"), + ), +) + +#: The category a report falls back to when nothing matched, if it is listed. +FALLBACK_CATEGORY = "task_failure" + +def _has_keyword(text: str, keyword: str) -> bool: + pattern = r"(? tuple[str, bool]: + """`(category, inferred)`: the category a model's report is recorded under. + + `raw` when it is on `names`; else the listed name it normalises to + (lowercase, trimmed, runs of spaces and hyphens as `_`); else the first + `CATEGORY_RULES` rule that matches the category and detail and targets a + listed name; else `task_failure` when listed, else the first listed name. + `inferred` is True whenever the result is not `raw` itself. An empty list + keeps `raw`. + """ + if not names or raw in names: + return raw, False + normalised = re.sub(r"[\s\-]+", "_", raw.strip().lower()) + if normalised in names: + return normalised, True + text = f"{raw} {detail}".lower() + for target, keywords in CATEGORY_RULES: + if target in names and any(_has_keyword(text, k) for k in keywords): + return target, True + return (FALLBACK_CATEGORY if FALLBACK_CATEGORY in names else names[0]), True + + +def _category_names(categories: Any) -> list[str]: + """The names of `categories` (a list of `{"name", ...}` or of names), else + the current settings' list.""" + if categories is None: + categories = load_settings()["categories"] + out: list[str] = [] + for c in categories: + name = c.get("name") if isinstance(c, dict) else c + if isinstance(name, str): + out.append(name) + return out + + +def _first_text(arguments: dict, key: str) -> str: + for name in (key, *ARG_ALIASES[key]): + text = _coerce_text(arguments.get(name)) + if text: + return text + return "" + + +def parse_arguments(arguments: Any) -> tuple[str, str]: + """`(category, detail)` from a model's tool-call arguments. Never raises. + + Accepts a dict or a JSON string (OpenAI sends a string, Anthropic a dict). + A string that is not a JSON object is kept whole as the detail, so a model + that fumbled the arguments still leaves a readable report. A missing or + empty argument falls back to its first non-empty alias (`ARG_ALIASES`). + """ + if isinstance(arguments, (str, bytes, bytearray)): + text = arguments.decode("utf-8", "replace") if not isinstance(arguments, str) else arguments + if not text.strip(): + arguments = {} + else: + try: + arguments = json.loads(text) + except ValueError: + return "", cut_report_detail(text) + if arguments is None: + arguments = {} + if not isinstance(arguments, dict): + return "", cut_report_detail(_coerce_text(arguments)) + return _first_text(arguments, "category"), _first_text(arguments, "detail") + + +_warned_unbound = False + + +def record_tool_call(arguments: Any, *, categories: Any = None, **fields: Any) -> str: + """Record a report from a model's tool call and return `"Recorded."`. + + The category is resolved against `categories` (the list the tool was + built with; default: the current settings' list) by `resolve_category`, so + a call that left it out, misspelt it or named one not on the list is still + filed under a listed one. + + Never raises into the agent loop. A report that cannot be recorded (a + writer fault, an invalid explicit id) is logged (once at WARNING, then at + DEBUG) and the model still gets `Recorded.`: the tool's contract is that it + changes nothing, and a raise here would turn a stuck agent into a crashed one. + """ + global _warned_unbound + category, detail = parse_arguments(arguments) + try: + category, _ = resolve_category(category, detail, _category_names(categories)) + self_report(category, detail, **fields) + except Exception as exc: # noqa: BLE001 - see docstring + level = logging.DEBUG if _warned_unbound else logging.WARNING + _warned_unbound = True + logger.log( + level, + "failproofai_sdk: a self report was not recorded (%s).", + exc, + ) + return RESULT + + +def handle_tool_call( + name: str, + arguments: Any = None, + *, + session_id: str | None = None, + agent_id: str | None = None, + tool_call_id: str | None = None, + categories: list[dict[str, str]] | None = None, +) -> str: + """Handle a report tool call from a raw model API. Returns `"Recorded."`. + + for call in message.tool_calls: + if fp.is_self_report_tool(call.function.name): + out = fp.handle_tool_call(call.function.name, call.function.arguments, + tool_call_id=call.id) + + `arguments` may be a dict or a JSON string. Pass `categories` when the tool + was built with its own list (`openai_tool(categories=...)`), so the + category is resolved against that list rather than the settings'. + Raises `ValueError` only when + `name` is not the report tool, so a dispatcher bug is loud; recording itself + never raises (see `record_tool_call`). + """ + if not is_self_report_tool(name): + raise ValueError( + f"{name!r} is not the FailproofAI report tool; check is_self_report_tool(name) first" + ) + fields: dict[str, Any] = {} + if session_id is not None: + fields["session_id"] = session_id + if agent_id is not None: + fields["agent_id"] = agent_id + if tool_call_id: + fields["tool_call_id"] = str(tool_call_id) + return record_tool_call(arguments, categories=categories, **fields) + + +# --------------------------------------------------------------------------- +# Shared by the framework tools in `integrations/.py` +# --------------------------------------------------------------------------- + +def record_framework_call( + category: Any, + detail: Any, + *, + identity: Any = None, + session_id: str | None = None, + agent_id: str | None = None, + tool_call_id: Any = None, + fields: dict | None = None, + extra_args: dict | None = None, + categories: Any = None, +) -> str: + """Record one framework tool call and return `"Recorded."`. Never raises. + + `categories`: the names (or entries) the tool was built with, which the + category is resolved against (`resolve_category`). + + Identity, most explicit first: the `session_id` / `agent_id` the developer + gave the tool factory; then `identity`, which the adapter resolved from the + framework's own run tree (so the report lands on the agent that made the + call even when no `failproofai_sdk.session()` is open); then what + `event.self_report` resolves itself (the open `tool_use` for the call, the + ambient scope, else `"unattributed"`). + """ + out: dict[str, Any] = dict(fields or {}) + if session_id is None and identity is not None and getattr(identity, "session_id", None): + session_id = identity.session_id + if agent_id is None: + agent_id = getattr(identity, "agent_id", None) + if session_id is not None: + out["session_id"] = session_id + if agent_id is not None: + out["agent_id"] = agent_id + if tool_call_id: + out["tool_call_id"] = str(tool_call_id) + # `extra_args`: any other arguments the framework passed through raw, so + # an aliased detail (`summary`, `sentence`, ...) is not lost. + arguments = {k: v for k, v in (extra_args or {}).items() if isinstance(k, str)} + arguments.update(category=category, detail=detail) + return record_tool_call(arguments, categories=categories, **out) + + +def framework_signature(names: list[str]): + """`(category: Literal[...], detail: str)` annotations for frameworks that + derive a tool's JSON schema from a Python signature. Stdlib only: the enum + comes from `typing.Literal`, which every framework's pydantic understands.""" + from typing import Literal + + return {"category": Literal[tuple(names)], "detail": str, "return": str} # type: ignore[valid-type] diff --git a/sdk/python/failproofai_sdk/integrations/crewai.py b/sdk/python/failproofai_sdk/integrations/crewai.py index dadd0bced..ac76c7772 100644 --- a/sdk/python/failproofai_sdk/integrations/crewai.py +++ b/sdk/python/failproofai_sdk/integrations/crewai.py @@ -1667,3 +1667,159 @@ def _count(usage, keys): adapter = _CrewAIAdapter() + + +# --------------------------------------------------------------------------- +# Self Reports: the ready-made report tool +# --------------------------------------------------------------------------- + +def _report_identity(): + """The identity of the CrewAI agent running this tool, if recorded. + + CrewAI keeps its own event-scope stack on a contextvar. Inside a tool's + `_run` the top is the tool usage (a leaf, not a node), so walk down to the + nearest scope this adapter has as a node: the agent execution that called + the tool. The stack itself is private to crewai, so a missing one falls + back to the public `get_current_parent_id()` and the adapter's own + root-fallback. + """ + tracker = adapter._tracker + if tracker is None: + return None + from crewai.events import event_context + + key = None + stack = getattr(event_context, "_event_id_stack", None) + if stack is not None: + with adapter._lock: + for entry in reversed(stack.get()): + event_id = entry[0] if isinstance(entry, tuple) else entry + if event_id in adapter._nodes: + key = event_id + break + if key is None: + key = adapter._parent_key(event_context.get_current_parent_id()) + if key is None: + return None + return tracker.identity(None, key, warn=False) + + +def _report_call_id() -> "str | None": + """The id of the CrewAI tool usage running this tool, or None. + + CrewAI pushes a `tool_usage_started` scope (its event's `event_id`) + synchronously when it emits the event, before the tool runs; that id is + the `tool_call_id` this adapter records the `tool_use` under. It is read + here because the adapter's own handler runs on CrewAI's event bus and may + record that `tool_use` after the report. + """ + if adapter._tracker is None: + # Not instrumented: no `tool_use` carries this id, so it joins nothing. + return None + from crewai.events import event_context + + stack = getattr(event_context, "_event_id_stack", None) + if stack is None: + return None + for entry in reversed(stack.get()): + if isinstance(entry, tuple) and len(entry) == 2 and entry[1] == "tool_usage_started": + return entry[0] if isinstance(entry[0], str) and entry[0] else None + return None + + +def _never_cache(_args=None, _result=None) -> bool: + """The report tool's `cache_function`: every call must run and record.""" + return False + + +_context_tool_classes: dict = {} + + +def _context_preserving(structured): + """`structured` with an `ainvoke` that runs the tool in the caller's context. + + CrewAI before 1.15 runs a sync tool's function through `run_in_executor` + without copying the context, so the report tool's `_run` saw an empty + CrewAI event stack in a fresh worker thread and could take another, + newer crew's identity. `asyncio.to_thread` copies the context (what 1.15+ + does itself). Same validation and usage counting: it calls the tool's own + sync `invoke`. Left unchanged if the instance cannot take the subclass. + """ + import asyncio + + base = type(structured) + cls = _context_tool_classes.get(base) + if cls is None: + async def ainvoke(self, input, config=None, **kwargs): # noqa: A002 - CrewAI's name + return await asyncio.to_thread(self.invoke, input, config, **kwargs) + + cls = type(base.__name__, (base,), {"__module__": __name__, "ainvoke": ainvoke}) + _context_tool_classes[base] = cls + try: + object.__setattr__(structured, "__class__", cls) + except TypeError: + logger.debug("failproofai_sdk: could not wrap CrewAI's structured tool", exc_info=True) + return structured + + +def self_report_tool( + *, + session_id: "str | None" = None, + agent_id: "str | None" = None, + categories: "list[dict] | None" = None, + guidance: "str | None" = None, +): + """The FailproofAI report tool as a CrewAI `BaseTool` instance. + + from failproofai_sdk.integrations.crewai import self_report_tool + Agent(role=..., goal=..., tools=[*my_tools, self_report_tool()]) + + The schema and description come from `self-report.json` (or the defaults), + read when the tool is built. Identity: the factory's `session_id` / + `agent_id`, else the crew run this adapter is recording (when instrumented), + else the ambient scope, else "unattributed". Always returns `"Recorded."`. + Never cached, and run in the caller's context on CrewAI's async path. + """ + from crewai.tools import BaseTool + + from failproofai_sdk import _self_report + + spec = _self_report.self_report_spec(categories=categories, guidance=guidance) + names = list(spec["input_schema"]["properties"]["category"]["enum"]) + extra = framework_fields(NAME, DIST) + + def _run(self, category, detail) -> str: + identity = None + tool_call_id = None + try: + identity = _report_identity() + tool_call_id = _report_call_id() + except Exception: # noqa: BLE001 - identity is best-effort; the report is not + logger.debug("failproofai_sdk: could not resolve the report's crew run", exc_info=True) + return _self_report.record_framework_call( + category, detail, identity=identity, session_id=session_id, + agent_id=agent_id, tool_call_id=tool_call_id, fields=extra, + categories=names, + ) + + _run.__annotations__ = _self_report.framework_signature(names) + + def to_structured_tool(self): + return _context_preserving(BaseTool.to_structured_tool(self)) + + tool_cls = type( + "FailproofAIReportTool", + (BaseTool,), + { + "__module__": __name__, + "__doc__": "Report to FailproofAI that the agent is stuck.", + "__annotations__": {"name": str, "description": str}, + "name": spec["name"], + "description": spec["description"], + "_run": _run, + "to_structured_tool": to_structured_tool, + }, + ) + # Never cached: CrewAI's cache would answer a repeated report (same + # arguments) with the stored "Recorded." and the report would not be made. + return tool_cls(cache_function=_never_cache) diff --git a/sdk/python/failproofai_sdk/integrations/langchain.py b/sdk/python/failproofai_sdk/integrations/langchain.py index f998a3231..778d697e4 100644 --- a/sdk/python/failproofai_sdk/integrations/langchain.py +++ b/sdk/python/failproofai_sdk/integrations/langchain.py @@ -2149,3 +2149,117 @@ def _close_everything() -> None: adapter = _Adapter() + + +# --------------------------------------------------------------------------- +# Self Reports: the ready-made report tool +# --------------------------------------------------------------------------- + +def _report_identity(callbacks: Any) -> "tuple[Any, str | None]": + """(identity, tool_call_id) for the tool run `callbacks` hangs off. + + `StructuredTool` hands a func that declares `callbacks` the tool run's child + manager, whose `parent_run_id` IS the tool run. While this adapter is + installed that run is in `_STATE`, so the report resolves to the agent the + model belongs to even with no `failproofai_sdk.session()` open. + """ + run_id = getattr(callbacks, "parent_run_id", None) + if run_id is None or not _STATE.enabled: + return None, None + key = str(run_id) + with _STATE.lock: + info = _STATE.runs.get(key) + tool_call_id = info.tool_call_id if info is not None else None + return _STATE.tracker.identity(None, key, warn=False), tool_call_id + + +#: The model's tool-call id of the report call running in this context. LangChain +#: hands `BaseTool.run`/`arun` the id of a `ToolCall` input, but a tool with a +#: JSON-schema `args_schema` cannot have it injected into its function, so the +#: report tool's own `run`/`arun` put it here for the function to read. +_REPORT_TOOL_CALL_ID: "contextvars.ContextVar[str | None]" = contextvars.ContextVar( + "failproofai_langchain_report_tool_call_id", default=None +) + +_REPORT_TOOL_CLASS: Any = None + + +def _report_tool_class() -> Any: + """`StructuredTool` with `run`/`arun` that keep the call's `tool_call_id`.""" + global _REPORT_TOOL_CLASS + if _REPORT_TOOL_CLASS is not None: + return _REPORT_TOOL_CLASS + from langchain_core.tools import StructuredTool + + class _SelfReportTool(StructuredTool): + def run(self, tool_input: Any, *args: Any, tool_call_id: "str | None" = None, **kwargs: Any) -> Any: + token = _REPORT_TOOL_CALL_ID.set(tool_call_id) + try: + return super().run(tool_input, *args, tool_call_id=tool_call_id, **kwargs) + finally: + _REPORT_TOOL_CALL_ID.reset(token) + + async def arun(self, tool_input: Any, *args: Any, tool_call_id: "str | None" = None, **kwargs: Any) -> Any: + token = _REPORT_TOOL_CALL_ID.set(tool_call_id) + try: + return await super().arun(tool_input, *args, tool_call_id=tool_call_id, **kwargs) + finally: + _REPORT_TOOL_CALL_ID.reset(token) + + _REPORT_TOOL_CLASS = _SelfReportTool + return _REPORT_TOOL_CLASS + + +def self_report_tool( + *, + session_id: str | None = None, + agent_id: str | None = None, + categories: "list[dict] | None" = None, + guidance: str | None = None, +): + """The FailproofAI report tool as a LangChain `StructuredTool`. + + from failproofai_sdk.integrations.langchain import self_report_tool + agent = create_agent(model, tools=[*my_tools, self_report_tool()]) + + Works in LangGraph's `ToolNode` and any tool-calling chain. The schema and + description come from `self-report.json` (or the defaults), read when the + tool is built. Identity: the factory's `session_id`/`agent_id`, else the run + this adapter is recording (when instrumented), else the ambient scope, else "unattributed". + `tool_call_id` is the model's call id: from the instrumented run, else the + `ToolCall` LangChain invoked the tool with (as `ToolNode` and + `create_agent` do), with or without instrumentation. + Always returns `"Recorded."`. + """ + from failproofai_sdk import _self_report + + spec = _self_report.self_report_spec(categories=categories, guidance=guidance) + extra = framework_fields(NAME, DIST) + + def _record(category: Any = "", detail: Any = "", callbacks: Any = None) -> str: + identity, tool_call_id = None, None + try: + identity, tool_call_id = _report_identity(callbacks) + except Exception: # noqa: BLE001 - identity is best-effort; the report is not + logger.debug("failproofai_sdk: could not resolve the report's run", exc_info=True) + if tool_call_id is None: + tool_call_id = _REPORT_TOOL_CALL_ID.get() + return _self_report.record_framework_call( + category, detail, identity=identity, session_id=session_id, + agent_id=agent_id, tool_call_id=tool_call_id, fields=extra, + categories=spec["input_schema"]["properties"]["category"]["enum"], + ) + + def report(category: str = "", detail: str = "", callbacks: Any = None) -> str: + return _record(category, detail, callbacks) + + async def areport(category: str = "", detail: str = "", callbacks: Any = None) -> str: + return _record(category, detail, callbacks) + + return _report_tool_class().from_function( + func=report, + coroutine=areport, + name=spec["name"], + description=spec["description"], + args_schema=spec["input_schema"], + ) diff --git a/sdk/python/failproofai_sdk/integrations/llama_index.py b/sdk/python/failproofai_sdk/integrations/llama_index.py index 827015b82..0b81f7c45 100644 --- a/sdk/python/failproofai_sdk/integrations/llama_index.py +++ b/sdk/python/failproofai_sdk/integrations/llama_index.py @@ -1586,3 +1586,82 @@ def uninstall(self) -> None: install: Callable[..., None] = adapter.install uninstall: Callable[..., None] = adapter.uninstall + + +# --------------------------------------------------------------------------- +# Self Reports: the ready-made report tool +# --------------------------------------------------------------------------- + +def _active_span_id() -> "str | None": + try: + from llama_index_instrumentation.span import active_span_id + except ImportError: # older cores carry it in-tree + from llama_index.core.instrumentation.span import active_span_id + return active_span_id.get() + + +def _report_identity(): + """The identity of the LlamaIndex agent whose tool span is active, if recorded.""" + state = adapter.state + if state is None: + return None + span_id = _active_span_id() + if span_id is None: + return None + with state._lock: + run = state._run_of(span_id) + key = (run.sub_key or run.span_id) if run is not None else None + if key is not None: + return state.tracker.identity(key, warn=False) + return state.tracker.identity(None, span_id, warn=False) + + +def self_report_tool( + *, + session_id: "str | None" = None, + agent_id: "str | None" = None, + categories: "list[dict] | None" = None, + guidance: "str | None" = None, +): + """The FailproofAI report tool as a LlamaIndex `FunctionTool`. + + from failproofai_sdk.integrations.llama_index import self_report_tool + agent = FunctionAgent(tools=[*my_tools, self_report_tool()], llm=llm) + + The schema and description come from `self-report.json` (or the defaults), + read when the tool is built. Identity: the factory's `session_id` / + `agent_id`, else the agent run this adapter is recording (when + instrumented), else the ambient scope, else "unattributed". Always returns `"Recorded."`. + """ + from llama_index.core.tools import FunctionTool + + from failproofai_sdk import _self_report + + spec = _self_report.self_report_spec(categories=categories, guidance=guidance) + names = list(spec["input_schema"]["properties"]["category"]["enum"]) + extra = _core.framework_fields(FRAMEWORK, DIST) + + def failproofai_report(category, detail) -> str: + identity = None + try: + identity = _report_identity() + except Exception: # noqa: BLE001 - identity is best-effort; the report is not + logger.debug("failproofai_sdk: could not resolve the report's agent run", exc_info=True) + return _self_report.record_framework_call( + category, detail, identity=identity, session_id=session_id, + agent_id=agent_id, fields=extra, categories=names, + ) + + failproofai_report.__annotations__ = _self_report.framework_signature(names) + + async def afailproofai_report(category, detail) -> str: + return failproofai_report(category, detail) + + afailproofai_report.__annotations__ = _self_report.framework_signature(names) + + return FunctionTool.from_defaults( + fn=failproofai_report, + async_fn=afailproofai_report, + name=spec["name"], + description=spec["description"], + ) diff --git a/sdk/python/failproofai_sdk/integrations/pydantic_ai.py b/sdk/python/failproofai_sdk/integrations/pydantic_ai.py index e62d5d67a..cb4886342 100644 --- a/sdk/python/failproofai_sdk/integrations/pydantic_ai.py +++ b/sdk/python/failproofai_sdk/integrations/pydantic_ai.py @@ -62,7 +62,9 @@ built before `uninstrument()` stops recording rather than recording into a half-dismantled adapter. By the same token, agents constructed *before* `instrument()` are not instrumented; construct them after, or pass -`capabilities=[FailproofAI()]` yourself. +`capabilities=[FailproofAI()]` yourself. A capability you pass yourself is +yours: it records whether or not `instrument()` ran, and `uninstrument()` does +not stop it. What is deliberately not captured --------------------------------- @@ -132,7 +134,9 @@ # Flipped by install()/uninstall(). Agents built while instrumented keep the # capability instance, so this flag — not the patch — is what actually stops the -# recording. Read on every hook, written only under the registry lock. +# recording of the capability install() injected. A `FailproofAI()` the user +# passed in `capabilities=` records regardless. Read on every hook, written +# only under the registry lock. _enabled = False _capability: "FailproofAI | None" = None _patcher = _core.Patcher() @@ -380,10 +384,15 @@ def _is_base_model(value: Any) -> bool: # --------------------------------------------------------------------------- class _RunState: - __slots__ = ("key", "scope", "spans", "closed", "reported_error") + __slots__ = ("key", "scope", "spans", "closed", "reported_error", "installed") - def __init__(self, key: Any) -> None: + def __init__(self, key: Any, installed: bool = False) -> None: self.key = key + # Whether the capability running it was injected by `instrument()`. + # `uninstrument()` tears down only those: a `FailproofAI()` the + # developer attached by hand records whether or not instrument() ran, + # and its runs finish on their own. + self.installed = installed self.scope: Any = None # Leaf spans this run has opened and not yet closed, newest last. This # exists because a leaf can outlive its own run — see `_close_spans`. @@ -549,17 +558,22 @@ def _close_spans(state: _RunState, exc: "BaseException | None") -> None: ) -def _close_open_runs() -> None: - """Close every run this adapter still has open, newest first. +def _close_open_runs() -> bool: + """Close every run the installed capability still has open, newest first. Teardown, not a hot path: `uninstall()` is the only caller. Each run's leaves close before its `agent_end`, and `_claim_run` makes the run's own - `wrap_run` frame a no-op when it eventually unwinds. + `wrap_run` frame a no-op when it eventually unwinds. A run of a manually + attached capability is left open to finish normally. + + Returns whether any such manual run is still open. """ with _runs_lock: states = list(_open_runs.values()) for state in reversed(states): - _core.call_safely(_close_run, (state,), {}, f"{__name__}.uninstall") + if state.installed: + _core.call_safely(_close_run, (state,), {}, f"{__name__}.uninstall") + return any(not state.installed for state in states) def _close_run(state: _RunState) -> None: @@ -604,6 +618,7 @@ def __init__( capture_content: bool = True, session_id: str | None = None, id: str | None = None, + self_report: bool = False, ) -> None: # `AbstractCapability` is a `@dataclass(init=False)`, so it contributes # class-level defaults (`id`, `defer_loading`, …) and no `__init__` to @@ -611,6 +626,27 @@ def __init__( self.capture_content = capture_content self.session_id = session_id self.id = id + self.self_report = self_report + # False for one you construct yourself: it records whether or not + # `instrument()` ran. `install()` sets True on the one it injects, which + # then records only while instrumented (so `uninstrument()` stops it). + self._installed = False + + def _recording(self) -> bool: + return _enabled or not getattr(self, "_installed", False) + + def get_toolset(self): + """The FailproofAI report tool, when `self_report=True` was asked for. + + Opt-in, never default: adding a tool changes what the model sees, and + this capability is otherwise pure observation. Built per agent, so the + categories are the ones in `self-report.json` when the agent is built. + """ + if not self.self_report: + return None + from pydantic_ai.toolsets import FunctionToolset + + return FunctionToolset([self_report_tool()]) def get_ordering(self) -> CapabilityOrdering: """Outermost, so our spans bracket every other capability's work. @@ -623,7 +659,7 @@ def get_ordering(self) -> CapabilityOrdering: # -- run -------------------------------------------------------------- async def wrap_run(self, ctx, *, handler): - if not _enabled: + if not self._recording(): return await handler() state = self._begin_run(ctx) try: @@ -660,7 +696,7 @@ def _begin_run(self, ctx) -> _RunState: metadata=getattr(ctx, "metadata", None), ), ) - state = _RunState(key) + state = _RunState(key, installed=bool(getattr(self, "_installed", False))) _register_run(state) try: scope = failproofai_sdk.session(identity.session_id, agent_id=identity.agent_id) @@ -730,7 +766,7 @@ def _end_run(self, state: "_RunState | None", result: Any, exc: "BaseException | # -- model ------------------------------------------------------------ async def wrap_model_request(self, ctx, *, request_context, handler): - if not _enabled: + if not self._recording(): return await handler(request_context) state = self._begin_model(ctx, request_context) try: @@ -834,7 +870,7 @@ def _end_model(self, ctx, state: "_SpanState | None", response: Any, exc: "BaseE # -- tools ------------------------------------------------------------ async def wrap_tool_execute(self, ctx, *, call, tool_def, args, handler): - if not _enabled: + if not self._recording(): return await handler(args) state = self._begin_tool(ctx, call, tool_def, args) try: @@ -951,7 +987,9 @@ def install(self, **options: Any) -> None: _capability = FailproofAI( capture_content=bool(options.get("capture_content", True)), session_id=options.get("session_id"), + self_report=bool(options.get("self_report", False)), ) + _capability._installed = True _patcher.patch(Agent, "__init__", _wrap_init(Agent.__init__)) _enabled = True @@ -967,7 +1005,13 @@ def uninstall(self) -> None: # `wrap_run` frame does not emit a second `agent_end` when it finally # unwinds. `close_open_agents()` stays as the backstop for a key that # reached the tracker without reaching `_open_runs`. - _close_open_runs() + # + # A manually attached `FailproofAI()` keeps recording after + # `uninstrument()`, and its runs share this tracker: while one is in + # flight the tracker is left as it is, so it can still emit its leaves + # and its own `agent_end`. + if _close_open_runs(): + return _tracker.close_open_agents() _tracker.reset() @@ -975,3 +1019,53 @@ def uninstall(self) -> None: adapter = _Adapter() install = adapter.install uninstall = adapter.uninstall + + +# --------------------------------------------------------------------------- +# Self Reports: the ready-made report tool +# --------------------------------------------------------------------------- + +def self_report_tool( + *, + session_id: str | None = None, + agent_id: str | None = None, + categories: "list[dict] | None" = None, + guidance: str | None = None, +): + """The FailproofAI report tool as a Pydantic AI `Tool`. + + from failproofai_sdk.integrations.pydantic_ai import self_report_tool + agent = Agent(model, tools=[self_report_tool()]) + + or let the capability add it: `capabilities=[FailproofAI(self_report=True)]` + / `failproofai_sdk.instrument("pydantic_ai", self_report=True)`. + + The JSON schema is exactly `self_report_spec()["input_schema"]` (built from + `self-report.json`, or the defaults). The call carries the model's + `tool_call_id`. Identity: the factory's `session_id`/`agent_id`, else the + run a `FailproofAI` capability on the agent is recording (it binds the run's + scope; `FailproofAI(self_report=True)` alone does, with or without + `instrument()`), else the ambient scope, else "unattributed". Always + returns `"Recorded."`. + """ + from pydantic_ai import Tool + + from failproofai_sdk import _self_report + + spec = _self_report.self_report_spec(categories=categories, guidance=guidance) + extra = framework_fields(NAME, DIST) + + def failproofai_report(ctx: Any, category: Any = "", detail: Any = "", **raw: Any) -> str: + return _self_report.record_framework_call( + category, detail, session_id=session_id, agent_id=agent_id, + tool_call_id=getattr(ctx, "tool_call_id", None), fields=extra, + extra_args=raw, categories=spec["input_schema"]["properties"]["category"]["enum"], + ) + + return Tool.from_schema( + failproofai_report, + name=spec["name"], + description=spec["description"], + json_schema=spec["input_schema"], + takes_ctx=True, + ) diff --git a/sdk/python/skill/SKILL.md b/sdk/python/skill/SKILL.md index 50683b35e..eb496b19d 100644 --- a/sdk/python/skill/SKILL.md +++ b/sdk/python/skill/SKILL.md @@ -15,7 +15,7 @@ description: |- # Failproof AI SDK — Python and TypeScript Two packages, one pipe: `failproofai-sdk` (Python, imported as `failproofai_sdk`) -and `@failproofai/sdk` (TypeScript/JavaScript). They write the same 15 events in +and `@failproofai/sdk` (TypeScript/JavaScript). They write the same 16 events in the same wire format into the same spool directory. Everything in this file is language-neutral unless it says otherwise, and code blocks are Python. **For a TypeScript or JavaScript agent, read `references/typescript.md` alongside @@ -40,7 +40,7 @@ your agent calls failproofai_sdk.event.* about it: everything up to the `.jsonl` is yours to get right and yours to verify, and it is verifiable on a laptop with no server, no API key, and no network. -The API is small — 15 event methods, all keyword-only. The hard parts are +The API is small — 16 event methods, all keyword-only except `self_report`'s two leading arguments. The hard parts are **deciding where to call them** and **knowing which silences are bugs**, because this SDK does not raise when you get it wrong. Sections 1-3 are the plan, 4 is the code, 5-6 are the proof, 7 is scoring the runs. @@ -137,6 +137,7 @@ doesn't apply; there is no requirement to emit every type. | your `except` blocks | `error` | the Errors surface | | a policy/guard/middleware layer | `hook_triggered` / `hook_completed` | hook behaviour | | an approval gate or human handoff | `human_wait` / `human_input`, `human_pause`, `human_interrupt` | where runs sit waiting on people | +| the agent's tool list | the report tool (`self_report_tool()` / `openai_tool()`), which emits `self_report` | the agent telling you it is stuck, and why (Self Reports) | | a run that suspends and resumes — waiting for a human, throttled, user-paused | `agent_pause` / `agent_resume` | a real "paused" state: the agent isn't ended, the resume isn't a new agent, and wait time is excluded from active work | If the codebase has one tool dispatcher and one LLM wrapper, you have two edit @@ -155,7 +156,7 @@ recipe — `references/typescript.md` → *The contract, in TypeScript* and *Shu - **There IS an ambient session, and it is the ergonomic path.** `session()`, `agent()` and `tool_call()` bind identity on contextvars, so `session_id` and - `agent_id` are optional on all 15 event methods — omitted, they resolve from + `agent_id` are optional on all 16 event methods — omitted, they resolve from the enclosing scope. `current()` reads it; `propagate(fn)` carries it into a new thread, which contextvars do NOT do on their own. @@ -165,6 +166,16 @@ recipe — `references/typescript.md` → *The contract, in TypeScript* and *Shu Nothing bound and nothing passed raises `TypeError` naming the fix — never a silent emit, because ingest skips an event with no session and answers `200`. + The one exception is `self_report()`: a report is evidence, so it never + raises for a missing session. With none passed or bound, an unambiguous open + `tool_use` for the call gives it its session, with no warning: the one with its + `tool_call_id`, else the NEWEST open report-tool call. Newest, not only: two + report calls open in one session (parallel tool calls) resolve to the later + one, so pass `tool_call_id` whenever report calls can overlap. Open calls in + several sessions resolve to none. Only when no explicit session, + no such open call and no enclosing scope identifies one is it recorded under + `session_id="unattributed"` (one warning per process). The other 15 methods + raise. Two more shapes raise, for the same reason: diff --git a/sdk/python/skill/references/events.md b/sdk/python/skill/references/events.md index ffcdb5159..a66cc601b 100644 --- a/sdk/python/skill/references/events.md +++ b/sdk/python/skill/references/events.md @@ -1,6 +1,6 @@ # Event catalog -> TypeScript/JavaScript: the same 15 events on `failproofai.event`, camelCase +> TypeScript/JavaScript: the same 16 events on `failproofai.event`, camelCase > (`toolUse({ toolName, toolCallId })`) taking one options object; the file written > is identical. Name map in `typescript.md`. Code below is Python, and where it > says `ValueError` or `TypeError`, TypeScript throws `TypeError` or a plain @@ -9,7 +9,7 @@ Every method lives on `failproofai_sdk.event`, is **keyword-only**, and returns `None`. Nothing here blocks or does I/O — the call queues the event and returns. -`session_id` and `agent_id` are optional on all fifteen: omit them and they come +`session_id` and `agent_id` are optional on all sixteen: omit them and they come from the enclosing `failproofai_sdk.session()` / `failproofai_sdk.agent()` scope. Pass them and your value wins. Omit `session_id` with nothing bound and you get a `TypeError` naming the fix; `agent_id` falls back to `"main"` and never raises. See @@ -19,7 +19,7 @@ Emit only what fits the agent. There is no requirement to use every type, and no penalty for skipping one — except `agent_start`, without which the session does not exist at all. -## The 15 events +## The 16 events Columns: **Required** is beyond `session_id` + `agent_id`, which every event carries and which you rarely pass by hand. @@ -43,6 +43,7 @@ not written as `null`. | `human_input` | `input_id` | `response` | `duration_ms` auto-computed — how long the human took. | | `human_pause` | — | `reason`, `user_id` | | | `human_interrupt` | — | `reason`, `user_id`, `at_step` | | +| `self_report` | `category`, `detail` (positional) | `tool_call_id` | The agent says it is stuck. Never raises for a missing session (see *Self Reports*). Always carries `source: "sdk"` (passing `source` raises `ValueError`). Category recorded as given; `detail` cut to 2,000 chars. Usually the model triggers it through the report tool — see *Self Reports* below. | ## Rules that apply to every event @@ -76,9 +77,9 @@ the optional names are silent. `agent_id`, `type`, `environment` — passing any as a custom field. (`session_id` and `agent_id` are already named args, so Python raises `TypeError` first.) -**`duration_ms` is yours to pass on eleven of the fifteen.** It is computed for you +**`duration_ms` is yours to pass on twelve of the sixteen.** It is computed for you on `tool_result`, `hook_completed`, `human_input`, and `agent_resume`, and passing -it to *those four* raises `ValueError`. On the other eleven there is no guard: +it to *those four* raises `ValueError`. On the other twelve there is no guard: `agent_end(..., duration_ms=5)` is accepted and stored as an ordinary custom field. Don't. The one place you *should* pass it is **`model_response`**, where nothing computes @@ -241,3 +242,31 @@ The agent span stays open across the pause (it is not ended); `agent_resume` carries the paused `duration_ms` when both halves run in the same process, and paused time is reported separately from active work. Persist `pause_id` if the resume happens in a different process so it reuses the same value. + + +## Self Reports + +Give the model a tool to report it is stuck instead of emitting `self_report` +yourself. The tool answers `Recorded.` and changes nothing. + +```python +import failproofai_sdk + +# a framework agent — one factory per adapter module +from failproofai_sdk.integrations.langchain import self_report_tool +tools = [*my_tools, self_report_tool()] + +# a raw provider API +tools = [failproofai_sdk.openai_tool(), *my_tools] # anthropic_tool(), openai_responses_tool() +if failproofai_sdk.is_self_report_tool(name): + output = failproofai_sdk.handle_tool_call(name, arguments, tool_call_id=call_id) +``` + +Tool name `failproofai_report`; description and `category` enum from +`~/.failproofai/self-report.json`, else six defaults +(`failproofai_sdk.self_report_spec()` shows the result). The same factory exists +in `integrations.crewai`, `integrations.llama_index` and +`integrations.pydantic_ai` (also `FailproofAI(self_report=True)`). Tool helpers +never raise into the agent loop. Unlike every other event, `self_report` never +raises for a missing session: it uses the open `tool_use` for the call, then the +enclosing scope, then files the report under `"unattributed"` with one warning. diff --git a/sdk/python/skill/references/frameworks.md b/sdk/python/skill/references/frameworks.md index a1e243cf5..01c94e1fd 100644 --- a/sdk/python/skill/references/frameworks.md +++ b/sdk/python/skill/references/frameworks.md @@ -230,6 +230,24 @@ from failproofai_sdk.integrations.pydantic_ai import FailproofAI agent = Agent("openai:gpt-5", capabilities=[FailproofAI()]) ``` +## The report tool (Self Reports) + +Each adapter module also ships `self_report_tool()`, the FailproofAI report +tool in that framework's own tool type. Add it to the agent's tools; it does not +need `instrument()`, but with the adapter installed the report lands on the +agent that called it. + +| Framework | Import | Type | +|---|---|---| +| LangChain / LangGraph | `from failproofai_sdk.integrations.langchain import self_report_tool` | `StructuredTool` | +| CrewAI | `from failproofai_sdk.integrations.crewai import self_report_tool` | `BaseTool` | +| LlamaIndex | `from failproofai_sdk.integrations.llama_index import self_report_tool` | `FunctionTool` | +| Pydantic AI | `from failproofai_sdk.integrations.pydantic_ai import self_report_tool` | `Tool` | + +Pydantic AI can add it for you, opt in only: `FailproofAI(self_report=True)` or +`instrument("pydantic_ai", self_report=True)`. Every factory takes +`session_id=`, `agent_id=`, `categories=` and `guidance=`. + ## Mixing adapters with hand-written events They compose, and this is the supported way to add detail an adapter cannot know diff --git a/sdk/python/skill/references/integration.md b/sdk/python/skill/references/integration.md index 9093e0803..5a3f04d80 100644 --- a/sdk/python/skill/references/integration.md +++ b/sdk/python/skill/references/integration.md @@ -80,7 +80,7 @@ and one that propagates is reported exactly once, by the enclosing `agent()`. ## Explicit identity still works -`session_id` and `agent_id` are optional keyword arguments on all 15 `event.*` +`session_id` and `agent_id` are optional keyword arguments on all 16 `event.*` methods, not removed ones. Passing them explicitly still works, and still wins over whatever is bound: @@ -94,6 +94,18 @@ fixes. That is deliberate: the alternative is dropping the event silently, and this SDK already asks you to debug enough invisible failures. `agent_id` never raises — it is a label, and it falls back to `"main"`. +`self_report()` is the exception: it never raises for a missing session, +because losing a report to a missing scope is worse than filing it +unattributed. With no session bound and none passed, an unambiguous open +`tool_use` for the call supplies the session and agent, with no warning: the +one matched by `tool_call_id`, else the newest open report-tool call. Two report +calls open in one session at once (parallel tool calls) resolve to the newer one, +so pass `tool_call_id` when report calls can overlap; open calls in several +sessions resolve to none. Only when no +explicit session, no such open call and no enclosing scope resolves the identity +is the report recorded under `session_id="unattributed"`, with one warning per +process. Every other event method raises as above. + ## Don't use a module global The shortcut the scopes exist to replace, because it breaks silently: diff --git a/sdk/python/skill/references/typescript.md b/sdk/python/skill/references/typescript.md index 0a6dc75bd..41e66e64a 100644 --- a/sdk/python/skill/references/typescript.md +++ b/sdk/python/skill/references/typescript.md @@ -1,7 +1,7 @@ # TypeScript and JavaScript agents — `@failproofai/sdk` Everything in `SKILL.md` §2 (plan) and §6 (production) applies unchanged. The -TypeScript SDK writes the **same 15 events, the same wire format, into the same +TypeScript SDK writes the **same 16 events, the same wire format, into the same spool directory** as the Python one, and `failproofaid` ships both. A fleet running both languages writes into one pipe, and the dashboard cannot tell which language wrote what. This page is what differs: install, names, adapters, bundlers, runtimes, diff --git a/sdk/python/tests/integrations/test_crewai.py b/sdk/python/tests/integrations/test_crewai.py index 97f30fba6..7b4fd8980 100644 --- a/sdk/python/tests/integrations/test_crewai.py +++ b/sdk/python/tests/integrations/test_crewai.py @@ -1297,3 +1297,101 @@ def _raise(*args): with pytest.raises(KeyboardInterrupt) as excinfo: _provider()._prompt_input(None) assert excinfo.value is boom + + +# --------------------------------------------------------------------------- +# Self Reports: the ready-made report tool +# --------------------------------------------------------------------------- + +USE_REPORT = ( + "Thought: I am stuck.\nAction: failproofai_report\n" + 'Action Input: {"category": "missing_context", "detail": "The input file is not provided."}' +) + + +class TestSelfReportTool: + def test_is_a_base_tool_with_the_spec(self): + from failproofai_sdk.integrations.crewai import self_report_tool + + tool = self_report_tool() + assert isinstance(tool, BaseTool) + assert tool.name == "failproofai_report" + assert failproofai_sdk.self_report_spec()["description"] in tool.description + schema = tool.args_schema.model_json_schema() + assert schema["properties"]["category"]["enum"] == ( + failproofai_sdk.self_report_spec()["input_schema"]["properties"]["category"]["enum"] + ) + assert set(schema["required"]) == {"category", "detail"} + + def test_records_on_the_instrumented_crew_agent(self, instrumented, emitted): + from failproofai_sdk.integrations.crewai import self_report_tool + + llm = ScriptedLLM(model="scripted/fake-1", responses=[USE_REPORT, FINAL]) + kickoff(build_crew(llm, tools=[self_report_tool()])) + events = emitted() + (report,) = [e for e in events if e["type"] == "self_report"] + starts = [e for e in events if e["type"] == "agent_start"] + assert report["session_id"] == starts[0]["session_id"] + assert report["agent_id"] == starts[1]["agent_id"] # the agent, not the crew + assert (report["category"], report["detail"], report["source"]) == ( + "missing_context", "The input file is not provided.", "sdk", + ) + assert report["framework"] == "crewai" + # CrewAI's tool sees no call id: the report takes the open call's. + (use,) = [e for e in events if e["type"] == "tool_use" and e["tool_name"] == "failproofai_report"] + assert use["tool_call_id"] and report["tool_call_id"] == use["tool_call_id"] + + def test_is_never_cached(self, emitted): + from failproofai_sdk.integrations.crewai import self_report_tool + + tool = self_report_tool() + args = {"category": "looping", "detail": "same"} + assert tool.cache_function(args, "Recorded.") is False + assert tool.to_structured_tool().cache_function(args, "Recorded.") is False + + def test_async_invoke_runs_in_the_callers_context(self, emitted): + import asyncio + import contextvars + import threading + + from failproofai_sdk.integrations.crewai import self_report_tool + + seen = [] + probe = contextvars.ContextVar("probe", default=None) + tool = self_report_tool() + structured = tool.to_structured_tool() + # Its own ainvoke, not CrewAI's: CrewAI < 1.15 hands a sync tool to + # run_in_executor without the caller's context. + from crewai.tools.structured_tool import CrewStructuredTool + + assert isinstance(structured, CrewStructuredTool) + assert type(structured).ainvoke is not CrewStructuredTool.ainvoke + original = structured.func + + def spy(**kw): + seen.append((probe.get(), threading.current_thread() is threading.main_thread())) + return original(**kw) + + structured.func = spy + + async def call(): + probe.set("caller") + with failproofai_sdk.session("crew-async"): + return await structured.ainvoke({"category": "looping", "detail": "d"}) + + assert asyncio.run(call()) == "Recorded." + # Off the loop's thread, with the caller's context (and its session). + assert seen == [("caller", False)] + (report,) = [e for e in emitted() if e["type"] == "self_report"] + assert report["session_id"] == "crew-async" + + def test_ambient_and_explicit_identity(self, emitted): + from failproofai_sdk.integrations.crewai import self_report_tool + + with failproofai_sdk.session("crew-ambient"): + assert self_report_tool().run(category="looping", detail="d") == "Recorded." + self_report_tool(session_id="crew-s", agent_id="crew-a").run(category="looping", detail="d") + reports = [e for e in emitted() if e["type"] == "self_report"] + assert [(r["session_id"], r["agent_id"]) for r in reports] == [ + ("crew-ambient", "main"), ("crew-s", "crew-a"), + ] diff --git a/sdk/python/tests/integrations/test_langchain.py b/sdk/python/tests/integrations/test_langchain.py index abbf149c7..6c4af3791 100644 --- a/sdk/python/tests/integrations/test_langchain.py +++ b/sdk/python/tests/integrations/test_langchain.py @@ -404,10 +404,11 @@ def _declared_fields_by_type(): "tool_use", "tool_result", "model_request", "model_response", "hook_triggered", "hook_completed", "error", "human_wait", "human_input", "human_pause", "human_interrupt", + "self_report", } -def test_only_the_fifteen_known_event_types_are_emitted(tmp_path, instrumented): +def test_only_the_known_event_types_are_emitted(tmp_path, instrumented): app = build_graph(checkpointer=InMemorySaver()) config = {"configurable": {"thread_id": "vocab"}} app.invoke(empty_state(), config=config) @@ -2336,3 +2337,110 @@ def test_an_unrelated_runnable_invoked_with_none_is_not_the_humans_approval( beats = [e for e in only(rows, "agent_start") if e["agent_id"] == "RunnableLambda"] assert len(beats) == 1 assert beats[0]["session_id"] != "hitl-unrelated" + + +# --------------------------------------------------------------------------- +# Self Reports: the ready-made report tool +# --------------------------------------------------------------------------- + +def _report_graph(report_tool): + model = fake_model( + AIMessage( + "stuck", + tool_calls=[{ + "name": "failproofai_report", + "args": {"category": "repeated_tool_failure", "detail": "The build fails every time."}, + "id": "call_report", + }], + ), + ) + + def plan(state): + return {"messages": [model.invoke(state["messages"])]} + + graph = StateGraph(State) + graph.add_node("plan", plan) + graph.add_node("tools", ToolNode([adder, report_tool])) + graph.add_edge(START, "plan") + graph.add_edge("plan", "tools") + graph.add_edge("tools", END) + return graph.compile(name="reporting_graph") + + +def test_self_report_tool_schema_matches_the_spec(): + from langchain_core.tools import StructuredTool + from langchain_core.utils.function_calling import convert_to_openai_tool + + tool_ = adapter.self_report_tool() + assert isinstance(tool_, StructuredTool) + spec = failproofai_sdk.self_report_spec() + converted = convert_to_openai_tool(tool_)["function"] + assert converted["name"] == "failproofai_report" + assert converted["description"] == spec["description"] + assert converted["parameters"]["properties"] == spec["input_schema"]["properties"] + assert converted["parameters"]["required"] == ["category", "detail"] + + +def test_self_report_tool_records_on_the_instrumented_run(tmp_path, instrumented): + app = _report_graph(adapter.self_report_tool()) + out = app.invoke(empty_state()) + rows = read_events(tmp_path) + (report,) = only(rows, "self_report") + root = only(rows, "agent_start")[0] + assert report["session_id"] == root["session_id"] + assert report["agent_id"] == root["agent_id"] + assert report["tool_call_id"] == "call_report" + assert (report["category"], report["detail"], report["source"]) == ( + "repeated_tool_failure", "The build fails every time.", "sdk", + ) + assert report["framework"] == "langchain" + tool_messages = [m for m in out["messages"] if isinstance(m, ToolMessage)] + assert [m.content for m in tool_messages] == ["Recorded."] + + +def test_self_report_tool_async_path(tmp_path, instrumented): + import asyncio + + asyncio.run(_report_graph(adapter.self_report_tool()).ainvoke(empty_state())) + (report,) = only(read_events(tmp_path), "self_report") + assert report["tool_call_id"] == "call_report" + + +def test_self_report_tool_ambient_scope_without_instrumentation(tmp_path): + with failproofai_sdk.session("lc-ambient"): + assert adapter.self_report_tool().invoke({"category": "looping", "detail": "d"}) == "Recorded." + (report,) = only(read_events(tmp_path), "self_report") + assert (report["session_id"], report["agent_id"]) == ("lc-ambient", "main") + + +def test_self_report_tool_takes_the_tool_call_id_without_instrumentation(tmp_path): + # ToolNode invokes the tool with the model's ToolCall; the id comes from it. + with failproofai_sdk.session("lc-plain"): + _report_graph(adapter.self_report_tool()).invoke(empty_state()) + (report,) = only(read_events(tmp_path), "self_report") + assert (report["session_id"], report["tool_call_id"]) == ("lc-plain", "call_report") + + +def test_self_report_tool_takes_the_tool_call_id_on_the_async_path_without_instrumentation(tmp_path): + import asyncio + + with failproofai_sdk.session("lc-plain-async"): + asyncio.run(_report_graph(adapter.self_report_tool()).ainvoke(empty_state())) + (report,) = only(read_events(tmp_path), "self_report") + assert report["tool_call_id"] == "call_report" + + +def test_self_report_tool_invoked_with_a_tool_call_dict_records_its_id(tmp_path): + tool_ = adapter.self_report_tool(session_id="lc-direct") + tool_.invoke({"name": "failproofai_report", "args": {"category": "looping", "detail": "d"}, + "id": "call_direct", "type": "tool_call"}) + tool_.invoke({"category": "looping", "detail": "plain args"}) + first, second = only(read_events(tmp_path), "self_report") + assert first["tool_call_id"] == "call_direct" + assert "tool_call_id" not in second + + +def test_self_report_tool_explicit_identity_wins(tmp_path, instrumented): + _report_graph(adapter.self_report_tool(session_id="lc-s", agent_id="lc-a")).invoke(empty_state()) + (report,) = only(read_events(tmp_path), "self_report") + assert (report["session_id"], report["agent_id"]) == ("lc-s", "lc-a") diff --git a/sdk/python/tests/integrations/test_llama_index.py b/sdk/python/tests/integrations/test_llama_index.py index 50361f21a..9e95aecfa 100644 --- a/sdk/python/tests/integrations/test_llama_index.py +++ b/sdk/python/tests/integrations/test_llama_index.py @@ -1574,3 +1574,52 @@ def test_captured_values_are_not_capped_at_a_quarter_of_the_core_limit(): assert adapter_module._capture_limit(float("inf")) == _core.FIELD_LIMIT assert adapter_module._capture_limit("nope") == _core.FIELD_LIMIT assert adapter_module._capture_limit(0) == _core.FIELD_LIMIT + + +# --------------------------------------------------------------------------- +# Self Reports: the ready-made report tool +# --------------------------------------------------------------------------- + +def test_self_report_tool_schema_matches_the_spec(): + from llama_index.core.tools import FunctionTool + + tool = adapter_module.self_report_tool() + spec = failproofai_sdk.self_report_spec() + assert isinstance(tool, FunctionTool) + assert tool.metadata.name == "failproofai_report" + assert tool.metadata.description == spec["description"] + params = tool.metadata.get_parameters_dict() + assert params["properties"]["category"]["enum"] == spec["input_schema"]["properties"]["category"]["enum"] + assert set(params["required"]) == {"category", "detail"} + + +def test_self_report_tool_records_on_the_instrumented_agent(instrumented, tmp_path): + llm = StubLLM(script=[("failproofai_report", {"category": "looping", "detail": "same step again"})], final="ok") + run_agent(calculator(llm, tools=[add, adapter_module.self_report_tool()]), "go") + events = read_events(tmp_path) + (report,) = only(events, "self_report") + start = only(events, "agent_start")[0] + assert report["session_id"] == start["session_id"] + assert report["agent_id"] == "calc" + assert (report["category"], report["detail"], report["source"]) == ("looping", "same step again", "sdk") + assert report["framework"] == "llama_index" + results = [e for e in only(events, "tool_result") if e["tool_name"] == "failproofai_report"] + assert results and "Recorded." in str(results[0].get("output")) + # LlamaIndex hands the tool no call id: the report takes the open call's. + (use,) = [e for e in only(events, "tool_use") if e["tool_name"] == "failproofai_report"] + assert use["tool_call_id"] and report["tool_call_id"] == use["tool_call_id"] + + +def test_self_report_tool_uses_the_ambient_scope_when_not_instrumented(tmp_path): + tool = adapter_module.self_report_tool() + with failproofai_sdk.session("li-ambient"): + assert str(tool.call(category="task_failure", detail="gave up")) == "Recorded." + (report,) = only(read_events(tmp_path), "self_report") + assert (report["session_id"], report["agent_id"]) == ("li-ambient", "main") + + +def test_self_report_tool_explicit_identity(tmp_path): + tool = adapter_module.self_report_tool(session_id="li-s", agent_id="li-a") + tool.call(category="looping", detail="x") + (report,) = only(read_events(tmp_path), "self_report") + assert (report["session_id"], report["agent_id"]) == ("li-s", "li-a") diff --git a/sdk/python/tests/integrations/test_pydantic_ai.py b/sdk/python/tests/integrations/test_pydantic_ai.py index 6e5838750..190e92388 100644 --- a/sdk/python/tests/integrations/test_pydantic_ai.py +++ b/sdk/python/tests/integrations/test_pydantic_ai.py @@ -325,7 +325,7 @@ def test_every_event_carries_the_framework_triple(instrumented, emitted): def test_the_type_table_covers_the_whole_schema(): # Guards the test below: a bad CamelCase split would make it vacuous. - assert len(TYPE_OF_DATACLASS) == 15 + assert len(TYPE_OF_DATACLASS) == 16 assert {"tool_use", "model_response", "agent_end", "hook_triggered", "error"} <= set( TYPE_OF_DATACLASS ) @@ -689,6 +689,51 @@ async def wait() -> str: assert kinds.index("tool_result") < kinds.index("agent_end") +def test_uninstrumenting_leaves_a_manually_attached_capabilitys_run_to_finish(instrumented, emitted): + """`uninstrument()` closes only the runs it instrumented. + + A `FailproofAI()` the developer attached by hand keeps recording after + `uninstrument()`; its in-flight run must end on its own, once, with its + real outcome, and its tool call must still be recorded. + """ + + async def main(): + waiting = [] + release = asyncio.Event() + manual = Agent( + one_shot_tool_model("wait", {}, tool_call_id="call-manual"), + name="manual_agent", + capabilities=[FailproofAI()], + ) + injected = Agent( + one_shot_tool_model("wait", {}, tool_call_id="call-injected"), + name="injected_agent", + ) + + async def wait() -> str: + waiting.append(1) + await release.wait() + return "finished" + + manual.tool_plain(wait) + injected.tool_plain(wait) + tasks = [asyncio.create_task(manual.run("go")), asyncio.create_task(injected.run("go"))] + while len(waiting) < 2: + await asyncio.sleep(0.01) + failproofai_sdk.uninstrument("pydantic_ai") + release.set() + await asyncio.gather(*tasks) + + asyncio.run(main()) + rows = emitted() + ends = {r["agent_id"]: r["outcome"] for r in of_type(rows, "agent_end")} + assert len(of_type(rows, "agent_end")) == 2, types_of(rows) + assert ends == {"manual_agent": "success", "injected_agent": "cancelled"} + manual_rows = [r for r in rows if r.get("agent_id") == "manual_agent"] + assert types_of(manual_rows).count("tool_result") == 1 + assert types_of(manual_rows)[-1] == "agent_end" + + # --------------------------------------------------------------------------- # What `tool_result.output` actually says # --------------------------------------------------------------------------- @@ -969,6 +1014,7 @@ def test_the_override_set_is_not_empty(self): # Guards every test below: `for name in {}` passes vacuously. assert set(OVERRIDES) == { "get_ordering", + "get_toolset", # contributes the opt-in report tool "wrap_run", "wrap_model_request", "wrap_tool_execute", @@ -1100,3 +1146,102 @@ def reject(value: str) -> str: # Strictly before agent_end: the dashboard closes the agent span there and # anything after it is attributed to nothing. assert types_of(rows).index("error") < types_of(rows).index("agent_end") + + +# --------------------------------------------------------------------------- +# Self Reports: the ready-made report tool, and the capability opt-in +# --------------------------------------------------------------------------- + +_REPORT_ARGS = {"category": "invalid_tool_or_credential", "detail": "The API key is rejected."} + + +def _tool_definitions(agent): + """The tool definitions the model is actually shown on the first request.""" + seen = {} + + def respond(messages, info): + seen["tools"] = {t.name: t for t in info.function_tools} + return ModelResponse(parts=[TextPart("done")]) + + agent.run_sync("go", model=FunctionModel(respond)) + return seen["tools"] + + +def test_self_report_tool_schema_is_exactly_the_spec(): + agent = Agent(TestModel(call_tools=[]), tools=[adapter.self_report_tool()]) + tools = _tool_definitions(agent) + spec = failproofai_sdk.self_report_spec() + definition = tools["failproofai_report"] + assert definition.description == spec["description"] + assert definition.parameters_json_schema == spec["input_schema"] + + +def test_self_report_tool_records_on_the_instrumented_run(instrumented, emitted): + agent = Agent( + one_shot_tool_model("failproofai_report", _REPORT_ARGS, tool_call_id="call-r"), + name="reporter_agent", + tools=[adapter.self_report_tool()], + ) + agent.run_sync("go") + rows = emitted() + (report,) = of_type(rows, "self_report") + start = of_type(rows, "agent_start")[0] + assert report["session_id"] == start["session_id"] + assert report["agent_id"] == "reporter_agent" + assert report["tool_call_id"] == "call-r" + assert (report["category"], report["detail"], report["source"]) == ( + "invalid_tool_or_credential", "The API key is rejected.", "sdk", + ) + assert report["framework"] == "pydantic_ai" + (result,) = [r for r in of_type(rows, "tool_result") if r["tool_name"] == "failproofai_report"] + assert result["output"] == "Recorded." + + +def test_self_report_tool_ambient_and_explicit_identity(emitted): + with failproofai_sdk.session("pai-ambient"): + Agent(one_shot_tool_model("failproofai_report", _REPORT_ARGS), + tools=[adapter.self_report_tool()]).run_sync("go") + Agent(one_shot_tool_model("failproofai_report", _REPORT_ARGS), + tools=[adapter.self_report_tool(session_id="pai-s", agent_id="pai-a")]).run_sync("go") + reports = of_type(emitted(), "self_report") + assert [(r["session_id"], r["agent_id"]) for r in reports] == [ + ("pai-ambient", "main"), ("pai-s", "pai-a"), + ] + + +def test_the_capability_adds_the_tool_only_when_asked(): + plain = _tool_definitions(Agent(TestModel(call_tools=[]), capabilities=[FailproofAI()])) + assert "failproofai_report" not in plain + opted = _tool_definitions(Agent(TestModel(call_tools=[]), capabilities=[FailproofAI(self_report=True)])) + assert "failproofai_report" in opted + + +def test_a_hand_added_self_report_capability_records_the_run_without_instrument(emitted): + agent = Agent( + one_shot_tool_model("failproofai_report", _REPORT_ARGS, tool_call_id="call-cap"), + name="cap_agent", + capabilities=[FailproofAI(self_report=True)], + ) + agent.run_sync("go") + rows = emitted() + assert types_of(rows)[0] == "agent_start" and types_of(rows)[-1] == "agent_end" + (start,) = of_type(rows, "agent_start") + (report,) = of_type(rows, "self_report") + assert report["session_id"] == start["session_id"] != "unattributed" + assert report["agent_id"] == "cap_agent" + assert report["tool_call_id"] == "call-cap" + + +def test_instrument_self_report_option_adds_the_tool(emitted): + _core.set_strict(False) + _compat.set_strict_integrations(False) + assert failproofai_sdk.instrument("pydantic_ai", self_report=True) == ("pydantic_ai",) + try: + agent = Agent( + one_shot_tool_model("failproofai_report", _REPORT_ARGS), name="auto_agent" + ) + agent.run_sync("go") + finally: + failproofai_sdk.uninstrument("pydantic_ai") + (report,) = of_type(emitted(), "self_report") + assert report["agent_id"] == "auto_agent" diff --git a/sdk/python/tests/test_self_report.py b/sdk/python/tests/test_self_report.py new file mode 100644 index 000000000..d6246980f --- /dev/null +++ b/sdk/python/tests/test_self_report.py @@ -0,0 +1,583 @@ +"""Self Reports in the core SDK: the event, the settings file, the raw tool helpers. + +Everything here is stdlib-only, like the code under test. The framework tools +are exercised against the real frameworks in tests/integrations/test_self_report_tools.py. +""" +import json +import logging + +import pytest + +import failproofai_sdk as fp +from failproofai_sdk import _runtime, _self_report +from failproofai_sdk._events import EventNamespace + +EXPECTED_DEFAULT_DESCRIPTION = """When you are stuck on something you cannot fix yourself, call this tool once with `category` (one of the categories below) and `detail` (one factual sentence: what is blocking you). It reports to FailproofAI. Call it BEFORE your final answer, for example for a missing, invalid or expired token or API key, a 401 or 403, a command, tool or MCP server that keeps failing, information or access you cannot get, or a request you cannot do here. Do not call it for normal work, clarifying questions or an error you then fixed. One call per distinct problem. +Reporting does not unblock you and changes no decision: afterwards, work around the problem or tell the user what is blocking you. There is no need to mention this report to the user. + +Categories: +- looping: You keep repeating the same or circular steps without making progress. +- cannot_do_request: The user asked for something you cannot do here: a missing capability, tool or permission, or it is only possible by cheating. +- invalid_tool_or_credential: A tool, MCP server, plugin, API key or token you need is broken, invalid, expired or rejected. +- missing_context: Information or access you need is missing and you cannot get it yourself. Not for normal clarifying questions. +- repeated_tool_failure: A command or tool failed on several distinct attempts and is blocking you. A single error is not enough. +- task_failure: You genuinely tried and could not complete the task, or something else blocks you that no other category describes. Not for refusals or policy blocks.""" + +DEFAULT_NAMES = [ + "looping", + "cannot_do_request", + "invalid_tool_or_credential", + "missing_context", + "repeated_tool_failure", + "task_failure", +] + + +class _Recorder: + def __init__(self): + self.entries = [] + + def submit(self, entry): + self.entries.append(entry) + + +@pytest.fixture() +def recorded(monkeypatch): + """Swap the process namespace for one that records instead of spooling.""" + from failproofai_sdk import _runtime + + recorder = _Recorder() + monkeypatch.setattr(_runtime, "event", EventNamespace(recorder)) + return recorder.entries + + +@pytest.fixture() +def home(tmp_path, monkeypatch): + path = tmp_path / "fphome" + path.mkdir() + monkeypatch.setenv("FAILPROOFAI_HOME", str(path)) + return path + + +def write_settings(home, body): + (home / "self-report.json").write_text( + body if isinstance(body, str) else json.dumps(body), encoding="utf-8" + ) + + +# ───────────────────────────────────────────────────────────────────────────── +# The event +# ───────────────────────────────────────────────────────────────────────────── + + +def test_event_shape_in_session_and_agent_scope(recorded): + with fp.session("sess-1"): + with fp.agent("planner"): + fp.self_report("looping", "I keep retrying the same search.") + # `agent()` brackets itself with agent_start / agent_end. + (event,) = [e for e in recorded if e["type"] == "self_report"] + assert event["session_id"] == "sess-1" + assert event["agent_id"] == "planner" + assert event["category"] == "looping" + assert event["detail"] == "I keep retrying the same search." + assert event["source"] == "sdk" + assert "environment" in event and event["timestamp"].endswith("Z") + assert "tool_call_id" not in event + + +def test_session_without_agent_scope_uses_the_default_agent(recorded): + with fp.session("s"): + fp.self_report("task_failure", "x") + assert recorded[0]["agent_id"] == "main" + + +def test_explicit_identity_and_extra_fields(recorded): + fp.self_report("missing_context", "d", session_id="s2", agent_id="a2", tool_call_id="call_9", run="r1") + event = recorded[0] + assert (event["session_id"], event["agent_id"], event["tool_call_id"], event["run"]) == ( + "s2", "a2", "call_9", "r1", + ) + + +def test_nothing_bound_is_filed_as_unattributed_with_one_warning(recorded, monkeypatch, caplog): + from failproofai_sdk import _events + + monkeypatch.setattr(_events, "_warned_unattributed", False) + with caplog.at_level(logging.WARNING, logger="failproofai_sdk"): + fp.self_report("looping", "x") + fp.self_report("looping", "y") + assert [(e["session_id"], e["agent_id"]) for e in recorded] == [ + ("unattributed", "main"), ("unattributed", "main"), + ] + assert len([r for r in caplog.records if "unattributed" in r.getMessage()]) == 1 + + +def test_the_open_tool_use_for_this_call_wins_over_the_ambient_agent(recorded): + with fp.session("s-tools"): + with fp.agent("worker"): + _runtime.event.tool_use(tool_name="failproofai_report", tool_call_id="call_7") + # reported from a different agent scope, same session: the tool's agent wins + fp.self_report("looping", "d", tool_call_id="call_7") + (report,) = [e for e in recorded if e["type"] == "self_report"] + assert (report["session_id"], report["agent_id"]) == ("s-tools", "worker") + + +def test_the_open_tool_use_resolves_a_report_with_nothing_bound(recorded): + _runtime.event.tool_use(session_id="s-open", agent_id="a-open", + tool_name="failproofai_report", tool_call_id="call_8") + fp.self_report("looping", "by id", tool_call_id="call_8") + fp.self_report("looping", "by tool name") # no id: newest open report-tool call + reports = [e for e in recorded if e["type"] == "self_report"] + assert [(r["session_id"], r["agent_id"]) for r in reports] == [("s-open", "a-open")] * 2 + # A report with no id takes the matched call's id. + assert [r["tool_call_id"] for r in reports] == ["call_8", "call_8"] + + +def test_the_callers_tool_call_id_beats_the_matched_calls(recorded): + _runtime.event.tool_use(session_id="s-own", agent_id="a", tool_name="failproofai_report", tool_call_id="adapter-id") + fp.self_report("looping", "d", tool_call_id="model-id") + with fp.session("s-none"): + fp.self_report("looping", "no open call") + first, second = [e for e in recorded if e["type"] == "self_report"] + assert (first["session_id"], first["tool_call_id"]) == ("s-own", "model-id") + assert second["session_id"] == "s-none" and "tool_call_id" not in second + + +def test_a_closed_or_foreign_session_tool_use_is_not_used(recorded): + _runtime.event.tool_use(session_id="s-a", agent_id="a", tool_name="failproofai_report", tool_call_id="c1") + _runtime.event.tool_result(session_id="s-a", agent_id="a", tool_name="failproofai_report", tool_call_id="c1") + _runtime.event.tool_use(session_id="s-other", agent_id="b", tool_name="failproofai_report", tool_call_id="c2") + with fp.session("s-mine"): + fp.self_report("looping", "d", tool_call_id="c1") + fp.self_report("looping", "d", tool_call_id="c2") + reports = [e for e in recorded if e["type"] == "self_report"] + assert [r["session_id"] for r in reports] == ["s-mine", "s-mine"] + + +def test_two_sessions_reusing_one_call_id_keep_their_own_open_calls(recorded): + ev = _runtime.event + ev.tool_use(session_id="s-1", agent_id="a-1", tool_name="failproofai_report", tool_call_id="call_0") + ev.tool_use(session_id="s-2", agent_id="a-2", tool_name="failproofai_report", tool_call_id="call_0") + # Each session's report finds its own call, not the other's. + with fp.session("s-1"): + fp.self_report("looping", "one", tool_call_id="call_0") + with fp.session("s-2"): + fp.self_report("looping", "two", tool_call_id="call_0") + # Closing s-1's call leaves s-2's open. + ev.tool_result(session_id="s-1", agent_id="a-1", tool_name="failproofai_report", tool_call_id="call_0") + with fp.session("s-2"): + fp.self_report("looping", "after", tool_call_id="call_0") + with fp.session("s-1"): + fp.self_report("looping", "closed", tool_call_id="call_0") + reports = [e for e in recorded if e["type"] == "self_report"] + assert [(r["detail"], r["session_id"], r["agent_id"]) for r in reports] == [ + ("one", "s-1", "a-1"), ("two", "s-2", "a-2"), ("after", "s-2", "a-2"), ("closed", "s-1", "main"), + ] + + +def test_with_nothing_bound_open_calls_in_two_sessions_are_not_guessed(recorded): + ev = _runtime.event + ev.tool_use(session_id="s-x", agent_id="a-x", tool_name="failproofai_report", tool_call_id="cx") + ev.tool_use(session_id="s-y", agent_id="a-y", tool_name="failproofai_report", tool_call_id="cy") + ev.tool_use(session_id="s-y", agent_id="a-y", tool_name="failproofai_report", tool_call_id="shared") + ev.tool_use(session_id="s-x", agent_id="a-x", tool_name="failproofai_report", tool_call_id="shared") + fp.self_report("looping", "no id") # newest of two sessions: no guess + fp.self_report("looping", "shared id", tool_call_id="shared") # id open in two sessions + fp.self_report("looping", "unique id", tool_call_id="cy") # one candidate: used + reports = [e for e in recorded if e["type"] == "self_report"] + assert [(r["detail"], r["session_id"]) for r in reports] == [ + ("no id", "unattributed"), ("shared id", "unattributed"), ("unique id", "s-y"), + ] + + +def test_an_id_open_in_two_sessions_never_falls_back_to_the_tool_name(recorded): + ev = _runtime.event + # The id is open in two sessions (on another tool); a report call is open in a third. + ev.tool_use(session_id="s-1", agent_id="a-1", tool_name="search", tool_call_id="dup") + ev.tool_use(session_id="s-2", agent_id="a-2", tool_name="search", tool_call_id="dup") + ev.tool_use(session_id="s-3", agent_id="a-3", tool_name="failproofai_report", tool_call_id="r3") + fp.self_report("looping", "ambiguous id", tool_call_id="dup") + fp.self_report("looping", "unknown id", tool_call_id="model-id") # no call has it: name fallback + fp.self_report("looping", "no id") + reports = [e for e in recorded if e["type"] == "self_report"] + assert [(r["detail"], r["session_id"], r.get("tool_call_id")) for r in reports] == [ + ("ambiguous id", "unattributed", "dup"), + ("unknown id", "s-3", "model-id"), + ("no id", "s-3", "r3"), + ] + + +def test_an_explicit_session_infers_the_call_id_only_from_one_call_of_its_agent(recorded): + ev = _runtime.event + ev.tool_use(session_id="s", agent_id="planner", tool_name="failproofai_report", tool_call_id="p-1") + ev.tool_use(session_id="s", agent_id="worker", tool_name="failproofai_report", tool_call_id="w-1") + fp.self_report("looping", "planner", session_id="s", agent_id="planner") + fp.self_report("looping", "worker", session_id="s", agent_id="worker") + fp.self_report("looping", "nobody", session_id="s", agent_id="other") + # A second open report call for the worker: two candidates, no guess. + ev.tool_use(session_id="s", agent_id="worker", tool_name="failproofai_report", tool_call_id="w-2") + fp.self_report("looping", "worker twice", session_id="s", agent_id="worker") + with fp.agent("planner"): + fp.self_report("looping", "ambient agent", session_id="s") + reports = [e for e in recorded if e["type"] == "self_report"] + assert [(r["detail"], r["agent_id"], r.get("tool_call_id")) for r in reports] == [ + ("planner", "planner", "p-1"), + ("worker", "worker", "w-1"), + ("nobody", "other", None), + ("worker twice", "worker", None), + ("ambient agent", "planner", "p-1"), + ] + + +def test_detail_cut_at_a_surrogate_boundary_has_no_lone_surrogate(recorded): + fp.self_report("looping", "a" * 1999 + "\U0001F600 and more", session_id="s") + fp.self_report("lo\ud83dping", "x\ud83d", session_id="s") + first, second = recorded + assert first["detail"] == "a" * 1999 + "\U0001F600" + assert (second["category"], second["detail"]) == ("lo\ufffdping", "x\ufffd") + # Encodable as strict UTF-8, which is what the collector reads. + json.dumps(second, ensure_ascii=False).encode("utf-8") + + +def test_written_to_the_spool_by_the_real_writer(tmp_path): + with fp.session("disk"): + fp.self_report("looping", "on disk") + fp._writer.flush_now() + rows = [ + json.loads(line) + for p in sorted((tmp_path / "events").glob("*.jsonl")) + for line in p.read_text().splitlines() + if line.strip() + ] + reports = [r for r in rows if r["type"] == "self_report"] + assert reports and reports[-1]["detail"] == "on disk" and reports[-1]["source"] == "sdk" + + +def test_detail_is_truncated_and_none_becomes_empty(recorded): + fp.self_report("looping", "x " * 2500, session_id="s") + fp.self_report("looping", None, session_id="s") + fp.self_report("looping", "token " + "eyJ" + "a" * 3000, session_id="s") + # Cut at 2000 code points, never leaving part of a token at the end. + assert recorded[0]["detail"] == ("x " * 1000).rstrip() + assert recorded[1]["detail"] == "" + assert recorded[2]["detail"] == "token" + + +def test_unknown_category_is_recorded_as_is(recorded): + # The developer's own call is recorded as given; only a model's tool call + # is resolved against the list. + fp.self_report("not_a_configured_one", "d", session_id="s") + assert recorded[0]["category"] == "not_a_configured_one" + + +LIVE_DETAIL = ( + 'Deployment is blocked because ./deploy.sh exits with "DEPLOY_TOKEN is not set" ' + "and no token is available in this environment." +) + + +def test_a_tool_call_with_no_category_is_filed_under_the_inferred_one(recorded, home): + assert fp.handle_tool_call("failproofai_report", {"detail": LIVE_DETAIL}, session_id="s") == "Recorded." + assert recorded[0]["category"] == "invalid_tool_or_credential" + assert recorded[0]["detail"] == LIVE_DETAIL + fp.handle_tool_call( + "failproofai_report", '{"category": "Invalid Tool Or Credential", "detail": "x"}', session_id="s" + ) + assert recorded[1]["category"] == "invalid_tool_or_credential" + fp.handle_tool_call( + "failproofai_report", {"category": "command_nonzero_exit", "detail": "the build failed"}, session_id="s" + ) + assert recorded[2]["category"] == "task_failure" + + +def test_a_tool_call_resolves_against_the_orgs_list_or_the_tools_own(recorded, home): + write_settings(home, {"enabled": True, "categories": [ + {"name": "data_gap", "description": "Data is missing."}, + {"name": "blocked", "description": "Blocked."}, + ]}) + fp.handle_tool_call("failproofai_report", {"category": "", "detail": "Nothing matches."}, session_id="s") + assert recorded[0]["category"] == "data_gap" + own = [{"name": "blocked", "description": "B."}, {"name": "missing_context", "description": "M."}] + fp.handle_tool_call("failproofai_report", {"detail": "The ticket is missing."}, session_id="s", categories=own) + assert recorded[1]["category"] == "missing_context" + + +@pytest.mark.parametrize("name", ["timestamp", "type", "environment", "source"]) +def test_reserved_and_sdk_owned_fields_are_rejected(recorded, name): + with pytest.raises(ValueError): + fp.self_report("looping", "d", session_id="s", **{name: "x"}) + + +def test_wrong_types_are_rejected(recorded): + with pytest.raises(TypeError): + fp.self_report(None, "d", session_id="s") + with pytest.raises(TypeError): + fp.self_report("looping", 5, session_id="s") + with pytest.raises(TypeError): + fp.self_report("looping", "d", session_id="s", tool_call_id=7) + + +def test_event_namespace_method_is_the_same_event(): + recorder = _Recorder() + EventNamespace(recorder).self_report("looping", "d", session_id="s", agent_id="a") + assert recorder.entries[0]["type"] == "self_report" + + +# ───────────────────────────────────────────────────────────────────────────── +# Settings and the spec +# ───────────────────────────────────────────────────────────────────────────── + + +def test_missing_file_gives_the_defaults(home): + spec = fp.self_report_spec() + assert spec["name"] == "failproofai_report" + assert spec["description"] == EXPECTED_DEFAULT_DESCRIPTION + assert spec["input_schema"] == { + "type": "object", + "properties": { + "category": {"type": "string", "enum": DEFAULT_NAMES}, + "detail": {"type": "string", "description": "One factual sentence: what is blocking you."}, + }, + "required": ["category", "detail"], + "additionalProperties": False, + } + assert _self_report.load_settings()["enabled"] is False + + +def test_settings_path_follows_failproofai_home(home): + assert _self_report.settings_path() == home / "self-report.json" + + +ORG = { + "version": 1, + "enabled": True, + "source": "cloud", + "categories": [ + {"name": "billing_blocked", "description": "A payment step is refused."}, + {"name": "looping", "description": "Going in circles."}, + ], + "guidance": "Report billing problems at once.", + "mcp": {"port": 4319, "url": "http://127.0.0.1:4319/mcp"}, + "updatedAt": "2026-11-25T10:00:00Z", +} + + +def test_enabled_file_replaces_categories_and_appends_guidance(home): + write_settings(home, ORG) + spec = fp.self_report_spec() + assert spec["input_schema"]["properties"]["category"]["enum"] == ["billing_blocked", "looping"] + assert spec["description"].endswith( + "Categories:\n- billing_blocked: A payment step is refused.\n- looping: Going in circles." + "\n\nReport billing problems at once." + ) + + +def test_settings_are_reread_on_every_call(home): + assert "billing_blocked" not in fp.self_report_spec()["description"] + write_settings(home, ORG) + assert "billing_blocked" in fp.self_report_spec()["description"] + + +def test_disabled_file_still_builds_the_default_spec(home): + write_settings(home, {**ORG, "enabled": False}) + spec = fp.self_report_spec() + assert spec["description"] == EXPECTED_DEFAULT_DESCRIPTION + + +@pytest.mark.parametrize("body", ["{not json", "[]", '"x"', ""]) +def test_unparsable_file_gives_the_defaults(home, body): + write_settings(home, body) + assert fp.self_report_spec()["description"] == EXPECTED_DEFAULT_DESCRIPTION + + +@pytest.mark.parametrize( + "categories", + [ + [], + None, + "looping", + [{"name": "Bad Name", "description": "x"}, {"name": "ok_one", "description": "fine"}], + [{"name": "ok_one", "description": "fine"}, {"name": "ok_one", "description": "dupe"}], + [{"name": "ok_one", "description": ""}], + [{"name": "ok_one", "description": "x" * 501}], + [{"name": f"c{i}", "description": "d"} for i in range(33)], + ], + ids=["empty", "null", "string", "bad-name", "duplicate", "empty-desc", "long-desc", "33"], +) +def test_an_invalid_category_list_means_all_six_defaults(home, categories): + write_settings(home, {**ORG, "categories": categories}) + assert fp.self_report_spec()["input_schema"]["properties"]["category"]["enum"] == DEFAULT_NAMES + + +def test_guidance_over_2000_chars_is_dropped_not_cut(home): + write_settings(home, {**ORG, "guidance": "g" * 2001}) + assert fp.self_report_spec()["description"].endswith("- looping: Going in circles.") + write_settings(home, {**ORG, "guidance": "g" * 2000}) + assert fp.self_report_spec()["description"].endswith("\n\n" + "g" * 2000) + + +def test_explicit_categories_override_the_file(home): + write_settings(home, ORG) + spec = fp.self_report_spec(categories=[{"name": "mine", "description": "Mine."}]) + assert spec["input_schema"]["properties"]["category"]["enum"] == ["mine"] + assert "Report billing problems" not in spec["description"] + with pytest.raises(ValueError): + fp.self_report_spec(categories=[{"name": "BAD", "description": "x"}]) + with pytest.raises(ValueError): + fp.self_report_spec(categories=[]) + + +def test_describe_matches_the_contract_layout(): + text = _self_report.describe([{"name": "a", "description": "A."}], "Extra.") + assert text.endswith("\n\nCategories:\n- a: A.\n\nExtra.") + assert _self_report.describe([{"name": "a", "description": "A."}], None).endswith("- a: A.") + + +# ───────────────────────────────────────────────────────────────────────────── +# Raw helpers +# ───────────────────────────────────────────────────────────────────────────── + + +def test_openai_chat_tool_shape(home): + tool = fp.openai_tool() + spec = fp.self_report_spec() + assert tool == { + "type": "function", + "function": {"name": spec["name"], "description": spec["description"], "parameters": spec["input_schema"]}, + } + + +def test_openai_responses_tool_shape(home): + tool = fp.openai_responses_tool() + spec = fp.self_report_spec() + assert tool == { + "type": "function", + "name": spec["name"], + "description": spec["description"], + "parameters": spec["input_schema"], + "strict": True, + } + # Strict mode holds: every property required, nothing else allowed. + params = tool["parameters"] + assert set(params["required"]) == set(params["properties"]) + assert params["additionalProperties"] is False + + +def test_anthropic_tool_shape(home): + assert fp.anthropic_tool() == fp.self_report_spec() + assert set(fp.anthropic_tool()) == {"name", "description", "input_schema"} + + +@pytest.mark.parametrize( + "name", + [ + "failproofai_report", + "mcp__failproofai_local__report", + "failproofai_local__report", + "failproofai_local.report", + "failproofai_local/report", + "failproofai_local-report", + ], +) +def test_is_self_report_tool_accepts_every_spelling(name): + assert fp.is_self_report_tool(name) + + +@pytest.mark.parametrize( + "name", ["report", "MCP:report", "bash", "mcp__other__report", "failproofai_report_x", "other-report", "failproofai-reports", "", None, 3] +) +def test_is_self_report_tool_rejects_others(name): + assert not fp.is_self_report_tool(name) + + +def test_handle_tool_call_with_a_json_string(recorded): + with fp.session("s"): + out = fp.handle_tool_call( + "failproofai_report", '{"category": "looping", "detail": "stuck"}', tool_call_id="call_1" + ) + assert out == "Recorded." + assert recorded[0]["category"] == "looping" + assert recorded[0]["detail"] == "stuck" + assert recorded[0]["tool_call_id"] == "call_1" + + +def test_handle_tool_call_with_a_dict_and_explicit_identity(recorded): + out = fp.handle_tool_call( + "mcp__failproofai_local__report", {"category": "x", "detail": "y"}, session_id="s", agent_id="a" + ) + assert out == "Recorded." + assert (recorded[0]["session_id"], recorded[0]["agent_id"]) == ("s", "a") + + +@pytest.mark.parametrize( + "arguments,expected", + [ + (None, ("", "")), + ("", ("", "")), + ({}, ("", "")), + ('{"category": "looping"}', ("looping", "")), + ("not json at all", ("", "not json at all")), + ('["a"]', ("", "['a']")), + ({"category": 5, "detail": None}, ("5", "")), + ], +) +def test_handle_tool_call_tolerates_bad_arguments(recorded, arguments, expected): + assert fp.handle_tool_call("failproofai_report", arguments, session_id="s") == "Recorded." + # Parsed as before; a category that is missing or not listed is then + # recorded as the one it resolves to (nothing here matches a keyword). + from failproofai_sdk import _self_report + + assert _self_report.parse_arguments(arguments) == expected + category = "looping" if expected[0] == "looping" else "task_failure" + assert (recorded[0]["category"], recorded[0]["detail"]) == (category, expected[1]) + + +def test_handle_tool_call_keeps_an_aliased_detail(recorded): + out = fp.handle_tool_call( + "failproofai_report", '{"kind": "looping", "sentence": "same fix again", "extra": 1}', session_id="s" + ) + assert out == "Recorded." + assert (recorded[0]["category"], recorded[0]["detail"]) == ("looping", "same fix again") + + +def test_framework_calls_keep_a_detail_passed_through_raw(recorded): + out = _self_report.record_framework_call( + "looping", "", session_id="s", extra_args={"summary": "retrying the same edit", "other": 1} + ) + assert out == "Recorded." + assert (recorded[0]["category"], recorded[0]["detail"]) == ("looping", "retrying the same edit") + + +def test_handle_tool_call_with_nothing_bound_records_unattributed(recorded): + assert fp.handle_tool_call("failproofai_report", {"category": "looping", "detail": "x"}) == "Recorded." + assert recorded[0]["session_id"] == "unattributed" + + +def test_handle_tool_call_never_raises_into_the_agent(recorded, caplog): + with caplog.at_level(logging.WARNING, logger="failproofai_sdk"): + # an invalid explicit id is refused by the event method; the helper swallows it + assert fp.handle_tool_call("failproofai_report", {"category": "looping"}, session_id=" ") == "Recorded." + assert recorded == [] + assert any("not recorded" in r.getMessage() for r in caplog.records) + + +def test_handle_tool_call_refuses_another_tool(): + with pytest.raises(ValueError, match="not the FailproofAI report tool"): + fp.handle_tool_call("bash", {}) + + +def test_importing_the_package_reads_no_settings(monkeypatch): + """The settings file is read when a spec is built, never at import.""" + import subprocess + import sys + + code = ( + "import builtins, pathlib\n" + "orig = pathlib.Path.read_text\n" + "def guard(self, *a, **k):\n" + " assert self.name != 'self-report.json', 'read at import'\n" + " return orig(self, *a, **k)\n" + "pathlib.Path.read_text = guard\n" + "import failproofai_sdk\n" + ) + subprocess.run([sys.executable, "-c", code], check=True) diff --git a/sdk/python/tests/test_self_report_golden.py b/sdk/python/tests/test_self_report_golden.py new file mode 100644 index 000000000..14f2d424b --- /dev/null +++ b/sdk/python/tests/test_self_report_golden.py @@ -0,0 +1,144 @@ +"""Self Reports: the Python side of the repository's shared golden files. + +The Rust daemon, the CLI and the TypeScript SDK are tested against the same +files in test-fixtures/self-report/, so the tool description, input schema, +default categories, recognised tool names and the `self_report` event's field +order cannot drift between the four implementations. Change a golden file only +together with every implementation. +""" + +from __future__ import annotations + +import json +import os +from pathlib import Path + +import pytest + +import failproofai_sdk as fp +from failproofai_sdk import _self_report +from failproofai_sdk._schema import SelfReportEvent + +_HERE = Path(__file__).resolve() +REPO_ROOT = _HERE.parents[3] if len(_HERE.parents) > 3 else _HERE.parent +GOLDEN = REPO_ROOT / "test-fixtures" / "self-report" + +#: CI sets this, so a missing golden directory fails instead of skipping. +REQUIRE = os.environ.get("FAILPROOFAI_SDK_REQUIRE_CONTRACT", "").strip().lower() in {"1", "true", "yes"} + +pytestmark = pytest.mark.skipif( + not GOLDEN.is_dir() and not REQUIRE, + reason="the golden files live in the failproofai repository, not in the sdist", +) + + +def golden(name: str) -> str: + return (GOLDEN / name).read_text(encoding="utf-8") + + +def lines(name: str) -> list[str]: + return [line for line in golden(name).split("\n") if line] + + +def test_description_byte_for_byte(): + cats = [dict(c) for c in _self_report.DEFAULT_CATEGORIES] + assert _self_report.describe(cats) == golden("description.golden.txt") + assert _self_report.describe(cats, "Report a missing repository as missing_context.") == golden( + "description-guidance.golden.txt" + ) + + +def test_input_schema_byte_for_byte(): + spec = _self_report.self_report_spec(categories=[dict(c) for c in _self_report.DEFAULT_CATEGORIES]) + assert json.dumps(spec["input_schema"], separators=(",", ":"), ensure_ascii=False) + "\n" == golden( + "input-schema.golden.json" + ) + + +def test_default_categories(): + assert [dict(c) for c in _self_report.DEFAULT_CATEGORIES] == json.loads(golden("categories.golden.json")) + + +def test_tool_names(): + assert list(_self_report.TOOL_SPELLINGS) == lines("tool-names.golden.txt") + for name in lines("tool-names.golden.txt"): + assert fp.is_self_report_tool(name), name + assert fp.is_self_report_tool(name.upper()), name + assert fp.is_self_report_tool("report", "failproofai_local") + assert fp.is_self_report_tool("MCP:report", "failproofai_local") + assert not fp.is_self_report_tool("report", "linear") + assert not fp.is_self_report_tool("MCP:report") + # The Cloud gateway's server is `failproofai`: its tools are never ours. + assert not fp.is_self_report_tool("report", "failproofai") + for name in ("mcp__failproofai__report", "failproofai__report", "mcp_failproofai_report", "failproofai-report"): + assert not fp.is_self_report_tool(name), name + + +def test_event_field_order(): + spec = json.loads(golden("event-fields.golden.json")) + base = dict( + timestamp="2026-11-25T10:00:00.000000Z", + session_id="s1", + agent_id="a1", + category="looping", + detail="Same step again.", + ) + assert list(SelfReportEvent(**base).to_dict()) == spec["order"] + assert list(SelfReportEvent(**base, tool_call_id="call_1").to_dict()) == spec["order"] + spec["optional"] + + +def test_category_inference_matches_the_shared_rules_and_cases(): + fixture = json.loads(golden("category-inference.json")) + rules = [{"category": c, "keywords": list(k)} for c, k in _self_report.CATEGORY_RULES] + assert rules == fixture["rules"] + assert _self_report.FALLBACK_CATEGORY == fixture["fallback"] + defaults = [c["name"] for c in _self_report.DEFAULT_CATEGORIES] + assert fixture["cases"] + for case in fixture["cases"]: + category, detail = _self_report.parse_arguments(case["args"]) + got = _self_report.resolve_category(category, detail, case.get("categories", defaults)) + assert got == (case["category"], case["inferred"]), case["name"] + + +def test_argument_aliases_match_the_shared_list(): + fixture = json.loads(golden("arg-aliases.json")) + assert {k: list(v) for k, v in _self_report.ARG_ALIASES.items()} == fixture["aliases"] + assert fixture["cases"] + for case in fixture["cases"]: + want = (case["category"], case["detail"]) + assert _self_report.parse_arguments(case["args"]) == want, case["args"] + assert _self_report.parse_arguments(json.dumps(case["args"])) == want, case["args"] + + +def test_truncation_counts_code_points_like_every_recorder(): + from failproofai_sdk._events import SELF_REPORT_DETAIL_LIMIT, clip_report_text + + fixture = json.loads(golden("truncation.golden.json")) + assert fixture["max"] == SELF_REPORT_DETAIL_LIMIT + assert fixture["cases"] + for case in fixture["cases"]: + pad = case["pad_char"] * case["pad"] + text, want = pad + case["tail"], pad + case["expected_tail"] + assert clip_report_text(text) == want, case + + +def test_detail_cut_never_leaves_part_of_a_token_like_every_recorder(): + """Round 3: a credential running past the cut was uploaded as a fragment.""" + from failproofai_sdk._events import DETAIL_CUT_MARKER, cut_report_detail + + fixture = json.loads(golden("truncation.golden.json")) + spec = fixture["detail_cut"] + assert spec["marker"] == DETAIL_CUT_MARKER + assert len(spec["cases"]) > 5 + + def join(parts): + return "".join(text * n for text, n in parts) + + for case in spec["cases"]: + text, want = join(case["input"]), join(case["expected"]) + assert cut_report_detail(text, fixture["max"]) == want, case["name"] + # Arguments that are not JSON are kept whole as the detail, cut the same way. + assert _self_report.parse_arguments(text) == ("", want), case["name"] + for ws in spec["whitespace"]: + assert cut_report_detail("ok" + ws + "t" * 2100) == "ok", repr(ws) + assert cut_report_detail("ok\u00a0" + "t" * 2100) == DETAIL_CUT_MARKER diff --git a/sdk/python/tests/test_server_contract.py b/sdk/python/tests/test_server_contract.py index 794404dbf..76441e5c3 100644 --- a/sdk/python/tests/test_server_contract.py +++ b/sdk/python/tests/test_server_contract.py @@ -82,6 +82,7 @@ def _emit_everything(): ns.human_input(**ids, input_id="i1", response="y") ns.human_pause(**ids, reason="r", user_id="u") ns.human_interrupt(**ids, reason="r", user_id="u", at_step="1") + ns.self_report("looping", "d", **ids, tool_call_id="tc") return recorder.entries @@ -203,7 +204,7 @@ def test_a_reserved_name_is_rejected_by_every_event_method(): """One method forgetting `_validate_fields` would let a caller rewrite `type`.""" ns = EventNamespace(_Recorder()) methods = [m for m in dir(ns) if not m.startswith("_") and callable(getattr(ns, m))] - assert len(methods) == 15, f"expected 15 event methods, found {len(methods)}: {sorted(methods)}" + assert len(methods) == 16, f"expected 16 event methods, found {len(methods)}: {sorted(methods)}" required = { "tool_use": dict(tool_name="t", tool_call_id="c"), @@ -215,6 +216,7 @@ def test_a_reserved_name_is_rejected_by_every_event_method(): "human_input": dict(input_id="i"), "agent_pause": dict(pause_id="p"), "agent_resume": dict(pause_id="p"), + "self_report": dict(category="looping", detail="d"), } for method in methods: with pytest.raises(ValueError, match="Reserved field names"): @@ -609,6 +611,7 @@ def test_the_measured_and_the_caller_supplied_paths_enforce_the_same_range(): ("error", {"error_type": "E", "message": "m"}), ("human_wait", {"input_id": "i"}), ("human_input", {"input_id": "i"}), ("human_pause", {}), ("human_interrupt", {}), + ("self_report", {"category": "looping", "detail": "d"}), ] @@ -630,6 +633,11 @@ def test_a_non_string_session_id_is_refused_on_every_event(method, extra, bad): success, the collector deletes the batch, and the event is gone. `None` is the realistic way in — an uninitialised variable, a lookup that missed. """ + if method == "self_report" and bad is None: + # `None` means "resolve" on every method, and `self_report` alone never + # raises when nothing resolves: it files the report as "unattributed" + # (tests/test_self_report.py). The non-None bad values still raise. + pytest.skip("self_report resolves a None session instead of raising") ns = EventNamespace(_Recorder()) with pytest.raises(TypeError, match="session_id"): getattr(ns, method)(session_id=bad, agent_id="a", **extra) diff --git a/sdk/python/tests/test_wire_format.py b/sdk/python/tests/test_wire_format.py index 64b98457a..918eb0e19 100644 --- a/sdk/python/tests/test_wire_format.py +++ b/sdk/python/tests/test_wire_format.py @@ -49,6 +49,7 @@ "human_input": '{"timestamp": "2026-01-02T03:04:05.678901Z", "session_id": "sess-1", "agent_id": "agent-1", "type": "human_input", "input_id": "i-1", "environment": "prod", "response": "y", "duration_ms": 78}', "human_pause": '{"timestamp": "2026-01-02T03:04:05.678901Z", "session_id": "sess-1", "agent_id": "agent-1", "type": "human_pause", "environment": "prod", "reason": "lunch", "user_id": "u-1"}', "human_interrupt": '{"timestamp": "2026-01-02T03:04:05.678901Z", "session_id": "sess-1", "agent_id": "agent-1", "type": "human_interrupt", "environment": "prod", "reason": "stop", "user_id": "u-1", "at_step": "3"}', + "self_report": '{"timestamp": "2026-01-02T03:04:05.678901Z", "session_id": "sess-1", "agent_id": "agent-1", "type": "self_report", "category": "looping", "detail": "same search again", "source": "sdk", "environment": "prod", "tool_call_id": "tc-1"}', } @@ -71,6 +72,7 @@ def _events(): "human_input": s.HumanInputEvent(**BASE, input_id="i-1", response="y", duration_ms=78), "human_pause": s.HumanPauseEvent(**BASE, reason="lunch", user_id="u-1"), "human_interrupt": s.HumanInterruptEvent(**BASE, reason="stop", user_id="u-1", at_step="3"), + "self_report": s.SelfReportEvent(**BASE, category="looping", detail="same search again", tool_call_id="tc-1"), } diff --git a/sdk/typescript/CHANGELOG.md b/sdk/typescript/CHANGELOG.md index c7d1b111f..3133940a5 100644 --- a/sdk/typescript/CHANGELOG.md +++ b/sdk/typescript/CHANGELOG.md @@ -10,9 +10,39 @@ section is missing or empty is refused before anything is built. ## 0.0.1-beta.3 — 2026-11-24 +### Features + +- **Self Reports.** A `self_report` event (`event.selfReport` / `selfReport()`, + `source: "sdk"`) and the `failproofai_report` tool an agent calls when it is + stuck: `selfReportSpec()`, `openaiTool()`, `anthropicTool()`, `handleToolCall()` + and `isSelfReportTool()` in the core, and a ready-made `selfReportTool()` on + `/ai` (v4–v7, no zod), `/langchain`, `/mastra` and `/llamaindex`, inert in the + Edge build. Categories and guidance come from `$FAILPROOFAI_HOME/self-report.json` + (`selfReportSettings()`), with the six defaults when it is missing or disabled. + A report made inside a framework's tool loop joins the agent whose loop called + it, and never throws for want of a session; with no scope it joins an open + call only when all candidates are in one session, and a `toolCallId` open in + several sessions is never resolved by the tool name instead; with an explicit + `sessionId` the call id is taken only from the one open report call of that + session and agent. `detail` is cut to 2000 code points (as the daemon and the + Python SDK count) with no lone surrogate, and never with part + of a token left at the end: a credential running past the cut is dropped whole, + so upload redaction still recognises what is kept (a detail that is one long + token reads `[detail cut]`). `openaiResponsesTool()` sets + `strict: true`, as openai's `FunctionTool` type requires. The `/langchain` tool + also reads the call id from `configurable.tool_call_id`. The `/ai` tool carries both + schema keys for a `module` passed in, and the Edge `/langchain` tool builds a + real LangChain tool with a `module` passed in (the tool needs + `@langchain/core` 0.3.44 or later). + ### Fixes -- _Nothing yet._ +- **The `/langchain` report tool refuses an `@langchain/core` older than 0.3.44.** + Before 0.3.44 a tool's schema is read only as zod, so the model was offered + `failproofai_report` with an empty schema. `selfReportTool()` now throws a + `FailproofAICompatError` naming the version found and the upgrade. The peer + range stays `>=0.3.0 <2`: the tracer records the same trace on 0.3.0, 0.3.43 + and 0.3.44. A `module` passed in is not version-checked. ## 0.0.1-beta.2 — 2026-10-16 diff --git a/sdk/typescript/README.md b/sdk/typescript/README.md index 26d8cf653..891c2f34e 100644 --- a/sdk/typescript/README.md +++ b/sdk/typescript/README.md @@ -23,7 +23,7 @@ and `failproofaid` — the daemon the `failproofai` CLI installs — picks them Nothing here opens a socket, and nothing blocks your agent loop on the network. This is the TypeScript counterpart to the Python -[`failproofai-sdk`](https://pypi.org/project/failproofai-sdk/). Same 15 events, +[`failproofai-sdk`](https://pypi.org/project/failproofai-sdk/). Same 16 events, same wire format, same spool directory: a fleet running both writes into one pipe, and the dashboard cannot tell which language wrote what. @@ -341,6 +341,9 @@ The 15 event methods, for anything the adapters do not cover: `agentEnd` · `agentPause` · `agentResume` · `hookTriggered` · `hookCompleted` · `error` · `humanWait` · `humanInput` · `humanPause` · `humanInterrupt` +plus `selfReport(category, detail, options?)`, the `self_report` event (see +[Self Reports](#self-reports--let-the-agent-say-it-is-stuck)). + ```ts failproofai.event.humanWait({ inputId: "approval-1", prompt: "Ship it?" }); // …later, from anywhere in the same session: @@ -440,6 +443,79 @@ integration suite runs that file on every CI run, as an ES module and as CommonJS, against the real `openai` client — the example is proven, not just documented. +## Self Reports — let the agent say it is stuck + +Offer your agent one more tool, `failproofai_report`. When the model is blocked +(looping, a broken credential, a request it cannot do) it calls the tool, the SDK +records a `self_report` event in the current session and agent, and the call +answers `Recorded.`, so the loop carries on. The reports show up on the Self +Reports page in FailproofAI Cloud. + +With a framework, add the ready-made tool from its subpath: + +```ts +import { selfReportTool } from "@failproofai/sdk/ai"; // Vercel AI SDK 4–7 +await generateText({ model, prompt, tools: { failproofai_report: selfReportTool(), ...tools } }); + +import { selfReportTool } from "@failproofai/sdk/langchain"; // @langchain/core >=0.3.44 +createReactAgent({ llm, tools: [selfReportTool(), ...tools] }); + +import { selfReportTool } from "@failproofai/sdk/mastra"; // createTool + your zod +new Agent({ ...config, tools: { failproofai_report: selfReportTool(), ...tools } }); + +import { selfReportTool } from "@failproofai/sdk/llamaindex"; // a plain BaseTool +agent({ llm, tools: [selfReportTool(), ...tools] }); +``` + +With a provider SDK directly: + +```ts +const tools = [failproofai.openaiTool(), ...yours]; // or openaiResponsesTool(), anthropicTool() +// for each tool call the model makes: +const answer = failproofai.handleToolCall(call.name, call.arguments, { toolCallId: call.id }); +if (answer !== null) toolResults.push({ id: call.id, content: answer }); // "Recorded." +``` + +`handleToolCall` returns `null` for any other tool, accepts the arguments as an +object or as the JSON string a provider sent, and never throws. To record a +report from your own code, `failproofai.selfReport(category, detail)`. +`failproofai.selfReportSpec()` gives `{ name, description, inputSchema }` for any +other tool format. + +- **On by default.** The tool works as soon as you add it: no setting has to be + turned on first, and adding it is the opt-in. +- **Categories.** The tool's categories, and an optional paragraph of guidance, + come from `~/.failproofai/self-report.json` (`$FAILPROOFAI_HOME` moves it), which + the daemon writes for a Cloud-managed machine and the failproofai CLI writes + otherwise. A missing or disabled file means the six default + categories (`failproofai.DEFAULT_SELF_REPORT_CATEGORIES`). + `failproofai.selfReportSettings()` returns what the file says. +- **Where a report lands.** An explicit `sessionId`, else the open `tool_use` of + the report call that an adapter recorded (so inside a framework's tool loop it + joins that agent, even with no `failproofai` scope around it), else the + enclosing scope, else the session `unattributed` with one warning. A report + never throws for want of a session. +- **What is recorded.** `category` as the model gave it (an unknown one is kept), + `detail` cut to 2,000 characters, `source: "sdk"`, and `tool_call_id` when + there is one. +- **Frameworks stay optional.** Each tool loads its framework from your + application when you call it. Pass `{ module }` to use a specific copy (a + bundled one, or the ES-module copy in an ESM app): + `selfReportTool({ module: await import("@langchain/core/tools") })`. The AI SDK + tool needs no zod and works on v7, which cannot be `require`d, by building the + `jsonSchema()` object itself. The LangChain, Mastra and LlamaIndex tools return + `unknown` unless you name the type, as above. +- **LangChain needs `@langchain/core` 0.3.44 or later for this tool**: older + 0.3 releases read a tool's schema only as zod and send the model an empty one, + so on them `selfReportTool()` throws a `FailproofAICompatError` that says so + (the tracer still works from 0.3.0). A `module` you pass in is not checked. +- **Edge builds** offer the same spec and tools, which answer `Recorded.` and + record nothing. The Edge LangChain tool is a real LangChain tool when you pass + `{ module: await import("@langchain/core/tools") }`; without it, it is a plain + named-tool object that `@langchain/core` 0.3.52 and later recognise. + +--- + ## Configuration ```ts diff --git a/sdk/typescript/integration/ai.test.ts b/sdk/typescript/integration/ai.test.ts index dd5921685..20b27e1cc 100644 --- a/sdk/typescript/integration/ai.test.ts +++ b/sdk/typescript/integration/ai.test.ts @@ -135,6 +135,37 @@ describe.each(FIXTURES)("%s", (fixture) => { expect(result.stdout).toContain("It is 20C in Paris."); }); + it("records a Self Report inside a scope, on the agent whose loop called the tool", () => { + const result = run("self-report"); + expect(result.stdout).toContain("It is 20C in Paris."); + const reports = ofType(result.events, "self_report"); + expect(reports, describeTrace(result)).toHaveLength(1); + expect(reports[0]).toMatchObject({ + session_id: "req-sr", + agent_id: "weather-agent", + category: "invalid_tool_or_credential", + detail: "The weather API rejected its key.", + source: "sdk", + tool_call_id: "call-r1", + }); + const done = ofType(result.events, "tool_result").find((e) => e.tool_name === "failproofai_report")!; + expect(JSON.stringify(done.output), describeTrace(result)).toContain("Recorded."); + expect(traceViolations(result.events), describeTrace(result)).toEqual([]); + }); + + it("attributes a Self Report with no scope to the run the adapter recorded", () => { + const result = run("self-report-bare"); + const [report] = ofType(result.events, "self_report"); + const use = ofType(result.events, "tool_use").find((e) => e.tool_name === "failproofai_report")!; + expect(report, describeTrace(result)).toMatchObject({ + session_id: use.session_id, + agent_id: "weather-agent", + tool_call_id: "call-r1", + source: "sdk", + }); + expect(report!.session_id).not.toBe("unattributed"); + }); + it("records streamText like generateText, and stamps the request when it is made", () => { const result = run("stream"); const { events } = result; diff --git a/sdk/typescript/integration/fixtures/ai-4/agent.ts b/sdk/typescript/integration/fixtures/ai-4/agent.ts index 2c556f23d..1fad9053c 100644 --- a/sdk/typescript/integration/fixtures/ai-4/agent.ts +++ b/sdk/typescript/integration/fixtures/ai-4/agent.ts @@ -12,7 +12,7 @@ import { createRequire } from "node:module"; import { join } from "node:path"; import * as failproofai from "@failproofai/sdk"; -import { middleware, telemetry, tracer, wrapModel } from "@failproofai/sdk/ai"; +import { middleware, selfReportTool, telemetry, tracer, wrapModel } from "@failproofai/sdk/ai"; import { generateObject, generateText, @@ -27,7 +27,7 @@ import { z } from "zod"; // --- version-specific: LanguageModelV1 (promptTokens/completionTokens, `text` + `toolCalls`) -type Script = "loop" | "answer" | "object" | "fail"; +type Script = "loop" | "answer" | "object" | "fail" | "report"; type StreamPart = Awaited>["stream"] extends ReadableStream ? P : never; const usage = (input: number, output: number) => ({ promptTokens: input, completionTokens: output }); @@ -45,6 +45,14 @@ function scripted(script: Script = "loop") { generated += 1; if (script === "fail") throw new Error("model exploded"); if (script === "object") return { text: '{"city":"Paris"}', finishReason: "stop", usage: usage(5, 3), rawCall }; + if (script === "report" && generated === 1) { + return { + toolCalls: [{ toolCallType: "function", toolCallId: "call-r1", toolName: "failproofai_report", args: '{"category":"invalid_tool_or_credential","detail":"The weather API rejected its key."}' }], + finishReason: "tool-calls", + usage: usage(11, 7), + rawCall, + }; + } if (script === "loop" && generated === 1) { return { toolCalls: [{ toolCallType: "function", toolCallId: "call-1", toolName: "weather", args: '{"city":"Paris"}' }], @@ -322,6 +330,31 @@ async function main(scenario: string): Promise { failproofai.agent("planner", { goal: "plan" }, () => ask(scripted(), { telemetry: telemetry({ functionId: "weather-agent" }) })), ); break; + case "self-report": + await failproofai.session({ sessionId: "req-sr" }, () => + failproofai.agent("planner", { goal: "plan" }, async () => { + const { text } = await generateText({ + model: scripted("report"), + prompt: "Weather in Paris?", + tools: { failproofai_report: selfReportTool(), ...makeTools() }, + ...loop, + experimental_telemetry: telemetry({ functionId: "weather-agent" }), + }); + report({ text }); + }), + ); + break; + case "self-report-bare": { + const { text } = await generateText({ + model: scripted("report"), + prompt: "Weather in Paris?", + tools: { failproofai_report: selfReportTool() }, + ...loop, + experimental_telemetry: telemetry({ functionId: "weather-agent" }), + }); + report({ text }); + break; + } case "readme": await readme(); break; diff --git a/sdk/typescript/integration/fixtures/ai-5/agent.ts b/sdk/typescript/integration/fixtures/ai-5/agent.ts index 247d4fd99..3138590f7 100644 --- a/sdk/typescript/integration/fixtures/ai-5/agent.ts +++ b/sdk/typescript/integration/fixtures/ai-5/agent.ts @@ -12,7 +12,7 @@ import { createRequire } from "node:module"; import { join } from "node:path"; import * as failproofai from "@failproofai/sdk"; -import { middleware, telemetry, tracer, wrapModel } from "@failproofai/sdk/ai"; +import { middleware, selfReportTool, telemetry, tracer, wrapModel } from "@failproofai/sdk/ai"; import { generateObject, generateText, @@ -28,7 +28,7 @@ import { z } from "zod"; // --- version-specific: LanguageModelV2 (flat usage numbers, string finish reasons) -type Script = "loop" | "answer" | "object" | "fail"; +type Script = "loop" | "answer" | "object" | "fail" | "report"; type StreamPart = Awaited>["stream"] extends ReadableStream ? P : never; const usage = (input: number, output: number) => ({ inputTokens: input, outputTokens: output, totalTokens: input + output }); @@ -45,6 +45,14 @@ function scripted(script: Script = "loop") { if (script === "object") { return { content: [{ type: "text", text: '{"city":"Paris"}' }], finishReason: "stop", usage: usage(5, 3), warnings: [] }; } + if (script === "report" && generated === 1) { + return { + content: [{ type: "tool-call", toolCallId: "call-r1", toolName: "failproofai_report", input: '{"category":"invalid_tool_or_credential","detail":"The weather API rejected its key."}' }], + finishReason: "tool-calls", + usage: usage(11, 7), + warnings: [], + }; + } if (script === "loop" && generated === 1) { return { content: [{ type: "tool-call", toolCallId: "call-1", toolName: "weather", input: '{"city":"Paris"}' }], @@ -327,6 +335,31 @@ async function main(scenario: string): Promise { failproofai.agent("planner", { goal: "plan" }, () => ask(scripted(), { telemetry: telemetry({ functionId: "weather-agent" }) })), ); break; + case "self-report": + await failproofai.session({ sessionId: "req-sr" }, () => + failproofai.agent("planner", { goal: "plan" }, async () => { + const { text } = await generateText({ + model: scripted("report"), + prompt: "Weather in Paris?", + tools: { failproofai_report: selfReportTool(), ...makeTools() }, + ...loop, + experimental_telemetry: telemetry({ functionId: "weather-agent" }), + }); + report({ text }); + }), + ); + break; + case "self-report-bare": { + const { text } = await generateText({ + model: scripted("report"), + prompt: "Weather in Paris?", + tools: { failproofai_report: selfReportTool() }, + ...loop, + experimental_telemetry: telemetry({ functionId: "weather-agent" }), + }); + report({ text }); + break; + } case "readme": await readme(); break; diff --git a/sdk/typescript/integration/fixtures/ai-6/agent.ts b/sdk/typescript/integration/fixtures/ai-6/agent.ts index 83ec01a7b..aca4a670c 100644 --- a/sdk/typescript/integration/fixtures/ai-6/agent.ts +++ b/sdk/typescript/integration/fixtures/ai-6/agent.ts @@ -12,7 +12,7 @@ import { createRequire } from "node:module"; import { join } from "node:path"; import * as failproofai from "@failproofai/sdk"; -import { middleware, telemetry, tracer, wrapModel } from "@failproofai/sdk/ai"; +import { middleware, selfReportTool, telemetry, tracer, wrapModel } from "@failproofai/sdk/ai"; import { generateObject, generateText, @@ -28,7 +28,7 @@ import { z } from "zod"; // --- version-specific: LanguageModelV3 (usage objects, finishReason objects) -type Script = "loop" | "answer" | "object" | "fail"; +type Script = "loop" | "answer" | "object" | "fail" | "report"; type StreamPart = Awaited>["stream"] extends ReadableStream ? P : never; const usage = (input: number, output: number) => ({ @@ -49,6 +49,14 @@ function scripted(script: Script = "loop") { if (script === "object") { return { content: [{ type: "text", text: '{"city":"Paris"}' }], finishReason: finish("stop"), usage: usage(5, 3), warnings: [] }; } + if (script === "report" && generated === 1) { + return { + content: [{ type: "tool-call", toolCallId: "call-r1", toolName: "failproofai_report", input: '{"category":"invalid_tool_or_credential","detail":"The weather API rejected its key."}' }], + finishReason: finish("tool-calls"), + usage: usage(11, 7), + warnings: [], + }; + } if (script === "loop" && generated === 1) { return { content: [{ type: "tool-call", toolCallId: "call-1", toolName: "weather", input: '{"city":"Paris"}' }], @@ -331,6 +339,31 @@ async function main(scenario: string): Promise { failproofai.agent("planner", { goal: "plan" }, () => ask(scripted(), { telemetry: telemetry({ functionId: "weather-agent" }) })), ); break; + case "self-report": + await failproofai.session({ sessionId: "req-sr" }, () => + failproofai.agent("planner", { goal: "plan" }, async () => { + const { text } = await generateText({ + model: scripted("report"), + prompt: "Weather in Paris?", + tools: { failproofai_report: selfReportTool(), ...makeTools() }, + ...loop, + experimental_telemetry: telemetry({ functionId: "weather-agent" }), + }); + report({ text }); + }), + ); + break; + case "self-report-bare": { + const { text } = await generateText({ + model: scripted("report"), + prompt: "Weather in Paris?", + tools: { failproofai_report: selfReportTool() }, + ...loop, + experimental_telemetry: telemetry({ functionId: "weather-agent" }), + }); + report({ text }); + break; + } case "readme": await readme(); break; diff --git a/sdk/typescript/integration/fixtures/ai-7/agent.ts b/sdk/typescript/integration/fixtures/ai-7/agent.ts index c8049f764..d85450db1 100644 --- a/sdk/typescript/integration/fixtures/ai-7/agent.ts +++ b/sdk/typescript/integration/fixtures/ai-7/agent.ts @@ -13,7 +13,7 @@ import { createRequire } from "node:module"; import { join } from "node:path"; import * as failproofai from "@failproofai/sdk"; -import { middleware, telemetry, wrapModel } from "@failproofai/sdk/ai"; +import { middleware, selfReportTool, telemetry, wrapModel } from "@failproofai/sdk/ai"; import { generateObject, generateText, @@ -29,7 +29,7 @@ import { z } from "zod"; // --- version-specific: LanguageModelV4 (usage objects, finishReason objects) -type Script = "loop" | "answer" | "object" | "fail"; +type Script = "loop" | "answer" | "object" | "fail" | "report"; type StreamPart = Awaited>["stream"] extends ReadableStream ? P : never; const usage = (input: number, output: number) => ({ @@ -50,6 +50,14 @@ function scripted(script: Script = "loop") { if (script === "object") { return { content: [{ type: "text", text: '{"city":"Paris"}' }], finishReason: finish("stop"), usage: usage(5, 3), warnings: [] }; } + if (script === "report" && generated === 1) { + return { + content: [{ type: "tool-call", toolCallId: "call-r1", toolName: "failproofai_report", input: '{"category":"invalid_tool_or_credential","detail":"The weather API rejected its key."}' }], + finishReason: finish("tool-calls"), + usage: usage(11, 7), + warnings: [], + }; + } if (script === "loop" && generated === 1) { return { content: [{ type: "tool-call", toolCallId: "call-1", toolName: "weather", input: '{"city":"Paris"}' }], @@ -335,6 +343,31 @@ async function main(scenario: string): Promise { failproofai.agent("planner", { goal: "plan" }, () => ask(scripted(), { telemetry: telemetry({ functionId: "weather-agent" }) })), ); break; + case "self-report": + await failproofai.session({ sessionId: "req-sr" }, () => + failproofai.agent("planner", { goal: "plan" }, async () => { + const { text } = await generateText({ + model: scripted("report"), + prompt: "Weather in Paris?", + tools: { failproofai_report: selfReportTool(), ...makeTools() }, + ...loop, + experimental_telemetry: telemetry({ functionId: "weather-agent" }), + }); + report({ text }); + }), + ); + break; + case "self-report-bare": { + const { text } = await generateText({ + model: scripted("report"), + prompt: "Weather in Paris?", + tools: { failproofai_report: selfReportTool() }, + ...loop, + experimental_telemetry: telemetry({ functionId: "weather-agent" }), + }); + report({ text }); + break; + } case "readme": await readme(); break; diff --git a/sdk/typescript/integration/fixtures/langchain-0.3/agent.ts b/sdk/typescript/integration/fixtures/langchain-0.3/agent.ts index 935224f11..9ada7a96f 100644 --- a/sdk/typescript/integration/fixtures/langchain-0.3/agent.ts +++ b/sdk/typescript/integration/fixtures/langchain-0.3/agent.ts @@ -14,7 +14,7 @@ import { spawnSync } from "node:child_process"; import { readFileSync, rmSync, writeFileSync } from "node:fs"; import * as failproofai from "@failproofai/sdk"; -import { langchainHandler } from "@failproofai/sdk/langchain"; +import { langchainHandler, selfReportTool } from "@failproofai/sdk/langchain"; import type { CallbackManagerForLLMRun } from "@langchain/core/callbacks/manager"; import { Document } from "@langchain/core/documents"; import { Embeddings } from "@langchain/core/embeddings"; @@ -35,7 +35,7 @@ import { RunnableSequence, type RunnableConfig, } from "@langchain/core/runnables"; -import { tool } from "@langchain/core/tools"; +import { tool, type StructuredToolInterface } from "@langchain/core/tools"; import { convertToOpenAITool } from "@langchain/core/utils/function_calling"; import { VectorStore } from "@langchain/core/vectorstores"; import { Annotation, Command, END, MemorySaver, MessagesAnnotation, START, StateGraph, interrupt } from "@langchain/langgraph"; @@ -80,6 +80,29 @@ class ScriptedModel extends BaseChatModel { } } +/** Calls the Self Reports tool once, then answers. */ +class ReportModel extends ScriptedModel { + override async _generate(messages: BaseMessage[]): Promise { + this.calls += 1; + const answered = messages.some((m) => m.getType() === "tool"); + const message = answered + ? new AIMessage({ content: "I could not reach the weather service.", response_metadata: { finish_reason: "stop" } }) + : new AIMessage({ + content: "", + tool_calls: [ + { + id: "call_r1", + name: "failproofai_report", + args: { category: "invalid_tool_or_credential", detail: "The weather API rejected its key." }, + type: "tool_call", + }, + ], + response_metadata: { finish_reason: "tool_calls" }, + }); + return { generations: [{ text: typeof message.content === "string" ? message.content : "", message }] }; + } +} + /** * A model that streams, the way a real provider integration does: one chunk * per piece, each reported through `handleLLMNewToken`. Five chunks, the same @@ -460,6 +483,17 @@ async function main(scenario: string): Promise { report({ answer: out.messages.at(-1)?.content }); break; } + case "self-report": { + const agent = createReactAgent({ + llm: new ReportModel(), + tools: [selfReportTool(), getWeather], + name: "react_bot", + }); + const out = await agent.invoke(question); + const toolMessage = out.messages.find((m) => m.getType() === "tool"); + report({ answer: out.messages.at(-1)?.content, toolResult: toolMessage?.content }); + break; + } case "error": { try { await buildGraph(new ScriptedModel({ fail: true })).invoke({ messages: [new HumanMessage("x")] }); diff --git a/sdk/typescript/integration/fixtures/langchain-1/agent.ts b/sdk/typescript/integration/fixtures/langchain-1/agent.ts index 935224f11..9ada7a96f 100644 --- a/sdk/typescript/integration/fixtures/langchain-1/agent.ts +++ b/sdk/typescript/integration/fixtures/langchain-1/agent.ts @@ -14,7 +14,7 @@ import { spawnSync } from "node:child_process"; import { readFileSync, rmSync, writeFileSync } from "node:fs"; import * as failproofai from "@failproofai/sdk"; -import { langchainHandler } from "@failproofai/sdk/langchain"; +import { langchainHandler, selfReportTool } from "@failproofai/sdk/langchain"; import type { CallbackManagerForLLMRun } from "@langchain/core/callbacks/manager"; import { Document } from "@langchain/core/documents"; import { Embeddings } from "@langchain/core/embeddings"; @@ -35,7 +35,7 @@ import { RunnableSequence, type RunnableConfig, } from "@langchain/core/runnables"; -import { tool } from "@langchain/core/tools"; +import { tool, type StructuredToolInterface } from "@langchain/core/tools"; import { convertToOpenAITool } from "@langchain/core/utils/function_calling"; import { VectorStore } from "@langchain/core/vectorstores"; import { Annotation, Command, END, MemorySaver, MessagesAnnotation, START, StateGraph, interrupt } from "@langchain/langgraph"; @@ -80,6 +80,29 @@ class ScriptedModel extends BaseChatModel { } } +/** Calls the Self Reports tool once, then answers. */ +class ReportModel extends ScriptedModel { + override async _generate(messages: BaseMessage[]): Promise { + this.calls += 1; + const answered = messages.some((m) => m.getType() === "tool"); + const message = answered + ? new AIMessage({ content: "I could not reach the weather service.", response_metadata: { finish_reason: "stop" } }) + : new AIMessage({ + content: "", + tool_calls: [ + { + id: "call_r1", + name: "failproofai_report", + args: { category: "invalid_tool_or_credential", detail: "The weather API rejected its key." }, + type: "tool_call", + }, + ], + response_metadata: { finish_reason: "tool_calls" }, + }); + return { generations: [{ text: typeof message.content === "string" ? message.content : "", message }] }; + } +} + /** * A model that streams, the way a real provider integration does: one chunk * per piece, each reported through `handleLLMNewToken`. Five chunks, the same @@ -460,6 +483,17 @@ async function main(scenario: string): Promise { report({ answer: out.messages.at(-1)?.content }); break; } + case "self-report": { + const agent = createReactAgent({ + llm: new ReportModel(), + tools: [selfReportTool(), getWeather], + name: "react_bot", + }); + const out = await agent.invoke(question); + const toolMessage = out.messages.find((m) => m.getType() === "tool"); + report({ answer: out.messages.at(-1)?.content, toolResult: toolMessage?.content }); + break; + } case "error": { try { await buildGraph(new ScriptedModel({ fail: true })).invoke({ messages: [new HumanMessage("x")] }); diff --git a/sdk/typescript/integration/fixtures/llamaindex-0.11/agent.ts b/sdk/typescript/integration/fixtures/llamaindex-0.11/agent.ts index 72266cd41..8fc752b8c 100644 --- a/sdk/typescript/integration/fixtures/llamaindex-0.11/agent.ts +++ b/sdk/typescript/integration/fixtures/llamaindex-0.11/agent.ts @@ -8,6 +8,7 @@ // assertions compare against the Python SDK's golden trace for the equivalent // `FunctionAgent` program. import * as failproofai from "@failproofai/sdk"; +import { selfReportTool } from "@failproofai/sdk/llamaindex"; import { wrapEventCaller, wrapLLMEvent } from "@llamaindex/core/decorator"; import { ToolCallLLM, @@ -334,6 +335,15 @@ async function main(scenario: string): Promise { const QUESTIONS = ["weather in Paris?", "weather in Rome?"]; switch (scenario) { + case "self-report": { + const turns: Turn[] = [ + { tool: { name: "failproofai_report", input: { category: "invalid_tool_or_credential", detail: "The weather API rejected its key." }, id: "call_r1" }, usage: { prompt_tokens: 12, completion_tokens: 5 } }, + { text: "I could not reach the weather service.", usage: { prompt_tokens: 30, completion_tokens: 7 } }, + ]; + const out = await agent({ llm: new ScriptedLLM(turns), tools: [selfReportTool(), getWeather] }).run(QUESTION); + report({ answer: out.data.result }); + break; + } case "workflow": { const out = await agent({ llm: new ScriptedLLM(), tools: [getWeather] }).run(QUESTION); report({ answer: out.data.result }); diff --git a/sdk/typescript/integration/fixtures/llamaindex-0.12/agent.ts b/sdk/typescript/integration/fixtures/llamaindex-0.12/agent.ts index 72266cd41..8fc752b8c 100644 --- a/sdk/typescript/integration/fixtures/llamaindex-0.12/agent.ts +++ b/sdk/typescript/integration/fixtures/llamaindex-0.12/agent.ts @@ -8,6 +8,7 @@ // assertions compare against the Python SDK's golden trace for the equivalent // `FunctionAgent` program. import * as failproofai from "@failproofai/sdk"; +import { selfReportTool } from "@failproofai/sdk/llamaindex"; import { wrapEventCaller, wrapLLMEvent } from "@llamaindex/core/decorator"; import { ToolCallLLM, @@ -334,6 +335,15 @@ async function main(scenario: string): Promise { const QUESTIONS = ["weather in Paris?", "weather in Rome?"]; switch (scenario) { + case "self-report": { + const turns: Turn[] = [ + { tool: { name: "failproofai_report", input: { category: "invalid_tool_or_credential", detail: "The weather API rejected its key." }, id: "call_r1" }, usage: { prompt_tokens: 12, completion_tokens: 5 } }, + { text: "I could not reach the weather service.", usage: { prompt_tokens: 30, completion_tokens: 7 } }, + ]; + const out = await agent({ llm: new ScriptedLLM(turns), tools: [selfReportTool(), getWeather] }).run(QUESTION); + report({ answer: out.data.result }); + break; + } case "workflow": { const out = await agent({ llm: new ScriptedLLM(), tools: [getWeather] }).run(QUESTION); report({ answer: out.data.result }); diff --git a/sdk/typescript/integration/fixtures/mastra-0/agent.ts b/sdk/typescript/integration/fixtures/mastra-0/agent.ts index 503fb8c04..cc56d6d3b 100644 --- a/sdk/typescript/integration/fixtures/mastra-0/agent.ts +++ b/sdk/typescript/integration/fixtures/mastra-0/agent.ts @@ -11,7 +11,7 @@ // the first call asks for a tool, the next one answers. Every agent gets its // own script so the token counts in the trace say which call they came from. import * as failproofai from "@failproofai/sdk"; -import { wrapTool } from "@failproofai/sdk/mastra"; +import { selfReportTool, wrapTool } from "@failproofai/sdk/mastra"; import { Agent } from "@mastra/core/agent"; import { createTool } from "@mastra/core/tools"; import { createStep, createWorkflow } from "@mastra/core/workflows"; @@ -414,6 +414,21 @@ async function main(scenario: string): Promise { report({ instrumented: await failproofai.instrument("mastra") }); switch (scenario) { + case "self-report": { + const reporting = new Agent({ + id: "weather-agent", + name: "weather-agent", + instructions: "Answer weather questions.", + model: scriptedModel([ + { tool: "failproofai_report", input: { category: "invalid_tool_or_credential", detail: "The weather API rejected its key." }, usage: [11, 7] }, + { text: "I could not reach the weather service.", usage: [23, 9] }, + ]) as never, + tools: { failproofai_report: selfReportTool() }, + }); + const out = await reporting.generate(question); + report({ answer: out.text }); + break; + } case "generate": { const out = await weatherAgent().generate(question); report({ answer: out.text }); diff --git a/sdk/typescript/integration/fixtures/mastra-1/agent.ts b/sdk/typescript/integration/fixtures/mastra-1/agent.ts index faefc8a01..8775f38b8 100644 --- a/sdk/typescript/integration/fixtures/mastra-1/agent.ts +++ b/sdk/typescript/integration/fixtures/mastra-1/agent.ts @@ -6,7 +6,7 @@ // the first call asks for a tool, the next one answers. Every agent gets its // own script so the token counts in the trace say which call they came from. import * as failproofai from "@failproofai/sdk"; -import { wrapTool } from "@failproofai/sdk/mastra"; +import { selfReportTool, wrapTool } from "@failproofai/sdk/mastra"; import { Agent } from "@mastra/core/agent"; import { createTool } from "@mastra/core/tools"; import { createStep, createWorkflow } from "@mastra/core/workflows"; @@ -409,6 +409,21 @@ async function main(scenario: string): Promise { report({ instrumented: await failproofai.instrument("mastra") }); switch (scenario) { + case "self-report": { + const reporting = new Agent({ + id: "weather-agent", + name: "weather-agent", + instructions: "Answer weather questions.", + model: scriptedModel([ + { tool: "failproofai_report", input: { category: "invalid_tool_or_credential", detail: "The weather API rejected its key." }, usage: [11, 7] }, + { text: "I could not reach the weather service.", usage: [23, 9] }, + ]) as never, + tools: { failproofai_report: selfReportTool() }, + }); + const out = await reporting.generate(question); + report({ answer: out.text }); + break; + } case "generate": { const out = await weatherAgent().generate(question); report({ answer: out.text }); diff --git a/sdk/typescript/integration/langchain.test.ts b/sdk/typescript/integration/langchain.test.ts index f45359645..501c48088 100644 --- a/sdk/typescript/integration/langchain.test.ts +++ b/sdk/typescript/integration/langchain.test.ts @@ -200,6 +200,23 @@ describe.each(FIXTURES)("%s", (fixture) => { expect(traceViolations(result.events), describeTrace(result)).toEqual([]); }); + it("records a Self Report on the agent whose loop called the tool", () => { + const result = run("self-report"); + expect(result.stdout).toContain('"toolResult":"Recorded."'); + const reports = ofType(result.events, "self_report"); + expect(reports, describeTrace(result)).toHaveLength(1); + const use = ofType(result.events, "tool_use").find((e) => e.tool_name === "failproofai_report")!; + expect(use, describeTrace(result)).toBeDefined(); + expect(reports[0]).toMatchObject({ + session_id: use.session_id, + agent_id: "react_bot", + category: "invalid_tool_or_credential", + detail: "The weather API rejected its key.", + source: "sdk", + }); + expect(traceViolations(result.events), describeTrace(result)).toEqual([]); + }); + it("records a failure once, where it happened", () => { const result = run("error"); expect(result.stdout).toContain("model exploded"); diff --git a/sdk/typescript/integration/llamaindex.test.ts b/sdk/typescript/integration/llamaindex.test.ts index c1ef8d864..1e83c1b83 100644 --- a/sdk/typescript/integration/llamaindex.test.ts +++ b/sdk/typescript/integration/llamaindex.test.ts @@ -97,6 +97,25 @@ describe.each(FIXTURES)("%s", (fixture) => { return result; }; + it("records a Self Report on the agent whose loop called the tool", () => { + const result = run("self-report"); + expect(result.stdout).toContain("I could not reach the weather service."); + const reports = ofType(result.events, "self_report"); + expect(reports, describeTrace(result)).toHaveLength(1); + const use = ofType(result.events, "tool_use").find((e) => e.tool_name === "failproofai_report")!; + expect(use, describeTrace(result)).toBeDefined(); + expect(reports[0]).toMatchObject({ + session_id: use.session_id, + agent_id: use.agent_id, + category: "invalid_tool_or_credential", + detail: "The weather API rejected its key.", + source: "sdk", + }); + const done = ofType(result.events, "tool_result").find((e) => e.tool_name === "failproofai_report")!; + expect(JSON.stringify(done.output), describeTrace(result)).toContain("Recorded."); + expect(traceViolations(result.events), describeTrace(result)).toEqual([]); + }); + it("records a workflow agent run as one agent with its steps as hooks", () => { const result = run("workflow"); expect(shape(result.events), describeTrace(result)).toEqual(WORKFLOW()); diff --git a/sdk/typescript/integration/mastra.test.ts b/sdk/typescript/integration/mastra.test.ts index 3ca46e00a..b72389a99 100644 --- a/sdk/typescript/integration/mastra.test.ts +++ b/sdk/typescript/integration/mastra.test.ts @@ -69,6 +69,25 @@ describe.each(FIXTURES)("%s", (fixture) => { return result; }; + it("records a Self Report on the agent whose loop called the tool", () => { + const result = run("self-report"); + expect(result.stdout).toContain("I could not reach the weather service."); + const reports = ofType(result.events, "self_report"); + expect(reports, describeTrace(result)).toHaveLength(1); + const use = ofType(result.events, "tool_use").find((e) => e.tool_name === "failproofai_report")!; + expect(use, describeTrace(result)).toBeDefined(); + expect(reports[0]).toMatchObject({ + session_id: use.session_id, + agent_id: use.agent_id, + category: "invalid_tool_or_credential", + detail: "The weather API rejected its key.", + source: "sdk", + }); + const done = ofType(result.events, "tool_result").find((e) => e.tool_name === "failproofai_report")!; + expect(JSON.stringify(done.output), describeTrace(result)).toContain("Recorded."); + expect(traceViolations(result.events), describeTrace(result)).toEqual([]); + }); + it("records generate() as one agent with one model pair per LLM step", () => { const result = run("generate"); expect(shape(result.events), describeTrace(result)).toEqual(LOOP); diff --git a/sdk/typescript/src/edge/ai.ts b/sdk/typescript/src/edge/ai.ts index c8ab09cd3..f100231db 100644 --- a/sdk/typescript/src/edge/ai.ts +++ b/sdk/typescript/src/edge/ai.ts @@ -9,6 +9,7 @@ import { noopAdapter } from "./adapter.js"; import { notice } from "./notice.js"; +import { inertAiTool } from "./self-report-tool.js"; type AttributeValue = string | number | boolean | Array; @@ -114,3 +115,9 @@ export function wrapTools(tools: T): T { } export const adapter = noopAdapter("ai"); + +/** The Self Reports tool, answering `Recorded.` and recording nothing. */ +export function selfReportTool(...options: unknown[]): T { + void options; + return inertAiTool(); +} diff --git a/sdk/typescript/src/edge/index.ts b/sdk/typescript/src/edge/index.ts index ec508f60b..5061766e1 100644 --- a/sdk/typescript/src/edge/index.ts +++ b/sdk/typescript/src/edge/index.ts @@ -36,9 +36,29 @@ import type { ToolCallFn, ToolCallOptions, } from "../scopes.js"; +import { + SELF_REPORT_RESULT, + buildSelfReportSpec, + defaultCategories, + isSelfReportTool, + toAnthropicTool, + toOpenAIResponsesTool, + toOpenAITool, + type AnthropicTool, + type OpenAIResponsesTool, + type OpenAITool, + type SelfReportSpec, +} from "../self-report-spec.js"; import { VERSION } from "../version.js"; import { notice } from "./notice.js"; +export { + DEFAULT_SELF_REPORT_CATEGORIES, + SELF_REPORT_RESULT, + SELF_REPORT_TOOL_NAME, + isSelfReportTool, +} from "../self-report-spec.js"; + export { VERSION as version }; export const DEFAULT_AGENT_ID = "main"; @@ -206,9 +226,10 @@ const EVENT_METHODS = [ "humanInput", "humanPause", "humanInterrupt", + "selfReport", ] as const; -/** The 15 event methods, each accepting its options and recording nothing. */ +/** The event methods, each accepting its options and recording nothing. */ export const event: EventNamespace = Object.freeze( Object.fromEntries(EVENT_METHODS.map((name) => [name, () => notice()])), ) as unknown as EventNamespace; @@ -245,3 +266,50 @@ export function availableFrameworks(): never[] { export function activeFrameworks(): never[] { return []; } + +// -- Self Reports: the same tool, recording nothing ---------------------------- +// +// No settings file can be read here, so the spec always carries the default +// categories. A report call still answers `Recorded.`: the model's loop must go +// on exactly as it would in Node. + +export function selfReportSettings(): { + enabled: false; + source: null; + categories: ReturnType; + guidance: null; + mcp: null; + updatedAt: null; +} { + return { enabled: false, source: null, categories: defaultCategories(), guidance: null, mcp: null, updatedAt: null }; +} + +export function selfReportSettingsPath(): string { + return "~/.failproofai/self-report.json"; +} + +export function selfReportSpec(): SelfReportSpec { + return buildSelfReportSpec(defaultCategories()); +} + +export function openaiTool(): OpenAITool { + return toOpenAITool(selfReportSpec()); +} + +export function openaiResponsesTool(): OpenAIResponsesTool { + return toOpenAIResponsesTool(selfReportSpec()); +} + +export function anthropicTool(): AnthropicTool { + return toAnthropicTool(selfReportSpec()); +} + +export function selfReport(): void { + notice(); +} + +export function handleToolCall(name: string): string | null { + if (!isSelfReportTool(name)) return null; + notice(); + return SELF_REPORT_RESULT; +} diff --git a/sdk/typescript/src/edge/langchain.ts b/sdk/typescript/src/edge/langchain.ts index 968789975..49b1c314d 100644 --- a/sdk/typescript/src/edge/langchain.ts +++ b/sdk/typescript/src/edge/langchain.ts @@ -2,6 +2,7 @@ import { noopAdapter } from "./adapter.js"; import { notice } from "./notice.js"; +import { inertLangChainTool, type EdgeLangChainToolsModule } from "./self-report-tool.js"; export const SESSION_METADATA_KEY = "failproofai_sdk_session_id"; @@ -16,3 +17,13 @@ export function langchainHandler(): Record { } export const adapter = noopAdapter("langchain"); + +/** + * The Self Reports tool, answering `Recorded.` and recording nothing. Pass the + * application's `@langchain/core/tools` as `module` to get a real LangChain + * structured tool (recognised by every `@langchain/core` from 0.3.44); without + * it, a plain named-tool object that 0.3.52 and later recognise. + */ +export function selfReportTool(options?: { module?: EdgeLangChainToolsModule } & Record): T { + return inertLangChainTool(options?.module); +} diff --git a/sdk/typescript/src/edge/llamaindex.ts b/sdk/typescript/src/edge/llamaindex.ts index b54121461..4c8c09e12 100644 --- a/sdk/typescript/src/edge/llamaindex.ts +++ b/sdk/typescript/src/edge/llamaindex.ts @@ -2,6 +2,7 @@ import { noopAdapter } from "./adapter.js"; import { notice } from "./notice.js"; +import { inertNamedTool } from "./self-report-tool.js"; /** Attaching to a LlamaIndex object records nothing here; returns a detach. */ export function attach(): () => void { @@ -10,3 +11,9 @@ export function attach(): () => void { } export const adapter = noopAdapter("llamaindex"); + +/** The Self Reports tool, answering `Recorded.` and recording nothing. */ +export function selfReportTool(...options: unknown[]): T { + void options; + return inertNamedTool(); +} diff --git a/sdk/typescript/src/edge/mastra.ts b/sdk/typescript/src/edge/mastra.ts index 5ae3bfb30..d11c3cde8 100644 --- a/sdk/typescript/src/edge/mastra.ts +++ b/sdk/typescript/src/edge/mastra.ts @@ -2,6 +2,7 @@ import { noopAdapter } from "./adapter.js"; import { notice } from "./notice.js"; +import { inertNamedTool } from "./self-report-tool.js"; export function wrapTool(tool: T): T { notice(); @@ -15,3 +16,9 @@ export function workflow(workflowName: string, body: () => T): T { } export const adapter = noopAdapter("mastra"); + +/** The Self Reports tool, answering `Recorded.` and recording nothing. */ +export function selfReportTool(...options: unknown[]): T { + void options; + return inertNamedTool(); +} diff --git a/sdk/typescript/src/edge/self-report-tool.ts b/sdk/typescript/src/edge/self-report-tool.ts new file mode 100644 index 000000000..6c5acef9d --- /dev/null +++ b/sdk/typescript/src/edge/self-report-tool.ts @@ -0,0 +1,81 @@ +/** + * The Self Reports tool for runtimes with no filesystem — see `./index.ts`. + * + * Each framework subpath's `selfReportTool()` returns a tool that offers the + * same name, description and schema and answers `Recorded.`, recording + * nothing. No framework is loaded: these are plain objects in the shape each + * framework reads. + */ + +import { + SELF_REPORT_RESULT, + SELF_REPORT_TOOL_NAME, + buildSelfReportSpec, + defaultCategories, +} from "../self-report-spec.js"; +import { notice } from "./notice.js"; + +export function inertSpec() { + return buildSelfReportSpec(defaultCategories()); +} + +export function inertAnswer(): Promise { + notice(); + return Promise.resolve(SELF_REPORT_RESULT); +} + +/** The AI SDK shape: a `jsonSchema()` result under both v4 and v5+ keys. */ +export function inertAiTool(): T { + const spec = inertSpec(); + const schema = { + [Symbol.for("vercel.ai.schema")]: true, + _type: undefined, + [Symbol.for("vercel.ai.validator")]: true, + jsonSchema: spec.inputSchema, + validate: undefined, + }; + return { description: spec.description, inputSchema: schema, parameters: schema, execute: inertAnswer } as T; +} + +/** A structured-tool-like object: `name`, `description`, `schema`, and every call entry point. */ +export function inertNamedTool(): T { + const spec = inertSpec(); + return { + name: SELF_REPORT_TOOL_NAME, + id: SELF_REPORT_TOOL_NAME, + description: spec.description, + schema: spec.inputSchema, + inputSchema: spec.inputSchema, + metadata: { name: SELF_REPORT_TOOL_NAME, description: spec.description, parameters: spec.inputSchema }, + invoke: inertAnswer, + call: inertAnswer, + func: inertAnswer, + execute: inertAnswer, + } as T; +} + +/** The `@langchain/core/tools` exports the Edge LangChain tool can build with. */ +export interface EdgeLangChainToolsModule { + tool?: (func: never, fields: never) => unknown; + DynamicStructuredTool?: new (fields: never) => unknown; +} + +/** + * The LangChain report tool for runtimes with no filesystem. Handed the + * application's `@langchain/core/tools` (`{ module: await import(...) }`), it is + * a real structured tool built by that module, which every `@langchain/core` + * from 0.3.44 converts for the model and runs like any other. Without one it is + * the plain named-tool object: `@langchain/core` 0.3.52 and later recognise it + * as a tool (name + JSON Schema); older ones would pass it to the model as it + * is, so pass the module there. No framework is ever imported here. + */ +export function inertLangChainTool(module?: EdgeLangChainToolsModule): T { + const spec = inertSpec(); + const fields = { name: SELF_REPORT_TOOL_NAME, description: spec.description, schema: spec.inputSchema }; + const func = () => inertAnswer(); + if (typeof module?.tool === "function") return module.tool(func as never, fields as never) as T; + if (typeof module?.DynamicStructuredTool === "function") { + return new module.DynamicStructuredTool({ ...fields, func } as never) as T; + } + return inertNamedTool(); +} diff --git a/sdk/typescript/src/events.ts b/sdk/typescript/src/events.ts index 4f7e411f1..8ec02f47e 100644 --- a/sdk/typescript/src/events.ts +++ b/sdk/typescript/src/events.ts @@ -14,12 +14,14 @@ import { humanWaitEvent, modelRequestEvent, modelResponseEvent, + selfReportEvent, toolResultEvent, toolUseEvent, } from "./schema.js"; import type { EventWriter } from "./writer.js"; import { formatMicros, nowMicros } from "./clock.js"; import { fatalSuffix, onProcessExit, type OpenItem } from "./exit.js"; +import { SELF_REPORT_DETAIL_LIMIT, clipDetail, clipReportText, isSelfReportTool } from "./self-report-spec.js"; /** * `sessionId` and `agentId` are named options on every method, so a caller @@ -397,6 +399,27 @@ export interface HumanInterruptOptions extends BaseEventOptions { atStep?: string | null; } +/** + * The options `selfReport` takes beside its category and detail. `toolCallId` + * is the model's id for the report call, when there was one: it is recorded, + * and it is how a report made from inside a framework's tool loop finds the + * agent whose loop called it. + */ +export interface SelfReportOptions extends BaseEventOptions { + toolCallId?: string | null; +} + +/** + * The session a report goes to when nothing names one — the same placeholder + * the MCP server uses. A report is never dropped and never throws for want of + * a session: an agent that is stuck is precisely the one whose run may have + * lost its scope. + */ +export const UNATTRIBUTED_SESSION = "unattributed"; + +/** Keys `selfReport` sets itself; an extra of the same name would overwrite them. */ +const SELF_REPORT_OWN: ReadonlySet = new Set(["category", "detail", "source", "tool_call_id"]); + type Extras = Record; /** A tool call, hook or model call opened and not yet closed. */ @@ -802,6 +825,115 @@ export class EventNamespace { ); } + /** + * `self_report` — the agent says it is stuck (Self Reports). + * + * `category` is recorded as given, known or not; a missing `detail` is + * recorded as `""`, and a longer one is cut to 2000 characters. `source` is + * always `"sdk"`. + * + * Identity, most specific first: an explicit `sessionId`; the open + * `tool_use` for `toolCallId` (or, with no id, for a report-tool name) that + * an adapter or a `toolCall()` scope recorded — so a report made inside a + * framework's tool loop lands on the agent whose loop called it; the + * enclosing scope; and last `"unattributed"`, with one warning. Unlike every + * other event method a missing session never throws. With no `toolCallId` + * given, the report takes the id of the open report-tool `tool_use` it was + * matched to (with an explicit `sessionId`, of the one such call open for + * that session and agent; none when several are). + */ + selfReport(category: string, detail?: string | null, options: SelfReportOptions = {}): void { + const { sessionId, agentId, toolCallId, ...fields } = options; + const own = Object.keys(fields).filter((key) => SELF_REPORT_OWN.has(key)); + if (own.length > 0) { + throw new Error( + `selfReport sets ${JSON.stringify(own.sort())} itself; they cannot be passed as custom fields`, + ); + } + this.validateFields(fields); + const callId = typeof toolCallId === "string" && toolCallId !== "" ? toolCallId : undefined; + const [sid, aid, matchedCallId] = this.reportIdentity(sessionId, agentId, callId); + this.writer.submit( + selfReportEvent({ + timestamp: this.fmtTs(this.now()), + sessionId: sid, + agentId: aid, + category: clipReportText( + typeof category === "string" ? category : category === undefined || category === null ? "" : String(category), + Infinity, + ), + detail: clipDetail(typeof detail === "string" ? detail : detail === undefined || detail === null ? "" : String(detail)), + source: "sdk", + toolCallId: callId ?? matchedCallId, + extraFields: fields, + }), + ); + } + + private warnedUnattributed = false; + + private reportIdentity( + sessionId: string | null | undefined, + agentId: string | null | undefined, + toolCallId: string | undefined, + ): [string, string, string | undefined] { + if (sessionId !== undefined && sessionId !== null) { + // An explicit session (a tool that resolved it itself) still takes the + // id of the report-tool call open in that session for that agent, when + // it has none — but only of the one such call: with two open (parallel + // calls) the id would be a guess. The agent is resolved first. + const [sid, aid] = resolveIdentity(sessionId, agentId); + if (toolCallId !== undefined) return [sid, aid, undefined]; + const open = [...this.openLeaves.values()].filter( + (leaf) => leaf.kind === "tool" && leaf.sessionId === sid && leaf.agentId === aid && isSelfReportTool(leaf.name), + ); + return [sid, aid, open.length === 1 ? open[0]!.id : undefined]; + } + const ambient = context.sessionId(); + const leaf = this.openToolFor(toolCallId, ambient); + if (leaf !== undefined) { + const aid = agentId ?? leaf.agentId; + validateIdentity("agentId", aid); + // The matched call's own id, so a tool that cannot see the model's call + // id (LlamaIndex) still joins the `tool_use` the adapter recorded. + return [leaf.sessionId, aid, leaf.id]; + } + if (ambient !== null) return [...resolveIdentity(null, agentId), undefined]; + if (!this.warnedUnattributed) { + this.warnedUnattributed = true; + logger.warn( + `selfReport found no session to record into and filed it under "${UNATTRIBUTED_SESSION}". ` + + "Call it inside `failproofai.session(fn)` / `failproofai.agent('name', fn)`, or pass sessionId. " + + "This is logged once.", + ); + } + const aid = agentId ?? context.agentId(); + validateIdentity("agentId", aid); + return [UNATTRIBUTED_SESSION, aid, undefined]; + } + + /** + * The newest open tool call a report belongs to: the one with this id, else + * — only when no open call has that id, or none was given — one named like + * the report tool (LlamaIndex gives a tool no id, and an adapter may have + * recorded its own id rather than the model's). Inside a scope only that + * scope's session is searched. With no scope, a match is used only when + * every candidate is in one session: picking the newest of several sessions + * (two concurrent LlamaIndex runs, each with a report call open) would be a + * guess, and the report goes the unattributed way instead. An id open in + * several sessions is the same guess, and does not fall back to the name. + */ + private openToolFor(toolCallId: string | undefined, preferSession: string | null): OpenLeaf | undefined { + const leaves = [...this.openLeaves.values()] + .filter((leaf) => leaf.kind === "tool" && (preferSession === null || leaf.sessionId === preferSession)) + .reverse(); + const pick = (found: OpenLeaf[]): OpenLeaf | undefined => + new Set(found.map((leaf) => leaf.sessionId)).size === 1 ? found[0] : undefined; + const byId = toolCallId !== undefined ? leaves.filter((leaf) => leaf.id === toolCallId) : []; + if (byId.length > 0) return pick(byId); + return pick(leaves.filter((leaf) => isSelfReportTool(leaf.name))); + } + humanWait(opts: HumanWaitOptions): void { const { sessionId, agentId, inputId, prompt, options, reason, ...fields } = opts; this.validateFields(fields); @@ -876,4 +1008,4 @@ export class EventNamespace { } } -export { RESERVED, PROMOTED_NUMERIC, PROMOTED_STRING, U32_MAX, PENDING_CAP }; +export { RESERVED, PROMOTED_NUMERIC, PROMOTED_STRING, U32_MAX, PENDING_CAP, SELF_REPORT_DETAIL_LIMIT }; diff --git a/sdk/typescript/src/index.ts b/sdk/typescript/src/index.ts index db9ed6c86..49dca6eb5 100644 --- a/sdk/typescript/src/index.ts +++ b/sdk/typescript/src/index.ts @@ -9,8 +9,10 @@ * express. * * **Adapters** — `instrument()`. Wires LangChain/LangGraph, the Vercel AI * SDK, Mastra and LlamaIndex.TS to the scopes above. - * * **`event.*`** — the 15 event methods, for anything the adapters do not + * * **`event.*`** — the event methods, for anything the adapters do not * cover. + * * **Self Reports** — `selfReport()` and the report tool (`openaiTool()`, `openaiResponsesTool()`, + * `anthropicTool()`, `handleToolCall()`), so an agent can say it is stuck. * * `sessionId` and `agentId` are optional on every event method: omitted, they * resolve from the enclosing scope. Nothing bound and nothing passed is an @@ -74,10 +76,34 @@ export type { HumanWaitOptions, ModelRequestOptions, ModelResponseOptions, + SelfReportOptions, ToolResultOptions, ToolUseOptions, } from "./events.js"; +export { + DEFAULT_SELF_REPORT_CATEGORIES, + SELF_REPORT_RESULT, + SELF_REPORT_TOOL_NAME, + anthropicTool, + handleToolCall, + isSelfReportTool, + openaiResponsesTool, + openaiTool, + selfReport, + selfReportSettings, + selfReportSettingsPath, + selfReportSpec, +} from "./self-report.js"; +export type { + AnthropicTool, + OpenAIResponsesTool, + OpenAITool, + SelfReportCategory, + SelfReportSettings, + SelfReportSpec, +} from "./self-report.js"; + export { setLogger, setLogLevel } from "./logger.js"; export type { Logger, LogLevel } from "./logger.js"; @@ -136,7 +162,7 @@ export function configure(options: ConfigureOptions = {}): void { } /** - * The 15 event methods. + * The event methods: the 15 shared event types, plus `selfReport`. * * A forwarding view of the process-wide namespace rather than a direct * reference, so a test can replace `runtime.event` with a recording namespace diff --git a/sdk/typescript/src/integrations/ai.ts b/sdk/typescript/src/integrations/ai.ts index ebe7fb127..14732cb24 100644 --- a/sdk/typescript/src/integrations/ai.ts +++ b/sdk/typescript/src/integrations/ai.ts @@ -1564,3 +1564,7 @@ export const _internals = { tracker: (): core.RunTracker | null => tracker, openCalls: (): number => calls.size, }; + +/** The Self Reports tool for this framework — see `./self-report-tools.ts`. */ +export { aiSelfReportTool as selfReportTool } from "./self-report-tools.js"; +export type { AiSelfReportToolOptions, AiSelfReportTool, AiModule } from "./self-report-tools.js"; diff --git a/sdk/typescript/src/integrations/langchain.ts b/sdk/typescript/src/integrations/langchain.ts index 4a6c7aab6..538922498 100644 --- a/sdk/typescript/src/integrations/langchain.ts +++ b/sdk/typescript/src/integrations/langchain.ts @@ -2338,3 +2338,7 @@ export function langchainHandler(options?: LangChainOptions): Record + values.find((value): value is string => typeof value === "string" && value !== ""); + +function identityOf(options: SelfReportToolOptions): { sessionId?: string; agentId?: string } { + return { + ...(options.sessionId === undefined ? {} : { sessionId: options.sessionId }), + ...(options.agentId === undefined ? {} : { agentId: options.agentId }), + }; +} + +function missing(framework: string, install: string): Error { + return new Error( + `selfReportTool() needs ${framework}, which could not be loaded from this application. ` + + `Install it (\`${install}\`), or pass the module: selfReportTool({ module: await import("${framework}") }).`, + ); +} + +// -- Vercel AI SDK ---------------------------------------------------------- + +/** The `ai` exports this builder uses. */ +export interface AiModule { + tool?: (definition: never) => unknown; + jsonSchema?: (schema: never) => unknown; +} + +export interface AiSelfReportToolOptions extends SelfReportToolOptions { + module?: AiModule; +} + +/** The shape `selfReportTool()` returns when nothing narrows it. */ +export interface AiSelfReportTool { + description: string; + inputSchema?: unknown; + parameters?: unknown; + execute: (input: unknown, options?: { toolCallId?: string }) => Promise; +} + +/** + * What `jsonSchema()` returns, built by hand when `ai` cannot be `require`d + * (v7 is ESM-only). Every major from 4 through 7 recognises a schema by these + * registered symbols and the `jsonSchema` / `validate` keys, so the result is + * the same object `jsonSchema()` would have made. + */ +function handMadeJsonSchema(schema: Record): Record { + return { + [Symbol.for("vercel.ai.schema")]: true, + _type: undefined, + [Symbol.for("vercel.ai.validator")]: true, + jsonSchema: schema, + validate: undefined, + }; +} + +/** + * The report tool for the Vercel AI SDK, majors 4–7: + * + * tools: { failproofai_report: selfReportTool(), ...yourTools } + * + * Built with `ai`'s own `tool()` and `jsonSchema()` (no zod). The schema goes + * under `parameters` on v4 and `inputSchema` from v5, and under both when the + * version is unknown (including a `module` passed in). The report lands on the + * agent whose loop called it: the model's `toolCallId` finds the `tool_use` + * the adapter recorded, else the enclosing `failproofai` scope. + */ +export function aiSelfReportTool(options: AiSelfReportToolOptions = {}): T { + const spec = selfReportSpec(); + const resolved = versionTuple("ai")?.[0]; + // v4–v6 ship CommonJS; v7 does not, and a `require` of it would print + // Node's require(esm) warning in the customer's process for nothing. + const ai = options.module ?? (resolved !== undefined && resolved <= 6 ? tryRequire("ai") : null); + // The resolved `ai` says nothing about a module the caller passed in (an + // application can resolve v6 and hand over a v4 copy), so its version is + // unknown and the definition carries both schema keys. + const major = options.module ? undefined : resolved; + const schema = + typeof ai?.jsonSchema === "function" + ? ai.jsonSchema(spec.inputSchema as never) + : handMadeJsonSchema(spec.inputSchema); + const identity = identityOf(options); + const definition: AiSelfReportTool = { + description: spec.description, + ...(major === undefined || major >= 5 ? { inputSchema: schema } : {}), + ...(major === undefined || major < 5 ? { parameters: schema } : {}), + execute: (input: unknown, callOptions?: { toolCallId?: string }) => + Promise.resolve(recordToolCall(input, { ...identity, toolCallId: pickId(callOptions?.toolCallId) })), + }; + return (typeof ai?.tool === "function" ? ai.tool(definition as never) : definition) as T; +} + +// -- LangChain ---------------------------------------------------------------- + +/** The `@langchain/core/tools` exports this builder uses. */ +export interface LangChainToolsModule { + tool?: (func: never, fields: never) => unknown; + DynamicStructuredTool?: new (fields: never) => unknown; +} + +export interface LangChainSelfReportToolOptions extends SelfReportToolOptions { + module?: LangChainToolsModule; +} + +/** + * The first `@langchain/core` whose tools take a JSON Schema. Before it, a + * tool's schema was read only as zod, so a JSON Schema reached the model as an + * empty one: the model saw a tool with no arguments. The `/langchain` tracer + * needs no such thing and keeps the peer range's 0.3.0 floor. + */ +const LANGCHAIN_SELF_REPORT_MIN_CORE = "0.3.44"; + +/** Refuse an `@langchain/core` older than the tool needs, by name and version. */ +function requireJsonSchemaTools(found: string | null): void { + if (found === null) return; + const [major = 0, minor = 0, patch = 0] = parseVersion(found); + const [needMajor = 0, needMinor = 0, needPatch = 0] = parseVersion(LANGCHAIN_SELF_REPORT_MIN_CORE); + const older = + major !== needMajor ? major < needMajor : minor !== needMinor ? minor < needMinor : patch < needPatch; + if (!older) return; + throw new FailproofAICompatError( + `selfReportTool() needs @langchain/core ${LANGCHAIN_SELF_REPORT_MIN_CORE} or later, and this ` + + `application has ${found}: older releases read a tool's schema only as zod, so the model ` + + `would be offered failproofai_report with no arguments. Upgrade it ` + + `(\`npm install @langchain/core@^${LANGCHAIN_SELF_REPORT_MIN_CORE}\`). The LangChain tracer ` + + `(instrument("langchain"), langchainHandler()) works on ${found} as it is.`, + ); +} + +/** + * The report tool for LangChain / LangGraph (`@langchain/core` ≥0.3.44), a + * structured tool with a JSON Schema — bind it with the rest: + * + * const model = chat.bindTools([selfReportTool(), ...tools]); + * createReactAgent({ llm, tools: [selfReportTool(), ...tools] }); + * + * Throws `FailproofAICompatError` when the application's `@langchain/core` is + * older than 0.3.44, rather than hand the model a tool with an empty schema. A + * `module` passed in is another copy whose version cannot be read, so it is + * taken as it is. + */ +export function langchainSelfReportTool(options: LangChainSelfReportToolOptions = {}): T { + if (options.module === undefined) requireJsonSchemaTools(versionString("@langchain/core")); + const tools = options.module ?? tryRequire("@langchain/core/tools"); + const spec = selfReportSpec(); + const identity = identityOf(options); + // `tool()` calls `func(input, config)`, with the model's call at + // `config.toolCall`; a `DynamicStructuredTool` calls `func(input, runManager, + // config)`. Read the id from whichever argument carries it, at + // `toolCall.id` or, as a graph runner may pass it, `configurable.tool_call_id`. + // A run id is not the model's call id, so it is never used. + type WithToolCall = { toolCall?: { id?: unknown }; configurable?: { tool_call_id?: unknown } } | undefined; + const func = (input: unknown, second?: WithToolCall, third?: WithToolCall) => + Promise.resolve( + recordToolCall(input, { + ...identity, + toolCallId: pickId( + second?.toolCall?.id, + third?.toolCall?.id, + second?.configurable?.tool_call_id, + third?.configurable?.tool_call_id, + ), + }), + ); + const fields = { name: SELF_REPORT_TOOL_NAME, description: spec.description, schema: spec.inputSchema }; + if (typeof tools?.tool === "function") return tools.tool(func as never, fields as never) as T; + if (typeof tools?.DynamicStructuredTool === "function") { + return new tools.DynamicStructuredTool({ ...fields, func } as never) as T; + } + throw missing("@langchain/core/tools", "npm install @langchain/core"); +} + +// -- Mastra ------------------------------------------------------------------- + +/** The `@mastra/core/tools` export this builder uses. */ +export interface MastraToolsModule { + createTool?: (definition: never) => unknown; +} + +/** The `zod` export this builder uses. */ +export interface ZodModule { + z?: ZodLike; + object?: ZodLike["object"]; +} +interface ZodLike { + object(shape: Record): unknown; + string(): { describe(text: string): unknown }; + enum(values: [string, ...string[]]): unknown; +} + +export interface MastraSelfReportToolOptions extends SelfReportToolOptions { + module?: MastraToolsModule; + /** The application's `zod`, which Mastra tools need for their schema. */ + zod?: ZodModule; +} + +/** + * The input and call id of a Mastra `execute`, in either major's signature: + * 1.x `execute(input, { agent: { toolCallId } })`, 0.x + * `execute({ context: input, runtimeContext, … }, { toolCallId })`. + */ +function mastraCall(args: unknown[]): { input: unknown; toolCallId?: string } { + const [first, second] = args as [unknown, Record | undefined]; + if (typeof first === "object" && first !== null && "context" in first) { + const envelope = first as { context?: unknown; toolCallId?: unknown }; + return { input: envelope.context, toolCallId: pickId(second?.toolCallId, envelope.toolCallId) }; + } + const agentContext = second?.agent as { toolCallId?: unknown } | undefined; + return { input: first, toolCallId: pickId(agentContext?.toolCallId, second?.toolCallId) }; +} + +/** + * The report tool for Mastra (`@mastra/core` ≥0.20), made with `createTool`: + * + * new Agent({ ..., tools: { failproofai_report: selfReportTool(), ...tools } }); + * + * Mastra tools take a zod schema, so this uses the application's own `zod` + * (every Mastra install has it). + */ +export function mastraSelfReportTool(options: MastraSelfReportToolOptions = {}): T { + const tools = options.module ?? tryRequire("@mastra/core/tools"); + if (typeof tools?.createTool !== "function") throw missing("@mastra/core/tools", "npm install @mastra/core"); + const zodModule = options.zod ?? tryRequire("zod"); + const z = zodModule?.z ?? (zodModule as ZodLike | null); + if (typeof z?.object !== "function") throw missing("zod", "npm install zod"); + const spec = selfReportSpec(); + const names = ((spec.inputSchema.properties as { category: { enum: string[] } }).category.enum) as [ + string, + ...string[], + ]; + const inputSchema = z.object({ + category: z.enum(names), + detail: z.string().describe("One factual sentence: what is blocking you."), + }); + const identity = identityOf(options); + return tools.createTool({ + id: SELF_REPORT_TOOL_NAME, + description: spec.description, + inputSchema, + execute: (...args: unknown[]) => { + const { input, toolCallId } = mastraCall(args); + return Promise.resolve(recordToolCall(input, { ...identity, toolCallId })); + }, + } as never) as T; +} + +// -- LlamaIndex --------------------------------------------------------------- + +/** The `FunctionTool` export this builder can use (`llamaindex` or `@llamaindex/core/tools`). */ +export interface LlamaIndexToolsModule { + FunctionTool?: { from(fn: never, metadata: never): unknown }; +} + +export interface LlamaIndexSelfReportToolOptions extends SelfReportToolOptions { + /** Build it with this `FunctionTool` instead of as a plain `BaseTool`. */ + module?: LlamaIndexToolsModule; +} + +/** + * The report tool for LlamaIndex.TS (`llamaindex` ≥0.11.4): + * + * agent({ llm, tools: [selfReportTool(), ...tools] }); + * + * A LlamaIndex tool is any `BaseTool` — `{ metadata, call }` — so by default + * this is that plain object with a JSON Schema, and loads nothing: `require` + * of a second copy of `llamaindex` is what makes it print "already imported. + * This breaks constructor checks". Pass `module` (your `FunctionTool`) to get + * a `FunctionTool` instead. + * + * LlamaIndex hands a tool no call id, so the report finds its agent, and + * takes its call id, from the open `tool_use` named `failproofai_report` + * (recorded by `instrument("llamaindex")`), else the enclosing scope. + */ +export function llamaindexSelfReportTool( + options: LlamaIndexSelfReportToolOptions = {}, +): T { + const spec = selfReportSpec(); + const identity = identityOf(options); + const call = (input: unknown) => Promise.resolve(recordToolCall(input, identity)); + const metadata = { name: SELF_REPORT_TOOL_NAME, description: spec.description, parameters: spec.inputSchema }; + if (typeof options.module?.FunctionTool?.from === "function") { + return options.module.FunctionTool.from(call as never, metadata as never) as T; + } + const tool: LlamaIndexSelfReportTool = { metadata, call }; + return tool as T; +} + +/** A LlamaIndex `BaseTool`, structurally. */ +export interface LlamaIndexSelfReportTool { + metadata: { name: string; description: string; parameters: Record }; + call: (input: unknown) => Promise; +} diff --git a/sdk/typescript/src/resolver.ts b/sdk/typescript/src/resolver.ts index 75f683f3f..beb082b19 100644 --- a/sdk/typescript/src/resolver.ts +++ b/sdk/typescript/src/resolver.ts @@ -72,10 +72,17 @@ export function getBaseDir(): string { * a first batch is written. */ export function failproofaiCustomAgentsDir(): string { + return join(failproofaiHome(), "custom-agents"); +} + +/** + * `~/.failproofai`, or `$FAILPROOFAI_HOME` when it is set — the umbrella every + * local failproofai file lives under (the spool above, `self-report.json`). + */ +export function failproofaiHome(): string { // Blank or whitespace-only means unset: otherwise it resolves against the cwd. const fpHome = process.env.FAILPROOFAI_HOME?.trim(); - const base = fpHome ? expandUser(fpHome) : join(homedir(), ".failproofai"); - return join(base, "custom-agents"); + return fpHome ? expandUser(fpHome) : join(homedir(), ".failproofai"); } /** diff --git a/sdk/typescript/src/schema.ts b/sdk/typescript/src/schema.ts index 5a564d2fe..4cfb88135 100644 --- a/sdk/typescript/src/schema.ts +++ b/sdk/typescript/src/schema.ts @@ -362,6 +362,37 @@ export function humanInterruptEvent(event: HumanInterruptEvent): Record { + return build( + identityBlock(event, "self_report", { + category: event.category, + detail: event.detail, + source: event.source, + }), + [["tool_call_id", event.toolCallId]], + event.extraFields ?? {}, + ); +} + /** * Every field name any event builder above declares, plus the wire names of the * identity block. `integrations/core.ts` derives its forbidden-extras set from @@ -407,4 +438,7 @@ export const DECLARED_FIELD_NAMES: ReadonlySet = new Set([ "options", "response", "at_step", + "category", + "detail", + "source", ]); diff --git a/sdk/typescript/src/self-report-spec.ts b/sdk/typescript/src/self-report-spec.ts new file mode 100644 index 000000000..7e69ae5c5 --- /dev/null +++ b/sdk/typescript/src/self-report-spec.ts @@ -0,0 +1,412 @@ +/** + * Self Reports: the tool an agent calls to say it is stuck — the pure half. + * + * Everything here is data and string-building, and the module imports NOTHING, + * so the Edge build (`src/edge/`) can hand out the very same spec, the same + * OpenAI / Anthropic tool definitions and the same name check as the Node + * build. The Node half (`self-report.ts`) adds the two things that need a + * filesystem: reading `$FAILPROOFAI_HOME/self-report.json`, and recording. + * + * The tool name, the description text, the input schema and the result text + * are one contract across every implementation — the MCP servers (daemon and + * `failproofai mcp`), the Python SDK and this one — so a model sees the same + * tool whichever way it was offered. Change them in all of them or none. + */ + +/** The tool's name when an SDK offers it to a model. */ +export const SELF_REPORT_TOOL_NAME = "failproofai_report"; + +/** What the tool answers, always. Reporting never fails the agent's call. */ +export const SELF_REPORT_RESULT = "Recorded."; + +/** `detail` beyond this many characters is cut. */ +export const SELF_REPORT_DETAIL_LIMIT = 2000; + +export interface SelfReportCategory { + name: string; + description: string; +} + +/** + * The categories used when nothing configures any. An organisation's own list + * REPLACES these entirely; it is never merged with them. + */ +export const DEFAULT_SELF_REPORT_CATEGORIES: ReadonlyArray> = Object.freeze([ + Object.freeze({ + name: "looping", + description: "You keep repeating the same or circular steps without making progress.", + }), + Object.freeze({ + name: "cannot_do_request", + description: + "The user asked for something you cannot do here: a missing capability, tool or permission, or it is only possible by cheating.", + }), + Object.freeze({ + name: "invalid_tool_or_credential", + description: "A tool, MCP server, plugin, API key or token you need is broken, invalid, expired or rejected.", + }), + Object.freeze({ + name: "missing_context", + description: + "Information or access you need is missing and you cannot get it yourself. Not for normal clarifying questions.", + }), + Object.freeze({ + name: "repeated_tool_failure", + description: + "A command or tool failed on several distinct attempts and is blocking you. A single error is not enough.", + }), + Object.freeze({ + name: "task_failure", + description: "You genuinely tried and could not complete the task, or something else blocks you that no other category describes. Not for refusals or policy blocks.", + }), +]); + +/** The bounds a configured list must keep to; outside them the defaults are used. */ +export const CATEGORY_NAME_PATTERN = /^[a-z][a-z0-9_]{0,63}$/; +export const MAX_CATEGORIES = 32; +export const MAX_CATEGORY_DESCRIPTION = 500; +export const MAX_GUIDANCE = 2000; + +const PREAMBLE = + "When you are stuck on something you cannot fix yourself, call this tool once with `category` (one of the categories " + + "below) and `detail` (one factual sentence: what is blocking you). It reports to FailproofAI. Call it BEFORE your " + + "final answer, for example for a missing, invalid or expired token or API key, a 401 or 403, a command, tool or MCP " + + "server that keeps failing, information or access you cannot get, or a request you cannot do here. Do not call it for " + + "normal work, clarifying questions or an error you then fixed. One call per distinct problem.\n" + + "Reporting does not unblock you and changes no decision: afterwards, work around the problem or tell the user what " + + "is blocking you. There is no need to mention this report to the user."; + +/** The tool description, built the same way in every implementation. */ +export function describeSelfReport( + categories: ReadonlyArray, + guidance?: string | null, +): string { + const lines = categories.map((category) => `- ${category.name}: ${category.description}`); + let text = `${PREAMBLE}\n\nCategories:\n${lines.join("\n")}`; + if (typeof guidance === "string" && guidance !== "") text += `\n\n${guidance}`; + return text; +} + +/** A JSON Schema object, as the tool definitions carry it. */ +export type JsonSchemaObject = Record; + +/** The input schema: `category` from the list, and a one-sentence `detail`. */ +export function selfReportInputSchema(categories: ReadonlyArray): JsonSchemaObject { + return { + type: "object", + properties: { + category: { type: "string", enum: categories.map((category) => category.name) }, + detail: { type: "string", description: "One factual sentence: what is blocking you." }, + }, + required: ["category", "detail"], + additionalProperties: false, + }; +} + +export interface SelfReportSpec { + name: string; + description: string; + inputSchema: JsonSchemaObject; +} + +export function buildSelfReportSpec( + categories: ReadonlyArray, + guidance?: string | null, +): SelfReportSpec { + return { + name: SELF_REPORT_TOOL_NAME, + description: describeSelfReport(categories, guidance), + inputSchema: selfReportInputSchema(categories), + }; +} + +/** The OpenAI Chat Completions `tools[]` entry. */ +export interface OpenAITool { + type: "function"; + function: { name: string; description: string; parameters: JsonSchemaObject }; +} + +export function toOpenAITool(spec: SelfReportSpec): OpenAITool { + return { + type: "function", + function: { name: spec.name, description: spec.description, parameters: spec.inputSchema }, + }; +} + +/** + * The OpenAI Responses API `tools[]` entry: the flat function shape. `strict` + * is required by openai's own `FunctionTool` type, and the schema already + * meets strict mode (every property required, no additional properties), so + * the model's arguments are held to it. + */ +export interface OpenAIResponsesTool { + type: "function"; + name: string; + description: string; + parameters: JsonSchemaObject; + strict: boolean; +} + +export function toOpenAIResponsesTool(spec: SelfReportSpec): OpenAIResponsesTool { + return { type: "function", name: spec.name, description: spec.description, parameters: spec.inputSchema, strict: true }; +} + +/** The Anthropic Messages `tools[]` entry. */ +export interface AnthropicTool { + name: string; + description: string; + input_schema: JsonSchemaObject; +} + +export function toAnthropicTool(spec: SelfReportSpec): AnthropicTool { + return { name: spec.name, description: spec.description, input_schema: spec.inputSchema }; +} + +/** + * Every spelling an agent gives the report tool (case-insensitive, exact): + * `failproofai_report` (the SDKs), and the MCP tool `report` on server + * `failproofai_local`: `mcp__failproofai_local__report` (Claude Code, Codex, + * Pi, Factory, Devin), `failproofai_local___report` (Factory's matcher form), + * `failproofai_local_report` (OpenCode), `mcp_failproofai_local_report` + * (Hermes, Antigravity), `failproofai_local__report` (OpenClaw, Goose), + * `failproofai_local-report` (Copilot CLI, likely), and other + * server-qualified forms. + * + * Mirrors `isSelfReportToolName` in the CLI's `src/hooks/self-report-names.ts`; + * this package cannot import that, so both are tested against the same golden + * list (`test-fixtures/self-report/tool-names.golden.txt` in the repo). + */ +export const SELF_REPORT_TOOL_SPELLINGS: ReadonlyArray = Object.freeze([ + "mcp__failproofai_local__report", + "failproofai_local___report", + "failproofai_local__report", + "failproofai_report", + "failproofai_local_report", + "failproofai_local.report", + "failproofai_local/report", + "failproofai_local:report", + "mcp_failproofai_local_report", + "mcp__failproofai_local_report", + "mcp:failproofai_local:report", + "mcp:failproofai_local/report", + "failproofai_local-report", +]); + +const SPELLINGS = new Set(SELF_REPORT_TOOL_SPELLINGS); + +/** + * Whether a tool is the report tool. `server` is for hosts that name an MCP + * tool and its server separately (Cursor's `tool_name` + `mcp_server_name`): + * a bare `report` matches only when the server is `failproofai_local`. + */ +export function isSelfReportTool(name: unknown, server?: unknown): boolean { + if (typeof name !== "string") return false; + const lower = name.toLowerCase(); + if (SPELLINGS.has(lower)) return true; + return ( + typeof server === "string" && server.toLowerCase() === "failproofai_local" && (lower === "report" || lower === "mcp:report") + ); +} + +/** + * The call's arguments as the event records them. + * + * Never rejects: the category is returned as sent (`recordToolCall` then + * resolves it with `resolveSelfReportCategory`), a missing or empty argument falls back to its first + * non-empty alias (`SELF_REPORT_ARG_ALIASES`) else `""`, and arguments that + * arrive as the JSON string a provider sent (OpenAI's `function.arguments`) + * are parsed first. Anything unreadable becomes the empty strings — the call + * itself always answers `Recorded.`. + */ +export function normalizeSelfReportArgs(args: unknown): { category: string; detail: string } { + let value = args; + if (typeof value === "string") { + try { + value = JSON.parse(value) as unknown; + } catch { + value = {}; + } + } + const record = typeof value === "object" && value !== null ? (value as Record) : {}; + return { + category: clipReportText(firstText(record, "category", SELF_REPORT_ARG_ALIASES.category), Infinity), + detail: clipDetail(firstText(record, "detail", SELF_REPORT_ARG_ALIASES.detail)), + }; +} + +/** + * Other names a model uses for an argument when it calls the tool without + * loading its schema (seen live: `summary` and `sentence` for `detail`). The + * first non-empty one is used when the real argument is missing or empty; + * unknown keys are ignored. The same list as the CLI and the daemon: + * test-fixtures/self-report/arg-aliases.json. + */ +export const SELF_REPORT_ARG_ALIASES = Object.freeze({ + category: Object.freeze(["type", "kind"]), + detail: Object.freeze(["summary", "sentence", "message", "description", "reason", "text", "details"]), +}); + +/** + * Keyword rules for a category the model did not name (or named wrongly), in + * order: the first rule whose target is on the active list and whose keyword + * appears in the lowercased `category + " " + detail` wins. The same rules as + * the CLI and the daemon: test-fixtures/self-report/category-inference.json. + */ +export const SELF_REPORT_CATEGORY_RULES: ReadonlyArray<{ readonly category: string; readonly keywords: readonly string[] }> = + Object.freeze([ + { + category: "invalid_tool_or_credential", + keywords: ["token", "api key", "apikey", "api_key", "credential", "unauthorized", "unauthenticated", "forbidden", "401", "403", "expired", "revoked", "auth", "password", "secret"], + }, + { category: "looping", keywords: ["loop", "looping", "circular", "in circles", "repeating the same"] }, + { + category: "repeated_tool_failure", + keywords: ["keeps failing", "keep failing", "repeatedly", "several attempts", "multiple attempts", "retried", "retries", "again and again"], + }, + { + category: "missing_context", + keywords: ["missing", "not found", "no information", "not provided", "cannot find", "can't find", "need more information", "unclear"], + }, + { + category: "cannot_do_request", + keywords: ["cannot", "can't", "unable", "not possible", "impossible", "not supported", "unsupported", "not allowed"], + }, + ]); + +/** The category a report falls back to when nothing matched, if it is listed. */ +export const SELF_REPORT_FALLBACK_CATEGORY = "task_failure"; + +function isWordChar(ch: string | undefined): boolean { + return ch !== undefined && /[a-z0-9]/.test(ch); +} + +function hasKeyword(text: string, keyword: string): boolean { + for (let at = text.indexOf(keyword); at !== -1; at = text.indexOf(keyword, at + 1)) { + if (!isWordChar(text[at - 1]) && !isWordChar(text[at + keyword.length])) return true; + } + return false; +} + +/** + * The category a model's report is recorded under: `raw` when it is on + * `names`, else the listed name it normalises to (lowercase, trimmed, runs of + * spaces and hyphens as `_`), else the first `SELF_REPORT_CATEGORY_RULES` rule + * that matches the category and detail and targets a listed name, else + * `task_failure` when listed, else the first listed name. `inferred` is true + * whenever the result is not `raw` itself. An empty list keeps `raw`. + */ +export function resolveSelfReportCategory( + raw: string, + detail: string, + names: readonly string[], +): { category: string; inferred: boolean } { + if (names.length === 0 || names.includes(raw)) return { category: raw, inferred: false }; + const normalised = raw.trim().toLowerCase().replace(/[\s-]+/g, "_"); + if (names.includes(normalised)) return { category: normalised, inferred: true }; + const text = `${raw} ${detail}`.toLowerCase(); + for (const rule of SELF_REPORT_CATEGORY_RULES) { + if (names.includes(rule.category) && rule.keywords.some((k) => hasKeyword(text, k))) { + return { category: rule.category, inferred: true }; + } + } + return { category: names.includes(SELF_REPORT_FALLBACK_CATEGORY) ? SELF_REPORT_FALLBACK_CATEGORY : (names[0] ?? raw), inferred: true }; +} + +function firstText(record: Record, key: string, aliases: readonly string[]): string { + for (const name of [key, ...aliases]) { + const text = asText(record[name]); + if (text) return text; + } + return ""; +} + +function asText(value: unknown): string { + if (value === undefined || value === null) return ""; + if (typeof value === "string") return value; + if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") return String(value); + try { + return JSON.stringify(value) ?? ""; + } catch { + return ""; + } +} + +/** + * `text` with no lone surrogate (each becomes U+FFFD), cut to `max` Unicode + * code points (`Infinity`: not cut). Code points are what the daemon and the + * Python SDK count, so all of them keep the same prefix of a long detail; a + * lone surrogate would be written as an unpaired `\ud8xx` escape, which the + * collector rejects along with the report. The shared cases are in + * `test-fixtures/self-report/truncation.golden.json` in the repo. + */ +export function clipReportText(text: string, max: number = SELF_REPORT_DETAIL_LIMIT): string { + let out = ""; + let n = 0; + for (const ch of text) { + if (n === max) break; + const code = ch.charCodeAt(0); + out += ch.length === 1 && code >= 0xd800 && code <= 0xdfff ? "\uFFFD" : ch; + n++; + } + return out; +} + +/** What a detail cut down to nothing reads as (truncation.golden.json `detail_cut`). */ +export const DETAIL_CUT_MARKER = "[detail cut]"; + +/** The whitespace the detail cut splits on: ASCII only, so every implementation agrees. */ +const CUT_WHITESPACE = new Set([" ", "\t", "\n", "\r", "\f", "\v"]); + +/** + * `detail` cut to `max` code points (never through a surrogate pair) without + * leaving part of a token at the end. A credential running past the cut (a + * long JWT or key) would otherwise be kept as a fragment that no secret + * scrubber recognises, and be uploaded as such. When the code point right + * after the cut is not whitespace, the trailing run of non-whitespace is + * dropped; then trailing whitespace; an empty result is `DETAIL_CUT_MARKER`. + * The CLI, the daemon and the Python SDK do the same; + * `test-fixtures/self-report/truncation.golden.json` `detail_cut` holds the cases. + */ +export function clipDetail(detail: string, max: number = SELF_REPORT_DETAIL_LIMIT): string { + const points = [...clipReportText(detail, Infinity)]; + if (points.length <= max) return points.join(""); + const head = points.slice(0, max); + if (!CUT_WHITESPACE.has(points[max]!)) { + while (head.length > 0 && !CUT_WHITESPACE.has(head[head.length - 1]!)) head.pop(); + } + while (head.length > 0 && CUT_WHITESPACE.has(head[head.length - 1]!)) head.pop(); + return head.length > 0 ? head.join("") : DETAIL_CUT_MARKER; +} + +/** + * A configured category list, or null when it is not one the contract allows + * (1–32 entries, names `^[a-z][a-z0-9_]{0,63}$` and unique, descriptions + * 1–500 characters). Null means "use the defaults" — a list that is half + * valid is not trimmed into a different list the organisation never wrote. + */ +export function validCategories(value: unknown): SelfReportCategory[] | null { + if (!Array.isArray(value) || value.length === 0 || value.length > MAX_CATEGORIES) return null; + const seen = new Set(); + const out: SelfReportCategory[] = []; + for (const entry of value) { + if (typeof entry !== "object" || entry === null) return null; + const { name, description } = entry as Record; + if (typeof name !== "string" || !CATEGORY_NAME_PATTERN.test(name) || seen.has(name)) return null; + if (typeof description !== "string" || description.length === 0 || description.length > MAX_CATEGORY_DESCRIPTION) { + return null; + } + seen.add(name); + out.push({ name, description }); + } + return out; +} + +/** Guidance as configured, or null when absent, empty, not a string or too long. */ +export function validGuidance(value: unknown): string | null { + if (typeof value !== "string" || value === "" || value.length > MAX_GUIDANCE) return null; + return value; +} + +export function defaultCategories(): SelfReportCategory[] { + return DEFAULT_SELF_REPORT_CATEGORIES.map((category) => ({ ...category })); +} diff --git a/sdk/typescript/src/self-report.ts b/sdk/typescript/src/self-report.ts new file mode 100644 index 000000000..644a897d4 --- /dev/null +++ b/sdk/typescript/src/self-report.ts @@ -0,0 +1,190 @@ +/** + * Self Reports: the tool an agent calls to say it is stuck. + * + * Offer the tool to a model, and when the model calls it, record a + * `self_report` event in the current session and answer `Recorded.`: + * + * const tools = [failproofai.openaiTool()]; // or openaiResponsesTool(), anthropicTool() + * ... + * const answer = failproofai.handleToolCall(call.name, call.arguments, { toolCallId: call.id }); + * if (answer !== null) { ...send `answer` back as the tool result... } + * + * The categories, and an optional paragraph of guidance appended to the + * description, come from `$FAILPROOFAI_HOME/self-report.json` — the one local + * settings file the daemon (Cloud-managed machines) or `failproofai + * self-report enable` writes. When the file is missing, unreadable or says the + * feature is off, the default categories are used: a developer who put the + * tool in their own agent's tool list has already decided to offer it. + * + * Framework tools built on these live on the adapter subpaths: + * `selfReportTool()` from `@failproofai/sdk/ai`, `/langchain`, `/mastra` and + * `/llamaindex`. + */ + +import { readFileSync } from "node:fs"; +import { join } from "node:path"; + +import { logger } from "./logger.js"; +import { failproofaiHome } from "./resolver.js"; +import { runtime } from "./runtime.js"; +import { + SELF_REPORT_RESULT, + buildSelfReportSpec, + defaultCategories, + isSelfReportTool, + normalizeSelfReportArgs, + resolveSelfReportCategory, + toAnthropicTool, + toOpenAIResponsesTool, + toOpenAITool, + validCategories, + validGuidance, + type AnthropicTool, + type OpenAIResponsesTool, + type OpenAITool, + type SelfReportCategory, + type SelfReportSpec, +} from "./self-report-spec.js"; +import type { SelfReportOptions } from "./events.js"; + +export { + DEFAULT_SELF_REPORT_CATEGORIES, + SELF_REPORT_RESULT, + SELF_REPORT_TOOL_NAME, + describeSelfReport, + isSelfReportTool, +} from "./self-report-spec.js"; +export type { + AnthropicTool, + OpenAIResponsesTool, + OpenAITool, + SelfReportCategory, + SelfReportSpec, +} from "./self-report-spec.js"; +export type { SelfReportOptions } from "./events.js"; + +/** What `self-report.json` says, with the defaults filled in. */ +export interface SelfReportSettings { + /** False when the file is missing, unreadable, or says so. */ + enabled: boolean; + /** Who wrote the file: `"cloud"` (the daemon) or `"local"` (the CLI); null without one. */ + source: "cloud" | "local" | null; + /** Never empty: the configured list when enabled and valid, else the defaults. */ + categories: SelfReportCategory[]; + guidance: string | null; + /** The local MCP server, when the file names one. */ + mcp: { port: number; url: string } | null; + updatedAt: string | null; +} + +/** `$FAILPROOFAI_HOME/self-report.json` (default `~/.failproofai/self-report.json`). */ +export function selfReportSettingsPath(): string { + return join(failproofaiHome(), "self-report.json"); +} + +/** + * Read the settings file. Never throws; read fresh on every call, so a change + * the daemon makes reaches the next spec without a restart. + */ +export function selfReportSettings(): SelfReportSettings { + const disabled: SelfReportSettings = { + enabled: false, + source: null, + categories: defaultCategories(), + guidance: null, + mcp: null, + updatedAt: null, + }; + let raw: unknown; + try { + raw = JSON.parse(readFileSync(selfReportSettingsPath(), "utf8")) as unknown; + } catch { + return disabled; + } + if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return disabled; + const file = raw as Record; + const source = file.source === "cloud" || file.source === "local" ? file.source : null; + const mcp = mcpOf(file.mcp); + const updatedAt = typeof file.updatedAt === "string" ? file.updatedAt : null; + if (file.enabled !== true) return { ...disabled, source, mcp, updatedAt }; + return { + enabled: true, + source, + categories: validCategories(file.categories) ?? defaultCategories(), + guidance: validGuidance(file.guidance), + mcp, + updatedAt, + }; +} + +function mcpOf(value: unknown): { port: number; url: string } | null { + if (typeof value !== "object" || value === null) return null; + const { port, url } = value as Record; + if (typeof port !== "number" || !Number.isInteger(port) || typeof url !== "string") return null; + return { port, url }; +} + +/** `{ name, description, inputSchema }` for the report tool, from the current settings. */ +export function selfReportSpec(): SelfReportSpec { + const settings = selfReportSettings(); + return buildSelfReportSpec(settings.categories, settings.guidance); +} + +/** The report tool as an OpenAI Chat Completions `tools[]` entry. */ +export function openaiTool(): OpenAITool { + return toOpenAITool(selfReportSpec()); +} + +/** The report tool as an OpenAI Responses API `tools[]` entry (flat function shape). */ +export function openaiResponsesTool(): OpenAIResponsesTool { + return toOpenAIResponsesTool(selfReportSpec()); +} + +/** The report tool as an Anthropic Messages `tools[]` entry. */ +export function anthropicTool(): AnthropicTool { + return toAnthropicTool(selfReportSpec()); +} + +/** + * Record a report: a `self_report` event with `source: "sdk"`, in the current + * session and agent. See `event.selfReport` for how the session is found when + * none is bound — this never throws for want of one. + */ +export function selfReport(category: string, detail?: string | null, fields: SelfReportOptions = {}): void { + runtime.event.selfReport(category, detail, fields); +} + +/** + * Handle a model's tool call if it is the report tool. + * + * Returns `"Recorded."` after recording it, or null when `name` is some other + * tool, so it chains: `handleToolCall(name, args) ?? runMyTool(name, args)`. + * `args` may be the parsed object or the JSON string a provider sent. + * + * Never throws: whatever goes wrong while recording is logged and the call + * still answers `Recorded.`, because a report must never break the loop it + * reports on. + */ +export function handleToolCall(name: string, args: unknown, fields: SelfReportOptions = {}): string | null { + if (!isSelfReportTool(name)) return null; + recordToolCall(args, fields); + return SELF_REPORT_RESULT; +} + +/** + * The shared body of every report tool: record, swallow, answer. A category + * the model left out, misspelt or named off the list is recorded as the + * listed one it resolves to (`resolveSelfReportCategory`, against the same + * settings the tool's schema came from). + */ +export function recordToolCall(args: unknown, fields: SelfReportOptions = {}): string { + try { + const { category: raw, detail } = normalizeSelfReportArgs(args); + const names = selfReportSettings().categories.map((c) => c.name); + const { category } = resolveSelfReportCategory(raw, detail, names); + runtime.event.selfReport(category, detail, fields); + } catch (error) { + logger.warn(`self report was not recorded: ${error instanceof Error ? error.message : String(error)}`); + } + return SELF_REPORT_RESULT; +} diff --git a/sdk/typescript/test/edge.test.ts b/sdk/typescript/test/edge.test.ts index cbb27b4ec..d632c0e1e 100644 --- a/sdk/typescript/test/edge.test.ts +++ b/sdk/typescript/test/edge.test.ts @@ -26,7 +26,7 @@ afterEach(() => { }); describe("the edge build's imports", () => { - it("imports no Node builtin and nothing from the Node build but VERSION and types", () => { + it("imports no Node builtin and nothing from the Node build but VERSION, the self-report spec and types", () => { for (const file of readdirSync(edgeDir).filter((name) => name.endsWith(".ts"))) { const source = readFileSync(join(edgeDir, file), "utf8"); const imports = [...source.matchAll(/^import\s+(type\s+)?[^;]*?from\s+"([^"]+)";/gms)].map((m) => ({ @@ -35,13 +35,20 @@ describe("the edge build's imports", () => { })); for (const { typeOnly, from } of imports) { if (typeOnly) continue; - const allowed = from.startsWith("./") || from === "../version.js"; + const allowed = from.startsWith("./") || from === "../version.js" || from === "../self-report-spec.js"; expect(allowed, `${file} imports ${from} at run time`).toBe(true); } expect(source, file).not.toMatch(/\bprocess\./); expect(source, file).not.toMatch(/require\(/); } }); + + it("shares a self-report spec module that itself imports nothing", () => { + const source = readFileSync(join(root, "src", "self-report-spec.ts"), "utf8"); + expect(source).not.toMatch(/^import\s/m); + expect(source).not.toMatch(/\bprocess\./); + expect(source).not.toMatch(/require\(/); + }); }); /** @@ -139,7 +146,7 @@ describe("the edge build's behaviour", () => { for (const method of Object.keys(edge.event)) { expect(() => (edge.event as unknown as Record void>)[method]!({})).not.toThrow(); } - expect(Object.keys(edge.event)).toHaveLength(15); + expect(Object.keys(edge.event)).toHaveLength(16); await expect(edge.flush()).resolves.toBeUndefined(); expect(await edge.instrument()).toEqual([]); expect(await (edge.instrument as (name: string) => Promise)("langchain")).toEqual([]); diff --git a/sdk/typescript/test/self-report-ai-module.test.ts b/sdk/typescript/test/self-report-ai-module.test.ts new file mode 100644 index 000000000..33d1c6eba --- /dev/null +++ b/sdk/typescript/test/self-report-ai-module.test.ts @@ -0,0 +1,44 @@ +/** + * The AI SDK report tool picks its schema key from the `ai` version this + * package resolves only when it builds with that copy. A module passed in may + * be another major (an application resolving v6 can hand over a v4 copy), so + * its definition carries both keys. + */ +import { describe, expect, it, vi } from "vitest"; + +const resolved = vi.hoisted(() => ({ major: 6 })); +vi.mock("../src/integrations/compat.js", async (orig) => { + const real = await orig(); + return { + ...real, + versionTuple: (pkg: string) => (pkg === "ai" ? [resolved.major, 0, 0] : real.versionTuple(pkg)), + }; +}); + +import { selfReportTool as aiTool } from "../src/integrations/ai.js"; + +type Def = { inputSchema?: unknown; parameters?: unknown }; + +describe("the AI SDK report tool's schema key", () => { + it("follows the resolved major when it builds with the resolved copy", () => { + resolved.major = 6; + const v6 = aiTool(); + expect(v6.inputSchema).toBeDefined(); + expect(v6.parameters).toBeUndefined(); + resolved.major = 4; + const v4 = aiTool(); + expect(v4.parameters).toBeDefined(); + expect(v4.inputSchema).toBeUndefined(); + }); + + it("carries both keys for a module passed in, whatever major resolves here", () => { + for (const major of [4, 6]) { + resolved.major = major; + // An AI SDK 4 `tool()` returns the definition unchanged. + const v4Module = { tool: (d: unknown) => d, jsonSchema: (s: unknown) => ({ schemaOf: s }) }; + const built = aiTool({ module: v4Module }); + expect(built.parameters, `resolved v${major}`).toBeDefined(); + expect(built.inputSchema).toBe(built.parameters); + } + }); +}); diff --git a/sdk/typescript/test/self-report-golden.test.ts b/sdk/typescript/test/self-report-golden.test.ts new file mode 100644 index 000000000..151878e1d --- /dev/null +++ b/sdk/typescript/test/self-report-golden.test.ts @@ -0,0 +1,108 @@ +import { readFileSync } from "node:fs"; +import { join, resolve } from "node:path"; + +import { describe, expect, it } from "vitest"; + +import * as schema from "../src/schema.js"; +import { + DEFAULT_SELF_REPORT_CATEGORIES, + SELF_REPORT_ARG_ALIASES, + SELF_REPORT_CATEGORY_RULES, + SELF_REPORT_FALLBACK_CATEGORY, + SELF_REPORT_TOOL_SPELLINGS, + describeSelfReport, + isSelfReportTool, + normalizeSelfReportArgs, + resolveSelfReportCategory, + selfReportInputSchema, +} from "../src/self-report-spec.js"; + +/** + * The SDK side of the shared golden files in the repository's + * test-fixtures/self-report/. The Rust daemon and the CLI are tested against + * the same files, so the tool description, input schema, default categories, + * tool names and `self_report` event fields cannot drift between them. + */ +const GOLDEN = resolve(__dirname, "..", "..", "..", "test-fixtures", "self-report"); +const golden = (name: string): string => readFileSync(join(GOLDEN, name), "utf8"); +const lines = (name: string): string[] => golden(name).split("\n").filter((l) => l !== ""); + +describe("Self Reports golden files (TypeScript SDK)", () => { + it("builds the description byte for byte", () => { + expect(describeSelfReport(DEFAULT_SELF_REPORT_CATEGORIES, null)).toBe(golden("description.golden.txt")); + expect( + describeSelfReport(DEFAULT_SELF_REPORT_CATEGORIES, "Report a missing repository as missing_context."), + ).toBe(golden("description-guidance.golden.txt")); + }); + + it("resolves a report's category by the shared rules and runs every shared case", () => { + const fixture = JSON.parse(golden("category-inference.json")) as { + rules: { category: string; keywords: string[] }[]; + fallback: string; + cases: { name: string; categories?: string[]; args: Record; category: string; inferred: boolean }[]; + }; + expect(SELF_REPORT_CATEGORY_RULES).toEqual(fixture.rules); + expect(SELF_REPORT_FALLBACK_CATEGORY).toBe(fixture.fallback); + const defaults = DEFAULT_SELF_REPORT_CATEGORIES.map((c) => c.name); + expect(fixture.cases.length).toBeGreaterThan(0); + for (const c of fixture.cases) { + const { category, detail } = normalizeSelfReportArgs(c.args); + expect(resolveSelfReportCategory(category, detail, c.categories ?? defaults), c.name).toEqual({ + category: c.category, + inferred: c.inferred, + }); + } + }); + + it("reads argument aliases from the shared list", () => { + const fixture = JSON.parse(golden("arg-aliases.json")) as { + aliases: { category: string[]; detail: string[] }; + cases: { args: Record; category: string; detail: string }[]; + }; + expect(SELF_REPORT_ARG_ALIASES).toEqual(fixture.aliases); + for (const c of fixture.cases) { + const want = { category: c.category, detail: c.detail }; + expect(normalizeSelfReportArgs(c.args), JSON.stringify(c.args)).toEqual(want); + expect(normalizeSelfReportArgs(JSON.stringify(c.args)), JSON.stringify(c.args)).toEqual(want); + } + }); + + it("builds the input schema byte for byte", () => { + expect(`${JSON.stringify(selfReportInputSchema(DEFAULT_SELF_REPORT_CATEGORIES))}\n`).toBe( + golden("input-schema.golden.json"), + ); + }); + + it("ships the six default categories", () => { + expect(DEFAULT_SELF_REPORT_CATEGORIES).toEqual(JSON.parse(golden("categories.golden.json"))); + }); + + it("recognises every per-agent spelling of the tool", () => { + expect([...SELF_REPORT_TOOL_SPELLINGS]).toEqual(lines("tool-names.golden.txt")); + for (const name of lines("tool-names.golden.txt")) expect(isSelfReportTool(name), name).toBe(true); + expect(isSelfReportTool("report")).toBe(false); + expect(isSelfReportTool("MCP:report")).toBe(false); + expect(isSelfReportTool("report", "failproofai_local")).toBe(true); + expect(isSelfReportTool("MCP:report", "failproofai_local")).toBe(true); + expect(isSelfReportTool("report", "linear")).toBe(false); + // The Cloud gateway's server is `failproofai`: its tools are never ours. + expect(isSelfReportTool("report", "failproofai")).toBe(false); + for (const name of ["mcp__failproofai__report", "failproofai__report", "mcp_failproofai_report", "failproofai-report"]) { + expect(isSelfReportTool(name), name).toBe(false); + } + }); + + it("writes the golden event fields in wire order", () => { + const spec = JSON.parse(golden("event-fields.golden.json")) as { order: string[]; optional: string[] }; + const base = { + timestamp: "2026-11-25T10:00:00.000000Z", + sessionId: "s1", + agentId: "a1", + category: "looping", + detail: "Same step again.", + source: "sdk", + }; + expect(Object.keys(schema.selfReportEvent(base))).toEqual(spec.order); + expect(Object.keys(schema.selfReportEvent({ ...base, toolCallId: "call_1" }))).toEqual([...spec.order, ...spec.optional]); + }); +}); diff --git a/sdk/typescript/test/self-report-langchain-core.test.ts b/sdk/typescript/test/self-report-langchain-core.test.ts new file mode 100644 index 000000000..d61953dad --- /dev/null +++ b/sdk/typescript/test/self-report-langchain-core.test.ts @@ -0,0 +1,60 @@ +/** + * The LangChain report tool needs `@langchain/core` 0.3.44 or later: older 0.3 + * releases read a tool's schema only as zod and would offer the model the tool + * with no arguments. The peer range keeps its 0.3.0 floor for the tracer, so the + * tool refuses an older core itself, with a message that says so. + */ +import { describe, expect, it, vi } from "vitest"; + +const installed = vi.hoisted(() => ({ core: null as string | null })); +vi.mock("../src/integrations/compat.js", async (orig) => { + const real = await orig(); + return { + ...real, + versionString: (pkg: string) => (pkg === "@langchain/core" ? installed.core : real.versionString(pkg)), + }; +}); + +import { FailproofAICompatError } from "../src/integrations/compat.js"; +import { selfReportTool as langchainTool } from "../src/integrations/langchain.js"; + +describe("the LangChain report tool's @langchain/core floor", () => { + it("refuses a core older than 0.3.44 by name, version and fix", () => { + for (const core of ["0.3.0", "0.3.43", "0.2.36"]) { + installed.core = core; + let thrown: unknown; + try { + langchainTool(); + } catch (error) { + thrown = error; + } + expect(thrown, core).toBeInstanceOf(FailproofAICompatError); + const message = (thrown as Error).message; + expect(message).toContain(`needs @langchain/core 0.3.44 or later, and this application has ${core}`); + expect(message).toContain("npm install @langchain/core@^0.3.44"); + expect(message).toContain("LangChain tracer"); + } + }); + + it("passes 0.3.44 and later on to the usual resolution", () => { + // `@langchain/core` is not installed in this package, so a supported + // version gets past the floor and then reports the missing module. + for (const core of ["0.3.44", "0.3.80", "1.3.0", "0.4.0-rc.1"]) { + installed.core = core; + expect(() => langchainTool(), core).toThrow(/npm install @langchain\/core`/); + expect(() => langchainTool(), core).not.toThrow(FailproofAICompatError); + } + }); + + it("takes a module passed in as it is, whatever version resolves here", () => { + installed.core = "0.3.0"; + const tool = vi.fn((func: unknown, fields: unknown) => ({ func, fields })); + const built = langchainTool<{ fields: { name: string } }>({ module: { tool } }); + expect(built.fields.name).toBe("failproofai_report"); + }); + + it("does not guess when the version cannot be read", () => { + installed.core = null; + expect(() => langchainTool()).not.toThrow(FailproofAICompatError); + }); +}); diff --git a/sdk/typescript/test/self-report.test.ts b/sdk/typescript/test/self-report.test.ts new file mode 100644 index 000000000..dc2bca4bf --- /dev/null +++ b/sdk/typescript/test/self-report.test.ts @@ -0,0 +1,730 @@ +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +import * as edge from "../src/edge/index.js"; +import * as edgeAi from "../src/edge/ai.js"; +import * as edgeLangchain from "../src/edge/langchain.js"; +import * as edgeLlamaindex from "../src/edge/llamaindex.js"; +import * as edgeMastra from "../src/edge/mastra.js"; +import { resetNotice } from "../src/edge/notice.js"; +import { EventNamespace, UNATTRIBUTED_SESSION } from "../src/events.js"; +import * as failproofai from "../src/index.js"; +import { selfReportTool as aiTool } from "../src/integrations/ai.js"; +import { selfReportTool as langchainTool } from "../src/integrations/langchain.js"; +import { selfReportTool as llamaindexTool } from "../src/integrations/llamaindex.js"; +import { selfReportTool as mastraTool } from "../src/integrations/mastra.js"; +import { setLogger } from "../src/logger.js"; +import { runtime } from "../src/runtime.js"; +import * as schema from "../src/schema.js"; +import { agent, session, toolCall } from "../src/scopes.js"; +import { DEFAULT_SELF_REPORT_CATEGORIES, DETAIL_CUT_MARKER, clipDetail, clipReportText } from "../src/self-report-spec.js"; +import { flushed, useSpool } from "./helpers.js"; +import type { Spool } from "./helpers.js"; + +/** + * Self Reports in the TypeScript SDK: the `self_report` event, the settings + * file, the raw tool helpers and the framework tools. The tool's name, + * description, schema and answer are a contract shared with the MCP servers and + * the Python SDK, so the texts below are asserted verbatim. + */ + +let spool: Spool; +let home: string; +let previousHome: string | undefined; + +beforeEach(() => { + spool = useSpool(); + home = mkdtempSync(join(tmpdir(), "failproofai-sr-home-")); + previousHome = process.env.FAILPROOFAI_HOME; + process.env.FAILPROOFAI_HOME = home; +}); + +afterEach(async () => { + await spool.cleanup(); + setLogger(null); + if (previousHome === undefined) delete process.env.FAILPROOFAI_HOME; + else process.env.FAILPROOFAI_HOME = previousHome; + rmSync(home, { recursive: true, force: true }); + resetNotice(); + vi.restoreAllMocks(); +}); + +/** openai's Responses `FunctionTool` (openai 7.x), copied: this package does not depend on openai. */ +interface OpenAIFunctionTool { + name: string; + parameters: { [key: string]: unknown } | null; + strict: boolean | null; + type: "function"; + description?: string | null; +} + +const reports = async () => (await flushed(spool)).filter((e) => e.type === "self_report"); +const writeSettings = (value: unknown) => + writeFileSync(join(home, "self-report.json"), typeof value === "string" ? value : JSON.stringify(value)); +const quietLogger = () => { + const warn = vi.fn(); + setLogger({ debug: vi.fn(), info: vi.fn(), warn, error: vi.fn() }); + return warn; +}; + +const DEFAULT_DESCRIPTION = [ + "When you are stuck on something you cannot fix yourself, call this tool once with `category` (one of the categories below) and `detail` (one factual sentence: what is blocking you). It reports to FailproofAI. Call it BEFORE your final answer, for example for a missing, invalid or expired token or API key, a 401 or 403, a command, tool or MCP server that keeps failing, information or access you cannot get, or a request you cannot do here. Do not call it for normal work, clarifying questions or an error you then fixed. One call per distinct problem.", + "Reporting does not unblock you and changes no decision: afterwards, work around the problem or tell the user what is blocking you. There is no need to mention this report to the user.", + "", + "Categories:", + "- looping: You keep repeating the same or circular steps without making progress.", + "- cannot_do_request: The user asked for something you cannot do here: a missing capability, tool or permission, or it is only possible by cheating.", + "- invalid_tool_or_credential: A tool, MCP server, plugin, API key or token you need is broken, invalid, expired or rejected.", + "- missing_context: Information or access you need is missing and you cannot get it yourself. Not for normal clarifying questions.", + "- repeated_tool_failure: A command or tool failed on several distinct attempts and is blocking you. A single error is not enough.", + "- task_failure: You genuinely tried and could not complete the task, or something else blocks you that no other category describes. Not for refusals or policy blocks.", +].join("\n"); + +const DEFAULT_SCHEMA = { + type: "object", + properties: { + category: { + type: "string", + enum: [ + "looping", + "cannot_do_request", + "invalid_tool_or_credential", + "missing_context", + "repeated_tool_failure", + "task_failure", + ], + }, + detail: { type: "string", description: "One factual sentence: what is blocking you." }, + }, + required: ["category", "detail"], + additionalProperties: false, +}; + +describe("the self_report wire format", () => { + it("puts category, detail and source beside the identity, then environment, then tool_call_id", () => { + const event = schema.selfReportEvent({ + timestamp: "2026-01-01T00:00:00.000000Z", + sessionId: "s1", + agentId: "main", + category: "looping", + detail: "d", + source: "sdk", + toolCallId: "c1", + extraFields: { fw_x: 1 }, + }); + expect(Object.keys(event)).toEqual([ + "timestamp", + "session_id", + "agent_id", + "type", + "category", + "detail", + "source", + "environment", + "tool_call_id", + "fw_x", + ]); + expect(event.type).toBe("self_report"); + }); + + it("declares its fields, so an adapter extra cannot overwrite them", () => { + for (const name of ["category", "detail", "source"]) expect(schema.DECLARED_FIELD_NAMES.has(name)).toBe(true); + }); +}); + +describe("event.selfReport and selfReport()", () => { + it("records in the current session and agent with source sdk", async () => { + await session({ sessionId: "s1" }, () => + agent("planner", () => failproofai.selfReport("looping", "Going in circles.")), + ); + const [report] = await reports(); + expect(report).toMatchObject({ + session_id: "s1", + agent_id: "planner", + category: "looping", + detail: "Going in circles.", + source: "sdk", + }); + expect("tool_call_id" in report!).toBe(false); + }); + + it("records an unknown category as-is, a missing detail as empty, and cuts detail at 2000", async () => { + await session({ sessionId: "s1" }, () => { + failproofai.selfReport("not_a_category"); + failproofai.event.selfReport("looping", "x ".repeat(1250)); + failproofai.selfReport("looping", `${"y".repeat(1999)}😀`); + }); + const [unknown, long, surrogate] = await reports(); + expect(unknown).toMatchObject({ category: "not_a_category", detail: "" }); + // Cut at 2000 code points, never leaving part of a token (the trailing space goes too). + expect(long!.detail).toBe("x ".repeat(1000).trimEnd()); + // 2000 code points, as the daemon and the Python SDK count: the emoji is the 2000th. + expect(surrogate!.detail).toBe(`${"y".repeat(1999)}😀`); + }); + + it("cuts detail as the shared truncation cases say, and replaces a lone surrogate", async () => { + const fixture = JSON.parse(readFileSync(join(__dirname, "..", "..", "..", "test-fixtures", "self-report", "truncation.golden.json"), "utf8")) as { + max: number; + cases: { pad_char: string; pad: number; tail: string; expected_tail: string }[]; + }; + await session({ sessionId: "trunc" }, () => { + for (const c of fixture.cases) failproofai.selfReport("looping", c.pad_char.repeat(c.pad) + c.tail); + failproofai.selfReport("lo\ud83dping", "x\ud83d"); + }); + const recorded = await reports(); + // The plain code-point cut (categories, any text) follows `cases`; a + // report's detail follows `detail_cut` (below). + fixture.cases.forEach((c) => { + expect(clipReportText(c.pad_char.repeat(c.pad) + c.tail, fixture.max)).toBe(c.pad_char.repeat(c.pad) + c.expected_tail); + }); + expect(recorded.at(-1)).toMatchObject({ category: "lo\ufffdping", detail: "x\ufffd" }); + }); + + // Round 3: a credential running past the 2000 cut was uploaded as a fragment + // no scrubber recognised. Every implementation cuts the same way. + it("cuts a detail without leaving part of a token, as the shared detail_cut cases say", async () => { + const fixture = JSON.parse(readFileSync(join(__dirname, "..", "..", "..", "test-fixtures", "self-report", "truncation.golden.json"), "utf8")) as { + max: number; + detail_cut: { marker: string; whitespace: string; cases: { name: string; input: [string, number][]; expected: [string, number][] }[] }; + }; + const joinParts = (parts: [string, number][]) => parts.map(([t, n]) => t.repeat(n)).join(""); + expect(DETAIL_CUT_MARKER).toBe(fixture.detail_cut.marker); + expect(fixture.detail_cut.cases.length).toBeGreaterThan(5); + await session({ sessionId: "cut" }, () => { + for (const c of fixture.detail_cut.cases) failproofai.selfReport("looping", joinParts(c.input)); + }); + const recorded = await reports(); + fixture.detail_cut.cases.forEach((c, i) => { + expect(clipDetail(joinParts(c.input), fixture.max), c.name).toBe(joinParts(c.expected)); + expect(recorded[i]!.detail, c.name).toBe(joinParts(c.expected)); + }); + for (const ws of fixture.detail_cut.whitespace) expect(clipDetail(`ok${ws}${"t".repeat(2100)}`), JSON.stringify(ws)).toBe("ok"); + expect(clipDetail(`ok\u00a0${"t".repeat(2100)}`)).toBe(DETAIL_CUT_MARKER); + }); + + it("takes an explicit session, agent, tool call id and custom fields", async () => { + failproofai.selfReport("task_failure", "d", { sessionId: "s9", agentId: "worker", toolCallId: "c1", fw_note: "n" }); + expect((await reports())[0]).toMatchObject({ + session_id: "s9", + agent_id: "worker", + tool_call_id: "c1", + fw_note: "n", + }); + }); + + it("refuses reserved names and the fields it sets itself", () => { + expect(() => failproofai.selfReport("looping", "d", { sessionId: "s", timestamp: "t" })).toThrow(/Reserved/); + expect(() => failproofai.selfReport("looping", "d", { sessionId: "s", category: "x" })).toThrow(/itself/); + expect(() => failproofai.selfReport("looping", "d", { sessionId: "s", source: "mcp" })).toThrow(/itself/); + }); + + it("joins the open tool call it was made from, by id, even outside any scope", async () => { + const ns = new EventNamespace(runtime.writer); + await session({ sessionId: "framework-run" }, () => + agent("weather-agent", () => { + ns.toolUse({ toolName: "failproofai_report", toolCallId: "call-7" }); + }), + ); + ns.selfReport("looping", "d", { toolCallId: "call-7" }); + const [report] = await reports(); + expect(report).toMatchObject({ session_id: "framework-run", agent_id: "weather-agent", tool_call_id: "call-7" }); + }); + + it("joins an open report-tool call by name when there is no id", async () => { + const ns = new EventNamespace(runtime.writer); + await session({ sessionId: "s2" }, () => + agent("reporter", () => ns.toolUse({ toolName: "failproofai_report", toolCallId: "own-id" })), + ); + ns.selfReport("looping", "d"); + expect((await reports())[0]).toMatchObject({ session_id: "s2", agent_id: "reporter", tool_call_id: "own-id" }); + }); + + it("keeps the caller's call id over the matched tool call's", async () => { + const ns = new EventNamespace(runtime.writer); + await session({ sessionId: "s3" }, () => + agent("reporter", () => ns.toolUse({ toolName: "failproofai_report", toolCallId: "adapter-id" })), + ); + ns.selfReport("looping", "d", { toolCallId: "model-id" }); + expect((await reports())[0]).toMatchObject({ session_id: "s3", tool_call_id: "model-id" }); + }); + + it("records no call id when no open tool call matches", async () => { + await session({ sessionId: "s4" }, () => failproofai.selfReport("looping", "d")); + expect((await reports())[0]!.tool_call_id).toBeUndefined(); + }); + + it("inside a scope, only looks at that scope's open tool calls", async () => { + await session({ sessionId: "other" }, () => + agent("elsewhere", () => failproofai.event.toolUse({ toolName: "failproofai_report", toolCallId: "c" })), + ); + await session({ sessionId: "mine" }, () => + toolCall("failproofai_report", { toolCallId: "c2" }, () => failproofai.selfReport("looping", "d")), + ); + const [report] = await reports(); + expect(report).toMatchObject({ session_id: "mine" }); + }); + + it("with no scope, never picks among open report calls of different sessions by recency", async () => { + const ns = new EventNamespace(runtime.writer); + quietLogger(); + // Two concurrent runs (LlamaIndex gives its tool no id and binds no scope), + // each with a report-tool call open. + await session({ sessionId: "run-a" }, () => + agent("a", () => ns.toolUse({ toolName: "failproofai_report", toolCallId: "a-1" })), + ); + await session({ sessionId: "run-b" }, () => + agent("b", () => ns.toolUse({ toolName: "failproofai_report", toolCallId: "b-1" })), + ); + ns.selfReport("looping", "no id"); + // An id open in both sessions is ambiguous too; one open in only one is not. + await session({ sessionId: "run-a" }, () => ns.toolUse({ toolName: "x", toolCallId: "dup" })); + await session({ sessionId: "run-b" }, () => ns.toolUse({ toolName: "x", toolCallId: "dup" })); + ns.selfReport("looping", "dup id", { toolCallId: "dup" }); + ns.selfReport("looping", "unique id", { toolCallId: "a-1" }); + const recorded = await reports(); + expect(recorded.map((e) => [e.detail, e.session_id])).toEqual([ + ["no id", UNATTRIBUTED_SESSION], + ["dup id", UNATTRIBUTED_SESSION], + ["unique id", "run-a"], + ]); + }); + + it("an id open in several sessions never falls back to the tool name; an id open nowhere does", async () => { + const ns = new EventNamespace(runtime.writer); + quietLogger(); + await session({ sessionId: "s-1" }, () => ns.toolUse({ toolName: "search", toolCallId: "dup" })); + await session({ sessionId: "s-2" }, () => ns.toolUse({ toolName: "search", toolCallId: "dup" })); + await session({ sessionId: "s-3" }, () => + agent("reporter", () => ns.toolUse({ toolName: "failproofai_report", toolCallId: "r-3" })), + ); + ns.selfReport("looping", "ambiguous id", { toolCallId: "dup" }); + ns.selfReport("looping", "unknown id", { toolCallId: "model-id" }); + const recorded = await reports(); + expect(recorded.map((e) => [e.detail, e.session_id, e.tool_call_id])).toEqual([ + ["ambiguous id", UNATTRIBUTED_SESSION, "dup"], + ["unknown id", "s-3", "model-id"], + ]); + }); + + it("with an explicit session, infers the call id only from the one open report call of that agent", async () => { + const ns = new EventNamespace(runtime.writer); + await session({ sessionId: "s" }, async () => { + await agent("planner", () => ns.toolUse({ toolName: "failproofai_report", toolCallId: "p-1" })); + await agent("worker", () => ns.toolUse({ toolName: "failproofai_report", toolCallId: "w-1" })); + }); + ns.selfReport("looping", "planner", { sessionId: "s", agentId: "planner" }); + ns.selfReport("looping", "worker", { sessionId: "s", agentId: "worker" }); + ns.selfReport("looping", "nobody", { sessionId: "s", agentId: "other" }); + await session({ sessionId: "s" }, () => + agent("worker", () => ns.toolUse({ toolName: "failproofai_report", toolCallId: "w-2" })), + ); + ns.selfReport("looping", "worker twice", { sessionId: "s", agentId: "worker" }); + await agent("planner", () => ns.selfReport("looping", "ambient agent", { sessionId: "s" })); + const recorded = await reports(); + expect(recorded.map((e) => [e.detail, e.agent_id, e.tool_call_id])).toEqual([ + ["planner", "planner", "p-1"], + ["worker", "worker", "w-1"], + ["nobody", "other", undefined], + ["worker twice", "worker", undefined], + ["ambient agent", "planner", "p-1"], + ]); + }); + + it("files a report with no session under unattributed and warns once, never throwing", async () => { + const warn = quietLogger(); + const namespace = new EventNamespace(runtime.writer); + namespace.selfReport("looping", "a"); + namespace.selfReport("looping", "b"); + const recorded = await reports(); + expect(recorded.map((e) => [e.session_id, e.agent_id])).toEqual([ + [UNATTRIBUTED_SESSION, "main"], + [UNATTRIBUTED_SESSION, "main"], + ]); + expect(warn).toHaveBeenCalledTimes(1); + expect(String(warn.mock.calls[0]![0])).toContain("unattributed"); + }); +}); + +describe("the settings file", () => { + it("is disabled, with the default categories, when the file is missing", () => { + expect(failproofai.selfReportSettingsPath()).toBe(join(home, "self-report.json")); + expect(failproofai.selfReportSettings()).toEqual({ + enabled: false, + source: null, + categories: DEFAULT_SELF_REPORT_CATEGORIES.map((c) => ({ ...c })), + guidance: null, + mcp: null, + updatedAt: null, + }); + }); + + it("is disabled when the file does not parse", () => { + writeSettings("{not json"); + expect(failproofai.selfReportSettings().enabled).toBe(false); + }); + + it("reads an enabled file: categories, guidance, mcp, source", () => { + writeSettings({ + version: 1, + enabled: true, + source: "cloud", + categories: [{ name: "tracker_down", description: "The ticket tracker is unreachable." }], + guidance: "Prefer tracker_down for anything about tickets.", + mcp: { port: 4319, url: "http://127.0.0.1:4319/mcp" }, + updatedAt: "2026-11-25T10:00:00Z", + }); + expect(failproofai.selfReportSettings()).toEqual({ + enabled: true, + source: "cloud", + categories: [{ name: "tracker_down", description: "The ticket tracker is unreachable." }], + guidance: "Prefer tracker_down for anything about tickets.", + mcp: { port: 4319, url: "http://127.0.0.1:4319/mcp" }, + updatedAt: "2026-11-25T10:00:00Z", + }); + const spec = failproofai.selfReportSpec(); + expect(spec.description.endsWith( + "Categories:\n- tracker_down: The ticket tracker is unreachable.\n\nPrefer tracker_down for anything about tickets.", + )).toBe(true); + expect((spec.inputSchema.properties as { category: { enum: string[] } }).category.enum).toEqual(["tracker_down"]); + }); + + it("uses the defaults when disabled, whatever categories the file lists", () => { + writeSettings({ enabled: false, categories: [{ name: "x", description: "y" }], guidance: "g" }); + const settings = failproofai.selfReportSettings(); + expect(settings.enabled).toBe(false); + expect(settings.categories.map((c) => c.name)).toEqual(DEFAULT_SELF_REPORT_CATEGORIES.map((c) => c.name)); + expect(settings.guidance).toBeNull(); + }); + + it.each([ + ["empty", []], + ["a bad name", [{ name: "Bad-Name", description: "d" }]], + ["a duplicate", [{ name: "a", description: "d" }, { name: "a", description: "e" }]], + ["an empty description", [{ name: "a", description: "" }]], + ["too many", Array.from({ length: 33 }, (_, i) => ({ name: `c${i}`, description: "d" }))], + ])("falls back to the default categories for %s list", (_label, categories) => { + writeSettings({ enabled: true, categories }); + expect(failproofai.selfReportSettings().categories.map((c) => c.name)).toEqual( + DEFAULT_SELF_REPORT_CATEGORIES.map((c) => c.name), + ); + }); + + it("drops guidance over 2000 characters", () => { + writeSettings({ enabled: true, guidance: "g".repeat(2001) }); + expect(failproofai.selfReportSettings().guidance).toBeNull(); + }); +}); + +describe("the raw tool helpers", () => { + it("builds the contract's spec from the defaults", () => { + expect(failproofai.selfReportSpec()).toEqual({ + name: "failproofai_report", + description: DEFAULT_DESCRIPTION, + inputSchema: DEFAULT_SCHEMA, + }); + }); + + it("shapes OpenAI and Anthropic tool entries", () => { + expect(failproofai.openaiTool()).toEqual({ + type: "function", + function: { name: "failproofai_report", description: DEFAULT_DESCRIPTION, parameters: DEFAULT_SCHEMA }, + }); + expect(failproofai.anthropicTool()).toEqual({ + name: "failproofai_report", + description: DEFAULT_DESCRIPTION, + input_schema: DEFAULT_SCHEMA, + }); + }); + + it("shapes the OpenAI Responses API entry flat, like Python's openai_responses_tool()", () => { + expect(failproofai.openaiResponsesTool()).toEqual({ + type: "function", + name: "failproofai_report", + description: DEFAULT_DESCRIPTION, + parameters: DEFAULT_SCHEMA, + strict: true, + }); + expect(edge.openaiResponsesTool()).toEqual(failproofai.openaiResponsesTool()); + // Strict mode holds for the schema: every property required, nothing else allowed. + const { parameters } = failproofai.openaiResponsesTool(); + expect([...(parameters.required as string[])].sort()).toEqual(Object.keys(parameters.properties as object).sort()); + expect(parameters.additionalProperties).toBe(false); + // Assignable to openai's own `FunctionTool` (openai/resources/responses), whose + // `strict` is required: checked by `npm run typecheck`, which covers test/. + const asOpenAI: OpenAIFunctionTool = failproofai.openaiResponsesTool(); + expect(asOpenAI.strict).toBe(true); + }); + + it.each([ + ["failproofai_report", true], + ["mcp__failproofai_local__report", true], + ["failproofai_local__report", true], + ["failproofai_local.report", true], + ["failproofai_local/report", true], + ["report", false], + ["failproofai_report_x", false], + ["mcp__other__report", false], + ])("isSelfReportTool(%j) is %s", (name, expected) => { + expect(failproofai.isSelfReportTool(name)).toBe(expected); + }); + + it("handles a report call: records it and answers Recorded.", async () => { + const answer = await session({ sessionId: "s1" }, () => + failproofai.handleToolCall("failproofai_report", '{"category":"missing_context","detail":"No repo access."}', { + toolCallId: "call_1", + }), + ); + expect(answer).toBe("Recorded."); + expect((await reports())[0]).toMatchObject({ + session_id: "s1", + category: "missing_context", + detail: "No repo access.", + tool_call_id: "call_1", + }); + }); + + it("keeps the detail a model sent under an alias (summary), ignoring unknown keys", async () => { + await session({ sessionId: "s1" }, () => + failproofai.handleToolCall("failproofai_report", { type: "looping", summary: "Same fix three times.", extra: 1 }), + ); + expect((await reports())[0]).toMatchObject({ category: "looping", detail: "Same fix three times." }); + }); + + it("returns null for any other tool, recording nothing", async () => { + expect(failproofai.handleToolCall("get_weather", { city: "Paris" })).toBeNull(); + expect(await reports()).toEqual([]); + }); + + it("never throws: unreadable arguments are recorded empty, a bad field is logged", async () => { + const warn = quietLogger(); + await session({ sessionId: "s1" }, () => { + expect(failproofai.handleToolCall("mcp__failproofai_local__report", "{oops")).toBe("Recorded."); + expect(failproofai.handleToolCall("failproofai_report", { category: "looping" }, { timestamp: "x" })).toBe( + "Recorded.", + ); + }); + const recorded = await reports(); + expect(recorded).toHaveLength(1); + // Unreadable arguments: no category, so it falls back to task_failure. + expect(recorded[0]).toMatchObject({ category: "task_failure", detail: "" }); + expect(String(warn.mock.calls[0]![0])).toContain("not recorded"); + }); + + it("files a call with no category (seen live) under the inferred one, and a near-miss under the listed name", async () => { + const detail = 'Deployment is blocked because ./deploy.sh exits with "DEPLOY_TOKEN is not set" and no token is available in this environment.'; + await session({ sessionId: "s1" }, () => { + expect(failproofai.handleToolCall("failproofai_report", { detail })).toBe("Recorded."); + failproofai.handleToolCall("failproofai_report", { category: "Invalid Tool Or Credential", detail: "x" }); + failproofai.handleToolCall("failproofai_report", { category: "command_nonzero_exit", detail: "the build failed" }); + }); + const [live, nearMiss, unknown] = await reports(); + expect(live).toMatchObject({ category: "invalid_tool_or_credential", detail }); + expect(nearMiss).toMatchObject({ category: "invalid_tool_or_credential" }); + expect(unknown).toMatchObject({ category: "task_failure" }); + }); + + it("resolves a call against the org's list: its first category when nothing matches", async () => { + writeSettings({ + enabled: true, + categories: [ + { name: "data_gap", description: "Data is missing." }, + { name: "blocked", description: "Blocked." }, + ], + }); + await session({ sessionId: "s1" }, () => { + failproofai.handleToolCall("failproofai_report", { category: "", detail: "Nothing matches." }); + }); + expect((await reports())[0]).toMatchObject({ category: "data_gap" }); + }); +}); + +describe("the framework tools", () => { + describe("/ai", () => { + it("is built with ai's own tool() and jsonSchema() when handed them", async () => { + const tool = vi.fn((definition: unknown) => ({ wrapped: definition })); + const jsonSchema = vi.fn((value: unknown) => ({ schemaOf: value })); + const built = aiTool<{ wrapped: { description: string; inputSchema: unknown; execute: (i: unknown, o: unknown) => Promise } }>({ + module: { tool, jsonSchema }, + }); + expect(jsonSchema).toHaveBeenCalledWith(DEFAULT_SCHEMA); + expect(built.wrapped.description).toBe(DEFAULT_DESCRIPTION); + expect(built.wrapped.inputSchema).toEqual({ schemaOf: DEFAULT_SCHEMA }); + const answer = await session({ sessionId: "s1" }, () => + built.wrapped.execute({ category: "looping", detail: "d" }, { toolCallId: "call-1" }), + ); + expect(answer).toBe("Recorded."); + expect((await reports())[0]).toMatchObject({ session_id: "s1", tool_call_id: "call-1", category: "looping" }); + }); + + it("makes the jsonSchema() object itself when ai cannot be required", () => { + // `ai` is not installed in this package, so neither the version nor the + // module resolves: the schema goes under both keys, by hand. + const built = aiTool(); + const schemaObject = built.inputSchema as Record; + expect(built.parameters).toBe(built.inputSchema); + expect(schemaObject[Symbol.for("vercel.ai.schema")]).toBe(true); + expect(schemaObject[Symbol.for("vercel.ai.validator")]).toBe(true); + expect(schemaObject.jsonSchema).toEqual(DEFAULT_SCHEMA); + expect("validate" in schemaObject).toBe(true); + }); + }); + + describe("/langchain", () => { + it("builds a structured tool with the JSON schema and records with the model's call id", async () => { + const tool = vi.fn((func: unknown, fields: unknown) => ({ func, fields })); + const built = langchainTool<{ + func: (input: unknown, runManager?: unknown, config?: unknown) => Promise; + fields: unknown; + }>({ module: { tool }, sessionId: "fixed", agentId: "lc" }); + expect(built.fields).toEqual({ name: "failproofai_report", description: DEFAULT_DESCRIPTION, schema: DEFAULT_SCHEMA }); + // `tool()` calls `func(input, config)`: the call is on the 2nd argument. + expect(await built.func({ category: "looping", detail: "d" }, { toolCall: { id: "call_9" } })).toBe("Recorded."); + expect((await reports())[0]).toMatchObject({ session_id: "fixed", agent_id: "lc", tool_call_id: "call_9" }); + }); + + it("reads the call id from the 3rd argument for DynamicStructuredTool, never a run id", async () => { + class DynamicStructuredTool { + constructor(readonly fields: { func: (...args: unknown[]) => Promise }) {} + } + const built = langchainTool({ module: { DynamicStructuredTool }, sessionId: "fixed" }); + await built.fields.func({ category: "looping", detail: "d" }, { runId: "run-1" }, { toolCall: { id: "call_3" } }); + await built.fields.func({ category: "looping", detail: "d" }, { runId: "run-2" }); + const recorded = await reports(); + expect(recorded[0]).toMatchObject({ tool_call_id: "call_3" }); + expect(recorded[1]!.tool_call_id).toBeUndefined(); + }); + + it("reads the call id from configurable.tool_call_id in either argument, toolCall.id first", async () => { + class DynamicStructuredTool { + constructor(readonly fields: { func: (...args: unknown[]) => Promise }) {} + } + const tool = vi.fn((func: unknown) => ({ func })); + const viaTool = langchainTool<{ func: (...args: unknown[]) => Promise }>({ module: { tool }, sessionId: "fixed" }); + const viaDst = langchainTool({ module: { DynamicStructuredTool }, sessionId: "fixed" }); + const input = { category: "looping", detail: "d" }; + await viaTool.func(input, { configurable: { tool_call_id: "cfg-2nd" } }); + await viaDst.fields.func(input, { runId: "run-1" }, { configurable: { tool_call_id: "cfg-3rd" } }); + await viaTool.func(input, { toolCall: { id: "tc" }, configurable: { tool_call_id: "cfg" } }); + await viaDst.fields.func(input, { runId: "run-2", configurable: {} }); + expect((await reports()).map((e) => e.tool_call_id)).toEqual(["cfg-2nd", "cfg-3rd", "tc", undefined]); + }); + + it("falls back to DynamicStructuredTool", () => { + class DynamicStructuredTool { + constructor(readonly fields: Record) {} + } + const built = langchainTool({ module: { DynamicStructuredTool } }); + expect(built.fields.name).toBe("failproofai_report"); + expect(typeof built.fields.func).toBe("function"); + }); + + it("says how to install @langchain/core when it is missing", () => { + expect(() => langchainTool()).toThrow(/npm install @langchain\/core/); + }); + }); + + describe("/mastra", () => { + const fakeZod = { + object: (shape: Record) => ({ kind: "object", shape }), + string: () => ({ describe: (text: string) => ({ kind: "string", text }) }), + enum: (values: string[]) => ({ kind: "enum", values }), + }; + + it("uses createTool with a zod schema, in both execute signatures", async () => { + const createTool = vi.fn((definition: Record) => definition); + const built = mastraTool<{ + id: string; + inputSchema: { shape: { category: { values: string[] } } }; + execute: (...args: unknown[]) => Promise; + }>({ module: { createTool }, zod: { z: fakeZod } }); + expect(built.id).toBe("failproofai_report"); + expect(built.inputSchema.shape.category.values).toEqual(DEFAULT_SCHEMA.properties.category.enum); + await session({ sessionId: "s1" }, async () => { + // 1.x + expect(await built.execute({ category: "looping", detail: "one" }, { agent: { toolCallId: "c1" } })).toBe("Recorded."); + // 0.x + expect(await built.execute({ context: { category: "looping", detail: "zero" }, runtimeContext: {} }, { toolCallId: "c0" })).toBe( + "Recorded.", + ); + }); + const recorded = await reports(); + expect(recorded.map((e) => [e.detail, e.tool_call_id])).toEqual([ + ["one", "c1"], + ["zero", "c0"], + ]); + }); + + it("says how to install what is missing", () => { + expect(() => mastraTool()).toThrow(/npm install @mastra\/core/); + expect(() => mastraTool({ module: { createTool: (d: unknown) => d }, zod: {} })).toThrow(/npm install zod/); + }); + }); + + describe("/llamaindex", () => { + it("is a plain BaseTool by default, loading nothing", async () => { + const built = llamaindexTool(); + expect(built.metadata).toEqual({ name: "failproofai_report", description: DEFAULT_DESCRIPTION, parameters: DEFAULT_SCHEMA }); + await session({ sessionId: "s1" }, () => + agent("li", async () => { + failproofai.event.toolUse({ toolName: "failproofai_report", toolCallId: "li-1" }); + expect(await built.call({ category: "looping", detail: "d" })).toBe("Recorded."); + }), + ); + // LlamaIndex hands the tool no call id: it takes the open call's. + expect((await reports())[0]).toMatchObject({ session_id: "s1", agent_id: "li", tool_call_id: "li-1" }); + }); + + it("uses FunctionTool.from when handed one", () => { + const from = vi.fn((fn: unknown, metadata: unknown) => ({ fn, metadata })); + const built = llamaindexTool<{ metadata: { name: string } }>({ module: { FunctionTool: { from } } }); + expect(built.metadata.name).toBe("failproofai_report"); + }); + }); +}); + +describe("the edge build", () => { + it("offers the same spec and answers Recorded. without writing", async () => { + vi.spyOn(console, "warn").mockImplementation(() => {}); + expect(edge.selfReportSpec()).toEqual(failproofai.selfReportSpec()); + expect(edge.openaiTool()).toEqual(failproofai.openaiTool()); + expect(edge.anthropicTool()).toEqual(failproofai.anthropicTool()); + expect(edge.handleToolCall("failproofai_report")).toBe("Recorded."); + expect(edge.handleToolCall("other")).toBeNull(); + expect(edge.selfReportSettings().enabled).toBe(false); + edge.selfReport(); + edge.event.selfReport("looping", "d"); + + const ai = edgeAi.selfReportTool<{ execute: () => Promise; inputSchema: Record }>(); + expect(await ai.execute()).toBe("Recorded."); + expect(ai.inputSchema[Symbol.for("vercel.ai.schema")]).toBe(true); + for (const make of [edgeLangchain.selfReportTool, edgeMastra.selfReportTool, edgeLlamaindex.selfReportTool]) { + const tool = make<{ name: string; invoke: () => Promise; execute: () => Promise; call: () => Promise }>(); + expect(tool.name).toBe("failproofai_report"); + expect(await tool.invoke()).toBe("Recorded."); + expect(await tool.execute()).toBe("Recorded."); + expect(await tool.call()).toBe("Recorded."); + } + expect(await reports()).toEqual([]); + }); + + it("builds a real LangChain tool with the module it is handed, still recording nothing", async () => { + const tool = vi.fn((func: (input: unknown) => Promise, fields: Record) => ({ func, fields })); + const built = edgeLangchain.selfReportTool<{ func: (i: unknown) => Promise; fields: Record }>({ + module: { tool: tool }, + }); + expect(tool).toHaveBeenCalledTimes(1); + expect(built.fields).toEqual({ name: "failproofai_report", description: DEFAULT_DESCRIPTION, schema: DEFAULT_SCHEMA }); + expect(await built.func({ category: "looping", detail: "d" })).toBe("Recorded."); + class DynamicStructuredTool { + constructor(readonly fields: Record) {} + } + const viaClass = edgeLangchain.selfReportTool({ module: { DynamicStructuredTool: DynamicStructuredTool } }); + expect(viaClass).toBeInstanceOf(DynamicStructuredTool); + expect(viaClass.fields).toMatchObject({ name: "failproofai_report", schema: DEFAULT_SCHEMA }); + expect(await (viaClass.fields.func as () => Promise)()).toBe("Recorded."); + expect(await reports()).toEqual([]); + }); +}); diff --git a/sdk/typescript/test/wire-format.test.ts b/sdk/typescript/test/wire-format.test.ts index fe7fbc5be..a1ace5299 100644 --- a/sdk/typescript/test/wire-format.test.ts +++ b/sdk/typescript/test/wire-format.test.ts @@ -206,6 +206,7 @@ describe("event wire format", () => { schema.humanInputEvent({ ...identity, inputId: "i", response: "r", durationMs: 1 }), schema.humanPauseEvent({ ...identity, reason: "r", userId: "u" }), schema.humanInterruptEvent({ ...identity, reason: "r", userId: "u", atStep: "s" }), + schema.selfReportEvent({ ...identity, category: "c", detail: "d", source: "sdk", toolCallId: "c1" }), ]; for (const event of builders) for (const key of Object.keys(event)) declared.add(key); diff --git a/src/audit/cache.ts b/src/audit/cache.ts index a8f3d4b6d..39ceec7fb 100644 --- a/src/audit/cache.ts +++ b/src/audit/cache.ts @@ -15,6 +15,7 @@ import { join } from "node:path"; import { BUILTIN_POLICIES } from "../hooks/builtin-policies"; import { AUDIT_DETECTORS } from "./detectors"; import type { TranscriptAuditResult, DetectorSessionState } from "./types"; +import type { IntegrationType } from "../hooks/types"; import { auditCacheDir } from "../hooks/fp-home"; let cachedEngineVersion: string | null = null; @@ -120,6 +121,22 @@ function getCachePathFor(transcriptPath: string): string { */ export const CACHE_SCHEMA_VERSION = 4; +/** + * Per-CLI transcript-parser versions. `engineVersion` hashes the builtins and + * `detectorVersion` the detectors, but neither sees a parser change: a parser + * that starts reading records it used to skip leaves the transcript's mtime and + * size alone, so its old result would keep being served until the TTL ran out. + * Bump a CLI's number here when its parser starts producing different events + * from the same file; only that CLI's entries are re-scanned. A CLI with no + * number is unaffected, and entries written before this existed carry none. + * + * codex 2: Codex code mode (`custom_tool_call` exec / apply_patch) is parsed. + * Before it every Codex 0.146+ session cached as zero tool calls. + */ +export const TRANSCRIPT_PARSER_VERSIONS: Partial> = { + codex: 2, +}; + /** * How much of the head and of the resume boundary is hashed to decide the * bytes already scanned are still the same bytes. @@ -174,6 +191,9 @@ interface CacheEntry { anchorHash?: string; /** Stateful detectors' session state at `bytesScanned`, Map-aware encoded. */ detectorState?: string; + /** `TRANSCRIPT_PARSER_VERSIONS[result.cli]` when written; absent for a CLI + * with no number. */ + parserVersion?: number; } /** What a cache lookup can say. */ @@ -274,6 +294,8 @@ export function readCachedTranscript( // and pin a stale entry as valid forever. if (!Number.isFinite(entry.cachedAt) || Date.now() - (entry.cachedAt as number) > CACHE_TTL_MS) return null; if (!entry.result) return null; + const parserVersion = TRANSCRIPT_PARSER_VERSIONS[entry.result.cli]; + if (parserVersion !== undefined && entry.parserVersion !== parserVersion) return null; if (entry.mtimeMs === mtimeMs && entry.sizeBytes === sizeBytes) { return { kind: "hit", result: entry.result }; @@ -334,6 +356,8 @@ export function writeCachedTranscriptResult( detectorVersion: getDetectorVersion(), result, }; + const parserVersion = TRANSCRIPT_PARSER_VERSIONS[result.cli]; + if (parserVersion !== undefined) entry.parserVersion = parserVersion; if (resume && resume.bytesScanned > 0) { const anchor = anchorHashFor(transcriptPath, resume.bytesScanned); // No anchor means no way to prove the prefix later, so the entry is diff --git a/src/hooks/agent-env.ts b/src/hooks/agent-env.ts new file mode 100644 index 000000000..df2e5cbbd --- /dev/null +++ b/src/hooks/agent-env.ts @@ -0,0 +1,125 @@ +/** + * The agent's own config-locating environment, carried to wherever a hook is + * evaluated (bot review of #1105). + * + * The Self Reports exemption skips every policy only while the + * `failproofai_local` registration the agent would use is failproofai's own + * (`selfReportRegistrationOwned`) and nothing else it reads could carry the + * same tool name (`selfReportNameCollides`). Where those files are depends on + * the AGENT's environment: CODEX_HOME, CLAUDE_CONFIG_DIR, HOME, … On a + * daemon-configured machine the hook is evaluated in the daemon's warm + * worker, whose environment is the service's, so a foreign server registered + * under an agent's own CODEX_HOME was judged by the daemon's genuine one and + * exempted. + * + * So the hook CLI, running in the process the agent started, puts those + * variables in the stdin payload as `AGENT_ENV_KEY`, like `AGENT_PATH_KEY` + * (agent-path.ts; crates/PROTOCOL.md): the daemon relays stdin untouched, a + * value the agent's payload carried is replaced or dropped, never trusted, + * and only a payload that could be a report call (it names + * `failproofai_local`) is touched. The worker evaluates the exemption under + * exactly that environment, and with none (an older client, a raw socket + * request, a value past the bound) the exemption is refused: the policies + * decide. The Hermes and OpenClaw plugins call the daemon directly and send + * no payload key; their profile comes from the request's `agentSettingsPath`. + */ + +/** Payload key the hook CLI sets to the variables below. */ +export const AGENT_ENV_KEY = "failproofai_agent_env"; + +/** Every variable that moves an agent config the exemption reads. */ +export const AGENT_ENV_VARS: readonly string[] = [ + "HOME", + "USERPROFILE", + "APPDATA", + "XDG_CONFIG_HOME", + "CLAUDE_CONFIG_DIR", + "CODEX_HOME", + "COPILOT_HOME", + "PI_CODING_AGENT_DIR", + "HERMES_HOME", + "OPENCLAW_STATE_DIR", + "OPENCLAW_HOME", + "OPENCLAW_CONFIG_PATH", + "OPENCLAW_PROFILE", + "GOOSE_PATH_ROOT", + "OPENCODE_CONFIG", +]; + +/** Longest value carried; with a longer one nothing is carried (no exemption). */ +export const AGENT_ENV_VALUE_MAX = 4096; + +/** Every spelling of the report tool, and the server-named calls, contain this. */ +const MAYBE_REPORT_RE = /failproofai_local/i; + +/** The set variables among `AGENT_ENV_VARS`, or undefined when one is past the bound. */ +function pick(env: Record): Record | undefined { + const out: Record = {}; + for (const name of AGENT_ENV_VARS) { + const v = env[name]; + if (v === undefined || v === "") continue; + if (typeof v !== "string" || v.length > AGENT_ENV_VALUE_MAX) return undefined; + out[name] = v; + } + return out; +} + +/** + * In the hook process: `stdin` with `AGENT_ENV_KEY` set to this process's + * config-locating variables when the payload could be a report call, and + * with any value it already carried removed otherwise. Never throws; an + * unparseable payload is returned as it was. + */ +export function markAgentEnv(stdin: string, env: Record = process.env): string { + const maybeReport = MAYBE_REPORT_RE.test(stdin); + const carried = stdin.includes(AGENT_ENV_KEY); + if (!maybeReport && !carried) return stdin; + try { + const parsed = JSON.parse(stdin) as unknown; + if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return stdin; + const { [AGENT_ENV_KEY]: dropped, ...rest } = parsed as Record; + const picked = maybeReport ? pick(env) : undefined; + if (picked) return JSON.stringify({ ...rest, [AGENT_ENV_KEY]: picked }); + return dropped === undefined ? stdin : JSON.stringify(rest); + } catch { + return stdin; + } +} + +/** The agent environment a payload carries (only known variables, bounded), or undefined. */ +export function agentEnvOf(payload: unknown): Record | undefined { + if (!payload || typeof payload !== "object" || Array.isArray(payload)) return undefined; + const v = (payload as Record)[AGENT_ENV_KEY]; + if (!v || typeof v !== "object" || Array.isArray(v)) return undefined; + const out: Record = {}; + for (const [k, x] of Object.entries(v as Record)) { + if (!AGENT_ENV_VARS.includes(k) || typeof x !== "string" || x === "" || x.length > AGENT_ENV_VALUE_MAX) return undefined; + out[k] = x; + } + return out; +} + +/** + * Run `fn` with every `AGENT_ENV_VARS` variable set exactly as in `env` (one + * absent from it is unset), then put the process's own back. `fn` must be + * synchronous: nothing else in the process may run while the variables are + * swapped (the worker evaluates other requests between awaits). + */ +export function withAgentEnv(env: Record, fn: () => T): T { + const saved = new Map(); + for (const name of AGENT_ENV_VARS) { + saved.set(name, process.env[name]); + if (env[name] === undefined) delete process.env[name]; + else process.env[name] = env[name]; + } + try { + const out = fn(); + if (out instanceof Promise) throw new Error("withAgentEnv needs a synchronous function"); + return out; + } finally { + for (const [name, value] of saved) { + if (value === undefined) delete process.env[name]; + else process.env[name] = value; + } + } +} diff --git a/src/hooks/agent-path.ts b/src/hooks/agent-path.ts new file mode 100644 index 000000000..4772d8922 --- /dev/null +++ b/src/hooks/agent-path.ts @@ -0,0 +1,86 @@ +/** + * The agent's own PATH, carried to wherever a hook is evaluated (review + * finding F17). + * + * `block-failproofai-commands` treats a quoted argument of `grep`/`rg`/`jq` + * (and a heredoc fed to `cat`/`tee`) as data only when the command word is + * the standard tool, which for a bare name means: where the AGENT's PATH finds + * it. On a daemon-configured machine the policy runs in the daemon's warm + * worker, whose PATH is the service's, not the agent's; a shadow `grep` early + * on the agent's PATH was judged by the daemon's PATH and ran its argument. + * + * So the hook CLI, running in the process the agent started, puts its own + * PATH in the stdin payload as `AGENT_PATH_KEY` before it forwards or + * evaluates it (crates/PROTOCOL.md: the daemon relays stdin untouched, so an + * older daemon carries it too, and an older client simply sends none). The + * guard reads it from the payload only; with none (an older client, the + * Hermes/OpenClaw plugins that talk to the daemon directly, a PATH past the + * bound) a bare name is not known to be the standard tool and nothing is + * exempt. Only a payload that could reach that exemption is touched, and a + * value already in the payload is replaced or dropped, never trusted. + */ + +/** Payload key the hook CLI sets to its own PATH. */ +export const AGENT_PATH_KEY = "failproofai_agent_path"; + +/** Longest PATH carried; a longer one is dropped (no exemption). */ +export const AGENT_PATH_MAX = 16_384; + +/** Command words whose exemption depends on PATH (see builtin-policies.ts). */ +const PATH_SENSITIVE_RE = /(?:e|f)?grep|\brg\b|\bjq\b|\bcat\b|\btee\b/; + +/** + * The commands the settings walk reads as reads or mentions of an agent's + * settings file (`block-failproofai-commands`): each is exempt only as the + * real tool the agent's PATH finds (#1105 bot review), so a payload that + * names one beside an agent settings word carries the PATH too. A test keeps + * this list equal to the walk's own (`SETTINGS_WALK_PATH_HEADS`). + */ +export const SETTINGS_READER_WORDS: readonly string[] = [ + "cat", "bat", "less", "more", "head", "tail", "nl", "strings", "xxd", "od", "jq", "yq", "diff", "cmp", "wc", + "sort", "uniq", "column", "awk", "cut", "tr", "tac", "rev", "fold", "fmt", "expand", "unexpand", "paste", + "comm", "join", "ls", "dir", "tree", "stat", "file", "du", "df", "readlink", "realpath", "basename", + "dirname", "find", "grep", "egrep", "fgrep", "rg", "ag", "ack", "md5sum", "sha1sum", "sha256sum", "shasum", + "cksum", "cp", "rsync", "install", "tee", "sed", "git", "gh", "glab", "curl", "code", "open", "mkdir", "touch", + // Builtins as well, for a runner (`env echo`) that finds them on PATH. + "echo", "printf", "test", "true", "false", "pwd", +]; +const SETTINGS_READER_RE = new RegExp(`(?; + if (sensitive && typeof path === "string" && path.length > 0 && path.length <= AGENT_PATH_MAX) { + return JSON.stringify({ ...rest, [AGENT_PATH_KEY]: path }); + } + return _dropped === undefined ? stdin : JSON.stringify(rest); + } catch { + return stdin; + } +} + +/** The agent PATH a payload carries, or undefined. */ +export function agentPathOf(payload: unknown): string | undefined { + if (!payload || typeof payload !== "object" || Array.isArray(payload)) return undefined; + const v = (payload as Record)[AGENT_PATH_KEY]; + return typeof v === "string" && v.length > 0 && v.length <= AGENT_PATH_MAX ? v : undefined; +} diff --git a/src/hooks/agent-settings-guard.ts b/src/hooks/agent-settings-guard.ts new file mode 100644 index 000000000..0b57bc0c8 --- /dev/null +++ b/src/hooks/agent-settings-guard.ts @@ -0,0 +1,926 @@ +/** + * The files through which every agent CLI calls failproofai, and the checks the + * always-on guard (`block-failproofai-commands`) runs against writes to them. + * + * Every integration wires failproofai in through a file the agent can write as + * itself: Claude Code's settings layers, Codex's hooks.json and the trust + * hashes in its config.toml, Copilot's and Cursor's hook files, OpenCode's + * config and plugin shim, Pi's settings and extensions, Antigravity's, Factory's, + * Devin's and Goose's hook files, Hermes' config and plugin link, OpenClaw's + * config. Editing one of them is the shortest way for an agent to switch its + * own enforcement off, and it never has to name failproofai to do it: + * `"disableAllHooks": true` in ANY Claude Code settings layer turns off every + * hook in the session, wherever the hooks were installed, and Claude Code picks + * the edit up from a file watcher, so it lands before the agent's next tool + * call. The guard used to check only `~/.failproofai`, and only reads of these + * files were ever refused (by the opt-in `block-read-outside-cwd`). + * + * Every write is refused, not only the ones that disable hooks, because a + * content check cannot be finished. Claude Code skips a settings file that does + * not parse or that holds one value its schema rejects, so an edit that leaves + * the hooks in place and breaks a different key switches them off just as + * well. The same files also hold commands Claude Code runs with no hook in front + * of them (`statusLine`, `apiKeyHelper`, new hooks of its own) and the `env` the + * hook process inherits (`NODE_OPTIONS`). The person at the keyboard, their + * editor, `/permissions` and `failproofai policies --install` still write these + * files: only the agent's own tool calls are refused. + * + * Names here are long on purpose. The CLI ships as one scope-hoisted bundle, and + * a short top-level name that matches a local inside a builtin policy makes the + * bundler rename that local (config-status.ts explains why that matters: the + * audit cache in src/audit/cache.ts keys on each policy's source). + */ +import { existsSync, lstatSync, readdirSync, readlinkSync, realpathSync } from "node:fs"; +import { homedir } from "node:os"; +import { basename, dirname, isAbsolute, join, normalize, relative, resolve } from "node:path"; +import { claudeLocalSettingsPaths } from "./claude-hooks-switch"; + +/** + * One shape per protected file, as the path's TAIL from the agent's config + * directory on. `[\\/]` so a Windows path matches too. + */ +const AGENT_SETTINGS_FILE_SHAPES: readonly RegExp[] = [ + // Claude Code: every settings layer. `disableAllHooks` in any one of them is + // read after precedence, so a project or local file overrides the user file. + /\.claude[\\/]settings(?:\.[^\\/]+)?\.json/, + // Codex: the hooks, and config.toml, which holds the trust hashes Codex checks + // before it runs a hooks.json hook at all. + /\.codex[\\/](?:hooks\.json|config\.toml)/, + // Copilot CLI (user scope), and Copilot CLI / VS Code agent mode (project). + /\.copilot[\\/]hooks[\\/][^\\/]+\.json/, + /\.github[\\/]hooks[\\/][^\\/]+\.json/, + /\.cursor[\\/]hooks\.json/, + // OpenCode: the config that registers the plugin, and the plugin shim itself. + /\.opencode[\\/](?:opencode\.jsonc?|plugins[\\/][^\\/]+\.(?:mjs|js|ts))/, + /\.config[\\/]opencode[\\/](?:opencode\.jsonc?|config\.json|plugins[\\/][^\\/]+\.(?:mjs|js|ts))/, + // And a project's own opencode.json(c), at its root or in any directory + // OpenCode climbs through to reach it: each one is merged over the global + // config. On OpenCode's current config a `"-"` entry in it removes a + // plugin another layer added (packages/core/src/config/plugin/source.ts). + /opencode\.jsonc?/, + // VS Code agent mode: `chat.hookFilesLocations` decides which hook files it + // loads, failproofai's among them. + /\.vscode[\\/]settings\.json/, + // Pi: settings, and the extension directories it loads code from. + /\.pi[\\/](?:agent[\\/])?(?:settings\.json|extensions(?:[\\/].*)?)/, + // Antigravity reuses ~/.gemini/; its project hooks live in .agents/. + /\.gemini[\\/](?:settings\.json|config[\\/]hooks\.json)/, + /\.agents[\\/]hooks\.json/, + // Goose: the plugin directory failproofai owns, and the config it registers in. + /\.agents[\\/]plugins[\\/]failproofai(?:[\\/].*)?/, + /\.config[\\/]goose[\\/]config\.yaml/, + /\.factory[\\/]hooks\.json/, + /(?:\.config[\\/]devin|\.devin)[\\/]config\.json/, + // Hermes: every profile's config.yaml, and the plugin link in its plugins/. + /\.hermes(?:-[^\\/]+)?(?:[\\/]profiles[\\/][^\\/]+)?[\\/](?:config\.yaml|plugins[\\/]failproofai(?:[\\/].*)?)/, + // OpenClaw: every profile's openclaw.json. + /\.openclaw(?:-[^\\/]+)?[\\/]openclaw\.json/, +]; + +/** + * The directories that hold those files. Deleting or moving one removes the + * file inside it, so `rm -rf ~/.claude` switches the hooks off as surely as + * editing settings.json does. Only the agents' own directories: `.github` and + * `.config` hold far too much else, and `.github/hooks/` is also where many + * repositories keep their GIT hooks, so only its `*.json` files are protected. + */ +const AGENT_CONFIG_DIR_SHAPES: readonly RegExp[] = [ + /\.(?:claude|codex|cursor|factory|devin|opencode|gemini|pi|agents)/, + /\.copilot(?:[\\/]hooks)?/, + /\.opencode[\\/]plugins/, + /\.config[\\/](?:opencode(?:[\\/]plugins)?|devin|goose)/, + /\.pi[\\/](?:agent(?:[\\/]extensions)?|extensions)/, + /\.gemini[\\/]config/, + /\.agents[\\/]plugins(?:[\\/]failproofai(?:[\\/]hooks)?)?/, + /\.hermes(?:-[^\\/]+)?(?:[\\/]profiles(?:[\\/][^\\/]+)?)?(?:[\\/]plugins)?/, + /\.openclaw(?:-[^\\/]+)?/, +]; + +const agentSettingsShapeSource = (shapes: readonly RegExp[]): string => shapes.map((shape) => shape.source).join("|"); + +/** + * Case-insensitive because macOS's default filesystem is: `~/.Claude/Settings.json` + * is the same file there. On Linux the wider match only ever refuses more. + */ +const AGENT_SETTINGS_FILE_RE = new RegExp(`(?:^|[\\\\/])(?:${agentSettingsShapeSource(AGENT_SETTINGS_FILE_SHAPES)})$`, "i"); +const AGENT_CONFIG_DIR_RE = new RegExp(`(?:^|[\\\\/])(?:${agentSettingsShapeSource(AGENT_CONFIG_DIR_SHAPES)})[\\\\/]?$`, "i"); + +/** + * The same files found anywhere in a command's text, including inside quoted + * code: `python3 -c "open('/home/u/.claude/settings.json','w')"` never presents + * the path as a word of its own. + */ +const AGENT_SETTINGS_IN_TEXT_RE = new RegExp(`(?])`, + "i", +); + +/** + * An agent directory's name as a string literal in a program: + * `os.path.join(os.path.expanduser('~'), '.claude', 'settings.json')` and + * `path.join(os.homedir(), '.codex', 'hooks.json')` never spell the path. + * Only read inside programs handed to an interpreter, which are never on the + * guard's read list anyway. + */ +const AGENT_DIR_IN_PROGRAM_RE = + /['"`\\/](?:\.(?:claude|codex|cursor|copilot|opencode|pi|gemini|agents|factory|devin)|\.hermes(?:-[^'"`\\/\s]+)?|\.openclaw(?:-[^'"`\\/\s]+)?)['"`\\/]/i; + +/** Whether `path` is an agent settings or hook-config file. Anchored at the end. */ +export function isAgentSettingsPath(path: string): boolean { + return AGENT_SETTINGS_FILE_RE.test(path); +} + +/** Whether `path` IS an agent config directory (not a path inside one). */ +export function isAgentConfigDirPath(path: string): boolean { + return AGENT_CONFIG_DIR_RE.test(path); +} + +/** `~`, `$HOME` and `${HOME}` as the shell would expand them. */ +export function expandAgentSettingsHome(path: string): string { + const home = homedir(); + if (path === "~" || path === "$HOME" || path === "${HOME}") return home; + const match = /^(?:~|\$HOME|\$\{HOME\})[\\/](.*)$/.exec(path); + return match ? join(home, match[1]) : path; +} + +/** + * A path as the tool would open it: home expanded, normalised (`a/./b` and + * `a//b` are `a/b` to the filesystem, never to a regex), and resolved against + * the session's cwd. A relative path with no cwd stays relative, which the + * anchored shapes still read (`.claude/settings.json` begins the string). + */ +function resolveAgentSettingsCandidate(path: string, cwd: string | undefined): string { + const expanded = expandAgentSettingsHome(path); + if (isAbsolute(expanded)) return resolve(expanded); + return cwd ? resolve(cwd, expanded) : normalize(expanded); +} + +/** + * Where a path really leads, following every symlink on the way. + * + * For a file that does not exist yet (a Write that creates it), the deepest + * ancestor that does exist is resolved and the rest appended: a project symlink + * `cfg -> ~/.claude` makes `cfg/settings.local.json` a Claude settings file + * before it has ever been written. Never throws. + */ +function realpathOfAgentSettingsCandidate(path: string): string { + let current = path; + const tail: string[] = []; + for (let depth = 0; depth < 64; depth++) { + try { + const real = realpathSync(current); + return tail.length === 0 ? real : join(real, ...tail.reverse()); + } catch { + const parent = dirname(current); + if (parent === current) return path; + tail.push(basename(current)); + current = parent; + } + } + return path; +} + +/** Linux gives up after this many links in one path (MAXSYMLINKS). */ +const MAX_LINK_HOPS = 40; + +/** + * `path` walked the way the kernel walks it: one component at a time from + * `base`, a symlink replaced by where it points before the walk goes on. So a + * `..` after a link climbs out of the link's TARGET: with `link -> + * ~/.claude/subdir`, `link/../settings.json` is `~/.claude/settings.json`, + * where text normalisation drops `link/..` and lands beside the link. A link + * that leads nowhere yet is followed too — a write through it creates its + * target. Past the first component that does not exist, the rest is joined as + * text. Null on a loop or a link that cannot be read; both fail the write too. + */ +function physicalWalk(base: string, path: string): string | null { + let parts = path.split("/"); + let current = base; + let hops = 0; + for (let k = 0; k < parts.length; k++) { + const part = parts[k]; + if (part === "" || part === ".") continue; + if (part === "..") { + current = dirname(current); + continue; + } + const next = join(current, part); + let stat: ReturnType | undefined; + try { + stat = lstatSync(next, { throwIfNoEntry: false }); + } catch { + // ENOTDIR under a file, EACCES, a component too long: nothing to follow. + stat = undefined; + } + if (stat === undefined) return join(next, ...parts.slice(k + 1)); + if (!stat.isSymbolicLink()) { + current = next; + continue; + } + if (++hops > MAX_LINK_HOPS) return null; + let target: string; + try { + target = readlinkSync(next); + } catch { + return null; + } + if (target.startsWith("/")) current = "/"; + parts = [...target.split("/"), ...parts.slice(k + 1)]; + k = -1; + } + return current; +} + +/** Paths longer than this cannot be opened (PATH_MAX), so they write nothing. */ +const MAX_PHYSICAL_PATH = 4096; + +/** + * Where `path` really leads from `cwd`, symlinks and `..` taken in the + * kernel's order (see physicalWalk), home expanded. Null when it cannot be + * known: a relative path with no cwd, or one too long to open. `bases` keeps + * each cwd's own walk for a caller that resolves many words from one. + */ +export function physicalAgentPath( + path: string, + cwd: string | undefined, + bases?: Map, +): string | null { + // Only the home prefix: `join` would also drop `link/..` before the walk + // could follow `link` (`~/link/../settings.json`). + const home = homedir(); + const prefixed = /^(?:~|\$HOME|\$\{HOME\})(\/.*)?$/.exec(path); + const expanded = prefixed ? `${home}${prefixed[1] ?? ""}` : path; + if (expanded.length === 0 || expanded.length > MAX_PHYSICAL_PATH) return null; + if (isAbsolute(expanded)) return physicalWalk("/", expanded); + if (!cwd) return null; + let base = bases?.get(cwd); + if (base === undefined) { + base = physicalWalk("/", resolve(cwd)); + bases?.set(cwd, base); + } + return base === null ? null : physicalWalk(base, expanded); +} + +/** Agent settings files under the home directory, relative to it. */ +const HOME_AGENT_SETTINGS_FILES: readonly string[] = [ + ".claude/settings.json", + ".claude/settings.local.json", + ".codex/hooks.json", + ".codex/config.toml", + ".copilot/hooks/failproofai.json", + ".cursor/hooks.json", + ".config/opencode/opencode.json", + ".config/opencode/opencode.jsonc", + ".config/opencode/config.json", + ".config/opencode/plugins/failproofai.mjs", + ".opencode/opencode.json", + ".pi/agent/settings.json", + ".gemini/settings.json", + ".gemini/config/hooks.json", + ".agents/plugins/failproofai/hooks/hooks.json", + ".config/goose/config.yaml", + ".factory/hooks.json", + ".config/devin/config.json", + ".hermes/config.yaml", + ".openclaw/openclaw.json", +]; + +/** The agent directories under the home directory, relative to it. */ +const HOME_AGENT_CONFIG_DIRS: readonly string[] = [ + ".claude", ".codex", ".copilot", ".cursor", ".config/opencode", ".opencode", ".pi", ".gemini", + ".agents", ".config/goose", ".factory", ".config/devin", ".hermes", ".openclaw", +]; + +/** A project's agent settings files, relative to the project root. */ +const PROJECT_AGENT_SETTINGS_FILES: readonly string[] = [ + ".claude/settings.json", + ".claude/settings.local.json", + ".codex/hooks.json", + ".codex/config.toml", + ".cursor/hooks.json", + ".github/hooks/failproofai.json", + ".opencode/opencode.json", + ".pi/settings.json", + ".gemini/settings.json", + ".agents/hooks.json", + ".factory/hooks.json", + ".devin/config.json", +]; + +function realpathsOf(paths: readonly string[]): Set { + const out = new Set(); + for (const path of paths) { + const real = settingsLinkTarget(path); + if (real !== null) out.add(real); + } + return out; +} + +/** + * Where a settings path really is: its realpath, or — for a link whose target + * does not exist yet — that target, walked the way the kernel would create + * it: `.claude/settings.local.json -> ../config/new.json` makes a first + * write of config/new.json a write of the settings. Null when there is + * neither a file nor a link there. + */ +function settingsLinkTarget(path: string): string | null { + try { + return realpathSync(path); + } catch { + try { + if (!lstatSync(path).isSymbolicLink()) return null; + } catch { + return null; + } + return physicalAgentPath(path, undefined); + } +} + +/** + * Where the settings this session's agent reads really are, after symlinks: + * the home directory's files (the dotfiles layout, `~/.claude/settings.json` + * linked into a repository of dotfiles), the project's files (a committed + * `.claude/settings.json` that links to `config/claude.json`), and the file the + * hook itself was loaded from. The file an agent edits there names no agent + * directory at all. + */ +function agentSettingsRealTargets(cwd: string | undefined, extraPaths: readonly string[]): Set { + const home = homedir(); + return realpathsOf([ + ...HOME_AGENT_SETTINGS_FILES.map((path) => join(home, path)), + ...agentProjectRoots(cwd).flatMap((root) => PROJECT_AGENT_SETTINGS_FILES.map((path) => join(root, path))), + ...agentLocalSettingsFiles(cwd), + ...extraPaths, + ]); +} + +/** + * Where Claude Code reads this session's `settings.local.json`, the places the + * walk to the repository root does not reach included: a linked worktree's + * are at the main checkout's root (the same files `config --status` reads). + */ +function agentLocalSettingsFiles(cwd: string | undefined): string[] { + return cwd ? claudeLocalSettingsPaths(cwd) : []; +} + +/** + * The directories whose project settings apply to a session in `cwd`: `cwd` + * itself and each directory above it up to the repository root. Agents read + * project and local settings at the root from a subdirectory (Claude Code + * keeps `settings.local.json` there), so a root file's link target is theirs + * too. Outside a repository, `cwd` alone. + */ +function agentProjectRoots(cwd: string | undefined): string[] { + if (!cwd) return []; + const roots: string[] = []; + let dir = resolve(cwd); + for (let depth = 0; depth < 32; depth++) { + roots.push(dir); + if (existsSync(join(dir, ".git"))) return roots; + const parent = dirname(dir); + if (parent === dir) break; + dir = parent; + } + return [resolve(cwd)]; +} + +/** + * Directories whose every file is part of an agent's hooks, wherever they + * live: what Hermes' `plugins/failproofai` links to (the package's + * `hermes-plugin/`, or a copy), in every profile, and the package's own plugin + * directories, which OpenClaw and Pi load in place. Editing one of their + * files changes what the hook does without touching any settings file. + */ +function agentPluginTrees(): string[] { + const home = homedir(); + const hermesHomes = [join(home, ".hermes")]; + try { + for (const name of readdirSync(join(home, ".hermes", "profiles"))) hermesHomes.push(join(home, ".hermes", "profiles", name)); + } catch { + // No profiles. + } + try { + for (const name of readdirSync(home)) if (name.startsWith(".hermes-")) hermesHomes.push(join(home, name)); + } catch { + // Unreadable home: the default profile alone. + } + const trees = new Set(); + for (const hermes of hermesHomes) { + const link = join(hermes, "plugins", "failproofai"); + try { + const real = realpathSync(link); + if (real !== link) trees.add(real); + } catch { + // Not installed for this profile. + } + } + const packageRoot = process.env.FAILPROOFAI_PACKAGE_ROOT; + if (packageRoot) { + for (const name of ["hermes-plugin", "openclaw-plugin", "pi-extension"]) { + const dir = join(packageRoot, name); + try { + trees.add(realpathSync(dir)); + } catch { + // Not in this package. + } + } + } + return [...trees]; +} + +/** Whether `path` is one of `trees` or lies inside one. */ +function insideAgentPluginTree(path: string, trees: readonly string[]): boolean { + return trees.some((tree) => path === tree || path.startsWith(`${tree}/`)); +} + +/** The string values of a tool input, a few levels deep (Codex wraps a patch in an array). */ +function agentSettingsInputStrings(value: unknown, depth = 0, out: string[] = []): string[] { + if (typeof value === "string") out.push(value); + else if (depth < 3 && Array.isArray(value)) for (const item of value) agentSettingsInputStrings(item, depth + 1, out); + else if (depth < 3 && value && typeof value === "object") { + for (const item of Object.values(value as Record)) agentSettingsInputStrings(item, depth + 1, out); + } + return out; +} + +/** + * The files a patch touches: OpenAI's apply_patch envelope (`*** Update File:`, + * `*** Add File:`, `*** Delete File:`, `*** Move to:`) and unified-diff headers. + * Leading whitespace is allowed on each, because Codex applies an indented + * marker too. + */ +export function agentPatchTargetPaths(patch: string): string[] { + const out: string[] = []; + for (const [, path] of patch.matchAll(/^[ \t]*\*\*\* (?:Add File|Update File|Delete File|Move to): *(.+?) *$/gm)) { + out.push(path); + } + for (const [, path] of patch.matchAll(/^[ \t]*(?:\+\+\+|---) (?:[ab][\\/])?([^\t\r\n]+?)(?:\t.*)? *$/gm)) { + if (path !== "/dev/null") out.push(path); + } + return out; +} + +/** The keys a patch arrives under, across the CLIs that canonicalize apply_patch to Edit. */ +const AGENT_PATCH_CARRIER_KEYS: readonly string[] = ["patch", "patchText", "patch_text", "input", "command", "diff", "changes"]; + +/** + * Every path a file-writing tool call would write. + * + * `file_path` (Write, Edit, MultiEdit), `notebook_path` (NotebookEdit) and + * `path` cover the canonical inputs. Codex, Copilot and OpenCode `apply_patch` + * canonicalize to `Edit` with the paths inside the patch text, so the keys a + * patch travels under are read as patches as well, whether or not a path key is + * there too. `content`, `old_string` and `new_string` never are: a Write whose + * content happens to be a diff writes its own file_path. + */ +export function agentToolWritePaths(toolInput: Record | undefined): string[] { + if (!toolInput) return []; + const named = ["file_path", "notebook_path", "path"] + .map((key) => toolInput[key]) + .filter((value): value is string => typeof value === "string" && value.length > 0); + const patched = AGENT_PATCH_CARRIER_KEYS.flatMap((key) => + agentSettingsInputStrings(toolInput[key]).flatMap((text) => agentPatchTargetPaths(text)), + ); + return [...named, ...patched]; +} + +/** + * The agent settings file a file-tool call would write, or null. + * + * Checked as written, then after symlinks: a path that leads into an agent + * directory through a link, and a file that IS the target of one of the agent's + * settings links, are the same file to the agent CLI. `extraPaths` are settings + * files known for this session that no shape describes: the file the hook was + * loaded from when `CLAUDE_CONFIG_DIR` or `CODEX_HOME` moved it. + */ +export function agentSettingsWriteTarget( + toolInput: Record | undefined, + cwd: string | undefined, + extraPaths: readonly string[] = [], +): string | null { + const extras = new Set([...extraPaths.map((path) => resolve(path)), ...relocatedAgentSettings(extraPaths)]); + let realTargets: Set | undefined; + let trees: string[] | undefined; + for (const raw of agentToolWritePaths(toolInput)) { + const lexical = resolveAgentSettingsCandidate(raw, cwd); + if (isAgentSettingsPath(lexical) || extras.has(lexical)) return lexical; + // Relative and no cwd: nothing on disk to follow. + if (!isAbsolute(lexical)) continue; + const real = realpathOfAgentSettingsCandidate(lexical); + if (real !== lexical && (isAgentSettingsPath(real) || extras.has(real))) return lexical; + realTargets ??= agentSettingsRealTargets(cwd, [...extras]); + if (realTargets.has(real)) return lexical; + // `lexical` lost its `..` before any link was followed; the filesystem + // follows the link first: `link/../settings.json` with `link -> + // ~/.claude/subdir` writes `~/.claude/settings.json`. + const physical = physicalAgentPath(raw, cwd); + if (physical !== null && physical !== real && (isAgentSettingsPath(physical) || extras.has(physical) || realTargets.has(physical))) { + return lexical; + } + trees ??= agentPluginTrees(); + if ([lexical, real, physical].some((path) => path !== null && insideAgentPluginTree(path, trees!))) return lexical; + } + return null; +} + +/** Shell punctuation that can stand around a word without being part of the path. */ +function bareAgentSettingsWord(word: string): string { + return word.replace(/^[(){}'"`;&|<>]+|[(){}'"`;&|<>]+$/g, ""); +} + +/** What can stand right before a path that starts a shell word, a quoted string or a value. */ +const PATH_START_EDGE = String.raw`\s'"\x60;&|()<>=,{}\[\]:@/`; + +/** + * A path as a regex literal that must start and end where a shell word or a + * quoted string would — or right after a glued short option (`-C/srv/x`) — so + * `/backup/srv/profile/settings.json` is not read as `/srv/profile/settings.json`. + */ +function agentSettingsPathInTextRe(path: string, isDirectory: boolean): RegExp { + const escaped = path.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + const start = `(?<=^|[${PATH_START_EDGE}]|(?:^|[${PATH_START_EDGE}])-[A-Za-z])`; + return new RegExp(`${start}${escaped}${isDirectory ? "[\\\\/]?" : ""}(?=$|[\\s'"\`;&|()<>])`, "i"); +} + +/** A directory as a regex literal that matches it and every path inside it, from where a word starts. */ +function agentSettingsTreeInTextRe(path: string): RegExp { + const escaped = path.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + const start = `(?<=^|[${PATH_START_EDGE}]|(?:^|[${PATH_START_EDGE}])-[A-Za-z])`; + return new RegExp(`${start}${escaped}(?=$|[\\/\\s'"\`;&|()<>])`, "i"); +} + +/** + * A word as each form the shell may hand it over in: the word itself, and the + * value after `=` for `--output=`, `of=` and `FOO=`. + */ +function agentSettingsWordForms(raw: string): string[] { + const word = bareAgentSettingsWord(raw); + const eq = word.indexOf("="); + return eq > 0 ? [word, word.slice(eq + 1)] : [word]; +} + +/** + * Settings files and directories known for this session beyond the shapes: + * `extraPaths` with their directories, and the real locations behind the home + * directory's agent links (a dotfiles checkout). A shell command reaching any of + * them reaches the agent's settings. + */ +function agentSettingsShellExtras( + extraPaths: readonly string[], + cwd: string | undefined, +): { files: Set; dirs: Set; trees: string[] } { + const files = new Set(); + const dirs = new Set(); + const home = homedir(); + for (const absolute of relocatedAgentSettings(extraPaths)) { + files.add(absolute); + dirs.add(dirname(absolute)); + // And where it really is, existing or not yet: CLAUDE_CONFIG_DIR's + // settings.json linked to /tmp/actual/primary.json is written as that. + const real = settingsLinkTarget(absolute); + if (real !== null && real !== absolute) files.add(real); + } + // `.github/hooks/` is protected as a directory only in a project that keeps + // failproofai's Copilot hooks there; elsewhere it is where git hooks live. + const roots = agentProjectRoots(cwd); + for (const root of roots) { + if (existsSync(join(root, ".github", "hooks", "failproofai.json"))) dirs.add(join(root, ".github", "hooks")); + } + // A project's settings linked elsewhere (`.claude/settings.json -> + // ../config/claude.json`) are written through the target's own name, from + // the root's subdirectories too. + const projectFiles = [ + ...roots.flatMap((root) => PROJECT_AGENT_SETTINGS_FILES.map((path) => join(root, path))), + ...agentLocalSettingsFiles(cwd), + ]; + for (const lexical of [...HOME_AGENT_SETTINGS_FILES.map((path) => join(home, path)), ...projectFiles]) { + const real = settingsLinkTarget(lexical); + if (real !== null && real !== lexical) files.add(real); + } + for (const relativePath of HOME_AGENT_CONFIG_DIRS) { + const lexical = join(home, relativePath); + try { + const real = realpathSync(lexical); + if (real !== lexical) dirs.add(real); + } catch { + // Not on this machine. + } + } + return { files, dirs, trees: agentPluginTrees() }; +} + +/** + * The session's settings files that no shape describes — a config directory + * moved by `CLAUDE_CONFIG_DIR` or `CODEX_HOME` — with the files beside them + * that switch the same hooks off: Claude Code's `settings.local.json`, Codex's + * `config.toml` (its hook trust and `[features] hooks`). A file the shapes + * already cover adds nothing: its directory may be a shared one + * (`.github/hooks`), where a directory rule would only refuse ordinary work. + */ +function relocatedAgentSettings(extraPaths: readonly string[]): string[] { + const out: string[] = []; + for (const path of extraPaths) { + const absolute = resolve(path); + if (isAgentSettingsPath(absolute)) continue; + out.push(absolute); + const name = basename(absolute).toLowerCase(); + if (name === "settings.json") out.push(join(dirname(absolute), "settings.local.json")); + if (name === "hooks.json") out.push(join(dirname(absolute), "config.toml")); + } + return out; +} + +/** A path under the home directory as `~/…` too, the way commands usually spell it. */ +function withAgentSettingsHomeForm(path: string): string[] { + const home = homedir(); + const rel = relative(home, path); + return rel && !rel.startsWith("..") && !isAbsolute(rel) ? [path, `~/${rel}`] : [path]; +} + +/** Text that every agent settings path or directory contains somewhere. */ +const AGENT_SETTINGS_HINT_SOURCE = + "claude|codex|cursor|copilot|github|opencode|\\.pi|gemini|agents|factory|devin|goose|hermes|openclaw|vscode|settings|hooks|config|plugins|extensions"; + +/** + * The hint for this session: the agents' names, plus every name in the + * session's extra settings files and the real locations behind the home + * directory's links, so a word that could reach one is never skipped. + */ +function agentSettingsHintFrom(extras: { files: Set; dirs: Set; trees: readonly string[] }): RegExp { + const names = [...extras.files, ...extras.dirs, ...extras.trees] + .flatMap((path) => path.split(/[\\/]/)) + .filter((segment) => segment.length > 2) + .map((segment) => segment.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")); + return new RegExp([AGENT_SETTINGS_HINT_SOURCE, ...names].join("|"), "i"); +} + +/** + * What a shell command can name for this session: the shapes, anywhere in its + * text; each word on its own, home expanded and normalised; and the session's + * extra files and directories. Relative words are left to the caller, which + * knows the directory a `cd` has moved the shell to. + */ +export function agentSettingsShellMatcher( + extraPaths: readonly string[], + cwd?: string, +): { + names: (text: string) => boolean; + hint: RegExp; + /** Whether a word (relative to `cwd` when relative) leads to one of them through a symlink. */ + throughLinks: (word: string, cwd: string | undefined) => boolean; + /** + * The files behind the session's settings links — a relocated settings + * file's target, a project's, the dotfiles' — in each spelling a command + * may use, for a glob to be matched against as well. + */ + linkedFiles: string[]; +} { + const extras = agentSettingsShellExtras(extraPaths, cwd); + const hint = agentSettingsHintFrom(extras); + const textForms = [ + ...[...extras.files].flatMap((path) => withAgentSettingsHomeForm(path).map((form) => agentSettingsPathInTextRe(form, false))), + ...[...extras.dirs].flatMap((path) => withAgentSettingsHomeForm(path).map((form) => agentSettingsPathInTextRe(form, true))), + // A plugin tree is reached by any path inside it, not only by its own name. + ...extras.trees.flatMap((path) => withAgentSettingsHomeForm(path).map((form) => agentSettingsTreeInTextRe(form))), + ]; + const names = (text: string): boolean => { + if (AGENT_SETTINGS_IN_TEXT_RE.test(text) || AGENT_CONFIG_DIR_IN_TEXT_RE.test(text)) return true; + if (textForms.some((re) => re.test(text))) return true; + for (const raw of text.split(/\s+/)) { + // A word with none of the agents' names in it cannot be one of their + // paths; skipping it spares a path resolution per word of a long line. + if (!hint.test(raw)) continue; + for (const word of agentSettingsWordForms(raw)) { + if (!word || word.startsWith("-")) continue; + // A variable other than HOME is the caller's to follow (it tracks which + // ones hold an agent path); resolving `$D` as a file name means nothing. + if (word.includes("$") && !/^\$\{?HOME\}?(?:[\\/]|$)/.test(word)) continue; + const path = resolveAgentSettingsCandidate(word, undefined); + if (isAgentSettingsPath(path) || isAgentConfigDirPath(path)) return true; + if (isAbsolute(path) && (extras.files.has(path) || extras.dirs.has(path.replace(/[\\/]+$/, "")))) return true; + if (isAbsolute(path) && insideAgentPluginTree(path.replace(/[\\/]+$/, ""), extras.trees)) return true; + } + } + return false; + }; + // A word whose own text names nothing can still lead to a settings file: a + // link in the project (`cfg.json -> ~/.claude/settings.json`), a linked + // directory (`agent-dir/settings.json`), a `..` after a link. Looked up on + // disk, so ahead of the hint, which only reads the text; once per word. + const physicalHits = new Map(); + const physicalBases = new Map(); + const throughLinks = (raw: string, cwd: string | undefined): boolean => { + const forms = agentSettingsWordForms(raw); + // A value glued to a short option is a path too: `-oarchive/link/../settings.json`. + if (/^-[A-Za-z]./.test(raw) && !raw.startsWith("--")) forms.push(...agentSettingsWordForms(raw.slice(2))); + for (const word of forms) { + if (!word || word.startsWith("-") || (word.includes("$") && !/^\$\{?HOME\}?(?:[\\/]|$)/.test(word))) continue; + const key = `${cwd ?? ""}\0${word}`; + let hit = physicalHits.get(key); + if (hit === undefined) { + const physical = physicalAgentPath(word, cwd, physicalBases); + hit = physical !== null && physical !== resolveAgentSettingsCandidate(word, cwd) && names(physical); + physicalHits.set(key, hit); + } + if (hit) return true; + } + return false; + }; + const linkedFiles = [...extras.files].flatMap((path) => withAgentSettingsHomeForm(path)); + return { names, hint, throughLinks, linkedFiles }; +} + +/** Whether a program handed to an interpreter builds an agent settings path. */ +export function programNamesAgentSettings(program: string): boolean { + return AGENT_DIR_IN_PROGRAM_RE.test(program); +} + +/** + * The directory a shell command runs in: Antigravity's `run_command` carries + * its own `Cwd` (canonicalized to `tool_input.cwd`), which wins over the + * session's; every other CLI runs in the session's cwd. + */ +export function agentSettingsShellCwd(toolInput: Record | undefined, sessionCwd: string | undefined): string | undefined { + // Codex's shell tool names its directory `workdir` (found by the #1105 + // review: `printf '{}' > hooks.json` with workdir `~/.codex` was read as a + // write in the project root). + const own = typeof toolInput?.cwd === "string" && toolInput.cwd !== "" ? toolInput.cwd : toolInput?.workdir; + if (typeof own !== "string" || own.length === 0) return sessionCwd; + return resolveAgentSettingsCandidate(own, sessionCwd); +} + +const AGENT_SETTINGS_ANYWHERE_SEGMENT = "⁘anywhere"; +/** + * Where a shell command starts when the agent may have run it in a directory + * its hook does not report (Codex's `workdir`). Deep, so a `..` climbs inside + * it and the walk still knows the word was read from an unknown place. + */ +export const AGENT_SETTINGS_ANYWHERE_ROOT = `/${Array.from({ length: 32 }, () => AGENT_SETTINGS_ANYWHERE_SEGMENT).join("/")}`; +/** + * The directory an unknown start may be, for the settings walk: Codex's own + * config directory only (a relocated CODEX_HOME arrives as one of the + * session's extra paths). Only Codex hides where a command runs, and its own + * files (`config.toml`, `hooks.json`) are what it would aim at; assuming every + * agent's directory refused ordinary relative writes of `config.json`, + * `settings.json` or `hooks.json` in any project. Another agent's settings + * named by path (`~/.claude/settings.json`) are caught by the ordinary walk. + */ +const AGENT_SETTINGS_ANYWHERE_ANCHORS: readonly string[] = [".codex"]; + +/** + * Whether a path resolved against `AGENT_SETTINGS_ANYWHERE_ROOT` is a settings + * file or config directory from some place it may really have started: the + * agents' config directories, and the directories of the session's extra + * settings files. `names` is the session's ordinary matcher. + */ +export function agentSettingsFromAnywhere( + names: (text: string) => boolean, + extraPaths: readonly string[], +): (text: string) => boolean { + const extraDirs = [...new Set(extraPaths.map((path) => dirname(resolve(path))))]; + return (text) => { + if (!text.includes(AGENT_SETTINGS_ANYWHERE_SEGMENT)) return false; + for (const word of text.split(/\s+/)) { + if (!word.includes(AGENT_SETTINGS_ANYWHERE_SEGMENT)) continue; + const at = word.indexOf(`/${AGENT_SETTINGS_ANYWHERE_SEGMENT}`); + if (at === -1) return true; + const rel = word + .slice(at) + .replace(new RegExp(`^(?:/${AGENT_SETTINGS_ANYWHERE_SEGMENT})+`), "") + .replace(/^\/+/, ""); + // A segment left inside the path is one no walk produces: refused. + if (rel.includes(AGENT_SETTINGS_ANYWHERE_SEGMENT)) return true; + for (const anchor of AGENT_SETTINGS_ANYWHERE_ANCHORS) { + if (names(rel ? `/${anchor}/${rel}` : `/${anchor}`)) return true; + } + for (const dir of extraDirs) { + if (names(rel ? join(dir, rel) : dir)) return true; + } + } + return false; + }; +} + +/** + * Commands of the agent CLIs themselves that turn hooks off for good, with no + * settings path in them: `codex features disable hooks` writes + * `[features] hooks = false` into config.toml (verified on Codex 0.160.0), and + * `pi remove ` takes it out of Pi's settings. Hermes' + * and OpenClaw's plugin commands are matched by their documented shape. A + * one-run override (`claude --settings`, `codex -c features.hooks=false`) + * starts a separate agent rather than changing this one's settings, and is + * not matched. + */ +const AGENT_CLI_HOOKS_OFF_RES: readonly RegExp[] = [ + /(?:^|[\s;&|(`])(?:[^\s;&|()`<>]*\/)?codex\s+(?:[^\n;&|]*\s)?features\s+disable\s+[^\n;&|]*\b(?:codex_)?hooks\b/i, + /(?:^|[\s;&|(`])(?:[^\s;&|()`<>]*\/)?pi\s+(?:remove|uninstall|rm)\s+[^\n;&|]*(?:failproofai|pi-extension)/i, + /(?:^|[\s;&|(`])(?:[^\s;&|()`<>]*\/)?(?:hermes|openclaw)\s+plugins?\s+(?:disable|remove|uninstall|rm|delete)\s+[^\n;&|]*failproofai/i, +]; + +export function agentCliSwitchesHooksOff(command: string): boolean { + return AGENT_CLI_HOOKS_OFF_RES.some((re) => re.test(command)); +} + +/** + * Agent paths as a glob would have to reach them: relative to a project, and + * under a home directory spelled every way a command can spell it. + */ +const PROJECT_AGENT_SETTINGS_GLOB_PATHS: readonly string[] = [ + ".claude", ".claude/settings.json", ".claude/settings.local.json", + ".codex", ".codex/hooks.json", ".codex/config.toml", + ".cursor", ".cursor/hooks.json", + ".github/hooks/failproofai.json", + ".opencode", ".opencode/opencode.json", ".opencode/plugins/failproofai.mjs", + ".pi", ".pi/settings.json", ".pi/extensions", + ".gemini", ".gemini/settings.json", + ".agents", ".agents/hooks.json", ".agents/plugins/failproofai", + ".factory", ".factory/hooks.json", + ".devin", ".devin/config.json", + "opencode.json", "opencode.jsonc", ".opencode/opencode.jsonc", + ".vscode/settings.json", +]; + +const HOME_AGENT_SETTINGS_GLOB_PATHS: readonly string[] = [ + ".claude", ".claude/settings.json", ".claude/settings.local.json", + ".codex", ".codex/hooks.json", ".codex/config.toml", + ".cursor", ".cursor/hooks.json", + ".copilot", ".copilot/hooks", ".copilot/hooks/failproofai.json", + ".config/opencode", ".config/opencode/opencode.json", ".config/opencode/plugins/failproofai.mjs", + ".pi", ".pi/agent/settings.json", ".pi/agent/extensions", + ".gemini", ".gemini/settings.json", ".gemini/config/hooks.json", + ".agents", ".agents/plugins/failproofai", ".agents/plugins/failproofai/hooks/hooks.json", + ".config/goose", ".config/goose/config.yaml", + ".factory", ".factory/hooks.json", + ".config/devin", ".config/devin/config.json", + ".hermes", ".hermes/config.yaml", ".hermes/plugins/failproofai", + ".openclaw", ".openclaw/openclaw.json", +]; + +/** + * Ordinary nested paths a glob aimed at agent settings must NOT reach. + * + * The state guard's decoys are top-level names, because its target is a + * top-level directory. Settings files sit one level down, so removing every + * `.json` one directory deep in a repository compiled to a pattern that reaches + * `.claude/settings.json` and no decoy at all. These are the ordinary files such + * a pattern also lands on — and the ordinary siblings of agent files that live + * in a shared directory (`~/.config`, `.github`, git hooks in `.github/hooks`), + * so a sweep of one reads as the sweep it is. Agents' own directories get no + * siblings here: a glob over `~/.claude` IS aimed at the settings inside it. + */ +const AGENT_SETTINGS_GLOB_DECOY_PATHS: readonly string[] = [ + "src/settings.json", "config/hooks.json", "app/config.toml", "deploy/config.yaml", + "lib/plugins/index.mjs", "projects", "docs", + ".config/git", ".config/gh", ".config/nvim", ".github/workflows", ".github/hooks/pre-commit", +]; + +const AGENT_SETTINGS_HOME_SPELLINGS = ["~", "$HOME", "${HOME}", "/home/u", "/Users/u", "/root"] as const; + +function underEveryAgentSettingsHome(paths: readonly string[]): string[] { + const homes = [...AGENT_SETTINGS_HOME_SPELLINGS, homedir().replaceAll("\\", "/")]; + return homes.flatMap((home) => paths.map((path) => `${home}/${path}`)); +} + +/** + * The paths a glob has to be able to reach to count as aimed at agent settings. + * + * When the session already stands in an agent directory, the files directly in + * it are reachable by a bare `*.json`, so their names join the list, and so do + * the session's extra settings files and directories. + */ +export function agentSettingsGlobCandidates(cwd: string | undefined, extraPaths: readonly string[] = []): string[] { + const candidates = [...PROJECT_AGENT_SETTINGS_GLOB_PATHS, ...underEveryAgentSettingsHome(HOME_AGENT_SETTINGS_GLOB_PATHS)]; + for (const absolute of relocatedAgentSettings(extraPaths)) { + candidates.push(...withAgentSettingsHomeForm(absolute), ...withAgentSettingsHomeForm(dirname(absolute))); + } + if (cwd && isAgentConfigDirPath(cwd)) { + const here = cwd.replaceAll("\\", "/").replace(/\/+$/, "").toLowerCase(); + for (const path of [...PROJECT_AGENT_SETTINGS_GLOB_PATHS, ...HOME_AGENT_SETTINGS_GLOB_PATHS]) { + // `.config/opencode/opencode.json` from inside `~/.config/opencode` is + // `opencode.json`: every split of the path whose directory half is where + // the session stands. + for (let cut = path.indexOf("/"); cut !== -1; cut = path.indexOf("/", cut + 1)) { + if (here.endsWith(`/${path.slice(0, cut).toLowerCase()}`)) candidates.push(path.slice(cut + 1)); + } + } + } + return candidates; +} + +/** + * Decoys for those candidates, in the same spellings, on top of the shared + * `baseDecoys`. From inside an agent directory the bare-name decoys go: they + * are what keeps `rm -rf *` allowed in a project, and in `~/.claude` that + * command removes the settings. + */ +export function agentSettingsGlobDecoys(cwd: string | undefined, baseDecoys: readonly string[]): string[] { + const decoys = [...baseDecoys, ...AGENT_SETTINGS_GLOB_DECOY_PATHS, ...underEveryAgentSettingsHome(AGENT_SETTINGS_GLOB_DECOY_PATHS)]; + return cwd && isAgentConfigDirPath(cwd) ? decoys.filter((decoy) => decoy.includes("/")) : decoys; +} diff --git a/src/hooks/builtin-policies.ts b/src/hooks/builtin-policies.ts index 717bd18c7..c68a80981 100644 --- a/src/hooks/builtin-policies.ts +++ b/src/hooks/builtin-policies.ts @@ -1,8 +1,9 @@ /** * Built-in security policies for Claude Code hooks. */ -import { resolve, join } from "node:path"; -import { lstatSync, readlinkSync, statSync } from "node:fs"; +import { resolve, join, posix } from "node:path"; +import { agentPathOf } from "./agent-path"; +import { accessSync, constants as fsConstants, lstatSync, readFileSync, readdirSync, readlinkSync, statSync } from "node:fs"; import { readFile, writeFile } from "node:fs/promises"; import { execSync, execFileSync } from "node:child_process"; import { homedir } from "node:os"; @@ -16,7 +17,18 @@ import { POLICY_CATALOG } from "./policy-catalog"; import { allow, deny, instruct } from "./policy-helpers"; import { normalizePolicyName, registerPolicy } from "./policy-registry"; import { hookLogWarn } from "./hook-logger"; - +import { + AGENT_SETTINGS_ANYWHERE_ROOT, + agentCliSwitchesHooksOff, + agentSettingsFromAnywhere, + agentSettingsGlobCandidates, + agentSettingsGlobDecoys, + agentSettingsShellCwd, + agentSettingsShellMatcher, + agentSettingsWriteTarget, + physicalAgentPath, + programNamesAgentSettings, +} from "./agent-settings-guard"; /** * Whether `resolved` lives under an agent CLI's home directory * (~/.claude/, ~/.codex/, ~/.copilot/, ~/.cursor/, ~/.pi/, ~/.gemini/, or any @@ -46,7 +58,6 @@ function isAgentInternalPath(resolved: string): boolean { } return false; } - /** * Whether `resolved` is a settings/hooks file for an agent CLI: * • Claude Code: `.claude/settings.json`, `.claude/settings.local.json`, etc. @@ -64,7 +75,9 @@ function isAgentInternalPath(resolved: string): boolean { * and the customization-root hook config * `~/.gemini/config/hooks.json`. * These must NEVER be edited by the agent itself — that would let it disable - * its own protections. + * its own protections. `block-read-outside-cwd` refuses READS of this list; + * writes are refused by `block-failproofai-commands`, against the wider list + * in agent-settings-guard.ts that covers all eleven integrations. */ function isAgentSettingsFile(resolved: string): boolean { if (/[\\/]\.claude[\\/]settings(?:\.[^/\\]+)?\.json$/.test(resolved)) return true; @@ -86,19 +99,15 @@ function isAgentSettingsFile(resolved: string): boolean { if (/[\\/]\.gemini[\\/]config[\\/]hooks\.json$/.test(resolved)) return true; return false; } - // Back-compat aliases — kept for any caller that imports the old names. const isClaudeInternalPath = isAgentInternalPath; const isClaudeSettingsFile = isAgentSettingsFile; - function getCommand(ctx: PolicyContext): string { return (ctx.toolInput?.command as string) ?? ""; } - function getFilePath(ctx: PolicyContext): string { return (ctx.toolInput?.file_path as string) ?? ""; } - /** * Parse a command string into argv tokens for safe pattern matching. * Splits on whitespace and strips simple single/double quotes. @@ -107,10 +116,8 @@ function getFilePath(ctx: PolicyContext): string { function parseArgvTokens(cmd: string): string[] { return cmd.trim().split(/\s+/).map((t) => t.replace(/^['"]|['"]$/g, "")); } - // Shell operators that always act as command separators when whitespace-delimited. const SHELL_OPERATORS = new Set(["&&", "||", "|", ";"]); - // Shell metacharacters that are unsafe when embedded inside a token. Any command // whose argv contains one of these in a token is rejected before allowlist matching. // This closes the bypass where operators are glued to a word (e.g. "nginx;evil" or @@ -120,10 +127,8 @@ const SHELL_OPERATORS = new Set(["&&", "||", "|", ";"]); const SHELL_METACHAR_RE = /[;&<>`$()\\]/; // -- Pre-compiled regex constants (hoisted to avoid per-call allocation) -- - // sanitizeJwt const JWT_RE = /eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/; - // sanitizeApiKeys const API_KEY_PATTERNS: Array<[RegExp, string]> = [ [/sk-ant-[A-Za-z0-9\-_]{20,}/, "Anthropic API key"], @@ -136,16 +141,12 @@ const API_KEY_PATTERNS: Array<[RegExp, string]> = [ [/sk_test_[A-Za-z0-9]{24,}/, "Stripe test secret key"], [/AIza[0-9A-Za-z\-_]{35}/, "Google API key"], ]; - // sanitizeConnectionStrings const CONNECTION_STRING_RE = /(?:postgresql|postgres|mysql|mongodb(?:\+srv)?|redis|amqps?|smtps?):\/\/[^@\s]+@/; - // sanitizePrivateKeyContent const PRIVATE_KEY_RE = /-----BEGIN (?:[A-Z]+ )?PRIVATE KEY-----/; - // sanitizeBearerTokens const BEARER_TOKEN_RE = /Authorization:\s*Bearer\s+[A-Za-z0-9\-._~+/]{20,}/i; - /** * Every pattern the `sanitize-*` policies treat as a secret, as one list. * @@ -171,17 +172,14 @@ export const SECRET_PATTERNS: ReadonlyArray = [ [CONNECTION_STRING_RE, "database credentials"], ...API_KEY_PATTERNS, ]; - // warnDestructiveSql / warnSchemaAlteration const SQL_TOOL_RE = /\b(?:psql|mysql|sqlite3|pgcli|clickhouse-client)\b/; const DESTRUCTIVE_SQL_RE = /\b(?:DROP\s+(?:TABLE|DATABASE|SCHEMA)|TRUNCATE\b)/i; const DELETE_NO_WHERE_RE = /\bDELETE\s+FROM\b/i; const SQL_WHERE_RE = /\bWHERE\b/i; const SCHEMA_ALTER_RE = /\bALTER\s+TABLE\b[\s\S]*\b(?:DROP\s+COLUMN|ADD\s+COLUMN|RENAME\s+(?:COLUMN|TO)|MODIFY\s+COLUMN)\b/i; - // warnPackagePublish const PUBLISH_CMD_RE = /(?:npm\s+publish|bun\s+publish|pnpm\s+publish|yarn\s+npm\s+publish|twine\s+upload|poetry\s+publish|cargo\s+publish|gem\s+push)\b/; - // protectEnvVars const ENV_PRINTENV_RE = /(?:^|\s|;|&&|\|\|)(?:env|printenv)(?:\s|$|;|&&|\|)/; const ECHO_ENV_RE = /echo\s+.*\$\{?[A-Za-z_]/; @@ -199,15 +197,12 @@ const PS_ENV_VAR_RE = /\$env:[A-Za-z_]/i; const PS_CHILDITEM_ENV_RE = /(?:Get-ChildItem|dir|gci|ls)\s+Env:/i; const DOTNET_GETENV_RE = /\[Environment\]::GetEnvironment/i; const CMD_ECHO_ENV_RE = /echo\s+%[A-Za-z_]/i; - // blockEnvFiles const ENV_FILE_PATH_RE = /(?:^|[\\/])\.env(?:\.|$)/; const ENV_CMD_RE = /\.env(?:\b|\s|$|\.)/; - // blockSudo const PS_ELEVATION_RE = /Start-Process\s+.*-Verb\s+RunAs/i; const RUNAS_RE = /(?:^|;|&&|\|\|)\s*runas\s/i; - // blockCurlPipeSh const CURL_PIPE_SH_RE = /(?:curl|wget)\s.*\|\s*(?:sh|bash|zsh|dash|ksh|csh|tcsh|fish|ash)\b/; /** @@ -252,7 +247,6 @@ const CURL_PIPE_SH_RE = /(?:curl|wget)\s.*\|\s*(?:sh|bash|zsh|dash|ksh|csh|tcsh| * a segment, or behind a runner (`npx`, `pnpm dlx`, `node`, `sh -c`) and its * flags. In every false positive above it sits where an ARGUMENT goes. */ - /** * Split a command into the pieces a shell would treat as separate commands. * @@ -262,7 +256,6 @@ const CURL_PIPE_SH_RE = /(?:curl|wget)\s.*\|\s*(?:sh|bash|zsh|dash|ksh|csh|tcsh| * argument of `echo`. */ const SEGMENT_SEPARATORS = /[;&|\n\r(){}`]+/; - /** * Tokens that stand in front of the real binary without being it: package * runners, interpreters, and the `exec`-alikes. Compared by basename, so @@ -274,12 +267,10 @@ const COMMAND_PREFIX_TOKENS = new Set([ "time", "timeout", "nice", "stdbuf", "xargs", "sudo", "doas", "sh", "bash", "zsh", "dash", "ksh", "fish", "ash", ]); - /** The binary itself, however it is pinned or pathed: `failproofai`, * `failproofai@latest`, `/usr/local/bin/failproofai`, * `./node_modules/.bin/failproofai`, `.../failproofai/bin/failproofai.mjs`. */ const SELF_BINARY_TOKEN_RE = /(?:^|\/)failproofai[^/]*$/; - /** * The same CLI, reached by path rather than by name. * @@ -288,23 +279,18 @@ const SELF_BINARY_TOKEN_RE = /(?:^|\/)failproofai[^/]*$/; * paused enforcement. Verified as a live bypass. */ const SELF_ENTRY_PATH_RE = /failproofai\/(?:dist\/(?:cli|index)\.mjs|bin\/failproofai\.mjs)$/; - /** `config`, and the two aliases the entrypoint normalizes to it. */ const CONFIG_SUBCOMMAND_RE = /^(?:config|configure|setup)$/; - /** `--pause`, with or without an `=value` tail. */ const PAUSE_FLAG_RE = /^--pause(?:=|$)/; - /** An `FOO=bar` prefix assignment, which a shell consumes before the command. */ const ENV_ASSIGNMENT_RE = /^[A-Za-z_][A-Za-z0-9_]*=/; - /** * A bare operand belonging to the runner in front of it — `timeout 30 …`, * `nice -n 5 …`. Skipped so the runner's argument is not mistaken for the * command. Safe to skip unconditionally: no binary is named `30` or `5m`. */ const RUNNER_OPERAND_RE = /^\d+[a-z]*$/i; - /** * True when `command` runs `failproofai config --pause` in command position. * @@ -315,7 +301,6 @@ const RUNNER_OPERAND_RE = /^\d+[a-z]*$/i; * errs toward refusing rather than toward silently suspending enforcement. */ type SelfInvocation = "pause" | "cli"; - /** * Classify a command by what it does to failproofai itself, or null when it * does nothing to failproofai at all. @@ -381,7 +366,6 @@ function classifySelfInvocation(raw: string): SelfInvocation | null { } return found; } - /** * Decode one ANSI-C `$'...'` body (the text between the quotes) to the bytes a * shell would produce. Covers the escape forms that can reconstruct an ASCII @@ -408,7 +392,6 @@ function decodeAnsiC(body: string): string { }, ); } - /** * Collapse the quoting a POSIX shell resolves LEXICALLY — before it execs a * command — so a literal matcher sees roughly what will actually run. @@ -446,20 +429,58 @@ function stripShellQuoting(command: string): string { ); return ansiDecoded.replace(/\\(.)/g, "$1").replace(/['"]/g, ""); } +/** + * `stripShellQuoting`, for the text a command's variables are read from. The + * quotes come off the same way, but a `$`, a backtick or a backslash the shell + * would NOT expand — inside single quotes or `$'…'`, or behind a backslash — + * stays escaped, so `B='$A'` is `B=\$A` here where the plain strip makes it + * `B=$A`, a reference the command never makes. One pass, linear. + */ +function stripShellQuotingKeepingLiterals(command: string): string { + const text = command.replace(/\\\r?\n/g, ""); + // Quote characters never reach the output, as in the plain strip. + const literal = (body: string): string => body.replace(/['"]/g, "").replace(/[\\$`]/g, "\\$&"); + let out = ""; + let inDouble = false; + for (let i = 0; i < text.length; i++) { + const ch = text[i]; + if (ch === "\\" && i + 1 < text.length) { + const next = text[++i]; + if (next === "\\" || next === "$" || next === "`") out += `\\${next}`; + else if (next !== "'" && next !== '"') out += next; + } else if (ch === '"') { + inDouble = !inDouble; + } else if (inDouble) { + if (ch !== "'") out += ch; + } else if (ch === "'") { + const close = text.indexOf("'", i + 1); + // Unclosed: the quote is dropped and the rest read as written. + if (close === -1) continue; + out += literal(text.slice(i + 1, close)); + i = close; + } else if (ch === "$" && text[i + 1] === "'") { + let close = i + 2; + while (close < text.length && text[close] !== "'") close += text[close] === "\\" ? 2 : 1; + if (close >= text.length) { + out += ch; + continue; + } + out += literal(decodeAnsiC(text.slice(i + 2, close))); + i = close; + } else out += ch; + } + return out; +} const PS_WEB_PIPE_RE = /(?:Invoke-WebRequest|iwr|Invoke-RestMethod|irm)\s+.*\|\s*(?:Invoke-Expression|iex)/i; - // blockForcePush const SHORT_FLAG_BUNDLE_RE = /^-[a-zA-Z]*f[a-zA-Z]*$/; const SAFE_FORCE_PREFIXES = ["--force-with-lease", "--force-if-includes"] as const; - // blockSecretsWrite const SECRET_FILE_RE = /\.(?:pem|key)$/; const SECRET_FILE_ID_RSA_RE = /id_rsa/; const SECRET_FILE_CREDENTIALS_RE = /credentials/; - // blockWorkOnMain const GIT_COMMIT_MERGE_RE = /git\s+(commit|merge|rebase|cherry-pick)\b/; - // blockFailproofaiCommands /** * The path component `name` (regex source), only where it STARTS a component: @@ -484,7 +505,6 @@ const GIT_COMMIT_MERGE_RE = /git\s+(commit|merge|rebase|cherry-pick)\b/; function pathComponent(name: string): string { return String.raw`${name}(?<=(?:^|[\\/\s"'\`=:;|&<>(){},])${name}|(?:^|\s)-[A-Za-z]+${name})`; } - /** * failproofai's INSTALLED CODE: the package a hook command runs, and the bin * entry that names it. @@ -498,11 +518,17 @@ function pathComponent(name: string): string { * tampered client never asks it. The state pattern below needs a `.` the * package path does not have (FailproofAI/agenteye#1796). * + * Project-scope hooks are portable instead: `npx -y failproofai --hook …`, so + * the committed file names no machine's path. npx runs a + * `node_modules/.bin/failproofai` it finds in the project, or in ANY directory + * above it, before the global install or its own cache, without checking what + * the file is. So one Write of `exit 0` to that path turned every later hook in + * that tree into an allow, and kept doing it in every later session + * (FailproofAI/agenteye#1795). That entry is matched below too. + * * A checkout of this repository matches none of the shapes below — no * `node_modules` above it, and its entry is `bin/failproofai.mjs` — so the guard * does not stand in front of working on failproofai itself. - * `node_modules/.bin/failproofai`, the stub `npx` prefers, is not matched here - * either (FailproofAI/agenteye#1795). * * Case-insensitive because macOS volumes are by default: every casing of these * paths opens the real file. `(?:\.?[\\/])*` absorbs the `//` and `/./` a path @@ -529,10 +555,22 @@ const FAILPROOFAI_CODE_PATH_RE = new RegExp( // the variables nvm and pnpm export for those directories. A FILE, so a // directory of that name (`~/bin/failproofai/src/…`) is not it. String.raw`(?:[\\/](?:bin|pnpm)|\$\{?(?:NVM_BIN|PNPM_HOME)\}?)[\\/](?:\.?[\\/])*failproofai(?:\.cmd|\.ps1)?(?![\w.@\\/-])`, + // The entry `npx -y failproofai` runs first: `.bin/failproofai` in a + // `node_modules` of the project or of any directory above it (and in the + // npx cache). With the shims npm (`.cmd`, `.ps1`) and bun (`.exe`, `.bunx`) + // write beside it on Windows. Not anchored on `node_modules`, so the + // relative `.bin/failproofai` a command run from inside `node_modules` + // names is the same file. `.bin` must start a path component + // (`pathComponent`), so `firmware.bin/failproofai` is not it, while + // `>.bin/…` and a short option the path is glued to (`-O.bin/…`, + // `-so.bin/…`) are. A FILE, like the entry above: the rest of + // `node_modules/.bin` (every other package's binary, run by path all the + // time) stays out of it. + pathComponent(String.raw`\.bin`) + + String.raw`[\\/](?:\.?[\\/])*failproofai(?:\.(?:cmd|ps1|exe|bunx))?(?![\w.@\\/-])`, ].join("|"), "i", ); - /** * failproofai's own files: its state, and the installed code above. * @@ -548,7 +586,6 @@ const FAILPROOFAI_STATE_PATH_RE = new RegExp( String.raw`\.failproofai(?:\/|\b)|` + FAILPROOFAI_CODE_PATH_RE.source, "i", ); - /** * Which of failproofai's own files `path` names, for a deny message that says * which. Tool input is untrusted JSON, so a non-string is read the way @@ -560,7 +597,6 @@ function failproofaiFileKind(path: unknown): "state" | "code" | null { if (!FAILPROOFAI_STATE_PATH_RE.test(text)) return null; return FAILPROOFAI_CODE_PATH_RE.test(text) ? "code" : "state"; } - /** * The file a write to `path` actually changes, every symlink resolved. * @@ -623,7 +659,6 @@ function resolveWriteTarget(path: unknown, cwd: unknown): string { return ""; } } - /** * Everything the state guard is allowed to let PAST, as a list of commands that * can only read. @@ -653,6 +688,8 @@ const STATE_READ_COMMANDS = new Set([ // Contents "cat", "bat", "less", "more", "head", "tail", "nl", "strings", "xxd", "od", "jq", "yq", "diff", "cmp", "wc", "sort", "uniq", "column", "awk", "cut", + // Filters with no output file of their own: `cat … | tr a-z A-Z` reads. + "tr", "tac", "rev", "fold", "fmt", "expand", "unexpand", "paste", "comm", "join", // Listing and metadata "ls", "dir", "tree", "stat", "file", "du", "df", "readlink", "realpath", "basename", "dirname", "pwd", "test", "find", @@ -673,7 +710,6 @@ const STATE_READ_COMMANDS = new Set([ // blocking the ordinary way of checking whether the state is there. "[", "[[", "]", "]]", "test", "read", "for", "select", "case", "done", "fi", "esac", ]); - /** * Shell keywords that stand in FRONT of a real command. * @@ -683,7 +719,6 @@ const STATE_READ_COMMANDS = new Set([ * relying on `until` being unrecognised. */ const SHELL_KEYWORD_PREFIXES = new Set(["do", "then", "else", "elif", "if", "while", "until", "!"]); - /** * A loop header, which hands its word list to the body that follows. * @@ -693,7 +728,6 @@ const SHELL_KEYWORD_PREFIXES = new Set(["do", "then", "else", "elif", "if", "whi * mentions. The header's reach has to carry into the body, and stop at `done`. */ const LOOP_HEADER_RE = /(?:^|[\s(])(?:while|until|for|select)\s/; - /** * Commands whose verdict depends on which END of the argument list the state * path sits at. @@ -704,7 +738,6 @@ const LOOP_HEADER_RE = /(?:^|[\s(])(?:while|until|for|select)\s/; * only the destination separates them, so the destination is what decides. */ const COPY_COMMANDS = new Set(["cp", "rsync", "install"]); - /** * Commands that write EVERY path operand they are given. * @@ -714,7 +747,6 @@ const COPY_COMMANDS = new Set(["cp", "rsync", "install"]); * copy family: which end of the pipe the state sits on. */ const OPERAND_WRITE_COMMANDS = new Set(["tee"]); - /** * Readers whose LAST operand is an output file rather than another input. * @@ -724,7 +756,6 @@ const OPERAND_WRITE_COMMANDS = new Set(["tee"]); * `xxd ~/.failproofai/policies-config.json | head` stays allowed. */ const SECOND_OPERAND_WRITERS = new Set(["uniq", "xxd"]); - /** * Readers that write to a file NAMED BY A FLAG, per command. * @@ -735,11 +766,30 @@ const SECOND_OPERAND_WRITERS = new Set(["uniq", "xxd"]); * the config with whatever a server returns. */ const OUTPUT_FLAG_COMMANDS: Record = { + // `git log --output=` writes whatever `--format` says into it; `-o` is + // only an output for `archive` and `format-patch`, which the git branch checks. + git: ["--output", "--output-directory"], + // `gh release download -O `, `gh run download -D `. + gh: ["-O", "--output", "-D", "--dir"], sort: ["-o", "--output"], tree: ["-o", "--output"], - curl: ["-o", "--output", "--output-dir", "-D", "--dump-header", "--trace", "--trace-ascii"], + curl: [ + "-o", + "--output", + "--output-dir", + "-D", + "--dump-header", + "--trace", + "--trace-ascii", + "-c", + "--cookie-jar", + "--stderr", + "--libcurl", + "--etag-save", + "--hsts", + "--alt-svc", + ], }; - /** * `find` actions that write a file of their own, as opposed to running one. * @@ -748,7 +798,6 @@ const OUTPUT_FLAG_COMMANDS: Record = { * target, and `find` is on the read allowlist. */ const FIND_WRITE_ACTIONS = new Set(["-fprint", "-fprint0", "-fprintf", "-fls"]); - /** * Commands safe to hand a matched path to from `find -exec`. * @@ -765,18 +814,138 @@ const SAFE_EXEC_COMMANDS = new Set([ "grep", "egrep", "fgrep", "rg", "md5sum", "sha1sum", "sha256sum", "shasum", "cksum", "echo", "printf", "true", ":", ]); - /** * `git` subcommands that rewrite or delete a working tree. * * `git` is otherwise treated as carrying a path as PROSE — `git commit -m * "document ~/.failproofai layout"` must not deny — but `git clean -xdff * .failproofai` deletes the directory as thoroughly as `rm -rf` does. + * + * The second row moves or rewrites files too: `git mv .claude/settings.json x` + * takes an agent's hooks away, `git -C ~/.claude pull` or `merge` or `switch` + * replaces them with whatever another branch holds, `git apply` writes whatever + * its patch says, and `git bundle create ` writes the file it is given. + * These count only when an OPERAND names a protected path, the repository + * (`-C`) is one, or the shell stands in one — never a message: `git merge + * feature -m "notes about ~/.failproofai"` writes nothing there. */ const GIT_DESTRUCTIVE_SUBCOMMANDS = new Set([ "clean", "rm", "restore", "checkout", "reset", "stash", + "mv", "pull", "apply", "merge", "switch", "rebase", "am", "cherry-pick", "revert", "bundle", ]); - +/** + * The options whose value is a message (or a parent number), per destructive + * subcommand. Per subcommand because `-m` means something else elsewhere: + * `--merge` to `checkout`, `switch`, `restore` and `rebase`, `--message-id` + * to `am` — skipping its "value" there would skip the path. + */ +const GIT_MESSAGE_OPTIONS: Readonly>> = { + merge: new Set(["-m", "--message", "-F", "--file"]), + stash: new Set(["-m", "--message"]), + revert: new Set(["-m", "--mainline"]), + "cherry-pick": new Set(["-m", "--mainline"]), +}; +/** + * Whether one of a git command's OPERANDS names the target: messages and + * config values skipped, `-C`'s repository kept. Once quotes are gone (the + * unescaped pass) a message is no longer one word, so it runs to the next + * option instead. + */ +function gitOperandsNameTarget( + gitWords: string[], + subcommand: string, + names: (text: string) => boolean, + quoted: boolean, +): boolean { + const messageOptions = GIT_MESSAGE_OPTIONS[subcommand] ?? new Set(); + for (let i = 1; i < gitWords.length; i++) { + const word = gitWords[i]; + if (word === "-c" || word === "--config-env") { + i++; + continue; + } + if (messageOptions.has(word)) { + i++; + if (!quoted) while (i + 1 < gitWords.length && !gitWords[i + 1].startsWith("-")) i++; + continue; + } + if (messageOptions.size > 0 && (/^--(?:message|file|mainline)=/.test(word) || /^-m./.test(word))) continue; + if (names(word)) return true; + } + return false; +} +/** + * The directories a git command runs in: every `-C ` before the + * subcommand applies in turn, from where the shell may stand, so `git -C + * .claude log --output=settings.json` writes `.claude/settings.json`. Where + * the shell stands is unknown, the chain stays relative, which the shapes + * still read. A `-C` after the subcommand is that subcommand's own option. + */ +/** A repository `-C` names that the walk lost track of: any relative path in it may be the target. */ +const GIT_REPOSITORY_LOST = "\u0000lost"; + +function gitRepositoryDirs( + gitWords: string[], + cwds: ReadonlyArray, + /** The texts a word built by expansions may become, or null; `-C "$D"` is each of them. */ + valuesOf: (word: string) => string[] | null = () => null, +): string[] { + const chain: string[] = []; + const at = gitWords.findIndex((word) => commandBasename(word) === "git"); + for (let i = at + 1; at !== -1 && i < gitWords.length; i++) { + const word = gitWords[i]; + if (GIT_FLAGS_WITH_OPERANDS.has(word)) { + if (word === "-C" && i + 1 < gitWords.length) chain.push(gitWords[i + 1]); + i++; + continue; + } + if (!word.startsWith("-")) break; + } + if (chain.length === 0) return []; + // Each `-C` as every text it may be, a few chains at most. + let chains: string[][] = [[]]; + for (const step of chain) { + const forms = /[$`]/.test(step) ? valuesOf(step) ?? [step] : [step]; + chains = chains.flatMap((walked) => forms.map((form) => [...walked, form])); + // More chains than are kept: the repository may be any of them, so a + // relative path is read as reaching the target (found by hermes on #1053). + if (chains.length > 16) return [GIT_REPOSITORY_LOST]; + } + const dirs = new Set(); + for (const steps of chains) for (const cwd of cwds) { + // As text, and as chdir walks it: `-C link/..` with `link -> ~/.claude/x` + // is ~/.claude to git, whatever the text says. + for (const physical of [false, true]) { + let dir: string | undefined = cwd; + let relativeChain = ""; + for (const step of steps) { + const literal = !/[$`]/.test(step); + const walked = physical && literal ? physicalAgentPath(step, dir) : null; + const next = walked ?? cdDestination(dir, step); + if (next !== undefined) { + dir = next; + relativeChain = ""; + } else if (dir === undefined && isRelativeShellWord(step) && literal) { + relativeChain = posix.join(relativeChain, step); + } else { + dir = undefined; + relativeChain = ""; + } + } + if (dir !== undefined) dirs.add(dir); + else if (relativeChain) dirs.add(relativeChain); + } + } + return [...dirs]; +} +/** + * `git -c` settings that make git run a command: an alias beginning `!`, a + * pager, an editor, an ssh command, a filter or diff driver, a credential + * helper. `git -c alias.x='!rm -rf ~/.claude' x` is a deleter wearing a mention + * command's name. + */ +const GIT_CONFIG_RUNS_CODE_RE = + /^['"]?(?:alias\.[^=]+=\s*['"]?!|core\.(?:pager|editor|sshcommand|fsmonitor|hookspath|askpass)=|(?:diff|merge|filter)\.[^=]*\.(?:command|textconv|driver|clean|smudge|process)=|credential\.[^=]*helper=|sequence\.editor=)/i; /** * `git`'s own options that swallow the token after them. * @@ -786,7 +955,6 @@ const GIT_DESTRUCTIVE_SUBCOMMANDS = new Set([ * `git clean -xdff` of the state directory through. */ const GIT_FLAGS_WITH_OPERANDS = new Set(["-C", "-c", "--git-dir", "--work-tree", "--namespace", "--exec-path"]); - /** * Where the `git` subcommand sits in `args`, with git's own global options * walked off first, or `-1` when there is no subcommand at all. @@ -807,13 +975,11 @@ function gitSubcommandIndex(args: string[]): number { } return -1; } - /** The `git` subcommand, with git's own global options walked off first. */ function gitSubcommand(args: string[]): string | undefined { const i = gitSubcommandIndex(args); return i < 0 ? undefined : args[i]; } - /** * Commands that take a path as text to record or print, not as a file to open. * @@ -822,10 +988,8 @@ function gitSubcommand(args: string[]): string | undefined { * half of this policy already had to be anchored to avoid. */ const STATE_MENTION_COMMANDS = new Set(["git", "gh", "glab", "echo", "printf", "curl", "code", "open"]); - /** `find` actions that hand the matched paths to an arbitrary command. */ const FIND_EXEC_ACTIONS = new Set(["-exec", "-execdir", "-ok", "-okdir"]); - /** * The pieces a shell treats as SEPARATE commands. * @@ -836,10 +1000,8 @@ const FIND_EXEC_ACTIONS = new Set(["-exec", "-execdir", "-ok", "-okdir"]); * keeps `cat ~/.failproofai/config.json && rm /tmp/scratch` allowed. */ const PIPELINE_SEPARATORS = /\|\||&&|[;\n\r&]+/; - /** A `$VAR` or `${VAR}` reference, wherever it sits. */ const VAR_REFERENCE_RE = /\$\{?([A-Za-z_][A-Za-z0-9_]*)\}?/g; - /** * The spellings of the state directory a glob would have to match. * @@ -881,8 +1043,14 @@ const STATE_GLOB_CANDIDATES = [ "/opt/homebrew/bin/failproofai", "~/.bun/bin/failproofai", "~/.volta/bin/failproofai", + // The entry a project-scope `npx -y failproofai` runs (FailproofAI/agenteye#1795), + // and the Windows shims beside it. + ...["", ".cmd", ".ps1", ".exe", ".bunx"].flatMap((shim) => [ + `node_modules/.bin/failproofai${shim}`, + `./node_modules/.bin/failproofai${shim}`, + `.bin/failproofai${shim}`, + ]), ]; - /** * Ordinary paths a targeted pattern must NOT be able to match. * @@ -906,10 +1074,16 @@ const GLOB_DECOYS = [ "node_modules/@types/node", "./node_modules/@types/node", "/usr/local/lib/node_modules/npm", "/usr/lib/node_modules/npm", "/opt/homebrew/lib/node_modules/npm", "/usr/local/bin/node", "/opt/homebrew/bin/node", "~/.bun/bin/bun", "~/.volta/bin/node", + // Other packages' entries beside it, so `rm -rf node_modules/.bin/*` is the + // sweep it is rather than an aim at failproofai's. + "node_modules/.bin/tsc", "./node_modules/.bin/tsc", ".bin/tsc", + "node_modules/.bin/tsc.cmd", "./node_modules/.bin/tsc.cmd", ".bin/tsc.cmd", + // Another dotfile ending in `ai`, so the `.*ai` of a sed program is a sweep. + ".openai", ]; - /** - * True when this token is a glob that could expand onto failproofai's state. + * True when this token is a glob that could expand onto the target — failproofai's + * state, or an agent's settings files (see `ProtectedPathTarget`). * * The floor used to be a literal `fail` in the token, and that is exactly what * a glob is for: `rm -rf ~/.f*ailproofai` spells the same directory without the @@ -925,15 +1099,14 @@ const GLOB_DECOYS = [ * allowed because they sweep the decoys too; `rm -rf /tmp/test-failures*` stays * allowed because it reaches no candidate at all. */ -function globCouldNameState(raw: string): boolean { +function globCouldNameTarget(raw: string, target: ProtectedPathTarget): boolean { // Both readings of a trailing `)`: part of the pattern, and the close of a // subshell that wrapped it. Trying both is safe in the way widening always is // here — the decoy test still has to pass. const stripped = raw.replace(/^[()]+|[()]+$/g, ""); - return globWordCouldNameState(raw) || (stripped !== raw && globWordCouldNameState(stripped)); + return globWordCouldNameTarget(raw, target) || (stripped !== raw && globWordCouldNameTarget(stripped, target)); } - -function globWordCouldNameState(token: string): boolean { +function globWordCouldNameTarget(token: string, target: ProtectedPathTarget): boolean { if (!GLOB_METACHAR_RE.test(token)) return false; // Braces FIRST, because that is the order the shell works in: brace expansion // rewrites the word into several words, and only then is each one matched @@ -942,11 +1115,10 @@ function globWordCouldNameState(token: string): boolean { // shell turns into `~/.fa*ilproofai` and then into `~/.failproofai` — read as // naming nothing at all. for (const word of expandBraces(token)) { - if (wordNamesState(word)) return true; + if (wordNamesTarget(word, target)) return true; } return false; } - /** * How many words one token may expand into before the expansion is abandoned. * @@ -955,14 +1127,12 @@ function globWordCouldNameState(token: string): boolean { * `expandBraces`, which is a superset and so cannot hide anything. */ const BRACE_EXPANSION_LIMIT = 4096; - /** * How many expansion passes one token gets. One pass resolves the outermost * group of every word, so this is a nesting-depth budget — and, like the width * one, running out collapses what is left rather than leaving it unresolved. */ const BRACE_EXPANSION_ROUNDS = 24; - /** * The words a token expands into, the way the shell would expand them. * @@ -998,7 +1168,6 @@ function expandBraces(token: string): string[] { } return words.map(collapseBraces); } - /** * Every brace group in a word replaced by `*`, innermost first. * @@ -1028,7 +1197,6 @@ function collapseBraces(word: string): string { } return out; } - /** The first brace group in a word, split on its TOP-LEVEL commas. */ function firstBraceGroup(word: string): { start: number; end: number; alternatives: string[] } | null { const start = word.indexOf("{"); @@ -1056,7 +1224,6 @@ function firstBraceGroup(word: string): { start: number; end: number; alternativ } return null; } - /** * True when one brace-expanded word names the state. * @@ -1064,8 +1231,8 @@ function firstBraceGroup(word: string): { start: number; end: number; alternativ * `~/.{failproofai,other}` carries no `.failproofai` as written, and the word it * expands to needs no glob compilation to be recognised. */ -function wordNamesState(word: string): boolean { - if (FAILPROOFAI_STATE_PATH_RE.test(word)) return true; +function wordNamesTarget(word: string, target: ProtectedPathTarget): boolean { + if (target.namesLiteral(word)) return true; // Every path PREFIX, not just the whole word. The candidates are the state // directory itself, so `~/.f*ailproofai/policies-config.json` — a glob in a // segment that is not the last one — compiled to a pattern that could never @@ -1073,11 +1240,10 @@ function wordNamesState(word: string): boolean { // the state is naming the state. const segments = word.split("/"); for (let end = 1; end <= segments.length; end++) { - if (globPrefixNamesState(segments.slice(0, end).join("/"))) return true; + if (globPrefixNamesTarget(segments.slice(0, end).join("/"), target)) return true; } return false; } - /** * Everything that makes a token a PATTERN rather than a path. * @@ -1087,7 +1253,6 @@ function wordNamesState(word: string): boolean { * compiled wrong. */ const GLOB_METACHAR_RE = /[*?[{]|[@+!]\(/; - /** * A glob compiled to regex source, extended-glob operators included. * @@ -1099,18 +1264,18 @@ const GLOB_METACHAR_RE = /[*?[{]|[@+!]\(/; * reaching too far is settled by the decoy test and reaching too little is a * bypass. */ -function compileGlobPattern(token: string): string { +function compileGlobPattern(token: string, anyOne = "[^/]"): string { let pattern = ""; for (let i = 0; i < token.length; i++) { - const extended = extglobAt(token, i); + const extended = extglobAt(token, i, anyOne); if (extended) { pattern += extended.source; i = extended.end; continue; } const ch = token[i]; - if (ch === "*") pattern += "[^/]*"; - else if (ch === "?") pattern += "[^/]"; + if (ch === "*") pattern += `${anyOne}*`; + else if (ch === "?") pattern += anyOne; else if (ch === "[") { const bracket = bracketExpressionAt(token, i); if (!bracket) { @@ -1127,9 +1292,8 @@ function compileGlobPattern(token: string): string { } return pattern; } - /** One `@(…)`-style group, with its alternatives compiled as patterns. */ -function extglobAt(token: string, start: number): { source: string; end: number } | null { +function extglobAt(token: string, start: number, anyOne = "[^/]"): { source: string; end: number } | null { const operator = token[start]; if (!"?*+@!".includes(operator) || token[start + 1] !== "(") return null; const alternatives: string[] = []; @@ -1156,12 +1320,11 @@ function extglobAt(token: string, start: number): { source: string; end: number } // Unterminated, so the operator is an ordinary character rather than a group. if (i >= token.length) return null; - if (operator === "!") return { source: "[^/]*", end: i }; - const body = alternatives.map((alternative) => compileGlobPattern(alternative)).join("|"); + if (operator === "!") return { source: `${anyOne}*`, end: i }; + const body = alternatives.map((alternative) => compileGlobPattern(alternative, anyOne)).join("|"); const quantifier = operator === "?" ? "?" : operator === "*" ? "*" : operator === "+" ? "+" : ""; return { source: `(?:${body})${quantifier}`, end: i }; } - /** * One shell bracket expression, translated into a JavaScript character class. * @@ -1213,27 +1376,156 @@ function bracketExpressionAt(token: string, start: number): { source: string; en if (escaped.length === 0) return { source: "[^/]", end: i }; return { source: `[${negated ? "^" : ""}${escaped}]`, end: i }; } - /** * One `/`-delimited prefix of a brace-expanded word, compiled and tried against * the candidates. Braces are already gone by here; an unmatched one is literal. */ -function globPrefixNamesState(token: string): boolean { +/** One atom of a glob with no extended-glob groups. */ +type GlobAtom = { kind: "char"; ch: string } | { kind: "one" } | { kind: "star" } | { kind: "class"; test: RegExp }; +/** + * A glob of literals, `?`, `*` and bracket expressions as atoms, or null when + * it holds an extended-glob group (left to the regex path). Runs of `*` + * collapse into one, as the shell reads them without globstar. + */ +function globAtoms(token: string): GlobAtom[] | null { + const atoms: GlobAtom[] = []; + for (let i = 0; i < token.length; i++) { + if (extglobAt(token, i)) return null; + const ch = token[i]; + if (ch === "*") { + if (atoms[atoms.length - 1]?.kind !== "star") atoms.push({ kind: "star" }); + } else if (ch === "?") atoms.push({ kind: "one" }); + else if (ch === "[") { + const bracket = bracketExpressionAt(token, i); + if (!bracket) { + atoms.push({ kind: "char", ch: "[" }); + continue; + } + atoms.push({ kind: "class", test: new RegExp(`^${bracket.source}$`) }); + i = bracket.end; + } else atoms.push({ kind: "char", ch }); + } + return atoms; +} +/** + * Whether one path segment matches a segment's atoms, with no backtracking + * beyond the last `*`: the classic greedy wildcard walk, O(atoms × length). + * A regex built from many `*` backtracked through every way of splitting a + * candidate between them — a 226-character word ran for over a minute. + */ +function globSegmentMatches(atoms: GlobAtom[], text: string): boolean { + let a = 0; + let t = 0; + let starAtom = -1; + let starText = 0; + while (t < text.length) { + const atom = atoms[a]; + if (atom && atom.kind === "star") { + starAtom = a++; + starText = t; + continue; + } + if ( + atom && + (atom.kind === "one" || (atom.kind === "char" && atom.ch === text[t]) || (atom.kind === "class" && atom.test.test(text[t]))) + ) { + a++; + t++; + continue; + } + if (starAtom === -1) return false; + a = starAtom + 1; + t = ++starText; + } + while (atoms[a]?.kind === "star") a++; + return a === atoms.length; +} +/** What a glob is tried with: `test` on a whole string. */ +interface GlobTest { + test(text: string): boolean; +} + +/** + * A glob as a test on a whole string, without backtracking wherever the + * pattern allows: segment by segment through `globSegmentMatches` (a `*` and + * `?` stay inside a `/`-separated part), or over the whole string when + * `anyOne` is `.` (a `${v%pattern}` pattern, where they match `/` too). Only a + * pattern with an extended-glob group goes through a regex, its runs of `*` + * collapsed first. A regex built from many `*` backtracked through every way + * of splitting a candidate: `rm ~/.c` with 200 stars and `laude/settings.json` + * took 472 s in the state walk, past every hook timeout, where a timed-out + * hook allows (found by #1053's tests on #1058). Null when it cannot be read. + */ +function globTest(pattern: string, opts: { anyOne?: string; ignoreCase?: boolean } = {}): GlobTest | null { + const fold = (text: string) => (opts.ignoreCase ? text.toLowerCase() : text); + const anyOne = opts.anyOne ?? "[^/]"; + const parts = anyOne === "." ? [fold(pattern)] : fold(pattern).split("/"); + const atoms = parts.map((part) => globAtoms(part)); + if (atoms.every((a) => a !== null)) { + return { + test: (text) => { + const textParts = anyOne === "." ? [fold(text)] : fold(text).split("/"); + return textParts.length === atoms.length && textParts.every((part, i) => globSegmentMatches(atoms[i]!, part)); + }, + }; + } + let re: RegExp; + try { + re = new RegExp(`^(?:${compileGlobPattern(pattern.replace(/\*{2,}/g, "*"), anyOne)})$`, `s${opts.ignoreCase ? "i" : ""}`); + } catch { + return null; + } + return { + test: (text) => { + // V8 compiles a pattern on its first use, so one too large throws here. + try { + return re.test(text); + } catch { + return false; + } + }, + }; +} +/** + * A matcher for a glob word against whole paths: segment by segment, since no + * `*`, `?` or bracket expression matches `/`. Null when the word holds an + * extended-glob group. + */ +function globMatcher(token: string): ((path: string) => boolean) | null { + // Case-insensitively, on both sides: macOS resolves a path's literal parts + // whatever their case, so `rm ~/.CLAUDE/settings.js*` reaches the settings. + const segments = token.toLowerCase().split("/").map((segment) => globAtoms(segment)); + if (segments.some((atoms) => atoms === null)) return null; + return (path: string): boolean => { + const parts = path.toLowerCase().split("/"); + return parts.length === segments.length && parts.every((part, i) => globSegmentMatches(segments[i]!, part)); + }; +} +function globPrefixNamesTarget(token: string, target: ProtectedPathTarget): boolean { if (!GLOB_METACHAR_RE.test(token)) return false; - const pattern = "^" + compileGlobPattern(token); + const matcher = globMatcher(token); + if (matcher) { + if (!target.globCandidates.some(matcher)) return false; + return !target.globDecoys.some(matcher); + } + // Extended-glob groups go through a regex, with runs of `*` collapsed first. + const pattern = "^" + compileGlobPattern(token.replace(/\*{2,}/g, "*")); let re: RegExp; try { - // Case-insensitive, like FAILPROOFAI_STATE_PATH_RE: on a default macOS - // volume `NODE_MODULES/fail*` reaches the real `node_modules/failproofai`, - // because the literal parent is resolved by the filesystem. re = new RegExp(pattern + "$", "i"); } catch { return false; } - if (!STATE_GLOB_CANDIDATES.some((candidate) => re.test(candidate))) return false; - return !GLOB_DECOYS.some((decoy) => re.test(decoy)); + // V8 compiles a pattern on its first use, so one too large to compile throws + // here, not at `new RegExp`. A pattern that large is a literal far longer + // than any path it could be tried against. + try { + if (!target.globCandidates.some((candidate) => re.test(candidate))) return false; + return !target.globDecoys.some((decoy) => re.test(decoy)); + } catch { + return false; + } } - /** * Every command-substitution body in a command, `$(…)` and backticked alike. * @@ -1245,9 +1537,32 @@ function globPrefixNamesState(token: string): boolean { * the bodies are pulled out and judged as commands as well as, not instead of, * the whole string. */ +/** Substitution bodies one line is read with; past it the line is refused. */ +const MAX_SUBSTITUTION_BODIES = 64; + +/** + * The whole commands a line runs before the one a substitution body sits in: + * what moves the shell to where the body runs. Empty when there are none, or + * when the body is not found as written. + */ +function commandsBefore(command: string, body: string): string { + const at = command.indexOf(body); + if (at <= 0) return ""; + const head = command.slice(0, at); + const ranges = cutRanges(lexShell(head).splittable, PIPELINE_SEPARATORS); + if (ranges.length <= 1) return ""; + return head.slice(0, ranges[ranges.length - 1][0]).replace(/[\s;&|]+$/, ""); +} + function substitutionBodies(command: string): string[] { const bodies: string[] = []; for (let i = 0; i < command.length; i++) { + // A backslash makes the next character literal in every quoting context: + // `\`` and `\$(` never start a substitution. + if (command[i] === "\\") { + i++; + continue; + } if (command[i] === "`") { const close = command.indexOf("`", i + 1); if (close === -1) break; @@ -1255,7 +1570,9 @@ function substitutionBodies(command: string): string[] { i = close; continue; } - if (command[i] !== "$" || command[i + 1] !== "(") continue; + // `$(…)`, and the process substitutions `>(…)` and `<(…)`, which run their + // body as a command just the same: `echo x > >(tee )`. + if (!((command[i] === "$" || command[i] === ">" || command[i] === "<") && command[i + 1] === "(")) continue; let depth = 1; let j = i + 2; for (; j < command.length && depth > 0; j++) { @@ -1267,10 +1584,8 @@ function substitutionBodies(command: string): string[] { } return bodies; } - /** An output redirect and the token it targets: `>f`, `> f`, `2>f`, `>>f`, `>|f`. */ -const REDIRECT_TARGET_RE = /\d*>{1,2}\|?\s*("[^"]*"|'[^']*'|[^\s;&|<>]+)/g; - +const REDIRECT_TARGET_RE = /\d*>{1,2}\|?\s*("[^"]*"|'[^']*'|(?:\\.|[^\s;&|<>\\])+)/g; /** * Strip the punctuation a shell consumes, so `(cd` reads as `cd`. * @@ -1284,7 +1599,6 @@ const REDIRECT_TARGET_RE = /\d*>{1,2}\|?\s*("[^"]*"|'[^']*'|[^\s;&|<>]+)/g; function bareToken(token: string): string { return token.replace(/^[(){}'"]+|[(){}'"]+$/g, ""); } - /** * Quotes only, for the glob scan. * @@ -1295,18 +1609,52 @@ function bareToken(token: string): string { * arrived here decapitated — an unterminated group that expands to nothing and * compiles to a pattern matching nothing. A closing character that really did * belong to a shell group leaves a word still carrying the literal path, which - * the literal check reads, and `globCouldNameState` tries the stripped form too. + * the literal check reads, and `globCouldNameTarget` tries the stripped form too. */ function unquotedToken(token: string): string { return token.replace(/^['"]+|['"]+$/g, ""); } - /** The name a shell would exec, given a token: `/usr/bin/rm` → `rm`. */ function commandBasename(token: string): string { const bare = bareToken(token); return bare.slice(bare.lastIndexOf("/") + 1); } - +/** + * `text` cut where the shell cuts words: at blanks outside quotes, a backslash + * keeping the character after it. Quotes and backslashes stay in the words, so + * `cp /tmp/x "my cfg.json"` has the destination `"my cfg.json"`, not `cfg.json"`. + */ +function shellSplit(text: string): string[] { + const words: string[] = []; + let current = ""; + let quote: "'" | '"' | "ansi" | null = null; + for (let i = 0; i < text.length; i++) { + const ch = text[i]; + if (quote !== null) { + current += ch; + if (ch === "\\" && quote !== "'" && i + 1 < text.length) current += text[++i]; + else if (ch === (quote === "ansi" ? "'" : quote)) quote = null; + continue; + } + if (ch === "\\" && i + 1 < text.length) { + current += ch + text[++i]; + continue; + } + if (ch === "'" || ch === '"') { + quote = ch === "'" && text[i - 1] === "$" ? "ansi" : ch; + current += ch; + continue; + } + if (/\s/.test(ch)) { + if (current) words.push(current); + current = ""; + continue; + } + current += ch; + } + if (current) words.push(current); + return words; +} /** * Walk off everything a shell resolves before it settles on the command word, * and return the tokens from the command word on. Mirrors the walk in @@ -1314,10 +1662,20 @@ function commandBasename(token: string): string { * binary, and `xargs -0 rm -f` is the one that matters most here. */ function commandWords(simpleCommand: string): string[] { - const tokens = simpleCommand.trim().split(/\s+/).map(bareToken).filter(Boolean); + const tokens = shellSplit(simpleCommand.trim()).map(bareToken).filter(Boolean); let i = 0; while (i < tokens.length) { const token = tokens[i]; + // A quoted word in the command's place — a shell's `-c` program — is a + // command line of its own: `bash -c 'cat x'` runs `cat`. An assignment + // with a quoted value (`env "A=b c" cp …`) is still one assignment. + if (/\s/.test(token) && !ENV_ASSIGNMENT_RE.test(token)) { + const inner = shellSplit(token).map(bareToken).filter(Boolean); + if (inner.length > 1) { + tokens.splice(i, 1, ...inner); + continue; + } + } // A redirect operator and, when it stands alone, the token it targets — // `> file` must not leave `file` sitting where the command word goes. if (/^\d*(?:>{1,2}\|?|<{1,3})/.test(token)) { @@ -1333,20 +1691,64 @@ function commandWords(simpleCommand: string): string[] { if (!skippable) break; i++; } - return tokens.slice(i); + // From the command word on, a redirect is no argument either: `cp /dev/null + // ~/.claude/settings.json 2>/dev/null` copies onto the settings file, and a + // copy's destination is its LAST word. The redirect is judged on its own, + // by REDIRECT_TARGET_RE; `<(…)` and `>(…)` are arguments and stay. + const words: string[] = []; + for (let k = i; k < tokens.length; k++) { + if (k > i && /^\d*(?:>{1,2}\|?|<{1,3})(?!\()/.test(tokens[k])) { + if (/^\d*(?:>{1,2}\|?|<{1,3})$/.test(tokens[k])) k++; + continue; + } + words.push(tokens[k]); + } + return words; +} +/** A redirect with its target as the shell reads it: quoted, escaped or glued, spaces and all. */ +const REDIRECT_WITH_TARGET_RE = /(^|\s)\d*(?:>{1,2}\|?|<{1,3})(?!\()\s*(?:"(?:[^"\\]|\\.)*"|'[^']*'|\\.|[^\s"'\\])+/g; +/** + * A simple command with its redirects blanked, so what is left is its + * arguments: `cp /dev/null ~/.claude/settings.json 2> '/tmp/build log'` has + * two, not a third called `log'`. Found in the splittable view, where a `>` + * inside a quoted argument is already blank, and blanked at the same offsets + * in the readable one. A redirect's target is judged on its own. + */ +function blankRedirects(readableSimple: string, splitSimple: string): string { + let out = ""; + let pos = 0; + for (const match of splitSimple.matchAll(REDIRECT_WITH_TARGET_RE)) { + const start = match.index + match[1].length; + const end = match.index + match[0].length; + out += readableSimple.slice(pos, start) + " ".repeat(end - start); + pos = end; + } + return pos === 0 ? readableSimple : out + readableSimple.slice(pos); } - /** * True when this one simple command would destroy whatever it is pointed at. * - * Reached only for a command that already names failproofai's state, so the + * Reached only for a command that already names the protected target, so the * question is narrow: is this a read, or is it everything else. */ -function simpleCommandDestroys(words: string[], namesState: (text: string) => boolean): boolean { +function simpleCommandDestroys( + words: string[], + namesState: (text: string) => boolean, + target: ProtectedPathTarget, + rawSimple: string, + cwdInTarget = false, + cwds: ReadonlyArray = [undefined], + valuesOfWord: (word: string) => string[] | null = () => null, +): boolean { if (words.length === 0) return false; const head = commandBasename(words[0]); const args = words.slice(1); + // Every exemption below reads the command word as the tool it is named + // after. A project's own `./cat` that writes "$1" is not that tool (#1105 + // bot review), so a word not known to be the real one exempts nothing. + if (target.trustsCommand && !target.trustsCommand(words[0], rawSimple)) return true; + // `find` is a read until one of its ACTIONS turns it into something else. // `-delete` is the miss that started all of this; `-exec` runs anything at // all, so it is judged by the command it hands the paths to, and an @@ -1360,7 +1762,10 @@ function simpleCommandDestroys(words: string[], namesState: (text: string) => bo // EVERY `-exec`, not the first: `find … -exec cat {} + -o -exec rm {} +` // put a read in front of the deleter and walked past a findIndex. return args.some( - (a, i) => FIND_EXEC_ACTIONS.has(a) && !SAFE_EXEC_COMMANDS.has(commandBasename(args[i + 1] ?? "")), + (a, i) => + FIND_EXEC_ACTIONS.has(a) && + (!SAFE_EXEC_COMMANDS.has(commandBasename(args[i + 1] ?? "")) || + (target.trustsCommand !== undefined && !target.trustsCommand(args[i + 1] ?? "", ""))), ); } @@ -1368,23 +1773,57 @@ function simpleCommandDestroys(words: string[], namesState: (text: string) => bo // which needs no flag at all: `sed 's/a/b/w ' /etc/hosts` writes the // state without `-i` anywhere on the line. if (head === "sed") { - if (args.some((a) => a.startsWith("-i") || a.startsWith("--in-place"))) return true; - // The filename may ride in the same token (`'s/a/b/w'`) or in the - // next one, because a quoted script containing a space is two tokens by the - // time it gets here. `s/a/b/w` and a bare `w` both end in a `w` that - // follows a delimiter, which is what separates them from a word like `raw`. - return args.some( - (a, i) => /(?:^|[;}/\s])w$/.test(a) && namesState(args[i + 1] ?? ""), - ) || args.some((a) => /(?:^|[;}/\s])w\s*\S*\.failproofai/.test(a)); + // In place, alone or bundled: `-i`, `-i.bak`, `-Ei`, `-ni`, `--in-place`. + if (args.some((a) => /^-(?!-)[A-Za-z]*i/.test(a) || a.startsWith("--in-place"))) return true; + // Only the SCRIPT is read for `e`, `w` and `W`. Reading every word made a + // file operand under `/workspaces/…` or `/Users/Wei/…` look like a `w` + // command. A script read from a file (`-f`) cannot be checked at all. + const scripts = sedScripts(rawSimple); + if (scripts === null) return true; + for (const script of scripts) { + // `e` runs a shell command, as a command (`1e cp …`) or as the flag on + // `s` (`s/x/y/e`), so a sed that reads nothing can still write anything. + if (SED_RUNS_COMMAND_RE.test(script)) return true; + // `w`/`W` write the rest of the line's text as a file name, glued on + // (`s/a/b/w`) or after a space; an address can stand in front. + for (const [, file] of script.matchAll(SED_WRITE_FILE_RE)) { + if (namesState(file.trim())) return true; + } + } + return false; + } + + // `yq -i` rewrites the file it reads, and reads JSON as readily as YAML. + if (head === "yq") { + if (args.some((a) => /^-[A-Za-z]*i/.test(a) || /^--in-?place/.test(a))) return true; } // `awk` can run a shell (`system("rm -rf …")`) or pipe into one, so its // program has to be read for those two, not just for the `>` the redirect // scan already catches. if (head === "awk" || head === "gawk" || head === "mawk") { - return args.some((a) => /system\s*\(|\|\s*["']|\|&/.test(a)); + // gawk's `inplace` extension rewrites every input file, loaded by flag + // (`-i inplace`, `--include=inplace`) or from the program (`@include`). + const inplace = args.some( + (a, i) => + ((a === "-i" || a === "--include" || a === "@include") && /^inplace/.test(args[i + 1] ?? "")) || + /^(?:-iinplace|--include=inplace)/.test(a), + ); + if (inplace || args.some((a) => /system\s*\(|\|\s*["']|\|&/.test(a))) return true; + // `print > ARGV[1]` writes a file the program names only at run time, so + // the redirect scan finds nothing to read. A program that prints AND holds + // a `>` is treated as writing; a comparison beside a print is the cost. + // String literals come out first, so a `}` or a `>` inside one neither ends + // the statement nor counts as a redirect; a comparison BEFORE the print + // (`$2 > 1 {print $1}`) is not one either. + return quoteAwareWords(rawSimple).some((w) => + /\bprintf?\b[^;}\n]*>/.test(w.replace(/"(?:[^"\\]|\\.)*"/g, '""')), + ); } + // `rg --pre ` runs a command over every file it searches. + if ((head === "rg" || head === "ripgrep") && args.some((a) => a === "--pre" || a.startsWith("--pre="))) return true; + // Copying the state OUT is a backup. Copying anything ONTO it — classically // `/dev/null` — empties it without naming a delete verb. The destination is // the last operand, unless `-t` names it instead: `cp -t ~/.failproofai @@ -1394,12 +1833,50 @@ function simpleCommandDestroys(words: string[], namesState: (text: string) => bo // being the SOURCE — the shape that makes every other copy a backup — is // what makes this one a move. if (args.includes("--remove-source-files") && args.some((a) => namesState(a))) return true; - const targetAt = args.findIndex((a) => a === "-t" || a === "--target-directory"); - if (targetAt !== -1 && namesState(args[targetAt + 1] ?? "")) return true; - if (args.some((a) => a.startsWith("--target-directory=") && namesState(a))) return true; + // `cp -l` and `cp -s` make a hard or symbolic link instead of a copy, so + // the protected file as SOURCE gets a second name that any later write + // reaches it through: `cp -l ~/.claude/settings.json /tmp/x; echo … > /tmp/x`. + const links = args.some((a) => /^-(?!-)[A-Za-z]*[ls]/.test(a) || a === "--link" || a === "--symbolic-link"); + if (head === "cp" && links && args.some((a) => !a.startsWith("-") && namesState(a))) return true; + // `--parents` keeps each source's own path under the directory: + // `cp --parents .claude/settings.json ~` writes ~/.claude/settings.json. + const parents = head === "cp" && args.some((a) => a.length >= 4 && "--parents".startsWith(a)); + const landing = (dir: string, source: string): string => { + const plain = stripShellQuoting(source); + if (parents) return `${dir}/${plain.replace(/^(?:\.\/)+/, "").replace(/^\/+/, "")}`; + const name = plain.replace(/\/+$/, "").split("/").pop() ?? ""; + const contents = name === "" || name === "." || name === ".." || (head === "rsync" && plain.endsWith("/")); + return contents ? dir : `${dir}/${name}`; + }; + const target = copyTargetDirectory(head, args); + if (target) { + // Every other operand is a source, and lands in the directory under its + // own name: `cp -t ~/.claude /tmp/settings.json` writes the settings, + // `cp -t ~/.claude /tmp/notes.md` and `cp -t /tmp/bak ~/.claude/settings.json` do not. + const sources = args.filter((a, i) => !a.startsWith("-") && !target.values.has(i)).flatMap((source) => valuesOfWord(source) ?? [source]); + return (valuesOfWord(target.dir) ?? [target.dir]).some((dir) => { + const plainDir = stripShellQuoting(dir).replace(/\/+$/, ""); + return sources.some((source) => namesState(landing(plainDir, source))); + }); + } const operands = args.filter((a) => !a.startsWith("-")); const destination = operands[operands.length - 1]; - return destination !== undefined && namesState(destination); + if (destination === undefined) return false; + // Into a directory that exists, each source lands under its own name: + // `cp README.md ~/.claude` writes ~/.claude/README.md and nothing else. Not + // with `-T`, which makes the directory the file; and a source's contents + // (`dir/.`, rsync's `dir/`) land in the directory itself. + const sources = operands.slice(0, -1).flatMap((source) => valuesOfWord(source) ?? [source]); + const noTarget = args.some((a) => a === "--no-target-directory" || /^-(?!-)[A-Za-z]*T/.test(a)); + // A destination that is just `$D` reads as the directories D is given. + const dirs = valuesOfWord(destination) ?? [destination]; + if (!noTarget && sources.length > 0 && dirs.every((dir) => cwds.some((cwd) => existingDirectory(dir, cwd)))) { + return dirs.some((dir) => { + const plainDir = stripShellQuoting(dir).replace(/\/+$/, ""); + return sources.some((source) => namesState(landing(plainDir, source))); + }); + } + return namesState(destination); } // `tee` writes every operand it is given and reads none of them. @@ -1413,10 +1890,51 @@ function simpleCommandDestroys(words: string[], namesState: (text: string) => bo return operands.length > 1 && namesState(operands[operands.length - 1]); } + // `yq -i` edits in place. + if (head === "yq" && args.some((a) => a === "-i" || a.startsWith("--inplace") || /^-[A-Za-z]*i[A-Za-z]*$/.test(a))) return true; + // `git` normally carries the path as prose in a message or a body. if (head === "git") { const subcommand = gitSubcommand(args); - return subcommand !== undefined && GIT_DESTRUCTIVE_SUBCOMMANDS.has(subcommand); + const gitWords = quoteAwareCommandWords(rawSimple).words; + // A relative output path lands in the repository `-C` names, joined as + // written so a `..` after a link there is walked the way the kernel does. + const repositories = gitRepositoryDirs(gitWords, cwds, valuesOfWord); + const namesInRepository = (text: string): boolean => + namesState(text) || + (isRelativeShellWord(text) && + repositories.some((repository) => repository === GIT_REPOSITORY_LOST || namesState(`${repository}/${text}`))); + // Output files, whatever the subcommand: `git log --output=` writes + // what `--format` says into it, and `-o` is the archive's or the patches'. + if (writesViaOutputFlag("git", args, namesInRepository)) return true; + if ((subcommand === "archive" || subcommand === "format-patch") && writesViaOutputFlag("git", args, namesInRepository, ["-o"])) { + return true; + } + // Config that runs a command, judged by what it runs: `alias.x='!rm …'` + // is a deleter, `core.pager=cat` is not. + if (gitWords.some((w, i) => (gitWords[i - 1] === "-c" || gitWords[i - 1] === "--config-env") && GIT_CONFIG_RUNS_CODE_RE.test(w) && namesState(w))) { + return true; + } + // Subcommands that run a command of their own, with nothing to say what it touches. + if (subcommand === "rebase" && args.some((a) => a === "-x" || a === "--exec" || a.startsWith("--exec=") || /^-(?!-)[A-Za-z]*x/.test(a))) { + return true; + } + if ((subcommand === "submodule" && args.includes("foreach")) || (subcommand === "bisect" && args.includes("run"))) return true; + if (subcommand === "filter-branch" || subcommand === "filter-repo") return true; + if ((subcommand === "difftool" || subcommand === "mergetool") && args.some((a) => a === "-x" || a === "--extcmd" || a.startsWith("--extcmd="))) { + return true; + } + // `git config` writes `.git/config`; only `-f ` writes elsewhere. + if (subcommand === "config") { + return gitWords.some((w, i) => ((gitWords[i - 1] === "-f" || gitWords[i - 1] === "--file") && namesInRepository(w)) || + (w.startsWith("--file=") && namesInRepository(w.slice("--file=".length)))); + } + // `restore --staged` alone touches the index, never the file on disk. + const staged = args.some((a) => a === "--staged" || /^-(?!-)[A-Za-z]*S/.test(a)); + const worktree = args.some((a) => a === "--worktree" || /^-(?!-)[A-Za-z]*W/.test(a)); + if (subcommand === "restore" && staged && !worktree) return false; + if (subcommand === undefined || !GIT_DESTRUCTIVE_SUBCOMMANDS.has(subcommand)) return false; + return cwdInTarget || gitOperandsNameTarget(gitWords, subcommand, namesInRepository, /['"]/.test(rawSimple)); } // A reader whose destination arrives as an option rather than as an operand. @@ -1425,1198 +1943,6848 @@ function simpleCommandDestroys(words: string[], namesState: (text: string) => bo if (writesViaOutputFlag(head, args, namesState)) return true; if (STATE_READ_COMMANDS.has(head) || STATE_MENTION_COMMANDS.has(head)) return false; + if (target.harmlessCommands?.has(head)) return false; return true; } - /** * True when a flag on this command names the state as an output file. * * `sort -o`, `tree -o` and `curl -o` all take their destination as an option, * so nothing about the head or the operand order says they are writing — and * all three heads were on a list that said they only read. Short options bundle - * (`curl -sfo `), so the trailing letter is what decides. + * (`curl -sfo `), so the trailing letter is what decides — and a short + * option can carry its value glued on (`sort -o`, `curl -so`). */ -function writesViaOutputFlag(head: string, args: string[], namesState: (text: string) => boolean): boolean { - const flags = OUTPUT_FLAG_COMMANDS[head]; +function writesViaOutputFlag( + head: string, + args: string[], + namesState: (text: string) => boolean, + flags: readonly string[] | undefined = OUTPUT_FLAG_COMMANDS[head], +): boolean { if (!flags) return false; + const shortLetters = flags.filter((f) => /^-[A-Za-z]$/.test(f)).map((f) => f[1]); for (let i = 0; i < args.length; i++) { const arg = args[i]; const long = flags.find((f) => f.startsWith("--") && arg.startsWith(`${f}=`)); - if (long && namesState(arg)) return true; - const bundled = /^-[A-Za-z]*[oD]$/.test(arg) && flags.includes(`-${arg[arg.length - 1]}`); + if (long && namesState(arg.slice(long.length + 1))) return true; + const bundled = /^-[A-Za-z]+$/.test(arg) && shortLetters.includes(arg[arg.length - 1]); if ((flags.includes(arg) || bundled) && namesState(args[i + 1] ?? "")) return true; + if (/^-[A-Za-z]/.test(arg)) { + for (const letter of shortLetters) { + const glued = arg.indexOf(letter, 1); + if (glued > 0 && /^[A-Za-z]*$/.test(arg.slice(1, glued)) && glued < arg.length - 1) { + if (namesState(arg.slice(glued + 1))) return true; + } + } + } } return false; } - /** - * True when `command` would delete, move or overwrite failproofai's own state. + * What the shell walk below protects, so one walk serves two targets. * - * Deleting the state IS disabling enforcement, and it never names the binary: - * `rm ~/.failproofai/policies/packs/installed.json` switches off every pack - * policy on the machine, and fail-closed does NOT fire, because a missing store - * reads as a fresh machine rather than a broken one — so nothing anywhere - * reports it. - * - * Two things carry the path into a command that never spells it, and both were - * live bypasses of the per-segment version: + * It was written for failproofai's own state. An agent's settings and hook + * files need exactly the same reading of a command — which end of a copy the + * path sits on, whether `sed` has `-i`, where a variable or a `cd` carries the + * path — so the walk takes its target as a parameter instead of existing twice. + */ +interface ProtectedPathTarget { + /** Whether a word, a value or a whole pipeline names the target as written. */ + namesLiteral(text: string): boolean; + /** + * Whether a program handed to an interpreter names the target. Defaults to + * `namesLiteral`; the settings target also reads directory names as string + * literals, which is how programs build those paths. + */ + namesProgram?(program: string): boolean; + /** Paths a glob has to be able to reach to count as aimed at the target. */ + globCandidates: readonly string[]; + /** Ordinary paths a glob aimed at the target must miss. */ + globDecoys: readonly string[]; + /** Heads that cannot write or remove the target, beyond the shared read and mention lists. */ + harmlessCommands?: ReadonlySet; + /** + * Where the shell starts, when it is known. A relative word is resolved + * against it — and against wherever a `cd` moves it — so + * `cd ~/.claude && cp /tmp/x settings.json` names the file it writes. + */ + cwd?: string; + /** + * Text every one of the target's paths contains somewhere. A relative word + * is resolved only when it, or the directory the shell stands in, could be + * one; the rest of a long command is not worth a path resolution per word. + */ + hint?: RegExp; + /** + * Whether a command word is the tool it is named after, so a read or + * mention exemption for that name may apply. `rawSimple` is the simple + * command it heads, or empty. Without it every name is trusted. + */ + trustsCommand?(word: string, rawSimple: string): boolean; + /** + * Whether a word leads to the target through a symlink (relative to `cwd` + * when relative). Asked of every word, ahead of `hint`, which reads only text. + */ + namesThroughLinks?(word: string, cwd: string | undefined): boolean; +} +/** failproofai's own state. Names, not copies, so widening any of them widens the walk. */ +const FAILPROOFAI_STATE_TARGET: ProtectedPathTarget = { + namesLiteral: (text) => FAILPROOFAI_STATE_PATH_RE.test(text), + globCandidates: STATE_GLOB_CANDIDATES, + globDecoys: GLOB_DECOYS, + hint: /failproof/i, +}; +/** + * `mkdir` and `touch` create, and neither can overwrite or remove a settings + * file — while an agent making `.claude/commands/` is ordinary work. + */ +const AGENT_SETTINGS_HARMLESS_COMMANDS: ReadonlySet = new Set(["mkdir", "touch"]); +/** + * Every command word the settings walk can exempt by name, less the shell + * builtins it trusts without PATH: what the hook CLI must carry the agent's + * PATH for (agent-path.ts's `SETTINGS_READER_WORDS`, kept equal by a test). + */ +export const SETTINGS_WALK_PATH_HEADS: ReadonlySet = new Set( + [...STATE_READ_COMMANDS, ...STATE_MENTION_COMMANDS, ...AGENT_SETTINGS_HARMLESS_COMMANDS, ...SAFE_EXEC_COMMANDS].filter( + (head) => !["cd", "pushd", "popd", "[", "[[", "]", "]]", ":", "read", "for", "select", "case", "done", "fi", "esac"].includes(head), + ), +); +/** + * Agents' settings and hook files (agent-settings-guard.ts), for a shell that + * starts in `cwd`. `extraPaths` are settings files known for this session that + * no shape describes (a config directory moved by `CLAUDE_CONFIG_DIR`). + */ +function agentSettingsShellTarget( + cwd: string | undefined, + extraPaths: readonly string[], + trustsCommand?: (word: string, rawSimple: string) => boolean, +): ProtectedPathTarget { + const matcher = agentSettingsShellMatcher(extraPaths, cwd); + return { + namesLiteral: matcher.names, + namesProgram: (program) => matcher.names(program) || programNamesAgentSettings(program), + // A glob reaches a link's target too: `cp x /tmp/actual/prim*.json`. + globCandidates: [...agentSettingsGlobCandidates(cwd, extraPaths), ...matcher.linkedFiles], + globDecoys: agentSettingsGlobDecoys(cwd, GLOB_DECOYS), + harmlessCommands: AGENT_SETTINGS_HARMLESS_COMMANDS, + cwd, + hint: matcher.hint, + namesThroughLinks: matcher.throughLinks, + trustsCommand, + }; +} +/** + * Shell builtins and keywords on the read and mention lists. Bash runs its + * builtin for these whatever PATH holds, unless a runner in front of it + * (`env`, `xargs`, `sudo`, …) looks the name up on PATH instead. + */ +const SHELL_BUILTIN_READ_HEADS = new Set([ + "cd", "pushd", "popd", "echo", "printf", "test", "[", "[[", "]", "]]", "true", "false", ":", "pwd", "read", + "for", "select", "case", "done", "fi", "esac", +]); +/** Words in front of a command that find it on PATH rather than as a builtin. */ +const PATH_LOOKUP_RUNNERS = new Set([ + "exec", "env", "nohup", "setsid", "timeout", "nice", "stdbuf", "xargs", "sudo", "doas", + "npx", "bunx", "pnpx", "npm", "pnpm", "yarn", "dlx", "run", "node", "bun", "deno", +]); +/** + * Whether a settings-walk command word is the standard tool it is named after + * (#1105 bot review; the state guard's F17 rule, `standardToolName`): a path + * in /usr/bin or /bin, a bare name the AGENT's PATH finds there first, or a + * shell builtin the shell runs as one. Nothing is, on a line that can change + * what a command word runs (a function, an alias, a PATH assignment). + */ +function settingsReaderTrust(cmd: string, agentPath: string | undefined): (word: string, rawSimple: string) => boolean { + // Scanned on first use: most commands never reach a reader exemption, and + // the scan is a second full pass over a command that may be very long. + let redefined: boolean | undefined; + const known = new Map(); + return (word, rawSimple) => { + if ((redefined ??= redefinesCommandWords(cmd, scanShellCommands(cmd)))) return false; + const bare = bareToken(word); + if (!bare.includes("/") && SHELL_BUILTIN_READ_HEADS.has(bare)) { + const tokens = rawSimple === "" ? [] : shellSplit(rawSimple.trim()).map(bareToken); + const at = tokens.indexOf(bare); + if (!tokens.slice(0, at === -1 ? tokens.length : at).some((t) => PATH_LOOKUP_RUNNERS.has(commandBasename(t)))) return true; + } + let trusted = known.get(bare); + if (trusted === undefined) known.set(bare, (trusted = standardToolName(bare, agentPath) !== undefined)); + return trusted; + }; +} +/** + * The settings target read from wherever an agent may have started a command + * without saying where: the session's matcher, plus a relative word resolved + * against `AGENT_SETTINGS_ANYWHERE_ROOT` read as if that root were one of the + * agents' config directories (`agentSettingsFromAnywhere`). + */ +function agentSettingsAnywhereTarget(base: ProtectedPathTarget, extraPaths: readonly string[]): ProtectedPathTarget { + const fromAnywhere = agentSettingsFromAnywhere(base.namesLiteral, extraPaths); + const names = (text: string): boolean => base.namesLiteral(text) || fromAnywhere(text); + const throughLinks = base.namesThroughLinks; + return { + ...base, + namesLiteral: names, + namesProgram: (program) => names(program) || (base.namesProgram?.(program) ?? false), + cwd: AGENT_SETTINGS_ANYWHERE_ROOT, + // No link on disk is under a directory nobody knows; an absolute word is + // looked up as the session's walk looks it up. + namesThroughLinks: + throughLinks && + ((word, cwd) => + cwd !== undefined && cwd.startsWith(AGENT_SETTINGS_ANYWHERE_ROOT.slice(0, 12)) && isRelativeShellWord(word) + ? false + : throughLinks(word, cwd)), + }; +} +/** Whether a shell tool's call names the directory it runs in (`cwd`, or Codex's `workdir`). */ +function shellCwdReported(toolInput: Record | undefined): boolean { + const toolCwd = toolInput?.cwd ?? toolInput?.workdir; + return typeof toolCwd === "string" && toolCwd !== ""; +} +/** Interpreters that take a program inline or on stdin. Never readers. */ +const INLINE_INTERPRETERS = "python[0-9.]*|pypy[0-9.]*|node|nodejs|bun|deno|perl|ruby|php|lua|osascript|pwsh|powershell"; +const INLINE_INTERPRETER_RE = new RegExp(`^(?:${INLINE_INTERPRETERS})$`); +/** + * A program handed to an interpreter on its command line: `python3 -c "…"`, + * `node -e '…'`, `perl -pe '…'`, `deno eval "…"`, glued (`-c"…"`) or not. * - * - `cd ~/.failproofai && rm -rf .` — the path is an argument of `cd`, and the - * destroying command names only `.` - * - `D=~/.failproofai; rm -rf $D` — the path is a value, and the destroying - * command names only `$D` + * The program is not shell, but the walk splits it like shell — on every `;` — + * so `python3 -c "import json; p=''; json.dump(d, open(p,'w'))"` left the + * path in a piece that reads as a bare assignment with no command in front of + * it, and the interpreter's own piece named nothing. So the whole program is + * judged as one: an interpreter is never on the read list, and naming the + * target anywhere in its program is enough. * - * So the walk is stateful: it remembers which variables hold the path and - * whether the shell has been moved INTO the directory, and carries both - * forward. What it does NOT do is treat every later command as suspect — - * `cat ~/.failproofai/config.json && rm /tmp/scratch` has to stay allowed, and - * does, because nothing in the second command reaches the state. + * Bounded on purpose: at most six words between the interpreter and its flag, + * all on one line (a backslash-newline is joined first). An unbounded gap + * re-scanned the rest of the input for every interpreter-shaped word. */ -function destroysFailproofaiState(command: string, depth = 0): boolean { - // A substitution runs its body as a command of its own, so it is judged as - // one — `echo $(rm -rf ~/.failproofai)` otherwise presents `echo` as the head - // and walks straight through. Bounded, because a body can contain another. - // Breadth-first with a budget rather than depth-limited recursion: a nest - // deeper than the limit is trivial to write (`echo $(echo $(… rm …))`), and - // every level of it presents `echo` as the head. The budget is what bounds - // the work instead, because siblings multiply where depth does not. - if (depth === 0) { - const bodies = substitutionBodies(command); - for (let i = 0; i < bodies.length && i < 64; i++) { - if (destroysFailproofaiState(bodies[i], 1)) return true; - bodies.push(...substitutionBodies(bodies[i])); +const INLINE_PROGRAM_RE = new RegExp( + String.raw`(?:^|[\s;&|(\x60])(?:[^\s;&|()\x60]*/)?(?:${INLINE_INTERPRETERS})(?:[ \t]+[^\s;&|]+){0,6}?[ \t]+(?:-[A-Za-z]*[ceErp]|--eval=?|--print=?|--command=?|-Command|eval)[ \t]*("(?:[^"\\]|\\.)*"|'[^']*'|\$'(?:[^'\\]|\\.)*')`, + "g", +); +/** Heads that run their quoted arguments, or a heredoc, as shell. */ +const SHELL_HEADS: ReadonlySet = new Set([ + "sh", "bash", "zsh", "dash", "ksh", "ash", "fish", "eval", "source", ".", "su", + "ssh", "docker", "podman", "kubectl", "watch", +]); +/** Shells and interpreters that read a program from stdin when given no script: `| sh`, `| node`. */ +const STDIN_PROGRAM_HEADS: ReadonlySet = new Set([ + "sh", "bash", "zsh", "dash", "ksh", "ash", "fish", "node", "bun", "deno", +]); +/** Words a shell walks past before the command that receives the arguments. */ +const MASK_TRANSPARENT_WORDS: ReadonlySet = new Set([ + "sudo", "doas", "env", "nohup", "time", "timeout", "nice", "stdbuf", "setsid", "command", "builtin", + "exec", "xargs", "then", "do", "else", "elif", "if", "while", "until", "!", +]); +/** Characters that steer the walk and mean nothing to the shell inside a quoted argument. */ +const MASKABLE_IN_QUOTES = "\n\r;&|<>()"; +/** Marks a word in the lexer's decoded words that holds an expansion. */ +const UNKNOWN_IN_WORD = "\u0000"; +/** What a quoted message holds and a quoted word does not. */ +const NOT_IN_A_QUOTED_WORD = ` \t\v\f${MASKABLE_IN_QUOTES}`; +/** One command context: the top level, a `$(…)`, a backtick or a `( … )` subshell. */ +interface LexCommandFrame { + kind: "cmd"; + /** What closes it: `)` for `$(` and `(`, a backtick for a backtick, nothing for the top level. */ + closer: ")" | "`" | null; + /** Opened by `$(` or a backtick: its output is spliced into the command around it. */ + substitution: boolean; + /** The current simple command's head, once its first real word is read. */ + head: string | null; + /** The current simple command's words so far (the first few). */ + words: string[]; + word: string; + /** + * The same words with their quotes undone — `'/tmp/example.md'` is + * `/tmp/example.md`, `"-"` is `-` — for the heredoc analysis only. A word + * holding an expansion carries UNKNOWN_IN_WORD and reads as unknown. + */ + decodedWords: string[]; + decoded: string; +} +interface LexQuoteFrame { + kind: "sq" | "dq" | "ansi"; + /** Blank separators inside: the command receiving this argument is not a shell. */ + mask: boolean; + /** An expansion inside (`$X`, `$(…)`, a backtick): its text is not known. */ + expands?: boolean; + /** Where the quoted text starts. */ + start: number; + /** + * Nothing inside so far that a message has and a word does not: no blank, + * separator, escape or expansion. Such a quote is a quoted WORD, and + * `commandsOnly` gives it back when it closes — `codex features disable + * "hooks"` is that command whether or not `hooks` is quoted. + */ + plain: boolean; +} +interface LexArithFrame { + kind: "arith"; + depth: number; +} +/** `${…}`: part of one word, whatever spaces, `#`, `;` or `)` it holds. */ +interface LexParamFrame { + kind: "param"; + depth: number; +} +type LexFrame = LexCommandFrame | LexQuoteFrame | LexArithFrame | LexParamFrame; +/** A simple command as it ended: its head and its first words. */ +interface LexEndedCommand { + head: string | null; + words: string[]; +} +interface PendingHeredoc { + delimiter: string; + literal: boolean; + /** `<<-`: leading tabs come off each body line before it is compared. */ + stripTabs: boolean; + /** Index, in the line's ended commands, of the command the operator belongs to. */ + commandIndex: number; + /** Inside a `$(…)`/backtick: the command the substitution is an argument of; undefined at the top level. */ + outer: LexEndedCommand | null | undefined; +} +/** What one pass over a command learns. Every string has the command's length. */ +interface ShellLex { + /** Comments and STORED heredoc bodies blanked; everything else as written. */ + readable: string; + /** `readable`, with separators, redirects and parentheses inside quoted arguments blanked too. */ + splittable: string; + /** The command with only LITERAL stored heredoc bodies blanked: where substitutions are looked for. */ + substitutionSource: string; + /** `splittable` with ALL text inside a non-shell command's quoted arguments blanked: the commands alone. */ + commandsOnly: string; + /** Bodies of heredocs that an interpreter reads as its program. */ + programBodies: string[]; +} +function isShellHead(head: string | null | undefined): boolean { + return head !== null && head !== undefined && SHELL_HEADS.has(head); +} +function isInterpreterHead(head: string | null | undefined): boolean { + return head !== null && head !== undefined && INLINE_INTERPRETER_RE.test(head); +} +/** `cat`, `cat -` or `cat /dev/stdin`: copies its stdin and nothing else. */ +function catReadsOnlyStdin(command: LexEndedCommand): boolean { + return command.head === "cat" && command.words.slice(1).every((word) => word === "-" || word === "/dev/stdin"); +} +/** `-F -`, `-F-`, `--file=/dev/stdin` and the like: a message read from stdin. */ +function readsMessageFromStdin(words: string[], options: readonly string[]): boolean { + const stdin = (value: string | undefined): boolean => value === "-" || value === "/dev/stdin"; + return words.some((word, i) => { + if (options.includes(word)) return stdin(words[i + 1]); + return options.some((option) => (option.startsWith("--") ? word === `${option}=-` || word === `${option}=/dev/stdin` : stdin(word.slice(option.length)) && word.startsWith(option))); + }); +} +/** `git commit|tag|notes … -F -`: the heredoc is the commit message. */ +function gitTakesMessageFromStdin(command: LexEndedCommand): boolean { + if (command.head !== "git") return false; + const sub = command.words.slice(1).find((word) => !word.startsWith("-")); + return (sub === "commit" || sub === "tag" || sub === "notes") && readsMessageFromStdin(command.words, ["-F", "--file"]); +} +/** `gh … --body-file -`: the heredoc is the body of an issue, a PR or a release. */ +function ghTakesBodyFromStdin(command: LexEndedCommand): boolean { + return command.head === "gh" && readsMessageFromStdin(command.words, ["--body-file", "-F"]); +} +/** Commands whose `$(cat <<'EOF' …)` argument is a message they store, never run. */ +function outerStoresMessage(outer: LexEndedCommand | null | undefined): boolean { + // Not `echo` or `printf`: their output is the body itself, and + // `echo "$(cat <<'EOF' …)" > x.sh && sh x.sh` runs it. + if (!outer || outer.head === null) return false; + const sub = outer.words.slice(1).find((word) => !word.startsWith("-")); + if (outer.head === "git") return sub === "commit" || sub === "tag" || sub === "notes" || sub === "merge"; + if (outer.head === "gh" || outer.head === "glab") return sub !== "alias" && sub !== "extension"; + return false; +} +/** A pipe into a shell or interpreter, or an eval/source, anywhere after `at`. */ +const RUNS_TEXT_LATER_RE = + /\|\s*(?:[^\s;&|()`<>]*\/)?(?:sh|bash|zsh|dash|ksh|ash|fish|python[0-9.]*|pypy[0-9.]*|node|nodejs|bun|deno|perl|ruby|php|lua|pwsh|powershell)(?=[\s;&|)]|$)|(?:^|[\s;&|(`])(?:eval|source)(?=\s)/; +/** The file a `cat > F` or `tee F` heredoc writes, or null. */ +function heredocWritesFile(command: LexEndedCommand): string | null { + const words = command.words; + if (command.head === "cat") { + for (let i = 1; i < words.length; i++) { + const m = /^>{1,2}(.*)$/.exec(words[i]); + if (m) return m[1] || words[i + 1] || null; } + return null; } - - // Variables that hold the path. The scan used to ask only whether a value - // CONTAINED the path, which caught `D=~/.failproofai; rm -rf $D` and missed - // `A=~/.failproofai; B=$A; rm -rf $B` — the second hop names no path at all, - // only the first variable. So a value referencing a known state variable - // counts too. Repeating to a fixpoint costs four lines and makes the result - // independent of the order the assignments appear in, rather than resting on - // a shell evaluating them top to bottom. - const assignments = [ - ...command.matchAll(/(?:^|[\s;&|(])(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=("[^"]*"|'[^']*'|[^\s;&|)]+)/g), - ].map(([, name, value]) => [name, value.replace(/^["']|["']$/g, "")] as const); - const stateVars = new Set(); - for (let pass = 0; pass < assignments.length + 1; pass++) { - const before = stateVars.size; - for (const [name, value] of assignments) { - const holdsState = - FAILPROOFAI_STATE_PATH_RE.test(value) || - [...value.matchAll(VAR_REFERENCE_RE)].some(([, ref]) => stateVars.has(ref)); - if (holdsState) stateVars.add(name); + if (command.head === "tee") return words.slice(1).find((word) => !word.startsWith("-")) ?? null; + return null; +} +/** + * Whether a heredoc's body is text being STORED rather than read by anything + * that acts on it — the only bodies the walk may skip. + * + * An allowlist, because the other direction failed: `git apply < x.sh < F` or `tee F` that nothing in the same command runs. + * Anything that later pipes into a shell, `eval`s or `source`s keeps its body. + */ +function heredocIsStoredText( + doc: PendingHeredoc, + own: LexEndedCommand, + /** How many commands follow `own` on its line, and the first of them. */ + downstream: { count: number; next: LexEndedCommand | undefined }, + later: { runsText: boolean; names: { has(name: string): boolean } }, + substitutionBody: boolean, +): boolean { + if (later.runsText) return false; + if (downstream.count === 0) { + if (catReadsOnlyStdin(own)) { + // Inside a substitution whose text the outer command stores; or a body + // being judged on its own (depth 1), whose outer command was judged with it. + if (doc.outer !== undefined ? outerStoresMessage(doc.outer) : substitutionBody) return true; } - if (stateVars.size === before) break; + if (gitTakesMessageFromStdin(own) || ghTakesBodyFromStdin(own)) return true; + const file = doc.outer === undefined ? heredocWritesFile(own) : null; + if (file) { + const name = file.slice(file.lastIndexOf("/") + 1); + return name.length > 0 && !later.names.has(name); + } + return false; } - - const namesState = (text: string): boolean => { - if (FAILPROOFAI_STATE_PATH_RE.test(text)) return true; - for (const [, name] of text.matchAll(VAR_REFERENCE_RE)) { - if (stateVars.has(name)) return true; + return ( + downstream.count === 1 && + downstream.next !== undefined && + catReadsOnlyStdin(own) && + (gitTakesMessageFromStdin(downstream.next) || ghTakesBodyFromStdin(downstream.next)) + ); +} +/** + * A heredoc delimiter word, read the way the shell reads it: quotes and + * backslashes come off, and any of them makes the body literal. `< globCouldNameState(unquotedToken(token))); - }; - - let cwdInState = false; - // How deep in `( … )` the walk is, and how deep it was when the `cd` fired. - // A `cd` inside a subshell moves the subshell only, so the window closes when - // the parenthesis does: `(cd ~/.failproofai && cat x); rm -rf node_modules` - // was denying a cleanup in an entirely unrelated directory. - let parenDepth = 0; - let cdParenDepth: number | null = null; - // A loop header hands its word list to the body, and the body is a separate - // pipeline that names nothing. Without this, `for f in ~/.failproofai/*; do - // rm -rf $f; done` is a header that only expands and a body that only deletes - // something called `$f`. - let loopCarriesState = false; - for (const pipeline of command.split(PIPELINE_SEPARATORS)) { - if (!pipeline.trim()) continue; - const simpleCommands = pipeline.split("|"); - const reachesState = namesState(pipeline) || cwdInState || loopCarriesState; - if (reachesState && LOOP_HEADER_RE.test(pipeline)) loopCarriesState = true; - if (/(?:^|\s)done(?:\s|$)/.test(pipeline)) loopCarriesState = false; - - // A redirect is a write with no command in front of it — `> path` empties a - // file on its own. Only a redirect whose TARGET is the state counts: the - // previous version matched any `>` anywhere in the segment, so - // `grep -r sudo ~/.failproofai 2>/dev/null` and - // `cat ~/.failproofai/config.json > /tmp/backup.json` both denied, which is - // exactly the diagnosis this guard must not block. - if (reachesState) { - for (const [, target] of pipeline.matchAll(REDIRECT_TARGET_RE)) { - if (namesState(target.replace(/^["']|["']$/g, ""))) return true; + if (c === '"') { + literal = true; + let k = j + 1; + for (; k < text.length && text[k] !== '"'; k++) { + if (text[k] === "\\" && k + 1 < text.length) k++; + delimiter += text[k]; } + j = k + 1; + continue; } - - for (const simple of simpleCommands) { - parenDepth += (simple.match(/\(/g) ?? []).length; - const words = commandWords(simple); - const head = words.length > 0 ? commandBasename(words[0]) : ""; - // Track the shell's position before judging: a `cd` INTO the state makes - // every later relative path a state path, and a `cd` back out ends that. - if (head === "cd" || head === "pushd") { - const operand = words.slice(1).find((w) => !w.startsWith("-")); - cwdInState = operand !== undefined && namesState(operand); - cdParenDepth = cwdInState ? parenDepth : null; - } else if (head === "popd") { - // `popd` returns to wherever the shell was before `pushd`, which ends - // the window as surely as a `cd` out does. Without it every command for - // the rest of the line was judged as if it stood in the state directory. - cwdInState = false; - cdParenDepth = null; - } else if (reachesState && words.length > 0 && simpleCommandDestroys(words, namesState)) { - // Judged BEFORE the closing parenthesis is counted: a `rm -rf ./*)` - // still runs inside the subshell it closes. - return true; - } - parenDepth -= (simple.match(/\)/g) ?? []).length; - if (cdParenDepth !== null && parenDepth < cdParenDepth) { - cwdInState = false; - cdParenDepth = null; - } + if (c === "\\") { + literal = true; + if (j + 1 < text.length) delimiter += text[j + 1]; + j += 2; + continue; } + if (/\s/.test(c) || ";&|<>()".includes(c)) break; + delimiter += c; + j++; } - return false; + // `<<''` and `<<""` are heredocs too, ended by the first empty line. + return delimiter || literal ? { delimiter, literal, stripTabs, end: j } : null; } - -const FAILPROOFAI_UNINSTALL_RE = /(?:npm\s+(?:uninstall|remove|un|r)\s.*failproofai|bun\s+remove\s.*failproofai|yarn\s+global\s+remove\s+failproofai|pnpm\s+(?:remove|uninstall|un)\s.*failproofai)/; - -// warnGitAmend -const GIT_AMEND_RE = /\bgit\s+commit\b.*--amend\b/; - -// warnGitStashDrop -const GIT_STASH_DROP_RE = /\bgit\s+stash\s+(?:drop|clear)\b/; - -// warnGitClean -/** - * `git`, however the command line spells it. Same shape as {@link RM_CMD_RE}: - * an absolute path to the binary does not change what it does. - */ -const GIT_CMD_RE = /^(?:\/\S*\/)?git$/; - -/** A short-flag cluster: `-f`, `-fdx`, `-xdf`. */ -const SHORT_FLAG_CLUSTER_RE = /^-[A-Za-z]+$/; - -/** - * `clean.requireForce=false`, the config that makes `git clean` delete with no - * `-f` at all — and settable per invocation as `git -c - * clean.requireForce=false clean -xd`. Reading the subcommand's flags alone - * would call that "no force, no warning" on the one spelling that needs none. - */ -const GIT_CLEAN_FORCE_WAIVED_RE = /^clean\.requireforce=(?:false|0|no|off)$/i; - /** - * The default `destructiveFlags`, and why the condition is these three letters - * rather than "any `git clean`". - * - * `git clean` deletes nothing without `-f` / `--force` (or the config above), - * and `-n` / `--dry-run` only prints — so force is the precondition and - * dry-run is the exemption. What force ALONE removes is untracked files in the - * current directory: the narrowest spelling, and the one people mean when they - * tidy up. These are the letters that widen the blast radius past that: - * - * - `-x` also removes IGNORED files — `.env`, local config, editor state, - * scratch work. That is the data that genuinely cannot be rebuilt by running - * a command, and it is what makes `git clean -fdx` the severe spelling. - * - `-X` removes ONLY ignored files: the same loss, tracked tree untouched. - * - `-d` also removes untracked DIRECTORIES — whole new subtrees git has never - * had a copy of. + * One linear pass over a command, as a shell would read it: quotes, `$'…'`, + * `${…}`, `$(…)` and backticks (also inside double quotes), `$((…))`, + * `( … )` subshells, comments, and heredocs with their bodies. * - * A bare `git clean -f` is deliberately absent. It has the smallest radius and - * by far the most traffic, and a guard that fires on the ordinary spelling is - * one people switch off — which would cost them the `-fdx` warning too. Add - * `"f"` to `destructiveFlags` to opt into it. + * The regexes this replaced read `< = { - pip: [/\bpip\b/, /\bpip3\b/, /\bpython3?\s+-m\s+pip\b/], - npm: [/\bnpm\b/, /\bnpx\b/], - yarn: [/\byarn\b/], - pnpm: [/\bpnpm\b/, /\bpnpx\b/], - bun: [/\bbun\b/, /\bbunx\b/], - uv: [/\buv\b/], - poetry: [/\bpoetry\b/], - pipenv: [/\bpipenv\b/], - conda: [/\bconda\b/], - cargo: [/\bcargo\b/], -}; +function lexShell(text: string, substitutionBody = false): ShellLex { + const n = text.length; + // Which outputs blank each position: one byte per character rather than four + // arrays of one-character strings, which made each pass allocate dozens of + // bytes per character of the command. + const READABLE = 1; + const SPLITTABLE = 2; + const SUBSTITUTION = 4; + const COMMANDS = 8; + const blanks = new Uint8Array(n); + const blankAt = (k: number, outputs: number): void => { + if (k < n) blanks[k] |= outputs; + }; + const programBodies: string[] = []; + const newCommand = (closer: ")" | "`" | null, substitution: boolean): LexCommandFrame => ({ + kind: "cmd", closer, substitution, head: null, words: [], word: "", decodedWords: [], decoded: "", + }); + const stack: LexFrame[] = [newCommand(null, false)]; + const pending: PendingHeredoc[] = []; + // Commands ended since the first pending heredoc on this line, in order: a + // heredoc's own command, then the ones its output is piped to. One list per + // line, so many operators on one line stay linear. + const lineCommands: LexEndedCommand[] = []; + + const commandFrame = (): LexCommandFrame => { + for (let k = stack.length - 1; k >= 0; k--) { + const frame = stack[k]; + if (frame.kind === "cmd") return frame; + } + return stack[0] as LexCommandFrame; + }; + const outerCommand = (): LexEndedCommand | null | undefined => { + // The substitution frame closest to the top, then the command below it. + for (let k = stack.length - 1; k >= 0; k--) { + const frame = stack[k]; + if (frame.kind !== "cmd") continue; + if (!frame.substitution) return undefined; + for (let j = k - 1; j >= 0; j--) { + const below = stack[j]; + if (below.kind === "cmd") return { head: below.head ?? (below.word ? commandBasename(below.word) : null), words: knownWords(below.decodedWords) }; + } + return null; + } + return undefined; + }; + const endWord = (frame: LexCommandFrame): void => { + if (!frame.word) return; + if (frame.words.length < 32) { + frame.words.push(frame.word); + frame.decodedWords.push(frame.decoded); + } + frame.decoded = ""; + if (frame.head === null) { + const base = commandBasename(frame.word); + const skipped = + ENV_ASSIGNMENT_RE.test(frame.word) || frame.word.startsWith("-") || RUNNER_OPERAND_RE.test(frame.word) || + MASK_TRANSPARENT_WORDS.has(base); + if (!skipped) frame.head = base; + } + frame.word = ""; + }; + const endCommand = (frame: LexCommandFrame): void => { + endWord(frame); + if (pending.length > 0) lineCommands.push({ head: frame.head, words: knownWords(frame.decodedWords) }); + frame.head = null; + frame.words = []; + frame.decodedWords = []; + }; + const quoteMask = (frame: LexCommandFrame): boolean => frame.head !== null && !isShellHead(frame.head); + // A word whose text an expansion decides is not known: empty, as before. + const knownWords = (words: readonly string[]): string[] => words.map((w) => (w.includes(UNKNOWN_IN_WORD) ? "" : w)); + // A closing quote hands its text, quotes undone, to the word it is part of. + const decodeQuote = (frame: LexQuoteFrame, end: number): void => { + const owner = stack[stack.length - 2]; + if (owner?.kind !== "cmd") return; + const raw = text.slice(frame.start, end); + if (frame.expands) owner.decoded += UNKNOWN_IN_WORD; + else if (frame.kind === "sq") owner.decoded += raw; + else if (frame.kind === "ansi") owner.decoded += decodeAnsiC(raw); + else owner.decoded += raw.replace(/\\([\\"$`])/g, "$1").replace(/\\\n/g, ""); + }; + const closeQuote = (frame: LexQuoteFrame, end: number): void => { + if (!frame.mask || !frame.plain) return; + for (let k = frame.start; k < end; k++) blanks[k] &= ~COMMANDS; + }; + const blankStored = (start: number, end: number, literal: boolean): void => { + for (let k = start; k < end; k++) { + if (text[k] === "\n") continue; + blankAt(k, READABLE | SPLITTABLE | COMMANDS | (literal ? SUBSTITUTION : 0)); + } + }; + // Whether anything from `pos` on pipes into a shell or `eval`s, and whether + // a file name appears from `pos` on. `pos` only grows, and each answer comes + // from a scan that never goes back over text: the next match of + // RUNS_TEXT_LATER_RE, and the last place each name appears. `pos` follows a + // newline, which stands in for the start of the text the regex once saw. + let nextRunsText = -2; + let lastNamed: Map | undefined; + // Later words an expansion builds (`bash /tmp/exam$X`), as patterns over the + // names they could make; past the cap, every name counts as used. + let wildNames: Array<{ at: number; atoms: GlobAtom[] }> = []; + let wildOverflowAt = -1; + const runsTextFrom = (pos: number): boolean => { + if (nextRunsText === -1) return false; + if (nextRunsText >= pos - 1) return true; + const scan = new RegExp(RUNS_TEXT_LATER_RE.source, "g"); + scan.lastIndex = Math.max(0, pos - 1); + nextRunsText = scan.exec(text)?.index ?? -1; + return nextRunsText !== -1; + }; + const namedFrom = (name: string, pos: number): boolean => { + if (lastNamed === undefined) { + lastNamed = new Map(); + // Words as the shell hands them over, quotes undone: `bash + // /tmp/exam'ple.md'` runs /tmp/example.md. + // A word built by an expansion, a glob or braces names whatever it can + // expand to: `bash /tmp/exa*`, `bash /tmp/{example,x}.md`, `bash + // /tmp/exam$X`. Each is a glob over names (an expansion is a `*`), + // matched by the same no-backtracking walk as every other glob here. + for (const { word, at } of decodedWordsAt(text)) { + const forms = word.includes("{") ? expandBraces(word) : [word]; + if (forms.length > 64) { + wildOverflowAt = Math.max(wildOverflowAt, at); + continue; + } + for (const form of forms) { + const base = form.slice(form.lastIndexOf("/") + 1); + if (!EXPANSION_IN_WORD_RE.test(base) && !GLOB_METACHAR_RE.test(base)) { + lastNamed.set(base, at); + continue; + } + const atoms = globAtoms(base.replace(EXPANSIONS_IN_NAME_RE, "*")); + if (atoms !== null && wildNames.length < 256) wildNames.push({ at, atoms }); + else wildOverflowAt = Math.max(wildOverflowAt, at); + } + } + } + if ((lastNamed.get(name) ?? -1) >= pos || wildOverflowAt >= pos) return true; + return wildNames.some((wild) => wild.at >= pos && globSegmentMatches(wild.atoms, name)); + }; + /** Read every pending heredoc's body, starting at `at`; return where lexing resumes. */ + const consumeBodies = (at: number): number => { + let pos = at; + const spans: Array<{ doc: PendingHeredoc; start: number; end: number }> = []; + for (const doc of pending.splice(0)) { + let bodyEnd = n; + let next = n; + for (let line = pos; line <= n; ) { + const end = text.indexOf("\n", line); + const content = text.slice(line, end === -1 ? n : end); + // The line must BE the delimiter: `EOF ` and ` EOF` are body text. + if ((doc.stripTabs ? content.replace(/^\t+/, "") : content) === doc.delimiter) { + bodyEnd = line; + next = end === -1 ? n : end + 1; + break; + } + if (end === -1) break; + line = end + 1; + } + spans.push({ doc, start: pos, end: bodyEnd }); + pos = next; + } + // What runs after the bodies, once for every heredoc on the line (a check + // per heredoc made thousands of operators on one line quadratic), and + // looked up rather than read: reading the rest of the text again for each + // line of heredocs made a script of them quadratic. + const later = { runsText: runsTextFrom(pos), names: { has: (name: string) => namedFrom(name, pos) } }; + // Whether an interpreter runs at or after each command of the line, read + // once from the end. Copying and scanning the rest of the line for every + // heredoc made a line of thousands of them quadratic. + const interpreterFrom = new Array(lineCommands.length + 1).fill(false); + for (let k = lineCommands.length - 1; k >= 0; k--) { + interpreterFrom[k] = interpreterFrom[k + 1] || isInterpreterHead(lineCommands[k].head); + } + for (const { doc, start, end } of spans) { + const own = lineCommands[doc.commandIndex] ?? { head: null, words: [] }; + const downstream = { count: Math.max(0, lineCommands.length - doc.commandIndex - 1), next: lineCommands[doc.commandIndex + 1] }; + if (heredocIsStoredText(doc, own, downstream, later, substitutionBody)) blankStored(start, end, doc.literal); + else if (isInterpreterHead(own.head) || interpreterFrom[doc.commandIndex + 1] === true) { + programBodies.push(text.slice(start, end)); + } + } + lineCommands.length = 0; + return pos; + }; -// warnBackgroundProcess -const NOHUP_RE = /\bnohup\s+\S/; -const SCREEN_DETACH_RE = /\bscreen\s+-[A-Za-z]*d[A-Za-z]*\b/; -const TMUX_DETACH_RE = /\btmux\s+(?:new-session|new)\b[^|&;]*-d\b/; -const DISOWN_RE = /\bdisown\b/; -const BACKGROUND_AMPERSAND_RE = /(?(); -const GIT_BRANCH_CACHE_MAX_ENTRIES = 500; + let i = 0; + while (i < n) { + const ch = text[i]; + const frame = stack[stack.length - 1]; + if (frame.kind === "sq") { + if (ch === "'") { + closeQuote(frame, i); + decodeQuote(frame, i); + stack.pop(); + } else if (frame.mask) { + if (MASKABLE_IN_QUOTES.includes(ch)) blankAt(i, SPLITTABLE); + if (ch !== "\n") blankAt(i, COMMANDS); + if (frame.plain && NOT_IN_A_QUOTED_WORD.includes(ch)) frame.plain = false; + } + i++; + continue; + } + if (frame.kind === "ansi") { + if (ch === "\\") { + frame.plain = false; + if (frame.mask) { + blankAt(i, COMMANDS); + if (i + 1 < n && text[i + 1] !== "\n") blankAt(i + 1, COMMANDS); + } + i += 2; + continue; + } + if (ch === "'") { + closeQuote(frame, i); + decodeQuote(frame, i); + stack.pop(); + } else if (frame.mask) { + if (MASKABLE_IN_QUOTES.includes(ch)) blankAt(i, SPLITTABLE); + if (ch !== "\n") blankAt(i, COMMANDS); + if (frame.plain && NOT_IN_A_QUOTED_WORD.includes(ch)) frame.plain = false; + } + i++; + continue; + } + if (frame.kind === "arith") { + if (ch === "(") frame.depth++; + else if (ch === ")") { + if (frame.depth === 0 && text[i + 1] === ")") { + blankAt(i, SPLITTABLE); + blankAt(i + 1, SPLITTABLE); + stack.pop(); + i += 2; + continue; + } + frame.depth = Math.max(0, frame.depth - 1); + } + i++; + continue; + } + if (frame.kind === "param") { + // Nothing inside `${…}` separates, redirects, opens a subshell or starts + // a comment: `${X:- #}; rm …` runs the `rm`. + if (ch === "\\") { + i += 2; + continue; + } + if (ch === "'" || ch === '"') { + stack.push({ kind: ch === "'" ? "sq" : "dq", mask: true, start: i + 1, plain: true }); + i++; + continue; + } + if (ch === "$" && text[i + 1] === "(") { + stack.push(newCommand(")", true)); + blankAt(i + 1, SPLITTABLE); + i += 2; + continue; + } + if (ch === "{") frame.depth++; + else if (ch === "}") { + if (frame.depth === 0) { + stack.pop(); + i++; + continue; + } + frame.depth--; + } else if (MASKABLE_IN_QUOTES.includes(ch)) blankAt(i, SPLITTABLE); + i++; + continue; + } + if (frame.kind === "dq") { + if (ch === "\\") { + frame.plain = false; + if (frame.mask) { + blankAt(i, COMMANDS); + if (i + 1 < n && text[i + 1] !== "\n") blankAt(i + 1, COMMANDS); + } + i += 2; + continue; + } + if (ch === '"') { + closeQuote(frame, i); + decodeQuote(frame, i); + stack.pop(); + i++; + continue; + } + if (ch === "`" || (ch === "$" && (text[i + 1] === "(" || text[i + 1] === "{"))) frame.plain = false; + if (ch === "`" || (ch === "$" && /[A-Za-z_({0-9@*#?$!-]/.test(text[i + 1] ?? ""))) frame.expands = true; + // The parentheses of `$(…)` and `$((…))` open no subshell: blanked where + // the walk counts subshells, so a `cd "$(dirname …)"` keeps its reach. + if (ch === "$" && text[i + 1] === "(" && text[i + 2] === "(") { + stack.push({ kind: "arith", depth: 0 }); + blankAt(i + 1, SPLITTABLE); + blankAt(i + 2, SPLITTABLE); + i += 3; + continue; + } + if (ch === "$" && text[i + 1] === "(") { + stack.push(newCommand(")", true)); + blankAt(i + 1, SPLITTABLE); + i += 2; + continue; + } + if (ch === "$" && text[i + 1] === "{") { + stack.push({ kind: "param", depth: 0 }); + i += 2; + continue; + } + if (ch === "`") { + stack.push(newCommand("`", true)); + i++; + continue; + } + if (frame.mask) { + if (MASKABLE_IN_QUOTES.includes(ch)) blankAt(i, SPLITTABLE); + if (ch !== "\n") blankAt(i, COMMANDS); + if (frame.plain && NOT_IN_A_QUOTED_WORD.includes(ch)) frame.plain = false; + } + i++; + continue; + } -function statGitHeadMtimeMs(cwd: string): number | null { - try { - return statSync(join(cwd, ".git", "HEAD")).mtimeMs; - } catch { - return null; + // A command context. + const command = frame as LexCommandFrame; + if (ch === "\\") { + // A backslash-newline joins lines; any other escaped character is literal. + if (text[i + 1] !== "\n") { + command.word += text[i + 1] ?? ""; + command.decoded += text[i + 1] ?? ""; + } + i += 2; + continue; + } + if (ch === "`" && command.closer === "`") { + endCommand(command); + stack.pop(); + commandFrame().word += "q"; + commandFrame().decoded += UNKNOWN_IN_WORD; + i++; + continue; + } + if (ch === "'" || ch === '"' || (ch === "$" && text[i + 1] === "'")) { + stack.push({ + kind: ch === "'" ? "sq" : ch === '"' ? "dq" : "ansi", + mask: quoteMask(command), + start: i + (ch === "$" ? 2 : 1), + plain: true, + }); + command.word += "q"; + i += ch === "$" ? 2 : 1; + continue; + } + if (ch === "$" && text[i + 1] === "(" && text[i + 2] === "(") { + stack.push({ kind: "arith", depth: 0 }); + blankAt(i + 1, SPLITTABLE); + blankAt(i + 2, SPLITTABLE); + command.word += "q"; + command.decoded += UNKNOWN_IN_WORD; + i += 3; + continue; + } + if (ch === "$" && text[i + 1] === "(") { + stack.push(newCommand(")", true)); + blankAt(i + 1, SPLITTABLE); + command.word += "q"; + command.decoded += UNKNOWN_IN_WORD; + i += 2; + continue; + } + if (ch === "$" && text[i + 1] === "{") { + stack.push({ kind: "param", depth: 0 }); + command.word += "q"; + command.decoded += UNKNOWN_IN_WORD; + i += 2; + continue; + } + if (ch === "`") { + stack.push(newCommand("`", true)); + command.word += "q"; + command.decoded += UNKNOWN_IN_WORD; + i++; + continue; + } + if (ch === "#" && command.word === "") { + // A comment runs to the end of the line, and nothing in it is shell. + let j = i; + for (; j < n && text[j] !== "\n"; j++) { + blankAt(j, READABLE | SPLITTABLE | COMMANDS); + } + i = j; + continue; + } + if (ch === "(") { + endWord(command); + stack.push(newCommand(")", false)); + i++; + continue; + } + if (ch === ")") { + if (command.closer === ")") { + endCommand(command); + stack.pop(); + if (command.substitution) { + blankAt(i, SPLITTABLE); + commandFrame().word += "q"; + } + } + i++; + continue; + } + if (ch === "<" && text[i + 1] === "<" && text[i + 2] !== "<" && text[i - 1] !== "<") { + const op = readHeredocDelimiter(text, i + 2); + if (op) { + endWord(command); + pending.push({ + delimiter: op.delimiter, + literal: op.literal, + stripTabs: op.stripTabs, + commandIndex: lineCommands.length, + outer: outerCommand(), + }); + i = op.end; + continue; + } + } + if (ch === "\n") { + endCommand(command); + i = pending.length > 0 ? consumeBodies(i + 1) : i + 1; + continue; + } + if (ch === ";" || ch === "&" || ch === "|") { + endCommand(command); + i++; + continue; + } + if (ch === " " || ch === "\t" || ch === "\r") { + endWord(command); + i++; + continue; + } + command.word += ch; + command.decoded += ch; + i++; + } + if (pending.length > 0) { + endCommand(commandFrame()); + consumeBodies(n); } + // Each output is the text with its blanked positions turned into spaces, or + // the text itself when nothing in it was blanked. + const render = (output: number): string => { + let out = ""; + let from = 0; + let blanked = false; + for (let k = 0; k < n; ) { + if ((blanks[k] & output) === 0) { + k++; + continue; + } + let end = k; + while (end < n && (blanks[end] & output) !== 0) end++; + out += text.slice(from, k) + " ".repeat(end - k); + from = end; + k = end; + blanked = true; + } + return blanked ? out + text.slice(from) : text; + }; + return { + readable: render(READABLE), + splittable: render(SPLITTABLE), + substitutionSource: render(SUBSTITUTION), + commandsOnly: render(COMMANDS), + programBodies, + }; } - -function getCurrentBranch(cwd: string): string | null { - try { - const headMtimeMs = statGitHeadMtimeMs(cwd); - const cached = gitBranchCache.get(cwd); - if (cached && headMtimeMs !== null && cached.headMtimeMs === headMtimeMs) { - return cached.branch || null; +/** + * Index past the end of a `$(…)`, `${…}` or backtick that starts at `i`, + * quotes inside it included: what the shell keeps inside one word. + */ +function endOfExpansion(text: string, i: number): number { + if (text[i] === "`") { + for (let j = i + 1; j < text.length; j++) { + if (text[j] === "\\") j++; + else if (text[j] === "`") return j + 1; } - const branch = execSync("git rev-parse --abbrev-ref HEAD", { - cwd, - encoding: "utf8", stdio: ["pipe", "pipe", "pipe"], - timeout: 3000, - }).trim(); - if (headMtimeMs !== null) { - if (gitBranchCache.size >= GIT_BRANCH_CACHE_MAX_ENTRIES) gitBranchCache.clear(); - gitBranchCache.set(cwd, { branch, headMtimeMs }); + return text.length; + } + const open = text[i + 1]; + const close = open === "(" ? ")" : "}"; + let depth = 0; + for (let j = i + 1; j < text.length; j++) { + const c = text[j]; + if (c === "\\") { + j++; + continue; + } + if (c === "'") { + const end = text.indexOf("'", j + 1); + if (end === -1) return text.length; + j = end; + continue; + } + if (c === open) depth++; + else if (c === close) { + depth--; + if (depth === 0) return j + 1; } - return branch || null; - } catch { - return null; } + return text.length; } - -function getHeadSha(cwd: string): string | null { - try { - const sha = execSync("git rev-parse HEAD", { - cwd, - encoding: "utf8", stdio: ["pipe", "pipe", "pipe"], - timeout: 3000, - }).trim(); - return sha || null; - } catch { - return null; +/** + * A simple command's words the way the shell will split them: whitespace + * outside quotes and expansions separates, and quotes and backslash escapes + * come off. `$(…)`, `${…}` and backticks stay whole, as written, so + * `cd $(echo ~/.claude)` has one operand. + */ +function quoteAwareWords(text: string): string[] { + const words: string[] = []; + let current = ""; + let inWord = false; + for (let i = 0; i < text.length; i++) { + const ch = text[i]; + if (ch === "'") { + const close = text.indexOf("'", i + 1); + const end = close === -1 ? text.length : close; + current += text.slice(i + 1, end); + inWord = true; + i = end; + continue; + } + if (ch === "$" && text[i + 1] === "'") { + let j = i + 2; + let body = ""; + for (; j < text.length && text[j] !== "'"; j++) { + if (text[j] === "\\" && j + 1 < text.length) { + body += text[j] + text[j + 1]; + j++; + } else body += text[j]; + } + current += decodeAnsiC(body); + inWord = true; + i = j; + continue; + } + if ((ch === "$" && (text[i + 1] === "(" || text[i + 1] === "{")) || ch === "`") { + const end = endOfExpansion(text, i); + current += text.slice(i, end); + inWord = true; + i = end - 1; + continue; + } + if (ch === '"') { + let j = i + 1; + for (; j < text.length && text[j] !== '"'; j++) { + if (text[j] === "$" && (text[j + 1] === "(" || text[j + 1] === "{")) { + const end = endOfExpansion(text, j); + current += text.slice(j, end); + j = end - 1; + } else if (text[j] === "\\" && j + 1 < text.length && '"\\$`\n'.includes(text[j + 1])) { + current += text[j + 1]; + j++; + } else current += text[j]; + } + inWord = true; + i = j; + continue; + } + if (ch === "\\" && i + 1 < text.length) { + current += text[i + 1]; + inWord = true; + i++; + continue; + } + if (/\s/.test(ch)) { + if (inWord) words.push(current); + current = ""; + inWord = false; + continue; + } + current += ch; + inWord = true; } + if (inWord) words.push(current); + return words; } - -interface CiCheck { - name: string; - status: string; - conclusion: string; +/** + * The words of a simple command from its head on, the prefixes a shell walks + * past dropped. `viaXargs`: an `xargs` stood among those prefixes. + * `readsStdinProgram`: the command is a bare shell or interpreter, which runs + * whatever is piped into it (`echo '…' | sh`). + */ +function quoteAwareCommandWords(simple: string): { words: string[]; viaXargs: boolean; readsStdinProgram: boolean } { + const all = quoteAwareWords(simple); + let viaXargs = false; + let shell = false; + let i = 0; + for (; i < all.length; i++) { + const word = all[i]; + const base = commandBasename(word); + if (base === "xargs") viaXargs = true; + if (STDIN_PROGRAM_HEADS.has(base)) shell = true; + const skippable = + ENV_ASSIGNMENT_RE.test(word) || word.startsWith("-") || RUNNER_OPERAND_RE.test(word) || + SHELL_KEYWORD_PREFIXES.has(word) || COMMAND_PREFIX_TOKENS.has(base); + if (!skippable) break; + } + const words = all.slice(i); + return { words, viaXargs, readsStdinProgram: shell && words.length === 0 }; } - -/** Fetch third-party check runs (non-GitHub-Actions) for a commit via the Checks API. */ -function getThirdPartyCheckRuns(cwd: string, sha: string): CiCheck[] { - try { - const json = execFileSync( - "gh", - [ - "api", - `repos/{owner}/{repo}/commits/${sha}/check-runs`, - "--jq", - '.check_runs | map(select(.app.slug != "github-actions")) | map({name: .name, status: .status, conclusion: (.conclusion // "")})', - ], - { - cwd, - encoding: "utf8", stdio: ["pipe", "pipe", "pipe"], - timeout: 15000, - }, - ).trim(); - - if (!json || json === "[]") return []; - return JSON.parse(json) as CiCheck[]; - } catch { - return []; +/** `e`: sed runs a shell command, as a command (`1e cp …`) or as the flag on `s` (`s/x/y/e`). */ +const SED_RUNS_COMMAND_RE = /(?:^|[;{}\s/0-9$,!])[ \t]*[gpIiMm0-9]*e[gpIiMm0-9]*(?=$|[\s;}])/; +/** `w` and `W`: sed writes the rest of the line's text as a file name, glued on or after a space. */ +const SED_WRITE_FILE_RE = /(?:^|[;{}\s/0-9$,!])[ \t]*[gpIiMm0-9]*[wW][ \t]*([^\n]+)/g; +/** + * The script texts a `sed` command runs: each `-e`/`--expression` value, or the + * first operand when there is none. Null when a script comes from a file + * (`-f`), which cannot be read from here. Options that take a value + * (`-l `, `--line-length `) take it, so the value is never the script. + */ +function sedScripts(rawSimple: string): string[] | null { + const words = quoteAwareWords(rawSimple); + const at = words.findIndex((w) => commandBasename(w) === "sed"); + if (at === -1) return []; + const scripts: string[] = []; + let explicit = false; + for (let i = at + 1; i < words.length; i++) { + const a = words[i]; + if (a === "-e" || a === "--expression") { + scripts.push(words[++i] ?? ""); + explicit = true; + continue; + } + if (a.startsWith("--expression=")) { + scripts.push(a.slice("--expression=".length)); + explicit = true; + continue; + } + if (a === "--file" || a.startsWith("--file=") || /^-(?!-)[A-Za-z]*f/.test(a)) return null; + if (a === "-l" || a === "--line-length") { + i++; + continue; + } + if (/^-(?!-)[A-Za-z]*e$/.test(a)) { + scripts.push(words[++i] ?? ""); + explicit = true; + continue; + } + if (/^-(?!-)[A-Za-z]*e./.test(a)) { + scripts.push(a.slice(a.indexOf("e") + 1)); + explicit = true; + continue; + } + if (a.startsWith("-")) continue; + if (!explicit && scripts.length === 0) scripts.push(a); } + return scripts; } - -/** Fetch commit statuses (legacy Status API) and normalize to CiCheck format. */ -function getCommitStatuses(cwd: string, sha: string): CiCheck[] { - try { - const json = execFileSync( - "gh", - [ - "api", - `repos/{owner}/{repo}/commits/${sha}/statuses`, - "--jq", - 'map({name: .context, state: .state}) | unique_by(.name)', - ], - { - cwd, - encoding: "utf8", stdio: ["pipe", "pipe", "pipe"], - timeout: 15000, - }, - ).trim(); - - if (!json || json === "[]") return []; - const statuses = JSON.parse(json) as Array<{ name: string; state: string }>; - return statuses.map((s) => ({ - name: s.name, - status: s.state === "pending" ? "in_progress" : "completed", - conclusion: s.state === "pending" ? "" : s.state === "success" ? "success" : "failure", - })); - } catch { - return []; +/** + * `text` with each expansion — `$VAR`, `${…}`, `$(…)`, backticks — turned into + * `*`, a pattern that reaches at least every word the shell could produce: + * `~/.claude/settings$X.json`, `~/.clau${X}de/settings.json`, + * `settings$( true ).json` and `~/.fa${X:-ilproofai}` all reach their file, and + * are tried against it like any other glob. Spliced before the text is cut into + * words, so an expansion holding a space stays in its word; an expansion + * standing alone becomes a bare `*`, which the decoys keep from naming + * anything. + * + * One pass with a bracket stack, so nesting and length cost nothing extra: a + * regex bounded to keep unclosed `${` linear also let an expansion longer than + * its bound through unspliced. An unclosed one stays as written. + */ +function spliceWordExpansions(text: string, commandSubstitutionsOnly = false): string { + const spans: Array<[number, number]> = []; + const stack: Array<{ close: string; start: number; expansion: boolean }> = []; + // How many of those are expansions: asking the stack each time made literal + // parentheses followed by `$NAME`s quadratic. + let openExpansions = 0; + const outermost = (): boolean => openExpansions === 0; + let backtick = -1; + for (let i = 0; i < text.length; i++) { + const ch = text[i]; + if (ch === "\\") { + i++; + continue; + } + if (ch === "`") { + if (backtick === -1) backtick = i; + else { + if (outermost()) spans.push([backtick, i + 1]); + backtick = -1; + } + continue; + } + if (backtick !== -1) continue; + if (ch === "$" && (text[i + 1] === "{" || text[i + 1] === "(")) { + const brace = text[i + 1] === "{"; + const expansion = !(brace && commandSubstitutionsOnly); + stack.push({ close: brace ? "}" : ")", start: i, expansion }); + if (expansion) openExpansions++; + i++; + continue; + } + if (ch === "$" && !commandSubstitutionsOnly && /[A-Za-z_]/.test(text[i + 1] ?? "")) { + let j = i + 1; + while (j < text.length && /[A-Za-z0-9_]/.test(text[j])) j++; + if (outermost()) spans.push([i, j]); + i = j - 1; + continue; + } + if (ch === "{" || ch === "(") { + stack.push({ close: ch === "{" ? "}" : ")", start: i, expansion: false }); + continue; + } + if ((ch === "}" || ch === ")") && stack.length > 0 && stack[stack.length - 1].close === ch) { + const open = stack.pop()!; + if (open.expansion) openExpansions--; + if (open.expansion && outermost()) spans.push([open.start, i + 1]); + } + } + if (spans.length === 0) return text; + spans.sort((a, b) => a[0] - b[0]); + let out = ""; + let pos = 0; + for (const [start, end] of spans) { + if (start < pos) continue; + out += text.slice(pos, start) + "*"; + pos = end; } + return out + text.slice(pos); } +/** `$(…)` and backticks, which the shell splices into the word around them. */ +/** A word the shell resolves against the current directory. */ /** - * Check if a command matches an allow pattern using token-by-token comparison. - * The "*" token is a wildcard. Extra command tokens beyond the pattern are allowed, - * UNLESS any token is a standalone shell operator (&&, ||, |, ;) OR contains an - * embedded shell metacharacter — both cases are rejected to prevent bypass via - * appended sub-commands or glued operators (e.g. "nginx;" or "nginx;evil"). + * A relative glob (`cfg*.json`): where the shell stands is lost, it may expand + * onto the target there as a plain name may (found by hermes on #1053). */ -function matchesAllowedPattern(cmd: string, pattern: string): boolean { - const cmdTokens = parseArgvTokens(cmd); - const patTokens = parseArgvTokens(pattern); - if (cmdTokens.length < patTokens.length) return false; - // Reject commands containing standalone shell-operator tokens - if (cmdTokens.some((tok) => SHELL_OPERATORS.has(tok))) return false; - // Reject any token containing embedded shell metacharacters - if (cmdTokens.some((tok) => SHELL_METACHAR_RE.test(tok))) return false; - return patTokens.every((tok, i) => tok === "*" || tok === cmdTokens[i]); +function isRelativeGlobWord(word: string): boolean { + return word.length > 0 && !/^[-/~$]/.test(word) && !word.includes("://") && GLOB_METACHAR_RE.test(word); } - -// -- Policy implementations -- - -function sanitizeJwt(ctx: PolicyContext): PolicyResult { - // PostToolUse: scrub JWT patterns from tool output - const output = JSON.stringify(ctx.payload); - if (JWT_RE.test(output)) { - return { - decision: "deny", - reason: "JWT token detected in tool output", - message: "[REDACTED: JWT token removed by failproofai]", - }; - } - return allow(); +function isRelativeShellWord(word: string): boolean { + return word.length > 0 && !/^[-/~$]/.test(word) && !word.includes("://") && !GLOB_METACHAR_RE.test(word); } - -function sanitizeApiKeys(ctx: PolicyContext): PolicyResult { - // PostToolUse: scrub common API key patterns from tool output - const output = JSON.stringify(ctx.payload); - for (const [pattern, label] of API_KEY_PATTERNS) { - if (pattern.test(output)) { - return { - decision: "deny", - reason: `${label} detected in tool output`, - message: `[REDACTED: ${label} removed by failproofai]`, - }; +/** + * Where `cd ` leaves a shell that stood in `from`, or undefined when + * that cannot be known from the text (`cd -`, `cd $DIR`, `cd "$(dirname …)"`). + */ +function cdDestination(from: string | undefined, operand: string | undefined): string | undefined { + if (operand === undefined || operand === "~" || operand === "$HOME" || operand === "${HOME}") return homedir(); + const home = /^(?:~|\$HOME|\$\{HOME\})\/(.*)$/.exec(operand); + if (home) return resolve(homedir(), home[1]); + if (operand === "-" || operand.includes("$") || operand.includes("`")) return undefined; + if (operand.startsWith("/")) return resolve(operand); + return from === undefined ? undefined : resolve(from, operand); +} +/** + * Whether a git command reaches the target through the directories its `-C` + * options move it to — which no word of its text names: `git -C external -C + * link/.. log --output=settings.json` writes ~/.claude/settings.json with + * `external/link -> ~/.claude/x`. Asked before the walk's own gate, which + * reads only the text. + */ +function gitReachesTarget( + gitWords: string[], + cwds: ReadonlyArray, + names: (text: string) => boolean, + valuesOf: (word: string) => string[] | null = () => null, +): boolean { + const repositories = gitRepositoryDirs(gitWords, cwds, valuesOf); + if (repositories.length === 0) return false; + if (repositories.some((repository) => repository !== GIT_REPOSITORY_LOST && names(repository))) return true; + const lost = repositories.includes(GIT_REPOSITORY_LOST); + return gitWords.some((word) => { + // `--output=`, a value glued to a short option (`-o`), or the word itself. + const value = word.includes("=") ? word.slice(word.indexOf("=") + 1) : /^-[A-Za-z]./.test(word) && !word.startsWith("--") ? word.slice(2) : word; + if (lost && /^--?(?:output|output-directory|o)(?:=|$)|^-o./.test(word) && isRelativeShellWord(value)) return true; + return isRelativeShellWord(value) && repositories.some((repository) => repository !== GIT_REPOSITORY_LOST && names(`${repository}/${value}`)); + }); +} +/** Short options of `cp` and `install` that take a value; `t` is the target directory. */ +const COPY_VALUE_OPTIONS: Readonly> = { cp: "St", install: "gmoSt" }; +/** + * The target directory a `cp` or `install` names, however it is spelled — `-t + * DIR`, `-tDIR`, `-vt DIR`, `-vtDIR`, `--target-directory=DIR` or any prefix + * of it — with the indexes of option values, which are no operands. Not + * `rsync`, whose `-t` is `--times`. + */ +function copyTargetDirectory(head: string, args: readonly string[]): { dir: string; values: Set } | null { + const valued = COPY_VALUE_OPTIONS[head]; + if (!valued) return null; + let dir: string | null = null; + const values = new Set(); + for (let i = 0; i < args.length; i++) { + const arg = args[i]; + if (arg === "--") break; + if (arg.startsWith("--")) { + const eq = arg.indexOf("="); + const name = arg.slice(2, eq === -1 ? undefined : eq); + if (name.length >= 1 && "target-directory".startsWith(name)) { + if (eq !== -1) dir = arg.slice(eq + 1); + else if (i + 1 < args.length) { + dir = args[i + 1]; + values.add(++i); + } + } + continue; } - } - - // Check additional user-configured patterns - const additional = ((ctx.params?.additionalPatterns ?? []) as Array<{ regex: string; label: string }>); - for (const { regex, label } of additional) { - try { - if (new RegExp(regex).test(output)) { - return { - decision: "deny", - reason: `${label} detected in tool output`, - message: `[REDACTED: ${label} removed by failproofai]`, - }; + if (!arg.startsWith("-") || arg.length < 2) continue; + for (let k = 1; k < arg.length; k++) { + if (!valued.includes(arg[k])) continue; + const rest = arg.slice(k + 1); + let value: string | undefined = rest; + if (rest.length === 0) { + value = args[i + 1]; + if (value !== undefined) values.add(++i); } - } catch { - hookLogWarn(`additionalPatterns: invalid regex "${regex}", skipping`); + if (arg[k] === "t" && value !== undefined) dir = value; + break; } } - - return allow(); + return dir === null ? null : { dir, values }; } - -function sanitizeConnectionStrings(ctx: PolicyContext): PolicyResult { - // PostToolUse: scrub database connection strings with embedded credentials - const output = JSON.stringify(ctx.payload); - if (CONNECTION_STRING_RE.test(output)) { - return { - decision: "deny", - reason: "Database connection string with credentials detected in tool output", - message: "[REDACTED: connection string removed by failproofai]", - }; - } - return allow(); +/** Whether a copy's destination word names a directory that exists now, seen from `cwd`. */ +function existingDirectory(word: string, cwd: string | undefined): boolean { + const plain = stripShellQuoting(word); + if (/[$`*?[]/.test(plain)) return false; + const path = cdDestination(cwd, plain); + return path !== undefined && isDirectoryNow(path); } - -function sanitizePrivateKeyContent(ctx: PolicyContext): PolicyResult { - // PostToolUse: scrub PEM private key blocks from tool output - const output = JSON.stringify(ctx.payload); - if (PRIVATE_KEY_RE.test(output)) { - return { - decision: "deny", - reason: "Private key content detected in tool output", - message: "[REDACTED: private key content removed by failproofai]", - }; +/** Whether `path` is a directory now, so a `cd` into it succeeds. */ +function isDirectoryNow(path: string): boolean { + try { + return statSync(path, { throwIfNoEntry: false })?.isDirectory() === true; + } catch { + return false; } - return allow(); } - -function sanitizeBearerTokens(ctx: PolicyContext): PolicyResult { - // PostToolUse: scrub Authorization: Bearer tokens from tool output - const output = JSON.stringify(ctx.payload); - if (BEARER_TOKEN_RE.test(output)) { - return { - decision: "deny", - reason: "Bearer token detected in tool output", - message: "[REDACTED: Bearer token removed by failproofai]", - }; +/** `text` cut at every match of `separator`, as `[start, end)` ranges. */ +function cutRanges(text: string, separator: RegExp): Array<[number, number]> { + const global = new RegExp(separator.source, separator.flags.includes("g") ? separator.flags : `${separator.flags}g`); + const ranges: Array<[number, number]> = []; + let start = 0; + for (const match of text.matchAll(global)) { + ranges.push([start, match.index]); + start = match.index + match[0].length; } - return allow(); + ranges.push([start, text.length]); + return ranges; } - -function warnDestructiveSql(ctx: PolicyContext): PolicyResult { - if (ctx.toolName !== "Bash") return allow(); - const cmd = getCommand(ctx); - if (!SQL_TOOL_RE.test(cmd)) return allow(); - - // DROP or TRUNCATE always warns - if (DESTRUCTIVE_SQL_RE.test(cmd)) { - return instruct( - "STOP: This command contains destructive SQL (DROP/TRUNCATE/DELETE). Confirm with the user before executing.", - ); - } - - // DELETE FROM without WHERE warns - if (DELETE_NO_WHERE_RE.test(cmd) && !SQL_WHERE_RE.test(cmd)) { - return instruct( - "STOP: This command contains destructive SQL (DROP/TRUNCATE/DELETE). Confirm with the user before executing.", - ); - } - - return allow(); +/** + * One command's disk-glob work: each directory read once, and bounds on the + * entries read, the entries matched and the paths checked across all of its + * globs. Only a command built to stall the guard reaches them, and one that + * does reads as reaching the target: a limit never stands for "no match". + */ +interface DiskGlobBudget { + listings: Map | null>; + /** Directory entries read from disk. */ + entries: number; + /** Entries matched against a pattern, cached listings included. */ + steps: number; + /** Expanded paths handed to the caller's check. */ + checks: number; } - -function warnLargeFileWrite(ctx: PolicyContext): PolicyResult { - if (ctx.toolName !== "Write") return allow(); - const content = ctx.toolInput?.content as string | undefined; - if (typeof content !== "string") return allow(); - const thresholdKb = ((ctx.params?.thresholdKb ?? 1024) as number); - const thresholdBytes = thresholdKb * 1024; - if (content.length > thresholdBytes) { - return instruct( - `STOP: You are writing a file larger than ${thresholdKb}KB (${Math.round(content.length / 1024)}KB). This is unusually large. Confirm this is intentional before proceeding.`, - ); - } - return allow(); +/** The shell options that change what a glob matches, as far as the command turns them on. */ +interface GlobOptions { + /** `*` and `?` match a leading dot (`shopt -s dotglob`, or GLOBIGNORE set). */ + dotglob: boolean; + /** `**` matches any depth of directories (`shopt -s globstar`). */ + globstar: boolean; + /** Matching ignores case (`shopt -s nocaseglob`). */ + nocaseglob: boolean; } - -function warnPackagePublish(ctx: PolicyContext): PolicyResult { - if (ctx.toolName !== "Bash") return allow(); - const cmd = getCommand(ctx); - if (PUBLISH_CMD_RE.test(cmd)) { - return instruct( - "STOP: This command publishes a package to a public registry. Confirm with the user that this is intentional.", - ); - } - return allow(); +/** + * The glob options a command may turn on, in bash's spelling or zsh's. + * + * - dotglob: bash `shopt -s dotglob` or `GLOBIGNORE=`; zsh `setopt globdots` + * (any case, underscores ignored) or a `(D)` glob qualifier. + * - globstar: bash `shopt -s globstar`; zsh `setopt globstarshort`; and any + * `**` or `***` path segment, which zsh recurses into by default. + * - nocaseglob: bash `shopt -s nocaseglob`; zsh `setopt nocaseglob`, + * `unsetopt caseglob`, or the `(#i)` pattern flag. + */ +/** A zsh pattern flag group: `(#i)`, `(#l)`, `(#a2)`. */ +const ZSH_GLOB_FLAG_RE = /\(#[A-Za-z0-9]*\)/; +function globOptionsOf(command: string): GlobOptions { + // zsh option names: case and underscores do not count (`GLOB_DOTS`). + const names = command.toLowerCase().replace(/_/g, ""); + return { + dotglob: /\b(?:dotglob|globdots)\b|globignore=/.test(names) || /\*\([^()|\s]*D[^()|\s]*\)/.test(command), + globstar: /\bglobstar(?:short)?\b/.test(names) || /(?:^|[\s/"'=(])\*{2,3}(?=\/|$|[\s"';&|)])/.test(command), + nocaseglob: + /\bnocaseglob\b/.test(names) || + /\bunsetopt\b[^;&|\n]*\bcaseglob\b/.test(names) || + /\(#[a-z]*i[a-z]*\)/i.test(command), + }; } - -function protectEnvVars(ctx: PolicyContext): PolicyResult { - if (ctx.toolName !== "Bash") return allow(); - const cmd = getCommand(ctx); - // Block: env, printenv, echo $VAR, export VAR= - if (ENV_PRINTENV_RE.test(cmd)) { - return deny("Command reads environment variables"); - } - if (ECHO_ENV_RE.test(cmd)) { - return deny("Command echoes environment variable"); - } - if (EXPORT_RE.test(cmd)) { - return deny("Command exports environment variable"); - } - if (ENV_DUMP_RE.test(cmd) || (SCRIPT_INTERP_RE.test(cmd) && ENV_OBJECT_RE.test(cmd))) { - return deny("Command dumps environment variables"); +/** A glob segment with each extended-glob group replaced by `*`, which matches at least what the group does. */ +function withExtglobsAsStars(segment: string): string { + let out = ""; + for (let i = 0; i < segment.length; i++) { + const group = extglobAt(segment, i); + if (group) { + out += "*"; + i = group.end; + } else { + out += segment[i]; + } } - // PowerShell: $env:VAR - if (PS_ENV_VAR_RE.test(cmd)) { - return deny("Command reads environment variable via PowerShell"); + return out; +} +/** + * Whether a glob word, expanded on disk as the shell expands it, reaches a + * path `reaches` accepts: braces first, then each segment with glob + * characters matched against the entries of its directory — a leading dot + * only by a pattern that starts with one unless dotglob is on, `**` at any + * depth under globstar — relative to `cwd` when relative. Paths are joined as + * written, never normalised, so a `..` after a link is walked the way the + * kernel walks it. Every path a glob expands to is checked, however many, + * within the command's budget; "exhausted" past it, which the caller reads as + * reaching the target. + */ +function globOnDiskReaches( + word: string, + cwd: string | undefined, + budget: DiskGlobBudget, + options: GlobOptions, + reaches: (path: string) => boolean, +): boolean | "exhausted" { + const join = (base: string, name: string): string => (base.endsWith("/") ? base + name : `${base}/${name}`); + const list = (base: string): Array<{ name: string; dir: boolean }> | null | "exhausted" => { + let entries = budget.listings.get(base); + if (entries === undefined) { + try { + entries = readdirSync(base, { withFileTypes: true }).map((entry) => ({ name: entry.name, dir: entry.isDirectory() })); + } catch { + entries = null; + } + budget.listings.set(base, entries); + budget.entries -= entries?.length ?? 0; + if (budget.entries < 0) return "exhausted"; + } + if (entries === null) return null; + budget.steps -= entries.length; + return budget.steps < 0 ? "exhausted" : entries; + }; + for (const expanded of expandBraces(word)) { + let path = expanded === "~" || expanded.startsWith("~/") ? homedir() + expanded.slice(1) : expanded; + if (!path.startsWith("/")) { + if (cwd === undefined) continue; + path = `${cwd}/${path}`; + } + const segments = path.split("/").filter(Boolean); + const pending: Array<[string, number]> = [["/", 0]]; + while (pending.length > 0) { + const [base, k] = pending.pop()!; + if (k === segments.length) { + if (--budget.checks < 0) return "exhausted"; + if (reaches(base)) return true; + continue; + } + // zsh pattern flags (`(#i)settings.json`) make a segment a pattern even + // with no glob character left; the flag itself matches nothing. + const flagged = ZSH_GLOB_FLAG_RE.test(segments[k]); + const segment = flagged ? segments[k].replace(new RegExp(ZSH_GLOB_FLAG_RE.source, "g"), "") : segments[k]; + if (!flagged && !GLOB_METACHAR_RE.test(segment)) { + pending.push([join(base, segment), k + 1]); + continue; + } + // zsh's `***/` recurses too, following links. + if ((segment === "**" || segment === "***") && options.globstar) { + // Zero directories here, or one more and `**` again below it. + pending.push([base, k + 1]); + const entries = list(base); + if (entries === "exhausted") return "exhausted"; + for (const entry of entries ?? []) { + if (entry.dir && (options.dotglob || !entry.name.startsWith("."))) pending.push([join(base, entry.name), k]); + } + continue; + } + // An extended glob matches no more than a `*` in its place would: that + // superset is what is checked. + const pattern = options.nocaseglob ? segment.toLowerCase() : segment; + const atoms = globAtoms(pattern) ?? globAtoms(withExtglobsAsStars(pattern)); + if (!atoms) return "exhausted"; + const entries = list(base); + if (entries === "exhausted") return "exhausted"; + for (const entry of entries ?? []) { + if (entry.name.startsWith(".") && !segment.startsWith(".") && !options.dotglob) continue; + if (globSegmentMatches(atoms, options.nocaseglob ? entry.name.toLowerCase() : entry.name)) pending.push([join(base, entry.name), k + 1]); + } + } } - // PowerShell: Get-ChildItem Env: / dir env: / gci env: / ls env: - if (PS_CHILDITEM_ENV_RE.test(cmd)) { - return deny("Command reads environment variables via PowerShell"); + return false; +} +/** + * An assignment's value as the variable resolver reads it: its quotes off, + * and a single-quoted one with its `$`, backticks and backslashes escaped, + * because the shell expands nothing inside single quotes: `B='$A'` holds the + * text `$A`. + */ +function assignedValueText(raw: string): string { + const single = /^'([\s\S]*)'$/.exec(raw); + if (single) return single[1].replace(/[\\$`]/g, "\\$&"); + return raw.replace(/^"([\s\S]*)"$/, "$1"); +} +/** A shell word with one pair of outer quotes taken off, expansions left in. */ +function withoutOuterQuotes(word: string): string { + return word.replace(/^(["'])([\s\S]*)\1$/, "$2"); +} +/** + * What `printf FORMAT ARGS…` prints, for the conversions a path is made with: + * each `%…` takes the next argument, `%%` is a percent sign, escapes decode, + * and the format repeats while arguments remain. + */ +function printfOutput(format: string, args: readonly string[]): string { + const decoded = decodeAnsiC(format); + let k = 0; + const pass = (): string => decoded.replace(/%(%|[-+ #0]*[0-9]*(?:\.[0-9]+)?[A-Za-z])/g, (_, spec: string) => (spec === "%" ? "%" : (args[k++] ?? ""))); + let out = pass(); + for (let round = 0; round < 64 && k > 0 && k < args.length; round++) out += pass(); + return out; +} +/** + * What a command substitution prints, for the few commands whose output the + * text alone decides: `echo`, `printf`, `basename`, `dirname`, `cat <<< word`, + * and `readlink`/`realpath`, whose output is the path a link resolves to — + * here the link's own name, which the walk resolves itself. Null for anything + * else, which the walk reads as unknown. + */ +function simpleSubstitutionOutput(body: string): string | null { + const words = quoteAwareWords(body.trim()).map(withoutOuterQuotes); + const head = commandBasename(words[0] ?? ""); + const args = words.slice(1); + if (head === "echo") { + let k = 0; + let escapes = false; + for (; k < args.length && /^-[neE]+$/.test(args[k]); k++) escapes ||= args[k].includes("e"); + const text = args.slice(k).join(" "); + return escapes ? decodeAnsiC(text) : text; } - // PowerShell: [Environment]::GetEnvironmentVariable - if (DOTNET_GETENV_RE.test(cmd)) { - return deny("Command reads environment variable via .NET"); + if (head === "printf") return args.length > 0 && !args[0].startsWith("-") ? printfOutput(args[0], args.slice(1)) : null; + const operands = args.filter((a) => !a.startsWith("-")); + if (head === "basename" && operands.length >= 1) { + const name = operands[0].replace(/\/+$/, "").split("/").pop() ?? ""; + const suffix = operands[1]; + return suffix && name.endsWith(suffix) && name !== suffix ? name.slice(0, name.length - suffix.length) : name; } - // cmd: echo %VAR% - if (CMD_ECHO_ENV_RE.test(cmd)) { - return deny("Command echoes environment variable via cmd"); + if (head === "dirname" && operands.length >= 1) { + const trimmed = operands[0].replace(/\/+$/, ""); + const at = trimmed.lastIndexOf("/"); + return at === -1 ? "." : at === 0 ? "/" : trimmed.slice(0, at); } - return allow(); + if ((head === "readlink" || head === "realpath") && operands.length >= 1) return operands[operands.length - 1]; + if (head === "cat" && args[0] === "<<<" && args.length === 2) return args[1]; + return null; } - -function blockEnvFiles(ctx: PolicyContext): PolicyResult { - const cmd = getCommand(ctx); - const filePath = getFilePath(ctx); - - // Check file_path for Read/Write tools (match both / and \ path separators) - if (filePath && ENV_FILE_PATH_RE.test(filePath)) { - return deny("Access to .env file blocked"); - } - // Check Bash commands referencing .env files - if (ctx.toolName === "Bash" && ENV_CMD_RE.test(cmd)) { - return deny("Command references .env file"); - } - return allow(); -} - -/** - * True when a segment runs an elevation binary IN COMMAND POSITION. - * - * Anchored structurally rather than by token, for the reason `namesSelfPause` - * is: `SUDO_RE` required the literal token `sudo` at a command boundary, so - * **`/usr/bin/sudo rm -rf /` was ALLOWED** — a direct invocation, no - * obfuscation, one absolute path away from root on a `defaultEnabled` guard. - * Every other form the shell resolves before settling on the binary — prefix - * assignments, redirections, runners and their flags — is walked off first, and - * the comparison is on the BASENAME so a path cannot hide the name. - * - * `doas` is included because it is the same capability under a different name; - * a machine with `doas` installed and only `sudo` blocked is not blocked. - * - * This raises the bar; it does not close the class. `bash -c "sudo …"`, a - * variable (`S=sudo; $S …`) and base64-through-a-pipe all still reach root, - * because static inspection of one command string cannot follow them. Closing - * that properly needs enforcement below the shell, not a better regex. - */ +/** What a variable may hold, for `shellWordExpansionForms`: its values, null when unknown, or "complex". */ +type ShellVariableLookup = (name: string) => string[] | "complex" | null; +/** Thrown inside `shellWordExpansionForms` when a word's texts cannot be followed within the limits. */ +class ShellWordTooComplex extends Error {} +/** How many texts one word may stand for before it reads as built to evade. */ +const SHELL_WORD_FORMS_LIMIT = 4096; /** - * Split a command into per-segment TOKEN LISTS the way a shell reads it. - * - * Distinct from `shellSegments` below, which returns raw segment STRINGS and is - * what the deletion policies want. Named apart deliberately: defining a second - * `shellSegments` here shadowed that one, silently broke every `rm -rf` check, - * and disabled this matcher too — caught only because `tsc` reports duplicate - * implementations. - * - * Segmentation happens on the RAW string and skips separators inside quotes, - * which is the whole point: stripping quoting FIRST turns `\|` — a literal pipe - * in a grep alternation — into a real separator, so `grep "a\|sudo b"` parses - * as a command called `sudo` and gets denied. That is a common enough pattern - * that over-blocking it is worse than the evasion it would catch. + * The texts a shell word may become once its expansions run, as far as the + * command's own text says: `$NAME`, `${NAME}`, an array element, and the + * operators a destination is built with — a default (`${A:-cfg.json}`, `-`, + * `=`, `:=`), an alternate (`:+`, `+`), a prefix or suffix removed (`#`, `##`, + * `%`, `%%`), a replacement (`/`, `//`, `/#`, `/%`), a case change (`^^`, `,,`, + * `@U`, `@L`), a substring with literal bounds, a length, an indirection + * (`${!R}`), quoting and `$'…'`. * - * Each token is unquoted individually afterwards, which still defeats `\sudo` - * and `"sudo"` without ever letting quote removal change where the boundaries - * are. Quoted tokens are returned separately so a caller can decide whether - * their CONTENTS deserve a second look — see `EVAL_FLAG_RE`. + * Only what the text gives is a text: a variable `lookup` cannot know (one the + * environment sets), a command substitution, a positional parameter add + * nothing, so a word made only of those has no texts at all. "complex" is a + * KNOWN value put through an operator this does not follow, or texts past the + * limits — what only a crafted command builds. Pattern matching runs on the + * no-backtracking glob walk, under `budget`, which every word of one command + * shares. */ -function quoteAwareSegments(command: string): Array { - const segments: Array = []; - let tokens: string[] = []; - let token = ""; - let quote: '"' | "'" | null = null; - const endToken = () => { - if (token) tokens.push(token); - token = ""; +function shellWordExpansionForms( + word: string, + lookup: ShellVariableLookup, + budget: { steps: number }, + /** No text longer: past it the word was built to grow. The walk passes its command's length. */ + maxLength = Math.max(4096, word.length), +): string[] | "complex" { + const product = (left: readonly string[], right: readonly string[]): string[] => { + if (left.length * right.length > SHELL_WORD_FORMS_LIMIT) throw new ShellWordTooComplex(); + const out: string[] = []; + for (const l of left) { + for (const r of right) { + if (l.length + r.length > maxLength) throw new ShellWordTooComplex(); + out.push(l + r); + } + } + return out; }; - const endSegment = () => { - endToken(); - if (tokens.length) segments.push(tokens); - tokens = []; + const union = (lists: ReadonlyArray): string[] => { + const out = [...new Set(lists.flat())]; + if (out.length > SHELL_WORD_FORMS_LIMIT) throw new ShellWordTooComplex(); + return out; }; - for (let i = 0; i < command.length; i++) { - const c = command[i]; - if (quote) { - // Inside single quotes a backslash is literal; inside double quotes it escapes. - if (c === "\\" && quote === '"' && i + 1 < command.length) { - token += command[++i]; - continue; + const valuesOf = (name: string): string[] => { + const values = lookup(name); + if (values === "complex") throw new ShellWordTooComplex(); + return values ?? []; + }; + // Where the `}` closing a `${` whose body starts at `from` is, past nested + // expansions, quotes and escapes; -1 when it is never closed. + const closeBrace = (s: string, from: number): number => { + let depth = 1; + for (let i = from; i < s.length; i++) { + const ch = s[i]; + if (ch === "\\") i++; + else if (ch === "'") { + const close = s.indexOf("'", i + 1); + if (close === -1) return -1; + i = close; + } else if (ch === "$" && s[i + 1] === "{") { + depth++; + i++; + } else if (ch === "}" && --depth === 0) return i; + } + return -1; + }; + // A pattern as glob atoms, or the literal it also reads as when quoted. + const glob = (pattern: string): GlobAtom[] => { + const atoms = globAtoms(pattern); + if (!atoms || atoms.length > 256) throw new ShellWordTooComplex(); + return atoms; + }; + const matches = (atoms: GlobAtom[], text: string): boolean => { + budget.steps -= (atoms.length + 1) * (text.length + 1); + if (budget.steps < 0) throw new ShellWordTooComplex(); + return globSegmentMatches(atoms, text); + }; + // `${v#p}`, `${v##p}`, `${v%p}`, `${v%%p}`: the shortest or longest match removed. + const removeAffix = (value: string, pattern: string, fromEnd: boolean, longest: boolean): string[] => { + // A quoted pattern is literal: `${v%"*"}` removes a star. + let literal = value; + if (fromEnd && value.endsWith(pattern)) literal = value.slice(0, value.length - pattern.length); + else if (!fromEnd && value.startsWith(pattern)) literal = value.slice(pattern.length); + if (!/[*?[]/.test(pattern)) return [literal]; + const atoms = glob(pattern); + const star: GlobAtom = { kind: "star" }; + // When no prefix (suffix) matches at all, one walk says so. + if (!matches(fromEnd ? [star, ...atoms] : [...atoms, star], value)) return [value, literal]; + // A pattern with no `*` matches one length only, so there is one cut to try. + const fixed = atoms.every((atom) => atom.kind !== "star") ? atoms.length : -1; + const cuts = + fixed === -1 + ? Array.from({ length: value.length + 1 }, (_, i) => i) + : fixed <= value.length + ? [fromEnd ? value.length - fixed : fixed] + : []; + const order = fromEnd === longest ? cuts : cuts.reverse(); + let globbed = value; + for (const cut of order) { + const piece = fromEnd ? value.slice(cut) : value.slice(0, cut); + if (matches(atoms, piece)) { + globbed = fromEnd ? value.slice(0, cut) : value.slice(cut); + break; } - if (c === quote) { - quote = null; + } + return [globbed, literal]; + }; + // `${v/p/r}`, `//` every match, `/#` at the start, `/%` at the end: the longest match at each place. + const replaceMatches = (value: string, pattern: string, replacement: string, mode: "first" | "all" | "prefix" | "suffix"): string[] => { + // An empty pattern changes nothing, except where it is anchored. + if (pattern === "") return [mode === "prefix" ? replacement + value : mode === "suffix" ? value + replacement : value]; + // A quoted pattern is literal; one with no glob characters is only that. + let literal = value; + if (mode === "all") { + if (value.split(pattern).length * (replacement.length + 1) > maxLength + value.length) throw new ShellWordTooComplex(); + literal = value.split(pattern).join(replacement); + } + else if (mode === "prefix") literal = value.startsWith(pattern) ? replacement + value.slice(pattern.length) : value; + else if (mode === "suffix") literal = value.endsWith(pattern) ? value.slice(0, value.length - pattern.length) + replacement : value; + else if (value.includes(pattern)) { + const at = value.indexOf(pattern); + literal = value.slice(0, at) + replacement + value.slice(at + pattern.length); + } + if (!/[*?[]/.test(pattern)) return [literal]; + const atoms = glob(pattern); + const star: GlobAtom = { kind: "star" }; + // No match anywhere: one walk, not one per place. And at each place, one + // walk first to ask whether any match starts there. + if (!matches([star, ...atoms, star], value)) return [value, literal]; + const startsHere = [...atoms, star]; + const fixed = atoms.every((atom) => atom.kind !== "star") ? atoms.length : -1; + let out = ""; + let replaced = false; + for (let i = 0; i <= value.length; ) { + let end = -1; + if ((mode === "all" || !replaced) && (mode !== "prefix" || i === 0) && (fixed !== -1 || matches(startsHere, value.slice(i)))) { + // The longest match starting here; one length only without a `*`. + const longest = fixed === -1 ? value.length : Math.min(value.length, i + fixed); + const shortest = fixed === -1 ? i + 1 : i + fixed; + for (let e = longest; e >= shortest && e > i; e--) { + if ((mode !== "suffix" || e === value.length) && matches(atoms, value.slice(i, e))) { + end = e; + break; + } + if (mode === "suffix") break; + } + } + if (end !== -1) { + out += replacement; + if (out.length > maxLength) throw new ShellWordTooComplex(); + replaced = true; + i = end; continue; } - token += c; - continue; + if (i < value.length) out += value[i]; + i++; } - if (c === "\\" && i + 1 < command.length) { - // An escaped character is literal — `\sudo` is still sudo, and `\|` is a - // pipe CHARACTER rather than a separator. - token += command[++i]; - continue; + return [out, literal]; + }; + const changeCase = (value: string, op: string): string => { + if (op === "^^" || op === "U") return value.toUpperCase(); + if (op === ",," || op === "L") return value.toLowerCase(); + if (op === "^" || op === "u") return value.charAt(0).toUpperCase() + value.slice(1); + if (op === ",") return value.charAt(0).toLowerCase() + value.slice(1); + const toggle = (c: string): string => (c === c.toUpperCase() ? c.toLowerCase() : c.toUpperCase()); + return op === "~" ? toggle(value.charAt(0)) + value.slice(1) : [...value].map(toggle).join(""); + }; + const substring = (value: string, offset: number, length: number | undefined): string => { + const start = offset < 0 ? Math.max(0, value.length + offset) : Math.min(offset, value.length); + if (length === undefined) return value.slice(start); + const end = length < 0 ? value.length + length : start + length; + return end < start ? "" : value.slice(start, end); + }; + // The first `/` of a replacement that is not escaped or inside an expansion. + const separatorAt = (s: string): number => { + for (let i = 0; i < s.length; i++) { + if (s[i] === "\\") i++; + else if (s[i] === "$" && s[i + 1] === "{") { + const close = closeBrace(s, i + 2); + if (close === -1) return -1; + i = close; + } else if (s[i] === "/") return i; } - if (c === '"' || c === "'") { - quote = c; - continue; + return -1; + }; + const braced = (body: string, depth: number): string[] => { + let m = /^#([A-Za-z_][A-Za-z0-9_]*)(?:\[[^\]]*\])?$/.exec(body); + if (m) return union([valuesOf(m[1]).map((value) => String(value.length))]); + if (body.startsWith("#")) return []; + m = /^!([A-Za-z_][A-Za-z0-9_]*)$/.exec(body); + if (m) return union(valuesOf(m[1]).map((name) => (/^[A-Za-z_][A-Za-z0-9_]*$/.test(name) ? valuesOf(name) : []))); + if (body.startsWith("!")) return []; + m = /^(?:([A-Za-z_][A-Za-z0-9_]*)|[0-9]+|[@*?$!-])(?:\[[^\]]*\])?/.exec(body); + if (!m) return []; + const values = m[1] === undefined ? [] : valuesOf(m[1]); + const rest = body.slice(m[0].length); + if (rest === "") return values; + const alternate = /^:?([-=+?])/.exec(rest); + if (alternate) { + const word = expand(rest.slice(alternate[0].length), depth + 1); + if (alternate[1] === "+") return union([[""], word]); + return alternate[1] === "?" ? values : union([values, word]); } - if (/\s/.test(c)) { - endToken(); - continue; + // Every operator below changes a value; with none known there is nothing to change. + if (values.length === 0) return []; + const affix = /^(##?|%%?)/.exec(rest); + if (affix) { + const fromEnd = affix[1][0] === "%"; + const patterns = expand(rest.slice(affix[1].length), depth + 1); + // A pattern the text does not give may remove any suffix (or prefix): + // every cut of a short value is a candidate. + if (patterns.length === 0) { + return union(values.map((value) => Array.from({ length: value.length + 1 }, (_, k) => (fromEnd ? value.slice(0, k) : value.slice(k))))); + } + return union(values.flatMap((value) => patterns.map((p) => removeAffix(value, p, fromEnd, affix[1].length === 2)))); } - if (/[;&|\n\r(){}`]/.test(c)) { - endSegment(); - continue; + if (rest.startsWith("/")) { + const mode = rest[1] === "/" ? "all" : rest[1] === "#" ? "prefix" : rest[1] === "%" ? "suffix" : "first"; + const spec = rest.slice(mode === "first" ? 1 : 2); + const at = separatorAt(spec); + const patterns = expand(at === -1 ? spec : spec.slice(0, at), depth + 1); + const replacements = expand(at === -1 ? "" : spec.slice(at + 1), depth + 1); + if (patterns.length === 0 || replacements.length === 0) throw new ShellWordTooComplex(); + return union(values.flatMap((value) => patterns.flatMap((p) => replacements.map((r) => replaceMatches(value, p, r, mode))))); } - token += c; + const caseChange = /^(\^\^|\^|,,|,|~~|~)$/.exec(rest) ?? /^@([ULu])$/.exec(rest); + if (caseChange) return union([values.map((value) => changeCase(value, caseChange[1]))]); + if (rest === "@E") return union([values.map((value) => decodeAnsiC(value))]); + if (rest === "@Q" || rest === "@a" || rest === "@A" || rest === "@K" || rest === "@k") return []; + const sub = /^:[ \t]*(-?[0-9]+)(?::[ \t]*(-?[0-9]+))?$/.exec(rest); + if (sub) { + const cut = values.map((value) => substring(value, Number(sub[1]), sub[2] === undefined ? undefined : Number(sub[2]))); + // On `[@]` or `[*]` it slices the array: its elements stay whole. + return /\[[@*]\]$/.test(m[0]) ? union([values, cut]) : union([cut]); + } + // An operator on a known value that this does not follow: offsets that are + // arithmetic, a case change limited to a pattern, a prompt expansion. + throw new ShellWordTooComplex(); + }; + const expand = (s: string, depth: number): string[] => { + if (depth > 8) throw new ShellWordTooComplex(); + let forms: string[] = [""]; + let literal = ""; + let inDouble = false; + const take = (next: readonly string[]): void => { + forms = product(product(forms, [literal]), next); + literal = ""; + }; + for (let i = 0; i < s.length; i++) { + const ch = s[i]; + if (ch === "\\") { + if (i + 1 < s.length) { + const next = s[++i]; + if (inDouble && !/[$`"\\\n]/.test(next)) literal += "\\"; + if (next !== "\n") literal += next; + } + } else if (ch === "'" && !inDouble) { + const close = s.indexOf("'", i + 1); + const stop = close === -1 ? s.length : close; + literal += s.slice(i + 1, stop); + i = stop; + } else if (ch === '"') { + inDouble = !inDouble; + } else if (ch === "`") { + return []; + } else if (ch === "$" && s[i + 1] === "'" && !inDouble) { + let j = i + 2; + let body = ""; + for (; j < s.length && s[j] !== "'"; j++) { + if (s[j] === "\\" && j + 1 < s.length) body += s[j++]; + body += s[j]; + } + literal += decodeAnsiC(body); + i = j; + } else if (ch === "$" && s[i + 1] === "(") { + return []; + } else if (ch === "$" && s[i + 1] === "{") { + // Unclosed, it runs to the end: the walk's command words come with + // their outer braces stripped (`"${A:-x}"` arrives as `${A:-x`), and + // a word really left open is a syntax error that writes nothing. + const close = closeBrace(s, i + 2); + const end = close === -1 ? s.length : close; + take(braced(s.slice(i + 2, end), depth)); + i = end; + } else if (ch === "$" && /[A-Za-z_]/.test(s[i + 1] ?? "")) { + let j = i + 1; + while (j < s.length && /[A-Za-z0-9_]/.test(s[j])) j++; + take(valuesOf(s.slice(i + 1, j))); + i = j - 1; + } else if (ch === "$" && /[0-9@*#?!$-]/.test(s[i + 1] ?? "")) { + return []; + } else { + literal += ch; + } + } + return product(forms, [literal]); + }; + try { + return expand(word, 0); + } catch (error) { + if (error instanceof ShellWordTooComplex) return "complex"; + throw error; } - endSegment(); - return segments; } - -/** `-c` and friends: the flags whose ARGUMENT is a command, not data. */ -const EVAL_FLAG_RE = /^-{1,2}c$/; - /** - * True when a command runs an elevation binary IN COMMAND POSITION. + * True when `command` would delete, move or overwrite the target — written for + * failproofai's own state, which is what the examples below are about. * - * Anchored structurally rather than by token, for the reason `namesSelfPause` - * is: `SUDO_RE` required the literal token `sudo` at a command boundary, so - * **`/usr/bin/sudo rm -rf /` was ALLOWED** — a direct invocation, no - * obfuscation, one absolute path away from root on a `defaultEnabled` guard. - * Every other form the shell resolves before settling on the binary — prefix - * assignments, redirections, runners and their flags — is walked off first, and - * the comparison is on the BASENAME so a path cannot hide the name. + * Deleting the state IS disabling enforcement, and it never names the binary: + * `rm ~/.failproofai/policies/packs/installed.json` switches off every pack + * policy on the machine, and fail-closed does NOT fire, because a missing store + * reads as a fresh machine rather than a broken one — so nothing anywhere + * reports it. * - * `doas` is included because it is the same capability under a different name; - * a machine with `doas` installed and only `sudo` blocked is not blocked. + * Two things carry the path into a command that never spells it, and both were + * live bypasses of the per-segment version: * - * A quoted argument is re-examined ONLY when the command that owns it is a - * shell runner invoked with an eval flag (`bash -c "sudo …"`). That distinction - * is load-bearing: `bash -c "sudo x"` and `grep "a|sudo x"` are identical from - * the outside, and the only thing separating an execution from a search string - * is whether the receiving binary evaluates its argument. + * - `cd ~/.failproofai && rm -rf .` — the path is an argument of `cd`, and the + * destroying command names only `.` + * - `D=~/.failproofai; rm -rf $D` — the path is a value, and the destroying + * command names only `$D` * - * This raises the bar; it does not close the class. A variable (`S=sudo; $S …`), - * base64 through a pipe, and a wrapper script on disk all still reach root, - * because static inspection of one command string cannot follow them. Closing - * that properly needs enforcement below the shell, not a better matcher. + * So the walk is stateful: it remembers which variables hold the path, whether + * the shell has been moved INTO the directory, and — where it can tell — which + * directory the shell stands in, so a relative destination + * (`cd ~/.failproofai && cp /dev/null policies-config.json`) is read as the path + * it is. What it does NOT do is treat every later command as suspect — + * `cat ~/.failproofai/config.json && rm /tmp/scratch` has to stay allowed, and + * does, because nothing in the second command reaches the state. */ -function namesElevation(command: string, depth = 0): boolean { - for (const tokens of quoteAwareSegments(command)) { - let i = 0; - while (i < tokens.length) { - const token = tokens[i]; - const base = token.slice(token.lastIndexOf("/") + 1); - // `sudo`/`doas` are themselves in COMMAND_PREFIX_TOKENS (they legitimately - // stand in front of another binary), so they must be tested BEFORE the - // skip list or the walk would step straight over the thing being looked for. - if (base === "sudo" || base === "doas") return true; - const isSkippable = - ENV_ASSIGNMENT_RE.test(token) || - token.startsWith("-") || - token.startsWith(">") || - token.startsWith("<") || - RUNNER_OPERAND_RE.test(token) || - COMMAND_PREFIX_TOKENS.has(base); - if (!isSkippable) break; - // `sh -c "…"` / `bash -c "…"`: the next token is a COMMAND. Bounded - // recursion so a nested `bash -c "bash -c …"` cannot spin. - if (EVAL_FLAG_RE.test(token) && depth < 3 && i + 1 < tokens.length) { - if (namesElevation(tokens[i + 1], depth + 1)) return true; - } - i++; +function destroysProtectedPath( + command: string, + target: ProtectedPathTarget, + depth = 0, + /** The text `command` was shell-unescaped from, when it is such a text (the unescaped pass). */ + unescapedFrom?: string, +): boolean { + const lexed = lexShell(command, depth > 0); + const unescapedPass = unescapedFrom !== undefined; + + // A substitution runs its body as a command of its own, so it is judged as + // one — `echo $(rm -rf ~/.failproofai)` otherwise presents `echo` as the head + // and walks straight through. Bounded, because a body can contain another. + // Breadth-first with a budget rather than depth-limited recursion: a nest + // deeper than the limit is trivial to write (`echo $(echo $(… rm …))`), and + // every level of it presents `echo` as the head. The budget is what bounds + // the work instead, because siblings multiply where depth does not. + // + // Not on a text whose quotes and backslashes are already gone + // (`unescapedPass`): there an escaped backtick in a commit message reads as a + // substitution. Each body is judged raw AND unescaped here instead, so a + // quote-broken path inside one (`$(rm ~/.claude/"settings.json")`) is caught. + if (depth === 0 && !unescapedPass) { + const bodies = substitutionBodies(lexed.substitutionSource); + for (let i = 0; i < bodies.length && i < MAX_SUBSTITUTION_BODIES; i++) { + // Judged where it runs: after the commands before it on the line, so a + // `cd` there moves it too (`cd sub; echo "$(cp x cfg.json)"`; found by + // hermes on #1053). + const before = commandsBefore(command, bodies[i]); + const body = before === "" ? bodies[i] : `${before}; ${bodies[i]}`; + if (destroysProtectedPath(body, target, 1)) return true; + const unescapedBody = stripShellQuoting(body); + if (unescapedBody !== body && destroysProtectedPath(unescapedBody, target, 1, body)) return true; + bodies.push(...substitutionBodies(lexShell(bodies[i], true).substitutionSource)); } + // More bodies than are read: the rest are refused, not skipped (found by hermes on #1053). + if (bodies.length > MAX_SUBSTITUTION_BODIES) return true; } - return false; -} -function blockSudo(ctx: PolicyContext): PolicyResult { - if (ctx.toolName !== "Bash") return allow(); - const cmd = getCommand(ctx).trimStart(); - // ONE pass. `shellSegments` unquotes each token individually, so `\sudo` and - // `"sudo"` are still caught — without a whole-string strip, which is what - // turned an escaped pipe in `grep "a\|sudo b"` into a segment separator and - // denied an ordinary search. - if (namesElevation(cmd)) { - // Check allowPatterns — match against parsed tokens, not raw string - const allowPatterns = ((ctx.params?.allowPatterns ?? []) as string[]); - if (allowPatterns.some((p) => matchesAllowedPattern(cmd, p))) return allow(); - return deny("sudo commands are blocked"); + // Variables that hold the path. The scan used to ask only whether a value + // CONTAINED the path, which caught `D=~/.failproofai; rm -rf $D` and missed + // `A=~/.failproofai; B=$A; rm -rf $B` — the second hop names no path at all, + // only the first variable. So a value referencing a known state variable + // counts too. Repeating to a fixpoint costs four lines and makes the result + // independent of the order the assignments appear in, rather than resting on + // a shell evaluating them top to bottom. + // + // A text whose quotes are already gone reads `B='$A'` as `B=$A`, a reference + // the command never makes. So the unescaped pass reads its variables from + // the same text unescaped with what the shell would not expand kept escaped. + // It still reads them: a value that starts with a quoted piece + // (`D="$HOME"/.claude/settings.json`, `A='cfg'.json`) is whole only there. + const assignmentText = + unescapedFrom === undefined ? lexed.readable : lexShell(stripShellQuotingKeepingLiterals(unescapedFrom), depth > 0).readable; + const assignments: Array = [ + ...assignmentText.matchAll(/(?:^|[\s;&|(])(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=("[^"]*"|'[^']*'|[^\s;&|)(][^\s;&|)]*)/g), + ].map(([, name, value]) => [name, assignedValueText(value)] as const); + // `A+=x` appends to A, the way `A=${A}x` does; `A=(x y)` and `A+=(z)` give + // an array whose every element may be the one a reference reads. + for (const [, name, value] of assignmentText.matchAll(/(?:^|[\s;&|(])([A-Za-z_][A-Za-z0-9_]*)\+=("[^"]*"|'[^']*'|[^\s;&|)(][^\s;&|)]*)/g)) { + assignments.push([name, `\${${name}}${assignedValueText(value)}`]); } - // PowerShell: Start-Process -Verb RunAs (elevation) - if (PS_ELEVATION_RE.test(cmd)) { - return deny("Elevated process launch is blocked"); + for (const [, name, elements] of assignmentText.matchAll(/(?:^|[\s;&|(])([A-Za-z_][A-Za-z0-9_]*)\+?=\(([^()]*)\)/g)) { + for (const element of quoteAwareWords(elements).slice(0, 64)) assignments.push([name, assignedValueText(element)]); } - // Windows: runas command - if (RUNAS_RE.test(cmd)) { - return deny("runas elevation is blocked"); + // And the other ways a line gives a variable a value it writes out: a + // substitution whose output the text decides (`A=$(echo cfg.json)`), a + // `for`/`select` list, `read … <<< word`, `printf -v NAME FORMAT ARGS`, and + // a nameref (`declare -n R=A` reads A). + for (const [, name, body, ticked] of assignmentText.matchAll(/(?:^|[\s;&|(])([A-Za-z_][A-Za-z0-9_]*)=["']?(?:\$\(([^()]*)\)|`([^`]*)`)/g)) { + const output = simpleSubstitutionOutput(body ?? ticked ?? ""); + if (output !== null) assignments.push([name, output]); } - return allow(); -} - -/** - * A pause the agent can issue is not a guardrail. - * - * `failproofai config --pause` is a human affordance: you watched the agent get - * blocked, you judged the block wrong, you suspended enforcement for a bit. An - * agent that can run it turns every other policy advisory — it need only shell - * out once to switch them all off, and the pause even survives into later turns. - * - * This raises the bar rather than closing the class: an agent can still reach - * the same state obfuscated (base64, a wrapper script, an alias). Closing it - * properly means the pause cannot originate from a tool call at all — a - * dashboard action, or a daemon that accepts it only from a TTY. Until then, - * the honest description of this policy is "stops the obvious attempt". - * - * It is deliberately NOT redundant with `block-failproofai-commands`, which - * blocks the CLI far more broadly. That one anchors on a command boundary - * (`FAILPROOFAI_CLI_RE`), so `npx -y failproofai config --pause` does not match - * it — and being broad, it is a policy people plausibly switch off so agents - * can run `failproofai audit`. Neither gap should leave pausing reachable, so - * this stays narrow, matches the runner forms, and survives that one being off. - */ - -function blockCurlPipeSh(ctx: PolicyContext): PolicyResult { - if (ctx.toolName !== "Bash") return allow(); - const cmd = getCommand(ctx); - if (CURL_PIPE_SH_RE.test(cmd)) { - return deny("Piping downloads to shell is blocked"); + for (const [, name, list] of assignmentText.matchAll(/(?:^|[\s;&|(])(?:for|select)\s+([A-Za-z_][A-Za-z0-9_]*)\s+in\s+([^;\n]*?)\s*[;\n]\s*do(?=[\s;]|$)/g)) { + for (const word of quoteAwareWords(list).slice(0, 64)) assignments.push([name, assignedValueText(word)]); } - // PowerShell: iwr | iex, irm | iex, Invoke-WebRequest | Invoke-Expression - if (PS_WEB_PIPE_RE.test(cmd)) { - return deny("Piping downloads to Invoke-Expression is blocked"); + for (const [, options, here] of assignmentText.matchAll(/(?:^|[\s;&|(])read((?:[ \t]+[^\s;&|<>]+)*?)[ \t]*<<<[ \t]*("[^"]*"|'[^']*'|[^\s;&|)]+)/g)) { + const value = withoutOuterQuotes(here); + const tokens = options.trim().split(/\s+/).filter(Boolean); + const names: string[] = []; + for (let k = 0; k < tokens.length; k++) { + if (/^-[adinNptu]$/.test(tokens[k])) { + if (tokens[k] === "-a" && tokens[k + 1]) names.push(tokens[k + 1]); + k++; + } else if (!tokens[k].startsWith("-")) names.push(tokens[k]); + } + for (const name of names.length > 0 ? names : ["REPLY"]) { + if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) continue; + assignments.push([name, value]); + for (const field of value.split(/\s+/).filter(Boolean).slice(0, 32)) assignments.push([name, field]); + } } - return allow(); -} - -function extractGitPushArgs(cmd: string): string[] { - return cmd - .split(/&&|\|\||[|;\n]/) - .map((s) => s.trim()) - .filter((s) => /^git\s+push\s/.test(s)) - .map((s) => s.replace(/^git\s+push\s+/, "")); -} - -function blockPushMaster(ctx: PolicyContext): PolicyResult { - if (ctx.toolName !== "Bash") return allow(); - const protectedBranches = ((ctx.params?.protectedBranches ?? ["main", "master"]) as string[]); - if (protectedBranches.length === 0) return allow(); - const args = extractGitPushArgs(getCommand(ctx)); - const branchPattern = new RegExp(`\\b(?:${protectedBranches.map((b) => b.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|")})\\b`); - if (args.some((a) => branchPattern.test(a))) { - return deny(`Pushing to ${protectedBranches.join("/")} is blocked`); + for (const [, name, rest] of assignmentText.matchAll(/(?:^|[\s;&|(])printf[ \t]+-v[ \t]*([A-Za-z_][A-Za-z0-9_]*)[ \t]+([^;&|\n]*)/g)) { + const [format = "", ...args] = quoteAwareWords(rest).map(withoutOuterQuotes); + assignments.push([name, printfOutput(format, args)]); + } + for (const [, flags, rest] of assignmentText.matchAll(/(?:^|[\s;&|(])(?:declare|local|typeset)((?:[ \t]+-[A-Za-z]+)+)[ \t]+([^;&|\n]*)/g)) { + if (!flags.includes("n")) continue; + for (const [, name, ref] of rest.matchAll(/([A-Za-z_][A-Za-z0-9_]*)=([A-Za-z_][A-Za-z0-9_]*)/g)) assignments.push([name, `\${${ref}}`]); + } + const stateVars = new Set(); + const assignedValues = new Map(); + // A variable given more values than are kept is not known: the value that + // matters may be one that was dropped. + const overflowed = new Set(); + for (const [name, value] of assignments) { + const list = assignedValues.get(name) ?? []; + if (list.length < 64) list.push(value); + else overflowed.add(name); + assignedValues.set(name, list); + } + // A variable's values with the variables inside them resolved too + // (`A=cfg.json; D=$A`), each variable once, however long the chain. A + // variable named in its own value is its earlier value, the shell's append + // (`F=ho; F=${F}oks` is `hooks`; `PATH=$PATH:/x` extends an environment + // value, which is unknown). Any assignment on the line may or may not have + // run where the variable is used, so a value that cannot be known (a command + // substitution) adds nothing but takes no known value away: + // `A=cfg.json; A=$(true); cp x "$A"` may still write cfg.json. COMPLEX is + // what only a crafted command builds — a cycle between variables, more + // values than are kept, too many combinations, a value grown longer than + // any path — and counts as naming the target; UNKNOWN (null: no known value + // at all) does not, like any environment variable. Both limits are checked + // before each value is made, never after a list is built: twenty-four + // appends double the values twenty-four times. + const MAX_VALUES = 64; + const MAX_VALUE_LENGTH = 4096; + const COMPLEX = "complex" as const; + type Resolved = string[] | typeof COMPLEX | null; + const resolved = new Map(); + const resolving = new Set(); + // One value with its expansions resolved the way the shell expands an + // assignment's value — references and parameter operators alike + // (`B=${A%.bak}`, `B=${A:-cfg.json}`) — `self` binding the variable's own + // name to its earlier value. Substitutions whose output the text decides + // were read as values of their own (simpleSubstitutionOutput). + const valueBudget = { steps: 4_000_000 }; + const expandValue = (value: string, name: string, self: string | undefined): Resolved => { + if (/`|\$\(/.test(value)) return null; + const forms = shellWordExpansionForms( + value, + (ref) => (ref === name ? (self === undefined ? null : [self]) : resolveVariable(ref)), + valueBudget, + Math.max(MAX_VALUE_LENGTH, value.length), + ); + if (forms === "complex") return COMPLEX; + return forms.length === 0 ? null : forms; + }; + const resolveVariable = (name: string): Resolved => { + if (resolved.has(name)) return resolved.get(name)!; + if (resolving.has(name) || resolving.size > 512) return COMPLEX; + const raw = assignedValues.get(name); + if (!raw || raw.length === 0) return null; + if (overflowed.has(name)) return COMPLEX; + resolving.add(name); + const out = knownValues(name, raw); + resolving.delete(name); + resolved.set(name, out); + return out; + }; + // The plain assignments' values, then each append applied to every value + // before it; COMPLEX the moment a value past the limit would be made. + const knownValues = (name: string, raw: readonly string[]): Resolved => { + // Its own name anywhere in a value, an operator's operand included (`A=${A%.bak}`). + const selfReference = new RegExp(`\\$(?:\\{[!#]?${name}(?![A-Za-z0-9_])|${name}(?![A-Za-z0-9_]))`); + const namesSelf = (value: string): boolean => selfReference.test(value); + const values = new Set(); + const keep = (forms: Resolved): boolean => { + if (forms === null) return true; + if (forms === COMPLEX) return false; + for (const form of forms) { + values.add(form); + if (values.size > MAX_VALUES) return false; + } + return true; + }; + // A value naming the variable itself is also what it gives while the + // variable is unset: `A=${A:-cfg.json}` is cfg.json, while `PATH=$PATH:/x` + // and `F=${F}oks` give nothing there. + for (const value of raw) { + if (!keep(expandValue(value, name, undefined))) return COMPLEX; + } + for (const value of raw) { + if (!namesSelf(value)) continue; + for (const previous of [...values]) { + if (!keep(expandValue(value, name, previous))) return COMPLEX; + } + } + return values.size === 0 ? null : [...values]; + }; + const resolvedValues = (name: string): string[] | null => { + const values = resolveVariable(name); + return values === COMPLEX ? null : values; + }; + // The texts a word built by expansions may become (shellWordExpansionForms), + // each word once, under one budget for the whole command. + const wordForms = new Map(); + const expansionBudget = { steps: 4_000_000 }; + const formsOfWord = (word: string): string[] | typeof COMPLEX => { + let forms = wordForms.get(word); + if (forms === undefined) { + const found = shellWordExpansionForms(word, resolveVariable, expansionBudget, Math.max(4096, command.length)); + forms = found === "complex" ? COMPLEX : found; + wordForms.set(word, forms); + } + return forms; + }; + // A word with expansions in it whose texts the command gives: those texts + // (`$D`, `"${D:-out}/x"`); null for anything else. + const valuesOfWord = (word: string): string[] | null => { + if (!word.includes("$")) return null; + const forms = formsOfWord(word); + return forms === COMPLEX || forms.length === 0 ? null : forms; + }; + for (let pass = 0; pass < assignments.length + 1; pass++) { + const before = stateVars.size; + for (const [name, value] of assignments) { + const holdsState = + target.namesLiteral(value) || + [...value.matchAll(VAR_REFERENCE_RE)].some(([, ref]) => stateVars.has(ref)) || + // A value that reaches the target where the session stands — through + // a link (`D=cfg.json`, `D=link/..`), or relative to it. + (target.namesThroughLinks?.(value, target.cwd) ?? false) || + (target.cwd !== undefined && isRelativeShellWord(value) && target.namesLiteral(resolve(target.cwd, value))); + if (holdsState) stateVars.add(name); + } + if (stateVars.size === before) break; } - return allow(); -} -// -- block-rm-rf: deletion-target resolution -- + // Where the shell may stand, as far as the text says: one directory, or a + // few when a `cd` may not have happened. Its directory may not exist, so it + // fails unless an earlier command makes it — `cd /nowhere; cp x settings.json` + // copies into the directory the shell already stood in — and the last + // command of a pipeline runs in the shell under zsh and not under bash. A + // relative word is judged against each of them; undefined is a place the + // text cannot name. `oldCwds` is OLDPWD for `cd -`, unknown until a `cd` + // sets it. `pushd` keeps where it left for `popd`, on a stack shared by + // reference, so a subshell can hand the parent's back. + let walkCwds: ReadonlyArray = [target.cwd]; + // Whether anything on the line may create a directory a later `cd` enters. + const lineMakesDirectories = /(?:^|[\s;&|(])(?:mkdir|install|git|cp|mv|rsync|tar|bsdtar|gtar|unzip|7z|ln|cpio|scp|wget|curl|npm|npx|pnpm|yarn|bun|pip|cargo|python[0-9.]*|node|perl|ruby|sh|bash|zsh|eval|source|xargs|find)(?=[\s;&|)]|$)|\$[({]|`/.test(command); + + let oldCwds: ReadonlyArray = [undefined]; + // Whether OLDPWD may still be the one from before this command, which could + // be anywhere, the target included. Once a `cd` on the line sets it, an + // unknown entry in it is where the session started (when that is not known) + // or a place the walk lost, and only the second counts. + let oldMayBeInitial = true; + type DirStack = { dirs: ReadonlyArray; below: DirStack } | null; + let dirStack: DirStack = null; + + // A word's glob verdict, once per walk: a command can repeat a word + // thousands of times (every `$NAME` is spliced to `*`), and each test runs + // it against every candidate and decoy. + const globVerdicts = new Map(); + const globNames = (word: string): boolean => { + let verdict = globVerdicts.get(word); + if (verdict === undefined) { + verdict = globCouldNameTarget(word, target); + globVerdicts.set(word, verdict); + } + return verdict; + }; -/** - * Leading shell forms that resolve to a home directory: `~`, `~user`, `$HOME`, - * `${HOME}`. The lookahead keeps `$HOMEBREW_PREFIX` (a variable this policy - * cannot resolve) from being mistaken for `$HOME`. - */ -const HOME_PREFIX_RE = /^(?:~[A-Za-z0-9_.-]*|\$HOME|\$\{HOME\})(?=$|\/)/; + // Whether one text a word may become reaches the target, judged as a word + // the shell hands over: by name, as a glob, through a link, relative to + // where the shell stands. + // A glob reaches what it expands to on disk: in a directory holding + // `cfg.json -> ~/.claude/settings.json`, `*.json` writes the settings. + const diskGlobs = new Map(); + const diskGlobBudget: DiskGlobBudget = { listings: new Map(), entries: 262_144, steps: 1_048_576, checks: 32_768 }; + // The options anywhere in the command that change what a glob matches: + // turned on in it, a glob after them may match more. The shell may be bash + // or zsh (Claude Code runs the user's, and zsh is macOS's default), so both + // spellings count. zsh ignores case and underscores in option names + // (`setopt GLOB_DOTS`), and its `**/` recurses with no option at all — + // where bash without globstar reads `**` as `*`, which matches less. + const globOptions = globOptionsOf(command); + // Each path a glob expands to, through links: `physical/../x` with + // `physical -> ~/.claude/subdir` is ~/.claude/x. By name too once the + // command turns a glob option on: what tells a sweep (`rm -rf ~/.*`, which + // stays allowed) from a pattern aimed at the target is the decoy test, and + // that reads a pattern under the default rules the command has just changed + // (`shopt -s dotglob; tee ~/*/settings.json`). + const globOptionsOn = globOptions.dotglob || globOptions.globstar || globOptions.nocaseglob; + const expandedReaches = (path: string): boolean => + (globOptionsOn && (target.namesLiteral(path) || target.namesLiteral(posix.normalize(path)))) || + target.namesThroughLinks!(path, undefined); + const globReachesThroughLinks = (glob: string): boolean => { + if (!target.namesThroughLinks) return false; + return walkCwds.some((cwd) => { + const key = `${cwd ?? ""}\0${glob}`; + let hit = diskGlobs.get(key); + if (hit === undefined) { + // Past the budget the command was built to stall the guard. + hit = globOnDiskReaches(glob, cwd, diskGlobBudget, globOptions, expandedReaches) !== false; + diskGlobs.set(key, hit); + } + return hit; + }); + }; + const formNamesTarget = (form: string): boolean => { + if (target.namesLiteral(form)) return true; + if ((GLOB_METACHAR_RE.test(form) || ZSH_GLOB_FLAG_RE.test(form)) && (globNames(form) || globReachesThroughLinks(form))) return true; + for (const cwd of walkCwds) { + if (target.namesThroughLinks?.(form, cwd)) return true; + if (cwd === undefined) continue; + if (isRelativeShellWord(form) && target.namesLiteral(resolve(cwd, form))) return true; + if (GLOB_METACHAR_RE.test(form) && !/^[-/~$]/.test(form) && globNames(resolve(cwd, form))) return true; + } + return false; + }; -/** `rm`, `/bin/rm`, `/usr/bin/rm`, … — the command word of a delete. */ -const RM_CMD_RE = /^(?:\/\S*\/)?rm$/; + const namesState = (text: string): boolean => { + if (target.namesLiteral(text)) return true; + // A word built by expansions, as each text the command says it may become: + // after `cd sub`, `"${A:-cfg.json}"` may be sub/cfg.json, and with + // `A=cfg.json.bak`, `"${A%.bak}"` is. + if (text.includes("$")) { + for (const word of quoteAwareWords(text)) { + if (!word.includes("$")) continue; + const forms = formsOfWord(word); + if (forms === COMPLEX) return true; + if (forms.some((form) => form !== word && formNamesTarget(form))) return true; + } + } + // A glob the shell expands — its glob characters outside quotes — as the + // paths it expands to. + if (target.namesThroughLinks && (GLOB_METACHAR_RE.test(text) || ZSH_GLOB_FLAG_RE.test(text))) { + for (const word of quoteAwareWords(text)) { + const unquoted = word.replace(/'[^']*'|"(?:[^"\\]|\\.)*"/g, ""); + if (/[$`]/.test(word) || !(GLOB_METACHAR_RE.test(unquoted) || ZSH_GLOB_FLAG_RE.test(unquoted))) continue; + if (globReachesThroughLinks(stripShellQuoting(word))) return true; + } + } + for (const [, name] of text.matchAll(VAR_REFERENCE_RE)) { + if (stateVars.has(name)) return true; + // Its value judged from where the shell stands where it is used: + // `cd sub; D=cfg.json; cp x "$D"` writes through sub/cfg.json. + if (resolveVariable(name) === COMPLEX) return true; + const values = resolvedValues(name); + if ( + values && + values.some( + (value) => + walkCwds.some( + (cwd) => + (target.namesThroughLinks?.(value, cwd) ?? false) || + (cwd !== undefined && isRelativeShellWord(value) && target.namesLiteral(resolve(cwd, value))), + ), + ) + ) { + return true; + } + } + // Per token, not over the whole text: a glob compiled from a whole command + // line matches nothing, and it is the individual operand — `~/.failproof*` + // — that would expand onto the state. Expansions are spliced first, so one + // holding a space (`settings$( true ).json`) stays inside its word. + const spliced = spliceWordExpansions(text); + // A quoted or escaped name with a space in it is ONE word to the shell: + // `> "my cfg.json"` writes through a link of that name. + if (target.namesThroughLinks && /["'\\]/.test(text)) { + for (const word of quoteAwareWords(text)) { + if (/\s/.test(word) && walkCwds.some((cwd) => target.namesThroughLinks!(word, cwd))) return true; + } + } + // And a word handed over whole with its quotes already off: an operand, + // `my cfg.json`. + const whole = text.trim(); + if (target.namesThroughLinks && /\s/.test(whole) && !/["'\\]/.test(whole) && whole.length <= 4096) { + if (walkCwds.some((cwd) => target.namesThroughLinks!(whole, cwd))) return true; + } + const here = walkCwds.filter((cwd): cwd is string => cwd !== undefined); + return spliced.split(/\s+/).some((token) => { + const word = unquotedToken(token); + if (globNames(word)) return true; + if (walkCwds.some((cwd) => target.namesThroughLinks?.(word, cwd))) return true; + // A relative word lands where the shell stands: `settings.json` after + // `cd ~/.claude`, `opencode` after `cd ~/.config`. Only words that could + // be one of the target's names, or `.`/`..` steps, are resolved: the + // rest cannot land on it, and resolving every word of a long line cost + // more than the whole walk. + for (const cwd of here) { + const cwdHinted = target.hint === undefined || target.hint.test(cwd); + for (const form of word.includes("=") ? [word, word.slice(word.indexOf("=") + 1)] : [word]) { + if (!isRelativeShellWord(form)) continue; + if (!cwdHinted && !target.hint!.test(form) && !/^\.{1,2}(?:\/\.{1,2})*\/?$/.test(form)) continue; + if (target.namesLiteral(resolve(cwd, form))) return true; + } + if (GLOB_METACHAR_RE.test(word) && !/^[-/~$]/.test(word) && globNames(resolve(cwd, word))) return true; + } + return false; + }); + }; -/** `find` expression that deletes: `-delete`, `-exec rm`, `-execdir rm`, `-ok rm`. */ -// Same shape as RM_CMD_RE: `find` is just as dangerous when invoked by -// absolute path (`/usr/bin/find / -delete`), so match both forms. -const FIND_CMD_RE = /^(?:\/\S*\/)?find$/; -const FIND_EXEC_RE = /^-(?:exec|execdir|ok|okdir)$/; + // Programs handed to an interpreter, judged whole (see INLINE_PROGRAM_RE). + // Found where the interpreter really is a command: through the comment and + // stored-text masks (`readable`), and only where its name is still there in + // `commandsOnly`, which also blanks what a command that is not a shell takes + // as a quoted argument — the example in `git commit -m 'Refuse python3 -c + // "…"'`. Line continuations become blanks of the same width, so an offset in + // one view is the same place in the other. + const namesProgram = (program: string): boolean => (target.namesProgram ?? target.namesLiteral)(program) || namesState(program); + const programText = lexed.readable.replace(/\\\r?\n/g, (joined) => " ".repeat(joined.length)); + for (const match of programText.matchAll(INLINE_PROGRAM_RE)) { + const at = match.index + (/^[\s;&|(\x60]/.test(match[0]) ? 1 : 0); + if (lexed.commandsOnly[at] !== programText[at]) continue; + if (namesProgram(match[1])) return true; + } + for (const body of lexed.programBodies) { + if (namesProgram(body)) return true; + } -/** find's global options, which precede its path operands (`find -L / -delete`). */ -const FIND_GLOBAL_OPT_RE = /^-(?:[HLP]|D|O\d*)$/; + let cwdInState = false; + // Whether the walk has lost track of where the shell stands because it may + // stand in too many places: a relative destination may then be anywhere, + // the target included, until a `cd` lands it somewhere known again. + let cwdLost = false; + // How deep in `( … )` the walk is. A `cd`, `pushd` or `popd` inside a + // subshell moves the subshell only, so where the shell stood — its + // directory, its `pushd` stack, and whether that was inside the target — + // comes back when the parenthesis closes: `(cd ~/.failproofai && cat x); rm + // -rf node_modules` was denying a cleanup in an entirely unrelated + // directory, and `(cd /tmp; pushd /tmp); popd` handed the parent a stack + // entry it never had. + let parenDepth = 0; + const cwdScopes: Array<{ + depth: number; + cwds: ReadonlyArray; + olds: ReadonlyArray; + inState: boolean; + lost: boolean; + dirs: DirStack; + }> = []; + // A loop header hands its word list to the body, and the body is a separate + // pipeline that names nothing. Without this, `for f in ~/.failproofai/*; do + // rm -rf $f; done` is a header that only expands and a body that only deletes + // something called `$f`. + let loopCarriesState = false; + // A destination after a `cd` into the target names it, even relative — and + // when the walk has lost track of where the shell stands, every relative + // destination counts: `cd $D && cp x policies-config.json`. + const namesHere = (text: string): boolean => + namesState(text) || + ((cwdInState || cwdLost) && walkCwds.includes(undefined) && (isRelativeShellWord(bareToken(text)) || isRelativeGlobWord(bareToken(text)))); + // The walk SPLITS the splittable text and READS the readable one: both keep + // every offset, so each piece of one is the same piece of the other. Comments + // and stored heredoc bodies are blank in both; separators inside a quoted + // argument are blank only in the first, so a sed or awk program still + // arrives with the separators and redirects it really has. + const { readable, splittable } = lexed; + for (const [pipelineStart, pipelineEnd] of cutRanges(splittable, PIPELINE_SEPARATORS)) { + const pipeline = readable.slice(pipelineStart, pipelineEnd); + const splitPipeline = splittable.slice(pipelineStart, pipelineEnd); + if (!pipeline.trim()) continue; + const reachesState = namesState(pipeline) || cwdInState || cwdLost || loopCarriesState; + if (reachesState && LOOP_HEADER_RE.test(splitPipeline)) loopCarriesState = true; + if (/(?:^|\s)done(?:\s|$)/.test(splitPipeline)) loopCarriesState = false; -/** First token of find's expression — everything before it is a path operand. */ -const FIND_EXPR_START_RE = /^(?:-|\\?[(!])/; + // A redirect is a write with no command in front of it — `> path` empties a + // file on its own. Only a redirect whose TARGET is the state counts: the + // previous version matched any `>` anywhere in the segment, so + // `grep -r sudo ~/.failproofai 2>/dev/null` and + // `cat ~/.failproofai/config.json > /tmp/backup.json` both denied, which is + // exactly the diagnosis this guard must not block. + if (reachesState) { + for (const [, redirected] of splitPipeline.matchAll(REDIRECT_TARGET_RE)) { + if (namesHere(redirected.replace(/^["']|["']$/g, ""))) return true; + } + } + const simples = cutRanges(splitPipeline, /\|/); + for (const [simpleIndex, [simpleStart, simpleEnd]] of simples.entries()) { + const simple = pipeline.slice(simpleStart, simpleEnd); + const splitSimple = splitPipeline.slice(simpleStart, simpleEnd); + parenDepth += (splitSimple.match(/\(/g) ?? []).length; + // A command substitution is one word however many spaces it holds: + // `cp x ~/.claude/settings$( true ).json` has three operands, not five. + const words = commandWords(spliceWordExpansions(blankRedirects(simple, splitSimple), true)); + const head = words.length > 0 ? commandBasename(words[0]) : ""; + // Track the shell's position before judging: a `cd` INTO the state makes + // every later relative path a state path, and a `cd` back out ends that. + if (head === "cd" || head === "pushd" || head === "popd") { + // Every command of a pipeline runs in a subshell, so one before a `|` + // moves nothing: `cd ~/.claude | cat; cp x settings.json` copies into + // the directory the shell already stood in. zsh runs the LAST command + // in the shell itself and bash does not, so after that one the shell + // may stand in either place. + if (simpleIndex === simples.length - 1) { + if (parenDepth > 0) cwdScopes.push({ depth: parenDepth, cwds: walkCwds, olds: oldCwds, inState: cwdInState, lost: cwdLost, dirs: dirStack }); + const before = walkCwds; + let after: ReadonlyArray = before; + let mayFail = false; + const stackWords = head === "cd" ? [] : quoteAwareCommandWords(simple).words.slice(1); + // `-n` changes the stack and leaves the shell where it is; `+N`/`-N` + // rotate the stack, so any entry of it may end up where the shell stands. + const stackOnly = stackWords.includes("-n"); + const rotation = stackWords.some((w) => /^[+-]\d+$/.test(w)); + const stackDirs = (): Array => { + const dirs: Array = []; + for (let entry = dirStack; entry !== null; entry = entry.below) dirs.push(...entry.dirs); + return dirs; + }; + if (head === "popd" && stackOnly) { + if (dirStack !== null) dirStack = dirStack.below; + } else if (rotation) { + // The stack's order after a rotation is not followed: every entry + // may now hold any of the directories, so every later `popd` may + // land on any of them. + const all = [...new Set([...before, ...stackDirs()])]; + let depth = 0; + for (let entry = dirStack; entry !== null; entry = entry.below) depth++; + dirStack = null; + for (let k = 0; k < depth; k++) dirStack = { dirs: all, below: dirStack }; + if (!stackOnly) after = all; + } else if (head === "popd") { + // `popd` returns to wherever the shell was before `pushd`, which + // ends the window as surely as a `cd` out does. Without it every + // command for the rest of the line was judged as if it stood in + // the state directory. On an empty stack it fails and the shell + // stays where it is. + if (dirStack !== null) { + cwdInState = false; + after = dirStack.dirs; + dirStack = dirStack.below; + } + } else if (head === "pushd" && !stackWords.some((w) => !w.startsWith("-") && !/^[+-]\d+$/.test(w))) { + // A bare `pushd` swaps the shell's directory with the top of the stack. + if (dirStack !== null) { + after = dirStack.dirs; + dirStack = { dirs: before, below: dirStack.below }; + } + } else { + const operands = quoteAwareCommandWords(simple).words.slice(1); + // Quote-aware, so `cd "$(dirname ~/.claude/settings.json)"` is one + // operand. A bare `-` is OLDPWD. + const operand = operands.find((w) => w === "-" || !w.startsWith("-")); + // `cd -P` follows links before `..`, the way the kernel walks: + // with `link -> ~/.claude/x`, `cd -P link/..` lands in ~/.claude. + const physical = head === "cd" && operands.some((w) => /^-[A-Za-z@]*P/.test(w)); + if (operand === "-") { + after = oldCwds; + // An OLDPWD from before this command could be anywhere, the target included. + cwdInState = + oldMayBeInitial || + (target.cwd !== undefined && oldCwds.includes(undefined)) || + oldCwds.some((dir) => dir !== undefined && namesState(dir)); + } else { + cwdInState = operand !== undefined && namesState(operand); + // An operand built by expansions moves the shell to each place + // its texts name (`D=sub; cd "$D"`), or somewhere unknown. + const operandForms = operand !== undefined && /[$`]/.test(operand) ? valuesOfWord(operand) : null; + const places: Array = operandForms ?? [operand]; + after = [ + ...new Set([ + ...before.flatMap((cwd) => + places.map((place) => + physical && place !== undefined && !/[$`]/.test(place) + ? physicalAgentPath(place, cwd) ?? cdDestination(cwd, place) + : cdDestination(cwd, place), + ), + ), + ...(operandForms ? [undefined] : []), + ]), + ]; + // failproofai's own state directory is there wherever this guard + // runs, so a `cd` into it does not fail (found by #1058's tests on + // #1053: `cd ~/.failproofai; …; cd -` returned to where it began). + const intoState = operand !== undefined && FAILPROOFAI_STATE_PATH_RE.test(operand) && !/[$`*?[]/.test(operand); + mayFail = !intoState && after.some((dir) => dir === undefined || !isDirectoryNow(dir)); + } + if (head === "pushd") { + if (stackOnly) { + // `pushd -n DIR` files DIR under the top and stays put. + dirStack = { dirs: after, below: dirStack }; + after = before; + mayFail = false; + } else { + dirStack = { dirs: before, below: dirStack }; + } + } + } + // A `cd` that fails leaves OLDPWD alone too: after `cd /missing`, + // `cd -` may still return to where an earlier `cd` left. + if (!mayFail && after !== before) oldMayBeInitial = false; + oldCwds = mayFail ? [...new Set([...before, ...oldCwds])] : after === before ? oldCwds : before; + walkCwds = [...new Set(mayFail || simples.length > 1 ? [...after, ...before] : after)]; + // Past a few places the walk stops naming them, and a relative + // destination may then be in any of them, the target included: from + // there on every one counts, until a `cd` lands somewhere known. + // A directory that is not there, and that nothing on the line can + // make, is one no `cd` reaches; past the limit those places go first, + // so `cd a && cd b && … && cd e` from a project without them is not + // 2^5 places (found by #1058's tests on #1053). The session's own + // directory always counts as there. + if (walkCwds.length > 16) { + walkCwds = walkCwds.filter( + (dir) => dir === undefined || dir === target.cwd || lineMakesDirectories || isDirectoryNow(dir), + ); + if (walkCwds.length === 0) walkCwds = [target.cwd]; + } + if (walkCwds.length > 16) { + cwdLost = true; + walkCwds = [undefined]; + } else if (walkCwds.every((dir) => dir !== undefined)) { + cwdLost = false; + } + } + } else if (reachesState && simpleIndex > 0 && quoteAwareCommandWords(simple).readsStdinProgram) { + // A bare shell or interpreter after a pipe runs the text piped into it: + // `echo 'rm -rf ~/.claude' | sh`. Whatever names the target upstream is + // its program. + return true; + } else if ((reachesState || (head === "git" && gitReachesTarget(quoteAwareCommandWords(simple).words, walkCwds, namesHere, valuesOfWord))) && words.length > 0) { + // `xargs` hands the paths on its stdin to the command after it, so a + // copy or a `tee` fed by `echo |` names its destination nowhere + // in its own words. Judged like `find -exec`: only a reader is safe. + // Read from the command's own words, not its quoted arguments. + if (quoteAwareCommandWords(simple).viaXargs && !SAFE_EXEC_COMMANDS.has(head)) return true; + // Judged BEFORE the closing parenthesis is counted: a `rm -rf ./*)` + // still runs inside the subshell it closes. + if (simpleCommandDestroys(words, namesHere, target, simple, cwdInState || cwdLost, walkCwds, valuesOfWord)) return true; + } + parenDepth -= (splitSimple.match(/\)/g) ?? []).length; + while (cwdScopes.length > 0 && parenDepth < cwdScopes[cwdScopes.length - 1].depth) { + const scope = cwdScopes.pop()!; + walkCwds = scope.cwds; + oldCwds = scope.olds; + cwdInState = scope.inState; + cwdLost = scope.lost; + dirStack = scope.dirs; + } + } + } + return false; +} +const FAILPROOFAI_UNINSTALL_RE = /(?:npm\s+(?:uninstall|remove|un|r)\s.*failproofai|bun\s+remove\s.*failproofai|yarn\s+global\s+remove\s+failproofai|pnpm\s+(?:remove|uninstall|un)\s.*failproofai)/; +// warnGitAmend +const GIT_AMEND_RE = /\bgit\s+commit\b.*--amend\b/; +// warnGitStashDrop +const GIT_STASH_DROP_RE = /\bgit\s+stash\s+(?:drop|clear)\b/; +// warnGitClean /** - * Roots that exist to hold throwaway data. A delete of the root itself is still - * catastrophic (`rm -rf /tmp` wipes every process's scratch space); a delete of - * something *inside* one is ordinary work. + * `git`, however the command line spells it. Same shape as {@link RM_CMD_RE}: + * an absolute path to the binary does not change what it does. */ -const SCRATCH_ROOTS = ["/tmp", "/var/tmp"]; - +const GIT_CMD_RE = /^(?:\/\S*\/)?git$/; +/** A short-flag cluster: `-f`, `-fdx`, `-xdf`. */ +const SHORT_FLAG_CLUSTER_RE = /^-[A-Za-z]+$/; /** - * How many path segments below a root (`/` or a home directory) a delete has to - * reach before it stops being catastrophic. `/etc` (1) and `/home/chetan` (2) - * are system- and user-level directories; `/home/chetan/project` (3) is a - * specific thing the caller meant to delete. + * `clean.requireForce=false`, the config that makes `git clean` delete with no + * `-f` at all — and settable per invocation as `git -c + * clean.requireForce=false clean -xd`. Reading the subcommand's flags alone + * would call that "no force, no warning" on the one spelling that needs none. */ -const CATASTROPHIC_DEPTH = 2; - -/** Expand the leading `~` / `$HOME` / `${HOME}` of a path to the real home directory. */ -function expandHomePrefix(path: string): string { - const m = path.match(/^(?:~|\$HOME|\$\{HOME\})(?=$|\/)/); - return m ? homedir() + path.slice(m[0].length) : path; -} - -/** Drop a trailing `/*` glob and any trailing slashes: `/tmp/foo/*` → `/tmp/foo`. */ -function stripTrailingGlob(path: string): string { - return path.replace(/\/\*$/, "").replace(/\/+$/, ""); -} - +const GIT_CLEAN_FORCE_WAIVED_RE = /^clean\.requireforce=(?:false|0|no|off)$/i; /** - * Would deleting this target be catastrophic? + * The default `destructiveFlags`, and why the condition is these three letters + * rather than "any `git clean`". * - * Rather than pattern-matching the raw command text, this resolves the token as - * far as the shell would: quotes are stripped, `~` / `$HOME` are recognised as a - * root in their own right, and the remaining path segments are counted. A target - * within {@link CATASTROPHIC_DEPTH} segments of either root (`/` or home) takes - * out the machine or the user's data. + * `git clean` deletes nothing without `-f` / `--force` (or the config above), + * and `-n` / `--dry-run` only prints — so force is the precondition and + * dry-run is the exemption. What force ALONE removes is untracked files in the + * current directory: the narrowest spelling, and the one people mean when they + * tidy up. These are the letters that widen the blast radius past that: * - * Fails safe: a token whose head is an expansion this policy cannot evaluate — - * command substitution (`$(…)`, backticks) or any variable other than `$HOME` — - * could expand to `/`, so it counts as catastrophic. Relative targets are not - * flagged: they resolve under the working directory, not under a root. - */ -function isCatastrophicTarget(token: string): boolean { - const raw = token.replace(/^['"]|['"]$/g, ""); - if (raw === "") return false; - - const homePrefix = raw.match(HOME_PREFIX_RE); - // Unresolvable head: `$(echo /)`, `` `pwd` ``, `$TARGET_DIR`, … - if (!homePrefix && /^[$`]/.test(raw)) return true; - - const belowRoot = homePrefix ? raw.slice(homePrefix[0].length) : raw.startsWith("/") ? raw : null; - if (belowRoot === null) return false; - - const segments = stripTrailingGlob(belowRoot).split("/").filter(Boolean); - if (!homePrefix && SCRATCH_ROOTS.some((r) => `/${segments.join("/")}`.startsWith(`${r}/`))) return false; - return segments.length <= CATASTROPHIC_DEPTH; -} - -/** - * The paths a single command segment would recursively delete, or `null` when the - * segment is not a recursive delete at all. + * - `-x` also removes IGNORED files — `.env`, local config, editor state, + * scratch work. That is the data that genuinely cannot be rebuilt by running + * a command, and it is what makes `git clean -fdx` the severe spelling. + * - `-X` removes ONLY ignored files: the same loss, tracked tree untouched. + * - `-d` also removes untracked DIRECTORIES — whole new subtrees git has never + * had a copy of. * - * Understands the two shapes that reach every file under a target: `rm` with both - * `-r` and `-f` (in any spelling or order), and `find`, which recurses by design, - * paired with `-delete` or an `-exec rm`. + * A bare `git clean -f` is deliberately absent. It has the smallest radius and + * by far the most traffic, and a guard that fires on the ordinary spelling is + * one people switch off — which would cost them the `-fdx` warning too. Add + * `"f"` to `destructiveFlags` to opt into it. */ -function recursiveDeletionTargets(seg: string): string[] | null { - const tokens = parseArgvTokens(seg); +const GIT_CLEAN_DESTRUCTIVE_FLAGS = ["d", "x", "X"]; +// warnAllFilesStaged +const GIT_ADD_ALL_RE = /\bgit\s+add\s+(?:-A\b|--all\b|\.(?:\s|$|;|&&|\|\|))/; +// warnGlobalPackageInstall +const NPM_GLOBAL_RE = /\bnpm\s+(?:install|i)\b(?=.*(?:\s-g\b|--global\b))/; +const YARN_GLOBAL_RE = /\byarn\s+global\s+add\b/; +const PNPM_GLOBAL_RE = /\bpnpm\s+(?:add|install|i)\b(?=.*(?:\s-g\b|--global\b))/; +const BUN_GLOBAL_RE = /\bbun\s+(?:install|add)\b(?=.*(?:\s-g\b|--global\b))/; +const CARGO_INSTALL_RE = /\bcargo\s+install\b/; +const PIP_SYSTEM_RE = /\bpip(?:3)?\s+install\b(?=.*(?:--user\b|--break-system-packages\b))/; +// preferPackageManager — maps manager name → detection patterns +const PKG_MANAGER_DETECTORS: Record = { + pip: [/\bpip\b/, /\bpip3\b/, /\bpython3?\s+-m\s+pip\b/], + npm: [/\bnpm\b/, /\bnpx\b/], + yarn: [/\byarn\b/], + pnpm: [/\bpnpm\b/, /\bpnpx\b/], + bun: [/\bbun\b/, /\bbunx\b/], + uv: [/\buv\b/], + poetry: [/\bpoetry\b/], + pipenv: [/\bpipenv\b/], + conda: [/\bconda\b/], + cargo: [/\bcargo\b/], +}; +// warnBackgroundProcess +const NOHUP_RE = /\bnohup\s+\S/; +const SCREEN_DETACH_RE = /\bscreen\s+-[A-Za-z]*d[A-Za-z]*\b/; +const TMUX_DETACH_RE = /\btmux\s+(?:new-session|new)\b[^|&;]*-d\b/; +const DISOWN_RE = /\bdisown\b/; +const BACKGROUND_AMPERSAND_RE = /(?(); +const GIT_BRANCH_CACHE_MAX_ENTRIES = 500; +function statGitHeadMtimeMs(cwd: string): number | null { + try { + return statSync(join(cwd, ".git", "HEAD")).mtimeMs; + } catch { + return null; + } +} +function getCurrentBranch(cwd: string): string | null { + try { + const headMtimeMs = statGitHeadMtimeMs(cwd); + const cached = gitBranchCache.get(cwd); + if (cached && headMtimeMs !== null && cached.headMtimeMs === headMtimeMs) { + return cached.branch || null; + } + const branch = execSync("git rev-parse --abbrev-ref HEAD", { + cwd, + encoding: "utf8", stdio: ["pipe", "pipe", "pipe"], + timeout: 3000, + }).trim(); + if (headMtimeMs !== null) { + if (gitBranchCache.size >= GIT_BRANCH_CACHE_MAX_ENTRIES) gitBranchCache.clear(); + gitBranchCache.set(cwd, { branch, headMtimeMs }); + } + return branch || null; + } catch { + return null; + } +} +function getHeadSha(cwd: string): string | null { + try { + const sha = execSync("git rev-parse HEAD", { + cwd, + encoding: "utf8", stdio: ["pipe", "pipe", "pipe"], + timeout: 3000, + }).trim(); + return sha || null; + } catch { + return null; + } +} +interface CiCheck { + name: string; + status: string; + conclusion: string; +} +/** Fetch third-party check runs (non-GitHub-Actions) for a commit via the Checks API. */ +function getThirdPartyCheckRuns(cwd: string, sha: string): CiCheck[] { + try { + const json = execFileSync( + "gh", + [ + "api", + `repos/{owner}/{repo}/commits/${sha}/check-runs`, + "--jq", + '.check_runs | map(select(.app.slug != "github-actions")) | map({name: .name, status: .status, conclusion: (.conclusion // "")})', + ], + { + cwd, + encoding: "utf8", stdio: ["pipe", "pipe", "pipe"], + timeout: 15000, + }, + ).trim(); + + if (!json || json === "[]") return []; + return JSON.parse(json) as CiCheck[]; + } catch { + return []; + } +} +/** Fetch commit statuses (legacy Status API) and normalize to CiCheck format. */ +function getCommitStatuses(cwd: string, sha: string): CiCheck[] { + try { + const json = execFileSync( + "gh", + [ + "api", + `repos/{owner}/{repo}/commits/${sha}/statuses`, + "--jq", + 'map({name: .context, state: .state}) | unique_by(.name)', + ], + { + cwd, + encoding: "utf8", stdio: ["pipe", "pipe", "pipe"], + timeout: 15000, + }, + ).trim(); + + if (!json || json === "[]") return []; + const statuses = JSON.parse(json) as Array<{ name: string; state: string }>; + return statuses.map((s) => ({ + name: s.name, + status: s.state === "pending" ? "in_progress" : "completed", + conclusion: s.state === "pending" ? "" : s.state === "success" ? "success" : "failure", + })); + } catch { + return []; + } +} +/** + * Check if a command matches an allow pattern using token-by-token comparison. + * The "*" token is a wildcard. Extra command tokens beyond the pattern are allowed, + * UNLESS any token is a standalone shell operator (&&, ||, |, ;) OR contains an + * embedded shell metacharacter — both cases are rejected to prevent bypass via + * appended sub-commands or glued operators (e.g. "nginx;" or "nginx;evil"). + */ +function matchesAllowedPattern(cmd: string, pattern: string): boolean { + const cmdTokens = parseArgvTokens(cmd); + const patTokens = parseArgvTokens(pattern); + if (cmdTokens.length < patTokens.length) return false; + // Reject commands containing standalone shell-operator tokens + if (cmdTokens.some((tok) => SHELL_OPERATORS.has(tok))) return false; + // Reject any token containing embedded shell metacharacters + if (cmdTokens.some((tok) => SHELL_METACHAR_RE.test(tok))) return false; + return patTokens.every((tok, i) => tok === "*" || tok === cmdTokens[i]); +} + +// -- Policy implementations -- +function sanitizeJwt(ctx: PolicyContext): PolicyResult { + // PostToolUse: scrub JWT patterns from tool output + const output = JSON.stringify(ctx.payload); + if (JWT_RE.test(output)) { + return { + decision: "deny", + reason: "JWT token detected in tool output", + message: "[REDACTED: JWT token removed by failproofai]", + }; + } + return allow(); +} +function sanitizeApiKeys(ctx: PolicyContext): PolicyResult { + // PostToolUse: scrub common API key patterns from tool output + const output = JSON.stringify(ctx.payload); + for (const [pattern, label] of API_KEY_PATTERNS) { + if (pattern.test(output)) { + return { + decision: "deny", + reason: `${label} detected in tool output`, + message: `[REDACTED: ${label} removed by failproofai]`, + }; + } + } + + // Check additional user-configured patterns + const additional = ((ctx.params?.additionalPatterns ?? []) as Array<{ regex: string; label: string }>); + for (const { regex, label } of additional) { + try { + if (new RegExp(regex).test(output)) { + return { + decision: "deny", + reason: `${label} detected in tool output`, + message: `[REDACTED: ${label} removed by failproofai]`, + }; + } + } catch { + hookLogWarn(`additionalPatterns: invalid regex "${regex}", skipping`); + } + } + + return allow(); +} +function sanitizeConnectionStrings(ctx: PolicyContext): PolicyResult { + // PostToolUse: scrub database connection strings with embedded credentials + const output = JSON.stringify(ctx.payload); + if (CONNECTION_STRING_RE.test(output)) { + return { + decision: "deny", + reason: "Database connection string with credentials detected in tool output", + message: "[REDACTED: connection string removed by failproofai]", + }; + } + return allow(); +} +function sanitizePrivateKeyContent(ctx: PolicyContext): PolicyResult { + // PostToolUse: scrub PEM private key blocks from tool output + const output = JSON.stringify(ctx.payload); + if (PRIVATE_KEY_RE.test(output)) { + return { + decision: "deny", + reason: "Private key content detected in tool output", + message: "[REDACTED: private key content removed by failproofai]", + }; + } + return allow(); +} +function sanitizeBearerTokens(ctx: PolicyContext): PolicyResult { + // PostToolUse: scrub Authorization: Bearer tokens from tool output + const output = JSON.stringify(ctx.payload); + if (BEARER_TOKEN_RE.test(output)) { + return { + decision: "deny", + reason: "Bearer token detected in tool output", + message: "[REDACTED: Bearer token removed by failproofai]", + }; + } + return allow(); +} +function warnDestructiveSql(ctx: PolicyContext): PolicyResult { + if (ctx.toolName !== "Bash") return allow(); + const cmd = getCommand(ctx); + if (!SQL_TOOL_RE.test(cmd)) return allow(); + + // DROP or TRUNCATE always warns + if (DESTRUCTIVE_SQL_RE.test(cmd)) { + return instruct( + "STOP: This command contains destructive SQL (DROP/TRUNCATE/DELETE). Confirm with the user before executing.", + ); + } + + // DELETE FROM without WHERE warns + if (DELETE_NO_WHERE_RE.test(cmd) && !SQL_WHERE_RE.test(cmd)) { + return instruct( + "STOP: This command contains destructive SQL (DROP/TRUNCATE/DELETE). Confirm with the user before executing.", + ); + } + + return allow(); +} +function warnLargeFileWrite(ctx: PolicyContext): PolicyResult { + if (ctx.toolName !== "Write") return allow(); + const content = ctx.toolInput?.content as string | undefined; + if (typeof content !== "string") return allow(); + const thresholdKb = ((ctx.params?.thresholdKb ?? 1024) as number); + const thresholdBytes = thresholdKb * 1024; + if (content.length > thresholdBytes) { + return instruct( + `STOP: You are writing a file larger than ${thresholdKb}KB (${Math.round(content.length / 1024)}KB). This is unusually large. Confirm this is intentional before proceeding.`, + ); + } + return allow(); +} +function warnPackagePublish(ctx: PolicyContext): PolicyResult { + if (ctx.toolName !== "Bash") return allow(); + const cmd = getCommand(ctx); + if (PUBLISH_CMD_RE.test(cmd)) { + return instruct( + "STOP: This command publishes a package to a public registry. Confirm with the user that this is intentional.", + ); + } + return allow(); +} +function protectEnvVars(ctx: PolicyContext): PolicyResult { + if (ctx.toolName !== "Bash") return allow(); + const cmd = getCommand(ctx); + // Block: env, printenv, echo $VAR, export VAR= + if (ENV_PRINTENV_RE.test(cmd)) { + return deny("Command reads environment variables"); + } + if (ECHO_ENV_RE.test(cmd)) { + return deny("Command echoes environment variable"); + } + if (EXPORT_RE.test(cmd)) { + return deny("Command exports environment variable"); + } + if (ENV_DUMP_RE.test(cmd) || (SCRIPT_INTERP_RE.test(cmd) && ENV_OBJECT_RE.test(cmd))) { + return deny("Command dumps environment variables"); + } + // PowerShell: $env:VAR + if (PS_ENV_VAR_RE.test(cmd)) { + return deny("Command reads environment variable via PowerShell"); + } + // PowerShell: Get-ChildItem Env: / dir env: / gci env: / ls env: + if (PS_CHILDITEM_ENV_RE.test(cmd)) { + return deny("Command reads environment variables via PowerShell"); + } + // PowerShell: [Environment]::GetEnvironmentVariable + if (DOTNET_GETENV_RE.test(cmd)) { + return deny("Command reads environment variable via .NET"); + } + // cmd: echo %VAR% + if (CMD_ECHO_ENV_RE.test(cmd)) { + return deny("Command echoes environment variable via cmd"); + } + return allow(); +} +function blockEnvFiles(ctx: PolicyContext): PolicyResult { + const cmd = getCommand(ctx); + const filePath = getFilePath(ctx); + + // Check file_path for Read/Write tools (match both / and \ path separators) + if (filePath && ENV_FILE_PATH_RE.test(filePath)) { + return deny("Access to .env file blocked"); + } + // Check Bash commands referencing .env files + if (ctx.toolName === "Bash" && ENV_CMD_RE.test(cmd)) { + return deny("Command references .env file"); + } + return allow(); +} +/** + * True when a segment runs an elevation binary IN COMMAND POSITION. + * + * Anchored structurally rather than by token, for the reason `namesSelfPause` + * is: `SUDO_RE` required the literal token `sudo` at a command boundary, so + * **`/usr/bin/sudo rm -rf /` was ALLOWED** — a direct invocation, no + * obfuscation, one absolute path away from root on a `defaultEnabled` guard. + * Every other form the shell resolves before settling on the binary — prefix + * assignments, redirections, runners and their flags — is walked off first, and + * the comparison is on the BASENAME so a path cannot hide the name. + * + * `doas` is included because it is the same capability under a different name; + * a machine with `doas` installed and only `sudo` blocked is not blocked. + * + * This raises the bar; it does not close the class. `bash -c "sudo …"`, a + * variable (`S=sudo; $S …`) and base64-through-a-pipe all still reach root, + * because static inspection of one command string cannot follow them. Closing + * that properly needs enforcement below the shell, not a better regex. + */ +/** + * Split a command into per-segment TOKEN LISTS the way a shell reads it. + * + * Distinct from `shellSegments` below, which returns raw segment STRINGS and is + * what the deletion policies want. Named apart deliberately: defining a second + * `shellSegments` here shadowed that one, silently broke every `rm -rf` check, + * and disabled this matcher too — caught only because `tsc` reports duplicate + * implementations. + * + * Segmentation happens on the RAW string and skips separators inside quotes, + * which is the whole point: stripping quoting FIRST turns `\|` — a literal pipe + * in a grep alternation — into a real separator, so `grep "a\|sudo b"` parses + * as a command called `sudo` and gets denied. That is a common enough pattern + * that over-blocking it is worse than the evasion it would catch. + * + * Each token is unquoted individually afterwards, which still defeats `\sudo` + * and `"sudo"` without ever letting quote removal change where the boundaries + * are. Quoted tokens are returned separately so a caller can decide whether + * their CONTENTS deserve a second look — see `EVAL_FLAG_RE`. + */ +function quoteAwareSegments(command: string): Array { + const segments: Array = []; + let tokens: string[] = []; + let token = ""; + let quote: '"' | "'" | null = null; + const endToken = () => { + if (token) tokens.push(token); + token = ""; + }; + const endSegment = () => { + endToken(); + if (tokens.length) segments.push(tokens); + tokens = []; + }; + for (let i = 0; i < command.length; i++) { + const c = command[i]; + if (quote) { + // Inside single quotes a backslash is literal; inside double quotes it escapes. + if (c === "\\" && quote === '"' && i + 1 < command.length) { + token += command[++i]; + continue; + } + if (c === quote) { + quote = null; + continue; + } + token += c; + continue; + } + if (c === "\\" && i + 1 < command.length) { + // An escaped character is literal — `\sudo` is still sudo, and `\|` is a + // pipe CHARACTER rather than a separator. + token += command[++i]; + continue; + } + if (c === '"' || c === "'") { + quote = c; + continue; + } + if (/\s/.test(c)) { + endToken(); + continue; + } + if (/[;&|\n\r(){}`]/.test(c)) { + endSegment(); + continue; + } + token += c; + } + endSegment(); + return segments; +} +/** `-c` and friends: the flags whose ARGUMENT is a command, not data. */ +const EVAL_FLAG_RE = /^-{1,2}c$/; +/** + * True when a command runs an elevation binary IN COMMAND POSITION. + * + * Anchored structurally rather than by token, for the reason `namesSelfPause` + * is: `SUDO_RE` required the literal token `sudo` at a command boundary, so + * **`/usr/bin/sudo rm -rf /` was ALLOWED** — a direct invocation, no + * obfuscation, one absolute path away from root on a `defaultEnabled` guard. + * Every other form the shell resolves before settling on the binary — prefix + * assignments, redirections, runners and their flags — is walked off first, and + * the comparison is on the BASENAME so a path cannot hide the name. + * + * `doas` is included because it is the same capability under a different name; + * a machine with `doas` installed and only `sudo` blocked is not blocked. + * + * A quoted argument is re-examined ONLY when the command that owns it is a + * shell runner invoked with an eval flag (`bash -c "sudo …"`). That distinction + * is load-bearing: `bash -c "sudo x"` and `grep "a|sudo x"` are identical from + * the outside, and the only thing separating an execution from a search string + * is whether the receiving binary evaluates its argument. + * + * This raises the bar; it does not close the class. A variable (`S=sudo; $S …`), + * base64 through a pipe, and a wrapper script on disk all still reach root, + * because static inspection of one command string cannot follow them. Closing + * that properly needs enforcement below the shell, not a better matcher. + */ +function namesElevation(command: string, depth = 0): boolean { + for (const tokens of quoteAwareSegments(command)) { + let i = 0; + while (i < tokens.length) { + const token = tokens[i]; + const base = token.slice(token.lastIndexOf("/") + 1); + // `sudo`/`doas` are themselves in COMMAND_PREFIX_TOKENS (they legitimately + // stand in front of another binary), so they must be tested BEFORE the + // skip list or the walk would step straight over the thing being looked for. + if (base === "sudo" || base === "doas") return true; + const isSkippable = + ENV_ASSIGNMENT_RE.test(token) || + token.startsWith("-") || + token.startsWith(">") || + token.startsWith("<") || + RUNNER_OPERAND_RE.test(token) || + COMMAND_PREFIX_TOKENS.has(base); + if (!isSkippable) break; + // `sh -c "…"` / `bash -c "…"`: the next token is a COMMAND. Bounded + // recursion so a nested `bash -c "bash -c …"` cannot spin. + if (EVAL_FLAG_RE.test(token) && depth < 3 && i + 1 < tokens.length) { + if (namesElevation(tokens[i + 1], depth + 1)) return true; + } + i++; + } + } + return false; +} +function blockSudo(ctx: PolicyContext): PolicyResult { + if (ctx.toolName !== "Bash") return allow(); + const cmd = getCommand(ctx).trimStart(); + // ONE pass. `shellSegments` unquotes each token individually, so `\sudo` and + // `"sudo"` are still caught — without a whole-string strip, which is what + // turned an escaped pipe in `grep "a\|sudo b"` into a segment separator and + // denied an ordinary search. + if (namesElevation(cmd)) { + // Check allowPatterns — match against parsed tokens, not raw string + const allowPatterns = ((ctx.params?.allowPatterns ?? []) as string[]); + if (allowPatterns.some((p) => matchesAllowedPattern(cmd, p))) return allow(); + return deny("sudo commands are blocked"); + } + // PowerShell: Start-Process -Verb RunAs (elevation) + if (PS_ELEVATION_RE.test(cmd)) { + return deny("Elevated process launch is blocked"); + } + // Windows: runas command + if (RUNAS_RE.test(cmd)) { + return deny("runas elevation is blocked"); + } + return allow(); +} + +/** + * A pause the agent can issue is not a guardrail. + * + * `failproofai config --pause` is a human affordance: you watched the agent get + * blocked, you judged the block wrong, you suspended enforcement for a bit. An + * agent that can run it turns every other policy advisory — it need only shell + * out once to switch them all off, and the pause even survives into later turns. + * + * This raises the bar rather than closing the class: an agent can still reach + * the same state obfuscated (base64, a wrapper script, an alias). Closing it + * properly means the pause cannot originate from a tool call at all — a + * dashboard action, or a daemon that accepts it only from a TTY. Until then, + * the honest description of this policy is "stops the obvious attempt". + * + * It is deliberately NOT redundant with `block-failproofai-commands`, which + * blocks the CLI far more broadly. That one anchors on a command boundary + * (`FAILPROOFAI_CLI_RE`), so `npx -y failproofai config --pause` does not match + * it — and being broad, it is a policy people plausibly switch off so agents + * can run `failproofai audit`. Neither gap should leave pausing reachable, so + * this stays narrow, matches the runner forms, and survives that one being off. + */ +function blockCurlPipeSh(ctx: PolicyContext): PolicyResult { + if (ctx.toolName !== "Bash") return allow(); + const cmd = getCommand(ctx); + if (CURL_PIPE_SH_RE.test(cmd)) { + return deny("Piping downloads to shell is blocked"); + } + // PowerShell: iwr | iex, irm | iex, Invoke-WebRequest | Invoke-Expression + if (PS_WEB_PIPE_RE.test(cmd)) { + return deny("Piping downloads to Invoke-Expression is blocked"); + } + return allow(); +} +function extractGitPushArgs(cmd: string): string[] { + return cmd + .split(/&&|\|\||[|;\n]/) + .map((s) => s.trim()) + .filter((s) => /^git\s+push\s/.test(s)) + .map((s) => s.replace(/^git\s+push\s+/, "")); +} +function blockPushMaster(ctx: PolicyContext): PolicyResult { + if (ctx.toolName !== "Bash") return allow(); + const protectedBranches = ((ctx.params?.protectedBranches ?? ["main", "master"]) as string[]); + if (protectedBranches.length === 0) return allow(); + const args = extractGitPushArgs(getCommand(ctx)); + const branchPattern = new RegExp(`\\b(?:${protectedBranches.map((b) => b.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|")})\\b`); + if (args.some((a) => branchPattern.test(a))) { + return deny(`Pushing to ${protectedBranches.join("/")} is blocked`); + } + return allow(); +} + +// -- block-rm-rf: deletion-target resolution -- +/** + * Leading shell forms that resolve to a home directory: `~`, `~user`, `$HOME`, + * `${HOME}`. The lookahead keeps `$HOMEBREW_PREFIX` (a variable this policy + * cannot resolve) from being mistaken for `$HOME`. + */ +const HOME_PREFIX_RE = /^(?:~[A-Za-z0-9_.-]*|\$HOME|\$\{HOME\})(?=$|\/)/; +/** `rm`, `/bin/rm`, `/usr/bin/rm`, … — the command word of a delete. */ +const RM_CMD_RE = /^(?:\/\S*\/)?rm$/; +/** `find` expression that deletes: `-delete`, `-exec rm`, `-execdir rm`, `-ok rm`. */ +// Same shape as RM_CMD_RE: `find` is just as dangerous when invoked by +// absolute path (`/usr/bin/find / -delete`), so match both forms. +const FIND_CMD_RE = /^(?:\/\S*\/)?find$/; +const FIND_EXEC_RE = /^-(?:exec|execdir|ok|okdir)$/; +/** find's global options, which precede its path operands (`find -L / -delete`). */ +const FIND_GLOBAL_OPT_RE = /^-(?:[HLP]|D|O\d*)$/; +/** First token of find's expression — everything before it is a path operand. */ +const FIND_EXPR_START_RE = /^(?:-|\\?[(!])/; +/** + * Roots that exist to hold throwaway data. A delete of the root itself is still + * catastrophic (`rm -rf /tmp` wipes every process's scratch space); a delete of + * something *inside* one is ordinary work. + */ +const SCRATCH_ROOTS = ["/tmp", "/var/tmp"]; +/** + * How many path segments below a root (`/` or a home directory) a delete has to + * reach before it stops being catastrophic. `/etc` (1) and `/home/chetan` (2) + * are system- and user-level directories; `/home/chetan/project` (3) is a + * specific thing the caller meant to delete. + */ +const CATASTROPHIC_DEPTH = 2; +/** Expand the leading `~` / `$HOME` / `${HOME}` of a path to the real home directory. */ +function expandHomePrefix(path: string): string { + const m = path.match(/^(?:~|\$HOME|\$\{HOME\})(?=$|\/)/); + return m ? homedir() + path.slice(m[0].length) : path; +} +/** Drop a trailing `/*` glob and any trailing slashes: `/tmp/foo/*` → `/tmp/foo`. */ +function stripTrailingGlob(path: string): string { + return path.replace(/\/\*$/, "").replace(/\/+$/, ""); +} +/** + * Would deleting this target be catastrophic? + * + * Rather than pattern-matching the raw command text, this resolves the token as + * far as the shell would: quotes are stripped, `~` / `$HOME` are recognised as a + * root in their own right, and the remaining path segments are counted. A target + * within {@link CATASTROPHIC_DEPTH} segments of either root (`/` or home) takes + * out the machine or the user's data. + * + * Fails safe: a token whose head is an expansion this policy cannot evaluate — + * command substitution (`$(…)`, backticks) or any variable other than `$HOME` — + * could expand to `/`, so it counts as catastrophic. Relative targets are not + * flagged: they resolve under the working directory, not under a root. + */ +function isCatastrophicTarget(token: string): boolean { + const raw = token.replace(/^['"]|['"]$/g, ""); + if (raw === "") return false; + + const homePrefix = raw.match(HOME_PREFIX_RE); + // Unresolvable head: `$(echo /)`, `` `pwd` ``, `$TARGET_DIR`, … + if (!homePrefix && /^[$`]/.test(raw)) return true; + + const belowRoot = homePrefix ? raw.slice(homePrefix[0].length) : raw.startsWith("/") ? raw : null; + if (belowRoot === null) return false; + + const segments = stripTrailingGlob(belowRoot).split("/").filter(Boolean); + if (!homePrefix && SCRATCH_ROOTS.some((r) => `/${segments.join("/")}`.startsWith(`${r}/`))) return false; + return segments.length <= CATASTROPHIC_DEPTH; +} +/** + * The paths a single command segment would recursively delete, or `null` when the + * segment is not a recursive delete at all. + * + * Understands the two shapes that reach every file under a target: `rm` with both + * `-r` and `-f` (in any spelling or order), and `find`, which recurses by design, + * paired with `-delete` or an `-exec rm`. + */ +function recursiveDeletionTargets(seg: string): string[] | null { + const tokens = parseArgvTokens(seg); + + const findIdx = tokens.findIndex((t) => FIND_CMD_RE.test(t)); + if (findIdx >= 0) { + const expr = tokens.slice(findIdx + 1); + const execIdx = expr.findIndex((t) => FIND_EXEC_RE.test(t)); + const deletes = expr.includes("-delete") || (execIdx >= 0 && RM_CMD_RE.test(expr[execIdx + 1] ?? "")); + if (deletes) { + // find's path operands sit between the leading global options and the + // first expression token: `find -L /home/chetan -name '*.log' -delete` + let start = 0; + while (start < expr.length && FIND_GLOBAL_OPT_RE.test(expr[start])) { + start += expr[start] === "-D" ? 2 : 1; + } + const rest = expr.slice(start); + const end = rest.findIndex((t) => FIND_EXPR_START_RE.test(t)); + return end < 0 ? rest : rest.slice(0, end); + } + } + + const rmIdx = tokens.findIndex((t) => RM_CMD_RE.test(t)); + if (rmIdx >= 0) { + const args = tokens.slice(rmIdx + 1); + const shortFlags = args.filter((t) => /^-[^-]/.test(t)).join(""); + const longFlags = args.filter((t) => /^--/.test(t)); + const recursive = /r/i.test(shortFlags) || longFlags.some((f) => /^--recursive$/i.test(f)); + const force = /f/.test(shortFlags) || longFlags.some((f) => /^--force$/i.test(f)); + if (recursive && force) return args.filter((t) => !t.startsWith("-")); + } + + return null; +} +/** Split a command into the segments the shell would run as separate commands. */ +function shellSegments(cmd: string): string[] { + return cmd.split(/&&|\|\||[|;\n]/).map((s) => s.trim()).filter((s) => s !== ""); +} +/** + * Check whether all recursive-delete targets in a command are under an allowlisted path. + * Splits on shell operators first so that `/tmp` appearing in an unrelated + * sub-command (e.g. `echo /tmp && rm -rf /`) does not trigger a false allow. + * Uses path-boundary comparison so `/tmp` does not cover `/tmp2`. + * Non-recursive rm segments (no -r/-R flag) are skipped — they pose no catastrophic risk. + * Quoted paths with spaces are handled via a segment-level regex fallback. + * Home-relative targets and allowPaths entries are expanded, so `~/scratch` is + * covered by an allowPaths entry of either `~/scratch` or the absolute home path. + */ +function deletionTargetIsAllowed(cmd: string, allowPaths: string[]): boolean { + if (allowPaths.length === 0) return false; + const normalizedAllowPaths = allowPaths.map((p) => stripTrailingGlob(expandHomePrefix(p)) || "/"); + let sawRecursiveDelete = false; + for (const seg of shellSegments(cmd)) { + const targets = recursiveDeletionTargets(seg); + if (targets === null) continue; + sawRecursiveDelete = true; + for (const target of targets) { + const normalized = stripTrailingGlob(expandHomePrefix(target)) || "/"; + const covered = normalizedAllowPaths.some((np) => normalized === np || normalized.startsWith(np + "/")); + if (!covered) { + // Fallback: check the raw segment for quoted paths that contain spaces + // (parseArgvTokens splits on whitespace, so "/tmp/my dir" becomes two tokens) + const segCovered = allowPaths.some((p) => { + const escaped = p.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + return new RegExp(`${escaped}(?:[/"'\\s/*]|$)`).test(seg); + }); + if (!segCovered) return false; + } + } + } + return sawRecursiveDelete; +} +function blockRmRf(ctx: PolicyContext): PolicyResult { + if (ctx.toolName !== "Bash") return allow(); + const cmd = getCommand(ctx); + + const hasCatastrophicTarget = shellSegments(cmd).some((seg) => { + const targets = recursiveDeletionTargets(seg); + return targets !== null && targets.some(isCatastrophicTarget); + }); + if (hasCatastrophicTarget) { + const allowPaths = ((ctx.params?.allowPaths ?? []) as string[]); + if (deletionTargetIsAllowed(cmd, allowPaths)) return allow(); + return deny("Catastrophic deletion blocked"); + } + + // PowerShell: Remove-Item -Recurse -Force on root/drive + if (/Remove-Item\s+.*-Recurse.*-Force.*(?:[A-Z]:\\(?:\s|$)|\\\*)/i.test(cmd)) { + return deny("Catastrophic deletion blocked"); + } + // cmd: rd /s /q or rmdir /s /q on drive root + if (/(?:rd|rmdir)\s+\/s\s+\/q\s+[A-Z]:\\/i.test(cmd)) { + return deny("Catastrophic deletion blocked"); + } + return allow(); +} +function blockForcePush(ctx: PolicyContext): PolicyResult { + if (ctx.toolName !== "Bash") return allow(); + for (const segment of extractGitPushArgs(getCommand(ctx))) { + let sawEndOfOptions = false; + for (const token of segment.split(/\s+/)) { + if (token === "--") { + sawEndOfOptions = true; + continue; + } + if (sawEndOfOptions) continue; + if (isForcePushFlag(token)) { + return deny("Force-pushing is blocked"); + } + } + } + return allow(); +} +function isForcePushFlag(token: string): boolean { + if (token === "--force") return true; + if (SAFE_FORCE_PREFIXES.some((prefix) => token.startsWith(prefix))) return false; + if (token.startsWith("--force")) return true; + return SHORT_FLAG_BUNDLE_RE.test(token); +} +function blockSecretsWrite(ctx: PolicyContext): PolicyResult { + if (ctx.toolName !== "Write") return allow(); + const filePath = getFilePath(ctx); + if (SECRET_FILE_RE.test(filePath) || SECRET_FILE_ID_RSA_RE.test(filePath) || SECRET_FILE_CREDENTIALS_RE.test(filePath)) { + return deny("Writing secret key files is blocked"); + } + const additionalPatterns = ((ctx.params?.additionalPatterns ?? []) as string[]); + for (const pattern of additionalPatterns) { + if (filePath.includes(pattern)) { + return deny(`Writing blocked file pattern: ${pattern}`); + } + } + return allow(); +} +/** Read-like commands that access file system contents. */ +const READ_LIKE_CMDS = + /(?:^|;|&&|\|\||\|)\s*(?:ls|find|cat|head|tail|less|more|wc|file|stat|tree|du)\s/; +/** + * Extract absolute paths from a Bash command string. + * Scans quoted strings only in the first pipeline segment (before the first + * bare pipe) and only when the quoted content has no glob or regex metacharacters. + * This catches `cat "/etc/passwd"` while avoiding false positives from grep + * patterns and find glob patterns that appear in later pipeline stages. + * Unquoted absolute paths are extracted from the whole command as before. + * + * The negative lookbehind also excludes glob metacharacters ('*', '?') and + * separator characters that appear in compound argv tokens (':' for Docker + * volume mounts and PATH-like lists, '=' for env var assignments) so that a + * suffix like '/dashboard.mdx' in 'docs/STAR/dashboard.mdx' or '/docs' in + * '-v HOST_DIR:/docs' is not misread as a standalone absolute path. '/' is in + * that list too, so a match cannot START on the second slash of a protocol + * separator: 'http://localhost:3000/x' used to yield '/localhost:3000/x'. + * A match that starts on the FIRST slash is untouched, so '//etc/passwd' — + * a real, working spelling of /etc/passwd — is still extracted and still + * resolves to /etc/passwd. + * + * A run of slashes with nothing else ('//', '///') that opens a line after + * the first is dropped: that is a line-comment marker in a heredoc body, not a + * directory. It used to resolve to the filesystem root, which denied a heredoc + * writing a TypeScript file into the project. Anywhere else a slash-run is + * the root, as a lone '/' is: `cd // && cat etc/shadow` reads /etc/shadow. + */ +function extractAbsolutePaths(command: string): string[] { + const paths: string[] = []; + const pathRe = /(?//`, which bash joins into one line. + if (/^\/{2,}$/.test(p)) { + const nl = s.lastIndexOf("\n", m.index - 1); + if (nl !== -1 && s[nl - 1] !== "\\" && /^[ \t]*$/.test(s.slice(nl + 1, m.index))) continue; + } + if (p === "~") p = homedir(); + else if (p.startsWith("~/")) p = join(homedir(), p.slice(2)); + paths.push(p); + } + } + + // Find the index of the first bare pipe (not inside quotes) to limit quoted extraction. + let firstBarePipe = command.length; + let inDouble = false, inSingle = false; + for (let i = 0; i < command.length; i++) { + const c = command[i]; + if (c === '"' && !inSingle) inDouble = !inDouble; + else if (c === "'" && !inDouble) inSingle = !inSingle; + else if (c === "|" && !inDouble && !inSingle) { firstBarePipe = i; break; } + } + + // Extract paths from quoted strings in the FIRST pipeline segment only, + // and only when the content has no glob/regex metacharacters. + const firstSegment = command.slice(0, firstBarePipe); + const quotedRe = /"([^"]*)"|'([^']*)'/g; + let qm: RegExpExecArray | null; + while ((qm = quotedRe.exec(firstSegment)) !== null) { + const content = qm[1] ?? qm[2] ?? ""; + // Skip patterns that contain glob or common regex metacharacters + if (/[*?\[\]^$+()\\]/.test(content)) continue; + addPaths(content); + } + + // Extract from unquoted portions of the whole command (existing behaviour). + const stripped = command + .replace(/"[^"]*"/g, (m) => " ".repeat(m.length)) + .replace(/'[^']*'/g, (m) => " ".repeat(m.length)); + addPaths(stripped); + + return paths; +} +function blockReadOutsideCwd(ctx: PolicyContext): PolicyResult { + // Prefer $CLAUDE_PROJECT_DIR (stable project root) over ctx.session.cwd, + // which tracks the live shell CWD and drifts when Claude `cd`s into a subdir. + const cwd = process.env.CLAUDE_PROJECT_DIR || ctx.session?.cwd; + if (!cwd) return allow(); // Can't enforce without cwd + + const allowPaths = ((ctx.params?.allowPaths ?? []) as string[]); + + // For Bash tool: check read-like commands for absolute paths outside cwd + if (ctx.toolName === "Bash") { + const cmd = getCommand(ctx); + if (!READ_LIKE_CMDS.test(cmd)) return allow(); + + const paths = extractAbsolutePaths(cmd); + const cwdWithSep = cwd.endsWith("/") ? cwd : cwd + "/"; + for (const p of paths) { + const resolved = resolve(cwd, p); + if (isClaudeSettingsFile(resolved)) { + return deny(`Reading agent settings file blocked: ${resolved}`); + } + if (isClaudeInternalPath(resolved)) continue; // Whitelist ~/.claude/ + if (resolved === "/dev/null") continue; // Harmless special file + if (resolved !== cwd && !resolved.startsWith(cwdWithSep)) { + if (allowPaths.some((ap) => resolved === ap || resolved.startsWith(ap.endsWith("/") ? ap : ap + "/"))) continue; + return deny(`Bash read outside project directory blocked: ${resolved}`); + } + } + return allow(); + } + + // For Read/Glob/Grep: existing file_path / path check + const filePath = getFilePath(ctx); + const searchPath = (ctx.toolInput?.path as string) ?? ""; + + const target = filePath || searchPath; + if (!target) return allow(); + + const resolved = resolve(cwd, target); + + // Block settings files in any .claude directory before whitelisting + if (isClaudeSettingsFile(resolved)) { + return deny(`Reading agent settings file blocked: ${resolved}`); + } + + // Whitelist ~/.claude/ — Claude Code's own config, plans, memory, and settings + if (isClaudeInternalPath(resolved)) return allow(); + + // Whitelist /dev/null — harmless special file commonly used in shell commands + if (resolved === "/dev/null") return allow(); + + const cwdWithSep = cwd.endsWith("/") ? cwd : cwd + "/"; + if (resolved !== cwd && !resolved.startsWith(cwdWithSep)) { + if (allowPaths.some((ap) => resolved === ap || resolved.startsWith(ap.endsWith("/") ? ap : ap + "/"))) return allow(); + return deny(`Access outside project directory blocked: ${resolved}`); + } + return allow(); +} +function blockWorkOnMain(ctx: PolicyContext): PolicyResult { + if (ctx.toolName !== "Bash") return allow(); + const cmd = getCommand(ctx); + const match = cmd.match(GIT_COMMIT_MERGE_RE); + if (!match) return allow(); + + const cwd = ctx.session?.cwd; + if (!cwd) return allow(); + + const branch = getCurrentBranch(cwd); + if (!branch) return allow(); + + const protectedBranches = ((ctx.params?.protectedBranches ?? ["main", "master"]) as string[]); + if (protectedBranches.includes(branch)) { + return deny( + `Git ${match[1]} on ${branch} is blocked. Create a feature branch first.`, + ); + } + return allow(); +} +// ── The state walk from FailproofAI/failproofai#1058 ───────────────────────── +// failproofai's state, installed code and the npx bin entry. The settings +// files go through destroysProtectedPath above; the state goes through both. + +/** + * Commands that put a file into a directory under the file's OWN name, and the + * options of each that take a value, short and long. + * + * `cp /tmp/stage/failproofai node_modules/.bin/` writes + * `node_modules/.bin/failproofai`, and that path appears nowhere on the line: + * the source names a scratch file and the destination names a directory that + * holds every package's binary. So the name a source would land under is + * judged as well as the operands as written (FailproofAI/agenteye#1795). + * A value is not a source: `install -o failproofai -m 0755 agentd /usr/local/bin/` + * installs `agentd`. `t` is the target directory for all but rsync, where it + * is `--times`, and scp, which has none. scp's `-T` is not `--no-target-directory` + * and its `-R` is not recursive. + */ +type IntoDirectoryOptions = { short: string; values: readonly string[]; flags: readonly string[] }; +// A Map, not an object literal: a command named `constructor` or `__proto__` +// must not find Object.prototype's member here, or the walk throws and the +// evaluator skips this always-on policy (found by CodeRabbit on #1058). +const INTO_DIRECTORY_OPTIONS = new Map(Object.entries({ + // From each command's `--help` (GNU coreutils 9, rsync 3.4.1): `values` take + // one, `flags` take none or only an `=VALUE` glued on. + cp: { + short: "St", + values: ["no-preserve", "sparse", "suffix", "target-directory"], + flags: [ + "archive", "attributes-only", "backup", "context", "copy-contents", "debug", "dereference", "force", "help", + "interactive", "keep-directory-symlink", "link", "no-clobber", "no-dereference", "no-target-directory", + "one-file-system", "parents", "preserve", "recursive", "reflink", "remove-destination", + "strip-trailing-slashes", "symbolic-link", "update", "verbose", "version", + ], + }, + mv: { + short: "St", + values: ["suffix", "target-directory"], + flags: [ + "backup", "context", "debug", "exchange", "force", "help", "interactive", "no-clobber", "no-copy", + "no-target-directory", "strip-trailing-slashes", "update", "verbose", "version", + ], + }, + ln: { + short: "St", + values: ["suffix", "target-directory"], + flags: [ + "backup", "force", "help", "interactive", "logical", "no-dereference", "no-target-directory", "physical", + "relative", "symbolic", "verbose", "version", + ], + }, + install: { + short: "mogSt", + values: ["group", "mode", "owner", "strip-program", "suffix", "target-directory"], + flags: [ + "backup", "compare", "context", "directory", "help", "no-target-directory", "preserve-context", + "preserve-timestamps", "strip", "unprivileged", "verbose", "version", + ], + }, + rsync: { + short: "@BefMT", + values: [ + "address", "backup-dir", "block-size", "bwlimit", "cc", "checksum-choice", "checksum-seed", "chmod", "chown", + "compare-dest", "compress-choice", "compress-level", "contimeout", "copy-as", "copy-dest", "debug", + "early-input", "exclude", "exclude-from", "files-from", "filter", "groupmap", "iconv", "include", + "include-from", "info", "link-dest", "log-file", "log-file-format", "max-alloc", "max-delete", "max-size", + "min-size", "modify-window", "only-write-batch", "outbuf", "out-format", "partial-dir", "password-file", + "port", "protocol", "read-batch", "remote-option", "rsh", "rsync-path", "skip-compress", "sockopts", + "stop-after", "stop-at", "suffix", "temp-dir", "timeout", "usermap", "write-batch", "zc", "zl", + ], + flags: [ + "acls", "append", "append-verify", "archive", "atimes", "backup", "blocking-io", "checksum", "compress", + "copy-devices", "copy-dirlinks", "copy-links", "copy-unsafe-links", "crtimes", "cvs-exclude", "daemon", "del", + "delay-updates", "delete", "delete-after", "delete-before", "delete-delay", "delete-during", + "delete-excluded", "delete-missing-args", "devices", "dirs", "dry-run", "executability", "existing", + "fake-super", "force", "from0", "fsync", "fuzzy", "group", "hard-links", "help", "human-readable", + "ignore-errors", "ignore-existing", "ignore-missing-args", "ignore-times", "inplace", "ipv4", "ipv6", + "itemize-changes", "keep-dirlinks", "links", "list-only", "mkpath", "munge-links", "no-implied-dirs", + "no-motd", "numeric-ids", "old-args", "old-d", "old-dirs", "omit-dir-times", "omit-link-times", + "one-file-system", "open-noatime", "owner", "partial", "perms", "preallocate", "progress", + "prune-empty-dirs", "quiet", "recursive", "relative", "remove-source-files", "safe-links", "secluded-args", + "size-only", "sparse", "specials", "stats", "stderr", "super", "times", "trust-sender", "update", "verbose", + "version", "whole-file", "write-devices", "xattrs", + ], + }, + // OpenSSH 9's `scp` synopsis: no long options. + scp: { short: "cDFiJloPSX", values: [], flags: [] }, +} satisfies Record)); +/** + * The long option `name` stands for, and whether it takes a value: an exact + * name first, so `--partial` is not read as an abbreviation of + * `--partial-dir` and made to swallow the next word, then the one option an + * abbreviation can only mean. Ambiguous or unknown, the command refuses to run. + */ +function longOptionOf( + options: { values: readonly string[]; flags: readonly string[] }, + name: string, +): { full: string; value: boolean } | undefined { + if (options.values.includes(name)) return { full: name, value: true }; + if (options.flags.includes(name)) return { full: name, value: false }; + const matches = [ + ...options.values.filter((full) => full.startsWith(name)).map((full) => ({ full, value: true })), + ...options.flags.filter((full) => full.startsWith(name)).map((full) => ({ full, value: false })), + ]; + return name.length > 0 && matches.length === 1 ? matches[0] : undefined; +} +/** + * npm's bin directory, `node_modules/.bin`. A directory moved, linked or copied + * recursively ONTO it brings entries the line never names: + * `ln -s /tmp/stage ~/node_modules/.bin` hands every project under `~` without + * its own entry a `failproofai` from `/tmp/stage`, because npx searches each + * parent's `.bin` (#1795). Only npm's: `~/.bin` is somebody's own scripts. + */ +const NPM_BIN_DIRECTORY_RE = /(?:^|[\\/])node_modules[\\/](?:\.?[\\/])*\.bin$/i; +/** Options that are a prefix of an output option's name but are another option themselves. */ +const EXACT_NON_OUTPUT_OPTIONS = new Set(["curl --cookie", "curl --trace-time", "curl --trace-ids", "curl --trace-config"]); +/** `NAME=value` or `export NAME=value`, quoted or not, wherever it sits. */ +const ASSIGNMENT_RE = /(?:^|[\s;&|(])(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=("[^"]*"|'[^']*'|[^\s;&|)]+)/g; +/** `declare -n NAME=TARGET` (or `typeset`, `local`): `NAME` read as `TARGET`. */ +const NAMEREF_RE = + /(?:^|[\s;&|(])(?:declare|typeset|local)\s+(?:[-+][A-Za-z]+\s+)*?-[A-Za-z]*n[A-Za-z]*\s+(?:[-+][A-Za-z]+\s+)*([A-Za-z_][A-Za-z0-9_]*)=["']?([A-Za-z_][A-Za-z0-9_]*)["']?/g; +/** The header of a `for` or `select` loop over a list: its variable and the list. */ +const LOOP_VARIABLE_RE = /(?:^|[\s(])(?:for|select)\s+([A-Za-z_][A-Za-z0-9_]*)\s+in\b\s*([\s\S]*)$/; +/** More values than a loop's variable is read with; past it, only those that may reach what is protected. */ +const MAX_LOOP_VALUES = 64; +/** A value a word still holds that the walk cannot read: a substitution, or a reference left unexpanded. */ +const UNREAD_VALUE_RE = /\$\(\((?:[^()]|\([^()]*\))*\)\)|\$\((?:[^()]|\([^()]*\))*\)|\$\(|`[^`]*`|`|\$\{[^}]*\}|\$\{|\$[A-Za-z_][A-Za-z0-9_]*|\$[0-9@*#?$!-]/g; +/** How many `/`-separated segments the deepest glob candidate has. */ +const GLOB_CANDIDATE_DEPTH = Math.max(...STATE_GLOB_CANDIDATES.map((candidate) => candidate.split("/").length)); +/** + * The candidates a mid-path stretch is tried against: the relative ones of two + * segments or more (`node_modules/failproofai`, `node_modules/.bin/failproofai`), + * which stand for the same files under any directory. + */ +const MULTI_SEGMENT_GLOB_CANDIDATES = STATE_GLOB_CANDIDATES.filter( + (candidate) => /^[^~/$]/.test(candidate) && candidate.replace(/^\.\//, "").includes("/"), +); +/** + * True when this token is a glob that could expand onto failproofai's state. + * + * The floor used to be a literal `fail` in the token, and that is exactly what + * a glob is for: `rm -rf ~/.f*ailproofai` spells the same directory without the + * substring anywhere in it, so the pattern was thrown out before it was ever + * compiled. `.[f]ailproofai`, `.fa*lproofai`, `.fa[i]lproofai` and + * `.f{a,b}ilproofai` all walked through the same hole. + * + * A substring cannot decide this, because the whole point of the metacharacter + * is to stand where a letter was. What CAN decide it is the pattern's reach: it + * has to hit the state and miss everything ordinary. So the floor is now + * computed the same way the match is — compile once, require a candidate, and + * reject anything that also catches a decoy. `rm -rf *` and `rm -rf ~/.*` stay + * allowed because they sweep the decoys too; `rm -rf /tmp/test-failures*` stays + * allowed because it reaches no candidate at all. + */ +function globCouldNameState(raw: string): boolean { + // Both readings of a trailing `)`: part of the pattern, and the close of a + // subshell that wrapped it. Trying both is safe in the way widening always is + // here — the decoy test still has to pass. + const stripped = raw.replace(/^[()]+|[()]+$/g, ""); + return globWordCouldNameState(raw) || (stripped !== raw && globWordCouldNameState(stripped)); +} +function globWordCouldNameState(token: string): boolean { + if (!GLOB_METACHAR_RE.test(token)) return false; + // Braces FIRST, because that is the order the shell works in: brace expansion + // rewrites the word into several words, and only then is each one matched + // against the disk. Compiling `{a*,x}` as an alternation of escaped literals + // put a literal `*` inside the pattern, so `~/.f{a*,x}ilproofai` — which the + // shell turns into `~/.fa*ilproofai` and then into `~/.failproofai` — read as + // naming nothing at all. + for (const word of expandBraces(token)) { + if (wordNamesState(word)) return true; + } + return false; +} +/** + * True when one brace-expanded word names the state. + * + * The literal check comes first because expansion can PRODUCE the literal: + * `~/.{failproofai,other}` carries no `.failproofai` as written, and the word it + * expands to needs no glob compilation to be recognised. + */ +function wordNamesState(word: string): boolean { + if (FAILPROOFAI_STATE_PATH_RE.test(word)) return true; + // Every path PREFIX, not just the whole word. The candidates are the state + // directory itself, so `~/.f*ailproofai/policies-config.json` — a glob in a + // segment that is not the last one — compiled to a pattern that could never + // equal `~/.failproofai` and was read as naming nothing. Naming a file INSIDE + // the state is naming the state. + // `//`, `/./` and `..` change nothing a shell opens (`~//.failproof*`), and + // somebody else's home is the same place as the candidates' `/home/u`: + // `/home/alice/.failproof*` and `~alice/.failproof*` named nothing. + const segments = (/\/\/|(?:^|\/)\.\.?\//.test(word) ? shellPath(undefined, word) : word) + .replace(/^\/(home|Users)\/[^/]+(?=\/)/, "/$1/u") + .replace(/^~[A-Za-z0-9._-]+(?=\/)/, "~") + .split("/"); + // A prefix with more segments than the deepest candidate cannot equal one: + // a compiled `*` never crosses a `/`. + for (let end = 1; end <= Math.min(segments.length, GLOB_CANDIDATE_DEPTH); end++) { + if (globPrefixNamesState(segments.slice(0, end).join("/"))) return true; + } + // And every stretch that starts after a `/`, because the paths the + // multi-segment candidates stand for can sit under any directory: + // `/work/proj/node_modules/.bin/fail*` named nothing as a whole word + // (FailproofAI/agenteye#1795). A one-segment stretch only when it starts + // with a literal `.`: a shell's `*` never matches a dotfile, so `models/*ai` + // cannot reach `.failproofai`, while `/var/lib/jenkins/.failproof*` — a home + // no candidate spells — can. + for (let start = 1; start < segments.length; start++) { + const last = Math.min(segments.length, start + GLOB_CANDIDATE_DEPTH); + const first = segments[start].startsWith(".") ? start + 1 : start + 2; + for (let end = first; end <= last; end++) { + const candidates = end - start === 1 ? STATE_GLOB_CANDIDATES : MULTI_SEGMENT_GLOB_CANDIDATES; + if (globPrefixNamesState(segments.slice(start, end).join("/"), candidates)) return true; + } + } + return false; +} +/** + * One `/`-delimited prefix of a brace-expanded word, compiled and tried against + * the candidates. Braces are already gone by here; an unmatched one is literal. + */ +function globPrefixNamesState(token: string, candidates: readonly string[] = STATE_GLOB_CANDIDATES): boolean { + if (!GLOB_METACHAR_RE.test(token)) return false; + // Case-insensitive, like FAILPROOFAI_STATE_PATH_RE: on a default macOS + // volume `NODE_MODULES/fail*` reaches the real `node_modules/failproofai`, + // because the literal parent is resolved by the filesystem. + const re = globTest(token, { ignoreCase: true }); + if (re === null) return false; + if (!candidates.some((candidate) => re.test(candidate))) return false; + return !GLOB_DECOYS.some((decoy) => re.test(decoy)); +} +/** + * Strip the punctuation a shell consumes, so `(cd` reads as `cd`. + * + * Quotes come off for the same reason the brackets do, and they are the pair + * that mattered: `bash -c 'cat ~/.failproofai/policies-config.json'` presented + * a head of `'cat`, which is on no allowlist, so the guard denied a plain read + * of the config through the most ordinary wrapper there is. Stripping them + * cannot let a deleter past — `"rm"` unquotes to `rm`, which is still not a + * reader. + */ +function bareTokenForState(token: string): string { + // A brace expansion keeps its braces: `{hook,x}` is two words to the shell, + // not `hook,x` (found by hermes on FailproofAI/failproofai#1058). + if (/\{[^{}]*(?:,|\.\.)[^{}]*\}/.test(token)) return token.replace(/^[()'"]+|[()'"]+$/g, ""); + return token.replace(/^[(){}'"]+|[(){}'"]+$/g, ""); +} +/** A redirect operator, with an optional fd (`2>`, `{fd}>`), and the same alone. */ +const REDIRECT_OPERATOR_RE = /^(?:\d*|\{[A-Za-z_]\w*\})(?:>{1,2}\|?|<{1,3})/; +const LONE_REDIRECT_OPERATOR_RE = /^(?:\d*|\{[A-Za-z_]\w*\})(?:>{1,2}\|?|<{1,3})$/; +/** + * A simple command split the way a shell splits it: on whitespace outside + * quotes, so `-H 'X-Ticket: #1795'` is one word. `quoted` says the word starts + * inside quotes or with an escape, where `#` and `>` are characters, not a + * comment or a redirect. + */ +function shellWords(text: string): Array<{ raw: string; quoted: boolean }> { + const words: Array<{ raw: string; quoted: boolean }> = []; + let current = ""; + let started = false; + let quoted = false; + let quote: string | null = null; + for (let i = 0; i < text.length; i++) { + const ch = text[i]; + if (quote === null && /\s/.test(ch)) { + if (started) words.push({ raw: current, quoted }); + current = ""; + started = false; + continue; + } + if (!started) { + started = true; + quoted = ch === "'" || ch === '"' || ch === "\\"; + } + current += ch; + if (ch === "\\" && quote !== "'" && i + 1 < text.length) { + current += text[++i]; + } else if (quote === null && (ch === "'" || ch === '"')) { + quote = ch; + } else if (ch === quote) { + quote = null; + } + } + if (started) words.push({ raw: current, quoted }); + return words; +} +/** + * Walk off everything a shell resolves before it settles on the command word, + * and return the words from the command word on. Mirrors the walk in + * `classifySelfInvocation` — the same prefixes hide a deleter that hid the + * binary, and `xargs -0 rm -f` is the one that matters most here. + * + * Redirects and a comment are not words, after the command word either. The + * copy checks take the LAST operand for the destination, so a redirect or a + * comment after it became the destination they judged: + * `cp /dev/null ~/.failproofai/policies-config.json 2>/dev/null` and + * `… node_modules/.bin/failproofai # keep` both walked through, while + * `uniq -c < ` read the file it only reads as one it writes. Split + * on whitespace alone, a quoted `#` or `<` cut off the real words after it, so + * the command is split the way a shell splits it (`shellWords`) + * (FailproofAI/agenteye#1795). A command word starting with `#` is a comment line. + */ +function commandWordList(simpleCommand: string): string[] { + const split = (text: string) => shellWords(text).map(({ raw, quoted }) => ({ raw, quoted, token: bareTokenForState(raw) })); + const all = split(simpleCommand.trim()); + let i = 0; + for (let programs = 0; i < all.length; ) { + const { raw, quoted, token } = all[i]; + if (token === "") { + i++; + continue; + } + // A quoted word where the command goes is a program handed to a shell + // (`bash -c 'rm -rf …'`): its own words are the command. + if (quoted && /\s/.test(token) && programs++ < 4) { + all.splice(i, 1, ...split(token)); + continue; + } + // A redirect operator and, when it stands alone, the token it targets — + // `> file` must not leave `file` sitting where the command word goes. + if (!quoted && REDIRECT_OPERATOR_RE.test(raw)) { + i += LONE_REDIRECT_OPERATOR_RE.test(raw) ? 2 : 1; + continue; + } + const skippable = + ENV_ASSIGNMENT_RE.test(token) || + token.startsWith("-") || + RUNNER_OPERAND_RE.test(token) || + SHELL_KEYWORD_PREFIXES.has(token) || + COMMAND_PREFIX_TOKENS.has(commandBasename(token)); + if (!skippable) break; + i++; + } + const words: string[] = []; + for (let j = i; j < all.length; j++) { + const { raw, quoted, token } = all[j]; + if (!quoted && raw.startsWith("#")) break; + if (j > i && !quoted && REDIRECT_OPERATOR_RE.test(raw)) { + if (LONE_REDIRECT_OPERATOR_RE.test(raw)) j++; + continue; + } + words.push(token); + } + return words; +} +/** + * True when a copy, move or link writes a protected path that its words never + * spell (see `INTO_DIRECTORY_OPTIONS`), or puts a directory onto npm's bin + * directory (see `NPM_BIN_DIRECTORY_RE`). + * + * The destination is `-t`'s value in any spelling (`-t DIR`, `-tDIR`, `-vt DIR`, + * `--target-directory=DIR`, `--target DIR`), or else the last operand. Each + * source is judged where it would land, `/`. Whether the + * destination really is a directory is not checked: when it is a file, that + * path is one nothing writes, and it matches only when a source is named like a + * protected file and the destination like the directory that holds one. + * + * A source that is itself protected is a copy OUT, so it counts only when it + * lands on installed code: `cp -r ~/.failproofai /tmp/backup/` lands at + * `/tmp/backup/.failproofai`, which the state pattern matches by name, and is a + * backup; `cp /tmp/bin/failproofai node_modules/.bin/` is not, however its + * source is spelled. A source ending in a separator copies what is IN it, whose + * names are not on the line, so it is judged only through the bin-directory + * check. `inShell` resolves a relative word against a `cd` the walk followed; + * `lost` says the walk could not follow one, so a relative destination may be + * npm's bin directory and the entry's own name there is refused. + * `landsOnState` judges where a written path really lands, symlinks followed. + */ +function landsInDirectoryAs( + words: string[], + namesState: (text: string) => boolean, + inShell: (word: string) => string = (word) => word, + lost = false, + landsOnState: (written: string) => boolean = () => false, + isBinDir: (written: string) => boolean = () => false, +): boolean { + if (words.length === 0) return false; + const head = commandBasename(words[0]); + const options = INTO_DIRECTORY_OPTIONS.get(head); + if (!options) return false; + const operands: string[] = []; + let directory: string | undefined; + let createsDirectories = false; + let recursive = false; + let ontoItself = false; + const args = words.slice(1); + for (let i = 0; i < args.length; i++) { + const arg = args[i]; + if (arg === "--") { + operands.push(...args.slice(i + 1)); + break; + } + if (arg.startsWith("--")) { + const eq = arg.indexOf("="); + const name = arg.slice(2, eq === -1 ? undefined : eq); + const value = eq === -1 ? undefined : arg.slice(eq + 1); + // GNU takes any unambiguous prefix of a long option: `--target DIR` is + // `--target-directory`, `--rec` is `--recursive`, `--suf x` is `--suffix x`. + const option = longOptionOf(options, name); + if (option?.full === "target-directory") { + directory = value ?? args[++i]; + } else if (option?.value) { + if (value === undefined) i++; + } else if (option?.full === "recursive" || option?.full === "archive") { + recursive = true; + } else if (option?.full === "no-target-directory") { + ontoItself = true; + } else if (option?.full === "directory" && head === "install") { + createsDirectories = true; + } + continue; + } + if (arg.startsWith("-") && arg.length > 1) { + for (let c = 1; c < arg.length; c++) { + const flag = arg[c]; + if (options.short.includes(flag)) { + // The rest of the cluster is the value, or else the next word is. + const value = c + 1 < arg.length ? arg.slice(c + 1) : args[++i]; + if (flag === "t" && head !== "rsync") directory = value; + break; + } + if (flag === "r" || ((flag === "R" || flag === "a") && head !== "scp")) recursive = true; + if (flag === "T" && head !== "rsync" && head !== "scp") ontoItself = true; + if (flag === "d" && head === "install") createsDirectories = true; + } + continue; + } + operands.push(arg); + } + if (createsDirectories) return false; + + // `ln -s ` alone links it into the current directory. + const sources = directory !== undefined ? operands : head === "ln" && operands.length === 1 ? operands : operands.slice(0, -1); + const written = directory ?? (head === "ln" && operands.length === 1 ? "." : operands[operands.length - 1]); + if (written === undefined || sources.length === 0) return false; + // `host:path` is somewhere else's disk. + if (head === "scp" && /^[^/\\]{2,}:/.test(written)) return false; + const destination = inShell(written); + if (directory === undefined && (namesState(destination) || landsOnState(written))) return true; + const baseName = (path: string) => path.slice(Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\")) + 1); + if (lost && directory === undefined && relativeWord(written) && couldBeEntryName(baseName(written))) return true; + + const into = destination.replace(/(?:[\\/]+\.?)+$/, ""); + // A directory becomes npm's bin directory when it is moved, linked or copied + // recursively onto a path that does not exist yet. `-t` needs a directory + // that exists, and so does `ln` given a trailing separator, so neither can. + // Copying what is IN a directory (`src/.`, rsync's `src/`, `-T`) fills an + // existing one with names that are not on the line. + // rsync never makes the destination a copy of a source directory: it puts + // `src` inside it, or with `src/` what is in `src`. + const createsDirectory = + directory === undefined && + !(head === "ln" && /[\\/]$/.test(written)) && + (head === "mv" || head === "ln" || (recursive && head !== "rsync")); + const copiesContents = recursive && (ontoItself || sources.some((s) => /[\\/]\.?$/.test(s))); + // The destination as written, or wherever a link there points. + const intoBin = NPM_BIN_DIRECTORY_RE.test(into) || isBinDir(written); + if (intoBin && (createsDirectory || copiesContents)) return true; + if (into === "" || ontoItself) return false; + return sources.some((source) => { + // A trailing separator keeps the directory's own name everywhere but rsync, + // where `src/` means what is in it. + if (head === "rsync" && /[\\/]$/.test(source)) return false; + // A remote source (`host:path`) lands under the name after the host. + const local = head === "scp" || head === "rsync" ? source.replace(/^[^/\\]{2,}:/, "") : source; + const name = baseName(local.replace(/[\\/]+$/, "")); + if (name === "" || name === "." || name === "..") return false; + if (lost && relativeWord(into) && couldBeEntryName(name)) return true; + const landing = `${into}/${name}`; + // A directory named `.bin` landing in a `node_modules` is the same swap. + const writtenLanding = `${written.replace(/[\\/]+$/, "")}/${name}`; + if ( + (NPM_BIN_DIRECTORY_RE.test(landing) || isBinDir(writtenLanding)) && + (head === "mv" || head === "ln" || recursive) + ) { + return true; + } + // A glob source puts names the line does not spell into the directory. + if (intoBin && GLOB_METACHAR_RE.test(name) && globCouldBeEntry(name)) return true; + if (!namesState(landing) && !landsOnState(`${written.replace(/[\\/]+$/, "")}/${name}`)) return false; + return !namesState(inShell(source)) || FAILPROOFAI_CODE_PATH_RE.test(landing) || landsOnState(`${written.replace(/[\\/]+$/, "")}/${name}`); + }); +} +/** The entry's own name and the Windows shims npm and bun write beside it. */ +const ENTRY_NAMES = ["failproofai", "failproofai.cmd", "failproofai.ps1", "failproofai.exe", "failproofai.bunx"]; +/** True when a one-segment glob could expand to the entry's name or a shim's. */ +function globCouldBeEntry(name: string): boolean { + const pattern = globTest(name, { ignoreCase: true }); + return pattern === null || ENTRY_NAMES.some((entry) => pattern.test(entry)); +} +/** + * True when this one simple command would destroy whatever it is pointed at. + * + * Reached only for a command that already names failproofai's state, so the + * question is narrow: is this a read, or is it everything else. + */ +function simpleCommandDestroysForState(words: string[], namesState: (text: string) => boolean): boolean { + if (words.length === 0) return false; + const head = commandBasename(words[0]); + const args = words.slice(1); + + // `find` is a read until one of its ACTIONS turns it into something else. + // `-delete` is the miss that started all of this; `-exec` runs anything at + // all, so it is judged by the command it hands the paths to, and an + // unrecognised one is treated as destructive rather than waved through. + if (head === "find") { + if (args.some((a) => a === "-delete")) return true; + // `-fprint ` and its siblings truncate the file they report INTO, so + // `find /etc -fprint ~/.failproofai/policies-config.json` empties the config + // while never descending into the state at all. + if (args.some((a) => FIND_WRITE_ACTIONS.has(a))) return true; + // EVERY `-exec`, not the first: `find … -exec cat {} + -o -exec rm {} +` + // put a read in front of the deleter and walked past a findIndex. + return args.some( + (a, i) => FIND_EXEC_ACTIONS.has(a) && !SAFE_EXEC_COMMANDS.has(commandBasename(args[i + 1] ?? "")), + ); + } + + // `sed -i` edits in place — and so does the `w` command inside a script, + // which needs no flag at all: `sed 's/a/b/w ' /etc/hosts` writes the + // state without `-i` anywhere on the line. + if (head === "sed") { + if (args.some((a) => a.startsWith("-i") || a.startsWith("--in-place"))) return true; + // The filename may ride in the same token (`'s/a/b/w'`) or in the + // next one, because a quoted script containing a space is two tokens by the + // time it gets here. `s/a/b/w` and a bare `w` both end in a `w` that + // follows a delimiter, which is what separates them from a word like `raw`. + return ( + args.some((a, i) => /(?:^|[;}/\s])w$/.test(a) && namesState(args[i + 1] ?? "")) || + args.some((a) => /(?:^|[;}/\s])w\s*\S*\.failproofai/.test(a)) || + sedWriteTargets(sedScriptArgs(args)).some((target) => namesState(target)) + ); + } + + // `awk` can run a shell (`system("rm -rf …")`) or pipe into one, so its + // program has to be read for those two, not just for the `>` the redirect + // scan already catches. + // An in-place edit writes the files it names, whatever reads them otherwise + // (`yq -i`, `awk -i inplace`, `perl -pi`, `ruby -i`; found by #1053's tests + // on #1058). + if (["yq", "awk", "gawk", "perl", "ruby"].includes(head) && writtenOperands(words).some(namesState)) return true; + + if (head === "awk" || head === "gawk" || head === "mawk") { + return args.some((a) => /system\s*\(|\|\s*["']|\|&/.test(a)); + } + + // Copying the state OUT is a backup. Copying anything ONTO it — classically + // `/dev/null` — empties it without naming a delete verb. The destination is + // the last operand, unless `-t` names it instead: `cp -t ~/.failproofai + // /dev/null` puts the destination FIRST and left the last operand innocent. + if (COPY_COMMANDS.has(head)) { + // `rsync --remove-source-files` deletes what it just copied, so the state + // being the SOURCE — the shape that makes every other copy a backup — is + // what makes this one a move. + if (args.includes("--remove-source-files") && args.some((a) => namesState(a))) return true; + const targetAt = args.findIndex((a) => a === "-t" || a === "--target-directory"); + if (targetAt !== -1 && namesState(args[targetAt + 1] ?? "")) return true; + if (args.some((a) => a.startsWith("--target-directory=") && namesState(a))) return true; + const operands = args.filter((a) => !a.startsWith("-")); + const destination = operands[operands.length - 1]; + return destination !== undefined && namesState(destination); + } + + // `tee` writes every operand it is given and reads none of them. + if (OPERAND_WRITE_COMMANDS.has(head)) { + return args.some((a) => !a.startsWith("-") && namesState(a)); + } + + // `uniq INPUT OUTPUT` and `xxd IN OUT`: the second operand is written. + if (SECOND_OPERAND_WRITERS.has(head)) { + const operands = args.filter((a) => !a.startsWith("-")); + return operands.length > 1 && namesState(operands[operands.length - 1]); + } + + // `git` normally carries the path as prose in a message or a body. + if (head === "git") { + const subcommand = gitSubcommand(args); + if (subcommand === undefined || !GIT_DESTRUCTIVE_SUBCOMMANDS.has(subcommand)) return false; + // A message names nothing it writes (a merge message that mentions the + // state): only the operands count, read as the settings walk reads them, + // a message running to the next option once quotes are gone. + const at = words.findIndex((word) => commandBasename(word) === "git"); + return gitOperandsNameTarget(words.slice(at === -1 ? 0 : at), subcommand, namesState, false); + } + + // A reader whose destination arrives as an option rather than as an operand. + // Checked before the allowlist, or `sort -o /dev/null` reads as the + // `sort` it is named after. + if (writesViaOutputFlagForState(head, args, namesState)) return true; + + if (STATE_READ_COMMANDS.has(head) || STATE_MENTION_COMMANDS.has(head)) return false; + return true; +} +/** + * The operands a simple command writes, apart from those it reads or deletes: + * every operand of `tee` and `truncate`, the destination of a copy, move or + * link, the last of `uniq` / `xxd`, `dd of=`, and what `sed -i` edits. + */ +function writtenOperands(words: string[]): string[] { + if (words.length === 0) return []; + const head = commandBasename(words[0]); + const args = words.slice(1); + const operands = args.filter((arg) => !arg.startsWith("-")); + if (OPERAND_WRITE_COMMANDS.has(head) || head === "truncate") return operands; + if (COPY_COMMANDS.has(head) || head === "mv" || head === "ln") return operands.slice(-1); + if (SECOND_OPERAND_WRITERS.has(head)) return operands.length > 1 ? operands.slice(-1) : []; + if (head === "dd") return args.filter((arg) => arg.startsWith("of=")).map((arg) => arg.slice(3)); + if (head === "sed" && args.some((arg) => arg.startsWith("-i") || arg.startsWith("--in-place"))) return operands; + // Other editors that rewrite their files in place (found by #1053's tests on + // #1058): `yq -i`, `awk -i inplace` (its first operand is the program), + // `perl -i` / `-pi`, `ruby -i`. + if (head === "yq" && args.some((arg) => arg === "-i" || arg === "--inplace" || /^-[A-Za-z]*i[A-Za-z]*$/.test(arg))) return operands; + if ((head === "awk" || head === "gawk") && args.some((arg, k) => arg === "-iinplace" || arg === "--include=inplace" || ((arg === "-i" || arg === "--include") && args[k + 1] === "inplace"))) { + return args.some((arg) => arg === "-f" || arg.startsWith("--file")) ? operands.filter((o) => o !== "inplace") : operands.filter((o) => o !== "inplace").slice(1); + } + if ((head === "perl" || head === "ruby") && args.some((arg) => /^-[A-Za-z]*i/.test(arg))) return operands; + return []; +} + +/** + * The sed script a command line carries: every `-e` / `--expression` value, + * or else its first operand. The files after it are files: reading every + * argument for `w` took `/Users/Wei/…` for a write (found by #1053's tests on + * #1058). Scripts read from `-f` files are checked separately. + */ +function sedScriptArgs(args: string[]): string[] { + const scripts: string[] = []; + let fromFile = false; + let first: string | undefined; + for (let k = 0; k < args.length; k++) { + const arg = args[k]; + if (arg === "--") { + first ??= args[k + 1]; + break; + } + if (arg === "-e" || arg === "--expression") scripts.push(args[++k] ?? ""); + else if (arg.startsWith("--expression=")) scripts.push(arg.slice("--expression=".length)); + else if (/^-[nrsuzE]*e./.test(arg)) scripts.push(arg.slice(arg.indexOf("e") + 1)); + else if (arg === "-f" || arg === "--file" || arg.startsWith("--file=") || /^-[nrsuzE]*f/.test(arg)) { + fromFile = true; + if (arg === "-f" || arg === "--file") k++; + } else if (arg === "-l" || arg === "--line-length") k++; + else if (!arg.startsWith("-") && first === undefined) first = arg; + } + if (scripts.length > 0 || fromFile) return scripts; + return first === undefined ? [] : [first]; +} +/** + * Whether a pipeline hands text naming failproofai's state or code to a bare + * shell or interpreter, which runs it as its program: `echo 'rm -rf + * ~/.failproofai' | sh`. Read as the settings walk reads it. + */ +function pipesStateIntoShell(command: string): boolean { + const lexed = lexShell(command); + for (const [start, end] of cutRanges(lexed.splittable, PIPELINE_SEPARATORS)) { + const readable = lexed.readable.slice(start, end); + const simples = cutRanges(lexed.splittable.slice(start, end), /\|/); + for (let i = 1; i < simples.length; i++) { + if (!quoteAwareCommandWords(readable.slice(simples[i][0], simples[i][1])).readsStdinProgram) continue; + const upstream = readable.slice(0, simples[i][0]); + if (FAILPROOFAI_STATE_TARGET.namesLiteral(upstream) || FAILPROOFAI_STATE_TARGET.namesLiteral(stripShellQuoting(upstream))) return true; + } + } + return false; +} + +/** How many texts the parameter defaults on one line are read in. */ +const MAX_DEFAULT_VARIANTS = 64; + +/** + * The line with its parameter defaults and alternates filled in, innermost + * first: `${X:-word}`, `${X-word}`, `${X:=word}` as `word` (what the shell uses + * when X is unset), `${X:+word}` / `${X+word}` as `word` and as nothing. The + * line as written is not among them. Bounded: past MAX_DEFAULT_VARIANTS texts + * the rest are dropped, and each of those words is still read as written. + */ +function parameterDefaultVariants(command: string): string[] { + if (!command.includes("${")) return []; + const INNER = /\$\{[#!]?[A-Za-z_][A-Za-z0-9_]*(:?[-=+?])([^{}]*)\}/; + let texts = [command]; + for (let round = 0; round < 32; round++) { + let changed = false; + const next: string[] = []; + for (const text of texts) { + const m = INNER.exec(text); + if (!m) { + next.push(text); + continue; + } + changed = true; + const before = text.slice(0, m.index); + const after = text.slice(m.index + m[0].length); + const op = m[1].replace(":", ""); + if (op === "+") next.push(before + m[2] + after, before + after); + else if (op === "?") next.push(before + after); + else next.push(before + m[2] + after); + } + texts = [...new Set(next)].slice(0, MAX_DEFAULT_VARIANTS); + if (!changed) break; + } + return texts.filter((text) => text !== command); +} + +/** + * The files a sed script writes: its `w` / `W` commands and the `w` flag of + * `s///`, with the name glued on (`wnode_modules/.bin/failproofai`) or after + * spaces, running to the end of the line as GNU sed reads it, and also cut at + * `;` or `}`, which a reader might take for its end. Read from every argument, + * so a match inside a regex can only add a name to check (found by hermes on + * FailproofAI/failproofai#1058). + */ +function sedWriteTargets(args: string[]): string[] { + const targets: string[] = []; + for (const arg of args) { + for (let i = 0; i < arg.length; i++) { + if (arg[i] !== "w" && arg[i] !== "W") continue; + // A `w` that starts a command or is an `s///` flag: at the start, after + // a separator or an address (`1w`, `$w`, `1,5w`, `0~2w`, `1!w`, `/re/w`; + // found by hermes on FailproofAI/failproofai#1058), or after a delimiter + // and other flags (`s/a/b/gw`). After a letter it is part of a word. + let j = i - 1; + while (j >= 0 && (arg[j] === " " || arg[j] === "\t")) j--; + let k = j; + while (k >= 0 && /[gpiImMeE0-9]/.test(arg[k])) k--; + const starts = j < 0 || !/[A-Za-z_\\]/.test(arg[j]) || (k >= 0 && k < j && !/[\w\s\\]/.test(arg[k])); + if (!starts) continue; + if (targets.length >= MAX_SED_TARGETS) throw new Error("a sed script names too many files to check"); + const end = arg.indexOf("\n", i); + const name = arg.slice(i + 1, Math.min(end === -1 ? arg.length : end, i + 1 + PATH_MAX_BYTES)).trim(); + if (name === "") continue; + targets.push(name); + const cut = name.split(/[;}]/)[0].trim(); + if (cut !== "" && cut !== name) targets.push(cut); + } + } + return targets; +} +/** More files than a sed script writes in practice; past it the line is refused unread. */ +const MAX_SED_TARGETS = 64; +/** Larger than a file of instructions (a sed script, a patch, a curl config) is read; past it, it is read as writing what is protected. */ +const MAX_INSTRUCTION_FILE_BYTES = 1024 * 1024; +/** curl's short options that take a value (curl 8 `--help all`); the rest of a cluster after one is that value. */ +const CURL_SHORT_VALUE_OPTIONS = "AbcCdDeEFHKmoPQrtTuUwxXyYz"; +/** + * bash's integer argument for `%d` and friends. Where the rest is not a number + * bash reports an error and still prints the valid prefix it read (`16junk` is + * 16, `abc` is 0; found by hermes on #1058), so that is the value. Null only + * past what a number holds exactly. + */ +function bashPrintfInteger(arg: string): number | null { + const text = arg.trim(); + if (/^['"]/.test(text)) return text.length > 1 ? (text.codePointAt(1) ?? 0) : 0; + const m = /^([+-]?)(0[xX][0-9a-fA-F]+|0[0-7]*|[1-9][0-9]*)/.exec(text); + if (m === null) return 0; + const digits = m[2]; + const magnitude = /^0[xX]/.test(digits) ? parseInt(digits.slice(2), 16) : digits.length > 1 && digits.startsWith("0") ? parseInt(digits.slice(1), 8) : parseInt(digits, 10); + if (!Number.isSafeInteger(magnitude)) return null; + return m[1] === "-" ? -magnitude : magnitude; +} + +/** bash's floating-point argument for `%f`, `%e` and `%g`: its valid prefix, or 0. */ +function bashPrintfFloat(arg: string): number { + const text = arg.trim(); + if (/^['"]/.test(text)) return text.length > 1 ? (text.codePointAt(1) ?? 0) : 0; + const hex = /^[+-]?0[xX][0-9a-fA-F]+/.exec(text); + if (hex) return parseInt(hex[0], 16); + const m = /^[+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/.exec(text); + return m ? Number(m[0]) : 0; +} + +/** C's `%e` exponent: at least two digits (`1.6e+01`). */ +const cExponent = (text: string): string => text.replace(/e([+-])(\d)$/, "e$10$2"); + +/** `%f`, `%e` or `%g` of `n` as C prints it, or null where this does not compute it. */ +function cFloat(n: number, c: string, precision: number | undefined, alternate: boolean): string | null { + if (!Number.isFinite(n) || Math.abs(n) >= 1e21) return null; + const lower = c.toLowerCase(); + let out: string; + if (lower === "f") out = n.toFixed(precision ?? 6); + else if (lower === "e") out = cExponent(n.toExponential(precision ?? 6)); + else if (lower === "g") { + const p = precision === 0 ? 1 : (precision ?? 6); + const x = n === 0 ? 0 : Math.floor(Math.log10(Math.abs(n))); + out = p > x && x >= -4 ? n.toFixed(Math.max(0, p - 1 - x)) : cExponent(n.toExponential(p - 1)); + if (!alternate) out = out.replace(/\.(\d*?)0+(e|$)/, (_m, d: string, tail: string) => (d === "" ? "" : `.${d}`) + tail).replace(/\.(e|$)/, "$1"); + } else return null; + return c === lower ? out : out.toUpperCase(); +} +/** + * `printf FORMAT ARGS…` as bash computes it, for `%s`, `%b` (escapes left in, + * so the caller can refuse them), `%q` of a plain word, `%c` and the integer + * conversions `%d`, `%i`, `%u`, `%o`, `%x`, `%X`, with the flags `-`, `0`, + * `+`, space and `#`, a width and a precision, the format reused until the + * arguments run out. Null for anything else: a `*` width, a conversion it does + * not compute, or an argument bash would reject. + */ +function bashPrintf(format: string, args: readonly string[]): string | null { + const SPEC = /%(%|([-0+ #]*)(\d*)(?:\.(\d*))?([^%]?))/g; + const conversions = (format.match(/%[^%]/g) ?? []).length; + let k = 0; + let out = ""; + let passes = 0; + const pad = (text: string, width: number, left: boolean, zero: boolean): string => { + if (text.length >= width) return text; + if (left) return text + " ".repeat(width - text.length); + if (!zero) return " ".repeat(width - text.length) + text; + const sign = /^[+ -]/.test(text) ? text[0] : ""; + const prefix = /^[+ -]?0[xX]/.test(text) ? text.slice(sign.length, sign.length + 2) : ""; + const digits = text.slice(sign.length + prefix.length); + return sign + prefix + "0".repeat(width - text.length) + digits; + }; + do { + let failed = false; + out += format.replace(SPEC, (whole, spec: string, flags = "", widthText = "", precisionText: string | undefined, c = "") => { + if (spec === "%") return "%"; + if (/[*]/.test(whole) || widthText.length > 4 || (precisionText ?? "").length > 4) { + failed = true; + return ""; + } + const arg = args[k++] ?? ""; + const width = widthText === "" ? 0 : Number(widthText); + const precision = precisionText === undefined ? undefined : precisionText === "" ? 0 : Number(precisionText); + const left = flags.includes("-"); + let text: string; + if (c === "s" || c === "b") text = precision === undefined ? arg : arg.slice(0, precision); + else if (c === "c") text = arg.charAt(0); + else if (c === "q") { + if (arg === "" || !/^[A-Za-z0-9_./:@%+=,-]*$/.test(arg)) { + failed = true; + return ""; + } + text = arg; + } else if (c !== "" && "diuoxX".includes(c)) { + const n = arg === "" ? 0 : bashPrintfInteger(arg); + // A negative number in an unsigned form is its 64-bit two's complement, past what a number holds exactly. + if (n === null || (n < 0 && c !== "d" && c !== "i")) { + failed = true; + return ""; + } + let digits = c === "o" ? n.toString(8) : c === "x" ? n.toString(16) : c === "X" ? n.toString(16).toUpperCase() : String(Math.abs(n)); + if (precision !== undefined) digits = precision === 0 && n === 0 ? "" : digits.padStart(precision, "0"); + if (flags.includes("#") && n !== 0) digits = c === "o" ? (digits.startsWith("0") ? digits : `0${digits}`) : c === "x" ? `0x${digits}` : c === "X" ? `0X${digits}` : digits; + const sign = (c === "d" || c === "i") && n < 0 ? "-" : (c === "d" || c === "i") && flags.includes("+") ? "+" : (c === "d" || c === "i") && flags.includes(" ") ? " " : ""; + return pad(sign + digits, width, left, flags.includes("0") && precision === undefined); + } else if (c !== "" && "fFeEgG".includes(c)) { + // Floating point, as C prints it (`%.0f` of 16 is 16; found by hermes on #1058). + const n = bashPrintfFloat(arg); + const printed = cFloat(n, c, precision, flags.includes("#")); + if (printed === null) { + failed = true; + return ""; + } + const signed = n >= 0 && flags.includes("+") ? `+${printed}` : n >= 0 && flags.includes(" ") ? ` ${printed}` : printed; + return pad(signed, width, left, flags.includes("0")); + } else { + failed = true; + return ""; + } + return pad(text, width, left, false); + }); + if (failed) return null; + } while (conversions > 0 && k < args.length && ++passes < 64); + return k < args.length ? null : out; +} +/** tar's short options other than `-C` that take a value (GNU tar and bsdtar). */ +const TAR_SHORT_VALUE_OPTIONS = "fbFgHIKLNTVX"; +/** How many curl configs deep one may name the next before the command is refused. */ +const MAX_CURL_CONFIG_DEPTH = 8; +/** + * The options a curl config file gives, as the words they would be on the + * line: `output = hook`, `-o hook`, `--output-dir bins` and `remote-name`, + * one per line, a value quoted or not, `#` starting a comment. + */ +function curlConfigArgs(text: string): string[] { + const args: string[] = []; + for (const line of text.split(/\r?\n/)) { + const trimmed = line.trim(); + if (trimmed === "" || trimmed.startsWith("#")) continue; + const m = /^(-{0,2}[A-Za-z0-9][\w-]*)(?:\s*[=:]\s*|\s+|$)(.*)$/.exec(trimmed); + if (m === null) continue; + const option = m[1].startsWith("-") ? m[1] : m[1].length === 1 ? `-${m[1]}` : `--${m[1]}`; + args.push(option); + const value = m[2].trim(); + if (value !== "") args.push(value.replace(/^"((?:[^"\\]|\\.)*)"$/, "$1").replace(/\\(.)/g, "$1")); + } + return args; +} +/** + * The script files a sed command line reads: `-f FILE` (alone, glued, or + * ending a cluster such as `-nf`) and `--file=FILE` / `--file FILE` in any + * abbreviation GNU sed takes (`--fi`). + */ +function sedScriptFiles(args: string[]): string[] { + const files: string[] = []; + for (let k = 0; k < args.length; k++) { + const arg = args[k]; + if (arg === "--") break; + if (arg.startsWith("--")) { + const eq = arg.indexOf("="); + const name = arg.slice(2, eq === -1 ? undefined : eq); + if (name !== "" && "file".startsWith(name) && !"follow-symlinks".startsWith(name)) { + files.push(eq === -1 ? (args[++k] ?? "") : arg.slice(eq + 1)); + } else if (eq === -1 && name !== "" && ["expression", "line-length"].some((option) => option.startsWith(name))) k++; + continue; + } + if (!/^-[A-Za-z]/.test(arg)) continue; + for (let c = 1; c < arg.length; c++) { + if (arg[c] === "f") { + files.push(c + 1 < arg.length ? arg.slice(c + 1) : (args[++k] ?? "")); + break; + } + // `-e SCRIPT` and `-l N` take a value; `-i` takes the rest as a suffix. + if (arg[c] === "e" || arg[c] === "l") { + if (c + 1 === arg.length) k++; + break; + } + if (arg[c] === "i") break; + } + } + return files; +} +/** What the shell splits a line at, when it is not quoted or escaped. */ +const SEPARATOR_CHARS = /[;&|\n\r]/; +/** + * `text` split at `separator`, the separators kept between the pieces as + * `String.split` keeps a capture group, except where a separator is quoted or + * escaped: the shell reads that as text, so `sed -e 's/w/x/;1whook'` keeps its + * whole script (found by hermes on FailproofAI/failproofai#1058). The pieces + * are the text as written. + */ +function splitUnquoted(text: string, separator: RegExp): string[] { + const chars: string[] = []; + let quote: "'" | '"' | null = null; + for (let i = 0; i < text.length; i++) { + const ch = text[i]; + if (ch === "\\" && quote !== "'" && i + 1 < text.length) { + chars.push(ch, SEPARATOR_CHARS.test(text[i + 1]) ? "\u0001" : text[i + 1]); + i++; + continue; + } + if (quote === null) { + if (ch === "'" || ch === '"') quote = ch; + chars.push(ch); + continue; + } + if (ch === quote) quote = null; + chars.push(quote !== null && SEPARATOR_CHARS.test(ch) ? "\u0001" : ch); + } + const out: string[] = []; + let offset = 0; + for (const piece of chars.join("").split(new RegExp(`(${separator.source})`))) { + out.push(text.slice(offset, offset + piece.length)); + offset += piece.length; + } + return out; +} +/** + * True when a flag on this command names the state as an output file. + * + * `sort -o`, `tree -o` and `curl -o` all take their destination as an option, + * so nothing about the head or the operand order says they are writing — and + * all three heads were on a list that said they only read. Short options bundle + * (`curl -sfo `), so the trailing letter is what decides. + */ +function writesViaOutputFlagForState(head: string, args: string[], namesState: (text: string) => boolean): boolean { + const flags = OUTPUT_FLAG_COMMANDS[head]; + if (!flags) return false; + for (let i = 0; i < args.length; i++) { + const arg = args[i]; + const long = flags.find((f) => f.startsWith("--") && arg.startsWith(`${f}=`)); + if (long && (namesState(arg) || namesState(arg.slice(long.length + 1)))) return true; + // A long option as getopt_long and curl before 8 also take it, cut short + // to a prefix of its name (`--stde`, `--outp=`), unless that prefix is + // itself another option (`--cookie`, which reads). + if (arg.startsWith("--") && arg.length > 2) { + const eq = arg.indexOf("="); + const name = arg.slice(2, eq === -1 ? undefined : eq); + if (!flags.includes(`--${name}`) && !EXACT_NON_OUTPUT_OPTIONS.has(`${head} --${name}`) && flags.some((f) => f.startsWith(`--${name}`))) { + if (namesState(eq === -1 ? (args[i + 1] ?? "") : arg.slice(eq + 1))) return true; + } + } + const bundled = /^-[A-Za-z]*[oDc]$/.test(arg) && flags.includes(`-${arg[arg.length - 1]}`); + if ((flags.includes(arg) || bundled) && namesState(args[i + 1] ?? "")) return true; + // Or the value glued on, after the option alone or at the end of a + // cluster: `curl -o`, `curl -so`. + if (/^-[A-Za-z]/.test(arg)) { + for (let c = 1; c < arg.length - 1 && /[A-Za-z]/.test(arg[c]); c++) { + if (flags.includes(`-${arg[c]}`) && namesState(arg.slice(c + 1))) return true; + } + } + } + return false; +} +/** wget's short options that take a value (`wget --help`, GNU Wget 1.21). */ +const WGET_VALUE_OPTIONS = "eoaiBtOTwQPlARDIXU"; +/** curl's short options that take a value (`curl --help all`, curl 8). */ +const CURL_VALUE_OPTIONS = "AbcCdDEeFHKmoPQrTtuUwxXyYz"; +/** Short options that take a value, for the commands whose list is known. */ +const SHORT_VALUE_OPTIONS: Record = { curl: CURL_VALUE_OPTIONS, wget: WGET_VALUE_OPTIONS }; +/** Short options that name a file the command writes, for the commands whose list is known. */ +const SHORT_OUTPUT_OPTIONS: Record = { curl: "oDc", wget: "Oao" }; +/** + * The long options that decide where a download lands. curl before 8 and + * wget (getopt_long) also take an unambiguous abbreviation of a long option + * (`--output-di` for `--output-dir`; found by hermes on + * FailproofAI/failproofai#1058), so a name that only starts one of these is + * read as each it may be. One two options share is refused by both tools, so + * reading it as either never misses a landing. + */ +const CURL_LANDING_OPTIONS = ["output", "output-dir", "remote-name", "remote-name-all", "remote-header-name", "next"]; +const WGET_LANDING_OPTIONS = [ + "directory-prefix", + "output-document", + "spider", + "content-disposition", + "trust-server-names", + "input-file", + "recursive", + "mirror", + "page-requisites", + "force-directories", + "no-directories", + "default-page", + "execute", +]; +const LANDING_VALUE_OPTIONS = new Set(["output", "output-dir", "directory-prefix", "output-document", "input-file", "default-page", "execute"]); +/** The landing options `--` may be, for curl or wget. */ +function landingOptions(head: string, written: string): string[] { + const options = head === "wget" ? WGET_LANDING_OPTIONS : CURL_LANDING_OPTIONS; + if (options.includes(written)) return [written]; + return written === "" ? [] : options.filter((option) => option.startsWith(written)); +} +/** + * wget's `-e` / `--execute` runs a `.wgetrc` command, whose name wget reads + * without case, `_` or `-` (`-e dir_prefix=node_modules/.bin`): the ones that + * decide where a download lands, as the long option each stands for. + */ +const WGETRC_LANDING_COMMANDS: Record = { + dirprefix: "directory-prefix", + outputdocument: "output-document", + spider: "spider", + contentdisposition: "content-disposition", + trustservernames: "trust-server-names", + recursive: "recursive", + mirror: "mirror", + pagerequisites: "page-requisites", + dirstruct: "force-directories", + defaultpage: "default-page", +}; +/** More letters than a short-option cluster has when written to be read. */ +const MAX_OPTION_CLUSTER = 32; +/** More paths than a glob in a directory component is expanded to on disk; past it, read as reaching the state. */ +const GLOB_DISK_LIMIT = 4096; +/** Directories one `**` may walk through before the walk is given up and read as reaching the state. */ +const GLOB_RECURSIVE_DIR_LIMIT = 16_384; +/** Whether a path component is a pattern to the shell, zsh's flags included. */ +function isGlobPart(part: string): boolean { + return GLOB_METACHAR_RE.test(part) || ZSH_GLOB_FLAG_RE.test(part); +} +/** A component's pattern as a regex, zsh's flags taken off; null when it cannot be read. */ +function globPartMatcher(part: string, options: GlobOptions): GlobTest | null { + return globTest(part.replace(new RegExp(ZSH_GLOB_FLAG_RE.source, "g"), ""), { ignoreCase: options.nocaseglob }); +} +/** How many of the words a brace expands to are each read on disk. */ +const MAX_BRACE_WORDS_ON_DISK = 64; +/** How many values of reassigned variables one line is read with; past it the line is refused. */ +const VARIANT_BUDGET = 4096; +/** + * The values an option word may carry glued on, each a path the command may + * write: `--output=`, and the rest of a short-option cluster, + * `curl -so`. Where a command's value-taking letters are known the + * cluster is read as getopt reads it, flags up to the first letter that takes + * a value; elsewhere any letter may take one (`gcc -o`, `tar -cf`), + * so the rest of the word after each letter is a candidate. `null` for a + * cluster longer than `MAX_OPTION_CLUSTER`, which is read as reaching the + * state rather than tried at every split. + */ +function gluedOptionValues(head: string, word: string): string[] | null { + if (word.startsWith("--")) { + const eq = word.indexOf("="); + return eq > 2 && eq < word.length - 1 ? [word.slice(eq + 1)] : []; + } + if (!/^-[A-Za-z]/.test(word)) return []; + const known = SHORT_VALUE_OPTIONS[head]; + const values: string[] = []; + for (let c = 1; c < word.length - 1 && /[A-Za-z]/.test(word[c]); c++) { + if (known !== undefined) { + if (known.includes(word[c])) return [word.slice(c + 1)]; + continue; + } + if (c > MAX_OPTION_CLUSTER) return null; + values.push(word.slice(c + 1)); + } + return values; +} +/** + * The files a download names after its URL rather than on the line, as + * `{dir, name}`: `wget `, and `curl -O` / `--remote-name`, save the URL's + * last segment into `-P` / `--directory-prefix` (wget), `--output-dir` (curl) + * or the current directory. So `cd node_modules/.bin && wget https://…/failproofai` + * writes the entry with `.bin/failproofai` nowhere on the line + * (FailproofAI/agenteye#1795). `name` is `null` when the server picks it + * (`--content-disposition`, `-J`), or the URLs come from a file (`-i`): then + * it could be anything, the entry's included. A name the line gives (`-O` + * for wget, `-o` for curl) is judged with the other operands, and a recursive + * wget puts what it fetches under a directory named after the host. + */ +function downloadLandings(words: string[]): Array<{ dir: string; name: string | null }> { + const head = words.length > 0 ? commandBasename(words[0]) : ""; + if (head !== "wget" && head !== "curl") return []; + // curl's `--next` (`-:`) starts a transfer with options of its own: each is + // read alone, so a later `--output-dir` cannot stand in for an earlier one + // (found by hermes on FailproofAI/failproofai#1058). + if (head === "curl") { + const transfers: string[][] = [[]]; + for (const word of words.slice(1)) { + if (word === "-:" || (word.startsWith("--") && !word.includes("=") && landingOptions(head, word.slice(2)).includes("next"))) transfers.push([]); + else transfers[transfers.length - 1].push(word); + } + if (transfers.length > 1) return transfers.flatMap((transfer) => transferLandings(head, transfer)); + } + return transferLandings(head, words.slice(1)); +} +/** `downloadLandings` for one transfer's arguments. */ +function transferLandings(head: string, args: string[]): Array<{ dir: string; name: string | null }> { + const valueOptions = head === "wget" ? WGET_VALUE_OPTIONS : CURL_VALUE_OPTIONS; + let dir = "."; + let urlNamed = head === "wget"; + let serverNamed = false; + let named = false; + let recursive = false; + let flat = false; + let dirGiven = false; + // The name wget gives a URL that ends in `/`. + let defaultPage = "index.html"; + // What curl's `-o` / `--output` name, which `--output-dir` also prefixes. + const outputs: string[] = []; + const urls: string[] = []; + const apply = (option: string, value: string | undefined) => { + if (option === "directory-prefix" || option === "output-dir") { + dir = value ?? dir; + dirGiven = true; + } else if (option === "output") outputs.push(value ?? ""); + else if (option === "output-document" || option === "spider") named = true; + else if (option === "remote-name" || option === "remote-name-all") urlNamed = true; + else if (option === "content-disposition" || option === "remote-header-name" || option === "input-file" || option === "trust-server-names") { + serverNamed = true; + } else if (option === "recursive" || option === "mirror" || option === "page-requisites" || option === "force-directories") recursive = true; + else if (option === "no-directories") flat = true; + else if (option === "default-page") defaultPage = value ?? defaultPage; + else if (option === "execute" && value !== undefined) { + const eq = value.indexOf("="); + const command = WGETRC_LANDING_COMMANDS[value.slice(0, eq === -1 ? undefined : eq).replace(/[\s_-]/g, "").toLowerCase()]; + if (command !== undefined) apply(command, eq === -1 ? undefined : value.slice(eq + 1).trim()); + } + }; + for (let i = 0; i < args.length; i++) { + const arg = args[i]; + if (arg === "--") { + urls.push(...args.slice(i + 1)); + break; + } + if (arg.startsWith("--")) { + const eq = arg.indexOf("="); + const options = landingOptions(head, arg.slice(2, eq === -1 ? undefined : eq)); + const value = eq !== -1 ? arg.slice(eq + 1) : options.some((option) => LANDING_VALUE_OPTIONS.has(option)) ? args[++i] : undefined; + for (const option of options) apply(option, value); + continue; + } + if (arg.startsWith("-") && arg.length > 1) { + // wget's two-letter `-n?` options (`-nd`, `-nH`, `-nc`, `-np`, `-nv`). + if (head === "wget" && /^-n[A-Za-z]$/.test(arg)) { + if (arg === "-nd") flat = true; + continue; + } + for (let c = 1; c < arg.length; c++) { + const flag = arg[c]; + if (valueOptions.includes(flag)) { + const value = c + 1 < arg.length ? arg.slice(c + 1) : args[++i]; + if (head === "wget" && flag === "P") apply("directory-prefix", value); + if (head === "curl" && flag === "o") apply("output", value); + if (head === "wget" && flag === "O") named = true; + if (head === "wget" && flag === "i") serverNamed = true; + if (head === "wget" && flag === "e") apply("execute", value); + break; + } + if (head === "curl" && flag === "O") urlNamed = true; + if (head === "curl" && flag === "J") serverNamed = true; + if (head === "wget" && "rmpx".includes(flag)) recursive = true; + } + continue; + } + urls.push(arg); + } + // curl puts a file `-o` names in `--output-dir` as well, an absolute name + // too (joined, not replaced): `--output-dir node_modules/.bin -o failproofai` + // and `-o /failproofai` both write the entry (found by hermes on + // FailproofAI/failproofai#1058). + const landings: Array<{ dir: string; name: string | null }> = + head === "curl" && dirGiven ? outputs.filter((output) => output !== "" && output !== "-").map((name) => ({ dir, name })) : []; + if (!urlNamed || named || (recursive && !flat)) return landings; + if (serverNamed || recursive) return [...landings, { dir, name: null }]; + for (const url of urls) { + // The last segment of the path, without the scheme, host, query or + // fragment, as written and percent-decoded. + const path = url.replace(/^[A-Za-z][\w+.-]*:\/\/[^/?#]*/, "").replace(/[?#][\s\S]*$/, ""); + const last = path.slice(path.lastIndexOf("/") + 1); + let decoded = last; + try { + decoded = decodeURIComponent(last); + } catch { + // Not valid percent-encoding: the name as written is what lands. + } + // wget saves a URL that ends in `/` as `--default-page`, `index.html` + // unless the line names another (`--default-page=failproofai`). + if (last === "" && head === "wget") landings.push({ dir, name: defaultPage }); + for (const name of new Set([last, decoded])) if (name !== "") landings.push({ dir, name }); + } + return landings; +} +/** + * A `$name` or `${…}` reference starting at `word[i]`, a `$`: where it ends, + * the variable it reads (`""` for one this does not read, such as `$1`, + * `${a[0]}` or `${!prefix*}`), and the operator and word after the name. + */ +type ParameterReference = { end: number; name: string; op: string; arg: string; indirect: boolean; count: boolean }; +/** The word whose brace table `closingBraceOf` holds, and that table. */ +let braceTableWord: string | null = null; +let braceTable: Int32Array = new Int32Array(0); + +/** + * Where the `}` closing the `{` at `open` is in `word`, past backslash + * escapes, or -1 when it is never closed. Every brace of a word is matched in + * one pass and kept for the next call on the same word: scanning to the end + * for each `${` was quadratic, and 50,000 unclosed `${` took 6 s a pass + * (found by #1053's tests on #1058). + */ +function closingBraceOf(word: string, open: number): number { + if (braceTableWord !== word) { + const table = new Int32Array(word.length).fill(-1); + const stack: number[] = []; + for (let k = 0; k < word.length; k++) { + if (word[k] === "\\") k++; + else if (word[k] === "{") stack.push(k); + else if (word[k] === "}" && stack.length > 0) table[stack.pop()!] = k; + } + braceTableWord = word; + braceTable = table; + } + return braceTable[open] ?? -1; +} + +function readParameterReference(word: string, i: number): ParameterReference | null { + if (word[i + 1] !== "{") { + const name = /^[A-Za-z_][A-Za-z0-9_]*/.exec(word.slice(i + 1, i + 257))?.[0]; + return name === undefined ? null : { end: i + 1 + name.length, name, op: "", arg: "", indirect: false, count: false }; + } + const j = closingBraceOf(word, i + 1); + if (j === -1) return null; + const body = word.slice(i + 2, j); + const indirect = body.startsWith("!"); + const count = !indirect && body.startsWith("#") && body.length > 1; + const from = indirect || count ? 1 : 0; + const name = /^[A-Za-z_][A-Za-z0-9_]*/.exec(body.slice(from))?.[0]; + const unread = { end: j + 1, name: "", op: "", arg: "", indirect, count }; + if (name === undefined) return unread; + const rest = body.slice(from + name.length); + const op = /^(?::[-=+?]|[-=+?]|##?|%%?|\/[/#%]?|\^\^?|,,?|@|:)/.exec(rest)?.[0] ?? ""; + if ((op === "" && rest !== "") || ((indirect || count) && op !== "")) return unread; + return { end: j + 1, name, op, arg: rest.slice(op.length), indirect, count }; +} +/** + * A glob as an expression for a whole string, or `null` for one that makes + * none. `parameter`: a `${v%pattern}`-style pattern, where `*` and `?` match + * `/` too (`${A%%/*}` of `long/out/x` is `long`; found by hermes on + * FailproofAI/failproofai#1058), not a path component. + */ +function wholeGlob(pattern: string, parameter = false): GlobTest | null { + return globTest(pattern, { anyOne: parameter ? "." : "[^/]" }); +} +/** Longer than a value an operator's pattern is matched against, position by position. */ +const MAX_OPERATED_VALUE = 512; +/** + * `${name}` for a variable holding `value`, as bash computes it, for + * the operators that change the value: trimming (`#`, `%`), replacing (`/`), + * case (`^`, `,`, `@U`), quoting (`@Q`) and substrings (`:2:3`). `null` for one + * this does not compute, which is then read as a value the walk cannot know. + */ +function applyParameterOperator(value: string, op: string, arg: string): string | null { + if (op === "^^" || (op === "@" && arg === "U")) return value.toUpperCase(); + if (op === ",," || (op === "@" && arg === "L")) return value.toLowerCase(); + if (op === "^" || (op === "@" && arg === "u")) return value.charAt(0).toUpperCase() + value.slice(1); + if (op === ",") return value.charAt(0).toLowerCase() + value.slice(1); + if (op === "@") return arg === "Q" ? `'${value.replace(/'/g, "'\\''")}'` : null; + if (op === ":") { + const m = /^\s*(-?\d{1,6})\s*(?::\s*(-?\d{1,6})\s*)?$/.exec(arg); + if (m === null) return null; + const start = Number(m[1]) < 0 ? Math.max(0, value.length + Number(m[1])) : Math.min(value.length, Number(m[1])); + if (m[2] === undefined) return value.slice(start); + const length = Number(m[2]); + return length < 0 ? value.slice(start, Math.max(start, value.length + length)) : value.slice(start, start + length); + } + if (value.length > MAX_OPERATED_VALUE) return null; + if (op === "#" || op === "##" || op === "%" || op === "%%") { + const re = wholeGlob(arg, true); + if (re === null) return null; + const cuts = Array.from({ length: value.length + 1 }, (_, k) => k); + // Shortest first; `##` and `%%` take the longest (found by hermes on FailproofAI/failproofai#1058). + if (op === "##" || op === "%%") cuts.reverse(); + for (const k of cuts) { + if (op.startsWith("#") ? re.test(value.slice(0, k)) : re.test(value.slice(value.length - k))) { + return op.startsWith("#") ? value.slice(k) : value.slice(0, value.length - k); + } + } + return value; + } + // `/pattern/string`, `//` for every match, `/#` at the start, `/%` at the end. + let slash = -1; + for (let k = 0; k < arg.length; k++) { + if (arg[k] === "\\") k++; + else if (arg[k] === "/") { + slash = k; + break; + } + } + const pattern = slash === -1 ? arg : arg.slice(0, slash); + const replacement = slash === -1 ? "" : arg.slice(slash + 1); + const re = wholeGlob(pattern, true); + if (re === null || pattern === "") return re === null ? null : value; + if (op === "/#") { + for (let k = value.length; k > 0; k--) if (re.test(value.slice(0, k))) return replacement + value.slice(k); + return value; + } + if (op === "/%") { + for (let k = 0; k < value.length; k++) if (re.test(value.slice(k))) return value.slice(0, k) + replacement; + return value; + } + let out = ""; + let pos = 0; + let replaced = false; + while (pos < value.length) { + let end = -1; + if (!(replaced && op === "/")) { + for (let k = value.length; k > pos; k--) { + if (re.test(value.slice(pos, k))) { + end = k; + break; + } + } + } + if (end === -1) { + out += value[pos++]; + continue; + } + out += replacement; + replaced = true; + pos = end; + } + return out; +} +/** + * What `word` may expand to, each `$name` and `${…}` in it read with every + * value `valuesOf` gives the variable: none for one the line never sets, which + * stays written as it is, as one whose value the walk cannot know. A + * `${name:-word}`-style default or `${name:+word}` alternate is also read for + * a variable it does not know, `${!name}` through the variable it names, and + * a value that refers to another variable through that one's values too. + * `null` past `limit` results. + */ +function expandParameters( + word: string, + valuesOf: (name: string) => readonly string[], + limit: number, + depth = 0, + memo = new Map(), +): string[] | null { + let results = [""]; + let literal = 0; + // A result longer than PATH_MAX names no file anything can open, so it is + // dropped as it grows: a value that refers to itself (`A=$A$A…`) doubles + // with every reading. + // + // The PAIRS are bounded, not only the results: a pair past PATH_MAX is + // dropped without growing `next`, so a self-doubling value made `limit` × + // `limit` concatenations per reference (0.9 s for 40 `A=${A}${A}`) while + // `next` stayed small. Past the bound the word is too complex to follow, as + // `wordForms` already rules for the same product. + const append = (alternatives: readonly string[]): boolean => { + if (results.length * alternatives.length > limit) return false; + const next = new Set(); + for (const result of results) { + for (const alternative of alternatives) { + if (result.length + alternative.length > PATH_MAX_BYTES) continue; + next.add(result + alternative); + if (next.size > limit) return false; + } + } + results = [...next]; + return true; + }; + for (let i = 0; i < word.length; i++) { + if (word[i] !== "$") continue; + const reference = readParameterReference(word, i); + if (reference === null) continue; + const written = word.slice(i, reference.end); + const alternatives = parameterAlternatives(reference, written, valuesOf, limit, depth, memo); + if (alternatives === null || !append([word.slice(literal, i)]) || !append(alternatives)) return null; + literal = reference.end; + i = reference.end - 1; + } + return append([word.slice(literal)]) ? results : null; +} +/** The values one reference in `expandParameters` may take. */ +function parameterAlternatives( + reference: ParameterReference, + written: string, + valuesOf: (name: string) => readonly string[], + limit: number, + depth: number, + memo: Map, +): string[] | null { + if (reference.name === "") return [written]; + const deeper = (text: string): string[] | null => { + if (depth >= 3 || !text.includes("$")) return [text]; + const key = `${depth}\u0000${text}`; + if (!memo.has(key)) memo.set(key, expandParameters(text, valuesOf, limit, depth + 1, memo)); + return memo.get(key)!; + }; + const argument = (): string[] | null => deeper(reference.arg); + let values: readonly string[] = valuesOf(reference.name); + if (reference.indirect) { + if (values.length === 0 || values.some((value) => !/^[A-Za-z_][A-Za-z0-9_]*$/.test(value))) return [written]; + values = values.flatMap((target) => valuesOf(target)); + } + const { op } = reference; + if (values.length === 0) { + const arg = op === "-" || op === ":-" || op === "=" || op === ":=" || op === "+" || op === ":+" ? argument() : []; + if (arg === null) return null; + if (op === "+" || op === ":+") return ["", ...arg]; + return [written, ...arg]; + } + const out: string[] = []; + for (const raw of values) { + const expanded = deeper(raw); + if (expanded === null) return null; + for (const value of expanded) { + if (reference.count) out.push(String(value.length)); + else if (op === "" || op === "-" || op === "=" || op === "?" || op === ":?") out.push(value); + else if (op === ":-" || op === ":=") { + if (value !== "") out.push(value); + else out.push(...(argument() ?? [written])); + } else if (op === "+") out.push(...(argument() ?? [written])); + else if (op === ":+") { + if (value === "") out.push(""); + else out.push(...(argument() ?? [written])); + } else { + const arg = argument(); + const result = arg === null ? null : applyParameterOperator(value, op, arg[0]); + out.push(result ?? written); + } + if (out.length > limit) return null; + } + } + return [...new Set(out)]; +} +/** A `${…}` that does more than name a variable: an operator, `${!name}` or `${#name}`. */ +const OPERATED_REFERENCE_RE = /\$\{[!#]?[A-Za-z_][A-Za-z0-9_]*[^A-Za-z0-9_}]|\$\{[!#]/; +/** + * True when `command` would delete, move or overwrite failproofai's own state. + * + * Deleting the state IS disabling enforcement, and it never names the binary: + * `rm ~/.failproofai/policies/packs/installed.json` switches off every pack + * policy on the machine, and fail-closed does NOT fire, because a missing store + * reads as a fresh machine rather than a broken one — so nothing anywhere + * reports it. + * + * Two things carry the path into a command that never spells it, and both were + * live bypasses of the per-segment version: + * + * - `cd ~/.failproofai && rm -rf .` — the path is an argument of `cd`, and the + * destroying command names only `.` + * - `D=~/.failproofai; rm -rf $D` — the path is a value, and the destroying + * command names only `$D` + * + * So the walk is stateful: it remembers which variables hold the path and + * whether the shell has been moved INTO the directory, and carries both + * forward. What it does NOT do is treat every later command as suspect — + * `cat ~/.failproofai/config.json && rm /tmp/scratch` has to stay allowed, and + * does, because nothing in the second command reaches the state. + */ +function destroysFailproofaiState(command: string, depth = 0, startDir?: string, startUnknown = false): boolean { + const globOptions = globOptionsOf(command); + // A substitution runs its body as a command of its own, so it is judged as + // one — `echo $(rm -rf ~/.failproofai)` otherwise presents `echo` as the head + // and walks straight through. Bounded, because a body can contain another. + // Breadth-first with a budget rather than depth-limited recursion: a nest + // deeper than the limit is trivial to write (`echo $(echo $(… rm …))`), and + // every level of it presents `echo` as the head. The budget is what bounds + // the work instead, because siblings multiply where depth does not. + if (depth === 0) { + const bodies = substitutionBodies(command); + for (let i = 0; i < bodies.length && i < MAX_SUBSTITUTION_BODIES; i++) { + const before = commandsBefore(command, bodies[i]); + if (destroysFailproofaiState(before === "" ? bodies[i] : `${before}; ${bodies[i]}`, 1, startDir, startUnknown)) return true; + bodies.push(...substitutionBodies(bodies[i])); + } + if (bodies.length > MAX_SUBSTITUTION_BODIES) return true; + } + + // Variables that hold the path. The scan used to ask only whether a value + // CONTAINED the path, which caught `D=~/.failproofai; rm -rf $D` and missed + // `A=~/.failproofai; B=$A; rm -rf $B` — the second hop names no path at all, + // only the first variable. So a value referencing a known state variable + // counts too. Repeating to a fixpoint costs four lines and makes the result + // independent of the order the assignments appear in, rather than resting on + // a shell evaluating them top to bottom. + const assignments = [ + ...command.matchAll(ASSIGNMENT_RE), + ].map(([, name, value]) => [name, value.replace(/^["']|["']$/g, "")] as const); + const stateVars = new Set(); + for (let pass = 0; pass < assignments.length + 1; pass++) { + const before = stateVars.size; + for (const [name, value] of assignments) { + const holdsState = + FAILPROOFAI_STATE_PATH_RE.test(value) || + [...value.matchAll(VAR_REFERENCE_RE)].some(([, ref]) => stateVars.has(ref)); + if (holdsState) stateVars.add(name); + } + if (stateVars.size === before) break; + } + + // Asked again and again for the same words (every check below, for the words + // as written and as expanded), so answered once per text. + const named = new Map(); + const globbed = new Map(); + const globNamesState = (token: string): boolean => { + let verdict = globbed.get(token); + if (verdict === undefined) globbed.set(token, (verdict = globCouldNameState(token))); + return verdict; + }; + const namesState = (text: string): boolean => { + let verdict = named.get(text); + if (verdict !== undefined) return verdict; + verdict = FAILPROOFAI_STATE_PATH_RE.test(text); + for (const [, name] of verdict ? [] : text.matchAll(VAR_REFERENCE_RE)) { + if (stateVars.has(name)) verdict = true; + } + // Per token, not over the whole text: a glob compiled from a whole command + // line matches nothing, and it is the individual operand — `~/.failproof*` + // — that would expand onto the state. + verdict ||= text.split(/\s+/).some((token) => globNamesState(unquotedToken(token))); + named.set(text, verdict); + return verdict; + }; + + let cwdInState = false; + // How deep in `( … )` the walk is, and how deep it was when the `cd` fired. + // A `cd` inside a subshell moves the subshell only, so the window closes when + // the parenthesis does: `(cd ~/.failproofai && cat x); rm -rf node_modules` + // was denying a cleanup in an entirely unrelated directory. + let parenDepth = 0; + let cdParenDepth: number | null = null; + + // Where the shell stands, when the walk can tell: the session's directory to + // begin with, then wherever each `cd`, `pushd` and `popd` moves it. A + // protected FILE sits in a directory nothing protects, so `cwdInState` never + // fires for it: `cd node_modules/.bin && printf 'exit 0' > failproofai`, or + // the same `printf` in a session a previous call left there, names + // `node_modules/.bin/failproofai` only once `failproofai` is read from there + // (FailproofAI/agenteye#1795). + // + // `dir` is the directory's last `SHELL_DIR_SEGMENTS` segments, which is what + // words are read from: every pattern matches the end of a path, and an + // unbounded path made every later word slower to judge. `full` is the whole + // path, absolute when the session's directory is known and otherwise relative + // to wherever the line started (`.`); it is what a `..` that climbs above + // `dir` and a symlink are resolved from. Past `FULL_DIR_SEGMENTS` it is + // dropped and `deep` set. `lost` marks a `cd` the walk could not follow + // (`cd "$(npm root)/.bin"`, `cd $ELSEWHERE`): a relative word is then also + // judged as if it stood in an installed location (`AS_IF_INSTALLED`). + // `anywhere` marks a directory read from where the line started when the + // agent may have run it somewhere its hook does not report (Codex's + // `workdir`): a relative destination there may be npm's bin directory. + type Where = { dir: string | undefined; full: string | undefined; deep: boolean; lost: boolean; inState: boolean; anywhere?: boolean }; + const startFull = typeof startDir === "string" && startDir !== "" ? shellPath(undefined, startDir) || "." : "."; + let at: Where = { + dir: startFull === "." ? undefined : shellTail(startFull), + full: startFull, + deep: false, + lost: false, + inState: false, + anywhere: startUnknown, + }; + let previous: Where | null = null; + // `set -P` / `set -o physical`: every later `cd` is a `cd -P`. + let physicalMoves = false; + const dirStack: Where[] = []; + // Where the shell may stand instead. A `cd` can fail, and a command after + // `;`, a newline, `&` or `||` runs anyway, in the directory the shell never + // left: `cd /nonexistent; printf x > failproofai`. Only `&&` makes what + // follows wait for the `cd`. So the directories a move leaves are held in + // `pending` until the next separator, and become possible (`alts`) unless + // that separator is `&&`. + let alts: Where[] = []; + let pending: Where[] = []; + const scopes: Array<{ + depth: number; + at: Where; + previous: Where | null; + stack: Where[]; + alts: Where[]; + pending: Where[]; + physical: boolean; + }> = []; + const sameWhere = (x: Where, y: Where) => x.dir === y.dir && x.full === y.full && x.lost === y.lost; + // A directory the walk cannot name: where the shell may be once there are + // more possibilities than it tracks. + const UNKNOWN: Where = { dir: undefined, full: undefined, deep: false, lost: true, inState: false }; + // Each place once. Past the limit the oldest are not dropped, since the + // shell may still be in any of them: the newest few are kept and the rest + // read as a directory the walk lost. + const fold = (list: Where[], limit: number): Where[] => { + const kept: Where[] = []; + for (const where of list) if (!kept.some((other) => sameWhere(other, where))) kept.push(where); + if (kept.length <= limit) return kept; + return [...kept.filter((where) => !sameWhere(where, UNKNOWN)).slice(-(limit - 1)), UNKNOWN]; + }; + // Where else the shell may stand: not where it certainly is. + const possible = (list: Where[]): Where[] => fold(list.filter((where) => !sameWhere(where, at)), MAX_ALTERNATE_DIRS); + // Symlinks this line makes (`ln -s `), which no `lstat` sees + // yet: keyed by where the link really is, holding its target as written. + const links = new Map(); + // Where an absolute path really is, as the kernel resolves it: one component + // at a time from the root, each link (this line's or one on disk) replaced + // by its target where it is met, and each `..` taken from the directory + // reached so far. So `inline/../failproofai` through a link to + // `node_modules/.bin/sub` is `.bin/failproofai`, which collapsing `..` as + // text first read as `./failproofai` (found by hermes on + // FailproofAI/failproofai#1058). Past 40 links (the kernel's MAXSYMLINKS) + // the write fails, but where it was headed is unknown, so that is `ELOOP` + // and read as landing on the state. Through a link whose target is a + // substitution or a variable the walk cannot read, `{ via, lost }` is that + // target as written and what remains of the path after it. + const ELOOP = Symbol("ELOOP"); + type Lost = { via: string; lost: string }; + type RealPath = string | typeof ELOOP | Lost; + type Walk = { reached: string; hops: number } | typeof ELOOP | Lost; + // The kernel's walk from `reached` ("" is the root) with `hops` links + // already followed, over the components still `pending`. + const walkFrom = (reached: string, hops: number, pending: string[]): Walk => { + while (pending.length > 0) { + const part = pending.shift()!; + if (part === "" || part === ".") continue; + if (part === "..") { + reached = reached.slice(0, reached.lastIndexOf("/")); + continue; + } + const next = `${reached}/${part}`; + let target = links.get(next); + const made = target !== undefined; + if (!made) { + try { + if (lstatSync(next).isSymbolicLink()) target = readlinkSync(next); + } catch { + // Missing or unreadable: a plain name once created, so walk on. + } + } + if (target === undefined) { + reached = next; + continue; + } + if (made && /[$`]/.test(target)) return { via: target, lost: pending.filter((p) => p !== "").join("/") }; + if (++hops > 40) return ELOOP; + if (target.startsWith("/")) reached = ""; + pending.unshift(...target.split("/")); + } + return { reached, hops }; + }; + // Each directory is walked once: every word read from the same place shares + // it, and the option values glued into a long command line are many words. + const directoryWalks = new Map(); + const realPaths = new Map(); + const realPath = (raw: string): RealPath => { + // Longer than PATH_MAX, no write can open it, and walking it on disk one + // component at a time cost a second for a 128 KB word of `a/a/a/…`. + if (raw.length > PATH_MAX_BYTES) return shellPath(undefined, raw); + let real = realPaths.get(raw); + if (real !== undefined) return real; + const cut = raw.lastIndexOf("/"); + const name = raw.slice(cut + 1); + let walked: Walk; + if (cut > 0 && name !== "" && name !== "." && name !== "..") { + const directory = raw.slice(0, cut); + let parent = directoryWalks.get(directory); + if (parent === undefined) directoryWalks.set(directory, (parent = walkFrom("", 0, directory.split("/")))); + walked = + parent === ELOOP + ? ELOOP + : "reached" in parent + ? walkFrom(parent.reached, parent.hops, [name]) + : { via: parent.via, lost: parent.lost === "" ? name : `${parent.lost}/${name}` }; + } else { + walked = walkFrom("", 0, raw.split("/")); + } + real = walked === ELOOP || !("reached" in walked) ? walked : walked.reached || "/"; + realPaths.set(raw, real); + return real; + }; + + // A relative word read from `base`, and `//`, `.` and `..` resolved in any. + const fromBase = (base: Where, word: string): string => + relativeWord(word) && base.dir !== undefined + ? shellPath(base.dir, word) + : /\/\/|(?:^|\/)\.\.?(?:\/|$)/.test(word) + ? shellPath(undefined, word) || "." + : word; + const resolvesFrom = (base: Where, text: string): boolean => { + // An option is not a path to read from where the shell stands. + if (text.startsWith("-")) return false; + if (base.lost && relativeWord(text)) { + if (AS_IF_INSTALLED.some((dir) => namesState(dir + text))) return true; + // From a directory the walk cannot see, `bins/failproofai` may go + // through a link to npm's bin directory. + if (text.includes("/") && couldBeEntryName(text.slice(text.lastIndexOf("/") + 1))) return true; + } + // A `..` can climb above `dir`. Then it is read from the whole path, cut + // the same way, or when even that was too long to keep, as if from an + // installed location. + if (relativeWord(text) && text.includes("..") && !base.lost) { + const climbed = fromBase(base, text); + if (climbed.startsWith("..") || (base.dir !== undefined && !climbed.startsWith("/") && base.full?.startsWith("/"))) { + if (base.full !== undefined) { + const whole = shellPath(base.full === "." ? undefined : base.full, text); + if (FAILPROOFAI_STATE_PATH_RE.test(whole) || namesState(shellTail(whole))) return true; + } else if (base.deep && climbed.startsWith("..")) { + const rest = climbed.replace(/^(?:\.\.\/)+/, ""); + if (AS_IF_INSTALLED.some((dir) => namesState(dir + rest))) return true; + } + } + } + if (base.lost) return false; + // Every pattern spells `failproof`, so only a word or a directory that + // does, or a glob that could, can resolve onto one. A glob as written is + // already tried against every candidate that starts with a relative + // directory, so it is read from where the shell stands only when that is a + // directory a candidate continues from by one name (`node_modules/.bin` + // and `fail*`), or when it climbs out with `..`. + if (!/failproof/i.test(text) && !/failproof/i.test(base.dir ?? "")) { + if (!GLOB_METACHAR_RE.test(text)) return false; + const parent = (base.dir ?? "").slice((base.dir ?? "").lastIndexOf("/") + 1).toLowerCase(); + if (!GLOB_PARENT_DIRECTORIES.has(parent) && !text.includes("..")) return false; + } + const resolved = fromBase(base, text); + return resolved !== text && namesState(resolved); + }; + // Whether `text`, read from where the shell stands or may stand, names what + // `namesState` protects — asked apart from `namesState(text)` where the whole + // line has already been judged as written. + const resolvesOntoState = (text: string): boolean => + resolvesFrom(at, text) || alts.some((base) => resolvesFrom(base, text)); + // A written path as the absolute path it spells from `base`: `raw` as the + // kernel walks it, each `..` taken after any link before it, and `plain` as + // text. + const absoluteFrom = (base: Where, written: string): { raw: string; plain: string } | undefined => { + if (written === "" || written.startsWith("-") || written.includes("$") || GLOB_METACHAR_RE.test(written)) { + return undefined; + } + const raw = written.startsWith("/") + ? written + : written === "~" || written.startsWith("~/") + ? homedir() + written.slice(1) + : relativeWord(written) && !base.lost && base.full?.startsWith("/") + ? `${base.full}/${written}` + : undefined; + if (raw === undefined) return undefined; + return { raw, plain: shellPath(undefined, raw) }; + }; + // Where a written path really is, from each place the shell may stand: as + // the kernel resolves it, through links on disk and those this line makes. + const realPathsOf = (written: string): Array<{ plain: string; real: RealPath }> => { + const out: Array<{ plain: string; real: RealPath }> = []; + for (const base of [at, ...alts]) { + const path = absoluteFrom(base, written); + if (path !== undefined) out.push({ plain: path.plain, real: realPath(path.raw) }); + } + return out; + }; + // Through a link whose target the walk cannot read, the target as written + // and what remains after it, and that remainder alone the way a word is read + // once the walk has lost the shell's directory: as if from an installed + // location. `ln -s "$(npm root)/.bin" b; printf x > b/failproofai`. + const lostNamesState = ({ via, lost }: { via: string; lost: string }): boolean => + namesState(lost === "" ? via : `${via}/${lost}`) || + (lost !== "" && AS_IF_INSTALLED.some((dir) => namesState(dir + lost))) || + couldBeEntryName(lost.slice(lost.lastIndexOf("/") + 1)); + // Whether a written directory really is npm's bin directory, through links. + // Through one the walk cannot read, it is when the target ends in `.bin`, or + // is a substitution (`$(npm root)/.bin` arrives cut short as `$(npm`); a + // variable the line never sets is read as an unknown `cd` is, which is not + // taken for npm's bin (`ln -sfn "$RELEASE" current && cp -r config current/`). + const isBinDir = (written: string): boolean => + realPathsOf(written.replace(/[\\/]+$/, "") || written).some(({ real }) => { + if (real === ELOOP) return true; + if (typeof real === "string") return NPM_BIN_DIRECTORY_RE.test(real); + const reached = real.lost === "" ? real.via : `${real.via}/${real.lost}`; + return /(?:^|[\\/])\.bin[\\/]*$/i.test(reached) || (real.lost === "" && /\$\(|`/.test(real.via)); + }); + // Whether a path really lands on what `namesState` protects once symlinks + // are followed — those on disk, as the file tools already follow them, and + // those this line makes: `printf x > bins/failproofai` where `bins` links to + // `node_modules/.bin`. Only a link counts, so a backup that merely carries a + // protected name somewhere else (`/tmp/backup/.failproofai`) does not. + // Whether a path exists, as `lstat` finds it: a missing name, or one under a + // file (`ENOTDIR`), does not. + const exists = (path: string): boolean => { + try { + return lstatSync(path || "/", { throwIfNoEntry: false }) !== undefined; + } catch { + return false; + } + }; + // What a directory holds, read once. + const listings = new Map | null>(); + const listingOf = (directory: string): Set | null => { + let names = listings.get(directory); + if (names === undefined) { + try { + names = new Set(readdirSync(directory || "/")); + } catch { + names = null; + } + listings.set(directory, names); + } + return names; + }; + // The names of the links this line has made in `directory` ("" is the + // root), which no listing holds yet but the shell's glob will. + const inlineNamesIn = (directory: string): string[] => { + if (links.size === 0) return []; + const names: string[] = []; + for (const place of links.keys()) { + const cut = place.lastIndexOf("/"); + if (place.slice(0, cut) === directory) names.push(place.slice(cut + 1)); + } + return names; + }; + // A directory as a glob reads it: the directory it really is, through this + // line's links too, and the names in it, this line's links among them. + const namesInDirectory = (path: string): { directory: string; names: Iterable } => { + let directory = path; + if (links.size > 0 && path !== "") { + const real = realPath(path); + if (typeof real === "string") directory = real === "/" ? "" : real; + } + const listed = listingOf(directory); + const inline = inlineNamesIn(directory); + return { directory, names: inline.length === 0 ? (listed ?? []) : new Set([...(listed ?? []), ...inline]) }; + }; + // Whether `path` is there once this line's links are made: on disk, or + // through or as one of them. + const present = (path: string): boolean => { + if (exists(path)) return true; + if (links.size === 0) return false; + const cut = path.lastIndexOf("/"); + const parent = realPath(path.slice(0, cut) || "/"); + if (typeof parent !== "string") return true; + if (links.has(`${parent === "/" ? "" : parent}/${path.slice(cut + 1)}`)) return true; + const real = realPath(path); + return typeof real !== "string" || exists(real) || links.has(real); + }; + // A pattern as the shell expands it against the disk, from directory + // `from`: each component with a pattern matched against what the directory + // before it holds, a leading `.` only by a pattern that spells one (no + // `dotglob`), and the whole path required to exist. `null` past + // GLOB_DISK_LIMIT paths. + const expandOnDisk = (from: string, pattern: string): string[] | null => { + let paths = [from === "/" ? "" : from]; + let reads = 0; + let walked = 0; + for (const part of pattern.split("/")) { + if (part === "" || part === ".") continue; + if (part === ".." || !isGlobPart(part)) { + paths = paths.map((path) => `${path}/${part}`); + continue; + } + // zsh's `**/` (and bash's under globstar): this directory and every one + // below it, hidden ones under dotglob; `***/` follows links to them too. + if ((part === "**" || part === "***") && globOptions.globstar) { + const queue = [...paths]; + for (let i = 0; i < queue.length; i++) { + if (++walked > GLOB_RECURSIVE_DIR_LIMIT) return null; + for (const name of namesInDirectory(queue[i]).names) { + if (name.startsWith(".") && !globOptions.dotglob) continue; + const child = `${queue[i]}/${name}`; + try { + if ((part === "***" ? statSync(child) : lstatSync(child)).isDirectory()) queue.push(child); + } catch { + // Gone or unreadable: nothing below it. + } + } + } + paths = queue; + continue; + } + const matcher = globPartMatcher(part, globOptions); + if (matcher === null) return null; + const next: string[] = []; + for (const path of paths) { + // After a `**` the directories are the ones it walked, under its own limit. + if (++reads > (walked > 0 ? GLOB_RECURSIVE_DIR_LIMIT : GLOB_DISK_LIMIT / 4)) return null; + for (const name of namesInDirectory(path).names) { + if (name.startsWith(".") && !part.startsWith(".") && !globOptions.dotglob) continue; + if (!matcher.test(name)) continue; + next.push(`${path}/${name}`); + if (next.length > GLOB_DISK_LIMIT) return null; + } + } + if (next.length === 0) return []; + paths = next; + } + return paths.filter(present); + }; + // The links in `directory`, read once from disk, with this line's. + const diskLinks = new Map(); + const linkNamesIn = (directory: string): string[] => { + let names = diskLinks.get(directory); + if (names === undefined) { + names = []; + try { + for (const entry of readdirSync(directory || "/", { withFileTypes: true })) if (entry.isSymbolicLink()) names.push(entry.name); + } catch { + // Unreadable: nothing in it can be reached through it. + } + diskLinks.set(directory, names); + } + const inline = inlineNamesIn(directory); + return inline.length === 0 ? names : [...names, ...inline]; + }; + // The matches of a pattern in one directory that are links, the only ones + // that reach anywhere else, however many plain names match beside them: + // `tee many/*` wrote through `many/hook`, a link to the entry, past 4096 + // plain names (found by hermes on FailproofAI/failproofai#1058). `null` + // past GLOB_DISK_LIMIT links. + const linksMatching = (directory: string, part: string): string[] | null => { + // A bracket bash cannot read either (`[r-p]`) matches nothing. + const matcher = globPartMatcher(part, globOptions); + if (matcher === null) return []; + const found: string[] = []; + for (const name of linkNamesIn(directory)) { + if (name.startsWith(".") && !part.startsWith(".") && !globOptions.dotglob) continue; + if (!matcher.test(name)) continue; + found.push(`${directory}/${name}`); + if (found.length > GLOB_DISK_LIMIT) return null; + } + return found; + }; + // A glob expands where its literal directories really are: `cp x bins/fail*` + // with `bins` a link to `node_modules/.bin`, and `fail*` from a directory + // reached through one, both expand onto the entry. So the directories before + // the first pattern are resolved, and the pattern is read from there. A + // pattern in a directory component (`b*/failproofai`) is expanded on disk as + // the shell expands it and each path it reaches resolved, and each word a + // brace expands to is read the same way (found by hermes on + // FailproofAI/failproofai#1058). + const patternLandsOnState = (word: string): boolean => { + const parts = word.split("/"); + const first = parts.findIndex((part) => isGlobPart(part)); + if (first === -1) return false; + const prefix = first === 0 ? "" : parts.slice(0, first).join("/") || "/"; + const pattern = parts.slice(first).join("/"); + if (/[$`]/.test(prefix)) return false; + const inDirectory = parts.slice(first, -1).some((part) => isGlobPart(part)); + return [at, ...alts].some((base) => { + const raw = + prefix === "" + ? !base.lost && base.full?.startsWith("/") + ? base.full + : undefined + : absoluteFrom(base, prefix)?.raw; + if (raw === undefined) return false; + const real = realPath(raw); + if (real === ELOOP) return true; + if (typeof real !== "string") return lostNamesState({ via: real.via, lost: real.lost === "" ? pattern : `${real.lost}/${pattern}` }); + if (real !== shellPath(undefined, raw) && namesState(`${real === "/" ? "" : real}/${pattern}`)) return true; + // A pattern only in the last component matches names in one directory: + // what counts there is a match that is a link (`hoo*` reaching `hook`, a + // link to the entry). In npm's bin directory or a `node_modules`, its + // names are what the pattern is read against, so a sweep stays a sweep; + // what a sweep writes is judged by `sweepWritesEntry`. + if (!inDirectory && (NPM_BIN_DIRECTORY_RE.test(real) || /(?:^|\/)(?:node_modules|\.pnpm)$/i.test(real))) return false; + const matches = inDirectory ? expandOnDisk(real, pattern) : linksMatching(real === "/" ? "" : real, pattern); + if (matches === null) return true; + return matches.some((match) => { + const reached = realPath(match); + if (reached === ELOOP) return true; + if (typeof reached !== "string") return lostNamesState(reached); + return (inDirectory || reached !== shellPath(undefined, match)) && namesState(reached); + }); + }); + }; + // Every word a brace expands to is read: a literal one as the path it is, + // which costs a lookup, and one that is still a pattern on disk, of which + // at most MAX_BRACE_WORDS_ON_DISK are expanded. Past that the rest are + // refused rather than dropped: `tee {x{a,b,c,d}{1,2,3,4}{i,j,k,l},hook}` + // wrote through `hook` as its 65th word (found by hermes on + // FailproofAI/failproofai#1058). + const globLandsOnState = (written: string): boolean => { + let patterns = 0; + for (const word of expandBraces(written)) { + if (!isGlobPart(word)) { + if (word !== written && landsOnState(word)) return true; + continue; + } + if (++patterns > MAX_BRACE_WORDS_ON_DISK) return true; + if (patternLandsOnState(word)) return true; + } + return false; + }; + const landsOnState = (written: string): boolean => + realPathsOf(written).some(({ plain, real }) => + real === ELOOP ? true : typeof real !== "string" ? lostNamesState(real) : real !== plain && namesState(real), + ) || + (isGlobPart(written) && globLandsOnState(written)); + const namesHere = (text: string): boolean => namesState(text) || resolvesOntoState(text) || landsOnState(text); + // A glob that sweeps npm's bin directory reaches every name in it, which is + // harmless for a delete (`rm -rf node_modules/.bin/*` stays allowed) and + // the entry for a write: `tee bins/* < stub` with `bins` a link to + // `node_modules/.bin` overwrote it (found by hermes on + // FailproofAI/failproofai#1058). So a written word whose last component is + // a pattern, in a bin directory, lands on the entry when the pattern matches + // the entry there, or a link there that reaches the entry or the state. + const sweepWritesEntry = (written: string): boolean => { + if (!GLOB_METACHAR_RE.test(written)) return false; + let patterns = 0; + for (const word of expandBraces(written)) { + const cut = word.replace(/[\\/]+$/, "").lastIndexOf("/"); + const pattern = word.slice(cut + 1); + const directory = cut === -1 ? "." : word.slice(0, cut) || "/"; + if (!GLOB_METACHAR_RE.test(pattern) || GLOB_METACHAR_RE.test(directory) || /[$`]/.test(word)) continue; + if (++patterns > MAX_BRACE_WORDS_ON_DISK) return true; + const matcher = globTest(pattern); + if (matcher === null) continue; + for (const base of [at, ...alts]) { + const path = absoluteFrom(base, directory); + if (path === undefined) continue; + const real = realPath(path.raw); + if (typeof real !== "string" || !NPM_BIN_DIRECTORY_RE.test(real)) continue; + const dir = real === "/" ? "" : real; + if (NPX_ENTRY_NAMES.some((name) => matcher.test(name) && present(`${dir}/${name}`))) return true; + for (const name of linkNamesIn(dir)) { + if ((name.startsWith(".") && !pattern.startsWith(".")) || !matcher.test(name)) continue; + const reached = realPath(`${dir}/${name}`); + if (reached === ELOOP) return true; + if (typeof reached !== "string") { + if (lostNamesState(reached)) return true; + } else if (NPX_ENTRY_PATH_RE.test(reached) || FAILPROOFAI_STATE_PATH_RE.test(reached)) return true; + } + } + } + return false; + }; + // From a directory the agent may have run the line in without saying so + // (`anywhere`), a relative destination that would be the entry, or the + // package, wherever that directory is: `printf … > failproofai`, and through + // any directory on the way, since one there may be a link into a bin + // directory or a `node_modules` that no lstat can see from here + // (`bins/failproofai`, `deps/failproofai/dist/cli.mjs`; found by hermes on + // FailproofAI/failproofai#1058). + const anywhereHere = (): boolean => at.anywhere === true || alts.some((base) => base.anywhere === true); + const plantsAnywhere = (written: string): boolean => { + if (!relativeWord(written) || /[$`]/.test(written)) return false; + const parts = written.replace(/[\\/]+$/, "").split(/[\\/]+/); + if (couldBeEntryName(parts[parts.length - 1])) return true; + // The package is read from each component that could start it, a few at most. + let tried = 0; + for (let i = 0; i < parts.length && tried < 16; i++) { + if (!/^(?:failproof|\.pnpm$|@failproofai$)/i.test(parts[i])) continue; + tried++; + const rest = parts.slice(i).join("/"); + if (AS_IF_INSTALLED.some((dir) => FAILPROOFAI_CODE_PATH_RE.test(dir + rest))) return true; + } + return false; + }; + // What a simple command writes that its options or operands name, read from + // such a directory: an output flag's value, separate or glued (`curl -o`, + // `wget -O`, `gcc -o`, `--output=`), every operand of a command that writes + // them all (`tee`), the last of one that writes its second (`uniq`), and + // `dd of=`. Copies, moves, links and downloads are judged where they land. + const writesEntryAnywhere = (list: string[]): boolean => { + if (list.length === 0) return false; + const head = commandBasename(list[0]); + const args = list.slice(1); + const operands = args.filter((arg) => !arg.startsWith("-")); + if (OPERAND_WRITE_COMMANDS.has(head) && operands.some(plantsAnywhere)) return true; + if (SECOND_OPERAND_WRITERS.has(head) && operands.length > 1 && plantsAnywhere(operands[operands.length - 1])) return true; + // A copy's destination into the package (`deps/failproofai/dist/cli.mjs`); + // where its sources land by name is judged with the other landings. + if (COPY_COMMANDS.has(head) && operands.length > 1 && plantsAnywhere(operands[operands.length - 1])) return true; + if (head === "dd" && args.some((arg) => arg.startsWith("of=") && plantsAnywhere(arg.slice(3)))) return true; + if (head === "sed" && sedWriteTargets(sedScriptArgs(args)).some(plantsAnywhere)) return true; + const known = SHORT_VALUE_OPTIONS[head]; + const outputLetters = SHORT_OUTPUT_OPTIONS[head]; + return args.some((arg, i) => { + const long = /^--(?:output|out)[\w-]*(=)?/.exec(arg); + if (long) return plantsAnywhere(long[1] ? arg.slice(arg.indexOf("=") + 1) : (args[i + 1] ?? "")); + // The other files curl writes (`--stderr`, `--dump-header`, …), by any + // prefix of the name curl before 8 takes. + if (arg.startsWith("--") && OUTPUT_FLAG_COMMANDS[head] !== undefined) { + const eq = arg.indexOf("="); + const name = arg.slice(2, eq === -1 ? undefined : eq); + if (name !== "" && !EXACT_NON_OUTPUT_OPTIONS.has(`${head} --${name}`) && OUTPUT_FLAG_COMMANDS[head].some((flag) => flag.startsWith(`--${name}`))) { + return plantsAnywhere(eq === -1 ? (args[i + 1] ?? "") : arg.slice(eq + 1)); + } + } + if (!/^-[A-Za-z]/.test(arg)) return false; + // Where the command's value letters are known, the cluster is read as + // getopt reads it: flags up to the first letter that takes a value, and + // that value, glued on or the next word, a file written only when the + // letter is an output's. curl's `-O` takes none, so `cd out && curl -sO + // http://host/failproofai/my-tool` names no file; where it lands is + // judged with the other downloads (found by hermes on + // FailproofAI/failproofai#1058). + if (known !== undefined) { + for (let c = 1; c < arg.length; c++) { + if (!known.includes(arg[c])) continue; + return outputLetters.includes(arg[c]) && plantsAnywhere(c + 1 < arg.length ? arg.slice(c + 1) : (args[i + 1] ?? "")); + } + return false; + } + if (/^-[A-Za-z]*[oO]$/.test(arg)) return plantsAnywhere(args[i + 1] ?? ""); + // Glued on after an `o` or `O`. + for (let c = 1; c < arg.length - 1 && /[A-Za-z]/.test(arg[c]); c++) { + if (c > MAX_OPTION_CLUSTER) return /failproof/i.test(arg); + if ((arg[c] === "o" || arg[c] === "O") && plantsAnywhere(arg.slice(c + 1))) return true; + } + return false; + }); + }; + // `namesHere` for a value glued to an option, of which a long command line + // has one per letter of its option words. Every protected name spells + // `failproof`, so a value that spells none, climbs nowhere and expands to + // nothing can only reach one through a link: one this line made, or one on + // disk under a first component that exists, which each directory's listing, + // read once, answers. + const existsIn = (directory: string, name: string): boolean => { + const names = listingOf(directory); + return names === null ? exists(`${directory}/${name}`) : names.has(name); + }; + const gluedValueNamesHere = (value: string): boolean => { + if (/failproof|\.\.|[$~]|[*?[{]|[@+!]\(/i.test(value) || links.size > 0 || value.startsWith("/")) { + return namesHere(value); + } + const relative = value.replace(/^(?:\.\/+)+/, ""); + const first = relative.slice(0, (relative.indexOf("/") + 1 || relative.length + 1) - 1); + return ( + first !== "" && + [at, ...alts].some((base) => !base.lost && base.full?.startsWith("/") === true && existsIn(base.full, first)) && + landsOnState(value) + ); + }; + // What the line has assigned by the point the walk reaches, so a word built + // from it is judged as the path it spells: `B=~/node_modules/.bin; ln -s + // /tmp/stage $B`. In a loop a later assignment can come first, so there the + // last one is known from the start. `$PWD` and `~+` are where the shell + // stands, `~-` where it stood, `$HOME` is `~` unless the line sets it. A + // variable the line never sets stays a reference, and a `cd` into one is a + // `cd` the walk cannot follow. Every word is judged as written as well, so an + // assignment the shell never makes (`: D=x`) cannot hide one. + const values = new Map(LOOP_HEADER_RE.test(command) ? assignments : []); + // A variable's value where the shell stands at `here`: `$PWD` is that + // directory, `$HOME` is `~` unless the line sets it. + const valueAt = (name: string, here: Where): string | undefined => + name === "PWD" && here.dir !== undefined && !here.lost ? here.dir : (values.get(name) ?? (name === "HOME" ? "~" : undefined)); + const expandAt = (word: string, here: Where): string => { + let out = word; + if (out.startsWith("~+") && here.dir !== undefined && !here.lost) out = here.dir + out.slice(2); + else if (out.startsWith("~-") && previous?.dir !== undefined && !previous.lost) out = previous.dir + out.slice(2); + if (!out.includes("$")) return out; + // Each operator as bash applies it (`${D%/}` is `D` without its trailing + // `/`), and a variable read in a value read too. + const results = expandParameters(out, (name) => { + const value = valueAt(name, here); + return value === undefined ? [] : [value]; + }, 64); + out = results?.[0] ?? word; + // A value that refers to itself grows with every pass. + return out.length > 4096 ? word : out; + }; + const expand = (word: string): string => expandAt(word, at); + // Every value the line gives each variable. One set only in a subshell or + // only for one command (`(F=x)`, `F=x true`) does not replace the value + // before it, so a word is also read with each other value its variables are + // given (found by hermes on FailproofAI/failproofai#1058). + // Outside a loop only what the line has assigned by the point the walk + // reaches counts, as with `values`; in one, every assignment may come first. + const everyValue = new Map(); + let reassigned = false; + const variantsByWord = new Map(); + const assigned = (name: string, value: string) => { + const seen = everyValue.get(name) ?? []; + if (seen.includes(value)) return; + seen.push(value); + everyValue.set(name, seen); + if (seen.length > 1) reassigned = true; + variantsByWord.clear(); + }; + if (LOOP_HEADER_RE.test(command)) for (const [name, value] of assignments) assigned(name, value); + // Every value is tried, so decoys in front of or after the one that counts + // cannot push it out of reach; past VARIANT_BUDGET tries the line is refused + // as one the walk could not read. + let variantBudget = VARIANT_BUDGET; + // Every combination of the values of the reassigned variables a word names, + // one value per variable as the shell uses it: `A=fail; B=proofai; (A=x; + // B=y); printf x > node_modules/.bin/$A$B` writes `failproofai`, which + // swapping one variable at a time never spelled (found by hermes on + // FailproofAI/failproofai#1058). + // A `${name:-word}` default, `${!name}` and the other operators give a word + // other values too, so those are read even when nothing is reassigned: + // `cp stub ${X:-bins}/failproofai` writes through `bins` when `X` is unset. + const variantsOf = (word: string): string[] => { + if (!word.includes("$") || (!reassigned && !OPERATED_REFERENCE_RE.test(word))) return []; + const known = variantsByWord.get(word); + if (known !== undefined) return known; + const results = expandParameters( + word, + (name) => { + const every = everyValue.get(name); + if (every !== undefined && every.length > 0 && !(name === "PWD" && at.dir !== undefined && !at.lost)) return every; + const value = valueAt(name, at); + return value === undefined ? [] : [value]; + }, + Math.max(variantBudget, 1), + ); + if (results === null) throw new Error("a variable is reassigned too many times to follow"); + if (results.length > 1) variantBudget -= results.length; + if (variantBudget < 0) throw new Error("a variable is reassigned too many times to follow"); + const current = expand(word); + const found = results.filter((variant) => variant !== current && variant.length <= 4096); + variantsByWord.set(word, found); + return found; + }; + // `$PWD` and `~+` name wherever the shell stands, which after a move that + // may have failed is any of the places it may be. + const NAMES_PWD_RE = /\$\{?PWD\b|^~\+/; + const expandEverywhere = (word: string): string[] => + NAMES_PWD_RE.test(word) ? alts.map((alt) => expandAt(word, alt)) : []; + // Gives `name` the values in `found`, keeping each it held before as one + // it may still hold; with none, a value the walk cannot know. + const setVariable = (name: string, found: readonly string[]) => { + if (values.has(name)) assigned(name, values.get(name)!); + if (found.length === 0) { + values.delete(name); + variantsByWord.clear(); + return; + } + for (const value of found) assigned(name, value); + values.set(name, found[found.length - 1]); + }; + // What a glob word expands to on disk from `base`, as the shell expands + // it; `null` past GLOB_DISK_LIMIT paths or from a directory the walk lost. + const globPaths = (base: Where, word: string): string[] | null => { + const absolute = word.startsWith("/") + ? word + : word === "~" || word.startsWith("~/") + ? homedir() + word.slice(1) + : !base.lost && base.full?.startsWith("/") + ? `${base.full}/${word}` + : undefined; + return absolute === undefined ? null : expandOnDisk("/", absolute.slice(1)); + }; + // A loop's variable takes each value its list gives as the shell expands + // it: `for d in out bins; do cp stub $d/failproofai; done` writes through + // `bins`, and `for f in many/*` through every link the pattern matches + // (found by hermes on FailproofAI/failproofai#1058). Past MAX_LOOP_VALUES, + // only the values that may reach what is protected are kept. + const loopValues = (name: string, list: string) => { + const found: string[] = []; + let plain = 0; + const take = (value: string, reaches: boolean) => { + if (found.includes(value) || (!reaches && plain++ >= MAX_LOOP_VALUES)) return; + found.push(value); + }; + const nameReaches = (path: string): boolean => /failproof/i.test(path) || couldBeEntryName(path.slice(path.lastIndexOf("/") + 1)); + const linked = (path: string): boolean => { + const cut = path.lastIndexOf("/"); + return linkNamesIn(path.slice(0, cut)).includes(path.slice(cut + 1)); + }; + for (const { raw } of shellWords(list)) { + const word = bareTokenForState(raw); + if (word === "" || word === "do") continue; + for (const each of [expand(word), ...variantsOf(word)]) { + if (!GLOB_METACHAR_RE.test(each) || /[$`]/.test(each)) { + take(each, nameReaches(each) || isBinDir(each) || landsOnState(each)); + continue; + } + const matches = globPaths(at, each); + if (matches === null) { + // Too many names to read one by one: in one directory, only its + // links and the entry reach anywhere else. + const cut = each.lastIndexOf("/"); + const part = each.slice(cut + 1); + const directory = cut === -1 ? "." : each.slice(0, cut) || "/"; + if (GLOB_METACHAR_RE.test(directory)) throw new Error("a loop runs over more paths than the walk reads"); + for (const { real } of realPathsOf(directory)) { + if (typeof real !== "string") throw new Error("a loop runs over more paths than the walk reads"); + const dir = real === "/" ? "" : real; + const links = linksMatching(dir, part); + if (links === null) throw new Error("a loop runs over more paths than the walk reads"); + for (const link of links) take(link, true); + const re = wholeGlob(part); + for (const entry of NPX_ENTRY_NAMES) if (re?.test(entry) && present(`${dir}/${entry}`)) take(`${dir}/${entry}`, true); + } + continue; + } + if (matches.length === 0) take(each, nameReaches(each)); + for (const match of matches) take(match, nameReaches(match) || (linked(match) && (landsOnState(match) || isBinDir(match)))); + } + } + setVariable(name, found); + }; + // `read`, `printf -v`, `mapfile` and `unset`, which set a variable without + // `=`: `read D <<< bins` gives `D` the here-string, and a value read from a + // file or a pipe is one the walk cannot know. + const setByBuiltin = (head: string, words: string[], simple: string) => { + if (head === "read") { + const names: string[] = []; + for (let k = 1; k < words.length; k++) { + if (/^-[A-Za-z]*[adinNptu]$/.test(words[k])) { + if (words[k].endsWith("a")) names.push(words[k + 1] ?? ""); + k++; + } else if (!words[k].startsWith("-")) names.push(words[k]); + } + const here = /<<<\s*("[^"]*"|'[^']*'|\S+)/.exec(simple); + const text = here === null ? undefined : expand(bareTokenForState(here[1])); + const fields = text?.split(/[ \t\n]+/).filter((field) => field !== "") ?? []; + names.forEach((name, index) => { + if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) return; + if (text === undefined) setVariable(name, []); + else setVariable(name, [index === names.length - 1 ? fields.slice(index).join(" ") : (fields[index] ?? "")]); + }); + if (names.length === 0) setVariable("REPLY", text === undefined ? [] : [text]); + } else if (head === "printf" && words[1] === "-v" && words[2] !== undefined) { + const format = expand(words[3] ?? ""); + const args = words.slice(4).map(expand); + // bash reuses the format until every argument is used (`printf -v D + // '%s' ho ok` is `hook`; found by hermes on FailproofAI/failproofai#1058). + // Numbers are converted as bash converts them (`%d` of `0x10` is `16`; + // found by hermes on FailproofAI/failproofai#1058); a form this does not + // compute leaves the variable unknown. + const value = bashPrintf(format, args); + // Unquoted, a value with spaces splits into words (`%2d` of 16 is ` 16`): + // each is a value the variable may stand for. + const fields = value === null ? [] : value.split(/\s+/).filter((field) => field !== "" && field !== value); + setVariable(words[2], value === null || /\\/.test(value) ? ["$(printf)"] : [value, ...fields]); + } else if (head === "mapfile" || head === "readarray") { + const named = words.slice(1).filter((word, k, all) => !word.startsWith("-") && !/^-[A-Za-z]*[dnOsuC]$/.test(all[k - 1] ?? "")); + setVariable(named[named.length - 1] ?? "MAPFILE", []); + } else if (head === "unset") { + for (const word of words.slice(1)) if (/^[A-Za-z_][A-Za-z0-9_]*$/.test(word)) setVariable(word, []); + } + }; + // A copy, move or link into a directory the walk cannot read puts each + // source there by its own name: `D=$(npm root)/.bin; cp stub/failproofai $D`. + const copiesIntoUnread = (list: string[]): boolean => { + const head = list.length > 0 ? commandBasename(list[0]) : ""; + if (!COPY_COMMANDS.has(head) && head !== "mv" && head !== "ln") return false; + const operands = list.slice(1).filter((arg) => !arg.startsWith("-")); + if (operands.length < 2 || !new RegExp(UNREAD_VALUE_RE.source).test(operands[operands.length - 1])) return false; + return operands.slice(0, -1).some((source) => couldBeEntryName(baseNameOf(source))); + }; + // What a sed script read from a file writes (`sed -n -f s.sed in`, the + // script holding `w hook`): the script as it is on disk, and one the walk + // cannot read (not there yet, standard input, or not a small regular file) + // is read as writing what is protected. + const sedScriptWrites = (args: string[]): boolean => + sedScriptFiles(args).some((file) => { + const text = instructionsIn(file); + return text === null || sedWriteTargets([text]).some(namesHere); + }); + // A file a command takes what it does from, as it is on disk where the + // shell stands; `null` for one the walk cannot read: standard input, one + // not there yet, or one that is not a small regular file. + const instructionsIn = (file: string): string | null => { + const path = file === "-" || file === "" ? undefined : absoluteFrom(at, file); + if (path === undefined) return null; + try { + const info = statSync(path.raw); + if (!info.isFile() || info.size > MAX_INSTRUCTION_FILE_BYTES) return null; + return readFileSync(path.raw, "utf8"); + } catch { + return null; + } + }; + // A patch applied from a file writes every file it names (`patch -p1 < + // stub.patch`, `patch -i stub.patch`, `git apply stub.patch`), each read + // with up to three leading directories stripped, as `-p` may, and from the + // directory `-d` / `--directory` names. One the walk cannot read, from a + // pipe or not there yet, is read as writing what is protected. + const patchFileWrites = (list: string[], simple: string): boolean => { + const head = list.length > 0 ? commandBasename(list[0]) : ""; + const args = list.slice(1); + const files: string[] = []; + const into: string[] = [""]; + if (head === "patch") { + for (let k = 0; k < args.length; k++) { + const arg = args[k]; + if (arg === "-i" || arg === "--input") files.push(args[++k] ?? ""); + else if (arg.startsWith("--input=")) files.push(arg.slice(8)); + else if (/^-i./.test(arg)) files.push(arg.slice(2)); + else if (arg === "-d" || arg === "--directory") into.push(args[++k] ?? ""); + else if (arg.startsWith("--directory=")) into.push(arg.slice(12)); + else if (/^-d./.test(arg)) into.push(arg.slice(2)); + } + if (files.length === 0) { + const redirected = /(?:^|[^<])<(?![<(])\s*("[^"]*"|'[^']*'|[^\s<>|&;]+)/.exec(simple); + files.push(redirected === null ? "-" : bareTokenForState(redirected[1])); + } + } else if (head === "git") { + const subcommand = gitSubcommandIndex(args); + if (subcommand < 0 || (args[subcommand] !== "apply" && args[subcommand] !== "am")) return false; + for (const arg of args.slice(subcommand + 1)) { + if (arg.startsWith("--directory=")) into.push(arg.slice(12)); + else if (!arg.startsWith("-")) files.push(arg); + } + if (files.length === 0) files.push("-"); + } else return false; + for (const file of files) { + const text = instructionsIn(file); + if (text === null) return true; + for (const target of patchTargets({ patch: text })) { + const parts = target.split("/"); + for (let strip = 0; strip <= Math.min(3, parts.length - 1); strip++) { + const rest = parts.slice(strip).join("/"); + if (into.some((dir) => namesHere(dir === "" ? rest : `${dir.replace(/\/+$/, "")}/${rest}`))) return true; + } + } + } + return false; + }; + // An archive extracted into npm's bin directory puts there names the line + // never spells: `tar -xf stub.tar -C bins`, `cd bins && unzip ../stub.zip`. + const extractsIntoBin = (list: string[]): boolean => { + const head = list.length > 0 ? commandBasename(list[0]) : ""; + const args = list.slice(1); + let into = "."; + // tar takes each `-C` from the directory the one before it left, and a + // member goes to the `-C` before it on the line, so every one is a place + // the archive may write (`-C bins failproofai -C out other`; found by + // hermes on FailproofAI/failproofai#1058). + const intos: string[] = []; + const changeDir = (dir: string) => { + if (dir === "") return; + const previous = intos[intos.length - 1]; + intos.push(dir); + if (previous !== undefined && previous !== "." && !dir.startsWith("/") && !dir.startsWith("~")) intos.push(`${previous.replace(/\/+$/, "")}/${dir}`); + }; + let extracting = false; + if (head === "tar" || head === "gtar" || head === "bsdtar") { + for (let k = 0; k < args.length; k++) { + const arg = args[k]; + if (arg.startsWith("--")) { + const eq = arg.indexOf("="); + const name = arg.slice(2, eq === -1 ? undefined : eq); + if (name.length >= 3 && "directory".startsWith(name)) changeDir(eq === -1 ? (args[++k] ?? "") : arg.slice(eq + 1)); + else if (name.length >= 3 && ("extract".startsWith(name) || name === "get")) extracting = true; + continue; + } + // The old form (`xzf` first, no dash): its value letters take the + // words after it in order. + if (!arg.startsWith("-")) { + if (k > 0) continue; + if (arg.includes("x")) extracting = true; + for (const letter of arg) { + if (letter === "C") changeDir(args[++k] ?? ""); + else if (TAR_SHORT_VALUE_OPTIONS.includes(letter)) k++; + } + continue; + } + // A dashed cluster, as getopt reads it: a letter that takes a value + // takes the rest of the cluster, or the next word when none is left + // (`-Cbins`, `-xfstub.tar`; found by hermes on FailproofAI/failproofai#1058). + for (let i = 1; i < arg.length; i++) { + const letter = arg[i]; + if (letter === "x") extracting = true; + if (letter !== "C" && !TAR_SHORT_VALUE_OPTIONS.includes(letter)) continue; + const value = i + 1 < arg.length ? arg.slice(i + 1) : (args[++k] ?? ""); + if (letter === "C") changeDir(value); + break; + } + } + } else if (head === "unzip") { + extracting = true; + const option = args.indexOf("-d"); + if (option !== -1) into = args[option + 1] ?? into; + } else if (head === "cpio") { + extracting = args.some((arg) => /^-[A-Za-z]*i/.test(arg) || arg === "--extract"); + } else if (head === "7z" || head === "7za" || head === "7zz") { + extracting = args[0] === "x" || args[0] === "e"; + const out = args.find((arg) => arg.startsWith("-o")); + if (out !== undefined) into = out.slice(2); + } + if (!extracting) return false; + const places = intos.length > 0 ? [into, ...intos] : [into]; + return places.some((place) => isBinDir(place === "" ? "." : place)); + }; + // curl reads options from `-K FILE` / `--config FILE` as if they were on + // the line, so they are read onto it; one it cannot read is refused. A + // short-option cluster is read the way curl's parser reads it: `K` takes + // the rest of the cluster or the next word (`-sKinner.cfg`), and a letter + // that takes a value before it makes the `K` part of that value (`-oK`). A + // config may name another (`config = inner.cfg`), which is read in turn, + // MAX_CURL_CONFIG_DEPTH deep and MAX_INSTRUCTION_FILE_BYTES in all (found by + // hermes on FailproofAI/failproofai#1058). + const withCurlConfig = (list: string[]): string[] | null => { + if (list.length === 0 || commandBasename(list[0]) !== "curl") return list; + let bytes = 0; + const expandArgs = (args: string[], depth: number): string[] | null => { + const out: string[] = []; + for (let k = 0; k < args.length; k++) { + const arg = args[k]; + let file: string | undefined; + if (arg.startsWith("--")) { + const eq = arg.indexOf("="); + const name = arg.slice(2, eq === -1 ? undefined : eq); + if (name.length >= 4 && "config".startsWith(name)) file = eq === -1 ? (args[++k] ?? "") : arg.slice(eq + 1); + } else if (/^-[^-]/.test(arg)) { + for (let i = 1; i < arg.length; i++) { + const letter = arg[i]; + if (letter === "K") { + if (i > 1) out.push(arg.slice(0, i)); + file = i + 1 < arg.length ? arg.slice(i + 1) : (args[++k] ?? ""); + break; + } + if (CURL_SHORT_VALUE_OPTIONS.includes(letter)) break; + } + } + if (file === undefined) { + out.push(arg); + continue; + } + if (depth >= MAX_CURL_CONFIG_DEPTH) return null; + const text = instructionsIn(file); + if (text === null) return null; + bytes += text.length; + if (bytes > MAX_INSTRUCTION_FILE_BYTES) return null; + const nested = expandArgs(curlConfigArgs(text), depth + 1); + if (nested === null) return null; + out.push(...nested); + } + return out; + }; + const expanded = expandArgs(list.slice(1), 0); + return expanded === null ? null : [list[0], ...expanded]; + }; + // A written word that still holds a value the walk cannot read — a + // substitution, or a variable set from what it cannot read or never set — + // could be anything there: `D=$(echo bins); cp stub $D/failproofai`. It + // lands on the entry or the state when what follows the last such value + // could, as if from anywhere npm installs (`$D/failproofai`), or when the + // name itself is unread and could be the entry, in a directory that is, or + // may be, npm's bin directory (`bins/$N`, `bins/${N}proofai`). + const unreadLands = (written: string): boolean => { + if (!/[$`]/.test(written)) return false; + const marked = written.replace(UNREAD_VALUE_RE, (piece) => (piece.startsWith("$((") ? "0" : "\u0000")); + if (!marked.includes("\u0000")) return false; + const tail = marked.slice(marked.lastIndexOf("\u0000") + 1).replace(/^[\\/]+/, ""); + if (tail !== "" && lostNamesState({ via: "", lost: tail })) return true; + const trimmed = marked.replace(/[\\/]+$/, ""); + const cut = trimmed.lastIndexOf("/"); + const component = trimmed.slice(cut + 1); + if (!component.includes("\u0000") || !couldBeEntryName(component.replaceAll("\u0000", "*"))) return false; + // A name that is wholly unread, in a directory that is too, is any path + // at all, as `> "$OUT"` is: only what the line spells can be judged. + const partial = component !== "\u0000"; + const directory = cut === -1 ? "." : trimmed.slice(0, cut) || "/"; + if (directory.includes("\u0000")) return partial; + return isBinDir(directory) || (partial && anywhereHere() && relativeWord(directory)); + }; + // `named` is the operand as written, judged when the walk cannot follow it. + // A `physical` move (`cd -P`, or any `cd` after `set -P`) goes where the path + // really is, each link followed and each `..` taken after it: with `deep` a + // link to `node_modules/.bin/sub`, `cd -P deep/..` stands in `.bin`, which + // collapsing `..` as text read as the directory it started from (found by + // hermes on FailproofAI/failproofai#1058). + const whereAfter = (base: Where, target: string, named: string, physical = false): Where => { + if (/\$|`/.test(target)) return { dir: undefined, full: undefined, deep: false, lost: true, inState: namesState(named) }; + const relative = relativeWord(target); + if (relative && base.lost) { + return { dir: undefined, full: undefined, deep: false, lost: true, inState: namesState(named) }; + } + const homeBased = target === "~" || target.startsWith("~/"); + let full: string | undefined = !relative + ? target.startsWith("/") + ? shellPath(undefined, target) + : homeBased + ? shellPath(undefined, homedir() + target.slice(1)) + : undefined + : base.full !== undefined + ? shellPath(base.full === "." ? undefined : base.full, target) || "." + : undefined; + if (physical) { + const raw = !relative + ? target.startsWith("/") + ? target + : homeBased + ? homedir() + target.slice(1) + : undefined + : base.full?.startsWith("/") + ? `${base.full}/${target}` + : undefined; + if (raw !== undefined) { + const real = realPath(raw); + if (typeof real !== "string") return { dir: undefined, full: undefined, deep: false, lost: true, inState: namesState(named) }; + full = real; + } + } + // `~user` and a `cd` from a directory too deep to keep are read from `dir`. + const fromDir = shellPath(relative ? base.dir : undefined, target); + let deep = relative && base.deep; + if (full !== undefined && full.length > FULL_DIR_SEGMENTS && full.split("/").length > FULL_DIR_SEGMENTS) { + full = undefined; + deep = true; + } + const kept = full !== undefined ? (full === "." ? undefined : shellTail(full)) : shellTail(fromDir); + // Inside the state: going further down from inside stays inside, so only a + // move that names a new path or climbs out reads the whole path again. + const climbs = /(?:^|\/)\.\.(?:\/|$)/.test(target); + const inState = + namesState(named) || + (kept !== undefined && namesState(kept)) || + (relative && !climbs + ? base.inState + : full !== undefined && (!relative || base.inState) && FAILPROOFAI_STATE_PATH_RE.test(full)); + return { dir: kept, full, deep, lost: false, inState, anywhere: relative && base.anywhere }; + }; + // Moves the shell to `to`, and anywhere else it may stand to `others`. If + // the move fails, it stays wherever it was, which `pending` keeps — unless + // it returns somewhere the shell has already stood (`popd`, `cd -`, the + // session's own directory), which exists. + const moveTo = (to: Where, others: Where[] = [], certain = false) => { + if (sameWhere(to, at) && alts.length === 0) return; + previous = at; + if (!certain) pending = fold([...pending, at, ...alts], 2 * MAX_ALTERNATE_DIRS); + at = to; + alts = possible(others); + cwdInState = at.inState; + cdParenDepth = cwdInState ? parenDepth : null; + }; + // `cd`, `pushd` and `popd` as bash runs them. A move that fails — `popd` on + // an empty stack, `cd -` with nowhere to go back to, `cd ""` — leaves the + // shell where it was, never somewhere safe. `+N` / `-N` count entries the + // way `dirs` lists them: the current directory first, then the stack from + // its top, and `-n` changes the stack without moving. `cd -` is `$OLDPWD` and + // a bare `cd` is `$HOME`, either of which the line may set itself. + const moveShell = (head: string, args: string[], expandedArgs: string[]) => { + const stackOnly = head !== "cd" && args.includes("-n"); + const k = args.findIndex((w) => !w.startsWith("-") || w === "-" || /^[+-]\d+$/.test(w)); + // `cd -P` and `-L`, the last one given winning; `pushd` follows `set -P`. + let physical = physicalMoves; + if (head === "cd") { + for (const option of args.slice(0, k === -1 ? args.length : k)) { + if (!/^-[A-Za-z@]+$/.test(option)) continue; + for (const flag of option.slice(1)) { + if (flag === "P") physical = true; + else if (flag === "L") physical = false; + } + } + } + const named = k === -1 ? undefined : args[k]; + const operand = k === -1 ? undefined : expandedArgs[k]; + if (operand !== undefined && head !== "cd" && /^[+-]\d+$/.test(operand)) { + const entries = [at, ...[...dirStack].reverse()]; + const n = Number(operand.slice(1)); + const index = operand.startsWith("+") ? n : entries.length - 1 - n; + if (index < 0 || index >= entries.length || stackOnly) return; + if (head === "pushd") { + const rotated = [...entries.slice(index), ...entries.slice(0, index)]; + dirStack.splice(0, dirStack.length, ...rotated.slice(1).reverse()); + moveTo(rotated[0], [], true); + } else if (entries.length > 1) { + const rest = entries.filter((_, i) => i !== index); + dirStack.splice(0, dirStack.length, ...rest.slice(1).reverse()); + if (index === 0) moveTo(rest[0], [], true); + } + return; + } + if (head === "popd") { + const top = dirStack.pop(); + if (top && !stackOnly) moveTo(top, [], true); + return; + } + if (head === "pushd" && operand === undefined) { + if (stackOnly) return; + const top = dirStack.pop(); + if (top) { + dirStack.push(at); + moveTo(top, [], true); + } + return; + } + if (operand === "-") { + const oldpwd = values.get("OLDPWD"); + if (oldpwd !== undefined) moveTo(whereAfter(at, expand(oldpwd), oldpwd, physical)); + else if (previous) moveTo(previous, [], true); + return; + } + if (operand === "") return; + let target = operand ?? expand("$HOME"); + // A pattern is the directory it matches on disk, and this line's links + // (`ln -s ../node_modules/.bin out/b && cd out/b*`). Matching none, the + // `cd` fails and the shell stays; matching several, bash 4.4 and later + // fail and older ones take the first, which a move that may fail covers. + if (GLOB_METACHAR_RE.test(target) && !/[$`]/.test(target)) { + const matches = globPaths(at, target); + if (matches !== null && matches.length === 0) return; + target = matches?.[0] ?? "$(unknown)"; + } + const to = whereAfter(at, target, named ?? target, physical); + if (stackOnly) { + dirStack.push(to); + return; + } + if (head === "pushd") dirStack.push(at); + // Wherever else the shell may stand moves too, the same way, and to each + // other value the operand may hold: `D=bins; (D=out); cd $D` stands in + // `bins` (found by hermes on FailproofAI/failproofai#1058). + const others = named === undefined ? [] : variantsOf(named); + moveTo( + to, + [ + ...alts.map((where) => whereAfter(where, target, named ?? target, physical)), + ...others.flatMap((other) => [at, ...alts].map((where) => whereAfter(where, other, named ?? other, physical))), + ], + startFull.startsWith("/") && to.full === startFull, + ); + }; + // `ln -s … `, in every form GNU ln takes: `-t DIR` + // in any spelling, a last operand that is a directory (`.`, `dir/`, one on + // disk, or a link to one unless `-n`), several targets into one directory, + // and `-r`, which reads each target from where the shell stands rather than + // from the link. `ln -s node_modules/.bin/failproofai .` made `./failproofai` + // a link to the entry while the walk recorded the directory itself. Each link + // is keyed by where it really is, its parent resolved through every link + // before it, so a later write through it on the same line lands where it would. + const LN_OPTIONS = INTO_DIRECTORY_OPTIONS.get("ln")!; + const baseNameOf = (word: string): string => { + const trimmed = word.replace(/[\\/]+$/, ""); + return trimmed.slice(trimmed.lastIndexOf("/") + 1); + }; + // Where a link written as `word` from `base` goes: its parent resolved, its + // own name not followed, as `symlink()` creates it. + const linkPlace = (base: Where, word: string): string | undefined => { + const path = absoluteFrom(base, word.replace(/[\\/]+$/, "") || word); + if (path === undefined) return undefined; + const cut = path.raw.replace(/\/+$/, "").lastIndexOf("/"); + const parent = realPath(path.raw.slice(0, cut) || "/"); + const name = path.raw.replace(/\/+$/, "").slice(cut + 1); + if (typeof parent !== "string" || name === "" || name === "." || name === "..") return undefined; + return `${parent === "/" ? "" : parent}/${name}`; + }; + // Whether `word` is a directory for `ln` to put links into: on disk, or a + // link this line made to one, followed unless `-n`. `undefined` when it does + // not exist yet, which a `mkdir` earlier on the line may change. + const linksInto = (base: Where, word: string, noDereference: boolean): boolean | undefined => { + if (/[\\/]$/.test(word) || word === "." || word === ".." || /[\\/]\.\.?$/.test(word)) return true; + const place = linkPlace(base, word); + if (place === undefined) return false; + if (links.has(place)) { + if (noDereference) return false; + const real = realPath(place); + if (typeof real !== "string") return true; + try { + return statSync(real).isDirectory(); + } catch { + return undefined; + } + } + try { + return (noDereference ? lstatSync(place) : statSync(place)).isDirectory(); + } catch { + return undefined; + } + }; + const recordLink = (args: string[]): void => { + let symbolic = false; + let fromShell = false; + let noDereference = false; + let ontoItself = false; + let directory: string | undefined; + const operands: string[] = []; + for (let i = 0; i < args.length; i++) { + const arg = args[i]; + if (arg === "--") { + operands.push(...args.slice(i + 1)); + break; + } + if (arg.startsWith("--")) { + const eq = arg.indexOf("="); + const option = longOptionOf(LN_OPTIONS, arg.slice(2, eq === -1 ? undefined : eq)); + if (option?.full === "target-directory") directory = eq === -1 ? args[++i] : arg.slice(eq + 1); + else if (option?.value) i += eq === -1 ? 1 : 0; + else if (option?.full === "symbolic") symbolic = true; + else if (option?.full === "relative") fromShell = true; + else if (option?.full === "no-dereference") noDereference = true; + else if (option?.full === "no-target-directory") ontoItself = true; + continue; + } + if (arg.startsWith("-") && arg.length > 1) { + for (let c = 1; c < arg.length; c++) { + const flag = arg[c]; + if (LN_OPTIONS.short.includes(flag)) { + // The rest of the cluster is the value, or else the next word is. + const value = c + 1 < arg.length ? arg.slice(c + 1) : args[++i]; + if (flag === "t") directory = value; + break; + } + if (flag === "s") symbolic = true; + else if (flag === "r") fromShell = true; + else if (flag === "n") noDereference = true; + else if (flag === "T") ontoItself = true; + } + continue; + } + operands.push(arg); + } + if (!symbolic || operands.length === 0) return; + for (const base of [at, ...alts]) { + const placed: Array<[string | undefined, string]> = []; + if (directory !== undefined) { + for (const target of operands) placed.push([linkPlace(base, `${directory}/${baseNameOf(target)}`), target]); + } else if (operands.length === 1) { + placed.push([linkPlace(base, baseNameOf(operands[0])), operands[0]]); + } else { + const last = operands[operands.length - 1]; + const targets = operands.slice(0, -1); + const into = targets.length > 1 ? true : ontoItself ? false : linksInto(base, last, noDereference); + // Into the directory, or the operand itself; both when it does not + // exist yet, since the line may have made it. + if (into !== false) for (const target of targets) placed.push([linkPlace(base, `${last.replace(/[\\/]+$/, "")}/${baseNameOf(target)}`), target]); + if (into !== true) placed.push([linkPlace(base, last), targets[0]]); + } + for (const [place, written] of placed) { + if (place === undefined || written === undefined) continue; + let target = written === "~" || written.startsWith("~/") ? homedir() + written.slice(1) : written; + // `-r` reads the target from where the shell stands. + if (fromShell && relativeWord(target) && !/[$`]/.test(target)) { + const fromHere = absoluteFrom(base, target); + if (fromHere === undefined) continue; + target = fromHere.raw; + } + links.set(place, target); + } + } + // Every path resolved so far may now run through one of these. + realPaths.clear(); + directoryWalks.clear(); + }; + + // A loop header hands its word list to the body, and the body is a separate + // pipeline that names nothing. Without this, `for f in ~/.failproofai/*; do + // rm -rf $f; done` is a header that only expands and a body that only deletes + // something called `$f`. + let loopCarriesState = false; + const parts = splitUnquoted(command, PIPELINE_SEPARATORS); + for (let part = 0; part < parts.length; part += 2) { + const pipeline = parts[part]; + // A move the next command does not depend on may have failed, so from + // there on the directory before it is possible too. + if (part > 0 && parts[part - 1] !== "&&" && pending.length > 0) { + alts = possible([...pending, ...alts]); + pending = []; + } + if (!pipeline.trim()) continue; + // `declare -n R=D` makes `R` a name for `D`, read through it. + const namerefs = new Map(); + for (const [, name, target] of pipeline.matchAll(NAMEREF_RE)) namerefs.set(name, target); + // A value is what the shell stores: its references read when it is + // assigned, each with every value it may hold, so `A=bins; (A=out); + // B=$A` gives `B` both (found by hermes on FailproofAI/failproofai#1058). + for (const [, name, value] of pipeline.matchAll(ASSIGNMENT_RE)) { + let bare = value.replace(/^["']|["']$/g, ""); + // A substitution with a space in it arrives cut short (`$(echo`): its + // value is one the walk cannot read, whole. + if ((bare.match(/\$\(/g) ?? []).length > (bare.match(/\)/g) ?? []).length || (bare.match(/`/g) ?? []).length % 2 === 1) bare = "$(…)"; + const target = namerefs.get(name); + const now = target !== undefined ? `\${${target}}` : expand(bare); + const others = target !== undefined ? [] : variantsOf(bare); + if (values.has(name)) assigned(name, values.get(name)!); + values.set(name, now); + assigned(name, now); + for (const other of others) assigned(name, other); + } + // A loop's variable takes each value its list gives, and `read`, + // `printf -v` and `mapfile` set one too. + const loop = LOOP_VARIABLE_RE.exec(pipeline.trim()); + if (loop !== null) loopValues(loop[1], loop[2] ?? ""); + const simpleCommands = splitUnquoted(pipeline, /\|/).filter((_, k) => k % 2 === 0); + const reachesState = namesState(pipeline) || cwdInState || loopCarriesState; + if (reachesState && LOOP_HEADER_RE.test(pipeline)) loopCarriesState = true; + if (/(?:^|\s)done(?:\s|$)/.test(pipeline)) loopCarriesState = false; + + // A redirect is a write with no command in front of it — `> path` empties a + // file on its own. Only a redirect whose TARGET is the state counts: the + // previous version matched any `>` anywhere in the segment, so + // `grep -r sudo ~/.failproofai 2>/dev/null` and + // `cat ~/.failproofai/config.json > /tmp/backup.json` both denied, which is + // exactly the diagnosis this guard must not block. + for (const [, target] of pipeline.matchAll(REDIRECT_TARGET_RE)) { + const written = target.replace(/^["']|["']$/g, ""); + if (namesHere(written) || namesHere(expand(written)) || expandEverywhere(written).some(namesHere)) return true; + if (sweepWritesEntry(written) || sweepWritesEntry(expand(written)) || unreadLands(expand(written))) return true; + if (anywhereHere() && (plantsAnywhere(written) || plantsAnywhere(expand(written)))) return true; + if (variantsOf(written).some((variant) => namesHere(variant) || (anywhereHere() && plantsAnywhere(variant)))) return true; + } - const findIdx = tokens.findIndex((t) => FIND_CMD_RE.test(t)); - if (findIdx >= 0) { - const expr = tokens.slice(findIdx + 1); - const execIdx = expr.findIndex((t) => FIND_EXEC_RE.test(t)); - const deletes = expr.includes("-delete") || (execIdx >= 0 && RM_CMD_RE.test(expr[execIdx + 1] ?? "")); - if (deletes) { - // find's path operands sit between the leading global options and the - // first expression token: `find -L /home/chetan -name '*.log' -delete` - let start = 0; - while (start < expr.length && FIND_GLOBAL_OPT_RE.test(expr[start])) { - start += expr[start] === "-D" ? 2 : 1; + for (const simple of simpleCommands) { + // Parentheses inside quotes or escaped open and close nothing, and a + // substitution's are not a subshell: `cd $(npm root)/.bin` moves this shell. + const shellText = withoutSubstitutions(simple.replace(/\\[()]|'[^']*'|"(?:[^"\\]|\\.)*"/g, "")); + parenDepth += (shellText.match(/\(/g) ?? []).length; + const configured = withCurlConfig(commandWordList(simple)); + if (configured === null) return true; + const words = configured; + const expanded = words.map(expand); + const lists = expanded.some((word, k) => word !== words[k]) ? [words, expanded] : [words]; + if (alts.length > 0 && words.some((word) => NAMES_PWD_RE.test(word))) { + for (const alt of alts) lists.push(words.map((word) => expandAt(word, alt))); + } + // The line read with each other value a reassigned variable may hold + // that could reach what is protected: the path itself, npm's bin + // directory, or the entry from a directory the agent may not report. + const variantLists: string[][] = []; + for (let k = 1; k < words.length; k++) { + for (const variant of variantsOf(words[k])) { + const reaches = + namesHere(variant) || + NPM_BIN_DIRECTORY_RE.test(variant.replace(/[\\/]+$/, "")) || + isBinDir(variant) || + (anywhereHere() && plantsAnywhere(variant)); + if (!reaches) continue; + if (variantLists.length >= 16) throw new Error("a variable is reassigned too many times to follow"); + variantLists.push(expanded.map((word, j) => (j === k ? variant : word))); + } + } + lists.push(...variantLists); + const head = words.length > 0 ? commandBasename(words[0]) : ""; + if (head === "cd" || head === "pushd" || head === "popd") { + // Every stage of a pipeline runs in a subshell of its own, so a `cd` + // there moves nothing the rest of the line sees. + if (simpleCommands.length === 1) { + if (parenDepth > 0) { + scopes.push({ depth: parenDepth, at, previous, stack: dirStack.slice(), alts: alts.slice(), pending: pending.slice(), physical: physicalMoves }); + } + moveShell(head, words.slice(1), expanded.slice(1)); + } + } else if ( + [at, ...alts].some((base) => + lists.some( + (list) => + landsInDirectoryAs(list, namesState, (word) => fromBase(base, word), base.lost, landsOnState, isBinDir) || + // From a directory the agent may have run the line in without + // saying, a copy is also read as written, from somewhere unknown. + (base.anywhere === true && landsInDirectoryAs(list, namesState, (word) => word, true, landsOnState, isBinDir)) || + downloadLandings(list).some(({ dir, name }) => { + const into = fromBase(base, dir).replace(/(?:[\\/]+\.?)+$/, ""); + if (name === null) return NPM_BIN_DIRECTORY_RE.test(into) || isBinDir(dir) || (base.anywhere === true && relativeWord(dir)); + const landing = `${dir.replace(/[\\/]+$/, "")}/${name}`; + return ( + namesState(fromBase(base, landing)) || + landsOnState(landing) || + ((base.lost || base.anywhere === true) && relativeWord(dir) && couldBeEntryName(name)) + ); + }), + ), + ) || + lists.some((list) => writtenOperands(list).some(sweepWritesEntry)) || + writtenOperands(expanded).some(unreadLands) || + copiesIntoUnread(expanded) || + (head === "sed" && lists.some((list) => sedScriptWrites(list.slice(1)))) || + lists.some((list) => patchFileWrites(list, simple) || extractsIntoBin(list)) || + (anywhereHere() && lists.some(writesEntryAnywhere)) + ) { + // Before the `reachesState` gate, because the point is that nothing on + // the line names the path: the source's name and the directory do. + return true; + } else if ( + words.length > 0 && + // Operands only: the command word is a program, not a path written to. + // The line as written is `reachesState`; a word adds to it only by + // resolving from where the shell stands or through a symlink, or by + // what expansion made it. + // Whether the command destroys anything is asked FIRST: both halves + // are pure, and the operand checks below stat every word on disk, so + // a `printf` of 40,000 arguments, which writes none of them, made + // 40,000 lstat calls before being asked. + lists.some((list) => simpleCommandDestroysForState(list, namesHere)) && + (reachesState || + words.some( + (word, k) => + k > 0 && + (resolvesOntoState(word) || landsOnState(word) || (expanded[k] !== word && namesHere(expanded[k]))), + ) || + // A value glued to its option is a path too, read from where the + // shell stands and through links: `cd node_modules/.bin && curl + // -sofailproofai `, and `curl -sohook ` with `hook` a link + // to the entry (found by hermes on FailproofAI/failproofai#1058). + lists.some((list) => + list.some((word, k) => { + if (k === 0 || !word.startsWith("-")) return false; + const values = gluedOptionValues(head, word); + return values === null || values.some(gluedValueNamesHere); + }), + ) || + variantLists.length > 0 || + // A file a sed script writes, read the same way. + (head === "sed" && lists.some((list) => sedWriteTargets(sedScriptArgs(list.slice(1))).some(namesHere)))) + ) { + // Judged BEFORE the closing parenthesis is counted: a `rm -rf ./*)` + // still runs inside the subshell it closes. + return true; + } else if (head === "ln" && simpleCommands.length === 1) { + recordLink(expanded.slice(1)); + } else if (head === "set" && simpleCommands.length === 1) { + // Inside `( … )` it is the subshell's setting only, put back when it + // closes (found by hermes on FailproofAI/failproofai#1058). + if (parenDepth > 0) { + scopes.push({ depth: parenDepth, at, previous, stack: dirStack.slice(), alts: alts.slice(), pending: pending.slice(), physical: physicalMoves }); + } + for (let i = 1; i < words.length; i++) { + if (/^[-+][A-Za-z]+$/.test(words[i]) && words[i].includes("P")) physicalMoves = words[i][0] === "-"; + else if ((words[i] === "-o" || words[i] === "+o") && words[i + 1] === "physical") physicalMoves = words[i] === "-o"; + } + } + // The builtins that set a variable without `=`. A pipeline's stages run + // in subshells, so only a command standing alone sets one this line keeps. + if (simpleCommands.length === 1) setByBuiltin(head, words, simple); + parenDepth = Math.max(0, parenDepth - (shellText.match(/\)/g) ?? []).length); + if (cdParenDepth !== null && parenDepth < cdParenDepth) { + cwdInState = false; + cdParenDepth = null; + } + // Leaving a subshell puts back where the shell stood before it, inside + // the state included: `cd ~/.failproofai && (cd /tmp) && rm -rf *`. + while (scopes.length > 0 && parenDepth < scopes[scopes.length - 1].depth) { + const scope = scopes.pop()!; + at = scope.at; + previous = scope.previous; + alts = scope.alts; + pending = scope.pending; + physicalMoves = scope.physical; + dirStack.splice(0, dirStack.length, ...scope.stack); + cwdInState = at.inState; + cdParenDepth = cwdInState ? parenDepth : null; } - const rest = expr.slice(start); - const end = rest.findIndex((t) => FIND_EXPR_START_RE.test(t)); - return end < 0 ? rest : rest.slice(0, end); } } - - const rmIdx = tokens.findIndex((t) => RM_CMD_RE.test(t)); - if (rmIdx >= 0) { - const args = tokens.slice(rmIdx + 1); - const shortFlags = args.filter((t) => /^-[^-]/.test(t)).join(""); - const longFlags = args.filter((t) => /^--/.test(t)); - const recursive = /r/i.test(shortFlags) || longFlags.some((f) => /^--recursive$/i.test(f)); - const force = /f/.test(shortFlags) || longFlags.some((f) => /^--force$/i.test(f)); - if (recursive && force) return args.filter((t) => !t.startsWith("-")); - } - - return null; -} - -/** Split a command into the segments the shell would run as separate commands. */ -function shellSegments(cmd: string): string[] { - return cmd.split(/&&|\|\||[|;\n]/).map((s) => s.trim()).filter((s) => s !== ""); + return false; } - +/** How much of the shell's directory the walk reads words from; see `shellTail`. */ +const SHELL_DIR_SEGMENTS = 16; /** - * Check whether all recursive-delete targets in a command are under an allowlisted path. - * Splits on shell operators first so that `/tmp` appearing in an unrelated - * sub-command (e.g. `echo /tmp && rm -rf /`) does not trigger a false allow. - * Uses path-boundary comparison so `/tmp` does not cover `/tmp2`. - * Non-recursive rm segments (no -r/-R flag) are skipped — they pose no catastrophic risk. - * Quoted paths with spaces are handled via a segment-level regex fallback. - * Home-relative targets and allowPaths entries are expanded, so `~/scratch` is - * covered by an allowPaths entry of either `~/scratch` or the absolute home path. + * How much of the shell's whole path the walk keeps for a `..` that climbs + * above `SHELL_DIR_SEGMENTS` and for following symlinks. Bounded so that a + * script of a thousand `cd`s stays linear. */ -function deletionTargetIsAllowed(cmd: string, allowPaths: string[]): boolean { - if (allowPaths.length === 0) return false; - const normalizedAllowPaths = allowPaths.map((p) => stripTrailingGlob(expandHomePrefix(p)) || "/"); - let sawRecursiveDelete = false; - for (const seg of shellSegments(cmd)) { - const targets = recursiveDeletionTargets(seg); - if (targets === null) continue; - sawRecursiveDelete = true; - for (const target of targets) { - const normalized = stripTrailingGlob(expandHomePrefix(target)) || "/"; - const covered = normalizedAllowPaths.some((np) => normalized === np || normalized.startsWith(np + "/")); - if (!covered) { - // Fallback: check the raw segment for quoted paths that contain spaces - // (parseArgvTokens splits on whitespace, so "/tmp/my dir" becomes two tokens) - const segCovered = allowPaths.some((p) => { - const escaped = p.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); - return new RegExp(`${escaped}(?:[/"'\\s/*]|$)`).test(seg); - }); - if (!segCovered) return false; +const FULL_DIR_SEGMENTS = 64; +/** How many directories a failed `cd` can leave the shell in that the walk tracks. */ +const MAX_ALTERNATE_DIRS = 4; +/** Linux's PATH_MAX: `open(2)` refuses a longer path with ENAMETOOLONG. */ +const PATH_MAX_BYTES = 4096; +/** + * Where a relative word is also read once the walk has lost the shell's + * directory: the places an installed failproofai entry or package lives. Only + * a word that names one there can match, so an ordinary file is unaffected. + */ +const AS_IF_INSTALLED = ["node_modules/.bin/", "node_modules/", "/bin/"]; +/** + * The directories a glob candidate continues from by one name: `.bin` and + * `bin` hold the entry, `node_modules` and `.pnpm` the package, `pnpm` is + * pnpm's home. Only from these can a relative glob that does not spell the + * name itself (`fail*`) land on installed code. + */ +const GLOB_PARENT_DIRECTORIES = new Set([".bin", "bin", "node_modules", ".pnpm", "pnpm"]); +/** + * `text` without its `$(…)` command substitutions, so their parentheses are + * not counted as a subshell's. One left open runs to the end of the text. + */ +function withoutSubstitutions(text: string): string { + let out = ""; + for (let i = 0; i < text.length; i++) { + if (text[i] === "$" && text[i + 1] === "(") { + let depth = 0; + let j = i + 1; + for (; j < text.length; j++) { + if (text[j] === "(") depth++; + else if (text[j] === ")" && --depth === 0) break; } + i = j; + continue; } + out += text[i]; } - return sawRecursiveDelete; -} - -function blockRmRf(ctx: PolicyContext): PolicyResult { - if (ctx.toolName !== "Bash") return allow(); - const cmd = getCommand(ctx); - - const hasCatastrophicTarget = shellSegments(cmd).some((seg) => { - const targets = recursiveDeletionTargets(seg); - return targets !== null && targets.some(isCatastrophicTarget); - }); - if (hasCatastrophicTarget) { - const allowPaths = ((ctx.params?.allowPaths ?? []) as string[]); - if (deletionTargetIsAllowed(cmd, allowPaths)) return allow(); - return deny("Catastrophic deletion blocked"); - } - - // PowerShell: Remove-Item -Recurse -Force on root/drive - if (/Remove-Item\s+.*-Recurse.*-Force.*(?:[A-Z]:\\(?:\s|$)|\\\*)/i.test(cmd)) { - return deny("Catastrophic deletion blocked"); - } - // cmd: rd /s /q or rmdir /s /q on drive root - if (/(?:rd|rmdir)\s+\/s\s+\/q\s+[A-Z]:\\/i.test(cmd)) { - return deny("Catastrophic deletion blocked"); - } - return allow(); + return out; } - -function blockForcePush(ctx: PolicyContext): PolicyResult { - if (ctx.toolName !== "Bash") return allow(); - for (const segment of extractGitPushArgs(getCommand(ctx))) { - let sawEndOfOptions = false; - for (const token of segment.split(/\s+/)) { - if (token === "--") { - sawEndOfOptions = true; - continue; - } - if (sawEndOfOptions) continue; - if (isForcePushFlag(token)) { - return deny("Force-pushing is blocked"); - } - } - } - return allow(); +/** A word a shell reads from its current directory: not `~`, `/`, `$…` or `C:`. */ +function relativeWord(word: string): boolean { + return word !== "" && !/^(?:[~/\\$]|[A-Za-z]:)/.test(word); } - -function isForcePushFlag(token: string): boolean { - if (token === "--force") return true; - if (SAFE_FORCE_PREFIXES.some((prefix) => token.startsWith(prefix))) return false; - if (token.startsWith("--force")) return true; - return SHORT_FLAG_BUNDLE_RE.test(token); +/** The entry's own name, a Windows shim of it, or a glob that could be either. */ +/** The names npx runs for `failproofai` in a bin directory, the Windows shims included. */ +const NPX_ENTRY_NAMES = ["failproofai", "failproofai.cmd", "failproofai.ps1", "failproofai.exe", "failproofai.bunx"]; +/** A path that is npx's entry for `failproofai`. */ +const NPX_ENTRY_PATH_RE = /(?:^|[\\/])node_modules[\\/](?:\.?[\\/])*\.bin[\\/]failproofai(?:\.(?:cmd|ps1|exe|bunx))?$/i; +function couldBeEntryName(name: string): boolean { + return /^failproofai(?:\.(?:cmd|ps1|exe|bunx))?$/i.test(name) || (GLOB_METACHAR_RE.test(name) && globCouldBeEntry(name)); } - -function blockSecretsWrite(ctx: PolicyContext): PolicyResult { - if (ctx.toolName !== "Write") return allow(); - const filePath = getFilePath(ctx); - if (SECRET_FILE_RE.test(filePath) || SECRET_FILE_ID_RSA_RE.test(filePath) || SECRET_FILE_CREDENTIALS_RE.test(filePath)) { - return deny("Writing secret key files is blocked"); - } - const additionalPatterns = ((ctx.params?.additionalPatterns ?? []) as string[]); - for (const pattern of additionalPatterns) { - if (filePath.includes(pattern)) { - return deny(`Writing blocked file pattern: ${pattern}`); +/** + * `word` read from directory `base` (as given when absolute, or with no base), + * with `//`, `.` and `..` resolved as text, the way a shell's logical `cd` + * does. + */ +function shellPath(base: string | undefined, word: string): string { + const joined = base === undefined ? word : `${base}/${word}`; + const absolute = joined.startsWith("/"); + const parts: string[] = []; + for (const part of joined.split("/")) { + if (part === "" || part === ".") continue; + if (part === "..") { + if (parts.length > 0 && parts[parts.length - 1] !== "..") parts.pop(); + else if (!absolute) parts.push(part); + continue; } + parts.push(part); } - return allow(); + return (absolute ? "/" : "") + parts.join("/"); } - -/** Read-like commands that access file system contents. */ -const READ_LIKE_CMDS = - /(?:^|;|&&|\|\||\|)\s*(?:ls|find|cat|head|tail|less|more|wc|file|stat|tree|du)\s/; - /** - * Extract absolute paths from a Bash command string. - * Scans quoted strings only in the first pipeline segment (before the first - * bare pipe) and only when the quoted content has no glob or regex metacharacters. - * This catches `cat "/etc/passwd"` while avoiding false positives from grep - * patterns and find glob patterns that appear in later pipeline stages. - * Unquoted absolute paths are extracted from the whole command as before. - * - * The negative lookbehind also excludes glob metacharacters ('*', '?') and - * separator characters that appear in compound argv tokens (':' for Docker - * volume mounts and PATH-like lists, '=' for env var assignments) so that a - * suffix like '/dashboard.mdx' in 'docs/STAR/dashboard.mdx' or '/docs' in - * '-v HOST_DIR:/docs' is not misread as a standalone absolute path. '/' is in - * that list too, so a match cannot START on the second slash of a protocol - * separator: 'http://localhost:3000/x' used to yield '/localhost:3000/x'. - * A match that starts on the FIRST slash is untouched, so '//etc/passwd' — - * a real, working spelling of /etc/passwd — is still extracted and still - * resolves to /etc/passwd. - * - * A run of slashes with nothing else ('//', '///') that opens a line after - * the first is dropped: that is a line-comment marker in a heredoc body, not a - * directory. It used to resolve to the filesystem root, which denied a heredoc - * writing a TypeScript file into the project. Anywhere else a slash-run is - * the root, as a lone '/' is: `cd // && cat etc/shadow` reads /etc/shadow. + * A directory cut to its last `SHELL_DIR_SEGMENTS` segments. Every protected + * pattern matches the END of a path, so the dropped head never decides + * anything, and the cut keeps a script of a thousand `cd`s from growing every + * later word it is joined to. */ -function extractAbsolutePaths(command: string): string[] { - const paths: string[] = []; - const pathRe = /(?//`, which bash joins into one line. - if (/^\/{2,}$/.test(p)) { - const nl = s.lastIndexOf("\n", m.index - 1); - if (nl !== -1 && s[nl - 1] !== "\\" && /^[ \t]*$/.test(s.slice(nl + 1, m.index))) continue; - } - if (p === "~") p = homedir(); - else if (p.startsWith("~/")) p = join(homedir(), p.slice(2)); - paths.push(p); - } - } - - // Find the index of the first bare pipe (not inside quotes) to limit quoted extraction. - let firstBarePipe = command.length; - let inDouble = false, inSingle = false; - for (let i = 0; i < command.length; i++) { - const c = command[i]; - if (c === '"' && !inSingle) inDouble = !inDouble; - else if (c === "'" && !inDouble) inSingle = !inSingle; - else if (c === "|" && !inDouble && !inSingle) { firstBarePipe = i; break; } - } - - // Extract paths from quoted strings in the FIRST pipeline segment only, - // and only when the content has no glob/regex metacharacters. - const firstSegment = command.slice(0, firstBarePipe); - const quotedRe = /"([^"]*)"|'([^']*)'/g; - let qm: RegExpExecArray | null; - while ((qm = quotedRe.exec(firstSegment)) !== null) { - const content = qm[1] ?? qm[2] ?? ""; - // Skip patterns that contain glob or common regex metacharacters - if (/[*?\[\]^$+()\\]/.test(content)) continue; - addPaths(content); +function shellTail(path: string): string { + let cut = path.length; + for (let kept = 0; kept < SHELL_DIR_SEGMENTS; kept++) { + if (cut <= 0) return path; + cut = path.lastIndexOf("/", cut - 1); + if (cut < 0) return path; } - - // Extract from unquoted portions of the whole command (existing behaviour). - const stripped = command - .replace(/"[^"]*"/g, (m) => " ".repeat(m.length)) - .replace(/'[^']*'/g, (m) => " ".repeat(m.length)); - addPaths(stripped); - - return paths; + return path.slice(cut + 1); } - -function blockReadOutsideCwd(ctx: PolicyContext): PolicyResult { - // Prefer $CLAUDE_PROJECT_DIR (stable project root) over ctx.session.cwd, - // which tracks the live shell CWD and drifts when Claude `cd`s into a subdir. - const cwd = process.env.CLAUDE_PROJECT_DIR || ctx.session?.cwd; - if (!cwd) return allow(); // Can't enforce without cwd - - const allowPaths = ((ctx.params?.allowPaths ?? []) as string[]); - - // For Bash tool: check read-like commands for absolute paths outside cwd - if (ctx.toolName === "Bash") { - const cmd = getCommand(ctx); - if (!READ_LIKE_CMDS.test(cmd)) return allow(); - - const paths = extractAbsolutePaths(cmd); - const cwdWithSep = cwd.endsWith("/") ? cwd : cwd + "/"; - for (const p of paths) { - const resolved = resolve(cwd, p); - if (isClaudeSettingsFile(resolved)) { - return deny(`Reading agent settings file blocked: ${resolved}`); - } - if (isClaudeInternalPath(resolved)) continue; // Whitelist ~/.claude/ - if (resolved === "/dev/null") continue; // Harmless special file - if (resolved !== cwd && !resolved.startsWith(cwdWithSep)) { - if (allowPaths.some((ap) => resolved === ap || resolved.startsWith(ap.endsWith("/") ? ap : ap + "/"))) continue; - return deny(`Bash read outside project directory blocked: ${resolved}`); +/** + * A patch's file headers: every file it adds, updates or deletes, and where + * `*** Move to:` renames one, in the format Codex's `apply_patch` takes + * (lenient about spacing, as its parser is); and the `---` / `+++` paths of a + * unified diff. + */ +const PATCH_FILE_RE = /^[ \t]*\*\*\*[ \t]*(?:(?:Add|Update|Delete)[ \t]+File|Move[ \t]+to)[ \t]*:[ \t]*(.*?)[ \t]*\r?$/gim; +const UNIFIED_DIFF_FILE_RE = /^(?:---|\+\+\+)[ \t]+(.*?)(?:\t.*)?\r?$/gm; +/** Input keys that hold what a file tool writes, never a patch to apply. */ +const FILE_CONTENT_KEYS = new Set(["content", "old_string", "new_string", "new_source", "file_text", "old_str", "new_str"]); +/** + * The files an edit tool's patch writes, when the tool carries a patch instead + * of a path. Codex's `apply_patch` (canonical `Edit`) delivers its patch as + * `tool_input.command`, with no `file_path` at all, so the path check below + * had nothing to read and a native patch could plant `node_modules/.bin/failproofai` + * (found by hermes on FailproofAI/failproofai#1058). OpenCode's sends `patchText`. + * Read from every input that is not a file's content, as text or a list of it. + */ +function patchTargets(input: Record | undefined): string[] { + const targets = new Set(); + for (const [key, value] of Object.entries(input ?? {})) { + if (FILE_CONTENT_KEYS.has(key)) continue; + const texts = typeof value === "string" ? [value] : Array.isArray(value) ? value.filter((v): v is string => typeof v === "string") : []; + for (const text of texts) { + for (const [, path] of text.matchAll(PATCH_FILE_RE)) if (path) targets.add(path); + for (const [, written] of text.matchAll(UNIFIED_DIFF_FILE_RE)) { + const path = written.replace(/^"(.*)"$/, "$1"); + if (!path || path === "/dev/null") continue; + targets.add(path); + // `a/` and `b/` are git's prefixes, not directories, unless they are. + if (/^[ab]\//.test(path)) targets.add(path.slice(2)); } } - return allow(); } - - // For Read/Glob/Grep: existing file_path / path check - const filePath = getFilePath(ctx); - const searchPath = (ctx.toolInput?.path as string) ?? ""; - - const target = filePath || searchPath; - if (!target) return allow(); - - const resolved = resolve(cwd, target); - - // Block settings files in any .claude directory before whitelisting - if (isClaudeSettingsFile(resolved)) { - return deny(`Reading agent settings file blocked: ${resolved}`); + return [...targets]; +} +/** The builtins that print their arguments and run none of them. */ +const PRINT_COMMANDS = new Set(["echo", "printf"]); +/** Readers a pipeline can hand printed text to without running any of it. */ +const TEXT_READERS = new Set([ + "cat", "less", "more", "head", "tail", "wc", "grep", "egrep", "fgrep", "sort", "uniq", "cut", "tr", "column", + "nl", "fold", "fmt", "rev", +]); +/** Where a print's own redirect can send it without keeping it anywhere it may be run from. */ +const HARMLESS_OUTPUT_RE = /^(?:&\d*-?|\/dev\/(?:null|stdout|stderr|tty))$/; +/** + * Commands that run a file or text they are handed: shells, interpreters and + * what runs a command for you. A line with one of these, or a command named by + * a path (`./notes.md`), may run a file it has just printed into. + */ +const RUNS_FILES = new Set([ + "sh", "bash", "zsh", "dash", "ksh", "mksh", "fish", "csh", "tcsh", "busybox", "source", ".", "eval", "xargs", "env", + "nohup", "timeout", "sudo", "doas", "su", "nice", "ionice", "chroot", "setsid", "stdbuf", "watch", "script", + "expect", "python", "python2", "python3", "node", "nodejs", "deno", "bun", "bunx", "npx", "pnpx", "perl", "ruby", + "php", "lua", "tclsh", "Rscript", "osascript", "pwsh", "powershell", "awk", "gawk", "mawk", "make", "chmod", + "crontab", "at", "batch", "systemd-run", +]); +/** + * Commands after which what a line prints may be run or kept to run: a + * compound command (`for … do echo '…'; done | sh`), a function or alias + * definition that can stand in for `echo`, and `exec`, which redirects the + * shell itself. + */ +const RUNS_PRINTED_TEXT = new Set([ + "if", "then", "elif", "else", "fi", "for", "while", "until", "do", "done", "case", "esac", "select", "function", + "coproc", "alias", "enable", "shopt", "exec", +]); +/** + * `command` with each `>` and `<` blanked where it is text that `echo` or + * `printf` only prints: `echo 'cat > node_modules/.bin/failproofai'` documents + * a command rather than running one (found by hermes on + * FailproofAI/failproofai#1058). The walk reads redirects from the text, + * quotes and all, because a quoted program handed to `bash -c` or piped into + * `sh` really does redirect, and the unescaped pass drops the quotes, so both + * read that `>` as a redirect. + * + * Text means quoted (`'…'`, `"…"`, `$'…'`) or escaped (`\>`). Blanked only + * where nothing on the line can run it: an `echo` or `printf` (not + * `printf -v`, which stores it) outside any subshell, group or substitution, + * holding no substitution, piped into nothing but text readers, and + * redirected, if at all, to another descriptor or `/dev/null`; on a line with + * no compound command, function, alias, `exec`, heredoc or process + * substitution. Otherwise the text is left as it is. + */ +function blankPrintedRedirects(command: string): string { + if (!/['"\\]/.test(command) || !/[<>]/.test(command)) return command; + // Per character: text (quoted or escaped), and inside a subshell, group or + // substitution, or a substitution's own start. + const text = new Uint8Array(command.length); + const nested = new Uint8Array(command.length); + const pieces: Array<{ start: number; end: number; pipeIn: boolean; pipeOut: boolean }> = []; + let quote: "'" | '"' | "$'" | null = null; + let depth = 0; + let backquoted = false; + let start = 0; + let pipeIn = false; + for (let i = 0; i < command.length; i++) { + const ch = command[i]; + if (quote === "'") { + if (ch === "'") quote = null; + else text[i] = 1; + continue; + } + if (quote === "$'") { + if (ch === "'") quote = null; + else { + text[i] = 1; + if (ch === "\\" && i + 1 < command.length) text[++i] = 1; + } + continue; + } + if (quote === '"') { + if (ch === '"') { + quote = null; + continue; + } + text[i] = 1; + // A substitution inside double quotes still runs. + if (ch === "`" || (ch === "$" && command[i + 1] === "(")) nested[i] = 1; + if (ch === "\\" && i + 1 < command.length) text[++i] = 1; + continue; + } + if (ch === "\\") { + if (i + 1 < command.length) text[++i] = 1; + continue; + } + if (ch === "'" || ch === '"') { + quote = ch === "'" && command[i - 1] === "$" ? "$'" : ch; + continue; + } + if ((ch === "<" || ch === ">") && command[i + 1] === "(") return command; + if (ch === "<" && command[i + 1] === "<") return command; + if (ch === "(" || ch === "{") depth++; + if (ch === "`") backquoted = !backquoted; + if (depth > 0 || backquoted || "`(){}".includes(ch)) nested[i] = 1; + if (ch === ")" || ch === "}") depth = Math.max(0, depth - 1); + // `&` beside a `>`, and `|` after one, belong to a redirect (`>&2`, `&>`, + // `>|`), not a separator. + const redirecting = (ch === "&" && (command[i - 1] === ">" || command[i + 1] === ">")) || (ch === "|" && command[i - 1] === ">"); + if ("|;&\n\r".includes(ch) && !redirecting) { + let j = i; + while (j < command.length && "|;&\n\r".includes(command[j])) j++; + const run = command.slice(i, j); + const pipe = run === "|" || run === "|&"; + pieces.push({ start, end: i, pipeIn, pipeOut: pipe }); + pipeIn = pipe; + start = j; + i = j - 1; + } } - - // Whitelist ~/.claude/ — Claude Code's own config, plans, memory, and settings - if (isClaudeInternalPath(resolved)) return allow(); - - // Whitelist /dev/null — harmless special file commonly used in shell commands - if (resolved === "/dev/null") return allow(); - - const cwdWithSep = cwd.endsWith("/") ? cwd : cwd + "/"; - if (resolved !== cwd && !resolved.startsWith(cwdWithSep)) { - if (allowPaths.some((ap) => resolved === ap || resolved.startsWith(ap.endsWith("/") ? ap : ap + "/"))) return allow(); - return deny(`Access outside project directory blocked: ${resolved}`); + if (quote !== null || depth > 0 || backquoted) return command; + pieces.push({ start, end: command.length, pipeIn, pipeOut: false }); + // The line read with its text blanked, for the commands that can run it. + let bare = ""; + for (let i = 0; i < command.length; i++) bare += text[i] ? " " : command[i]; + if (/\w\s*\(\s*\)/.test(bare)) return command; + // Each piece's command word, past any assignments in front of it: as the + // shell reads it, quotes and escapes removed (`'sh'` runs `sh`; found by + // hermes on FailproofAI/failproofai#1058), and as written with its text + // blanked, which is how a reserved word stands. A runner anywhere in the + // piece (`time sh`, `command sh`) counts, and so does a command word the + // walk cannot read (`"$SHELL" notes`) or one named by a path. + const commandOf = (from: number, to: number): string => + bare.slice(from, to).trim().split(/\s+/).find((word) => !/^[A-Za-z_]\w*=/.test(word)) ?? ""; + let runsFiles = false; + for (const { start: from, end: to } of pieces) { + const words = shellWords(command.slice(from, to)).map(({ raw }) => stripShellQuoting(raw)); + const head = words.find((word) => !/^[A-Za-z_]\w*=/.test(word)) ?? ""; + if (RUNS_PRINTED_TEXT.has(commandOf(from, to)) || RUNS_PRINTED_TEXT.has(head)) return command; + if (head.includes("/") || /[$`]/.test(head) || words.some((word) => RUNS_FILES.has(word))) runsFiles = true; } - return allow(); -} - -function blockWorkOnMain(ctx: PolicyContext): PolicyResult { - if (ctx.toolName !== "Bash") return allow(); - const cmd = getCommand(ctx); - const match = cmd.match(GIT_COMMIT_MERGE_RE); - if (!match) return allow(); - - const cwd = ctx.session?.cwd; - if (!cwd) return allow(); - const branch = getCurrentBranch(cwd); - if (!branch) return allow(); - - const protectedBranches = ((ctx.params?.protectedBranches ?? ["main", "master"]) as string[]); - if (protectedBranches.includes(branch)) { - return deny( - `Git ${match[1]} on ${branch} is blocked. Create a feature branch first.`, - ); + // Whether a piece stands alone at the top of the line with only harmless + // output redirects, and the command it runs. + const plain = (from: number, to: number): string | undefined => { + for (let k = from; k < to; k++) if (nested[k]) return undefined; + for (let k = from; k < to; k++) { + if (command[k] !== ">" || text[k]) continue; + let j = k + 1; + if (command[j] === ">" || command[j] === "|") j++; + const duplicate = command[j] === "&"; + if (duplicate) j++; + while (j < to && /[ \t]/.test(command[j])) j++; + let target = duplicate ? "&" : ""; + for (; j < to && !/\s/.test(command[j]); j++) if (command[j] !== "'" && command[j] !== '"') target += command[j]; + // Into a file, as documentation is, unless something on the line may + // run what it holds (`echo '…' > notes.md` stays text; `… && sh notes.md` + // does not). + if (!HARMLESS_OUTPUT_RE.test(target) && (runsFiles || target === "" || target.startsWith("&"))) return undefined; + k = j - 1; + } + const words = shellWords(command.slice(from, to)); + return words.length > 0 ? words[0].raw : undefined; + }; + const out = command.split(""); + for (let p = 0; p < pieces.length; p++) { + if (pieces[p].pipeIn) continue; + // The pipeline this piece starts. + let last = p; + while (pieces[last].pipeOut && last + 1 < pieces.length) last++; + const head = plain(pieces[p].start, pieces[p].end); + if (head === undefined || !PRINT_COMMANDS.has(head)) continue; + const words = shellWords(command.slice(pieces[p].start, pieces[p].end)); + if (head === "printf" && words.some(({ raw }) => /^-[A-Za-z]*v/.test(raw))) continue; + let readers = true; + for (let q = p + 1; q <= last && readers; q++) { + const reader = plain(pieces[q].start, pieces[q].end); + readers = reader !== undefined && (TEXT_READERS.has(reader) || (reader === "tee" && !runsFiles)); + } + if (!readers) continue; + for (let k = pieces[p].start; k < pieces[last].end; k++) if (text[k] && (command[k] === ">" || command[k] === "<")) out[k] = "_"; } - return allow(); + return out.join(""); } - /** * The one policy that cannot be turned off — see `alwaysOn` on its definition. * @@ -2637,6 +8805,353 @@ function blockWorkOnMain(ctx: PolicyContext): PolicyResult { * deny is what actually happened on every machine and the allow never ran. The * merge keeps the behaviour users have. */ +// -- block-failproofai-commands: arguments that never run -- +// +// Both halves of this guard read the command without knowing where quoting +// ends, which is what makes them hard to fool with `fail"proof"ai`. The price +// was paid by reads and by text: `jq '.categories | length' ` split at +// the `|` inside the filter and judged `length'` an unknown, destructive +// command; `grep -E '(failproofai_local|x)' f` split at the `(` and saw the +// binary in command position; a heredoc writing notes that mention the CLI +// was judged line by line as if it were a script. Before either half looks, +// the command is rewritten so only those inert pieces disappear: +// +// - a quoted argument of a command that never executes its arguments (the +// grep family, jq, yq), unless it names the state or holds a substitution, +// and only when the command word is that standard tool: a bare name with no +// relative PATH entry, or a path in /usr/bin or /bin (`standardToolName`) — +// a project's own `./grep` may `eval "$1"`; +// - the body of a heredoc fed to a command that only writes it out (`cat`, +// `tee`, `:`), when nothing in the same command could run what it wrote; +// +// A `python -c` program is never treated as inert. An earlier version vetted +// "read-only" programs with a blacklist, and dynamic lookups such as +// `sys._getframe().f_builtins["o"+"pen"](path, "w")` walked straight past it: +// no syntactic check of a Python program can prove it only reads. Use `jq`, +// `grep` or `cat` to read the state instead. Nothing is inert either when the +// same command could change what `grep` or `cat` resolves to +// (`COMMAND_REDEFINITION_RE`). A heredoc written out by `cat`/`tee` is no +// more than the Write tool already does, which is not judged by content. +// +// Anything the scan does not fully understand (an unbalanced quote, a heredoc +// with no end) leaves the command exactly as it was, so a confusing command is +// judged as strictly as before. + +/** Commands that never execute an argument: their quoted operands are data. */ +const INERT_ARGUMENT_HEADS = new Set(["grep", "egrep", "fgrep", "rg", "jq"]); + +/** Commands a heredoc body can be fed to without the body running. */ +const HEREDOC_DATA_HEADS = new Set(["cat", "tee", ":"]); + +/** + * Command words that run code they are handed, so a heredoc written by another + * part of the same command could be executed by them, and a body piped to them + * runs. Also any command word that is a path (`/tmp/p.sh`, `./p.sh`). + */ +const CODE_RUNNING_HEADS = new Set([ + "sh", "bash", "zsh", "dash", "ksh", "fish", "ash", "csh", "tcsh", "source", ".", "eval", "exec", + "xargs", "env", "sudo", "doas", "su", "ssh", "script", "watch", "nohup", "setsid", "timeout", "nice", + "node", "bun", "deno", "perl", "ruby", "php", "lua", "npx", "bunx", "pnpx", "npm", "pnpm", "yarn", + "make", "chmod", "crontab", "at", "batch", "systemd-run", "launchctl", +]); + +const PYTHON_HEAD_RE = /^python(?:\d+(?:\.\d+)?)?$/; + +/** A word of a command, with where it sits in the raw text. */ +interface ShellWord { + /** The word with its quotes removed (`fail"proof"ai` → `failproofai`). */ + value: string; + start: number; + end: number; + /** Any part of it was quoted. */ + quoted: boolean; + /** Its raw text contains `$(`, `${` or a backtick, quoted or not. */ + substitutes: boolean; +} + +/** A simple command: its words, and whether a `|` follows it. */ +interface ShellSimple { + words: ShellWord[]; + pipedOut: boolean; + pipedIn: boolean; + /** Heredocs opened in this command: delimiter, and the raw span of the body (with its end line). */ + /** Raw span of each body; `expands` when an unquoted delimiter lets `$(…)` or a backtick in it run. */ + heredocs: Array<{ bodyStart: number; bodyEnd: number; expands: boolean }>; +} + +/** + * Split `cmd` into simple commands the way a shell would, honouring quotes, + * or null when it cannot be done with confidence (unbalanced quotes, a + * heredoc without its end line, nested `$(` inside quotes it would have to + * follow). Separators: `;`, `&`, `|`, newline and the brackets of a subshell, + * brace group or substitution. + */ +function scanShellCommands(cmd: string): ShellSimple[] | null { + const out: ShellSimple[] = []; + let words: ShellWord[] = []; + let heredocs: ShellSimple["heredocs"] = []; + let pendingHeredocs: Array<{ delim: string; strip: boolean; quoted: boolean; owner: number }> = []; + let pipedIn = false; + let cur: ShellWord | null = null; + const flushWord = (end: number) => { + if (cur) { + cur.end = end; + words.push(cur); + cur = null; + } + }; + const flushCommand = (pipedOut: boolean) => { + if (words.length > 0 || heredocs.length > 0) out.push({ words, pipedOut, pipedIn, heredocs }); + pipedIn = pipedOut; + words = []; + heredocs = []; + }; + let i = 0; + while (i < cmd.length) { + const c = cmd[i]; + if (c === "\n") { + flushWord(i); + // Heredoc bodies start on the line after their operator. + let pos = i + 1; + for (const h of pendingHeredocs) { + const bodyStart = pos; + let found = false; + while (pos <= cmd.length) { + const nl = cmd.indexOf("\n", pos); + const lineEnd = nl === -1 ? cmd.length : nl; + const line = cmd.slice(pos, lineEnd); + const next = nl === -1 ? cmd.length : nl + 1; + if ((h.strip ? line.replace(/^\t+/, "") : line) === h.delim) { + const body = cmd.slice(bodyStart, pos); + // The body only: the delimiter line stays, or a reader of the + // text with the body taken out reads every line after it as more + // heredoc (`cat > n <<'EOF'\nx\nEOF\nrm -rf ` was allowed). + const span = { bodyStart, bodyEnd: pos, expands: !h.quoted && /\$\(|`/.test(body) }; + // The command that opened it, which a `;` may already have ended. + if (h.owner < out.length) out[h.owner].heredocs.push(span); + else heredocs.push(span); + pos = next; + found = true; + break; + } + if (nl === -1) break; + pos = next; + } + if (!found) return null; + } + const hadHeredocs = pendingHeredocs.length > 0; + pendingHeredocs = []; + flushCommand(false); + i = hadHeredocs ? pos : i + 1; + continue; + } + if (c === "\\") { + if (!cur) cur = { value: "", start: i, end: i, quoted: true, substitutes: false }; + if (cmd[i + 1] === "\n") { + i += 2; + continue; + } + cur.value += cmd[i + 1] ?? ""; + i += 2; + continue; + } + if (c === "'" || c === '"' || (c === "$" && cmd[i + 1] === "'")) { + if (!cur) cur = { value: "", start: i, end: i, quoted: true, substitutes: false }; + cur.quoted = true; + if (c === "$") { + const close = cmd.indexOf("'", i + 2); + if (close === -1) return null; + cur.value += decodeAnsiC(cmd.slice(i + 2, close)); + i = close + 1; + continue; + } + if (c === "'") { + const close = cmd.indexOf("'", i + 1); + if (close === -1) return null; + cur.value += cmd.slice(i + 1, close); + i = close + 1; + continue; + } + let j = i + 1; + while (j < cmd.length && cmd[j] !== '"') { + if (cmd[j] === "\\") j++; + else if (cmd[j] === "`" || (cmd[j] === "$" && (cmd[j + 1] === "(" || cmd[j + 1] === "{"))) cur.substitutes = true; + j++; + } + if (j >= cmd.length) return null; + cur.value += cmd.slice(i + 1, j).replace(/\\(["\\$`])/g, "$1"); + i = j + 1; + continue; + } + if (c === "<" && cmd[i + 1] === "<" && cmd[i + 2] !== "<") { + flushWord(i); + let j = i + 2; + const strip = cmd[j] === "-"; + if (strip) j++; + while (cmd[j] === " " || cmd[j] === "\t") j++; + const m = /^(?:'([^'\n]*)'|"([^"\n]*)"|([^\s;&|<>()]+))/.exec(cmd.slice(j)); + if (!m) return null; + const raw = m[1] ?? m[2] ?? m[3]; + pendingHeredocs.push({ delim: raw.replace(/\\/g, ""), strip, quoted: m[3] === undefined || raw.includes("\\"), owner: out.length }); + words.push({ value: "<<", start: i, end: j, quoted: false, substitutes: false }); + i = j + m[0].length; + continue; + } + if (/[;&|(){}`]/.test(c) || (c === "$" && cmd[i + 1] === "(")) { + flushWord(i); + flushCommand(c === "|" && cmd[i + 1] !== "|"); + i += c === "$" ? 2 : c === "|" || c === "&" ? (cmd[i + 1] === c ? 2 : 1) : 1; + continue; + } + if (c === " " || c === "\t" || c === "\r") { + flushWord(i); + i++; + continue; + } + if (c === "<" || c === ">") { + flushWord(i); + let j = i; + while (cmd[j] === "<" || cmd[j] === ">" || cmd[j] === "|" || cmd[j] === "&") j++; + words.push({ value: cmd.slice(i, j), start: i, end: j, quoted: false, substitutes: false }); + i = j; + continue; + } + if (!cur) cur = { value: "", start: i, end: i, quoted: false, substitutes: false }; + if (c === "$" && cmd[i + 1] === "{") cur.substitutes = true; + cur.value += c; + i++; + } + if (pendingHeredocs.length > 0) return null; + flushWord(cmd.length); + flushCommand(false); + return out; +} + +/** The command word of a simple command (after assignments and runners), or undefined. */ +function scannedHead(words: ShellWord[]): { word: ShellWord; at: number } | undefined { + for (let i = 0; i < words.length; i++) { + const v = words[i].value; + if (/^[<>]/.test(v)) { + i++; // and its target + continue; + } + if (ENV_ASSIGNMENT_RE.test(v) || SHELL_KEYWORD_PREFIXES.has(v)) continue; + return { word: words[i], at: i }; + } + return undefined; +} + +/** + * Anything in the command that can change what a later command word runs: + * a shell function definition (`grep() { "$@"; }`), an alias, `shopt`, + * `enable`, `hash -p`, or a `PATH` assignment (`PATH=/tmp/x grep …`). With + * any of them, `grep` is not known to be grep, so nothing is treated as inert. + */ +const COMMAND_REDEFINITION_RE = + /(?:^|[\s;&|(){}])(?:function\s+[\w.:-]+|[\w.:-]+\s*\(\s*\)|alias\b|unalias\b|shopt\b|enable\b|hash\b|(?:export\s+|declare\s+[-\w\s]*|typeset\s+[-\w\s]*|readonly\s+)?PATH\+?=|BASH_ENV=|ENV=)/; + +/** A scanned word, quotes removed, that assigns a variable which changes what a command word runs. */ +const COMMAND_REDEFINING_ASSIGNMENT_RE = /^(?:PATH|BASH_ENV|ENV)\+?=/; + +/** + * Whether the command could change what a later command word runs. Checked + * on the raw text, on its shell-unescaped form (`PA""TH=/tmp/x grep …` is a + * PATH assignment once the shell drops the quotes), and on every scanned word. + */ +function redefinesCommandWords(cmd: string, scanned: ShellSimple[] | null): boolean { + if (COMMAND_REDEFINITION_RE.test(cmd) || COMMAND_REDEFINITION_RE.test(stripShellQuoting(cmd))) return true; + return !!scanned && scanned.some((simple) => simple.words.some((w) => COMMAND_REDEFINING_ASSIGNMENT_RE.test(w.value))); +} + +/** Directories whose programs only root can replace: a path command word there is the real tool. */ +const SYSTEM_TOOL_DIRS = new Set(["/usr/bin", "/bin"]); + +/** + * The name of the tool a command word runs, when it is known to be that + * standard tool, else undefined. A bare name (`grep`) is the tool the AGENT's + * PATH (`agentPath`, carried in the payload by the hook CLI: agent-path.ts) + * finds, and only when that is in `/usr/bin` or `/bin` and PATH has no + * relative entry (`.`, an empty one), which can find a program in the + * project instead. Never this process's own PATH: in the daemon's worker that + * is the service's. With no agent PATH, a bare name is not known to be the + * tool. A path (`./grep`, `/tmp/x/grep`) is the tool only in `/usr/bin` or + * `/bin`: anywhere else it is whatever program was put there, which may run + * its arguments. + */ +function standardToolName(word: string, agentPath: string | undefined): string | undefined { + if (!word.includes("/")) { + if (agentPath === undefined) return undefined; + const entries = agentPath.split(":"); + if (entries.some((e) => !e.startsWith("/"))) return undefined; + // The program PATH finds first must itself be in a system directory: a + // user-writable PATH entry (~/.local/bin, a package manager's bin) earlier + // than /usr/bin could hold a `grep` that runs its arguments. + for (const e of entries) { + const dir = e.replace(/\/+$/, "") || "/"; + try { + accessSync(`${dir}/${word}`, fsConstants.X_OK); + } catch { + continue; + } + return SYSTEM_TOOL_DIRS.has(dir) ? word : undefined; + } + return undefined; + } + const slash = word.lastIndexOf("/"); + const dir = word.slice(0, slash).replace(/\/+$/, "") || "/"; + return SYSTEM_TOOL_DIRS.has(dir) ? word.slice(slash + 1) : undefined; +} + +/** `cmd` with its inert pieces taken out (see above), or `cmd` unchanged. */ +function withoutInertArguments(cmd: string, agentPath: string | undefined): string { + const scanned = scanShellCommands(cmd); + if (redefinesCommandWords(cmd, scanned)) return cmd; + if (!scanned) return cmd; + const cuts: Array<{ start: number; end: number; text: string }> = []; + const heads = scanned.map((s) => scannedHead(s.words)); + const anyCodeRunner = heads.some((h) => { + if (!h) return false; + const base = h.word.value.slice(h.word.value.lastIndexOf("/") + 1); + return CODE_RUNNING_HEADS.has(base) || h.word.value.includes("/") || PYTHON_HEAD_RE.test(base); + }); + // One lookup per distinct head: with the agent's PATH known, each is a + // filesystem probe per PATH entry, and `echo ${${…` scans as 50,000 heads. + const toolNames = new Map(); + scanned.forEach((simple, n) => { + const head = heads[n]; + if (!head) return; + // Only the standard tool's arguments are inert: a project's own `./grep` + // can `eval "$1"`. + const word = head.word.value; + if (!toolNames.has(word)) toolNames.set(word, standardToolName(word, agentPath)); + const base = toolNames.get(word); + if (base === undefined) return; + const args = simple.words.slice(head.at + 1); + // rg runs a preprocessor named by `--pre`. + if (INERT_ARGUMENT_HEADS.has(base) && !(base === "rg" && args.some((w) => w.value.startsWith("--pre")))) { + args.forEach((w, k) => { + const prev = k === 0 ? simple.words[head.at] : args[k - 1]; + if (!w.quoted || w.substitutes || /^[<>]/.test(prev.value)) return; + if (FAILPROOFAI_STATE_PATH_RE.test(w.value) || globCouldNameState(w.value)) return; + cuts.push({ start: w.start, end: w.end, text: "''" }); + }); + } + if (simple.heredocs.length > 0 && HEREDOC_DATA_HEADS.has(base) && !simple.pipedOut && !anyCodeRunner) { + for (const h of simple.heredocs) if (!h.expands) cuts.push({ start: h.bodyStart, end: h.bodyEnd, text: "" }); + } + }); + if (cuts.length === 0) return cmd; + cuts.sort((a, b) => b.start - a.start); + let result = cmd; + let floor = Infinity; + for (const cut of cuts) { + if (cut.end > floor) return cmd; // overlapping pieces: not understood + result = result.slice(0, cut.start) + cut.text + result.slice(cut.end); + floor = cut.start; + } + return result; +} + function blockFailproofaiCommands(ctx: PolicyContext): PolicyResult { // A file tool reaches the state without a shell at all. Writing // `{"enabledPolicies":[]}` over `~/.failproofai/policies-config.json`, or an @@ -2644,33 +9159,62 @@ function blockFailproofaiCommands(ctx: PolicyContext): PolicyResult { // completely as `rm -rf` does — and the machine still reads as fresh, so // fail-closed never fires. Reading is not offered by these tools' write half, // so naming the state at all is the whole test. - if (ctx.toolName === "Write" || ctx.toolName === "Edit" || ctx.toolName === "NotebookEdit") { - const path = getFilePath(ctx) || ((ctx.toolInput?.notebook_path as string) ?? ""); - // The path as given AND the file it lands on. The bin entry a user-scope - // hook runs is usually a symlink into the package, so writing through it - // changes the hook's code without the package's path ever being named. - const kind = failproofaiFileKind(path) ?? failproofaiFileKind(resolveWriteTarget(path, ctx.session?.cwd)); - if (kind === "code") { - return deny( - "Writing to failproofai's installed code would switch enforcement off. " + - "If a policy is blocking legitimate work, say so and let the operator decide.", - ); + const rawPatch = ctx.toolName === "apply_patch"; + if (ctx.toolName === "Write" || ctx.toolName === "Edit" || ctx.toolName === "MultiEdit" || ctx.toolName === "NotebookEdit" || rawPatch) { + // The path the tool names, and every file a patch it carries names. + const paths = [getFilePath(ctx) || ((ctx.toolInput?.notebook_path as string) ?? ""), ...patchTargets(ctx.toolInput)]; + // A patch's relative paths are read from the session's directory, and + // from the one the call names when it names one. + const toolCwd = ctx.toolInput?.workdir ?? ctx.toolInput?.cwd; + const cwds = [ctx.session?.cwd, ...(typeof toolCwd === "string" && toolCwd !== "" ? [toolCwd] : [])]; + for (const path of paths) { + // The path as given AND the file it lands on. The bin entry a user-scope + // hook runs is usually a symlink into the package, so writing through it + // changes the hook's code without the package's path ever being named. + const kind = + failproofaiFileKind(path) ?? + cwds.map((cwd) => failproofaiFileKind(resolveWriteTarget(path, cwd))).find((found) => found !== null) ?? + null; + if (kind === "code") { + return deny( + "Writing to failproofai's installed code would switch enforcement off. " + + "If a policy is blocking legitimate work, say so and let the operator decide.", + ); + } + if (kind === "state") { + return deny( + "Writing to failproofai's own state would switch enforcement off. " + + "If a policy is blocking legitimate work, say so and let the operator decide.", + ); + } } - if (kind === "state") { + // The agent CLI's own settings and hook files are how it calls failproofai + // at all. `"disableAllHooks": true` in any Claude Code settings layer, or a + // hooks file with our entries taken out, switches off every policy — this + // one included — and Claude Code's file watcher applies it before the next + // tool call. Checked after symlinks, and through apply_patch's patch text. + // A patch tool that arrives by its own name (OpenClaw's) is read whole: + // every string it carries, whatever the key, as a patch. + const writeInput = rawPatch ? { ...ctx.toolInput, patch: Object.values(ctx.toolInput ?? {}) } : ctx.toolInput; + const settingsFile = agentSettingsWriteTarget(writeInput, ctx.session?.cwd, sessionAgentSettingsPaths(ctx)); + if (settingsFile) { return deny( - "Writing to failproofai's own state would switch enforcement off. " + - "If a policy is blocking legitimate work, say so and let the operator decide.", + `${settingsFile} is an agent settings or hook file, and editing it could switch failproofai's hooks off. ` + + "If this change is needed, say so and let the user make it.", ); } return allow(); } if (ctx.toolName !== "Bash") return allow(); - const cmd = getCommand(ctx); + return judgeFailproofaiCommand(withoutInertArguments(getCommand(ctx), agentPathOf(ctx.payload)), ctx); +} + +function judgeFailproofaiCommand(cmd: string, ctx: PolicyContext): PolicyResult { // The raw command AND its shell-unescaped form: a shell strips quotes and // backslashes before running the binary, so `fail\proofai config --pause` // reaches the pause CLI even though the literal name is broken. const unescaped = stripShellQuoting(cmd); - const kind = classifySelfInvocation(cmd) ?? classifySelfInvocation(unescaped); + const kind = classifySelfInvocation(cmd) ?? classifySelfInvocation(unescaped) ?? classifyTextPipedIntoShell(cmd); if (kind === "pause") { return deny( @@ -2686,19 +9230,308 @@ function blockFailproofaiCommands(ctx: PolicyContext): PolicyResult { if (FAILPROOFAI_UNINSTALL_RE.test(cmd) || FAILPROOFAI_UNINSTALL_RE.test(unescaped)) { return deny("Uninstalling failproofai is blocked"); } + // Checked before the state, so a command aimed at an agent's settings is + // refused for that reason, not as the state walk's catch-all for a patch or + // archive it cannot read. + // + // An agent CLI's own command can turn its hooks off with no settings path in + // it at all: `codex features disable hooks` rewrites config.toml. Read from + // the commands alone, so a commit message that quotes one is still a message. + const lexed = lexShell(cmd); + // Text piped into a shell is a command too: `echo 'codex features disable hooks' | sh`. + const pipesIntoShell = /\|\s*(?:[^\s;&|()`<>]*\/)?(?:sh|bash|zsh|dash|ksh|ash|fish)(?=[\s;&|)]|$)/.test(lexed.commandsOnly); + const cliText = pipesIntoShell ? cmd : lexed.commandsOnly; + if ( + agentCliSwitchesHooksOff(cliText) || + agentCliSwitchesHooksOff(stripShellQuoting(cliText)) || + agentCliSwitchesHooksOff(agentCliArgvLines(lexed)) || + agentCliHooksOffByArgv(lexed) + ) { + return deny( + "Turning an agent's hooks off would switch failproofai's enforcement off. " + + "If this change is needed, say so and let the user make it.", + ); + } + // The same walk, aimed at the agents' settings and hook files: `jq + // '.disableAllHooks=true' ~/.claude/settings.json > t && mv t + // ~/.claude/settings.json` switches the hooks off without naming failproofai. + // The unescaped pass is built from the MASKED command, so quoted arguments + // stay one argument after their quotes come off. + const settingsPaths = sessionAgentSettingsPaths(ctx); + const settingsTarget = agentSettingsShellTarget( + agentSettingsShellCwd(ctx.toolInput, ctx.session?.cwd), + settingsPaths, + settingsReaderTrust(cmd, agentPathOf(ctx.payload)), + ); + const maskedUnescaped = stripShellQuoting(lexed.splittable); + const settingsDenial = deny( + "Writing, moving or deleting an agent's settings or hook files could switch failproofai's hooks off. " + + "If this change is needed, say so and let the user make it.", + ); + // Codex runs a command in the `workdir` its shell tool names, and its hook + // payload carries the session's directory and the command only (see the + // state walk below). Unless the call reports one, the line is also read as + // starting in an agent's config directory: `printf '{}' > hooks.json` may be + // a write to ~/.codex/hooks.json (found by the #1105 review). + const settingsStartUnknown = ctx.cli === "codex" && !shellCwdReported(ctx.toolInput); + const anywhereTarget = settingsStartUnknown ? agentSettingsAnywhereTarget(settingsTarget, settingsPaths) : null; + const writesSettings = + destroysProtectedPath(cmd, settingsTarget) || + destroysProtectedPath(maskedUnescaped, settingsTarget, 0, lexed.splittable) || + (anywhereTarget !== null && + (destroysProtectedPath(cmd, anywhereTarget) || destroysProtectedPath(maskedUnescaped, anywhereTarget, 0, lexed.splittable))); + // A command that names a settings file is refused for that. One the settings + // walk refuses without naming one (an expansion it cannot resolve) is checked + // against the state first, so `rm -rf ~/.fa${X:-ilproofai}` says the state. + if (writesSettings && settingsTarget.namesLiteral(cmd)) return settingsDenial; // Deleting the state IS disabling enforcement, without ever naming the binary. // Checked on the raw command AND its shell-unescaped form for the same reason // the binary walk is: `rm -rf ~/.failproof"ai"` presents a broken literal to a - // matcher and a real path to the shell. - if (destroysFailproofaiState(cmd) || destroysFailproofaiState(unescaped)) { + // matcher and a real path to the shell. The walk starts where the command runs: + // the session's directory, or the one an Antigravity `run_command` names. + const toolCwd = ctx.toolInput?.cwd ?? ctx.toolInput?.workdir; + const reported = shellCwdReported(ctx.toolInput); + const shellCwd = reported && typeof toolCwd === "string" ? toolCwd : ctx.session?.cwd; + // Codex runs a command in the `workdir` its shell tool names, and its hook + // payload carries the session's directory and the command only: a native + // `printf … > failproofai` with workdir `node_modules/.bin` arrived as a + // write in the project root (found by hermes on FailproofAI/failproofai#1058). + // Unless the call reports one, the line may start anywhere, which the walk + // reads as it reads a directory it has lost. + const startUnknown = ctx.cli === "codex" && !reported; + // Quoted text an `echo` or `printf` only prints is read as text, in both + // passes (see `blankPrintedRedirects`). + // And, on a line with a heredoc, with message heredocs blanked as the + // settings walk reads them: a commit message built from `$(cat <<'EOF' … + // EOF)` is a message. A heredoc a command reads (`git apply <' | sh`. + pipesStateIntoShell(cmd) || + // A default the shell uses when the variable is unset is part of the + // path: `rm -rf ~/.fa${X:-ilproofai}` (both found by #1053's tests on #1058). + parameterDefaultVariants(walked).some((variant) => destroysFailproofaiState(variant, 0, shellCwd, startUnknown)); + } catch (err) { + return deny( + "failproofai could not read this command to check it against its own files, so it is refused. " + + `Rewrite it more simply, or say so and let the operator decide. (${err instanceof Error ? err.message : String(err)})`, + ); + } + if (destroys) { return deny( "Deleting, moving or overwriting failproofai's own state or installed code would switch enforcement off. " + "If a policy is blocking legitimate work, say so and let the operator decide.", ); } + if (writesSettings) return settingsDenial; return allow(); } - +/** A word whose text an expansion decides: `$F`, `${F:-x}`, `$(…)`, a backtick. */ +const EXPANSION_IN_WORD_RE = /\$[A-Za-z_{(0-9@*#?!$-]|`/; +/** + * The agent CLIs' hooks-off commands, read word by word from each command's + * argv: `codex features disable hooks`, `pi remove `, `hermes | + * openclaw plugins disable|remove `. A word an expansion decides + * could be any word, so it stands for whichever word the shape needs there — + * `codex $(echo features) disable "$F"` is refused whatever F holds — unless + * it is exactly `$NAME` for a variable every assignment of which comes + * earlier on the line with a plain value: then it is each of those values. + * A head an expansion decides is not followed; every command could be it. + */ +function agentCliHooksOffByArgv(lexed: ShellLex): boolean { + const assignments = new Map>(); + for (const match of lexed.readable.matchAll(/(?:^|[\s;&|(])(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=("[^"]*"|'[^']*'|[^\s;&|)]*)/g)) { + const list = assignments.get(match[1]) ?? []; + list.push({ at: match.index, value: match[2].replace(/^["']|["']$/g, "") }); + assignments.set(match[1], list); + } + // A variable appended to (`F=ho; F+=oks`) holds what no single assignment says. + const appended = new Set([...lexed.readable.matchAll(/(?:^|[\s;&|(])([A-Za-z_][A-Za-z0-9_]*)\+=/g)].map((m) => m[1])); + // A word's possible texts, or null for any word at all. + const optionsOf = (word: string, at: number): string[] | null => { + if (!EXPANSION_IN_WORD_RE.test(word)) return [word]; + const ref = /^\$(?:\{([A-Za-z_][A-Za-z0-9_]*)\}|([A-Za-z_][A-Za-z0-9_]*))$/.exec(word); + if (ref && appended.has(ref[1] ?? ref[2])) return null; + const list = ref ? assignments.get(ref[1] ?? ref[2]) : undefined; + if (!list || list.length > 64 || list.some((a) => a.at > at || EXPANSION_IN_WORD_RE.test(a.value))) return null; + return list.map((a) => a.value); + }; + const can = (options: string[] | null, test: (word: string) => boolean): boolean => options === null || options.some(test); + for (const [start, end] of cutRanges(lexed.splittable, PIPELINE_SEPARATORS)) { + const splitPipeline = lexed.splittable.slice(start, end); + for (const [simpleStart, simpleEnd] of cutRanges(splitPipeline, /\|/)) { + const at = start + simpleStart; + const words = quoteAwareWords(lexed.readable.slice(at, start + simpleEnd)).map((word) => optionsOf(word, at)); + // The head: past assignments, wrappers, runners and their flags. + let h = 0; + while (h < words.length) { + const options = words[h]; + if (options === null) break; + const word = options[0] ?? ""; + if (ENV_ASSIGNMENT_RE.test(word) || word.startsWith("-") || RUNNER_OPERAND_RE.test(word) || COMMAND_PREFIX_TOKENS.has(commandBasename(word))) { + h++; + continue; + } + break; + } + const head = words[h]; + if (!head) continue; + const heads = new Set(head.map((word) => commandBasename(word).toLowerCase())); + const rest = words.slice(h + 1).filter((options) => options === null || !options.every((w) => w.startsWith("-"))); + const seq = (tests: Array<(word: string) => boolean>): boolean => { + // Each test met by a later word than the one before it. + let k = 0; + for (const test of tests) { + while (k < rest.length && !can(rest[k], test)) k++; + if (k >= rest.length) return false; + k++; + } + return true; + }; + if (heads.has("codex") && seq([(w) => /^features?$/i.test(w), (w) => /^disable$/i.test(w), (w) => /(?:^|[^A-Za-z0-9_])(?:codex_)?hooks(?![A-Za-z0-9_])/i.test(w)])) { + return true; + } + if (heads.has("pi") && seq([(w) => /^(?:remove|uninstall|rm)$/i.test(w), (w) => /failproofai|pi-extension/i.test(w)])) return true; + if ( + (heads.has("hermes") || heads.has("openclaw")) && + seq([(w) => /^plugins?$/i.test(w), (w) => /^(?:disable|remove|uninstall|rm|delete)$/i.test(w), (w) => /failproofai/i.test(w)]) + ) { + return true; + } + } + } + return false; +} +/** + * The words of `text` as the shell splits and unquotes them — at blanks and at + * `;&|<>()=` outside quotes — each with where it starts. An expansion stays + * in its word as written, for the caller to treat as unknown. + */ +function decodedWordsAt(text: string): Array<{ word: string; at: number }> { + const out: Array<{ word: string; at: number }> = []; + let word = ""; + let at = -1; + const end = (): void => { + if (at !== -1) out.push({ word, at }); + word = ""; + at = -1; + }; + for (let i = 0; i < text.length; i++) { + const ch = text[i]; + if (/[\s;&|<>()=]/.test(ch)) { + end(); + continue; + } + if (at === -1) at = i; + if (ch === "\\" && i + 1 < text.length) { + word += text[++i]; + } else if (ch === "'" && text[i - 1] === "$") { + const close = text.indexOf("'", i + 1); + const stop = close === -1 ? text.length : close; + word = word.slice(0, -1) + decodeAnsiC(text.slice(i + 1, stop)); + i = stop; + } else if (ch === "'") { + const close = text.indexOf("'", i + 1); + const stop = close === -1 ? text.length : close; + word += text.slice(i + 1, stop); + i = stop; + } else if (ch === '"') { + let j = i + 1; + for (; j < text.length && text[j] !== '"'; j++) { + if (text[j] === "\\" && j + 1 < text.length) j++; + word += text[j]; + } + i = j; + } else { + word += ch; + } + } + end(); + return out; +} +/** The expansions inside a name, each read as a `*`: `exam$X`, `a${X}b`, `$(f)`, a backtick. */ +const EXPANSIONS_IN_NAME_RE = /\$\{[^}]*\}?|\$\([^)]*\)?|\$[A-Za-z_][A-Za-z0-9_]*|\$.?|`[^`]*`?/g; +/** A word an agent CLI's hooks-off command is made of. */ +const HOOKS_OFF_WORD_RE = /(?:^|[^A-Za-z0-9_-])(?:codex|features?|disable|(?:codex_)?hooks|pi|remove|uninstall|rm|delete|failproofai|pi-extension|hermes|openclaw|plugins?)(?![A-Za-z0-9_-])/i; +/** + * Each command of a line as its argv reads, one per line, for the agent-CLI + * checks: quotes and `$'…'` escapes undone (`codex features disable + * $'\x68ooks'`), `$NAME` and `${NAME}` replaced by a value the line assigns + * (`F=hooks; codex features disable "$F"`), and an argument holding a blank — + * a message — replaced by `_`, so its words never read as a command. + */ +function agentCliArgvLines(lexed: ShellLex): string { + // Every value a variable is given anywhere on the line, not the last one: + // `F=hooks; codex features disable "$F"; F=web_search` runs with `hooks`. + const values = new Map(); + for (const [, name, value] of lexed.readable.matchAll(/(?:^|[\s;&|(])(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=("[^"]*"|'[^']*'|[^\s;&|)]*)/g)) { + const known = values.get(name) ?? []; + if (known.length < 64) known.push(value.replace(/^["']|["']$/g, "")); + values.set(name, known); + } + // `F+=oks` appends to every value F had, or is the whole value of an unset F. + for (const [, name, value] of lexed.readable.matchAll(/(?:^|[\s;&|(])([A-Za-z_][A-Za-z0-9_]*)\+=("[^"]*"|'[^']*'|[^\s;&|)]*)/g)) { + const tail = value.replace(/^["']|["']$/g, ""); + const known = values.get(name) ?? []; + values.set(name, [...new Set([...known, ...known.map((v) => v + tail), tail])].slice(0, 64)); + } + // Of the values a reference may take, the one that would turn hooks off if + // any would: what the check needs to know is whether some run does. + const pick = (options: readonly string[]): string => options.find((o) => HOOKS_OFF_WORD_RE.test(o)) ?? options[0] ?? ""; + // `${NAME:-word}`, `${NAME=word}`, `${NAME:+word}`…: a variable this line + // does not set may be unset, so its default word is what the command gets + // (`${UNSET:-ho}oks` is `hooks`); a set one gives its value. + const expand = (text: string): string => + text + .replace(/\$\{([A-Za-z_][A-Za-z0-9_]*):?([-=+?])([^{}]*)\}/g, (_whole, name: string, op: string, word: string) => { + const known = values.get(name) ?? []; + return op === "+" ? pick([word, ""]) : pick([...known.filter(Boolean), word]); + }) + .replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)/g, (whole, braced?: string, bare?: string) => + pick([...(values.get(braced ?? bare ?? "") ?? []), whole]), + ); + const lines: string[] = []; + for (const [start, end] of cutRanges(lexed.splittable, PIPELINE_SEPARATORS)) { + const splitPipeline = lexed.splittable.slice(start, end); + for (const [simpleStart, simpleEnd] of cutRanges(splitPipeline, /\|/)) { + const simple = lexed.readable.slice(start + simpleStart, start + simpleEnd); + lines.push(quoteAwareWords(expand(simple)).map((word) => (/\s/.test(word) ? "_" : word)).join(" ")); + } + } + return lines.join("\n"); +} +/** + * The failproofai CLI inside text piped into a shell, which runs it: + * `echo 'failproofai config --pause' | sh`. Each quoted string is read as the + * command it becomes there. + */ +function classifyTextPipedIntoShell(cmd: string): SelfInvocation | null { + if (!/\|\s*(?:[^\s;&|()`<>]*\/)?(?:sh|bash|zsh|dash|ksh|ash|fish)(?=[\s;&|)]|$)/.test(cmd)) return null; + for (const [, single, double] of cmd.matchAll(/'([^']*)'|"((?:[^"\\]|\\.)*)"/g)) { + const piped = single ?? double ?? ""; + const kind = classifySelfInvocation(piped) ?? classifySelfInvocation(stripShellQuoting(piped)); + if (kind) return kind; + } + return null; +} +/** + * The settings file this session's hook was loaded from, when the hook process + * could tell (handler.ts reads it from the agent's own environment, so a + * `CLAUDE_CONFIG_DIR` or `CODEX_HOME` that moved it is followed). + */ +function sessionAgentSettingsPaths(ctx: PolicyContext): string[] { + const path = ctx.session?.agentSettingsPath; + return typeof path === "string" && path.length > 0 ? [path] : []; +} // Shared CLI-blocker: deny any command whose argv begins with the matched CLI, // unless an entry in `allowPatterns` matches via `matchesAllowedPattern` (which // already defends against shell-operator injection). @@ -2710,42 +9543,33 @@ function blockInfraCli(ctx: PolicyContext, re: RegExp, denyMsg: string): PolicyR if (allowPatterns.some((p) => matchesAllowedPattern(cmd, p))) return allow(); return deny(denyMsg); } - function blockKubectl(ctx: PolicyContext): PolicyResult { return blockInfraCli(ctx, KUBECTL_RE, "kubectl commands are blocked"); } - function blockTerraform(ctx: PolicyContext): PolicyResult { return blockInfraCli(ctx, TERRAFORM_RE, "terraform/tofu commands are blocked"); } - function blockAwsCli(ctx: PolicyContext): PolicyResult { return blockInfraCli(ctx, AWS_CLI_RE, "aws CLI commands are blocked"); } - function blockGcloud(ctx: PolicyContext): PolicyResult { return blockInfraCli(ctx, GCLOUD_RE, "gcloud commands are blocked"); } - function blockAzCli(ctx: PolicyContext): PolicyResult { return blockInfraCli(ctx, AZ_CLI_RE, "az (Azure) CLI commands are blocked"); } - function blockHelm(ctx: PolicyContext): PolicyResult { return blockInfraCli(ctx, HELM_RE, "helm commands are blocked"); } - // gh-pipeline only fires on mutating subcommands; allowPatterns are still // supported in case a user wants to permit a specific scripted invocation. function blockGhPipeline(ctx: PolicyContext): PolicyResult { return blockInfraCli(ctx, GH_PIPELINE_RE, "gh pipeline-trigger commands are blocked"); } - // Maximum size of the per-session tool-call sidecar before we stop updating it. // If exceeded, repeated-call detection degrades gracefully (allows through) rather // than growing the file unboundedly. const TOOL_CALL_TRACKER_MAX_BYTES = 65_536; // 64 KB - async function warnRepeatedToolCalls(ctx: PolicyContext): Promise { const THRESHOLD = 3; const transcriptPath = ctx.session?.transcriptPath; @@ -2778,7 +9602,6 @@ async function warnRepeatedToolCalls(ctx: PolicyContext): Promise return allow(); } - function warnGitAmend(ctx: PolicyContext): PolicyResult { if (ctx.toolName !== "Bash") return allow(); const cmd = getCommand(ctx); @@ -2789,7 +9612,6 @@ function warnGitAmend(ctx: PolicyContext): PolicyResult { } return allow(); } - function warnGitStashDrop(ctx: PolicyContext): PolicyResult { if (ctx.toolName !== "Bash") return allow(); const cmd = getCommand(ctx); @@ -2800,7 +9622,6 @@ function warnGitStashDrop(ctx: PolicyContext): PolicyResult { } return allow(); } - /** What one `git clean` argument list asks for. */ interface GitCleanFlags { force: boolean; @@ -2808,7 +9629,6 @@ interface GitCleanFlags { /** Short-flag letters, with `--force` counted as `f` so widening works either way. */ letters: Set; } - /** * Read `git clean`'s own options: clusters (`-fdx`) and the two long forms * that matter (`--force`, `--dry-run`). @@ -2846,7 +9666,6 @@ function readGitCleanFlags(args: string[]): GitCleanFlags { if (force) letters.add("f"); return { force, dryRun, letters }; } - /** True when git's own `-c key=value` options waive `clean.requireForce`. */ function gitCleanForceWaived(globalOptions: string[]): boolean { for (let i = 0; i < globalOptions.length; i++) { @@ -2857,7 +9676,6 @@ function gitCleanForceWaived(globalOptions: string[]): boolean { } return false; } - /** * The gap this closes: `git clean -fdx` was caught by NEITHER tier — no regex * builtin matched the string at all, and the semantic check that covers @@ -2895,7 +9713,6 @@ function warnGitClean(ctx: PolicyContext): PolicyResult { } return allow(); } - function warnAllFilesStaged(ctx: PolicyContext): PolicyResult { if (ctx.toolName !== "Bash") return allow(); const cmd = getCommand(ctx); @@ -2906,7 +9723,6 @@ function warnAllFilesStaged(ctx: PolicyContext): PolicyResult { } return allow(); } - function warnSchemaAlteration(ctx: PolicyContext): PolicyResult { if (ctx.toolName !== "Bash") return allow(); const cmd = getCommand(ctx); @@ -2918,7 +9734,6 @@ function warnSchemaAlteration(ctx: PolicyContext): PolicyResult { } return allow(); } - function warnGlobalPackageInstall(ctx: PolicyContext): PolicyResult { if (ctx.toolName !== "Bash") return allow(); const cmd = getCommand(ctx); @@ -2938,10 +9753,8 @@ function warnGlobalPackageInstall(ctx: PolicyContext): PolicyResult { } return allow(); } - // Split a compound shell command into independent segments. const SEGMENT_SPLIT_RE = /\s*(?:&&|\|\||\||;)\s*/; - function preferPackageManager(ctx: PolicyContext): PolicyResult { if (ctx.toolName !== "Bash") return allow(); const cmd = getCommand(ctx); @@ -3005,7 +9818,6 @@ function preferPackageManager(ctx: PolicyContext): PolicyResult { return allow(); } - function warnBackgroundProcess(ctx: PolicyContext): PolicyResult { if (ctx.toolName !== "Bash") return allow(); const cmd = getCommand(ctx); @@ -3024,7 +9836,6 @@ function warnBackgroundProcess(ctx: PolicyContext): PolicyResult { } // -- Workflow (Stop event) policies -- - /** * Claude Code plan mode (permission_mode: "plan") is research-and-plan-only — the * agent makes no commits, pushes, or PRs by design. The Stop-workflow gates below @@ -3035,7 +9846,6 @@ function warnBackgroundProcess(ctx: PolicyContext): PolicyResult { function isPlanMode(ctx: PolicyContext): boolean { return ctx.session?.permissionMode === "plan"; } - function requireCommitBeforeStop(ctx: PolicyContext): PolicyResult { if (isPlanMode(ctx)) return allow("Plan mode — no changes made, skipping commit check."); const cwd = ctx.session?.cwd; @@ -3058,7 +9868,6 @@ function requireCommitBeforeStop(ctx: PolicyContext): PolicyResult { return allow("Not a git repository, skipping commit check."); } } - function requirePushBeforeStop(ctx: PolicyContext): PolicyResult { if (isPlanMode(ctx)) return allow("Plan mode — no changes made, skipping push check."); const cwd = ctx.session?.cwd; @@ -3153,7 +9962,6 @@ function requirePushBeforeStop(ctx: PolicyContext): PolicyResult { return allow("Could not check push status, skipping."); } } - function requirePrBeforeStop(ctx: PolicyContext): PolicyResult { if (isPlanMode(ctx)) return allow("Plan mode — no changes made, skipping PR check."); const cwd = ctx.session?.cwd; @@ -3247,7 +10055,6 @@ function requirePrBeforeStop(ctx: PolicyContext): PolicyResult { return allow("Could not check PR status, skipping."); } } - function requireNoConflictsBeforeStop(ctx: PolicyContext): PolicyResult { if (isPlanMode(ctx)) return allow("Plan mode — no changes made, skipping conflict check."); const cwd = ctx.session?.cwd; @@ -3346,7 +10153,6 @@ function requireNoConflictsBeforeStop(ctx: PolicyContext): PolicyResult { } return allow(`PR #${pr.number} merges cleanly per GitHub.`); } - function requireCiGreenBeforeStop(ctx: PolicyContext): PolicyResult { if (isPlanMode(ctx)) return allow("Plan mode — no changes made, skipping CI check."); const cwd = ctx.session?.cwd; @@ -3451,7 +10257,6 @@ function requireCiGreenBeforeStop(ctx: PolicyContext): PolicyResult { } // -- Registry -- - /** * Name → implementation. The other half of {@link POLICY_CATALOG}. * @@ -3505,7 +10310,6 @@ const POLICY_IMPLEMENTATIONS: Record = { "require-no-conflicts-before-stop": requireNoConflictsBeforeStop, "require-ci-green-before-stop": requireCiGreenBeforeStop, }; - /** * Catalog and implementations must be in BIJECTION, and this throws rather than * warns because the failure is otherwise invisible in the worst direction: a @@ -3532,7 +10336,6 @@ function assertCatalogBijection(): void { } } assertCatalogBijection(); - /** * The joined view, and the shape every consumer has always seen. * @@ -3546,7 +10349,6 @@ export const BUILTIN_POLICIES: BuiltinPolicyDefinition[] = POLICY_CATALOG.map((e ...entry, fn: POLICY_IMPLEMENTATIONS[entry.name] as PolicyFunction, })); - export function registerBuiltinPolicies(enabledNames: string[]): void { // Tolerate both flat ("sanitize-jwt") and qualified ("failproofai/sanitize-jwt") // forms in the user's enabledPolicies config — canonicalize both sides. @@ -3569,7 +10371,6 @@ export function registerBuiltinPolicies(enabledNames: string[]): void { } } } - /** Clears the git branch cache. Exposed for test isolation only. */ export function clearGitBranchCache(): void { gitBranchCache.clear(); diff --git a/src/hooks/claude-hooks-switch.ts b/src/hooks/claude-hooks-switch.ts new file mode 100644 index 000000000..70b3f5218 --- /dev/null +++ b/src/hooks/claude-hooks-switch.ts @@ -0,0 +1,149 @@ +/** + * Whether Claude Code's `disableAllHooks` is switching failproofai's hooks off. + * + * Claude Code reads ONE value of the key: the one left after settings precedence + * (managed, then local, then project, then user). So a `true` in a project's + * `.claude/settings.local.json` turns off hooks installed in + * `~/.claude/settings.json`, and a running session picks the change up from its + * settings file watcher. Nothing in failproofai read the key, so a machine whose + * agent had set it — the cheapest way for a prompt-injected agent to switch its + * own enforcement off — still reported itself as enforcing. + * + * Pure apart from the reads, which go through a seam: `config --status` passes + * the real files, tests pass their own. + */ +import { existsSync, lstatSync, readdirSync, readFileSync } from "node:fs"; +import { homedir } from "node:os"; +import { dirname, join, resolve } from "node:path"; + +/** + * Where Claude Code looks for the managed (enterprise) settings file. It no + * longer reads the old Windows location, `C:\ProgramData\ClaudeCode`. + */ +export const CLAUDE_MANAGED_SETTINGS_PATHS: Readonly>> = { + linux: "/etc/claude-code/managed-settings.json", + darwin: "/Library/Application Support/ClaudeCode/managed-settings.json", + win32: "C:\\Program Files\\ClaudeCode\\managed-settings.json", +}; + +/** + * The managed layer, highest precedence first. Claude Code merges + * `managed-settings.json` and then every `*.json` in `managed-settings.d/` + * beside it, in alphabetical order, a later file's value replacing an earlier + * one's: the last fragment that sets the key decides, and the base file only + * when none does. Hidden files and other extensions are skipped. + */ +export function claudeManagedSettingsLayers(managed: string | null): string[] { + if (!managed) return []; + const dir = join(dirname(managed), "managed-settings.d"); + let fragments: string[] = []; + try { + fragments = readdirSync(dir).filter((name) => name.endsWith(".json") && !name.startsWith(".")).sort(); + } catch { + // No directory: the base file alone. + } + return [...fragments.reverse().map((name) => join(dir, name)), managed]; +} + +/** The settings files that can decide `disableAllHooks`, highest precedence first. */ +export function claudeSettingsLayersByPrecedence( + scopes: { user: string; project: string; local: string | readonly string[] }, + /** The managed settings file; null where there is none. */ + managed: string | null = CLAUDE_MANAGED_SETTINGS_PATHS[process.platform] ?? null, +): string[] { + const local = typeof scopes.local === "string" ? [scopes.local] : scopes.local; + return [...claudeManagedSettingsLayers(managed), ...local, scopes.project, scopes.user]; +} + +/** The nearest directory at or above `cwd` holding a `.git` (a worktree's is a file). */ +function gitRepositoryRoot(cwd: string): string | null { + let dir = resolve(cwd); + for (let depth = 0; depth < 256; depth++) { + if (existsSync(join(dir, ".git"))) return dir; + const parent = dirname(dir); + if (parent === dir) return null; + dir = parent; + } + return null; +} + +/** + * The checkout whose root keeps the local settings. A linked worktree's `.git` + * is a file naming its git directory under the main checkout's + * `.git/worktrees/`, and Claude Code keeps a worktree's local settings at the + * main checkout's root. Anything else, a submodule included, is its own root. + */ +function mainCheckoutRoot(root: string): string { + try { + const dotGit = join(root, ".git"); + if (!lstatSync(dotGit).isFile()) return root; + const gitdir = /^gitdir:\s*(.+?)\s*$/m.exec(readFileSync(dotGit, "utf8"))?.[1]; + if (!gitdir) return root; + const worktreeGitDir = resolve(root, gitdir); + const common = readFileSync(join(worktreeGitDir, "commondir"), "utf8").trim(); + return dirname(resolve(worktreeGitDir, common)); + } catch { + return root; + } +} + +/** Whether the repository root, its `.git` and its `.claude` (where present) are the user's own. */ +function ownedByCurrentUser(root: string): boolean { + const uid = process.getuid?.(); + if (uid === undefined) return true; + return [root, join(root, ".git"), join(root, ".claude")].every((path) => { + const stat = lstatSync(path, { throwIfNoEntry: false }); + return stat === undefined || stat.uid === uid; + }); +} + +/** + * Where Claude Code reads a project's `settings.local.json`, current place + * first. Since v2.1.211 a session started in a subdirectory of a git + * repository keeps it at the repository root (a worktree's: the main + * checkout's) — except outside a repository, when that root is the home + * directory, on Windows, or when the root, its `.git` or its `.claude` is not + * the user's — and it still reads one an older version left in the starting + * directory. + */ +export function claudeLocalSettingsPaths( + cwd: string, + platform: NodeJS.Platform = process.platform, + home: string = homedir(), +): string[] { + const here = join(resolve(cwd), ".claude", "settings.local.json"); + if (platform === "win32") return [here]; + const top = gitRepositoryRoot(cwd); + if (top === null) return [here]; + const root = mainCheckoutRoot(top); + if (root === resolve(home) || !ownedByCurrentUser(root)) return [here]; + const atRoot = join(root, ".claude", "settings.local.json"); + return atRoot === here ? [here] : [atRoot, here]; +} + +/** + * The settings file whose `"disableAllHooks": true` is in effect, or null. + * + * The first layer that sets the key as a boolean decides, as in Claude Code: a + * `false` higher up wins over a `true` below it. A file that is missing or does + * not parse is skipped, which is what Claude Code does with it too. + */ +export function claudeHooksSwitchedOffBy( + layers: readonly string[], + read: (path: string) => string = (path) => readFileSync(path, "utf8"), +): string | null { + // Two scopes resolve to one file when run from the home directory. + for (const path of new Set(layers)) { + let parsed: unknown; + try { + parsed = JSON.parse(read(path)); + } catch { + continue; + } + if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) continue; + const value = (parsed as Record).disableAllHooks; + if (typeof value !== "boolean") continue; + return value ? path : null; + } + return null; +} diff --git a/src/hooks/codex-interactive-session.ts b/src/hooks/codex-interactive-session.ts new file mode 100644 index 000000000..8cd532c77 --- /dev/null +++ b/src/hooks/codex-interactive-session.ts @@ -0,0 +1,408 @@ +/** + * Codex sessions may not open an interactive shell or REPL. + * + * Codex can leave a command running and type into it later (`exec_command`, + * then `write_stdin`; in code mode both are called from inside its JavaScript + * `exec` tool). It runs PreToolUse for the command that starts the session and + * for nothing typed into it afterwards: in a live codex-cli 0.172 session the + * only hook call was `Bash` with `{"command": "bash -i"}`, and + * `failproofai policies list` typed into that shell ran unchecked (found by + * hermes on FailproofAI/failproofai#1058, FailproofAI/agenteye#1898). Turning + * `unified_exec` off does not remove those tools in code mode, and turning code + * mode off leaves Codex's model with no shell at all. + * + * So the one point failproofai can enforce is the start: under Codex, a command + * that opens a program which runs what is typed into it — a shell with no + * script, an interpreter with no program, a multiplexer, a remote or container + * shell, an editor or pager with a shell escape, a database client that can + * shell out — is refused, and the agent is told to run each command on its own, + * which Codex does hook. A server or build left running (`npm run dev`) stays + * allowed: it does not run what is typed into it. + * + * The list cannot be complete: a program not named here that runs typed text + * is not refused. Pagers (`less`, `man`) are left off on purpose: agents read + * documentation with them, and their `!` shell escape needs a terminal. + */ +import { deny, allow } from "./policy-helpers"; +import type { PolicyContext, PolicyMatcher, PolicyResult } from "./policy-types"; + +export const CODEX_SESSION_GUARD_NAME = "failproofai/codex-interactive-session"; + +export const CODEX_SESSION_GUARD_DESCRIPTION = + "Refuse a Codex command that opens an interactive shell or REPL, whose typed input Codex runs no hooks for."; + +export const CODEX_SESSION_GUARD_MATCH: PolicyMatcher = { + events: ["PreToolUse"], + toolNames: ["Bash"], +}; + +const SHELLS = new Set(["bash", "sh", "zsh", "dash", "ksh", "mksh", "ash", "fish", "tcsh", "csh", "nu", "xonsh", "elvish", "pwsh", "powershell", "busybox"]); +/** Interpreters that read their program from what is typed when given none. */ +const STDIN_INTERPRETERS = new Set(["ruby", "perl", "php", "lua", "luajit", "tclsh", "wish"]); +const ALWAYS_INTERACTIVE = new Set([ + "irb", "pry", "ipython", "bpython", "ptpython", "ghci", "iex", "erl", "scala", "clj", "clojure", "R", "julia", "sbcl", "racket", + "tmux", "screen", "byobu", "zellij", "mosh", "telnet", "ftp", "sftp", "lftp", + "vi", "vim", "nvim", "view", "ex", "ed", "emacs", "nano", "pico", + "gdb", "lldb", "pdb", "nix-repl", "redis-cli", "mongosh", "mongo", "expect", "login", +]); +/** Words before the program that run it rather than being it. */ +const WRAPPERS = new Set(["env", "exec", "command", "builtin", "nohup", "time", "nice", "ionice", "stdbuf", "timeout", "setsid", "chrt", "taskset", "unbuffer", "caffeinate"]); + +/** Top-level simple commands of a line, each with whether its stdin comes from a pipe and whether from a redirect. */ +function simpleCommands(command: string): Array<{ words: string[]; piped: boolean; redirected: boolean }> { + const out: Array<{ words: string[]; piped: boolean; redirected: boolean }> = []; + let words: string[] = []; + let word = ""; + let inWord = false; + let quote: "'" | '"' | null = null; + let piped = false; + let redirected = false; + // The word after `<` or `>` names the redirect's file, not an argument. + let skipNext = false; + const endWord = () => { + if (inWord) { + if (skipNext) skipNext = false; + else words.push(word); + } + word = ""; + inWord = false; + }; + const endCommand = (nextPiped: boolean) => { + endWord(); + if (words.length > 0) out.push({ words, piped, redirected }); + words = []; + piped = nextPiped; + redirected = false; + }; + for (let i = 0; i < command.length; i++) { + const ch = command[i]; + if (quote) { + if (ch === quote) quote = null; + else if (ch === "\\" && quote === '"' && i + 1 < command.length) word += command[++i]; + else word += ch; + continue; + } + if (ch === "'" || ch === '"') { + quote = ch; + inWord = true; + } else if (ch === "\\" && i + 1 < command.length) { + word += command[++i]; + inWord = true; + } else if (ch === "#" && !inWord) { + while (i < command.length && command[i] !== "\n") i++; + endCommand(false); + } else if (ch === "|" && command[i + 1] !== "|") { + endCommand(true); + } else if (ch === ";" || ch === "\n" || ch === "&" || ch === "|" || ch === "(" || ch === ")" || ch === "{" || ch === "}") { + if ((ch === "&" || ch === "|") && command[i + 1] === ch) i++; + endCommand(false); + } else if (ch === "<" && command[i + 1] !== "(") { + // `< file`, `<" && command[i + 1] !== "(") { + // `> out.log`, `2>&1`, `&> log`: output elsewhere, still typed into. + if (/^\d+$/.test(word)) { + word = ""; + inWord = false; + } + endWord(); + while (command[i + 1] === ">") i++; + if (command[i + 1] === "&") { + i++; + while (/\d/.test(command[i + 1] ?? "")) i++; + } else skipNext = true; + } else if (/\s/.test(ch)) { + endWord(); + } else { + word += ch; + inWord = true; + } + } + endCommand(false); + return out; +} + +const baseName = (word: string): string => word.slice(word.lastIndexOf("/") + 1); + +/** A program operand that reads the program from stdin: `node -`, `bash /dev/stdin`. */ +const STDIN_OPERAND_RE = /^(?:-|\/dev\/stdin|\/dev\/fd\/0|\/proc\/self\/fd\/0|\/dev\/tty)$/; + +/** + * Filters that pass what they read from stdin on to stdout, so a shell or + * interpreter after them in a pipe runs what is typed into them: `cat | bash` + * (found by the #1105 review). Each with the options that take a value, so + * that value is not read as a file it reads instead. + */ +const STDIN_FORWARDERS: ReadonlyMap> = new Map>([ + ["cat", new Set()], + ["tac", new Set(["-s"])], + ["head", new Set(["-n", "-c"])], + ["tail", new Set(["-n", "-c", "-s", "--pid"])], + ["tr", new Set()], + ["sort", new Set(["-k", "-t", "-o", "-S", "-T"])], + ["uniq", new Set(["-f", "-s", "-w"])], + ["cut", new Set(["-d", "-f", "-c", "-b"])], + ["nl", new Set(["-b", "-d", "-f", "-h", "-i", "-l", "-n", "-s", "-v", "-w"])], + ["rev", new Set()], + ["fold", new Set(["-w"])], + ["fmt", new Set(["-w"])], + ["iconv", new Set(["-f", "-t"])], + ["col", new Set()], + ["pv", new Set(["-L", "-s", "-N"])], + ["base64", new Set(["-w"])], + ["xxd", new Set(["-c", "-g", "-l", "-s"])], + ["sed", new Set(["-e", "-f", "-l"])], + ["awk", new Set(["-F", "-v", "-f"])], + ["gawk", new Set(["-F", "-v", "-f"])], + ["mawk", new Set(["-F", "-v", "-f"])], + ["grep", new Set(["-e", "-f", "-m", "-A", "-B", "-C"])], + ["egrep", new Set(["-e", "-f", "-m", "-A", "-B", "-C"])], + ["fgrep", new Set(["-e", "-f", "-m", "-A", "-B", "-C"])], + ["tee", new Set()], + ["dd", new Set()], +]); + +/** Whether `program args`, reading typed input, passes it on to the next command in a pipe. */ +function forwardsStdin(program: string, args: string[]): boolean { + const valued = STDIN_FORWARDERS.get(program); + if (!valued) return false; + // `tee` writes its operands and still passes stdin on. + if (program === "tee") return true; + if (program === "dd") return !args.some((a) => a.startsWith("if=") && !STDIN_OPERAND_RE.test(a.slice(3))); + // Their first operand is the program or pattern, unless an option gave one. + const scripted = + (program === "sed" || program === "grep" || program === "egrep" || program === "fgrep" || /awk$/.test(program)) && + !args.some((a) => a === "-e" || a === "-f" || a.startsWith("--expression") || a.startsWith("--file") || a.startsWith("--regexp")); + // `tr`'s operands are sets of characters, never files. + const files = program === "tr" ? [] : operands(args, valued).slice(scripted ? 1 : 0); + return files.every((file) => STDIN_OPERAND_RE.test(file)); +} + +/** Whether an option word is a cluster carrying `letter` (`-lc` carries `c`). */ +const clusterHas = (word: string, letter: string): boolean => /^-[A-Za-z]+$/.test(word) && word.includes(letter); + +/** The program a simple command runs, past assignments and wrappers, with its arguments. */ +function programOf(words: string[]): { program: string; args: string[] } | null { + let i = 0; + while (i < words.length) { + const word = words[i]; + if (/^[A-Za-z_][A-Za-z0-9_]*=/.test(word)) { + i++; + continue; + } + const name = baseName(word); + if (!WRAPPERS.has(name)) break; + i++; + // A wrapper's own options and values (`env -u X`, `nice -n 5`, `timeout 30s`). + while (i < words.length && (words[i].startsWith("-") || /^[A-Za-z_][A-Za-z0-9_]*=/.test(words[i]) || (name === "timeout" && /^\d/.test(words[i])))) { + if (["-n", "-u", "-C", "-S", "-o", "-e", "-i", "-c", "-k", "-s", "-p"].includes(words[i]) && name !== "env") i++; + else if (name === "env" && (words[i] === "-u" || words[i] === "-C" || words[i] === "-S")) i++; + i++; + } + } + if (i >= words.length) return null; + return { program: baseName(words[i]), args: words.slice(i + 1) }; +} + +/** Operands: arguments that are not options (and not an option's value from `valued`). */ +function operands(args: string[], valued: ReadonlySet): string[] { + const out: string[] = []; + for (let k = 0; k < args.length; k++) { + const arg = args[k]; + if (arg === "--") return [...out, ...args.slice(k + 1)]; + if (arg.startsWith("-") && arg !== "-") { + if (valued.has(arg)) k++; + continue; + } + out.push(arg); + } + return out; +} + +const SHELL_VALUED = new Set(["-o", "+o", "-O", "+O", "--rcfile", "--init-file"]); +const SSH_VALUED = new Set(["-b", "-c", "-D", "-E", "-e", "-F", "-I", "-i", "-J", "-L", "-l", "-m", "-O", "-o", "-p", "-Q", "-R", "-S", "-W", "-w", "-B", "-P"]); + +/** Flags that print something and exit, for the programs below (`python3 --version`, `bash --help`). */ +const INFO_FLAGS = new Set(["--version", "--help", "-h", "-?", "--usage", "-version", "-help"]); +/** Interpreter one-liners that hand the terminal to a shell: `pty.spawn("/bin/bash")`, `os.execv("/bin/sh", …)`. */ +const SPAWNS_SHELL_RE = /(?:pty\.spawn|os\.exec[lv]p?e?|os\.system|subprocess\.(?:call|run|Popen)|child_process|spawnSync|execSync|\bexec\s*\(|\bsystem\s*\(|\bexec\s+["'qQ{]|\bsystem\s+["'qQ{])[^\n]*?\b(?:bash|sh|zsh|dash|ksh|fish)\b/; + +/** The value a `-c` (or `-e`, `--eval`, …) option carries, if the command has one. */ +function inlineProgram(args: string[], flags: readonly string[]): string | undefined { + for (let k = 0; k < args.length; k++) { + const arg = args[k]; + if (flags.includes(arg)) return args[k + 1]; + for (const flag of flags) { + if (flag.length === 2 && /^-[A-Za-z]+$/.test(arg) && arg.endsWith(flag[1]) && arg.length > 2) return args[k + 1]; + if (flag.startsWith("--") && arg.startsWith(`${flag}=`)) return arg.slice(flag.length + 1); + } + } + return undefined; +} + +/** Why `program args` opens an interactive session, or null when it does not. */ +function sessionReason(program: string, args: string[], stdinFed: boolean, depth = 0): string | null { + const name = /^python[0-9.]*$|^pypy[0-9.]*$/.test(program) ? "python" : program; + // A version or help flag prints and exits (`python3 --version`; found by + // hermes on #1058). `-V` is that for the interpreters, not for the shells. + if (args.some((a) => INFO_FLAGS.has(a)) || (!SHELLS.has(name) && args.some((a) => a === "-V" || a === "-VV"))) return null; + // A program handed to a shell or an interpreter can open a session of its + // own: `bash -c 'bash -i'`, `python3 -c 'import pty; pty.spawn("/bin/bash")'` + // (found by hermes on #1058). + const program1 = SHELLS.has(name) ? inlineProgram(args, ["-c", "--command"]) : inlineProgram(args, ["-c", "-e", "-E", "--eval", "-p", "--print"]); + if (program1 !== undefined && depth < 4) { + if (SHELLS.has(name)) { + const nested = opensInteractiveSessionAt(program1, depth + 1); + if (nested) return nested; + } else if (SPAWNS_SHELL_RE.test(program1)) { + return `a shell started from ${name}`; + } + } + if (SHELLS.has(name)) { + if (args.some((a) => a === "-c" || clusterHas(a, "c") || a === "--command")) return null; + const ops = operands(args, SHELL_VALUED); + if (name === "busybox" && ops[0] !== undefined && !SHELLS.has(ops[0])) return null; + // `bash -` and `bash /dev/stdin` read the script from what is typed. + const script = name === "busybox" ? ops[1] : ops[0]; + if (script !== undefined && STDIN_OPERAND_RE.test(script)) return stdinFed ? null : `an interactive ${name} shell`; + if ((name === "busybox" ? ops.length > 1 : ops.length > 0) && !args.includes("-s")) return null; + return stdinFed ? null : `an interactive ${name} shell`; + } + if (name === "python") { + if (args.some((a) => a === "-i" || clusterHas(a, "i"))) return "an interactive Python session"; + const m = args.indexOf("-m"); + if (m !== -1) return ["code", "asyncio", "pdb", "IPython", "idlelib", "ptpython", "bpython"].includes(args[m + 1] ?? "") ? "an interactive Python session" : null; + if (args.includes("-c")) return null; + const ops = operands(args, new Set(["-W", "-X", "-Q"])); + if (ops.length > 0 && !STDIN_OPERAND_RE.test(ops[0])) return null; + return stdinFed ? null : "an interactive Python session"; + } + if (name === "node" || name === "nodejs") { + if (args.some((a) => a === "-i" || a === "--interactive")) return "an interactive Node.js session"; + if (args.some((a) => ["-e", "-p", "--eval", "--print", "--test", "--check", "-c", "--version", "-v", "--help", "-h"].includes(a))) return null; + const ops = operands(args, new Set(["-r", "--require", "--import", "--loader", "--input-type"])); + return (ops.length > 0 && !STDIN_OPERAND_RE.test(ops[0])) || stdinFed ? null : "an interactive Node.js session"; + } + if (name === "bun" || name === "deno") { + if (args[0] === "repl") return `an interactive ${name} session`; + return name === "deno" && args.length === 0 && !stdinFed ? "an interactive deno session" : null; + } + if (STDIN_INTERPRETERS.has(name)) { + if (name === "php" && args.includes("-a")) return "an interactive PHP session"; + if ((name === "lua" || name === "luajit") && args.includes("-i")) return `an interactive ${name} session`; + if (name === "perl" && args.some((a) => /^-d/.test(a))) return "the Perl debugger"; + if (args.some((a) => a === "-e" || a === "-E" || a === "-r" || clusterHas(a, "e") || clusterHas(a, "E"))) return null; + const ops = operands(args, new Set(["-I", "-M", "-f", "-F", "-v"])); + return (ops.length > 0 && !STDIN_OPERAND_RE.test(ops[0])) || stdinFed ? null : `${name} reading its program from typed input`; + } + if (ALWAYS_INTERACTIVE.has(name)) { + if (name === "tmux" && ["send-keys", "send", "ls", "list-sessions", "kill-session", "kill-server", "capture-pane", "has-session", "-V"].includes(operands(args, new Set(["-L", "-S", "-f", "-c", "-t"]))[0] ?? args[0] ?? "")) return null; + if (name === "screen" && args.some((a) => a === "-ls" || a === "-list" || a === "-X" || a === "-Q" || a === "-v")) return null; + if ((name === "gdb" || name === "lldb") && args.some((a) => a === "-batch" || a === "--batch")) return null; + if (name === "emacs" && args.some((a) => a === "--batch" || a === "--script" || a === "-batch")) return null; + if ((name === "redis-cli" || name === "mongosh" || name === "mongo") && args.some((a) => a === "--eval" || a === "-e")) return null; + if (name === "redis-cli" && operands(args, new Set(["-h", "-p", "-a", "-n", "-u", "--user", "--pass"])).length > 0) return null; + if ((name === "sftp" || name === "ftp" || name === "lftp") && args.some((a) => a === "-b" || a === "-c" || a === "-f")) return null; + if (name === "R" && args.some((a) => a === "-e" || a === "-f" || a.startsWith("--file") || a === "CMD")) return null; + if (name === "julia" && (args.some((a) => a === "-e" || a === "-E") || operands(args, new Set(["-p", "-t", "-J"])).length > 0)) return null; + if (name === "erl" && args.some((a) => a === "-noshell" || a === "-eval" || a === "-s")) return null; + if (name === "expect" && operands(args, new Set(["-c"])).length > 0) return null; + return `an interactive ${name} session`; + } + if (name === "sqlite3") return operands(args, new Set(["-cmd", "-separator", "-nullvalue"])).length > 1 || stdinFed ? null : "an interactive sqlite3 session"; + if (name === "psql") return args.some((a) => /^(-c|-f|--command|--file)(=|$)/.test(a)) || stdinFed ? null : "an interactive psql session"; + if (name === "mysql" || name === "mariadb") return args.some((a) => /^(-e|--execute)(=|$)/.test(a)) || stdinFed ? null : `an interactive ${name} session`; + if (name === "ssh") { + const ops = operands(args, SSH_VALUED); + if (args.some((a) => a === "-N" || a === "-V" || a === "-G" || a === "-Q")) return null; + return ops.length === 1 && !stdinFed ? "a remote shell over ssh" : ops.length > 1 && /^(bash|sh|zsh|fish|-?i?bash)$/.test(baseName(ops[1])) && ops.length === 2 ? "a remote shell over ssh" : null; + } + if (name === "su" || name === "script") { + // The command `-c` hands over runs as a shell line of its own: + // `script -qc bash /dev/null` is a shell (found by the #1105 review). + const line = inlineProgram(args, ["-c", "--command"]); + if (line !== undefined) return depth < 4 ? opensInteractiveSessionAt(line, depth + 1) : `a command started from ${name}`; + if (args.some((a) => a === "-c" || a === "--command" || clusterHas(a, "c"))) return null; + return name === "su" ? "a shell through su" : "a recorded interactive shell (script)"; + } + if (name === "sudo" || name === "doas") { + if (args.some((a) => a === "-i" || a === "-s" || a === "--login" || a === "--shell" || clusterHas(a, "i") || clusterHas(a, "s"))) return `a shell through ${name}`; + const rest = programOf(skipSudoOptions(args)); + return rest ? sessionReason(rest.program, rest.args, stdinFed, depth) : null; + } + if (name === "docker" || name === "podman" || name === "nerdctl") { + const sub = args.find((a) => !a.startsWith("-")); + if (sub === "attach") return `an attached ${name} container`; + if (sub !== "exec" && sub !== "run") return null; + const after = args.slice(args.indexOf(sub) + 1); + return after.some((a) => a === "-i" || a === "--interactive" || a === "--interactive=true" || clusterHas(a, "i")) ? `an interactive ${name} ${sub}` : null; + } + if (name === "kubectl" || name === "oc") { + const sub = args.find((a) => !a.startsWith("-")); + if (sub === "attach") return `an attached ${name} pod`; + if (sub !== "exec" && sub !== "run" && sub !== "debug") return null; + return args.some((a) => a === "-i" || a === "--stdin" || a === "--stdin=true" || clusterHas(a, "i")) ? `an interactive ${name} ${sub}` : null; + } + if (name === "nix-shell") return args.some((a) => a === "--run" || a === "--command") ? null : "an interactive nix-shell"; + if (name === "nix" && (args[0] === "repl" || ((args[0] === "develop" || args[0] === "shell") && !args.some((a) => a === "-c" || a === "--command")))) return `an interactive nix ${args[0]}`; + if ((name === "poetry" || name === "pipenv" || name === "hatch") && args[0] === "shell") return `an interactive ${name} shell`; + if (name === "vagrant" && args[0] === "ssh" && !args.some((a) => a === "-c" || a === "--command")) return "a remote shell over vagrant ssh"; + return null; +} + +function skipSudoOptions(args: string[]): string[] { + let k = 0; + while (k < args.length && args[k].startsWith("-")) { + if (["-u", "-g", "-C", "-D", "-h", "-p", "-r", "-t", "-U", "--user", "--group"].includes(args[k])) k++; + k++; + } + return args.slice(k); +} + +/** Why this command opens an interactive session (the first one found), or null. */ +export function opensInteractiveSession(command: string): string | null { + return opensInteractiveSessionAt(command, 0); +} + +function opensInteractiveSessionAt(command: string, depth: number): string | null { + // Whether the previous command in the pipe passes typed input on. + let forwardsTyped = false; + for (const { words, piped, redirected } of simpleCommands(command)) { + const typed: boolean = !redirected && (!piped || forwardsTyped); + const found = programOf(words); + forwardsTyped = typed && found !== null && forwardsStdin(found.program, found.args); + if (!found) continue; + const reason = sessionReason(found.program, found.args, !typed, depth); + if (reason) return reason; + } + return null; +} + +/** Whether a canonicalized Codex call is a shell command that opens one. */ +export function codexCallOpensSession(eventType: string, toolName: string | undefined, toolInput: unknown): string | null { + if (eventType !== "PreToolUse" || toolName !== "Bash") return null; + const command = (toolInput as Record | null | undefined)?.command; + return typeof command === "string" ? opensInteractiveSession(command) : null; +} + +/** The guard for one Codex call found to open an interactive session. */ +export function codexSessionGuardFor(reason: string): (ctx: PolicyContext) => PolicyResult { + return (ctx) => { + if (ctx.eventType !== "PreToolUse") return allow(); + return deny( + `failproofai refused this because it opens ${reason}, and Codex runs no hooks for what is typed into one. ` + + "Run each command on its own instead, without keeping a shell or REPL open.", + ); + }; +} diff --git a/src/hooks/config-status.ts b/src/hooks/config-status.ts index c5f4621b6..40751a6fa 100644 --- a/src/hooks/config-status.ts +++ b/src/hooks/config-status.ts @@ -22,8 +22,14 @@ * history is rescanned at upgrade. */ import { readFileSync } from "node:fs"; -import { resolve } from "node:path"; +import { dirname, resolve } from "node:path"; import { readCloudCredentials } from "./cloud-enrollment"; +import { + CLAUDE_MANAGED_SETTINGS_PATHS, + claudeHooksSwitchedOffBy, + claudeLocalSettingsPaths, + claudeSettingsLayersByPrecedence, +} from "./claude-hooks-switch"; import { CODEX_UNTRUSTED_NOTICE, codexHookTrust, type CodexHookTrust } from "./codex-system-hooks"; import { describeMachine } from "./cloud-enrollment-cli"; import { cloudBaseFor } from "./cloud-connection"; @@ -42,14 +48,14 @@ import { spoolBacklog } from "./flush-cli"; import { isAgentTraced, readConfig, readCredentials, readVersionFile } from "./fp-config"; import { collectorHealthFile, customPoliciesDir } from "./fp-home"; import { configuredCustomPolicyPaths, findProjectConfigDir, readMergedHooksConfig } from "./hooks-config"; -import { detectInstalledClis, listInstallableIds } from "./integrations"; +import { claudeCode, detectInstalledClis, listInstallableIds } from "./integrations"; import { cloudPolicyStatus, notEnforcingReason, type NotEnforcingReason } from "./manager"; import { hasInstalledRegexPacks, readInstalledPacks } from "./pack-manifest"; import { CORE_SOURCE } from "./pack-store"; import { formatDuration, listActivePauses } from "./session-pause"; import { pauseClockTime, type PauseClock } from "./session-pause-cli"; import { optsFor, screenKit, type ScreenKitOpts, type TTYOut } from "./tui"; -import type { IntegrationType } from "./types"; +import { HOOK_SCOPES, type IntegrationType } from "./types"; /** * A health record older than this was left by a daemon that stopped writing it. @@ -153,6 +159,12 @@ export interface StatusFacts { * hooks nobody has trusted, so hooks being installed is not enough. */ codex?: CodexHookTrust; + /** + * Present when failproofai's Claude Code hooks are installed and a settings + * file's `"disableAllHooks": true` is in effect, so Claude Code runs none of + * them — the always-on guard included. `path` is the file that decides. + */ + claudeHooksOff?: { path: string }; } /** Seams for everything that would otherwise reach a service manager, PATH or the network. */ @@ -164,6 +176,8 @@ export interface StatusDeps { detectInstalled?: () => IntegrationType[]; notEnforcing?: (cwd?: string) => NotEnforcingReason | null; codexTrust?: () => CodexHookTrust; + /** The Claude Code settings file switching failproofai's hooks off, or null. */ + claudeHooksOff?: (cwd: string) => string | null; } /** @@ -374,6 +388,7 @@ export async function gatherStatusFacts(deps: StatusDeps = {}): Promise claudeCode.hooksInstalledInSettings(scope, cwd)) || + local.some((path) => claudeCode.hooksInstalledInSettings("local", dirname(dirname(path)))); + if (!installed) return null; + return claudeHooksSwitchedOffBy( + claudeSettingsLayersByPrecedence( + { + user: claudeCode.getSettingsPath("user", cwd), + project: claudeCode.getSettingsPath("project", cwd), + local, + }, + managed, + ), + ); +} + +function claudeHooksOffFact(deps: StatusDeps, cwd: string): Pick { + try { + const path = (deps.claudeHooksOff ?? claudeHooksSwitchedOff)(cwd); + return path ? { claudeHooksOff: { path } } : {}; + } catch { + return {}; + } +} + /** The one line that needs attention, before it is painted. */ export interface StatusAttention { severity: "fail" | "caution"; @@ -425,6 +478,15 @@ export function pickStatusAttention(facts: StatusFacts): StatusAttention | null fix: "failproofai config", }; } + // Ahead of "not enforcing": this one is silent from inside the session, and + // it is what an agent switching its own enforcement off leaves behind. + if (facts.claudeHooksOff) { + return { + severity: "fail", + text: "Claude Code is running none of failproofai's hooks: disableAllHooks is true.", + detail: `Remove "disableAllHooks" from ${facts.claudeHooksOff.path}.`, + }; + } if (facts.notEnforcing) { const fix = facts.notEnforcing === "no-hooks" @@ -441,8 +503,9 @@ export function pickStatusAttention(facts: StatusFacts): StatusAttention | null return { severity: "caution", text: "Policies are not enforcing yet.", fix }; } if (facts.codex?.kind === "untrusted") { - const [text, fixLine] = CODEX_UNTRUSTED_NOTICE.split("\n"); - return { severity: "caution", text, detail: fixLine }; + // One line: the fix that needs no one at the Codex prompt (sudo puts the + // hooks in Codex's system config, which runs them without trust). + return { severity: "caution", text: CODEX_UNTRUSTED_NOTICE.split("\n")[0], fix: "failproofai config" }; } if (cloud.kind !== "none" && !daemon.answering && daemon.service !== "running") { const idle = @@ -630,6 +693,9 @@ export function renderStatusScreen(facts: StatusFacts, opts: ScreenKitOpts & { c ], ["policies", policiesValue()], ...(codexValue() ? [["codex", codexValue()!] as [string, string]] : []), + ...(facts.claudeHooksOff + ? [["claude", `${kit.off} Not enforcing: disableAllHooks in ${facts.claudeHooksOff.path}`] as [string, string]] + : []), ]; const sections: Array<[string, Array<[string, string]>]> = [ diff --git a/src/hooks/configure-wizard.ts b/src/hooks/configure-wizard.ts index 2bdcd6578..d5f769afa 100644 --- a/src/hooks/configure-wizard.ts +++ b/src/hooks/configure-wizard.ts @@ -64,7 +64,6 @@ import { INTEGRATION_TYPES, type IntegrationType, type HookScope } from "./types import { cloudDashboardUrl, enforcingPolicyCount, installHooks, notEnforcingReason } from "./manager"; import { installAgentSkill } from "./agent-skill"; import { - CODEX_UNTRUSTED_NOTICE, codexHookTrust, removeCodexSystemHooks, type CodexHookTrust, @@ -1898,7 +1897,18 @@ export function doneLines( lines.push(kit.ok(`Policies are enforcing on ${on}.`)); } } - if (codexSkips) lines.push(...kit.notice("caution", CODEX_UNTRUSTED_NOTICE)); + // Setup prints only what needs the user, and this does: an untrusted Codex + // runs none of the hooks (it is left out of the count above), and on a + // Codex-only machine "Done" would otherwise be all setup says. One line, + // with both fixes. + if (codexSkips) { + lines.push( + kit.caution( + `Codex won't run failproofai's hooks until you trust them: open ${kit.cmd("codex")} once and approve them, ` + + `or re-run ${kit.cmd("failproofai config")} with sudo.`, + ), + ); + } if (!state.connected) lines.push(` Connect to cloud any time: ${kit.cmd("failproofai config")}`); for (const warning of describeCustomPolicies(state.cwd).warnings) { lines.push(kit.caution(warning.replace(/^! /, ""))); diff --git a/src/hooks/daemon-client.ts b/src/hooks/daemon-client.ts index ac2c80365..1d5ea7b69 100644 --- a/src/hooks/daemon-client.ts +++ b/src/hooks/daemon-client.ts @@ -173,6 +173,35 @@ export async function daemonAcceptsConnections( }); } +/** The Self Reports MCP server a daemon's pong names (see crates/PROTOCOL.md). */ +export interface DaemonSelfReportServer { + instanceId: string; + port: number; +} + +/** + * The Self Reports MCP server the daemon behind this home's socket is serving, + * from its pong (a live daemon: a socket file left by a hard-killed one + * refuses the connection). Used where a stale answer writes something lasting + * (the Self Reports transport choice), never on the hook path. `null` when no + * daemon answers, when its MCP listener is not bound (a busy port), or when the + * daemon predates the field. The endpoint's + * MCP `initialize` carries the same `instanceId`, which is how a caller proves + * the HTTP port belongs to this daemon and not to another one. + */ +export async function daemonSelfReportServer(responseTimeoutMs = 1000): Promise { + const attempt = await attemptDaemonRequest( + (protocolVersion) => ({ type: "ping", protocolVersion }), + { responseTimeoutMs }, + ); + if (!attempt.ok || attempt.message.type !== "pong") return null; + const sr = attempt.message.selfReport as Record | undefined; + if (!sr || typeof sr !== "object") return null; + const { instanceId, port } = sr; + if (typeof instanceId !== "string" || instanceId === "" || typeof port !== "number" || !Number.isInteger(port)) return null; + return { instanceId, port }; +} + function socketPath(): string { if (process.env.FAILPROOFAI_DAEMON_SOCKET) return process.env.FAILPROOFAI_DAEMON_SOCKET; return daemonSocketPath(); diff --git a/src/hooks/daemon-service.ts b/src/hooks/daemon-service.ts index 4fb780b15..aedc336c3 100644 --- a/src/hooks/daemon-service.ts +++ b/src/hooks/daemon-service.ts @@ -1603,7 +1603,9 @@ export async function probeDaemonPolicyEvaluation(): Promise { event: "on_session_start", payload: { hook_event_name: "on_session_start", - source: "failproofai-native-policy-health-probe", + // The shared probe marker: the worker answers it before any activity + // row is written, and the daemon's hook watch does not count it. + source: HEALTH_PROBE_SOURCE, }, }, { responseTimeoutMs: DAEMON_PROBE_TIMEOUT_MS }, diff --git a/src/hooks/gateway-restart.ts b/src/hooks/gateway-restart.ts index 6691648f4..7c289814f 100644 --- a/src/hooks/gateway-restart.ts +++ b/src/hooks/gateway-restart.ts @@ -43,6 +43,8 @@ export interface GatewayRestart { export interface CommandResult { status: number | null; stdout: string; + /** The program is not installed (ENOENT): no gateway of it can be running. */ + missing?: boolean; } export interface GatewayRestartDeps { @@ -63,7 +65,8 @@ function defaultRun(cmd: string, args: string[], env: NodeJS.ProcessEnv): Comman killSignal: "SIGKILL", stdio: ["ignore", "pipe", "pipe"], }); - return { status: out.error ? null : out.status, stdout: `${out.stdout ?? ""}${out.stderr ?? ""}` }; + const missing = (out.error as NodeJS.ErrnoException | undefined)?.code === "ENOENT"; + return { status: out.error ? null : out.status, stdout: `${out.stdout ?? ""}${out.stderr ?? ""}`, ...(missing ? { missing } : {}) }; } function restartLogPath(): string { @@ -128,6 +131,8 @@ function restartHermesGatewayUnsafe( const result = (status: GatewayRestartStatus): GatewayRestart => ({ host: "hermes", profile: profile.name, status }); const status = run("hermes", ["gateway", "status"], env); + // No `hermes` on this machine: there is no gateway to restart, so nothing to say. + if (status.missing) return result("not-running"); if (status.status === null) return result("failed"); if (HERMES_SUPERVISED.some((line) => line.test(status.stdout))) { return result(spawnDetached("hermes", ["gateway", "restart"], env) ? "restarting" : "failed"); @@ -164,6 +169,7 @@ function restartOpenClawGatewayUnsafe( const result = (status: GatewayRestartStatus): GatewayRestart => ({ host: "openclaw", profile: profile.name, status }); const out = run("openclaw", [...profileArgs, "gateway", "status", "--json"], env); + if (out.missing) return result("not-running"); if (out.status === null) return result("failed"); let parsed: OpenClawStatus; try { diff --git a/src/hooks/handler.ts b/src/hooks/handler.ts index 3ca7992ef..9f7be5d43 100644 --- a/src/hooks/handler.ts +++ b/src/hooks/handler.ts @@ -38,6 +38,21 @@ import { antigravityPathGuard, antigravityPathGuardActive, } from "./antigravity-path-guard"; +import { + TYPED_INPUT_GUARD_DESCRIPTION, + TYPED_INPUT_GUARD_MATCH, + TYPED_INPUT_GUARD_NAME, + typedInputGuardActive, + typedInputGuardFor, + typedShellInput, +} from "./typed-shell-input"; +import { + CODEX_SESSION_GUARD_DESCRIPTION, + CODEX_SESSION_GUARD_MATCH, + CODEX_SESSION_GUARD_NAME, + codexCallOpensSession, + codexSessionGuardFor, +} from "./codex-interactive-session"; import { evaluatePolicies } from "./policy-evaluator"; // Types only: the semantic (Jev) modules are loaded with a dynamic import, and // only once a Jev config exists, so an unconfigured machine never loads them. @@ -55,6 +70,23 @@ import { } from "./policy-authority"; import type { CustomHook } from "./policy-types"; import { persistHookActivity } from "./hook-activity-store"; +import { + isSelfReportCursorCall, + isSelfReportToolName, + readEnabledSelfReport, + resolveSelfReportCategory, + selfReportAntigravityWrappedArgs, + selfReportArgs, + SELF_REPORT_MCP_TOOL_NAME, + SELF_REPORT_SERVER_RECORDS, +} from "./self-report"; +import { selfReportLogCategoryText } from "./self-report-names"; +import { selfReportFailureHint, selfReportSessionStartContext } from "./self-report-hint"; +import { selfReportClaudeHookFromDevin } from "./self-report-devin"; +import { SELF_REPORT_AGENT_PID_KEY, selfReportAgentPidOf, selfReportMarkAgentPid } from "./self-report-ancestry"; +import { dirname, isAbsolute } from "node:path"; +import { markAgentPath } from "./agent-path"; +import { AGENT_ENV_KEY, agentEnvOf, markAgentEnv, withAgentEnv } from "./agent-env"; import { deliveryHealth, deliveryHealthLine } from "./delivery-health"; import { trackHookEvent, flushHookTelemetry } from "./hook-telemetry"; import * as hookTelemetry from "./hook-telemetry"; @@ -224,6 +256,13 @@ export interface EvaluateHookEventOptions { fallbackCwd?: string; /** Config selected by the hook process (may differ from the worker's env). */ agentSettingsPath?: string; + /** + * Set by the daemon's warm worker: this process's environment is the + * daemon's, not the agent's, so whatever depends on where the agent keeps + * its configs (the Self Reports exemption) is read only from what the + * request carried, and refused without it. + */ + inWorker?: boolean; /** * The warm worker's hook into its request queue. Called at most once, and * only on the two-tier path, at the point this evaluation stops reading the @@ -656,6 +695,168 @@ async function captureJevIntent( } } +/** + * The Self Reports short-circuit's whole answer: one activity row, then allow. + * + * The row carries `selfReport` only on PreToolUse, and only for an agent whose + * hook is the recorder (contract §8). An agent in + * `SELF_REPORT_SERVER_RECORDS` has its report written by the MCP server + * instead, so a hook that turns out to see the call there must not file it a + * second time. A PostToolUse row is the call's completion, not a second report. + * + * Only while Self Reports is on, read from `self-report.json` on every call: a + * running agent keeps the MCP tools it loaded at startup, so taking our entry + * out of its config cannot stop it calling `report`, and this check is what + * makes `self-report disable` take effect at once. A missing, unreadable or + * disabled file records no report; the call is still allowed either way. + */ +function recordSelfReportCall( + canonicalEventType: string, + cli: IntegrationType, + parsed: Record, + session: SessionMetadata, + arrivedAt: number, + startTime: number, +): HookEventOutcome { + const durationMs = Math.round(performance.now() - startTime); + const writtenAt = Date.now(); + const toolCallId = toolCallIdOf(parsed); + // Only the PreToolUse row carries the report: the collector emits one + // `self_report` event per row that has it, and a call that also raises a + // PermissionRequest (or completes with a PostToolUse) is still one report. + const isReportRow = canonicalEventType === "PreToolUse"; + // Devin runs Claude Code's hooks too: a `--cli claude` call that is really + // Devin's is left to Devin's MCP server, so the report is filed once, as devin. + const devinViaClaude = isReportRow && cli === "claude" && selfReportClaudeHookFromDevin(parsed); + const enabled = isReportRow && !devinViaClaude && !SELF_REPORT_SERVER_RECORDS.includes(cli) ? readEnabledSelfReport() : null; + const hookRecords = enabled !== null; + // The category is recorded as the listed name it resolves to (a model may + // leave it out or misspell it); the line below says when it was inferred. + const report = hookRecords ? selfReportArgs(parsed.tool_input) : null; + const resolved = report && enabled + ? resolveSelfReportCategory(report.category, report.detail, enabled.categories.map((c) => c.name)) + : null; + // The agent process the call came from, when the hook CLI could read it: + // the stdio server suppresses its own copy only for a row from its agent. + const agentPid = selfReportAgentPidOf(parsed[SELF_REPORT_AGENT_PID_KEY]); + try { + persistHookActivity({ + timestamp: writtenAt, + startedAt: Math.min(arrivedAt, writtenAt), + ...(toolCallId ? { toolCallId } : {}), + eventType: canonicalEventType, + integration: cli, + toolName: (parsed.tool_name as string) ?? null, + policyName: null, + matchedPolicies: [], + decision: "allow", + reason: null, + durationMs, + sessionId: session.sessionId, + transcriptPath: session.transcriptPath, + cwd: session.cwd, + permissionMode: session.permissionMode, + hookEventName: session.hookEventName, + ...(report && resolved ? { selfReport: { category: resolved.category, detail: report.detail, source: "mcp" as const } } : {}), + ...(agentPid !== undefined ? { agentPid } : {}), + }); + } catch { + hookLogWarn("activity persistence failed"); + } + hookLogInfo( + `event=${canonicalEventType} cli=${cli} self-report allowed${devinViaClaude ? " (Devin via Claude hooks, left to Devin)" : ""}${ + resolved?.inferred ? ` category=${resolved.category} inferred_category=true raw_category=${JSON.stringify(selfReportLogCategoryText(report?.category ?? ""))}` : "" + } duration=${durationMs}ms`, + ); + return { + exitCode: 0, + stdout: "", + stderr: "", + evaluation: { + decision: "allow", + policyName: null, + policyNames: [], + reason: null, + matchedPolicies: [], + durationMs, + toolName: (parsed.tool_name as string) ?? null, + }, + }; +} + +/** + * Where the calling agent's configs are, for the report exemption: the + * environment its hook CLI carried (agent-env.ts), else, in the daemon's + * worker, what can be read from the request alone, else nothing (null: no + * exemption). The one-shot hook process IS the agent's child, so there its + * own environment is the agent's. + */ +function selfReportOriginEnv( + cli: IntegrationType, + carried: Record | undefined, + inWorker: boolean, + agentSettingsPath: string | undefined, +): Record | "process" | null { + if (carried) return carried; + if (!inWorker) return "process"; + // The Hermes and OpenClaw plugins call the daemon directly with no payload + // key, but name the profile config they run under: the only config their + // exemption reads (both are user-scope only). + const settings = agentSettingsPath?.trim(); + if (settings && isAbsolute(settings)) { + const base: Record = {}; + for (const name of ["HOME", "USERPROFILE"]) { + const v = process.env[name]; + if (v) base[name] = v; + } + if (cli === "hermes") return { ...base, HERMES_HOME: dirname(settings) }; + if (cli === "openclaw") return { ...base, OPENCLAW_CONFIG_PATH: settings }; + } + return null; +} + +/** + * Whether `cli`'s `failproofai_local` registration, as the CALLING agent sees + * it from `cwd`, is failproofai's own. Loaded on demand: only a call to the + * report tool asks. Read under the agent's environment, never the daemon + * worker's (bot review of #1105: a foreign server under the agent's own + * CODEX_HOME was judged by the daemon's genuine one). Any failure, or an + * agent environment that cannot be established, is "not ours", so the call + * is evaluated like any other. + */ +async function selfReportRegistrationIsOurs( + cli: IntegrationType, + cwd: string | undefined, + toolName: string | undefined, + originEnv: Record | "process" | null, +): Promise { + if (originEnv === null) { + hookLogWarn(`cli=${cli} report tool: the agent's config locations are unknown here; evaluated by policies`); + return false; + } + try { + const { selfReportNameCollides, selfReportRegistrationOwned } = await import("./self-report-install"); + // Synchronous from here: nothing else in the worker runs while the + // agent's variables stand in for the daemon's. + const check = (): "not-ours" | "collides" | "ours" => { + if (!selfReportRegistrationOwned(cli, cwd)) return "not-ours"; + // A name from the hook (not Cursor's or Antigravity's server-named call) + // must not be one another server registered here could also produce. + if (toolName !== undefined && selfReportNameCollides(cli, cwd, toolName)) return "collides"; + return "ours"; + }; + const verdict = originEnv === "process" ? check() : withAgentEnv(originEnv, check); + if (verdict === "not-ours") { + hookLogWarn(`cli=${cli} report tool: failproofai_local is not failproofai's registration here; evaluated by policies`); + } else if (verdict === "collides") { + hookLogWarn(`cli=${cli} report tool: another server here could be named ${toolName}; evaluated by policies`); + } + return verdict === "ours"; + } catch { + return false; + } +} + /** * The core hook-evaluation logic, decoupled from process stdin/stdout so it * can be called repeatedly inside a long-lived process (the daemon's warm @@ -698,12 +899,32 @@ export async function evaluateHookEvent( // The daemon health probe: proof the worker answers, not an agent event. // Answered before anything records scope errors or activity (B3). + // The allow `evaluation` is what the native policy-evaluation probe needs: + // the daemon answers a PolicyEvaluation only from a worker decision. if (isHealthProbe(eventType, parsed)) { - return { exitCode: 0, stdout: "", stderr: "" }; + return { + exitCode: 0, + stdout: "", + stderr: "", + evaluation: { + decision: "allow", + policyName: null, + policyNames: [], + reason: null, + matchedPolicies: [], + durationMs: Math.round(performance.now() - startTime), + toolName: null, + }, + }; } normalizeCliPayload(cli, parsed); + // The agent's config-locating environment, as its hook CLI carried it + // (agent-env.ts). Read once and kept out of everything downstream. + const carriedAgentEnv = agentEnvOf(parsed); + delete parsed[AGENT_ENV_KEY]; + // Canonicalize event name (Codex sends snake_case; internals expect PascalCase) const canonicalEventType = canonicalizeEventType(eventType, cli); @@ -711,8 +932,38 @@ export async function evaluateHookEvent( // filter and policy bodies (`ctx.toolName === "Bash"`) see the canonical // form. Mutating `parsed.tool_name` keeps the activity store + telemetry // tagging consistent (they read from `parsed.tool_name`). + // Cursor's MCP hook names our tool `report` and the server separately; + // file it under the one name before anything else reads the tool name. + // Cursor's preToolUse names one `MCP:report` with no server; only a payload + // that also names the server (`mcp_server_name: "failproofai_local"`) is ours. + // + // For Cursor that server check is the ONLY way a call becomes ours: a + // payload naming another server (or none) keeps its own tool name even + // when that name is one of our qualified spellings, and never reaches the + // short-circuit below. Otherwise another server's tool could be named + // `mcp__failproofai_local__report` and skip every policy. + const cursorSelfReport = cli === "cursor" && isSelfReportCursorCall(parsed); + if (cursorSelfReport) { + parsed.tool_name = SELF_REPORT_MCP_TOOL_NAME; + } + // Antigravity's lazy MCP path wraps the call in `call_mcp_tool`; unwrap it + // only when the wrapper names server `failproofai_local` and tool `report`. + let antigravityWrappedSelfReport = false; + if (cli === "antigravity") { + const wrapped = selfReportAntigravityWrappedArgs(parsed.tool_name, parsed.tool_input); + if (wrapped) { + parsed.tool_name = SELF_REPORT_MCP_TOOL_NAME; + parsed.tool_input = wrapped.args; + antigravityWrappedSelfReport = true; + } + } const rawToolName = parsed.tool_name as string | undefined; - const canonicalToolName = canonicalizeToolName(rawToolName, cli); + // The report tool only under THIS agent's own spelling (or a call that + // names our server outright): another agent's spelling is, here, some + // other server's tool. `canonicalizeToolName` maps only that spelling. + const serverNamedSelfReport = cursorSelfReport || antigravityWrappedSelfReport; + const ownSpellingSelfReport = !serverNamedSelfReport && isSelfReportToolName(rawToolName, cli); + const canonicalToolName = serverNamedSelfReport ? SELF_REPORT_MCP_TOOL_NAME : canonicalizeToolName(rawToolName, cli); if (canonicalToolName !== rawToolName) { parsed.tool_name = canonicalToolName; } @@ -727,6 +978,19 @@ export async function evaluateHookEvent( if (canonicalInput !== rawInput) { parsed.tool_input = canonicalInput; } + // Text typed into a running shell (Codex `write_stdin`, Copilot + // `write_bash`) arrives outside `command`, the field every shell policy + // reads: moved there as the lines it runs, or refused below when it cannot + // be read as whole lines. See typed-shell-input.ts. + const typedInput = typedShellInput(cli, rawToolName, canonicalToolName, parsed.tool_input); + if (typedInput?.kind === "command") { + parsed.tool_input = { ...(parsed.tool_input as Record), command: typedInput.command }; + } + const unreadableTypedInput = typedInput?.kind === "unreadable" ? typedInput.why : undefined; + // Codex runs no hooks for what is typed into a shell it keeps open, so a + // Codex command that opens one is refused. See codex-interactive-session.ts. + const codexSession = + cli === "codex" ? codexCallOpensSession(canonicalEventType, canonicalToolName, parsed.tool_input) : null; // Extract session metadata from payload const sessionId = parsed.session_id as string | undefined; @@ -746,9 +1010,47 @@ export async function evaluateHookEvent( rawHookEventName: eventType, cli, }; - const runtimeAgent = readRuntimeAgentIdentity( - cli, opts?.agentSettingsPath ?? runtimeAgentSettingsPath(cli, session.cwd), - ); + + // Self Reports: the agent telling FailproofAI it is stuck. Answered HERE, + // ahead of the fail-closed branch, the session pause, every policy layer + // (builtin, custom, Cloud, pack) and Jev, so nothing can block, rewrite or + // delay a report — in the study our own `.env` policy blocked one. The + // allow is the same empty answer the evaluator gives every integration + // when no policy decides. PostToolUse for the tool is recorded, never + // evaluated; any other event for it takes the ordinary path. + // + // The name alone is not enough: any server can be registered as + // `failproofai_local`. The exemption holds only while the registration the + // agent would use from this project is ours (`selfReportRegistrationOwned`: + // the installer's ownership test on the user-scope entry, and no project- + // scope definition of the name). Anything else, including anything that + // cannot be read, takes the ordinary path and the policies decide. + if ( + (serverNamedSelfReport || ownSpellingSelfReport) && + (canonicalEventType === "PreToolUse" || + (cli === "cursor" && eventType === "beforeMCPExecution") || + canonicalEventType === "PermissionRequest" || + canonicalEventType === "PostToolUse") && + (await selfReportRegistrationIsOurs( + cli, + session.cwd, + ownSpellingSelfReport ? rawToolName : undefined, + selfReportOriginEnv(cli, carriedAgentEnv, opts?.inWorker === true, opts?.agentSettingsPath), + )) + ) { + const outcome = recordSelfReportCall( + canonicalEventType === "PostToolUse" || canonicalEventType === "PermissionRequest" ? canonicalEventType : "PreToolUse", + cli, parsed, session, arrivedAt, startTime, + ); + // beforeMCPExecution requires a schema-valid answer: anything else blocks the call. + return eventType === "beforeMCPExecution" ? { ...outcome, stdout: JSON.stringify({ permission: "allow" }) } : outcome; + } + + const agentSettingsPath = opts?.agentSettingsPath ?? runtimeAgentSettingsPath(cli, session.cwd); + // The always-on guard protects this file too: when CLAUDE_CONFIG_DIR or + // CODEX_HOME moved it, no directory name the guard knows describes it. + if (agentSettingsPath) session.agentSettingsPath = agentSettingsPath; + const runtimeAgent = readRuntimeAgentIdentity(cli, agentSettingsPath); let config: HooksConfig; let customHooksList: CustomHook[] = []; @@ -892,6 +1194,28 @@ export async function evaluateHookEvent( ANTIGRAVITY_PATH_GUARD_MATCH, ); } + // Typed text no shell policy could read is refused, outside the enabled + // set for the same reason, and only for the call that carries it. + if ( + unreadableTypedInput !== undefined && + canonicalEventType === "PreToolUse" && + typedInputGuardActive(Boolean(activePause), cloudManagedPolicies) + ) { + registerPolicy( + TYPED_INPUT_GUARD_NAME, + TYPED_INPUT_GUARD_DESCRIPTION, + typedInputGuardFor(unreadableTypedInput), + TYPED_INPUT_GUARD_MATCH, + ); + } + if (codexSession !== null && typedInputGuardActive(Boolean(activePause), cloudManagedPolicies)) { + registerPolicy( + CODEX_SESSION_GUARD_NAME, + CODEX_SESSION_GUARD_DESCRIPTION, + codexSessionGuardFor(codexSession), + CODEX_SESSION_GUARD_MATCH, + ); + } // Recorded on every row once a machine is managed, whether or not a cloud // policy decided this event: "what was deployed here at the time" is a // separate question from "what decided", and only the former can tell a @@ -1295,6 +1619,12 @@ export async function evaluateHookEvent( cwd: session.cwd, permissionMode: session.permissionMode, hookEventName: session.hookEventName, + // The agent process behind the session (stamped by the hook CLI on + // session-start and prompt events): the stdio server attributes a + // report only to a session of its own agent (self-report-ancestry.ts). + ...(selfReportAgentPidOf(parsed[SELF_REPORT_AGENT_PID_KEY]) !== undefined + ? { agentPid: selfReportAgentPidOf(parsed[SELF_REPORT_AGENT_PID_KEY]) } + : {}), // Attribution. A builtin is anything registered that is not in the map, // so its absence is meaningful rather than missing — but only when a // policy actually decided; a plain allow names nobody. When Jev's own @@ -1390,10 +1720,19 @@ export async function evaluateHookEvent( } } + // Self Reports' one failure hint per session (self-report-hint.ts): only + // where every policy allowed with nothing to say, so it never replaces a + // policy's answer. + const hint = + result.decision === "allow" && result.exitCode === 0 && !result.stdout + ? (selfReportFailureHint({ cli, eventType: canonicalEventType, payload: parsed, sessionId: session.sessionId, toolCallId }) ?? + selfReportSessionStartContext(cli, canonicalEventType)) + : null; + return { - exitCode: result.exitCode, - stdout: result.stdout, - stderr: result.stderr, + exitCode: hint?.exitCode ?? result.exitCode, + stdout: hint?.stdout ?? result.stdout, + stderr: hint ? [result.stderr, hint.stderr].filter(Boolean).join("\n") : result.stderr, evaluation: { decision: result.decision, policyName: result.policyName, @@ -1461,8 +1800,10 @@ export async function handleHookEvent( }); } + // The agent process above this hook, for a Claude Code / Codex report call + // (self-report-ancestry.ts); the daemon path adds it in the hook CLI. const result = await evaluateHookEvent( - eventType, cli, stdinRead.payload, + eventType, cli, markAgentEnv(markAgentPath(selfReportMarkAgentPid(cli, canonicalizeEventType(eventType, cli), stdinRead.payload))), agentSettingsPath === undefined ? undefined : { agentSettingsPath }, ); diff --git a/src/hooks/health-probe.ts b/src/hooks/health-probe.ts index 5199187b0..07df52b07 100644 --- a/src/hooks/health-probe.ts +++ b/src/hooks/health-probe.ts @@ -9,7 +9,16 @@ */ export const HEALTH_PROBE_SOURCE = "failproofai-health-probe"; +/** + * The events a probe is sent as: the shell-hook probe's `SessionStart`, and the + * native policy-evaluation probe's Hermes `on_session_start` + * (`probeDaemonPolicyEvaluation`), which also carries this source so it writes + * no activity row either (it used to leave a phantom `hermes` SessionStart on + * machines with no Hermes). + */ +const HEALTH_PROBE_EVENTS: ReadonlySet = new Set(["SessionStart", "on_session_start"]); + /** Whether a parsed hook payload is the daemon health probe. */ export function isHealthProbe(eventType: string, parsed: Record): boolean { - return eventType === "SessionStart" && parsed.source === HEALTH_PROBE_SOURCE && parsed.session_id === undefined; + return HEALTH_PROBE_EVENTS.has(eventType) && parsed.source === HEALTH_PROBE_SOURCE && parsed.session_id === undefined; } diff --git a/src/hooks/hook-activity-store.ts b/src/hooks/hook-activity-store.ts index 4a15480ab..c3df1608f 100644 --- a/src/hooks/hook-activity-store.ts +++ b/src/hooks/hook-activity-store.ts @@ -25,6 +25,8 @@ import { join } from "node:path"; import type { IntegrationType } from "./types"; import { hookActivityDir } from "./fp-home"; import { sanitizeJevActivity, type JevCheckRecord } from "./jev-activity"; +import { selfReportClip, selfReportCutDetail } from "./self-report-names"; +import { selfReportAgentPidOf } from "./self-report-ancestry"; export const PAGE_SIZE = 25; @@ -181,6 +183,22 @@ export interface HookActivityEntry { decision: "deny" | "instruct"; reason: string | null; }>; + /** + * Set only on a call to the Self Reports tool (`mcp__failproofai_local__report` and + * its per-agent spellings): what the agent reported. Such a row was allowed + * before any policy ran and was never evaluated, so its decision is always + * `allow` and it names no policy. The collector turns it into a + * `self_report` event. `detail` is at most 2000 characters. + */ + selfReport?: { category: string; detail: string; source: "mcp" }; + /** + * The agent process behind the hook (the nearest process above it that is + * not a shell or exec wrapper), stamped on Self Reports calls and on + * session-start and prompt events (self-report-ancestry.ts). Local only, + * never shipped: the stdio server matches a row, and picks a session, only + * for its own agent's pid. + */ + agentPid?: number; } export interface HookActivityFilters { @@ -250,7 +268,7 @@ export function persistHookActivity(input: HookActivityEntry): void { // machine by the collector, and a fallback reason is the one field that can // carry free text (see jev-activity.ts). A row with no Jev fields is written // exactly as given. - const entry = sanitizeJevActivity(input); + const entry = sanitizeSelfReportActivity(sanitizeJevActivity(input)); ensureDir(); acquireLock(); try { @@ -275,6 +293,32 @@ export function persistHookActivity(input: HookActivityEntry): void { } } +/** + * Keep `selfReport` only in its declared shape: two strings of at most 2000 + * code points (no lone surrogate) and `source: "mcp"`. Like the Jev fields it is shipped off the + * machine by the collector, so it is checked at this one door. + */ +function sanitizeSelfReportActivity(entry: HookActivityEntry): HookActivityEntry { + if (entry.selfReport === undefined && entry.agentPid === undefined) return entry; + const sr = entry.selfReport as unknown; + const out = { ...entry }; + const pid = selfReportAgentPidOf(entry.agentPid); + if (pid !== undefined) out.agentPid = pid; + else delete out.agentPid; + if (sr === undefined) return out; + if (!sr || typeof sr !== "object" || Array.isArray(sr)) { + delete out.selfReport; + return out; + } + const rec = sr as Record; + out.selfReport = { + category: typeof rec.category === "string" ? selfReportClip(rec.category) : "", + detail: typeof rec.detail === "string" ? selfReportCutDetail(rec.detail) : "", + source: "mcp", + }; + return out; +} + function rotate(currentPath: string, countPath: string): void { const archiveName = `page-${Date.now()}-${rotateSeq++}.jsonl`; const archivePath = join(storeDirValue(), archiveName); diff --git a/src/hooks/integrations.ts b/src/hooks/integrations.ts index 4dcda2b6c..d7752734d 100644 --- a/src/hooks/integrations.ts +++ b/src/hooks/integrations.ts @@ -116,7 +116,7 @@ function writeJsonFile(path: string, data: Record): void { * an empty Document; unreadable or unparseable → {@link UnreadableAgentConfigError}, * never an empty Document that the next write would put in the user's place. * Used by the Hermes integration, whose config lives in `~/.hermes/config.yaml`. */ -function readYamlDoc(path: string): Document { +export function readYamlDoc(path: string): Document { if (!existsSync(path)) return parseDocument(""); let text: string; try { @@ -141,7 +141,7 @@ function inspectYamlDoc(path: string): Document | null { } } -function writeYamlDoc(path: string, doc: Document): void { +export function writeYamlDoc(path: string, doc: Document): void { writeConfigFileAtomic(path, doc.toString()); } @@ -1506,7 +1506,7 @@ interface HermesPluginsConfig { const HERMES_PLUGIN_ID = "failproofai"; const HERMES_PLUGIN_MARKER = ".failproofai-managed"; -const HERMES_PLUGIN_FILES = ["plugin.yaml", "__init__.py", "client.py", "ledger.py"] as const; +const HERMES_PLUGIN_FILES = ["plugin.yaml", "__init__.py", "client.py", "ledger.py", "self_report.py"] as const; /** Basename of the plugin directory inside the npm package. */ const HERMES_PLUGIN_SOURCE_DIR = "hermes-plugin"; diff --git a/src/hooks/manager.ts b/src/hooks/manager.ts index a826eb215..db4959406 100644 --- a/src/hooks/manager.ts +++ b/src/hooks/manager.ts @@ -43,6 +43,8 @@ import { packPolicyParamKey } from "./policy-evaluator"; import { probeDaemonPolicyEvaluation } from "./daemon-service"; import { NO_PRINTED_COMMAND_REASON, sudoPath } from "./system-command"; import { keepAgentSelectionTrue } from "./agent-selection"; +import { removeSelfReportMcp, selfReportSummary, syncSelfReportMcp } from "./self-report-install"; +import { ensureSelfReportSettingsFile, selfReportSettingsState } from "./self-report"; import { INDENT, colorsEnabled, optsFor, printBlock, screenKit, type ScreenKitOpts } from "./tui"; const VALID_POLICY_NAMES = new Set(BUILTIN_POLICIES.map((p) => p.name)); @@ -1008,6 +1010,34 @@ async function installHooksImpl( } catch {} } + // Self Reports: on by default, so the agents that now have hooks get + // failproofai's MCP server unless it was turned off (and lose a stale one + // when it is). The settings file is written first when it is missing (off + // Cloud), so every reader agrees. Best-effort: a config it cannot change is + // reported, never a failed install. + // Only a user-scope install touches the agents' user-wide MCP configs: a + // project or local install must not register anything outside that project. + if (scope === "user") { + try { + await ensureSelfReportSettingsFile(); + } catch { + // the readers apply the same default without the file + } + try { + const results = await syncSelfReportMcp({ + quiet: true, + alsoHooked: writtenSettingsPaths.map((written) => written.cli), + binaryPath, + }); + // Nothing when it worked: `self-report status` and `sync` show where each + // agent stands. Only an agent that could not be updated gets a line. + const summary = selfReportSummary(results, selfReportSettingsState()); + if (summary && !summary.ok) console.log(kit.caution(summary.text, summary.fix)); + } catch { + // never block the install + } + } + // Last, after everything above: the agents whose hooks were actually written. // A call that returned early (only a third-party pack's policies were named) // or threw wrote none and changes nothing. @@ -1212,6 +1242,19 @@ export async function removeHooks(policyNames?: string[], scope: HookScope | "al } } + // Self Reports, after the hooks: an agent whose user-scope hooks go also loses failproofai's + // MCP server, whatever the setting says. Project/local removals leave it: + // the user-scope hooks that use it are still there. + if (scope === "user" || scope === "all") { + try { + const summary = selfReportSummary(removeSelfReportMcp({ agents: selectedClis, quiet: true }), "removed"); + const kit = screenKit(optsFor(process.stdout)); + if (summary && !summary.ok) say(kit.caution(summary.text, summary.fix)); + } catch { + // never block the removal + } + } + if (nothingToReport && totalRemoved === 0) { untraceRemoved(); return; diff --git a/src/hooks/policy-catalog.ts b/src/hooks/policy-catalog.ts index ad4300c5e..47f2b06f8 100644 --- a/src/hooks/policy-catalog.ts +++ b/src/hooks/policy-catalog.ts @@ -232,7 +232,7 @@ export const POLICY_CATALOG: PolicyCatalogEntry[] = [ name: "block-failproofai-commands", displayTitle: "Tried to disable, pause or modify failproofai itself", impact: "An agent that can pause or remove enforcement can switch off every other policy.", - description: "Block failproofai CLI commands, self-pause and uninstallation", + description: "Block failproofai CLI commands, self-pause, uninstallation, and agent edits to hook settings", // PermissionRequest is carried over from the merged-in `block-self-pause`. // It is a real enforcement point on Copilot and Devin, and dropping it would // have left this guard blind on both. @@ -240,10 +240,15 @@ export const POLICY_CATALOG: PolicyCatalogEntry[] = [ // through this guard unguarded: the agent never needs a shell to overwrite // `~/.failproofai/policies-config.json` with `{"enabledPolicies":[]}` — it // just writes the file. Every CLI canonicalizes its own file tool's path - // key to `file_path`, so one branch covers all of them. + // key to `file_path`, so one branch covers all of them. MultiEdit is the + // same write through Claude Code's other edit tool, and these tools are + // also how an agent would set `"disableAllHooks": true` in its settings. match: { events: ["PreToolUse", "PermissionRequest"], - toolNames: ["Bash", "Write", "Edit", "NotebookEdit"], + // `apply_patch` by its own name too: OpenClaw passes its patch tool + // through uncanonicalized, where Codex, Copilot and OpenCode map theirs to Edit + // (FailproofAI/failproofai#1058). + toolNames: ["Bash", "Write", "Edit", "MultiEdit", "NotebookEdit", "apply_patch"], }, defaultEnabled: true, alwaysOn: true, diff --git a/src/hooks/self-report-ancestry.ts b/src/hooks/self-report-ancestry.ts new file mode 100644 index 000000000..b82f6a1d1 --- /dev/null +++ b/src/hooks/self-report-ancestry.ts @@ -0,0 +1,203 @@ +/** + * Which agent process a hook event or a stdio report came from, so the stdio + * server can tell its own agent's hook rows and session from another's + * (review finding F14). + * + * The hook process and the stdio MCP server are both started by the agent: + * the hook through the agent's hook runner (often a shell, sometimes `npx`), + * the server as the agent's child. Each side names its agent as the NEAREST + * process above it that is not such a runner (`selfReportAgentPid`), and the + * two match only when that is the same pid, exactly. An ancestor further up + * is never enough: an agent B started inside agent A (A's shell tool running + * `claude -p …` in the same directory) has A above it too, and B's hook rows + * and reports are B's, not A's. + * + * The hook side has to read its ancestry in the hook process the agent + * started, not in the daemon's warm worker (whose parent is the daemon): the + * hook CLI adds `SELF_REPORT_AGENT_PID_KEY` to the payload before it forwards + * or evaluates it, and the handler copies it onto the activity row as + * `agentPid`. It is added to a Claude Code / Codex report call (the stdio + * server's dedup) and to every agent's session-start and prompt events (the + * server's session attribution), so ordinary tool traffic pays nothing. + * Anything unreadable gives no pid, and a row with no pid never vouches for a + * call: the server records rather than suppresses. + */ +import { execFileSync } from "node:child_process"; +import { readFileSync } from "node:fs"; +import { basename } from "node:path"; +import { isSelfReportToolName } from "./self-report-names"; +import { readEnabledSelfReport } from "./self-report"; + +/** Payload key the hook CLI adds: the pid of the agent process above the hook. */ +export const SELF_REPORT_AGENT_PID_KEY = "failproofai_report_agent_pid"; + +/** + * The earlier form of the stamp: a pid list a worker of the previous build + * copies onto a report row as `selfReportAgentPids`. The client writes BOTH, + * the list holding just the agent pid, because after `npm i -g` the daemon's + * warm worker keeps running the previous build until the daemon restarts, and + * a row it wrote without a stamp made the new stdio server record the report + * a second time. + */ +export const SELF_REPORT_AGENT_PIDS_KEY_V1 = "failproofai_report_agent_pids"; + +/** How many processes above this one are looked at. */ +export const SELF_REPORT_ANCESTRY_DEPTH = 8; + +/** Agents whose hook records the report and whose stdio server must recognise that row. */ +const HOOK_RECORDED: readonly string[] = ["claude", "codex"]; + +/** Canonical events that stamp the agent pid on every agent: they name the session. */ +const SESSION_EVENTS: readonly string[] = ["SessionStart", "UserPromptSubmit"]; + +/** + * Processes that run something on an agent's behalf and are not the agent: + * shells and the usual exec wrappers. `npm exec`/`npx` (a project-scope hook + * is `npx -y failproofai --hook …`) show as `npm…`/`npx…` once npm sets its + * process title. + */ +const RUNNER_NAMES: ReadonlySet = new Set([ + "sh", "bash", "zsh", "dash", "ash", "ksh", "mksh", "fish", "csh", "tcsh", + "env", "timeout", "nice", "nohup", "setsid", "stdbuf", "xargs", + "npx", "npm", "pnpm", "pnpx", "yarn", "bunx", +]); + +function isRunner(name: string): boolean { + const n = basename(name).toLowerCase().replace(/^-/, ""); // a login shell's `-bash` + return RUNNER_NAMES.has(n) || /^(?:npm|npx)[\s-]/.test(n); +} + +export interface SelfReportProcess { + pid: number; + name: string; +} + +/** + * The processes above this one, nearest first (its parent first), up to + * `depth`, stopping after the first one `until` accepts. Best effort: `[]` on + * any failure. + * + * Linux reads `/proc//stat`. macOS asks `ps` for one process per level + * (`ps -o pid=,ppid=,comm= -p `), not the whole table (`ps -A`): the + * agent is normally one or two levels up, so with `until` that is one or two + * small lookups instead of listing every process on the machine. + */ +export function selfReportAncestry( + depth: number = SELF_REPORT_ANCESTRY_DEPTH, + until?: (p: SelfReportProcess) => boolean, +): SelfReportProcess[] { + const out: SelfReportProcess[] = []; + try { + if (process.platform === "linux") { + let pid = process.ppid; + for (let i = 0; i < depth && pid > 1; i++) { + // " () …"; comm may itself hold ") ". + const stat = readFileSync(`/proc/${pid}/stat`, "utf8"); + const close = stat.lastIndexOf(")"); + const p = { pid, name: stat.slice(stat.indexOf("(") + 1, close) }; + out.push(p); + if (until?.(p)) break; + pid = Number(stat.slice(close + 2).split(" ")[1]) || 0; + } + } else if (process.platform === "darwin") { + let pid = process.ppid; + for (let i = 0; i < depth && pid > 1; i++) { + const ps = execFileSync("/bin/ps", ["-o", "pid=,ppid=,comm=", "-p", String(pid)], { encoding: "utf8", timeout: 1000 }); + const m = /^\s*(\d+)\s+(\d+)\s+(.*)$/m.exec(ps); + if (!m || Number(m[1]) !== pid) break; + const p = { pid, name: basename(m[3].trim()) }; + out.push(p); + if (until?.(p)) break; + pid = Number(m[2]); + } + } + } catch { + // Unreadable /proc, no ps: no more ancestry (what was read is kept). + } + return out; +} + +/** The nearest process above this one that is not a shell or exec wrapper: the agent. */ +export function selfReportAgentPid( + ancestry: () => SelfReportProcess[] = () => selfReportAncestry(SELF_REPORT_ANCESTRY_DEPTH, (p) => !isRunner(p.name)), +): number | undefined { + for (const p of ancestry()) { + if (!isRunner(p.name)) return p.pid > 1 ? p.pid : undefined; + } + return undefined; +} + +/** Whether Self Reports is on now; an unreadable setting counts as off. */ +function selfReportStampWanted(): boolean { + try { + return readEnabledSelfReport() !== null; + } catch { + return false; + } +} + +let serverAgentPid: { value: number | undefined } | null = null; + +/** + * This stdio server's agent: the nearest process above it that is not a shell + * or exec wrapper (normally its parent). Read once per server process. + */ +export function selfReportServerAgentPid(): number | undefined { + if (!serverAgentPid) serverAgentPid = { value: selfReportAgentPid() }; + return serverAgentPid.value; +} + +/** + * The agent pid a hook-activity row was stamped with, in either form: this + * build's `agentPid`, or `selfReportAgentPids` (a list, nearest process + * first) from a worker of the previous build. Only the list's FIRST pid + * counts: the client stamps `[pid]`, and a longer list from an older client + * names the agent only there when the hook ran with no shell between; any + * later entry may be an outer agent, and taking it would suppress a report + * that is not its own. With neither, undefined: the server records. + */ +export function selfReportRowAgentPid(row: Record): number | undefined { + const pid = selfReportAgentPidOf(row.agentPid); + if (pid !== undefined) return pid; + const list = row.selfReportAgentPids; + return Array.isArray(list) ? selfReportAgentPidOf(list[0]) : undefined; +} + +/** A pid in a payload or row field, kept only in its declared shape. */ +export function selfReportAgentPidOf(value: unknown): number | undefined { + return typeof value === "number" && Number.isSafeInteger(value) && value > 1 ? value : undefined; +} + +/** + * In the hook process: `stdin` with `SELF_REPORT_AGENT_PID_KEY` set to the + * agent's pid on a Claude Code / Codex report call and on any agent's + * session-start or prompt event (`canonicalEvent`), else `stdin` unchanged + * (a value it already carried is replaced or dropped, never trusted). Only + * while Self Reports is on (`enabled`, by default the effective settings + * file): off, nothing is looked up. Never throws. + */ +export function selfReportMarkAgentPid( + cli: string, + canonicalEvent: string, + stdin: string, + agentPid: () => number | undefined = selfReportAgentPid, + enabled: () => boolean = selfReportStampWanted, +): string { + const sessionEvent = SESSION_EVENTS.includes(canonicalEvent); + const maybeReport = HOOK_RECORDED.includes(cli) && /failproofai_local/i.test(stdin); + const carried = stdin.includes(SELF_REPORT_AGENT_PID_KEY); // also matches the V1 key, which it prefixes + if (!sessionEvent && !maybeReport && !carried) return stdin; + try { + const parsed = JSON.parse(stdin) as unknown; + if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return stdin; + const { [SELF_REPORT_AGENT_PID_KEY]: dropped, [SELF_REPORT_AGENT_PIDS_KEY_V1]: droppedV1, ...rest } = parsed as Record; + // Only while Self Reports is on: nothing reads the stamp otherwise, and on + // macOS the lookup runs `ps` on every session start and prompt. + const stamp = (sessionEvent || (maybeReport && isSelfReportToolName(rest.tool_name, cli))) && enabled(); + const pid = stamp ? agentPid() : undefined; + if (pid !== undefined) return JSON.stringify({ ...rest, [SELF_REPORT_AGENT_PID_KEY]: pid, [SELF_REPORT_AGENT_PIDS_KEY_V1]: [pid] }); + return dropped === undefined && droppedV1 === undefined ? stdin : JSON.stringify(rest); + } catch { + return stdin; + } +} diff --git a/src/hooks/self-report-cli.ts b/src/hooks/self-report-cli.ts new file mode 100644 index 000000000..d7a93dfb3 --- /dev/null +++ b/src/hooks/self-report-cli.ts @@ -0,0 +1,679 @@ +/** + * `failproofai self-report status | enable | disable | test`. + * + * `sync` (registering the MCP server in every agent) lives in + * self-report-install.ts; enable/disable call it in process, and bin keeps the + * `failproofai self-report sync --quiet` subcommand the daemon runs (contract §6). + * + * Returns lines and an exit code like the other `*-cli.ts` modules; bin prints + * them. + */ +import { spawn } from "node:child_process"; +import { readdirSync, readFileSync } from "node:fs"; +import { basename, dirname, join } from "node:path"; +import { customAgentsEventsDir, hookActivityDir } from "./fp-home"; +import { + SELF_REPORT_DEFAULT_CATEGORIES, + SELF_REPORT_MCP_TOOL_NAME, + SELF_REPORT_RESULT_TEXT, + SELF_REPORT_SERVER_NAME, + SELF_REPORT_SERVER_RECORDS, + SELF_REPORT_TOOL_NAME, + readEffectiveSelfReport, + readLocalSelfReportConfig, + resolveSelfReport, + selfReportClip, + selfReportCloudEnrolled, + selfReportFileDecides, + selfReportCloudManaged, + selfReportSettingsFile, + validateSelfReportCategories, + validateSelfReportGuidance, + writeEffectiveSelfReport, + writeLocalSelfReportConfig, + type SelfReportCategory, +} from "./self-report"; +import { INTEGRATION_TYPES } from "./types"; +import { daemonSocketPresent, isDaemonConfigured } from "./daemon-client"; +import { SELF_REPORT_RECEIPT_ENV, SELF_REPORT_RECEIPT_PREFIX } from "./self-report-mcp"; +import { + SELF_REPORT_HOOK_RECORDED_AGENTS, + claudeHooksBlockedReason, + codexReportHookRuns, + selfReportHookState, + type SelfReportHookState, +} from "./self-report-hook-trust"; +import { + SELF_REPORT_CURSOR_APPROVAL_HINT, + probeSelfReportHttp, + selfReportDaemonLive, + selfReportHttpAllowed, + selfReportCommandRunnable, + selfReportRegistrationStatus, + selfReportSyncChanged, + selfReportSummaryLine, + selfReportSyncLines, + syncSelfReportMcp, + type SelfReportRegistration, +} from "./self-report-install"; + +export interface SelfReportCliResult { + exitCode: number; + lines: string[]; + /** `status --json`: printed as JSON instead of the lines. */ + json?: unknown; +} + +export interface SelfReportCliDeps { + /** argv prefix that runs this CLI: `[node, dist/cli.mjs]`. */ + cliCommand?: string[]; + /** Health probe override (tests): does the HTTP endpoint on this port answer? */ + probeEndpoint?: (url: string, port: number) => Promise; + /** Ownership override (tests): is the endpoint on this port this home's daemon? (`selfReportDaemonLive`) */ + daemonLive?: (port: number) => Promise; + /** Registration rows override (tests). */ + registrations?: () => SelfReportRegistration[]; + /** Sync override (tests). */ + sync?: () => Promise; + /** Override (tests): is a daemon configured here, or its socket file present? */ + daemonExpected?: () => boolean; + /** Who records a hook-recorded agent's reports (tests; default `selfReportHookState`). */ + hookState?: (agent: string) => SelfReportHookState; + /** Skip the agent sync after enable/disable (tests). */ + skipSync?: boolean; + /** The last update's routine gateway rows (tests; default `readGatewayReport`). */ + gatewayReport?: () => { at: string; rows: string[] } | null; + cwd?: string; +} + +const SELF_REPORT_CLOUD_REFUSAL = [ + "This machine is managed by FailproofAI Cloud, so Self Reports is set there.", + "Turn it on or off in the dashboard: Settings > Self Reports.", +]; + +function selfReportCliCommand(deps: SelfReportCliDeps): string[] { + return deps.cliCommand ?? [process.execPath, process.argv[1]]; +} + +/** Run the CLI as a child, feeding `stdin`; resolves with its output. */ +function selfReportRunChild( + argv: string[], + stdin: string, + timeoutMs: number, + cwd?: string, + extraEnv: Record = {}, +): Promise<{ code: number | null; stdout: string; stderr: string }> { + return new Promise((resolveRun) => { + const [cmd, ...rest] = argv; + const child = spawn(cmd, rest, { cwd, stdio: ["pipe", "pipe", "pipe"], env: { ...process.env, ...extraEnv } }); + let stdout = ""; + let stderr = ""; + const timer = setTimeout(() => child.kill("SIGKILL"), timeoutMs); + child.stdout.on("data", (b: Buffer) => (stdout += b.toString("utf8"))); + child.stderr.on("data", (b: Buffer) => (stderr += b.toString("utf8"))); + child.on("error", (err) => { + clearTimeout(timer); + resolveRun({ code: null, stdout, stderr: stderr + String(err) }); + }); + child.on("close", (code) => { + clearTimeout(timer); + resolveRun({ code, stdout, stderr }); + }); + child.stdin.end(stdin); + }); +} + +/** The port of one of our endpoint URLs, or null. */ +function selfReportUrlPort(url: string | null): number | null { + if (!url) return null; + try { + const port = Number(new URL(url).port); + return Number.isInteger(port) && port > 0 ? port : null; + } catch { + return null; + } +} + +/** Probe each distinct HTTP port among the rows once. */ +async function selfReportHttpHealth(rows: readonly SelfReportRegistration[], deps: SelfReportCliDeps): Promise> { + const probe = deps.probeEndpoint ?? ((_url: string, port: number) => probeSelfReportHttp(port)); + const ports = new Set(); + for (const r of rows) { + const port = r.registered && r.transport === "http" ? selfReportUrlPort(r.endpoint) : null; + if (port !== null) ports.add(port); + } + const health = new Map(); + await Promise.all( + [...ports].map(async (port) => health.set(port, await probe(`http://127.0.0.1:${port}/mcp`, port))), + ); + return health; +} + +/** + * For each answering port, whether it is THIS home's daemon that answers + * (`selfReportDaemonLive`): a name-only answer may be another user's or + * another FAILPROOFAI_HOME's daemon, which would record reports under its + * own home and credentials. + */ +async function selfReportHttpOwnership(health: ReadonlyMap, deps: SelfReportCliDeps): Promise> { + const live = deps.daemonLive ?? selfReportDaemonLive; + const owned = new Map(); + await Promise.all( + [...health].filter(([, answering]) => answering).map(async ([port]) => owned.set(port, await live(port))), + ); + return owned; +} + +/** Per-agent registration state: transport, endpoint and whether it answers. */ +function selfReportRegistrationLines( + rows: readonly SelfReportRegistration[], + health: ReadonlyMap, + owned: ReadonlyMap, + recorders: ReadonlyMap = new Map(), +): string[] { + const hooked = rows.filter((r) => r.hooked || r.registered || r.conflict || r.error); + if (hooked.length === 0) return ["Agents: none with failproofai hooks"]; + return [ + "Agents:", + ...hooked.map((r) => { + let state: string; + if (r.error) state = `unreadable (${r.error})`; + else if (r.conflict) state = `another "${SELF_REPORT_SERVER_NAME}" MCP server is configured; left alone`; + else if (r.registered && r.transport === "http") { + const port = selfReportUrlPort(r.endpoint); + const ok = port !== null && health.get(port) === true; + const mine = ok && owned.get(port!) === true; + state = `http ${r.endpoint ?? "?"} ${mine ? "(answering)" : ok ? "(answering, but NOT this home's daemon)" : "(NOT answering)"}`; + } else if (r.registered && r.transport === "extension") { + state = `tool offered by failproofai's ${r.agent === "pi" ? "Pi extension" : r.agent === "hermes" ? "Hermes plugin" : "OpenClaw plugin"} (loaded with its hooks)`; + } else if (r.registered) { + const ok = !!r.endpoint && selfReportCommandRunnable(r.endpoint); + state = `stdio ${r.endpoint ?? "?"} ${ok ? "(runnable)" : "(NOT runnable)"}`; + } else state = r.hooked ? "not registered" : "registered, no hooks"; + if (r.registered && !r.hooked) state += ", no hooks"; + const line = ` ${r.agent.padEnd(12)} ${state}`; + const pad = ` ${"".padEnd(12)} `; + if (r.agent === "cursor" && r.registered) return [line, `${pad}${SELF_REPORT_CURSOR_APPROVAL_HINT}`]; + const recorder = recorders.get(r.agent); + if (recorder && r.registered) { + return recorder.recorder === "hook" + ? [line, `${pad}reports recorded by its hook`] + : [line, `${pad}reports recorded by the MCP server: ${recorder.reason}.`, `${pad}${recorder.fix}`]; + } + return [line]; + }).flat(), + ]; +} + +/** + * Whether a row is registered over HTTP where it should not be: an endpoint + * that is not answering, or that answers as some other home's daemon, or an + * agent whose reports the server records (those belong on stdio, where the + * server knows the caller's cwd; an older version registered them over HTTP). + */ +function selfReportStranded( + r: SelfReportRegistration, + health: ReadonlyMap, + owned: ReadonlyMap, + recorders: ReadonlyMap = new Map(), +): boolean { + if (!r.registered || r.transport !== "http") return false; + if (!selfReportHttpAllowed(r.agent)) return true; + // The daemon's endpoint records nothing for Claude Code or Codex, so one + // whose hook will not run (an untrusted Codex) would lose every report there. + if (recorders.get(r.agent)?.recorder === "server") return true; + const port = selfReportUrlPort(r.endpoint); + return port === null || health.get(port) !== true || owned.get(port) !== true; +} + +/** One agent's state, for every view of `status`. */ +interface SelfReportAgentView { + agent: string; + path: string; + hooked: boolean; + registered: boolean; + transport: SelfReportRegistration["transport"]; + endpoint: string | null; + /** Registered and working: its endpoint answers as this home's daemon, or its command runs. */ + healthy: boolean; + /** What is wrong, when something is, and the command that fixes it. */ + problem?: string; + fix?: string; + /** Claude Code / Codex: who records its reports, and why when it is the server. */ + recorder?: SelfReportHookState; +} + +const SELF_REPORT_SYNC_FIX = "failproofai self-report sync"; + +function selfReportAgentViews( + rows: readonly SelfReportRegistration[], + health: ReadonlyMap, + owned: ReadonlyMap, + recorders: ReadonlyMap, +): SelfReportAgentView[] { + const out: SelfReportAgentView[] = []; + for (const r of rows.filter((x) => x.hooked || x.registered || x.conflict || x.error)) { + const recorder = r.registered ? recorders.get(r.agent) : undefined; + const view: SelfReportAgentView = { + agent: r.agent, path: r.path, hooked: r.hooked, registered: r.registered, + transport: r.transport, endpoint: r.endpoint, healthy: false, + ...(recorder ? { recorder } : {}), + }; + if (r.error) view.problem = `config unreadable (${r.error})`; + else if (r.conflict) view.problem = `another "${SELF_REPORT_SERVER_NAME}" MCP server is configured; left alone`; + else if (!r.registered) Object.assign(view, { problem: "not registered", fix: SELF_REPORT_SYNC_FIX }); + else if (r.transport === "http") { + const port = selfReportUrlPort(r.endpoint); + const ok = port !== null && health.get(port) === true; + if (ok && owned.get(port!) === true) view.healthy = true; + else Object.assign(view, { problem: ok ? "endpoint is another home's daemon" : "endpoint not answering", fix: SELF_REPORT_SYNC_FIX }); + } else if (r.transport === "extension") view.healthy = true; + else if (r.endpoint && selfReportCommandRunnable(r.endpoint)) view.healthy = true; + else Object.assign(view, { problem: "command not runnable", fix: SELF_REPORT_SYNC_FIX }); + out.push(view); + } + return out; +} + +async function selfReportStatus(args: string[], deps: SelfReportCliDeps): Promise { + const unknown = args.find((a) => a !== "--json"); + if (unknown) return { exitCode: 1, lines: [`Unexpected argument: ${unknown}.`] }; + const asJson = args.includes("--json"); + const file = readEffectiveSelfReport(); + const settings = resolveSelfReport(); + const cloud = await selfReportCloudManaged(); + const lines: string[] = []; + if (!settings) { + const missing = !file && !selfReportFileExists(); + // This machine's own file, set aside while the org's setting is awaited. + // This machine's own file, or one another enrolment (a previous org) + // left, set aside while this enrolment's setting is awaited. + const awaitingCloud = !!file && selfReportCloudEnrolled() && !selfReportFileDecides(file); + const why = awaitingCloud || (missing && selfReportCloudEnrolled()) ? "waiting" : missing ? "config" : "unreadable"; + if (asJson) { + return { + exitCode: 0, + lines: [], + json: { + enabled: false, + reason: why === "waiting" ? "waiting for Cloud" : why === "unreadable" ? "settings unreadable" : "off in config.json", + settingsPath: selfReportSettingsFile(), + managedByCloud: cloud, + }, + }; + } + lines.push( + awaitingCloud + ? "Self Reports: off (waiting for FailproofAI Cloud to send this machine's setting; this machine's own setting no longer applies)" + : missing + ? selfReportCloudEnrolled() + ? "Self Reports: off (waiting for FailproofAI Cloud to send this machine's setting)" + : "Self Reports: off (turned off in config.json)" + : "Self Reports: off (the settings file cannot be read)", + ); + lines.push(`Settings: ${selfReportSettingsFile()}`); + lines.push(cloud ? "Managed by: FailproofAI Cloud (Settings > Self Reports)" : "Turn on: `failproofai self-report enable`"); + return { exitCode: 0, lines }; + } + const source = settings.source === "cloud" ? "cloud" : file ? "local" : "default"; + const readRows = deps.registrations ?? (() => selfReportRegistrationStatus()); + let rows = readRows(); + let health = await selfReportHttpHealth(rows, deps); + let owned = await selfReportHttpOwnership(health, deps); + const recorders = new Map(); + for (const agent of SELF_REPORT_HOOK_RECORDED_AGENTS) { + if (!rows.some((r) => r.agent === agent && (r.registered || r.hooked))) continue; + try { + const hooked = (a: string) => rows.some((r) => r.agent === a && r.hooked); + recorders.set(agent, deps.hookState ? deps.hookState(agent) : selfReportHookState(agent, { userHooksInstalled: hooked })); + } catch { + // unknown: show nothing for it + } + } + // An agent left on the daemon's HTTP endpoint after the daemon died would + // have no report tool, and one on a port another home's daemon holds would + // report into that home. Move it (live check: stdio unless this home's + // daemon serves the endpoint). + let repairedLines: string[] = []; + let repairedAgents: string[] = []; + if (settings.enabled && !deps.skipSync && rows.some((r) => selfReportStranded(r, health, owned, recorders))) { + try { + const results = await (deps.sync ?? (() => syncSelfReportMcp({ quiet: true })))(); + if (selfReportSyncChanged(results)) { + repairedAgents = results + .filter((r) => r.action === "added" || r.action === "updated" || r.action === "removed") + .map((r) => r.agent) + .filter((a, i, all) => all.indexOf(a) === i); + repairedLines = [ + "Repaired: agents on an HTTP endpoint that is not this home's answering daemon, or that belong on stdio, were re-synced:", + ...selfReportSyncLines(results).map((l) => ` ${l}`), + ]; + rows = readRows(); + health = await selfReportHttpHealth(rows, deps); + owned = await selfReportHttpOwnership(health, deps); + } + } catch { + repairedLines = [`▲ Could not re-sync agents whose HTTP endpoint is not answering. Run \`${SELF_REPORT_SYNC_FIX}\`.`]; + } + } + if (!health.has(settings.mcp.port)) { + const probe = deps.probeEndpoint ?? ((_url: string, port: number) => probeSelfReportHttp(port)); + health.set(settings.mcp.port, await probe(settings.mcp.url, settings.mcp.port)); + } + const daemonAnswering = health.get(settings.mcp.port) === true; + const views = selfReportAgentViews(rows, health, owned, recorders); + + if (asJson) { + return { + exitCode: 0, + lines: [], + json: { + enabled: settings.enabled, + source, + settingsPath: selfReportSettingsFile(), + updatedAt: settings.updatedAt || null, + categories: settings.categories.map((c) => c.name), + guidance: settings.guidance, + server: SELF_REPORT_SERVER_NAME, + tool: SELF_REPORT_TOOL_NAME, + daemon: { url: settings.mcp.url, answering: daemonAnswering }, + repaired: repairedAgents, + agents: views.map((v) => ({ + agent: v.agent, + path: v.path, + hooked: v.hooked, + registered: v.registered, + transport: v.transport, + endpoint: v.endpoint, + healthy: v.healthy, + problem: v.problem ?? null, + fix: v.fix ?? null, + recordedBy: v.recorder ? v.recorder.recorder : null, + })), + }, + }; + } + + lines.push(`Self Reports: ${settings.enabled ? "on" : "off"}`); + lines.push( + `Source: ${ + source === "cloud" ? "FailproofAI Cloud" : source === "local" ? "this machine (config.json)" : "the default (no settings file yet)" + }`, + ); + lines.push(`Settings: ${selfReportSettingsFile()}`); + lines.push( + settings.source === "cloud" + ? "Turn off: in the dashboard, Settings > Self Reports" + : settings.enabled + ? "Turn off: `failproofai self-report disable`" + : "Turn on: `failproofai self-report enable`", + ); + if (settings.updatedAt) lines.push(`Updated: ${settings.updatedAt}`); + lines.push(`Categories: ${settings.categories.map((c) => c.name).join(", ")}`); + lines.push(`MCP server: ${SELF_REPORT_SERVER_NAME} (tool \`${SELF_REPORT_TOOL_NAME}\`)`); + if (settings.guidance) lines.push(`Guidance: ${[...settings.guidance].length > 60 ? `${selfReportClip(settings.guidance, 57)}...` : settings.guidance}`); + lines.push(...repairedLines); + lines.push(selfReportDaemonLine(settings.mcp.url, daemonAnswering, deps)); + lines.push(...selfReportRegistrationLines(rows, health, owned, recorders)); + if (settings.enabled) { + for (const v of views) if (!v.healthy && v.problem) lines.push(`▲ ${v.agent}: ${v.problem}${v.fix ? ` · \`${v.fix}\`` : ""}`); + } + // What the last update did to Hermes and OpenClaw gateways: `update` and + // `config` print only a gateway the user must restart, so the routine rows + // are shown here. + const gateways = (deps.gatewayReport ?? (await import("./update-run")).readGatewayReport)(); + if (gateways) { + lines.push(`Gateways: at the last update (${gateways.at})`); + lines.push(...gateways.rows.map((row) => ` ${row}`)); + } + return { exitCode: 0, lines }; +} + +/** + * The daemon's MCP endpoint, for `status`. "not answering" reads as a fault, so + * it is shown only where a daemon is expected: one is configured (setup ran) or + * its socket file is there. With neither, there is no daemon and agents use + * stdio, which is a normal setup. + */ +function selfReportDaemonLine(url: string, answering: boolean, deps: SelfReportCliDeps): string { + if (answering) return `Daemon MCP: ${url} (answering)`; + const expected = deps.daemonExpected ?? (() => isDaemonConfigured() || daemonSocketPresent()); + if (expected()) return `Daemon MCP: ${url} (not answering)`; + return "Daemon MCP: not running (agents use stdio)"; +} + +/** + * Update every hooked agent's MCP entry to match the settings just written, + * and say it in the one line enable and disable print. + */ +async function selfReportSyncLine(deps: SelfReportCliDeps, enabled: boolean): Promise { + const plain = enabled ? "✓ Self Reports: on" : "✓ Self Reports: off"; + if (deps.skipSync) return plain; + try { + const results = await (deps.sync ?? (() => syncSelfReportMcp({ quiet: true })))(); + const line = selfReportSummaryLine(results, enabled ? "on" : "off"); + return (line ?? plain).replace(/ · (failproofai .+)$/, " · `$1`"); + } catch { + return `▲ Self Reports: ${enabled ? "on" : "off"}; agents not updated · \`${SELF_REPORT_SYNC_FIX}\``; + } +} + +function selfReportFlag(args: string[], name: string): { value?: string; error?: string } { + const i = args.indexOf(name); + if (i < 0) return {}; + const v = args[i + 1]; + if (v === undefined || v.startsWith("--")) return { error: `Missing value after ${name}.` }; + return { value: v }; +} + +async function selfReportEnable(args: string[], deps: SelfReportCliDeps): Promise { + const known = new Set(["--categories-file", "--guidance"]); + const unknown = args.find((a, i) => a.startsWith("-") && !known.has(a) && !known.has(args[i - 1])); + if (unknown) return { exitCode: 1, lines: [`Unexpected argument: ${unknown}.`] }; + const stray = args.find((a, i) => !a.startsWith("-") && !known.has(args[i - 1])); + if (stray) return { exitCode: 1, lines: [`Unexpected argument: ${stray}.`] }; + if (await selfReportCloudManaged()) return { exitCode: 1, lines: SELF_REPORT_CLOUD_REFUSAL }; + + const file = selfReportFlag(args, "--categories-file"); + const guid = selfReportFlag(args, "--guidance"); + if (file.error) return { exitCode: 1, lines: [file.error] }; + if (guid.error) return { exitCode: 1, lines: [guid.error] }; + + const previous = await readLocalSelfReportConfig(); + let categories: SelfReportCategory[] | undefined = previous?.categories; + if (file.value) { + let parsed: unknown; + try { + parsed = JSON.parse(readFileSync(file.value, "utf8")); + } catch (err) { + return { exitCode: 1, lines: [`Could not read ${file.value}: ${err instanceof Error ? err.message : String(err)}`] }; + } + // A bare list, or `{ "categories": [...] }` (the shape of the org setting). + const list = parsed && typeof parsed === "object" && !Array.isArray(parsed) ? (parsed as Record).categories : parsed; + const checked = validateSelfReportCategories(list); + if (!checked.ok) return { exitCode: 1, lines: [`${file.value}: ${checked.error}`] }; + categories = checked.value; + } + let guidance: string | undefined = previous?.guidance; + if (guid.value !== undefined) { + const checked = validateSelfReportGuidance(guid.value); + if (!checked.ok) return { exitCode: 1, lines: [checked.error] }; + guidance = checked.value ?? undefined; + } + + await writeLocalSelfReportConfig({ enabled: true, categories, guidance }); + writeEffectiveSelfReport({ enabled: true, categories, guidance }); + return { exitCode: 0, lines: [await selfReportSyncLine(deps, true)] }; +} + +async function selfReportDisable(args: string[], deps: SelfReportCliDeps): Promise { + if (args.length > 0) return { exitCode: 1, lines: [`Unexpected argument: ${args[0]}.`] }; + if (await selfReportCloudManaged()) return { exitCode: 1, lines: SELF_REPORT_CLOUD_REFUSAL }; + const previous = await readLocalSelfReportConfig(); + // The category list and guidance are kept, so turning it back on restores them. + await writeLocalSelfReportConfig({ enabled: false, categories: previous?.categories, guidance: previous?.guidance }); + writeEffectiveSelfReport({ enabled: false, categories: previous?.categories, guidance: previous?.guidance }); + return { exitCode: 0, lines: [await selfReportSyncLine(deps, false)] }; +} + +const SELF_REPORT_TEST_DETAIL = "failproofai self-report test: this is a test report, not a real problem."; + +/** + * Whether a Claude Code or Codex session started in `cwd` would skip + * failproofai's hook, so its report is the server's to record: Codex has not + * trusted the hook (or has none of ours to run), or Claude Code has hooks off. + * A Claude Code without user-scope hooks may still have them in the project, + * so that alone does not count. + */ +function selfReportTestHookSkipped(agent: string, cwd: string, deps: SelfReportCliDeps): boolean { + if (deps.hookState) return deps.hookState(agent).recorder === "server"; + return agent === "codex" ? !codexReportHookRuns(cwd) : claudeHooksBlockedReason(cwd) !== null; +} + +async function selfReportTest(args: string[], deps: SelfReportCliDeps): Promise { + const agentFlag = selfReportFlag(args, "--agent"); + if (agentFlag.error || !agentFlag.value) { + return { exitCode: 1, lines: ["Missing --agent .", `Agents: ${INTEGRATION_TYPES.join(", ")}`] }; + } + const agent = agentFlag.value; + if (!(INTEGRATION_TYPES as readonly string[]).includes(agent)) { + return { exitCode: 1, lines: [`Not an agent: ${agent}.`, `Agents: ${INTEGRATION_TYPES.join(", ")}`] }; + } + const settings = resolveSelfReport(); + if (!settings?.enabled) { + return { exitCode: 1, lines: ["Self Reports is off, so there is nothing to test.", "Turn it on with `failproofai self-report enable`."] }; + } + const category = settings.categories[0]?.name ?? SELF_REPORT_DEFAULT_CATEGORIES[0].name; + const cwd = deps.cwd ?? process.cwd(); + const cli = selfReportCliCommand(deps); + + if ( + SELF_REPORT_SERVER_RECORDS.includes(agent) || + (SELF_REPORT_HOOK_RECORDED_AGENTS.includes(agent) && selfReportTestHookSkipped(agent, cwd, deps)) + ) { + // This agent's hooks do not see MCP calls, or will not run (an untrusted + // Codex): the MCP server records. Drive the stdio server as the agent would. + const dir = customAgentsEventsDir(); + const stdin = [ + { jsonrpc: "2.0", id: 1, method: "initialize", params: { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "failproofai-self-report-test", version: "1" } } }, + { jsonrpc: "2.0", method: "notifications/initialized" }, + { jsonrpc: "2.0", id: 2, method: "tools/call", params: { name: "report", arguments: { category, detail: SELF_REPORT_TEST_DETAIL } } }, + ] + .map((m) => JSON.stringify(m)) + .join("\n"); + const run = await selfReportRunChild([...cli, "mcp", "--agent", agent], `${stdin}\n`, 20_000, cwd, { + [SELF_REPORT_RECEIPT_ENV]: "1", + }); + const answered = run.stdout.includes(SELF_REPORT_RESULT_TEXT); + // The server's receipt names the batch it published. The batch itself may + // already be gone: a running collector uploads and deletes it, often + // before this child has exited, so its absence proves nothing. + const receipt = run.stderr + .split("\n") + .filter((l) => l.startsWith(SELF_REPORT_RECEIPT_PREFIX)) + .map((l) => l.slice(SELF_REPORT_RECEIPT_PREFIX.length).trim()) + .find((p) => dirname(p) === dir && p.endsWith(".jsonl")); + if (!answered || !receipt) { + const diagnostic = run.stderr + .split("\n") + .filter((l) => l.trim() && !l.startsWith(SELF_REPORT_RECEIPT_PREFIX)) + .pop(); + return { + exitCode: 1, + lines: [ + `✕ The test report for ${agent} did not land.`, + ` MCP server ${answered ? "answered Recorded., but recorded nothing" : "did not answer"}${diagnostic ? `: ${diagnostic.trim()}` : ""}`, + ], + }; + } + const stillThere = selfReportListDir(dir).includes(basename(receipt)); + return { + exitCode: 0, + lines: [ + `✓ Test report from ${agent} recorded by the MCP server.`, + stillThere + ? ` Event file: ${receipt}` + : ` Event file: ${receipt} (already picked up by the collector)`, + " The collector uploads it to FailproofAI Cloud when this machine is connected.", + ], + }; + } + + // Hook-recorded agent: send the PreToolUse hook the agent would send, through + // the same `--hook` entry point (and so the daemon, when it is configured). + const sessionId = `failproofai-self-report-test-${Date.now()}`; + const payload = { + session_id: sessionId, + hook_event_name: "PreToolUse", + tool_name: SELF_REPORT_MCP_TOOL_NAME, + tool_input: { category, detail: SELF_REPORT_TEST_DETAIL }, + cwd, + }; + const run = await selfReportRunChild([...cli, "--hook", "PreToolUse", "--cli", agent], JSON.stringify(payload), 30_000, cwd); + const file = join(hookActivityDir(), "current.jsonl"); + let row: Record | undefined; + try { + row = readFileSync(file, "utf8") + .split("\n") + .filter((l) => l.includes(sessionId)) + .map((l) => JSON.parse(l) as Record) + .pop(); + } catch { + row = undefined; + } + if (run.code !== 0 || !row || !row.selfReport || row.decision !== "allow") { + return { + exitCode: 1, + lines: [ + `✕ The test report for ${agent} did not land.`, + ` Hook exit code: ${run.code ?? "none"}${row ? `, decision: ${String(row.decision)}` : ", no activity row"}`, + ...(run.stderr.trim() ? [` ${run.stderr.trim().split("\n").pop()}`] : []), + ], + }; + } + return { + exitCode: 0, + lines: [ + `✓ Test report from ${agent} allowed and recorded by the hook.`, + ` Activity row: ${file} (session ${sessionId})`, + " The collector uploads it to FailproofAI Cloud as a self_report event when this machine is connected.", + ], + }; +} + +function selfReportFileExists(): boolean { + try { + readFileSync(selfReportSettingsFile()); + return true; + } catch (err) { + return (err as NodeJS.ErrnoException)?.code !== "ENOENT"; + } +} + +function selfReportListDir(dir: string): string[] { + try { + return readdirSync(dir); + } catch { + return []; + } +} + +export async function runSelfReportCommand(args: string[], deps: SelfReportCliDeps = {}): Promise { + const [verb, ...rest] = args; + try { + switch (verb) { + case "status": + return await selfReportStatus(rest, deps); + case "enable": + return await selfReportEnable(rest, deps); + case "disable": + return await selfReportDisable(rest, deps); + case "test": + return await selfReportTest(rest, deps); + default: + return { exitCode: 1, lines: [verb ? `Unknown self-report command: ${verb}.` : "Missing self-report command.", "Use status, enable, disable or test."] }; + } + } catch (err) { + return { exitCode: 1, lines: [`✕ ${err instanceof Error ? err.message : String(err)}`] }; + } +} diff --git a/src/hooks/self-report-devin.ts b/src/hooks/self-report-devin.ts new file mode 100644 index 000000000..0e255792c --- /dev/null +++ b/src/hooks/self-report-devin.ts @@ -0,0 +1,119 @@ +/** + * Devin runs Claude Code's hooks as well as its own: it reads the `hooks` in + * `~/.claude/settings.json` too, so one Devin call to `report` reaches the + * hook twice, once as `--cli devin` and once as `--cli claude`. Devin's report + * is written by its MCP server (it is in `SELF_REPORT_SERVER_RECORDS`), while + * the Claude hook is the recorder for Claude Code, so without this check the + * one report is filed twice: as devin and as claude. + * + * `selfReportClaudeHookFromDevin` says whether a `--cli claude` invocation was + * really Devin's, so the Claude path can leave the report to Devin's server. + * Signals, any one of which is enough: + * + * - the nearest agent above this process is a `devin` process (Linux reads + * `/proc`, macOS asks `ps` once; Windows has no check). A `claude` process + * met first wins, so Claude Code started from a Devin shell still records. + * - the payload carries `tool_provenance`, a field of Devin's Claude-hook + * input that Claude Code never sends. + * - no `transcript_path` (Claude Code sends one on every event; Devin keeps + * sessions in SQLite and sends none) together with Devin's `call-` + * tool call id (Claude Code's ids are `toolu_…`). + * + * The process walk has to run in the hook process Devin started, not in the + * daemon's warm worker (whose parent is the daemon). So the one-shot hook CLI + * calls `selfReportMarkDevinOrigin` before it forwards the payload, which + * adds `SELF_REPORT_DEVIN_MARKER` to a Claude-path report call made under + * Devin; the worker then reads the marker. Only a report call on the Claude + * path is looked at, so ordinary hook traffic pays nothing. + */ +import { execFileSync } from "node:child_process"; +import { readFileSync } from "node:fs"; +import { basename } from "node:path"; +import { isSelfReportToolName } from "./self-report-names"; + +/** Every spelling of the report tool's name carries the server name. */ +const SELF_REPORT_SERVER_NAME_FRAGMENT = /failproofai_local/i; + +/** Payload key the hook CLI adds when a Claude-path report call runs under Devin. */ +export const SELF_REPORT_DEVIN_MARKER = "failproofai_via_devin"; +const SELF_REPORT_DEVIN_CALL_ID_RE = /^call-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; +const SELF_REPORT_ANCESTRY_DEPTH = 8; + +/** Names of the processes above this one, nearest first. Best effort: `[]` on any failure. */ +export function selfReportParentProcessNames(depth: number = SELF_REPORT_ANCESTRY_DEPTH): string[] { + const names: string[] = []; + try { + if (process.platform === "linux") { + let pid = process.ppid; + for (let i = 0; i < depth && pid > 1; i++) { + // " () …"; comm may itself hold ") ". + const stat = readFileSync(`/proc/${pid}/stat`, "utf8"); + const close = stat.lastIndexOf(")"); + names.push(stat.slice(stat.indexOf("(") + 1, close)); + pid = Number(stat.slice(close + 2).split(" ")[1]); + } + } else if (process.platform === "darwin") { + const out = execFileSync("ps", ["-A", "-o", "pid=,ppid=,comm="], { encoding: "utf8", timeout: 1000 }); + const table = new Map(); + for (const line of out.split("\n")) { + const m = /^\s*(\d+)\s+(\d+)\s+(.*)$/.exec(line); + if (m) table.set(Number(m[1]), { ppid: Number(m[2]), comm: m[3].trim() }); + } + let pid = process.ppid; + for (let i = 0; i < depth && pid > 1; i++) { + const row = table.get(pid); + if (!row) break; + names.push(basename(row.comm)); + pid = row.ppid; + } + } + } catch { + // Unreadable /proc, no ps: no ancestry signal. + } + return names; +} + +/** Whether the nearest agent process above this one is Devin (a `claude` met first says no). */ +export function selfReportAncestryIsDevin(names: readonly string[]): boolean { + for (const raw of names) { + const name = basename(raw).toLowerCase(); + if (name === "claude") return false; + if (name === "devin") return true; + } + return false; +} + +/** Whether a `--cli claude` hook payload was sent by Devin rather than Claude Code. */ +export function selfReportClaudeHookFromDevin( + parsed: Record, + ancestry: () => readonly string[] = selfReportParentProcessNames, +): boolean { + if (parsed[SELF_REPORT_DEVIN_MARKER] === true || "tool_provenance" in parsed) return true; + const id = parsed.tool_use_id ?? parsed.tool_call_id; + if (typeof parsed.transcript_path !== "string" && typeof id === "string" && SELF_REPORT_DEVIN_CALL_ID_RE.test(id)) { + return true; + } + return selfReportAncestryIsDevin(ancestry()); +} + +/** + * In the hook process: return `stdin` with `SELF_REPORT_DEVIN_MARKER` set when + * this is a `--cli claude` report call and Devin is the agent above us, else + * `stdin` unchanged. Never throws. + */ +export function selfReportMarkDevinOrigin( + cli: string, + stdin: string, + ancestry: () => readonly string[] = selfReportParentProcessNames, +): string { + if (cli !== "claude" || !SELF_REPORT_SERVER_NAME_FRAGMENT.test(stdin)) return stdin; + try { + const parsed = JSON.parse(stdin) as unknown; + if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return stdin; + const rec = parsed as Record; + if (!isSelfReportToolName(rec.tool_name, "claude") || !selfReportAncestryIsDevin(ancestry())) return stdin; + return JSON.stringify({ ...rec, [SELF_REPORT_DEVIN_MARKER]: true }); + } catch { + return stdin; + } +} diff --git a/src/hooks/self-report-hint.ts b/src/hooks/self-report-hint.ts new file mode 100644 index 000000000..2429bcd16 --- /dev/null +++ b/src/hooks/self-report-hint.ts @@ -0,0 +1,418 @@ +/** + * Self Reports: one just-in-time hint when a tool call clearly failed. + * + * A built-in behaviour of Self Reports, not a policy: nobody toggles it, it + * never blocks or rewrites a decision, and it runs only after every policy + * allowed the PostToolUse event with nothing to say. When the call FAILED + * (`selfReportToolFailed`), the model gets one short line through the + * harness's own after-a-tool context channel: + * + * If this blocks you and you can't fix it, call failproofai_local's `report` tool once. + * + * At most once per session (a marker under `$FAILPROOFAI_HOME/cache`), only + * while Self Reports is on, never for the report call itself, and never for a + * failure a failproofai deny caused: those are already recorded as blocks. + * + * Only a failure that clearly blocks (`selfReportFailureBlocks`) earns it: an + * auth or credential error (a 401 or 403, unauthorized, an invalid or expired + * key or token, a `*_TOKEN` that is not set), or the same tool or command + * failing a second time in the session. One non-zero exit is ordinary work, and + * read-only exploration (`ls`, `cat`, `grep`, `find`, `test`, Read, Glob...) + * failing, however often, is how an agent finds out what is there. + * + * Where a hint can reach the model (`SELF_REPORT_HINT_CHANNELS`): + * + * | Agent | Event | Channel | + * |----------|-----------------------|---------| + * | claude | PostToolUse, PostToolUseFailure | `hookSpecificOutput.additionalContext` | + * | codex | PostToolUse | `hookSpecificOutput.additionalContext` | + * | cursor | PostToolUse | `{additional_context}` (postToolUse reads only that) | + * | copilot | PostToolUseFailure | `{additionalContext}` (postToolUse reads only a block) | + * | factory | PostToolUse | exit 2 + stderr: droid adds it as an llm-only system message | + * + * None elsewhere: OpenCode's only route is a queued follow-up prompt, Pi, + * Hermes and OpenClaw observe tool results only (through our hooks), Devin's + * PostToolUse answer never reached the transcript in probes, and Antigravity + * and Goose discard it (src/hooks/enforcement-capability.ts). + */ +import { closeSync, lstatSync, mkdirSync, openSync, readdirSync, readFileSync, statSync, unlinkSync, utimesSync, writeFileSync } from "node:fs"; +import { createHash } from "node:crypto"; +import { join } from "node:path"; +import { failproofaiHome } from "./fp-home"; +import { getHookActivityEntriesSince } from "./hook-activity-store"; +import { readEnabledSelfReport, selfReportInstructions } from "./self-report"; +import { isAnySelfReportToolName, SELF_REPORT_SERVER_NAME, selfReportAntigravityWrappedArgs } from "./self-report-names"; +import type { IntegrationType } from "./types"; + +export const SELF_REPORT_FAILURE_HINT = `If this blocks you and you can't fix it, call ${SELF_REPORT_SERVER_NAME}'s \`report\` tool once.`; + +/** Agents and events whose answer can carry the hint, by how. */ +export const SELF_REPORT_HINT_CHANNELS: Partial>>> = { + claude: { PostToolUse: "hookSpecificOutput", PostToolUseFailure: "hookSpecificOutput" }, + codex: { PostToolUse: "hookSpecificOutput" }, + cursor: { PostToolUse: "cursor" }, + copilot: { PostToolUseFailure: "flat" }, + factory: { PostToolUse: "exit2" }, +}; + +const TEXT_LIMIT = 4000; +const SHORT_RESULT = 600; + +/** The text of a value, bounded. */ +function textOf(v: unknown): string { + if (typeof v === "string") return v.slice(0, TEXT_LIMIT); + if (v === undefined || v === null) return ""; + try { + return JSON.stringify(v).slice(0, TEXT_LIMIT); + } catch { + return ""; + } +} + +const FAILURE_TEXT: RegExp[] = [ + /\b(?:HTTP\/\d(?:\.\d)?\s+|status(?:\s*code)?[:=\s]+|error[:\s]+)40[13]\b/i, + /\b40[13]\s+(?:unauthori[sz]ed|forbidden)\b/i, + /\bunauthori[sz]ed\b|\bforbidden\b/i, + /\bpermission denied\b|\bEACCES\b|\bEPERM\b/i, + /\bnot found\b|\bENOENT\b|\bno such file or directory\b/i, + /\bexit(?:ed)?(?: with)? (?:code|status)[:\s]+[1-9]\d*\b/i, +]; + +function textLooksFailed(text: string): boolean { + return text !== "" && FAILURE_TEXT.some((re) => re.test(text)); +} + +function nonZeroExit(v: unknown): boolean { + return typeof v === "number" && Number.isFinite(v) && v !== 0; +} + +/** + * Whether a PostToolUse (or PostToolUseFailure) payload is a call that clearly + * FAILED: the failure event itself, an explicit error or error flag (an MCP + * `isError`), a non-zero exit code, or, in the error-ish text only (stderr, an + * error message, or a short result), a 401/403, `not found`, `permission + * denied` or a non-zero exit status. A long successful result that happens to + * contain such words (a file being read) is never judged by its text. + */ +export function selfReportToolFailed(eventType: string, payload: Record): boolean { + if (eventType === "PostToolUseFailure") return true; + if (eventType !== "PostToolUse") return false; + if (typeof payload.error === "string" && payload.error.trim() !== "") return true; + if (payload.is_error === true || payload.isError === true) return true; + const response = payload.tool_response ?? payload.tool_output ?? payload.toolResult ?? payload.tool_result ?? payload.result; + if (response && typeof response === "object" && !Array.isArray(response)) { + const r = response as Record; + if (r.isError === true || r.is_error === true || r.success === false) return true; + for (const k of ["exit_code", "exitCode", "returncode", "returnCode", "status_code"]) { + if (k === "status_code" ? typeof r[k] === "number" && (r[k] as number) >= 400 : nonZeroExit(r[k])) return true; + } + if (typeof r.error === "string" && r.error.trim() !== "") return true; + if (r.error && typeof r.error === "object") return true; + if (textLooksFailed(textOf(r.stderr))) return true; + for (const k of ["output", "content", "text", "message", "result"]) { + const t = textOf(r[k]); + if (t.length <= SHORT_RESULT && textLooksFailed(t)) return true; + } + return false; + } + const t = textOf(response); + return t.length <= SHORT_RESULT && textLooksFailed(t); +} + +/** The error-ish text of a call: its error fields, stderr, and a short result. */ +function errorTextOf(payload: Record): string { + const parts: string[] = [textOf(payload.error)]; + const response = payload.tool_response ?? payload.tool_output ?? payload.toolResult ?? payload.tool_result ?? payload.result; + if (response && typeof response === "object" && !Array.isArray(response)) { + const r = response as Record; + parts.push(textOf(r.error), textOf(r.stderr)); + for (const k of ["output", "content", "text", "message", "result", "stdout"]) { + const t = textOf(r[k]); + if (t.length <= SHORT_RESULT) parts.push(t); + } + } else { + const t = textOf(response); + if (t.length <= SHORT_RESULT) parts.push(t); + } + return parts.filter((p) => p !== "").join("\n"); +} + +const AUTH_TEXT: RegExp[] = [ + /\b(?:HTTP\/\d(?:\.\d)?\s+|status(?:\s*code)?[:=\s]+|error[:\s]+)40[13]\b/i, + /\b40[13]\s+(?:unauthori[sz]ed|forbidden)\b/i, + /\bunauthori[sz]ed\b|\bforbidden\b|\bunauthenticated\b/i, + /\bauthentication (?:failed|required|error)\b|\bnot authenticated\b|\bnot logged in\b|\blogin required\b/i, + /\b(?:invalid|expired|revoked|missing|bad|incorrect)\s+(?:api[\s_-]?key|access[\s_-]?key|token|credentials?|password|secret)\b/i, + /\b(?:api[\s_-]?key|token|credentials?)\s+(?:is\s+)?(?:invalid|expired|revoked|missing|required|not (?:set|found|provided|valid))\b/i, + /\b[A-Z][A-Z0-9_]*(?:TOKEN|API_KEY|_KEY|SECRET|PASSWORD|CREDENTIALS?)\b[^\n]{0,40}\b(?:not set|unset|missing|required|is empty|undefined)\b/, +]; + +/** An auth or credential failure: the agent cannot fix it by trying again. */ +function authFailure(payload: Record): boolean { + const text = errorTextOf(payload); + return text !== "" && AUTH_TEXT.some((re) => re.test(text)); +} + +/** Tools that only look: a failure of one is finding out, not being blocked. */ +const SELF_REPORT_READ_ONLY_TOOLS = new Set([ + "read", "glob", "grep", "ls", "notebookread", "view", "read_file", "list_dir", "list_directory", "search_files", + "find_files", "file_search", "codebase_search", "tree", +]); +/** Programs that only look, as the first word of a shell command segment. */ +const SELF_REPORT_READ_ONLY_PROGRAMS = new Set([ + "ls", "cat", "head", "tail", "less", "more", "grep", "egrep", "fgrep", "rg", "ag", "find", "fd", "test", "[", "[[", + "stat", "file", "which", "whereis", "type", "command", "wc", "tree", "pwd", "echo", "printf", "readlink", "realpath", + "du", "df", "env", "printenv", "id", "whoami", "uname", "date", "true", "false", "jq", "sort", "uniq", "cut", "diff", + "basename", "dirname", +]); +const SELF_REPORT_READ_ONLY_GIT = new Set(["status", "log", "diff", "show", "branch", "ls-files", "rev-parse", "remote", "blame", "grep"]); + +function commandOf(payload: Record): string { + const input = payload.tool_input; + if (!input || typeof input !== "object" || Array.isArray(input)) return ""; + const rec = input as Record; + const c = rec.command ?? rec.cmd; + if (typeof c === "string") return c.trim(); + if (Array.isArray(c)) return c.filter((x) => typeof x === "string").join(" ").trim(); + return ""; +} + +/** The program each segment of a shell command runs (env assignments, `sudo`, `bash -lc` skipped). */ +function programsOf(command: string): string[] { + let cmd = command; + // `bash -lc '...'` / `sh -c "..."`: look at the inner command (Codex wraps this way). + const wrapped = /^(?:\S*\/)?(?:ba|z|da)?sh\s+-l?c\s+(['"])([\s\S]*)\1\s*$/.exec(cmd); + if (wrapped) cmd = wrapped[2]; + return cmd + .split(/&&|\|\||[;|\n]/) + .map((seg) => seg.trim().split(/\s+/).filter((w) => w !== "")) + .filter((words) => words.length > 0) + .map((words) => { + let i = 0; + while (i < words.length && (/^[A-Za-z_][A-Za-z0-9_]*=/.test(words[i]) || words[i] === "sudo" || words[i] === "time" || words[i] === "!")) i++; + const prog = (words[i] ?? "").replace(/^.*\//, ""); + return prog === "git" ? `git ${words[i + 1] ?? ""}` : prog; + }); +} + +/** A call that only looks: a read-only tool, or a shell command whose every segment only looks. */ +export function selfReportReadOnlyCall(payload: Record): boolean { + const tool = typeof payload.tool_name === "string" ? payload.tool_name.toLowerCase() : ""; + if (SELF_REPORT_READ_ONLY_TOOLS.has(tool)) return true; + const command = commandOf(payload); + if (command === "") return false; + const programs = programsOf(command); + return ( + programs.length > 0 && + programs.every((p) => (p.startsWith("git ") ? SELF_REPORT_READ_ONLY_GIT.has(p.slice(4)) : SELF_REPORT_READ_ONLY_PROGRAMS.has(p))) + ); +} + +/** What "the same tool or command" means: the tool, and for a shell call the programs it ran. */ +function failureKey(payload: Record): string { + const tool = typeof payload.tool_name === "string" ? payload.tool_name : ""; + const command = commandOf(payload); + const programs = command === "" ? [] : programsOf(command); + return programs.length > 0 ? `${tool}\0${programs.join(" ")}` : tool; +} + +function hintDir(): string { + return join(failproofaiHome(), "cache", "self-report-hints"); +} + +/** A hint file untouched this long belongs to a session that is over. */ +const HINT_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000; +/** The directory is scanned at most this often, across hook processes. */ +const HINT_PRUNE_EVERY_MS = 60 * 60 * 1000; +/** Its mtime is when the directory was last scanned. */ +const HINT_PRUNE_STAMP = ".pruned"; +/** When this process last looked at the stamp: one hook process scans once. */ +let hintPrunedAt = 0; + +/** Tests: forget this process's last scan, as a new hook process would. */ +export function _resetSelfReportHintPruneForTest(): void { + hintPrunedAt = 0; +} + +/** + * Remove hint files older than 7 days (each session leaves one or two). + * Called only after a write, so a machine with no failures never scans; and + * at most once an hour, kept in a stamp file because each hook is its own + * short-lived process. Best effort: anything that fails is left as it is. + */ +function pruneHintDir(now: number = Date.now()): void { + if (now - hintPrunedAt < HINT_PRUNE_EVERY_MS) return; + hintPrunedAt = now; + const dir = hintDir(); + const stamp = join(dir, HINT_PRUNE_STAMP); + try { + if (now - statSync(stamp).mtimeMs < HINT_PRUNE_EVERY_MS) return; + } catch { + // no stamp yet: scan + } + try { + writeFileSync(stamp, "", { mode: 0o600 }); + utimesSync(stamp, now / 1000, now / 1000); + for (const name of readdirSync(dir)) { + if (name === HINT_PRUNE_STAMP) continue; + const path = join(dir, name); + try { + const st = lstatSync(path); + if (st.isFile() && now - st.mtimeMs > HINT_MAX_AGE_MS) unlinkSync(path); + } catch { + // gone already, or not ours to remove + } + } + } catch { + // unreadable directory: try again in another process + } +} + +function sessionDigest(cli: string, sessionId: string): string { + return createHash("sha256").update(`${cli}\0${sessionId}`).digest("hex").slice(0, 32); +} + +/** + * Note this failure for the session; true when the same tool or command had + * already failed in it (the second failure). Best effort: an unreadable file + * counts nothing. + */ +function failedBefore(cli: string, sessionId: string, key: string): boolean { + const file = join(hintDir(), `${sessionDigest(cli, sessionId)}.failures`); + const digest = createHash("sha256").update(key).digest("hex").slice(0, 16); + let seen: string[] = []; + try { + seen = readFileSync(file, "utf8").split("\n").filter((l) => l !== ""); + } catch { + seen = []; + } + if (seen.includes(digest)) return true; + try { + mkdirSync(hintDir(), { recursive: true, mode: 0o700 }); + writeFileSync(file, `${[...seen.slice(-49), digest].join("\n")}\n`, { mode: 0o600 }); + pruneHintDir(); + } catch { + // no record: the next failure counts as a first one again + } + return false; +} + +/** + * Whether a failed call clearly blocks the agent: an auth or credential error, + * or (for anything but read-only exploration) the same tool or command failing + * a second time this session. Records the failure for that count. + */ +export function selfReportFailureBlocks(cli: string, sessionId: string, payload: Record): boolean { + if (authFailure(payload)) return true; + if (selfReportReadOnlyCall(payload)) return false; + return failedBefore(cli, sessionId, failureKey(payload)); +} + +/** The call's text mentions a failproofai block (a deny's own message). */ +function blockedByFailproofai(payload: Record): boolean { + const t = textOf(payload.tool_response ?? payload.error ?? payload.tool_output ?? payload.toolResult ?? ""); + return /\b(?:blocked|denied) by failproofai\b|\bfailproofai\b.*\b(?:blocked|denied)\b|FailproofAI could not check this call/i.test(t); +} + +/** A PreToolUse deny for this very call (same session and tool call id) in the last 10 minutes. */ +function deniedEarlier(sessionId: string, toolCallId: string | undefined, now: number): boolean { + if (!toolCallId) return false; + try { + return (getHookActivityEntriesSince(now - 10 * 60 * 1000) as unknown as Array>).some( + (row) => row.sessionId === sessionId && row.toolCallId === toolCallId && row.decision === "deny", + ); + } catch { + return false; + } +} + +/** Claim the per-session marker: true only for the first claim of this session. */ +function claimOnce(cli: string, sessionId: string): boolean { + const dir = hintDir(); + try { + mkdirSync(dir, { recursive: true, mode: 0o700 }); + closeSync(openSync(join(dir, sessionDigest(cli, sessionId)), "wx", 0o600)); + pruneHintDir(); + return true; + } catch { + return false; + } +} + +export interface SelfReportHintInput { + cli: IntegrationType; + /** Canonical event: PostToolUse or PostToolUseFailure. */ + eventType: string; + payload: Record; + sessionId: string | undefined; + toolCallId?: string; + now?: number; + /** Test seam: whether Self Reports is on (default: the settings readers). */ + enabled?: () => boolean; +} + +/** + * The answer that carries the hint, or null to answer as usual. Consumes the + * session's one hint when it returns one. + */ +export function selfReportFailureHint(input: SelfReportHintInput): { exitCode: number; stdout: string; stderr: string } | null { + const channel = SELF_REPORT_HINT_CHANNELS[input.cli]?.[input.eventType]; + if (!channel || !input.sessionId) return null; + const { payload } = input; + const tool = payload.tool_name; + if (isAnySelfReportToolName(tool) || selfReportAntigravityWrappedArgs(tool, payload.tool_input)) return null; + if (typeof tool === "string" && /(^|[^a-z])report$/i.test(tool) && String(payload.mcp_server_name ?? "").toLowerCase() === SELF_REPORT_SERVER_NAME) return null; + if (!selfReportToolFailed(input.eventType, payload)) return null; + if (blockedByFailproofai(payload)) return null; + const now = input.now ?? Date.now(); + if (deniedEarlier(input.sessionId, input.toolCallId, now)) return null; + if (!(input.enabled ?? (() => readEnabledSelfReport() !== null))()) return null; + if (!selfReportFailureBlocks(input.cli, input.sessionId, payload)) return null; + if (!claimOnce(input.cli, input.sessionId)) return null; + switch (channel) { + case "hookSpecificOutput": + return { + exitCode: 0, + stdout: JSON.stringify({ hookSpecificOutput: { hookEventName: input.eventType, additionalContext: SELF_REPORT_FAILURE_HINT } }), + stderr: "", + }; + case "cursor": + return { exitCode: 0, stdout: JSON.stringify({ additional_context: SELF_REPORT_FAILURE_HINT }), stderr: "" }; + case "flat": + return { exitCode: 0, stdout: JSON.stringify({ additionalContext: SELF_REPORT_FAILURE_HINT }), stderr: "" }; + case "exit2": + return { exitCode: 2, stdout: "", stderr: SELF_REPORT_FAILURE_HINT }; + } +} + +/** + * Agents whose MCP tools are deferred with no setting to keep ours direct, and + * whose SessionStart answer reaches the model: the server's instructions go + * there, so the model knows the tool exists before it needs it. Factory droid + * defers every MCP server's tools whose name does not contain `github` or + * `agentbrowser` (droid 0.17x, `McpToolSearch` on by default) and reads a + * SessionStart `additionalContext` (applySessionStartHookResults). + */ +export const SELF_REPORT_SESSION_START_CONTEXT_AGENTS: readonly IntegrationType[] = ["factory"]; + +/** The SessionStart answer that carries the instructions, or null. */ +export function selfReportSessionStartContext( + cli: IntegrationType, + eventType: string, + settings: ReturnType | undefined = undefined, +): { exitCode: number; stdout: string; stderr: string } | null { + if (eventType !== "SessionStart" || !SELF_REPORT_SESSION_START_CONTEXT_AGENTS.includes(cli)) return null; + const s = settings === undefined ? readEnabledSelfReport() : settings; + if (!s) return null; + return { + exitCode: 0, + stdout: JSON.stringify({ + hookSpecificOutput: { + hookEventName: "SessionStart", + // The instructions name the server themselves, so they read the same here. + additionalContext: selfReportInstructions(s.categories, s.guidance), + }, + }), + stderr: "", + }; +} diff --git a/src/hooks/self-report-hook-trust.ts b/src/hooks/self-report-hook-trust.ts new file mode 100644 index 000000000..7ba635191 --- /dev/null +++ b/src/hooks/self-report-hook-trust.ts @@ -0,0 +1,312 @@ +/** + * Self Reports for the agents whose HOOK records the report (Claude Code and + * Codex, contract §8): will that hook actually run? + * + * Both can skip failproofai's hooks while still loading its MCP server: + * + * - Codex ≥0.129 runs a `hooks.json` hook only once a person trusted it at its + * current hash (`codexHookTrust`). An untrusted hook never runs, so a report + * would be lost. Hooks in Codex's system config run without trust. + * - Claude Code runs no hooks with `disableAllHooks: true`, and only managed + * ones with a managed `allowManagedHooksOnly: true`. + * + * Two uses, and only the second decides whether a report is recorded: + * + * - `self-report sync` registers such an agent on the daemon's HTTP endpoint + * (which records nothing for it) only when its user-scope hook will run, and + * over stdio otherwise. `status` shows the state and how to fix it. + * - The stdio server records a Claude Code or Codex report itself unless the + * hook already did (`selfReportHookRecordedRecently`). The agent runs its + * PreToolUse hook before it sends the MCP call, so the hook's row is on disk + * first. Asking what happened, rather than predicting it from trust state, + * is what keeps a report from being lost or counted twice when the + * prediction is wrong (a Codex whose hash scheme changed, say) or the state + * changes while the agent runs (a person trusts the hooks mid-session). + */ +import { closeSync, existsSync, mkdirSync, openSync, readdirSync, readFileSync, realpathSync, rmSync, statSync } from "node:fs"; +import { createHash } from "node:crypto"; +import { dirname, join, resolve } from "node:path"; +import { + CODEX_UNTRUSTED_NOTICE, + codexGatesHookTrust, + codexHome, + codexSystemHooksPresent, + detectCodexVersion, + failproofaiCodexHookIdentities, + parseCodexTrustedHashes, +} from "./codex-system-hooks"; +import { claudeConfigDir, getIntegration } from "./integrations"; +import { getHookActivityEntriesSince } from "./hook-activity-store"; +import { readEnabledSelfReport, resolveSelfReportCategory, selfReportArgs } from "./self-report"; +import { selfReportClip, selfReportCutDetail } from "./self-report-names"; +import { selfReportRowAgentPid, selfReportServerAgentPid } from "./self-report-ancestry"; +import { failproofaiHome } from "./fp-home"; + +/** The agents whose hook, when it runs, is the recorder. */ +export const SELF_REPORT_HOOK_RECORDED_AGENTS: readonly string[] = ["claude", "codex"]; + +export type SelfReportHookState = + | { recorder: "hook" } + | { recorder: "server"; reason: string; fix: string }; + +export interface SelfReportHookTrustDeps { + /** Codex: the trust check (default `codexHookTrust`'s pieces, at user scope). */ + codexVersion?: () => string | null; + codexSystemPresent?: () => boolean; + /** Claude Code: managed settings file (default per platform). */ + claudeManagedSettingsPath?: string | null; + /** Hooks installed at user scope (default: the integration's own check). */ + userHooksInstalled?: (agent: string) => boolean; +} + +// ── Codex ─────────────────────────────────────────────────────────────────── + +/** `.codex/hooks.json` files a Codex started in `cwd` reads: the user's, then the project's up the tree. */ +function codexHooksFiles(cwd: string | undefined): string[] { + const files = [resolve(codexHome(), "hooks.json")]; + if (cwd) { + let dir = resolve(cwd); + for (;;) { + const candidate = resolve(dir, ".codex", "hooks.json"); + if (!files.includes(candidate)) files.push(candidate); + const up = dirname(dir); + if (up === dir) break; + dir = up; + } + } + return files; +} + +/** + * Whether Codex will run failproofai's PreToolUse hook (the one that records a + * report): it is in Codex's system config, or in a hooks.json Codex reads and + * either trusted at its current hash or on a Codex too old to ask. + */ +export function codexReportHookRuns(cwd?: string, deps: SelfReportHookTrustDeps = {}): boolean { + try { + if ((deps.codexSystemPresent ?? codexSystemHooksPresent)()) return true; + } catch { + // unreadable system config: fall through to hooks.json + } + let trusted: Map | undefined; + let version: string | null | undefined; + for (const file of codexHooksFiles(cwd)) { + const pre = failproofaiCodexHookIdentities(file).filter((h) => h.key.includes(":pre_tool_use:")); + if (pre.length === 0) continue; + if (version === undefined) version = (deps.codexVersion ?? detectCodexVersion)(); + if (!codexGatesHookTrust(version)) return true; + if (!trusted) { + try { + trusted = parseCodexTrustedHashes(readFileSync(resolve(codexHome(), "config.toml"), "utf8")); + } catch { + trusted = new Map(); + } + } + if (pre.some((h) => trusted!.get(h.key) === h.hash)) return true; + } + return false; +} + +// ── Claude Code ───────────────────────────────────────────────────────────── + +function claudeManagedSettingsPath(): string | null { + const override = process.env.FAILPROOFAI_CLAUDE_MANAGED_SETTINGS; + if (override !== undefined) return override.trim() === "" || override === "off" ? null : override; + if (process.platform === "darwin") return "/Library/Application Support/ClaudeCode/managed-settings.json"; + if (process.platform === "linux") return "/etc/claude-code/managed-settings.json"; + return null; +} + +function readJsonObject(path: string | null): Record | null { + if (!path || !existsSync(path)) return null; + try { + const v: unknown = JSON.parse(readFileSync(path, "utf8")); + return v && typeof v === "object" && !Array.isArray(v) ? (v as Record) : null; + } catch { + return null; + } +} + +/** + * Why Claude Code will not run failproofai's user or project hooks, or null + * when nothing stops them. `disableAllHooks` is read with Claude Code's + * precedence (managed, then local, then project, then user: the first layer + * that sets it wins); a managed `allowManagedHooksOnly` stops every hook that + * is not managed, which failproofai's never are. + */ +export function claudeHooksBlockedReason(cwd?: string, deps: SelfReportHookTrustDeps = {}): string | null { + const managed = readJsonObject(deps.claudeManagedSettingsPath !== undefined ? deps.claudeManagedSettingsPath : claudeManagedSettingsPath()); + if (managed?.allowManagedHooksOnly === true) return "managed settings allow only managed hooks (allowManagedHooksOnly)"; + const layers: Array<[string, Record | null]> = [ + ["managed settings", managed], + ...(cwd + ? ([ + [".claude/settings.local.json", readJsonObject(resolve(cwd, ".claude", "settings.local.json"))], + [".claude/settings.json", readJsonObject(resolve(cwd, ".claude", "settings.json"))], + ] as Array<[string, Record | null]>) + : []), + [`${claudeConfigDir()}/settings.json`, readJsonObject(resolve(claudeConfigDir(), "settings.json"))], + ]; + for (const [label, layer] of layers) { + const v = layer?.disableAllHooks; + if (typeof v === "boolean") return v ? `disableAllHooks is set in ${label}` : null; + } + return null; +} + +// ── Both ──────────────────────────────────────────────────────────────────── + +function defaultUserHooksInstalled(agent: string): boolean { + try { + return getIntegration(agent as Parameters[0]).hooksInstalledInSettings("user"); + } catch { + return false; + } +} + +/** + * Who records a report from `agent` registered at user scope: its hook, or (for + * Claude Code and Codex when their user-scope hook will not run) the MCP + * server. Every other agent is recorded by the server and is not asked here. + */ +export function selfReportHookState(agent: string, deps: SelfReportHookTrustDeps = {}): SelfReportHookState { + if (!SELF_REPORT_HOOK_RECORDED_AGENTS.includes(agent)) return { recorder: "hook" }; + const installed = (deps.userHooksInstalled ?? defaultUserHooksInstalled)(agent); + if (agent === "codex") { + if (codexReportHookRuns(undefined, deps)) return { recorder: "hook" }; + return installed + ? { recorder: "server", reason: "Codex has not trusted failproofai's hooks, so it does not run them", fix: CODEX_UNTRUSTED_NOTICE.replace(/\n/g, " ") } + : { recorder: "server", reason: "failproofai's Codex hooks are not installed at user scope", fix: "Run `failproofai policies --install --cli codex`." }; + } + const blocked = claudeHooksBlockedReason(undefined, deps); + if (blocked) { + return { recorder: "server", reason: `Claude Code runs no failproofai hooks: ${blocked}`, fix: "Remove that setting to let failproofai's hooks run." }; + } + if (!installed) { + return { recorder: "server", reason: "failproofai's Claude Code hooks are not installed at user scope", fix: "Run `failproofai policies --install --cli claude`." }; + } + return { recorder: "hook" }; +} + +/** How long after its hook row a report can still be the same call. */ +export const SELF_REPORT_HOOK_DEDUPE_MS = 2 * 60 * 1000; + +/** + * Whether `agent`'s hook already recorded THIS call, and if so claim that + * record so it vouches for one call only (review 4722003644). + * + * A hook row matches when it is a PreToolUse row from that integration, + * written in the last two minutes, in the same working directory as this + * server (`cwd`; a row or a server without one never matches), recorded by a + * hook running under this server's own agent process (the row's `agentPid` + * is exactly this server's agent, `selfReportServerAgentPid`; not merely an + * ancestor, and a row without one never matches), carrying a `selfReport` + * with the same category (as + * sent, or as resolved against the list) and detail as the hook would have + * clipped them. Matching on the report's text alone suppressed distinct calls: + * a report the hook recorded in project A made an identical report in project + * B answer `Recorded.` with no event; and matching on text and directory + * alone let a session whose hooks did not run take the row another session's + * hook wrote in the same directory (F14). Each agent process is one session's + * (or one process's sessions'), so another session's row never matches. + * + * Each row is consumed by the first call it matches: a receipt named after the + * row (its integration, session, tool call id and timestamp) is created with + * O_EXCL under `$FAILPROOFAI_HOME/cache/self-report-receipts/`, and a row whose + * receipt exists already vouched for another call. So two sessions in one + * directory sending the same text each need their own hook row, and a second + * identical call in one session is recorded unless its own hook row is there. + * + * An unreadable activity store reads as "no", and so does a receipt that + * cannot be written for any reason but "already there": a report is recorded + * rather than lost. + */ +export function selfReportHookRecordedRecently( + agent: string, + args: unknown, + now: number = Date.now(), + cwd?: string, + agentPid: number | undefined = selfReportServerAgentPid(), +): boolean { + if (!cwd || agentPid === undefined || !Number.isSafeInteger(agentPid) || agentPid <= 1) return false; + const { category, detail } = selfReportArgs(args ?? {}); + const want = { category: selfReportClip(category), detail: selfReportCutDetail(detail) }; + // The hook row holds the category as it was resolved against the list + // (resolveSelfReportCategory), so a call whose category was missing or + // misspelt matches it by that name; the name as sent still matches too. + const names = (readEnabledSelfReport()?.categories ?? []).map((c) => c.name); + const resolved = resolveSelfReportCategory(want.category, want.detail, names).category; + const here = sameDir(cwd); + let rows: Array>; + try { + rows = getHookActivityEntriesSince(now - SELF_REPORT_HOOK_DEDUPE_MS) as unknown as Array>; + } catch { + return false; + } + const candidates = rows.filter((row) => { + if (row.integration !== agent || row.eventType !== "PreToolUse") return false; + const ts = typeof row.timestamp === "number" ? row.timestamp : NaN; + if (!Number.isFinite(ts) || now - ts > SELF_REPORT_HOOK_DEDUPE_MS || ts - now > 60_000) return false; + if (typeof row.cwd !== "string" || !row.cwd || sameDir(row.cwd) !== here) return false; + // Either stamp: a worker of the previous build (still running until the + // daemon restarts after an upgrade) writes `selfReportAgentPids`. + if (selfReportRowAgentPid(row) !== agentPid) return false; + const sr = row.selfReport as { category?: unknown; detail?: unknown } | undefined; + return !!sr && (sr.category === want.category || sr.category === resolved) && sr.detail === want.detail; + }); + // Oldest first, so concurrent calls claim rows in the order the hooks ran. + candidates.sort((x, y) => (x.timestamp as number) - (y.timestamp as number)); + for (const row of candidates) { + const claimed = claimHookRow(row, now); + if (claimed === "claimed") return true; + if (claimed === "error") return false; + } + return false; +} + +/** A directory as the filesystem names it (symlinks resolved when it exists). */ +function sameDir(dir: string): string { + try { + return realpathSync(dir); + } catch { + return resolve(dir); + } +} + +/** `$FAILPROOFAI_HOME/cache/self-report-receipts`. */ +export function selfReportReceiptDir(): string { + return join(failproofaiHome(), "cache", "self-report-receipts"); +} + +/** Claim one hook row for one call: `taken` when another call already did. */ +function claimHookRow(row: Record, now: number): "claimed" | "taken" | "error" { + const dir = selfReportReceiptDir(); + const id = createHash("sha256") + .update(JSON.stringify([row.integration, row.sessionId ?? null, row.toolCallId ?? null, row.timestamp, row.cwd])) + .digest("hex") + .slice(0, 32); + try { + mkdirSync(dir, { recursive: true, mode: 0o700 }); + pruneReceipts(dir, now); + closeSync(openSync(join(dir, id), "wx", 0o600)); + return "claimed"; + } catch (err) { + return (err as NodeJS.ErrnoException)?.code === "EEXIST" ? "taken" : "error"; + } +} + +/** Receipts older than the window can match no row any more. */ +function pruneReceipts(dir: string, now: number): void { + try { + for (const name of readdirSync(dir)) { + try { + const path = join(dir, name); + if (now - statSync(path).mtimeMs > 2 * SELF_REPORT_HOOK_DEDUPE_MS) rmSync(path, { force: true }); + } catch { + // raced with another server's prune + } + } + } catch { + // nothing to prune + } +} diff --git a/src/hooks/self-report-install.ts b/src/hooks/self-report-install.ts new file mode 100644 index 000000000..5710a37bb --- /dev/null +++ b/src/hooks/self-report-install.ts @@ -0,0 +1,1883 @@ +/** + * Self Reports: register failproofai's `report` MCP server in every agent that + * has failproofai hooks, and take it out again. + * + * The server is named `failproofai_local` everywhere (CONTRACT §1), so it + * never clashes with the FailproofAI Cloud gateway MCP server, which users + * register as `failproofai`; the two coexist. Which transport + * an agent gets depends on who records its reports (CONTRACT §7, §8): + * + * - Every agent gets `failproofai mcp --agent ` over stdio. Hook-recorded + * agents (claude, codex: not in `SELF_REPORT_SERVER_RECORDS`) used to be + * served by the daemon over Streamable HTTP while their user-scope hook would + * record, but a project can turn the hooks off (Claude Code + * `disableAllHooks`) under a user-wide entry, and that endpoint records + * nothing for them. Over stdio the server records what the hook did not + * (`selfReportHookRecordedRecently`). The HTTP path is kept behind + * `SELF_REPORT_HTTP_AGENTS` (empty) and an HTTP entry is moved to stdio. + * - Server-recorded agents always got stdio: the server records their report + * itself and must pick the session; one user-scope HTTP entry serves every + * project and carries only `?agent=`, so over HTTP it could not tell which + * project called, while a stdio server knows its real cwd. + * - Pi, Hermes and OpenClaw get no MCP entry: failproofai's own extension or + * plugin registers the tool (see "Visibility" below). + * + * ## Where each agent keeps user-scope MCP servers (checked 2026-11-25) + * + * Sources are each agent's current official docs (and source where the docs + * are silent). "Hook sees MCP" is whether the hook failproofai installs fires + * for an MCP tool call, and the name it carries for server `failproofai_local`, + * tool `report`. + * + * | Agent | File (profile/env) | Key | HTTP entry | stdio entry | Hook sees MCP / name | + * |-------------|------------------------------------------------------|----------------------------|----------------------------------------------|-------------------------------------|----------------------| + * | claude | `$CLAUDE_CONFIG_DIR/.claude.json`, else `~/.claude.json` | `mcpServers` | `{type:"http", url, alwaysLoad}` | `{type:"stdio", command, args, alwaysLoad:true}` | yes, PreToolUse `mcp__failproofai_local__report` | + * | codex | `$CODEX_HOME/config.toml` (TOML) | `[mcp_servers.failproofai_local]`| `url = "…"` | `command`, `args` | yes, PreToolUse `mcp__failproofai_local__report` | + * | copilot | `$COPILOT_HOME/mcp-config.json`, else `~/.copilot/` | `mcpServers` | `{type:"http", url, tools:["*"]}` | `{type:"local", command, args, tools:["*"]}` | not documented; likely `failproofai_local-report` (exempt, with `failproofai_local/report`) | + * | cursor | `~/.cursor/mcp.json` (editor and cursor-agent) | `mcpServers` | `{url}` | `{type:"stdio", command, args}` | `beforeMCPExecution` (tool_name `report` + mcp_server_name; not installed) and preToolUse `MCP:report` with no server, so the server records | + * | opencode | `~/.config/opencode/opencode.json` (as the hooks) | v1 `mcp.`; v2 `mcp.servers.` | `{type:"remote", url, enabled:true}` (v2: no `enabled`) | `{type:"local", command:[…]}` | yes, plugin `tool.execute.before` `failproofai_local_report` | + * | pi | `$PI_CODING_AGENT_DIR/mcp.json`, else `~/.pi/agent/` | `mcpServers` | `{url, exposure:"direct"}` | `{command, args, exposure:"direct"}` | yes per docs, `tool_call` `mcp__failproofai_local__report` | + * | hermes | every profile's `config.yaml` (YAML, HERMES_HOME) | `mcp_servers` | (none written: plugin tool) | (removed if an earlier version wrote it) | yes per source, `pre_tool_call` `mcp_failproofai_local_report` | + * | openclaw | every profile's `openclaw.json` | `mcp.servers` | (none written: plugin tool) | (removed if an earlier version wrote it) | yes, `before_tool_call` `failproofai_local__report` | + * | factory | `~/.factory/mcp.json` | `mcpServers` | `{type:"http", url}` | `{type:"stdio", command, args}` | yes, `mcp__failproofai_local__report` (regex sees `failproofai_local___report`) | + * | devin | `~/.config/devin/mcp_config.json` | `mcpServers` | `{url, transport:"http"}` | `{command, args}` | yes, `mcp__failproofai_local__report` | + * | antigravity | `~/.gemini/config/mcp_config.json` | `mcpServers` | `{serverUrl, eager}` | `{command, args, eager:true}` | not documented; eager tools `mcp_failproofai_local_report`, lazy (default) via `call_mcp_tool` | + * | goose | `$GOOSE_PATH_ROOT/config/config.yaml`, else `~/.config/goose/config.yaml` (YAML) | `extensions` | `{type:"streamable_http", name, enabled, uri, …}` | `{type:"stdio", name, enabled, cmd, args, …}` | not documented; would be `failproofai_local__report` | + * + * Cursor approval (cursor-agent 2026.11): servers from a *project* + * `.cursor/mcp.json` load only once approved; approvals live per project root + * in `~/.cursor/projects//mcp-approvals.json`, keyed by a hash of the + * root and the entry. `~/.cursor/mcp.json` is user scope and needs none, except + * when cursor-agent runs with the home directory as its project, where it is + * also the project file. That key changes with every project and transport, so + * failproofai writes no approval; sync and status point at + * `cursor-agent mcp enable failproofai_local` instead. + * + * ## Visibility: how `report` reaches the model (checked 2026-11-29) + * + * | Agent | Deferred by default? | What failproofai does (evidence) | + * |-------------|----------------------------------------------|----------------------------------| + * | claude | yes, behind tool search | entry `alwaysLoad: true`: "never deferred behind tool search … Equivalent to setting defer_loading: false" (claude 2.1.332 MCP config schema) | + * | codex | yes in code mode (0.172: tools run through `exec`, MCP tools deferred) | marked block (`` … `end`) in the global `$CODEX_HOME/AGENTS.md` (`AGENTS.override.md` when that exists), always loaded: the instructions plus "search your tools for `failproofai_local`" (3/5 stuck runs reported without, 4/4 with) | + * | copilot | tools direct; server instructions only for the built-in `mcpRegistryServerInstructionAllowlist` (github-mcp-server, bluebird, computer-use in 1.0.83), no setting extends it | marked `~/.copilot/instructions/failproofai-self-reports.instructions.md` (any `*.instructions.md` under `$HOME/.copilot/instructions` is a documented source) | + * | cursor | no | nothing; reported unprompted | + * | opencode | no (`defer_loading` only inside the AI SDK, never set by OpenCode) | nothing; reported unprompted | + * | pi | no MCP before 0.99; from 0.99 MCP tools default to codemode (1.7.0) | Pi extension registers the tool (same name on every version; it also carries the hooks, so no MCP entry is written) | + * | hermes | yes: MCP and plugin tools, unless named in `toolsets._HERMES_CORE_TOOLS` (0.20.0 and 0.21.3 `is_deferrable_tool_name`); no per-server option | Hermes plugin registers it natively and adds it to that list; verified against both sources: deferrable before, direct after | + * | openclaw | yes, Tool Search on by default (2026.10.5); no per-server option | plugin tool with `catalogMode: "direct-only"` (tool-search catalog skips it); instructions as `before_prompt_build` `appendSystemContext` AND per-turn `appendContext` (system context alone: 0/3 stuck runs reported; both: 3/3, 0/2 false reports) | + * | factory | yes: every MCP server whose name lacks `github`/`agentbrowser` (droid `McpToolSearch`, default on); no setting | the instructions as SessionStart `additionalContext` | + * | devin | can defer behind `tool_search` (namespaces); server config has no eager key (3000.15.14) | nothing possible beyond the name in its listing | + * | antigravity | yes, lazy via `call_mcp_tool`; server instructions ignored | entry `eager: true` (mcp_config.json server field, protobuf `force_all_tools_eager`, agy 1.5.18), plus a plugin of ours, `~/.gemini/config/plugins/failproofai-self-reports/` (`plugin.json`, `rules/AGENTS.md`, marker `.failproofai-managed`), whose rules agy merges into every session (0/3 → 3/3) | + * | goose | no (no tool search) | nothing; reported unprompted | + * + * Every agent supports Streamable HTTP; HTTP is still used only for the + * hook-recorded ones (see above). Every path is the user-scope one: MCP servers are a per + * user (per profile) setting even where failproofai's hooks are per project. + * Codex: user scope only. Its system config (`/etc/codex/config.toml`, where + * root installs put the hooks) is not documented to honour `[mcp_servers]`, so + * a root install still registers the server in `$CODEX_HOME/config.toml`. + * + * ## Ownership + * + * An entry is ours when it is named `failproofai_local` AND has our shape: a URL + * `http://127.0.0.1:/mcp?agent=`, or a command whose file name + * contains `failproofai` run with `mcp --agent `. That shape is the marker: + * the JSON agents validate their server schema and an extra marker key could + * make one reject the whole file. Codex's entry also sits between two marker + * comments; Hermes' and Goose's carry a marker comment. A `failproofai_local` + * entry of any other shape is the user's: it is never changed and is reported + * as a conflict. An entry named `failproofai` (the Cloud MCP gateway, or + * anything else) is not ours by name and is never read, changed or reported. + */ +import { accessSync, constants as fsConstants, existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, rmSync } from "node:fs"; +import { execSync } from "node:child_process"; +import { homedir, userInfo } from "node:os"; +import { basename, dirname, resolve, sep } from "node:path"; +import { fileURLToPath } from "node:url"; +import { parse as parseToml } from "smol-toml"; +import { applyEdits, modify, parse as parseJsonc, type ParseError } from "jsonc-parser/lib/esm/main.js"; +import { isMap, parse as parseYaml, type Document } from "yaml"; +import { writeConfigFileAtomic } from "./safe-config-write"; +import { codexHome } from "./codex-system-hooks"; +import { claudeConfigDir, getIntegration, readYamlDoc, writeYamlDoc, UnreadableAgentConfigError } from "./integrations"; + +import { daemonSelfReportServer } from "./daemon-client"; +import { flushSelfReportLogs, sendSelfReportLog } from "./self-report-log"; +import { selfReportHookState } from "./self-report-hook-trust"; +import { + resolveSelfReport, + selfReportInstructions, + selfReportPort, + selfReportSettingsFile, + SELF_REPORT_DEFAULT_CATEGORIES, + SELF_REPORT_SERVER_NAME, + SELF_REPORT_SERVER_RECORDS, + SELF_REPORT_TOOL_NAME, + selfReportFlatteningOf, +} from "./self-report"; +import { listHermesProfiles } from "../../lib/hermes-profiles"; +import { listOpenClawProfiles } from "../../lib/openclaw-profiles"; +import { INTEGRATION_TYPES, type IntegrationType } from "./types"; +import { mergeTomlManagedBlock, readTomlManagedBlock, tomlString, type TomlBlockMarkers } from "./toml-managed-block"; + +/** + * Test-only guard: a test that forgot to isolate HOME must never write the + * developer's real agent configs. `os.userInfo().homedir` ignores `$HOME`, so it + * names the real home even when a test moved `$HOME`; under Vitest a write into + * it throws. Production (no `VITEST` in the environment) is unaffected. + */ +function assertNotRealHomeUnderTest(path: string): void { + if (!process.env.VITEST) return; + let real = ""; + try { + real = userInfo().homedir; + } catch { + return; + } + if (!real) return; + const target = resolve(path); + if (target === real || target.startsWith(real.endsWith(sep) ? real : real + sep)) { + throw new Error(`refusing to write ${target} under test: set HOME to a temp dir`); + } +} + +function guardedWriteConfig(path: string, text: string): void { + assertNotRealHomeUnderTest(path); + writeConfigFileAtomic(path, text); +} + +// ── Settings (CONTRACT §4) ────────────────────────────────────────────────── + +/** The MCP server's name in every agent. */ +export { SELF_REPORT_SERVER_NAME as SELF_REPORT_MCP_SERVER_NAME, SELF_REPORT_DEFAULT_PORT } from "./self-report"; + +/** `$FAILPROOFAI_HOME/self-report.json`. */ +export function selfReportSettingsPath(): string { + return selfReportSettingsFile(); +} + +export interface SelfReportMcpSettings { + enabled: boolean; + port: number; +} + +/** + * The bits of self-report.json this module needs, through the one settings + * reader in ./self-report (`resolveSelfReport`). On by default: a missing file + * is enabled off Cloud and disabled on a Cloud-enrolled machine until the + * daemon writes it; an unparsable file is disabled. Disabled is reported on the + * port a local writer would record. + */ +export function readSelfReportMcpSettings(path = selfReportSettingsPath()): SelfReportMcpSettings { + const s = resolveSelfReport(path); + if (!s) return { enabled: false, port: selfReportPort() }; + return { enabled: s.enabled, port: s.mcp.port }; +} + +// ── Transports ────────────────────────────────────────────────────────────── + +/** + * The agents sync may register on the daemon's HTTP endpoint: none. + * + * The endpoint records nothing for Claude Code and Codex, because their hook + * records the report. But the MCP entry is user-wide while whether those hooks + * run is not: a Claude Code project can turn them off + * (`.claude/settings.local.json` with `disableAllHooks: true`, review + * 4722003649), a Codex project config can change its hook setup, and a hook + * can be switched off after the entry was written. Over HTTP every report from + * such a project answered `Recorded.` and was lost. Over stdio the server + * records whatever the hook did not, matched per call + * (`selfReportHookRecordedRecently`), so a report is recorded exactly once + * whichever way any project is set up. An HTTP entry an earlier version wrote + * is moved to stdio by the next sync, and `status` flags it. + */ +export const SELF_REPORT_HTTP_AGENTS: readonly IntegrationType[] = []; + +/** Whether an agent may be registered over HTTP at all (see `SELF_REPORT_HTTP_AGENTS`). */ +export function selfReportHttpAllowed( + agent: IntegrationType, + httpAgents: readonly IntegrationType[] = SELF_REPORT_HTTP_AGENTS, +): boolean { + return ( + httpAgents.includes(agent) && + SELF_REPORT_MCP_TARGETS[agent]?.http === true && + !SELF_REPORT_SERVER_RECORDS.includes(agent) + ); +} + +export type SelfReportTransport = + | { kind: "http"; url: string } + | { kind: "stdio"; command: string; args: string[] }; + +export function selfReportHttpUrl(port: number, agent: IntegrationType): string { + return `http://127.0.0.1:${port}/mcp?agent=${agent}`; +} + +export function selfReportStdioArgs(agent: IntegrationType): string[] { + return ["mcp", "--agent", agent]; +} + +const OUR_URL_RE = /^http:\/\/(?:127\.0\.0\.1|localhost):\d{1,5}\/mcp\?agent=[a-z][a-z0-9_-]*$/; + +/** Launcher names a failproofai install puts on disk (npm's and bun's bin link, the package's own bin). */ +const LAUNCHER_NAMES: ReadonlySet = new Set(["failproofai", "failproofai.cmd", "failproofai.mjs"]); + +/** + * Whether `real` (a resolved path) is the CLI entry point of SOME failproofai + * package: `/bin/failproofai.mjs` or `/dist/cli.mjs` where + * `/package.json` names `failproofai`. Any version: an entry an earlier + * install wrote points at the same npm link, which now resolves to whatever + * version is installed (or the one it was). + */ +function isFailproofaiPackageEntry(real: string): boolean { + const root = resolve(dirname(real), ".."); + const rel = real.slice(root.length + 1); + if (rel !== `bin${sep}failproofai.mjs` && rel !== `dist${sep}cli.mjs`) return false; + try { + const pkg = JSON.parse(readFileSync(resolve(root, "package.json"), "utf8")) as { name?: unknown }; + return pkg.name === "failproofai"; + } catch { + return false; + } +} + +/** + * Whether a stdio command is one failproofai wrote (install, sync, uninstall): + * it resolves, through every link, to a failproofai package's CLI entry point + * (`isFailproofaiPackageEntry`). A path that no longer resolves at all counts + * only when its name is exactly a failproofai launcher: a link an earlier + * install left behind, which runs nothing. A program merely NAMED like ours + * (`failproofai-foreign`, or a script called `failproofai` that is not a + * failproofai package) is foreign, so sync reports it as a conflict and + * leaves it alone (review round 3). + */ +function isOurCliCommand(command: string): boolean { + if (!command.startsWith("/")) return false; + let real: string; + try { + real = realpathSync(command); + } catch { + return LAUNCHER_NAMES.has(basename(command).toLowerCase()) && !existsSync(command); + } + return isFailproofaiPackageEntry(real); +} + +function isOurCommand(command: unknown, args: unknown): boolean { + if (typeof command !== "string" || !isOurCliCommand(command)) return false; + return Array.isArray(args) && args[0] === "mcp" && args[1] === "--agent" && typeof args[2] === "string"; +} + +/** Whether a server entry (any agent's shape) is one failproofai wrote. */ +export function isOurMcpEntry(entry: unknown): boolean { + if (!entry || typeof entry !== "object" || Array.isArray(entry)) return false; + const e = entry as Record; + for (const key of ["url", "serverUrl", "uri"]) { + if (typeof e[key] === "string" && OUR_URL_RE.test(e[key] as string)) return true; + } + if (isOurCommand(e.command, e.args) || isOurCommand(e.cmd, e.args)) return true; + // OpenCode's local form: command is one array. + if (Array.isArray(e.command) && isOurCommand(e.command[0], e.command.slice(1))) return true; + return false; +} + +/** Which transport an entry of ours uses (for status), or null. */ +function transportOf(entry: unknown): "http" | "stdio" | null { + if (!isOurMcpEntry(entry)) return null; + const e = entry as Record; + return ["url", "serverUrl", "uri"].some((k) => typeof e[k] === "string") ? "http" : "stdio"; +} + +/** The URL (http) or command (stdio) an entry of ours points at, for status. */ +function endpointOf(entry: unknown): string | null { + if (!isOurMcpEntry(entry)) return null; + const e = entry as Record; + for (const key of ["url", "serverUrl", "uri"]) if (typeof e[key] === "string") return e[key] as string; + if (typeof e.command === "string") return e.command; + if (typeof e.cmd === "string") return e.cmd; + if (Array.isArray(e.command) && typeof e.command[0] === "string") return e.command[0]; + return null; +} + +// ── Liveness ──────────────────────────────────────────────────────────────── + +/** How long the endpoint may take to answer an MCP initialize. */ +const SELF_REPORT_PROBE_TIMEOUT_MS = 1500; + +/** + * The `serverInfo.instanceId` that `http://127.0.0.1:/mcp` returns when + * it answers an MCP `initialize` as failproofai's server within the timeout, + * `""` when it answers as failproofai's server with no id (an older daemon), + * or null for anything else (refused, timed out, another server on the port). + */ +export async function probeSelfReportHttpInstance(port: number, timeoutMs = SELF_REPORT_PROBE_TIMEOUT_MS): Promise { + try { + const res = await fetch(`http://127.0.0.1:${port}/mcp`, { + method: "POST", + headers: { "content-type": "application/json", accept: "application/json, text/event-stream" }, + body: JSON.stringify({ + jsonrpc: "2.0", + id: 1, + method: "initialize", + params: { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "failproofai-probe", version: "1" } }, + }), + signal: AbortSignal.timeout(timeoutMs), + }); + if (!res.ok) return null; + const body = (await res.json()) as { result?: { serverInfo?: { name?: unknown; instanceId?: unknown } } }; + const info = body?.result?.serverInfo; + if (info?.name !== SELF_REPORT_SERVER_NAME) return null; + return typeof info.instanceId === "string" ? info.instanceId : ""; + } catch { + return null; + } +} + +/** Whether the endpoint answers an MCP `initialize` as failproofai's server. */ +export async function probeSelfReportHttp(port: number, timeoutMs = SELF_REPORT_PROBE_TIMEOUT_MS): Promise { + return (await probeSelfReportHttpInstance(port, timeoutMs)) !== null; +} + +/** + * Whether agents should be pointed at the daemon's HTTP server: the daemon + * behind THIS home's socket answers a ping naming the MCP server it is + * serving (its pong's `selfReport`: present only while its listener is bound, + * on this port), AND the endpoint answers an initialize with that same + * `instanceId`. A socket file alone is not enough (a hard-killed daemon leaves + * one behind), and neither is a ping plus an answering port: the port may be + * held by a different daemon (another user's, or another FAILPROOFAI_HOME's) + * whose bind won while this one's failed, and a report sent there would be + * recorded under that daemon's home and credentials. Anything short of a match + * is stdio. + */ +export async function selfReportDaemonLive(port: number): Promise { + const [mine, served] = await Promise.all([daemonSelfReportServer(), probeSelfReportHttpInstance(port)]); + return !!mine && mine.port === port && !!served && served === mine.instanceId; +} + +/** Whether a stdio command can be run (exists and is executable). */ +export function selfReportCommandRunnable(command: string): boolean { + try { + accessSync(command, fsConstants.X_OK); + return true; + } catch { + return false; + } +} + +// ── Per-agent targets ─────────────────────────────────────────────────────── + +type Format = "json" | "toml" | "yaml"; + +interface McpTarget { + agent: IntegrationType; + format: Format; + /** Every file to write (one per profile for Hermes/OpenClaw). */ + paths(): string[]; + /** Whether the agent can reach a Streamable HTTP server. */ + http: boolean; + /** JSON/YAML key path of the servers map, given the parsed document. */ + container(parsed: Record): string[]; + /** The entry to write, given the container path chosen above. */ + entry(t: SelfReportTransport, container: string[]): Record; + /** + * The tool comes from failproofai's own extension for this agent, not from + * an MCP entry (Pi): sync writes none, and takes out one an earlier version + * wrote. + */ + extension?: true; + /** + * Something of ours beside the MCP entry that puts the instructions in front + * of the model through a channel the agent always loads (Copilot's + * instructions file, Codex's global AGENTS.md block, Antigravity's plugin + * rules): written while the entry is, rewritten when its text changes, + * removed with it. `path` names it in errors; `sync` only ever touches what + * carries our marker. + */ + companion?: { path(): string; sync(want: boolean): CompanionOutcome }; +} + +type CompanionOutcome = "added" | "updated" | "removed" | "unchanged" | "foreign"; + +function copilotHome(): string { + return process.env.COPILOT_HOME?.trim() || resolve(homedir(), ".copilot"); +} + +function copilotInstructionsPath(): string { + return resolve(copilotHome(), "instructions", "failproofai-self-reports.instructions.md"); +} + +/** The marker that makes a companion instructions file ours. */ +export const SELF_REPORT_COMPANION_MARKER = ""; + +/** + * Settings-independent instructions for a companion file: the categories and + * guidance stay in the tool's description, which the agent reads from the + * server on every start, so the file never goes stale. + */ +export function selfReportCompanionInstructions(): string { + return [ + "---", + 'applyTo: "**"', + "---", + SELF_REPORT_COMPANION_MARKER, + "", + "# FailproofAI Self Reports", + "", + "If you get stuck (you keep looping, a tool, credential, API key or token is broken or rejected, you", + "are missing context or access you cannot get, a command keeps failing, or you cannot do what was", + `asked), call the \`report\` tool of the \`${SELF_REPORT_SERVER_NAME}\` MCP server once, with a \`category\``, + "from its description and a one-sentence `detail`. It does not unblock you: continue, or tell the", + "user what is blocking you. There is no need to mention the report to the user.", + "", + ].join("\n"); +} + +/** Write (want) or remove (!want) a whole file of ours; only ever touches one carrying our marker. */ +function syncMarkedFile(path: string, content: () => string, want: boolean): CompanionOutcome { + const existing = existsSync(path) ? readFileSync(path, "utf8") : null; + if (existing !== null && !existing.includes(SELF_REPORT_COMPANION_MARKER)) return "foreign"; + if (!want) { + if (existing === null) return "unchanged"; + assertNotRealHomeUnderTest(path); + rmSync(path, { force: true }); + return "removed"; + } + const text = content(); + if (existing === text) return "unchanged"; + assertNotRealHomeUnderTest(path); + mkdirSync(dirname(path), { recursive: true }); + writeConfigFileAtomic(path, text); + return existing === null ? "added" : "updated"; +} + +/** + * The instructions the MCP server sends at initialize, with this machine's + * categories and guidance (a sync runs whenever they change, so the copy in + * an always-loaded file follows them). While the setting is off or unreadable + * a sync removes the file, so the defaults here are only ever written by a + * sync told to enable. + */ +function selfReportAlwaysOnInstructions(): string { + const s = resolveSelfReport(); + return selfReportInstructions(s?.categories ?? SELF_REPORT_DEFAULT_CATEGORIES, s?.guidance); +} + +/** The block of ours in Codex's global AGENTS.md. */ +export const SELF_REPORT_CODEX_AGENTS_MARKERS: TomlBlockMarkers = { + begin: "", + end: "", +}; + +/** The text between Codex's markers, markers included. */ +export function selfReportCodexAgentsBlock(): string { + // A guidance line equal to a marker would end the block early. + const body = selfReportAlwaysOnInstructions() + .split("\n") + .filter((l) => l.trim() !== SELF_REPORT_CODEX_AGENTS_MARKERS.begin && l.trim() !== SELF_REPORT_CODEX_AGENTS_MARKERS.end) + .join("\n"); + return [ + SELF_REPORT_CODEX_AGENTS_MARKERS.begin, + body, + `If the tool is not listed directly, search your tools for \`${SELF_REPORT_SERVER_NAME}\`.`, + SELF_REPORT_CODEX_AGENTS_MARKERS.end, + "", + ].join("\n"); +} + +/** + * Codex's global instructions file: `$CODEX_HOME/AGENTS.override.md` when it + * exists (Codex then reads it instead of AGENTS.md), else `$CODEX_HOME/AGENTS.md`. + */ +function codexAgentsPaths(): { active: string; other: string } { + const override = resolve(codexHome(), "AGENTS.override.md"); + const plain = resolve(codexHome(), "AGENTS.md"); + return existsSync(override) ? { active: override, other: plain } : { active: plain, other: override }; +} + +/** + * Put our marked block in Codex's global AGENTS.md (want), or take it out. + * Every byte outside the markers is kept; a file that held only our block is + * removed with it. A half block (one marker) throws, writing nothing. + */ +function syncCodexAgentsBlock(want: boolean): CompanionOutcome { + const { active, other } = codexAgentsPaths(); + const put = (path: string, block: string | null): "changed" | "same" | "absent" => { + if (!existsSync(path)) { + if (block === null) return "absent"; + assertNotRealHomeUnderTest(path); + mkdirSync(dirname(path), { recursive: true }); + writeConfigFileAtomic(path, block); + return "changed"; + } + const text = readFileSync(path, "utf8"); + const next = mergeTomlManagedBlock(text, block, SELF_REPORT_CODEX_AGENTS_MARKERS); + if (next === text) return "same"; + assertNotRealHomeUnderTest(path); + if (block === null && next.trim() === "") rmSync(path, { force: true }); + else writeConfigFileAtomic(path, next); + return "changed"; + }; + const hadBlock = [active, other].some( + (p) => existsSync(p) && readTomlManagedBlock(readFileSync(p, "utf8"), SELF_REPORT_CODEX_AGENTS_MARKERS) !== null, + ); + const movedOut = put(other, null) === "changed"; + if (!want) return put(active, null) === "changed" || movedOut ? "removed" : "unchanged"; + const wrote = put(active, selfReportCodexAgentsBlock()) === "changed"; + return !wrote && !movedOut ? "unchanged" : hadBlock ? "updated" : "added"; +} + +/** The Antigravity plugin of ours, in agy's global customization root. */ +export const SELF_REPORT_ANTIGRAVITY_PLUGIN = "failproofai-self-reports"; +/** The file whose presence makes that plugin directory ours. */ +export const SELF_REPORT_MANAGED_MARKER_FILE = ".failproofai-managed"; + +function antigravityPluginDir(): string { + return resolve(homedir(), ".gemini", "config", "plugins", SELF_REPORT_ANTIGRAVITY_PLUGIN); +} + +/** Every file of the Antigravity plugin, by path relative to its directory. */ +export function selfReportAntigravityPluginFiles(): Record { + // The marker comes first, so a directory left half-written is still ours. + return { + [SELF_REPORT_MANAGED_MARKER_FILE]: + "Written by failproofai (Self Reports). `failproofai self-report disable` or `failproofai uninstall` removes this directory.\n", + "plugin.json": `${JSON.stringify({ name: SELF_REPORT_ANTIGRAVITY_PLUGIN }, null, 2)}\n`, + "rules/AGENTS.md": `# FailproofAI Self Reports\n\n${selfReportAlwaysOnInstructions()}\n`, + }; +} + +/** + * Write (want) or remove the Antigravity plugin directory. agy merges a + * global plugin's `rules/` into every session's rules, where it ignores MCP + * server instructions. A directory of that name without our marker file is + * the user's and is never written into or removed. + */ +function syncAntigravityPlugin(want: boolean): CompanionOutcome { + const dir = antigravityPluginDir(); + const exists = existsSync(dir); + if (exists && !existsSync(resolve(dir, SELF_REPORT_MANAGED_MARKER_FILE))) return "foreign"; + if (!want) { + if (!exists) return "unchanged"; + assertNotRealHomeUnderTest(dir); + rmSync(dir, { recursive: true, force: true }); + return "removed"; + } + let changed = false; + for (const [rel, text] of Object.entries(selfReportAntigravityPluginFiles())) { + const path = resolve(dir, rel); + if (existsSync(path) && readFileSync(path, "utf8") === text) continue; + assertNotRealHomeUnderTest(path); + mkdirSync(dirname(path), { recursive: true }); + writeConfigFileAtomic(path, text); + changed = true; + } + return !changed ? "unchanged" : exists ? "updated" : "added"; +} + +const plainEntry = (t: SelfReportTransport, urlKey = "url"): Record => + t.kind === "http" ? { [urlKey]: t.url } : { command: t.command, args: t.args }; + +function xdgConfigHome(): string { + const x = process.env.XDG_CONFIG_HOME?.trim(); + return x ? resolve(x) : resolve(homedir(), ".config"); +} + +function claudeUserConfigPath(): string { + // Claude Code keeps `.claude.json` inside CLAUDE_CONFIG_DIR when it is set, + // and beside `~/.claude` otherwise. + return process.env.CLAUDE_CONFIG_DIR?.trim() + ? resolve(claudeConfigDir(), ".claude.json") + : resolve(homedir(), ".claude.json"); +} + +function gooseConfigPath(): string { + const root = process.env.GOOSE_PATH_ROOT?.trim(); + if (root) return resolve(root, "config", "config.yaml"); + if (process.platform === "win32" && process.env.APPDATA) { + return resolve(process.env.APPDATA, "Block", "goose", "config", "config.yaml"); + } + return resolve(xdgConfigHome(), "goose", "config.yaml"); +} + +function opencodeUserConfigPath(): string { + // Same directory the hooks are written to (integrations.ts `opencode`). + const dir = resolve(homedir(), ".config", "opencode"); + const json = resolve(dir, "opencode.json"); + const jsonc = resolve(dir, "opencode.jsonc"); + return !existsSync(json) && existsSync(jsonc) ? jsonc : json; +} + +/** OpenCode v2 nests servers under `mcp.servers`; v1 puts them directly under `mcp`. */ +function opencodeIsV2(parsed: Record): boolean { + const mcp = parsed.mcp as Record | undefined; + const servers = mcp?.servers as Record | undefined; + return !!servers && typeof servers === "object" && !Array.isArray(servers) && !("type" in servers); +} + +export const SELF_REPORT_MCP_TARGETS: Record = { + claude: { + agent: "claude", format: "json", http: true, + paths: () => [claudeUserConfigPath()], + container: () => ["mcpServers"], + // `alwaysLoad: true`: Claude Code keeps this server's tools in the prompt + // instead of deferring them behind tool search (its own MCP schema: + // "never deferred behind tool search … Equivalent to setting + // defer_loading: false on the API"). For our entry only. + entry: (t) => + t.kind === "http" + ? { type: "http", url: t.url, alwaysLoad: true } + : { type: "stdio", command: t.command, args: t.args, alwaysLoad: true }, + }, + codex: { + agent: "codex", format: "toml", http: true, + paths: () => [resolve(codexHome(), "config.toml")], + container: () => ["mcp_servers"], + entry: (t) => plainEntry(t), + // Codex 0.172 runs tools through code mode and defers MCP tools, and the + // model rarely looked for ours (3/5 stuck runs reported). A global + // AGENTS.md is in every session; with the instructions there it searched + // for `failproofai_local` and reported 4/4. A marked block in that file. + companion: { + path: () => codexAgentsPaths().active, + sync: syncCodexAgentsBlock, + }, + }, + copilot: { + agent: "copilot", format: "json", http: true, + paths: () => [resolve(copilotHome(), "mcp-config.json")], + container: () => ["mcpServers"], + entry: (t) => + t.kind === "http" + ? { type: "http", url: t.url, tools: ["*"] } + : { type: "local", command: t.command, args: t.args, tools: ["*"] }, + // Copilot passes a server's instructions to the model only for its + // built-in allowlist (`mcpRegistryServerInstructionAllowlist`: + // github-mcp-server, bluebird, computer-use in 1.0.83; no setting extends + // it, only the per-run `--allow-all-mcp-server-instructions` flag). It + // does load user instructions from `~/.copilot/instructions/*.instructions.md`, + // so the same text goes there, in a file of ours. + companion: { + path: copilotInstructionsPath, + sync: (want) => syncMarkedFile(copilotInstructionsPath(), selfReportCompanionInstructions, want), + }, + }, + cursor: { + agent: "cursor", format: "json", http: true, + paths: () => [resolve(homedir(), ".cursor", "mcp.json")], + container: () => ["mcpServers"], + entry: (t) => (t.kind === "http" ? { url: t.url } : { type: "stdio", command: t.command, args: t.args }), + }, + opencode: { + agent: "opencode", format: "json", http: true, + paths: () => [opencodeUserConfigPath()], + container: (parsed) => (opencodeIsV2(parsed) ? ["mcp", "servers"] : ["mcp"]), + entry: (t, container) => { + const v2 = container.length === 2; + const base = t.kind === "http" ? { type: "remote", url: t.url } : { type: "local", command: [t.command, ...t.args] }; + return v2 ? base : { ...base, enabled: true }; + }, + }, + pi: { + agent: "pi", format: "json", http: true, + paths: () => [resolve(process.env.PI_CODING_AGENT_DIR?.trim() || resolve(homedir(), ".pi", "agent"), "mcp.json")], + container: () => ["mcpServers"], + // Pi before 0.99 has no MCP at all, so an entry here reached no model on + // the Pi this was verified against (0.85.1). failproofai's Pi extension, + // which a hooked Pi already loads, registers the tool itself + // (pi-extension/index.ts); this file only loses an entry an earlier + // version wrote. The entry shape is kept so that one is recognised. + entry: (t) => ({ ...plainEntry(t), exposure: "direct" }), + extension: true, + }, + hermes: { + agent: "hermes", format: "yaml", http: true, + paths: () => listHermesProfiles().map((p) => resolve(p.home, "config.yaml")), + container: () => ["mcp_servers"], + // Hermes defers MCP (and plugin) tools behind its tool search with no + // per-server switch, so an MCP entry reached the model as a bare name. + // failproofai's Hermes plugin registers the tool natively and keeps it + // direct (hermes-plugin/self_report.py); this file only loses an entry an + // earlier version wrote. The shape is kept so that one is recognised. + entry: (t) => plainEntry(t), + extension: true, + }, + openclaw: { + agent: "openclaw", format: "json", http: true, + paths: () => listOpenClawProfiles().map((p) => resolve(p.home, "openclaw.json")), + container: () => ["mcp", "servers"], + // Same as Hermes: Tool Search defers MCP tools and has no per-server + // setting; failproofai's OpenClaw plugin registers a `catalogMode: + // "direct-only"` tool instead (openclaw-plugin/self-report.js). + entry: (t) => (t.kind === "http" ? { url: t.url, transport: "streamable-http" } : { command: t.command, args: t.args }), + extension: true, + }, + factory: { + agent: "factory", format: "json", http: true, + paths: () => [resolve(homedir(), ".factory", "mcp.json")], + container: () => ["mcpServers"], + entry: (t) => (t.kind === "http" ? { type: "http", url: t.url } : { type: "stdio", command: t.command, args: t.args }), + }, + devin: { + agent: "devin", format: "json", http: true, + paths: () => [ + process.platform === "win32" && process.env.APPDATA + ? resolve(process.env.APPDATA, "devin", "mcp_config.json") + : resolve(homedir(), ".config", "devin", "mcp_config.json"), + ], + container: () => ["mcpServers"], + entry: (t) => (t.kind === "http" ? { url: t.url, transport: "http" } : { command: t.command, args: t.args }), + }, + antigravity: { + agent: "antigravity", format: "json", http: true, + paths: () => [resolve(homedir(), ".gemini", "config", "mcp_config.json")], + container: () => ["mcpServers"], + // `eager: true` (agy's per-server `force_all_tools_eager`): the tools are + // direct, not behind the lazy `call_mcp_tool` wrapper (agy 1.5.18). + entry: (t) => ({ ...plainEntry(t, "serverUrl"), eager: true }), + // agy ignores MCP server instructions; a plugin in its global + // customization root has its `rules/` merged into every session's rules + // (0/3 stuck runs reported without, 3/3 with). + companion: { + path: antigravityPluginDir, + sync: syncAntigravityPlugin, + }, + }, + goose: { + agent: "goose", format: "yaml", http: true, + paths: () => [gooseConfigPath()], + container: () => ["extensions"], + entry: (t) => + t.kind === "http" + ? { name: SELF_REPORT_SERVER_NAME, type: "streamable_http", enabled: true, uri: t.url, envs: {}, env_keys: [], timeout: 300 } + : { name: SELF_REPORT_SERVER_NAME, type: "stdio", enabled: true, cmd: t.command, args: t.args, envs: {}, env_keys: [], timeout: 300 }, + }, +}; + +// ── Reading and writing one file ──────────────────────────────────────────── + +const TOML_MARKERS: TomlBlockMarkers = { + begin: "# >>> failproofai self-report mcp >>>", + end: "# <<< failproofai self-report mcp <<<", +}; +const YAML_MARKER_COMMENT = " failproofai self-report MCP server (managed by failproofai; removed by `failproofai self-report disable`)"; + +type Current = + | { state: "absent" } + | { state: "ours"; entry: Record } + | { state: "foreign" }; + +interface FileOps { + current(): Current; + /** Desired entry → new file text; null entry removes ours. */ + write(entry: Record | null): void; + /** The container path the entry goes in (json/yaml only). */ + container: string[]; +} + +function readText(path: string): string { + if (!existsSync(path)) return ""; + try { + return readFileSync(path, "utf8"); + } catch (err) { + throw new UnreadableAgentConfigError(path, `it could not be read (${err instanceof Error ? err.message : String(err)})`); + } +} + +function getIn(obj: unknown, path: string[]): unknown { + let v: unknown = obj; + for (const k of path) { + if (!v || typeof v !== "object" || Array.isArray(v)) return undefined; + v = (v as Record)[k]; + } + return v; +} + +function classify(value: unknown): Current { + if (value === undefined) return { state: "absent" }; + return isOurMcpEntry(value) ? { state: "ours", entry: value as Record } : { state: "foreign" }; +} + +function jsonOps(target: McpTarget, path: string): FileOps { + const text = readText(path); + let parsed: Record = {}; + if (text.trim() !== "") { + const errors: ParseError[] = []; + const value: unknown = parseJsonc(text, errors, { allowTrailingComma: true }); + if (errors.length > 0) throw new UnreadableAgentConfigError(path, "it is not valid JSON"); + if (!value || typeof value !== "object" || Array.isArray(value)) { + throw new UnreadableAgentConfigError(path, "its top level is not a JSON object"); + } + parsed = value as Record; + } + const container = target.container(parsed); + // A container that exists but is not an object cannot take our key. + const holder = getIn(parsed, container); + if (holder !== undefined && (typeof holder !== "object" || holder === null || Array.isArray(holder))) { + return { + container, + current: () => ({ state: "foreign" }), + write: () => { + throw new Error(`${container.join(".")} is not an object`); + }, + }; + } + const keyPath = [...container, SELF_REPORT_SERVER_NAME]; + return { + container, + current: () => classify(getIn(parsed, keyPath)), + write(entry) { + const base = text.trim() === "" ? "{}\n" : text; + const edits = modify(base, keyPath, entry ?? undefined, { + formattingOptions: { insertSpaces: true, tabSize: 2, eol: "\n" }, + }); + let next = applyEdits(base, edits); + if (!next.endsWith("\n")) next += "\n"; + guardedWriteConfig(path, next); + }, + }; +} + +function renderTomlBlock(entry: Record): string { + const lines = [ + TOML_MARKERS.begin, + "# Written by failproofai (Self Reports). `failproofai self-report disable` or", + "# `failproofai uninstall` removes it. Everything between the markers is replaced.", + `[mcp_servers.${SELF_REPORT_SERVER_NAME}]`, + ]; + for (const [k, v] of Object.entries(entry)) { + if (typeof v === "string") lines.push(`${k} = ${tomlString(v)}`); + else if (Array.isArray(v)) lines.push(`${k} = [${v.map((x) => tomlString(String(x))).join(", ")}]`); + } + lines.push(TOML_MARKERS.end); + return `${lines.join("\n")}\n`; +} + +function tomlOps(path: string): FileOps { + const text = readText(path); + let outside: string; + let ourBlock: string | null; + try { + ourBlock = readTomlManagedBlock(text, TOML_MARKERS); + outside = mergeTomlManagedBlock(text, null, TOML_MARKERS); + } catch (err) { + throw new UnreadableAgentConfigError(path, err instanceof Error ? err.message : String(err)); + } + let parsedOutside: Record; + let parsedAll: Record; + try { + parsedOutside = parseToml(outside) as Record; + parsedAll = parseToml(text) as Record; + } catch (err) { + throw new UnreadableAgentConfigError(path, `it does not parse as TOML (${err instanceof Error ? err.message.split("\n")[0] : String(err)})`); + } + const keyPath = ["mcp_servers", SELF_REPORT_SERVER_NAME]; + return { + container: ["mcp_servers"], + current() { + if (getIn(parsedOutside, keyPath) !== undefined) return { state: "foreign" }; + if (!ourBlock) return { state: "absent" }; + const entry = getIn(parsedAll, keyPath); + return entry && typeof entry === "object" ? { state: "ours", entry: entry as Record } : { state: "absent" }; + }, + write(entry) { + const next = mergeTomlManagedBlock(text, entry ? renderTomlBlock(entry) : null, TOML_MARKERS); + // Never hand Codex a file it cannot start with: an inline `mcp_servers = {…}` + // elsewhere would collide with our table header. + let check: Record; + try { + check = parseToml(next) as Record; + } catch (err) { + throw new Error(`the result would not be valid TOML (${err instanceof Error ? err.message.split("\n")[0] : String(err)})`); + } + if (entry && getIn(check, keyPath) === undefined) throw new Error("the written entry did not read back"); + guardedWriteConfig(path, next); + }, + }; +} + +function yamlOps(target: McpTarget, path: string): FileOps { + const doc: Document = readYamlDoc(path); + const js = (doc.toJS() ?? {}) as Record; + if (typeof js !== "object" || Array.isArray(js)) throw new UnreadableAgentConfigError(path, "its top level is not a mapping"); + const container = target.container(js); + const holder = doc.getIn(container); + const keyPath = [...container, SELF_REPORT_SERVER_NAME]; + if (holder !== undefined && holder !== null && !isMap(holder)) { + return { + container, + current: () => ({ state: "foreign" }), + write: () => { + throw new Error(`${container.join(".")} is not a mapping`); + }, + }; + } + return { + container, + current: () => classify(getIn(js, keyPath)), + write(entry) { + if (entry) { + const node = doc.createNode(entry); + node.commentBefore = YAML_MARKER_COMMENT; + if (holder === undefined || holder === null) doc.setIn(container, doc.createNode({})); + doc.setIn(keyPath, node); + } else { + doc.deleteIn(keyPath); + } + assertNotRealHomeUnderTest(path); + writeYamlDoc(path, doc); + }, + }; +} + +function opsFor(target: McpTarget, path: string): FileOps { + if (target.format === "toml") return tomlOps(path); + if (target.format === "yaml") return yamlOps(target, path); + return jsonOps(target, path); +} + +function sameEntry(a: unknown, b: unknown): boolean { + return JSON.stringify(a) === JSON.stringify(b); +} + +// ── Sync ──────────────────────────────────────────────────────────────────── + +export type SelfReportMcpAction = "added" | "updated" | "removed" | "unchanged" | "skipped"; +export type SelfReportMcpStatus = + /** The file now matches what was wanted. */ + | "ok" + /** Enabled, but this agent has no failproofai hooks; nothing written. */ + | "not-hooked" + /** A `failproofai_local` server that is not ours is there; left alone. */ + | "conflict" + /** The file could not be read or written; left as it was. */ + | "error" + /** The agent cannot take an MCP server this way. */ + | "unsupported"; + +export interface SelfReportMcpResult { + agent: IntegrationType; + path: string; + action: SelfReportMcpAction; + /** `extension`: the agent's tool comes from failproofai's own extension (Pi). */ + transport: "http" | "stdio" | "extension" | null; + status: SelfReportMcpStatus; + detail?: string; +} + +export interface SyncSelfReportMcpOptions { + /** Override the settings file's `enabled`. `false` removes our entries everywhere. */ + enabled?: boolean; + /** Print one line per change (default: print nothing; callers print results). */ + quiet?: boolean; + /** Only these agents (default: every integration). */ + agents?: readonly IntegrationType[]; + /** + * When enabling, register in these agents even if their user-scope hooks are + * not detected (installHooks passes the agents it just wrote, at any scope). + */ + alsoHooked?: readonly IntegrationType[]; + /** The failproofai CLI the hooks use (stdio command). Default: resolved like the installer does. */ + binaryPath?: string; + /** Test seams. */ + deps?: { + /** The live check (default `selfReportDaemonLive`); asked only when an agent wants the server. */ + daemonLive?: (port: number) => Promise; + hooksInstalled?: (agent: IntegrationType) => boolean; + /** + * Whether a hook-recorded agent's user-scope hook will run (default + * `selfReportHookState`): only then may it be on the daemon's HTTP endpoint, + * which records nothing for it. + */ + hookRecords?: (agent: IntegrationType) => boolean; + settings?: SelfReportMcpSettings; + resolveCliPath?: () => string | null; + /** Agents allowed on HTTP (default `SELF_REPORT_HTTP_AGENTS`, none); tests of the HTTP path set it. */ + httpAgents?: readonly IntegrationType[]; + }; +} + +/** The failproofai CLI the hooks run: the installer's override, PATH, then this process's own bin. */ +export function resolveSelfReportCliPath(): string | null { + const override = process.env.FAILPROOFAI_BINARY_OVERRIDE?.trim(); + if (override) return override; + try { + const cmd = process.platform === "win32" ? "where failproofai" : "which failproofai"; + const found = execSync(cmd, { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim().split("\n")[0]?.trim(); + if (found) return found; + } catch { + // not on PATH (a daemon's service environment, say) + } + // A daemon's service has no login PATH (an nvm node is on no system PATH), + // and it runs the CLI as ` …/failproofai/dist/cli.mjs`, whose name is + // not one an entry can be recognised by. npm puts the `failproofai` link in + // the same bin directory as the node that installed it, so look there, then + // where the daemon looks for the CLI (`global_bin_dirs` in + // crates/failproofaid/src/self_report.rs). Without this the daemon's sync + // had no stdio command and failed every server-recorded agent. + for (const dir of selfReportCliDirs()) { + const candidate = resolve(dir, process.platform === "win32" ? "failproofai.cmd" : "failproofai"); + if (selfReportCommandRunnable(candidate)) return candidate; + } + const self = process.argv[1]; + if (self && basename(self).toLowerCase().includes("failproofai")) { + try { + return realpathSync(self); + } catch { + return resolve(self); + } + } + return null; +} + +/** Bin directories that hold an npm/bun global `failproofai` when PATH does not. */ +export function selfReportCliDirs(env: Record = process.env, execPath = process.execPath, home = homedir()): string[] { + const dirs = [dirname(execPath)]; + const prefix = (env.NPM_CONFIG_PREFIX ?? env.npm_config_prefix)?.trim(); + if (prefix) dirs.push(resolve(prefix, "bin")); + dirs.push(resolve(home, ".npm-global", "bin"), "/usr/local/bin", resolve(home, ".bun", "bin")); + return [...new Set(dirs)]; +} + +function defaultHooksInstalled(agent: IntegrationType): boolean { + try { + const integration = getIntegration(agent); + return integration.scopes.includes("user") && integration.hooksInstalledInSettings("user"); + } catch { + return false; + } +} + +/** + * Add (enabled) or remove (disabled) our `failproofai_local` MCP server in every + * agent. Enabled: only agents with failproofai hooks get it, and agents without + * hooks are left as they are; HTTP for a hook-recorded agent when this home's + * daemon is serving the port right now (see `selfReportDaemonLive`), stdio + * otherwise and always for a server-recorded agent. Disabled: ours is removed from + * every agent's file, hooked or not. Idempotent; never touches an entry that + * is not ours; one agent's failure never stops the others. + */ +export async function syncSelfReportMcp(opts: SyncSelfReportMcpOptions = {}): Promise { + const settings = opts.deps?.settings ?? readSelfReportMcpSettings(); + const enabled = opts.enabled ?? settings.enabled; + const agents = opts.agents ?? INTEGRATION_TYPES; + const seen = new Map(); + const isHooked = opts.deps?.hooksInstalled ?? defaultHooksInstalled; + const hooked = (a: IntegrationType): boolean => { + if (!seen.has(a)) seen.set(a, isHooked(a)); + return seen.get(a)!; + }; + // The live check costs up to a couple of seconds against a wedged daemon, so + // it runs only when some agent will get an HTTP-capable entry. + const also = opts.alsoHooked ?? []; + const wanted = + enabled && + agents.some((a) => selfReportHttpAllowed(a, opts.deps?.httpAgents) && (also.includes(a) || hooked(a) || ownedRegistrationIn(a))); + const daemonHere = wanted ? await (opts.deps?.daemonLive ?? selfReportDaemonLive)(settings.port) : false; + const results = applySelfReportMcp({ ...opts, deps: { ...opts.deps, settings, hooksInstalled: hooked } }, enabled, daemonHere); + logSelfReportSync(results); + await flushSelfReportLogs(); + return results; +} + +/** + * The environment variable the daemon sets on the sync it runs itself: it + * logs that sync's stdout, so the result is printed there (by bin's `sync`) + * rather than sent back over its socket. Same name as `SYNC_LOG_ENV` in + * crates/failproofaid/src/self_report.rs. + */ +export const SELF_REPORT_SYNC_LOG_ENV = "FAILPROOFAI_SELF_REPORT_SYNC_LOG"; + +/** A sync's result for the daemon's log, when it changed or failed anything. */ +function logSelfReportSync(results: readonly SelfReportMcpResult[]): void { + if (process.env[SELF_REPORT_SYNC_LOG_ENV] === "stdout") return; + const summary = selfReportSyncLogLine(results); + if (!summary) return; + const failed = selfReportFailedAgents(results).length > 0; + void sendSelfReportLog({ event: "sync", transport: "cli", outcome: failed ? "failed" : "ok", summary }); +} + +/** + * Whether any of an agent's files already holds our entry. An agent whose + * hooks are installed only at project/local scope is registered by the + * install itself (`alsoHooked`), and later syncs do not see those hooks; its + * existing entry is still kept and its transport repaired. + */ +function ownedRegistrationIn(agent: IntegrationType): boolean { + const target = SELF_REPORT_MCP_TARGETS[agent]; + if (!target) return false; + try { + return target.paths().some((path) => { + try { + return existsSync(path) && opsFor(target, path).current().state === "ours"; + } catch { + return false; + } + }); + } catch { + return false; + } +} + +// ── Ownership at call time (the hook's report exemption) ──────────────────── + +/** + * Project-scope files an agent may read MCP servers from, relative to the + * project directory or any directory above it, and the server maps inside + * them. failproofai never writes `failproofai_local` at project scope, so a + * definition in any of these is not ours. + */ +const PROJECT_MCP_FILES: readonly string[] = [ + ".mcp.json", + ".cursor/mcp.json", + ".factory/mcp.json", + ".vscode/mcp.json", + ".codex/config.toml", + "opencode.json", + "opencode.jsonc", + ".opencode/opencode.json", + ".opencode/opencode.jsonc", + ".gemini/settings.json", + ".gemini/config/mcp_config.json", + ".pi/mcp.json", +]; + +/** Agents with no project-scope config at all (CLAUDE.md: user scope only). */ +const USER_SCOPE_ONLY: readonly IntegrationType[] = ["hermes", "openclaw"]; +const PROJECT_MCP_CONTAINERS: readonly string[][] = [ + ["mcpServers"], ["servers"], ["mcp"], ["mcp", "servers"], ["mcp_servers"], ["extensions"], +]; + +function definesServer(doc: unknown): boolean { + const want = SELF_REPORT_SERVER_NAME.toLowerCase(); + return PROJECT_MCP_CONTAINERS.some((path) => { + const holder = getIn(doc, path); + if (!holder || typeof holder !== "object" || Array.isArray(holder)) return false; + return Object.keys(holder).some((k) => k.toLowerCase() === want); + }); +} + +/** `path` with symlinks resolved when it exists, else as given (absolute). */ +function realOrResolved(path: string): string { + try { + return realpathSync(path); + } catch { + return resolve(path); + } +} + +/** + * Every agent's USER-scope config file, as the installer writes them (each + * honours its own override: `CODEX_HOME`, `CLAUDE_CONFIG_DIR`, `XDG_CONFIG_HOME`, + * `PI_CODING_AGENT_DIR`, the Hermes/OpenClaw profiles, …). A walk up from a + * project beneath HOME meets several of them (`~/.codex/config.toml`, + * `~/.cursor/mcp.json`); they hold our own user-wide registration, not a + * project override, so the project scan skips them. + */ +function userScopeConfigPaths(): Set { + const out = new Set(); + for (const agent of INTEGRATION_TYPES) { + const target = SELF_REPORT_MCP_TARGETS[agent]; + if (!target) continue; + try { + for (const p of target.paths()) out.add(realOrResolved(p)); + } catch { + // A profile list that cannot be read adds nothing: the scan stays strict. + } + } + // OpenCode's user config may be either spelling. + const opencodeDir = resolve(homedir(), ".config", "opencode"); + out.add(realOrResolved(resolve(opencodeDir, "opencode.json"))); + out.add(realOrResolved(resolve(opencodeDir, "opencode.jsonc"))); + return out; +} + +/** + * Whether any project-scope config at or above `cwd` defines a server named + * `failproofai_local` (or names it in a way that cannot be read). Claude + * Code's local scope (`projects[].mcpServers` in `.claude.json`) counts. + * Agents' user-scope files met on the way up are not project config and are + * skipped (`userScopeConfigPaths`). + */ +function projectDefinesSelfReportServer(cwd: string): boolean { + const want = SELF_REPORT_SERVER_NAME.toLowerCase(); + const dirs: string[] = []; + for (let d = resolve(cwd); ; d = dirname(d)) { + dirs.push(d); + if (dirname(d) === d) break; + } + const userFiles = userScopeConfigPaths(); + for (const dir of dirs) { + for (const rel of PROJECT_MCP_FILES) { + const path = resolve(dir, rel); + if (!existsSync(path)) continue; + if (userFiles.has(realOrResolved(path))) continue; + let text: string; + try { + text = readFileSync(path, "utf8"); + } catch { + return true; // unreadable: cannot show it does not define ours + } + if (!text.toLowerCase().includes(want)) continue; + try { + let doc: unknown; + if (path.endsWith(".toml")) { + doc = parseToml(text); + } else { + const errors: ParseError[] = []; + doc = parseJsonc(text, errors, { allowTrailingComma: true }); + if (errors.length > 0) return true; + } + if (definesServer(doc)) return true; + } catch { + return true; + } + } + } + // Claude Code's local scope, keyed by project directory in `.claude.json`. + const claudeJson = claudeUserConfigPath(); + if (existsSync(claudeJson)) { + let text: string; + try { + text = readFileSync(claudeJson, "utf8"); + } catch { + return true; + } + if (text.toLowerCase().includes(want)) { + const errors: ParseError[] = []; + const doc = parseJsonc(text, errors, { allowTrailingComma: true }) as Record | undefined; + if (errors.length > 0 || !doc || typeof doc !== "object") return true; + const projects = doc.projects; + if (projects && typeof projects === "object" && !Array.isArray(projects)) { + for (const dir of dirs) { + const p = (projects as Record)[dir]; + if (definesServer(p)) return true; + } + } + } + } + return false; +} + +/** + * The real paths of this failproofai's own CLI entry points: the package's + * `bin/failproofai.mjs` (what npm's and bun's global `failproofai` link to, + * and what the installer writes as the stdio command) and its bundled + * `dist/cli.mjs`. The package is `FAILPROOFAI_PACKAGE_ROOT` (set by the CLI + * and the daemon's worker), else found by walking up from this module. + */ +function selfReportOwnCliEntries(): Set { + const out = new Set(); + const roots: string[] = []; + const fromEnv = process.env.FAILPROOFAI_PACKAGE_ROOT?.trim(); + if (fromEnv) roots.push(fromEnv); + try { + let dir = dirname(fileURLToPath(import.meta.url)); + for (let i = 0; i < 8; i++) { + if (existsSync(resolve(dir, "bin", "failproofai.mjs")) && existsSync(resolve(dir, "package.json"))) { + roots.push(dir); + break; + } + const up = dirname(dir); + if (up === dir) break; + dir = up; + } + } catch { + // No module URL (a CJS bundle): the environment is the only source. + } + for (const root of roots) { + for (const rel of [["bin", "failproofai.mjs"], ["dist", "cli.mjs"]]) { + try { + out.add(realpathSync(resolve(root, ...rel))); + } catch { + // not in this layout + } + } + } + return out; +} + +/** + * The strict test the report exemption uses (stricter than `isOurMcpEntry`, + * which install and uninstall use and which trusts any command whose name + * contains `failproofai`): a stdio entry whose command, followed through every + * symlink, IS this failproofai's own CLI entry point, run as `mcp --agent + * ` and nothing else. A loopback HTTP entry is not accepted: sync + * writes none any more, and the hook cannot cheaply prove which process + * answers that port, so it takes the policy path until sync moves it to stdio. + */ +export function selfReportEntryStrictlyOurs( + entry: unknown, + agent: IntegrationType, + ownEntries: Set = selfReportOwnCliEntries(), + container?: string[], +): boolean { + if (!entry || typeof entry !== "object" || Array.isArray(entry)) return false; + const e = entry as Record; + if (["url", "serverUrl", "uri"].some((k) => e[k] !== undefined)) return false; + let command: unknown; + let args: unknown; + if (Array.isArray(e.command)) { + command = e.command[0]; + args = e.command.slice(1); + } else { + command = typeof e.command === "string" ? e.command : e.cmd; + args = e.args; + } + if (typeof command !== "string" || !command.startsWith("/")) return false; + if (!Array.isArray(args) || args.length !== 3 || args[0] !== "mcp" || args[1] !== "--agent" || args[2] !== agent) return false; + // Nothing beyond what the installer writes for this agent: an `env` + // (NODE_OPTIONS, PATH, LD_PRELOAD, BUN_*…), an `envFile`, a `cwd`, a + // wrapper or any other field can change what runs while the command stays + // ours (review round 3). + const target = SELF_REPORT_MCP_TARGETS[agent]; + if (!target) return false; + const containers = container ? [container] : [["mcpServers"], ["mcp"], ["mcp", "servers"], ["mcp_servers"], ["extensions"]]; + const transport: SelfReportTransport = { kind: "stdio", command, args: selfReportStdioArgs(agent) }; + if (!containers.some((c) => sameShape(e, target.entry(transport, c)))) return false; + let real: string; + try { + real = realpathSync(command); + } catch { + return false; + } + return ownEntries.has(real); +} + +/** + * `entry` holds exactly the installer's `expected` fields and values (key order + * aside). The only extra fields allowed are an empty `env`/`envs`/`env_keys` + * (some agents add an empty one when they rewrite their file), which change + * nothing. + */ +function sameShape(entry: Record, expected: Record): boolean { + const canon = (v: unknown): string => + JSON.stringify(v, (_k, x: unknown) => + x && typeof x === "object" && !Array.isArray(x) + ? Object.fromEntries(Object.entries(x as Record).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))) + : x, + ); + for (const [k, v] of Object.entries(entry)) { + if (k in expected) continue; + const empty = (Array.isArray(v) && v.length === 0) || (!!v && typeof v === "object" && !Array.isArray(v) && Object.keys(v).length === 0); + if (!(["env", "envs", "env_keys"].includes(k) && empty)) return false; + } + for (const [k, v] of Object.entries(expected)) { + if (canon(entry[k]) !== canon(v)) return false; + } + return true; +} + +/** + * Whether the `failproofai_local` server `agent` would talk to from `cwd` is + * failproofai's, so its `report` tool may skip the policies (the hook's early + * allow). Fails closed: anything that cannot be shown to be ours is not. + * + * - The user-scope entry must be strictly ours (`selfReportEntryStrictlyOurs`: + * a stdio command that resolves to this failproofai's own CLI entry point, + * `mcp --agent `), in every file the agent reads (one per + * Hermes/OpenClaw profile). A foreign program merely named like ours is not. + * - For an agent whose tool comes from failproofai's own plugin (Pi, Hermes, + * OpenClaw), there must be no foreign entry of that name: one would collide + * with our tool's name. + * - No project-scope config at or above `cwd` may define the name at all + * (failproofai never writes one there), and `cwd` must be known. Hermes and + * OpenClaw read no project config, so for them only the user files count. + */ +export function selfReportRegistrationOwned(agent: IntegrationType, cwd: string | undefined): boolean { + const target = SELF_REPORT_MCP_TARGETS[agent]; + if (!target) return false; + const projectScoped = !USER_SCOPE_ONLY.includes(agent); + if (projectScoped && (typeof cwd !== "string" || cwd.trim() === "")) return false; + try { + let ours = false; + const ownEntries = selfReportOwnCliEntries(); + for (const path of target.paths()) { + if (!existsSync(path)) continue; + const ops = opsFor(target, path); + const cur = ops.current(); + if (cur.state === "foreign") return false; + if (cur.state === "ours") { + if (!selfReportEntryStrictlyOurs(cur.entry, agent, ownEntries, ops.container)) return false; + ours = true; + } + } + if (!ours && !target.extension) return false; + return !projectScoped || !projectDefinesSelfReportServer(cwd as string); + } catch { + return false; + } +} + +/** + * Project files each agent reads MCP servers from, where that is known to be + * narrower than every file in `PROJECT_MCP_FILES` (the default). + */ +const PROJECT_MCP_FILES_BY_AGENT: Partial> = { + opencode: ["opencode.json", "opencode.jsonc", ".opencode/opencode.json", ".opencode/opencode.jsonc"], + antigravity: [".gemini/settings.json", ".gemini/config/mcp_config.json"], +}; + +/** User-scope files `agent` may also read servers or tools from, beside the ones sync writes. */ +function extraUserServerFiles(agent: IntegrationType): string[] { + if (agent === "opencode") { + const dirs = [resolve(homedir(), ".config", "opencode")]; + const xdg = process.env.XDG_CONFIG_HOME?.trim(); + if (xdg) dirs.push(resolve(xdg, "opencode")); + const out = dirs.flatMap((d) => ["opencode.json", "opencode.jsonc", "config.json"].map((f) => resolve(d, f))); + const explicit = process.env.OPENCODE_CONFIG?.trim(); + if (explicit) out.push(resolve(explicit)); + return out; + } + if (agent === "antigravity") return [resolve(homedir(), ".gemini", "settings.json")]; + return []; +} + +/** + * Directories of OpenCode custom tools: a file there defines a tool named + * after it (``, or `_` for each further export), so it + * flattens like a server does. + */ +function opencodeToolDirs(projectDirs: readonly string[]): string[] { + const roots = [resolve(homedir(), ".config", "opencode")]; + const xdg = process.env.XDG_CONFIG_HOME?.trim(); + if (xdg) roots.push(resolve(xdg, "opencode")); + for (const d of projectDirs) roots.push(resolve(d, ".opencode")); + return roots.flatMap((r) => [resolve(r, "tool"), resolve(r, "tools")]); +} + +/** + * Every server name in one config file: the keys of each server map, and any + * entry's own `name` (Goose names an extension by it). `ours` marks the entry + * under our own key, whose names are our registration's. Throws when unreadable. + */ +function serverNamesIn(path: string, extraContainers: readonly string[][] = []): ServerName[] { + const text = readFileSync(path, "utf8"); + let doc: unknown; + if (path.endsWith(".toml")) { + doc = parseToml(text); + } else if (path.endsWith(".yaml") || path.endsWith(".yml")) { + doc = parseYaml(text); + } else { + const errors: ParseError[] = []; + doc = parseJsonc(text, errors, { allowTrailingComma: true }); + if (errors.length > 0) throw new UnreadableAgentConfigError(path, "it is not valid JSON"); + } + return serverNamesInDoc(doc, extraContainers); +} + +interface ServerName { + name: string; + ours: boolean; +} + +function serverNamesInDoc(doc: unknown, extraContainers: readonly string[][] = []): ServerName[] { + const out: ServerName[] = []; + for (const container of [...PROJECT_MCP_CONTAINERS, ...extraContainers]) { + const holder = getIn(doc, container); + if (!holder || typeof holder !== "object" || Array.isArray(holder)) continue; + for (const [key, value] of Object.entries(holder as Record)) { + const ours = key === SELF_REPORT_SERVER_NAME; + out.push({ name: key, ours }); + const name = value && typeof value === "object" ? (value as Record).name : undefined; + if (typeof name === "string") out.push({ name, ours: ours && name === SELF_REPORT_SERVER_NAME }); + } + } + return out; +} + +/** + * Whether some OTHER server or tool `agent` can see could be the one the hook + * names `toolName`, so the name alone cannot say the call is our report tool + * (review #1105). An agent that joins server and tool with a single character + * makes that possible: on OpenCode server `failproofai` + tool `local_report` + * is `failproofai_local_report`, our tool's name there, and on Hermes and + * Antigravity server `failproofai` + tool `local_report` is + * `mcp_failproofai_local_report`. Any server whose name (as written, or with + * every character outside `[a-z0-9_]` read as `_`, the way agents sanitise + * names) followed by the separator starts our name counts: its tool list is + * not ours to read, so it could hold the rest. + * + * Reads the agent's user files and every project file at or above `cwd` it + * may read. True (no exemption) for a name that is not `agent`'s own spelling, + * and whenever a file cannot be read or parsed. + */ +export function selfReportNameCollides(agent: IntegrationType, cwd: string | undefined, toolName: unknown): boolean { + const f = selfReportFlatteningOf(toolName, agent); + if (!f) return true; + const want = `${f.prefix}${SELF_REPORT_SERVER_NAME}${f.sep}${SELF_REPORT_TOOL_NAME}`; + const collides = (server: string | ServerName): boolean => { + if (typeof server !== "string") return !server.ours && collides(server.name); + const lower = server.toLowerCase(); + return [lower, lower.replace(/[^a-z0-9_]/g, "_")].some((s) => { + const head = `${f.prefix}${s}${f.sep}`; + return s !== "" && want.length > head.length && want.startsWith(head); + }); + }; + try { + const target = SELF_REPORT_MCP_TARGETS[agent]; + if (!target) return true; + const dirs: string[] = []; + if (!USER_SCOPE_ONLY.includes(agent)) { + if (typeof cwd !== "string" || cwd.trim() === "") return true; + for (let d = resolve(cwd); ; d = dirname(d)) { + dirs.push(d); + if (dirname(d) === d) break; + } + } + const files = [...target.paths(), ...extraUserServerFiles(agent)]; + const rels = PROJECT_MCP_FILES_BY_AGENT[agent] ?? PROJECT_MCP_FILES; + for (const dir of dirs) for (const rel of rels) files.push(resolve(dir, rel)); + for (const path of files) { + if (!existsSync(path)) continue; + if (serverNamesIn(path).some(collides)) return true; + } + if (agent === "claude") { + const claudeJson = claudeUserConfigPath(); + if (existsSync(claudeJson)) { + const errors: ParseError[] = []; + const doc = parseJsonc(readFileSync(claudeJson, "utf8"), errors, { allowTrailingComma: true }) as Record | undefined; + if (errors.length > 0 || !doc || typeof doc !== "object") return true; + const projects = doc.projects as Record | undefined; + for (const dir of dirs) { + if (projects && typeof projects === "object" && serverNamesInDoc(projects[dir]).some(collides)) return true; + } + } + } + if (agent === "opencode") { + for (const toolDir of opencodeToolDirs(dirs)) { + if (!existsSync(toolDir)) continue; + for (const file of readdirSync(toolDir)) { + const stem = file.replace(/\.[^.]*$/, ""); + if (stem.toLowerCase() === want || collides(stem)) return true; + } + } + } + return false; + } catch { + return true; + } +} + +function applySelfReportMcp(opts: SyncSelfReportMcpOptions, enabled: boolean, daemonHere: boolean): SelfReportMcpResult[] { + const settings = opts.deps?.settings ?? readSelfReportMcpSettings(); + const agents = opts.agents ?? INTEGRATION_TYPES; + const hooked = opts.deps?.hooksInstalled ?? defaultHooksInstalled; + const also = new Set(opts.alsoHooked ?? []); + const hookRecords = + opts.deps?.hookRecords ?? + ((a: IntegrationType) => selfReportHookState(a, { userHooksInstalled: (x) => hooked(x as IntegrationType) }).recorder === "hook"); + let cliPath: string | null | undefined = opts.binaryPath; + const results: SelfReportMcpResult[] = []; + + for (const agent of agents) { + const target = SELF_REPORT_MCP_TARGETS[agent]; + if (!target) { + results.push({ agent, path: "", action: "skipped", transport: null, status: "unsupported" }); + continue; + } + let paths: string[]; + try { + paths = target.paths(); + } catch (err) { + results.push({ agent, path: "", action: "skipped", transport: null, status: "error", detail: errText(err) }); + continue; + } + const agentHooked = enabled && (also.has(agent) || hooked(agent)); + + if (target.extension) { + for (const path of paths) { + try { + const ops = existsSync(path) ? opsFor(target, path) : null; + const cur = ops?.current(); + if (ops && cur?.state === "ours") { + ops.write(null); + results.push({ agent, path, action: "removed", transport: transportOf(cur.entry), status: "ok" }); + } + } catch (err) { + results.push({ agent, path, action: "skipped", transport: null, status: "error", detail: errText(err) }); + } + } + results.push({ + agent, path: "", action: "unchanged", transport: agentHooked ? "extension" : null, + status: enabled && !agentHooked ? "not-hooked" : "ok", + }); + continue; + } + + let chosen: SelfReportTransport | null | undefined; + const transportFor = (): SelfReportTransport | null => { + if (chosen !== undefined) return chosen; + chosen = null; + // HTTP only while the hook will record: an untrusted Codex, or a Claude + // Code with hooks off, gets stdio, whose server records what the hook + // did not. + if (daemonHere && selfReportHttpAllowed(agent, opts.deps?.httpAgents) && hookRecords(agent)) { + chosen = { kind: "http", url: selfReportHttpUrl(settings.port, agent) }; + } else { + if (cliPath === undefined) cliPath = (opts.deps?.resolveCliPath ?? resolveSelfReportCliPath)(); + if (cliPath) chosen = { kind: "stdio", command: cliPath, args: selfReportStdioArgs(agent) }; + } + return chosen; + }; + + for (const path of paths) { + // No hooks detected (user scope), but our entry is already in this file: + // keep it and repair its transport. A file without ours is left alone. + let wantIt = agentHooked; + if (enabled && !wantIt) { + let owned = false; + try { + owned = existsSync(path) && opsFor(target, path).current().state === "ours"; + } catch { + owned = false; + } + if (!owned) { + results.push({ agent, path, action: "skipped", transport: null, status: "not-hooked" }); + continue; + } + wantIt = true; + } + const transport = wantIt ? transportFor() : null; + if (wantIt && !transport) { + results.push({ + agent, path, action: "skipped", transport: null, status: "error", + detail: "no daemon is answering here and the failproofai CLI was not found for stdio", + }); + continue; + } + try { + if (!wantIt && !existsSync(path)) { + results.push({ agent, path, action: "unchanged", transport: null, status: "ok" }); + continue; + } + const ops = opsFor(target, path); + const cur = ops.current(); + if (cur.state === "foreign") { + results.push({ + agent, path, action: "skipped", transport: null, status: "conflict", + detail: `a "${SELF_REPORT_SERVER_NAME}" MCP server that failproofai did not write is already configured`, + }); + continue; + } + if (!wantIt) { + if (cur.state === "absent") { + results.push({ agent, path, action: "unchanged", transport: null, status: "ok" }); + } else { + ops.write(null); + results.push({ agent, path, action: "removed", transport: transportOf(cur.entry), status: "ok" }); + } + continue; + } + const desired = target.entry(transport!, ops.container); + if (cur.state === "ours" && sameEntry(cur.entry, desired)) { + results.push({ agent, path, action: "unchanged", transport: transport!.kind, status: "ok" }); + continue; + } + ops.write(desired); + results.push({ agent, path, action: cur.state === "ours" ? "updated" : "added", transport: transport!.kind, status: "ok" }); + } catch (err) { + results.push({ agent, path, action: "skipped", transport: null, status: "error", detail: errText(err) }); + } + } + + if (target.companion) { + // Kept while our entry is registered somewhere for this agent. + const registered = results.some( + (r) => r.agent === agent && r.status === "ok" && r.transport !== null && r.action !== "removed", + ); + try { + target.companion.sync(enabled && registered); + } catch (err) { + results.push({ agent, path: target.companion.path(), action: "skipped", transport: null, status: "error", detail: errText(err) }); + } + } + } + + if (!opts.quiet) for (const line of selfReportSyncLines(results)) console.log(line); + return results; +} + +/** Remove our entries from every agent (or `agents`), whatever the settings say. Needs no live check. */ +export function removeSelfReportMcp(opts: Omit = {}): SelfReportMcpResult[] { + const results = applySelfReportMcp({ ...opts, enabled: false }, false, false); + logSelfReportSync(results); + return results; +} + +/** Whether a sync changed any agent's file. */ +export function selfReportSyncChanged(results: readonly SelfReportMcpResult[]): boolean { + return results.some((r) => r.action === "added" || r.action === "updated" || r.action === "removed"); +} + +function errText(err: unknown): string { + return err instanceof Error ? err.message : String(err); +} + +/** What to do when cursor-agent has not loaded the server yet. */ +export const SELF_REPORT_CURSOR_APPROVAL_HINT = + "cursor-agent: if `cursor-agent mcp list` shows failproofai_local as needing approval, run `cursor-agent mcp enable failproofai_local`"; + +/** One line per change, conflict or error; nothing for an agent left as it was. */ +export function selfReportSyncLines(results: readonly SelfReportMcpResult[]): string[] { + const out: string[] = []; + for (const r of results) { + const name = displayName(r.agent); + if (r.action === "added" || r.action === "updated") { + out.push(`✓ Self Reports MCP server ${r.action === "added" ? "added to" : "updated in"} ${name} (${r.transport}): ${r.path}`); + if (r.agent === "cursor") out.push(` ${SELF_REPORT_CURSOR_APPROVAL_HINT}`); + } else if (r.action === "removed") { + out.push(`✓ Self Reports MCP server removed from ${name}: ${r.path}`); + } else if (r.status === "conflict" || r.status === "error") { + out.push(`! ${name}: Self Reports MCP server not changed in ${r.path || "its config"}: ${r.detail ?? r.status}`); + } + } + return out; +} + +/** The distinct agents among `results` that match `pick`, in order. */ +function agentsWhere(results: readonly SelfReportMcpResult[], pick: (r: SelfReportMcpResult) => boolean): IntegrationType[] { + const out: IntegrationType[] = []; + for (const r of results) if (pick(r) && !out.includes(r.agent)) out.push(r.agent); + return out; +} + +/** Agents a sync left registered (any transport, Pi's extension included). */ +export function selfReportRegisteredAgents(results: readonly SelfReportMcpResult[]): IntegrationType[] { + return agentsWhere(results, (r) => r.status === "ok" && r.action !== "removed" && r.transport !== null); +} + +/** Agents a sync could not update (an error, or a `failproofai_local` that is not ours). */ +export function selfReportFailedAgents(results: readonly SelfReportMcpResult[]): IntegrationType[] { + return agentsWhere(results, (r) => r.status === "error" || r.status === "conflict"); +} + +/** + * The one line every command but `sync` and `status` prints about Self + * Reports, or null for nothing to say. `state` is the setting + * (`selfReportSettingsState`), or `removed` for a command that took the + * entries out of the agents it unhooked. A failure is named in the same line. + */ +export function selfReportSummaryLine( + results: readonly SelfReportMcpResult[], + state: "on" | "off" | "waiting" | "unreadable" | "removed", +): string | null { + const s = selfReportSummary(results, state); + if (!s) return null; + return s.ok ? `✓ ${s.text}` : `▲ ${s.text} · ${s.fix}`; +} + +/** `selfReportSummaryLine` before it is drawn: for a caller with its own screen kit. */ +export function selfReportSummary( + results: readonly SelfReportMcpResult[], + state: "on" | "off" | "waiting" | "unreadable" | "removed", +): { ok: boolean; text: string; fix?: string } | null { + const failed = selfReportFailedAgents(results).map(displayName); + const n = (k: number) => `${k} ${k === 1 ? "agent" : "agents"}`; + let text: string | null; + if (state === "on") { + const on = selfReportRegisteredAgents(results).length; + text = on > 0 ? `Self Reports: on for ${n(on)}` : null; + } else if (state === "removed") { + const removed = agentsWhere(results, (r) => r.action === "removed").length; + text = removed > 0 ? `Self Reports: removed from ${n(removed)}` : null; + } else { + text = state === "waiting" ? "Self Reports: off until Cloud sends this machine's setting" : "Self Reports: off"; + } + if (failed.length === 0) return text ? { ok: true, text } : null; + const problem = `not updated for ${failed.join(", ")}`; + return { ok: false, text: text ? `${text}; ${problem}` : `Self Reports: ${problem}`, fix: "failproofai self-report sync" }; +} + +/** + * The daemon-log summary of one sync: `added claude (http), cursor (stdio); + * removed pi; failed codex (reason)`, or null when nothing changed or failed. + * Agents and transports only, never a path: the line can leave the machine as + * part of its machine logs. + */ +export function selfReportSyncLogLine(results: readonly SelfReportMcpResult[]): string | null { + const parts: string[] = []; + const list = (action: SelfReportMcpAction) => + results + .filter((r) => r.action === action) + .map((r) => (r.transport && action !== "removed" ? `${r.agent} (${r.transport})` : r.agent)) + .filter((v, i, all) => all.indexOf(v) === i); + for (const action of ["added", "updated", "removed"] as const) { + const items = list(action); + if (items.length > 0) parts.push(`${action} ${items.join(", ")}`); + } + const failed = results + .filter((r) => r.status === "error" || r.status === "conflict") + .map((r) => `${r.agent} (${r.status === "conflict" ? "another failproofai_local server is configured" : (r.detail ?? "error").slice(0, 120)})`); + if (failed.length > 0) parts.push(`failed ${failed.join(", ")}`); + return parts.length > 0 ? parts.join("; ") : null; +} + +function displayName(agent: IntegrationType): string { + try { + return getIntegration(agent).displayName; + } catch { + return agent; + } +} + +// ── Status ────────────────────────────────────────────────────────────────── + +export interface SelfReportRegistration { + agent: IntegrationType; + path: string; + /** failproofai hooks are installed for this agent (user scope). */ + hooked: boolean; + /** Our entry is in this file (or, for Pi, its extension offers the tool). */ + registered: boolean; + transport: "http" | "stdio" | "extension" | null; + /** The URL (http) or command (stdio) our entry points at. */ + endpoint: string | null; + /** A `failproofai_local` server that is not ours is there. */ + conflict: boolean; + /** The file could not be read. */ + error?: string; +} + +/** Per-agent, per-file registration state, for `failproofai self-report status`. Writes nothing. */ +export function selfReportRegistrationStatus( + opts: { agents?: readonly IntegrationType[]; hooksInstalled?: (agent: IntegrationType) => boolean } = {}, +): SelfReportRegistration[] { + const hooked = opts.hooksInstalled ?? defaultHooksInstalled; + const out: SelfReportRegistration[] = []; + for (const agent of opts.agents ?? INTEGRATION_TYPES) { + const target = SELF_REPORT_MCP_TARGETS[agent]; + if (!target) continue; + const isHooked = hooked(agent); + if (target.extension) { + out.push({ agent, path: "", hooked: isHooked, registered: isHooked, transport: isHooked ? "extension" : null, endpoint: null, conflict: false }); + continue; + } + let paths: string[] = []; + try { + paths = target.paths(); + } catch (err) { + out.push({ agent, path: "", hooked: isHooked, registered: false, transport: null, endpoint: null, conflict: false, error: errText(err) }); + continue; + } + for (const path of paths) { + if (!existsSync(path)) { + out.push({ agent, path, hooked: isHooked, registered: false, transport: null, endpoint: null, conflict: false }); + continue; + } + try { + const cur = opsFor(target, path).current(); + out.push({ + agent, path, hooked: isHooked, + registered: cur.state === "ours", + transport: cur.state === "ours" ? transportOf(cur.entry) : null, + endpoint: cur.state === "ours" ? endpointOf(cur.entry) : null, + conflict: cur.state === "foreign", + }); + } catch (err) { + out.push({ agent, path, hooked: isHooked, registered: false, transport: null, endpoint: null, conflict: false, error: errText(err) }); + } + } + } + return out; +} + diff --git a/src/hooks/self-report-log.ts b/src/hooks/self-report-log.ts new file mode 100644 index 000000000..4dd4d29fe --- /dev/null +++ b/src/hooks/self-report-log.ts @@ -0,0 +1,166 @@ +/** + * Self Reports events for the daemon's log, from processes outside it: the + * stdio MCP server (`failproofai mcp`, a child of each agent) and the CLI's + * `self-report sync`. + * + * The daemon's log is what machine logs ship (crates/failproofaid/src/logship.rs), + * so an event belongs there and nowhere else. It goes over the daemon's own + * socket as one `selfReportLog` frame (crates/PROTOCOL.md): one-way, no reply + * read. An older daemon cannot parse the type and closes the connection, so + * it is dropped. No daemon, a slow one, or any error: dropped too, inside + * `SELF_REPORT_LOG_BUDGET_MS`. Nothing here ever throws or holds up an agent. + * + * A report's detail is sent as the agent sent it, before the 2000-code-point + * report cut, bounded at 64 KiB: the daemon scrubs secrets from the whole text + * and only then cuts it for the log line. Cutting it here first cut long credentials (a JWT past 200 + * characters) into pieces the scrubber no longer recognised (F18). The model's + * category is sent whole too, and the daemon shows it only when it is shaped + * like a category name (F20). + * + * Top-level names are prefixed for the same bundle reason as self-report.ts. + */ +import { existsSync } from "node:fs"; +import { createConnection } from "node:net"; +import { daemonSocket } from "./fp-home"; +import { SELF_REPORT_DETAIL_MAX, selfReportClip, selfReportCutDetail } from "./self-report-names"; + + +/** The whole budget for one event, connect to close. */ +export const SELF_REPORT_LOG_BUDGET_MS = 250; +/** How late a budget timer may fire before it counts as a blocked event loop, not a slow daemon. */ +export const SELF_REPORT_LOG_LATE_MS = 50; +/** + * How much detail is sent: the detail AS SENT, not the 2,000-character report + * (a credential straddling that cut was split into something the daemon's + * scrubber no longer recognised, F18), bounded like the daemon's own HTTP + * body (64 KiB). The daemon scrubs all of it, then logs at most 40 characters. + */ +export const SELF_REPORT_LOG_PREVIEW_CHARS = 64 * 1024; +/** How much of an inferred report's raw category is sent: all of it, for the same reason. */ +export const SELF_REPORT_LOG_RAW_CATEGORY_CHARS = SELF_REPORT_DETAIL_MAX; +const SELF_REPORT_LOG_PROTOCOL_VERSION = 2; + +export interface SelfReportLogEvent { + event: "initialize" | "tools/list" | "tools/call" | "sync" | "error"; + agent?: string; + transport?: "stdio" | "cli"; + outcome?: string; + reason?: string; + category?: string; + /** False when `category` was resolved from something the model sent that is not on the list. */ + knownCategory?: boolean; + /** What the model sent as the category (maybe empty), when `category` was inferred; cut before sending. */ + rawCategory?: string; + session?: string; + /** The report's detail; bounded at `SELF_REPORT_LOG_PREVIEW_CHARS` here, scrubbed then cut by the daemon. */ + preview?: string; + summary?: string; +} + +const selfReportLogPending = new Set>(); + +function selfReportLogSocket(): string { + return process.env.FAILPROOFAI_DAEMON_SOCKET || daemonSocket(); +} + +/** + * Send one event, without waiting for it. Returns the send, which always + * resolves (in at most the budget); callers that are about to exit may await + * `flushSelfReportLogs` instead. + */ +export function sendSelfReportLog(event: SelfReportLogEvent): Promise { + const sent = selfReportLogSend(event); + selfReportLogPending.add(sent); + void sent.then(() => selfReportLogPending.delete(sent)); + return sent; +} + +/** Wait for every event still in flight, at most `maxMs`. */ +export async function flushSelfReportLogs(maxMs: number = SELF_REPORT_LOG_BUDGET_MS): Promise { + if (selfReportLogPending.size === 0) return; + let timer: ReturnType | undefined; + await Promise.race([ + Promise.all([...selfReportLogPending]), + new Promise((done) => { + timer = setTimeout(done, maxMs); + timer.unref?.(); + }), + ]); + if (timer) clearTimeout(timer); +} + +function selfReportLogSend(event: SelfReportLogEvent): Promise { + return new Promise((resolve) => { + let path: string; + let frame: Buffer; + try { + if (process.platform === "win32") return resolve(); + path = selfReportLogSocket(); + if (!existsSync(path)) return resolve(); + const body = Buffer.from( + JSON.stringify({ + type: "selfReportLog", + protocolVersion: SELF_REPORT_LOG_PROTOCOL_VERSION, + event: { + ...event, + // Bounded without leaving part of a token at the cut (F18): a + // fragment is what the daemon's scrubber cannot recognise. + ...(event.preview !== undefined ? { preview: selfReportCutDetail(event.preview, SELF_REPORT_LOG_PREVIEW_CHARS) } : {}), + ...(event.rawCategory !== undefined ? { rawCategory: selfReportClip(event.rawCategory, SELF_REPORT_LOG_RAW_CATEGORY_CHARS) } : {}), + }, + }), + "utf8", + ); + const header = Buffer.alloc(4); + header.writeUInt32BE(body.length, 0); + frame = Buffer.concat([header, body]); + } catch { + return resolve(); + } + let settled = false; + const socket = createConnection({ path }); + const done = (): void => { + if (settled) return; + settled = true; + clearTimeout(timer); + socket.removeAllListeners(); + socket.on("error", () => {}); + socket.destroy(); + resolve(); + }; + // A timer that fires late means the event loop was blocked (a synchronous + // call elsewhere), not that the daemon is slow: the connect may already be + // done and simply not delivered yet. Give it one more budget before + // dropping, so a busy process never reads as an unreachable daemon (#1024). + // + // The budget timer is NOT unref'd: it is what keeps the process alive + // while a send is in flight, and it bounds that to the budget (one more + // when it fires late). Unref'd along with the socket, a process whose + // other work had finished saw a pending flush with nothing keeping the + // loop alive and exited 13 (unsettled top-level await) instead of waiting + // the few milliseconds for the daemon to close. `done` clears it. + let armedAt = Date.now(); + let extended = false; + const expire = (): void => { + const late = Date.now() - armedAt - SELF_REPORT_LOG_BUDGET_MS; + if (!extended && late > SELF_REPORT_LOG_LATE_MS) { + extended = true; + armedAt = Date.now(); + timer = setTimeout(expire, SELF_REPORT_LOG_BUDGET_MS); + return; + } + done(); + }; + let timer = setTimeout(expire, SELF_REPORT_LOG_BUDGET_MS); + socket.unref(); + socket.on("error", done); + socket.on("close", done); + socket.on("connect", () => { + // Half-close and wait for the daemon to close its side (`close` above), + // not just for our write to finish: on macOS a connection the daemon has + // not accepted yet is dropped, data and all, when the client destroys it, + // so tearing down on `finish` lost every line after the first. + socket.end(frame); + }); + }); +} diff --git a/src/hooks/self-report-mcp.ts b/src/hooks/self-report-mcp.ts new file mode 100644 index 000000000..5ab3f5263 --- /dev/null +++ b/src/hooks/self-report-mcp.ts @@ -0,0 +1,608 @@ +/** + * `failproofai mcp [--agent ]`: the Self Reports MCP server over + * stdio (newline-delimited JSON-RPC 2.0). + * + * The same server the daemon serves over HTTP, for agents that only speak stdio + * MCP and for environments with no reachable daemon (containers, CI). It needs + * no daemon: it reads `self-report.json` on every request and writes its + * fallback records straight into the custom-agents spool. + * + * Methods: `initialize` (with `instructions` while the feature is on), `ping`, `tools/list` (the report tool, or nothing + * while the feature is off), `tools/call` (always answers `Recorded.`). + * + * Recording (contract §8): an agent whose hooks see MCP calls (Claude Code, + * Codex, Cursor) is recorded by its PreToolUse hook, so this server writes + * nothing for it. For an agent in `SELF_REPORT_SERVER_RECORDS` the server + * appends one `self_report` event itself, attributed to the newest session of + * that agent seen by the hooks in the last 6 hours: in this working directory, + * else in one above or below it, else anywhere (`selfReportFindSessionMatch`). + * + * Nothing but JSON-RPC goes to stdout: a stray byte there corrupts the agent's + * MCP stream. Diagnostics go to stderr. + * + * Top-level names are prefixed for the same bundle reason as self-report.ts. + */ +import { closeSync, fsyncSync, mkdirSync, openSync, readdirSync, readSync, renameSync, rmSync, statSync, writeSync, constants as fsConstants } from "node:fs"; +import { homedir } from "node:os"; +import { join } from "node:path"; +import { createInterface } from "node:readline"; +import type { Readable, Writable } from "node:stream"; +import { version as selfReportCliVersion } from "../../package.json"; +import { customAgentsEventsDir } from "./fp-home"; +import { getHookActivityEntriesSince } from "./hook-activity-store"; +import { + SELF_REPORT_RESULT_TEXT, + SELF_REPORT_SERVER_NAME, + SELF_REPORT_SERVER_RECORDS, + SELF_REPORT_TOOL_NAME, + describeSelfReportTool, + readEnabledSelfReport, + resolveSelfReportCategory, + selfReportArgs, + selfReportClip, + selfReportCutDetail, + selfReportInputSchema, + selfReportInstructions, + selfReportSettingsState, +} from "./self-report"; +import { SELF_REPORT_LOG_PREVIEW_CHARS, flushSelfReportLogs, sendSelfReportLog } from "./self-report-log"; +import { selfReportAgentPidOf, selfReportServerAgentPid } from "./self-report-ancestry"; + +/** + * Set to `1` in the server's environment (by `self-report test`), it writes one + * receipt line to stderr for each report it published, naming the batch file: + * `[failproofai mcp] recorded: `. The file itself is no proof: a running + * collector can upload and delete it before anyone looks. + */ +export const SELF_REPORT_RECEIPT_ENV = "FAILPROOFAI_SELF_REPORT_RECEIPT"; +export const SELF_REPORT_RECEIPT_PREFIX = "[failproofai mcp] recorded: "; + +/** How far back a hook-activity session may be and still own a report. */ +export const SELF_REPORT_SESSION_WINDOW_MS = 6 * 60 * 60 * 1000; +const SELF_REPORT_DEFAULT_PROTOCOL = "2025-06-18"; + +let selfReportBatchSeq = 0; + +export interface SelfReportMcpOptions { + /** The integration this server was registered for (`--agent`). */ + agent?: string; + /** Working directory used for session attribution; defaults to process.cwd(). */ + cwd?: string; + input?: Readable; + output?: Writable; + /** Clock override for tests. */ + now?: () => number; +} + +/** The tool list the server advertises right now. */ +export function selfReportToolList(): Array> { + const settings = readEnabledSelfReport(); + if (!settings) return []; + return [ + { + name: SELF_REPORT_TOOL_NAME, + description: describeSelfReportTool(settings.categories, settings.guidance), + inputSchema: selfReportInputSchema(settings.categories), + }, + ]; +} + +/** + * The initialize result's `instructions`, or undefined while the feature is + * off (the field is then left out). Read at initialize time: a client reads it + * once per connection. + */ +export function selfReportServerInstructions(): string | undefined { + const settings = readEnabledSelfReport(); + if (!settings) return undefined; + return selfReportInstructions(settings.categories, settings.guidance); +} + +// ── Session attribution ───────────────────────────────────────────────────── + +/** + * How closely a hook row's cwd matches the server's: 2 the same directory, 1 an + * ancestor or descendant of it, 0 unrelated (or unknown). Trailing slashes are + * ignored; `/` is an ancestor of every absolute path. + */ +export function selfReportCwdAffinity(want: string, have: unknown): 0 | 1 | 2 { + if (typeof have !== "string" || have === "") return 0; + const a = want.replace(/\/+$/, ""); + const b = have.replace(/\/+$/, ""); + if (a === b) return 2; + if (a === "" || b === "") return 1; + return b.startsWith(`${a}/`) || a.startsWith(`${b}/`) ? 1 : 0; +} + +/** A hook session that owns a report, and the cwd its row had. */ +export interface SelfReportSessionMatch { + sessionId: string; + cwd: string | undefined; +} + +/** + * The hook-activity session a report from `integration` belongs to, seen by + * the hooks within the window (6 h), or null. Most specific first: the newest + * session whose row has exactly this `cwd`; else the newest whose cwd is an + * ancestor or descendant of it. The stdio server's cwd is wherever the agent + * started it, which is often not the project (Hermes runs it from its own + * directory), so with no related row the agent's newest session is still + * taken, but only when every one of its rows in the window has the same cwd: + * with several projects to choose from that would be a guess, and the report + * is `unattributed` instead. The daemon's HTTP fallback + * (crates/fpai-collect/src/self_report.rs `find_session`) ranks the same way. + * + * Reads every activity page that can hold a row from the window + * (`getHookActivityEntriesSince`), not just the newest ones: `current.jsonl` + * rotates every 25 rows, so another busy project's hooks can push this + * project's rows several pages back within minutes. + * + * The agent process comes first (F14). Hook rows carry the pid of the agent + * behind them (`agentPid`, on session-start, prompt and report rows). With + * `agentPid` known (this server's own agent), a session stamped with it is + * the answer, exactly; a session stamped only with another agent's pid is + * never taken, whatever directory it shares (an agent started inside + * another, in the same project, is its own session). Only sessions with no + * stamp at all (a hook that could not read its ancestry, rows from before + * this) are left to the directory ranking below. `excluded` receives the + * sessions known to be another agent's, for the transcript fallbacks. + */ +export function selfReportFindSessionMatch( + integration: string, + cwd: string | undefined, + now: number = Date.now(), + agentPid?: number, + excluded?: Set, +): SelfReportSessionMatch | null { + let entries: ReturnType; + try { + entries = getHookActivityEntriesSince(now - SELF_REPORT_SESSION_WINDOW_MS); + } catch { + return null; // No readable activity: nothing to attribute to. + } + const rows = (entries as unknown as Array>).filter((row) => { + const ts = typeof row.timestamp === "number" ? row.timestamp : NaN; + return ( + row.integration === integration && + typeof row.sessionId === "string" && + !!row.sessionId && + Number.isFinite(ts) && + now - ts <= SELF_REPORT_SESSION_WINDOW_MS && + ts - now <= 60_000 + ); + }); + if (agentPid !== undefined) { + const stamps = new Map>(); + for (const row of rows) { + const pid = selfReportAgentPidOf(row.agentPid); + if (pid === undefined) continue; + const set = stamps.get(row.sessionId as string) ?? new Set(); + set.add(pid); + stamps.set(row.sessionId as string, set); + } + let own: { ts: number; id: string; cwd: string | undefined } | null = null; + for (const row of rows) { + if (!stamps.get(row.sessionId as string)?.has(agentPid)) continue; + const ts = row.timestamp as number; + if (!own || ts > own.ts) own = { ts, id: row.sessionId as string, cwd: typeof row.cwd === "string" && row.cwd ? row.cwd : undefined }; + } + if (own) return { sessionId: own.id, cwd: own.cwd }; + for (const [id, pids] of stamps) { + if (!pids.has(agentPid)) excluded?.add(id); + } + return selfReportRankSessions(rows.filter((row) => !stamps.has(row.sessionId as string)), cwd); + } + return selfReportRankSessions(rows, cwd); +} + +/** The directory ranking of `selfReportFindSessionMatch`, over rows already in the window. */ +function selfReportRankSessions(rows: Array>, cwd: string | undefined): SelfReportSessionMatch | null { + let best: { rank: number; ts: number; id: string; cwd: string | undefined } | null = null; + // The distinct cwds of this integration's rows, to tell one project from several. + const cwds = new Set(); + for (const row of rows) { + const ts = row.timestamp as number; + const rowCwd = typeof row.cwd === "string" && row.cwd ? row.cwd : undefined; + cwds.add(rowCwd === undefined ? "" : rowCwd.replace(/\/+$/, "") || "/"); + const rank = cwd ? selfReportCwdAffinity(cwd, row.cwd) : 0; + if (!best || rank > best.rank || (rank === best.rank && ts > best.ts)) { + best = { rank, ts, id: row.sessionId as string, cwd: rowCwd }; + } + } + if (!best || (best.rank === 0 && cwds.size > 1)) return null; + return { sessionId: best.id, cwd: best.cwd }; +} + +/** The session id of `selfReportFindSessionMatch`, or null. */ +export function selfReportFindSession(integration: string, cwd: string, now: number = Date.now()): string | null { + return selfReportFindSessionMatch(integration, cwd, now)?.sessionId ?? null; +} + +/** + * The agent id the collector files a hook event under (`agent_id` in + * crates/fpai-collect/src/sources/hooks/transform.rs): `-`, each part reduced to `[A-Za-z0-9._-]`, dashes collapsed, 48 + * characters. A report must land under the same agent as the session's hooks. + */ +export function selfReportAgentId(integration: string, cwd: string | undefined): string { + const clean = (s: string): string => + [...s] + .map((c) => (/[A-Za-z0-9._]/.test(c) ? c : "-")) + .join("") + .split("-") + .filter((p) => p !== "") + .join("-") + .slice(0, 48); + const base = clean(integration || "failproofai"); + const last = cwd?.replace(/\/+$/, "").split("/").filter((p) => p !== "").pop(); + const project = last ? clean(last) : ""; + return project ? `${base}-${project}` : base; +} + +/** `environment` as the collector stamps it: config.json's collector.environment, else "local". */ +async function selfReportEnvironment(): Promise { + try { + const { readConfig } = await import("./fp-config"); + return readConfig().collector.environment || "local"; + } catch { + return "local"; + } +} + +// ── The event file (SDK writer format) ────────────────────────────────────── + +export interface SelfReportEventInput { + integration: string; + category: string; + detail: string; + cwd: string; + now?: number; + /** Overrides session attribution (the `self-report test` command). */ + sessionId?: string; + /** This server's agent process (default: read from the process tree); see `selfReportFindSessionMatch`. */ + agentPid?: number | null; +} + +/** + * Write one `self_report` event as its own batch in the custom-agents spool, + * exactly as the SDK writers publish (`event---.jsonl`, written + * as `.tmp` with O_EXCL and 0600, fsynced, renamed; directory 0700). Returns + * the published path and the event. + */ +export async function writeSelfReportEvent(input: SelfReportEventInput): Promise<{ path: string; event: Record }> { + const now = input.now ?? Date.now(); + // Sessions the hooks show to be another agent process's: never taken, not + // even by the transcript fallbacks (an agent started inside another one, in + // the same directory, has its own session). + const excluded = new Set(); + const agentPid = input.agentPid === undefined ? selfReportServerAgentPid() : input.agentPid ?? undefined; + const fallback = (m: SelfReportSessionMatch | null) => (m && !excluded.has(m.sessionId) ? m : null); + const match = + input.sessionId === undefined + ? selfReportFindSessionMatch(input.integration, input.cwd, now, agentPid, excluded) ?? + (input.integration === "codex" + ? fallback(selfReportCodexRolloutSession(input.cwd, now, undefined, excluded)) + : input.integration === "claude" + ? fallback(selfReportClaudeTranscriptSession(input.cwd, now, undefined, excluded)) + : null) + : null; + const sessionId = input.sessionId ?? match?.sessionId ?? "unattributed"; + const event: Record = { + timestamp: new Date(now).toISOString(), + session_id: sessionId, + // The agent the session's hook rows are filed under: from the matched + // row's cwd, not the server's own (they differ when the agent starts the + // server elsewhere). + agent_id: selfReportAgentId(input.integration, match?.cwd ?? input.cwd), + type: "self_report", + category: selfReportClip(input.category), + detail: selfReportCutDetail(input.detail), + source: "mcp", + // Wire order as the SDK writers build it: environment after the event's own fields. + environment: await selfReportEnvironment(), + integration: input.integration, + }; + const dir = customAgentsEventsDir(); + mkdirSync(dir, { recursive: true, mode: 0o700 }); + const stamp = new Date(now).toISOString().replace(/[:.]/g, "-"); + const stem = `event-${stamp}-${process.pid}-${selfReportBatchSeq++}`; + const tmp = join(dir, `${stem}.tmp`); + const finalPath = join(dir, `${stem}.jsonl`); + try { + const fd = openSync(tmp, fsConstants.O_WRONLY | fsConstants.O_CREAT | fsConstants.O_EXCL, 0o600); + try { + writeSync(fd, `${JSON.stringify(event)}\n`); + fsyncSync(fd); + } finally { + closeSync(fd); + } + renameSync(tmp, finalPath); + } catch (err) { + rmSync(tmp, { force: true }); + throw err; + } + return { path: finalPath, event }; +} + +/** + * Whether this server records a report from `agent`: always for an agent in + * `SELF_REPORT_SERVER_RECORDS`; for Claude Code and Codex, whose hook is the + * recorder, only when that hook did not already record this call (same + * working directory, and each hook row vouches for one call) — it was + * not trusted (Codex), hooks are off (Claude Code), or none is installed where + * the agent runs. The hook runs before the agent sends the MCP call, so its + * row is already on disk (self-report-hook-trust.ts). + */ +export async function selfReportServerShouldRecord(agent: string, args: unknown, now?: number, cwd?: string): Promise { + if (SELF_REPORT_SERVER_RECORDS.includes(agent)) return true; + const { SELF_REPORT_HOOK_RECORDED_AGENTS, selfReportHookRecordedRecently } = await import("./self-report-hook-trust"); + if (!SELF_REPORT_HOOK_RECORDED_AGENTS.includes(agent)) return false; + return !selfReportHookRecordedRecently(agent, args ?? {}, now ?? Date.now(), cwd ?? process.cwd()); +} + +/** + * Codex's own record of its newest session in (or around) `cwd`, from its + * rollout files (`$CODEX_HOME/sessions/YYYY/MM/DD/rollout-*.jsonl`, whose first + * line is `session_meta` with the session `id` and `cwd`), for a report its + * hooks never saw: an untrusted Codex runs no hook, so there is no hook row to + * attribute to. The session id is the one Codex's hooks would have carried. + */ +export function selfReportCodexRolloutSession( + cwd: string, + now: number = Date.now(), + home: string = process.env.CODEX_HOME?.trim() || join(homedirForCodex(), ".codex"), + excluded: ReadonlySet = new Set(), +): SelfReportSessionMatch | null { + const dayDirs = new Set(); + for (const t of [now, now - SELF_REPORT_SESSION_WINDOW_MS]) { + const d = new Date(t); + const pad = (n: number) => String(n).padStart(2, "0"); + dayDirs.add(join(home, "sessions", String(d.getFullYear()), pad(d.getMonth() + 1), pad(d.getDate()))); + } + let best: { rank: number; mtime: number; id: string; cwd: string } | null = null; + for (const dir of dayDirs) { + let names: string[]; + try { + names = readdirSync(dir).filter((n) => n.startsWith("rollout-") && n.endsWith(".jsonl")); + } catch { + continue; + } + for (const name of names) { + const file = join(dir, name); + try { + const mtime = statSync(file).mtimeMs; + if (now - mtime > SELF_REPORT_SESSION_WINDOW_MS) continue; + const head = readFirstLine(file); + const meta = JSON.parse(head) as { type?: unknown; payload?: { id?: unknown; cwd?: unknown } }; + if (meta.type !== "session_meta" || typeof meta.payload?.id !== "string" || typeof meta.payload.cwd !== "string") continue; + if (excluded.has(meta.payload.id)) continue; + const rank = selfReportCwdAffinity(cwd, meta.payload.cwd); + if (rank === 0) continue; + if (!best || rank > best.rank || (rank === best.rank && mtime > best.mtime)) { + best = { rank, mtime, id: meta.payload.id, cwd: meta.payload.cwd }; + } + } catch { + // unreadable or not a rollout: skip it + } + } + } + return best ? { sessionId: best.id, cwd: best.cwd } : null; +} + +/** + * Claude Code's newest session in exactly `cwd`, from its transcripts + * (`/projects//.jsonl`), + * for a report its hooks never saw (`disableAllHooks`). + */ +export function selfReportClaudeTranscriptSession( + cwd: string, + now: number = Date.now(), + configDir: string = process.env.CLAUDE_CONFIG_DIR?.trim() || join(homedirForCodex(), ".claude"), + excluded: ReadonlySet = new Set(), +): SelfReportSessionMatch | null { + const dir = join(configDir, "projects", cwd.replace(/\/+$/, "").replace(/[^A-Za-z0-9]/g, "-")); + let best: { mtime: number; id: string } | null = null; + let names: string[]; + try { + names = readdirSync(dir).filter((n) => /^[0-9a-f-]{36}\.jsonl$/i.test(n)); + } catch { + return null; + } + for (const name of names) { + try { + const mtime = statSync(join(dir, name)).mtimeMs; + if (now - mtime > SELF_REPORT_SESSION_WINDOW_MS) continue; + const id = name.slice(0, -".jsonl".length); + if (excluded.has(id)) continue; + if (!best || mtime > best.mtime) best = { mtime, id }; + } catch { + // gone since the listing + } + } + return best ? { sessionId: best.id, cwd } : null; +} + +function homedirForCodex(): string { + return process.env.HOME?.trim() || homedir(); +} + +/** The first line of a file, reading at most 1 MiB (session_meta carries the base instructions). */ +function readFirstLine(file: string): string { + const fd = openSync(file, "r"); + try { + const buf = Buffer.alloc(1 << 20); + const n = readSync(fd, buf, 0, buf.length, 0); + const text = buf.subarray(0, n).toString("utf8"); + const nl = text.indexOf("\n"); + return nl < 0 ? text : text.slice(0, nl); + } finally { + closeSync(fd); + } +} + +// ── JSON-RPC ──────────────────────────────────────────────────────────────── + +type SelfReportRpcResponse = Record | null; + +/** + * Answer one JSON-RPC message. Returns null for a notification (no reply). + * Exported so tests (and the daemon parity check) can drive it without a pipe. + */ +export async function handleSelfReportRpc( + message: unknown, + opts: { agent?: string; cwd?: string; now?: () => number } = {}, +): Promise { + if (!message || typeof message !== "object" || Array.isArray(message)) { + return { jsonrpc: "2.0", id: null, error: { code: -32600, message: "Invalid Request" } }; + } + const req = message as { id?: unknown; method?: unknown; params?: unknown }; + const hasId = req.id !== undefined && req.id !== null; + const id = hasId ? req.id : null; + const method = typeof req.method === "string" ? req.method : ""; + const params = req.params && typeof req.params === "object" ? (req.params as Record) : {}; + const ok = (result: unknown) => ({ jsonrpc: "2.0", id, result }); + + if (!hasId) return null; // notifications/initialized and friends + + const log = (event: Parameters[0]): void => { + void sendSelfReportLog({ transport: "stdio", ...(opts.agent ? { agent: opts.agent } : {}), ...event }); + }; + + switch (method) { + case "initialize": { + const instructions = selfReportServerInstructions(); + log({ event: "initialize", outcome: instructions ? "on" : "off" }); + return ok({ + protocolVersion: typeof params.protocolVersion === "string" ? params.protocolVersion : SELF_REPORT_DEFAULT_PROTOCOL, + capabilities: { tools: {} }, + serverInfo: { name: SELF_REPORT_SERVER_NAME, version: selfReportCliVersion }, + ...(instructions ? { instructions } : {}), + }); + } + case "ping": + return ok({}); + case "tools/list": { + const tools = selfReportToolList(); + log({ event: "tools/list", outcome: tools.length > 0 ? "report" : "no tool (off)" }); + return ok({ tools }); + } + case "tools/call": { + if (params.name !== SELF_REPORT_TOOL_NAME) { + log({ event: "tools/call", outcome: "skipped", reason: "unknown tool" }); + return ok({ content: [{ type: "text", text: `Unknown tool: ${String(params.name)}` }], isError: true }); + } + const agent = opts.agent; + const { category: rawCategory, detail } = selfReportArgs(params.arguments ?? {}); + // The log gets the detail as sent (bounded), scrubbed whole by the + // daemon before its cut; the 2000-character report cut could split a + // credential so the scrubber no longer recognises it. + const asSent = selfReportArgs(params.arguments ?? {}, SELF_REPORT_LOG_PREVIEW_CHARS).detail; + const call = { event: "tools/call" as const, category: rawCategory, preview: asSent }; + const settings = readEnabledSelfReport(); + if (!agent) { + log({ ...call, outcome: "skipped", reason: "no --agent" }); + } else if (!settings) { + log({ ...call, outcome: "skipped", reason: selfReportSettingsState() === "unreadable" ? "settings unreadable" : "Self Reports is off" }); + } else if (!(await selfReportServerShouldRecord(agent, params.arguments, opts.now?.(), opts.cwd ?? process.cwd()))) { + log({ ...call, outcome: "skipped", reason: "its hook recorded it" }); + } else { + // A missing, unlisted or misspelt category is recorded as the listed + // one it resolves to; the log keeps what the model sent. + const resolved = resolveSelfReportCategory(rawCategory, detail, settings.categories.map((c) => c.name)); + const category = resolved.category; + const knownCategory = !resolved.inferred; + const logged = { ...call, category, knownCategory, ...(resolved.inferred ? { rawCategory } : {}) }; + try { + const { path, event } = await writeSelfReportEvent({ + integration: agent, + category, + detail, + cwd: opts.cwd ?? process.cwd(), + now: opts.now?.(), + }); + log({ ...logged, outcome: "recorded", session: String(event.session_id) }); + if (process.env[SELF_REPORT_RECEIPT_ENV] === "1") process.stderr.write(`${SELF_REPORT_RECEIPT_PREFIX}${path}\n`); + } catch (err) { + // The agent still hears "Recorded.": a report changes no decision, + // and an error here would only make it retry. + const why = err instanceof Error ? err.message : String(err); + log({ ...logged, outcome: "failed", reason: `write failed: ${why}` }); + process.stderr.write(`[failproofai mcp] could not record a self report: ${why}\n`); + } + } + return ok({ content: [{ type: "text", text: SELF_REPORT_RESULT_TEXT }] }); + } + default: + return { jsonrpc: "2.0", id, error: { code: -32601, message: `Method not found: ${method}` } }; + } +} + +/** + * `handleSelfReportRpc`, never throwing: a request (one with an id) whose + * handler throws is answered with a JSON-RPC internal error, so the agent is + * not left waiting for its timeout; a notification gets nothing, as always. + */ +async function answerSelfReportRpc( + message: unknown, + opts: { agent?: string; cwd?: string; now?: () => number }, +): Promise { + try { + return await handleSelfReportRpc(message, opts); + } catch (err) { + const why = err instanceof Error ? err.message : String(err); + process.stderr.write(`[failproofai mcp] ${why}\n`); + const id = message && typeof message === "object" && !Array.isArray(message) ? (message as { id?: unknown }).id : undefined; + if (id === undefined || id === null) return null; + return { jsonrpc: "2.0", id, error: { code: -32603, message: `Internal error: ${why}` } }; + } +} + +/** + * Run the server until stdin closes. Requests are answered in arrival order. + * Resolves when the input ends and every reply has been written. + */ +export function runSelfReportMcpServer(opts: SelfReportMcpOptions = {}): Promise { + const input = opts.input ?? process.stdin; + const output = opts.output ?? process.stdout; + const handlerOpts = { agent: opts.agent, cwd: opts.cwd, now: opts.now }; + // Read this server's agent now, before any request: on macOS it runs `ps` + // synchronously, and doing that later blocked the event loop while a log + // frame was connecting, so its short budget fired first and the line was lost. + if (!opts.input) selfReportServerAgentPid(); + let chain: Promise = Promise.resolve(); + const send = (msg: unknown) => { + output.write(`${JSON.stringify(msg)}\n`); + }; + return new Promise((resolveRun) => { + const rl = createInterface({ input, crlfDelay: Infinity }); + rl.on("line", (line) => { + if (!line.trim()) return; + chain = chain.then(async () => { + let parsed: unknown; + try { + parsed = JSON.parse(line); + } catch { + send({ jsonrpc: "2.0", id: null, error: { code: -32700, message: "Parse error" } }); + return; + } + try { + if (Array.isArray(parsed)) { + const replies = (await Promise.all(parsed.map((m) => answerSelfReportRpc(m, handlerOpts)))).filter( + (r) => r !== null, + ); + if (replies.length > 0) send(replies); + } else { + const reply = await answerSelfReportRpc(parsed, handlerOpts); + if (reply) send(reply); + } + } catch (err) { + process.stderr.write(`[failproofai mcp] ${err instanceof Error ? err.message : String(err)}\n`); + } + }); + }); + rl.on("close", () => { + // Events still on their way to the daemon's log get a moment, never more. + void chain.then(() => flushSelfReportLogs()).then(() => resolveRun()); + }); + }); +} diff --git a/src/hooks/self-report-names.ts b/src/hooks/self-report-names.ts new file mode 100644 index 000000000..59b993efb --- /dev/null +++ b/src/hooks/self-report-names.ts @@ -0,0 +1,260 @@ +/** + * The Self Reports tool's names (contract §1), in a module that imports + * NOTHING. `tool-name-canonicalize.ts` needs `isSelfReportToolName` and is + * bundled ahead of the builtin policies; a module with imports placed there + * (self-report.ts pulls node:fs and lazily fp-config/safe-config-write) moves + * other modules ahead of builtin-policies.ts in the scope-hoisted CLI bundle + * and renames bindings inside the policy functions, which changes the audit + * cache's `engineVersion` and rescans every user's history at upgrade. Every + * name here is prefixed so it cannot collide with a local in a policy either. + * + * Re-exported from self-report.ts; import from there everywhere else. + */ + +/** + * MCP server name every installer registers. Not `failproofai`: that is the name + * users give the FailproofAI Cloud gateway MCP server, and the two coexist. An + * underscore, not a hyphen, because some agents rewrite hyphens in tool names. + */ +export const SELF_REPORT_SERVER_NAME = "failproofai_local"; +/** The MCP tool's own name. */ +export const SELF_REPORT_TOOL_NAME = "report"; +/** How Claude Code and Codex spell it: `mcp____`. */ +export const SELF_REPORT_MCP_TOOL_NAME = "mcp__failproofai_local__report"; +/** The SDK tool's name. */ +export const SELF_REPORT_SDK_TOOL_NAME = "failproofai_report"; +/** Detail is truncated to this many characters (contract §3). */ +export const SELF_REPORT_DETAIL_MAX = 2000; +/** Default loopback port of the daemon's HTTP MCP server (contract §4, D5). */ +export const SELF_REPORT_DEFAULT_PORT = 4319; + +/** + * `text` cut to `max` Unicode code points, the unit the daemon + * (`truncate_chars`) and the Python SDK count in, so all of them keep the same + * prefix. Never cuts through a surrogate pair, and a lone surrogate already in + * the input becomes U+FFFD: either one would be written as an unpaired `\ud8xx` + * escape, which the Rust collector rejects together with the whole activity + * row (its hook event too). test-fixtures/self-report/truncation.golden.json + * holds the cases every implementation is tested against. + */ +export function selfReportClip(text: string, max: number = SELF_REPORT_DETAIL_MAX): string { + let out = ""; + let n = 0; + for (const ch of text) { + if (n === max) break; + const code = ch.charCodeAt(0); + out += ch.length === 1 && code >= 0xd800 && code <= 0xdfff ? "\uFFFD" : ch; + n++; + } + return out; +} + +/** The longest agent-sent category a log line shows as written. */ +export const SELF_REPORT_LOG_CATEGORY_MAX = 32; + +/** + * A category the model sent, as a log line may show it: as written only when + * it is shaped like a category name (lowercase letters, digits, `_`, `-`, `.` + * or a space, starting with a letter, at most 32 characters and at most 4 + * digits), else `(N characters, not shown)`. The model can put anything in + * the field, a token included, and a log line can leave the machine; no + * credential format is that short, lowercase and digit-poor. The daemon + * (`log_category_text`, crates/fpai-collect/src/self_report.rs) applies the + * same rule to what it logs. + */ +export function selfReportLogCategoryText(raw: string): string { + const n = [...raw].length; + const digits = (raw.match(/[0-9]/g) ?? []).length; + if (raw === "" || (n <= SELF_REPORT_LOG_CATEGORY_MAX && digits <= 4 && /^[a-z][a-z0-9_. -]*$/.test(raw))) return raw; + return `(${n} characters, not shown)`; +} + +/** What a detail cut down to nothing reads as (test-fixtures/self-report/truncation.golden.json `detail_cut`). */ +export const SELF_REPORT_DETAIL_CUT_MARKER = "[detail cut]"; + +/** The whitespace the detail cut splits on: ASCII only, so every implementation agrees. */ +const SELF_REPORT_CUT_WHITESPACE = new Set([" ", "\t", "\n", "\r", "\f", "\v"]); + +/** + * A report's detail cut to `max` code points without leaving part of a token + * at the end. A credential that runs past the cut (a JWT, a long key) would + * otherwise be kept as a fragment that no secret scrubber recognises any more, + * and be uploaded and logged as such (review round 3). So when the cut lands + * inside a run of non-whitespace, that whole trailing run is dropped; trailing + * whitespace goes too; and if nothing is left the detail is + * `SELF_REPORT_DETAIL_CUT_MARKER`. Text that fits is returned whole (with + * lone surrogates replaced, as `selfReportClip` does). The same rule runs in + * the daemon (`cut_detail`) and both SDKs; truncation.golden.json `detail_cut` + * holds the cases. + */ +export function selfReportCutDetail(text: string, max: number = SELF_REPORT_DETAIL_MAX): string { + const points = [...selfReportClip(text, Number.MAX_SAFE_INTEGER)]; + if (points.length <= max) return points.join(""); + const head = points.slice(0, max); + if (!SELF_REPORT_CUT_WHITESPACE.has(points[max])) { + while (head.length > 0 && !SELF_REPORT_CUT_WHITESPACE.has(head[head.length - 1])) head.pop(); + } + while (head.length > 0 && SELF_REPORT_CUT_WHITESPACE.has(head[head.length - 1])) head.pop(); + return head.length > 0 ? head.join("") : SELF_REPORT_DETAIL_CUT_MARKER; +} + +/** + * How one agent flattens an MCP server and tool into the tool name its hook + * sees: ``. + */ +export interface SelfReportFlattening { + readonly prefix: string; + readonly sep: string; +} + +/** + * Each agent's own spelling(s) of the report tool (installer research, + * 2026-11-25; see self-report-install.ts). The exemption takes ONLY the + * calling agent's spelling, exactly: a name another agent would use is, on + * this agent, some other server's tool (review #1105: OpenCode flattens server + * `mcp_failproofai_local` + tool `report` to Hermes's spelling). + * + * - `mcp__failproofai_local__report`: Claude Code, Codex, Pi (its extension + * registers that name), Factory, Devin. + * - `failproofai_local___report`: Factory's matcher-regex form of the same name. + * - `mcp_failproofai_local_report`: Hermes (its plugin's name), and + * Antigravity's eager tools. + * - `failproofai_local_report`: OpenCode (`_`). + * - `failproofai_local__report`: OpenClaw (its plugin's name) and Goose. + * - `failproofai_local-report` and `failproofai_local/report`: Copilot CLI's + * likely forms. Its hook spelling of an MCP tool is not documented and could + * not be observed without a signed-in run, so both are exempt. + * - Cursor: none. See `isSelfReportCursorCall`; its preToolUse name + * `MCP:report` carries no server, so it is never matched by name alone. + * - Antigravity's lazy path, `call_mcp_tool`: see + * `selfReportAntigravityWrappedArgs`; matched only on its server and tool. + * - Never `failproofai_report`, the SDK tool's name: it is OpenCode's spelling + * of tool `report` on a server named `failproofai` (the Cloud gateway's + * usual name). The SDKs recognise it themselves (`isSelfReportTool`). + * + * The earlier catch-all forms (`failproofai_local.report`, `…:report`, + * `mcp__failproofai_local_report`, `mcp:failproofai_local:report`, …), kept + * "so a spelling change cannot route a report through the policies", are + * gone: no agent delivers them, and on some agent each is another server's + * tool. A spelling change now sends the report through the policies, which is + * the safe direction. + * + * A spelling whose separator is a single character (`_`, `-`, `/`) is + * ambiguous: other server/tool pairs flatten to the same string. The hook + * refuses the exemption while the agent's config registers any such server + * (`selfReportNameCollides` in self-report-install.ts). + */ +const SELF_REPORT_FLATTENINGS: Readonly> = { + claude: [{ prefix: "mcp__", sep: "__" }], + codex: [{ prefix: "mcp__", sep: "__" }], + pi: [{ prefix: "mcp__", sep: "__" }], + devin: [{ prefix: "mcp__", sep: "__" }], + factory: [{ prefix: "mcp__", sep: "__" }, { prefix: "", sep: "___" }], + hermes: [{ prefix: "mcp_", sep: "_" }], + antigravity: [{ prefix: "mcp_", sep: "_" }], + opencode: [{ prefix: "", sep: "_" }], + openclaw: [{ prefix: "", sep: "__" }], + goose: [{ prefix: "", sep: "__" }], + copilot: [{ prefix: "", sep: "-" }, { prefix: "", sep: "/" }], + cursor: [], +}; + +const selfReportSpelling = (f: SelfReportFlattening): string => + `${f.prefix}${SELF_REPORT_SERVER_NAME}${f.sep}${SELF_REPORT_TOOL_NAME}`; + +/** The flattening of `cli` that spells `name` as our tool, if any (case-insensitive, exact). */ +export function selfReportFlatteningOf(name: unknown, cli: string): SelfReportFlattening | undefined { + if (typeof name !== "string") return undefined; + const lower = name.toLowerCase(); + return (SELF_REPORT_FLATTENINGS[cli] ?? []).find((f) => selfReportSpelling(f) === lower); +} + +/** `cli`'s own spellings of the report tool. */ +export function selfReportToolSpellings(cli: string): string[] { + return (SELF_REPORT_FLATTENINGS[cli] ?? []).map(selfReportSpelling); +} + +/** + * True when `name` is `cli`'s own spelling of the report tool (contract §1). + * Exact matches only, and only the calling agent's: a prefix or substring + * match, or another agent's spelling, could be any other server's tool, and + * this name is the one thing that skips every policy. + */ +export function isSelfReportToolName(name: unknown, cli: string): boolean { + return selfReportFlatteningOf(name, cli) !== undefined; +} + +/** + * True for any agent's spelling. NOT for the exemption: only for choices that + * skip nothing (not adding a "report it" hint to the report call itself). + */ +export function isAnySelfReportToolName(name: unknown): boolean { + return Object.keys(SELF_REPORT_FLATTENINGS).some((cli) => isSelfReportToolName(name, cli)); +} + +/** + * Cursor's MCP hook (`beforeMCPExecution`) names the tool bare (`report`) and + * the server separately, as `mcp_server_name` (its key in mcp.json). Only that + * pair identifies our tool: a bare `report`, or preToolUse's `MCP:report` + * without a server name, could be any server's tool and is NOT matched. + */ +export function isSelfReportCursorCall(payload: unknown): boolean { + if (!payload || typeof payload !== "object" || Array.isArray(payload)) return false; + const p = payload as Record; + const server = p.mcp_server_name; + if (typeof server !== "string" || server.toLowerCase() !== SELF_REPORT_SERVER_NAME) return false; + const tool = typeof p.tool_name === "string" ? p.tool_name.toLowerCase() : ""; + return tool === SELF_REPORT_TOOL_NAME || tool === `mcp:${SELF_REPORT_TOOL_NAME}` || isAnySelfReportToolName(tool); +} + +/** + * Antigravity's lazy (default) MCP path: the model calls the built-in + * `call_mcp_tool` wrapper with `{ServerName, ToolName, Arguments}` (agy 1.5's + * own description says to judge it by ServerName + ToolName). Returns the + * wrapped call's arguments when, and only when, the wrapper names server + * `failproofai_local` and tool `report`; `undefined` for any other server or tool, + * whose calls keep going through the policies. + */ +export function selfReportAntigravityWrappedArgs(toolName: unknown, toolInput: unknown): { args: unknown } | undefined { + if (typeof toolName !== "string" || toolName.toLowerCase() !== "call_mcp_tool") return undefined; + let input: unknown = toolInput; + if (typeof input === "string") { + try { + input = JSON.parse(input); + } catch { + return undefined; + } + } + if (!input || typeof input !== "object" || Array.isArray(input)) return undefined; + const i = input as Record; + const pick = (...keys: string[]): unknown => keys.map((k) => i[k]).find((v) => v !== undefined); + const server = pick("ServerName", "serverName", "server_name"); + const tool = pick("ToolName", "toolName", "tool_name"); + if (typeof server !== "string" || server.toLowerCase() !== SELF_REPORT_SERVER_NAME) return undefined; + if (typeof tool !== "string") return undefined; + const t = tool.toLowerCase(); + if (t !== SELF_REPORT_TOOL_NAME && !isAnySelfReportToolName(t)) return undefined; + return { args: pick("Arguments", "arguments", "args") ?? {} }; +} + +/** + * Integrations whose hooks do not see MCP tool calls, or do not see which + * server a call is for, so the MCP server itself records a report (contract + * §8). Claude Code and Codex are recorded by the hook. Cursor is here because + * the hook failproofai installs (preToolUse) names an MCP call `MCP:` + * with no server, and its MCP hook (beforeMCPExecution) is not installed. + * Kept identical to the Rust list. + */ +export const SELF_REPORT_SERVER_RECORDS: readonly string[] = [ + "openclaw", + "pi", + "devin", + "hermes", + "goose", + "factory", + "antigravity", + "copilot", + "opencode", + "cursor", +]; + diff --git a/src/hooks/self-report.ts b/src/hooks/self-report.ts new file mode 100644 index 000000000..894ff4e1a --- /dev/null +++ b/src/hooks/self-report.ts @@ -0,0 +1,774 @@ +/** + * Self Reports: the `report` tool FailproofAI puts into every agent, so an + * agent that is stuck can say so. + * + * This module is the one TypeScript home for everything the feature shares: + * the default categories, the tool's description and input schema (identical + * text in every implementation — the daemon, the stdio server and both SDKs + * build the same string), the recognised tool names, and the effective + * settings file `self-report.json` every reader goes through. + * + * Every top-level name here starts with `selfReport` / `SELF_REPORT`, on + * purpose. The CLI ships as one scope-hoisted bundle, and a new top-level name + * that matches a local inside a builtin policy makes the bundler rename that + * local — which changes the function source the audit cache keys on (see the + * note on `screenKit` in tui.ts). The short names the brief asks for + * (`describe`, `inputSchema`, `DEFAULT_CATEGORIES`) are export aliases only. + * + * Only the name/description/settings-read half is used on the hook path, and it + * imports nothing beyond `node:fs` and the home resolver. The local-config and + * Cloud-enrolment helpers load their modules lazily. + */ +import { chmodSync, closeSync, existsSync, fsyncSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, writeSync } from "node:fs"; +import { dirname, join } from "node:path"; +import { createHash, randomBytes } from "node:crypto"; +import { configFile, credentialsFile, failproofaiHome } from "./fp-home"; + +export { + SELF_REPORT_SERVER_NAME, + SELF_REPORT_TOOL_NAME, + SELF_REPORT_MCP_TOOL_NAME, + SELF_REPORT_SDK_TOOL_NAME, + SELF_REPORT_DETAIL_MAX, + SELF_REPORT_DEFAULT_PORT, + SELF_REPORT_SERVER_RECORDS, + isSelfReportToolName, + isAnySelfReportToolName, + selfReportFlatteningOf, + selfReportToolSpellings, + isSelfReportCursorCall, + selfReportAntigravityWrappedArgs, + selfReportClip, + selfReportCutDetail, + SELF_REPORT_DETAIL_CUT_MARKER, +} from "./self-report-names"; +import { SELF_REPORT_DEFAULT_PORT, SELF_REPORT_DETAIL_MAX, selfReportClip, selfReportCutDetail } from "./self-report-names"; + +// ── Categories (contract §2) ──────────────────────────────────────────────── + +export interface SelfReportCategory { + name: string; + description: string; +} + +const SELF_REPORT_DEFAULT_CATEGORIES: readonly SelfReportCategory[] = Object.freeze([ + { name: "looping", description: "You keep repeating the same or circular steps without making progress." }, + { + name: "cannot_do_request", + description: + "The user asked for something you cannot do here: a missing capability, tool or permission, or it is only possible by cheating.", + }, + { + name: "invalid_tool_or_credential", + description: "A tool, MCP server, plugin, API key or token you need is broken, invalid, expired or rejected.", + }, + { + name: "missing_context", + description: + "Information or access you need is missing and you cannot get it yourself. Not for normal clarifying questions.", + }, + { + name: "repeated_tool_failure", + description: + "A command or tool failed on several distinct attempts and is blocking you. A single error is not enough.", + }, + { + name: "task_failure", + description: "You genuinely tried and could not complete the task, or something else blocks you that no other category describes. Not for refusals or policy blocks.", + }, +].map((c) => Object.freeze(c))); + +export { SELF_REPORT_DEFAULT_CATEGORIES, SELF_REPORT_DEFAULT_CATEGORIES as DEFAULT_CATEGORIES }; + +const SELF_REPORT_NAME_RE = /^[a-z][a-z0-9_]{0,63}$/; +const SELF_REPORT_MAX_CATEGORIES = 32; +const SELF_REPORT_MAX_DESCRIPTION = 500; +export const SELF_REPORT_MAX_GUIDANCE = 2000; + +export type SelfReportValidation = { ok: true; value: T } | { ok: false; error: string }; + +/** + * Check an org's or a user's category list against contract §2: 1–32 entries, + * names `^[a-z][a-z0-9_]{0,63}$` and unique, descriptions 1–500 characters. + * Descriptions are trimmed; nothing else is rewritten. + */ +export function validateSelfReportCategories(input: unknown): SelfReportValidation { + if (!Array.isArray(input)) return { ok: false, error: "categories must be a list of {name, description}" }; + if (input.length < 1 || input.length > SELF_REPORT_MAX_CATEGORIES) { + return { ok: false, error: `categories must have between 1 and ${SELF_REPORT_MAX_CATEGORIES} entries` }; + } + const seen = new Set(); + const out: SelfReportCategory[] = []; + for (const [i, raw] of input.entries()) { + if (!raw || typeof raw !== "object" || Array.isArray(raw)) { + return { ok: false, error: `category ${i + 1} must be an object with name and description` }; + } + const { name, description } = raw as Record; + if (typeof name !== "string" || !SELF_REPORT_NAME_RE.test(name)) { + return { + ok: false, + error: `category ${i + 1}: name must match ^[a-z][a-z0-9_]{0,63}$ (lowercase, digits, underscores)`, + }; + } + if (seen.has(name)) return { ok: false, error: `category "${name}" is listed twice` }; + seen.add(name); + const desc = typeof description === "string" ? description.trim() : ""; + if (desc.length < 1 || desc.length > SELF_REPORT_MAX_DESCRIPTION) { + return { ok: false, error: `category "${name}": description must be 1-${SELF_REPORT_MAX_DESCRIPTION} characters` }; + } + out.push({ name, description: desc }); + } + return { ok: true, value: out }; +} + +/** Guidance: a string of at most 2000 characters, or nothing. Blank reads as nothing. */ +export function validateSelfReportGuidance(input: unknown): SelfReportValidation { + if (input === undefined || input === null) return { ok: true, value: null }; + if (typeof input !== "string") return { ok: false, error: "guidance must be text" }; + const trimmed = input.trim(); + if (trimmed.length > SELF_REPORT_MAX_GUIDANCE) { + return { ok: false, error: `guidance must be at most ${SELF_REPORT_MAX_GUIDANCE} characters` }; + } + return { ok: true, value: trimmed === "" ? null : trimmed }; +} + +// ── The tool (contract §3) ────────────────────────────────────────────────── + +const SELF_REPORT_DESCRIPTION_HEAD = + "When you are stuck on something you cannot fix yourself, call this tool once with `category` (one of the categories " + + "below) and `detail` (one factual sentence: what is blocking you). It reports to FailproofAI. Call it BEFORE your " + + "final answer, for example for a missing, invalid or expired token or API key, a 401 or 403, a command, tool or MCP " + + "server that keeps failing, information or access you cannot get, or a request you cannot do here. Do not call it for " + + "normal work, clarifying questions or an error you then fixed. One call per distinct problem.\n" + + "Reporting does not unblock you and changes no decision: afterwards, work around the problem or tell the user what is " + + "blocking you. There is no need to mention this report to the user."; + +/** The tool description, built from the categories and the optional guidance. */ +function describeSelfReportTool( + categories: readonly SelfReportCategory[], + guidance?: string | null, +): string { + const lines = categories.map((c) => `- ${c.name}: ${c.description}`); + const body = `${SELF_REPORT_DESCRIPTION_HEAD}\n\nCategories:\n${lines.join("\n")}`; + return guidance ? `${body}\n\n${guidance}` : body; +} + +/** The tool's JSON input schema. */ +function selfReportInputSchema(categories: readonly SelfReportCategory[]): Record { + return { + type: "object", + properties: { + category: { type: "string", enum: categories.map((c) => c.name) }, + detail: { type: "string", description: "One factual sentence: what is blocking you." }, + }, + required: ["category", "detail"], + additionalProperties: false, + }; +} + +export { describeSelfReportTool, describeSelfReportTool as describe, selfReportInputSchema, selfReportInputSchema as inputSchema }; + +/** + * The MCP server's `instructions` (the initialize result), the same text in the + * daemon (crates/fpai-collect/src/self_report.rs `instructions`). + * + * Claude Code defers MCP tools behind tool search, so the model never reads the + * tool's description until it already decided to look for one; a server's + * instructions go into the system prompt. One short paragraph naming the + * categories, then the org's guidance when set. + * + * The first sentence says on its own what to do and how: Codex's code mode + * lists MCP servers as namespaces and keeps only about the first 250 + * characters of a server's instructions and of a tool's description. + */ +function selfReportInstructions( + categories: readonly SelfReportCategory[], + guidance?: string | null, +): string { + const names = categories.map((c) => c.name).join(", "); + const body = + "When you are stuck, call failproofai_local's `report` tool once with `category` and `detail` (one factual " + + "sentence: what is blocking you). Stuck means something you cannot fix yourself: a missing or expired token or " + + "key, a 401 or 403, a command or tool that keeps failing, information you cannot get, a request you cannot do. " + + `\`category\` is one of: ${names}. Call it before your final answer, not when the task succeeded. It does not ` + + "unblock you, and there is no need to mention it to the user."; + return guidance ? `${body}\n\n${guidance}` : body; +} + +export { selfReportInstructions }; + +/** Exactly what the tool returns (contract §3). */ +export const SELF_REPORT_RESULT_TEXT = "Recorded."; + +/** + * A call's arguments as a model sent them (the recorders then resolve the + * category with `resolveSelfReportCategory`; a call is never rejected), a missing or empty argument falls back to its first + * non-empty alias (`SELF_REPORT_ARG_ALIASES`), else `""`; unknown keys are ignored; detail is cut to 2000 + * code points (`selfReportClip`). A category is cut to the same bound so a hostile argument cannot + * grow every activity row without limit. + * + * Accepts the arguments object itself, or a hook's `tool_input` that wraps it + * (`{arguments: {...}}`, `{args: {...}}`, or either as a JSON string), because + * agents differ in how they hand an MCP call to their hooks. + */ +export function selfReportArgs(input: unknown, max: number = SELF_REPORT_DETAIL_MAX): { category: string; detail: string } { + let args: unknown = input; + if (typeof args === "string") args = selfReportParseJson(args); + if (args && typeof args === "object" && !Array.isArray(args)) { + const rec = args as Record; + if (!SELF_REPORT_ARG_KEYS.some((key) => rec[key] !== undefined)) { + for (const key of ["arguments", "args", "input", "params"]) { + let inner = rec[key]; + if (typeof inner === "string") inner = selfReportParseJson(inner); + if (inner && typeof inner === "object" && !Array.isArray(inner)) { + args = inner; + break; + } + } + } + } + const rec = args && typeof args === "object" && !Array.isArray(args) ? (args as Record) : {}; + const category = selfReportArg(rec, "category", SELF_REPORT_ARG_ALIASES.category); + const detail = selfReportArg(rec, "detail", SELF_REPORT_ARG_ALIASES.detail); + return { + category: selfReportClip(category, max), + detail: selfReportCutDetail(detail, max), + }; +} + +/** + * Other names a model uses for an argument when it calls the tool without + * loading its schema (seen live: `summary` and `sentence` for `detail`). The + * first non-empty one is used when the real argument is missing or empty. + * Identical in the daemon (crates/fpai-collect/src/self_report.rs) and both + * SDKs; test-fixtures/self-report/arg-aliases.json holds the list for all of them. + */ +export const SELF_REPORT_ARG_ALIASES = { + category: ["type", "kind"], + detail: ["summary", "sentence", "message", "description", "reason", "text", "details"], +} as const; + +/** + * Keyword rules for a category the model did not name (or named wrongly), in + * order; the first rule whose target is on the active list and whose keyword + * appears in the lowercased `category + " " + detail` wins. Identical in the + * daemon and both SDKs; test-fixtures/self-report/category-inference.json + * holds the rules and the cases for all of them. + */ +export const SELF_REPORT_CATEGORY_RULES: readonly { category: string; keywords: readonly string[] }[] = [ + { + category: "invalid_tool_or_credential", + keywords: ["token", "api key", "apikey", "api_key", "credential", "unauthorized", "unauthenticated", "forbidden", "401", "403", "expired", "revoked", "auth", "password", "secret"], + }, + { category: "looping", keywords: ["loop", "looping", "circular", "in circles", "repeating the same"] }, + { + category: "repeated_tool_failure", + keywords: ["keeps failing", "keep failing", "repeatedly", "several attempts", "multiple attempts", "retried", "retries", "again and again"], + }, + { + category: "missing_context", + keywords: ["missing", "not found", "no information", "not provided", "cannot find", "can't find", "need more information", "unclear"], + }, + { + category: "cannot_do_request", + keywords: ["cannot", "can't", "unable", "not possible", "impossible", "not supported", "unsupported", "not allowed"], + }, +]; + +/** The category a report falls back to when nothing matched, if it is listed. */ +export const SELF_REPORT_FALLBACK_CATEGORY = "task_failure"; + +function selfReportIsWordChar(ch: string | undefined): boolean { + return ch !== undefined && /[a-z0-9]/.test(ch); +} + +function selfReportHasKeyword(text: string, keyword: string): boolean { + for (let at = text.indexOf(keyword); at !== -1; at = text.indexOf(keyword, at + 1)) { + if (!selfReportIsWordChar(text[at - 1]) && !selfReportIsWordChar(text[at + keyword.length])) return true; + } + return false; +} + +/** + * The category a report is recorded under: `raw` when it is on `names`, else + * the listed name it normalises to (lowercase, trimmed, runs of spaces and + * hyphens as `_`), else the first keyword rule (`SELF_REPORT_CATEGORY_RULES`) + * that matches the category and detail and targets a listed name, else + * `task_failure` when listed, else the first listed name. `inferred` is true + * whenever the result is not `raw` itself. An empty list keeps `raw`. + */ +export function resolveSelfReportCategory( + raw: string, + detail: string, + names: readonly string[], +): { category: string; inferred: boolean } { + if (names.length === 0 || names.includes(raw)) return { category: raw, inferred: false }; + const normalised = raw.trim().toLowerCase().replace(/[\s-]+/g, "_"); + if (names.includes(normalised)) return { category: normalised, inferred: true }; + const text = `${raw} ${detail}`.toLowerCase(); + for (const rule of SELF_REPORT_CATEGORY_RULES) { + if (names.includes(rule.category) && rule.keywords.some((k) => selfReportHasKeyword(text, k))) { + return { category: rule.category, inferred: true }; + } + } + return { category: names.includes(SELF_REPORT_FALLBACK_CATEGORY) ? SELF_REPORT_FALLBACK_CATEGORY : names[0], inferred: true }; +} + +const SELF_REPORT_ARG_KEYS: readonly string[] = [ + "category", + "detail", + ...SELF_REPORT_ARG_ALIASES.category, + ...SELF_REPORT_ARG_ALIASES.detail, +]; + +function selfReportArg(rec: Record, key: string, aliases: readonly string[]): string { + for (const name of [key, ...aliases]) { + const value = rec[name]; + const text = value === undefined || value === null ? "" : typeof value === "string" ? value : JSON.stringify(value); + if (text) return text; + } + return ""; +} + +function selfReportParseJson(text: string): unknown { + try { + return JSON.parse(text); + } catch { + return undefined; + } +} + +// ── The effective settings file (contract §4) ─────────────────────────────── + +export interface SelfReportEffective { + version: 1; + enabled: boolean; + source: "cloud" | "local"; + categories: SelfReportCategory[]; + guidance: string | null; + mcp: { port: number; url: string }; + updatedAt: string; + /** + * A `cloud` file's enrolment: `selfReportEnrolmentId` of the credential + * whose poll the daemon wrote it from. It decides only while this machine is + * enrolled as that credential (a file left by a previous org must not keep + * recording for the next one). + */ + enrolment?: string; +} + +/** `$FAILPROOFAI_HOME/self-report.json`. */ +export function selfReportSettingsFile(): string { + return join(failproofaiHome(), "self-report.json"); +} + +/** The port a local writer records: `FAILPROOFAI_SELF_REPORT_PORT`, else 4319. */ +export function selfReportPort(): number { + const raw = process.env.FAILPROOFAI_SELF_REPORT_PORT?.trim(); + if (raw && /^\d+$/.test(raw)) { + const n = Number(raw); + if (n > 0 && n < 65536) return n; + } + return SELF_REPORT_DEFAULT_PORT; +} + +export function selfReportMcpUrl(port: number): string { + return `http://127.0.0.1:${port}/mcp`; +} + +/** + * Read `self-report.json` exactly as it is on disk. Missing, unparsable or not + * version 1 reads as `null`. A file that says enabled but whose category list + * is unusable falls back to the defaults (contract §4: "never empty when + * enabled; defaults if none given"). + * + * This is the raw file. Whether Self Reports is ON is `resolveSelfReport()`, + * which tells a missing file (on by default off Cloud) from a broken one (off). + */ +export function readEffectiveSelfReport(path: string = selfReportSettingsFile()): SelfReportEffective | null { + let raw: unknown; + try { + raw = JSON.parse(readFileSync(path, "utf8")); + } catch { + return null; + } + if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null; + const rec = raw as Record; + if (rec.version !== 1) return null; + const cats = validateSelfReportCategories(rec.categories); + const guidance = validateSelfReportGuidance(rec.guidance); + const mcp = rec.mcp && typeof rec.mcp === "object" && !Array.isArray(rec.mcp) ? (rec.mcp as Record) : {}; + const port = + typeof mcp.port === "number" && Number.isInteger(mcp.port) && mcp.port > 0 && mcp.port < 65536 + ? mcp.port + : SELF_REPORT_DEFAULT_PORT; + return { + version: 1, + enabled: rec.enabled === true, + source: rec.source === "cloud" ? "cloud" : "local", + categories: cats.ok ? cats.value : SELF_REPORT_DEFAULT_CATEGORIES.map((c) => ({ ...c })), + guidance: guidance.ok ? guidance.value : null, + mcp: { port, url: typeof mcp.url === "string" && mcp.url ? mcp.url : selfReportMcpUrl(port) }, + updatedAt: typeof rec.updatedAt === "string" ? rec.updatedAt : "", + ...(typeof rec.enrolment === "string" && rec.enrolment ? { enrolment: rec.enrolment } : {}), + }; +} + +/** + * Whether a settings file that parsed may decide anything (the daemon's + * `authoritative`): off Cloud, any file; on a Cloud-enrolled machine, only a + * `cloud` file written for the enrolment the machine is under right now. + * This machine's own file, a previous org's, one from a daemon that predates + * the binding, and any file while the credential cannot be read are set + * aside: off until this enrolment's setting is written. + */ +export function selfReportFileDecides( + file: SelfReportEffective, + enrolled: () => boolean = selfReportCloudEnrolled, + enrolmentId: () => string | null = selfReportEnrolmentId, +): boolean { + if (!enrolled()) return true; + if (file.source !== "cloud") return false; + const current = enrolmentId(); + return current !== null && file.enrolment === current; +} + +/** + * The settings every reader acts on (contract §4). Self Reports is ON by + * default. Identical to the daemon's `effective_settings` + * (crates/fpai-collect/src/self_report.rs): + * + * - the file, when it is there and parses, except, on a Cloud-enrolled + * machine, any file but a `cloud` one written for this enrolment + * (`selfReportFileDecides`): `null`, off until the daemon writes the org's + * setting (enrolling must not leave this machine's own switch, or a + * previous org's, in charge); + * - an unparsable file, or one in another version: `null`, off (fail safe: a half-written or hand-broken + * file must not turn recording on); + * - a missing file on a Cloud-enrolled machine: `null`, off until the daemon + * writes it from the org's setting; + * - a missing file otherwise: on with the default categories, unless + * `config.json`'s `selfReport.enabled` is `false` (an explicit off wins). + */ +export function resolveSelfReport( + path: string = selfReportSettingsFile(), + enrolled: () => boolean = selfReportCloudEnrolled, + enrolmentId: () => string | null = selfReportEnrolmentId, +): SelfReportEffective | null { + const presence = selfReportFilePresence(path); + // Present: the file decides, except that this machine's own (local) file + // does not on a Cloud-enrolled machine, where the organization decides: off + // until the daemon writes the org's setting, as with no file. Unreadable is + // a broken file: off. + if (presence === "present") { + const file = readEffectiveSelfReport(path); + if (file && !selfReportFileDecides(file, enrolled, enrolmentId)) return null; + return file; + } + if (presence === "unreadable") return null; + if (enrolled() || selfReportLocalConfigOff()) return null; + return selfReportDefaultSettings(); +} + +/** On, local, the default categories: what a machine with no settings file runs. */ +export function selfReportDefaultSettings(): SelfReportEffective { + const port = selfReportPort(); + return { + version: 1, + enabled: true, + source: "local", + categories: SELF_REPORT_DEFAULT_CATEGORIES.map((c) => ({ ...c })), + guidance: null, + mcp: { port, url: selfReportMcpUrl(port) }, + updatedAt: "", + }; +} + +/** `config.json`'s `selfReport.enabled` is exactly `false` (sync; the hook path). */ +function selfReportLocalConfigOff(): boolean { + try { + const raw: unknown = JSON.parse(readFileSync(configFile(), "utf8")); + if (!raw || typeof raw !== "object" || Array.isArray(raw)) return false; + const block = (raw as Record).selfReport; + return !!block && typeof block === "object" && (block as Record).enabled === false; + } catch { + return false; + } +} + +/** + * Is this machine Cloud enrolled, for the missing-file rule? Synchronous (the + * hook path), and the same answer as the daemon's `Enrolment::resolve` + * (cloud_client.rs) so TS and Rust readers agree: `FAILPROOFAI_CLOUD_URL` set; + * else, unless `config.json` says `mode.kind == "oss"`, a credential file: + * `FAILPROOFAI_CLOUD_CREDENTIALS` when named, else `credentials.json` with a + * `cloud` entry, else the layout-1 `cloud.json`. A credential file that cannot + * be read or parsed counts as enrolled, as the daemon's does: a missing + * `self-report.json` then stays off rather than guessing on. + */ +export function selfReportCloudEnrolled(): boolean { + if (process.env.FAILPROOFAI_CLOUD_URL?.trim()) return true; + if (selfReportOssMode()) return false; + const override = process.env.FAILPROOFAI_CLOUD_CREDENTIALS; + if (override) return selfReportFilePresence(override) !== "missing"; + const creds = credentialsFile(); + const presence = selfReportFilePresence(creds); + if (presence === "missing") return selfReportFilePresence(join(failproofaiHome(), "cloud.json")) !== "missing"; + if (presence === "unreadable") return true; + try { + const raw: unknown = JSON.parse(readFileSync(creds, "utf8")); + if (!raw || typeof raw !== "object" || Array.isArray(raw)) return true; + const cloud = (raw as Record).cloud; + return cloud !== undefined && cloud !== null; + } catch { + return true; + } +} + +/** + * The id `self-report.json` is bound to on a Cloud-enrolled machine: the + * daemon's `enrolment_id` (crates/fpai-collect/src/self_report.rs) of the + * credential `Enrolment::resolve` finds, or null when there is none or it + * cannot be read. A SHA-256 over a fixed tag and the length-prefixed URL, + * machine id and token exactly as stored, first 16 bytes in hex. + */ +export function selfReportEnrolmentId(): string | null { + const env = (name: string) => process.env[name]?.trim() || undefined; + const envUrl = env("FAILPROOFAI_CLOUD_URL"); + if (envUrl) { + const token = env("FAILPROOFAI_CLOUD_TOKEN"); + const machineId = env("FAILPROOFAI_MACHINE_ID"); + return token && machineId ? selfReportEnrolmentIdOf(envUrl, machineId, token) : null; + } + if (selfReportOssMode()) return null; + const stored = (path: string): string | null => { + try { + const raw = JSON.parse(readFileSync(path, "utf8")) as Record; + if (raw?.schemaVersion !== 1) return null; + const { url, machineId, token } = raw; + if (typeof url !== "string" || typeof machineId !== "string" || typeof token !== "string" || !token) return null; + return selfReportEnrolmentIdOf(url, machineId, token); + } catch { + return null; + } + }; + const override = process.env.FAILPROOFAI_CLOUD_CREDENTIALS; + if (override) return stored(override); + const creds = credentialsFile(); + if (selfReportFilePresence(creds) === "missing") return stored(join(failproofaiHome(), "cloud.json")); + try { + const raw = JSON.parse(readFileSync(creds, "utf8")) as Record; + const cloud = raw?.cloud as Record | undefined; + if (!cloud || typeof cloud !== "object") return null; + const { url, machine_id: machineId, token } = cloud; + if (typeof url !== "string" || typeof machineId !== "string" || typeof token !== "string" || !token) return null; + return selfReportEnrolmentIdOf(url, machineId, token); + } catch { + return null; + } +} + +/** `enrolment_id` in crates/fpai-collect/src/self_report.rs. */ +export function selfReportEnrolmentIdOf(url: string, machineId: string, token: string): string { + const h = createHash("sha256"); + h.update("failproofai self-report enrolment v1"); + for (const part of [url, machineId, token]) { + const bytes = Buffer.from(part, "utf8"); + const len = Buffer.alloc(8); + len.writeBigUInt64BE(BigInt(bytes.length)); + h.update(len); + h.update(bytes); + } + return h.digest().subarray(0, 16).toString("hex"); +} + +function selfReportFilePresence(path: string): "present" | "missing" | "unreadable" { + try { + readFileSync(path); + return "present"; + } catch (err) { + return (err as NodeJS.ErrnoException)?.code === "ENOENT" ? "missing" : "unreadable"; + } +} + +function selfReportOssMode(): boolean { + try { + const raw: unknown = JSON.parse(readFileSync(configFile(), "utf8")); + const mode = raw && typeof raw === "object" && !Array.isArray(raw) ? (raw as { mode?: unknown }).mode : undefined; + return !!mode && typeof mode === "object" && !Array.isArray(mode) && (mode as { kind?: unknown }).kind === "oss"; + } catch { + return false; + } +} + +/** + * Why Self Reports is on or off, in the same order `resolveSelfReport` decides: + * `waiting` is a Cloud-enrolled machine with no setting from its org yet, and + * `unreadable` a settings file that cannot be read or parsed (both are off). + */ +export type SelfReportState = "on" | "off" | "waiting" | "unreadable"; + +export function selfReportSettingsState( + path: string = selfReportSettingsFile(), + enrolled: () => boolean = selfReportCloudEnrolled, + enrolmentId: () => string | null = selfReportEnrolmentId, +): SelfReportState { + const presence = selfReportFilePresence(path); + if (presence === "unreadable") return "unreadable"; + if (presence === "present") { + const file = readEffectiveSelfReport(path); + if (!file) return "unreadable"; + if (!selfReportFileDecides(file, enrolled, enrolmentId)) return "waiting"; + return file.enabled ? "on" : "off"; + } + if (enrolled()) return "waiting"; + return selfReportLocalConfigOff() ? "off" : "on"; +} + +/** The settings only when the feature is on (`resolveSelfReport`); `null` otherwise. */ +export function readEnabledSelfReport(path?: string): SelfReportEffective | null { + const s = resolveSelfReport(path); + return s && s.enabled ? s : null; +} + +/** + * Write `self-report.json` atomically (tmp + fsync + rename), mode 0644. The + * non-Cloud writer; on a Cloud-managed machine the daemon owns this file. + * The mode is set explicitly rather than left to the umask: the SDKs read this + * file from agent processes that may run as another account. + */ +export function writeEffectiveSelfReport( + input: { enabled: boolean; categories?: readonly SelfReportCategory[] | null; guidance?: string | null }, + path: string = selfReportSettingsFile(), +): SelfReportEffective { + const port = selfReportPort(); + const value: SelfReportEffective = { + version: 1, + enabled: input.enabled, + source: "local", + categories: (input.categories && input.categories.length > 0 ? input.categories : SELF_REPORT_DEFAULT_CATEGORIES).map( + (c) => ({ name: c.name, description: c.description }), + ), + guidance: input.guidance ?? null, + mcp: { port, url: selfReportMcpUrl(port) }, + updatedAt: new Date().toISOString().replace(/\.\d{3}Z$/, "Z"), + }; + const dir = dirname(path); + if (!existsSync(dir)) mkdirSync(dir, { recursive: true, mode: 0o700 }); + const tmp = join(dir, `.self-report.json.${process.pid}.${randomBytes(6).toString("hex")}.tmp`); + try { + const fd = openSync(tmp, "wx", 0o644); + try { + writeSync(fd, `${JSON.stringify(value, null, 2)}\n`); + fsyncSync(fd); + } finally { + closeSync(fd); + } + chmodSync(tmp, 0o644); + renameSync(tmp, path); + } catch (err) { + rmSync(tmp, { force: true }); + throw err; + } + return value; +} + +// ── Local config: `selfReport` in config.json (contract §4) ───────────────── + +export interface SelfReportLocalConfig { + enabled: boolean; + categories?: SelfReportCategory[]; + guidance?: string; +} + +/** The `selfReport` block of `~/.failproofai/config.json`, or `null` if absent. */ +export async function readLocalSelfReportConfig(): Promise { + const { readConfigRaw } = await import("./fp-config"); + const block = readConfigRaw().raw.selfReport; + if (!block || typeof block !== "object" || Array.isArray(block)) return null; + const rec = block as Record; + const cats = rec.categories === undefined || rec.categories === null ? null : validateSelfReportCategories(rec.categories); + const guidance = validateSelfReportGuidance(rec.guidance); + return { + enabled: rec.enabled === true, + ...(cats && cats.ok ? { categories: cats.value } : {}), + ...(guidance.ok && guidance.value ? { guidance: guidance.value } : {}), + }; +} + +/** + * Replace the `selfReport` block, keeping every other key in the file as it + * was (the same read-raw-then-write the OTEL settings use, so a key this build + * does not know survives). + */ +export async function writeLocalSelfReportConfig(block: SelfReportLocalConfig): Promise { + const [{ readConfigRaw }, { writeConfigFileAtomic }, { configFile }] = await Promise.all([ + import("./fp-config"), + import("./safe-config-write"), + import("./fp-home"), + ]); + const raw = { ...readConfigRaw().raw }; + raw.selfReport = { + enabled: block.enabled, + ...(block.categories ? { categories: block.categories } : {}), + ...(block.guidance ? { guidance: block.guidance } : {}), + }; + writeConfigFileAtomic(configFile(), `${JSON.stringify(raw, null, 2)}\n`, { backup: false }); +} + +/** + * On install (`policies --install`, `config`): make the effective settings file + * exist, so every reader (the hooks, the stdio server, the daemon's HTTP + * server, the SDKs, `status`) reads the same thing from disk rather than each + * applying the missing-file default on its own. + * + * Writes only when the file is missing and the machine is not Cloud enrolled + * (on Cloud the daemon owns the file). It carries config.json's `selfReport` + * block when there is one — so an explicit `enabled: false` there is written + * as off — and is on with the defaults otherwise. An existing file, even a + * broken one, is left alone: it is the user's or the daemon's, and a broken + * file reads as off until `self-report enable` / `disable` rewrites it. + * Returns what it wrote, or `null` when it wrote nothing. + */ +export async function ensureSelfReportSettingsFile( + path: string = selfReportSettingsFile(), + enrolled: () => boolean = selfReportCloudEnrolled, +): Promise { + if (selfReportFilePresence(path) !== "missing" || enrolled()) return null; + const local = await readLocalSelfReportConfig().catch(() => null); + const enabled = !selfReportLocalConfigOff(); + return writeEffectiveSelfReport( + { enabled, categories: local?.categories ?? null, guidance: local?.guidance ?? null }, + path, + ); +} + +// ── Cloud enrolment ───────────────────────────────────────────────────────── + +/** + * Whether the daemon takes this machine's settings from FailproofAI Cloud, in + * which case Cloud owns `self-report.json` and local enable/disable refuse. + * Mirrors the daemon's `Enrolment::resolve` (cloud_client.rs): the + * `FAILPROOFAI_CLOUD_URL` environment, or a stored cloud credential on a + * machine not switched back to open source (`mode.kind == "oss"`). + */ +export async function selfReportCloudManaged(): Promise { + if (process.env.FAILPROOFAI_CLOUD_URL?.trim()) return true; + try { + const { readCloudCredentials } = await import("./cloud-enrollment"); + if (!readCloudCredentials()) return false; + } catch { + return false; + } + try { + const { configFile } = await import("./fp-home"); + const raw: unknown = JSON.parse(readFileSync(configFile(), "utf8")); + const mode = raw && typeof raw === "object" && !Array.isArray(raw) ? (raw as { mode?: unknown }).mode : undefined; + if (mode && typeof mode === "object" && !Array.isArray(mode) && (mode as { kind?: unknown }).kind === "oss") { + return false; + } + } catch { + // Missing or unreadable config does not veto an enrolled machine (the daemon's rule). + } + return true; +} diff --git a/src/hooks/setup-finish.ts b/src/hooks/setup-finish.ts new file mode 100644 index 000000000..77745d581 --- /dev/null +++ b/src/hooks/setup-finish.ts @@ -0,0 +1,80 @@ +/** + * What `failproofai config` does after the wizard has applied: finish the + * upgrade (restart a Hermes or OpenClaw gateway that still runs an older + * plugin, or none) and bring every hooked agent's Self Reports MCP entry in + * line with `self-report.json`. + * + * All of it runs behind one spinner line and leaves only a line for anything + * that needs the user: a gateway they + * must restart themselves, a Hermes failure, an agent the sync could not + * update. A gateway that is restarting by itself, and the per-agent MCP + * changes, are not the user's to act on, so they are not printed (`self-report + * sync` and `status` show those). + */ +import type { PluggedProfile } from "./update-run"; +import type { TTYOut } from "./tui"; + +export interface FinishSetupOptions { + /** This CLI's version. */ + version: string; + /** The plugged gateway profiles before the wizard ran. */ + pluggedBefore: PluggedProfile[]; + out?: TTYOut; +} + +/** Runs the steps; returns the exit code the upgrade part asks for (0 or 1). */ +export async function finishSetup(opts: FinishSetupOptions): Promise { + const out = opts.out ?? process.stdout; + const { runUpdateSteps, markUpdated, setupNeedsUpdateSteps, setupGatewayLine, restartNewlyPlugged } = await import("./update-run"); + const { progressLine, screenKit, colorsEnabled } = await import("./tui"); + const kit = screenKit({ color: colorsEnabled(out) }); + const keep: string[] = []; + let exit = 0; + const progress = progressLine(out, "Finishing setup…"); + try { + // Self Reports (on by default): write self-report.json when it is missing + // off Cloud, then sync every hooked agent, also when setup found the + // machine already configured and wrote no hooks. Best-effort. Ahead of the + // gateway restarts, so a Hermes or OpenClaw gateway restarts without the + // MCP entry an earlier version wrote (their tool comes from the plugin). + progress.set("Updating Self Reports…"); + const summary = await selfReportSetupSummary(); + if (!setupNeedsUpdateSteps(opts.version)) { + // Already updated on this version: only a profile this run plugged in + // (one created since) has a gateway still running without the plugin. + const gateway = setupGatewayLine(await restartNewlyPlugged(opts.pluggedBefore).catch(() => [])); + if (gateway && !gateway.ok) keep.push(kit.caution(gateway.text)); + } else { + progress.set("Restarting agent gateways…"); + const run = await runUpdateSteps({ layout: false, daemon: false, restart: true }); + keep.push(...run.lines.filter((l) => l.startsWith("✕"))); + const gateway = setupGatewayLine(run.restarts); + if (gateway && !gateway.ok) keep.push(kit.caution(gateway.text)); + if (run.ok) markUpdated(opts.version); + else exit = 1; + } + // Nothing about Self Reports when it worked (`self-report status` says + // where it stands); only an agent the sync could not update needs the user. + if (summary && !summary.ok) keep.push(kit.caution(summary.text, summary.fix)); + } finally { + progress.done(keep); + } + return exit; +} + +/** Write the settings file if missing, sync, and say it in one line (or none). */ +export async function selfReportSetupSummary(): Promise<{ ok: boolean; text: string; fix?: string } | null> { + try { + const { ensureSelfReportSettingsFile, selfReportSettingsState } = await import("./self-report"); + try { + await ensureSelfReportSettingsFile(); + } catch { + // the readers apply the same default without the file + } + const { syncSelfReportMcp, selfReportSummary } = await import("./self-report-install"); + const results = await syncSelfReportMcp({ quiet: true }); + return selfReportSummary(results, selfReportSettingsState()); + } catch { + return null; // never fail setup over it + } +} diff --git a/src/hooks/toml-managed-block.ts b/src/hooks/toml-managed-block.ts new file mode 100644 index 000000000..97e87c4f3 --- /dev/null +++ b/src/hooks/toml-managed-block.ts @@ -0,0 +1,80 @@ +/** + * A comment-delimited block that failproofai owns inside someone else's TOML. + * + * There is no comment-preserving TOML writer in the dependency tree (smol-toml + * parses and stringifies, and stringifying drops every comment), and a full one + * is far more than failproofai needs: it only ever adds or removes ITS OWN + * table. So the table goes between two marker comments, appended at the end of + * the file, and every byte outside the markers is kept exactly as it was. + * Appending at the end is always valid placement for a `[table]` header: TOML + * root keys must come before the first table, so nothing of the user's can be + * captured by our header. + * + * Callers validate the merged text with smol-toml before writing it; this + * module only splices text. + */ + +export interface TomlBlockMarkers { + begin: string; + end: string; +} + +type BlockSpan = { start: number; end: number } | null | "malformed"; + +function escapeRe(s: string): string { + return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); +} + +function findBlock(text: string, markers: TomlBlockMarkers): BlockSpan { + const begin = new RegExp(`^${escapeRe(markers.begin)}[ \\t]*\\r?$`, "m").exec(text); + if (!begin) { + return new RegExp(`^${escapeRe(markers.end)}[ \\t]*\\r?$`, "m").test(text) ? "malformed" : null; + } + const endRe = new RegExp(`^${escapeRe(markers.end)}[ \\t]*\\r?$`, "mg"); + endRe.lastIndex = begin.index + begin[0].length; + const end = endRe.exec(text); + if (!end) return "malformed"; + let stop = end.index + end[0].length; + if (text[stop] === "\n") stop++; + return { start: begin.index, end: stop }; +} + +/** Whether `text` holds a complete block. A half block (one marker) throws. */ +export function hasTomlManagedBlock(text: string, markers: TomlBlockMarkers): boolean { + const span = findBlock(text, markers); + if (span === "malformed") throw new Error(`a failproofai marker (${markers.begin}) is missing its pair`); + return span !== null; +} + +/** The block's own text (markers included), or null when there is none. */ +export function readTomlManagedBlock(text: string, markers: TomlBlockMarkers): string | null { + const span = findBlock(text, markers); + if (span === "malformed") throw new Error(`a failproofai marker (${markers.begin}) is missing its pair`); + return span ? text.slice(span.start, span.end) : null; +} + +/** + * Put `block` into `original` (replacing ours in place when it is there), or + * take ours out when `block` is null. A new block is appended after one blank + * line, which removal takes back out, so add-then-remove on a file that ended + * in a newline returns it byte for byte. + */ +export function mergeTomlManagedBlock(original: string, block: string | null, markers: TomlBlockMarkers): string { + const span = findBlock(original, markers); + if (span === "malformed") throw new Error(`a failproofai marker (${markers.begin}) is missing its pair`); + if (span) { + const before = original.slice(0, span.start); + const after = original.slice(span.end); + if (block !== null) return before + block + after; + const trimmed = before.endsWith("\n\n") && after === "" ? before.slice(0, -1) : before; + return trimmed + after; + } + if (block === null) return original; + if (original === "") return block; + return `${original}${original.endsWith("\n") ? "\n" : "\n\n"}${block}`; +} + +/** A TOML basic string. JSON's string escapes are a subset of TOML's. */ +export function tomlString(value: string): string { + return JSON.stringify(value); +} diff --git a/src/hooks/tool-name-canonicalize.ts b/src/hooks/tool-name-canonicalize.ts index b784d5d91..6bfd2c5c0 100644 --- a/src/hooks/tool-name-canonicalize.ts +++ b/src/hooks/tool-name-canonicalize.ts @@ -6,8 +6,10 @@ * `src/audit/cli-adapters/*.ts` keeps the per-CLI maps in one place. */ import type { IntegrationType } from "./types"; +import { isSelfReportToolName, SELF_REPORT_MCP_TOOL_NAME } from "./self-report-names"; import { CODEX_TOOL_MAP, + CODEX_TOOL_INPUT_MAP, COPILOT_TOOL_MAP, COPILOT_TOOL_INPUT_MAP, CURSOR_TOOL_MAP, @@ -37,6 +39,10 @@ export function canonicalizeToolName( cli: IntegrationType, ): string | undefined { if (!raw) return raw; + // The Self Reports tool, under whatever name this agent gives MCP tools, is + // filed under one name so the hook's short-circuit and the collector see it + // the same way on every agent. + if (isSelfReportToolName(raw, cli)) return SELF_REPORT_MCP_TOOL_NAME; if (cli === "copilot") return COPILOT_TOOL_MAP[raw] ?? raw; if (cli === "cursor") return CURSOR_TOOL_MAP[raw] ?? raw; if (cli === "codex") return CODEX_TOOL_MAP[raw] ?? raw; @@ -81,6 +87,8 @@ export function canonicalizeToolInput( // `old_str`/`new_str`); map to canonical keys so path/content builtins fire // (verified live against Copilot CLI 1.0.71). if (cli === "copilot") perToolMap = COPILOT_TOOL_INPUT_MAP[toolName]; + // Codex transcripts give exec_command `{cmd, workdir}`; map to `command`/`cwd`. + else if (cli === "codex") perToolMap = CODEX_TOOL_INPUT_MAP[toolName]; else if (cli === "opencode") perToolMap = OPENCODE_TOOL_INPUT_MAP[toolName]; else if (cli === "pi") perToolMap = PI_TOOL_INPUT_MAP[toolName]; // Hermes read_file/write_file/patch deliver the file path as `path`; map it to diff --git a/src/hooks/tui.ts b/src/hooks/tui.ts index 7c7071927..2ce3ed30e 100644 --- a/src/hooks/tui.ts +++ b/src/hooks/tui.ts @@ -1662,6 +1662,45 @@ function ctx(opts?: RenderOpts): { cols: number; c: ReturnType } { return { cols: Math.max(20, opts?.cols ?? 80), c: paint(opts?.color ?? false) }; } +/** + * One spinner line for work that has nothing to show until it ends, drawn with + * the kit's `live()` block. `set` changes its text; `done` replaces it with the + * lines to keep (often none). Piped or under NO_COLOR nothing is drawn while it + * runs, and `done` prints its lines once. + */ +export function progressLine(out: TTYOut, text: string): { set(text: string): void; done(lines: string[]): void } { + if (!out.isTTY || !colorsEnabled(out)) { + return { + set() {}, + done(lines) { + if (lines.length > 0) out.write(`${lines.join("\n")}\n`); + }, + }; + } + const c = paint(true); + const region = screenKit(optsFor(out)).live(out); + const frames = "⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏"; + let frame = 0; + let label = text; + const draw = (): void => region.draw(() => [`${c.ink3(frames[frame % frames.length])} ${c.ink3(label)}`]); + draw(); + const spin = setInterval(() => { + frame += 1; + draw(); + }, 100); + spin.unref?.(); + return { + set(next) { + label = next; + draw(); + }, + done(lines) { + clearInterval(spin); + region.done(lines); + }, + }; +} + /** Derive render options from a real stream, honouring NO_COLOR and non-TTY. */ export function optsFor(stdout: TTYOut = process.stdout): Required { return { cols: stdout.columns || 80, color: colorsEnabled(stdout) }; @@ -2461,6 +2500,13 @@ export function screenKit(opts: ScreenKitOpts = {}) { timer = null; pending = null; release(); + if (lines.length === 0) { + // Nothing to leave behind: erase the block and give the cursor back. + const clear = region.lastCount > 0 ? `${ESC}[${region.lastCount}A${ESC}[J` : ""; + if (clear || hidden) out.write(`${clear}${hidden ? `${ESC}[?25h` : ""}`); + region.lastCount = 0; + return; + } repaint(out, region, lines, { cut: false, tail: hidden ? `${ESC}[?25h` : "" }); }, }; diff --git a/src/hooks/typed-shell-input.ts b/src/hooks/typed-shell-input.ts new file mode 100644 index 000000000..d1b4f15e6 --- /dev/null +++ b/src/hooks/typed-shell-input.ts @@ -0,0 +1,218 @@ +/** + * Text an agent types into a shell that is already running. + * + * Codex's `write_stdin` and Copilot's `write_bash` / `write_powershell` send + * keystrokes to a shell an earlier call started. They are canonicalized to + * `Bash` so the shell policies judge them, but their text is not in `command`, + * the one field those policies read: Codex sends it as `chars` + * (`{session_id, chars}`, codex-cli 0.172) and Copilot as `input` + * (`{shellId, input, delay}`, Copilot CLI 1.0.114). With `command` empty every + * shell policy allowed what was typed. + * + * So `handler.ts` moves the text into `command`, as far as it can be read as + * whole command lines, and refuses the rest: + * - An empty write reads a shell's output (Codex polls that way): nothing to judge. + * - Text that ends a line is the lines it runs. + * - Keys alone (Ctrl-C, Ctrl-D, an arrow key, Enter) add no text of their own; + * a line they bring back from history was judged when it was first typed. + * - Everything else is refused: text that does not end its command (no line + * end, a trailing backslash, an open quote or heredoc), because the + * shell runs it once a later write adds the rest, which is then judged + * without it (`rm -rf ~/.fail` now, `proofai` and Enter next); and text + * mixed with editing keys (Tab completion, Ctrl-W, Ctrl-Y, a cursor key), + * because the line the shell runs is then not the text sent. + * + * Text typed into a program the shell started (a REPL, an editor) is judged as + * shell text too: the payload does not say what reads it. + * + * Live codex-cli 0.172 runs no hook at all for `write_stdin`, so for Codex + * this is a second line only: codex-interactive-session.ts refuses opening the + * session in the first place. + */ +import { deny, allow } from "./policy-helpers"; +import type { PolicyContext, PolicyMatcher, PolicyResult } from "./policy-types"; +import type { HookEventType, IntegrationType } from "./types"; + +export const TYPED_INPUT_GUARD_NAME = "failproofai/typed-shell-input-readable"; + +export const TYPED_INPUT_GUARD_DESCRIPTION = + "Refuse text typed into a running shell that failproofai cannot read as whole command lines."; + +export const TYPED_INPUT_GUARD_MATCH: PolicyMatcher = { + events: ["PreToolUse"], + toolNames: ["Bash"], +}; + +/** The raw tool names that type into a running shell, and the field each sends its text in. */ +const TYPING_TOOLS: Partial>> = { + codex: { write_stdin: "chars" }, + copilot: { write_bash: "input", write_powershell: "input" }, +}; + +/** What a typing call's text gives the shell policies to read. */ +export type TypedInput = + /** Lines to judge as a command (`""` when there is nothing to judge). */ + | { kind: "command"; command: string } + /** Text that cannot be read as whole command lines: refused. */ + | { kind: "unreadable"; why: string }; + +/** + * The field a call types its text in, or undefined for a call that types + * nothing. Known by the raw tool name, and by shape for a name the CLI already + * reports as `Bash`: a text field beside a shell id, and no `command`. + */ +function typedTextField(cli: IntegrationType, rawToolName: string | undefined, input: Record): string | undefined { + const byName = rawToolName === undefined ? undefined : TYPING_TOOLS[cli]?.[rawToolName]; + if (byName !== undefined) return byName; + if (input.command !== undefined) return undefined; + if (cli === "codex" && "chars" in input && "session_id" in input) return "chars"; + if (cli === "copilot" && "input" in input && "shellId" in input) return "input"; + return undefined; +} + +// A terminal escape sequence: CSI (`ESC [ … final`), SS3 (`ESC O x`), or ESC and one key. +const ESCAPE_SEQUENCE_RE = /\x1b(?:\[[0-?]*[ -/]*[@-~]|O.|[\s\S])?/g; +// A control character other than a line ending. +const EDITING_KEY_RE = /[\x00-\x09\x0b\x0c\x0e-\x1f\x7f]/; + +/** How `text`, typed into a running shell, reads; see the module comment. */ +export function readTypedText(text: unknown): TypedInput { + if (typeof text !== "string") return { kind: "unreadable", why: "its text is not a string" }; + if (text === "") return { kind: "command", command: "" }; + const withoutEscapes = text.replace(ESCAPE_SEQUENCE_RE, ""); + const visible = withoutEscapes.replace(/[\x00-\x1f\x7f]/g, ""); + if (visible.trim() === "") return { kind: "command", command: "" }; + if (withoutEscapes !== text || EDITING_KEY_RE.test(withoutEscapes)) { + return { kind: "unreadable", why: "it mixes text with editing keys, so the line the shell runs is not the text sent" }; + } + const lines = withoutEscapes.replace(/\r\n?/g, "\n"); + if (!lines.endsWith("\n")) { + return { kind: "unreadable", why: "it does not end its line, so the shell would run it with whatever is typed next" }; + } + const command = lines.slice(0, -1); + if (continuesPastWrite(command)) { + return { kind: "unreadable", why: "its command continues onto a later write, which would be judged without it" }; + } + if (usesShellState(command)) { + return { + kind: "unreadable", + why: "it sets or reads state the running shell keeps between writes (a variable, its directory, an alias or function), which a later write could build on unchecked", + }; + } + return { kind: "command", command }; +} + +/** + * Whether typed text sets or reads state the receiving shell keeps from one + * write to the next. Each write is judged on its own, so a value set in one and + * used in another (`F=hook`, then `cp source $F`), a `cd` in one and a relative + * write in the next, or an alias or function defined earlier, would reach the + * shell unchecked (found by hermes on #1058). So typed text may not expand a + * variable or a substitution, assign one, move the shell, or define or load + * anything; a command that needs any of that is sent on its own. + */ +function usesShellState(command: string): boolean { + // Quoted text is still expanded inside double quotes, so only single-quoted + // spans are taken out before looking for `$` and backticks. + const unquoted = command.replace(/'[^']*'/g, "''"); + if (/[$`]/.test(unquoted)) return true; + for (const line of command.split("\n")) { + for (const piece of line.split(/;|&&|\|\||\||&/)) { + const words = piece.trim().split(/\s+/).filter(Boolean); + let i = 0; + while (i < words.length && /^[A-Za-z_][A-Za-z0-9_]*\+?=/.test(words[i])) i++; + // An assignment with no command after it sets the shell's own variable. + if (i > 0 && i === words.length) return true; + const head = (words[i] ?? "").replace(/^\\/, ""); + if (STATEFUL_BUILTINS.has(head)) return true; + if (/^[A-Za-z_][\w-]*\s*\(\)/.test(piece.trim())) return true; + } + } + return false; +} + +/** Builtins whose effect outlives the line they are typed on. */ +const STATEFUL_BUILTINS = new Set([ + "cd", "pushd", "popd", "export", "declare", "typeset", "local", "readonly", "unset", "alias", "unalias", + "function", "source", ".", "eval", "set", "shopt", "setopt", "unsetopt", "trap", "hash", "enable", + "builtin", "exec", "read", "mapfile", "readarray", "let", "umask", "ulimit", "bind", "complete", "compdef", +]); + +/** + * Whether the shell is still reading the same command when this text ends: a + * trailing backslash, an unclosed quote, or a heredoc whose closing line has + * not been sent. Its rest then arrives in a later write, judged on its own + * (`cp source \` now, `hook` and Enter next). + */ +function continuesPastWrite(command: string): boolean { + let quote: "'" | '"' | null = null; + const heredocs: string[] = []; + const lines = command.split("\n"); + for (let n = 0; n < lines.length; n++) { + const line = lines[n]; + if (quote === null && heredocs.length > 0) { + if (line.replace(/^\t+/, "") === heredocs[0]) heredocs.shift(); + continue; + } + for (let i = 0; i < line.length; i++) { + const ch = line[i]; + if (quote === "'") { + if (ch === "'") quote = null; + } else if (ch === "\\") { + if (i === line.length - 1) return true; + i++; + } else if (quote === '"') { + if (ch === '"') quote = null; + } else if (ch === "'" || ch === '"') { + quote = ch; + } else if (ch === "#" && (i === 0 || /\s/.test(line[i - 1]))) { + break; + } else if (ch === "<" && line[i + 1] === "<" && line[i + 2] !== "<") { + const m = /^<<-?\s*(['"]?)([^\s'"<>;&|()]+)\1/.exec(line.slice(i)); + if (m) { + heredocs.push(m[2]); + i += m[0].length - 1; + } + } + } + } + return quote !== null || heredocs.length > 0; +} + +/** + * For a call that types into a running shell: what its text reads as. + * Undefined for any other call, which is left exactly as it came. + */ +export function typedShellInput( + cli: IntegrationType, + rawToolName: string | undefined, + canonicalToolName: string | undefined, + toolInput: unknown, +): TypedInput | undefined { + if (canonicalToolName !== "Bash" || !toolInput || typeof toolInput !== "object" || Array.isArray(toolInput)) return undefined; + const input = toolInput as Record; + const field = typedTextField(cli, rawToolName, input); + if (field === undefined) return undefined; + return readTypedText(input[field]); +} + +/** + * Lifted by a pause, which is the way through when an agent CLI changes how it + * sends typed text, unless an enforcing Cloud policy is deployed: a pause does + * not suspend those, and they could not read this text either. Same rule as + * `antigravityPathGuardActive`. + */ +export function typedInputGuardActive(paused: boolean, cloudPolicies: ReadonlyArray<{ effect?: string }>): boolean { + return !paused || cloudPolicies.some((p) => p.effect !== "observe"); +} + +/** The guard for one call `handler.ts` found unreadable, saying why. */ +export function typedInputGuardFor(why: string): (ctx: PolicyContext) => PolicyResult { + return (ctx) => { + if ((ctx.eventType as HookEventType | string) !== "PreToolUse") return allow(); + return deny( + `failproofai refused this input to a running shell because ${why}. ` + + "Send whole command lines ending in a newline, with no editing keys.", + ); + }; +} diff --git a/src/hooks/types.ts b/src/hooks/types.ts index e719b1e6f..3f5af411a 100644 --- a/src/hooks/types.ts +++ b/src/hooks/types.ts @@ -68,11 +68,23 @@ export const CODEX_EVENT_MAP: Record = { * Local Codex sessions also expose `write_stdin` (sends input to a running * shell — same risk class as Bash). Map the two non-canonical names so * builtin policies fire; everything else (MCP `mcp__*`, future tools) - * passes through. + * passes through. `write_stdin`'s text arrives in `chars`, not `command`: + * typed-shell-input.ts moves it there (as it does Copilot `write_bash`'s + * `input`) and refuses text it cannot read as whole command lines. */ export const CODEX_TOOL_MAP: Record = { apply_patch: "Edit", write_stdin: "Bash", + // Transcripts (audit) name the shell tool `exec_command {cmd, workdir}`, + // both as a function_call and inside a code-mode `exec` snippet. Live hooks + // already receive `Bash`, so this entry only reaches the audit. + exec_command: "Bash", +}; + +// Codex tool-INPUT keys, keyed by canonical name. Only `exec_command`'s +// transcript arguments need it; the live Bash payload is already `command`. +export const CODEX_TOOL_INPUT_MAP: Record> = { + Bash: { cmd: "command", workdir: "cwd" }, }; // ── Hermes (hermes-agent) ─────────────────────────────────────────────────── @@ -1125,6 +1137,13 @@ export interface SessionMetadata { rawHookEventName?: string; /** Which agent CLI fired this hook (claude | codex | copilot | cursor | opencode | pi | hermes | openclaw | factory | devin | antigravity | goose). Set by handler.ts from --cli. */ cli?: IntegrationType; + /** + * The settings file this hook was installed in, as the hook process resolved + * it from the agent's own environment (`CLAUDE_CONFIG_DIR`, `CODEX_HOME`, + * `HERMES_HOME`, …). Absent when it could not tell. The always-on guard + * protects it even where it sits outside every directory the guard knows. + */ + agentSettingsPath?: string; } export interface ClaudeSettings { diff --git a/src/hooks/uninstall-cli.ts b/src/hooks/uninstall-cli.ts index 158e4225f..fbf8e897a 100644 --- a/src/hooks/uninstall-cli.ts +++ b/src/hooks/uninstall-cli.ts @@ -48,6 +48,7 @@ import { import { listInstallableIds, getIntegration } from "./integrations"; import type { IntegrationType } from "./types"; import { removeHooks } from "./manager"; +import { removeSelfReportMcp, selfReportRegistrationStatus } from "./self-report-install"; import { shellQuote } from "./shell-quote"; import { NO_PRINTED_COMMAND_REASON, sudoCommandLine } from "./system-command"; import { installedAgentSkillDirs, removeAgentSkill } from "./agent-skill"; @@ -128,6 +129,18 @@ interface Leftovers { stagedBinaryDir: string | null; daemonConfigured: boolean; homeExists: boolean; + /** + * Agent config files holding failproofai's own Self Reports MCP entry, hooked + * or not: an entry left after its hooks were removed by hand is exactly the + * kind of orphan this command clears. + */ + selfReportMcpPaths: string[]; + /** + * Agent config files that could not be inspected for that entry (unreadable + * or malformed). Not proof the entry is absent, so they are not "nothing to + * uninstall": the removal step tries them and reports any it cannot clean. + */ + selfReportMcpErrors: Array<{ path: string; error: string }>; } function survey(cwd?: string): Leftovers { @@ -169,9 +182,27 @@ function survey(cwd?: string): Leftovers { stagedBinaryDir: stagedBinaryDir && existsSync(stagedBinaryDir) ? stagedBinaryDir : null, daemonConfigured, homeExists: existsSync(failproofaiHome()), + ...selfReportMcpSurvey(), }; } +function selfReportMcpSurvey(): Pick { + try { + const rows = selfReportRegistrationStatus({ hooksInstalled: () => false }); + return { + selfReportMcpPaths: rows.filter((r) => r.registered).map((r) => r.path), + selfReportMcpErrors: rows + .filter((r) => r.error !== undefined) + .map((r) => ({ path: r.path || `${r.agent}'s MCP settings`, error: r.error! })), + }; + } catch (err) { + return { + selfReportMcpPaths: [], + selfReportMcpErrors: [{ path: "agent MCP settings", error: err instanceof Error ? err.message : String(err) }], + }; + } +} + export async function runUninstallCommand(opts: UninstallOptions = {}): Promise { const found = survey(opts.cwd); const kit = screenKit(opts.render ?? optsFor(process.stdout)); @@ -181,7 +212,9 @@ export async function runUninstallCommand(opts: UninstallOptions = {}): Promise< const lines: string[] = []; const nothingToDo = - found.clis.length === 0 && found.skillDirs.length === 0 && !found.serviceInstalled && !found.stagedBinaryDir && !found.daemonConfigured && + found.clis.length === 0 && found.skillDirs.length === 0 && found.selfReportMcpPaths.length === 0 && + found.selfReportMcpErrors.length === 0 && + !found.serviceInstalled && !found.stagedBinaryDir && !found.daemonConfigured && !(opts.purge && found.homeExists); if (nothingToDo) { return { @@ -207,6 +240,12 @@ export async function runUninstallCommand(opts: UninstallOptions = {}): Promise< const removals: string[] = []; if (found.clis.length > 0) removals.push(`failproofai's hooks from ${many(found.clis.length, "agent")}`); if (found.skillDirs.length > 0) removals.push(`the failproofai skill from ${many(found.skillDirs.length, "agent folder")}`); + if (found.selfReportMcpPaths.length > 0) { + removals.push(`the Self Reports MCP server from ${many(found.selfReportMcpPaths.length, "agent config")}`); + } + if (found.selfReportMcpErrors.length > 0 && found.selfReportMcpPaths.length === 0) { + removals.push(`any Self Reports MCP server from ${many(found.selfReportMcpErrors.length, "agent config")} that could not be read`); + } if (found.serviceInstalled) removals.push("the failproofaid service (needs sudo)"); else if (found.stagedBinaryDir) removals.push(`the failproofaid binary in ${found.stagedBinaryDir} (needs sudo)`); if (purging) removals.push(home); @@ -225,6 +264,9 @@ export async function runUninstallCommand(opts: UninstallOptions = {}): Promise< "Also resets enabled policies, custom policy paths and policy parameters in policies-config.json.", ); } + for (const { path, error } of found.selfReportMcpErrors) { + details.push(`Could not read ${path} (${error}); failproofai's MCP entry may still be in it.`); + } if (purging) details.push(`${home} holds your settings, credentials, audit history and the daemon binary.`); else if (found.homeExists) { details.push(`${found.clis.length > 0 ? "The rest of " : ""}${home} is kept unless you add --purge.`); @@ -338,6 +380,19 @@ export async function runUninstallCommand(opts: UninstallOptions = {}): Promise< } } + // Self Reports: failproofai's MCP server comes out of every agent, hooked or + // not, so nothing is left pointing at a CLI or daemon this run removes. + try { + const mcp = removeSelfReportMcp({ quiet: true }); + const removedFrom = mcp.filter((r) => r.action === "removed").length; + if (removedFrom > 0) lines.push(kit.ok(`Removed the Self Reports MCP server from ${many(removedFrom, "agent config")}.`)); + for (const r of mcp.filter((x) => x.status === "error")) { + failures.push(`Could not remove the Self Reports MCP server from ${r.path}: ${r.detail ?? "unknown error"}`); + } + } catch (err) { + failures.push(`Could not remove the Self Reports MCP server: ${errText(err)}`); + } + if (found.skillDirs.length > 0) { const left = found.skillDirs.length - removeAgentSkill().length; if (left === 0) lines.push(kit.ok(`Removed the failproofai skill from ${many(found.skillDirs.length, "agent folder")}.`)); diff --git a/src/hooks/update-run.ts b/src/hooks/update-run.ts index 320ca6135..4bbf1d24a 100644 --- a/src/hooks/update-run.ts +++ b/src/hooks/update-run.ts @@ -11,7 +11,7 @@ * already migrated the home, so `config` skips those two. */ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; -import { dirname } from "node:path"; +import { dirname, resolve } from "node:path"; import { updatedVersionFile } from "./fp-home"; import type { GatewayRestart } from "./gateway-restart"; @@ -140,9 +140,24 @@ export async function runUpdateSteps(opts: UpdateStepsOptions): Promise p.status === "migrated").length; if (hermesResult.lines.length > 0) { // Its lines open on a "Hermes:" heading over one row per profile; on a // failure the heading carries the ✕ and the rows say which profile. + // Printed only when something needs the user (a failure, a migration + // with its advice, a gateway to restart by hand). "already current, + // gateway restarting" is routine: it is kept for `self-report status + // --verbose` instead. const [heading, ...rest] = hermesResult.lines; - lines.push("", hermesResult.ok ? heading : `✕ ${heading}`, ...rest); + const needsUser = !hermesResult.ok || hermesMigrated > 0 || restarts.some(needsManualRestart); + if (needsUser) lines.push("", hermesResult.ok ? heading : `✕ ${heading}`, ...rest); + else gatewayRows.push(...rest); } - hermesOk = hermesResult.ok; - hermesMigrated = hermesResult.profiles.filter((p) => p.status === "migrated").length; // "already current" with no gateway touched is not news. changed = changed || !hermesOk || hermesMigrated > 0 || mentionsGateway(hermesResult.lines); @@ -177,16 +198,19 @@ export async function runUpdateSteps(opts: UpdateStepsOptions): Promise 0) { - lines.push("", ...restartLines); - changed = true; - } + // Only a gateway the user has to restart is printed; the rest is kept + // for `self-report status`. + const restartLines = restart.openclawRestartLines(openclaw.filter(needsManualRestart)); + if (restartLines.length > 0) lines.push("", ...restartLines); + gatewayRows.push(...restart.openclawRestartLines(openclaw).slice(1)); + if (openclaw.some((r) => r.status === "restarting" || needsManualRestart(r))) changed = true; } catch { // Restarting is a convenience; the update itself already succeeded. } } + if (gatewayRows.length > 0) writeGatewayReport(gatewayRows.map((l) => l.trim().replace(/\s{2,}/g, " "))); + return { lines, ok: daemonOk && !migrationFailed && hermesOk && codexOk, @@ -265,6 +289,38 @@ export async function restartNewlyPlugged( return fresh.map((p) => (p.host === "hermes" ? hermes(p) : openclaw(p))); } +function needsManualRestart(r: GatewayRestart): boolean { + return r.status === "not-supervised" || r.status === "failed"; +} + +/** Where the last update's routine gateway rows are kept. */ +export function gatewayReportFile(home?: string): string { + return resolve(dirname(updatedVersionFile(home)), "gateway-report.json"); +} + +/** Keep the last update's routine gateway rows (`hermes/default already current, gateway restarting`). Best effort. */ +export function writeGatewayReport(rows: string[], home?: string, now = new Date()): void { + try { + const file = gatewayReportFile(home); + if (!existsSync(dirname(file))) mkdirSync(dirname(file), { recursive: true, mode: 0o700 }); + writeFileSync(file, `${JSON.stringify({ at: now.toISOString(), rows })}\n`, { mode: 0o600 }); + } catch { + // only `self-report status` reads it + } +} + +/** The last update's routine gateway rows, or null. */ +export function readGatewayReport(home?: string): { at: string; rows: string[] } | null { + try { + const parsed = JSON.parse(readFileSync(gatewayReportFile(home), "utf8")) as { at?: unknown; rows?: unknown }; + if (typeof parsed.at !== "string" || !Array.isArray(parsed.rows)) return null; + const rows = parsed.rows.filter((r): r is string => typeof r === "string"); + return rows.length > 0 ? { at: parsed.at, rows } : null; + } catch { + return null; + } +} + function mentionsGateway(lines: string[]): boolean { return lines.some((l) => /gateway/.test(l)); } diff --git a/src/hooks/worker-server.ts b/src/hooks/worker-server.ts index bba1e80f0..a4db89bbe 100644 --- a/src/hooks/worker-server.ts +++ b/src/hooks/worker-server.ts @@ -282,6 +282,8 @@ function handleConnection(socket: Socket, shutdown: () => void): void { // "absent" as null. fallbackCwd: request.cwd ?? undefined, agentSettingsPath: request.agentSettingsPath ?? undefined, + // This process has the daemon's environment, not the agent's. + inWorker: true, releaseRegistry: release, }); deliver( diff --git a/test-fixtures/self-report/arg-aliases.json b/test-fixtures/self-report/arg-aliases.json new file mode 100644 index 000000000..1c0b73bae --- /dev/null +++ b/test-fixtures/self-report/arg-aliases.json @@ -0,0 +1,58 @@ +{ + "aliases": { + "category": ["type", "kind"], + "detail": ["summary", "sentence", "message", "description", "reason", "text", "details"] + }, + "cases": [ + { + "args": {"category": "looping", "detail": "Same test fails after three fixes."}, + "category": "looping", + "detail": "Same test fails after three fixes." + }, + { + "args": {"category": "missing_context", "summary": "No access to the staging database."}, + "category": "missing_context", + "detail": "No access to the staging database." + }, + { + "args": {"category": "task_failure", "sentence": "The build never finishes."}, + "category": "task_failure", + "detail": "The build never finishes." + }, + { + "args": {"category": "looping", "detail": "", "sentence": "", "message": "Going in circles."}, + "category": "looping", + "detail": "Going in circles." + }, + { + "args": {"category": "looping", "detail": "Kept.", "summary": "Ignored."}, + "category": "looping", + "detail": "Kept." + }, + { + "args": {"type": "invalid_tool_or_credential", "details": "The API key is rejected."}, + "category": "invalid_tool_or_credential", + "detail": "The API key is rejected." + }, + { + "args": {"category": "", "kind": "cannot_do_request", "reason": "No deploy permission."}, + "category": "cannot_do_request", + "detail": "No deploy permission." + }, + { + "args": {"category": "looping", "type": "ignored", "text": "Later in the list.", "description": "Earlier in the list."}, + "category": "looping", + "detail": "Earlier in the list." + }, + { + "args": {"category": "looping", "unknown": "Not an alias.", "priority": "high"}, + "category": "looping", + "detail": "" + }, + { + "args": {}, + "category": "", + "detail": "" + } + ] +} diff --git a/test-fixtures/self-report/categories.golden.json b/test-fixtures/self-report/categories.golden.json new file mode 100644 index 000000000..ba4e4c7c7 --- /dev/null +++ b/test-fixtures/self-report/categories.golden.json @@ -0,0 +1,26 @@ +[ + { + "name": "looping", + "description": "You keep repeating the same or circular steps without making progress." + }, + { + "name": "cannot_do_request", + "description": "The user asked for something you cannot do here: a missing capability, tool or permission, or it is only possible by cheating." + }, + { + "name": "invalid_tool_or_credential", + "description": "A tool, MCP server, plugin, API key or token you need is broken, invalid, expired or rejected." + }, + { + "name": "missing_context", + "description": "Information or access you need is missing and you cannot get it yourself. Not for normal clarifying questions." + }, + { + "name": "repeated_tool_failure", + "description": "A command or tool failed on several distinct attempts and is blocking you. A single error is not enough." + }, + { + "name": "task_failure", + "description": "You genuinely tried and could not complete the task, or something else blocks you that no other category describes. Not for refusals or policy blocks." + } +] diff --git a/test-fixtures/self-report/category-inference.json b/test-fixtures/self-report/category-inference.json new file mode 100644 index 000000000..c2567bbe4 --- /dev/null +++ b/test-fixtures/self-report/category-inference.json @@ -0,0 +1,151 @@ +{ + "rules": [ + { + "category": "invalid_tool_or_credential", + "keywords": ["token", "api key", "apikey", "api_key", "credential", "unauthorized", "unauthenticated", "forbidden", "401", "403", "expired", "revoked", "auth", "password", "secret"] + }, + { + "category": "looping", + "keywords": ["loop", "looping", "circular", "in circles", "repeating the same"] + }, + { + "category": "repeated_tool_failure", + "keywords": ["keeps failing", "keep failing", "repeatedly", "several attempts", "multiple attempts", "retried", "retries", "again and again"] + }, + { + "category": "missing_context", + "keywords": ["missing", "not found", "no information", "not provided", "cannot find", "can't find", "need more information", "unclear"] + }, + { + "category": "cannot_do_request", + "keywords": ["cannot", "can't", "unable", "not possible", "impossible", "not supported", "unsupported", "not allowed"] + } + ], + "fallback": "task_failure", + "cases": [ + { + "name": "the live case: no category, a missing token in the detail", + "args": {"detail": "Deployment is blocked because ./deploy.sh exits with \"DEPLOY_TOKEN is not set\" and no token is available in this environment."}, + "category": "invalid_tool_or_credential", + "inferred": true + }, + { + "name": "an exact listed name is kept", + "args": {"category": "looping", "detail": "The API key is rejected."}, + "category": "looping", + "inferred": false + }, + { + "name": "a near-miss spelling is normalised", + "args": {"category": "Invalid Tool Or Credential", "detail": "The build failed."}, + "category": "invalid_tool_or_credential", + "inferred": true + }, + { + "name": "hyphens and padding are normalised", + "args": {"category": " missing-context ", "detail": ""}, + "category": "missing_context", + "inferred": true + }, + { + "name": "empty category and no keyword falls back to task_failure", + "args": {"category": "", "detail": "The build never finishes."}, + "category": "task_failure", + "inferred": true + }, + { + "name": "no arguments at all falls back to task_failure", + "args": {}, + "category": "task_failure", + "inferred": true + }, + { + "name": "an unknown category with no keyword falls back to task_failure", + "args": {"category": "command_nonzero_exit", "detail": "the build failed"}, + "category": "task_failure", + "inferred": true + }, + { + "name": "the unknown category text is searched too", + "args": {"category": "auth_error", "detail": "Something broke."}, + "category": "invalid_tool_or_credential", + "inferred": true + }, + { + "name": "auth does not match inside author", + "args": {"detail": "The author of the change is unknown."}, + "category": "task_failure", + "inferred": true + }, + { + "name": "a 403 is a credential problem", + "args": {"detail": "The registry answers HTTP 403 for every push."}, + "category": "invalid_tool_or_credential", + "inferred": true + }, + { + "name": "looping", + "args": {"category": "stuck", "detail": "I am going in circles on the same test."}, + "category": "looping", + "inferred": true + }, + { + "name": "repeated tool failure", + "args": {"detail": "The linter keeps failing on the generated file."}, + "category": "repeated_tool_failure", + "inferred": true + }, + { + "name": "missing context", + "args": {"detail": "The staging database URL is not provided anywhere."}, + "category": "missing_context", + "inferred": true + }, + { + "name": "cannot do the request", + "args": {"detail": "Sending email is not supported here."}, + "category": "cannot_do_request", + "inferred": true + }, + { + "name": "the first matching rule wins", + "args": {"detail": "Unable to continue: the token expired."}, + "category": "invalid_tool_or_credential", + "inferred": true + }, + { + "name": "an alias carries the category", + "args": {"type": "Looping", "summary": "Same fix again."}, + "category": "looping", + "inferred": true + }, + { + "name": "a rule whose target is not listed is skipped", + "categories": ["data_gap", "blocked"], + "args": {"detail": "The token expired."}, + "category": "data_gap", + "inferred": true + }, + { + "name": "a custom list without task_failure falls back to its first category", + "categories": ["data_gap", "blocked"], + "args": {"category": "", "detail": "Nothing matches here."}, + "category": "data_gap", + "inferred": true + }, + { + "name": "a custom list keeps its own names and still infers listed targets", + "categories": ["blocked", "missing_context"], + "args": {"category": "whatever", "detail": "The ticket number is missing."}, + "category": "missing_context", + "inferred": true + }, + { + "name": "a custom name is kept exactly", + "categories": ["blocked", "missing_context"], + "args": {"category": "blocked", "detail": "The token expired."}, + "category": "blocked", + "inferred": false + } + ] +} diff --git a/test-fixtures/self-report/description-guidance.golden.txt b/test-fixtures/self-report/description-guidance.golden.txt new file mode 100644 index 000000000..b86f97eac --- /dev/null +++ b/test-fixtures/self-report/description-guidance.golden.txt @@ -0,0 +1,12 @@ +When you are stuck on something you cannot fix yourself, call this tool once with `category` (one of the categories below) and `detail` (one factual sentence: what is blocking you). It reports to FailproofAI. Call it BEFORE your final answer, for example for a missing, invalid or expired token or API key, a 401 or 403, a command, tool or MCP server that keeps failing, information or access you cannot get, or a request you cannot do here. Do not call it for normal work, clarifying questions or an error you then fixed. One call per distinct problem. +Reporting does not unblock you and changes no decision: afterwards, work around the problem or tell the user what is blocking you. There is no need to mention this report to the user. + +Categories: +- looping: You keep repeating the same or circular steps without making progress. +- cannot_do_request: The user asked for something you cannot do here: a missing capability, tool or permission, or it is only possible by cheating. +- invalid_tool_or_credential: A tool, MCP server, plugin, API key or token you need is broken, invalid, expired or rejected. +- missing_context: Information or access you need is missing and you cannot get it yourself. Not for normal clarifying questions. +- repeated_tool_failure: A command or tool failed on several distinct attempts and is blocking you. A single error is not enough. +- task_failure: You genuinely tried and could not complete the task, or something else blocks you that no other category describes. Not for refusals or policy blocks. + +Report a missing repository as missing_context. \ No newline at end of file diff --git a/test-fixtures/self-report/description.golden.txt b/test-fixtures/self-report/description.golden.txt new file mode 100644 index 000000000..00a88d3ad --- /dev/null +++ b/test-fixtures/self-report/description.golden.txt @@ -0,0 +1,10 @@ +When you are stuck on something you cannot fix yourself, call this tool once with `category` (one of the categories below) and `detail` (one factual sentence: what is blocking you). It reports to FailproofAI. Call it BEFORE your final answer, for example for a missing, invalid or expired token or API key, a 401 or 403, a command, tool or MCP server that keeps failing, information or access you cannot get, or a request you cannot do here. Do not call it for normal work, clarifying questions or an error you then fixed. One call per distinct problem. +Reporting does not unblock you and changes no decision: afterwards, work around the problem or tell the user what is blocking you. There is no need to mention this report to the user. + +Categories: +- looping: You keep repeating the same or circular steps without making progress. +- cannot_do_request: The user asked for something you cannot do here: a missing capability, tool or permission, or it is only possible by cheating. +- invalid_tool_or_credential: A tool, MCP server, plugin, API key or token you need is broken, invalid, expired or rejected. +- missing_context: Information or access you need is missing and you cannot get it yourself. Not for normal clarifying questions. +- repeated_tool_failure: A command or tool failed on several distinct attempts and is blocking you. A single error is not enough. +- task_failure: You genuinely tried and could not complete the task, or something else blocks you that no other category describes. Not for refusals or policy blocks. \ No newline at end of file diff --git a/test-fixtures/self-report/event-fields.golden.json b/test-fixtures/self-report/event-fields.golden.json new file mode 100644 index 000000000..c3e05f61f --- /dev/null +++ b/test-fixtures/self-report/event-fields.golden.json @@ -0,0 +1,5 @@ +{ + "order": ["timestamp", "session_id", "agent_id", "type", "category", "detail", "source", "environment"], + "optional": ["tool_call_id"], + "fallbackExtras": ["integration"] +} diff --git a/test-fixtures/self-report/input-schema.golden.json b/test-fixtures/self-report/input-schema.golden.json new file mode 100644 index 000000000..4b468f14c --- /dev/null +++ b/test-fixtures/self-report/input-schema.golden.json @@ -0,0 +1 @@ +{"type":"object","properties":{"category":{"type":"string","enum":["looping","cannot_do_request","invalid_tool_or_credential","missing_context","repeated_tool_failure","task_failure"]},"detail":{"type":"string","description":"One factual sentence: what is blocking you."}},"required":["category","detail"],"additionalProperties":false} diff --git a/test-fixtures/self-report/instructions-guidance.golden.txt b/test-fixtures/self-report/instructions-guidance.golden.txt new file mode 100644 index 000000000..050030c2f --- /dev/null +++ b/test-fixtures/self-report/instructions-guidance.golden.txt @@ -0,0 +1,3 @@ +When you are stuck, call failproofai_local's `report` tool once with `category` and `detail` (one factual sentence: what is blocking you). Stuck means something you cannot fix yourself: a missing or expired token or key, a 401 or 403, a command or tool that keeps failing, information you cannot get, a request you cannot do. `category` is one of: looping, cannot_do_request, invalid_tool_or_credential, missing_context, repeated_tool_failure, task_failure. Call it before your final answer, not when the task succeeded. It does not unblock you, and there is no need to mention it to the user. + +Report a missing repository as missing_context. \ No newline at end of file diff --git a/test-fixtures/self-report/instructions.golden.txt b/test-fixtures/self-report/instructions.golden.txt new file mode 100644 index 000000000..fda449a8f --- /dev/null +++ b/test-fixtures/self-report/instructions.golden.txt @@ -0,0 +1 @@ +When you are stuck, call failproofai_local's `report` tool once with `category` and `detail` (one factual sentence: what is blocking you). Stuck means something you cannot fix yourself: a missing or expired token or key, a 401 or 403, a command or tool that keeps failing, information you cannot get, a request you cannot do. `category` is one of: looping, cannot_do_request, invalid_tool_or_credential, missing_context, repeated_tool_failure, task_failure. Call it before your final answer, not when the task succeeded. It does not unblock you, and there is no need to mention it to the user. \ No newline at end of file diff --git a/test-fixtures/self-report/server-records.golden.txt b/test-fixtures/self-report/server-records.golden.txt new file mode 100644 index 000000000..5c7de041d --- /dev/null +++ b/test-fixtures/self-report/server-records.golden.txt @@ -0,0 +1,10 @@ +openclaw +pi +devin +hermes +goose +factory +antigravity +copilot +opencode +cursor diff --git a/test-fixtures/self-report/settings-cases.golden.json b/test-fixtures/self-report/settings-cases.golden.json new file mode 100644 index 000000000..b2f989df7 --- /dev/null +++ b/test-fixtures/self-report/settings-cases.golden.json @@ -0,0 +1,320 @@ +{ + "_comment": "Every Self Reports settings reader (the CLI's resolveSelfReport, the daemon's effective_settings and its HTTP settings cache) must reach the same on/off for each case. `file` null means no self-report.json; `text` is a raw file body. `currentEnrolment` is the enrolment id the machine is enrolled as (absent while enrolled: the credential cannot be read); a cloud file decides only when its `enrolment` matches it.", + "cases": [ + { + "name": "no file, not enrolled: on by default", + "file": null, + "enrolled": false, + "on": true + }, + { + "name": "no file, enrolled: off until the daemon writes the org setting", + "file": null, + "enrolled": true, + "on": false, + "currentEnrolment": "enrolment-a" + }, + { + "name": "local file on, not enrolled", + "file": { + "version": 1, + "enabled": true, + "source": "local", + "categories": [ + { + "name": "looping", + "description": "You keep repeating the same or circular steps without making progress." + } + ], + "guidance": null, + "mcp": { + "port": 4319, + "url": "http://127.0.0.1:4319/mcp" + }, + "updatedAt": "2026-11-27T10:00:00Z" + }, + "enrolled": false, + "on": true + }, + { + "name": "local file on, enrolled: ignored until the org setting arrives", + "file": { + "version": 1, + "enabled": true, + "source": "local", + "categories": [ + { + "name": "looping", + "description": "You keep repeating the same or circular steps without making progress." + } + ], + "guidance": null, + "mcp": { + "port": 4319, + "url": "http://127.0.0.1:4319/mcp" + }, + "updatedAt": "2026-11-27T10:00:00Z" + }, + "enrolled": true, + "on": false, + "currentEnrolment": "enrolment-a" + }, + { + "name": "local file off, not enrolled", + "file": { + "version": 1, + "enabled": false, + "source": "local", + "categories": [ + { + "name": "looping", + "description": "You keep repeating the same or circular steps without making progress." + } + ], + "guidance": null, + "mcp": { + "port": 4319, + "url": "http://127.0.0.1:4319/mcp" + }, + "updatedAt": "2026-11-27T10:00:00Z" + }, + "enrolled": false, + "on": false + }, + { + "name": "cloud file on, enrolled", + "file": { + "version": 1, + "enabled": true, + "source": "cloud", + "categories": [ + { + "name": "looping", + "description": "You keep repeating the same or circular steps without making progress." + } + ], + "guidance": null, + "mcp": { + "port": 4319, + "url": "http://127.0.0.1:4319/mcp" + }, + "updatedAt": "2026-11-27T10:00:00Z", + "enrolment": "enrolment-a" + }, + "enrolled": true, + "on": true, + "currentEnrolment": "enrolment-a" + }, + { + "name": "cloud file on, enrolled as another org: off until this org's setting arrives", + "file": { + "version": 1, + "enabled": true, + "source": "cloud", + "categories": [ + { + "name": "looping", + "description": "You keep repeating the same or circular steps without making progress." + } + ], + "guidance": null, + "mcp": { + "port": 4319, + "url": "http://127.0.0.1:4319/mcp" + }, + "updatedAt": "2026-11-27T10:00:00Z", + "enrolment": "enrolment-a" + }, + "enrolled": true, + "on": false, + "currentEnrolment": "enrolment-b" + }, + { + "name": "cloud file on with no enrolment (an older daemon), enrolled: off until rewritten", + "file": { + "version": 1, + "enabled": true, + "source": "cloud", + "categories": [ + { + "name": "looping", + "description": "You keep repeating the same or circular steps without making progress." + } + ], + "guidance": null, + "mcp": { + "port": 4319, + "url": "http://127.0.0.1:4319/mcp" + }, + "updatedAt": "2026-11-27T10:00:00Z" + }, + "enrolled": true, + "on": false, + "currentEnrolment": "enrolment-a" + }, + { + "name": "cloud file on, enrolled with an unreadable credential: off", + "file": { + "version": 1, + "enabled": true, + "source": "cloud", + "categories": [ + { + "name": "looping", + "description": "You keep repeating the same or circular steps without making progress." + } + ], + "guidance": null, + "mcp": { + "port": 4319, + "url": "http://127.0.0.1:4319/mcp" + }, + "updatedAt": "2026-11-27T10:00:00Z", + "enrolment": "enrolment-a" + }, + "enrolled": true, + "on": false + }, + { + "name": "cloud file off, enrolled", + "file": { + "version": 1, + "enabled": false, + "source": "cloud", + "categories": [ + { + "name": "looping", + "description": "You keep repeating the same or circular steps without making progress." + } + ], + "guidance": null, + "mcp": { + "port": 4319, + "url": "http://127.0.0.1:4319/mcp" + }, + "updatedAt": "2026-11-27T10:00:00Z", + "enrolment": "enrolment-a" + }, + "enrolled": true, + "on": false, + "currentEnrolment": "enrolment-a" + }, + { + "name": "cloud file on, not enrolled (left from an org; the daemon removes it)", + "file": { + "version": 1, + "enabled": true, + "source": "cloud", + "categories": [ + { + "name": "looping", + "description": "You keep repeating the same or circular steps without making progress." + } + ], + "guidance": null, + "mcp": { + "port": 4319, + "url": "http://127.0.0.1:4319/mcp" + }, + "updatedAt": "2026-11-27T10:00:00Z", + "enrolment": "enrolment-a" + }, + "enrolled": false, + "on": true + }, + { + "name": "version 2, local, on, not enrolled: unsupported, off", + "file": { + "version": 2, + "enabled": true, + "source": "local", + "categories": [ + { + "name": "looping", + "description": "You keep repeating the same or circular steps without making progress." + } + ], + "guidance": null, + "mcp": { + "port": 4319, + "url": "http://127.0.0.1:4319/mcp" + }, + "updatedAt": "2026-11-27T10:00:00Z" + }, + "enrolled": false, + "on": false + }, + { + "name": "version 2, cloud, on, enrolled: unsupported, off", + "file": { + "version": 2, + "enabled": true, + "source": "cloud", + "categories": [ + { + "name": "looping", + "description": "You keep repeating the same or circular steps without making progress." + } + ], + "guidance": null, + "mcp": { + "port": 4319, + "url": "http://127.0.0.1:4319/mcp" + }, + "updatedAt": "2026-11-27T10:00:00Z", + "enrolment": "enrolment-a" + }, + "enrolled": true, + "on": false, + "currentEnrolment": "enrolment-a" + }, + { + "name": "version 0: unsupported, off", + "file": { + "version": 0, + "enabled": true, + "source": "local", + "categories": [ + { + "name": "looping", + "description": "You keep repeating the same or circular steps without making progress." + } + ], + "guidance": null, + "mcp": { + "port": 4319, + "url": "http://127.0.0.1:4319/mcp" + }, + "updatedAt": "2026-11-27T10:00:00Z" + }, + "enrolled": false, + "on": false + }, + { + "name": "unparsable file: off", + "text": "{not json", + "enrolled": false, + "on": false + } + ], + "enrolmentIds": [ + { + "url": "https://app.example.test", + "machineId": "machine-1", + "token": "tok-org-a", + "id": "6717885485f102770227c9e8b66bd52f" + }, + { + "url": "https://app.example.test", + "machineId": "machine-1", + "token": "tok-org-b", + "id": "fad1c08a1a8ea89c571d6f3f942c3400" + }, + { + "url": "http://localhost:3000/", + "machineId": "m-ü", + "token": "t", + "id": "9cf9e654c5587423dd7500f1786f16af" + } + ] +} diff --git a/test-fixtures/self-report/tool-names.golden.txt b/test-fixtures/self-report/tool-names.golden.txt new file mode 100644 index 000000000..20a7f567e --- /dev/null +++ b/test-fixtures/self-report/tool-names.golden.txt @@ -0,0 +1,13 @@ +mcp__failproofai_local__report +failproofai_local___report +failproofai_local__report +failproofai_report +failproofai_local_report +failproofai_local.report +failproofai_local/report +failproofai_local:report +mcp_failproofai_local_report +mcp__failproofai_local_report +mcp:failproofai_local:report +mcp:failproofai_local/report +failproofai_local-report diff --git a/test-fixtures/self-report/truncation.golden.json b/test-fixtures/self-report/truncation.golden.json new file mode 100644 index 000000000..fde34a014 --- /dev/null +++ b/test-fixtures/self-report/truncation.golden.json @@ -0,0 +1,29 @@ +{ + "comment": "How text is cut to 2000 characters, counted in Unicode code points (never UTF-16 units, never through a surrogate pair). input = pad_char repeated pad times + tail; the recorded value = the same pad + expected_tail. Every implementation (CLI, daemon, both SDKs) tests its plain code-point cut against `cases`.", + "max": 2000, + "cases": [ + {"pad_char": "a", "pad": 1999, "tail": "😀 and more text", "expected_tail": "😀"}, + {"pad_char": "a", "pad": 1998, "tail": "😀😀😀", "expected_tail": "😀😀"}, + {"pad_char": "a", "pad": 2000, "tail": "😀", "expected_tail": ""}, + {"pad_char": "a", "pad": 1999, "tail": "éè", "expected_tail": "é"}, + {"pad_char": "😀", "pad": 2000, "tail": "x", "expected_tail": ""}, + {"pad_char": "😀", "pad": 1999, "tail": "中文", "expected_tail": "中"}, + {"pad_char": "a", "pad": 0, "tail": "short 😀", "expected_tail": "short 😀"} + ], + "detail_cut": { + "comment": "A report's DETAIL is cut to `max` code points without leaving part of a token at the end: a credential running past the cut would be kept as a fragment no secret scrubber recognises. If the code point right after the cut is not whitespace, the trailing run of non-whitespace is dropped; then trailing whitespace is dropped; an empty result is `marker`. Whitespace is exactly the characters in `whitespace`. Text that fits is kept whole. input and expected are lists of [text, repeat] joined in order. Every implementation's detail path (CLI hook and stdio, daemon HTTP, both SDKs) is tested against these.", + "marker": "[detail cut]", + "whitespace": " \t\n\r\f\u000b", + "cases": [ + {"name": "fits", "input": [["short 😀", 1]], "expected": [["short 😀", 1]]}, + {"name": "exactly max, one run", "input": [["a", 2000]], "expected": [["a", 2000]]}, + {"name": "cut lands before a space", "input": [["a", 2000], [" more", 1]], "expected": [["a", 2000]]}, + {"name": "a JWT straddling the cut", "input": [["token ", 1], ["eyJhbGciOiJIUzI1NiJ9.eyJ", 1], ["a", 2500], [".sig rejected", 1]], "expected": [["token", 1]]}, + {"name": "one token longer than max", "input": [["eyJhbGciOiJIUzI1NiJ9.eyJ", 1], ["a", 3000], [".sig", 1]], "expected": [["[detail cut]", 1]]}, + {"name": "cut lands just after a space", "input": [["a", 1999], [" ", 1], ["b", 10]], "expected": [["a", 1999]]}, + {"name": "an emoji run past the cut", "input": [["x ", 1], ["😀", 2100]], "expected": [["x", 1]]}, + {"name": "a newline before the token", "input": [["line one\n", 1], ["k", 2500]], "expected": [["line one", 1]]}, + {"name": "trailing whitespace before the cut", "input": [["a b", 1], [" ", 1997], ["c", 5]], "expected": [["a b", 1]]} + ] + } +}