fix(hooks): share matcher validation instances

This commit is contained in:
ZiyaZhang
2026-07-28 20:10:21 -07:00
parent 774755ef2d
commit ec72d0b57e
17 changed files with 221 additions and 128 deletions
@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-06-30-hook-protocol-lib.md
2026-06-30-hook-protocol-lib.md: a169b94611fa3f5b9606a100957b3146b662ee12
2026-06-30-hook-protocol-lib.zh.md: 56e32d36dbda882ce72026f8d9425aac5b97e9eb
2026-06-30-hook-protocol-lib.md: 611acd88547456514375e6850698c4c5d974c989
2026-06-30-hook-protocol-lib.zh.md: 28dce0365775b6142406ffdda82b643b5038e606
@@ -15,7 +15,7 @@ This Agent Note introduces `@deepseek-ai/dsh-hook-protocol`, a **library** (not
A new `packages/hooks/` group with `hook-protocol` as a pure library. It owns four primitive families and the `hook/*` session events; each bridge plugin (`dsh-hooks-claude`, `dsh-hooks-codex`) owns what genuinely differs.
**Shared (here):**
- **Matcher** — `matcherDiagnostic(pattern, mode)`, `compileMatchers(patterns, mode)`, and `matchesMatcher(pattern, query, mode)`. Pure `[A-Za-z0-9_|]+` patterns use the shared exact-match fast path (pipe = alternatives); the ONE remaining dialect axis is collapsed to `mode`: other Claude patterns use JavaScript `RegExp`, while other Codex patterns use Rust `regex`, including Rust-only syntax such as `(?i)`. Match-all on absent/`''`/`'*'`. Each bridge ignores unsupported events before group parsing, discards matcher fields on supported events without matcher subjects, validates the remaining runnable groups, and treats an invalid regex there as a whole-config load failure, with a stable dialect/pattern/event diagnostic; no hook listeners are registered. For runtime, a bridge compiles its finite set of unique config patterns ONCE, reuses that set across hook points, and disposes it after detached runs drain on plugin teardown. This config-scoped ownership avoids a module-global cache while preventing repeated Rust/WASM construction from raising a non-shrinking memory high-water mark on every match. The one-shot predicate still contains an invalid regex as a non-match, so a direct library caller never throws into the loop.
- **Matcher** — `compileMatchers(patterns, mode)`, `matcherDiagnostic(pattern, mode)`, and `matchesMatcher(pattern, query, mode)`. Pure `[A-Za-z0-9_|]+` patterns use the shared exact-match fast path (pipe = alternatives); the ONE remaining dialect axis is collapsed to `mode`: other Claude patterns use JavaScript `RegExp`, while other Codex patterns use Rust `regex`, including Rust-only syntax such as `(?i)`. Match-all on absent/`''`/`'*'`. Each bridge ignores unsupported events before group parsing, discards matcher fields on supported events without matcher subjects, collects the remaining runnable groups, and compiles their finite set of unique patterns ONCE. It reads validation diagnostics from that compiled registry: an invalid regex causes whole-config rejection after the registry is disposed, while a valid parse returns the SAME registry for hook-point matching and plugin-teardown disposal after detached runs drain. The stable diagnostic still names dialect/pattern/event and no hook listeners are registered on failure. This config-scoped ownership avoids both a module-global cache and separate validation/runtime Rust/WASM construction, whose non-shrinking allocator raises its memory high-water mark on every construction. The one-shot helpers remain contained, so a direct library caller never throws into the loop.
- **Execution** — `runHook(bash, hook, options)`. Runs a command hook through the `ctx.bash` seam rather than a bespoke `spawn`: the executor already provides the scrubbed-but-overridable env, process-group kills, and timeout the protocol needs, and `dsh-bash`'s `stdin`/`env` fields (added for exactly this) are the trusted-plugin surface an in-process bridge is allowed to use. It serializes the bridge-built payload to stdin (trailing newline iff CC), honors the hook's `timeoutSec` (else `DEFAULT_HOOK_TIMEOUT_MS`, the 10-minute reference default both dialects share), and never throws (an executor rejection becomes a non-blocking-error `HookOutput`).
- **Decode** — `parseHookOutput(exit, stdout, stderr)`, the exit-code + structured-stdout codec, producing a dialect-neutral `HookOutput`. Exit `0` → lenient JSON parse of stdout; exit `2` → blocking error with `stderr` as the reason (surfaced as `decision: 'block'` so no caller needs a separate exit-code branch); other → non-blocking error. Parses the CC structured-stdout fields that have a consumer on some path (`continue`/`stopReason`/`decision`/`hookSpecificOutput.{permissionDecision,additionalContext,updatedInput}`/`systemMessage`); the bridge honors only the subset meaningful for its dialect. Fields with no consumer on any path are not parsed at all (CC's `suppressOutput` — hook stdout never enters a transcript here, so there is nothing to suppress; see [the tighten-hook-protocol-contract Agent Note](../simplification/2026-07-04-tighten-hook-protocol-contract.md)).
- **Merge** — `mergeHookOutputs(outputs)`, folding multiple matched hooks into one most-restrictive `MergedHookOutcome`: permission precedence **deny > ask > allow**, halt sticky on the first `continue:false`, block reasons joined `\n\n`, context/system-messages accumulated in order.
@@ -15,7 +15,7 @@ Status: implemented
`packages/hooks/` 分组下新建 `hook-protocol` 作为纯库。它拥有四个原语族和 `hook/*` 会话事件;每个桥接插件(`dsh-hooks-claude``dsh-hooks-codex`)拥有真正不同的部分。
**共享(本库):**
- **Matcher** — `matcherDiagnostic(pattern, mode)``compileMatchers(patterns, mode)``matchesMatcher(pattern, query, mode)`。纯 `[A-Za-z0-9_|]+` pattern 使用共享的精确匹配快速路径(管道符 = 多选);剩余的唯一方言差异收敛为 `mode`:其他 Claude pattern 使用 JavaScript `RegExp`,其他 Codex pattern 使用 Rust `regex`,包括 `(?i)` 等 Rust 专属语法。缺省/`''`/`'*'` 匹配一切。每个桥接插件会在解析 group 前忽略不支持的事件,丢弃受支持但没有 matcher 匹配对象的事件所带 matcher 字段,再校验剩余的可运行 group;其中的无效正则会导致整份配置加载失败,并输出稳定的方言/模式/事件诊断,且不注册任何 hook 监听器。运行时,桥接会将配置中有限的唯一 pattern 集合只编译一次,在各 hook 点重复使用,并在插件 teardown 时先 drain 脱离运行,再释放该集合。这种配置作用域的所有权既避免模块全局缓存,也防止反复构造 RustWASM 正则在每次匹配时抬高且无法收缩的内存高水位。一次性谓词仍将无效正则收敛为不匹配,因此直接调用本库时绝不向 agent loop(智能体循环)抛异常。
- **Matcher** — `compileMatchers(patterns, mode)``matcherDiagnostic(pattern, mode)``matchesMatcher(pattern, query, mode)`。纯 `[A-Za-z0-9_|]+` pattern 使用共享的精确匹配快速路径(管道符 = 多选);剩余的唯一方言差异收敛为 `mode`:其他 Claude pattern 使用 JavaScript `RegExp`,其他 Codex pattern 使用 Rust `regex`,包括 `(?i)` 等 Rust 专属语法。缺省/`''`/`'*'` 匹配一切。每个桥接插件会在解析 group 前忽略不支持的事件,丢弃受支持但没有 matcher 匹配对象的事件所带字段,收集其余可运行 group,再将其中有限的唯一 pattern 集合只编译一次。它直接从该 registry 读取校验诊断:无效正则会在释放 registry 后导致整份配置加载失败;有效解析则把同一个 registry 交给各 hook 点匹配,并在插件 teardown 时先 drain 脱离运行,再释放它。稳定诊断仍包含方言/模式/事件,失败时不会注册任何 hook 监听器。这种配置作用域的所有权既避免模块全局缓存,也避免校验和运行时分别构造 RustWASM 正则;其无法收缩的分配器会在每次构造时抬高内存高水位。一次性 helper 仍是收敛的,因此直接调用本库时绝不向 agent loop(智能体循环)抛异常。
- **执行** — `runHook(bash, hook, options)`。通过 `ctx.bash` seam 而非自建 `spawn` 运行命令钩子:执行器已提供清洗但可覆盖的 env、进程组 kill 和超时,正是协议所需的能力;`dsh-bash``stdin`/`env` 字段(正是为此添加的)是进程内桥接插件被允许使用的受信插件接口。它将桥接插件构建的 payload 序列化到 stdin(CC 时追加尾部换行),遵守钩子的 `timeoutSec`(否则使用 `DEFAULT_HOOK_TIMEOUT_MS`,即两种方言共享的 10 分钟参考默认值),且从不抛异常(执行器拒绝变为 non-blocking-error 的 `HookOutput`)。
- **解码** — `parseHookOutput(exit, stdout, stderr)`exit-code + structured-stdout 编解码器,产出方言无关的 `HookOutput`。Exit `0` → 宽松 JSON 解析 stdoutexit `2` → blocking error`stderr` 为原因(以 `decision: 'block'` 呈现,调用方无需单独处理 exit-code 分支);其他 → non-blocking error。解析 CC structured-stdout 中在某条路径上有消费方的字段(`continue`/`stopReason`/`decision`/`hookSpecificOutput.{permissionDecision,additionalContext,updatedInput}`/`systemMessage`);桥接插件只采纳对其方言有意义的子集。在任何路径上都没有消费方的字段不予解析(CC 的 `suppressOutput`——钩子 stdout 在此处从不进入 transcript(文本记录),因此无需抑制;见 [收紧钩子协议契约 Agent Note](../simplification/2026-07-04-tighten-hook-protocol-contract.md))。
- **合并** — `mergeHookOutputs(outputs)`,将多个匹配钩子的输出折叠为一个最严格的 `MergedHookOutcome`:权限优先级 **deny > ask > allow**halt 在首个 `continue:false` 时粘滞,阻止原因以 `\n\n` 拼接,context/system-messages 按序累积。
+2 -2
View File
@@ -478,7 +478,7 @@ export interface Config {
}
```
Source: [`packages/hooks/hooks-claude/src/index.ts:46`](../packages/hooks/hooks-claude/src/index.ts)
Source: [`packages/hooks/hooks-claude/src/index.ts:45`](../packages/hooks/hooks-claude/src/index.ts)
## `@deepseek-ai/dsh-hooks-codex`
@@ -503,7 +503,7 @@ export interface Config {
}
```
Source: [`packages/hooks/hooks-codex/src/index.ts:45`](../packages/hooks/hooks-codex/src/index.ts)
Source: [`packages/hooks/hooks-codex/src/index.ts:44`](../packages/hooks/hooks-codex/src/index.ts)
## `@deepseek-ai/dsh-host-apiproxy`
@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write packages/hooks/hook-protocol/README.md
README.md: 1b4c6c3b73b0d4f3d5df06405d27b94652b6c686
README.zh.md: 5b55034ff136129f83ae90a84b8efc89affcfce0
README.md: 36607ed9b98a97288690c869e58ee1d45ba765c4
README.zh.md: 5e1abce23aea65f670bde8c8c5d74c40f6afd07e
+2 -2
View File
@@ -10,7 +10,7 @@ Why a shared lib at all: Codex deliberately reimplements a *subset* of the Claud
| Concern | Here (`dsh-hook-protocol`) | The bridge (`dsh-hooks-claude` / `-codex`) |
|---|---|---|
| Matcher validation + test | `matcherDiagnostic(pattern, mode)` for parse-time diagnostics; `compileMatchers(patterns, mode)` for repeated config-lifetime matching; `matchesMatcher(pattern, query, mode)` for one-shot contained matching | picks its native regex `mode` (`claude` = JavaScript, `codex` = Rust `regex`), rejects a config group carrying a diagnostic, and disposes the compiled set on teardown |
| Matcher validation + test | `compileMatchers(patterns, mode)` exposes diagnostics and repeated config-lifetime matching from one compiled set; `matcherDiagnostic` / `matchesMatcher` are contained one-shot helpers | picks its native regex `mode` (`claude` = JavaScript, `codex` = Rust `regex`), compiles the unique runnable patterns once, rejects a group carrying a registry diagnostic, and disposes that same set on failure or teardown |
| Run a hook | `runHook(bash, hook, opts, now)` — stdin payload + env via `ctx.bash`, decode | builds the per-event stdin **payload** + the dialect's **env** |
| Decode output | `parseHookOutput(exit, stdout, stderr)` → neutral `HookOutput` | maps the neutral `HookOutput` onto a seam-specific typed Decision |
| Merge N hooks | `mergeHookOutputs(outputs)` → most-restrictive `MergedHookOutcome` | — |
@@ -19,7 +19,7 @@ Why a shared lib at all: Codex deliberately reimplements a *subset* of the Claud
## Primitives
- **`matcherDiagnostic(matcher, mode)` / `compileMatchers(matchers, mode)` / `matchesMatcher(matcher, query, mode)`** — match-all on absent/`''`/`'*'`; both dialects treat a pure `[A-Za-z0-9_|]+` pattern as exact pipe-separated alternatives. Other patterns are unanchored regexes compiled in the native dialect: JavaScript for Claude Code, Rust `regex` for Codex (including inline flags such as `(?i)`). Bridge parsers discard matcher fields for events without matcher subjects, then use `matcherDiagnostic` to reject an invalid consumed regex with a stable diagnostic before registering any hooks. Each bridge uses `compileMatchers` to compile every unique config pattern once, reuses it at every hook point, and disposes the finite set after detached runs drain on plugin teardown; this avoids the Rust/WASM allocator's non-shrinking high-water mark growing on every match. `matchesMatcher` remains the contained one-shot predicate, and invalid runtime patterns are non-matches rather than exceptions.
- **`compileMatchers(matchers, mode)` / `matcherDiagnostic(matcher, mode)` / `matchesMatcher(matcher, query, mode)`** — match-all on absent/`''`/`'*'`; both dialects treat a pure `[A-Za-z0-9_|]+` pattern as exact pipe-separated alternatives. Other patterns are unanchored regexes compiled in the native dialect: JavaScript for Claude Code, Rust `regex` for Codex (including inline flags such as `(?i)`). A bridge parser first discards matcher fields for events without matcher subjects and collects the remaining runnable groups, then compiles their unique patterns once. It reads `registry.diagnostic(pattern)` from those exact instances, disposes the registry before throwing on an invalid consumed regex, or returns the same registry for runtime matching. The plugin reuses it at every hook point and disposes it after detached runs drain on teardown. Thus neither validation nor matching reconstructs a Rust/WASM regex and raises its non-shrinking memory high-water mark. `matcherDiagnostic` and `matchesMatcher` remain contained one-shot helpers; invalid runtime patterns are non-matches rather than exceptions.
- **`runHook(bash, hook, options, now)`** — require and forward the caller-owned `options.signal`, serialize `options.payload` to the hook's stdin (with a trailing newline iff `options.trailingNewline`), merge `options.env` after the executor's credential scrub (the `dsh-bash` trusted-plugin surface), honor the hook's `timeoutSec` (else `options.defaultTimeoutMs` — the bridge owns the default, its config defaulting to the lib's `DEFAULT_HOOK_TIMEOUT_MS` 10-minute reference), and decode the result (threading `options.expectedEventName` to the codec). Cancellation therefore reaches the executor's process-group kill and join boundary. Never throws: an executor rejection (infra fault) becomes a `HookOutput` with `exitCode: undefined` (a non-blocking error). `now` is injected for testable durations.
- **`parseHookOutput(exitCode, stdout, stderr, expectedEventName?)`** decodes exit status and structured stdout. Exit 2 blocks with stderr; other failures are non-blocking. A matching hook-specific permission decision overrides the legacy top-level decision; mismatched or missing event discriminators suppress only event-specific fields. Top-level fields remain event-agnostic, and successful non-JSON output is left to the bridge.
- **`mergeHookOutputs(outputs)`** — fold the results of every hook that matched one point: permission precedence **deny > ask > allow**, halt sticky on the first `continue:false`, block reasons joined with `\n\n`, `additionalContext`/`systemMessages` accumulated in order.
+2 -2
View File
@@ -10,7 +10,7 @@ Claude CodeCodex hook 协议格式的**共享核心**。它不是 cordis 插
| 关注点 | 此处(`dsh-hook-protocol` | 桥接(`dsh-hooks-claude` / `-codex` |
|---|---|---|
| Matcher 校验 + 测试 | `matcherDiagnostic(pattern, mode)` 用于解析时诊断;`compileMatchers(patterns, mode)` 用于配置生命周期内的重复匹配;`matchesMatcher(pattern, query, mode)` 用于一次性的收敛匹配 | 选择自身原生正则 `mode``claude` = JavaScript`codex` = Rust `regex`),拒绝带有诊断的配置组,并在 teardown 时释放已编译集合 |
| Matcher 校验 + 测试 | `compileMatchers(patterns, mode)` 从同一已编译集合提供诊断与配置生命周期内的重复匹配;`matcherDiagnostic``matchesMatcher` 是收敛的一次性 helper | 选择自身原生正则 `mode``claude` = JavaScript`codex` = Rust `regex`),将可运行的唯一 pattern 只编译一次,拒绝带有 registry 诊断的配置组,并在失败或 teardown 时释放同一集合 |
| 运行 hook | `runHook(bash, hook, opts, now)`:通过 `ctx.bash` 提供 stdin payload + env,再解码 | 构造每个事件的 stdin **payload** + 该方言的 **env** |
| 解码输出 | `parseHookOutput(exit, stdout, stderr)` → 中性 `HookOutput` | 将中性 `HookOutput` 映射到 seam 特定的类型化 Decision |
| 合并 N 个 hook | `mergeHookOutputs(outputs)` → 最严格的 `MergedHookOutcome` | (无) |
@@ -19,7 +19,7 @@ Claude CodeCodex hook 协议格式的**共享核心**。它不是 cordis 插
## 原语
- **`matcherDiagnostic(matcher, mode)` / `compileMatchers(matchers, mode)` / `matchesMatcher(matcher, query, mode)`**:缺失、`''``'*'` 时匹配全部;两种方言都将纯 `[A-Za-z0-9_|]+` pattern 视为按 pipe 分隔的精确多选。其他 pattern 会用原生方言编译为未锚定正则:Claude Code 使用 JavaScriptCodex 使用 Rust `regex`(包括 `(?i)` 等内联 flag)。桥接解析器会丢弃没有 matcher 匹配对象的事件所带 matcher 字段,再使用 `matcherDiagnostic` 在注册任何 hook 之前拒绝实际会被消费的无效正则,并输出稳定诊断。每个桥接通过 `compileMatchers` 将配置中每个唯一 pattern 只编译一次,在各 hook 点重复使用,并在插件 teardown 时先 drain 脱离运行,再释放这个有限集合因此 Rust/WASM 分配器不会因每次匹配都抬高无法收缩的内存高水位。`matchesMatcher` 保留为收敛的一次性谓词,运行时无效 pattern 仍是不匹配而非异常。
- **`compileMatchers(matchers, mode)` / `matcherDiagnostic(matcher, mode)` / `matchesMatcher(matcher, query, mode)`**:缺失、`''``'*'` 时匹配全部;两种方言都将纯 `[A-Za-z0-9_|]+` pattern 视为按 pipe 分隔的精确多选。其他 pattern 会用原生方言编译为未锚定正则:Claude Code 使用 JavaScriptCodex 使用 Rust `regex`(包括 `(?i)` 等内联 flag)。桥接解析器会丢弃没有 matcher 匹配对象的事件所带字段,收集其余可运行 group,再将它们的唯一 pattern 只编译一次。解析器直接从这些实例读取 `registry.diagnostic(pattern)`;实际消费的正则无效时,会先释放 registry 再抛错,否则把同一 registry 交给运行时。插件会在各 hook 点重复使用,并在 teardown 时先 drain 脱离运行,再释放集合因此校验和匹配都不会重复构造 Rust/WASM 正则并抬高无法收缩的内存高水位。`matcherDiagnostic``matchesMatcher` 保留为收敛的一次性 helper运行时无效 pattern 仍是不匹配而非异常。
- **`runHook(bash, hook, options, now)`**:要求并转发调用方拥有的 `options.signal`,将 `options.payload` 序列化到 hook stdin(当且仅当 `options.trailingNewline` 时添加尾随换行符),在执行器凭证清理后合并 `options.env``dsh-bash` 受信任插件表层),遵循 hook 的 `timeoutSec`(否则使用 `options.defaultTimeoutMs`;默认值属于桥接,其配置默认为 lib 的 `DEFAULT_HOOK_TIMEOUT_MS` 10 分钟参考值),再解码结果(将 `options.expectedEventName` 传递给 codec)。因此取消会到达执行器的进程组终止与 join 边界。它绝不抛出异常:执行器拒绝(基础设施故障)会变为 `HookOutput`,其 `exitCode: undefined`(非阻塞错误)。`now` 会被注入,以便测试持续时间。
- **`parseHookOutput(exitCode, stdout, stderr, expectedEventName?)`** 解码退出状态与结构化 stdout。退出码 2 使用 stderr 阻塞;其他失败不阻塞。匹配的 hook 特定权限决策会覆盖遗留顶层决策;事件判别字段不匹配或缺失只会抑制事件特定字段。顶层字段仍与事件无关,成功但非 JSON 的输出会留给桥接处理。
- **`mergeHookOutputs(outputs)`**:折叠在一个点上匹配的每个 hook 结果:权限优先级为 **deny > ask > allow**,首个 `continue:false` 使 halt 粘滞,阻塞原因用 `\n\n` 连接,`additionalContext``systemMessages` 按顺序累积。
+22 -10
View File
@@ -3,8 +3,8 @@
* pipe patterns as literal alternatives and other patterns as regex. Codex
* uses the same literal fast path, then compiles regex patterns with Rust's
* `regex` dialect. Missing, empty, and `*` match all. Runtime matching contains
* invalid regexes as non-matches; config parsers use {@link matcherDiagnostic}
* to reject them with a diagnostic.
* invalid regexes as non-matches. A compiled config registry exposes the same
* stable diagnostic without constructing a second native regex.
* @module @deepseek-ai/dsh-hook-protocol/matcher
*/
@@ -30,6 +30,7 @@ const EXACT_MATCHER = /^[A-Za-z0-9_|]+$/
interface CompiledMatcher {
matches(query: string): boolean
diagnostic?: string
dispose(): void
}
@@ -37,6 +38,8 @@ interface CompiledMatcher {
export interface CompiledMatchers {
/** Match one of the patterns supplied to {@link compileMatchers}. */
matches(matcher: string | undefined, query: string): boolean
/** Diagnose one supplied pattern using the already-compiled instance. */
diagnostic(matcher: string | undefined): string | undefined
/** Release every native matcher. Safe to call more than once. */
dispose(): void
}
@@ -66,7 +69,13 @@ function compileMatcher(matcher: string | undefined, mode: MatcherMode): Compile
return { matches: query => alternatives.has(query), dispose: () => {} }
}
const regex = compileRegex(pattern, mode)
if (regex === undefined) return { matches: () => false, dispose: () => {} }
if (regex === undefined) {
return {
matches: () => false,
diagnostic: `invalid ${mode} regex matcher ${JSON.stringify(pattern)}`,
dispose: () => {},
}
}
return {
matches: query => regex instanceof RRegex ? regex.isMatch(query) : regex.test(query),
dispose: () => { disposeRegex(regex) },
@@ -92,6 +101,10 @@ export function compileMatchers(matchers: Iterable<string | undefined>, mode: Ma
if (disposed) return false
return compiled.get(matcher)?.matches(query) ?? false
},
diagnostic(matcher) {
if (disposed) return undefined
return compiled.get(matcher)?.diagnostic
},
dispose() {
if (disposed) return
disposed = true
@@ -108,13 +121,12 @@ export function compileMatchers(matchers: Iterable<string | undefined>, mode: Ma
* @returns `undefined` for a valid matcher, otherwise a stable diagnostic.
*/
export function matcherDiagnostic(matcher: string | undefined, mode: MatcherMode): string | undefined {
if (isMatchAll(matcher)) return undefined
const pattern = matcher as string
if (EXACT_MATCHER.test(pattern)) return undefined
const regex = compileRegex(pattern, mode)
if (regex === undefined) return `invalid ${mode} regex matcher ${JSON.stringify(pattern)}`
disposeRegex(regex)
return undefined
const compiled = compileMatcher(matcher, mode)
try {
return compiled.diagnostic
} finally {
compiled.dispose()
}
}
/**
@@ -30,6 +30,7 @@ describe('compileMatchers — native regex lifecycle', () => {
expect(construct.mock.calls.map(([pattern]) => pattern)).toEqual(['(?i)^bash$', '^write$'])
for (let i = 0; i < 1_000; i++) {
expect(matchers.diagnostic('(?i)^bash$')).toBeUndefined()
expect(matchers.matches('(?i)^bash$', 'BASH')).toBe(true)
}
expect(construct).toHaveBeenCalledTimes(2)
@@ -93,10 +93,14 @@ describe('compileMatchers — config-lifetime reuse', () => {
expect(matchers.matches('(?i)^bash$', 'BASH')).toBe(true)
expect(matchers.matches('[', 'anything')).toBe(false)
expect(matchers.matches('not-compiled', 'not-compiled')).toBe(false)
expect(matchers.diagnostic('(?i)^bash$')).toBeUndefined()
expect(matchers.diagnostic('[')).toBe('invalid codex regex matcher "["')
expect(matchers.diagnostic('not-compiled')).toBeUndefined()
matchers.dispose()
expect(matchers.matches(undefined, 'anything')).toBe(false)
expect(matchers.matches('(?i)^bash$', 'BASH')).toBe(false)
expect(matchers.diagnostic('[')).toBeUndefined()
expect(() => { matchers.dispose() }).not.toThrow()
})
+52 -34
View File
@@ -6,7 +6,11 @@
* @module @deepseek-ai/dsh-hooks-claude/config
*/
import { matcherDiagnostic, type MatcherGroup } from '@deepseek-ai/dsh-hook-protocol'
import {
compileMatchers,
type CompiledMatchers,
type MatcherGroup,
} from '@deepseek-ai/dsh-hook-protocol'
const CLAUDE_EVENTS = [
'SessionStart',
@@ -31,6 +35,8 @@ export interface SkippedHook {
export interface ParsedClaudeConfig {
config: ClaudeHookConfig
skipped: SkippedHook[]
/** Config-scoped matcher registry; the caller owns and must dispose it. */
matchers: CompiledMatchers
}
/** Substitution variables applied to each `command` string at parse time. */
@@ -68,6 +74,7 @@ export function substituteCommand(command: string, vars: SubstitutionVars): stri
* command. Matcher fields on UserPromptSubmit and Stop are discarded because those events have no
* matcher subject. A matcher-bearing supported runnable group with an invalid regex throws a
* `SyntaxError`, allowing the bridge to reject the complete config before listener registration.
* Validation and runtime matching share the returned compiled registry; its caller must dispose it.
*
* @param raw - the parsed JSON config: a settings object with a `hooks` key, or the bare
* event map.
@@ -81,43 +88,54 @@ export function parseClaudeConfig(raw: unknown, vars: SubstitutionVars = {}): Pa
// Accept either `{ hooks: { … } }` (a settings file) or the bare event map.
const root = asObject(raw)
const hooksMap = root ? asObject(root.hooks) ?? root : undefined
if (!hooksMap) return { config, skipped }
for (const event of CLAUDE_EVENTS) {
const rawGroups = hooksMap[event]
if (!Array.isArray(rawGroups)) continue
const groups: MatcherGroup[] = []
for (const rawGroup of rawGroups) {
const group = asObject(rawGroup)
if (!group || !Array.isArray(group.hooks)) continue
const commands: MatcherGroup['hooks'] = []
for (const rawHook of group.hooks) {
const hook = asObject(rawHook)
if (!hook) continue
const type = typeof hook.type === 'string' ? hook.type : 'command'
if (type !== 'command') {
skipped.push({ event, type })
continue
if (hooksMap) {
for (const event of CLAUDE_EVENTS) {
const rawGroups = hooksMap[event]
if (!Array.isArray(rawGroups)) continue
const groups: MatcherGroup[] = []
for (const rawGroup of rawGroups) {
const group = asObject(rawGroup)
if (!group || !Array.isArray(group.hooks)) continue
const commands: MatcherGroup['hooks'] = []
for (const rawHook of group.hooks) {
const hook = asObject(rawHook)
if (!hook) continue
const type = typeof hook.type === 'string' ? hook.type : 'command'
if (type !== 'command') {
skipped.push({ event, type })
continue
}
if (typeof hook.command !== 'string') continue
commands.push({
command: substituteCommand(hook.command, vars),
...typeof hook.timeout === 'number' ? { timeoutSec: hook.timeout } : {},
})
}
if (typeof hook.command !== 'string') continue
commands.push({
command: substituteCommand(hook.command, vars),
...typeof hook.timeout === 'number' ? { timeoutSec: hook.timeout } : {},
if (commands.length === 0) continue
const matcher = event === 'UserPromptSubmit' || event === 'Stop'
? undefined
: typeof group.matcher === 'string' ? group.matcher : undefined
groups.push({
...matcher !== undefined ? { matcher } : {},
hooks: commands,
})
}
if (commands.length === 0) continue
const matcher = event === 'UserPromptSubmit' || event === 'Stop'
? undefined
: typeof group.matcher === 'string' ? group.matcher : undefined
const diagnostic = matcherDiagnostic(matcher, 'claude')
if (diagnostic !== undefined) throw new SyntaxError(`${diagnostic} on event ${JSON.stringify(event)}`)
groups.push({
...matcher !== undefined ? { matcher } : {},
hooks: commands,
})
if (groups.length > 0) config[event] = groups
}
if (groups.length > 0) config[event] = groups
}
return { config, skipped }
/* jscpd:ignore-start -- dialect-local event diagnostics intentionally stay beside parsing. */
const entries = Object.entries(config).flatMap(([event, groups]) => (
groups.map(group => ({ event, matcher: group.matcher }))
))
const matchers = compileMatchers(new Set(entries.map(entry => entry.matcher)), 'claude')
for (const { event, matcher } of entries) {
const diagnostic = matchers.diagnostic(matcher)
if (diagnostic === undefined) continue
matchers.dispose()
throw new SyntaxError(`${diagnostic} on event ${JSON.stringify(event)}`)
}
/* jscpd:ignore-end */
return { config, skipped, matchers }
}
+11 -12
View File
@@ -21,7 +21,6 @@ import type { PostToolDecision, PreToolDecision, ToolExecution, ToolExecutionRes
import {
appendHookInvoked,
appendHookResult,
compileMatchers,
createDetachedRuns,
DEFAULT_HOOK_TIMEOUT_MS,
DEFAULT_STDERR_SUMMARY_MAX_CHARS,
@@ -35,7 +34,7 @@ import {
// declarations (declaration-merged into cordis `Events` by dsh-subagent) so the
// SubagentStart/SubagentStop listeners below type-check.
import type {} from '@deepseek-ai/dsh-subagent'
import { parseClaudeConfig, type ClaudeHookConfig } from './config.ts'
import { parseClaudeConfig, type ParsedClaudeConfig } from './config.ts'
export const name = 'hooks-claude'
// `bash` is required to run hooks; the rest are read opportunistically via
@@ -100,26 +99,22 @@ export function apply(ctx: Context, config: Config): void {
assertPositiveInteger('stderrSummaryMaxChars', stderrSummaryMaxChars)
const defaultTimeoutMs = config.defaultTimeoutMs ?? DEFAULT_HOOK_TIMEOUT_MS
// Parse once at load. A read or parse failure logs and registers nothing.
let parsed: ClaudeHookConfig = {}
let result: ParsedClaudeConfig
try {
const raw: unknown = JSON.parse(readFileSync(config.configPath, 'utf8'))
const result = parseClaudeConfig(raw, {
result = parseClaudeConfig(raw, {
...config.pluginRoot !== undefined ? { pluginRoot: config.pluginRoot } : {},
...config.projectDir !== undefined ? { projectDir: config.projectDir } : {},
})
parsed = result.config
for (const s of result.skipped) {
ctx.logger.warn(`hooks-claude: skipping unsupported "${s.type}" hook on ${s.event} (only command hooks run)`)
}
} catch (error: unknown) {
ctx.logger.warn(`hooks-claude: could not load hook config "${config.configPath}": ${String(error)} — no hooks registered`)
return
}
const matchers = compileMatchers(
Object.values(parsed).flatMap(groups => groups.map(group => group.matcher)),
'claude',
)
const parsed = result.config
// Parsing validates through this same registry, so admission and runtime do
// not construct separate matcher instances.
const matchers = result.matchers
// Emit-shaped points run detached, so track their chains; disposal aborts
// active hooks and drains continuations before releasing matchers.
@@ -132,6 +127,10 @@ export function apply(ctx: Context, config: Config): void {
}
}, 'hooks-claude: drain detached hook runs and dispose matchers')
for (const s of result.skipped) {
ctx.logger.warn(`hooks-claude: skipping unsupported "${s.type}" hook on ${s.event} (only command hooks run)`)
}
/**
* Run every command hook configured for `point` whose matcher selects
* `matchQuery`, with the per-event `payload` on stdin, and fold the results.
@@ -1,5 +1,14 @@
import { describe, expect, it } from 'vitest'
import { parseClaudeConfig, substituteCommand } from '@deepseek-ai/dsh-hooks-claude/src/config.ts'
import { afterEach, describe, expect, it } from 'vitest'
import { parseClaudeConfig as parseRawClaudeConfig, substituteCommand } from '@deepseek-ai/dsh-hooks-claude/src/config.ts'
const matcherSets: Array<ReturnType<typeof parseRawClaudeConfig>['matchers']> = []
afterEach(() => { for (const matchers of matcherSets.splice(0)) matchers.dispose() })
function parseClaudeConfig(...args: Parameters<typeof parseRawClaudeConfig>): ReturnType<typeof parseRawClaudeConfig> {
const result = parseRawClaudeConfig(...args)
matcherSets.push(result.matchers)
return result
}
describe('substituteCommand', () => {
it('replaces CLAUDE_PLUGIN_ROOT and CLAUDE_PROJECT_DIR (all occurrences)', () => {
@@ -64,6 +73,13 @@ describe('parseClaudeConfig', () => {
expect('matcher' in config.Stop![0]!).toBe(false)
})
it('returns the same validated matcher registry for runtime use', () => {
const { matchers } = parseClaudeConfig({
PreToolUse: [{ matcher: '^Bash$', hooks: [{ type: 'command', command: 'x.sh' }] }],
})
expect(matchers.matches('^Bash$', 'Bash')).toBe(true)
})
it('rejects an invalid regex matcher with its event name', () => {
expect(() => parseClaudeConfig({
PreToolUse: [{ matcher: '(', hooks: [{ type: 'command', command: 'x.sh' }] }],
+52 -36
View File
@@ -5,7 +5,11 @@
* @module @deepseek-ai/dsh-hooks-codex/config
*/
import { matcherDiagnostic, type MatcherGroup } from '@deepseek-ai/dsh-hook-protocol'
import {
compileMatchers,
type CompiledMatchers,
type MatcherGroup,
} from '@deepseek-ai/dsh-hook-protocol'
/** The five Codex hook points this bridge supports. */
export const CODEX_EVENTS = ['PreToolUse', 'PostToolUse', 'SessionStart', 'UserPromptSubmit', 'Stop'] as const
@@ -23,6 +27,8 @@ export interface SkippedHook {
export interface ParsedCodexConfig {
config: CodexHookConfig
skipped: SkippedHook[]
/** Config-scoped matcher registry; the caller owns and must dispose it. */
matchers: CompiledMatchers
}
function asObject(value: unknown): Record<string, unknown> | undefined {
@@ -36,7 +42,8 @@ function asObject(value: unknown): Record<string, unknown> | undefined {
* than failing boot; unsupported or asynchronous hooks are returned in `skipped`. Matcher fields on
* UserPromptSubmit and Stop are discarded because those events have no matcher subject. A
* matcher-bearing runnable group with an invalid regex throws a `SyntaxError`, allowing the bridge
* to reject the complete config before listener registration.
* to reject the complete config before listener registration. Validation and runtime matching
* share the returned compiled registry; its caller must dispose it.
* @param raw - the parsed JSON config: a `{ hooks: … }` wrapper or the bare event map.
* @returns the runnable per-event groups plus the skipped hooks with their reasons.
*/
@@ -45,42 +52,51 @@ export function parseCodexConfig(raw: unknown): ParsedCodexConfig {
const skipped: SkippedHook[] = []
const root = asObject(raw)
const hooksMap = root ? asObject(root.hooks) ?? root : undefined
if (!hooksMap) return { config, skipped }
for (const event of CODEX_EVENTS) {
const rawGroups = hooksMap[event]
// Matcher-group parsing remains dialect-local because the supported hook
// shapes and skip reasons differ from Claude Code's.
/* jscpd:ignore-start */
if (!Array.isArray(rawGroups)) continue
const groups: MatcherGroup[] = []
for (const rawGroup of rawGroups) {
const group = asObject(rawGroup)
if (!group || !Array.isArray(group.hooks)) continue
const commands: MatcherGroup['hooks'] = []
for (const rawHook of group.hooks) {
const hook = asObject(rawHook)
if (!hook) continue
const type = typeof hook.type === 'string' ? hook.type : 'command'
if (type !== 'command') { skipped.push({ event, reason: `unsupported "${type}" hook` }); continue }
/* jscpd:ignore-end */
if (hook.async === true) { skipped.push({ event, reason: 'async hook' }); continue }
if (typeof hook.command !== 'string') continue
// Codex accepts `timeout` or the `timeoutSec` alias.
const timeout = typeof hook.timeout === 'number' ? hook.timeout
: typeof hook.timeoutSec === 'number' ? hook.timeoutSec : undefined
commands.push({ command: hook.command, ...timeout !== undefined ? { timeoutSec: timeout } : {} })
if (hooksMap) {
for (const event of CODEX_EVENTS) {
const rawGroups = hooksMap[event]
// Matcher-group parsing remains dialect-local because the supported hook
// shapes and skip reasons differ from Claude Code's.
/* jscpd:ignore-start */
if (!Array.isArray(rawGroups)) continue
const groups: MatcherGroup[] = []
for (const rawGroup of rawGroups) {
const group = asObject(rawGroup)
if (!group || !Array.isArray(group.hooks)) continue
const commands: MatcherGroup['hooks'] = []
for (const rawHook of group.hooks) {
const hook = asObject(rawHook)
if (!hook) continue
const type = typeof hook.type === 'string' ? hook.type : 'command'
if (type !== 'command') { skipped.push({ event, reason: `unsupported "${type}" hook` }); continue }
/* jscpd:ignore-end */
if (hook.async === true) { skipped.push({ event, reason: 'async hook' }); continue }
if (typeof hook.command !== 'string') continue
// Codex accepts `timeout` or the `timeoutSec` alias.
const timeout = typeof hook.timeout === 'number' ? hook.timeout
: typeof hook.timeoutSec === 'number' ? hook.timeoutSec : undefined
commands.push({ command: hook.command, ...timeout !== undefined ? { timeoutSec: timeout } : {} })
}
if (commands.length === 0) continue
const matcher = event === 'UserPromptSubmit' || event === 'Stop'
? undefined
: typeof group.matcher === 'string' ? group.matcher : undefined
groups.push({ ...matcher !== undefined ? { matcher } : {}, hooks: commands })
}
if (commands.length === 0) continue
const matcher = event === 'UserPromptSubmit' || event === 'Stop'
? undefined
: typeof group.matcher === 'string' ? group.matcher : undefined
const diagnostic = matcherDiagnostic(matcher, 'codex')
if (diagnostic !== undefined) throw new SyntaxError(`${diagnostic} on event ${JSON.stringify(event)}`)
groups.push({ ...matcher !== undefined ? { matcher } : {}, hooks: commands })
if (groups.length > 0) config[event] = groups
}
if (groups.length > 0) config[event] = groups
}
return { config, skipped }
const entries = Object.entries(config).flatMap(([event, groups]) => (
groups.map(group => ({ event, matcher: group.matcher }))
))
const matchers = compileMatchers(new Set(entries.map(entry => entry.matcher)), 'codex')
for (const { event, matcher } of entries) {
const diagnostic = matchers.diagnostic(matcher)
if (diagnostic === undefined) continue
matchers.dispose()
throw new SyntaxError(`${diagnostic} on event ${JSON.stringify(event)}`)
}
return { config, skipped, matchers }
}
+11 -16
View File
@@ -25,7 +25,6 @@ import type { PostToolDecision, PreToolDecision, ToolExecution, ToolExecutionRes
import {
appendHookInvoked,
appendHookResult,
compileMatchers,
createDetachedRuns,
DEFAULT_HOOK_TIMEOUT_MS,
DEFAULT_STDERR_SUMMARY_MAX_CHARS,
@@ -35,7 +34,7 @@ import {
type MatcherGroup,
type MergedHookOutcome,
} from '@deepseek-ai/dsh-hook-protocol'
import { parseCodexConfig, type CodexHookConfig } from './config.ts'
import { parseCodexConfig, type ParsedCodexConfig } from './config.ts'
/* jscpd:ignore-end */
export const name = 'hooks-codex'
@@ -84,28 +83,20 @@ export function apply(ctx: Context, config: Config): void {
const stderrSummaryMaxChars = config.stderrSummaryMaxChars ?? DEFAULT_STDERR_SUMMARY_MAX_CHARS
assertPositiveInteger('stderrSummaryMaxChars', stderrSummaryMaxChars)
const defaultTimeoutMs = config.defaultTimeoutMs ?? DEFAULT_HOOK_TIMEOUT_MS
let parsed: CodexHookConfig = {}
let result: ParsedCodexConfig
try {
const raw: unknown = JSON.parse(readFileSync(config.configPath, 'utf8'))
const result = parseCodexConfig(raw)
parsed = result.config
for (const s of result.skipped) {
ctx.logger.warn(`hooks-codex: skipping ${s.reason} on ${s.event} (only sync command hooks run)`)
}
result = parseCodexConfig(raw)
} catch (error: unknown) {
ctx.logger.warn(`hooks-codex: could not load hook config "${config.configPath}": ${String(error)} — no hooks registered`)
return
}
const parsed = result.config
const model = config.model ?? ''
// Compile each distinct config matcher once. In particular, rebuilding an
// rregex WASM value on every hook point permanently raises the module's WASM
// memory high-water mark even when each value is freed.
const matchers = compileMatchers(
Object.values(parsed).flatMap(groups => groups.map(group => group.matcher)),
'codex',
)
// Parsing validates through this same registry, so no native regex is rebuilt
// between config admission and runtime matching.
const matchers = result.matchers
// SessionStart is the one emit-shaped (detached) point Codex has: track its
// run chains so disposal aborts a still-running hook process and drains the
@@ -120,6 +111,10 @@ export function apply(ctx: Context, config: Config): void {
}
}, 'hooks-codex: drain detached hook runs and dispose matchers')
for (const s of result.skipped) {
ctx.logger.warn(`hooks-codex: skipping ${s.reason} on ${s.event} (only sync command hooks run)`)
}
/**
* Run and fold one configured Codex hook point.
*
@@ -1,5 +1,14 @@
import { describe, expect, it } from 'vitest'
import { parseCodexConfig, CODEX_EVENTS } from '@deepseek-ai/dsh-hooks-codex/src/config.ts'
import { afterEach, describe, expect, it } from 'vitest'
import { parseCodexConfig as parseRawCodexConfig, CODEX_EVENTS } from '@deepseek-ai/dsh-hooks-codex/src/config.ts'
const matcherSets: Array<ReturnType<typeof parseRawCodexConfig>['matchers']> = []
afterEach(() => { for (const matchers of matcherSets.splice(0)) matchers.dispose() })
function parseCodexConfig(...args: Parameters<typeof parseRawCodexConfig>): ReturnType<typeof parseRawCodexConfig> {
const result = parseRawCodexConfig(...args)
matcherSets.push(result.matchers)
return result
}
describe('parseCodexConfig', () => {
it('honors only the five bridge-supported Codex events, dropping the rest', () => {
@@ -62,8 +71,9 @@ describe('parseCodexConfig', () => {
})
it('keeps a valid Rust-regex matcher when present', () => {
const { config } = parseCodexConfig({ PreToolUse: [{ matcher: '(?i)^bash$', hooks: [{ type: 'command', command: 'b.sh' }] }] })
const { config, matchers } = parseCodexConfig({ PreToolUse: [{ matcher: '(?i)^bash$', hooks: [{ type: 'command', command: 'b.sh' }] }] })
expect(config.PreToolUse![0]!.matcher).toBe('(?i)^bash$')
expect(matchers.matches('(?i)^bash$', 'BASH')).toBe(true)
})
it('rejects an invalid regex matcher with its event name', () => {
@@ -9,6 +9,7 @@ import LocalSubprocessService from '@deepseek-ai/dsh-subprocess-local'
const matcherLifecycle = vi.hoisted(() => {
const registry = {
matches: vi.fn(() => true),
diagnostic: vi.fn<(matcher: string | undefined) => string | undefined>(() => undefined),
dispose: vi.fn<() => void>(),
}
return {
@@ -26,9 +27,30 @@ const dirs: string[] = []
afterEach(() => {
for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true })
vi.clearAllMocks()
matcherLifecycle.registry.diagnostic.mockReturnValue(undefined)
})
describe('hooks-codex matcher lifecycle', () => {
it('disposes the compiled set when one event-specific diagnostic rejects the config', async () => {
const { parseCodexConfig } = await import('@deepseek-ai/dsh-hooks-codex/src/config.ts')
matcherLifecycle.registry.diagnostic.mockImplementation((matcher: string | undefined) => (
matcher === '[' ? 'invalid codex regex matcher "["' : undefined
))
expect(() => parseCodexConfig({
PreToolUse: [
{ matcher: '(?i)^bash$', hooks: [{ type: 'command', command: 'first' }] },
{ matcher: '[', hooks: [{ type: 'command', command: 'second' }] },
],
})).toThrow('invalid codex regex matcher "[" on event "PreToolUse"')
expect(matcherLifecycle.compileMatchers).toHaveBeenCalledExactlyOnceWith(
new Set(['(?i)^bash$', '[']),
'codex',
)
expect(matcherLifecycle.registry.dispose).toHaveBeenCalledOnce()
})
it('gives the loaded config one matcher registry and disposes it on plugin teardown', async () => {
const dir = mkdtempSync(join(tmpdir(), 'dsh-hooks-codex-matchers-'))
dirs.push(dir)
@@ -44,10 +66,10 @@ describe('hooks-codex matcher lifecycle', () => {
await ctx.plugin(LocalBashExecutor, { timeoutMs: 10_000 })
const fiber = await ctx.plugin(HooksCodex, { configPath, model: 'm' })
expect(matcherLifecycle.compileMatchers).toHaveBeenCalledExactlyOnceWith([
expect(matcherLifecycle.compileMatchers).toHaveBeenCalledExactlyOnceWith(new Set([
'(?i)^bash$',
'(?i)^bash$',
], 'codex')
]), 'codex')
expect(matcherLifecycle.registry.diagnostic).toHaveBeenCalledTimes(2)
expect(matcherLifecycle.registry.dispose).not.toHaveBeenCalled()
await fiber.dispose()