Repository navigation
Description
Part of #240. Every per-tool automation issue builds on this one. Reporting is #241.
Problem
Each AI coding tool calls hook scripts with its own stdin JSON, its own event names and its own way to block, warn or hand text back to the agent. If every tool got hand-written shell scripts, we would have eleven copies of the same logic: working out which files changed, scoping the run, enforcing time limits, guarding against recursion, and reporting back. Every copy would drift and none would be tested. Users also need to switch automations on and off when they want them, without editing JSON by hand.
Goal
- One entrypoint,
secfoo hook <recipe> --host <tool>, that every tool-specific config calls. All behaviour lives in Python and is tested once, with recorded stdin fixtures per tool. - Recipes as data. Each automation is a small versioned definition that also generates the per-tool files and the plugin bundles (Secfoo in every agent marketplace: one MCP server, local by default, optional key for the org portal #224's build step).
secfoo automations: list, enable, disable, status and doctor, so a user can pick up a recipe for the tool they're in and drop it again.
Spec
1. Recipe definitions
src/secfoo/automations/recipes/<id>.toml, loaded like skills (built-ins plus user folders; never from the target repo, which is the same rule as skills in docs/SKILLS.md):
id = "commit-guard"
version = 1
description = "Scan staged changes for secrets and high-risk code before the agent commits or pushes."
skills = ["secret-scanning", "sast"]
events = ["pre_shell"]
shell_match = '^\s*(git\s+(commit|push)|gh\s+pr\s+create)\b' # matched against the parsed command, never executed
scope = "staged" # staged | turn_changes | paths:<glob list> | repo
blocking = true
fail_on = "high"
budget_seconds = 120 # hard wall-clock budget; on expiry: allow + background (see 4)
max_cost = 0.50
default_mode = "delegate" # delegate | hostThe v1 catalogue (ids, skills and triggers) is in #240.
2. Host adapters
src/secfoo/automations/hosts/<host>.py, one per tool, each with two functions:
parse(stdin_json, env) -> HookEvent: normalizedevent,tool_name,command,edited_paths,session_id,workspace_roots,loop_active(Claude/Droidstop_hook_active, Grok Buildloop_count, AntigravitycontinuationActive),host_version.render(result) -> (stdout, exit_code): in the tool's own vocabulary. Examples: Claude CodehookSpecificOutput.permissionDecision: "deny"ordecision: "block"+reason; Grok Buildpermission: "deny"+user_message/agent_message, andfollowup_messageonstop; CopilotpermissionDecision; Gemini CLIdecision: "deny"; Antigravitydecision: "deny", ordecision: "continue"onStop; Kiro plain stdout, which is added to the agent's context.
Detect the host; don't trust the flag blindly. Several tools read other tools' config files. Copilot and Devin both read .claude/settings.json, and Grok Build sets CLAUDE_PROJECT_DIR as an alias. One configured hook can therefore be called by a different host than it was written for. Detect the real host from the env (CURSOR_VERSION, CLAUDE_PROJECT_DIR without CURSOR_VERSION, …) and the payload shape. Warn on mismatch. De-duplicate with a short-lived lock keyed by (recipe, session_ref, diff hash), so the same change isn't reviewed twice when two configs fire.
3. Two execution modes
- delegate: run the recipe's skills through the existing runner in-process (
secfoo runsemantics:--changed-filesfrom the event,--depth quick,--fail-on,--max-cost). This gives an independent reviewer, but it costs model spend and takes time. - host: no nested agent. The hook answers with an instruction for the host agent, for example "before committing, run the secfoo
secret-scanningskill on these 3 files and submit the report". The host agent follows the skill prompt and callssubmit_reportonsecfoo mcp serve(Secfoo in every agent marketplace: one MCP server, local by default, optional key for the org portal #224, PR feat(mcp): add secfoo mcp serve stdio server, single-source plugin builder, and server.json #229). There is no extra model spend. To keep "every run reports" true, the hook first opens apendingrun and gets a run id. A laterturn_end/session_endinvocation marks any still-pending runnot_submitted(status defined in Automation runs always report back: trigger provenance, every outcome (not just success), offline queue, env-var key #241). Host mode requires the MCP server. When it isn't configured, fall back to delegate.
4. Time budgets and background runs
Hosts kill slow hooks, and their defaults differ widely: Claude Code 600 s, Codex 600 s, Gemini CLI 60 s, Kiro 60 s, Droid 60 s, Antigravity 30 s, Copilot 30 s, and Claude Code SessionEnd only 1.5 s. Rules:
- Write an explicit
timeoutinto every generated hook entry, longer than the recipe budget. - A blocking recipe that exceeds
budget_secondsallows the action, tells the user, and finishes in a detached background process (secfoo hook --resume <run>). The result is still recorded and reported. - Non-blocking recipes (post-edit, file-save) always run in the background. Use the host's native async hooks where they exist: Claude Code
async: true/asyncRewake, Codexasync: true. - Background results are surfaced on the next
turn_end/session_startinvocation from the local DB.
5. Recursion guard (must-have)
secfoo's own agent adapters run the same CLIs non-interactively, and their hooks still fire:
claude -ploads user and plugin hooks. secfoo passes--setting-sources user, which does not exclude them.- Factory documents that hooks run under
droid exec. - For
codex execthis is unverified.
A delegate run could therefore trigger itself.
- Every nested run gets
SECFOO_AUTOMATION_DEPTH=1in its env.secfoo hookexits 0 immediately with no output when it is set. - Where the CLI allows it, adapters also disable hooks for the nested run. For example, Claude Code documents
--settings '{"disableAllHooks": true}'for scripted-pruns; check how it interacts with--setting-sources. - Test: a recipe whose nested agent edits a file does not re-enter itself.
6. Loop guard for turn-end follow-ups
When findings are handed back so the agent fixes them, respect the host's flags: stop_hook_active, loop_count / loop_limit (default 5 in Grok Build), continuationActive, and the 8-continuation caps in Claude Code and Copilot. Also add secfoo's own limits: never re-review an identical diff hash, and at most 2 follow-ups per recipe per session.
7. Fail open, never stall
Only a real finding at or above the recipe threshold blocks. Any internal error, timeout, missing config, unreachable portal or unknown payload shape allows the action. It shows one line to the user and records the run as failed, which #241 then reports. Never use a host's fail-closed options (for example Grok Build failClosed, Droid onFailure: "block") in generated configs.
8. Hook input is untrusted
The stdin JSON can include repo-controlled text such as file names, commands and prompts.
- Never pass it through a shell. Never interpolate it into the generated config.
- Resolve paths and keep only those inside the workspace roots that also pass the existing excludes. Cap the file count.
- Only file paths flow into the run. Nothing from stdin goes to the portal except the hashed
session_ref. - Add adversarial fixtures (paths with
.., newlines, shell metacharacters) next totests/fixtures/adversarial/.
9. secfoo automations CLI
secfoo automations list # recipes × tools, enabled state
secfoo automations enable commit-guard --tool claude-code [--scope project|user] [--mode delegate|host] [--dry-run]
secfoo automations disable commit-guard --tool claude-code [--scope ...]
secfoo automations status # enabled recipes, last run per recipe, queued reports
secfoo automations doctor [--tool X] # tool installed + version, hooks enabled in the tool, secfoo resolvable from the hook's PATH, portal reachable
enablemerges into the tool's own config without disturbing other entries. Tag secfoo's entries sodisableremoves exactly those. Print the diff, support--dry-run, and write user-level files with 0600 permissions. Reuse the safe merge patterns insrc/secfoo/mcp.py, which already merges into~/.cursor/mcp.jsonand Codex'sconfig.toml. See the bugs fixed in Bug:secfoo mcp sync --agent agentcrashes on a non-object ~/.cursor/mcp.json and drops its other keys #170 / Security: write ~/.cursor/mcp.json with 0600 permissions (it holds MCP auth headers) #171 for what goes wrong otherwise.- Generated commands call
secfooby absolute path, or through a tiny shim, because hooks often run with a minimalPATH. They must never contain a key. - When
--scope projectwrites into a committed file, warn that it affects everyone who opens the repo.
10. One source for plugin bundles
The same recipe data generates the hooks.json files inside the Claude, Copilot, Gemini CLI and other plugin bundles. Hook into #224's build step (scripts/build_plugins.py) rather than writing a second generator. Recipes ship disabled in plugins unless the platform has a per-hook enable UI.
Where to look
src/secfoo/runner.py (run entry and --changed-files scoping), src/secfoo/targets/diff.py, src/secfoo/agents/* (adapters that need the recursion guard), src/secfoo/mcp.py (config merging), src/secfoo/skills/loader.py (loading built-ins plus user folders), tests/fixtures/agents/ (recorded-transcript precedent), scripts/record_agent.py (redaction before saving fixtures).
Tests (required)
- Recorded stdin fixtures per host and event under
tests/fixtures/hooks/<host>/<version>/, redacted the same way as agent recordings.parse→renderround trips assert the exact output shape each host documents. - Recursion guard, loop guard, de-duplication, fail-open on every error path, budget expiry → background.
enable/disableare idempotent, preserve unrelated config, and--dry-runwrites nothing.
Done when
secfoo hook and secfoo automations ship with the tests above and docs in docs/automations.md. At least the Claude Code adapter (#243) is implemented end to end as the reference, and the other host adapters can be added independently by the per-tool issues.
Activity