DeepSeek Harness treats runtime invariants as a first-class, semi-declarative discipline: every workspace package can register small "contract checks" that run inside the live agent runtime and throw a package-attributed InvariantError the moment a cross-record relationship is violated. This page dissects the registry service (@deepseek-ai/dsh-invariants), how each package's ./invariant companion registers checks, the suite of relationships actually protected, and how unit tests lean on the same philosophy.
The invariant philosophy
The idea (documented in docs/defensive-patterns.md and the dsh-invariants README) is that product packages should fail loud in development when an event-stream or mutable-data contract breaks, instead of silently degrading. Two decisions keep this cheap and non-invasive:
- Registration is exhaustive; assertions are deliberately not synthetic. Every workspace package publishes a
./invariantcompanion that registers its exact npm package name. But a companion installs a real check only when it owns an observable event relationship or relevant mutable data. Confirming a required method, plugin name, injection, or fixed pure-function result is a type/load/unit-test concern, not a runtime invariant. - The service contains no product checks.
@deepseek-ai/dsh-invariantsis a pure registry; loading it alone installs nothing. Product checks live in each owner's companion.
The service
packages/runtime-diagnostics/invariants/src/index.ts exports InvariantRegistry, installed as the Cordis service ctx.invariants. Its config:
export interface Config {
readonly enabled?: boolean
readonly package_allowlist?: string[]
readonly package_blocklist?: string[]
}Defaults are enabled: true, empty allowlist, empty blocklist. Selection is: enabled and (allowlist empty or a pattern matches the full npm name) and (no blocklist pattern matches). Blocklist overrides allowlist. Patterns are unanchored new RegExp(source) unless the caller supplies ^/$.
The two central API points:
class InvariantRegistry extends Service {
register(packageName: string, installer: InvariantInstaller): () => void
}
export type InvariantFailure = (message: string) => neverregister(packageName, installer)reserves the package name (throwingErroron duplicates), then runs the installer in a dedicated child Cordis fiber when the package is selected by filters. It returns a disposer; disposal releases the reservation, removes listeners, and disposes the child — so a companion can reload and re-register the same name without lingering state.- The
installerreceives a childctxand afail(message)reporter that throws anInvariantErrorbound to the registering package.InvariantErrorcarries a stablecode: 'INVARIANT'and thepackageName:
export class InvariantError extends Error {
readonly code = 'INVARIANT' as const
readonly packageName: string
constructor(packageName: string, message: string) {
super(`invariant violated by "${packageName}": ${message}`)
this.name = 'InvariantError'
this.packageName = packageName
}
}Enforcement: throw, not log
Violations surface by throwing. fail(message) is typed to return never, so an invariant breach aborts the offending operation with a package-attributed error rather than being swallowed into logs. That is what makes it a true "assertions in dev" gate — a regression trips InvariantError loudly, and the runtime tests that mount the companions catch it.
Filters with verify-package-invariants
A root hygiene gate, scripts/verify-package-invariants.ts, statically discovers every workspace package and rejects: generated markers, unexplained empty installers, non-empty installers that omit or ignore the reporter, incorrect registration names, and incomplete export/dependency/TypeScript wiring. This is a minimum ownership check; focused .spec.ts suites prove each executable companion's semantics.
What is checked
The README's companion table summarizes the protected relationships (this is exhaustive and read from source):
| Companions | Relationship protected |
|---|---|
dsh-session, dsh-agent, dsh-scope, dsh-agent-loop | Session enclosure and call/result trace, agent-status transitions, inbox FIFO conservation, scoped subjects, model-request reconstruction |
dsh-llm, dsh-llm-retry, dsh-tools, dsh-system-prompt | Stream grammar, durable retry position/bounds, tool-pipeline stages & frozen results, prompt-assembly data |
dsh-compaction, dsh-hook-protocol, dsh-sandbox-policy | Durable compaction & hook pairing, compaction metadata, sandbox-mode vocabulary |
dsh-fs, dsh-subagent, dsh-workflow | Filesystem event identity, provider/child pairing, workflow/agent lifecycle identity |
dsh-goal, dsh-goal-round-driver | Durable goal source/content agreement, revision & lifecycle transitions, timestamps, sequential admitted rounds |
dsh-permission-presets, dsh-user-approval | Active-preset references, approval asked/decided audit pairing |
dsh-jobs, dsh-tool-todo | Task snapshot lifecycle/ownership, durable whole-list todo structure |
dsh-time-context | Durable clock readings agree with open turn / next pre-step position; rendered time parses and does not postdate its event |
A real check: the LLM stream grammar
packages/llm/llm/src/invariant.ts wraps every provider stream to enforce the terminal-finish contract — the same normalized contract documented in docs/defensive-patterns.md ("honour public contracts on BOTH sides"):
// packages/llm/llm/src/invariant.ts (excerpt)
const install: InvariantInstaller = (ctx, fail) => {
ctx.on('llm/stream', (_options, next) => validateStream(next(), fail), { global: true, prepend: true })
ctx.on('llm/adapters-updated', () => {
const llm = ctx.get('llm')
if (llm === undefined) return
for (const provider of llm.listProviders()) {
try {
llm.providerRetryPolicy(provider.id)
} catch {
// Reaching here IS the violation: the notification promised a readable registry.
fail(`llm/adapters-updated fired while provider "${provider.id}" has no readable registration`)
}
}
}, { global: true })
}On a regular untagged stream, the validator ends with:
if (!finished) fail('LLM stream ended without a terminal finish chunk')Empty installers are intentional
Many companions use an empty installer with a No runtime invariant: comment. For example, the test-support package @deepseek-ai/dsh-agent-loop-testkit/invariant.ts:
/** No runtime invariant: this test-support package owns no production event stream or mutable data;
* consuming test suites exercise its behavior. */
const install: InvariantInstaller = () => {}
export const apply = (ctx: Context): Promise<() => void> =>
Promise.resolve(ctx.invariants.register(PACKAGE_NAME, install))How tests rely on invariants
The main Vitest configs (unit, e2e, snapshot) set setupFiles: ['./scripts/test-invariants.ts']; the three web/browser configs omit it. The standard agent composition mounts the service enabled: true plus the four core stateful companions (dsh-session, dsh-agent, dsh-scope, dsh-agent-loop); focused suites prove valid and invalid observations, and one exhaustive topology mounts all companions to prove registration/disposal wiring. Because violations throw, a test can expect(() => …).toThrow(InvariantError) to pin a regression — the invariant is an oracle for cross-record consistency the unit test does not have to re-derive by hand.
A defensive utility: packages/util/timeout
The invariant mindset extends to defensive primitives. @deepseek-ai/dsh-timeout is a zero-dependency timeout/deadline helper — clampTimeout, deadline, timeoutOf, and a TimeoutReason carrying a capability-owned code and elapsed deadline. It only notifies through AbortSignals (each capability owns the mechanism that stops its work), and clampTimeout validates caller hints strictly: non-finite or non-positive values throw, and the effective value is min(requested ?? def, max) capped at MAX_TIMER_DELAY_MS (2_147_483_647). It reuses the same validate-then-fail-fast, classify through a typed code pattern the invariant service embodies.
Further reading
- Testing strategy — how focused suites prove each companion's semantics.
- CI & release — the
verify-package-invariantshygiene gate, plusverify-built-package-invariants. - Official
docs/defensive-patterns.md— the bug-class rules some invariants encode. packages/runtime-diagnostics/invariants/README.md— the exhaustive companion table and config semantics.packages/runtime-diagnostics/invariants/src/index.ts— the registry implementation.packages/llm/llm/src/invariant.ts— a concrete, non-empty invariant companion.