fix(hooks): remove speculative regex runtime
This commit is contained in:
@@ -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/hooks-codex/README.md
|
||||
README.md: eb8882cda590293e21dd6011244f15359a797768
|
||||
README.zh.md: 641b7b57ad78f21d2df52dfc05ff4e8466a0f1c0
|
||||
README.md: e906810ed58c3d0204c618c32787af06c91cfb78
|
||||
README.zh.md: 4940fdb976dd963bbb2e41c0ec6ef274ee475334
|
||||
|
||||
@@ -7,7 +7,7 @@ A cordis plugin that runs the supported subset of a user's existing **Codex** ho
|
||||
This bridge implements a deliberate subset of Codex's current hook protocol:
|
||||
|
||||
- **Five of ten hook points:** `PreToolUse`, `PostToolUse`, `SessionStart`, `UserPromptSubmit`, and `Stop`.
|
||||
- **Native Codex matcher semantics:** pure word/pipe patterns are exact alternatives; other patterns are unanchored Rust `regex` expressions (including inline flags such as `(?i)`).
|
||||
- **Regex-only matchers** (no literal fast path; the matcher is always an unanchored regex).
|
||||
- **snake_case stdin payloads** with `turn_id`/`model` extras, written **without** a trailing newline.
|
||||
- **No Codex plugin env injection and no config-time placeholder substitution** (the command still receives the executor's environment and runs through its shell).
|
||||
- **No pre-tool approval or rewrite path** — a hook can block, but the bridge does not pre-approve or replace tool input.
|
||||
@@ -34,7 +34,7 @@ In a `cordis.yml`:
|
||||
model: deepseek-v4
|
||||
```
|
||||
|
||||
The config is parsed **once** at load. `configPath` is **process-level** — a relative path resolves against the process launch cwd at load time, not per-session (`TODO(per-session-hook-config)`). A read/parse failure is contained (logs + registers nothing); an invalid regex matcher on an event that consumes matchers is one such failure and reports its pattern and event. Non-literal Rust-regex patterns are interned across reloads under a process budget of 128 distinct patterns: once full, a new distinct pattern is rejected before WASM construction with a capacity diagnostic, while already interned patterns remain usable; restarting the process resets the budget. Only sync `type: 'command'` hooks run — a non-command or `async: true` hook is parsed-and-skipped with a warning. A hook accepts `timeout` or the `timeoutSec` alias; one that sets neither runs under the protocol's reference default (`DEFAULT_HOOK_TIMEOUT_MS` from `dsh-hook-protocol`, 10 minutes). Events outside the five bridge-supported points are dropped at parse.
|
||||
The config is parsed **once** at load. `configPath` is **process-level** — a relative path resolves against the process launch cwd at load time, not per-session (`TODO(per-session-hook-config)`). A read/parse failure is contained (logs + registers nothing); an invalid regex matcher on an event that consumes matchers is one such failure and reports its pattern and event. Only sync `type: 'command'` hooks run — a non-command or `async: true` hook is parsed-and-skipped with a warning. A hook accepts `timeout` or the `timeoutSec` alias; one that sets neither runs under the protocol's reference default (`DEFAULT_HOOK_TIMEOUT_MS` from `dsh-hook-protocol`, 10 minutes). Events outside the five bridge-supported points are dropped at parse.
|
||||
|
||||
The hooks themselves run in the agent's session workspace: for the agent-scoped points the bridge passes the session's `cwd` as the hook process's working directory, so a hook operates in the user's project tree, not the server launch dir.
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
该桥接实现 Codex 当前 hook 协议的一个明确子集:
|
||||
|
||||
- **10 个 hook 点中的 5 个:** `PreToolUse`、`PostToolUse`、`SessionStart`、`UserPromptSubmit` 和 `Stop`。
|
||||
- **Codex 原生 matcher 语义:** 纯 word/pipe pattern 是精确匹配的多选;其他 pattern 是未锚定的 Rust `regex` 表达式(包括 `(?i)` 等内联 flag)。
|
||||
- **仅使用正则的 matcher**(没有字面量快速路径;matcher 始终是未锚定正则)。
|
||||
- **snake_case stdin payload**,携带 `turn_id`/`model` 额外字段,写入时**不带**尾随换行符。
|
||||
- **没有 Codex 插件 env 注入,也没有配置时 placeholder 替换**(命令仍会接收执行器环境,并通过其 shell 运行)。
|
||||
- **没有工具前审批或改写路径**:hook 可以阻塞,但桥接不会预审批或替换工具输入。
|
||||
@@ -34,7 +34,7 @@ const config: Config = {
|
||||
model: deepseek-v4
|
||||
```
|
||||
|
||||
配置只在加载时解析**一次**。`configPath` 是**进程级**配置:相对路径在加载时根据进程启动 cwd 解析,而非每会话解析(`TODO(per-session-hook-config)`)。读取/解析失败会被隔离处理(记录 + 不注册任何内容);实际消费 matcher 的事件所带的无效 matcher 正则属于此类失败,并报告其 pattern 与事件。非字面的 Rust-regex pattern 会跨重载 intern,并受每进程最多 128 个不同 pattern 的预算约束:容量用满后,新的不同 pattern 会在 WASM 构造前被容量诊断拒绝,已经 intern 的 pattern 仍可使用;重启进程会重置预算。只运行同步 `type: 'command'` hook;非 command 或 `async: true` hook 会被解析并跳过,同时记录警告。hook 接受 `timeout` 或 `timeoutSec` alias;两者都未设置时,使用协议参考默认值 `DEFAULT_HOOK_TIMEOUT_MS`(来自 `dsh-hook-protocol`,10 分钟)。五个桥接支持点之外的事件会在解析时丢弃。
|
||||
配置只在加载时解析**一次**。`configPath` 是**进程级**配置:相对路径在加载时根据进程启动 cwd 解析,而非每会话解析(`TODO(per-session-hook-config)`)。读取/解析失败会被隔离处理(记录 + 不注册任何内容);实际消费 matcher 的事件所带的无效 matcher 正则属于此类失败,并报告其 pattern 与事件。只运行同步 `type: 'command'` hook;非 command 或 `async: true` hook 会被解析并跳过,同时记录警告。hook 接受 `timeout` 或 `timeoutSec` alias;两者都未设置时,使用协议参考默认值 `DEFAULT_HOOK_TIMEOUT_MS`(来自 `dsh-hook-protocol`,10 分钟)。五个桥接支持点之外的事件会在解析时丢弃。
|
||||
|
||||
hook 本身会在 agent(智能体)的会话工作区中运行:对 agent scope 点,桥接会将会话 `cwd` 作为 hook 进程工作目录,因此 hook 作用于用户项目树,而非服务器启动目录。
|
||||
|
||||
|
||||
@@ -5,11 +5,7 @@
|
||||
* @module @deepseek-ai/dsh-hooks-codex/config
|
||||
*/
|
||||
|
||||
import {
|
||||
compileMatchers,
|
||||
type CompiledMatchers,
|
||||
type MatcherGroup,
|
||||
} from '@deepseek-ai/dsh-hook-protocol'
|
||||
import { matcherDiagnostic, 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
|
||||
@@ -27,8 +23,6 @@ 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 {
|
||||
@@ -42,8 +36,7 @@ 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. Validation and runtime matching
|
||||
* share the returned compiled registry; its caller must dispose it.
|
||||
* to reject the complete config before listener registration.
|
||||
* @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.
|
||||
*/
|
||||
@@ -52,51 +45,42 @@ export function parseCodexConfig(raw: unknown): ParsedCodexConfig {
|
||||
const skipped: SkippedHook[] = []
|
||||
const root = asObject(raw)
|
||||
const hooksMap = root ? asObject(root.hooks) ?? root : undefined
|
||||
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 (!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 (groups.length > 0) config[event] = groups
|
||||
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
|
||||
}
|
||||
|
||||
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 }
|
||||
return { config, skipped }
|
||||
}
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
/**
|
||||
* Bridge for unmodified Codex command hooks on harness interception seams. It
|
||||
* supports five points (SessionStart, prompt/tool pre/post, Stop), native
|
||||
* literal-or-Rust-regex matchers, snake_case payloads without a trailing
|
||||
* newline, no hook environment or command substitution, and no pre-tool
|
||||
* approval or rewrite path; only blocking decisions are honored. Shared
|
||||
* execution and parsing live in
|
||||
* supports five points (SessionStart, prompt/tool pre/post, Stop), regex-only
|
||||
* matchers, snake_case payloads without a trailing newline, no hook environment
|
||||
* or command substitution, and no pre-tool approval or rewrite path; only
|
||||
* blocking decisions are honored. Shared execution and parsing live in
|
||||
* `dsh-hook-protocol`; see the
|
||||
* [hook-bridges Agent Note](../../../../.agents/notes/implemented/feature/2026-06-30-hook-bridges.md).
|
||||
* @module @deepseek-ai/dsh-hooks-codex
|
||||
@@ -28,13 +27,14 @@ import {
|
||||
createDetachedRuns,
|
||||
DEFAULT_HOOK_TIMEOUT_MS,
|
||||
DEFAULT_STDERR_SUMMARY_MAX_CHARS,
|
||||
matchesMatcher,
|
||||
mergeHookOutputs,
|
||||
runHook,
|
||||
type HookOutput,
|
||||
type MatcherGroup,
|
||||
type MergedHookOutcome,
|
||||
} from '@deepseek-ai/dsh-hook-protocol'
|
||||
import { parseCodexConfig, type ParsedCodexConfig } from './config.ts'
|
||||
import { parseCodexConfig, type CodexHookConfig } from './config.ts'
|
||||
/* jscpd:ignore-end */
|
||||
|
||||
export const name = 'hooks-codex'
|
||||
@@ -83,37 +83,26 @@ 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 result: ParsedCodexConfig
|
||||
let parsed: CodexHookConfig = {}
|
||||
try {
|
||||
const raw: unknown = JSON.parse(readFileSync(config.configPath, 'utf8'))
|
||||
result = parseCodexConfig(raw)
|
||||
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)`)
|
||||
}
|
||||
} 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 ?? ''
|
||||
// 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
|
||||
// continuation before releasing matchers (docs/defensive-patterns.md:
|
||||
// dispose must reach quiescence).
|
||||
// continuation (docs/defensive-patterns.md: dispose must reach quiescence).
|
||||
const detached = createDetachedRuns()
|
||||
ctx.effect(() => async () => {
|
||||
try {
|
||||
await detached.drain()
|
||||
} finally {
|
||||
matchers.dispose()
|
||||
}
|
||||
}, '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)`)
|
||||
}
|
||||
ctx.effect(() => () => detached.drain(), 'hooks-codex: drain detached hook runs')
|
||||
|
||||
/**
|
||||
* Run and fold one configured Codex hook point.
|
||||
@@ -137,11 +126,9 @@ export function apply(ctx: Context, config: Config): void {
|
||||
// Run hooks in the agent's session workspace so relative paths address the
|
||||
// user's project rather than the server launch directory.
|
||||
const workdir = opts.agent?.session.header.cwd
|
||||
// Keep each dialect's audit stamping readable beside its payload mapping.
|
||||
/* jscpd:ignore-start */
|
||||
for (const group of groups) {
|
||||
// The protocol library owns Codex's exact-literal/Rust-regex split.
|
||||
if (!matchers.matches(group.matcher, matchQuery)) continue
|
||||
// Codex always interprets matchers as regexes; it has no literal fast path.
|
||||
if (!matchesMatcher(group.matcher, matchQuery, 'codex')) continue
|
||||
for (const hook of group.hooks) {
|
||||
const handlerId = nextHandlerId(point)
|
||||
const session = opts.agent?.session
|
||||
@@ -151,7 +138,6 @@ export function apply(ctx: Context, config: Config): void {
|
||||
...group.matcher !== undefined ? { matcher: group.matcher } : {},
|
||||
})
|
||||
}
|
||||
/* jscpd:ignore-end */
|
||||
const { output, durationMs } = await runHook(ctx.bash, hook, {
|
||||
payload,
|
||||
defaultTimeoutMs,
|
||||
|
||||
@@ -66,11 +66,11 @@ async function waitFor(predicate: () => boolean, timeout = 5000, interval = 10):
|
||||
}
|
||||
|
||||
describe('hooks-codex bridge', () => {
|
||||
it('a PreToolUse hook (exit 2) honors a Rust-regex inline flag matcher', async () => {
|
||||
it('a PreToolUse hook (exit 2) denies a tool the regex matcher matches as a substring', async () => {
|
||||
const dir = configDir()
|
||||
const deny = script(dir, 'deny.sh', '#!/usr/bin/env bash\necho "codex blocked it" >&2\nexit 2\n')
|
||||
// `(?i)` is accepted by Rust regex but rejected by JavaScript RegExp.
|
||||
writeHooks(dir, { PreToolUse: [{ matcher: '(?i)^bash$', hooks: [{ type: 'command', command: deny }] }] })
|
||||
// Codex regex matcher: "Bash" is /Bash/ — matches the tool name "Bash".
|
||||
writeHooks(dir, { PreToolUse: [{ matcher: 'Bash', hooks: [{ type: 'command', command: deny }] }] })
|
||||
|
||||
const adapter = new MockAdapter([toolCallResponse('c1', 'Bash', { command: 'ls' }), textResponse('done')])
|
||||
const ctx = await harness(dir, adapter)
|
||||
|
||||
@@ -1,14 +1,5 @@
|
||||
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
|
||||
}
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { parseCodexConfig, CODEX_EVENTS } from '@deepseek-ai/dsh-hooks-codex/src/config.ts'
|
||||
|
||||
describe('parseCodexConfig', () => {
|
||||
it('honors only the five bridge-supported Codex events, dropping the rest', () => {
|
||||
@@ -70,10 +61,9 @@ describe('parseCodexConfig', () => {
|
||||
expect('matcher' in config.Stop![0]!).toBe(false)
|
||||
})
|
||||
|
||||
it('keeps a valid Rust-regex matcher when present', () => {
|
||||
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('keeps a matcher when present', () => {
|
||||
const { config } = parseCodexConfig({ PreToolUse: [{ matcher: '^Bash$', hooks: [{ type: 'command', command: 'b.sh' }] }] })
|
||||
expect(config.PreToolUse![0]!.matcher).toBe('^Bash$')
|
||||
})
|
||||
|
||||
it('rejects an invalid regex matcher with its event name', () => {
|
||||
@@ -82,12 +72,6 @@ describe('parseCodexConfig', () => {
|
||||
})).toThrow('invalid codex regex matcher "[" on event "PreToolUse"')
|
||||
})
|
||||
|
||||
it('rejects JavaScript-only regex syntax that Codex cannot execute', () => {
|
||||
expect(() => parseCodexConfig({
|
||||
PreToolUse: [{ matcher: '(?=Bash)', hooks: [{ type: 'command', command: 's.sh' }] }],
|
||||
})).toThrow('invalid codex regex matcher "(?=Bash)" on event "PreToolUse"')
|
||||
})
|
||||
|
||||
it('discards matcher fields on events without matcher subjects before validation', () => {
|
||||
const { config } = parseCodexConfig({
|
||||
UserPromptSubmit: [{ matcher: '[', hooks: [{ type: 'command', command: 'prompt.sh' }] }],
|
||||
|
||||
@@ -1,78 +0,0 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { Context } from 'cordis'
|
||||
import { LocalBashExecutor } from '@deepseek-ai/dsh-bash-local'
|
||||
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 {
|
||||
registry,
|
||||
compileMatchers: vi.fn(() => registry),
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('@deepseek-ai/dsh-hook-protocol', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@deepseek-ai/dsh-hook-protocol')>()
|
||||
return { ...actual, compileMatchers: matcherLifecycle.compileMatchers }
|
||||
})
|
||||
|
||||
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)
|
||||
const configPath = join(dir, 'hooks.json')
|
||||
writeFileSync(configPath, JSON.stringify({ hooks: {
|
||||
PreToolUse: [{ matcher: '(?i)^bash$', hooks: [{ type: 'command', command: 'true' }] }],
|
||||
PostToolUse: [{ matcher: '(?i)^bash$', hooks: [{ type: 'command', command: 'true' }] }],
|
||||
} }))
|
||||
|
||||
const HooksCodex = await import('@deepseek-ai/dsh-hooks-codex')
|
||||
const ctx = new Context()
|
||||
await ctx.plugin(LocalSubprocessService)
|
||||
await ctx.plugin(LocalBashExecutor, { timeoutMs: 10_000 })
|
||||
const fiber = await ctx.plugin(HooksCodex, { configPath, model: 'm' })
|
||||
|
||||
expect(matcherLifecycle.compileMatchers).toHaveBeenCalledExactlyOnceWith(new Set([
|
||||
'(?i)^bash$',
|
||||
]), 'codex')
|
||||
expect(matcherLifecycle.registry.diagnostic).toHaveBeenCalledTimes(2)
|
||||
expect(matcherLifecycle.registry.dispose).not.toHaveBeenCalled()
|
||||
|
||||
await fiber.dispose()
|
||||
expect(matcherLifecycle.registry.dispose).toHaveBeenCalledOnce()
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user