Merge commit 'refs/codex/unblock/master-current' into HEAD
# Conflicts: # docs/event-producer-consumer.md # examples/acp-agent/tests/snapshots/bash-spill/session.jsonl # examples/acp-agent/tests/snapshots/escalation-approved/session.jsonl # examples/acp-agent/tests/snapshots/escalation-rejected/session.jsonl # examples/acp-agent/tests/snapshots/fs-escalation-approved/session.jsonl # examples/acp-agent/tests/snapshots/hook-cc-pretool-ask/session.jsonl # packages/context/workspace-context/tests/workspace-context.spec.ts # packages/core/agent/src/index.ts # packages/support/invariants/tests/invariants.spec.ts # packages/ui/acp/src/index.ts # packages/ui/tui/tests/harness.ts # packages/ui/tui/tests/tui.spec.ts
This commit is contained in:
@@ -11,11 +11,16 @@
|
||||
"types": "./lib/types/index.d.ts",
|
||||
"default": "./lib/index.js"
|
||||
},
|
||||
"./invariant": {
|
||||
"types": "./lib/types/invariant.d.ts",
|
||||
"default": "./lib/invariant.js"
|
||||
},
|
||||
"./src/*": "./src/*",
|
||||
"./package.json": "./package.json"
|
||||
},
|
||||
"files": [
|
||||
"lib/index.js",
|
||||
"lib/invariant.js",
|
||||
"lib/types/**/*.d.ts",
|
||||
"lib/types/**/*.d.ts.map",
|
||||
"src"
|
||||
@@ -24,6 +29,7 @@
|
||||
"peerDependencies": {
|
||||
"@deepseek-ai/dsh-commands": "^0.0.1",
|
||||
"@deepseek-ai/dsh-goal": "^0.0.1",
|
||||
"@deepseek-ai/dsh-invariants": "^0.0.1",
|
||||
"cordis": "^4.0.0-rc.7"
|
||||
},
|
||||
"devDependencies": {
|
||||
@@ -31,6 +37,7 @@
|
||||
"@deepseek-ai/dsh-agent": "workspace:^",
|
||||
"@deepseek-ai/dsh-commands": "workspace:^",
|
||||
"@deepseek-ai/dsh-goal": "workspace:^",
|
||||
"@deepseek-ai/dsh-invariants": "workspace:^",
|
||||
"@deepseek-ai/dsh-llm": "workspace:^",
|
||||
"@deepseek-ai/dsh-session": "workspace:^",
|
||||
"cordis": "^4.0.0-rc.7"
|
||||
|
||||
30
packages/goal/command-goal/src/invariant.ts
Normal file
30
packages/goal/command-goal/src/invariant.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
/**
|
||||
* Package-owned invariant companion for `@deepseek-ai/dsh-command-goal`.
|
||||
* @module @deepseek-ai/dsh-command-goal/invariant
|
||||
*/
|
||||
|
||||
/* jscpd:ignore-start */
|
||||
import type { Context } from 'cordis'
|
||||
import type { InvariantInstaller } from '@deepseek-ai/dsh-invariants'
|
||||
|
||||
const PACKAGE_NAME = '@deepseek-ai/dsh-command-goal'
|
||||
|
||||
/** Cordis companion plugin name. */
|
||||
export const name = 'command-goal-invariant'
|
||||
/** Service required before the companion can reserve package ownership. */
|
||||
export const inject = ['invariants']
|
||||
|
||||
/**
|
||||
* No runtime invariant: this command adapter owns no event stream or state projection; accepted
|
||||
* mutations are checked by the goal domain and command dispatch behavior is covered by package tests.
|
||||
*/
|
||||
const install: InvariantInstaller = () => {}
|
||||
|
||||
/**
|
||||
* Register this package's 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 */
|
||||
@@ -19,6 +19,9 @@
|
||||
},
|
||||
{
|
||||
"path": "../goal"
|
||||
},
|
||||
{
|
||||
"path": "../../support/invariants"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -11,11 +11,16 @@
|
||||
"types": "./lib/types/index.d.ts",
|
||||
"default": "./lib/index.js"
|
||||
},
|
||||
"./invariant": {
|
||||
"types": "./lib/types/invariant.d.ts",
|
||||
"default": "./lib/invariant.js"
|
||||
},
|
||||
"./src/*": "./src/*",
|
||||
"./package.json": "./package.json"
|
||||
},
|
||||
"files": [
|
||||
"lib/index.js",
|
||||
"lib/invariant.js",
|
||||
"lib/types/**/*.d.ts",
|
||||
"lib/types/**/*.d.ts.map",
|
||||
"src"
|
||||
@@ -24,6 +29,7 @@
|
||||
"peerDependencies": {
|
||||
"@deepseek-ai/dsh-agent": "^0.0.1",
|
||||
"@deepseek-ai/dsh-goal": "^0.0.1",
|
||||
"@deepseek-ai/dsh-invariants": "^0.0.1",
|
||||
"@deepseek-ai/dsh-llm": "^0.0.1",
|
||||
"@deepseek-ai/dsh-session": "^0.0.1",
|
||||
"cordis": "^4.0.0-rc.7"
|
||||
@@ -33,6 +39,7 @@
|
||||
"@deepseek-ai/dsh-agent-loop": "workspace:^",
|
||||
"@deepseek-ai/dsh-agent-loop-testkit": "workspace:^",
|
||||
"@deepseek-ai/dsh-goal": "workspace:^",
|
||||
"@deepseek-ai/dsh-invariants": "workspace:^",
|
||||
"@deepseek-ai/dsh-llm": "workspace:^",
|
||||
"@deepseek-ai/dsh-session": "workspace:^",
|
||||
"@deepseek-ai/dsh-system-prompt": "workspace:^",
|
||||
|
||||
84
packages/goal/goal-session/src/invariant.ts
Normal file
84
packages/goal/goal-session/src/invariant.ts
Normal file
@@ -0,0 +1,84 @@
|
||||
/** Package-owned goal-round prompt invariants. @module @deepseek-ai/dsh-goal-session/invariant */
|
||||
|
||||
import { isDeepStrictEqual } from 'node:util'
|
||||
import type { Context } from 'cordis'
|
||||
import { foldGoal, type FoldedGoal, type GoalMessageSource, type GoalView } from '@deepseek-ai/dsh-goal'
|
||||
import type { InvariantFailure, InvariantInstaller } from '@deepseek-ai/dsh-invariants'
|
||||
import type { Session, SessionEvent } from '@deepseek-ai/dsh-session'
|
||||
import { renderGoalRoundPrompt } from './prompt.ts'
|
||||
|
||||
const PACKAGE_NAME = '@deepseek-ai/dsh-goal-session'
|
||||
|
||||
/** Cordis companion plugin name. */
|
||||
export const name = 'goal-session-invariant'
|
||||
/** Service required before the companion can reserve package ownership. */
|
||||
export const inject = ['invariants']
|
||||
|
||||
/** Attribute strict goal-fold failures to this companion's reconstruction. */
|
||||
function foldChecked(events: readonly SessionEvent[], fail: InvariantFailure): FoldedGoal {
|
||||
try {
|
||||
return foldGoal(events)
|
||||
} catch (error: unknown) {
|
||||
/* v8 ignore next -- the strict goal decoder throws Error instances */
|
||||
const message = error instanceof Error ? error.message : String(error)
|
||||
return fail(`cannot reconstruct the goal before a continuation message: ${message}`)
|
||||
}
|
||||
}
|
||||
|
||||
/** Recreate the live-shaped view consumed by the package's pure prompt renderer. */
|
||||
function goalView(folded: FoldedGoal, source: GoalMessageSource, fail: InvariantFailure): GoalView {
|
||||
const goal = folded.goal
|
||||
if (goal === undefined || folded.createdAt === undefined || folded.updatedAt === undefined
|
||||
|| goal.phase !== 'active' || goal.id !== source.goalId || goal.revision !== source.revision
|
||||
|| source.round !== folded.roundsStarted + 1 || source.round > goal.maxGoalRounds) {
|
||||
return fail(`goal round ${source.round} cannot be reconstructed from the preceding durable goal state`)
|
||||
}
|
||||
return {
|
||||
...goal,
|
||||
roundsStarted: folded.roundsStarted,
|
||||
createdAt: folded.createdAt,
|
||||
updatedAt: folded.updatedAt,
|
||||
activation: 'armed',
|
||||
}
|
||||
}
|
||||
|
||||
/** Validate one package-owned continuation message against its durable prefix. */
|
||||
function validateEvent(
|
||||
prior: readonly SessionEvent[],
|
||||
event: SessionEvent,
|
||||
fail: InvariantFailure,
|
||||
): void {
|
||||
if (event.type !== 'user/message') return
|
||||
const source = event.data.source
|
||||
if (source.kind !== 'goal' || source.round <= 0) return
|
||||
const expected = renderGoalRoundPrompt(goalView(foldChecked(prior, fail), source, fail), source.round)
|
||||
if (!isDeepStrictEqual(event.data.content, expected)) {
|
||||
fail(`goal round ${source.round} content does not match the package-owned continuation prompt`)
|
||||
}
|
||||
}
|
||||
|
||||
/** Check existing sessions and every candidate event before Session publishes it. */
|
||||
const install: InvariantInstaller = Object.assign((ctx: Context, fail: InvariantFailure) => {
|
||||
for (const session of ctx.sessions.list()) {
|
||||
const prior: SessionEvent[] = []
|
||||
for (const event of session.events) {
|
||||
validateEvent(prior, event, fail)
|
||||
prior.push(event)
|
||||
}
|
||||
}
|
||||
/* jscpd:ignore-start -- package companions share dispatch and registration plumbing */
|
||||
ctx.on('internal/dispatch', (_mode, eventName, args) => {
|
||||
if (eventName !== 'session/event') return
|
||||
const [session, event] = args as [Session, SessionEvent]
|
||||
validateEvent(session.events, event, fail)
|
||||
}, { global: true })
|
||||
}, { inject: ['sessions'] })
|
||||
|
||||
/**
|
||||
* Register the goal-session 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 */
|
||||
143
packages/goal/goal-session/tests/invariant.spec.ts
Normal file
143
packages/goal/goal-session/tests/invariant.spec.ts
Normal file
@@ -0,0 +1,143 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { Context } from 'cordis'
|
||||
import {
|
||||
GoalId,
|
||||
renderGoalChange,
|
||||
type GoalSnapshotChangeMeta,
|
||||
type GoalView,
|
||||
} from '@deepseek-ai/dsh-goal'
|
||||
import * as GoalSessionInvariant from '@deepseek-ai/dsh-goal-session/invariant'
|
||||
import { renderGoalRoundPrompt } from '@deepseek-ai/dsh-goal-session'
|
||||
import InvariantService, { InvariantError } from '@deepseek-ai/dsh-invariants'
|
||||
import SessionStore, { SessionId, type Session } from '@deepseek-ai/dsh-session'
|
||||
|
||||
const change: GoalSnapshotChangeMeta = {
|
||||
kind: 'goal/change',
|
||||
version: 1,
|
||||
operation: 'create',
|
||||
goal: {
|
||||
id: GoalId('goal-session-invariant'),
|
||||
revision: 1,
|
||||
objective: 'verify every continuation prompt',
|
||||
phase: 'active',
|
||||
maxGoalRounds: 2,
|
||||
},
|
||||
roundsStarted: 0,
|
||||
createdAt: 1,
|
||||
updatedAt: 1,
|
||||
}
|
||||
|
||||
const changeSource = {
|
||||
kind: 'goal',
|
||||
goalId: change.goal.id,
|
||||
revision: change.goal.revision,
|
||||
round: 0,
|
||||
} as const
|
||||
|
||||
function view(roundsStarted: number): GoalView {
|
||||
return { ...change.goal, roundsStarted, createdAt: 1, updatedAt: 1, activation: 'armed' }
|
||||
}
|
||||
|
||||
function appendChange(session: Session): void {
|
||||
session.append('turn/start', { turn: 1, trigger: { kind: 'injection', source: changeSource } })
|
||||
session.append('context/message', {
|
||||
content: renderGoalChange(change),
|
||||
source: changeSource,
|
||||
meta: change as never,
|
||||
}, { surfaceOp: 'append' })
|
||||
session.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
|
||||
}
|
||||
|
||||
function appendRound(session: Session, turn: number, content = renderGoalRoundPrompt(view(turn - 2), turn - 1)): void {
|
||||
const source = { kind: 'goal', goalId: change.goal.id, revision: 1, round: turn - 1 } as const
|
||||
session.append('turn/start', { turn, trigger: { kind: 'message', source } })
|
||||
session.append('user/message', { content, source }, { surfaceOp: 'append' })
|
||||
session.append('turn/end', { turn, reason: { kind: 'completed' } })
|
||||
}
|
||||
|
||||
async function mount(sessionFirst = false): Promise<{ ctx: Context; session: Session }> {
|
||||
const ctx = new Context()
|
||||
await ctx.plugin(SessionStore)
|
||||
const session = ctx.sessions.create(SessionId('goal-session-invariant'))
|
||||
if (!sessionFirst) {
|
||||
await ctx.plugin(InvariantService, { enabled: true })
|
||||
await ctx.plugin(GoalSessionInvariant)
|
||||
}
|
||||
return { ctx, session }
|
||||
}
|
||||
|
||||
describe('goal-session prompt invariants', () => {
|
||||
it('reconstructs existing rounds and accepts the next canonical prompt', async () => {
|
||||
const { ctx, session } = await mount(true)
|
||||
appendChange(session)
|
||||
appendRound(session, 2)
|
||||
|
||||
await ctx.plugin(InvariantService, { enabled: true })
|
||||
await ctx.plugin(GoalSessionInvariant)
|
||||
|
||||
expect(() => { appendRound(session, 3) }).not.toThrow()
|
||||
ctx.sessions.create(SessionId('goal-session-invariant-dispatch'))
|
||||
|
||||
const userSource = { kind: 'user' } as const
|
||||
session.append('turn/start', { turn: 4, trigger: { kind: 'message', source: userSource } })
|
||||
session.append('user/message', {
|
||||
content: [{ type: 'text', text: 'ordinary human message' }],
|
||||
source: userSource,
|
||||
}, { surfaceOp: 'append' })
|
||||
session.append('turn/end', { turn: 4, reason: { kind: 'completed' } })
|
||||
|
||||
const stateSource = { ...changeSource, round: 0 } as const
|
||||
session.append('turn/start', { turn: 5, trigger: { kind: 'message', source: stateSource } })
|
||||
expect(() => {
|
||||
session.append('user/message', {
|
||||
content: [{ type: 'text', text: 'round zero is not a driver continuation' }],
|
||||
source: stateSource,
|
||||
}, { surfaceOp: 'append' })
|
||||
}).not.toThrow()
|
||||
})
|
||||
|
||||
it('rejects a continuation whose content differs from the package renderer', async () => {
|
||||
const { session } = await mount()
|
||||
appendChange(session)
|
||||
|
||||
expect(() => {
|
||||
appendRound(session, 2, [{ type: 'text', text: 'counterfeit continuation' }])
|
||||
}).toThrow(expect.objectContaining<Partial<InvariantError>>({
|
||||
code: 'INVARIANT',
|
||||
packageName: '@deepseek-ai/dsh-goal-session',
|
||||
}))
|
||||
})
|
||||
|
||||
it('rejects a goal round without a reconstructable active goal', async () => {
|
||||
const { session } = await mount()
|
||||
const source = { kind: 'goal', goalId: change.goal.id, revision: 1, round: 1 } as const
|
||||
session.append('turn/start', { turn: 1, trigger: { kind: 'message', source } })
|
||||
|
||||
expect(() => {
|
||||
session.append('user/message', {
|
||||
content: renderGoalRoundPrompt(view(0), 1),
|
||||
source,
|
||||
}, { surfaceOp: 'append' })
|
||||
}).toThrow(expect.objectContaining<Partial<InvariantError>>({
|
||||
packageName: '@deepseek-ai/dsh-goal-session',
|
||||
}))
|
||||
})
|
||||
|
||||
it('attributes an invalid durable prefix during late loading', async () => {
|
||||
const { ctx, session } = await mount(true)
|
||||
session.append('turn/start', { turn: 1, trigger: { kind: 'injection', source: changeSource } })
|
||||
session.append('context/message', {
|
||||
content: [{ type: 'text', text: 'counterfeit goal state' }],
|
||||
source: changeSource,
|
||||
meta: change as never,
|
||||
}, { surfaceOp: 'append' })
|
||||
session.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
|
||||
appendRound(session, 2)
|
||||
await ctx.plugin(InvariantService, { enabled: true })
|
||||
|
||||
await expect(ctx.plugin(GoalSessionInvariant)).rejects.toMatchObject({
|
||||
code: 'INVARIANT',
|
||||
packageName: '@deepseek-ai/dsh-goal-session',
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -25,6 +25,9 @@
|
||||
},
|
||||
{
|
||||
"path": "../../core/session"
|
||||
},
|
||||
{
|
||||
"path": "../../support/invariants"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
25
packages/goal/goal-session/tsdown.config.ts
Normal file
25
packages/goal/goal-session/tsdown.config.ts
Normal file
@@ -0,0 +1,25 @@
|
||||
import { defineConfig } from 'tsdown'
|
||||
|
||||
/** Build the package root and invariant companion as independent bundles. */
|
||||
export default defineConfig([
|
||||
{
|
||||
entry: ['lib/types/index.js'],
|
||||
outDir: 'lib',
|
||||
format: ['esm'],
|
||||
platform: 'node',
|
||||
target: 'es2024',
|
||||
fixedExtension: false,
|
||||
dts: false,
|
||||
clean: false,
|
||||
},
|
||||
{
|
||||
entry: ['lib/types/invariant.js'],
|
||||
outDir: 'lib',
|
||||
format: ['esm'],
|
||||
platform: 'node',
|
||||
target: 'es2024',
|
||||
fixedExtension: false,
|
||||
dts: false,
|
||||
clean: false,
|
||||
},
|
||||
])
|
||||
@@ -25,6 +25,8 @@ Injection may append immediately or wait in an active tool-batch FIFO. The servi
|
||||
|
||||
Activation is never persisted. A fresh cache and every `agent/session-start` edge disarm it even when replay finds an active durable phase. A continuation driver also calls `disarm()` before unload or after durability uncertainty. Session resume, fork, and driver replacement therefore retain the objective, phase, revisions, and admitted-round count without initiating work; a later explicit resume mutation must arm continuation.
|
||||
|
||||
The separately published `./invariant` companion maintains an independent fold of each attached session. It rejects malformed goal metadata, source or model-visible content drift, discontinuous revisions, illegal lifecycle transitions, timestamp regressions, and non-sequential admitted rounds before the candidate event enters the durable log.
|
||||
|
||||
## Extension points
|
||||
|
||||
Policy plugins call the service verbs and react to the scoped `goal/changed` event. A continuation consumer admits rounds as `user/message` events with `GoalMessageSource`; ordinary human turns never increment `roundsStarted`. Consumers use the `Agent` interface and events rather than importing `dsh-agent-loop`.
|
||||
|
||||
@@ -11,11 +11,16 @@
|
||||
"types": "./lib/types/index.d.ts",
|
||||
"default": "./lib/index.js"
|
||||
},
|
||||
"./invariant": {
|
||||
"types": "./lib/types/invariant.d.ts",
|
||||
"default": "./lib/invariant.js"
|
||||
},
|
||||
"./src/*": "./src/*",
|
||||
"./package.json": "./package.json"
|
||||
},
|
||||
"files": [
|
||||
"lib/index.js",
|
||||
"lib/invariant.js",
|
||||
"lib/types/**/*.d.ts",
|
||||
"lib/types/**/*.d.ts.map",
|
||||
"src"
|
||||
@@ -24,6 +29,7 @@
|
||||
"peerDependencies": {
|
||||
"@deepseek-ai/dsh-agent": "^0.0.1",
|
||||
"@deepseek-ai/dsh-brand": "^0.0.1",
|
||||
"@deepseek-ai/dsh-invariants": "^0.0.1",
|
||||
"@deepseek-ai/dsh-llm": "^0.0.1",
|
||||
"@deepseek-ai/dsh-scope": "^0.0.1",
|
||||
"@deepseek-ai/dsh-session": "^0.0.1",
|
||||
@@ -35,6 +41,7 @@
|
||||
"devDependencies": {
|
||||
"@deepseek-ai/dsh-agent": "workspace:^",
|
||||
"@deepseek-ai/dsh-brand": "workspace:^",
|
||||
"@deepseek-ai/dsh-invariants": "workspace:^",
|
||||
"@deepseek-ai/dsh-llm": "workspace:^",
|
||||
"@deepseek-ai/dsh-loader-smoke": "workspace:^",
|
||||
"@deepseek-ai/dsh-scope": "workspace:^",
|
||||
|
||||
79
packages/goal/goal/src/invariant.ts
Normal file
79
packages/goal/goal/src/invariant.ts
Normal file
@@ -0,0 +1,79 @@
|
||||
/** Package-owned durable goal-stream invariants. @module @deepseek-ai/dsh-goal/invariant */
|
||||
|
||||
import type { Context } from 'cordis'
|
||||
import type { InvariantFailure, InvariantInstaller } from '@deepseek-ai/dsh-invariants'
|
||||
import type { Session, SessionEvent } from '@deepseek-ai/dsh-session'
|
||||
import { applyGoalEvent, emptyGoalFoldState } from './fold.ts'
|
||||
import type { GoalFoldState } from './fold.ts'
|
||||
|
||||
const PACKAGE_NAME = '@deepseek-ai/dsh-goal'
|
||||
|
||||
/** Cordis companion plugin name. */
|
||||
export const name = 'goal-invariant'
|
||||
/** Service required before the companion can reserve package ownership. */
|
||||
export const inject = ['invariants']
|
||||
|
||||
/** Copy the independent fold before validating one candidate event. */
|
||||
function cloneState(state: GoalFoldState): GoalFoldState {
|
||||
return {
|
||||
goal: state.goal,
|
||||
roundsStarted: state.roundsStarted,
|
||||
createdAt: state.createdAt,
|
||||
updatedAt: state.updatedAt,
|
||||
lastRef: state.lastRef,
|
||||
seenGoalIds: new Set(state.seenGoalIds),
|
||||
}
|
||||
}
|
||||
|
||||
/** Apply one event through the strict goal decoder and attribute failures. */
|
||||
function applyChecked(state: GoalFoldState, event: SessionEvent, fail: InvariantFailure): void {
|
||||
try {
|
||||
applyGoalEvent(state, event)
|
||||
} catch (error) {
|
||||
/* v8 ignore next -- the strict goal decoder throws Error instances */
|
||||
const message = error instanceof Error ? error.message : String(error)
|
||||
fail(`session event ${event.seq} violates the durable goal stream: ${message}`)
|
||||
}
|
||||
}
|
||||
|
||||
/** Install an independent incremental fold over every attached session. */
|
||||
const install: InvariantInstaller = Object.assign((ctx: Context, fail: InvariantFailure) => {
|
||||
const states = new WeakMap<Session, GoalFoldState>()
|
||||
const staged = new WeakMap<SessionEvent, { session: Session; state: GoalFoldState }>()
|
||||
|
||||
const seed = (session: Session): GoalFoldState => {
|
||||
const state = emptyGoalFoldState()
|
||||
for (const event of session.events) applyChecked(state, event, fail)
|
||||
states.set(session, state)
|
||||
return state
|
||||
}
|
||||
/* v8 ignore next -- session/event always follows list() or session/created seeding */
|
||||
const stateFor = (session: Session): GoalFoldState => states.get(session) ?? seed(session)
|
||||
|
||||
for (const session of ctx.sessions.list()) seed(session)
|
||||
ctx.on('session/created', (session) => { seed(session) }, { global: true })
|
||||
ctx.on('internal/dispatch', (_mode, eventName, args) => {
|
||||
if (eventName !== 'session/event') return
|
||||
const [session, event] = args as [Session, SessionEvent]
|
||||
const state = cloneState(stateFor(session))
|
||||
applyChecked(state, event, fail)
|
||||
staged.set(event, { session, state })
|
||||
}, { global: true })
|
||||
ctx.on('session/event', (session, event) => {
|
||||
const candidate = staged.get(event)
|
||||
/* v8 ignore next 2 -- internal/dispatch stages the exact callback arguments */
|
||||
if (candidate === undefined || candidate.session !== session) {
|
||||
return fail('session/event reached publication without matching goal-fold validation')
|
||||
}
|
||||
staged.delete(event)
|
||||
states.set(session, candidate.state)
|
||||
}, { global: true })
|
||||
}, { inject: ['sessions'] })
|
||||
|
||||
/**
|
||||
* Register the goal-stream 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))
|
||||
121
packages/goal/goal/tests/invariant.spec.ts
Normal file
121
packages/goal/goal/tests/invariant.spec.ts
Normal file
@@ -0,0 +1,121 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { Context } from 'cordis'
|
||||
import {
|
||||
GoalId,
|
||||
renderGoalChange,
|
||||
type GoalSnapshotChangeMeta,
|
||||
} from '@deepseek-ai/dsh-goal'
|
||||
import * as GoalInvariantCompanion from '@deepseek-ai/dsh-goal/invariant'
|
||||
import InvariantService, { InvariantError } from '@deepseek-ai/dsh-invariants'
|
||||
import SessionStore, { SessionId } from '@deepseek-ai/dsh-session'
|
||||
|
||||
const change: GoalSnapshotChangeMeta = {
|
||||
kind: 'goal/change',
|
||||
version: 1,
|
||||
operation: 'create',
|
||||
goal: {
|
||||
id: GoalId('goal-invariant'),
|
||||
revision: 1,
|
||||
objective: 'check the stream',
|
||||
phase: 'active',
|
||||
maxGoalRounds: 2,
|
||||
},
|
||||
roundsStarted: 0,
|
||||
createdAt: 1,
|
||||
updatedAt: 1,
|
||||
}
|
||||
|
||||
const changeSource = {
|
||||
kind: 'goal',
|
||||
goalId: change.goal.id,
|
||||
revision: change.goal.revision,
|
||||
round: 0,
|
||||
} as const
|
||||
|
||||
async function setup(): Promise<Context> {
|
||||
const ctx = new Context()
|
||||
await ctx.plugin(SessionStore)
|
||||
await ctx.plugin(InvariantService, { enabled: true })
|
||||
await ctx.plugin(GoalInvariantCompanion)
|
||||
return ctx
|
||||
}
|
||||
|
||||
describe('goal stream invariants', () => {
|
||||
it('accepts canonical goal snapshots and sequential admitted rounds', async () => {
|
||||
const ctx = await setup()
|
||||
const session = ctx.sessions.create(SessionId('goal-invariant-valid'))
|
||||
session.append('turn/start', { turn: 1, trigger: { kind: 'injection', source: changeSource } })
|
||||
session.append('context/message', {
|
||||
content: renderGoalChange(change),
|
||||
source: changeSource,
|
||||
meta: change as never,
|
||||
}, { surfaceOp: 'append' })
|
||||
session.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
|
||||
session.append('turn/start', {
|
||||
turn: 2,
|
||||
trigger: {
|
||||
kind: 'message',
|
||||
source: { kind: 'goal', goalId: change.goal.id, revision: 1, round: 1 },
|
||||
},
|
||||
})
|
||||
expect(() => {
|
||||
session.append('user/message', {
|
||||
content: [{ type: 'text', text: 'continue' }],
|
||||
source: { kind: 'goal', goalId: change.goal.id, revision: 1, round: 1 },
|
||||
}, { surfaceOp: 'append' })
|
||||
}).not.toThrow()
|
||||
})
|
||||
|
||||
it('rejects model-visible drift before committing it and keeps the fold reusable', async () => {
|
||||
const ctx = await setup()
|
||||
const session = ctx.sessions.create(SessionId('goal-invariant-invalid'))
|
||||
session.append('turn/start', { turn: 1, trigger: { kind: 'injection', source: changeSource } })
|
||||
expect(() => {
|
||||
session.append('context/message', {
|
||||
content: [{ type: 'text', text: 'counterfeit' }],
|
||||
source: changeSource,
|
||||
meta: change as never,
|
||||
}, { surfaceOp: 'append' })
|
||||
}).toThrow(expect.objectContaining<Partial<InvariantError>>({
|
||||
code: 'INVARIANT',
|
||||
packageName: '@deepseek-ai/dsh-goal',
|
||||
}))
|
||||
expect(session.seq).toBe(1)
|
||||
expect(() => {
|
||||
session.append('context/message', {
|
||||
content: renderGoalChange(change),
|
||||
source: changeSource,
|
||||
meta: change as never,
|
||||
}, { surfaceOp: 'append' })
|
||||
}).not.toThrow()
|
||||
})
|
||||
|
||||
it('reconstructs an existing durable goal before checking later rounds', async () => {
|
||||
const ctx = new Context()
|
||||
await ctx.plugin(SessionStore)
|
||||
const session = ctx.sessions.create(SessionId('goal-invariant-late-load'))
|
||||
session.append('turn/start', { turn: 1, trigger: { kind: 'injection', source: changeSource } })
|
||||
session.append('context/message', {
|
||||
content: renderGoalChange(change),
|
||||
source: changeSource,
|
||||
meta: change as never,
|
||||
}, { surfaceOp: 'append' })
|
||||
session.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
|
||||
|
||||
await ctx.plugin(InvariantService, { enabled: true })
|
||||
await ctx.plugin(GoalInvariantCompanion)
|
||||
session.append('turn/start', {
|
||||
turn: 2,
|
||||
trigger: {
|
||||
kind: 'message',
|
||||
source: { kind: 'goal', goalId: change.goal.id, revision: 1, round: 1 },
|
||||
},
|
||||
})
|
||||
expect(() => {
|
||||
session.append('user/message', {
|
||||
content: [{ type: 'text', text: 'continue after load' }],
|
||||
source: { kind: 'goal', goalId: change.goal.id, revision: 1, round: 1 },
|
||||
}, { surfaceOp: 'append' })
|
||||
}).not.toThrow()
|
||||
})
|
||||
})
|
||||
@@ -31,6 +31,9 @@
|
||||
},
|
||||
{
|
||||
"path": "../../core/agent"
|
||||
},
|
||||
{
|
||||
"path": "../../support/invariants"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
25
packages/goal/goal/tsdown.config.ts
Normal file
25
packages/goal/goal/tsdown.config.ts
Normal file
@@ -0,0 +1,25 @@
|
||||
import { defineConfig } from 'tsdown'
|
||||
|
||||
/** Build the package root and invariant companion as independent bundles. */
|
||||
export default defineConfig([
|
||||
{
|
||||
entry: ['lib/types/index.js'],
|
||||
outDir: 'lib',
|
||||
format: ['esm'],
|
||||
platform: 'node',
|
||||
target: 'es2024',
|
||||
fixedExtension: false,
|
||||
dts: false,
|
||||
clean: false,
|
||||
},
|
||||
{
|
||||
entry: ['lib/types/invariant.js'],
|
||||
outDir: 'lib',
|
||||
format: ['esm'],
|
||||
platform: 'node',
|
||||
target: 'es2024',
|
||||
fixedExtension: false,
|
||||
dts: false,
|
||||
clean: false,
|
||||
},
|
||||
])
|
||||
@@ -11,11 +11,16 @@
|
||||
"types": "./lib/types/index.d.ts",
|
||||
"default": "./lib/index.js"
|
||||
},
|
||||
"./invariant": {
|
||||
"types": "./lib/types/invariant.d.ts",
|
||||
"default": "./lib/invariant.js"
|
||||
},
|
||||
"./src/*": "./src/*",
|
||||
"./package.json": "./package.json"
|
||||
},
|
||||
"files": [
|
||||
"lib/index.js",
|
||||
"lib/invariant.js",
|
||||
"lib/types/**/*.d.ts",
|
||||
"lib/types/**/*.d.ts.map",
|
||||
"src"
|
||||
@@ -24,6 +29,7 @@
|
||||
"peerDependencies": {
|
||||
"@deepseek-ai/dsh-agent": "^0.0.1",
|
||||
"@deepseek-ai/dsh-goal": "^0.0.1",
|
||||
"@deepseek-ai/dsh-invariants": "^0.0.1",
|
||||
"@deepseek-ai/dsh-llm": "^0.0.1",
|
||||
"@deepseek-ai/dsh-session": "^0.0.1",
|
||||
"@deepseek-ai/dsh-system-prompt": "^0.0.1",
|
||||
@@ -37,6 +43,7 @@
|
||||
"@cordisjs/plugin-loader": "workspace:^",
|
||||
"@deepseek-ai/dsh-agent": "workspace:^",
|
||||
"@deepseek-ai/dsh-goal": "workspace:^",
|
||||
"@deepseek-ai/dsh-invariants": "workspace:^",
|
||||
"@deepseek-ai/dsh-llm": "workspace:^",
|
||||
"@deepseek-ai/dsh-session": "workspace:^",
|
||||
"@deepseek-ai/dsh-system-prompt": "workspace:^",
|
||||
|
||||
30
packages/goal/tool-goal/src/invariant.ts
Normal file
30
packages/goal/tool-goal/src/invariant.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
/**
|
||||
* Package-owned invariant companion for `@deepseek-ai/dsh-tool-goal`.
|
||||
* @module @deepseek-ai/dsh-tool-goal/invariant
|
||||
*/
|
||||
|
||||
/* jscpd:ignore-start */
|
||||
import type { Context } from 'cordis'
|
||||
import type { InvariantInstaller } from '@deepseek-ai/dsh-invariants'
|
||||
|
||||
const PACKAGE_NAME = '@deepseek-ai/dsh-tool-goal'
|
||||
|
||||
/** Cordis companion plugin name. */
|
||||
export const name = 'tool-goal-invariant'
|
||||
/** Service required before the companion can reserve package ownership. */
|
||||
export const inject = ['invariants']
|
||||
|
||||
/**
|
||||
* No runtime invariant: this model-facing adapter owns no independent state or event protocol;
|
||||
* accepted mutations are checked by the goal domain and authority behavior is package-tested.
|
||||
*/
|
||||
const install: InvariantInstaller = () => {}
|
||||
|
||||
/**
|
||||
* Register this package's 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 */
|
||||
@@ -34,6 +34,9 @@
|
||||
},
|
||||
{
|
||||
"path": "../goal"
|
||||
},
|
||||
{
|
||||
"path": "../../support/invariants"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user