Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
73 changes: 73 additions & 0 deletions docs/adr/0199-hook-tool-matchers.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
# ADR 0199: Hook tool matchers

- Status: Proposed
- Date: 2026-11-09
- Scope: restricted lifecycle hook declarations and tool-event filtering
- Updates: ADR 0197 (operator script hooks) and the hook boundary contract in
docs/extensions.md
- References: Claude Code matcher syntax and Codex hook matchers (external
parity baselines)

## Problem

Tool-event hooks filter by an exact `tool_names` list capped at 64 entries.
Both external harnesses match tools with regular expressions instead, and real
tool families break the exact-list model: MCP servers expose dynamic tool
names (`mcp_github_create_issue`, `mcp_github_create_pr`, …), so a reviewed
plugin cannot deny a whole write family without enumerating every name or
consuming the entire list budget on one server.

## Decision (proposed)

1. **One filter per declaration, either form.** A tool-event declaration
declares either the exact `tool_names` list or a single `tool_pattern`
regular expression — never both. The pattern matches unanchored against the
tool name (the same effective behavior as the external matchers), so
`mcp_github_(create|delete)_` covers a write family with one rule.
2. **Bounded and linear-time.** Patterns are at most 256 bytes, reject NUL and
control characters, and must compile as Go regexp. Go's regexp is a
linear-time engine, so a hostile or sloppy pattern cannot cause
catastrophic backtracking in a hook boundary. Compilation happens at
registry replacement, and the compiled forms are stored beside the sorted
registrations; a pattern that fails to compile at replacement time fails
closed.
3. **Same generation contract.** The pattern is part of the declaration
fingerprint: changing it advances the registry generation exactly like any
other declaration edit, and the plugin diagnostics projection exposes the
declared pattern next to `tool_names` so operator views can render the real
filter.
4. **Non-tool events unchanged.** `user_prompt_submit`, run, session,
compaction, subagent, and checkpoint boundaries have no tool name to match;
they reject both filters exactly as before.

## Alternatives considered

- Anchored full-match semantics were rejected: the external matchers match
unanchored, and anchor-free patterns are strictly more expressive anyway
(`^…$` is one escape away).
- Glob-style matchers (`mcp_github_*`) were rejected: regular expressions
cover globs and more, and the repository already standardizes on Go regexp
elsewhere.
- Allowing both the list and the pattern per declaration was rejected: the
union is expressible with a pattern alternation, and one filter keeps the
audit and the operator views unambiguous.

## Verification

- `internal/hooks` tests cover validation (mutual exclusion, size, syntax,
NUL, non-tool events), unanchored matching against matching, non-matching,
and unrelated tools, registry generation changes on pattern edits, and
fail-closed compilation at replacement.
- `internal/httpapi` and the web client validate the extended declaration
projection (the `tool_pattern` field, its bounds, mutual exclusion, and
tool-event restriction); the OpenAPI snapshot and the generated TypeScript
schema are regenerated.
- Documentation: the hook contract in docs/extensions.md (bilingual) and this
ADR.

## Consequences

Reviewed plugins can express per-family policy in one rule, and the 64-entry
exact-list budget stops being the binding constraint for dynamic tool
families. The matcher joins the existing engine path with no new surfaces,
and the diagnostics views render the actual filter instead of an empty list.
4 changes: 3 additions & 1 deletion docs/extensions.md
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,8 @@ cyberagent plugin show <new-installation-id>

同一事件按 event、Plugin ID、Hook ID 稳定排序。每条声明有最大 2 秒超时,输入 256 KiB、输出 16 KiB、注释 16 条的上限;`failure_policy=deny` 失败关闭,`continue` 只记录失败并继续。每个结果写 metadata-only audit,不保存 Hook 输入、注释正文或工具 payload。

工具事件的过滤器二选一:`tool_names`(精确列表)或 `tool_pattern`(一条 Go 正则,非锚定匹配工具名,长度上限 256 字节;Go regexp 为线性时间引擎,不存在灾难性回溯)。两条路径的 deny/annotate/narrow 语义完全一致,声明改变 pattern 会推进注册表 generation。

`user_prompt_submit` 的 payload 由 Go 编码:Thread 面携带 `thread_id`,Session 面携带 `session_id` 与 `run_id`,加上 `content`(超长 prompt 在 UTF-8 边界截断并带 `truncated` 标记;非法 UTF-8 字节一次性剔除),不支持工具过滤。deny 在消息意图预留与排队发生之前拒绝提交;annotate 只进入结果与审计,不注入模型上下文。已知盲区:image-only 提交(`content` 为空)不触发边界,MCP-only 提交以合成文案触发、真实 MCP 参数不在 payload 中;同一 operation key 的每次重试都会再次触发(attempt-scoped)。

## Operator 脚本 Hook
Expand Down Expand Up @@ -178,7 +180,7 @@ Schemas v120-v121 introduced the low-trust extension runtime; Universal Code add

The MCP state flow is `staged -> approve_discovery -> capabilities_pending -> enable_capabilities -> enabled`. Disable and revoke are immediate; capability or restart ambiguity quarantines the server. A connection, discovery, or tool-call failure during invocation marks it unavailable and removes it from model-visible capabilities until an explicit refresh succeeds. Plugin installation is independently `staged -> approved -> enabled`, with capability-by-capability enablement, publisher trust/revocation, atomic upgrade/rollback, and a separate MCP review for contributed server descriptors. HTTPS import requires an exact archive SHA-256 and rejects every redirect. Git import accepts only a credential-free HTTPS repository, a full commit SHA, and a safe repository-relative ZIP path; it fetches into a temporary bare repository with system/global Git config, URL rewrites, credential helpers, hooks, redirects, and non-HTTPS protocols disabled, performs no checkout or submodule load, and reads only the exact ordinary blob. A revoked publisher cannot be bypassed with untrusted confirmation, and the database permits at most one enabled version of each Plugin ID. Enabling a Plugin's `skills` capability never auto-selects, injects, or authorizes those inert resources for a Run; the existing explicit Skill installation, selection, and mode-compatibility path remains authoritative.

Actual hook boundaries are Tool pre/post, initial Run start, terminal Run finalization, Session creation/archive, operator prompt submission at its four surfaces (the Thread turn endpoint, CLI `thread send`, Session chat, and Session message submission) before any persistence or queueing, real compaction immediately before summary persistence, operator-authorized Specialist scheduling, and continuity/manual Workspace Checkpoint persistence. Ordering, time, input/output, annotation, reentry, and failure-policy limits are enforced by Go and every execution writes a metadata-only audit.
Actual hook boundaries are Tool pre/post, initial Run start, terminal Run finalization, Session creation/archive, operator prompt submission at its four surfaces (the Thread turn endpoint, CLI `thread send`, Session chat, and Session message submission) before any persistence or queueing, real compaction immediately before summary persistence, operator-authorized Specialist scheduling, and continuity/manual Workspace Checkpoint persistence. Tool events filter by either the exact `tool_names` list or a single `tool_pattern` Go regular expression (unanchored against the tool name, at most 256 bytes; Go regexp is a linear-time engine without catastrophic backtracking). Ordering, time, input/output, annotation, reentry, and failure-policy limits are enforced by Go and every execution writes a metadata-only audit.

The `user_prompt_submit` payload is Go-encoded: Thread surfaces carry `thread_id`, Session surfaces carry `session_id` and `run_id`, plus `content` (oversized prompts clip on a UTF-8 boundary with a `truncated` flag; invalid UTF-8 bytes are dropped once); tool filters are not allowed. A deny rejects the submission before the message intent or steering queue entry exists; annotations stay in the result and audit and are never injected into model context. Known blind spots: image-only submissions (empty content) skip the boundary, MCP-only submissions fire with synthesized text while the real MCP arguments stay outside the payload, and every attempt of the same operation key re-fires the boundary (attempt-scoped).

Expand Down
5 changes: 5 additions & 0 deletions docs/openapi.json
Original file line number Diff line number Diff line change
Expand Up @@ -52188,6 +52188,10 @@
"type": "string"
},
"type": "array"
},
"tool_pattern": {
"maxLength": 256,
"type": "string"
}
},
"required": [
Expand All @@ -52203,6 +52207,7 @@
"failure_policy",
"timeout_ms",
"tool_names",
"tool_pattern",
"remove_fields"
],
"type": "object"
Expand Down
52 changes: 49 additions & 3 deletions internal/hooks/hooks.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import (
"errors"
"fmt"
"io"
"regexp"
"slices"
"sort"
"strings"
Expand All @@ -32,6 +33,7 @@ const (
MaxAnnotationBytes = 1024
MaxHookTimeoutMillis = 2_000
MaxHookIdentityRunes = 256
MaxToolPatternBytes = 256
)

type Event string
Expand Down Expand Up @@ -91,6 +93,7 @@ type Declaration struct {
FailurePolicy FailurePolicy `json:"failure_policy"`
TimeoutMillis int `json:"timeout_ms"`
ToolNames []string `json:"tool_names,omitempty"`
ToolPattern string `json:"tool_pattern,omitempty"`
RemoveFields []string `json:"remove_fields,omitempty"`
Message string `json:"message,omitempty"`
Script *ScriptSpec `json:"script,omitempty"`
Expand Down Expand Up @@ -141,6 +144,25 @@ func (d Declaration) Validate() error {
if d.Event != PreTool && d.Event != PostTool && len(d.ToolNames) != 0 {
return errors.New("non-tool hooks cannot declare tool filters")
}
if d.Event != PreTool && d.Event != PostTool && d.ToolPattern != "" {
return errors.New("non-tool hooks cannot declare tool filters")
}
if d.ToolPattern != "" && len(d.ToolNames) != 0 {
return errors.New("a hook declares either exact tool names or one tool pattern")
}
if d.ToolPattern != "" {
if !validText(d.ToolPattern, MaxToolPatternBytes, false) {
return errors.New("hook tool pattern is invalid or oversized")
}
// The web parser's trim check also strips a leading BOM; reject it
// here so the projection and the parser agree on every byte.
if strings.ContainsRune(d.ToolPattern, '\uFEFF') || strings.ContainsAny(d.ToolPattern, "\n\r\t") {
return errors.New("hook tool pattern contains a byte order mark or control character")
}
if _, err := regexp.Compile(d.ToolPattern); err != nil {
return fmt.Errorf("hook tool pattern does not compile: %w", err)
}
}
if duplicatesOrInvalid(d.ToolNames, false) || duplicatesOrInvalid(d.RemoveFields, true) {
return errors.New("hook tool names or removal fields are invalid or repeated")
}
Expand Down Expand Up @@ -274,6 +296,7 @@ type AuditSink interface {
type Engine struct {
mu sync.RWMutex
registrations []Registration
toolPatterns []*regexp.Regexp
generation string
sink AuditSink
now func() time.Time
Expand Down Expand Up @@ -339,8 +362,22 @@ func (e *Engine) Replace(registrations []Registration) error {
})
raw, _ := json.Marshal(values)
digest := sha256.Sum256(append([]byte(ProtocolVersion+"\x00"), raw...))
// Validate already compiled and rejected every pattern, so this loop is
// defensive depth: keep the compiled forms aligned with the sorted
// registrations without trusting the earlier pass.
toolPatterns := make([]*regexp.Regexp, len(values))
for index, value := range values {
if value.Declaration.ToolPattern != "" {
compiled, err := regexp.Compile(value.Declaration.ToolPattern)
if err != nil {
return fmt.Errorf("hook tool pattern does not compile: %w", err)
}
toolPatterns[index] = compiled
}
}
e.mu.Lock()
e.registrations = values
e.toolPatterns = toolPatterns
e.generation = hex.EncodeToString(digest[:])
e.mu.Unlock()
return nil
Expand All @@ -364,13 +401,19 @@ func (e *Engine) Execute(ctx context.Context, input Input) (Result, error) {
}
e.mu.RLock()
registrations := slices.Clone(e.registrations)
toolPatterns := append([]*regexp.Regexp(nil), e.toolPatterns...)
generation := e.generation
e.mu.RUnlock()
result := Result{ProtocolVersion: ProtocolVersion, Generation: generation,
Payload: append(json.RawMessage(nil), input.Payload...), Executed: []string{}}
for _, registration := range registrations {
for index, registration := range registrations {
declaration := registration.Declaration
if declaration.Event != input.Event || !matchesTool(declaration.ToolNames, input.ToolName) {
var toolPattern *regexp.Regexp
if index < len(toolPatterns) {
toolPattern = toolPatterns[index]
}
if declaration.Event != input.Event ||
!matchesTool(declaration.ToolNames, toolPattern, input.ToolName) {
continue
}
hookCtx, cancel := context.WithTimeout(ctx,
Expand Down Expand Up @@ -511,7 +554,10 @@ func (e *Engine) Generation() string {
return e.generation
}

func matchesTool(values []string, toolName string) bool {
func matchesTool(values []string, pattern *regexp.Regexp, toolName string) bool {
if pattern != nil {
return pattern.MatchString(toolName)
}
return len(values) == 0 || slices.Contains(values, toolName)
}

Expand Down
Loading
Loading