fix(invariants): enforce runtime relationships

This commit is contained in:
Tianyi Cui
2026-07-20 23:16:08 +08:00
parent 023cde5d82
commit e92b34bd7e
22 changed files with 398 additions and 75 deletions

View File

@@ -18,8 +18,39 @@ export const name = 'time-context-invariant'
/** Service required before the companion can reserve package ownership. */
export const inject = ['invariants']
/** Validate one plugin-attributed time reading against its durable event timestamp. */
function validateReading(event: SessionEvent<'context/message'>, fail: InvariantFailure): void {
/** Derive the pre-step position at which a time-context reading may append. */
function preparationPosition(session: Session, fail: InvariantFailure): { turn: number; step: number } {
const currentTurnEvents: SessionEvent[] = []
let openTurn: number | undefined
for (const event of session.events.slice().reverse()) {
if (event.type === 'turn/end') {
fail('time-context reading must be appended inside an open turn')
}
if (event.type === 'turn/start') {
openTurn = event.data.turn
break
}
currentTurnEvents.push(event)
}
if (openTurn === undefined) fail('time-context reading must be appended inside an open turn')
for (const event of currentTurnEvents) {
if (event.type === 'step/start') {
fail(`time-context reading must precede step/start, but step ${event.data.step} is already open`)
}
if (event.type === 'step/end') {
return { turn: openTurn, step: event.data.step + 1 }
}
}
return { turn: openTurn, step: 1 }
}
/** Validate one plugin-attributed time reading against its session position and timestamp. */
function validateReading(
session: Session,
event: SessionEvent<'context/message'>,
fail: InvariantFailure,
): void {
const [block] = event.data.content
if (event.data.content.length !== 1 || block?.type !== 'text') {
fail('time-context messages must contain exactly one text block')
@@ -31,6 +62,10 @@ function validateReading(event: SessionEvent<'context/message'>, fail: Invariant
if (!Number.isSafeInteger(turn) || turn < 1 || !Number.isSafeInteger(step) || step < 1) {
fail('time-context turn and step must be positive safe integers')
}
const expected = preparationPosition(session, fail)
if (turn !== expected.turn || step !== expected.step) {
fail(`time-context reading names turn ${turn}/step ${step}, expected turn ${expected.turn}/step ${expected.step}`)
}
const baseline = match[4]
if ((step === 1) !== (baseline === 'model-visible message')) {
fail(`time-context step ${step} uses the wrong elapsed-time baseline ${JSON.stringify(baseline)}`)
@@ -49,11 +84,11 @@ function validateReading(event: SessionEvent<'context/message'>, fail: Invariant
const install: InvariantInstaller = (ctx, fail) => {
ctx.on('internal/dispatch', (_mode, eventName, args) => {
if (eventName !== 'session/event') return
const event = (args as [Session, SessionEvent])[1]
const [session, event] = args as [Session, SessionEvent]
if (event.type !== 'context/message'
|| event.data.source.kind !== 'plugin'
|| event.data.source.plugin !== SOURCE_NAME) return
validateReading(event, fail)
validateReading(session, event, fail)
}, { global: true })
}

View File

@@ -1,7 +1,7 @@
import { describe, expect, it } from 'vitest'
import { Context } from 'cordis'
import type { ContentBlock } from '@deepseek-ai/dsh-llm'
import type { Session, SessionEvent } from '@deepseek-ai/dsh-session'
import { Session, SessionId, type SessionEvent } from '@deepseek-ai/dsh-session'
import * as TimeInvariant from '@deepseek-ai/dsh-time-context/invariant'
import InvariantService from '@deepseek-ai/dsh-invariants'
@@ -36,12 +36,56 @@ function reading(
+ `Elapsed since the preceding ${baseline}: unavailable.`
}
function preparing(turn: number, step: number): Session {
const session = new Session(SessionId(`time-invariant-${turn}-${step}`))
for (let priorTurn = 1; priorTurn < turn; priorTurn += 1) {
session.append('turn/start', { turn: priorTurn, trigger: { kind: 'message', source: { kind: 'user' } } })
session.append('turn/end', { turn: priorTurn, reason: { kind: 'completed' } })
}
session.append('turn/start', { turn, trigger: { kind: 'message', source: { kind: 'user' } } })
session.append('user/message', {
content: [{ type: 'text', text: `turn ${turn}` }],
source: { kind: 'user' },
}, { surfaceOp: 'append' })
for (let priorStep = 1; priorStep < step; priorStep += 1) {
session.append('step/start', { turn, step: priorStep })
session.append('step/end', { turn, step: priorStep })
}
return session
}
describe('time-context invariants', () => {
it('accepts a reading whose turn, step, baseline, and timestamp agree', async () => {
const ctx = await setup()
const text = 'Time sampled while preparing turn 2, step 3: 2026-07-14T00:00:00+00:00[UTC]\n'
+ 'Elapsed since the preceding step context: 4m 2s.'
expect(() => { ctx.emit('session/event', {} as Session, event(text)) }).not.toThrow()
expect(() => { ctx.emit('session/event', preparing(2, 3), event(text)) }).not.toThrow()
})
it.each([
[reading('1', '3', 'step context'), /expected turn 2\/step 3/],
[reading('2', '2', 'step context'), /expected turn 2\/step 3/],
])('rejects a reading that disagrees with its session position', async (text, message) => {
const ctx = await setup()
expect(() => { ctx.emit('session/event', preparing(2, 3), event(text)) }).toThrow(message)
})
it('rejects a reading after cancellation closes the turn', async () => {
const ctx = await setup()
const session = preparing(1, 2)
session.append('turn/end', { turn: 1, reason: { kind: 'aborted', reason: 'cancelled' } })
expect(() => { ctx.emit('session/event', session, event(reading('1', '2', 'step context'))) })
.toThrow(/inside an open turn/)
})
it('rejects a reading after step/start or without any open turn', async () => {
const ctx = await setup()
const started = preparing(1, 1)
started.append('step/start', { turn: 1, step: 1 })
expect(() => { ctx.emit('session/event', started, event(reading())) }).toThrow(/must precede step\/start/)
expect(() => {
ctx.emit('session/event', new Session(SessionId('time-invariant-empty')), event(reading()))
}).toThrow(/inside an open turn/)
})
it.each([
@@ -61,8 +105,13 @@ describe('time-context invariants', () => {
['ignored', SECOND, [{ type: 'text', text: 'one' }, { type: 'text', text: 'two' }], /exactly one text block/],
] as const)('rejects an incoherent durable reading', async (text, time, content, message) => {
const ctx = await setup()
const preparationStep = text.includes('turn 1, step 2:') ? 2 : 1
expect(() => {
ctx.emit('session/event', {} as Session, event(text, time, content === undefined ? undefined : [...content]))
ctx.emit('session/event', preparing(1, preparationStep), event(
text,
time,
content === undefined ? undefined : [...content],
))
}).toThrow(message)
})
@@ -70,11 +119,11 @@ describe('time-context invariants', () => {
const ctx = await setup()
const other = event('unrelated') as SessionEvent<'context/message'>
other.data.source = { kind: 'plugin', plugin: 'other' }
expect(() => { ctx.emit('session/event', {} as Session, other) }).not.toThrow()
expect(() => { ctx.emit('session/event', preparing(1, 1), other) }).not.toThrow()
other.data.source = { kind: 'user' }
expect(() => { ctx.emit('session/event', {} as Session, other) }).not.toThrow()
expect(() => { ctx.emit('session/event', preparing(1, 1), other) }).not.toThrow()
expect(() => {
ctx.emit('session/event', {} as Session, {
ctx.emit('session/event', preparing(1, 1), {
type: 'turn/start', seq: 0, time: 0, data: { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } },
})
ctx.emit('tools/change')