Skip to content

feat(harness): lifecycle hooks (P2a) - #106

Closed
mlubbad wants to merge 13 commits into
mainfrom
feat/harness-hooks
Closed

mlubbad wants to merge 13 commits into
mainfrom
feat/harness-hooks

Conversation

@mlubbad

@mlubbad mlubbad commented Jul 25, 2026

Copy link
Copy Markdown
Owner

Harness P2a — Hooks

Gives the harness a programmable policy layer: shell commands you configure that run at agent-loop lifecycle events, receiving the event as JSON on stdin and returning a decision on stdout. They execute outside the model's context — no tokens, and the model can't argue with them. This is what makes external gate/evidence and telemetry systems pluggable rather than something we hard-code. Follow-up to #102 (Harness P1) and #103 (workspace bash). Spec: docs/superpowers/specs/2026-07-22-harness-hooks-design.md.

Five events (Claude Code's contract, so existing hook scripts port over)

Event Fires Can
SessionStart turn begins inject context into the system prompt
UserPromptSubmit before the prompt reaches the model inject context, or block the turn
PreToolUse before a tool runs allow / deny / ask
PostToolUse after a tool returns inject context (observational)
Stop turn ends inject context (observational)

Config lives in app settings: {"hooks": {"PreToolUse": [{"matcher": "bash|edit_file", "command": "python gate.py", "timeout": 30}]}}. Matchers are anchored regexes on the tool name; multiple hooks per event run in order and the strictest decision wins.

Safety model

  • App-settings-only trust. Hooks are never loaded from a workspace's .claude/settings.json. P1 reads workspace permission rules because those only ever restrict; a hook executes, so a cloned repo must not be able to ship one. (Verified adversarially: a planted workspace hook is ignored.)
  • Fail closed where it matters. A PreToolUse/UserPromptSubmit hook that times out, crashes, exits non-zero, or emits malformed JSON → deny. A hook that requests approval in an unattended run (Cowork/scheduler, nobody to ask) → deny, so the tighten signal can't silently invert into "proceed."
  • Fail open where it can't hurt. PostToolUse/Stop/SessionStart failures are logged and ignored — an observational hook can't brick a turn.
  • Tighten-only. A hook's allow can never resurrect a rules.gate deny or defeat the catastrophic-bash breaker; its ask forces a prompt even where the mode would auto-run.
  • Bounded & isolated. shell=False; tool input arrives only as stdin JSON (never argv); secret-stripped env; capped timeout with whole-process-tree kill; output capped and secret-scrubbed; every run audited with duration_ms/ok.
  • Zero-config = unchanged. No hooks configured ⇒ no subprocess, byte-for-byte today's behavior.

Caveat documented in SECURITY.md: the converse of tighten-only is that a broad-matcher allow hook skips approval prompts — that's the intended operator trust delegation, and deserves the same caution as bypass mode.

Adversarial verification

13 attack classes probed against the built feature with real subprocesses; 10 held clean, 3 escapes found and fixed:

  1. A hook's ask silently became allow in unattended auto-mode runs (a safety signal failing open) — now fails closed.
  2. A detached grandchild survived a timed-out hook's kill — now the whole tree is killed (taskkill /T / killpg).
  3. DATABASE_URL-style credentials passed the secret-env name filter — pattern widened (this also retroactively hardens workspace bash from feat(harness): workspace-cwd bash — run tests/builds in the folder (P1.5) #103, which shares the filter).

Two findings accepted and documented rather than fixed (spec §9b): PreToolUse latency scales with hook count (each individually capped), and a pathological matcher regex can stall (operator-authored, self-inflicted only).

Earlier review rounds also caught and fixed: a PostToolUse context-ordering bug that put a user message between an assistant's tool_calls and its tool replies (would have 400'd on real providers, breaking every turn with such a hook), a missing tighten path where the rules-gate allow skipped a hook's ask, and exit-2 not honoring fail-open for observational events.

Testing

34 unit tests (test_harness_hooks.py) + loop-level tests in test_agent_workspace.py; 133 passing across the harness/HITL/permissions/rules/bash suites (the single test_bash_jail::test_run_bash_still_allows_safe_relative failure is the pre-existing Windows-only echo baseline — green on Linux CI). Full-repo ruff clean.

Roadmap: this is P2a. P2b (generalized subagents — with the permission_mode="auto" ungated-write problem to resolve deliberately) and P2c (skills/commands $ARGUMENTS/allowed-tools) remain.

🤖 Generated with Claude Code

mlubbad and others added 13 commits July 25, 2026 15:40
Deterministic user-owned interception (SessionStart/UserPromptSubmit/
PreToolUse/PostToolUse/Stop) with Claude''s JSON stdin/stdout contract.
App-settings-only trust (never workspace-supplied), command hooks only,
fail-closed on PreToolUse, tighten-only vs the P1 rules gate. Also records
the P2 decomposition (P2b subagents, P2c skills-format).

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
7 TDD tasks: config+loader, matcher, decision parse/merge, runner (stdin JSON,
timeout, sanitized env, audited), blocking call sites (PreToolUse +
UserPromptSubmit), observational call sites (SessionStart/PostToolUse/Stop),
adversarial verify + docs. Anchors verified against agent.py line numbers.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Executes matching hooks with shell=False, passes the event as stdin JSON,
enforces a capped timeout with kill, inherits the secret-stripped env, scrubs
secrets from output, and audits every run. Zero configured hooks spawns
nothing (byte-for-byte pre-hooks behavior).

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Spec review found the audit record omitted the spec-required duration_ms/ok,
and the timeout path killed the child without awaiting it (leaving a dangling
asyncio transport that surfaced as ResourceWarnings; the process itself was
killed). Adds await proc.wait() and the two audit fields, plus a test locking
UserPromptSubmit''s fail-closed behavior into the suite (previously only
verified by an out-of-band probe). 31 tests green, no warnings.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
…guarantee)

The workspace rules-gate allow branch continue''d straight to execution without
consulting _hook_forces_ask, so a PreToolUse hook returning "ask" was silently
dropped in bypass/acceptEdits for the harness-governed tools — violating spec
6.4 (a hook may always tighten). Found by the Task 5 implementer''s own
self-review. Regression test added.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
…s tree, widen secret-env filter (adversarial verify)
…tions

Adversarial verify: 13 attack classes probed, 10 held; 3 escapes found and
fixed (ask evaporating unattended, detached grandchild surviving a timeout,
DSN/cloud credential env names passing the secret filter). Spec corrected to
the as-built ordering (PreToolUse runs before rules.gate — the gate deny and
breaker still win) and documents the two accepted limitations. P2 roadmap row
split into P2a shipped / P2b subagents / P2c skills-format.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
@mlubbad

mlubbad commented Nov 21, 2026

Copy link
Copy Markdown
Owner Author

Merged and shipped as part of the clean-slate VersoWork v0.1.0 open-source release.

@mlubbad mlubbad closed this Nov 21, 2026
@mlubbad
mlubbad deleted the feat/harness-hooks branch November 21, 2026 20:26
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant