Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
docs(security): ADR-016 argv-lane auto-approval and per-agent permission contexts
Salman Qureshica8ce711b343
diff --git a/DECISIONS.md b/DECISIONS.mdindex a06ee201..e8bf3662 100644--- a/DECISIONS.md+++ b/DECISIONS.md@@ -136,6 +136,16 @@- **Decision**: Accept and maintain. Verified empirically on macOS before merge: an xattr-bearing `web/` directory produced `._web` in the archive without `COPYFILE_DISABLE=1` and nothing with it. Full suite green (487 tests), `tsc --noEmit` clean. The allowlist change is a security positive (defense in depth — children can no longer invoke tools outside their allowlist, e.g. `list_agents`/`stop_agent`); the runtime filter subsumes the prompt-text filtering in `sub-agent.ts` line 516, which remains as harmless documentation. Merge commit authored by Mercury, feature commits retain the original author.- **Consequence**: Release archives stay safe for GNU tar consumers; sub-agent tool scoping is now enforced at the SDK boundary rather than trusted to the model's cooperation. Maintenance owned by Mercury: any new tool surface exposed to sub-agents must respect `resolveTools()` (not `capabilities.getTools()` directly), and release builds on macOS must keep `COPYFILE_DISABLE=1` — re-verify archive contents with GNU tar or the `verify-standalone-release.cjs` path check before publishing.+## ADR-016: Argv-lane auto-approval and per-agent permission contexts++- **Context**: Ask Me mode auto-approved a list of "safe read" commands by matching regex patterns against the command string, then ran the string through `sh -c` with the daemon's `PATH`. Every fix to that classifier (find action flags #71/#77/#101, redirection #72/#82, variable expansion #76/#80, residual `find -fprint0`, `rg --pre`, `git --output`/`--ext-diff`) left the class open, because the check and the shell parsed the string differently, and an allowlisted name resolved through a mutable `PATH` (#103). Separately, channel, allow-all, skill elevation and session scopes were mutable fields on the one `PermissionManager` shared by the main agent and every sub-agent; an internal (scheduled) turn switched allow-all on for its duration and a concurrently running sub-agent inherited it (#75/#99 residual), a sub-agent's `use_skill` elevated the main agent, and the `/` scope an internal turn added was never removed.+- **Decision**:+ - **Two shell lanes.** The *argv lane* (`src/capabilities/shell/argv-lane.ts`) auto-approves only commands that a strict POSIX tokenizer turns into argv without meeting any shell syntax (it rejects `$`, backticks, `~`, redirection, pipes, lists, unquoted globs, `!`, `#`, subshells, env-assignment prefixes), whose `argv[0]` is a bare name on `ARGV_ALLOWLIST`, whose flags pass that program's policy (`SIDE_EFFECT_FLAGS` as the deny list over quote-removed argv, plus positive rules for `git` — read subcommands only, nothing before the subcommand — `git branch` listing, `ps` without `e`/`E`, `rg -z`, `tree -R`), whose path arguments stay inside the tool cwd or a readable scope, and whose binary exists in the pinned directories. It executes with `execFile(absBinary, argv, { cwd, env: minimalEnv(), shell: false })`; git gets `-c core.fsmonitor=false -c core.pager=cat --no-pager` and `--no-ext-diff --no-textconv`. `cd` runs in-process. Everything else is the *approval lane*: the user sees the exact string and, once approved, it may run through the shell (still via execFile when it is expressible as argv). Pipelines of read-only commands go to the approval lane — running each stage via execFile and piping in-process was rejected as more code and more policy surface for a convenience.+ - **Pinned binaries.** Allowlisted programs are resolved once at startup from `/usr/bin`, `/bin`, `/usr/sbin`, `/sbin`, `/usr/local/bin`, `/opt/homebrew/bin` (Windows: `System32`, `Program Files\Git\cmd`), never `process.env.PATH`; world-writable binaries are skipped. The git read tools use the same pinned git. Service files write a fixed `PATH` (system dirs plus the node binary's directory); on Windows, where Task Scheduler XML has no environment block, the `--daemon` process pins its own `PATH`.+ - **Immutable per-agent contexts.** `PermissionContext { channelType, channelId, senderRole, autoApprove, autoApproveOrigin, allowedTools, scopes, elevated }` is frozen. Sub-agents run under their own context through `AsyncLocalStorage` (`PermissionManager.withContext`), derived at spawn time by `deriveChildContext` (child ⊆ parent: tools intersected, scopes covered, no elevation, allow-all only from a user-chosen *session* grant). The supervisor stores the snapshot on `SubAgentConfig.permissionContext`, so a queued agent keeps it. The main agent's messages are serialised, so its context stays the root one; internal turns layer a turn grant (`beginTurnGrant`/`endTurnGrant`) over it that children neither see nor inherit. The legacy setters remain as shims that replace the calling agent's context. `AsyncLocalStorage.run` is used rather than `enterWith`, which on Node 20 leaks a store into the caller's continuation.+- **Alternatives considered**: hardening the regex classifier further (the approach that kept failing); a full shell parser (bash-compatible parsing is large and still has to agree with the real shell); capability tokens passed explicitly through every tool factory (correct but touches every tool; ALS gives the same isolation behind the existing API); a separate `PermissionManager` per sub-agent (approval memory, the ask handler and manifest persistence would fork).+- **Consequence**: The auto-approved path no longer involves a shell or `PATH`, so redirection/expansion/chaining/PATH-substitution bypasses do not apply to it; the remaining risk is an option of an allowlisted program that the flag policy misses. Some commands that used to run silently now prompt: pipelines and `&&` chains of read-only commands (including `cd dir && ls`), quoted absolute paths outside the workspace (`cat "/etc/passwd"`, which the old regex path gate missed), `ps -ef`/`ps e`, tools not installed in the pinned dirs (e.g. `rg` under `~/.cargo/bin`), and Windows `dir`/`type` (cmd builtins). Bare `ls`, `git status` and similar now auto-approve (the old `cmd *` patterns needed an argument). On the internal channel `requestApproval` approves only under allow-all. Maintenance owned by Mercury: new auto-approved programs go into `ARGV_ALLOWLIST` with a policy and a test row; never add a shell-dependent fallback to the argv path; any new agent-like runner must enter `withContext` with a derived context.+## ADR-018: SQLite backend selection: better-sqlite3 → bun:sqlite → node:sqlite → JSON- **Context**: Four stores depend on SQLite — Second Brain (`src/memory/second-brain-db.ts`), the bots job queue (`src/bots/queue.ts`), boards (`src/core/board-db.ts`) and the cloud pool-search cache (`src/cloud/pool-search.ts`). Each carried its own `require('better-sqlite3')` probe. The standalone binaries (`bun build --compile`) bundle better-sqlite3's JavaScript but not its native addon, so inside a binary every probe failed on every target: Second Brain was silently disabled and bots/boards fell back to JSON (ROADMAP P1.9, §F, #96). Toolchain-less npm installs (Termux, no compiler) hit the same wall. Meanwhile both runtimes ship an embedded engine — `bun:sqlite` in Bun and `node:sqlite` (`DatabaseSync`) in Node ≥ 22.5 (unflagged in 22.13 / 23.4) — with the same synchronous shape better-sqlite3 has.diff --git a/SECURITY.md b/SECURITY.mdindex 71ad27dc..84334ab5 100644--- a/SECURITY.md+++ b/SECURITY.md@@ -56,15 +56,51 @@ Out of scope:## A note on the permission modelMercury's "Ask Me" mode is the real security boundary: risky commands and-out-of-scope file access prompt you before they run. On top of that, a small-allowlist of read-only commands (`ls`, `cat`, `grep`, `find`, ...) is auto-approved-for usability. That classifier is a **best-effort** pattern check on the command-string. Several bypasses of it have been reported and fixed (find action flags,-shell redirection, variable expansion), and we expect the class to keep producing-reports until the auto-approval lane is rebuilt around a tokenised argv allowlist-with per-command flag policy (tracked in `ROADMAP.md`, P2.2). Until then, treat-auto-approval as a convenience, not a guarantee, and keep Ask Me on for any-instance reachable by people you do not fully trust.+out-of-scope file access prompt you before they run. Shell commands take one of+two lanes (ADR-016 in `DECISIONS.md`):++- **Argv lane (no prompt).** A command is auto-approved only if it tokenises+ into a plain argument list with no shell syntax at all (no `$`, backticks,+ `~`, redirection, pipes, `;`/`&&`, unquoted globs, subshells); its program is+ on a short read-only allowlist (`ls`, `cat`, `head`, `tail`, `wc`, `grep`,+ `rg`, `find`, `tree`, `du`, `df`, `ps`, `uname`, `pwd`, `which`, `echo`,+ `git status|diff|log|branch`, and `cd`, handled in-process); its flags pass+ that program's policy (write/exec flags such as `find -exec`, `rg --pre`,+ `git --output` are refused); and every path argument stays inside the+ working directory or an approved scope. It then runs with+ `execFile(absolute binary, argv)` and a minimal environment, never a shell.+ Binaries are resolved once at startup from a fixed list of system+ directories (`/usr/bin`, `/bin`, `/usr/sbin`, `/sbin`, `/usr/local/bin`,+ `/opt/homebrew/bin`; System32 and Git on Windows), not from `PATH`. Git+ reads run with repository-configured hooks, pagers, external diffs and+ textconv filters disabled.+- **Approval lane (prompt).** Everything else, including pipelines such as+ `git log | head` and `&&` chains of read-only commands. You see the exact+ string; once approved it runs through the platform shell (`sh -c` /+ `cmd.exe`) with the daemon's environment. If an approved command can be+ expressed as argv it still runs without a shell. Allow All, an "always"+ answer, skill elevation and bot allow-lists approve through this lane+ without a prompt; hard-blocked commands are refused in every lane.++What this does and does not cover. The argv lane removes the shell from the+auto-approved path, so the bypass class that kept recurring (redirection,+expansion, chained commands, PATH substitution) no longer applies to it; what+remains is the per-program flag policy, which is a deny/allow table we maintain+and could still miss an option of an allowlisted tool. Path checks are lexical+plus symlink canonicalisation for file tools; the argv lane checks path+arguments lexically. Commands you approve run with whatever the shell does,+by design.++Each agent has its own frozen permission context (channel, sender role, Allow+All, allowed tools, session scopes). Delegated sub-agents get a context derived+from their parent's when they are spawned and can never hold more than the+parent: tool lists are intersected, scopes must be covered by the parent's, skill+elevation is not inherited, and the allow-all of a scheduled/internal turn is+neither inherited nor visible to sub-agents running at the same time.++Service files (`mercury service install`) write a fixed `PATH` rather than the+installing shell's. Keep Ask Me on for any instance reachable by people you do+not fully trust.Known-fixed issues and the regression tests that cover them are listed in`docs/security/`.