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

@@ -16,7 +16,7 @@ These package-specific rules supplement the repo-wide [conventions](../AGENTS.md
- **Publish state only at its commit point.** Emit each notification and update derived state only after the success boundary that makes it true; derive caches, prompts, UI echoes, replay, and query views from one authoritative source.
- **Apply bounds to the complete result.** Enforce byte, token, item, and time limits where the complete emitted or retained value, including wrappers and metadata, is known; test tiny and exact limits, oversized single chunks, and multibyte byte limits.
- **Registry contributions prove disposal.** Add the HMR-safety test required by the [testing policy](../docs/testing.md): dispose the contributing fiber and observe removal.
- **Every package owns executable invariants.** Publish `./invariant`, register its manifest name, and enforce a runtime contract with the bound reporter; generated, empty, and reporter-free installers fail `verify-package-invariants` ([rationale](../.agents/notes/implemented/architecture/2026-07-19-package-invariant-runtime-contracts.md)).
- **Every package owns an explicit invariant companion.** Publish `./invariant` and register its manifest name. Check observable event or mutable-data relationships; when none exists, keep an empty installer with a package-specific `No runtime invariant:` explanation instead of inventing an API-shape assertion. Generated companions, unexplained empties, and non-empty installers that ignore the reporter fail `verify-package-invariants` ([rationale](../.agents/notes/implemented/architecture/2026-07-19-package-invariant-runtime-contracts.md)).
Naming notes:

View File

@@ -1,28 +1,24 @@
/** Package-owned runtime contract checks for `@deepseek-ai/dsh-bash-local`. @module @deepseek-ai/dsh-bash-local/invariant */
/**
* Package-owned invariant companion for `@deepseek-ai/dsh-bash-local`.
* @module @deepseek-ai/dsh-bash-local/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-bash-local'
/** Cordis companion plugin name. */
export const name = 'bash-local-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: 'LocalBashExecutor',
effects: [
'ctx.provide("bash")',
'local bash teardown',
],
services: [
'bash',
],
})
}
/**
* No runtime invariant: this package exposes no independent event sequence or mutable data relation
* beyond contracts enforced at its owning seam.
*/
const install: InvariantInstaller = () => {}
/**
* Register this package's invariant companion.
@@ -31,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,30 +1,24 @@
/** Package-owned runtime contract checks for `@deepseek-ai/dsh-bash-sandbox`. @module @deepseek-ai/dsh-bash-sandbox/invariant */
/**
* Package-owned invariant companion for `@deepseek-ai/dsh-bash-sandbox`.
* @module @deepseek-ai/dsh-bash-sandbox/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-bash-sandbox'
/** Cordis companion plugin name. */
export const name = 'bash-sandbox-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: 'SandboxBashExecutor',
inject: [
'sandbox',
],
effects: [
'ctx.provide("bash")',
],
services: [
'bash',
],
})
}
/**
* No runtime invariant: this package exposes no independent event sequence or mutable data relation
* beyond contracts enforced at its owning seam.
*/
const install: InvariantInstaller = () => {}
/**
* Register this package's invariant companion.
@@ -33,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,24 +1,30 @@
/** Package-owned runtime contract checks for `@deepseek-ai/dsh-bash`. @module @deepseek-ai/dsh-bash/invariant */
/** Package-owned session-event invariants for the bash seam. @module @deepseek-ai/dsh-bash/invariant */
import type { Context } from 'cordis'
import { observeServiceInvariant, serviceShapeViolation, type InvariantInstaller } from '@deepseek-ai/dsh-invariants'
import type { Session, SessionEvent } from '@deepseek-ai/dsh-session'
import type { InvariantInstaller } from '@deepseek-ai/dsh-invariants'
import { SANDBOX_MODES } from './session-mode.ts'
const PACKAGE_NAME = '@deepseek-ai/dsh-bash'
/** Cordis companion plugin name. */
export const name = 'bash-invariant'
/** Services required before the companion can register. */
/** Service required before the companion can reserve package ownership. */
export const inject = ['invariants']
/** Validate every implementation bound to this package's service seam. */
/** Install validation for the durable sandbox-mode vocabulary. */
const install: InvariantInstaller = (ctx, fail) => {
observeServiceInvariant(ctx, fail, 'bash', value => serviceShapeViolation(value, {
methods: ['resolve', 'run', 'start'],
}))
ctx.on('internal/dispatch', (_mode, eventName, args) => {
if (eventName !== 'session/event') return
const event = (args as [Session, SessionEvent])[1]
if (event.type === 'bash/sandbox-mode' && !SANDBOX_MODES.includes(event.data.mode)) {
fail(`bash/sandbox-mode carries unknown mode ${JSON.stringify(event.data.mode)}`)
}
}, { global: true })
}
/**
* Register this package's invariant companion.
* Register the bash invariant companion.
* @param ctx - Cordis context carrying the invariant service.
* @returns the installed registration's disposer after setup succeeds.
*/

View File

@@ -0,0 +1,33 @@
import { describe, expect, it } from 'vitest'
import { Context } from 'cordis'
import type { Session, SessionEvent } from '@deepseek-ai/dsh-session'
import InvariantService from '@deepseek-ai/dsh-invariants'
import * as BashInvariant from '@deepseek-ai/dsh-bash/invariant'
async function setup(): Promise<Context> {
const ctx = new Context()
await ctx.plugin(InvariantService)
await ctx.plugin(BashInvariant)
return ctx
}
function modeEvent(mode: string): SessionEvent {
return { type: 'bash/sandbox-mode', seq: 0, time: 0, data: { mode } } as SessionEvent
}
describe('bash invariants', () => {
it('accepts the closed sandbox vocabulary and ignores unrelated events', async () => {
const ctx = await setup()
expect(() => { ctx.emit('session/event', {} as Session, modeEvent('workspace-write')) }).not.toThrow()
expect(() => { ctx.emit('session/event', {} as Session, {
type: 'turn/start', seq: 0, time: 0, data: {},
} as SessionEvent) }).not.toThrow()
expect(() => { ctx.emit('tools/change') }).not.toThrow()
})
it('rejects an unknown durable sandbox mode', async () => {
const ctx = await setup()
expect(() => { ctx.emit('session/event', {} as Session, modeEvent('host-root')) })
.toThrow(/unknown mode "host-root"/)
})
})

View File

@@ -1,34 +1,24 @@
/** Package-owned runtime contract checks for `@deepseek-ai/dsh-tool-bash`. @module @deepseek-ai/dsh-tool-bash/invariant */
/**
* Package-owned invariant companion for `@deepseek-ai/dsh-tool-bash`.
* @module @deepseek-ai/dsh-tool-bash/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-tool-bash'
/** Cordis companion plugin name. */
export const name = 'tool-bash-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: 'tool-bash',
inject: [
'tools',
'bash',
'systemPrompt',
],
effects: [
'ctx.provide("bashEnv")',
'bashEnv.register()',
'tools.register()',
],
services: [
'bashEnv',
],
})
}
/**
* No runtime invariant: the environment registry validates ownership and collected values at each
* mutation/read; it publishes no independent snapshot that a companion could cross-check.
*/
const install: InvariantInstaller = () => {}
/**
* Register this package's invariant companion.
@@ -37,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,31 +1,24 @@
/**
* Package-owned runtime contract checks for `@deepseek-ai/dsh-code-runtime-worker`.
* Package-owned invariant companion for `@deepseek-ai/dsh-code-runtime-worker`.
* @module @deepseek-ai/dsh-code-runtime-worker/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-code-runtime-worker'
/** Cordis companion plugin name. */
export const name = 'code-runtime-worker-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: 'WorkerCodeRuntime',
effects: [
'ctx.provide("codeRuntime")',
'worker code-runtime teardown',
],
services: [
'codeRuntime',
],
})
}
/**
* No runtime invariant: this process-boundary implementation exposes no same-process event relation;
* worker protocol and built-worker tests cover it.
*/
const install: InvariantInstaller = () => {}
/**
* Register this package's invariant companion.
@@ -34,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,29 +1,24 @@
/** Package-owned runtime contract checks for `@deepseek-ai/dsh-code-runtime`. @module @deepseek-ai/dsh-code-runtime/invariant */
/**
* Package-owned invariant companion for `@deepseek-ai/dsh-code-runtime`.
* @module @deepseek-ai/dsh-code-runtime/invariant
*/
/* jscpd:ignore-start */
import type { Context } from 'cordis'
import { observeServiceInvariant, serviceShapeViolation, type InvariantInstaller } from '@deepseek-ai/dsh-invariants'
import type { InvariantInstaller } from '@deepseek-ai/dsh-invariants'
const PACKAGE_NAME = '@deepseek-ai/dsh-code-runtime'
/** Cordis companion plugin name. */
export const name = 'code-runtime-invariant'
/** Services required before the companion can register. */
/** Service required before the companion can reserve package ownership. */
export const inject = ['invariants']
/** Validate every implementation bound to this package's service seam. */
const install: InvariantInstaller = (ctx, fail) => {
observeServiceInvariant(ctx, fail, 'codeRuntime', (value) => {
const violation = serviceShapeViolation(value, {
methods: ['run'],
stringProperties: ['language', 'isolation'],
})
if (violation !== undefined) return violation
const service = value as { language: string; isolation: string }
return /^[a-z][a-z0-9-]*$/.test(service.language) && /^[a-z][a-z0-9-]*$/.test(service.isolation)
? undefined
: 'code runtime language and isolation must be lowercase identifiers'
})
}
/**
* No runtime invariant: this package exposes no independent event sequence or mutable data relation
* beyond contracts enforced at its owning seam.
*/
const install: InvariantInstaller = () => {}
/**
* Register this package's invariant companion.
@@ -32,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

@@ -2,7 +2,6 @@ import { describe, expect, it } from 'vitest'
import { Context } from 'cordis'
import { CodeRuntime } from '@deepseek-ai/dsh-code-runtime'
import type { CodeRunRequest, CodeRunResult } from '@deepseek-ai/dsh-code-runtime'
import { InvariantError } from '@deepseek-ai/dsh-invariants'
/**
* Minimal concrete runtime: records requests, "executes" by invoking every
@@ -86,24 +85,4 @@ describe('CodeRuntime service seam', () => {
await expect(ctx.plugin(StubRuntime)).rejects.toThrow(/registered/)
})
it.each([
[{ language: 'typescript', isolation: 'worker' }, /must expose method "run"/],
[{ language: 'TypeScript', isolation: 'worker', run() {} }, /must be lowercase identifiers/],
])('rejects an invalid runtime implementation through the package invariant', async (value, message) => {
const ctx = new Context()
const invalidRuntime = {
name: 'invalid-code-runtime',
apply(child: Context) {
child.provide('codeRuntime', value as unknown as CodeRuntime)
},
}
let caught: unknown
try {
await ctx.plugin(invalidRuntime)
} catch (error) {
caught = error
}
expect(caught).toBeInstanceOf(InvariantError)
expect((caught as Error).message).toMatch(message)
})
})

View File

@@ -1,46 +1,24 @@
/** Package-owned runtime contract checks for `@deepseek-ai/dsh-compact-basic`. @module @deepseek-ai/dsh-compact-basic/invariant */
/**
* Package-owned invariant companion for `@deepseek-ai/dsh-compact-basic`.
* @module @deepseek-ai/dsh-compact-basic/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-compact-basic'
/** Cordis companion plugin name. */
export const name = 'compact-basic-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: 'BasicCompactService',
inject: [
'llm',
'tokenMeter',
],
effects: [
'ctx.provide("compact")',
],
services: [
'compact',
],
validate: (fiber, effectLabels) => {
const automaticEffects = [
'ctx.on("agent/post-step")',
'ctx.on("agent/request-error")',
]
const installed = automaticEffects.filter(label => effectLabels.has(label)).length
const automatic = (fiber.config as { auto?: boolean }).auto !== false
if (automatic && installed !== automaticEffects.length) {
return 'automatic compaction must install both pressure and overflow listeners'
}
if (!automatic && installed !== 0) {
return 'auto:false must install neither automatic compaction listener'
}
return undefined
},
})
}
/**
* No runtime invariant: this package exposes no independent event sequence or mutable data relation
* beyond contracts enforced at its owning seam.
*/
const install: InvariantInstaller = () => {}
/**
* Register this package's invariant companion.
@@ -49,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

@@ -5,7 +5,7 @@ import type { BasicCompactConfig } from '@deepseek-ai/dsh-compact-basic'
import { selectCompactableRange } from '@deepseek-ai/dsh-compact-basic/src/region.ts'
import { toolPairingBalancedAfter, toolPairingBalancedBefore } from '@deepseek-ai/dsh-compact'
import { resolveConfig } from '@deepseek-ai/dsh-compact-basic/src/config.ts'
import type { CompactService, CompactionResult } from '@deepseek-ai/dsh-compact'
import type { CompactionResult } from '@deepseek-ai/dsh-compact'
import LlmService, { CallId, CONTEXT_WINDOW_EXCEEDED_CODE, LlmAdapter } from '@deepseek-ai/dsh-llm'
import type { ContentBlock, GenerateOptions, StreamChunk } from '@deepseek-ai/dsh-llm'
import { Session, SessionId } from '@deepseek-ai/dsh-session'
@@ -199,28 +199,6 @@ describe('compact configuration and defaults', () => {
}
})
it.each([
[{ auto: true }, false, /must install both pressure and overflow listeners/],
[{ auto: false }, true, /must install neither automatic compaction listener/],
])('rejects an inconsistent automatic-listener topology through the package invariant', async (config, installListener, message) => {
const ctx = new Context()
await ctx.plugin(LlmService)
await ctx.plugin(TokenMeterService)
const invalidCompact = {
name: 'BasicCompactService',
inject: ['llm', 'tokenMeter'],
apply(child: Context, _config: { auto?: boolean }) {
child.provide('compact', {
compactIfNeeded() {},
compactRegion() {},
} as unknown as CompactService)
if (installListener) {
child.effect(() => () => {}, 'ctx.on("agent/post-step")')
}
},
}
await expect(ctx.plugin(invalidCompact, config)).rejects.toThrow(message)
})
})
describe('pressure measurement and retention', () => {

View File

@@ -1,24 +1,106 @@
/** Package-owned runtime contract checks for `@deepseek-ai/dsh-compact`. @module @deepseek-ai/dsh-compact/invariant */
/** Package-owned compaction log-stream invariants. @module @deepseek-ai/dsh-compact/invariant */
import type { Context } from 'cordis'
import { observeServiceInvariant, serviceShapeViolation, 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-compact'
/** Cordis companion plugin name. */
export const name = 'compact-invariant'
/** Services required before the companion can register. */
/** Service required before the companion can reserve package ownership. */
export const inject = ['invariants']
/** Validate every implementation bound to this package's service seam. */
const install: InvariantInstaller = (ctx, fail) => {
observeServiceInvariant(ctx, fail, 'compact', value => serviceShapeViolation(value, {
methods: ['compactIfNeeded', 'compactRegion'],
}))
interface CompactionTrace {
turn: number
summarized: boolean
}
type CompactionTransition =
| { kind: 'start'; turn: number }
| { kind: 'summary'; turn: number }
| { kind: 'end' }
/** Validate one compaction event without advancing committed trace state. */
function validateCompactionEvent(
open: CompactionTrace | undefined,
event: SessionEvent,
fail: InvariantFailure,
): CompactionTransition | undefined {
if (event.type === 'compact/start') {
if (open !== undefined) fail(`compact/start for turn ${event.data.turn} while turn ${open.turn} is still compacting`)
return { kind: 'start', turn: event.data.turn }
}
if (event.type === 'compact/summary') {
if (open === undefined) fail('compact/summary has no matching compact/start')
if (open.summarized) fail('compact/summary repeated within one compaction')
const seqs = event.data.shadowedSeqs
if (seqs.length === 0) fail('compact/summary shadowedSeqs must be non-empty')
if (seqs[0] !== event.data.shadowedRange.start || seqs.at(-1) !== event.data.shadowedRange.end) {
fail('compact/summary shadowedRange must match the first and last shadowedSeqs')
}
if (!Number.isSafeInteger(event.data.shadowedTokenCount) || event.data.shadowedTokenCount < 0) {
fail('compact/summary shadowedTokenCount must be a non-negative safe integer')
}
return { kind: 'summary', turn: open.turn }
}
if (event.type !== 'compact/end') return undefined
if (open === undefined) fail('compact/end has no matching compact/start')
if (event.data.turn !== open.turn) {
fail(`compact/end turn ${event.data.turn} does not match compact/start turn ${open.turn}`)
}
if (event.data.error === undefined && !open.summarized) {
fail('successful compact/end requires one compact/summary')
}
return { kind: 'end' }
}
/** Apply one committed compaction transition. */
function applyCompactionTransition(
transition: CompactionTransition,
): CompactionTrace | undefined {
if (transition.kind === 'start') return { turn: transition.turn, summarized: false }
if (transition.kind === 'summary') return { turn: transition.turn, summarized: true }
return undefined
}
/** Install compaction start/summary/end checks. */
const install: InvariantInstaller = Object.assign((ctx: Context, fail: InvariantFailure) => {
const traces = new WeakMap<Session, CompactionTrace>()
const staged = new WeakMap<SessionEvent, { session: Session; transition: CompactionTransition }>()
const seed = (session: Session): void => {
let open: CompactionTrace | undefined
for (const event of session.events) {
const transition = validateCompactionEvent(open, event, fail)
if (transition !== undefined) open = applyCompactionTransition(transition)
}
if (open !== undefined) traces.set(session, open)
}
const traceFor = (session: Session): CompactionTrace | undefined => traces.get(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 !== 'compact/start' && event.type !== 'compact/summary' && event.type !== 'compact/end') return
const candidate = staged.get(event)
/* v8 ignore next -- internal/dispatch stages every compaction event */
if (candidate === undefined || candidate.session !== session) return fail('compaction event published without pre-commit validation')
staged.delete(event)
const next = applyCompactionTransition(candidate.transition)
if (next === undefined) traces.delete(session)
else traces.set(session, next)
}, { global: true })
ctx.on('internal/dispatch', (_mode, eventName, args) => {
if (eventName !== 'session/event') return
const [session, event] = args as [Session, SessionEvent]
const transition = validateCompactionEvent(traceFor(session), event, fail)
if (transition !== undefined) staged.set(event, { session, transition })
}, { global: true })
}, { inject: ['sessions'] })
/**
* Register this package's invariant companion.
* Register the compact invariant companion.
* @param ctx - Cordis context carrying the invariant service.
* @returns the installed registration's disposer after setup succeeds.
*/

View File

@@ -38,7 +38,7 @@ class StubCompactService extends CompactService {
const summaryEvent = session.append('compact/summary', {
summary,
shadowedRange: { start, end },
shadowedSeqs: [],
shadowedSeqs: [start],
shadowedTokenCount: 0,
provider: 'mock',
model: 'stub',
@@ -50,7 +50,7 @@ class StubCompactService extends CompactService {
endSeq: endEvent.seq,
summary,
shadowedRange: { start, end },
shadowedSeqs: [],
shadowedSeqs: [start],
shadowedTokenCount: 0,
}
}

View File

@@ -0,0 +1,90 @@
import { describe, expect, it } from 'vitest'
import { Context } from 'cordis'
import SessionStore from '@deepseek-ai/dsh-session'
import * as CompactInvariant from '@deepseek-ai/dsh-compact/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(CompactInvariant)
return ctx
}
const summary = (overrides: Record<string, unknown> = {}) => ({
summary: [{ type: 'text' as const, text: 'short' }],
shadowedRange: { start: 2, end: 4 },
shadowedSeqs: [2, 3, 4],
shadowedTokenCount: 12,
provider: 'mock',
model: 'mock',
...overrides,
})
describe('compaction invariants', () => {
it('accepts successful and failed compaction lifecycles', async () => {
const ctx = await setup()
const success = ctx.sessions.create()
success.append('compact/start', { turn: 1 })
success.append('compact/summary', summary())
success.append('compact/end', { turn: 1 })
const failed = ctx.sessions.create()
failed.append('compact/start', { turn: 2 })
failed.append('compact/end', { turn: 2, error: 'provider failed' })
})
it('rebuilds an open trace when the companion loads after the 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('compact/start', { turn: 3 })
await ctx.plugin(InvariantService)
await ctx.plugin(CompactInvariant)
expect(() => session.append('compact/end', { turn: 3, error: 'resume failed' })).not.toThrow()
session.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
})
it.each([
['summary without start', (session: ReturnType<Context['sessions']['create']>) => {
session.append('compact/summary', summary())
}, /no matching compact\/start/],
['nested start', (session: ReturnType<Context['sessions']['create']>) => {
session.append('compact/start', { turn: 1 })
session.append('compact/start', { turn: 2 })
}, /still compacting/],
['repeated summary', (session: ReturnType<Context['sessions']['create']>) => {
session.append('compact/start', { turn: 1 })
session.append('compact/summary', summary())
session.append('compact/summary', summary())
}, /repeated within one compaction/],
['empty shadow set', (session: ReturnType<Context['sessions']['create']>) => {
session.append('compact/start', { turn: 1 })
session.append('compact/summary', summary({ shadowedSeqs: [] }))
}, /shadowedSeqs must be non-empty/],
['wrong endpoints', (session: ReturnType<Context['sessions']['create']>) => {
session.append('compact/start', { turn: 1 })
session.append('compact/summary', summary({ shadowedRange: { start: 1, end: 4 } }))
}, /shadowedRange must match/],
['invalid token count', (session: ReturnType<Context['sessions']['create']>) => {
session.append('compact/start', { turn: 1 })
session.append('compact/summary', summary({ shadowedTokenCount: -1 }))
}, /non-negative safe integer/],
['end without start', (session: ReturnType<Context['sessions']['create']>) => {
session.append('compact/end', { turn: 1, error: 'failed' })
}, /no matching compact\/start/],
['wrong end turn', (session: ReturnType<Context['sessions']['create']>) => {
session.append('compact/start', { turn: 1 })
session.append('compact/end', { turn: 2, error: 'failed' })
}, /does not match/],
['success without summary', (session: ReturnType<Context['sessions']['create']>) => {
session.append('compact/start', { turn: 1 })
session.append('compact/end', { turn: 1 })
}, /requires one compact\/summary/],
])('rejects %s', async (_name, action, message) => {
const ctx = await setup()
expect(() => { action(ctx.sessions.create()) }).toThrow(message)
})
})

View File

@@ -1,30 +1,64 @@
/** Package-owned runtime contract checks for `@deepseek-ai/dsh-time-context`. @module @deepseek-ai/dsh-time-context/invariant */
/** Package-owned durable clock-context invariants. @module @deepseek-ai/dsh-time-context/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'
const PACKAGE_NAME = '@deepseek-ai/dsh-time-context'
const SOURCE_NAME = 'time-context'
const READING = new RegExp(
'^Time sampled while preparing turn (\\d+), step (\\d+): '
+ '(\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:Z|[+-]\\d{2}:\\d{2})\\[[^\\]]+\\])\\n'
+ 'Elapsed since the preceding (model-visible message|step context): '
+ '(?:unavailable|(?:(?:\\d+d )?(?:\\d+h )?(?:\\d+m )?\\d+s))\\.$',
)
/** Cordis companion plugin name. */
export const name = 'time-context-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. */
/** Validate one plugin-attributed time reading against its durable event timestamp. */
function validateReading(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')
}
const match = READING.exec(block.text)
if (match === null) fail('time-context message does not match the durable reading format')
const turn = Number(match[1])
const step = Number(match[2])
if (!Number.isSafeInteger(turn) || turn < 1 || !Number.isSafeInteger(step) || step < 1) {
fail('time-context turn and step must be positive safe integers')
}
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)}`)
}
const rendered = match[3]
/* v8 ignore next -- the preceding fixed regexp always supplies capture group three. */
if (rendered === undefined) fail('time-context reading omitted its rendered timestamp')
const renderedTime = Date.parse(rendered.replace(/\[[^\]]+\]$/, ''))
if (!Number.isFinite(renderedTime) || !Number.isSafeInteger(event.time)
|| event.time < renderedTime || event.time - renderedTime >= 1_000) {
fail('time-context rendered timestamp must identify the durable event second')
}
}
/** Install validation for plugin-attributed context readings. */
const install: InvariantInstaller = (ctx, fail) => {
observePluginInvariant(ctx, fail, {
name: 'time-context',
inject: [
'agents',
],
effects: [
'ctx.on("agent/pre-step")',
],
})
ctx.on('internal/dispatch', (_mode, eventName, args) => {
if (eventName !== 'session/event') return
const event = (args as [Session, SessionEvent])[1]
if (event.type !== 'context/message'
|| event.data.source.kind !== 'plugin'
|| event.data.source.plugin !== SOURCE_NAME) return
validateReading(event, fail)
}, { global: true })
}
/**
* Register this package's invariant companion.
* Register the time-context invariant companion.
* @param ctx - Cordis context carrying the invariant service.
* @returns the installed registration's disposer after setup succeeds.
*/

View File

@@ -0,0 +1,83 @@
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 * as TimeInvariant from '@deepseek-ai/dsh-time-context/invariant'
import InvariantService from '@deepseek-ai/dsh-invariants'
const SECOND = Date.parse('2026-07-14T00:00:00Z')
async function setup(): Promise<Context> {
const ctx = new Context()
await ctx.plugin(InvariantService)
await ctx.plugin(TimeInvariant)
return ctx
}
function event(text: string, time = SECOND + 456, content?: unknown[]): SessionEvent {
return {
type: 'context/message',
seq: 0,
time,
data: {
content: (content ?? [{ type: 'text', text }]) as ContentBlock[],
source: { kind: 'plugin', plugin: 'time-context' },
},
}
}
function reading(
turn = '1',
step = '1',
baseline = 'model-visible message',
timestamp = '2026-07-14T00:00:00+00:00[UTC]',
): string {
return `Time sampled while preparing turn ${turn}, step ${step}: ${timestamp}\n`
+ `Elapsed since the preceding ${baseline}: unavailable.`
}
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()
})
it.each([
['not a reading', SECOND, undefined, /durable reading format/],
[reading('0'), SECOND, undefined, /positive safe integers/],
[reading('999999999999999999999'), SECOND, undefined, /positive safe integers/],
[reading('1', '0', 'step context'), SECOND, undefined, /positive safe integers/],
[reading('1', '999999999999999999999', 'step context'), SECOND, undefined, /positive safe integers/],
[reading('1', '1', 'step context'), SECOND, undefined, /wrong elapsed-time baseline/],
[reading('1', '2', 'model-visible message'), SECOND, undefined, /wrong elapsed-time baseline/],
[reading('1', '1', 'model-visible message', '2026-99-99T00:00:00+00:00[UTC]'), SECOND, undefined, /durable event second/],
[reading(), Number.NaN, undefined, /durable event second/],
[reading(), SECOND - 1, undefined, /durable event second/],
[reading(), SECOND + 1_000, undefined, /durable event second/],
['ignored', SECOND, [], /exactly one text block/],
['ignored', SECOND, [{ type: 'image', data: 'x', mimeType: 'image/png' }], /exactly one text block/],
['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()
expect(() => {
ctx.emit('session/event', {} as Session, event(text, time, content === undefined ? undefined : [...content]))
}).toThrow(message)
})
it('ignores context messages owned by another package', async () => {
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()
other.data.source = { kind: 'user' }
expect(() => { ctx.emit('session/event', {} as Session, other) }).not.toThrow()
expect(() => {
ctx.emit('session/event', {} as Session, {
type: 'turn/start', seq: 0, time: 0, data: { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } },
})
ctx.emit('tools/change')
}).not.toThrow()
})
})

View File

@@ -1,27 +1,24 @@
/** Package-owned runtime contract checks for `@deepseek-ai/dsh-workspace-context`. @module @deepseek-ai/dsh-workspace-context/invariant */
/**
* Package-owned invariant companion for `@deepseek-ai/dsh-workspace-context`.
* @module @deepseek-ai/dsh-workspace-context/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-workspace-context'
/** Cordis companion plugin name. */
export const name = 'workspace-context-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: 'workspace-context',
effects: [
'ctx.on("session/event")',
'ctx.on("agent/session-prefix")',
'ctx.on("tools/post-execute")',
'ctx.on("tools/result")',
],
})
}
/**
* No runtime invariant: replay intentionally tolerates unknown or malformed workspace metadata,
* while focused pipeline tests own its private pending/cache state transitions.
*/
const install: InvariantInstaller = () => {}
/**
* Register this package's invariant companion.
@@ -30,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,28 +1,24 @@
/** Package-owned runtime contract checks for `@deepseek-ai/dsh-tool-cordis`. @module @deepseek-ai/dsh-tool-cordis/invariant */
/**
* Package-owned invariant companion for `@deepseek-ai/dsh-tool-cordis`.
* @module @deepseek-ai/dsh-tool-cordis/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-tool-cordis'
/** Cordis companion plugin name. */
export const name = 'tool-cordis-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: 'tool-cordis',
inject: [
'tools',
],
effects: [
'ctx.plugin()',
'tools.register()',
],
})
}
/**
* No runtime invariant: this model-facing adapter has no independent lifecycle stream; execution
* relations are owned by the capability seam it calls.
*/
const install: InvariantInstaller = () => {}
/**
* Register this package's invariant companion.
@@ -31,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,31 +1,50 @@
/** Package-owned runtime contract checks for `@deepseek-ai/dsh-system-prompt`. @module @deepseek-ai/dsh-system-prompt/invariant */
/** Package-owned prompt-assembly invariants. @module @deepseek-ai/dsh-system-prompt/invariant */
import type { Context } from 'cordis'
import { observePluginInvariant, type InvariantInstaller } from '@deepseek-ai/dsh-invariants'
import type { InvariantFailure, InvariantInstaller } from '@deepseek-ai/dsh-invariants'
import type { PromptAssembly } from './index.ts'
const PACKAGE_NAME = '@deepseek-ai/dsh-system-prompt'
const VARIABLE_NAME = /^[a-z][a-z0-9_]*$/
/** Cordis companion plugin name. */
export const name = 'system-prompt-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. */
/** Validate the authoritative assembly returned by the waterfall. */
function validateAssembly(assembly: PromptAssembly, fail: InvariantFailure): void {
const sectionNames = new Set<string>()
for (const section of assembly.sections) {
if (section.name.length === 0) fail('assembled section names must be non-empty')
if (sectionNames.has(section.name)) fail(`assembled section name ${JSON.stringify(section.name)} is duplicated`)
sectionNames.add(section.name)
if (typeof section.text !== 'string') fail(`assembled section ${JSON.stringify(section.name)} text must be a string`)
}
for (const tool of assembly.tools) {
if (tool.name.length === 0) fail('assembled tool names must be non-empty')
}
for (const [name, value] of Object.entries(assembly.variables)) {
if (!VARIABLE_NAME.test(name)) fail(`assembled variable name ${JSON.stringify(name)} is invalid`)
if (value !== undefined && typeof value !== 'string') {
fail(`assembled variable ${JSON.stringify(name)} must be a string or undefined`)
}
}
}
/** Install validation around the authoritative assembly waterfall result. */
const install: InvariantInstaller = (ctx, fail) => {
observePluginInvariant(ctx, fail, {
name: 'SystemPrompt',
effects: [
'ctx.provide("systemPrompt")',
'systemPrompt.section()',
],
services: [
'systemPrompt',
],
})
ctx.on('system-prompt/assemble', async (_assembly, _context, next) => {
const assembled = await next()
validateAssembly(assembled, fail)
return assembled
}, { global: true, prepend: true })
}
/**
* Register this package's invariant companion.
* Register the system-prompt invariant companion.
* @param ctx - Cordis context carrying the invariant service.
* @returns the installed registration's disposer after setup succeeds.
*/

View File

@@ -0,0 +1,44 @@
import { describe, expect, it } from 'vitest'
import { Context } from 'cordis'
import type { PromptAssembly } from '@deepseek-ai/dsh-system-prompt'
import * as SystemPromptInvariant from '@deepseek-ai/dsh-system-prompt/invariant'
import InvariantService from '@deepseek-ai/dsh-invariants'
async function setup(): Promise<Context> {
const ctx = new Context()
await ctx.plugin(InvariantService)
await ctx.plugin(SystemPromptInvariant)
return ctx
}
const valid = (): PromptAssembly => ({
sections: [{ name: 'identity', text: 'prompt' }],
tools: [{ name: 'echo', description: 'Echo', parameters: {} }],
variables: { cwd: '/repo', optional: undefined },
})
async function assemble(ctx: Context, result: PromptAssembly): Promise<PromptAssembly> {
return ctx.waterfall(
ctx as never, 'system-prompt/assemble', valid(), {},
() => Promise.resolve(result),
)
}
describe('system-prompt invariants', () => {
it('accepts a well-formed authoritative assembly', async () => {
const ctx = await setup()
await expect(assemble(ctx, valid())).resolves.toEqual(valid())
})
it.each([
[{ ...valid(), sections: [{ name: '', text: 'x' }] }, /section names must be non-empty/],
[{ ...valid(), sections: [{ name: 'x', text: 'a' }, { name: 'x', text: 'b' }] }, /section name "x" is duplicated/],
[{ ...valid(), sections: [{ name: 'x', text: 1 as never }] }, /section "x" text must be a string/],
[{ ...valid(), tools: [{ name: '', description: 'x', parameters: {} }] }, /tool names must be non-empty/],
[{ ...valid(), variables: { Bad: 'x' } }, /variable name "Bad" is invalid/],
[{ ...valid(), variables: { value: 1 as never } }, /variable "value" must be a string or undefined/],
])('rejects malformed authoritative assembly %#', async (assembly, message) => {
const ctx = await setup()
await expect(assemble(ctx, assembly)).rejects.toThrow(message)
})
})

View File

@@ -1,34 +1,67 @@
/** Package-owned runtime contract checks for `@deepseek-ai/dsh-tools`. @module @deepseek-ai/dsh-tools/invariant */
/** Package-owned tool-pipeline invariants. @module @deepseek-ai/dsh-tools/invariant */
import type { Context } from 'cordis'
import { observePluginInvariant, type InvariantInstaller } from '@deepseek-ai/dsh-invariants'
import type { InvariantFailure, InvariantInstaller } from '@deepseek-ai/dsh-invariants'
import type { ToolExecution, ToolExecutionResult } from './index.ts'
const PACKAGE_NAME = '@deepseek-ai/dsh-tools'
/** Cordis companion plugin name. */
export const name = 'tools-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. */
type ToolStage = 'pre' | 'execute' | 'post'
/** Validate the immutable final execution/result snapshot. */
function validateResult(
exec: Readonly<ToolExecution>,
result: Readonly<ToolExecutionResult>,
fail: InvariantFailure,
): void {
if (!Object.isFrozen(exec)) fail('tools/result execution must be frozen before publication')
if (!Object.isFrozen(result) || !Object.isFrozen(result.content)) {
fail('tools/result outcome and content must be frozen before publication')
}
if (exec.name.length === 0 || String(exec.callId).length === 0) {
fail('tools/result execution must carry non-empty name and callId')
}
}
/** Install monotonic pipeline and final-snapshot checks. */
const install: InvariantInstaller = (ctx, fail) => {
observePluginInvariant(ctx, fail, {
name: 'ToolRegistry',
inject: [
'systemPrompt',
],
effects: [
'ctx.provide("tools")',
'systemPrompt.tools()',
],
services: [
'tools',
],
})
const stages = new WeakMap<object, ToolStage>()
ctx.on('internal/dispatch', (_mode, eventName, args) => {
if (eventName === 'tools/pre-execute') {
const exec = args[0] as ToolExecution
if (stages.has(exec)) fail('tools/pre-execute repeated for one execution')
stages.set(exec, 'pre')
return
}
if (eventName === 'tools/execute') {
const exec = args[0] as ToolExecution
if (stages.get(exec) !== 'pre') fail('tools/execute must follow tools/pre-execute')
stages.set(exec, 'execute')
return
}
if (eventName === 'tools/post-execute') {
const exec = args[0] as ToolExecution
const previous = stages.get(exec)
if (previous !== 'pre' && previous !== 'execute') {
fail('tools/post-execute must follow tools/pre-execute or tools/execute')
}
stages.set(exec, 'post')
return
}
if (eventName !== 'tools/result') return
const [exec, result] = args as [Readonly<ToolExecution>, Readonly<ToolExecutionResult>]
validateResult(exec, result, fail)
stages.delete(exec)
}, { global: true })
}
/**
* Register this package's invariant companion.
* Register the tools invariant companion.
* @param ctx - Cordis context carrying the invariant service.
* @returns the installed registration's disposer after setup succeeds.
*/

View File

@@ -0,0 +1,84 @@
import { describe, expect, it } from 'vitest'
import { Context } from 'cordis'
import { scopeTarget } from '@deepseek-ai/dsh-scope'
import { CallId } from '@deepseek-ai/dsh-llm'
import type { ToolExecution, ToolExecutionResult, ToolExecutionToken } from '@deepseek-ai/dsh-tools'
import * as ToolsInvariant from '@deepseek-ai/dsh-tools/invariant'
import InvariantService from '@deepseek-ai/dsh-invariants'
async function setup(): Promise<Context> {
const ctx = new Context()
await ctx.plugin(InvariantService)
await ctx.plugin(ToolsInvariant)
return ctx
}
const execution = (overrides: Partial<ToolExecution> = {}): ToolExecution => ({
token: Symbol('tool') as ToolExecutionToken,
callId: CallId('call-1'),
name: 'echo',
arguments: Object.freeze({ text: 'hi' }),
...overrides,
})
const outcome = (): ToolExecutionResult => Object.freeze({
content: Object.freeze([{ type: 'text' as const, text: 'ok' }]) as never,
isError: false,
})
function emitResult(ctx: Context, exec: ToolExecution, result: ToolExecutionResult): void {
ctx.emit(scopeTarget(ctx as never, undefined), 'tools/result', exec, result)
}
async function stage(ctx: Context, name: 'tools/pre-execute' | 'tools/execute', exec: ToolExecution): Promise<void> {
if (name === 'tools/pre-execute') {
await ctx.waterfall(ctx as never, name, exec, () => Promise.resolve({ kind: 'allow' as const }))
} else {
await ctx.waterfall(ctx as never, name, exec, () => Promise.resolve(outcome()))
}
}
describe('tool-pipeline invariants', () => {
it('accepts dispatch and denial stage orders with frozen results', async () => {
const ctx = await setup()
const dispatched = execution()
await stage(ctx, 'tools/pre-execute', dispatched)
await stage(ctx, 'tools/execute', dispatched)
await ctx.waterfall(ctx as never, 'tools/post-execute', dispatched, outcome(), () => Promise.resolve({ kind: 'accept' as const }))
Object.freeze(dispatched)
emitResult(ctx, dispatched, outcome())
const denied = execution({ callId: CallId('call-2') })
await stage(ctx, 'tools/pre-execute', denied)
await ctx.waterfall(ctx as never, 'tools/post-execute', denied, outcome(), () => Promise.resolve({ kind: 'accept' as const }))
Object.freeze(denied)
emitResult(ctx, denied, outcome())
ctx.emit('tools/change')
})
it('rejects repeated and out-of-order pipeline stages', async () => {
const ctx = await setup()
const exec = execution()
await stage(ctx, 'tools/pre-execute', exec)
await expect(stage(ctx, 'tools/pre-execute', exec)).rejects.toThrow(/repeated/)
const noPre = execution({ callId: CallId('call-2') })
await expect(stage(ctx, 'tools/execute', noPre)).rejects.toThrow(/must follow tools\/pre-execute/)
expect(() => ctx.waterfall(
ctx as never, 'tools/post-execute', noPre, outcome(),
() => Promise.resolve({ kind: 'accept' as const }),
)).toThrow(/must follow tools\/pre-execute or tools\/execute/)
})
it('rejects mutable or anonymous final snapshots', async () => {
const ctx = await setup()
expect(() => { emitResult(ctx, execution(), outcome()) }).toThrow(/execution must be frozen/)
const exec = Object.freeze(execution())
expect(() => { emitResult(ctx, exec, { content: [], isError: false }) })
.toThrow(/outcome and content must be frozen/)
const anonymous = Object.freeze(execution({ name: '' }))
expect(() => { emitResult(ctx, anonymous, outcome()) }).toThrow(/non-empty name and callId/)
})
})

View File

@@ -1,24 +1,24 @@
/** Package-owned runtime contract checks for `@deepseek-ai/dsh-acp-demo`. @module @deepseek-ai/dsh-acp-demo/invariant */
/**
* Package-owned invariant companion for `@deepseek-ai/dsh-acp-demo`.
* @module @deepseek-ai/dsh-acp-demo/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-acp-demo'
/** Cordis companion plugin name. */
export const name = 'acp-demo-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: 'acp-demo',
effects: [
'ctx.plugin()',
],
})
}
/**
* No runtime invariant: this composition package owns no independent event stream or mutable data;
* Loader and built-entry tests cover its wiring.
*/
const install: InvariantInstaller = () => {}
/**
* Register this package's invariant companion.
@@ -27,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,24 +1,24 @@
/** Package-owned runtime contract checks for `@deepseek-ai/dsh-agent-spine-demo`. @module @deepseek-ai/dsh-agent-spine-demo/invariant */
/**
* Package-owned invariant companion for `@deepseek-ai/dsh-agent-spine-demo`.
* @module @deepseek-ai/dsh-agent-spine-demo/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-agent-spine-demo'
/** Cordis companion plugin name. */
export const name = 'agent-spine-demo-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: 'agent-spine-demo',
effects: [
'ctx.plugin()',
],
})
}
/**
* No runtime invariant: this composition package owns no independent event stream or mutable data;
* Loader and built-entry tests cover its wiring.
*/
const install: InvariantInstaller = () => {}
/**
* Register this package's invariant companion.
@@ -27,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,24 +1,24 @@
/** Package-owned runtime contract checks for `@deepseek-ai/dsh-cli-demo`. @module @deepseek-ai/dsh-cli-demo/invariant */
/**
* Package-owned invariant companion for `@deepseek-ai/dsh-cli-demo`.
* @module @deepseek-ai/dsh-cli-demo/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-cli-demo'
/** Cordis companion plugin name. */
export const name = 'cli-demo-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: 'cli-demo',
effects: [
'ctx.plugin()',
],
})
}
/**
* No runtime invariant: this composition package owns no independent event stream or mutable data;
* Loader and built-entry tests cover its wiring.
*/
const install: InvariantInstaller = () => {}
/**
* Register this package's invariant companion.
@@ -27,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,22 +1,24 @@
/** Package-owned runtime contract for @deepseek-ai/dsh-jsonrpc-demo. @module @deepseek-ai/dsh-jsonrpc-demo/invariant */
/**
* Package-owned invariant companion for `@deepseek-ai/dsh-jsonrpc-demo`.
* @module @deepseek-ai/dsh-jsonrpc-demo/invariant
*/
/* jscpd:ignore-start */
import type { Context } from 'cordis'
import { assertInvariant, type InvariantInstaller } from '@deepseek-ai/dsh-invariants'
import type { InvariantInstaller } from '@deepseek-ai/dsh-invariants'
const PACKAGE_NAME = '@deepseek-ai/dsh-jsonrpc-demo'
/** Cordis companion plugin name. */
export const name = 'jsonrpc-demo-invariant'
/** Services required before the companion can register. */
/** Service required before the companion can reserve package ownership. */
export const inject = ['invariants']
/** Assert that Loader configuration, rather than a hidden root plugin, owns composition. */
const install: InvariantInstaller = async (_ctx, fail) => {
const packageEntry = await import('./index.ts')
assertInvariant(fail, Object.keys(packageEntry).length === 0,
'the JSON-RPC demo library entrypoint must remain empty because cordis.yml owns composition')
}
/**
* No runtime invariant: this composition package owns no independent event stream or mutable data;
* Loader and built-entry tests cover its wiring.
*/
const install: InvariantInstaller = () => {}
/**
* Register this package's invariant companion.

View File

@@ -1,24 +1,24 @@
/** Package-owned runtime contract checks for `@deepseek-ai/dsh-stdio-demo`. @module @deepseek-ai/dsh-stdio-demo/invariant */
/**
* Package-owned invariant companion for `@deepseek-ai/dsh-stdio-demo`.
* @module @deepseek-ai/dsh-stdio-demo/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-stdio-demo'
/** Cordis companion plugin name. */
export const name = 'stdio-demo-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: 'stdio-demo',
effects: [
'ctx.plugin()',
],
})
}
/**
* No runtime invariant: this composition package owns no independent event stream or mutable data;
* Loader and built-entry tests cover its wiring.
*/
const install: InvariantInstaller = () => {}
/**
* Register this package's invariant companion.
@@ -27,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,27 +1,24 @@
/** Package-owned runtime contract checks for `@deepseek-ai/dsh-fs-local`. @module @deepseek-ai/dsh-fs-local/invariant */
/**
* Package-owned invariant companion for `@deepseek-ai/dsh-fs-local`.
* @module @deepseek-ai/dsh-fs-local/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-fs-local'
/** Cordis companion plugin name. */
export const name = 'fs-local-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: 'LocalFileSystem',
effects: [
'ctx.provide("fs")',
],
services: [
'fs',
],
})
}
/**
* No runtime invariant: this package exposes no independent event sequence or mutable data relation
* beyond contracts enforced at its owning seam.
*/
const install: InvariantInstaller = () => {}
/**
* Register this package's invariant companion.
@@ -30,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 +1,24 @@
/** Package-owned runtime contract checks for `@deepseek-ai/dsh-fs-policy`. @module @deepseek-ai/dsh-fs-policy/invariant */
/**
* Package-owned invariant companion for `@deepseek-ai/dsh-fs-policy`.
* @module @deepseek-ai/dsh-fs-policy/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-fs-policy'
/** Cordis companion plugin name. */
export const name = 'fs-policy-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: 'fs-policy',
effects: [
'ctx.on("fs/write-intent")',
'ctx.on("fs/edit-intent")',
'ctx.on("fs/observed")',
],
})
}
/**
* No runtime invariant: this package exposes no independent event sequence or mutable data relation
* beyond contracts enforced at its owning seam.
*/
const install: InvariantInstaller = () => {}
/**
* Register this package's invariant companion.
@@ -29,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,24 +1,37 @@
/** Package-owned runtime contract checks for `@deepseek-ai/dsh-fs`. @module @deepseek-ai/dsh-fs/invariant */
/** Package-owned filesystem event-data invariants. @module @deepseek-ai/dsh-fs/invariant */
import type { Context } from 'cordis'
import { observeServiceInvariant, serviceShapeViolation, type InvariantInstaller } from '@deepseek-ai/dsh-invariants'
import type { InvariantInstaller } from '@deepseek-ai/dsh-invariants'
import type { FsTarget, FsVersion } from './types.ts'
const PACKAGE_NAME = '@deepseek-ai/dsh-fs'
/** Cordis companion plugin name. */
export const name = 'fs-invariant'
/** Services required before the companion can register. */
/** Service required before the companion can reserve package ownership. */
export const inject = ['invariants']
/** Validate every implementation bound to this package's service seam. */
/** Assert that an event carries a usable opaque target identity. */
function validateTarget(target: FsTarget, fail: (message: string) => never): void {
if (target.targetKey.length === 0) fail('filesystem event targetKey must be non-empty')
if (target.displayPath.length === 0) fail('filesystem event displayPath must be non-empty')
}
/** Install checks over the filesystem decision and observation event stream. */
const install: InvariantInstaller = (ctx, fail) => {
observeServiceInvariant(ctx, fail, 'fs', value => serviceShapeViolation(value, {
methods: ['resolve', 'stat', 'lstat', 'readText', 'streamText', 'listDir', 'writeText', 'editText'],
}))
ctx.on('internal/dispatch', (_mode, eventName, args) => {
if (eventName !== 'fs/write-intent'
&& eventName !== 'fs/edit-intent'
&& eventName !== 'fs/observed') return
validateTarget(args[0] as FsTarget, fail)
if (eventName === 'fs/observed' && (args[1] as FsVersion).length === 0) {
fail('fs/observed version must be non-empty')
}
}, { global: true })
}
/**
* Register this package's invariant companion.
* Register the filesystem invariant companion.
* @param ctx - Cordis context carrying the invariant service.
* @returns the installed registration's disposer after setup succeeds.
*/

View File

@@ -0,0 +1,44 @@
import { describe, expect, it } from 'vitest'
import { Context } from 'cordis'
import { FsTargetKey, FsVersion } from '@deepseek-ai/dsh-fs'
import type { FsTarget } from '@deepseek-ai/dsh-fs'
import * as FsInvariant from '@deepseek-ai/dsh-fs/invariant'
import InvariantService from '@deepseek-ai/dsh-invariants'
async function setup(): Promise<Context> {
const ctx = new Context()
await ctx.plugin(InvariantService)
await ctx.plugin(FsInvariant)
return ctx
}
const target = (key = 'file:1', displayPath = 'file.txt'): FsTarget => ({
targetKey: FsTargetKey(key),
displayPath,
})
describe('filesystem invariants', () => {
it('accepts decision and observation events with usable identities', async () => {
const ctx = await setup()
await expect(ctx.waterfall(
ctx as never, 'fs/write-intent', target(), undefined,
() => Promise.resolve(undefined),
)).resolves.toBeUndefined()
await expect(ctx.waterfall(
ctx as never, 'fs/edit-intent', target(), undefined,
() => Promise.resolve(undefined),
)).resolves.toBeUndefined()
expect(() => { ctx.emit('fs/observed', target(), FsVersion('v1'), undefined) }).not.toThrow()
expect(() => { ctx.emit('tools/change') }).not.toThrow()
})
it('rejects empty target and version identities', async () => {
const ctx = await setup()
expect(() => { ctx.emit('fs/observed', target(''), FsVersion('v1'), undefined) })
.toThrow(/targetKey must be non-empty/)
expect(() => { ctx.emit('fs/observed', target('file:1', ''), FsVersion('v1'), undefined) })
.toThrow(/displayPath must be non-empty/)
expect(() => { ctx.emit('fs/observed', target(), FsVersion(''), undefined) })
.toThrow(/version must be non-empty/)
})
})

View File

@@ -1,29 +1,24 @@
/** Package-owned runtime contract checks for `@deepseek-ai/dsh-tool-fs-search`. @module @deepseek-ai/dsh-tool-fs-search/invariant */
/**
* Package-owned invariant companion for `@deepseek-ai/dsh-tool-fs-search`.
* @module @deepseek-ai/dsh-tool-fs-search/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-tool-fs-search'
/** Cordis companion plugin name. */
export const name = 'tool-fs-search-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: 'tool-fs-search',
inject: [
'tools',
'systemPrompt',
'bash',
],
effects: [
'tools.register()',
],
})
}
/**
* No runtime invariant: this model-facing adapter has no independent lifecycle stream; execution
* relations are owned by the capability seam it calls.
*/
const install: InvariantInstaller = () => {}
/**
* Register this package's invariant companion.
@@ -32,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,29 +1,24 @@
/** Package-owned runtime contract checks for `@deepseek-ai/dsh-tool-fs`. @module @deepseek-ai/dsh-tool-fs/invariant */
/**
* Package-owned invariant companion for `@deepseek-ai/dsh-tool-fs`.
* @module @deepseek-ai/dsh-tool-fs/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-tool-fs'
/** Cordis companion plugin name. */
export const name = 'tool-fs-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: 'tool-fs',
inject: [
'tools',
'fs',
'systemPrompt',
],
effects: [
'tools.register()',
],
})
}
/**
* No runtime invariant: this model-facing adapter has no independent lifecycle stream; execution
* relations are owned by the capability seam it calls.
*/
const install: InvariantInstaller = () => {}
/**
* Register this package's invariant companion.
@@ -32,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,25 +1,24 @@
/** Package-owned runtime contract checks for `@deepseek-ai/dsh-repeat-tool-guard`. @module @deepseek-ai/dsh-repeat-tool-guard/invariant */
/**
* Package-owned invariant companion for `@deepseek-ai/dsh-repeat-tool-guard`.
* @module @deepseek-ai/dsh-repeat-tool-guard/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-repeat-tool-guard'
/** Cordis companion plugin name. */
export const name = 'repeat-tool-guard-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: 'repeat-tool-guard',
effects: [
'ctx.on("tools/post-execute")',
'ctx.on("agent/prompt-submit")',
],
})
}
/**
* No runtime invariant: the repeat chain is private to one post-execute listener and exposes no
* package-owned event or snapshot that an independent companion can observe.
*/
const install: InvariantInstaller = () => {}
/**
* Register this package's invariant companion.
@@ -28,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,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/)
})
})

View File

@@ -1,27 +1,24 @@
/** Package-owned runtime contract checks for `@deepseek-ai/dsh-llm-deepseek`. @module @deepseek-ai/dsh-llm-deepseek/invariant */
/**
* Package-owned invariant companion for `@deepseek-ai/dsh-llm-deepseek`.
* @module @deepseek-ai/dsh-llm-deepseek/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-llm-deepseek'
/** Cordis companion plugin name. */
export const name = 'llm-deepseek-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: 'llm-deepseek',
inject: [
'llm',
],
effects: [
'llm.registerAdapter()',
],
})
}
/**
* No runtime invariant: this package exposes no independent event sequence or mutable data relation
* beyond contracts enforced at its owning seam.
*/
const install: InvariantInstaller = () => {}
/**
* Register this package's invariant companion.
@@ -30,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,27 +1,24 @@
/** Package-owned runtime contract checks for `@deepseek-ai/dsh-llm-pi-ai`. @module @deepseek-ai/dsh-llm-pi-ai/invariant */
/**
* Package-owned invariant companion for `@deepseek-ai/dsh-llm-pi-ai`.
* @module @deepseek-ai/dsh-llm-pi-ai/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-llm-pi-ai'
/** Cordis companion plugin name. */
export const name = 'llm-pi-ai-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: 'llm-pi-ai',
inject: [
'llm',
],
effects: [
'llm.registerAdapter()',
],
})
}
/**
* No runtime invariant: this package exposes no independent event sequence or mutable data relation
* beyond contracts enforced at its owning seam.
*/
const install: InvariantInstaller = () => {}
/**
* Register this package's invariant companion.
@@ -30,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,30 +1,93 @@
/** Package-owned runtime contract checks for `@deepseek-ai/dsh-llm`. @module @deepseek-ai/dsh-llm/invariant */
/** Package-owned LLM stream-protocol invariants. @module @deepseek-ai/dsh-llm/invariant */
import type { Context } from 'cordis'
import { observePluginInvariant, type InvariantInstaller } from '@deepseek-ai/dsh-invariants'
import type { InvariantFailure, InvariantInstaller } from '@deepseek-ai/dsh-invariants'
import type { ContentBlockType, StreamChunk } from './types.ts'
const PACKAGE_NAME = '@deepseek-ai/dsh-llm'
/** Cordis companion plugin name. */
export const name = 'llm-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. */
/** Require one chunk index to be a non-negative safe integer. */
function validateIndex(index: number, fail: InvariantFailure): void {
if (!Number.isSafeInteger(index) || index < 0) {
fail(`LLM stream block index must be a non-negative safe integer, got ${index}`)
}
}
/** Require a delta to address an open block of its matching type. */
function validateDelta(
open: ReadonlyMap<number, ContentBlockType>,
index: number,
expected: ContentBlockType,
fail: InvariantFailure,
): void {
validateIndex(index, fail)
const actual = open.get(index)
if (actual !== expected) {
fail(`${expected} delta at index ${index} requires an open ${expected} block, got ${String(actual)}`)
}
}
/** Wrap one provider stream and enforce its grammar as chunks are consumed. */
async function* validateStream(
source: AsyncIterable<StreamChunk>,
fail: InvariantFailure,
): AsyncIterable<StreamChunk> {
const open = new Map<number, ContentBlockType>()
let usageSeen = false
let finished = false
for await (const chunk of source) {
if (finished) fail(`LLM stream emitted ${chunk.type} after terminal finish`)
switch (chunk.type) {
case 'block-start':
validateIndex(chunk.index, fail)
if (open.has(chunk.index)) fail(`LLM stream repeated block-start index ${chunk.index}`)
open.set(chunk.index, chunk.blockType)
break
case 'text-delta':
validateDelta(open, chunk.index, 'text', fail)
break
case 'reasoning-delta':
validateDelta(open, chunk.index, 'reasoning', fail)
break
case 'tool-call-delta':
validateDelta(open, chunk.index, 'tool-call', fail)
break
case 'block-end': {
validateIndex(chunk.index, fail)
const blockType = open.get(chunk.index)
if (blockType === undefined) fail(`LLM stream block-end index ${chunk.index} has no open block`)
if (chunk.block.type !== blockType) {
fail(`LLM stream block-end index ${chunk.index} closes ${chunk.block.type}, expected ${blockType}`)
}
open.delete(chunk.index)
break
}
case 'usage':
if (usageSeen) fail('LLM stream emitted usage more than once')
usageSeen = true
break
case 'finish':
if (open.size > 0) fail(`LLM stream finished with ${open.size} open block(s)`)
finished = true
break
}
yield chunk
}
if (!finished) fail('LLM stream ended without a terminal finish chunk')
}
/** Install validation around every provider stream. */
const install: InvariantInstaller = (ctx, fail) => {
observePluginInvariant(ctx, fail, {
name: 'LlmService',
effects: [
'ctx.provide("llm")',
],
services: [
'llm',
],
})
ctx.on('llm/stream', (_options, next) => validateStream(next(), fail), { global: true, prepend: true })
}
/**
* Register this package's invariant companion.
* Register the LLM invariant companion.
* @param ctx - Cordis context carrying the invariant service.
* @returns the installed registration's disposer after setup succeeds.
*/

View File

@@ -0,0 +1,86 @@
import { describe, expect, it } from 'vitest'
import { Context } from 'cordis'
import { CallId } from '@deepseek-ai/dsh-llm'
import type { GenerateOptions, StreamChunk } from '@deepseek-ai/dsh-llm'
import * as LlmInvariant from '@deepseek-ai/dsh-llm/invariant'
import InvariantService from '@deepseek-ai/dsh-invariants'
async function setup(): Promise<Context> {
const ctx = new Context()
await ctx.plugin(InvariantService)
await ctx.plugin(LlmInvariant)
return ctx
}
const options: GenerateOptions = { provider: 'mock', model: 'mock', messages: [] }
async function* source(chunks: readonly StreamChunk[]): AsyncIterable<StreamChunk> {
yield* chunks
}
async function consume(ctx: Context, chunks: readonly StreamChunk[]): Promise<StreamChunk[]> {
const stream = ctx.waterfall(ctx as never, 'llm/stream', options, () => source(chunks))
const consumed: StreamChunk[] = []
for await (const chunk of stream) consumed.push(chunk)
return consumed
}
const finish: StreamChunk = { type: 'finish', reason: { kind: 'stop' } }
describe('LLM stream invariants', () => {
it('accepts a complete interleaved stream grammar', async () => {
const ctx = await setup()
const chunks: StreamChunk[] = [
{ type: 'block-start', index: 0, blockType: 'text' },
{ type: 'text-delta', index: 0, text: 'a' },
{ type: 'block-start', index: 1, blockType: 'reasoning' },
{ type: 'reasoning-delta', index: 1, text: 'b' },
{ type: 'block-end', index: 1, block: { type: 'reasoning', text: 'b' } },
{ type: 'block-end', index: 0, block: { type: 'text', text: 'a' } },
{ type: 'block-start', index: 2, blockType: 'tool-call' },
{ type: 'tool-call-delta', index: 2, id: CallId('c1'), name: 'echo', argumentsDelta: '{}' },
{ type: 'block-end', index: 2, block: { type: 'tool-call', id: CallId('c1'), name: 'echo', arguments: '{}' } },
{ type: 'usage', usage: { inputTokens: 1, outputTokens: 1 } },
finish,
]
await expect(consume(ctx, chunks)).resolves.toEqual(chunks)
})
it.each([
[[{ type: 'block-start', index: -1, blockType: 'text' }, finish], /non-negative safe integer/],
[[
{ type: 'block-start', index: 0, blockType: 'text' },
{ type: 'block-start', index: 0, blockType: 'text' },
], /repeated block-start/],
[[{ type: 'text-delta', index: 0, text: 'x' }], /requires an open text block/],
[[
{ type: 'block-start', index: 0, blockType: 'reasoning' },
{ type: 'text-delta', index: 0, text: 'x' },
], /got reasoning/],
[[{ type: 'block-end', index: 0, block: { type: 'text', text: '' } }], /has no open block/],
[[
{ type: 'block-start', index: 0, blockType: 'text' },
{ type: 'block-end', index: 0, block: { type: 'reasoning', text: '' } },
], /closes reasoning, expected text/],
[[
{ type: 'usage', usage: { inputTokens: 1, outputTokens: 1 } },
{ type: 'usage', usage: { inputTokens: 1, outputTokens: 1 } },
], /usage more than once/],
[[{ type: 'block-start', index: 0, blockType: 'text' }, finish], /finished with 1 open block/],
[[finish, { type: 'usage', usage: { inputTokens: 1, outputTokens: 1 } }], /usage after terminal finish/],
[[], /ended without a terminal finish/],
] as Array<[StreamChunk[], RegExp]>)('rejects malformed stream %#', async (chunks, message) => {
const ctx = await setup()
await expect(consume(ctx, chunks)).rejects.toThrow(message)
})
it('preserves provider exceptions without inventing a missing-finish failure', async () => {
const ctx = await setup()
const stream = ctx.waterfall(ctx as never, 'llm/stream', options, async function* () {
throw new Error('provider failed')
})
await expect((async () => {
for await (const _chunk of stream) { /* consume */ }
})()).rejects.toThrow('provider failed')
})
})

View File

@@ -60,6 +60,7 @@ class CatalogAdapter extends ScriptedAdapter {
const SCRIPT: StreamChunk[] = [
{ type: 'block-start', index: 0, blockType: 'text' },
{ type: 'text-delta', index: 0, text: 'hi' },
{ type: 'block-end', index: 0, block: { type: 'text', text: 'hi' } },
{ type: 'finish', reason: { kind: 'stop' } },
]
@@ -489,13 +490,14 @@ describe('LlmService', () => {
const inner = next()
return (async function * () {
yield { type: 'block-start', index: 99, blockType: 'text' } satisfies StreamChunk
yield { type: 'block-end', index: 99, block: { type: 'text', text: '' } } satisfies StreamChunk
yield * inner
})()
})
const chunks: StreamChunk[] = []
for await (const chunk of ctx.llm.stream({ provider: 'test-model', model: 'dynamic-model', messages: [] })) chunks.push(chunk)
expect(chunks).toHaveLength(4)
expect(chunks).toHaveLength(6)
expect(chunks[0]).toMatchObject({ index: 99 })
})

View File

@@ -1,28 +1,24 @@
/** Package-owned runtime contract checks for `@deepseek-ai/dsh-token-meter`. @module @deepseek-ai/dsh-token-meter/invariant */
/**
* Package-owned invariant companion for `@deepseek-ai/dsh-token-meter`.
* @module @deepseek-ai/dsh-token-meter/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-token-meter'
/** Cordis companion plugin name. */
export const name = 'token-meter-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: 'TokenMeterService',
effects: [
'ctx.provide("tokenMeter")',
'ctx.on("session/event")',
],
services: [
'tokenMeter',
],
})
}
/**
* No runtime invariant: token estimates are per-call outputs and the private session cache is
* invalidated at its event mutation boundary; neither exposes an independent observation stream.
*/
const install: InvariantInstaller = () => {}
/**
* Register this package's invariant companion.
@@ -31,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,28 +1,24 @@
/** Package-owned runtime contract checks for `@deepseek-ai/dsh-mcp-client`. @module @deepseek-ai/dsh-mcp-client/invariant */
/**
* Package-owned invariant companion for `@deepseek-ai/dsh-mcp-client`.
* @module @deepseek-ai/dsh-mcp-client/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-mcp-client'
/** Cordis companion plugin name. */
export const name = 'mcp-client-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: 'mcp-client',
inject: [
'tools',
],
effects: [
'mcp-client.serverName',
'mcp-client.connection',
],
})
}
/**
* No runtime invariant: MCP generations contribute through the tool registry, but the bridge
* exposes no independent server-to-tool snapshot after an asynchronous resync.
*/
const install: InvariantInstaller = () => {}
/**
* Register this package's invariant companion.
@@ -31,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,27 +1,24 @@
/** Package-owned runtime contract checks for `@deepseek-ai/dsh-sandbox-local`. @module @deepseek-ai/dsh-sandbox-local/invariant */
/**
* Package-owned invariant companion for `@deepseek-ai/dsh-sandbox-local`.
* @module @deepseek-ai/dsh-sandbox-local/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-sandbox-local'
/** Cordis companion plugin name. */
export const name = 'sandbox-local-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: 'LocalSandboxProvider',
effects: [
'ctx.provide("sandbox")',
],
services: [
'sandbox',
],
})
}
/**
* No runtime invariant: this package exposes no independent event sequence or mutable data relation
* beyond contracts enforced at its owning seam.
*/
const install: InvariantInstaller = () => {}
/**
* Register this package's invariant companion.
@@ -30,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,21 +1,24 @@
/** Package-owned runtime contract checks for `@deepseek-ai/dsh-sandbox`. @module @deepseek-ai/dsh-sandbox/invariant */
/**
* Package-owned invariant companion for `@deepseek-ai/dsh-sandbox`.
* @module @deepseek-ai/dsh-sandbox/invariant
*/
/* jscpd:ignore-start */
import type { Context } from 'cordis'
import { observeServiceInvariant, serviceShapeViolation, type InvariantInstaller } from '@deepseek-ai/dsh-invariants'
import type { InvariantInstaller } from '@deepseek-ai/dsh-invariants'
const PACKAGE_NAME = '@deepseek-ai/dsh-sandbox'
/** Cordis companion plugin name. */
export const name = 'sandbox-invariant'
/** Services required before the companion can register. */
/** Service required before the companion can reserve package ownership. */
export const inject = ['invariants']
/** Validate every implementation bound to this package's service seam. */
const install: InvariantInstaller = (ctx, fail) => {
observeServiceInvariant(ctx, fail, 'sandbox', value => serviceShapeViolation(value, {
methods: ['confine'],
}))
}
/**
* No runtime invariant: this package exposes no independent event sequence or mutable data relation
* beyond contracts enforced at its owning seam.
*/
const install: InvariantInstaller = () => {}
/**
* Register this package's invariant companion.
@@ -24,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,43 +0,0 @@
import { describe, expect, it } from 'vitest'
import { Context } from 'cordis'
import { InvariantError } from '@deepseek-ai/dsh-invariants'
import { SandboxProvider } from '@deepseek-ai/dsh-sandbox'
import type { ConfinedArgv, SandboxPolicy } from '@deepseek-ai/dsh-sandbox'
class StubSandboxProvider extends SandboxProvider {
confine(argv: readonly string[], _policy: SandboxPolicy): ConfinedArgv {
return {
argv: [...argv],
enforcement: 'full',
denialSignatures: [],
runnerFailureSignatures: [],
}
}
}
describe('sandbox package invariant', () => {
it('accepts a provider that exposes the confinement seam', async () => {
const ctx = new Context()
await ctx.plugin(StubSandboxProvider)
expect(ctx.sandbox).toBeInstanceOf(StubSandboxProvider)
})
it('rejects a service binding without confine()', async () => {
const ctx = new Context()
const invalidSandbox = {
name: 'invalid-sandbox',
apply(child: Context) {
child.provide('sandbox', {} as SandboxProvider)
},
}
let caught: unknown
try {
await ctx.plugin(invalidSandbox)
} catch (error) {
caught = error
}
expect(caught).toBeInstanceOf(InvariantError)
expect(caught).toHaveProperty('packageName', '@deepseek-ai/dsh-sandbox')
expect((caught as Error).message).toMatch(/must expose method "confine"/)
})
})

View File

@@ -1,35 +1,24 @@
/** Package-owned runtime contracts for @deepseek-ai/create-sdk. @module @deepseek-ai/create-sdk/invariant */
/**
* Package-owned invariant companion for `@deepseek-ai/create-sdk`.
* @module @deepseek-ai/create-sdk/invariant
*/
/* jscpd:ignore-start */
import type { Context } from 'cordis'
import { assertInvariant, type InvariantInstaller } from '@deepseek-ai/dsh-invariants'
import type { InvariantInstaller } from '@deepseek-ai/dsh-invariants'
const PACKAGE_NAME = '@deepseek-ai/create-sdk'
/** Cordis companion plugin name. */
export const name = 'create-sdk-invariant'
/** Services required before the companion can register. */
/** Service required before the companion can reserve package ownership. */
export const inject = ['invariants']
/** Assert the bin-only entrypoint and its core argument mapping. */
const install: InvariantInstaller = async (_ctx, fail) => {
const [{ parseCreateArgs }, packageEntry] = await Promise.all([
import('./args.ts'),
import('./index.ts'),
])
assertInvariant(fail, Object.keys(packageEntry).length === 0,
'the create-sdk library entrypoint must remain empty because the package is bin-only')
const parsed = parseCreateArgs([
'workspace', '--provider=custom', '--base-url=https://example.test', '--interface=embed', '--no-install',
])
assertInvariant(fail,
parsed.directory === 'workspace'
&& parsed.provider === 'custom'
&& parsed.baseURL === 'https://example.test'
&& parsed.runInterface === 'embed'
&& parsed.install === false,
'create-sdk arguments must preserve directory, provider, base URL, interface, and negative install flags')
}
/**
* No runtime invariant: this SDK build-time package owns no live event stream or mutable data;
* generated output and consumer tests cover its contract.
*/
const install: InvariantInstaller = () => {}
/**
* Register this package's invariant companion.

View File

@@ -1,29 +1,24 @@
/** Package-owned runtime contracts for @deepseek-ai/dsh-helper. @module @deepseek-ai/dsh-helper/invariant */
/**
* Package-owned invariant companion for `@deepseek-ai/dsh-helper`.
* @module @deepseek-ai/dsh-helper/invariant
*/
/* jscpd:ignore-start */
import type { Context } from 'cordis'
import { assertInvariant, type InvariantInstaller } from '@deepseek-ai/dsh-invariants'
import type { InvariantInstaller } from '@deepseek-ai/dsh-invariants'
const PACKAGE_NAME = '@deepseek-ai/dsh-helper'
/** Cordis companion plugin name. */
export const name = 'helper-invariant'
/** Services required before the companion can register. */
/** Service required before the companion can reserve package ownership. */
export const inject = ['invariants']
/** Assert FeatureId's zero-cost representation and boundary validation. */
const install: InvariantInstaller = async (_ctx, fail) => {
const { featureId } = await import('./ids.ts')
assertInvariant(fail, featureId('local-plugin') === 'local-plugin',
'a valid feature id must preserve its runtime string value')
let rejected = false
try {
featureId('Invalid Feature')
} catch (error) {
rejected = error instanceof Error
}
assertInvariant(fail, rejected, 'feature ids must reject values outside lowercase kebab-case')
}
/**
* No runtime invariant: this SDK build-time package owns no live event stream or mutable data;
* generated output and consumer tests cover its contract.
*/
const install: InvariantInstaller = () => {}
/**
* Register this package's invariant companion.

View File

@@ -1,31 +1,24 @@
/** Package-owned runtime contracts for @deepseek-ai/dsh-scripts. @module @deepseek-ai/dsh-scripts/invariant */
/**
* Package-owned invariant companion for `@deepseek-ai/dsh-scripts`.
* @module @deepseek-ai/dsh-scripts/invariant
*/
/* jscpd:ignore-start */
import type { Context } from 'cordis'
import { assertInvariant, type InvariantInstaller } from '@deepseek-ai/dsh-invariants'
import type { InvariantInstaller } from '@deepseek-ai/dsh-invariants'
const PACKAGE_NAME = '@deepseek-ai/dsh-scripts'
/** Cordis companion plugin name. */
export const name = 'scripts-invariant'
/** Services required before the companion can register. */
/** Service required before the companion can reserve package ownership. */
export const inject = ['invariants']
/** Assert the launcher's opaque post-separator forwarding boundary. */
const install: InvariantInstaller = async (_ctx, fail) => {
const { splitForwardedArgs } = await import('./forwarding.ts')
const plain = splitForwardedArgs(['dev', 'src/index.ts'])
const separated = splitForwardedArgs(['dev', 'src/index.ts', '--', '--inspect', '9229'])
assertInvariant(fail,
plain.launcher.length === 2
&& plain.forwarded.length === 0
&& separated.launcher.length === 2
&& separated.launcher[1] === 'src/index.ts'
&& separated.forwarded.length === 2
&& separated.forwarded[0] === '--inspect'
&& separated.forwarded[1] === '9229',
'dsh-sdk must split the first delimiter without interpreting forwarded runtime arguments')
}
/**
* No runtime invariant: this SDK build-time package owns no live event stream or mutable data;
* generated output and consumer tests cover its contract.
*/
const install: InvariantInstaller = () => {}
/**
* Register this package's invariant companion.

View File

@@ -1,28 +1,24 @@
/** Package-owned runtime contracts for @deepseek-ai/dsh-telemetry. @module @deepseek-ai/dsh-telemetry/invariant */
/**
* Package-owned invariant companion for `@deepseek-ai/dsh-telemetry`.
* @module @deepseek-ai/dsh-telemetry/invariant
*/
/* jscpd:ignore-start */
import type { Context } from 'cordis'
import { assertInvariant, type InvariantInstaller } from '@deepseek-ai/dsh-invariants'
import type { InvariantInstaller } from '@deepseek-ai/dsh-invariants'
const PACKAGE_NAME = '@deepseek-ai/dsh-telemetry'
/** Cordis companion plugin name. */
export const name = 'telemetry-invariant'
/** Services required before the companion can register. */
/** Service required before the companion can reserve package ownership. */
export const inject = ['invariants']
/** Assert the final telemetry redaction boundary removes secrets without corrupting ordinary package metadata. */
const install: InvariantInstaller = async (_ctx, fail) => {
const [{ telemetryRedactionViolation }, { DEFAULT_REDACTION_PLACEHOLDER, SecretRedactor }] = await Promise.all([
import('./redaction-contract.ts'),
import('./secret-redactor.ts'),
])
const redactor = new SecretRedactor()
const violation = telemetryRedactionViolation(redactor, DEFAULT_REDACTION_PLACEHOLDER, PACKAGE_NAME)
assertInvariant(fail,
violation === undefined,
violation ?? 'telemetry redaction contract failed without a diagnostic')
}
/**
* No runtime invariant: this SDK build-time package owns no live event stream or mutable data;
* generated output and consumer tests cover its contract.
*/
const install: InvariantInstaller = () => {}
/**
* Register this package's invariant companion.

View File

@@ -1,33 +1,24 @@
/**
* Package-owned runtime contract checks for `@deepseek-ai/dsh-session-persistence-jsonl`.
* Package-owned invariant companion for `@deepseek-ai/dsh-session-persistence-jsonl`.
* @module @deepseek-ai/dsh-session-persistence-jsonl/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-session-persistence-jsonl'
/** Cordis companion plugin name. */
export const name = 'session-persistence-jsonl-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: 'SessionPersistenceJsonl',
inject: [
'sessions',
],
effects: [
'ctx.provide("sessionPersistence")',
],
services: [
'sessionPersistence',
],
})
}
/**
* No runtime invariant: persistence correctness requires backend round-trip and crash-tail tests;
* this package exposes no continuously observable in-process relation.
*/
const install: InvariantInstaller = () => {}
/**
* Register this package's invariant companion.
@@ -36,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,33 +1,24 @@
/**
* Package-owned runtime contract checks for `@deepseek-ai/dsh-session-persistence-sqlite`.
* Package-owned invariant companion for `@deepseek-ai/dsh-session-persistence-sqlite`.
* @module @deepseek-ai/dsh-session-persistence-sqlite/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-session-persistence-sqlite'
/** Cordis companion plugin name. */
export const name = 'session-persistence-sqlite-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: 'SessionPersistenceSqlite',
inject: [
'sessions',
],
effects: [
'ctx.provide("sessionPersistence")',
],
services: [
'sessionPersistence',
],
})
}
/**
* No runtime invariant: persistence correctness requires backend round-trip and crash-tail tests;
* this package exposes no continuously observable in-process relation.
*/
const install: InvariantInstaller = () => {}
/**
* Register this package's invariant companion.
@@ -36,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,24 +1,24 @@
/**
* Package-owned runtime contract checks for `@deepseek-ai/dsh-session-persistence`.
* Package-owned invariant companion for `@deepseek-ai/dsh-session-persistence`.
* @module @deepseek-ai/dsh-session-persistence/invariant
*/
/* jscpd:ignore-start */
import type { Context } from 'cordis'
import { observeServiceInvariant, serviceShapeViolation, type InvariantInstaller } from '@deepseek-ai/dsh-invariants'
import type { InvariantInstaller } from '@deepseek-ai/dsh-invariants'
const PACKAGE_NAME = '@deepseek-ai/dsh-session-persistence'
/** Cordis companion plugin name. */
export const name = 'session-persistence-invariant'
/** Services required before the companion can register. */
/** Service required before the companion can reserve package ownership. */
export const inject = ['invariants']
/** Validate every implementation bound to this package's service seam. */
const install: InvariantInstaller = (ctx, fail) => {
observeServiceInvariant(ctx, fail, 'sessionPersistence', value => serviceShapeViolation(value, {
methods: ['locate', 'create', 'append', 'load', 'list'],
}))
}
/**
* No runtime invariant: persistence correctness requires backend round-trip and crash-tail tests;
* this package exposes no continuously observable in-process relation.
*/
const install: InvariantInstaller = () => {}
/**
* Register this package's invariant companion.
@@ -27,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,30 +1,24 @@
/** Package-owned runtime contract checks for `@deepseek-ai/dsh-session-query`. @module @deepseek-ai/dsh-session-query/invariant */
/**
* Package-owned invariant companion for `@deepseek-ai/dsh-session-query`.
* @module @deepseek-ai/dsh-session-query/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-session-query'
/** Cordis companion plugin name. */
export const name = 'session-query-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: 'SessionQueryService',
inject: [
'sessions',
],
effects: [
'ctx.provide("sessionQuery")',
],
services: [
'sessionQuery',
],
})
}
/**
* No runtime invariant: query results are immutable per-call projections whose lineage and event
* relations are validated while they are built; the service retains no observable result state.
*/
const install: InvariantInstaller = () => {}
/**
* Register this package's invariant companion.
@@ -33,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,27 +1,24 @@
/** Package-owned runtime contract checks for `@deepseek-ai/dsh-skill-local`. @module @deepseek-ai/dsh-skill-local/invariant */
/**
* Package-owned invariant companion for `@deepseek-ai/dsh-skill-local`.
* @module @deepseek-ai/dsh-skill-local/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-skill-local'
/** Cordis companion plugin name. */
export const name = 'skill-local-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: 'skill-local',
inject: [
'skills',
],
effects: [
'skills.registerProvider()',
],
})
}
/**
* No runtime invariant: this package exposes no independent event sequence or mutable data relation
* beyond contracts enforced at its owning seam.
*/
const install: InvariantInstaller = () => {}
/**
* Register this package's invariant companion.
@@ -30,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,27 +1,24 @@
/** Package-owned runtime contract checks for `@deepseek-ai/dsh-skill`. @module @deepseek-ai/dsh-skill/invariant */
/**
* Package-owned invariant companion for `@deepseek-ai/dsh-skill`.
* @module @deepseek-ai/dsh-skill/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-skill'
/** Cordis companion plugin name. */
export const name = 'skill-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: 'SkillService',
effects: [
'ctx.provide("skills")',
],
services: [
'skills',
],
})
}
/**
* No runtime invariant: provider/runtime maps and revisioned caches mutate atomically inside the
* registry, which exposes no independent change event or snapshot for cross-checking them.
*/
const install: InvariantInstaller = () => {}
/**
* Register this package's invariant companion.
@@ -30,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,29 +1,24 @@
/** Package-owned runtime contract checks for `@deepseek-ai/dsh-tool-skill`. @module @deepseek-ai/dsh-tool-skill/invariant */
/**
* Package-owned invariant companion for `@deepseek-ai/dsh-tool-skill`.
* @module @deepseek-ai/dsh-tool-skill/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-tool-skill'
/** Cordis companion plugin name. */
export const name = 'tool-skill-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: 'tool-skill',
inject: [
'tools',
'skills',
],
effects: [
'tools.register()',
'ctx.on("agent/session-prefix")',
],
})
}
/**
* No runtime invariant: this model-facing adapter has no independent lifecycle stream; execution
* relations are owned by the capability seam it calls.
*/
const install: InvariantInstaller = () => {}
/**
* Register this package's invariant companion.
@@ -32,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,27 +1,24 @@
/** Package-owned runtime contract checks for `@deepseek-ai/dsh-spill-local`. @module @deepseek-ai/dsh-spill-local/invariant */
/**
* Package-owned invariant companion for `@deepseek-ai/dsh-spill-local`.
* @module @deepseek-ai/dsh-spill-local/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-spill-local'
/** Cordis companion plugin name. */
export const name = 'spill-local-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: 'LocalSpillStore',
effects: [
'ctx.provide("spillStore")',
],
services: [
'spillStore',
],
})
}
/**
* No runtime invariant: this package exposes no independent event sequence or mutable data relation
* beyond contracts enforced at its owning seam.
*/
const install: InvariantInstaller = () => {}
/**
* Register this package's invariant companion.
@@ -30,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,31 +1,24 @@
/** Package-owned runtime contract checks for `@deepseek-ai/dsh-spill-policy`. @module @deepseek-ai/dsh-spill-policy/invariant */
/**
* Package-owned invariant companion for `@deepseek-ai/dsh-spill-policy`.
* @module @deepseek-ai/dsh-spill-policy/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-spill-policy'
/** Cordis companion plugin name. */
export const name = 'spill-policy-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: 'spill-policy',
inject: [
'tools',
],
validate: (fiber, effectLabels) => {
const installed = effectLabels.has('ctx.on("tools/post-execute")')
const enabled = (fiber.config as { maxInlineBytes?: number }).maxInlineBytes !== undefined
return installed === enabled
? undefined
: 'the post-execute spill policy listener must exist exactly when maxInlineBytes is configured'
},
})
}
/**
* No runtime invariant: this package exposes no independent event sequence or mutable data relation
* beyond contracts enforced at its owning seam.
*/
const install: InvariantInstaller = () => {}
/**
* Register this package's invariant companion.
@@ -34,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,21 +1,24 @@
/** Package-owned runtime contract checks for `@deepseek-ai/dsh-spill`. @module @deepseek-ai/dsh-spill/invariant */
/**
* Package-owned invariant companion for `@deepseek-ai/dsh-spill`.
* @module @deepseek-ai/dsh-spill/invariant
*/
/* jscpd:ignore-start */
import type { Context } from 'cordis'
import { observeServiceInvariant, serviceShapeViolation, type InvariantInstaller } from '@deepseek-ai/dsh-invariants'
import type { InvariantInstaller } from '@deepseek-ai/dsh-invariants'
const PACKAGE_NAME = '@deepseek-ai/dsh-spill'
/** Cordis companion plugin name. */
export const name = 'spill-invariant'
/** Services required before the companion can register. */
/** Service required before the companion can reserve package ownership. */
export const inject = ['invariants']
/** Validate every implementation bound to this package's service seam. */
const install: InvariantInstaller = (ctx, fail) => {
observeServiceInvariant(ctx, fail, 'spillStore', value => serviceShapeViolation(value, {
methods: ['saveText'],
}))
}
/**
* No runtime invariant: this package exposes no independent event sequence or mutable data relation
* beyond contracts enforced at its owning seam.
*/
const install: InvariantInstaller = () => {}
/**
* Register this package's invariant companion.
@@ -24,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,27 +1,24 @@
/** Package-owned runtime contract checks for `@deepseek-ai/dsh-subagent-acp`. @module @deepseek-ai/dsh-subagent-acp/invariant */
/**
* Package-owned invariant companion for `@deepseek-ai/dsh-subagent-acp`.
* @module @deepseek-ai/dsh-subagent-acp/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-subagent-acp'
/** Cordis companion plugin name. */
export const name = 'subagent-acp-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: 'subagent-acp',
inject: [
'subagents',
],
effects: [
'subagents.registerProvider()',
],
})
}
/**
* No runtime invariant: this package exposes no independent event sequence or mutable data relation
* beyond contracts enforced at its owning seam.
*/
const install: InvariantInstaller = () => {}
/**
* Register this package's invariant companion.
@@ -30,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,27 +1,24 @@
/** Package-owned runtime contract checks for `@deepseek-ai/dsh-subagent-fork`. @module @deepseek-ai/dsh-subagent-fork/invariant */
/**
* Package-owned invariant companion for `@deepseek-ai/dsh-subagent-fork`.
* @module @deepseek-ai/dsh-subagent-fork/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-subagent-fork'
/** Cordis companion plugin name. */
export const name = 'subagent-fork-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: 'subagent-fork',
inject: [
'subagents',
],
effects: [
'subagents.registerProvider()',
],
})
}
/**
* No runtime invariant: this package exposes no independent event sequence or mutable data relation
* beyond contracts enforced at its owning seam.
*/
const install: InvariantInstaller = () => {}
/**
* Register this package's invariant companion.
@@ -30,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,24 +1,24 @@
/** Package-owned runtime contracts for @deepseek-ai/dsh-subagent-inprocess. @module @deepseek-ai/dsh-subagent-inprocess/invariant */
/**
* Package-owned invariant companion for `@deepseek-ai/dsh-subagent-inprocess`.
* @module @deepseek-ai/dsh-subagent-inprocess/invariant
*/
/* jscpd:ignore-start */
import type { Context } from 'cordis'
import { assertInvariant, type InvariantInstaller } from '@deepseek-ai/dsh-invariants'
import type { InvariantInstaller } from '@deepseek-ai/dsh-invariants'
const PACKAGE_NAME = '@deepseek-ai/dsh-subagent-inprocess'
/** Cordis companion plugin name. */
export const name = 'subagent-inprocess-invariant'
/** Services required before the companion can register. */
/** Service required before the companion can reserve package ownership. */
export const inject = ['invariants']
/** Assert that structured-output guidance names the tool it actually installs. */
const install: InvariantInstaller = async (_ctx, fail) => {
const { STRUCTURED_OUTPUT_INSTRUCTION, STRUCTURED_OUTPUT_TOOL } = await import('./structured-protocol.ts')
assertInvariant(fail, /^[a-z][a-z0-9_]*$/.test(STRUCTURED_OUTPUT_TOOL),
'the structured-output tool must retain a stable lowercase protocol name')
assertInvariant(fail, STRUCTURED_OUTPUT_INSTRUCTION.includes(STRUCTURED_OUTPUT_TOOL),
'the structured-output instruction must name the exact installed tool')
}
/**
* No runtime invariant: this package exposes no independent event sequence or mutable data relation
* beyond contracts enforced at its owning seam.
*/
const install: InvariantInstaller = () => {}
/**
* Register this package's invariant companion.

View File

@@ -1,27 +1,24 @@
/** Package-owned runtime contract checks for `@deepseek-ai/dsh-subagent-spawn`. @module @deepseek-ai/dsh-subagent-spawn/invariant */
/**
* Package-owned invariant companion for `@deepseek-ai/dsh-subagent-spawn`.
* @module @deepseek-ai/dsh-subagent-spawn/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-subagent-spawn'
/** Cordis companion plugin name. */
export const name = 'subagent-spawn-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: 'subagent-spawn',
inject: [
'subagents',
],
effects: [
'subagents.registerProvider()',
],
})
}
/**
* No runtime invariant: this package exposes no independent event sequence or mutable data relation
* beyond contracts enforced at its owning seam.
*/
const install: InvariantInstaller = () => {}
/**
* Register this package's invariant companion.
@@ -30,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,37 +1,24 @@
/** Package-owned runtime contracts for @deepseek-ai/dsh-subagent-subprocess. @module @deepseek-ai/dsh-subagent-subprocess/invariant */
/**
* Package-owned invariant companion for `@deepseek-ai/dsh-subagent-subprocess`.
* @module @deepseek-ai/dsh-subagent-subprocess/invariant
*/
/* jscpd:ignore-start */
import type { Context } from 'cordis'
import { assertInvariant, type InvariantInstaller } from '@deepseek-ai/dsh-invariants'
import type { InvariantInstaller } from '@deepseek-ai/dsh-invariants'
const PACKAGE_NAME = '@deepseek-ai/dsh-subagent-subprocess'
const SENSITIVE_ENV_PATTERN = /KEY|SECRET|TOKEN/i
/** Cordis companion plugin name. */
export const name = 'subagent-subprocess-invariant'
/** Services required before the companion can register. */
/** Service required before the companion can reserve package ownership. */
export const inject = ['invariants']
/** Assert ambient credential scrubbing and explicit credential precedence. */
const install: InvariantInstaller = async (_ctx, fail) => {
const { buildChildEnv } = await import('./index.ts')
const ambientProbe = `DSH_INVARIANT_AMBIENT_TOKEN_${process.pid}`
assertInvariant(fail, SENSITIVE_ENV_PATTERN.test(ambientProbe),
'the invariant ambient probe must remain credential-shaped')
process.env[ambientProbe] = 'must-not-reach-child'
let scrubbed: NodeJS.ProcessEnv
try {
scrubbed = buildChildEnv({})
} finally {
Reflect.deleteProperty(process.env, ambientProbe)
}
assertInvariant(fail, !Object.hasOwn(scrubbed, ambientProbe),
'subprocess environments must omit every credential-shaped ambient variable')
const explicit = buildChildEnv({ DSH_INVARIANT_TOKEN: 'explicit-child-value' })
assertInvariant(fail, explicit.DSH_INVARIANT_TOKEN === 'explicit-child-value',
'explicit child credentials must be applied after ambient scrubbing')
}
/**
* No runtime invariant: this package exposes no independent event sequence or mutable data relation
* beyond contracts enforced at its owning seam.
*/
const install: InvariantInstaller = () => {}
/**
* Register this package's invariant companion.

View File

@@ -1,30 +1,89 @@
/** Package-owned runtime contract checks for `@deepseek-ai/dsh-subagent`. @module @deepseek-ai/dsh-subagent/invariant */
/** Package-owned subagent registry and lifecycle invariants. @module @deepseek-ai/dsh-subagent/invariant */
import type { Context } from 'cordis'
import { observePluginInvariant, type InvariantInstaller } from '@deepseek-ai/dsh-invariants'
import type { InvariantFailure, InvariantInstaller } from '@deepseek-ai/dsh-invariants'
import type { SubagentProvider } from './types.ts'
import type { SubagentRunEndInfo, SubagentRunInfo } from './index.ts'
const PACKAGE_NAME = '@deepseek-ai/dsh-subagent'
/** Cordis companion plugin name. */
export const name = 'subagent-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: 'SubagentService',
effects: [
'ctx.provide("subagents")',
],
services: [
'subagents',
],
})
/** Assert that a terminal lifecycle payload matches its start identity. */
function validateRunEnd(start: SubagentRunInfo, end: SubagentRunEndInfo, fail: InvariantFailure): void {
if (start.provider !== end.provider || start.id !== end.id || start.local !== end.local) {
fail(`subagent/end identity diverges from subagent/start for run ${JSON.stringify(end.runId)}`)
}
}
/** Install provider-registry and start/end pairing checks. */
const install: InvariantInstaller = Object.assign((ctx: Context, fail: InvariantFailure) => {
const providers = new Set(ctx.subagents.list())
const runs = new Map<string, SubagentRunInfo>()
const stagedProviders = new WeakSet<SubagentProvider>()
const stagedRemovals = new Set<string>()
const stagedStarts = new WeakSet<SubagentRunInfo>()
const stagedEnds = new WeakSet<SubagentRunEndInfo>()
ctx.on('internal/dispatch', (_mode, eventName, args) => {
if (eventName === 'subagent/provider-added') {
const provider = args[0] as SubagentProvider
if (provider.name.length === 0) fail('subagent provider names must be non-empty')
if (providers.has(provider.name)) fail(`subagent/provider-added repeated ${JSON.stringify(provider.name)}`)
stagedProviders.add(provider)
return
}
if (eventName === 'subagent/provider-removed') {
const providerName = args[0] as string
if (!providers.has(providerName)) fail(`subagent/provider-removed names unknown provider ${JSON.stringify(providerName)}`)
stagedRemovals.add(providerName)
return
}
if (eventName === 'subagent/start') {
const info = args[0] as SubagentRunInfo
if (!providers.has(info.provider)) fail(`subagent/start names inactive provider ${JSON.stringify(info.provider)}`)
if (String(info.runId).length === 0 || String(info.id).length === 0) {
fail('subagent/start runId and child id must be non-empty')
}
if (runs.has(info.runId)) fail(`subagent/start repeated run id ${JSON.stringify(info.runId)}`)
stagedStarts.add(info)
return
}
if (eventName !== 'subagent/end') return
const info = args[0] as SubagentRunEndInfo
const start = runs.get(info.runId)
if (start === undefined) fail(`subagent/end has no matching subagent/start for run ${JSON.stringify(info.runId)}`)
validateRunEnd(start, info, fail)
stagedEnds.add(info)
}, { global: true })
ctx.on('subagent/provider-added', (provider) => {
/* v8 ignore next -- internal/dispatch stages the same provider object */
if (!stagedProviders.delete(provider)) return
providers.add(provider.name)
}, { global: true })
ctx.on('subagent/provider-removed', (providerName) => {
/* v8 ignore next -- internal/dispatch stages the same provider name */
if (!stagedRemovals.delete(providerName)) return
providers.delete(providerName)
}, { global: true })
ctx.on('subagent/start', (info) => {
/* v8 ignore next -- internal/dispatch stages the same lifecycle object */
if (!stagedStarts.delete(info)) return
runs.set(info.runId, info)
}, { global: true })
ctx.on('subagent/end', (info) => {
/* v8 ignore next -- internal/dispatch stages the same lifecycle object */
if (!stagedEnds.delete(info)) return
runs.delete(info.runId)
}, { global: true })
}, { inject: ['subagents'] })
/**
* Register this package's invariant companion.
* Register the subagent invariant companion.
* @param ctx - Cordis context carrying the invariant service.
* @returns the installed registration's disposer after setup succeeds.
*/

View File

@@ -0,0 +1,82 @@
import { describe, expect, it } from 'vitest'
import { Context } from 'cordis'
import { scopeTarget } from '@deepseek-ai/dsh-scope'
import { SessionId } from '@deepseek-ai/dsh-session'
import SubagentService, { SubagentRunId } from '@deepseek-ai/dsh-subagent'
import type {
SubagentProvider,
SubagentRunEndInfo,
SubagentRunInfo,
} from '@deepseek-ai/dsh-subagent'
import * as SubagentInvariant from '@deepseek-ai/dsh-subagent/invariant'
import InvariantService from '@deepseek-ai/dsh-invariants'
async function setup(): Promise<Context> {
const ctx = new Context()
await ctx.plugin(SubagentService)
await ctx.plugin(InvariantService)
await ctx.plugin(SubagentInvariant)
return ctx
}
const provider = (name: string): SubagentProvider => ({
name,
capabilities: { outputSchema: false, depthLimit: false, toolFilter: false, persona: false },
inheritsParentContext: false,
start: async () => { throw new Error('not used') },
})
const start = (overrides: Partial<SubagentRunInfo> = {}): SubagentRunInfo => ({
runId: SubagentRunId('run-1'),
provider: 'mock',
id: SessionId('child-1'),
local: false,
...overrides,
})
const end = (overrides: Partial<SubagentRunEndInfo> = {}): SubagentRunEndInfo => ({
...start(),
stopReason: 'completed',
...overrides,
})
function emitRun(ctx: Context, name: 'subagent/start', info: SubagentRunInfo): void
function emitRun(ctx: Context, name: 'subagent/end', info: SubagentRunEndInfo): void
function emitRun(ctx: Context, name: 'subagent/start' | 'subagent/end', info: SubagentRunInfo | SubagentRunEndInfo): void {
ctx.emit(scopeTarget(ctx.subagents, {}), name as 'subagent/start', info)
}
describe('subagent invariants', () => {
it('accepts provider and run lifecycle pairs', async () => {
const ctx = await setup()
const mock = provider('mock')
ctx.emit('subagent/provider-added', mock)
emitRun(ctx, 'subagent/start', start())
emitRun(ctx, 'subagent/end', end())
ctx.emit('subagent/provider-removed', 'mock')
ctx.emit('tools/change')
})
it('rejects malformed provider transitions', async () => {
const ctx = await setup()
expect(() => { ctx.emit('subagent/provider-added', provider('')) }).toThrow(/names must be non-empty/)
const mock = provider('mock')
ctx.emit('subagent/provider-added', mock)
expect(() => { ctx.emit('subagent/provider-added', mock) }).toThrow(/repeated "mock"/)
expect(() => { ctx.emit('subagent/provider-removed', 'missing') }).toThrow(/unknown provider/)
})
it('rejects malformed and unpaired run transitions', async () => {
const ctx = await setup()
expect(() => { emitRun(ctx, 'subagent/start', start()) }).toThrow(/inactive provider/)
ctx.emit('subagent/provider-added', provider('mock'))
expect(() => { emitRun(ctx, 'subagent/start', start({ runId: SubagentRunId('') })) })
.toThrow(/runId and child id must be non-empty/)
emitRun(ctx, 'subagent/start', start())
expect(() => { emitRun(ctx, 'subagent/start', start()) }).toThrow(/repeated run id/)
expect(() => { emitRun(ctx, 'subagent/end', end({ runId: SubagentRunId('missing') })) })
.toThrow(/no matching subagent\/start/)
expect(() => { emitRun(ctx, 'subagent/end', end({ id: SessionId('other') })) })
.toThrow(/identity diverges/)
})
})

View File

@@ -1,29 +1,24 @@
/** Package-owned runtime contract checks for `@deepseek-ai/dsh-tool-subagent`. @module @deepseek-ai/dsh-tool-subagent/invariant */
/**
* Package-owned invariant companion for `@deepseek-ai/dsh-tool-subagent`.
* @module @deepseek-ai/dsh-tool-subagent/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-tool-subagent'
/** Cordis companion plugin name. */
export const name = 'tool-subagent-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: 'tool-subagent',
inject: [
'tools',
'subagents',
],
effects: [
'ctx.on("subagent/provider-added")',
'ctx.on("subagent/provider-removed")',
],
})
}
/**
* No runtime invariant: this model-facing adapter has no independent lifecycle stream; execution
* relations are owned by the capability seam it calls.
*/
const install: InvariantInstaller = () => {}
/**
* Register this package's invariant companion.
@@ -32,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,34 +1,24 @@
/** Package-owned runtime contracts for @deepseek-ai/dsh-acp-snapshot. @module @deepseek-ai/dsh-acp-snapshot/invariant */
/**
* Package-owned invariant companion for `@deepseek-ai/dsh-acp-snapshot`.
* @module @deepseek-ai/dsh-acp-snapshot/invariant
*/
/* jscpd:ignore-start */
import type { Context } from 'cordis'
import { assertInvariant, type InvariantInstaller } from '@deepseek-ai/dsh-invariants'
import type { InvariantInstaller } from '@deepseek-ai/dsh-invariants'
const PACKAGE_NAME = '@deepseek-ai/dsh-acp-snapshot'
/** Cordis companion plugin name. */
export const name = 'acp-snapshot-invariant'
/** Services required before the companion can register. */
/** Service required before the companion can reserve package ownership. */
export const inject = ['invariants']
/** Assert stable JSON-RPC correlation and volatile-value tokenization. */
const install: InvariantInstaller = async (_ctx, fail) => {
const { normalizeStdout } = await import('./normalize.ts')
const sessionId = '12345678-1234-1234-1234-123456789abc'
const volatile = { sessionIds: [sessionId], cwd: '/tmp/dsh-acp-invariant' }
const raw = [
JSON.stringify({ jsonrpc: '2.0', id: 'request-7', result: { cwd: volatile.cwd } }),
JSON.stringify({ jsonrpc: '2.0', id: 'request-7', result: { sessionId } }),
].join('\n')
const normalized = normalizeStdout(raw, volatile)
assertInvariant(fail,
normalized.includes('"id":1')
&& normalized.includes('"cwd":"{{cwd}}"')
&& normalized.includes('"sessionId":"{{sessionId}}"'),
'ACP normalization must preserve RPC correlation while tokenizing cwd and session ids')
assertInvariant(fail, normalizeStdout(normalized, volatile) === normalized,
'ACP stdout normalization must be idempotent')
}
/**
* No runtime invariant: this test-support package owns no production event stream or mutable data;
* consuming test suites exercise its behavior.
*/
const install: InvariantInstaller = () => {}
/**
* Register this package's invariant companion.

View File

@@ -1,25 +1,24 @@
/** Package-owned runtime contracts for @deepseek-ai/dsh-agent-loop-testkit. @module @deepseek-ai/dsh-agent-loop-testkit/invariant */
/**
* Package-owned invariant companion for `@deepseek-ai/dsh-agent-loop-testkit`.
* @module @deepseek-ai/dsh-agent-loop-testkit/invariant
*/
/* jscpd:ignore-start */
import type { Context } from 'cordis'
import { assertInvariant, type InvariantInstaller } from '@deepseek-ai/dsh-invariants'
import type { InvariantInstaller } from '@deepseek-ai/dsh-invariants'
const PACKAGE_NAME = '@deepseek-ai/dsh-agent-loop-testkit'
/** Cordis companion plugin name. */
export const name = 'agent-loop-testkit-invariant'
/** Services required before the companion can register. */
/** Service required before the companion can reserve package ownership. */
export const inject = ['invariants']
/** Assert the awaitable helper shape and optional-options call boundary. */
const install: InvariantInstaller = async (_ctx, fail) => {
const { mountAgentLoopTestDependencies } = await import('./index.ts')
assertInvariant(fail,
mountAgentLoopTestDependencies.constructor.name === 'AsyncFunction',
'the prerequisite mount helper must remain awaitable so tests cannot race service activation')
assertInvariant(fail, mountAgentLoopTestDependencies.length === 1,
'the prerequisite mount helper must keep its options argument optional')
}
/**
* No runtime invariant: this test-support package owns no production event stream or mutable data;
* consuming test suites exercise its behavior.
*/
const install: InvariantInstaller = () => {}
/**
* Register this package's invariant companion.

View File

@@ -12,38 +12,37 @@ interface Config {
}
```
Defaults are `enabled: true`, `package_allowlist: []`, and `package_blocklist: []`. A package is selected only when the service is enabled, the empty allowlist or at least one allowlist pattern matches its full npm name, and no blocklist pattern matches. Blocklist matches therefore override allowlist matches.
Defaults are `enabled: true`, `package_allowlist: []`, and `package_blocklist: []`. A package is selected only when the service is enabled, the allowlist is empty or at least one allowlist pattern matches its full npm name, and no blocklist pattern matches. Blocklist matches therefore override allowlist matches.
Each entry is a case-sensitive JavaScript regular-expression source compiled with `new RegExp(pattern)`. Matching is unanchored unless the source supplies `^` and `$`; `/pattern/flags` syntax is not parsed. Blank, whitespace-padded, invalid, or duplicate entries within one list fail service startup. A valid pattern may match no currently loaded package so later loading and HMR remain deterministic.
`ctx.invariants.register(packageName, installer)` reserves one active registration for the full npm package name, including when filters keep its installer inactive, and returns its disposer. An enabled contribution runs in a dedicated child Cordis fiber. The installer can declare its required service surface through `installer.inject` and receives `fail(message)`, which throws an `InvariantError` bound to the registering package. Synchronous or asynchronous installer completion is joined before registration succeeds; failure disposes the child and releases ownership atomically.
The service owns every registration fiber, while the returned disposer also belongs to the companion fiber. Unloading either side removes the listeners and reservation completely. A companion can therefore reload and register the same package name without retaining trace state or duplicate listeners; packages that need an existing baseline rebuild it during installation.
The service owns every registration fiber, while the returned disposer also belongs to the companion fiber. Unloading either side removes listeners, trace state, and the reservation. A companion can therefore reload and register the same package name without retaining its previous state. Session-backed companions rebuild their baseline from durable events; live-only companions observe operations that begin after reload.
`InvariantError` extends `Error`, carries stable `code: 'INVARIANT'`, and exposes the owning `packageName` without adding a product-package dependency to the service.
`InvariantError` extends `Error`, carries stable `code: 'INVARIANT'`, and exposes the owning `packageName` without adding a product dependency to the service.
## Package companions
Every companion installs at least one executable, package-specific contract and reports failure through its bound reporter. There is no generated or ownership-only baseline. `pnpm run verify-package-invariants` rejects generated markers, empty installers, installers that ignore the reporter, duplicate name-based plugin observers, incorrect registration names, and incomplete export, publication, dependency, TypeScript-reference, or bundle wiring.
Publication and registration are exhaustive; runtime assertions are deliberately not synthetic. A companion installs a check only when its package owns an observable event relationship or relevant mutable-data relationship. Confirming a required method, plugin name, injection, effect, or fixed pure-function result is a type, load, or unit-test concern rather than a runtime invariant.
Packages select the narrowest runtime form that protects their public contract:
When no plausible runtime relationship exists, the companion uses an empty installer with a package-specific leading `No runtime invariant:` comment explaining why. This is common for pure utilities, thin implementations whose behavior is already observed through their seam, composition-only packages, binaries, persistence adapters whose contracts require crash/round-trip tests, and test-support packages. The explanation must be revisited when the owner gains mutable state or an event protocol.
| Package shape | Companion check |
The current executable companions protect these relationships:
| Companion | Checks |
|---|---|
| Cordis plugin | `observePluginInvariant` validates the plugin's own declared name, required injections, owned effect group, provided services, and optional package-specific relation for existing, late, and HMR-activated fibers. |
| Cordis service seam | `observeServiceInvariant` plus `serviceShapeViolation` validates current and future structural implementations, including conforming third-party backends and test doubles. |
| Pure library, bin, or support package | `assertInvariant` checks stable protocol algebra, parser mapping, path/timeout/retention rules, normalization, or entrypoint shape during child startup. |
| `dsh-session`, `dsh-agent`, `dsh-scope`, `dsh-agent-loop` | Session enclosure and call/result trace, agent-status transitions, scoped subjects, and model-request reconstruction. |
| `dsh-llm`, `dsh-tools`, `dsh-system-prompt` | Stream grammar, tool-pipeline stages and frozen results, and authoritative prompt-assembly data. |
| `dsh-compact`, `dsh-hook-protocol`, `dsh-bash` | Durable compaction and hook pairing, compaction metadata, and sandbox-mode vocabulary. |
| `dsh-fs`, `dsh-subagent`, `dsh-workflow` | Filesystem event identity, provider/child pairing, and workflow/agent lifecycle identity. |
| `dsh-permission`, `dsh-user-approval` | Active-preset references and approval asked/decided audit pairing. |
| `dsh-tasks`, `dsh-tool-todo` | Task snapshot lifecycle/ownership fields and durable whole-list todo structure. |
| `dsh-time-context` | Durable clock readings agree with their turn, step, elapsed baseline, and event timestamp. |
Four companions additionally install stateful event and request checks:
The root entrypoint of each owner remains independent of diagnostics. Loading the service alone installs no product checks, and loading a companion without the service waits on its declared `invariants` injection.
| Companion | Registration | Checks |
|---|---|---|
| `@deepseek-ai/dsh-session/invariant` | `@deepseek-ai/dsh-session` | sequence, turn/step enclosure, and same-step tool call/result trace |
| `@deepseek-ai/dsh-agent/invariant` | `@deepseek-ai/dsh-agent` | agent-status transitions |
| `@deepseek-ai/dsh-scope/invariant` | `@deepseek-ai/dsh-scope` | scoped-event carrier presence and subject consistency |
| `@deepseek-ai/dsh-agent-loop/invariant` | `@deepseek-ai/dsh-agent-loop` | loop-built model-request reconstruction from the session log |
The root entrypoint of each owner remains independent of diagnostics. Loading the service alone installs no checks; loading a companion without the service remains pending on its declared `invariants` dependency. Name-based plugin observers match only a fiber's own declared runtime name, not anonymous child fibers that inherit a parent display name. They avoid importing the product entrypoint before it is loaded; pure-library checks likewise defer owner imports into the installer child so Vitest mocks and deployment loaders establish their module boundary first.
`pnpm run verify-package-invariants` discovers all workspace packages. It rejects generated markers, unexplained empty installers, non-empty installers that omit or ignore the reporter, incorrect registration names, and incomplete export, publication, dependency, TypeScript-reference, or bundle wiring. This source rule is a minimum ownership check; focused tests prove each executable companion's semantics.
## Composition
@@ -62,11 +61,13 @@ ctx.plugin(InvariantService, {
ctx.plugin(SessionInvariant)
```
The standard agent spine mounts the service and the four stateful companions. Custom compositions explicitly add the companions for the packages whose contracts they want checked and may disable or filter them without changing package entrypoints. Plugin and service helpers multiplex package contracts through indexed lifecycle listeners shared by the Cordis root, while contribution disposal removes only that owner's contract. Vitest gives every ordinary root an explicitly enabled service and mounts the current test package's companion; one exhaustive topology test mounts all companions once, and focused invariant-service tests construct their own topology to exercise filtering and lifecycle behavior.
The standard agent spine mounts the service and its four core stateful companions. Custom compositions explicitly add companions for other loaded packages whose contracts they want checked; filters can disable or select registrations without changing package entrypoints.
Every ordinary Vitest topology mounts an explicitly enabled service and the current test package's companion. Focused suites cover valid and invalid observations for executable companions, while one exhaustive topology mounts all companions to prove registration and disposal wiring.
## Model Experience
None, as the service and companions observe runtime events and requests but never alter prompts, messages, schemas, streams, or tool results.
None. The service and companions observe runtime events, mutable snapshots, and requests but never alter prompts, messages, schemas, streams, or tool results.
#### KV Cache effect
@@ -74,7 +75,6 @@ None; invariant checks do not assemble or send provider requests.
## Known Limitations and Deferred Work
- A name-based plugin observer assumes Cordis plugin names are unique within one root; a package can provide the exact callback when importing it does not preload an unrelated runtime.
- Pure-library contracts are sampled when their companion child activates rather than observed continuously; mutable package behavior belongs on an event, service, or plugin-fiber observer.
- Request reconstruction covers frozen loop-built requests with a live session id; direct one-shot calls remain outside that companion's marker contract.
- Request reconstruction covers frozen loop-built requests with a live session id; direct one-shot LLM calls remain outside that marker contract.
- Live-only lifecycle companions cannot reconstruct operations that began before their own reload. Standard and test compositions mount them before the corresponding operations begin.
- Regular-expression filters are fixed for the service lifetime; changing them requires ordinary Cordis plugin reload.

View File

@@ -6,8 +6,8 @@
* @module @deepseek-ai/dsh-invariants
*/
import { Context, FiberState, Service } from 'cordis'
import type { Fiber, Inject, Plugin } from 'cordis'
import { Context, Service } from 'cordis'
import type { Inject } from 'cordis'
import z from 'schemastery'
import type Schema from 'schemastery'
@@ -41,300 +41,6 @@ export interface InvariantInstaller {
readonly inject?: Inject
}
/** Runtime facts one package expects from its Cordis plugin fiber. */
export interface PluginInvariantContract {
/** Exact plugin value when checking it does not preload an unrelated runtime; otherwise matching uses `name`. */
readonly plugin?: Plugin
/** Exact Cordis display name for the plugin fiber. */
readonly name: string
/** Required service injections that must be present when the fiber activates. */
readonly inject?: readonly string[]
/** Required owned effect labels; an inner array means at least one alternative must exist. */
readonly effects?: readonly (string | readonly string[])[]
/** Services the active fiber must provide. */
readonly services?: readonly string[]
/** Optional package-owned validation after the structural checks pass. */
readonly validate?: (fiber: Fiber, effectLabels: ReadonlySet<string>) => string | undefined
}
/** Collect all live effect labels below a plugin fiber. */
function collectEffectLabels(fiber: Fiber): ReadonlySet<string> {
const labels = new Set<string>()
const visit = (effects: ReturnType<Fiber['getEffects']>): void => {
for (const effect of effects) {
labels.add(effect.label)
visit(effect.children)
}
}
visit(fiber.getEffects())
return labels
}
/** One package check routed by a root-shared plugin lifecycle dispatcher. */
interface PluginObservation {
readonly callback: globalThis.Function | undefined
readonly contract: PluginInvariantContract
readonly fail: InvariantFailure
}
/** Indexed plugin checks and the two lifecycle listeners shared by one root. */
interface PluginObservationHub {
readonly byCallback: Map<globalThis.Function, Set<PluginObservation>>
readonly byName: Map<string, Set<PluginObservation>>
}
const pluginObservationHubs = new WeakMap<Context, PluginObservationHub>()
/** Check one already-matched active plugin fiber. */
function inspectPluginObservation(observation: PluginObservation, fiber: Fiber): void {
if (fiber.state !== FiberState.ACTIVE || fiber.uid === null) return
const { callback, contract, fail } = observation
if (callback !== undefined && fiber.name !== contract.name) {
fail(`active plugin name must be ${JSON.stringify(contract.name)}, got ${JSON.stringify(fiber.name)}`)
}
const injections = new Set(Object.keys(fiber.inject))
for (const service of contract.inject ?? []) {
if (!injections.has(service)) fail(`active plugin must inject ${JSON.stringify(service)}`)
}
const effectLabels = collectEffectLabels(fiber)
for (const requirement of contract.effects ?? []) {
const alternatives = typeof requirement === 'string' ? [requirement] : requirement
if (!alternatives.some(label => effectLabels.has(label))) {
fail(`active plugin must own effect ${alternatives.map(label => JSON.stringify(label)).join(' or ')}`)
}
}
for (const service of contract.services ?? []) {
const provided = Reflect.ownKeys(fiber.ctx.reflect.store).some((key) => {
const implementation = fiber.ctx.reflect.store[key as symbol]
return implementation?.fiber === fiber && implementation.name === service
})
if (!provided) fail(`active plugin must provide service ${JSON.stringify(service)}`)
}
const message = contract.validate?.(fiber, effectLabels)
if (message !== undefined) fail(message)
}
/** Route one lifecycle notification only to checks that can match its runtime. */
function inspectObservedPlugin(hub: PluginObservationHub, fiber: Fiber): void {
const callback = fiber.runtime?.callback
if (callback !== undefined) {
for (const observation of hub.byCallback.get(callback) ?? []) {
inspectPluginObservation(observation, fiber)
}
}
const runtimeName = fiber.runtime?.name
if (runtimeName !== undefined) {
for (const observation of hub.byName.get(runtimeName) ?? []) {
inspectPluginObservation(observation, fiber)
}
}
}
/** Return the root's shared plugin dispatcher, creating its two listeners once. */
function pluginObservationHub(ctx: Context): PluginObservationHub {
const root = ctx.root
const existing = pluginObservationHubs.get(root)
if (existing !== undefined) return existing
const hub: PluginObservationHub = {
byCallback: new Map(),
byName: new Map(),
}
pluginObservationHubs.set(root, hub)
root.on('internal/plugin', (fiber) => { inspectObservedPlugin(hub, fiber) }, { global: true })
root.on('internal/status', (fiber) => { inspectObservedPlugin(hub, fiber) }, { global: true })
return hub
}
/** Add one plugin observation to a typed exact-key index. */
function addIndexedPluginObservation<Key>(
index: Map<Key, Set<PluginObservation>>,
key: Key,
observation: PluginObservation,
): () => void {
const observations = index.get(key) ?? new Set<PluginObservation>()
index.set(key, observations)
observations.add(observation)
return () => {
observations.delete(observation)
if (observations.size === 0) index.delete(key)
}
}
/** Add one observation to its exact callback or runtime-name index. */
function addPluginObservation(hub: PluginObservationHub, observation: PluginObservation): () => void {
if (observation.callback === undefined) {
return addIndexedPluginObservation(hub.byName, observation.contract.name, observation)
}
return addIndexedPluginObservation(hub.byCallback, observation.callback, observation)
}
/**
* Observe one package plugin and fail whenever an active fiber violates its
* declared name, dependency, effect, service, or package-specific contract.
* Existing fibers are checked immediately; later starts and HMR activations
* are checked through two indexed lifecycle listeners shared by the root.
* @param ctx - invariant child context that owns the observers.
* @param fail - reporter bound to the package that owns the plugin.
* @param contract - expected runtime facts for the package plugin.
* @returns nothing after lifecycle observers are installed.
*/
export function observePluginInvariant(
ctx: Context,
fail: InvariantFailure,
contract: PluginInvariantContract,
): void {
const callback = contract.plugin === undefined ? undefined : ctx.registry.resolve(contract.plugin)
if (contract.plugin !== undefined && callback === undefined) {
fail('invariant contract does not identify a Cordis plugin')
}
const observation: PluginObservation = { callback, contract, fail }
if (contract.plugin === undefined) {
for (const runtime of ctx.registry.values()) {
if (runtime.name !== contract.name) continue
for (const fiber of runtime.fibers) inspectPluginObservation(observation, fiber)
}
} else {
for (const fiber of ctx.registry.get(contract.plugin)?.fibers ?? []) {
inspectPluginObservation(observation, fiber)
}
}
const hub = pluginObservationHub(ctx)
ctx.effect(
() => addPluginObservation(hub, observation),
`invariants.observePlugin(${JSON.stringify(contract.name)})`,
)
}
/** One structural check routed by a root-shared service lifecycle dispatcher. */
interface ServiceObservation {
readonly fail: InvariantFailure
readonly validate: (value: unknown) => string | undefined
}
/** Service checks and the single service listener shared by one root. */
interface ServiceObservationHub {
readonly byName: Map<string, Set<ServiceObservation>>
}
const serviceObservationHubs = new WeakMap<Context, ServiceObservationHub>()
/** Check one present service implementation. */
function inspectServiceObservation(observation: ServiceObservation, value: unknown): void {
if (value === undefined) return
const message = observation.validate(value)
if (message !== undefined) observation.fail(message)
}
/** Return the root's shared service dispatcher, creating its listener once. */
function serviceObservationHub(ctx: Context): ServiceObservationHub {
const root = ctx.root
const existing = serviceObservationHubs.get(root)
if (existing !== undefined) return existing
const hub: ServiceObservationHub = { byName: new Map() }
serviceObservationHubs.set(root, hub)
root.on('internal/service', (name, value: unknown) => {
for (const observation of hub.byName.get(name) ?? []) {
inspectServiceObservation(observation, value)
}
}, { global: true })
return hub
}
/** Add one service observation to its exact service-name index. */
function addServiceObservation(
hub: ServiceObservationHub,
serviceName: string,
observation: ServiceObservation,
): () => void {
const observations = hub.byName.get(serviceName) ?? new Set<ServiceObservation>()
hub.byName.set(serviceName, observations)
observations.add(observation)
return () => {
observations.delete(observation)
if (observations.size === 0) hub.byName.delete(serviceName)
}
}
/**
* Validate every current and future implementation bound to one Cordis
* service through the root's indexed shared service listener.
* @param ctx - invariant child context that owns the service observer.
* @param fail - reporter bound to the package that owns the service seam.
* @param serviceName - Cordis service name to observe.
* @param validate - returns the violated contract, or `undefined` for a valid implementation.
* @returns nothing after the current binding is checked and the observer is installed.
*/
export function observeServiceInvariant(
ctx: Context,
fail: InvariantFailure,
serviceName: string,
validate: (value: unknown) => string | undefined,
): void {
const observation: ServiceObservation = { fail, validate }
const current: unknown = ctx.get(serviceName)
inspectServiceObservation(observation, current)
const hub = serviceObservationHub(ctx)
ctx.effect(
() => addServiceObservation(hub, serviceName, observation),
`invariants.observeService(${JSON.stringify(serviceName)})`,
)
}
/** Structural runtime surface required from a Cordis service implementation. */
export interface ServiceShapeInvariant {
/** Members that must be callable. */
readonly methods: readonly string[]
/** Members that must be non-empty strings. */
readonly stringProperties?: readonly string[]
}
/**
* Describe the first missing member in a structural service implementation.
* This deliberately accepts test doubles and third-party implementations that
* satisfy the seam without inheriting the first-party abstract service class.
* @param value - candidate service implementation.
* @param shape - callable and string members owned by the service package.
* @returns the violated shape, or `undefined` when the candidate conforms.
*/
export function serviceShapeViolation(
value: unknown,
shape: ServiceShapeInvariant,
): string | undefined {
if ((typeof value !== 'object' && typeof value !== 'function') || value === null) {
return 'service implementation must be an object'
}
const record = value as Record<string, unknown>
for (const method of shape.methods) {
if (typeof record[method] !== 'function') return `service implementation must expose method ${JSON.stringify(method)}`
}
for (const property of shape.stringProperties ?? []) {
if (typeof record[property] !== 'string' || record[property].length === 0) {
return `service implementation must expose non-empty string ${JSON.stringify(property)}`
}
}
return undefined
}
/**
* Report a failed package-owned synchronous invariant.
* @param fail - reporter bound to the package that owns the assertion.
* @param condition - condition that must hold.
* @param message - violated contract when `condition` is false.
* @returns nothing when the condition holds.
*/
export function assertInvariant(
fail: InvariantFailure,
condition: unknown,
message: string,
): void {
if (!condition) fail(message)
}
/** Internal effect shape used to join child startup before a companion loads. */
interface PendingInvariantRegistration extends PromiseLike<() => void> {
(): void | Promise<void>

View File

@@ -1,28 +1,24 @@
/** Package-owned runtime contract checks for `@deepseek-ai/dsh-invariants`. @module @deepseek-ai/dsh-invariants/invariant */
/**
* Package-owned invariant companion for `@deepseek-ai/dsh-invariants`.
* @module @deepseek-ai/dsh-invariants/invariant
*/
/* jscpd:ignore-start */
import type { Context } from 'cordis'
import InvariantService, { observePluginInvariant, type InvariantInstaller } from './index.ts'
import type { InvariantInstaller } from './index.ts'
const PACKAGE_NAME = '@deepseek-ai/dsh-invariants'
/** Cordis companion plugin name. */
export const name = 'invariants-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, {
plugin: InvariantService,
name: 'InvariantService',
effects: [
'ctx.provide("invariants")',
],
services: [
'invariants',
],
})
}
/**
* No runtime invariant: registration ownership and child lifecycle are the service's mutation
* boundary itself; observing them from the same registry would only duplicate its implementation.
*/
const install: InvariantInstaller = () => {}
/**
* Register this package's invariant companion.
@@ -31,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

@@ -2,19 +2,12 @@ import { describe, expect, it, vi } from 'vitest'
import { Context, Service } from 'cordis'
import InvariantService, {
InvariantError,
assertInvariant,
observePluginInvariant,
observeServiceInvariant,
serviceShapeViolation,
type Config,
type InvariantInstaller,
type PluginInvariantContract,
} from '@deepseek-ai/dsh-invariants'
declare module 'cordis' {
interface Context {
invariantProbe: InvariantProbeService
watchedInvariantProbe: WatchedInvariantProbeService
}
interface Events {
@@ -28,12 +21,6 @@ class InvariantProbeService extends Service {
}
}
class WatchedInvariantProbeService extends Service {
constructor(ctx: Context) {
super(ctx, 'watchedInvariantProbe')
}
}
interface RuntimeRegistration extends PromiseLike<() => void> {
(): void | Promise<void>
}
@@ -299,277 +286,3 @@ describe('InvariantService lifecycle', () => {
expect(() => service.register('@deepseek-ai/dsh-session', () => {})).toThrow(/inactive/i)
})
})
describe('package-owned invariant helpers', () => {
interface InvariantDisposer {
(): void | Promise<void>
}
async function registerInstaller(
ctx: Context,
packageName: string,
installer: InvariantInstaller,
): Promise<InvariantDisposer> {
const registration = runtimeRegistration(ctx.invariants.register(packageName, installer))
const dispose = await Promise.resolve(registration)
return dispose
}
function effectPlugin(options: {
name?: string
inject?: string[]
effect?: string
service?: string
} = {}) {
return {
name: options.name ?? 'effect-probe',
inject: options.inject ?? [],
apply(ctx: Context) {
if (options.service !== undefined) ctx.provide(options.service, {})
if (options.effect !== undefined) {
ctx.effect(() => {
ctx.effect(() => () => {}, `${options.effect}.child`)
return () => {}
}, options.effect)
}
},
}
}
async function expectPluginViolation(
contract: PluginInvariantContract,
plugin: ReturnType<typeof effectPlugin>,
message: RegExp,
): Promise<void> {
const { ctx } = await setup()
await registerInstaller(ctx, `@deepseek-ai/${contract.name}`, (child, fail) => {
observePluginInvariant(child, fail, contract)
})
await expect(Promise.resolve(ctx.plugin(plugin))).rejects.toThrow(message)
}
it('checks existing and later plugin fibers, including nested effects and alternatives', async () => {
const { ctx } = await setup()
await ctx.plugin(InvariantProbeService)
const plugin = effectPlugin({
inject: ['invariantProbe'],
effect: 'probe.effect',
service: 'pluginProbe',
})
await ctx.plugin(plugin)
const validated = vi.fn(() => undefined)
await registerInstaller(ctx, '@deepseek-ai/dsh-existing-probe', (child, fail) => {
observePluginInvariant(child, fail, {
plugin,
name: 'effect-probe',
inject: ['invariantProbe'],
effects: [['missing.effect', 'probe.effect.child']],
services: ['pluginProbe'],
validate: validated,
})
})
expect(validated).toHaveBeenCalledOnce()
const later = effectPlugin({ name: 'later-probe', effect: 'later.effect' })
await registerInstaller(ctx, '@deepseek-ai/dsh-later-probe', (child, fail) => {
observePluginInvariant(child, fail, {
plugin: later,
name: 'later-probe',
effects: ['later.effect'],
})
})
await ctx.plugin(later)
})
it('matches package plugins by Cordis name without importing their callback', async () => {
const { ctx } = await setup()
const plugin = {
name: 'name-only-probe',
apply(pluginCtx: Context) {
pluginCtx.effect(() => () => {}, 'name-only.effect')
pluginCtx.inject([], () => {})
},
}
await registerInstaller(ctx, '@deepseek-ai/dsh-name-only-probe', (child, fail) => {
observePluginInvariant(child, fail, {
name: 'name-only-probe',
effects: ['name-only.effect'],
})
})
await ctx.plugin(plugin)
})
it('multiplexes same-runtime plugin checks through one root listener pair and disposes each owner', async () => {
const { ctx } = await setup()
const firstValidation = vi.fn(() => undefined)
const secondValidation = vi.fn(() => undefined)
const first = await registerInstaller(ctx, '@deepseek-ai/dsh-shared-plugin-first', (child, fail) => {
observePluginInvariant(child, fail, { name: 'shared-plugin-probe', validate: firstValidation })
})
const second = await registerInstaller(ctx, '@deepseek-ai/dsh-shared-plugin-second', (child, fail) => {
observePluginInvariant(child, fail, { name: 'shared-plugin-probe', validate: secondValidation })
})
const rootEffectLabels = ctx.fiber.getEffects().map(effect => effect.label)
expect(rootEffectLabels.filter(label => label === 'ctx.on("internal/plugin")')).toHaveLength(1)
expect(rootEffectLabels.filter(label => label === 'ctx.on("internal/status")')).toHaveLength(1)
const plugin = effectPlugin({ name: 'shared-plugin-probe' })
const firstFiber = await ctx.plugin(plugin)
expect(firstValidation).toHaveBeenCalledOnce()
expect(secondValidation).toHaveBeenCalledOnce()
await first()
await firstFiber.dispose()
const secondFiber = await ctx.plugin(plugin)
expect(firstValidation).toHaveBeenCalledOnce()
expect(secondValidation).toHaveBeenCalledTimes(2)
await second()
await secondFiber.dispose()
await ctx.plugin(plugin)
expect(firstValidation).toHaveBeenCalledOnce()
expect(secondValidation).toHaveBeenCalledTimes(2)
})
it('rejects a contract that does not identify a plugin', async () => {
const { ctx } = await setup()
const registration = runtimeRegistration(ctx.invariants.register('@deepseek-ai/dsh-invalid-plugin', (child, fail) => {
observePluginInvariant(child, fail, {
plugin: {} as never,
name: 'invalid-plugin',
})
}))
await expect(Promise.resolve(registration)).rejects.toThrow(/does not identify a Cordis plugin/)
})
it('rejects wrong plugin names, missing injections, effects, services, and custom checks', async () => {
const wrongName = effectPlugin({ name: 'actual-name', effect: 'probe.effect' })
await expectPluginViolation({
plugin: wrongName,
name: 'expected-name',
}, wrongName, /plugin name must be "expected-name"/)
const missingInjection = effectPlugin({ effect: 'probe.effect' })
await expectPluginViolation({
plugin: missingInjection,
name: 'effect-probe',
inject: ['missingService'],
}, missingInjection, /must inject "missingService"/)
const missingEffect = effectPlugin()
await expectPluginViolation({
plugin: missingEffect,
name: 'effect-probe',
effects: [['first.effect', 'second.effect']],
}, missingEffect, /must own effect "first.effect" or "second.effect"/)
const missingService = effectPlugin({ effect: 'probe.effect' })
await expectPluginViolation({
plugin: missingService,
name: 'effect-probe',
services: ['missingService'],
}, missingService, /must provide service "missingService"/)
const invalidCustom = effectPlugin({ effect: 'probe.effect' })
await expectPluginViolation({
plugin: invalidCustom,
name: 'effect-probe',
validate: () => 'custom plugin contract failed',
}, invalidCustom, /custom plugin contract failed/)
})
it('checks existing and future service implementations while ignoring unrelated changes', async () => {
const existing = await setup()
await existing.ctx.plugin(WatchedInvariantProbeService)
await registerInstaller(existing.ctx, '@deepseek-ai/dsh-existing-service', (child, fail) => {
observeServiceInvariant(child, fail, 'watchedInvariantProbe', value => (
value instanceof WatchedInvariantProbeService ? undefined : 'wrong watched service'
))
})
const future = await setup()
await registerInstaller(future.ctx, '@deepseek-ai/dsh-future-service', (child, fail) => {
observeServiceInvariant(child, fail, 'watchedInvariantProbe', value => (
value instanceof WatchedInvariantProbeService ? undefined : 'wrong watched service'
))
})
await future.ctx.plugin(InvariantProbeService)
await future.ctx.plugin(WatchedInvariantProbeService)
const invalid = await setup()
await registerInstaller(invalid.ctx, '@deepseek-ai/dsh-invalid-service', (child, fail) => {
observeServiceInvariant(child, fail, 'watchedInvariantProbe', () => 'wrong watched service')
})
await expect(Promise.resolve(invalid.ctx.plugin(WatchedInvariantProbeService)))
.rejects.toThrow(/wrong watched service/)
})
it('multiplexes same-name service checks through one root listener and disposes each owner', async () => {
const { ctx } = await setup()
const firstValidation = vi.fn(() => undefined)
const secondValidation = vi.fn(() => undefined)
const first = await registerInstaller(ctx, '@deepseek-ai/dsh-shared-service-first', (child, fail) => {
observeServiceInvariant(child, fail, 'watchedInvariantProbe', firstValidation)
})
const second = await registerInstaller(ctx, '@deepseek-ai/dsh-shared-service-second', (child, fail) => {
observeServiceInvariant(child, fail, 'watchedInvariantProbe', secondValidation)
})
const rootEffectLabels = ctx.fiber.getEffects().map(effect => effect.label)
expect(rootEffectLabels.filter(label => label === 'ctx.on("internal/service")')).toHaveLength(1)
const firstFiber = await ctx.plugin(WatchedInvariantProbeService)
expect(firstValidation).toHaveBeenCalledOnce()
expect(secondValidation).toHaveBeenCalledOnce()
await first()
const firstCallsAfterDisposal = firstValidation.mock.calls.length
const secondCallsBeforeRemount = secondValidation.mock.calls.length
await firstFiber.dispose()
const secondFiber = await ctx.plugin(WatchedInvariantProbeService)
expect(firstValidation).toHaveBeenCalledTimes(firstCallsAfterDisposal)
expect(secondValidation.mock.calls.length).toBeGreaterThan(secondCallsBeforeRemount)
await second()
const firstCallsAfterBothDisposals = firstValidation.mock.calls.length
const secondCallsAfterBothDisposals = secondValidation.mock.calls.length
await secondFiber.dispose()
await ctx.plugin(WatchedInvariantProbeService)
expect(firstValidation).toHaveBeenCalledTimes(firstCallsAfterBothDisposals)
expect(secondValidation).toHaveBeenCalledTimes(secondCallsAfterBothDisposals)
})
it('reports synchronous package assertions through the bound failure reporter', async () => {
const { ctx } = await setup()
const valid = await registerInstaller(ctx, '@deepseek-ai/dsh-valid-assertion', (_child, fail) => {
assertInvariant(fail, true, 'must stay true')
})
await valid()
const invalid = runtimeRegistration(ctx.invariants.register('@deepseek-ai/dsh-invalid-assertion', (_child, fail) => {
assertInvariant(fail, false, 'must stay true')
}))
await expect(Promise.resolve(invalid)).rejects.toThrow(/must stay true/)
})
it('accepts structural service implementations and test doubles', () => {
expect(serviceShapeViolation({ kind: 'probe', run() {} }, {
methods: ['run'],
stringProperties: ['kind'],
})).toBeUndefined()
expect(serviceShapeViolation(Object.assign(() => {}, { run() {} }), {
methods: ['run'],
})).toBeUndefined()
})
it.each([
{ value: null, message: 'service implementation must be an object' },
{ value: 42, message: 'service implementation must be an object' },
{ value: {}, message: 'service implementation must expose method "run"' },
{ value: { run() {}, kind: '' }, message: 'service implementation must expose non-empty string "kind"' },
])('rejects invalid structural service implementations: $message', ({ value, message }) => {
expect(serviceShapeViolation(value, {
methods: ['run'],
stringProperties: ['kind'],
})).toBe(message)
})
})

View File

@@ -1,30 +1,24 @@
/** Package-owned runtime contract checks for `@deepseek-ai/dsh-llm-replay`. @module @deepseek-ai/dsh-llm-replay/invariant */
/**
* Package-owned invariant companion for `@deepseek-ai/dsh-llm-replay`.
* @module @deepseek-ai/dsh-llm-replay/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-llm-replay'
/** Cordis companion plugin name. */
export const name = 'llm-replay-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: 'llm-replay',
inject: [
'llm',
],
effects: [
[
'llm.registerAdapter()',
'ctx.on("llm/stream")',
],
],
})
}
/**
* No runtime invariant: this test-only adapter consumes a fixed replay script; its stream grammar
* is checked by the LLM companion and fixture derivation tests.
*/
const install: InvariantInstaller = () => {}
/**
* Register this package's invariant companion.
@@ -33,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,32 +1,24 @@
/** Package-owned runtime contracts for @deepseek-ai/dsh-loader-smoke. @module @deepseek-ai/dsh-loader-smoke/invariant */
/**
* Package-owned invariant companion for `@deepseek-ai/dsh-loader-smoke`.
* @module @deepseek-ai/dsh-loader-smoke/invariant
*/
/* jscpd:ignore-start */
import type { Context } from 'cordis'
import { assertInvariant, type InvariantInstaller } from '@deepseek-ai/dsh-invariants'
import type { InvariantInstaller } from '@deepseek-ai/dsh-invariants'
const PACKAGE_NAME = '@deepseek-ai/dsh-loader-smoke'
/** Cordis companion plugin name. */
export const name = 'loader-smoke-invariant'
/** Services required before the companion can register. */
/** Service required before the companion can reserve package ownership. */
export const inject = ['invariants']
/** Assert default source mode and plain-Node built-artifact launch resolution. */
const install: InvariantInstaller = async (_ctx, fail) => {
const { resolveExampleLaunch, resolveExampleMode } = await import('./index.ts')
assertInvariant(fail, resolveExampleMode('') === 'src',
'an empty example-mode selection must preserve source-mode development')
const launch = resolveExampleLaunch({
srcBin: '/workspace/probe/src/bin.ts',
mode: 'lib',
})
assertInvariant(fail,
launch.command === process.execPath
&& launch.args.length === 1
&& launch.args[0] === '/workspace/probe/lib/bin.js'
&& launch.env.TSX_TSCONFIG_PATH === undefined,
'built example launches must use plain Node, the derived lib entry, and no tsx paths map')
}
/**
* No runtime invariant: this test-support package owns no production event stream or mutable data;
* consuming test suites exercise its behavior.
*/
const install: InvariantInstaller = () => {}
/**
* Register this package's invariant companion.

View File

@@ -1,31 +1,55 @@
/** Package-owned runtime contract checks for `@deepseek-ai/dsh-tasks`. @module @deepseek-ai/dsh-tasks/invariant */
/** Package-owned background-task snapshot invariants. @module @deepseek-ai/dsh-tasks/invariant */
import type { Context } from 'cordis'
import { observePluginInvariant, type InvariantInstaller } from '@deepseek-ai/dsh-invariants'
import type { Agent } from '@deepseek-ai/dsh-agent'
import type { InvariantFailure, InvariantInstaller } from '@deepseek-ai/dsh-invariants'
import type { TaskSnapshot } from './types.ts'
const PACKAGE_NAME = '@deepseek-ai/dsh-tasks'
const TERMINAL_STATUSES = new Set(['completed', 'killed', 'failed'])
/** Cordis companion plugin name. */
export const name = 'tasks-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: 'TaskService',
effects: [
'ctx.provide("tasks")',
'tasks teardown',
],
services: [
'tasks',
],
})
/** Validate the cross-field relationships in one registry snapshot. */
function validateSnapshot(snapshot: TaskSnapshot, owner: Agent | undefined, fail: InvariantFailure): void {
const id = String(snapshot.id)
const prefix = `${snapshot.kind}-`
const ordinal = Number(id.slice(prefix.length))
if (snapshot.kind.length === 0 || !id.startsWith(prefix)
|| !Number.isSafeInteger(ordinal) || ordinal < 1) {
fail(`task snapshot id ${JSON.stringify(id)} must be ${JSON.stringify(prefix)} followed by a positive ordinal`)
}
if (snapshot.label.length === 0) fail(`task ${JSON.stringify(id)} label must be non-empty`)
if (!Number.isSafeInteger(snapshot.startedAt) || snapshot.startedAt < 0) {
fail(`task ${JSON.stringify(id)} startedAt must be a non-negative epoch integer`)
}
const terminal = TERMINAL_STATUSES.has(snapshot.status)
if (terminal !== (snapshot.finishedAt !== undefined)) {
fail(`task ${JSON.stringify(id)} finishedAt must be present exactly for a terminal status`)
}
if (snapshot.finishedAt !== undefined
&& (!Number.isSafeInteger(snapshot.finishedAt) || snapshot.finishedAt < snapshot.startedAt)) {
fail(`task ${JSON.stringify(id)} finishedAt must be an epoch integer no earlier than startedAt`)
}
const expectedOwner = owner?.id
if (snapshot.ownerSession !== expectedOwner) {
fail(`task ${JSON.stringify(id)} ownerSession does not match its completion owner`)
}
}
/** Install checks over current unowned records and every terminal snapshot. */
const install: InvariantInstaller = Object.assign((ctx: Context, fail: InvariantFailure) => {
for (const snapshot of ctx.tasks.list()) validateSnapshot(snapshot, undefined, fail)
ctx.tasks.onTaskDone((snapshot, owner) => { validateSnapshot(snapshot, owner, fail) })
}, { inject: ['tasks'] })
/**
* Register this package's invariant companion.
* Register the task-registry invariant companion.
* @param ctx - Cordis context carrying the invariant service.
* @returns the installed registration's disposer after setup succeeds.
*/

View File

@@ -0,0 +1,87 @@
import { describe, expect, it } from 'vitest'
import { Context } from 'cordis'
import type { Agent } from '@deepseek-ai/dsh-agent'
import { SessionId } from '@deepseek-ai/dsh-session'
import TaskService, { TaskId } from '@deepseek-ai/dsh-tasks'
import type { TaskDoneListener, TaskSnapshot } from '@deepseek-ai/dsh-tasks'
import * as TasksInvariant from '@deepseek-ai/dsh-tasks/invariant'
import InvariantService from '@deepseek-ai/dsh-invariants'
const BASE: TaskSnapshot = {
id: TaskId('bash-1'),
kind: 'bash',
label: 'compile',
status: 'completed',
startedAt: 10,
finishedAt: 20,
reported: false,
}
const RUNNING: TaskSnapshot = {
id: TaskId('bash-1'),
kind: 'bash',
label: 'compile',
status: 'running',
startedAt: 10,
reported: false,
}
const TERMINAL_WITHOUT_FINISH: TaskSnapshot = {
id: TaskId('bash-1'),
kind: 'bash',
label: 'compile',
status: 'completed',
startedAt: 10,
reported: false,
}
async function setup(seed: TaskSnapshot[] = []): Promise<(snapshot: unknown, owner?: Agent) => void> {
const ctx = new Context()
let listener: TaskDoneListener | undefined
const probe = {
list: () => seed,
onTaskDone(value: TaskDoneListener) {
listener = value
return () => { listener = undefined }
},
} as unknown as TaskService
await ctx.plugin(InvariantService)
await ctx.plugin({
name: 'task-invariant-probe',
apply(child: Context) { child.provide('tasks', probe) },
})
await ctx.plugin(TasksInvariant)
if (listener === undefined) throw new Error('task invariant did not subscribe to terminal snapshots')
return (snapshot, owner) => { listener!(snapshot as TaskSnapshot, owner) }
}
describe('task-registry invariants', () => {
it('accepts coherent current and terminal snapshots', async () => {
const notify = await setup([RUNNING])
expect(() => { notify(BASE) }).not.toThrow()
const owner = { id: SessionId('owner') } as Agent
expect(() => { notify({ ...BASE, id: TaskId('subagent-2'), kind: 'subagent', ownerSession: owner.id }, owner) })
.not.toThrow()
})
it.each([
[{ ...BASE, id: TaskId('-1'), kind: '' }, undefined, /positive ordinal/],
[{ ...BASE, id: TaskId('other-1') }, undefined, /must be "bash-" followed by a positive ordinal/],
[{ ...BASE, id: TaskId('bash-x') }, undefined, /positive ordinal/],
[{ ...BASE, id: TaskId('bash-0') }, undefined, /positive ordinal/],
[{ ...BASE, startedAt: -1 }, undefined, /startedAt must be a non-negative epoch integer/],
[{ ...BASE, startedAt: 0.5 }, undefined, /startedAt must be a non-negative epoch integer/],
[{ ...BASE, status: 'running' }, undefined, /finishedAt must be present exactly for a terminal status/],
[TERMINAL_WITHOUT_FINISH, undefined, /finishedAt must be present exactly for a terminal status/],
[{ ...BASE, finishedAt: 9 }, undefined, /no earlier than startedAt/],
[{ ...BASE, finishedAt: 20.5 }, undefined, /no earlier than startedAt/],
[{ ...BASE, ownerSession: SessionId('recorded') }, { id: SessionId('actual') } as Agent, /does not match its completion owner/],
] as const)('rejects an incoherent registry snapshot', async (snapshot, owner, message) => {
const notify = await setup()
expect(() => { notify(snapshot, owner) }).toThrow(message)
})
it('rejects an incoherent record already present at installation', async () => {
await expect(setup([{ ...BASE, label: '' }])).rejects.toThrow(/label must be non-empty/)
})
})

View File

@@ -1,29 +1,24 @@
/** Package-owned runtime contract checks for `@deepseek-ai/dsh-tool-tasks`. @module @deepseek-ai/dsh-tool-tasks/invariant */
/**
* Package-owned invariant companion for `@deepseek-ai/dsh-tool-tasks`.
* @module @deepseek-ai/dsh-tool-tasks/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-tool-tasks'
/** Cordis companion plugin name. */
export const name = 'tool-tasks-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: 'tool-tasks',
inject: [
'tools',
'tasks',
'systemPrompt',
],
effects: [
'tools.register()',
],
})
}
/**
* No runtime invariant: this model-facing adapter has no independent lifecycle stream; execution
* relations are owned by the capability seam it calls.
*/
const install: InvariantInstaller = () => {}
/**
* Register this package's invariant companion.
@@ -32,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,27 +1,24 @@
/** Package-owned runtime contract checks for `@deepseek-ai/dsh-timeout-policy`. @module @deepseek-ai/dsh-timeout-policy/invariant */
/**
* Package-owned invariant companion for `@deepseek-ai/dsh-timeout-policy`.
* @module @deepseek-ai/dsh-timeout-policy/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-timeout-policy'
/** Cordis companion plugin name. */
export const name = 'timeout-policy-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: 'timeout-policy',
inject: [
'tools',
],
effects: [
'ctx.on("tools/execute")',
],
})
}
/**
* No runtime invariant: this stateless policy plugin owns no package-local event history or mutable
* data relation beyond the seam it intercepts.
*/
const install: InvariantInstaller = () => {}
/**
* Register this package's invariant companion.
@@ -30,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,30 +1,49 @@
/** Package-owned runtime contract checks for `@deepseek-ai/dsh-tool-todo`. @module @deepseek-ai/dsh-tool-todo/invariant */
/** Package-owned durable todo-snapshot invariants. @module @deepseek-ai/dsh-tool-todo/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'
const PACKAGE_NAME = '@deepseek-ai/dsh-tool-todo'
const TODO_STATUSES = new Set(['pending', 'in_progress', 'completed'])
/** Cordis companion plugin name. */
export const name = 'tool-todo-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. */
/** Validate one whole-list todo snapshot before it reaches the durable log. */
function validateTodos(value: unknown, fail: InvariantFailure): void {
if (!Array.isArray(value)) fail('todo/write todos must be an array')
const seen = new Set<string>()
let active = 0
for (const item of value) {
if (typeof item !== 'object' || item === null) fail('todo/write entries must be objects')
const { content, status } = item as Record<string, unknown>
if (typeof content !== 'string' || content.length === 0 || content.trim() !== content) {
fail('todo/write content must be non-empty and already trimmed')
}
if (seen.has(content)) fail(`todo/write repeats content ${JSON.stringify(content)}`)
seen.add(content)
if (typeof status !== 'string' || !TODO_STATUSES.has(status)) {
fail(`todo/write carries unknown status ${JSON.stringify(status)}`)
}
if (status === 'in_progress') active += 1
}
if (active > 1) fail(`todo/write contains ${active} in-progress entries; at most one is allowed`)
}
/** Install validation for durable whole-list todo snapshots. */
const install: InvariantInstaller = (ctx, fail) => {
observePluginInvariant(ctx, fail, {
name: 'tool-todo',
inject: [
'tools',
],
effects: [
'tools.register()',
],
})
ctx.on('internal/dispatch', (_mode, eventName, args) => {
if (eventName !== 'session/event') return
const event = (args as [Session, SessionEvent])[1]
if (event.type === 'todo/write') validateTodos(event.data.todos, fail)
}, { global: true })
}
/**
* Register this package's invariant companion.
* Register the todo invariant companion.
* @param ctx - Cordis context carrying the invariant service.
* @returns the installed registration's disposer after setup succeeds.
*/

View File

@@ -0,0 +1,53 @@
import { describe, expect, it } from 'vitest'
import { Context } from 'cordis'
import type { Session, SessionEvent } from '@deepseek-ai/dsh-session'
import * as TodoInvariant from '@deepseek-ai/dsh-tool-todo/invariant'
import InvariantService from '@deepseek-ai/dsh-invariants'
async function setup(): Promise<Context> {
const ctx = new Context()
await ctx.plugin(InvariantService)
await ctx.plugin(TodoInvariant)
return ctx
}
function event(todos: unknown): SessionEvent {
return { type: 'todo/write', seq: 0, time: 0, data: { todos } } as SessionEvent
}
describe('todo snapshot invariants', () => {
it('accepts a unique whole-list snapshot with one active item', async () => {
const ctx = await setup()
expect(() => { ctx.emit('session/event', {} as Session, event([
{ content: 'Inspect state', status: 'completed' },
{ content: 'Apply fix', status: 'in_progress' },
{ content: 'Run checks', status: 'pending' },
])) }).not.toThrow()
})
it.each([
['not-an-array', /must be an array/],
[[null], /entries must be objects/],
[[42], /entries must be objects/],
[[{ content: 42, status: 'pending' }], /content must be non-empty/],
[[{ content: '', status: 'pending' }], /content must be non-empty/],
[[{ content: ' padded ', status: 'pending' }], /already trimmed/],
[[{ content: 'same', status: 'pending' }, { content: 'same', status: 'completed' }], /repeats content/],
[[{ content: 'task', status: 42 }], /unknown status/],
[[{ content: 'task', status: 'paused' }], /unknown status/],
[[{ content: 'one', status: 'in_progress' }, { content: 'two', status: 'in_progress' }], /at most one/],
])('rejects an incoherent durable todo snapshot', async (todos, message) => {
const ctx = await setup()
expect(() => { ctx.emit('session/event', {} as Session, event(todos)) }).toThrow(message)
})
it('ignores unrelated dispatches and session events', async () => {
const ctx = await setup()
expect(() => {
ctx.emit('tools/change')
ctx.emit('session/event', {} as Session, {
type: 'turn/start', seq: 0, time: 0, data: { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } },
})
}).not.toThrow()
})
})

View File

@@ -1,34 +1,24 @@
/** Package-owned runtime contract checks for `@deepseek-ai/dsh-acp`. @module @deepseek-ai/dsh-acp/invariant */
/**
* Package-owned invariant companion for `@deepseek-ai/dsh-acp`.
* @module @deepseek-ai/dsh-acp/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-acp'
/** Cordis companion plugin name. */
export const name = 'acp-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: 'acp',
inject: [
'agents',
'sessionPersistence',
'tools',
'userInteraction',
'llm',
'systemPrompt',
],
effects: [
'userInteraction.registerProvider()',
'ctx.on("session/event")',
'acp.connection',
],
})
}
/**
* No runtime invariant: this presentation adapter owns no durable package-local event stream;
* boundary and replay tests cover its protocol mapping.
*/
const install: InvariantInstaller = () => {}
/**
* Register this package's invariant companion.
@@ -37,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,28 +1,24 @@
/** Package-owned runtime contracts for @deepseek-ai/dsh-app-boot. @module @deepseek-ai/dsh-app-boot/invariant */
/**
* Package-owned invariant companion for `@deepseek-ai/dsh-app-boot`.
* @module @deepseek-ai/dsh-app-boot/invariant
*/
/* jscpd:ignore-start */
import { resolve } from 'node:path'
import type { Context } from 'cordis'
import { assertInvariant, type InvariantInstaller } from '@deepseek-ai/dsh-invariants'
import type { InvariantInstaller } from '@deepseek-ai/dsh-invariants'
const PACKAGE_NAME = '@deepseek-ai/dsh-app-boot'
/** Cordis companion plugin name. */
export const name = 'app-boot-invariant'
/** Services required before the companion can register. */
/** Service required before the companion can reserve package ownership. */
export const inject = ['invariants']
/** Assert ordinary and replay config-path selection. */
const install: InvariantInstaller = async (_ctx, fail) => {
const { resolveConfigPath } = await import('./config-path.ts')
const cwd = '/tmp/dsh-app-boot-invariant'
const ordinary = resolveConfigPath('cordis.yml', undefined, cwd)
const replay = resolveConfigPath('cordis.yml', 'replay', cwd)
assertInvariant(fail, ordinary === resolve(cwd, 'cordis.yml'),
'ordinary app boot must retain the requested config basename')
assertInvariant(fail, replay === resolve(cwd, 'cordis.snapshot.yml'),
'snapshot replay must select cordis.snapshot.yml in the requested config directory')
}
/**
* No runtime invariant: this presentation adapter owns no durable package-local event stream;
* boundary and replay tests cover its protocol mapping.
*/
const install: InvariantInstaller = () => {}
/**
* Register this package's invariant companion.

View File

@@ -1,27 +1,24 @@
/** Package-owned runtime contract checks for `@deepseek-ai/dsh-jsonrpc`. @module @deepseek-ai/dsh-jsonrpc/invariant */
/**
* Package-owned invariant companion for `@deepseek-ai/dsh-jsonrpc`.
* @module @deepseek-ai/dsh-jsonrpc/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-jsonrpc'
/** Cordis companion plugin name. */
export const name = 'jsonrpc-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: 'jsonrpc',
inject: [
'agents',
],
effects: [
'jsonrpc.serve',
],
})
}
/**
* No runtime invariant: this presentation adapter owns no durable package-local event stream;
* boundary and replay tests cover its protocol mapping.
*/
const install: InvariantInstaller = () => {}
/**
* Register this package's invariant companion.
@@ -30,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,34 +1,29 @@
/** Package-owned runtime contract checks for `@deepseek-ai/dsh-permission`. @module @deepseek-ai/dsh-permission/invariant */
/** Package-owned permission-preset event invariants. @module @deepseek-ai/dsh-permission/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 { InvariantInstaller } from '@deepseek-ai/dsh-invariants'
const PACKAGE_NAME = '@deepseek-ai/dsh-permission'
/** Cordis companion plugin name. */
export const name = 'permission-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: 'PermissionService',
inject: [
'bash',
'approval',
],
effects: [
'ctx.provide("permission")',
],
services: [
'permission',
],
})
}
/** Install validation that durable preset events remain resolvable. */
const install: InvariantInstaller = Object.assign((ctx: Context, fail: (message: string) => never) => {
ctx.on('internal/dispatch', (_mode, eventName, args) => {
if (eventName !== 'session/event') return
const event = (args as [Session, SessionEvent])[1]
if (event.type === 'permission/preset' && !ctx.permission.names.includes(event.data.preset)) {
fail(`permission/preset names unknown preset ${JSON.stringify(event.data.preset)}`)
}
}, { global: true })
}, { inject: ['permission'] })
/**
* Register this package's invariant companion.
* Register the permission invariant companion.
* @param ctx - Cordis context carrying the invariant service.
* @returns the installed registration's disposer after setup succeeds.
*/

View File

@@ -0,0 +1,42 @@
import { describe, expect, it } from 'vitest'
import { Context, Service } from 'cordis'
import type { Session, SessionEvent } from '@deepseek-ai/dsh-session'
import * as PermissionInvariant from '@deepseek-ai/dsh-permission/invariant'
import InvariantService from '@deepseek-ai/dsh-invariants'
class PermissionProbe extends Service {
readonly names = ['safe', 'trusted']
constructor(ctx: Context) {
super(ctx, 'permission')
}
}
async function setup(): Promise<Context> {
const ctx = new Context()
await ctx.plugin(PermissionProbe)
await ctx.plugin(InvariantService)
await ctx.plugin(PermissionInvariant)
return ctx
}
function presetEvent(preset: string): SessionEvent {
return { type: 'permission/preset', seq: 0, time: 0, data: { preset } }
}
describe('permission invariants', () => {
it('accepts configured preset events and ignores other session data', async () => {
const ctx = await setup()
expect(() => { ctx.emit('session/event', {} as Session, presetEvent('safe')) }).not.toThrow()
expect(() => { ctx.emit('session/event', {} as Session, {
type: 'turn/end', seq: 0, time: 0, data: {},
} as SessionEvent) }).not.toThrow()
expect(() => { ctx.emit('tools/change') }).not.toThrow()
})
it('rejects a durable preset that the active table cannot resolve', async () => {
const ctx = await setup()
expect(() => { ctx.emit('session/event', {} as Session, presetEvent('missing')) })
.toThrow(/unknown preset "missing"/)
})
})

View File

@@ -1,29 +1,24 @@
/** Package-owned runtime contract checks for `@deepseek-ai/dsh-stdio`. @module @deepseek-ai/dsh-stdio/invariant */
/**
* Package-owned invariant companion for `@deepseek-ai/dsh-stdio`.
* @module @deepseek-ai/dsh-stdio/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-stdio'
/** Cordis companion plugin name. */
export const name = 'stdio-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: 'ui-stdio',
inject: [
'agents',
'userInteraction',
],
effects: [
'ctx.on("session/event")',
'userInteraction.registerProvider()',
],
})
}
/**
* No runtime invariant: this presentation adapter owns no durable package-local event stream;
* boundary and replay tests cover its protocol mapping.
*/
const install: InvariantInstaller = () => {}
/**
* Register this package's invariant companion.
@@ -32,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,28 +1,24 @@
/** Package-owned runtime contract checks for `@deepseek-ai/dsh-tool-ask-user`. @module @deepseek-ai/dsh-tool-ask-user/invariant */
/**
* Package-owned invariant companion for `@deepseek-ai/dsh-tool-ask-user`.
* @module @deepseek-ai/dsh-tool-ask-user/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-tool-ask-user'
/** Cordis companion plugin name. */
export const name = 'tool-ask-user-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: 'tool-ask-user',
inject: [
'tools',
'userInteraction',
],
effects: [
'tools.register()',
],
})
}
/**
* No runtime invariant: this model-facing adapter has no independent lifecycle stream; execution
* relations are owned by the capability seam it calls.
*/
const install: InvariantInstaller = () => {}
/**
* Register this package's invariant companion.
@@ -31,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,30 +1,24 @@
/** Package-owned runtime contract checks for `@deepseek-ai/dsh-tui`. @module @deepseek-ai/dsh-tui/invariant */
/**
* Package-owned invariant companion for `@deepseek-ai/dsh-tui`.
* @module @deepseek-ai/dsh-tui/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-tui'
/** Cordis companion plugin name. */
export const name = 'tui-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: 'ui-tui',
inject: [
'agents',
'userInteraction',
'tools',
],
effects: [
'ctx.on("session/event")',
'userInteraction.registerProvider()',
],
})
}
/**
* No runtime invariant: this presentation adapter owns no durable package-local event stream;
* boundary and replay tests cover its protocol mapping.
*/
const install: InvariantInstaller = () => {}
/**
* Register this package's invariant companion.
@@ -33,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,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/)
})
})

View File

@@ -1,27 +1,24 @@
/** Package-owned runtime contract checks for `@deepseek-ai/dsh-user-interaction`. @module @deepseek-ai/dsh-user-interaction/invariant */
/**
* Package-owned invariant companion for `@deepseek-ai/dsh-user-interaction`.
* @module @deepseek-ai/dsh-user-interaction/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-user-interaction'
/** Cordis companion plugin name. */
export const name = 'user-interaction-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: 'UserInteractionService',
effects: [
'ctx.provide("userInteraction")',
],
services: [
'userInteraction',
],
})
}
/**
* No runtime invariant: the single provider slot is validated at registration and asks return
* directly to their caller; the seam publishes no independent request/answer audit stream.
*/
const install: InvariantInstaller = () => {}
/**
* Register this package's invariant companion.
@@ -30,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,22 +1,24 @@
/** Package-owned runtime contract for @deepseek-ai/dsh-brand. @module @deepseek-ai/dsh-brand/invariant */
/**
* Package-owned invariant companion for `@deepseek-ai/dsh-brand`.
* @module @deepseek-ai/dsh-brand/invariant
*/
/* jscpd:ignore-start */
import type { Context } from 'cordis'
import { assertInvariant, type InvariantInstaller } from '@deepseek-ai/dsh-invariants'
import type { InvariantInstaller } from '@deepseek-ai/dsh-invariants'
const PACKAGE_NAME = '@deepseek-ai/dsh-brand'
/** Cordis companion plugin name. */
export const name = 'brand-invariant'
/** Services required before the companion can register. */
/** Service required before the companion can reserve package ownership. */
export const inject = ['invariants']
/** Assert that the nominal-type primitive remains erased at runtime. */
const install: InvariantInstaller = async (_ctx, fail) => {
const brandRuntime = await import('./index.ts')
assertInvariant(fail, Object.keys(brandRuntime).length === 0,
'the branded-id primitive must remain type-only with no runtime exports')
}
/**
* No runtime invariant: this pure utility owns no event stream or mutable runtime data; its value
* algebra is enforced by unit tests.
*/
const install: InvariantInstaller = () => {}
/**
* Register this package's invariant companion.

View File

@@ -1,27 +1,24 @@
/** Package-owned runtime contracts for @deepseek-ai/dsh-home. @module @deepseek-ai/dsh-home/invariant */
/**
* Package-owned invariant companion for `@deepseek-ai/dsh-home`.
* @module @deepseek-ai/dsh-home/invariant
*/
/* jscpd:ignore-start */
import { resolve } from 'node:path'
import type { Context } from 'cordis'
import { assertInvariant, type InvariantInstaller } from '@deepseek-ai/dsh-invariants'
import type { InvariantInstaller } from '@deepseek-ai/dsh-invariants'
const PACKAGE_NAME = '@deepseek-ai/dsh-home'
/** Cordis companion plugin name. */
export const name = 'home-invariant'
/** Services required before the companion can register. */
/** Service required before the companion can reserve package ownership. */
export const inject = ['invariants']
/** Assert the canonical environment key and configured-path precedence. */
const install: InvariantInstaller = async (_ctx, fail) => {
const { DSH_HOME_ENV, resolveDshHome } = await import('./index.ts')
const environmentKey: string = DSH_HOME_ENV
assertInvariant(fail, environmentKey === ['DSH', 'HOME'].join('_'),
'the canonical Harness home environment key must remain DSH_HOME')
const configured = 'relative-invariant-home'
assertInvariant(fail, resolveDshHome(configured) === resolve(configured),
'an explicitly configured Harness home must normalize to an absolute path')
}
/**
* No runtime invariant: this pure utility owns no event stream or mutable runtime data; its value
* algebra is enforced by unit tests.
*/
const install: InvariantInstaller = () => {}
/**
* Register this package's invariant companion.

View File

@@ -1,28 +1,24 @@
/** Package-owned runtime contracts for @deepseek-ai/dsh-paths. @module @deepseek-ai/dsh-paths/invariant */
/**
* Package-owned invariant companion for `@deepseek-ai/dsh-paths`.
* @module @deepseek-ai/dsh-paths/invariant
*/
/* jscpd:ignore-start */
import { homedir } from 'node:os'
import { join, resolve } from 'node:path'
import type { Context } from 'cordis'
import { assertInvariant, type InvariantInstaller } from '@deepseek-ai/dsh-invariants'
import type { InvariantInstaller } from '@deepseek-ai/dsh-invariants'
const PACKAGE_NAME = '@deepseek-ai/dsh-paths'
/** Cordis companion plugin name. */
export const name = 'paths-invariant'
/** Services required before the companion can register. */
/** Service required before the companion can reserve package ownership. */
export const inject = ['invariants']
/** Assert tilde expansion and explicit-over-environment home precedence. */
const install: InvariantInstaller = async (_ctx, fail) => {
const { DSH_HOME_ENV, expandHomePath, resolveDshHome } = await import('./index.ts')
assertInvariant(fail, expandHomePath('~/invariant-probe') === join(homedir(), 'invariant-probe'),
'supported tilde prefixes must expand against the operating-system home')
const configured = 'relative-invariant-home'
const resolved = resolveDshHome(configured, { [DSH_HOME_ENV]: '/ignored-environment-home' })
assertInvariant(fail, resolved === resolve(configured),
'an explicit DSH home must override the environment and normalize to an absolute path')
}
/**
* No runtime invariant: this pure utility owns no event stream or mutable runtime data; its value
* algebra is enforced by unit tests.
*/
const install: InvariantInstaller = () => {}
/**
* Register this package's invariant companion.

Some files were not shown because too many files have changed in this diff Show More