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,31 +1,88 @@
/** Package-owned runtime contract checks for `@deepseek-ai/dsh-user-approval`. @module @deepseek-ai/dsh-user-approval/invariant */
/** Package-owned approval audit-stream invariants. @module @deepseek-ai/dsh-user-approval/invariant */
import type { Context } from 'cordis'
import { observePluginInvariant, 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 { ApprovalRequestId } from './index.ts'
import { APPROVAL_POLICIES } from './index.ts'
const PACKAGE_NAME = '@deepseek-ai/dsh-user-approval'
const APPROVAL_OUTCOMES = ['allowed-once', 'rejected', 'cancelled', 'unavailable'] as const
/** Cordis companion plugin name. */
export const name = 'user-approval-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: 'ApprovalService',
effects: [
'ctx.provide("approval")',
'ctx.on("agent/pre-step")',
],
services: [
'approval',
],
})
type ApprovalTransition =
| { kind: 'asked'; id: ApprovalRequestId }
| { kind: 'decided'; id: ApprovalRequestId }
/** Validate one approval event against committed unmatched questions. */
function validateApprovalEvent(
pending: ReadonlySet<ApprovalRequestId>,
event: SessionEvent,
fail: InvariantFailure,
): ApprovalTransition | undefined {
if (event.type === 'approval/asked') {
if (event.data.toolName.length === 0) fail('approval/asked toolName must be non-empty')
if (pending.has(event.data.id)) fail(`approval/asked repeated open id ${JSON.stringify(event.data.id)}`)
return { kind: 'asked', id: event.data.id }
}
if (event.type === 'approval/decided') {
if (!pending.has(event.data.id)) fail(`approval/decided has no matching approval/asked for id ${JSON.stringify(event.data.id)}`)
if (!APPROVAL_OUTCOMES.includes(event.data.outcome)) {
fail(`approval/decided carries unknown outcome ${JSON.stringify(event.data.outcome)}`)
}
return { kind: 'decided', id: event.data.id }
}
if (event.type === 'approval/policy' && !APPROVAL_POLICIES.includes(event.data.policy)) {
fail(`approval/policy carries unknown policy ${JSON.stringify(event.data.policy)}`)
}
return undefined
}
/** Apply one accepted approval-pair transition. */
function applyApprovalTransition(pending: Set<ApprovalRequestId>, transition: ApprovalTransition): void {
if (transition.kind === 'asked') pending.add(transition.id)
else pending.delete(transition.id)
}
/** Install audit pairing and closed-vocabulary checks. */
const install: InvariantInstaller = Object.assign((ctx: Context, fail: InvariantFailure) => {
const traces = new WeakMap<Session, Set<ApprovalRequestId>>()
const staged = new WeakMap<SessionEvent, { session: Session; transition: ApprovalTransition }>()
const seed = (session: Session): Set<ApprovalRequestId> => {
const pending = new Set<ApprovalRequestId>()
traces.set(session, pending)
for (const event of session.events) {
const transition = validateApprovalEvent(pending, event, fail)
if (transition !== undefined) applyApprovalTransition(pending, transition)
}
return pending
}
const traceFor = (session: Session): Set<ApprovalRequestId> => 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 !== 'approval/asked' && event.type !== 'approval/decided') return
const candidate = staged.get(event)
/* v8 ignore next -- internal/dispatch stages every package-owned pair event */
if (candidate === undefined || candidate.session !== session) return fail('approval audit event published without pre-commit validation')
staged.delete(event)
applyApprovalTransition(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 = validateApprovalEvent(traceFor(session), event, fail)
if (transition !== undefined) staged.set(event, { session, transition })
}, { global: true })
}, { inject: ['sessions'] })
/**
* Register this package's invariant companion.
* Register the approval invariant companion.
* @param ctx - Cordis context carrying the invariant service.
* @returns the installed registration's disposer after setup succeeds.
*/

View File

@@ -0,0 +1,72 @@
import { describe, expect, it } from 'vitest'
import { Context } from 'cordis'
import SessionStore, { Session, SessionId } from '@deepseek-ai/dsh-session'
import { ApprovalRequestId } from '@deepseek-ai/dsh-user-approval'
import * as ApprovalInvariant from '@deepseek-ai/dsh-user-approval/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(ApprovalInvariant)
return ctx
}
describe('approval invariants', () => {
it('accepts paired audit events and closed policy values', async () => {
const ctx = await setup()
const session = ctx.sessions.create()
const id = ApprovalRequestId('ask-1')
session.append('approval/asked', { id, toolName: 'bash' })
session.append('approval/decided', { id, outcome: 'allowed-once' })
session.append('approval/policy', { policy: 'never' })
})
it('rebuilds an unmatched question 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' } } })
const id = ApprovalRequestId('ask-resume')
session.append('approval/asked', { id, toolName: 'bash' })
await ctx.plugin(InvariantService)
await ctx.plugin(ApprovalInvariant)
expect(() => session.append('approval/decided', { id, outcome: 'cancelled' })).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-approval-session'))
const id = ApprovalRequestId('bare-ask')
const asked = {
type: 'approval/asked', seq: 0, time: 0, data: { id, toolName: 'bash' },
} as const
const decided = {
type: 'approval/decided', seq: 1, time: 1, data: { id, outcome: 'rejected' as const },
} as const
expect(() => {
ctx.emit('session/event', session, asked)
ctx.emit('session/event', session, decided)
}).not.toThrow()
})
it('rejects malformed and unpaired audit events', async () => {
const ctx = await setup()
const session = ctx.sessions.create()
const id = ApprovalRequestId('ask-1')
expect(() => session.append('approval/asked', { id, toolName: '' }))
.toThrow(/toolName must be non-empty/)
session.append('approval/asked', { id, toolName: 'bash' })
expect(() => session.append('approval/asked', { id, toolName: 'bash' }))
.toThrow(/repeated open id/)
expect(() => session.append('approval/decided', {
id: ApprovalRequestId('missing'), outcome: 'rejected',
})).toThrow(/no matching approval\/asked/)
expect(() => session.append('approval/decided', { id, outcome: 'maybe' as never }))
.toThrow(/unknown outcome/)
expect(() => session.append('approval/policy', { policy: 'always' as never }))
.toThrow(/unknown policy/)
})
})