fix(invariants): assert runtime relationships, not API shapes

This commit is contained in:
Tianyi Cui
2026-07-20 19:34:19 +08:00
parent 1254c07025
commit 1145ee5fc3
124 changed files with 2923 additions and 2334 deletions

View File

@@ -1,39 +1,98 @@
/** Package-owned runtime contracts for @deepseek-ai/dsh-hook-protocol. @module @deepseek-ai/dsh-hook-protocol/invariant */
/** Package-owned hook provenance-stream invariants. @module @deepseek-ai/dsh-hook-protocol/invariant */
/* jscpd:ignore-start */
import type { Context } from 'cordis'
import { assertInvariant, type InvariantInstaller } from '@deepseek-ai/dsh-invariants'
import type { Session, SessionEvent } from '@deepseek-ai/dsh-session'
import type { InvariantFailure, InvariantInstaller } from '@deepseek-ai/dsh-invariants'
import type {} from './types.ts'
const PACKAGE_NAME = '@deepseek-ai/dsh-hook-protocol'
/** Cordis companion plugin name. */
export const name = 'hook-protocol-invariant'
/** Services required before the companion can register. */
/** Service required before the companion can reserve package ownership. */
export const inject = ['invariants']
/** Assert blocking-exit decoding and restrictive merge precedence. */
const install: InvariantInstaller = async (_ctx, fail) => {
const [{ parseHookOutput }, { mergeHookOutputs }] = await Promise.all([
import('./codec.ts'),
import('./merge.ts'),
])
const blocked = parseHookOutput(2, '', ' denied ')
assertInvariant(fail, blocked.decision === 'block' && blocked.reason === 'denied',
'exit 2 must decode as a block whose reason is trimmed stderr')
const merged = mergeHookOutputs([
{ exitCode: 0, stderr: '', stdout: '', decision: 'allow', reason: 'permitted' },
{ exitCode: 0, stderr: '', stdout: '', decision: 'deny', reason: 'forbidden' },
])
assertInvariant(fail, merged.decision === 'deny' && merged.reason === 'forbidden',
'deny must override allow and retain only the winning decision reason')
interface HookTransition {
key: string
delta: 1 | -1
}
/** Correlation key shared by an invoked/result pair. */
function hookKey(data: { turn: number; point: string; handlerId: string }): string {
return `${data.turn}\0${data.point}\0${data.handlerId}`
}
/** Validate one hook event against committed pending invocations. */
function validateHookEvent(
pending: ReadonlyMap<string, number>,
event: SessionEvent,
fail: InvariantFailure,
): HookTransition | undefined {
if (event.type === 'hook/invoked') {
if (event.data.point.length === 0 || event.data.handlerId.length === 0) {
fail('hook/invoked point and handlerId must be non-empty')
}
const dialect: string = event.data.dialect
if (dialect !== 'claude' && dialect !== 'codex') {
fail(`hook/invoked carries unknown dialect ${JSON.stringify(dialect)}`)
}
return { key: hookKey(event.data), delta: 1 }
}
if (event.type !== 'hook/result') return undefined
const key = hookKey(event.data)
if ((pending.get(key) ?? 0) === 0) {
fail(`hook/result has no matching hook/invoked for ${JSON.stringify(event.data.handlerId)}`)
}
if (!Number.isFinite(event.data.durationMs) || event.data.durationMs < 0) {
fail('hook/result durationMs must be a non-negative finite number')
}
return { key, delta: -1 }
}
/** Apply one committed hook-pair transition. */
function applyHookTransition(pending: Map<string, number>, transition: HookTransition): void {
const next = (pending.get(transition.key) ?? 0) + transition.delta
if (next === 0) pending.delete(transition.key)
else pending.set(transition.key, next)
}
/** Install hook invoked/result pairing checks. */
const install: InvariantInstaller = Object.assign((ctx: Context, fail: InvariantFailure) => {
const traces = new WeakMap<Session, Map<string, number>>()
const staged = new WeakMap<SessionEvent, { session: Session; transition: HookTransition }>()
const seed = (session: Session): Map<string, number> => {
const pending = new Map<string, number>()
traces.set(session, pending)
for (const event of session.events) {
const transition = validateHookEvent(pending, event, fail)
if (transition !== undefined) applyHookTransition(pending, transition)
}
return pending
}
const traceFor = (session: Session): Map<string, number> => traces.get(session) ?? seed(session)
for (const session of ctx.sessions.list()) seed(session)
ctx.on('session/created', (session) => { seed(session) }, { global: true })
ctx.on('session/event', (session, event) => {
if (event.type !== 'hook/invoked' && event.type !== 'hook/result') return
const candidate = staged.get(event)
/* v8 ignore next -- internal/dispatch stages every hook provenance event */
if (candidate === undefined || candidate.session !== session) return fail('hook event published without pre-commit validation')
staged.delete(event)
applyHookTransition(traceFor(session), candidate.transition)
}, { global: true })
ctx.on('internal/dispatch', (_mode, eventName, args) => {
if (eventName !== 'session/event') return
const [session, event] = args as [Session, SessionEvent]
const transition = validateHookEvent(traceFor(session), event, fail)
if (transition !== undefined) staged.set(event, { session, transition })
}, { global: true })
}, { inject: ['sessions'] })
/**
* Register this package's invariant companion.
* Register the hook-protocol invariant companion.
* @param ctx - Cordis context carrying the invariant service.
* @returns the installed registration's disposer after setup succeeds.
*/
export const apply = (ctx: Context): Promise<() => void> =>
Promise.resolve(ctx.invariants.register(PACKAGE_NAME, install))
/* jscpd:ignore-end */

View File

@@ -0,0 +1,86 @@
import { describe, expect, it } from 'vitest'
import { Context } from 'cordis'
import SessionStore, { Session, SessionId } from '@deepseek-ai/dsh-session'
import * as HookInvariant from '@deepseek-ai/dsh-hook-protocol/invariant'
import InvariantService from '@deepseek-ai/dsh-invariants'
async function setup(): Promise<Context> {
const ctx = new Context()
await ctx.plugin(SessionStore)
await ctx.plugin(InvariantService)
await ctx.plugin(HookInvariant)
return ctx
}
const invoked = (overrides: Record<string, unknown> = {}) => ({
turn: 1,
point: 'PreToolUse',
dialect: 'claude' as const,
handlerId: 'hook-1',
...overrides,
})
const result = (overrides: Record<string, unknown> = {}) => ({
turn: 1,
point: 'PreToolUse',
handlerId: 'hook-1',
decision: 'pass',
durationMs: 3,
...overrides,
})
describe('hook-protocol invariants', () => {
it('pairs serial and repeated handler invocations', async () => {
const ctx = await setup()
const session = ctx.sessions.create()
session.append('hook/invoked', invoked())
session.append('hook/invoked', invoked())
session.append('hook/result', result())
session.append('hook/result', result())
})
it('rebuilds pending hook provenance from an existing session', async () => {
const ctx = new Context()
await ctx.plugin(SessionStore)
const session = ctx.sessions.create()
session.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
session.append('hook/invoked', invoked())
await ctx.plugin(InvariantService)
await ctx.plugin(HookInvariant)
expect(() => session.append('hook/result', result())).not.toThrow()
session.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
})
it('adopts a bare session first observed through publication', async () => {
const ctx = await setup()
const session = new Session(SessionId('bare-hook-session'))
expect(() => {
ctx.emit('session/event', session, {
type: 'hook/invoked', seq: 0, time: 0, data: invoked(),
})
ctx.emit('session/event', session, {
type: 'hook/result', seq: 1, time: 1, data: result(),
})
}).not.toThrow()
})
it.each([
[invoked({ point: '' }), /point and handlerId must be non-empty/],
[invoked({ handlerId: '' }), /point and handlerId must be non-empty/],
[invoked({ dialect: 'other' }), /unknown dialect/],
])('rejects malformed hook invocation %#', async (data, message) => {
const ctx = await setup()
expect(() => ctx.sessions.create().append('hook/invoked', data as never)).toThrow(message)
})
it('rejects unmatched and malformed results', async () => {
const ctx = await setup()
const session = ctx.sessions.create()
expect(() => session.append('hook/result', result())).toThrow(/no matching hook\/invoked/)
session.append('hook/invoked', invoked())
expect(() => session.append('hook/result', result({ durationMs: -1 })))
.toThrow(/durationMs must be a non-negative finite number/)
expect(() => session.append('hook/result', result({ point: 'Stop' })))
.toThrow(/no matching hook\/invoked/)
})
})

View File

@@ -1,40 +1,24 @@
/** Package-owned runtime contract checks for `@deepseek-ai/dsh-hooks-claude`. @module @deepseek-ai/dsh-hooks-claude/invariant */
/**
* Package-owned invariant companion for `@deepseek-ai/dsh-hooks-claude`.
* @module @deepseek-ai/dsh-hooks-claude/invariant
*/
/* jscpd:ignore-start */
import type { Context } from 'cordis'
import { observePluginInvariant, type InvariantInstaller } from '@deepseek-ai/dsh-invariants'
import type { InvariantInstaller } from '@deepseek-ai/dsh-invariants'
const PACKAGE_NAME = '@deepseek-ai/dsh-hooks-claude'
/** Cordis companion plugin name. */
export const name = 'hooks-claude-invariant'
/** Services required before the companion can register. */
/** Service required before the companion can reserve package ownership. */
export const inject = ['invariants']
/** Install checks for this package's active plugin fibers. */
const install: InvariantInstaller = (ctx, fail) => {
observePluginInvariant(ctx, fail, {
name: 'hooks-claude',
inject: [
'bash',
],
validate: (_fiber, effectLabels) => {
const hookEffects = [
'hooks-claude: drain detached hook runs',
'ctx.on("agent/session-start")',
'ctx.on("agent/prompt-submit")',
'ctx.on("tools/pre-execute")',
'ctx.on("tools/post-execute")',
'ctx.on("agent/turn-continuation")',
'ctx.on("subagent/start")',
'ctx.on("subagent/end")',
]
const installed = hookEffects.filter(label => effectLabels.has(label)).length
return installed === 0 || installed === hookEffects.length
? undefined
: 'a readable Claude hook config must install its complete listener set atomically'
},
})
}
/**
* No runtime invariant: this bridge publishes hook-protocol session events, whose companion owns
* their cross-event provenance relation.
*/
const install: InvariantInstaller = () => {}
/**
* Register this package's invariant companion.
@@ -43,3 +27,4 @@ const install: InvariantInstaller = (ctx, fail) => {
*/
export const apply = (ctx: Context): Promise<() => void> =>
Promise.resolve(ctx.invariants.register(PACKAGE_NAME, install))
/* jscpd:ignore-end */

View File

@@ -1,26 +0,0 @@
import { describe, expect, it } from 'vitest'
import { Context } from 'cordis'
import type { BashExecutor } from '@deepseek-ai/dsh-bash'
describe('Claude hook package invariant', () => {
it('rejects a partially installed hook listener set', async () => {
const ctx = new Context()
await ctx.plugin({
name: 'claude-invariant-bash',
apply(child: Context) {
child.provide('bash', {
resolve() {},
async run() {},
start() {},
} as unknown as BashExecutor)
},
})
await expect(ctx.plugin({
name: 'hooks-claude',
inject: ['bash'],
apply(child: Context) {
child.effect(() => () => {}, 'ctx.on("agent/session-start")')
},
})).rejects.toThrow(/must install its complete listener set atomically/)
})
})

View File

@@ -1,38 +1,24 @@
/** Package-owned runtime contract checks for `@deepseek-ai/dsh-hooks-codex`. @module @deepseek-ai/dsh-hooks-codex/invariant */
/**
* Package-owned invariant companion for `@deepseek-ai/dsh-hooks-codex`.
* @module @deepseek-ai/dsh-hooks-codex/invariant
*/
/* jscpd:ignore-start */
import type { Context } from 'cordis'
import { observePluginInvariant, type InvariantInstaller } from '@deepseek-ai/dsh-invariants'
import type { InvariantInstaller } from '@deepseek-ai/dsh-invariants'
const PACKAGE_NAME = '@deepseek-ai/dsh-hooks-codex'
/** Cordis companion plugin name. */
export const name = 'hooks-codex-invariant'
/** Services required before the companion can register. */
/** Service required before the companion can reserve package ownership. */
export const inject = ['invariants']
/** Install checks for this package's active plugin fibers. */
const install: InvariantInstaller = (ctx, fail) => {
observePluginInvariant(ctx, fail, {
name: 'hooks-codex',
inject: [
'bash',
],
validate: (_fiber, effectLabels) => {
const hookEffects = [
'hooks-codex: drain detached hook runs',
'ctx.on("agent/session-start")',
'ctx.on("agent/prompt-submit")',
'ctx.on("tools/pre-execute")',
'ctx.on("tools/post-execute")',
'ctx.on("agent/turn-continuation")',
]
const installed = hookEffects.filter(label => effectLabels.has(label)).length
return installed === 0 || installed === hookEffects.length
? undefined
: 'a readable Codex hook config must install its complete listener set atomically'
},
})
}
/**
* No runtime invariant: this bridge publishes hook-protocol session events, whose companion owns
* their cross-event provenance relation.
*/
const install: InvariantInstaller = () => {}
/**
* Register this package's invariant companion.
@@ -41,3 +27,4 @@ const install: InvariantInstaller = (ctx, fail) => {
*/
export const apply = (ctx: Context): Promise<() => void> =>
Promise.resolve(ctx.invariants.register(PACKAGE_NAME, install))
/* jscpd:ignore-end */

View File

@@ -1,26 +0,0 @@
import { describe, expect, it } from 'vitest'
import { Context } from 'cordis'
import type { BashExecutor } from '@deepseek-ai/dsh-bash'
describe('Codex hook package invariant', () => {
it('rejects a partially installed hook listener set', async () => {
const ctx = new Context()
await ctx.plugin({
name: 'codex-invariant-bash',
apply(child: Context) {
child.provide('bash', {
resolve() {},
async run() {},
start() {},
} as unknown as BashExecutor)
},
})
await expect(ctx.plugin({
name: 'hooks-codex',
inject: ['bash'],
apply(child: Context) {
child.effect(() => () => {}, 'ctx.on("agent/session-start")')
},
})).rejects.toThrow(/must install its complete listener set atomically/)
})
})