feat(invariants): implement package runtime checks

This commit is contained in:
Tianyi Cui
2026-07-20 00:38:37 +08:00
parent 36e99e737b
commit 941b0411d8
125 changed files with 2317 additions and 1161 deletions

View File

@@ -1,14 +1,8 @@
/**
* Generated invariant ownership companion for `@deepseek-ai/dsh-acp-snapshot`.
* Replace this file with package-owned checks while preserving its registration.
*
* @generated scripts/gen-package-invariants.ts
* @module @deepseek-ai/dsh-acp-snapshot/invariant
*/
/** Package-owned runtime contracts for @deepseek-ai/dsh-acp-snapshot. @module @deepseek-ai/dsh-acp-snapshot/invariant */
/* jscpd:ignore-start */
import type { Context } from 'cordis'
import type { InvariantInstaller } from '@deepseek-ai/dsh-invariants'
import { assertInvariant, type InvariantInstaller } from '@deepseek-ai/dsh-invariants'
const PACKAGE_NAME = '@deepseek-ai/dsh-acp-snapshot'
@@ -17,8 +11,27 @@ export const name = 'acp-snapshot-invariant'
/** Services required before the companion can register. */
export const inject = ['invariants']
/** Reserve this package's invariant ownership until it adds relational checks. */
const install: InvariantInstaller = () => {}
/** Assert stable JSON-RPC correlation and volatile-value tokenization. */
const install: InvariantInstaller = (ctx, fail) => {
ctx.effect(async () => {
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')
return () => {}
}, 'acp-snapshot: validate stable transcript normalization')
}
/**
* Register this package's invariant companion.

View File

@@ -6,12 +6,7 @@
*/
import type { Context } from 'cordis'
import AgentRegistry from '@deepseek-ai/dsh-agent'
import LlmService from '@deepseek-ai/dsh-llm'
import SessionStore from '@deepseek-ai/dsh-session'
import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
import type { Config as SystemPromptConfig } from '@deepseek-ai/dsh-system-prompt'
import ToolRegistry from '@deepseek-ai/dsh-tools'
import type { Config as ToolRegistryConfig } from '@deepseek-ai/dsh-tools'
/** Configuration forwarded to the prerequisite service plugins. */
@@ -38,6 +33,19 @@ export async function mountAgentLoopTestDependencies(
ctx: Context,
options: AgentLoopTestDependenciesOptions = {},
): Promise<void> {
const [
{ default: LlmService },
{ default: SessionStore },
{ default: SystemPrompt },
{ default: ToolRegistry },
{ default: AgentRegistry },
] = await Promise.all([
import('@deepseek-ai/dsh-llm'),
import('@deepseek-ai/dsh-session'),
import('@deepseek-ai/dsh-system-prompt'),
import('@deepseek-ai/dsh-tools'),
import('@deepseek-ai/dsh-agent'),
])
await ctx.plugin(LlmService)
await ctx.plugin(SessionStore)
await ctx.plugin(SystemPrompt, options.systemPrompt ?? {})

View File

@@ -1,14 +1,8 @@
/**
* Generated invariant ownership companion for `@deepseek-ai/dsh-agent-loop-testkit`.
* Replace this file with package-owned checks while preserving its registration.
*
* @generated scripts/gen-package-invariants.ts
* @module @deepseek-ai/dsh-agent-loop-testkit/invariant
*/
/** Package-owned runtime contracts for @deepseek-ai/dsh-agent-loop-testkit. @module @deepseek-ai/dsh-agent-loop-testkit/invariant */
/* jscpd:ignore-start */
import type { Context } from 'cordis'
import type { InvariantInstaller } from '@deepseek-ai/dsh-invariants'
import { assertInvariant, type InvariantInstaller } from '@deepseek-ai/dsh-invariants'
const PACKAGE_NAME = '@deepseek-ai/dsh-agent-loop-testkit'
@@ -17,8 +11,18 @@ export const name = 'agent-loop-testkit-invariant'
/** Services required before the companion can register. */
export const inject = ['invariants']
/** Reserve this package's invariant ownership until it adds relational checks. */
const install: InvariantInstaller = () => {}
/** Assert the awaitable helper shape and optional-options call boundary. */
const install: InvariantInstaller = (ctx, fail) => {
ctx.effect(async () => {
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')
return () => {}
}, 'agent-loop-testkit: validate prerequisite mount boundary')
}
/**
* Register this package's invariant companion.

View File

@@ -24,9 +24,17 @@ The service owns every registration fiber, while the returned disposer also belo
## Package companions
An ownership-only generated baseline installs no listeners but still reserves its package name through the real service boundary. A package replaces that marked file when it gains a relational check, retaining the same registration. `pnpm run verify-package-invariants` checks every package's source registration, export, published files, dependencies, TypeScript reference, and bundle entry.
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.
Four companions currently install stateful checks:
Packages select the narrowest runtime form that protects their public contract:
| Package shape | Companion check |
|---|---|
| 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 in a child effect. |
Four companions additionally install stateful event and request checks:
| Companion | Registration | Checks |
|---|---|---|
@@ -35,7 +43,7 @@ Four companions currently install stateful checks:
| `@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.
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.
## Composition
@@ -54,7 +62,7 @@ ctx.plugin(InvariantService, {
ctx.plugin(SessionInvariant)
```
The standard agent spine mounts the service and the four stateful companions. Custom compositions choose the companions they want and may disable or filter them without changing package entrypoints. Vitest mounts every package companion against an explicitly enabled service for ordinary Cordis roots, so baseline ownership and stateful checks execute across unit, snapshot, and e2e suites; focused invariant-service tests construct their own topology to exercise filtering and lifecycle behavior.
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. Vitest mounts every package companion against an explicitly enabled service for ordinary Cordis roots, so all package checks execute across unit, snapshot, and e2e suites; focused invariant-service tests construct their own topology to exercise filtering and lifecycle behavior.
## Model Experience
@@ -62,6 +70,7 @@ None, as the service and companions observe runtime events and requests but neve
## Known Limitations and Deferred Work
- Stateful checks cover only the four listed package contracts; other companions reserve ownership but add no listeners until their packages gain relational assertions.
- 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.
- Regular-expression filters are fixed for the service lifetime; changing them requires ordinary Cordis plugin reload.

View File

@@ -1,14 +1,13 @@
/**
* Configurable registry for package-owned runtime invariant contributions.
* Every workspace package registers its name from a `./invariant` companion;
* ordinary package entrypoints stay independent of diagnostics, and packages
* without relational checks use an ownership-only installer.
* Every workspace package registers checks from a `./invariant` companion;
* ordinary package entrypoints stay independent of diagnostics.
*
* @module @deepseek-ai/dsh-invariants
*/
import { Context, Service } from 'cordis'
import type { Inject } from 'cordis'
import { Context, FiberState, Service } from 'cordis'
import type { Fiber, Inject, Plugin } from 'cordis'
import z from 'schemastery'
import type Schema from 'schemastery'
@@ -42,6 +41,173 @@ 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
}
/**
* 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 Cordis lifecycle events.
* @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 inspect = (fiber: Fiber): void => {
const matches = callback === undefined
? fiber.runtime?.name === contract.name
: fiber.runtime?.callback === callback
if (!matches || fiber.state !== FiberState.ACTIVE) return
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)
}
if (contract.plugin === undefined) {
for (const runtime of ctx.registry.values()) {
for (const fiber of runtime.fibers) inspect(fiber)
}
} else {
for (const fiber of ctx.registry.get(contract.plugin)?.fibers ?? []) inspect(fiber)
}
ctx.on('internal/plugin', inspect, { global: true })
ctx.on('internal/status', inspect, { global: true })
}
/**
* Validate every current and future implementation bound to one Cordis service.
* @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 inspect = (value: unknown): void => {
if (value === undefined) return
const message = validate(value)
if (message !== undefined) fail(message)
}
const current: unknown = ctx.get(serviceName)
inspect(current)
ctx.on('internal/service', (name, value: unknown) => {
if (name === serviceName) inspect(value)
}, { global: true })
}
/** 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,14 +1,7 @@
/**
* Generated invariant ownership companion for `@deepseek-ai/dsh-invariants`.
* Replace this file with package-owned checks while preserving its registration.
*
* @generated scripts/gen-package-invariants.ts
* @module @deepseek-ai/dsh-invariants/invariant
*/
/** Package-owned runtime contract checks for `@deepseek-ai/dsh-invariants`. @module @deepseek-ai/dsh-invariants/invariant */
/* jscpd:ignore-start */
import type { Context } from 'cordis'
import type { InvariantInstaller } from './index.ts'
import InvariantService, { observePluginInvariant, type InvariantInstaller } from './index.ts'
const PACKAGE_NAME = '@deepseek-ai/dsh-invariants'
@@ -17,8 +10,19 @@ export const name = 'invariants-invariant'
/** Services required before the companion can register. */
export const inject = ['invariants']
/** Reserve this package's invariant ownership until it adds relational checks. */
const install: InvariantInstaller = () => {}
/** 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',
],
})
}
/**
* Register this package's invariant companion.
@@ -27,4 +31,3 @@ const install: InvariantInstaller = () => {}
*/
export const apply = (ctx: Context): Promise<() => void> =>
Promise.resolve(ctx.invariants.register(PACKAGE_NAME, install))
/* jscpd:ignore-end */

View File

@@ -1,10 +1,20 @@
import { describe, expect, it, vi } from 'vitest'
import { Context, Service } from 'cordis'
import InvariantService, { InvariantError, type Config } from '@deepseek-ai/dsh-invariants'
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 {
@@ -18,6 +28,12 @@ class InvariantProbeService extends Service {
}
}
class WatchedInvariantProbeService extends Service {
constructor(ctx: Context) {
super(ctx, 'watchedInvariantProbe')
}
}
interface RuntimeRegistration extends PromiseLike<() => void> {
(): void | Promise<void>
}
@@ -264,3 +280,207 @@ describe('InvariantService lifecycle', () => {
expect(() => service.register('@deepseek-ai/dsh-session', () => {})).toThrow(/inactive/i)
})
})
describe('package-owned invariant helpers', () => {
async function registerInstaller(
ctx: Context,
packageName: string,
installer: InvariantInstaller,
): Promise<() => void> {
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('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('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')
})
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,14 +1,7 @@
/**
* Generated invariant ownership companion for `@deepseek-ai/dsh-llm-replay`.
* Replace this file with package-owned checks while preserving its registration.
*
* @generated scripts/gen-package-invariants.ts
* @module @deepseek-ai/dsh-llm-replay/invariant
*/
/** Package-owned runtime contract checks for `@deepseek-ai/dsh-llm-replay`. @module @deepseek-ai/dsh-llm-replay/invariant */
/* jscpd:ignore-start */
import type { Context } from 'cordis'
import type { InvariantInstaller } from '@deepseek-ai/dsh-invariants'
import { observePluginInvariant, type InvariantInstaller } from '@deepseek-ai/dsh-invariants'
const PACKAGE_NAME = '@deepseek-ai/dsh-llm-replay'
@@ -17,8 +10,21 @@ export const name = 'llm-replay-invariant'
/** Services required before the companion can register. */
export const inject = ['invariants']
/** Reserve this package's invariant ownership until it adds relational checks. */
const install: InvariantInstaller = () => {}
/** 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")',
],
],
})
}
/**
* Register this package's invariant companion.
@@ -27,4 +33,3 @@ const install: InvariantInstaller = () => {}
*/
export const apply = (ctx: Context): Promise<() => void> =>
Promise.resolve(ctx.invariants.register(PACKAGE_NAME, install))
/* jscpd:ignore-end */

View File

@@ -1,14 +1,8 @@
/**
* Generated invariant ownership companion for `@deepseek-ai/dsh-loader-smoke`.
* Replace this file with package-owned checks while preserving its registration.
*
* @generated scripts/gen-package-invariants.ts
* @module @deepseek-ai/dsh-loader-smoke/invariant
*/
/** Package-owned runtime contracts for @deepseek-ai/dsh-loader-smoke. @module @deepseek-ai/dsh-loader-smoke/invariant */
/* jscpd:ignore-start */
import type { Context } from 'cordis'
import type { InvariantInstaller } from '@deepseek-ai/dsh-invariants'
import { assertInvariant, type InvariantInstaller } from '@deepseek-ai/dsh-invariants'
const PACKAGE_NAME = '@deepseek-ai/dsh-loader-smoke'
@@ -17,8 +11,25 @@ export const name = 'loader-smoke-invariant'
/** Services required before the companion can register. */
export const inject = ['invariants']
/** Reserve this package's invariant ownership until it adds relational checks. */
const install: InvariantInstaller = () => {}
/** Assert default source mode and plain-Node built-artifact launch resolution. */
const install: InvariantInstaller = (ctx, fail) => {
ctx.effect(async () => {
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')
return () => {}
}, 'loader-smoke: validate source and built launch resolution')
}
/**
* Register this package's invariant companion.