Skip to content

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 ./invariant companion 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-invariants is 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:

ts
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:

ts
class InvariantRegistry extends Service {
  register(packageName: string, installer: InvariantInstaller): () => void
}

export type InvariantFailure = (message: string) => never
  • register(packageName, installer) reserves the package name (throwing Error on 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 installer receives a child ctx and a fail(message) reporter that throws an InvariantError bound to the registering package. InvariantError carries a stable code: 'INVARIANT' and the packageName:
ts
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):

CompanionsRelationship protected
dsh-session, dsh-agent, dsh-scope, dsh-agent-loopSession 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-promptStream grammar, durable retry position/bounds, tool-pipeline stages & frozen results, prompt-assembly data
dsh-compaction, dsh-hook-protocol, dsh-sandbox-policyDurable compaction & hook pairing, compaction metadata, sandbox-mode vocabulary
dsh-fs, dsh-subagent, dsh-workflowFilesystem event identity, provider/child pairing, workflow/agent lifecycle identity
dsh-goal, dsh-goal-round-driverDurable goal source/content agreement, revision & lifecycle transitions, timestamps, sequential admitted rounds
dsh-permission-presets, dsh-user-approvalActive-preset references, approval asked/decided audit pairing
dsh-jobs, dsh-tool-todoTask snapshot lifecycle/ownership, durable whole-list todo structure
dsh-time-contextDurable 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"):

ts
// 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:

ts
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:

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-invariants hygiene gate, plus verify-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.