interplane.Get Omega
Read in your language

aien-sovereign-core-mv

AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.

Brought by drakestapleton

GitHub aien-dev/aien-sovereign-core-mv#900 (code only)

closed derived 1e10c4cb6702595e #900

Imported from GitHub aien-dev/aien-sovereign-core-mv#900 (code only)

GitHub's metadata for this pull request is unavailable: its state is DERIVED from the commits (merged: the head is reachable from this project's main; open: GitHub kept a merge ref; else closed).

Base 2ef3e06c2a7b6c7498d7550cb0de6133129ed49a · Head afb79e890ba931eff27f487b55610db0b3875862

cursor[bot] commented on crates/aien-drive/src/command.rs line 405 on 2026-11-02 01:08 UTC

Eval-flag detector misses clustered options

High Severity

is_eval_flag only matches tokens that equal or start with a few prefixes, so clustered short options and PHP's run-code flag never trip the new interpreter gate. An operator-allowlisted perl, ruby, node, or php can still evaluate model text.

<details> <summary>Additional Locations (1)</summary>

</details>

<div><a href="https://cursor.com/open?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9DVVJTT1IiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OjlkYjhlNDc1LWE2MmYtNGQ3YS1iNTVlLTk5N2QyNzE3MTZiYSIsImVuY3J5cHRpb25LZXkiOiJ5bHE1MXdzM21GZVdnVEdXUFhVWXd4dEVaLVhJc2tmTHVjZERDYktxZE84IiwiYnJhbmNoIjoiY3Vyc29yL2NvbmZpbmUtZHJpdmUtcnVuLWNvbW1hbmQtZjE4YiIsInJlcG9Pd25lciI6ImFpZW4tZGV2IiwicmVwb05hbWUiOiJhaWVuLXNvdmVyZWlnbi1jb3JlLW12IiwicHJvdmlkZXIiOiJnaXRodWIifX0" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-cursor-light.png"><img alt="Fix in Cursor" width="115" height="28" src="https://cursor.com/assets/images/fix-in-cursor-dark.png"></picture></a> <a href="https://cursor.com/agents?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9XRUIiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OjlkYjhlNDc1LWE2MmYtNGQ3YS1iNTVlLTk5N2QyNzE3MTZiYSIsImVuY3J5cHRpb25LZXkiOiJ5bHE1MXdzM21GZVdnVEdXUFhVWXd4dEVaLVhJc2tmTHVjZERDYktxZE84IiwiYnJhbmNoIjoiY3Vyc29yL2NvbmZpbmUtZHJpdmUtcnVuLWNvbW1hbmQtZjE4YiIsInJlcG9Pd25lciI6ImFpZW4tZGV2IiwicmVwb05hbWUiOiJhaWVuLXNvdmVyZWlnbi1jb3JlLW12IiwicHJOdW1iZXIiOjkwMCwiY29tbWl0U2hhIjoiNjBkZjk3MjYxZjQzMjBmZDk5MzdiZmQ1ZjYzZWJlNTgxYzdlZmQyZiIsInByb3ZpZGVyIjoiZ2l0aHViIn19" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-web-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-web-light.png"><img alt="Fix in Web" width="99" height="28" src="https://cursor.com/assets/images/fix-in-web-dark.png"></picture></a></div>

<sup>Reviewed by Cursor Bugbot for commit 60df97261f4320fd9937bfd5f63ebe581c7efd2f. Configure here.</sup>

cursor[bot] commented on crates/aien-drive/src/command.rs line 513 on 2026-11-02 01:08 UTC

Git filter rejects ordinary core paths

Medium Severity

git_override treats any argument containing the substring core. as a config override. Ordinary paths and refs such as core.c, core.rs, and score.txt are rejected even when they are not git config keys.

<details> <summary>Additional Locations (1)</summary>

</details>

<div><a href="https://cursor.com/open?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9DVVJTT1IiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OmZiNjFhZDRiLWQ5ZjMtNDhhMi05M2M3LWFlOGRlZTI2NjQxOCIsImVuY3J5cHRpb25LZXkiOiJ4NVJDV3lVWDdVUnZqczRtWmVzOWY3dGg5c0luTDkzZUZKc2ZDNm90dExVIiwiYnJhbmNoIjoiY3Vyc29yL2NvbmZpbmUtZHJpdmUtcnVuLWNvbW1hbmQtZjE4YiIsInJlcG9Pd25lciI6ImFpZW4tZGV2IiwicmVwb05hbWUiOiJhaWVuLXNvdmVyZWlnbi1jb3JlLW12IiwicHJvdmlkZXIiOiJnaXRodWIifX0" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-cursor-light.png"><img alt="Fix in Cursor" width="115" height="28" src="https://cursor.com/assets/images/fix-in-cursor-dark.png"></picture></a> <a href="https://cursor.com/agents?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9XRUIiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OmZiNjFhZDRiLWQ5ZjMtNDhhMi05M2M3LWFlOGRlZTI2NjQxOCIsImVuY3J5cHRpb25LZXkiOiJ4NVJDV3lVWDdVUnZqczRtWmVzOWY3dGg5c0luTDkzZUZKc2ZDNm90dExVIiwiYnJhbmNoIjoiY3Vyc29yL2NvbmZpbmUtZHJpdmUtcnVuLWNvbW1hbmQtZjE4YiIsInJlcG9Pd25lciI6ImFpZW4tZGV2IiwicmVwb05hbWUiOiJhaWVuLXNvdmVyZWlnbi1jb3JlLW12IiwicHJOdW1iZXIiOjkwMCwiY29tbWl0U2hhIjoiNjBkZjk3MjYxZjQzMjBmZDk5MzdiZmQ1ZjYzZWJlNTgxYzdlZmQyZiIsInByb3ZpZGVyIjoiZ2l0aHViIn19" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-web-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-web-light.png"><img alt="Fix in Web" width="99" height="28" src="https://cursor.com/assets/images/fix-in-web-dark.png"></picture></a></div>

<sup>Reviewed by Cursor Bugbot for commit 60df97261f4320fd9937bfd5f63ebe581c7efd2f. Configure here.</sup>

cursor[bot] commented on crates/aien-cli/src/approval.rs line 246 on 2026-11-02 01:21 UTC

Person check skips hardline floors

High Severity

decide returns AskPerson from requires_person before check_floors. A run_command line that mentions approval-policy.json plus a redirect or sed/tee/cp/mv/install never hits hardline or runtime floors, so a person approve runs the rest of that line.

<details> <summary>Additional Locations (1)</summary>

</details>

<div><a href="https://cursor.com/open?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9DVVJTT1IiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OmNhMGMyMTI3LWI2MzYtNDBmOS1hNTRmLTVkZDA5NmJjMGE5NCIsImVuY3J5cHRpb25LZXkiOiJRdzlkUTdZY2lCY1dzeHg4dkJoNGsySURvRXZCVGotTjJlbEt1eGswZkhrIiwiYnJhbmNoIjoiY3Vyc29yL2NvbmZpbmUtZHJpdmUtcnVuLWNvbW1hbmQtZjE4YiIsInJlcG9Pd25lciI6ImFpZW4tZGV2IiwicmVwb05hbWUiOiJhaWVuLXNvdmVyZWlnbi1jb3JlLW12IiwicHJvdmlkZXIiOiJnaXRodWIifX0" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-cursor-light.png"><img alt="Fix in Cursor" width="115" height="28" src="https://cursor.com/assets/images/fix-in-cursor-dark.png"></picture></a> <a href="https://cursor.com/agents?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9XRUIiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OmNhMGMyMTI3LWI2MzYtNDBmOS1hNTRmLTVkZDA5NmJjMGE5NCIsImVuY3J5cHRpb25LZXkiOiJRdzlkUTdZY2lCY1dzeHg4dkJoNGsySURvRXZCVGotTjJlbEt1eGswZkhrIiwiYnJhbmNoIjoiY3Vyc29yL2NvbmZpbmUtZHJpdmUtcnVuLWNvbW1hbmQtZjE4YiIsInJlcG9Pd25lciI6ImFpZW4tZGV2IiwicmVwb05hbWUiOiJhaWVuLXNvdmVyZWlnbi1jb3JlLW12IiwicHJOdW1iZXIiOjkwMCwiY29tbWl0U2hhIjoiNDFmNGQxOGJhMjY1ZThlYjQwNDljZDc5OGY3Y2U0YjBhMDAzNDRiYSIsInByb3ZpZGVyIjoiZ2l0aHViIn19" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-web-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-web-light.png"><img alt="Fix in Web" width="99" height="28" src="https://cursor.com/assets/images/fix-in-web-dark.png"></picture></a></div>

<sup>Reviewed by Cursor Bugbot for commit 41f4d18ba265e8eb4049cd798f7ce4b0a00344ba. Configure here.</sup>

cursor[bot] commented on crates/aien-cli/src/approval.rs line 344 on 2026-11-02 01:21 UTC

Policy write detector is bypassable

High Severity

approval_policy_write only treats a path substring of approval-policy.json, or a command that also contains >, sed, tee, cp , mv , or install, as person-only. Other writers still run in yolo and off. GateContext then loads that file at the next process start for allow and deny patterns.

<details> <summary>Additional Locations (1)</summary>

</details>

<div><a href="https://cursor.com/open?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9DVVJTT1IiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OmUzZDBlNjYzLWY5YzYtNDI1Yi05MjQzLWIzZmViZWY2MTNkMCIsImVuY3J5cHRpb25LZXkiOiJ2WXVUYkN6Vk5lMkIzeWYzaUdyWVJrbEpJcFdHdXgyMHBHWWhubnl6Y1VVIiwiYnJhbmNoIjoiY3Vyc29yL2NvbmZpbmUtZHJpdmUtcnVuLWNvbW1hbmQtZjE4YiIsInJlcG9Pd25lciI6ImFpZW4tZGV2IiwicmVwb05hbWUiOiJhaWVuLXNvdmVyZWlnbi1jb3JlLW12IiwicHJvdmlkZXIiOiJnaXRodWIifX0" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-cursor-light.png"><img alt="Fix in Cursor" width="115" height="28" src="https://cursor.com/assets/images/fix-in-cursor-dark.png"></picture></a> <a href="https://cursor.com/agents?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9XRUIiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OmUzZDBlNjYzLWY5YzYtNDI1Yi05MjQzLWIzZmViZWY2MTNkMCIsImVuY3J5cHRpb25LZXkiOiJ2WXVUYkN6Vk5lMkIzeWYzaUdyWVJrbEpJcFdHdXgyMHBHWWhubnl6Y1VVIiwiYnJhbmNoIjoiY3Vyc29yL2NvbmZpbmUtZHJpdmUtcnVuLWNvbW1hbmQtZjE4YiIsInJlcG9Pd25lciI6ImFpZW4tZGV2IiwicmVwb05hbWUiOiJhaWVuLXNvdmVyZWlnbi1jb3JlLW12IiwicHJOdW1iZXIiOjkwMCwiY29tbWl0U2hhIjoiNDFmNGQxOGJhMjY1ZThlYjQwNDljZDc5OGY3Y2U0YjBhMDAzNDRiYSIsInByb3ZpZGVyIjoiZ2l0aHViIn19" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-web-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-web-light.png"><img alt="Fix in Web" width="99" height="28" src="https://cursor.com/assets/images/fix-in-web-dark.png"></picture></a></div>

<sup>Reviewed by Cursor Bugbot for commit 41f4d18ba265e8eb4049cd798f7ce4b0a00344ba. Configure here.</sup>

cursor[bot] commented on crates/aien-drive/src/paths.rs line 29 on 2026-11-02 01:21 UTC

Wrong openat2 resolve flag value

Medium Severity

RESOLVE_NO_MAGICLINKS is hardcoded as 0x04, which is RESOLVE_NO_SYMLINKS. Combined with RESOLVE_BENEATH, openat2 refuses every symlink component, including ones that stay under the command root. The module text and the ENOSYS fallback still describe following in-root links.

<details> <summary>Additional Locations (1)</summary>

</details>

<div><a href="https://cursor.com/open?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9DVVJTT1IiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OjIwZjMxYTExLWUyNWItNDM5Ni1hMWEyLWRhODE2MWI5YTg1NiIsImVuY3J5cHRpb25LZXkiOiI0NldYemNhdzdKeTdMeTdYQ01fU2pPbXQ4a0l3VzdVenN3ZEFyNTh1RzkwIiwiYnJhbmNoIjoiY3Vyc29yL2NvbmZpbmUtZHJpdmUtcnVuLWNvbW1hbmQtZjE4YiIsInJlcG9Pd25lciI6ImFpZW4tZGV2IiwicmVwb05hbWUiOiJhaWVuLXNvdmVyZWlnbi1jb3JlLW12IiwicHJvdmlkZXIiOiJnaXRodWIifX0" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-cursor-light.png"><img alt="Fix in Cursor" width="115" height="28" src="https://cursor.com/assets/images/fix-in-cursor-dark.png"></picture></a> <a href="https://cursor.com/agents?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9XRUIiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OjIwZjMxYTExLWUyNWItNDM5Ni1hMWEyLWRhODE2MWI5YTg1NiIsImVuY3J5cHRpb25LZXkiOiI0NldYemNhdzdKeTdMeTdYQ01fU2pPbXQ4a0l3VzdVenN3ZEFyNTh1RzkwIiwiYnJhbmNoIjoiY3Vyc29yL2NvbmZpbmUtZHJpdmUtcnVuLWNvbW1hbmQtZjE4YiIsInJlcG9Pd25lciI6ImFpZW4tZGV2IiwicmVwb05hbWUiOiJhaWVuLXNvdmVyZWlnbi1jb3JlLW12IiwicHJOdW1iZXIiOjkwMCwiY29tbWl0U2hhIjoiNDFmNGQxOGJhMjY1ZThlYjQwNDljZDc5OGY3Y2U0YjBhMDAzNDRiYSIsInByb3ZpZGVyIjoiZ2l0aHViIn19" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-web-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-web-light.png"><img alt="Fix in Web" width="99" height="28" src="https://cursor.com/assets/images/fix-in-web-dark.png"></picture></a></div>

<sup>Reviewed by Cursor Bugbot for commit 41f4d18ba265e8eb4049cd798f7ce4b0a00344ba. Configure here.</sup>

cursor[bot] commented on crates/aien-drive/src/paths.rs line 277 on 2026-11-02 01:21 UTC

Medium Severity

open_rel_fallback skips the outside-root check when canonicalize fails, then calls open with O_CREAT and no O_NOFOLLOW. A dangling symlink under the root can create or truncate a target outside it on the ENOSYS path.

<details> <summary>Additional Locations (1)</summary>

</details>

<div><a href="https://cursor.com/open?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9DVVJTT1IiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OjIwNmJmNDI0LWVmNDItNDllYi05OGM2LTBlM2MzY2JiNTYwYyIsImVuY3J5cHRpb25LZXkiOiJVSjF6RHhiNTJOZ2NOcTM1VVlXWFlYQ09YTktTRTBQS0lCNFdYMmZFN1l3IiwiYnJhbmNoIjoiY3Vyc29yL2NvbmZpbmUtZHJpdmUtcnVuLWNvbW1hbmQtZjE4YiIsInJlcG9Pd25lciI6ImFpZW4tZGV2IiwicmVwb05hbWUiOiJhaWVuLXNvdmVyZWlnbi1jb3JlLW12IiwicHJvdmlkZXIiOiJnaXRodWIifX0" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-cursor-light.png"><img alt="Fix in Cursor" width="115" height="28" src="https://cursor.com/assets/images/fix-in-cursor-dark.png"></picture></a> <a href="https://cursor.com/agents?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9XRUIiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OjIwNmJmNDI0LWVmNDItNDllYi05OGM2LTBlM2MzY2JiNTYwYyIsImVuY3J5cHRpb25LZXkiOiJVSjF6RHhiNTJOZ2NOcTM1VVlXWFlYQ09YTktTRTBQS0lCNFdYMmZFN1l3IiwiYnJhbmNoIjoiY3Vyc29yL2NvbmZpbmUtZHJpdmUtcnVuLWNvbW1hbmQtZjE4YiIsInJlcG9Pd25lciI6ImFpZW4tZGV2IiwicmVwb05hbWUiOiJhaWVuLXNvdmVyZWlnbi1jb3JlLW12IiwicHJOdW1iZXIiOjkwMCwiY29tbWl0U2hhIjoiNDFmNGQxOGJhMjY1ZThlYjQwNDljZDc5OGY3Y2U0YjBhMDAzNDRiYSIsInByb3ZpZGVyIjoiZ2l0aHViIn19" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-web-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-web-light.png"><img alt="Fix in Web" width="99" height="28" src="https://cursor.com/assets/images/fix-in-web-dark.png"></picture></a></div>

<sup>Reviewed by Cursor Bugbot for commit 41f4d18ba265e8eb4049cd798f7ce4b0a00344ba. Configure here.</sup>

cursor[bot] commented on crates/aien-drive/src/paths.rs line 344 on 2026-11-02 02:51 UTC

Medium Severity

The new hardlink guard only fingerprints a short inode list, so a hardlink whose path looks harmless still rewrites files that refuse_sensitive_write already treats as protected, including git hooks, shell rc files, and workflow files. A worktree .git file also keeps the real config inode out of that set.

<details> <summary>Additional Locations (1)</summary>

</details>

<div><a href="https://cursor.com/open?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9DVVJTT1IiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OjI3ZGNkMjM4LWRkNDEtNGExNi05MDhmLTc4NjUzNjY2ZDg4NiIsImVuY3J5cHRpb25LZXkiOiJZQ3lOQThFTHhPVE1VT0YzRzdTUFV1c09ZNHRTZi0tMkg1TDBtamRQMl9FIiwiYnJhbmNoIjoiY3Vyc29yL2NvbmZpbmUtZHJpdmUtcnVuLWNvbW1hbmQtZjE4YiIsInJlcG9Pd25lciI6ImFpZW4tZGV2IiwicmVwb05hbWUiOiJhaWVuLXNvdmVyZWlnbi1jb3JlLW12IiwicHJvdmlkZXIiOiJnaXRodWIifX0" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-cursor-light.png"><img alt="Fix in Cursor" width="115" height="28" src="https://cursor.com/assets/images/fix-in-cursor-dark.png"></picture></a> <a href="https://cursor.com/agents?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9XRUIiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OjI3ZGNkMjM4LWRkNDEtNGExNi05MDhmLTc4NjUzNjY2ZDg4NiIsImVuY3J5cHRpb25LZXkiOiJZQ3lOQThFTHhPVE1VT0YzRzdTUFV1c09ZNHRTZi0tMkg1TDBtamRQMl9FIiwiYnJhbmNoIjoiY3Vyc29yL2NvbmZpbmUtZHJpdmUtcnVuLWNvbW1hbmQtZjE4YiIsInJlcG9Pd25lciI6ImFpZW4tZGV2IiwicmVwb05hbWUiOiJhaWVuLXNvdmVyZWlnbi1jb3JlLW12IiwicHJOdW1iZXIiOjkwMCwiY29tbWl0U2hhIjoiZTA1YTQ4YWRkNDU5OGM1MmRmMDgzZWU3NTVkMWQyM2YwNjg5OTE3MCIsInByb3ZpZGVyIjoiZ2l0aHViIn19" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-web-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-web-light.png"><img alt="Fix in Web" width="99" height="28" src="https://cursor.com/assets/images/fix-in-web-dark.png"></picture></a></div>

<sup>Reviewed by Cursor Bugbot for commit e05a48add4598c52df083ee755d1d23f06899170. Configure here.</sup>

cursor[bot] commented on crates/aien-drive/src/lib.rs line 119 on 2026-11-02 02:51 UTC

Unclosed think blocks still execute

Medium Severity

strip_think_blocks only drops paired <think> or <thinking> spans. An unclosed block, which is common when the stream hits max_tokens, leaves any <tool_call> inside it eligible for extract_tool_calls, so draft calls in the content channel still run.

<details> <summary>Additional Locations (1)</summary>

</details>

<div><a href="https://cursor.com/open?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9DVVJTT1IiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OjRhY2YzYjE5LTRlMDMtNDI1YS1hY2RjLTllMmVlYmNmNTE5YSIsImVuY3J5cHRpb25LZXkiOiJPSFR3ZUVvSndEckxXb25aYlVmZXcwU01yQ0VQY0R6STBfUUdoZWQzaEcwIiwiYnJhbmNoIjoiY3Vyc29yL2NvbmZpbmUtZHJpdmUtcnVuLWNvbW1hbmQtZjE4YiIsInJlcG9Pd25lciI6ImFpZW4tZGV2IiwicmVwb05hbWUiOiJhaWVuLXNvdmVyZWlnbi1jb3JlLW12IiwicHJvdmlkZXIiOiJnaXRodWIifX0" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-cursor-light.png"><img alt="Fix in Cursor" width="115" height="28" src="https://cursor.com/assets/images/fix-in-cursor-dark.png"></picture></a> <a href="https://cursor.com/agents?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9XRUIiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OjRhY2YzYjE5LTRlMDMtNDI1YS1hY2RjLTllMmVlYmNmNTE5YSIsImVuY3J5cHRpb25LZXkiOiJPSFR3ZUVvSndEckxXb25aYlVmZXcwU01yQ0VQY0R6STBfUUdoZWQzaEcwIiwiYnJhbmNoIjoiY3Vyc29yL2NvbmZpbmUtZHJpdmUtcnVuLWNvbW1hbmQtZjE4YiIsInJlcG9Pd25lciI6ImFpZW4tZGV2IiwicmVwb05hbWUiOiJhaWVuLXNvdmVyZWlnbi1jb3JlLW12IiwicHJOdW1iZXIiOjkwMCwiY29tbWl0U2hhIjoiZTA1YTQ4YWRkNDU5OGM1MmRmMDgzZWU3NTVkMWQyM2YwNjg5OTE3MCIsInByb3ZpZGVyIjoiZ2l0aHViIn19" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-web-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-web-light.png"><img alt="Fix in Web" width="99" height="28" src="https://cursor.com/assets/images/fix-in-web-dark.png"></picture></a></div>

<sup>Reviewed by Cursor Bugbot for commit e05a48add4598c52df083ee755d1d23f06899170. Configure here.</sup>

cursor[bot] commented on crates/aien-cli/src/approval.rs line 427 on 2026-11-02 02:51 UTC

Glob floor ignores command cwd

Medium Severity

glob_token_covers resolves glob tokens against facts.cwd, not the command cwd, so a relative glob that expands onto a protected file from the tool working directory misses command_names_protected_write. The later redirect scanner also does not treat *.json as the policy path, so that write is no longer a hard floor.

<details> <summary>Additional Locations (2)</summary>

</details>

<div><a href="https://cursor.com/open?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9DVVJTT1IiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OmQ2OTI2MjNmLTg0NzYtNDBmMy1hNTcwLTQ0Zjc5MjgyNDFlMyIsImVuY3J5cHRpb25LZXkiOiJoVVg2ekFRbzMzQlhUWmNWcGxTVlhDRnVJN3E1UVBKaDRkMkNUOG5MT0NVIiwiYnJhbmNoIjoiY3Vyc29yL2NvbmZpbmUtZHJpdmUtcnVuLWNvbW1hbmQtZjE4YiIsInJlcG9Pd25lciI6ImFpZW4tZGV2IiwicmVwb05hbWUiOiJhaWVuLXNvdmVyZWlnbi1jb3JlLW12IiwicHJvdmlkZXIiOiJnaXRodWIifX0" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-cursor-light.png"><img alt="Fix in Cursor" width="115" height="28" src="https://cursor.com/assets/images/fix-in-cursor-dark.png"></picture></a> <a href="https://cursor.com/agents?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9XRUIiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OmQ2OTI2MjNmLTg0NzYtNDBmMy1hNTcwLTQ0Zjc5MjgyNDFlMyIsImVuY3J5cHRpb25LZXkiOiJoVVg2ekFRbzMzQlhUWmNWcGxTVlhDRnVJN3E1UVBKaDRkMkNUOG5MT0NVIiwiYnJhbmNoIjoiY3Vyc29yL2NvbmZpbmUtZHJpdmUtcnVuLWNvbW1hbmQtZjE4YiIsInJlcG9Pd25lciI6ImFpZW4tZGV2IiwicmVwb05hbWUiOiJhaWVuLXNvdmVyZWlnbi1jb3JlLW12IiwicHJOdW1iZXIiOjkwMCwiY29tbWl0U2hhIjoiZTA1YTQ4YWRkNDU5OGM1MmRmMDgzZWU3NTVkMWQyM2YwNjg5OTE3MCIsInByb3ZpZGVyIjoiZ2l0aHViIn19" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-web-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-web-light.png"><img alt="Fix in Web" width="99" height="28" src="https://cursor.com/assets/images/fix-in-web-dark.png"></picture></a></div>

<sup>Reviewed by Cursor Bugbot for commit e05a48add4598c52df083ee755d1d23f06899170. Configure here.</sup>

cursor[bot] reviewed (COMMENTED) on 2026-11-02 00:39 UTC

<details> <summary>Stale comment</summary>

<blockquote>

Risk: high. Left a non-blocking comment. This PR changes the model-triggered process-execution boundary in aien-drive, which is above the medium approval threshold, so it is not approved. Cursor Bugbot and Cursor Security Agent both completed successfully with no findings; assigned drakestapleton for human review.

<div><a href="https://cursor.com/agents/bc-7224e9df-163b-478b-8e6a-4956c64999b2?cursor_ref=pr_footer&cursor_cta=open_in_web"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/open-in-web-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/open-in-web-light.png"><img alt="Open in Web" width="114" height="28" src="https://cursor.com/assets/images/open-in-web-dark.png"></picture></a> <a href="https://cursor.com/automations/ca4a13aa-d616-11f1-a7e4-4605a90eab71"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/view-automation-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/view-automation-light.png"><img alt="View Automation" width="141" height="28" src="https://cursor.com/assets/images/view-automation-dark.png"></picture></a> </div>

<sub>Sent by Cursor Approval Agent: Pull Request Router and Approver</sub>

</blockquote>

</details>

cursor[bot] reviewed (COMMENTED) on 2026-11-02 01:08 UTC

Stale Bugbot comment from a previous run.

cursor[bot] reviewed (COMMENTED) on 2026-11-02 01:11 UTC

Risk: high. Left a non-blocking comment. This update changes the model-triggered process-execution boundary and Bugbot left unresolved findings, including a high-severity eval-flag gap, so it is not approved. Human review is needed and no reviewers were assigned.

<div><a href="https://cursor.com/agents/bc-1b856f6c-d8d0-4c14-8351-87b5e7b28d5f?cursor_ref=pr_footer&cursor_cta=open_in_web"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/open-in-web-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/open-in-web-light.png"><img alt="Open in Web" width="114" height="28" src="https://cursor.com/assets/images/open-in-web-dark.png"></picture></a> <a href="https://cursor.com/automations/ca4a13aa-d616-11f1-a7e4-4605a90eab71"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/view-automation-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/view-automation-light.png"><img alt="View Automation" width="141" height="28" src="https://cursor.com/assets/images/view-automation-dark.png"></picture></a> </div>

<sub>Sent by Cursor Approval Agent: Pull Request Router and Approver</sub>

cursor[bot] reviewed (COMMENTED) on 2026-11-02 01:21 UTC

Stale Bugbot comment from a previous run.

cursor[bot] reviewed (COMMENTED) on 2026-11-02 01:25 UTC

Risk: high. Left a non-blocking comment. This update changes model-triggered command execution, filesystem confinement, and CLI approval-gate semantics, which is above the medium approval threshold, so it is not approved. Cursor Security Agent passed with no findings; Cursor Bugbot was skipped as a check, and reviewers assigned were drakestapleton.

<div><a href="https://cursor.com/agents/bc-8bafa8bc-155a-4dd1-b22d-37fdd7962ae5?cursor_ref=pr_footer&cursor_cta=open_in_web"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/open-in-web-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/open-in-web-light.png"><img alt="Open in Web" width="114" height="28" src="https://cursor.com/assets/images/open-in-web-dark.png"></picture></a> <a href="https://cursor.com/automations/ca4a13aa-d616-11f1-a7e4-4605a90eab71"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/view-automation-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/view-automation-light.png"><img alt="View Automation" width="141" height="28" src="https://cursor.com/assets/images/view-automation-dark.png"></picture></a> </div>

<sub>Sent by Cursor Approval Agent: Pull Request Router and Approver</sub>

cursor[bot] reviewed (COMMENTED) on 2026-11-02 02:51 UTC

Cursor Bugbot has reviewed your changes using high effort and found 3 potential issues.

There are 5 total unresolved issues (including 2 from previous reviews).

<a href="https://cursor.com/open?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9BTExfSU5fQ1VSU09SIiwiZGF0YSI6eyJyZWRpc0tleSI6ImJ1Z2JvdC1tdWx0aToyNmFiNzY5Yi1lOGE0LTRmNGItYjVlNi1jNjk0M2QzNDk4ZDAiLCJlbmNyeXB0aW9uS2V5IjoiUGtIZ2FLNVZhYTRGd0x3QTk5ckZzSUFSWllrNnViQnlCNjZQZkppSTNOVSIsImJyYW5jaCI6ImN1cnNvci9jb25maW5lLWRyaXZlLXJ1bi1jb21tYW5kLWYxOGIiLCJyZXBvT3duZXIiOiJhaWVuLWRldiIsInJlcG9OYW1lIjoiYWllbi1zb3ZlcmVpZ24tY29yZS1tdiIsInByb3ZpZGVyIjoiZ2l0aHViIn19" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-cursor-light.png"><img alt="Fix All in Cursor" width="115" height="28" src="https://cursor.com/assets/images/fix-in-cursor-dark.png"></picture></a>

<sup>❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.</sup>

<sup>Reviewed by Cursor Bugbot for commit e05a48add4598c52df083ee755d1d23f06899170. Configure here.</sup>

cursor[bot] reviewed (COMMENTED) on 2026-11-02 02:54 UTC

Risk: high. Left a non-blocking comment. This update changes model-triggered command execution, filesystem confinement, and CLI approval-gate semantics, which is above the medium approval threshold, so it is not approved. Cursor Security Agent passed with no findings; Cursor Bugbot was skipped as a check, and reviewers assigned were drakestapleton.

<div><a href="https://cursor.com/agents/bc-a2df5864-4467-4fac-8eed-ef34cd4433f5?cursor_ref=pr_footer&cursor_cta=open_in_web"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/open-in-web-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/open-in-web-light.png"><img alt="Open in Web" width="114" height="28" src="https://cursor.com/assets/images/open-in-web-dark.png"></picture></a> <a href="https://cursor.com/automations/ca4a13aa-d616-11f1-a7e4-4605a90eab71"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/view-automation-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/view-automation-light.png"><img alt="View Automation" width="141" height="28" src="https://cursor.com/assets/images/view-automation-dark.png"></picture></a> </div>

<sub>Sent by Cursor Approval Agent: Pull Request Router and Approver</sub>

Fetch it

A git bundle of the pull request's head, 55120 bytes.

curl -fsSL https://interplane.io/drakestapleton/aien-sovereign-core-mv/patches/1e10c4cb6702595e.bundle -o 1e10c4cb6702595e.bundle
git fetch 1e10c4cb6702595e.bundle refs/pull/900/head

Raw bundle · Diff

Provenance

This proposal is imported from GitHub; it is not signed by its author. Its import statement and source record:

github-import 1
aien-dev/aien-sovereign-core-mv
900
afb79e890ba931eff27f487b55610db0b3875862
{"kind":"github-import","owner":"aien-dev","repo":"aien-sovereign-core-mv","number":900,"url":"https://github.com/aien-dev/aien-sovereign-core-mv/pull/900","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:38:14Z","metadata":"unavailable","state_derived":true}

Changes

diff --git a/Cargo.lock b/Cargo.lock
index bd4280f7..500453ac 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -134,6 +134,7 @@ name = "aien-drive"
 version = "0.1.0"
 dependencies = [
  "clap",
+ "libc",
  "regex",
  "serde_json",
 ]
diff --git a/crates/aien-cli/src/approval.rs b/crates/aien-cli/src/approval.rs
index c140cd84..ca2494dd 100644
--- a/crates/aien-cli/src/approval.rs
+++ b/crates/aien-cli/src/approval.rs
@@ -29,8 +29,9 @@
 //!    decision is denied (unattended defaults to deny).
 //! 6. **Dangerous patterns** and the engine's own questions decide whether a
 //!    decision is needed at all.
-//! 7. **Decision**: in `smart` mode a guardian model answers approve, deny or
-//!    escalate behind a circuit breaker; otherwise, or on escalate, the person.
+//! 7. **Decision**: in `smart` mode a guardian model may deny or escalate.
+//!    It is never the final allow. Escalate, approve, and failure all go to
+//!    the person. Otherwise the person is asked directly.
 //!
 //! The functions in the pure section take values and return values: no
 //! clock, disk, environment or terminal. The edges (policy file, presence,
@@ -149,6 +150,9 @@ pub struct OperatorPolicy {
 /// policy file that does not parse, denies every request with the reason.
 #[derive(Debug, Clone, Default)]
 pub struct CompiledPolicy {
+    /// Parsed from the policy file and not consulted. The process mode is the
+    /// CLI flag or `AIEN_APPROVAL_MODE`, fixed at startup.
+    #[allow(dead_code)]
     pub mode: Option<ApprovalMode>,
     deny: Vec<Regex>,
     allow: Vec<Regex>,
@@ -229,7 +233,8 @@ pub struct Gate<'a> {
     pub guardian_ready: bool,
 }
 
-/// The ordering rule. Floors first, every mode.
+/// The ordering rule. Floors first, every mode. A person-required action
+/// never skips a floor.
 pub fn decide(gate: &Gate) -> Verdict {
     if let Some((floor, reason)) = check_floors(gate.tool, gate.args, gate.policy, gate.facts) {
         return Verdict::Deny {
@@ -243,7 +248,28 @@ pub fn decide(gate: &Gate) -> Verdict {
             reason: reason.clone(),
         };
     }
+    if let Some(reason) = requires_person(gate.tool, gate.args) {
+        if gate.presence == Presence::Unattended {
+            return Verdict::Deny {
+                by: Stage::Presence,
+                reason: format!("person required, unattended default is deny: {reason}"),
+            };
+        }
+        return Verdict::AskPerson { reason };
+    }
     if matches!(gate.mode, ApprovalMode::Yolo | ApprovalMode::Off) {
+        // `run_command` is executed by `bash -c`. Yolo and off do not waive that.
+        if gate.tool == "run_command" {
+            if gate.presence == Presence::Unattended {
+                return Verdict::Deny {
+                    by: Stage::Presence,
+                    reason: "run_command requires the person, unattended default is deny".into(),
+                };
+            }
+            return Verdict::AskPerson {
+                reason: "run_command requires the person".into(),
+            };
+        }
         return Verdict::Allow { by: Stage::Mode };
     }
     let subject = subject(gate.tool, gate.args);
@@ -286,14 +312,203 @@ pub enum GuardianAnswer {
 /// Second half of [`decide`] after an `AskGuardian` verdict.
 pub fn after_guardian(answer: &GuardianAnswer, reason: String) -> Verdict {
     match answer {
-        GuardianAnswer::Approve => Verdict::Allow {
-            by: Stage::Guardian,
-        },
+        // The guardian may deny or escalate. An approve is an escalation:
+        // the person is the only final allow.
         GuardianAnswer::Deny(why) => Verdict::Deny {
             by: Stage::Guardian,
             reason: format!("guardian denied: {why}"),
         },
-        GuardianAnswer::Escalate | GuardianAnswer::Failed(_) => Verdict::AskPerson { reason },
+        GuardianAnswer::Approve | GuardianAnswer::Escalate | GuardianAnswer::Failed(_) => {
+            Verdict::AskPerson { reason }
+        }
+    }
+}
+
+/// Actions that stay with the person in every mode, including `yolo` and `off`.
+/// Floors are decided first. This does not waive a floor.
+pub fn requires_person(tool: &str, args: &Value) -> Option<String> {
+    let action = args.get("action").and_then(Value::as_str).unwrap_or("");
+    if tool == "sandbox" && action == "promote" {
+        return Some("sandbox promote requires the person".into());
+    }
+    if matches!(tool, "skill" | "skills") && action == "optimize" {
+        return Some("skill optimize requires the person".into());
+    }
+    None
+}
+
+/// Where a shell word lands relative to a protected path. The word is
+/// brace-expanded, resolved against the command's own working directory, and
+/// matched one path component at a time with `*`, `?` and `[...]`.
+#[derive(Clone, Copy, PartialEq, Eq)]
+enum Cover {
+    None,
+    /// The word names the protected path or something inside it.
+    Inside,
+    /// The word names a parent of the protected path.
+    Parent,
+}
+
+fn word_covers(word: &str, protected: &Path, home: &Path, base: &Path) -> Cover {
+    let mut best = Cover::None;
+    for alt in expand_braces(word) {
+        let abs = lexical_abs(&alt, home, base);
+        let want: Vec<_> = protected.components().collect();
+        let got: Vec<_> = abs.components().collect();
+        let matched = want.iter().zip(&got).all(|(w, g)| {
+            match (w.as_os_str().to_str(), g.as_os_str().to_str()) {
+                (Some(w), Some(g)) => glob_match(g, w),
+                _ => w == g,
+            }
+        });
+        if !matched || got.is_empty() {
+            continue;
+        }
+        if got.len() >= want.len() {
+            return Cover::Inside;
+        }
+        best = Cover::Parent;
+    }
+    best
+}
+
+/// Bash brace expansion of `a{b,c}d` forms, nested, capped at 256 words.
+fn expand_braces(word: &str) -> Vec<String> {
+    const CAP: usize = 256;
+    let bytes = word.as_bytes();
+    let Some(open) = bytes.iter().position(|&b| b == b'{') else {
+        return vec![word.to_string()];
+    };
+    let mut depth = 0usize;
+    let mut commas = Vec::new();
+    let mut close = None;
+    for (i, &b) in bytes.iter().enumerate().skip(open) {
+        match b {
+            b'{' => depth += 1,
+            b'}' => {
+                depth -= 1;
+                if depth == 0 {
+                    close = Some(i);
+                    break;
+                }
+            }
+            b',' if depth == 1 => commas.push(i),
+            _ => {}
+        }
+    }
+    let (Some(close), false) = (close, commas.is_empty()) else {
+        // No list inside: the braces are literal; expand what follows.
+        let head = &word[..=open];
+        return expand_braces(&word[open + 1..])
+            .into_iter()
+            .map(|tail| format!("{head}{tail}"))
+            .take(CAP)
+            .collect();
+    };
+    let mut cuts = vec![open];
+    cuts.extend(commas);
+    cuts.push(close);
+    let mut out = Vec::new();
+    for pair in cuts.windows(2) {
+        let joined = format!(
+            "{}{}{}",
+            &word[..open],
+            &word[pair[0] + 1..pair[1]],
+            &word[close + 1..]
+        );
+        for w in expand_braces(&joined) {
+            if out.len() == CAP {
+                return out;
+            }
+            out.push(w);
+        }
+    }
+    out
+}
+
+fn glob_match(pat: &str, name: &str) -> bool {
+    fn class(pat: &[u8], c: u8) -> Option<(bool, usize)> {
+        // `pat` starts after `[`. Returns (matched, bytes consumed incl. `]`).
+        let (negate, start) = match pat.first() {
+            Some(b'!') | Some(b'^') => (true, 1),
+            _ => (false, 0),
+        };
+        let mut i = start;
+        let mut hit = false;
+        while i < pat.len() {
+            if pat[i] == b']' && i > start {
+                return Some((hit != negate, i + 1));
+            }
+            if i + 2 < pat.len() && pat[i + 1] == b'-' && pat[i + 2] != b']' {
+                hit |= pat[i] <= c && c <= pat[i + 2];
+                i += 3;
+            } else {
+                hit |= pat[i] == c;
+                i += 1;
+            }
+        }
+        None
+    }
+    fn rec(pat: &[u8], name: &[u8]) -> bool {
+        match pat.first() {
+            None => name.is_empty(),
+            Some(b'*') => rec(&pat[1..], name) || (!name.is_empty() && rec(pat, &name[1..])),
+            Some(b'?') => !name.is_empty() && rec(&pat[1..], &name[1..]),
+            Some(b'[') if !name.is_empty() => match class(&pat[1..], name[0]) {
+                Some((true, used)) => rec(&pat[1 + used..], &name[1..]),
+                Some((false, _)) => false,
+                None => name[0] == b'[' && rec(&pat[1..], &name[1..]),
+            },
+            Some(&c) => name.first().copied() == Some(c) && rec(&pat[1..], &name[1..]),
+        }
+    }
+    rec(pat.as_bytes(), name.as_bytes())
+}
+
+/// The path part of a shell word: after a redirect operator or `of=`.
+fn path_part(token: &str) -> &str {
+    let t = token.rsplit('>').next().unwrap_or(token);
+    t.strip_prefix("of=").unwrap_or(t)
+}
+
+/// True when a command string writes a protected runtime file, including
+/// forms the redirect scanner does not name on its own.
+fn command_names_protected_write(cmd: &str, cwd: &Path, facts: &RuntimeFacts) -> bool {
+    let expanded = expand_policy_env(cmd);
+    let lower = expanded.to_ascii_lowercase();
+    let mentions = facts.protected.iter().any(|p| {
+        expanded.contains(&p.to_string_lossy().to_string())
+            || p.file_name()
+                .and_then(|n| n.to_str())
+                .is_some_and(|n| lower.contains(&n.to_ascii_lowercase()))
+            || expanded.split_whitespace().any(|tok| {
+                let word = path_part(tok).trim_matches(|c| c == '\'' || c == '"');
+                word_covers(word, p, &facts.home, cwd) == Cover::Inside
+            })
+    }) || lower.contains("$aien_approval_policy")
+        || lower.contains("${aien_approval_policy}");
+    if !mentions {
+        return false;
+    }
+    lower.contains('>')
+        || lower.contains(" of=")
+        || lower.contains("dd ")
+        || lower.contains("python")
+        || lower.contains("perl")
+        || lower.contains("tee")
+        || lower.contains("sed")
+        || lower.contains("cp ")
+        || lower.contains("mv ")
+        || lower.contains("install")
+        || lower.contains("truncate")
+}
+
+fn expand_policy_env(cmd: &str) -> String {
+    match std::env::var("AIEN_APPROVAL_POLICY") {
+        Ok(path) => cmd
+            .replace("${AIEN_APPROVAL_POLICY}", &path)
+            .replace("$AIEN_APPROVAL_POLICY", &path),
+        Err(_) => cmd.to_string(),
     }
 }
 
@@ -677,16 +892,6 @@ pub fn lexical_abs(path: &str, home: &Path, base: &Path) -> PathBuf {
     out
 }
 
-fn is_protected(path: &Path, facts: &RuntimeFacts) -> Option<PathBuf> {
-    facts
-        .protected
-        .iter()
-        // The path is inside a protected entry, or a protected entry is
-        // inside the path (deleting a parent deletes the runtime too).
-        .find(|p| path.starts_with(p) || (p.starts_with(path) && path != Path::new("")))
-        .cloned()
-}
-
 const MUTATING: [&str; 16] = [
     "rm", "rmdir", "mv", "shred", "truncate", "unlink", "cp", "ln", "chmod", "chown", "tee", "dd",
     "install", "rsync", "find", "sed",
@@ -716,6 +921,12 @@ pub fn runtime_self_delete(tool: &str, args: &Value, facts: &RuntimeFacts) -> Op
         "run_command" => {
             let cwd = cwd_of(args, facts);
             let original = command_of(args);
+            if command_names_protected_write(original, &cwd, facts) {
+                return Some(
+                    "command would rewrite the runtime's own approval policy or another protected file"
+                        .into(),
+                );
+            }
             // Paths are case-sensitive: segment the quote-stripped original,
             // compare verbs in lower case.
             let stripped: String = original
@@ -740,8 +951,11 @@ pub fn runtime_self_delete(tool: &str, args: &Value, facts: &RuntimeFacts) -> Op
                     })
                     .collect();
                 for t in &redirect_targets {
-                    let p = lexical_abs(t, &facts.home, &cwd);
-                    if let Some(hit) = facts.protected.iter().find(|r| p.starts_with(r)) {
+                    if let Some(hit) = facts
+                        .protected
+                        .iter()
+                        .find(|r| word_covers(t, r, &facts.home, &cwd) == Cover::Inside)
+                    {
                         return Some(format!(
                             "shell redirect would overwrite the runtime's own file {}",
                             hit.display()
@@ -777,12 +991,15 @@ pub fn runtime_self_delete(tool: &str, args: &Value, facts: &RuntimeFacts) -> Op
                     let deleting =
                         matches!(name.as_str(), "rm" | "rmdir" | "shred" | "unlink" | "find")
                             || (name == "mv" && i + 1 < operands.len());
-                    let p = lexical_abs(t, &facts.home, &cwd);
-                    let hit = if deleting {
-                        is_protected(&p, facts)
-                    } else {
-                        facts.protected.iter().find(|r| p.starts_with(r)).cloned()
-                    };
+                    let hit = facts
+                        .protected
+                        .iter()
+                        .find(|r| match word_covers(t, r, &facts.home, &cwd) {
+                            Cover::Inside => true,
+                            Cover::Parent => deleting,
+                            Cover::None => false,
+                        })
+                        .cloned();
                     if let Some(hit) = hit {
                         return Some(format!(
                             "{} would delete or rewrite the runtime's own file {}",
@@ -871,15 +1088,43 @@ pub fn load_policy(path: &Path) -> CompiledPolicy {
     }
 }
 
-/// `$AIEN_APPROVAL_MODE`, else the policy file's mode, else manual. An
-/// unknown word in the variable falls back to manual (the strictest).
-pub fn resolve_mode(policy: &CompiledPolicy) -> ApprovalMode {
-    match std::env::var("AIEN_APPROVAL_MODE") {
-        Ok(v) => ApprovalMode::parse(&v).unwrap_or(ApprovalMode::Manual),
-        Err(_) => policy.mode.unwrap_or(ApprovalMode::Manual),
+/// Mode comes from the CLI flag or `$AIEN_APPROVAL_MODE`, captured for the
+/// process. The policy file's `mode` field is not a source. An unknown word
+/// falls back to manual.
+pub fn resolve_mode(_policy: &CompiledPolicy) -> ApprovalMode {
+    mode_from_startup_inputs(
+        std::env::var("AIEN_APPROVAL_MODE").ok().as_deref(),
+        cli_approval_mode().as_deref(),
+    )
+}
+
+pub fn mode_from_startup_inputs(env_value: Option<&str>, cli_value: Option<&str>) -> ApprovalMode {
+    if let Some(mode) = cli_value.and_then(ApprovalMode::parse) {
+        return mode;
+    }
+    if let Some(value) = env_value {
+        return ApprovalMode::parse(value).unwrap_or(ApprovalMode::Manual);
+    }
+    ApprovalMode::Manual
+}
+
+static CLI_APPROVAL_MODE: std::sync::Mutex<Option<String>> = std::sync::Mutex::new(None);
+
+/// Record `--approval-mode` from process start. Later calls do not replace it.
+pub fn set_cli_approval_mode(text: &str) {
+    let mut slot = CLI_APPROVAL_MODE.lock().unwrap_or_else(|e| e.into_inner());
+    if slot.is_none() {
+        *slot = Some(text.to_string());
     }
 }
 
+fn cli_approval_mode() -> Option<String> {
+    CLI_APPROVAL_MODE
+        .lock()
+        .unwrap_or_else(|e| e.into_inner())
+        .clone()
+}
+
 /// A person is present when stdin is a terminal and `AIEN_UNATTENDED` is not
 /// set to a true value.
 pub fn resolve_presence() -> Presence {
@@ -913,8 +1158,8 @@ pub fn runtime_facts(home: &Path, policy_file: &Path) -> RuntimeFacts {
     }
 }
 
-/// Everything the gate needs from the environment, read once per request so
-/// an operator's edit to the policy file applies at once.
+/// Everything the gate needs from the environment. Mode is fixed at startup.
+/// Deny and allow rules are loaded from the policy file on each call.
 #[derive(Debug, Clone)]
 pub struct GateContext {
     pub mode: ApprovalMode,
@@ -927,16 +1172,23 @@ impl GateContext {
     pub fn from_env() -> Self {
         let home = crate::platform::PlatformContext::detect().home_dir;
         let path = policy_path(&home);
-        let policy = load_policy(&path);
+        let mode = *STARTUP_MODE.get_or_init(|| resolve_mode(&CompiledPolicy::default()));
+        // Deny and allow rules are read again each call. Mode stays the startup value.
+        Self::load_at(&home, &path, mode)
+    }
+
+    pub fn load_at(home: &Path, policy_file: &Path, mode: ApprovalMode) -> Self {
         Self {
-            mode: resolve_mode(&policy),
+            mode,
             presence: resolve_presence(),
-            facts: runtime_facts(&home, &path),
-            policy,
+            facts: runtime_facts(home, policy_file),
+            policy: load_policy(policy_file),
         }
     }
 }
 
+static STARTUP_MODE: std::sync::OnceLock<ApprovalMode> = std::sync::OnceLock::new();
+
 fn breaker() -> &'static std::sync::Mutex<GuardianBreaker> {
     static BREAKER: std::sync::OnceLock<std::sync::Mutex<GuardianBreaker>> =
         std::sync::OnceLock::new();
@@ -1031,7 +1283,8 @@ mod tests {
                 "mode {mode:?} presence {presence:?}: {v:?}"
             );
         }
-        // Negative control: the same mode and policy let an unmatched command through.
+        // Negative control: an unmatched command is allowed in manual and smart.
+        // Yolo and off still ask, because run_command is bash -c.
         let v = run(
             "run_command",
             &cmd("git status"),
@@ -1040,7 +1293,14 @@ mod tests {
             Presence::Person,
             &pol,
         );
-        assert!(matches!(v, Verdict::Allow { .. }), "mode {mode:?}: {v:?}");
+        if matches!(mode, ApprovalMode::Yolo | ApprovalMode::Off) {
+            assert!(
+                matches!(v, Verdict::AskPerson { .. }),
+                "mode {mode:?}: {v:?}"
+            );
+        } else {
+            assert!(matches!(v, Verdict::Allow { .. }), "mode {mode:?}: {v:?}");
+        }
     }
 
     #[test]
@@ -1256,22 +1516,22 @@ mod tests {
                 "run_command",
                 cmd("echo '{}' > ~/basecamp/approval-policy.json"),
             ),
-            (
-                "run_command",
-                json!({"command": "rm -r sessions", "cwd": "/home/op/basecamp"}),
-            ),
             (
                 "run_command",
                 cmd("sed -i s/deny/x/ /home/op/basecamp/approval-policy.json"),
             ),
             (
                 "run_command",
-                cmd("find /home/op/basecamp/sessions -delete"),
+                json!({"command": "rm -r sessions", "cwd": "/home/op/basecamp"}),
             ),
             (
                 "write_to_file",
                 json!({"path": "/home/op/basecamp/approval-policy.json", "content": "{}"}),
             ),
+            (
+                "run_command",
+                cmd("find /home/op/basecamp/sessions -delete"),
+            ),
             (
                 "replace_file_content",
                 json!({"path": "../basecamp/checkpoints/ledger/s.jsonl", "target": "a", "replacement": "b"}),
@@ -1351,7 +1611,10 @@ mod tests {
                 Presence::Unattended,
                 &pol
             ),
-            Verdict::Allow { by: Stage::Mode }
+            Verdict::Deny {
+                by: Stage::Presence,
+                reason: "run_command requires the person, unattended default is deny".into(),
+            }
         );
         assert_eq!(
             run(
@@ -1362,7 +1625,9 @@ mod tests {
                 Presence::Person,
                 &pol
             ),
-            Verdict::Allow { by: Stage::Mode }
+            Verdict::AskPerson {
+                reason: "run_command requires the person".into(),
+            }
         );
         assert_eq!(
             run(
@@ -1474,9 +1739,7 @@ mod tests {
 
         assert_eq!(
             after_guardian(&GuardianAnswer::Approve, "r".into()),
-            Verdict::Allow {
-                by: Stage::Guardian
-            }
+            Verdict::AskPerson { reason: "r".into() }
         );
         assert!(matches!(
             after_guardian(&GuardianAnswer::Deny("x".into()), "r".into()),
@@ -1485,7 +1748,11 @@ mod tests {
                 ..
             }
         ));
-        for a in [GuardianAnswer::Escalate, GuardianAnswer::Failed("t".into())] {
+        for a in [
+            GuardianAnswer::Approve,
+            GuardianAnswer::Escalate,
+            GuardianAnswer::Failed("t".into()),
+        ] {
             assert_eq!(
                 after_guardian(&a, "r".into()),
                 Verdict::AskPerson { reason: "r".into() }
@@ -1520,6 +1787,193 @@ mod tests {
         assert_eq!(v, Verdict::AskPerson { reason: "q".into() });
     }
 
+    #[test]
+    fn person_floor_holds_in_every_mode_including_yolo() {
+        let pol = policy(&[], &[r".*"]);
+        let cases = [
+            ("sandbox", json!({"action": "promote", "message": "ship"})),
+            ("skill", json!({"action": "optimize", "name": "demo"})),
+            ("skills", json!({"action": "optimize"})),
+        ];
+        for mode in ALL_MODES {
+            for (tool, args) in &cases {
+                let v = run(
+                    tool,
+                    args,
+                    &SafetyDecision::Allow,
+                    mode,
+                    Presence::Person,
+                    &pol,
+                );
+                assert!(
+                    matches!(v, Verdict::AskPerson { .. }),
+                    "{mode:?} {tool}: {v:?}"
+                );
+                let unattended = run(
+                    tool,
+                    args,
+                    &SafetyDecision::Allow,
+                    mode,
+                    Presence::Unattended,
+                    &pol,
+                );
+                assert!(
+                    matches!(unattended, Verdict::Deny { .. }),
+                    "{mode:?} unattended {tool}: {unattended:?}"
+                );
+            }
+        }
+    }
+
+    #[test]
+    fn floors_precede_the_person_prompt() {
+        let pol = policy(&[], &[r".*"]);
+        let bypasses = [
+            "rm -rf / ; echo {} > ~/basecamp/approval-policy.json",
+            "rm -rf / && echo {} > ~/basecamp/approval-policy.json",
+        ];
+        for mode in ALL_MODES {
+            for c in bypasses {
+                let v = run(
+                    "run_command",
+                    &cmd(c),
+                    &SafetyDecision::Allow,
+                    mode,
+                    Presence::Person,
+                    &pol,
+                );
+                assert!(
+                    matches!(
+                        v,
+                        Verdict::Deny {
+                            by: Stage::Floor(Floor::Hardline),
+                            ..
+                        }
+                    ),
+                    "{mode:?} {c}: {v:?}"
+                );
+            }
+        }
+    }
+
+    #[test]
+    fn policy_write_variants_stay_on_the_runtime_floor() {
+        let pol = policy(&[], &[r".*"]);
+        let cases = [
+            "dd if=/dev/zero of=/home/op/basecamp/approval-policy.json",
+            "python3 -c 'open(\"/home/op/basecamp/approval-policy.json\",\"w\").write(\"x\")'",
+            "perl -pi -e s/a/b/ /home/op/basecamp/approval-policy.json",
+            "echo x > /home/op/basecamp/*.json",
+        ];
+        for mode in ALL_MODES {
+            for c in cases {
+                let v = run(
+                    "run_command",
+                    &cmd(c),
+                    &SafetyDecision::Allow,
+                    mode,
+                    Presence::Person,
+                    &pol,
+                );
+                assert!(
+                    matches!(
+                        v,
+                        Verdict::Deny {
+                            by: Stage::Floor(Floor::RuntimeSelfDelete),
+                            ..
+                        }
+                    ),
+                    "{mode:?} {c}: {v:?}"
+                );
+            }
+        }
+        let mut custom = facts();
+        custom
+            .protected
+            .push(PathBuf::from("/var/aien/custom-approval.json"));
+        let v = decide(&Gate {
+            tool: "run_command",
+            args: &cmd("echo x > /var/aien/custom-approval.json"),
+            base: &SafetyDecision::Allow,
+            mode: ApprovalMode::Yolo,
+            presence: Presence::Person,
+            policy: &pol,
+            facts: &custom,
+            guardian_ready: false,
+        });
+        assert!(
+            matches!(
+                v,
+                Verdict::Deny {
+                    by: Stage::Floor(Floor::RuntimeSelfDelete),
+                    ..
+                }
+            ),
+            "custom policy path: {v:?}"
+        );
+    }
+
+    #[test]
+    fn reloaded_deny_rules_apply_and_startup_mode_does_not() {
+        let dir = tempfile::tempdir().unwrap();
+        let file = dir.path().join("approval-policy.json");
+        std::fs::write(&file, r#"{"mode":"off"}"#).unwrap();
+        let first = GateContext::load_at(dir.path(), &file, ApprovalMode::Yolo);
+        assert_eq!(first.mode, ApprovalMode::Yolo);
+        std::fs::write(&file, r#"{"mode":"manual","deny":["echo hi"]}"#).unwrap();
+        let second = GateContext::load_at(dir.path(), &file, first.mode);
+        assert_eq!(second.mode, ApprovalMode::Yolo);
+        let v = run(
+            "run_command",
+            &cmd("echo hi"),
+            &SafetyDecision::Allow,
+            second.mode,
+            Presence::Person,
+            &second.policy,
+        );
+        assert!(
+            matches!(
+                v,
+                Verdict::Deny {
+                    by: Stage::Floor(Floor::OperatorDeny),
+                    ..
+                }
+            ),
+            "{v:?}"
+        );
+    }
+
+    #[test]
+    fn mode_ignores_the_policy_file_and_a_later_edit() {
+        assert_eq!(mode_from_startup_inputs(None, None), ApprovalMode::Manual);
+        assert_eq!(
+            mode_from_startup_inputs(Some("yolo"), None),
+            ApprovalMode::Yolo
+        );
+        assert_eq!(
+            mode_from_startup_inputs(Some("manual"), Some("off")),
+            ApprovalMode::Off
+        );
+        let dir = tempfile::tempdir().unwrap();
+        let file = dir.path().join("approval-policy.json");
+        std::fs::write(&file, r#"{"mode":"yolo"}"#).unwrap();
+        let ctx = GateContext::load_at(dir.path(), &file, ApprovalMode::Manual);
+        assert_eq!(ctx.mode, ApprovalMode::Manual);
+        std::fs::write(&file, r#"{"mode":"off","allow":[".*"]}"#).unwrap();
+        let v = run(
+            "run_command",
+            &cmd("true"),
+            &SafetyDecision::AskUser("needs approval".into()),
+            ctx.mode,
+            Presence::Person,
+            &ctx.policy,
+        );
+        assert!(
+            matches!(v, Verdict::AskPerson { .. }),
+            "a rewritten policy file changed the loaded mode: {v:?}"
+        );
+    }
+
     #[test]
     fn decide_is_deterministic() {
         let pol = policy(&["x"], &["y"]);
@@ -1546,4 +2000,53 @@ mod tests {
             );
         }
     }
+
+    // A glob, class or brace word resolves against the command's own cwd,
+    // not the session cwd, and every write form names the protected file.
+    #[test]
+    fn protected_globs_resolve_against_the_command_cwd() {
+        let f = facts();
+        let at = |c: &str, cwd: &str| json!({"command": c, "cwd": cwd});
+        for (c, cwd) in [
+            ("cp x *-policy.json", "/home/op/basecamp"),
+            ("printf x > *.json", "/home/op/basecamp"),
+            ("printf x >*.json", "/home/op/basecamp"),
+            ("printf x > approval-polic[y].json", "/home/op/basecamp"),
+            (
+                "echo x | tee approval-policy.{json,bak}",
+                "/home/op/basecamp",
+            ),
+            ("printf x > ../basecamp/[a]*.json", "/home/op/work"),
+            ("rm -rf ~/base*", "/home/op/work"),
+            ("rm -rf ../ba?ecamp", "/home/op/work"),
+        ] {
+            assert!(
+                runtime_self_delete("run_command", &at(c, cwd), &f).is_some(),
+                "{c} in {cwd} must hit the runtime floor"
+            );
+        }
+        for (c, cwd) in [
+            ("ls *.json", "/home/op/basecamp"),
+            ("cp a.txt b.txt", "/home/op/basecamp"),
+            ("printf x > *.json", "/home/op/work"),
+            ("cp notes.txt ~/", "/home/op/work"),
+            ("touch ~/base*", "/home/op/work"),
+        ] {
+            assert!(
+                runtime_self_delete("run_command", &at(c, cwd), &f).is_none(),
+                "{c} in {cwd} is not a runtime write"
+            );
+        }
+    }
+
+    #[test]
+    fn brace_and_class_words_expand_like_bash() {
+        assert_eq!(expand_braces("a{b,c}d"), ["abd", "acd"]);
+        assert_eq!(expand_braces("x{1,{2,3}}"), ["x1", "x2", "x3"]);
+        assert_eq!(expand_braces("{}"), ["{}"]);
+        assert!(glob_match("polic[xy]", "policy"));
+        assert!(!glob_match("polic[!y]", "policy"));
+        assert!(glob_match("p[a-z]licy", "policy"));
+        assert!(glob_match("[", "["));
+    }
 }
diff --git a/crates/aien-cli/src/main.rs b/crates/aien-cli/src/main.rs
index e20e83be..f0a53a91 100644
--- a/crates/aien-cli/src/main.rs
+++ b/crates/aien-cli/src/main.rs
@@ -64,6 +64,11 @@ use ui::print_banner;
 #[tokio::main]
 async fn main() {
     let args: Vec<String> = env::args().collect();
+    if let Some(pos) = args.iter().position(|a| a == "--approval-mode") {
+        if let Some(value) = args.get(pos + 1) {
+            crate::approval::set_cli_approval_mode(value);
+        }
+    }
 
     if args.len() > 1 {
         if args[1] == "--daemon" || args[1] == "daemon" {
diff --git a/crates/aien-cli/src/safety.rs b/crates/aien-cli/src/safety.rs
index 0573f38f..00333d7b 100644
--- a/crates/aien-cli/src/safety.rs
+++ b/crates/aien-cli/src/safety.rs
@@ -258,15 +258,7 @@ impl SafetyEngine {
             });
         }
 
-        // 6. GLOBAL WILDCARD ALLOW: Permissive default for verified standard commands
-        engine.add_rule(PolicyRule {
-            name: "allow_standard_commands".to_string(),
-            tool_pattern: "run_command".to_string(),
-            priority: PolicyPriority::GlobalWildcardAllow,
-            predicate: None,
-            action: SafetyDecision::Allow,
-        });
-
+        // `run_command` has no wildcard allow. Manual mode asks the person.
         engine.add_rule(PolicyRule {
             name: "allow_standard_writes".to_string(),
             tool_pattern: "write_to_file".to_string(),
diff --git a/crates/aien-cli/src/tools.rs b/crates/aien-cli/src/tools.rs
index 1c104e8a..f3ab2274 100644
--- a/crates/aien-cli/src/tools.rs
+++ b/crates/aien-cli/src/tools.rs
@@ -18,9 +18,13 @@ use serde_json::{json, Value};
 use sha2::{Digest, Sha256};
 use std::fs;
 use std::io::Write;
+use std::os::fd::AsRawFd;
+use std::os::unix::process::CommandExt;
 use std::path::Path;
-use std::process::Command;
-use std::time::Instant;
+use std::process::{Command, Stdio};
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::Arc;
+use std::time::{Duration, Instant};
 
 use crate::crumbs::{
     format_dir_crumb_tui, leave_dir_whisper, load_or_init_dir_crumb, record_directory_crumb,
@@ -484,36 +488,188 @@ fn bind_err(err: crate::fs_bind::BindError) -> (Value, bool) {
 }
 
 fn exec_command(cmd: &str, cwd: &str) -> (Value, bool) {
-    if let Err(err) = validate_tool_path(cwd) {
-        return (
-            json!({"error": format!("CONFINEMENT DENIAL: Invalid command working directory: {}", err)}),
-            false,
-        );
-    }
+    exec_command_in(cmd, cwd, Duration::from_secs(120))
+}
+
+fn exec_command_in(cmd: &str, cwd: &str, timeout: Duration) -> (Value, bool) {
+    let canon = match validate_tool_path(cwd) {
+        Ok(path) => path,
+        Err(err) => {
+            return (
+                json!({"error": format!("CONFINEMENT DENIAL: Invalid command working directory: {}", err)}),
+                false,
+            );
+        }
+    };
 
-    let out = Command::new("bash")
+    let mut command = Command::new("bash");
+    command
         .args(["-c", cmd])
-        .current_dir(cwd)
-        .output();
-
-    match out {
-        Ok(output) => {
-            let raw_stdout = String::from_utf8_lossy(&output.stdout).to_string();
-            let raw_stderr = String::from_utf8_lossy(&output.stderr).to_string();
-            let stdout = redact_secrets(&raw_stdout);
-            let stderr = redact_secrets(&raw_stderr);
-            let code = output.status.code().unwrap_or(-1);
-            let success = output.status.success();
-            (
-                json!({
-                    "exit_code": code,
-                    "stdout": stdout,
-                    "stderr": stderr
-                }),
-                success,
-            )
+        .current_dir(&canon)
+        .env_clear()
+        .stdin(Stdio::null())
+        .stdout(Stdio::piped())
+        .stderr(Stdio::piped());
+    for key in ["PATH", "HOME", "LANG", "TERM"] {
+        if let Ok(value) = std::env::var(key) {
+            command.env(key, value);
+        }
+    }
+    // New session so the process group id is the child pid. A later
+    // `kill(-pid)` reaches grandchildren that stayed in that group.
+    unsafe {
+        command.pre_exec(|| {
+            if libc::setsid() == -1 {
+                Err(std::io::Error::last_os_error())
+            } else {
+                Ok(())
+            }
+        });
+    }
+    let mut child = match command.spawn() {
+        Ok(child) => child,
+        Err(e) => return (json!({"error": e.to_string()}), false),
+    };
+    let pgid = child.id();
+    let deadline = Instant::now() + timeout;
+    let stop = Arc::new(AtomicBool::new(false));
+    let out = child.stdout.take();
+    let err = child.stderr.take();
+    let out_stop = Arc::clone(&stop);
+    let stdout_thread = std::thread::spawn(move || match out {
+        Some(pipe) => read_until(pipe, deadline, &out_stop),
+        None => Vec::new(),
+    });
+    let err_stop = Arc::clone(&stop);
+    let stderr_thread = std::thread::spawn(move || match err {
+        Some(pipe) => read_until(pipe, deadline, &err_stop),
+        None => Vec::new(),
+    });
+    let status = loop {
+        match child.try_wait() {
+            Ok(Some(status)) => {
+                kill_command_group(pgid);
+                break Some(status);
+            }
+            Ok(None) if Instant::now() >= deadline => {
+                kill_command_group(pgid);
+                let _ = child.wait();
+                stop.store(true, Ordering::Release);
+                let _ = stdout_thread.join();
+                let _ = stderr_thread.join();
+                return (
+                    json!({"error": format!("Command timed out after {:.3} seconds", timeout.as_secs_f64())}),
+                    false,
+                );
+            }
+            Ok(None) => std::thread::sleep(Duration::from_millis(20)),
+            Err(e) => {
+                kill_command_group(pgid);
+                let _ = child.wait();
+                stop.store(true, Ordering::Release);
+                let _ = stdout_thread.join();
+                let _ = stderr_thread.join();
+                return (json!({"error": e.to_string()}), false);
+            }
+        }
+    };
+    // A `setsid` grandchild is outside the killed group and can hold the
+    // pipes open. After a short grace the readers take only buffered output.
+    let grace = (Instant::now() + DRAIN_AFTER_EXIT).min(deadline);
+    while !(stdout_thread.is_finished() && stderr_thread.is_finished()) && Instant::now() < grace {
+        std::thread::sleep(Duration::from_millis(10));
+    }
+    stop.store(true, Ordering::Release);
+    let stdout = String::from_utf8_lossy(&stdout_thread.join().unwrap_or_default()).into_owned();
+    let stderr = String::from_utf8_lossy(&stderr_thread.join().unwrap_or_default()).into_owned();
+    let code = status.map(|s| s.code().unwrap_or(-1)).unwrap_or(-1);
+    let success = status.map(|s| s.success()).unwrap_or(false);
+    (
+        json!({
+            "exit_code": code,
+            "stdout": redact_secrets(&stdout),
+            "stderr": redact_secrets(&stderr)
+        }),
+        success,
+    )
+}
+
+/// How long the readers may wait for more output after the leader exited.
+const DRAIN_AFTER_EXIT: Duration = Duration::from_millis(500);
+
+/// Longest single poll, so a reader notices `stop` promptly.
+const POLL_SLICE_MS: i32 = 50;
+
+fn read_until(
+    mut reader: impl std::io::Read + AsRawFd,
+    deadline: Instant,
+    stop: &AtomicBool,
+) -> Vec<u8> {
+    let fd = reader.as_raw_fd();
+    let flags = unsafe { libc::fcntl(fd, libc::F_GETFL, 0) };
+    if flags >= 0 {
+        unsafe {
+            libc::fcntl(fd, libc::F_SETFL, flags | libc::O_NONBLOCK);
+        }
+    }
+    let mut buf = Vec::new();
+    let mut tmp = [0u8; 8192];
+    loop {
+        match reader.read(&mut tmp) {
+            Ok(0) => return buf,
+            Ok(n) => buf.extend_from_slice(&tmp[..n]),
+            Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue,
+            Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
+                if !wait_fd(fd, deadline, stop) {
+                    return buf;
+                }
+            }
+            Err(_) => return buf,
         }
-        Err(e) => (json!({"error": e.to_string()}), false),
+    }
+}
+
+/// Wait for input in slices of at most [`POLL_SLICE_MS`]. Once `stop` is
+/// set, one zero-timeout poll reports whether data is already buffered.
+fn wait_fd(fd: i32, deadline: Instant, stop: &AtomicBool) -> bool {
+    loop {
+        let stopping = stop.load(Ordering::Acquire);
+        let now = Instant::now();
+        if now >= deadline {
+            return false;
+        }
+        let wait_ms = if stopping {
+            0
+        } else {
+            deadline
+                .saturating_duration_since(now)
+                .as_millis()
+                .clamp(1, POLL_SLICE_MS as u128) as i32
+        };
+        let mut pfd = libc::pollfd {
+            fd,
+            events: libc::POLLIN,
+            revents: 0,
+        };
+        let rc = unsafe { libc::poll(&mut pfd, 1, wait_ms) };
+        if rc > 0 {
+            return true;
+        }
+        if rc == 0 && stopping {
+            return false;
+        }
+        if rc < 0 && std::io::Error::last_os_error().kind() != std::io::ErrorKind::Interrupted {
+            return false;
+        }
+    }
+}
+
+fn kill_command_group(pgid: u32) {
+    if pgid == 0 {
+        return;
+    }
+    unsafe {
+        libc::kill(-(pgid as i32), libc::SIGKILL);
     }
 }
 
@@ -1387,8 +1543,12 @@ mod tests {
                 assert!(!marker.exists(), "{mode:?}: command ran despite the floor");
 
                 let res = dispatch_tool_with("run_command", &args, &gate_ctx(mode, &[]));
-                assert!(res.get("error").is_none(), "{mode:?}: {res}");
-                assert!(marker.exists(), "{mode:?}: control command did not run");
+                let err = res.get("error").and_then(Value::as_str).unwrap_or("");
+                assert!(
+                    err.contains("aborted") || err.contains("SAFETY") || err.contains("approval"),
+                    "{mode:?}: bash -c ran with no person: {res}"
+                );
+                assert!(!marker.exists(), "{mode:?}: command ran without approval");
             }
         });
     }
@@ -1451,4 +1611,88 @@ mod tests {
                 .contains(&operator_file.to_string_lossy().into_owned()));
         });
     }
+
+    #[test]
+    fn run_command_in_manual_mode_requires_approval() {
+        let ctx = gate_ctx(crate::approval::ApprovalMode::Manual, &[]);
+        let res = dispatch_tool_with(
+            "run_command",
+            &json!({"command": "true", "cwd": "/tmp"}),
+            &ctx,
+        );
+        let err = res.get("error").and_then(Value::as_str).unwrap_or("");
+        assert!(
+            err.contains("aborted") || err.contains("approval") || err.contains("SAFETY"),
+            "{res}"
+        );
+    }
+
+    #[test]
+    fn command_child_does_not_inherit_the_parent_environment() {
+        let key = "AIEN_ENV_PROBE_SECRET";
+        let value = "probe-value-not-for-the-child";
+        std::env::set_var(key, value);
+        let (res, _) = exec_command_in(&format!("printenv {key}"), "/tmp", Duration::from_secs(5));
+        std::env::remove_var(key);
+        let rendered = res.to_string();
+        assert!(!rendered.contains(value), "{key} was inherited: {res}");
+    }
+
+    #[test]
+    fn command_timeout_kills_the_process_group() {
+        let started = Instant::now();
+        let (res, ok) = exec_command_in("sleep 30", "/tmp", Duration::from_millis(300));
+        assert!(
+            started.elapsed() < Duration::from_secs(3),
+            "sleep was not killed: {res}"
+        );
+        assert!(!ok, "{res}");
+        assert!(
+            res["error"].as_str().unwrap_or("").contains("timed out"),
+            "{res}"
+        );
+
+        let started = Instant::now();
+        let _ = exec_command_in("sleep 30 &", "/tmp", Duration::from_secs(2));
+        assert!(
+            started.elapsed() < Duration::from_secs(3),
+            "a background grandchild held the command open"
+        );
+    }
+
+    #[test]
+    fn setsid_grandchild_cannot_hold_the_drain_open() {
+        let dir = tempfile::tempdir().unwrap();
+        let script = dir.path().join("hold.sh");
+        let pidfile = dir.path().join("pid");
+        // The holder records its pid only after `setsid`, and the leader
+        // waits for that, so the escape always happens before the group kill.
+        std::fs::write(
+            &script,
+            "#!/bin/sh\nsetsid sh -c 'echo $$ > \"$1\"; exec sleep 60' hold \"$1\" &\nwhile [ ! -s \"$1\" ]; do sleep 0.01; done\necho leader-done\n",
+        )
+        .unwrap();
+        std::fs::set_permissions(
+            &script,
+            <std::fs::Permissions as std::os::unix::fs::PermissionsExt>::from_mode(0o755),
+        )
+        .unwrap();
+        let command = format!("{} {}", script.display(), pidfile.display());
+        let started = Instant::now();
+        // The timeout is far above the bound, so only the post-exit drain
+        // limit can make the call return in time.
+        let (res, _) = exec_command_in(&command, "/tmp", Duration::from_secs(10));
+        let elapsed = started.elapsed();
+        let pid_txt = std::fs::read_to_string(&pidfile).unwrap_or_default();
+        let pid: i32 = pid_txt.trim().parse().unwrap_or(0);
+        if pid > 0 {
+            unsafe {
+                libc::kill(pid, libc::SIGKILL);
+            }
+        }
+        assert!(
+            elapsed < Duration::from_secs(3),
+            "setsid grandchild held the drain: {elapsed:?} {res}"
+        );
+    }
 }
diff --git a/crates/aien-cli/src/ui.rs b/crates/aien-cli/src/ui.rs
index fc70f4ea..47118cb6 100644
--- a/crates/aien-cli/src/ui.rs
+++ b/crates/aien-cli/src/ui.rs
@@ -103,6 +103,11 @@ pub fn print_tool_done(tool_name: &str, elapsed_ms: u128, success: bool) {
 }
 
 pub fn print_safety_prompt(cmd: &str) -> bool {
+    use std::io::IsTerminal;
+    // CI and a non-interactive stdin have no person to answer. Do not block.
+    if std::env::var_os("CI").is_some() || !std::io::stdin().is_terminal() {
+        return false;
+    }
     println!(
         "\n{}",
         "⚠ [SAFETY GATE] AIEN requested high-risk operation:"
diff --git a/crates/aien-drive/Cargo.toml b/crates/aien-drive/Cargo.toml
index 4458b54c..a40272f2 100644
--- a/crates/aien-drive/Cargo.toml
+++ b/crates/aien-drive/Cargo.toml
@@ -10,6 +10,7 @@ repository.workspace = true
 # Plain http:// to loopback only, over std::net. No Python, no TLS, no async.
 [dependencies]
 clap = { version = "4.5", features = ["derive"] }
+libc = "0.2"
 regex = "1.10"
 serde_json = "1"
 
diff --git a/crates/aien-drive/src/command.rs b/crates/aien-drive/src/command.rs
new file mode 100644
index 00000000..db8b7841
--- /dev/null
+++ b/crates/aien-drive/src/command.rs
@@ -0,0 +1,980 @@
+// SPDX-License-Identifier: Apache-2.0
+// Copyright 2026 Drake Stapleton (AIEN / aien-dev)
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+//! Operator policy for `run_command`.
+//!
+//! The model supplies `command` and `cwd` only. This policy is filled from
+//! code or from the operator environment, never from tool arguments.
+//!
+//! Extending [`CommandPolicy::allowlist`] is an operator-trusted action, and
+//! for any program that can run code (an interpreter, `git`, `make`, `awk`,
+//! a compiler) it is shell-equivalent: the model can write a script with the
+//! file tools and pass its path. A name that is accepted is executed with the
+//! model's arguments. Shells and exec wrappers (`sh`, `bash`, `nice`,
+//! `timeout`, `env`, `xargs`, `nohup`, `setsid`, `stdbuf`, and the rest of
+//! [`SHELLS`] / [`EXEC_WRAPPERS`]) are rejected when the allowlist is built
+//! and again at execution, even if a caller puts them on the list.
+//! Interpreters in [`INTERPRETERS`] reject their inline-code options, including
+//! inside short clusters (`perl -le`, `python3 -Bc`) and versioned names
+//! (`python3.12`, `php8.2`). `git` rejects global `-c` / `--exec-path` /
+//! `--config-env`, `git config` writes, and the options and subcommands that
+//! run a program (`--upload-pack`, `rebase -x`, `bisect run`, ...). These
+//! checks remove one-line escalation; they do not make such a program safe.
+
+use serde_json::{json, Value};
+use std::io::Read;
+use std::os::unix::io::AsRawFd;
+use std::path::{Component, Path, PathBuf};
+use std::process::{Child, Command, Stdio};
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::Arc;
+use std::thread::JoinHandle;
+use std::time::{Duration, Instant};
+
+use std::os::unix::process::CommandExt;
+
+/// Programs the crate itself has been shown to need, and nothing that reads
+/// or writes the filesystem. `echo` is the loop-stub round trip. `printf` is
+/// the historical output-size fixture. `true` is the bad-cwd probe. `false`
+/// and `pwd` are the same class of program: they do not take a shell and they
+/// do not open files. File inspection stays on `view_file`, `list_dir`, and
+/// `grep_search`. Operators add other names with
+/// `AIEN_DRIVE_COMMAND_ALLOWLIST`. That extension is trusted: see the module
+/// docs. Shells and exec wrappers in the value are dropped.
+pub const DEFAULT_COMMAND_ALLOWLIST: &[&str] = &["echo", "printf", "true", "false", "pwd"];
+
+/// Limits and the program allowlist for one driver process.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct CommandPolicy {
+    /// Bare program names that may be executed. The model cannot extend this.
+    pub allowlist: Vec<String>,
+    /// When true, the command string is passed to `/bin/sh -c`.
+    /// Off by default. Tool arguments cannot turn this on.
+    pub allow_shell: bool,
+    /// `cwd` must canonicalize inside this directory. An absolute `cwd`
+    /// inside the root is accepted. An absolute `cwd` outside the root is
+    /// rejected. The default is empty, which fails closed. Set
+    /// `AIEN_DRIVE_COMMAND_ROOT`, or assign this field. The process cwd is
+    /// not used as the root.
+    pub root: PathBuf,
+    pub timeout: Duration,
+    /// Stdout characters returned to the model (the tail, matching the
+    /// previous driver).
+    pub max_stdout: usize,
+    /// Stderr characters returned to the model.
+    pub max_stderr: usize,
+    /// Bytes read from one stream before the process is killed.
+    pub max_capture: usize,
+}
+
+impl Default for CommandPolicy {
+    fn default() -> Self {
+        Self {
+            allowlist: DEFAULT_COMMAND_ALLOWLIST
+                .iter()
+                .map(|s| (*s).to_string())
+                .collect(),
+            allow_shell: false,
+            // Not the process cwd. The operator sets `AIEN_DRIVE_COMMAND_ROOT`
+            // or assigns this field. An empty root fails closed.
+            root: PathBuf::new(),
+            timeout: Duration::from_secs(120),
+            max_stdout: 4000,
+            max_stderr: 2000,
+            max_capture: 1024 * 1024,
+        }
+    }
+}
+
+impl CommandPolicy {
+    /// Operator environment of the `aien-drive` process. Unset variables keep
+    /// the defaults. `AIEN_DRIVE_ALLOW_SHELL` must be the exact string `1`.
+    pub fn from_operator_env() -> Self {
+        Self::from_operator_values(
+            std::env::var("AIEN_DRIVE_COMMAND_ALLOWLIST")
+                .ok()
+                .as_deref(),
+            std::env::var("AIEN_DRIVE_ALLOW_SHELL").ok().as_deref(),
+            std::env::var("AIEN_DRIVE_COMMAND_ROOT").ok().as_deref(),
+            std::env::var("AIEN_DRIVE_COMMAND_TIMEOUT_SECS")
+                .ok()
+                .as_deref(),
+        )
+    }
+
+    pub fn from_operator_values(
+        allowlist: Option<&str>,
+        allow_shell: Option<&str>,
+        root: Option<&str>,
+        timeout_secs: Option<&str>,
+    ) -> Self {
+        let mut policy = Self::default();
+        if let Some(raw) = allowlist {
+            // Shells and exec wrappers are dropped here so an operator string
+            // cannot reintroduce them. Direct struct assignment is checked
+            // again in `reject_dangerous_invocation`.
+            policy.allowlist = raw
+                .split(',')
+                .map(str::trim)
+                .filter(|s| !s.is_empty() && !is_shell_or_wrapper(s))
+                .map(str::to_string)
+                .collect();
+        }
+        policy.allow_shell = matches!(allow_shell.map(str::trim), Some("1"));
+        if let Some(root) = root.map(str::trim).filter(|s| !s.is_empty()) {
+            policy.root = PathBuf::from(root);
+        }
+        if let Some(secs) = timeout_secs {
+            if let Ok(secs) = secs.trim().parse::<u64>() {
+                if secs > 0 {
+                    policy.timeout = Duration::from_secs(secs);
+                }
+            }
+        }
+        policy
+    }
+}
+
+/// Shells. Rejected on the allowlist and at execution. Use `allow_shell`.
+const SHELLS: &[&str] = &[
+    "sh", "bash", "dash", "zsh", "ksh", "ash", "csh", "tcsh", "fish", "busybox", "elvish",
+];
+
+/// Programs whose job is to exec another program. Rejected on the allowlist
+/// and at execution so `nice bash -c id` cannot undo the confinement.
+const EXEC_WRAPPERS: &[&str] = &[
+    "env", "nice", "timeout", "xargs", "nohup", "setsid", "stdbuf", "ionice", "taskset", "chrt",
+    "numactl", "setarch", "setpriv", "unshare", "nsenter", "watch", "time", "find", "flock",
+];
+
+/// An interpreter's inline-code options. Short options are scanned as a
+/// cluster: an eval letter is rejected unless an earlier letter in the same
+/// cluster takes the rest of the argument as its value.
+struct Interpreter {
+    names: &'static [&'static str],
+    eval_short: &'static str,
+    value_short: &'static str,
+    eval_long: &'static [&'static str],
+}
+
+/// Interpreters whose eval options run model text as code.
+const INTERPRETERS: &[Interpreter] = &[
+    Interpreter {
+        names: &["perl"],
+        eval_short: "eE",
+        value_short: "IMmxdDF",
+        eval_long: &[],
+    },
+    Interpreter {
+        names: &["python", "pypy"],
+        eval_short: "c",
+        value_short: "WXm",
+        eval_long: &[],
+    },
+    Interpreter {
+        names: &["ruby"],
+        eval_short: "e",
+        value_short: "IrCEFxK",
+        eval_long: &[],
+    },
+    Interpreter {
+        names: &["node", "nodejs", "bun"],
+        eval_short: "epc",
+        value_short: "r",
+        eval_long: &["--eval", "--print"],
+    },
+    Interpreter {
+        names: &["lua", "luajit"],
+        eval_short: "e",
+        value_short: "l",
+        eval_long: &[],
+    },
+    Interpreter {
+        names: &["php"],
+        eval_short: "rBRFE",
+        value_short: "dcz",
+        eval_long: &[
+            "--run",
+            "--process-begin",
+            "--process-code",
+            "--process-file",
+            "--process-end",
+        ],
+    },
+    Interpreter {
+        names: &["awk", "gawk", "mawk", "nawk"],
+        eval_short: "eE",
+        value_short: "fvF",
+        eval_long: &["--source", "--exec"],
+    },
+];
+
+/// The interpreter for an argv[0], ignoring a version suffix (`python3.12`).
+fn interpreter(name: &str) -> Option<&'static Interpreter> {
+    let base = name.trim_end_matches(|c: char| c.is_ascii_digit() || c == '.');
+    INTERPRETERS.iter().find(|i| i.names.contains(&base))
+}
+
+fn is_shell_or_wrapper(name: &str) -> bool {
+    SHELLS.contains(&name) || EXEC_WRAPPERS.contains(&name)
+}
+
+const SEARCH_DIRS: &[&str] = &["/bin", "/usr/bin"];
+
+/// Run the model `command` under `policy`. Failures are strings for the model.
+pub(crate) fn execute(policy: &CommandPolicy, args: &Value) -> Result<Value, String> {
+    let command = args.get("command").and_then(Value::as_str).unwrap_or("");
+    if command.trim().is_empty() {
+        return Err("run_command rejected: empty command".into());
+    }
+    if command.contains('\0') {
+        return Err("run_command rejected: shell metacharacter NUL is not allowed".into());
+    }
+    let cwd_arg = args.get("cwd").and_then(Value::as_str).unwrap_or(".");
+    let cwd = resolve_cwd(&policy.root, cwd_arg)?;
+    let (program, argv) = if policy.allow_shell {
+        let program = PathBuf::from("/bin/sh");
+        if !program.is_file() {
+            return Err(
+                "run_command rejected: /bin/sh is not available for the operator shell opt-in"
+                    .into(),
+            );
+        }
+        (program, vec!["-c".to_string(), command.to_string()])
+    } else {
+        reject_metacharacters(command)?;
+        let argv = parse_argv(command)?;
+        reject_dangerous_invocation(&argv)?;
+        let program = resolve_program(&argv[0], &policy.allowlist)?;
+        (program, argv[1..].to_vec())
+    };
+    let (code, stdout, stderr) = run_captured(
+        &program,
+        &argv,
+        &cwd,
+        policy.timeout,
+        policy.max_capture,
+        &short_label(command),
+    )?;
+    Ok(json!({
+        "exit_code": code,
+        "stdout": crate::last_chars(&stdout, policy.max_stdout),
+        "stderr": crate::last_chars(&stderr, policy.max_stderr),
+    }))
+}
+
+fn reject_metacharacters(command: &str) -> Result<(), String> {
+    for c in command.chars() {
+        if is_shell_meta(c) {
+            return Err(format!(
+                "run_command rejected: shell metacharacter {} is not allowed. Pass one allowlisted program and its arguments.",
+                meta_label(c)
+            ));
+        }
+    }
+    Ok(())
+}
+
+fn is_shell_meta(c: char) -> bool {
+    matches!(
+        c,
+        ';' | '|'
+            | '&'
+            | '$'
+            | '`'
+            | '<'
+            | '>'
+            | '('
+            | ')'
+            | '{'
+            | '}'
+            | '\\'
+            | '!'
+            | '*'
+            | '?'
+            | '~'
+            | '#'
+            | '\n'
+            | '\r'
+            | '\0'
+    )
+}
+
+fn meta_label(c: char) -> String {
+    match c {
+        '\n' => "newline".to_string(),
+        '\r' => "carriage return".to_string(),
+        '\0' => "NUL".to_string(),
+        _ => format!("'{c}'"),
+    }
+}
+
+fn parse_argv(command: &str) -> Result<Vec<String>, String> {
+    let mut args = Vec::new();
+    let mut cur = String::new();
+    let mut in_single = false;
+    let mut in_double = false;
+    let mut any = false;
+    for c in command.chars() {
+        match c {
+            '\'' if !in_double => {
+                in_single = !in_single;
+                any = true;
+            }
+            '"' if !in_single => {
+                in_double = !in_double;
+                any = true;
+            }
+            ' ' | '\t' if !in_single && !in_double => {
+                if any {
+                    args.push(std::mem::take(&mut cur));
+                    any = false;
+                }
+            }
+            _ => {
+                cur.push(c);
+                any = true;
+            }
+        }
+    }
+    if in_single || in_double {
+        return Err("run_command rejected: unmatched quote".into());
+    }
+    if any {
+        args.push(cur);
+    }
+    if args.is_empty() {
+        return Err("run_command rejected: empty command".into());
+    }
+    Ok(args)
+}
+
+fn reject_dangerous_invocation(argv: &[String]) -> Result<(), String> {
+    let name = argv.first().map(String::as_str).unwrap_or("");
+    if is_shell_or_wrapper(name) {
+        return Err(format!(
+            "run_command rejected: '{name}' is a shell or exec wrapper and cannot be allowlisted. Shell execution requires the operator allow_shell opt-in, which is off."
+        ));
+    }
+    if let Some(interp) = interpreter(name) {
+        // Every argument is scanned, not just options before the script:
+        // value-taking options make "stop at the first operand" unsafe.
+        if let Some(arg) = argv.iter().skip(1).find(|a| is_eval_flag(interp, a)) {
+            return Err(format!(
+                "run_command rejected: '{name}' option '{arg}' is an eval flag and runs inline code."
+            ));
+        }
+    }
+    if name == "git" {
+        if let Some(why) = git_override(&argv[1..]) {
+            return Err(format!("run_command rejected: git {why} is not allowed."));
+        }
+    }
+    Ok(())
+}
+
+fn is_eval_flag(interp: &Interpreter, arg: &str) -> bool {
+    if let Some(long) = arg.strip_prefix("--") {
+        let long = long.split('=').next().unwrap_or("");
+        return interp.eval_long.iter().any(|e| &e[2..] == long);
+    }
+    let Some(cluster) = arg.strip_prefix('-') else {
+        return false;
+    };
+    for c in cluster.chars() {
+        if interp.eval_short.contains(c) {
+            return true;
+        }
+        if interp.value_short.contains(c) {
+            return false;
+        }
+    }
+    false
+}
+
+/// Global options that take the next argument as their value.
+const GIT_GLOBAL_VALUE: &[&str] = &[
+    "-C",
+    "--git-dir",
+    "--work-tree",
+    "--namespace",
+    "--super-prefix",
+    "--attr-source",
+];
+
+/// Options that name a program for git to run.
+const GIT_RUNS_PROGRAM: &[&str] = &[
+    "--upload-pack",
+    "--receive-pack",
+    "--exec",
+    "--extcmd",
+    "--template",
+    "--config",
+];
+
+/// Why this git invocation can run a program or rewrite config, if it can.
+/// `args` excludes `git` itself.
+fn git_override(args: &[String]) -> Option<String> {
+    let mut i = 0;
+    while i < args.len() {
+        let arg = args[i].as_str();
+        if arg == "-c"
+            || arg.starts_with("-c")
+            || arg == "--exec-path"
+            || arg.starts_with("--exec-path=")
+            || arg.starts_with("--config-env")
+        {
+            return Some(format!("'{arg}' (global config or exec-path override)"));
+        }
+        if !arg.starts_with('-') {
+            break;
+        }
+        i += if GIT_GLOBAL_VALUE.contains(&arg) {
+            2
+        } else {
+            1
+        };
+    }
+    let sub = args.get(i).map(String::as_str)?;
+    let rest = &args[i + 1..];
+    for arg in rest {
+        let long = arg.split('=').next().unwrap_or("");
+        if GIT_RUNS_PROGRAM.contains(&long) {
+            return Some(format!("'{arg}' (runs a program or sets config)"));
+        }
+    }
+    // Short options that run a program or set config in one subcommand only;
+    // elsewhere the same letter is harmless (`git log -c`, `git add -u`).
+    let short_runs = match sub {
+        "clone" => "cu",
+        "rebase" | "difftool" => "x",
+        _ => "",
+    };
+    if let Some(arg) = rest.iter().find(|a| {
+        a.strip_prefix('-')
+            .is_some_and(|c| !c.starts_with('-') && c.chars().any(|c| short_runs.contains(c)))
+    }) {
+        return Some(format!("{sub} '{arg}' (runs a program or sets config)"));
+    }
+    let first = rest
+        .iter()
+        .find(|a| !a.starts_with('-'))
+        .map(String::as_str);
+    match (sub, first) {
+        ("bisect", Some("run")) | ("submodule", Some("foreach")) | ("filter-branch", _) => {
+            return Some(format!("{sub} (runs a program)"));
+        }
+        ("config", _) => {
+            const READ: &[&str] = &[
+                "--get",
+                "--get-all",
+                "--get-regexp",
+                "--get-urlmatch",
+                "--get-color",
+                "--get-colorbool",
+                "--list",
+                "-l",
+            ];
+            const WRITE: &[&str] = &[
+                "--add",
+                "--replace-all",
+                "--unset",
+                "--unset-all",
+                "--rename-section",
+                "--remove-section",
+                "--edit",
+                "-e",
+            ];
+            let read = matches!(first, Some("get" | "list"))
+                || rest.iter().any(|a| READ.contains(&a.as_str()));
+            let write = matches!(
+                first,
+                Some("set" | "unset" | "rename-section" | "remove-section" | "edit")
+            ) || rest.iter().any(|a| WRITE.contains(&a.as_str()));
+            if write || !read {
+                return Some("config write".into());
+            }
+        }
+        _ => {}
+    }
+    None
+}
+
+fn resolve_program(name: &str, allowlist: &[String]) -> Result<PathBuf, String> {
+    if name.contains('/') || name.contains('\\') {
+        return Err(format!(
+            "run_command rejected: program path '{name}' is not allowed; pass a bare name"
+        ));
+    }
+    if is_shell_or_wrapper(name) {
+        return Err(format!(
+            "run_command rejected: '{name}' is a shell or exec wrapper and cannot be allowlisted. Shell execution requires the operator allow_shell opt-in, which is off."
+        ));
+    }
+    let bare = !name.is_empty()
+        && name
+            .chars()
+            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '+' | '-'));
+    if !bare {
+        return Err(format!(
+            "run_command rejected: program '{name}' is not a bare name"
+        ));
+    }
+    if !allowlist.iter().any(|allowed| allowed == name) {
+        return Err(format!(
+            "run_command rejected: program '{name}' is not in the allowlist"
+        ));
+    }
+    for dir in SEARCH_DIRS {
+        let path = Path::new(dir).join(name);
+        if path.is_file() {
+            return Ok(path);
+        }
+    }
+    Err(format!(
+        "run_command rejected: program '{name}' was not found in /bin or /usr/bin"
+    ))
+}
+
+fn resolve_cwd(root: &Path, requested: &str) -> Result<PathBuf, String> {
+    let root = root.canonicalize().map_err(|e| {
+        format!(
+            "run_command rejected: command root '{}' is not available: {e}",
+            root.display()
+        )
+    })?;
+    let requested_path = PathBuf::from(requested);
+    let joined = if requested_path.is_absolute() {
+        requested_path
+    } else {
+        root.join(requested_path)
+    };
+    let lexical = normalize_lexical(&joined);
+    if !lexical.starts_with(&root) {
+        return Err(format!(
+            "run_command rejected: working directory '{requested}' is outside the command root '{}'",
+            root.display()
+        ));
+    }
+    let canon = joined.canonicalize().map_err(|e| {
+        format!("run_command rejected: working directory '{requested}' is not available: {e}")
+    })?;
+    if !canon.starts_with(&root) {
+        return Err(format!(
+            "run_command rejected: working directory '{requested}' is outside the command root '{}'",
+            root.display()
+        ));
+    }
+    Ok(canon)
+}
+
+fn normalize_lexical(path: &Path) -> PathBuf {
+    let mut out = PathBuf::new();
+    for component in path.components() {
+        match component {
+            Component::CurDir => {}
+            Component::ParentDir => {
+                out.pop();
+            }
+            other => out.push(other.as_os_str()),
+        }
+    }
+    out
+}
+
+fn run_captured(
+    program: &Path,
+    args: &[String],
+    cwd: &Path,
+    timeout: Duration,
+    max_capture: usize,
+    label: &str,
+) -> Result<(i32, String, String), String> {
+    let deadline = Instant::now() + timeout;
+    let mut cmd = Command::new(program);
+    cmd.args(args)
+        .current_dir(cwd)
+        .env_clear()
+        .env("PATH", "/usr/bin:/bin")
+        .env("LANG", "C")
+        .env("LC_ALL", "C")
+        .stdin(Stdio::null())
+        .stdout(Stdio::piped())
+        .stderr(Stdio::piped())
+        // Own process group so a background grandchild shares this pgid
+        // and `kill_group` reaches it.
+        .process_group(0);
+    let mut child = cmd.spawn().map_err(|e| {
+        format!(
+            "run_command rejected: failed to start '{}': {e}",
+            program.display()
+        )
+    })?;
+    let pgid = child.id();
+    let out = child
+        .stdout
+        .take()
+        .ok_or_else(|| "run_command rejected: stdout pipe was not created".to_string())?;
+    let err = child
+        .stderr
+        .take()
+        .ok_or_else(|| "run_command rejected: stderr pipe was not created".to_string())?;
+    let stdout_hit = Arc::new(AtomicBool::new(false));
+    let stderr_hit = Arc::new(AtomicBool::new(false));
+    let stop = Arc::new(AtomicBool::new(false));
+    let stdout_thread = spawn_reader(out, max_capture, &stdout_hit, deadline, &stop);
+    let stderr_thread = spawn_reader(err, max_capture, &stderr_hit, deadline, &stop);
+    let status: Result<std::process::ExitStatus, String> = loop {
+        match child.try_wait() {
+            Ok(Some(status)) => {
+                // The leader exited. A grandchild may still hold the pipes.
+                kill_group(pgid);
+                break Ok(status);
+            }
+            Ok(None) => {}
+            Err(e) => {
+                reap_group(&mut child, pgid);
+                stop.store(true, Ordering::Release);
+                let _ = join_readers(stdout_thread, stderr_thread);
+                return Err(e.to_string());
+            }
+        }
+        if stdout_hit.load(Ordering::Acquire) || stderr_hit.load(Ordering::Acquire) {
+            reap_group(&mut child, pgid);
+            stop.store(true, Ordering::Release);
+            let _ = join_readers(stdout_thread, stderr_thread);
+            let stream = if stdout_hit.load(Ordering::Acquire) {
+                "stdout"
+            } else {
+                "stderr"
+            };
+            return Err(format!(
+                "run_command rejected: {stream} exceeded the {max_capture} byte capture cap"
+            ));
+        }
+        if Instant::now() >= deadline {
+            reap_group(&mut child, pgid);
+            stop.store(true, Ordering::Release);
+            let _ = join_readers(stdout_thread, stderr_thread);
+            return Err(format!(
+                "Command '{label}' timed out after {:.3} seconds",
+                timeout.as_secs_f64()
+            ));
+        }
+        std::thread::sleep(Duration::from_millis(20));
+    };
+    // A grandchild that left the group with `setsid` is out of `kill_group`'s
+    // reach and can hold the pipes open. Give the readers a short grace to
+    // take what the leader wrote, then stop them; they still drain whatever
+    // is already buffered.
+    let grace = (Instant::now() + DRAIN_AFTER_EXIT).min(deadline);
+    while !(stdout_thread.is_finished() && stderr_thread.is_finished()) && Instant::now() < grace {
+        std::thread::sleep(Duration::from_millis(10));
+    }
+    stop.store(true, Ordering::Release);
+    let (stdout, stderr) = join_readers(stdout_thread, stderr_thread);
+    let status = status?;
+    if stdout_hit.load(Ordering::Acquire) {
+        return Err(format!(
+            "run_command rejected: stdout exceeded the {max_capture} byte capture cap"
+        ));
+    }
+    if stderr_hit.load(Ordering::Acquire) {
+        return Err(format!(
+            "run_command rejected: stderr exceeded the {max_capture} byte capture cap"
+        ));
+    }
+    Ok((status.code().unwrap_or(-1), stdout, stderr))
+}
+
+/// How long the readers may wait for more output after the leader exited.
+const DRAIN_AFTER_EXIT: Duration = Duration::from_millis(500);
+
+/// Longest single poll, so a reader notices `stop` promptly.
+const POLL_SLICE_MS: i32 = 50;
+
+fn spawn_reader<R>(
+    reader: R,
+    cap: usize,
+    hit: &Arc<AtomicBool>,
+    deadline: Instant,
+    stop: &Arc<AtomicBool>,
+) -> JoinHandle<Vec<u8>>
+where
+    R: Read + AsRawFd + Send + 'static,
+{
+    let (hit, stop) = (Arc::clone(hit), Arc::clone(stop));
+    std::thread::spawn(move || read_bounded(reader, cap, &hit, deadline, &stop))
+}
+
+/// Read until EOF, `cap`, `deadline`, or `stop`. After `stop` the reader
+/// takes only what is already buffered, so a grandchild holding the pipe
+/// cannot block the drain.
+fn read_bounded(
+    mut reader: impl Read + AsRawFd,
+    cap: usize,
+    hit: &AtomicBool,
+    deadline: Instant,
+    stop: &AtomicBool,
+) -> Vec<u8> {
+    let fd = reader.as_raw_fd();
+    set_nonblock(fd);
+    let mut buf = Vec::new();
+    let mut tmp = [0u8; 8192];
+    loop {
+        if buf.len() >= cap {
+            if extra_byte(&mut reader, fd, deadline, stop) {
+                hit.store(true, Ordering::Release);
+            }
+            return buf;
+        }
+        let want = (cap - buf.len()).min(tmp.len());
+        match reader.read(&mut tmp[..want]) {
+            Ok(0) => return buf,
+            Ok(n) => buf.extend_from_slice(&tmp[..n]),
+            Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue,
+            Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
+                if !wait_readable(fd, deadline, stop) {
+                    return buf;
+                }
+            }
+            Err(_) => return buf,
+        }
+    }
+}
+
+fn extra_byte(reader: &mut impl Read, fd: i32, deadline: Instant, stop: &AtomicBool) -> bool {
+    loop {
+        let mut extra = [0u8; 1];
+        match reader.read(&mut extra) {
+            Ok(0) => return false,
+            Ok(_) => return true,
+            Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue,
+            Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
+                if !wait_readable(fd, deadline, stop) {
+                    return false;
+                }
+            }
+            Err(_) => return false,
+        }
+    }
+}
+
+/// Wait for input in slices of at most [`POLL_SLICE_MS`]. Once `stop` is
+/// set, one zero-timeout poll reports whether data is already buffered.
+fn wait_readable(fd: i32, deadline: Instant, stop: &AtomicBool) -> bool {
+    loop {
+        let stopping = stop.load(Ordering::Acquire);
+        let now = Instant::now();
+        if now >= deadline {
+            return false;
+        }
+        let wait_ms = if stopping {
+            0
+        } else {
+            deadline
+                .saturating_duration_since(now)
+                .as_millis()
+                .clamp(1, POLL_SLICE_MS as u128) as i32
+        };
+        let mut pfd = PollFd {
+            fd,
+            events: POLLIN,
+            revents: 0,
+        };
+        let rc = unsafe { poll(&mut pfd, 1, wait_ms) };
+        if rc > 0 {
+            return true;
+        }
+        if rc == 0 && stopping {
+            return false;
+        }
+        if rc < 0 && std::io::Error::last_os_error().kind() != std::io::ErrorKind::Interrupted {
+            return false;
+        }
+    }
+}
+
+fn set_nonblock(fd: i32) {
+    let flags = unsafe { fcntl(fd, F_GETFL, 0) };
+    if flags >= 0 {
+        let _ = unsafe { fcntl(fd, F_SETFL, flags | O_NONBLOCK) };
+    }
+}
+
+fn short_label(command: &str) -> String {
+    let mut out = String::new();
+    for (i, c) in command.chars().enumerate() {
+        if i == 120 {
+            out.push_str("...");
+            break;
+        }
+        out.push(c);
+    }
+    out
+}
+
+fn join_readers(stdout: JoinHandle<Vec<u8>>, stderr: JoinHandle<Vec<u8>>) -> (String, String) {
+    let stdout = String::from_utf8_lossy(&stdout.join().unwrap_or_default()).into_owned();
+    let stderr = String::from_utf8_lossy(&stderr.join().unwrap_or_default()).into_owned();
+    (stdout, stderr)
+}
+
+fn reap_group(child: &mut Child, pgid: u32) {
+    kill_group(pgid);
+    let _ = child.kill();
+    let _ = child.wait();
+}
+
+fn kill_group(pgid: u32) {
+    if pgid == 0 {
+        return;
+    }
+    let _ = unsafe {
+        // SAFETY: `pgid` is the spawned child's pid. `process_group(0)` made
+        // that pid the process group id. A negative pid signals only that
+        // group, not the driver.
+        kill(-(pgid as i32), 9)
+    };
+}
+
+const POLLIN: i16 = 1;
+const F_GETFL: i32 = 3;
+const F_SETFL: i32 = 4;
+const O_NONBLOCK: i32 = 0o4000;
+
+#[repr(C)]
+struct PollFd {
+    fd: i32,
+    events: i16,
+    revents: i16,
+}
+
+unsafe extern "C" {
+    fn kill(pid: i32, sig: i32) -> i32;
+    fn poll(fds: *mut PollFd, nfds: usize, timeout: i32) -> i32;
+    fn fcntl(fd: i32, cmd: i32, arg: i32) -> i32;
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use std::os::unix::fs::PermissionsExt;
+
+    #[test]
+    fn grandchild_holding_the_pipe_does_not_hang_the_drain() {
+        let dir = std::env::temp_dir().join(format!(
+            "aien-drive-bg-{}-{}",
+            std::process::id(),
+            std::time::SystemTime::now()
+                .duration_since(std::time::UNIX_EPOCH)
+                .unwrap()
+                .as_nanos()
+        ));
+        std::fs::create_dir_all(&dir).unwrap();
+        let script = dir.join("bg.sh");
+        let pidfile = dir.join("pid");
+        std::fs::write(&script, "#!/bin/sh\nsleep 30 &\necho $! > \"$1\"\nexit 0\n").unwrap();
+        std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();
+        let started = Instant::now();
+        let result = run_captured(
+            &script,
+            &[pidfile.display().to_string()],
+            &dir,
+            Duration::from_secs(2),
+            1024 * 1024,
+            "bg",
+        );
+        let elapsed = started.elapsed();
+        let pid_txt = std::fs::read_to_string(&pidfile).unwrap_or_default();
+        let pid: i32 = pid_txt.trim().parse().unwrap_or(0);
+        let mut alive = pid > 0;
+        if alive {
+            for _ in 0..50 {
+                if !std::path::Path::new(&format!("/proc/{pid}")).exists() {
+                    alive = false;
+                    break;
+                }
+                std::thread::sleep(Duration::from_millis(10));
+            }
+        }
+        if alive {
+            // Direct signal to the recorded pid. `kill_group` uses a negative
+            // pgid, and this pid is the sleeper, not the group leader.
+            let _ = unsafe { kill(pid, 9) };
+        }
+        let _ = std::fs::remove_dir_all(&dir);
+        assert!(
+            elapsed < Duration::from_secs(3),
+            "drain hung for {elapsed:?}: {result:?}"
+        );
+        assert!(result.is_ok(), "{result:?}");
+        assert!(pid > 0, "helper did not record the grandchild pid");
+        assert!(!alive, "grandchild {pid} survived kill_group");
+    }
+
+    #[test]
+    fn setsid_grandchild_cannot_hold_the_drain_until_the_deadline() {
+        // `setsid` takes the sleeper out of the group, so `kill_group` cannot
+        // reach it and it keeps both pipes open. The drain must stop shortly
+        // after the leader exits, not at the 10 s deadline.
+        let dir = std::env::temp_dir().join(format!(
+            "aien-drive-setsid-{}-{}",
+            std::process::id(),
+            std::time::SystemTime::now()
+                .duration_since(std::time::UNIX_EPOCH)
+                .unwrap()
+                .as_nanos()
+        ));
+        std::fs::create_dir_all(&dir).unwrap();
+        let script = dir.join("escape.sh");
+        let pidfile = dir.join("pid");
+        std::fs::write(
+            &script,
+            // The leader waits until the sleeper has left the group and
+            // recorded its pid, so `kill_group` cannot win a race with it.
+            "#!/bin/sh\nsetsid sh -c 'echo $$ > \"$1\"; exec sleep 30' escape \"$1\" &\nwhile [ ! -s \"$1\" ]; do sleep 0.01; done\necho leader-done\nexit 0\n",
+        )
+        .unwrap();
+        std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();
+        let started = Instant::now();
+        let result = run_captured(
+            &script,
+            &[pidfile.display().to_string()],
+            &dir,
+            Duration::from_secs(10),
+            1024 * 1024,
+            "escape",
+        );
+        let elapsed = started.elapsed();
+        let pid: i32 = std::fs::read_to_string(&pidfile)
+            .unwrap_or_default()
+            .trim()
+            .parse()
+            .unwrap_or(0);
+        if pid > 0 {
+            let _ = unsafe { kill(pid, 9) };
+        }
+        let _ = std::fs::remove_dir_all(&dir);
+        assert!(pid > 0, "helper did not record the sleeper pid");
+        assert!(
+            elapsed < Duration::from_secs(3),
+            "escaped grandchild held the drain for {elapsed:?}: {result:?}"
+        );
+        let (code, stdout, _) = result.unwrap();
+        assert_eq!(code, 0);
+        assert!(stdout.contains("leader-done"), "{stdout:?}");
+    }
+}
diff --git a/crates/aien-drive/src/http.rs b/crates/aien-drive/src/http.rs
index d3d69bf0..cd5283e5 100644
--- a/crates/aien-drive/src/http.rs
+++ b/crates/aien-drive/src/http.rs
@@ -96,6 +96,15 @@ impl<R: BufRead> Read for Chunked<R> {
 
 /// POST a JSON body. `timeout` bounds each socket read and write.
 pub fn post_json(url: &str, body: &str, timeout: Duration) -> Result<Response, String> {
+    post_json_auth(url, body, timeout, None)
+}
+
+pub fn post_json_auth(
+    url: &str,
+    body: &str,
+    timeout: Duration,
+    bearer: Option<&str>,
+) -> Result<Response, String> {
     let (host, path) = split_url(url)?;
     let addrs = loopback_addrs(&host)?;
     let mut s = TcpStream::connect(&addrs[..]).map_err(|e| format!("connect {host}: {e}"))?;
@@ -103,8 +112,12 @@ pub fn post_json(url: &str, body: &str, timeout: Duration) -> Result<Response, S
         .map_err(|e| e.to_string())?;
     s.set_write_timeout(Some(timeout))
         .map_err(|e| e.to_string())?;
+    let auth = match bearer {
+        Some(token) if !token.is_empty() => format!("Authorization: Bearer {token}\r\n"),
+        _ => String::new(),
+    };
     let req = format!(
-        "POST {path} HTTP/1.0\r\nHost: {host}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
+        "POST {path} HTTP/1.0\r\nHost: {host}\r\nContent-Type: application/json\r\n{auth}Content-Length: {}\r\nConnection: close\r\n\r\n{body}",
         body.len()
     );
     s.write_all(req.as_bytes())
diff --git a/crates/aien-drive/src/lib.rs b/crates/aien-drive/src/lib.rs
index 2a78052d..0483389d 100644
--- a/crates/aien-drive/src/lib.rs
+++ b/crates/aien-drive/src/lib.rs
@@ -18,12 +18,20 @@
 //! Loops a chat model at an OpenAI-style streaming endpoint with a system
 //! prompt, extracts `<tool_call>` blocks from its reply, dispatches them, and
 //! feeds the results back as `<tool_response>` user messages.
+//!
+//! `run_command` execs one allowlisted program with an argument vector.
+//! A shell is used only when the operator sets `CommandPolicy::allow_shell`.
 
+pub mod command;
 pub mod http;
+mod paths;
+
+pub use command::CommandPolicy;
 
 use regex::Regex;
 use serde_json::{json, Value};
 use std::io::{BufRead, Write};
+use std::os::fd::AsRawFd;
 use std::process::{Command, Stdio};
 use std::time::{Duration, Instant};
 
@@ -38,15 +46,18 @@ You are an autonomous operator-builder running on NVIDIA DGX Spark Grace Blackwe
 Always be concise, precise, and lead with verified results.
 
 Available Tools:
-- run_command: {"command": "string", "cwd": "string"}
+- run_command: {"command": "program and arguments", "cwd": "directory inside the command root"}
+  One allowlisted program plus arguments. No shell syntax: no pipes, semicolons, substitution, or backticks.
+  The operator sets the allowlist and the command root. A shell is an operator opt-in and is off by default.
 - view_file: {"path": "string", "start_line": 1, "end_line": 100}
-- write_to_file: {"path": "string", "content": "string", "overwrite": true}
+- write_to_file: {"path": "string", "content": "string", "overwrite": false}
 - replace_file_content: {"path": "string", "target": "string", "replacement": "string"}
 - create_dir: {"path": "string", "purpose": "string"}
 - list_dir: {"path": "string"}
 - grep_search: {"query": "string", "path": "string"}
 - goal: {"action": "milestone_done|done", "id": "string", "milestone_id": 1}
 - cortex: {"action": "write", "name": "string", "content": "string", "kind": "lesson|discovery|procedure"}
+  Cortex writes only when the operator configured a token. The model cannot supply that token.
 
 MANDATORY RULES:
 1. ZERO EM DASHES AND EN DASHES: Use plain commas, periods, or standard hyphens (-).
@@ -70,9 +81,14 @@ pub struct Config {
     /// Cortex area the `cortex` tool writes to.
     pub cortex_space: String,
     pub request_timeout: Duration,
+    /// Operator policy for `run_command` and the file tools. The model cannot change this.
+    pub command: CommandPolicy,
+    /// Operator credential for the `cortex` tool. Empty means the tool does not run.
+    /// The model cannot set this.
+    pub cortex_token: Option<String>,
 }
 
-fn last_chars(s: &str, n: usize) -> String {
+pub(crate) fn last_chars(s: &str, n: usize) -> String {
     let c: Vec<char> = s.chars().collect();
     if c.len() > n {
         c[c.len() - n..].iter().collect()
@@ -85,26 +101,53 @@ fn first_chars(s: &str, n: usize) -> String {
     s.chars().take(n).collect()
 }
 
-/// Pull tool calls out of model text. Pattern 1: `<tool_call>{json}</tool_call>`.
-/// Pattern 2 (only if pattern 1 found nothing): bare `{name, arguments}` objects.
+/// Pull tool calls out of model text. Only `<tool_call>{json}</tool_call>`
+/// in the content channel counts. Bare `{name, arguments}` objects are not
+/// executed.
 pub fn extract_tool_calls(text: &str) -> Vec<Value> {
+    let text = strip_think_blocks(text);
     let p1 = Regex::new(r"(?s)<tool_call>\s*(\{.*?\})\s*</tool_call>").unwrap();
-    let calls: Vec<Value> = p1
-        .captures_iter(text)
+    p1.captures_iter(&text)
         .filter_map(|c| serde_json::from_str(c[1].trim()).ok())
-        .collect();
-    if !calls.is_empty() {
-        return calls;
-    }
-    let p2 = Regex::new(
-        r#"(?s)(\{\s*"?name"?\s*:\s*"[a-zA-Z0-9_]+"\s*,\s*"?arguments"?\s*:\s*\{.*?\}\s*\})"#,
-    )
-    .unwrap();
-    p2.captures_iter(text)
-        .filter_map(|c| serde_json::from_str(&c[1].replace('\'', "\"")).ok())
         .collect()
 }
 
+/// Drop model thinking before any tool-call parse. A tool call inside a
+/// thinking block is not the content channel. An opener that never closes
+/// (truncated reasoning) hides everything after it. A closer with no opener
+/// (a chat template that opened the block in the prompt) hides everything
+/// before it.
+fn strip_think_blocks(text: &str) -> String {
+    let tag = Regex::new(r"(?i)<(/?)think(?:ing)?>").unwrap();
+    let mut out = String::new();
+    let mut open: Option<usize> = None;
+    let mut kept_from = 0;
+    for m in tag.captures_iter(text) {
+        let whole = m.get(0).unwrap();
+        let closing = !m[1].is_empty();
+        match (open, closing) {
+            (None, false) => {
+                out.push_str(&text[kept_from..whole.start()]);
+                open = Some(whole.start());
+            }
+            (Some(_), true) => {
+                open = None;
+                kept_from = whole.end();
+            }
+            // An orphan closer: everything kept so far was reasoning.
+            (None, true) => {
+                out.clear();
+                kept_from = whole.end();
+            }
+            (Some(_), false) => {}
+        }
+    }
+    if open.is_none() {
+        out.push_str(&text[kept_from..]);
+    }
+    out
+}
+
 fn s_arg<'a>(a: &'a Value, k: &str, d: &'a str) -> &'a str {
     a.get(k).and_then(Value::as_str).unwrap_or(d)
 }
@@ -163,20 +206,14 @@ pub fn dispatch_tool(cfg: &Config, name: &str, args: &Value) -> Value {
 }
 
 fn dispatch_inner(cfg: &Config, name: &str, a: &Value) -> Result<Value, String> {
-    let io = |e: std::io::Error| e.to_string();
     Ok(match name {
-        "run_command" => {
-            let command = s_arg(a, "command", "");
-            let mut c = Command::new("sh");
-            c.arg("-c").arg(command).current_dir(s_arg(a, "cwd", "."));
-            let (code, o, e) = run_with_timeout(c, Duration::from_secs(120), command)?;
-            json!({"exit_code": code, "stdout": last_chars(&o, 4000), "stderr": last_chars(&e, 2000)})
-        }
+        "run_command" => command::execute(&cfg.command, a)?,
         "view_file" => {
             let path = s_arg(a, "path", "");
             let start = a.get("start_line").and_then(Value::as_i64).unwrap_or(1);
             let end = a.get("end_line").and_then(Value::as_i64).unwrap_or(100);
-            let text = String::from_utf8_lossy(&std::fs::read(path).map_err(io)?).into_owned();
+            let bytes = paths::read_bytes(&cfg.command.root, path)?;
+            let text = String::from_utf8_lossy(&bytes).into_owned();
             let lines: Vec<&str> = text.split_inclusive('\n').collect();
             let total = lines.len() as i64;
             let lo = (start - 1).max(0).min(total) as usize;
@@ -191,56 +228,59 @@ fn dispatch_inner(cfg: &Config, name: &str, a: &Value) -> Result<Value, String>
         "write_to_file" => {
             let path = s_arg(a, "path", "");
             let content = s_arg(a, "content", "");
-            let overwrite = a.get("overwrite").and_then(Value::as_bool).unwrap_or(true);
-            if std::path::Path::new(path).exists() && !overwrite {
-                json!({"error": format!("File {path} exists and overwrite=false")})
-            } else {
-                if let Some(dir) = std::path::Path::new(path).parent() {
-                    if !dir.as_os_str().is_empty() {
-                        std::fs::create_dir_all(dir).map_err(io)?;
-                    }
-                }
-                std::fs::write(path, content).map_err(io)?;
-                json!({"status": "ok", "bytes_written": content.len()})
-            }
+            let overwrite = a.get("overwrite").and_then(Value::as_bool).unwrap_or(false);
+            let n = paths::write_bytes(&cfg.command.root, path, content.as_bytes(), overwrite)?;
+            json!({"status": "ok", "bytes_written": n})
         }
         "replace_file_content" => {
             let path = s_arg(a, "path", "");
             let target = s_arg(a, "target", "");
-            let content = std::fs::read_to_string(path).map_err(io)?;
+            let bytes = paths::read_bytes(&cfg.command.root, path)?;
+            let content = String::from_utf8_lossy(&bytes).into_owned();
             if !content.contains(target) {
                 json!({"error": format!("Target string not found in {path}")})
             } else {
                 let new = content.replacen(target, s_arg(a, "replacement", ""), 1);
-                std::fs::write(path, new).map_err(io)?;
+                paths::write_bytes(&cfg.command.root, path, new.as_bytes(), true)?;
                 json!({"status": "ok", "replaced": true})
             }
         }
         "list_dir" => {
             let path = s_arg(a, "path", ".");
-            let mut names: Vec<String> = std::fs::read_dir(path)
-                .map_err(io)?
-                .filter_map(|e| e.ok().map(|e| e.file_name().to_string_lossy().into_owned()))
-                .collect();
-            names.sort();
-            names.truncate(100);
+            let names = paths::list_dir(&cfg.command.root, path)?;
             json!({"path": path, "entries": names})
         }
         "grep_search" => {
+            let query = s_arg(a, "query", "");
+            let path = s_arg(a, "path", ".");
+            let opened = paths::open_existing(&cfg.command.root, path)?;
+            let raw = opened.as_raw_fd();
+            unsafe {
+                let flags = libc::fcntl(raw, libc::F_GETFD);
+                if flags >= 0 {
+                    libc::fcntl(raw, libc::F_SETFD, flags & !libc::FD_CLOEXEC);
+                }
+            }
             let mut c = Command::new("grep");
-            c.args(["-rnI", s_arg(a, "query", ""), s_arg(a, "path", ".")]);
+            c.args(["-rnI", "--", query, &format!("/proc/self/fd/{raw}")]);
             let (_, o, _) = run_with_timeout(c, Duration::from_secs(30), "grep")?;
+            drop(opened);
             json!({"matches": first_chars(&o, 4000)})
         }
         "create_dir" => {
             let path = s_arg(a, "path", "");
-            std::fs::create_dir_all(path).map_err(io)?;
+            paths::create_dir(&cfg.command.root, path)?;
             json!({"status": "ok", "created": path})
         }
         "goal" => {
             json!({"status": "ok", "goal_action": s_arg(a, "action", ""), "milestone_done": true})
         }
         "cortex" => {
+            let Some(token) = cfg.cortex_token.as_deref().filter(|t| !t.is_empty()) else {
+                return Err(
+                    "cortex rejected: the operator has not configured a cortex token".into(),
+                );
+            };
             let ts = std::time::SystemTime::now()
                 .duration_since(std::time::UNIX_EPOCH)
                 .map(|d| d.as_secs())
@@ -256,7 +296,12 @@ fn dispatch_inner(cfg: &Config, name: &str, a: &Value) -> Result<Value, String>
                 }
             });
             let url = format!("{}/api/cortex/write", cfg.cortex_endpoint);
-            match http::post_json(&url, &payload.to_string(), Duration::from_secs(10)) {
+            match http::post_json_auth(
+                &url,
+                &payload.to_string(),
+                Duration::from_secs(10),
+                Some(token),
+            ) {
                 Ok(r) if r.status < 400 => json!({"status": "ok", "cortex_code": r.status}),
                 Ok(r) => json!({"warning": format!("Cortex write notice: HTTP {}", r.status)}),
                 Err(e) => json!({"warning": format!("Cortex write notice: {e}")}),
@@ -270,8 +315,9 @@ fn sanitize(s: &str) -> String {
     s.replace('\u{2014}', ", ").replace('\u{2013}', "-")
 }
 
-/// Read an SSE stream of chat-completion chunks. Returns the assistant text
-/// (falling back to the reasoning text if it holds a tool call and content is empty).
+/// Read an SSE stream of chat-completion chunks. Returns the assistant
+/// content channel only. Tool calls that appear in reasoning text are not
+/// a tool-call channel and are not returned for execution.
 pub fn read_stream(body: impl BufRead, out: &mut dyn Write) -> String {
     let (mut content, mut reasoning) = (String::new(), String::new());
     let mut in_reasoning = false;
@@ -309,11 +355,8 @@ pub fn read_stream(body: impl BufRead, out: &mut dyn Write) -> String {
         let _ = out.flush();
     }
     let _ = writeln!(out, "\n");
-    if content.is_empty() && reasoning.contains("<tool_call>") {
-        reasoning
-    } else {
-        content
-    }
+    let _ = reasoning;
+    content
 }
 
 fn call_model(cfg: &Config, messages: &[Value], out: &mut dyn Write) -> Result<String, String> {
diff --git a/crates/aien-drive/src/main.rs b/crates/aien-drive/src/main.rs
index 53c591ce..9efd8bb9 100644
--- a/crates/aien-drive/src/main.rs
+++ b/crates/aien-drive/src/main.rs
@@ -57,6 +57,10 @@ fn main() {
         cortex_endpoint: env("CORTEX_ENDPOINT", DEFAULT_CORTEX),
         cortex_space: env("AIEN_CORTEX_SPACE", "aien-sources"),
         request_timeout: Duration::from_secs(180),
+        command: CommandPolicy::from_operator_env(),
+        cortex_token: std::env::var("AIEN_CORTEX_TOKEN")
+            .ok()
+            .filter(|v| !v.is_empty()),
     };
     match run_directive(&cfg, &a.directive.join(" "), a.max_turns) {
         Ok(true) => {}
diff --git a/crates/aien-drive/src/paths.rs b/crates/aien-drive/src/paths.rs
new file mode 100644
index 00000000..e33f077e
--- /dev/null
+++ b/crates/aien-drive/src/paths.rs
@@ -0,0 +1,414 @@
+// SPDX-License-Identifier: Apache-2.0
+// Copyright 2026 Drake Stapleton (AIEN / aien-dev)
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+//! File tools stay inside the command root.
+//!
+//! Opens use `openat2` with `RESOLVE_BENEATH` and `RESOLVE_NO_SYMLINKS`.
+//! A symlink is refused, which also blocks a write through an in-root symlink
+//! into `.git`. If `openat2` is unavailable, components are opened with
+//! `openat` and `O_NOFOLLOW` from the root directory fd. A symlink, including
+//! a dangling one, is refused. The fallback does not create through it.
+
+use std::fs::File;
+use std::io::{Read, Write};
+use std::os::fd::{AsRawFd, FromRawFd, OwnedFd};
+use std::path::{Component, Path, PathBuf};
+
+const RESOLVE_BENEATH: u64 = 0x08;
+/// Linux `RESOLVE_NO_SYMLINKS` is `0x04`. This is not `RESOLVE_NO_MAGICLINKS`
+/// (`0x02`). Keeping `0x04` refuses every symlink, including one whose target
+/// is inside the root.
+const RESOLVE_NO_SYMLINKS: u64 = 0x04;
+
+#[repr(C)]
+struct OpenHow {
+    flags: u64,
+    mode: u64,
+    resolve: u64,
+}
+
+const SHELL_RC: &[&str] = &[
+    ".bashrc",
+    ".bash_profile",
+    ".bash_login",
+    ".profile",
+    ".zshrc",
+    ".zshenv",
+    ".zprofile",
+    ".zlogin",
+    ".kshrc",
+    ".cshrc",
+    ".tcshrc",
+    ".shrc",
+];
+
+pub(crate) fn read_bytes(root: &Path, user: &str) -> Result<Vec<u8>, String> {
+    let rel = relative_under_root(root, user)?;
+    let root_fd = open_root(root)?;
+    let fd = open_rel(&root_fd, &rel, libc::O_RDONLY, 0)?;
+    let mut file = File::from(fd);
+    let mut buf = Vec::new();
+    file.read_to_end(&mut buf).map_err(|e| e.to_string())?;
+    Ok(buf)
+}
+
+pub(crate) fn write_bytes(
+    root: &Path,
+    user: &str,
+    bytes: &[u8],
+    overwrite: bool,
+) -> Result<usize, String> {
+    let rel = relative_under_root(root, user)?;
+    refuse_sensitive_write(&rel)?;
+    let root_fd = open_root(root)?;
+    ensure_parents(&root_fd, &rel)?;
+    let flags = if overwrite {
+        libc::O_RDWR | libc::O_CREAT
+    } else {
+        libc::O_RDWR | libc::O_CREAT | libc::O_EXCL
+    };
+    let fd = open_rel(&root_fd, &rel, flags, 0o644).map_err(|e| {
+        if e.contains("EEXIST") || e.contains("File exists") {
+            format!("File {user} exists and overwrite=false")
+        } else {
+            e
+        }
+    })?;
+    // A second name for the inode may sit anywhere: a refused path inside the
+    // root (`.git/hooks/pre-commit`) or a file outside it. The jail cannot
+    // see the other names, so a multiply linked file is not written.
+    if link_count(fd.as_raw_fd()).is_none_or(|n| n > 1) {
+        return Err(format!(
+            "refusing write to {user}: the file has more than one hard link"
+        ));
+    }
+    if overwrite {
+        let rc = unsafe { libc::ftruncate(fd.as_raw_fd(), 0) };
+        if rc < 0 {
+            return Err(std::io::Error::last_os_error().to_string());
+        }
+    }
+    let mut file = File::from(fd);
+    file.write_all(bytes).map_err(|e| e.to_string())?;
+    Ok(bytes.len())
+}
+
+pub(crate) fn list_dir(root: &Path, user: &str) -> Result<Vec<String>, String> {
+    let rel = relative_under_root(root, user)?;
+    let root_fd = open_root(root)?;
+    let fd = open_rel(&root_fd, &rel, libc::O_RDONLY | libc::O_DIRECTORY, 0)?;
+    let proc = format!("/proc/self/fd/{}", fd.as_raw_fd());
+    let mut names: Vec<String> = std::fs::read_dir(&proc)
+        .map_err(|e| e.to_string())?
+        .filter_map(|e| e.ok().map(|e| e.file_name().to_string_lossy().into_owned()))
+        .collect();
+    names.sort();
+    names.truncate(100);
+    Ok(names)
+}
+
+pub(crate) fn create_dir(root: &Path, user: &str) -> Result<(), String> {
+    let rel = relative_under_root(root, user)?;
+    if rel.as_os_str().is_empty() {
+        return Ok(());
+    }
+    refuse_sensitive_write(&rel)?;
+    let root_fd = open_root(root)?;
+    let mut acc = PathBuf::new();
+    for c in rel.components() {
+        acc.push(c);
+        refuse_sensitive_write(&acc)?;
+        match open_rel(&root_fd, &acc, libc::O_RDONLY | libc::O_DIRECTORY, 0) {
+            Ok(_) => {}
+            Err(_) => {
+                mkdir_rel(&root_fd, &acc)?;
+            }
+        }
+    }
+    Ok(())
+}
+
+/// Existing object, already opened beneath the root. Callers pass this fd
+/// to child processes instead of a path that would be opened again.
+pub(crate) fn open_existing(root: &Path, user: &str) -> Result<OwnedFd, String> {
+    let rel = relative_under_root(root, user)?;
+    let root_fd = open_root(root)?;
+    open_rel(&root_fd, &rel, libc::O_RDONLY, 0)
+}
+
+fn refuse_sensitive_write(rel: &Path) -> Result<(), String> {
+    let mut comps = Vec::new();
+    for c in rel.components() {
+        if let Component::Normal(s) = c {
+            comps.push(s.to_string_lossy().to_ascii_lowercase());
+        }
+    }
+    if comps.iter().any(|c| c == ".git" || c == ".ssh") {
+        return Err("refusing write under a protected directory".into());
+    }
+    if comps.windows(2).any(|w| {
+        (w[0] == ".github" && w[1] == "workflows") || (w[0] == ".cargo" && w[1] == "config.toml")
+    }) {
+        return Err("refusing write under a protected directory".into());
+    }
+    if let Some(name) = comps.last() {
+        if name == "build.rs"
+            || name == "makefile"
+            || name == ".gitattributes"
+            || name == ".envrc"
+            || SHELL_RC.iter().any(|rc| name == &rc.to_ascii_lowercase())
+        {
+            return Err("refusing write to a protected file".into());
+        }
+    }
+    Ok(())
+}
+
+fn relative_under_root(root: &Path, user: &str) -> Result<PathBuf, String> {
+    if user.is_empty() {
+        return Err("path is empty".into());
+    }
+    let root = root
+        .canonicalize()
+        .map_err(|e| format!("command root '{}' is not available: {e}", root.display()))?;
+    let raw = Path::new(user);
+    let joined = if raw.is_absolute() {
+        raw.to_path_buf()
+    } else {
+        root.join(raw)
+    };
+    let lexical = normalize_lexical(&joined);
+    if !lexical.starts_with(&root) {
+        return Err(format!("path '{user}' is outside the command root"));
+    }
+    Ok(lexical
+        .strip_prefix(&root)
+        .map(Path::to_path_buf)
+        .unwrap_or_default())
+}
+
+fn normalize_lexical(path: &Path) -> PathBuf {
+    let mut out = PathBuf::new();
+    for c in path.components() {
+        match c {
+            Component::CurDir => {}
+            Component::ParentDir => {
+                out.pop();
+            }
+            other => out.push(other.as_os_str()),
+        }
+    }
+    out
+}
+
+fn open_root(root: &Path) -> Result<OwnedFd, String> {
+    let c = std::ffi::CString::new(
+        root.canonicalize()
+            .map_err(|e| e.to_string())?
+            .as_os_str()
+            .as_encoded_bytes(),
+    )
+    .map_err(|e| e.to_string())?;
+    let fd = unsafe {
+        libc::open(
+            c.as_ptr(),
+            libc::O_RDONLY | libc::O_DIRECTORY | libc::O_CLOEXEC,
+        )
+    };
+    if fd < 0 {
+        return Err(std::io::Error::last_os_error().to_string());
+    }
+    Ok(unsafe { OwnedFd::from_raw_fd(fd) })
+}
+
+fn open_rel(root: &OwnedFd, rel: &Path, flags: i32, mode: u64) -> Result<OwnedFd, String> {
+    if rel.as_os_str().is_empty() {
+        let n = unsafe { libc::fcntl(root.as_raw_fd(), libc::F_DUPFD_CLOEXEC, 0) };
+        if n < 0 {
+            return Err(std::io::Error::last_os_error().to_string());
+        }
+        return Ok(unsafe { OwnedFd::from_raw_fd(n) });
+    }
+    let bytes = rel.as_os_str().as_encoded_bytes();
+    let c = std::ffi::CString::new(bytes).map_err(|e| e.to_string())?;
+    let how = OpenHow {
+        flags: (flags | libc::O_CLOEXEC) as u64,
+        mode,
+        resolve: RESOLVE_BENEATH | RESOLVE_NO_SYMLINKS,
+    };
+    if force_enosys() {
+        return open_rel_fallback(root, rel, flags, mode);
+    }
+    let fd = unsafe {
+        libc::syscall(
+            libc::SYS_openat2,
+            root.as_raw_fd(),
+            c.as_ptr(),
+            &how as *const OpenHow,
+            std::mem::size_of::<OpenHow>(),
+        )
+    };
+    if fd >= 0 {
+        return Ok(unsafe { OwnedFd::from_raw_fd(fd as i32) });
+    }
+    let err = std::io::Error::last_os_error();
+    if err.raw_os_error() == Some(libc::ENOSYS) {
+        return open_rel_fallback(root, rel, flags, mode);
+    }
+    if err.raw_os_error() == Some(libc::ELOOP) {
+        return Err("refusing a symlink".into());
+    }
+    if err.raw_os_error() == Some(libc::EXDEV) {
+        return Err("path leaves the command root".into());
+    }
+    Err(err.to_string())
+}
+
+fn open_rel_fallback(root: &OwnedFd, rel: &Path, flags: i32, mode: u64) -> Result<OwnedFd, String> {
+    let mut current = dup_fd(root)?;
+    let comps: Vec<_> = rel.components().collect();
+    if comps.is_empty() {
+        return Ok(current);
+    }
+    for (i, comp) in comps.iter().enumerate() {
+        let Component::Normal(name) = comp else {
+            return Err("path leaves the command root".into());
+        };
+        let last = i + 1 == comps.len();
+        let step_flags = if last {
+            flags | libc::O_NOFOLLOW
+        } else {
+            libc::O_RDONLY | libc::O_DIRECTORY | libc::O_NOFOLLOW
+        };
+        let step_mode = if last { mode } else { 0 };
+        let next = open_at(&current, name, step_flags, step_mode)?;
+        if last {
+            return Ok(next);
+        }
+        current = next;
+    }
+    Ok(current)
+}
+
+fn open_at(
+    dir: &OwnedFd,
+    name: &std::ffi::OsStr,
+    flags: i32,
+    mode: u64,
+) -> Result<OwnedFd, String> {
+    let c = std::ffi::CString::new(name.as_encoded_bytes()).map_err(|e| e.to_string())?;
+    let fd = unsafe {
+        libc::openat(
+            dir.as_raw_fd(),
+            c.as_ptr(),
+            flags | libc::O_CLOEXEC,
+            mode as libc::mode_t,
+        )
+    };
+    if fd >= 0 {
+        return Ok(unsafe { OwnedFd::from_raw_fd(fd) });
+    }
+    let err = std::io::Error::last_os_error();
+    if err.raw_os_error() == Some(libc::ELOOP) {
+        return Err("refusing a symlink".into());
+    }
+    Err(err.to_string())
+}
+
+fn dup_fd(fd: &OwnedFd) -> Result<OwnedFd, String> {
+    let n = unsafe { libc::fcntl(fd.as_raw_fd(), libc::F_DUPFD_CLOEXEC, 0) };
+    if n < 0 {
+        return Err(std::io::Error::last_os_error().to_string());
+    }
+    Ok(unsafe { OwnedFd::from_raw_fd(n) })
+}
+
+fn link_count(fd: i32) -> Option<u64> {
+    let mut st: libc::stat = unsafe { std::mem::zeroed() };
+    if unsafe { libc::fstat(fd, &mut st) } < 0 {
+        return None;
+    }
+    Some(st.st_nlink as u64)
+}
+
+fn force_enosys() -> bool {
+    ENOSYS_FOR_TEST.load(std::sync::atomic::Ordering::Relaxed)
+}
+
+static ENOSYS_FOR_TEST: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
+
+#[cfg(test)]
+pub(crate) fn set_force_enosys(value: bool) {
+    ENOSYS_FOR_TEST.store(value, std::sync::atomic::Ordering::Relaxed);
+}
+
+fn ensure_parents(root: &OwnedFd, rel: &Path) -> Result<(), String> {
+    let mut acc = PathBuf::new();
+    let comps: Vec<_> = rel.components().collect();
+    if comps.len() <= 1 {
+        return Ok(());
+    }
+    for c in &comps[..comps.len() - 1] {
+        acc.push(c);
+        match open_rel(root, &acc, libc::O_RDONLY | libc::O_DIRECTORY, 0) {
+            Ok(_) => {}
+            Err(_) => mkdir_rel(root, &acc)?,
+        }
+    }
+    Ok(())
+}
+
+fn mkdir_rel(root: &OwnedFd, rel: &Path) -> Result<(), String> {
+    let parent = rel.parent().unwrap_or(Path::new(""));
+    let name = rel
+        .file_name()
+        .ok_or_else(|| "directory name missing".to_string())?;
+    let parent_fd = open_rel(root, parent, libc::O_RDONLY | libc::O_DIRECTORY, 0)?;
+    let c = std::ffi::CString::new(name.as_encoded_bytes()).map_err(|e| e.to_string())?;
+    let rc = unsafe { libc::mkdirat(parent_fd.as_raw_fd(), c.as_ptr(), 0o755) };
+    if rc < 0 {
+        let err = std::io::Error::last_os_error();
+        if err.kind() != std::io::ErrorKind::AlreadyExists {
+            return Err(err.to_string());
+        }
+    }
+    Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use std::os::unix::fs::symlink;
+
+    #[test]
+    fn enosys_fallback_does_not_create_through_a_dangling_symlink() {
+        let dir = std::env::temp_dir().join(format!("aien-drive-enosys-{}", std::process::id()));
+        let _ = std::fs::remove_dir_all(&dir);
+        std::fs::create_dir_all(&dir).unwrap();
+        let outside = dir
+            .parent()
+            .unwrap()
+            .join(format!("aien-drive-dangling-{}", std::process::id()));
+        let _ = std::fs::remove_file(&outside);
+        symlink(&outside, dir.join("link")).unwrap();
+        set_force_enosys(true);
+        let result = write_bytes(&dir, "link", b"pwned", true);
+        set_force_enosys(false);
+        assert!(result.is_err(), "{result:?}");
+        assert!(!outside.exists(), "fallback created the symlink target");
+        let _ = std::fs::remove_dir_all(&dir);
+        let _ = std::fs::remove_file(&outside);
+    }
+}
diff --git a/crates/aien-drive/tests/command_confinement.rs b/crates/aien-drive/tests/command_confinement.rs
new file mode 100644
index 00000000..bece4f3f
--- /dev/null
+++ b/crates/aien-drive/tests/command_confinement.rs
@@ -0,0 +1,626 @@
+// SPDX-License-Identifier: Apache-2.0
+// Copyright 2026 Drake Stapleton (AIEN / aien-dev)
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+//! `run_command` must exec one allowlisted program. The model does not get a shell.
+
+use aien_drive::{CommandPolicy, Config};
+use serde_json::{json, Value};
+use std::path::{Path, PathBuf};
+use std::sync::atomic::{AtomicU64, Ordering};
+use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
+
+static TMP_SEQ: AtomicU64 = AtomicU64::new(0);
+
+struct Tmp(PathBuf);
+
+impl Tmp {
+    fn new() -> Self {
+        let n = TMP_SEQ.fetch_add(1, Ordering::Relaxed);
+        let nanos = SystemTime::now()
+            .duration_since(UNIX_EPOCH)
+            .unwrap()
+            .as_nanos();
+        let p =
+            std::env::temp_dir().join(format!("aien-drive-cmd-{}-{nanos}-{n}", std::process::id()));
+        std::fs::create_dir_all(&p).unwrap();
+        Self(p)
+    }
+
+    fn path(&self) -> &Path {
+        &self.0
+    }
+}
+
+impl Drop for Tmp {
+    fn drop(&mut self) {
+        let _ = std::fs::remove_dir_all(&self.0);
+    }
+}
+
+fn policy_at(root: &Path) -> CommandPolicy {
+    CommandPolicy {
+        root: root.to_path_buf(),
+        ..CommandPolicy::default()
+    }
+}
+
+fn cfg(policy: CommandPolicy) -> Config {
+    Config {
+        endpoint: String::new(),
+        model: String::new(),
+        cortex_endpoint: String::new(),
+        cortex_space: "aien-sources".into(),
+        request_timeout: Duration::from_secs(5),
+        command: policy,
+        cortex_token: None,
+    }
+}
+
+fn run(policy: CommandPolicy, args: Value) -> Value {
+    aien_drive::dispatch_tool(&cfg(policy), "run_command", &args)
+}
+
+fn cwd_args(root: &Path, command: &str) -> Value {
+    json!({"command": command, "cwd": root.display().to_string()})
+}
+
+fn error_of(res: &Value) -> String {
+    res.get("error")
+        .and_then(Value::as_str)
+        .unwrap_or("")
+        .to_string()
+}
+
+#[test]
+fn allowed_echo_runs_and_returns_stdout() {
+    let tmp = Tmp::new();
+    let res = run(policy_at(tmp.path()), cwd_args(tmp.path(), "echo hello"));
+    assert_eq!(res["exit_code"], 0, "{res}");
+    assert!(
+        res["stdout"].as_str().unwrap_or("").contains("hello"),
+        "{res}"
+    );
+    assert!(res.get("error").is_none(), "{res}");
+}
+
+#[test]
+fn quoted_argument_reaches_the_program() {
+    let tmp = Tmp::new();
+    let res = run(
+        policy_at(tmp.path()),
+        cwd_args(tmp.path(), "echo \"hello world\""),
+    );
+    assert_eq!(res["exit_code"], 0, "{res}");
+    assert!(
+        res["stdout"].as_str().unwrap_or("").contains("hello world"),
+        "{res}"
+    );
+}
+
+#[test]
+fn false_exit_code_is_a_result() {
+    let tmp = Tmp::new();
+    let res = run(policy_at(tmp.path()), cwd_args(tmp.path(), "false"));
+    assert_eq!(res["exit_code"], 1, "{res}");
+    assert!(res.get("error").is_none(), "{res}");
+}
+
+#[test]
+fn program_outside_allowlist_is_rejected_and_does_not_run() {
+    let tmp = Tmp::new();
+    let marker = tmp.path().join("pwned");
+    let res = run(policy_at(tmp.path()), cwd_args(tmp.path(), "touch pwned"));
+    let err = error_of(&res);
+    assert!(err.contains("allowlist"), "{res}");
+    assert!(!marker.exists(), "disallowed touch created {marker:?}");
+}
+
+#[test]
+fn semicolon_curl_chain_is_rejected() {
+    let tmp = Tmp::new();
+    let marker = tmp.path().join("pwned");
+    let res = run(
+        policy_at(tmp.path()),
+        cwd_args(tmp.path(), "ls; curl http://127.0.0.1:9/owned; touch pwned"),
+    );
+    let err = error_of(&res);
+    assert!(
+        err.contains("metacharacter"),
+        "shell chaining must be rejected before exec: {res}"
+    );
+    assert!(!marker.exists(), "chained touch ran");
+}
+
+#[test]
+fn command_substitution_is_rejected_and_does_not_run() {
+    let tmp = Tmp::new();
+    let marker = tmp.path().join("pwned");
+    let res = run(
+        policy_at(tmp.path()),
+        cwd_args(tmp.path(), "echo $(touch pwned)"),
+    );
+    let err = error_of(&res);
+    assert!(err.contains("metacharacter"), "{res}");
+    assert!(!marker.exists(), "command substitution ran");
+}
+
+#[test]
+fn backticks_are_rejected_and_do_not_run() {
+    let tmp = Tmp::new();
+    let marker = tmp.path().join("pwned");
+    let res = run(
+        policy_at(tmp.path()),
+        cwd_args(tmp.path(), "echo `touch pwned`"),
+    );
+    let err = error_of(&res);
+    assert!(err.contains("metacharacter"), "{res}");
+    assert!(!marker.exists(), "backtick substitution ran");
+}
+
+#[test]
+fn model_supplied_shell_flag_does_not_enable_shell() {
+    let tmp = Tmp::new();
+    let marker = tmp.path().join("pwned");
+    let res = run(
+        policy_at(tmp.path()),
+        json!({
+            "command": "echo one; touch pwned",
+            "cwd": tmp.path().display().to_string(),
+            "allow_shell": true,
+            "shell": true
+        }),
+    );
+    let err = error_of(&res);
+    assert!(err.contains("metacharacter"), "{res}");
+    assert!(!marker.exists(), "model flag enabled a shell");
+}
+
+#[test]
+fn program_path_is_rejected() {
+    let tmp = Tmp::new();
+    let res = run(
+        policy_at(tmp.path()),
+        cwd_args(tmp.path(), "/bin/echo hello"),
+    );
+    let err = error_of(&res);
+    assert!(
+        err.contains("bare") || err.contains("path"),
+        "a path must not select the binary: {res}"
+    );
+}
+
+#[test]
+fn shell_wrapper_on_the_allowlist_is_still_rejected() {
+    let tmp = Tmp::new();
+    let marker = tmp.path().join("pwned");
+    let policy = CommandPolicy {
+        allowlist: vec!["bash".into(), "echo".into()],
+        ..policy_at(tmp.path())
+    };
+    let res = run(policy, cwd_args(tmp.path(), "bash -c \"touch pwned\""));
+    let err = error_of(&res);
+    assert!(
+        err.contains("allow_shell"),
+        "a shell wrapper must stay behind the operator opt-in: {res}"
+    );
+    assert!(!marker.exists(), "bash -c ran from the allowlist");
+}
+
+#[test]
+fn timeout_fires() {
+    let tmp = Tmp::new();
+    let policy = CommandPolicy {
+        allowlist: vec!["sleep".into()],
+        timeout: Duration::from_millis(200),
+        ..policy_at(tmp.path())
+    };
+    let started = Instant::now();
+    let res = run(policy, cwd_args(tmp.path(), "sleep 2"));
+    let elapsed = started.elapsed();
+    let err = error_of(&res);
+    assert!(err.contains("timed out"), "{res} after {elapsed:?}");
+    assert!(
+        elapsed < Duration::from_millis(1500),
+        "sleep 2 was not killed: {elapsed:?} {res}"
+    );
+}
+
+#[test]
+fn output_capture_cap_fires() {
+    let tmp = Tmp::new();
+    let policy = CommandPolicy {
+        max_capture: 128,
+        max_stdout: 128,
+        ..policy_at(tmp.path())
+    };
+    let blob = "x".repeat(20_000);
+    let started = Instant::now();
+    let res = run(policy, cwd_args(tmp.path(), &format!("printf %s {blob}")));
+    assert!(
+        started.elapsed() < Duration::from_secs(5),
+        "capture cap hung"
+    );
+    let err = error_of(&res);
+    assert!(err.contains("capture cap"), "output must be capped: {res}");
+}
+
+#[test]
+fn working_directory_outside_root_is_rejected() {
+    let tmp = Tmp::new();
+    let parent = tmp.path().parent().unwrap();
+    let res = run(
+        policy_at(tmp.path()),
+        json!({"command": "echo hello", "cwd": parent.display().to_string()}),
+    );
+    let err = error_of(&res);
+    assert!(err.contains("outside"), "{res}");
+}
+
+#[test]
+fn working_directory_symlink_escape_is_rejected() {
+    let tmp = Tmp::new();
+    let link = tmp.path().join("escape");
+    std::os::unix::fs::symlink("/tmp", &link).unwrap();
+    let res = run(
+        policy_at(tmp.path()),
+        json!({"command": "echo hello", "cwd": link.display().to_string()}),
+    );
+    let err = error_of(&res);
+    assert!(err.contains("outside"), "{res}");
+}
+
+#[test]
+fn relative_cwd_stays_inside_root() {
+    let tmp = Tmp::new();
+    let sub = tmp.path().join("sub");
+    std::fs::create_dir(&sub).unwrap();
+    let res = run(
+        policy_at(tmp.path()),
+        json!({"command": "pwd", "cwd": "sub"}),
+    );
+    assert_eq!(res["exit_code"], 0, "{res}");
+    let stdout = res["stdout"].as_str().unwrap_or("");
+    assert!(stdout.contains("sub"), "{res}");
+    let canon = sub.canonicalize().unwrap();
+    assert!(
+        stdout.contains(canon.to_str().unwrap()),
+        "pwd left the command root: {res}"
+    );
+}
+
+#[test]
+fn shell_opt_in_runs_a_pipeline_and_the_default_does_not() {
+    let tmp = Tmp::new();
+    let off = run(
+        policy_at(tmp.path()),
+        cwd_args(tmp.path(), "echo one; echo two"),
+    );
+    assert!(
+        error_of(&off).contains("metacharacter"),
+        "default must not keep sh -c: {off}"
+    );
+
+    let on_policy = CommandPolicy {
+        allow_shell: true,
+        ..policy_at(tmp.path())
+    };
+    let on = run(on_policy, cwd_args(tmp.path(), "echo one; echo two"));
+    assert_eq!(on["exit_code"], 0, "{on}");
+    let stdout = on["stdout"].as_str().unwrap_or("");
+    assert!(stdout.contains("one") && stdout.contains("two"), "{on}");
+}
+
+#[test]
+fn environment_is_not_inherited() {
+    let tmp = Tmp::new();
+    let key = "AIEN_ENV_PROBE_SECRET";
+    let secret = "probe-value-not-for-the-child";
+    std::env::set_var(key, secret);
+    let policy = CommandPolicy {
+        allowlist: vec!["printenv".into()],
+        ..policy_at(tmp.path())
+    };
+    let res = run(policy, cwd_args(tmp.path(), &format!("printenv {key}")));
+    std::env::remove_var(key);
+    let rendered = res.to_string();
+    assert!(!rendered.contains(secret), "child inherited {key}: {res}");
+}
+
+#[test]
+fn shell_opt_in_also_drops_the_environment_and_stays_in_root() {
+    let tmp = Tmp::new();
+    let secret = "probe-value-not-for-the-shell-child";
+    std::env::set_var("AIEN_ENV_PROBE_SECRET", secret);
+    let policy = CommandPolicy {
+        allow_shell: true,
+        ..policy_at(tmp.path())
+    };
+    let res = run(
+        policy.clone(),
+        cwd_args(tmp.path(), "printenv AIEN_ENV_PROBE_SECRET"),
+    );
+    std::env::remove_var("AIEN_ENV_PROBE_SECRET");
+    assert!(!res.to_string().contains(secret), "{res}");
+
+    let parent = tmp.path().parent().unwrap();
+    let escaped = run(
+        policy,
+        json!({"command": "echo pwned", "cwd": parent.display().to_string()}),
+    );
+    assert!(error_of(&escaped).contains("outside"), "{escaped}");
+}
+
+#[test]
+fn default_policy_keeps_the_shell_off() {
+    let policy = CommandPolicy::default();
+    assert!(!policy.allow_shell);
+    assert_eq!(policy.timeout, Duration::from_secs(120));
+    assert_eq!(
+        policy.allowlist,
+        vec!["echo", "printf", "true", "false", "pwd"]
+    );
+    assert!(policy.max_capture >= policy.max_stdout);
+    assert!(
+        policy.root.as_os_str().is_empty(),
+        "the command root must not default to the process cwd"
+    );
+}
+
+#[test]
+fn operator_values_do_not_enable_the_shell_unless_the_flag_is_one() {
+    let off = CommandPolicy::from_operator_values(Some("echo, ls"), Some("true"), None, Some("0"));
+    assert!(!off.allow_shell);
+    assert_eq!(off.allowlist, vec!["echo", "ls"]);
+    assert_eq!(off.timeout, Duration::from_secs(120));
+
+    let on = CommandPolicy::from_operator_values(
+        Some(""),
+        Some("1"),
+        Some("/tmp/aien-drive-root"),
+        Some("9"),
+    );
+    assert!(on.allow_shell);
+    assert!(on.allowlist.is_empty());
+    assert_eq!(on.root, PathBuf::from("/tmp/aien-drive-root"));
+    assert_eq!(on.timeout, Duration::from_secs(9));
+}
+
+#[test]
+fn operator_allowlist_drops_shells_and_exec_wrappers() {
+    let policy = CommandPolicy::from_operator_values(
+        Some("echo, nice, timeout, env, xargs, nohup, setsid, stdbuf, bash"),
+        None,
+        None,
+        None,
+    );
+    assert_eq!(policy.allowlist, vec!["echo".to_string()]);
+}
+
+#[test]
+fn allowlisted_exec_wrapper_cannot_launch_a_shell() {
+    let tmp = Tmp::new();
+    let marker = tmp.path().join("pwned");
+    for (program, command) in [
+        ("nice", "nice bash -c \"touch pwned\""),
+        ("timeout", "timeout 9 sh -c \"touch pwned\""),
+        ("env", "env bash -c \"touch pwned\""),
+        ("xargs", "xargs -0 echo"),
+        ("nohup", "nohup echo hi"),
+        ("setsid", "setsid echo hi"),
+        ("stdbuf", "stdbuf -o0 echo hi"),
+    ] {
+        let policy = CommandPolicy {
+            allowlist: vec![program.into(), "echo".into()],
+            ..policy_at(tmp.path())
+        };
+        let res = run(policy, cwd_args(tmp.path(), command));
+        let err = error_of(&res);
+        assert!(
+            err.contains("exec wrapper") || err.contains("allow_shell"),
+            "{program}: {res}"
+        );
+        assert!(!marker.exists(), "{program} created {marker:?}");
+    }
+}
+
+#[test]
+fn allowlisted_interpreter_eval_and_git_overrides_are_rejected() {
+    let tmp = Tmp::new();
+    let cases = [
+        ("perl", "perl -e id", "eval"),
+        ("python", "python -c id", "eval"),
+        ("python3", "python3 -c id", "eval"),
+        ("ruby", "ruby -e id", "eval"),
+        ("node", "node -e id", "eval"),
+        ("node", "node --eval id", "eval"),
+        ("git", "git -c core.fsmonitor=id status", "git"),
+        ("git", "git --exec-path /tmp status", "git"),
+    ];
+    for (program, command, needle) in cases {
+        let policy = CommandPolicy {
+            allowlist: vec![program.into()],
+            ..policy_at(tmp.path())
+        };
+        let res = run(policy, cwd_args(tmp.path(), command));
+        let err = error_of(&res);
+        assert!(err.contains(needle), "{command}: {res}");
+    }
+}
+
+#[test]
+fn allowlisted_git_status_is_not_an_override() {
+    let tmp = Tmp::new();
+    let policy = CommandPolicy {
+        allowlist: vec!["git".into()],
+        ..policy_at(tmp.path())
+    };
+    let res = run(policy, cwd_args(tmp.path(), "git status"));
+    assert!(
+        res.get("error").is_none(),
+        "plain git status must not be treated as a config override: {res}"
+    );
+    assert!(res.get("exit_code").is_some(), "{res}");
+}
+
+#[test]
+fn clustered_and_versioned_interpreter_eval_flags_are_rejected() {
+    let tmp = Tmp::new();
+    let cases = [
+        ("perl", "perl -le print"),
+        ("perl", "perl -wE print"),
+        ("perl", "perl -I. -e print"),
+        ("python3", "python3 -Bc print"),
+        ("python3", "python3 -Ic print"),
+        ("python3.12", "python3.12 -c print"),
+        ("ruby", "ruby -we print"),
+        ("node", "node -pe 1"),
+        ("node", "node --print=1"),
+        ("node", "node --eval=1"),
+        ("php", "php -r phpinfo"),
+        ("php8.2", "php8.2 -B phpinfo"),
+        ("luajit", "luajit -e print"),
+        ("gawk", "gawk --source BEGIN"),
+    ];
+    for (program, command) in cases {
+        let policy = CommandPolicy {
+            allowlist: vec![program.into()],
+            ..policy_at(tmp.path())
+        };
+        let res = run(policy, cwd_args(tmp.path(), command));
+        assert!(error_of(&res).contains("eval"), "{command}: {res}");
+    }
+}
+
+#[test]
+fn interpreter_option_values_are_not_eval_flags() {
+    // `-X` consumes the rest of the cluster, so the `c` in `pycache_prefix`
+    // is a value, not `-c`. The program runs.
+    let tmp = Tmp::new();
+    let policy = CommandPolicy {
+        allowlist: vec!["python3".into()],
+        ..policy_at(tmp.path())
+    };
+    let res = run(
+        policy,
+        cwd_args(tmp.path(), "python3 -Xpycache_prefix=pc -V"),
+    );
+    assert_eq!(res["exit_code"], 0, "{res}");
+    assert!(
+        res["stdout"].as_str().unwrap_or("").contains("Python"),
+        "{res}"
+    );
+}
+
+#[test]
+fn git_operands_that_contain_core_are_not_overrides() {
+    let tmp = Tmp::new();
+    for command in [
+        "git log -- core.rs",
+        "git status score.txt",
+        "git config --get core.editor",
+        "git config get core.editor",
+        "git config --list",
+        "git log -c",
+    ] {
+        let policy = CommandPolicy {
+            allowlist: vec!["git".into()],
+            ..policy_at(tmp.path())
+        };
+        let res = run(policy, cwd_args(tmp.path(), command));
+        assert!(res.get("error").is_none(), "{command}: {res}");
+        assert!(res.get("exit_code").is_some(), "{command}: {res}");
+    }
+}
+
+#[test]
+fn git_config_writes_and_command_options_are_rejected() {
+    let tmp = Tmp::new();
+    for command in [
+        "git config core.fsmonitor id",
+        "git config diff.external id",
+        "git config set core.pager id",
+        "git config --add alias.x id",
+        "git config --get core.pager --add x",
+        "git -ccore.pager=id log",
+        "git --config-env=core.pager=X log",
+        "git clone --upload-pack=id a b",
+        "git clone -u id a b",
+        "git clone -c core.fsmonitor=id a b",
+        "git fetch --upload-pack id origin",
+        "git push --receive-pack=id origin",
+        "git rebase -x id main",
+        "git rebase --exec=id main",
+        "git difftool --extcmd=id",
+        "git init --template=t",
+        "git bisect run id",
+        "git submodule foreach id",
+    ] {
+        let policy = CommandPolicy {
+            allowlist: vec!["git".into()],
+            ..policy_at(tmp.path())
+        };
+        let res = run(policy, cwd_args(tmp.path(), command));
+        assert!(error_of(&res).contains("git"), "{command}: {res}");
+    }
+}
+
+#[test]
+fn shell_opt_in_background_grandchild_does_not_hang() {
+    std::env::set_var("AIEN_DRIVE_ALLOW_SHELL", "1");
+    let loaded = CommandPolicy::from_operator_env();
+    std::env::remove_var("AIEN_DRIVE_ALLOW_SHELL");
+    assert!(
+        loaded.allow_shell,
+        "AIEN_DRIVE_ALLOW_SHELL=1 must enable the operator shell"
+    );
+    let tmp = Tmp::new();
+    let pidfile = tmp.path().join("pid");
+    let policy = CommandPolicy {
+        allow_shell: true,
+        root: tmp.path().to_path_buf(),
+        timeout: Duration::from_secs(2),
+        ..loaded
+    };
+    let command = format!("sleep 30 & echo $! > {}", pidfile.display());
+    let started = Instant::now();
+    let res = run(policy, cwd_args(tmp.path(), &command));
+    let elapsed = started.elapsed();
+    let pid_txt = std::fs::read_to_string(&pidfile).unwrap_or_default();
+    let pid: i32 = pid_txt.trim().parse().unwrap_or(0);
+    let mut alive = pid > 0;
+    if alive {
+        for _ in 0..50 {
+            if !Path::new(&format!("/proc/{pid}")).exists() {
+                alive = false;
+                break;
+            }
+            std::thread::sleep(Duration::from_millis(10));
+        }
+    }
+    if alive {
+        let _ = std::process::Command::new("kill")
+            .args(["-9", &pid.to_string()])
+            .status();
+    }
+    assert!(
+        elapsed < Duration::from_secs(3),
+        "shell grandchild hung the driver for {elapsed:?}: {res}"
+    );
+    assert!(
+        pid > 0,
+        "shell did not record the grandchild pid: {res} {pid_txt:?}"
+    );
+    assert!(!alive, "grandchild {pid} survived the shell opt-in");
+}
diff --git a/crates/aien-drive/tests/equivalence.rs b/crates/aien-drive/tests/equivalence.rs
index 327a31f5..1b684f9a 100644
--- a/crates/aien-drive/tests/equivalence.rs
+++ b/crates/aien-drive/tests/equivalence.rs
@@ -23,17 +23,25 @@
 //! "[Errno 2] ...", Rust prints "No such file or directory (os error 2)"),
 //! so for errors that come from the OS only the `error` key is compared.
 
-use aien_drive::{dispatch_tool, extract_tool_calls, Config};
+use aien_drive::{dispatch_tool, extract_tool_calls, CommandPolicy, Config};
 use serde_json::Value;
 use std::time::Duration;
 
-fn cfg() -> Config {
+fn cfg_at(root: &std::path::Path) -> Config {
     Config {
         endpoint: String::new(),
         model: String::new(),
         cortex_endpoint: "http://127.0.0.1:1".into(),
         cortex_space: "aien-sources".into(),
         request_timeout: Duration::from_secs(5),
+        command: CommandPolicy {
+            // The golden `run_command` cwd is this directory. It has to be
+            // the command root, or the root check rejects the call before
+            // the shell-metacharacter check runs.
+            root: root.to_path_buf(),
+            ..CommandPolicy::default()
+        },
+        cortex_token: None,
     }
 }
 
@@ -47,8 +55,17 @@ fn extract_matches_python() {
     let cases = g["extract"].as_array().unwrap();
     assert!(cases.len() >= 6);
     for c in cases {
-        let got = extract_tool_calls(c["text"].as_str().unwrap());
-        assert_eq!(Value::Array(got), c["calls"], "text: {}", c["text"]);
+        let text = c["text"].as_str().unwrap();
+        let got = extract_tool_calls(text);
+        // Bare `{name, arguments}` objects are not a tool-call channel.
+        if text.starts_with("bare ") {
+            assert!(
+                got.is_empty(),
+                "bare JSON must not be executed: {got:?} from {text}"
+            );
+            continue;
+        }
+        assert_eq!(Value::Array(got), c["calls"], "text: {text}");
     }
 }
 
@@ -74,8 +91,21 @@ fn run_dispatch_cases(mutate_expected: impl Fn(&mut Value)) -> Vec<String> {
     for c in g["dispatch"].as_array().unwrap() {
         let name = c["name"].as_str().unwrap();
         let args: Value = serde_json::from_str(&c["args"].to_string().replace("{TMP}", t)).unwrap();
-        let got = dispatch_tool(&cfg(), name, &args);
+        let got = dispatch_tool(&cfg_at(&tmp), name, &args);
         let got: Value = serde_json::from_str(&got.to_string().replace(t, "{TMP}")).unwrap();
+        // The Python golden ran these strings through a shell (`echo out; ...`,
+        // `$(seq ...)`). The cwd is `tmp`, which is the command root, so the
+        // rejection has to be the metacharacter check and not the root check.
+        // The historical shell result stays in the fixture.
+        if name == "run_command" {
+            let err = got.get("error").and_then(Value::as_str).unwrap_or("");
+            if !err.contains("metacharacter") {
+                failures.push(format!(
+                    "{name}: expected shell metacharacter rejection inside the command root, got {got}"
+                ));
+            }
+            continue;
+        }
         let mut want = c["result"].clone();
         mutate_expected(&mut want);
         let os_error = want["error"]
diff --git a/crates/aien-drive/tests/loop_stub.rs b/crates/aien-drive/tests/loop_stub.rs
index e45e9e4f..26d841af 100644
--- a/crates/aien-drive/tests/loop_stub.rs
+++ b/crates/aien-drive/tests/loop_stub.rs
@@ -16,7 +16,7 @@
 //! One full tool-dispatch round trip against stub HTTP servers (issue #179
 //! acceptance test), plus the cortex write payload and the failure paths.
 
-use aien_drive::{run_directive, Config};
+use aien_drive::{run_directive, CommandPolicy, Config};
 use serde_json::Value;
 use std::io::{BufRead, BufReader, Read, Write};
 use std::net::TcpListener;
@@ -69,6 +69,11 @@ fn cfg(endpoint: String, cortex: String) -> Config {
         cortex_endpoint: cortex,
         cortex_space: "aien-sources".into(),
         request_timeout: Duration::from_secs(10),
+        command: CommandPolicy {
+            root: std::env::current_dir().unwrap_or_else(|_| std::path::PathBuf::from("/tmp")),
+            ..CommandPolicy::default()
+        },
+        cortex_token: None,
     }
 }
 
@@ -121,18 +126,32 @@ fn http_error_and_dead_endpoint_are_errors() {
 }
 
 #[test]
-fn reasoning_only_tool_call_is_recovered_and_dashes_sanitized() {
+fn reasoning_text_tool_call_is_not_executed() {
     let chunk = serde_json::json!({"choices": [{"delta": {"reasoning": "a\u{2014}b <tool_call>{\"name\":\"goal\",\"arguments\":{\"action\":\"done\"}}</tool_call>"}}]});
     let (base, seen) = stub(vec![(200, format!("data: {chunk}\n\ndata: [DONE]\n"))]);
-    assert!(run_directive(&cfg(format!("{base}/x"), String::new()), "d", 3).unwrap());
+    assert!(!run_directive(&cfg(format!("{base}/x"), String::new()), "d", 3).unwrap());
     assert_eq!(seen.lock().unwrap().len(), 1);
 }
 
 #[test]
-fn cortex_tool_posts_payload() {
+fn cortex_without_operator_token_does_not_post() {
     let (cortex, seen) = stub(vec![(200, "{}".into())]);
     let a = serde_json::json!({"action":"write","name":"n1","content":"c1","kind":"procedure"});
     let r = aien_drive::dispatch_tool(&cfg(String::new(), cortex), "cortex", &a);
+    assert!(r.get("error").is_some(), "{r}");
+    assert!(
+        seen.lock().unwrap().is_empty(),
+        "unauthenticated cortex posted"
+    );
+}
+
+#[test]
+fn cortex_tool_posts_payload() {
+    let (cortex, seen) = stub(vec![(200, "{}".into())]);
+    let a = serde_json::json!({"action":"write","name":"n1","content":"c1","kind":"procedure"});
+    let mut c = cfg(String::new(), cortex);
+    c.cortex_token = Some("operator-token".into());
+    let r = aien_drive::dispatch_tool(&c, "cortex", &a);
     assert_eq!(r["status"], "ok");
     assert_eq!(r["cortex_code"], 200);
     let p: Value = serde_json::from_str(&seen.lock().unwrap()[0]).unwrap();
diff --git a/crates/aien-drive/tests/path_jail.rs b/crates/aien-drive/tests/path_jail.rs
new file mode 100644
index 00000000..0df1510f
--- /dev/null
+++ b/crates/aien-drive/tests/path_jail.rs
@@ -0,0 +1,367 @@
+// SPDX-License-Identifier: Apache-2.0
+// Copyright 2026 Drake Stapleton (AIEN / aien-dev)
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+//! File tools stay inside the command root.
+
+use aien_drive::{CommandPolicy, Config};
+use serde_json::json;
+use std::os::unix::fs::symlink;
+use std::path::{Path, PathBuf};
+use std::sync::atomic::{AtomicU64, Ordering};
+use std::time::{Duration, SystemTime, UNIX_EPOCH};
+
+static N: AtomicU64 = AtomicU64::new(0);
+
+struct Tmp(PathBuf);
+
+impl Tmp {
+    fn new() -> Self {
+        let n = N.fetch_add(1, Ordering::Relaxed);
+        let p = std::env::temp_dir().join(format!(
+            "aien-drive-paths-{}-{}-{n}",
+            std::process::id(),
+            SystemTime::now()
+                .duration_since(UNIX_EPOCH)
+                .unwrap()
+                .as_nanos()
+        ));
+        std::fs::create_dir_all(&p).unwrap();
+        Self(p)
+    }
+}
+
+impl Drop for Tmp {
+    fn drop(&mut self) {
+        let _ = std::fs::remove_dir_all(&self.0);
+    }
+}
+
+fn cfg(root: &Path) -> Config {
+    Config {
+        endpoint: String::new(),
+        model: String::new(),
+        cortex_endpoint: String::new(),
+        cortex_space: "aien-sources".into(),
+        request_timeout: Duration::from_secs(5),
+        command: CommandPolicy {
+            root: root.to_path_buf(),
+            ..CommandPolicy::default()
+        },
+        cortex_token: None,
+    }
+}
+
+fn tool(root: &Path, name: &str, args: serde_json::Value) -> serde_json::Value {
+    aien_drive::dispatch_tool(&cfg(root), name, &args)
+}
+
+#[test]
+fn parent_traversal_is_rejected() {
+    let tmp = Tmp::new();
+    let outside = tmp
+        .0
+        .parent()
+        .unwrap()
+        .join(format!("outside-{}", std::process::id()));
+    std::fs::write(&outside, "secret-outside").unwrap();
+    let rel = format!("../{}", outside.file_name().unwrap().to_string_lossy());
+    let res = tool(tmp.0.as_path(), "view_file", json!({"path": rel}));
+    assert!(res.get("error").is_some(), "{res}");
+    assert!(
+        !res.to_string().contains("secret-outside"),
+        "escaped read returned the outside file: {res}"
+    );
+    let _ = std::fs::remove_file(&outside);
+}
+
+#[test]
+fn symlink_that_leaves_the_root_is_rejected() {
+    let tmp = Tmp::new();
+    let outside = tmp
+        .0
+        .parent()
+        .unwrap()
+        .join(format!("sym-out-{}", std::process::id()));
+    std::fs::write(&outside, "secret-symlink").unwrap();
+    symlink(&outside, tmp.0.join("escape")).unwrap();
+    let res = tool(tmp.0.as_path(), "view_file", json!({"path": "escape"}));
+    assert!(res.get("error").is_some(), "{res}");
+    assert!(
+        !res.to_string().contains("secret-symlink"),
+        "symlink read left the root: {res}"
+    );
+    let _ = std::fs::remove_file(&outside);
+}
+
+#[test]
+fn absolute_path_inside_the_root_is_readable() {
+    let tmp = Tmp::new();
+    let file = tmp.0.join("inside.txt");
+    std::fs::write(&file, "inside-ok\n").unwrap();
+    let res = tool(
+        tmp.0.as_path(),
+        "view_file",
+        json!({"path": file.display().to_string()}),
+    );
+    assert_eq!(res["lines"], "inside-ok\n", "{res}");
+}
+
+#[test]
+fn git_hooks_write_is_refused() {
+    let tmp = Tmp::new();
+    let hook = tmp.0.join(".git/hooks/pre-commit");
+    let res = tool(
+        tmp.0.as_path(),
+        "write_to_file",
+        json!({"path": ".git/hooks/pre-commit", "content": "echo hooked\n"}),
+    );
+    assert!(res.get("error").is_some(), "{res}");
+    assert!(!hook.exists(), "hook file was written");
+}
+
+#[test]
+fn overwrite_defaults_to_false() {
+    let tmp = Tmp::new();
+    std::fs::write(tmp.0.join("keep.txt"), "original").unwrap();
+    let res = tool(
+        tmp.0.as_path(),
+        "write_to_file",
+        json!({"path": "keep.txt", "content": "replaced"}),
+    );
+    assert!(res.get("error").is_some(), "{res}");
+    assert_eq!(
+        std::fs::read_to_string(tmp.0.join("keep.txt")).unwrap(),
+        "original"
+    );
+}
+
+#[test]
+fn protected_write_names_are_refused() {
+    let tmp = Tmp::new();
+    for path in [
+        ".ssh/config",
+        "build.rs",
+        ".bashrc",
+        ".profile",
+        ".zshrc",
+        ".GIT/hooks/pre-commit",
+        ".envrc",
+        "Makefile",
+        ".gitattributes",
+        ".cargo/config.toml",
+        ".github/workflows/ci.yml",
+    ] {
+        let res = tool(
+            tmp.0.as_path(),
+            "write_to_file",
+            json!({"path": path, "content": "x", "overwrite": true}),
+        );
+        assert!(res.get("error").is_some(), "{path}: {res}");
+        assert!(!tmp.0.join(path).exists(), "{path} was written");
+    }
+}
+
+#[test]
+fn write_through_symlink_into_git_is_refused() {
+    let tmp = Tmp::new();
+    std::fs::create_dir_all(tmp.0.join(".git")).unwrap();
+    std::fs::write(tmp.0.join(".git/config"), "safe").unwrap();
+    symlink(tmp.0.join(".git/config"), tmp.0.join("alias")).unwrap();
+    let res = tool(
+        tmp.0.as_path(),
+        "write_to_file",
+        json!({"path": "alias", "content": "pwned", "overwrite": true}),
+    );
+    assert!(res.get("error").is_some(), "{res}");
+    assert_eq!(
+        std::fs::read_to_string(tmp.0.join(".git/config")).unwrap(),
+        "safe"
+    );
+}
+
+#[test]
+fn hardlink_to_git_config_is_refused() {
+    let tmp = Tmp::new();
+    std::fs::create_dir_all(tmp.0.join(".git")).unwrap();
+    std::fs::write(tmp.0.join(".git/config"), "safe").unwrap();
+    std::fs::hard_link(tmp.0.join(".git/config"), tmp.0.join("notes.txt")).unwrap();
+    let res = tool(
+        tmp.0.as_path(),
+        "write_to_file",
+        json!({"path": "notes.txt", "content": "pwned", "overwrite": true}),
+    );
+    assert!(res.get("error").is_some(), "{res}");
+    assert_eq!(
+        std::fs::read_to_string(tmp.0.join(".git/config")).unwrap(),
+        "safe"
+    );
+}
+
+#[test]
+fn any_hardlinked_file_is_not_written() {
+    // Hooks, rc files, worktree configs and files outside the root are not
+    // on any fixed list. A second link to the inode is enough to refuse.
+    let tmp = Tmp::new();
+    std::fs::create_dir_all(tmp.0.join(".git/hooks")).unwrap();
+    std::fs::write(tmp.0.join(".git/hooks/pre-commit"), "#!/bin/sh\n").unwrap();
+    std::fs::hard_link(tmp.0.join(".git/hooks/pre-commit"), tmp.0.join("hook.txt")).unwrap();
+    let outside = tmp
+        .0
+        .parent()
+        .unwrap()
+        .join(format!("link-out-{}", std::process::id()));
+    std::fs::write(&outside, "outside").unwrap();
+    let linked = std::fs::hard_link(&outside, tmp.0.join("out.txt")).is_ok();
+    let mut targets = vec!["hook.txt"];
+    if linked {
+        targets.push("out.txt");
+    }
+    for name in targets {
+        let res = tool(
+            tmp.0.as_path(),
+            "write_to_file",
+            json!({"path": name, "content": "pwned", "overwrite": true}),
+        );
+        assert!(res.get("error").is_some(), "{name}: {res}");
+    }
+    assert_eq!(
+        std::fs::read_to_string(tmp.0.join(".git/hooks/pre-commit")).unwrap(),
+        "#!/bin/sh\n"
+    );
+    assert_eq!(std::fs::read_to_string(&outside).unwrap(), "outside");
+    let _ = std::fs::remove_file(&outside);
+    // Control: a file with one link is still overwritten.
+    std::fs::write(tmp.0.join("plain.txt"), "old").unwrap();
+    let res = tool(
+        tmp.0.as_path(),
+        "write_to_file",
+        json!({"path": "plain.txt", "content": "new", "overwrite": true}),
+    );
+    assert!(res.get("error").is_none(), "{res}");
+    assert_eq!(
+        std::fs::read_to_string(tmp.0.join("plain.txt")).unwrap(),
+        "new"
+    );
+}
+
+#[test]
+fn intermediate_symlink_is_refused() {
+    let tmp = Tmp::new();
+    let outside = tmp
+        .0
+        .parent()
+        .unwrap()
+        .join(format!("mid-out-{}", std::process::id()));
+    std::fs::create_dir(&outside).unwrap();
+    std::fs::write(outside.join("secret.txt"), "secret-mid").unwrap();
+    symlink(&outside, tmp.0.join("mid")).unwrap();
+    let res = tool(
+        tmp.0.as_path(),
+        "view_file",
+        json!({"path": "mid/secret.txt"}),
+    );
+    assert!(res.get("error").is_some(), "{res}");
+    assert!(!res.to_string().contains("secret-mid"), "{res}");
+    let _ = std::fs::remove_dir_all(&outside);
+}
+
+#[test]
+fn absolute_path_outside_the_root_is_rejected() {
+    let tmp = Tmp::new();
+    let outside = tmp
+        .0
+        .parent()
+        .unwrap()
+        .join(format!("abs-out-{}", std::process::id()));
+    std::fs::write(&outside, "secret-abs").unwrap();
+    let res = tool(
+        tmp.0.as_path(),
+        "view_file",
+        json!({"path": outside.display().to_string()}),
+    );
+    assert!(res.get("error").is_some(), "{res}");
+    assert!(!res.to_string().contains("secret-abs"), "{res}");
+    let _ = std::fs::remove_file(&outside);
+}
+
+#[test]
+fn create_dir_into_git_is_refused() {
+    let tmp = Tmp::new();
+    let res = tool(tmp.0.as_path(), "create_dir", json!({"path": ".git/hooks"}));
+    assert!(res.get("error").is_some(), "{res}");
+    assert!(!tmp.0.join(".git/hooks").exists());
+}
+
+#[test]
+fn list_dir_and_grep_cannot_leave_the_root() {
+    let tmp = Tmp::new();
+    std::fs::write(tmp.0.join("notes.txt"), "needle\n").unwrap();
+    let listed = tool(tmp.0.as_path(), "list_dir", json!({"path": ".."}));
+    assert!(listed.get("error").is_some(), "{listed}");
+    let searched = tool(
+        tmp.0.as_path(),
+        "grep_search",
+        json!({"query": "root", "path": ".."}),
+    );
+    assert!(searched.get("error").is_some(), "{searched}");
+    let ok = tool(
+        tmp.0.as_path(),
+        "grep_search",
+        json!({"query": "needle", "path": "notes.txt"}),
+    );
+    assert!(
+        ok["matches"].as_str().unwrap_or("").contains("needle"),
+        "{ok}"
+    );
+}
+
+#[test]
+fn think_blocks_are_not_a_tool_channel() {
+    let hidden = "<think><tool_call>{\"name\":\"goal\",\"arguments\":{\"action\":\"done\"}}</tool_call></think>";
+    assert!(aien_drive::extract_tool_calls(hidden).is_empty());
+    let mixed = "<think>no</think>\n<tool_call>{\"name\":\"goal\",\"arguments\":{\"action\":\"done\"}}</tool_call>";
+    let calls = aien_drive::extract_tool_calls(mixed);
+    assert_eq!(calls.len(), 1, "{calls:?}");
+    assert_eq!(calls[0]["name"], "goal");
+}
+
+#[test]
+fn unclosed_or_orphan_think_blocks_are_not_a_tool_channel() {
+    let call = "<tool_call>{\"name\":\"goal\",\"arguments\":{\"action\":\"done\"}}</tool_call>";
+    // Truncated reasoning: the opener never closes.
+    assert!(aien_drive::extract_tool_calls(&format!("<think>plan {call}")).is_empty());
+    assert!(aien_drive::extract_tool_calls(&format!("<THINKING>plan {call}")).is_empty());
+    // A chat template that opens the block in the prompt leaves only the
+    // closer in the content.
+    assert!(aien_drive::extract_tool_calls(&format!("plan {call}</think>\nanswer")).is_empty());
+    let after = aien_drive::extract_tool_calls(&format!("plan</think>\n{call}"));
+    assert_eq!(after.len(), 1, "{after:?}");
+}
+
+#[test]
+fn grep_pattern_is_not_a_flag() {
+    let tmp = Tmp::new();
+    std::fs::write(tmp.0.join("notes.txt"), "keep -n here\n").unwrap();
+    let res = tool(
+        tmp.0.as_path(),
+        "grep_search",
+        json!({"query": "-n", "path": "notes.txt"}),
+    );
+    let matches = res["matches"].as_str().unwrap_or("");
+    assert!(
+        matches.contains("-n"),
+        "pattern was treated as a grep flag: {res}"
+    );
+}